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