Got "medieval on our ass" about adding the -1 to slprintf.
[ira/wip.git] / source3 / lib / util.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Samba utility functions
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
25 #ifdef WITH_NISPLUS_HOME
26 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
27 /*
28  * The following lines are needed due to buggy include files
29  * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
30  * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
31  * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
32  * an enum in /usr/include/rpcsvc/nis.h.
33  */
34
35 #if defined(GROUP)
36 #undef GROUP
37 #endif
38
39 #if defined(GROUP_OBJ)
40 #undef GROUP_OBJ
41 #endif
42
43 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
44
45 #include <rpcsvc/nis.h>
46
47 #else /* !WITH_NISPLUS_HOME */
48
49 #include "rpcsvc/ypclnt.h"
50
51 #endif /* WITH_NISPLUS_HOME */
52 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
53
54 #ifdef WITH_SSL
55 #include <ssl.h>
56 #undef Realloc  /* SSLeay defines this and samba has a function of this name */
57 extern SSL  *ssl;
58 extern int  sslFd;
59 #endif  /* WITH_SSL */
60
61 extern int DEBUGLEVEL;
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   }
104   return "/tmp";
105 }
106
107 /****************************************************************************
108 determine whether we are in the specified group
109 ****************************************************************************/
110
111 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, gid_t *groups)
112 {
113         int i;
114
115         if (group == current_gid) 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 /****************************************************************************
126 like atoi but gets the value up to the separater character
127 ****************************************************************************/
128 char *Atoic(char *p, int *n, char *c)
129 {
130         if (!isdigit((int)*p))
131         {
132                 DEBUG(5, ("Atoic: malformed number\n"));
133                 return NULL;
134         }
135
136         (*n) = atoi(p);
137
138         while ((*p) && isdigit((int)*p))
139         {
140                 p++;
141         }
142
143         if (strchr(c, *p) == NULL)
144         {
145                 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
146                 return NULL;
147         }
148
149         return p;
150 }
151
152 /*************************************************************************
153  reads a list of numbers
154  *************************************************************************/
155 char *get_numlist(char *p, uint32 **num, int *count)
156 {
157         int val;
158
159         if (num == NULL || count == NULL)
160         {
161                 return NULL;
162         }
163
164         (*count) = 0;
165         (*num  ) = NULL;
166
167         while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':')
168         {
169                 (*num) = Realloc((*num), ((*count)+1) * sizeof(uint32));
170                 if ((*num) == NULL)
171                 {
172                         return NULL;
173                 }
174                 (*num)[(*count)] = val;
175                 (*count)++;
176                 p++;
177         }
178
179         return p;
180 }
181
182
183 /*******************************************************************
184   check if a file exists - call vfs_file_exist for samba files
185 ********************************************************************/
186 BOOL file_exist(char *fname,SMB_STRUCT_STAT *sbuf)
187 {
188   SMB_STRUCT_STAT st;
189   if (!sbuf) 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   rename a unix file
199 ********************************************************************/
200 int file_rename(char *from, char *to)
201 {
202         int rcode = rename (from, to);
203
204         if (errno == EXDEV) 
205         {
206                 /* Rename across filesystems needed. */
207                 rcode = copy_reg (from, to);        
208         }
209         return rcode;
210 }
211
212 /*******************************************************************
213 check a files mod time
214 ********************************************************************/
215 time_t file_modtime(char *fname)
216 {
217   SMB_STRUCT_STAT st;
218   
219   if (sys_stat(fname,&st) != 0) 
220     return(0);
221
222   return(st.st_mtime);
223 }
224
225 /*******************************************************************
226   check if a directory exists
227 ********************************************************************/
228 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
229 {
230   SMB_STRUCT_STAT st2;
231   BOOL ret;
232
233   if (!st) st = &st2;
234
235   if (sys_stat(dname,st) != 0) 
236     return(False);
237
238   ret = S_ISDIR(st->st_mode);
239   if(!ret)
240     errno = ENOTDIR;
241   return ret;
242 }
243
244 /*******************************************************************
245 returns the size in bytes of the named file
246 ********************************************************************/
247 SMB_OFF_T get_file_size(char *file_name)
248 {
249   SMB_STRUCT_STAT buf;
250   buf.st_size = 0;
251   if(sys_stat(file_name,&buf) != 0)
252     return (SMB_OFF_T)-1;
253   return(buf.st_size);
254 }
255
256 /*******************************************************************
257 return a string representing an attribute for a file
258 ********************************************************************/
259 char *attrib_string(uint16 mode)
260 {
261   static fstring attrstr;
262
263   attrstr[0] = 0;
264
265   if (mode & aVOLID) fstrcat(attrstr,"V");
266   if (mode & aDIR) fstrcat(attrstr,"D");
267   if (mode & aARCH) fstrcat(attrstr,"A");
268   if (mode & aHIDDEN) fstrcat(attrstr,"H");
269   if (mode & aSYSTEM) fstrcat(attrstr,"S");
270   if (mode & aRONLY) fstrcat(attrstr,"R");        
271
272   return(attrstr);
273 }
274
275 /*******************************************************************
276   show a smb message structure
277 ********************************************************************/
278 void show_msg(char *buf)
279 {
280         int i;
281         int bcc=0;
282
283         if (DEBUGLEVEL < 5) return;
284
285         DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
286                         smb_len(buf),
287                         (int)CVAL(buf,smb_com),
288                         (int)CVAL(buf,smb_rcls),
289                         (int)CVAL(buf,smb_reh),
290                         (int)SVAL(buf,smb_err),
291                         (int)CVAL(buf,smb_flg),
292                         (int)SVAL(buf,smb_flg2)));
293         DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
294                         (int)SVAL(buf,smb_tid),
295                         (int)SVAL(buf,smb_pid),
296                         (int)SVAL(buf,smb_uid),
297                         (int)SVAL(buf,smb_mid),
298                         (int)CVAL(buf,smb_wct)));
299
300         for (i=0;i<(int)CVAL(buf,smb_wct);i++)
301         {
302                 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
303                         SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
304         }
305
306         bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
307
308         DEBUG(5,("smb_bcc=%d\n",bcc));
309
310         if (DEBUGLEVEL < 10) return;
311
312         if (DEBUGLEVEL < 50)
313         {
314                 bcc = MIN(bcc, 512);
315         }
316
317         dump_data(10, smb_buf(buf), bcc);
318 }
319
320 /*******************************************************************
321   set the length and marker of an smb packet
322 ********************************************************************/
323 void smb_setlen(char *buf,int len)
324 {
325   _smb_setlen(buf,len);
326
327   CVAL(buf,4) = 0xFF;
328   CVAL(buf,5) = 'S';
329   CVAL(buf,6) = 'M';
330   CVAL(buf,7) = 'B';
331 }
332
333 /*******************************************************************
334   setup the word count and byte count for a smb message
335 ********************************************************************/
336 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
337 {
338         if (zero)
339                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
340         CVAL(buf,smb_wct) = num_words;
341         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
342         smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
343         return (smb_size + num_words*2 + num_bytes);
344 }
345
346 /*******************************************************************
347   setup only the byte count for a smb message
348 ********************************************************************/
349 void set_message_bcc(char *buf,int num_bytes)
350 {
351         int num_words = CVAL(buf,smb_wct);
352         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
353         smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
354 }
355
356 /*******************************************************************
357   setup only the byte count for a smb message, using the end of the
358   message as a marker
359 ********************************************************************/
360 void set_message_end(void *outbuf,void *end_ptr)
361 {
362         set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
363 }
364
365 /*******************************************************************
366 reduce a file name, removing .. elements.
367 ********************************************************************/
368 void dos_clean_name(char *s)
369 {
370   char *p=NULL;
371
372   DEBUG(3,("dos_clean_name [%s]\n",s));
373
374   /* remove any double slashes */
375   all_string_sub(s, "\\\\", "\\", 0);
376
377   while ((p = strstr(s,"\\..\\")) != NULL)
378     {
379       pstring s1;
380
381       *p = 0;
382       pstrcpy(s1,p+3);
383
384       if ((p=strrchr(s,'\\')) != NULL)
385         *p = 0;
386       else
387         *s = 0;
388       pstrcat(s,s1);
389     }  
390
391   trim_string(s,NULL,"\\..");
392
393   all_string_sub(s, "\\.\\", "\\", 0);
394 }
395
396 /*******************************************************************
397 reduce a file name, removing .. elements. 
398 ********************************************************************/
399 void unix_clean_name(char *s)
400 {
401   char *p=NULL;
402
403   DEBUG(3,("unix_clean_name [%s]\n",s));
404
405   /* remove any double slashes */
406   all_string_sub(s, "//","/", 0);
407
408   /* Remove leading ./ characters */
409   if(strncmp(s, "./", 2) == 0) {
410     trim_string(s, "./", NULL);
411     if(*s == 0)
412       pstrcpy(s,"./");
413   }
414
415   while ((p = strstr(s,"/../")) != NULL)
416     {
417       pstring s1;
418
419       *p = 0;
420       pstrcpy(s1,p+3);
421
422       if ((p=strrchr(s,'/')) != NULL)
423         *p = 0;
424       else
425         *s = 0;
426       pstrcat(s,s1);
427     }  
428
429   trim_string(s,NULL,"/..");
430 }
431
432 /****************************************************************************
433   make a dir struct
434 ****************************************************************************/
435 void make_dir_struct(char *buf,char *mask,char *fname,SMB_OFF_T size,int mode,time_t date)
436 {  
437   char *p;
438   pstring mask2;
439
440   pstrcpy(mask2,mask);
441
442   if ((mode & aDIR) != 0)
443     size = 0;
444
445   memset(buf+1,' ',11);
446   if ((p = strchr(mask2,'.')) != NULL)
447     {
448       *p = 0;
449       memcpy(buf+1,mask2,MIN(strlen(mask2),8));
450       memcpy(buf+9,p+1,MIN(strlen(p+1),3));
451       *p = '.';
452     }
453   else
454     memcpy(buf+1,mask2,MIN(strlen(mask2),11));
455
456   memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
457   CVAL(buf,21) = mode;
458   put_dos_date(buf,22,date);
459   SSVAL(buf,26,size & 0xFFFF);
460   SSVAL(buf,28,(size >> 16)&0xFFFF);
461   StrnCpy(buf+30,fname,12);
462   if (!case_sensitive)
463     strupper(buf+30);
464   DEBUG(8,("put name [%s] into dir struct\n",buf+30));
465 }
466
467
468 /*******************************************************************
469 close the low 3 fd's and open dev/null in their place
470 ********************************************************************/
471 void close_low_fds(void)
472 {
473   int fd;
474   int i;
475   close(0); close(1); 
476 #ifndef __INSURE__
477   close(2);
478 #endif
479   /* try and use up these file descriptors, so silly
480      library routines writing to stdout etc won't cause havoc */
481   for (i=0;i<3;i++) {
482     fd = sys_open("/dev/null",O_RDWR,0);
483     if (fd < 0) fd = sys_open("/dev/null",O_WRONLY,0);
484     if (fd < 0) {
485       DEBUG(0,("Can't open /dev/null\n"));
486       return;
487     }
488     if (fd != i) {
489       DEBUG(0,("Didn't get file descriptor %d\n",i));
490       return;
491     }
492   }
493 }
494
495 /****************************************************************************
496 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
497 else
498 if SYSV use O_NDELAY
499 if BSD use FNDELAY
500 ****************************************************************************/
501 int set_blocking(int fd, BOOL set)
502 {
503   int val;
504 #ifdef O_NONBLOCK
505 #define FLAG_TO_SET O_NONBLOCK
506 #else
507 #ifdef SYSV
508 #define FLAG_TO_SET O_NDELAY
509 #else /* BSD */
510 #define FLAG_TO_SET FNDELAY
511 #endif
512 #endif
513
514   if((val = fcntl(fd, F_GETFL, 0)) == -1)
515         return -1;
516   if(set) /* Turn blocking on - ie. clear nonblock flag */
517         val &= ~FLAG_TO_SET;
518   else
519     val |= FLAG_TO_SET;
520   return fcntl( fd, F_SETFL, val);
521 #undef FLAG_TO_SET
522 }
523
524 /****************************************************************************
525 transfer some data between two fd's
526 ****************************************************************************/
527 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n,char *header,int headlen,int align)
528 {
529   static char *buf=NULL;  
530   static int size=0;
531   char *buf1,*abuf;
532   SMB_OFF_T total = 0;
533
534   DEBUG(4,("transfer_file n=%.0f  (head=%d) called\n",(double)n,headlen));
535
536   if (size == 0) {
537     size = lp_readsize();
538     size = MAX(size,1024);
539   }
540
541   while (!buf && size>0) {
542     buf = (char *)Realloc(buf,size+8);
543     if (!buf) size /= 2;
544   }
545
546   if (!buf) {
547     DEBUG(0,("Can't allocate transfer buffer!\n"));
548     exit(1);
549   }
550
551   abuf = buf + (align%8);
552
553   if (header)
554     n += headlen;
555
556   while (n > 0)
557   {
558     int s = (int)MIN(n,(SMB_OFF_T)size);
559     int ret,ret2=0;
560
561     ret = 0;
562
563     if (header && (headlen >= MIN(s,1024))) {
564       buf1 = header;
565       s = headlen;
566       ret = headlen;
567       headlen = 0;
568       header = NULL;
569     } else {
570       buf1 = abuf;
571     }
572
573     if (header && headlen > 0)
574     {
575       ret = MIN(headlen,size);
576       memcpy(buf1,header,ret);
577       headlen -= ret;
578       header += ret;
579       if (headlen <= 0) header = NULL;
580     }
581
582     if (s > ret)
583       ret += read(infd,buf1+ret,s-ret);
584
585     if (ret > 0)
586     {
587       ret2 = (outfd>=0?write_data(outfd,buf1,ret):ret);
588       if (ret2 > 0) total += ret2;
589       /* if we can't write then dump excess data */
590       if (ret2 != ret)
591         transfer_file(infd,-1,n-(ret+headlen),NULL,0,0);
592     }
593     if (ret <= 0 || ret2 != ret)
594       return(total);
595     n -= ret;
596   }
597   return(total);
598 }
599
600
601 /*******************************************************************
602 sleep for a specified number of milliseconds
603 ********************************************************************/
604 void msleep(int t)
605 {
606   int tdiff=0;
607   struct timeval tval,t1,t2;  
608   fd_set fds;
609
610   GetTimeOfDay(&t1);
611   GetTimeOfDay(&t2);
612   
613   while (tdiff < t) {
614     tval.tv_sec = (t-tdiff)/1000;
615     tval.tv_usec = 1000*((t-tdiff)%1000);
616  
617     FD_ZERO(&fds);
618     errno = 0;
619     sys_select_intr(0,&fds,&tval);
620
621     GetTimeOfDay(&t2);
622     tdiff = TvalDiff(&t1,&t2);
623   }
624 }
625
626
627 /****************************************************************************
628 become a daemon, discarding the controlling terminal
629 ****************************************************************************/
630 void become_daemon(void)
631 {
632         if (sys_fork()) {
633                 _exit(0);
634         }
635
636   /* detach from the terminal */
637 #ifdef HAVE_SETSID
638         setsid();
639 #elif defined(TIOCNOTTY)
640         {
641                 int i = sys_open("/dev/tty", O_RDWR, 0);
642                 if (i != -1) {
643                         ioctl(i, (int) TIOCNOTTY, (char *)0);      
644                         close(i);
645                 }
646         }
647 #endif /* HAVE_SETSID */
648
649         /* Close fd's 0,1,2. Needed if started by rsh */
650         close_low_fds();
651 }
652
653
654 /****************************************************************************
655 put up a yes/no prompt
656 ****************************************************************************/
657 BOOL yesno(char *p)
658 {
659   pstring ans;
660   printf("%s",p);
661
662   if (!fgets(ans,sizeof(ans)-1,stdin))
663     return(False);
664
665   if (*ans == 'y' || *ans == 'Y')
666     return(True);
667
668   return(False);
669 }
670
671 #ifdef HPUX
672 /****************************************************************************
673 this is a version of setbuffer() for those machines that only have setvbuf
674 ****************************************************************************/
675  void setbuffer(FILE *f,char *buf,int bufsize)
676 {
677   setvbuf(f,buf,_IOFBF,bufsize);
678 }
679 #endif
680
681 /****************************************************************************
682 expand a pointer to be a particular size
683 ****************************************************************************/
684 void *Realloc(void *p,size_t size)
685 {
686   void *ret=NULL;
687
688   if (size == 0) {
689     if (p) free(p);
690     DEBUG(5,("Realloc asked for 0 bytes\n"));
691     return NULL;
692   }
693
694   if (!p)
695     ret = (void *)malloc(size);
696   else
697     ret = (void *)realloc(p,size);
698
699   if (!ret)
700     DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
701
702   return(ret);
703 }
704
705
706 /****************************************************************************
707 free memory, checks for NULL
708 ****************************************************************************/
709 void safe_free(void *p)
710 {
711         if (p != NULL)
712         {
713                 free(p);
714         }
715 }
716
717
718 /****************************************************************************
719 get my own name and IP
720 ****************************************************************************/
721 BOOL get_myname(char *my_name)
722 {
723         pstring hostname;
724
725         *hostname = 0;
726
727         /* get my host name */
728         if (gethostname(hostname, sizeof(hostname)) == -1) {
729                 DEBUG(0,("gethostname failed\n"));
730                 return False;
731         } 
732
733         /* Ensure null termination. */
734         hostname[sizeof(hostname)-1] = '\0';
735
736         if (my_name) {
737                 /* split off any parts after an initial . */
738                 char *p = strchr(hostname,'.');
739                 if (p) *p = 0;
740                 
741                 fstrcpy(my_name,hostname);
742         }
743         
744         return(True);
745 }
746
747 /****************************************************************************
748 interpret a protocol description string, with a default
749 ****************************************************************************/
750 int interpret_protocol(char *str,int def)
751 {
752   if (strequal(str,"NT1"))
753     return(PROTOCOL_NT1);
754   if (strequal(str,"LANMAN2"))
755     return(PROTOCOL_LANMAN2);
756   if (strequal(str,"LANMAN1"))
757     return(PROTOCOL_LANMAN1);
758   if (strequal(str,"CORE"))
759     return(PROTOCOL_CORE);
760   if (strequal(str,"COREPLUS"))
761     return(PROTOCOL_COREPLUS);
762   if (strequal(str,"CORE+"))
763     return(PROTOCOL_COREPLUS);
764   
765   DEBUG(0,("Unrecognised protocol level %s\n",str));
766   
767   return(def);
768 }
769
770 /****************************************************************************
771  Return true if a string could be a pure IP address.
772 ****************************************************************************/
773
774 BOOL is_ipaddress(const char *str)
775 {
776   BOOL pure_address = True;
777   int i;
778   
779   for (i=0; pure_address && str[i]; i++)
780     if (!(isdigit((int)str[i]) || str[i] == '.'))
781       pure_address = False;
782
783   /* Check that a pure number is not misinterpreted as an IP */
784   pure_address = pure_address && (strchr(str, '.') != NULL);
785
786   return pure_address;
787 }
788
789 /****************************************************************************
790 interpret an internet address or name into an IP address in 4 byte form
791 ****************************************************************************/
792
793 uint32 interpret_addr(char *str)
794 {
795   struct hostent *hp;
796   uint32 res;
797
798   if (strcmp(str,"0.0.0.0") == 0) return(0);
799   if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
800
801   /* if it's in the form of an IP address then get the lib to interpret it */
802   if (is_ipaddress(str)) {
803     res = inet_addr(str);
804   } else {
805     /* otherwise assume it's a network name of some sort and use 
806        Get_Hostbyname */
807     if ((hp = Get_Hostbyname(str)) == 0) {
808       DEBUG(3,("Get_Hostbyname: Unknown host. %s\n",str));
809       return 0;
810     }
811     if(hp->h_addr == NULL) {
812       DEBUG(3,("Get_Hostbyname: host address is invalid for host %s\n",str));
813       return 0;
814     }
815     putip((char *)&res,(char *)hp->h_addr);
816   }
817
818   if (res == (uint32)-1) return(0);
819
820   return(res);
821 }
822
823 /*******************************************************************
824   a convenient addition to interpret_addr()
825   ******************************************************************/
826 struct in_addr *interpret_addr2(char *str)
827 {
828   static struct in_addr ret;
829   uint32 a = interpret_addr(str);
830   ret.s_addr = a;
831   return(&ret);
832 }
833
834 /*******************************************************************
835   check if an IP is the 0.0.0.0
836   ******************************************************************/
837 BOOL zero_ip(struct in_addr ip)
838 {
839   uint32 a;
840   putip((char *)&a,(char *)&ip);
841   return(a == 0);
842 }
843
844
845 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
846 /******************************************************************
847  Remove any mount options such as -rsize=2048,wsize=2048 etc.
848  Based on a fix from <Thomas.Hepper@icem.de>.
849 *******************************************************************/
850
851 static void strip_mount_options( pstring *str)
852 {
853   if (**str == '-')
854   { 
855     char *p = *str;
856     while(*p && !isspace(*p))
857       p++;
858     while(*p && isspace(*p))
859       p++;
860     if(*p) {
861       pstring tmp_str;
862
863       pstrcpy(tmp_str, p);
864       pstrcpy(*str, tmp_str);
865     }
866   }
867 }
868
869 /*******************************************************************
870  Patch from jkf@soton.ac.uk
871  Split Luke's automount_server into YP lookup and string splitter
872  so can easily implement automount_path(). 
873  As we may end up doing both, cache the last YP result. 
874 *******************************************************************/
875
876 #ifdef WITH_NISPLUS_HOME
877 static char *automount_lookup(char *user_name)
878 {
879   static fstring last_key = "";
880   static pstring last_value = "";
881  
882   char *nis_map = (char *)lp_nis_home_map_name();
883  
884   char nis_domain[NIS_MAXNAMELEN + 1];
885   char buffer[NIS_MAXATTRVAL + 1];
886   nis_result *result;
887   nis_object *object;
888   entry_obj  *entry;
889  
890   strncpy(nis_domain, (char *)nis_local_directory(), NIS_MAXNAMELEN);
891   nis_domain[NIS_MAXNAMELEN] = '\0';
892  
893   DEBUG(5, ("NIS+ Domain: %s\n", nis_domain));
894  
895   if (strcmp(user_name, last_key))
896   {
897     slprintf(buffer, sizeof(buffer)-1, "[%s=%s]%s.%s", "key", user_name, nis_map, nis_domain);
898     DEBUG(5, ("NIS+ querystring: %s\n", buffer));
899  
900     if (result = nis_list(buffer, RETURN_RESULT, NULL, NULL))
901     {
902        if (result->status != NIS_SUCCESS)
903       {
904         DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
905         fstrcpy(last_key, ""); pstrcpy(last_value, "");
906       }
907       else
908       {
909         object = result->objects.objects_val;
910         if (object->zo_data.zo_type == ENTRY_OBJ)
911         {
912            entry = &object->zo_data.objdata_u.en_data;
913            DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
914            DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
915  
916            pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
917            pstring_sub(last_value, "&", user_name);
918            fstrcpy(last_key, user_name);
919         }
920       }
921     }
922     nis_freeresult(result);
923   }
924
925   strip_mount_options(&last_value);
926
927   DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
928   return last_value;
929 }
930 #else /* WITH_NISPLUS_HOME */
931 static char *automount_lookup(char *user_name)
932 {
933   static fstring last_key = "";
934   static pstring last_value = "";
935
936   int nis_error;        /* returned by yp all functions */
937   char *nis_result;     /* yp_match inits this */
938   int nis_result_len;  /* and set this */
939   char *nis_domain;     /* yp_get_default_domain inits this */
940   char *nis_map = (char *)lp_nis_home_map_name();
941
942   if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
943     DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
944     return last_value;
945   }
946
947   DEBUG(5, ("NIS Domain: %s\n", nis_domain));
948
949   if (!strcmp(user_name, last_key)) {
950         nis_result = last_value;
951     nis_result_len = strlen(last_value);
952     nis_error = 0;
953
954   } else {
955
956     if ((nis_error = yp_match(nis_domain, nis_map,
957                               user_name, strlen(user_name),
958                               &nis_result, &nis_result_len)) == 0) {
959        if (!nis_error && nis_result_len >= sizeof(pstring)) {
960                nis_result_len = sizeof(pstring)-1;
961        }
962        fstrcpy(last_key, user_name);
963        strncpy(last_value, nis_result, nis_result_len);
964        last_value[nis_result_len] = '\0';
965         strip_mount_options(&last_value);
966
967     } else if(nis_error == YPERR_KEY) {
968
969     /* If Key lookup fails user home server is not in nis_map 
970        use default information for server, and home directory */
971        last_value[0] = 0;
972        DEBUG(3, ("YP Key not found:  while looking up \"%s\" in map \"%s\"\n", 
973                 user_name, nis_map));
974        DEBUG(3, ("using defaults for server and home directory\n"));
975     } else {
976        DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n", 
977                yperr_string(nis_error), user_name, nis_map));
978     }
979   }
980
981
982   DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
983   return last_value;
984 }
985 #endif /* WITH_NISPLUS_HOME */
986 #endif
987
988
989 /*******************************************************************
990 are two IPs on the same subnet?
991 ********************************************************************/
992 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
993 {
994   uint32 net1,net2,nmask;
995
996   nmask = ntohl(mask.s_addr);
997   net1  = ntohl(ip1.s_addr);
998   net2  = ntohl(ip2.s_addr);
999             
1000   return((net1 & nmask) == (net2 & nmask));
1001 }
1002
1003
1004 /****************************************************************************
1005 a wrapper for gethostbyname() that tries with all lower and all upper case 
1006 if the initial name fails
1007 ****************************************************************************/
1008 struct hostent *Get_Hostbyname(const char *name)
1009 {
1010   char *name2 = strdup(name);
1011   struct hostent *ret;
1012
1013   if (!name2)
1014     {
1015       DEBUG(0,("Memory allocation error in Get_Hostbyname! panic\n"));
1016       exit(0);
1017     }
1018
1019    
1020   /* 
1021    * This next test is redundent and causes some systems (with
1022    * broken isalnum() calls) problems.
1023    * JRA.
1024    */
1025
1026 #if 0
1027   if (!isalnum(*name2))
1028     {
1029       free(name2);
1030       return(NULL);
1031     }
1032 #endif /* 0 */
1033
1034   ret = sys_gethostbyname(name2);
1035   if (ret != NULL)
1036     {
1037       free(name2);
1038       return(ret);
1039     }
1040
1041   /* try with all lowercase */
1042   strlower(name2);
1043   ret = sys_gethostbyname(name2);
1044   if (ret != NULL)
1045     {
1046       free(name2);
1047       return(ret);
1048     }
1049
1050   /* try with all uppercase */
1051   strupper(name2);
1052   ret = sys_gethostbyname(name2);
1053   if (ret != NULL)
1054     {
1055       free(name2);
1056       return(ret);
1057     }
1058   
1059   /* nothing works :-( */
1060   free(name2);
1061   return(NULL);
1062 }
1063
1064
1065 /****************************************************************************
1066 check if a process exists. Does this work on all unixes?
1067 ****************************************************************************/
1068
1069 BOOL process_exists(pid_t pid)
1070 {
1071         return(kill(pid,0) == 0 || errno != ESRCH);
1072 }
1073
1074
1075 /*******************************************************************
1076  Convert a uid into a user name.
1077 ********************************************************************/
1078
1079 char *uidtoname(uid_t uid)
1080 {
1081         static fstring name;
1082         struct passwd *pass;
1083
1084         if (winbind_uidtoname(name, uid))
1085                 return name;
1086
1087         pass = sys_getpwuid(uid);
1088         if (pass) return(pass->pw_name);
1089         slprintf(name, sizeof(name) - 1, "%d",(int)uid);
1090         return(name);
1091 }
1092
1093
1094 /*******************************************************************
1095  Convert a gid into a group name.
1096 ********************************************************************/
1097
1098 char *gidtoname(gid_t gid)
1099 {
1100         static fstring name;
1101         struct group *grp;
1102
1103         if (winbind_gidtoname(name, gid))
1104                 return name;
1105
1106         grp = getgrgid(gid);
1107         if (grp) return(grp->gr_name);
1108         slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1109         return(name);
1110 }
1111
1112 /*******************************************************************
1113  Convert a user name into a uid. If winbindd is present uses this.
1114 ********************************************************************/
1115
1116 uid_t nametouid(char *name)
1117 {
1118         struct passwd *pass;
1119         char *p;
1120         uid_t u;
1121
1122         u = (uid_t)strtol(name, &p, 0);
1123         if (p != name) return u;
1124
1125         if (winbind_nametouid(&u, name))
1126                 return u;
1127
1128         pass = sys_getpwnam(name);
1129         if (pass) return(pass->pw_uid);
1130         return (uid_t)-1;
1131 }
1132
1133 /*******************************************************************
1134  Convert a name to a gid_t if possible. Return -1 if not a group. If winbindd
1135  is present does a shortcut lookup...
1136 ********************************************************************/
1137
1138 gid_t nametogid(char *name)
1139 {
1140         struct group *grp;
1141         char *p;
1142         gid_t g;
1143
1144         g = (gid_t)strtol(name, &p, 0);
1145         if (p != name) return g;
1146
1147         if (winbind_nametogid(&g, name))
1148                 return g;
1149
1150         grp = getgrnam(name);
1151         if (grp) return(grp->gr_gid);
1152         return (gid_t)-1;
1153 }
1154
1155 /*******************************************************************
1156 something really nasty happened - panic!
1157 ********************************************************************/
1158 void smb_panic(char *why)
1159 {
1160         char *cmd = lp_panic_action();
1161         if (cmd && *cmd) {
1162                 system(cmd);
1163         }
1164         DEBUG(0,("PANIC: %s\n", why));
1165         dbgflush();
1166         abort();
1167 }
1168
1169
1170 /*******************************************************************
1171 a readdir wrapper which just returns the file name
1172 ********************************************************************/
1173 char *readdirname(DIR *p)
1174 {
1175         SMB_STRUCT_DIRENT *ptr;
1176         char *dname;
1177
1178         if (!p) return(NULL);
1179   
1180         ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1181         if (!ptr) return(NULL);
1182
1183         dname = ptr->d_name;
1184
1185 #ifdef NEXT2
1186         if (telldir(p) < 0) return(NULL);
1187 #endif
1188
1189 #ifdef HAVE_BROKEN_READDIR
1190         /* using /usr/ucb/cc is BAD */
1191         dname = dname - 2;
1192 #endif
1193
1194         {
1195                 static pstring buf;
1196                 memcpy(buf, dname, NAMLEN(ptr)+1);
1197                 dname = buf;
1198         }
1199
1200         return(dname);
1201 }
1202
1203 /*******************************************************************
1204  Utility function used to decide if the last component 
1205  of a path matches a (possibly wildcarded) entry in a namelist.
1206 ********************************************************************/
1207
1208 BOOL is_in_path(char *name, name_compare_entry *namelist)
1209 {
1210   pstring last_component;
1211   char *p;
1212
1213   DEBUG(8, ("is_in_path: %s\n", name));
1214
1215   /* if we have no list it's obviously not in the path */
1216   if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) 
1217   {
1218     DEBUG(8,("is_in_path: no name list.\n"));
1219     return False;
1220   }
1221
1222   /* Get the last component of the unix name. */
1223   p = strrchr(name, '/');
1224   strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1225   last_component[sizeof(last_component)-1] = '\0'; 
1226
1227   for(; namelist->name != NULL; namelist++)
1228   {
1229     if(namelist->is_wild)
1230     {
1231       if (mask_match(last_component, namelist->name, case_sensitive))
1232       {
1233          DEBUG(8,("is_in_path: mask match succeeded\n"));
1234          return True;
1235       }
1236     }
1237     else
1238     {
1239       if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1240        (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
1241         {
1242          DEBUG(8,("is_in_path: match succeeded\n"));
1243          return True;
1244         }
1245     }
1246   }
1247   DEBUG(8,("is_in_path: match not found\n"));
1248  
1249   return False;
1250 }
1251
1252 /*******************************************************************
1253  Strip a '/' separated list into an array of 
1254  name_compare_enties structures suitable for 
1255  passing to is_in_path(). We do this for
1256  speed so we can pre-parse all the names in the list 
1257  and don't do it for each call to is_in_path().
1258  namelist is modified here and is assumed to be 
1259  a copy owned by the caller.
1260  We also check if the entry contains a wildcard to
1261  remove a potentially expensive call to mask_match
1262  if possible.
1263 ********************************************************************/
1264  
1265 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1266 {
1267   char *name_end;
1268   char *nameptr = namelist;
1269   int num_entries = 0;
1270   int i;
1271
1272   (*ppname_array) = NULL;
1273
1274   if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0'))) 
1275     return;
1276
1277   /* We need to make two passes over the string. The
1278      first to count the number of elements, the second
1279      to split it.
1280    */
1281   while(*nameptr) 
1282     {
1283       if ( *nameptr == '/' ) 
1284         {
1285           /* cope with multiple (useless) /s) */
1286           nameptr++;
1287           continue;
1288         }
1289       /* find the next / */
1290       name_end = strchr(nameptr, '/');
1291
1292       /* oops - the last check for a / didn't find one. */
1293       if (name_end == NULL)
1294         break;
1295
1296       /* next segment please */
1297       nameptr = name_end + 1;
1298       num_entries++;
1299     }
1300
1301   if(num_entries == 0)
1302     return;
1303
1304   if(( (*ppname_array) = (name_compare_entry *)malloc( 
1305            (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
1306         {
1307     DEBUG(0,("set_namearray: malloc fail\n"));
1308     return;
1309         }
1310
1311   /* Now copy out the names */
1312   nameptr = namelist;
1313   i = 0;
1314   while(*nameptr)
1315              {
1316       if ( *nameptr == '/' ) 
1317       {
1318           /* cope with multiple (useless) /s) */
1319           nameptr++;
1320           continue;
1321       }
1322       /* find the next / */
1323       if ((name_end = strchr(nameptr, '/')) != NULL) 
1324       {
1325           *name_end = 0;
1326          }
1327
1328       /* oops - the last check for a / didn't find one. */
1329       if(name_end == NULL) 
1330         break;
1331
1332       (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1333       if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
1334       {
1335         DEBUG(0,("set_namearray: malloc fail (1)\n"));
1336         return;
1337       }
1338
1339       /* next segment please */
1340       nameptr = name_end + 1;
1341       i++;
1342     }
1343   
1344   (*ppname_array)[i].name = NULL;
1345
1346   return;
1347 }
1348
1349 /****************************************************************************
1350 routine to free a namearray.
1351 ****************************************************************************/
1352
1353 void free_namearray(name_compare_entry *name_array)
1354 {
1355   if(name_array == 0)
1356     return;
1357
1358   if(name_array->name != NULL)
1359     free(name_array->name);
1360
1361   free((char *)name_array);
1362 }
1363
1364 /****************************************************************************
1365  Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1366  is dealt with in posix.c
1367 ****************************************************************************/
1368
1369 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1370 {
1371   SMB_STRUCT_FLOCK lock;
1372   int ret;
1373
1374   DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1375
1376   lock.l_type = type;
1377   lock.l_whence = SEEK_SET;
1378   lock.l_start = offset;
1379   lock.l_len = count;
1380   lock.l_pid = 0;
1381
1382   errno = 0;
1383
1384   ret = fcntl(fd,op,&lock);
1385
1386   if (errno != 0)
1387     DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1388
1389   /* a lock query */
1390   if (op == SMB_F_GETLK)
1391   {
1392     if ((ret != -1) &&
1393         (lock.l_type != F_UNLCK) && 
1394         (lock.l_pid != 0) && 
1395         (lock.l_pid != sys_getpid()))
1396     {
1397       DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1398       return(True);
1399     }
1400
1401     /* it must be not locked or locked by me */
1402     return(False);
1403   }
1404
1405   /* a lock set or unset */
1406   if (ret == -1)
1407   {
1408     DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1409           (double)offset,(double)count,op,type,strerror(errno)));
1410     return(False);
1411   }
1412
1413   /* everything went OK */
1414   DEBUG(8,("fcntl_lock: Lock call successful\n"));
1415
1416   return(True);
1417 }
1418
1419 /*******************************************************************
1420 is the name specified one of my netbios names
1421 returns true is it is equal, false otherwise
1422 ********************************************************************/
1423 BOOL is_myname(char *s)
1424 {
1425   int n;
1426   BOOL ret = False;
1427
1428   for (n=0; my_netbios_names[n]; n++) {
1429     if (strequal(my_netbios_names[n], s))
1430       ret=True;
1431   }
1432   DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1433   return(ret);
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, 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,char *buf1,int len)
1537 {
1538   unsigned char *buf = (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         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         saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1640
1641         if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1642                 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n", 
1643                         (int)rlp.rlim_cur, strerror(errno) ));
1644                 /* just guess... */
1645                 return saved_current_limit;
1646         }
1647
1648         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1649                 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1650                         strerror(errno) ));
1651                 /* just guess... */
1652                 return saved_current_limit;
1653     }
1654
1655 #if defined(RLIM_INFINITY)
1656         if(rlp.rlim_cur == RLIM_INFINITY)
1657                 return saved_current_limit;
1658 #endif
1659
1660     if((int)rlp.rlim_cur > saved_current_limit)
1661                 return saved_current_limit;
1662
1663         return rlp.rlim_cur;
1664 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1665         /*
1666          * No way to know - just guess...
1667          */
1668         return requested_max;
1669 #endif
1670 }
1671
1672 /*****************************************************************
1673  splits out the start of the key (HKLM or HKU) and the rest of the key
1674  *****************************************************************/  
1675 BOOL reg_split_key(char *full_keyname, uint32 *reg_type, char *key_name)
1676 {
1677         pstring tmp;
1678
1679         if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1680         {
1681                 return False;
1682         }
1683
1684         (*reg_type) = 0;
1685
1686         DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1687
1688         if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1689         {
1690                 (*reg_type) = HKEY_LOCAL_MACHINE;
1691         }
1692         else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1693         {
1694                 (*reg_type) = HKEY_USERS;
1695         }
1696         else
1697         {
1698                 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1699                 return False;
1700         }
1701         
1702         if (next_token(NULL, tmp, "\n\r", sizeof(tmp)))
1703         {
1704                 fstrcpy(key_name, tmp);
1705         }
1706         else
1707         {
1708                 key_name[0] = 0;
1709         }
1710
1711         DEBUG(10, ("reg_split_key: name %s\n", key_name));
1712
1713         return True;
1714 }
1715
1716
1717 /*****************************************************************
1718 like mktemp() but make sure that no % characters are used
1719 % characters are bad for us because of the macro subs
1720  *****************************************************************/  
1721 char *smbd_mktemp(char *template)
1722 {
1723         char *p = mktemp(template);
1724         char *p2;
1725         SMB_STRUCT_STAT st;
1726
1727         if (!p) return NULL;
1728
1729         while ((p2=strchr(p,'%'))) {
1730                 p2[0] = 'A';
1731                 while (sys_stat(p,&st) == 0 && p2[0] < 'Z') {
1732                         /* damn, it exists */
1733                         p2[0]++;
1734                 }
1735                 if (p2[0] == 'Z') {
1736                         /* oh well ... better return something */
1737                         p2[0] = '%';
1738                         return p;
1739                 }
1740         }
1741
1742         return p;
1743 }
1744
1745
1746 /*****************************************************************
1747 like strdup but for memory
1748  *****************************************************************/  
1749 void *memdup(void *p, size_t size)
1750 {
1751         void *p2;
1752         if (size == 0) return NULL;
1753         p2 = malloc(size);
1754         if (!p2) return NULL;
1755         memcpy(p2, p, size);
1756         return p2;
1757 }
1758
1759 /*****************************************************************
1760 get local hostname and cache result
1761  *****************************************************************/  
1762 char *myhostname(void)
1763 {
1764         static pstring ret;
1765         if (ret[0] == 0) {
1766                 get_myname(ret);
1767         }
1768         return ret;
1769 }
1770
1771
1772 /*****************************************************************
1773 a useful function for returning a path in the Samba lock directory
1774  *****************************************************************/  
1775 char *lock_path(char *name)
1776 {
1777         static pstring fname;
1778
1779         pstrcpy(fname,lp_lockdir());
1780         trim_string(fname,"","/");
1781         
1782         if (!directory_exist(fname,NULL)) {
1783                 mkdir(fname,0755);
1784         }
1785         
1786         pstrcat(fname,"/");
1787         pstrcat(fname,name);
1788
1789         return fname;
1790 }
1791
1792 /*******************************************************************
1793  Given a filename - get its directory name
1794  NB: Returned in static storage.  Caveats:
1795  o  Not safe in thread environment.
1796  o  Caller must not free.
1797  o  If caller wishes to preserve, they should copy.
1798 ********************************************************************/
1799
1800 char *parent_dirname(const char *path)
1801 {
1802         static pstring dirpath;
1803         char *p;
1804
1805         if (!path)
1806                 return(NULL);
1807
1808         pstrcpy(dirpath, path);
1809         p = strrchr(dirpath, '/');  /* Find final '/', if any */
1810         if (!p) {
1811                 pstrcpy(dirpath, ".");    /* No final "/", so dir is "." */
1812         } else {
1813                 if (p == dirpath)
1814                         ++p;    /* For root "/", leave "/" in place */
1815                 *p = '\0';
1816         }
1817         return dirpath;
1818 }
1819
1820
1821 /*******************************************************************
1822 determine if a pattern contains any Microsoft wildcard characters
1823  *******************************************************************/
1824 BOOL ms_has_wild(char *s)
1825 {
1826         char c;
1827         while ((c = *s++)) {
1828                 switch (c) {
1829                 case '*':
1830                 case '?':
1831                 case '<':
1832                 case '>':
1833                 case '"':
1834                         return True;
1835                 }
1836         }
1837         return False;
1838 }
1839
1840
1841 /*******************************************************************
1842  a wrapper that handles case sensitivity and the special handling
1843    of the ".." name
1844  *******************************************************************/
1845 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
1846 {
1847         fstring p2, s2;
1848         if (strcmp(string,"..") == 0) string = ".";
1849         if (strcmp(pattern,".") == 0) return False;
1850         
1851         if (is_case_sensitive) {
1852                 return ms_fnmatch(pattern, string) == 0;
1853         }
1854
1855         fstrcpy(p2, pattern);
1856         fstrcpy(s2, string);
1857         strlower(p2); 
1858         strlower(s2);
1859         return ms_fnmatch(p2, s2) == 0;
1860 }
1861
1862
1863
1864 #ifdef __INSURE__
1865
1866 /*******************************************************************
1867 This routine is a trick to immediately catch errors when debugging
1868 with insure. A xterm with a gdb is popped up when insure catches
1869 a error. It is Linux specific.
1870 ********************************************************************/
1871 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1872 {
1873         static int (*fn)();
1874         int ret;
1875         char pidstr[10];
1876         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'";
1877
1878         slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
1879         pstring_sub(cmd, "%d", pidstr);
1880
1881         if (!fn) {
1882                 static void *h;
1883                 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1884                 fn = dlsym(h, "_Insure_trap_error");
1885         }
1886
1887         ret = fn(a1, a2, a3, a4, a5, a6);
1888
1889         system(cmd);
1890
1891         return ret;
1892 }
1893 #endif