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') {
254 fstrcpy( name, myhostname() );
255 p = strchr( name, '.' );
258 if (!set_global_myname(name)) {
259 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
264 if (!set_netbios_aliases(lp_netbios_aliases())) {
265 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
269 fstrcpy( local_machine, global_myname() );
270 trim_string( local_machine, " ", " " );
271 p = strchr( local_machine, ' ' );
274 strlower( local_machine );
276 DEBUG( 5, ("Netbios name list:-\n") );
277 for( n=0; my_netbios_names(n); n++ )
278 DEBUGADD( 5, ( "my_netbios_names[%d]=\"%s\"\n", n, my_netbios_names(n) ) );
283 /**************************************************************************n
284 Find a suitable temporary directory. The result should be copied immediately
285 as it may be overwritten by a subsequent call.
286 ****************************************************************************/
288 const char *tmpdir(void)
291 if ((p = getenv("TMPDIR")))
296 /****************************************************************************
297 Determine whether we are in the specified group.
298 ****************************************************************************/
300 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, const gid_t *groups)
304 if (group == current_gid)
307 for (i=0;i<ngroups;i++)
308 if (group == groups[i])
314 /****************************************************************************
315 Like atoi but gets the value up to the separator character.
316 ****************************************************************************/
318 static char *Atoic(char *p, int *n, char *c)
320 if (!isdigit((int)*p)) {
321 DEBUG(5, ("Atoic: malformed number\n"));
327 while ((*p) && isdigit((int)*p))
330 if (strchr_m(c, *p) == NULL) {
331 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
338 /*************************************************************************
339 Reads a list of numbers.
340 *************************************************************************/
342 char *get_numlist(char *p, uint32 **num, int *count)
346 if (num == NULL || count == NULL)
352 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
355 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
361 (*num)[(*count)] = val;
369 /*******************************************************************
370 Check if a file exists - call vfs_file_exist for samba files.
371 ********************************************************************/
373 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
379 if (sys_stat(fname,sbuf) != 0)
382 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
385 /*******************************************************************
386 Check a files mod time.
387 ********************************************************************/
389 time_t file_modtime(const char *fname)
393 if (sys_stat(fname,&st) != 0)
399 /*******************************************************************
400 Check if a directory exists.
401 ********************************************************************/
403 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
411 if (sys_stat(dname,st) != 0)
414 ret = S_ISDIR(st->st_mode);
420 /*******************************************************************
421 Returns the size in bytes of the named file.
422 ********************************************************************/
424 SMB_OFF_T get_file_size(char *file_name)
428 if(sys_stat(file_name,&buf) != 0)
429 return (SMB_OFF_T)-1;
433 /*******************************************************************
434 Return a string representing an attribute for a file.
435 ********************************************************************/
437 char *attrib_string(uint16 mode)
439 static fstring attrstr;
443 if (mode & aVOLID) fstrcat(attrstr,"V");
444 if (mode & aDIR) fstrcat(attrstr,"D");
445 if (mode & aARCH) fstrcat(attrstr,"A");
446 if (mode & aHIDDEN) fstrcat(attrstr,"H");
447 if (mode & aSYSTEM) fstrcat(attrstr,"S");
448 if (mode & aRONLY) fstrcat(attrstr,"R");
453 /*******************************************************************
454 Show a smb message structure.
455 ********************************************************************/
457 void show_msg(char *buf)
465 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
467 (int)CVAL(buf,smb_com),
468 (int)CVAL(buf,smb_rcls),
469 (int)CVAL(buf,smb_reh),
470 (int)SVAL(buf,smb_err),
471 (int)CVAL(buf,smb_flg),
472 (int)SVAL(buf,smb_flg2)));
473 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
474 (int)SVAL(buf,smb_tid),
475 (int)SVAL(buf,smb_pid),
476 (int)SVAL(buf,smb_uid),
477 (int)SVAL(buf,smb_mid)));
478 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
480 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
481 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
482 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
484 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
486 DEBUGADD(5,("smb_bcc=%d\n",bcc));
494 dump_data(10, smb_buf(buf), bcc);
497 /*******************************************************************
498 Set the length and marker of an smb packet.
499 ********************************************************************/
501 void smb_setlen(char *buf,int len)
503 _smb_setlen(buf,len);
511 /*******************************************************************
512 Setup the word count and byte count for a smb message.
513 ********************************************************************/
515 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
518 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
519 SCVAL(buf,smb_wct,num_words);
520 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
521 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
522 return (smb_size + num_words*2 + num_bytes);
525 /*******************************************************************
526 Setup only the byte count for a smb message.
527 ********************************************************************/
529 int set_message_bcc(char *buf,int num_bytes)
531 int num_words = CVAL(buf,smb_wct);
532 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
533 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
534 return (smb_size + num_words*2 + num_bytes);
537 /*******************************************************************
538 Setup only the byte count for a smb message, using the end of the
540 ********************************************************************/
542 int set_message_end(void *outbuf,void *end_ptr)
544 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
547 /*******************************************************************
548 Reduce a file name, removing .. elements.
549 ********************************************************************/
551 void dos_clean_name(char *s)
555 DEBUG(3,("dos_clean_name [%s]\n",s));
557 /* remove any double slashes */
558 all_string_sub(s, "\\\\", "\\", 0);
560 while ((p = strstr(s,"\\..\\")) != NULL) {
566 if ((p=strrchr_m(s,'\\')) != NULL)
573 trim_string(s,NULL,"\\..");
575 all_string_sub(s, "\\.\\", "\\", 0);
578 /*******************************************************************
579 Reduce a file name, removing .. elements.
580 ********************************************************************/
582 void unix_clean_name(char *s)
586 DEBUG(3,("unix_clean_name [%s]\n",s));
588 /* remove any double slashes */
589 all_string_sub(s, "//","/", 0);
591 /* Remove leading ./ characters */
592 if(strncmp(s, "./", 2) == 0) {
593 trim_string(s, "./", NULL);
598 while ((p = strstr(s,"/../")) != NULL) {
604 if ((p=strrchr_m(s,'/')) != NULL)
611 trim_string(s,NULL,"/..");
614 /*******************************************************************
616 Reduce a file name, removing or reducing /../ , /./ , // elements.
617 Remove also any trailing . and /
618 Return a new allocated string.
619 ********************************************************************/
621 smb_ucs2_t *unix_clean_path(const smb_ucs2_t *s)
624 smb_ucs2_t *p, *r, *t;
626 DEBUG(3, ("unix_clean_path\n")); /* [%unicode]\n")); */
630 /* convert '\' to '/' */
636 /* remove all double slashes */
638 ns = all_string_sub_wa(p, "//", "/");
645 ns = all_string_sub_wa(p, "/./", "/");
650 /* reduce any /../ */
652 while (*t && (r = strstr_wa(t, "/.."))) {
654 if (*t == UCS2_CHAR('/') || *t == 0) {
656 p = strrchr_w(ns, UCS2_CHAR('/'));
662 memmove(p, t, (strlen_w(t) + 1) * sizeof(smb_ucs2_t));
667 /* remove any leading ./ trailing /. */
668 trim_string_wa(ns, "./", "/.");
670 /* remove any leading and trailing / */
671 trim_string_wa(ns, "/", "/");
676 /****************************************************************************
678 ****************************************************************************/
680 void make_dir_struct(char *buf, const char *mask, const char *fname,SMB_OFF_T size,int mode,time_t date)
687 if ((mode & aDIR) != 0)
690 memset(buf+1,' ',11);
691 if ((p = strchr_m(mask2,'.')) != NULL) {
693 push_ascii(buf+1,mask2,8, 0);
694 push_ascii(buf+9,p+1,3, 0);
697 push_ascii(buf+1,mask2,11, 0);
699 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
701 put_dos_date(buf,22,date);
702 SSVAL(buf,26,size & 0xFFFF);
703 SSVAL(buf,28,(size >> 16)&0xFFFF);
704 push_ascii(buf+30,fname,12, case_sensitive ? 0 : STR_UPPER);
705 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
708 /*******************************************************************
709 Close the low 3 fd's and open dev/null in their place.
710 ********************************************************************/
712 void close_low_fds(BOOL stderr_too)
724 /* try and use up these file descriptors, so silly
725 library routines writing to stdout etc won't cause havoc */
727 if (i == 2 && !stderr_too)
730 fd = sys_open("/dev/null",O_RDWR,0);
732 fd = sys_open("/dev/null",O_WRONLY,0);
734 DEBUG(0,("Can't open /dev/null\n"));
738 DEBUG(0,("Didn't get file descriptor %d\n",i));
745 /****************************************************************************
746 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
750 ****************************************************************************/
752 int set_blocking(int fd, BOOL set)
756 #define FLAG_TO_SET O_NONBLOCK
759 #define FLAG_TO_SET O_NDELAY
761 #define FLAG_TO_SET FNDELAY
765 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
767 if(set) /* Turn blocking on - ie. clear nonblock flag */
771 return sys_fcntl_long( fd, F_SETFL, val);
775 /****************************************************************************
776 Transfer some data between two fd's.
777 ****************************************************************************/
779 #ifndef TRANSFER_BUF_SIZE
780 #define TRANSFER_BUF_SIZE 65536
783 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
784 ssize_t (*write_fn)(int, const void *, size_t))
790 size_t num_to_read_thistime;
791 size_t num_written = 0;
793 if ((buf = malloc(TRANSFER_BUF_SIZE)) == NULL)
797 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
799 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
800 if (read_ret == -1) {
801 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
810 while (num_written < read_ret) {
811 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
813 if (write_ret == -1) {
814 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
819 return (ssize_t)total;
821 num_written += (size_t)write_ret;
824 total += (size_t)read_ret;
828 return (ssize_t)total;
831 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
833 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
836 /*******************************************************************
837 Sleep for a specified number of milliseconds.
838 ********************************************************************/
840 void msleep(unsigned int t)
842 unsigned int tdiff=0;
843 struct timeval tval,t1,t2;
850 tval.tv_sec = (t-tdiff)/1000;
851 tval.tv_usec = 1000*((t-tdiff)%1000);
853 /* Never wait for more than 1 sec. */
854 if (tval.tv_sec > 1) {
861 sys_select_intr(0,&fds,NULL,NULL,&tval);
864 if (t2.tv_sec < t1.tv_sec) {
865 /* Someone adjusted time... */
869 tdiff = TvalDiff(&t1,&t2);
873 /****************************************************************************
874 Become a daemon, discarding the controlling terminal.
875 ****************************************************************************/
877 void become_daemon(BOOL Fork)
885 /* detach from the terminal */
888 #elif defined(TIOCNOTTY)
890 int i = sys_open("/dev/tty", O_RDWR, 0);
892 ioctl(i, (int) TIOCNOTTY, (char *)0);
896 #endif /* HAVE_SETSID */
898 /* Close fd's 0,1,2. Needed if started by rsh */
899 close_low_fds(False); /* Don't close stderr, let the debug system
900 attach it to the logfile */
903 /****************************************************************************
904 Put up a yes/no prompt.
905 ****************************************************************************/
912 if (!fgets(ans,sizeof(ans)-1,stdin))
915 if (*ans == 'y' || *ans == 'Y')
921 /****************************************************************************
922 Expand a pointer to be a particular size.
923 ****************************************************************************/
925 void *Realloc(void *p,size_t size)
931 DEBUG(5,("Realloc asked for 0 bytes\n"));
936 ret = (void *)malloc(size);
938 ret = (void *)realloc(p,size);
941 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
946 /****************************************************************************
947 Free memory, checks for NULL.
948 Use directly SAFE_FREE()
949 Exists only because we need to pass a function pointer somewhere --SSS
950 ****************************************************************************/
952 void safe_free(void *p)
957 /****************************************************************************
958 Get my own name and IP.
959 ****************************************************************************/
961 BOOL get_myname(char *my_name)
967 /* get my host name */
968 if (gethostname(hostname, sizeof(hostname)) == -1) {
969 DEBUG(0,("gethostname failed\n"));
973 /* Ensure null termination. */
974 hostname[sizeof(hostname)-1] = '\0';
977 /* split off any parts after an initial . */
978 char *p = strchr_m(hostname,'.');
983 fstrcpy(my_name,hostname);
989 /****************************************************************************
990 Get my own name, including domain.
991 ****************************************************************************/
993 BOOL get_myfullname(char *my_name)
999 /* get my host name */
1000 if (gethostname(hostname, sizeof(hostname)) == -1) {
1001 DEBUG(0,("gethostname failed\n"));
1005 /* Ensure null termination. */
1006 hostname[sizeof(hostname)-1] = '\0';
1009 fstrcpy(my_name, hostname);
1013 /****************************************************************************
1014 Get my own domain name.
1015 ****************************************************************************/
1017 BOOL get_mydomname(char *my_domname)
1023 /* get my host name */
1024 if (gethostname(hostname, sizeof(hostname)) == -1) {
1025 DEBUG(0,("gethostname failed\n"));
1029 /* Ensure null termination. */
1030 hostname[sizeof(hostname)-1] = '\0';
1032 p = strchr_m(hostname, '.');
1040 fstrcpy(my_domname, p);
1045 /****************************************************************************
1046 Interpret a protocol description string, with a default.
1047 ****************************************************************************/
1049 int interpret_protocol(char *str,int def)
1051 if (strequal(str,"NT1"))
1052 return(PROTOCOL_NT1);
1053 if (strequal(str,"LANMAN2"))
1054 return(PROTOCOL_LANMAN2);
1055 if (strequal(str,"LANMAN1"))
1056 return(PROTOCOL_LANMAN1);
1057 if (strequal(str,"CORE"))
1058 return(PROTOCOL_CORE);
1059 if (strequal(str,"COREPLUS"))
1060 return(PROTOCOL_COREPLUS);
1061 if (strequal(str,"CORE+"))
1062 return(PROTOCOL_COREPLUS);
1064 DEBUG(0,("Unrecognised protocol level %s\n",str));
1069 /****************************************************************************
1070 Return true if a string could be a pure IP address.
1071 ****************************************************************************/
1073 BOOL is_ipaddress(const char *str)
1075 BOOL pure_address = True;
1078 for (i=0; pure_address && str[i]; i++)
1079 if (!(isdigit((int)str[i]) || str[i] == '.'))
1080 pure_address = False;
1082 /* Check that a pure number is not misinterpreted as an IP */
1083 pure_address = pure_address && (strchr_m(str, '.') != NULL);
1085 return pure_address;
1088 /****************************************************************************
1089 Interpret an internet address or name into an IP address in 4 byte form.
1090 ****************************************************************************/
1092 uint32 interpret_addr(const char *str)
1097 if (strcmp(str,"0.0.0.0") == 0)
1099 if (strcmp(str,"255.255.255.255") == 0)
1102 /* if it's in the form of an IP address then get the lib to interpret it */
1103 if (is_ipaddress(str)) {
1104 res = inet_addr(str);
1106 /* otherwise assume it's a network name of some sort and use
1107 sys_gethostbyname */
1108 if ((hp = sys_gethostbyname(str)) == 0) {
1109 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
1113 if(hp->h_addr == NULL) {
1114 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
1117 putip((char *)&res,(char *)hp->h_addr);
1120 if (res == (uint32)-1)
1126 /*******************************************************************
1127 A convenient addition to interpret_addr().
1128 ******************************************************************/
1130 struct in_addr *interpret_addr2(const char *str)
1132 static struct in_addr ret;
1133 uint32 a = interpret_addr(str);
1138 /*******************************************************************
1139 Check if an IP is the 0.0.0.0.
1140 ******************************************************************/
1142 BOOL is_zero_ip(struct in_addr ip)
1145 putip((char *)&a,(char *)&ip);
1149 /*******************************************************************
1150 Set an IP to 0.0.0.0.
1151 ******************************************************************/
1153 void zero_ip(struct in_addr *ip)
1156 static struct in_addr ipzero;
1159 ipzero = *interpret_addr2("0.0.0.0");
1166 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1167 /******************************************************************
1168 Remove any mount options such as -rsize=2048,wsize=2048 etc.
1169 Based on a fix from <Thomas.Hepper@icem.de>.
1170 *******************************************************************/
1172 static void strip_mount_options( pstring *str)
1176 while(*p && !isspace(*p))
1178 while(*p && isspace(*p))
1183 pstrcpy(tmp_str, p);
1184 pstrcpy(*str, tmp_str);
1189 /*******************************************************************
1190 Patch from jkf@soton.ac.uk
1191 Split Luke's automount_server into YP lookup and string splitter
1192 so can easily implement automount_path().
1193 As we may end up doing both, cache the last YP result.
1194 *******************************************************************/
1196 #ifdef WITH_NISPLUS_HOME
1197 char *automount_lookup(const char *user_name)
1199 static fstring last_key = "";
1200 static pstring last_value = "";
1202 char *nis_map = (char *)lp_nis_home_map_name();
1204 char buffer[NIS_MAXATTRVAL + 1];
1209 if (strcmp(user_name, last_key)) {
1210 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
1211 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
1213 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
1214 if (result->status != NIS_SUCCESS) {
1215 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
1216 fstrcpy(last_key, ""); pstrcpy(last_value, "");
1218 object = result->objects.objects_val;
1219 if (object->zo_data.zo_type == ENTRY_OBJ) {
1220 entry = &object->zo_data.objdata_u.en_data;
1221 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
1222 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
1224 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
1225 pstring_sub(last_value, "&", user_name);
1226 fstrcpy(last_key, user_name);
1230 nis_freeresult(result);
1233 strip_mount_options(&last_value);
1235 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
1238 #else /* WITH_NISPLUS_HOME */
1240 char *automount_lookup(const char *user_name)
1242 static fstring last_key = "";
1243 static pstring last_value = "";
1245 int nis_error; /* returned by yp all functions */
1246 char *nis_result; /* yp_match inits this */
1247 int nis_result_len; /* and set this */
1248 char *nis_domain; /* yp_get_default_domain inits this */
1249 char *nis_map = (char *)lp_nis_home_map_name();
1251 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
1252 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
1256 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
1258 if (!strcmp(user_name, last_key)) {
1259 nis_result = last_value;
1260 nis_result_len = strlen(last_value);
1263 if ((nis_error = yp_match(nis_domain, nis_map, user_name, strlen(user_name),
1264 &nis_result, &nis_result_len)) == 0) {
1265 if (!nis_error && nis_result_len >= sizeof(pstring)) {
1266 nis_result_len = sizeof(pstring)-1;
1268 fstrcpy(last_key, user_name);
1269 strncpy(last_value, nis_result, nis_result_len);
1270 last_value[nis_result_len] = '\0';
1271 strip_mount_options(&last_value);
1273 } else if(nis_error == YPERR_KEY) {
1275 /* If Key lookup fails user home server is not in nis_map
1276 use default information for server, and home directory */
1278 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1279 user_name, nis_map));
1280 DEBUG(3, ("using defaults for server and home directory\n"));
1282 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1283 yperr_string(nis_error), user_name, nis_map));
1287 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1290 #endif /* WITH_NISPLUS_HOME */
1293 /*******************************************************************
1294 Are two IPs on the same subnet?
1295 ********************************************************************/
1297 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1299 uint32 net1,net2,nmask;
1301 nmask = ntohl(mask.s_addr);
1302 net1 = ntohl(ip1.s_addr);
1303 net2 = ntohl(ip2.s_addr);
1305 return((net1 & nmask) == (net2 & nmask));
1309 /****************************************************************************
1310 Check if a process exists. Does this work on all unixes?
1311 ****************************************************************************/
1313 BOOL process_exists(pid_t pid)
1315 /* Doing kill with a non-positive pid causes messages to be
1316 * sent to places we don't want. */
1317 SMB_ASSERT(pid > 0);
1318 return(kill(pid,0) == 0 || errno != ESRCH);
1321 /*******************************************************************
1322 Convert a uid into a user name.
1323 ********************************************************************/
1325 const char *uidtoname(uid_t uid)
1327 static fstring name;
1328 struct passwd *pass;
1330 pass = getpwuid_alloc(uid);
1332 fstrcpy(name, pass->pw_name);
1335 slprintf(name, sizeof(name) - 1, "%ld",(long int)uid);
1341 /*******************************************************************
1342 Convert a gid into a group name.
1343 ********************************************************************/
1345 char *gidtoname(gid_t gid)
1347 static fstring name;
1350 grp = getgrgid(gid);
1352 return(grp->gr_name);
1353 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1357 /*******************************************************************
1358 Convert a user name into a uid.
1359 ********************************************************************/
1361 uid_t nametouid(char *name)
1363 struct passwd *pass;
1367 pass = getpwnam_alloc(name);
1374 u = (uid_t)strtol(name, &p, 0);
1375 if ((p != name) && (*p == '\0'))
1381 /*******************************************************************
1382 Convert a name to a gid_t if possible. Return -1 if not a group.
1383 ********************************************************************/
1385 gid_t nametogid(const char *name)
1391 g = (gid_t)strtol(name, &p, 0);
1392 if ((p != name) && (*p == '\0'))
1395 grp = sys_getgrnam(name);
1397 return(grp->gr_gid);
1401 /*******************************************************************
1402 Something really nasty happened - panic !
1403 ********************************************************************/
1405 void smb_panic(const char *why)
1407 char *cmd = lp_panic_action();
1411 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
1412 result = system(cmd);
1415 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
1418 DEBUG(0, ("smb_panic(): action returned status %d\n",
1419 WEXITSTATUS(result)));
1421 DEBUG(0,("PANIC: %s\n", why));
1426 /*******************************************************************
1427 A readdir wrapper which just returns the file name.
1428 ********************************************************************/
1430 char *readdirname(DIR *p)
1432 SMB_STRUCT_DIRENT *ptr;
1438 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1442 dname = ptr->d_name;
1449 #ifdef HAVE_BROKEN_READDIR
1450 /* using /usr/ucb/cc is BAD */
1456 int len = NAMLEN(ptr);
1457 memcpy(buf, dname, len);
1465 /*******************************************************************
1466 Utility function used to decide if the last component
1467 of a path matches a (possibly wildcarded) entry in a namelist.
1468 ********************************************************************/
1470 BOOL is_in_path(const char *name, name_compare_entry *namelist)
1472 pstring last_component;
1475 DEBUG(8, ("is_in_path: %s\n", name));
1477 /* if we have no list it's obviously not in the path */
1478 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
1479 DEBUG(8,("is_in_path: no name list.\n"));
1483 /* Get the last component of the unix name. */
1484 p = strrchr_m(name, '/');
1485 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1486 last_component[sizeof(last_component)-1] = '\0';
1488 for(; namelist->name != NULL; namelist++) {
1489 if(namelist->is_wild) {
1490 if (mask_match(last_component, namelist->name, case_sensitive)) {
1491 DEBUG(8,("is_in_path: mask match succeeded\n"));
1495 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1496 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0))) {
1497 DEBUG(8,("is_in_path: match succeeded\n"));
1502 DEBUG(8,("is_in_path: match not found\n"));
1507 /*******************************************************************
1508 Strip a '/' separated list into an array of
1509 name_compare_enties structures suitable for
1510 passing to is_in_path(). We do this for
1511 speed so we can pre-parse all the names in the list
1512 and don't do it for each call to is_in_path().
1513 namelist is modified here and is assumed to be
1514 a copy owned by the caller.
1515 We also check if the entry contains a wildcard to
1516 remove a potentially expensive call to mask_match
1518 ********************************************************************/
1520 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1523 char *nameptr = namelist;
1524 int num_entries = 0;
1527 (*ppname_array) = NULL;
1529 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1532 /* We need to make two passes over the string. The
1533 first to count the number of elements, the second
1538 if ( *nameptr == '/' ) {
1539 /* cope with multiple (useless) /s) */
1543 /* find the next / */
1544 name_end = strchr_m(nameptr, '/');
1546 /* oops - the last check for a / didn't find one. */
1547 if (name_end == NULL)
1550 /* next segment please */
1551 nameptr = name_end + 1;
1555 if(num_entries == 0)
1558 if(( (*ppname_array) = (name_compare_entry *)malloc(
1559 (num_entries + 1) * sizeof(name_compare_entry))) == NULL) {
1560 DEBUG(0,("set_namearray: malloc fail\n"));
1564 /* Now copy out the names */
1568 if ( *nameptr == '/' ) {
1569 /* cope with multiple (useless) /s) */
1573 /* find the next / */
1574 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1577 /* oops - the last check for a / didn't find one. */
1578 if(name_end == NULL)
1581 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1582 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL) {
1583 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1587 /* next segment please */
1588 nameptr = name_end + 1;
1592 (*ppname_array)[i].name = NULL;
1597 /****************************************************************************
1598 Routine to free a namearray.
1599 ****************************************************************************/
1601 void free_namearray(name_compare_entry *name_array)
1605 if(name_array == NULL)
1608 for(i=0; name_array[i].name!=NULL; i++)
1609 SAFE_FREE(name_array[i].name);
1610 SAFE_FREE(name_array);
1613 /****************************************************************************
1614 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1615 is dealt with in posix.c
1616 ****************************************************************************/
1618 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1620 SMB_STRUCT_FLOCK lock;
1623 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1626 lock.l_whence = SEEK_SET;
1627 lock.l_start = offset;
1631 ret = sys_fcntl_ptr(fd,op,&lock);
1633 if (ret == -1 && errno != 0)
1634 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1637 if (op == SMB_F_GETLK) {
1639 (lock.l_type != F_UNLCK) &&
1640 (lock.l_pid != 0) &&
1641 (lock.l_pid != sys_getpid())) {
1642 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1646 /* it must be not locked or locked by me */
1650 /* a lock set or unset */
1652 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1653 (double)offset,(double)count,op,type,strerror(errno)));
1657 /* everything went OK */
1658 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1663 /*******************************************************************
1664 Is the name specified one of my netbios names.
1665 Returns true if it is equal, false otherwise.
1666 ********************************************************************/
1668 BOOL is_myname(const char *s)
1673 for (n=0; my_netbios_names(n); n++) {
1674 if (strequal(my_netbios_names(n), s)) {
1679 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1683 /********************************************************************
1684 Return only the first IP address of our configured interfaces
1686 *******************************************************************/
1688 const char* get_my_primary_ip (void)
1690 static fstring ip_string;
1692 struct iface_struct nics[MAX_INTERFACES];
1694 if ((n=get_interfaces(nics, MAX_INTERFACES)) <= 0)
1697 fstrcpy(ip_string, inet_ntoa(nics[0].ip));
1701 BOOL is_myname_or_ipaddr(const char *s)
1703 /* optimize for the common case */
1704 if (strequal(s, global_myname()))
1707 /* maybe its an IP address? */
1708 if (is_ipaddress(s)) {
1709 struct iface_struct nics[MAX_INTERFACES];
1713 ip = interpret_addr(s);
1714 if ((ip==0) || (ip==0xffffffff))
1717 n = get_interfaces(nics, MAX_INTERFACES);
1718 for (i=0; i<n; i++) {
1719 if (ip == nics[i].ip.s_addr)
1724 /* check for an alias */
1732 /*******************************************************************
1733 Set the horrid remote_arch string based on an enum.
1734 ********************************************************************/
1736 void set_remote_arch(enum remote_arch_types type)
1738 extern fstring remote_arch;
1742 fstrcpy(remote_arch, "WfWg");
1745 fstrcpy(remote_arch, "OS2");
1748 fstrcpy(remote_arch, "Win95");
1751 fstrcpy(remote_arch, "WinNT");
1754 fstrcpy(remote_arch, "Win2K");
1757 fstrcpy(remote_arch,"Samba");
1760 ra_type = RA_UNKNOWN;
1761 fstrcpy(remote_arch, "UNKNOWN");
1766 /*******************************************************************
1767 Get the remote_arch type.
1768 ********************************************************************/
1770 enum remote_arch_types get_remote_arch(void)
1776 void out_ascii(FILE *f, unsigned char *buf,int len)
1780 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1783 void out_data(FILE *f,char *buf1,int len, int per_line)
1785 unsigned char *buf = (unsigned char *)buf1;
1791 fprintf(f, "[%03X] ",i);
1793 fprintf(f, "%02X ",(int)buf[i]);
1795 if (i%(per_line/2) == 0) fprintf(f, " ");
1796 if (i%per_line == 0) {
1797 out_ascii(f,&buf[i-per_line ],per_line/2); fprintf(f, " ");
1798 out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1799 if (i<len) fprintf(f, "[%03X] ",i);
1802 if ((i%per_line) != 0) {
1805 n = per_line - (i%per_line);
1807 if (n>(per_line/2)) fprintf(f, " ");
1811 n = MIN(per_line/2,i%per_line);
1812 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1813 n = (i%per_line) - n;
1814 if (n>0) out_ascii(f,&buf[i-n],n);
1819 void print_asc(int level, const unsigned char *buf,int len)
1823 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1826 void dump_data(int level, const char *buf1,int len)
1828 const unsigned char *buf = (const unsigned char *)buf1;
1832 if (!DEBUGLVL(level)) return;
1834 DEBUGADD(level,("[%03X] ",i));
1836 DEBUGADD(level,("%02X ",(int)buf[i]));
1838 if (i%8 == 0) DEBUGADD(level,(" "));
1840 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
1841 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
1842 if (i<len) DEBUGADD(level,("[%03X] ",i));
1848 DEBUGADD(level,(" "));
1849 if (n>8) DEBUGADD(level,(" "));
1850 while (n--) DEBUGADD(level,(" "));
1852 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
1854 if (n>0) print_asc(level,&buf[i-n],n);
1855 DEBUGADD(level,("\n"));
1859 char *tab_depth(int depth)
1861 static pstring spaces;
1862 memset(spaces, ' ', depth * 4);
1863 spaces[depth * 4] = 0;
1867 /*****************************************************************************
1868 Provide a checksum on a string
1870 Input: s - the null-terminated character string for which the checksum
1873 Output: The checksum value calculated for s.
1874 *****************************************************************************/
1876 int str_checksum(const char *s)
1884 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1891 /*****************************************************************
1892 Zero a memory area then free it. Used to catch bugs faster.
1893 *****************************************************************/
1895 void zero_free(void *p, size_t size)
1901 /*****************************************************************
1902 Set our open file limit to a requested max and return the limit.
1903 *****************************************************************/
1905 int set_maxfiles(int requested_max)
1907 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1909 int saved_current_limit;
1911 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1912 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1915 return requested_max;
1919 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1920 * account for the extra fd we need
1921 * as well as the log files and standard
1922 * handles etc. Save the limit we want to set in case
1923 * we are running on an OS that doesn't support this limit (AIX)
1924 * which always returns RLIM_INFINITY for rlp.rlim_max.
1927 /* Try raising the hard (max) limit to the requested amount. */
1929 #if defined(RLIM_INFINITY)
1930 if (rlp.rlim_max != RLIM_INFINITY) {
1931 int orig_max = rlp.rlim_max;
1933 if ( rlp.rlim_max < requested_max )
1934 rlp.rlim_max = requested_max;
1936 /* This failing is not an error - many systems (Linux) don't
1937 support our default request of 10,000 open files. JRA. */
1939 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1940 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1941 (int)rlp.rlim_max, strerror(errno) ));
1943 /* Set failed - restore original value from get. */
1944 rlp.rlim_max = orig_max;
1949 /* Now try setting the soft (current) limit. */
1951 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1953 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1954 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1955 (int)rlp.rlim_cur, strerror(errno) ));
1957 return saved_current_limit;
1960 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1961 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1964 return saved_current_limit;
1967 #if defined(RLIM_INFINITY)
1968 if(rlp.rlim_cur == RLIM_INFINITY)
1969 return saved_current_limit;
1972 if((int)rlp.rlim_cur > saved_current_limit)
1973 return saved_current_limit;
1975 return rlp.rlim_cur;
1976 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1978 * No way to know - just guess...
1980 return requested_max;
1984 /*****************************************************************
1985 Splits out the start of the key (HKLM or HKU) and the rest of the key.
1986 *****************************************************************/
1988 BOOL reg_split_key(const char *full_keyname, uint32 *reg_type, char *key_name)
1992 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1997 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1999 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
2000 (*reg_type) = HKEY_LOCAL_MACHINE;
2001 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
2002 (*reg_type) = HKEY_USERS;
2004 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
2008 if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
2009 fstrcpy(key_name, tmp);
2013 DEBUG(10, ("reg_split_key: name %s\n", key_name));
2018 /*****************************************************************
2019 Possibly replace mkstemp if it is broken.
2020 *****************************************************************/
2022 int smb_mkstemp(char *template)
2024 #if HAVE_SECURE_MKSTEMP
2025 return mkstemp(template);
2027 /* have a reasonable go at emulating it. Hope that
2028 the system mktemp() isn't completly hopeless */
2029 char *p = mktemp(template);
2032 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
2036 /*****************************************************************
2037 malloc that aborts with smb_panic on fail or zero size.
2038 *****************************************************************/
2040 void *smb_xmalloc(size_t size)
2044 smb_panic("smb_xmalloc: called with zero size.\n");
2045 if ((p = malloc(size)) == NULL)
2046 smb_panic("smb_xmalloc: malloc fail.\n");
2051 Memdup with smb_panic on fail.
2054 void *smb_xmemdup(const void *p, size_t size)
2057 p2 = smb_xmalloc(size);
2058 memcpy(p2, p, size);
2063 strdup that aborts on malloc fail.
2066 char *smb_xstrdup(const char *s)
2068 char *s1 = strdup(s);
2070 smb_panic("smb_xstrdup: malloc fail\n");
2075 strndup that aborts on malloc fail.
2078 char *smb_xstrndup(const char *s, size_t n)
2080 char *s1 = strndup(s, n);
2082 smb_panic("smb_xstrndup: malloc fail\n");
2087 vasprintf that aborts on malloc fail
2090 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
2097 n = vasprintf(ptr, format, ap2);
2098 if (n == -1 || ! *ptr)
2099 smb_panic("smb_xvasprintf: out of memory");
2103 /*****************************************************************
2104 Like strdup but for memory.
2105 *****************************************************************/
2107 void *memdup(const void *p, size_t size)
2115 memcpy(p2, p, size);
2119 /*****************************************************************
2120 Get local hostname and cache result.
2121 *****************************************************************/
2123 char *myhostname(void)
2131 /*****************************************************************
2132 A useful function for returning a path in the Samba lock directory.
2133 *****************************************************************/
2135 char *lock_path(const char *name)
2137 static pstring fname;
2139 pstrcpy(fname,lp_lockdir());
2140 trim_string(fname,"","/");
2142 if (!directory_exist(fname,NULL))
2146 pstrcat(fname,name);
2151 /*****************************************************************
2152 A useful function for returning a path in the Samba pid directory.
2153 *****************************************************************/
2155 char *pid_path(const char *name)
2157 static pstring fname;
2159 pstrcpy(fname,lp_piddir());
2160 trim_string(fname,"","/");
2162 if (!directory_exist(fname,NULL))
2166 pstrcat(fname,name);
2172 * @brief Returns an absolute path to a file in the Samba lib directory.
2174 * @param name File to find, relative to LIBDIR.
2176 * @retval Pointer to a static #pstring containing the full path.
2179 char *lib_path(const char *name)
2181 static pstring fname;
2182 snprintf(fname, sizeof(fname), "%s/%s", dyn_LIBDIR, name);
2187 * @brief Returns the platform specific shared library extension.
2189 * @retval Pointer to a static #fstring containing the extension.
2192 const char *shlib_ext(void)
2194 return dyn_SHLIBEXT;
2197 /*******************************************************************
2198 Given a filename - get its directory name
2199 NB: Returned in static storage. Caveats:
2200 o Not safe in thread environment.
2201 o Caller must not free.
2202 o If caller wishes to preserve, they should copy.
2203 ********************************************************************/
2205 char *parent_dirname(const char *path)
2207 static pstring dirpath;
2213 pstrcpy(dirpath, path);
2214 p = strrchr_m(dirpath, '/'); /* Find final '/', if any */
2216 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
2219 ++p; /* For root "/", leave "/" in place */
2226 /*******************************************************************
2227 Determine if a pattern contains any Microsoft wildcard characters.
2228 *******************************************************************/
2230 BOOL ms_has_wild(char *s)
2233 while ((c = *s++)) {
2246 BOOL ms_has_wild_w(const smb_ucs2_t *s)
2249 if (!s) return False;
2250 while ((c = *s++)) {
2252 case UCS2_CHAR('*'):
2253 case UCS2_CHAR('?'):
2254 case UCS2_CHAR('<'):
2255 case UCS2_CHAR('>'):
2256 case UCS2_CHAR('"'):
2263 /*******************************************************************
2264 A wrapper that handles case sensitivity and the special handling
2266 *******************************************************************/
2268 BOOL mask_match(const char *string, char *pattern, BOOL is_case_sensitive)
2272 if (strcmp(string,"..") == 0)
2274 if (strcmp(pattern,".") == 0)
2277 if (is_case_sensitive)
2278 return ms_fnmatch(pattern, string, Protocol) == 0;
2280 fstrcpy(p2, pattern);
2281 fstrcpy(s2, string);
2284 return ms_fnmatch(p2, s2, Protocol) == 0;
2287 /*********************************************************
2288 Recursive routine that is called by unix_wild_match.
2289 *********************************************************/
2291 static BOOL unix_do_match(char *regexp, char *str)
2295 for( p = regexp; *p && *str; ) {
2306 * Look for a character matching
2307 * the one after the '*'.
2311 return True; /* Automatic match */
2314 while(*str && (*p != *str))
2318 * Patch from weidel@multichart.de. In the case of the regexp
2319 * '*XX*' we want to ensure there are at least 2 'X' characters
2320 * in the string after the '*' for a match to be made.
2327 * Eat all the characters that match, but count how many there were.
2330 while(*str && (*p == *str)) {
2336 * Now check that if the regexp had n identical characters that
2337 * matchcount had at least that many matches.
2340 while ( *(p+1) && (*(p+1) == *p)) {
2345 if ( matchcount <= 0 )
2349 str--; /* We've eaten the match char after the '*' */
2351 if(unix_do_match(p, str))
2373 if (!*p && str[0] == '.' && str[1] == 0)
2376 if (!*str && *p == '?') {
2382 if(!*str && (*p == '*' && p[1] == '\0'))
2388 /*******************************************************************
2389 Simple case insensitive interface to a UNIX wildcard matcher.
2390 *******************************************************************/
2392 BOOL unix_wild_match(char *pattern, char *string)
2397 pstrcpy(p2, pattern);
2398 pstrcpy(s2, string);
2402 /* Remove any *? and ** from the pattern as they are meaningless */
2403 for(p = p2; *p; p++)
2404 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2405 pstrcpy( &p[1], &p[2]);
2407 if (strequal(p2,"*"))
2410 return unix_do_match(p2, s2) == 0;
2415 /*******************************************************************
2416 This routine is a trick to immediately catch errors when debugging
2417 with insure. A xterm with a gdb is popped up when insure catches
2418 a error. It is Linux specific.
2419 ********************************************************************/
2421 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2426 /* you can get /usr/bin/backtrace from
2427 http://samba.org/ftp/unpacked/junkcode/backtrace */
2428 pstring cmd = "/usr/bin/backtrace %d";
2430 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2431 pstring_sub(cmd, "%d", pidstr);
2435 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2436 fn = dlsym(h, "_Insure_trap_error");
2438 if (!h || h == _Insure_trap_error) {
2439 h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2440 fn = dlsym(h, "_Insure_trap_error");
2444 ret = fn(a1, a2, a3, a4, a5, a6);