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