e143364db5402a36d7ba28b07053ac336efc7307
[ira/wip.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, 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 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(void)
507 {
508   int fd;
509   int i;
510   close(0); close(1); 
511 #ifndef __INSURE__
512   close(2);
513 #endif
514   /* try and use up these file descriptors, so silly
515      library routines writing to stdout etc won't cause havoc */
516   for (i=0;i<3;i++) {
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();
682 }
683
684
685 /****************************************************************************
686  Put up a yes/no prompt
687 ****************************************************************************/
688 BOOL yesno(char *p)
689 {
690   pstring ans;
691   printf("%s",p);
692
693   if (!fgets(ans,sizeof(ans)-1,stdin))
694     return(False);
695
696   if (*ans == 'y' || *ans == 'Y')
697     return(True);
698
699   return(False);
700 }
701
702 /****************************************************************************
703  Expand a pointer to be a particular size.
704 ****************************************************************************/
705
706 void *Realloc(void *p,size_t size)
707 {
708   void *ret=NULL;
709
710   if (size == 0) {
711     SAFE_FREE(p);
712     DEBUG(5,("Realloc asked for 0 bytes\n"));
713     return NULL;
714   }
715
716   if (!p)
717     ret = (void *)malloc(size);
718   else
719     ret = (void *)realloc(p,size);
720
721   if (!ret)
722     DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
723
724   return(ret);
725 }
726
727 /****************************************************************************
728  Free memory, checks for NULL.
729 use directly SAFE_FREE()
730 exist only because we need to pass a function pointer somewhere --SSS
731 ****************************************************************************/
732
733 void safe_free(void *p)
734 {
735         SAFE_FREE(p);
736 }
737
738 /****************************************************************************
739  Get my own name and IP.
740 ****************************************************************************/
741
742 BOOL get_myname(char *my_name)
743 {
744         pstring hostname;
745
746         *hostname = 0;
747
748         /* get my host name */
749         if (gethostname(hostname, sizeof(hostname)) == -1) {
750                 DEBUG(0,("gethostname failed\n"));
751                 return False;
752         } 
753
754         /* Ensure null termination. */
755         hostname[sizeof(hostname)-1] = '\0';
756
757         if (my_name) {
758                 /* split off any parts after an initial . */
759                 char *p = strchr_m(hostname,'.');
760
761                 if (p)
762                         *p = 0;
763                 
764                 fstrcpy(my_name,hostname);
765         }
766         
767         return(True);
768 }
769
770 /****************************************************************************
771  Interpret a protocol description string, with a default.
772 ****************************************************************************/
773
774 int interpret_protocol(char *str,int def)
775 {
776   if (strequal(str,"NT1"))
777     return(PROTOCOL_NT1);
778   if (strequal(str,"LANMAN2"))
779     return(PROTOCOL_LANMAN2);
780   if (strequal(str,"LANMAN1"))
781     return(PROTOCOL_LANMAN1);
782   if (strequal(str,"CORE"))
783     return(PROTOCOL_CORE);
784   if (strequal(str,"COREPLUS"))
785     return(PROTOCOL_COREPLUS);
786   if (strequal(str,"CORE+"))
787     return(PROTOCOL_COREPLUS);
788   
789   DEBUG(0,("Unrecognised protocol level %s\n",str));
790   
791   return(def);
792 }
793
794 /****************************************************************************
795  Return true if a string could be a pure IP address.
796 ****************************************************************************/
797
798 BOOL is_ipaddress(const char *str)
799 {
800   BOOL pure_address = True;
801   int i;
802   
803   for (i=0; pure_address && str[i]; i++)
804     if (!(isdigit((int)str[i]) || str[i] == '.'))
805       pure_address = False;
806
807   /* Check that a pure number is not misinterpreted as an IP */
808   pure_address = pure_address && (strchr_m(str, '.') != NULL);
809
810   return pure_address;
811 }
812
813 /****************************************************************************
814 interpret an internet address or name into an IP address in 4 byte form
815 ****************************************************************************/
816
817 uint32 interpret_addr(const char *str)
818 {
819   struct hostent *hp;
820   uint32 res;
821
822   if (strcmp(str,"0.0.0.0") == 0) return(0);
823   if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
824
825   /* if it's in the form of an IP address then get the lib to interpret it */
826   if (is_ipaddress(str)) {
827     res = inet_addr(str);
828   } else {
829     /* otherwise assume it's a network name of some sort and use 
830        sys_gethostbyname */
831     if ((hp = sys_gethostbyname(str)) == 0) {
832       DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
833       return 0;
834     }
835     if(hp->h_addr == NULL) {
836       DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
837       return 0;
838     }
839     putip((char *)&res,(char *)hp->h_addr);
840   }
841
842   if (res == (uint32)-1) return(0);
843
844   return(res);
845 }
846
847 /*******************************************************************
848   a convenient addition to interpret_addr()
849   ******************************************************************/
850 struct in_addr *interpret_addr2(const char *str)
851 {
852   static struct in_addr ret;
853   uint32 a = interpret_addr(str);
854   ret.s_addr = a;
855   return(&ret);
856 }
857
858 /*******************************************************************
859  Check if an IP is the 0.0.0.0
860   ******************************************************************/
861 BOOL is_zero_ip(struct in_addr ip)
862 {
863   uint32 a;
864   putip((char *)&a,(char *)&ip);
865   return(a == 0);
866 }
867
868 /*******************************************************************
869  Set an IP to 0.0.0.0
870  ******************************************************************/
871
872 void zero_ip(struct in_addr *ip)
873 {
874         static BOOL init;
875         static struct in_addr ipzero;
876
877         if (!init) {
878                 ipzero = *interpret_addr2("0.0.0.0");
879                 init = True;
880         }
881
882         *ip = ipzero;
883 }
884
885 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
886 /******************************************************************
887  Remove any mount options such as -rsize=2048,wsize=2048 etc.
888  Based on a fix from <Thomas.Hepper@icem.de>.
889 *******************************************************************/
890
891 static void strip_mount_options( pstring *str)
892 {
893   if (**str == '-')
894   { 
895     char *p = *str;
896     while(*p && !isspace(*p))
897       p++;
898     while(*p && isspace(*p))
899       p++;
900     if(*p) {
901       pstring tmp_str;
902
903       pstrcpy(tmp_str, p);
904       pstrcpy(*str, tmp_str);
905     }
906   }
907 }
908
909 /*******************************************************************
910  Patch from jkf@soton.ac.uk
911  Split Luke's automount_server into YP lookup and string splitter
912  so can easily implement automount_path(). 
913  As we may end up doing both, cache the last YP result. 
914 *******************************************************************/
915
916 #ifdef WITH_NISPLUS_HOME
917 char *automount_lookup(const char *user_name)
918 {
919   static fstring last_key = "";
920   static pstring last_value = "";
921  
922   char *nis_map = (char *)lp_nis_home_map_name();
923  
924   char buffer[NIS_MAXATTRVAL + 1];
925   nis_result *result;
926   nis_object *object;
927   entry_obj  *entry;
928  
929   if (strcmp(user_name, last_key))
930   {
931     slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
932     DEBUG(5, ("NIS+ querystring: %s\n", buffer));
933  
934     if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL))
935     {
936        if (result->status != NIS_SUCCESS)
937       {
938         DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
939         fstrcpy(last_key, ""); pstrcpy(last_value, "");
940       }
941       else
942       {
943         object = result->objects.objects_val;
944         if (object->zo_data.zo_type == ENTRY_OBJ)
945         {
946            entry = &object->zo_data.objdata_u.en_data;
947            DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
948            DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
949  
950            pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
951            pstring_sub(last_value, "&", user_name);
952            fstrcpy(last_key, user_name);
953         }
954       }
955     }
956     nis_freeresult(result);
957   }
958
959   strip_mount_options(&last_value);
960
961   DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
962   return last_value;
963 }
964 #else /* WITH_NISPLUS_HOME */
965 char *automount_lookup(const char *user_name)
966 {
967   static fstring last_key = "";
968   static pstring last_value = "";
969
970   int nis_error;        /* returned by yp all functions */
971   char *nis_result;     /* yp_match inits this */
972   int nis_result_len;  /* and set this */
973   char *nis_domain;     /* yp_get_default_domain inits this */
974   char *nis_map = (char *)lp_nis_home_map_name();
975
976   if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
977     DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
978     return last_value;
979   }
980
981   DEBUG(5, ("NIS Domain: %s\n", nis_domain));
982
983   if (!strcmp(user_name, last_key)) {
984         nis_result = last_value;
985     nis_result_len = strlen(last_value);
986     nis_error = 0;
987
988   } else {
989
990     if ((nis_error = yp_match(nis_domain, nis_map,
991                               user_name, strlen(user_name),
992                               &nis_result, &nis_result_len)) == 0) {
993        if (!nis_error && nis_result_len >= sizeof(pstring)) {
994                nis_result_len = sizeof(pstring)-1;
995        }
996        fstrcpy(last_key, user_name);
997        strncpy(last_value, nis_result, nis_result_len);
998        last_value[nis_result_len] = '\0';
999         strip_mount_options(&last_value);
1000
1001     } else if(nis_error == YPERR_KEY) {
1002
1003     /* If Key lookup fails user home server is not in nis_map 
1004        use default information for server, and home directory */
1005        last_value[0] = 0;
1006        DEBUG(3, ("YP Key not found:  while looking up \"%s\" in map \"%s\"\n", 
1007                 user_name, nis_map));
1008        DEBUG(3, ("using defaults for server and home directory\n"));
1009     } else {
1010        DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n", 
1011                yperr_string(nis_error), user_name, nis_map));
1012     }
1013   }
1014
1015
1016   DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1017   return last_value;
1018 }
1019 #endif /* WITH_NISPLUS_HOME */
1020 #endif
1021
1022
1023 /*******************************************************************
1024 are two IPs on the same subnet?
1025 ********************************************************************/
1026 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1027 {
1028   uint32 net1,net2,nmask;
1029
1030   nmask = ntohl(mask.s_addr);
1031   net1  = ntohl(ip1.s_addr);
1032   net2  = ntohl(ip2.s_addr);
1033             
1034   return((net1 & nmask) == (net2 & nmask));
1035 }
1036
1037
1038 /****************************************************************************
1039 check if a process exists. Does this work on all unixes?
1040 ****************************************************************************/
1041
1042 BOOL process_exists(pid_t pid)
1043 {
1044         /* Doing kill with a non-positive pid causes messages to be
1045          * sent to places we don't want. */
1046         SMB_ASSERT(pid > 0);
1047         return(kill(pid,0) == 0 || errno != ESRCH);
1048 }
1049
1050
1051 /*******************************************************************
1052  Convert a uid into a user name.
1053 ********************************************************************/
1054
1055 char *uidtoname(uid_t uid)
1056 {
1057         static fstring name;
1058         struct passwd *pass;
1059
1060         pass = sys_getpwuid(uid);
1061         if (pass)
1062                 return(pass->pw_name);
1063         slprintf(name, sizeof(name) - 1, "%d",(int)uid);
1064         return(name);
1065 }
1066
1067
1068 /*******************************************************************
1069  Convert a gid into a group name.
1070 ********************************************************************/
1071
1072 char *gidtoname(gid_t gid)
1073 {
1074         static fstring name;
1075         struct group *grp;
1076
1077         grp = getgrgid(gid);
1078         if (grp)
1079                 return(grp->gr_name);
1080         slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1081         return(name);
1082 }
1083
1084 /*******************************************************************
1085  Convert a user name into a uid. 
1086 ********************************************************************/
1087
1088 uid_t nametouid(char *name)
1089 {
1090         struct passwd *pass;
1091         char *p;
1092         uid_t u;
1093
1094         pass = getpwnam_alloc(name);
1095         if (pass) {
1096                 u = pass->pw_uid;
1097                 passwd_free(&pass);
1098                 return u;
1099         }
1100
1101         u = (uid_t)strtol(name, &p, 0);
1102         if ((p != name) && (*p == '\0'))
1103                 return u;
1104
1105         return (uid_t)-1;
1106 }
1107
1108 /*******************************************************************
1109  Convert a name to a gid_t if possible. Return -1 if not a group. 
1110 ********************************************************************/
1111
1112 gid_t nametogid(const char *name)
1113 {
1114         struct group *grp;
1115         char *p;
1116         gid_t g;
1117
1118         g = (gid_t)strtol(name, &p, 0);
1119         if ((p != name) && (*p == '\0'))
1120                 return g;
1121
1122         grp = getgrnam(name);
1123         if (grp)
1124                 return(grp->gr_gid);
1125         return (gid_t)-1;
1126 }
1127
1128 /*******************************************************************
1129 something really nasty happened - panic!
1130 ********************************************************************/
1131 void smb_panic(char *why)
1132 {
1133         char *cmd = lp_panic_action();
1134         if (cmd && *cmd) {
1135                 system(cmd);
1136         }
1137         DEBUG(0,("PANIC: %s\n", why));
1138         dbgflush();
1139         abort();
1140 }
1141
1142
1143 /*******************************************************************
1144 a readdir wrapper which just returns the file name
1145 ********************************************************************/
1146 char *readdirname(DIR *p)
1147 {
1148         SMB_STRUCT_DIRENT *ptr;
1149         char *dname;
1150
1151         if (!p) return(NULL);
1152   
1153         ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1154         if (!ptr) return(NULL);
1155
1156         dname = ptr->d_name;
1157
1158 #ifdef NEXT2
1159         if (telldir(p) < 0) return(NULL);
1160 #endif
1161
1162 #ifdef HAVE_BROKEN_READDIR
1163         /* using /usr/ucb/cc is BAD */
1164         dname = dname - 2;
1165 #endif
1166
1167         {
1168                 static pstring buf;
1169                 int len = NAMLEN(ptr);
1170                 memcpy(buf, dname, len);
1171                 buf[len] = 0;
1172                 dname = buf;
1173         }
1174
1175         return(dname);
1176 }
1177
1178 /*******************************************************************
1179  Utility function used to decide if the last component 
1180  of a path matches a (possibly wildcarded) entry in a namelist.
1181 ********************************************************************/
1182
1183 BOOL is_in_path(char *name, name_compare_entry *namelist)
1184 {
1185   pstring last_component;
1186   char *p;
1187
1188   DEBUG(8, ("is_in_path: %s\n", name));
1189
1190   /* if we have no list it's obviously not in the path */
1191   if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) 
1192   {
1193     DEBUG(8,("is_in_path: no name list.\n"));
1194     return False;
1195   }
1196
1197   /* Get the last component of the unix name. */
1198   p = strrchr_m(name, '/');
1199   strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1200   last_component[sizeof(last_component)-1] = '\0'; 
1201
1202   for(; namelist->name != NULL; namelist++)
1203   {
1204     if(namelist->is_wild)
1205     {
1206       if (mask_match(last_component, namelist->name, case_sensitive))
1207       {
1208          DEBUG(8,("is_in_path: mask match succeeded\n"));
1209          return True;
1210       }
1211     }
1212     else
1213     {
1214       if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1215        (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
1216         {
1217          DEBUG(8,("is_in_path: match succeeded\n"));
1218          return True;
1219         }
1220     }
1221   }
1222   DEBUG(8,("is_in_path: match not found\n"));
1223  
1224   return False;
1225 }
1226
1227 /*******************************************************************
1228  Strip a '/' separated list into an array of 
1229  name_compare_enties structures suitable for 
1230  passing to is_in_path(). We do this for
1231  speed so we can pre-parse all the names in the list 
1232  and don't do it for each call to is_in_path().
1233  namelist is modified here and is assumed to be 
1234  a copy owned by the caller.
1235  We also check if the entry contains a wildcard to
1236  remove a potentially expensive call to mask_match
1237  if possible.
1238 ********************************************************************/
1239  
1240 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1241 {
1242   char *name_end;
1243   char *nameptr = namelist;
1244   int num_entries = 0;
1245   int i;
1246
1247   (*ppname_array) = NULL;
1248
1249   if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0'))) 
1250     return;
1251
1252   /* We need to make two passes over the string. The
1253      first to count the number of elements, the second
1254      to split it.
1255    */
1256   while(*nameptr) 
1257     {
1258       if ( *nameptr == '/' ) 
1259         {
1260           /* cope with multiple (useless) /s) */
1261           nameptr++;
1262           continue;
1263         }
1264       /* find the next / */
1265       name_end = strchr_m(nameptr, '/');
1266
1267       /* oops - the last check for a / didn't find one. */
1268       if (name_end == NULL)
1269         break;
1270
1271       /* next segment please */
1272       nameptr = name_end + 1;
1273       num_entries++;
1274     }
1275
1276   if(num_entries == 0)
1277     return;
1278
1279   if(( (*ppname_array) = (name_compare_entry *)malloc( 
1280            (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
1281         {
1282     DEBUG(0,("set_namearray: malloc fail\n"));
1283     return;
1284         }
1285
1286   /* Now copy out the names */
1287   nameptr = namelist;
1288   i = 0;
1289   while(*nameptr)
1290              {
1291       if ( *nameptr == '/' ) 
1292       {
1293           /* cope with multiple (useless) /s) */
1294           nameptr++;
1295           continue;
1296       }
1297       /* find the next / */
1298       if ((name_end = strchr_m(nameptr, '/')) != NULL) 
1299       {
1300           *name_end = 0;
1301          }
1302
1303       /* oops - the last check for a / didn't find one. */
1304       if(name_end == NULL) 
1305         break;
1306
1307       (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1308       if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
1309       {
1310         DEBUG(0,("set_namearray: malloc fail (1)\n"));
1311         return;
1312       }
1313
1314       /* next segment please */
1315       nameptr = name_end + 1;
1316       i++;
1317     }
1318   
1319   (*ppname_array)[i].name = NULL;
1320
1321   return;
1322 }
1323
1324 /****************************************************************************
1325 routine to free a namearray.
1326 ****************************************************************************/
1327
1328 void free_namearray(name_compare_entry *name_array)
1329 {
1330   if(name_array == NULL)
1331     return;
1332
1333   SAFE_FREE(name_array->name);
1334   SAFE_FREE(name_array);
1335 }
1336
1337 /****************************************************************************
1338  Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1339  is dealt with in posix.c
1340 ****************************************************************************/
1341
1342 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1343 {
1344   SMB_STRUCT_FLOCK lock;
1345   int ret;
1346
1347   DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1348
1349   lock.l_type = type;
1350   lock.l_whence = SEEK_SET;
1351   lock.l_start = offset;
1352   lock.l_len = count;
1353   lock.l_pid = 0;
1354
1355   ret = sys_fcntl_ptr(fd,op,&lock);
1356
1357   if (ret == -1 && errno != 0)
1358     DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1359
1360   /* a lock query */
1361   if (op == SMB_F_GETLK)
1362   {
1363     if ((ret != -1) &&
1364         (lock.l_type != F_UNLCK) && 
1365         (lock.l_pid != 0) && 
1366         (lock.l_pid != sys_getpid()))
1367     {
1368       DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1369       return(True);
1370     }
1371
1372     /* it must be not locked or locked by me */
1373     return(False);
1374   }
1375
1376   /* a lock set or unset */
1377   if (ret == -1)
1378   {
1379     DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1380           (double)offset,(double)count,op,type,strerror(errno)));
1381     return(False);
1382   }
1383
1384   /* everything went OK */
1385   DEBUG(8,("fcntl_lock: Lock call successful\n"));
1386
1387   return(True);
1388 }
1389
1390 /*******************************************************************
1391  Is the name specified one of my netbios names.
1392  Returns true if it is equal, false otherwise.
1393 ********************************************************************/
1394
1395 BOOL is_myname(char *s)
1396 {
1397         int n;
1398         BOOL ret = False;
1399
1400         for (n=0; my_netbios_names[n]; n++) {
1401                 if (strequal(my_netbios_names[n], s))
1402                         ret=True;
1403         }
1404         DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1405         return(ret);
1406 }
1407
1408 /********************************************************************
1409  Return only the first IP address of our configured interfaces
1410  as a string
1411  *******************************************************************/
1412
1413 const char* get_my_primary_ip (void)
1414 {
1415         static fstring ip_string;
1416         int n;
1417         struct iface_struct nics[MAX_INTERFACES];
1418
1419         if ((n=get_interfaces(nics, MAX_INTERFACES)) <= 0)
1420                 return NULL;
1421
1422         fstrcpy(ip_string, inet_ntoa(nics[0].ip));
1423         return ip_string;
1424 }
1425
1426 BOOL is_myname_or_ipaddr(char *s)
1427 {
1428         char **ptr;
1429         
1430         /* optimize for the common case */
1431         if (strequal(s, global_myname)) 
1432                 return True;
1433
1434         /* maybe its an IP address? */
1435         if (is_ipaddress(s)) {
1436                 struct iface_struct nics[MAX_INTERFACES];
1437                 int i, n;
1438                 uint32 ip;
1439                 
1440                 ip = interpret_addr(s);
1441                 if ((ip==0) || (ip==0xffffffff))
1442                         return False;
1443                         
1444                 n = get_interfaces(nics, MAX_INTERFACES);
1445                 for (i=0; i<n; i++) {
1446                         if (ip == nics[i].ip.s_addr)
1447                                 return True;
1448                 }
1449         }       
1450
1451         /* check for an alias */
1452         ptr = lp_netbios_aliases();
1453         for ( ; *ptr; ptr++ ) {
1454                 if (StrCaseCmp(s, *ptr) == 0)
1455                         return True;
1456         }
1457         
1458         /* no match */
1459         return False;
1460 }
1461
1462 /*******************************************************************
1463  Set the horrid remote_arch string based on an enum.
1464 ********************************************************************/
1465
1466 void set_remote_arch(enum remote_arch_types type)
1467 {
1468         extern fstring remote_arch;
1469         ra_type = type;
1470         switch( type ) {
1471         case RA_WFWG:
1472                 fstrcpy(remote_arch, "WfWg");
1473                 return;
1474         case RA_OS2:
1475                 fstrcpy(remote_arch, "OS2");
1476                 return;
1477         case RA_WIN95:
1478                 fstrcpy(remote_arch, "Win95");
1479                 return;
1480         case RA_WINNT:
1481                 fstrcpy(remote_arch, "WinNT");
1482                 return;
1483         case RA_WIN2K:
1484                 fstrcpy(remote_arch, "Win2K");
1485                 return;
1486         case RA_SAMBA:
1487                 fstrcpy(remote_arch,"Samba");
1488                 return;
1489         default:
1490                 ra_type = RA_UNKNOWN;
1491                 fstrcpy(remote_arch, "UNKNOWN");
1492                 break;
1493         }
1494 }
1495
1496 /*******************************************************************
1497  Get the remote_arch type.
1498 ********************************************************************/
1499
1500 enum remote_arch_types get_remote_arch(void)
1501 {
1502         return ra_type;
1503 }
1504
1505
1506 void out_ascii(FILE *f, unsigned char *buf,int len)
1507 {
1508         int i;
1509         for (i=0;i<len;i++)
1510                 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1511 }
1512
1513 void out_data(FILE *f,char *buf1,int len, int per_line)
1514 {
1515         unsigned char *buf = (unsigned char *)buf1;
1516         int i=0;
1517         if (len<=0) {
1518                 return;
1519         }
1520
1521         fprintf(f, "[%03X] ",i);
1522         for (i=0;i<len;) {
1523                 fprintf(f, "%02X ",(int)buf[i]);
1524                 i++;
1525                 if (i%(per_line/2) == 0) fprintf(f, " ");
1526                 if (i%per_line == 0) {      
1527                         out_ascii(f,&buf[i-per_line  ],per_line/2); fprintf(f, " ");
1528                         out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1529                         if (i<len) fprintf(f, "[%03X] ",i);
1530                 }
1531         }
1532         if ((i%per_line) != 0) {
1533                 int n;
1534
1535                 n = per_line - (i%per_line);
1536                 fprintf(f, " ");
1537                 if (n>(per_line/2)) fprintf(f, " ");
1538                 while (n--) {
1539                         fprintf(f, "   ");
1540                 }
1541                 n = MIN(per_line/2,i%per_line);
1542                 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1543                 n = (i%per_line) - n;
1544                 if (n>0) out_ascii(f,&buf[i-n],n); 
1545                 fprintf(f, "\n");    
1546         }
1547 }
1548
1549 void print_asc(int level, const unsigned char *buf,int len)
1550 {
1551         int i;
1552         for (i=0;i<len;i++)
1553                 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1554 }
1555
1556 void dump_data(int level, const char *buf1,int len)
1557 {
1558   const unsigned char *buf = (const unsigned char *)buf1;
1559   int i=0;
1560   if (len<=0) return;
1561
1562   DEBUG(level,("[%03X] ",i));
1563   for (i=0;i<len;) {
1564     DEBUG(level,("%02X ",(int)buf[i]));
1565     i++;
1566     if (i%8 == 0) DEBUG(level,(" "));
1567     if (i%16 == 0) {      
1568       print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
1569       print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
1570       if (i<len) DEBUG(level,("[%03X] ",i));
1571     }
1572   }
1573   if (i%16) {
1574     int n;
1575
1576     n = 16 - (i%16);
1577     DEBUG(level,(" "));
1578     if (n>8) DEBUG(level,(" "));
1579     while (n--) DEBUG(level,("   "));
1580
1581     n = MIN(8,i%16);
1582     print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
1583     n = (i%16) - n;
1584     if (n>0) print_asc(level,&buf[i-n],n); 
1585     DEBUG(level,("\n"));    
1586   }
1587 }
1588
1589 char *tab_depth(int depth)
1590 {
1591         static pstring spaces;
1592         memset(spaces, ' ', depth * 4);
1593         spaces[depth * 4] = 0;
1594         return spaces;
1595 }
1596
1597 /*****************************************************************************
1598  * Provide a checksum on a string
1599  *
1600  *  Input:  s - the null-terminated character string for which the checksum
1601  *              will be calculated.
1602  *
1603  *  Output: The checksum value calculated for s.
1604  *
1605  * ****************************************************************************
1606  */
1607 int str_checksum(const char *s)
1608 {
1609         int res = 0;
1610         int c;
1611         int i=0;
1612         
1613         while(*s) {
1614                 c = *s;
1615                 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1616                 s++;
1617                 i++;
1618         }
1619         return(res);
1620 } /* str_checksum */
1621
1622
1623
1624 /*****************************************************************
1625 zero a memory area then free it. Used to catch bugs faster
1626 *****************************************************************/  
1627 void zero_free(void *p, size_t size)
1628 {
1629         memset(p, 0, size);
1630         SAFE_FREE(p);
1631 }
1632
1633
1634 /*****************************************************************
1635 set our open file limit to a requested max and return the limit
1636 *****************************************************************/  
1637 int set_maxfiles(int requested_max)
1638 {
1639 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1640         struct rlimit rlp;
1641         int saved_current_limit;
1642
1643         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1644                 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1645                         strerror(errno) ));
1646                 /* just guess... */
1647                 return requested_max;
1648         }
1649
1650         /* 
1651      * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1652          * account for the extra fd we need 
1653          * as well as the log files and standard
1654          * handles etc. Save the limit we want to set in case
1655          * we are running on an OS that doesn't support this limit (AIX)
1656          * which always returns RLIM_INFINITY for rlp.rlim_max.
1657          */
1658
1659         /* Try raising the hard (max) limit to the requested amount. */
1660
1661 #if defined(RLIM_INFINITY)
1662         if (rlp.rlim_max != RLIM_INFINITY) {
1663                 int orig_max = rlp.rlim_max;
1664
1665                 if ( rlp.rlim_max < requested_max )
1666                         rlp.rlim_max = requested_max;
1667
1668                 /* This failing is not an error - many systems (Linux) don't
1669                         support our default request of 10,000 open files. JRA. */
1670
1671                 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1672                         DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n", 
1673                                 (int)rlp.rlim_max, strerror(errno) ));
1674
1675                         /* Set failed - restore original value from get. */
1676                         rlp.rlim_max = orig_max;
1677                 }
1678         }
1679 #endif
1680
1681         /* Now try setting the soft (current) limit. */
1682
1683         saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1684
1685         if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1686                 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n", 
1687                         (int)rlp.rlim_cur, strerror(errno) ));
1688                 /* just guess... */
1689                 return saved_current_limit;
1690         }
1691
1692         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1693                 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1694                         strerror(errno) ));
1695                 /* just guess... */
1696                 return saved_current_limit;
1697     }
1698
1699 #if defined(RLIM_INFINITY)
1700         if(rlp.rlim_cur == RLIM_INFINITY)
1701                 return saved_current_limit;
1702 #endif
1703
1704     if((int)rlp.rlim_cur > saved_current_limit)
1705                 return saved_current_limit;
1706
1707         return rlp.rlim_cur;
1708 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1709         /*
1710          * No way to know - just guess...
1711          */
1712         return requested_max;
1713 #endif
1714 }
1715
1716 /*****************************************************************
1717  splits out the start of the key (HKLM or HKU) and the rest of the key
1718  *****************************************************************/  
1719 BOOL reg_split_key(char *full_keyname, uint32 *reg_type, char *key_name)
1720 {
1721         pstring tmp;
1722
1723         if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1724         {
1725                 return False;
1726         }
1727
1728         (*reg_type) = 0;
1729
1730         DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1731
1732         if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1733         {
1734                 (*reg_type) = HKEY_LOCAL_MACHINE;
1735         }
1736         else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1737         {
1738                 (*reg_type) = HKEY_USERS;
1739         }
1740         else
1741         {
1742                 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1743                 return False;
1744         }
1745         
1746         if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
1747         {
1748                 fstrcpy(key_name, tmp);
1749         }
1750         else
1751         {
1752                 key_name[0] = 0;
1753         }
1754
1755         DEBUG(10, ("reg_split_key: name %s\n", key_name));
1756
1757         return True;
1758 }
1759
1760
1761 /*****************************************************************
1762 possibly replace mkstemp if it is broken
1763 *****************************************************************/  
1764 int smb_mkstemp(char *template)
1765 {
1766 #if HAVE_SECURE_MKSTEMP
1767         return mkstemp(template);
1768 #else
1769         /* have a reasonable go at emulating it. Hope that
1770            the system mktemp() isn't completly hopeless */
1771         char *p = mktemp(template);
1772         if (!p) return -1;
1773         return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
1774 #endif
1775 }
1776
1777 /*****************************************************************
1778  malloc that aborts with smb_panic on fail or zero size.
1779  *****************************************************************/  
1780
1781 void *smb_xmalloc(size_t size)
1782 {
1783         void *p;
1784         if (size == 0)
1785                 smb_panic("smb_xmalloc: called with zero size.\n");
1786         if ((p = malloc(size)) == NULL)
1787                 smb_panic("smb_xmalloc: malloc fail.\n");
1788         return p;
1789 }
1790
1791 /**
1792  Memdup with smb_panic on fail.
1793 **/
1794 void *smb_xmemdup(const void *p, size_t size)
1795 {
1796         void *p2;
1797         p2 = smb_xmalloc(size);
1798         memcpy(p2, p, size);
1799         return p2;
1800 }
1801
1802 /**
1803  strdup that aborts on malloc fail.
1804 **/
1805 char *smb_xstrdup(const char *s)
1806 {
1807         char *s1 = strdup(s);
1808         if (!s1)
1809                 smb_panic("smb_xstrdup: malloc fail\n");
1810         return s1;
1811 }
1812
1813 /*
1814   vasprintf that aborts on malloc fail
1815 */
1816 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
1817 {
1818         int n;
1819         va_list ap2;
1820 #if defined(HAVE_VA_COPY)
1821         __va_copy(ap2, ap);
1822 #else
1823         ap2 = ap;
1824 #endif
1825         n = vasprintf(ptr, format, ap2);
1826         if (n == -1 || ! *ptr) {
1827                 smb_panic("smb_xvasprintf: out of memory");
1828         }
1829         return n;
1830 }
1831
1832 /*****************************************************************
1833 like strdup but for memory
1834  *****************************************************************/  
1835 void *memdup(const void *p, size_t size)
1836 {
1837         void *p2;
1838         if (size == 0) return NULL;
1839         p2 = malloc(size);
1840         if (!p2) return NULL;
1841         memcpy(p2, p, size);
1842         return p2;
1843 }
1844
1845 /*****************************************************************
1846 get local hostname and cache result
1847  *****************************************************************/  
1848 char *myhostname(void)
1849 {
1850         static pstring ret;
1851         if (ret[0] == 0) {
1852                 get_myname(ret);
1853         }
1854         return ret;
1855 }
1856
1857
1858 /*****************************************************************
1859 a useful function for returning a path in the Samba lock directory
1860  *****************************************************************/  
1861 char *lock_path(char *name)
1862 {
1863         static pstring fname;
1864
1865         pstrcpy(fname,lp_lockdir());
1866         trim_string(fname,"","/");
1867         
1868         if (!directory_exist(fname,NULL)) {
1869                 mkdir(fname,0755);
1870         }
1871         
1872         pstrcat(fname,"/");
1873         pstrcat(fname,name);
1874
1875         return fname;
1876 }
1877
1878 /*****************************************************************
1879 a useful function for returning a path in the Samba pid directory
1880  *****************************************************************/
1881 char *pid_path(char *name)
1882 {
1883         static pstring fname;
1884
1885         pstrcpy(fname,lp_piddir());
1886         trim_string(fname,"","/");
1887
1888         if (!directory_exist(fname,NULL)) {
1889                 mkdir(fname,0755);
1890         }
1891
1892         pstrcat(fname,"/");
1893         pstrcat(fname,name);
1894
1895         return fname;
1896 }
1897
1898
1899 /**
1900  * @brief Returns an absolute path to a file in the Samba lib directory.
1901  *
1902  * @param name File to find, relative to LIBDIR.
1903  *
1904  * @retval Pointer to a static #pstring containing the full path.
1905  **/
1906 char *lib_path(char *name)
1907 {
1908         static pstring fname;
1909         snprintf(fname, sizeof(fname), "%s/%s", dyn_LIBDIR, name);
1910         return fname;
1911 }
1912
1913 /*******************************************************************
1914  Given a filename - get its directory name
1915  NB: Returned in static storage.  Caveats:
1916  o  Not safe in thread environment.
1917  o  Caller must not free.
1918  o  If caller wishes to preserve, they should copy.
1919 ********************************************************************/
1920
1921 char *parent_dirname(const char *path)
1922 {
1923         static pstring dirpath;
1924         char *p;
1925
1926         if (!path)
1927                 return(NULL);
1928
1929         pstrcpy(dirpath, path);
1930         p = strrchr_m(dirpath, '/');  /* Find final '/', if any */
1931         if (!p) {
1932                 pstrcpy(dirpath, ".");    /* No final "/", so dir is "." */
1933         } else {
1934                 if (p == dirpath)
1935                         ++p;    /* For root "/", leave "/" in place */
1936                 *p = '\0';
1937         }
1938         return dirpath;
1939 }
1940
1941
1942 /*******************************************************************
1943 determine if a pattern contains any Microsoft wildcard characters
1944  *******************************************************************/
1945 BOOL ms_has_wild(char *s)
1946 {
1947         char c;
1948         while ((c = *s++)) {
1949                 switch (c) {
1950                 case '*':
1951                 case '?':
1952                 case '<':
1953                 case '>':
1954                 case '"':
1955                         return True;
1956                 }
1957         }
1958         return False;
1959 }
1960
1961 BOOL ms_has_wild_w(const smb_ucs2_t *s)
1962 {
1963         smb_ucs2_t c;
1964         if (!s) return False;
1965         while ((c = *s++)) {
1966                 switch (c) {
1967                 case UCS2_CHAR('*'):
1968                 case UCS2_CHAR('?'):
1969                 case UCS2_CHAR('<'):
1970                 case UCS2_CHAR('>'):
1971                 case UCS2_CHAR('"'):
1972                         return True;
1973                 }
1974         }
1975         return False;
1976 }
1977
1978 /*******************************************************************
1979  a wrapper that handles case sensitivity and the special handling
1980    of the ".." name
1981  *******************************************************************/
1982 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
1983 {
1984         fstring p2, s2;
1985
1986         if (strcmp(string,"..") == 0) string = ".";
1987         if (strcmp(pattern,".") == 0) return False;
1988         
1989         if (is_case_sensitive) {
1990                 return ms_fnmatch(pattern, string, Protocol) == 0;
1991         }
1992
1993         fstrcpy(p2, pattern);
1994         fstrcpy(s2, string);
1995         strlower(p2); 
1996         strlower(s2);
1997         return ms_fnmatch(p2, s2, Protocol) == 0;
1998 }
1999
2000 /*********************************************************
2001  Recursive routine that is called by unix_wild_match.
2002 *********************************************************/
2003
2004 static BOOL unix_do_match(char *regexp, char *str)
2005 {
2006         char *p;
2007
2008         for( p = regexp; *p && *str; ) {
2009
2010                 switch(*p) {
2011                         case '?':
2012                                 str++;
2013                                 p++;
2014                                 break;
2015
2016                         case '*':
2017
2018                                 /*
2019                                  * Look for a character matching 
2020                                  * the one after the '*'.
2021                                  */
2022                                 p++;
2023                                 if(!*p)
2024                                         return True; /* Automatic match */
2025                                 while(*str) {
2026
2027                                         while(*str && (*p != *str))
2028                                                 str++;
2029
2030                                         /*
2031                                          * Patch from weidel@multichart.de. In the case of the regexp
2032                                          * '*XX*' we want to ensure there are at least 2 'X' characters
2033                                          * in the string after the '*' for a match to be made.
2034                                          */
2035
2036                                         {
2037                                                 int matchcount=0;
2038
2039                                                 /*
2040                                                  * Eat all the characters that match, but count how many there were.
2041                                                  */
2042
2043                                                 while(*str && (*p == *str)) {
2044                                                         str++;
2045                                                         matchcount++;
2046                                                 }
2047
2048                                                 /*
2049                                                  * Now check that if the regexp had n identical characters that
2050                                                  * matchcount had at least that many matches.
2051                                                  */
2052
2053                                                 while ( *(p+1) && (*(p+1) == *p)) {
2054                                                         p++;
2055                                                         matchcount--;
2056                                                 }
2057
2058                                                 if ( matchcount <= 0 )
2059                                                         return False;
2060                                         }
2061
2062                                         str--; /* We've eaten the match char after the '*' */
2063
2064                                         if(unix_do_match(p, str))
2065                                                 return True;
2066
2067                                         if(!*str)
2068                                                 return False;
2069                                         else
2070                                                 str++;
2071                                 }
2072                                 return False;
2073
2074                         default:
2075                                 if(*str != *p)
2076                                         return False;
2077                                 str++;
2078                                 p++;
2079                                 break;
2080                 }
2081         }
2082
2083         if(!*p && !*str)
2084                 return True;
2085
2086         if (!*p && str[0] == '.' && str[1] == 0)
2087                 return(True);
2088   
2089         if (!*str && *p == '?') {
2090                 while (*p == '?')
2091                         p++;
2092                 return(!*p);
2093         }
2094
2095         if(!*str && (*p == '*' && p[1] == '\0'))
2096                 return True;
2097
2098         return False;
2099 }
2100
2101 /*******************************************************************
2102  Simple case insensitive interface to a UNIX wildcard matcher.
2103 *******************************************************************/
2104
2105 BOOL unix_wild_match(char *pattern, char *string)
2106 {
2107         pstring p2, s2;
2108         char *p;
2109
2110         pstrcpy(p2, pattern);
2111         pstrcpy(s2, string);
2112         strlower(p2);
2113         strlower(s2);
2114
2115         /* Remove any *? and ** from the pattern as they are meaningless */
2116         for(p = p2; *p; p++)
2117                 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2118                         pstrcpy( &p[1], &p[2]);
2119  
2120         if (strequal(p2,"*"))
2121                 return True;
2122
2123         return unix_do_match(p2, s2) == 0;      
2124 }
2125
2126 #ifdef __INSURE__
2127
2128 /*******************************************************************
2129 This routine is a trick to immediately catch errors when debugging
2130 with insure. A xterm with a gdb is popped up when insure catches
2131 a error. It is Linux specific.
2132 ********************************************************************/
2133 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2134 {
2135         static int (*fn)();
2136         int ret;
2137         char pidstr[10];
2138         /* you can get /usr/bin/backtrace from 
2139            http://samba.org/ftp/unpacked/junkcode/backtrace */
2140         pstring cmd = "/usr/bin/backtrace %d";
2141
2142         slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2143         pstring_sub(cmd, "%d", pidstr);
2144
2145         if (!fn) {
2146                 static void *h;
2147                 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2148                 fn = dlsym(h, "_Insure_trap_error");
2149
2150                 if (!h || h == _Insure_trap_error) {
2151                         h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2152                         fn = dlsym(h, "_Insure_trap_error");
2153                 }               
2154         }
2155
2156         ret = fn(a1, a2, a3, a4, a5, a6);
2157
2158         system(cmd);
2159
2160         return ret;
2161 }
2162 #endif