Modified Files:
[samba.git] / source3 / smbd / server.c
index 5f59af1bf198a3824d6f878da64db4bb0ffe8a22..908cf984b8e4a0b822514bdb55f52a62a4af682e 100644 (file)
@@ -48,7 +48,7 @@ extern BOOL case_preserve;
 extern BOOL use_mangled_map;
 extern BOOL short_case_preserve;
 extern BOOL case_mangle;
-extern time_t smb_last_time;
+time_t smb_last_time=(time_t)0;
 
 extern int smb_read_error;
 
@@ -84,19 +84,17 @@ int chain_fnum = -1;
 /* number of open connections */
 static int num_connections_open = 0;
 
-#ifdef USE_OPLOCKS
 /* Oplock ipc UDP socket. */
 int oplock_sock = -1;
 uint16 oplock_port = 0;
 /* Current number of oplocks we have outstanding. */
-uint32 global_oplocks_open = 0;
-#endif /* USE_OPLOCKS */
+int32 global_oplocks_open = 0;
 
 BOOL global_oplock_break = False;
 
 extern fstring remote_machine;
 
-pstring OriginalDir;
+extern pstring OriginalDir;
 
 /* these can be set by some functions to override the error codes */
 int unix_ERR_class=SUCCESS;
@@ -189,7 +187,7 @@ int dos_mode(int cnum,char *path,struct stat *sbuf)
   int result = 0;
   extern struct current_user current_user;
 
-  DEBUG(5,("dos_mode: %d %s\n", cnum, path));
+  DEBUG(8,("dos_mode: %d %s\n", cnum, path));
 
   if (CAN_WRITE(cnum) && !lp_alternate_permissions(SNUM(cnum))) {
     if (!((sbuf->st_mode & S_IWOTH) ||
@@ -216,9 +214,11 @@ int dos_mode(int cnum,char *path,struct stat *sbuf)
   if (S_ISDIR(sbuf->st_mode))
     result = aDIR | (result & aRONLY);
 
+#ifdef S_ISLNK
 #if LINKS_READ_ONLY
   if (S_ISLNK(sbuf->st_mode) && S_ISDIR(sbuf->st_mode))
     result |= aRONLY;
+#endif
 #endif
 
   /* hide files with a name starting with a . */
@@ -241,20 +241,19 @@ int dos_mode(int cnum,char *path,struct stat *sbuf)
     result |= aHIDDEN;
   }
 
-  DEBUG(5,("dos_mode returning "));
+  DEBUG(8,("dos_mode returning "));
 
-  if (result & aHIDDEN) DEBUG(5, ("h"));
-  if (result & aRONLY ) DEBUG(5, ("r"));
-  if (result & aSYSTEM) DEBUG(5, ("s"));
-  if (result & aDIR   ) DEBUG(5, ("d"));
-  if (result & aARCH  ) DEBUG(5, ("a"));
+  if (result & aHIDDEN) DEBUG(8, ("h"));
+  if (result & aRONLY ) DEBUG(8, ("r"));
+  if (result & aSYSTEM) DEBUG(8, ("s"));
+  if (result & aDIR   ) DEBUG(8, ("d"));
+  if (result & aARCH  ) DEBUG(8, ("a"));
 
-  DEBUG(5,("\n"));
+  DEBUG(8,("\n"));
 
   return(result);
 }
 
-
 /*******************************************************************
 chmod a file - but preserve some bits
 ********************************************************************/
@@ -308,6 +307,73 @@ int dos_chmod(int cnum,char *fname,int dosmode,struct stat *st)
   return(sys_chmod(fname,unixmode));
 }
 
+/*******************************************************************
+Wrapper around sys_utime that possibly allows DOS semantics rather
+than POSIX.
+*******************************************************************/
+
+int file_utime(int cnum, char *fname, struct utimbuf *times)
+{
+  extern struct current_user current_user;
+  struct stat sb;
+  int ret = -1;
+
+  errno = 0;
+
+  if(sys_utime(fname, times) == 0)
+    return 0;
+
+  if((errno != EPERM) && (errno != EACCES))
+    return -1;
+
+  if(!lp_dos_filetimes(SNUM(cnum)))
+    return -1;
+
+  /* We have permission (given by the Samba admin) to
+     break POSIX semantics and allow a user to change
+     the time on a file they don't own but can write to
+     (as DOS does).
+   */
+
+  if(sys_stat(fname,&sb) != 0)
+    return -1;
+
+  /* Check if we have write access. */
+  if (CAN_WRITE(cnum)) {
+         if (((sb.st_mode & S_IWOTH) ||
+              Connections[cnum].admin_user ||
+              ((sb.st_mode & S_IWUSR) && current_user.uid==sb.st_uid) ||
+              ((sb.st_mode & S_IWGRP) &&
+               in_group(sb.st_gid,current_user.gid,
+                        current_user.ngroups,current_user.igroups)))) {
+                 /* We are allowed to become root and change the filetime. */
+                 become_root(False);
+                 ret = sys_utime(fname, times);
+                 unbecome_root(False);
+         }
+  }
+
+  return ret;
+}
+  
+/*******************************************************************
+Change a filetime - possibly allowing DOS semantics.
+*******************************************************************/
+
+BOOL set_filetime(int cnum, char *fname, time_t mtime)
+{
+  struct utimbuf times;
+
+  if (null_mtime(mtime)) return(True);
+
+  times.modtime = times.actime = mtime;
+
+  if (file_utime(cnum, fname, &times)) {
+    DEBUG(4,("set_filetime(%s) failed: %s\n",fname,strerror(errno)));
+  }
+  
+  return(True);
+} 
 
 /****************************************************************************
 check if two filenames are equal
@@ -713,7 +779,15 @@ int disk_free(char *path,int *bsize,int *dfree,int *dsize)
                            dfree_retval : dfreeq_retval ;
           /* maybe dfree and dfreeq are calculated using different bsizes 
              so convert dfree from bsize into bsizeq */
-          *dfree = ((*dfree) * (*bsize)) / (bsizeq);
+          /* avoid overflows due to multiplication, so do not:
+                *dfree = ((*dfree) * (*bsize)) / (bsizeq); 
+             bsize and bsizeq are powers of 2 so its better to
+             to divide them getting a multiplication or division factor
+             for dfree. Rene Nieuwenhuizen (07-10-1997) */
+          if (*bsize >= bsizeq) 
+            *dfree = *dfree * (*bsize / bsizeq);
+          else 
+            *dfree = *dfree / (bsizeq / *bsize);
           *dfree = ( *dfree < dfreeq ) ? *dfree : dfreeq ; 
           *bsize = bsizeq;
           *dsize = dsizeq;
@@ -803,7 +877,15 @@ if ((*bsize) < 512 || (*bsize)>0xFFFF) *bsize = 1024;
                        dfree_retval : dfreeq_retval ;
       /* maybe dfree and dfreeq are calculated using different bsizes 
          so convert dfree from bsize into bsizeq */
-      *dfree = ((*dfree) * (*bsize)) / (bsizeq);
+      /* avoid overflows due to multiplication, so do not:
+              *dfree = ((*dfree) * (*bsize)) / (bsizeq); 
+       bsize and bsizeq are powers of 2 so its better to
+       to divide them getting a multiplication or division factor
+       for dfree. Rene Nieuwenhuizen (07-10-1997) */
+      if (*bsize >= bsizeq)
+        *dfree = *dfree * (*bsize / bsizeq);
+      else
+        *dfree = *dfree / (bsizeq / *bsize);
       *dfree = ( *dfree < dfreeq ) ? *dfree : dfreeq ;
       *bsize = bsizeq;
       *dsize = dsizeq;
@@ -849,6 +931,7 @@ BOOL check_name(char *name,int cnum)
   /* Patch from David Clerc <David.Clerc@cui.unige.ch>
      University of Geneva */
 
+#ifdef S_ISLNK
   if (!lp_symlinks(SNUM(cnum)))
     {
       struct stat statbuf;
@@ -859,6 +942,7 @@ BOOL check_name(char *name,int cnum)
           ret=0; 
         }
     }
+#endif
 
   if (!ret)
     DEBUG(5,("check_name on %s failed\n",name));
@@ -886,8 +970,7 @@ static void check_for_pipe(char *fname)
 /****************************************************************************
 fd support routines - attempt to do a sys_open
 ****************************************************************************/
