home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / NEXTSTEP / Networking / SambaManager / samba-1.9.17p4 / source / server.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-03-30  |  120.3 KB  |  4,503 lines

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