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