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