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