doing that irritating compiler clash warning with the protos for standard_sub
[kai/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-1997
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 pstring scope = "";
25
26 int DEBUGLEVEL = 1;
27
28 BOOL passive = False;
29
30 int Protocol = PROTOCOL_COREPLUS;
31
32 /* a default finfo structure to ensure all fields are sensible */
33 file_info def_finfo = {-1,0,0,0,0,0,0,""};
34
35 /* these are some file handles where debug info will be stored */
36 FILE *dbf = NULL;
37
38 /* the client file descriptor */
39 int Client = -1;
40
41 /* the last IP received from */
42 struct in_addr lastip;
43
44 /* the last port received from */
45 int lastport=0;
46
47 /* this is used by the chaining code */
48 int chain_size = 0;
49
50 int trans_num = 0;
51
52 /*
53    case handling on filenames 
54 */
55 int case_default = CASE_LOWER;
56
57 pstring debugf = "";
58 int syslog_level;
59
60 /* the following control case operations - they are put here so the
61    client can link easily */
62 BOOL case_sensitive;
63 BOOL case_preserve;
64 BOOL use_mangled_map = False;
65 BOOL short_case_preserve;
66 BOOL case_mangle;
67
68 fstring remote_machine="";
69 fstring local_machine="";
70 fstring remote_arch="UNKNOWN";
71 fstring remote_proto="UNKNOWN";
72 pstring myhostname="";
73 pstring user_socket_options="";   
74 pstring sesssetup_user="";
75 pstring myname = "";
76 fstring myworkgroup = "";
77 char **my_netbios_names;
78
79 int smb_read_error = 0;
80
81 static BOOL stdout_logging = False;
82
83 static char *filename_dos(char *path,char *buf);
84
85 /*******************************************************************
86   get ready for syslog stuff
87   ******************************************************************/
88 void setup_logging(char *pname,BOOL interactive)
89 {
90 #ifdef SYSLOG
91   if (!interactive) {
92     char *p = strrchr(pname,'/');
93     if (p) pname = p+1;
94     openlog(pname, LOG_PID, LOG_DAEMON);
95   }
96 #endif
97   if (interactive) {
98     stdout_logging = True;
99     dbf = stdout;
100   }
101 }
102
103
104 BOOL append_log=False;
105
106
107 /****************************************************************************
108 reopen the log files
109 ****************************************************************************/
110 void reopen_logs(void)
111 {
112   extern FILE *dbf;
113   pstring fname;
114   
115   if (DEBUGLEVEL > 0)
116     {
117       strcpy(fname,debugf);
118       if (lp_loaded() && (*lp_logfile()))
119         strcpy(fname,lp_logfile());
120
121       if (!strcsequal(fname,debugf) || !dbf || !file_exist(debugf,NULL))
122         {
123           int oldumask = umask(022);
124           strcpy(debugf,fname);
125           if (dbf) fclose(dbf);
126           if (append_log)
127             dbf = fopen(debugf,"a");
128           else
129             dbf = fopen(debugf,"w");
130           if (dbf) setbuf(dbf,NULL);
131           umask(oldumask);
132         }
133     }
134   else
135     {
136       if (dbf)
137         {
138           fclose(dbf);
139           dbf = NULL;
140         }
141     }
142 }
143
144
145 /*******************************************************************
146 check if the log has grown too big
147 ********************************************************************/
148 static void check_log_size(void)
149 {
150   static int debug_count=0;
151   int maxlog;
152   struct stat st;
153
154   if (debug_count++ < 100) return;
155
156   maxlog = lp_max_log_size() * 1024;
157   if (!dbf || maxlog <= 0) return;
158
159   if (fstat(fileno(dbf),&st) == 0 && st.st_size > maxlog) {
160     fclose(dbf); dbf = NULL;
161     reopen_logs();
162     if (dbf && file_size(debugf) > maxlog) {
163       pstring name;
164       fclose(dbf); dbf = NULL;
165       sprintf(name,"%s.old",debugf);
166       sys_rename(debugf,name);
167       reopen_logs();
168     }
169   }
170   debug_count=0;
171 }
172
173
174 /*******************************************************************
175 write an debug message on the debugfile. This is called by the DEBUG
176 macro
177 ********************************************************************/
178 #ifdef __STDC__
179  int Debug1(char *format_str, ...)
180 {
181 #else
182  int Debug1(va_alist)
183 va_dcl
184 {  
185   char *format_str;
186 #endif
187   va_list ap;  
188   
189   if (stdout_logging) {
190 #ifdef __STDC__
191     va_start(ap, format_str);
192 #else
193     va_start(ap);
194     format_str = va_arg(ap,char *);
195 #endif
196     vfprintf(dbf,format_str,ap);
197     va_end(ap);
198     return(0);
199   }
200   
201 #ifdef SYSLOG
202   if (!lp_syslog_only())
203 #endif  
204     {
205       if (!dbf) 
206         {
207           int oldumask = umask(022);
208           dbf = fopen(debugf,"w");
209           umask(oldumask);
210           if (dbf)
211             setbuf(dbf,NULL);
212           else
213             return(0);
214         }
215     }
216
217 #ifdef SYSLOG
218   if (syslog_level < lp_syslog())
219     {
220       /* 
221        * map debug levels to syslog() priorities
222        * note that not all DEBUG(0, ...) calls are
223        * necessarily errors
224        */
225       static int priority_map[] = { 
226         LOG_ERR,     /* 0 */
227         LOG_WARNING, /* 1 */
228         LOG_NOTICE,  /* 2 */
229         LOG_INFO,    /* 3 */
230       };
231       int priority;
232       pstring msgbuf;
233       
234       if (syslog_level >= sizeof(priority_map) / sizeof(priority_map[0]) ||
235           syslog_level < 0)
236         priority = LOG_DEBUG;
237       else
238         priority = priority_map[syslog_level];
239       
240 #ifdef __STDC__
241       va_start(ap, format_str);
242 #else
243       va_start(ap);
244       format_str = va_arg(ap,char *);
245 #endif
246       vsprintf(msgbuf, format_str, ap);
247       va_end(ap);
248       
249       msgbuf[255] = '\0';
250       syslog(priority, "%s", msgbuf);
251     }
252 #endif
253   
254 #ifdef SYSLOG
255   if (!lp_syslog_only())
256 #endif
257     {
258 #ifdef __STDC__
259       va_start(ap, format_str);
260 #else
261       va_start(ap);
262       format_str = va_arg(ap,char *);
263 #endif
264       vfprintf(dbf,format_str,ap);
265       va_end(ap);
266       fflush(dbf);
267     }
268
269   check_log_size();
270
271   return(0);
272 }
273
274 /****************************************************************************
275   find a suitable temporary directory. The result should be copied immediately
276   as it may be overwritten by a subsequent call
277   ****************************************************************************/
278 char *tmpdir(void)
279 {
280   char *p;
281   if ((p = getenv("TMPDIR"))) {
282     return p;
283   }
284   return "/tmp";
285 }
286
287
288
289 /****************************************************************************
290 determine if a file descriptor is in fact a socket
291 ****************************************************************************/
292 BOOL is_a_socket(int fd)
293 {
294   int v,l;
295   l = sizeof(int);
296   return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
297 }
298
299
300 static char *last_ptr=NULL;
301
302 /****************************************************************************
303   Get the next token from a string, return False if none found
304   handles double-quotes. 
305 Based on a routine by GJC@VILLAGE.COM. 
306 Extensively modified by Andrew.Tridgell@anu.edu.au
307 ****************************************************************************/
308 BOOL next_token(char **ptr,char *buff,char *sep)
309 {
310   char *s;
311   BOOL quoted;
312
313   if (!ptr) ptr = &last_ptr;
314   if (!ptr) return(False);
315
316   s = *ptr;
317
318   /* default to simple separators */
319   if (!sep) sep = " \t\n\r";
320
321   /* find the first non sep char */
322   while(*s && strchr(sep,*s)) s++;
323
324   /* nothing left? */
325   if (! *s) return(False);
326
327   /* copy over the token */
328   for (quoted = False; *s && (quoted || !strchr(sep,*s)); s++)
329     {
330       if (*s == '\"') 
331         quoted = !quoted;
332       else
333         *buff++ = *s;
334     }
335
336   *ptr = (*s) ? s+1 : s;  
337   *buff = 0;
338   last_ptr = *ptr;
339
340   return(True);
341 }
342
343 /****************************************************************************
344 Convert list of tokens to array; dependent on above routine.
345 Uses last_ptr from above - bit of a hack.
346 ****************************************************************************/
347 char **toktocliplist(int *ctok, char *sep)
348 {
349   char *s=last_ptr;
350   int ictok=0;
351   char **ret, **iret;
352
353   if (!sep) sep = " \t\n\r";
354
355   while(*s && strchr(sep,*s)) s++;
356
357   /* nothing left? */
358   if (!*s) return(NULL);
359
360   do {
361     ictok++;
362     while(*s && (!strchr(sep,*s))) s++;
363     while(*s && strchr(sep,*s)) *s++=0;
364   } while(*s);
365
366   *ctok=ictok;
367   s=last_ptr;
368
369   if (!(ret=iret=malloc(ictok*sizeof(char *)))) return NULL;
370   
371   while(ictok--) {    
372     *iret++=s;
373     while(*s++);
374     while(!*s) s++;
375   }
376
377   return ret;
378 }
379
380 #ifndef HAVE_MEMMOVE
381 /*******************************************************************
382 safely copies memory, ensuring no overlap problems.
383 this is only used if the machine does not have it's own memmove().
384 this is not the fastest algorithm in town, but it will do for our
385 needs.
386 ********************************************************************/
387 void *MemMove(void *dest,void *src,int size)
388 {
389   unsigned long d,s;
390   int i;
391   if (dest==src || !size) return(dest);
392
393   d = (unsigned long)dest;
394   s = (unsigned long)src;
395
396   if ((d >= (s+size)) || (s >= (d+size))) {
397     /* no overlap */
398     memcpy(dest,src,size);
399     return(dest);
400   }
401
402   if (d < s)
403     {
404       /* we can forward copy */
405       if (s-d >= sizeof(int) && 
406           !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
407         /* do it all as words */
408         int *idest = (int *)dest;
409         int *isrc = (int *)src;
410         size /= sizeof(int);
411         for (i=0;i<size;i++) idest[i] = isrc[i];
412       } else {
413         /* simplest */
414         char *cdest = (char *)dest;
415         char *csrc = (char *)src;
416         for (i=0;i<size;i++) cdest[i] = csrc[i];
417       }
418     }
419   else
420     {
421       /* must backward copy */
422       if (d-s >= sizeof(int) && 
423           !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
424         /* do it all as words */
425         int *idest = (int *)dest;
426         int *isrc = (int *)src;
427         size /= sizeof(int);
428         for (i=size-1;i>=0;i--) idest[i] = isrc[i];
429       } else {
430         /* simplest */
431         char *cdest = (char *)dest;
432         char *csrc = (char *)src;
433         for (i=size-1;i>=0;i--) cdest[i] = csrc[i];
434       }      
435     }
436   return(dest);
437 }
438 #endif
439
440
441 /****************************************************************************
442 prompte a dptr (to make it recently used)
443 ****************************************************************************/
444 void array_promote(char *array,int elsize,int element)
445 {
446   char *p;
447   if (element == 0)
448     return;
449
450   p = (char *)malloc(elsize);
451
452   if (!p)
453     {
454       DEBUG(5,("Ahh! Can't malloc\n"));
455       return;
456     }
457   memcpy(p,array + element * elsize, elsize);
458   memmove(array + elsize,array,elsize*element);
459   memcpy(array,p,elsize);
460   free(p);
461 }
462
463 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
464
465 struct
466 {
467   char *name;
468   int level;
469   int option;
470   int value;
471   int opttype;
472 } socket_options[] = {
473   {"SO_KEEPALIVE",      SOL_SOCKET,    SO_KEEPALIVE,    0,                 OPT_BOOL},
474   {"SO_REUSEADDR",      SOL_SOCKET,    SO_REUSEADDR,    0,                 OPT_BOOL},
475   {"SO_BROADCAST",      SOL_SOCKET,    SO_BROADCAST,    0,                 OPT_BOOL},
476 #ifdef TCP_NODELAY
477   {"TCP_NODELAY",       IPPROTO_TCP,   TCP_NODELAY,     0,                 OPT_BOOL},
478 #endif
479 #ifdef IPTOS_LOWDELAY
480   {"IPTOS_LOWDELAY",    IPPROTO_IP,    IP_TOS,          IPTOS_LOWDELAY,    OPT_ON},
481 #endif
482 #ifdef IPTOS_THROUGHPUT
483   {"IPTOS_THROUGHPUT",  IPPROTO_IP,    IP_TOS,          IPTOS_THROUGHPUT,  OPT_ON},
484 #endif
485 #ifdef SO_SNDBUF
486   {"SO_SNDBUF",         SOL_SOCKET,    SO_SNDBUF,       0,                 OPT_INT},
487 #endif
488 #ifdef SO_RCVBUF
489   {"SO_RCVBUF",         SOL_SOCKET,    SO_RCVBUF,       0,                 OPT_INT},
490 #endif
491 #ifdef SO_SNDLOWAT
492   {"SO_SNDLOWAT",       SOL_SOCKET,    SO_SNDLOWAT,     0,                 OPT_INT},
493 #endif
494 #ifdef SO_RCVLOWAT
495   {"SO_RCVLOWAT",       SOL_SOCKET,    SO_RCVLOWAT,     0,                 OPT_INT},
496 #endif
497 #ifdef SO_SNDTIMEO
498   {"SO_SNDTIMEO",       SOL_SOCKET,    SO_SNDTIMEO,     0,                 OPT_INT},
499 #endif
500 #ifdef SO_RCVTIMEO
501   {"SO_RCVTIMEO",       SOL_SOCKET,    SO_RCVTIMEO,     0,                 OPT_INT},
502 #endif
503   {NULL,0,0,0,0}};
504
505         
506
507 /****************************************************************************
508 set user socket options
509 ****************************************************************************/
510 void set_socket_options(int fd, char *options)
511 {
512   string tok;
513
514   while (next_token(&options,tok," \t,"))
515     {
516       int ret=0,i;
517       int value = 1;
518       char *p;
519       BOOL got_value = False;
520
521       if ((p = strchr(tok,'=')))
522         {
523           *p = 0;
524           value = atoi(p+1);
525           got_value = True;
526         }
527
528       for (i=0;socket_options[i].name;i++)
529         if (strequal(socket_options[i].name,tok))
530           break;
531
532       if (!socket_options[i].name)
533         {
534           DEBUG(0,("Unknown socket option %s\n",tok));
535           continue;
536         }
537
538       switch (socket_options[i].opttype)
539         {
540         case OPT_BOOL:
541         case OPT_INT:
542           ret = setsockopt(fd,socket_options[i].level,
543                            socket_options[i].option,(char *)&value,sizeof(int));
544           break;
545
546         case OPT_ON:
547           if (got_value)
548             DEBUG(0,("syntax error - %s does not take a value\n",tok));
549
550           {
551             int on = socket_options[i].value;
552             ret = setsockopt(fd,socket_options[i].level,
553                              socket_options[i].option,(char *)&on,sizeof(int));
554           }
555           break;          
556         }
557       
558       if (ret != 0)
559         DEBUG(0,("Failed to set socket option %s\n",tok));
560     }
561 }
562
563
564
565 /****************************************************************************
566   close the socket communication
567 ****************************************************************************/
568 void close_sockets(void )
569 {
570   close(Client);
571   Client = 0;
572 }
573
574 /****************************************************************************
575 determine whether we are in the specified group
576 ****************************************************************************/
577 BOOL in_group(gid_t group, int current_gid, int ngroups, int *groups)
578 {
579   int i;
580
581   if (group == current_gid) return(True);
582
583   for (i=0;i<ngroups;i++)
584     if (group == groups[i])
585       return(True);
586
587   return(False);
588 }
589
590 /****************************************************************************
591 this is a safer strcpy(), meant to prevent core dumps when nasty things happen
592 ****************************************************************************/
593 char *StrCpy(char *dest,char *src)
594 {
595   char *d = dest;
596
597 #if AJT
598   /* I don't want to get lazy with these ... */
599   if (!dest || !src) {
600     DEBUG(0,("ERROR: NULL StrCpy() called!\n"));
601     ajt_panic();
602   }
603 #endif
604
605   if (!dest) return(NULL);
606   if (!src) {
607     *dest = 0;
608     return(dest);
609   }
610   while ((*d++ = *src++)) ;
611   return(dest);
612 }
613
614 /****************************************************************************
615 line strncpy but always null terminates. Make sure there is room!
616 ****************************************************************************/
617 char *StrnCpy(char *dest,char *src,int n)
618 {
619   char *d = dest;
620   if (!dest) return(NULL);
621   if (!src) {
622     *dest = 0;
623     return(dest);
624   }
625   while (n-- && (*d++ = *src++)) ;
626   *d = 0;
627   return(dest);
628 }
629
630
631 /*******************************************************************
632 copy an IP address from one buffer to another
633 ********************************************************************/
634 void putip(void *dest,void *src)
635 {
636   memcpy(dest,src,4);
637 }
638
639
640 /****************************************************************************
641 interpret the weird netbios "name". Return the name type
642 ****************************************************************************/
643 static int name_interpret(char *in,char *out)
644 {
645   int ret;
646   int len = (*in++) / 2;
647
648   *out=0;
649
650   if (len > 30 || len<1) return(0);
651
652   while (len--)
653     {
654       if (in[0] < 'A' || in[0] > 'P' || in[1] < 'A' || in[1] > 'P') {
655         *out = 0;
656         return(0);
657       }
658       *out = ((in[0]-'A')<<4) + (in[1]-'A');
659       in += 2;
660       out++;
661     }
662   *out = 0;
663   ret = out[-1];
664
665 #ifdef NETBIOS_SCOPE
666   /* Handle any scope names */
667   while(*in) 
668     {
669       *out++ = '.'; /* Scope names are separated by periods */
670       len = *(unsigned char *)in++;
671       StrnCpy(out, in, len);
672       out += len;
673       *out=0;
674       in += len;
675     }
676 #endif
677   return(ret);
678 }
679
680 /****************************************************************************
681 mangle a name into netbios format
682 ****************************************************************************/
683 int name_mangle(char *In,char *Out,char name_type)
684 {
685   fstring name;
686   char buf[20];
687   char *in = (char *)&buf[0];
688   char *out = (char *)Out;
689   char *p, *label;
690   int i;
691
692   if (In[0] != '*') {
693     StrnCpy(name,In,sizeof(name)-1);
694     sprintf(buf,"%-15.15s%c",name,name_type);
695   } else {
696     buf[0]='*';
697     memset(&buf[1],0,16);
698   }
699
700   *out++ = 32;
701   for (i=0;i<16;i++) {
702     char c = toupper(in[i]);
703     out[i*2] = (c>>4) + 'A';
704     out[i*2+1] = (c & 0xF) + 'A';
705   }
706   out[32]=0;
707   out += 32;
708   
709   label = scope;
710   while (*label)
711     {
712       p = strchr(label, '.');
713       if (p == 0)
714         p = label + strlen(label);
715       *out++ = p - label;
716       memcpy(out, label, p - label);
717       out += p - label;
718       label += p - label + (*p == '.');
719     }
720   *out = 0;
721   return(name_len(Out));
722 }
723
724
725 /*******************************************************************
726   check if a file exists
727 ********************************************************************/
728 BOOL file_exist(char *fname,struct stat *sbuf)
729 {
730   struct stat st;
731   if (!sbuf) sbuf = &st;
732   
733   if (sys_stat(fname,sbuf) != 0) 
734     return(False);
735
736   return(S_ISREG(sbuf->st_mode));
737 }
738
739 /*******************************************************************
740 check a files mod time
741 ********************************************************************/
742 time_t file_modtime(char *fname)
743 {
744   struct stat st;
745   
746   if (sys_stat(fname,&st) != 0) 
747     return(0);
748
749   return(st.st_mtime);
750 }
751
752 /*******************************************************************
753   check if a directory exists
754 ********************************************************************/
755 BOOL directory_exist(char *dname,struct stat *st)
756 {
757   struct stat st2;
758   BOOL ret;
759
760   if (!st) st = &st2;
761
762   if (sys_stat(dname,st) != 0) 
763     return(False);
764
765   ret = S_ISDIR(st->st_mode);
766   if(!ret)
767     errno = ENOTDIR;
768   return ret;
769 }
770
771 /*******************************************************************
772 returns the size in bytes of the named file
773 ********************************************************************/
774 uint32 file_size(char *file_name)
775 {
776   struct stat buf;
777   buf.st_size = 0;
778   sys_stat(file_name,&buf);
779   return(buf.st_size);
780 }
781
782 /*******************************************************************
783 return a string representing an attribute for a file
784 ********************************************************************/
785 char *attrib_string(int mode)
786 {
787   static char attrstr[10];
788
789   attrstr[0] = 0;
790
791   if (mode & aVOLID) strcat(attrstr,"V");
792   if (mode & aDIR) strcat(attrstr,"D");
793   if (mode & aARCH) strcat(attrstr,"A");
794   if (mode & aHIDDEN) strcat(attrstr,"H");
795   if (mode & aSYSTEM) strcat(attrstr,"S");
796   if (mode & aRONLY) strcat(attrstr,"R");         
797
798   return(attrstr);
799 }
800
801
802 /*******************************************************************
803   case insensitive string compararison
804 ********************************************************************/
805 int StrCaseCmp(const char *s, const char *t)
806 {
807   /* compare until we run out of string, either t or s, or find a difference */
808   /* We *must* use toupper rather than tolower here due to the
809      asynchronous upper to lower mapping.
810    */
811 #if defined(KANJI) && !defined(KANJI_WIN95_COMPATIBILITY)
812   /* Win95 treats full width ascii characters as case sensitive. */
813   int diff;
814   for (;;)
815   {
816     if (!*s || !*t)
817           return toupper (*s) - toupper (*t);
818     else if (is_sj_alph (*s) && is_sj_alph (*t))
819         {
820           diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
821           if (diff)
822             return diff;
823           s += 2;
824           t += 2;
825         }
826     else if (is_shift_jis (*s) && is_shift_jis (*t))
827         {
828           diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
829           if (diff)
830             return diff;
831           diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
832           if (diff)
833             return diff;
834           s += 2;
835           t += 2;
836         }
837     else if (is_shift_jis (*s))
838           return 1;
839     else if (is_shift_jis (*t))
840           return -1;
841     else 
842         {
843           diff = toupper (*s) - toupper (*t);
844           if (diff)
845             return diff;
846           s++;
847           t++;
848         }
849   }
850 #else /* KANJI */
851   while (*s && *t && toupper(*s) == toupper(*t))
852   {
853     s++; t++;
854   }
855
856   return(toupper(*s) - toupper(*t));
857 #endif /* KANJI */
858 }
859
860 /*******************************************************************
861   case insensitive string compararison, length limited
862 ********************************************************************/
863 int StrnCaseCmp(const char *s, const char *t, int n)
864 {
865   /* compare until we run out of string, either t or s, or chars */
866   /* We *must* use toupper rather than tolower here due to the
867      asynchronous upper to lower mapping.
868    */
869 #if defined(KANJI) && !defined(KANJI_WIN95_COMPATIBILITY)
870   /* Win95 treats full width ascii characters as case sensitive. */
871   int diff;
872   for (;n > 0;)
873   {
874     if (!*s || !*t)
875           return toupper (*s) - toupper (*t);
876     else if (is_sj_alph (*s) && is_sj_alph (*t))
877         {
878           diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
879           if (diff)
880             return diff;
881           s += 2;
882           t += 2;
883           n -= 2;
884         }
885     else if (is_shift_jis (*s) && is_shift_jis (*t))
886         {
887           diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
888           if (diff)
889             return diff;
890           diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
891           if (diff)
892             return diff;
893           s += 2;
894           t += 2;
895           n -= 2;
896         }
897     else if (is_shift_jis (*s))
898           return 1;
899     else if (is_shift_jis (*t))
900           return -1;
901     else 
902         {
903           diff = toupper (*s) - toupper (*t);
904           if (diff)
905             return diff;
906           s++;
907           t++;
908           n--;
909         }
910   }
911   return 0;
912 #else /* KANJI */
913   while (n-- && *s && *t && toupper(*s) == toupper(*t))
914   {
915     s++; t++;
916   }
917
918   /* not run out of chars - strings are different lengths */
919   if (n) return(toupper(*s) - toupper(*t));
920
921   /* identical up to where we run out of chars, and strings are same length */
922   return(0);
923 #endif /* KANJI */
924 }
925
926 /*******************************************************************
927   compare 2 strings 
928 ********************************************************************/
929 BOOL strequal(const char *s1, const char *s2)
930 {
931   if (s1 == s2) return(True);
932   if (!s1 || !s2) return(False);
933   
934   return(StrCaseCmp(s1,s2)==0);
935 }
936
937 /*******************************************************************
938   compare 2 strings up to and including the nth char.
939   ******************************************************************/
940 BOOL strnequal(const char *s1,const char *s2,int n)
941 {
942   if (s1 == s2) return(True);
943   if (!s1 || !s2 || !n) return(False);
944   
945   return(StrnCaseCmp(s1,s2,n)==0);
946 }
947
948 /*******************************************************************
949   compare 2 strings (case sensitive)
950 ********************************************************************/
951 BOOL strcsequal(char *s1,char *s2)
952 {
953   if (s1 == s2) return(True);
954   if (!s1 || !s2) return(False);
955   
956   return(strcmp(s1,s2)==0);
957 }
958
959
960 /*******************************************************************
961   convert a string to lower case
962 ********************************************************************/
963 void strlower(char *s)
964 {
965   while (*s)
966     {
967 #if defined(KANJI) && !defined(KANJI_WIN95_COMPATIBILITY)
968   /* Win95 treats full width ascii characters as case sensitive. */
969         if (is_shift_jis (*s)) {
970             if (is_sj_upper (s[0], s[1])) {
971                   s[1] = sj_tolower2 (s[1]);
972             }
973             s += 2;
974         } else if (is_kana (*s)) {
975             s++;
976         } else {
977             if (isupper(*s))
978                 *s = tolower(*s);
979             s++;
980         }
981 #else /* KANJI */
982       if (isupper(*s))
983           *s = tolower(*s);
984       s++;
985 #endif /* KANJI */
986     }
987 }
988
989 /*******************************************************************
990   convert a string to upper case
991 ********************************************************************/
992 void strupper(char *s)
993 {
994   while (*s)
995     {
996 #if defined(KANJI) && !defined(KANJI_WIN95_COMPATIBILITY)
997   /* Win95 treats full width ascii characters as case sensitive. */
998         if (is_shift_jis (*s)) {
999             if (is_sj_lower (s[0], s[1])) {
1000                   s[1] = sj_toupper2 (s[1]);
1001             }
1002             s += 2;
1003         } else if (is_kana (*s)) {
1004             s++;
1005         } else {
1006             if (islower(*s))
1007                 *s = toupper(*s);
1008             s++;
1009         }
1010 #else /* KANJI */
1011       if (islower(*s))
1012         *s = toupper(*s);
1013       s++;
1014 #endif /* KANJI */
1015     }
1016 }
1017
1018 /*******************************************************************
1019   convert a string to "normal" form
1020 ********************************************************************/
1021 void strnorm(char *s)
1022 {
1023   if (case_default == CASE_UPPER)
1024     strupper(s);
1025   else
1026     strlower(s);
1027 }
1028
1029 /*******************************************************************
1030 check if a string is in "normal" case
1031 ********************************************************************/
1032 BOOL strisnormal(char *s)
1033 {
1034   if (case_default == CASE_UPPER)
1035     return(!strhaslower(s));
1036
1037   return(!strhasupper(s));
1038 }
1039
1040
1041 /****************************************************************************
1042   string replace
1043 ****************************************************************************/
1044 void string_replace(char *s,char oldc,char newc)
1045 {
1046   while (*s)
1047     {
1048 #if defined(KANJI) && !defined(KANJI_WIN95_COMPATIBILITY)
1049   /* Win95 treats full width ascii characters as case sensitive. */
1050         if (is_shift_jis (*s)) {
1051             s += 2;
1052         } else if (is_kana (*s)) {
1053             s++;
1054         } else {
1055             if (oldc == *s)
1056                 *s = newc;
1057             s++;
1058         }
1059 #else /* KANJI */
1060       if (oldc == *s)
1061         *s = newc;
1062       s++;
1063 #endif /* KANJI */
1064     }
1065 }
1066
1067 /****************************************************************************
1068   make a file into unix format
1069 ****************************************************************************/
1070 void unix_format(char *fname)
1071 {
1072   pstring namecopy;
1073   string_replace(fname,'\\','/');
1074
1075   if (*fname == '/')
1076     {
1077       strcpy(namecopy,fname);
1078       strcpy(fname,".");
1079       strcat(fname,namecopy);
1080     }  
1081 }
1082
1083 /****************************************************************************
1084   make a file into dos format
1085 ****************************************************************************/
1086 void dos_format(char *fname)
1087 {
1088   string_replace(fname,'/','\\');
1089 }
1090
1091
1092 /*******************************************************************
1093   show a smb message structure
1094 ********************************************************************/
1095 void show_msg(char *buf)
1096 {
1097   int i;
1098   int j;
1099   int bcc=0;
1100   if (DEBUGLEVEL < 5)
1101     return;
1102
1103   DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
1104           smb_len(buf),
1105           (int)CVAL(buf,smb_com),
1106           (int)CVAL(buf,smb_rcls),
1107           (int)CVAL(buf,smb_reh),
1108           (int)SVAL(buf,smb_err),
1109           (int)CVAL(buf,smb_flg),
1110           (int)SVAL(buf,smb_flg2)));
1111   DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
1112           (int)SVAL(buf,smb_tid),
1113           (int)SVAL(buf,smb_pid),
1114           (int)SVAL(buf,smb_uid),
1115           (int)SVAL(buf,smb_mid),
1116           (int)CVAL(buf,smb_wct)));
1117   for (i=0;i<(int)CVAL(buf,smb_wct);i++)
1118     DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
1119           SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
1120   bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
1121   DEBUG(5,("smb_bcc=%d\n",bcc));
1122   if (DEBUGLEVEL < 10)
1123     return;
1124   for (i = 0; i < MIN(bcc, 256); i += 16)
1125   {
1126     for (j = 0; j < 16 && i+j < MIN(bcc,256); j++)
1127     {
1128
1129       DEBUG(10,("%2X ",CVAL(smb_buf(buf),i+j)));
1130       if (j == 7) DEBUG(10, ("  "));
1131
1132     }
1133     DEBUG(10,("  "));  
1134
1135     for (j = 0; j < 16 && i+j < MIN(bcc,256); j++)
1136     {
1137       unsigned char c = CVAL(smb_buf(buf),i+j);
1138       if (c < 32 || c > 128) c = '.';
1139       DEBUG(10,("%c",c));
1140
1141       if (j == 7) DEBUG(10, ("  "));
1142     }
1143
1144   DEBUG(10,("\n"));  
1145 }
1146 }
1147
1148 /*******************************************************************
1149   return the length of an smb packet
1150 ********************************************************************/
1151 int smb_len(char *buf)
1152 {
1153   return( PVAL(buf,3) | (PVAL(buf,2)<<8) | ((PVAL(buf,1)&1)<<16) );
1154 }
1155
1156 /*******************************************************************
1157   set the length of an smb packet
1158 ********************************************************************/
1159 void _smb_setlen(char *buf,int len)
1160 {
1161   buf[0] = 0;
1162   buf[1] = (len&0x10000)>>16;
1163   buf[2] = (len&0xFF00)>>8;
1164   buf[3] = len&0xFF;
1165 }
1166
1167 /*******************************************************************
1168   set the length and marker of an smb packet
1169 ********************************************************************/
1170 void smb_setlen(char *buf,int len)
1171 {
1172   _smb_setlen(buf,len);
1173
1174   CVAL(buf,4) = 0xFF;
1175   CVAL(buf,5) = 'S';
1176   CVAL(buf,6) = 'M';
1177   CVAL(buf,7) = 'B';
1178 }
1179
1180 /*******************************************************************
1181   setup the word count and byte count for a smb message
1182 ********************************************************************/
1183 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
1184 {
1185   if (zero)
1186     bzero(buf + smb_size,num_words*2 + num_bytes);
1187   CVAL(buf,smb_wct) = num_words;
1188   SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
1189   smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
1190   return (smb_size + num_words*2 + num_bytes);
1191 }
1192
1193 /*******************************************************************
1194 return the number of smb words
1195 ********************************************************************/
1196 int smb_numwords(char *buf)
1197 {
1198   return (CVAL(buf,smb_wct));
1199 }
1200
1201 /*******************************************************************
1202 return the size of the smb_buf region of a message
1203 ********************************************************************/
1204 int smb_buflen(char *buf)
1205 {
1206   return(SVAL(buf,smb_vwv0 + smb_numwords(buf)*2));
1207 }
1208
1209 /*******************************************************************
1210   return a pointer to the smb_buf data area
1211 ********************************************************************/
1212 int smb_buf_ofs(char *buf)
1213 {
1214   return (smb_size + CVAL(buf,smb_wct)*2);
1215 }
1216
1217 /*******************************************************************
1218   return a pointer to the smb_buf data area
1219 ********************************************************************/
1220 char *smb_buf(char *buf)
1221 {
1222   return (buf + smb_buf_ofs(buf));
1223 }
1224
1225 /*******************************************************************
1226 return the SMB offset into an SMB buffer
1227 ********************************************************************/
1228 int smb_offset(char *p,char *buf)
1229 {
1230   return(PTR_DIFF(p,buf+4) + chain_size);
1231 }
1232
1233
1234 /*******************************************************************
1235 skip past some strings in a buffer
1236 ********************************************************************/
1237 char *skip_string(char *buf,int n)
1238 {
1239   while (n--)
1240     buf += strlen(buf) + 1;
1241   return(buf);
1242 }
1243
1244 /*******************************************************************
1245 trim the specified elements off the front and back of a string
1246 ********************************************************************/
1247 BOOL trim_string(char *s,char *front,char *back)
1248 {
1249   BOOL ret = False;
1250   while (front && *front && strncmp(s,front,strlen(front)) == 0)
1251     {
1252       char *p = s;
1253       ret = True;
1254       while (1)
1255         {
1256           if (!(*p = p[strlen(front)]))
1257             break;
1258           p++;
1259         }
1260     }
1261   while (back && *back && strlen(s) >= strlen(back) && 
1262          (strncmp(s+strlen(s)-strlen(back),back,strlen(back))==0))  
1263     {
1264       ret = True;
1265       s[strlen(s)-strlen(back)] = 0;
1266     }
1267   return(ret);
1268 }
1269
1270
1271 /*******************************************************************
1272 reduce a file name, removing .. elements.
1273 ********************************************************************/
1274 void dos_clean_name(char *s)
1275 {
1276   char *p=NULL;
1277
1278   DEBUG(3,("dos_clean_name [%s]\n",s));
1279
1280   /* remove any double slashes */
1281   string_sub(s, "\\\\", "\\");
1282
1283   while ((p = strstr(s,"\\..\\")) != NULL)
1284     {
1285       pstring s1;
1286
1287       *p = 0;
1288       strcpy(s1,p+3);
1289
1290       if ((p=strrchr(s,'\\')) != NULL)
1291         *p = 0;
1292       else
1293         *s = 0;
1294       strcat(s,s1);
1295     }  
1296
1297   trim_string(s,NULL,"\\..");
1298
1299   string_sub(s, "\\.\\", "\\");
1300 }
1301
1302 /*******************************************************************
1303 reduce a file name, removing .. elements. 
1304 ********************************************************************/
1305 void unix_clean_name(char *s)
1306 {
1307   char *p=NULL;
1308
1309   DEBUG(3,("unix_clean_name [%s]\n",s));
1310
1311   /* remove any double slashes */
1312   string_sub(s, "//","/");
1313
1314   /* Remove leading ./ characters */
1315   if(strncmp(s, "./", 2) == 0) {
1316     trim_string(s, "./", NULL);
1317     if(*s == 0)
1318       strcpy(s,"./");
1319   }
1320
1321   while ((p = strstr(s,"/../")) != NULL)
1322     {
1323       pstring s1;
1324
1325       *p = 0;
1326       strcpy(s1,p+3);
1327
1328       if ((p=strrchr(s,'/')) != NULL)
1329         *p = 0;
1330       else
1331         *s = 0;
1332       strcat(s,s1);
1333     }  
1334
1335   trim_string(s,NULL,"/..");
1336 }
1337
1338
1339 /*******************************************************************
1340 a wrapper for the normal chdir() function
1341 ********************************************************************/
1342 int ChDir(char *path)
1343 {
1344   int res;
1345   static pstring LastDir="";
1346
1347   if (strcsequal(path,".")) return(0);
1348
1349   if (*path == '/' && strcsequal(LastDir,path)) return(0);
1350   DEBUG(3,("chdir to %s\n",path));
1351   res = sys_chdir(path);
1352   if (!res)
1353     strcpy(LastDir,path);
1354   return(res);
1355 }
1356
1357 /* number of list structures for a caching GetWd function. */
1358 #define MAX_GETWDCACHE (50)
1359
1360 struct
1361 {
1362   ino_t inode;
1363   dev_t dev;
1364   char *text;
1365   BOOL valid;
1366 } ino_list[MAX_GETWDCACHE];
1367
1368 BOOL use_getwd_cache=True;
1369
1370 /*******************************************************************
1371   return the absolute current directory path
1372 ********************************************************************/
1373 char *GetWd(char *str)
1374 {
1375   pstring s;
1376   static BOOL getwd_cache_init = False;
1377   struct stat st, st2;
1378   int i;
1379
1380   *s = 0;
1381
1382   if (!use_getwd_cache)
1383     return(sys_getwd(str));
1384
1385   /* init the cache */
1386   if (!getwd_cache_init)
1387     {
1388       getwd_cache_init = True;
1389       for (i=0;i<MAX_GETWDCACHE;i++)
1390         {
1391           string_init(&ino_list[i].text,"");
1392           ino_list[i].valid = False;
1393         }
1394     }
1395
1396   /*  Get the inode of the current directory, if this doesn't work we're
1397       in trouble :-) */
1398
1399   if (stat(".",&st) == -1) 
1400     {
1401       DEBUG(0,("Very strange, couldn't stat \".\"\n"));
1402       return(sys_getwd(str));
1403     }
1404
1405
1406   for (i=0; i<MAX_GETWDCACHE; i++)
1407     if (ino_list[i].valid)
1408       {
1409
1410         /*  If we have found an entry with a matching inode and dev number
1411             then find the inode number for the directory in the cached string.
1412             If this agrees with that returned by the stat for the current
1413             directory then all is o.k. (but make sure it is a directory all
1414             the same...) */
1415       
1416         if (st.st_ino == ino_list[i].inode &&
1417             st.st_dev == ino_list[i].dev)
1418           {
1419             if (stat(ino_list[i].text,&st2) == 0)
1420               {
1421                 if (st.st_ino == st2.st_ino &&
1422                     st.st_dev == st2.st_dev &&
1423                     (st2.st_mode & S_IFMT) == S_IFDIR)
1424                   {
1425                     strcpy (str, ino_list[i].text);
1426
1427                     /* promote it for future use */
1428                     array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
1429                     return (str);
1430                   }
1431                 else
1432                   {
1433                     /*  If the inode is different then something's changed, 
1434                         scrub the entry and start from scratch. */
1435                     ino_list[i].valid = False;
1436                   }
1437               }
1438           }
1439       }
1440
1441
1442   /*  We don't have the information to hand so rely on traditional methods.
1443       The very slow getcwd, which spawns a process on some systems, or the
1444       not quite so bad getwd. */
1445
1446   if (!sys_getwd(s))
1447     {
1448       DEBUG(0,("Getwd failed, errno %d\n",errno));
1449       return (NULL);
1450     }
1451
1452   strcpy(str,s);
1453
1454   DEBUG(5,("GetWd %s, inode %d, dev %x\n",s,(int)st.st_ino,(int)st.st_dev));
1455
1456   /* add it to the cache */
1457   i = MAX_GETWDCACHE - 1;
1458   string_set(&ino_list[i].text,s);
1459   ino_list[i].dev = st.st_dev;
1460   ino_list[i].inode = st.st_ino;
1461   ino_list[i].valid = True;
1462
1463   /* put it at the top of the list */
1464   array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
1465
1466   return (str);
1467 }
1468
1469
1470
1471 /*******************************************************************
1472 reduce a file name, removing .. elements and checking that 
1473 it is below dir in the heirachy. This uses GetWd() and so must be run
1474 on the system that has the referenced file system.
1475
1476 widelinks are allowed if widelinks is true
1477 ********************************************************************/
1478 BOOL reduce_name(char *s,char *dir,BOOL widelinks)
1479 {
1480 #ifndef REDUCE_PATHS
1481   return True;
1482 #else
1483   pstring dir2;
1484   pstring wd;
1485   pstring basename;
1486   pstring newname;
1487   char *p=NULL;
1488   BOOL relative = (*s != '/');
1489
1490   *dir2 = *wd = *basename = *newname = 0;
1491
1492   if (widelinks)
1493     {
1494       unix_clean_name(s);
1495       /* can't have a leading .. */
1496       if (strncmp(s,"..",2) == 0 && (s[2]==0 || s[2]=='/'))
1497         {
1498           DEBUG(3,("Illegal file name? (%s)\n",s));
1499           return(False);
1500         }
1501
1502       if (strlen(s) == 0)
1503         strcpy(s,"./");
1504
1505       return(True);
1506     }
1507   
1508   DEBUG(3,("reduce_name [%s] [%s]\n",s,dir));
1509
1510   /* remove any double slashes */
1511   string_sub(s,"//","/");
1512
1513   strcpy(basename,s);
1514   p = strrchr(basename,'/');
1515
1516   if (!p)
1517     return(True);
1518
1519   if (!GetWd(wd))
1520     {
1521       DEBUG(0,("couldn't getwd for %s %s\n",s,dir));
1522       return(False);
1523     }
1524
1525   if (ChDir(dir) != 0)
1526     {
1527       DEBUG(0,("couldn't chdir to %s\n",dir));
1528       return(False);
1529     }
1530
1531   if (!GetWd(dir2))
1532     {
1533       DEBUG(0,("couldn't getwd for %s\n",dir));
1534       ChDir(wd);
1535       return(False);
1536     }
1537
1538
1539     if (p && (p != basename))
1540       {
1541         *p = 0;
1542         if (strcmp(p+1,".")==0)
1543           p[1]=0;
1544         if (strcmp(p+1,"..")==0)
1545           *p = '/';
1546       }
1547
1548   if (ChDir(basename) != 0)
1549     {
1550       ChDir(wd);
1551       DEBUG(3,("couldn't chdir for %s %s basename=%s\n",s,dir,basename));
1552       return(False);
1553     }
1554
1555   if (!GetWd(newname))
1556     {
1557       ChDir(wd);
1558       DEBUG(2,("couldn't get wd for %s %s\n",s,dir2));
1559       return(False);
1560     }
1561
1562   if (p && (p != basename))
1563     {
1564       strcat(newname,"/");
1565       strcat(newname,p+1);
1566     }
1567
1568   {
1569     int l = strlen(dir2);    
1570     if (dir2[l-1] == '/')
1571       l--;
1572
1573     if (strncmp(newname,dir2,l) != 0)
1574       {
1575         ChDir(wd);
1576         DEBUG(2,("Bad access attempt? s=%s dir=%s newname=%s l=%d\n",s,dir2,newname,l));
1577         return(False);
1578       }
1579
1580     if (relative)
1581       {
1582         if (newname[l] == '/')
1583           strcpy(s,newname + l + 1);
1584         else
1585           strcpy(s,newname+l);
1586       }
1587     else
1588       strcpy(s,newname);
1589   }
1590
1591   ChDir(wd);
1592
1593   if (strlen(s) == 0)
1594     strcpy(s,"./");
1595
1596   DEBUG(3,("reduced to %s\n",s));
1597   return(True);
1598 #endif
1599 }
1600
1601 /****************************************************************************
1602 expand some *s 
1603 ****************************************************************************/
1604 static void expand_one(char *Mask,int len)
1605 {
1606   char *p1;
1607   while ((p1 = strchr(Mask,'*')) != NULL)
1608     {
1609       int lfill = (len+1) - strlen(Mask);
1610       int l1= (p1 - Mask);
1611       pstring tmp;
1612       strcpy(tmp,Mask);  
1613       memset(tmp+l1,'?',lfill);
1614       strcpy(tmp + l1 + lfill,Mask + l1 + 1);   
1615       strcpy(Mask,tmp);      
1616     }
1617 }
1618
1619 /****************************************************************************
1620 expand a wildcard expression, replacing *s with ?s
1621 ****************************************************************************/
1622 void expand_mask(char *Mask,BOOL doext)
1623 {
1624   pstring mbeg,mext;
1625   pstring dirpart;
1626   pstring filepart;
1627   BOOL hasdot = False;
1628   char *p1;
1629   BOOL absolute = (*Mask == '\\');
1630
1631   *mbeg = *mext = *dirpart = *filepart = 0;
1632
1633   /* parse the directory and filename */
1634   if (strchr(Mask,'\\'))
1635     dirname_dos(Mask,dirpart);
1636
1637   filename_dos(Mask,filepart);
1638
1639   strcpy(mbeg,filepart);
1640   if ((p1 = strchr(mbeg,'.')) != NULL)
1641     {
1642       hasdot = True;
1643       *p1 = 0;
1644       p1++;
1645       strcpy(mext,p1);
1646     }
1647   else
1648     {
1649       strcpy(mext,"");
1650       if (strlen(mbeg) > 8)
1651         {
1652           strcpy(mext,mbeg + 8);
1653           mbeg[8] = 0;
1654         }
1655     }
1656
1657   if (*mbeg == 0)
1658     strcpy(mbeg,"????????");
1659   if ((*mext == 0) && doext && !hasdot)
1660     strcpy(mext,"???");
1661
1662   if (strequal(mbeg,"*") && *mext==0) 
1663     strcpy(mext,"*");
1664
1665   /* expand *'s */
1666   expand_one(mbeg,8);
1667   if (*mext)
1668     expand_one(mext,3);
1669
1670   strcpy(Mask,dirpart);
1671   if (*dirpart || absolute) strcat(Mask,"\\");
1672   strcat(Mask,mbeg);
1673   strcat(Mask,".");
1674   strcat(Mask,mext);
1675
1676   DEBUG(6,("Mask expanded to [%s]\n",Mask));
1677 }  
1678
1679
1680 /****************************************************************************
1681 does a string have any uppercase chars in it?
1682 ****************************************************************************/
1683 BOOL strhasupper(char *s)
1684 {
1685   while (*s) 
1686     {
1687 #if defined(KANJI) && !defined(KANJI_WIN95_COMPATIBILITY)
1688   /* Win95 treats full width ascii characters as case sensitive. */
1689         if (is_shift_jis (*s)) {
1690             s += 2;
1691         } else if (is_kana (*s)) {
1692             s++;
1693         } else {
1694             if (isupper(*s)) return(True);
1695             s++;
1696         }
1697 #else /* KANJI */
1698       if (isupper(*s)) return(True);
1699       s++;
1700 #endif /* KANJI */
1701     }
1702   return(False);
1703 }
1704
1705 /****************************************************************************
1706 does a string have any lowercase chars in it?
1707 ****************************************************************************/
1708 BOOL strhaslower(char *s)
1709 {
1710   while (*s) 
1711     {
1712 #if defined(KANJI) && !defined(KANJI_WIN95_COMPATIBILITY)
1713   /* Win95 treats full width ascii characters as case sensitive. */
1714         if (is_shift_jis (*s)) {
1715             if (is_sj_upper (s[0], s[1])) return(True);
1716             if (is_sj_lower (s[0], s[1])) return (True);
1717             s += 2;
1718         } else if (is_kana (*s)) {
1719             s++;
1720         } else {
1721             if (islower(*s)) return(True);
1722             s++;
1723         }
1724 #else /* KANJI */
1725       if (islower(*s)) return(True);
1726       s++;
1727 #endif /* KANJI */
1728     }
1729   return(False);
1730 }
1731
1732 /****************************************************************************
1733 find the number of chars in a string
1734 ****************************************************************************/
1735 int count_chars(char *s,char c)
1736 {
1737   int count=0;
1738 #if defined(KANJI) && !defined(KANJI_WIN95_COMPATIBILITY)
1739   /* Win95 treats full width ascii characters as case sensitive. */
1740   while (*s) 
1741     {
1742     if (is_shift_jis (*s))
1743           s += 2;
1744     else 
1745         {
1746       if (*s == c)
1747         count++;
1748       s++;
1749     }
1750   }
1751 #else /* KANJI */
1752   while (*s) 
1753     {
1754       if (*s == c)
1755         count++;
1756       s++;
1757     }
1758 #endif /* KANJI */
1759   return(count);
1760 }
1761
1762
1763 /****************************************************************************
1764   make a dir struct
1765 ****************************************************************************/
1766 void make_dir_struct(char *buf,char *mask,char *fname,unsigned int size,int mode,time_t date)
1767 {  
1768   char *p;
1769   pstring mask2;
1770
1771   strcpy(mask2,mask);
1772
1773   if ((mode & aDIR) != 0)
1774     size = 0;
1775
1776   memset(buf+1,' ',11);
1777   if ((p = strchr(mask2,'.')) != NULL)
1778     {
1779       *p = 0;
1780       memcpy(buf+1,mask2,MIN(strlen(mask2),8));
1781       memcpy(buf+9,p+1,MIN(strlen(p+1),3));
1782       *p = '.';
1783     }
1784   else
1785     memcpy(buf+1,mask2,MIN(strlen(mask2),11));
1786
1787   bzero(buf+21,DIR_STRUCT_SIZE-21);
1788   CVAL(buf,21) = mode;
1789   put_dos_date(buf,22,date);
1790   SSVAL(buf,26,size & 0xFFFF);
1791   SSVAL(buf,28,size >> 16);
1792   StrnCpy(buf+30,fname,12);
1793   if (!case_sensitive)
1794     strupper(buf+30);
1795   DEBUG(8,("put name [%s] into dir struct\n",buf+30));
1796 }
1797
1798
1799 /*******************************************************************
1800 close the low 3 fd's and open dev/null in their place
1801 ********************************************************************/
1802 void close_low_fds(void)
1803 {
1804   int fd;
1805   int i;
1806   close(0); close(1); close(2);
1807   /* try and use up these file descriptors, so silly
1808      library routines writing to stdout etc won't cause havoc */
1809   for (i=0;i<3;i++) {
1810     fd = open("/dev/null",O_RDWR,0);
1811     if (fd < 0) fd = open("/dev/null",O_WRONLY,0);
1812     if (fd < 0) {
1813       DEBUG(0,("Can't open /dev/null\n"));
1814       return;
1815     }
1816     if (fd != i) {
1817       DEBUG(0,("Didn't get file descriptor %d\n",i));
1818       return;
1819     }
1820   }
1821 }
1822
1823 /****************************************************************************
1824 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
1825 else
1826 if SYSV use O_NDELAY
1827 if BSD use FNDELAY
1828 ****************************************************************************/
1829 int set_blocking(int fd, BOOL set)
1830 {
1831   int val;
1832 #ifdef O_NONBLOCK
1833 #define FLAG_TO_SET O_NONBLOCK
1834 #else
1835 #ifdef SYSV
1836 #define FLAG_TO_SET O_NDELAY
1837 #else /* BSD */
1838 #define FLAG_TO_SET FNDELAY
1839 #endif
1840 #endif
1841
1842   if((val = fcntl(fd, F_GETFL, 0)) == -1)
1843         return -1;
1844   if(set) /* Turn blocking on - ie. clear nonblock flag */
1845         val &= ~FLAG_TO_SET;
1846   else
1847     val |= FLAG_TO_SET;
1848   return fcntl( fd, F_SETFL, val);
1849 #undef FLAG_TO_SET
1850 }
1851
1852
1853 /****************************************************************************
1854 write to a socket
1855 ****************************************************************************/
1856 int write_socket(int fd,char *buf,int len)
1857 {
1858   int ret=0;
1859
1860   if (passive)
1861     return(len);
1862   DEBUG(6,("write_socket(%d,%d)\n",fd,len));
1863   ret = write_data(fd,buf,len);
1864       
1865   DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,len,ret));
1866   return(ret);
1867 }
1868
1869 /****************************************************************************
1870 read from a socket
1871 ****************************************************************************/
1872 int read_udp_socket(int fd,char *buf,int len)
1873 {
1874   int ret;
1875   struct sockaddr sock;
1876   int socklen;
1877   
1878   socklen = sizeof(sock);
1879   bzero((char *)&sock,socklen);
1880   bzero((char *)&lastip,sizeof(lastip));
1881   ret = recvfrom(fd,buf,len,0,&sock,&socklen);
1882   if (ret <= 0) {
1883     DEBUG(2,("read socket failed. ERRNO=%d\n",errno));
1884     return(0);
1885   }
1886
1887   lastip = *(struct in_addr *) &sock.sa_data[2];
1888   lastport = ntohs(((struct sockaddr_in *)&sock)->sin_port);
1889
1890   return(ret);
1891 }
1892
1893 /****************************************************************************
1894 read data from a device with a timout in msec.
1895 mincount = if timeout, minimum to read before returning
1896 maxcount = number to be read.
1897 ****************************************************************************/
1898 int read_with_timeout(int fd,char *buf,int mincnt,int maxcnt,long time_out)
1899 {
1900   fd_set fds;
1901   int selrtn;
1902   int readret;
1903   int nread = 0;
1904   struct timeval timeout;
1905
1906   /* just checking .... */
1907   if (maxcnt <= 0) return(0);
1908
1909   smb_read_error = 0;
1910
1911   /* Blocking read */
1912   if (time_out <= 0) {
1913     if (mincnt == 0) mincnt = maxcnt;
1914
1915     while (nread < mincnt) {
1916       readret = read(fd, buf + nread, maxcnt - nread);
1917       if (readret == 0) {
1918         smb_read_error = READ_EOF;
1919         return -1;
1920       }
1921
1922       if (readret == -1) {
1923         smb_read_error = READ_ERROR;
1924         return -1;
1925       }
1926       nread += readret;
1927     }
1928     return(nread);
1929   }
1930   
1931   /* Most difficult - timeout read */
1932   /* If this is ever called on a disk file and 
1933          mincnt is greater then the filesize then
1934          system performance will suffer severely as 
1935          select always return true on disk files */
1936
1937   /* Set initial timeout */
1938   timeout.tv_sec = time_out / 1000;
1939   timeout.tv_usec = 1000 * (time_out % 1000);
1940
1941   for (nread=0; nread<mincnt; ) 
1942     {      
1943       FD_ZERO(&fds);
1944       FD_SET(fd,&fds);
1945       
1946       selrtn = sys_select(&fds,&timeout);
1947
1948       /* Check if error */
1949       if(selrtn == -1) {
1950         /* something is wrong. Maybe the socket is dead? */
1951         smb_read_error = READ_ERROR;
1952         return -1;
1953       }
1954       
1955       /* Did we timeout ? */
1956       if (selrtn == 0) {
1957         smb_read_error = READ_TIMEOUT;
1958         return -1;
1959       }
1960       
1961       readret = read(fd, buf+nread, maxcnt-nread);
1962       if (readret == 0) {
1963         /* we got EOF on the file descriptor */
1964         smb_read_error = READ_EOF;
1965         return -1;
1966       }
1967
1968       if (readret == -1) {
1969         /* the descriptor is probably dead */
1970         smb_read_error = READ_ERROR;
1971         return -1;
1972       }
1973       
1974       nread += readret;
1975     }
1976
1977   /* Return the number we got */
1978   return(nread);
1979 }
1980
1981 /****************************************************************************
1982 read data from the client. Maxtime is in milliseconds
1983 ****************************************************************************/
1984 int read_max_udp(int fd,char *buffer,int bufsize,int maxtime)
1985 {
1986   fd_set fds;
1987   int selrtn;
1988   int nread;
1989   struct timeval timeout;
1990  
1991   FD_ZERO(&fds);
1992   FD_SET(fd,&fds);
1993
1994   timeout.tv_sec = maxtime / 1000;
1995   timeout.tv_usec = (maxtime % 1000) * 1000;
1996
1997   selrtn = sys_select(&fds,maxtime>0?&timeout:NULL);
1998
1999   if (!FD_ISSET(fd,&fds))
2000     return 0;
2001
2002   nread = read_udp_socket(fd, buffer, bufsize);
2003
2004   /* return the number got */
2005   return(nread);
2006 }
2007
2008 /*******************************************************************
2009 find the difference in milliseconds between two struct timeval
2010 values
2011 ********************************************************************/
2012 int TvalDiff(struct timeval *tvalold,struct timeval *tvalnew)
2013 {
2014   return((tvalnew->tv_sec - tvalold->tv_sec)*1000 + 
2015          ((int)tvalnew->tv_usec - (int)tvalold->tv_usec)/1000);  
2016 }
2017
2018 /****************************************************************************
2019 send a keepalive packet (rfc1002)
2020 ****************************************************************************/
2021 BOOL send_keepalive(int client)
2022 {
2023   unsigned char buf[4];
2024
2025   buf[0] = 0x85;
2026   buf[1] = buf[2] = buf[3] = 0;
2027
2028   return(write_data(client,(char *)buf,4) == 4);
2029 }
2030
2031
2032
2033 /****************************************************************************
2034   read data from the client, reading exactly N bytes. 
2035 ****************************************************************************/
2036 int read_data(int fd,char *buffer,int N)
2037 {
2038   int  ret;
2039   int total=0;  
2040  
2041   smb_read_error = 0;
2042
2043   while (total < N)
2044     {
2045       ret = read(fd,buffer + total,N - total);
2046       if (ret == 0) {
2047         smb_read_error = READ_EOF;
2048         return 0;
2049       }
2050       if (ret == -1) {
2051         smb_read_error = READ_ERROR;
2052         return -1;
2053       }
2054       total += ret;
2055     }
2056   return total;
2057 }
2058
2059
2060 /****************************************************************************
2061   write data to a fd 
2062 ****************************************************************************/
2063 int write_data(int fd,char *buffer,int N)
2064 {
2065   int total=0;
2066   int ret;
2067
2068   while (total < N)
2069     {
2070       ret = write(fd,buffer + total,N - total);
2071
2072       if (ret == -1) return -1;
2073       if (ret == 0) return total;
2074
2075       total += ret;
2076     }
2077   return total;
2078 }
2079
2080
2081 /****************************************************************************
2082 transfer some data between two fd's
2083 ****************************************************************************/
2084 int transfer_file(int infd,int outfd,int n,char *header,int headlen,int align)
2085 {
2086   static char *buf=NULL;  
2087   static int size=0;
2088   char *buf1,*abuf;
2089   int total = 0;
2090
2091   DEBUG(4,("transfer_file %d  (head=%d) called\n",n,headlen));
2092
2093   if (size == 0) {
2094     size = lp_readsize();
2095     size = MAX(size,1024);
2096   }
2097
2098   while (!buf && size>0) {
2099     buf = (char *)Realloc(buf,size+8);
2100     if (!buf) size /= 2;
2101   }
2102
2103   if (!buf) {
2104     DEBUG(0,("Can't allocate transfer buffer!\n"));
2105     exit(1);
2106   }
2107
2108   abuf = buf + (align%8);
2109
2110   if (header)
2111     n += headlen;
2112
2113   while (n > 0)
2114     {
2115       int s = MIN(n,size);
2116       int ret,ret2=0;
2117
2118       ret = 0;
2119
2120       if (header && (headlen >= MIN(s,1024))) {
2121         buf1 = header;
2122         s = headlen;
2123         ret = headlen;
2124         headlen = 0;
2125         header = NULL;
2126       } else {
2127         buf1 = abuf;
2128       }
2129
2130       if (header && headlen > 0)
2131         {
2132           ret = MIN(headlen,size);
2133           memcpy(buf1,header,ret);
2134           headlen -= ret;
2135           header += ret;
2136           if (headlen <= 0) header = NULL;
2137         }
2138
2139       if (s > ret)
2140         ret += read(infd,buf1+ret,s-ret);
2141
2142       if (ret > 0)
2143         {
2144           ret2 = (outfd>=0?write_data(outfd,buf1,ret):ret);
2145           if (ret2 > 0) total += ret2;
2146           /* if we can't write then dump excess data */
2147           if (ret2 != ret)
2148             transfer_file(infd,-1,n-(ret+headlen),NULL,0,0);
2149         }
2150       if (ret <= 0 || ret2 != ret)
2151         return(total);
2152       n -= ret;
2153     }
2154   return(total);
2155 }
2156
2157
2158 /****************************************************************************
2159 read 4 bytes of a smb packet and return the smb length of the packet
2160 possibly store the result in the buffer
2161 ****************************************************************************/
2162 int read_smb_length(int fd,char *inbuf,int timeout)
2163 {
2164   char *buffer;
2165   char buf[4];
2166   int len=0, msg_type;
2167   BOOL ok=False;
2168
2169   if (inbuf)
2170     buffer = inbuf;
2171   else
2172     buffer = buf;
2173
2174   while (!ok)
2175     {
2176       if (timeout > 0)
2177         ok = (read_with_timeout(fd,buffer,4,4,timeout) == 4);
2178       else 
2179         ok = (read_data(fd,buffer,4) == 4);
2180
2181       if (!ok)
2182         return(-1);
2183
2184       len = smb_len(buffer);
2185       msg_type = CVAL(buffer,0);
2186
2187       if (msg_type == 0x85) 
2188         {
2189           DEBUG(5,("Got keepalive packet\n"));
2190           ok = False;
2191         }
2192     }
2193
2194   DEBUG(10,("got smb length of %d\n",len));
2195
2196   return(len);
2197 }
2198
2199
2200
2201 /****************************************************************************
2202   read an smb from a fd and return it's length
2203 The timeout is in milli seconds
2204 ****************************************************************************/
2205 BOOL receive_smb(int fd,char *buffer,int timeout)
2206 {
2207   int len,ret;
2208
2209   smb_read_error = 0;
2210
2211   bzero(buffer,smb_size + 100);
2212
2213   len = read_smb_length(fd,buffer,timeout);
2214   if (len == -1)
2215     return(False);
2216
2217   if (len > BUFFER_SIZE) {
2218     DEBUG(0,("Invalid packet length! (%d bytes).\n",len));
2219     if (len > BUFFER_SIZE + (SAFETY_MARGIN/2))
2220       exit(1);
2221   }
2222
2223   ret = read_data(fd,buffer+4,len);
2224   if (ret != len) {
2225     smb_read_error = READ_ERROR;
2226     return False;
2227   }
2228
2229   return(True);
2230 }
2231
2232
2233 /****************************************************************************
2234   send an smb to a fd 
2235 ****************************************************************************/
2236 BOOL send_smb(int fd,char *buffer)
2237 {
2238   int len;
2239   int ret,nwritten=0;
2240   len = smb_len(buffer) + 4;
2241
2242   while (nwritten < len)
2243     {
2244       ret = write_socket(fd,buffer+nwritten,len - nwritten);
2245       if (ret <= 0)
2246         {
2247           DEBUG(0,("Error writing %d bytes to client. %d. Exiting\n",len,ret));
2248           close_sockets();
2249           exit(1);
2250         }
2251       nwritten += ret;
2252     }
2253
2254
2255   return True;
2256 }
2257
2258
2259 /****************************************************************************
2260 find a pointer to a netbios name
2261 ****************************************************************************/
2262 char *name_ptr(char *buf,int ofs)
2263 {
2264   unsigned char c = *(unsigned char *)(buf+ofs);
2265
2266   if ((c & 0xC0) == 0xC0)
2267     {
2268       uint16 l;
2269       char p[2];
2270       memcpy(p,buf+ofs,2);
2271       p[0] &= ~0xC0;
2272       l = RSVAL(p,0);
2273       DEBUG(5,("name ptr to pos %d from %d is %s\n",l,ofs,buf+l));
2274       return(buf + l);
2275     }
2276   else
2277     return(buf+ofs);
2278 }  
2279
2280 /****************************************************************************
2281 extract a netbios name from a buf
2282 ****************************************************************************/
2283 int name_extract(char *buf,int ofs,char *name)
2284 {
2285   char *p = name_ptr(buf,ofs);
2286   int d = PTR_DIFF(p,buf+ofs);
2287   strcpy(name,"");
2288   if (d < -50 || d > 50) return(0);
2289   return(name_interpret(p,name));
2290 }  
2291   
2292
2293 /****************************************************************************
2294 return the total storage length of a mangled name
2295 ****************************************************************************/
2296 int name_len(char *s)
2297 {
2298   char *s0=s;
2299   unsigned char c = *(unsigned char *)s;
2300   if ((c & 0xC0) == 0xC0)
2301     return(2);
2302   while (*s) s += (*s)+1;
2303   return(PTR_DIFF(s,s0)+1);
2304 }
2305
2306 /****************************************************************************
2307 send a single packet to a port on another machine
2308 ****************************************************************************/
2309 BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
2310 {
2311   BOOL ret;
2312   int out_fd;
2313   struct sockaddr_in sock_out;
2314
2315   if (passive)
2316     return(True);
2317
2318   /* create a socket to write to */
2319   out_fd = socket(AF_INET, type, 0);
2320   if (out_fd == -1) 
2321     {
2322       DEBUG(0,("socket failed"));
2323       return False;
2324     }
2325
2326   /* set the address and port */
2327   bzero((char *)&sock_out,sizeof(sock_out));
2328   putip((char *)&sock_out.sin_addr,(char *)&ip);
2329   sock_out.sin_port = htons( port );
2330   sock_out.sin_family = AF_INET;
2331   
2332   if (DEBUGLEVEL > 0)
2333     DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
2334              len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));
2335         
2336   /* send it */
2337   ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);
2338
2339   if (!ret)
2340     DEBUG(0,("Packet send to %s(%d) failed ERRNO=%d\n",
2341              inet_ntoa(ip),port,errno));
2342
2343   close(out_fd);
2344   return(ret);
2345 }
2346
2347 /*******************************************************************
2348 sleep for a specified number of milliseconds
2349 ********************************************************************/
2350 void msleep(int t)
2351 {
2352   int tdiff=0;
2353   struct timeval tval,t1,t2;  
2354   fd_set fds;
2355
2356   GetTimeOfDay(&t1);
2357   GetTimeOfDay(&t2);
2358   
2359   while (tdiff < t) {
2360     tval.tv_sec = (t-tdiff)/1000;
2361     tval.tv_usec = 1000*((t-tdiff)%1000);
2362  
2363     FD_ZERO(&fds);
2364     errno = 0;
2365     sys_select(&fds,&tval);
2366
2367     GetTimeOfDay(&t2);
2368     tdiff = TvalDiff(&t1,&t2);
2369   }
2370 }
2371
2372 /****************************************************************************
2373 check if a string is part of a list
2374 ****************************************************************************/
2375 BOOL in_list(char *s,char *list,BOOL casesensitive)
2376 {
2377   pstring tok;
2378   char *p=list;
2379
2380   if (!list) return(False);
2381
2382   while (next_token(&p,tok,LIST_SEP))
2383     {
2384       if (casesensitive) {
2385         if (strcmp(tok,s) == 0)
2386           return(True);
2387       } else {
2388         if (StrCaseCmp(tok,s) == 0)
2389           return(True);
2390       }
2391     }
2392   return(False);
2393 }
2394
2395 /* this is used to prevent lots of mallocs of size 1 */
2396 static char *null_string = NULL;
2397
2398 /****************************************************************************
2399 set a string value, allocing the space for the string
2400 ****************************************************************************/
2401 BOOL string_init(char **dest,char *src)
2402 {
2403   int l;
2404   if (!src)     
2405     src = "";
2406
2407   l = strlen(src);
2408
2409   if (l == 0)
2410     {
2411       if (!null_string)
2412         null_string = (char *)malloc(1);
2413
2414       *null_string = 0;
2415       *dest = null_string;
2416     }
2417   else
2418     {
2419       *dest = (char *)malloc(l+1);
2420       strcpy(*dest,src);
2421     }
2422   return(True);
2423 }
2424
2425 /****************************************************************************
2426 free a string value
2427 ****************************************************************************/
2428 void string_free(char **s)
2429 {
2430   if (!s || !(*s)) return;
2431   if (*s == null_string)
2432     *s = NULL;
2433   if (*s) free(*s);
2434   *s = NULL;
2435 }
2436
2437 /****************************************************************************
2438 set a string value, allocing the space for the string, and deallocating any 
2439 existing space
2440 ****************************************************************************/
2441 BOOL string_set(char **dest,char *src)
2442 {
2443   string_free(dest);
2444
2445   return(string_init(dest,src));
2446 }
2447
2448 /****************************************************************************
2449 substitute a string for a pattern in another string. Make sure there is 
2450 enough room!
2451
2452 This routine looks for pattern in s and replaces it with 
2453 insert. It may do multiple replacements.
2454
2455 return True if a substitution was done.
2456 ****************************************************************************/
2457 BOOL string_sub(char *s,char *pattern,char *insert)
2458 {
2459   BOOL ret = False;
2460   char *p;
2461   int ls,lp,li;
2462
2463   if (!insert || !pattern || !s) return(False);
2464
2465   ls = strlen(s);
2466   lp = strlen(pattern);
2467   li = strlen(insert);
2468
2469   if (!*pattern) return(False);
2470
2471   while (lp <= ls && (p = strstr(s,pattern)))
2472     {
2473       ret = True;
2474       memmove(p+li,p+lp,ls + 1 - (PTR_DIFF(p,s) + lp));
2475       memcpy(p,insert,li);
2476       s = p + li;
2477       ls = strlen(s);
2478     }
2479   return(ret);
2480 }
2481
2482
2483
2484 /*********************************************************
2485 * Recursive routine that is called by mask_match.
2486 * Does the actual matching.
2487 *********************************************************/
2488 BOOL do_match(char *str, char *regexp, int case_sig)
2489 {
2490   char *p;
2491
2492   for( p = regexp; *p && *str; ) {
2493     switch(*p) {
2494     case '?':
2495       str++; p++;
2496       break;
2497
2498     case '*':
2499       /* Look for a character matching 
2500          the one after the '*' */
2501       p++;
2502       if(!*p)
2503         return True; /* Automatic match */
2504       while(*str) {
2505         while(*str && (case_sig ? (*p != *str) : (toupper(*p)!=toupper(*str))))
2506           str++;
2507         if(do_match(str,p,case_sig))
2508           return True;
2509         if(!*str)
2510           return False;
2511         else
2512           str++;
2513       }
2514       return False;
2515
2516     default:
2517       if(case_sig) {
2518         if(*str != *p)
2519           return False;
2520       } else {
2521         if(toupper(*str) != toupper(*p))
2522           return False;
2523       }
2524       str++, p++;
2525       break;
2526     }
2527   }
2528   if(!*p && !*str)
2529     return True;
2530
2531   if (!*p && str[0] == '.' && str[1] == 0)
2532     return(True);
2533   
2534   if (!*str && *p == '?')
2535     {
2536       while (*p == '?') p++;
2537       return(!*p);
2538     }
2539
2540   if(!*str && (*p == '*' && p[1] == '\0'))
2541     return True;
2542   return False;
2543 }
2544
2545
2546 /*********************************************************
2547 * Routine to match a given string with a regexp - uses
2548 * simplified regexp that takes * and ? only. Case can be
2549 * significant or not.
2550 *********************************************************/
2551 BOOL mask_match(char *str, char *regexp, int case_sig,BOOL trans2)
2552 {
2553   char *p;
2554   pstring p1, p2;
2555   fstring ebase,eext,sbase,sext;
2556
2557   BOOL matched;
2558
2559   /* Make local copies of str and regexp */
2560   StrnCpy(p1,regexp,sizeof(pstring)-1);
2561   StrnCpy(p2,str,sizeof(pstring)-1);
2562
2563   if (!strchr(p2,'.')) {
2564     strcat(p2,".");
2565   }
2566
2567 /*
2568   if (!strchr(p1,'.')) {
2569     strcat(p1,".");
2570   }
2571 */
2572
2573 #if 0
2574   if (strchr(p1,'.'))
2575     {
2576       string_sub(p1,"*.*","*");
2577       string_sub(p1,".*","*");
2578     }
2579 #endif
2580
2581   /* Remove any *? and ** as they are meaningless */
2582   for(p = p1; *p; p++)
2583     while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2584       (void)strcpy( &p[1], &p[2]);
2585
2586   if (strequal(p1,"*")) return(True);
2587
2588   DEBUG(5,("mask_match str=<%s> regexp=<%s>, case_sig = %d\n", p2, p1, case_sig));
2589
2590   if (trans2) {
2591     strcpy(ebase,p1);
2592     strcpy(sbase,p2);
2593   } else {
2594     if ((p=strrchr(p1,'.'))) {
2595       *p = 0;
2596       strcpy(ebase,p1);
2597       strcpy(eext,p+1);
2598     } else {
2599       strcpy(ebase,p1);
2600       eext[0] = 0;
2601     }
2602
2603   if (!strequal(p2,".") && !strequal(p2,"..") && (p=strrchr(p2,'.'))) {
2604     *p = 0;
2605     strcpy(sbase,p2);
2606     strcpy(sext,p+1);
2607   } else {
2608     strcpy(sbase,p2);
2609     strcpy(sext,"");
2610   }
2611   }
2612
2613   matched = do_match(sbase,ebase,case_sig) && 
2614     (trans2 || do_match(sext,eext,case_sig));
2615
2616   DEBUG(5,("mask_match returning %d\n", matched));
2617
2618   return matched;
2619 }
2620
2621
2622
2623 /****************************************************************************
2624 become a daemon, discarding the controlling terminal
2625 ****************************************************************************/
2626 void become_daemon(void)
2627 {
2628 #ifndef NO_FORK_DEBUG
2629   if (fork())
2630     exit(0);
2631
2632   /* detach from the terminal */
2633 #ifdef USE_SETSID
2634   setsid();
2635 #else /* USE_SETSID */
2636 #ifdef TIOCNOTTY
2637   {
2638     int i = open("/dev/tty", O_RDWR);
2639     if (i >= 0) 
2640       {
2641         ioctl(i, (int) TIOCNOTTY, (char *)0);      
2642         close(i);
2643       }
2644   }
2645 #endif /* TIOCNOTTY */
2646 #endif /* USE_SETSID */
2647   /* Close fd's 0,1,2. Needed if started by rsh */
2648   close_low_fds();
2649 #endif /* NO_FORK_DEBUG */
2650 }
2651
2652
2653 /****************************************************************************
2654 put up a yes/no prompt
2655 ****************************************************************************/
2656 BOOL yesno(char *p)
2657 {
2658   pstring ans;
2659   printf("%s",p);
2660
2661   if (!fgets(ans,sizeof(ans)-1,stdin))
2662     return(False);
2663
2664   if (*ans == 'y' || *ans == 'Y')
2665     return(True);
2666
2667   return(False);
2668 }
2669
2670 /****************************************************************************
2671 read a line from a file with possible \ continuation chars. 
2672 Blanks at the start or end of a line are stripped.
2673 The string will be allocated if s2 is NULL
2674 ****************************************************************************/
2675 char *fgets_slash(char *s2,int maxlen,FILE *f)
2676 {
2677   char *s=s2;
2678   int len = 0;
2679   int c;
2680   BOOL start_of_line = True;
2681
2682   if (feof(f))
2683     return(NULL);
2684
2685   if (!s2)
2686     {
2687       maxlen = MIN(maxlen,8);
2688       s = (char *)Realloc(s,maxlen);
2689     }
2690
2691   if (!s || maxlen < 2) return(NULL);
2692
2693   *s = 0;
2694
2695   while (len < maxlen-1)
2696     {
2697       c = getc(f);
2698       switch (c)
2699         {
2700         case '\r':
2701           break;
2702         case '\n':
2703           while (len > 0 && s[len-1] == ' ')
2704             {
2705               s[--len] = 0;
2706             }
2707           if (len > 0 && s[len-1] == '\\')
2708             {
2709               s[--len] = 0;
2710               start_of_line = True;
2711               break;
2712             }
2713           return(s);
2714         case EOF:
2715           if (len <= 0 && !s2) 
2716             free(s);
2717           return(len>0?s:NULL);
2718         case ' ':
2719           if (start_of_line)
2720             break;
2721         default:
2722           start_of_line = False;
2723           s[len++] = c;
2724           s[len] = 0;
2725         }
2726       if (!s2 && len > maxlen-3)
2727         {
2728           maxlen *= 2;
2729           s = (char *)Realloc(s,maxlen);
2730           if (!s) return(NULL);
2731         }
2732     }
2733   return(s);
2734 }
2735
2736
2737
2738 /****************************************************************************
2739 set the length of a file from a filedescriptor.
2740 Returns 0 on success, -1 on failure.
2741 ****************************************************************************/
2742 int set_filelen(int fd, long len)
2743 {
2744 /* According to W. R. Stevens advanced UNIX prog. Pure 4.3 BSD cannot
2745    extend a file with ftruncate. Provide alternate implementation
2746    for this */
2747
2748 #if FTRUNCATE_CAN_EXTEND
2749   return ftruncate(fd, len);
2750 #else
2751   struct stat st;
2752   char c = 0;
2753   long currpos = lseek(fd, 0L, SEEK_CUR);
2754
2755   if(currpos < 0)
2756     return -1;
2757   /* Do an fstat to see if the file is longer than
2758      the requested size (call ftruncate),
2759      or shorter, in which case seek to len - 1 and write 1
2760      byte of zero */
2761   if(fstat(fd, &st)<0)
2762     return -1;
2763
2764 #ifdef S_ISFIFO
2765   if (S_ISFIFO(st.st_mode)) return 0;
2766 #endif
2767
2768   if(st.st_size == len)
2769     return 0;
2770   if(st.st_size > len)
2771     return ftruncate(fd, len);
2772
2773   if(lseek(fd, len-1, SEEK_SET) != len -1)
2774     return -1;
2775   if(write(fd, &c, 1)!=1)
2776     return -1;
2777   /* Seek to where we were */
2778   lseek(fd, currpos, SEEK_SET);
2779   return 0;
2780 #endif
2781 }
2782
2783
2784 /****************************************************************************
2785 return the byte checksum of some data
2786 ****************************************************************************/
2787 int byte_checksum(char *buf,int len)
2788 {
2789   unsigned char *p = (unsigned char *)buf;
2790   int ret = 0;
2791   while (len--)
2792     ret += *p++;
2793   return(ret);
2794 }
2795
2796
2797
2798 #ifdef HPUX
2799 /****************************************************************************
2800 this is a version of setbuffer() for those machines that only have setvbuf
2801 ****************************************************************************/
2802  void setbuffer(FILE *f,char *buf,int bufsize)
2803 {
2804   setvbuf(f,buf,_IOFBF,bufsize);
2805 }
2806 #endif
2807
2808
2809 /****************************************************************************
2810 parse out a directory name from a path name. Assumes dos style filenames.
2811 ****************************************************************************/
2812 char *dirname_dos(char *path,char *buf)
2813 {
2814   char *p = strrchr(path,'\\');
2815
2816   if (!p)
2817     strcpy(buf,path);
2818   else
2819     {
2820       *p = 0;
2821       strcpy(buf,path);
2822       *p = '\\';
2823     }
2824
2825   return(buf);
2826 }
2827
2828
2829 /****************************************************************************
2830 parse out a filename from a path name. Assumes dos style filenames.
2831 ****************************************************************************/
2832 static char *filename_dos(char *path,char *buf)
2833 {
2834   char *p = strrchr(path,'\\');
2835
2836   if (!p)
2837     strcpy(buf,path);
2838   else
2839     strcpy(buf,p+1);
2840
2841   return(buf);
2842 }
2843
2844
2845
2846 /****************************************************************************
2847 expand a pointer to be a particular size
2848 ****************************************************************************/
2849 void *Realloc(void *p,int size)
2850 {
2851   void *ret=NULL;
2852
2853   if (size == 0) {
2854     if (p) free(p);
2855     DEBUG(5,("Realloc asked for 0 bytes\n"));
2856     return NULL;
2857   }
2858
2859   if (!p)
2860     ret = (void *)malloc(size);
2861   else
2862     ret = (void *)realloc(p,size);
2863
2864   if (!ret)
2865     DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",size));
2866
2867   return(ret);
2868 }
2869
2870 #ifdef NOSTRDUP
2871 /****************************************************************************
2872 duplicate a string
2873 ****************************************************************************/
2874  char *strdup(char *s)
2875 {
2876   char *ret = NULL;
2877   if (!s) return(NULL);
2878   ret = (char *)malloc(strlen(s)+1);
2879   if (!ret) return(NULL);
2880   strcpy(ret,s);
2881   return(ret);
2882 }
2883 #endif
2884
2885
2886 /****************************************************************************
2887   Signal handler for SIGPIPE (write on a disconnected socket) 
2888 ****************************************************************************/
2889 void Abort(void )
2890 {
2891   DEBUG(0,("Probably got SIGPIPE\nExiting\n"));
2892   exit(2);
2893 }
2894
2895 /****************************************************************************
2896 get my own name and IP
2897 ****************************************************************************/
2898 BOOL get_myname(char *my_name,struct in_addr *ip)
2899 {
2900   struct hostent *hp;
2901   pstring hostname;
2902
2903   *hostname = 0;
2904
2905   /* get my host name */
2906   if (gethostname(hostname, MAXHOSTNAMELEN) == -1) 
2907     {
2908       DEBUG(0,("gethostname failed\n"));
2909       return False;
2910     } 
2911
2912   /* get host info */
2913   if ((hp = Get_Hostbyname(hostname)) == 0) 
2914     {
2915       DEBUG(0,( "Get_Hostbyname: Unknown host %s.\n",hostname));
2916       return False;
2917     }
2918
2919   if (my_name)
2920     {
2921       /* split off any parts after an initial . */
2922       char *p = strchr(hostname,'.');
2923       if (p) *p = 0;
2924
2925       strcpy(my_name,hostname);
2926     }
2927
2928   if (ip)
2929     putip((char *)ip,(char *)hp->h_addr);
2930
2931   return(True);
2932 }
2933
2934
2935 /****************************************************************************
2936 true if two IP addresses are equal
2937 ****************************************************************************/
2938 BOOL ip_equal(struct in_addr ip1,struct in_addr ip2)
2939 {
2940   uint32 a1,a2;
2941   a1 = ntohl(ip1.s_addr);
2942   a2 = ntohl(ip2.s_addr);
2943   return(a1 == a2);
2944 }
2945
2946
2947 /****************************************************************************
2948 open a socket of the specified type, port and address for incoming data
2949 ****************************************************************************/
2950 int open_socket_in(int type, int port, int dlevel,uint32 socket_addr)
2951 {
2952   struct hostent *hp;
2953   struct sockaddr_in sock;
2954   pstring host_name;
2955   int res;
2956
2957   /* get my host name */
2958   if (gethostname(host_name, MAXHOSTNAMELEN) == -1) 
2959     { DEBUG(0,("gethostname failed\n")); return -1; } 
2960
2961   /* get host info */
2962   if ((hp = Get_Hostbyname(host_name)) == 0) 
2963     {
2964       DEBUG(0,( "Get_Hostbyname: Unknown host. %s\n",host_name));
2965       return -1;
2966     }
2967   
2968   bzero((char *)&sock,sizeof(sock));
2969   memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
2970 #if defined(__FreeBSD__) || defined(NETBSD) /* XXX not the right ifdef */
2971   sock.sin_len = sizeof(sock);
2972 #endif
2973   sock.sin_port = htons( port );
2974   sock.sin_family = hp->h_addrtype;
2975   sock.sin_addr.s_addr = socket_addr;
2976   res = socket(hp->h_addrtype, type, 0);
2977   if (res == -1) 
2978     { DEBUG(0,("socket failed\n")); return -1; }
2979
2980   {
2981     int one=1;
2982     setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
2983   }
2984
2985   /* now we've got a socket - we need to bind it */
2986   if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) < 0) 
2987     { 
2988       if (port) {
2989         if (port == SMB_PORT || port == NMB_PORT)
2990           DEBUG(dlevel,("bind failed on port %d socket_addr=%x (%s)\n",
2991                         port,socket_addr,strerror(errno))); 
2992         close(res); 
2993
2994         if (dlevel > 0 && port < 1000)
2995           port = 7999;
2996
2997         if (port >= 1000 && port < 9000)
2998           return(open_socket_in(type,port+1,dlevel,socket_addr));
2999       }
3000
3001       return(-1); 
3002     }
3003   DEBUG(3,("bind succeeded on port %d\n",port));
3004
3005   return res;
3006 }
3007
3008
3009 /****************************************************************************
3010   create an outgoing socket
3011   **************************************************************************/
3012 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
3013 {
3014   struct sockaddr_in sock_out;
3015   int res,ret;
3016   int connect_loop = 250; /* 250 milliseconds */
3017   int loops = (timeout * 1000) / connect_loop;
3018
3019   /* create a socket to write to */
3020   res = socket(PF_INET, type, 0);
3021   if (res == -1) 
3022     { DEBUG(0,("socket error\n")); return -1; }
3023
3024   if (type != SOCK_STREAM) return(res);
3025   
3026   bzero((char *)&sock_out,sizeof(sock_out));
3027   putip((char *)&sock_out.sin_addr,(char *)addr);
3028   
3029   sock_out.sin_port = htons( port );
3030   sock_out.sin_family = PF_INET;
3031
3032   /* set it non-blocking */
3033   set_blocking(res,False);
3034
3035   DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
3036   
3037   /* and connect it to the destination */
3038 connect_again:
3039   ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
3040
3041   /* Some systems return EAGAIN when they mean EINPROGRESS */
3042   if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
3043         errno == EAGAIN) && loops--) {
3044     msleep(connect_loop);
3045     goto connect_again;
3046   }
3047
3048   if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
3049          errno == EAGAIN)) {
3050       DEBUG(1,("timeout connecting to %s:%d\n",inet_ntoa(*addr),port));
3051       close(res);
3052       return -1;
3053   }
3054
3055 #ifdef EISCONN
3056   if (ret < 0 && errno == EISCONN) {
3057     errno = 0;
3058     ret = 0;
3059   }
3060 #endif
3061
3062   if (ret < 0) {
3063     DEBUG(1,("error connecting to %s:%d (%s)\n",
3064              inet_ntoa(*addr),port,strerror(errno)));
3065     return -1;
3066   }
3067
3068   /* set it blocking again */
3069   set_blocking(res,True);
3070
3071   return res;
3072 }
3073
3074
3075 /****************************************************************************
3076 interpret a protocol description string, with a default
3077 ****************************************************************************/
3078 int interpret_protocol(char *str,int def)
3079 {
3080   if (strequal(str,"NT1"))
3081     return(PROTOCOL_NT1);
3082   if (strequal(str,"LANMAN2"))
3083     return(PROTOCOL_LANMAN2);
3084   if (strequal(str,"LANMAN1"))
3085     return(PROTOCOL_LANMAN1);
3086   if (strequal(str,"CORE"))
3087     return(PROTOCOL_CORE);
3088   if (strequal(str,"COREPLUS"))
3089     return(PROTOCOL_COREPLUS);
3090   if (strequal(str,"CORE+"))
3091     return(PROTOCOL_COREPLUS);
3092   
3093   DEBUG(0,("Unrecognised protocol level %s\n",str));
3094   
3095   return(def);
3096 }
3097
3098 /****************************************************************************
3099 interpret a security level
3100 ****************************************************************************/
3101 int interpret_security(char *str,int def)
3102 {
3103   if (strequal(str,"SERVER"))
3104     return(SEC_SERVER);
3105   if (strequal(str,"USER"))
3106     return(SEC_USER);
3107   if (strequal(str,"SHARE"))
3108     return(SEC_SHARE);
3109   
3110   DEBUG(0,("Unrecognised security level %s\n",str));
3111   
3112   return(def);
3113 }
3114
3115
3116 /****************************************************************************
3117 interpret an internet address or name into an IP address in 4 byte form
3118 ****************************************************************************/
3119 uint32 interpret_addr(char *str)
3120 {
3121   struct hostent *hp;
3122   uint32 res;
3123   int i;
3124   BOOL pure_address = True;
3125
3126   if (strcmp(str,"0.0.0.0") == 0) return(0);
3127   if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
3128
3129   for (i=0; pure_address && str[i]; i++)
3130     if (!(isdigit(str[i]) || str[i] == '.')) 
3131       pure_address = False;
3132
3133   /* if it's in the form of an IP address then get the lib to interpret it */
3134   if (pure_address) {
3135     res = inet_addr(str);
3136   } else {
3137     /* otherwise assume it's a network name of some sort and use 
3138        Get_Hostbyname */
3139     if ((hp = Get_Hostbyname(str)) == 0) {
3140       DEBUG(3,("Get_Hostbyname: Unknown host. %s\n",str));
3141       return 0;
3142     }
3143     putip((char *)&res,(char *)hp->h_addr);
3144   }
3145
3146   if (res == (uint32)-1) return(0);
3147
3148   return(res);
3149 }
3150
3151 /*******************************************************************
3152   a convenient addition to interpret_addr()
3153   ******************************************************************/
3154 struct in_addr *interpret_addr2(char *str)
3155 {
3156   static struct in_addr ret;
3157   uint32 a = interpret_addr(str);
3158   ret.s_addr = a;
3159   return(&ret);
3160 }
3161
3162 /*******************************************************************
3163   check if an IP is the 0.0.0.0
3164   ******************************************************************/
3165 BOOL zero_ip(struct in_addr ip)
3166 {
3167   uint32 a;
3168   putip((char *)&a,(char *)&ip);
3169   return(a == 0);
3170 }
3171
3172
3173 /*******************************************************************
3174  matchname - determine if host name matches IP address 
3175  ******************************************************************/
3176 static BOOL matchname(char *remotehost,struct in_addr  addr)
3177 {
3178   struct hostent *hp;
3179   int     i;
3180   
3181   if ((hp = Get_Hostbyname(remotehost)) == 0) {
3182     DEBUG(0,("Get_Hostbyname(%s): lookup failure", remotehost));
3183     return False;
3184   } 
3185
3186   /*
3187    * Make sure that gethostbyname() returns the "correct" host name.
3188    * Unfortunately, gethostbyname("localhost") sometimes yields
3189    * "localhost.domain". Since the latter host name comes from the
3190    * local DNS, we just have to trust it (all bets are off if the local
3191    * DNS is perverted). We always check the address list, though.
3192    */
3193   
3194   if (strcasecmp(remotehost, hp->h_name)
3195       && strcasecmp(remotehost, "localhost")) {
3196     DEBUG(0,("host name/name mismatch: %s != %s",
3197              remotehost, hp->h_name));
3198     return False;
3199   }
3200         
3201   /* Look up the host address in the address list we just got. */
3202   for (i = 0; hp->h_addr_list[i]; i++) {
3203     if (memcmp(hp->h_addr_list[i], (caddr_t) & addr, sizeof(addr)) == 0)
3204       return True;
3205   }
3206
3207   /*
3208    * The host name does not map to the original host address. Perhaps
3209    * someone has compromised a name server. More likely someone botched
3210    * it, but that could be dangerous, too.
3211    */
3212   
3213   DEBUG(0,("host name/address mismatch: %s != %s",
3214            inet_ntoa(addr), hp->h_name));
3215   return False;
3216 }
3217
3218 /*******************************************************************
3219  Reset the 'done' variables so after a client process is created
3220  from a fork call these calls will be re-done. This should be
3221  expanded if more variables need reseting.
3222  ******************************************************************/
3223
3224 static BOOL global_client_name_done = False;
3225 static BOOL global_client_addr_done = False;
3226
3227 void reset_globals_after_fork()
3228 {
3229   global_client_name_done = False;
3230   global_client_addr_done = False;
3231 }
3232  
3233 /*******************************************************************
3234  return the DNS name of the client 
3235  ******************************************************************/
3236 char *client_name(void)
3237 {
3238   extern int Client;
3239   struct sockaddr sa;
3240   struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
3241   int     length = sizeof(sa);
3242   static pstring name_buf;
3243   struct hostent *hp;
3244
3245   if (global_client_name_done) 
3246     return name_buf;
3247
3248   strcpy(name_buf,"UNKNOWN");
3249
3250   if (getpeername(Client, &sa, &length) < 0) {
3251     DEBUG(0,("getpeername failed\n"));
3252     return name_buf;
3253   }
3254
3255   /* Look up the remote host name. */
3256   if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
3257                           sizeof(sockin->sin_addr),
3258                           AF_INET)) == 0) {
3259     DEBUG(1,("Gethostbyaddr failed for %s\n",client_addr()));
3260     StrnCpy(name_buf,client_addr(),sizeof(name_buf) - 1);
3261   } else {
3262     StrnCpy(name_buf,(char *)hp->h_name,sizeof(name_buf) - 1);
3263     if (!matchname(name_buf, sockin->sin_addr)) {
3264       DEBUG(0,("Matchname failed on %s %s\n",name_buf,client_addr()));
3265       strcpy(name_buf,"UNKNOWN");
3266     }
3267   }
3268   global_client_name_done = True;
3269   return name_buf;
3270 }
3271
3272 /*******************************************************************
3273  return the IP addr of the client as a string 
3274  ******************************************************************/
3275 char *client_addr(void)
3276 {
3277   extern int Client;
3278   struct sockaddr sa;
3279   struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
3280   int     length = sizeof(sa);
3281   static fstring addr_buf;
3282
3283   if (global_client_addr_done) 
3284     return addr_buf;
3285
3286   strcpy(addr_buf,"0.0.0.0");
3287
3288   if (getpeername(Client, &sa, &length) < 0) {
3289     DEBUG(0,("getpeername failed\n"));
3290     return addr_buf;
3291   }
3292
3293   strcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
3294
3295   global_client_addr_done = True;
3296   return addr_buf;
3297 }
3298
3299 /*******************************************************************
3300 sub strings with useful parameters
3301 Rewritten by Stefaan A Eeckels <Stefaan.Eeckels@ecc.lu> and
3302 Paul Rippin <pr3245@nopc.eurostat.cec.be>
3303 ********************************************************************/
3304 void standard_sub_basic(char *str)
3305   {
3306   char *s, *p;
3307     char pidstr[10];
3308   struct passwd *pass;
3309
3310   for (s = str ; (p = strchr(s,'%')) != NULL ; s = p )
3311   {
3312     switch (*(p+1))
3313   {
3314       case 'G' : if ((pass = Get_Pwnam(sesssetup_user,False))!=NULL)
3315                    string_sub(p,"%G",gidtoname(pass->pw_gid));
3316                  else
3317                    p += 2;
3318                  break;
3319       case 'I' : string_sub(p,"%I",client_addr()); break;
3320       case 'L' : string_sub(p,"%L",local_machine); break;
3321       case 'M' : string_sub(p,"%M",client_name()); break;
3322       case 'R' : string_sub(p,"%R",remote_proto); break;
3323       case 'T' : string_sub(p,"%T",timestring()); break;
3324       case 'U' : string_sub(p,"%U",sesssetup_user); break;
3325       case 'a' : string_sub(p,"%a",remote_arch); break;
3326       case 'd' : sprintf(pidstr,"%d",(int)getpid());
3327                  string_sub(p,"%d",pidstr);
3328                  break;
3329       case 'h' : string_sub(p,"%h",myhostname); break;
3330       case 'm' : string_sub(p,"%m",remote_machine); break;
3331       case 'v' : string_sub(p,"%v",VERSION); break;
3332       case '\0' : p++; break; /* don't run off end if last character is % */
3333       default  : p+=2; break;
3334     }
3335   }
3336   return;
3337 }
3338
3339 /*******************************************************************
3340 are two IPs on the same subnet?
3341 ********************************************************************/
3342 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
3343 {
3344   uint32 net1,net2,nmask;
3345
3346   nmask = ntohl(mask.s_addr);
3347   net1  = ntohl(ip1.s_addr);
3348   net2  = ntohl(ip2.s_addr);
3349             
3350   return((net1 & nmask) == (net2 & nmask));
3351 }
3352
3353
3354 /*******************************************************************
3355 write a string in unicoode format
3356 ********************************************************************/
3357 int PutUniCode(char *dst,char *src)
3358 {
3359   int ret = 0;
3360   while (*src) {
3361     dst[ret++] = src[0];
3362     dst[ret++] = 0;    
3363     src++;
3364   }
3365   dst[ret++]=0;
3366   dst[ret++]=0;
3367   return(ret);
3368 }
3369
3370 /****************************************************************************
3371 a wrapper for gethostbyname() that tries with all lower and all upper case 
3372 if the initial name fails
3373 ****************************************************************************/
3374 struct hostent *Get_Hostbyname(char *name)
3375 {
3376   char *name2 = strdup(name);
3377   struct hostent *ret;
3378
3379   if (!name2)
3380     {
3381       DEBUG(0,("Memory allocation error in Get_Hostbyname! panic\n"));
3382       exit(0);
3383     }
3384
3385   if (!isalnum(*name2))
3386     {
3387       free(name2);
3388       return(NULL);
3389     }
3390
3391   ret = sys_gethostbyname(name2);
3392   if (ret != NULL)
3393     {
3394       free(name2);
3395       return(ret);
3396     }
3397
3398   /* try with all lowercase */
3399   strlower(name2);
3400   ret = sys_gethostbyname(name2);
3401   if (ret != NULL)
3402     {
3403       free(name2);
3404       return(ret);
3405     }
3406
3407   /* try with all uppercase */
3408   strupper(name2);
3409   ret = sys_gethostbyname(name2);
3410   if (ret != NULL)
3411     {
3412       free(name2);
3413       return(ret);
3414     }
3415   
3416   /* nothing works :-( */
3417   free(name2);
3418   return(NULL);
3419 }
3420
3421
3422 /****************************************************************************
3423 check if a process exists. Does this work on all unixes?
3424 ****************************************************************************/
3425 BOOL process_exists(int pid)
3426 {
3427 #ifdef LINUX
3428   fstring s;
3429   sprintf(s,"/proc/%d",pid);
3430   return(directory_exist(s,NULL));
3431 #else
3432   {
3433     static BOOL tested=False;
3434     static BOOL ok=False;
3435     fstring s;
3436     if (!tested) {
3437       tested = True;
3438       sprintf(s,"/proc/%05d",(int)getpid());
3439       ok = file_exist(s,NULL);
3440     }
3441     if (ok) {
3442       sprintf(s,"/proc/%05d",pid);
3443       return(file_exist(s,NULL));
3444     }
3445   }
3446
3447   /* CGH 8/16/96 - added ESRCH test */
3448   return(pid == getpid() || kill(pid,0) == 0 || errno != ESRCH);
3449 #endif
3450 }
3451
3452
3453 /*******************************************************************
3454 turn a uid into a user name
3455 ********************************************************************/
3456 char *uidtoname(int uid)
3457 {
3458   static char name[40];
3459   struct passwd *pass = getpwuid(uid);
3460   if (pass) return(pass->pw_name);
3461   sprintf(name,"%d",uid);
3462   return(name);
3463 }
3464
3465 /*******************************************************************
3466 turn a gid into a group name
3467 ********************************************************************/
3468 char *gidtoname(int gid)
3469 {
3470   static char name[40];
3471   struct group *grp = getgrgid(gid);
3472   if (grp) return(grp->gr_name);
3473   sprintf(name,"%d",gid);
3474   return(name);
3475 }
3476
3477 /*******************************************************************
3478 block sigs
3479 ********************************************************************/
3480 void BlockSignals(BOOL block,int signum)
3481 {
3482 #ifdef USE_SIGBLOCK
3483   int block_mask = sigmask(signum);
3484   static int oldmask = 0;
3485   if (block) 
3486     oldmask = sigblock(block_mask);
3487   else
3488     sigsetmask(oldmask);
3489 #elif defined(USE_SIGPROCMASK)
3490   sigset_t set;
3491   sigemptyset(&set);
3492   sigaddset(&set,signum);
3493   sigprocmask(block?SIG_BLOCK:SIG_UNBLOCK,&set,NULL);
3494 #endif
3495 }
3496
3497 #if AJT
3498 /*******************************************************************
3499 my own panic function - not suitable for general use
3500 ********************************************************************/
3501 void ajt_panic(void)
3502 {
3503   system("/usr/bin/X11/xedit -display ljus:0 /tmp/ERROR_FAULT");
3504 }
3505 #endif
3506
3507 #ifdef USE_DIRECT
3508 #define DIRECT direct
3509 #else
3510 #define DIRECT dirent
3511 #endif
3512
3513 /*******************************************************************
3514 a readdir wrapper which just returns the file name
3515 also return the inode number if requested
3516 ********************************************************************/
3517 char *readdirname(void *p)
3518 {
3519   struct DIRECT *ptr;
3520   char *dname;
3521
3522   if (!p) return(NULL);
3523   
3524   ptr = (struct DIRECT *)readdir(p);
3525   if (!ptr) return(NULL);
3526
3527   dname = ptr->d_name;
3528
3529 #ifdef NEXT2
3530   if (telldir(p) < 0) return(NULL);
3531 #endif
3532
3533 #ifdef SUNOS5
3534   /* this handles a broken compiler setup, causing a mixture
3535    of BSD and SYSV headers and libraries */
3536   {
3537     static BOOL broken_readdir = False;
3538     if (!broken_readdir && !(*(dname)) && strequal("..",dname-2))
3539       {
3540         DEBUG(0,("Your readdir() is broken. You have somehow mixed SYSV and BSD headers and libraries\n"));
3541         broken_readdir = True;
3542       }
3543     if (broken_readdir)
3544       dname = dname - 2;
3545   }
3546 #endif
3547
3548   {
3549     static pstring buf;
3550     strcpy(buf, dname);
3551     unix_to_dos(buf, True);
3552     dname = buf;
3553   }
3554
3555   return(dname);
3556 }
3557
3558 /*
3559  * Utility function used to decide if the last component 
3560  * of a path matches a (possibly wildcarded) entry in a namelist.
3561  */
3562
3563 BOOL is_in_path(char *name, name_compare_entry *namelist)
3564 {
3565   pstring last_component;
3566   char *p;
3567
3568   DEBUG(5, ("is_in_path: %s\n", name));
3569
3570   /* if we have no list it's obviously not in the path */
3571   if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) 
3572         {
3573     DEBUG(5,("is_in_path: no name list.\n"));
3574     return False;
3575 }
3576
3577   /* Get the last component of the unix name. */
3578   p = strrchr(name, '/');
3579   strncpy(last_component, p ? p : name, sizeof(last_component)-1);
3580   last_component[sizeof(last_component)-1] = '\0'; 
3581
3582   for(; namelist->name != NULL; namelist++)
3583   {
3584     if(namelist->is_wild)
3585     {
3586       /* look for a wildcard match. */
3587       if (mask_match(last_component, namelist->name, case_sensitive, False))
3588       {
3589          DEBUG(5,("is_in_path: mask match succeeded\n"));
3590          return True;
3591       }
3592     }
3593     else
3594     {
3595       if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
3596        (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
3597         {
3598          DEBUG(5,("is_in_path: match succeeded\n"));
3599          return True;
3600         }
3601     }
3602   }
3603   DEBUG(5,("is_in_path: match not found\n"));
3604  
3605   return False;
3606 }
3607
3608 /*
3609  * Strip a '/' separated list into an array of 
3610  * name_compare_enties structures suitable for 
3611  * passing to is_in_path(). We do this for
3612  * speed so we can pre-parse all the names in the list 
3613  * and don't do it for each call to is_in_path().
3614  * namelist is modified here and is assumed to be 
3615  * a copy owned by the caller.
3616  * We also check if the entry contains a wildcard to
3617  * remove a potentially expensive call to mask_match
3618  * if possible.
3619    */
3620
3621 void set_namearray(name_compare_entry **ppname_array, char *namelist)
3622 {
3623   char *name_end;
3624   char *nameptr = namelist;
3625   int num_entries = 0;
3626   int i;
3627
3628   (*ppname_array) = NULL;
3629
3630   if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0'))) 
3631     return;
3632
3633   /* We need to make two passes over the string. The
3634      first to count the number of elements, the second
3635      to split it.
3636    */
3637   while(*nameptr) 
3638     {
3639       if ( *nameptr == '/' ) 
3640         {
3641           /* cope with multiple (useless) /s) */
3642           nameptr++;
3643           continue;
3644         }
3645       /* find the next / */
3646       name_end = strchr(nameptr, '/');
3647
3648       /* oops - the last check for a / didn't find one. */
3649       if (name_end == NULL)
3650         break;
3651
3652       /* next segment please */
3653       nameptr = name_end + 1;
3654       num_entries++;
3655     }
3656
3657   if(num_entries == 0)
3658     return;
3659
3660   if(( (*ppname_array) = (name_compare_entry *)malloc( 
3661            (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
3662         {
3663     DEBUG(0,("set_namearray: malloc fail\n"));
3664     return;
3665         }
3666
3667   /* Now copy out the names */
3668   nameptr = namelist;
3669   i = 0;
3670   while(*nameptr)
3671              {
3672       if ( *nameptr == '/' ) 
3673       {
3674           /* cope with multiple (useless) /s) */
3675           nameptr++;
3676           continue;
3677       }
3678       /* find the next / */
3679       if ((name_end = strchr(nameptr, '/')) != NULL) 
3680       {
3681           *name_end = 0;
3682          }
3683
3684       /* oops - the last check for a / didn't find one. */
3685       if(name_end == NULL) 
3686         break;
3687
3688       (*ppname_array)[i].is_wild = ((strchr( nameptr, '?')!=NULL) ||
3689                                 (strchr( nameptr, '*')!=NULL));
3690       if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
3691       {
3692         DEBUG(0,("set_namearray: malloc fail (1)\n"));
3693         return;
3694       }
3695
3696       /* next segment please */
3697       nameptr = name_end + 1;
3698       i++;
3699     }
3700   
3701   (*ppname_array)[i].name = NULL;
3702
3703   return;
3704 }
3705
3706 /****************************************************************************
3707 routine to free a namearray.
3708 ****************************************************************************/
3709
3710 void free_namearray(name_compare_entry *name_array)
3711 {
3712   if(name_array == 0)
3713     return;
3714
3715   if(name_array->name != NULL)
3716     free(name_array->name);
3717
3718   free((char *)name_array);
3719 }
3720
3721 /****************************************************************************
3722 routine to do file locking
3723 ****************************************************************************/
3724 BOOL fcntl_lock(int fd,int op,uint32 offset,uint32 count,int type)
3725 {
3726 #if HAVE_FCNTL_LOCK
3727   struct flock lock;
3728   int ret;
3729
3730 #if 1
3731   uint32 mask = 0xC0000000;
3732
3733   /* make sure the count is reasonable, we might kill the lockd otherwise */
3734   count &= ~mask;
3735
3736   /* the offset is often strange - remove 2 of its bits if either of
3737      the top two bits are set. Shift the top ones by two bits. This
3738      still allows OLE2 apps to operate, but should stop lockd from
3739      dieing */
3740   if ((offset & mask) != 0)
3741     offset = (offset & ~mask) | ((offset & mask) >> 2);
3742 #else
3743   uint32 mask = ((unsigned)1<<31);
3744
3745   /* interpret negative counts as large numbers */
3746   if (count < 0)
3747     count &= ~mask;
3748
3749   /* no negative offsets */
3750   offset &= ~mask;
3751
3752   /* count + offset must be in range */
3753   while ((offset < 0 || (offset + count < 0)) && mask)
3754     {
3755       offset &= ~mask;
3756       mask = mask >> 1;
3757     }
3758 #endif
3759
3760
3761   DEBUG(5,("fcntl_lock %d %d %d %d %d\n",fd,op,(int)offset,(int)count,type));
3762
3763   lock.l_type = type;
3764   lock.l_whence = SEEK_SET;
3765   lock.l_start = (int)offset;
3766   lock.l_len = (int)count;
3767   lock.l_pid = 0;
3768
3769   errno = 0;
3770
3771   ret = fcntl(fd,op,&lock);
3772
3773   if (errno != 0)
3774     DEBUG(3,("fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
3775
3776   /* a lock query */
3777   if (op == F_GETLK)
3778     {
3779       if ((ret != -1) &&
3780           (lock.l_type != F_UNLCK) && 
3781           (lock.l_pid != 0) && 
3782           (lock.l_pid != getpid()))
3783         {
3784           DEBUG(3,("fd %d is locked by pid %d\n",fd,lock.l_pid));
3785           return(True);
3786         }
3787
3788       /* it must be not locked or locked by me */
3789       return(False);
3790     }
3791
3792   /* a lock set or unset */
3793   if (ret == -1)
3794     {
3795       DEBUG(3,("lock failed at offset %d count %d op %d type %d (%s)\n",
3796                offset,count,op,type,strerror(errno)));
3797
3798       /* perhaps it doesn't support this sort of locking?? */
3799       if (errno == EINVAL)
3800         {
3801           DEBUG(3,("locking not supported? returning True\n"));
3802           return(True);
3803         }
3804
3805       return(False);
3806     }
3807
3808   /* everything went OK */
3809   DEBUG(5,("Lock call successful\n"));
3810
3811   return(True);
3812 #else
3813   return(False);
3814 #endif
3815 }
3816
3817 /*******************************************************************
3818 lock a file - returning a open file descriptor or -1 on failure
3819 The timeout is in seconds. 0 means no timeout
3820 ********************************************************************/
3821 int file_lock(char *name,int timeout)
3822 {  
3823   int fd = open(name,O_RDWR|O_CREAT,0666);
3824   time_t t=0;
3825   if (fd < 0) return(-1);
3826
3827 #if HAVE_FCNTL_LOCK
3828   if (timeout) t = time(NULL);
3829   while (!timeout || (time(NULL)-t < timeout)) {
3830     if (fcntl_lock(fd,F_SETLK,0,1,F_WRLCK)) return(fd);    
3831     msleep(LOCK_RETRY_TIMEOUT);
3832   }
3833   return(-1);
3834 #else
3835   return(fd);
3836 #endif
3837 }
3838
3839 /*******************************************************************
3840 unlock a file locked by file_lock
3841 ********************************************************************/
3842 void file_unlock(int fd)
3843 {
3844   if (fd<0) return;
3845 #if HAVE_FCNTL_LOCK
3846   fcntl_lock(fd,F_SETLK,0,1,F_UNLCK);
3847 #endif
3848   close(fd);
3849 }
3850
3851 /*******************************************************************
3852 is the name specified one of my netbios names
3853 returns true is it is equal, false otherwise
3854 ********************************************************************/
3855 BOOL is_myname(const char *s)
3856 {
3857   int n;
3858   BOOL ret = False;
3859
3860   for (n=0; my_netbios_names[n]; n++) {
3861     if (strequal(my_netbios_names[n], s))
3862       ret=True;
3863   }
3864   DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
3865   return(ret);
3866 }