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
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
26 #ifdef WITH_NISPLUS_HOME
27 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
29 * The following lines are needed due to buggy include files
30 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
31 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
32 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
33 * an enum in /usr/include/rpcsvc/nis.h.
40 #if defined(GROUP_OBJ)
44 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
46 #include <rpcsvc/nis.h>
48 #else /* !WITH_NISPLUS_HOME */
50 #include "rpcsvc/ypclnt.h"
52 #endif /* WITH_NISPLUS_HOME */
53 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
55 int Protocol = PROTOCOL_COREPLUS;
57 /* a default finfo structure to ensure all fields are sensible */
58 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
60 /* this is used by the chaining code */
66 case handling on filenames
68 int case_default = CASE_LOWER;
70 /* the following control case operations - they are put here so the
71 client can link easily */
74 BOOL use_mangled_map = False;
75 BOOL short_case_preserve;
78 static enum remote_arch_types ra_type = RA_UNKNOWN;
79 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;
81 /***********************************************************************
82 Definitions for all names.
83 ***********************************************************************/
85 static char *smb_myname;
86 static char *smb_myworkgroup;
87 static char *smb_scope;
88 static int smb_num_netbios_names;
89 static char **smb_my_netbios_names;
91 /***********************************************************************
92 Allocate and set myname. Ensure upper case.
93 ***********************************************************************/
95 BOOL set_global_myname(const char *myname)
97 SAFE_FREE(smb_myname);
98 smb_myname = strdup(myname);
101 strupper(smb_myname);
105 const char *global_myname(void)
110 /***********************************************************************
111 Allocate and set myworkgroup. Ensure upper case.
112 ***********************************************************************/
114 BOOL set_global_myworkgroup(const char *myworkgroup)
116 SAFE_FREE(smb_myworkgroup);
117 smb_myworkgroup = strdup(myworkgroup);
118 if (!smb_myworkgroup)
120 strupper(smb_myworkgroup);
124 const char *lp_workgroup(void)
126 return smb_myworkgroup;
129 /***********************************************************************
130 Allocate and set scope. Ensure upper case.
131 ***********************************************************************/
133 BOOL set_global_scope(const char *scope)
135 SAFE_FREE(smb_scope);
136 smb_scope = strdup(scope);
143 /*********************************************************************
144 Ensure scope is never null string.
145 *********************************************************************/
147 const char *global_scope(void)
150 set_global_scope("");
154 static void free_netbios_names_array(void)
158 for (i = 0; i < smb_num_netbios_names; i++)
159 SAFE_FREE(smb_my_netbios_names[i]);
161 SAFE_FREE(smb_my_netbios_names);
162 smb_num_netbios_names = 0;
165 static BOOL allocate_my_netbios_names_array(size_t number)
167 free_netbios_names_array();
169 smb_num_netbios_names = number + 1;
170 smb_my_netbios_names = (char **)malloc( sizeof(char *) * smb_num_netbios_names );
172 if (!smb_my_netbios_names)
175 memset(smb_my_netbios_names, '\0', sizeof(char *) * smb_num_netbios_names);
179 static BOOL set_my_netbios_names(const char *name, int i)
181 SAFE_FREE(smb_my_netbios_names[i]);
183 smb_my_netbios_names[i] = strdup(name);
184 if (!smb_my_netbios_names[i])
186 strupper(smb_my_netbios_names[i]);
190 const char *my_netbios_names(int i)
192 return smb_my_netbios_names[i];
195 BOOL set_netbios_aliases(const char **str_array)
199 /* Work out the max number of netbios aliases that we have */
200 for( namecount=0; str_array && (str_array[namecount] != NULL); namecount++ )
203 if ( global_myname() && *global_myname())
206 /* Allocate space for the netbios aliases */
207 if (!allocate_my_netbios_names_array(namecount))
210 /* Use the global_myname string first */
212 if ( global_myname() && *global_myname()) {
213 set_my_netbios_names( global_myname(), namecount );
219 for ( i = 0; str_array[i] != NULL; i++) {
221 BOOL duplicate = False;
223 /* Look for duplicates */
224 for( n=0; n<namecount; n++ ) {
225 if( strequal( str_array[i], my_netbios_names(n) ) ) {
231 if (!set_my_netbios_names(str_array[i], namecount))
240 /****************************************************************************
241 Common name initialization code.
242 ****************************************************************************/
244 BOOL init_names(void)
246 extern fstring local_machine;
250 if (global_myname() == NULL || *global_myname() == '\0') {
253 fstrcpy( name, myhostname() );
254 p = strchr( name, '.' );
257 if (!set_global_myname(name)) {
258 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
263 if (!set_netbios_aliases(lp_netbios_aliases())) {
264 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
268 fstrcpy( local_machine, global_myname() );
269 trim_string( local_machine, " ", " " );
270 p = strchr( local_machine, ' ' );
273 strlower( local_machine );
275 DEBUG( 5, ("Netbios name list:-\n") );
276 for( n=0; my_netbios_names(n); n++ )
277 DEBUGADD( 5, ( "my_netbios_names[%d]=\"%s\"\n", n, my_netbios_names(n) ) );
282 /**************************************************************************n
283 Find a suitable temporary directory. The result should be copied immediately
284 as it may be overwritten by a subsequent call.
285 ****************************************************************************/
287 const char *tmpdir(void)
290 if ((p = getenv("TMPDIR")))
295 /****************************************************************************
296 Determine whether we are in the specified group.
297 ****************************************************************************/
299 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, const gid_t *groups)
303 if (group == current_gid)
306 for (i=0;i<ngroups;i++)
307 if (group == groups[i])
313 /****************************************************************************
314 Like atoi but gets the value up to the separator character.
315 ****************************************************************************/
317 static char *Atoic(char *p, int *n, char *c)
319 if (!isdigit((int)*p)) {
320 DEBUG(5, ("Atoic: malformed number\n"));
326 while ((*p) && isdigit((int)*p))
329 if (strchr_m(c, *p) == NULL) {
330 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
337 /*************************************************************************
338 Reads a list of numbers.
339 *************************************************************************/
341 char *get_numlist(char *p, uint32 **num, int *count)
345 if (num == NULL || count == NULL)
351 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
354 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
360 (*num)[(*count)] = val;
368 /*******************************************************************
369 Check if a file exists - call vfs_file_exist for samba files.
370 ********************************************************************/
372 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
378 if (sys_stat(fname,sbuf) != 0)
381 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
384 /*******************************************************************
385 Check a files mod time.
386 ********************************************************************/
388 time_t file_modtime(const char *fname)
392 if (sys_stat(fname,&st) != 0)
398 /*******************************************************************
399 Check if a directory exists.
400 ********************************************************************/
402 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
410 if (sys_stat(dname,st) != 0)
413 ret = S_ISDIR(st->st_mode);
419 /*******************************************************************
420 Returns the size in bytes of the named file.
421 ********************************************************************/
423 SMB_OFF_T get_file_size(char *file_name)
427 if(sys_stat(file_name,&buf) != 0)
428 return (SMB_OFF_T)-1;
432 /*******************************************************************
433 Return a string representing an attribute for a file.
434 ********************************************************************/
436 char *attrib_string(uint16 mode)
438 static fstring attrstr;
442 if (mode & aVOLID) fstrcat(attrstr,"V");
443 if (mode & aDIR) fstrcat(attrstr,"D");
444 if (mode & aARCH) fstrcat(attrstr,"A");
445 if (mode & aHIDDEN) fstrcat(attrstr,"H");
446 if (mode & aSYSTEM) fstrcat(attrstr,"S");
447 if (mode & aRONLY) fstrcat(attrstr,"R");
452 /*******************************************************************
453 Show a smb message structure.
454 ********************************************************************/
456 void show_msg(char *buf)
464 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
466 (int)CVAL(buf,smb_com),
467 (int)CVAL(buf,smb_rcls),
468 (int)CVAL(buf,smb_reh),
469 (int)SVAL(buf,smb_err),
470 (int)CVAL(buf,smb_flg),
471 (int)SVAL(buf,smb_flg2)));
472 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
473 (int)SVAL(buf,smb_tid),
474 (int)SVAL(buf,smb_pid),
475 (int)SVAL(buf,smb_uid),
476 (int)SVAL(buf,smb_mid)));
477 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
479 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
480 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
481 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
483 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
485 DEBUGADD(5,("smb_bcc=%d\n",bcc));
493 dump_data(10, smb_buf(buf), bcc);
496 /*******************************************************************
497 Set the length and marker of an smb packet.
498 ********************************************************************/
500 void smb_setlen(char *buf,int len)
502 _smb_setlen(buf,len);
510 /*******************************************************************
511 Setup the word count and byte count for a smb message.
512 ********************************************************************/
514 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
517 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
518 SCVAL(buf,smb_wct,num_words);
519 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
520 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
521 return (smb_size + num_words*2 + num_bytes);
524 /*******************************************************************
525 Setup only the byte count for a smb message.
526 ********************************************************************/
528 int set_message_bcc(char *buf,int num_bytes)
530 int num_words = CVAL(buf,smb_wct);
531 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
532 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
533 return (smb_size + num_words*2 + num_bytes);
536 /*******************************************************************
537 Setup only the byte count for a smb message, using the end of the
539 ********************************************************************/
541 int set_message_end(void *outbuf,void *end_ptr)
543 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
546 /*******************************************************************
547 Reduce a file name, removing .. elements.
548 ********************************************************************/
550 void dos_clean_name(char *s)
554 DEBUG(3,("dos_clean_name [%s]\n",s));
556 /* remove any double slashes */
557 all_string_sub(s, "\\\\", "\\", 0);
559 while ((p = strstr(s,"\\..\\")) != NULL) {
565 if ((p=strrchr_m(s,'\\')) != NULL)
572 trim_string(s,NULL,"\\..");
574 all_string_sub(s, "\\.\\", "\\", 0);
577 /*******************************************************************
578 Reduce a file name, removing .. elements.
579 ********************************************************************/
581 void unix_clean_name(char *s)
585 DEBUG(3,("unix_clean_name [%s]\n",s));
587 /* remove any double slashes */
588 all_string_sub(s, "//","/", 0);
590 /* Remove leading ./ characters */
591 if(strncmp(s, "./", 2) == 0) {
592 trim_string(s, "./", NULL);
597 while ((p = strstr(s,"/../")) != NULL) {
603 if ((p=strrchr_m(s,'/')) != NULL)
610 trim_string(s,NULL,"/..");
613 /*******************************************************************
615 Reduce a file name, removing or reducing /../ , /./ , // elements.
616 Remove also any trailing . and /
617 Return a new allocated string.
618 ********************************************************************/
620 smb_ucs2_t *unix_clean_path(const smb_ucs2_t *s)
623 smb_ucs2_t *p, *r, *t;
625 DEBUG(3, ("unix_clean_path\n")); /* [%unicode]\n")); */
629 /* convert '\' to '/' */
635 /* remove all double slashes */
637 ns = all_string_sub_wa(p, "//", "/");
644 ns = all_string_sub_wa(p, "/./", "/");
649 /* reduce any /../ */
651 while (*t && (r = strstr_wa(t, "/.."))) {
653 if (*t == UCS2_CHAR('/') || *t == 0) {
655 p = strrchr_w(ns, UCS2_CHAR('/'));
661 memmove(p, t, (strlen_w(t) + 1) * sizeof(smb_ucs2_t));
666 /* remove any leading ./ trailing /. */
667 trim_string_wa(ns, "./", "/.");
669 /* remove any leading and trailing / */
670 trim_string_wa(ns, "/", "/");
675 /****************************************************************************
677 ****************************************************************************/
679 void make_dir_struct(char *buf,char *mask,char *fname,SMB_OFF_T size,int mode,time_t date)
686 if ((mode & aDIR) != 0)
689 memset(buf+1,' ',11);
690 if ((p = strchr_m(mask2,'.')) != NULL) {
692 push_ascii(buf+1,mask2,8, 0);
693 push_ascii(buf+9,p+1,3, 0);
696 push_ascii(buf+1,mask2,11, 0);
698 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
700 put_dos_date(buf,22,date);
701 SSVAL(buf,26,size & 0xFFFF);
702 SSVAL(buf,28,(size >> 16)&0xFFFF);
703 push_ascii(buf+30,fname,12, case_sensitive ? 0 : STR_UPPER);
704 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
707 /*******************************************************************
708 Close the low 3 fd's and open dev/null in their place.
709 ********************************************************************/
711 void close_low_fds(BOOL stderr_too)
723 /* try and use up these file descriptors, so silly
724 library routines writing to stdout etc won't cause havoc */
726 if (i == 2 && !stderr_too)
729 fd = sys_open("/dev/null",O_RDWR,0);
731 fd = sys_open("/dev/null",O_WRONLY,0);
733 DEBUG(0,("Can't open /dev/null\n"));
737 DEBUG(0,("Didn't get file descriptor %d\n",i));
744 /****************************************************************************
745 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
749 ****************************************************************************/
751 int set_blocking(int fd, BOOL set)
755 #define FLAG_TO_SET O_NONBLOCK
758 #define FLAG_TO_SET O_NDELAY
760 #define FLAG_TO_SET FNDELAY
764 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
766 if(set) /* Turn blocking on - ie. clear nonblock flag */
770 return sys_fcntl_long( fd, F_SETFL, val);
774 /****************************************************************************
775 Transfer some data between two fd's.
776 ****************************************************************************/
778 #ifndef TRANSFER_BUF_SIZE
779 #define TRANSFER_BUF_SIZE 65536
782 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
783 ssize_t (*write_fn)(int, const void *, size_t))
789 size_t num_to_read_thistime;
790 size_t num_written = 0;
792 if ((buf = malloc(TRANSFER_BUF_SIZE)) == NULL)
796 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
798 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
799 if (read_ret == -1) {
800 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
809 while (num_written < read_ret) {
810 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
812 if (write_ret == -1) {
813 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
818 return (ssize_t)total;
820 num_written += (size_t)write_ret;
823 total += (size_t)read_ret;
827 return (ssize_t)total;
830 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
832 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
835 /*******************************************************************
836 Sleep for a specified number of milliseconds.
837 ********************************************************************/
839 void msleep(unsigned int t)
841 unsigned int tdiff=0;
842 struct timeval tval,t1,t2;
849 tval.tv_sec = (t-tdiff)/1000;
850 tval.tv_usec = 1000*((t-tdiff)%1000);
852 /* Never wait for more than 1 sec. */
853 if (tval.tv_sec > 1) {
860 sys_select_intr(0,&fds,NULL,NULL,&tval);
863 if (t2.tv_sec < t1.tv_sec) {
864 /* Someone adjusted time... */
868 tdiff = TvalDiff(&t1,&t2);
872 /****************************************************************************
873 Become a daemon, discarding the controlling terminal.
874 ****************************************************************************/
876 void become_daemon(void)
881 /* detach from the terminal */
884 #elif defined(TIOCNOTTY)
886 int i = sys_open("/dev/tty", O_RDWR, 0);
888 ioctl(i, (int) TIOCNOTTY, (char *)0);
892 #endif /* HAVE_SETSID */
894 /* Close fd's 0,1,2. Needed if started by rsh */
895 close_low_fds(False); /* Don't close stderr, let the debug system
896 attach it to the logfile */
899 /****************************************************************************
900 Put up a yes/no prompt.
901 ****************************************************************************/
908 if (!fgets(ans,sizeof(ans)-1,stdin))
911 if (*ans == 'y' || *ans == 'Y')
917 /****************************************************************************
918 Expand a pointer to be a particular size.
919 ****************************************************************************/
921 void *Realloc(void *p,size_t size)
927 DEBUG(5,("Realloc asked for 0 bytes\n"));
932 ret = (void *)malloc(size);
934 ret = (void *)realloc(p,size);
937 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
942 /****************************************************************************
943 Free memory, checks for NULL.
944 Use directly SAFE_FREE()
945 Exists only because we need to pass a function pointer somewhere --SSS
946 ****************************************************************************/
948 void safe_free(void *p)
953 /****************************************************************************
954 Get my own name and IP.
955 ****************************************************************************/
957 BOOL get_myname(char *my_name)
963 /* get my host name */
964 if (gethostname(hostname, sizeof(hostname)) == -1) {
965 DEBUG(0,("gethostname failed\n"));
969 /* Ensure null termination. */
970 hostname[sizeof(hostname)-1] = '\0';
973 /* split off any parts after an initial . */
974 char *p = strchr_m(hostname,'.');
979 fstrcpy(my_name,hostname);
985 /****************************************************************************
986 Get my own name, including domain.
987 ****************************************************************************/
989 BOOL get_myfullname(char *my_name)
995 /* get my host name */
996 if (gethostname(hostname, sizeof(hostname)) == -1) {
997 DEBUG(0,("gethostname failed\n"));
1001 /* Ensure null termination. */
1002 hostname[sizeof(hostname)-1] = '\0';
1005 fstrcpy(my_name, hostname);
1009 /****************************************************************************
1010 Get my own domain name.
1011 ****************************************************************************/
1013 BOOL get_mydomname(char *my_domname)
1019 /* get my host name */
1020 if (gethostname(hostname, sizeof(hostname)) == -1) {
1021 DEBUG(0,("gethostname failed\n"));
1025 /* Ensure null termination. */
1026 hostname[sizeof(hostname)-1] = '\0';
1028 p = strchr_m(hostname, '.');
1036 fstrcpy(my_domname, p);
1041 /****************************************************************************
1042 Interpret a protocol description string, with a default.
1043 ****************************************************************************/
1045 int interpret_protocol(char *str,int def)
1047 if (strequal(str,"NT1"))
1048 return(PROTOCOL_NT1);
1049 if (strequal(str,"LANMAN2"))
1050 return(PROTOCOL_LANMAN2);
1051 if (strequal(str,"LANMAN1"))
1052 return(PROTOCOL_LANMAN1);
1053 if (strequal(str,"CORE"))
1054 return(PROTOCOL_CORE);
1055 if (strequal(str,"COREPLUS"))
1056 return(PROTOCOL_COREPLUS);
1057 if (strequal(str,"CORE+"))
1058 return(PROTOCOL_COREPLUS);
1060 DEBUG(0,("Unrecognised protocol level %s\n",str));
1065 /****************************************************************************
1066 Return true if a string could be a pure IP address.
1067 ****************************************************************************/
1069 BOOL is_ipaddress(const char *str)
1071 BOOL pure_address = True;
1074 for (i=0; pure_address && str[i]; i++)
1075 if (!(isdigit((int)str[i]) || str[i] == '.'))
1076 pure_address = False;
1078 /* Check that a pure number is not misinterpreted as an IP */
1079 pure_address = pure_address && (strchr_m(str, '.') != NULL);
1081 return pure_address;
1084 /****************************************************************************
1085 Interpret an internet address or name into an IP address in 4 byte form.
1086 ****************************************************************************/
1088 uint32 interpret_addr(const char *str)
1093 if (strcmp(str,"0.0.0.0") == 0)
1095 if (strcmp(str,"255.255.255.255") == 0)
1098 /* if it's in the form of an IP address then get the lib to interpret it */
1099 if (is_ipaddress(str)) {
1100 res = inet_addr(str);
1102 /* otherwise assume it's a network name of some sort and use
1103 sys_gethostbyname */
1104 if ((hp = sys_gethostbyname(str)) == 0) {
1105 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
1109 if(hp->h_addr == NULL) {
1110 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
1113 putip((char *)&res,(char *)hp->h_addr);
1116 if (res == (uint32)-1)
1122 /*******************************************************************
1123 A convenient addition to interpret_addr().
1124 ******************************************************************/
1126 struct in_addr *interpret_addr2(const char *str)
1128 static struct in_addr ret;
1129 uint32 a = interpret_addr(str);
1134 /*******************************************************************
1135 Check if an IP is the 0.0.0.0.
1136 ******************************************************************/
1138 BOOL is_zero_ip(struct in_addr ip)
1141 putip((char *)&a,(char *)&ip);
1145 /*******************************************************************
1146 Set an IP to 0.0.0.0.
1147 ******************************************************************/
1149 void zero_ip(struct in_addr *ip)
1152 static struct in_addr ipzero;
1155 ipzero = *interpret_addr2("0.0.0.0");
1162 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1163 /******************************************************************
1164 Remove any mount options such as -rsize=2048,wsize=2048 etc.
1165 Based on a fix from <Thomas.Hepper@icem.de>.
1166 *******************************************************************/
1168 static void strip_mount_options( pstring *str)
1172 while(*p && !isspace(*p))
1174 while(*p && isspace(*p))
1179 pstrcpy(tmp_str, p);
1180 pstrcpy(*str, tmp_str);
1185 /*******************************************************************
1186 Patch from jkf@soton.ac.uk
1187 Split Luke's automount_server into YP lookup and string splitter
1188 so can easily implement automount_path().
1189 As we may end up doing both, cache the last YP result.
1190 *******************************************************************/
1192 #ifdef WITH_NISPLUS_HOME
1193 char *automount_lookup(const char *user_name)
1195 static fstring last_key = "";
1196 static pstring last_value = "";
1198 char *nis_map = (char *)lp_nis_home_map_name();
1200 char buffer[NIS_MAXATTRVAL + 1];
1205 if (strcmp(user_name, last_key)) {
1206 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
1207 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
1209 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
1210 if (result->status != NIS_SUCCESS) {
1211 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
1212 fstrcpy(last_key, ""); pstrcpy(last_value, "");
1214 object = result->objects.objects_val;
1215 if (object->zo_data.zo_type == ENTRY_OBJ) {
1216 entry = &object->zo_data.objdata_u.en_data;
1217 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
1218 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
1220 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
1221 pstring_sub(last_value, "&", user_name);
1222 fstrcpy(last_key, user_name);
1226 nis_freeresult(result);
1229 strip_mount_options(&last_value);
1231 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
1234 #else /* WITH_NISPLUS_HOME */
1236 char *automount_lookup(const char *user_name)
1238 static fstring last_key = "";
1239 static pstring last_value = "";
1241 int nis_error; /* returned by yp all functions */
1242 char *nis_result; /* yp_match inits this */
1243 int nis_result_len; /* and set this */
1244 char *nis_domain; /* yp_get_default_domain inits this */
1245 char *nis_map = (char *)lp_nis_home_map_name();
1247 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
1248 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
1252 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
1254 if (!strcmp(user_name, last_key)) {
1255 nis_result = last_value;
1256 nis_result_len = strlen(last_value);
1259 if ((nis_error = yp_match(nis_domain, nis_map, user_name, strlen(user_name),
1260 &nis_result, &nis_result_len)) == 0) {
1261 if (!nis_error && nis_result_len >= sizeof(pstring)) {
1262 nis_result_len = sizeof(pstring)-1;
1264 fstrcpy(last_key, user_name);
1265 strncpy(last_value, nis_result, nis_result_len);
1266 last_value[nis_result_len] = '\0';
1267 strip_mount_options(&last_value);
1269 } else if(nis_error == YPERR_KEY) {
1271 /* If Key lookup fails user home server is not in nis_map
1272 use default information for server, and home directory */
1274 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1275 user_name, nis_map));
1276 DEBUG(3, ("using defaults for server and home directory\n"));
1278 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1279 yperr_string(nis_error), user_name, nis_map));
1283 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1286 #endif /* WITH_NISPLUS_HOME */
1289 /*******************************************************************
1290 Are two IPs on the same subnet?
1291 ********************************************************************/
1293 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1295 uint32 net1,net2,nmask;
1297 nmask = ntohl(mask.s_addr);
1298 net1 = ntohl(ip1.s_addr);
1299 net2 = ntohl(ip2.s_addr);
1301 return((net1 & nmask) == (net2 & nmask));
1305 /****************************************************************************
1306 Check if a process exists. Does this work on all unixes?
1307 ****************************************************************************/
1309 BOOL process_exists(pid_t pid)
1311 /* Doing kill with a non-positive pid causes messages to be
1312 * sent to places we don't want. */
1313 SMB_ASSERT(pid > 0);
1314 return(kill(pid,0) == 0 || errno != ESRCH);
1317 /*******************************************************************
1318 Convert a uid into a user name.
1319 ********************************************************************/
1321 const char *uidtoname(uid_t uid)
1323 static fstring name;
1324 struct passwd *pass;
1326 pass = getpwuid_alloc(uid);
1328 fstrcpy(name, pass->pw_name);
1331 slprintf(name, sizeof(name) - 1, "%ld",(long int)uid);
1337 /*******************************************************************
1338 Convert a gid into a group name.
1339 ********************************************************************/
1341 char *gidtoname(gid_t gid)
1343 static fstring name;
1346 grp = getgrgid(gid);
1348 return(grp->gr_name);
1349 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1353 /*******************************************************************
1354 Convert a user name into a uid.
1355 ********************************************************************/
1357 uid_t nametouid(char *name)
1359 struct passwd *pass;
1363 pass = getpwnam_alloc(name);
1370 u = (uid_t)strtol(name, &p, 0);
1371 if ((p != name) && (*p == '\0'))
1377 /*******************************************************************
1378 Convert a name to a gid_t if possible. Return -1 if not a group.
1379 ********************************************************************/
1381 gid_t nametogid(const char *name)
1387 g = (gid_t)strtol(name, &p, 0);
1388 if ((p != name) && (*p == '\0'))
1391 grp = sys_getgrnam(name);
1393 return(grp->gr_gid);
1397 /*******************************************************************
1398 Something really nasty happened - panic !
1399 ********************************************************************/
1401 void smb_panic(char *why)
1403 char *cmd = lp_panic_action();
1407 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
1408 result = system(cmd);
1411 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
1414 DEBUG(0, ("smb_panic(): action returned status %d\n",
1415 WEXITSTATUS(result)));
1417 DEBUG(0,("PANIC: %s\n", why));
1422 /*******************************************************************
1423 A readdir wrapper which just returns the file name.
1424 ********************************************************************/
1426 char *readdirname(DIR *p)
1428 SMB_STRUCT_DIRENT *ptr;
1434 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1438 dname = ptr->d_name;
1445 #ifdef HAVE_BROKEN_READDIR
1446 /* using /usr/ucb/cc is BAD */
1452 int len = NAMLEN(ptr);
1453 memcpy(buf, dname, len);
1461 /*******************************************************************
1462 Utility function used to decide if the last component
1463 of a path matches a (possibly wildcarded) entry in a namelist.
1464 ********************************************************************/
1466 BOOL is_in_path(char *name, name_compare_entry *namelist)
1468 pstring last_component;
1471 DEBUG(8, ("is_in_path: %s\n", name));
1473 /* if we have no list it's obviously not in the path */
1474 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
1475 DEBUG(8,("is_in_path: no name list.\n"));
1479 /* Get the last component of the unix name. */
1480 p = strrchr_m(name, '/');
1481 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1482 last_component[sizeof(last_component)-1] = '\0';
1484 for(; namelist->name != NULL; namelist++) {
1485 if(namelist->is_wild) {
1486 if (mask_match(last_component, namelist->name, case_sensitive)) {
1487 DEBUG(8,("is_in_path: mask match succeeded\n"));
1491 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1492 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0))) {
1493 DEBUG(8,("is_in_path: match succeeded\n"));
1498 DEBUG(8,("is_in_path: match not found\n"));
1503 /*******************************************************************
1504 Strip a '/' separated list into an array of
1505 name_compare_enties structures suitable for
1506 passing to is_in_path(). We do this for
1507 speed so we can pre-parse all the names in the list
1508 and don't do it for each call to is_in_path().
1509 namelist is modified here and is assumed to be
1510 a copy owned by the caller.
1511 We also check if the entry contains a wildcard to
1512 remove a potentially expensive call to mask_match
1514 ********************************************************************/
1516 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1519 char *nameptr = namelist;
1520 int num_entries = 0;
1523 (*ppname_array) = NULL;
1525 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1528 /* We need to make two passes over the string. The
1529 first to count the number of elements, the second
1534 if ( *nameptr == '/' ) {
1535 /* cope with multiple (useless) /s) */
1539 /* find the next / */
1540 name_end = strchr_m(nameptr, '/');
1542 /* oops - the last check for a / didn't find one. */
1543 if (name_end == NULL)
1546 /* next segment please */
1547 nameptr = name_end + 1;
1551 if(num_entries == 0)
1554 if(( (*ppname_array) = (name_compare_entry *)malloc(
1555 (num_entries + 1) * sizeof(name_compare_entry))) == NULL) {
1556 DEBUG(0,("set_namearray: malloc fail\n"));
1560 /* Now copy out the names */
1564 if ( *nameptr == '/' ) {
1565 /* cope with multiple (useless) /s) */
1569 /* find the next / */
1570 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1573 /* oops - the last check for a / didn't find one. */
1574 if(name_end == NULL)
1577 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1578 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL) {
1579 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1583 /* next segment please */
1584 nameptr = name_end + 1;
1588 (*ppname_array)[i].name = NULL;
1593 /****************************************************************************
1594 Routine to free a namearray.
1595 ****************************************************************************/
1597 void free_namearray(name_compare_entry *name_array)
1599 if(name_array == NULL)
1602 SAFE_FREE(name_array->name);
1603 SAFE_FREE(name_array);
1606 /****************************************************************************
1607 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1608 is dealt with in posix.c
1609 ****************************************************************************/
1611 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1613 SMB_STRUCT_FLOCK lock;
1616 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1619 lock.l_whence = SEEK_SET;
1620 lock.l_start = offset;
1624 ret = sys_fcntl_ptr(fd,op,&lock);
1626 if (ret == -1 && errno != 0)
1627 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1630 if (op == SMB_F_GETLK) {
1632 (lock.l_type != F_UNLCK) &&
1633 (lock.l_pid != 0) &&
1634 (lock.l_pid != sys_getpid())) {
1635 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1639 /* it must be not locked or locked by me */
1643 /* a lock set or unset */
1645 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1646 (double)offset,(double)count,op,type,strerror(errno)));
1650 /* everything went OK */
1651 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1656 /*******************************************************************
1657 Is the name specified one of my netbios names.
1658 Returns true if it is equal, false otherwise.
1659 ********************************************************************/
1661 BOOL is_myname(const char *s)
1666 for (n=0; my_netbios_names(n); n++) {
1667 if (strequal(my_netbios_names(n), s)) {
1672 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1676 /********************************************************************
1677 Return only the first IP address of our configured interfaces
1679 *******************************************************************/
1681 const char* get_my_primary_ip (void)
1683 static fstring ip_string;
1685 struct iface_struct nics[MAX_INTERFACES];
1687 if ((n=get_interfaces(nics, MAX_INTERFACES)) <= 0)
1690 fstrcpy(ip_string, inet_ntoa(nics[0].ip));
1694 BOOL is_myname_or_ipaddr(const char *s)
1696 /* optimize for the common case */
1697 if (strequal(s, global_myname()))
1700 /* maybe its an IP address? */
1701 if (is_ipaddress(s)) {
1702 struct iface_struct nics[MAX_INTERFACES];
1706 ip = interpret_addr(s);
1707 if ((ip==0) || (ip==0xffffffff))
1710 n = get_interfaces(nics, MAX_INTERFACES);
1711 for (i=0; i<n; i++) {
1712 if (ip == nics[i].ip.s_addr)
1717 /* check for an alias */
1725 /*******************************************************************
1726 Set the horrid remote_arch string based on an enum.
1727 ********************************************************************/
1729 void set_remote_arch(enum remote_arch_types type)
1731 extern fstring remote_arch;
1735 fstrcpy(remote_arch, "WfWg");
1738 fstrcpy(remote_arch, "OS2");
1741 fstrcpy(remote_arch, "Win95");
1744 fstrcpy(remote_arch, "WinNT");
1747 fstrcpy(remote_arch, "Win2K");
1750 fstrcpy(remote_arch,"Samba");
1753 ra_type = RA_UNKNOWN;
1754 fstrcpy(remote_arch, "UNKNOWN");
1759 /*******************************************************************
1760 Get the remote_arch type.
1761 ********************************************************************/
1763 enum remote_arch_types get_remote_arch(void)
1769 void out_ascii(FILE *f, unsigned char *buf,int len)
1773 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1776 void out_data(FILE *f,char *buf1,int len, int per_line)
1778 unsigned char *buf = (unsigned char *)buf1;
1784 fprintf(f, "[%03X] ",i);
1786 fprintf(f, "%02X ",(int)buf[i]);
1788 if (i%(per_line/2) == 0) fprintf(f, " ");
1789 if (i%per_line == 0) {
1790 out_ascii(f,&buf[i-per_line ],per_line/2); fprintf(f, " ");
1791 out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1792 if (i<len) fprintf(f, "[%03X] ",i);
1795 if ((i%per_line) != 0) {
1798 n = per_line - (i%per_line);
1800 if (n>(per_line/2)) fprintf(f, " ");
1804 n = MIN(per_line/2,i%per_line);
1805 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1806 n = (i%per_line) - n;
1807 if (n>0) out_ascii(f,&buf[i-n],n);
1812 void print_asc(int level, const unsigned char *buf,int len)
1816 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1819 void dump_data(int level, const char *buf1,int len)
1821 const unsigned char *buf = (const unsigned char *)buf1;
1825 if (!DEBUGLVL(level)) return;
1827 DEBUGADD(level,("[%03X] ",i));
1829 DEBUGADD(level,("%02X ",(int)buf[i]));
1831 if (i%8 == 0) DEBUGADD(level,(" "));
1833 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
1834 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
1835 if (i<len) DEBUGADD(level,("[%03X] ",i));
1841 DEBUGADD(level,(" "));
1842 if (n>8) DEBUGADD(level,(" "));
1843 while (n--) DEBUGADD(level,(" "));
1845 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
1847 if (n>0) print_asc(level,&buf[i-n],n);
1848 DEBUGADD(level,("\n"));
1852 char *tab_depth(int depth)
1854 static pstring spaces;
1855 memset(spaces, ' ', depth * 4);
1856 spaces[depth * 4] = 0;
1860 /*****************************************************************************
1861 Provide a checksum on a string
1863 Input: s - the null-terminated character string for which the checksum
1866 Output: The checksum value calculated for s.
1867 *****************************************************************************/
1869 int str_checksum(const char *s)
1877 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1884 /*****************************************************************
1885 Zero a memory area then free it. Used to catch bugs faster.
1886 *****************************************************************/
1888 void zero_free(void *p, size_t size)
1894 /*****************************************************************
1895 Set our open file limit to a requested max and return the limit.
1896 *****************************************************************/
1898 int set_maxfiles(int requested_max)
1900 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1902 int saved_current_limit;
1904 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1905 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1908 return requested_max;
1912 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1913 * account for the extra fd we need
1914 * as well as the log files and standard
1915 * handles etc. Save the limit we want to set in case
1916 * we are running on an OS that doesn't support this limit (AIX)
1917 * which always returns RLIM_INFINITY for rlp.rlim_max.
1920 /* Try raising the hard (max) limit to the requested amount. */
1922 #if defined(RLIM_INFINITY)
1923 if (rlp.rlim_max != RLIM_INFINITY) {
1924 int orig_max = rlp.rlim_max;
1926 if ( rlp.rlim_max < requested_max )
1927 rlp.rlim_max = requested_max;
1929 /* This failing is not an error - many systems (Linux) don't
1930 support our default request of 10,000 open files. JRA. */
1932 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1933 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1934 (int)rlp.rlim_max, strerror(errno) ));
1936 /* Set failed - restore original value from get. */
1937 rlp.rlim_max = orig_max;
1942 /* Now try setting the soft (current) limit. */
1944 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1946 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1947 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1948 (int)rlp.rlim_cur, strerror(errno) ));
1950 return saved_current_limit;
1953 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1954 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1957 return saved_current_limit;
1960 #if defined(RLIM_INFINITY)
1961 if(rlp.rlim_cur == RLIM_INFINITY)
1962 return saved_current_limit;
1965 if((int)rlp.rlim_cur > saved_current_limit)
1966 return saved_current_limit;
1968 return rlp.rlim_cur;
1969 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1971 * No way to know - just guess...
1973 return requested_max;
1977 /*****************************************************************
1978 Splits out the start of the key (HKLM or HKU) and the rest of the key.
1979 *****************************************************************/
1981 BOOL reg_split_key(const char *full_keyname, uint32 *reg_type, char *key_name)
1985 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1990 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1992 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1993 (*reg_type) = HKEY_LOCAL_MACHINE;
1994 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1995 (*reg_type) = HKEY_USERS;
1997 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
2001 if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
2002 fstrcpy(key_name, tmp);
2006 DEBUG(10, ("reg_split_key: name %s\n", key_name));
2011 /*****************************************************************
2012 Possibly replace mkstemp if it is broken.
2013 *****************************************************************/
2015 int smb_mkstemp(char *template)
2017 #if HAVE_SECURE_MKSTEMP
2018 return mkstemp(template);
2020 /* have a reasonable go at emulating it. Hope that
2021 the system mktemp() isn't completly hopeless */
2022 char *p = mktemp(template);
2025 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
2029 /*****************************************************************
2030 malloc that aborts with smb_panic on fail or zero size.
2031 *****************************************************************/
2033 void *smb_xmalloc(size_t size)
2037 smb_panic("smb_xmalloc: called with zero size.\n");
2038 if ((p = malloc(size)) == NULL)
2039 smb_panic("smb_xmalloc: malloc fail.\n");
2044 Memdup with smb_panic on fail.
2047 void *smb_xmemdup(const void *p, size_t size)
2050 p2 = smb_xmalloc(size);
2051 memcpy(p2, p, size);
2056 strdup that aborts on malloc fail.
2059 char *smb_xstrdup(const char *s)
2061 char *s1 = strdup(s);
2063 smb_panic("smb_xstrdup: malloc fail\n");
2068 strndup that aborts on malloc fail.
2071 char *smb_xstrndup(const char *s, size_t n)
2073 char *s1 = strndup(s, n);
2075 smb_panic("smb_xstrndup: malloc fail\n");
2080 vasprintf that aborts on malloc fail
2083 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
2090 n = vasprintf(ptr, format, ap2);
2091 if (n == -1 || ! *ptr)
2092 smb_panic("smb_xvasprintf: out of memory");
2096 /*****************************************************************
2097 Like strdup but for memory.
2098 *****************************************************************/
2100 void *memdup(const void *p, size_t size)
2108 memcpy(p2, p, size);
2112 /*****************************************************************
2113 Get local hostname and cache result.
2114 *****************************************************************/
2116 char *myhostname(void)
2124 /*****************************************************************
2125 A useful function for returning a path in the Samba lock directory.
2126 *****************************************************************/
2128 char *lock_path(const char *name)
2130 static pstring fname;
2132 pstrcpy(fname,lp_lockdir());
2133 trim_string(fname,"","/");
2135 if (!directory_exist(fname,NULL))
2139 pstrcat(fname,name);
2144 /*****************************************************************
2145 A useful function for returning a path in the Samba pid directory.
2146 *****************************************************************/
2148 char *pid_path(const char *name)
2150 static pstring fname;
2152 pstrcpy(fname,lp_piddir());
2153 trim_string(fname,"","/");
2155 if (!directory_exist(fname,NULL))
2159 pstrcat(fname,name);
2165 * @brief Returns an absolute path to a file in the Samba lib directory.
2167 * @param name File to find, relative to LIBDIR.
2169 * @retval Pointer to a static #pstring containing the full path.
2172 char *lib_path(const char *name)
2174 static pstring fname;
2175 snprintf(fname, sizeof(fname), "%s/%s", dyn_LIBDIR, name);
2179 /*******************************************************************
2180 Given a filename - get its directory name
2181 NB: Returned in static storage. Caveats:
2182 o Not safe in thread environment.
2183 o Caller must not free.
2184 o If caller wishes to preserve, they should copy.
2185 ********************************************************************/
2187 char *parent_dirname(const char *path)
2189 static pstring dirpath;
2195 pstrcpy(dirpath, path);
2196 p = strrchr_m(dirpath, '/'); /* Find final '/', if any */
2198 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
2201 ++p; /* For root "/", leave "/" in place */
2208 /*******************************************************************
2209 Determine if a pattern contains any Microsoft wildcard characters.
2210 *******************************************************************/
2212 BOOL ms_has_wild(char *s)
2215 while ((c = *s++)) {
2228 BOOL ms_has_wild_w(const smb_ucs2_t *s)
2231 if (!s) return False;
2232 while ((c = *s++)) {
2234 case UCS2_CHAR('*'):
2235 case UCS2_CHAR('?'):
2236 case UCS2_CHAR('<'):
2237 case UCS2_CHAR('>'):
2238 case UCS2_CHAR('"'):
2245 /*******************************************************************
2246 A wrapper that handles case sensitivity and the special handling
2248 *******************************************************************/
2250 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
2254 if (strcmp(string,"..") == 0)
2256 if (strcmp(pattern,".") == 0)
2259 if (is_case_sensitive)
2260 return ms_fnmatch(pattern, string, Protocol) == 0;
2262 fstrcpy(p2, pattern);
2263 fstrcpy(s2, string);
2266 return ms_fnmatch(p2, s2, Protocol) == 0;
2269 /*********************************************************
2270 Recursive routine that is called by unix_wild_match.
2271 *********************************************************/
2273 static BOOL unix_do_match(char *regexp, char *str)
2277 for( p = regexp; *p && *str; ) {
2288 * Look for a character matching
2289 * the one after the '*'.
2293 return True; /* Automatic match */
2296 while(*str && (*p != *str))
2300 * Patch from weidel@multichart.de. In the case of the regexp
2301 * '*XX*' we want to ensure there are at least 2 'X' characters
2302 * in the string after the '*' for a match to be made.
2309 * Eat all the characters that match, but count how many there were.
2312 while(*str && (*p == *str)) {
2318 * Now check that if the regexp had n identical characters that
2319 * matchcount had at least that many matches.
2322 while ( *(p+1) && (*(p+1) == *p)) {
2327 if ( matchcount <= 0 )
2331 str--; /* We've eaten the match char after the '*' */
2333 if(unix_do_match(p, str))
2355 if (!*p && str[0] == '.' && str[1] == 0)
2358 if (!*str && *p == '?') {
2364 if(!*str && (*p == '*' && p[1] == '\0'))
2370 /*******************************************************************
2371 Simple case insensitive interface to a UNIX wildcard matcher.
2372 *******************************************************************/
2374 BOOL unix_wild_match(char *pattern, char *string)
2379 pstrcpy(p2, pattern);
2380 pstrcpy(s2, string);
2384 /* Remove any *? and ** from the pattern as they are meaningless */
2385 for(p = p2; *p; p++)
2386 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2387 pstrcpy( &p[1], &p[2]);
2389 if (strequal(p2,"*"))
2392 return unix_do_match(p2, s2) == 0;
2397 /*******************************************************************
2398 This routine is a trick to immediately catch errors when debugging
2399 with insure. A xterm with a gdb is popped up when insure catches
2400 a error. It is Linux specific.
2401 ********************************************************************/
2403 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2408 /* you can get /usr/bin/backtrace from
2409 http://samba.org/ftp/unpacked/junkcode/backtrace */
2410 pstring cmd = "/usr/bin/backtrace %d";
2412 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2413 pstring_sub(cmd, "%d", pidstr);
2417 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2418 fn = dlsym(h, "_Insure_trap_error");
2420 if (!h || h == _Insure_trap_error) {
2421 h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2422 fn = dlsym(h, "_Insure_trap_error");
2426 ret = fn(a1, a2, a3, a4, a5, a6);