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