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