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