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