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