home *** CD-ROM | disk | FTP | other *** search
/ Dream 52 / Amiga_Dream_52.iso / Linux / Divers / samba-1.9.18p7.tar.gz / samba-1.9.18p7.tar / samba-1.9.18p7 / source / util.c < prev    next >
C/C++ Source or Header  |  1998-05-12  |  123KB  |  4,936 lines

  1. /* 
  2.    Unix SMB/Netbios implementation.
  3.    Version 1.9.
  4.    Samba utility functions
  5.    Copyright (C) Andrew Tridgell 1992-1998
  6.    
  7.    This program is free software; you can redistribute it and/or modify
  8.    it under the terms of the GNU General Public License as published by
  9.    the Free Software Foundation; either version 2 of the License, or
  10.    (at your option) any later version.
  11.    
  12.    This program is distributed in the hope that it will be useful,
  13.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.    GNU General Public License for more details.
  16.    
  17.    You should have received a copy of the GNU General Public License
  18.    along with this program; if not, write to the Free Software
  19.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21.  
  22. #include "includes.h"
  23.  
  24. #if (defined(NETGROUP) && defined (AUTOMOUNT))
  25. #ifdef NISPLUS
  26. #include <rpcsvc/nis.h>
  27. #else
  28. #include "rpcsvc/ypclnt.h"
  29. #endif
  30. #endif
  31.  
  32. pstring scope = "";
  33.  
  34. int DEBUGLEVEL = 1;
  35.  
  36. BOOL passive = False;
  37.  
  38. int Protocol = PROTOCOL_COREPLUS;
  39.  
  40. /* a default finfo structure to ensure all fields are sensible */
  41. file_info def_finfo = {-1,0,0,0,0,0,0,""};
  42.  
  43. /* these are some file handles where debug info will be stored */
  44. FILE *dbf = NULL;
  45.  
  46. /* the client file descriptor */
  47. int Client = -1;
  48.  
  49. /* the last IP received from */
  50. struct in_addr lastip;
  51.  
  52. /* the last port received from */
  53. int lastport=0;
  54.  
  55. /* this is used by the chaining code */
  56. int chain_size = 0;
  57.  
  58. int trans_num = 0;
  59.  
  60. /*
  61.    case handling on filenames 
  62. */
  63. int case_default = CASE_LOWER;
  64.  
  65. pstring debugf = "";
  66. int syslog_level;
  67.  
  68. /* the following control case operations - they are put here so the
  69.    client can link easily */
  70. BOOL case_sensitive;
  71. BOOL case_preserve;
  72. BOOL use_mangled_map = False;
  73. BOOL short_case_preserve;
  74. BOOL case_mangle;
  75.  
  76. fstring remote_machine="";
  77. fstring local_machine="";
  78. fstring remote_arch="UNKNOWN";
  79. static enum remote_arch_types ra_type = RA_UNKNOWN;
  80. fstring remote_proto="UNKNOWN";
  81. pstring myhostname="";
  82. pstring user_socket_options="";   
  83.  
  84. pstring sesssetup_user="";
  85. pstring samlogon_user="";
  86.  
  87. BOOL sam_logon_in_ssb = False;
  88.  
  89. pstring myname = "";
  90. fstring myworkgroup = "";
  91. char **my_netbios_names;
  92.  
  93. int smb_read_error = 0;
  94.  
  95. static BOOL stdout_logging = False;
  96.  
  97. static char *filename_dos(char *path,char *buf);
  98.  
  99. #if defined(SIGUSR2)
  100. /**************************************************************************** **
  101.  catch a sigusr2 - decrease the debug log level.
  102.  **************************************************************************** */
  103. int sig_usr2(void)
  104. {  
  105.   BlockSignals( True, SIGUSR2);
  106.  
  107.   DEBUGLEVEL--; 
  108.    
  109.   if(DEBUGLEVEL < 0) 
  110.     DEBUGLEVEL = 0; 
  111.  
  112.   DEBUG( 0, ( "Got SIGUSR2 set debug level to %d.\n", DEBUGLEVEL ) );
  113.    
  114.   BlockSignals( False, SIGUSR2);
  115. #ifndef DONT_REINSTALL_SIG
  116.   signal(SIGUSR2, SIGNAL_CAST sig_usr2);
  117. #endif 
  118.   return(0);
  119. }  
  120. #endif /* SIGUSR1 */
  121.    
  122. #if defined(SIGUSR1)
  123. /**************************************************************************** **
  124.  catch a sigusr1 - increase the debug log level. 
  125.  **************************************************************************** */
  126. int sig_usr1(void)
  127. {
  128.   BlockSignals( True, SIGUSR1);
  129.  
  130.   DEBUGLEVEL++;
  131.  
  132.   if(DEBUGLEVEL > 10)
  133.     DEBUGLEVEL = 10;
  134.  
  135.   DEBUG( 0, ( "Got SIGUSR1 set debug level to %d.\n", DEBUGLEVEL ) );
  136.  
  137.   BlockSignals( False, SIGUSR1);
  138. #ifndef DONT_REINSTALL_SIG
  139.   signal(SIGUSR1, SIGNAL_CAST sig_usr1);
  140. #endif
  141.   return(0);
  142. }
  143. #endif /* SIGUSR1 */
  144.  
  145.  
  146. /*******************************************************************
  147.   get ready for syslog stuff
  148.   ******************************************************************/
  149. void setup_logging(char *pname,BOOL interactive)
  150. {
  151. #ifdef SYSLOG
  152.   if (!interactive) {
  153.     char *p = strrchr(pname,'/');
  154.     if (p) pname = p+1;
  155. #ifdef LOG_DAEMON
  156.     openlog(pname, LOG_PID, SYSLOG_FACILITY);
  157. #else /* for old systems that have no facility codes. */
  158.     openlog(pname, LOG_PID);
  159. #endif
  160.   }
  161. #endif
  162.   if (interactive) {
  163.     stdout_logging = True;
  164.     dbf = stdout;
  165.   }
  166. }
  167.  
  168.  
  169. BOOL append_log=False;
  170.  
  171.  
  172. /****************************************************************************
  173. reopen the log files
  174. ****************************************************************************/
  175. void reopen_logs(void)
  176. {
  177.   pstring fname;
  178.   
  179.   if (DEBUGLEVEL > 0)
  180.     {
  181.       pstrcpy(fname,debugf);
  182.       if (lp_loaded() && (*lp_logfile()))
  183.     pstrcpy(fname,lp_logfile());
  184.  
  185.       if (!strcsequal(fname,debugf) || !dbf || !file_exist(debugf,NULL))
  186.     {
  187.       int oldumask = umask(022);
  188.       pstrcpy(debugf,fname);
  189.       if (dbf) fclose(dbf);
  190.       if (append_log)
  191.         dbf = fopen(debugf,"a");
  192.       else
  193.         dbf = fopen(debugf,"w");
  194.       if (dbf) setbuf(dbf,NULL);
  195.       umask(oldumask);
  196.     }
  197.     }
  198.   else
  199.     {
  200.       if (dbf)
  201.     {
  202.       fclose(dbf);
  203.       dbf = NULL;
  204.     }
  205.     }
  206. }
  207.  
  208.  
  209. /*******************************************************************
  210. check if the log has grown too big
  211. ********************************************************************/
  212. static void check_log_size(void)
  213. {
  214.   static int debug_count=0;
  215.   int maxlog;
  216.   struct stat st;
  217.  
  218.   if (debug_count++ < 100 || getuid() != 0) return;
  219.  
  220.   maxlog = lp_max_log_size() * 1024;
  221.   if (!dbf || maxlog <= 0) return;
  222.  
  223.   if (fstat(fileno(dbf),&st) == 0 && st.st_size > maxlog) {
  224.     fclose(dbf); dbf = NULL;
  225.     reopen_logs();
  226.     if (dbf && file_size(debugf) > maxlog) {
  227.       pstring name;
  228.       fclose(dbf); dbf = NULL;
  229.       slprintf(name,sizeof(name)-1,"%s.old",debugf);
  230.       sys_rename(debugf,name);
  231.       reopen_logs();
  232.     }
  233.   }
  234.   debug_count=0;
  235. }
  236.  
  237.  
  238. /*******************************************************************
  239. write an debug message on the debugfile. This is called by the DEBUG
  240. macro
  241. ********************************************************************/
  242. #ifdef __STDC__
  243.  int Debug1(char *format_str, ...)
  244. {
  245. #else
  246.  int Debug1(va_alist)
  247. va_dcl
  248. {  
  249.   char *format_str;
  250. #endif
  251.   va_list ap;  
  252.   int old_errno = errno;
  253.  
  254.   if (stdout_logging) {
  255. #ifdef __STDC__
  256.     va_start(ap, format_str);
  257. #else
  258.     va_start(ap);
  259.     format_str = va_arg(ap,char *);
  260. #endif
  261.     vfprintf(dbf,format_str,ap);
  262.     va_end(ap);
  263.     errno = old_errno;
  264.     return(0);
  265.   }
  266.   
  267. #ifdef SYSLOG
  268.   if (!lp_syslog_only())
  269. #endif  
  270.     {
  271.       if (!dbf) {
  272.           int oldumask = umask(022);
  273.               if(append_log)
  274.                 dbf = fopen(debugf,"a");
  275.               else
  276.                 dbf = fopen(debugf,"w");
  277.           umask(oldumask);
  278.           if (dbf) {
  279.               setbuf(dbf,NULL);
  280.           } else {
  281.               errno = old_errno;
  282.               return(0);
  283.           }
  284.       }
  285.     }
  286.  
  287. #ifdef SYSLOG
  288.   if (syslog_level < lp_syslog())
  289.     {
  290.       /* 
  291.        * map debug levels to syslog() priorities
  292.        * note that not all DEBUG(0, ...) calls are
  293.        * necessarily errors
  294.        */
  295.       static int priority_map[] = { 
  296.     LOG_ERR,     /* 0 */
  297.     LOG_WARNING, /* 1 */
  298.     LOG_NOTICE,  /* 2 */
  299.     LOG_INFO,    /* 3 */
  300.       };
  301.       int priority;
  302.       pstring msgbuf;
  303.       
  304.       if (syslog_level >= sizeof(priority_map) / sizeof(priority_map[0]) ||
  305.       syslog_level < 0)
  306.     priority = LOG_DEBUG;
  307.       else
  308.     priority = priority_map[syslog_level];
  309.       
  310. #ifdef __STDC__
  311.       va_start(ap, format_str);
  312. #else
  313.       va_start(ap);
  314.       format_str = va_arg(ap,char *);
  315. #endif
  316.       vslprintf(msgbuf, sizeof(msgbuf)-1,format_str, ap);
  317.       va_end(ap);
  318.       
  319.       msgbuf[255] = '\0';
  320.       syslog(priority, "%s", msgbuf);
  321.     }
  322. #endif
  323.   
  324. #ifdef SYSLOG
  325.   if (!lp_syslog_only())
  326. #endif
  327.     {
  328. #ifdef __STDC__
  329.       va_start(ap, format_str);
  330. #else
  331.       va_start(ap);
  332.       format_str = va_arg(ap,char *);
  333. #endif
  334.       vfprintf(dbf,format_str,ap);
  335.       va_end(ap);
  336.       fflush(dbf);
  337.     }
  338.  
  339.   check_log_size();
  340.  
  341.   errno = old_errno;
  342.  
  343.   return(0);
  344. }
  345.  
  346. /****************************************************************************
  347.   find a suitable temporary directory. The result should be copied immediately
  348.   as it may be overwritten by a subsequent call
  349.   ****************************************************************************/
  350. char *tmpdir(void)
  351. {
  352.   char *p;
  353.   if ((p = getenv("TMPDIR"))) {
  354.     return p;
  355.   }
  356.   return "/tmp";
  357. }
  358.  
  359.  
  360.  
  361. /****************************************************************************
  362. determine if a file descriptor is in fact a socket
  363. ****************************************************************************/
  364. BOOL is_a_socket(int fd)
  365. {
  366.   int v,l;
  367.   l = sizeof(int);
  368.   return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
  369. }
  370.  
  371.  
  372. static char *last_ptr=NULL;
  373.  
  374. /****************************************************************************
  375.   Get the next token from a string, return False if none found
  376.   handles double-quotes. 
  377. Based on a routine by GJC@VILLAGE.COM. 
  378. Extensively modified by Andrew.Tridgell@anu.edu.au
  379. ****************************************************************************/
  380. BOOL next_token(char **ptr,char *buff,char *sep)
  381. {
  382.   char *s;
  383.   BOOL quoted;
  384.  
  385.   if (!ptr) ptr = &last_ptr;
  386.   if (!ptr) return(False);
  387.  
  388.   s = *ptr;
  389.  
  390.   /* default to simple separators */
  391.   if (!sep) sep = " \t\n\r";
  392.  
  393.   /* find the first non sep char */
  394.   while(*s && strchr(sep,*s)) s++;
  395.  
  396.   /* nothing left? */
  397.   if (! *s) return(False);
  398.  
  399.   /* copy over the token */
  400.   for (quoted = False; *s && (quoted || !strchr(sep,*s)); s++)
  401.     {
  402.       if (*s == '\"') 
  403.     quoted = !quoted;
  404.       else
  405.     *buff++ = *s;
  406.     }
  407.  
  408.   *ptr = (*s) ? s+1 : s;  
  409.   *buff = 0;
  410.   last_ptr = *ptr;
  411.  
  412.   return(True);
  413. }
  414.  
  415. /****************************************************************************
  416. Convert list of tokens to array; dependent on above routine.
  417. Uses last_ptr from above - bit of a hack.
  418. ****************************************************************************/
  419. char **toktocliplist(int *ctok, char *sep)
  420. {
  421.   char *s=last_ptr;
  422.   int ictok=0;
  423.   char **ret, **iret;
  424.  
  425.   if (!sep) sep = " \t\n\r";
  426.  
  427.   while(*s && strchr(sep,*s)) s++;
  428.  
  429.   /* nothing left? */
  430.   if (!*s) return(NULL);
  431.  
  432.   do {
  433.     ictok++;
  434.     while(*s && (!strchr(sep,*s))) s++;
  435.     while(*s && strchr(sep,*s)) *s++=0;
  436.   } while(*s);
  437.  
  438.   *ctok=ictok;
  439.   s=last_ptr;
  440.  
  441.   if (!(ret=iret=malloc(ictok*sizeof(char *)))) return NULL;
  442.   
  443.   while(ictok--) {    
  444.     *iret++=s;
  445.     while(*s++);
  446.     while(!*s) s++;
  447.   }
  448.  
  449.   return ret;
  450. }
  451.  
  452. #ifndef HAVE_MEMMOVE
  453. /*******************************************************************
  454. safely copies memory, ensuring no overlap problems.
  455. this is only used if the machine does not have it's own memmove().
  456. this is not the fastest algorithm in town, but it will do for our
  457. needs.
  458. ********************************************************************/
  459. void *MemMove(void *dest,void *src,int size)
  460. {
  461.   unsigned long d,s;
  462.   int i;
  463.   if (dest==src || !size) return(dest);
  464.  
  465.   d = (unsigned long)dest;
  466.   s = (unsigned long)src;
  467.  
  468.   if ((d >= (s+size)) || (s >= (d+size))) {
  469.     /* no overlap */
  470.     memcpy(dest,src,size);
  471.     return(dest);
  472.   }
  473.  
  474.   if (d < s)
  475.     {
  476.       /* we can forward copy */
  477.       if (s-d >= sizeof(int) && 
  478.       !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
  479.     /* do it all as words */
  480.     int *idest = (int *)dest;
  481.     int *isrc = (int *)src;
  482.     size /= sizeof(int);
  483.     for (i=0;i<size;i++) idest[i] = isrc[i];
  484.       } else {
  485.     /* simplest */
  486.     char *cdest = (char *)dest;
  487.     char *csrc = (char *)src;
  488.     for (i=0;i<size;i++) cdest[i] = csrc[i];
  489.       }
  490.     }
  491.   else
  492.     {
  493.       /* must backward copy */
  494.       if (d-s >= sizeof(int) && 
  495.       !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
  496.     /* do it all as words */
  497.     int *idest = (int *)dest;
  498.     int *isrc = (int *)src;
  499.     size /= sizeof(int);
  500.     for (i=size-1;i>=0;i--) idest[i] = isrc[i];
  501.       } else {
  502.     /* simplest */
  503.     char *cdest = (char *)dest;
  504.     char *csrc = (char *)src;
  505.     for (i=size-1;i>=0;i--) cdest[i] = csrc[i];
  506.       }      
  507.     }
  508.   return(dest);
  509. }
  510. #endif
  511.  
  512.  
  513. /****************************************************************************
  514. prompte a dptr (to make it recently used)
  515. ****************************************************************************/
  516. void array_promote(char *array,int elsize,int element)
  517. {
  518.   char *p;
  519.   if (element == 0)
  520.     return;
  521.  
  522.   p = (char *)malloc(elsize);
  523.  
  524.   if (!p)
  525.     {
  526.       DEBUG(5,("Ahh! Can't malloc\n"));
  527.       return;
  528.     }
  529.   memcpy(p,array + element * elsize, elsize);
  530.   memmove(array + elsize,array,elsize*element);
  531.   memcpy(array,p,elsize);
  532.   free(p);
  533. }
  534.  
  535. enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
  536.  
  537. struct
  538. {
  539.   char *name;
  540.   int level;
  541.   int option;
  542.   int value;
  543.   int opttype;
  544. } socket_options[] = {
  545.   {"SO_KEEPALIVE",      SOL_SOCKET,    SO_KEEPALIVE,    0,                 OPT_BOOL},
  546.   {"SO_REUSEADDR",      SOL_SOCKET,    SO_REUSEADDR,    0,                 OPT_BOOL},
  547.   {"SO_BROADCAST",      SOL_SOCKET,    SO_BROADCAST,    0,                 OPT_BOOL},
  548. #ifdef TCP_NODELAY
  549.   {"TCP_NODELAY",       IPPROTO_TCP,   TCP_NODELAY,     0,                 OPT_BOOL},
  550. #endif
  551. #ifdef IPTOS_LOWDELAY
  552.   {"IPTOS_LOWDELAY",    IPPROTO_IP,    IP_TOS,          IPTOS_LOWDELAY,    OPT_ON},
  553. #endif
  554. #ifdef IPTOS_THROUGHPUT
  555.   {"IPTOS_THROUGHPUT",  IPPROTO_IP,    IP_TOS,          IPTOS_THROUGHPUT,  OPT_ON},
  556. #endif
  557. #ifdef SO_SNDBUF
  558.   {"SO_SNDBUF",         SOL_SOCKET,    SO_SNDBUF,       0,                 OPT_INT},
  559. #endif
  560. #ifdef SO_RCVBUF
  561.   {"SO_RCVBUF",         SOL_SOCKET,    SO_RCVBUF,       0,                 OPT_INT},
  562. #endif
  563. #ifdef SO_SNDLOWAT
  564.   {"SO_SNDLOWAT",       SOL_SOCKET,    SO_SNDLOWAT,     0,                 OPT_INT},
  565. #endif
  566. #ifdef SO_RCVLOWAT
  567.   {"SO_RCVLOWAT",       SOL_SOCKET,    SO_RCVLOWAT,     0,                 OPT_INT},
  568. #endif
  569. #ifdef SO_SNDTIMEO
  570.   {"SO_SNDTIMEO",       SOL_SOCKET,    SO_SNDTIMEO,     0,                 OPT_INT},
  571. #endif
  572. #ifdef SO_RCVTIMEO
  573.   {"SO_RCVTIMEO",       SOL_SOCKET,    SO_RCVTIMEO,     0,                 OPT_INT},
  574. #endif
  575.   {NULL,0,0,0,0}};
  576.  
  577.     
  578.  
  579. /****************************************************************************
  580. set user socket options
  581. ****************************************************************************/
  582. void set_socket_options(int fd, char *options)
  583. {
  584.   fstring tok;
  585.  
  586.   while (next_token(&options,tok," \t,"))
  587.     {
  588.       int ret=0,i;
  589.       int value = 1;
  590.       char *p;
  591.       BOOL got_value = False;
  592.  
  593.       if ((p = strchr(tok,'=')))
  594.     {
  595.       *p = 0;
  596.       value = atoi(p+1);
  597.       got_value = True;
  598.     }
  599.  
  600.       for (i=0;socket_options[i].name;i++)
  601.     if (strequal(socket_options[i].name,tok))
  602.       break;
  603.  
  604.       if (!socket_options[i].name)
  605.     {
  606.       DEBUG(0,("Unknown socket option %s\n",tok));
  607.       continue;
  608.     }
  609.  
  610.       switch (socket_options[i].opttype)
  611.     {
  612.     case OPT_BOOL:
  613.     case OPT_INT:
  614.       ret = setsockopt(fd,socket_options[i].level,
  615.                socket_options[i].option,(char *)&value,sizeof(int));
  616.       break;
  617.  
  618.     case OPT_ON:
  619.       if (got_value)
  620.         DEBUG(0,("syntax error - %s does not take a value\n",tok));
  621.  
  622.       {
  623.         int on = socket_options[i].value;
  624.         ret = setsockopt(fd,socket_options[i].level,
  625.                  socket_options[i].option,(char *)&on,sizeof(int));
  626.       }
  627.       break;      
  628.     }
  629.       
  630.       if (ret != 0)
  631.     DEBUG(0,("Failed to set socket option %s\n",tok));
  632.     }
  633. }
  634.  
  635.  
  636.  
  637. /****************************************************************************
  638.   close the socket communication
  639. ****************************************************************************/
  640. void close_sockets(void )
  641. {
  642.   close(Client);
  643.   Client = 0;
  644. }
  645.  
  646. /****************************************************************************
  647. determine whether we are in the specified group
  648. ****************************************************************************/
  649. BOOL in_group(gid_t group, int current_gid, int ngroups, int *groups)
  650. {
  651.   int i;
  652.  
  653.   if (group == current_gid) return(True);
  654.  
  655.   for (i=0;i<ngroups;i++)
  656.     if (group == groups[i])
  657.       return(True);
  658.  
  659.   return(False);
  660. }
  661.  
  662. /****************************************************************************
  663. this is a safer strcpy(), meant to prevent core dumps when nasty things happen
  664. ****************************************************************************/
  665. char *StrCpy(char *dest,char *src)
  666. {
  667.   char *d = dest;
  668.  
  669. #if AJT
  670.   /* I don't want to get lazy with these ... */
  671.   if (!dest || !src) {
  672.     DEBUG(0,("ERROR: NULL StrCpy() called!\n"));
  673.     ajt_panic();
  674.   }
  675. #endif
  676.  
  677.   if (!dest) return(NULL);
  678.   if (!src) {
  679.     *dest = 0;
  680.     return(dest);
  681.   }
  682.   while ((*d++ = *src++)) ;
  683.   return(dest);
  684. }
  685.  
  686. /****************************************************************************
  687. line strncpy but always null terminates. Make sure there is room!
  688. ****************************************************************************/
  689. char *StrnCpy(char *dest,char *src,int n)
  690. {
  691.   char *d = dest;
  692.   if (!dest) return(NULL);
  693.   if (!src) {
  694.     *dest = 0;
  695.     return(dest);
  696.   }
  697.   while (n-- && (*d++ = *src++)) ;
  698.   *d = 0;
  699.   return(dest);
  700. }
  701.  
  702.  
  703. /*******************************************************************
  704. copy an IP address from one buffer to another
  705. ********************************************************************/
  706. void putip(void *dest,void *src)
  707. {
  708.   memcpy(dest,src,4);
  709. }
  710.  
  711.  
  712. /****************************************************************************
  713. interpret the weird netbios "name". Return the name type
  714. ****************************************************************************/
  715. static int name_interpret(char *in,char *out)
  716. {
  717.   int ret;
  718.   int len = (*in++) / 2;
  719.  
  720.   *out=0;
  721.  
  722.   if (len > 30 || len<1) return(0);
  723.  
  724.   while (len--)
  725.     {
  726.       if (in[0] < 'A' || in[0] > 'P' || in[1] < 'A' || in[1] > 'P') {
  727.     *out = 0;
  728.     return(0);
  729.       }
  730.       *out = ((in[0]-'A')<<4) + (in[1]-'A');
  731.       in += 2;
  732.       out++;
  733.     }
  734.   *out = 0;
  735.   ret = out[-1];
  736.  
  737. #ifdef NETBIOS_SCOPE
  738.   /* Handle any scope names */
  739.   while(*in) 
  740.     {
  741.       *out++ = '.'; /* Scope names are separated by periods */
  742.       len = *(unsigned char *)in++;
  743.       StrnCpy(out, in, len);
  744.       out += len;
  745.       *out=0;
  746.       in += len;
  747.     }
  748. #endif
  749.   return(ret);
  750. }
  751.  
  752. /****************************************************************************
  753. mangle a name into netbios format
  754.  
  755.   Note:  <Out> must be (33 + strlen(scope) + 2) bytes long, at minimum.
  756. ****************************************************************************/
  757. int name_mangle( char *In, char *Out, char name_type )
  758.   {
  759.   int   i;
  760.   int   c;
  761.   int   len;
  762.   char  buf[20];
  763.   char *p = Out;
  764.  
  765.   /* Safely copy the input string, In, into buf[]. */
  766.   (void)memset( buf, 0, 20 );
  767.   if( '*' == In[0] )
  768.     buf[0] = '*';
  769.   else
  770.     (void)slprintf( buf, sizeof(buf)-1, "%-15.15s%c", In, name_type );
  771.  
  772.   /* Place the length of the first field into the output buffer. */
  773.   p[0] = 32;
  774.   p++;
  775.  
  776.   /* Now convert the name to the rfc1001/1002 format. */
  777.   for( i = 0; i < 16; i++ )
  778.     {
  779.     c = toupper( buf[i] );
  780.     p[i*2]     = ( (c >> 4) & 0x000F ) + 'A';
  781.     p[(i*2)+1] = (c & 0x000F) + 'A';
  782.     }
  783.   p += 32;
  784.   p[0] = '\0';
  785.  
  786.   /* Add the scope string. */
  787.   for( i = 0, len = 0; NULL != scope; i++, len++ )
  788.     {
  789.     switch( scope[i] )
  790.       {
  791.       case '\0':
  792.         p[0]     = len;
  793.         if( len > 0 )
  794.           p[len+1] = 0;
  795.         return( name_len(Out) );
  796.       case '.':
  797.         p[0] = len;
  798.         p   += (len + 1);
  799.         len  = 0;
  800.         break;
  801.       default:
  802.         p[len+1] = scope[i];
  803.         break;
  804.       }
  805.     }
  806.  
  807.   return( name_len(Out) );
  808.   } /* name_mangle */
  809.  
  810. /*******************************************************************
  811.   check if a file exists
  812. ********************************************************************/
  813. BOOL file_exist(char *fname,struct stat *sbuf)
  814. {
  815.   struct stat st;
  816.   if (!sbuf) sbuf = &st;
  817.   
  818.   if (sys_stat(fname,sbuf) != 0) 
  819.     return(False);
  820.  
  821.   return(S_ISREG(sbuf->st_mode));
  822. }
  823.  
  824. /*******************************************************************
  825. check a files mod time
  826. ********************************************************************/
  827. time_t file_modtime(char *fname)
  828. {
  829.   struct stat st;
  830.   
  831.   if (sys_stat(fname,&st) != 0) 
  832.     return(0);
  833.  
  834.   return(st.st_mtime);
  835. }
  836.  
  837. /*******************************************************************
  838.   check if a directory exists
  839. ********************************************************************/
  840. BOOL directory_exist(char *dname,struct stat *st)
  841. {
  842.   struct stat st2;
  843.   BOOL ret;
  844.  
  845.   if (!st) st = &st2;
  846.  
  847.   if (sys_stat(dname,st) != 0) 
  848.     return(False);
  849.  
  850.   ret = S_ISDIR(st->st_mode);
  851.   if(!ret)
  852.     errno = ENOTDIR;
  853.   return ret;
  854. }
  855.  
  856. /*******************************************************************
  857. returns the size in bytes of the named file
  858. ********************************************************************/
  859. uint32 file_size(char *file_name)
  860. {
  861.   struct stat buf;
  862.   buf.st_size = 0;
  863.   sys_stat(file_name,&buf);
  864.   return(buf.st_size);
  865. }
  866.  
  867. /*******************************************************************
  868. return a string representing an attribute for a file
  869. ********************************************************************/
  870. char *attrib_string(int mode)
  871. {
  872.   static fstring attrstr;
  873.  
  874.   attrstr[0] = 0;
  875.  
  876.   if (mode & aVOLID) fstrcat(attrstr,"V");
  877.   if (mode & aDIR) fstrcat(attrstr,"D");
  878.   if (mode & aARCH) fstrcat(attrstr,"A");
  879.   if (mode & aHIDDEN) fstrcat(attrstr,"H");
  880.   if (mode & aSYSTEM) fstrcat(attrstr,"S");
  881.   if (mode & aRONLY) fstrcat(attrstr,"R");      
  882.  
  883.   return(attrstr);
  884. }
  885.  
  886.  
  887. /*******************************************************************
  888.   case insensitive string compararison
  889. ********************************************************************/
  890. int StrCaseCmp(char *s, char *t)
  891. {
  892.   /* compare until we run out of string, either t or s, or find a difference */
  893.   /* We *must* use toupper rather than tolower here due to the
  894.      asynchronous upper to lower mapping.
  895.    */
  896. #if !defined(KANJI_WIN95_COMPATIBILITY)
  897.   /*
  898.    * For completeness we should put in equivalent code for code pages
  899.    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
  900.    * doubt anyone wants Samba to behave differently from Win95 and WinNT
  901.    * here. They both treat full width ascii characters as case senstive
  902.    * filenames (ie. they don't do the work we do here).
  903.    * JRA.
  904.    */
  905.  
  906.   if(lp_client_code_page() == KANJI_CODEPAGE)
  907.   {
  908.     /* Win95 treats full width ascii characters as case sensitive. */
  909.     int diff;
  910.     for (;;)
  911.     {
  912.       if (!*s || !*t)
  913.         return toupper (*s) - toupper (*t);
  914.       else if (is_sj_alph (*s) && is_sj_alph (*t))
  915.       {
  916.         diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
  917.         if (diff)
  918.           return diff;
  919.         s += 2;
  920.         t += 2;
  921.       }
  922.       else if (is_shift_jis (*s) && is_shift_jis (*t))
  923.       {
  924.         diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
  925.         if (diff)
  926.           return diff;
  927.         diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
  928.         if (diff)
  929.           return diff;
  930.         s += 2;
  931.         t += 2;
  932.       }
  933.       else if (is_shift_jis (*s))
  934.         return 1;
  935.       else if (is_shift_jis (*t))
  936.         return -1;
  937.       else 
  938.       {
  939.         diff = toupper (*s) - toupper (*t);
  940.         if (diff)
  941.           return diff;
  942.         s++;
  943.         t++;
  944.       }
  945.     }
  946.   }
  947.   else
  948. #endif /* KANJI_WIN95_COMPATIBILITY */
  949.   {
  950.     while (*s && *t && toupper(*s) == toupper(*t))
  951.     {
  952.       s++;
  953.       t++;
  954.     }
  955.  
  956.     return(toupper(*s) - toupper(*t));
  957.   }
  958. }
  959.  
  960. /*******************************************************************
  961.   case insensitive string compararison, length limited
  962. ********************************************************************/
  963. int StrnCaseCmp(char *s, char *t, int n)
  964. {
  965.   /* compare until we run out of string, either t or s, or chars */
  966.   /* We *must* use toupper rather than tolower here due to the
  967.      asynchronous upper to lower mapping.
  968.    */
  969. #if !defined(KANJI_WIN95_COMPATIBILITY)
  970.   /*
  971.    * For completeness we should put in equivalent code for code pages
  972.    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
  973.    * doubt anyone wants Samba to behave differently from Win95 and WinNT
  974.    * here. They both treat full width ascii characters as case senstive
  975.    * filenames (ie. they don't do the work we do here).
  976.    * JRA. 
  977.    */
  978.  
  979.   if(lp_client_code_page() == KANJI_CODEPAGE)
  980.   {
  981.     /* Win95 treats full width ascii characters as case sensitive. */
  982.     int diff;
  983.     for (;n > 0;)
  984.     {
  985.       if (!*s || !*t)
  986.         return toupper (*s) - toupper (*t);
  987.       else if (is_sj_alph (*s) && is_sj_alph (*t))
  988.       {
  989.         diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
  990.         if (diff)
  991.           return diff;
  992.         s += 2;
  993.         t += 2;
  994.         n -= 2;
  995.       }
  996.       else if (is_shift_jis (*s) && is_shift_jis (*t))
  997.       {
  998.         diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
  999.         if (diff)
  1000.           return diff;
  1001.         diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
  1002.         if (diff)
  1003.           return diff;
  1004.         s += 2;
  1005.         t += 2;
  1006.         n -= 2;
  1007.       }
  1008.       else if (is_shift_jis (*s))
  1009.         return 1;
  1010.       else if (is_shift_jis (*t))
  1011.         return -1;
  1012.       else 
  1013.       {
  1014.         diff = toupper (*s) - toupper (*t);
  1015.         if (diff)
  1016.           return diff;
  1017.         s++;
  1018.         t++;
  1019.         n--;
  1020.       }
  1021.     }
  1022.     return 0;
  1023.   }
  1024.   else
  1025. #endif /* KANJI_WIN95_COMPATIBILITY */
  1026.   {
  1027.     while (n && *s && *t && toupper(*s) == toupper(*t))
  1028.     {
  1029.       s++;
  1030.       t++;
  1031.       n--;
  1032.     }
  1033.  
  1034.     /* not run out of chars - strings are different lengths */
  1035.     if (n) 
  1036.       return(toupper(*s) - toupper(*t));
  1037.  
  1038.     /* identical up to where we run out of chars, 
  1039.        and strings are same length */
  1040.     return(0);
  1041.   }
  1042. }
  1043.  
  1044. /*******************************************************************
  1045.   compare 2 strings 
  1046. ********************************************************************/
  1047. BOOL strequal(char *s1, char *s2)
  1048. {
  1049.   if (s1 == s2) return(True);
  1050.   if (!s1 || !s2) return(False);
  1051.   
  1052.   return(StrCaseCmp(s1,s2)==0);
  1053. }
  1054.  
  1055. /*******************************************************************
  1056.   compare 2 strings up to and including the nth char.
  1057.   ******************************************************************/
  1058. BOOL strnequal(char *s1,char *s2,int n)
  1059. {
  1060.   if (s1 == s2) return(True);
  1061.   if (!s1 || !s2 || !n) return(False);
  1062.   
  1063.   return(StrnCaseCmp(s1,s2,n)==0);
  1064. }
  1065.  
  1066. /*******************************************************************
  1067.   compare 2 strings (case sensitive)
  1068. ********************************************************************/
  1069. BOOL strcsequal(char *s1,char *s2)
  1070. {
  1071.   if (s1 == s2) return(True);
  1072.   if (!s1 || !s2) return(False);
  1073.   
  1074.   return(strcmp(s1,s2)==0);
  1075. }
  1076.  
  1077.  
  1078. /*******************************************************************
  1079.   convert a string to lower case
  1080. ********************************************************************/
  1081. void strlower(char *s)
  1082. {
  1083.   while (*s)
  1084.   {
  1085. #if !defined(KANJI_WIN95_COMPATIBILITY)
  1086.   /*
  1087.    * For completeness we should put in equivalent code for code pages
  1088.    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
  1089.    * doubt anyone wants Samba to behave differently from Win95 and WinNT
  1090.    * here. They both treat full width ascii characters as case senstive
  1091.    * filenames (ie. they don't do the work we do here).
  1092.    * JRA. 
  1093.    */
  1094.  
  1095.     if(lp_client_code_page() == KANJI_CODEPAGE)
  1096.     {
  1097.       /* Win95 treats full width ascii characters as case sensitive. */
  1098.       if (is_shift_jis (*s))
  1099.       {
  1100.         if (is_sj_upper (s[0], s[1]))
  1101.           s[1] = sj_tolower2 (s[1]);
  1102.         s += 2;
  1103.       }
  1104.       else if (is_kana (*s))
  1105.       {
  1106.         s++;
  1107.       }
  1108.       else
  1109.       {
  1110.         if (isupper(*s))
  1111.           *s = tolower(*s);
  1112.         s++;
  1113.       }
  1114.     }
  1115.     else
  1116. #endif /* KANJI_WIN95_COMPATIBILITY */
  1117.     {
  1118.       if (isupper(*s))
  1119.         *s = tolower(*s);
  1120.       s++;
  1121.     }
  1122.   }
  1123. }
  1124.  
  1125. /*******************************************************************
  1126.   convert a string to upper case
  1127. ********************************************************************/
  1128. void strupper(char *s)
  1129. {
  1130.   while (*s)
  1131.   {
  1132. #if !defined(KANJI_WIN95_COMPATIBILITY)
  1133.   /*
  1134.    * For completeness we should put in equivalent code for code pages
  1135.    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
  1136.    * doubt anyone wants Samba to behave differently from Win95 and WinNT
  1137.    * here. They both treat full width ascii characters as case senstive
  1138.    * filenames (ie. they don't do the work we do here).
  1139.    * JRA. 
  1140.    */
  1141.  
  1142.     if(lp_client_code_page() == KANJI_CODEPAGE)
  1143.     {
  1144.       /* Win95 treats full width ascii characters as case sensitive. */
  1145.       if (is_shift_jis (*s))
  1146.       {
  1147.         if (is_sj_lower (s[0], s[1]))
  1148.           s[1] = sj_toupper2 (s[1]);
  1149.         s += 2;
  1150.       }
  1151.       else if (is_kana (*s))
  1152.       {
  1153.         s++;
  1154.       }
  1155.       else
  1156.       {
  1157.         if (islower(*s))
  1158.           *s = toupper(*s);
  1159.         s++;
  1160.       }
  1161.     }
  1162.     else
  1163. #endif /* KANJI_WIN95_COMPATIBILITY */
  1164.     {
  1165.       if (islower(*s))
  1166.         *s = toupper(*s);
  1167.       s++;
  1168.     }
  1169.   }
  1170. }
  1171.  
  1172. /*******************************************************************
  1173.   convert a string to "normal" form
  1174. ********************************************************************/
  1175. void strnorm(char *s)
  1176. {
  1177.   if (case_default == CASE_UPPER)
  1178.     strupper(s);
  1179.   else
  1180.     strlower(s);
  1181. }
  1182.  
  1183. /*******************************************************************
  1184. check if a string is in "normal" case
  1185. ********************************************************************/
  1186. BOOL strisnormal(char *s)
  1187. {
  1188.   if (case_default == CASE_UPPER)
  1189.     return(!strhaslower(s));
  1190.  
  1191.   return(!strhasupper(s));
  1192. }
  1193.  
  1194.  
  1195. /****************************************************************************
  1196.   string replace
  1197. ****************************************************************************/
  1198. void string_replace(char *s,char oldc,char newc)
  1199. {
  1200.   while (*s)
  1201.   {
  1202. #if !defined(KANJI_WIN95_COMPATIBILITY)
  1203.   /*
  1204.    * For completeness we should put in equivalent code for code pages
  1205.    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
  1206.    * doubt anyone wants Samba to behave differently from Win95 and WinNT
  1207.    * here. They both treat full width ascii characters as case senstive
  1208.    * filenames (ie. they don't do the work we do here).
  1209.    * JRA. 
  1210.    */
  1211.  
  1212.     if(lp_client_code_page() == KANJI_CODEPAGE)
  1213.     {
  1214.       /* Win95 treats full width ascii characters as case sensitive. */
  1215.       if (is_shift_jis (*s))
  1216.         s += 2;
  1217.       else if (is_kana (*s))
  1218.         s++;
  1219.       else
  1220.       {
  1221.         if (oldc == *s)
  1222.           *s = newc;
  1223.         s++;
  1224.       }
  1225.     }
  1226.     else
  1227. #endif /* KANJI_WIN95_COMPATIBILITY */
  1228.     {
  1229.       if (oldc == *s)
  1230.         *s = newc;
  1231.       s++;
  1232.     }
  1233.   }
  1234. }
  1235.  
  1236. /****************************************************************************
  1237.   make a file into unix format
  1238. ****************************************************************************/
  1239. void unix_format(char *fname)
  1240. {
  1241.   pstring namecopy;
  1242.   string_replace(fname,'\\','/');
  1243.  
  1244.   if (*fname == '/')
  1245.     {
  1246.       pstrcpy(namecopy,fname);
  1247.       pstrcpy(fname,".");
  1248.       pstrcat(fname,namecopy);
  1249.     }  
  1250. }
  1251.  
  1252. /****************************************************************************
  1253.   make a file into dos format
  1254. ****************************************************************************/
  1255. void dos_format(char *fname)
  1256. {
  1257.   string_replace(fname,'/','\\');
  1258. }
  1259.  
  1260.  
  1261. /*******************************************************************
  1262.   show a smb message structure
  1263. ********************************************************************/
  1264. void show_msg(char *buf)
  1265. {
  1266.   int i;
  1267.   int bcc=0;
  1268.  
  1269.   if (DEBUGLEVEL < 5) return;
  1270.  
  1271.   DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
  1272.       smb_len(buf),
  1273.       (int)CVAL(buf,smb_com),
  1274.       (int)CVAL(buf,smb_rcls),
  1275.       (int)CVAL(buf,smb_reh),
  1276.       (int)SVAL(buf,smb_err),
  1277.       (int)CVAL(buf,smb_flg),
  1278.       (int)SVAL(buf,smb_flg2)));
  1279.   DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
  1280.       (int)SVAL(buf,smb_tid),
  1281.       (int)SVAL(buf,smb_pid),
  1282.       (int)SVAL(buf,smb_uid),
  1283.       (int)SVAL(buf,smb_mid),
  1284.       (int)CVAL(buf,smb_wct)));
  1285.  
  1286.   for (i=0;i<(int)CVAL(buf,smb_wct);i++)
  1287.     DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
  1288.       SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
  1289.  
  1290.   bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
  1291.   DEBUG(5,("smb_bcc=%d\n",bcc));
  1292.  
  1293.   if (DEBUGLEVEL < 10) return;
  1294.  
  1295.   dump_data(10, smb_buf(buf), MIN(bcc, 512));
  1296. }
  1297.  
  1298. /*******************************************************************
  1299.   return the length of an smb packet
  1300. ********************************************************************/
  1301. int smb_len(char *buf)
  1302. {
  1303.   return( PVAL(buf,3) | (PVAL(buf,2)<<8) | ((PVAL(buf,1)&1)<<16) );
  1304. }
  1305.  
  1306. /*******************************************************************
  1307.   set the length of an smb packet
  1308. ********************************************************************/
  1309. void _smb_setlen(char *buf,int len)
  1310. {
  1311.   buf[0] = 0;
  1312.   buf[1] = (len&0x10000)>>16;
  1313.   buf[2] = (len&0xFF00)>>8;
  1314.   buf[3] = len&0xFF;
  1315. }
  1316.  
  1317. /*******************************************************************
  1318.   set the length and marker of an smb packet
  1319. ********************************************************************/
  1320. void smb_setlen(char *buf,int len)
  1321. {
  1322.   _smb_setlen(buf,len);
  1323.  
  1324.   CVAL(buf,4) = 0xFF;
  1325.   CVAL(buf,5) = 'S';
  1326.   CVAL(buf,6) = 'M';
  1327.   CVAL(buf,7) = 'B';
  1328. }
  1329.  
  1330. /*******************************************************************
  1331.   setup the word count and byte count for a smb message
  1332. ********************************************************************/
  1333. int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
  1334. {
  1335.   if (zero)
  1336.     bzero(buf + smb_size,num_words*2 + num_bytes);
  1337.   CVAL(buf,smb_wct) = num_words;
  1338.   SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
  1339.   smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
  1340.   return (smb_size + num_words*2 + num_bytes);
  1341. }
  1342.  
  1343. /*******************************************************************
  1344. return the number of smb words
  1345. ********************************************************************/
  1346. int smb_numwords(char *buf)
  1347. {
  1348.   return (CVAL(buf,smb_wct));
  1349. }
  1350.  
  1351. /*******************************************************************
  1352. return the size of the smb_buf region of a message
  1353. ********************************************************************/
  1354. int smb_buflen(char *buf)
  1355. {
  1356.   return(SVAL(buf,smb_vwv0 + smb_numwords(buf)*2));
  1357. }
  1358.  
  1359. /*******************************************************************
  1360.   return a pointer to the smb_buf data area
  1361. ********************************************************************/
  1362. int smb_buf_ofs(char *buf)
  1363. {
  1364.   return (smb_size + CVAL(buf,smb_wct)*2);
  1365. }
  1366.  
  1367. /*******************************************************************
  1368.   return a pointer to the smb_buf data area
  1369. ********************************************************************/
  1370. char *smb_buf(char *buf)
  1371. {
  1372.   return (buf + smb_buf_ofs(buf));
  1373. }
  1374.  
  1375. /*******************************************************************
  1376. return the SMB offset into an SMB buffer
  1377. ********************************************************************/
  1378. int smb_offset(char *p,char *buf)
  1379. {
  1380.   return(PTR_DIFF(p,buf+4) + chain_size);
  1381. }
  1382.  
  1383.  
  1384. /*******************************************************************
  1385. skip past some strings in a buffer
  1386. ********************************************************************/
  1387. char *skip_string(char *buf,int n)
  1388. {
  1389.   while (n--)
  1390.     buf += strlen(buf) + 1;
  1391.   return(buf);
  1392. }
  1393.  
  1394. /*******************************************************************
  1395. trim the specified elements off the front and back of a string
  1396. ********************************************************************/
  1397. BOOL trim_string(char *s,char *front,char *back)
  1398. {
  1399.   BOOL ret = False;
  1400.   while (front && *front && strncmp(s,front,strlen(front)) == 0)
  1401.     {
  1402.       char *p = s;
  1403.       ret = True;
  1404.       while (1)
  1405.     {
  1406.       if (!(*p = p[strlen(front)]))
  1407.         break;
  1408.       p++;
  1409.     }
  1410.     }
  1411.   while (back && *back && strlen(s) >= strlen(back) && 
  1412.      (strncmp(s+strlen(s)-strlen(back),back,strlen(back))==0))  
  1413.     {
  1414.       ret = True;
  1415.       s[strlen(s)-strlen(back)] = 0;
  1416.     }
  1417.   return(ret);
  1418. }
  1419.  
  1420.  
  1421. /*******************************************************************
  1422. reduce a file name, removing .. elements.
  1423. ********************************************************************/
  1424. void dos_clean_name(char *s)
  1425. {
  1426.   char *p=NULL;
  1427.  
  1428.   DEBUG(3,("dos_clean_name [%s]\n",s));
  1429.  
  1430.   /* remove any double slashes */
  1431.   string_sub(s, "\\\\", "\\");
  1432.  
  1433.   while ((p = strstr(s,"\\..\\")) != NULL)
  1434.     {
  1435.       pstring s1;
  1436.  
  1437.       *p = 0;
  1438.       pstrcpy(s1,p+3);
  1439.  
  1440.       if ((p=strrchr(s,'\\')) != NULL)
  1441.     *p = 0;
  1442.       else
  1443.     *s = 0;
  1444.       pstrcat(s,s1);
  1445.     }  
  1446.  
  1447.   trim_string(s,NULL,"\\..");
  1448.  
  1449.   string_sub(s, "\\.\\", "\\");
  1450. }
  1451.  
  1452. /*******************************************************************
  1453. reduce a file name, removing .. elements. 
  1454. ********************************************************************/
  1455. void unix_clean_name(char *s)
  1456. {
  1457.   char *p=NULL;
  1458.  
  1459.   DEBUG(3,("unix_clean_name [%s]\n",s));
  1460.  
  1461.   /* remove any double slashes */
  1462.   string_sub(s, "//","/");
  1463.  
  1464.   /* Remove leading ./ characters */
  1465.   if(strncmp(s, "./", 2) == 0) {
  1466.     trim_string(s, "./", NULL);
  1467.     if(*s == 0)
  1468.       pstrcpy(s,"./");
  1469.   }
  1470.  
  1471.   while ((p = strstr(s,"/../")) != NULL)
  1472.     {
  1473.       pstring s1;
  1474.  
  1475.       *p = 0;
  1476.       pstrcpy(s1,p+3);
  1477.  
  1478.       if ((p=strrchr(s,'/')) != NULL)
  1479.     *p = 0;
  1480.       else
  1481.     *s = 0;
  1482.       pstrcat(s,s1);
  1483.     }  
  1484.  
  1485.   trim_string(s,NULL,"/..");
  1486. }
  1487.  
  1488.  
  1489. /*******************************************************************
  1490. a wrapper for the normal chdir() function
  1491. ********************************************************************/
  1492. int ChDir(char *path)
  1493. {
  1494.   int res;
  1495.   static pstring LastDir="";
  1496.  
  1497.   if (strcsequal(path,".")) return(0);
  1498.  
  1499.   if (*path == '/' && strcsequal(LastDir,path)) return(0);
  1500.   DEBUG(3,("chdir to %s\n",path));
  1501.   res = sys_chdir(path);
  1502.   if (!res)
  1503.     pstrcpy(LastDir,path);
  1504.   return(res);
  1505. }
  1506.  
  1507. /* number of list structures for a caching GetWd function. */
  1508. #define MAX_GETWDCACHE (50)
  1509.  
  1510. struct
  1511. {
  1512.   ino_t inode;
  1513.   dev_t dev;
  1514.   char *text;
  1515.   BOOL valid;
  1516. } ino_list[MAX_GETWDCACHE];
  1517.  
  1518. BOOL use_getwd_cache=True;
  1519.  
  1520. /*******************************************************************
  1521.   return the absolute current directory path
  1522. ********************************************************************/
  1523. char *GetWd(char *str)
  1524. {
  1525.   pstring s;
  1526.   static BOOL getwd_cache_init = False;
  1527.   struct stat st, st2;
  1528.   int i;
  1529.  
  1530.   *s = 0;
  1531.  
  1532.   if (!use_getwd_cache)
  1533.     return(sys_getwd(str));
  1534.  
  1535.   /* init the cache */
  1536.   if (!getwd_cache_init)
  1537.     {
  1538.       getwd_cache_init = True;
  1539.       for (i=0;i<MAX_GETWDCACHE;i++)
  1540.     {
  1541.       string_init(&ino_list[i].text,"");
  1542.       ino_list[i].valid = False;
  1543.     }
  1544.     }
  1545.  
  1546.   /*  Get the inode of the current directory, if this doesn't work we're
  1547.       in trouble :-) */
  1548.  
  1549.   if (stat(".",&st) == -1) 
  1550.     {
  1551.       DEBUG(0,("Very strange, couldn't stat \".\"\n"));
  1552.       return(sys_getwd(str));
  1553.     }
  1554.  
  1555.  
  1556.   for (i=0; i<MAX_GETWDCACHE; i++)
  1557.     if (ino_list[i].valid)
  1558.       {
  1559.  
  1560.     /*  If we have found an entry with a matching inode and dev number
  1561.         then find the inode number for the directory in the cached string.
  1562.         If this agrees with that returned by the stat for the current
  1563.         directory then all is o.k. (but make sure it is a directory all
  1564.         the same...) */
  1565.       
  1566.     if (st.st_ino == ino_list[i].inode &&
  1567.         st.st_dev == ino_list[i].dev)
  1568.       {
  1569.         if (stat(ino_list[i].text,&st2) == 0)
  1570.           {
  1571.         if (st.st_ino == st2.st_ino &&
  1572.             st.st_dev == st2.st_dev &&
  1573.             (st2.st_mode & S_IFMT) == S_IFDIR)
  1574.           {
  1575.             pstrcpy (str, ino_list[i].text);
  1576.  
  1577.             /* promote it for future use */
  1578.             array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
  1579.             return (str);
  1580.           }
  1581.         else
  1582.           {
  1583.             /*  If the inode is different then something's changed, 
  1584.             scrub the entry and start from scratch. */
  1585.             ino_list[i].valid = False;
  1586.           }
  1587.           }
  1588.       }
  1589.       }
  1590.  
  1591.  
  1592.   /*  We don't have the information to hand so rely on traditional methods.
  1593.       The very slow getcwd, which spawns a process on some systems, or the
  1594.       not quite so bad getwd. */
  1595.  
  1596.   if (!sys_getwd(s))
  1597.     {
  1598.       DEBUG(0,("Getwd failed, errno %s\n",strerror(errno)));
  1599.       return (NULL);
  1600.     }
  1601.  
  1602.   pstrcpy(str,s);
  1603.  
  1604.   DEBUG(5,("GetWd %s, inode %d, dev %x\n",s,(int)st.st_ino,(int)st.st_dev));
  1605.  
  1606.   /* add it to the cache */
  1607.   i = MAX_GETWDCACHE - 1;
  1608.   string_set(&ino_list[i].text,s);
  1609.   ino_list[i].dev = st.st_dev;
  1610.   ino_list[i].inode = st.st_ino;
  1611.   ino_list[i].valid = True;
  1612.  
  1613.   /* put it at the top of the list */
  1614.   array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
  1615.  
  1616.   return (str);
  1617. }
  1618.  
  1619.  
  1620.  
  1621. /*******************************************************************
  1622. reduce a file name, removing .. elements and checking that 
  1623. it is below dir in the heirachy. This uses GetWd() and so must be run
  1624. on the system that has the referenced file system.
  1625.  
  1626. widelinks are allowed if widelinks is true
  1627. ********************************************************************/
  1628. BOOL reduce_name(char *s,char *dir,BOOL widelinks)
  1629. {
  1630. #ifndef REDUCE_PATHS
  1631.   return True;
  1632. #else
  1633.   pstring dir2;
  1634.   pstring wd;
  1635.   pstring base_name;
  1636.   pstring newname;
  1637.   char *p=NULL;
  1638.   BOOL relative = (*s != '/');
  1639.  
  1640.   *dir2 = *wd = *base_name = *newname = 0;
  1641.  
  1642.   if (widelinks)
  1643.     {
  1644.       unix_clean_name(s);
  1645.       /* can't have a leading .. */
  1646.       if (strncmp(s,"..",2) == 0 && (s[2]==0 || s[2]=='/'))
  1647.     {
  1648.       DEBUG(3,("Illegal file name? (%s)\n",s));
  1649.       return(False);
  1650.     }
  1651.  
  1652.       if (strlen(s) == 0)
  1653.         pstrcpy(s,"./");
  1654.  
  1655.       return(True);
  1656.     }
  1657.   
  1658.   DEBUG(3,("reduce_name [%s] [%s]\n",s,dir));
  1659.  
  1660.   /* remove any double slashes */
  1661.   string_sub(s,"//","/");
  1662.  
  1663.   pstrcpy(base_name,s);
  1664.   p = strrchr(base_name,'/');
  1665.  
  1666.   if (!p)
  1667.     return(True);
  1668.  
  1669.   if (!GetWd(wd))
  1670.     {
  1671.       DEBUG(0,("couldn't getwd for %s %s\n",s,dir));
  1672.       return(False);
  1673.     }
  1674.  
  1675.   if (ChDir(dir) != 0)
  1676.     {
  1677.       DEBUG(0,("couldn't chdir to %s\n",dir));
  1678.       return(False);
  1679.     }
  1680.  
  1681.   if (!GetWd(dir2))
  1682.     {
  1683.       DEBUG(0,("couldn't getwd for %s\n",dir));
  1684.       ChDir(wd);
  1685.       return(False);
  1686.     }
  1687.  
  1688.  
  1689.     if (p && (p != base_name))
  1690.       {
  1691.     *p = 0;
  1692.     if (strcmp(p+1,".")==0)
  1693.       p[1]=0;
  1694.     if (strcmp(p+1,"..")==0)
  1695.       *p = '/';
  1696.       }
  1697.  
  1698.   if (ChDir(base_name) != 0)
  1699.     {
  1700.       ChDir(wd);
  1701.       DEBUG(3,("couldn't chdir for %s %s basename=%s\n",s,dir,base_name));
  1702.       return(False);
  1703.     }
  1704.  
  1705.   if (!GetWd(newname))
  1706.     {
  1707.       ChDir(wd);
  1708.       DEBUG(2,("couldn't get wd for %s %s\n",s,dir2));
  1709.       return(False);
  1710.     }
  1711.  
  1712.   if (p && (p != base_name))
  1713.     {
  1714.       pstrcat(newname,"/");
  1715.       pstrcat(newname,p+1);
  1716.     }
  1717.  
  1718.   {
  1719.     int l = strlen(dir2);    
  1720.     if (dir2[l-1] == '/')
  1721.       l--;
  1722.  
  1723.     if (strncmp(newname,dir2,l) != 0)
  1724.       {
  1725.     ChDir(wd);
  1726.     DEBUG(2,("Bad access attempt? s=%s dir=%s newname=%s l=%d\n",s,dir2,newname,l));
  1727.     return(False);
  1728.       }
  1729.  
  1730.     if (relative)
  1731.       {
  1732.     if (newname[l] == '/')
  1733.       pstrcpy(s,newname + l + 1);
  1734.     else
  1735.       pstrcpy(s,newname+l);
  1736.       }
  1737.     else
  1738.       pstrcpy(s,newname);
  1739.   }
  1740.  
  1741.   ChDir(wd);
  1742.  
  1743.   if (strlen(s) == 0)
  1744.     pstrcpy(s,"./");
  1745.  
  1746.   DEBUG(3,("reduced to %s\n",s));
  1747.   return(True);
  1748. #endif
  1749. }
  1750.  
  1751. /****************************************************************************
  1752. expand some *s 
  1753. ****************************************************************************/
  1754. static void expand_one(char *Mask,int len)
  1755. {
  1756.   char *p1;
  1757.   while ((p1 = strchr(Mask,'*')) != NULL)
  1758.     {
  1759.       int lfill = (len+1) - strlen(Mask);
  1760.       int l1= (p1 - Mask);
  1761.       pstring tmp;
  1762.       pstrcpy(tmp,Mask);  
  1763.       memset(tmp+l1,'?',lfill);
  1764.       pstrcpy(tmp + l1 + lfill,Mask + l1 + 1);    
  1765.       pstrcpy(Mask,tmp);      
  1766.     }
  1767. }
  1768.  
  1769. /****************************************************************************
  1770. expand a wildcard expression, replacing *s with ?s
  1771. ****************************************************************************/
  1772. void expand_mask(char *Mask,BOOL doext)
  1773. {
  1774.   pstring mbeg,mext;
  1775.   pstring dirpart;
  1776.   pstring filepart;
  1777.   BOOL hasdot = False;
  1778.   char *p1;
  1779.   BOOL absolute = (*Mask == '\\');
  1780.  
  1781.   *mbeg = *mext = *dirpart = *filepart = 0;
  1782.  
  1783.   /* parse the directory and filename */
  1784.   if (strchr(Mask,'\\'))
  1785.     dirname_dos(Mask,dirpart);
  1786.  
  1787.   filename_dos(Mask,filepart);
  1788.  
  1789.   pstrcpy(mbeg,filepart);
  1790.   if ((p1 = strchr(mbeg,'.')) != NULL)
  1791.     {
  1792.       hasdot = True;
  1793.       *p1 = 0;
  1794.       p1++;
  1795.       pstrcpy(mext,p1);
  1796.     }
  1797.   else
  1798.     {
  1799.       pstrcpy(mext,"");
  1800.       if (strlen(mbeg) > 8)
  1801.     {
  1802.       pstrcpy(mext,mbeg + 8);
  1803.       mbeg[8] = 0;
  1804.     }
  1805.     }
  1806.  
  1807.   if (*mbeg == 0)
  1808.     pstrcpy(mbeg,"????????");
  1809.   if ((*mext == 0) && doext && !hasdot)
  1810.     pstrcpy(mext,"???");
  1811.  
  1812.   if (strequal(mbeg,"*") && *mext==0) 
  1813.     pstrcpy(mext,"*");
  1814.  
  1815.   /* expand *'s */
  1816.   expand_one(mbeg,8);
  1817.   if (*mext)
  1818.     expand_one(mext,3);
  1819.  
  1820.   pstrcpy(Mask,dirpart);
  1821.   if (*dirpart || absolute) pstrcat(Mask,"\\");
  1822.   pstrcat(Mask,mbeg);
  1823.   pstrcat(Mask,".");
  1824.   pstrcat(Mask,mext);
  1825.  
  1826.   DEBUG(6,("Mask expanded to [%s]\n",Mask));
  1827. }  
  1828.  
  1829.  
  1830. /****************************************************************************
  1831. does a string have any uppercase chars in it?
  1832. ****************************************************************************/
  1833. BOOL strhasupper(char *s)
  1834. {
  1835.   while (*s) 
  1836.   {
  1837. #if !defined(KANJI_WIN95_COMPATIBILITY)
  1838.   /*
  1839.    * For completeness we should put in equivalent code for code pages
  1840.    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
  1841.    * doubt anyone wants Samba to behave differently from Win95 and WinNT
  1842.    * here. They both treat full width ascii characters as case senstive
  1843.    * filenames (ie. they don't do the work we do here).
  1844.    * JRA. 
  1845.    */
  1846.  
  1847.     if(lp_client_code_page() == KANJI_CODEPAGE)
  1848.     {
  1849.       /* Win95 treats full width ascii characters as case sensitive. */
  1850.       if (is_shift_jis (*s))
  1851.         s += 2;
  1852.       else if (is_kana (*s))
  1853.         s++;
  1854.       else
  1855.       {
  1856.         if (isupper(*s))
  1857.           return(True);
  1858.         s++;
  1859.       }
  1860.     }
  1861.     else
  1862. #endif /* KANJI_WIN95_COMPATIBILITY */
  1863.     {
  1864.       if (isupper(*s))
  1865.         return(True);
  1866.       s++;
  1867.     }
  1868.   }
  1869.   return(False);
  1870. }
  1871.  
  1872. /****************************************************************************
  1873. does a string have any lowercase chars in it?
  1874. ****************************************************************************/
  1875. BOOL strhaslower(char *s)
  1876. {
  1877.   while (*s) 
  1878.   {
  1879. #if !defined(KANJI_WIN95_COMPATIBILITY)
  1880.   /*
  1881.    * For completeness we should put in equivalent code for code pages
  1882.    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
  1883.    * doubt anyone wants Samba to behave differently from Win95 and WinNT
  1884.    * here. They both treat full width ascii characters as case senstive
  1885.    * filenames (ie. they don't do the work we do here).
  1886.    * JRA. 
  1887.    */
  1888.  
  1889.     if(lp_client_code_page() == KANJI_CODEPAGE)
  1890.     {
  1891.       /* Win95 treats full width ascii characters as case sensitive. */
  1892.       if (is_shift_jis (*s))
  1893.       {
  1894.         if (is_sj_upper (s[0], s[1]))
  1895.           return(True);
  1896.         if (is_sj_lower (s[0], s[1]))
  1897.           return (True);
  1898.         s += 2;
  1899.       }
  1900.       else if (is_kana (*s))
  1901.       {
  1902.         s++;
  1903.       }
  1904.       else
  1905.       {
  1906.         if (islower(*s))
  1907.           return(True);
  1908.         s++;
  1909.       }
  1910.     }
  1911.     else
  1912. #endif /* KANJI_WIN95_COMPATIBILITY */
  1913.     {
  1914.       if (islower(*s))
  1915.         return(True);
  1916.       s++;
  1917.     }
  1918.   }
  1919.   return(False);
  1920. }
  1921.  
  1922. /****************************************************************************
  1923. find the number of chars in a string
  1924. ****************************************************************************/
  1925. int count_chars(char *s,char c)
  1926. {
  1927.   int count=0;
  1928.  
  1929. #if !defined(KANJI_WIN95_COMPATIBILITY)
  1930.   /*
  1931.    * For completeness we should put in equivalent code for code pages
  1932.    * 949 (Korean hangul) and 950 (Big5 Traditional Chinese) here - but
  1933.    * doubt anyone wants Samba to behave differently from Win95 and WinNT
  1934.    * here. They both treat full width ascii characters as case senstive
  1935.    * filenames (ie. they don't do the work we do here).
  1936.    * JRA. 
  1937.    */
  1938.  
  1939.   if(lp_client_code_page() == KANJI_CODEPAGE)
  1940.   {
  1941.     /* Win95 treats full width ascii characters as case sensitive. */
  1942.     while (*s) 
  1943.     {
  1944.       if (is_shift_jis (*s))
  1945.         s += 2;
  1946.       else 
  1947.       {
  1948.         if (*s == c)
  1949.           count++;
  1950.         s++;
  1951.       }
  1952.     }
  1953.   }
  1954.   else
  1955. #endif /* KANJI_WIN95_COMPATIBILITY */
  1956.   {
  1957.     while (*s) 
  1958.     {
  1959.       if (*s == c)
  1960.         count++;
  1961.       s++;
  1962.     }
  1963.   }
  1964.   return(count);
  1965. }
  1966.  
  1967.  
  1968. /****************************************************************************
  1969.   make a dir struct
  1970. ****************************************************************************/
  1971. void make_dir_struct(char *buf,char *mask,char *fname,unsigned int size,int mode,time_t date)
  1972. {  
  1973.   char *p;
  1974.   pstring mask2;
  1975.  
  1976.   pstrcpy(mask2,mask);
  1977.  
  1978.   if ((mode & aDIR) != 0)
  1979.     size = 0;
  1980.  
  1981.   memset(buf+1,' ',11);
  1982.   if ((p = strchr(mask2,'.')) != NULL)
  1983.     {
  1984.       *p = 0;
  1985.       memcpy(buf+1,mask2,MIN(strlen(mask2),8));
  1986.       memcpy(buf+9,p+1,MIN(strlen(p+1),3));
  1987.       *p = '.';
  1988.     }
  1989.   else
  1990.     memcpy(buf+1,mask2,MIN(strlen(mask2),11));
  1991.  
  1992.   bzero(buf+21,DIR_STRUCT_SIZE-21);
  1993.   CVAL(buf,21) = mode;
  1994.   put_dos_date(buf,22,date);
  1995.   SSVAL(buf,26,size & 0xFFFF);
  1996.   SSVAL(buf,28,size >> 16);
  1997.   StrnCpy(buf+30,fname,12);
  1998.   if (!case_sensitive)
  1999.     strupper(buf+30);
  2000.   DEBUG(8,("put name [%s] into dir struct\n",buf+30));
  2001. }
  2002.  
  2003.  
  2004. /*******************************************************************
  2005. close the low 3 fd's and open dev/null in their place
  2006. ********************************************************************/
  2007. void close_low_fds(void)
  2008. {
  2009.   int fd;
  2010.   int i;
  2011.   close(0); close(1); close(2);
  2012.   /* try and use up these file descriptors, so silly
  2013.      library routines writing to stdout etc won't cause havoc */
  2014.   for (i=0;i<3;i++) {
  2015.     fd = open("/dev/null",O_RDWR,0);
  2016.     if (fd < 0) fd = open("/dev/null",O_WRONLY,0);
  2017.     if (fd < 0) {
  2018.       DEBUG(0,("Can't open /dev/null\n"));
  2019.       return;
  2020.     }
  2021.     if (fd != i) {
  2022.       DEBUG(0,("Didn't get file descriptor %d\n",i));
  2023.       return;
  2024.     }
  2025.   }
  2026. }
  2027.  
  2028. /****************************************************************************
  2029. Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
  2030. else
  2031. if SYSV use O_NDELAY
  2032. if BSD use FNDELAY
  2033. ****************************************************************************/
  2034. int set_blocking(int fd, BOOL set)
  2035. {
  2036.   int val;
  2037. #ifdef O_NONBLOCK
  2038. #define FLAG_TO_SET O_NONBLOCK
  2039. #else
  2040. #ifdef SYSV
  2041. #define FLAG_TO_SET O_NDELAY
  2042. #else /* BSD */
  2043. #define FLAG_TO_SET FNDELAY
  2044. #endif
  2045. #endif
  2046.  
  2047.   if((val = fcntl(fd, F_GETFL, 0)) == -1)
  2048.     return -1;
  2049.   if(set) /* Turn blocking on - ie. clear nonblock flag */
  2050.     val &= ~FLAG_TO_SET;
  2051.   else
  2052.     val |= FLAG_TO_SET;
  2053.   return fcntl( fd, F_SETFL, val);
  2054. #undef FLAG_TO_SET
  2055. }
  2056.  
  2057.  
  2058. /****************************************************************************
  2059. write to a socket
  2060. ****************************************************************************/
  2061. int write_socket(int fd,char *buf,int len)
  2062. {
  2063.   int ret=0;
  2064.  
  2065.   if (passive)
  2066.     return(len);
  2067.   DEBUG(6,("write_socket(%d,%d)\n",fd,len));
  2068.   ret = write_data(fd,buf,len);
  2069.       
  2070.   DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,len,ret));
  2071.   if(ret <= 0)
  2072.     DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n", 
  2073.        len, fd, strerror(errno) ));
  2074.  
  2075.   return(ret);
  2076. }
  2077.  
  2078. /****************************************************************************
  2079. read from a socket
  2080. ****************************************************************************/
  2081. int read_udp_socket(int fd,char *buf,int len)
  2082. {
  2083.   int ret;
  2084.   struct sockaddr_in sock;
  2085.   int socklen;
  2086.   
  2087.   socklen = sizeof(sock);
  2088.   bzero((char *)&sock,socklen);
  2089.   bzero((char *)&lastip,sizeof(lastip));
  2090.   ret = recvfrom(fd,buf,len,0,(struct sockaddr *)&sock,&socklen);
  2091.   if (ret <= 0) {
  2092.     DEBUG(2,("read socket failed. ERRNO=%s\n",strerror(errno)));
  2093.     return(0);
  2094.   }
  2095.  
  2096.   lastip = sock.sin_addr;
  2097.   lastport = ntohs(sock.sin_port);
  2098.  
  2099.   DEBUG(10,("read_udp_socket: lastip %s lastport %d read: %d\n",
  2100.              inet_ntoa(lastip), lastport, ret));
  2101.  
  2102.   return(ret);
  2103. }
  2104.  
  2105. /****************************************************************************
  2106. read data from a device with a timout in msec.
  2107. mincount = if timeout, minimum to read before returning
  2108. maxcount = number to be read.
  2109. ****************************************************************************/
  2110. int read_with_timeout(int fd,char *buf,int mincnt,int maxcnt,long time_out)
  2111. {
  2112.   fd_set fds;
  2113.   int selrtn;
  2114.   int readret;
  2115.   int nread = 0;
  2116.   struct timeval timeout;
  2117.  
  2118.   /* just checking .... */
  2119.   if (maxcnt <= 0) return(0);
  2120.  
  2121.   smb_read_error = 0;
  2122.  
  2123.   /* Blocking read */
  2124.   if (time_out <= 0) {
  2125.     if (mincnt == 0) mincnt = maxcnt;
  2126.  
  2127.     while (nread < mincnt) {
  2128.       readret = read(fd, buf + nread, maxcnt - nread);
  2129.       if (readret == 0) {
  2130.     smb_read_error = READ_EOF;
  2131.     return -1;
  2132.       }
  2133.  
  2134.       if (readret == -1) {
  2135.     smb_read_error = READ_ERROR;
  2136.     return -1;
  2137.       }
  2138.       nread += readret;
  2139.     }
  2140.     return(nread);
  2141.   }
  2142.   
  2143.   /* Most difficult - timeout read */
  2144.   /* If this is ever called on a disk file and 
  2145.      mincnt is greater then the filesize then
  2146.      system performance will suffer severely as 
  2147.      select always return true on disk files */
  2148.  
  2149.   /* Set initial timeout */
  2150.   timeout.tv_sec = time_out / 1000;
  2151.   timeout.tv_usec = 1000 * (time_out % 1000);
  2152.  
  2153.   for (nread=0; nread<mincnt; ) 
  2154.     {      
  2155.       FD_ZERO(&fds);
  2156.       FD_SET(fd,&fds);
  2157.       
  2158.       selrtn = sys_select(&fds,&timeout);
  2159.  
  2160.       /* Check if error */
  2161.       if(selrtn == -1) {
  2162.     /* something is wrong. Maybe the socket is dead? */
  2163.     smb_read_error = READ_ERROR;
  2164.     return -1;
  2165.       }
  2166.       
  2167.       /* Did we timeout ? */
  2168.       if (selrtn == 0) {
  2169.     smb_read_error = READ_TIMEOUT;
  2170.     return -1;
  2171.       }
  2172.       
  2173.       readret = read(fd, buf+nread, maxcnt-nread);
  2174.       if (readret == 0) {
  2175.     /* we got EOF on the file descriptor */
  2176.     smb_read_error = READ_EOF;
  2177.     return -1;
  2178.       }
  2179.  
  2180.       if (readret == -1) {
  2181.     /* the descriptor is probably dead */
  2182.     smb_read_error = READ_ERROR;
  2183.     return -1;
  2184.       }
  2185.       
  2186.       nread += readret;
  2187.     }
  2188.  
  2189.   /* Return the number we got */
  2190.   return(nread);
  2191. }
  2192.  
  2193. /****************************************************************************
  2194. read data from the client. Maxtime is in milliseconds
  2195. ****************************************************************************/
  2196. int read_max_udp(int fd,char *buffer,int bufsize,int maxtime)
  2197. {
  2198.   fd_set fds;
  2199.   int selrtn;
  2200.   int nread;
  2201.   struct timeval timeout;
  2202.  
  2203.   FD_ZERO(&fds);
  2204.   FD_SET(fd,&fds);
  2205.  
  2206.   timeout.tv_sec = maxtime / 1000;
  2207.   timeout.tv_usec = (maxtime % 1000) * 1000;
  2208.  
  2209.   selrtn = sys_select(&fds,maxtime>0?&timeout:NULL);
  2210.  
  2211.   if (!FD_ISSET(fd,&fds))
  2212.     return 0;
  2213.  
  2214.   nread = read_udp_socket(fd, buffer, bufsize);
  2215.  
  2216.   /* return the number got */
  2217.   return(nread);
  2218. }
  2219.  
  2220. /*******************************************************************
  2221. find the difference in milliseconds between two struct timeval
  2222. values
  2223. ********************************************************************/
  2224. int TvalDiff(struct timeval *tvalold,struct timeval *tvalnew)
  2225. {
  2226.   return((tvalnew->tv_sec - tvalold->tv_sec)*1000 + 
  2227.      ((int)tvalnew->tv_usec - (int)tvalold->tv_usec)/1000);     
  2228. }
  2229.  
  2230. /****************************************************************************
  2231. send a keepalive packet (rfc1002)
  2232. ****************************************************************************/
  2233. BOOL send_keepalive(int client)
  2234. {
  2235.   unsigned char buf[4];
  2236.  
  2237.   buf[0] = 0x85;
  2238.   buf[1] = buf[2] = buf[3] = 0;
  2239.  
  2240.   return(write_data(client,(char *)buf,4) == 4);
  2241. }
  2242.  
  2243.  
  2244.  
  2245. /****************************************************************************
  2246.   read data from the client, reading exactly N bytes. 
  2247. ****************************************************************************/
  2248. int read_data(int fd,char *buffer,int N)
  2249. {
  2250.   int  ret;
  2251.   int total=0;  
  2252.  
  2253.   smb_read_error = 0;
  2254.  
  2255.   while (total < N)
  2256.     {
  2257.       ret = read(fd,buffer + total,N - total);
  2258.       if (ret == 0) {
  2259.     smb_read_error = READ_EOF;
  2260.     return 0;
  2261.       }
  2262.       if (ret == -1) {
  2263.     smb_read_error = READ_ERROR;
  2264.     return -1;
  2265.       }
  2266.       total += ret;
  2267.     }
  2268.   return total;
  2269. }
  2270.  
  2271.  
  2272. /****************************************************************************
  2273.   write data to a fd 
  2274. ****************************************************************************/
  2275. int write_data(int fd,char *buffer,int N)
  2276. {
  2277.   int total=0;
  2278.   int ret;
  2279.  
  2280.   while (total < N)
  2281.     {
  2282.       ret = write(fd,buffer + total,N - total);
  2283.  
  2284.       if (ret == -1) return -1;
  2285.       if (ret == 0) return total;
  2286.  
  2287.       total += ret;
  2288.     }
  2289.   return total;
  2290. }
  2291.  
  2292.  
  2293. /****************************************************************************
  2294. transfer some data between two fd's
  2295. ****************************************************************************/
  2296. int transfer_file(int infd,int outfd,int n,char *header,int headlen,int align)
  2297. {
  2298.   static char *buf=NULL;  
  2299.   static int size=0;
  2300.   char *buf1,*abuf;
  2301.   int total = 0;
  2302.  
  2303.   DEBUG(4,("transfer_file %d  (head=%d) called\n",n,headlen));
  2304.  
  2305.   if (size == 0) {
  2306.     size = lp_readsize();
  2307.     size = MAX(size,1024);
  2308.   }
  2309.  
  2310.   while (!buf && size>0) {
  2311.     buf = (char *)Realloc(buf,size+8);
  2312.     if (!buf) size /= 2;
  2313.   }
  2314.  
  2315.   if (!buf) {
  2316.     DEBUG(0,("Can't allocate transfer buffer!\n"));
  2317.     exit(1);
  2318.   }
  2319.  
  2320.   abuf = buf + (align%8);
  2321.  
  2322.   if (header)
  2323.     n += headlen;
  2324.  
  2325.   while (n > 0)
  2326.     {
  2327.       int s = MIN(n,size);
  2328.       int ret,ret2=0;
  2329.  
  2330.       ret = 0;
  2331.  
  2332.       if (header && (headlen >= MIN(s,1024))) {
  2333.     buf1 = header;
  2334.     s = headlen;
  2335.     ret = headlen;
  2336.     headlen = 0;
  2337.     header = NULL;
  2338.       } else {
  2339.     buf1 = abuf;
  2340.       }
  2341.  
  2342.       if (header && headlen > 0)
  2343.     {
  2344.       ret = MIN(headlen,size);
  2345.       memcpy(buf1,header,ret);
  2346.       headlen -= ret;
  2347.       header += ret;
  2348.       if (headlen <= 0) header = NULL;
  2349.     }
  2350.  
  2351.       if (s > ret)
  2352.     ret += read(infd,buf1+ret,s-ret);
  2353.  
  2354.       if (ret > 0)
  2355.     {
  2356.       ret2 = (outfd>=0?write_data(outfd,buf1,ret):ret);
  2357.       if (ret2 > 0) total += ret2;
  2358.       /* if we can't write then dump excess data */
  2359.       if (ret2 != ret)
  2360.         transfer_file(infd,-1,n-(ret+headlen),NULL,0,0);
  2361.     }
  2362.       if (ret <= 0 || ret2 != ret)
  2363.     return(total);
  2364.       n -= ret;
  2365.     }
  2366.   return(total);
  2367. }
  2368.  
  2369.  
  2370. /****************************************************************************
  2371. read 4 bytes of a smb packet and return the smb length of the packet
  2372. store the result in the buffer
  2373. This version of the function will return a length of zero on receiving
  2374. a keepalive packet.
  2375. ****************************************************************************/
  2376. static int read_smb_length_return_keepalive(int fd,char *inbuf,int timeout)
  2377. {
  2378.   int len=0, msg_type;
  2379.   BOOL ok=False;
  2380.  
  2381.   while (!ok)
  2382.     {
  2383.       if (timeout > 0)
  2384.     ok = (read_with_timeout(fd,inbuf,4,4,timeout) == 4);
  2385.       else 
  2386.     ok = (read_data(fd,inbuf,4) == 4);
  2387.  
  2388.       if (!ok)
  2389.     return(-1);
  2390.  
  2391.       len = smb_len(inbuf);
  2392.       msg_type = CVAL(inbuf,0);
  2393.  
  2394.       if (msg_type == 0x85) 
  2395.         DEBUG(5,("Got keepalive packet\n"));
  2396.     }
  2397.  
  2398.   DEBUG(10,("got smb length of %d\n",len));
  2399.  
  2400.   return(len);
  2401. }
  2402.  
  2403. /****************************************************************************
  2404. read 4 bytes of a smb packet and return the smb length of the packet
  2405. store the result in the buffer. This version of the function will
  2406. never return a session keepalive (length of zero).
  2407. ****************************************************************************/
  2408. int read_smb_length(int fd,char *inbuf,int timeout)
  2409. {
  2410.   int len;
  2411.  
  2412.   for(;;)
  2413.   {
  2414.     len = read_smb_length_return_keepalive(fd, inbuf, timeout);
  2415.  
  2416.     if(len < 0)
  2417.       return len;
  2418.  
  2419.     /* Ignore session keepalives. */
  2420.     if(CVAL(inbuf,0) != 0x85)
  2421.       break;
  2422.   }
  2423.  
  2424.   return len;
  2425. }
  2426.  
  2427. /****************************************************************************
  2428.   read an smb from a fd. Note that the buffer *MUST* be of size
  2429.   BUFFER_SIZE+SAFETY_MARGIN.
  2430.   The timeout is in milli seconds. 
  2431.  
  2432.   This function will return on a
  2433.   receipt of a session keepalive packet.
  2434. ****************************************************************************/
  2435. BOOL receive_smb(int fd,char *buffer, int timeout)
  2436. {
  2437.   int len,ret;
  2438.  
  2439.   smb_read_error = 0;
  2440.  
  2441.   bzero(buffer,smb_size + 100);
  2442.  
  2443.   len = read_smb_length_return_keepalive(fd,buffer,timeout);
  2444.   if (len < 0)
  2445.     return(False);
  2446.  
  2447.   if (len > BUFFER_SIZE) {
  2448.     DEBUG(0,("Invalid packet length! (%d bytes).\n",len));
  2449.     if (len > BUFFER_SIZE + (SAFETY_MARGIN/2))
  2450.       exit(1);
  2451.   }
  2452.  
  2453.   if(len > 0) {
  2454.     ret = read_data(fd,buffer+4,len);
  2455.     if (ret != len) {
  2456.       smb_read_error = READ_ERROR;
  2457.       return False;
  2458.     }
  2459.   }
  2460.   return(True);
  2461. }
  2462.  
  2463. /****************************************************************************
  2464.   read an smb from a fd ignoring all keepalive packets. Note that the buffer 
  2465.   *MUST* be of size BUFFER_SIZE+SAFETY_MARGIN.
  2466.   The timeout is in milli seconds
  2467.  
  2468.   This is exactly the same as receive_smb except that it never returns
  2469.   a session keepalive packet (just as receive_smb used to do).
  2470.   receive_smb was changed to return keepalives as the oplock processing means this call
  2471.   should never go into a blocking read.
  2472. ****************************************************************************/
  2473.  
  2474. BOOL client_receive_smb(int fd,char *buffer, int timeout)
  2475. {
  2476.   BOOL ret;
  2477.  
  2478.   for(;;)
  2479.   {
  2480.     ret = receive_smb(fd, buffer, timeout);
  2481.  
  2482.     if(ret == False)
  2483.       return ret;
  2484.  
  2485.     /* Ignore session keepalive packets. */
  2486.     if(CVAL(buffer,0) != 0x85)
  2487.       break;
  2488.   }
  2489.   return ret;
  2490. }
  2491.  
  2492. /****************************************************************************
  2493.   read a message from a udp fd.
  2494. The timeout is in milli seconds
  2495. ****************************************************************************/
  2496. BOOL receive_local_message(int fd, char *buffer, int buffer_len, int timeout)
  2497. {
  2498.   struct sockaddr_in from;
  2499.   int fromlen = sizeof(from);
  2500.   int32 msg_len = 0;
  2501.  
  2502.   smb_read_error = 0;
  2503.  
  2504.   if(timeout != 0)
  2505.   {
  2506.     struct timeval to;
  2507.     fd_set fds;
  2508.     int selrtn;
  2509.  
  2510.     FD_ZERO(&fds);
  2511.     FD_SET(fd,&fds);
  2512.  
  2513.     to.tv_sec = timeout / 1000;
  2514.     to.tv_usec = (timeout % 1000) * 1000;
  2515.  
  2516.     selrtn = sys_select(&fds,&to);
  2517.  
  2518.     /* Check if error */
  2519.     if(selrtn == -1) 
  2520.     {
  2521.       /* something is wrong. Maybe the socket is dead? */
  2522.       smb_read_error = READ_ERROR;
  2523.       return False;
  2524.     } 
  2525.     
  2526.     /* Did we timeout ? */
  2527.     if (selrtn == 0) 
  2528.     {
  2529.       smb_read_error = READ_TIMEOUT;
  2530.       return False;
  2531.     }
  2532.   }
  2533.  
  2534.   /*
  2535.    * Read a loopback udp message.
  2536.    */
  2537.   msg_len = recvfrom(fd, &buffer[UDP_CMD_HEADER_LEN], 
  2538.                      buffer_len - UDP_CMD_HEADER_LEN, 0,
  2539.                      (struct sockaddr *)&from, &fromlen);
  2540.  
  2541.   if(msg_len < 0)
  2542.   {
  2543.     DEBUG(0,("receive_local_message. Error in recvfrom. (%s).\n",strerror(errno)));
  2544.     return False;
  2545.   }
  2546.  
  2547.   /* Validate message length. */
  2548.   if(msg_len > (buffer_len - UDP_CMD_HEADER_LEN))
  2549.   {
  2550.     DEBUG(0,("receive_local_message: invalid msg_len (%d) max can be %d\n",
  2551.               msg_len, 
  2552.               buffer_len  - UDP_CMD_HEADER_LEN));
  2553.     return False;
  2554.   }
  2555.  
  2556.   /* Validate message from address (must be localhost). */
  2557.   if(from.sin_addr.s_addr != htonl(INADDR_LOOPBACK))
  2558.   {
  2559.     DEBUG(0,("receive_local_message: invalid 'from' address \
  2560. (was %x should be 127.0.0.1\n", from.sin_addr.s_addr));
  2561.    return False;
  2562.   }
  2563.  
  2564.   /* Setup the message header */
  2565.   SIVAL(buffer,UDP_CMD_LEN_OFFSET,msg_len);
  2566.   SSVAL(buffer,UDP_CMD_PORT_OFFSET,ntohs(from.sin_port));
  2567.  
  2568.   return True;
  2569. }
  2570.  
  2571. /****************************************************************************
  2572.  structure to hold a linked list of local messages.
  2573.  for processing.
  2574. ****************************************************************************/
  2575.  
  2576. typedef struct _message_list {
  2577.    struct _message_list *msg_next;
  2578.    char *msg_buf;
  2579.    int msg_len;
  2580. } pending_message_list;
  2581.  
  2582. static pending_message_list *smb_msg_head = NULL;
  2583.  
  2584. /****************************************************************************
  2585.  Function to push a linked list of local messages ready
  2586.  for processing.
  2587. ****************************************************************************/
  2588.  
  2589. static BOOL push_local_message(pending_message_list **pml, char *buf, int msg_len)
  2590. {
  2591.   pending_message_list *msg = (pending_message_list *)
  2592.                                malloc(sizeof(pending_message_list));
  2593.  
  2594.   if(msg == NULL)
  2595.   {
  2596.     DEBUG(0,("push_message: malloc fail (1)\n"));
  2597.     return False;
  2598.   }
  2599.  
  2600.   msg->msg_buf = (char *)malloc(msg_len);
  2601.   if(msg->msg_buf == NULL)
  2602.   {
  2603.     DEBUG(0,("push_local_message: malloc fail (2)\n"));
  2604.     free((char *)msg);
  2605.     return False;
  2606.   }
  2607.  
  2608.   memcpy(msg->msg_buf, buf, msg_len);
  2609.   msg->msg_len = msg_len;
  2610.  
  2611.   msg->msg_next = *pml;
  2612.   *pml = msg;
  2613.  
  2614.   return True;
  2615. }
  2616.  
  2617. /****************************************************************************
  2618.  Function to push a linked list of local smb messages ready
  2619.  for processing.
  2620. ****************************************************************************/
  2621.  
  2622. BOOL push_smb_message(char *buf, int msg_len)
  2623. {
  2624.   return push_local_message(&smb_msg_head, buf, msg_len);
  2625. }
  2626.  
  2627. /****************************************************************************
  2628.   Do a select on an two fd's - with timeout. 
  2629.  
  2630.   If a local udp message has been pushed onto the
  2631.   queue (this can only happen during oplock break
  2632.   processing) return this first.
  2633.  
  2634.   If a pending smb message has been pushed onto the
  2635.   queue (this can only happen during oplock break
  2636.   processing) return this next.
  2637.  
  2638.   If the first smbfd is ready then read an smb from it.
  2639.   if the second (loopback UDP) fd is ready then read a message
  2640.   from it and setup the buffer header to identify the length
  2641.   and from address.
  2642.   Returns False on timeout or error.
  2643.   Else returns True.
  2644.  
  2645. The timeout is in milli seconds
  2646. ****************************************************************************/
  2647. BOOL receive_message_or_smb(int smbfd, int oplock_fd, 
  2648.                            char *buffer, int buffer_len, 
  2649.                            int timeout, BOOL *got_smb)
  2650. {
  2651.   fd_set fds;
  2652.   int selrtn;
  2653.   struct timeval to;
  2654.  
  2655.   smb_read_error = 0;
  2656.  
  2657.   *got_smb = False;
  2658.  
  2659.   /*
  2660.    * Check to see if we already have a message on the smb queue.
  2661.    * If so - copy and return it.
  2662.    */
  2663.   
  2664.   if(smb_msg_head)
  2665.   {
  2666.     pending_message_list *msg = smb_msg_head;
  2667.     memcpy(buffer, msg->msg_buf, MIN(buffer_len, msg->msg_len));
  2668.     smb_msg_head = msg->msg_next;
  2669.   
  2670.     /* Free the message we just copied. */
  2671.     free((char *)msg->msg_buf);
  2672.     free((char *)msg);
  2673.     *got_smb = True;
  2674.  
  2675.     DEBUG(5,("receive_message_or_smb: returning queued smb message.\n"));
  2676.     return True;
  2677.   }
  2678.  
  2679.   FD_ZERO(&fds);
  2680.   FD_SET(smbfd,&fds);
  2681.   FD_SET(oplock_fd,&fds);
  2682.  
  2683.   to.tv_sec = timeout / 1000;
  2684.   to.tv_usec = (timeout % 1000) * 1000;
  2685.  
  2686.   selrtn = sys_select(&fds,timeout>0?&to:NULL);
  2687.  
  2688.   /* Check if error */
  2689.   if(selrtn == -1) {
  2690.     /* something is wrong. Maybe the socket is dead? */
  2691.     smb_read_error = READ_ERROR;
  2692.     return False;
  2693.   } 
  2694.     
  2695.   /* Did we timeout ? */
  2696.   if (selrtn == 0) {
  2697.     smb_read_error = READ_TIMEOUT;
  2698.     return False;
  2699.   }
  2700.  
  2701.   if (FD_ISSET(smbfd,&fds))
  2702.   {
  2703.     *got_smb = True;
  2704.     return receive_smb(smbfd, buffer, 0);
  2705.   }
  2706.   else
  2707.   {
  2708.     return receive_local_message(oplock_fd, buffer, buffer_len, 0);
  2709.   }
  2710. }
  2711.  
  2712. /****************************************************************************
  2713.   send an smb to a fd 
  2714. ****************************************************************************/
  2715. BOOL send_smb(int fd,char *buffer)
  2716. {
  2717.   int len;
  2718.   int ret,nwritten=0;
  2719.   len = smb_len(buffer) + 4;
  2720.  
  2721.   while (nwritten < len)
  2722.     {
  2723.       ret = write_socket(fd,buffer+nwritten,len - nwritten);
  2724.       if (ret <= 0)
  2725.     {
  2726.       DEBUG(0,("Error writing %d bytes to client. %d. Exiting\n",len,ret));
  2727.           close_sockets();
  2728.       exit(1);
  2729.     }
  2730.       nwritten += ret;
  2731.     }
  2732.  
  2733.  
  2734.   return True;
  2735. }
  2736.  
  2737.  
  2738. /****************************************************************************
  2739. find a pointer to a netbios name
  2740. ****************************************************************************/
  2741. char *name_ptr(char *buf,int ofs)
  2742. {
  2743.   unsigned char c = *(unsigned char *)(buf+ofs);
  2744.  
  2745.   if ((c & 0xC0) == 0xC0)
  2746.     {
  2747.       uint16 l;
  2748.       char p[2];
  2749.       memcpy(p,buf+ofs,2);
  2750.       p[0] &= ~0xC0;
  2751.       l = RSVAL(p,0);
  2752.       DEBUG(5,("name ptr to pos %d from %d is %s\n",l,ofs,buf+l));
  2753.       return(buf + l);
  2754.     }
  2755.   else
  2756.     return(buf+ofs);
  2757. }  
  2758.  
  2759. /****************************************************************************
  2760. extract a netbios name from a buf
  2761. ****************************************************************************/
  2762. int name_extract(char *buf,int ofs,char *name)
  2763. {
  2764.   char *p = name_ptr(buf,ofs);
  2765.   int d = PTR_DIFF(p,buf+ofs);
  2766.   pstrcpy(name,"");
  2767.   if (d < -50 || d > 50) return(0);
  2768.   return(name_interpret(p,name));
  2769. }
  2770.   
  2771. /****************************************************************************
  2772. return the total storage length of a mangled name
  2773. ****************************************************************************/
  2774. int name_len( char *s )
  2775.   {
  2776.   int len;
  2777.  
  2778.   /* If the two high bits of the byte are set, return 2. */
  2779.   if( 0xC0 == (*(unsigned char *)s & 0xC0) )
  2780.     return(2);
  2781.  
  2782.   /* Add up the length bytes. */
  2783.   for( len = 1; (*s); s += (*s) + 1 )
  2784.     {
  2785.     len += *s + 1;
  2786.     }
  2787.  
  2788.   return( len );
  2789.   } /* name_len */
  2790.  
  2791. /****************************************************************************
  2792. send a single packet to a port on another machine
  2793. ****************************************************************************/
  2794. BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
  2795. {
  2796.   BOOL ret;
  2797.   int out_fd;
  2798.   struct sockaddr_in sock_out;
  2799.  
  2800.   if (passive)
  2801.     return(True);
  2802.  
  2803.   /* create a socket to write to */
  2804.   out_fd = socket(AF_INET, type, 0);
  2805.   if (out_fd == -1) 
  2806.     {
  2807.       DEBUG(0,("socket failed"));
  2808.       return False;
  2809.     }
  2810.  
  2811.   /* set the address and port */
  2812.   bzero((char *)&sock_out,sizeof(sock_out));
  2813.   putip((char *)&sock_out.sin_addr,(char *)&ip);
  2814.   sock_out.sin_port = htons( port );
  2815.   sock_out.sin_family = AF_INET;
  2816.   
  2817.   if (DEBUGLEVEL > 0)
  2818.     DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
  2819.          len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));
  2820.     
  2821.   /* send it */
  2822.   ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);
  2823.  
  2824.   if (!ret)
  2825.     DEBUG(0,("Packet send to %s(%d) failed ERRNO=%s\n",
  2826.          inet_ntoa(ip),port,strerror(errno)));
  2827.  
  2828.   close(out_fd);
  2829.   return(ret);
  2830. }
  2831.  
  2832. /*******************************************************************
  2833. sleep for a specified number of milliseconds
  2834. ********************************************************************/
  2835. void msleep(int t)
  2836. {
  2837.   int tdiff=0;
  2838.   struct timeval tval,t1,t2;  
  2839.   fd_set fds;
  2840.  
  2841.   GetTimeOfDay(&t1);
  2842.   GetTimeOfDay(&t2);
  2843.   
  2844.   while (tdiff < t) {
  2845.     tval.tv_sec = (t-tdiff)/1000;
  2846.     tval.tv_usec = 1000*((t-tdiff)%1000);
  2847.  
  2848.     FD_ZERO(&fds);
  2849.     errno = 0;
  2850.     sys_select(&fds,&tval);
  2851.  
  2852.     GetTimeOfDay(&t2);
  2853.     tdiff = TvalDiff(&t1,&t2);
  2854.   }
  2855. }
  2856.  
  2857. /****************************************************************************
  2858. check if a string is part of a list
  2859. ****************************************************************************/
  2860. BOOL in_list(char *s,char *list,BOOL casesensitive)
  2861. {
  2862.   pstring tok;
  2863.   char *p=list;
  2864.  
  2865.   if (!list) return(False);
  2866.  
  2867.   while (next_token(&p,tok,LIST_SEP))
  2868.     {
  2869.       if (casesensitive) {
  2870.     if (strcmp(tok,s) == 0)
  2871.       return(True);
  2872.       } else {
  2873.     if (StrCaseCmp(tok,s) == 0)
  2874.       return(True);
  2875.       }
  2876.     }
  2877.   return(False);
  2878. }
  2879.  
  2880. /* this is used to prevent lots of mallocs of size 1 */
  2881. static char *null_string = NULL;
  2882.  
  2883. /****************************************************************************
  2884. set a string value, allocing the space for the string
  2885. ****************************************************************************/
  2886. BOOL string_init(char **dest,char *src)
  2887. {
  2888.   int l;
  2889.   if (!src)     
  2890.     src = "";
  2891.  
  2892.   l = strlen(src);
  2893.  
  2894.   if (l == 0)
  2895.     {
  2896.       if (!null_string)
  2897.     null_string = (char *)malloc(1);
  2898.  
  2899.       *null_string = 0;
  2900.       *dest = null_string;
  2901.     }
  2902.   else
  2903.     {
  2904.       (*dest) = (char *)malloc(l+1);
  2905.       if ((*dest) == NULL) {
  2906.           DEBUG(0,("Out of memory in string_init\n"));
  2907.           return False;
  2908.       }
  2909.  
  2910.       pstrcpy(*dest,src);
  2911.     }
  2912.   return(True);
  2913. }
  2914.  
  2915. /****************************************************************************
  2916. free a string value
  2917. ****************************************************************************/
  2918. void string_free(char **s)
  2919. {
  2920.   if (!s || !(*s)) return;
  2921.   if (*s == null_string)
  2922.     *s = NULL;
  2923.   if (*s) free(*s);
  2924.   *s = NULL;
  2925. }
  2926.  
  2927. /****************************************************************************
  2928. set a string value, allocing the space for the string, and deallocating any 
  2929. existing space
  2930. ****************************************************************************/
  2931. BOOL string_set(char **dest,char *src)
  2932. {
  2933.   string_free(dest);
  2934.  
  2935.   return(string_init(dest,src));
  2936. }
  2937.  
  2938. /****************************************************************************
  2939. substitute a string for a pattern in another string. Make sure there is 
  2940. enough room!
  2941.  
  2942. This routine looks for pattern in s and replaces it with 
  2943. insert. It may do multiple replacements.
  2944.  
  2945. return True if a substitution was done.
  2946. ****************************************************************************/
  2947. BOOL string_sub(char *s,char *pattern,char *insert)
  2948. {
  2949.   BOOL ret = False;
  2950.   char *p;
  2951.   int ls,lp,li;
  2952.  
  2953.   if (!insert || !pattern || !s) return(False);
  2954.  
  2955.   ls = strlen(s);
  2956.   lp = strlen(pattern);
  2957.   li = strlen(insert);
  2958.  
  2959.   if (!*pattern) return(False);
  2960.  
  2961.   while (lp <= ls && (p = strstr(s,pattern)))
  2962.     {
  2963.       ret = True;
  2964.       memmove(p+li,p+lp,ls + 1 - (PTR_DIFF(p,s) + lp));
  2965.       memcpy(p,insert,li);
  2966.       s = p + li;
  2967.       ls = strlen(s);
  2968.     }
  2969.   return(ret);
  2970. }
  2971.  
  2972.  
  2973.  
  2974. /*********************************************************
  2975. * Recursive routine that is called by mask_match.
  2976. * Does the actual matching.
  2977. *********************************************************/
  2978. BOOL do_match(char *str, char *regexp, int case_sig)
  2979. {
  2980.   char *p;
  2981.  
  2982.   for( p = regexp; *p && *str; ) {
  2983.     switch(*p) {
  2984.     case '?':
  2985.       str++; p++;
  2986.       break;
  2987.  
  2988.     case '*':
  2989.       /* Look for a character matching 
  2990.      the one after the '*' */
  2991.       p++;
  2992.       if(!*p)
  2993.     return True; /* Automatic match */
  2994.       while(*str) {
  2995.     while(*str && (case_sig ? (*p != *str) : (toupper(*p)!=toupper(*str))))
  2996.       str++;
  2997.     if(do_match(str,p,case_sig))
  2998.       return True;
  2999.     if(!*str)
  3000.       return False;
  3001.     else
  3002.       str++;
  3003.       }
  3004.       return False;
  3005.  
  3006.     default:
  3007.       if(case_sig) {
  3008.     if(*str != *p)
  3009.       return False;
  3010.       } else {
  3011.     if(toupper(*str) != toupper(*p))
  3012.       return False;
  3013.       }
  3014.       str++, p++;
  3015.       break;
  3016.     }
  3017.   }
  3018.   if(!*p && !*str)
  3019.     return True;
  3020.  
  3021.   if (!*p && str[0] == '.' && str[1] == 0)
  3022.     return(True);
  3023.   
  3024.   if (!*str && *p == '?')
  3025.     {
  3026.       while (*p == '?') p++;
  3027.       return(!*p);
  3028.     }
  3029.  
  3030.   if(!*str && (*p == '*' && p[1] == '\0'))
  3031.     return True;
  3032.   return False;
  3033. }
  3034.  
  3035.  
  3036. /*********************************************************
  3037. * Routine to match a given string with a regexp - uses
  3038. * simplified regexp that takes * and ? only. Case can be
  3039. * significant or not.
  3040. *********************************************************/
  3041. BOOL mask_match(char *str, char *regexp, int case_sig,BOOL trans2)
  3042. {
  3043.   char *p;
  3044.   pstring p1, p2;
  3045.   fstring ebase,eext,sbase,sext;
  3046.  
  3047.   BOOL matched;
  3048.  
  3049.   /* Make local copies of str and regexp */
  3050.   StrnCpy(p1,regexp,sizeof(pstring)-1);
  3051.   StrnCpy(p2,str,sizeof(pstring)-1);
  3052.  
  3053.   if (!strchr(p2,'.')) {
  3054.     pstrcat(p2,".");
  3055.   }
  3056.  
  3057. /*
  3058.   if (!strchr(p1,'.')) {
  3059.     pstrcat(p1,".");
  3060.   }
  3061. */
  3062.  
  3063. #if 0
  3064.   if (strchr(p1,'.'))
  3065.     {
  3066.       string_sub(p1,"*.*","*");
  3067.       string_sub(p1,".*","*");
  3068.     }
  3069. #endif
  3070.  
  3071.   /* Remove any *? and ** as they are meaningless */
  3072.   for(p = p1; *p; p++)
  3073.     while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
  3074.       (void)pstrcpy( &p[1], &p[2]);
  3075.  
  3076.   if (strequal(p1,"*")) return(True);
  3077.  
  3078.   DEBUG(8,("mask_match str=<%s> regexp=<%s>, case_sig = %d\n", p2, p1, case_sig));
  3079.  
  3080.   if (trans2) {
  3081.     fstrcpy(ebase,p1);
  3082.     fstrcpy(sbase,p2);
  3083.   } else {
  3084.     if ((p=strrchr(p1,'.'))) {
  3085.       *p = 0;
  3086.       fstrcpy(ebase,p1);
  3087.       fstrcpy(eext,p+1);
  3088.     } else {
  3089.       fstrcpy(ebase,p1);
  3090.       eext[0] = 0;
  3091.     }
  3092.  
  3093.   if (!strequal(p2,".") && !strequal(p2,"..") && (p=strrchr(p2,'.'))) {
  3094.     *p = 0;
  3095.     fstrcpy(sbase,p2);
  3096.     fstrcpy(sext,p+1);
  3097.   } else {
  3098.     fstrcpy(sbase,p2);
  3099.     fstrcpy(sext,"");
  3100.   }
  3101.   }
  3102.  
  3103.   matched = do_match(sbase,ebase,case_sig) && 
  3104.     (trans2 || do_match(sext,eext,case_sig));
  3105.  
  3106.   DEBUG(8,("mask_match returning %d\n", matched));
  3107.  
  3108.   return matched;
  3109. }
  3110.  
  3111.  
  3112.  
  3113. /****************************************************************************
  3114. become a daemon, discarding the controlling terminal
  3115. ****************************************************************************/
  3116. void become_daemon(void)
  3117. {
  3118. #ifndef NO_FORK_DEBUG
  3119.   if (fork())
  3120.     exit(0);
  3121.  
  3122.   /* detach from the terminal */
  3123. #ifdef USE_SETSID
  3124.   setsid();
  3125. #else /* USE_SETSID */
  3126. #ifdef TIOCNOTTY
  3127.   {
  3128.     int i = open("/dev/tty", O_RDWR);
  3129.     if (i >= 0) 
  3130.       {
  3131.     ioctl(i, (int) TIOCNOTTY, (char *)0);      
  3132.     close(i);
  3133.       }
  3134.   }
  3135. #endif /* TIOCNOTTY */
  3136. #endif /* USE_SETSID */
  3137.   /* Close fd's 0,1,2. Needed if started by rsh */
  3138.   close_low_fds();
  3139. #endif /* NO_FORK_DEBUG */
  3140. }
  3141.  
  3142.  
  3143. /****************************************************************************
  3144. put up a yes/no prompt
  3145. ****************************************************************************/
  3146. BOOL yesno(char *p)
  3147. {
  3148.   pstring ans;
  3149.   printf("%s",p);
  3150.  
  3151.   if (!fgets(ans,sizeof(ans)-1,stdin))
  3152.     return(False);
  3153.  
  3154.   if (*ans == 'y' || *ans == 'Y')
  3155.     return(True);
  3156.  
  3157.   return(False);
  3158. }
  3159.  
  3160. /****************************************************************************
  3161. read a line from a file with possible \ continuation chars. 
  3162. Blanks at the start or end of a line are stripped.
  3163. The string will be allocated if s2 is NULL
  3164. ****************************************************************************/
  3165. char *fgets_slash(char *s2,int maxlen,FILE *f)
  3166. {
  3167.   char *s=s2;
  3168.   int len = 0;
  3169.   int c;
  3170.   BOOL start_of_line = True;
  3171.  
  3172.   if (feof(f))
  3173.     return(NULL);
  3174.  
  3175.   if (!s2)
  3176.     {
  3177.       maxlen = MIN(maxlen,8);
  3178.       s = (char *)Realloc(s,maxlen);
  3179.     }
  3180.  
  3181.   if (!s || maxlen < 2) return(NULL);
  3182.  
  3183.   *s = 0;
  3184.  
  3185.   while (len < maxlen-1)
  3186.     {
  3187.       c = getc(f);
  3188.       switch (c)
  3189.     {
  3190.     case '\r':
  3191.       break;
  3192.     case '\n':
  3193.       while (len > 0 && s[len-1] == ' ')
  3194.         {
  3195.           s[--len] = 0;
  3196.         }
  3197.       if (len > 0 && s[len-1] == '\\')
  3198.         {
  3199.           s[--len] = 0;
  3200.           start_of_line = True;
  3201.           break;
  3202.         }
  3203.       return(s);
  3204.     case EOF:
  3205.       if (len <= 0 && !s2) 
  3206.         free(s);
  3207.       return(len>0?s:NULL);
  3208.     case ' ':
  3209.       if (start_of_line)
  3210.         break;
  3211.     default:
  3212.       start_of_line = False;
  3213.       s[len++] = c;
  3214.       s[len] = 0;
  3215.     }
  3216.       if (!s2 && len > maxlen-3)
  3217.     {
  3218.       maxlen *= 2;
  3219.       s = (char *)Realloc(s,maxlen);
  3220.       if (!s) return(NULL);
  3221.     }
  3222.     }
  3223.   return(s);
  3224. }
  3225.  
  3226.  
  3227.  
  3228. /****************************************************************************
  3229. set the length of a file from a filedescriptor.
  3230. Returns 0 on success, -1 on failure.
  3231. ****************************************************************************/
  3232. int set_filelen(int fd, long len)
  3233. {
  3234. /* According to W. R. Stevens advanced UNIX prog. Pure 4.3 BSD cannot
  3235.    extend a file with ftruncate. Provide alternate implementation
  3236.    for this */
  3237.  
  3238. #if FTRUNCATE_CAN_EXTEND
  3239.   return ftruncate(fd, len);
  3240. #else
  3241.   struct stat st;
  3242.   char c = 0;
  3243.   long currpos = lseek(fd, 0L, SEEK_CUR);
  3244.  
  3245.   if(currpos < 0)
  3246.     return -1;
  3247.   /* Do an fstat to see if the file is longer than
  3248.      the requested size (call ftruncate),
  3249.      or shorter, in which case seek to len - 1 and write 1
  3250.      byte of zero */
  3251.   if(fstat(fd, &st)<0)
  3252.     return -1;
  3253.  
  3254. #ifdef S_ISFIFO
  3255.   if (S_ISFIFO(st.st_mode)) return 0;
  3256. #endif
  3257.  
  3258.   if(st.st_size == len)
  3259.     return 0;
  3260.   if(st.st_size > len)
  3261.     return ftruncate(fd, len);
  3262.  
  3263.   if(lseek(fd, len-1, SEEK_SET) != len -1)
  3264.     return -1;
  3265.   if(write(fd, &c, 1)!=1)
  3266.     return -1;
  3267.   /* Seek to where we were */
  3268.   lseek(fd, currpos, SEEK_SET);
  3269.   return 0;
  3270. #endif
  3271. }
  3272.  
  3273.  
  3274. /****************************************************************************
  3275. return the byte checksum of some data
  3276. ****************************************************************************/
  3277. int byte_checksum(char *buf,int len)
  3278. {
  3279.   unsigned char *p = (unsigned char *)buf;
  3280.   int ret = 0;
  3281.   while (len--)
  3282.     ret += *p++;
  3283.   return(ret);
  3284. }
  3285.  
  3286.  
  3287.  
  3288. #ifdef HPUX
  3289. /****************************************************************************
  3290. this is a version of setbuffer() for those machines that only have setvbuf
  3291. ****************************************************************************/
  3292.  void setbuffer(FILE *f,char *buf,int bufsize)
  3293. {
  3294.   setvbuf(f,buf,_IOFBF,bufsize);
  3295. }
  3296. #endif
  3297.  
  3298.  
  3299. /****************************************************************************
  3300. parse out a directory name from a path name. Assumes dos style filenames.
  3301. ****************************************************************************/
  3302. char *dirname_dos(char *path,char *buf)
  3303. {
  3304.   char *p = strrchr(path,'\\');
  3305.  
  3306.   if (!p)
  3307.     pstrcpy(buf,path);
  3308.   else
  3309.     {
  3310.       *p = 0;
  3311.       pstrcpy(buf,path);
  3312.       *p = '\\';
  3313.     }
  3314.  
  3315.   return(buf);
  3316. }
  3317.  
  3318.  
  3319. /****************************************************************************
  3320. parse out a filename from a path name. Assumes dos style filenames.
  3321. ****************************************************************************/
  3322. static char *filename_dos(char *path,char *buf)
  3323. {
  3324.   char *p = strrchr(path,'\\');
  3325.  
  3326.   if (!p)
  3327.     pstrcpy(buf,path);
  3328.   else
  3329.     pstrcpy(buf,p+1);
  3330.  
  3331.   return(buf);
  3332. }
  3333.  
  3334.  
  3335.  
  3336. /****************************************************************************
  3337. expand a pointer to be a particular size
  3338. ****************************************************************************/
  3339. void *Realloc(void *p,int size)
  3340. {
  3341.   void *ret=NULL;
  3342.  
  3343.   if (size == 0) {
  3344.     if (p) free(p);
  3345.     DEBUG(5,("Realloc asked for 0 bytes\n"));
  3346.     return NULL;
  3347.   }
  3348.  
  3349.   if (!p)
  3350.     ret = (void *)malloc(size);
  3351.   else
  3352.     ret = (void *)realloc(p,size);
  3353.  
  3354.   if (!ret)
  3355.     DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",size));
  3356.  
  3357.   return(ret);
  3358. }
  3359.  
  3360. #ifdef NOSTRDUP
  3361. /****************************************************************************
  3362. duplicate a string
  3363. ****************************************************************************/
  3364.  char *strdup(char *s)
  3365. {
  3366.   char *ret = NULL;
  3367.   int len;
  3368.   if (!s) return(NULL);
  3369.   ret = (char *)malloc((len = strlen(s))+1);
  3370.   if (!ret) return(NULL);
  3371.   safe_strcpy(ret,s,len);
  3372.   return(ret);
  3373. }
  3374. #endif
  3375.  
  3376.  
  3377. /****************************************************************************
  3378.   Signal handler for SIGPIPE (write on a disconnected socket) 
  3379. ****************************************************************************/
  3380. void Abort(void )
  3381. {
  3382.   DEBUG(0,("Probably got SIGPIPE\nExiting\n"));
  3383.   exit(2);
  3384. }
  3385.  
  3386. /****************************************************************************
  3387. get my own name and IP
  3388. ****************************************************************************/
  3389. BOOL get_myname(char *my_name,struct in_addr *ip)
  3390. {
  3391.   struct hostent *hp;
  3392.   pstring hostname;
  3393.  
  3394.   *hostname = 0;
  3395.  
  3396.   /* get my host name */
  3397.   if (gethostname(hostname, MAXHOSTNAMELEN) == -1) 
  3398.     {
  3399.       DEBUG(0,("gethostname failed\n"));
  3400.       return False;
  3401.     } 
  3402.  
  3403.   /* get host info */
  3404.   if ((hp = Get_Hostbyname(hostname)) == 0) 
  3405.     {
  3406.       DEBUG(0,( "Get_Hostbyname: Unknown host %s.\n",hostname));
  3407.       return False;
  3408.     }
  3409.  
  3410.   if (my_name)
  3411.     {
  3412.       /* split off any parts after an initial . */
  3413.       char *p = strchr(hostname,'.');
  3414.       if (p) *p = 0;
  3415.  
  3416.       fstrcpy(my_name,hostname);
  3417.     }
  3418.  
  3419.   if (ip)
  3420.     putip((char *)ip,(char *)hp->h_addr);
  3421.  
  3422.   return(True);
  3423. }
  3424.  
  3425.  
  3426. /****************************************************************************
  3427. true if two IP addresses are equal
  3428. ****************************************************************************/
  3429. BOOL ip_equal(struct in_addr ip1,struct in_addr ip2)
  3430. {
  3431.   uint32 a1,a2;
  3432.   a1 = ntohl(ip1.s_addr);
  3433.   a2 = ntohl(ip2.s_addr);
  3434.   return(a1 == a2);
  3435. }
  3436.  
  3437.  
  3438. /****************************************************************************
  3439. open a socket of the specified type, port and address for incoming data
  3440. ****************************************************************************/
  3441. int open_socket_in(int type, int port, int dlevel,uint32 socket_addr)
  3442. {
  3443.   struct hostent *hp;
  3444.   struct sockaddr_in sock;
  3445.   pstring host_name;
  3446.   int res;
  3447.  
  3448.   /* get my host name */
  3449.   if (gethostname(host_name, MAXHOSTNAMELEN) == -1) 
  3450.     { DEBUG(0,("gethostname failed\n")); return -1; } 
  3451.  
  3452.   /* get host info */
  3453.   if ((hp = Get_Hostbyname(host_name)) == 0) 
  3454.     {
  3455.       DEBUG(0,( "Get_Hostbyname: Unknown host. %s\n",host_name));
  3456.       return -1;
  3457.     }
  3458.   
  3459.   bzero((char *)&sock,sizeof(sock));
  3460.   memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
  3461. #if defined(__FreeBSD__) || defined(NETBSD) || defined(__OpenBSD__) /* XXX not the right ifdef */
  3462.   sock.sin_len = sizeof(sock);
  3463. #endif
  3464.   sock.sin_port = htons( port );
  3465.   sock.sin_family = hp->h_addrtype;
  3466.   sock.sin_addr.s_addr = socket_addr;
  3467.   res = socket(hp->h_addrtype, type, 0);
  3468.   if (res == -1) 
  3469.     { DEBUG(0,("socket failed\n")); return -1; }
  3470.  
  3471.   {
  3472.     int one=1;
  3473.     setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
  3474.   }
  3475.  
  3476.   /* now we've got a socket - we need to bind it */
  3477.   if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) < 0) 
  3478.     { 
  3479.       if (port) {
  3480.     if (port == SMB_PORT || port == NMB_PORT)
  3481.       DEBUG(dlevel,("bind failed on port %d socket_addr=%s (%s)\n",
  3482.             port,inet_ntoa(sock.sin_addr),strerror(errno))); 
  3483.     close(res); 
  3484.  
  3485.     if (dlevel > 0 && port < 1000)
  3486.       port = 7999;
  3487.  
  3488.     if (port >= 1000 && port < 9000)
  3489.       return(open_socket_in(type,port+1,dlevel,socket_addr));
  3490.       }
  3491.  
  3492.       return(-1); 
  3493.     }
  3494.   DEBUG(3,("bind succeeded on port %d\n",port));
  3495.  
  3496.   return res;
  3497. }
  3498.  
  3499.  
  3500. /****************************************************************************
  3501.   create an outgoing socket
  3502.   **************************************************************************/
  3503. int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
  3504. {
  3505.   struct sockaddr_in sock_out;
  3506.   int res,ret;
  3507.   int connect_loop = 250; /* 250 milliseconds */
  3508.   int loops = (timeout * 1000) / connect_loop;
  3509.  
  3510.   /* create a socket to write to */
  3511.   res = socket(PF_INET, type, 0);
  3512.   if (res == -1) 
  3513.     { DEBUG(0,("socket error\n")); return -1; }
  3514.  
  3515.   if (type != SOCK_STREAM) return(res);
  3516.   
  3517.   bzero((char *)&sock_out,sizeof(sock_out));
  3518.   putip((char *)&sock_out.sin_addr,(char *)addr);
  3519.   
  3520.   sock_out.sin_port = htons( port );
  3521.   sock_out.sin_family = PF_INET;
  3522.  
  3523.   /* set it non-blocking */
  3524.   set_blocking(res,False);
  3525.  
  3526.   DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
  3527.   
  3528.   /* and connect it to the destination */
  3529. connect_again:
  3530.   ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
  3531.  
  3532.   /* Some systems return EAGAIN when they mean EINPROGRESS */
  3533.   if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
  3534.         errno == EAGAIN) && loops--) {
  3535.     msleep(connect_loop);
  3536.     goto connect_again;
  3537.   }
  3538.  
  3539.   if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
  3540.          errno == EAGAIN)) {
  3541.       DEBUG(1,("timeout connecting to %s:%d\n",inet_ntoa(*addr),port));
  3542.       close(res);
  3543.       return -1;
  3544.   }
  3545.  
  3546. #ifdef EISCONN
  3547.   if (ret < 0 && errno == EISCONN) {
  3548.     errno = 0;
  3549.     ret = 0;
  3550.   }
  3551. #endif
  3552.  
  3553.   if (ret < 0) {
  3554.     DEBUG(1,("error connecting to %s:%d (%s)\n",
  3555.          inet_ntoa(*addr),port,strerror(errno)));
  3556.     return -1;
  3557.   }
  3558.  
  3559.   /* set it blocking again */
  3560.   set_blocking(res,True);
  3561.  
  3562.   return res;
  3563. }
  3564.  
  3565.  
  3566. /****************************************************************************
  3567. interpret a protocol description string, with a default
  3568. ****************************************************************************/
  3569. int interpret_protocol(char *str,int def)
  3570. {
  3571.   if (strequal(str,"NT1"))
  3572.     return(PROTOCOL_NT1);
  3573.   if (strequal(str,"LANMAN2"))
  3574.     return(PROTOCOL_LANMAN2);
  3575.   if (strequal(str,"LANMAN1"))
  3576.     return(PROTOCOL_LANMAN1);
  3577.   if (strequal(str,"CORE"))
  3578.     return(PROTOCOL_CORE);
  3579.   if (strequal(str,"COREPLUS"))
  3580.     return(PROTOCOL_COREPLUS);
  3581.   if (strequal(str,"CORE+"))
  3582.     return(PROTOCOL_COREPLUS);
  3583.   
  3584.   DEBUG(0,("Unrecognised protocol level %s\n",str));
  3585.   
  3586.   return(def);
  3587. }
  3588.  
  3589. /****************************************************************************
  3590. interpret a security level
  3591. ****************************************************************************/
  3592. int interpret_security(char *str,int def)
  3593. {
  3594.   if (strequal(str,"SERVER"))
  3595.     return(SEC_SERVER);
  3596.   if (strequal(str,"USER"))
  3597.     return(SEC_USER);
  3598.   if (strequal(str,"SHARE"))
  3599.     return(SEC_SHARE);
  3600.   
  3601.   DEBUG(0,("Unrecognised security level %s\n",str));
  3602.   
  3603.   return(def);
  3604. }
  3605.  
  3606.  
  3607. /****************************************************************************
  3608. interpret an internet address or name into an IP address in 4 byte form
  3609. ****************************************************************************/
  3610. uint32 interpret_addr(char *str)
  3611. {
  3612.   struct hostent *hp;
  3613.   uint32 res;
  3614.   int i;
  3615.   BOOL pure_address = True;
  3616.  
  3617.   if (strcmp(str,"0.0.0.0") == 0) return(0);
  3618.   if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
  3619.  
  3620.   for (i=0; pure_address && str[i]; i++)
  3621.     if (!(isdigit(str[i]) || str[i] == '.')) 
  3622.       pure_address = False;
  3623.  
  3624.   /* if it's in the form of an IP address then get the lib to interpret it */
  3625.   if (pure_address) {
  3626.     res = inet_addr(str);
  3627.   } else {
  3628.     /* otherwise assume it's a network name of some sort and use 
  3629.        Get_Hostbyname */
  3630.     if ((hp = Get_Hostbyname(str)) == 0) {
  3631.       DEBUG(3,("Get_Hostbyname: Unknown host. %s\n",str));
  3632.       return 0;
  3633.     }
  3634.     if(hp->h_addr == NULL) {
  3635.       DEBUG(3,("Get_Hostbyname: host address is invalid for host %s.\n",str));
  3636.       return 0;
  3637.     }
  3638.     putip((char *)&res,(char *)hp->h_addr);
  3639.   }
  3640.  
  3641.   if (res == (uint32)-1) return(0);
  3642.  
  3643.   return(res);
  3644. }
  3645.  
  3646. /*******************************************************************
  3647.   a convenient addition to interpret_addr()
  3648.   ******************************************************************/
  3649. struct in_addr *interpret_addr2(char *str)
  3650. {
  3651.   static struct in_addr ret;
  3652.   uint32 a = interpret_addr(str);
  3653.   ret.s_addr = a;
  3654.   return(&ret);
  3655. }
  3656.  
  3657. /*******************************************************************
  3658.   check if an IP is the 0.0.0.0
  3659.   ******************************************************************/
  3660. BOOL zero_ip(struct in_addr ip)
  3661. {
  3662.   uint32 a;
  3663.   putip((char *)&a,(char *)&ip);
  3664.   return(a == 0);
  3665. }
  3666.  
  3667.  
  3668. /*******************************************************************
  3669.  matchname - determine if host name matches IP address 
  3670.  ******************************************************************/
  3671. static BOOL matchname(char *remotehost,struct in_addr  addr)
  3672. {
  3673.   struct hostent *hp;
  3674.   int     i;
  3675.   
  3676.   if ((hp = Get_Hostbyname(remotehost)) == 0) {
  3677.     DEBUG(0,("Get_Hostbyname(%s): lookup failure", remotehost));
  3678.     return False;
  3679.   } 
  3680.  
  3681.   /*
  3682.    * Make sure that gethostbyname() returns the "correct" host name.
  3683.    * Unfortunately, gethostbyname("localhost") sometimes yields
  3684.    * "localhost.domain". Since the latter host name comes from the
  3685.    * local DNS, we just have to trust it (all bets are off if the local
  3686.    * DNS is perverted). We always check the address list, though.
  3687.    */
  3688.   
  3689.   if (strcasecmp(remotehost, hp->h_name)
  3690.       && strcasecmp(remotehost, "localhost")) {
  3691.     DEBUG(0,("host name/name mismatch: %s != %s",
  3692.          remotehost, hp->h_name));
  3693.     return False;
  3694.   }
  3695.     
  3696.   /* Look up the host address in the address list we just got. */
  3697.   for (i = 0; hp->h_addr_list[i]; i++) {
  3698.     if (memcmp(hp->h_addr_list[i], (caddr_t) & addr, sizeof(addr)) == 0)
  3699.       return True;
  3700.   }
  3701.  
  3702.   /*
  3703.    * The host name does not map to the original host address. Perhaps
  3704.    * someone has compromised a name server. More likely someone botched
  3705.    * it, but that could be dangerous, too.
  3706.    */
  3707.   
  3708.   DEBUG(0,("host name/address mismatch: %s != %s",
  3709.        inet_ntoa(addr), hp->h_name));
  3710.   return False;
  3711. }
  3712.  
  3713. /*******************************************************************
  3714.  Reset the 'done' variables so after a client process is created
  3715.  from a fork call these calls will be re-done. This should be
  3716.  expanded if more variables need reseting.
  3717.  ******************************************************************/
  3718.  
  3719. static BOOL global_client_name_done = False;
  3720. static BOOL global_client_addr_done = False;
  3721.  
  3722. void reset_globals_after_fork(void)
  3723. {
  3724.   global_client_name_done = False;
  3725.   global_client_addr_done = False;
  3726. }
  3727.  
  3728. /*******************************************************************
  3729.  return the DNS name of the client 
  3730.  ******************************************************************/
  3731. char *client_name(void)
  3732. {
  3733.   struct sockaddr sa;
  3734.   struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
  3735.   int     length = sizeof(sa);
  3736.   static pstring name_buf;
  3737.   struct hostent *hp;
  3738.  
  3739.   if (global_client_name_done) 
  3740.     return name_buf;
  3741.  
  3742.   pstrcpy(name_buf,"UNKNOWN");
  3743.  
  3744.   if (Client == -1) {
  3745.       return name_buf;
  3746.   }
  3747.  
  3748.   if (getpeername(Client, &sa, &length) < 0) {
  3749.     DEBUG(0,("getpeername failed\n"));
  3750.     return name_buf;
  3751.   }
  3752.  
  3753.   /* Look up the remote host name. */
  3754.   if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
  3755.               sizeof(sockin->sin_addr),
  3756.               AF_INET)) == 0) {
  3757.     DEBUG(1,("Gethostbyaddr failed for %s\n",client_addr()));
  3758.     StrnCpy(name_buf,client_addr(),sizeof(name_buf) - 1);
  3759.   } else {
  3760.     StrnCpy(name_buf,(char *)hp->h_name,sizeof(name_buf) - 1);
  3761.     if (!matchname(name_buf, sockin->sin_addr)) {
  3762.       DEBUG(0,("Matchname failed on %s %s\n",name_buf,client_addr()));
  3763.       pstrcpy(name_buf,"UNKNOWN");
  3764.     }
  3765.   }
  3766.   global_client_name_done = True;
  3767.   return name_buf;
  3768. }
  3769.  
  3770. /*******************************************************************
  3771.  return the IP addr of the client as a string 
  3772.  ******************************************************************/
  3773. char *client_addr(void)
  3774. {
  3775.   struct sockaddr sa;
  3776.   struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
  3777.   int     length = sizeof(sa);
  3778.   static fstring addr_buf;
  3779.  
  3780.   if (global_client_addr_done) 
  3781.     return addr_buf;
  3782.  
  3783.   fstrcpy(addr_buf,"0.0.0.0");
  3784.  
  3785.   if (Client == -1) {
  3786.       return addr_buf;
  3787.   }
  3788.  
  3789.   if (getpeername(Client, &sa, &length) < 0) {
  3790.     DEBUG(0,("getpeername failed\n"));
  3791.     return addr_buf;
  3792.   }
  3793.  
  3794.   fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
  3795.  
  3796.   global_client_addr_done = True;
  3797.   return addr_buf;
  3798. }
  3799.  
  3800. /*******************************************************************
  3801.  Patch from jkf@soton.ac.uk
  3802.  Split Luke's automount_server into YP lookup and string splitter
  3803.  so can easily implement automount_path(). 
  3804.  As we may end up doing both, cache the last YP result. 
  3805. *******************************************************************/
  3806.  
  3807. #if (defined(NETGROUP) && defined(AUTOMOUNT))
  3808. #ifdef NISPLUS
  3809. static char *automount_lookup(char *user_name)
  3810. {
  3811.   static fstring last_key = "";
  3812.   static pstring last_value = "";
  3813.  
  3814.   char *nis_map = (char *)lp_nis_home_map_name();
  3815.  
  3816.   char nis_domain[NIS_MAXNAMELEN + 1];
  3817.   char buffer[NIS_MAXATTRVAL + 1];
  3818.   nis_result *result;
  3819.   nis_object *object;
  3820.   entry_obj  *entry;
  3821.  
  3822.   strncpy(nis_domain, (char *)nis_local_directory(), NIS_MAXNAMELEN);
  3823.   nis_domain[NIS_MAXNAMELEN] = '\0';
  3824.  
  3825.   DEBUG(5, ("NIS+ Domain: %s\n", nis_domain));
  3826.  
  3827.   if (strcmp(user_name, last_key))
  3828.   {
  3829.     slprintf(buffer, sizeof(buffer)-1, "[%s=%s]%s.%s", "key", user_name, nis_map, nis_domain);
  3830.     DEBUG(5, ("NIS+ querystring: %s\n", buffer));
  3831.  
  3832.     if (result = nis_list(buffer, RETURN_RESULT, NULL, NULL))
  3833.     {
  3834.        if (result->status != NIS_SUCCESS)
  3835.       {
  3836.         DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
  3837.         fstrcpy(last_key, ""); pstrcpy(last_value, "");
  3838.       }
  3839.       else
  3840.       {
  3841.         object = result->objects.objects_val;
  3842.         if (object->zo_data.zo_type == ENTRY_OBJ)
  3843.         {
  3844.            entry = &object->zo_data.objdata_u.en_data;
  3845.            DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
  3846.            DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
  3847.  
  3848.            pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
  3849.            string_sub(last_value, "&", user_name);
  3850.            fstrcpy(last_key, user_name);
  3851.         }
  3852.       }
  3853.     }
  3854.     nis_freeresult(result);
  3855.   }
  3856.   DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
  3857.   return last_value;
  3858. }
  3859. #else /* NISPLUS */
  3860. static char *automount_lookup(char *user_name)
  3861. {
  3862.   static fstring last_key = "";
  3863.   static pstring last_value = "";
  3864.  
  3865.   int nis_error;        /* returned by yp all functions */
  3866.   char *nis_result;     /* yp_match inits this */
  3867.   int nis_result_len;  /* and set this */
  3868.   char *nis_domain;     /* yp_get_default_domain inits this */
  3869.   char *nis_map = (char *)lp_nis_home_map_name();
  3870.  
  3871.   if ((nis_error = yp_get_default_domain(&nis_domain)) != 0)
  3872.   {
  3873.     DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
  3874.     return last_value;
  3875.   }
  3876.  
  3877.   DEBUG(5, ("NIS Domain: %s\n", nis_domain));
  3878.  
  3879.   if (!strcmp(user_name, last_key))
  3880.   {
  3881.     nis_result = last_value;
  3882.     nis_result_len = strlen(last_value);
  3883.     nis_error = 0;
  3884.   }
  3885.   else
  3886.   {
  3887.     if ((nis_error = yp_match(nis_domain, nis_map,
  3888.                               user_name, strlen(user_name),
  3889.                               &nis_result, &nis_result_len)) != 0)
  3890.     {
  3891.       DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n", 
  3892.                yperr_string(nis_error), user_name, nis_map));
  3893.     }
  3894.     if (!nis_error && nis_result_len >= sizeof(pstring))
  3895.     {
  3896.       nis_result_len = sizeof(pstring)-1;
  3897.     }
  3898.     fstrcpy(last_key, user_name);
  3899.     strncpy(last_value, nis_result, nis_result_len);
  3900.     last_value[nis_result_len] = '\0';
  3901.   }
  3902.  
  3903.   DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
  3904.   return last_value;
  3905. }
  3906. #endif /* NISPLUS */
  3907. #endif
  3908.  
  3909. /*******************************************************************
  3910.  Patch from jkf@soton.ac.uk
  3911.  This is Luke's original function with the NIS lookup code
  3912.  moved out to a separate function.
  3913. *******************************************************************/
  3914.  
  3915. char *automount_server(char *user_name)
  3916. {
  3917.     static pstring server_name;
  3918.  
  3919. #if (defined(NETGROUP) && defined (AUTOMOUNT))
  3920.     int home_server_len;
  3921.  
  3922.     /* set to default of local machine */
  3923.     pstrcpy(server_name, local_machine);
  3924.  
  3925.     if (lp_nis_home_map())
  3926.     {
  3927.         char *automount_value = automount_lookup(user_name);
  3928.         home_server_len = strcspn(automount_value,":");
  3929.         DEBUG(5, ("NIS lookup succeeded.  Home server length: %d\n",home_server_len));
  3930.         if (home_server_len > sizeof(pstring))
  3931.         {
  3932.             home_server_len = sizeof(pstring);
  3933.         }
  3934.         strncpy(server_name, automount_value, home_server_len);
  3935.                 server_name[home_server_len] = '\0';
  3936.     }
  3937. #else
  3938.     /* use the local machine name instead of the auto-map server */
  3939.     pstrcpy(server_name, local_machine);
  3940. #endif
  3941.  
  3942.     DEBUG(4,("Home server: %s\n", server_name));
  3943.  
  3944.     return server_name;
  3945. }
  3946.  
  3947. /*******************************************************************
  3948.  Patch from jkf@soton.ac.uk
  3949.  Added this to implement %p (NIS auto-map version of %H)
  3950. *******************************************************************/
  3951.  
  3952. char *automount_path(char *user_name)
  3953. {
  3954.     static pstring server_path;
  3955.  
  3956. #if (defined(NETGROUP) && defined (AUTOMOUNT))
  3957.     char *home_path_start;
  3958.  
  3959.     /* set to default of no string */
  3960.     server_path[0] = 0;
  3961.  
  3962.     if (lp_nis_home_map())
  3963.     {
  3964.         char *automount_value = automount_lookup(user_name);
  3965.         home_path_start = strchr(automount_value,':');
  3966.         if (home_path_start != NULL)
  3967.         {
  3968.           DEBUG(5, ("NIS lookup succeeded.  Home path is: %s\n",
  3969.                 home_path_start?(home_path_start+1):""));
  3970.           pstrcpy(server_path, home_path_start+1);
  3971.         }
  3972.     }
  3973. #else
  3974.     /* use the passwd entry instead of the auto-map server entry */
  3975.     /* pstrcpy() copes with get_home_dir() returning NULL */
  3976.     pstrcpy(server_path, get_home_dir(user_name));
  3977. #endif
  3978.  
  3979.     DEBUG(4,("Home server path: %s\n", server_path));
  3980.  
  3981.     return server_path;
  3982. }
  3983.  
  3984.  
  3985. /*******************************************************************
  3986. sub strings with useful parameters
  3987. Rewritten by Stefaan A Eeckels <Stefaan.Eeckels@ecc.lu> and
  3988. Paul Rippin <pr3245@nopc.eurostat.cec.be>
  3989. ********************************************************************/
  3990. void standard_sub_basic(char *str)
  3991. {
  3992.     char *s, *p;
  3993.     char pidstr[10];
  3994.         struct passwd *pass;
  3995.         char *username = sam_logon_in_ssb ? samlogon_user : sesssetup_user;
  3996.  
  3997.     for (s = str ; s && *s && (p = strchr(s,'%')); s = p )
  3998.     {
  3999.         switch (*(p+1))
  4000.         {
  4001.                         case 'G' :
  4002.                         {
  4003.                                 if ((pass = Get_Pwnam(username,False))!=NULL)
  4004.                                 {
  4005.                                         string_sub(p,"%G",gidtoname(pass->pw_gid));
  4006.                                 }
  4007.                                 else
  4008.                                 {
  4009.                                         p += 2;
  4010.                                 }
  4011.                                 break;
  4012.                         }
  4013.                         case 'N' : string_sub(p,"%N", automount_server(username)); break;
  4014.             case 'I' : string_sub(p,"%I", client_addr()); break;
  4015.             case 'L' : string_sub(p,"%L", local_machine); break;
  4016.             case 'M' : string_sub(p,"%M", client_name()); break;
  4017.             case 'R' : string_sub(p,"%R", remote_proto); break;
  4018.             case 'T' : string_sub(p,"%T", timestring()); break;
  4019.             case 'a' : string_sub(p,"%a", remote_arch); break;
  4020.                         case 'U' : string_sub(p,"%U", username); break;
  4021.             case 'd' :
  4022.             {
  4023.                 slprintf(pidstr,sizeof(pidstr)-1,"%d",(int)getpid());
  4024.                 string_sub(p,"%d", pidstr);
  4025.                 break;
  4026.             }
  4027.             case 'h' : string_sub(p,"%h", myhostname); break;
  4028.             case 'm' : string_sub(p,"%m", remote_machine); break;
  4029.             case 'v' : string_sub(p,"%v", VERSION); break;
  4030.                         case '$' : /* Expand environment variables */
  4031.                         {
  4032.                           /* Contributed by Branko Cibej <branko.cibej@hermes.si> */
  4033.                           fstring envname;
  4034.                           char *envval;
  4035.                           char *q, *r;
  4036.                           int copylen;
  4037.  
  4038.                           if (*(p+2) != '(') { p+=2; break; }
  4039.                           if ((q = strchr(p,')')) == NULL)
  4040.                           {
  4041.                             DEBUG(0,("standard_sub_basic: Unterminated environment \
  4042. variable [%s]\n", p));
  4043.                             p+=2; break;
  4044.                           }
  4045.  
  4046.                           r = p+3;
  4047.                           copylen = MIN((q-r),(sizeof(envname)-1));
  4048.                           strncpy(envname,r,copylen);
  4049.                           envname[copylen] = '\0';
  4050.                           if ((envval = getenv(envname)) == NULL)
  4051.                           {
  4052.                             DEBUG(0,("standard_sub_basic: Environment variable [%s] not set\n",
  4053.                                      envname));
  4054.                             p+=2; break;
  4055.                           }
  4056.                           copylen = MIN((q+1-p),(sizeof(envname)-1));
  4057.                           strncpy(envname,p,copylen);
  4058.                           envname[copylen] = '\0';
  4059.                           string_sub(p,envname,envval);
  4060.                           break;
  4061.                         }
  4062.             case '\0': p++; break; /* don't run off end if last character is % */
  4063.             default  : p+=2; break;
  4064.         }
  4065.     }
  4066.     return;
  4067. }
  4068.  
  4069. /*******************************************************************
  4070. are two IPs on the same subnet?
  4071. ********************************************************************/
  4072. BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
  4073. {
  4074.   uint32 net1,net2,nmask;
  4075.  
  4076.   nmask = ntohl(mask.s_addr);
  4077.   net1  = ntohl(ip1.s_addr);
  4078.   net2  = ntohl(ip2.s_addr);
  4079.             
  4080.   return((net1 & nmask) == (net2 & nmask));
  4081. }
  4082.  
  4083.  
  4084. /*******************************************************************
  4085. write a string in unicoode format
  4086. ********************************************************************/
  4087. int PutUniCode(char *dst,char *src)
  4088. {
  4089.   int ret = 0;
  4090.   while (*src) {
  4091.     dst[ret++] = src[0];
  4092.     dst[ret++] = 0;    
  4093.     src++;
  4094.   }
  4095.   dst[ret++]=0;
  4096.   dst[ret++]=0;
  4097.   return(ret);
  4098. }
  4099.  
  4100. /****************************************************************************
  4101. a wrapper for gethostbyname() that tries with all lower and all upper case 
  4102. if the initial name fails
  4103. ****************************************************************************/
  4104. struct hostent *Get_Hostbyname(char *name)
  4105. {
  4106.   char *name2 = strdup(name);
  4107.   struct hostent *ret;
  4108.  
  4109.   if (!name2)
  4110.     {
  4111.       DEBUG(0,("Memory allocation error in Get_Hostbyname! panic\n"));
  4112.       exit(0);
  4113.     }
  4114.  
  4115.   /*
  4116.    * This next test is redundent and causes some systems (with
  4117.    * broken isalnum() calls) problems.
  4118.    * JRA.
  4119.    */
  4120.  
  4121. #if 0
  4122.   if (!isalnum(*name2))
  4123.     {
  4124.       free(name2);
  4125.       return(NULL);
  4126.     }
  4127. #endif /* 0 */
  4128.  
  4129.   ret = sys_gethostbyname(name2);
  4130.   if (ret != NULL)
  4131.     {
  4132.       free(name2);
  4133.       return(ret);
  4134.     }
  4135.  
  4136.   /* try with all lowercase */
  4137.   strlower(name2);
  4138.   ret = sys_gethostbyname(name2);
  4139.   if (ret != NULL)
  4140.     {
  4141.       free(name2);
  4142.       return(ret);
  4143.     }
  4144.  
  4145.   /* try with all uppercase */
  4146.   strupper(name2);
  4147.   ret = sys_gethostbyname(name2);
  4148.   if (ret != NULL)
  4149.     {
  4150.       free(name2);
  4151.       return(ret);
  4152.     }
  4153.   
  4154.   /* nothing works :-( */
  4155.   free(name2);
  4156.   return(NULL);
  4157. }
  4158.  
  4159.  
  4160. /****************************************************************************
  4161. check if a process exists. Does this work on all unixes?
  4162. ****************************************************************************/
  4163. BOOL process_exists(int pid)
  4164. {
  4165.     return(kill(pid,0) == 0 || errno != ESRCH);
  4166. }
  4167.  
  4168.  
  4169. /*******************************************************************
  4170. turn a uid into a user name
  4171. ********************************************************************/
  4172. char *uidtoname(int uid)
  4173. {
  4174.   static char name[40];
  4175.   struct passwd *pass = getpwuid(uid);
  4176.   if (pass) return(pass->pw_name);
  4177.   slprintf(name,sizeof(name)-1,"%d",uid);
  4178.   return(name);
  4179. }
  4180.  
  4181. /*******************************************************************
  4182. turn a gid into a group name
  4183. ********************************************************************/
  4184. char *gidtoname(int gid)
  4185. {
  4186.   static char name[40];
  4187.   struct group *grp = getgrgid(gid);
  4188.   if (grp) return(grp->gr_name);
  4189.   slprintf(name,sizeof(name)-1,"%d",gid);
  4190.   return(name);
  4191. }
  4192.  
  4193. /*******************************************************************
  4194. block sigs
  4195. ********************************************************************/
  4196. void BlockSignals(BOOL block,int signum)
  4197. {
  4198. #ifdef USE_SIGBLOCK
  4199.   int block_mask = sigmask(signum);
  4200.   static int oldmask = 0;
  4201.   if (block) 
  4202.     oldmask = sigblock(block_mask);
  4203.   else
  4204.     sigsetmask(oldmask);
  4205. #elif defined(USE_SIGPROCMASK)
  4206.   sigset_t set;
  4207.   sigemptyset(&set);
  4208.   sigaddset(&set,signum);
  4209.   sigprocmask(block?SIG_BLOCK:SIG_UNBLOCK,&set,NULL);
  4210. #endif
  4211. }
  4212.  
  4213. #if AJT
  4214. /*******************************************************************
  4215. my own panic function - not suitable for general use
  4216. ********************************************************************/
  4217. void ajt_panic(void)
  4218. {
  4219.   system("/usr/bin/X11/xedit -display solen:0 /tmp/ERROR_FAULT");
  4220. }
  4221. #endif
  4222.  
  4223. #ifdef USE_DIRECT
  4224. #define DIRECT direct
  4225. #else
  4226. #define DIRECT dirent
  4227. #endif
  4228.  
  4229. /*******************************************************************
  4230. a readdir wrapper which just returns the file name
  4231. also return the inode number if requested
  4232. ********************************************************************/
  4233. char *readdirname(void *p)
  4234. {
  4235.   struct DIRECT *ptr;
  4236.   char *dname;
  4237.  
  4238.   if (!p) return(NULL);
  4239.   
  4240.   ptr = (struct DIRECT *)readdir(p);
  4241.   if (!ptr) return(NULL);
  4242.  
  4243.   dname = ptr->d_name;
  4244.  
  4245. #ifdef NEXT2
  4246.   if (telldir(p) < 0) return(NULL);
  4247. #endif
  4248.  
  4249. #ifdef SUNOS5
  4250.   /* this handles a broken compiler setup, causing a mixture
  4251.    of BSD and SYSV headers and libraries */
  4252.   {
  4253.     static BOOL broken_readdir = False;
  4254.     if (!broken_readdir && !(*(dname)) && strequal("..",dname-2))
  4255.       {
  4256.     DEBUG(0,("Your readdir() is broken. You have somehow mixed SYSV and BSD headers and libraries\n"));
  4257.     broken_readdir = True;
  4258.       }
  4259.     if (broken_readdir)
  4260.       dname = dname - 2;
  4261.   }
  4262. #endif
  4263.  
  4264.   {
  4265.     static pstring buf;
  4266.     pstrcpy(buf, dname);
  4267.     unix_to_dos(buf, True);
  4268.     dname = buf;
  4269.   }
  4270.  
  4271.   return(dname);
  4272. }
  4273.  
  4274. /*******************************************************************
  4275.  Utility function used to decide if the last component 
  4276.  of a path matches a (possibly wildcarded) entry in a namelist.
  4277. ********************************************************************/
  4278.  
  4279. BOOL is_in_path(char *name, name_compare_entry *namelist)
  4280. {
  4281.   pstring last_component;
  4282.   char *p;
  4283.  
  4284.   DEBUG(8, ("is_in_path: %s\n", name));
  4285.  
  4286.   /* if we have no list it's obviously not in the path */
  4287.   if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) 
  4288.   {
  4289.     DEBUG(8,("is_in_path: no name list.\n"));
  4290.     return False;
  4291.   }
  4292.  
  4293.   /* Get the last component of the unix name. */
  4294.   p = strrchr(name, '/');
  4295.   strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
  4296.   last_component[sizeof(last_component)-1] = '\0'; 
  4297.  
  4298.   for(; namelist->name != NULL; namelist++)
  4299.   {
  4300.     if(namelist->is_wild)
  4301.     {
  4302.       /* look for a wildcard match. */
  4303.       if (mask_match(last_component, namelist->name, case_sensitive, False))
  4304.       {
  4305.          DEBUG(8,("is_in_path: mask match succeeded\n"));
  4306.          return True;
  4307.       }
  4308.     }
  4309.     else
  4310.     {
  4311.       if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
  4312.        (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
  4313.         {
  4314.          DEBUG(8,("is_in_path: match succeeded\n"));
  4315.          return True;
  4316.         }
  4317.     }
  4318.   }
  4319.   DEBUG(8,("is_in_path: match not found\n"));
  4320.  
  4321.   return False;
  4322. }
  4323.  
  4324. /*******************************************************************
  4325.  Strip a '/' separated list into an array of 
  4326.  name_compare_enties structures suitable for 
  4327.  passing to is_in_path(). We do this for
  4328.  speed so we can pre-parse all the names in the list 
  4329.  and don't do it for each call to is_in_path().
  4330.  namelist is modified here and is assumed to be 
  4331.  a copy owned by the caller.
  4332.  We also check if the entry contains a wildcard to
  4333.  remove a potentially expensive call to mask_match
  4334.  if possible.
  4335. ********************************************************************/
  4336.  
  4337. void set_namearray(name_compare_entry **ppname_array, char *namelist)
  4338. {
  4339.   char *name_end;
  4340.   char *nameptr = namelist;
  4341.   int num_entries = 0;
  4342.   int i;
  4343.  
  4344.   (*ppname_array) = NULL;
  4345.  
  4346.   if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0'))) 
  4347.     return;
  4348.  
  4349.   /* We need to make two passes over the string. The
  4350.      first to count the number of elements, the second
  4351.      to split it.
  4352.    */
  4353.   while(*nameptr) 
  4354.     {
  4355.       if ( *nameptr == '/' ) 
  4356.         {
  4357.           /* cope with multiple (useless) /s) */
  4358.           nameptr++;
  4359.           continue;
  4360.         }
  4361.       /* find the next / */
  4362.       name_end = strchr(nameptr, '/');
  4363.  
  4364.       /* oops - the last check for a / didn't find one. */
  4365.       if (name_end == NULL)
  4366.         break;
  4367.  
  4368.       /* next segment please */
  4369.       nameptr = name_end + 1;
  4370.       num_entries++;
  4371.     }
  4372.  
  4373.   if(num_entries == 0)
  4374.     return;
  4375.  
  4376.   if(( (*ppname_array) = (name_compare_entry *)malloc( 
  4377.            (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
  4378.         {
  4379.     DEBUG(0,("set_namearray: malloc fail\n"));
  4380.     return;
  4381.         }
  4382.  
  4383.   /* Now copy out the names */
  4384.   nameptr = namelist;
  4385.   i = 0;
  4386.   while(*nameptr)
  4387.              {
  4388.       if ( *nameptr == '/' ) 
  4389.       {
  4390.           /* cope with multiple (useless) /s) */
  4391.           nameptr++;
  4392.           continue;
  4393.       }
  4394.       /* find the next / */
  4395.       if ((name_end = strchr(nameptr, '/')) != NULL) 
  4396.       {
  4397.           *name_end = 0;
  4398.          }
  4399.  
  4400.       /* oops - the last check for a / didn't find one. */
  4401.       if(name_end == NULL) 
  4402.         break;
  4403.  
  4404.       (*ppname_array)[i].is_wild = ((strchr( nameptr, '?')!=NULL) ||
  4405.                                 (strchr( nameptr, '*')!=NULL));
  4406.       if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
  4407.       {
  4408.         DEBUG(0,("set_namearray: malloc fail (1)\n"));
  4409.         return;
  4410.       }
  4411.  
  4412.       /* next segment please */
  4413.       nameptr = name_end + 1;
  4414.       i++;
  4415.     }
  4416.   
  4417.   (*ppname_array)[i].name = NULL;
  4418.  
  4419.   return;
  4420. }
  4421.  
  4422. /****************************************************************************
  4423. routine to free a namearray.
  4424. ****************************************************************************/
  4425.  
  4426. void free_namearray(name_compare_entry *name_array)
  4427. {
  4428.   if(name_array == 0)
  4429.     return;
  4430.  
  4431.   if(name_array->name != NULL)
  4432.     free(name_array->name);
  4433.  
  4434.   free((char *)name_array);
  4435. }
  4436.  
  4437. /****************************************************************************
  4438. routine to do file locking
  4439. ****************************************************************************/
  4440. BOOL fcntl_lock(int fd,int op,uint32 offset,uint32 count,int type)
  4441. {
  4442. #if HAVE_FCNTL_LOCK
  4443.   struct flock lock;
  4444.   int ret;
  4445.  
  4446. #if 1
  4447.   uint32 mask = 0xC0000000;
  4448.  
  4449.   /* make sure the count is reasonable, we might kill the lockd otherwise */
  4450.   count &= ~mask;
  4451.  
  4452.   /* the offset is often strange - remove 2 of its bits if either of
  4453.      the top two bits are set. Shift the top ones by two bits. This
  4454.      still allows OLE2 apps to operate, but should stop lockd from
  4455.      dieing */
  4456.   if ((offset & mask) != 0)
  4457.     offset = (offset & ~mask) | ((offset & mask) >> 2);
  4458. #else
  4459.   uint32 mask = ((unsigned)1<<31);
  4460.  
  4461.   /* interpret negative counts as large numbers */
  4462.   if (count < 0)
  4463.     count &= ~mask;
  4464.  
  4465.   /* no negative offsets */
  4466.   offset &= ~mask;
  4467.  
  4468.   /* count + offset must be in range */
  4469.   while ((offset < 0 || (offset + count < 0)) && mask)
  4470.     {
  4471.       offset &= ~mask;
  4472.       mask = mask >> 1;
  4473.     }
  4474. #endif
  4475.  
  4476.  
  4477.   DEBUG(8,("fcntl_lock %d %d %d %d %d\n",fd,op,(int)offset,(int)count,type));
  4478.  
  4479.   lock.l_type = type;
  4480.   lock.l_whence = SEEK_SET;
  4481.   lock.l_start = (int)offset;
  4482.   lock.l_len = (int)count;
  4483.   lock.l_pid = 0;
  4484.  
  4485.   errno = 0;
  4486.  
  4487.   ret = fcntl(fd,op,&lock);
  4488.  
  4489.   if (errno != 0)
  4490.     DEBUG(3,("fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
  4491.  
  4492.   /* a lock query */
  4493.   if (op == F_GETLK)
  4494.     {
  4495.       if ((ret != -1) &&
  4496.       (lock.l_type != F_UNLCK) && 
  4497.       (lock.l_pid != 0) && 
  4498.       (lock.l_pid != getpid()))
  4499.     {
  4500.       DEBUG(3,("fd %d is locked by pid %d\n",fd,lock.l_pid));
  4501.       return(True);
  4502.     }
  4503.  
  4504.       /* it must be not locked or locked by me */
  4505.       return(False);
  4506.     }
  4507.  
  4508.   /* a lock set or unset */
  4509.   if (ret == -1)
  4510.     {
  4511.       DEBUG(3,("lock failed at offset %d count %d op %d type %d (%s)\n",
  4512.            offset,count,op,type,strerror(errno)));
  4513.  
  4514.       /* perhaps it doesn't support this sort of locking?? */
  4515.       if (errno == EINVAL)
  4516.     {
  4517.       DEBUG(3,("locking not supported? returning True\n"));
  4518.       return(True);
  4519.     }
  4520.  
  4521.       return(False);
  4522.     }
  4523.  
  4524.   /* everything went OK */
  4525.   DEBUG(8,("Lock call successful\n"));
  4526.  
  4527.   return(True);
  4528. #else
  4529.   return(False);
  4530. #endif
  4531. }
  4532.  
  4533. /*******************************************************************
  4534. lock a file - returning a open file descriptor or -1 on failure
  4535. The timeout is in seconds. 0 means no timeout
  4536. ********************************************************************/
  4537. int file_lock(char *name,int timeout)
  4538. {  
  4539.   int fd = open(name,O_RDWR|O_CREAT,0666);
  4540.   time_t t=0;
  4541.   if (fd < 0) return(-1);
  4542.  
  4543. #if HAVE_FCNTL_LOCK
  4544.   if (timeout) t = time(NULL);
  4545.   while (!timeout || (time(NULL)-t < timeout)) {
  4546.     if (fcntl_lock(fd,F_SETLK,0,1,F_WRLCK)) return(fd);    
  4547.     msleep(LOCK_RETRY_TIMEOUT);
  4548.   }
  4549.   return(-1);
  4550. #else
  4551.   return(fd);
  4552. #endif
  4553. }
  4554.  
  4555. /*******************************************************************
  4556. unlock a file locked by file_lock
  4557. ********************************************************************/
  4558. void file_unlock(int fd)
  4559. {
  4560.   if (fd<0) return;
  4561. #if HAVE_FCNTL_LOCK
  4562.   fcntl_lock(fd,F_SETLK,0,1,F_UNLCK);
  4563. #endif
  4564.   close(fd);
  4565. }
  4566.  
  4567. /*******************************************************************
  4568. is the name specified one of my netbios names
  4569. returns true is it is equal, false otherwise
  4570. ********************************************************************/
  4571. BOOL is_myname(char *s)
  4572. {
  4573.   int n;
  4574.   BOOL ret = False;
  4575.  
  4576.   for (n=0; my_netbios_names[n]; n++) {
  4577.     if (strequal(my_netbios_names[n], s))
  4578.       ret=True;
  4579.   }
  4580.   DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
  4581.   return(ret);
  4582. }
  4583.  
  4584. /*******************************************************************
  4585. set the horrid remote_arch string based on an enum.
  4586. ********************************************************************/
  4587. void set_remote_arch(enum remote_arch_types type)
  4588. {
  4589.   ra_type = type;
  4590.   switch( type )
  4591.   {
  4592.   case RA_WFWG:
  4593.     fstrcpy(remote_arch, "WfWg");
  4594.     return;
  4595.   case RA_OS2:
  4596.     fstrcpy(remote_arch, "OS2");
  4597.     return;
  4598.   case RA_WIN95:
  4599.     fstrcpy(remote_arch, "Win95");
  4600.     return;
  4601.   case RA_WINNT:
  4602.     fstrcpy(remote_arch, "WinNT");
  4603.     return;
  4604.   case RA_SAMBA:
  4605.     fstrcpy(remote_arch,"Samba");
  4606.     return;
  4607.   default:
  4608.     ra_type = RA_UNKNOWN;
  4609.     fstrcpy(remote_arch, "UNKNOWN");
  4610.     break;
  4611.   }
  4612. }
  4613.  
  4614. /*******************************************************************
  4615.  Get the remote_arch type.
  4616. ********************************************************************/
  4617. enum remote_arch_types get_remote_arch(void)
  4618. {
  4619.   return ra_type;
  4620. }
  4621.  
  4622.  
  4623. /*******************************************************************
  4624. skip past some unicode strings in a buffer
  4625. ********************************************************************/
  4626. char *skip_unicode_string(char *buf,int n)
  4627. {
  4628.   while (n--)
  4629.   {
  4630.     while (*buf)
  4631.       buf += 2;
  4632.     buf += 2;
  4633.   }
  4634.   return(buf);
  4635. }
  4636.  
  4637. /*******************************************************************
  4638. Return a ascii version of a unicode string
  4639. Hack alert: uses fixed buffer(s) and only handles ascii strings
  4640. ********************************************************************/
  4641. #define MAXUNI 1024
  4642. char *unistrn2(uint16 *buf, int len)
  4643. {
  4644.     static char lbufs[8][MAXUNI];
  4645.     static int nexti;
  4646.     char *lbuf = lbufs[nexti];
  4647.     char *p;
  4648.  
  4649.     nexti = (nexti+1)%8;
  4650.  
  4651.     DEBUG(10, ("unistrn2: "));
  4652.  
  4653.     for (p = lbuf; *buf && p-lbuf < MAXUNI-2 && len > 0; len--, p++, buf++)
  4654.     {
  4655.         DEBUG(10, ("%4x ", *buf));
  4656.         *p = *buf;
  4657.     }
  4658.  
  4659.     DEBUG(10,("\n"));
  4660.  
  4661.     *p = 0;
  4662.     return lbuf;
  4663. }
  4664.  
  4665. /*******************************************************************
  4666. Return a ascii version of a unicode string
  4667. Hack alert: uses fixed buffer(s) and only handles ascii strings
  4668. ********************************************************************/
  4669. #define MAXUNI 1024
  4670. char *unistr2(uint16 *buf)
  4671. {
  4672.     static char lbufs[8][MAXUNI];
  4673.     static int nexti;
  4674.     char *lbuf = lbufs[nexti];
  4675.     char *p;
  4676.  
  4677.     nexti = (nexti+1)%8;
  4678.  
  4679.     DEBUG(10, ("unistr2: "));
  4680.  
  4681.     for (p = lbuf; *buf && p-lbuf < MAXUNI-2; p++, buf++)
  4682.     {
  4683.         DEBUG(10, ("%4x ", *buf));
  4684.         *p = *buf;
  4685.     }
  4686.  
  4687.     DEBUG(10,("\n"));
  4688.  
  4689.     *p = 0;
  4690.     return lbuf;
  4691. }
  4692.  
  4693. /*******************************************************************
  4694. create a null-terminated unicode string from a null-terminated ascii string.
  4695. return number of unicode chars copied, excluding the null character.
  4696.  
  4697. only handles ascii strings
  4698. ********************************************************************/
  4699. #define MAXUNI 1024
  4700. int struni2(uint16 *p, char *buf)
  4701. {
  4702.     int len = 0;
  4703.  
  4704.     if (p == NULL) return 0;
  4705.  
  4706.     DEBUG(10, ("struni2: "));
  4707.  
  4708.     if (buf != NULL)
  4709.     {
  4710.         for (; *buf && len < MAXUNI-2; len++, p++, buf++)
  4711.         {
  4712.             DEBUG(10, ("%2x ", *buf));
  4713.             *p = *buf;
  4714.         }
  4715.  
  4716.         DEBUG(10,("\n"));
  4717.     }
  4718.  
  4719.     *p = 0;
  4720.  
  4721.     return len;
  4722. }
  4723.  
  4724. /*******************************************************************
  4725. Return a ascii version of a unicode string
  4726. Hack alert: uses fixed buffer(s) and only handles ascii strings
  4727. ********************************************************************/
  4728. #define MAXUNI 1024
  4729. char *unistr(char *buf)
  4730. {
  4731.     static char lbufs[8][MAXUNI];
  4732.     static int nexti;
  4733.     char *lbuf = lbufs[nexti];
  4734.     char *p;
  4735.  
  4736.     nexti = (nexti+1)%8;
  4737.  
  4738.     for (p = lbuf; *buf && p-lbuf < MAXUNI-2; p++, buf += 2)
  4739.     {
  4740.         *p = *buf;
  4741.     }
  4742.     *p = 0;
  4743.     return lbuf;
  4744. }
  4745.  
  4746. /*******************************************************************
  4747. strncpy for unicode strings
  4748. ********************************************************************/
  4749. int unistrncpy(char *dst, char *src, int len)
  4750. {
  4751.     int num_wchars = 0;
  4752.  
  4753.     while (*src && len > 0)
  4754.     {
  4755.         *dst++ = *src++;
  4756.         *dst++ = *src++;
  4757.         len--;
  4758.         num_wchars++;
  4759.     }
  4760.     *dst++ = 0;
  4761.     *dst++ = 0;
  4762.  
  4763.     return num_wchars;
  4764. }
  4765.  
  4766.  
  4767. /*******************************************************************
  4768. strcpy for unicode strings.  returns length (in num of wide chars)
  4769. ********************************************************************/
  4770. int unistrcpy(char *dst, char *src)
  4771. {
  4772.     int num_wchars = 0;
  4773.  
  4774.     while (*src)
  4775.     {
  4776.         *dst++ = *src++;
  4777.         *dst++ = *src++;
  4778.         num_wchars++;
  4779.     }
  4780.     *dst++ = 0;
  4781.     *dst++ = 0;
  4782.  
  4783.     return num_wchars;
  4784. }
  4785.  
  4786. /*******************************************************************
  4787. safe string copy into a known length string. maxlength does not
  4788. include the terminating zero.
  4789. ********************************************************************/
  4790. char *safe_strcpy(char *dest, char *src, int maxlength)
  4791. {
  4792.     int len;
  4793.  
  4794.     if (!dest) {
  4795.         DEBUG(0,("ERROR: NULL dest in safe_strcpy\n"));
  4796.         return NULL;
  4797.     }
  4798.  
  4799.     if (!src) {
  4800.         *dest = 0;
  4801.         return dest;
  4802.     } 
  4803.  
  4804.     len = strlen(src);
  4805.  
  4806.     if (len > maxlength) {
  4807.             DEBUG(0,("ERROR: string overflow by %d in safe_strcpy [%.50s]\n",
  4808.                      len-maxlength, src));
  4809.             len = maxlength;
  4810.     }
  4811.  
  4812.     memcpy(dest, src, len);
  4813.     dest[len] = 0;
  4814.     return dest;
  4815.  
  4816. /*******************************************************************
  4817. safe string cat into a string. maxlength does not
  4818. include the terminating zero.
  4819. ********************************************************************/
  4820. char *safe_strcat(char *dest, char *src, int maxlength)
  4821. {
  4822.     int src_len, dest_len;
  4823.  
  4824.     if (!dest) {
  4825.         DEBUG(0,("ERROR: NULL dest in safe_strcat\n"));
  4826.         return NULL;
  4827.     }
  4828.  
  4829.     if (!src) {
  4830.         return dest;
  4831.     }
  4832.  
  4833.     src_len = strlen(src);
  4834.     dest_len = strlen(dest);
  4835.  
  4836.     if (src_len + dest_len > maxlength) {
  4837.             DEBUG(0,("ERROR: string overflow by %d in safe_strcat [%.50s]\n",
  4838.                      src_len + dest_len - maxlength, src));
  4839.             src_len = maxlength - dest_len;
  4840.     }
  4841.  
  4842.     memcpy(&dest[dest_len], src, src_len);
  4843.     dest[dest_len + src_len] = 0;
  4844.     return dest;
  4845. }
  4846.  
  4847.  
  4848. /*******************************************************************
  4849. align a pointer to a multiple of 4 bytes
  4850. ********************************************************************/
  4851. char *align4(char *q, char *base)
  4852. {
  4853.     if ((q - base) & 3)
  4854.     {
  4855.         q += 4 - ((q - base) & 3);
  4856.     }
  4857.     return q;
  4858. }
  4859.  
  4860. /*******************************************************************
  4861. align a pointer to a multiple of 2 bytes
  4862. ********************************************************************/
  4863. char *align2(char *q, char *base)
  4864. {
  4865.     if ((q - base) & 1)
  4866.     {
  4867.         q++;
  4868.     }
  4869.     return q;
  4870. }
  4871.  
  4872. /*******************************************************************
  4873. align a pointer to a multiple of align_offset bytes.  looks like it
  4874. will work for offsets of 0, 2 and 4...
  4875. ********************************************************************/
  4876. char *align_offset(char *q, char *base, int align_offset_len)
  4877. {
  4878.     int mod = ((q - base) & (align_offset_len-1));
  4879.     if (align_offset_len != 0 && mod != 0)
  4880.     {
  4881.         q += align_offset_len - mod;
  4882.     }
  4883.     return q;
  4884. }
  4885.  
  4886. void print_asc(int level, unsigned char *buf,int len)
  4887. {
  4888.     int i;
  4889.     for (i=0;i<len;i++)
  4890.         DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
  4891. }
  4892.  
  4893. void dump_data(int level,char *buf1,int len)
  4894. {
  4895.   unsigned char *buf = (unsigned char *)buf1;
  4896.   int i=0;
  4897.   if (len<=0) return;
  4898.  
  4899.   DEBUG(level,("[%03X] ",i));
  4900.   for (i=0;i<len;) {
  4901.     DEBUG(level,("%02X ",(int)buf[i]));
  4902.     i++;
  4903.     if (i%8 == 0) DEBUG(level,(" "));
  4904.     if (i%16 == 0) {      
  4905.       print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
  4906.       print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
  4907.       if (i<len) DEBUG(level,("[%03X] ",i));
  4908.     }
  4909.   }
  4910.   if (i%16) {
  4911.     int n;
  4912.  
  4913.     n = 16 - (i%16);
  4914.     DEBUG(level,(" "));
  4915.     if (n>8) DEBUG(level,(" "));
  4916.     while (n--) DEBUG(level,("   "));
  4917.  
  4918.     n = MIN(8,i%16);
  4919.     print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
  4920.     n = (i%16) - n;
  4921.     if (n>0) print_asc(level,&buf[i-n],n); 
  4922.     DEBUG(level,("\n"));    
  4923.   }
  4924. }
  4925.  
  4926. char *tab_depth(int depth)
  4927. {
  4928.     static pstring spaces;
  4929.     memset(spaces, ' ', depth * 4);
  4930.     spaces[depth * 4] = 0;
  4931.     return spaces;
  4932. }
  4933.  
  4934.  
  4935.