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