a big one:
[kai/samba.git] / source / lib / util.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Samba utility functions
5    Copyright (C) Andrew Tridgell 1992-1998
6    Copyright (C) Jeremy Allison 2001
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24
25 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
26 #ifdef WITH_NISPLUS_HOME
27 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
28 /*
29  * The following lines are needed due to buggy include files
30  * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
31  * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
32  * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
33  * an enum in /usr/include/rpcsvc/nis.h.
34  */
35
36 #if defined(GROUP)
37 #undef GROUP
38 #endif
39
40 #if defined(GROUP_OBJ)
41 #undef GROUP_OBJ
42 #endif
43
44 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
45
46 #include <rpcsvc/nis.h>
47
48 #else /* !WITH_NISPLUS_HOME */
49
50 #include "rpcsvc/ypclnt.h"
51
52 #endif /* WITH_NISPLUS_HOME */
53 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
54
55 #ifdef WITH_SSL
56 #include <openssl/ssl.h>
57 #undef Realloc  /* SSLeay defines this and samba has a function of this name */
58 extern SSL  *ssl;
59 extern int  sslFd;
60 #endif  /* WITH_SSL */
61
62 int Protocol = PROTOCOL_COREPLUS;
63
64 /* a default finfo structure to ensure all fields are sensible */
65 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
66
67 /* this is used by the chaining code */
68 int chain_size = 0;
69
70 int trans_num = 0;
71
72 /*
73    case handling on filenames 
74 */
75 int case_default = CASE_LOWER;
76
77 /* the following control case operations - they are put here so the
78    client can link easily */
79 BOOL case_sensitive;
80 BOOL case_preserve;
81 BOOL use_mangled_map = False;
82 BOOL short_case_preserve;
83 BOOL case_mangle;
84
85 static enum remote_arch_types ra_type = RA_UNKNOWN;
86 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;   
87
88 pstring global_myname = "";
89 fstring global_myworkgroup = "";
90 char **my_netbios_names;
91
92
93 /****************************************************************************
94   find a suitable temporary directory. The result should be copied immediately
95   as it may be overwritten by a subsequent call
96   ****************************************************************************/
97 char *tmpdir(void)
98 {
99   char *p;
100   if ((p = getenv("TMPDIR"))) {
101     return p;
102   }
103   return "/tmp";
104 }
105
106 /****************************************************************************
107 determine whether we are in the specified group
108 ****************************************************************************/
109
110 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, gid_t *groups)
111 {
112         int i;
113
114         if (group == current_gid) return(True);
115
116         for (i=0;i<ngroups;i++)
117                 if (group == groups[i])
118                         return(True);
119
120         return(False);
121 }
122
123
124 /****************************************************************************
125 like atoi but gets the value up to the separater character
126 ****************************************************************************/
127 char *Atoic(char *p, int *n, char *c)
128 {
129         if (!isdigit((int)*p))
130         {
131                 DEBUG(5, ("Atoic: malformed number\n"));
132                 return NULL;
133         }
134
135         (*n) = atoi(p);
136
137         while ((*p) && isdigit((int)*p))
138         {
139                 p++;
140         }
141
142         if (strchr_m(c, *p) == NULL)
143         {
144                 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
145                 return NULL;
146         }
147
148         return p;
149 }
150
151 /*************************************************************************
152  reads a list of numbers
153  *************************************************************************/
154 char *get_numlist(char *p, uint32 **num, int *count)
155 {
156         int val;
157
158         if (num == NULL || count == NULL)
159         {
160                 return NULL;
161         }
162
163         (*count) = 0;
164         (*num  ) = NULL;
165
166         while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':')
167         {
168                 uint32 *tn;
169                 
170                 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
171                 if (tn == NULL)
172                 {
173                         SAFE_FREE(*num);
174                         return NULL;
175                 }
176                 else (*num) = tn;
177                 (*num)[(*count)] = val;
178                 (*count)++;
179                 p++;
180         }
181
182         return p;
183 }
184
185
186 /*******************************************************************
187   check if a file exists - call vfs_file_exist for samba files
188 ********************************************************************/
189 BOOL file_exist(char *fname,SMB_STRUCT_STAT *sbuf)
190 {
191   SMB_STRUCT_STAT st;
192   if (!sbuf) sbuf = &st;
193   
194   if (sys_stat(fname,sbuf) != 0) 
195     return(False);
196
197   return(S_ISREG(sbuf->st_mode));
198 }
199
200 /*******************************************************************
201 check a files mod time
202 ********************************************************************/
203 time_t file_modtime(char *fname)
204 {
205   SMB_STRUCT_STAT st;
206   
207   if (sys_stat(fname,&st) != 0) 
208     return(0);
209
210   return(st.st_mtime);
211 }
212
213 /*******************************************************************
214   check if a directory exists
215 ********************************************************************/
216 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
217 {
218   SMB_STRUCT_STAT st2;
219   BOOL ret;
220
221   if (!st) st = &st2;
222
223   if (sys_stat(dname,st) != 0) 
224     return(False);
225
226   ret = S_ISDIR(st->st_mode);
227   if(!ret)
228     errno = ENOTDIR;
229   return ret;
230 }
231
232 /*******************************************************************
233 returns the size in bytes of the named file
234 ********************************************************************/
235 SMB_OFF_T get_file_size(char *file_name)
236 {
237   SMB_STRUCT_STAT buf;
238   buf.st_size = 0;
239   if(sys_stat(file_name,&buf) != 0)
240     return (SMB_OFF_T)-1;
241   return(buf.st_size);
242 }
243
244 /*******************************************************************
245 return a string representing an attribute for a file
246 ********************************************************************/
247 char *attrib_string(uint16 mode)
248 {
249   static fstring attrstr;
250
251   attrstr[0] = 0;
252
253   if (mode & aVOLID) fstrcat(attrstr,"V");
254   if (mode & aDIR) fstrcat(attrstr,"D");
255   if (mode & aARCH) fstrcat(attrstr,"A");
256   if (mode & aHIDDEN) fstrcat(attrstr,"H");
257   if (mode & aSYSTEM) fstrcat(attrstr,"S");
258   if (mode & aRONLY) fstrcat(attrstr,"R");        
259
260   return(attrstr);
261 }
262
263 /*******************************************************************
264   show a smb message structure
265 ********************************************************************/
266 void show_msg(char *buf)
267 {
268         int i;
269         int bcc=0;
270
271         if (DEBUGLEVEL < 5) return;
272
273         DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
274                         smb_len(buf),
275                         (int)CVAL(buf,smb_com),
276                         (int)CVAL(buf,smb_rcls),
277                         (int)CVAL(buf,smb_reh),
278                         (int)SVAL(buf,smb_err),
279                         (int)CVAL(buf,smb_flg),
280                         (int)SVAL(buf,smb_flg2)));
281         DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
282                         (int)SVAL(buf,smb_tid),
283                         (int)SVAL(buf,smb_pid),
284                         (int)SVAL(buf,smb_uid),
285                         (int)SVAL(buf,smb_mid),
286                         (int)CVAL(buf,smb_wct)));
287
288         for (i=0;i<(int)CVAL(buf,smb_wct);i++)
289         {
290                 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
291                         SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
292         }
293
294         bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
295
296         DEBUG(5,("smb_bcc=%d\n",bcc));
297
298         if (DEBUGLEVEL < 10) return;
299
300         if (DEBUGLEVEL < 50)
301         {
302                 bcc = MIN(bcc, 512);
303         }
304
305         dump_data(10, smb_buf(buf), bcc);
306 }
307
308 /*******************************************************************
309   set the length and marker of an smb packet
310 ********************************************************************/
311 void smb_setlen(char *buf,int len)
312 {
313   _smb_setlen(buf,len);
314
315   CVAL(buf,4) = 0xFF;
316   CVAL(buf,5) = 'S';
317   CVAL(buf,6) = 'M';
318   CVAL(buf,7) = 'B';
319 }
320
321 /*******************************************************************
322   setup the word count and byte count for a smb message
323 ********************************************************************/
324 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
325 {
326         if (zero)
327                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
328         CVAL(buf,smb_wct) = num_words;
329         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
330         smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
331         return (smb_size + num_words*2 + num_bytes);
332 }
333
334 /*******************************************************************
335   setup only the byte count for a smb message
336 ********************************************************************/
337 int set_message_bcc(char *buf,int num_bytes)
338 {
339         int num_words = CVAL(buf,smb_wct);
340         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
341         smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
342         return (smb_size + num_words*2 + num_bytes);
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 int set_message_end(void *outbuf,void *end_ptr)
350 {
351         return 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 convert '\' to '/'
423 reduce a file name, removing or reducing /../ , /./ , // elements.
424 remove also any trailing . and /
425 return a new allocated string.
426 ********************************************************************/
427 smb_ucs2_t *unix_clean_path(const smb_ucs2_t *s)
428 {
429         smb_ucs2_t *ns;
430         smb_ucs2_t *p, *r, *t;
431
432         DEBUG(3, ("unix_clean_name_w\n")); /*  [%unicode]\n")); */
433
434         /* convert '\' to '/' */
435         ns = strdup_w(s);
436         if (!ns) return NULL;
437         unix_format_w(ns);
438
439         /* remove all double slashes */
440         p = ns;
441         ns = all_string_sub_wa(p, "//", "/");
442         SAFE_FREE(p);
443         if (!ns) return NULL;
444
445         /* remove any /./ */
446         p = ns;
447         ns = all_string_sub_wa(p, "/./", "/");
448         SAFE_FREE(p);
449         if (!ns) return NULL;
450
451         /* reduce any /../ */
452         t = ns;
453         while ((r = strstr_wa(t, "/..")) != NULL) {
454                 t = &(r[3]);
455                 if (*t == UCS2_CHAR('/') || *t == 0) {
456                         *r = 0;
457                         p = strrchr_w(ns, UCS2_CHAR('/'));
458                         if (!p) p = ns;
459                         memmove(p, t, (strlen_w(t) + 1) * sizeof(smb_ucs2_t));
460                         t = p;
461                 }
462         }
463
464         /* remove any trailing /. */
465         trim_string_wa(ns, NULL, "/.");
466
467         /* remove any leading and trailing / */
468         trim_string_wa(ns, "/", "/");
469
470         return ns;
471 }
472
473 /****************************************************************************
474   make a dir struct
475 ****************************************************************************/
476 void make_dir_struct(char *buf,char *mask,char *fname,SMB_OFF_T size,int mode,time_t date)
477 {  
478   char *p;
479   pstring mask2;
480
481   pstrcpy(mask2,mask);
482
483   if ((mode & aDIR) != 0)
484     size = 0;
485
486   memset(buf+1,' ',11);
487   if ((p = strchr_m(mask2,'.')) != NULL)
488     {
489       *p = 0;
490       push_ascii(buf+1,mask2,8, 0);
491       push_ascii(buf+9,p+1,3, 0);
492       *p = '.';
493     }
494   else
495       push_ascii(buf+1,mask2,11, 0);
496
497   memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
498   CVAL(buf,21) = mode;
499   put_dos_date(buf,22,date);
500   SSVAL(buf,26,size & 0xFFFF);
501   SSVAL(buf,28,(size >> 16)&0xFFFF);
502   push_ascii(buf+30,fname,12, 0);
503   if (!case_sensitive)
504     strupper(buf+30);
505   DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
506 }
507
508
509 /*******************************************************************
510 close the low 3 fd's and open dev/null in their place
511 ********************************************************************/
512 void close_low_fds(void)
513 {
514   int fd;
515   int i;
516   close(0); close(1); 
517 #ifndef __INSURE__
518   close(2);
519 #endif
520   /* try and use up these file descriptors, so silly
521      library routines writing to stdout etc won't cause havoc */
522   for (i=0;i<3;i++) {
523     fd = sys_open("/dev/null",O_RDWR,0);
524     if (fd < 0) fd = sys_open("/dev/null",O_WRONLY,0);
525     if (fd < 0) {
526       DEBUG(0,("Can't open /dev/null\n"));
527       return;
528     }
529     if (fd != i) {
530       DEBUG(0,("Didn't get file descriptor %d\n",i));
531       return;
532     }
533   }
534 }
535
536 /****************************************************************************
537 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
538 else
539 if SYSV use O_NDELAY
540 if BSD use FNDELAY
541 ****************************************************************************/
542 int set_blocking(int fd, BOOL set)
543 {
544   int val;
545 #ifdef O_NONBLOCK
546 #define FLAG_TO_SET O_NONBLOCK
547 #else
548 #ifdef SYSV
549 #define FLAG_TO_SET O_NDELAY
550 #else /* BSD */
551 #define FLAG_TO_SET FNDELAY
552 #endif
553 #endif
554
555   if((val = fcntl(fd, F_GETFL, 0)) == -1)
556         return -1;
557   if(set) /* Turn blocking on - ie. clear nonblock flag */
558         val &= ~FLAG_TO_SET;
559   else
560     val |= FLAG_TO_SET;
561   return fcntl( fd, F_SETFL, val);
562 #undef FLAG_TO_SET
563 }
564
565 /****************************************************************************
566  Transfer some data between two fd's.
567 ****************************************************************************/
568
569 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
570                                                 ssize_t (*write_fn)(int, const void *, size_t))
571 {
572         static char buf[16384];
573         size_t total = 0;
574         ssize_t read_ret;
575         size_t write_total = 0;
576     ssize_t write_ret;
577
578         while (total < n) {
579                 size_t num_to_read_thistime = MIN((n - total), sizeof(buf));
580
581                 read_ret = (*read_fn)(infd, buf + total, num_to_read_thistime);
582                 if (read_ret == -1) {
583                         DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
584                         return -1;
585                 }
586                 if (read_ret == 0)
587                         break;
588
589                 write_total = 0;
590  
591                 while (write_total < read_ret) {
592                         write_ret = (*write_fn)(outfd,buf + total, read_ret);
593  
594                         if (write_ret == -1) {
595                                 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
596                                 return -1;
597                         }
598                         if (write_ret == 0)
599                                 return (ssize_t)total;
600  
601                         write_total += (size_t)write_ret;
602                 }
603
604                 total += (size_t)read_ret;
605         }
606
607         return (ssize_t)total;          
608 }
609
610 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
611 {
612         return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, read, write);
613 }
614
615 /*******************************************************************
616 sleep for a specified number of milliseconds
617 ********************************************************************/
618 void msleep(int t)
619 {
620   int tdiff=0;
621   struct timeval tval,t1,t2;  
622   fd_set fds;
623
624   GetTimeOfDay(&t1);
625   GetTimeOfDay(&t2);
626   
627   while (tdiff < t) {
628     tval.tv_sec = (t-tdiff)/1000;
629     tval.tv_usec = 1000*((t-tdiff)%1000);
630  
631     FD_ZERO(&fds);
632     errno = 0;
633     sys_select_intr(0,&fds,&tval);
634
635     GetTimeOfDay(&t2);
636     tdiff = TvalDiff(&t1,&t2);
637   }
638 }
639
640
641 /****************************************************************************
642 become a daemon, discarding the controlling terminal
643 ****************************************************************************/
644 void become_daemon(void)
645 {
646         if (sys_fork()) {
647                 _exit(0);
648         }
649
650   /* detach from the terminal */
651 #ifdef HAVE_SETSID
652         setsid();
653 #elif defined(TIOCNOTTY)
654         {
655                 int i = sys_open("/dev/tty", O_RDWR, 0);
656                 if (i != -1) {
657                         ioctl(i, (int) TIOCNOTTY, (char *)0);      
658                         close(i);
659                 }
660         }
661 #endif /* HAVE_SETSID */
662
663         /* Close fd's 0,1,2. Needed if started by rsh */
664         close_low_fds();
665 }
666
667
668 /****************************************************************************
669 put up a yes/no prompt
670 ****************************************************************************/
671 BOOL yesno(char *p)
672 {
673   pstring ans;
674   printf("%s",p);
675
676   if (!fgets(ans,sizeof(ans)-1,stdin))
677     return(False);
678
679   if (*ans == 'y' || *ans == 'Y')
680     return(True);
681
682   return(False);
683 }
684
685 /****************************************************************************
686 expand a pointer to be a particular size
687 ****************************************************************************/
688 void *Realloc(void *p,size_t size)
689 {
690   void *ret=NULL;
691
692   if (size == 0) {
693     SAFE_FREE(p);
694     DEBUG(5,("Realloc asked for 0 bytes\n"));
695     return NULL;
696   }
697
698   if (!p)
699     ret = (void *)malloc(size);
700   else
701     ret = (void *)realloc(p,size);
702
703   if (!ret)
704     DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
705
706   return(ret);
707 }
708
709
710 /****************************************************************************
711 free memory, checks for NULL and set to NULL
712 use directly SAFE_FREE()
713 exist only because we need to pass a function pointer somewhere --SSS
714 ****************************************************************************/
715 void safe_free(void *p)
716 {
717         SAFE_FREE(p);
718 }
719
720 /****************************************************************************
721 get my own name and IP
722 ****************************************************************************/
723 BOOL get_myname(char *my_name)
724 {
725         pstring hostname;
726
727         *hostname = 0;
728
729         /* get my host name */
730         if (gethostname(hostname, sizeof(hostname)) == -1) {
731                 DEBUG(0,("gethostname failed\n"));
732                 return False;
733         } 
734
735         /* Ensure null termination. */
736         hostname[sizeof(hostname)-1] = '\0';
737
738         if (my_name) {
739                 /* split off any parts after an initial . */
740                 char *p = strchr_m(hostname,'.');
741                 if (p) *p = 0;
742                 
743                 fstrcpy(my_name,hostname);
744         }
745         
746         return(True);
747 }
748
749 /****************************************************************************
750 interpret a protocol description string, with a default
751 ****************************************************************************/
752 int interpret_protocol(char *str,int def)
753 {
754   if (strequal(str,"NT1"))
755     return(PROTOCOL_NT1);
756   if (strequal(str,"LANMAN2"))
757     return(PROTOCOL_LANMAN2);
758   if (strequal(str,"LANMAN1"))
759     return(PROTOCOL_LANMAN1);
760   if (strequal(str,"CORE"))
761     return(PROTOCOL_CORE);
762   if (strequal(str,"COREPLUS"))
763     return(PROTOCOL_COREPLUS);
764   if (strequal(str,"CORE+"))
765     return(PROTOCOL_COREPLUS);
766   
767   DEBUG(0,("Unrecognised protocol level %s\n",str));
768   
769   return(def);
770 }
771
772 /****************************************************************************
773  Return true if a string could be a pure IP address.
774 ****************************************************************************/
775
776 BOOL is_ipaddress(const char *str)
777 {
778   BOOL pure_address = True;
779   int i;
780   
781   for (i=0; pure_address && str[i]; i++)
782     if (!(isdigit((int)str[i]) || str[i] == '.'))
783       pure_address = False;
784
785   /* Check that a pure number is not misinterpreted as an IP */
786   pure_address = pure_address && (strchr_m(str, '.') != NULL);
787
788   return pure_address;
789 }
790
791 /****************************************************************************
792 interpret an internet address or name into an IP address in 4 byte form
793 ****************************************************************************/
794
795 uint32 interpret_addr(const char *str)
796 {
797   struct hostent *hp;
798   uint32 res;
799
800   if (strcmp(str,"0.0.0.0") == 0) return(0);
801   if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
802
803   /* if it's in the form of an IP address then get the lib to interpret it */
804   if (is_ipaddress(str)) {
805     res = inet_addr(str);
806   } else {
807     /* otherwise assume it's a network name of some sort and use 
808        sys_gethostbyname */
809     if ((hp = sys_gethostbyname(str)) == 0) {
810       DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
811       return 0;
812     }
813     if(hp->h_addr == NULL) {
814       DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
815       return 0;
816     }
817     putip((char *)&res,(char *)hp->h_addr);
818   }
819
820   if (res == (uint32)-1) return(0);
821
822   return(res);
823 }
824
825 /*******************************************************************
826   a convenient addition to interpret_addr()
827   ******************************************************************/
828 struct in_addr *interpret_addr2(const char *str)
829 {
830   static struct in_addr ret;
831   uint32 a = interpret_addr(str);
832   ret.s_addr = a;
833   return(&ret);
834 }
835
836 /*******************************************************************
837   check if an IP is the 0.0.0.0
838   ******************************************************************/
839 BOOL zero_ip(struct in_addr ip)
840 {
841   uint32 a;
842   putip((char *)&a,(char *)&ip);
843   return(a == 0);
844 }
845
846
847 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
848 /******************************************************************
849  Remove any mount options such as -rsize=2048,wsize=2048 etc.
850  Based on a fix from <Thomas.Hepper@icem.de>.
851 *******************************************************************/
852
853 static void strip_mount_options( pstring *str)
854 {
855   if (**str == '-')
856   { 
857     char *p = *str;
858     while(*p && !isspace(*p))
859       p++;
860     while(*p && isspace(*p))
861       p++;
862     if(*p) {
863       pstring tmp_str;
864
865       pstrcpy(tmp_str, p);
866       pstrcpy(*str, tmp_str);
867     }
868   }
869 }
870
871 /*******************************************************************
872  Patch from jkf@soton.ac.uk
873  Split Luke's automount_server into YP lookup and string splitter
874  so can easily implement automount_path(). 
875  As we may end up doing both, cache the last YP result. 
876 *******************************************************************/
877
878 #ifdef WITH_NISPLUS_HOME
879 char *automount_lookup(const char *user_name)
880 {
881   static fstring last_key = "";
882   static pstring last_value = "";
883  
884   char *nis_map = (char *)lp_nis_home_map_name();
885  
886   char buffer[NIS_MAXATTRVAL + 1];
887   nis_result *result;
888   nis_object *object;
889   entry_obj  *entry;
890  
891   if (strcmp(user_name, last_key))
892   {
893     slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
894     DEBUG(5, ("NIS+ querystring: %s\n", buffer));
895  
896     if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL))
897     {
898        if (result->status != NIS_SUCCESS)
899       {
900         DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
901         fstrcpy(last_key, ""); pstrcpy(last_value, "");
902       }
903       else
904       {
905         object = result->objects.objects_val;
906         if (object->zo_data.zo_type == ENTRY_OBJ)
907         {
908            entry = &object->zo_data.objdata_u.en_data;
909            DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
910            DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
911  
912            pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
913            pstring_sub(last_value, "&", user_name);
914            fstrcpy(last_key, user_name);
915         }
916       }
917     }
918     nis_freeresult(result);
919   }
920
921   strip_mount_options(&last_value);
922
923   DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
924   return last_value;
925 }
926 #else /* WITH_NISPLUS_HOME */
927 char *automount_lookup(const char *user_name)
928 {
929   static fstring last_key = "";
930   static pstring last_value = "";
931
932   int nis_error;        /* returned by yp all functions */
933   char *nis_result;     /* yp_match inits this */
934   int nis_result_len;  /* and set this */
935   char *nis_domain;     /* yp_get_default_domain inits this */
936   char *nis_map = (char *)lp_nis_home_map_name();
937
938   if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
939     DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
940     return last_value;
941   }
942
943   DEBUG(5, ("NIS Domain: %s\n", nis_domain));
944
945   if (!strcmp(user_name, last_key)) {
946         nis_result = last_value;
947     nis_result_len = strlen(last_value);
948     nis_error = 0;
949
950   } else {
951
952     if ((nis_error = yp_match(nis_domain, nis_map,
953                               user_name, strlen(user_name),
954                               &nis_result, &nis_result_len)) == 0) {
955        if (!nis_error && nis_result_len >= sizeof(pstring)) {
956                nis_result_len = sizeof(pstring)-1;
957        }
958        fstrcpy(last_key, user_name);
959        strncpy(last_value, nis_result, nis_result_len);
960        last_value[nis_result_len] = '\0';
961         strip_mount_options(&last_value);
962
963     } else if(nis_error == YPERR_KEY) {
964
965     /* If Key lookup fails user home server is not in nis_map 
966        use default information for server, and home directory */
967        last_value[0] = 0;
968        DEBUG(3, ("YP Key not found:  while looking up \"%s\" in map \"%s\"\n", 
969                 user_name, nis_map));
970        DEBUG(3, ("using defaults for server and home directory\n"));
971     } else {
972        DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n", 
973                yperr_string(nis_error), user_name, nis_map));
974     }
975   }
976
977
978   DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
979   return last_value;
980 }
981 #endif /* WITH_NISPLUS_HOME */
982 #endif
983
984
985 /*******************************************************************
986 are two IPs on the same subnet?
987 ********************************************************************/
988 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
989 {
990   uint32 net1,net2,nmask;
991
992   nmask = ntohl(mask.s_addr);
993   net1  = ntohl(ip1.s_addr);
994   net2  = ntohl(ip2.s_addr);
995             
996   return((net1 & nmask) == (net2 & nmask));
997 }
998
999
1000 /****************************************************************************
1001 check if a process exists. Does this work on all unixes?
1002 ****************************************************************************/
1003
1004 BOOL process_exists(pid_t pid)
1005 {
1006         return(kill(pid,0) == 0 || errno != ESRCH);
1007 }
1008
1009
1010 /*******************************************************************
1011  Convert a uid into a user name.
1012 ********************************************************************/
1013
1014 char *uidtoname(uid_t uid)
1015 {
1016         static fstring name;
1017         struct passwd *pass;
1018
1019         if (winbind_uidtoname(name, uid))
1020                 return name;
1021
1022         pass = sys_getpwuid(uid);
1023         if (pass) return(pass->pw_name);
1024         slprintf(name, sizeof(name) - 1, "%d",(int)uid);
1025         return(name);
1026 }
1027
1028
1029 /*******************************************************************
1030  Convert a gid into a group name.
1031 ********************************************************************/
1032
1033 char *gidtoname(gid_t gid)
1034 {
1035         static fstring name;
1036         struct group *grp;
1037
1038         if (winbind_gidtoname(name, gid))
1039                 return name;
1040
1041         grp = getgrgid(gid);
1042         if (grp) return(grp->gr_name);
1043         slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1044         return(name);
1045 }
1046
1047 /*******************************************************************
1048  Convert a user name into a uid. If winbindd is present uses this.
1049 ********************************************************************/
1050
1051 uid_t nametouid(char *name)
1052 {
1053         struct passwd *pass;
1054         char *p;
1055         uid_t u;
1056
1057         u = (uid_t)strtol(name, &p, 0);
1058         if ((p != name) && (*p == '\0'))
1059                 return u;
1060
1061         if (winbind_nametouid(&u, name))
1062                 return u;
1063
1064         pass = sys_getpwnam(name);
1065         if (pass)
1066                 return(pass->pw_uid);
1067         return (uid_t)-1;
1068 }
1069
1070 /*******************************************************************
1071  Convert a name to a gid_t if possible. Return -1 if not a group. If winbindd
1072  is present does a shortcut lookup...
1073 ********************************************************************/
1074
1075 gid_t nametogid(const char *name)
1076 {
1077         struct group *grp;
1078         char *p;
1079         gid_t g;
1080
1081         g = (gid_t)strtol(name, &p, 0);
1082         if ((p != name) && (*p == '\0'))
1083                 return g;
1084
1085         if (winbind_nametogid(&g, name))
1086                 return g;
1087
1088         grp = getgrnam(name);
1089         if (grp)
1090                 return(grp->gr_gid);
1091         return (gid_t)-1;
1092 }
1093
1094 /*******************************************************************
1095 something really nasty happened - panic!
1096 ********************************************************************/
1097 void smb_panic(char *why)
1098 {
1099         char *cmd = lp_panic_action();
1100         if (cmd && *cmd) {
1101                 system(cmd);
1102         }
1103         DEBUG(0,("PANIC: %s\n", why));
1104         dbgflush();
1105         abort();
1106 }
1107
1108
1109 /*******************************************************************
1110 a readdir wrapper which just returns the file name
1111 ********************************************************************/
1112 char *readdirname(DIR *p)
1113 {
1114         SMB_STRUCT_DIRENT *ptr;
1115         char *dname;
1116
1117         if (!p) return(NULL);
1118   
1119         ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1120         if (!ptr) return(NULL);
1121
1122         dname = ptr->d_name;
1123
1124 #ifdef NEXT2
1125         if (telldir(p) < 0) return(NULL);
1126 #endif
1127
1128 #ifdef HAVE_BROKEN_READDIR
1129         /* using /usr/ucb/cc is BAD */
1130         dname = dname - 2;
1131 #endif
1132
1133         {
1134                 static pstring buf;
1135                 int len = NAMLEN(ptr);
1136                 memcpy(buf, dname, len);
1137                 buf[len] = 0;
1138                 dname = buf;
1139         }
1140
1141         return(dname);
1142 }
1143
1144 /*******************************************************************
1145  Utility function used to decide if the last component 
1146  of a path matches a (possibly wildcarded) entry in a namelist.
1147 ********************************************************************/
1148
1149 BOOL is_in_path(char *name, name_compare_entry *namelist)
1150 {
1151   pstring last_component;
1152   char *p;
1153
1154   DEBUG(8, ("is_in_path: %s\n", name));
1155
1156   /* if we have no list it's obviously not in the path */
1157   if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) 
1158   {
1159     DEBUG(8,("is_in_path: no name list.\n"));
1160     return False;
1161   }
1162
1163   /* Get the last component of the unix name. */
1164   p = strrchr_m(name, '/');
1165   strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1166   last_component[sizeof(last_component)-1] = '\0'; 
1167
1168   for(; namelist->name != NULL; namelist++)
1169   {
1170     if(namelist->is_wild)
1171     {
1172       if (mask_match(last_component, namelist->name, case_sensitive))
1173       {
1174          DEBUG(8,("is_in_path: mask match succeeded\n"));
1175          return True;
1176       }
1177     }
1178     else
1179     {
1180       if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1181        (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
1182         {
1183          DEBUG(8,("is_in_path: match succeeded\n"));
1184          return True;
1185         }
1186     }
1187   }
1188   DEBUG(8,("is_in_path: match not found\n"));
1189  
1190   return False;
1191 }
1192
1193 /*******************************************************************
1194  Strip a '/' separated list into an array of 
1195  name_compare_enties structures suitable for 
1196  passing to is_in_path(). We do this for
1197  speed so we can pre-parse all the names in the list 
1198  and don't do it for each call to is_in_path().
1199  namelist is modified here and is assumed to be 
1200  a copy owned by the caller.
1201  We also check if the entry contains a wildcard to
1202  remove a potentially expensive call to mask_match
1203  if possible.
1204 ********************************************************************/
1205  
1206 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1207 {
1208   char *name_end;
1209   char *nameptr = namelist;
1210   int num_entries = 0;
1211   int i;
1212
1213   (*ppname_array) = NULL;
1214
1215   if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0'))) 
1216     return;
1217
1218   /* We need to make two passes over the string. The
1219      first to count the number of elements, the second
1220      to split it.
1221    */
1222   while(*nameptr) 
1223     {
1224       if ( *nameptr == '/' ) 
1225         {
1226           /* cope with multiple (useless) /s) */
1227           nameptr++;
1228           continue;
1229         }
1230       /* find the next / */
1231       name_end = strchr_m(nameptr, '/');
1232
1233       /* oops - the last check for a / didn't find one. */
1234       if (name_end == NULL)
1235         break;
1236
1237       /* next segment please */
1238       nameptr = name_end + 1;
1239       num_entries++;
1240     }
1241
1242   if(num_entries == 0)
1243     return;
1244
1245   if(( (*ppname_array) = (name_compare_entry *)malloc( 
1246            (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
1247         {
1248     DEBUG(0,("set_namearray: malloc fail\n"));
1249     return;
1250         }
1251
1252   /* Now copy out the names */
1253   nameptr = namelist;
1254   i = 0;
1255   while(*nameptr)
1256              {
1257       if ( *nameptr == '/' ) 
1258       {
1259           /* cope with multiple (useless) /s) */
1260           nameptr++;
1261           continue;
1262       }
1263       /* find the next / */
1264       if ((name_end = strchr_m(nameptr, '/')) != NULL) 
1265       {
1266           *name_end = 0;
1267          }
1268
1269       /* oops - the last check for a / didn't find one. */
1270       if(name_end == NULL) 
1271         break;
1272
1273       (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1274       if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
1275       {
1276         DEBUG(0,("set_namearray: malloc fail (1)\n"));
1277         return;
1278       }
1279
1280       /* next segment please */
1281       nameptr = name_end + 1;
1282       i++;
1283     }
1284   
1285   (*ppname_array)[i].name = NULL;
1286
1287   return;
1288 }
1289
1290 /****************************************************************************
1291 routine to free a namearray.
1292 ****************************************************************************/
1293
1294 void free_namearray(name_compare_entry *name_array)
1295 {
1296   if(name_array == NULL)
1297     return;
1298
1299   SAFE_FREE(name_array->name);
1300   SAFE_FREE(name_array);
1301 }
1302
1303 /****************************************************************************
1304  Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1305  is dealt with in posix.c
1306 ****************************************************************************/
1307
1308 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1309 {
1310   SMB_STRUCT_FLOCK lock;
1311   int ret;
1312
1313   DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1314
1315   lock.l_type = type;
1316   lock.l_whence = SEEK_SET;
1317   lock.l_start = offset;
1318   lock.l_len = count;
1319   lock.l_pid = 0;
1320
1321   errno = 0;
1322
1323   ret = fcntl(fd,op,&lock);
1324
1325   if (errno != 0)
1326     DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1327
1328   /* a lock query */
1329   if (op == SMB_F_GETLK)
1330   {
1331     if ((ret != -1) &&
1332         (lock.l_type != F_UNLCK) && 
1333         (lock.l_pid != 0) && 
1334         (lock.l_pid != sys_getpid()))
1335     {
1336       DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1337       return(True);
1338     }
1339
1340     /* it must be not locked or locked by me */
1341     return(False);
1342   }
1343
1344   /* a lock set or unset */
1345   if (ret == -1)
1346   {
1347     DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1348           (double)offset,(double)count,op,type,strerror(errno)));
1349     return(False);
1350   }
1351
1352   /* everything went OK */
1353   DEBUG(8,("fcntl_lock: Lock call successful\n"));
1354
1355   return(True);
1356 }
1357
1358 /*******************************************************************
1359 is the name specified one of my netbios names
1360 returns true is it is equal, false otherwise
1361 ********************************************************************/
1362 BOOL is_myname(char *s)
1363 {
1364   int n;
1365   BOOL ret = False;
1366
1367   for (n=0; my_netbios_names[n]; n++) {
1368     if (strequal(my_netbios_names[n], s))
1369       ret=True;
1370   }
1371   DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1372   return(ret);
1373 }
1374
1375 /*******************************************************************
1376 set the horrid remote_arch string based on an enum.
1377 ********************************************************************/
1378 void set_remote_arch(enum remote_arch_types type)
1379 {
1380   extern fstring remote_arch;
1381   ra_type = type;
1382   switch( type )
1383   {
1384   case RA_WFWG:
1385     fstrcpy(remote_arch, "WfWg");
1386     return;
1387   case RA_OS2:
1388     fstrcpy(remote_arch, "OS2");
1389     return;
1390   case RA_WIN95:
1391     fstrcpy(remote_arch, "Win95");
1392     return;
1393   case RA_WINNT:
1394     fstrcpy(remote_arch, "WinNT");
1395     return;
1396   case RA_WIN2K:
1397     fstrcpy(remote_arch, "Win2K");
1398     return;
1399   case RA_SAMBA:
1400     fstrcpy(remote_arch,"Samba");
1401     return;
1402   default:
1403     ra_type = RA_UNKNOWN;
1404     fstrcpy(remote_arch, "UNKNOWN");
1405     break;
1406   }
1407 }
1408
1409 /*******************************************************************
1410  Get the remote_arch type.
1411 ********************************************************************/
1412 enum remote_arch_types get_remote_arch(void)
1413 {
1414   return ra_type;
1415 }
1416
1417
1418 void out_ascii(FILE *f, unsigned char *buf,int len)
1419 {
1420         int i;
1421         for (i=0;i<len;i++)
1422         {
1423                 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1424         }
1425 }
1426
1427 void out_data(FILE *f,char *buf1,int len, int per_line)
1428 {
1429         unsigned char *buf = (unsigned char *)buf1;
1430         int i=0;
1431         if (len<=0)
1432         {
1433                 return;
1434         }
1435
1436         fprintf(f, "[%03X] ",i);
1437         for (i=0;i<len;)
1438         {
1439                 fprintf(f, "%02X ",(int)buf[i]);
1440                 i++;
1441                 if (i%(per_line/2) == 0) fprintf(f, " ");
1442                 if (i%per_line == 0)
1443                 {      
1444                         out_ascii(f,&buf[i-per_line  ],per_line/2); fprintf(f, " ");
1445                         out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1446                         if (i<len) fprintf(f, "[%03X] ",i);
1447                 }
1448         }
1449         if ((i%per_line) != 0)
1450         {
1451                 int n;
1452
1453                 n = per_line - (i%per_line);
1454                 fprintf(f, " ");
1455                 if (n>(per_line/2)) fprintf(f, " ");
1456                 while (n--)
1457                 {
1458                         fprintf(f, "   ");
1459                 }
1460                 n = MIN(per_line/2,i%per_line);
1461                 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1462                 n = (i%per_line) - n;
1463                 if (n>0) out_ascii(f,&buf[i-n],n); 
1464                 fprintf(f, "\n");    
1465         }
1466 }
1467
1468 void print_asc(int level, const unsigned char *buf,int len)
1469 {
1470         int i;
1471         for (i=0;i<len;i++)
1472                 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1473 }
1474
1475 void dump_data(int level, const char *buf1,int len)
1476 {
1477   const unsigned char *buf = (const unsigned char *)buf1;
1478   int i=0;
1479   if (len<=0) return;
1480
1481   DEBUG(level,("[%03X] ",i));
1482   for (i=0;i<len;) {
1483     DEBUG(level,("%02X ",(int)buf[i]));
1484     i++;
1485     if (i%8 == 0) DEBUG(level,(" "));
1486     if (i%16 == 0) {      
1487       print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
1488       print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
1489       if (i<len) DEBUG(level,("[%03X] ",i));
1490     }
1491   }
1492   if (i%16) {
1493     int n;
1494
1495     n = 16 - (i%16);
1496     DEBUG(level,(" "));
1497     if (n>8) DEBUG(level,(" "));
1498     while (n--) DEBUG(level,("   "));
1499
1500     n = MIN(8,i%16);
1501     print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
1502     n = (i%16) - n;
1503     if (n>0) print_asc(level,&buf[i-n],n); 
1504     DEBUG(level,("\n"));    
1505   }
1506 }
1507
1508 char *tab_depth(int depth)
1509 {
1510         static pstring spaces;
1511         memset(spaces, ' ', depth * 4);
1512         spaces[depth * 4] = 0;
1513         return spaces;
1514 }
1515
1516 /*****************************************************************************
1517  * Provide a checksum on a string
1518  *
1519  *  Input:  s - the null-terminated character string for which the checksum
1520  *              will be calculated.
1521  *
1522  *  Output: The checksum value calculated for s.
1523  *
1524  * ****************************************************************************
1525  */
1526 int str_checksum(const char *s)
1527 {
1528         int res = 0;
1529         int c;
1530         int i=0;
1531         
1532         while(*s) {
1533                 c = *s;
1534                 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1535                 s++;
1536                 i++;
1537         }
1538         return(res);
1539 } /* str_checksum */
1540
1541
1542
1543 /*****************************************************************
1544 zero a memory area then free it. Used to catch bugs faster
1545 *****************************************************************/  
1546 void zero_free(void *p, size_t size)
1547 {
1548         memset(p, 0, size);
1549         SAFE_FREE(p);
1550 }
1551
1552
1553 /*****************************************************************
1554 set our open file limit to a requested max and return the limit
1555 *****************************************************************/  
1556 int set_maxfiles(int requested_max)
1557 {
1558 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1559         struct rlimit rlp;
1560         int saved_current_limit;
1561
1562         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1563                 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1564                         strerror(errno) ));
1565                 /* just guess... */
1566                 return requested_max;
1567         }
1568
1569         /* 
1570      * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1571          * account for the extra fd we need 
1572          * as well as the log files and standard
1573          * handles etc. Save the limit we want to set in case
1574          * we are running on an OS that doesn't support this limit (AIX)
1575          * which always returns RLIM_INFINITY for rlp.rlim_max.
1576          */
1577
1578         /* Try raising the hard (max) limit to the requested amount. */
1579
1580 #if defined(RLIM_INFINITY)
1581         if (rlp.rlim_max != RLIM_INFINITY) {
1582                 int orig_max = rlp.rlim_max;
1583
1584                 if ( rlp.rlim_max < requested_max )
1585                         rlp.rlim_max = requested_max;
1586
1587                 /* This failing is not an error - many systems (Linux) don't
1588                         support our default request of 10,000 open files. JRA. */
1589
1590                 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1591                         DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n", 
1592                                 (int)rlp.rlim_max, strerror(errno) ));
1593
1594                         /* Set failed - restore original value from get. */
1595                         rlp.rlim_max = orig_max;
1596                 }
1597         }
1598 #endif
1599
1600         /* Now try setting the soft (current) limit. */
1601
1602         saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1603
1604         if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1605                 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n", 
1606                         (int)rlp.rlim_cur, strerror(errno) ));
1607                 /* just guess... */
1608                 return saved_current_limit;
1609         }
1610
1611         if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1612                 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1613                         strerror(errno) ));
1614                 /* just guess... */
1615                 return saved_current_limit;
1616     }
1617
1618 #if defined(RLIM_INFINITY)
1619         if(rlp.rlim_cur == RLIM_INFINITY)
1620                 return saved_current_limit;
1621 #endif
1622
1623     if((int)rlp.rlim_cur > saved_current_limit)
1624                 return saved_current_limit;
1625
1626         return rlp.rlim_cur;
1627 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1628         /*
1629          * No way to know - just guess...
1630          */
1631         return requested_max;
1632 #endif
1633 }
1634
1635 /*****************************************************************
1636  splits out the start of the key (HKLM or HKU) and the rest of the key
1637  *****************************************************************/  
1638 BOOL reg_split_key(char *full_keyname, uint32 *reg_type, char *key_name)
1639 {
1640         pstring tmp;
1641
1642         if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1643         {
1644                 return False;
1645         }
1646
1647         (*reg_type) = 0;
1648
1649         DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1650
1651         if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1652         {
1653                 (*reg_type) = HKEY_LOCAL_MACHINE;
1654         }
1655         else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1656         {
1657                 (*reg_type) = HKEY_USERS;
1658         }
1659         else
1660         {
1661                 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1662                 return False;
1663         }
1664         
1665         if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
1666         {
1667                 fstrcpy(key_name, tmp);
1668         }
1669         else
1670         {
1671                 key_name[0] = 0;
1672         }
1673
1674         DEBUG(10, ("reg_split_key: name %s\n", key_name));
1675
1676         return True;
1677 }
1678
1679
1680 /*****************************************************************
1681 possibly replace mkstemp if it is broken
1682 *****************************************************************/  
1683 int smb_mkstemp(char *template)
1684 {
1685 #if HAVE_SECURE_MKSTEMP
1686         return mkstemp(template);
1687 #else
1688         /* have a reasonable go at emulating it. Hope that
1689            the system mktemp() isn't completly hopeless */
1690         char *p = mktemp(template);
1691         if (!p) return -1;
1692         return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
1693 #endif
1694 }
1695
1696 /*****************************************************************
1697  malloc that aborts with smb_panic on fail or zero size.
1698  *****************************************************************/  
1699
1700 void *xmalloc(size_t size)
1701 {
1702         void *p;
1703         if (size == 0)
1704                 smb_panic("xmalloc: called with zero size.\n");
1705         if ((p = malloc(size)) == NULL)
1706                 smb_panic("xmalloc: malloc fail.\n");
1707         return p;
1708 }
1709
1710 /*****************************************************************
1711  Memdup with smb_panic on fail.
1712  *****************************************************************/  
1713
1714 void *xmemdup(const void *p, size_t size)
1715 {
1716         void *p2;
1717         p2 = xmalloc(size);
1718         memcpy(p2, p, size);
1719         return p2;
1720 }
1721
1722 /*****************************************************************
1723  strdup that aborts on malloc fail.
1724  *****************************************************************/  
1725
1726 char *xstrdup(const char *s)
1727 {
1728         char *s1 = strdup(s);
1729         if (!s1)
1730                 smb_panic("xstrdup: malloc fail\n");
1731         return s1;
1732 }
1733
1734 /*****************************************************************
1735 like strdup but for memory
1736  *****************************************************************/  
1737 void *memdup(const void *p, size_t size)
1738 {
1739         void *p2;
1740         if (size == 0) return NULL;
1741         p2 = malloc(size);
1742         if (!p2) return NULL;
1743         memcpy(p2, p, size);
1744         return p2;
1745 }
1746
1747 /*****************************************************************
1748 get local hostname and cache result
1749  *****************************************************************/  
1750 char *myhostname(void)
1751 {
1752         static pstring ret;
1753         if (ret[0] == 0) {
1754                 get_myname(ret);
1755         }
1756         return ret;
1757 }
1758
1759
1760 /*****************************************************************
1761 a useful function for returning a path in the Samba lock directory
1762  *****************************************************************/  
1763 char *lock_path(char *name)
1764 {
1765         static pstring fname;
1766
1767         pstrcpy(fname,lp_lockdir());
1768         trim_string(fname,"","/");
1769         
1770         if (!directory_exist(fname,NULL)) {
1771                 mkdir(fname,0755);
1772         }
1773         
1774         pstrcat(fname,"/");
1775         pstrcat(fname,name);
1776
1777         return fname;
1778 }
1779
1780 /*****************************************************************
1781 a useful function for returning a path in the Samba lib directory
1782  *****************************************************************/  
1783 char *lib_path(char *name)
1784 {
1785         static pstring fname;
1786         snprintf(fname, sizeof(fname), "%s/%s", LIBDIR, name);
1787         return fname;
1788 }
1789
1790 /*******************************************************************
1791  Given a filename - get its directory name
1792  NB: Returned in static storage.  Caveats:
1793  o  Not safe in thread environment.
1794  o  Caller must not free.
1795  o  If caller wishes to preserve, they should copy.
1796 ********************************************************************/
1797
1798 char *parent_dirname(const char *path)
1799 {
1800         static pstring dirpath;
1801         char *p;
1802
1803         if (!path)
1804                 return(NULL);
1805
1806         pstrcpy(dirpath, path);
1807         p = strrchr_m(dirpath, '/');  /* Find final '/', if any */
1808         if (!p) {
1809                 pstrcpy(dirpath, ".");    /* No final "/", so dir is "." */
1810         } else {
1811                 if (p == dirpath)
1812                         ++p;    /* For root "/", leave "/" in place */
1813                 *p = '\0';
1814         }
1815         return dirpath;
1816 }
1817
1818
1819 /*******************************************************************
1820 determine if a pattern contains any Microsoft wildcard characters
1821  *******************************************************************/
1822 BOOL ms_has_wild(char *s)
1823 {
1824         char c;
1825         while ((c = *s++)) {
1826                 switch (c) {
1827                 case '*':
1828                 case '?':
1829                 case '<':
1830                 case '>':
1831                 case '"':
1832                         return True;
1833                 }
1834         }
1835         return False;
1836 }
1837
1838 BOOL ms_has_wild_w(const smb_ucs2_t *s)
1839 {
1840         smb_ucs2_t c;
1841         while ((c = *s++)) {
1842                 switch (c) {
1843                 case UCS2_CHAR('*'):
1844                 case UCS2_CHAR('?'):
1845                 case UCS2_CHAR('<'):
1846                 case UCS2_CHAR('>'):
1847                 case UCS2_CHAR('"'):
1848                         return True;
1849                 }
1850         }
1851         return False;
1852 }
1853
1854 /*******************************************************************
1855  a wrapper that handles case sensitivity and the special handling
1856    of the ".." name
1857  *******************************************************************/
1858 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
1859 {
1860         fstring p2, s2;
1861
1862         if (strcmp(string,"..") == 0) string = ".";
1863         if (strcmp(pattern,".") == 0) return False;
1864         
1865         if (is_case_sensitive) {
1866                 return ms_fnmatch(pattern, string, Protocol) == 0;
1867         }
1868
1869         fstrcpy(p2, pattern);
1870         fstrcpy(s2, string);
1871         strlower(p2); 
1872         strlower(s2);
1873         return ms_fnmatch(p2, s2, Protocol) == 0;
1874 }
1875
1876 /*********************************************************
1877  Recursive routine that is called by unix_wild_match.
1878 *********************************************************/
1879
1880 static BOOL unix_do_match(char *regexp, char *str)
1881 {
1882         char *p;
1883
1884         for( p = regexp; *p && *str; ) {
1885
1886                 switch(*p) {
1887                         case '?':
1888                                 str++;
1889                                 p++;
1890                                 break;
1891
1892                         case '*':
1893
1894                                 /*
1895                                  * Look for a character matching 
1896                                  * the one after the '*'.
1897                                  */
1898                                 p++;
1899                                 if(!*p)
1900                                         return True; /* Automatic match */
1901                                 while(*str) {
1902
1903                                         while(*str && (*p != *str))
1904                                                 str++;
1905
1906                                         /*
1907                                          * Patch from weidel@multichart.de. In the case of the regexp
1908                                          * '*XX*' we want to ensure there are at least 2 'X' characters
1909                                          * in the string after the '*' for a match to be made.
1910                                          */
1911
1912                                         {
1913                                                 int matchcount=0;
1914
1915                                                 /*
1916                                                  * Eat all the characters that match, but count how many there were.
1917                                                  */
1918
1919                                                 while(*str && (*p == *str)) {
1920                                                         str++;
1921                                                         matchcount++;
1922                                                 }
1923
1924                                                 /*
1925                                                  * Now check that if the regexp had n identical characters that
1926                                                  * matchcount had at least that many matches.
1927                                                  */
1928
1929                                                 while ( *(p+1) && (*(p+1) == *p)) {
1930                                                         p++;
1931                                                         matchcount--;
1932                                                 }
1933
1934                                                 if ( matchcount <= 0 )
1935                                                         return False;
1936                                         }
1937
1938                                         str--; /* We've eaten the match char after the '*' */
1939
1940                                         if(unix_do_match(p, str))
1941                                                 return True;
1942
1943                                         if(!*str)
1944                                                 return False;
1945                                         else
1946                                                 str++;
1947                                 }
1948                                 return False;
1949
1950                         default:
1951                                 if(*str != *p)
1952                                         return False;
1953                                 str++;
1954                                 p++;
1955                                 break;
1956                 }
1957         }
1958
1959         if(!*p && !*str)
1960                 return True;
1961
1962         if (!*p && str[0] == '.' && str[1] == 0)
1963                 return(True);
1964   
1965         if (!*str && *p == '?') {
1966                 while (*p == '?')
1967                         p++;
1968                 return(!*p);
1969         }
1970
1971         if(!*str && (*p == '*' && p[1] == '\0'))
1972                 return True;
1973
1974         return False;
1975 }
1976
1977 /*******************************************************************
1978  Simple case insensitive interface to a UNIX wildcard matcher.
1979 *******************************************************************/
1980
1981 BOOL unix_wild_match(char *pattern, char *string)
1982 {
1983         pstring p2, s2;
1984         char *p;
1985
1986         pstrcpy(p2, pattern);
1987         pstrcpy(s2, string);
1988         strlower(p2);
1989         strlower(s2);
1990
1991         /* Remove any *? and ** from the pattern as they are meaningless */
1992         for(p = p2; *p; p++)
1993                 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
1994                         pstrcpy( &p[1], &p[2]);
1995  
1996         if (strequal(p2,"*"))
1997                 return True;
1998
1999         return unix_do_match(p2, s2) == 0;      
2000 }
2001
2002 /*******************************************************************
2003  construct a data blob, must be freed with data_blob_free()
2004 *******************************************************************/
2005 DATA_BLOB data_blob(const void *p, size_t length)
2006 {
2007         DATA_BLOB ret;
2008
2009         if (!p || !length) {
2010                 ZERO_STRUCT(ret);
2011                 return ret;
2012         }
2013
2014         ret.data = xmemdup(p, length);
2015         ret.length = length;
2016         return ret;
2017 }
2018
2019 /*******************************************************************
2020 free a data blob
2021 *******************************************************************/
2022 void data_blob_free(DATA_BLOB *d)
2023 {
2024         SAFE_FREE(d->data);
2025 }
2026
2027 /*******************************************************************
2028 free a data blob and clear its contents
2029 *******************************************************************/
2030 void data_blob_clear_free(DATA_BLOB *d)
2031 {
2032         if (d->data) {
2033                 memset(d->data, 0, d->length);
2034         }
2035         data_blob_free(d);
2036 }
2037
2038 #ifdef __INSURE__
2039
2040 /*******************************************************************
2041 This routine is a trick to immediately catch errors when debugging
2042 with insure. A xterm with a gdb is popped up when insure catches
2043 a error. It is Linux specific.
2044 ********************************************************************/
2045 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2046 {
2047         static int (*fn)();
2048         int ret;
2049         char pidstr[10];
2050         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'";
2051
2052         slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2053         pstring_sub(cmd, "%d", pidstr);
2054
2055         if (!fn) {
2056                 static void *h;
2057                 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2058                 fn = dlsym(h, "_Insure_trap_error");
2059         }
2060
2061         ret = fn(a1, a2, a3, a4, a5, a6);
2062
2063         system(cmd);
2064
2065         return ret;
2066 }
2067 #endif