"Fixing my FORTRAN". Ensure we always have some valid char converter for the
[tprouty/samba.git] / source / lib / util.c
1 /* 
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) Jim McDonough <jmcd@us.ibm.com> 2003
8    
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.
13    
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.
18    
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.
22 */
23
24 #include "includes.h"
25
26 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
27 #ifdef WITH_NISPLUS_HOME
28 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
29 /*
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.
35  */
36
37 #if defined(GROUP)
38 #undef GROUP
39 #endif
40
41 #if defined(GROUP_OBJ)
42 #undef GROUP_OBJ
43 #endif
44
45 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
46
47 #include <rpcsvc/nis.h>
48
49 #else /* !WITH_NISPLUS_HOME */
50
51 #include "rpcsvc/ypclnt.h"
52
53 #endif /* WITH_NISPLUS_HOME */
54 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
55
56 int Protocol = PROTOCOL_COREPLUS;
57
58 /* a default finfo structure to ensure all fields are sensible */
59 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
60
61 /* this is used by the chaining code */
62 int chain_size = 0;
63
64 int trans_num = 0;
65
66 /*
67    case handling on filenames 
68 */
69 int case_default = CASE_LOWER;
70
71 /* the following control case operations - they are put here so the
72    client can link easily */
73 BOOL case_sensitive;
74 BOOL case_preserve;
75 BOOL use_mangled_map = False;
76 BOOL short_case_preserve;
77 BOOL case_mangle;
78
79 static enum remote_arch_types ra_type = RA_UNKNOWN;
80 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;   
81
82 /***********************************************************************
83  Definitions for all names.
84 ***********************************************************************/
85
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;
91
92 /***********************************************************************
93  Allocate and set myname. Ensure upper case.
94 ***********************************************************************/
95
96 BOOL set_global_myname(const char *myname)
97 {
98         SAFE_FREE(smb_myname);
99         smb_myname = strdup(myname);
100         if (!smb_myname)
101                 return False;
102         strupper_m(smb_myname);
103         return True;
104 }
105
106 const char *global_myname(void)
107 {
108         return smb_myname;
109 }
110
111 /***********************************************************************
112  Allocate and set myworkgroup. Ensure upper case.
113 ***********************************************************************/
114
115 BOOL set_global_myworkgroup(const char *myworkgroup)
116 {
117         SAFE_FREE(smb_myworkgroup);
118         smb_myworkgroup = strdup(myworkgroup);
119         if (!smb_myworkgroup)
120                 return False;
121         strupper_m(smb_myworkgroup);
122         return True;
123 }
124
125 const char *lp_workgroup(void)
126 {
127         return smb_myworkgroup;
128 }
129
130 /***********************************************************************
131  Allocate and set scope. Ensure upper case.
132 ***********************************************************************/
133
134 BOOL set_global_scope(const char *scope)
135 {
136         SAFE_FREE(smb_scope);
137         smb_scope = strdup(scope);
138         if (!smb_scope)
139                 return False;
140         strupper_m(smb_scope);
141         return True;
142 }
143
144 /*********************************************************************
145  Ensure scope is never null string.
146 *********************************************************************/
147
148 const char *global_scope(void)
149 {
150         if (!smb_scope)
151                 set_global_scope("");
152         return smb_scope;
153 }
154
155 static void free_netbios_names_array(void)
156 {
157         int i;
158
159         for (i = 0; i < smb_num_netbios_names; i++)
160                 SAFE_FREE(smb_my_netbios_names[i]);
161
162         SAFE_FREE(smb_my_netbios_names);
163         smb_num_netbios_names = 0;
164 }
165
166 static BOOL allocate_my_netbios_names_array(size_t number)
167 {
168         free_netbios_names_array();
169
170         smb_num_netbios_names = number + 1;
171         smb_my_netbios_names = (char **)malloc( sizeof(char *) * smb_num_netbios_names );
172
173         if (!smb_my_netbios_names)
174                 return False;
175
176         memset(smb_my_netbios_names, '\0', sizeof(char *) * smb_num_netbios_names);
177         return True;
178 }
179
180 static BOOL set_my_netbios_names(const char *name, int i)
181 {
182         SAFE_FREE(smb_my_netbios_names[i]);
183
184         smb_my_netbios_names[i] = strdup(name);
185         if (!smb_my_netbios_names[i])
186                 return False;
187         strupper_m(smb_my_netbios_names[i]);
188         return True;
189 }
190
191 const char *my_netbios_names(int i)
192 {
193         return smb_my_netbios_names[i];
194 }
195
196 BOOL set_netbios_aliases(const char **str_array)
197 {
198         size_t namecount;
199
200         /* Work out the max number of netbios aliases that we have */
201         for( namecount=0; str_array && (str_array[namecount] != NULL); namecount++ )
202                 ;
203
204         if ( global_myname() && *global_myname())
205                 namecount++;
206
207         /* Allocate space for the netbios aliases */
208         if (!allocate_my_netbios_names_array(namecount))
209                 return False;
210
211         /* Use the global_myname string first */
212         namecount=0;
213         if ( global_myname() && *global_myname()) {
214                 set_my_netbios_names( global_myname(), namecount );
215                 namecount++;
216         }
217
218         if (str_array) {
219                 size_t i;
220                 for ( i = 0; str_array[i] != NULL; i++) {
221                         size_t n;
222                         BOOL duplicate = False;
223
224                         /* Look for duplicates */
225                         for( n=0; n<namecount; n++ ) {
226                                 if( strequal( str_array[i], my_netbios_names(n) ) ) {
227                                         duplicate = True;
228                                         break;
229                                 }
230                         }
231                         if (!duplicate) {
232                                 if (!set_my_netbios_names(str_array[i], namecount))
233                                         return False;
234                                 namecount++;
235                         }
236                 }
237         }
238         return True;
239 }
240
241 /****************************************************************************
242   Common name initialization code.
243 ****************************************************************************/
244
245 BOOL init_names(void)
246 {
247         extern fstring local_machine;
248         char *p;
249         int n;
250
251         if (global_myname() == NULL || *global_myname() == '\0') {
252                 if (!set_global_myname(myhostname())) {
253                         DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
254                         return False;
255                 }
256         }
257
258         if (!set_netbios_aliases(lp_netbios_aliases())) {
259                 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
260                 return False;
261         }                       
262
263         fstrcpy( local_machine, global_myname() );
264         trim_char( local_machine, ' ', ' ' );
265         p = strchr( local_machine, ' ' );
266         if (p)
267                 *p = 0;
268         strlower_m( local_machine );
269
270         DEBUG( 5, ("Netbios name list:-\n") );
271         for( n=0; my_netbios_names(n); n++ )
272                 DEBUGADD( 5, ( "my_netbios_names[%d]=\"%s\"\n", n, my_netbios_names(n) ) );
273
274         return( True );
275 }
276
277 /**************************************************************************n
278  Find a suitable temporary directory. The result should be copied immediately
279  as it may be overwritten by a subsequent call.
280 ****************************************************************************/
281
282 const char *tmpdir(void)
283 {
284         char *p;
285         if ((p = getenv("TMPDIR")))
286                 return p;
287         return "/tmp";
288 }
289
290 /****************************************************************************
291  Determine whether we are in the specified group.
292 ****************************************************************************/
293
294 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, const gid_t *groups)
295 {
296         int i;
297
298         if (group == current_gid)
299                 return(True);
300
301         for (i=0;i<ngroups;i++)
302                 if (group == groups[i])
303                         return(True);
304
305         return(False);
306 }
307
308 /****************************************************************************
309  Like atoi but gets the value up to the separator character.
310 ****************************************************************************/
311
312 static const char *Atoic(const char *p, int *n, const char *c)
313 {
314         if (!isdigit((int)*p)) {
315                 DEBUG(5, ("Atoic: malformed number\n"));
316                 return NULL;
317         }
318
319         (*n) = atoi(p);
320
321         while ((*p) && isdigit((int)*p))
322                 p++;
323
324         if (strchr_m(c, *p) == NULL) {
325                 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
326                 return NULL;
327         }
328
329         return p;
330 }
331
332 /*************************************************************************
333  Reads a list of numbers.
334  *************************************************************************/
335
336 const char *get_numlist(const char *p, uint32 **num, int *count)
337 {
338         int val;
339
340         if (num == NULL || count == NULL)
341                 return NULL;
342
343         (*count) = 0;
344         (*num  ) = NULL;
345
346         while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
347                 uint32 *tn;
348                 
349                 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
350                 if (tn == NULL) {
351                         SAFE_FREE(*num);
352                         return NULL;
353                 } else
354                         (*num) = tn;
355                 (*num)[(*count)] = val;
356                 (*count)++;
357                 p++;
358         }
359
360         return p;
361 }
362
363 /*******************************************************************
364  Check if a file exists - call vfs_file_exist for samba files.
365 ********************************************************************/
366
367 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
368 {
369         SMB_STRUCT_STAT st;
370         if (!sbuf)
371                 sbuf = &st;
372   
373         if (sys_stat(fname,sbuf) != 0) 
374                 return(False);
375
376         return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
377 }
378
379 /*******************************************************************
380  Check a files mod time.
381 ********************************************************************/
382
383 time_t file_modtime(const char *fname)
384 {
385         SMB_STRUCT_STAT st;
386   
387         if (sys_stat(fname,&st) != 0) 
388                 return(0);
389
390         return(st.st_mtime);
391 }
392
393 /*******************************************************************
394  Check if a directory exists.
395 ********************************************************************/
396
397 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
398 {
399         SMB_STRUCT_STAT st2;
400         BOOL ret;
401
402         if (!st)
403                 st = &st2;
404
405         if (sys_stat(dname,st) != 0) 
406                 return(False);
407
408         ret = S_ISDIR(st->st_mode);
409         if(!ret)
410                 errno = ENOTDIR;
411         return ret;
412 }
413
414 /*******************************************************************
415  Returns the size in bytes of the named file.
416 ********************************************************************/
417
418 SMB_OFF_T get_file_size(char *file_name)
419 {
420         SMB_STRUCT_STAT buf;
421         buf.st_size = 0;
422         if(sys_stat(file_name,&buf) != 0)
423                 return (SMB_OFF_T)-1;
424         return(buf.st_size);
425 }
426
427 /*******************************************************************
428  Return a string representing an attribute for a file.
429 ********************************************************************/
430
431 char *attrib_string(uint16 mode)
432 {
433         static fstring attrstr;
434
435         attrstr[0] = 0;
436
437         if (mode & aVOLID) fstrcat(attrstr,"V");
438         if (mode & aDIR) fstrcat(attrstr,"D");
439         if (mode & aARCH) fstrcat(attrstr,"A");
440         if (mode & aHIDDEN) fstrcat(attrstr,"H");
441         if (mode & aSYSTEM) fstrcat(attrstr,"S");
442         if (mode & aRONLY) fstrcat(attrstr,"R");          
443
444         return(attrstr);
445 }
446
447 /*******************************************************************
448  Show a smb message structure.
449 ********************************************************************/
450
451 void show_msg(char *buf)
452 {
453         int i;
454         int bcc=0;
455
456         if (!DEBUGLVL(5))
457                 return;
458         
459         DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
460                         smb_len(buf),
461                         (int)CVAL(buf,smb_com),
462                         (int)CVAL(buf,smb_rcls),
463                         (int)CVAL(buf,smb_reh),
464                         (int)SVAL(buf,smb_err),
465                         (int)CVAL(buf,smb_flg),
466                         (int)SVAL(buf,smb_flg2)));
467         DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
468                         (int)SVAL(buf,smb_tid),
469                         (int)SVAL(buf,smb_pid),
470                         (int)SVAL(buf,smb_uid),
471                         (int)SVAL(buf,smb_mid)));
472         DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
473
474         for (i=0;i<(int)CVAL(buf,smb_wct);i++)
475                 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
476                         SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
477         
478         bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
479
480         DEBUGADD(5,("smb_bcc=%d\n",bcc));
481
482         if (DEBUGLEVEL < 10)
483                 return;
484
485         if (DEBUGLEVEL < 50)
486                 bcc = MIN(bcc, 512);
487
488         dump_data(10, smb_buf(buf), bcc);       
489 }
490
491 /*******************************************************************
492  Set the length and marker of an smb packet.
493 ********************************************************************/
494
495 void smb_setlen(char *buf,int len)
496 {
497         _smb_setlen(buf,len);
498
499         SCVAL(buf,4,0xFF);
500         SCVAL(buf,5,'S');
501         SCVAL(buf,6,'M');
502         SCVAL(buf,7,'B');
503 }
504
505 /*******************************************************************
506  Setup the word count and byte count for a smb message.
507 ********************************************************************/
508
509 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
510 {
511         if (zero)
512                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
513         SCVAL(buf,smb_wct,num_words);
514         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
515         smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
516         return (smb_size + num_words*2 + num_bytes);
517 }
518
519 /*******************************************************************
520  Setup only the byte count for a smb message.
521 ********************************************************************/
522
523 int set_message_bcc(char *buf,int num_bytes)
524 {
525         int num_words = CVAL(buf,smb_wct);
526         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
527         smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
528         return (smb_size + num_words*2 + num_bytes);
529 }
530
531 /*******************************************************************
532  Setup only the byte count for a smb message, using the end of the
533  message as a marker.
534 ********************************************************************/
535
536 int set_message_end(void *outbuf,void *end_ptr)
537 {
538         return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
539 }
540
541 /*******************************************************************
542  Reduce a file name, removing .. elements.
543 ********************************************************************/
544
545 void dos_clean_name(char *s)
546 {
547         char *p=NULL;
548
549         DEBUG(3,("dos_clean_name [%s]\n",s));
550
551         /* remove any double slashes */
552         all_string_sub(s, "\\\\", "\\", 0);
553
554         while ((p = strstr_m(s,"\\..\\")) != NULL) {
555                 pstring s1;
556
557                 *p = 0;
558                 pstrcpy(s1,p+3);
559
560                 if ((p=strrchr_m(s,'\\')) != NULL)
561                         *p = 0;
562                 else
563                         *s = 0;
564                 pstrcat(s,s1);
565         }  
566
567         trim_string(s,NULL,"\\..");
568
569         all_string_sub(s, "\\.\\", "\\", 0);
570 }
571
572 /*******************************************************************
573  Reduce a file name, removing .. elements. 
574 ********************************************************************/
575
576 void unix_clean_name(char *s)
577 {
578         char *p=NULL;
579
580         DEBUG(3,("unix_clean_name [%s]\n",s));
581
582         /* remove any double slashes */
583         all_string_sub(s, "//","/", 0);
584
585         /* Remove leading ./ characters */
586         if(strncmp(s, "./", 2) == 0) {
587                 trim_string(s, "./", NULL);
588                 if(*s == 0)
589                         pstrcpy(s,"./");
590         }
591
592         while ((p = strstr_m(s,"/../")) != NULL) {
593                 pstring s1;
594
595                 *p = 0;
596                 pstrcpy(s1,p+3);
597
598                 if ((p=strrchr_m(s,'/')) != NULL)
599                         *p = 0;
600                 else
601                         *s = 0;
602                 pstrcat(s,s1);
603         }  
604
605         trim_string(s,NULL,"/..");
606 }
607
608 /****************************************************************************
609  Make a dir struct.
610 ****************************************************************************/
611
612 void make_dir_struct(char *buf, const char *mask, const char *fname,SMB_OFF_T size,int mode,time_t date)
613 {  
614         char *p;
615         pstring mask2;
616
617         pstrcpy(mask2,mask);
618
619         if ((mode & aDIR) != 0)
620                 size = 0;
621
622         memset(buf+1,' ',11);
623         if ((p = strchr_m(mask2,'.')) != NULL) {
624                 *p = 0;
625                 push_ascii(buf+1,mask2,8, 0);
626                 push_ascii(buf+9,p+1,3, 0);
627                 *p = '.';
628         } else
629                 push_ascii(buf+1,mask2,11, 0);
630
631         memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
632         SCVAL(buf,21,mode);
633         put_dos_date(buf,22,date);
634         SSVAL(buf,26,size & 0xFFFF);
635         SSVAL(buf,28,(size >> 16)&0xFFFF);
636         push_ascii(buf+30,fname,12, case_sensitive ? 0 : STR_UPPER);
637         DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
638 }
639
640 /*******************************************************************
641  Close the low 3 fd's and open dev/null in their place.
642 ********************************************************************/
643
644 void close_low_fds(BOOL stderr_too)
645 {
646 #ifndef VALGRIND
647         int fd;
648         int i;
649
650         close(0);
651         close(1); 
652
653         if (stderr_too)
654                 close(2);
655
656         /* try and use up these file descriptors, so silly
657                 library routines writing to stdout etc won't cause havoc */
658         for (i=0;i<3;i++) {
659                 if (i == 2 && !stderr_too)
660                         continue;
661
662                 fd = sys_open("/dev/null",O_RDWR,0);
663                 if (fd < 0)
664                         fd = sys_open("/dev/null",O_WRONLY,0);
665                 if (fd < 0) {
666                         DEBUG(0,("Can't open /dev/null\n"));
667                         return;
668                 }
669                 if (fd != i) {
670                         DEBUG(0,("Didn't get file descriptor %d\n",i));
671                         return;
672                 }
673         }
674 #endif
675 }
676
677 /****************************************************************************
678  Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
679  else
680   if SYSV use O_NDELAY
681   if BSD use FNDELAY
682 ****************************************************************************/
683
684 int set_blocking(int fd, BOOL set)
685 {
686         int val;
687 #ifdef O_NONBLOCK
688 #define FLAG_TO_SET O_NONBLOCK
689 #else
690 #ifdef SYSV
691 #define FLAG_TO_SET O_NDELAY
692 #else /* BSD */
693 #define FLAG_TO_SET FNDELAY
694 #endif
695 #endif
696
697         if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
698                 return -1;
699         if(set) /* Turn blocking on - ie. clear nonblock flag */
700                 val &= ~FLAG_TO_SET;
701         else
702                 val |= FLAG_TO_SET;
703         return sys_fcntl_long( fd, F_SETFL, val);
704 #undef FLAG_TO_SET
705 }
706
707 /****************************************************************************
708  Transfer some data between two fd's.
709 ****************************************************************************/
710
711 #ifndef TRANSFER_BUF_SIZE
712 #define TRANSFER_BUF_SIZE 65536
713 #endif
714
715 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
716                                                 ssize_t (*write_fn)(int, const void *, size_t))
717 {
718         char *buf;
719         size_t total = 0;
720         ssize_t read_ret;
721         ssize_t write_ret;
722         size_t num_to_read_thistime;
723         size_t num_written = 0;
724
725         if ((buf = malloc(TRANSFER_BUF_SIZE)) == NULL)
726                 return -1;
727
728         while (total < n) {
729                 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
730
731                 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
732                 if (read_ret == -1) {
733                         DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
734                         SAFE_FREE(buf);
735                         return -1;
736                 }
737                 if (read_ret == 0)
738                         break;
739
740                 num_written = 0;
741  
742                 while (num_written < read_ret) {
743                         write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
744  
745                         if (write_ret == -1) {
746                                 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
747                                 SAFE_FREE(buf);
748                                 return -1;
749                         }
750                         if (write_ret == 0)
751                                 return (ssize_t)total;
752  
753                         num_written += (size_t)write_ret;
754                 }
755
756                 total += (size_t)read_ret;
757         }
758
759         SAFE_FREE(buf);
760         return (ssize_t)total;          
761 }
762
763 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
764 {
765         return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
766 }
767
768 /*******************************************************************
769  Sleep for a specified number of milliseconds.
770 ********************************************************************/
771
772 void smb_msleep(unsigned int t)
773 {
774         unsigned int tdiff=0;
775         struct timeval tval,t1,t2;  
776         fd_set fds;
777
778         GetTimeOfDay(&t1);
779         GetTimeOfDay(&t2);
780   
781         while (tdiff < t) {
782                 tval.tv_sec = (t-tdiff)/1000;
783                 tval.tv_usec = 1000*((t-tdiff)%1000);
784
785                 /* Never wait for more than 1 sec. */
786                 if (tval.tv_sec > 1) {
787                         tval.tv_sec = 1; 
788                         tval.tv_usec = 0;
789                 }
790
791                 FD_ZERO(&fds);
792                 errno = 0;
793                 sys_select_intr(0,&fds,NULL,NULL,&tval);
794
795                 GetTimeOfDay(&t2);
796                 if (t2.tv_sec < t1.tv_sec) {
797                         /* Someone adjusted time... */
798                         t1 = t2;
799                 }
800
801                 tdiff = TvalDiff(&t1,&t2);
802         }
803 }
804
805 /****************************************************************************
806  Become a daemon, discarding the controlling terminal.
807 ****************************************************************************/
808
809 void become_daemon(BOOL Fork)
810 {
811         if (Fork) {
812                 if (sys_fork()) {
813                         _exit(0);
814                 }
815         }
816
817   /* detach from the terminal */
818 #ifdef HAVE_SETSID
819         setsid();
820 #elif defined(TIOCNOTTY)
821         {
822                 int i = sys_open("/dev/tty", O_RDWR, 0);
823                 if (i != -1) {
824                         ioctl(i, (int) TIOCNOTTY, (char *)0);      
825                         close(i);
826                 }
827         }
828 #endif /* HAVE_SETSID */
829
830         /* Close fd's 0,1,2. Needed if started by rsh */
831         close_low_fds(False);  /* Don't close stderr, let the debug system
832                                   attach it to the logfile */
833 }
834
835 /****************************************************************************
836  Put up a yes/no prompt.
837 ****************************************************************************/
838
839 BOOL yesno(char *p)
840 {
841         pstring ans;
842         printf("%s",p);
843
844         if (!fgets(ans,sizeof(ans)-1,stdin))
845                 return(False);
846
847         if (*ans == 'y' || *ans == 'Y')
848                 return(True);
849
850         return(False);
851 }
852
853 /****************************************************************************
854  Expand a pointer to be a particular size.
855 ****************************************************************************/
856
857 void *Realloc(void *p,size_t size)
858 {
859         void *ret=NULL;
860
861         if (size == 0) {
862                 SAFE_FREE(p);
863                 DEBUG(5,("Realloc asked for 0 bytes\n"));
864                 return NULL;
865         }
866
867         if (!p)
868                 ret = (void *)malloc(size);
869         else
870                 ret = (void *)realloc(p,size);
871
872         if (!ret)
873                 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
874
875         return(ret);
876 }
877
878 void *Realloc_zero(void *ptr, size_t size)
879 {
880         void *tptr = NULL;
881                 
882         tptr = Realloc(ptr, size);
883         if(tptr == NULL)
884                 return NULL;
885
886         memset((char *)tptr,'\0',size);
887
888         return tptr;
889 }
890
891 /****************************************************************************
892  Free memory, checks for NULL.
893  Use directly SAFE_FREE()
894  Exists only because we need to pass a function pointer somewhere --SSS
895 ****************************************************************************/
896
897 void safe_free(void *p)
898 {
899         SAFE_FREE(p);
900 }
901
902 /****************************************************************************
903  Get my own name and IP.
904 ****************************************************************************/
905
906 BOOL get_myname(char *my_name)
907 {
908         pstring hostname;
909
910         *hostname = 0;
911
912         /* get my host name */
913         if (gethostname(hostname, sizeof(hostname)) == -1) {
914                 DEBUG(0,("gethostname failed\n"));
915                 return False;
916         } 
917
918         /* Ensure null termination. */
919         hostname[sizeof(hostname)-1] = '\0';
920
921         if (my_name) {
922                 /* split off any parts after an initial . */
923                 char *p = strchr_m(hostname,'.');
924
925                 if (p)
926                         *p = 0;
927                 
928                 fstrcpy(my_name,hostname);
929         }
930         
931         return(True);
932 }
933
934 /****************************************************************************
935  Get my own canonical name, including domain.
936 ****************************************************************************/
937
938 BOOL get_mydnsfullname(fstring my_dnsname)
939 {
940         static fstring dnshostname;
941         struct hostent *hp;
942
943         if (!*dnshostname) {
944                 /* get my host name */
945                 if (gethostname(dnshostname, sizeof(dnshostname)) == -1) {
946                         *dnshostname = '\0';
947                         DEBUG(0,("gethostname failed\n"));
948                         return False;
949                 } 
950
951                 /* Ensure null termination. */
952                 dnshostname[sizeof(dnshostname)-1] = '\0';
953
954                 /* Ensure we get the cannonical name. */
955                 if (!(hp = sys_gethostbyname(dnshostname))) {
956                         *dnshostname = '\0';
957                         return False;
958                 }
959                 fstrcpy(dnshostname, hp->h_name);
960         }
961         fstrcpy(my_dnsname, dnshostname);
962         return True;
963 }
964
965 /****************************************************************************
966  Get my own domain name.
967 ****************************************************************************/
968
969 BOOL get_mydnsdomname(fstring my_domname)
970 {
971         fstring domname;
972         char *p;
973
974         *my_domname = '\0';
975         if (!get_mydnsfullname(domname)) {
976                 return False;
977         }       
978         p = strchr_m(domname, '.');
979         if (p) {
980                 p++;
981                 fstrcpy(my_domname, p);
982         }
983
984         return False;
985 }
986
987 /****************************************************************************
988  Interpret a protocol description string, with a default.
989 ****************************************************************************/
990
991 int interpret_protocol(const char *str,int def)
992 {
993         if (strequal(str,"NT1"))
994                 return(PROTOCOL_NT1);
995         if (strequal(str,"LANMAN2"))
996                 return(PROTOCOL_LANMAN2);
997         if (strequal(str,"LANMAN1"))
998                 return(PROTOCOL_LANMAN1);
999         if (strequal(str,"CORE"))
1000                 return(PROTOCOL_CORE);
1001         if (strequal(str,"COREPLUS"))
1002                 return(PROTOCOL_COREPLUS);
1003         if (strequal(str,"CORE+"))
1004                 return(PROTOCOL_COREPLUS);
1005   
1006         DEBUG(0,("Unrecognised protocol level %s\n",str));
1007   
1008         return(def);
1009 }
1010
1011 /****************************************************************************
1012  Return true if a string could be a pure IP address.
1013 ****************************************************************************/
1014
1015 BOOL is_ipaddress(const char *str)
1016 {
1017         BOOL pure_address = True;
1018         int i;
1019   
1020         for (i=0; pure_address && str[i]; i++)
1021                 if (!(isdigit((int)str[i]) || str[i] == '.'))
1022                         pure_address = False;
1023
1024         /* Check that a pure number is not misinterpreted as an IP */
1025         pure_address = pure_address && (strchr_m(str, '.') != NULL);
1026
1027         return pure_address;
1028 }
1029
1030 /****************************************************************************
1031  Interpret an internet address or name into an IP address in 4 byte form.
1032 ****************************************************************************/
1033
1034 uint32 interpret_addr(const char *str)
1035 {
1036         struct hostent *hp;
1037         uint32 res;
1038
1039         if (strcmp(str,"0.0.0.0") == 0)
1040                 return(0);
1041         if (strcmp(str,"255.255.255.255") == 0)
1042                 return(0xFFFFFFFF);
1043
1044   /* if it's in the form of an IP address then get the lib to interpret it */
1045         if (is_ipaddress(str)) {
1046                 res = inet_addr(str);
1047         } else {
1048                 /* otherwise assume it's a network name of some sort and use 
1049                         sys_gethostbyname */
1050                 if ((hp = sys_gethostbyname(str)) == 0) {
1051                         DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
1052                         return 0;
1053                 }
1054
1055                 if(hp->h_addr == NULL) {
1056                         DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
1057                         return 0;
1058                 }
1059                 putip((char *)&res,(char *)hp->h_addr);
1060         }
1061
1062         if (res == (uint32)-1)
1063                 return(0);
1064
1065         return(res);
1066 }
1067
1068 /*******************************************************************
1069  A convenient addition to interpret_addr().
1070 ******************************************************************/
1071
1072 struct in_addr *interpret_addr2(const char *str)
1073 {
1074         static struct in_addr ret;
1075         uint32 a = interpret_addr(str);
1076         ret.s_addr = a;
1077         return(&ret);
1078 }
1079
1080 /*******************************************************************
1081  Check if an IP is the 0.0.0.0.
1082 ******************************************************************/
1083
1084 BOOL is_zero_ip(struct in_addr ip)
1085 {
1086         uint32 a;
1087         putip((char *)&a,(char *)&ip);
1088         return(a == 0);
1089 }
1090
1091 /*******************************************************************
1092  Set an IP to 0.0.0.0.
1093 ******************************************************************/
1094
1095 void zero_ip(struct in_addr *ip)
1096 {
1097         static BOOL init;
1098         static struct in_addr ipzero;
1099
1100         if (!init) {
1101                 ipzero = *interpret_addr2("0.0.0.0");
1102                 init = True;
1103         }
1104
1105         *ip = ipzero;
1106 }
1107
1108 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1109 /******************************************************************
1110  Remove any mount options such as -rsize=2048,wsize=2048 etc.
1111  Based on a fix from <Thomas.Hepper@icem.de>.
1112 *******************************************************************/
1113
1114 static void strip_mount_options( pstring *str)
1115 {
1116         if (**str == '-') { 
1117                 char *p = *str;
1118                 while(*p && !isspace(*p))
1119                         p++;
1120                 while(*p && isspace(*p))
1121                         p++;
1122                 if(*p) {
1123                         pstring tmp_str;
1124
1125                         pstrcpy(tmp_str, p);
1126                         pstrcpy(*str, tmp_str);
1127                 }
1128         }
1129 }
1130
1131 /*******************************************************************
1132  Patch from jkf@soton.ac.uk
1133  Split Luke's automount_server into YP lookup and string splitter
1134  so can easily implement automount_path(). 
1135  As we may end up doing both, cache the last YP result. 
1136 *******************************************************************/
1137
1138 #ifdef WITH_NISPLUS_HOME
1139 char *automount_lookup(const char *user_name)
1140 {
1141         static fstring last_key = "";
1142         static pstring last_value = "";
1143  
1144         char *nis_map = (char *)lp_nis_home_map_name();
1145  
1146         char buffer[NIS_MAXATTRVAL + 1];
1147         nis_result *result;
1148         nis_object *object;
1149         entry_obj  *entry;
1150  
1151         if (strcmp(user_name, last_key)) {
1152                 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
1153                 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
1154  
1155                 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
1156                         if (result->status != NIS_SUCCESS) {
1157                                 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
1158                                 fstrcpy(last_key, ""); pstrcpy(last_value, "");
1159                         } else {
1160                                 object = result->objects.objects_val;
1161                                 if (object->zo_data.zo_type == ENTRY_OBJ) {
1162                                         entry = &object->zo_data.objdata_u.en_data;
1163                                         DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
1164                                         DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
1165  
1166                                         pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
1167                                         pstring_sub(last_value, "&", user_name);
1168                                         fstrcpy(last_key, user_name);
1169                                 }
1170                         }
1171                 }
1172                 nis_freeresult(result);
1173         }
1174
1175         strip_mount_options(&last_value);
1176
1177         DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
1178         return last_value;
1179 }
1180 #else /* WITH_NISPLUS_HOME */
1181
1182 char *automount_lookup(const char *user_name)
1183 {
1184         static fstring last_key = "";
1185         static pstring last_value = "";
1186
1187         int nis_error;        /* returned by yp all functions */
1188         char *nis_result;     /* yp_match inits this */
1189         int nis_result_len;  /* and set this */
1190         char *nis_domain;     /* yp_get_default_domain inits this */
1191         char *nis_map = (char *)lp_nis_home_map_name();
1192
1193         if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
1194                 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
1195                 return last_value;
1196         }
1197
1198         DEBUG(5, ("NIS Domain: %s\n", nis_domain));
1199
1200         if (!strcmp(user_name, last_key)) {
1201                 nis_result = last_value;
1202                 nis_result_len = strlen(last_value);
1203                 nis_error = 0;
1204         } else {
1205                 if ((nis_error = yp_match(nis_domain, nis_map, user_name, strlen(user_name),
1206                                 &nis_result, &nis_result_len)) == 0) {
1207                         if (!nis_error && nis_result_len >= sizeof(pstring)) {
1208                                 nis_result_len = sizeof(pstring)-1;
1209                         }
1210                         fstrcpy(last_key, user_name);
1211                         strncpy(last_value, nis_result, nis_result_len);
1212                         last_value[nis_result_len] = '\0';
1213                         strip_mount_options(&last_value);
1214
1215                 } else if(nis_error == YPERR_KEY) {
1216
1217                         /* If Key lookup fails user home server is not in nis_map 
1218                                 use default information for server, and home directory */
1219                         last_value[0] = 0;
1220                         DEBUG(3, ("YP Key not found:  while looking up \"%s\" in map \"%s\"\n", 
1221                                         user_name, nis_map));
1222                         DEBUG(3, ("using defaults for server and home directory\n"));
1223                 } else {
1224                         DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n", 
1225                                         yperr_string(nis_error), user_name, nis_map));
1226                 }
1227         }
1228
1229         DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1230         return last_value;
1231 }
1232 #endif /* WITH_NISPLUS_HOME */
1233 #endif
1234
1235 /*******************************************************************
1236  Are two IPs on the same subnet?
1237 ********************************************************************/
1238
1239 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1240 {
1241         uint32 net1,net2,nmask;
1242
1243         nmask = ntohl(mask.s_addr);
1244         net1  = ntohl(ip1.s_addr);
1245         net2  = ntohl(ip2.s_addr);
1246             
1247         return((net1 & nmask) == (net2 & nmask));
1248 }
1249
1250
1251 /****************************************************************************
1252  Check if a process exists. Does this work on all unixes?
1253 ****************************************************************************/
1254
1255 BOOL process_exists(pid_t pid)
1256 {
1257         /* Doing kill with a non-positive pid causes messages to be
1258          * sent to places we don't want. */
1259         SMB_ASSERT(pid > 0);
1260         return(kill(pid,0) == 0 || errno != ESRCH);
1261 }
1262
1263 /*******************************************************************
1264  Convert a uid into a user name.
1265 ********************************************************************/
1266
1267 const char *uidtoname(uid_t uid)
1268 {
1269         static fstring name;
1270         struct passwd *pass;
1271
1272         pass = getpwuid_alloc(uid);
1273         if (pass) {
1274                 fstrcpy(name, pass->pw_name);
1275                 passwd_free(&pass);
1276         } else {
1277                 slprintf(name, sizeof(name) - 1, "%ld",(long int)uid);
1278         }
1279         return name;
1280 }
1281
1282
1283 /*******************************************************************
1284  Convert a gid into a group name.
1285 ********************************************************************/
1286
1287 char *gidtoname(gid_t gid)
1288 {
1289         static fstring name;
1290         struct group *grp;
1291
1292         grp = getgrgid(gid);
1293         if (grp)
1294                 return(grp->gr_name);
1295         slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1296         return(name);
1297 }
1298
1299 /*******************************************************************
1300  Convert a user name into a uid. 
1301 ********************************************************************/
1302
1303 uid_t nametouid(const char *name)
1304 {
1305         struct passwd *pass;
1306         char *p;
1307         uid_t u;
1308
1309         pass = getpwnam_alloc(name);
1310         if (pass) {
1311                 u = pass->pw_uid;
1312                 passwd_free(&pass);
1313                 return u;
1314         }
1315
1316         u = (uid_t)strtol(name, &p, 0);
1317         if ((p != name) && (*p == '\0'))
1318                 return u;
1319
1320         return (uid_t)-1;
1321 }
1322
1323 /*******************************************************************
1324  Convert a name to a gid_t if possible. Return -1 if not a group. 
1325 ********************************************************************/
1326
1327 gid_t nametogid(const char *name)
1328 {
1329         struct group *grp;
1330         char *p;
1331         gid_t g;
1332
1333         g = (gid_t)strtol(name, &p, 0);
1334         if ((p != name) && (*p == '\0'))
1335                 return g;
1336
1337         grp = sys_getgrnam(name);
1338         if (grp)
1339                 return(grp->gr_gid);
1340         return (gid_t)-1;
1341 }
1342
1343 /*******************************************************************
1344  legacy wrapper for smb_panic2()
1345 ********************************************************************/
1346 void smb_panic( const char *why )
1347 {
1348         smb_panic2( why, True );
1349 }
1350
1351 /*******************************************************************
1352  Something really nasty happened - panic !
1353 ********************************************************************/
1354
1355 #ifdef HAVE_LIBEXC_H
1356 #include <libexc.h>
1357 #endif
1358
1359 void smb_panic2(const char *why, BOOL decrement_pid_count )
1360 {
1361         char *cmd;
1362         int result;
1363 #ifdef HAVE_BACKTRACE_SYMBOLS
1364         void *backtrace_stack[BACKTRACE_STACK_SIZE];
1365         size_t backtrace_size;
1366         char **backtrace_strings;
1367 #endif
1368
1369 #ifdef DEVELOPER
1370         {
1371                 extern char *global_clobber_region_function;
1372                 extern unsigned int global_clobber_region_line;
1373
1374                 if (global_clobber_region_function) {
1375                         DEBUG(0,("smb_panic: clobber_region() last called from [%s(%u)]\n",
1376                                          global_clobber_region_function,
1377                                          global_clobber_region_line));
1378                 } 
1379         }
1380 #endif
1381
1382         /* only smbd needs to decrement the smbd counter in connections.tdb */
1383         if ( decrement_pid_count )
1384                 decrement_smbd_process_count();
1385
1386         cmd = lp_panic_action();
1387         if (cmd && *cmd) {
1388                 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
1389                 result = system(cmd);
1390
1391                 if (result == -1)
1392                         DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
1393                                           strerror(errno)));
1394                 else
1395                         DEBUG(0, ("smb_panic(): action returned status %d\n",
1396                                           WEXITSTATUS(result)));
1397         }
1398         DEBUG(0,("PANIC: %s\n", why));
1399
1400 #ifdef HAVE_BACKTRACE_SYMBOLS
1401         /* get the backtrace (stack frames) */
1402         backtrace_size = backtrace(backtrace_stack,BACKTRACE_STACK_SIZE);
1403         backtrace_strings = backtrace_symbols(backtrace_stack, backtrace_size);
1404
1405         DEBUG(0, ("BACKTRACE: %lu stack frames:\n", 
1406                   (unsigned long)backtrace_size));
1407         
1408         if (backtrace_strings) {
1409                 int i;
1410
1411                 for (i = 0; i < backtrace_size; i++)
1412                         DEBUGADD(0, (" #%u %s\n", i, backtrace_strings[i]));
1413
1414                 /* Leak the backtrace_strings, rather than risk what free() might do */
1415         }
1416
1417 #elif HAVE_LIBEXC
1418
1419 #define NAMESIZE 32 /* Arbitrary */
1420
1421         /* The IRIX libexc library provides an API for unwinding the stack. See
1422          * libexc(3) for details. Apparantly trace_back_stack leaks memory, but
1423          * since we are about to abort anyway, it hardly matters.
1424          *
1425          * Note that if we paniced due to a SIGSEGV or SIGBUS (or similar) this
1426          * will fail with a nasty message upon failing to open the /proc entry.
1427          */
1428         {
1429                 __uint64_t      addrs[BACKTRACE_STACK_SIZE];
1430                 char *          names[BACKTRACE_STACK_SIZE];
1431                 char            namebuf[BACKTRACE_STACK_SIZE * NAMESIZE];
1432
1433                 int             i;
1434                 int             levels;
1435
1436                 ZERO_ARRAY(addrs);
1437                 ZERO_ARRAY(names);
1438                 ZERO_ARRAY(namebuf);
1439
1440                 for (i = 0; i < BACKTRACE_STACK_SIZE; i++) {
1441                         names[i] = namebuf + (i * NAMESIZE);
1442                 }
1443
1444                 levels = trace_back_stack(0, addrs, names,
1445                                 BACKTRACE_STACK_SIZE, NAMESIZE);
1446
1447                 DEBUG(0, ("BACKTRACE: %d stack frames:\n", levels));
1448                 for (i = 0; i < levels; i++) {
1449                         DEBUGADD(0, (" #%d 0x%llx %s\n", i, addrs[i], names[i]));
1450                 }
1451      }
1452 #undef NAMESIZE
1453 #endif
1454
1455         dbgflush();
1456         abort();
1457 }
1458
1459 /*******************************************************************
1460   A readdir wrapper which just returns the file name.
1461  ********************************************************************/
1462
1463 const char *readdirname(DIR *p)
1464 {
1465         SMB_STRUCT_DIRENT *ptr;
1466         char *dname;
1467
1468         if (!p)
1469                 return(NULL);
1470   
1471         ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1472         if (!ptr)
1473                 return(NULL);
1474
1475         dname = ptr->d_name;
1476
1477 #ifdef NEXT2
1478         if (telldir(p) < 0)
1479                 return(NULL);
1480 #endif
1481
1482 #ifdef HAVE_BROKEN_READDIR
1483         /* using /usr/ucb/cc is BAD */
1484         dname = dname - 2;
1485 #endif
1486
1487         {
1488                 static pstring buf;
1489                 int len = NAMLEN(ptr);
1490                 memcpy(buf, dname, len);
1491                 buf[len] = 0;
1492                 dname = buf;
1493         }
1494
1495         return(dname);
1496 }
1497
1498 /*******************************************************************
1499  Utility function used to decide if the last component 
1500  of a path matches a (possibly wildcarded) entry in a namelist.
1501 ********************************************************************/
1502
1503 BOOL is_in_path(const char *name, name_compare_entry *namelist)
1504 {
1505         pstring last_component;
1506         char *p;
1507
1508         DEBUG(8, ("is_in_path: %s\n", name));
1509
1510         /* if we have no list it's obviously not in the path */
1511         if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
1512                 DEBUG(8,("is_in_path: no name list.\n"));
1513                 return False;
1514         }
1515
1516         /* Get the last component of the unix name. */
1517         p = strrchr_m(name, '/');
1518         strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1519         last_component[sizeof(last_component)-1] = '\0'; 
1520
1521         for(; namelist->name != NULL; namelist++) {
1522                 if(namelist->is_wild) {
1523                         if (mask_match(last_component, namelist->name, case_sensitive)) {
1524                                 DEBUG(8,("is_in_path: mask match succeeded\n"));
1525                                 return True;
1526                         }
1527                 } else {
1528                         if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1529                                                 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0))) {
1530                                 DEBUG(8,("is_in_path: match succeeded\n"));
1531                                 return True;
1532                         }
1533                 }
1534         }
1535         DEBUG(8,("is_in_path: match not found\n"));
1536  
1537         return False;
1538 }
1539
1540 /*******************************************************************
1541  Strip a '/' separated list into an array of 
1542  name_compare_enties structures suitable for 
1543  passing to is_in_path(). We do this for
1544  speed so we can pre-parse all the names in the list 
1545  and don't do it for each call to is_in_path().
1546  namelist is modified here and is assumed to be 
1547  a copy owned by the caller.
1548  We also check if the entry contains a wildcard to
1549  remove a potentially expensive call to mask_match
1550  if possible.
1551 ********************************************************************/
1552  
1553 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1554 {
1555         char *name_end;
1556         char *nameptr = namelist;
1557         int num_entries = 0;
1558         int i;
1559
1560         (*ppname_array) = NULL;
1561
1562         if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0'))) 
1563                 return;
1564
1565         /* We need to make two passes over the string. The
1566                 first to count the number of elements, the second
1567                 to split it.
1568         */
1569
1570         while(*nameptr) {
1571                 if ( *nameptr == '/' ) {
1572                         /* cope with multiple (useless) /s) */
1573                         nameptr++;
1574                         continue;
1575                 }
1576                 /* find the next / */
1577                 name_end = strchr_m(nameptr, '/');
1578
1579                 /* oops - the last check for a / didn't find one. */
1580                 if (name_end == NULL)
1581                         break;
1582
1583                 /* next segment please */
1584                 nameptr = name_end + 1;
1585                 num_entries++;
1586         }
1587
1588         if(num_entries == 0)
1589                 return;
1590
1591         if(( (*ppname_array) = (name_compare_entry *)malloc(
1592                                         (num_entries + 1) * sizeof(name_compare_entry))) == NULL) {
1593                 DEBUG(0,("set_namearray: malloc fail\n"));
1594                 return;
1595         }
1596
1597         /* Now copy out the names */
1598         nameptr = namelist;
1599         i = 0;
1600         while(*nameptr) {
1601                 if ( *nameptr == '/' ) {
1602                         /* cope with multiple (useless) /s) */
1603                         nameptr++;
1604                         continue;
1605                 }
1606                 /* find the next / */
1607                 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1608                         *name_end = 0;
1609
1610                 /* oops - the last check for a / didn't find one. */
1611                 if(name_end == NULL) 
1612                         break;
1613
1614                 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1615                 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL) {
1616                         DEBUG(0,("set_namearray: malloc fail (1)\n"));
1617                         return;
1618                 }
1619
1620                 /* next segment please */
1621                 nameptr = name_end + 1;
1622                 i++;
1623         }
1624   
1625         (*ppname_array)[i].name = NULL;
1626
1627         return;
1628 }
1629
1630 /****************************************************************************
1631  Routine to free a namearray.
1632 ****************************************************************************/
1633
1634 void free_namearray(name_compare_entry *name_array)
1635 {
1636         int i;
1637
1638         if(name_array == NULL)
1639                 return;
1640
1641         for(i=0; name_array[i].name!=NULL; i++)
1642                 SAFE_FREE(name_array[i].name);
1643         SAFE_FREE(name_array);
1644 }
1645
1646 /****************************************************************************
1647  Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1648  is dealt with in posix.c
1649 ****************************************************************************/
1650
1651 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1652 {
1653         SMB_STRUCT_FLOCK lock;
1654         int ret;
1655
1656         DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1657
1658         lock.l_type = type;
1659         lock.l_whence = SEEK_SET;
1660         lock.l_start = offset;
1661         lock.l_len = count;
1662         lock.l_pid = 0;
1663
1664         ret = sys_fcntl_ptr(fd,op,&lock);
1665
1666         if (ret == -1 && errno != 0)
1667                 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1668
1669         /* a lock query */
1670         if (op == SMB_F_GETLK) {
1671                 if ((ret != -1) &&
1672                                 (lock.l_type != F_UNLCK) && 
1673                                 (lock.l_pid != 0) && 
1674                                 (lock.l_pid != sys_getpid())) {
1675                         DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1676                         return(True);
1677                 }
1678
1679                 /* it must be not locked or locked by me */
1680                 return(False);
1681         }
1682
1683         /* a lock set or unset */
1684         if (ret == -1) {
1685                 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1686                         (double)offset,(double)count,op,type,strerror(errno)));
1687                 return(False);
1688         }
1689
1690         /* everything went OK */
1691         DEBUG(8,("fcntl_lock: Lock call successful\n"));
1692
1693         return(True);
1694 }
1695
1696 /*******************************************************************
1697  Is the name specified one of my netbios names.
1698  Returns true if it is equal, false otherwise.
1699 ********************************************************************/
1700
1701 BOOL is_myname(const char *s)
1702 {
1703         int n;
1704         BOOL ret = False;
1705
1706         for (n=0; my_netbios_names(n); n++) {
1707                 if (strequal(my_netbios_names(n), s)) {
1708                         ret=True;
1709                         break;
1710                 }
1711         }
1712         DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1713         return(ret);
1714 }
1715
1716 /********************************************************************
1717  Return only the first IP address of our configured interfaces
1718  as a string
1719  *******************************************************************/
1720
1721 const char* get_my_primary_ip (void)
1722 {
1723         static fstring ip_string;
1724         int n;
1725         struct iface_struct nics[MAX_INTERFACES];
1726
1727         if ((n=get_interfaces(nics, MAX_INTERFACES)) <= 0)
1728                 return NULL;
1729
1730         fstrcpy(ip_string, inet_ntoa(nics[0].ip));
1731         return ip_string;
1732 }
1733
1734 BOOL is_myname_or_ipaddr(const char *s)
1735 {
1736         /* optimize for the common case */
1737         if (strequal(s, global_myname())) 
1738                 return True;
1739
1740         /* maybe its an IP address? */
1741         if (is_ipaddress(s)) {
1742                 struct iface_struct nics[MAX_INTERFACES];
1743                 int i, n;
1744                 uint32 ip;
1745                 
1746                 ip = interpret_addr(s);
1747                 if ((ip==0) || (ip==0xffffffff))
1748                         return False;
1749                         
1750                 n = get_interfaces(nics, MAX_INTERFACES);
1751                 for (i=0; i<n; i++) {
1752                         if (ip == nics[i].ip.s_addr)
1753                                 return True;
1754                 }
1755         }       
1756
1757         /* check for an alias */
1758         if (is_myname(s))
1759                 return True;
1760         
1761         /* no match */
1762         return False;
1763 }
1764
1765 /*******************************************************************
1766  Is the name specified our workgroup/domain.
1767  Returns true if it is equal, false otherwise.
1768 ********************************************************************/
1769
1770 BOOL is_myworkgroup(const char *s)
1771 {
1772         BOOL ret = False;
1773
1774         if (strequal(s, lp_workgroup())) {
1775                 ret=True;
1776         }
1777
1778         DEBUG(8, ("is_myworkgroup(\"%s\") returns %d\n", s, ret));
1779         return(ret);
1780 }
1781
1782 /*******************************************************************
1783  we distinguish between 2K and XP by the "Native Lan Manager" string
1784    WinXP => "Windows 2002 5.1"
1785    Win2k => "Windows 2000 5.0"
1786    NT4   => "Windows NT 4.0" 
1787    Win9x => "Windows 4.0"
1788  Windows 2003 doesn't set the native lan manager string but 
1789  they do set the domain to "Windows 2003 5.2" (probably a bug).
1790 ********************************************************************/
1791
1792 void ra_lanman_string( const char *native_lanman )
1793 {                
1794         if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1795                 set_remote_arch( RA_WINXP );
1796         else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1797                 set_remote_arch( RA_WIN2K3 );
1798 }
1799
1800 /*******************************************************************
1801  Set the horrid remote_arch string based on an enum.
1802 ********************************************************************/
1803
1804 void set_remote_arch(enum remote_arch_types type)
1805 {
1806         extern fstring remote_arch;
1807         ra_type = type;
1808         switch( type ) {
1809         case RA_WFWG:
1810                 fstrcpy(remote_arch, "WfWg");
1811                 break;
1812         case RA_OS2:
1813                 fstrcpy(remote_arch, "OS2");
1814                 break;
1815         case RA_WIN95:
1816                 fstrcpy(remote_arch, "Win95");
1817                 break;
1818         case RA_WINNT:
1819                 fstrcpy(remote_arch, "WinNT");
1820                 break;
1821         case RA_WIN2K:
1822                 fstrcpy(remote_arch, "Win2K");
1823                 break;
1824         case RA_WINXP:
1825                 fstrcpy(remote_arch, "WinXP");
1826                 break;
1827         case RA_WIN2K3:
1828                 fstrcpy(remote_arch, "Win2K3");
1829                 break;
1830         case RA_SAMBA:
1831                 fstrcpy(remote_arch,"Samba");
1832                 break;
1833         default:
1834                 ra_type = RA_UNKNOWN;
1835                 fstrcpy(remote_arch, "UNKNOWN");
1836                 break;
1837         }
1838
1839         DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n", remote_arch));
1840 }
1841
1842 /*******************************************************************
1843  Get the remote_arch type.
1844 ********************************************************************/
1845
1846 enum remote_arch_types get_remote_arch(void)
1847 {
1848         return ra_type;
1849 }
1850
1851 void print_asc(int level, const unsigned char *buf,int len)
1852 {
1853         int i;
1854         for (i=0;i<len;i++)
1855                 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1856 }
1857
1858 void dump_data(int level, const char *buf1,int len)
1859 {
1860         const unsigned char *buf = (const unsigned char *)buf1;
1861         int i=0;
1862         if (len<=0) return;
1863
1864         if (!DEBUGLVL(level)) return;
1865         
1866         DEBUGADD(level,("[%03X] ",i));
1867         for (i=0;i<len;) {
1868                 DEBUGADD(level,("%02X ",(int)buf[i]));
1869                 i++;
1870                 if (i%8 == 0) DEBUGADD(level,(" "));
1871                 if (i%16 == 0) {      
1872                         print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
1873                         print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
1874                         if (i<len) DEBUGADD(level,("[%03X] ",i));
1875                 }
1876         }
1877         if (i%16) {
1878                 int n;
1879                 n = 16 - (i%16);
1880                 DEBUGADD(level,(" "));
1881                 if (n>8) DEBUGADD(level,(" "));
1882                 while (n--) DEBUGADD(level,("   "));
1883                 n = MIN(8,i%16);
1884                 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
1885                 n = (i%16) - n;
1886                 if (n>0) print_asc(level,&buf[i-n],n); 
1887                 DEBUGADD(level,("\n"));    
1888         }       
1889 }
1890
1891 void dump_data_pw(const char *msg, const uchar * data, size_t len)
1892 {
1893 #ifdef DEBUG_PASSWORD
1894         DEBUG(11, ("%s", msg));
1895         if (data != NULL && len > 0)
1896         {
1897                 dump_data(11, data, len);
1898         }
1899 #endif
1900 }
1901
1902 char *tab_depth(int depth)
1903 {
1904         static pstring spaces;
1905         memset(spaces, ' ', depth * 4);
1906         spaces[depth * 4] = 0;
1907         return spaces;
1908 }
1909
1910 /*****************************************************************************
1911  Provide a checksum on a string
1912
1913  Input:  s - the null-terminated character string for which the checksum
1914              will be calculated.
1915
1916   Output: The checksum value calculated for s.
1917 *****************************************************************************/
1918
1919 int str_checksum(const char *s)
1920 {
1921         int res = 0;
1922         int c;
1923         int i=0;
1924         
1925         while(*s) {
1926                 c = *s;
1927                 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1928                 s++;
1929                 i++;
1930         }
1931         return(res);
1932 }
1933
1934 /*****************************************************************
1935  Zero a memory area then free it. Used to catch bugs faster.
1936 *****************************************************************/  
1937
1938 void zero_free(void *p, size_t size)
1939 {
1940         memset(p, 0, size);
1941         SAFE_FREE(p);
1942 }
1943
1944 /*****************************************************************
1945  Set our open file limit to a requested max and return the limit.
1946 *****************************************************************/  
1947
1948 int set_maxfiles(int requested_max)
1949 {
1950 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1951         struct rlimit rlp;
1952         int saved_current_limit;
1953
1954         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1955                 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1956                         strerror(errno) ));
1957                 /* just guess... */
1958                 return requested_max;
1959         }
1960
1961         /* 
1962          * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1963          * account for the extra fd we need 
1964          * as well as the log files and standard
1965          * handles etc. Save the limit we want to set in case
1966          * we are running on an OS that doesn't support this limit (AIX)
1967          * which always returns RLIM_INFINITY for rlp.rlim_max.
1968          */
1969
1970         /* Try raising the hard (max) limit to the requested amount. */
1971
1972 #if defined(RLIM_INFINITY)
1973         if (rlp.rlim_max != RLIM_INFINITY) {
1974                 int orig_max = rlp.rlim_max;
1975
1976                 if ( rlp.rlim_max < requested_max )
1977                         rlp.rlim_max = requested_max;
1978
1979                 /* This failing is not an error - many systems (Linux) don't
1980                         support our default request of 10,000 open files. JRA. */
1981
1982                 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1983                         DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n", 
1984                                 (int)rlp.rlim_max, strerror(errno) ));
1985
1986                         /* Set failed - restore original value from get. */
1987                         rlp.rlim_max = orig_max;
1988                 }
1989         }
1990 #endif
1991
1992         /* Now try setting the soft (current) limit. */
1993
1994         saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1995
1996         if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1997                 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n", 
1998                         (int)rlp.rlim_cur, strerror(errno) ));
1999                 /* just guess... */
2000                 return saved_current_limit;
2001         }
2002
2003         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
2004                 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
2005                         strerror(errno) ));
2006                 /* just guess... */
2007                 return saved_current_limit;
2008     }
2009
2010 #if defined(RLIM_INFINITY)
2011         if(rlp.rlim_cur == RLIM_INFINITY)
2012                 return saved_current_limit;
2013 #endif
2014
2015         if((int)rlp.rlim_cur > saved_current_limit)
2016                 return saved_current_limit;
2017
2018         return rlp.rlim_cur;
2019 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
2020         /*
2021          * No way to know - just guess...
2022          */
2023         return requested_max;
2024 #endif
2025 }
2026
2027 /*****************************************************************
2028  Splits out the start of the key (HKLM or HKU) and the rest of the key.
2029 *****************************************************************/  
2030
2031 BOOL reg_split_key(const char *full_keyname, uint32 *reg_type, char *key_name)
2032 {
2033         pstring tmp;
2034
2035         if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
2036                 return False;
2037
2038         (*reg_type) = 0;
2039
2040         DEBUG(10, ("reg_split_key: hive %s\n", tmp));
2041
2042         if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
2043                 (*reg_type) = HKEY_LOCAL_MACHINE;
2044         else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
2045                 (*reg_type) = HKEY_USERS;
2046         else {
2047                 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
2048                 return False;
2049         }
2050         
2051         if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
2052                 fstrcpy(key_name, tmp);
2053         else
2054                 key_name[0] = 0;
2055
2056         DEBUG(10, ("reg_split_key: name %s\n", key_name));
2057
2058         return True;
2059 }
2060
2061 /*****************************************************************
2062  Possibly replace mkstemp if it is broken.
2063 *****************************************************************/  
2064
2065 int smb_mkstemp(char *template)
2066 {
2067 #if HAVE_SECURE_MKSTEMP
2068         return mkstemp(template);
2069 #else
2070         /* have a reasonable go at emulating it. Hope that
2071            the system mktemp() isn't completly hopeless */
2072         char *p = mktemp(template);
2073         if (!p)
2074                 return -1;
2075         return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
2076 #endif
2077 }
2078
2079 /*****************************************************************
2080  malloc that aborts with smb_panic on fail or zero size.
2081  *****************************************************************/  
2082
2083 void *smb_xmalloc(size_t size)
2084 {
2085         void *p;
2086         if (size == 0)
2087                 smb_panic("smb_xmalloc: called with zero size.\n");
2088         if ((p = malloc(size)) == NULL) {
2089                 DEBUG(0, ("smb_xmalloc() failed to allocate %lu bytes\n", (unsigned long)size));
2090                 smb_panic("smb_xmalloc: malloc fail.\n");
2091         }
2092         return p;
2093 }
2094
2095 /**
2096  Memdup with smb_panic on fail.
2097 **/
2098
2099 void *smb_xmemdup(const void *p, size_t size)
2100 {
2101         void *p2;
2102         p2 = smb_xmalloc(size);
2103         memcpy(p2, p, size);
2104         return p2;
2105 }
2106
2107 /**
2108  strdup that aborts on malloc fail.
2109 **/
2110
2111 char *smb_xstrdup(const char *s)
2112 {
2113         char *s1 = strdup(s);
2114         if (!s1)
2115                 smb_panic("smb_xstrdup: malloc fail\n");
2116         return s1;
2117 }
2118
2119 /**
2120  strndup that aborts on malloc fail.
2121 **/
2122
2123 char *smb_xstrndup(const char *s, size_t n)
2124 {
2125         char *s1 = strndup(s, n);
2126         if (!s1)
2127                 smb_panic("smb_xstrndup: malloc fail\n");
2128         return s1;
2129 }
2130
2131 /*
2132   vasprintf that aborts on malloc fail
2133 */
2134
2135  int smb_xvasprintf(char **ptr, const char *format, va_list ap)
2136 {
2137         int n;
2138         va_list ap2;
2139
2140         VA_COPY(ap2, ap);
2141
2142         n = vasprintf(ptr, format, ap2);
2143         if (n == -1 || ! *ptr)
2144                 smb_panic("smb_xvasprintf: out of memory");
2145         return n;
2146 }
2147
2148 /*****************************************************************
2149  Like strdup but for memory.
2150 *****************************************************************/  
2151
2152 void *memdup(const void *p, size_t size)
2153 {
2154         void *p2;
2155         if (size == 0)
2156                 return NULL;
2157         p2 = malloc(size);
2158         if (!p2)
2159                 return NULL;
2160         memcpy(p2, p, size);
2161         return p2;
2162 }
2163
2164 /*****************************************************************
2165  Get local hostname and cache result.
2166 *****************************************************************/  
2167
2168 char *myhostname(void)
2169 {
2170         static pstring ret;
2171         if (ret[0] == 0)
2172                 get_myname(ret);
2173         return ret;
2174 }
2175
2176 /*****************************************************************
2177  A useful function for returning a path in the Samba lock directory.
2178 *****************************************************************/  
2179
2180 char *lock_path(const char *name)
2181 {
2182         static pstring fname;
2183
2184         pstrcpy(fname,lp_lockdir());
2185         trim_char(fname,'\0','/');
2186         
2187         if (!directory_exist(fname,NULL))
2188                 mkdir(fname,0755);
2189         
2190         pstrcat(fname,"/");
2191         pstrcat(fname,name);
2192
2193         return fname;
2194 }
2195
2196 /*****************************************************************
2197  A useful function for returning a path in the Samba pid directory.
2198 *****************************************************************/
2199
2200 char *pid_path(const char *name)
2201 {
2202         static pstring fname;
2203
2204         pstrcpy(fname,lp_piddir());
2205         trim_char(fname,'\0','/');
2206
2207         if (!directory_exist(fname,NULL))
2208                 mkdir(fname,0755);
2209
2210         pstrcat(fname,"/");
2211         pstrcat(fname,name);
2212
2213         return fname;
2214 }
2215
2216 /**
2217  * @brief Returns an absolute path to a file in the Samba lib directory.
2218  *
2219  * @param name File to find, relative to LIBDIR.
2220  *
2221  * @retval Pointer to a static #pstring containing the full path.
2222  **/
2223
2224 char *lib_path(const char *name)
2225 {
2226         static pstring fname;
2227         fstr_sprintf(fname, "%s/%s", dyn_LIBDIR, name);
2228         return fname;
2229 }
2230
2231 /**
2232  * @brief Returns the platform specific shared library extension.
2233  *
2234  * @retval Pointer to a static #fstring containing the extension.
2235  **/
2236
2237 const char *shlib_ext(void)
2238 {
2239   return dyn_SHLIBEXT;
2240 }
2241
2242 /*******************************************************************
2243  Given a filename - get its directory name
2244  NB: Returned in static storage.  Caveats:
2245  o  Not safe in thread environment.
2246  o  Caller must not free.
2247  o  If caller wishes to preserve, they should copy.
2248 ********************************************************************/
2249
2250 char *parent_dirname(const char *path)
2251 {
2252         static pstring dirpath;
2253         char *p;
2254
2255         if (!path)
2256                 return(NULL);
2257
2258         pstrcpy(dirpath, path);
2259         p = strrchr_m(dirpath, '/');  /* Find final '/', if any */
2260         if (!p) {
2261                 pstrcpy(dirpath, ".");    /* No final "/", so dir is "." */
2262         } else {
2263                 if (p == dirpath)
2264                         ++p;    /* For root "/", leave "/" in place */
2265                 *p = '\0';
2266         }
2267         return dirpath;
2268 }
2269
2270
2271 /*******************************************************************
2272  Determine if a pattern contains any Microsoft wildcard characters.
2273 *******************************************************************/
2274
2275 BOOL ms_has_wild(const char *s)
2276 {
2277         char c;
2278         while ((c = *s++)) {
2279                 switch (c) {
2280                 case '*':
2281                 case '?':
2282                 case '<':
2283                 case '>':
2284                 case '"':
2285                         return True;
2286                 }
2287         }
2288         return False;
2289 }
2290
2291 BOOL ms_has_wild_w(const smb_ucs2_t *s)
2292 {
2293         smb_ucs2_t c;
2294         if (!s) return False;
2295         while ((c = *s++)) {
2296                 switch (c) {
2297                 case UCS2_CHAR('*'):
2298                 case UCS2_CHAR('?'):
2299                 case UCS2_CHAR('<'):
2300                 case UCS2_CHAR('>'):
2301                 case UCS2_CHAR('"'):
2302                         return True;
2303                 }
2304         }
2305         return False;
2306 }
2307
2308 /*******************************************************************
2309  A wrapper that handles case sensitivity and the special handling
2310  of the ".." name.
2311 *******************************************************************/
2312
2313 BOOL mask_match(const char *string, char *pattern, BOOL is_case_sensitive)
2314 {
2315         if (strcmp(string,"..") == 0)
2316                 string = ".";
2317         if (strcmp(pattern,".") == 0)
2318                 return False;
2319         
2320         return ms_fnmatch(pattern, string, Protocol, is_case_sensitive) == 0;
2321 }
2322
2323 /*******************************************************************
2324  A wrapper that handles a list of patters and calls mask_match()
2325  on each.  Returns True if any of the patterns match.
2326 *******************************************************************/
2327
2328 BOOL mask_match_list(const char *string, char **list, int listLen, BOOL is_case_sensitive)
2329 {
2330        while (listLen-- > 0) {
2331                if (mask_match(string, *list++, is_case_sensitive))
2332                        return True;
2333        }
2334        return False;
2335 }
2336
2337 /*********************************************************
2338  Recursive routine that is called by unix_wild_match.
2339 *********************************************************/
2340
2341 static BOOL unix_do_match(const char *regexp, const char *str)
2342 {
2343         const char *p;
2344
2345         for( p = regexp; *p && *str; ) {
2346
2347                 switch(*p) {
2348                         case '?':
2349                                 str++;
2350                                 p++;
2351                                 break;
2352
2353                         case '*':
2354
2355                                 /*
2356                                  * Look for a character matching 
2357                                  * the one after the '*'.
2358                                  */
2359                                 p++;
2360                                 if(!*p)
2361                                         return True; /* Automatic match */
2362                                 while(*str) {
2363
2364                                         while(*str && (*p != *str))
2365                                                 str++;
2366
2367                                         /*
2368                                          * Patch from weidel@multichart.de. In the case of the regexp
2369                                          * '*XX*' we want to ensure there are at least 2 'X' characters
2370                                          * in the string after the '*' for a match to be made.
2371                                          */
2372
2373                                         {
2374                                                 int matchcount=0;
2375
2376                                                 /*
2377                                                  * Eat all the characters that match, but count how many there were.
2378                                                  */
2379
2380                                                 while(*str && (*p == *str)) {
2381                                                         str++;
2382                                                         matchcount++;
2383                                                 }
2384
2385                                                 /*
2386                                                  * Now check that if the regexp had n identical characters that
2387                                                  * matchcount had at least that many matches.
2388                                                  */
2389
2390                                                 while ( *(p+1) && (*(p+1) == *p)) {
2391                                                         p++;
2392                                                         matchcount--;
2393                                                 }
2394
2395                                                 if ( matchcount <= 0 )
2396                                                         return False;
2397                                         }
2398
2399                                         str--; /* We've eaten the match char after the '*' */
2400
2401                                         if(unix_do_match(p, str))
2402                                                 return True;
2403
2404                                         if(!*str)
2405                                                 return False;
2406                                         else
2407                                                 str++;
2408                                 }
2409                                 return False;
2410
2411                         default:
2412                                 if(*str != *p)
2413                                         return False;
2414                                 str++;
2415                                 p++;
2416                                 break;
2417                 }
2418         }
2419
2420         if(!*p && !*str)
2421                 return True;
2422
2423         if (!*p && str[0] == '.' && str[1] == 0)
2424                 return(True);
2425   
2426         if (!*str && *p == '?') {
2427                 while (*p == '?')
2428                         p++;
2429                 return(!*p);
2430         }
2431
2432         if(!*str && (*p == '*' && p[1] == '\0'))
2433                 return True;
2434
2435         return False;
2436 }
2437
2438 /*******************************************************************
2439  Simple case insensitive interface to a UNIX wildcard matcher.
2440 *******************************************************************/
2441
2442 BOOL unix_wild_match(const char *pattern, const char *string)
2443 {
2444         pstring p2, s2;
2445         char *p;
2446
2447         pstrcpy(p2, pattern);
2448         pstrcpy(s2, string);
2449         strlower_m(p2);
2450         strlower_m(s2);
2451
2452         /* Remove any *? and ** from the pattern as they are meaningless */
2453         for(p = p2; *p; p++)
2454                 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2455                         pstrcpy( &p[1], &p[2]);
2456  
2457         if (strequal(p2,"*"))
2458                 return True;
2459
2460         return unix_do_match(p2, s2) == 0;      
2461 }
2462
2463
2464 #ifdef __INSURE__
2465
2466 /*******************************************************************
2467 This routine is a trick to immediately catch errors when debugging
2468 with insure. A xterm with a gdb is popped up when insure catches
2469 a error. It is Linux specific.
2470 ********************************************************************/
2471
2472 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2473 {
2474         static int (*fn)();
2475         int ret;
2476         char pidstr[10];
2477         /* you can get /usr/bin/backtrace from 
2478            http://samba.org/ftp/unpacked/junkcode/backtrace */
2479         pstring cmd = "/usr/bin/backtrace %d";
2480
2481         slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2482         pstring_sub(cmd, "%d", pidstr);
2483
2484         if (!fn) {
2485                 static void *h;
2486                 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2487                 fn = dlsym(h, "_Insure_trap_error");
2488
2489                 if (!h || h == _Insure_trap_error) {
2490                         h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2491                         fn = dlsym(h, "_Insure_trap_error");
2492                 }               
2493         }
2494
2495         ret = fn(a1, a2, a3, a4, a5, a6);
2496
2497         system(cmd);
2498
2499         return ret;
2500 }
2501 #endif