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