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