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