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