a bunch of fixes from the s\7fflight to seattle
[metze/samba/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_m(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                 uint32 *tn;
170                 
171                 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
172                 if (tn == NULL)
173                 {
174                         if (*num) free(*num);
175                         return NULL;
176                 }
177                 else (*num) = tn;
178                 (*num)[(*count)] = val;
179                 (*count)++;
180                 p++;
181         }
182
183         return p;
184 }
185
186
187 /*******************************************************************
188   check if a file exists - call vfs_file_exist for samba files
189 ********************************************************************/
190 BOOL file_exist(char *fname,SMB_STRUCT_STAT *sbuf)
191 {
192   SMB_STRUCT_STAT st;
193   if (!sbuf) sbuf = &st;
194   
195   if (sys_stat(fname,sbuf) != 0) 
196     return(False);
197
198   return(S_ISREG(sbuf->st_mode));
199 }
200
201 /*******************************************************************
202 check a files mod time
203 ********************************************************************/
204 time_t file_modtime(char *fname)
205 {
206   SMB_STRUCT_STAT st;
207   
208   if (sys_stat(fname,&st) != 0) 
209     return(0);
210
211   return(st.st_mtime);
212 }
213
214 /*******************************************************************
215   check if a directory exists
216 ********************************************************************/
217 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
218 {
219   SMB_STRUCT_STAT st2;
220   BOOL ret;
221
222   if (!st) st = &st2;
223
224   if (sys_stat(dname,st) != 0) 
225     return(False);
226
227   ret = S_ISDIR(st->st_mode);
228   if(!ret)
229     errno = ENOTDIR;
230   return ret;
231 }
232
233 /*******************************************************************
234 returns the size in bytes of the named file
235 ********************************************************************/
236 SMB_OFF_T get_file_size(char *file_name)
237 {
238   SMB_STRUCT_STAT buf;
239   buf.st_size = 0;
240   if(sys_stat(file_name,&buf) != 0)
241     return (SMB_OFF_T)-1;
242   return(buf.st_size);
243 }
244
245 /*******************************************************************
246 return a string representing an attribute for a file
247 ********************************************************************/
248 char *attrib_string(uint16 mode)
249 {
250   static fstring attrstr;
251
252   attrstr[0] = 0;
253
254   if (mode & aVOLID) fstrcat(attrstr,"V");
255   if (mode & aDIR) fstrcat(attrstr,"D");
256   if (mode & aARCH) fstrcat(attrstr,"A");
257   if (mode & aHIDDEN) fstrcat(attrstr,"H");
258   if (mode & aSYSTEM) fstrcat(attrstr,"S");
259   if (mode & aRONLY) fstrcat(attrstr,"R");        
260
261   return(attrstr);
262 }
263
264 /*******************************************************************
265   show a smb message structure
266 ********************************************************************/
267 void show_msg(char *buf)
268 {
269         int i;
270         int bcc=0;
271
272         if (DEBUGLEVEL < 5) return;
273
274         DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
275                         smb_len(buf),
276                         (int)CVAL(buf,smb_com),
277                         (int)CVAL(buf,smb_rcls),
278                         (int)CVAL(buf,smb_reh),
279                         (int)SVAL(buf,smb_err),
280                         (int)CVAL(buf,smb_flg),
281                         (int)SVAL(buf,smb_flg2)));
282         DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
283                         (int)SVAL(buf,smb_tid),
284                         (int)SVAL(buf,smb_pid),
285                         (int)SVAL(buf,smb_uid),
286                         (int)SVAL(buf,smb_mid),
287                         (int)CVAL(buf,smb_wct)));
288
289         for (i=0;i<(int)CVAL(buf,smb_wct);i++)
290         {
291                 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
292                         SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
293         }
294
295         bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
296
297         DEBUG(5,("smb_bcc=%d\n",bcc));
298
299         if (DEBUGLEVEL < 10) return;
300
301         if (DEBUGLEVEL < 50)
302         {
303                 bcc = MIN(bcc, 512);
304         }
305
306         dump_data(10, smb_buf(buf), bcc);
307 }
308
309 /*******************************************************************
310   set the length and marker of an smb packet
311 ********************************************************************/
312 void smb_setlen(char *buf,int len)
313 {
314   _smb_setlen(buf,len);
315
316   CVAL(buf,4) = 0xFF;
317   CVAL(buf,5) = 'S';
318   CVAL(buf,6) = 'M';
319   CVAL(buf,7) = 'B';
320 }
321
322 /*******************************************************************
323   setup the word count and byte count for a smb message
324 ********************************************************************/
325 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
326 {
327         if (zero)
328                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
329         CVAL(buf,smb_wct) = num_words;
330         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
331         smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
332         return (smb_size + num_words*2 + num_bytes);
333 }
334
335 /*******************************************************************
336   setup only the byte count for a smb message
337 ********************************************************************/
338 void set_message_bcc(char *buf,int num_bytes)
339 {
340         int num_words = CVAL(buf,smb_wct);
341         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
342         smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
343 }
344
345 /*******************************************************************
346   setup only the byte count for a smb message, using the end of the
347   message as a marker
348 ********************************************************************/
349 void set_message_end(void *outbuf,void *end_ptr)
350 {
351         set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
352 }
353
354 /*******************************************************************
355 reduce a file name, removing .. elements.
356 ********************************************************************/
357 void dos_clean_name(char *s)
358 {
359   char *p=NULL;
360
361   DEBUG(3,("dos_clean_name [%s]\n",s));
362
363   /* remove any double slashes */
364   all_string_sub(s, "\\\\", "\\", 0);
365
366   while ((p = strstr(s,"\\..\\")) != NULL)
367     {
368       pstring s1;
369
370       *p = 0;
371       pstrcpy(s1,p+3);
372
373       if ((p=strrchr_m(s,'\\')) != NULL)
374         *p = 0;
375       else
376         *s = 0;
377       pstrcat(s,s1);
378     }  
379
380   trim_string(s,NULL,"\\..");
381
382   all_string_sub(s, "\\.\\", "\\", 0);
383 }
384
385 /*******************************************************************
386 reduce a file name, removing .. elements. 
387 ********************************************************************/
388 void unix_clean_name(char *s)
389 {
390   char *p=NULL;
391
392   DEBUG(3,("unix_clean_name [%s]\n",s));
393
394   /* remove any double slashes */
395   all_string_sub(s, "//","/", 0);
396
397   /* Remove leading ./ characters */
398   if(strncmp(s, "./", 2) == 0) {
399     trim_string(s, "./", NULL);
400     if(*s == 0)
401       pstrcpy(s,"./");
402   }
403
404   while ((p = strstr(s,"/../")) != NULL)
405     {
406       pstring s1;
407
408       *p = 0;
409       pstrcpy(s1,p+3);
410
411       if ((p=strrchr_m(s,'/')) != NULL)
412         *p = 0;
413       else
414         *s = 0;
415       pstrcat(s,s1);
416     }  
417
418   trim_string(s,NULL,"/..");
419 }
420
421 /****************************************************************************
422   make a dir struct
423 ****************************************************************************/
424 void make_dir_struct(char *buf,char *mask,char *fname,SMB_OFF_T size,int mode,time_t date)
425 {  
426   char *p;
427   pstring mask2;
428
429   pstrcpy(mask2,mask);
430
431   if ((mode & aDIR) != 0)
432     size = 0;
433
434   memset(buf+1,' ',11);
435   if ((p = strchr_m(mask2,'.')) != NULL)
436     {
437       *p = 0;
438       push_ascii(buf+1,mask2,8, 0);
439       push_ascii(buf+9,p+1,3, 0);
440       *p = '.';
441     }
442   else
443       push_ascii(buf+1,mask2,11, 0);
444
445   memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
446   CVAL(buf,21) = mode;
447   put_dos_date(buf,22,date);
448   SSVAL(buf,26,size & 0xFFFF);
449   SSVAL(buf,28,(size >> 16)&0xFFFF);
450   push_ascii(buf+30,fname,12, 0);
451   if (!case_sensitive)
452     strupper(buf+30);
453   DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
454 }
455
456
457 /*******************************************************************
458 close the low 3 fd's and open dev/null in their place
459 ********************************************************************/
460 void close_low_fds(void)
461 {
462   int fd;
463   int i;
464   close(0); close(1); 
465 #ifndef __INSURE__
466   close(2);
467 #endif
468   /* try and use up these file descriptors, so silly
469      library routines writing to stdout etc won't cause havoc */
470   for (i=0;i<3;i++) {
471     fd = sys_open("/dev/null",O_RDWR,0);
472     if (fd < 0) fd = sys_open("/dev/null",O_WRONLY,0);
473     if (fd < 0) {
474       DEBUG(0,("Can't open /dev/null\n"));
475       return;
476     }
477     if (fd != i) {
478       DEBUG(0,("Didn't get file descriptor %d\n",i));
479       return;
480     }
481   }
482 }
483
484 /****************************************************************************
485 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
486 else
487 if SYSV use O_NDELAY
488 if BSD use FNDELAY
489 ****************************************************************************/
490 int set_blocking(int fd, BOOL set)
491 {
492   int val;
493 #ifdef O_NONBLOCK
494 #define FLAG_TO_SET O_NONBLOCK
495 #else
496 #ifdef SYSV
497 #define FLAG_TO_SET O_NDELAY
498 #else /* BSD */
499 #define FLAG_TO_SET FNDELAY
500 #endif
501 #endif
502
503   if((val = fcntl(fd, F_GETFL, 0)) == -1)
504         return -1;
505   if(set) /* Turn blocking on - ie. clear nonblock flag */
506         val &= ~FLAG_TO_SET;
507   else
508     val |= FLAG_TO_SET;
509   return fcntl( fd, F_SETFL, val);
510 #undef FLAG_TO_SET
511 }
512
513 /****************************************************************************
514 transfer some data between two fd's
515 ****************************************************************************/
516 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n,char *header,int headlen,int align)
517 {
518   static char *buf=NULL;  
519   static int size=0;
520   char *buf1,*abuf;
521   SMB_OFF_T total = 0;
522
523   DEBUG(4,("transfer_file n=%.0f  (head=%d) called\n",(double)n,headlen));
524
525   if (size == 0) {
526     size = lp_readsize();
527     size = MAX(size,1024);
528   }
529
530   while (!buf && size>0) {
531     buf = (char *)malloc(size+8);
532     if (!buf) size /= 2;
533   }
534
535   if (!buf) {
536     DEBUG(0,("Can't allocate transfer buffer!\n"));
537     exit(1);
538   }
539
540   abuf = buf + (align%8);
541
542   if (header)
543     n += headlen;
544
545   while (n > 0)
546   {
547     int s = (int)MIN(n,(SMB_OFF_T)size);
548     int ret,ret2=0;
549
550     ret = 0;
551
552     if (header && (headlen >= MIN(s,1024))) {
553       buf1 = header;
554       s = headlen;
555       ret = headlen;
556       headlen = 0;
557       header = NULL;
558     } else {
559       buf1 = abuf;
560     }
561
562     if (header && headlen > 0)
563     {
564       ret = MIN(headlen,size);
565       memcpy(buf1,header,ret);
566       headlen -= ret;
567       header += ret;
568       if (headlen <= 0) header = NULL;
569     }
570
571     if (s > ret)
572       ret += read(infd,buf1+ret,s-ret);
573
574     if (ret > 0)
575     {
576       ret2 = (outfd>=0?write_data(outfd,buf1,ret):ret);
577       if (ret2 > 0) total += ret2;
578       /* if we can't write then dump excess data */
579       if (ret2 != ret)
580         transfer_file(infd,-1,n-(ret+headlen),NULL,0,0);
581     }
582     if (ret <= 0 || ret2 != ret)
583       return(total);
584     n -= ret;
585   }
586   return(total);
587 }
588
589
590 /*******************************************************************
591 sleep for a specified number of milliseconds
592 ********************************************************************/
593 void msleep(int t)
594 {
595   int tdiff=0;
596   struct timeval tval,t1,t2;  
597   fd_set fds;
598
599   GetTimeOfDay(&t1);
600   GetTimeOfDay(&t2);
601   
602   while (tdiff < t) {
603     tval.tv_sec = (t-tdiff)/1000;
604     tval.tv_usec = 1000*((t-tdiff)%1000);
605  
606     FD_ZERO(&fds);
607     errno = 0;
608     sys_select_intr(0,&fds,&tval);
609
610     GetTimeOfDay(&t2);
611     tdiff = TvalDiff(&t1,&t2);
612   }
613 }
614
615
616 /****************************************************************************
617 become a daemon, discarding the controlling terminal
618 ****************************************************************************/
619 void become_daemon(void)
620 {
621         if (sys_fork()) {
622                 _exit(0);
623         }
624
625   /* detach from the terminal */
626 #ifdef HAVE_SETSID
627         setsid();
628 #elif defined(TIOCNOTTY)
629         {
630                 int i = sys_open("/dev/tty", O_RDWR, 0);
631                 if (i != -1) {
632                         ioctl(i, (int) TIOCNOTTY, (char *)0);      
633                         close(i);
634                 }
635         }
636 #endif /* HAVE_SETSID */
637
638         /* Close fd's 0,1,2. Needed if started by rsh */
639         close_low_fds();
640 }
641
642
643 /****************************************************************************
644 put up a yes/no prompt
645 ****************************************************************************/
646 BOOL yesno(char *p)
647 {
648   pstring ans;
649   printf("%s",p);
650
651   if (!fgets(ans,sizeof(ans)-1,stdin))
652     return(False);
653
654   if (*ans == 'y' || *ans == 'Y')
655     return(True);
656
657   return(False);
658 }
659
660 #ifdef HPUX
661 /****************************************************************************
662 this is a version of setbuffer() for those machines that only have setvbuf
663 ****************************************************************************/
664  void setbuffer(FILE *f,char *buf,int bufsize)
665 {
666   setvbuf(f,buf,_IOFBF,bufsize);
667 }
668 #endif
669
670 /****************************************************************************
671 expand a pointer to be a particular size
672 ****************************************************************************/
673 void *Realloc(void *p,size_t size)
674 {
675   void *ret=NULL;
676
677   if (size == 0) {
678     if (p) free(p);
679     DEBUG(5,("Realloc asked for 0 bytes\n"));
680     return NULL;
681   }
682
683   if (!p)
684     ret = (void *)malloc(size);
685   else
686     ret = (void *)realloc(p,size);
687
688   if (!ret)
689     DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
690
691   return(ret);
692 }
693
694
695 /****************************************************************************
696 free memory, checks for NULL
697 ****************************************************************************/
698 void safe_free(void *p)
699 {
700         if (p != NULL)
701         {
702                 free(p);
703         }
704 }
705
706
707 /****************************************************************************
708 get my own name and IP
709 ****************************************************************************/
710 BOOL get_myname(char *my_name)
711 {
712         pstring hostname;
713
714         *hostname = 0;
715
716         /* get my host name */
717         if (gethostname(hostname, sizeof(hostname)) == -1) {
718                 DEBUG(0,("gethostname failed\n"));
719                 return False;
720         } 
721
722         /* Ensure null termination. */
723         hostname[sizeof(hostname)-1] = '\0';
724
725         if (my_name) {
726                 /* split off any parts after an initial . */
727                 char *p = strchr_m(hostname,'.');
728                 if (p) *p = 0;
729                 
730                 fstrcpy(my_name,hostname);
731         }
732         
733         return(True);
734 }
735
736 /****************************************************************************
737 interpret a protocol description string, with a default
738 ****************************************************************************/
739 int interpret_protocol(char *str,int def)
740 {
741   if (strequal(str,"NT1"))
742     return(PROTOCOL_NT1);
743   if (strequal(str,"LANMAN2"))
744     return(PROTOCOL_LANMAN2);
745   if (strequal(str,"LANMAN1"))
746     return(PROTOCOL_LANMAN1);
747   if (strequal(str,"CORE"))
748     return(PROTOCOL_CORE);
749   if (strequal(str,"COREPLUS"))
750     return(PROTOCOL_COREPLUS);
751   if (strequal(str,"CORE+"))
752     return(PROTOCOL_COREPLUS);
753   
754   DEBUG(0,("Unrecognised protocol level %s\n",str));
755   
756   return(def);
757 }
758
759 /****************************************************************************
760  Return true if a string could be a pure IP address.
761 ****************************************************************************/
762
763 BOOL is_ipaddress(const char *str)
764 {
765   BOOL pure_address = True;
766   int i;
767   
768   for (i=0; pure_address && str[i]; i++)
769     if (!(isdigit((int)str[i]) || str[i] == '.'))
770       pure_address = False;
771
772   /* Check that a pure number is not misinterpreted as an IP */
773   pure_address = pure_address && (strchr_m(str, '.') != NULL);
774
775   return pure_address;
776 }
777
778 /****************************************************************************
779 interpret an internet address or name into an IP address in 4 byte form
780 ****************************************************************************/
781
782 uint32 interpret_addr(const char *str)
783 {
784   struct hostent *hp;
785   uint32 res;
786
787   if (strcmp(str,"0.0.0.0") == 0) return(0);
788   if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
789
790   /* if it's in the form of an IP address then get the lib to interpret it */
791   if (is_ipaddress(str)) {
792     res = inet_addr(str);
793   } else {
794     /* otherwise assume it's a network name of some sort and use 
795        sys_gethostbyname */
796     if ((hp = sys_gethostbyname(str)) == 0) {
797       DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
798       return 0;
799     }
800     if(hp->h_addr == NULL) {
801       DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
802       return 0;
803     }
804     putip((char *)&res,(char *)hp->h_addr);
805   }
806
807   if (res == (uint32)-1) return(0);
808
809   return(res);
810 }
811
812 /*******************************************************************
813   a convenient addition to interpret_addr()
814   ******************************************************************/
815 struct in_addr *interpret_addr2(const char *str)
816 {
817   static struct in_addr ret;
818   uint32 a = interpret_addr(str);
819   ret.s_addr = a;
820   return(&ret);
821 }
822
823 /*******************************************************************
824   check if an IP is the 0.0.0.0
825   ******************************************************************/
826 BOOL zero_ip(struct in_addr ip)
827 {
828   uint32 a;
829   putip((char *)&a,(char *)&ip);
830   return(a == 0);
831 }
832
833
834 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
835 /******************************************************************
836  Remove any mount options such as -rsize=2048,wsize=2048 etc.
837  Based on a fix from <Thomas.Hepper@icem.de>.
838 *******************************************************************/
839
840 static void strip_mount_options( pstring *str)
841 {
842   if (**str == '-')
843   { 
844     char *p = *str;
845     while(*p && !isspace(*p))
846       p++;
847     while(*p && isspace(*p))
848       p++;
849     if(*p) {
850       pstring tmp_str;
851
852       pstrcpy(tmp_str, p);
853       pstrcpy(*str, tmp_str);
854     }
855   }
856 }
857
858 /*******************************************************************
859  Patch from jkf@soton.ac.uk
860  Split Luke's automount_server into YP lookup and string splitter
861  so can easily implement automount_path(). 
862  As we may end up doing both, cache the last YP result. 
863 *******************************************************************/
864
865 #ifdef WITH_NISPLUS_HOME
866 char *automount_lookup(char *user_name)
867 {
868   static fstring last_key = "";
869   static pstring last_value = "";
870  
871   char *nis_map = (char *)lp_nis_home_map_name();
872  
873   char buffer[NIS_MAXATTRVAL + 1];
874   nis_result *result;
875   nis_object *object;
876   entry_obj  *entry;
877  
878   if (strcmp(user_name, last_key))
879   {
880     slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
881     DEBUG(5, ("NIS+ querystring: %s\n", buffer));
882  
883     if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL))
884     {
885        if (result->status != NIS_SUCCESS)
886       {
887         DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
888         fstrcpy(last_key, ""); pstrcpy(last_value, "");
889       }
890       else
891       {
892         object = result->objects.objects_val;
893         if (object->zo_data.zo_type == ENTRY_OBJ)
894         {
895            entry = &object->zo_data.objdata_u.en_data;
896            DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
897            DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
898  
899            pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
900            pstring_sub(last_value, "&", user_name);
901            fstrcpy(last_key, user_name);
902         }
903       }
904     }
905     nis_freeresult(result);
906   }
907
908   strip_mount_options(&last_value);
909
910   DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
911   return last_value;
912 }
913 #else /* WITH_NISPLUS_HOME */
914 char *automount_lookup(char *user_name)
915 {
916   static fstring last_key = "";
917   static pstring last_value = "";
918
919   int nis_error;        /* returned by yp all functions */
920   char *nis_result;     /* yp_match inits this */
921   int nis_result_len;  /* and set this */
922   char *nis_domain;     /* yp_get_default_domain inits this */
923   char *nis_map = (char *)lp_nis_home_map_name();
924
925   if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
926     DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
927     return last_value;
928   }
929
930   DEBUG(5, ("NIS Domain: %s\n", nis_domain));
931
932   if (!strcmp(user_name, last_key)) {
933         nis_result = last_value;
934     nis_result_len = strlen(last_value);
935     nis_error = 0;
936
937   } else {
938
939     if ((nis_error = yp_match(nis_domain, nis_map,
940                               user_name, strlen(user_name),
941                               &nis_result, &nis_result_len)) == 0) {
942        if (!nis_error && nis_result_len >= sizeof(pstring)) {
943                nis_result_len = sizeof(pstring)-1;
944        }
945        fstrcpy(last_key, user_name);
946        strncpy(last_value, nis_result, nis_result_len);
947        last_value[nis_result_len] = '\0';
948         strip_mount_options(&last_value);
949
950     } else if(nis_error == YPERR_KEY) {
951
952     /* If Key lookup fails user home server is not in nis_map 
953        use default information for server, and home directory */
954        last_value[0] = 0;
955        DEBUG(3, ("YP Key not found:  while looking up \"%s\" in map \"%s\"\n", 
956                 user_name, nis_map));
957        DEBUG(3, ("using defaults for server and home directory\n"));
958     } else {
959        DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n", 
960                yperr_string(nis_error), user_name, nis_map));
961     }
962   }
963
964
965   DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
966   return last_value;
967 }
968 #endif /* WITH_NISPLUS_HOME */
969 #endif
970
971
972 /*******************************************************************
973 are two IPs on the same subnet?
974 ********************************************************************/
975 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
976 {
977   uint32 net1,net2,nmask;
978
979   nmask = ntohl(mask.s_addr);
980   net1  = ntohl(ip1.s_addr);
981   net2  = ntohl(ip2.s_addr);
982             
983   return((net1 & nmask) == (net2 & nmask));
984 }
985
986
987 /****************************************************************************
988 check if a process exists. Does this work on all unixes?
989 ****************************************************************************/
990
991 BOOL process_exists(pid_t pid)
992 {
993         return(kill(pid,0) == 0 || errno != ESRCH);
994 }
995
996
997 /*******************************************************************
998  Convert a uid into a user name.
999 ********************************************************************/
1000
1001 char *uidtoname(uid_t uid)
1002 {
1003         static fstring name;
1004         struct passwd *pass;
1005
1006         if (winbind_uidtoname(name, uid))
1007                 return name;
1008
1009         pass = sys_getpwuid(uid);
1010         if (pass) return(pass->pw_name);
1011         slprintf(name, sizeof(name) - 1, "%d",(int)uid);
1012         return(name);
1013 }
1014
1015
1016 /*******************************************************************
1017  Convert a gid into a group name.
1018 ********************************************************************/
1019
1020 char *gidtoname(gid_t gid)
1021 {
1022         static fstring name;
1023         struct group *grp;
1024
1025         if (winbind_gidtoname(name, gid))
1026                 return name;
1027
1028         grp = getgrgid(gid);
1029         if (grp) return(grp->gr_name);
1030         slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1031         return(name);
1032 }
1033
1034 /*******************************************************************
1035  Convert a user name into a uid. If winbindd is present uses this.
1036 ********************************************************************/
1037
1038 uid_t nametouid(char *name)
1039 {
1040         struct passwd *pass;
1041         char *p;
1042         uid_t u;
1043
1044         u = (uid_t)strtol(name, &p, 0);
1045         if ((p != name) && (*p == '\0'))
1046                 return u;
1047
1048         if (winbind_nametouid(&u, name))
1049                 return u;
1050
1051         pass = sys_getpwnam(name);
1052         if (pass)
1053                 return(pass->pw_uid);
1054         return (uid_t)-1;
1055 }
1056
1057 /*******************************************************************
1058  Convert a name to a gid_t if possible. Return -1 if not a group. If winbindd
1059  is present does a shortcut lookup...
1060 ********************************************************************/
1061
1062 gid_t nametogid(char *name)
1063 {
1064         struct group *grp;
1065         char *p;
1066         gid_t g;
1067
1068         g = (gid_t)strtol(name, &p, 0);
1069         if ((p != name) && (*p == '\0'))
1070                 return g;
1071
1072         if (winbind_nametogid(&g, name))
1073                 return g;
1074
1075         grp = getgrnam(name);
1076         if (grp)
1077                 return(grp->gr_gid);
1078         return (gid_t)-1;
1079 }
1080
1081 /*******************************************************************
1082 something really nasty happened - panic!
1083 ********************************************************************/
1084 void smb_panic(char *why)
1085 {
1086         char *cmd = lp_panic_action();
1087         if (cmd && *cmd) {
1088                 system(cmd);
1089         }
1090         DEBUG(0,("PANIC: %s\n", why));
1091         dbgflush();
1092         abort();
1093 }
1094
1095
1096 /*******************************************************************
1097 a readdir wrapper which just returns the file name
1098 ********************************************************************/
1099 char *readdirname(DIR *p)
1100 {
1101         SMB_STRUCT_DIRENT *ptr;
1102         char *dname;
1103
1104         if (!p) return(NULL);
1105   
1106         ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1107         if (!ptr) return(NULL);
1108
1109         dname = ptr->d_name;
1110
1111 #ifdef NEXT2
1112         if (telldir(p) < 0) return(NULL);
1113 #endif
1114
1115 #ifdef HAVE_BROKEN_READDIR
1116         /* using /usr/ucb/cc is BAD */
1117         dname = dname - 2;
1118 #endif
1119
1120         {
1121                 static pstring buf;
1122                 int len = NAMLEN(ptr);
1123                 memcpy(buf, dname, len);
1124                 buf[len] = 0;
1125                 dname = buf;
1126         }
1127
1128         return(dname);
1129 }
1130
1131 /*******************************************************************
1132  Utility function used to decide if the last component 
1133  of a path matches a (possibly wildcarded) entry in a namelist.
1134 ********************************************************************/
1135
1136 BOOL is_in_path(char *name, name_compare_entry *namelist)
1137 {
1138   pstring last_component;
1139   char *p;
1140
1141   DEBUG(8, ("is_in_path: %s\n", name));
1142
1143   /* if we have no list it's obviously not in the path */
1144   if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) 
1145   {
1146     DEBUG(8,("is_in_path: no name list.\n"));
1147     return False;
1148   }
1149
1150   /* Get the last component of the unix name. */
1151   p = strrchr_m(name, '/');
1152   strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1153   last_component[sizeof(last_component)-1] = '\0'; 
1154
1155   for(; namelist->name != NULL; namelist++)
1156   {
1157     if(namelist->is_wild)
1158     {
1159       if (mask_match(last_component, namelist->name, case_sensitive))
1160       {
1161          DEBUG(8,("is_in_path: mask match succeeded\n"));
1162          return True;
1163       }
1164     }
1165     else
1166     {
1167       if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1168        (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
1169         {
1170          DEBUG(8,("is_in_path: match succeeded\n"));
1171          return True;
1172         }
1173     }
1174   }
1175   DEBUG(8,("is_in_path: match not found\n"));
1176  
1177   return False;
1178 }
1179
1180 /*******************************************************************
1181  Strip a '/' separated list into an array of 
1182  name_compare_enties structures suitable for 
1183  passing to is_in_path(). We do this for
1184  speed so we can pre-parse all the names in the list 
1185  and don't do it for each call to is_in_path().
1186  namelist is modified here and is assumed to be 
1187  a copy owned by the caller.
1188  We also check if the entry contains a wildcard to
1189  remove a potentially expensive call to mask_match
1190  if possible.
1191 ********************************************************************/
1192  
1193 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1194 {
1195   char *name_end;
1196   char *nameptr = namelist;
1197   int num_entries = 0;
1198   int i;
1199
1200   (*ppname_array) = NULL;
1201
1202   if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0'))) 
1203     return;
1204
1205   /* We need to make two passes over the string. The
1206      first to count the number of elements, the second
1207      to split it.
1208    */
1209   while(*nameptr) 
1210     {
1211       if ( *nameptr == '/' ) 
1212         {
1213           /* cope with multiple (useless) /s) */
1214           nameptr++;
1215           continue;
1216         }
1217       /* find the next / */
1218       name_end = strchr_m(nameptr, '/');
1219
1220       /* oops - the last check for a / didn't find one. */
1221       if (name_end == NULL)
1222         break;
1223
1224       /* next segment please */
1225       nameptr = name_end + 1;
1226       num_entries++;
1227     }
1228
1229   if(num_entries == 0)
1230     return;
1231
1232   if(( (*ppname_array) = (name_compare_entry *)malloc( 
1233            (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
1234         {
1235     DEBUG(0,("set_namearray: malloc fail\n"));
1236     return;
1237         }
1238
1239   /* Now copy out the names */
1240   nameptr = namelist;
1241   i = 0;
1242   while(*nameptr)
1243              {
1244       if ( *nameptr == '/' ) 
1245       {
1246           /* cope with multiple (useless) /s) */
1247           nameptr++;
1248           continue;
1249       }
1250       /* find the next / */
1251       if ((name_end = strchr_m(nameptr, '/')) != NULL) 
1252       {
1253           *name_end = 0;
1254          }
1255
1256       /* oops - the last check for a / didn't find one. */
1257       if(name_end == NULL) 
1258         break;
1259
1260       (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1261       if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
1262       {
1263         DEBUG(0,("set_namearray: malloc fail (1)\n"));
1264         return;
1265       }
1266
1267       /* next segment please */
1268       nameptr = name_end + 1;
1269       i++;
1270     }
1271   
1272   (*ppname_array)[i].name = NULL;
1273
1274   return;
1275 }
1276
1277 /****************************************************************************
1278 routine to free a namearray.
1279 ****************************************************************************/
1280
1281 void free_namearray(name_compare_entry *name_array)
1282 {
1283   if(name_array == 0)
1284     return;
1285
1286   if(name_array->name != NULL)
1287     free(name_array->name);
1288
1289   free((char *)name_array);
1290 }
1291
1292 /****************************************************************************
1293  Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1294  is dealt with in posix.c
1295 ****************************************************************************/
1296
1297 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1298 {
1299   SMB_STRUCT_FLOCK lock;
1300   int ret;
1301
1302   DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1303
1304   lock.l_type = type;
1305   lock.l_whence = SEEK_SET;
1306   lock.l_start = offset;
1307   lock.l_len = count;
1308   lock.l_pid = 0;
1309
1310   errno = 0;
1311
1312   ret = fcntl(fd,op,&lock);
1313
1314   if (errno != 0)
1315     DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1316
1317   /* a lock query */
1318   if (op == SMB_F_GETLK)
1319   {
1320     if ((ret != -1) &&
1321         (lock.l_type != F_UNLCK) && 
1322         (lock.l_pid != 0) && 
1323         (lock.l_pid != sys_getpid()))
1324     {
1325       DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1326       return(True);
1327     }
1328
1329     /* it must be not locked or locked by me */
1330     return(False);
1331   }
1332
1333   /* a lock set or unset */
1334   if (ret == -1)
1335   {
1336     DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1337           (double)offset,(double)count,op,type,strerror(errno)));
1338     return(False);
1339   }
1340
1341   /* everything went OK */
1342   DEBUG(8,("fcntl_lock: Lock call successful\n"));
1343
1344   return(True);
1345 }
1346
1347 /*******************************************************************
1348 is the name specified one of my netbios names
1349 returns true is it is equal, false otherwise
1350 ********************************************************************/
1351 BOOL is_myname(char *s)
1352 {
1353   int n;
1354   BOOL ret = False;
1355
1356   for (n=0; my_netbios_names[n]; n++) {
1357     if (strequal(my_netbios_names[n], s))
1358       ret=True;
1359   }
1360   DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1361   return(ret);
1362 }
1363
1364 /*******************************************************************
1365 set the horrid remote_arch string based on an enum.
1366 ********************************************************************/
1367 void set_remote_arch(enum remote_arch_types type)
1368 {
1369   extern fstring remote_arch;
1370   ra_type = type;
1371   switch( type )
1372   {
1373   case RA_WFWG:
1374     fstrcpy(remote_arch, "WfWg");
1375     return;
1376   case RA_OS2:
1377     fstrcpy(remote_arch, "OS2");
1378     return;
1379   case RA_WIN95:
1380     fstrcpy(remote_arch, "Win95");
1381     return;
1382   case RA_WINNT:
1383     fstrcpy(remote_arch, "WinNT");
1384     return;
1385   case RA_WIN2K:
1386     fstrcpy(remote_arch, "Win2K");
1387     return;
1388   case RA_SAMBA:
1389     fstrcpy(remote_arch,"Samba");
1390     return;
1391   default:
1392     ra_type = RA_UNKNOWN;
1393     fstrcpy(remote_arch, "UNKNOWN");
1394     break;
1395   }
1396 }
1397
1398 /*******************************************************************
1399  Get the remote_arch type.
1400 ********************************************************************/
1401 enum remote_arch_types get_remote_arch(void)
1402 {
1403   return ra_type;
1404 }
1405
1406
1407 void out_ascii(FILE *f, unsigned char *buf,int len)
1408 {
1409         int i;
1410         for (i=0;i<len;i++)
1411         {
1412                 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1413         }
1414 }
1415
1416 void out_data(FILE *f,char *buf1,int len, int per_line)
1417 {
1418         unsigned char *buf = (unsigned char *)buf1;
1419         int i=0;
1420         if (len<=0)
1421         {
1422                 return;
1423         }
1424
1425         fprintf(f, "[%03X] ",i);
1426         for (i=0;i<len;)
1427         {
1428                 fprintf(f, "%02X ",(int)buf[i]);
1429                 i++;
1430                 if (i%(per_line/2) == 0) fprintf(f, " ");
1431                 if (i%per_line == 0)
1432                 {      
1433                         out_ascii(f,&buf[i-per_line  ],per_line/2); fprintf(f, " ");
1434                         out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1435                         if (i<len) fprintf(f, "[%03X] ",i);
1436                 }
1437         }
1438         if ((i%per_line) != 0)
1439         {
1440                 int n;
1441
1442                 n = per_line - (i%per_line);
1443                 fprintf(f, " ");
1444                 if (n>(per_line/2)) fprintf(f, " ");
1445                 while (n--)
1446                 {
1447                         fprintf(f, "   ");
1448                 }
1449                 n = MIN(per_line/2,i%per_line);
1450                 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1451                 n = (i%per_line) - n;
1452                 if (n>0) out_ascii(f,&buf[i-n],n); 
1453                 fprintf(f, "\n");    
1454         }
1455 }
1456
1457 void print_asc(int level, const unsigned char *buf,int len)
1458 {
1459         int i;
1460         for (i=0;i<len;i++)
1461                 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1462 }
1463
1464 void dump_data(int level, const char *buf1,int len)
1465 {
1466   const unsigned char *buf = (const unsigned char *)buf1;
1467   int i=0;
1468   if (len<=0) return;
1469
1470   DEBUG(level,("[%03X] ",i));
1471   for (i=0;i<len;) {
1472     DEBUG(level,("%02X ",(int)buf[i]));
1473     i++;
1474     if (i%8 == 0) DEBUG(level,(" "));
1475     if (i%16 == 0) {      
1476       print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
1477       print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
1478       if (i<len) DEBUG(level,("[%03X] ",i));
1479     }
1480   }
1481   if (i%16) {
1482     int n;
1483
1484     n = 16 - (i%16);
1485     DEBUG(level,(" "));
1486     if (n>8) DEBUG(level,(" "));
1487     while (n--) DEBUG(level,("   "));
1488
1489     n = MIN(8,i%16);
1490     print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
1491     n = (i%16) - n;
1492     if (n>0) print_asc(level,&buf[i-n],n); 
1493     DEBUG(level,("\n"));    
1494   }
1495 }
1496
1497 char *tab_depth(int depth)
1498 {
1499         static pstring spaces;
1500         memset(spaces, ' ', depth * 4);
1501         spaces[depth * 4] = 0;
1502         return spaces;
1503 }
1504
1505 /*****************************************************************************
1506  * Provide a checksum on a string
1507  *
1508  *  Input:  s - the null-terminated character string for which the checksum
1509  *              will be calculated.
1510  *
1511  *  Output: The checksum value calculated for s.
1512  *
1513  * ****************************************************************************
1514  */
1515 int str_checksum(const char *s)
1516 {
1517         int res = 0;
1518         int c;
1519         int i=0;
1520         
1521         while(*s) {
1522                 c = *s;
1523                 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1524                 s++;
1525                 i++;
1526         }
1527         return(res);
1528 } /* str_checksum */
1529
1530
1531
1532 /*****************************************************************
1533 zero a memory area then free it. Used to catch bugs faster
1534 *****************************************************************/  
1535 void zero_free(void *p, size_t size)
1536 {
1537         memset(p, 0, size);
1538         free(p);
1539 }
1540
1541
1542 /*****************************************************************
1543 set our open file limit to a requested max and return the limit
1544 *****************************************************************/  
1545 int set_maxfiles(int requested_max)
1546 {
1547 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1548         struct rlimit rlp;
1549         int saved_current_limit;
1550
1551         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1552                 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1553                         strerror(errno) ));
1554                 /* just guess... */
1555                 return requested_max;
1556         }
1557
1558         /* 
1559      * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1560          * account for the extra fd we need 
1561          * as well as the log files and standard
1562          * handles etc. Save the limit we want to set in case
1563          * we are running on an OS that doesn't support this limit (AIX)
1564          * which always returns RLIM_INFINITY for rlp.rlim_max.
1565          */
1566
1567         /* Try raising the hard (max) limit to the requested amount. */
1568
1569 #if defined(RLIM_INFINITY)
1570         if (rlp.rlim_max != RLIM_INFINITY) {
1571                 int orig_max = rlp.rlim_max;
1572
1573                 if ( rlp.rlim_max < requested_max )
1574                         rlp.rlim_max = requested_max;
1575
1576                 /* This failing is not an error - many systems (Linux) don't
1577                         support our default request of 10,000 open files. JRA. */
1578
1579                 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1580                         DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n", 
1581                                 (int)rlp.rlim_max, strerror(errno) ));
1582
1583                         /* Set failed - restore original value from get. */
1584                         rlp.rlim_max = orig_max;
1585                 }
1586         }
1587 #endif
1588
1589         /* Now try setting the soft (current) limit. */
1590
1591         saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1592
1593         if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1594                 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n", 
1595                         (int)rlp.rlim_cur, strerror(errno) ));
1596                 /* just guess... */
1597                 return saved_current_limit;
1598         }
1599
1600         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1601                 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1602                         strerror(errno) ));
1603                 /* just guess... */
1604                 return saved_current_limit;
1605     }
1606
1607 #if defined(RLIM_INFINITY)
1608         if(rlp.rlim_cur == RLIM_INFINITY)
1609                 return saved_current_limit;
1610 #endif
1611
1612     if((int)rlp.rlim_cur > saved_current_limit)
1613                 return saved_current_limit;
1614
1615         return rlp.rlim_cur;
1616 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1617         /*
1618          * No way to know - just guess...
1619          */
1620         return requested_max;
1621 #endif
1622 }
1623
1624 /*****************************************************************
1625  splits out the start of the key (HKLM or HKU) and the rest of the key
1626  *****************************************************************/  
1627 BOOL reg_split_key(char *full_keyname, uint32 *reg_type, char *key_name)
1628 {
1629         pstring tmp;
1630
1631         if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1632         {
1633                 return False;
1634         }
1635
1636         (*reg_type) = 0;
1637
1638         DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1639
1640         if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1641         {
1642                 (*reg_type) = HKEY_LOCAL_MACHINE;
1643         }
1644         else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1645         {
1646                 (*reg_type) = HKEY_USERS;
1647         }
1648         else
1649         {
1650                 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1651                 return False;
1652         }
1653         
1654         if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
1655         {
1656                 fstrcpy(key_name, tmp);
1657         }
1658         else
1659         {
1660                 key_name[0] = 0;
1661         }
1662
1663         DEBUG(10, ("reg_split_key: name %s\n", key_name));
1664
1665         return True;
1666 }
1667
1668
1669 /*****************************************************************
1670 possibly replace mkstemp if it is broken
1671 *****************************************************************/  
1672 int smb_mkstemp(char *template)
1673 {
1674 #if HAVE_SECURE_MKSTEMP
1675         return mkstemp(template);
1676 #else
1677         /* have a reasonable go at emulating it. Hope that
1678            the system mktemp() isn't completly hopeless */
1679         char *p = mktemp(template);
1680         if (!p) return -1;
1681         return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
1682 #endif
1683 }
1684
1685 /*****************************************************************
1686 like strdup but for memory
1687  *****************************************************************/  
1688 void *memdup(void *p, size_t size)
1689 {
1690         void *p2;
1691         if (size == 0) return NULL;
1692         p2 = malloc(size);
1693         if (!p2) return NULL;
1694         memcpy(p2, p, size);
1695         return p2;
1696 }
1697
1698 /*****************************************************************
1699 get local hostname and cache result
1700  *****************************************************************/  
1701 char *myhostname(void)
1702 {
1703         static pstring ret;
1704         if (ret[0] == 0) {
1705                 get_myname(ret);
1706         }
1707         return ret;
1708 }
1709
1710
1711 /*****************************************************************
1712 a useful function for returning a path in the Samba lock directory
1713  *****************************************************************/  
1714 char *lock_path(char *name)
1715 {
1716         static pstring fname;
1717
1718         pstrcpy(fname,lp_lockdir());
1719         trim_string(fname,"","/");
1720         
1721         if (!directory_exist(fname,NULL)) {
1722                 mkdir(fname,0755);
1723         }
1724         
1725         pstrcat(fname,"/");
1726         pstrcat(fname,name);
1727
1728         return fname;
1729 }
1730
1731 /*******************************************************************
1732  Given a filename - get its directory name
1733  NB: Returned in static storage.  Caveats:
1734  o  Not safe in thread environment.
1735  o  Caller must not free.
1736  o  If caller wishes to preserve, they should copy.
1737 ********************************************************************/
1738
1739 char *parent_dirname(const char *path)
1740 {
1741         static pstring dirpath;
1742         char *p;
1743
1744         if (!path)
1745                 return(NULL);
1746
1747         pstrcpy(dirpath, path);
1748         p = strrchr_m(dirpath, '/');  /* Find final '/', if any */
1749         if (!p) {
1750                 pstrcpy(dirpath, ".");    /* No final "/", so dir is "." */
1751         } else {
1752                 if (p == dirpath)
1753                         ++p;    /* For root "/", leave "/" in place */
1754                 *p = '\0';
1755         }
1756         return dirpath;
1757 }
1758
1759
1760 /*******************************************************************
1761 determine if a pattern contains any Microsoft wildcard characters
1762  *******************************************************************/
1763 BOOL ms_has_wild(char *s)
1764 {
1765         char c;
1766         while ((c = *s++)) {
1767                 switch (c) {
1768                 case '*':
1769                 case '?':
1770                 case '<':
1771                 case '>':
1772                 case '"':
1773                         return True;
1774                 }
1775         }
1776         return False;
1777 }
1778
1779 /*******************************************************************
1780  a wrapper that handles case sensitivity and the special handling
1781    of the ".." name
1782  *******************************************************************/
1783 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
1784 {
1785         extern int Protocol;
1786         fstring p2, s2;
1787
1788         if (strcmp(string,"..") == 0) string = ".";
1789         if (strcmp(pattern,".") == 0) return False;
1790         
1791         if (is_case_sensitive) {
1792                 return ms_fnmatch(pattern, string, Protocol) == 0;
1793         }
1794
1795         fstrcpy(p2, pattern);
1796         fstrcpy(s2, string);
1797         strlower(p2); 
1798         strlower(s2);
1799         return ms_fnmatch(p2, s2, Protocol) == 0;
1800 }
1801
1802 /*******************************************************************
1803  Simple case insensitive interface to ms_fnmatch.
1804 *******************************************************************/
1805  
1806 BOOL wild_match(char *string, char *pattern)
1807 {
1808         pstring p2, s2;
1809         extern int Protocol;
1810
1811         pstrcpy(p2, pattern);
1812         pstrcpy(s2, string);
1813         strlower(p2);
1814         strlower(s2);
1815         return ms_fnmatch(p2, s2, Protocol) == 0;
1816 }
1817
1818 #ifdef __INSURE__
1819
1820 /*******************************************************************
1821 This routine is a trick to immediately catch errors when debugging
1822 with insure. A xterm with a gdb is popped up when insure catches
1823 a error. It is Linux specific.
1824 ********************************************************************/
1825 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1826 {
1827         static int (*fn)();
1828         int ret;
1829         char pidstr[10];
1830         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'";
1831
1832         slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
1833         pstring_sub(cmd, "%d", pidstr);
1834
1835         if (!fn) {
1836                 static void *h;
1837                 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1838                 fn = dlsym(h, "_Insure_trap_error");
1839         }
1840
1841         ret = fn(a1, a2, a3, a4, a5, a6);
1842
1843         system(cmd);
1844
1845         return ret;
1846 }
1847 #endif