-
-int fd_attempt_open(char *fname, int flags, int mode)
+static int fd_attempt_open(char *fname, int flags, int mode)
 {
   int fd = sys_open(fname,flags,mode);
 
@@ -939,7 +1022,7 @@ int fd_attempt_open(char *fname, int flags, int mode)
 fd support routines - attempt to find an already open file by dev
 and inode - increments the ref_count of the returned file_fd_struct *.
 ****************************************************************************/
-file_fd_struct *fd_get_already_open(struct stat *sbuf)
+static file_fd_struct *fd_get_already_open(struct stat *sbuf)
 {
   int i;
   file_fd_struct *fd_ptr;
@@ -966,7 +1049,7 @@ file_fd_struct *fd_get_already_open(struct stat *sbuf)
 fd support routines - attempt to find a empty slot in the FileFd array.
 Increments the ref_count of the returned entry.
 ****************************************************************************/
-file_fd_struct *fd_get_new()
+static file_fd_struct *fd_get_new()
 {
   int i;
   file_fd_struct *fd_ptr;
@@ -999,8 +1082,7 @@ n"));
 fd support routines - attempt to re-open an already open fd as O_RDWR.
 Save the already open fd (we cannot close due to POSIX file locking braindamage.
 ****************************************************************************/
-
-void fd_attempt_reopen(char *fname, int mode, file_fd_struct *fd_ptr)
+static void fd_attempt_reopen(char *fname, int mode, file_fd_struct *fd_ptr)
 {
   int fd = sys_open( fname, O_RDWR, mode);
 
@@ -1020,7 +1102,7 @@ void fd_attempt_reopen(char *fname, int mode, file_fd_struct *fd_ptr)
 fd support routines - attempt to close the file referenced by this fd.
 Decrements the ref_count and returns it.
 ****************************************************************************/
-int fd_attempt_close(file_fd_struct *fd_ptr)
+static int fd_attempt_close(file_fd_struct *fd_ptr)
 {
   DEBUG(3,("fd_attempt_close on file_fd_struct %d, fd = %d, dev = %x, inode = %x, open_flags = %d, ref_count = %d.\n",
           fd_ptr - &FileFd[0],
@@ -1060,6 +1142,7 @@ static void open_file(int fnum,int cnum,char *fname1,int flags,int mode, struct
 
   fsp->open = False;
   fsp->fd_ptr = 0;
+  fsp->granted_oplock = False;
   errno = EPERM;
 
   pstrcpy(fname,fname1);
@@ -1082,13 +1165,6 @@ static void open_file(int fnum,int cnum,char *fname1,int flags,int mode, struct
     DEBUG(3,("Bug in client? Set O_WRONLY without O_CREAT\n"));
 */
 
-#if UTIME_WORKAROUND
-  /* XXXX - is this OK?? */
-  /* this works around a utime bug but can cause other problems */
-  if ((flags & (O_WRONLY|O_RDWR)) && (flags & O_CREAT) && !(flags & O_APPEND))
-    sys_unlink(fname);
-#endif
-
   /*
    * Ensure we have a valid struct stat so we can search the
    * open fd table.
@@ -1344,16 +1420,24 @@ static void check_magic(int fnum,int cnum)
 
 /****************************************************************************
 close a file - possibly invalidating the read prediction
+
+If normal_close is 1 then this came from a normal SMBclose (or equivalent)
+operation otherwise it came as the result of some other operation such as
+the closing of the connection. In the latter case printing and
+magic scripts are not run
 ****************************************************************************/
-void close_file(int fnum)
+void close_file(int fnum, BOOL normal_close)
 {
   files_struct *fs_p = &Files[fnum];
   int cnum = fs_p->cnum;
   uint32 dev = fs_p->fd_ptr->dev;
   uint32 inode = fs_p->fd_ptr->inode;
-  share_lock_token token;
+  int token;
 
+#if USE_READ_PREDICTION
   invalidate_read_prediction(fs_p->fd_ptr->fd);
+#endif
+
   fs_p->open = False;
   Connections[cnum].num_files_open--;
   if(fs_p->wbmpx_ptr) 
@@ -1382,11 +1466,12 @@ void close_file(int fnum)
     unlock_share_entry( cnum, dev, inode, token);
 
   /* NT uses smbclose to start a print - weird */
-  if (fs_p->print_file)
+  if (normal_close && fs_p->print_file)
     print_file(fnum);
 
   /* check for magic scripts */
-  check_magic(fnum,cnum);
+  if (normal_close)
+    check_magic(fnum,cnum);
 
   DEBUG(2,("%s %s closed file %s (numopen=%d)\n",
           timestring(),Connections[cnum].user,fs_p->name,
@@ -1404,7 +1489,8 @@ static int access_table(int new_deny,int old_deny,int old_mode,
   if (new_deny == DENY_ALL || old_deny == DENY_ALL) return(AFAIL);
 
   if (new_deny == DENY_DOS || old_deny == DENY_DOS) {
-    if (old_deny == new_deny && share_pid == getpid()) 
+    int pid = getpid();
+    if (old_deny == new_deny && share_pid == pid) 
        return(AALL);    
 
     if (old_mode == 0) return(AREAD);
@@ -1453,10 +1539,10 @@ BOOL check_file_sharing(int cnum,char *fname)
 {
   int i;
   int ret = False;
-  min_share_mode_entry *old_shares = 0;
+  share_mode_entry *old_shares = 0;
   int num_share_modes;
   struct stat sbuf;
-  share_lock_token token;
+  int token;
   int pid = getpid();
   uint32 dev, inode;
 
@@ -1485,18 +1571,13 @@ BOOL check_file_sharing(int cnum,char *fname)
       broke_oplock = False;
       for(i = 0; i < num_share_modes; i++)
       {
-        min_share_mode_entry *share_entry = &old_shares[i];
+        share_mode_entry *share_entry = &old_shares[i];
 
-        /* someone else has a share lock on it, check to see 
-           if we can too */
-        if ((share_entry->share_mode != DENY_DOS) || (share_entry->pid != pid))
-          goto free_and_exit;
-
-#ifdef USE_OPLOCKS
         /* 
-         * The share modes would give us access. Check if someone
-         * has an oplock on this file. If so we must break it before
-         * continuing. 
+         * Break oplocks before checking share modes. See comment in
+         * open_file_shared for details. 
+         * Check if someone has an oplock on this file. If so we must 
+         * break it before continuing. 
          */
         if(share_entry->op_type & BATCH_OPLOCK)
         {
@@ -1517,7 +1598,12 @@ dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
           broke_oplock = True;
           break;
         }
-#endif /* USE_OPLOCKS */
+
+        /* someone else has a share lock on it, check to see 
+           if we can too */
+        if ((share_entry->share_mode != DENY_DOS) || (share_entry->pid != pid))
+          goto free_and_exit;
+
       } /* end for */
 
       if(broke_oplock)
@@ -1547,8 +1633,8 @@ free_and_exit:
   Helper for open_file_shared. 
   Truncate a file after checking locking; close file if locked.
   **************************************************************************/
-static void truncate_unless_locked(int fnum, int cnum, share_lock_token token, 
-       BOOL *share_locked)
+static void truncate_unless_locked(int fnum, int cnum, int token, 
+                                  BOOL *share_locked)
 {
   if (Files[fnum].can_write){
     if (is_locked(fnum,cnum,0x3FFFFFFF,0)){
@@ -1557,7 +1643,7 @@ static void truncate_unless_locked(int fnum, int cnum, share_lock_token token,
       if (*share_locked && lp_share_modes(SNUM(cnum)))
         unlock_share_entry( cnum, Files[fnum].fd_ptr->dev, 
                             Files[fnum].fd_ptr->inode, token);
-      close_file(fnum);   
+      close_file(fnum,False);   
       /* Share mode no longer locked. */
       *share_locked = False;
       errno = EACCES;
@@ -1572,7 +1658,7 @@ static void truncate_unless_locked(int fnum, int cnum, share_lock_token token,
 /****************************************************************************
 check if we can open a file with a share mode
 ****************************************************************************/
-int check_share_mode( min_share_mode_entry *share, int deny_mode, char *fname,
+int check_share_mode( share_mode_entry *share, int deny_mode, char *fname,
                       BOOL fcbopen, int *flags)
 {
   int old_open_mode = share->share_mode &0xF;
@@ -1624,7 +1710,7 @@ void open_file_shared(int fnum,int cnum,char *fname,int share_mode,int ofun,
   BOOL file_existed = file_exist(fname,&sbuf);
   BOOL share_locked = False;
   BOOL fcbopen = False;
-  share_lock_token token;
+  int token;
   uint32 dev = 0;
   uint32 inode = 0;
   int num_share_modes = 0;
@@ -1700,7 +1786,7 @@ void open_file_shared(int fnum,int cnum,char *fname,int share_mode,int ofun,
   if (lp_share_modes(SNUM(cnum))) 
   {
     int i;
-    min_share_mode_entry *old_shares = 0;
+    share_mode_entry *old_shares = 0;
 
     if (file_existed)
     {
@@ -1725,24 +1811,14 @@ void open_file_shared(int fnum,int cnum,char *fname,int share_mode,int ofun,
         broke_oplock = False;
         for(i = 0; i < num_share_modes; i++)
         {
-          min_share_mode_entry *share_entry = &old_shares[i];
+          share_mode_entry *share_entry = &old_shares[i];
 
-          /* someone else has a share lock on it, check to see 
-             if we can too */
-          if(check_share_mode(share_entry, deny_mode, fname, fcbopen, &flags) == False)
-          {
-            free((char *)old_shares);
-            unlock_share_entry(cnum, dev, inode, token);
-            errno = EACCES;
-            unix_ERR_class = ERRDOS;
-            unix_ERR_code = ERRbadshare;
-            return;
-          }
-#ifdef USE_OPLOCKS
           /* 
-           * The share modes would give us access. Check if someone
-           * has an oplock on this file. If so we must break it before
-           * continuing. 
+           * By observation of NetBench, oplocks are broken *before* share
+           * modes are checked. This allows a file to be closed by the client
+           * if the share mode would deny access and the client has an oplock. 
+           * Check if someone has an oplock on this file. If so we must break 
+           * it before continuing. 
            */
           if(share_entry->op_type & (EXCLUSIVE_OPLOCK|BATCH_OPLOCK))
           {
@@ -1766,7 +1842,19 @@ dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
             broke_oplock = True;
             break;
           }
-#endif /* USE_OPLOCKS */
+
+          /* someone else has a share lock on it, check to see 
+             if we can too */
+          if(check_share_mode(share_entry, deny_mode, fname, fcbopen, &flags) == False)
+          {
+            free((char *)old_shares);
+            unlock_share_entry(cnum, dev, inode, token);
+            errno = EACCES;
+            unix_ERR_class = ERRDOS;
+            unix_ERR_code = ERRbadshare;
+            return;
+          }
+
         } /* end for */
 
         if(broke_oplock)
@@ -1835,13 +1923,12 @@ dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
     if (lp_share_modes(SNUM(cnum)))
     {
       uint16 port = 0;
-#ifdef USE_OPLOCKS
       /* JRA. Currently this only services Exlcusive and batch
          oplocks (no other opens on this file). This needs to
          be extended to level II oplocks (multiple reader
          oplocks). */
 
-      if(oplock_request && (num_share_modes == 0))
+      if(oplock_request && (num_share_modes == 0) && lp_oplocks(SNUM(cnum)))
       {
         fs_p->granted_oplock = True;
         global_oplocks_open++;
@@ -1849,9 +1936,13 @@ dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
 
         DEBUG(5,("open_file_shared: granted oplock (%x) on file %s, \
 dev = %x, inode = %x\n", oplock_request, fname, dev, inode));
-      }
 
-#endif /* USE_OPLOCKS */
+      }
+      else
+      {
+        port = 0;
+        oplock_request = 0;
+      }
       set_share_mode(token, fnum, port, oplock_request);
     }
 
@@ -1884,6 +1975,7 @@ int read_file(int fnum,char *data,uint32 pos,int n)
 {
   int ret=0,readret;
 
+#if USE_READ_PREDICTION
   if (!Files[fnum].can_write)
     {
       ret = read_predict(Files[fnum].fd_ptr->fd,pos,data,NULL,n);
@@ -1892,6 +1984,7 @@ int read_file(int fnum,char *data,uint32 pos,int n)
       n -= ret;
       pos += ret;
     }
+#endif
 
 #if USE_MMAP
   if (Files[fnum].mmap_ptr)
@@ -2102,7 +2195,7 @@ struct
   {EPERM,ERRDOS,ERRnoaccess},
   {EACCES,ERRDOS,ERRnoaccess},
   {ENOENT,ERRDOS,ERRbadfile},
-  {ENOTDIR,ERRDOS,ERRbaddirectory},
+  {ENOTDIR,ERRDOS,ERRbadpath},
   {EIO,ERRHRD,ERRgeneral},
   {EBADF,ERRSRV,ERRsrverror},
   {EINVAL,ERRSRV,ERRsrverror},
@@ -2123,20 +2216,6 @@ struct
   {0,0,0}
 };
 
-/* Mapping for old clients. */
-
-struct
-{
-  int new_smb_error;
-  int old_smb_error;
-  int protocol_level;
-  enum remote_arch_types valid_ra_type;
-} old_client_errmap[] =
-{
-  {ERRbaddirectory, ERRbadpath, (int)PROTOCOL_NT1, RA_WINNT},
-  {0,0,0}
-};
-
 /****************************************************************************
   create an error packet from errno
 ****************************************************************************/
@@ -2167,29 +2246,6 @@ int unix_error_packet(char *inbuf,char *outbuf,int def_class,uint32 def_code,int
       }
     }
 
-  /* Make sure we don't return error codes that old
-     clients don't understand. */
-
-  /* JRA - unfortunately, WinNT needs some error codes
-     for apps to work correctly, Win95 will break if
-     these error codes are returned. But they both
-     negotiate the *same* protocol. So we need to use
-     the revolting 'remote_arch' enum to tie break.
-
-     There must be a better way of doing this...
-  */
-
-  for(i = 0; old_client_errmap[i].new_smb_error != 0; i++)
-  {
-    if(((Protocol < old_client_errmap[i].protocol_level) ||
-       (old_client_errmap[i].valid_ra_type != get_remote_arch())) &&
-       (old_client_errmap[i].new_smb_error == ecode))
-    {
-      ecode = old_client_errmap[i].old_smb_error;
-      break;
-    }
-  }
-
   return(error_packet(inbuf,outbuf,eclass,ecode,line));
 }
 
@@ -2272,22 +2328,21 @@ static int sig_cld()
   **************************************************************************/
 static int sig_pipe()
 {
-  extern int password_client;
-  BlockSignals(True,SIGPIPE);
+       struct cli_state *cli;
+       BlockSignals(True,SIGPIPE);
 
-  if (password_client != -1) {
-    DEBUG(3,("lost connection to password server\n"));
-    close(password_client);
-    password_client = -1;
+       if ((cli = server_client()) && cli->initialised) {
+               DEBUG(3,("lost connection to password server\n"));
+               cli_shutdown(cli);
 #ifndef DONT_REINSTALL_SIG
-    signal(SIGPIPE, SIGNAL_CAST sig_pipe);
+               signal(SIGPIPE, SIGNAL_CAST sig_pipe);
 #endif
-    BlockSignals(False,SIGPIPE);
-    return 0;
-  }
+               BlockSignals(False,SIGPIPE);
+               return 0;
+       }
 
-  exit_server("Got sigpipe\n");
-  return(0);
+       exit_server("Got sigpipe\n");
+       return(0);
 }
 
 /****************************************************************************
@@ -2298,100 +2353,182 @@ static BOOL open_sockets(BOOL is_daemon,int port)
   extern int Client;
 
   if (is_daemon)
-    {
-      int s;
-      struct sockaddr addr;
-      int in_addrlen = sizeof(addr);
-       
-      /* Stop zombies */
+  {
+    int num_interfaces = iface_count();
+    int fd_listenset[FD_SETSIZE];
+    fd_set listen_set;
+    int s;
+    int i;
+
+    /* Stop zombies */
 #ifdef SIGCLD_IGNORE
-      signal(SIGCLD, SIG_IGN);
+    signal(SIGCLD, SIG_IGN);
 #else
-      signal(SIGCLD, SIGNAL_CAST sig_cld);
+    signal(SIGCLD, SIGNAL_CAST sig_cld);
 #endif
 
+    if(atexit_set == 0)
+      atexit(killkids);
+
+    FD_ZERO(&listen_set);
+
+    if(lp_interfaces() && lp_bind_interfaces_only())
+    {
+       /* We have been given an interfaces line, and been 
+          told to only bind to those interfaces. Create a
+          socket per interface and bind to only these.
+        */
+
+      if(num_interfaces > FD_SETSIZE)
+      {
+        DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
+max can be %d\n", num_interfaces, FD_SETSIZE));
+        return False;
+      }
+
+      /* Now open a listen socket for each of the interfaces. */
+      for(i = 0; i < num_interfaces; i++)
+      {
+        struct in_addr *ifip = iface_n_ip(i);
+
+        if(ifip == NULL)
+        {
+          DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
+          continue;
+        }
+        s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr);
+        if(s == -1)
+          return False;
+        /* ready to listen */
+        if (listen(s, 5) == -1) 
+        {
+          DEBUG(0,("listen: %s\n",strerror(errno)));
+          close(s);
+          return False;
+        }
+        FD_SET(s,&listen_set);
+      }
+    }
+    else
+    {
+      /* Just bind to 0.0.0.0 - accept connections from anywhere. */
+      num_interfaces = 1;
+
       /* open an incoming socket */
       s = open_socket_in(SOCK_STREAM, port, 0,interpret_addr(lp_socket_address()));
       if (s == -1)
-       return(False);
+        return(False);
 
       /* ready to listen */
       if (listen(s, 5) == -1) 
-       {
-         DEBUG(0,("listen: %s\n",strerror(errno)));
-         close(s);
-         return False;
-       }
-      
-      if(atexit_set == 0)
-        atexit(killkids);
+      {
+        DEBUG(0,("open_sockets: listen: %s\n",strerror(errno)));
+        close(s);
+        return False;
+      }
 
-      /* now accept incoming connections - forking a new process
-        for each incoming connection */
-      DEBUG(2,("waiting for a connection\n"));
-      while (1)
-       {
-         Client = accept(s,&addr,&in_addrlen);
+      fd_listenset[0] = s;
+      FD_SET(s,&listen_set);
+    }      
+
+    /* now accept incoming connections - forking a new process
+       for each incoming connection */
+    DEBUG(2,("waiting for a connection\n"));
+    while (1)
+    {
+      fd_set lfds;
+      int num;
 
-         if (Client == -1 && errno == EINTR)
-           continue;
+      memcpy((char *)&lfds, (char *)&listen_set, sizeof(listen_set));
 
-         if (Client == -1)
-           {
-             DEBUG(0,("accept: %s\n",strerror(errno)));
-             continue;
-           }
+      num = sys_select(&lfds,NULL);
+
+      if (num == -1 && errno == EINTR)
+        continue;
+
+      /* Find the sockets that are read-ready - accept on these. */
+      for( ; num > 0; num--)
+      {
+        struct sockaddr addr;
+        int in_addrlen = sizeof(addr);
+
+        s = -1;
+        for(i = 0; i < num_interfaces; i++)
+        {
+          if(FD_ISSET(fd_listenset[i],&lfds))
+          {
+            s = fd_listenset[i];
+            /* Clear this so we don't look at it again. */
+            FD_CLR(fd_listenset[i],&lfds);
+            break;
+          }
+        }
+
+        Client = accept(s,&addr,&in_addrlen);
+
+        if (Client == -1 && errno == EINTR)
+          continue;
+
+        if (Client == -1)
+        {
+          DEBUG(0,("open_sockets: accept: %s\n",strerror(errno)));
+          continue;
+        }
 
 #ifdef NO_FORK_DEBUG
+#ifndef NO_SIGNAL_TEST
+        signal(SIGPIPE, SIGNAL_CAST sig_pipe);
+        signal(SIGCLD, SIGNAL_CAST SIG_DFL);
+#endif /* NO_SIGNAL_TEST */
+        return True;
+#else /* NO_FORK_DEBUG */
+        if (Client != -1 && fork()==0)
+        {
+          /* Child code ... */
+
 #ifndef NO_SIGNAL_TEST
           signal(SIGPIPE, SIGNAL_CAST sig_pipe);
           signal(SIGCLD, SIGNAL_CAST SIG_DFL);
-#endif
-         return True;
-#else
-         if (Client != -1 && fork()==0)
-           {
-              /* Child code ... */
-#ifndef NO_SIGNAL_TEST
-             signal(SIGPIPE, SIGNAL_CAST sig_pipe);
-             signal(SIGCLD, SIGNAL_CAST SIG_DFL);
-#endif
-             /* close the listening socket */
-             close(s);
-
-             /* close our standard file descriptors */
-             close_low_fds();
-              am_parent = 0;
+#endif /* NO_SIGNAL_TEST */
+          /* close the listening socket(s) */
+          for(i = 0; i < num_interfaces; i++)
+            close(fd_listenset[i]);
+
+          /* close our standard file descriptors */
+          close_low_fds();
+          am_parent = 0;
   
-             set_socket_options(Client,"SO_KEEPALIVE");
-             set_socket_options(Client,user_socket_options);
-
-              /* Reset global variables in util.c so that
-                 client substitutions will be done correctly
-                 in the process.
-               */
-              reset_globals_after_fork();
-             return True; 
-           }
-          close(Client); /* The parent doesn't need this socket */
-#endif
-       }
-    }
+          set_socket_options(Client,"SO_KEEPALIVE");
+          set_socket_options(Client,user_socket_options);
+
+          /* Reset global variables in util.c so that
+             client substitutions will be done correctly
+             in the process.
+           */
+          reset_globals_after_fork();
+          return True; 
+        }
+        close(Client); /* The parent doesn't need this socket */
+#endif /NO_FORK_DEBUG */
+      } /* end for num */
+    } /* end while 1 */
+  } /* end if is_daemon */
   else
-    {
-      /* We will abort gracefully when the client or remote system 
-        goes away */
+  {
+    /* Started from inetd. fd 0 is the socket. */
+    /* We will abort gracefully when the client or remote system 
+       goes away */
 #ifndef NO_SIGNAL_TEST
-      signal(SIGPIPE, SIGNAL_CAST sig_pipe);
+    signal(SIGPIPE, SIGNAL_CAST sig_pipe);
 #endif
-      Client = dup(0);
+    Client = dup(0);
 
-      /* close our standard file descriptors */
-      close_low_fds();
+    /* close our standard file descriptors */
+    close_low_fds();
 
-      set_socket_options(Client,"SO_KEEPALIVE");
-      set_socket_options(Client,user_socket_options);
-    }
+    set_socket_options(Client,"SO_KEEPALIVE");
+    set_socket_options(Client,user_socket_options);
+  }
 
   return True;
 }
@@ -2404,12 +2541,27 @@ static BOOL open_sockets(BOOL is_daemon,int port)
 static void process_smb(char *inbuf, char *outbuf)
 {
   extern int Client;
-  static int trans_num = 0;
-
+  static int trans_num;
   int msg_type = CVAL(inbuf,0);
-  int32 len = smb_len(outbuf);
+  int32 len = smb_len(inbuf);
   int nread = len + 4;
 
+  if (trans_num == 0) {
+         /* on the first packet, check the global hosts allow/ hosts
+            deny parameters before doing any parsing of the packet
+            passed to us by the client.  This prevents attacks on our
+            parsing code from hosts not in the hosts allow list */
+         if (!check_access(-1)) {
+                 /* send a negative session response "not listining on calling
+                  name" */
+                 static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
+                 DEBUG(1,("%s Connection denied from %s\n",
+                          timestring(),client_addr()));
+                 send_smb(Client,(char *)buf);
+                 exit_server("connection denied");
+         }
+  }
+
   DEBUG(6,("got message type 0x%x of len 0x%x\n",msg_type,len));
   DEBUG(3,("%s Transaction %d of length %d\n",timestring(),trans_num,nread));
 
@@ -2442,14 +2594,13 @@ static void process_smb(char *inbuf, char *outbuf)
   trans_num++;
 }
 
-#ifdef USE_OPLOCKS
 /****************************************************************************
   open the oplock IPC socket communication
 ****************************************************************************/
 static BOOL open_oplock_ipc()
 {
   struct sockaddr_in sock_name;
-  int name_len = sizeof(sock_name);
+  int len = sizeof(sock_name);
 
   DEBUG(3,("open_oplock_ipc: opening loopback UDP socket.\n"));
 
@@ -2464,7 +2615,7 @@ address %x. Error was %s\n", htonl(INADDR_LOOPBACK), strerror(errno)));
   }
 
   /* Find out the transient UDP port we have been allocated. */
-  if(getsockname(oplock_sock, (struct sockaddr *)&sock_name, &name_len)<0)
+  if(getsockname(oplock_sock, (struct sockaddr *)&sock_name, &len)<0)
   {
     DEBUG(0,("open_oplock_ipc: Failed to get local UDP port. Error was %s\n",
             strerror(errno)));
@@ -2475,16 +2626,19 @@ address %x. Error was %s\n", htonl(INADDR_LOOPBACK), strerror(errno)));
   }
   oplock_port = ntohs(sock_name.sin_port);
 
+  DEBUG(3,("open_oplock ipc: pid = %d, oplock_port = %u\n", 
+            getpid(), oplock_port));
+
   return True;
 }
 
 /****************************************************************************
   process an oplock break message.
 ****************************************************************************/
-static BOOL process_local_message(int oplock_sock, char *buffer, int buf_size)
+static BOOL process_local_message(int sock, char *buffer, int buf_size)
 {
   int32 msg_len;
-  int16 from_port;
+  uint16 from_port;
   char *msg_start;
 
   msg_len = IVAL(buffer,UDP_CMD_LEN_OFFSET);
@@ -2512,8 +2666,12 @@ should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
         uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
         uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
         uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
+        struct timeval tval;
         struct sockaddr_in toaddr;
 
+        tval.tv_sec = IVAL(msg_start, OPLOCK_BREAK_SEC_OFFSET);
+        tval.tv_usec = IVAL(msg_start, OPLOCK_BREAK_USEC_OFFSET);
+
         DEBUG(5,("process_local_message: oplock break request from \
 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
 
@@ -2526,7 +2684,7 @@ pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
 
         if(global_oplocks_open != 0)
         {
-          if(oplock_break(dev, inode) == False)
+          if(oplock_break(dev, inode, &tval) == False)
           {
             DEBUG(0,("process_local_message: oplock break failed - \
 not returning udp message.\n"));
@@ -2547,7 +2705,7 @@ oplocks. Returning success.\n"));
         toaddr.sin_port = htons(from_port);
         toaddr.sin_family = AF_INET;
 
-        if(sendto( oplock_sock, msg_start, OPLOCK_BREAK_MSG_LEN, 0,
+        if(sendto( sock, msg_start, OPLOCK_BREAK_MSG_LEN, 0,
                 (struct sockaddr *)&toaddr, sizeof(toaddr)) < 0) 
         {
           DEBUG(0,("process_local_message: sendto process %d failed. Errno was %s\n",
@@ -2561,6 +2719,31 @@ pid %d, port %d, for file dev = %x, inode = %x\n", remotepid,
 
       }
       break;
+    /* 
+     * Keep this as a debug case - eventually we can remove it.
+     */
+    case 0x8001:
+      DEBUG(0,("process_local_message: Received unsolicited break \
+reply - dumping info.\n"));
+
+      if(msg_len != OPLOCK_BREAK_MSG_LEN)
+      {
+        DEBUG(0,("process_local_message: ubr: incorrect length for reply \
+(was %d, should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
+        return False;
+      }
+
+      {
+        uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
+        uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
+        uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
+
+        DEBUG(0,("process_local_message: unsolicited oplock break reply from \
+pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
+
+       }
+       return False;
+
     default:
       DEBUG(0,("process_local_message: unknown UDP message command code (%x) - ignoring.\n",
                 (unsigned int)SVAL(msg_start,0)));
@@ -2572,17 +2755,19 @@ pid %d, port %d, for file dev = %x, inode = %x\n", remotepid,
 /****************************************************************************
  Process an oplock break directly.
 ****************************************************************************/
-BOOL oplock_break(uint32 dev, uint32 inode)
+BOOL oplock_break(uint32 dev, uint32 inode, struct timeval *tval)
 {
   extern int Client;
   static char *inbuf = NULL;
   static char *outbuf = NULL;
   files_struct *fsp = NULL;
   int fnum;
-  share_lock_token token;
   time_t start_time;
   BOOL shutdown_server = False;
 
+  DEBUG(3,("%s oplock_break: called for dev = %x, inode = %x. Current \
+global_oplocks_open = %d\n", timestring(), dev, inode, global_oplocks_open));
+
   if(inbuf == NULL)
   {
     inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
@@ -2607,7 +2792,9 @@ BOOL oplock_break(uint32 dev, uint32 inode)
     if(OPEN_FNUM(fnum))
     {
       fsp = &Files[fnum];
-      if((fsp->fd_ptr->dev == dev) && (fsp->fd_ptr->inode == inode))
+      if((fsp->fd_ptr->dev == dev) && (fsp->fd_ptr->inode == inode) &&
+         (fsp->open_time.tv_sec == tval->tv_sec) && 
+         (fsp->open_time.tv_usec == tval->tv_usec))
         break;
     }
   }
@@ -2615,23 +2802,25 @@ BOOL oplock_break(uint32 dev, uint32 inode)
   if(fsp == NULL)
   {
     /* The file could have been closed in the meantime - return success. */
-    DEBUG(3,("oplock_break: cannot find open file with dev = %x, inode = %x (fnum = %d) \
-allowing break to succeed.\n", dev, inode, fnum));
+    DEBUG(3,("%s oplock_break: cannot find open file with dev = %x, inode = %x (fnum = %d) \
+allowing break to succeed.\n", timestring(), dev, inode, fnum));
     return True;
   }
 
   /* Ensure we have an oplock on the file */
 
-  /* Question - can a client asynchronously break an oplock ? Would it
-     ever do so ? If so this test is invalid for external smbd oplock
-     breaks and we should return True in these cases (JRA).
+  /* There is a potential race condition in that an oplock could
+     have been broken due to another udp request, and yet there are
+     still oplock break messages being sent in the udp message
+     queue for this file. So return true if we don't have an oplock,
+     as we may have just freed it.
    */
 
   if(!fsp->granted_oplock)
   {
-    DEBUG(0,("oplock_break: file %s (fnum = %d, dev = %x, inode = %x) has no oplock.\n",
-              fsp->name, fnum, dev, inode));
-    return False;
+    DEBUG(3,("%s oplock_break: file %s (fnum = %d, dev = %x, inode = %x) has no oplock. \
+Allowing break to succeed regardless.\n", timestring(), fsp->name, fnum, dev, inode));
+    return True;
   }
 
   /* Now comes the horrid part. We must send an oplock break to the client,
@@ -2673,25 +2862,26 @@ allowing break to succeed.\n", dev, inode, fnum));
        */
 
       if (smb_read_error == READ_EOF)
-        DEBUG(0,("oplock_break: end of file from client\n"));
+        DEBUG(0,("%s oplock_break: end of file from client\n", timestring()));
  
       if (smb_read_error == READ_ERROR)
-        DEBUG(0,("oplock_break: receive_smb error (%s)\n",
-                  strerror(errno)));
+        DEBUG(0,("%s oplock_break: receive_smb error (%s)\n",
+                  timestring(), strerror(errno)));
 
       if (smb_read_error == READ_TIMEOUT)
-        DEBUG(0,("oplock_break: receive_smb timed out after %d seconds.\n",
-                  OPLOCK_BREAK_TIMEOUT));
+        DEBUG(0,("%s oplock_break: receive_smb timed out after %d seconds.\n",
+                  timestring(), OPLOCK_BREAK_TIMEOUT));
 
-      DEBUG(0,("oplock_break failed for file %s (fnum = %d, dev = %x, \
-inode = %x).\n", fsp->name, fnum, dev, inode));
+      DEBUG(0,("%s oplock_break failed for file %s (fnum = %d, dev = %x, \
+inode = %x).\n", timestring(), fsp->name, fnum, dev, inode));
       shutdown_server = True;
       break;
     }
     process_smb(inbuf, outbuf);
 
     /* We only need this in case a readraw crossed on the wire. */
-    global_oplock_break = False;
+    if(global_oplock_break)
+      global_oplock_break = False;
 
     /*
      * Die if we go over the time limit.
@@ -2699,10 +2889,10 @@ inode = %x).\n", fsp->name, fnum, dev, inode));
 
     if((time(NULL) - start_time) > OPLOCK_BREAK_TIMEOUT)
     {
-      DEBUG(0,("oplock_break: no break received from client within \
-%d seconds.\n", OPLOCK_BREAK_TIMEOUT));
-      DEBUG(0,("oplock_break failed for file %s (fnum = %d, dev = %x, \
-inode = %x).\n", fsp->name, fnum, dev, inode));
+      DEBUG(0,("%s oplock_break: no break received from client within \
+%d seconds.\n", timestring(), OPLOCK_BREAK_TIMEOUT));
+      DEBUG(0,("%s oplock_break failed for file %s (fnum = %d, dev = %x, \
+inode = %x).\n", timestring(), fsp->name, fnum, dev, inode));
       shutdown_server = True;
       break;
     }
@@ -2714,7 +2904,8 @@ inode = %x).\n", fsp->name, fnum, dev, inode));
 
   if(shutdown_server)
   {
-    DEBUG(0,("oplock_break: client failure in break - shutting down this smbd.\n"));
+    DEBUG(0,("%s oplock_break: client failure in break - shutting down this smbd.\n",
+          timestring()));
     close_sockets();
     close(oplock_sock);
     exit_server("oplock break failure");
@@ -2722,16 +2913,10 @@ inode = %x).\n", fsp->name, fnum, dev, inode));
 
   if(OPEN_FNUM(fnum))
   {
-    /* Remove the oplock flag from the sharemode. */
-    lock_share_entry(fsp->cnum, dev, inode, &token);
-    if(remove_share_oplock( fnum, token)==False)
-    {
-      DEBUG(0,("oplock_break: failed to remove share oplock for fnum %d, \
-dev = %x, inode = %x\n", fnum, dev, inode));
-      unlock_share_entry(fsp->cnum, dev, inode, token);
-      return False;
-    }
-    unlock_share_entry(fsp->cnum, dev, inode, token);
+    /* The lockingX reply will have removed the oplock flag 
+       from the sharemode. */
+    /* Paranoia.... */
+    fsp->granted_oplock = False;
   }
 
   global_oplocks_open--;
@@ -2741,9 +2926,12 @@ dev = %x, inode = %x\n", fnum, dev, inode));
   {
     DEBUG(0,("oplock_break: global_oplocks_open < 0 (%d). PANIC ERROR\n",
               global_oplocks_open));
-    abort();
+    exit_server("oplock_break: global_oplocks_open < 0");
   }
 
+  DEBUG(3,("%s oplock_break: returning success for fnum = %d, dev = %x, inode = %x. Current \
+global_oplocks_open = %d\n", timestring(), fnum, dev, inode, global_oplocks_open));
+
   return True;
 }
 
@@ -2752,7 +2940,7 @@ Send an oplock break message to another smbd process. If the oplock is held
 by the local smbd then call the oplock break function directly.
 ****************************************************************************/
 
-BOOL request_oplock_break(min_share_mode_entry *share_entry, 
+BOOL request_oplock_break(share_mode_entry *share_entry, 
                           uint32 dev, uint32 inode)
 {
   char op_break_msg[OPLOCK_BREAK_MSG_LEN];
@@ -2764,12 +2952,15 @@ BOOL request_oplock_break(min_share_mode_entry *share_entry,
     /* We are breaking our own oplock, make sure it's us. */
     if(share_entry->op_port != oplock_port)
     {
-      DEBUG(0,("request_oplock_break: corrupt share mode entry - pid = %x, port = %d \
+      DEBUG(0,("request_oplock_break: corrupt share mode entry - pid = %d, port = %d \
 should be %d\n", pid, share_entry->op_port, oplock_port));
       return False;
     }
+
+    DEBUG(5,("request_oplock_break: breaking our own oplock\n"));
+
     /* Call oplock break direct. */
-    return oplock_break(dev, inode);
+    return oplock_break(dev, inode, &share_entry->time);
   }
 
   /* We need to send a OPLOCK_BREAK_CMD message to the
@@ -2779,6 +2970,8 @@ should be %d\n", pid, share_entry->op_port, oplock_port));
   SIVAL(op_break_msg,OPLOCK_BREAK_PID_OFFSET,pid);
   SIVAL(op_break_msg,OPLOCK_BREAK_DEV_OFFSET,dev);
   SIVAL(op_break_msg,OPLOCK_BREAK_INODE_OFFSET,inode);
+  SIVAL(op_break_msg,OPLOCK_BREAK_SEC_OFFSET,(uint32)share_entry->time.tv_sec);
+  SIVAL(op_break_msg,OPLOCK_BREAK_USEC_OFFSET,(uint32)share_entry->time.tv_usec);
 
   /* set the address and port */
   bzero((char *)&addr_out,sizeof(addr_out));
@@ -2786,15 +2979,15 @@ should be %d\n", pid, share_entry->op_port, oplock_port));
   addr_out.sin_port = htons( share_entry->op_port );
   addr_out.sin_family = AF_INET;
    
-  DEBUG(3,("request_oplock_break: sending a oplock break message to pid %d on port %d \
-for dev = %x, inode = %x\n", share_entry->pid, share_entry->op_port, dev, inode));
+  DEBUG(3,("%s request_oplock_break: sending a oplock break message to pid %d on port %d \
+for dev = %x, inode = %x\n", timestring(), share_entry->pid, share_entry->op_port, dev, inode));
 
   if(sendto(oplock_sock,op_break_msg,OPLOCK_BREAK_MSG_LEN,0,
          (struct sockaddr *)&addr_out,sizeof(addr_out)) < 0)
   {
-    DEBUG(0,("request_oplock_break: failed when sending a oplock break message \
+    DEBUG(0,("%s request_oplock_break: failed when sending a oplock break message \
 to pid %d on port %d for dev = %x, inode = %x. Error was %s\n",
-         share_entry->pid, share_entry->op_port, dev, inode,
+         timestring(), share_entry->pid, share_entry->op_port, dev, inode,
          strerror(errno)));
     return False;
   }
@@ -2802,7 +2995,7 @@ to pid %d on port %d for dev = %x, inode = %x. Error was %s\n",
   /*
    * Now we must await the oplock broken message coming back
    * from the target smbd process. Timeout if it fails to
-   * return in OPLOCK_BREAK_TIMEOUT seconds.
+   * return in (OPLOCK_BREAK_TIMEOUT + OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR) seconds.
    * While we get messages that aren't ours, loop.
    */
 
@@ -2810,19 +3003,29 @@ to pid %d on port %d for dev = %x, inode = %x. Error was %s\n",
   {
     char op_break_reply[UDP_CMD_HEADER_LEN+OPLOCK_BREAK_MSG_LEN];
     int32 reply_msg_len;
-    int16 reply_from_port;
+    uint16 reply_from_port;
     char *reply_msg_start;
 
     if(receive_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply),
-                             OPLOCK_BREAK_TIMEOUT * 1000) == False)
+               (OPLOCK_BREAK_TIMEOUT+OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR) * 1000) == False)
     {
       if(smb_read_error == READ_TIMEOUT)
-        DEBUG(0,("request_oplock_break: no response received to oplock break request to \
-pid %d on port %d for dev = %x, inode = %x\n", share_entry->pid, 
+      {
+        DEBUG(0,("%s request_oplock_break: no response received to oplock break request to \
+pid %d on port %d for dev = %x, inode = %x\n", timestring(), share_entry->pid, 
                            share_entry->op_port, dev, inode));
+        /*
+         * This is a hack to make handling of failing clients more robust.
+         * If a oplock break response message is not received in the timeout
+         * period we may assume that the smbd servicing that client holding
+         * the oplock has died and the client changes were lost anyway, so
+         * we should continue to try and open the file.
+         */
+        break;
+      }
       else
-        DEBUG(0,("request_oplock_break: error in response received to oplock break request to \
-pid %d on port %d for dev = %x, inode = %x. Error was (%s).\n", share_entry->pid, 
+        DEBUG(0,("%s request_oplock_break: error in response received to oplock break request to \
+pid %d on port %d for dev = %x, inode = %x. Error was (%s).\n", timestring, share_entry->pid, 
                          share_entry->op_port, dev, inode, strerror(errno)));
       return False;
     }
@@ -2852,7 +3055,8 @@ pid %d on port %d for dev = %x, inode = %x. Error was (%s).\n", share_entry->pid
     if(reply_msg_len != OPLOCK_BREAK_MSG_LEN)
     {
       /* Ignore it. */
-      DEBUG(0,("request_oplock_break: invalid message length received. Ignoring\n"));
+      DEBUG(0,("%s request_oplock_break: invalid message length received. Ignoring\n",
+             timestring()));
       continue;
     }
 
@@ -2862,23 +3066,22 @@ pid %d on port %d for dev = %x, inode = %x. Error was (%s).\n", share_entry->pid
                &op_break_msg[OPLOCK_BREAK_PID_OFFSET],
                OPLOCK_BREAK_MSG_LEN - OPLOCK_BREAK_PID_OFFSET) != 0))
     {
-      DEBUG(3,("request_oplock_break: received other message whilst awaiting \
+      DEBUG(3,("%s request_oplock_break: received other message whilst awaiting \
 oplock break response from pid %d on port %d for dev = %x, inode = %x.\n",
-             share_entry->pid, share_entry->op_port, dev, inode));
+             timestring(), share_entry->pid, share_entry->op_port, dev, inode));
       if(push_local_message(op_break_reply, sizeof(op_break_reply)) == False)
         return False;
+      continue;
     }
 
     break;
   }
 
-  DEBUG(3,("request_oplock_break: broke oplock.\n"));
+  DEBUG(3,("%s request_oplock_break: broke oplock.\n", timestring()));
 
   return True;
 }
 
-#endif /* USE_OPLOCKS */
-
 /****************************************************************************
 check if a snum is in use
 ****************************************************************************/
@@ -2934,7 +3137,7 @@ BOOL reload_services(BOOL test)
     }
   }
 
-  create_mangled_stack(lp_mangledstack());
+  reset_mangled_stack( lp_mangledstack() );
 
   /* this forces service parameters to be flushed */
   become_service(-1,True);
@@ -2963,7 +3166,8 @@ static int sig_hup()
 Setup the groups a user belongs to.
 ****************************************************************************/
 int setup_groups(char *user, int uid, int gid, int *p_ngroups, 
-                int **p_igroups, gid_t **p_groups)
+                int **p_igroups, gid_t **p_groups,
+         int **p_attrs)
 {
   if (-1 == initgroups(user,gid))
     {
@@ -2978,19 +3182,25 @@ int setup_groups(char *user, int uid, int gid, int *p_ngroups,
     {
       int i,ngroups;
       int *igroups;
+      int *attrs;
       gid_t grp = 0;
       ngroups = getgroups(0,&grp);
       if (ngroups <= 0)
         ngroups = 32;
       igroups = (int *)malloc(sizeof(int)*ngroups);
+      attrs   = (int *)malloc(sizeof(int)*ngroups);
       for (i=0;i<ngroups;i++)
+      {
+        attrs  [i] = 0x7; /* XXXX don't know what NT user attributes are yet! */
         igroups[i] = 0x42424242;
+      }
       ngroups = getgroups(ngroups,(gid_t *)igroups);
 
       if (igroups[0] == 0x42424242)
         ngroups = 0;
 
       *p_ngroups = ngroups;
+      *p_attrs   = attrs;
 
       /* The following bit of code is very strange. It is due to the
          fact that some OSes use int* and some use gid_t* for
@@ -3012,16 +3222,18 @@ int setup_groups(char *user, int uid, int gid, int *p_ngroups,
              groups_use_ints = False;
              
           if (groups_use_ints)
-            {
+          {
              *p_igroups = igroups;
              *p_groups = (gid_t *)igroups;       
-            }
+          }
           else
-            {
+          {
              gid_t *groups = (gid_t *)igroups;
              igroups = (int *)malloc(sizeof(int)*ngroups);
              for (i=0;i<ngroups;i++)
+          {
                igroups[i] = groups[i];
+          }
              *p_igroups = igroups;
              *p_groups = (gid_t *)groups;
            }
@@ -3147,8 +3359,17 @@ int make_connection(char *service,char *user,char *password, int pwlen, char *de
   }
 
   /* admin user check */
-  if (user_in_list(user,lp_admin_users(snum)) &&
-      !pcon->read_only)
+
+  /* JRA - original code denied admin user if the share was
+     marked read_only. Changed as I don't think this is needed,
+     but old code left in case there is a problem here.
+   */
+  if (user_in_list(user,lp_admin_users(snum)) 
+#if 0
+      && !pcon->read_only)
+#else
+      )
+#endif
     {
       pcon->admin_user = True;
       DEBUG(0,("%s logged in as admin user (root privileges)\n",user));
@@ -3221,12 +3442,15 @@ int make_connection(char *service,char *user,char *password, int pwlen, char *de
 
   /* groups stuff added by ih */
   pcon->ngroups = 0;
+  pcon->igroups = NULL;
   pcon->groups = NULL;
+  pcon->attrs = NULL;
 
   if (!IS_IPC(cnum))
     {
       /* Find all the groups this uid is in and store them. Used by become_user() */
-      setup_groups(pcon->user,pcon->uid,pcon->gid,&pcon->ngroups,&pcon->igroups,&pcon->groups);
+      setup_groups(pcon->user,pcon->uid,pcon->gid,
+                  &pcon->ngroups,&pcon->igroups,&pcon->groups,&pcon->attrs);
       
       /* check number of connections */
       if (!claim_connection(cnum,
@@ -3255,7 +3479,7 @@ int make_connection(char *service,char *user,char *password, int pwlen, char *de
       smbrun(cmd,NULL,False);
     }
 
-  if (!become_user(cnum,pcon->vuid))
+  if (!become_user(&Connections[cnum], cnum,pcon->vuid))
     {
       DEBUG(0,("Can't become connected user!\n"));
       pcon->open = False;
@@ -3424,11 +3648,6 @@ int reply_lanman1(char *outbuf)
   int secword=0;
   BOOL doencrypt = SMBENCRYPT();
   time_t t = time(NULL);
-  /* We need to save and restore this as it can be destroyed
-     if we call another server if security=server
-     Thanks to Paul Nelson @ Thursby for pointing this out.
-   */
-  uint16 mid = SVAL(outbuf, smb_mid);
 
   if (lp_security()>=SEC_USER) secword |= 1;
   if (doencrypt) secword |= 2;
@@ -3441,13 +3660,7 @@ int reply_lanman1(char *outbuf)
 
   Protocol = PROTOCOL_LANMAN1;
 
-  if (lp_security() == SEC_SERVER && server_cryptkey(outbuf)) {
-    DEBUG(3,("using password server validation\n"));
-  if (doencrypt) set_challenge(smb_buf(outbuf));    
-  }
-
   CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
-  SSVAL(outbuf,smb_mid,mid); /* Restore possibly corrupted mid */
   SSVAL(outbuf,smb_vwv2,max_recv);
   SSVAL(outbuf,smb_vwv3,lp_maxmux()); /* maxmux */
   SSVAL(outbuf,smb_vwv4,1);
@@ -3471,32 +3684,41 @@ int reply_lanman2(char *outbuf)
   int secword=0;
   BOOL doencrypt = SMBENCRYPT();
   time_t t = time(NULL);
-  /* We need to save and restore this as it can be destroyed
-     if we call another server if security=server
-     Thanks to Paul Nelson @ Thursby for pointing this out.
-   */
-  uint16 mid = SVAL(outbuf, smb_mid);
+  struct cli_state *cli = NULL;
+  char cryptkey[8];
+  char crypt_len = 0;
+
+  if (lp_security() == SEC_SERVER) {
+         cli = server_cryptkey();
+  }
+
+  if (cli) {
+         DEBUG(3,("using password server validation\n"));
+         doencrypt = ((cli->sec_mode & 2) != 0);
+  }
 
   if (lp_security()>=SEC_USER) secword |= 1;
   if (doencrypt) secword |= 2;
 
-  set_message(outbuf,13,doencrypt?8:0,True);
-  SSVAL(outbuf,smb_vwv1,secword); 
-  /* Create a token value and add it to the outgoing packet. */
-  if (doencrypt) 
-    generate_next_challenge(smb_buf(outbuf));
+  if (doencrypt) {
+         crypt_len = 8;
+         if (!cli) {
+                 generate_next_challenge(cryptkey);
+         } else {
+                 memcpy(cryptkey, cli->cryptkey, 8);
+                 set_challenge(cli->cryptkey);
+         }
+  }
 
+  set_message(outbuf,13,crypt_len,True);
+  SSVAL(outbuf,smb_vwv1,secword); 
   SIVAL(outbuf,smb_vwv6,getpid());
+  if (doencrypt) 
+         memcpy(smb_buf(outbuf), cryptkey, 8);
 
   Protocol = PROTOCOL_LANMAN2;
 
-  if (lp_security() == SEC_SERVER && server_cryptkey(outbuf)) {
-    DEBUG(3,("using password server validation\n"));
-    if (doencrypt) set_challenge(smb_buf(outbuf));    
-  }
-
   CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
-  SSVAL(outbuf,smb_mid,mid); /* Restore possibly corrupted mid */
   SSVAL(outbuf,smb_vwv2,max_recv);
   SSVAL(outbuf,smb_vwv3,lp_maxmux()); 
   SSVAL(outbuf,smb_vwv4,1);
@@ -3518,67 +3740,58 @@ int reply_nt1(char *outbuf)
 /*
   other valid capabilities which we may support at some time...
                      CAP_LARGE_FILES|CAP_NT_SMBS|CAP_RPC_REMOTE_APIS;
-                     CAP_LARGE_FILES|CAP_LARGE_READX|
-                     CAP_STATUS32|CAP_LEVEL_II_OPLOCKS;
+                     CAP_LARGE_READX|CAP_STATUS32|CAP_LEVEL_II_OPLOCKS;
  */
 
   int secword=0;
   BOOL doencrypt = SMBENCRYPT();
   time_t t = time(NULL);
   int data_len;
-  int encrypt_len;
-  char challenge_len = 8;
-  /* We need to save and restore this as it can be destroyed
-     if we call another server if security=server
-     Thanks to Paul Nelson @ Thursby for pointing this out.
-   */
-  uint16 mid = SVAL(outbuf, smb_mid);
+  struct cli_state *cli = NULL;
+  char cryptkey[8];
+  char crypt_len = 0;
 
-  if (lp_readraw() && lp_writeraw())
-  {
-    capabilities |= CAP_RAW_MODE;
+  if (lp_security() == SEC_SERVER) {
+         cli = server_cryptkey();
   }
 
-  if (lp_security()>=SEC_USER) secword |= 1;
+  if (cli) {
+         DEBUG(3,("using password server validation\n"));
+         doencrypt = ((cli->sec_mode & 2) != 0);
+  }
+
+  if (doencrypt) {
+         crypt_len = 8;
+         if (!cli) {
+                 generate_next_challenge(cryptkey);
+         } else {
+                 memcpy(cryptkey, cli->cryptkey, 8);
+                 set_challenge(cli->cryptkey);
+         }
+  }
+
+  if (lp_readraw() && lp_writeraw()) {
+         capabilities |= CAP_RAW_MODE;
+  }
+
+  if (lp_security() >= SEC_USER) secword |= 1;
   if (doencrypt) secword |= 2;
 
   /* decide where (if) to put the encryption challenge, and
      follow it with the OEM'd domain name
    */
-  encrypt_len = doencrypt?challenge_len:0;
-#if UNICODE
-  data_len = encrypt_len + 2*(strlen(myworkgroup)+1);
-#else
-  data_len = encrypt_len + strlen(myworkgroup) + 1;
-#endif
+  data_len = crypt_len + strlen(myworkgroup) + 1;
 
   set_message(outbuf,17,data_len,True);
-
-#if UNICODE
-  /* put the OEM'd domain name */
-  PutUniCode(smb_buf(outbuf)+encrypt_len,myworkgroup);
-#else
-  strcpy(smb_buf(outbuf)+encrypt_len, myworkgroup);
-#endif
+  strcpy(smb_buf(outbuf)+crypt_len, myworkgroup);
 
   CVAL(outbuf,smb_vwv1) = secword;
-  /* Create a token value and add it to the outgoing packet. */
-  if (doencrypt)
-  {
-    generate_next_challenge(smb_buf(outbuf));
-
-    /* Tell the nt machine how long the challenge is. */
-    SSVALS(outbuf,smb_vwv16+1,challenge_len);
-  }
+  SSVALS(outbuf,smb_vwv16+1,crypt_len);
+  if (doencrypt) 
+         memcpy(smb_buf(outbuf), cryptkey, 8);
 
   Protocol = PROTOCOL_NT1;
 
-  if (lp_security() == SEC_SERVER && server_cryptkey(outbuf)) {
-    DEBUG(3,("using password server validation\n"));
-    if (doencrypt) set_challenge(smb_buf(outbuf));    
-  }
-
-  SSVAL(outbuf,smb_mid,mid); /* Restore possibly corrupted mid */
   SSVAL(outbuf,smb_vwv1+1,lp_maxmux()); /* maxmpx */
   SSVAL(outbuf,smb_vwv2+1,1); /* num vcs */
   SIVAL(outbuf,smb_vwv3+1,0xffff); /* max buffer. LOTS! */
@@ -3786,7 +3999,7 @@ static void close_open_files(int cnum)
   int i;
   for (i=0;i<MAX_OPEN_FILES;i++)
     if( Files[i].cnum == cnum && Files[i].open) {
-      close_file(i);
+      close_file(i,False);
     }
 }
 
@@ -3823,7 +4036,7 @@ void close_cnum(int cnum, uint16 vuid)
   dptr_closecnum(cnum);
 
   /* execute any "postexec = " line */
-  if (*lp_postexec(SNUM(cnum)) && become_user(cnum,vuid))
+  if (*lp_postexec(SNUM(cnum)) && become_user(&Connections[cnum], cnum,vuid))
     {
       pstring cmd;
       strcpy(cmd,lp_postexec(SNUM(cnum)));
@@ -4110,9 +4323,7 @@ void exit_server(char *reason)
 #endif
   }    
 
-#ifdef FAST_SHARE_MODES
-  stop_share_mode_mgmt();
-#endif /* FAST_SHARE_MODES */
+  locking_end();
 
   DEBUG(3,("%s Server exit  (%s)\n",timestring(),reason?reason:""));
   exit(0);
@@ -4348,7 +4559,7 @@ static int switch_message(int type,char *inbuf,char *outbuf,int size,int bufsize
            unbecome_user();
 
          /* does this protocol need to be run as the connected user? */
-         if ((flags & AS_USER) && !become_user(cnum,session_tag)) {
+         if ((flags & AS_USER) && !become_user(&Connections[cnum], cnum,session_tag)) {
            if (flags & AS_GUEST) 
              flags &= ~AS_USER;
            else
@@ -4521,6 +4732,7 @@ int construct_reply(char *inbuf,char *outbuf,int size,int bufsize)
 
   chain_size = 0;
   chain_fnum = -1;
+  reset_chain_pnum();
 
   bzero(outbuf,smb_size);
 
@@ -4577,31 +4789,30 @@ static void process(void)
   }
 #endif    
 
+  /* re-initialise the timezone */
+  TimeInit();
+
   while (True)
   {
     int deadtime = lp_deadtime()*60;
     int counter;
     int last_keepalive=0;
     int service_load_counter = 0;
-#ifdef USE_OPLOCKS
     BOOL got_smb = False;
-#endif /* USE_OPLOCKS */
 
     if (deadtime <= 0)
       deadtime = DEFAULT_SMBD_TIMEOUT;
 
+#if USE_READ_PREDICTION
     if (lp_readprediction())
       do_read_prediction();
+#endif
 
     errno = 0;      
 
     for (counter=SMBD_SELECT_LOOP; 
-#ifdef USE_OPLOCKS
           !receive_message_or_smb(Client,oplock_sock,
                       InBuffer,BUFFER_SIZE,SMBD_SELECT_LOOP*1000,&got_smb); 
-#else /* USE_OPLOCKS */
-          !receive_smb(Client,InBuffer,SMBD_SELECT_LOOP*1000); 
-#endif /* USE_OPLOCKS */
           counter += SMBD_SELECT_LOOP)
     {
       int i;
@@ -4651,17 +4862,16 @@ static void process(void)
 
       if (keepalive && (counter-last_keepalive)>keepalive) 
       {
-        extern int password_client;
-        if (!send_keepalive(Client))
-        { 
-          DEBUG(2,("%s Keepalive failed - exiting\n",timestring()));
-          return;
-        }          
-        /* also send a keepalive to the password server if its still
-           connected */
-        if (password_client != -1)
-          send_keepalive(password_client);
-        last_keepalive = counter;
+             struct cli_state *cli = server_client();
+             if (!send_keepalive(Client)) { 
+                     DEBUG(2,("%s Keepalive failed - exiting\n",timestring()));
+                     return;
+             }     
+             /* also send a keepalive to the password server if its still
+                connected */
+             if (cli && cli->initialised)
+                     send_keepalive(cli->fd);
+             last_keepalive = counter;
       }
 
       /* check for connection timeouts */
@@ -4684,14 +4894,10 @@ static void process(void)
       }
     }
 
-#ifdef USE_OPLOCKS
     if(got_smb)
-#endif /* USE_OPLOCKS */
       process_smb(InBuffer, OutBuffer);
-#ifdef USE_OPLOCKS
     else
       process_local_message(oplock_sock, InBuffer, BUFFER_SIZE);
-#endif /* USE_OPLOCKS */
   }
 }
 
@@ -4735,6 +4941,14 @@ static void init_structs(void )
       fd_ptr->real_open_flags = -1;
     }
 
+  /* for RPC pipes */
+  init_rpc_pipe_hnd();
+
+#ifdef NTDOMAIN
+  /* for LSA handles */
+  init_lsa_policy_hnd();
+#endif
+
   init_dptrs();
 }
 
@@ -4955,10 +5169,8 @@ static void usage(char *pname)
   if (!open_sockets(is_daemon,port))
     exit(1);
 
-#ifdef FAST_SHARE_MODES
-  if (!start_share_mode_mgmt())
+  if (!locking_init(0))
     exit(1);
-#endif /* FAST_SHARE_MODES */
 
   /* possibly reload the services file. */
   reload_services(True);
@@ -4971,11 +5183,9 @@ static void usage(char *pname)
        DEBUG(2,("%s changed root to %s\n",timestring(),lp_rootdir()));
     }
 
-#ifdef USE_OPLOCKS
   /* Setup the oplock IPC socket. */
   if(!open_oplock_ipc())
     exit(1);
-#endif /* USE_OPLOCKS */
 
   process();
   close_sockets();