2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2002
6 Copyright (C) Simo Sorce 2001
7 Copyright (C) Anthony Liguori 2003
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
27 #ifdef WITH_NISPLUS_HOME
28 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
30 * The following lines are needed due to buggy include files
31 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
32 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
33 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
34 * an enum in /usr/include/rpcsvc/nis.h.
41 #if defined(GROUP_OBJ)
45 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
47 #include <rpcsvc/nis.h>
49 #else /* !WITH_NISPLUS_HOME */
51 #include "rpcsvc/ypclnt.h"
53 #endif /* WITH_NISPLUS_HOME */
54 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
56 int Protocol
= PROTOCOL_COREPLUS
;
58 /* a default finfo structure to ensure all fields are sensible */
59 file_info def_finfo
= {-1,0,0,0,0,0,0,"",""};
61 /* this is used by the chaining code */
67 case handling on filenames
69 int case_default
= CASE_LOWER
;
71 /* the following control case operations - they are put here so the
72 client can link easily */
75 BOOL use_mangled_map
= False
;
76 BOOL short_case_preserve
;
79 static enum remote_arch_types ra_type
= RA_UNKNOWN
;
80 pstring user_socket_options
=DEFAULT_SOCKET_OPTIONS
;
82 /***********************************************************************
83 Definitions for all names.
84 ***********************************************************************/
86 static char *smb_myname
;
87 static char *smb_myworkgroup
;
88 static char *smb_scope
;
89 static int smb_num_netbios_names
;
90 static char **smb_my_netbios_names
;
92 /***********************************************************************
93 Allocate and set myname. Ensure upper case.
94 ***********************************************************************/
96 BOOL
set_global_myname(const char *myname
)
98 SAFE_FREE(smb_myname
);
99 smb_myname
= strdup(myname
);
102 strupper(smb_myname
);
106 const char *global_myname(void)
111 /***********************************************************************
112 Allocate and set myworkgroup. Ensure upper case.
113 ***********************************************************************/
115 BOOL
set_global_myworkgroup(const char *myworkgroup
)
117 SAFE_FREE(smb_myworkgroup
);
118 smb_myworkgroup
= strdup(myworkgroup
);
119 if (!smb_myworkgroup
)
121 strupper(smb_myworkgroup
);
125 const char *lp_workgroup(void)
127 return smb_myworkgroup
;
130 /***********************************************************************
131 Allocate and set scope. Ensure upper case.
132 ***********************************************************************/
134 BOOL
set_global_scope(const char *scope
)
136 SAFE_FREE(smb_scope
);
137 smb_scope
= strdup(scope
);
144 /*********************************************************************
145 Ensure scope is never null string.
146 *********************************************************************/
148 const char *global_scope(void)
151 set_global_scope("");
155 static void free_netbios_names_array(void)
159 for (i
= 0; i
< smb_num_netbios_names
; i
++)
160 SAFE_FREE(smb_my_netbios_names
[i
]);
162 SAFE_FREE(smb_my_netbios_names
);
163 smb_num_netbios_names
= 0;
166 static BOOL
allocate_my_netbios_names_array(size_t number
)
168 free_netbios_names_array();
170 smb_num_netbios_names
= number
+ 1;
171 smb_my_netbios_names
= (char **)malloc( sizeof(char *) * smb_num_netbios_names
);
173 if (!smb_my_netbios_names
)
176 memset(smb_my_netbios_names
, '\0', sizeof(char *) * smb_num_netbios_names
);
180 static BOOL
set_my_netbios_names(const char *name
, int i
)
182 SAFE_FREE(smb_my_netbios_names
[i
]);
184 smb_my_netbios_names
[i
] = strdup(name
);
185 if (!smb_my_netbios_names
[i
])
187 strupper(smb_my_netbios_names
[i
]);
191 const char *my_netbios_names(int i
)
193 return smb_my_netbios_names
[i
];
196 BOOL
set_netbios_aliases(const char **str_array
)
200 /* Work out the max number of netbios aliases that we have */
201 for( namecount
=0; str_array
&& (str_array
[namecount
] != NULL
); namecount
++ )
204 if ( global_myname() && *global_myname())
207 /* Allocate space for the netbios aliases */
208 if (!allocate_my_netbios_names_array(namecount
))
211 /* Use the global_myname string first */
213 if ( global_myname() && *global_myname()) {
214 set_my_netbios_names( global_myname(), namecount
);
220 for ( i
= 0; str_array
[i
] != NULL
; i
++) {
222 BOOL duplicate
= False
;
224 /* Look for duplicates */
225 for( n
=0; n
<namecount
; n
++ ) {
226 if( strequal( str_array
[i
], my_netbios_names(n
) ) ) {
232 if (!set_my_netbios_names(str_array
[i
], namecount
))
241 /****************************************************************************
242 Common name initialization code.
243 ****************************************************************************/
245 BOOL
init_names(void)
247 extern fstring local_machine
;
251 if (global_myname() == NULL
|| *global_myname() == '\0') {
252 if (!set_global_myname(myhostname())) {
253 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
258 if (!set_netbios_aliases(lp_netbios_aliases())) {
259 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
263 fstrcpy( local_machine
, global_myname() );
264 trim_string( local_machine
, " ", " " );
265 p
= strchr( local_machine
, ' ' );
268 strlower( local_machine
);
270 DEBUG( 5, ("Netbios name list:-\n") );
271 for( n
=0; my_netbios_names(n
); n
++ )
272 DEBUGADD( 5, ( "my_netbios_names[%d]=\"%s\"\n", n
, my_netbios_names(n
) ) );
277 /**************************************************************************n
278 Find a suitable temporary directory. The result should be copied immediately
279 as it may be overwritten by a subsequent call.
280 ****************************************************************************/
282 const char *tmpdir(void)
285 if ((p
= getenv("TMPDIR")))
290 /****************************************************************************
291 Determine whether we are in the specified group.
292 ****************************************************************************/
294 BOOL
in_group(gid_t group
, gid_t current_gid
, int ngroups
, const gid_t
*groups
)
298 if (group
== current_gid
)
301 for (i
=0;i
<ngroups
;i
++)
302 if (group
== groups
[i
])
308 /****************************************************************************
309 Like atoi but gets the value up to the separator character.
310 ****************************************************************************/
312 static const char *Atoic(const char *p
, int *n
, const char *c
)
314 if (!isdigit((const int)*p
)) {
315 DEBUG(5, ("Atoic: malformed number\n"));
321 while ((*p
) && isdigit((int)*p
))
324 if (strchr_m(c
, *p
) == NULL
) {
325 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c
));
332 /*************************************************************************
333 Reads a list of numbers.
334 *************************************************************************/
336 const char *get_numlist(const char *p
, uint32
**num
, int *count
)
340 if (num
== NULL
|| count
== NULL
)
346 while ((p
= Atoic(p
, &val
, ":,")) != NULL
&& (*p
) != ':') {
349 tn
= Realloc((*num
), ((*count
)+1) * sizeof(uint32
));
355 (*num
)[(*count
)] = val
;
363 /*******************************************************************
364 Check if a file exists - call vfs_file_exist for samba files.
365 ********************************************************************/
367 BOOL
file_exist(const char *fname
,SMB_STRUCT_STAT
*sbuf
)
373 if (sys_stat(fname
,sbuf
) != 0)
376 return((S_ISREG(sbuf
->st_mode
)) || (S_ISFIFO(sbuf
->st_mode
)));
379 /*******************************************************************
380 Check a files mod time.
381 ********************************************************************/
383 time_t file_modtime(const char *fname
)
387 if (sys_stat(fname
,&st
) != 0)
393 /*******************************************************************
394 Check if a directory exists.
395 ********************************************************************/
397 BOOL
directory_exist(char *dname
,SMB_STRUCT_STAT
*st
)
405 if (sys_stat(dname
,st
) != 0)
408 ret
= S_ISDIR(st
->st_mode
);
414 /*******************************************************************
415 Returns the size in bytes of the named file.
416 ********************************************************************/
418 SMB_OFF_T
get_file_size(char *file_name
)
422 if(sys_stat(file_name
,&buf
) != 0)
423 return (SMB_OFF_T
)-1;
427 /*******************************************************************
428 Return a string representing an attribute for a file.
429 ********************************************************************/
431 char *attrib_string(uint16 mode
)
433 static fstring attrstr
;
437 if (mode
& aVOLID
) fstrcat(attrstr
,"V");
438 if (mode
& aDIR
) fstrcat(attrstr
,"D");
439 if (mode
& aARCH
) fstrcat(attrstr
,"A");
440 if (mode
& aHIDDEN
) fstrcat(attrstr
,"H");
441 if (mode
& aSYSTEM
) fstrcat(attrstr
,"S");
442 if (mode
& aRONLY
) fstrcat(attrstr
,"R");
447 /*******************************************************************
448 Show a smb message structure.
449 ********************************************************************/
451 void show_msg(char *buf
)
459 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
461 (int)CVAL(buf
,smb_com
),
462 (int)CVAL(buf
,smb_rcls
),
463 (int)CVAL(buf
,smb_reh
),
464 (int)SVAL(buf
,smb_err
),
465 (int)CVAL(buf
,smb_flg
),
466 (int)SVAL(buf
,smb_flg2
)));
467 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
468 (int)SVAL(buf
,smb_tid
),
469 (int)SVAL(buf
,smb_pid
),
470 (int)SVAL(buf
,smb_uid
),
471 (int)SVAL(buf
,smb_mid
)));
472 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf
,smb_wct
)));
474 for (i
=0;i
<(int)CVAL(buf
,smb_wct
);i
++)
475 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i
,
476 SVAL(buf
,smb_vwv
+2*i
),SVAL(buf
,smb_vwv
+2*i
)));
478 bcc
= (int)SVAL(buf
,smb_vwv
+2*(CVAL(buf
,smb_wct
)));
480 DEBUGADD(5,("smb_bcc=%d\n",bcc
));
488 dump_data(10, smb_buf(buf
), bcc
);
491 /*******************************************************************
492 Set the length and marker of an smb packet.
493 ********************************************************************/
495 void smb_setlen(char *buf
,int len
)
497 _smb_setlen(buf
,len
);
505 /*******************************************************************
506 Setup the word count and byte count for a smb message.
507 ********************************************************************/
509 int set_message(char *buf
,int num_words
,int num_bytes
,BOOL zero
)
512 memset(buf
+ smb_size
,'\0',num_words
*2 + num_bytes
);
513 SCVAL(buf
,smb_wct
,num_words
);
514 SSVAL(buf
,smb_vwv
+ num_words
*SIZEOFWORD
,num_bytes
);
515 smb_setlen(buf
,smb_size
+ num_words
*2 + num_bytes
- 4);
516 return (smb_size
+ num_words
*2 + num_bytes
);
519 /*******************************************************************
520 Setup only the byte count for a smb message.
521 ********************************************************************/
523 int set_message_bcc(char *buf
,int num_bytes
)
525 int num_words
= CVAL(buf
,smb_wct
);
526 SSVAL(buf
,smb_vwv
+ num_words
*SIZEOFWORD
,num_bytes
);
527 smb_setlen(buf
,smb_size
+ num_words
*2 + num_bytes
- 4);
528 return (smb_size
+ num_words
*2 + num_bytes
);
531 /*******************************************************************
532 Setup only the byte count for a smb message, using the end of the
534 ********************************************************************/
536 int set_message_end(void *outbuf
,void *end_ptr
)
538 return set_message_bcc((char *)outbuf
,PTR_DIFF(end_ptr
,smb_buf((char *)outbuf
)));
541 /*******************************************************************
542 Reduce a file name, removing .. elements.
543 ********************************************************************/
545 void dos_clean_name(char *s
)
549 DEBUG(3,("dos_clean_name [%s]\n",s
));
551 /* remove any double slashes */
552 all_string_sub(s
, "\\\\", "\\", 0);
554 while ((p
= strstr(s
,"\\..\\")) != NULL
) {
560 if ((p
=strrchr_m(s
,'\\')) != NULL
)
567 trim_string(s
,NULL
,"\\..");
569 all_string_sub(s
, "\\.\\", "\\", 0);
572 /*******************************************************************
573 Reduce a file name, removing .. elements.
574 ********************************************************************/
576 void unix_clean_name(char *s
)
580 DEBUG(3,("unix_clean_name [%s]\n",s
));
582 /* remove any double slashes */
583 all_string_sub(s
, "//","/", 0);
585 /* Remove leading ./ characters */
586 if(strncmp(s
, "./", 2) == 0) {
587 trim_string(s
, "./", NULL
);
592 while ((p
= strstr(s
,"/../")) != NULL
) {
598 if ((p
=strrchr_m(s
,'/')) != NULL
)
605 trim_string(s
,NULL
,"/..");
608 /*******************************************************************
610 Reduce a file name, removing or reducing /../ , /./ , // elements.
611 Remove also any trailing . and /
612 Return a new allocated string.
613 ********************************************************************/
615 smb_ucs2_t
*unix_clean_path(const smb_ucs2_t
*s
)
618 smb_ucs2_t
*p
, *r
, *t
;
620 DEBUG(3, ("unix_clean_path\n")); /* [%unicode]\n")); */
624 /* convert '\' to '/' */
630 /* remove all double slashes */
632 ns
= all_string_sub_wa(p
, "//", "/");
639 ns
= all_string_sub_wa(p
, "/./", "/");
644 /* reduce any /../ */
646 while (*t
&& (r
= strstr_wa(t
, "/.."))) {
648 if (*t
== UCS2_CHAR('/') || *t
== 0) {
650 p
= strrchr_w(ns
, UCS2_CHAR('/'));
656 memmove(p
, t
, (strlen_w(t
) + 1) * sizeof(smb_ucs2_t
));
661 /* remove any leading ./ trailing /. */
662 trim_string_wa(ns
, "./", "/.");
664 /* remove any leading and trailing / */
665 trim_string_wa(ns
, "/", "/");
670 /****************************************************************************
672 ****************************************************************************/
674 void make_dir_struct(char *buf
, const char *mask
, const char *fname
,SMB_OFF_T size
,int mode
,time_t date
)
681 if ((mode
& aDIR
) != 0)
684 memset(buf
+1,' ',11);
685 if ((p
= strchr_m(mask2
,'.')) != NULL
) {
687 push_ascii(buf
+1,mask2
,8, 0);
688 push_ascii(buf
+9,p
+1,3, 0);
691 push_ascii(buf
+1,mask2
,11, 0);
693 memset(buf
+21,'\0',DIR_STRUCT_SIZE
-21);
695 put_dos_date(buf
,22,date
);
696 SSVAL(buf
,26,size
& 0xFFFF);
697 SSVAL(buf
,28,(size
>> 16)&0xFFFF);
698 push_ascii(buf
+30,fname
,12, case_sensitive
? 0 : STR_UPPER
);
699 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf
+30, fname
));
702 /*******************************************************************
703 Close the low 3 fd's and open dev/null in their place.
704 ********************************************************************/
706 void close_low_fds(BOOL stderr_too
)
718 /* try and use up these file descriptors, so silly
719 library routines writing to stdout etc won't cause havoc */
721 if (i
== 2 && !stderr_too
)
724 fd
= sys_open("/dev/null",O_RDWR
,0);
726 fd
= sys_open("/dev/null",O_WRONLY
,0);
728 DEBUG(0,("Can't open /dev/null\n"));
732 DEBUG(0,("Didn't get file descriptor %d\n",i
));
739 /****************************************************************************
740 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
744 ****************************************************************************/
746 int set_blocking(int fd
, BOOL set
)
750 #define FLAG_TO_SET O_NONBLOCK
753 #define FLAG_TO_SET O_NDELAY
755 #define FLAG_TO_SET FNDELAY
759 if((val
= sys_fcntl_long(fd
, F_GETFL
, 0)) == -1)
761 if(set
) /* Turn blocking on - ie. clear nonblock flag */
765 return sys_fcntl_long( fd
, F_SETFL
, val
);
769 /****************************************************************************
770 Transfer some data between two fd's.
771 ****************************************************************************/
773 #ifndef TRANSFER_BUF_SIZE
774 #define TRANSFER_BUF_SIZE 65536
777 ssize_t
transfer_file_internal(int infd
, int outfd
, size_t n
, ssize_t (*read_fn
)(int, void *, size_t),
778 ssize_t (*write_fn
)(int, const void *, size_t))
784 size_t num_to_read_thistime
;
785 size_t num_written
= 0;
787 if ((buf
= malloc(TRANSFER_BUF_SIZE
)) == NULL
)
791 num_to_read_thistime
= MIN((n
- total
), TRANSFER_BUF_SIZE
);
793 read_ret
= (*read_fn
)(infd
, buf
, num_to_read_thistime
);
794 if (read_ret
== -1) {
795 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno
) ));
804 while (num_written
< read_ret
) {
805 write_ret
= (*write_fn
)(outfd
,buf
+ num_written
, read_ret
- num_written
);
807 if (write_ret
== -1) {
808 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno
) ));
813 return (ssize_t
)total
;
815 num_written
+= (size_t)write_ret
;
818 total
+= (size_t)read_ret
;
822 return (ssize_t
)total
;
825 SMB_OFF_T
transfer_file(int infd
,int outfd
,SMB_OFF_T n
)
827 return (SMB_OFF_T
)transfer_file_internal(infd
, outfd
, (size_t)n
, sys_read
, sys_write
);
830 /*******************************************************************
831 Sleep for a specified number of milliseconds.
832 ********************************************************************/
834 void msleep(unsigned int t
)
836 unsigned int tdiff
=0;
837 struct timeval tval
,t1
,t2
;
844 tval
.tv_sec
= (t
-tdiff
)/1000;
845 tval
.tv_usec
= 1000*((t
-tdiff
)%1000);
847 /* Never wait for more than 1 sec. */
848 if (tval
.tv_sec
> 1) {
855 sys_select_intr(0,&fds
,NULL
,NULL
,&tval
);
858 if (t2
.tv_sec
< t1
.tv_sec
) {
859 /* Someone adjusted time... */
863 tdiff
= TvalDiff(&t1
,&t2
);
867 /****************************************************************************
868 Become a daemon, discarding the controlling terminal.
869 ****************************************************************************/
871 void become_daemon(BOOL Fork
)
879 /* detach from the terminal */
882 #elif defined(TIOCNOTTY)
884 int i
= sys_open("/dev/tty", O_RDWR
, 0);
886 ioctl(i
, (int) TIOCNOTTY
, (char *)0);
890 #endif /* HAVE_SETSID */
892 /* Close fd's 0,1,2. Needed if started by rsh */
893 close_low_fds(False
); /* Don't close stderr, let the debug system
894 attach it to the logfile */
897 /****************************************************************************
898 Put up a yes/no prompt.
899 ****************************************************************************/
906 if (!fgets(ans
,sizeof(ans
)-1,stdin
))
909 if (*ans
== 'y' || *ans
== 'Y')
915 /****************************************************************************
916 Expand a pointer to be a particular size.
917 ****************************************************************************/
919 void *Realloc(void *p
,size_t size
)
925 DEBUG(5,("Realloc asked for 0 bytes\n"));
930 ret
= (void *)malloc(size
);
932 ret
= (void *)realloc(p
,size
);
935 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size
));
940 /****************************************************************************
941 Free memory, checks for NULL.
942 Use directly SAFE_FREE()
943 Exists only because we need to pass a function pointer somewhere --SSS
944 ****************************************************************************/
946 void safe_free(void *p
)
951 /****************************************************************************
952 Get my own name and IP.
953 ****************************************************************************/
955 BOOL
get_myname(char *my_name
)
961 /* get my host name */
962 if (gethostname(hostname
, sizeof(hostname
)) == -1) {
963 DEBUG(0,("gethostname failed\n"));
967 /* Ensure null termination. */
968 hostname
[sizeof(hostname
)-1] = '\0';
971 /* split off any parts after an initial . */
972 char *p
= strchr_m(hostname
,'.');
977 fstrcpy(my_name
,hostname
);
983 /****************************************************************************
984 Get my own name, including domain.
985 ****************************************************************************/
987 BOOL
get_myfullname(char *my_name
)
993 /* get my host name */
994 if (gethostname(hostname
, sizeof(hostname
)) == -1) {
995 DEBUG(0,("gethostname failed\n"));
999 /* Ensure null termination. */
1000 hostname
[sizeof(hostname
)-1] = '\0';
1003 fstrcpy(my_name
, hostname
);
1007 /****************************************************************************
1008 Get my own domain name.
1009 ****************************************************************************/
1011 BOOL
get_mydomname(fstring my_domname
)
1017 /* get my host name */
1018 if (gethostname(hostname
, sizeof(hostname
)) == -1) {
1019 DEBUG(0,("gethostname failed\n"));
1023 /* Ensure null termination. */
1024 hostname
[sizeof(hostname
)-1] = '\0';
1026 p
= strchr_m(hostname
, '.');
1034 fstrcpy(my_domname
, p
);
1039 /****************************************************************************
1040 Interpret a protocol description string, with a default.
1041 ****************************************************************************/
1043 int interpret_protocol(char *str
,int def
)
1045 if (strequal(str
,"NT1"))
1046 return(PROTOCOL_NT1
);
1047 if (strequal(str
,"LANMAN2"))
1048 return(PROTOCOL_LANMAN2
);
1049 if (strequal(str
,"LANMAN1"))
1050 return(PROTOCOL_LANMAN1
);
1051 if (strequal(str
,"CORE"))
1052 return(PROTOCOL_CORE
);
1053 if (strequal(str
,"COREPLUS"))
1054 return(PROTOCOL_COREPLUS
);
1055 if (strequal(str
,"CORE+"))
1056 return(PROTOCOL_COREPLUS
);
1058 DEBUG(0,("Unrecognised protocol level %s\n",str
));
1063 /****************************************************************************
1064 Return true if a string could be a pure IP address.
1065 ****************************************************************************/
1067 BOOL
is_ipaddress(const char *str
)
1069 BOOL pure_address
= True
;
1072 for (i
=0; pure_address
&& str
[i
]; i
++)
1073 if (!(isdigit((int)str
[i
]) || str
[i
] == '.'))
1074 pure_address
= False
;
1076 /* Check that a pure number is not misinterpreted as an IP */
1077 pure_address
= pure_address
&& (strchr_m(str
, '.') != NULL
);
1079 return pure_address
;
1082 /****************************************************************************
1083 Interpret an internet address or name into an IP address in 4 byte form.
1084 ****************************************************************************/
1086 uint32
interpret_addr(const char *str
)
1091 if (strcmp(str
,"0.0.0.0") == 0)
1093 if (strcmp(str
,"255.255.255.255") == 0)
1096 /* if it's in the form of an IP address then get the lib to interpret it */
1097 if (is_ipaddress(str
)) {
1098 res
= inet_addr(str
);
1100 /* otherwise assume it's a network name of some sort and use
1101 sys_gethostbyname */
1102 if ((hp
= sys_gethostbyname(str
)) == 0) {
1103 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str
));
1107 if(hp
->h_addr
== NULL
) {
1108 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str
));
1111 putip((char *)&res
,(char *)hp
->h_addr
);
1114 if (res
== (uint32
)-1)
1120 /*******************************************************************
1121 A convenient addition to interpret_addr().
1122 ******************************************************************/
1124 struct in_addr
*interpret_addr2(const char *str
)
1126 static struct in_addr ret
;
1127 uint32 a
= interpret_addr(str
);
1132 /*******************************************************************
1133 Check if an IP is the 0.0.0.0.
1134 ******************************************************************/
1136 BOOL
is_zero_ip(struct in_addr ip
)
1139 putip((char *)&a
,(char *)&ip
);
1143 /*******************************************************************
1144 Set an IP to 0.0.0.0.
1145 ******************************************************************/
1147 void zero_ip(struct in_addr
*ip
)
1150 static struct in_addr ipzero
;
1153 ipzero
= *interpret_addr2("0.0.0.0");
1160 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1161 /******************************************************************
1162 Remove any mount options such as -rsize=2048,wsize=2048 etc.
1163 Based on a fix from <Thomas.Hepper@icem.de>.
1164 *******************************************************************/
1166 static void strip_mount_options( pstring
*str
)
1170 while(*p
&& !isspace(*p
))
1172 while(*p
&& isspace(*p
))
1177 pstrcpy(tmp_str
, p
);
1178 pstrcpy(*str
, tmp_str
);
1183 /*******************************************************************
1184 Patch from jkf@soton.ac.uk
1185 Split Luke's automount_server into YP lookup and string splitter
1186 so can easily implement automount_path().
1187 As we may end up doing both, cache the last YP result.
1188 *******************************************************************/
1190 #ifdef WITH_NISPLUS_HOME
1191 char *automount_lookup(const char *user_name
)
1193 static fstring last_key
= "";
1194 static pstring last_value
= "";
1196 char *nis_map
= (char *)lp_nis_home_map_name();
1198 char buffer
[NIS_MAXATTRVAL
+ 1];
1203 if (strcmp(user_name
, last_key
)) {
1204 slprintf(buffer
, sizeof(buffer
)-1, "[key=%s],%s", user_name
, nis_map
);
1205 DEBUG(5, ("NIS+ querystring: %s\n", buffer
));
1207 if (result
= nis_list(buffer
, FOLLOW_PATH
|EXPAND_NAME
|HARD_LOOKUP
, NULL
, NULL
)) {
1208 if (result
->status
!= NIS_SUCCESS
) {
1209 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result
->status
)));
1210 fstrcpy(last_key
, ""); pstrcpy(last_value
, "");
1212 object
= result
->objects
.objects_val
;
1213 if (object
->zo_data
.zo_type
== ENTRY_OBJ
) {
1214 entry
= &object
->zo_data
.objdata_u
.en_data
;
1215 DEBUG(5, ("NIS+ entry type: %s\n", entry
->en_type
));
1216 DEBUG(3, ("NIS+ result: %s\n", entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
));
1218 pstrcpy(last_value
, entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
);
1219 pstring_sub(last_value
, "&", user_name
);
1220 fstrcpy(last_key
, user_name
);
1224 nis_freeresult(result
);
1227 strip_mount_options(&last_value
);
1229 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name
, last_value
));
1232 #else /* WITH_NISPLUS_HOME */
1234 char *automount_lookup(const char *user_name
)
1236 static fstring last_key
= "";
1237 static pstring last_value
= "";
1239 int nis_error
; /* returned by yp all functions */
1240 char *nis_result
; /* yp_match inits this */
1241 int nis_result_len
; /* and set this */
1242 char *nis_domain
; /* yp_get_default_domain inits this */
1243 char *nis_map
= (char *)lp_nis_home_map_name();
1245 if ((nis_error
= yp_get_default_domain(&nis_domain
)) != 0) {
1246 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error
)));
1250 DEBUG(5, ("NIS Domain: %s\n", nis_domain
));
1252 if (!strcmp(user_name
, last_key
)) {
1253 nis_result
= last_value
;
1254 nis_result_len
= strlen(last_value
);
1257 if ((nis_error
= yp_match(nis_domain
, nis_map
, user_name
, strlen(user_name
),
1258 &nis_result
, &nis_result_len
)) == 0) {
1259 if (!nis_error
&& nis_result_len
>= sizeof(pstring
)) {
1260 nis_result_len
= sizeof(pstring
)-1;
1262 fstrcpy(last_key
, user_name
);
1263 strncpy(last_value
, nis_result
, nis_result_len
);
1264 last_value
[nis_result_len
] = '\0';
1265 strip_mount_options(&last_value
);
1267 } else if(nis_error
== YPERR_KEY
) {
1269 /* If Key lookup fails user home server is not in nis_map
1270 use default information for server, and home directory */
1272 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1273 user_name
, nis_map
));
1274 DEBUG(3, ("using defaults for server and home directory\n"));
1276 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1277 yperr_string(nis_error
), user_name
, nis_map
));
1281 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name
, last_value
));
1284 #endif /* WITH_NISPLUS_HOME */
1287 /*******************************************************************
1288 Are two IPs on the same subnet?
1289 ********************************************************************/
1291 BOOL
same_net(struct in_addr ip1
,struct in_addr ip2
,struct in_addr mask
)
1293 uint32 net1
,net2
,nmask
;
1295 nmask
= ntohl(mask
.s_addr
);
1296 net1
= ntohl(ip1
.s_addr
);
1297 net2
= ntohl(ip2
.s_addr
);
1299 return((net1
& nmask
) == (net2
& nmask
));
1303 /****************************************************************************
1304 Check if a process exists. Does this work on all unixes?
1305 ****************************************************************************/
1307 BOOL
process_exists(pid_t pid
)
1309 /* Doing kill with a non-positive pid causes messages to be
1310 * sent to places we don't want. */
1311 SMB_ASSERT(pid
> 0);
1312 return(kill(pid
,0) == 0 || errno
!= ESRCH
);
1315 /*******************************************************************
1316 Convert a uid into a user name.
1317 ********************************************************************/
1319 const char *uidtoname(uid_t uid
)
1321 static fstring name
;
1322 struct passwd
*pass
;
1324 pass
= getpwuid_alloc(uid
);
1326 fstrcpy(name
, pass
->pw_name
);
1329 slprintf(name
, sizeof(name
) - 1, "%ld",(long int)uid
);
1335 /*******************************************************************
1336 Convert a gid into a group name.
1337 ********************************************************************/
1339 char *gidtoname(gid_t gid
)
1341 static fstring name
;
1344 grp
= getgrgid(gid
);
1346 return(grp
->gr_name
);
1347 slprintf(name
,sizeof(name
) - 1, "%d",(int)gid
);
1351 /*******************************************************************
1352 Convert a user name into a uid.
1353 ********************************************************************/
1355 uid_t
nametouid(char *name
)
1357 struct passwd
*pass
;
1361 pass
= getpwnam_alloc(name
);
1368 u
= (uid_t
)strtol(name
, &p
, 0);
1369 if ((p
!= name
) && (*p
== '\0'))
1375 /*******************************************************************
1376 Convert a name to a gid_t if possible. Return -1 if not a group.
1377 ********************************************************************/
1379 gid_t
nametogid(const char *name
)
1385 g
= (gid_t
)strtol(name
, &p
, 0);
1386 if ((p
!= name
) && (*p
== '\0'))
1389 grp
= sys_getgrnam(name
);
1391 return(grp
->gr_gid
);
1395 /*******************************************************************
1396 Something really nasty happened - panic !
1397 ********************************************************************/
1399 void smb_panic(const char *why
)
1406 extern char *global_clobber_region_function
;
1407 extern unsigned int global_clobber_region_line
;
1409 if (global_clobber_region_function
) {
1410 DEBUG(0,("smb_panic: clobber_region() last called from [%s(%u)]\n",
1411 global_clobber_region_function
,
1412 global_clobber_region_line
));
1417 cmd
= lp_panic_action();
1419 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd
));
1420 result
= system(cmd
);
1423 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
1426 DEBUG(0, ("smb_panic(): action returned status %d\n",
1427 WEXITSTATUS(result
)));
1429 DEBUG(0,("PANIC: %s\n", why
));
1434 /*******************************************************************
1435 A readdir wrapper which just returns the file name.
1436 ********************************************************************/
1438 const char *readdirname(DIR *p
)
1440 SMB_STRUCT_DIRENT
*ptr
;
1446 ptr
= (SMB_STRUCT_DIRENT
*)sys_readdir(p
);
1450 dname
= ptr
->d_name
;
1457 #ifdef HAVE_BROKEN_READDIR
1458 /* using /usr/ucb/cc is BAD */
1464 int len
= NAMLEN(ptr
);
1465 memcpy(buf
, dname
, len
);
1473 /*******************************************************************
1474 Utility function used to decide if the last component
1475 of a path matches a (possibly wildcarded) entry in a namelist.
1476 ********************************************************************/
1478 BOOL
is_in_path(const char *name
, name_compare_entry
*namelist
)
1480 pstring last_component
;
1483 DEBUG(8, ("is_in_path: %s\n", name
));
1485 /* if we have no list it's obviously not in the path */
1486 if((namelist
== NULL
) || ((namelist
!= NULL
) && (namelist
[0].name
== NULL
))) {
1487 DEBUG(8,("is_in_path: no name list.\n"));
1491 /* Get the last component of the unix name. */
1492 p
= strrchr_m(name
, '/');
1493 strncpy(last_component
, p
? ++p
: name
, sizeof(last_component
)-1);
1494 last_component
[sizeof(last_component
)-1] = '\0';
1496 for(; namelist
->name
!= NULL
; namelist
++) {
1497 if(namelist
->is_wild
) {
1498 if (mask_match(last_component
, namelist
->name
, case_sensitive
)) {
1499 DEBUG(8,("is_in_path: mask match succeeded\n"));
1503 if((case_sensitive
&& (strcmp(last_component
, namelist
->name
) == 0))||
1504 (!case_sensitive
&& (StrCaseCmp(last_component
, namelist
->name
) == 0))) {
1505 DEBUG(8,("is_in_path: match succeeded\n"));
1510 DEBUG(8,("is_in_path: match not found\n"));
1515 /*******************************************************************
1516 Strip a '/' separated list into an array of
1517 name_compare_enties structures suitable for
1518 passing to is_in_path(). We do this for
1519 speed so we can pre-parse all the names in the list
1520 and don't do it for each call to is_in_path().
1521 namelist is modified here and is assumed to be
1522 a copy owned by the caller.
1523 We also check if the entry contains a wildcard to
1524 remove a potentially expensive call to mask_match
1526 ********************************************************************/
1528 void set_namearray(name_compare_entry
**ppname_array
, char *namelist
)
1531 char *nameptr
= namelist
;
1532 int num_entries
= 0;
1535 (*ppname_array
) = NULL
;
1537 if((nameptr
== NULL
) || ((nameptr
!= NULL
) && (*nameptr
== '\0')))
1540 /* We need to make two passes over the string. The
1541 first to count the number of elements, the second
1546 if ( *nameptr
== '/' ) {
1547 /* cope with multiple (useless) /s) */
1551 /* find the next / */
1552 name_end
= strchr_m(nameptr
, '/');
1554 /* oops - the last check for a / didn't find one. */
1555 if (name_end
== NULL
)
1558 /* next segment please */
1559 nameptr
= name_end
+ 1;
1563 if(num_entries
== 0)
1566 if(( (*ppname_array
) = (name_compare_entry
*)malloc(
1567 (num_entries
+ 1) * sizeof(name_compare_entry
))) == NULL
) {
1568 DEBUG(0,("set_namearray: malloc fail\n"));
1572 /* Now copy out the names */
1576 if ( *nameptr
== '/' ) {
1577 /* cope with multiple (useless) /s) */
1581 /* find the next / */
1582 if ((name_end
= strchr_m(nameptr
, '/')) != NULL
)
1585 /* oops - the last check for a / didn't find one. */
1586 if(name_end
== NULL
)
1589 (*ppname_array
)[i
].is_wild
= ms_has_wild(nameptr
);
1590 if(((*ppname_array
)[i
].name
= strdup(nameptr
)) == NULL
) {
1591 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1595 /* next segment please */
1596 nameptr
= name_end
+ 1;
1600 (*ppname_array
)[i
].name
= NULL
;
1605 /****************************************************************************
1606 Routine to free a namearray.
1607 ****************************************************************************/
1609 void free_namearray(name_compare_entry
*name_array
)
1613 if(name_array
== NULL
)
1616 for(i
=0; name_array
[i
].name
!=NULL
; i
++)
1617 SAFE_FREE(name_array
[i
].name
);
1618 SAFE_FREE(name_array
);
1621 /****************************************************************************
1622 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1623 is dealt with in posix.c
1624 ****************************************************************************/
1626 BOOL
fcntl_lock(int fd
, int op
, SMB_OFF_T offset
, SMB_OFF_T count
, int type
)
1628 SMB_STRUCT_FLOCK lock
;
1631 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd
,op
,(double)offset
,(double)count
,type
));
1634 lock
.l_whence
= SEEK_SET
;
1635 lock
.l_start
= offset
;
1639 ret
= sys_fcntl_ptr(fd
,op
,&lock
);
1641 if (ret
== -1 && errno
!= 0)
1642 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno
,strerror(errno
)));
1645 if (op
== SMB_F_GETLK
) {
1647 (lock
.l_type
!= F_UNLCK
) &&
1648 (lock
.l_pid
!= 0) &&
1649 (lock
.l_pid
!= sys_getpid())) {
1650 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd
,(int)lock
.l_pid
));
1654 /* it must be not locked or locked by me */
1658 /* a lock set or unset */
1660 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1661 (double)offset
,(double)count
,op
,type
,strerror(errno
)));
1665 /* everything went OK */
1666 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1671 /*******************************************************************
1672 Is the name specified one of my netbios names.
1673 Returns true if it is equal, false otherwise.
1674 ********************************************************************/
1676 BOOL
is_myname(const char *s
)
1681 for (n
=0; my_netbios_names(n
); n
++) {
1682 if (strequal(my_netbios_names(n
), s
)) {
1687 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s
, ret
));
1691 /********************************************************************
1692 Return only the first IP address of our configured interfaces
1694 *******************************************************************/
1696 const char* get_my_primary_ip (void)
1698 static fstring ip_string
;
1700 struct iface_struct nics
[MAX_INTERFACES
];
1702 if ((n
=get_interfaces(nics
, MAX_INTERFACES
)) <= 0)
1705 fstrcpy(ip_string
, inet_ntoa(nics
[0].ip
));
1709 BOOL
is_myname_or_ipaddr(const char *s
)
1711 /* optimize for the common case */
1712 if (strequal(s
, global_myname()))
1715 /* maybe its an IP address? */
1716 if (is_ipaddress(s
)) {
1717 struct iface_struct nics
[MAX_INTERFACES
];
1721 ip
= interpret_addr(s
);
1722 if ((ip
==0) || (ip
==0xffffffff))
1725 n
= get_interfaces(nics
, MAX_INTERFACES
);
1726 for (i
=0; i
<n
; i
++) {
1727 if (ip
== nics
[i
].ip
.s_addr
)
1732 /* check for an alias */
1740 /*******************************************************************
1741 Is the name specified our workgroup/domain.
1742 Returns true if it is equal, false otherwise.
1743 ********************************************************************/
1745 BOOL
is_myworkgroup(const char *s
)
1749 if (strequal(s
, lp_workgroup())) {
1753 DEBUG(8, ("is_myworkgroup(\"%s\") returns %d\n", s
, ret
));
1757 /*******************************************************************
1758 we distinguish between 2K and XP by the "Native Lan Manager" string
1759 WinXP => "Windows 2002 5.1"
1760 Win2k => "Windows 2000 5.0"
1761 NT4 => "Windows NT 4.0"
1762 Win9x => "Windows 4.0"
1763 ********************************************************************/
1765 void ra_lanman_string( const char *native_lanman
)
1767 if ( 0 == strcmp( native_lanman
, "Windows 2002 5.1" ) )
1768 set_remote_arch( RA_WINXP
);
1769 else if ( 0 == strcmp( native_lanman
, "Windows .NET 5.2" ) )
1770 set_remote_arch( RA_WIN2K3
);
1773 /*******************************************************************
1774 Set the horrid remote_arch string based on an enum.
1775 ********************************************************************/
1777 void set_remote_arch(enum remote_arch_types type
)
1779 extern fstring remote_arch
;
1783 fstrcpy(remote_arch
, "WfWg");
1786 fstrcpy(remote_arch
, "OS2");
1789 fstrcpy(remote_arch
, "Win95");
1792 fstrcpy(remote_arch
, "WinNT");
1795 fstrcpy(remote_arch
, "Win2K");
1798 fstrcpy(remote_arch
, "WinXP");
1801 fstrcpy(remote_arch
, "Win2K3");
1804 fstrcpy(remote_arch
,"Samba");
1807 ra_type
= RA_UNKNOWN
;
1808 fstrcpy(remote_arch
, "UNKNOWN");
1813 /*******************************************************************
1814 Get the remote_arch type.
1815 ********************************************************************/
1817 enum remote_arch_types
get_remote_arch(void)
1823 void out_ascii(FILE *f
, unsigned char *buf
,int len
)
1827 fprintf(f
, "%c", isprint(buf
[i
])?buf
[i
]:'.');
1830 void out_data(FILE *f
,char *buf1
,int len
, int per_line
)
1832 unsigned char *buf
= (unsigned char *)buf1
;
1838 fprintf(f
, "[%03X] ",i
);
1840 fprintf(f
, "%02X ",(int)buf
[i
]);
1842 if (i
%(per_line
/2) == 0) fprintf(f
, " ");
1843 if (i
%per_line
== 0) {
1844 out_ascii(f
,&buf
[i
-per_line
],per_line
/2); fprintf(f
, " ");
1845 out_ascii(f
,&buf
[i
-per_line
/2],per_line
/2); fprintf(f
, "\n");
1846 if (i
<len
) fprintf(f
, "[%03X] ",i
);
1849 if ((i
%per_line
) != 0) {
1852 n
= per_line
- (i
%per_line
);
1854 if (n
>(per_line
/2)) fprintf(f
, " ");
1858 n
= MIN(per_line
/2,i
%per_line
);
1859 out_ascii(f
,&buf
[i
-(i
%per_line
)],n
); fprintf(f
, " ");
1860 n
= (i
%per_line
) - n
;
1861 if (n
>0) out_ascii(f
,&buf
[i
-n
],n
);
1866 void print_asc(int level
, const unsigned char *buf
,int len
)
1870 DEBUG(level
,("%c", isprint(buf
[i
])?buf
[i
]:'.'));
1873 void dump_data(int level
, const char *buf1
,int len
)
1875 const unsigned char *buf
= (const unsigned char *)buf1
;
1879 if (!DEBUGLVL(level
)) return;
1881 DEBUGADD(level
,("[%03X] ",i
));
1883 DEBUGADD(level
,("%02X ",(int)buf
[i
]));
1885 if (i
%8 == 0) DEBUGADD(level
,(" "));
1887 print_asc(level
,&buf
[i
-16],8); DEBUGADD(level
,(" "));
1888 print_asc(level
,&buf
[i
-8],8); DEBUGADD(level
,("\n"));
1889 if (i
<len
) DEBUGADD(level
,("[%03X] ",i
));
1895 DEBUGADD(level
,(" "));
1896 if (n
>8) DEBUGADD(level
,(" "));
1897 while (n
--) DEBUGADD(level
,(" "));
1899 print_asc(level
,&buf
[i
-(i
%16)],n
); DEBUGADD(level
,( " " ));
1901 if (n
>0) print_asc(level
,&buf
[i
-n
],n
);
1902 DEBUGADD(level
,("\n"));
1906 char *tab_depth(int depth
)
1908 static pstring spaces
;
1909 memset(spaces
, ' ', depth
* 4);
1910 spaces
[depth
* 4] = 0;
1914 /*****************************************************************************
1915 Provide a checksum on a string
1917 Input: s - the null-terminated character string for which the checksum
1920 Output: The checksum value calculated for s.
1921 *****************************************************************************/
1923 int str_checksum(const char *s
)
1931 res
^= (c
<< (i
% 15)) ^ (c
>> (15-(i
%15)));
1938 /*****************************************************************
1939 Zero a memory area then free it. Used to catch bugs faster.
1940 *****************************************************************/
1942 void zero_free(void *p
, size_t size
)
1948 /*****************************************************************
1949 Set our open file limit to a requested max and return the limit.
1950 *****************************************************************/
1952 int set_maxfiles(int requested_max
)
1954 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1956 int saved_current_limit
;
1958 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1959 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1962 return requested_max
;
1966 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1967 * account for the extra fd we need
1968 * as well as the log files and standard
1969 * handles etc. Save the limit we want to set in case
1970 * we are running on an OS that doesn't support this limit (AIX)
1971 * which always returns RLIM_INFINITY for rlp.rlim_max.
1974 /* Try raising the hard (max) limit to the requested amount. */
1976 #if defined(RLIM_INFINITY)
1977 if (rlp
.rlim_max
!= RLIM_INFINITY
) {
1978 int orig_max
= rlp
.rlim_max
;
1980 if ( rlp
.rlim_max
< requested_max
)
1981 rlp
.rlim_max
= requested_max
;
1983 /* This failing is not an error - many systems (Linux) don't
1984 support our default request of 10,000 open files. JRA. */
1986 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1987 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1988 (int)rlp
.rlim_max
, strerror(errno
) ));
1990 /* Set failed - restore original value from get. */
1991 rlp
.rlim_max
= orig_max
;
1996 /* Now try setting the soft (current) limit. */
1998 saved_current_limit
= rlp
.rlim_cur
= MIN(requested_max
,rlp
.rlim_max
);
2000 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
2001 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
2002 (int)rlp
.rlim_cur
, strerror(errno
) ));
2004 return saved_current_limit
;
2007 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
2008 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
2011 return saved_current_limit
;
2014 #if defined(RLIM_INFINITY)
2015 if(rlp
.rlim_cur
== RLIM_INFINITY
)
2016 return saved_current_limit
;
2019 if((int)rlp
.rlim_cur
> saved_current_limit
)
2020 return saved_current_limit
;
2022 return rlp
.rlim_cur
;
2023 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
2025 * No way to know - just guess...
2027 return requested_max
;
2031 /*****************************************************************
2032 Splits out the start of the key (HKLM or HKU) and the rest of the key.
2033 *****************************************************************/
2035 BOOL
reg_split_key(const char *full_keyname
, uint32
*reg_type
, char *key_name
)
2039 if (!next_token(&full_keyname
, tmp
, "\\", sizeof(tmp
)))
2044 DEBUG(10, ("reg_split_key: hive %s\n", tmp
));
2046 if (strequal(tmp
, "HKLM") || strequal(tmp
, "HKEY_LOCAL_MACHINE"))
2047 (*reg_type
) = HKEY_LOCAL_MACHINE
;
2048 else if (strequal(tmp
, "HKU") || strequal(tmp
, "HKEY_USERS"))
2049 (*reg_type
) = HKEY_USERS
;
2051 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp
));
2055 if (next_token(&full_keyname
, tmp
, "\n\r", sizeof(tmp
)))
2056 fstrcpy(key_name
, tmp
);
2060 DEBUG(10, ("reg_split_key: name %s\n", key_name
));
2065 /*****************************************************************
2066 Possibly replace mkstemp if it is broken.
2067 *****************************************************************/
2069 int smb_mkstemp(char *template)
2071 #if HAVE_SECURE_MKSTEMP
2072 return mkstemp(template);
2074 /* have a reasonable go at emulating it. Hope that
2075 the system mktemp() isn't completly hopeless */
2076 char *p
= mktemp(template);
2079 return open(p
, O_CREAT
|O_EXCL
|O_RDWR
, 0600);
2083 /*****************************************************************
2084 malloc that aborts with smb_panic on fail or zero size.
2085 *****************************************************************/
2087 void *smb_xmalloc(size_t size
)
2091 smb_panic("smb_xmalloc: called with zero size.\n");
2092 if ((p
= malloc(size
)) == NULL
) {
2093 DEBUG(0, ("smb_xmalloc() failed to allocate %lu bytes\n", (unsigned long)size
));
2094 smb_panic("smb_xmalloc: malloc fail.\n");
2100 Memdup with smb_panic on fail.
2103 void *smb_xmemdup(const void *p
, size_t size
)
2106 p2
= smb_xmalloc(size
);
2107 memcpy(p2
, p
, size
);
2112 strdup that aborts on malloc fail.
2115 char *smb_xstrdup(const char *s
)
2117 char *s1
= strdup(s
);
2119 smb_panic("smb_xstrdup: malloc fail\n");
2124 strndup that aborts on malloc fail.
2127 char *smb_xstrndup(const char *s
, size_t n
)
2129 char *s1
= strndup(s
, n
);
2131 smb_panic("smb_xstrndup: malloc fail\n");
2136 vasprintf that aborts on malloc fail
2139 int smb_xvasprintf(char **ptr
, const char *format
, va_list ap
)
2146 n
= vasprintf(ptr
, format
, ap2
);
2147 if (n
== -1 || ! *ptr
)
2148 smb_panic("smb_xvasprintf: out of memory");
2152 /*****************************************************************
2153 Like strdup but for memory.
2154 *****************************************************************/
2156 void *memdup(const void *p
, size_t size
)
2164 memcpy(p2
, p
, size
);
2168 /*****************************************************************
2169 Get local hostname and cache result.
2170 *****************************************************************/
2172 char *myhostname(void)
2180 /*****************************************************************
2181 A useful function for returning a path in the Samba lock directory.
2182 *****************************************************************/
2184 char *lock_path(const char *name
)
2186 static pstring fname
;
2188 pstrcpy(fname
,lp_lockdir());
2189 trim_string(fname
,"","/");
2191 if (!directory_exist(fname
,NULL
))
2195 pstrcat(fname
,name
);
2200 /*****************************************************************
2201 A useful function for returning a path in the Samba pid directory.
2202 *****************************************************************/
2204 char *pid_path(const char *name
)
2206 static pstring fname
;
2208 pstrcpy(fname
,lp_piddir());
2209 trim_string(fname
,"","/");
2211 if (!directory_exist(fname
,NULL
))
2215 pstrcat(fname
,name
);
2221 * @brief Returns an absolute path to a file in the Samba lib directory.
2223 * @param name File to find, relative to LIBDIR.
2225 * @retval Pointer to a static #pstring containing the full path.
2228 char *lib_path(const char *name
)
2230 static pstring fname
;
2231 snprintf(fname
, sizeof(fname
), "%s/%s", dyn_LIBDIR
, name
);
2236 * @brief Returns the platform specific shared library extension.
2238 * @retval Pointer to a static #fstring containing the extension.
2241 const char *shlib_ext(void)
2243 return dyn_SHLIBEXT
;
2246 /*******************************************************************
2247 Given a filename - get its directory name
2248 NB: Returned in static storage. Caveats:
2249 o Not safe in thread environment.
2250 o Caller must not free.
2251 o If caller wishes to preserve, they should copy.
2252 ********************************************************************/
2254 char *parent_dirname(const char *path
)
2256 static pstring dirpath
;
2262 pstrcpy(dirpath
, path
);
2263 p
= strrchr_m(dirpath
, '/'); /* Find final '/', if any */
2265 pstrcpy(dirpath
, "."); /* No final "/", so dir is "." */
2268 ++p
; /* For root "/", leave "/" in place */
2275 /*******************************************************************
2276 Determine if a pattern contains any Microsoft wildcard characters.
2277 *******************************************************************/
2279 BOOL
ms_has_wild(char *s
)
2282 while ((c
= *s
++)) {
2295 BOOL
ms_has_wild_w(const smb_ucs2_t
*s
)
2298 if (!s
) return False
;
2299 while ((c
= *s
++)) {
2301 case UCS2_CHAR('*'):
2302 case UCS2_CHAR('?'):
2303 case UCS2_CHAR('<'):
2304 case UCS2_CHAR('>'):
2305 case UCS2_CHAR('"'):
2312 /*******************************************************************
2313 A wrapper that handles case sensitivity and the special handling
2315 *******************************************************************/
2317 BOOL
mask_match(const char *string
, char *pattern
, BOOL is_case_sensitive
)
2321 if (strcmp(string
,"..") == 0)
2323 if (strcmp(pattern
,".") == 0)
2326 if (is_case_sensitive
)
2327 return ms_fnmatch(pattern
, string
, Protocol
) == 0;
2329 fstrcpy(p2
, pattern
);
2330 fstrcpy(s2
, string
);
2333 return ms_fnmatch(p2
, s2
, Protocol
) == 0;
2336 /*********************************************************
2337 Recursive routine that is called by unix_wild_match.
2338 *********************************************************/
2340 static BOOL
unix_do_match(char *regexp
, char *str
)
2344 for( p
= regexp
; *p
&& *str
; ) {
2355 * Look for a character matching
2356 * the one after the '*'.
2360 return True
; /* Automatic match */
2363 while(*str
&& (*p
!= *str
))
2367 * Patch from weidel@multichart.de. In the case of the regexp
2368 * '*XX*' we want to ensure there are at least 2 'X' characters
2369 * in the string after the '*' for a match to be made.
2376 * Eat all the characters that match, but count how many there were.
2379 while(*str
&& (*p
== *str
)) {
2385 * Now check that if the regexp had n identical characters that
2386 * matchcount had at least that many matches.
2389 while ( *(p
+1) && (*(p
+1) == *p
)) {
2394 if ( matchcount
<= 0 )
2398 str
--; /* We've eaten the match char after the '*' */
2400 if(unix_do_match(p
, str
))
2422 if (!*p
&& str
[0] == '.' && str
[1] == 0)
2425 if (!*str
&& *p
== '?') {
2431 if(!*str
&& (*p
== '*' && p
[1] == '\0'))
2437 /*******************************************************************
2438 Simple case insensitive interface to a UNIX wildcard matcher.
2439 *******************************************************************/
2441 BOOL
unix_wild_match(const char *pattern
, const char *string
)
2446 pstrcpy(p2
, pattern
);
2447 pstrcpy(s2
, string
);
2451 /* Remove any *? and ** from the pattern as they are meaningless */
2452 for(p
= p2
; *p
; p
++)
2453 while( *p
== '*' && (p
[1] == '?' ||p
[1] == '*'))
2454 pstrcpy( &p
[1], &p
[2]);
2456 if (strequal(p2
,"*"))
2459 return unix_do_match(p2
, s2
) == 0;
2464 /*******************************************************************
2465 This routine is a trick to immediately catch errors when debugging
2466 with insure. A xterm with a gdb is popped up when insure catches
2467 a error. It is Linux specific.
2468 ********************************************************************/
2470 int _Insure_trap_error(int a1
, int a2
, int a3
, int a4
, int a5
, int a6
)
2475 /* you can get /usr/bin/backtrace from
2476 http://samba.org/ftp/unpacked/junkcode/backtrace */
2477 pstring cmd
= "/usr/bin/backtrace %d";
2479 slprintf(pidstr
, sizeof(pidstr
)-1, "%d", sys_getpid());
2480 pstring_sub(cmd
, "%d", pidstr
);
2484 h
= dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY
);
2485 fn
= dlsym(h
, "_Insure_trap_error");
2487 if (!h
|| h
== _Insure_trap_error
) {
2488 h
= dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY
);
2489 fn
= dlsym(h
, "_Insure_trap_error");
2493 ret
= fn(a1
, a2
, a3
, a4
, a5
, a6
);