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 / server.c < prev    next >
C/C++ Source or Header  |  1998-05-12  |  158KB  |  5,523 lines

  1. /* 
  2.    Unix SMB/Netbios implementation.
  3.    Version 1.9.
  4.    Main SMB server routines
  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. #include "trans2.h"
  24.  
  25. pstring servicesf = CONFIGFILE;
  26. extern pstring debugf;
  27. extern pstring sesssetup_user;
  28. extern fstring myworkgroup;
  29.  
  30. char *InBuffer = NULL;
  31. char *OutBuffer = NULL;
  32. char *last_inbuf = NULL;
  33.  
  34. int am_parent = 1;
  35. int atexit_set = 0;
  36.  
  37. /* the last message the was processed */
  38. int last_message = -1;
  39.  
  40. /* a useful macro to debug the last message processed */
  41. #define LAST_MESSAGE() smb_fn_name(last_message)
  42.  
  43. extern pstring scope;
  44. extern int DEBUGLEVEL;
  45. extern int case_default;
  46. extern BOOL case_sensitive;
  47. extern BOOL case_preserve;
  48. extern BOOL use_mangled_map;
  49. extern BOOL short_case_preserve;
  50. extern BOOL case_mangle;
  51. time_t smb_last_time=(time_t)0;
  52.  
  53. extern int smb_read_error;
  54.  
  55. extern pstring user_socket_options;
  56.  
  57. #ifdef DFS_AUTH
  58. extern int dcelogin_atmost_once;
  59. #endif /* DFS_AUTH */
  60.  
  61. connection_struct Connections[MAX_CONNECTIONS];
  62. files_struct Files[MAX_OPEN_FILES];
  63.  
  64. /*
  65.  * Indirection for file fd's. Needed as POSIX locking
  66.  * is based on file/process, not fd/process.
  67.  */
  68. file_fd_struct FileFd[MAX_OPEN_FILES];
  69. int max_file_fd_used = 0;
  70.  
  71. extern int Protocol;
  72.  
  73. /* 
  74.  * Size of data we can send to client. Set
  75.  *  by the client for all protocols above CORE.
  76.  *  Set by us for CORE protocol.
  77.  */
  78. int max_send = BUFFER_SIZE;
  79. /*
  80.  * Size of the data we can receive. Set by us.
  81.  * Can be modified by the max xmit parameter.
  82.  */
  83. int max_recv = BUFFER_SIZE;
  84.  
  85. /* a fnum to use when chaining */
  86. int chain_fnum = -1;
  87.  
  88. /* number of open connections */
  89. static int num_connections_open = 0;
  90.  
  91. /* Oplock ipc UDP socket. */
  92. int oplock_sock = -1;
  93. uint16 oplock_port = 0;
  94. /* Current number of oplocks we have outstanding. */
  95. int32 global_oplocks_open = 0;
  96.  
  97. BOOL global_oplock_break = False;
  98.  
  99. extern fstring remote_machine;
  100.  
  101. extern pstring OriginalDir;
  102.  
  103. /* these can be set by some functions to override the error codes */
  104. int unix_ERR_class=SMB_SUCCESS;
  105. int unix_ERR_code=0;
  106.  
  107.  
  108. extern int extra_time_offset;
  109.  
  110. extern pstring myhostname;
  111.  
  112. static int find_free_connection(int hash);
  113.  
  114. /* for readability... */
  115. #define IS_DOS_READONLY(test_mode) (((test_mode) & aRONLY) != 0)
  116. #define IS_DOS_DIR(test_mode) (((test_mode) & aDIR) != 0)
  117. #define IS_DOS_ARCHIVE(test_mode) (((test_mode) & aARCH) != 0)
  118. #define IS_DOS_SYSTEM(test_mode) (((test_mode) & aSYSTEM) != 0)
  119. #define IS_DOS_HIDDEN(test_mode) (((test_mode) & aHIDDEN) != 0)
  120.  
  121. /****************************************************************************
  122.   when exiting, take the whole family
  123. ****************************************************************************/
  124. void  *dflt_sig(void)
  125. {
  126.   exit_server("caught signal");
  127.   return 0; /* Keep -Wall happy :-) */
  128. }
  129. /****************************************************************************
  130.   Send a SIGTERM to our process group.
  131. *****************************************************************************/
  132. void  killkids(void)
  133. {
  134.   if(am_parent) kill(0,SIGTERM);
  135. }
  136.  
  137. /****************************************************************************
  138.   change a dos mode to a unix mode
  139.     base permission for files:
  140.          everybody gets read bit set
  141.          dos readonly is represented in unix by removing everyone's write bit
  142.          dos archive is represented in unix by the user's execute bit
  143.          dos system is represented in unix by the group's execute bit
  144.          dos hidden is represented in unix by the other's execute bit
  145.          Then apply create mask,
  146.          then add force bits.
  147.     base permission for directories:
  148.          dos directory is represented in unix by unix's dir bit and the exec bit
  149.          Then apply create mask,
  150.          then add force bits.
  151. ****************************************************************************/
  152. mode_t unix_mode(int cnum,int dosmode)
  153. {
  154.   mode_t result = (S_IRUSR | S_IRGRP | S_IROTH);
  155.  
  156.   if ( !IS_DOS_READONLY(dosmode) )
  157.     result |= (S_IWUSR | S_IWGRP | S_IWOTH);
  158.  
  159.   if (IS_DOS_DIR(dosmode)) {
  160.     /* We never make directories read only for the owner as under DOS a user
  161.        can always create a file in a read-only directory. */
  162.     result |= (S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH | S_IWUSR);
  163.     /* Apply directory mask */
  164.     result &= lp_dir_mode(SNUM(cnum));
  165.     /* Add in force bits */
  166.     result |= lp_force_dir_mode(SNUM(cnum));
  167.   } else { 
  168.     if (MAP_ARCHIVE(cnum) && IS_DOS_ARCHIVE(dosmode))
  169.       result |= S_IXUSR;
  170.  
  171.     if (MAP_SYSTEM(cnum) && IS_DOS_SYSTEM(dosmode))
  172.       result |= S_IXGRP;
  173.  
  174.     if (MAP_HIDDEN(cnum) && IS_DOS_HIDDEN(dosmode))
  175.       result |= S_IXOTH;  
  176.  
  177.     /* Apply mode mask */
  178.     result &= lp_create_mode(SNUM(cnum));
  179.     /* Add in force bits */
  180.     result |= lp_force_create_mode(SNUM(cnum));
  181.   }
  182.   return(result);
  183. }
  184.  
  185.  
  186. /****************************************************************************
  187.   change a unix mode to a dos mode
  188. ****************************************************************************/
  189. int dos_mode(int cnum,char *path,struct stat *sbuf)
  190. {
  191.   int result = 0;
  192.   extern struct current_user current_user;
  193.  
  194.   DEBUG(8,("dos_mode: %d %s\n", cnum, path));
  195.  
  196.   if (CAN_WRITE(cnum) && !lp_alternate_permissions(SNUM(cnum))) {
  197.     if (!((sbuf->st_mode & S_IWOTH) ||
  198.       Connections[cnum].admin_user ||
  199.       ((sbuf->st_mode & S_IWUSR) && current_user.uid==sbuf->st_uid) ||
  200.       ((sbuf->st_mode & S_IWGRP) && 
  201.        in_group(sbuf->st_gid,current_user.gid,
  202.             current_user.ngroups,current_user.igroups))))
  203.       result |= aRONLY;
  204.   } else {
  205.     if ((sbuf->st_mode & S_IWUSR) == 0)
  206.       result |= aRONLY;
  207.   }
  208.  
  209.   if (MAP_ARCHIVE(cnum) && ((sbuf->st_mode & S_IXUSR) != 0))
  210.     result |= aARCH;
  211.  
  212.   if (MAP_SYSTEM(cnum) && ((sbuf->st_mode & S_IXGRP) != 0))
  213.     result |= aSYSTEM;
  214.  
  215.   if (MAP_HIDDEN(cnum) && ((sbuf->st_mode & S_IXOTH) != 0))
  216.     result |= aHIDDEN;   
  217.   
  218.   if (S_ISDIR(sbuf->st_mode))
  219.     result = aDIR | (result & aRONLY);
  220.  
  221. #ifdef S_ISLNK
  222. #if LINKS_READ_ONLY
  223.   if (S_ISLNK(sbuf->st_mode) && S_ISDIR(sbuf->st_mode))
  224.     result |= aRONLY;
  225. #endif
  226. #endif
  227.  
  228.   /* hide files with a name starting with a . */
  229.   if (lp_hide_dot_files(SNUM(cnum)))
  230.     {
  231.       char *p = strrchr(path,'/');
  232.       if (p)
  233.     p++;
  234.       else
  235.     p = path;
  236.       
  237.       if (p[0] == '.' && p[1] != '.' && p[1] != 0)
  238.     result |= aHIDDEN;
  239.     }
  240.  
  241.   /* Optimization : Only call is_hidden_path if it's not already
  242.      hidden. */
  243.   if (!(result & aHIDDEN) && IS_HIDDEN_PATH(cnum,path))
  244.   {
  245.     result |= aHIDDEN;
  246.   }
  247.  
  248.   DEBUG(8,("dos_mode returning "));
  249.  
  250.   if (result & aHIDDEN) DEBUG(8, ("h"));
  251.   if (result & aRONLY ) DEBUG(8, ("r"));
  252.   if (result & aSYSTEM) DEBUG(8, ("s"));
  253.   if (result & aDIR   ) DEBUG(8, ("d"));
  254.   if (result & aARCH  ) DEBUG(8, ("a"));
  255.  
  256.   DEBUG(8,("\n"));
  257.  
  258.   return(result);
  259. }
  260.  
  261. /*******************************************************************
  262. chmod a file - but preserve some bits
  263. ********************************************************************/
  264. int dos_chmod(int cnum,char *fname,int dosmode,struct stat *st)
  265. {
  266.   struct stat st1;
  267.   int mask=0;
  268.   int tmp;
  269.   int unixmode;
  270.  
  271.   if (!st) {
  272.     st = &st1;
  273.     if (sys_stat(fname,st)) return(-1);
  274.   }
  275.  
  276.   if (S_ISDIR(st->st_mode)) dosmode |= aDIR;
  277.  
  278.   if (dos_mode(cnum,fname,st) == dosmode) return(0);
  279.  
  280.   unixmode = unix_mode(cnum,dosmode);
  281.  
  282.   /* preserve the s bits */
  283.   mask |= (S_ISUID | S_ISGID);
  284.  
  285.   /* preserve the t bit */
  286. #ifdef S_ISVTX
  287.   mask |= S_ISVTX;
  288. #endif
  289.  
  290.   /* possibly preserve the x bits */
  291.   if (!MAP_ARCHIVE(cnum)) mask |= S_IXUSR;
  292.   if (!MAP_SYSTEM(cnum)) mask |= S_IXGRP;
  293.   if (!MAP_HIDDEN(cnum)) mask |= S_IXOTH;
  294.  
  295.   unixmode |= (st->st_mode & mask);
  296.  
  297.   /* if we previously had any r bits set then leave them alone */
  298.   if ((tmp = st->st_mode & (S_IRUSR|S_IRGRP|S_IROTH))) {
  299.     unixmode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
  300.     unixmode |= tmp;
  301.   }
  302.  
  303.   /* if we previously had any w bits set then leave them alone 
  304.    if the new mode is not rdonly */
  305.   if (!IS_DOS_READONLY(dosmode) &&
  306.       (tmp = st->st_mode & (S_IWUSR|S_IWGRP|S_IWOTH))) {
  307.     unixmode &= ~(S_IWUSR|S_IWGRP|S_IWOTH);
  308.     unixmode |= tmp;
  309.   }
  310.  
  311.   return(sys_chmod(fname,unixmode));
  312. }
  313.  
  314. /*******************************************************************
  315. Wrapper around sys_utime that possibly allows DOS semantics rather
  316. than POSIX.
  317. *******************************************************************/
  318.  
  319. int file_utime(int cnum, char *fname, struct utimbuf *times)
  320. {
  321.   extern struct current_user current_user;
  322.   struct stat sb;
  323.   int ret = -1;
  324.  
  325.   errno = 0;
  326.  
  327.   if(sys_utime(fname, times) == 0)
  328.     return 0;
  329.  
  330.   if((errno != EPERM) && (errno != EACCES))
  331.     return -1;
  332.  
  333.   if(!lp_dos_filetimes(SNUM(cnum)))
  334.     return -1;
  335.  
  336.   /* We have permission (given by the Samba admin) to
  337.      break POSIX semantics and allow a user to change
  338.      the time on a file they don't own but can write to
  339.      (as DOS does).
  340.    */
  341.  
  342.   if(sys_stat(fname,&sb) != 0)
  343.     return -1;
  344.  
  345.   /* Check if we have write access. */
  346.   if (CAN_WRITE(cnum)) {
  347.       if (((sb.st_mode & S_IWOTH) ||
  348.            Connections[cnum].admin_user ||
  349.            ((sb.st_mode & S_IWUSR) && current_user.uid==sb.st_uid) ||
  350.            ((sb.st_mode & S_IWGRP) &&
  351.         in_group(sb.st_gid,current_user.gid,
  352.              current_user.ngroups,current_user.igroups)))) {
  353.           /* We are allowed to become root and change the filetime. */
  354.           become_root(False);
  355.           ret = sys_utime(fname, times);
  356.           unbecome_root(False);
  357.       }
  358.   }
  359.  
  360.   return ret;
  361. }
  362.   
  363. /*******************************************************************
  364. Change a filetime - possibly allowing DOS semantics.
  365. *******************************************************************/
  366.  
  367. BOOL set_filetime(int cnum, char *fname, time_t mtime)
  368. {
  369.   struct utimbuf times;
  370.  
  371.   if (null_mtime(mtime)) return(True);
  372.  
  373.   times.modtime = times.actime = mtime;
  374.  
  375.   if (file_utime(cnum, fname, ×)) {
  376.     DEBUG(4,("set_filetime(%s) failed: %s\n",fname,strerror(errno)));
  377.   }
  378.   
  379.   return(True);
  380.  
  381. /****************************************************************************
  382. check if two filenames are equal
  383.  
  384. this needs to be careful about whether we are case sensitive
  385. ****************************************************************************/
  386. static BOOL fname_equal(char *name1, char *name2)
  387. {
  388.   int l1 = strlen(name1);
  389.   int l2 = strlen(name2);
  390.  
  391.   /* handle filenames ending in a single dot */
  392.   if (l1-l2 == 1 && name1[l1-1] == '.' && lp_strip_dot())
  393.     {
  394.       BOOL ret;
  395.       name1[l1-1] = 0;
  396.       ret = fname_equal(name1,name2);
  397.       name1[l1-1] = '.';
  398.       return(ret);
  399.     }
  400.  
  401.   if (l2-l1 == 1 && name2[l2-1] == '.' && lp_strip_dot())
  402.     {
  403.       BOOL ret;
  404.       name2[l2-1] = 0;
  405.       ret = fname_equal(name1,name2);
  406.       name2[l2-1] = '.';
  407.       return(ret);
  408.     }
  409.  
  410.   /* now normal filename handling */
  411.   if (case_sensitive)
  412.     return(strcmp(name1,name2) == 0);
  413.  
  414.   return(strequal(name1,name2));
  415. }
  416.  
  417.  
  418. /****************************************************************************
  419. mangle the 2nd name and check if it is then equal to the first name
  420. ****************************************************************************/
  421. static BOOL mangled_equal(char *name1, char *name2)
  422. {
  423.   pstring tmpname;
  424.  
  425.   if (is_8_3(name2, True))
  426.     return(False);
  427.  
  428.   pstrcpy(tmpname,name2);
  429.   mangle_name_83(tmpname,sizeof(pstring)-1);
  430.  
  431.   return(strequal(name1,tmpname));
  432. }
  433.  
  434.  
  435. /****************************************************************************
  436. scan a directory to find a filename, matching without case sensitivity
  437.  
  438. If the name looks like a mangled name then try via the mangling functions
  439. ****************************************************************************/
  440. static BOOL scan_directory(char *path, char *name,int cnum,BOOL docache)
  441. {
  442.   void *cur_dir;
  443.   char *dname;
  444.   BOOL mangled;
  445.   pstring name2;
  446.  
  447.   mangled = is_mangled(name);
  448.  
  449.   /* handle null paths */
  450.   if (*path == 0)
  451.     path = ".";
  452.  
  453.   if (docache && (dname = DirCacheCheck(path,name,SNUM(cnum)))) {
  454.     pstrcpy(name, dname);    
  455.     return(True);
  456.   }      
  457.  
  458.   /*
  459.    * The incoming name can be mangled, and if we de-mangle it
  460.    * here it will not compare correctly against the filename (name2)
  461.    * read from the directory and then mangled by the name_map_mangle()
  462.    * call. We need to mangle both names or neither.
  463.    * (JRA).
  464.    */
  465.   if (mangled)
  466.     mangled = !check_mangled_stack(name);
  467.  
  468.   /* open the directory */
  469.   if (!(cur_dir = OpenDir(cnum, path, True))) 
  470.     {
  471.       DEBUG(3,("scan dir didn't open dir [%s]\n",path));
  472.       return(False);
  473.     }
  474.  
  475.   /* now scan for matching names */
  476.   while ((dname = ReadDirName(cur_dir))) 
  477.     {
  478.       if (*dname == '.' &&
  479.       (strequal(dname,".") || strequal(dname,"..")))
  480.     continue;
  481.  
  482.       pstrcpy(name2,dname);
  483.       if (!name_map_mangle(name2,False,SNUM(cnum))) continue;
  484.  
  485.       if ((mangled && mangled_equal(name,name2))
  486.       || fname_equal(name, name2))
  487.     {
  488.       /* we've found the file, change it's name and return */
  489.       if (docache) DirCacheAdd(path,name,dname,SNUM(cnum));
  490.       pstrcpy(name, dname);
  491.       CloseDir(cur_dir);
  492.       return(True);
  493.     }
  494.     }
  495.  
  496.   CloseDir(cur_dir);
  497.   return(False);
  498. }
  499.  
  500. /****************************************************************************
  501. This routine is called to convert names from the dos namespace to unix
  502. namespace. It needs to handle any case conversions, mangling, format
  503. changes etc.
  504.  
  505. We assume that we have already done a chdir() to the right "root" directory
  506. for this service.
  507.  
  508. The function will return False if some part of the name except for the last
  509. part cannot be resolved
  510.  
  511. If the saved_last_component != 0, then the unmodified last component
  512. of the pathname is returned there. This is used in an exceptional
  513. case in reply_mv (so far). If saved_last_component == 0 then nothing
  514. is returned there.
  515.  
  516. The bad_path arg is set to True if the filename walk failed. This is
  517. used to pick the correct error code to return between ENOENT and ENOTDIR
  518. as Windows applications depend on ERRbadpath being returned if a component
  519. of a pathname does not exist.
  520. ****************************************************************************/
  521. BOOL unix_convert(char *name,int cnum,pstring saved_last_component, BOOL *bad_path)
  522. {
  523.   struct stat st;
  524.   char *start, *end;
  525.   pstring dirpath;
  526.   int saved_errno;
  527.  
  528.   *dirpath = 0;
  529.   *bad_path = False;
  530.  
  531.   if(saved_last_component)
  532.     *saved_last_component = 0;
  533.  
  534.   /* convert to basic unix format - removing \ chars and cleaning it up */
  535.   unix_format(name);
  536.   unix_clean_name(name);
  537.  
  538.   /* names must be relative to the root of the service - trim any leading /.
  539.    also trim trailing /'s */
  540.   trim_string(name,"/","/");
  541.  
  542.   /*
  543.    * Ensure saved_last_component is valid even if file exists.
  544.    */
  545.   if(saved_last_component) {
  546.     end = strrchr(name, '/');
  547.     if(end)
  548.       pstrcpy(saved_last_component, end + 1);
  549.     else
  550.       pstrcpy(saved_last_component, name);
  551.   }
  552.  
  553.   if (!case_sensitive && 
  554.       (!case_preserve || (is_8_3(name, False) && !short_case_preserve)))
  555.     strnorm(name);
  556.  
  557.   /* check if it's a printer file */
  558.   if (Connections[cnum].printer)
  559.     {
  560.       if ((! *name) || strchr(name,'/') || !is_8_3(name, True))
  561.     {
  562.       char *s;
  563.       fstring name2;
  564.       slprintf(name2,sizeof(name2)-1,"%.6s.XXXXXX",remote_machine);
  565.       /* sanitise the name */
  566.       for (s=name2 ; *s ; s++)
  567.         if (!issafe(*s)) *s = '_';
  568.       pstrcpy(name,(char *)mktemp(name2));      
  569.     }      
  570.       return(True);
  571.     }
  572.  
  573.   /* stat the name - if it exists then we are all done! */
  574.   if (sys_stat(name,&st) == 0)
  575.     return(True);
  576.  
  577.   saved_errno = errno;
  578.  
  579.   DEBUG(5,("unix_convert(%s,%d)\n",name,cnum));
  580.  
  581.   /* a special case - if we don't have any mangling chars and are case
  582.      sensitive then searching won't help */
  583.   if (case_sensitive && !is_mangled(name) && 
  584.       !lp_strip_dot() && !use_mangled_map && (saved_errno != ENOENT))
  585.     return(False);
  586.  
  587.   /* now we need to recursively match the name against the real 
  588.      directory structure */
  589.  
  590.   start = name;
  591.   while (strncmp(start,"./",2) == 0)
  592.     start += 2;
  593.  
  594.   /* now match each part of the path name separately, trying the names
  595.      as is first, then trying to scan the directory for matching names */
  596.   for (;start;start = (end?end+1:(char *)NULL)) 
  597.     {
  598.       /* pinpoint the end of this section of the filename */
  599.       end = strchr(start, '/');
  600.  
  601.       /* chop the name at this point */
  602.       if (end)     *end = 0;
  603.  
  604.       if(saved_last_component != 0)
  605.         pstrcpy(saved_last_component, end ? end + 1 : start);
  606.  
  607.       /* check if the name exists up to this point */
  608.       if (sys_stat(name, &st) == 0) 
  609.     {
  610.       /* it exists. it must either be a directory or this must be
  611.          the last part of the path for it to be OK */
  612.       if (end && !(st.st_mode & S_IFDIR)) 
  613.         {
  614.           /* an intermediate part of the name isn't a directory */
  615.           DEBUG(5,("Not a dir %s\n",start));
  616.           *end = '/';
  617.           return(False);
  618.         }
  619.     }
  620.       else 
  621.     {
  622.       pstring rest;
  623.  
  624.       *rest = 0;
  625.  
  626.       /* remember the rest of the pathname so it can be restored
  627.          later */
  628.       if (end) pstrcpy(rest,end+1);
  629.  
  630.       /* try to find this part of the path in the directory */
  631.       if (strchr(start,'?') || strchr(start,'*') ||
  632.           !scan_directory(dirpath, start, cnum, end?True:False))
  633.         {
  634.           if (end) 
  635.         {
  636.           /* an intermediate part of the name can't be found */
  637.           DEBUG(5,("Intermediate not found %s\n",start));
  638.           *end = '/';
  639.                   /* We need to return the fact that the intermediate
  640.                      name resolution failed. This is used to return an
  641.                      error of ERRbadpath rather than ERRbadfile. Some
  642.                      Windows applications depend on the difference between
  643.                      these two errors.
  644.                    */
  645.                   *bad_path = True;
  646.           return(False);
  647.         }
  648.           
  649.           /* just the last part of the name doesn't exist */
  650.           /* we may need to strupper() or strlower() it in case
  651.          this conversion is being used for file creation 
  652.          purposes */
  653.           /* if the filename is of mixed case then don't normalise it */
  654.           if (!case_preserve && 
  655.           (!strhasupper(start) || !strhaslower(start)))        
  656.         strnorm(start);
  657.  
  658.           /* check on the mangled stack to see if we can recover the 
  659.          base of the filename */
  660.           if (is_mangled(start))
  661.         check_mangled_stack(start);
  662.  
  663.           DEBUG(5,("New file %s\n",start));
  664.           return(True); 
  665.         }
  666.  
  667.       /* restore the rest of the string */
  668.       if (end) 
  669.         {
  670.           pstrcpy(start+strlen(start)+1,rest);
  671.           end = start + strlen(start);
  672.         }
  673.     }
  674.  
  675.       /* add to the dirpath that we have resolved so far */
  676.       if (*dirpath) pstrcat(dirpath,"/");
  677.       pstrcat(dirpath,start);
  678.  
  679.       /* restore the / that we wiped out earlier */
  680.       if (end) *end = '/';
  681.     }
  682.   
  683.   /* the name has been resolved */
  684.   DEBUG(5,("conversion finished %s\n",name));
  685.   return(True);
  686. }
  687.  
  688.  
  689. /****************************************************************************
  690. normalise for DOS usage 
  691. ****************************************************************************/
  692. static void disk_norm(int *bsize,int *dfree,int *dsize)
  693. {
  694.   /* check if the disk is beyond the max disk size */
  695.   int maxdisksize = lp_maxdisksize();
  696.   if (maxdisksize) {
  697.     /* convert to blocks - and don't overflow */
  698.     maxdisksize = ((maxdisksize*1024)/(*bsize))*1024;
  699.     if (*dsize > maxdisksize) *dsize = maxdisksize;
  700.     if (*dfree > maxdisksize) *dfree = maxdisksize-1; /* the -1 should stop 
  701.                              applications getting 
  702.                              div by 0 errors */
  703.   }  
  704.  
  705.   while (*dfree > WORDMAX || *dsize > WORDMAX || *bsize < 512) 
  706.     {
  707.       *dfree /= 2;
  708.       *dsize /= 2;
  709.       *bsize *= 2;
  710.       if (*bsize > WORDMAX )
  711.     {
  712.       *bsize = WORDMAX;
  713.       if (*dsize > WORDMAX)
  714.         *dsize = WORDMAX;
  715.       if (*dfree >  WORDMAX)
  716.         *dfree = WORDMAX;
  717.       break;
  718.     }
  719.     }
  720. }
  721.  
  722. /****************************************************************************
  723.   return number of 1K blocks available on a path and total number 
  724. ****************************************************************************/
  725. int disk_free(char *path,int *bsize,int *dfree,int *dsize)
  726. {
  727.   char *df_command = lp_dfree_command();
  728.   int dfree_retval;
  729. #ifdef QUOTAS
  730.   int dfreeq_retval;
  731.   int dfreeq = 0;
  732.   int bsizeq = *bsize;
  733.   int dsizeq = *dsize;
  734. #endif
  735.  
  736. #ifndef NO_STATFS
  737. #ifdef USE_STATVFS
  738.   struct statvfs fs;
  739. #else
  740. #ifdef ULTRIX
  741.   struct fs_data fs;
  742. #else
  743.   struct statfs fs;
  744. #endif
  745. #endif
  746. #endif
  747.  
  748.   /* possibly use system() to get the result */
  749.   if (df_command && *df_command)
  750.     {
  751.       int ret;
  752.       pstring syscmd;
  753.       pstring outfile;
  754.       
  755.       slprintf(outfile,sizeof(outfile)-1, "%s/dfree.smb.%d",tmpdir(),(int)getpid());
  756.       slprintf(syscmd,sizeof(syscmd)-1,"%s %s",df_command,path);
  757.       standard_sub_basic(syscmd);
  758.  
  759.       ret = smbrun(syscmd,outfile,False);
  760.       DEBUG(3,("Running the command `%s' gave %d\n",syscmd,ret));
  761.       
  762.       {
  763.         FILE *f = fopen(outfile,"r");    
  764.         *dsize = 0;
  765.         *dfree = 0;
  766.         *bsize = 1024;
  767.         if (f)
  768.           {
  769.             fscanf(f,"%d %d %d",dsize,dfree,bsize);
  770.             fclose(f);
  771.           }
  772.         else
  773.           DEBUG(0,("Can't open %s\n",outfile));
  774.       }
  775.       
  776.       unlink(outfile);
  777.       disk_norm(bsize,dfree,dsize);
  778.       dfree_retval = ((*bsize)/1024)*(*dfree);
  779. #ifdef QUOTAS
  780.       /* Ensure we return the min value between the users quota and
  781.          what's free on the disk. Thanks to Albrecht Gebhardt 
  782.          <albrecht.gebhardt@uni-klu.ac.at> for this fix.
  783.       */
  784.       if (disk_quotas(path, &bsizeq, &dfreeq, &dsizeq))
  785.         {
  786.           disk_norm(&bsizeq, &dfreeq, &dsizeq);
  787.           dfreeq_retval = ((bsizeq)/1024)*(dfreeq);
  788.           dfree_retval =  ( dfree_retval < dfreeq_retval ) ? 
  789.                            dfree_retval : dfreeq_retval ;
  790.           /* maybe dfree and dfreeq are calculated using different bsizes 
  791.              so convert dfree from bsize into bsizeq */
  792.           /* avoid overflows due to multiplication, so do not:
  793.                 *dfree = ((*dfree) * (*bsize)) / (bsizeq); 
  794.              bsize and bsizeq are powers of 2 so its better to
  795.              to divide them getting a multiplication or division factor
  796.              for dfree. Rene Nieuwenhuizen (07-10-1997) */
  797.           if (*bsize >= bsizeq) 
  798.             *dfree = *dfree * (*bsize / bsizeq);
  799.           else 
  800.             *dfree = *dfree / (bsizeq / *bsize);
  801.           *dfree = ( *dfree < dfreeq ) ? *dfree : dfreeq ; 
  802.           *bsize = bsizeq;
  803.           *dsize = dsizeq;
  804.         }
  805. #endif
  806.       return(dfree_retval);
  807.     }
  808.  
  809. #ifdef NO_STATFS
  810.   DEBUG(1,("Warning - no statfs function\n"));
  811.   return(1);
  812. #else
  813. #ifdef STATFS4
  814.   if (statfs(path,&fs,sizeof(fs),0) != 0)
  815. #else
  816. #ifdef USE_STATVFS
  817.     if (statvfs(path, &fs))
  818. #else
  819. #ifdef STATFS3
  820.       if (statfs(path,&fs,sizeof(fs)) == -1)     
  821. #else
  822.     if (statfs(path,&fs) == -1)
  823. #endif /* STATFS3 */
  824. #endif /* USE_STATVFS */
  825. #endif /* STATFS4 */
  826.       {
  827.         DEBUG(3,("dfree call failed code errno=%d\n",errno));
  828.         *bsize = 1024;
  829.         *dfree = 1;
  830.         *dsize = 1;
  831.         return(((*bsize)/1024)*(*dfree));
  832.       }
  833.  
  834. #ifdef ULTRIX
  835.   *bsize = 1024;
  836.   *dfree = fs.fd_req.bfree;
  837.   *dsize = fs.fd_req.btot;
  838. #else
  839. #ifdef USE_STATVFS
  840.   *bsize = fs.f_frsize;
  841. #else
  842. #ifdef USE_F_FSIZE
  843.   /* eg: osf1 has f_fsize = fundamental filesystem block size, 
  844.      f_bsize = optimal transfer block size (MX: 94-04-19) */
  845.   *bsize = fs.f_fsize;
  846. #else
  847.   *bsize = fs.f_bsize;
  848. #endif /* STATFS3 */
  849. #endif /* USE_STATVFS */
  850.  
  851. #ifdef STATFS4
  852.   *dfree = fs.f_bfree;
  853. #else
  854.   *dfree = fs.f_bavail;
  855. #endif /* STATFS4 */
  856.   *dsize = fs.f_blocks;
  857. #endif /* ULTRIX */
  858.  
  859. #if defined(SCO) || defined(ISC) || defined(MIPS)
  860.   *bsize = 512;
  861. #endif
  862.  
  863. /* handle rediculous bsize values - some OSes are broken */
  864. if ((*bsize) < 512 || (*bsize)>0xFFFF) *bsize = 1024;
  865.  
  866.   disk_norm(bsize,dfree,dsize);
  867.  
  868.   if (*bsize < 256)
  869.     *bsize = 512;
  870.   if ((*dsize)<1)
  871.     {
  872.       DEBUG(0,("dfree seems to be broken on your system\n"));
  873.       *dsize = 20*1024*1024/(*bsize);
  874.       *dfree = MAX(1,*dfree);
  875.     }
  876.   dfree_retval = ((*bsize)/1024)*(*dfree);
  877. #ifdef QUOTAS
  878.   /* Ensure we return the min value between the users quota and
  879.      what's free on the disk. Thanks to Albrecht Gebhardt 
  880.      <albrecht.gebhardt@uni-klu.ac.at> for this fix.
  881.   */
  882.   if (disk_quotas(path, &bsizeq, &dfreeq, &dsizeq))
  883.     {
  884.       disk_norm(&bsizeq, &dfreeq, &dsizeq);
  885.       dfreeq_retval = ((bsizeq)/1024)*(dfreeq);
  886.       dfree_retval = ( dfree_retval < dfreeq_retval ) ? 
  887.                        dfree_retval : dfreeq_retval ;
  888.       /* maybe dfree and dfreeq are calculated using different bsizes 
  889.          so convert dfree from bsize into bsizeq */
  890.       /* avoid overflows due to multiplication, so do not:
  891.               *dfree = ((*dfree) * (*bsize)) / (bsizeq); 
  892.        bsize and bsizeq are powers of 2 so its better to
  893.        to divide them getting a multiplication or division factor
  894.        for dfree. Rene Nieuwenhuizen (07-10-1997) */
  895.       if (*bsize >= bsizeq)
  896.         *dfree = *dfree * (*bsize / bsizeq);
  897.       else
  898.         *dfree = *dfree / (bsizeq / *bsize);
  899.       *dfree = ( *dfree < dfreeq ) ? *dfree : dfreeq ;
  900.       *bsize = bsizeq;
  901.       *dsize = dsizeq;
  902.     }
  903. #endif
  904.   return(dfree_retval);
  905. #endif
  906. }
  907.  
  908.  
  909. /****************************************************************************
  910. wrap it to get filenames right
  911. ****************************************************************************/
  912. int sys_disk_free(char *path,int *bsize,int *dfree,int *dsize)
  913. {
  914.   return(disk_free(dos_to_unix(path,False),bsize,dfree,dsize));
  915. }
  916.  
  917.  
  918.  
  919. /****************************************************************************
  920. check a filename - possibly caling reducename
  921.  
  922. This is called by every routine before it allows an operation on a filename.
  923. It does any final confirmation necessary to ensure that the filename is
  924. a valid one for the user to access.
  925. ****************************************************************************/
  926. BOOL check_name(char *name,int cnum)
  927. {
  928.   BOOL ret;
  929.  
  930.   errno = 0;
  931.  
  932.   if( IS_VETO_PATH(cnum, name)) 
  933.     {
  934.       DEBUG(5,("file path name %s vetoed\n",name));
  935.       return(0);
  936.     }
  937.  
  938.   ret = reduce_name(name,Connections[cnum].connectpath,lp_widelinks(SNUM(cnum)));
  939.  
  940.   /* Check if we are allowing users to follow symlinks */
  941.   /* Patch from David Clerc <David.Clerc@cui.unige.ch>
  942.      University of Geneva */
  943.  
  944. #ifdef S_ISLNK
  945.   if (!lp_symlinks(SNUM(cnum)))
  946.     {
  947.       struct stat statbuf;
  948.       if ( (sys_lstat(name,&statbuf) != -1) &&
  949.           (S_ISLNK(statbuf.st_mode)) )
  950.         {
  951.           DEBUG(3,("check_name: denied: file path name %s is a symlink\n",name));
  952.           ret=0; 
  953.         }
  954.     }
  955. #endif
  956.  
  957.   if (!ret)
  958.     DEBUG(5,("check_name on %s failed\n",name));
  959.  
  960.   return(ret);
  961. }
  962.  
  963. /****************************************************************************
  964. check a filename - possibly caling reducename
  965. ****************************************************************************/
  966. static void check_for_pipe(char *fname)
  967. {
  968.   /* special case of pipe opens */
  969.   char s[10];
  970.   StrnCpy(s,fname,9);
  971.   strlower(s);
  972.   if (strstr(s,"pipe/"))
  973.     {
  974.       DEBUG(3,("Rejecting named pipe open for %s\n",fname));
  975.       unix_ERR_class = ERRSRV;
  976.       unix_ERR_code = ERRaccess;
  977.     }
  978. }
  979.  
  980. /****************************************************************************
  981. fd support routines - attempt to do a sys_open
  982. ****************************************************************************/
  983. static int fd_attempt_open(char *fname, int flags, int mode)
  984. {
  985.   int fd = sys_open(fname,flags,mode);
  986.  
  987.   /* Fix for files ending in '.' */
  988.   if((fd == -1) && (errno == ENOENT) &&
  989.      (strchr(fname,'.')==NULL))
  990.     {
  991.       pstrcat(fname,".");
  992.       fd = sys_open(fname,flags,mode);
  993.     }
  994.  
  995. #if (defined(ENAMETOOLONG) && defined(HAVE_PATHCONF))
  996.   if ((fd == -1) && (errno == ENAMETOOLONG))
  997.     {
  998.       int max_len;
  999.       char *p = strrchr(fname, '/');
  1000.  
  1001.       if (p == fname)   /* name is "/xxx" */
  1002.         {
  1003.           max_len = pathconf("/", _PC_NAME_MAX);
  1004.           p++;
  1005.         }
  1006.       else if ((p == NULL) || (p == fname))
  1007.         {
  1008.           p = fname;
  1009.           max_len = pathconf(".", _PC_NAME_MAX);
  1010.         }
  1011.       else
  1012.         {
  1013.           *p = '\0';
  1014.           max_len = pathconf(fname, _PC_NAME_MAX);
  1015.           *p = '/';
  1016.           p++;
  1017.         }
  1018.       if (strlen(p) > max_len)
  1019.         {
  1020.           char tmp = p[max_len];
  1021.  
  1022.           p[max_len] = '\0';
  1023.           if ((fd = sys_open(fname,flags,mode)) == -1)
  1024.             p[max_len] = tmp;
  1025.         }
  1026.     }
  1027. #endif
  1028.   return fd;
  1029. }
  1030.  
  1031. /****************************************************************************
  1032. fd support routines - attempt to find an already open file by dev
  1033. and inode - increments the ref_count of the returned file_fd_struct *.
  1034. ****************************************************************************/
  1035. static file_fd_struct *fd_get_already_open(struct stat *sbuf)
  1036. {
  1037.   int i;
  1038.   file_fd_struct *fd_ptr;
  1039.  
  1040.   if(sbuf == 0)
  1041.     return 0;
  1042.  
  1043.   for(i = 0; i <= max_file_fd_used; i++) {
  1044.     fd_ptr = &FileFd[i];
  1045.     if((fd_ptr->ref_count > 0) &&
  1046.        (((uint32)sbuf->st_dev) == fd_ptr->dev) &&
  1047.        (((uint32)sbuf->st_ino) == fd_ptr->inode)) {
  1048.       fd_ptr->ref_count++;
  1049.       DEBUG(3,
  1050.        ("Re-used file_fd_struct %d, dev = %x, inode = %x, ref_count = %d\n",
  1051.         i, fd_ptr->dev, fd_ptr->inode, fd_ptr->ref_count));
  1052.       return fd_ptr;
  1053.     }
  1054.   }
  1055.   return 0;
  1056. }
  1057.  
  1058. /****************************************************************************
  1059. fd support routines - attempt to find a empty slot in the FileFd array.
  1060. Increments the ref_count of the returned entry.
  1061. ****************************************************************************/
  1062. static file_fd_struct *fd_get_new(void)
  1063. {
  1064.   int i;
  1065.   file_fd_struct *fd_ptr;
  1066.  
  1067.   for(i = 0; i < MAX_OPEN_FILES; i++) {
  1068.     fd_ptr = &FileFd[i];
  1069.     if(fd_ptr->ref_count == 0) {
  1070.       fd_ptr->dev = (uint32)-1;
  1071.       fd_ptr->inode = (uint32)-1;
  1072.       fd_ptr->fd = -1;
  1073.       fd_ptr->fd_readonly = -1;
  1074.       fd_ptr->fd_writeonly = -1;
  1075.       fd_ptr->real_open_flags = -1;
  1076.       fd_ptr->ref_count++;
  1077.       /* Increment max used counter if neccessary, cuts down
  1078.      on search time when re-using */
  1079.       if(i > max_file_fd_used)
  1080.         max_file_fd_used = i;
  1081.       DEBUG(3,("Allocated new file_fd_struct %d, dev = %x, inode = %x\n",
  1082.                i, fd_ptr->dev, fd_ptr->inode));
  1083.       return fd_ptr;
  1084.     }
  1085.   }
  1086.   DEBUG(1,("ERROR! Out of file_fd structures - perhaps increase MAX_OPEN_FILES?\n"));
  1087.   return 0;
  1088. }
  1089.  
  1090. /****************************************************************************
  1091. fd support routines - attempt to re-open an already open fd as O_RDWR.
  1092. Save the already open fd (we cannot close due to POSIX file locking braindamage.
  1093. ****************************************************************************/
  1094. static void fd_attempt_reopen(char *fname, int mode, file_fd_struct *fd_ptr)
  1095. {
  1096.   int fd = sys_open( fname, O_RDWR, mode);
  1097.  
  1098.   if(fd == -1)
  1099.     return;
  1100.  
  1101.   if(fd_ptr->real_open_flags == O_RDONLY)
  1102.     fd_ptr->fd_readonly = fd_ptr->fd;
  1103.   if(fd_ptr->real_open_flags == O_WRONLY)
  1104.     fd_ptr->fd_writeonly = fd_ptr->fd;
  1105.  
  1106.   fd_ptr->fd = fd;
  1107.   fd_ptr->real_open_flags = O_RDWR;
  1108. }
  1109.  
  1110. /****************************************************************************
  1111. fd support routines - attempt to close the file referenced by this fd.
  1112. Decrements the ref_count and returns it.
  1113. ****************************************************************************/
  1114. static int fd_attempt_close(file_fd_struct *fd_ptr)
  1115. {
  1116.   DEBUG(3,("fd_attempt_close on file_fd_struct %d, fd = %d, dev = %x, inode = %x, open_flags = %d, ref_count = %d.\n",
  1117.        fd_ptr - &FileFd[0],
  1118.        fd_ptr->fd, fd_ptr->dev, fd_ptr->inode,
  1119.        fd_ptr->real_open_flags,
  1120.        fd_ptr->ref_count));
  1121.   if(fd_ptr->ref_count > 0) {
  1122.     fd_ptr->ref_count--;
  1123.     if(fd_ptr->ref_count == 0) {
  1124.       if(fd_ptr->fd != -1)
  1125.         close(fd_ptr->fd);
  1126.       if(fd_ptr->fd_readonly != -1)
  1127.     close(fd_ptr->fd_readonly);
  1128.       if(fd_ptr->fd_writeonly != -1)
  1129.     close(fd_ptr->fd_writeonly);
  1130.       fd_ptr->fd = -1;
  1131.       fd_ptr->fd_readonly = -1;
  1132.       fd_ptr->fd_writeonly = -1;
  1133.       fd_ptr->real_open_flags = -1;
  1134.       fd_ptr->dev = (uint32)-1;
  1135.       fd_ptr->inode = (uint32)-1;
  1136.     }
  1137.   } 
  1138.  return fd_ptr->ref_count;
  1139. }
  1140.  
  1141. /****************************************************************************
  1142. open a file
  1143. ****************************************************************************/
  1144. static void open_file(int fnum,int cnum,char *fname1,int flags,int mode, struct stat *sbuf)
  1145. {
  1146.   extern struct current_user current_user;
  1147.   pstring fname;
  1148.   struct stat statbuf;
  1149.   file_fd_struct *fd_ptr;
  1150.   files_struct *fsp = &Files[fnum];
  1151.   int accmode = (flags & (O_RDONLY | O_WRONLY | O_RDWR));
  1152.  
  1153.   fsp->open = False;
  1154.   fsp->fd_ptr = 0;
  1155.   fsp->granted_oplock = False;
  1156.   errno = EPERM;
  1157.  
  1158.   pstrcpy(fname,fname1);
  1159.  
  1160.   /* check permissions */
  1161.  
  1162.   /*
  1163.    * This code was changed after seeing a client open request 
  1164.    * containing the open mode of (DENY_WRITE/read-only) with
  1165.    * the 'create if not exist' bit set. The previous code
  1166.    * would fail to open the file read only on a read-only share
  1167.    * as it was checking the flags parameter  directly against O_RDONLY,
  1168.    * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
  1169.    * JRA.
  1170.    */
  1171.  
  1172.   if (!CAN_WRITE(cnum) && !Connections[cnum].printer) {
  1173.     /* It's a read-only share - fail if we wanted to write. */
  1174.     if(accmode != O_RDONLY) {
  1175.       DEBUG(3,("Permission denied opening %s\n",fname));
  1176.       check_for_pipe(fname);
  1177.       return;
  1178.     }
  1179.     else if(flags & O_CREAT) {
  1180.       /* We don't want to write - but we must make sure that O_CREAT
  1181.          doesn't create the file if we have write access into the
  1182.          directory.
  1183.        */
  1184.       flags &= ~O_CREAT;
  1185.     }
  1186.   }
  1187.  
  1188.   /* this handles a bug in Win95 - it doesn't say to create the file when it 
  1189.      should */
  1190.   if (Connections[cnum].printer)
  1191.     flags |= O_CREAT;
  1192.  
  1193. /*
  1194.   if (flags == O_WRONLY)
  1195.     DEBUG(3,("Bug in client? Set O_WRONLY without O_CREAT\n"));
  1196. */
  1197.  
  1198.   /*
  1199.    * Ensure we have a valid struct stat so we can search the
  1200.    * open fd table.
  1201.    */
  1202.   if(sbuf == 0) {
  1203.     if(stat(fname, &statbuf) < 0) {
  1204.       if(errno != ENOENT) {
  1205.         DEBUG(3,("Error doing stat on file %s (%s)\n",
  1206.                  fname,strerror(errno)));
  1207.  
  1208.         check_for_pipe(fname);
  1209.         return;
  1210.       }
  1211.       sbuf = 0;
  1212.     } else {
  1213.       sbuf = &statbuf;
  1214.     }
  1215.   }
  1216.  
  1217.   /*
  1218.    * Check to see if we have this file already
  1219.    * open. If we do, just use the already open fd and increment the
  1220.    * reference count (fd_get_already_open increments the ref_count).
  1221.    */
  1222.   if((fd_ptr = fd_get_already_open(sbuf))!= 0) {
  1223.  
  1224.     /* File was already open. */
  1225.     if((flags & O_CREAT) && (flags & O_EXCL)) {
  1226.       fd_ptr->ref_count--;
  1227.       errno = EEXIST;
  1228.       return;
  1229.     }
  1230.  
  1231.     /* 
  1232.      * If not opened O_RDWR try
  1233.      * and do that here - a chmod may have been done
  1234.      * between the last open and now. 
  1235.      */
  1236.     if(fd_ptr->real_open_flags != O_RDWR)
  1237.       fd_attempt_reopen(fname, mode, fd_ptr);
  1238.  
  1239.     /*
  1240.      * Ensure that if we wanted write access
  1241.      * it has been opened for write, and if we wanted read it
  1242.      * was open for read. 
  1243.      */
  1244.     if(((accmode == O_WRONLY) && (fd_ptr->real_open_flags == O_RDONLY)) ||
  1245.        ((accmode == O_RDONLY) && (fd_ptr->real_open_flags == O_WRONLY)) ||
  1246.        ((accmode == O_RDWR) && (fd_ptr->real_open_flags != O_RDWR))) {
  1247.       DEBUG(3,("Error opening (already open for flags=%d) file %s (%s) (flags=%d)\n",
  1248.                fd_ptr->real_open_flags, fname,strerror(EACCES),flags));
  1249.       check_for_pipe(fname);
  1250.       fd_ptr->ref_count--;
  1251.       return;
  1252.     }
  1253.  
  1254.   } else {
  1255.     int open_flags;
  1256.     /* We need to allocate a new file_fd_struct (this increments the
  1257.        ref_count). */
  1258.     if((fd_ptr = fd_get_new()) == 0)
  1259.       return;
  1260.     /*
  1261.      * Whatever the requested flags, attempt read/write access,
  1262.      * as we don't know what flags future file opens may require.
  1263.      * If this fails, try again with the required flags. 
  1264.      * Even if we open read/write when only read access was 
  1265.      * requested the setting of the can_write flag in
  1266.      * the file_struct will protect us from errant
  1267.      * write requests. We never need to worry about O_APPEND
  1268.      * as this is not set anywhere in Samba.
  1269.      */
  1270.     fd_ptr->real_open_flags = O_RDWR;
  1271.     /* Set the flags as needed without the read/write modes. */
  1272.     open_flags = flags & ~(O_RDWR|O_WRONLY|O_RDONLY);
  1273.     fd_ptr->fd = fd_attempt_open(fname, open_flags|O_RDWR, mode);
  1274.     /*
  1275.      * On some systems opening a file for R/W access on a read only
  1276.      * filesystems sets errno to EROFS.
  1277.      */
  1278. #ifdef EROFS
  1279.     if((fd_ptr->fd == -1) && ((errno == EACCES) || (errno == EROFS))) {
  1280. #else /* No EROFS */
  1281.     if((fd_ptr->fd == -1) && (errno == EACCES)) {
  1282. #endif /* EROFS */
  1283.       if(flags & O_WRONLY) {
  1284.         fd_ptr->fd = fd_attempt_open(fname, open_flags|O_WRONLY, mode);
  1285.         fd_ptr->real_open_flags = O_WRONLY;
  1286.       } else {
  1287.     fd_ptr->fd = fd_attempt_open(fname, open_flags|O_RDONLY, mode);
  1288.         fd_ptr->real_open_flags = O_RDONLY;
  1289.       }
  1290.     }
  1291.   }
  1292.  
  1293.   if ((fd_ptr->fd >=0) && 
  1294.       Connections[cnum].printer && lp_minprintspace(SNUM(cnum))) {
  1295.     pstring dname;
  1296.     int dum1,dum2,dum3;
  1297.     char *p;
  1298.     pstrcpy(dname,fname);
  1299.     p = strrchr(dname,'/');
  1300.     if (p) *p = 0;
  1301.     if (sys_disk_free(dname,&dum1,&dum2,&dum3) < 
  1302.     lp_minprintspace(SNUM(cnum))) {
  1303.       fd_attempt_close(fd_ptr);
  1304.       fsp->fd_ptr = 0;
  1305.       if(fd_ptr->ref_count == 0)
  1306.         sys_unlink(fname);
  1307.       errno = ENOSPC;
  1308.       return;
  1309.     }
  1310.   }
  1311.     
  1312.   if (fd_ptr->fd < 0)
  1313.     {
  1314.       DEBUG(3,("Error opening file %s (%s) (flags=%d)\n",
  1315.            fname,strerror(errno),flags));
  1316.       /* Ensure the ref_count is decremented. */
  1317.       fd_attempt_close(fd_ptr);
  1318.       check_for_pipe(fname);
  1319.       return;
  1320.     }
  1321.  
  1322.   if (fd_ptr->fd >= 0)
  1323.     {
  1324.       if(sbuf == 0) {
  1325.         /* Do the fstat */
  1326.         if(fstat(fd_ptr->fd, &statbuf) == -1) {
  1327.           /* Error - backout !! */
  1328.           DEBUG(3,("Error doing fstat on fd %d, file %s (%s)\n",
  1329.                    fd_ptr->fd, fname,strerror(errno)));
  1330.           /* Ensure the ref_count is decremented. */
  1331.           fd_attempt_close(fd_ptr);
  1332.           return;
  1333.         }
  1334.         sbuf = &statbuf;
  1335.       }
  1336.       /* Set the correct entries in fd_ptr. */
  1337.       fd_ptr->dev = (uint32)sbuf->st_dev;
  1338.       fd_ptr->inode = (uint32)sbuf->st_ino;
  1339.  
  1340.       fsp->fd_ptr = fd_ptr;
  1341.       Connections[cnum].num_files_open++;
  1342.       fsp->mode = sbuf->st_mode;
  1343.       GetTimeOfDay(&fsp->open_time);
  1344.       fsp->vuid = current_user.vuid;
  1345.       fsp->size = 0;
  1346.       fsp->pos = -1;
  1347.       fsp->open = True;
  1348.       fsp->mmap_ptr = NULL;
  1349.       fsp->mmap_size = 0;
  1350.       fsp->can_lock = True;
  1351.       fsp->can_read = ((flags & O_WRONLY)==0);
  1352.       fsp->can_write = ((flags & (O_WRONLY|O_RDWR))!=0);
  1353.       fsp->share_mode = 0;
  1354.       fsp->print_file = Connections[cnum].printer;
  1355.       fsp->modified = False;
  1356.       fsp->granted_oplock = False;
  1357.       fsp->sent_oplock_break = False;
  1358.       fsp->cnum = cnum;
  1359.       string_set(&fsp->name,dos_to_unix(fname,False));
  1360.       fsp->wbmpx_ptr = NULL;      
  1361.  
  1362.       /*
  1363.        * If the printer is marked as postscript output a leading
  1364.        * file identifier to ensure the file is treated as a raw
  1365.        * postscript file.
  1366.        * This has a similar effect as CtrlD=0 in WIN.INI file.
  1367.        * tim@fsg.com 09/06/94
  1368.        */
  1369.       if (fsp->print_file && POSTSCRIPT(cnum) && 
  1370.       fsp->can_write) 
  1371.     {
  1372.       DEBUG(3,("Writing postscript line\n"));
  1373.       write_file(fnum,"%!\n",3);
  1374.     }
  1375.       
  1376.       DEBUG(2,("%s %s opened file %s read=%s write=%s (numopen=%d fnum=%d)\n",
  1377.            timestring(),Connections[cnum].user,fname,
  1378.            BOOLSTR(fsp->can_read),BOOLSTR(fsp->can_write),
  1379.            Connections[cnum].num_files_open,fnum));
  1380.  
  1381.     }
  1382.  
  1383. #if USE_MMAP
  1384.   /* mmap it if read-only */
  1385.   if (!fsp->can_write)
  1386.     {
  1387.       fsp->mmap_size = file_size(fname);
  1388.       fsp->mmap_ptr = (char *)mmap(NULL,fsp->mmap_size,
  1389.                       PROT_READ,MAP_SHARED,fsp->fd_ptr->fd,0);
  1390.  
  1391.       if (fsp->mmap_ptr == (char *)-1 || !fsp->mmap_ptr)
  1392.     {
  1393.       DEBUG(3,("Failed to mmap() %s - %s\n",fname,strerror(errno)));
  1394.       fsp->mmap_ptr = NULL;
  1395.     }
  1396.     }
  1397. #endif
  1398. }
  1399.  
  1400. /*******************************************************************
  1401. sync a file
  1402. ********************************************************************/
  1403. void sync_file(int fnum)
  1404. {
  1405. #ifndef NO_FSYNC
  1406.   fsync(Files[fnum].fd_ptr->fd);
  1407. #endif
  1408. }
  1409.  
  1410. /****************************************************************************
  1411. run a file if it is a magic script
  1412. ****************************************************************************/
  1413. static void check_magic(int fnum,int cnum)
  1414. {
  1415.   if (!*lp_magicscript(SNUM(cnum)))
  1416.     return;
  1417.  
  1418.   DEBUG(5,("checking magic for %s\n",Files[fnum].name));
  1419.  
  1420.   {
  1421.     char *p;
  1422.     if (!(p = strrchr(Files[fnum].name,'/')))
  1423.       p = Files[fnum].name;
  1424.     else
  1425.       p++;
  1426.  
  1427.     if (!strequal(lp_magicscript(SNUM(cnum)),p))
  1428.       return;
  1429.   }
  1430.  
  1431.   {
  1432.     int ret;
  1433.     pstring magic_output;
  1434.     pstring fname;
  1435.     pstrcpy(fname,Files[fnum].name);
  1436.  
  1437.     if (*lp_magicoutput(SNUM(cnum)))
  1438.       pstrcpy(magic_output,lp_magicoutput(SNUM(cnum)));
  1439.     else
  1440.       slprintf(magic_output,sizeof(fname)-1, "%s.out",fname);
  1441.  
  1442.     chmod(fname,0755);
  1443.     ret = smbrun(fname,magic_output,False);
  1444.     DEBUG(3,("Invoking magic command %s gave %d\n",fname,ret));
  1445.     unlink(fname);
  1446.   }
  1447. }
  1448.  
  1449.  
  1450. /****************************************************************************
  1451. close a file - possibly invalidating the read prediction
  1452.  
  1453. If normal_close is 1 then this came from a normal SMBclose (or equivalent)
  1454. operation otherwise it came as the result of some other operation such as
  1455. the closing of the connection. In the latter case printing and
  1456. magic scripts are not run
  1457. ****************************************************************************/
  1458. void close_file(int fnum, BOOL normal_close)
  1459. {
  1460.   files_struct *fs_p = &Files[fnum];
  1461.   int cnum = fs_p->cnum;
  1462.   uint32 dev = fs_p->fd_ptr->dev;
  1463.   uint32 inode = fs_p->fd_ptr->inode;
  1464.   int token;
  1465.  
  1466.   Files[fnum].reserved = False;
  1467.  
  1468. #if USE_READ_PREDICTION
  1469.   invalidate_read_prediction(fs_p->fd_ptr->fd);
  1470. #endif
  1471.  
  1472.   fs_p->open = False;
  1473.   Connections[cnum].num_files_open--;
  1474.   if(fs_p->wbmpx_ptr) 
  1475.   {
  1476.     free((char *)fs_p->wbmpx_ptr);
  1477.     fs_p->wbmpx_ptr = NULL;
  1478.   }
  1479.  
  1480. #if USE_MMAP
  1481.   if(fs_p->mmap_ptr) 
  1482.   {
  1483.     munmap(fs_p->mmap_ptr,fs_p->mmap_size);
  1484.     fs_p->mmap_ptr = NULL;
  1485.   }
  1486. #endif
  1487.  
  1488.   if (lp_share_modes(SNUM(cnum)))
  1489.   {
  1490.     lock_share_entry( cnum, dev, inode, &token);
  1491.     del_share_mode(token, fnum);
  1492.   }
  1493.  
  1494.   fd_attempt_close(fs_p->fd_ptr);
  1495.  
  1496.   if (lp_share_modes(SNUM(cnum)))
  1497.     unlock_share_entry( cnum, dev, inode, token);
  1498.  
  1499.   /* NT uses smbclose to start a print - weird */
  1500.   if (normal_close && fs_p->print_file)
  1501.     print_file(fnum);
  1502.  
  1503.   /* check for magic scripts */
  1504.   if (normal_close)
  1505.     check_magic(fnum,cnum);
  1506.  
  1507.   if(fs_p->granted_oplock == True)
  1508.     global_oplocks_open--;
  1509.  
  1510.   fs_p->sent_oplock_break = False;
  1511.  
  1512.   DEBUG(2,("%s %s closed file %s (numopen=%d)\n",
  1513.        timestring(),Connections[cnum].user,fs_p->name,
  1514.        Connections[cnum].num_files_open));
  1515.  
  1516.   if (fs_p->name) {
  1517.       string_free(&fs_p->name);
  1518.   }
  1519.  
  1520.   /* we will catch bugs faster by zeroing this structure */
  1521.   memset(fs_p, 0, sizeof(*fs_p));
  1522. }
  1523.  
  1524. enum {AFAIL,AREAD,AWRITE,AALL};
  1525.  
  1526. /*******************************************************************
  1527. reproduce the share mode access table
  1528. ********************************************************************/
  1529. static int access_table(int new_deny,int old_deny,int old_mode,
  1530.             int share_pid,char *fname)
  1531. {
  1532.   if (new_deny == DENY_ALL || old_deny == DENY_ALL) return(AFAIL);
  1533.  
  1534.   if (new_deny == DENY_DOS || old_deny == DENY_DOS) {
  1535.     int pid = getpid();
  1536.     if (old_deny == new_deny && share_pid == pid) 
  1537.     return(AALL);    
  1538.  
  1539.     if (old_mode == 0) return(AREAD);
  1540.  
  1541.     /* the new smbpub.zip spec says that if the file extension is
  1542.        .com, .dll, .exe or .sym then allow the open. I will force
  1543.        it to read-only as this seems sensible although the spec is
  1544.        a little unclear on this. */
  1545.     if ((fname = strrchr(fname,'.'))) {
  1546.       if (strequal(fname,".com") ||
  1547.       strequal(fname,".dll") ||
  1548.       strequal(fname,".exe") ||
  1549.       strequal(fname,".sym"))
  1550.     return(AREAD);
  1551.     }
  1552.  
  1553.     return(AFAIL);
  1554.   }
  1555.  
  1556.   switch (new_deny) 
  1557.     {
  1558.     case DENY_WRITE:
  1559.       if (old_deny==DENY_WRITE && old_mode==0) return(AREAD);
  1560.       if (old_deny==DENY_READ && old_mode==0) return(AWRITE);
  1561.       if (old_deny==DENY_NONE && old_mode==0) return(AALL);
  1562.       return(AFAIL);
  1563.     case DENY_READ:
  1564.       if (old_deny==DENY_WRITE && old_mode==1) return(AREAD);
  1565.       if (old_deny==DENY_READ && old_mode==1) return(AWRITE);
  1566.       if (old_deny==DENY_NONE && old_mode==1) return(AALL);
  1567.       return(AFAIL);
  1568.     case DENY_NONE:
  1569.       if (old_deny==DENY_WRITE) return(AREAD);
  1570.       if (old_deny==DENY_READ) return(AWRITE);
  1571.       if (old_deny==DENY_NONE) return(AALL);
  1572.       return(AFAIL);      
  1573.     }
  1574.   return(AFAIL);      
  1575. }
  1576.  
  1577. /*******************************************************************
  1578. check if the share mode on a file allows it to be deleted or unlinked
  1579. return True if sharing doesn't prevent the operation
  1580. ********************************************************************/
  1581. BOOL check_file_sharing(int cnum,char *fname, BOOL rename_op)
  1582. {
  1583.   int i;
  1584.   int ret = False;
  1585.   share_mode_entry *old_shares = 0;
  1586.   int num_share_modes;
  1587.   struct stat sbuf;
  1588.   int token;
  1589.   int pid = getpid();
  1590.   uint32 dev, inode;
  1591.  
  1592.   if(!lp_share_modes(SNUM(cnum)))
  1593.     return True;
  1594.  
  1595.   if (stat(fname,&sbuf) == -1) return(True);
  1596.  
  1597.   dev = (uint32)sbuf.st_dev;
  1598.   inode = (uint32)sbuf.st_ino;
  1599.  
  1600.   lock_share_entry(cnum, dev, inode, &token);
  1601.   num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
  1602.  
  1603.   /*
  1604.    * Check if the share modes will give us access.
  1605.    */
  1606.  
  1607.   if(num_share_modes != 0)
  1608.   {
  1609.     BOOL broke_oplock;
  1610.  
  1611.     do
  1612.     {
  1613.  
  1614.       broke_oplock = False;
  1615.       for(i = 0; i < num_share_modes; i++)
  1616.       {
  1617.         share_mode_entry *share_entry = &old_shares[i];
  1618.  
  1619.         /* 
  1620.          * Break oplocks before checking share modes. See comment in
  1621.          * open_file_shared for details. 
  1622.          * Check if someone has an oplock on this file. If so we must 
  1623.          * break it before continuing. 
  1624.          */
  1625.         if(share_entry->op_type & BATCH_OPLOCK)
  1626.         {
  1627.  
  1628.           /*
  1629.            * It appears that the NT redirector may have a bug, in that
  1630.            * it tries to do an SMBmv on a file that it has open with a
  1631.            * batch oplock, and then fails to respond to the oplock break
  1632.            * request. This only seems to occur when the client is doing an
  1633.            * SMBmv to the smbd it is using - thus we try and detect this
  1634.            * condition by checking if the file being moved is open and oplocked by
  1635.            * this smbd process, and then not sending the oplock break in this
  1636.            * special case. If the file was open with a deny mode that 
  1637.            * prevents the move the SMBmv will fail anyway with a share
  1638.            * violation error. JRA.
  1639.            */
  1640.           if(rename_op && (share_entry->pid == pid))
  1641.           {
  1642.             DEBUG(0,("check_file_sharing: NT redirector workaround - rename attempted on \
  1643. batch oplocked file %s, dev = %x, inode = %x\n", fname, dev, inode));
  1644.             /* 
  1645.              * This next line is a test that allows the deny-mode
  1646.              * processing to be skipped. This seems to be needed as
  1647.              * NT insists on the rename succeeding (in Office 9x no less !).
  1648.              * This should be removed as soon as (a) MS fix the redirector
  1649.              * bug or (b) NT SMB support in Samba makes NT not issue the
  1650.              * call (as is my fervent hope). JRA.
  1651.              */ 
  1652.             continue;
  1653.           }
  1654.           else
  1655.           {
  1656.             DEBUG(5,("check_file_sharing: breaking oplock (%x) on file %s, \
  1657. dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
  1658.  
  1659.             /* Oplock break.... */
  1660.             unlock_share_entry(cnum, dev, inode, token);
  1661.             if(request_oplock_break(share_entry, dev, inode) == False)
  1662.             {
  1663.               free((char *)old_shares);
  1664.               DEBUG(0,("check_file_sharing: FAILED when breaking oplock (%x) on file %s, \
  1665. dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
  1666.               return False;
  1667.             }
  1668.             lock_share_entry(cnum, dev, inode, &token);
  1669.             broke_oplock = True;
  1670.             break;
  1671.           }
  1672.         }
  1673.  
  1674.         /* someone else has a share lock on it, check to see 
  1675.            if we can too */
  1676.         if ((share_entry->share_mode != DENY_DOS) || (share_entry->pid != pid))
  1677.           goto free_and_exit;
  1678.  
  1679.       } /* end for */
  1680.  
  1681.       if(broke_oplock)
  1682.       {
  1683.         free((char *)old_shares);
  1684.         num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
  1685.       }
  1686.     } while(broke_oplock);
  1687.   }
  1688.  
  1689.   /* XXXX exactly what share mode combinations should be allowed for
  1690.      deleting/renaming? */
  1691.   /* If we got here then either there were no share modes or
  1692.      all share modes were DENY_DOS and the pid == getpid() */
  1693.   ret = True;
  1694.  
  1695. free_and_exit:
  1696.  
  1697.   unlock_share_entry(cnum, dev, inode, token);
  1698.   if(old_shares != NULL)
  1699.     free((char *)old_shares);
  1700.   return(ret);
  1701. }
  1702.  
  1703. /****************************************************************************
  1704.   C. Hoch 11/22/95
  1705.   Helper for open_file_shared. 
  1706.   Truncate a file after checking locking; close file if locked.
  1707.   **************************************************************************/
  1708. static void truncate_unless_locked(int fnum, int cnum, int token, 
  1709.                    BOOL *share_locked)
  1710. {
  1711.   if (Files[fnum].can_write){
  1712.     if (is_locked(fnum,cnum,0x3FFFFFFF,0)){
  1713.       /* If share modes are in force for this connection we
  1714.          have the share entry locked. Unlock it before closing. */
  1715.       if (*share_locked && lp_share_modes(SNUM(cnum)))
  1716.         unlock_share_entry( cnum, Files[fnum].fd_ptr->dev, 
  1717.                             Files[fnum].fd_ptr->inode, token);
  1718.       close_file(fnum,False);   
  1719.       /* Share mode no longer locked. */
  1720.       *share_locked = False;
  1721.       errno = EACCES;
  1722.       unix_ERR_class = ERRDOS;
  1723.       unix_ERR_code = ERRlock;
  1724.     }
  1725.     else
  1726.       ftruncate(Files[fnum].fd_ptr->fd,0); 
  1727.   }
  1728. }
  1729.  
  1730. /****************************************************************************
  1731. check if we can open a file with a share mode
  1732. ****************************************************************************/
  1733. int check_share_mode( share_mode_entry *share, int deny_mode, char *fname,
  1734.                       BOOL fcbopen, int *flags)
  1735. {
  1736.   int old_open_mode = share->share_mode &0xF;
  1737.   int old_deny_mode = (share->share_mode >>4)&7;
  1738.  
  1739.   if (old_deny_mode > 4 || old_open_mode > 2)
  1740.   {
  1741.     DEBUG(0,("Invalid share mode found (%d,%d,%d) on file %s\n",
  1742.                deny_mode,old_deny_mode,old_open_mode,fname));
  1743.     return False;
  1744.   }
  1745.  
  1746.   {
  1747.     int access_allowed = access_table(deny_mode,old_deny_mode,old_open_mode,
  1748.                                 share->pid,fname);
  1749.  
  1750.     if ((access_allowed == AFAIL) ||
  1751.         (!fcbopen && (access_allowed == AREAD && *flags == O_RDWR)) ||
  1752.         (access_allowed == AREAD && *flags == O_WRONLY) ||
  1753.         (access_allowed == AWRITE && *flags == O_RDONLY))
  1754.     {
  1755.       DEBUG(2,("Share violation on file (%d,%d,%d,%d,%s,fcbopen = %d, flags = %d) = %d\n",
  1756.                 deny_mode,old_deny_mode,old_open_mode,
  1757.                 share->pid,fname, fcbopen, *flags, access_allowed));
  1758.       return False;
  1759.     }
  1760.  
  1761.     if (access_allowed == AREAD)
  1762.       *flags = O_RDONLY;
  1763.  
  1764.     if (access_allowed == AWRITE)
  1765.       *flags = O_WRONLY;
  1766.  
  1767.   }
  1768.   return True;
  1769. }
  1770.  
  1771. /****************************************************************************
  1772. open a file with a share mode
  1773. ****************************************************************************/
  1774. void open_file_shared(int fnum,int cnum,char *fname,int share_mode,int ofun,
  1775.               int mode,int oplock_request, int *Access,int *action)
  1776. {
  1777.   files_struct *fs_p = &Files[fnum];
  1778.   int flags=0;
  1779.   int flags2=0;
  1780.   int deny_mode = (share_mode>>4)&7;
  1781.   struct stat sbuf;
  1782.   BOOL file_existed = file_exist(fname,&sbuf);
  1783.   BOOL share_locked = False;
  1784.   BOOL fcbopen = False;
  1785.   int token;
  1786.   uint32 dev = 0;
  1787.   uint32 inode = 0;
  1788.   int num_share_modes = 0;
  1789.  
  1790.   fs_p->open = False;
  1791.   fs_p->fd_ptr = 0;
  1792.  
  1793.   /* this is for OS/2 EAs - try and say we don't support them */
  1794.   if (strstr(fname,".+,;=[].")) 
  1795.   {
  1796.     unix_ERR_class = ERRDOS;
  1797.     /* OS/2 Workplace shell fix may be main code stream in a later release. */ 
  1798. #if 1 /* OS2_WPS_FIX - Recent versions of OS/2 need this. */
  1799.     unix_ERR_code = ERRcannotopen;
  1800. #else /* OS2_WPS_FIX */
  1801.     unix_ERR_code = ERROR_EAS_NOT_SUPPORTED;
  1802. #endif /* OS2_WPS_FIX */
  1803.  
  1804.     return;
  1805.   }
  1806.  
  1807.   if ((ofun & 0x3) == 0 && file_existed)  
  1808.   {
  1809.     errno = EEXIST;
  1810.     return;
  1811.   }
  1812.       
  1813.   if (ofun & 0x10)
  1814.     flags2 |= O_CREAT;
  1815.   if ((ofun & 0x3) == 2)
  1816.     flags2 |= O_TRUNC;
  1817.  
  1818.   /* note that we ignore the append flag as 
  1819.      append does not mean the same thing under dos and unix */
  1820.  
  1821.   switch (share_mode&0xF)
  1822.   {
  1823.     case 1: 
  1824.       flags = O_WRONLY; 
  1825.       break;
  1826.     case 0xF: 
  1827.       fcbopen = True;
  1828.       flags = O_RDWR; 
  1829.       break;
  1830.     case 2: 
  1831.       flags = O_RDWR; 
  1832.       break;
  1833.     default:
  1834.       flags = O_RDONLY;
  1835.       break;
  1836.   }
  1837.   
  1838.   if (flags != O_RDONLY && file_existed && 
  1839.       (!CAN_WRITE(cnum) || IS_DOS_READONLY(dos_mode(cnum,fname,&sbuf)))) 
  1840.   {
  1841.     if (!fcbopen) 
  1842.     {
  1843.       errno = EACCES;
  1844.       return;
  1845.     }
  1846.     flags = O_RDONLY;
  1847.   }
  1848.  
  1849.   if (deny_mode > DENY_NONE && deny_mode!=DENY_FCB) 
  1850.   {
  1851.     DEBUG(2,("Invalid deny mode %d on file %s\n",deny_mode,fname));
  1852.     errno = EINVAL;
  1853.     return;
  1854.   }
  1855.  
  1856.   if (deny_mode == DENY_FCB) deny_mode = DENY_DOS;
  1857.  
  1858.   if (lp_share_modes(SNUM(cnum))) 
  1859.   {
  1860.     int i;
  1861.     share_mode_entry *old_shares = 0;
  1862.  
  1863.     if (file_existed)
  1864.     {
  1865.       dev = (uint32)sbuf.st_dev;
  1866.       inode = (uint32)sbuf.st_ino;
  1867.       lock_share_entry(cnum, dev, inode, &token);
  1868.       share_locked = True;
  1869.       num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
  1870.     }
  1871.  
  1872.     /*
  1873.      * Check if the share modes will give us access.
  1874.      */
  1875.  
  1876.     if(share_locked && (num_share_modes != 0))
  1877.     {
  1878.       BOOL broke_oplock;
  1879.  
  1880.       do
  1881.       {
  1882.  
  1883.         broke_oplock = False;
  1884.         for(i = 0; i < num_share_modes; i++)
  1885.         {
  1886.           share_mode_entry *share_entry = &old_shares[i];
  1887.  
  1888.           /* 
  1889.            * By observation of NetBench, oplocks are broken *before* share
  1890.            * modes are checked. This allows a file to be closed by the client
  1891.            * if the share mode would deny access and the client has an oplock. 
  1892.            * Check if someone has an oplock on this file. If so we must break 
  1893.            * it before continuing. 
  1894.            */
  1895.           if(share_entry->op_type & (EXCLUSIVE_OPLOCK|BATCH_OPLOCK))
  1896.           {
  1897.  
  1898.             DEBUG(5,("open_file_shared: breaking oplock (%x) on file %s, \
  1899. dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
  1900.  
  1901.             /* Oplock break.... */
  1902.             unlock_share_entry(cnum, dev, inode, token);
  1903.             if(request_oplock_break(share_entry, dev, inode) == False)
  1904.             {
  1905.               free((char *)old_shares);
  1906.               DEBUG(0,("open_file_shared: FAILED when breaking oplock (%x) on file %s, \
  1907. dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
  1908.               errno = EACCES;
  1909.               unix_ERR_class = ERRDOS;
  1910.               unix_ERR_code = ERRbadshare;
  1911.               return;
  1912.             }
  1913.             lock_share_entry(cnum, dev, inode, &token);
  1914.             broke_oplock = True;
  1915.             break;
  1916.           }
  1917.  
  1918.           /* someone else has a share lock on it, check to see 
  1919.              if we can too */
  1920.           if(check_share_mode(share_entry, deny_mode, fname, fcbopen, &flags) == False)
  1921.           {
  1922.             free((char *)old_shares);
  1923.             unlock_share_entry(cnum, dev, inode, token);
  1924.             errno = EACCES;
  1925.             unix_ERR_class = ERRDOS;
  1926.             unix_ERR_code = ERRbadshare;
  1927.             return;
  1928.           }
  1929.  
  1930.         } /* end for */
  1931.  
  1932.         if(broke_oplock)
  1933.         {
  1934.           free((char *)old_shares);
  1935.           num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
  1936.         }
  1937.       } while(broke_oplock);
  1938.     }
  1939.  
  1940.     if(old_shares != 0)
  1941.       free((char *)old_shares);
  1942.   }
  1943.  
  1944.   DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o\n",
  1945.        flags,flags2,mode));
  1946.  
  1947.   open_file(fnum,cnum,fname,flags|(flags2&~(O_TRUNC)),mode,file_existed ? &sbuf : 0);
  1948.   if (!fs_p->open && flags==O_RDWR && errno!=ENOENT && fcbopen) 
  1949.   {
  1950.     flags = O_RDONLY;
  1951.     open_file(fnum,cnum,fname,flags,mode,file_existed ? &sbuf : 0 );
  1952.   }
  1953.  
  1954.   if (fs_p->open) 
  1955.   {
  1956.     int open_mode=0;
  1957.  
  1958.     if((share_locked == False) && lp_share_modes(SNUM(cnum)))
  1959.     {
  1960.       /* We created the file - thus we must now lock the share entry before creating it. */
  1961.       dev = fs_p->fd_ptr->dev;
  1962.       inode = fs_p->fd_ptr->inode;
  1963.       lock_share_entry(cnum, dev, inode, &token);
  1964.       share_locked = True;
  1965.     }
  1966.  
  1967.     switch (flags) 
  1968.     {
  1969.       case O_RDONLY:
  1970.         open_mode = 0;
  1971.         break;
  1972.       case O_RDWR:
  1973.         open_mode = 2;
  1974.         break;
  1975.       case O_WRONLY:
  1976.         open_mode = 1;
  1977.         break;
  1978.     }
  1979.  
  1980.     fs_p->share_mode = (deny_mode<<4) | open_mode;
  1981.  
  1982.     if (Access)
  1983.       (*Access) = open_mode;
  1984.  
  1985.     if (action) 
  1986.     {
  1987.       if (file_existed && !(flags2 & O_TRUNC)) *action = 1;
  1988.       if (!file_existed) *action = 2;
  1989.       if (file_existed && (flags2 & O_TRUNC)) *action = 3;
  1990.     }
  1991.     /* We must create the share mode entry before truncate as
  1992.        truncate can fail due to locking and have to close the
  1993.        file (which expects the share_mode_entry to be there).
  1994.      */
  1995.     if (lp_share_modes(SNUM(cnum)))
  1996.     {
  1997.       uint16 port = 0;
  1998.       /* JRA. Currently this only services Exlcusive and batch
  1999.          oplocks (no other opens on this file). This needs to
  2000.          be extended to level II oplocks (multiple reader
  2001.          oplocks). */
  2002.  
  2003.       if(oplock_request && (num_share_modes == 0) && lp_oplocks(SNUM(cnum)) && 
  2004.           !IS_VETO_OPLOCK_PATH(cnum,fname))
  2005.       {
  2006.         fs_p->granted_oplock = True;
  2007.         fs_p->sent_oplock_break = False;
  2008.         global_oplocks_open++;
  2009.         port = oplock_port;
  2010.  
  2011.         DEBUG(5,("open_file_shared: granted oplock (%x) on file %s, \
  2012. dev = %x, inode = %x\n", oplock_request, fname, dev, inode));
  2013.  
  2014.       }
  2015.       else
  2016.       {
  2017.         port = 0;
  2018.         oplock_request = 0;
  2019.       }
  2020.       set_share_mode(token, fnum, port, oplock_request);
  2021.     }
  2022.  
  2023.     if ((flags2&O_TRUNC) && file_existed)
  2024.       truncate_unless_locked(fnum,cnum,token,&share_locked);
  2025.   }
  2026.  
  2027.   if (share_locked && lp_share_modes(SNUM(cnum)))
  2028.     unlock_share_entry( cnum, dev, inode, token);
  2029. }
  2030.  
  2031. /****************************************************************************
  2032. seek a file. Try to avoid the seek if possible
  2033. ****************************************************************************/
  2034. int seek_file(int fnum,uint32 pos)
  2035. {
  2036.   uint32 offset = 0;
  2037.   if (Files[fnum].print_file && POSTSCRIPT(Files[fnum].cnum))
  2038.     offset = 3;
  2039.  
  2040.   Files[fnum].pos = (int)(lseek(Files[fnum].fd_ptr->fd,pos+offset,SEEK_SET) 
  2041.                                   - offset);
  2042.   return(Files[fnum].pos);
  2043. }
  2044.  
  2045. /****************************************************************************
  2046. read from a file
  2047. ****************************************************************************/
  2048. int read_file(int fnum,char *data,uint32 pos,int n)
  2049. {
  2050.   int ret=0,readret;
  2051.  
  2052. #if USE_READ_PREDICTION
  2053.   if (!Files[fnum].can_write)
  2054.     {
  2055.       ret = read_predict(Files[fnum].fd_ptr->fd,pos,data,NULL,n);
  2056.  
  2057.       data += ret;
  2058.       n -= ret;
  2059.       pos += ret;
  2060.     }
  2061. #endif
  2062.  
  2063. #if USE_MMAP
  2064.   if (Files[fnum].mmap_ptr)
  2065.     {
  2066.       int num = (Files[fnum].mmap_size > pos) ? (Files[fnum].mmap_size - pos) : -1;
  2067.       num = MIN(n,num);
  2068.       if (num > 0)
  2069.     {
  2070.       memcpy(data,Files[fnum].mmap_ptr+pos,num);
  2071.       data += num;
  2072.       pos += num;
  2073.       n -= num;
  2074.       ret += num;
  2075.     }
  2076.     }
  2077. #endif
  2078.  
  2079.   if (n <= 0)
  2080.     return(ret);
  2081.  
  2082.   if (seek_file(fnum,pos) != pos)
  2083.     {
  2084.       DEBUG(3,("Failed to seek to %d\n",pos));
  2085.       return(ret);
  2086.     }
  2087.   
  2088.   if (n > 0) {
  2089.     readret = read(Files[fnum].fd_ptr->fd,data,n);
  2090.     if (readret > 0) ret += readret;
  2091.   }
  2092.  
  2093.   return(ret);
  2094. }
  2095.  
  2096.  
  2097. /****************************************************************************
  2098. write to a file
  2099. ****************************************************************************/
  2100. int write_file(int fnum,char *data,int n)
  2101. {
  2102.   if (!Files[fnum].can_write) {
  2103.     errno = EPERM;
  2104.     return(0);
  2105.   }
  2106.  
  2107.   if (!Files[fnum].modified) {
  2108.     struct stat st;
  2109.     Files[fnum].modified = True;
  2110.     if (fstat(Files[fnum].fd_ptr->fd,&st) == 0) {
  2111.       int dosmode = dos_mode(Files[fnum].cnum,Files[fnum].name,&st);
  2112.       if (MAP_ARCHIVE(Files[fnum].cnum) && !IS_DOS_ARCHIVE(dosmode)) {    
  2113.     dos_chmod(Files[fnum].cnum,Files[fnum].name,dosmode | aARCH,&st);
  2114.       }
  2115.     }  
  2116.   }
  2117.  
  2118.   return(write_data(Files[fnum].fd_ptr->fd,data,n));
  2119. }
  2120.  
  2121.  
  2122. /****************************************************************************
  2123. load parameters specific to a connection/service
  2124. ****************************************************************************/
  2125. BOOL become_service(int cnum,BOOL do_chdir)
  2126. {
  2127.   extern char magic_char;
  2128.   static int last_cnum = -1;
  2129.   int snum;
  2130.  
  2131.   if (!OPEN_CNUM(cnum))
  2132.     {
  2133.       last_cnum = -1;
  2134.       return(False);
  2135.     }
  2136.  
  2137.   Connections[cnum].lastused = smb_last_time;
  2138.  
  2139.   snum = SNUM(cnum);
  2140.   
  2141.   if (do_chdir &&
  2142.       ChDir(Connections[cnum].connectpath) != 0 &&
  2143.       ChDir(Connections[cnum].origpath) != 0)
  2144.     {
  2145.       DEBUG(0,("%s chdir (%s) failed cnum=%d\n",timestring(),
  2146.         Connections[cnum].connectpath,cnum));     
  2147.       return(False);
  2148.     }
  2149.  
  2150.   if (cnum == last_cnum)
  2151.     return(True);
  2152.  
  2153.   last_cnum = cnum;
  2154.  
  2155.   case_default = lp_defaultcase(snum);
  2156.   case_preserve = lp_preservecase(snum);
  2157.   short_case_preserve = lp_shortpreservecase(snum);
  2158.   case_mangle = lp_casemangle(snum);
  2159.   case_sensitive = lp_casesensitive(snum);
  2160.   magic_char = lp_magicchar(snum);
  2161.   use_mangled_map = (*lp_mangled_map(snum) ? True:False);
  2162.   return(True);
  2163. }
  2164.  
  2165.  
  2166. /****************************************************************************
  2167.   find a service entry
  2168. ****************************************************************************/
  2169. int find_service(char *service)
  2170. {
  2171.    int iService;
  2172.  
  2173.    string_sub(service,"\\","/");
  2174.  
  2175.    iService = lp_servicenumber(service);
  2176.  
  2177.    /* now handle the special case of a home directory */
  2178.    if (iService < 0)
  2179.    {
  2180.       char *phome_dir = get_home_dir(service);
  2181.       DEBUG(3,("checking for home directory %s gave %s\n",service,
  2182.         phome_dir?phome_dir:"(NULL)"));
  2183.       if (phome_dir)
  2184.       {   
  2185.      int iHomeService;
  2186.      if ((iHomeService = lp_servicenumber(HOMES_NAME)) >= 0)
  2187.      {
  2188.         lp_add_home(service,iHomeService,phome_dir);
  2189.         iService = lp_servicenumber(service);
  2190.      }
  2191.       }
  2192.    }
  2193.  
  2194.    /* If we still don't have a service, attempt to add it as a printer. */
  2195.    if (iService < 0)
  2196.    {
  2197.       int iPrinterService;
  2198.  
  2199.       if ((iPrinterService = lp_servicenumber(PRINTERS_NAME)) >= 0)
  2200.       {
  2201.          char *pszTemp;
  2202.  
  2203.          DEBUG(3,("checking whether %s is a valid printer name...\n", service));
  2204.          pszTemp = PRINTCAP;
  2205.          if ((pszTemp != NULL) && pcap_printername_ok(service, pszTemp))
  2206.          {
  2207.             DEBUG(3,("%s is a valid printer name\n", service));
  2208.             DEBUG(3,("adding %s as a printer service\n", service));
  2209.             lp_add_printer(service,iPrinterService);
  2210.             iService = lp_servicenumber(service);
  2211.             if (iService < 0)
  2212.                DEBUG(0,("failed to add %s as a printer service!\n", service));
  2213.          }
  2214.          else
  2215.             DEBUG(3,("%s is not a valid printer name\n", service));
  2216.       }
  2217.    }
  2218.  
  2219.    /* just possibly it's a default service? */
  2220.    if (iService < 0) 
  2221.      {
  2222.        char *pdefservice = lp_defaultservice();
  2223.        if (pdefservice && *pdefservice && !strequal(pdefservice,service)) {
  2224.          /*
  2225.           * We need to do a local copy here as lp_defaultservice() 
  2226.           * returns one of the rotating lp_string buffers that
  2227.           * could get overwritten by the recursive find_service() call
  2228.           * below. Fix from Josef Hinteregger <joehtg@joehtg.co.at>.
  2229.           */
  2230.          pstring defservice;
  2231.          pstrcpy(defservice, pdefservice);
  2232.      iService = find_service(defservice);
  2233.      if (iService >= 0) {
  2234.        string_sub(service,"_","/");
  2235.        iService = lp_add_service(service,iService);
  2236.      }
  2237.        }
  2238.      }
  2239.  
  2240.    if (iService >= 0)
  2241.       if (!VALID_SNUM(iService))
  2242.       {
  2243.          DEBUG(0,("Invalid snum %d for %s\n",iService,service));
  2244.      iService = -1;
  2245.       }
  2246.  
  2247.    if (iService < 0)
  2248.       DEBUG(3,("find_service() failed to find service %s\n", service));
  2249.  
  2250.    return (iService);
  2251. }
  2252.  
  2253.  
  2254. /****************************************************************************
  2255.   create an error packet from a cached error.
  2256. ****************************************************************************/
  2257. int cached_error_packet(char *inbuf,char *outbuf,int fnum,int line)
  2258. {
  2259.   write_bmpx_struct *wbmpx = Files[fnum].wbmpx_ptr;
  2260.  
  2261.   int32 eclass = wbmpx->wr_errclass;
  2262.   int32 err = wbmpx->wr_error;
  2263.  
  2264.   /* We can now delete the auxiliary struct */
  2265.   free((char *)wbmpx);
  2266.   Files[fnum].wbmpx_ptr = NULL;
  2267.   return error_packet(inbuf,outbuf,eclass,err,line);
  2268. }
  2269.  
  2270.  
  2271. struct
  2272. {
  2273.   int unixerror;
  2274.   int smbclass;
  2275.   int smbcode;
  2276. } unix_smb_errmap[] =
  2277. {
  2278.   {EPERM,ERRDOS,ERRnoaccess},
  2279.   {EACCES,ERRDOS,ERRnoaccess},
  2280.   {ENOENT,ERRDOS,ERRbadfile},
  2281.   {ENOTDIR,ERRDOS,ERRbadpath},
  2282.   {EIO,ERRHRD,ERRgeneral},
  2283.   {EBADF,ERRSRV,ERRsrverror},
  2284.   {EINVAL,ERRSRV,ERRsrverror},
  2285.   {EEXIST,ERRDOS,ERRfilexists},
  2286.   {ENFILE,ERRDOS,ERRnofids},
  2287.   {EMFILE,ERRDOS,ERRnofids},
  2288.   {ENOSPC,ERRHRD,ERRdiskfull},
  2289. #ifdef EDQUOT
  2290.   {EDQUOT,ERRHRD,ERRdiskfull},
  2291. #endif
  2292. #ifdef ENOTEMPTY
  2293.   {ENOTEMPTY,ERRDOS,ERRnoaccess},
  2294. #endif
  2295. #ifdef EXDEV
  2296.   {EXDEV,ERRDOS,ERRdiffdevice},
  2297. #endif
  2298.   {EROFS,ERRHRD,ERRnowrite},
  2299.   {0,0,0}
  2300. };
  2301.  
  2302. /****************************************************************************
  2303.   create an error packet from errno
  2304. ****************************************************************************/
  2305. int unix_error_packet(char *inbuf,char *outbuf,int def_class,uint32 def_code,int line)
  2306. {
  2307.   int eclass=def_class;
  2308.   int ecode=def_code;
  2309.   int i=0;
  2310.  
  2311.   if (unix_ERR_class != SMB_SUCCESS)
  2312.     {
  2313.       eclass = unix_ERR_class;
  2314.       ecode = unix_ERR_code;
  2315.       unix_ERR_class = SMB_SUCCESS;
  2316.       unix_ERR_code = 0;
  2317.     }
  2318.   else
  2319.     {
  2320.       while (unix_smb_errmap[i].smbclass != 0)
  2321.       {
  2322.         if (unix_smb_errmap[i].unixerror == errno)
  2323.         {
  2324.           eclass = unix_smb_errmap[i].smbclass;
  2325.           ecode = unix_smb_errmap[i].smbcode;
  2326.           break;
  2327.         }
  2328.       i++;
  2329.       }
  2330.     }
  2331.  
  2332.   return(error_packet(inbuf,outbuf,eclass,ecode,line));
  2333. }
  2334.  
  2335.  
  2336. /****************************************************************************
  2337.   create an error packet. Normally called using the ERROR() macro
  2338. ****************************************************************************/
  2339. int error_packet(char *inbuf,char *outbuf,int error_class,uint32 error_code,int line)
  2340. {
  2341.   int outsize = set_message(outbuf,0,0,True);
  2342.   int cmd;
  2343.   cmd = CVAL(inbuf,smb_com);
  2344.   
  2345.   CVAL(outbuf,smb_rcls) = error_class;
  2346.   SSVAL(outbuf,smb_err,error_code);  
  2347.   
  2348.   DEBUG(3,("%s error packet at line %d cmd=%d (%s) eclass=%d ecode=%d\n",
  2349.        timestring(),
  2350.        line,
  2351.        (int)CVAL(inbuf,smb_com),
  2352.        smb_fn_name(CVAL(inbuf,smb_com)),
  2353.        error_class,
  2354.        error_code));
  2355.  
  2356.   if (errno != 0)
  2357.     DEBUG(3,("error string = %s\n",strerror(errno)));
  2358.   
  2359.   return(outsize);
  2360. }
  2361.  
  2362.  
  2363. #ifndef SIGCLD_IGNORE
  2364. /****************************************************************************
  2365. this prevents zombie child processes
  2366. ****************************************************************************/
  2367. static int sig_cld(void)
  2368. {
  2369.   static int depth = 0;
  2370.   if (depth != 0)
  2371.     {
  2372.       DEBUG(0,("ERROR: Recursion in sig_cld? Perhaps you need `#define USE_WAITPID'?\n"));
  2373.       depth=0;
  2374.       return(0);
  2375.     }
  2376.   depth++;
  2377.  
  2378.   BlockSignals(True,SIGCLD);
  2379.   DEBUG(5,("got SIGCLD\n"));
  2380.  
  2381. #ifdef USE_WAITPID
  2382.   while (sys_waitpid((pid_t)-1,(int *)NULL, WNOHANG) > 0);
  2383. #endif
  2384.  
  2385.   /* Stop zombies */
  2386.   /* Stevens, Adv. Unix Prog. says that on system V you must call
  2387.      wait before reinstalling the signal handler, because the kernel
  2388.      calls the handler from within the signal-call when there is a
  2389.      child that has exited. This would lead to an infinite recursion
  2390.      if done vice versa. */
  2391.         
  2392. #ifndef DONT_REINSTALL_SIG
  2393. #ifdef SIGCLD_IGNORE
  2394.   signal(SIGCLD, SIG_IGN);  
  2395. #else
  2396.   signal(SIGCLD, SIGNAL_CAST sig_cld);
  2397. #endif
  2398. #endif
  2399.  
  2400. #ifndef USE_WAITPID
  2401.   while (wait3(WAIT3_CAST1 NULL, WNOHANG, WAIT3_CAST2 NULL) > 0);
  2402. #endif
  2403.   depth--;
  2404.   BlockSignals(False,SIGCLD);
  2405.   return 0;
  2406. }
  2407. #endif
  2408.  
  2409. /****************************************************************************
  2410.   this is called when the client exits abruptly
  2411.   **************************************************************************/
  2412. static int sig_pipe(void)
  2413. {
  2414.     struct cli_state *cli;
  2415.     BlockSignals(True,SIGPIPE);
  2416.  
  2417.     if ((cli = server_client()) && cli->initialised) {
  2418.         DEBUG(3,("lost connection to password server\n"));
  2419.         cli_shutdown(cli);
  2420. #ifndef DONT_REINSTALL_SIG
  2421.         signal(SIGPIPE, SIGNAL_CAST sig_pipe);
  2422. #endif
  2423.         BlockSignals(False,SIGPIPE);
  2424.         return 0;
  2425.     }
  2426.  
  2427.     exit_server("Got sigpipe\n");
  2428.     return(0);
  2429. }
  2430.  
  2431. /****************************************************************************
  2432.   open the socket communication
  2433. ****************************************************************************/
  2434. static BOOL open_sockets(BOOL is_daemon,int port)
  2435. {
  2436.   extern int Client;
  2437.  
  2438.   if (is_daemon)
  2439.   {
  2440.     int num_interfaces = iface_count();
  2441.     int fd_listenset[FD_SETSIZE];
  2442.     fd_set listen_set;
  2443.     int s;
  2444.     int i;
  2445.  
  2446.     /* Stop zombies */
  2447. #ifdef SIGCLD_IGNORE
  2448.     signal(SIGCLD, SIG_IGN);
  2449. #else
  2450.     signal(SIGCLD, SIGNAL_CAST sig_cld);
  2451. #endif
  2452.  
  2453.     if(atexit_set == 0)
  2454.       atexit(killkids);
  2455.  
  2456.     FD_ZERO(&listen_set);
  2457.  
  2458.     if(lp_interfaces() && lp_bind_interfaces_only())
  2459.     {
  2460.        /* We have been given an interfaces line, and been 
  2461.           told to only bind to those interfaces. Create a
  2462.           socket per interface and bind to only these.
  2463.         */
  2464.  
  2465.       if(num_interfaces > FD_SETSIZE)
  2466.       {
  2467.         DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
  2468. max can be %d\n", num_interfaces, FD_SETSIZE));
  2469.         return False;
  2470.       }
  2471.  
  2472.       /* Now open a listen socket for each of the interfaces. */
  2473.       for(i = 0; i < num_interfaces; i++)
  2474.       {
  2475.         struct in_addr *ifip = iface_n_ip(i);
  2476.  
  2477.         if(ifip == NULL)
  2478.         {
  2479.           DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
  2480.           continue;
  2481.         }
  2482.         s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr);
  2483.         if(s == -1)
  2484.           return False;
  2485.         /* ready to listen */
  2486.         if (listen(s, 5) == -1) 
  2487.         {
  2488.           DEBUG(0,("listen: %s\n",strerror(errno)));
  2489.           close(s);
  2490.           return False;
  2491.         }
  2492.         FD_SET(s,&listen_set);
  2493.       }
  2494.     }
  2495.     else
  2496.     {
  2497.       /* Just bind to 0.0.0.0 - accept connections from anywhere. */
  2498.       num_interfaces = 1;
  2499.  
  2500.       /* open an incoming socket */
  2501.       s = open_socket_in(SOCK_STREAM, port, 0,interpret_addr(lp_socket_address()));
  2502.       if (s == -1)
  2503.         return(False);
  2504.  
  2505.       /* ready to listen */
  2506.       if (listen(s, 5) == -1) 
  2507.       {
  2508.         DEBUG(0,("open_sockets: listen: %s\n",strerror(errno)));
  2509.         close(s);
  2510.         return False;
  2511.       }
  2512.  
  2513.       fd_listenset[0] = s;
  2514.       FD_SET(s,&listen_set);
  2515.     }      
  2516.  
  2517.     /* now accept incoming connections - forking a new process
  2518.        for each incoming connection */
  2519.     DEBUG(2,("waiting for a connection\n"));
  2520.     while (1)
  2521.     {
  2522.       fd_set lfds;
  2523.       int num;
  2524.  
  2525.       memcpy((char *)&lfds, (char *)&listen_set, sizeof(listen_set));
  2526.  
  2527.       num = sys_select(&lfds,NULL);
  2528.  
  2529.       if (num == -1 && errno == EINTR)
  2530.         continue;
  2531.  
  2532.       /* Find the sockets that are read-ready - accept on these. */
  2533.       for( ; num > 0; num--)
  2534.       {
  2535.         struct sockaddr addr;
  2536.         int in_addrlen = sizeof(addr);
  2537.  
  2538.         s = -1;
  2539.         for(i = 0; i < num_interfaces; i++)
  2540.         {
  2541.           if(FD_ISSET(fd_listenset[i],&lfds))
  2542.           {
  2543.             s = fd_listenset[i];
  2544.             /* Clear this so we don't look at it again. */
  2545.             FD_CLR(fd_listenset[i],&lfds);
  2546.             break;
  2547.           }
  2548.         }
  2549.  
  2550.         Client = accept(s,&addr,&in_addrlen);
  2551.  
  2552.         if (Client == -1 && errno == EINTR)
  2553.           continue;
  2554.  
  2555.         if (Client == -1)
  2556.         {
  2557.           DEBUG(0,("open_sockets: accept: %s\n",strerror(errno)));
  2558.           continue;
  2559.         }
  2560.  
  2561. #ifdef NO_FORK_DEBUG
  2562. #ifndef NO_SIGNAL_TEST
  2563.         signal(SIGPIPE, SIGNAL_CAST sig_pipe);
  2564.         signal(SIGCLD, SIGNAL_CAST SIG_DFL);
  2565. #endif /* NO_SIGNAL_TEST */
  2566.         return True;
  2567. #else /* NO_FORK_DEBUG */
  2568.         if (Client != -1 && fork()==0)
  2569.         {
  2570.           /* Child code ... */
  2571.  
  2572. #ifndef NO_SIGNAL_TEST
  2573.           signal(SIGPIPE, SIGNAL_CAST sig_pipe);
  2574.           signal(SIGCLD, SIGNAL_CAST SIG_DFL);
  2575. #endif /* NO_SIGNAL_TEST */
  2576.           /* close the listening socket(s) */
  2577.           for(i = 0; i < num_interfaces; i++)
  2578.             close(fd_listenset[i]);
  2579.  
  2580.           /* close our standard file descriptors */
  2581.           close_low_fds();
  2582.           am_parent = 0;
  2583.   
  2584.           set_socket_options(Client,"SO_KEEPALIVE");
  2585.           set_socket_options(Client,user_socket_options);
  2586.  
  2587.           /* Reset global variables in util.c so that
  2588.              client substitutions will be done correctly
  2589.              in the process.
  2590.            */
  2591.           reset_globals_after_fork();
  2592.           return True; 
  2593.         }
  2594.         close(Client); /* The parent doesn't need this socket */
  2595. #endif /* NO_FORK_DEBUG */
  2596.       } /* end for num */
  2597.     } /* end while 1 */
  2598.   } /* end if is_daemon */
  2599.   else
  2600.   {
  2601.     /* Started from inetd. fd 0 is the socket. */
  2602.     /* We will abort gracefully when the client or remote system 
  2603.        goes away */
  2604. #ifndef NO_SIGNAL_TEST
  2605.     signal(SIGPIPE, SIGNAL_CAST sig_pipe);
  2606. #endif
  2607.     Client = dup(0);
  2608.  
  2609.     /* close our standard file descriptors */
  2610.     close_low_fds();
  2611.  
  2612.     set_socket_options(Client,"SO_KEEPALIVE");
  2613.     set_socket_options(Client,user_socket_options);
  2614.   }
  2615.  
  2616.   return True;
  2617. }
  2618.  
  2619. /****************************************************************************
  2620.   process an smb from the client - split out from the process() code so
  2621.   it can be used by the oplock break code.
  2622. ****************************************************************************/
  2623.  
  2624. static void process_smb(char *inbuf, char *outbuf)
  2625. {
  2626.   extern int Client;
  2627.   static int trans_num;
  2628.   int msg_type = CVAL(inbuf,0);
  2629.   int32 len = smb_len(inbuf);
  2630.   int nread = len + 4;
  2631.  
  2632.   if (trans_num == 0) {
  2633.       /* on the first packet, check the global hosts allow/ hosts
  2634.          deny parameters before doing any parsing of the packet
  2635.          passed to us by the client.  This prevents attacks on our
  2636.          parsing code from hosts not in the hosts allow list */
  2637.       if (!check_access(-1)) {
  2638.           /* send a negative session response "not listining on calling
  2639.            name" */
  2640.           static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
  2641.           DEBUG(1,("%s Connection denied from %s\n",
  2642.                timestring(),client_addr()));
  2643.           send_smb(Client,(char *)buf);
  2644.           exit_server("connection denied");
  2645.       }
  2646.   }
  2647.  
  2648.   DEBUG(6,("got message type 0x%x of len 0x%x\n",msg_type,len));
  2649.   DEBUG(3,("%s Transaction %d of length %d\n",timestring(),trans_num,nread));
  2650.  
  2651. #ifdef WITH_VTP
  2652.   if(trans_num == 1 && VT_Check(inbuf)) 
  2653.   {
  2654.     VT_Process();
  2655.     return;
  2656.   }
  2657. #endif
  2658.  
  2659.   if (msg_type == 0)
  2660.     show_msg(inbuf);
  2661.   else if(msg_type == 0x85)
  2662.     return; /* Keepalive packet. */
  2663.  
  2664.   nread = construct_reply(inbuf,outbuf,nread,max_send);
  2665.       
  2666.   if(nread > 0) 
  2667.   {
  2668.     if (CVAL(outbuf,0) == 0)
  2669.       show_msg(outbuf);
  2670.     
  2671.     if (nread != smb_len(outbuf) + 4) 
  2672.     {
  2673.       DEBUG(0,("ERROR: Invalid message response size! %d %d\n",
  2674.                  nread, smb_len(outbuf)));
  2675.     }
  2676.     else
  2677.       send_smb(Client,outbuf);
  2678.   }
  2679.   trans_num++;
  2680. }
  2681.  
  2682. /****************************************************************************
  2683.   open the oplock IPC socket communication
  2684. ****************************************************************************/
  2685. static BOOL open_oplock_ipc(void)
  2686. {
  2687.   struct sockaddr_in sock_name;
  2688.   int len = sizeof(sock_name);
  2689.  
  2690.   DEBUG(3,("open_oplock_ipc: opening loopback UDP socket.\n"));
  2691.  
  2692.   /* Open a lookback UDP socket on a random port. */
  2693.   oplock_sock = open_socket_in(SOCK_DGRAM, 0, 0, htonl(INADDR_LOOPBACK));
  2694.   if (oplock_sock == -1)
  2695.   {
  2696.     DEBUG(0,("open_oplock_ipc: Failed to get local UDP socket for \
  2697. address %x. Error was %s\n", htonl(INADDR_LOOPBACK), strerror(errno)));
  2698.     oplock_port = 0;
  2699.     return(False);
  2700.   }
  2701.  
  2702.   /* Find out the transient UDP port we have been allocated. */
  2703.   if(getsockname(oplock_sock, (struct sockaddr *)&sock_name, &len)<0)
  2704.   {
  2705.     DEBUG(0,("open_oplock_ipc: Failed to get local UDP port. Error was %s\n",
  2706.             strerror(errno)));
  2707.     close(oplock_sock);
  2708.     oplock_sock = -1;
  2709.     oplock_port = 0;
  2710.     return False;
  2711.   }
  2712.   oplock_port = ntohs(sock_name.sin_port);
  2713.  
  2714.   DEBUG(3,("open_oplock ipc: pid = %d, oplock_port = %u\n", 
  2715.             getpid(), oplock_port));
  2716.  
  2717.   return True;
  2718. }
  2719.  
  2720. /****************************************************************************
  2721.   process an oplock break message.
  2722. ****************************************************************************/
  2723. static BOOL process_local_message(int sock, char *buffer, int buf_size)
  2724. {
  2725.   int32 msg_len;
  2726.   uint16 from_port;
  2727.   char *msg_start;
  2728.  
  2729.   msg_len = IVAL(buffer,UDP_CMD_LEN_OFFSET);
  2730.   from_port = SVAL(buffer,UDP_CMD_PORT_OFFSET);
  2731.  
  2732.   msg_start = &buffer[UDP_CMD_HEADER_LEN];
  2733.  
  2734.   DEBUG(5,("process_local_message: Got a message of length %d from port (%d)\n", 
  2735.             msg_len, from_port));
  2736.  
  2737.   /* Switch on message command - currently OPLOCK_BREAK_CMD is the
  2738.      only valid request. */
  2739.  
  2740.   switch(SVAL(msg_start,UDP_MESSAGE_CMD_OFFSET))
  2741.   {
  2742.     case OPLOCK_BREAK_CMD:
  2743.       /* Ensure that the msg length is correct. */
  2744.       if(msg_len != OPLOCK_BREAK_MSG_LEN)
  2745.       {
  2746.         DEBUG(0,("process_local_message: incorrect length for OPLOCK_BREAK_CMD (was %d, \
  2747. should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
  2748.         return False;
  2749.       }
  2750.       {
  2751.         uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
  2752.         uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
  2753.         uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
  2754.         struct timeval tval;
  2755.         struct sockaddr_in toaddr;
  2756.  
  2757.         tval.tv_sec = IVAL(msg_start, OPLOCK_BREAK_SEC_OFFSET);
  2758.         tval.tv_usec = IVAL(msg_start, OPLOCK_BREAK_USEC_OFFSET);
  2759.  
  2760.         DEBUG(5,("process_local_message: oplock break request from \
  2761. pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
  2762.  
  2763.         /*
  2764.          * If we have no record of any currently open oplocks,
  2765.          * it's not an error, as a close command may have
  2766.          * just been issued on the file that was oplocked.
  2767.          * Just return success in this case.
  2768.          */
  2769.  
  2770.         if(global_oplocks_open != 0)
  2771.         {
  2772.           if(oplock_break(dev, inode, &tval) == False)
  2773.           {
  2774.             DEBUG(0,("process_local_message: oplock break failed - \
  2775. not returning udp message.\n"));
  2776.             return False;
  2777.           }
  2778.         }
  2779.         else
  2780.         {
  2781.           DEBUG(3,("process_local_message: oplock break requested with no outstanding \
  2782. oplocks. Returning success.\n"));
  2783.         }
  2784.  
  2785.         /* Send the message back after OR'ing in the 'REPLY' bit. */
  2786.         SSVAL(msg_start,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD | CMD_REPLY);
  2787.   
  2788.         bzero((char *)&toaddr,sizeof(toaddr));
  2789.         toaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2790.         toaddr.sin_port = htons(from_port);
  2791.         toaddr.sin_family = AF_INET;
  2792.  
  2793.         if(sendto( sock, msg_start, OPLOCK_BREAK_MSG_LEN, 0,
  2794.                 (struct sockaddr *)&toaddr, sizeof(toaddr)) < 0) 
  2795.         {
  2796.           DEBUG(0,("process_local_message: sendto process %d failed. Errno was %s\n",
  2797.                     remotepid, strerror(errno)));
  2798.           return False;
  2799.         }
  2800.  
  2801.         DEBUG(5,("process_local_message: oplock break reply sent to \
  2802. pid %d, port %d, for file dev = %x, inode = %x\n", remotepid, 
  2803.                 from_port, dev, inode));
  2804.  
  2805.       }
  2806.       break;
  2807.     /* 
  2808.      * Keep this as a debug case - eventually we can remove it.
  2809.      */
  2810.     case 0x8001:
  2811.       DEBUG(0,("process_local_message: Received unsolicited break \
  2812. reply - dumping info.\n"));
  2813.  
  2814.       if(msg_len != OPLOCK_BREAK_MSG_LEN)
  2815.       {
  2816.         DEBUG(0,("process_local_message: ubr: incorrect length for reply \
  2817. (was %d, should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
  2818.         return False;
  2819.       }
  2820.  
  2821.       {
  2822.         uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
  2823.         uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
  2824.         uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
  2825.  
  2826.         DEBUG(0,("process_local_message: unsolicited oplock break reply from \
  2827. pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
  2828.  
  2829.        }
  2830.        return False;
  2831.  
  2832.     default:
  2833.       DEBUG(0,("process_local_message: unknown UDP message command code (%x) - ignoring.\n",
  2834.                 (unsigned int)SVAL(msg_start,0)));
  2835.       return False;
  2836.   }
  2837.   return True;
  2838. }
  2839.  
  2840. /****************************************************************************
  2841.  Process an oplock break directly.
  2842. ****************************************************************************/
  2843. BOOL oplock_break(uint32 dev, uint32 inode, struct timeval *tval)
  2844. {
  2845.   extern int Client;
  2846.   char *inbuf = NULL;
  2847.   char *outbuf = NULL;
  2848.   files_struct *fsp = NULL;
  2849.   int fnum;
  2850.   time_t start_time;
  2851.   BOOL shutdown_server = False;
  2852.  
  2853.   DEBUG(3,("%s oplock_break: called for dev = %x, inode = %x. Current \
  2854. global_oplocks_open = %d\n", timestring(), dev, inode, global_oplocks_open));
  2855.  
  2856.   /* We need to search the file open table for the
  2857.      entry containing this dev and inode, and ensure
  2858.      we have an oplock on it. */
  2859.   for( fnum = 0; fnum < MAX_OPEN_FILES; fnum++)
  2860.   {
  2861.     if(OPEN_FNUM(fnum))
  2862.     {
  2863.       if((Files[fnum].fd_ptr->dev == dev) && (Files[fnum].fd_ptr->inode == inode) &&
  2864.          (Files[fnum].open_time.tv_sec == tval->tv_sec) && 
  2865.          (Files[fnum].open_time.tv_usec == tval->tv_usec)) {
  2866.           fsp = &Files[fnum];
  2867.           break;
  2868.       }
  2869.     }
  2870.   }
  2871.  
  2872.   if(fsp == NULL)
  2873.   {
  2874.     /* The file could have been closed in the meantime - return success. */
  2875.     DEBUG(0,("%s oplock_break: cannot find open file with dev = %x, inode = %x (fnum = %d) \
  2876. allowing break to succeed.\n", timestring(), dev, inode, fnum));
  2877.     return True;
  2878.   }
  2879.  
  2880.   /* Ensure we have an oplock on the file */
  2881.  
  2882.   /* There is a potential race condition in that an oplock could
  2883.      have been broken due to another udp request, and yet there are
  2884.      still oplock break messages being sent in the udp message
  2885.      queue for this file. So return true if we don't have an oplock,
  2886.      as we may have just freed it.
  2887.    */
  2888.  
  2889.   if(!fsp->granted_oplock)
  2890.   {
  2891.     DEBUG(0,("%s oplock_break: file %s (fnum = %d, dev = %x, inode = %x) has no oplock. Allowing break to succeed regardless.\n", timestring(), fsp->name, fnum, dev, inode));
  2892.     return True;
  2893.   }
  2894.  
  2895.   /* mark the oplock break as sent - we don't want to send twice! */
  2896.   if (fsp->sent_oplock_break)
  2897.   {
  2898.     DEBUG(0,("%s oplock_break: ERROR: oplock_break already sent for file %s (fnum = %d, dev = %x, inode = %x)\n", timestring(), fsp->name, fnum, dev, inode));
  2899.  
  2900.     /* We have to fail the open here as we cannot send another oplock break on this
  2901.        file whilst we are awaiting a response from the client - neither can we
  2902.        allow another open to succeed while we are waiting for the client. */
  2903.     return False;
  2904.   }
  2905.  
  2906.   /* Now comes the horrid part. We must send an oplock break to the client,
  2907.      and then process incoming messages until we get a close or oplock release.
  2908.      At this point we know we need a new inbuf/outbuf buffer pair.
  2909.      We cannot use these staticaly as we may recurse into here due to
  2910.      messages crossing on the wire.
  2911.    */
  2912.  
  2913.   if((inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
  2914.   {
  2915.     DEBUG(0,("oplock_break: malloc fail for input buffer.\n"));
  2916.     return False;
  2917.   }
  2918.  
  2919.   if((outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
  2920.   {
  2921.     DEBUG(0,("oplock_break: malloc fail for output buffer.\n"));
  2922.     free(inbuf);
  2923.     inbuf = NULL;
  2924.     return False;
  2925.   }
  2926.  
  2927.   /* Prepare the SMBlockingX message. */
  2928.   bzero(outbuf,smb_size);
  2929.   set_message(outbuf,8,0,True);
  2930.  
  2931.   SCVAL(outbuf,smb_com,SMBlockingX);
  2932.   SSVAL(outbuf,smb_tid,fsp->cnum);
  2933.   SSVAL(outbuf,smb_pid,0xFFFF);
  2934.   SSVAL(outbuf,smb_uid,0);
  2935.   SSVAL(outbuf,smb_mid,0xFFFF);
  2936.   SCVAL(outbuf,smb_vwv0,0xFF);
  2937.   SSVAL(outbuf,smb_vwv2,fnum);
  2938.   SCVAL(outbuf,smb_vwv3,LOCKING_ANDX_OPLOCK_RELEASE);
  2939.   /* Change this when we have level II oplocks. */
  2940.   SCVAL(outbuf,smb_vwv3+1,OPLOCKLEVEL_NONE);
  2941.  
  2942.   send_smb(Client, outbuf);
  2943.  
  2944.   /* Remember we just sent an oplock break on this file. */
  2945.   fsp->sent_oplock_break = True;
  2946.  
  2947.   /* We need this in case a readraw crosses on the wire. */
  2948.   global_oplock_break = True;
  2949.  
  2950.   /* Process incoming messages. */
  2951.  
  2952.   /* JRA - If we don't get a break from the client in OPLOCK_BREAK_TIMEOUT
  2953.      seconds we should just die.... */
  2954.  
  2955.   start_time = time(NULL);
  2956.  
  2957.   while(OPEN_FNUM(fnum) && fsp->granted_oplock)
  2958.   {
  2959.     if(receive_smb(Client,inbuf,OPLOCK_BREAK_TIMEOUT * 1000) == False)
  2960.     {
  2961.       /*
  2962.        * Die if we got an error.
  2963.        */
  2964.  
  2965.       if (smb_read_error == READ_EOF)
  2966.         DEBUG(0,("%s oplock_break: end of file from client\n", timestring()));
  2967.  
  2968.       if (smb_read_error == READ_ERROR)
  2969.         DEBUG(0,("%s oplock_break: receive_smb error (%s)\n",
  2970.                   timestring(), strerror(errno)));
  2971.  
  2972.       if (smb_read_error == READ_TIMEOUT)
  2973.         DEBUG(0,("%s oplock_break: receive_smb timed out after %d seconds.\n",
  2974.                   timestring(), OPLOCK_BREAK_TIMEOUT));
  2975.  
  2976.       DEBUG(0,("%s oplock_break failed for file %s (fnum = %d, dev = %x, \
  2977. inode = %x).\n", timestring(), fsp->name, fnum, dev, inode));
  2978.       shutdown_server = True;
  2979.       break;
  2980.     }
  2981.  
  2982.     /*
  2983.      * There are certain SMB requests that we shouldn't allow
  2984.      * to recurse. opens, renames and deletes are the obvious
  2985.      * ones. This is handled in the switch_message() function.
  2986.      * If global_oplock_break is set they will push the packet onto
  2987.      * the pending smb queue and return -1 (no reply).
  2988.      * JRA.
  2989.      */
  2990.  
  2991.     process_smb(inbuf, outbuf);
  2992.  
  2993.     /*
  2994.      * Die if we go over the time limit.
  2995.      */
  2996.  
  2997.     if((time(NULL) - start_time) > OPLOCK_BREAK_TIMEOUT)
  2998.     {
  2999.       DEBUG(0,("%s oplock_break: no break received from client within \
  3000. %d seconds.\n", timestring(), OPLOCK_BREAK_TIMEOUT));
  3001.       DEBUG(0,("%s oplock_break failed for file %s (fnum = %d, dev = %x, \
  3002. inode = %x).\n", timestring(), fsp->name, fnum, dev, inode));
  3003.       shutdown_server = True;
  3004.       break;
  3005.     }
  3006.   }
  3007.  
  3008.   /* Free the buffers we've been using to recurse. */
  3009.   free(inbuf);
  3010.   free(outbuf);
  3011.  
  3012.   /* We need this in case a readraw crossed on the wire. */
  3013.   if(global_oplock_break)
  3014.     global_oplock_break = False;
  3015.  
  3016.   /*
  3017.    * If the client did not respond we must die.
  3018.    */
  3019.  
  3020.   if(shutdown_server)
  3021.   {
  3022.     DEBUG(0,("%s oplock_break: client failure in break - shutting down this smbd.\n",
  3023.           timestring()));
  3024.     close_sockets();
  3025.     close(oplock_sock);
  3026.     exit_server("oplock break failure");
  3027.   }
  3028.  
  3029.   if(OPEN_FNUM(fnum))
  3030.   {
  3031.     /* The lockingX reply will have removed the oplock flag 
  3032.        from the sharemode. */
  3033.     /* Paranoia.... */
  3034.     fsp->granted_oplock = False;
  3035.     fsp->sent_oplock_break = False;
  3036.     global_oplocks_open--;
  3037.   }
  3038.  
  3039.   /* Santity check - remove this later. JRA */
  3040.   if(global_oplocks_open < 0)
  3041.   {
  3042.     DEBUG(0,("oplock_break: global_oplocks_open < 0 (%d). PANIC ERROR\n",
  3043.               global_oplocks_open));
  3044.     exit_server("oplock_break: global_oplocks_open < 0");
  3045.   }
  3046.  
  3047.   DEBUG(3,("%s oplock_break: returning success for fnum = %d, dev = %x, inode = %x. Current \
  3048. global_oplocks_open = %d\n", timestring(), fnum, dev, inode, global_oplocks_open));
  3049.  
  3050.   return True;
  3051. }
  3052.  
  3053. /****************************************************************************
  3054. Send an oplock break message to another smbd process. If the oplock is held 
  3055. by the local smbd then call the oplock break function directly.
  3056. ****************************************************************************/
  3057.  
  3058. BOOL request_oplock_break(share_mode_entry *share_entry, 
  3059.                           uint32 dev, uint32 inode)
  3060. {
  3061.   char op_break_msg[OPLOCK_BREAK_MSG_LEN];
  3062.   struct sockaddr_in addr_out;
  3063.   int pid = getpid();
  3064.   time_t start_time;
  3065.   int time_left;
  3066.  
  3067.   if(pid == share_entry->pid)
  3068.   {
  3069.     /* We are breaking our own oplock, make sure it's us. */
  3070.     if(share_entry->op_port != oplock_port)
  3071.     {
  3072.       DEBUG(0,("request_oplock_break: corrupt share mode entry - pid = %d, port = %d \
  3073. should be %d\n", pid, share_entry->op_port, oplock_port));
  3074.       return False;
  3075.     }
  3076.  
  3077.     DEBUG(5,("request_oplock_break: breaking our own oplock\n"));
  3078.  
  3079.     /* Call oplock break direct. */
  3080.     return oplock_break(dev, inode, &share_entry->time);
  3081.   }
  3082.  
  3083.   /* We need to send a OPLOCK_BREAK_CMD message to the
  3084.      port in the share mode entry. */
  3085.  
  3086.   SSVAL(op_break_msg,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD);
  3087.   SIVAL(op_break_msg,OPLOCK_BREAK_PID_OFFSET,pid);
  3088.   SIVAL(op_break_msg,OPLOCK_BREAK_DEV_OFFSET,dev);
  3089.   SIVAL(op_break_msg,OPLOCK_BREAK_INODE_OFFSET,inode);
  3090.   SIVAL(op_break_msg,OPLOCK_BREAK_SEC_OFFSET,(uint32)share_entry->time.tv_sec);
  3091.   SIVAL(op_break_msg,OPLOCK_BREAK_USEC_OFFSET,(uint32)share_entry->time.tv_usec);
  3092.  
  3093.   /* set the address and port */
  3094.   bzero((char *)&addr_out,sizeof(addr_out));
  3095.   addr_out.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3096.   addr_out.sin_port = htons( share_entry->op_port );
  3097.   addr_out.sin_family = AF_INET;
  3098.    
  3099.   DEBUG(3,("%s request_oplock_break: sending a oplock break message to pid %d on port %d \
  3100. for dev = %x, inode = %x\n", timestring(), share_entry->pid, share_entry->op_port, dev, inode));
  3101.  
  3102.   if(sendto(oplock_sock,op_break_msg,OPLOCK_BREAK_MSG_LEN,0,
  3103.          (struct sockaddr *)&addr_out,sizeof(addr_out)) < 0)
  3104.   {
  3105.     DEBUG(0,("%s request_oplock_break: failed when sending a oplock break message \
  3106. to pid %d on port %d for dev = %x, inode = %x. Error was %s\n",
  3107.          timestring(), share_entry->pid, share_entry->op_port, dev, inode,
  3108.          strerror(errno)));
  3109.     return False;
  3110.   }
  3111.  
  3112.   /*
  3113.    * Now we must await the oplock broken message coming back
  3114.    * from the target smbd process. Timeout if it fails to
  3115.    * return in (OPLOCK_BREAK_TIMEOUT + OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR) seconds.
  3116.    * While we get messages that aren't ours, loop.
  3117.    */
  3118.  
  3119.   start_time = time(NULL);
  3120.   time_left = OPLOCK_BREAK_TIMEOUT+OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR;
  3121.  
  3122.   while(time_left >= 0)
  3123.   {
  3124.     char op_break_reply[UDP_CMD_HEADER_LEN+OPLOCK_BREAK_MSG_LEN];
  3125.     int32 reply_msg_len;
  3126.     uint16 reply_from_port;
  3127.     char *reply_msg_start;
  3128.  
  3129.     if(receive_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply),
  3130.                time_left ? time_left * 1000 : 1) == False)
  3131.     {
  3132.       if(smb_read_error == READ_TIMEOUT)
  3133.       {
  3134.         DEBUG(0,("%s request_oplock_break: no response received to oplock break request to \
  3135. pid %d on port %d for dev = %x, inode = %x\n", timestring(), share_entry->pid, 
  3136.                            share_entry->op_port, dev, inode));
  3137.         /*
  3138.          * This is a hack to make handling of failing clients more robust.
  3139.          * If a oplock break response message is not received in the timeout
  3140.          * period we may assume that the smbd servicing that client holding
  3141.          * the oplock has died and the client changes were lost anyway, so
  3142.          * we should continue to try and open the file.
  3143.          */
  3144.         break;
  3145.       }
  3146.       else
  3147.         DEBUG(0,("%s request_oplock_break: error in response received to oplock break request to \
  3148. pid %d on port %d for dev = %x, inode = %x. Error was (%s).\n", timestring, share_entry->pid, 
  3149.                          share_entry->op_port, dev, inode, strerror(errno)));
  3150.       return False;
  3151.     }
  3152.  
  3153.     reply_msg_len = IVAL(op_break_reply,UDP_CMD_LEN_OFFSET);
  3154.     reply_from_port = SVAL(op_break_reply,UDP_CMD_PORT_OFFSET);
  3155.  
  3156.     reply_msg_start = &op_break_reply[UDP_CMD_HEADER_LEN];
  3157.  
  3158.     if(reply_msg_len != OPLOCK_BREAK_MSG_LEN)
  3159.     {
  3160.       /* Ignore it. */
  3161.       DEBUG(0,("%s request_oplock_break: invalid message length received. Ignoring\n",
  3162.              timestring()));
  3163.       continue;
  3164.     }
  3165.  
  3166.     /*
  3167.      * Test to see if this is the reply we are awaiting.
  3168.      */
  3169.  
  3170.     if((SVAL(reply_msg_start,UDP_MESSAGE_CMD_OFFSET) & CMD_REPLY) &&
  3171.        (reply_from_port == share_entry->op_port) && 
  3172.        (memcmp(&reply_msg_start[OPLOCK_BREAK_PID_OFFSET], 
  3173.                &op_break_msg[OPLOCK_BREAK_PID_OFFSET],
  3174.                OPLOCK_BREAK_MSG_LEN - OPLOCK_BREAK_PID_OFFSET) == 0))
  3175.     {
  3176.       /*
  3177.        * This is the reply we've been waiting for.
  3178.        */
  3179.       break;
  3180.     }
  3181.     else
  3182.     {
  3183.       /*
  3184.        * This is another message - probably a break request.
  3185.        * Process it to prevent potential deadlock.
  3186.        * Note that the code in switch_message() prevents
  3187.        * us from recursing into here as any SMB requests
  3188.        * we might process that would cause another oplock
  3189.        * break request to be made will be queued.
  3190.        * JRA.
  3191.        */
  3192.  
  3193.       process_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply));
  3194.     }
  3195.  
  3196.     time_left -= (time(NULL) - start_time);
  3197.   }
  3198.  
  3199.   DEBUG(3,("%s request_oplock_break: broke oplock.\n", timestring()));
  3200.  
  3201.   return True;
  3202. }
  3203.  
  3204. /****************************************************************************
  3205. Get the next SMB packet, doing the local message processing automatically.
  3206. ****************************************************************************/
  3207.  
  3208. BOOL receive_next_smb(int smbfd, int oplockfd, char *inbuf, int bufsize, int timeout)
  3209. {
  3210.   BOOL got_smb = False;
  3211.   BOOL ret;
  3212.  
  3213.   do
  3214.   {
  3215.     ret = receive_message_or_smb(smbfd,oplockfd,inbuf,bufsize,
  3216.                                  timeout,&got_smb);
  3217.  
  3218.     if(ret && !got_smb)
  3219.     {
  3220.       /* Deal with oplock break requests from other smbd's. */
  3221.       process_local_message(oplock_sock, inbuf, bufsize);
  3222.       continue;
  3223.     }
  3224.  
  3225.     if(ret && (CVAL(inbuf,0) == 0x85))
  3226.     {
  3227.       /* Keepalive packet. */
  3228.       got_smb = False;
  3229.     }
  3230.  
  3231.   }
  3232.   while(ret && !got_smb);
  3233.  
  3234.   return ret;
  3235. }
  3236.  
  3237. /****************************************************************************
  3238. check if a snum is in use
  3239. ****************************************************************************/
  3240. BOOL snum_used(int snum)
  3241. {
  3242.   int i;
  3243.   for (i=0;i<MAX_CONNECTIONS;i++)
  3244.     if (OPEN_CNUM(i) && (SNUM(i) == snum))
  3245.       return(True);
  3246.   return(False);
  3247. }
  3248.  
  3249. /****************************************************************************
  3250.   reload the services file
  3251.   **************************************************************************/
  3252. BOOL reload_services(BOOL test)
  3253. {
  3254.   BOOL ret;
  3255.  
  3256.   if (lp_loaded())
  3257.     {
  3258.       pstring fname;
  3259.       pstrcpy(fname,lp_configfile());
  3260.       if (file_exist(fname,NULL) && !strcsequal(fname,servicesf))
  3261.     {
  3262.       pstrcpy(servicesf,fname);
  3263.       test = False;
  3264.     }
  3265.     }
  3266.  
  3267.   reopen_logs();
  3268.  
  3269.   if (test && !lp_file_list_changed())
  3270.     return(True);
  3271.  
  3272.   lp_killunused(snum_used);
  3273.  
  3274.   ret = lp_load(servicesf,False);
  3275.  
  3276.   /* perhaps the config filename is now set */
  3277.   if (!test)
  3278.     reload_services(True);
  3279.  
  3280.   reopen_logs();
  3281.  
  3282.   load_interfaces();
  3283.  
  3284.   {
  3285.     extern int Client;
  3286.     if (Client != -1) {      
  3287.       set_socket_options(Client,"SO_KEEPALIVE");
  3288.       set_socket_options(Client,user_socket_options);
  3289.     }
  3290.   }
  3291.  
  3292.   reset_mangled_stack( lp_mangledstack() );
  3293.  
  3294.   /* this forces service parameters to be flushed */
  3295.   become_service(-1,True);
  3296.  
  3297.   return(ret);
  3298. }
  3299.  
  3300.  
  3301.  
  3302. /****************************************************************************
  3303. this prevents zombie child processes
  3304. ****************************************************************************/
  3305. static int sig_hup(void)
  3306. {
  3307.   BlockSignals(True,SIGHUP);
  3308.   DEBUG(0,("Got SIGHUP\n"));
  3309.   reload_services(False);
  3310. #ifndef DONT_REINSTALL_SIG
  3311.   signal(SIGHUP,SIGNAL_CAST sig_hup);
  3312. #endif
  3313.   BlockSignals(False,SIGHUP);
  3314.   return(0);
  3315. }
  3316.  
  3317. /****************************************************************************
  3318. Setup the groups a user belongs to.
  3319. ****************************************************************************/
  3320. int setup_groups(char *user, int uid, int gid, int *p_ngroups, 
  3321.          int **p_igroups, gid_t **p_groups,
  3322.          int **p_attrs)
  3323. {
  3324.   if (-1 == initgroups(user,gid))
  3325.     {
  3326.       if (getuid() == 0)
  3327.     {
  3328.       DEBUG(0,("Unable to initgroups!\n"));
  3329.       if (gid < 0 || gid > 16000 || uid < 0 || uid > 16000)
  3330.         DEBUG(0,("This is probably a problem with the account %s\n",user));
  3331.     }
  3332.     }
  3333.   else
  3334.     {
  3335.       int i,ngroups;
  3336.       int *igroups;
  3337.       int *attrs;
  3338.       gid_t grp = 0;
  3339.       ngroups = getgroups(0,&grp);
  3340.       if (ngroups <= 0)
  3341.         ngroups = 32;
  3342.       igroups = (int *)malloc(sizeof(int)*ngroups);
  3343.       attrs   = (int *)malloc(sizeof(int)*ngroups);
  3344.       for (i=0;i<ngroups;i++)
  3345.       {
  3346.         attrs  [i] = 0x7; /* XXXX don't know what NT user attributes are yet! */
  3347.         igroups[i] = 0x42424242;
  3348.       }
  3349.       ngroups = getgroups(ngroups,(gid_t *)igroups);
  3350.  
  3351.       if (igroups[0] == 0x42424242)
  3352.         ngroups = 0;
  3353.  
  3354.       *p_ngroups = ngroups;
  3355.       *p_attrs   = attrs;
  3356.  
  3357.       /* The following bit of code is very strange. It is due to the
  3358.          fact that some OSes use int* and some use gid_t* for
  3359.          getgroups, and some (like SunOS) use both, one in prototypes,
  3360.          and one in man pages and the actual code. Thus we detect it
  3361.          dynamically using some very ugly code */
  3362.       if (ngroups > 0)
  3363.         {
  3364.       /* does getgroups return ints or gid_t ?? */
  3365.       static BOOL groups_use_ints = True;
  3366.  
  3367.       if (groups_use_ints && 
  3368.           ngroups == 1 && 
  3369.           SVAL(igroups,2) == 0x4242)
  3370.         groups_use_ints = False;
  3371.       
  3372.           for (i=0;groups_use_ints && i<ngroups;i++)
  3373.             if (igroups[i] == 0x42424242)
  3374.               groups_use_ints = False;
  3375.           
  3376.           if (groups_use_ints)
  3377.           {
  3378.               *p_igroups = igroups;
  3379.               *p_groups = (gid_t *)igroups;      
  3380.           }
  3381.           else
  3382.           {
  3383.           gid_t *groups = (gid_t *)igroups;
  3384.           igroups = (int *)malloc(sizeof(int)*ngroups);
  3385.           for (i=0;i<ngroups;i++)
  3386.           {
  3387.             igroups[i] = groups[i];
  3388.           }
  3389.           *p_igroups = igroups;
  3390.           *p_groups = (gid_t *)groups;
  3391.         }
  3392.     }
  3393.       DEBUG(3,("%s is in %d groups\n",user,ngroups));
  3394.       for (i=0;i<ngroups;i++)
  3395.         DEBUG(3,("%d ",igroups[i]));
  3396.       DEBUG(3,("\n"));
  3397.     }
  3398.   return 0;
  3399. }
  3400.  
  3401. /****************************************************************************
  3402.   make a connection to a service
  3403. ****************************************************************************/
  3404. int make_connection(char *service,char *user,char *password, int pwlen, char *dev,uint16 vuid)
  3405. {
  3406.   int cnum;
  3407.   int snum;
  3408.   struct passwd *pass = NULL;
  3409.   connection_struct *pcon;
  3410.   BOOL guest = False;
  3411.   BOOL force = False;
  3412.   static BOOL first_connection = True;
  3413.  
  3414.   strlower(service);
  3415.  
  3416.   snum = find_service(service);
  3417.   if (snum < 0)
  3418.     {
  3419.       if (strequal(service,"IPC$"))
  3420.     {      
  3421.       DEBUG(3,("%s refusing IPC connection\n",timestring()));
  3422.       return(-3);
  3423.     }
  3424.  
  3425.       DEBUG(0,("%s %s (%s) couldn't find service %s\n",timestring(),remote_machine,client_addr(),service));      
  3426.       return(-2);
  3427.     }
  3428.  
  3429.   if (strequal(service,HOMES_NAME))
  3430.     {
  3431.       if (*user && Get_Pwnam(user,True))
  3432.     return(make_connection(user,user,password,pwlen,dev,vuid));
  3433.  
  3434.       if(lp_security() != SEC_SHARE)
  3435.       {
  3436.         if (validated_username(vuid))
  3437.         {
  3438.           pstrcpy(user,validated_username(vuid));
  3439.           return(make_connection(user,user,password,pwlen,dev,vuid));
  3440.         }
  3441.       }
  3442.       else
  3443.       {
  3444.         /*
  3445.          * Security = share. Try with sesssetup_user as the username.
  3446.          */
  3447.         if(*sesssetup_user)
  3448.         {
  3449.           pstrcpy(user,sesssetup_user);
  3450.           return(make_connection(user,user,password,pwlen,dev,vuid));
  3451.         }
  3452.       }
  3453.     }
  3454.  
  3455.   if (!lp_snum_ok(snum) || !check_access(snum)) {    
  3456.     return(-4);
  3457.   }
  3458.  
  3459.   /* you can only connect to the IPC$ service as an ipc device */
  3460.   if (strequal(service,"IPC$"))
  3461.     pstrcpy(dev,"IPC");
  3462.  
  3463.   if (*dev == '?' || !*dev)
  3464.     {
  3465.       if (lp_print_ok(snum))
  3466.     pstrcpy(dev,"LPT1:");
  3467.       else
  3468.     pstrcpy(dev,"A:");
  3469.     }
  3470.  
  3471.   /* if the request is as a printer and you can't print then refuse */
  3472.   strupper(dev);
  3473.   if (!lp_print_ok(snum) && (strncmp(dev,"LPT",3) == 0)) {
  3474.     DEBUG(1,("Attempt to connect to non-printer as a printer\n"));
  3475.     return(-6);
  3476.   }
  3477.  
  3478.   /* lowercase the user name */
  3479.   strlower(user);
  3480.  
  3481.   /* add it as a possible user name */
  3482.   add_session_user(service);
  3483.  
  3484.   /* shall we let them in? */
  3485.   if (!authorise_login(snum,user,password,pwlen,&guest,&force,vuid))
  3486.     {
  3487.       DEBUG(2,("%s invalid username/password for %s\n",timestring(),service));
  3488.       return(-1);
  3489.     }
  3490.   
  3491.   cnum = find_free_connection(str_checksum(service) + str_checksum(user));
  3492.   if (cnum < 0)
  3493.     {
  3494.       DEBUG(0,("%s couldn't find free connection\n",timestring()));      
  3495.       return(-1);
  3496.     }
  3497.  
  3498.   pcon = &Connections[cnum];
  3499.   bzero((char *)pcon,sizeof(*pcon));
  3500.  
  3501.   /* find out some info about the user */
  3502.   pass = Get_Pwnam(user,True);
  3503.  
  3504.   if (pass == NULL)
  3505.     {
  3506.       DEBUG(0,("%s couldn't find account %s\n",timestring(),user)); 
  3507.       return(-7);
  3508.     }
  3509.  
  3510.   pcon->read_only = lp_readonly(snum);
  3511.  
  3512.   {
  3513.     pstring list;
  3514.     StrnCpy(list,lp_readlist(snum),sizeof(pstring)-1);
  3515.     string_sub(list,"%S",service);
  3516.  
  3517.     if (user_in_list(user,list))
  3518.       pcon->read_only = True;
  3519.  
  3520.     StrnCpy(list,lp_writelist(snum),sizeof(pstring)-1);
  3521.     string_sub(list,"%S",service);
  3522.  
  3523.     if (user_in_list(user,list))
  3524.       pcon->read_only = False;    
  3525.   }
  3526.  
  3527.   /* admin user check */
  3528.  
  3529.   /* JRA - original code denied admin user if the share was
  3530.      marked read_only. Changed as I don't think this is needed,
  3531.      but old code left in case there is a problem here.
  3532.    */
  3533.   if (user_in_list(user,lp_admin_users(snum)) 
  3534. #if 0
  3535.       && !pcon->read_only)
  3536. #else
  3537.       )
  3538. #endif
  3539.     {
  3540.       pcon->admin_user = True;
  3541.       DEBUG(0,("%s logged in as admin user (root privileges)\n",user));
  3542.     }
  3543.   else
  3544.     pcon->admin_user = False;
  3545.     
  3546.   pcon->force_user = force;
  3547.   pcon->vuid = vuid;
  3548.   pcon->uid = pass->pw_uid;
  3549.   pcon->gid = pass->pw_gid;
  3550.   pcon->num_files_open = 0;
  3551.   pcon->lastused = time(NULL);
  3552.   pcon->service = snum;
  3553.   pcon->used = True;
  3554.   pcon->printer = (strncmp(dev,"LPT",3) == 0);
  3555.   pcon->ipc = (strncmp(dev,"IPC",3) == 0);
  3556.   pcon->dirptr = NULL;
  3557.   pcon->veto_list = NULL;
  3558.   pcon->hide_list = NULL;
  3559.   pcon->veto_oplock_list = NULL;
  3560.   string_set(&pcon->dirpath,"");
  3561.   string_set(&pcon->user,user);
  3562.  
  3563. #if HAVE_GETGRNAM 
  3564.   if (*lp_force_group(snum))
  3565.     {
  3566.       struct group *gptr;
  3567.       pstring gname;
  3568.  
  3569.       StrnCpy(gname,lp_force_group(snum),sizeof(pstring)-1);
  3570.       /* default service may be a group name         */
  3571.       string_sub(gname,"%S",service);
  3572.       gptr = (struct group *)getgrnam(gname);
  3573.  
  3574.       if (gptr)
  3575.     {
  3576.       pcon->gid = gptr->gr_gid;
  3577.       DEBUG(3,("Forced group %s\n",gname));
  3578.     }
  3579.       else
  3580.     DEBUG(1,("Couldn't find group %s\n",gname));
  3581.     }
  3582. #endif
  3583.  
  3584.   if (*lp_force_user(snum))
  3585.     {
  3586.       struct passwd *pass2;
  3587.       fstring fuser;
  3588.       fstrcpy(fuser,lp_force_user(snum));
  3589.       pass2 = (struct passwd *)Get_Pwnam(fuser,True);
  3590.       if (pass2)
  3591.     {
  3592.       pcon->uid = pass2->pw_uid;
  3593.       string_set(&pcon->user,fuser);
  3594.       fstrcpy(user,fuser);
  3595.       pcon->force_user = True;
  3596.       DEBUG(3,("Forced user %s\n",fuser));      
  3597.     }
  3598.       else
  3599.     DEBUG(1,("Couldn't find user %s\n",fuser));
  3600.     }
  3601.  
  3602.   {
  3603.     pstring s;
  3604.     pstrcpy(s,lp_pathname(snum));
  3605.     standard_sub(cnum,s);
  3606.     string_set(&pcon->connectpath,s);
  3607.     DEBUG(3,("Connect path is %s\n",s));
  3608.   }
  3609.  
  3610.   /* groups stuff added by ih */
  3611.   pcon->ngroups = 0;
  3612.   pcon->igroups = NULL;
  3613.   pcon->groups = NULL;
  3614.   pcon->attrs = NULL;
  3615.  
  3616.   if (!IS_IPC(cnum))
  3617.     {
  3618.       /* Find all the groups this uid is in and store them. Used by become_user() */
  3619.       setup_groups(pcon->user,pcon->uid,pcon->gid,
  3620.                   &pcon->ngroups,&pcon->igroups,&pcon->groups,&pcon->attrs);
  3621.       
  3622.       /* check number of connections */
  3623.       if (!claim_connection(cnum,
  3624.                 lp_servicename(SNUM(cnum)),
  3625.                 lp_max_connections(SNUM(cnum)),False))
  3626.     {
  3627.       DEBUG(1,("too many connections - rejected\n"));
  3628.       return(-8);
  3629.     }  
  3630.  
  3631.       if (lp_status(SNUM(cnum)))
  3632.     claim_connection(cnum,"STATUS.",MAXSTATUS,first_connection);
  3633.  
  3634.       first_connection = False;
  3635.     } /* IS_IPC */
  3636.  
  3637.   pcon->open = True;
  3638.  
  3639.   /* execute any "root preexec = " line */
  3640.   if (*lp_rootpreexec(SNUM(cnum)))
  3641.     {
  3642.       pstring cmd;
  3643.       pstrcpy(cmd,lp_rootpreexec(SNUM(cnum)));
  3644.       standard_sub(cnum,cmd);
  3645.       DEBUG(5,("cmd=%s\n",cmd));
  3646.       smbrun(cmd,NULL,False);
  3647.     }
  3648.  
  3649.   if (!become_user(&Connections[cnum], cnum,pcon->vuid))
  3650.     {
  3651.       DEBUG(0,("Can't become connected user!\n"));
  3652.       pcon->open = False;
  3653.       if (!IS_IPC(cnum)) {
  3654.     yield_connection(cnum,
  3655.              lp_servicename(SNUM(cnum)),
  3656.              lp_max_connections(SNUM(cnum)));
  3657.     if (lp_status(SNUM(cnum))) yield_connection(cnum,"STATUS.",MAXSTATUS);
  3658.       }
  3659.       return(-1);
  3660.     }
  3661.  
  3662.   if (ChDir(pcon->connectpath) != 0)
  3663.     {
  3664.       DEBUG(0,("Can't change directory to %s (%s)\n",
  3665.            pcon->connectpath,strerror(errno)));
  3666.       pcon->open = False;
  3667.       unbecome_user();
  3668.       if (!IS_IPC(cnum)) {
  3669.     yield_connection(cnum,
  3670.              lp_servicename(SNUM(cnum)),
  3671.              lp_max_connections(SNUM(cnum)));
  3672.     if (lp_status(SNUM(cnum))) yield_connection(cnum,"STATUS.",MAXSTATUS);
  3673.       }
  3674.       return(-5);      
  3675.     }
  3676.  
  3677.   string_set(&pcon->origpath,pcon->connectpath);
  3678.  
  3679. #if SOFTLINK_OPTIMISATION
  3680.   /* resolve any soft links early */
  3681.   {
  3682.     pstring s;
  3683.     pstrcpy(s,pcon->connectpath);
  3684.     GetWd(s);
  3685.     string_set(&pcon->connectpath,s);
  3686.     ChDir(pcon->connectpath);
  3687.   }
  3688. #endif
  3689.  
  3690.   num_connections_open++;
  3691.   add_session_user(user);
  3692.   
  3693.   /* execute any "preexec = " line */
  3694.   if (*lp_preexec(SNUM(cnum)))
  3695.     {
  3696.       pstring cmd;
  3697.       pstrcpy(cmd,lp_preexec(SNUM(cnum)));
  3698.       standard_sub(cnum,cmd);
  3699.       smbrun(cmd,NULL,False);
  3700.     }
  3701.   
  3702.   /* we've finished with the sensitive stuff */
  3703.   unbecome_user();
  3704.  
  3705.   /* Add veto/hide lists */
  3706.   if (!IS_IPC(cnum) && !IS_PRINT(cnum))
  3707.   {
  3708.     set_namearray( &pcon->veto_list, lp_veto_files(SNUM(cnum)));
  3709.     set_namearray( &pcon->hide_list, lp_hide_files(SNUM(cnum)));
  3710.     set_namearray( &pcon->veto_oplock_list, lp_veto_oplocks(SNUM(cnum)));
  3711.   }
  3712.  
  3713.   {
  3714.     DEBUG(IS_IPC(cnum)?3:1,("%s %s (%s) connect to service %s as user %s (uid=%d,gid=%d) (pid %d)\n",
  3715.                 timestring(),
  3716.                 remote_machine,
  3717.                 client_addr(),
  3718.                 lp_servicename(SNUM(cnum)),user,
  3719.                 pcon->uid,
  3720.                 pcon->gid,
  3721.                 (int)getpid()));
  3722.   }
  3723.  
  3724.   return(cnum);
  3725. }
  3726.  
  3727. /****************************************************************************
  3728.   Attempt to break an oplock on a file (if oplocked).
  3729.   Returns True if the file was closed as a result of
  3730.   the oplock break, False otherwise.
  3731.   Used as a last ditch attempt to free a space in the 
  3732.   file table when we have run out.
  3733. ****************************************************************************/
  3734.  
  3735. static BOOL attempt_close_oplocked_file(files_struct *fp)
  3736. {
  3737.  
  3738.   DEBUG(5,("attempt_close_oplocked_file: checking file %s.\n", fp->name));
  3739.  
  3740.   if (fp->open && fp->granted_oplock && !fp->sent_oplock_break) {
  3741.  
  3742.     /* Try and break the oplock. */
  3743.     file_fd_struct *fsp = fp->fd_ptr;
  3744.     if(oplock_break( fsp->dev, fsp->inode, &fp->open_time)) {
  3745.       if(!fp->open) /* Did the oplock break close the file ? */
  3746.         return True;
  3747.     }
  3748.   }
  3749.  
  3750.   return False;
  3751. }
  3752.  
  3753. /****************************************************************************
  3754.   find first available file slot
  3755. ****************************************************************************/
  3756. int find_free_file(void )
  3757. {
  3758.     int i;
  3759.     static int first_file;
  3760.  
  3761.     /* we want to give out file handles differently on each new
  3762.        connection because of a common bug in MS clients where they try to
  3763.        reuse a file descriptor from an earlier smb connection. This code
  3764.        increases the chance that the errant client will get an error rather
  3765.        than causing corruption */
  3766.     if (first_file == 0) {
  3767.         first_file = (getpid() ^ (int)time(NULL)) % MAX_OPEN_FILES;
  3768.         if (first_file == 0) first_file = 1;
  3769.     }
  3770.  
  3771.     if (first_file >= MAX_OPEN_FILES)
  3772.         first_file = 1;
  3773.  
  3774.     for (i=first_file;i<MAX_OPEN_FILES;i++)
  3775.         if (!Files[i].open && !Files[i].reserved) {
  3776.             memset(&Files[i], 0, sizeof(Files[i]));
  3777.             first_file = i+1;
  3778.             Files[i].reserved = True;
  3779.             return(i);
  3780.         }
  3781.  
  3782.     /* returning a file handle of 0 is a bad idea - so we start at 1 */
  3783.     for (i=1;i<first_file;i++)
  3784.         if (!Files[i].open && !Files[i].reserved) {
  3785.             memset(&Files[i], 0, sizeof(Files[i]));
  3786.             first_file = i+1;
  3787.             Files[i].reserved = True;
  3788.             return(i);
  3789.         }
  3790.  
  3791.         /* 
  3792.          * Before we give up, go through the open files 
  3793.          * and see if there are any files opened with a
  3794.          * batch oplock. If so break the oplock and then
  3795.          * re-use that entry (if it becomes closed).
  3796.          * This may help as NT/95 clients tend to keep
  3797.          * files batch oplocked for quite a long time
  3798.          * after they have finished with them.
  3799.          */
  3800.         for (i=first_file;i<MAX_OPEN_FILES;i++) {
  3801.           if(attempt_close_oplocked_file( &Files[i])) {
  3802.             memset(&Files[i], 0, sizeof(Files[i]));
  3803.             first_file = i+1;
  3804.             Files[i].reserved = True;
  3805.             return(i);
  3806.           }
  3807.         }
  3808.  
  3809.         for (i=1;i<MAX_OPEN_FILES;i++) {
  3810.           if(attempt_close_oplocked_file( &Files[i])) {
  3811.             memset(&Files[i], 0, sizeof(Files[i]));
  3812.             first_file = i+1;
  3813.             Files[i].reserved = True;
  3814.             return(i);
  3815.           }
  3816.         }
  3817.  
  3818.     DEBUG(1,("ERROR! Out of file structures - perhaps increase MAX_OPEN_FILES?\n"));
  3819.     return(-1);
  3820. }
  3821.  
  3822. /****************************************************************************
  3823.   find first available connection slot, starting from a random position.
  3824. The randomisation stops problems with the server dieing and clients
  3825. thinking the server is still available.
  3826. ****************************************************************************/
  3827. static int find_free_connection(int hash )
  3828. {
  3829.   int i;
  3830.   BOOL used=False;
  3831.   hash = (hash % (MAX_CONNECTIONS-2))+1;
  3832.  
  3833.  again:
  3834.  
  3835.   for (i=hash+1;i!=hash;)
  3836.     {
  3837.       if (!Connections[i].open && Connections[i].used == used) 
  3838.     {
  3839.       DEBUG(3,("found free connection number %d\n",i));
  3840.       return(i);
  3841.     }
  3842.       i++;
  3843.       if (i == MAX_CONNECTIONS)
  3844.     i = 1;
  3845.     }
  3846.  
  3847.   if (!used)
  3848.     {
  3849.       used = !used;
  3850.       goto again;
  3851.     }
  3852.  
  3853.   DEBUG(1,("ERROR! Out of connection structures\n"));
  3854.   return(-1);
  3855. }
  3856.  
  3857.  
  3858. /****************************************************************************
  3859. reply for the core protocol
  3860. ****************************************************************************/
  3861. int reply_corep(char *outbuf)
  3862. {
  3863.   int outsize = set_message(outbuf,1,0,True);
  3864.  
  3865.   Protocol = PROTOCOL_CORE;
  3866.  
  3867.   return outsize;
  3868. }
  3869.  
  3870.  
  3871. /****************************************************************************
  3872. reply for the coreplus protocol
  3873. ****************************************************************************/
  3874. int reply_coreplus(char *outbuf)
  3875. {
  3876.   int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
  3877.   int outsize = set_message(outbuf,13,0,True);
  3878.   SSVAL(outbuf,smb_vwv5,raw); /* tell redirector we support
  3879.                  readbraw and writebraw (possibly) */
  3880.   CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
  3881.   SSVAL(outbuf,smb_vwv1,0x1); /* user level security, don't encrypt */    
  3882.  
  3883.   Protocol = PROTOCOL_COREPLUS;
  3884.  
  3885.   return outsize;
  3886. }
  3887.  
  3888.  
  3889. /****************************************************************************
  3890. reply for the lanman 1.0 protocol
  3891. ****************************************************************************/
  3892. int reply_lanman1(char *outbuf)
  3893. {
  3894.   int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
  3895.   int secword=0;
  3896.   BOOL doencrypt = SMBENCRYPT();
  3897.   time_t t = time(NULL);
  3898.  
  3899.   if (lp_security()>=SEC_USER) secword |= 1;
  3900.   if (doencrypt) secword |= 2;
  3901.  
  3902.   set_message(outbuf,13,doencrypt?8:0,True);
  3903.   SSVAL(outbuf,smb_vwv1,secword); 
  3904.   /* Create a token value and add it to the outgoing packet. */
  3905.   if (doencrypt) 
  3906.     generate_next_challenge(smb_buf(outbuf));
  3907.  
  3908.   Protocol = PROTOCOL_LANMAN1;
  3909.  
  3910.   CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
  3911.   SSVAL(outbuf,smb_vwv2,max_recv);
  3912.   SSVAL(outbuf,smb_vwv3,lp_maxmux()); /* maxmux */
  3913.   SSVAL(outbuf,smb_vwv4,1);
  3914.   SSVAL(outbuf,smb_vwv5,raw); /* tell redirector we support
  3915.                  readbraw writebraw (possibly) */
  3916.   SIVAL(outbuf,smb_vwv6,getpid());
  3917.   SSVAL(outbuf,smb_vwv10, TimeDiff(t)/60);
  3918.  
  3919.   put_dos_date(outbuf,smb_vwv8,t);
  3920.  
  3921.   return (smb_len(outbuf)+4);
  3922. }
  3923.  
  3924.  
  3925. /****************************************************************************
  3926. reply for the lanman 2.0 protocol
  3927. ****************************************************************************/
  3928. int reply_lanman2(char *outbuf)
  3929. {
  3930.   int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
  3931.   int secword=0;
  3932.   BOOL doencrypt = SMBENCRYPT();
  3933.   time_t t = time(NULL);
  3934.   struct cli_state *cli = NULL;
  3935.   char cryptkey[8];
  3936.   char crypt_len = 0;
  3937.  
  3938.   if (lp_security() == SEC_SERVER) {
  3939.       cli = server_cryptkey();
  3940.   }
  3941.  
  3942.   if (cli) {
  3943.       DEBUG(3,("using password server validation\n"));
  3944.       doencrypt = ((cli->sec_mode & 2) != 0);
  3945.   }
  3946.  
  3947.   if (lp_security()>=SEC_USER) secword |= 1;
  3948.   if (doencrypt) secword |= 2;
  3949.  
  3950.   if (doencrypt) {
  3951.       crypt_len = 8;
  3952.       if (!cli) {
  3953.           generate_next_challenge(cryptkey);
  3954.       } else {
  3955.           memcpy(cryptkey, cli->cryptkey, 8);
  3956.           set_challenge(cli->cryptkey);
  3957.       }
  3958.   }
  3959.  
  3960.   set_message(outbuf,13,crypt_len,True);
  3961.   SSVAL(outbuf,smb_vwv1,secword); 
  3962.   SIVAL(outbuf,smb_vwv6,getpid());
  3963.   if (doencrypt) 
  3964.       memcpy(smb_buf(outbuf), cryptkey, 8);
  3965.  
  3966.   Protocol = PROTOCOL_LANMAN2;
  3967.  
  3968.   CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
  3969.   SSVAL(outbuf,smb_vwv2,max_recv);
  3970.   SSVAL(outbuf,smb_vwv3,lp_maxmux()); 
  3971.   SSVAL(outbuf,smb_vwv4,1);
  3972.   SSVAL(outbuf,smb_vwv5,raw); /* readbraw and/or writebraw */
  3973.   SSVAL(outbuf,smb_vwv10, TimeDiff(t)/60);
  3974.   put_dos_date(outbuf,smb_vwv8,t);
  3975.  
  3976.   return (smb_len(outbuf)+4);
  3977. }
  3978.  
  3979.  
  3980. /****************************************************************************
  3981. reply for the nt protocol
  3982. ****************************************************************************/
  3983. int reply_nt1(char *outbuf)
  3984. {
  3985.   /* dual names + lock_and_read + nt SMBs + remote API calls */
  3986.   int capabilities = CAP_NT_FIND|CAP_LOCK_AND_READ;
  3987. /*
  3988.   other valid capabilities which we may support at some time...
  3989.                      CAP_LARGE_FILES|CAP_NT_SMBS|CAP_RPC_REMOTE_APIS;
  3990.                      CAP_LARGE_READX|CAP_STATUS32|CAP_LEVEL_II_OPLOCKS;
  3991.  */
  3992.  
  3993.   int secword=0;
  3994.   BOOL doencrypt = SMBENCRYPT();
  3995.   time_t t = time(NULL);
  3996.   int data_len;
  3997.   struct cli_state *cli = NULL;
  3998.   char cryptkey[8];
  3999.   char crypt_len = 0;
  4000.  
  4001.   if (lp_security() == SEC_SERVER) {
  4002.       cli = server_cryptkey();
  4003.   }
  4004.  
  4005.   if (cli) {
  4006.       DEBUG(3,("using password server validation\n"));
  4007.       doencrypt = ((cli->sec_mode & 2) != 0);
  4008.   }
  4009.  
  4010.   if (doencrypt) {
  4011.       crypt_len = 8;
  4012.       if (!cli) {
  4013.           generate_next_challenge(cryptkey);
  4014.       } else {
  4015.           memcpy(cryptkey, cli->cryptkey, 8);
  4016.           set_challenge(cli->cryptkey);
  4017.       }
  4018.   }
  4019.  
  4020.   if (lp_readraw() && lp_writeraw()) {
  4021.       capabilities |= CAP_RAW_MODE;
  4022.   }
  4023.  
  4024.   if (lp_security() >= SEC_USER) secword |= 1;
  4025.   if (doencrypt) secword |= 2;
  4026.  
  4027.   /* decide where (if) to put the encryption challenge, and
  4028.      follow it with the OEM'd domain name
  4029.    */
  4030.   data_len = crypt_len + strlen(myworkgroup) + 1;
  4031.  
  4032.   set_message(outbuf,17,data_len,True);
  4033.   pstrcpy(smb_buf(outbuf)+crypt_len, myworkgroup);
  4034.  
  4035.   CVAL(outbuf,smb_vwv1) = secword;
  4036.   SSVALS(outbuf,smb_vwv16+1,crypt_len);
  4037.   if (doencrypt) 
  4038.       memcpy(smb_buf(outbuf), cryptkey, 8);
  4039.  
  4040.   Protocol = PROTOCOL_NT1;
  4041.  
  4042.   SSVAL(outbuf,smb_vwv1+1,lp_maxmux()); /* maxmpx */
  4043.   SSVAL(outbuf,smb_vwv2+1,1); /* num vcs */
  4044.   SIVAL(outbuf,smb_vwv3+1,0xffff); /* max buffer. LOTS! */
  4045.   SIVAL(outbuf,smb_vwv5+1,0xffff); /* raw size. LOTS! */
  4046.   SIVAL(outbuf,smb_vwv7+1,getpid()); /* session key */
  4047.   SIVAL(outbuf,smb_vwv9+1,capabilities); /* capabilities */
  4048.   put_long_date(outbuf+smb_vwv11+1,t);
  4049.   SSVALS(outbuf,smb_vwv15+1,TimeDiff(t)/60);
  4050.   SSVAL(outbuf,smb_vwv17,data_len); /* length of challenge+domain strings */
  4051.  
  4052.   return (smb_len(outbuf)+4);
  4053. }
  4054.  
  4055. /* these are the protocol lists used for auto architecture detection:
  4056.  
  4057. WinNT 3.51:
  4058. protocol [PC NETWORK PROGRAM 1.0]
  4059. protocol [XENIX CORE]
  4060. protocol [MICROSOFT NETWORKS 1.03]
  4061. protocol [LANMAN1.0]
  4062. protocol [Windows for Workgroups 3.1a]
  4063. protocol [LM1.2X002]
  4064. protocol [LANMAN2.1]
  4065. protocol [NT LM 0.12]
  4066.  
  4067. Win95:
  4068. protocol [PC NETWORK PROGRAM 1.0]
  4069. protocol [XENIX CORE]
  4070. protocol [MICROSOFT NETWORKS 1.03]
  4071. protocol [LANMAN1.0]
  4072. protocol [Windows for Workgroups 3.1a]
  4073. protocol [LM1.2X002]
  4074. protocol [LANMAN2.1]
  4075. protocol [NT LM 0.12]
  4076.  
  4077. OS/2:
  4078. protocol [PC NETWORK PROGRAM 1.0]
  4079. protocol [XENIX CORE]
  4080. protocol [LANMAN1.0]
  4081. protocol [LM1.2X002]
  4082. protocol [LANMAN2.1]
  4083. */
  4084.  
  4085. /*
  4086.   * Modified to recognize the architecture of the remote machine better.
  4087.   *
  4088.   * This appears to be the matrix of which protocol is used by which
  4089.   * MS product.
  4090.        Protocol                       WfWg    Win95   WinNT  OS/2
  4091.        PC NETWORK PROGRAM 1.0          1       1       1      1
  4092.        XENIX CORE                                      2      2
  4093.        MICROSOFT NETWORKS 3.0          2       2       
  4094.        DOS LM1.2X002                   3       3       
  4095.        MICROSOFT NETWORKS 1.03                         3
  4096.        DOS LANMAN2.1                   4       4       
  4097.        LANMAN1.0                                       4      3
  4098.        Windows for Workgroups 3.1a     5       5       5
  4099.        LM1.2X002                                       6      4
  4100.        LANMAN2.1                                       7      5
  4101.        NT LM 0.12                              6       8
  4102.   *
  4103.   *  tim@fsg.com 09/29/95
  4104.   */
  4105.   
  4106. #define ARCH_WFWG     0x3      /* This is a fudge because WfWg is like Win95 */
  4107. #define ARCH_WIN95    0x2
  4108. #define    ARCH_OS2      0xC      /* Again OS/2 is like NT */
  4109. #define ARCH_WINNT    0x8
  4110. #define ARCH_SAMBA    0x10
  4111.  
  4112. #define ARCH_ALL      0x1F
  4113.  
  4114. /* List of supported protocols, most desired first */
  4115. struct {
  4116.   char *proto_name;
  4117.   char *short_name;
  4118.   int (*proto_reply_fn)(char *);
  4119.   int protocol_level;
  4120. } supported_protocols[] = {
  4121.   {"NT LANMAN 1.0",           "NT1",      reply_nt1,      PROTOCOL_NT1},
  4122.   {"NT LM 0.12",              "NT1",      reply_nt1,      PROTOCOL_NT1},
  4123.   {"LM1.2X002",               "LANMAN2",  reply_lanman2,  PROTOCOL_LANMAN2},
  4124.   {"Samba",                   "LANMAN2",  reply_lanman2,  PROTOCOL_LANMAN2},
  4125.   {"DOS LM1.2X002",           "LANMAN2",  reply_lanman2,  PROTOCOL_LANMAN2},
  4126.   {"LANMAN1.0",               "LANMAN1",  reply_lanman1,  PROTOCOL_LANMAN1},
  4127.   {"MICROSOFT NETWORKS 3.0",  "LANMAN1",  reply_lanman1,  PROTOCOL_LANMAN1},
  4128.   {"MICROSOFT NETWORKS 1.03", "COREPLUS", reply_coreplus, PROTOCOL_COREPLUS},
  4129.   {"PC NETWORK PROGRAM 1.0",  "CORE",     reply_corep,    PROTOCOL_CORE}, 
  4130.   {NULL,NULL},
  4131. };
  4132.  
  4133.  
  4134. /****************************************************************************
  4135.   reply to a negprot
  4136. ****************************************************************************/
  4137. static int reply_negprot(char *inbuf,char *outbuf, int size, int bufsize)
  4138. {
  4139.   int outsize = set_message(outbuf,1,0,True);
  4140.   int Index=0;
  4141.   int choice= -1;
  4142.   int protocol;
  4143.   char *p;
  4144.   int bcc = SVAL(smb_buf(inbuf),-2);
  4145.   int arch = ARCH_ALL;
  4146.  
  4147.   p = smb_buf(inbuf)+1;
  4148.   while (p < (smb_buf(inbuf) + bcc))
  4149.     { 
  4150.       Index++;
  4151.       DEBUG(3,("Requested protocol [%s]\n",p));
  4152.       if (strcsequal(p,"Windows for Workgroups 3.1a"))
  4153.     arch &= ( ARCH_WFWG | ARCH_WIN95 | ARCH_WINNT );
  4154.       else if (strcsequal(p,"DOS LM1.2X002"))
  4155.     arch &= ( ARCH_WFWG | ARCH_WIN95 );
  4156.       else if (strcsequal(p,"DOS LANMAN2.1"))
  4157.     arch &= ( ARCH_WFWG | ARCH_WIN95 );
  4158.       else if (strcsequal(p,"NT LM 0.12"))
  4159.     arch &= ( ARCH_WIN95 | ARCH_WINNT );
  4160.       else if (strcsequal(p,"LANMAN2.1"))
  4161.     arch &= ( ARCH_WINNT | ARCH_OS2 );
  4162.       else if (strcsequal(p,"LM1.2X002"))
  4163.     arch &= ( ARCH_WINNT | ARCH_OS2 );
  4164.       else if (strcsequal(p,"MICROSOFT NETWORKS 1.03"))
  4165.     arch &= ARCH_WINNT;
  4166.       else if (strcsequal(p,"XENIX CORE"))
  4167.     arch &= ( ARCH_WINNT | ARCH_OS2 );
  4168.       else if (strcsequal(p,"Samba")) {
  4169.     arch = ARCH_SAMBA;
  4170.     break;
  4171.       }
  4172.  
  4173.       p += strlen(p) + 2;
  4174.     }
  4175.     
  4176.   switch ( arch ) {
  4177.   case ARCH_SAMBA:
  4178.     set_remote_arch(RA_SAMBA);
  4179.     break;
  4180.   case ARCH_WFWG:
  4181.     set_remote_arch(RA_WFWG);
  4182.     break;
  4183.   case ARCH_WIN95:
  4184.     set_remote_arch(RA_WIN95);
  4185.     break;
  4186.   case ARCH_WINNT:
  4187.     set_remote_arch(RA_WINNT);
  4188.     break;
  4189.   case ARCH_OS2:
  4190.     set_remote_arch(RA_OS2);
  4191.     break;
  4192.   default:
  4193.     set_remote_arch(RA_UNKNOWN);
  4194.     break;
  4195.   }
  4196.  
  4197.   /* possibly reload - change of architecture */
  4198.   reload_services(True);      
  4199.     
  4200.   /* a special case to stop password server loops */
  4201.   if (Index == 1 && strequal(remote_machine,myhostname) && 
  4202.       lp_security()==SEC_SERVER)
  4203.     exit_server("Password server loop!");
  4204.   
  4205.   /* Check for protocols, most desirable first */
  4206.   for (protocol = 0; supported_protocols[protocol].proto_name; protocol++)
  4207.     {
  4208.       p = smb_buf(inbuf)+1;
  4209.       Index = 0;
  4210.       if (lp_maxprotocol() >= supported_protocols[protocol].protocol_level)
  4211.     while (p < (smb_buf(inbuf) + bcc))
  4212.       { 
  4213.         if (strequal(p,supported_protocols[protocol].proto_name))
  4214.           choice = Index;
  4215.         Index++;
  4216.         p += strlen(p) + 2;
  4217.       }
  4218.       if(choice != -1)
  4219.     break;
  4220.     }
  4221.   
  4222.   SSVAL(outbuf,smb_vwv0,choice);
  4223.   if(choice != -1) {
  4224.     extern fstring remote_proto;
  4225.     fstrcpy(remote_proto,supported_protocols[protocol].short_name);
  4226.     reload_services(True);          
  4227.     outsize = supported_protocols[protocol].proto_reply_fn(outbuf);
  4228.     DEBUG(3,("Selected protocol %s\n",supported_protocols[protocol].proto_name));
  4229.   }
  4230.   else {
  4231.     DEBUG(0,("No protocol supported !\n"));
  4232.   }
  4233.   SSVAL(outbuf,smb_vwv0,choice);
  4234.   
  4235.   DEBUG(5,("%s negprot index=%d\n",timestring(),choice));
  4236.  
  4237.   return(outsize);
  4238. }
  4239.  
  4240.  
  4241. /****************************************************************************
  4242. close all open files for a connection
  4243. ****************************************************************************/
  4244. static void close_open_files(int cnum)
  4245. {
  4246.   int i;
  4247.   for (i=0;i<MAX_OPEN_FILES;i++)
  4248.     if( Files[i].cnum == cnum && Files[i].open) {
  4249.       close_file(i,False);
  4250.     }
  4251. }
  4252.  
  4253.  
  4254.  
  4255. /****************************************************************************
  4256. close a cnum
  4257. ****************************************************************************/
  4258. void close_cnum(int cnum, uint16 vuid)
  4259. {
  4260.   DirCacheFlush(SNUM(cnum));
  4261.  
  4262.   unbecome_user();
  4263.  
  4264.   if (!OPEN_CNUM(cnum))
  4265.     {
  4266.       DEBUG(0,("Can't close cnum %d\n",cnum));
  4267.       return;
  4268.     }
  4269.  
  4270.   DEBUG(IS_IPC(cnum)?3:1,("%s %s (%s) closed connection to service %s\n",
  4271.               timestring(),
  4272.               remote_machine,client_addr(),
  4273.               lp_servicename(SNUM(cnum))));
  4274.  
  4275.   yield_connection(cnum,
  4276.            lp_servicename(SNUM(cnum)),
  4277.            lp_max_connections(SNUM(cnum)));
  4278.  
  4279.   if (lp_status(SNUM(cnum)))
  4280.     yield_connection(cnum,"STATUS.",MAXSTATUS);
  4281.  
  4282.   close_open_files(cnum);
  4283.   dptr_closecnum(cnum);
  4284.  
  4285.   /* execute any "postexec = " line */
  4286.   if (*lp_postexec(SNUM(cnum)) && become_user(&Connections[cnum], cnum,vuid))
  4287.     {
  4288.       pstring cmd;
  4289.       pstrcpy(cmd,lp_postexec(SNUM(cnum)));
  4290.       standard_sub(cnum,cmd);
  4291.       smbrun(cmd,NULL,False);
  4292.       unbecome_user();
  4293.     }
  4294.  
  4295.   unbecome_user();
  4296.   /* execute any "root postexec = " line */
  4297.   if (*lp_rootpostexec(SNUM(cnum)))
  4298.     {
  4299.       pstring cmd;
  4300.       pstrcpy(cmd,lp_rootpostexec(SNUM(cnum)));
  4301.       standard_sub(cnum,cmd);
  4302.       smbrun(cmd,NULL,False);
  4303.     }
  4304.  
  4305.   Connections[cnum].open = False;
  4306.   num_connections_open--;
  4307.   if (Connections[cnum].ngroups && Connections[cnum].groups)
  4308.     {
  4309.       if (Connections[cnum].igroups != (int *)Connections[cnum].groups)
  4310.     free(Connections[cnum].groups);
  4311.       free(Connections[cnum].igroups);
  4312.       Connections[cnum].groups = NULL;
  4313.       Connections[cnum].igroups = NULL;
  4314.       Connections[cnum].ngroups = 0;
  4315.     }
  4316.  
  4317.   free_namearray(Connections[cnum].veto_list);
  4318.   free_namearray(Connections[cnum].hide_list);
  4319.   free_namearray(Connections[cnum].veto_oplock_list);
  4320.  
  4321.   string_set(&Connections[cnum].user,"");
  4322.   string_set(&Connections[cnum].dirpath,"");
  4323.   string_set(&Connections[cnum].connectpath,"");
  4324. }
  4325.  
  4326.  
  4327. /****************************************************************************
  4328. simple routines to do connection counting
  4329. ****************************************************************************/
  4330. BOOL yield_connection(int cnum,char *name,int max_connections)
  4331. {
  4332.   struct connect_record crec;
  4333.   pstring fname;
  4334.   FILE *f;
  4335.   int mypid = getpid();
  4336.   int i;
  4337.  
  4338.   DEBUG(3,("Yielding connection to %d %s\n",cnum,name));
  4339.  
  4340.   if (max_connections <= 0)
  4341.     return(True);
  4342.  
  4343.   bzero(&crec,sizeof(crec));
  4344.  
  4345.   pstrcpy(fname,lp_lockdir());
  4346.   standard_sub(cnum,fname);
  4347.   trim_string(fname,"","/");
  4348.  
  4349.   pstrcat(fname,"/");
  4350.   pstrcat(fname,name);
  4351.   pstrcat(fname,".LCK");
  4352.  
  4353.   f = fopen(fname,"r+");
  4354.   if (!f)
  4355.     {
  4356.       DEBUG(2,("Couldn't open lock file %s (%s)\n",fname,strerror(errno)));
  4357.       return(False);
  4358.     }
  4359.  
  4360.   fseek(f,0,SEEK_SET);
  4361.  
  4362.   /* find a free spot */
  4363.   for (i=0;i<max_connections;i++)
  4364.     {
  4365.       if (fread(&crec,sizeof(crec),1,f) != 1)
  4366.     {
  4367.       DEBUG(2,("Entry not found in lock file %s\n",fname));
  4368.       fclose(f);
  4369.       return(False);
  4370.     }
  4371.       if (crec.pid == mypid && crec.cnum == cnum)
  4372.     break;
  4373.     }
  4374.  
  4375.   if (crec.pid != mypid || crec.cnum != cnum)
  4376.     {
  4377.       fclose(f);
  4378.       DEBUG(2,("Entry not found in lock file %s\n",fname));
  4379.       return(False);
  4380.     }
  4381.  
  4382.   bzero((void *)&crec,sizeof(crec));
  4383.   
  4384.   /* remove our mark */
  4385.   if (fseek(f,i*sizeof(crec),SEEK_SET) != 0 ||
  4386.       fwrite(&crec,sizeof(crec),1,f) != 1)
  4387.     {
  4388.       DEBUG(2,("Couldn't update lock file %s (%s)\n",fname,strerror(errno)));
  4389.       fclose(f);
  4390.       return(False);
  4391.     }
  4392.  
  4393.   DEBUG(3,("Yield successful\n"));
  4394.  
  4395.   fclose(f);
  4396.   return(True);
  4397. }
  4398.  
  4399.  
  4400. /****************************************************************************
  4401. simple routines to do connection counting
  4402. ****************************************************************************/
  4403. BOOL claim_connection(int cnum,char *name,int max_connections,BOOL Clear)
  4404. {
  4405.   struct connect_record crec;
  4406.   pstring fname;
  4407.   FILE *f;
  4408.   int snum = SNUM(cnum);
  4409.   int i,foundi= -1;
  4410.   int total_recs;
  4411.  
  4412.   if (max_connections <= 0)
  4413.     return(True);
  4414.  
  4415.   DEBUG(5,("trying claim %s %s %d\n",lp_lockdir(),name,max_connections));
  4416.  
  4417.   pstrcpy(fname,lp_lockdir());
  4418.   standard_sub(cnum,fname);
  4419.   trim_string(fname,"","/");
  4420.  
  4421.   if (!directory_exist(fname,NULL))
  4422.     mkdir(fname,0755);
  4423.  
  4424.   pstrcat(fname,"/");
  4425.   pstrcat(fname,name);
  4426.   pstrcat(fname,".LCK");
  4427.  
  4428.   if (!file_exist(fname,NULL))
  4429.     {
  4430.       int oldmask = umask(022);
  4431.       f = fopen(fname,"w");
  4432.       if (f) fclose(f);
  4433.       umask(oldmask);
  4434.     }
  4435.  
  4436.   total_recs = file_size(fname) / sizeof(crec);
  4437.  
  4438.   f = fopen(fname,"r+");
  4439.  
  4440.   if (!f)
  4441.     {
  4442.       DEBUG(1,("couldn't open lock file %s\n",fname));
  4443.       return(False);
  4444.     }
  4445.  
  4446.   /* find a free spot */
  4447.   for (i=0;i<max_connections;i++)
  4448.     {
  4449.  
  4450.       if (i>=total_recs || 
  4451.       fseek(f,i*sizeof(crec),SEEK_SET) != 0 ||
  4452.       fread(&crec,sizeof(crec),1,f) != 1)
  4453.     {
  4454.       if (foundi < 0) foundi = i;
  4455.       break;
  4456.     }
  4457.  
  4458.       if (Clear && crec.pid && !process_exists(crec.pid))
  4459.     {
  4460.       fseek(f,i*sizeof(crec),SEEK_SET);
  4461.       bzero((void *)&crec,sizeof(crec));
  4462.       fwrite(&crec,sizeof(crec),1,f);
  4463.       if (foundi < 0) foundi = i;
  4464.       continue;
  4465.     }
  4466.       if (foundi < 0 && (!crec.pid || !process_exists(crec.pid)))
  4467.     {
  4468.       foundi=i;
  4469.       if (!Clear) break;
  4470.     }
  4471.     }  
  4472.  
  4473.   if (foundi < 0)
  4474.     {
  4475.       DEBUG(3,("no free locks in %s\n",fname));
  4476.       fclose(f);
  4477.       return(False);
  4478.     }      
  4479.  
  4480.   /* fill in the crec */
  4481.   bzero((void *)&crec,sizeof(crec));
  4482.   crec.magic = 0x280267;
  4483.   crec.pid = getpid();
  4484.   crec.cnum = cnum;
  4485.   crec.uid = Connections[cnum].uid;
  4486.   crec.gid = Connections[cnum].gid;
  4487.   StrnCpy(crec.name,lp_servicename(snum),sizeof(crec.name)-1);
  4488.   crec.start = time(NULL);
  4489.  
  4490.   StrnCpy(crec.machine,remote_machine,sizeof(crec.machine)-1);
  4491.   StrnCpy(crec.addr,client_addr(),sizeof(crec.addr)-1);
  4492.   
  4493.   /* make our mark */
  4494.   if (fseek(f,foundi*sizeof(crec),SEEK_SET) != 0 ||
  4495.       fwrite(&crec,sizeof(crec),1,f) != 1)
  4496.     {
  4497.       fclose(f);
  4498.       return(False);
  4499.     }
  4500.  
  4501.   fclose(f);
  4502.   return(True);
  4503. }
  4504.  
  4505. #if DUMP_CORE
  4506. /*******************************************************************
  4507. prepare to dump a core file - carefully!
  4508. ********************************************************************/
  4509. static BOOL dump_core(void)
  4510. {
  4511.   char *p;
  4512.   pstring dname;
  4513.   pstrcpy(dname,debugf);
  4514.   if ((p=strrchr(dname,'/'))) *p=0;
  4515.   pstrcat(dname,"/corefiles");
  4516.   mkdir(dname,0700);
  4517.   sys_chown(dname,getuid(),getgid());
  4518.   chmod(dname,0700);
  4519.   if (chdir(dname)) return(False);
  4520.   umask(~(0700));
  4521.  
  4522. #ifndef NO_GETRLIMIT
  4523. #ifdef RLIMIT_CORE
  4524.   {
  4525.     struct rlimit rlp;
  4526.     getrlimit(RLIMIT_CORE, &rlp);
  4527.     rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
  4528.     setrlimit(RLIMIT_CORE, &rlp);
  4529.     getrlimit(RLIMIT_CORE, &rlp);
  4530.     DEBUG(3,("Core limits now %d %d\n",rlp.rlim_cur,rlp.rlim_max));
  4531.   }
  4532. #endif
  4533. #endif
  4534.  
  4535.  
  4536.   DEBUG(0,("Dumping core in %s\n",dname));
  4537.   return(True);
  4538. }
  4539. #endif
  4540.  
  4541. /****************************************************************************
  4542. exit the server
  4543. ****************************************************************************/
  4544. void exit_server(char *reason)
  4545. {
  4546.   static int firsttime=1;
  4547.   int i;
  4548.  
  4549.   if (!firsttime) exit(0);
  4550.   firsttime = 0;
  4551.  
  4552.   unbecome_user();
  4553.   DEBUG(2,("Closing connections\n"));
  4554.   for (i=0;i<MAX_CONNECTIONS;i++)
  4555.     if (Connections[i].open)
  4556.       close_cnum(i,(uint16)-1);
  4557. #ifdef DFS_AUTH
  4558.   if (dcelogin_atmost_once)
  4559.     dfs_unlogin();
  4560. #endif
  4561.   if (!reason) {   
  4562.     int oldlevel = DEBUGLEVEL;
  4563.     DEBUGLEVEL = 10;
  4564.     DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
  4565.     if (last_inbuf)
  4566.       show_msg(last_inbuf);
  4567.     DEBUGLEVEL = oldlevel;
  4568.     DEBUG(0,("===============================================================\n"));
  4569. #if DUMP_CORE
  4570.     if (dump_core()) return;
  4571. #endif
  4572.   }    
  4573.  
  4574.   locking_end();
  4575.  
  4576.   DEBUG(3,("%s Server exit  (%s)\n",timestring(),reason?reason:""));
  4577.   exit(0);
  4578. }
  4579.  
  4580. /****************************************************************************
  4581. do some standard substitutions in a string
  4582. ****************************************************************************/
  4583. void standard_sub(int cnum,char *str)
  4584. {
  4585.   if (VALID_CNUM(cnum)) {
  4586.     char *p, *s, *home;
  4587.  
  4588.     for ( s=str ; (p=strchr(s, '%')) != NULL ; s=p ) {
  4589.       switch (*(p+1)) {
  4590.         case 'H' : if ((home = get_home_dir(Connections[cnum].user))!=NULL)
  4591.                      string_sub(p,"%H",home);
  4592.                    else
  4593.                      p += 2;
  4594.                    break;
  4595.         case 'P' : string_sub(p,"%P",Connections[cnum].connectpath); break;
  4596.         case 'S' : string_sub(p,"%S",lp_servicename(Connections[cnum].service)); break;
  4597.         case 'g' : string_sub(p,"%g",gidtoname(Connections[cnum].gid)); break;
  4598.         case 'u' : string_sub(p,"%u",Connections[cnum].user); break;
  4599.     /* 
  4600.          * Patch from jkf@soton.ac.uk
  4601.          * Left the %N (NIS server name) in standard_sub_basic as it
  4602.          * is a feature for logon servers, hence uses the username.
  4603.      * The %p (NIS server path) code is here as it is used
  4604.      * instead of the default "path =" string in [homes] and so
  4605.      * needs the service name, not the username. 
  4606.          */
  4607.     case 'p' : string_sub(p,"%p",automount_path(lp_servicename(Connections[cnum].service))); break;
  4608.         case '\0' : p++; break; /* don't run off the end of the string */
  4609.         default  : p+=2; break;
  4610.       }
  4611.     }
  4612.   }
  4613.   standard_sub_basic(str);
  4614. }
  4615.  
  4616. /*
  4617. These flags determine some of the permissions required to do an operation 
  4618.  
  4619. Note that I don't set NEED_WRITE on some write operations because they
  4620. are used by some brain-dead clients when printing, and I don't want to
  4621. force write permissions on print services.
  4622. */
  4623. #define AS_USER (1<<0)
  4624. #define NEED_WRITE (1<<1)
  4625. #define TIME_INIT (1<<2)
  4626. #define CAN_IPC (1<<3)
  4627. #define AS_GUEST (1<<5)
  4628. #define QUEUE_IN_OPLOCK (1<<6)
  4629.  
  4630. /* 
  4631.    define a list of possible SMB messages and their corresponding
  4632.    functions. Any message that has a NULL function is unimplemented -
  4633.    please feel free to contribute implementations!
  4634. */
  4635.  
  4636. struct smb_message_struct
  4637. {
  4638.   int code;
  4639.   char *name;
  4640.   int (*fn)(char *, char *, int, int);
  4641.   int flags;
  4642. #if PROFILING
  4643.   unsigned long time;
  4644. #endif
  4645. }
  4646.  smb_messages[] = {
  4647.  
  4648.     /* CORE PROTOCOL */
  4649.  
  4650.    {SMBnegprot,"SMBnegprot",reply_negprot,0},
  4651.    {SMBtcon,"SMBtcon",reply_tcon,0},
  4652.    {SMBtdis,"SMBtdis",reply_tdis,0},
  4653.    {SMBexit,"SMBexit",reply_exit,0},
  4654.    {SMBioctl,"SMBioctl",reply_ioctl,0},
  4655.    {SMBecho,"SMBecho",reply_echo,0},
  4656.    {SMBsesssetupX,"SMBsesssetupX",reply_sesssetup_and_X,0},
  4657.    {SMBtconX,"SMBtconX",reply_tcon_and_X,0},
  4658.    {SMBulogoffX, "SMBulogoffX",reply_ulogoffX, 0}, /* ulogoff doesn't give a valid TID */
  4659.    {SMBgetatr,"SMBgetatr",reply_getatr,AS_USER},
  4660.    {SMBsetatr,"SMBsetatr",reply_setatr,AS_USER | NEED_WRITE},
  4661.    {SMBchkpth,"SMBchkpth",reply_chkpth,AS_USER},
  4662.    {SMBsearch,"SMBsearch",reply_search,AS_USER},
  4663.    {SMBopen,"SMBopen",reply_open,AS_USER | QUEUE_IN_OPLOCK },
  4664.  
  4665.    /* note that SMBmknew and SMBcreate are deliberately overloaded */   
  4666.    {SMBcreate,"SMBcreate",reply_mknew,AS_USER},
  4667.    {SMBmknew,"SMBmknew",reply_mknew,AS_USER}, 
  4668.  
  4669.    {SMBunlink,"SMBunlink",reply_unlink,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
  4670.    {SMBread,"SMBread",reply_read,AS_USER},
  4671.    {SMBwrite,"SMBwrite",reply_write,AS_USER},
  4672.    {SMBclose,"SMBclose",reply_close,AS_USER | CAN_IPC},
  4673.    {SMBmkdir,"SMBmkdir",reply_mkdir,AS_USER | NEED_WRITE},
  4674.    {SMBrmdir,"SMBrmdir",reply_rmdir,AS_USER | NEED_WRITE},
  4675.    {SMBdskattr,"SMBdskattr",reply_dskattr,AS_USER},
  4676.    {SMBmv,"SMBmv",reply_mv,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
  4677.  
  4678.    /* this is a Pathworks specific call, allowing the 
  4679.       changing of the root path */
  4680.    {pSETDIR,"pSETDIR",reply_setdir,AS_USER}, 
  4681.  
  4682.    {SMBlseek,"SMBlseek",reply_lseek,AS_USER},
  4683.    {SMBflush,"SMBflush",reply_flush,AS_USER},
  4684.    {SMBctemp,"SMBctemp",reply_ctemp,AS_USER | QUEUE_IN_OPLOCK },
  4685.    {SMBsplopen,"SMBsplopen",reply_printopen,AS_USER | QUEUE_IN_OPLOCK },
  4686.    {SMBsplclose,"SMBsplclose",reply_printclose,AS_USER},
  4687.    {SMBsplretq,"SMBsplretq",reply_printqueue,AS_USER|AS_GUEST},
  4688.    {SMBsplwr,"SMBsplwr",reply_printwrite,AS_USER},
  4689.    {SMBlock,"SMBlock",reply_lock,AS_USER},
  4690.    {SMBunlock,"SMBunlock",reply_unlock,AS_USER},
  4691.    
  4692.    /* CORE+ PROTOCOL FOLLOWS */
  4693.    
  4694.    {SMBreadbraw,"SMBreadbraw",reply_readbraw,AS_USER},
  4695.    {SMBwritebraw,"SMBwritebraw",reply_writebraw,AS_USER},
  4696.    {SMBwriteclose,"SMBwriteclose",reply_writeclose,AS_USER},
  4697.    {SMBlockread,"SMBlockread",reply_lockread,AS_USER},
  4698.    {SMBwriteunlock,"SMBwriteunlock",reply_writeunlock,AS_USER},
  4699.    
  4700.    /* LANMAN1.0 PROTOCOL FOLLOWS */
  4701.    
  4702.    {SMBreadBmpx,"SMBreadBmpx",reply_readbmpx,AS_USER},
  4703.    {SMBreadBs,"SMBreadBs",NULL,AS_USER},
  4704.    {SMBwriteBmpx,"SMBwriteBmpx",reply_writebmpx,AS_USER},
  4705.    {SMBwriteBs,"SMBwriteBs",reply_writebs,AS_USER},
  4706.    {SMBwritec,"SMBwritec",NULL,AS_USER},
  4707.    {SMBsetattrE,"SMBsetattrE",reply_setattrE,AS_USER | NEED_WRITE},
  4708.    {SMBgetattrE,"SMBgetattrE",reply_getattrE,AS_USER},
  4709.    {SMBtrans,"SMBtrans",reply_trans,AS_USER | CAN_IPC},
  4710.    {SMBtranss,"SMBtranss",NULL,AS_USER | CAN_IPC},
  4711.    {SMBioctls,"SMBioctls",NULL,AS_USER},
  4712.    {SMBcopy,"SMBcopy",reply_copy,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
  4713.    {SMBmove,"SMBmove",NULL,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
  4714.    
  4715.    {SMBopenX,"SMBopenX",reply_open_and_X,AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
  4716.    {SMBreadX,"SMBreadX",reply_read_and_X,AS_USER},
  4717.    {SMBwriteX,"SMBwriteX",reply_write_and_X,AS_USER},
  4718.    {SMBlockingX,"SMBlockingX",reply_lockingX,AS_USER},
  4719.    
  4720.    {SMBffirst,"SMBffirst",reply_search,AS_USER},
  4721.    {SMBfunique,"SMBfunique",reply_search,AS_USER},
  4722.    {SMBfclose,"SMBfclose",reply_fclose,AS_USER},
  4723.  
  4724.    /* LANMAN2.0 PROTOCOL FOLLOWS */
  4725.    {SMBfindnclose, "SMBfindnclose",reply_findnclose, AS_USER},
  4726.    {SMBfindclose, "SMBfindclose",reply_findclose,AS_USER},
  4727.    {SMBtrans2, "SMBtrans2",reply_trans2, AS_USER},
  4728.    {SMBtranss2, "SMBtranss2",reply_transs2, AS_USER},
  4729.  
  4730.    /* messaging routines */
  4731.    {SMBsends,"SMBsends",reply_sends,AS_GUEST},
  4732.    {SMBsendstrt,"SMBsendstrt",reply_sendstrt,AS_GUEST},
  4733.    {SMBsendend,"SMBsendend",reply_sendend,AS_GUEST},
  4734.    {SMBsendtxt,"SMBsendtxt",reply_sendtxt,AS_GUEST},
  4735.  
  4736.    /* NON-IMPLEMENTED PARTS OF THE CORE PROTOCOL */
  4737.    
  4738.    {SMBsendb,"SMBsendb",NULL,AS_GUEST},
  4739.    {SMBfwdname,"SMBfwdname",NULL,AS_GUEST},
  4740.    {SMBcancelf,"SMBcancelf",NULL,AS_GUEST},
  4741.    {SMBgetmac,"SMBgetmac",NULL,AS_GUEST}
  4742.  };
  4743.  
  4744. /****************************************************************************
  4745. return a string containing the function name of a SMB command
  4746. ****************************************************************************/
  4747. char *smb_fn_name(int type)
  4748. {
  4749.   static char *unknown_name = "SMBunknown";
  4750.   static int num_smb_messages = 
  4751.     sizeof(smb_messages) / sizeof(struct smb_message_struct);
  4752.   int match;
  4753.  
  4754.   for (match=0;match<num_smb_messages;match++)
  4755.     if (smb_messages[match].code == type)
  4756.       break;
  4757.  
  4758.   if (match == num_smb_messages)
  4759.     return(unknown_name);
  4760.  
  4761.   return(smb_messages[match].name);
  4762. }
  4763.  
  4764.  
  4765. /****************************************************************************
  4766. do a switch on the message type, and return the response size
  4767. ****************************************************************************/
  4768. static int switch_message(int type,char *inbuf,char *outbuf,int size,int bufsize)
  4769. {
  4770.   static int pid= -1;
  4771.   int outsize = 0;
  4772.   static int num_smb_messages = 
  4773.     sizeof(smb_messages) / sizeof(struct smb_message_struct);
  4774.   int match;
  4775.  
  4776. #if PROFILING
  4777.   struct timeval msg_start_time;
  4778.   struct timeval msg_end_time;
  4779.   static unsigned long total_time = 0;
  4780.  
  4781.   GetTimeOfDay(&msg_start_time);
  4782. #endif
  4783.  
  4784.   if (pid == -1)
  4785.     pid = getpid();
  4786.  
  4787.   errno = 0;
  4788.   last_message = type;
  4789.  
  4790.   /* make sure this is an SMB packet */
  4791.   if (strncmp(smb_base(inbuf),"\377SMB",4) != 0)
  4792.     {
  4793.       DEBUG(2,("Non-SMB packet of length %d\n",smb_len(inbuf)));
  4794.       return(-1);
  4795.     }
  4796.  
  4797.   for (match=0;match<num_smb_messages;match++)
  4798.     if (smb_messages[match].code == type)
  4799.       break;
  4800.  
  4801.   if (match == num_smb_messages)
  4802.     {
  4803.       DEBUG(0,("Unknown message type %d!\n",type));
  4804.       outsize = reply_unknown(inbuf,outbuf);
  4805.     }
  4806.   else
  4807.     {
  4808.       DEBUG(3,("switch message %s (pid %d)\n",smb_messages[match].name,pid));
  4809.  
  4810.       if(global_oplock_break && (smb_messages[match].flags & QUEUE_IN_OPLOCK))
  4811.       {
  4812.         /* 
  4813.          * Queue this message as we are the process of an oplock break.
  4814.          */
  4815.  
  4816.         DEBUG(2,("%s: switch_message: queueing message due to being in oplock break state.\n",
  4817.                timestring() ));
  4818.  
  4819.         push_smb_message( inbuf, size);
  4820.         return -1;
  4821.       }          
  4822.  
  4823.       if (smb_messages[match].fn)
  4824.     {
  4825.       int cnum = SVAL(inbuf,smb_tid);
  4826.       int flags = smb_messages[match].flags;
  4827.           static uint16 last_session_tag = UID_FIELD_INVALID;
  4828.           /* In share mode security we must ignore the vuid. */
  4829.       uint16 session_tag = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : SVAL(inbuf,smb_uid);
  4830.           /* Ensure this value is replaced in the incoming packet. */
  4831.           SSVAL(inbuf,smb_uid,session_tag);
  4832.  
  4833.           /*
  4834.            * Ensure the correct username is in sesssetup_user.
  4835.            * This is a really ugly bugfix for problems with
  4836.            * multiple session_setup_and_X's being done and
  4837.            * allowing %U and %G substitutions to work correctly.
  4838.            * There is a reason this code is done here, don't
  4839.            * move it unless you know what you're doing... :-).
  4840.            * JRA.
  4841.            */
  4842.           if(session_tag != last_session_tag ) {
  4843.             user_struct *vuser = NULL;
  4844.  
  4845.             last_session_tag = session_tag;
  4846.             if(session_tag != UID_FIELD_INVALID)
  4847.               vuser = get_valid_user_struct(session_tag);
  4848.             if(vuser != NULL)
  4849.               pstrcpy( sesssetup_user, vuser->requested_name);
  4850.           }
  4851.  
  4852.       /* does this protocol need to be run as root? */
  4853.       if (!(flags & AS_USER))
  4854.         unbecome_user();
  4855.  
  4856.       /* does this protocol need to be run as the connected user? */
  4857.       if ((flags & AS_USER) && !become_user(&Connections[cnum], cnum,session_tag)) {
  4858.         if (flags & AS_GUEST) 
  4859.           flags &= ~AS_USER;
  4860.         else
  4861.           return(ERROR(ERRSRV,ERRinvnid));
  4862.       }
  4863.       /* this code is to work around a bug is MS client 3 without
  4864.          introducing a security hole - it needs to be able to do
  4865.          print queue checks as guest if it isn't logged in properly */
  4866.       if (flags & AS_USER)
  4867.         flags &= ~AS_GUEST;
  4868.  
  4869.       /* does it need write permission? */
  4870.       if ((flags & NEED_WRITE) && !CAN_WRITE(cnum))
  4871.         return(ERROR(ERRSRV,ERRaccess));
  4872.  
  4873.       /* ipc services are limited */
  4874.       if (IS_IPC(cnum) && (flags & AS_USER) && !(flags & CAN_IPC))
  4875.         return(ERROR(ERRSRV,ERRaccess));        
  4876.  
  4877.       /* load service specific parameters */
  4878.       if (OPEN_CNUM(cnum) && !become_service(cnum,(flags & AS_USER)?True:False))
  4879.         return(ERROR(ERRSRV,ERRaccess));
  4880.  
  4881.       /* does this protocol need to be run as guest? */
  4882.       if ((flags & AS_GUEST) && (!become_guest() || !check_access(-1)))
  4883.         return(ERROR(ERRSRV,ERRaccess));
  4884.  
  4885.       last_inbuf = inbuf;
  4886.  
  4887.       outsize = smb_messages[match].fn(inbuf,outbuf,size,bufsize);
  4888.     }
  4889.       else
  4890.     {
  4891.       outsize = reply_unknown(inbuf,outbuf);
  4892.     }
  4893.     }
  4894.  
  4895. #if PROFILING
  4896.   GetTimeOfDay(&msg_end_time);
  4897.   if (!(smb_messages[match].flags & TIME_INIT))
  4898.     {
  4899.       smb_messages[match].time = 0;
  4900.       smb_messages[match].flags |= TIME_INIT;
  4901.     }
  4902.   {
  4903.     unsigned long this_time =     
  4904.       (msg_end_time.tv_sec - msg_start_time.tv_sec)*1e6 +
  4905.     (msg_end_time.tv_usec - msg_start_time.tv_usec);
  4906.     smb_messages[match].time += this_time;
  4907.     total_time += this_time;
  4908.   }
  4909.   DEBUG(2,("TIME %s  %d usecs   %g pct\n",
  4910.        smb_fn_name(type),smb_messages[match].time,
  4911.     (100.0*smb_messages[match].time) / total_time));
  4912. #endif
  4913.  
  4914.   return(outsize);
  4915. }
  4916.  
  4917.  
  4918. /****************************************************************************
  4919.   construct a chained reply and add it to the already made reply
  4920.   **************************************************************************/
  4921. int chain_reply(char *inbuf,char *outbuf,int size,int bufsize)
  4922. {
  4923.   static char *orig_inbuf;
  4924.   static char *orig_outbuf;
  4925.   int smb_com1, smb_com2 = CVAL(inbuf,smb_vwv0);
  4926.   unsigned smb_off2 = SVAL(inbuf,smb_vwv1);
  4927.   char *inbuf2, *outbuf2;
  4928.   int outsize2;
  4929.   char inbuf_saved[smb_wct];
  4930.   char outbuf_saved[smb_wct];
  4931.   extern int chain_size;
  4932.   int wct = CVAL(outbuf,smb_wct);
  4933.   int outsize = smb_size + 2*wct + SVAL(outbuf,smb_vwv0+2*wct);
  4934.  
  4935.   /* maybe its not chained */
  4936.   if (smb_com2 == 0xFF) {
  4937.     CVAL(outbuf,smb_vwv0) = 0xFF;
  4938.     return outsize;
  4939.   }
  4940.  
  4941.   if (chain_size == 0) {
  4942.     /* this is the first part of the chain */
  4943.     orig_inbuf = inbuf;
  4944.     orig_outbuf = outbuf;
  4945.   }
  4946.  
  4947.   /* we need to tell the client where the next part of the reply will be */
  4948.   SSVAL(outbuf,smb_vwv1,smb_offset(outbuf+outsize,outbuf));
  4949.   CVAL(outbuf,smb_vwv0) = smb_com2;
  4950.  
  4951.   /* remember how much the caller added to the chain, only counting stuff
  4952.      after the parameter words */
  4953.   chain_size += outsize - smb_wct;
  4954.  
  4955.   /* work out pointers into the original packets. The
  4956.      headers on these need to be filled in */
  4957.   inbuf2 = orig_inbuf + smb_off2 + 4 - smb_wct;
  4958.   outbuf2 = orig_outbuf + SVAL(outbuf,smb_vwv1) + 4 - smb_wct;
  4959.  
  4960.   /* remember the original command type */
  4961.   smb_com1 = CVAL(orig_inbuf,smb_com);
  4962.  
  4963.   /* save the data which will be overwritten by the new headers */
  4964.   memcpy(inbuf_saved,inbuf2,smb_wct);
  4965.   memcpy(outbuf_saved,outbuf2,smb_wct);
  4966.  
  4967.   /* give the new packet the same header as the last part of the SMB */
  4968.   memmove(inbuf2,inbuf,smb_wct);
  4969.  
  4970.   /* create the in buffer */
  4971.   CVAL(inbuf2,smb_com) = smb_com2;
  4972.  
  4973.   /* create the out buffer */
  4974.   bzero(outbuf2,smb_size);
  4975.   set_message(outbuf2,0,0,True);
  4976.   CVAL(outbuf2,smb_com) = CVAL(inbuf2,smb_com);
  4977.   
  4978.   memcpy(outbuf2+4,inbuf2+4,4);
  4979.   CVAL(outbuf2,smb_rcls) = SMB_SUCCESS;
  4980.   CVAL(outbuf2,smb_reh) = 0;
  4981.   CVAL(outbuf2,smb_flg) = 0x80 | (CVAL(inbuf2,smb_flg) & 0x8); /* bit 7 set 
  4982.                                   means a reply */
  4983.   SSVAL(outbuf2,smb_flg2,1); /* say we support long filenames */
  4984.   SSVAL(outbuf2,smb_err,SMB_SUCCESS);
  4985.   SSVAL(outbuf2,smb_tid,SVAL(inbuf2,smb_tid));
  4986.   SSVAL(outbuf2,smb_pid,SVAL(inbuf2,smb_pid));
  4987.   SSVAL(outbuf2,smb_uid,SVAL(inbuf2,smb_uid));
  4988.   SSVAL(outbuf2,smb_mid,SVAL(inbuf2,smb_mid));
  4989.  
  4990.   DEBUG(3,("Chained message\n"));
  4991.   show_msg(inbuf2);
  4992.  
  4993.   /* process the request */
  4994.   outsize2 = switch_message(smb_com2,inbuf2,outbuf2,size-chain_size,
  4995.                 bufsize-chain_size);
  4996.  
  4997.   /* copy the new reply and request headers over the old ones, but
  4998.      preserve the smb_com field */
  4999.   memmove(orig_outbuf,outbuf2,smb_wct);
  5000.   CVAL(orig_outbuf,smb_com) = smb_com1;
  5001.  
  5002.   /* restore the saved data, being careful not to overwrite any
  5003.    data from the reply header */
  5004.   memcpy(inbuf2,inbuf_saved,smb_wct);
  5005.   {
  5006.     int ofs = smb_wct - PTR_DIFF(outbuf2,orig_outbuf);
  5007.     if (ofs < 0) ofs = 0;
  5008.     memmove(outbuf2+ofs,outbuf_saved+ofs,smb_wct-ofs);
  5009.   }
  5010.  
  5011.   return outsize2;
  5012. }
  5013.  
  5014.  
  5015.  
  5016. /****************************************************************************
  5017.   construct a reply to the incoming packet
  5018. ****************************************************************************/
  5019. int construct_reply(char *inbuf,char *outbuf,int size,int bufsize)
  5020. {
  5021.   int type = CVAL(inbuf,smb_com);
  5022.   int outsize = 0;
  5023.   int msg_type = CVAL(inbuf,0);
  5024.   extern int chain_size;
  5025.  
  5026.   smb_last_time = time(NULL);
  5027.  
  5028.   chain_size = 0;
  5029.   chain_fnum = -1;
  5030.   reset_chain_pnum();
  5031.  
  5032.   bzero(outbuf,smb_size);
  5033.  
  5034.   if (msg_type != 0)
  5035.     return(reply_special(inbuf,outbuf));  
  5036.  
  5037.   CVAL(outbuf,smb_com) = CVAL(inbuf,smb_com);
  5038.   set_message(outbuf,0,0,True);
  5039.   
  5040.   memcpy(outbuf+4,inbuf+4,4);
  5041.   CVAL(outbuf,smb_rcls) = SMB_SUCCESS;
  5042.   CVAL(outbuf,smb_reh) = 0;
  5043.   CVAL(outbuf,smb_flg) = 0x80 | (CVAL(inbuf,smb_flg) & 0x8); /* bit 7 set 
  5044.                                  means a reply */
  5045.   SSVAL(outbuf,smb_flg2,1); /* say we support long filenames */
  5046.   SSVAL(outbuf,smb_err,SMB_SUCCESS);
  5047.   SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
  5048.   SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
  5049.   SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
  5050.   SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
  5051.  
  5052.   outsize = switch_message(type,inbuf,outbuf,size,bufsize);
  5053.  
  5054.   outsize += chain_size;
  5055.  
  5056.   if(outsize > 4)
  5057.     smb_setlen(outbuf,outsize - 4);
  5058.   return(outsize);
  5059. }
  5060.  
  5061. /****************************************************************************
  5062.   process commands from the client
  5063. ****************************************************************************/
  5064. static void process(void)
  5065. {
  5066.   extern int Client;
  5067.  
  5068.   InBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
  5069.   OutBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
  5070.   if ((InBuffer == NULL) || (OutBuffer == NULL)) 
  5071.     return;
  5072.  
  5073.   InBuffer += SMB_ALIGNMENT;
  5074.   OutBuffer += SMB_ALIGNMENT;
  5075.  
  5076. #if PRIME_NMBD
  5077.   DEBUG(3,("priming nmbd\n"));
  5078.   {
  5079.     struct in_addr ip;
  5080.     ip = *interpret_addr2("localhost");
  5081.     if (zero_ip(ip)) ip = *interpret_addr2("127.0.0.1");
  5082.     *OutBuffer = 0;
  5083.     send_one_packet(OutBuffer,1,ip,NMB_PORT,SOCK_DGRAM);
  5084.   }
  5085. #endif    
  5086.  
  5087.   /* re-initialise the timezone */
  5088.   TimeInit();
  5089.  
  5090.   while (True)
  5091.   {
  5092.     int deadtime = lp_deadtime()*60;
  5093.     int counter;
  5094.     int last_keepalive=0;
  5095.     int service_load_counter = 0;
  5096.     BOOL got_smb = False;
  5097.  
  5098.     if (deadtime <= 0)
  5099.       deadtime = DEFAULT_SMBD_TIMEOUT;
  5100.  
  5101. #if USE_READ_PREDICTION
  5102.     if (lp_readprediction())
  5103.       do_read_prediction();
  5104. #endif
  5105.  
  5106.     errno = 0;      
  5107.  
  5108.     for (counter=SMBD_SELECT_LOOP; 
  5109.           !receive_message_or_smb(Client,oplock_sock,
  5110.                       InBuffer,BUFFER_SIZE,SMBD_SELECT_LOOP*1000,&got_smb); 
  5111.           counter += SMBD_SELECT_LOOP)
  5112.     {
  5113.       int i;
  5114.       time_t t;
  5115.       BOOL allidle = True;
  5116.       extern int keepalive;
  5117.  
  5118.       if (counter > 365 * 3600) /* big number of seconds. */
  5119.       {
  5120.         counter = 0;
  5121.         service_load_counter = 0;
  5122.       }
  5123.  
  5124.       if (smb_read_error == READ_EOF) 
  5125.       {
  5126.         DEBUG(3,("end of file from client\n"));
  5127.         return;
  5128.       }
  5129.  
  5130.       if (smb_read_error == READ_ERROR) 
  5131.       {
  5132.         DEBUG(3,("receive_smb error (%s) exiting\n",
  5133.                   strerror(errno)));
  5134.         return;
  5135.       }
  5136.  
  5137.       t = time(NULL);
  5138.  
  5139.       /* become root again if waiting */
  5140.       unbecome_user();
  5141.  
  5142.       /* check for smb.conf reload */
  5143.       if (counter >= service_load_counter + SMBD_RELOAD_CHECK)
  5144.       {
  5145.         service_load_counter = counter;
  5146.  
  5147.         /* reload services, if files have changed. */
  5148.         reload_services(True);
  5149.       }
  5150.  
  5151.       /* automatic timeout if all connections are closed */      
  5152.       if (num_connections_open==0 && counter >= IDLE_CLOSED_TIMEOUT) 
  5153.       {
  5154.         DEBUG(2,("%s Closing idle connection\n",timestring()));
  5155.         return;
  5156.       }
  5157.  
  5158.       if (keepalive && (counter-last_keepalive)>keepalive) 
  5159.       {
  5160.           struct cli_state *cli = server_client();
  5161.           if (!send_keepalive(Client)) { 
  5162.               DEBUG(2,("%s Keepalive failed - exiting\n",timestring()));
  5163.               return;
  5164.           }        
  5165.           /* also send a keepalive to the password server if its still
  5166.          connected */
  5167.           if (cli && cli->initialised)
  5168.               send_keepalive(cli->fd);
  5169.           last_keepalive = counter;
  5170.       }
  5171.  
  5172.       /* check for connection timeouts */
  5173.       for (i=0;i<MAX_CONNECTIONS;i++)
  5174.         if (Connections[i].open)
  5175.         {
  5176.           /* close dirptrs on connections that are idle */
  5177.           if ((t-Connections[i].lastused)>DPTR_IDLE_TIMEOUT)
  5178.             dptr_idlecnum(i);
  5179.  
  5180.           if (Connections[i].num_files_open > 0 ||
  5181.                      (t-Connections[i].lastused)<deadtime)
  5182.             allidle = False;
  5183.         }
  5184.  
  5185.       if (allidle && num_connections_open>0) 
  5186.       {
  5187.         DEBUG(2,("%s Closing idle connection 2\n",timestring()));
  5188.         return;
  5189.       }
  5190.     }
  5191.  
  5192.     if(got_smb)
  5193.       process_smb(InBuffer, OutBuffer);
  5194.     else
  5195.       process_local_message(oplock_sock, InBuffer, BUFFER_SIZE);
  5196.   }
  5197. }
  5198.  
  5199.  
  5200. /****************************************************************************
  5201.   initialise connect, service and file structs
  5202. ****************************************************************************/
  5203. static void init_structs(void )
  5204. {
  5205.   int i;
  5206.   get_myname(myhostname,NULL);
  5207.  
  5208.   for (i=0;i<MAX_CONNECTIONS;i++)
  5209.     {
  5210.       Connections[i].open = False;
  5211.       Connections[i].num_files_open=0;
  5212.       Connections[i].lastused=0;
  5213.       Connections[i].used=False;
  5214.       string_init(&Connections[i].user,"");
  5215.       string_init(&Connections[i].dirpath,"");
  5216.       string_init(&Connections[i].connectpath,"");
  5217.       string_init(&Connections[i].origpath,"");
  5218.     }
  5219.  
  5220.   for (i=0;i<MAX_OPEN_FILES;i++)
  5221.     {
  5222.       Files[i].open = False;
  5223.       string_init(&Files[i].name,"");
  5224.  
  5225.     }
  5226.  
  5227.   for (i=0;i<MAX_OPEN_FILES;i++)
  5228.     {
  5229.       file_fd_struct *fd_ptr = &FileFd[i];
  5230.       fd_ptr->ref_count = 0;
  5231.       fd_ptr->dev = (int32)-1;
  5232.       fd_ptr->inode = (int32)-1;
  5233.       fd_ptr->fd = -1;
  5234.       fd_ptr->fd_readonly = -1;
  5235.       fd_ptr->fd_writeonly = -1;
  5236.       fd_ptr->real_open_flags = -1;
  5237.     }
  5238.  
  5239.   /* for RPC pipes */
  5240.   init_rpc_pipe_hnd();
  5241.  
  5242. #ifdef NTDOMAIN
  5243.   /* for LSA handles */
  5244.   init_lsa_policy_hnd();
  5245. #endif
  5246.  
  5247.   init_dptrs();
  5248. }
  5249.  
  5250. /****************************************************************************
  5251. usage on the program
  5252. ****************************************************************************/
  5253. static void usage(char *pname)
  5254. {
  5255.   DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
  5256.  
  5257.   printf("Usage: %s [-D] [-p port] [-d debuglevel] [-l log basename] [-s services file]\n",pname);
  5258.   printf("Version %s\n",VERSION);
  5259.   printf("\t-D                    become a daemon\n");
  5260.   printf("\t-p port               listen on the specified port\n");
  5261.   printf("\t-d debuglevel         set the debuglevel\n");
  5262.   printf("\t-l log basename.      Basename for log/debug files\n");
  5263.   printf("\t-s services file.     Filename of services file\n");
  5264.   printf("\t-P                    passive only\n");
  5265.   printf("\t-a                    overwrite log file, don't append\n");
  5266.   printf("\n");
  5267. }
  5268.  
  5269.  
  5270. /****************************************************************************
  5271.   main program
  5272. ****************************************************************************/
  5273.  int main(int argc,char *argv[])
  5274. {
  5275.   extern BOOL append_log;
  5276.   /* shall I run as a daemon */
  5277.   BOOL is_daemon = False;
  5278.   int port = SMB_PORT;
  5279.   int opt;
  5280.   extern char *optarg;
  5281.   char pidFile[100];
  5282.  
  5283.   *pidFile = '\0';
  5284.  
  5285. #ifdef NEED_AUTH_PARAMETERS
  5286.   set_auth_parameters(argc,argv);
  5287. #endif
  5288.  
  5289. #ifdef SecureWare
  5290.   setluid(0);
  5291. #endif
  5292.  
  5293.   append_log = True;
  5294.  
  5295.   TimeInit();
  5296.  
  5297.   pstrcpy(debugf,SMBLOGFILE);  
  5298.  
  5299.   pstrcpy(remote_machine, "smb");
  5300.  
  5301.   setup_logging(argv[0],False);
  5302.  
  5303.   charset_initialise();
  5304.  
  5305.   /* make absolutely sure we run as root - to handle cases where people
  5306.      are crazy enough to have it setuid */
  5307. #ifdef USE_SETRES
  5308.   setresuid(0,0,0);
  5309. #else
  5310.   setuid(0);
  5311.   seteuid(0);
  5312.   setuid(0);
  5313.   seteuid(0);
  5314. #endif
  5315.  
  5316.   fault_setup((void (*)(void *))exit_server);
  5317.   signal(SIGTERM , SIGNAL_CAST dflt_sig);
  5318.  
  5319.   /* we want total control over the permissions on created files,
  5320.      so set our umask to 0 */
  5321.   umask(0);
  5322.  
  5323.   GetWd(OriginalDir);
  5324.  
  5325.   init_uid();
  5326.  
  5327.   /* this is for people who can't start the program correctly */
  5328.   while (argc > 1 && (*argv[1] != '-'))
  5329.     {
  5330.       argv++;
  5331.       argc--;
  5332.     }
  5333.  
  5334.   while ((opt = getopt(argc, argv, "O:i:l:s:d:Dp:hPaf:")) != EOF)
  5335.     switch (opt)
  5336.       {
  5337.       case 'f':
  5338.         strncpy(pidFile, optarg, sizeof(pidFile));
  5339.         break;
  5340.       case 'O':
  5341.     pstrcpy(user_socket_options,optarg);
  5342.     break;
  5343.       case 'i':
  5344.     pstrcpy(scope,optarg);
  5345.     break;
  5346.       case 'P':
  5347.     {
  5348.       extern BOOL passive;
  5349.       passive = True;
  5350.     }
  5351.     break;    
  5352.       case 's':
  5353.     pstrcpy(servicesf,optarg);
  5354.     break;
  5355.       case 'l':
  5356.     pstrcpy(debugf,optarg);
  5357.     break;
  5358.       case 'a':
  5359.     {
  5360.       extern BOOL append_log;
  5361.       append_log = !append_log;
  5362.     }
  5363.     break;
  5364.       case 'D':
  5365.     is_daemon = True;
  5366.     break;
  5367.       case 'd':
  5368.     if (*optarg == 'A')
  5369.       DEBUGLEVEL = 10000;
  5370.     else
  5371.       DEBUGLEVEL = atoi(optarg);
  5372.     break;
  5373.       case 'p':
  5374.     port = atoi(optarg);
  5375.     break;
  5376.       case 'h':
  5377.     usage(argv[0]);
  5378.     exit(0);
  5379.     break;
  5380.       default:
  5381.     usage(argv[0]);
  5382.     exit(1);
  5383.       }
  5384.  
  5385.   reopen_logs();
  5386.  
  5387.   DEBUG(2,("%s smbd version %s started\n",timestring(),VERSION));
  5388.   DEBUG(2,("Copyright Andrew Tridgell 1992-1997\n"));
  5389.  
  5390. #ifndef NO_GETRLIMIT
  5391. #ifdef RLIMIT_NOFILE
  5392.   {
  5393.     struct rlimit rlp;
  5394.     getrlimit(RLIMIT_NOFILE, &rlp);
  5395.     /*
  5396.      * Set the fd limit to be MAX_OPEN_FILES + 10 to account for the
  5397.      * extra fd we need to read directories, as well as the log files
  5398.      * and standard handles etc.
  5399.      */
  5400.     rlp.rlim_cur = (MAX_OPEN_FILES+10>rlp.rlim_max)? rlp.rlim_max:MAX_OPEN_FILES+10;
  5401.     setrlimit(RLIMIT_NOFILE, &rlp);
  5402.     getrlimit(RLIMIT_NOFILE, &rlp);
  5403.     DEBUG(3,("Maximum number of open files per session is %d\n",rlp.rlim_cur));
  5404.   }
  5405. #endif
  5406. #endif
  5407.  
  5408.   
  5409.   DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
  5410.     getuid(),getgid(),geteuid(),getegid()));
  5411.  
  5412.   if (sizeof(uint16) < 2 || sizeof(uint32) < 4)
  5413.     {
  5414.       DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
  5415.       exit(1);
  5416.     }
  5417.  
  5418.   init_structs();
  5419.  
  5420.   if (!reload_services(False))
  5421.     return(-1);    
  5422.  
  5423.   codepage_initialise(lp_client_code_page());
  5424.  
  5425.   pstrcpy(myworkgroup, lp_workgroup());
  5426.  
  5427. #ifndef NO_SIGNAL_TEST
  5428.   signal(SIGHUP,SIGNAL_CAST sig_hup);
  5429. #endif
  5430.  
  5431.   /* Setup the signals that allow the debug log level
  5432.      to by dynamically changed. */
  5433.  
  5434.   /* If we are using the malloc debug code we can't use
  5435.      SIGUSR1 and SIGUSR2 to do debug level changes. */
  5436.  
  5437. #ifndef MEM_MAN
  5438. #if defined(SIGUSR1)
  5439.   signal( SIGUSR1, SIGNAL_CAST sig_usr1 );
  5440. #endif /* SIGUSR1 */
  5441.    
  5442. #if defined(SIGUSR2)
  5443.   signal( SIGUSR2, SIGNAL_CAST sig_usr2 );
  5444. #endif /* SIGUSR2 */
  5445. #endif /* MEM_MAN */
  5446.  
  5447.   DEBUG(3,("%s loaded services\n",timestring()));
  5448.  
  5449.   if (!is_daemon && !is_a_socket(0))
  5450.     {
  5451.       DEBUG(0,("standard input is not a socket, assuming -D option\n"));
  5452.       is_daemon = True;
  5453.     }
  5454.  
  5455.   if (is_daemon)
  5456.     {
  5457.       DEBUG(3,("%s becoming a daemon\n",timestring()));
  5458.       become_daemon();
  5459.     }
  5460.  
  5461.   if (!directory_exist(lp_lockdir(), NULL)) {
  5462.       mkdir(lp_lockdir(), 0755);
  5463.   }
  5464.  
  5465.   if (*pidFile)
  5466.     {
  5467.       int     fd;
  5468.       char    buf[20];
  5469.  
  5470.       if ((fd = open(pidFile,
  5471. #ifdef O_NONBLOCK
  5472.          O_NONBLOCK | 
  5473. #endif
  5474.          O_CREAT | O_WRONLY | O_TRUNC, 0644)) < 0)
  5475.         {
  5476.            DEBUG(0,("ERROR: can't open %s: %s\n", pidFile, strerror(errno)));
  5477.            exit(1);
  5478.         }
  5479.       if(fcntl_lock(fd,F_SETLK,0,1,F_WRLCK)==False)
  5480.         {
  5481.           DEBUG(0,("ERROR: smbd is already running\n"));
  5482.           exit(1);
  5483.         }
  5484.       slprintf(buf, sizeof(buf)-1, "%u\n", (unsigned int) getpid());
  5485.       if (write(fd, buf, strlen(buf)) < 0)
  5486.         {
  5487.           DEBUG(0,("ERROR: can't write to %s: %s\n", pidFile, strerror(errno)));
  5488.           exit(1);
  5489.         }
  5490.       /* Leave pid file open & locked for the duration... */
  5491.     }
  5492.  
  5493.   if (!open_sockets(is_daemon,port))
  5494.     exit(1);
  5495.  
  5496.   if (!locking_init(0))
  5497.     exit(1);
  5498.  
  5499.   /* possibly reload the services file. */
  5500.   reload_services(True);
  5501.  
  5502.   max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
  5503.  
  5504.   if (*lp_rootdir())
  5505.     {
  5506.       if (sys_chroot(lp_rootdir()) == 0)
  5507.     DEBUG(2,("%s changed root to %s\n",timestring(),lp_rootdir()));
  5508.     }
  5509.  
  5510.   /* Setup the oplock IPC socket. */
  5511.   if(!open_oplock_ipc())
  5512.     exit(1);
  5513.  
  5514.   process();
  5515.   close_sockets();
  5516.  
  5517.   exit_server("normal exit");
  5518.   return(0);
  5519. }
  5520.  
  5521.  
  5522.