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