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