more splitting of server.c
[samba.git] / source3 / smbd / server.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Main SMB server routines
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23 #include "trans2.h"
24
25 pstring servicesf = CONFIGFILE;
26 extern pstring debugf;
27 extern pstring sesssetup_user;
28 extern fstring global_myworkgroup;
29 extern pstring global_myname;
30
31 char *InBuffer = NULL;
32 char *OutBuffer = NULL;
33 char *last_inbuf = NULL;
34
35 int am_parent = 1;
36
37 /* the last message the was processed */
38 int last_message = -1;
39
40 /* a useful macro to debug the last message processed */
41 #define LAST_MESSAGE() smb_fn_name(last_message)
42
43 extern pstring scope;
44 extern int DEBUGLEVEL;
45 extern int case_default;
46 extern BOOL case_sensitive;
47 extern BOOL case_preserve;
48 extern BOOL use_mangled_map;
49 extern BOOL short_case_preserve;
50 extern BOOL case_mangle;
51 time_t smb_last_time=(time_t)0;
52 extern BOOL global_machine_pasword_needs_changing;
53
54 extern int smb_read_error;
55
56 extern pstring user_socket_options;
57
58 #ifdef WITH_DFS
59 extern int dcelogin_atmost_once;
60 #endif /* WITH_DFS */
61
62 /*
63  * This is set on startup - it defines the SID for this
64  * machine.
65  */
66 extern DOM_SID global_machine_sid;
67
68 /* 
69  * Size of data we can send to client. Set
70  *  by the client for all protocols above CORE.
71  *  Set by us for CORE protocol.
72  */
73 int max_send = BUFFER_SIZE;
74 /*
75  * Size of the data we can receive. Set by us.
76  * Can be modified by the max xmit parameter.
77  */
78 int max_recv = BUFFER_SIZE;
79
80 /* Oplock ipc UDP socket. */
81 int oplock_sock = -1;
82 uint16 oplock_port = 0;
83 /* Current number of oplocks we have outstanding. */
84 int32 global_oplocks_open = 0;
85
86 BOOL global_oplock_break = False;
87
88 extern fstring remote_machine;
89
90 extern pstring OriginalDir;
91
92 /* these can be set by some functions to override the error codes */
93 int unix_ERR_class=SMB_SUCCESS;
94 int unix_ERR_code=0;
95
96
97 extern int extra_time_offset;
98
99 extern pstring myhostname;
100
101 /****************************************************************************
102   when exiting, take the whole family
103 ****************************************************************************/
104 void  *dflt_sig(void)
105 {
106   exit_server("caught signal");
107   return 0; /* Keep -Wall happy :-) */
108 }
109 /****************************************************************************
110   Send a SIGTERM to our process group.
111 *****************************************************************************/
112 void  killkids(void)
113 {
114   if(am_parent) kill(0,SIGTERM);
115 }
116
117 /*******************************************************************
118 Wrapper around sys_utime that possibly allows DOS semantics rather
119 than POSIX.
120 *******************************************************************/
121 int file_utime(connection_struct *conn, char *fname, struct utimbuf *times)
122 {
123   extern struct current_user current_user;
124   struct stat sb;
125   int ret = -1;
126
127   errno = 0;
128
129   if(sys_utime(fname, times) == 0)
130     return 0;
131
132   if((errno != EPERM) && (errno != EACCES))
133     return -1;
134
135   if(!lp_dos_filetimes(SNUM(conn)))
136     return -1;
137
138   /* We have permission (given by the Samba admin) to
139      break POSIX semantics and allow a user to change
140      the time on a file they don't own but can write to
141      (as DOS does).
142    */
143
144   if(sys_stat(fname,&sb) != 0)
145     return -1;
146
147   /* Check if we have write access. */
148   if (CAN_WRITE(conn)) {
149           if (((sb.st_mode & S_IWOTH) ||
150                conn->admin_user ||
151                ((sb.st_mode & S_IWUSR) && current_user.uid==sb.st_uid) ||
152                ((sb.st_mode & S_IWGRP) &&
153                 in_group(sb.st_gid,current_user.gid,
154                          current_user.ngroups,current_user.groups)))) {
155                   /* We are allowed to become root and change the filetime. */
156                   become_root(False);
157                   ret = sys_utime(fname, times);
158                   unbecome_root(False);
159           }
160   }
161
162   return ret;
163 }
164   
165 /*******************************************************************
166 Change a filetime - possibly allowing DOS semantics.
167 *******************************************************************/
168 BOOL set_filetime(connection_struct *conn, char *fname, time_t mtime)
169 {
170   struct utimbuf times;
171
172   if (null_mtime(mtime)) return(True);
173
174   times.modtime = times.actime = mtime;
175
176   if (file_utime(conn, fname, &times)) {
177     DEBUG(4,("set_filetime(%s) failed: %s\n",fname,strerror(errno)));
178   }
179   
180   return(True);
181
182
183
184 /****************************************************************************
185 fd support routines - attempt to do a sys_open
186 ****************************************************************************/
187 static int fd_attempt_open(char *fname, int flags, int mode)
188 {
189   int fd = sys_open(fname,flags,mode);
190
191   /* Fix for files ending in '.' */
192   if((fd == -1) && (errno == ENOENT) &&
193      (strchr(fname,'.')==NULL))
194     {
195       pstrcat(fname,".");
196       fd = sys_open(fname,flags,mode);
197     }
198
199 #if (defined(ENAMETOOLONG) && defined(HAVE_PATHCONF))
200   if ((fd == -1) && (errno == ENAMETOOLONG))
201     {
202       int max_len;
203       char *p = strrchr(fname, '/');
204
205       if (p == fname)   /* name is "/xxx" */
206         {
207           max_len = pathconf("/", _PC_NAME_MAX);
208           p++;
209         }
210       else if ((p == NULL) || (p == fname))
211         {
212           p = fname;
213           max_len = pathconf(".", _PC_NAME_MAX);
214         }
215       else
216         {
217           *p = '\0';
218           max_len = pathconf(fname, _PC_NAME_MAX);
219           *p = '/';
220           p++;
221         }
222       if (strlen(p) > max_len)
223         {
224           char tmp = p[max_len];
225
226           p[max_len] = '\0';
227           if ((fd = sys_open(fname,flags,mode)) == -1)
228             p[max_len] = tmp;
229         }
230     }
231 #endif
232   return fd;
233 }
234
235 /****************************************************************************
236 Cache a uid_t currently with this file open. This is an optimization only
237 used when multiple sessionsetup's have been done to one smbd.
238 ****************************************************************************/
239 void fd_add_to_uid_cache(file_fd_struct *fd_ptr, uid_t u)
240 {
241   if(fd_ptr->uid_cache_count >= sizeof(fd_ptr->uid_users_cache)/sizeof(uid_t))
242     return;
243   fd_ptr->uid_users_cache[fd_ptr->uid_cache_count++] = u;
244 }
245
246 /****************************************************************************
247 Remove a uid_t that currently has this file open. This is an optimization only
248 used when multiple sessionsetup's have been done to one smbd.
249 ****************************************************************************/
250 static void fd_remove_from_uid_cache(file_fd_struct *fd_ptr, uid_t u)
251 {
252   int i;
253   for(i = 0; i < fd_ptr->uid_cache_count; i++)
254     if(fd_ptr->uid_users_cache[i] == u) {
255       if(i < (fd_ptr->uid_cache_count-1))
256         memmove((char *)&fd_ptr->uid_users_cache[i], (char *)&fd_ptr->uid_users_cache[i+1],
257                sizeof(uid_t)*(fd_ptr->uid_cache_count-1-i) );
258       fd_ptr->uid_cache_count--;
259     }
260   return;
261 }
262
263 /****************************************************************************
264 Check if a uid_t that currently has this file open is present. This is an
265 optimization only used when multiple sessionsetup's have been done to one smbd.
266 ****************************************************************************/
267 static BOOL fd_is_in_uid_cache(file_fd_struct *fd_ptr, uid_t u)
268 {
269   int i;
270   for(i = 0; i < fd_ptr->uid_cache_count; i++)
271     if(fd_ptr->uid_users_cache[i] == u)
272       return True;
273   return False;
274 }
275
276
277 /****************************************************************************
278 fd support routines - attempt to re-open an already open fd as O_RDWR.
279 Save the already open fd (we cannot close due to POSIX file locking braindamage.
280 ****************************************************************************/
281 static void fd_attempt_reopen(char *fname, int mode, file_fd_struct *fd_ptr)
282 {
283   int fd = sys_open( fname, O_RDWR, mode);
284
285   if(fd == -1)
286     return;
287
288   if(fd_ptr->real_open_flags == O_RDONLY)
289     fd_ptr->fd_readonly = fd_ptr->fd;
290   if(fd_ptr->real_open_flags == O_WRONLY)
291     fd_ptr->fd_writeonly = fd_ptr->fd;
292
293   fd_ptr->fd = fd;
294   fd_ptr->real_open_flags = O_RDWR;
295 }
296
297 /****************************************************************************
298 fd support routines - attempt to close the file referenced by this fd.
299 Decrements the ref_count and returns it.
300 ****************************************************************************/
301 static int fd_attempt_close(file_fd_struct *fd_ptr)
302 {
303   extern struct current_user current_user;
304
305   DEBUG(3,("fd_attempt_close fd = %d, dev = %x, inode = %x, open_flags = %d, ref_count = %d.\n",
306           fd_ptr->fd, fd_ptr->dev, fd_ptr->inode,
307           fd_ptr->real_open_flags,
308           fd_ptr->ref_count));
309   if(fd_ptr->ref_count > 0) {
310     fd_ptr->ref_count--;
311     if(fd_ptr->ref_count == 0) {
312       if(fd_ptr->fd != -1)
313         close(fd_ptr->fd);
314       if(fd_ptr->fd_readonly != -1)
315         close(fd_ptr->fd_readonly);
316       if(fd_ptr->fd_writeonly != -1)
317         close(fd_ptr->fd_writeonly);
318       fd_ptr->fd = -1;
319       fd_ptr->fd_readonly = -1;
320       fd_ptr->fd_writeonly = -1;
321       fd_ptr->real_open_flags = -1;
322       fd_ptr->dev = (uint32)-1;
323       fd_ptr->inode = (uint32)-1;
324       fd_ptr->uid_cache_count = 0;
325     } else {
326       fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
327     }
328   } 
329  return fd_ptr->ref_count;
330 }
331
332 /****************************************************************************
333 fd support routines - check that current user has permissions
334 to open this file. Used when uid not found in optimization cache.
335 This is really ugly code, as due to POSIX locking braindamage we must
336 fork and then attempt to open the file, and return success or failure
337 via an exit code.
338 ****************************************************************************/
339 static BOOL check_access_allowed_for_current_user( char *fname, int accmode )
340 {
341   pid_t child_pid;
342
343   if((child_pid = fork()) < 0) {
344     DEBUG(0,("check_access_allowed_for_current_user: fork failed.\n"));
345     return False;
346   }
347
348   if(child_pid) {
349     /*
350      * Parent.
351      */
352     pid_t wpid;
353     int status_code;
354     if ((wpid = sys_waitpid(child_pid, &status_code, 0)) < 0) {
355       DEBUG(0,("check_access_allowed_for_current_user: The process is no longer waiting!\n"));
356       return(False);
357     }
358
359     if (child_pid != wpid) {
360       DEBUG(0,("check_access_allowed_for_current_user: We were waiting for the wrong process ID\n"));
361       return(False);
362     }
363 #if defined(WIFEXITED) && defined(WEXITSTATUS)
364     if (WIFEXITED(status_code) == 0) {
365       DEBUG(0,("check_access_allowed_for_current_user: The process exited while we were waiting\n"));
366       return(False);
367     }
368     if (WEXITSTATUS(status_code) != 0) {
369       DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access denied.\n", status_code));
370       return(False);
371     }
372 #else /* defined(WIFEXITED) && defined(WEXITSTATUS) */
373     if(status_code != 0) {
374       DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access denied.\n", status_code));
375       return(False);
376     }
377 #endif /* defined(WIFEXITED) && defined(WEXITSTATUS) */
378
379     /*
380      * Success - the child could open the file.
381      */
382     DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access allowed.\n", status_code));
383     return True;
384   } else {
385     /*
386      * Child.
387      */
388     int fd;
389     DEBUG(9,("check_access_allowed_for_current_user: Child - attempting to open %s with mode %d.\n", fname, accmode ));
390     if((fd = fd_attempt_open( fname, accmode, 0)) < 0) {
391       /* Access denied. */
392       _exit(EACCES);
393     }
394     close(fd);
395     DEBUG(9,("check_access_allowed_for_current_user: Child - returning ok.\n"));
396     _exit(0);
397   }
398
399   return False;
400 }
401
402 /****************************************************************************
403 check a filename for the pipe string
404 ****************************************************************************/
405 static void check_for_pipe(char *fname)
406 {
407         /* special case of pipe opens */
408         char s[10];
409         StrnCpy(s,fname,9);
410         strlower(s);
411         if (strstr(s,"pipe/")) {
412                 DEBUG(3,("Rejecting named pipe open for %s\n",fname));
413                 unix_ERR_class = ERRSRV;
414                 unix_ERR_code = ERRaccess;
415         }
416 }
417
418 /****************************************************************************
419 open a file
420 ****************************************************************************/
421 static void open_file(files_struct *fsp,connection_struct *conn,
422                       char *fname1,int flags,int mode, struct stat *sbuf)
423 {
424   extern struct current_user current_user;
425   pstring fname;
426   struct stat statbuf;
427   file_fd_struct *fd_ptr;
428   int accmode = (flags & (O_RDONLY | O_WRONLY | O_RDWR));
429
430   fsp->open = False;
431   fsp->fd_ptr = 0;
432   fsp->granted_oplock = False;
433   errno = EPERM;
434
435   pstrcpy(fname,fname1);
436
437   /* check permissions */
438
439   /*
440    * This code was changed after seeing a client open request 
441    * containing the open mode of (DENY_WRITE/read-only) with
442    * the 'create if not exist' bit set. The previous code
443    * would fail to open the file read only on a read-only share
444    * as it was checking the flags parameter  directly against O_RDONLY,
445    * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
446    * JRA.
447    */
448
449   if (conn->read_only && !conn->printer) {
450     /* It's a read-only share - fail if we wanted to write. */
451     if(accmode != O_RDONLY) {
452       DEBUG(3,("Permission denied opening %s\n",fname));
453       check_for_pipe(fname);
454       return;
455     } else if(flags & O_CREAT) {
456       /* We don't want to write - but we must make sure that O_CREAT
457          doesn't create the file if we have write access into the
458          directory.
459        */
460       flags &= ~O_CREAT;
461     }
462   }
463
464   /* this handles a bug in Win95 - it doesn't say to create the file when it 
465      should */
466   if (conn->printer) {
467           flags |= O_CREAT;
468   }
469
470 /*
471   if (flags == O_WRONLY)
472     DEBUG(3,("Bug in client? Set O_WRONLY without O_CREAT\n"));
473 */
474
475   /*
476    * Ensure we have a valid struct stat so we can search the
477    * open fd table.
478    */
479   if(sbuf == 0) {
480     if(sys_stat(fname, &statbuf) < 0) {
481       if(errno != ENOENT) {
482         DEBUG(3,("Error doing stat on file %s (%s)\n",
483                  fname,strerror(errno)));
484
485         check_for_pipe(fname);
486         return;
487       }
488       sbuf = 0;
489     } else {
490       sbuf = &statbuf;
491     }
492   }
493
494   /*
495    * Check to see if we have this file already
496    * open. If we do, just use the already open fd and increment the
497    * reference count (fd_get_already_open increments the ref_count).
498    */
499   if((fd_ptr = fd_get_already_open(sbuf))!= 0) {
500     /*
501      * File was already open.
502      */
503
504     /* 
505      * Check it wasn't open for exclusive use.
506      */
507     if((flags & O_CREAT) && (flags & O_EXCL)) {
508       fd_ptr->ref_count--;
509       errno = EEXIST;
510       return;
511     }
512
513     /*
514      * Ensure that the user attempting to open
515      * this file has permissions to do so, if
516      * the user who originally opened the file wasn't
517      * the same as the current user.
518      */
519
520     if(!fd_is_in_uid_cache(fd_ptr, (uid_t)current_user.uid)) {
521       if(!check_access_allowed_for_current_user( fname, accmode )) {
522         /* Error - permission denied. */
523         DEBUG(3,("Permission denied opening file %s (flags=%d, accmode = %d)\n",
524               fname, flags, accmode));
525         /* Ensure the ref_count is decremented. */
526         fd_ptr->ref_count--;
527         fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
528         errno = EACCES;
529         return;
530       }
531     }
532
533     fd_add_to_uid_cache(fd_ptr, (uid_t)current_user.uid);
534
535     /* 
536      * If not opened O_RDWR try
537      * and do that here - a chmod may have been done
538      * between the last open and now. 
539      */
540     if(fd_ptr->real_open_flags != O_RDWR)
541       fd_attempt_reopen(fname, mode, fd_ptr);
542
543     /*
544      * Ensure that if we wanted write access
545      * it has been opened for write, and if we wanted read it
546      * was open for read. 
547      */
548     if(((accmode == O_WRONLY) && (fd_ptr->real_open_flags == O_RDONLY)) ||
549        ((accmode == O_RDONLY) && (fd_ptr->real_open_flags == O_WRONLY)) ||
550        ((accmode == O_RDWR) && (fd_ptr->real_open_flags != O_RDWR))) {
551       DEBUG(3,("Error opening (already open for flags=%d) file %s (%s) (flags=%d)\n",
552                fd_ptr->real_open_flags, fname,strerror(EACCES),flags));
553       check_for_pipe(fname);
554       fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
555       fd_ptr->ref_count--;
556       return;
557     }
558
559   } else {
560     int open_flags;
561     /* We need to allocate a new file_fd_struct (this increments the
562        ref_count). */
563     if((fd_ptr = fd_get_new()) == 0)
564       return;
565     /*
566      * Whatever the requested flags, attempt read/write access,
567      * as we don't know what flags future file opens may require.
568      * If this fails, try again with the required flags. 
569      * Even if we open read/write when only read access was 
570      * requested the setting of the can_write flag in
571      * the file_struct will protect us from errant
572      * write requests. We never need to worry about O_APPEND
573      * as this is not set anywhere in Samba.
574      */
575     fd_ptr->real_open_flags = O_RDWR;
576     /* Set the flags as needed without the read/write modes. */
577     open_flags = flags & ~(O_RDWR|O_WRONLY|O_RDONLY);
578     fd_ptr->fd = fd_attempt_open(fname, open_flags|O_RDWR, mode);
579     /*
580      * On some systems opening a file for R/W access on a read only
581      * filesystems sets errno to EROFS.
582      */
583 #ifdef EROFS
584     if((fd_ptr->fd == -1) && ((errno == EACCES) || (errno == EROFS))) {
585 #else /* No EROFS */
586     if((fd_ptr->fd == -1) && (errno == EACCES)) {
587 #endif /* EROFS */
588       if(accmode != O_RDWR) {
589         fd_ptr->fd = fd_attempt_open(fname, open_flags|accmode, mode);
590         fd_ptr->real_open_flags = accmode;
591       }
592     }
593   }
594
595   if ((fd_ptr->fd >=0) && 
596       conn->printer && lp_minprintspace(SNUM(conn))) {
597     pstring dname;
598     int dum1,dum2,dum3;
599     char *p;
600     pstrcpy(dname,fname);
601     p = strrchr(dname,'/');
602     if (p) *p = 0;
603     if (sys_disk_free(dname,&dum1,&dum2,&dum3) < 
604         lp_minprintspace(SNUM(conn))) {
605       fd_attempt_close(fd_ptr);
606       fsp->fd_ptr = 0;
607       if(fd_ptr->ref_count == 0)
608         sys_unlink(fname);
609       errno = ENOSPC;
610       return;
611     }
612   }
613     
614   if (fd_ptr->fd < 0)
615   {
616     DEBUG(3,("Error opening file %s (%s) (flags=%d)\n",
617       fname,strerror(errno),flags));
618     /* Ensure the ref_count is decremented. */
619     fd_attempt_close(fd_ptr);
620     check_for_pipe(fname);
621     return;
622   }
623
624   if (fd_ptr->fd >= 0)
625   {
626     if(sbuf == 0) {
627       /* Do the fstat */
628       if(fstat(fd_ptr->fd, &statbuf) == -1) {
629         /* Error - backout !! */
630         DEBUG(3,("Error doing fstat on fd %d, file %s (%s)\n",
631                  fd_ptr->fd, fname,strerror(errno)));
632         /* Ensure the ref_count is decremented. */
633         fd_attempt_close(fd_ptr);
634         return;
635       }
636       sbuf = &statbuf;
637     }
638
639     /* Set the correct entries in fd_ptr. */
640     fd_ptr->dev = (uint32)sbuf->st_dev;
641     fd_ptr->inode = (uint32)sbuf->st_ino;
642
643     fsp->fd_ptr = fd_ptr;
644     conn->num_files_open++;
645     fsp->mode = sbuf->st_mode;
646     GetTimeOfDay(&fsp->open_time);
647     fsp->vuid = current_user.vuid;
648     fsp->size = 0;
649     fsp->pos = -1;
650     fsp->open = True;
651     fsp->mmap_ptr = NULL;
652     fsp->mmap_size = 0;
653     fsp->can_lock = True;
654     fsp->can_read = ((flags & O_WRONLY)==0);
655     fsp->can_write = ((flags & (O_WRONLY|O_RDWR))!=0);
656     fsp->share_mode = 0;
657     fsp->print_file = conn->printer;
658     fsp->modified = False;
659     fsp->granted_oplock = False;
660     fsp->sent_oplock_break = False;
661     fsp->is_directory = False;
662     fsp->conn = conn;
663     /*
664      * Note that the file name here is the *untranslated* name
665      * ie. it is still in the DOS codepage sent from the client.
666      * All use of this filename will pass though the sys_xxxx
667      * functions which will do the dos_to_unix translation before
668      * mapping into a UNIX filename. JRA.
669      */
670     string_set(&fsp->fsp_name,fname);
671     fsp->wbmpx_ptr = NULL;      
672
673     /*
674      * If the printer is marked as postscript output a leading
675      * file identifier to ensure the file is treated as a raw
676      * postscript file.
677      * This has a similar effect as CtrlD=0 in WIN.INI file.
678      * tim@fsg.com 09/06/94
679      */
680     if (fsp->print_file && lp_postscript(SNUM(conn)) && fsp->can_write) {
681             DEBUG(3,("Writing postscript line\n"));
682             write_file(fsp,"%!\n",3);
683     }
684       
685     DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
686              *sesssetup_user ? sesssetup_user : conn->user,fname,
687              BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
688              conn->num_files_open));
689
690   }
691
692 #if WITH_MMAP
693   /* mmap it if read-only */
694   if (!fsp->can_write) {
695           fsp->mmap_size = file_size(fname);
696           fsp->mmap_ptr = (char *)mmap(NULL,fsp->mmap_size,
697                                        PROT_READ,MAP_SHARED,fsp->fd_ptr->fd,0);
698
699           if (fsp->mmap_ptr == (char *)-1 || !fsp->mmap_ptr) {
700                   DEBUG(3,("Failed to mmap() %s - %s\n",
701                            fname,strerror(errno)));
702                   fsp->mmap_ptr = NULL;
703           }
704   }
705 #endif
706 }
707
708 /****************************************************************************
709 run a file if it is a magic script
710 ****************************************************************************/
711 static void check_magic(files_struct *fsp,connection_struct *conn)
712 {
713   if (!*lp_magicscript(SNUM(conn)))
714     return;
715
716   DEBUG(5,("checking magic for %s\n",fsp->fsp_name));
717
718   {
719     char *p;
720     if (!(p = strrchr(fsp->fsp_name,'/')))
721       p = fsp->fsp_name;
722     else
723       p++;
724
725     if (!strequal(lp_magicscript(SNUM(conn)),p))
726       return;
727   }
728
729   {
730     int ret;
731     pstring magic_output;
732     pstring fname;
733     pstrcpy(fname,fsp->fsp_name);
734
735     if (*lp_magicoutput(SNUM(conn)))
736       pstrcpy(magic_output,lp_magicoutput(SNUM(conn)));
737     else
738       slprintf(magic_output,sizeof(fname)-1, "%s.out",fname);
739
740     chmod(fname,0755);
741     ret = smbrun(fname,magic_output,False);
742     DEBUG(3,("Invoking magic command %s gave %d\n",fname,ret));
743     unlink(fname);
744   }
745 }
746
747 /****************************************************************************
748   Common code to close a file or a directory.
749 ****************************************************************************/
750 static void close_filestruct(files_struct *fsp)
751 {   
752         connection_struct *conn = fsp->conn;
753     
754         fsp->open = False;
755         fsp->is_directory = False; 
756     
757         conn->num_files_open--;
758         if(fsp->wbmpx_ptr) {  
759                 free((char *)fsp->wbmpx_ptr);
760                 fsp->wbmpx_ptr = NULL; 
761         }  
762      
763 #if WITH_MMAP
764         if(fsp->mmap_ptr) {
765                 munmap(fsp->mmap_ptr,fsp->mmap_size);
766                 fsp->mmap_ptr = NULL;
767         }  
768 #endif 
769 }    
770
771 /****************************************************************************
772  Close a file - possibly invalidating the read prediction.
773
774  If normal_close is 1 then this came from a normal SMBclose (or equivalent)
775  operation otherwise it came as the result of some other operation such as
776  the closing of the connection. In the latter case printing and
777  magic scripts are not run.
778 ****************************************************************************/
779 void close_file(files_struct *fsp, BOOL normal_close)
780 {
781         uint32 dev = fsp->fd_ptr->dev;
782         uint32 inode = fsp->fd_ptr->inode;
783         int token;
784         connection_struct *conn = fsp->conn;
785
786         close_filestruct(fsp);
787
788 #if USE_READ_PREDICTION
789         invalidate_read_prediction(fsp->fd_ptr->fd);
790 #endif
791
792         if (lp_share_modes(SNUM(conn))) {
793                 lock_share_entry(conn, dev, inode, &token);
794                 del_share_mode(token, fsp);
795         }
796
797         fd_attempt_close(fsp->fd_ptr);
798
799         if (lp_share_modes(SNUM(conn)))
800                 unlock_share_entry(conn, dev, inode, token);
801
802         /* NT uses smbclose to start a print - weird */
803         if (normal_close && fsp->print_file)
804                 print_file(conn, fsp);
805
806         /* check for magic scripts */
807         if (normal_close) {
808                 check_magic(fsp,conn);
809         }
810
811         if(fsp->granted_oplock == True)
812                 global_oplocks_open--;
813
814         fsp->sent_oplock_break = False;
815
816         DEBUG(2,("%s closed file %s (numopen=%d)\n",
817                  conn->user,fsp->fsp_name,
818                  conn->num_files_open));
819
820         if (fsp->fsp_name) {
821                 string_free(&fsp->fsp_name);
822         }
823
824         file_free(fsp);
825 }
826
827 /****************************************************************************
828  Close a directory opened by an NT SMB call. 
829 ****************************************************************************/
830   
831 void close_directory(files_struct *fsp)
832 {
833         /* TODO - walk the list of pending
834            change notify requests and free
835            any pertaining to this fsp. */
836
837         remove_pending_change_notify_requests_by_fid(fsp);
838
839         /*
840          * Do the code common to files and directories.
841          */
842         close_filestruct(fsp);
843         
844         if (fsp->fsp_name)
845                 string_free(&fsp->fsp_name);
846         
847         file_free(fsp);
848 }
849
850 /****************************************************************************
851  Open a directory from an NT SMB call.
852 ****************************************************************************/
853 int open_directory(files_struct *fsp,connection_struct *conn,
854                    char *fname, int smb_ofun, int unixmode, int *action)
855 {
856         extern struct current_user current_user;
857         struct stat st;
858
859         if (smb_ofun & 0x10) {
860                 /*
861                  * Create the directory.
862                  */
863
864                 if(sys_mkdir(fname, unixmode) < 0) {
865                         DEBUG(0,("open_directory: unable to create %s. Error was %s\n",
866                                  fname, strerror(errno) ));
867                         return -1;
868                 }
869
870                 *action = FILE_WAS_CREATED;
871         } else {
872                 /*
873                  * Check that it *was* a directory.
874                  */
875
876                 if(sys_stat(fname, &st) < 0) {
877                         DEBUG(0,("open_directory: unable to stat name = %s. Error was %s\n",
878                                  fname, strerror(errno) ));
879                         return -1;
880                 }
881
882                 if(!S_ISDIR(st.st_mode)) {
883                         DEBUG(0,("open_directory: %s is not a directory !\n", fname ));
884                         return -1;
885                 }
886                 *action = FILE_WAS_OPENED;
887         }
888         
889         DEBUG(5,("open_directory: opening directory %s\n",
890                  fname));
891
892         /*
893          * Setup the files_struct for it.
894          */
895         
896         fsp->fd_ptr = NULL;
897         conn->num_files_open++;
898         fsp->mode = 0;
899         GetTimeOfDay(&fsp->open_time);
900         fsp->vuid = current_user.vuid;
901         fsp->size = 0;
902         fsp->pos = -1;
903         fsp->open = True;
904         fsp->mmap_ptr = NULL;
905         fsp->mmap_size = 0;
906         fsp->can_lock = True;
907         fsp->can_read = False;
908         fsp->can_write = False;
909         fsp->share_mode = 0;
910         fsp->print_file = False;
911         fsp->modified = False;
912         fsp->granted_oplock = False;
913         fsp->sent_oplock_break = False;
914         fsp->is_directory = True;
915         fsp->conn = conn;
916         /*
917          * Note that the file name here is the *untranslated* name
918          * ie. it is still in the DOS codepage sent from the client.
919          * All use of this filename will pass though the sys_xxxx
920          * functions which will do the dos_to_unix translation before
921          * mapping into a UNIX filename. JRA.
922          */
923         string_set(&fsp->fsp_name,fname);
924         fsp->wbmpx_ptr = NULL;
925
926         return 0;
927 }
928
929 enum {AFAIL,AREAD,AWRITE,AALL};
930
931 /*******************************************************************
932 reproduce the share mode access table
933 ********************************************************************/
934 static int access_table(int new_deny,int old_deny,int old_mode,
935                         int share_pid,char *fname)
936 {
937   if (new_deny == DENY_ALL || old_deny == DENY_ALL) return(AFAIL);
938
939   if (new_deny == DENY_DOS || old_deny == DENY_DOS) {
940     int pid = getpid();
941     if (old_deny == new_deny && share_pid == pid) 
942         return(AALL);    
943
944     if (old_mode == 0) return(AREAD);
945
946     /* the new smbpub.zip spec says that if the file extension is
947        .com, .dll, .exe or .sym then allow the open. I will force
948        it to read-only as this seems sensible although the spec is
949        a little unclear on this. */
950     if ((fname = strrchr(fname,'.'))) {
951       if (strequal(fname,".com") ||
952           strequal(fname,".dll") ||
953           strequal(fname,".exe") ||
954           strequal(fname,".sym"))
955         return(AREAD);
956     }
957
958     return(AFAIL);
959   }
960
961   switch (new_deny) 
962     {
963     case DENY_WRITE:
964       if (old_deny==DENY_WRITE && old_mode==0) return(AREAD);
965       if (old_deny==DENY_READ && old_mode==0) return(AWRITE);
966       if (old_deny==DENY_NONE && old_mode==0) return(AALL);
967       return(AFAIL);
968     case DENY_READ:
969       if (old_deny==DENY_WRITE && old_mode==1) return(AREAD);
970       if (old_deny==DENY_READ && old_mode==1) return(AWRITE);
971       if (old_deny==DENY_NONE && old_mode==1) return(AALL);
972       return(AFAIL);
973     case DENY_NONE:
974       if (old_deny==DENY_WRITE) return(AREAD);
975       if (old_deny==DENY_READ) return(AWRITE);
976       if (old_deny==DENY_NONE) return(AALL);
977       return(AFAIL);      
978     }
979   return(AFAIL);      
980 }
981
982 /*******************************************************************
983 check if the share mode on a file allows it to be deleted or unlinked
984 return True if sharing doesn't prevent the operation
985 ********************************************************************/
986 BOOL check_file_sharing(connection_struct *conn,char *fname, BOOL rename_op)
987 {
988   int i;
989   int ret = False;
990   share_mode_entry *old_shares = 0;
991   int num_share_modes;
992   struct stat sbuf;
993   int token;
994   int pid = getpid();
995   uint32 dev, inode;
996
997   if(!lp_share_modes(SNUM(conn)))
998     return True;
999
1000   if (sys_stat(fname,&sbuf) == -1) return(True);
1001
1002   dev = (uint32)sbuf.st_dev;
1003   inode = (uint32)sbuf.st_ino;
1004
1005   lock_share_entry(conn, dev, inode, &token);
1006   num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1007
1008   /*
1009    * Check if the share modes will give us access.
1010    */
1011
1012   if(num_share_modes != 0)
1013   {
1014     BOOL broke_oplock;
1015
1016     do
1017     {
1018
1019       broke_oplock = False;
1020       for(i = 0; i < num_share_modes; i++)
1021       {
1022         share_mode_entry *share_entry = &old_shares[i];
1023
1024         /* 
1025          * Break oplocks before checking share modes. See comment in
1026          * open_file_shared for details. 
1027          * Check if someone has an oplock on this file. If so we must 
1028          * break it before continuing. 
1029          */
1030         if(share_entry->op_type & BATCH_OPLOCK)
1031         {
1032
1033           /*
1034            * It appears that the NT redirector may have a bug, in that
1035            * it tries to do an SMBmv on a file that it has open with a
1036            * batch oplock, and then fails to respond to the oplock break
1037            * request. This only seems to occur when the client is doing an
1038            * SMBmv to the smbd it is using - thus we try and detect this
1039            * condition by checking if the file being moved is open and oplocked by
1040            * this smbd process, and then not sending the oplock break in this
1041            * special case. If the file was open with a deny mode that 
1042            * prevents the move the SMBmv will fail anyway with a share
1043            * violation error. JRA.
1044            */
1045           if(rename_op && (share_entry->pid == pid))
1046           {
1047             DEBUG(0,("check_file_sharing: NT redirector workaround - rename attempted on \
1048 batch oplocked file %s, dev = %x, inode = %x\n", fname, dev, inode));
1049             /* 
1050              * This next line is a test that allows the deny-mode
1051              * processing to be skipped. This seems to be needed as
1052              * NT insists on the rename succeeding (in Office 9x no less !).
1053              * This should be removed as soon as (a) MS fix the redirector
1054              * bug or (b) NT SMB support in Samba makes NT not issue the
1055              * call (as is my fervent hope). JRA.
1056              */ 
1057             continue;
1058           }
1059           else
1060           {
1061             DEBUG(5,("check_file_sharing: breaking oplock (%x) on file %s, \
1062 dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
1063
1064             /* Oplock break.... */
1065             unlock_share_entry(conn, dev, inode, token);
1066             if(request_oplock_break(share_entry, dev, inode) == False)
1067             {
1068               free((char *)old_shares);
1069               DEBUG(0,("check_file_sharing: FAILED when breaking oplock (%x) on file %s, \
1070 dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
1071               return False;
1072             }
1073             lock_share_entry(conn, dev, inode, &token);
1074             broke_oplock = True;
1075             break;
1076           }
1077         }
1078
1079         /* someone else has a share lock on it, check to see 
1080            if we can too */
1081         if ((share_entry->share_mode != DENY_DOS) || (share_entry->pid != pid))
1082           goto free_and_exit;
1083
1084       } /* end for */
1085
1086       if(broke_oplock)
1087       {
1088         free((char *)old_shares);
1089         num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1090       }
1091     } while(broke_oplock);
1092   }
1093
1094   /* XXXX exactly what share mode combinations should be allowed for
1095      deleting/renaming? */
1096   /* If we got here then either there were no share modes or
1097      all share modes were DENY_DOS and the pid == getpid() */
1098   ret = True;
1099
1100 free_and_exit:
1101
1102   unlock_share_entry(conn, dev, inode, token);
1103   if(old_shares != NULL)
1104     free((char *)old_shares);
1105   return(ret);
1106 }
1107
1108 /****************************************************************************
1109   C. Hoch 11/22/95
1110   Helper for open_file_shared. 
1111   Truncate a file after checking locking; close file if locked.
1112   **************************************************************************/
1113 static void truncate_unless_locked(files_struct *fsp, connection_struct *conn, int token, 
1114                                    BOOL *share_locked)
1115 {
1116   if (fsp->can_write){
1117     if (is_locked(fsp,conn,0x3FFFFFFF,0,F_WRLCK)){
1118       /* If share modes are in force for this connection we
1119          have the share entry locked. Unlock it before closing. */
1120       if (*share_locked && lp_share_modes(SNUM(conn)))
1121         unlock_share_entry( conn, fsp->fd_ptr->dev, 
1122                             fsp->fd_ptr->inode, token);
1123       close_file(fsp,False);   
1124       /* Share mode no longer locked. */
1125       *share_locked = False;
1126       errno = EACCES;
1127       unix_ERR_class = ERRDOS;
1128       unix_ERR_code = ERRlock;
1129     }
1130     else
1131       ftruncate(fsp->fd_ptr->fd,0); 
1132   }
1133 }
1134
1135 /****************************************************************************
1136 check if we can open a file with a share mode
1137 ****************************************************************************/
1138 int check_share_mode( share_mode_entry *share, int deny_mode, char *fname,
1139                       BOOL fcbopen, int *flags)
1140 {
1141   int old_open_mode = share->share_mode &0xF;
1142   int old_deny_mode = (share->share_mode >>4)&7;
1143
1144   if (old_deny_mode > 4 || old_open_mode > 2)
1145   {
1146     DEBUG(0,("Invalid share mode found (%d,%d,%d) on file %s\n",
1147                deny_mode,old_deny_mode,old_open_mode,fname));
1148     return False;
1149   }
1150
1151   {
1152     int access_allowed = access_table(deny_mode,old_deny_mode,old_open_mode,
1153                                 share->pid,fname);
1154
1155     if ((access_allowed == AFAIL) ||
1156         (!fcbopen && (access_allowed == AREAD && *flags == O_RDWR)) ||
1157         (access_allowed == AREAD && *flags == O_WRONLY) ||
1158         (access_allowed == AWRITE && *flags == O_RDONLY))
1159     {
1160       DEBUG(2,("Share violation on file (%d,%d,%d,%d,%s,fcbopen = %d, flags = %d) = %d\n",
1161                 deny_mode,old_deny_mode,old_open_mode,
1162                 share->pid,fname, fcbopen, *flags, access_allowed));
1163       return False;
1164     }
1165
1166     if (access_allowed == AREAD)
1167       *flags = O_RDONLY;
1168
1169     if (access_allowed == AWRITE)
1170       *flags = O_WRONLY;
1171
1172   }
1173   return True;
1174 }
1175
1176 /****************************************************************************
1177 open a file with a share mode
1178 ****************************************************************************/
1179 void open_file_shared(files_struct *fsp,connection_struct *conn,char *fname,int share_mode,int ofun,
1180                       int mode,int oplock_request, int *Access,int *action)
1181 {
1182   int flags=0;
1183   int flags2=0;
1184   int deny_mode = (share_mode>>4)&7;
1185   struct stat sbuf;
1186   BOOL file_existed = file_exist(fname,&sbuf);
1187   BOOL share_locked = False;
1188   BOOL fcbopen = False;
1189   int token;
1190   uint32 dev = 0;
1191   uint32 inode = 0;
1192   int num_share_modes = 0;
1193
1194   fsp->open = False;
1195   fsp->fd_ptr = 0;
1196
1197   /* this is for OS/2 EAs - try and say we don't support them */
1198   if (strstr(fname,".+,;=[].")) 
1199   {
1200     unix_ERR_class = ERRDOS;
1201     /* OS/2 Workplace shell fix may be main code stream in a later release. */ 
1202 #if 1 /* OS2_WPS_FIX - Recent versions of OS/2 need this. */
1203     unix_ERR_code = ERRcannotopen;
1204 #else /* OS2_WPS_FIX */
1205     unix_ERR_code = ERROR_EAS_NOT_SUPPORTED;
1206 #endif /* OS2_WPS_FIX */
1207
1208     return;
1209   }
1210
1211   if ((ofun & 0x3) == 0 && file_existed)  
1212   {
1213     errno = EEXIST;
1214     return;
1215   }
1216       
1217   if (ofun & 0x10)
1218     flags2 |= O_CREAT;
1219   if ((ofun & 0x3) == 2)
1220     flags2 |= O_TRUNC;
1221
1222   /* note that we ignore the append flag as 
1223      append does not mean the same thing under dos and unix */
1224
1225   switch (share_mode&0xF)
1226   {
1227     case 1: 
1228       flags = O_WRONLY; 
1229       break;
1230     case 0xF: 
1231       fcbopen = True;
1232       flags = O_RDWR; 
1233       break;
1234     case 2: 
1235       flags = O_RDWR; 
1236       break;
1237     default:
1238       flags = O_RDONLY;
1239       break;
1240   }
1241
1242 #if defined(O_SYNC)
1243   if (share_mode&(1<<14)) {
1244           flags2 |= O_SYNC;
1245   }
1246 #endif /* O_SYNC */
1247   
1248   if (flags != O_RDONLY && file_existed && 
1249       (!CAN_WRITE(conn) || IS_DOS_READONLY(dos_mode(conn,fname,&sbuf)))) 
1250   {
1251     if (!fcbopen) 
1252     {
1253       errno = EACCES;
1254       return;
1255     }
1256     flags = O_RDONLY;
1257   }
1258
1259   if (deny_mode > DENY_NONE && deny_mode!=DENY_FCB) 
1260   {
1261     DEBUG(2,("Invalid deny mode %d on file %s\n",deny_mode,fname));
1262     errno = EINVAL;
1263     return;
1264   }
1265
1266   if (deny_mode == DENY_FCB) deny_mode = DENY_DOS;
1267
1268   if (lp_share_modes(SNUM(conn))) 
1269   {
1270     int i;
1271     share_mode_entry *old_shares = 0;
1272
1273     if (file_existed)
1274     {
1275       dev = (uint32)sbuf.st_dev;
1276       inode = (uint32)sbuf.st_ino;
1277       lock_share_entry(conn, dev, inode, &token);
1278       share_locked = True;
1279       num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1280     }
1281
1282     /*
1283      * Check if the share modes will give us access.
1284      */
1285
1286     if(share_locked && (num_share_modes != 0))
1287     {
1288       BOOL broke_oplock;
1289
1290       do
1291       {
1292
1293         broke_oplock = False;
1294         for(i = 0; i < num_share_modes; i++)
1295         {
1296           share_mode_entry *share_entry = &old_shares[i];
1297
1298           /* 
1299            * By observation of NetBench, oplocks are broken *before* share
1300            * modes are checked. This allows a file to be closed by the client
1301            * if the share mode would deny access and the client has an oplock. 
1302            * Check if someone has an oplock on this file. If so we must break 
1303            * it before continuing. 
1304            */
1305           if(share_entry->op_type & (EXCLUSIVE_OPLOCK|BATCH_OPLOCK))
1306           {
1307
1308             DEBUG(5,("open_file_shared: breaking oplock (%x) on file %s, \
1309 dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
1310
1311             /* Oplock break.... */
1312             unlock_share_entry(conn, dev, inode, token);
1313             if(request_oplock_break(share_entry, dev, inode) == False)
1314             {
1315               free((char *)old_shares);
1316               DEBUG(0,("open_file_shared: FAILED when breaking oplock (%x) on file %s, \
1317 dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
1318               errno = EACCES;
1319               unix_ERR_class = ERRDOS;
1320               unix_ERR_code = ERRbadshare;
1321               return;
1322             }
1323             lock_share_entry(conn, dev, inode, &token);
1324             broke_oplock = True;
1325             break;
1326           }
1327
1328           /* someone else has a share lock on it, check to see 
1329              if we can too */
1330           if(check_share_mode(share_entry, deny_mode, fname, fcbopen, &flags) == False)
1331           {
1332             free((char *)old_shares);
1333             unlock_share_entry(conn, dev, inode, token);
1334             errno = EACCES;
1335             unix_ERR_class = ERRDOS;
1336             unix_ERR_code = ERRbadshare;
1337             return;
1338           }
1339
1340         } /* end for */
1341
1342         if(broke_oplock)
1343         {
1344           free((char *)old_shares);
1345           num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1346         }
1347       } while(broke_oplock);
1348     }
1349
1350     if(old_shares != 0)
1351       free((char *)old_shares);
1352   }
1353
1354   DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o\n",
1355            flags,flags2,mode));
1356
1357   open_file(fsp,conn,fname,flags|(flags2&~(O_TRUNC)),mode,file_existed ? &sbuf : 0);
1358   if (!fsp->open && flags==O_RDWR && errno!=ENOENT && fcbopen) 
1359   {
1360     flags = O_RDONLY;
1361     open_file(fsp,conn,fname,flags,mode,file_existed ? &sbuf : 0 );
1362   }
1363
1364   if (fsp->open) 
1365   {
1366     int open_mode=0;
1367
1368     if((share_locked == False) && lp_share_modes(SNUM(conn)))
1369     {
1370       /* We created the file - thus we must now lock the share entry before creating it. */
1371       dev = fsp->fd_ptr->dev;
1372       inode = fsp->fd_ptr->inode;
1373       lock_share_entry(conn, dev, inode, &token);
1374       share_locked = True;
1375     }
1376
1377     switch (flags) 
1378     {
1379       case O_RDONLY:
1380         open_mode = 0;
1381         break;
1382       case O_RDWR:
1383         open_mode = 2;
1384         break;
1385       case O_WRONLY:
1386         open_mode = 1;
1387         break;
1388     }
1389
1390     fsp->share_mode = (deny_mode<<4) | open_mode;
1391
1392     if (Access)
1393       (*Access) = open_mode;
1394
1395     if (action) 
1396     {
1397       if (file_existed && !(flags2 & O_TRUNC)) *action = FILE_WAS_OPENED;
1398       if (!file_existed) *action = FILE_WAS_CREATED;
1399       if (file_existed && (flags2 & O_TRUNC)) *action = FILE_WAS_OVERWRITTEN;
1400     }
1401     /* We must create the share mode entry before truncate as
1402        truncate can fail due to locking and have to close the
1403        file (which expects the share_mode_entry to be there).
1404      */
1405     if (lp_share_modes(SNUM(conn)))
1406     {
1407       uint16 port = 0;
1408       /* JRA. Currently this only services Exlcusive and batch
1409          oplocks (no other opens on this file). This needs to
1410          be extended to level II oplocks (multiple reader
1411          oplocks). */
1412
1413       if(oplock_request && (num_share_modes == 0) && lp_oplocks(SNUM(conn)) && 
1414               !IS_VETO_OPLOCK_PATH(conn,fname))
1415       {
1416         fsp->granted_oplock = True;
1417         fsp->sent_oplock_break = False;
1418         global_oplocks_open++;
1419         port = oplock_port;
1420
1421         DEBUG(5,("open_file_shared: granted oplock (%x) on file %s, \
1422 dev = %x, inode = %x\n", oplock_request, fname, dev, inode));
1423
1424       }
1425       else
1426       {
1427         port = 0;
1428         oplock_request = 0;
1429       }
1430       set_share_mode(token, fsp, port, oplock_request);
1431     }
1432
1433     if ((flags2&O_TRUNC) && file_existed)
1434       truncate_unless_locked(fsp,conn,token,&share_locked);
1435   }
1436
1437   if (share_locked && lp_share_modes(SNUM(conn)))
1438     unlock_share_entry( conn, dev, inode, token);
1439 }
1440
1441
1442 /****************************************************************************
1443 load parameters specific to a connection/service
1444 ****************************************************************************/
1445 BOOL become_service(connection_struct *conn,BOOL do_chdir)
1446 {
1447         extern char magic_char;
1448         static connection_struct *last_conn;
1449         int snum;
1450
1451         if (!conn)  {
1452                 last_conn = NULL;
1453                 return(False);
1454         }
1455
1456         conn->lastused = smb_last_time;
1457
1458         snum = SNUM(conn);
1459   
1460         if (do_chdir &&
1461             ChDir(conn->connectpath) != 0 &&
1462             ChDir(conn->origpath) != 0) {
1463                 DEBUG(0,("chdir (%s) failed\n",
1464                          conn->connectpath));
1465                 return(False);
1466         }
1467
1468         if (conn == last_conn)
1469                 return(True);
1470
1471         last_conn = conn;
1472
1473         case_default = lp_defaultcase(snum);
1474         case_preserve = lp_preservecase(snum);
1475         short_case_preserve = lp_shortpreservecase(snum);
1476         case_mangle = lp_casemangle(snum);
1477         case_sensitive = lp_casesensitive(snum);
1478         magic_char = lp_magicchar(snum);
1479         use_mangled_map = (*lp_mangled_map(snum) ? True:False);
1480         return(True);
1481 }
1482
1483
1484 /****************************************************************************
1485   find a service entry
1486 ****************************************************************************/
1487 int find_service(char *service)
1488 {
1489    int iService;
1490
1491    string_sub(service,"\\","/");
1492
1493    iService = lp_servicenumber(service);
1494
1495    /* now handle the special case of a home directory */
1496    if (iService < 0)
1497    {
1498       char *phome_dir = get_home_dir(service);
1499
1500       if(!phome_dir)
1501       {
1502         /*
1503          * Try mapping the servicename, it may
1504          * be a Windows to unix mapped user name.
1505          */
1506         if(map_username(service))
1507           phome_dir = get_home_dir(service);
1508       }
1509
1510       DEBUG(3,("checking for home directory %s gave %s\n",service,
1511             phome_dir?phome_dir:"(NULL)"));
1512
1513       if (phome_dir)
1514       {   
1515         int iHomeService;
1516         if ((iHomeService = lp_servicenumber(HOMES_NAME)) >= 0)
1517         {
1518           lp_add_home(service,iHomeService,phome_dir);
1519           iService = lp_servicenumber(service);
1520         }
1521       }
1522    }
1523
1524    /* If we still don't have a service, attempt to add it as a printer. */
1525    if (iService < 0)
1526    {
1527       int iPrinterService;
1528
1529       if ((iPrinterService = lp_servicenumber(PRINTERS_NAME)) >= 0)
1530       {
1531          char *pszTemp;
1532
1533          DEBUG(3,("checking whether %s is a valid printer name...\n", service));
1534          pszTemp = PRINTCAP;
1535          if ((pszTemp != NULL) && pcap_printername_ok(service, pszTemp))
1536          {
1537             DEBUG(3,("%s is a valid printer name\n", service));
1538             DEBUG(3,("adding %s as a printer service\n", service));
1539             lp_add_printer(service,iPrinterService);
1540             iService = lp_servicenumber(service);
1541             if (iService < 0)
1542                DEBUG(0,("failed to add %s as a printer service!\n", service));
1543          }
1544          else
1545             DEBUG(3,("%s is not a valid printer name\n", service));
1546       }
1547    }
1548
1549    /* just possibly it's a default service? */
1550    if (iService < 0) 
1551    {
1552      char *pdefservice = lp_defaultservice();
1553      if (pdefservice && *pdefservice && !strequal(pdefservice,service))
1554      {
1555        /*
1556         * We need to do a local copy here as lp_defaultservice() 
1557         * returns one of the rotating lp_string buffers that
1558         * could get overwritten by the recursive find_service() call
1559         * below. Fix from Josef Hinteregger <joehtg@joehtg.co.at>.
1560         */
1561        pstring defservice;
1562        pstrcpy(defservice, pdefservice);
1563        iService = find_service(defservice);
1564        if (iService >= 0)
1565        {
1566          string_sub(service,"_","/");
1567          iService = lp_add_service(service,iService);
1568        }
1569      }
1570    }
1571
1572    if (iService >= 0)
1573      if (!VALID_SNUM(iService))
1574      {
1575        DEBUG(0,("Invalid snum %d for %s\n",iService,service));
1576        iService = -1;
1577      }
1578
1579    if (iService < 0)
1580      DEBUG(3,("find_service() failed to find service %s\n", service));
1581
1582    return (iService);
1583 }
1584
1585
1586 /****************************************************************************
1587   create an error packet from a cached error.
1588 ****************************************************************************/
1589 int cached_error_packet(char *inbuf,char *outbuf,files_struct *fsp,int line)
1590 {
1591   write_bmpx_struct *wbmpx = fsp->wbmpx_ptr;
1592
1593   int32 eclass = wbmpx->wr_errclass;
1594   int32 err = wbmpx->wr_error;
1595
1596   /* We can now delete the auxiliary struct */
1597   free((char *)wbmpx);
1598   fsp->wbmpx_ptr = NULL;
1599   return error_packet(inbuf,outbuf,eclass,err,line);
1600 }
1601
1602
1603 struct
1604 {
1605   int unixerror;
1606   int smbclass;
1607   int smbcode;
1608 } unix_smb_errmap[] =
1609 {
1610   {EPERM,ERRDOS,ERRnoaccess},
1611   {EACCES,ERRDOS,ERRnoaccess},
1612   {ENOENT,ERRDOS,ERRbadfile},
1613   {ENOTDIR,ERRDOS,ERRbadpath},
1614   {EIO,ERRHRD,ERRgeneral},
1615   {EBADF,ERRSRV,ERRsrverror},
1616   {EINVAL,ERRSRV,ERRsrverror},
1617   {EEXIST,ERRDOS,ERRfilexists},
1618   {ENFILE,ERRDOS,ERRnofids},
1619   {EMFILE,ERRDOS,ERRnofids},
1620   {ENOSPC,ERRHRD,ERRdiskfull},
1621 #ifdef EDQUOT
1622   {EDQUOT,ERRHRD,ERRdiskfull},
1623 #endif
1624 #ifdef ENOTEMPTY
1625   {ENOTEMPTY,ERRDOS,ERRnoaccess},
1626 #endif
1627 #ifdef EXDEV
1628   {EXDEV,ERRDOS,ERRdiffdevice},
1629 #endif
1630   {EROFS,ERRHRD,ERRnowrite},
1631   {0,0,0}
1632 };
1633
1634 /****************************************************************************
1635   create an error packet from errno
1636 ****************************************************************************/
1637 int unix_error_packet(char *inbuf,char *outbuf,int def_class,uint32 def_code,int line)
1638 {
1639   int eclass=def_class;
1640   int ecode=def_code;
1641   int i=0;
1642
1643   if (unix_ERR_class != SMB_SUCCESS)
1644     {
1645       eclass = unix_ERR_class;
1646       ecode = unix_ERR_code;
1647       unix_ERR_class = SMB_SUCCESS;
1648       unix_ERR_code = 0;
1649     }
1650   else
1651     {
1652       while (unix_smb_errmap[i].smbclass != 0)
1653       {
1654             if (unix_smb_errmap[i].unixerror == errno)
1655             {
1656               eclass = unix_smb_errmap[i].smbclass;
1657               ecode = unix_smb_errmap[i].smbcode;
1658               break;
1659             }
1660           i++;
1661       }
1662     }
1663
1664   return(error_packet(inbuf,outbuf,eclass,ecode,line));
1665 }
1666
1667
1668 /****************************************************************************
1669   create an error packet. Normally called using the ERROR() macro
1670 ****************************************************************************/
1671 int error_packet(char *inbuf,char *outbuf,int error_class,uint32 error_code,int line)
1672 {
1673   int outsize = set_message(outbuf,0,0,True);
1674   int cmd = CVAL(inbuf,smb_com);
1675   int flgs2 = SVAL(outbuf,smb_flg2); 
1676
1677   if ((flgs2 & FLAGS2_32_BIT_ERROR_CODES) == FLAGS2_32_BIT_ERROR_CODES)
1678   {
1679     SIVAL(outbuf,smb_rcls,error_code);
1680     
1681     DEBUG( 3, ( "32 bit error packet at line %d cmd=%d (%s) eclass=%08x [%s]\n",
1682               line, cmd, smb_fn_name(cmd), error_code, smb_errstr(outbuf) ) );
1683   }
1684   else
1685   {
1686     CVAL(outbuf,smb_rcls) = error_class;
1687     SSVAL(outbuf,smb_err,error_code);  
1688     DEBUG( 3, ( "error packet at line %d cmd=%d (%s) eclass=%d ecode=%d\n",
1689               line,
1690               (int)CVAL(inbuf,smb_com),
1691               smb_fn_name(CVAL(inbuf,smb_com)),
1692               error_class,
1693               error_code ) );
1694
1695   }
1696   
1697   if (errno != 0)
1698     DEBUG(3,("error string = %s\n",strerror(errno)));
1699   
1700   return(outsize);
1701 }
1702
1703
1704 /****************************************************************************
1705   this is called when the client exits abruptly
1706   **************************************************************************/
1707 static void sig_pipe(int sig)
1708 {
1709         struct cli_state *cli;
1710         BlockSignals(True,SIGPIPE);
1711
1712         if ((cli = server_client()) && cli->initialised) {
1713                 DEBUG(3,("lost connection to password server\n"));
1714                 cli_shutdown(cli);
1715                 BlockSignals(False,SIGPIPE);
1716                 return;
1717         }
1718
1719         exit_server("Got sigpipe\n");
1720 }
1721
1722 /****************************************************************************
1723   open the socket communication
1724 ****************************************************************************/
1725 static BOOL open_sockets(BOOL is_daemon,int port)
1726 {
1727   extern int Client;
1728
1729   if (is_daemon)
1730   {
1731     int num_interfaces = iface_count();
1732     int fd_listenset[FD_SETSIZE];
1733     fd_set listen_set;
1734     int s;
1735     int i;
1736
1737 #ifdef HAVE_ATEXIT
1738     static int atexit_set;
1739     if(atexit_set == 0) {
1740             atexit_set=1;
1741             atexit(killkids);
1742     }
1743 #endif
1744
1745     /* Stop zombies */
1746     CatchChild();
1747
1748
1749     FD_ZERO(&listen_set);
1750
1751     if(lp_interfaces() && lp_bind_interfaces_only())
1752     {
1753        /* We have been given an interfaces line, and been 
1754           told to only bind to those interfaces. Create a
1755           socket per interface and bind to only these.
1756         */
1757
1758       if(num_interfaces > FD_SETSIZE)
1759       {
1760         DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
1761 max can be %d\n", num_interfaces, FD_SETSIZE));
1762         return False;
1763       }
1764
1765       /* Now open a listen socket for each of the interfaces. */
1766       for(i = 0; i < num_interfaces; i++)
1767       {
1768         struct in_addr *ifip = iface_n_ip(i);
1769
1770         if(ifip == NULL)
1771         {
1772           DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
1773           continue;
1774         }
1775         s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr);
1776         if(s == -1)
1777           return False;
1778         /* ready to listen */
1779         if (listen(s, 5) == -1) 
1780         {
1781           DEBUG(0,("listen: %s\n",strerror(errno)));
1782           close(s);
1783           return False;
1784         }
1785         FD_SET(s,&listen_set);
1786       }
1787     }
1788     else
1789     {
1790       /* Just bind to 0.0.0.0 - accept connections from anywhere. */
1791       num_interfaces = 1;
1792
1793       /* open an incoming socket */
1794       s = open_socket_in(SOCK_STREAM, port, 0,interpret_addr(lp_socket_address()));
1795       if (s == -1)
1796         return(False);
1797
1798       /* ready to listen */
1799       if (listen(s, 5) == -1) 
1800       {
1801         DEBUG(0,("open_sockets: listen: %s\n",strerror(errno)));
1802         close(s);
1803         return False;
1804       }
1805
1806       fd_listenset[0] = s;
1807       FD_SET(s,&listen_set);
1808     }      
1809
1810     /* now accept incoming connections - forking a new process
1811        for each incoming connection */
1812     DEBUG(2,("waiting for a connection\n"));
1813     while (1)
1814     {
1815       fd_set lfds;
1816       int num;
1817
1818       memcpy((char *)&lfds, (char *)&listen_set, sizeof(listen_set));
1819
1820       num = sys_select(&lfds,NULL);
1821
1822       if (num == -1 && errno == EINTR)
1823         continue;
1824
1825       /* Find the sockets that are read-ready - accept on these. */
1826       for( ; num > 0; num--)
1827       {
1828         struct sockaddr addr;
1829         int in_addrlen = sizeof(addr);
1830
1831         s = -1;
1832         for(i = 0; i < num_interfaces; i++)
1833         {
1834           if(FD_ISSET(fd_listenset[i],&lfds))
1835           {
1836             s = fd_listenset[i];
1837             /* Clear this so we don't look at it again. */
1838             FD_CLR(fd_listenset[i],&lfds);
1839             break;
1840           }
1841         }
1842
1843         Client = accept(s,&addr,&in_addrlen);
1844
1845         if (Client == -1 && errno == EINTR)
1846           continue;
1847
1848         if (Client == -1)
1849         {
1850           DEBUG(0,("open_sockets: accept: %s\n",strerror(errno)));
1851           continue;
1852         }
1853
1854         if (Client != -1 && fork()==0)
1855         {
1856           /* Child code ... */
1857
1858           CatchSignal(SIGPIPE, SIGNAL_CAST sig_pipe);
1859
1860           /* close the listening socket(s) */
1861           for(i = 0; i < num_interfaces; i++)
1862             close(fd_listenset[i]);
1863
1864           /* close our standard file descriptors */
1865           close_low_fds();
1866           am_parent = 0;
1867   
1868           set_socket_options(Client,"SO_KEEPALIVE");
1869           set_socket_options(Client,user_socket_options);
1870
1871           /* Reset global variables in util.c so that
1872              client substitutions will be done correctly
1873              in the process.
1874            */
1875           reset_globals_after_fork();
1876           return True; 
1877         }
1878         close(Client); /* The parent doesn't need this socket */
1879
1880         /*
1881          * Force parent to check log size after spawning child.
1882          * Fix from klausr@ITAP.Physik.Uni-Stuttgart.De.
1883          * The parent smbd will log to logserver.smb. 
1884          * It writes only two messages for each child
1885          * started/finished. But each child writes, say, 50 messages also in
1886          * logserver.smb, begining with the debug_count of the parent, before the
1887          * child opens its own log file logserver.client. In a worst case
1888          * scenario the size of logserver.smb would be checked after about
1889          * 50*50=2500 messages (ca. 100kb).
1890          */
1891         force_check_log_size();
1892  
1893       } /* end for num */
1894     } /* end while 1 */
1895   } /* end if is_daemon */
1896   else
1897   {
1898     /* Started from inetd. fd 0 is the socket. */
1899     /* We will abort gracefully when the client or remote system 
1900        goes away */
1901     CatchSignal(SIGPIPE, SIGNAL_CAST sig_pipe);
1902     Client = dup(0);
1903
1904     /* close our standard file descriptors */
1905     close_low_fds();
1906
1907     set_socket_options(Client,"SO_KEEPALIVE");
1908     set_socket_options(Client,user_socket_options);
1909   }
1910
1911   return True;
1912 }
1913
1914 /****************************************************************************
1915   process an smb from the client - split out from the process() code so
1916   it can be used by the oplock break code.
1917 ****************************************************************************/
1918
1919 static void process_smb(char *inbuf, char *outbuf)
1920 {
1921   extern int Client;
1922 #ifdef WITH_SSL
1923   extern BOOL sslEnabled;     /* don't use function for performance reasons */
1924   static int sslConnected = 0;
1925 #endif /* WITH_SSL */
1926   static int trans_num;
1927   int msg_type = CVAL(inbuf,0);
1928   int32 len = smb_len(inbuf);
1929   int nread = len + 4;
1930
1931   if (trans_num == 0) {
1932           /* on the first packet, check the global hosts allow/ hosts
1933              deny parameters before doing any parsing of the packet
1934              passed to us by the client.  This prevents attacks on our
1935              parsing code from hosts not in the hosts allow list */
1936           if (!check_access(Client, lp_hostsallow(-1), lp_hostsdeny(-1))) {
1937                   /* send a negative session response "not listining on calling
1938                    name" */
1939                   static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
1940                   DEBUG( 1, ( "Connection denied from %s\n",
1941                               client_addr(Client) ) );
1942                   send_smb(Client,(char *)buf);
1943                   exit_server("connection denied");
1944           }
1945   }
1946
1947   DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type, len ) );
1948   DEBUG( 3, ( "Transaction %d of length %d\n", trans_num, nread ) );
1949
1950 #ifdef WITH_SSL
1951     if(sslEnabled && !sslConnected){
1952         sslConnected = sslutil_negotiate_ssl(Client, msg_type);
1953         if(sslConnected < 0){   /* an error occured */
1954             exit_server("SSL negotiation failed");
1955         }else if(sslConnected){
1956             trans_num++;
1957             return;
1958         }
1959     }
1960 #endif  /* WITH_SSL */
1961
1962 #ifdef WITH_VTP
1963   if(trans_num == 1 && VT_Check(inbuf)) 
1964   {
1965     VT_Process();
1966     return;
1967   }
1968 #endif
1969
1970   if (msg_type == 0)
1971     show_msg(inbuf);
1972   else if(msg_type == 0x85)
1973     return; /* Keepalive packet. */
1974
1975   nread = construct_reply(inbuf,outbuf,nread,max_send);
1976       
1977   if(nread > 0) 
1978   {
1979     if (CVAL(outbuf,0) == 0)
1980       show_msg(outbuf);
1981         
1982     if (nread != smb_len(outbuf) + 4) 
1983     {
1984       DEBUG(0,("ERROR: Invalid message response size! %d %d\n",
1985                  nread, smb_len(outbuf)));
1986     }
1987     else
1988       send_smb(Client,outbuf);
1989   }
1990   trans_num++;
1991 }
1992
1993 /****************************************************************************
1994   open the oplock IPC socket communication
1995 ****************************************************************************/
1996 static BOOL open_oplock_ipc(void)
1997 {
1998   struct sockaddr_in sock_name;
1999   int len = sizeof(sock_name);
2000
2001   DEBUG(3,("open_oplock_ipc: opening loopback UDP socket.\n"));
2002
2003   /* Open a lookback UDP socket on a random port. */
2004   oplock_sock = open_socket_in(SOCK_DGRAM, 0, 0, htonl(INADDR_LOOPBACK));
2005   if (oplock_sock == -1)
2006   {
2007     DEBUG(0,("open_oplock_ipc: Failed to get local UDP socket for \
2008 address %x. Error was %s\n", htonl(INADDR_LOOPBACK), strerror(errno)));
2009     oplock_port = 0;
2010     return(False);
2011   }
2012
2013   /* Find out the transient UDP port we have been allocated. */
2014   if(getsockname(oplock_sock, (struct sockaddr *)&sock_name, &len)<0)
2015   {
2016     DEBUG(0,("open_oplock_ipc: Failed to get local UDP port. Error was %s\n",
2017             strerror(errno)));
2018     close(oplock_sock);
2019     oplock_sock = -1;
2020     oplock_port = 0;
2021     return False;
2022   }
2023   oplock_port = ntohs(sock_name.sin_port);
2024
2025   DEBUG(3,("open_oplock ipc: pid = %d, oplock_port = %u\n", 
2026             (int)getpid(), oplock_port));
2027
2028   return True;
2029 }
2030
2031 /****************************************************************************
2032   process an oplock break message.
2033 ****************************************************************************/
2034 static BOOL process_local_message(int sock, char *buffer, int buf_size)
2035 {
2036   int32 msg_len;
2037   uint16 from_port;
2038   char *msg_start;
2039
2040   msg_len = IVAL(buffer,UDP_CMD_LEN_OFFSET);
2041   from_port = SVAL(buffer,UDP_CMD_PORT_OFFSET);
2042
2043   msg_start = &buffer[UDP_CMD_HEADER_LEN];
2044
2045   DEBUG(5,("process_local_message: Got a message of length %d from port (%d)\n", 
2046             msg_len, from_port));
2047
2048   /* Switch on message command - currently OPLOCK_BREAK_CMD is the
2049      only valid request. */
2050
2051   switch(SVAL(msg_start,UDP_MESSAGE_CMD_OFFSET))
2052   {
2053     case OPLOCK_BREAK_CMD:
2054       /* Ensure that the msg length is correct. */
2055       if(msg_len != OPLOCK_BREAK_MSG_LEN)
2056       {
2057         DEBUG(0,("process_local_message: incorrect length for OPLOCK_BREAK_CMD (was %d, \
2058 should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
2059         return False;
2060       }
2061       {
2062         uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
2063         uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
2064         uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
2065         struct timeval tval;
2066         struct sockaddr_in toaddr;
2067
2068         tval.tv_sec = IVAL(msg_start, OPLOCK_BREAK_SEC_OFFSET);
2069         tval.tv_usec = IVAL(msg_start, OPLOCK_BREAK_USEC_OFFSET);
2070
2071         DEBUG(5,("process_local_message: oplock break request from \
2072 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
2073
2074         /*
2075          * If we have no record of any currently open oplocks,
2076          * it's not an error, as a close command may have
2077          * just been issued on the file that was oplocked.
2078          * Just return success in this case.
2079          */
2080
2081         if(global_oplocks_open != 0)
2082         {
2083           if(oplock_break(dev, inode, &tval) == False)
2084           {
2085             DEBUG(0,("process_local_message: oplock break failed - \
2086 not returning udp message.\n"));
2087             return False;
2088           }
2089         }
2090         else
2091         {
2092           DEBUG(3,("process_local_message: oplock break requested with no outstanding \
2093 oplocks. Returning success.\n"));
2094         }
2095
2096         /* Send the message back after OR'ing in the 'REPLY' bit. */
2097         SSVAL(msg_start,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD | CMD_REPLY);
2098   
2099         bzero((char *)&toaddr,sizeof(toaddr));
2100         toaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2101         toaddr.sin_port = htons(from_port);
2102         toaddr.sin_family = AF_INET;
2103
2104         if(sendto( sock, msg_start, OPLOCK_BREAK_MSG_LEN, 0,
2105                 (struct sockaddr *)&toaddr, sizeof(toaddr)) < 0) 
2106         {
2107           DEBUG(0,("process_local_message: sendto process %d failed. Errno was %s\n",
2108                     remotepid, strerror(errno)));
2109           return False;
2110         }
2111
2112         DEBUG(5,("process_local_message: oplock break reply sent to \
2113 pid %d, port %d, for file dev = %x, inode = %x\n", remotepid, 
2114                 from_port, dev, inode));
2115
2116       }
2117       break;
2118     /* 
2119      * Keep this as a debug case - eventually we can remove it.
2120      */
2121     case 0x8001:
2122       DEBUG(0,("process_local_message: Received unsolicited break \
2123 reply - dumping info.\n"));
2124
2125       if(msg_len != OPLOCK_BREAK_MSG_LEN)
2126       {
2127         DEBUG(0,("process_local_message: ubr: incorrect length for reply \
2128 (was %d, should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
2129         return False;
2130       }
2131
2132       {
2133         uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
2134         uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
2135         uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
2136
2137         DEBUG(0,("process_local_message: unsolicited oplock break reply from \
2138 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
2139
2140        }
2141        return False;
2142
2143     default:
2144       DEBUG(0,("process_local_message: unknown UDP message command code (%x) - ignoring.\n",
2145                 (unsigned int)SVAL(msg_start,0)));
2146       return False;
2147   }
2148   return True;
2149 }
2150
2151 /****************************************************************************
2152  Process an oplock break directly.
2153 ****************************************************************************/
2154 BOOL oplock_break(uint32 dev, uint32 inode, struct timeval *tval)
2155 {
2156   extern struct current_user current_user;
2157   extern int Client;
2158   char *inbuf = NULL;
2159   char *outbuf = NULL;
2160   files_struct *fsp = NULL;
2161   time_t start_time;
2162   BOOL shutdown_server = False;
2163   connection_struct *saved_conn;
2164   int saved_vuid;
2165   pstring saved_dir; 
2166
2167   if( DEBUGLVL( 3 ) )
2168     {
2169     dbgtext( "oplock_break: called for dev = %x, inode = %x.\n", dev, inode );
2170     dbgtext( "Current global_oplocks_open = %d\n", global_oplocks_open );
2171     }
2172
2173   /* We need to search the file open table for the
2174      entry containing this dev and inode, and ensure
2175      we have an oplock on it. */
2176   fsp = file_find_dit(dev, inode, tval);
2177
2178   if(fsp == NULL)
2179   {
2180     /* The file could have been closed in the meantime - return success. */
2181     if( DEBUGLVL( 0 ) )
2182       {
2183       dbgtext( "oplock_break: cannot find open file with " );
2184       dbgtext( "dev = %x, inode = %x ", dev, inode);
2185       dbgtext( "allowing break to succeed.\n" );
2186       }
2187     return True;
2188   }
2189
2190   /* Ensure we have an oplock on the file */
2191
2192   /* There is a potential race condition in that an oplock could
2193      have been broken due to another udp request, and yet there are
2194      still oplock break messages being sent in the udp message
2195      queue for this file. So return true if we don't have an oplock,
2196      as we may have just freed it.
2197    */
2198
2199   if(!fsp->granted_oplock)
2200   {
2201     if( DEBUGLVL( 0 ) )
2202       {
2203       dbgtext( "oplock_break: file %s ", fsp->fsp_name );
2204       dbgtext( "(dev = %x, inode = %x) has no oplock.\n", dev, inode );
2205       dbgtext( "Allowing break to succeed regardless.\n" );
2206       }
2207     return True;
2208   }
2209
2210   /* mark the oplock break as sent - we don't want to send twice! */
2211   if (fsp->sent_oplock_break)
2212   {
2213     if( DEBUGLVL( 0 ) )
2214       {
2215       dbgtext( "oplock_break: ERROR: oplock_break already sent for " );
2216       dbgtext( "file %s ", fsp->fsp_name);
2217       dbgtext( "(dev = %x, inode = %x)\n", dev, inode );
2218       }
2219
2220     /* We have to fail the open here as we cannot send another oplock break on
2221        this file whilst we are awaiting a response from the client - neither
2222        can we allow another open to succeed while we are waiting for the
2223        client.
2224      */
2225     return False;
2226   }
2227
2228   /* Now comes the horrid part. We must send an oplock break to the client,
2229      and then process incoming messages until we get a close or oplock release.
2230      At this point we know we need a new inbuf/outbuf buffer pair.
2231      We cannot use these staticaly as we may recurse into here due to
2232      messages crossing on the wire.
2233    */
2234
2235   if((inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
2236   {
2237     DEBUG(0,("oplock_break: malloc fail for input buffer.\n"));
2238     return False;
2239   }
2240
2241   if((outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
2242   {
2243     DEBUG(0,("oplock_break: malloc fail for output buffer.\n"));
2244     free(inbuf);
2245     inbuf = NULL;
2246     return False;
2247   }
2248
2249   /* Prepare the SMBlockingX message. */
2250   bzero(outbuf,smb_size);
2251   set_message(outbuf,8,0,True);
2252
2253   SCVAL(outbuf,smb_com,SMBlockingX);
2254   SSVAL(outbuf,smb_tid,fsp->conn->cnum);
2255   SSVAL(outbuf,smb_pid,0xFFFF);
2256   SSVAL(outbuf,smb_uid,0);
2257   SSVAL(outbuf,smb_mid,0xFFFF);
2258   SCVAL(outbuf,smb_vwv0,0xFF);
2259   SSVAL(outbuf,smb_vwv2,fsp->fnum);
2260   SCVAL(outbuf,smb_vwv3,LOCKING_ANDX_OPLOCK_RELEASE);
2261   /* Change this when we have level II oplocks. */
2262   SCVAL(outbuf,smb_vwv3+1,OPLOCKLEVEL_NONE);
2263  
2264   send_smb(Client, outbuf);
2265
2266   /* Remember we just sent an oplock break on this file. */
2267   fsp->sent_oplock_break = True;
2268
2269   /* We need this in case a readraw crosses on the wire. */
2270   global_oplock_break = True;
2271  
2272   /* Process incoming messages. */
2273
2274   /* JRA - If we don't get a break from the client in OPLOCK_BREAK_TIMEOUT
2275      seconds we should just die.... */
2276
2277   start_time = time(NULL);
2278
2279   /*
2280    * Save the information we need to re-become the
2281    * user, then unbecome the user whilst we're doing this.
2282    */
2283   saved_conn = fsp->conn;
2284   saved_vuid = current_user.vuid;
2285   GetWd(saved_dir);
2286   unbecome_user();
2287
2288   while(OPEN_FSP(fsp) && fsp->granted_oplock)
2289   {
2290     if(receive_smb(Client,inbuf,OPLOCK_BREAK_TIMEOUT * 1000) == False)
2291     {
2292       /*
2293        * Die if we got an error.
2294        */
2295
2296       if (smb_read_error == READ_EOF)
2297         DEBUG( 0, ( "oplock_break: end of file from client\n" ) );
2298  
2299       if (smb_read_error == READ_ERROR)
2300         DEBUG( 0, ("oplock_break: receive_smb error (%s)\n", strerror(errno)) );
2301
2302       if (smb_read_error == READ_TIMEOUT)
2303         DEBUG( 0, ( "oplock_break: receive_smb timed out after %d seconds.\n",
2304                      OPLOCK_BREAK_TIMEOUT ) );
2305
2306       DEBUGADD( 0, ( "oplock_break failed for file %s ", fsp->fsp_name ) );
2307       DEBUGADD( 0, ( "(dev = %x, inode = %x).\n", dev, inode));
2308       shutdown_server = True;
2309       break;
2310     }
2311
2312     /*
2313      * There are certain SMB requests that we shouldn't allow
2314      * to recurse. opens, renames and deletes are the obvious
2315      * ones. This is handled in the switch_message() function.
2316      * If global_oplock_break is set they will push the packet onto
2317      * the pending smb queue and return -1 (no reply).
2318      * JRA.
2319      */
2320
2321     process_smb(inbuf, outbuf);
2322
2323     /*
2324      * Die if we go over the time limit.
2325      */
2326
2327     if((time(NULL) - start_time) > OPLOCK_BREAK_TIMEOUT)
2328     {
2329       if( DEBUGLVL( 0 ) )
2330         {
2331         dbgtext( "oplock_break: no break received from client " );
2332         dbgtext( "within %d seconds.\n", OPLOCK_BREAK_TIMEOUT );
2333         dbgtext( "oplock_break failed for file %s ", fsp->fsp_name );
2334         dbgtext( "(dev = %x, inode = %x).\n", dev, inode );
2335         }
2336       shutdown_server = True;
2337       break;
2338     }
2339   }
2340
2341   /*
2342    * Go back to being the user who requested the oplock
2343    * break.
2344    */
2345   if(!become_user(saved_conn, saved_vuid))
2346   {
2347     DEBUG( 0, ( "oplock_break: unable to re-become user!" ) );
2348     DEBUGADD( 0, ( "Shutting down server\n" ) );
2349     close_sockets();
2350     close(oplock_sock);
2351     exit_server("unable to re-become user");
2352   }
2353   /* Including the directory. */
2354   ChDir(saved_dir);
2355
2356   /* Free the buffers we've been using to recurse. */
2357   free(inbuf);
2358   free(outbuf);
2359
2360   /* We need this in case a readraw crossed on the wire. */
2361   if(global_oplock_break)
2362     global_oplock_break = False;
2363
2364   /*
2365    * If the client did not respond we must die.
2366    */
2367
2368   if(shutdown_server)
2369   {
2370     DEBUG( 0, ( "oplock_break: client failure in break - " ) );
2371     DEBUGADD( 0, ( "shutting down this smbd.\n" ) );
2372     close_sockets();
2373     close(oplock_sock);
2374     exit_server("oplock break failure");
2375   }
2376
2377   if(OPEN_FSP(fsp))
2378   {
2379     /* The lockingX reply will have removed the oplock flag 
2380        from the sharemode. */
2381     /* Paranoia.... */
2382     fsp->granted_oplock = False;
2383     fsp->sent_oplock_break = False;
2384     global_oplocks_open--;
2385   }
2386
2387   /* Santity check - remove this later. JRA */
2388   if(global_oplocks_open < 0)
2389   {
2390     DEBUG(0,("oplock_break: global_oplocks_open < 0 (%d). PANIC ERROR\n",
2391               global_oplocks_open));
2392     exit_server("oplock_break: global_oplocks_open < 0");
2393   }
2394
2395   if( DEBUGLVL( 3 ) )
2396     {
2397     dbgtext( "oplock_break: returning success for " );
2398     dbgtext( "dev = %x, inode = %x.\n", dev, inode );
2399     dbgtext( "Current global_oplocks_open = %d\n", global_oplocks_open );
2400     }
2401
2402   return True;
2403 }
2404
2405 /****************************************************************************
2406 Send an oplock break message to another smbd process. If the oplock is held 
2407 by the local smbd then call the oplock break function directly.
2408 ****************************************************************************/
2409
2410 BOOL request_oplock_break(share_mode_entry *share_entry, 
2411                           uint32 dev, uint32 inode)
2412 {
2413   char op_break_msg[OPLOCK_BREAK_MSG_LEN];
2414   struct sockaddr_in addr_out;
2415   int pid = getpid();
2416   time_t start_time;
2417   int time_left;
2418
2419   if(pid == share_entry->pid)
2420   {
2421     /* We are breaking our own oplock, make sure it's us. */
2422     if(share_entry->op_port != oplock_port)
2423     {
2424       DEBUG(0,("request_oplock_break: corrupt share mode entry - pid = %d, port = %d \
2425 should be %d\n", pid, share_entry->op_port, oplock_port));
2426       return False;
2427     }
2428
2429     DEBUG(5,("request_oplock_break: breaking our own oplock\n"));
2430
2431     /* Call oplock break direct. */
2432     return oplock_break(dev, inode, &share_entry->time);
2433   }
2434
2435   /* We need to send a OPLOCK_BREAK_CMD message to the
2436      port in the share mode entry. */
2437
2438   SSVAL(op_break_msg,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD);
2439   SIVAL(op_break_msg,OPLOCK_BREAK_PID_OFFSET,pid);
2440   SIVAL(op_break_msg,OPLOCK_BREAK_DEV_OFFSET,dev);
2441   SIVAL(op_break_msg,OPLOCK_BREAK_INODE_OFFSET,inode);
2442   SIVAL(op_break_msg,OPLOCK_BREAK_SEC_OFFSET,(uint32)share_entry->time.tv_sec);
2443   SIVAL(op_break_msg,OPLOCK_BREAK_USEC_OFFSET,(uint32)share_entry->time.tv_usec);
2444
2445   /* set the address and port */
2446   bzero((char *)&addr_out,sizeof(addr_out));
2447   addr_out.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2448   addr_out.sin_port = htons( share_entry->op_port );
2449   addr_out.sin_family = AF_INET;
2450    
2451   if( DEBUGLVL( 3 ) )
2452     {
2453     dbgtext( "request_oplock_break: sending a oplock break message to " );
2454     dbgtext( "pid %d on port %d ", share_entry->pid, share_entry->op_port );
2455     dbgtext( "for dev = %x, inode = %x\n", dev, inode );
2456     }
2457
2458   if(sendto(oplock_sock,op_break_msg,OPLOCK_BREAK_MSG_LEN,0,
2459          (struct sockaddr *)&addr_out,sizeof(addr_out)) < 0)
2460   {
2461     if( DEBUGLVL( 0 ) )
2462       {
2463       dbgtext( "request_oplock_break: failed when sending a oplock " );
2464       dbgtext( "break message to pid %d ", share_entry->pid );
2465       dbgtext( "on port %d ", share_entry->op_port );
2466       dbgtext( "for dev = %x, inode = %x.\n", dev, inode );
2467       dbgtext( "Error was %s\n", strerror(errno) );
2468       }
2469     return False;
2470   }
2471
2472   /*
2473    * Now we must await the oplock broken message coming back
2474    * from the target smbd process. Timeout if it fails to
2475    * return in (OPLOCK_BREAK_TIMEOUT + OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR) seconds.
2476    * While we get messages that aren't ours, loop.
2477    */
2478
2479   start_time = time(NULL);
2480   time_left = OPLOCK_BREAK_TIMEOUT+OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR;
2481
2482   while(time_left >= 0)
2483   {
2484     char op_break_reply[UDP_CMD_HEADER_LEN+OPLOCK_BREAK_MSG_LEN];
2485     int32 reply_msg_len;
2486     uint16 reply_from_port;
2487     char *reply_msg_start;
2488
2489     if(receive_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply),
2490                time_left ? time_left * 1000 : 1) == False)
2491     {
2492       if(smb_read_error == READ_TIMEOUT)
2493       {
2494         if( DEBUGLVL( 0 ) )
2495           {
2496           dbgtext( "request_oplock_break: no response received to oplock " );
2497           dbgtext( "break request to pid %d ", share_entry->pid );
2498           dbgtext( "on port %d ", share_entry->op_port );
2499           dbgtext( "for dev = %x, inode = %x\n", dev, inode );
2500           }
2501         /*
2502          * This is a hack to make handling of failing clients more robust.
2503          * If a oplock break response message is not received in the timeout
2504          * period we may assume that the smbd servicing that client holding
2505          * the oplock has died and the client changes were lost anyway, so
2506          * we should continue to try and open the file.
2507          */
2508         break;
2509       }
2510       else
2511         if( DEBUGLVL( 0 ) )
2512           {
2513           dbgtext( "request_oplock_break: error in response received " );
2514           dbgtext( "to oplock break request to pid %d ", share_entry->pid );
2515           dbgtext( "on port %d ", share_entry->op_port );
2516           dbgtext( "for dev = %x, inode = %x.\n", dev, inode );
2517           dbgtext( "Error was (%s).\n", strerror(errno) );
2518           }
2519       return False;
2520     }
2521
2522     reply_msg_len = IVAL(op_break_reply,UDP_CMD_LEN_OFFSET);
2523     reply_from_port = SVAL(op_break_reply,UDP_CMD_PORT_OFFSET);
2524
2525     reply_msg_start = &op_break_reply[UDP_CMD_HEADER_LEN];
2526
2527     if(reply_msg_len != OPLOCK_BREAK_MSG_LEN)
2528     {
2529       /* Ignore it. */
2530       DEBUG( 0, ( "request_oplock_break: invalid message length received." ) );
2531       DEBUGADD( 0, ( "  Ignoring.\n" ) );
2532       continue;
2533     }
2534
2535     /*
2536      * Test to see if this is the reply we are awaiting.
2537      */
2538
2539     if((SVAL(reply_msg_start,UDP_MESSAGE_CMD_OFFSET) & CMD_REPLY) &&
2540        (reply_from_port == share_entry->op_port) && 
2541        (memcmp(&reply_msg_start[OPLOCK_BREAK_PID_OFFSET], 
2542                &op_break_msg[OPLOCK_BREAK_PID_OFFSET],
2543                OPLOCK_BREAK_MSG_LEN - OPLOCK_BREAK_PID_OFFSET) == 0))
2544     {
2545       /*
2546        * This is the reply we've been waiting for.
2547        */
2548       break;
2549     }
2550     else
2551     {
2552       /*
2553        * This is another message - probably a break request.
2554        * Process it to prevent potential deadlock.
2555        * Note that the code in switch_message() prevents
2556        * us from recursing into here as any SMB requests
2557        * we might process that would cause another oplock
2558        * break request to be made will be queued.
2559        * JRA.
2560        */
2561
2562       process_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply));
2563     }
2564
2565     time_left -= (time(NULL) - start_time);
2566   }
2567
2568   DEBUG(3,("request_oplock_break: broke oplock.\n"));
2569
2570   return True;
2571 }
2572
2573 /****************************************************************************
2574 Get the next SMB packet, doing the local message processing automatically.
2575 ****************************************************************************/
2576
2577 BOOL receive_next_smb(int smbfd, int oplockfd, char *inbuf, int bufsize, int timeout)
2578 {
2579   BOOL got_smb = False;
2580   BOOL ret;
2581
2582   do
2583   {
2584     ret = receive_message_or_smb(smbfd,oplockfd,inbuf,bufsize,
2585                                  timeout,&got_smb);
2586
2587     if(ret && !got_smb)
2588     {
2589       /* Deal with oplock break requests from other smbd's. */
2590       process_local_message(oplock_sock, inbuf, bufsize);
2591       continue;
2592     }
2593
2594     if(ret && (CVAL(inbuf,0) == 0x85))
2595     {
2596       /* Keepalive packet. */
2597       got_smb = False;
2598     }
2599
2600   }
2601   while(ret && !got_smb);
2602
2603   return ret;
2604 }
2605
2606 /****************************************************************************
2607   reload the services file
2608   **************************************************************************/
2609 BOOL reload_services(BOOL test)
2610 {
2611         BOOL ret;
2612
2613         if (lp_loaded()) {
2614                 pstring fname;
2615                 pstrcpy(fname,lp_configfile());
2616                 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
2617                         pstrcpy(servicesf,fname);
2618                         test = False;
2619                 }
2620         }
2621
2622         reopen_logs();
2623
2624         if (test && !lp_file_list_changed())
2625                 return(True);
2626
2627         lp_killunused(conn_snum_used);
2628
2629         ret = lp_load(servicesf,False,False,True);
2630
2631         load_printers();
2632
2633         /* perhaps the config filename is now set */
2634         if (!test)
2635                 reload_services(True);
2636
2637         reopen_logs();
2638
2639         load_interfaces();
2640
2641         {
2642                 extern int Client;
2643                 if (Client != -1) {      
2644                         set_socket_options(Client,"SO_KEEPALIVE");
2645                         set_socket_options(Client,user_socket_options);
2646                 }
2647         }
2648
2649         reset_mangled_cache();
2650
2651         /* this forces service parameters to be flushed */
2652         become_service(NULL,True);
2653
2654         return(ret);
2655 }
2656
2657
2658
2659 /****************************************************************************
2660 this prevents zombie child processes
2661 ****************************************************************************/
2662 static BOOL reload_after_sighup = False;
2663
2664 static void sig_hup(int sig)
2665 {
2666   BlockSignals(True,SIGHUP);
2667   DEBUG(0,("Got SIGHUP\n"));
2668
2669   /*
2670    * Fix from <branko.cibej@hermes.si> here.
2671    * We used to reload in the signal handler - this
2672    * is a *BIG* no-no.
2673    */
2674
2675   reload_after_sighup = True;
2676   BlockSignals(False,SIGHUP);
2677 }
2678
2679
2680 /****************************************************************************
2681   make a connection to a service
2682 ****************************************************************************/
2683 connection_struct *make_connection(char *service,char *user,char *password, int pwlen, char *dev,uint16 vuid, int *ecode)
2684 {
2685         int snum;
2686         struct passwd *pass = NULL;
2687         BOOL guest = False;
2688         BOOL force = False;
2689         extern int Client;
2690         connection_struct *conn;
2691
2692         strlower(service);
2693
2694         snum = find_service(service);
2695         if (snum < 0) {
2696                 extern int Client;
2697                 if (strequal(service,"IPC$")) {
2698                         DEBUG(3,("refusing IPC connection\n"));
2699                         *ecode = ERRnoipc;
2700                         return NULL;
2701                 }
2702
2703                 DEBUG(0,("%s (%s) couldn't find service %s\n",
2704                          remote_machine, client_addr(Client), service));
2705                 *ecode = ERRinvnetname;
2706                 return NULL;
2707         }
2708
2709         if (strequal(service,HOMES_NAME)) {
2710                 if (*user && Get_Pwnam(user,True))
2711                         return(make_connection(user,user,password,
2712                                                pwlen,dev,vuid,ecode));
2713
2714                 if(lp_security() != SEC_SHARE) {
2715                         if (validated_username(vuid)) {
2716                                 pstrcpy(user,validated_username(vuid));
2717                                 return(make_connection(user,user,password,pwlen,dev,vuid,ecode));
2718                         }
2719                 } else {
2720                         /* Security = share. Try with sesssetup_user
2721                          * as the username.  */
2722                         if(*sesssetup_user) {
2723                                 pstrcpy(user,sesssetup_user);
2724                                 return(make_connection(user,user,password,pwlen,dev,vuid,ecode));
2725                         }
2726                 }
2727         }
2728
2729         if (!lp_snum_ok(snum) || 
2730             !check_access(Client, 
2731                           lp_hostsallow(snum), lp_hostsdeny(snum))) {    
2732                 *ecode = ERRaccess;
2733                 return NULL;
2734         }
2735
2736         /* you can only connect to the IPC$ service as an ipc device */
2737         if (strequal(service,"IPC$"))
2738                 pstrcpy(dev,"IPC");
2739         
2740         if (*dev == '?' || !*dev) {
2741                 if (lp_print_ok(snum)) {
2742                         pstrcpy(dev,"LPT1:");
2743                 } else {
2744                         pstrcpy(dev,"A:");
2745                 }
2746         }
2747
2748         /* if the request is as a printer and you can't print then refuse */
2749         strupper(dev);
2750         if (!lp_print_ok(snum) && (strncmp(dev,"LPT",3) == 0)) {
2751                 DEBUG(1,("Attempt to connect to non-printer as a printer\n"));
2752                 *ecode = ERRinvdevice;
2753                 return NULL;
2754         }
2755
2756         /* lowercase the user name */
2757         strlower(user);
2758
2759         /* add it as a possible user name */
2760         add_session_user(service);
2761
2762         /* shall we let them in? */
2763         if (!authorise_login(snum,user,password,pwlen,&guest,&force,vuid)) {
2764                 DEBUG( 2, ( "Invalid username/password for %s\n", service ) );
2765                 *ecode = ERRbadpw;
2766                 return NULL;
2767         }
2768   
2769         conn = conn_new();
2770         if (!conn) {
2771                 DEBUG(0,("Couldn't find free connection.\n"));
2772                 *ecode = ERRnoresource;
2773                 conn_free(conn);
2774                 return NULL;
2775         }
2776
2777         /* find out some info about the user */
2778         pass = Get_Pwnam(user,True);
2779
2780         if (pass == NULL) {
2781                 DEBUG(0,( "Couldn't find account %s\n",user));
2782                 *ecode = ERRbaduid;
2783                 conn_free(conn);
2784                 return NULL;
2785         }
2786
2787         conn->read_only = lp_readonly(snum);
2788
2789         {
2790                 pstring list;
2791                 StrnCpy(list,lp_readlist(snum),sizeof(pstring)-1);
2792                 string_sub(list,"%S",service);
2793
2794                 if (user_in_list(user,list))
2795                         conn->read_only = True;
2796                 
2797                 StrnCpy(list,lp_writelist(snum),sizeof(pstring)-1);
2798                 string_sub(list,"%S",service);
2799                 
2800                 if (user_in_list(user,list))
2801                         conn->read_only = False;    
2802         }
2803
2804         /* admin user check */
2805         
2806         /* JRA - original code denied admin user if the share was
2807            marked read_only. Changed as I don't think this is needed,
2808            but old code left in case there is a problem here.
2809         */
2810         if (user_in_list(user,lp_admin_users(snum)) 
2811 #if 0
2812             && !conn->read_only
2813 #endif
2814             ) {
2815                 conn->admin_user = True;
2816                 DEBUG(0,("%s logged in as admin user (root privileges)\n",user));
2817         } else {
2818                 conn->admin_user = False;
2819         }
2820     
2821         conn->force_user = force;
2822         conn->vuid = vuid;
2823         conn->uid = pass->pw_uid;
2824         conn->gid = pass->pw_gid;
2825         conn->num_files_open = 0;
2826         conn->lastused = time(NULL);
2827         conn->service = snum;
2828         conn->used = True;
2829         conn->printer = (strncmp(dev,"LPT",3) == 0);
2830         conn->ipc = (strncmp(dev,"IPC",3) == 0);
2831         conn->dirptr = NULL;
2832         conn->veto_list = NULL;
2833         conn->hide_list = NULL;
2834         conn->veto_oplock_list = NULL;
2835         string_set(&conn->dirpath,"");
2836         string_set(&conn->user,user);
2837         
2838 #ifdef HAVE_GETGRNAM 
2839         if (*lp_force_group(snum)) {
2840                 struct group *gptr;
2841                 pstring gname;
2842                 
2843                 StrnCpy(gname,lp_force_group(snum),sizeof(pstring)-1);
2844                 /* default service may be a group name          */
2845                 string_sub(gname,"%S",service);
2846                 gptr = (struct group *)getgrnam(gname);
2847                 
2848                 if (gptr) {
2849                         conn->gid = gptr->gr_gid;
2850                         DEBUG(3,("Forced group %s\n",gname));
2851                 } else {
2852                         DEBUG(1,("Couldn't find group %s\n",gname));
2853                 }
2854         }
2855 #endif
2856         
2857         if (*lp_force_user(snum)) {
2858                 struct passwd *pass2;
2859                 fstring fuser;
2860                 fstrcpy(fuser,lp_force_user(snum));
2861                 pass2 = (struct passwd *)Get_Pwnam(fuser,True);
2862                 if (pass2) {
2863                         conn->uid = pass2->pw_uid;
2864                         string_set(&conn->user,fuser);
2865                         fstrcpy(user,fuser);
2866                         conn->force_user = True;
2867                         DEBUG(3,("Forced user %s\n",fuser));      
2868                 } else {
2869                         DEBUG(1,("Couldn't find user %s\n",fuser));
2870                 }
2871         }
2872
2873         {
2874                 pstring s;
2875                 pstrcpy(s,lp_pathname(snum));
2876                 standard_sub(conn,s);
2877                 string_set(&conn->connectpath,s);
2878                 DEBUG(3,("Connect path is %s\n",s));
2879         }
2880
2881         /* groups stuff added by ih */
2882         conn->ngroups = 0;
2883         conn->groups = NULL;
2884         
2885         if (!IS_IPC(conn)) {
2886                 /* Find all the groups this uid is in and
2887                    store them. Used by become_user() */
2888                 setup_groups(conn->user,conn->uid,conn->gid,
2889                              &conn->ngroups,&conn->groups);
2890                 
2891                 /* check number of connections */
2892                 if (!claim_connection(conn,
2893                                       lp_servicename(SNUM(conn)),
2894                                       lp_max_connections(SNUM(conn)),
2895                                       False)) {
2896                         DEBUG(1,("too many connections - rejected\n"));
2897                         *ecode = ERRnoresource;
2898                         conn_free(conn);
2899                         return NULL;
2900                 }  
2901                 
2902                 if (lp_status(SNUM(conn)))
2903                         claim_connection(conn,"STATUS.",
2904                                          MAXSTATUS,False);
2905         } /* IS_IPC */
2906         
2907         /* execute any "root preexec = " line */
2908         if (*lp_rootpreexec(SNUM(conn))) {
2909                 pstring cmd;
2910                 pstrcpy(cmd,lp_rootpreexec(SNUM(conn)));
2911                 standard_sub(conn,cmd);
2912                 DEBUG(5,("cmd=%s\n",cmd));
2913                 smbrun(cmd,NULL,False);
2914         }
2915         
2916         if (!become_user(conn, conn->vuid)) {
2917                 DEBUG(0,("Can't become connected user!\n"));
2918                 if (!IS_IPC(conn)) {
2919                         yield_connection(conn,
2920                                          lp_servicename(SNUM(conn)),
2921                                          lp_max_connections(SNUM(conn)));
2922                         if (lp_status(SNUM(conn))) {
2923                                 yield_connection(conn,"STATUS.",MAXSTATUS);
2924                         }
2925                 }
2926                 conn_free(conn);
2927                 *ecode = ERRbadpw;
2928                 return NULL;
2929         }
2930         
2931         if (ChDir(conn->connectpath) != 0) {
2932                 DEBUG(0,("Can't change directory to %s (%s)\n",
2933                          conn->connectpath,strerror(errno)));
2934                 unbecome_user();
2935                 if (!IS_IPC(conn)) {
2936                         yield_connection(conn,
2937                                          lp_servicename(SNUM(conn)),
2938                                          lp_max_connections(SNUM(conn)));
2939                         if (lp_status(SNUM(conn))) 
2940                                 yield_connection(conn,"STATUS.",MAXSTATUS);
2941                 }
2942                 conn_free(conn);
2943                 *ecode = ERRinvnetname;
2944                 return NULL;
2945         }
2946         
2947         string_set(&conn->origpath,conn->connectpath);
2948         
2949 #if SOFTLINK_OPTIMISATION
2950         /* resolve any soft links early */
2951         {
2952                 pstring s;
2953                 pstrcpy(s,conn->connectpath);
2954                 GetWd(s);
2955                 string_set(&conn->connectpath,s);
2956                 ChDir(conn->connectpath);
2957         }
2958 #endif
2959         
2960         add_session_user(user);
2961                 
2962         /* execute any "preexec = " line */
2963         if (*lp_preexec(SNUM(conn))) {
2964                 pstring cmd;
2965                 pstrcpy(cmd,lp_preexec(SNUM(conn)));
2966                 standard_sub(conn,cmd);
2967                 smbrun(cmd,NULL,False);
2968         }
2969         
2970         /* we've finished with the sensitive stuff */
2971         unbecome_user();
2972         
2973         /* Add veto/hide lists */
2974         if (!IS_IPC(conn) && !IS_PRINT(conn)) {
2975                 set_namearray( &conn->veto_list, lp_veto_files(SNUM(conn)));
2976                 set_namearray( &conn->hide_list, lp_hide_files(SNUM(conn)));
2977                 set_namearray( &conn->veto_oplock_list, lp_veto_oplocks(SNUM(conn)));
2978         }
2979         
2980         if( DEBUGLVL( IS_IPC(conn) ? 3 : 1 ) ) {
2981                 extern int Client;
2982                 
2983                 dbgtext( "%s (%s) ", remote_machine, client_addr(Client) );
2984                 dbgtext( "connect to service %s ", lp_servicename(SNUM(conn)) );
2985                 dbgtext( "as user %s ", user );
2986                 dbgtext( "(uid=%d, gid=%d) ", conn->uid, conn->gid );
2987                 dbgtext( "(pid %d)\n", (int)getpid() );
2988         }
2989         
2990         return(conn);
2991 }
2992
2993 /****************************************************************************
2994   Attempt to break an oplock on a file (if oplocked).
2995   Returns True if the file was closed as a result of
2996   the oplock break, False otherwise.
2997   Used as a last ditch attempt to free a space in the 
2998   file table when we have run out.
2999 ****************************************************************************/
3000 BOOL attempt_close_oplocked_file(files_struct *fsp)
3001 {
3002
3003   DEBUG(5,("attempt_close_oplocked_file: checking file %s.\n", fsp->fsp_name));
3004
3005   if (fsp->open && fsp->granted_oplock && !fsp->sent_oplock_break) {
3006
3007     /* Try and break the oplock. */
3008     file_fd_struct *fd_ptr = fsp->fd_ptr;
3009     if(oplock_break( fd_ptr->dev, fd_ptr->inode, &fsp->open_time)) {
3010       if(!fsp->open) /* Did the oplock break close the file ? */
3011         return True;
3012     }
3013   }
3014
3015   return False;
3016 }
3017
3018
3019
3020 /****************************************************************************
3021 close a cnum
3022 ****************************************************************************/
3023 void close_cnum(connection_struct *conn, uint16 vuid)
3024 {
3025         extern int Client;
3026         DirCacheFlush(SNUM(conn));
3027
3028         unbecome_user();
3029
3030         DEBUG(IS_IPC(conn)?3:1, ("%s (%s) closed connection to service %s\n",
3031                                  remote_machine,client_addr(Client),
3032                                  lp_servicename(SNUM(conn))));
3033
3034         yield_connection(conn,
3035                          lp_servicename(SNUM(conn)),
3036                          lp_max_connections(SNUM(conn)));
3037
3038         if (lp_status(SNUM(conn)))
3039                 yield_connection(conn,"STATUS.",MAXSTATUS);
3040
3041         file_close_conn(conn);
3042         dptr_closecnum(conn);
3043
3044         /* execute any "postexec = " line */
3045         if (*lp_postexec(SNUM(conn)) && 
3046             become_user(conn, vuid))  {
3047                 pstring cmd;
3048                 pstrcpy(cmd,lp_postexec(SNUM(conn)));
3049                 standard_sub(conn,cmd);
3050                 smbrun(cmd,NULL,False);
3051                 unbecome_user();
3052         }
3053
3054         unbecome_user();
3055         /* execute any "root postexec = " line */
3056         if (*lp_rootpostexec(SNUM(conn)))  {
3057                 pstring cmd;
3058                 pstrcpy(cmd,lp_rootpostexec(SNUM(conn)));
3059                 standard_sub(conn,cmd);
3060                 smbrun(cmd,NULL,False);
3061         }
3062         
3063         conn_free(conn);
3064 }
3065
3066
3067
3068 #if DUMP_CORE
3069 /*******************************************************************
3070 prepare to dump a core file - carefully!
3071 ********************************************************************/
3072 static BOOL dump_core(void)
3073 {
3074   char *p;
3075   pstring dname;
3076   pstrcpy(dname,debugf);
3077   if ((p=strrchr(dname,'/'))) *p=0;
3078   pstrcat(dname,"/corefiles");
3079   mkdir(dname,0700);
3080   sys_chown(dname,getuid(),getgid());
3081   chmod(dname,0700);
3082   if (chdir(dname)) return(False);
3083   umask(~(0700));
3084
3085 #ifdef HAVE_GETRLIMIT
3086 #ifdef RLIMIT_CORE
3087   {
3088     struct rlimit rlp;
3089     getrlimit(RLIMIT_CORE, &rlp);
3090     rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
3091     setrlimit(RLIMIT_CORE, &rlp);
3092     getrlimit(RLIMIT_CORE, &rlp);
3093     DEBUG(3,("Core limits now %d %d\n",(int)rlp.rlim_cur,(int)rlp.rlim_max));
3094   }
3095 #endif
3096 #endif
3097
3098
3099   DEBUG(0,("Dumping core in %s\n",dname));
3100   abort();
3101   return(True);
3102 }
3103 #endif
3104
3105 /****************************************************************************
3106 exit the server
3107 ****************************************************************************/
3108 void exit_server(char *reason)
3109 {
3110   static int firsttime=1;
3111
3112   if (!firsttime) exit(0);
3113   firsttime = 0;
3114
3115   unbecome_user();
3116   DEBUG(2,("Closing connections\n"));
3117
3118   conn_close_all();
3119
3120 #ifdef WITH_DFS
3121   if (dcelogin_atmost_once) {
3122     dfs_unlogin();
3123   }
3124 #endif
3125   if (!reason) {   
3126     int oldlevel = DEBUGLEVEL;
3127     DEBUGLEVEL = 10;
3128     DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
3129     if (last_inbuf)
3130       show_msg(last_inbuf);
3131     DEBUGLEVEL = oldlevel;
3132     DEBUG(0,("===============================================================\n"));
3133 #if DUMP_CORE
3134     if (dump_core()) return;
3135 #endif
3136   }    
3137
3138   locking_end();
3139
3140   DEBUG( 3, ( "Server exit (%s)\n", (reason ? reason : "") ) );
3141   exit(0);
3142 }
3143
3144 /*
3145 These flags determine some of the permissions required to do an operation 
3146
3147 Note that I don't set NEED_WRITE on some write operations because they
3148 are used by some brain-dead clients when printing, and I don't want to
3149 force write permissions on print services.
3150 */
3151 #define AS_USER (1<<0)
3152 #define NEED_WRITE (1<<1)
3153 #define TIME_INIT (1<<2)
3154 #define CAN_IPC (1<<3)
3155 #define AS_GUEST (1<<5)
3156 #define QUEUE_IN_OPLOCK (1<<6)
3157
3158 /* 
3159    define a list of possible SMB messages and their corresponding
3160    functions. Any message that has a NULL function is unimplemented -
3161    please feel free to contribute implementations!
3162 */
3163 struct smb_message_struct
3164 {
3165   int code;
3166   char *name;
3167   int (*fn)(connection_struct *conn, char *, char *, int, int);
3168   int flags;
3169 #if PROFILING
3170   unsigned long time;
3171 #endif
3172 }
3173  smb_messages[] = {
3174
3175     /* CORE PROTOCOL */
3176
3177    {SMBnegprot,"SMBnegprot",reply_negprot,0},
3178    {SMBtcon,"SMBtcon",reply_tcon,0},
3179    {SMBtdis,"SMBtdis",reply_tdis,0},
3180    {SMBexit,"SMBexit",reply_exit,0},
3181    {SMBioctl,"SMBioctl",reply_ioctl,0},
3182    {SMBecho,"SMBecho",reply_echo,0},
3183    {SMBsesssetupX,"SMBsesssetupX",reply_sesssetup_and_X,0},
3184    {SMBtconX,"SMBtconX",reply_tcon_and_X,0},
3185    {SMBulogoffX, "SMBulogoffX", reply_ulogoffX, 0}, /* ulogoff doesn't give a valid TID */
3186    {SMBgetatr,"SMBgetatr",reply_getatr,AS_USER},
3187    {SMBsetatr,"SMBsetatr",reply_setatr,AS_USER | NEED_WRITE},
3188    {SMBchkpth,"SMBchkpth",reply_chkpth,AS_USER},
3189    {SMBsearch,"SMBsearch",reply_search,AS_USER},
3190    {SMBopen,"SMBopen",reply_open,AS_USER | QUEUE_IN_OPLOCK },
3191
3192    /* note that SMBmknew and SMBcreate are deliberately overloaded */   
3193    {SMBcreate,"SMBcreate",reply_mknew,AS_USER},
3194    {SMBmknew,"SMBmknew",reply_mknew,AS_USER}, 
3195
3196    {SMBunlink,"SMBunlink",reply_unlink,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
3197    {SMBread,"SMBread",reply_read,AS_USER},
3198    {SMBwrite,"SMBwrite",reply_write,AS_USER},
3199    {SMBclose,"SMBclose",reply_close,AS_USER | CAN_IPC},
3200    {SMBmkdir,"SMBmkdir",reply_mkdir,AS_USER | NEED_WRITE},
3201    {SMBrmdir,"SMBrmdir",reply_rmdir,AS_USER | NEED_WRITE},
3202    {SMBdskattr,"SMBdskattr",reply_dskattr,AS_USER},
3203    {SMBmv,"SMBmv",reply_mv,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
3204
3205    /* this is a Pathworks specific call, allowing the 
3206       changing of the root path */
3207    {pSETDIR,"pSETDIR",reply_setdir,AS_USER}, 
3208
3209    {SMBlseek,"SMBlseek",reply_lseek,AS_USER},
3210    {SMBflush,"SMBflush",reply_flush,AS_USER},
3211    {SMBctemp,"SMBctemp",reply_ctemp,AS_USER | QUEUE_IN_OPLOCK },
3212    {SMBsplopen,"SMBsplopen",reply_printopen,AS_USER | QUEUE_IN_OPLOCK },
3213    {SMBsplclose,"SMBsplclose",reply_printclose,AS_USER},
3214    {SMBsplretq,"SMBsplretq",reply_printqueue,AS_USER},
3215    {SMBsplwr,"SMBsplwr",reply_printwrite,AS_USER},
3216    {SMBlock,"SMBlock",reply_lock,AS_USER},
3217    {SMBunlock,"SMBunlock",reply_unlock,AS_USER},
3218    
3219    /* CORE+ PROTOCOL FOLLOWS */
3220    
3221    {SMBreadbraw,"SMBreadbraw",reply_readbraw,AS_USER},
3222    {SMBwritebraw,"SMBwritebraw",reply_writebraw,AS_USER},
3223    {SMBwriteclose,"SMBwriteclose",reply_writeclose,AS_USER},
3224    {SMBlockread,"SMBlockread",reply_lockread,AS_USER},
3225    {SMBwriteunlock,"SMBwriteunlock",reply_writeunlock,AS_USER},
3226    
3227    /* LANMAN1.0 PROTOCOL FOLLOWS */
3228    
3229    {SMBreadBmpx,"SMBreadBmpx",reply_readbmpx,AS_USER},
3230    {SMBreadBs,"SMBreadBs",NULL,AS_USER},
3231    {SMBwriteBmpx,"SMBwriteBmpx",reply_writebmpx,AS_USER},
3232    {SMBwriteBs,"SMBwriteBs",reply_writebs,AS_USER},
3233    {SMBwritec,"SMBwritec",NULL,AS_USER},
3234    {SMBsetattrE,"SMBsetattrE",reply_setattrE,AS_USER | NEED_WRITE},
3235    {SMBgetattrE,"SMBgetattrE",reply_getattrE,AS_USER},
3236    {SMBtrans,"SMBtrans",reply_trans,AS_USER | CAN_IPC},
3237    {SMBtranss,"SMBtranss",NULL,AS_USER | CAN_IPC},
3238    {SMBioctls,"SMBioctls",NULL,AS_USER},
3239    {SMBcopy,"SMBcopy",reply_copy,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
3240    {SMBmove,"SMBmove",NULL,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
3241    
3242    {SMBopenX,"SMBopenX",reply_open_and_X,AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
3243    {SMBreadX,"SMBreadX",reply_read_and_X,AS_USER | CAN_IPC },
3244    {SMBwriteX,"SMBwriteX",reply_write_and_X,AS_USER},
3245    {SMBlockingX,"SMBlockingX",reply_lockingX,AS_USER},
3246    
3247    {SMBffirst,"SMBffirst",reply_search,AS_USER},
3248    {SMBfunique,"SMBfunique",reply_search,AS_USER},
3249    {SMBfclose,"SMBfclose",reply_fclose,AS_USER},
3250
3251    /* LANMAN2.0 PROTOCOL FOLLOWS */
3252    {SMBfindnclose, "SMBfindnclose", reply_findnclose, AS_USER},
3253    {SMBfindclose, "SMBfindclose", reply_findclose,AS_USER},
3254    {SMBtrans2, "SMBtrans2", reply_trans2, AS_USER },
3255    {SMBtranss2, "SMBtranss2", reply_transs2, AS_USER},
3256
3257    /* NT PROTOCOL FOLLOWS */
3258    {SMBntcreateX, "SMBntcreateX", reply_ntcreate_and_X, AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
3259    {SMBnttrans, "SMBnttrans", reply_nttrans, AS_USER | CAN_IPC },
3260    {SMBnttranss, "SMBnttranss", reply_nttranss, AS_USER | CAN_IPC },
3261    {SMBntcancel, "SMBntcancel", reply_ntcancel, AS_USER },
3262
3263    /* messaging routines */
3264    {SMBsends,"SMBsends",reply_sends,AS_GUEST},
3265    {SMBsendstrt,"SMBsendstrt",reply_sendstrt,AS_GUEST},
3266    {SMBsendend,"SMBsendend",reply_sendend,AS_GUEST},
3267    {SMBsendtxt,"SMBsendtxt",reply_sendtxt,AS_GUEST},
3268
3269    /* NON-IMPLEMENTED PARTS OF THE CORE PROTOCOL */
3270    
3271    {SMBsendb,"SMBsendb",NULL,AS_GUEST},
3272    {SMBfwdname,"SMBfwdname",NULL,AS_GUEST},
3273    {SMBcancelf,"SMBcancelf",NULL,AS_GUEST},
3274    {SMBgetmac,"SMBgetmac",NULL,AS_GUEST}
3275  };
3276
3277 /****************************************************************************
3278 return a string containing the function name of a SMB command
3279 ****************************************************************************/
3280 char *smb_fn_name(int type)
3281 {
3282         static char *unknown_name = "SMBunknown";
3283         static int num_smb_messages = 
3284                 sizeof(smb_messages) / sizeof(struct smb_message_struct);
3285         int match;
3286
3287         for (match=0;match<num_smb_messages;match++)
3288                 if (smb_messages[match].code == type)
3289                         break;
3290
3291         if (match == num_smb_messages)
3292                 return(unknown_name);
3293
3294         return(smb_messages[match].name);
3295 }
3296
3297
3298 /****************************************************************************
3299 do a switch on the message type, and return the response size
3300 ****************************************************************************/
3301 static int switch_message(int type,char *inbuf,char *outbuf,int size,int bufsize)
3302 {
3303   static int pid= -1;
3304   int outsize = 0;
3305   static int num_smb_messages = 
3306     sizeof(smb_messages) / sizeof(struct smb_message_struct);
3307   int match;
3308   extern int Client;
3309
3310 #if PROFILING
3311   struct timeval msg_start_time;
3312   struct timeval msg_end_time;
3313   static unsigned long total_time = 0;
3314
3315   GetTimeOfDay(&msg_start_time);
3316 #endif
3317
3318   if (pid == -1)
3319     pid = getpid();
3320
3321   errno = 0;
3322   last_message = type;
3323
3324   /* make sure this is an SMB packet */
3325   if (strncmp(smb_base(inbuf),"\377SMB",4) != 0)
3326   {
3327     DEBUG(2,("Non-SMB packet of length %d\n",smb_len(inbuf)));
3328     return(-1);
3329   }
3330
3331   for (match=0;match<num_smb_messages;match++)
3332     if (smb_messages[match].code == type)
3333       break;
3334
3335   if (match == num_smb_messages)
3336   {
3337     DEBUG(0,("Unknown message type %d!\n",type));
3338     outsize = reply_unknown(inbuf,outbuf);
3339   }
3340   else
3341   {
3342     DEBUG(3,("switch message %s (pid %d)\n",smb_messages[match].name,pid));
3343
3344     if(global_oplock_break && (smb_messages[match].flags & QUEUE_IN_OPLOCK))
3345     {
3346       /* 
3347        * Queue this message as we are the process of an oplock break.
3348        */
3349
3350       DEBUG( 2, ( "switch_message: queueing message due to being in " ) );
3351       DEBUGADD( 2, ( "oplock break state.\n" ) );
3352
3353       push_oplock_pending_smb_message( inbuf, size );
3354       return -1;
3355     }          
3356
3357     if (smb_messages[match].fn)
3358     {
3359       int flags = smb_messages[match].flags;
3360       static uint16 last_session_tag = UID_FIELD_INVALID;
3361       /* In share mode security we must ignore the vuid. */
3362       uint16 session_tag = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : SVAL(inbuf,smb_uid);
3363       connection_struct *conn = conn_find(SVAL(inbuf,smb_tid));
3364
3365
3366       /* Ensure this value is replaced in the incoming packet. */
3367       SSVAL(inbuf,smb_uid,session_tag);
3368
3369       /*
3370        * Ensure the correct username is in sesssetup_user.
3371        * This is a really ugly bugfix for problems with
3372        * multiple session_setup_and_X's being done and
3373        * allowing %U and %G substitutions to work correctly.
3374        * There is a reason this code is done here, don't
3375        * move it unless you know what you're doing... :-).
3376        * JRA.
3377        */
3378       if (session_tag != last_session_tag) {
3379         user_struct *vuser = NULL;
3380
3381         last_session_tag = session_tag;
3382         if(session_tag != UID_FIELD_INVALID)
3383           vuser = get_valid_user_struct(session_tag);           
3384         if(vuser != NULL)
3385           pstrcpy( sesssetup_user, vuser->requested_name);
3386       }
3387
3388       /* does this protocol need to be run as root? */
3389       if (!(flags & AS_USER))
3390         unbecome_user();
3391
3392       /* does this protocol need to be run as the connected user? */
3393       if ((flags & AS_USER) && !become_user(conn,session_tag)) {
3394         if (flags & AS_GUEST) 
3395           flags &= ~AS_USER;
3396         else
3397           return(ERROR(ERRSRV,ERRinvnid));
3398       }
3399       /* this code is to work around a bug is MS client 3 without
3400          introducing a security hole - it needs to be able to do
3401          print queue checks as guest if it isn't logged in properly */
3402       if (flags & AS_USER)
3403         flags &= ~AS_GUEST;
3404
3405       /* does it need write permission? */
3406       if ((flags & NEED_WRITE) && !CAN_WRITE(conn))
3407         return(ERROR(ERRSRV,ERRaccess));
3408
3409       /* ipc services are limited */
3410       if (IS_IPC(conn) && (flags & AS_USER) && !(flags & CAN_IPC)) {
3411         return(ERROR(ERRSRV,ERRaccess));            
3412       }
3413
3414       /* load service specific parameters */
3415       if (conn && 
3416           !become_service(conn,(flags & AS_USER)?True:False)) {
3417         return(ERROR(ERRSRV,ERRaccess));
3418       }
3419
3420       /* does this protocol need to be run as guest? */
3421       if ((flags & AS_GUEST) && 
3422           (!become_guest() || 
3423            !check_access(Client, lp_hostsallow(-1), lp_hostsdeny(-1)))) {
3424         return(ERROR(ERRSRV,ERRaccess));
3425       }
3426
3427       last_inbuf = inbuf;
3428
3429       outsize = smb_messages[match].fn(conn, inbuf,outbuf,size,bufsize);
3430     }
3431     else
3432     {
3433       outsize = reply_unknown(inbuf,outbuf);
3434     }
3435   }
3436
3437 #if PROFILING
3438   GetTimeOfDay(&msg_end_time);
3439   if (!(smb_messages[match].flags & TIME_INIT))
3440   {
3441     smb_messages[match].time = 0;
3442     smb_messages[match].flags |= TIME_INIT;
3443   }
3444   {
3445     unsigned long this_time =     
3446       (msg_end_time.tv_sec - msg_start_time.tv_sec)*1e6 +
3447       (msg_end_time.tv_usec - msg_start_time.tv_usec);
3448     smb_messages[match].time += this_time;
3449     total_time += this_time;
3450   }
3451   DEBUG(2,("TIME %s  %d usecs   %g pct\n",
3452         smb_fn_name(type),smb_messages[match].time,
3453         (100.0*smb_messages[match].time) / total_time));
3454 #endif
3455
3456   return(outsize);
3457 }
3458
3459
3460 /****************************************************************************
3461   construct a chained reply and add it to the already made reply
3462   **************************************************************************/
3463 int chain_reply(char *inbuf,char *outbuf,int size,int bufsize)
3464 {
3465   static char *orig_inbuf;
3466   static char *orig_outbuf;
3467   int smb_com1, smb_com2 = CVAL(inbuf,smb_vwv0);
3468   unsigned smb_off2 = SVAL(inbuf,smb_vwv1);
3469   char *inbuf2, *outbuf2;
3470   int outsize2;
3471   char inbuf_saved[smb_wct];
3472   char outbuf_saved[smb_wct];
3473   extern int chain_size;
3474   int wct = CVAL(outbuf,smb_wct);
3475   int outsize = smb_size + 2*wct + SVAL(outbuf,smb_vwv0+2*wct);
3476
3477   /* maybe its not chained */
3478   if (smb_com2 == 0xFF) {
3479     CVAL(outbuf,smb_vwv0) = 0xFF;
3480     return outsize;
3481   }
3482
3483   if (chain_size == 0) {
3484     /* this is the first part of the chain */
3485     orig_inbuf = inbuf;
3486     orig_outbuf = outbuf;
3487   }
3488
3489   /* we need to tell the client where the next part of the reply will be */
3490   SSVAL(outbuf,smb_vwv1,smb_offset(outbuf+outsize,outbuf));
3491   CVAL(outbuf,smb_vwv0) = smb_com2;
3492
3493   /* remember how much the caller added to the chain, only counting stuff
3494      after the parameter words */
3495   chain_size += outsize - smb_wct;
3496
3497   /* work out pointers into the original packets. The
3498      headers on these need to be filled in */
3499   inbuf2 = orig_inbuf + smb_off2 + 4 - smb_wct;
3500   outbuf2 = orig_outbuf + SVAL(outbuf,smb_vwv1) + 4 - smb_wct;
3501
3502   /* remember the original command type */
3503   smb_com1 = CVAL(orig_inbuf,smb_com);
3504
3505   /* save the data which will be overwritten by the new headers */
3506   memcpy(inbuf_saved,inbuf2,smb_wct);
3507   memcpy(outbuf_saved,outbuf2,smb_wct);
3508
3509   /* give the new packet the same header as the last part of the SMB */
3510   memmove(inbuf2,inbuf,smb_wct);
3511
3512   /* create the in buffer */
3513   CVAL(inbuf2,smb_com) = smb_com2;
3514
3515   /* create the out buffer */
3516   bzero(outbuf2,smb_size);
3517   set_message(outbuf2,0,0,True);
3518   CVAL(outbuf2,smb_com) = CVAL(inbuf2,smb_com);
3519   
3520   memcpy(outbuf2+4,inbuf2+4,4);
3521   CVAL(outbuf2,smb_rcls) = SMB_SUCCESS;
3522   CVAL(outbuf2,smb_reh) = 0;
3523   CVAL(outbuf2,smb_flg) = 0x80 | (CVAL(inbuf2,smb_flg) & 0x8); /* bit 7 set 
3524                                                                   means a reply */
3525   SSVAL(outbuf2,smb_flg2,1); /* say we support long filenames */
3526   SSVAL(outbuf2,smb_err,SMB_SUCCESS);
3527   SSVAL(outbuf2,smb_tid,SVAL(inbuf2,smb_tid));
3528   SSVAL(outbuf2,smb_pid,SVAL(inbuf2,smb_pid));
3529   SSVAL(outbuf2,smb_uid,SVAL(inbuf2,smb_uid));
3530   SSVAL(outbuf2,smb_mid,SVAL(inbuf2,smb_mid));
3531
3532   DEBUG(3,("Chained message\n"));
3533   show_msg(inbuf2);
3534
3535   /* process the request */
3536   outsize2 = switch_message(smb_com2,inbuf2,outbuf2,size-chain_size,
3537                             bufsize-chain_size);
3538
3539   /* copy the new reply and request headers over the old ones, but
3540      preserve the smb_com field */
3541   memmove(orig_outbuf,outbuf2,smb_wct);
3542   CVAL(orig_outbuf,smb_com) = smb_com1;
3543
3544   /* restore the saved data, being careful not to overwrite any
3545    data from the reply header */
3546   memcpy(inbuf2,inbuf_saved,smb_wct);
3547   {
3548     int ofs = smb_wct - PTR_DIFF(outbuf2,orig_outbuf);
3549     if (ofs < 0) ofs = 0;
3550     memmove(outbuf2+ofs,outbuf_saved+ofs,smb_wct-ofs);
3551   }
3552
3553   return outsize2;
3554 }
3555
3556
3557 /****************************************************************************
3558  Helper function for contruct_reply.
3559 ****************************************************************************/
3560
3561 void construct_reply_common(char *inbuf,char *outbuf)
3562 {
3563   bzero(outbuf,smb_size);
3564
3565   CVAL(outbuf,smb_com) = CVAL(inbuf,smb_com);
3566   set_message(outbuf,0,0,True);
3567
3568   memcpy(outbuf+4,inbuf+4,4);
3569   CVAL(outbuf,smb_rcls) = SMB_SUCCESS;
3570   CVAL(outbuf,smb_reh) = 0;
3571   CVAL(outbuf,smb_flg) = 0x80 | (CVAL(inbuf,smb_flg) & 0x8); /* bit 7 set
3572                                  means a reply */
3573   SSVAL(outbuf,smb_flg2,1); /* say we support long filenames */
3574   SSVAL(outbuf,smb_err,SMB_SUCCESS);
3575   SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
3576   SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
3577   SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
3578   SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
3579 }
3580
3581 /****************************************************************************
3582   construct a reply to the incoming packet
3583 ****************************************************************************/
3584 int construct_reply(char *inbuf,char *outbuf,int size,int bufsize)
3585 {
3586   int type = CVAL(inbuf,smb_com);
3587   int outsize = 0;
3588   int msg_type = CVAL(inbuf,0);
3589   extern int chain_size;
3590
3591   smb_last_time = time(NULL);
3592
3593   chain_size = 0;
3594   file_chain_reset();
3595   reset_chain_p();
3596
3597   if (msg_type != 0)
3598     return(reply_special(inbuf,outbuf));  
3599
3600   construct_reply_common(inbuf, outbuf);
3601
3602   outsize = switch_message(type,inbuf,outbuf,size,bufsize);
3603
3604   outsize += chain_size;
3605
3606   if(outsize > 4)
3607     smb_setlen(outbuf,outsize - 4);
3608   return(outsize);
3609 }
3610
3611 /****************************************************************************
3612   process commands from the client
3613 ****************************************************************************/
3614 static void process(void)
3615 {
3616   extern int Client;
3617
3618   InBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
3619   OutBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
3620   if ((InBuffer == NULL) || (OutBuffer == NULL)) 
3621     return;
3622
3623   InBuffer += SMB_ALIGNMENT;
3624   OutBuffer += SMB_ALIGNMENT;
3625
3626 #if PRIME_NMBD
3627   DEBUG(3,("priming nmbd\n"));
3628   {
3629     struct in_addr ip;
3630     ip = *interpret_addr2("localhost");
3631     if (zero_ip(ip)) ip = *interpret_addr2("127.0.0.1");
3632     *OutBuffer = 0;
3633     send_one_packet(OutBuffer,1,ip,NMB_PORT,SOCK_DGRAM);
3634   }
3635 #endif    
3636
3637   /* re-initialise the timezone */
3638   TimeInit();
3639
3640   while (True)
3641   {
3642     int deadtime = lp_deadtime()*60;
3643     int counter;
3644     int last_keepalive=0;
3645     int service_load_counter = 0;
3646     BOOL got_smb = False;
3647
3648     if (deadtime <= 0)
3649       deadtime = DEFAULT_SMBD_TIMEOUT;
3650
3651 #if USE_READ_PREDICTION
3652     if (lp_readprediction())
3653       do_read_prediction();
3654 #endif
3655
3656     errno = 0;      
3657
3658     for (counter=SMBD_SELECT_LOOP; 
3659           !receive_message_or_smb(Client,oplock_sock,
3660                       InBuffer,BUFFER_SIZE,SMBD_SELECT_LOOP*1000,&got_smb); 
3661           counter += SMBD_SELECT_LOOP)
3662     {
3663       time_t t;
3664       BOOL allidle = True;
3665       extern int keepalive;
3666
3667       if (counter > 365 * 3600) /* big number of seconds. */
3668       {
3669         counter = 0;
3670         service_load_counter = 0;
3671       }
3672
3673       if (smb_read_error == READ_EOF) 
3674       {
3675         DEBUG(3,("end of file from client\n"));
3676         return;
3677       }
3678
3679       if (smb_read_error == READ_ERROR) 
3680       {
3681         DEBUG(3,("receive_smb error (%s) exiting\n",
3682                   strerror(errno)));
3683         return;
3684       }
3685
3686       t = time(NULL);
3687
3688       /* become root again if waiting */
3689       unbecome_user();
3690
3691       /* check for smb.conf reload */
3692       if (counter >= service_load_counter + SMBD_RELOAD_CHECK)
3693       {
3694         service_load_counter = counter;
3695
3696         /* reload services, if files have changed. */
3697         reload_services(True);
3698       }
3699
3700       /*
3701        * If reload_after_sighup == True then we got a SIGHUP
3702        * and are being asked to reload. Fix from <branko.cibej@hermes.si>
3703        */
3704
3705       if (reload_after_sighup)
3706       {
3707         DEBUG(0,("Reloading services after SIGHUP\n"));
3708         reload_services(False);
3709         reload_after_sighup = False;
3710       }
3711
3712       /* automatic timeout if all connections are closed */      
3713       if (conn_num_open()==0 && counter >= IDLE_CLOSED_TIMEOUT) 
3714       {
3715         DEBUG( 2, ( "Closing idle connection\n" ) );
3716         return;
3717       }
3718
3719       if (keepalive && (counter-last_keepalive)>keepalive) 
3720       {
3721               struct cli_state *cli = server_client();
3722               if (!send_keepalive(Client)) {
3723                       DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
3724                       return;
3725               }     
3726               /* also send a keepalive to the password server if its still
3727                  connected */
3728               if (cli && cli->initialised)
3729                       send_keepalive(cli->fd);
3730               last_keepalive = counter;
3731       }
3732
3733       /* check for connection timeouts */
3734       allidle = conn_idle_all(t, deadtime);
3735
3736       if (allidle && conn_num_open()>0) {
3737               DEBUG(2,("Closing idle connection 2.\n"));
3738               return;
3739       }
3740
3741       if(global_machine_pasword_needs_changing)
3742       {
3743         unsigned char trust_passwd_hash[16];
3744         time_t lct;
3745         pstring remote_machine_list;
3746
3747         /*
3748          * We're in domain level security, and the code that
3749          * read the machine password flagged that the machine
3750          * password needs changing.
3751          */
3752
3753         /*
3754          * First, open the machine password file with an exclusive lock.
3755          */
3756
3757         if(!trust_password_lock( global_myworkgroup, global_myname, True)) {
3758           DEBUG(0,("process: unable to open the machine account password file for \
3759 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
3760           continue;
3761         }
3762
3763         if(!get_trust_account_password( trust_passwd_hash, &lct)) {
3764           DEBUG(0,("process: unable to read the machine account password for \
3765 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
3766           trust_password_unlock();
3767           continue;
3768         }
3769
3770         /*
3771          * Make sure someone else hasn't already done this.
3772          */
3773
3774         if(t < lct + lp_machine_password_timeout()) {
3775           trust_password_unlock();
3776           global_machine_pasword_needs_changing = False;
3777           continue;
3778         }
3779
3780         pstrcpy(remote_machine_list, lp_passwordserver());
3781
3782         change_trust_account_password( global_myworkgroup, remote_machine_list);
3783         trust_password_unlock();
3784         global_machine_pasword_needs_changing = False;
3785       }
3786
3787       /*
3788        * Check to see if we have any change notifies 
3789        * outstanding on the queue.
3790        */
3791       process_pending_change_notify_queue(t);
3792     }
3793
3794     if(got_smb)
3795       process_smb(InBuffer, OutBuffer);
3796     else
3797       process_local_message(oplock_sock, InBuffer, BUFFER_SIZE);
3798   }
3799 }
3800
3801
3802 /****************************************************************************
3803   initialise connect, service and file structs
3804 ****************************************************************************/
3805 static void init_structs(void )
3806 {
3807   get_myname(myhostname,NULL);
3808
3809   /*
3810    * Set the machine NETBIOS name if not already
3811    * set from the config file.
3812    */
3813
3814   if (!*global_myname)
3815   {
3816     char *p;
3817     fstrcpy( global_myname, myhostname );
3818     p = strchr( global_myname, '.' );
3819     if (p) 
3820       *p = 0;
3821   }
3822   strupper( global_myname );
3823
3824   conn_init();
3825
3826   file_init();
3827
3828   /* for RPC pipes */
3829   init_rpc_pipe_hnd();
3830
3831   /* for LSA handles */
3832   init_lsa_policy_hnd();
3833
3834   init_dptrs();
3835 }
3836
3837 /****************************************************************************
3838 usage on the program
3839 ****************************************************************************/
3840 static void usage(char *pname)
3841 {
3842   DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
3843
3844   printf("Usage: %s [-D] [-p port] [-d debuglevel] [-l log basename] [-s services file]\n",pname);
3845   printf("Version %s\n",VERSION);
3846   printf("\t-D                    become a daemon\n");
3847   printf("\t-p port               listen on the specified port\n");
3848   printf("\t-d debuglevel         set the debuglevel\n");
3849   printf("\t-l log basename.      Basename for log/debug files\n");
3850   printf("\t-s services file.     Filename of services file\n");
3851   printf("\t-P                    passive only\n");
3852   printf("\t-a                    overwrite log file, don't append\n");
3853   printf("\n");
3854 }
3855
3856
3857 /****************************************************************************
3858   main program
3859 ****************************************************************************/
3860  int main(int argc,char *argv[])
3861 {
3862   extern BOOL append_log;
3863   /* shall I run as a daemon */
3864   BOOL is_daemon = False;
3865   int port = SMB_PORT;
3866   int opt;
3867   extern char *optarg;
3868
3869 #ifdef HAVE_SET_AUTH_PARAMETERS
3870   set_auth_parameters(argc,argv);
3871 #endif
3872
3873 #ifdef HAVE_SETLUID
3874   /* needed for SecureWare on SCO */
3875   setluid(0);
3876 #endif
3877
3878   append_log = True;
3879
3880   TimeInit();
3881
3882   pstrcpy(debugf,SMBLOGFILE);  
3883
3884   pstrcpy(remote_machine, "smb");
3885
3886   setup_logging(argv[0],False);
3887
3888   charset_initialise();
3889
3890   /* make absolutely sure we run as root - to handle cases where people
3891      are crazy enough to have it setuid */
3892 #ifdef HAVE_SETRESUID
3893   setresuid(0,0,0);
3894 #else
3895   setuid(0);
3896   seteuid(0);
3897   setuid(0);
3898   seteuid(0);
3899 #endif
3900
3901   fault_setup((void (*)(void *))exit_server);
3902   CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
3903
3904   /* we want total control over the permissions on created files,
3905      so set our umask to 0 */
3906   umask(0);
3907
3908   GetWd(OriginalDir);
3909
3910   init_uid();
3911
3912   /* this is for people who can't start the program correctly */
3913   while (argc > 1 && (*argv[1] != '-'))
3914     {
3915       argv++;
3916       argc--;
3917     }
3918
3919   while ((opt = getopt(argc, argv, "O:i:l:s:d:Dp:hPaf:")) != EOF)
3920     switch (opt)
3921       {
3922       case 'O':
3923         pstrcpy(user_socket_options,optarg);
3924         break;
3925       case 'i':
3926         pstrcpy(scope,optarg);
3927         break;
3928       case 'P':
3929         {
3930           extern BOOL passive;
3931           passive = True;
3932         }
3933         break;  
3934       case 's':
3935         pstrcpy(servicesf,optarg);
3936         break;
3937       case 'l':
3938         pstrcpy(debugf,optarg);
3939         break;
3940       case 'a':
3941         {
3942           extern BOOL append_log;
3943           append_log = !append_log;
3944         }
3945         break;
3946       case 'D':
3947         is_daemon = True;
3948         break;
3949       case 'd':
3950         if (*optarg == 'A')
3951           DEBUGLEVEL = 10000;
3952         else
3953           DEBUGLEVEL = atoi(optarg);
3954         break;
3955       case 'p':
3956         port = atoi(optarg);
3957         break;
3958       case 'h':
3959         usage(argv[0]);
3960         exit(0);
3961         break;
3962       default:
3963         usage(argv[0]);
3964         exit(1);
3965       }
3966
3967   reopen_logs();
3968
3969   DEBUG( 1, ( "smbd version %s started.\n", VERSION ) );
3970   DEBUGADD( 1, ( "Copyright Andrew Tridgell 1992-1997\n" ) );
3971
3972   DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
3973         (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
3974
3975   if (sizeof(uint16) < 2 || sizeof(uint32) < 4)
3976     {
3977       DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
3978       exit(1);
3979     }
3980
3981   init_structs();
3982
3983   if (!reload_services(False))
3984     return(-1); 
3985
3986 #ifdef WITH_SSL
3987   {
3988     extern BOOL sslEnabled;
3989     sslEnabled = lp_ssl_enabled();
3990     if(sslEnabled)
3991       sslutil_init(True);
3992   }
3993 #endif        /* WITH_SSL */
3994
3995   codepage_initialise(lp_client_code_page());
3996
3997   pstrcpy(global_myworkgroup, lp_workgroup());
3998
3999   if(!pdb_generate_machine_sid()) {
4000           DEBUG(0,("ERROR: Samba cannot get a machine SID.\n"));
4001           exit(1);
4002   }
4003
4004   CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
4005
4006   /* Setup the signals that allow the debug log level
4007      to by dynamically changed. */
4008  
4009   /* If we are using the malloc debug code we can't use
4010      SIGUSR1 and SIGUSR2 to do debug level changes. */
4011
4012 #ifndef MEM_MAN
4013 #if defined(SIGUSR1)
4014   CatchSignal( SIGUSR1, SIGNAL_CAST sig_usr1 );
4015 #endif /* SIGUSR1 */
4016    
4017 #if defined(SIGUSR2)
4018   CatchSignal( SIGUSR2, SIGNAL_CAST sig_usr2 );
4019 #endif /* SIGUSR2 */
4020 #endif /* MEM_MAN */
4021
4022   DEBUG( 3, ( "loaded services\n" ) );
4023
4024   if (!is_daemon && !is_a_socket(0))
4025     {
4026       DEBUG(0,("standard input is not a socket, assuming -D option\n"));
4027       is_daemon = True;
4028     }
4029
4030   if (is_daemon)
4031     {
4032       DEBUG( 3, ( "Becoming a daemon.\n" ) );
4033       become_daemon();
4034     }
4035
4036   if (!directory_exist(lp_lockdir(), NULL)) {
4037           mkdir(lp_lockdir(), 0755);
4038   }
4039
4040   if (is_daemon) {
4041           pidfile_create("smbd");
4042   }
4043
4044   if (!open_sockets(is_daemon,port))
4045     exit(1);
4046
4047   if (!locking_init(0))
4048     exit(1);
4049
4050   if(!initialize_password_db())
4051     exit(1);
4052
4053   /* possibly reload the services file. */
4054   reload_services(True);
4055
4056   max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
4057
4058   if (*lp_rootdir())
4059     {
4060       if (sys_chroot(lp_rootdir()) == 0)
4061         DEBUG( 2, ( "Changed root to %s\n", lp_rootdir() ) );
4062     }
4063
4064   /* Setup the oplock IPC socket. */
4065   if( !open_oplock_ipc() )
4066     exit(1);
4067
4068   process();
4069   close_sockets();
4070
4071   exit_server("normal exit");
4072   return(0);
4073 }