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