2 Unix SMB/Netbios implementation.
4 Main SMB server routines
5 Copyright (C) Andrew Tridgell 1992-1998
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.
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.
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.
25 pstring servicesf = CONFIGFILE;
26 extern pstring debugf;
27 extern pstring sesssetup_user;
28 extern fstring myworkgroup;
30 char *InBuffer = NULL;
31 char *OutBuffer = NULL;
32 char *last_inbuf = NULL;
37 /* the last message the was processed */
38 int last_message = -1;
40 /* a useful macro to debug the last message processed */
41 #define LAST_MESSAGE() smb_fn_name(last_message)
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;
53 extern int smb_read_error;
55 extern pstring user_socket_options;
58 extern int dcelogin_atmost_once;
61 connection_struct Connections[MAX_CONNECTIONS];
62 files_struct Files[MAX_OPEN_FILES];
65 * Indirection for file fd's. Needed as POSIX locking
66 * is based on file/process, not fd/process.
68 file_fd_struct FileFd[MAX_OPEN_FILES];
69 int max_file_fd_used = 0;
74 * Size of data we can send to client. Set
75 * by the client for all protocols above CORE.
76 * Set by us for CORE protocol.
78 int max_send = BUFFER_SIZE;
80 * Size of the data we can receive. Set by us.
81 * Can be modified by the max xmit parameter.
83 int max_recv = BUFFER_SIZE;
85 /* a fnum to use when chaining */
88 /* number of open connections */
89 static int num_connections_open = 0;
91 /* Oplock ipc UDP socket. */
93 uint16 oplock_port = 0;
94 /* Current number of oplocks we have outstanding. */
95 int32 global_oplocks_open = 0;
97 BOOL global_oplock_break = False;
99 extern fstring remote_machine;
101 extern pstring OriginalDir;
103 /* these can be set by some functions to override the error codes */
104 int unix_ERR_class=SMB_SUCCESS;
108 extern int extra_time_offset;
110 extern pstring myhostname;
112 static int find_free_connection(int hash);
114 /* for readability... */
115 #define IS_DOS_READONLY(test_mode) (((test_mode) & aRONLY) != 0)
116 #define IS_DOS_DIR(test_mode) (((test_mode) & aDIR) != 0)
117 #define IS_DOS_ARCHIVE(test_mode) (((test_mode) & aARCH) != 0)
118 #define IS_DOS_SYSTEM(test_mode) (((test_mode) & aSYSTEM) != 0)
119 #define IS_DOS_HIDDEN(test_mode) (((test_mode) & aHIDDEN) != 0)
121 /****************************************************************************
122 when exiting, take the whole family
123 ****************************************************************************/
126 exit_server("caught signal");
127 return 0; /* Keep -Wall happy :-) */
129 /****************************************************************************
130 Send a SIGTERM to our process group.
131 *****************************************************************************/
134 if(am_parent) kill(0,SIGTERM);
137 /****************************************************************************
138 change a dos mode to a unix mode
139 base permission for files:
140 everybody gets read bit set
141 dos readonly is represented in unix by removing everyone's write bit
142 dos archive is represented in unix by the user's execute bit
143 dos system is represented in unix by the group's execute bit
144 dos hidden is represented in unix by the other's execute bit
145 Then apply create mask,
147 base permission for directories:
148 dos directory is represented in unix by unix's dir bit and the exec bit
149 Then apply create mask,
151 ****************************************************************************/
152 mode_t unix_mode(int cnum,int dosmode)
154 mode_t result = (S_IRUSR | S_IRGRP | S_IROTH);
156 if ( !IS_DOS_READONLY(dosmode) )
157 result |= (S_IWUSR | S_IWGRP | S_IWOTH);
159 if (IS_DOS_DIR(dosmode)) {
160 /* We never make directories read only for the owner as under DOS a user
161 can always create a file in a read-only directory. */
162 result |= (S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH | S_IWUSR);
163 /* Apply directory mask */
164 result &= lp_dir_mode(SNUM(cnum));
165 /* Add in force bits */
166 result |= lp_force_dir_mode(SNUM(cnum));
168 if (MAP_ARCHIVE(cnum) && IS_DOS_ARCHIVE(dosmode))
171 if (MAP_SYSTEM(cnum) && IS_DOS_SYSTEM(dosmode))
174 if (MAP_HIDDEN(cnum) && IS_DOS_HIDDEN(dosmode))
177 /* Apply mode mask */
178 result &= lp_create_mode(SNUM(cnum));
179 /* Add in force bits */
180 result |= lp_force_create_mode(SNUM(cnum));
186 /****************************************************************************
187 change a unix mode to a dos mode
188 ****************************************************************************/
189 int dos_mode(int cnum,char *path,struct stat *sbuf)
192 extern struct current_user current_user;
194 DEBUG(8,("dos_mode: %d %s\n", cnum, path));
196 if (CAN_WRITE(cnum) && !lp_alternate_permissions(SNUM(cnum))) {
197 if (!((sbuf->st_mode & S_IWOTH) ||
198 Connections[cnum].admin_user ||
199 ((sbuf->st_mode & S_IWUSR) && current_user.uid==sbuf->st_uid) ||
200 ((sbuf->st_mode & S_IWGRP) &&
201 in_group(sbuf->st_gid,current_user.gid,
202 current_user.ngroups,current_user.igroups))))
205 if ((sbuf->st_mode & S_IWUSR) == 0)
209 if (MAP_ARCHIVE(cnum) && ((sbuf->st_mode & S_IXUSR) != 0))
212 if (MAP_SYSTEM(cnum) && ((sbuf->st_mode & S_IXGRP) != 0))
215 if (MAP_HIDDEN(cnum) && ((sbuf->st_mode & S_IXOTH) != 0))
218 if (S_ISDIR(sbuf->st_mode))
219 result = aDIR | (result & aRONLY);
223 if (S_ISLNK(sbuf->st_mode) && S_ISDIR(sbuf->st_mode))
228 /* hide files with a name starting with a . */
229 if (lp_hide_dot_files(SNUM(cnum)))
231 char *p = strrchr(path,'/');
237 if (p[0] == '.' && p[1] != '.' && p[1] != 0)
241 /* Optimization : Only call is_hidden_path if it's not already
243 if (!(result & aHIDDEN) && IS_HIDDEN_PATH(cnum,path))
248 DEBUG(8,("dos_mode returning "));
250 if (result & aHIDDEN) DEBUG(8, ("h"));
251 if (result & aRONLY ) DEBUG(8, ("r"));
252 if (result & aSYSTEM) DEBUG(8, ("s"));
253 if (result & aDIR ) DEBUG(8, ("d"));
254 if (result & aARCH ) DEBUG(8, ("a"));
261 /*******************************************************************
262 chmod a file - but preserve some bits
263 ********************************************************************/
264 int dos_chmod(int cnum,char *fname,int dosmode,struct stat *st)
273 if (sys_stat(fname,st)) return(-1);
276 if (S_ISDIR(st->st_mode)) dosmode |= aDIR;
278 if (dos_mode(cnum,fname,st) == dosmode) return(0);
280 unixmode = unix_mode(cnum,dosmode);
282 /* preserve the s bits */
283 mask |= (S_ISUID | S_ISGID);
285 /* preserve the t bit */
290 /* possibly preserve the x bits */
291 if (!MAP_ARCHIVE(cnum)) mask |= S_IXUSR;
292 if (!MAP_SYSTEM(cnum)) mask |= S_IXGRP;
293 if (!MAP_HIDDEN(cnum)) mask |= S_IXOTH;
295 unixmode |= (st->st_mode & mask);
297 /* if we previously had any r bits set then leave them alone */
298 if ((tmp = st->st_mode & (S_IRUSR|S_IRGRP|S_IROTH))) {
299 unixmode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
303 /* if we previously had any w bits set then leave them alone
304 if the new mode is not rdonly */
305 if (!IS_DOS_READONLY(dosmode) &&
306 (tmp = st->st_mode & (S_IWUSR|S_IWGRP|S_IWOTH))) {
307 unixmode &= ~(S_IWUSR|S_IWGRP|S_IWOTH);
311 return(sys_chmod(fname,unixmode));
314 /*******************************************************************
315 Wrapper around sys_utime that possibly allows DOS semantics rather
317 *******************************************************************/
319 int file_utime(int cnum, char *fname, struct utimbuf *times)
321 extern struct current_user current_user;
327 if(sys_utime(fname, times) == 0)
330 if((errno != EPERM) && (errno != EACCES))
333 if(!lp_dos_filetimes(SNUM(cnum)))
336 /* We have permission (given by the Samba admin) to
337 break POSIX semantics and allow a user to change
338 the time on a file they don't own but can write to
342 if(sys_stat(fname,&sb) != 0)
345 /* Check if we have write access. */
346 if (CAN_WRITE(cnum)) {
347 if (((sb.st_mode & S_IWOTH) ||
348 Connections[cnum].admin_user ||
349 ((sb.st_mode & S_IWUSR) && current_user.uid==sb.st_uid) ||
350 ((sb.st_mode & S_IWGRP) &&
351 in_group(sb.st_gid,current_user.gid,
352 current_user.ngroups,current_user.igroups)))) {
353 /* We are allowed to become root and change the filetime. */
355 ret = sys_utime(fname, times);
356 unbecome_root(False);
363 /*******************************************************************
364 Change a filetime - possibly allowing DOS semantics.
365 *******************************************************************/
367 BOOL set_filetime(int cnum, char *fname, time_t mtime)
369 struct utimbuf times;
371 if (null_mtime(mtime)) return(True);
373 times.modtime = times.actime = mtime;
375 if (file_utime(cnum, fname, ×)) {
376 DEBUG(4,("set_filetime(%s) failed: %s\n",fname,strerror(errno)));
382 /****************************************************************************
383 check if two filenames are equal
385 this needs to be careful about whether we are case sensitive
386 ****************************************************************************/
387 static BOOL fname_equal(char *name1, char *name2)
389 int l1 = strlen(name1);
390 int l2 = strlen(name2);
392 /* handle filenames ending in a single dot */
393 if (l1-l2 == 1 && name1[l1-1] == '.' && lp_strip_dot())
397 ret = fname_equal(name1,name2);
402 if (l2-l1 == 1 && name2[l2-1] == '.' && lp_strip_dot())
406 ret = fname_equal(name1,name2);
411 /* now normal filename handling */
413 return(strcmp(name1,name2) == 0);
415 return(strequal(name1,name2));
419 /****************************************************************************
420 mangle the 2nd name and check if it is then equal to the first name
421 ****************************************************************************/
422 static BOOL mangled_equal(char *name1, char *name2)
426 if (is_8_3(name2, True))
429 strcpy(tmpname,name2);
430 mangle_name_83(tmpname);
432 return(strequal(name1,tmpname));
436 /****************************************************************************
437 scan a directory to find a filename, matching without case sensitivity
439 If the name looks like a mangled name then try via the mangling functions
440 ****************************************************************************/
441 static BOOL scan_directory(char *path, char *name,int cnum,BOOL docache)
448 mangled = is_mangled(name);
450 /* handle null paths */
454 if (docache && (dname = DirCacheCheck(path,name,SNUM(cnum)))) {
460 * The incoming name can be mangled, and if we de-mangle it
461 * here it will not compare correctly against the filename (name2)
462 * read from the directory and then mangled by the name_map_mangle()
463 * call. We need to mangle both names or neither.
467 mangled = !check_mangled_stack(name);
469 /* open the directory */
470 if (!(cur_dir = OpenDir(cnum, path, True)))
472 DEBUG(3,("scan dir didn't open dir [%s]\n",path));
476 /* now scan for matching names */
477 while ((dname = ReadDirName(cur_dir)))
480 (strequal(dname,".") || strequal(dname,"..")))
483 pstrcpy(name2,dname);
484 if (!name_map_mangle(name2,False,SNUM(cnum))) continue;
486 if ((mangled && mangled_equal(name,name2))
487 || fname_equal(name, name2))
489 /* we've found the file, change it's name and return */
490 if (docache) DirCacheAdd(path,name,dname,SNUM(cnum));
501 /****************************************************************************
502 This routine is called to convert names from the dos namespace to unix
503 namespace. It needs to handle any case conversions, mangling, format
506 We assume that we have already done a chdir() to the right "root" directory
509 The function will return False if some part of the name except for the last
510 part cannot be resolved
512 If the saved_last_component != 0, then the unmodified last component
513 of the pathname is returned there. This is used in an exceptional
514 case in reply_mv (so far). If saved_last_component == 0 then nothing
517 The bad_path arg is set to True if the filename walk failed. This is
518 used to pick the correct error code to return between ENOENT and ENOTDIR
519 as Windows applications depend on ERRbadpath being returned if a component
520 of a pathname does not exist.
521 ****************************************************************************/
522 BOOL unix_convert(char *name,int cnum,pstring saved_last_component, BOOL *bad_path)
532 if(saved_last_component)
533 *saved_last_component = 0;
535 /* convert to basic unix format - removing \ chars and cleaning it up */
537 unix_clean_name(name);
539 /* names must be relative to the root of the service - trim any leading /.
540 also trim trailing /'s */
541 trim_string(name,"/","/");
544 * Ensure saved_last_component is valid even if file exists.
546 if(saved_last_component) {
547 end = strrchr(name, '/');
549 strcpy(saved_last_component, end + 1);
551 strcpy(saved_last_component, name);
554 if (!case_sensitive &&
555 (!case_preserve || (is_8_3(name, False) && !short_case_preserve)))
558 /* check if it's a printer file */
559 if (Connections[cnum].printer)
561 if ((! *name) || strchr(name,'/') || !is_8_3(name, True))
565 sprintf(name2,"%.6s.XXXXXX",remote_machine);
566 /* sanitise the name */
567 for (s=name2 ; *s ; s++)
568 if (!issafe(*s)) *s = '_';
569 strcpy(name,(char *)mktemp(name2));
574 /* stat the name - if it exists then we are all done! */
575 if (sys_stat(name,&st) == 0)
580 DEBUG(5,("unix_convert(%s,%d)\n",name,cnum));
582 /* a special case - if we don't have any mangling chars and are case
583 sensitive then searching won't help */
584 if (case_sensitive && !is_mangled(name) &&
585 !lp_strip_dot() && !use_mangled_map && (saved_errno != ENOENT))
588 /* now we need to recursively match the name against the real
589 directory structure */
592 while (strncmp(start,"./",2) == 0)
595 /* now match each part of the path name separately, trying the names
596 as is first, then trying to scan the directory for matching names */
597 for (;start;start = (end?end+1:(char *)NULL))
599 /* pinpoint the end of this section of the filename */
600 end = strchr(start, '/');
602 /* chop the name at this point */
605 if(saved_last_component != 0)
606 strcpy(saved_last_component, end ? end + 1 : start);
608 /* check if the name exists up to this point */
609 if (sys_stat(name, &st) == 0)
611 /* it exists. it must either be a directory or this must be
612 the last part of the path for it to be OK */
613 if (end && !(st.st_mode & S_IFDIR))
615 /* an intermediate part of the name isn't a directory */
616 DEBUG(5,("Not a dir %s\n",start));
627 /* remember the rest of the pathname so it can be restored
629 if (end) pstrcpy(rest,end+1);
631 /* try to find this part of the path in the directory */
632 if (strchr(start,'?') || strchr(start,'*') ||
633 !scan_directory(dirpath, start, cnum, end?True:False))
637 /* an intermediate part of the name can't be found */
638 DEBUG(5,("Intermediate not found %s\n",start));
640 /* We need to return the fact that the intermediate
641 name resolution failed. This is used to return an
642 error of ERRbadpath rather than ERRbadfile. Some
643 Windows applications depend on the difference between
650 /* just the last part of the name doesn't exist */
651 /* we may need to strupper() or strlower() it in case
652 this conversion is being used for file creation
654 /* if the filename is of mixed case then don't normalise it */
655 if (!case_preserve &&
656 (!strhasupper(start) || !strhaslower(start)))
659 /* check on the mangled stack to see if we can recover the
660 base of the filename */
661 if (is_mangled(start))
662 check_mangled_stack(start);
664 DEBUG(5,("New file %s\n",start));
668 /* restore the rest of the string */
671 strcpy(start+strlen(start)+1,rest);
672 end = start + strlen(start);
676 /* add to the dirpath that we have resolved so far */
677 if (*dirpath) strcat(dirpath,"/");
678 strcat(dirpath,start);
680 /* restore the / that we wiped out earlier */
684 /* the name has been resolved */
685 DEBUG(5,("conversion finished %s\n",name));
690 /****************************************************************************
691 normalise for DOS usage
692 ****************************************************************************/
693 static void disk_norm(int *bsize,int *dfree,int *dsize)
695 /* check if the disk is beyond the max disk size */
696 int maxdisksize = lp_maxdisksize();
698 /* convert to blocks - and don't overflow */
699 maxdisksize = ((maxdisksize*1024)/(*bsize))*1024;
700 if (*dsize > maxdisksize) *dsize = maxdisksize;
701 if (*dfree > maxdisksize) *dfree = maxdisksize-1; /* the -1 should stop
706 while (*dfree > WORDMAX || *dsize > WORDMAX || *bsize < 512)
711 if (*bsize > WORDMAX )
714 if (*dsize > WORDMAX)
716 if (*dfree > WORDMAX)
723 /****************************************************************************
724 return number of 1K blocks available on a path and total number
725 ****************************************************************************/
726 int disk_free(char *path,int *bsize,int *dfree,int *dsize)
728 char *df_command = lp_dfree_command();
749 /* possibly use system() to get the result */
750 if (df_command && *df_command)
756 sprintf(outfile,"%s/dfree.smb.%d",tmpdir(),(int)getpid());
757 sprintf(syscmd,"%s %s",df_command,path);
758 standard_sub_basic(syscmd);
760 ret = smbrun(syscmd,outfile,False);
761 DEBUG(3,("Running the command `%s' gave %d\n",syscmd,ret));
764 FILE *f = fopen(outfile,"r");
770 fscanf(f,"%d %d %d",dsize,dfree,bsize);
774 DEBUG(0,("Can't open %s\n",outfile));
778 disk_norm(bsize,dfree,dsize);
779 dfree_retval = ((*bsize)/1024)*(*dfree);
781 /* Ensure we return the min value between the users quota and
782 what's free on the disk. Thanks to Albrecht Gebhardt
783 <albrecht.gebhardt@uni-klu.ac.at> for this fix.
785 if (disk_quotas(path, &bsizeq, &dfreeq, &dsizeq))
787 disk_norm(&bsizeq, &dfreeq, &dsizeq);
788 dfreeq_retval = ((bsizeq)/1024)*(dfreeq);
789 dfree_retval = ( dfree_retval < dfreeq_retval ) ?
790 dfree_retval : dfreeq_retval ;
791 /* maybe dfree and dfreeq are calculated using different bsizes
792 so convert dfree from bsize into bsizeq */
793 /* avoid overflows due to multiplication, so do not:
794 *dfree = ((*dfree) * (*bsize)) / (bsizeq);
795 bsize and bsizeq are powers of 2 so its better to
796 to divide them getting a multiplication or division factor
797 for dfree. Rene Nieuwenhuizen (07-10-1997) */
798 if (*bsize >= bsizeq)
799 *dfree = *dfree * (*bsize / bsizeq);
801 *dfree = *dfree / (bsizeq / *bsize);
802 *dfree = ( *dfree < dfreeq ) ? *dfree : dfreeq ;
807 return(dfree_retval);
811 DEBUG(1,("Warning - no statfs function\n"));
815 if (statfs(path,&fs,sizeof(fs),0) != 0)
818 if (statvfs(path, &fs))
821 if (statfs(path,&fs,sizeof(fs)) == -1)
823 if (statfs(path,&fs) == -1)
825 #endif /* USE_STATVFS */
828 DEBUG(3,("dfree call failed code errno=%d\n",errno));
832 return(((*bsize)/1024)*(*dfree));
837 *dfree = fs.fd_req.bfree;
838 *dsize = fs.fd_req.btot;
841 *bsize = fs.f_frsize;
844 /* eg: osf1 has f_fsize = fundamental filesystem block size,
845 f_bsize = optimal transfer block size (MX: 94-04-19) */
850 #endif /* USE_STATVFS */
855 *dfree = fs.f_bavail;
857 *dsize = fs.f_blocks;
860 #if defined(SCO) || defined(ISC) || defined(MIPS)
864 /* handle rediculous bsize values - some OSes are broken */
865 if ((*bsize) < 512 || (*bsize)>0xFFFF) *bsize = 1024;
867 disk_norm(bsize,dfree,dsize);
873 DEBUG(0,("dfree seems to be broken on your system\n"));
874 *dsize = 20*1024*1024/(*bsize);
875 *dfree = MAX(1,*dfree);
877 dfree_retval = ((*bsize)/1024)*(*dfree);
879 /* Ensure we return the min value between the users quota and
880 what's free on the disk. Thanks to Albrecht Gebhardt
881 <albrecht.gebhardt@uni-klu.ac.at> for this fix.
883 if (disk_quotas(path, &bsizeq, &dfreeq, &dsizeq))
885 disk_norm(&bsizeq, &dfreeq, &dsizeq);
886 dfreeq_retval = ((bsizeq)/1024)*(dfreeq);
887 dfree_retval = ( dfree_retval < dfreeq_retval ) ?
888 dfree_retval : dfreeq_retval ;
889 /* maybe dfree and dfreeq are calculated using different bsizes
890 so convert dfree from bsize into bsizeq */
891 /* avoid overflows due to multiplication, so do not:
892 *dfree = ((*dfree) * (*bsize)) / (bsizeq);
893 bsize and bsizeq are powers of 2 so its better to
894 to divide them getting a multiplication or division factor
895 for dfree. Rene Nieuwenhuizen (07-10-1997) */
896 if (*bsize >= bsizeq)
897 *dfree = *dfree * (*bsize / bsizeq);
899 *dfree = *dfree / (bsizeq / *bsize);
900 *dfree = ( *dfree < dfreeq ) ? *dfree : dfreeq ;
905 return(dfree_retval);
910 /****************************************************************************
911 wrap it to get filenames right
912 ****************************************************************************/
913 int sys_disk_free(char *path,int *bsize,int *dfree,int *dsize)
915 return(disk_free(dos_to_unix(path,False),bsize,dfree,dsize));
920 /****************************************************************************
921 check a filename - possibly caling reducename
923 This is called by every routine before it allows an operation on a filename.
924 It does any final confirmation necessary to ensure that the filename is
925 a valid one for the user to access.
926 ****************************************************************************/
927 BOOL check_name(char *name,int cnum)
933 if( IS_VETO_PATH(cnum, name))
935 DEBUG(5,("file path name %s vetoed\n",name));
939 ret = reduce_name(name,Connections[cnum].connectpath,lp_widelinks(SNUM(cnum)));
941 /* Check if we are allowing users to follow symlinks */
942 /* Patch from David Clerc <David.Clerc@cui.unige.ch>
943 University of Geneva */
946 if (!lp_symlinks(SNUM(cnum)))
949 if ( (sys_lstat(name,&statbuf) != -1) &&
950 (S_ISLNK(statbuf.st_mode)) )
952 DEBUG(3,("check_name: denied: file path name %s is a symlink\n",name));
959 DEBUG(5,("check_name on %s failed\n",name));
964 /****************************************************************************
965 check a filename - possibly caling reducename
966 ****************************************************************************/
967 static void check_for_pipe(char *fname)
969 /* special case of pipe opens */
973 if (strstr(s,"pipe/"))
975 DEBUG(3,("Rejecting named pipe open for %s\n",fname));
976 unix_ERR_class = ERRSRV;
977 unix_ERR_code = ERRaccess;
981 /****************************************************************************
982 fd support routines - attempt to do a sys_open
983 ****************************************************************************/
984 static int fd_attempt_open(char *fname, int flags, int mode)
986 int fd = sys_open(fname,flags,mode);
988 /* Fix for files ending in '.' */
989 if((fd == -1) && (errno == ENOENT) &&
990 (strchr(fname,'.')==NULL))
993 fd = sys_open(fname,flags,mode);
996 #if (defined(ENAMETOOLONG) && defined(HAVE_PATHCONF))
997 if ((fd == -1) && (errno == ENAMETOOLONG))
1000 char *p = strrchr(fname, '/');
1002 if (p == fname) /* name is "/xxx" */
1004 max_len = pathconf("/", _PC_NAME_MAX);
1007 else if ((p == NULL) || (p == fname))
1010 max_len = pathconf(".", _PC_NAME_MAX);
1015 max_len = pathconf(fname, _PC_NAME_MAX);
1019 if (strlen(p) > max_len)
1021 char tmp = p[max_len];
1024 if ((fd = sys_open(fname,flags,mode)) == -1)
1032 /****************************************************************************
1033 fd support routines - attempt to find an already open file by dev
1034 and inode - increments the ref_count of the returned file_fd_struct *.
1035 ****************************************************************************/
1036 static file_fd_struct *fd_get_already_open(struct stat *sbuf)
1039 file_fd_struct *fd_ptr;
1044 for(i = 0; i <= max_file_fd_used; i++) {
1045 fd_ptr = &FileFd[i];
1046 if((fd_ptr->ref_count > 0) &&
1047 (((uint32)sbuf->st_dev) == fd_ptr->dev) &&
1048 (((uint32)sbuf->st_ino) == fd_ptr->inode)) {
1049 fd_ptr->ref_count++;
1051 ("Re-used file_fd_struct %d, dev = %x, inode = %x, ref_count = %d\n",
1052 i, fd_ptr->dev, fd_ptr->inode, fd_ptr->ref_count));
1059 /****************************************************************************
1060 fd support routines - attempt to find a empty slot in the FileFd array.
1061 Increments the ref_count of the returned entry.
1062 ****************************************************************************/
1063 static file_fd_struct *fd_get_new()
1066 file_fd_struct *fd_ptr;
1068 for(i = 0; i < MAX_OPEN_FILES; i++) {
1069 fd_ptr = &FileFd[i];
1070 if(fd_ptr->ref_count == 0) {
1071 fd_ptr->dev = (uint32)-1;
1072 fd_ptr->inode = (uint32)-1;
1074 fd_ptr->fd_readonly = -1;
1075 fd_ptr->fd_writeonly = -1;
1076 fd_ptr->real_open_flags = -1;
1077 fd_ptr->ref_count++;
1078 /* Increment max used counter if neccessary, cuts down
1079 on search time when re-using */
1080 if(i > max_file_fd_used)
1081 max_file_fd_used = i;
1082 DEBUG(3,("Allocated new file_fd_struct %d, dev = %x, inode = %x\n",
1083 i, fd_ptr->dev, fd_ptr->inode));
1087 DEBUG(1,("ERROR! Out of file_fd structures - perhaps increase MAX_OPEN_FILES?\
1092 /****************************************************************************
1093 fd support routines - attempt to re-open an already open fd as O_RDWR.
1094 Save the already open fd (we cannot close due to POSIX file locking braindamage.
1095 ****************************************************************************/
1096 static void fd_attempt_reopen(char *fname, int mode, file_fd_struct *fd_ptr)
1098 int fd = sys_open( fname, O_RDWR, mode);
1103 if(fd_ptr->real_open_flags == O_RDONLY)
1104 fd_ptr->fd_readonly = fd_ptr->fd;
1105 if(fd_ptr->real_open_flags == O_WRONLY)
1106 fd_ptr->fd_writeonly = fd_ptr->fd;
1109 fd_ptr->real_open_flags = O_RDWR;
1112 /****************************************************************************
1113 fd support routines - attempt to close the file referenced by this fd.
1114 Decrements the ref_count and returns it.
1115 ****************************************************************************/
1116 static int fd_attempt_close(file_fd_struct *fd_ptr)
1118 DEBUG(3,("fd_attempt_close on file_fd_struct %d, fd = %d, dev = %x, inode = %x, open_flags = %d, ref_count = %d.\n",
1119 fd_ptr - &FileFd[0],
1120 fd_ptr->fd, fd_ptr->dev, fd_ptr->inode,
1121 fd_ptr->real_open_flags,
1122 fd_ptr->ref_count));
1123 if(fd_ptr->ref_count > 0) {
1124 fd_ptr->ref_count--;
1125 if(fd_ptr->ref_count == 0) {
1126 if(fd_ptr->fd != -1)
1128 if(fd_ptr->fd_readonly != -1)
1129 close(fd_ptr->fd_readonly);
1130 if(fd_ptr->fd_writeonly != -1)
1131 close(fd_ptr->fd_writeonly);
1133 fd_ptr->fd_readonly = -1;
1134 fd_ptr->fd_writeonly = -1;
1135 fd_ptr->real_open_flags = -1;
1136 fd_ptr->dev = (uint32)-1;
1137 fd_ptr->inode = (uint32)-1;
1140 return fd_ptr->ref_count;
1143 /****************************************************************************
1145 ****************************************************************************/
1146 static void open_file(int fnum,int cnum,char *fname1,int flags,int mode, struct stat *sbuf)
1148 extern struct current_user current_user;
1150 struct stat statbuf;
1151 file_fd_struct *fd_ptr;
1152 files_struct *fsp = &Files[fnum];
1153 int accmode = (flags & (O_RDONLY | O_WRONLY | O_RDWR));
1157 fsp->granted_oplock = False;
1160 pstrcpy(fname,fname1);
1162 /* check permissions */
1165 * This code was changed after seeing a client open request
1166 * containing the open mode of (DENY_WRITE/read-only) with
1167 * the 'create if not exist' bit set. The previous code
1168 * would fail to open the file read only on a read-only share
1169 * as it was checking the flags parameter directly against O_RDONLY,
1170 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1174 if (!CAN_WRITE(cnum) && !Connections[cnum].printer) {
1175 /* It's a read-only share - fail if we wanted to write. */
1176 if(accmode != O_RDONLY) {
1177 DEBUG(3,("Permission denied opening %s\n",fname));
1178 check_for_pipe(fname);
1181 else if(flags & O_CREAT) {
1182 /* We don't want to write - but we must make sure that O_CREAT
1183 doesn't create the file if we have write access into the
1190 /* this handles a bug in Win95 - it doesn't say to create the file when it
1192 if (Connections[cnum].printer)
1196 if (flags == O_WRONLY)
1197 DEBUG(3,("Bug in client? Set O_WRONLY without O_CREAT\n"));
1201 * Ensure we have a valid struct stat so we can search the
1205 if(stat(fname, &statbuf) < 0) {
1206 if(errno != ENOENT) {
1207 DEBUG(3,("Error doing stat on file %s (%s)\n",
1208 fname,strerror(errno)));
1210 check_for_pipe(fname);
1220 * Check to see if we have this file already
1221 * open. If we do, just use the already open fd and increment the
1222 * reference count (fd_get_already_open increments the ref_count).
1224 if((fd_ptr = fd_get_already_open(sbuf))!= 0) {
1226 /* File was already open. */
1227 if((flags & O_CREAT) && (flags & O_EXCL)) {
1228 fd_ptr->ref_count--;
1234 * If not opened O_RDWR try
1235 * and do that here - a chmod may have been done
1236 * between the last open and now.
1238 if(fd_ptr->real_open_flags != O_RDWR)
1239 fd_attempt_reopen(fname, mode, fd_ptr);
1242 * Ensure that if we wanted write access
1243 * it has been opened for write, and if we wanted read it
1244 * was open for read.
1246 if(((accmode == O_WRONLY) && (fd_ptr->real_open_flags == O_RDONLY)) ||
1247 ((accmode == O_RDONLY) && (fd_ptr->real_open_flags == O_WRONLY)) ||
1248 ((accmode == O_RDWR) && (fd_ptr->real_open_flags != O_RDWR))) {
1249 DEBUG(3,("Error opening (already open for flags=%d) file %s (%s) (flags=%d)\n",
1250 fd_ptr->real_open_flags, fname,strerror(EACCES),flags));
1251 check_for_pipe(fname);
1252 fd_ptr->ref_count--;
1258 /* We need to allocate a new file_fd_struct (this increments the
1260 if((fd_ptr = fd_get_new()) == 0)
1263 * Whatever the requested flags, attempt read/write access,
1264 * as we don't know what flags future file opens may require.
1265 * If this fails, try again with the required flags.
1266 * Even if we open read/write when only read access was
1267 * requested the setting of the can_write flag in
1268 * the file_struct will protect us from errant
1269 * write requests. We never need to worry about O_APPEND
1270 * as this is not set anywhere in Samba.
1272 fd_ptr->real_open_flags = O_RDWR;
1273 /* Set the flags as needed without the read/write modes. */
1274 open_flags = flags & ~(O_RDWR|O_WRONLY|O_RDONLY);
1275 fd_ptr->fd = fd_attempt_open(fname, open_flags|O_RDWR, mode);
1277 * On some systems opening a file for R/W access on a read only
1278 * filesystems sets errno to EROFS.
1281 if((fd_ptr->fd == -1) && ((errno == EACCES) || (errno == EROFS))) {
1282 #else /* No EROFS */
1283 if((fd_ptr->fd == -1) && (errno == EACCES)) {
1285 if(flags & O_WRONLY) {
1286 fd_ptr->fd = fd_attempt_open(fname, open_flags|O_WRONLY, mode);
1287 fd_ptr->real_open_flags = O_WRONLY;
1289 fd_ptr->fd = fd_attempt_open(fname, open_flags|O_RDONLY, mode);
1290 fd_ptr->real_open_flags = O_RDONLY;
1295 if ((fd_ptr->fd >=0) &&
1296 Connections[cnum].printer && lp_minprintspace(SNUM(cnum))) {
1300 pstrcpy(dname,fname);
1301 p = strrchr(dname,'/');
1303 if (sys_disk_free(dname,&dum1,&dum2,&dum3) <
1304 lp_minprintspace(SNUM(cnum))) {
1305 fd_attempt_close(fd_ptr);
1307 if(fd_ptr->ref_count == 0)
1316 DEBUG(3,("Error opening file %s (%s) (flags=%d)\n",
1317 fname,strerror(errno),flags));
1318 /* Ensure the ref_count is decremented. */
1319 fd_attempt_close(fd_ptr);
1320 check_for_pipe(fname);
1324 if (fd_ptr->fd >= 0)
1328 if(fstat(fd_ptr->fd, &statbuf) == -1) {
1329 /* Error - backout !! */
1330 DEBUG(3,("Error doing fstat on fd %d, file %s (%s)\n",
1331 fd_ptr->fd, fname,strerror(errno)));
1332 /* Ensure the ref_count is decremented. */
1333 fd_attempt_close(fd_ptr);
1338 /* Set the correct entries in fd_ptr. */
1339 fd_ptr->dev = (uint32)sbuf->st_dev;
1340 fd_ptr->inode = (uint32)sbuf->st_ino;
1342 fsp->fd_ptr = fd_ptr;
1343 Connections[cnum].num_files_open++;
1344 fsp->mode = sbuf->st_mode;
1345 GetTimeOfDay(&fsp->open_time);
1346 fsp->vuid = current_user.vuid;
1350 fsp->mmap_ptr = NULL;
1352 fsp->can_lock = True;
1353 fsp->can_read = ((flags & O_WRONLY)==0);
1354 fsp->can_write = ((flags & (O_WRONLY|O_RDWR))!=0);
1355 fsp->share_mode = 0;
1356 fsp->print_file = Connections[cnum].printer;
1357 fsp->modified = False;
1358 fsp->granted_oplock = False;
1359 fsp->sent_oplock_break = False;
1361 string_set(&fsp->name,dos_to_unix(fname,False));
1362 fsp->wbmpx_ptr = NULL;
1365 * If the printer is marked as postscript output a leading
1366 * file identifier to ensure the file is treated as a raw
1368 * This has a similar effect as CtrlD=0 in WIN.INI file.
1369 * tim@fsg.com 09/06/94
1371 if (fsp->print_file && POSTSCRIPT(cnum) &&
1374 DEBUG(3,("Writing postscript line\n"));
1375 write_file(fnum,"%!\n",3);
1378 DEBUG(2,("%s %s opened file %s read=%s write=%s (numopen=%d fnum=%d)\n",
1379 timestring(),Connections[cnum].user,fname,
1380 BOOLSTR(fsp->can_read),BOOLSTR(fsp->can_write),
1381 Connections[cnum].num_files_open,fnum));
1386 /* mmap it if read-only */
1387 if (!fsp->can_write)
1389 fsp->mmap_size = file_size(fname);
1390 fsp->mmap_ptr = (char *)mmap(NULL,fsp->mmap_size,
1391 PROT_READ,MAP_SHARED,fsp->fd_ptr->fd,0);
1393 if (fsp->mmap_ptr == (char *)-1 || !fsp->mmap_ptr)
1395 DEBUG(3,("Failed to mmap() %s - %s\n",fname,strerror(errno)));
1396 fsp->mmap_ptr = NULL;
1402 /*******************************************************************
1404 ********************************************************************/
1405 void sync_file(int fnum)
1408 fsync(Files[fnum].fd_ptr->fd);
1412 /****************************************************************************
1413 run a file if it is a magic script
1414 ****************************************************************************/
1415 static void check_magic(int fnum,int cnum)
1417 if (!*lp_magicscript(SNUM(cnum)))
1420 DEBUG(5,("checking magic for %s\n",Files[fnum].name));
1424 if (!(p = strrchr(Files[fnum].name,'/')))
1425 p = Files[fnum].name;
1429 if (!strequal(lp_magicscript(SNUM(cnum)),p))
1435 pstring magic_output;
1437 pstrcpy(fname,Files[fnum].name);
1439 if (*lp_magicoutput(SNUM(cnum)))
1440 pstrcpy(magic_output,lp_magicoutput(SNUM(cnum)));
1442 sprintf(magic_output,"%s.out",fname);
1445 ret = smbrun(fname,magic_output,False);
1446 DEBUG(3,("Invoking magic command %s gave %d\n",fname,ret));
1452 /****************************************************************************
1453 close a file - possibly invalidating the read prediction
1455 If normal_close is 1 then this came from a normal SMBclose (or equivalent)
1456 operation otherwise it came as the result of some other operation such as
1457 the closing of the connection. In the latter case printing and
1458 magic scripts are not run
1459 ****************************************************************************/
1460 void close_file(int fnum, BOOL normal_close)
1462 files_struct *fs_p = &Files[fnum];
1463 int cnum = fs_p->cnum;
1464 uint32 dev = fs_p->fd_ptr->dev;
1465 uint32 inode = fs_p->fd_ptr->inode;
1468 Files[fnum].reserved = False;
1470 #if USE_READ_PREDICTION
1471 invalidate_read_prediction(fs_p->fd_ptr->fd);
1475 Connections[cnum].num_files_open--;
1478 free((char *)fs_p->wbmpx_ptr);
1479 fs_p->wbmpx_ptr = NULL;
1485 munmap(fs_p->mmap_ptr,fs_p->mmap_size);
1486 fs_p->mmap_ptr = NULL;
1490 if (lp_share_modes(SNUM(cnum)))
1492 lock_share_entry( cnum, dev, inode, &token);
1493 del_share_mode(token, fnum);
1496 fd_attempt_close(fs_p->fd_ptr);
1498 if (lp_share_modes(SNUM(cnum)))
1499 unlock_share_entry( cnum, dev, inode, token);
1501 /* NT uses smbclose to start a print - weird */
1502 if (normal_close && fs_p->print_file)
1505 /* check for magic scripts */
1507 check_magic(fnum,cnum);
1509 if(fs_p->granted_oplock == True)
1510 global_oplocks_open--;
1512 fs_p->sent_oplock_break = False;
1514 DEBUG(2,("%s %s closed file %s (numopen=%d)\n",
1515 timestring(),Connections[cnum].user,fs_p->name,
1516 Connections[cnum].num_files_open));
1519 enum {AFAIL,AREAD,AWRITE,AALL};
1521 /*******************************************************************
1522 reproduce the share mode access table
1523 ********************************************************************/
1524 static int access_table(int new_deny,int old_deny,int old_mode,
1525 int share_pid,char *fname)
1527 if (new_deny == DENY_ALL || old_deny == DENY_ALL) return(AFAIL);
1529 if (new_deny == DENY_DOS || old_deny == DENY_DOS) {
1531 if (old_deny == new_deny && share_pid == pid)
1534 if (old_mode == 0) return(AREAD);
1536 /* the new smbpub.zip spec says that if the file extension is
1537 .com, .dll, .exe or .sym then allow the open. I will force
1538 it to read-only as this seems sensible although the spec is
1539 a little unclear on this. */
1540 if ((fname = strrchr(fname,'.'))) {
1541 if (strequal(fname,".com") ||
1542 strequal(fname,".dll") ||
1543 strequal(fname,".exe") ||
1544 strequal(fname,".sym"))
1554 if (old_deny==DENY_WRITE && old_mode==0) return(AREAD);
1555 if (old_deny==DENY_READ && old_mode==0) return(AWRITE);
1556 if (old_deny==DENY_NONE && old_mode==0) return(AALL);
1559 if (old_deny==DENY_WRITE && old_mode==1) return(AREAD);
1560 if (old_deny==DENY_READ && old_mode==1) return(AWRITE);
1561 if (old_deny==DENY_NONE && old_mode==1) return(AALL);
1564 if (old_deny==DENY_WRITE) return(AREAD);
1565 if (old_deny==DENY_READ) return(AWRITE);
1566 if (old_deny==DENY_NONE) return(AALL);
1572 /*******************************************************************
1573 check if the share mode on a file allows it to be deleted or unlinked
1574 return True if sharing doesn't prevent the operation
1575 ********************************************************************/
1576 BOOL check_file_sharing(int cnum,char *fname, BOOL rename_op)
1580 share_mode_entry *old_shares = 0;
1581 int num_share_modes;
1587 if(!lp_share_modes(SNUM(cnum)))
1590 if (stat(fname,&sbuf) == -1) return(True);
1592 dev = (uint32)sbuf.st_dev;
1593 inode = (uint32)sbuf.st_ino;
1595 lock_share_entry(cnum, dev, inode, &token);
1596 num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
1599 * Check if the share modes will give us access.
1602 if(num_share_modes != 0)
1609 broke_oplock = False;
1610 for(i = 0; i < num_share_modes; i++)
1612 share_mode_entry *share_entry = &old_shares[i];
1615 * Break oplocks before checking share modes. See comment in
1616 * open_file_shared for details.
1617 * Check if someone has an oplock on this file. If so we must
1618 * break it before continuing.
1620 if(share_entry->op_type & BATCH_OPLOCK)
1624 * It appears that the NT redirector may have a bug, in that
1625 * it tries to do an SMBmv on a file that it has open with a
1626 * batch oplock, and then fails to respond to the oplock break
1627 * request. This only seems to occur when the client is doing an
1628 * SMBmv to the smbd it is using - thus we try and detect this
1629 * condition by checking if the file being moved is open and oplocked by
1630 * this smbd process, and then not sending the oplock break in this
1631 * special case. If the file was open with a deny mode that
1632 * prevents the move the SMBmv will fail anyway with a share
1633 * violation error. JRA.
1635 if(rename_op && (share_entry->pid == pid))
1637 DEBUG(0,("check_file_sharing: NT redirector workaround - rename attempted on \
1638 batch oplocked file %s, dev = %x, inode = %x\n", fname, dev, inode));
1640 * This next line is a test that allows the deny-mode
1641 * processing to be skipped. This seems to be needed as
1642 * NT insists on the rename succeeding (in Office 9x no less !).
1643 * This should be removed as soon as (a) MS fix the redirector
1644 * bug or (b) NT SMB support in Samba makes NT not issue the
1645 * call (as is my fervent hope). JRA.
1651 DEBUG(5,("check_file_sharing: breaking oplock (%x) on file %s, \
1652 dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
1654 /* Oplock break.... */
1655 unlock_share_entry(cnum, dev, inode, token);
1656 if(request_oplock_break(share_entry, dev, inode) == False)
1658 free((char *)old_shares);
1659 DEBUG(0,("check_file_sharing: FAILED when breaking oplock (%x) on file %s, \
1660 dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
1663 lock_share_entry(cnum, dev, inode, &token);
1664 broke_oplock = True;
1669 /* someone else has a share lock on it, check to see
1671 if ((share_entry->share_mode != DENY_DOS) || (share_entry->pid != pid))
1678 free((char *)old_shares);
1679 num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
1681 } while(broke_oplock);
1684 /* XXXX exactly what share mode combinations should be allowed for
1685 deleting/renaming? */
1686 /* If we got here then either there were no share modes or
1687 all share modes were DENY_DOS and the pid == getpid() */
1692 unlock_share_entry(cnum, dev, inode, token);
1693 if(old_shares != NULL)
1694 free((char *)old_shares);
1698 /****************************************************************************
1700 Helper for open_file_shared.
1701 Truncate a file after checking locking; close file if locked.
1702 **************************************************************************/
1703 static void truncate_unless_locked(int fnum, int cnum, int token,
1706 if (Files[fnum].can_write){
1707 if (is_locked(fnum,cnum,0x3FFFFFFF,0)){
1708 /* If share modes are in force for this connection we
1709 have the share entry locked. Unlock it before closing. */
1710 if (*share_locked && lp_share_modes(SNUM(cnum)))
1711 unlock_share_entry( cnum, Files[fnum].fd_ptr->dev,
1712 Files[fnum].fd_ptr->inode, token);
1713 close_file(fnum,False);
1714 /* Share mode no longer locked. */
1715 *share_locked = False;
1717 unix_ERR_class = ERRDOS;
1718 unix_ERR_code = ERRlock;
1721 ftruncate(Files[fnum].fd_ptr->fd,0);
1725 /****************************************************************************
1726 check if we can open a file with a share mode
1727 ****************************************************************************/
1728 int check_share_mode( share_mode_entry *share, int deny_mode, char *fname,
1729 BOOL fcbopen, int *flags)
1731 int old_open_mode = share->share_mode &0xF;
1732 int old_deny_mode = (share->share_mode >>4)&7;
1734 if (old_deny_mode > 4 || old_open_mode > 2)
1736 DEBUG(0,("Invalid share mode found (%d,%d,%d) on file %s\n",
1737 deny_mode,old_deny_mode,old_open_mode,fname));
1742 int access_allowed = access_table(deny_mode,old_deny_mode,old_open_mode,
1745 if ((access_allowed == AFAIL) ||
1746 (!fcbopen && (access_allowed == AREAD && *flags == O_RDWR)) ||
1747 (access_allowed == AREAD && *flags == O_WRONLY) ||
1748 (access_allowed == AWRITE && *flags == O_RDONLY))
1750 DEBUG(2,("Share violation on file (%d,%d,%d,%d,%s,fcbopen = %d, flags = %d) = %d\n",
1751 deny_mode,old_deny_mode,old_open_mode,
1752 share->pid,fname, fcbopen, *flags, access_allowed));
1756 if (access_allowed == AREAD)
1759 if (access_allowed == AWRITE)
1766 /****************************************************************************
1767 open a file with a share mode
1768 ****************************************************************************/
1769 void open_file_shared(int fnum,int cnum,char *fname,int share_mode,int ofun,
1770 int mode,int oplock_request, int *Access,int *action)
1772 files_struct *fs_p = &Files[fnum];
1775 int deny_mode = (share_mode>>4)&7;
1777 BOOL file_existed = file_exist(fname,&sbuf);
1778 BOOL share_locked = False;
1779 BOOL fcbopen = False;
1783 int num_share_modes = 0;
1788 /* this is for OS/2 EAs - try and say we don't support them */
1789 if (strstr(fname,".+,;=[]."))
1791 unix_ERR_class = ERRDOS;
1792 /* OS/2 Workplace shell fix may be main code stream in a later release. */
1793 #if 1 /* OS2_WPS_FIX - Recent versions of OS/2 need this. */
1794 unix_ERR_code = ERRcannotopen;
1795 #else /* OS2_WPS_FIX */
1796 unix_ERR_code = ERROR_EAS_NOT_SUPPORTED;
1797 #endif /* OS2_WPS_FIX */
1802 if ((ofun & 0x3) == 0 && file_existed)
1810 if ((ofun & 0x3) == 2)
1813 /* note that we ignore the append flag as
1814 append does not mean the same thing under dos and unix */
1816 switch (share_mode&0xF)
1833 if (flags != O_RDONLY && file_existed &&
1834 (!CAN_WRITE(cnum) || IS_DOS_READONLY(dos_mode(cnum,fname,&sbuf))))
1844 if (deny_mode > DENY_NONE && deny_mode!=DENY_FCB)
1846 DEBUG(2,("Invalid deny mode %d on file %s\n",deny_mode,fname));
1851 if (deny_mode == DENY_FCB) deny_mode = DENY_DOS;
1853 if (lp_share_modes(SNUM(cnum)))
1856 share_mode_entry *old_shares = 0;
1860 dev = (uint32)sbuf.st_dev;
1861 inode = (uint32)sbuf.st_ino;
1862 lock_share_entry(cnum, dev, inode, &token);
1863 share_locked = True;
1864 num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
1868 * Check if the share modes will give us access.
1871 if(share_locked && (num_share_modes != 0))
1878 broke_oplock = False;
1879 for(i = 0; i < num_share_modes; i++)
1881 share_mode_entry *share_entry = &old_shares[i];
1884 * By observation of NetBench, oplocks are broken *before* share
1885 * modes are checked. This allows a file to be closed by the client
1886 * if the share mode would deny access and the client has an oplock.
1887 * Check if someone has an oplock on this file. If so we must break
1888 * it before continuing.
1890 if(share_entry->op_type & (EXCLUSIVE_OPLOCK|BATCH_OPLOCK))
1893 DEBUG(5,("open_file_shared: breaking oplock (%x) on file %s, \
1894 dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
1896 /* Oplock break.... */
1897 unlock_share_entry(cnum, dev, inode, token);
1898 if(request_oplock_break(share_entry, dev, inode) == False)
1900 free((char *)old_shares);
1901 DEBUG(0,("open_file_shared: FAILED when breaking oplock (%x) on file %s, \
1902 dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
1904 unix_ERR_class = ERRDOS;
1905 unix_ERR_code = ERRbadshare;
1908 lock_share_entry(cnum, dev, inode, &token);
1909 broke_oplock = True;
1913 /* someone else has a share lock on it, check to see
1915 if(check_share_mode(share_entry, deny_mode, fname, fcbopen, &flags) == False)
1917 free((char *)old_shares);
1918 unlock_share_entry(cnum, dev, inode, token);
1920 unix_ERR_class = ERRDOS;
1921 unix_ERR_code = ERRbadshare;
1929 free((char *)old_shares);
1930 num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
1932 } while(broke_oplock);
1936 free((char *)old_shares);
1939 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o\n",
1940 flags,flags2,mode));
1942 open_file(fnum,cnum,fname,flags|(flags2&~(O_TRUNC)),mode,file_existed ? &sbuf : 0);
1943 if (!fs_p->open && flags==O_RDWR && errno!=ENOENT && fcbopen)
1946 open_file(fnum,cnum,fname,flags,mode,file_existed ? &sbuf : 0 );
1953 if((share_locked == False) && lp_share_modes(SNUM(cnum)))
1955 /* We created the file - thus we must now lock the share entry before creating it. */
1956 dev = fs_p->fd_ptr->dev;
1957 inode = fs_p->fd_ptr->inode;
1958 lock_share_entry(cnum, dev, inode, &token);
1959 share_locked = True;
1975 fs_p->share_mode = (deny_mode<<4) | open_mode;
1978 (*Access) = open_mode;
1982 if (file_existed && !(flags2 & O_TRUNC)) *action = 1;
1983 if (!file_existed) *action = 2;
1984 if (file_existed && (flags2 & O_TRUNC)) *action = 3;
1986 /* We must create the share mode entry before truncate as
1987 truncate can fail due to locking and have to close the
1988 file (which expects the share_mode_entry to be there).
1990 if (lp_share_modes(SNUM(cnum)))
1993 /* JRA. Currently this only services Exlcusive and batch
1994 oplocks (no other opens on this file). This needs to
1995 be extended to level II oplocks (multiple reader
1998 if(oplock_request && (num_share_modes == 0) && lp_oplocks(SNUM(cnum)) &&
1999 !IS_VETO_OPLOCK_PATH(cnum,fname))
2001 fs_p->granted_oplock = True;
2002 fs_p->sent_oplock_break = False;
2003 global_oplocks_open++;
2006 DEBUG(5,("open_file_shared: granted oplock (%x) on file %s, \
2007 dev = %x, inode = %x\n", oplock_request, fname, dev, inode));
2015 set_share_mode(token, fnum, port, oplock_request);
2018 if ((flags2&O_TRUNC) && file_existed)
2019 truncate_unless_locked(fnum,cnum,token,&share_locked);
2022 if (share_locked && lp_share_modes(SNUM(cnum)))
2023 unlock_share_entry( cnum, dev, inode, token);
2026 /****************************************************************************
2027 seek a file. Try to avoid the seek if possible
2028 ****************************************************************************/
2029 int seek_file(int fnum,uint32 pos)
2032 if (Files[fnum].print_file && POSTSCRIPT(Files[fnum].cnum))
2035 Files[fnum].pos = (int)(lseek(Files[fnum].fd_ptr->fd,pos+offset,SEEK_SET)
2037 return(Files[fnum].pos);
2040 /****************************************************************************
2042 ****************************************************************************/
2043 int read_file(int fnum,char *data,uint32 pos,int n)
2047 #if USE_READ_PREDICTION
2048 if (!Files[fnum].can_write)
2050 ret = read_predict(Files[fnum].fd_ptr->fd,pos,data,NULL,n);
2059 if (Files[fnum].mmap_ptr)
2061 int num = (Files[fnum].mmap_size > pos) ? (Files[fnum].mmap_size - pos) : -1;
2065 memcpy(data,Files[fnum].mmap_ptr+pos,num);
2077 if (seek_file(fnum,pos) != pos)
2079 DEBUG(3,("Failed to seek to %d\n",pos));
2084 readret = read(Files[fnum].fd_ptr->fd,data,n);
2085 if (readret > 0) ret += readret;
2092 /****************************************************************************
2094 ****************************************************************************/
2095 int write_file(int fnum,char *data,int n)
2097 if (!Files[fnum].can_write) {
2102 if (!Files[fnum].modified) {
2104 Files[fnum].modified = True;
2105 if (fstat(Files[fnum].fd_ptr->fd,&st) == 0) {
2106 int dosmode = dos_mode(Files[fnum].cnum,Files[fnum].name,&st);
2107 if (MAP_ARCHIVE(Files[fnum].cnum) && !IS_DOS_ARCHIVE(dosmode)) {
2108 dos_chmod(Files[fnum].cnum,Files[fnum].name,dosmode | aARCH,&st);
2113 return(write_data(Files[fnum].fd_ptr->fd,data,n));
2117 /****************************************************************************
2118 load parameters specific to a connection/service
2119 ****************************************************************************/
2120 BOOL become_service(int cnum,BOOL do_chdir)
2122 extern char magic_char;
2123 static int last_cnum = -1;
2126 if (!OPEN_CNUM(cnum))
2132 Connections[cnum].lastused = smb_last_time;
2137 ChDir(Connections[cnum].connectpath) != 0 &&
2138 ChDir(Connections[cnum].origpath) != 0)
2140 DEBUG(0,("%s chdir (%s) failed cnum=%d\n",timestring(),
2141 Connections[cnum].connectpath,cnum));
2145 if (cnum == last_cnum)
2150 case_default = lp_defaultcase(snum);
2151 case_preserve = lp_preservecase(snum);
2152 short_case_preserve = lp_shortpreservecase(snum);
2153 case_mangle = lp_casemangle(snum);
2154 case_sensitive = lp_casesensitive(snum);
2155 magic_char = lp_magicchar(snum);
2156 use_mangled_map = (*lp_mangled_map(snum) ? True:False);
2161 /****************************************************************************
2162 find a service entry
2163 ****************************************************************************/
2164 int find_service(char *service)
2168 string_sub(service,"\\","/");
2170 iService = lp_servicenumber(service);
2172 /* now handle the special case of a home directory */
2175 char *phome_dir = get_home_dir(service);
2176 DEBUG(3,("checking for home directory %s gave %s\n",service,
2177 phome_dir?phome_dir:"(NULL)"));
2181 if ((iHomeService = lp_servicenumber(HOMES_NAME)) >= 0)
2183 lp_add_home(service,iHomeService,phome_dir);
2184 iService = lp_servicenumber(service);
2189 /* If we still don't have a service, attempt to add it as a printer. */
2192 int iPrinterService;
2194 if ((iPrinterService = lp_servicenumber(PRINTERS_NAME)) >= 0)
2198 DEBUG(3,("checking whether %s is a valid printer name...\n", service));
2200 if ((pszTemp != NULL) && pcap_printername_ok(service, pszTemp))
2202 DEBUG(3,("%s is a valid printer name\n", service));
2203 DEBUG(3,("adding %s as a printer service\n", service));
2204 lp_add_printer(service,iPrinterService);
2205 iService = lp_servicenumber(service);
2207 DEBUG(0,("failed to add %s as a printer service!\n", service));
2210 DEBUG(3,("%s is not a valid printer name\n", service));
2214 /* just possibly it's a default service? */
2217 char *pdefservice = lp_defaultservice();
2218 if (pdefservice && *pdefservice && !strequal(pdefservice,service)) {
2220 * We need to do a local copy here as lp_defaultservice()
2221 * returns one of the rotating lp_string buffers that
2222 * could get overwritten by the recursive find_service() call
2223 * below. Fix from Josef Hinteregger <joehtg@joehtg.co.at>.
2226 pstrcpy(defservice, pdefservice);
2227 iService = find_service(defservice);
2228 if (iService >= 0) {
2229 string_sub(service,"_","/");
2230 iService = lp_add_service(service,iService);
2236 if (!VALID_SNUM(iService))
2238 DEBUG(0,("Invalid snum %d for %s\n",iService,service));
2243 DEBUG(3,("find_service() failed to find service %s\n", service));
2249 /****************************************************************************
2250 create an error packet from a cached error.
2251 ****************************************************************************/
2252 int cached_error_packet(char *inbuf,char *outbuf,int fnum,int line)
2254 write_bmpx_struct *wbmpx = Files[fnum].wbmpx_ptr;
2256 int32 eclass = wbmpx->wr_errclass;
2257 int32 err = wbmpx->wr_error;
2259 /* We can now delete the auxiliary struct */
2260 free((char *)wbmpx);
2261 Files[fnum].wbmpx_ptr = NULL;
2262 return error_packet(inbuf,outbuf,eclass,err,line);
2271 } unix_smb_errmap[] =
2273 {EPERM,ERRDOS,ERRnoaccess},
2274 {EACCES,ERRDOS,ERRnoaccess},
2275 {ENOENT,ERRDOS,ERRbadfile},
2276 {ENOTDIR,ERRDOS,ERRbadpath},
2277 {EIO,ERRHRD,ERRgeneral},
2278 {EBADF,ERRSRV,ERRsrverror},
2279 {EINVAL,ERRSRV,ERRsrverror},
2280 {EEXIST,ERRDOS,ERRfilexists},
2281 {ENFILE,ERRDOS,ERRnofids},
2282 {EMFILE,ERRDOS,ERRnofids},
2283 {ENOSPC,ERRHRD,ERRdiskfull},
2285 {EDQUOT,ERRHRD,ERRdiskfull},
2288 {ENOTEMPTY,ERRDOS,ERRnoaccess},
2291 {EXDEV,ERRDOS,ERRdiffdevice},
2293 {EROFS,ERRHRD,ERRnowrite},
2297 /****************************************************************************
2298 create an error packet from errno
2299 ****************************************************************************/
2300 int unix_error_packet(char *inbuf,char *outbuf,int def_class,uint32 def_code,int line)
2302 int eclass=def_class;
2306 if (unix_ERR_class != SMB_SUCCESS)
2308 eclass = unix_ERR_class;
2309 ecode = unix_ERR_code;
2310 unix_ERR_class = SMB_SUCCESS;
2315 while (unix_smb_errmap[i].smbclass != 0)
2317 if (unix_smb_errmap[i].unixerror == errno)
2319 eclass = unix_smb_errmap[i].smbclass;
2320 ecode = unix_smb_errmap[i].smbcode;
2327 return(error_packet(inbuf,outbuf,eclass,ecode,line));
2331 /****************************************************************************
2332 create an error packet. Normally called using the ERROR() macro
2333 ****************************************************************************/
2334 int error_packet(char *inbuf,char *outbuf,int error_class,uint32 error_code,int line)
2336 int outsize = set_message(outbuf,0,0,True);
2337 int cmd = CVAL(inbuf,smb_com);
2338 int flgs2 = SVAL(outbuf,smb_flg2);
2340 if ((flgs2 & FLAGS2_32_BIT_ERROR_CODES) == FLAGS2_32_BIT_ERROR_CODES)
2342 SIVAL(outbuf,smb_rcls,error_code);
2344 DEBUG(3,("%s 32 bit error packet at line %d cmd=%d (%s) eclass=%08x [%s]\n",
2345 timestring(), line, cmd, smb_fn_name(cmd), error_code, smb_errstr(outbuf)));
2349 CVAL(outbuf,smb_rcls) = error_class;
2350 SSVAL(outbuf,smb_err,error_code);
2351 DEBUG(3,("%s error packet at line %d cmd=%d (%s) eclass=%d ecode=%d\n",
2354 (int)CVAL(inbuf,smb_com),
2355 smb_fn_name(CVAL(inbuf,smb_com)),
2362 DEBUG(3,("error string = %s\n",strerror(errno)));
2368 #ifndef SIGCLD_IGNORE
2369 /****************************************************************************
2370 this prevents zombie child processes
2371 ****************************************************************************/
2372 static int sig_cld()
2374 static int depth = 0;
2377 DEBUG(0,("ERROR: Recursion in sig_cld? Perhaps you need `#define USE_WAITPID'?\n"));
2383 BlockSignals(True,SIGCLD);
2384 DEBUG(5,("got SIGCLD\n"));
2387 while (sys_waitpid((pid_t)-1,(int *)NULL, WNOHANG) > 0);
2391 /* Stevens, Adv. Unix Prog. says that on system V you must call
2392 wait before reinstalling the signal handler, because the kernel
2393 calls the handler from within the signal-call when there is a
2394 child that has exited. This would lead to an infinite recursion
2395 if done vice versa. */
2397 #ifndef DONT_REINSTALL_SIG
2398 #ifdef SIGCLD_IGNORE
2399 signal(SIGCLD, SIG_IGN);
2401 signal(SIGCLD, SIGNAL_CAST sig_cld);
2406 while (wait3(WAIT3_CAST1 NULL, WNOHANG, WAIT3_CAST2 NULL) > 0);
2409 BlockSignals(False,SIGCLD);
2414 /****************************************************************************
2415 this is called when the client exits abruptly
2416 **************************************************************************/
2417 static int sig_pipe()
2419 struct cli_state *cli;
2420 BlockSignals(True,SIGPIPE);
2422 if ((cli = server_client()) && cli->initialised) {
2423 DEBUG(3,("lost connection to password server\n"));
2425 #ifndef DONT_REINSTALL_SIG
2426 signal(SIGPIPE, SIGNAL_CAST sig_pipe);
2428 BlockSignals(False,SIGPIPE);
2432 exit_server("Got sigpipe\n");
2436 /****************************************************************************
2437 open the socket communication
2438 ****************************************************************************/
2439 static BOOL open_sockets(BOOL is_daemon,int port)
2445 int num_interfaces = iface_count();
2446 int fd_listenset[FD_SETSIZE];
2452 #ifdef SIGCLD_IGNORE
2453 signal(SIGCLD, SIG_IGN);
2455 signal(SIGCLD, SIGNAL_CAST sig_cld);
2461 FD_ZERO(&listen_set);
2463 if(lp_interfaces() && lp_bind_interfaces_only())
2465 /* We have been given an interfaces line, and been
2466 told to only bind to those interfaces. Create a
2467 socket per interface and bind to only these.
2470 if(num_interfaces > FD_SETSIZE)
2472 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
2473 max can be %d\n", num_interfaces, FD_SETSIZE));
2477 /* Now open a listen socket for each of the interfaces. */
2478 for(i = 0; i < num_interfaces; i++)
2480 struct in_addr *ifip = iface_n_ip(i);
2484 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
2487 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr);
2490 /* ready to listen */
2491 if (listen(s, 5) == -1)
2493 DEBUG(0,("listen: %s\n",strerror(errno)));
2497 FD_SET(s,&listen_set);
2502 /* Just bind to 0.0.0.0 - accept connections from anywhere. */
2505 /* open an incoming socket */
2506 s = open_socket_in(SOCK_STREAM, port, 0,interpret_addr(lp_socket_address()));
2510 /* ready to listen */
2511 if (listen(s, 5) == -1)
2513 DEBUG(0,("open_sockets: listen: %s\n",strerror(errno)));
2518 fd_listenset[0] = s;
2519 FD_SET(s,&listen_set);
2522 /* now accept incoming connections - forking a new process
2523 for each incoming connection */
2524 DEBUG(2,("waiting for a connection\n"));
2530 memcpy((char *)&lfds, (char *)&listen_set, sizeof(listen_set));
2532 num = sys_select(&lfds,NULL);
2534 if (num == -1 && errno == EINTR)
2537 /* Find the sockets that are read-ready - accept on these. */
2538 for( ; num > 0; num--)
2540 struct sockaddr addr;
2541 int in_addrlen = sizeof(addr);
2544 for(i = 0; i < num_interfaces; i++)
2546 if(FD_ISSET(fd_listenset[i],&lfds))
2548 s = fd_listenset[i];
2549 /* Clear this so we don't look at it again. */
2550 FD_CLR(fd_listenset[i],&lfds);
2555 Client = accept(s,&addr,&in_addrlen);
2557 if (Client == -1 && errno == EINTR)
2562 DEBUG(0,("open_sockets: accept: %s\n",strerror(errno)));
2566 #ifdef NO_FORK_DEBUG
2567 #ifndef NO_SIGNAL_TEST
2568 signal(SIGPIPE, SIGNAL_CAST sig_pipe);
2569 signal(SIGCLD, SIGNAL_CAST SIG_DFL);
2570 #endif /* NO_SIGNAL_TEST */
2572 #else /* NO_FORK_DEBUG */
2573 if (Client != -1 && fork()==0)
2575 /* Child code ... */
2577 #ifndef NO_SIGNAL_TEST
2578 signal(SIGPIPE, SIGNAL_CAST sig_pipe);
2579 signal(SIGCLD, SIGNAL_CAST SIG_DFL);
2580 #endif /* NO_SIGNAL_TEST */
2581 /* close the listening socket(s) */
2582 for(i = 0; i < num_interfaces; i++)
2583 close(fd_listenset[i]);
2585 /* close our standard file descriptors */
2589 set_socket_options(Client,"SO_KEEPALIVE");
2590 set_socket_options(Client,user_socket_options);
2592 /* Reset global variables in util.c so that
2593 client substitutions will be done correctly
2596 reset_globals_after_fork();
2599 close(Client); /* The parent doesn't need this socket */
2600 #endif /* NO_FORK_DEBUG */
2603 } /* end if is_daemon */
2606 /* Started from inetd. fd 0 is the socket. */
2607 /* We will abort gracefully when the client or remote system
2609 #ifndef NO_SIGNAL_TEST
2610 signal(SIGPIPE, SIGNAL_CAST sig_pipe);
2614 /* close our standard file descriptors */
2617 set_socket_options(Client,"SO_KEEPALIVE");
2618 set_socket_options(Client,user_socket_options);
2624 /****************************************************************************
2625 process an smb from the client - split out from the process() code so
2626 it can be used by the oplock break code.
2627 ****************************************************************************/
2629 static void process_smb(char *inbuf, char *outbuf)
2632 static int trans_num;
2633 int msg_type = CVAL(inbuf,0);
2634 int32 len = smb_len(inbuf);
2635 int nread = len + 4;
2637 if (trans_num == 0) {
2638 /* on the first packet, check the global hosts allow/ hosts
2639 deny parameters before doing any parsing of the packet
2640 passed to us by the client. This prevents attacks on our
2641 parsing code from hosts not in the hosts allow list */
2642 if (!check_access(-1)) {
2643 /* send a negative session response "not listining on calling
2645 static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
2646 DEBUG(1,("%s Connection denied from %s\n",
2647 timestring(),client_addr(Client)));
2648 send_smb(Client,(char *)buf);
2649 exit_server("connection denied");
2653 DEBUG(6,("got message type 0x%x of len 0x%x\n",msg_type,len));
2654 DEBUG(3,("%s Transaction %d of length %d\n",timestring(),trans_num,nread));
2657 if(trans_num == 1 && VT_Check(inbuf))
2666 else if(msg_type == 0x85)
2667 return; /* Keepalive packet. */
2669 nread = construct_reply(inbuf,outbuf,nread,max_send);
2673 if (CVAL(outbuf,0) == 0)
2676 if (nread != smb_len(outbuf) + 4)
2678 DEBUG(0,("ERROR: Invalid message response size! %d %d\n",
2679 nread, smb_len(outbuf)));
2682 send_smb(Client,outbuf);
2687 /****************************************************************************
2688 open the oplock IPC socket communication
2689 ****************************************************************************/
2690 static BOOL open_oplock_ipc()
2692 struct sockaddr_in sock_name;
2693 int len = sizeof(sock_name);
2695 DEBUG(3,("open_oplock_ipc: opening loopback UDP socket.\n"));
2697 /* Open a lookback UDP socket on a random port. */
2698 oplock_sock = open_socket_in(SOCK_DGRAM, 0, 0, htonl(INADDR_LOOPBACK));
2699 if (oplock_sock == -1)
2701 DEBUG(0,("open_oplock_ipc: Failed to get local UDP socket for \
2702 address %x. Error was %s\n", htonl(INADDR_LOOPBACK), strerror(errno)));
2707 /* Find out the transient UDP port we have been allocated. */
2708 if(getsockname(oplock_sock, (struct sockaddr *)&sock_name, &len)<0)
2710 DEBUG(0,("open_oplock_ipc: Failed to get local UDP port. Error was %s\n",
2717 oplock_port = ntohs(sock_name.sin_port);
2719 DEBUG(3,("open_oplock ipc: pid = %d, oplock_port = %u\n",
2720 getpid(), oplock_port));
2725 /****************************************************************************
2726 process an oplock break message.
2727 ****************************************************************************/
2728 static BOOL process_local_message(int sock, char *buffer, int buf_size)
2734 msg_len = IVAL(buffer,UDP_CMD_LEN_OFFSET);
2735 from_port = SVAL(buffer,UDP_CMD_PORT_OFFSET);
2737 msg_start = &buffer[UDP_CMD_HEADER_LEN];
2739 DEBUG(5,("process_local_message: Got a message of length %d from port (%d)\n",
2740 msg_len, from_port));
2742 /* Switch on message command - currently OPLOCK_BREAK_CMD is the
2743 only valid request. */
2745 switch(SVAL(msg_start,UDP_MESSAGE_CMD_OFFSET))
2747 case OPLOCK_BREAK_CMD:
2748 /* Ensure that the msg length is correct. */
2749 if(msg_len != OPLOCK_BREAK_MSG_LEN)
2751 DEBUG(0,("process_local_message: incorrect length for OPLOCK_BREAK_CMD (was %d, \
2752 should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
2756 uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
2757 uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
2758 uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
2759 struct timeval tval;
2760 struct sockaddr_in toaddr;
2762 tval.tv_sec = IVAL(msg_start, OPLOCK_BREAK_SEC_OFFSET);
2763 tval.tv_usec = IVAL(msg_start, OPLOCK_BREAK_USEC_OFFSET);
2765 DEBUG(5,("process_local_message: oplock break request from \
2766 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
2769 * If we have no record of any currently open oplocks,
2770 * it's not an error, as a close command may have
2771 * just been issued on the file that was oplocked.
2772 * Just return success in this case.
2775 if(global_oplocks_open != 0)
2777 if(oplock_break(dev, inode, &tval) == False)
2779 DEBUG(0,("process_local_message: oplock break failed - \
2780 not returning udp message.\n"));
2786 DEBUG(3,("process_local_message: oplock break requested with no outstanding \
2787 oplocks. Returning success.\n"));
2790 /* Send the message back after OR'ing in the 'REPLY' bit. */
2791 SSVAL(msg_start,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD | CMD_REPLY);
2793 bzero((char *)&toaddr,sizeof(toaddr));
2794 toaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2795 toaddr.sin_port = htons(from_port);
2796 toaddr.sin_family = AF_INET;
2798 if(sendto( sock, msg_start, OPLOCK_BREAK_MSG_LEN, 0,
2799 (struct sockaddr *)&toaddr, sizeof(toaddr)) < 0)
2801 DEBUG(0,("process_local_message: sendto process %d failed. Errno was %s\n",
2802 remotepid, strerror(errno)));
2806 DEBUG(5,("process_local_message: oplock break reply sent to \
2807 pid %d, port %d, for file dev = %x, inode = %x\n", remotepid,
2808 from_port, dev, inode));
2813 * Keep this as a debug case - eventually we can remove it.
2816 DEBUG(0,("process_local_message: Received unsolicited break \
2817 reply - dumping info.\n"));
2819 if(msg_len != OPLOCK_BREAK_MSG_LEN)
2821 DEBUG(0,("process_local_message: ubr: incorrect length for reply \
2822 (was %d, should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
2827 uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
2828 uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
2829 uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
2831 DEBUG(0,("process_local_message: unsolicited oplock break reply from \
2832 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
2838 DEBUG(0,("process_local_message: unknown UDP message command code (%x) - ignoring.\n",
2839 (unsigned int)SVAL(msg_start,0)));
2845 /****************************************************************************
2846 Process an oplock break directly.
2847 ****************************************************************************/
2848 BOOL oplock_break(uint32 dev, uint32 inode, struct timeval *tval)
2852 char *outbuf = NULL;
2853 files_struct *fsp = NULL;
2856 BOOL shutdown_server = False;
2858 DEBUG(3,("%s oplock_break: called for dev = %x, inode = %x. Current \
2859 global_oplocks_open = %d\n", timestring(), dev, inode, global_oplocks_open));
2861 /* We need to search the file open table for the
2862 entry containing this dev and inode, and ensure
2863 we have an oplock on it. */
2864 for( fnum = 0; fnum < MAX_OPEN_FILES; fnum++)
2868 if((Files[fnum].fd_ptr->dev == dev) && (Files[fnum].fd_ptr->inode == inode) &&
2869 (Files[fnum].open_time.tv_sec == tval->tv_sec) &&
2870 (Files[fnum].open_time.tv_usec == tval->tv_usec)) {
2879 /* The file could have been closed in the meantime - return success. */
2880 DEBUG(0,("%s oplock_break: cannot find open file with dev = %x, inode = %x (fnum = %d) \
2881 allowing break to succeed.\n", timestring(), dev, inode, fnum));
2885 /* Ensure we have an oplock on the file */
2887 /* There is a potential race condition in that an oplock could
2888 have been broken due to another udp request, and yet there are
2889 still oplock break messages being sent in the udp message
2890 queue for this file. So return true if we don't have an oplock,
2891 as we may have just freed it.
2894 if(!fsp->granted_oplock)
2896 DEBUG(0,("%s oplock_break: file %s (fnum = %d, dev = %x, inode = %x) has no oplock. Allowing break to succeed regardless.\n", timestring(), fsp->name, fnum, dev, inode));
2900 /* mark the oplock break as sent - we don't want to send twice! */
2901 if (fsp->sent_oplock_break)
2903 DEBUG(0,("%s oplock_break: ERROR: oplock_break already sent for file %s (fnum = %d, dev = %x, inode = %x)\n", timestring(), fsp->name, fnum, dev, inode));
2905 /* We have to fail the open here as we cannot send another oplock break on this
2906 file whilst we are awaiting a response from the client - neither can we
2907 allow another open to succeed while we are waiting for the client. */
2911 /* Now comes the horrid part. We must send an oplock break to the client,
2912 and then process incoming messages until we get a close or oplock release.
2913 At this point we know we need a new inbuf/outbuf buffer pair.
2914 We cannot use these staticaly as we may recurse into here due to
2915 messages crossing on the wire.
2918 if((inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
2920 DEBUG(0,("oplock_break: malloc fail for input buffer.\n"));
2924 if((outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
2926 DEBUG(0,("oplock_break: malloc fail for output buffer.\n"));
2932 /* Prepare the SMBlockingX message. */
2933 bzero(outbuf,smb_size);
2934 set_message(outbuf,8,0,True);
2936 SCVAL(outbuf,smb_com,SMBlockingX);
2937 SSVAL(outbuf,smb_tid,fsp->cnum);
2938 SSVAL(outbuf,smb_pid,0xFFFF);
2939 SSVAL(outbuf,smb_uid,0);
2940 SSVAL(outbuf,smb_mid,0xFFFF);
2941 SCVAL(outbuf,smb_vwv0,0xFF);
2942 SSVAL(outbuf,smb_vwv2,fnum);
2943 SCVAL(outbuf,smb_vwv3,LOCKING_ANDX_OPLOCK_RELEASE);
2944 /* Change this when we have level II oplocks. */
2945 SCVAL(outbuf,smb_vwv3+1,OPLOCKLEVEL_NONE);
2947 send_smb(Client, outbuf);
2949 /* Remember we just sent an oplock break on this file. */
2950 fsp->sent_oplock_break = True;
2952 /* We need this in case a readraw crosses on the wire. */
2953 global_oplock_break = True;
2955 /* Process incoming messages. */
2957 /* JRA - If we don't get a break from the client in OPLOCK_BREAK_TIMEOUT
2958 seconds we should just die.... */
2960 start_time = time(NULL);
2962 while(OPEN_FNUM(fnum) && fsp->granted_oplock)
2964 if(receive_smb(Client,inbuf,OPLOCK_BREAK_TIMEOUT * 1000) == False)
2967 * Die if we got an error.
2970 if (smb_read_error == READ_EOF)
2971 DEBUG(0,("%s oplock_break: end of file from client\n", timestring()));
2973 if (smb_read_error == READ_ERROR)
2974 DEBUG(0,("%s oplock_break: receive_smb error (%s)\n",
2975 timestring(), strerror(errno)));
2977 if (smb_read_error == READ_TIMEOUT)
2978 DEBUG(0,("%s oplock_break: receive_smb timed out after %d seconds.\n",
2979 timestring(), OPLOCK_BREAK_TIMEOUT));
2981 DEBUG(0,("%s oplock_break failed for file %s (fnum = %d, dev = %x, \
2982 inode = %x).\n", timestring(), fsp->name, fnum, dev, inode));
2983 shutdown_server = True;
2988 * There are certain SMB requests that we shouldn't allow
2989 * to recurse. opens, renames and deletes are the obvious
2990 * ones. This is handled in the switch_message() function.
2991 * If global_oplock_break is set they will push the packet onto
2992 * the pending smb queue and return -1 (no reply).
2996 process_smb(inbuf, outbuf);
2999 * Die if we go over the time limit.
3002 if((time(NULL) - start_time) > OPLOCK_BREAK_TIMEOUT)
3004 DEBUG(0,("%s oplock_break: no break received from client within \
3005 %d seconds.\n", timestring(), OPLOCK_BREAK_TIMEOUT));
3006 DEBUG(0,("%s oplock_break failed for file %s (fnum = %d, dev = %x, \
3007 inode = %x).\n", timestring(), fsp->name, fnum, dev, inode));
3008 shutdown_server = True;
3013 /* Free the buffers we've been using to recurse. */
3017 /* We need this in case a readraw crossed on the wire. */
3018 if(global_oplock_break)
3019 global_oplock_break = False;
3022 * If the client did not respond we must die.
3027 DEBUG(0,("%s oplock_break: client failure in break - shutting down this smbd.\n",
3031 exit_server("oplock break failure");
3036 /* The lockingX reply will have removed the oplock flag
3037 from the sharemode. */
3039 fsp->granted_oplock = False;
3040 fsp->sent_oplock_break = False;
3041 global_oplocks_open--;
3044 /* Santity check - remove this later. JRA */
3045 if(global_oplocks_open < 0)
3047 DEBUG(0,("oplock_break: global_oplocks_open < 0 (%d). PANIC ERROR\n",
3048 global_oplocks_open));
3049 exit_server("oplock_break: global_oplocks_open < 0");
3052 DEBUG(3,("%s oplock_break: returning success for fnum = %d, dev = %x, inode = %x. Current \
3053 global_oplocks_open = %d\n", timestring(), fnum, dev, inode, global_oplocks_open));
3058 /****************************************************************************
3059 Send an oplock break message to another smbd process. If the oplock is held
3060 by the local smbd then call the oplock break function directly.
3061 ****************************************************************************/
3063 BOOL request_oplock_break(share_mode_entry *share_entry,
3064 uint32 dev, uint32 inode)
3066 char op_break_msg[OPLOCK_BREAK_MSG_LEN];
3067 struct sockaddr_in addr_out;
3072 if(pid == share_entry->pid)
3074 /* We are breaking our own oplock, make sure it's us. */
3075 if(share_entry->op_port != oplock_port)
3077 DEBUG(0,("request_oplock_break: corrupt share mode entry - pid = %d, port = %d \
3078 should be %d\n", pid, share_entry->op_port, oplock_port));
3082 DEBUG(5,("request_oplock_break: breaking our own oplock\n"));
3084 /* Call oplock break direct. */
3085 return oplock_break(dev, inode, &share_entry->time);
3088 /* We need to send a OPLOCK_BREAK_CMD message to the
3089 port in the share mode entry. */
3091 SSVAL(op_break_msg,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD);
3092 SIVAL(op_break_msg,OPLOCK_BREAK_PID_OFFSET,pid);
3093 SIVAL(op_break_msg,OPLOCK_BREAK_DEV_OFFSET,dev);
3094 SIVAL(op_break_msg,OPLOCK_BREAK_INODE_OFFSET,inode);
3095 SIVAL(op_break_msg,OPLOCK_BREAK_SEC_OFFSET,(uint32)share_entry->time.tv_sec);
3096 SIVAL(op_break_msg,OPLOCK_BREAK_USEC_OFFSET,(uint32)share_entry->time.tv_usec);
3098 /* set the address and port */
3099 bzero((char *)&addr_out,sizeof(addr_out));
3100 addr_out.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3101 addr_out.sin_port = htons( share_entry->op_port );
3102 addr_out.sin_family = AF_INET;
3104 DEBUG(3,("%s request_oplock_break: sending a oplock break message to pid %d on port %d \
3105 for dev = %x, inode = %x\n", timestring(), share_entry->pid, share_entry->op_port, dev, inode));
3107 if(sendto(oplock_sock,op_break_msg,OPLOCK_BREAK_MSG_LEN,0,
3108 (struct sockaddr *)&addr_out,sizeof(addr_out)) < 0)
3110 DEBUG(0,("%s request_oplock_break: failed when sending a oplock break message \
3111 to pid %d on port %d for dev = %x, inode = %x. Error was %s\n",
3112 timestring(), share_entry->pid, share_entry->op_port, dev, inode,
3118 * Now we must await the oplock broken message coming back
3119 * from the target smbd process. Timeout if it fails to
3120 * return in (OPLOCK_BREAK_TIMEOUT + OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR) seconds.
3121 * While we get messages that aren't ours, loop.
3124 start_time = time(NULL);
3125 time_left = OPLOCK_BREAK_TIMEOUT+OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR;
3127 while(time_left >= 0)
3129 char op_break_reply[UDP_CMD_HEADER_LEN+OPLOCK_BREAK_MSG_LEN];
3130 int32 reply_msg_len;
3131 uint16 reply_from_port;
3132 char *reply_msg_start;
3134 if(receive_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply),
3135 time_left ? time_left * 1000 : 1) == False)
3137 if(smb_read_error == READ_TIMEOUT)
3139 DEBUG(0,("%s request_oplock_break: no response received to oplock break request to \
3140 pid %d on port %d for dev = %x, inode = %x\n", timestring(), share_entry->pid,
3141 share_entry->op_port, dev, inode));
3143 * This is a hack to make handling of failing clients more robust.
3144 * If a oplock break response message is not received in the timeout
3145 * period we may assume that the smbd servicing that client holding
3146 * the oplock has died and the client changes were lost anyway, so
3147 * we should continue to try and open the file.
3152 DEBUG(0,("%s request_oplock_break: error in response received to oplock break request to \
3153 pid %d on port %d for dev = %x, inode = %x. Error was (%s).\n", timestring, share_entry->pid,
3154 share_entry->op_port, dev, inode, strerror(errno)));
3158 reply_msg_len = IVAL(op_break_reply,UDP_CMD_LEN_OFFSET);
3159 reply_from_port = SVAL(op_break_reply,UDP_CMD_PORT_OFFSET);
3161 reply_msg_start = &op_break_reply[UDP_CMD_HEADER_LEN];
3163 if(reply_msg_len != OPLOCK_BREAK_MSG_LEN)
3166 DEBUG(0,("%s request_oplock_break: invalid message length received. Ignoring\n",
3172 * Test to see if this is the reply we are awaiting.
3175 if((SVAL(reply_msg_start,UDP_MESSAGE_CMD_OFFSET) & CMD_REPLY) &&
3176 (reply_from_port == share_entry->op_port) &&
3177 (memcmp(&reply_msg_start[OPLOCK_BREAK_PID_OFFSET],
3178 &op_break_msg[OPLOCK_BREAK_PID_OFFSET],
3179 OPLOCK_BREAK_MSG_LEN - OPLOCK_BREAK_PID_OFFSET) == 0))
3182 * This is the reply we've been waiting for.
3189 * This is another message - probably a break request.
3190 * Process it to prevent potential deadlock.
3191 * Note that the code in switch_message() prevents
3192 * us from recursing into here as any SMB requests
3193 * we might process that would cause another oplock
3194 * break request to be made will be queued.
3198 process_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply));
3201 time_left -= (time(NULL) - start_time);
3204 DEBUG(3,("%s request_oplock_break: broke oplock.\n", timestring()));
3209 /****************************************************************************
3210 Get the next SMB packet, doing the local message processing automatically.
3211 ****************************************************************************/
3213 BOOL receive_next_smb(int smbfd, int oplockfd, char *inbuf, int bufsize, int timeout)
3215 BOOL got_smb = False;
3220 ret = receive_message_or_smb(smbfd,oplockfd,inbuf,bufsize,
3225 /* Deal with oplock break requests from other smbd's. */
3226 process_local_message(oplock_sock, inbuf, bufsize);
3230 if(ret && (CVAL(inbuf,0) == 0x85))
3232 /* Keepalive packet. */
3237 while(ret && !got_smb);
3242 /****************************************************************************
3243 check if a snum is in use
3244 ****************************************************************************/
3245 BOOL snum_used(int snum)
3248 for (i=0;i<MAX_CONNECTIONS;i++)
3249 if (OPEN_CNUM(i) && (SNUM(i) == snum))
3254 /****************************************************************************
3255 reload the services file
3256 **************************************************************************/
3257 BOOL reload_services(BOOL test)
3264 pstrcpy(fname,lp_configfile());
3265 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf))
3267 pstrcpy(servicesf,fname);
3274 if (test && !lp_file_list_changed())
3277 lp_killunused(snum_used);
3279 ret = lp_load(servicesf,False,False,True);
3281 /* perhaps the config filename is now set */
3283 reload_services(True);
3292 set_socket_options(Client,"SO_KEEPALIVE");
3293 set_socket_options(Client,user_socket_options);
3297 reset_mangled_stack( lp_mangledstack() );
3299 /* this forces service parameters to be flushed */
3300 become_service(-1,True);
3307 /****************************************************************************
3308 this prevents zombie child processes
3309 ****************************************************************************/
3310 static int sig_hup()
3312 BlockSignals(True,SIGHUP);
3313 DEBUG(0,("Got SIGHUP\n"));
3314 reload_services(False);
3315 #ifndef DONT_REINSTALL_SIG
3316 signal(SIGHUP,SIGNAL_CAST sig_hup);
3318 BlockSignals(False,SIGHUP);
3323 /****************************************************************************
3324 make a connection to a service
3325 ****************************************************************************/
3326 int make_connection(char *service,char *user,char *password, int pwlen, char *dev,uint16 vuid)
3330 struct passwd *pass = NULL;
3331 connection_struct *pcon;
3337 snum = find_service(service);
3341 if (strequal(service,"IPC$"))
3343 DEBUG(3,("%s refusing IPC connection\n",timestring()));
3347 DEBUG(0,("%s %s (%s) couldn't find service %s\n",timestring(),remote_machine,client_addr(Client),service));
3351 if (strequal(service,HOMES_NAME))
3353 if (*user && Get_Pwnam(user,True))
3354 return(make_connection(user,user,password,pwlen,dev,vuid));
3356 if(lp_security() != SEC_SHARE)
3358 if (validated_username(vuid))
3360 strcpy(user,validated_username(vuid));
3361 return(make_connection(user,user,password,pwlen,dev,vuid));
3367 * Security = share. Try with sesssetup_user as the username.
3371 strcpy(user,sesssetup_user);
3372 return(make_connection(user,user,password,pwlen,dev,vuid));
3377 if (!lp_snum_ok(snum) || !check_access(snum)) {
3381 /* you can only connect to the IPC$ service as an ipc device */
3382 if (strequal(service,"IPC$"))
3385 if (*dev == '?' || !*dev)
3387 if (lp_print_ok(snum))
3388 strcpy(dev,"LPT1:");
3393 /* if the request is as a printer and you can't print then refuse */
3395 if (!lp_print_ok(snum) && (strncmp(dev,"LPT",3) == 0)) {
3396 DEBUG(1,("Attempt to connect to non-printer as a printer\n"));
3400 /* lowercase the user name */
3403 /* add it as a possible user name */
3404 add_session_user(service);
3406 /* shall we let them in? */
3407 if (!authorise_login(snum,user,password,pwlen,&guest,&force,vuid))
3409 DEBUG(2,("%s invalid username/password for %s\n",timestring(),service));
3413 cnum = find_free_connection(str_checksum(service) + str_checksum(user));
3416 DEBUG(0,("%s couldn't find free connection\n",timestring()));
3420 pcon = &Connections[cnum];
3421 bzero((char *)pcon,sizeof(*pcon));
3423 /* find out some info about the user */
3424 pass = Get_Pwnam(user,True);
3428 DEBUG(0,("%s couldn't find account %s\n",timestring(),user));
3432 pcon->read_only = lp_readonly(snum);
3436 StrnCpy(list,lp_readlist(snum),sizeof(pstring)-1);
3437 string_sub(list,"%S",service);
3439 if (user_in_list(user,list))
3440 pcon->read_only = True;
3442 StrnCpy(list,lp_writelist(snum),sizeof(pstring)-1);
3443 string_sub(list,"%S",service);
3445 if (user_in_list(user,list))
3446 pcon->read_only = False;
3449 /* admin user check */
3451 /* JRA - original code denied admin user if the share was
3452 marked read_only. Changed as I don't think this is needed,
3453 but old code left in case there is a problem here.
3455 if (user_in_list(user,lp_admin_users(snum))
3457 && !pcon->read_only)
3462 pcon->admin_user = True;
3463 DEBUG(0,("%s logged in as admin user (root privileges)\n",user));
3466 pcon->admin_user = False;
3468 pcon->force_user = force;
3470 pcon->uid = pass->pw_uid;
3471 pcon->gid = pass->pw_gid;
3472 pcon->num_files_open = 0;
3473 pcon->lastused = time(NULL);
3474 pcon->service = snum;
3476 pcon->printer = (strncmp(dev,"LPT",3) == 0);
3477 pcon->ipc = (strncmp(dev,"IPC",3) == 0);
3478 pcon->dirptr = NULL;
3479 pcon->veto_list = NULL;
3480 pcon->hide_list = NULL;
3481 pcon->veto_oplock_list = NULL;
3482 string_set(&pcon->dirpath,"");
3483 string_set(&pcon->user,user);
3486 if (*lp_force_group(snum))
3491 StrnCpy(gname,lp_force_group(snum),sizeof(pstring)-1);
3492 /* default service may be a group name */
3493 string_sub(gname,"%S",service);
3494 gptr = (struct group *)getgrnam(gname);
3498 pcon->gid = gptr->gr_gid;
3499 DEBUG(3,("Forced group %s\n",gname));
3502 DEBUG(1,("Couldn't find group %s\n",gname));
3506 if (*lp_force_user(snum))
3508 struct passwd *pass2;
3510 fstrcpy(fuser,lp_force_user(snum));
3511 pass2 = (struct passwd *)Get_Pwnam(fuser,True);
3514 pcon->uid = pass2->pw_uid;
3515 string_set(&pcon->user,fuser);
3516 fstrcpy(user,fuser);
3517 pcon->force_user = True;
3518 DEBUG(3,("Forced user %s\n",fuser));
3521 DEBUG(1,("Couldn't find user %s\n",fuser));
3526 pstrcpy(s,lp_pathname(snum));
3527 standard_sub(cnum,s);
3528 string_set(&pcon->connectpath,s);
3529 DEBUG(3,("Connect path is %s\n",s));
3532 /* groups stuff added by ih */
3534 pcon->igroups = NULL;
3535 pcon->groups = NULL;
3540 /* Find all the groups this uid is in and store them. Used by become_user() */
3541 setup_groups(pcon->user,pcon->uid,pcon->gid,
3542 &pcon->ngroups,&pcon->igroups,&pcon->groups,&pcon->attrs);
3544 /* check number of connections */
3545 if (!claim_connection(cnum,
3546 lp_servicename(SNUM(cnum)),
3547 lp_max_connections(SNUM(cnum)),False))
3549 DEBUG(1,("too many connections - rejected\n"));
3553 if (lp_status(SNUM(cnum)))
3554 claim_connection(cnum,"STATUS.",MAXSTATUS,False);
3559 /* execute any "root preexec = " line */
3560 if (*lp_rootpreexec(SNUM(cnum)))
3563 pstrcpy(cmd,lp_rootpreexec(SNUM(cnum)));
3564 standard_sub(cnum,cmd);
3565 DEBUG(5,("cmd=%s\n",cmd));
3566 smbrun(cmd,NULL,False);
3569 if (!become_user(&Connections[cnum], cnum,pcon->vuid))
3571 DEBUG(0,("Can't become connected user!\n"));
3573 if (!IS_IPC(cnum)) {
3574 yield_connection(cnum,
3575 lp_servicename(SNUM(cnum)),
3576 lp_max_connections(SNUM(cnum)));
3577 if (lp_status(SNUM(cnum))) yield_connection(cnum,"STATUS.",MAXSTATUS);
3582 if (ChDir(pcon->connectpath) != 0)
3584 DEBUG(0,("Can't change directory to %s (%s)\n",
3585 pcon->connectpath,strerror(errno)));
3588 if (!IS_IPC(cnum)) {
3589 yield_connection(cnum,
3590 lp_servicename(SNUM(cnum)),
3591 lp_max_connections(SNUM(cnum)));
3592 if (lp_status(SNUM(cnum))) yield_connection(cnum,"STATUS.",MAXSTATUS);
3597 string_set(&pcon->origpath,pcon->connectpath);
3599 #if SOFTLINK_OPTIMISATION
3600 /* resolve any soft links early */
3603 pstrcpy(s,pcon->connectpath);
3605 string_set(&pcon->connectpath,s);
3606 ChDir(pcon->connectpath);
3610 num_connections_open++;
3611 add_session_user(user);
3613 /* execute any "preexec = " line */
3614 if (*lp_preexec(SNUM(cnum)))
3617 pstrcpy(cmd,lp_preexec(SNUM(cnum)));
3618 standard_sub(cnum,cmd);
3619 smbrun(cmd,NULL,False);
3622 /* we've finished with the sensitive stuff */
3625 /* Add veto/hide lists */
3626 if (!IS_IPC(cnum) && !IS_PRINT(cnum))
3628 set_namearray( &pcon->veto_list, lp_veto_files(SNUM(cnum)));
3629 set_namearray( &pcon->hide_list, lp_hide_files(SNUM(cnum)));
3630 set_namearray( &pcon->veto_oplock_list, lp_veto_oplocks(SNUM(cnum)));
3635 DEBUG(IS_IPC(cnum)?3:1,("%s %s (%s) connect to service %s as user %s (uid=%d,gid=%d) (pid %d)\n",
3638 client_addr(Client),
3639 lp_servicename(SNUM(cnum)),user,
3648 /****************************************************************************
3649 Attempt to break an oplock on a file (if oplocked).
3650 Returns True if the file was closed as a result of
3651 the oplock break, False otherwise.
3652 Used as a last ditch attempt to free a space in the
3653 file table when we have run out.
3654 ****************************************************************************/
3656 static BOOL attempt_close_oplocked_file(files_struct *fp)
3659 DEBUG(5,("attempt_close_oplocked_file: checking file %s.\n", fp->name));
3661 if (fp->open && fp->granted_oplock && !fp->sent_oplock_break) {
3663 /* Try and break the oplock. */
3664 file_fd_struct *fsp = fp->fd_ptr;
3665 if(oplock_break( fsp->dev, fsp->inode, &fp->open_time)) {
3666 if(!fp->open) /* Did the oplock break close the file ? */
3674 /****************************************************************************
3675 find first available file slot
3676 ****************************************************************************/
3677 int find_free_file(void )
3680 static int first_file;
3682 /* we want to give out file handles differently on each new
3683 connection because of a common bug in MS clients where they try to
3684 reuse a file descriptor from an earlier smb connection. This code
3685 increases the chance that the errant client will get an error rather
3686 than causing corruption */
3687 if (first_file == 0) {
3688 first_file = (getpid() ^ (int)time(NULL)) % MAX_OPEN_FILES;
3689 if (first_file == 0) first_file = 1;
3692 if (first_file >= MAX_OPEN_FILES)
3695 for (i=first_file;i<MAX_OPEN_FILES;i++)
3696 if (!Files[i].open && !Files[i].reserved) {
3697 memset(&Files[i], 0, sizeof(Files[i]));
3699 Files[i].reserved = True;
3703 /* returning a file handle of 0 is a bad idea - so we start at 1 */
3704 for (i=1;i<first_file;i++)
3705 if (!Files[i].open && !Files[i].reserved) {
3706 memset(&Files[i], 0, sizeof(Files[i]));
3708 Files[i].reserved = True;
3713 * Before we give up, go through the open files
3714 * and see if there are any files opened with a
3715 * batch oplock. If so break the oplock and then
3716 * re-use that entry (if it becomes closed).
3717 * This may help as NT/95 clients tend to keep
3718 * files batch oplocked for quite a long time
3719 * after they have finished with them.
3721 for (i=first_file;i<MAX_OPEN_FILES;i++) {
3722 if(attempt_close_oplocked_file( &Files[i])) {
3723 memset(&Files[i], 0, sizeof(Files[i]));
3725 Files[i].reserved = True;
3730 for (i=1;i<MAX_OPEN_FILES;i++) {
3731 if(attempt_close_oplocked_file( &Files[i])) {
3732 memset(&Files[i], 0, sizeof(Files[i]));
3734 Files[i].reserved = True;
3739 DEBUG(1,("ERROR! Out of file structures - perhaps increase MAX_OPEN_FILES?\n"));
3743 /****************************************************************************
3744 find first available connection slot, starting from a random position.
3745 The randomisation stops problems with the server dieing and clients
3746 thinking the server is still available.
3747 ****************************************************************************/
3748 static int find_free_connection(int hash )
3752 hash = (hash % (MAX_CONNECTIONS-2))+1;
3756 for (i=hash+1;i!=hash;)
3758 if (!Connections[i].open && Connections[i].used == used)
3760 DEBUG(3,("found free connection number %d\n",i));
3764 if (i == MAX_CONNECTIONS)
3774 DEBUG(1,("ERROR! Out of connection structures\n"));
3779 /****************************************************************************
3780 reply for the core protocol
3781 ****************************************************************************/
3782 int reply_corep(char *outbuf)
3784 int outsize = set_message(outbuf,1,0,True);
3786 Protocol = PROTOCOL_CORE;
3792 /****************************************************************************
3793 reply for the coreplus protocol
3794 ****************************************************************************/
3795 int reply_coreplus(char *outbuf)
3797 int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
3798 int outsize = set_message(outbuf,13,0,True);
3799 SSVAL(outbuf,smb_vwv5,raw); /* tell redirector we support
3800 readbraw and writebraw (possibly) */
3801 CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
3802 SSVAL(outbuf,smb_vwv1,0x1); /* user level security, don't encrypt */
3804 Protocol = PROTOCOL_COREPLUS;
3810 /****************************************************************************
3811 reply for the lanman 1.0 protocol
3812 ****************************************************************************/
3813 int reply_lanman1(char *outbuf)
3815 int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
3817 BOOL doencrypt = SMBENCRYPT();
3818 time_t t = time(NULL);
3820 if (lp_security()>=SEC_USER) secword |= 1;
3821 if (doencrypt) secword |= 2;
3823 set_message(outbuf,13,doencrypt?8:0,True);
3824 SSVAL(outbuf,smb_vwv1,secword);
3825 /* Create a token value and add it to the outgoing packet. */
3827 generate_next_challenge(smb_buf(outbuf));
3829 Protocol = PROTOCOL_LANMAN1;
3831 CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
3832 SSVAL(outbuf,smb_vwv2,max_recv);
3833 SSVAL(outbuf,smb_vwv3,lp_maxmux()); /* maxmux */
3834 SSVAL(outbuf,smb_vwv4,1);
3835 SSVAL(outbuf,smb_vwv5,raw); /* tell redirector we support
3836 readbraw writebraw (possibly) */
3837 SIVAL(outbuf,smb_vwv6,getpid());
3838 SSVAL(outbuf,smb_vwv10, TimeDiff(t)/60);
3840 put_dos_date(outbuf,smb_vwv8,t);
3842 return (smb_len(outbuf)+4);
3846 /****************************************************************************
3847 reply for the lanman 2.0 protocol
3848 ****************************************************************************/
3849 int reply_lanman2(char *outbuf)
3851 int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
3853 BOOL doencrypt = SMBENCRYPT();
3854 time_t t = time(NULL);
3855 struct cli_state *cli = NULL;
3859 if (lp_security() == SEC_SERVER) {
3860 cli = server_cryptkey();
3864 DEBUG(3,("using password server validation\n"));
3865 doencrypt = ((cli->sec_mode & 2) != 0);
3868 if (lp_security()>=SEC_USER) secword |= 1;
3869 if (doencrypt) secword |= 2;
3874 generate_next_challenge(cryptkey);
3876 memcpy(cryptkey, cli->cryptkey, 8);
3877 set_challenge(cli->cryptkey);
3881 set_message(outbuf,13,crypt_len,True);
3882 SSVAL(outbuf,smb_vwv1,secword);
3883 SIVAL(outbuf,smb_vwv6,getpid());
3885 memcpy(smb_buf(outbuf), cryptkey, 8);
3887 Protocol = PROTOCOL_LANMAN2;
3889 CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
3890 SSVAL(outbuf,smb_vwv2,max_recv);
3891 SSVAL(outbuf,smb_vwv3,lp_maxmux());
3892 SSVAL(outbuf,smb_vwv4,1);
3893 SSVAL(outbuf,smb_vwv5,raw); /* readbraw and/or writebraw */
3894 SSVAL(outbuf,smb_vwv10, TimeDiff(t)/60);
3895 put_dos_date(outbuf,smb_vwv8,t);
3897 return (smb_len(outbuf)+4);
3901 /****************************************************************************
3902 reply for the nt protocol
3903 ****************************************************************************/
3904 int reply_nt1(char *outbuf)
3906 /* dual names + lock_and_read + nt SMBs + remote API calls */
3907 int capabilities = CAP_NT_FIND|CAP_LOCK_AND_READ|CAP_RPC_REMOTE_APIS;
3909 other valid capabilities which we may support at some time...
3910 CAP_LARGE_FILES|CAP_NT_SMBS|CAP_RPC_REMOTE_APIS;
3911 CAP_LARGE_READX|CAP_STATUS32|CAP_LEVEL_II_OPLOCKS;
3915 BOOL doencrypt = SMBENCRYPT();
3916 time_t t = time(NULL);
3918 struct cli_state *cli = NULL;
3922 if (lp_security() == SEC_SERVER) {
3923 cli = server_cryptkey();
3927 DEBUG(3,("using password server validation\n"));
3928 doencrypt = ((cli->sec_mode & 2) != 0);
3934 generate_next_challenge(cryptkey);
3936 memcpy(cryptkey, cli->cryptkey, 8);
3937 set_challenge(cli->cryptkey);
3941 if (lp_readraw() && lp_writeraw()) {
3942 capabilities |= CAP_RAW_MODE;
3945 if (lp_security() >= SEC_USER) secword |= 1;
3946 if (doencrypt) secword |= 2;
3948 /* decide where (if) to put the encryption challenge, and
3949 follow it with the OEM'd domain name
3951 data_len = crypt_len + strlen(myworkgroup) + 1;
3953 set_message(outbuf,17,data_len,True);
3954 strcpy(smb_buf(outbuf)+crypt_len, myworkgroup);
3956 CVAL(outbuf,smb_vwv1) = secword;
3957 SSVALS(outbuf,smb_vwv16+1,crypt_len);
3959 memcpy(smb_buf(outbuf), cryptkey, 8);
3961 Protocol = PROTOCOL_NT1;
3963 SSVAL(outbuf,smb_vwv1+1,lp_maxmux()); /* maxmpx */
3964 SSVAL(outbuf,smb_vwv2+1,1); /* num vcs */
3965 SIVAL(outbuf,smb_vwv3+1,0xffff); /* max buffer. LOTS! */
3966 SIVAL(outbuf,smb_vwv5+1,0x10000); /* raw size. full 64k */
3967 SIVAL(outbuf,smb_vwv7+1,getpid()); /* session key */
3968 SIVAL(outbuf,smb_vwv9+1,capabilities); /* capabilities */
3969 put_long_date(outbuf+smb_vwv11+1,t);
3970 SSVALS(outbuf,smb_vwv15+1,TimeDiff(t)/60);
3971 SSVAL(outbuf,smb_vwv17,data_len); /* length of challenge+domain strings */
3973 return (smb_len(outbuf)+4);
3976 /* these are the protocol lists used for auto architecture detection:
3979 protocol [PC NETWORK PROGRAM 1.0]
3980 protocol [XENIX CORE]
3981 protocol [MICROSOFT NETWORKS 1.03]
3982 protocol [LANMAN1.0]
3983 protocol [Windows for Workgroups 3.1a]
3984 protocol [LM1.2X002]
3985 protocol [LANMAN2.1]
3986 protocol [NT LM 0.12]
3989 protocol [PC NETWORK PROGRAM 1.0]
3990 protocol [XENIX CORE]
3991 protocol [MICROSOFT NETWORKS 1.03]
3992 protocol [LANMAN1.0]
3993 protocol [Windows for Workgroups 3.1a]
3994 protocol [LM1.2X002]
3995 protocol [LANMAN2.1]
3996 protocol [NT LM 0.12]
3999 protocol [PC NETWORK PROGRAM 1.0]
4000 protocol [XENIX CORE]
4001 protocol [LANMAN1.0]
4002 protocol [LM1.2X002]
4003 protocol [LANMAN2.1]
4007 * Modified to recognize the architecture of the remote machine better.
4009 * This appears to be the matrix of which protocol is used by which
4011 Protocol WfWg Win95 WinNT OS/2
4012 PC NETWORK PROGRAM 1.0 1 1 1 1
4014 MICROSOFT NETWORKS 3.0 2 2
4016 MICROSOFT NETWORKS 1.03 3
4019 Windows for Workgroups 3.1a 5 5 5
4024 * tim@fsg.com 09/29/95
4027 #define ARCH_WFWG 0x3 /* This is a fudge because WfWg is like Win95 */
4028 #define ARCH_WIN95 0x2
4029 #define ARCH_OS2 0xC /* Again OS/2 is like NT */
4030 #define ARCH_WINNT 0x8
4031 #define ARCH_SAMBA 0x10
4033 #define ARCH_ALL 0x1F
4035 /* List of supported protocols, most desired first */
4039 int (*proto_reply_fn)(char *);
4041 } supported_protocols[] = {
4042 {"NT LANMAN 1.0", "NT1", reply_nt1, PROTOCOL_NT1},
4043 {"NT LM 0.12", "NT1", reply_nt1, PROTOCOL_NT1},
4044 {"LM1.2X002", "LANMAN2", reply_lanman2, PROTOCOL_LANMAN2},
4045 {"Samba", "LANMAN2", reply_lanman2, PROTOCOL_LANMAN2},
4046 {"DOS LM1.2X002", "LANMAN2", reply_lanman2, PROTOCOL_LANMAN2},
4047 {"LANMAN1.0", "LANMAN1", reply_lanman1, PROTOCOL_LANMAN1},
4048 {"MICROSOFT NETWORKS 3.0", "LANMAN1", reply_lanman1, PROTOCOL_LANMAN1},
4049 {"MICROSOFT NETWORKS 1.03", "COREPLUS", reply_coreplus, PROTOCOL_COREPLUS},
4050 {"PC NETWORK PROGRAM 1.0", "CORE", reply_corep, PROTOCOL_CORE},
4055 /****************************************************************************
4057 ****************************************************************************/
4058 static int reply_negprot(char *inbuf,char *outbuf)
4060 int outsize = set_message(outbuf,1,0,True);
4065 int bcc = SVAL(smb_buf(inbuf),-2);
4066 int arch = ARCH_ALL;
4068 p = smb_buf(inbuf)+1;
4069 while (p < (smb_buf(inbuf) + bcc))
4072 DEBUG(3,("Requested protocol [%s]\n",p));
4073 if (strcsequal(p,"Windows for Workgroups 3.1a"))
4074 arch &= ( ARCH_WFWG | ARCH_WIN95 | ARCH_WINNT );
4075 else if (strcsequal(p,"DOS LM1.2X002"))
4076 arch &= ( ARCH_WFWG | ARCH_WIN95 );
4077 else if (strcsequal(p,"DOS LANMAN2.1"))
4078 arch &= ( ARCH_WFWG | ARCH_WIN95 );
4079 else if (strcsequal(p,"NT LM 0.12"))
4080 arch &= ( ARCH_WIN95 | ARCH_WINNT );
4081 else if (strcsequal(p,"LANMAN2.1"))
4082 arch &= ( ARCH_WINNT | ARCH_OS2 );
4083 else if (strcsequal(p,"LM1.2X002"))
4084 arch &= ( ARCH_WINNT | ARCH_OS2 );
4085 else if (strcsequal(p,"MICROSOFT NETWORKS 1.03"))
4087 else if (strcsequal(p,"XENIX CORE"))
4088 arch &= ( ARCH_WINNT | ARCH_OS2 );
4089 else if (strcsequal(p,"Samba")) {
4099 set_remote_arch(RA_SAMBA);
4102 set_remote_arch(RA_WFWG);
4105 set_remote_arch(RA_WIN95);
4108 set_remote_arch(RA_WINNT);
4111 set_remote_arch(RA_OS2);
4114 set_remote_arch(RA_UNKNOWN);
4118 /* possibly reload - change of architecture */
4119 reload_services(True);
4121 /* a special case to stop password server loops */
4122 if (Index == 1 && strequal(remote_machine,myhostname) &&
4123 lp_security()==SEC_SERVER)
4124 exit_server("Password server loop!");
4126 /* Check for protocols, most desirable first */
4127 for (protocol = 0; supported_protocols[protocol].proto_name; protocol++)
4129 p = smb_buf(inbuf)+1;
4131 if (lp_maxprotocol() >= supported_protocols[protocol].protocol_level)
4132 while (p < (smb_buf(inbuf) + bcc))
4134 if (strequal(p,supported_protocols[protocol].proto_name))
4143 SSVAL(outbuf,smb_vwv0,choice);
4145 extern fstring remote_proto;
4146 fstrcpy(remote_proto,supported_protocols[protocol].short_name);
4147 reload_services(True);
4148 outsize = supported_protocols[protocol].proto_reply_fn(outbuf);
4149 DEBUG(3,("Selected protocol %s\n",supported_protocols[protocol].proto_name));
4152 DEBUG(0,("No protocol supported !\n"));
4154 SSVAL(outbuf,smb_vwv0,choice);
4156 DEBUG(5,("%s negprot index=%d\n",timestring(),choice));
4162 /****************************************************************************
4163 close all open files for a connection
4164 ****************************************************************************/
4165 static void close_open_files(int cnum)
4168 for (i=0;i<MAX_OPEN_FILES;i++)
4169 if( Files[i].cnum == cnum && Files[i].open) {
4170 close_file(i,False);
4176 /****************************************************************************
4178 ****************************************************************************/
4179 void close_cnum(int cnum, uint16 vuid)
4182 DirCacheFlush(SNUM(cnum));
4186 if (!OPEN_CNUM(cnum))
4188 DEBUG(0,("Can't close cnum %d\n",cnum));
4192 DEBUG(IS_IPC(cnum)?3:1,("%s %s (%s) closed connection to service %s\n",
4194 remote_machine,client_addr(Client),
4195 lp_servicename(SNUM(cnum))));
4197 yield_connection(cnum,
4198 lp_servicename(SNUM(cnum)),
4199 lp_max_connections(SNUM(cnum)));
4201 if (lp_status(SNUM(cnum)))
4202 yield_connection(cnum,"STATUS.",MAXSTATUS);
4204 close_open_files(cnum);
4205 dptr_closecnum(cnum);
4207 /* execute any "postexec = " line */
4208 if (*lp_postexec(SNUM(cnum)) && become_user(&Connections[cnum], cnum,vuid))
4211 strcpy(cmd,lp_postexec(SNUM(cnum)));
4212 standard_sub(cnum,cmd);
4213 smbrun(cmd,NULL,False);
4218 /* execute any "root postexec = " line */
4219 if (*lp_rootpostexec(SNUM(cnum)))
4222 strcpy(cmd,lp_rootpostexec(SNUM(cnum)));
4223 standard_sub(cnum,cmd);
4224 smbrun(cmd,NULL,False);
4227 Connections[cnum].open = False;
4228 num_connections_open--;
4229 if (Connections[cnum].ngroups && Connections[cnum].groups)
4231 if (Connections[cnum].igroups != (int *)Connections[cnum].groups)
4232 free(Connections[cnum].groups);
4233 free(Connections[cnum].igroups);
4234 Connections[cnum].groups = NULL;
4235 Connections[cnum].igroups = NULL;
4236 Connections[cnum].ngroups = 0;
4239 free_namearray(Connections[cnum].veto_list);
4240 free_namearray(Connections[cnum].hide_list);
4241 free_namearray(Connections[cnum].veto_oplock_list);
4243 string_set(&Connections[cnum].user,"");
4244 string_set(&Connections[cnum].dirpath,"");
4245 string_set(&Connections[cnum].connectpath,"");
4251 /*******************************************************************
4252 prepare to dump a core file - carefully!
4253 ********************************************************************/
4254 static BOOL dump_core(void)
4258 pstrcpy(dname,debugf);
4259 if ((p=strrchr(dname,'/'))) *p=0;
4260 strcat(dname,"/corefiles");
4262 sys_chown(dname,getuid(),getgid());
4264 if (chdir(dname)) return(False);
4267 #ifndef NO_GETRLIMIT
4271 getrlimit(RLIMIT_CORE, &rlp);
4272 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
4273 setrlimit(RLIMIT_CORE, &rlp);
4274 getrlimit(RLIMIT_CORE, &rlp);
4275 DEBUG(3,("Core limits now %d %d\n",rlp.rlim_cur,rlp.rlim_max));
4281 DEBUG(0,("Dumping core in %s\n",dname));
4286 /****************************************************************************
4288 ****************************************************************************/
4289 void exit_server(char *reason)
4291 static int firsttime=1;
4294 if (!firsttime) exit(0);
4298 DEBUG(2,("Closing connections\n"));
4299 for (i=0;i<MAX_CONNECTIONS;i++)
4300 if (Connections[i].open)
4301 close_cnum(i,(uint16)-1);
4303 if (dcelogin_atmost_once)
4307 int oldlevel = DEBUGLEVEL;
4309 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
4311 show_msg(last_inbuf);
4312 DEBUGLEVEL = oldlevel;
4313 DEBUG(0,("===============================================================\n"));
4315 if (dump_core()) return;
4321 DEBUG(3,("%s Server exit (%s)\n",timestring(),reason?reason:""));
4325 /****************************************************************************
4326 do some standard substitutions in a string
4327 ****************************************************************************/
4328 void standard_sub(int cnum,char *str)
4330 if (VALID_CNUM(cnum)) {
4333 for ( s=str ; (p=strchr(s, '%')) != NULL ; s=p ) {
4335 case 'H' : if ((home = get_home_dir(Connections[cnum].user))!=NULL)
4336 string_sub(p,"%H",home);
4340 case 'P' : string_sub(p,"%P",Connections[cnum].connectpath); break;
4341 case 'S' : string_sub(p,"%S",lp_servicename(Connections[cnum].service)); break;
4342 case 'g' : string_sub(p,"%g",gidtoname(Connections[cnum].gid)); break;
4343 case 'u' : string_sub(p,"%u",Connections[cnum].user); break;
4345 * Patch from jkf@soton.ac.uk
4346 * Left the %N (NIS server name) in standard_sub_basic as it
4347 * is a feature for logon servers, hence uses the username.
4348 * The %p (NIS server path) code is here as it is used
4349 * instead of the default "path =" string in [homes] and so
4350 * needs the service name, not the username.
4352 case 'p' : string_sub(p,"%p",automount_path(lp_servicename(Connections[cnum].service))); break;
4353 case '\0' : p++; break; /* don't run off the end of the string */
4354 default : p+=2; break;
4358 standard_sub_basic(str);
4362 These flags determine some of the permissions required to do an operation
4364 Note that I don't set NEED_WRITE on some write operations because they
4365 are used by some brain-dead clients when printing, and I don't want to
4366 force write permissions on print services.
4368 #define AS_USER (1<<0)
4369 #define NEED_WRITE (1<<1)
4370 #define TIME_INIT (1<<2)
4371 #define CAN_IPC (1<<3)
4372 #define AS_GUEST (1<<5)
4373 #define QUEUE_IN_OPLOCK (1<<6)
4376 define a list of possible SMB messages and their corresponding
4377 functions. Any message that has a NULL function is unimplemented -
4378 please feel free to contribute implementations!
4380 struct smb_message_struct
4394 {SMBnegprot,"SMBnegprot",reply_negprot,0},
4395 {SMBtcon,"SMBtcon",reply_tcon,0},
4396 {SMBtdis,"SMBtdis",reply_tdis,0},
4397 {SMBexit,"SMBexit",reply_exit,0},
4398 {SMBioctl,"SMBioctl",reply_ioctl,0},
4399 {SMBecho,"SMBecho",reply_echo,0},
4400 {SMBsesssetupX,"SMBsesssetupX",reply_sesssetup_and_X,0},
4401 {SMBtconX,"SMBtconX",reply_tcon_and_X,0},
4402 {SMBulogoffX, "SMBulogoffX", reply_ulogoffX, 0}, /* ulogoff doesn't give a valid TID */
4403 {SMBgetatr,"SMBgetatr",reply_getatr,AS_USER},
4404 {SMBsetatr,"SMBsetatr",reply_setatr,AS_USER | NEED_WRITE},
4405 {SMBchkpth,"SMBchkpth",reply_chkpth,AS_USER},
4406 {SMBsearch,"SMBsearch",reply_search,AS_USER},
4407 {SMBopen,"SMBopen",reply_open,AS_USER | QUEUE_IN_OPLOCK },
4409 /* note that SMBmknew and SMBcreate are deliberately overloaded */
4410 {SMBcreate,"SMBcreate",reply_mknew,AS_USER},
4411 {SMBmknew,"SMBmknew",reply_mknew,AS_USER},
4413 {SMBunlink,"SMBunlink",reply_unlink,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
4414 {SMBread,"SMBread",reply_read,AS_USER},
4415 {SMBwrite,"SMBwrite",reply_write,AS_USER},
4416 {SMBclose,"SMBclose",reply_close,AS_USER | CAN_IPC},
4417 {SMBmkdir,"SMBmkdir",reply_mkdir,AS_USER | NEED_WRITE},
4418 {SMBrmdir,"SMBrmdir",reply_rmdir,AS_USER | NEED_WRITE},
4419 {SMBdskattr,"SMBdskattr",reply_dskattr,AS_USER},
4420 {SMBmv,"SMBmv",reply_mv,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
4422 /* this is a Pathworks specific call, allowing the
4423 changing of the root path */
4424 {pSETDIR,"pSETDIR",reply_setdir,AS_USER},
4426 {SMBlseek,"SMBlseek",reply_lseek,AS_USER},
4427 {SMBflush,"SMBflush",reply_flush,AS_USER},
4428 {SMBctemp,"SMBctemp",reply_ctemp,AS_USER | QUEUE_IN_OPLOCK },
4429 {SMBsplopen,"SMBsplopen",reply_printopen,AS_USER | QUEUE_IN_OPLOCK },
4430 {SMBsplclose,"SMBsplclose",reply_printclose,AS_USER},
4431 {SMBsplretq,"SMBsplretq",reply_printqueue,AS_USER|AS_GUEST},
4432 {SMBsplwr,"SMBsplwr",reply_printwrite,AS_USER},
4433 {SMBlock,"SMBlock",reply_lock,AS_USER},
4434 {SMBunlock,"SMBunlock",reply_unlock,AS_USER},
4436 /* CORE+ PROTOCOL FOLLOWS */
4438 {SMBreadbraw,"SMBreadbraw",reply_readbraw,AS_USER},
4439 {SMBwritebraw,"SMBwritebraw",reply_writebraw,AS_USER},
4440 {SMBwriteclose,"SMBwriteclose",reply_writeclose,AS_USER},
4441 {SMBlockread,"SMBlockread",reply_lockread,AS_USER},
4442 {SMBwriteunlock,"SMBwriteunlock",reply_writeunlock,AS_USER},
4444 /* LANMAN1.0 PROTOCOL FOLLOWS */
4446 {SMBreadBmpx,"SMBreadBmpx",reply_readbmpx,AS_USER},
4447 {SMBreadBs,"SMBreadBs",NULL,AS_USER},
4448 {SMBwriteBmpx,"SMBwriteBmpx",reply_writebmpx,AS_USER},
4449 {SMBwriteBs,"SMBwriteBs",reply_writebs,AS_USER},
4450 {SMBwritec,"SMBwritec",NULL,AS_USER},
4451 {SMBsetattrE,"SMBsetattrE",reply_setattrE,AS_USER | NEED_WRITE},
4452 {SMBgetattrE,"SMBgetattrE",reply_getattrE,AS_USER},
4453 {SMBtrans,"SMBtrans",reply_trans,AS_USER | CAN_IPC},
4454 {SMBtranss,"SMBtranss",NULL,AS_USER | CAN_IPC},
4455 {SMBioctls,"SMBioctls",NULL,AS_USER},
4456 {SMBcopy,"SMBcopy",reply_copy,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
4457 {SMBmove,"SMBmove",NULL,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
4459 {SMBopenX,"SMBopenX",reply_open_and_X,AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
4460 {SMBreadX,"SMBreadX",reply_read_and_X,AS_USER | CAN_IPC },
4461 {SMBwriteX,"SMBwriteX",reply_write_and_X,AS_USER},
4462 {SMBlockingX,"SMBlockingX",reply_lockingX,AS_USER},
4464 {SMBffirst,"SMBffirst",reply_search,AS_USER},
4465 {SMBfunique,"SMBfunique",reply_search,AS_USER},
4466 {SMBfclose,"SMBfclose",reply_fclose,AS_USER},
4468 /* LANMAN2.0 PROTOCOL FOLLOWS */
4469 {SMBfindnclose, "SMBfindnclose", reply_findnclose, AS_USER},
4470 {SMBfindclose, "SMBfindclose", reply_findclose,AS_USER},
4471 {SMBtrans2, "SMBtrans2", reply_trans2, AS_USER },
4472 {SMBtranss2, "SMBtranss2", reply_transs2, AS_USER},
4474 /* messaging routines */
4475 {SMBsends,"SMBsends",reply_sends,AS_GUEST},
4476 {SMBsendstrt,"SMBsendstrt",reply_sendstrt,AS_GUEST},
4477 {SMBsendend,"SMBsendend",reply_sendend,AS_GUEST},
4478 {SMBsendtxt,"SMBsendtxt",reply_sendtxt,AS_GUEST},
4480 /* NON-IMPLEMENTED PARTS OF THE CORE PROTOCOL */
4482 {SMBsendb,"SMBsendb",NULL,AS_GUEST},
4483 {SMBfwdname,"SMBfwdname",NULL,AS_GUEST},
4484 {SMBcancelf,"SMBcancelf",NULL,AS_GUEST},
4485 {SMBgetmac,"SMBgetmac",NULL,AS_GUEST}
4488 /****************************************************************************
4489 return a string containing the function name of a SMB command
4490 ****************************************************************************/
4491 char *smb_fn_name(int type)
4493 static char *unknown_name = "SMBunknown";
4494 static int num_smb_messages =
4495 sizeof(smb_messages) / sizeof(struct smb_message_struct);
4498 for (match=0;match<num_smb_messages;match++)
4499 if (smb_messages[match].code == type)
4502 if (match == num_smb_messages)
4503 return(unknown_name);
4505 return(smb_messages[match].name);
4509 /****************************************************************************
4510 do a switch on the message type, and return the response size
4511 ****************************************************************************/
4512 static int switch_message(int type,char *inbuf,char *outbuf,int size,int bufsize)
4516 static int num_smb_messages =
4517 sizeof(smb_messages) / sizeof(struct smb_message_struct);
4521 struct timeval msg_start_time;
4522 struct timeval msg_end_time;
4523 static unsigned long total_time = 0;
4525 GetTimeOfDay(&msg_start_time);
4532 last_message = type;
4534 /* make sure this is an SMB packet */
4535 if (strncmp(smb_base(inbuf),"\377SMB",4) != 0)
4537 DEBUG(2,("Non-SMB packet of length %d\n",smb_len(inbuf)));
4541 for (match=0;match<num_smb_messages;match++)
4542 if (smb_messages[match].code == type)
4545 if (match == num_smb_messages)
4547 DEBUG(0,("Unknown message type %d!\n",type));
4548 outsize = reply_unknown(inbuf,outbuf);
4552 DEBUG(3,("switch message %s (pid %d)\n",smb_messages[match].name,pid));
4554 if(global_oplock_break && (smb_messages[match].flags & QUEUE_IN_OPLOCK))
4557 * Queue this message as we are the process of an oplock break.
4560 DEBUG(2,("%s: switch_message: queueing message due to being in oplock break state.\n",
4563 push_smb_message( inbuf, size);
4567 if (smb_messages[match].fn)
4569 int cnum = SVAL(inbuf,smb_tid);
4570 int flags = smb_messages[match].flags;
4571 /* In share mode security we must ignore the vuid. */
4572 uint16 session_tag = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : SVAL(inbuf,smb_uid);
4573 /* Ensure this value is replaced in the incoming packet. */
4574 SSVAL(inbuf,smb_uid,session_tag);
4576 /* does this protocol need to be run as root? */
4577 if (!(flags & AS_USER))
4580 /* does this protocol need to be run as the connected user? */
4581 if ((flags & AS_USER) && !become_user(&Connections[cnum], cnum,session_tag)) {
4582 if (flags & AS_GUEST)
4585 return(ERROR(ERRSRV,ERRinvnid));
4587 /* this code is to work around a bug is MS client 3 without
4588 introducing a security hole - it needs to be able to do
4589 print queue checks as guest if it isn't logged in properly */
4590 if (flags & AS_USER)
4593 /* does it need write permission? */
4594 if ((flags & NEED_WRITE) && !CAN_WRITE(cnum))
4595 return(ERROR(ERRSRV,ERRaccess));
4597 /* ipc services are limited */
4598 if (IS_IPC(cnum) && (flags & AS_USER) && !(flags & CAN_IPC))
4599 return(ERROR(ERRSRV,ERRaccess));
4601 /* load service specific parameters */
4602 if (OPEN_CNUM(cnum) && !become_service(cnum,(flags & AS_USER)?True:False))
4603 return(ERROR(ERRSRV,ERRaccess));
4605 /* does this protocol need to be run as guest? */
4606 if ((flags & AS_GUEST) && (!become_guest() || !check_access(-1)))
4607 return(ERROR(ERRSRV,ERRaccess));
4611 outsize = smb_messages[match].fn(inbuf,outbuf,size,bufsize);
4615 outsize = reply_unknown(inbuf,outbuf);
4620 GetTimeOfDay(&msg_end_time);
4621 if (!(smb_messages[match].flags & TIME_INIT))
4623 smb_messages[match].time = 0;
4624 smb_messages[match].flags |= TIME_INIT;
4627 unsigned long this_time =
4628 (msg_end_time.tv_sec - msg_start_time.tv_sec)*1e6 +
4629 (msg_end_time.tv_usec - msg_start_time.tv_usec);
4630 smb_messages[match].time += this_time;
4631 total_time += this_time;
4633 DEBUG(2,("TIME %s %d usecs %g pct\n",
4634 smb_fn_name(type),smb_messages[match].time,
4635 (100.0*smb_messages[match].time) / total_time));
4642 /****************************************************************************
4643 construct a chained reply and add it to the already made reply
4644 **************************************************************************/
4645 int chain_reply(char *inbuf,char *outbuf,int size,int bufsize)
4647 static char *orig_inbuf;
4648 static char *orig_outbuf;
4649 int smb_com1, smb_com2 = CVAL(inbuf,smb_vwv0);
4650 unsigned smb_off2 = SVAL(inbuf,smb_vwv1);
4651 char *inbuf2, *outbuf2;
4653 char inbuf_saved[smb_wct];
4654 char outbuf_saved[smb_wct];
4655 extern int chain_size;
4656 int wct = CVAL(outbuf,smb_wct);
4657 int outsize = smb_size + 2*wct + SVAL(outbuf,smb_vwv0+2*wct);
4659 /* maybe its not chained */
4660 if (smb_com2 == 0xFF) {
4661 CVAL(outbuf,smb_vwv0) = 0xFF;
4665 if (chain_size == 0) {
4666 /* this is the first part of the chain */
4668 orig_outbuf = outbuf;
4671 /* we need to tell the client where the next part of the reply will be */
4672 SSVAL(outbuf,smb_vwv1,smb_offset(outbuf+outsize,outbuf));
4673 CVAL(outbuf,smb_vwv0) = smb_com2;
4675 /* remember how much the caller added to the chain, only counting stuff
4676 after the parameter words */
4677 chain_size += outsize - smb_wct;
4679 /* work out pointers into the original packets. The
4680 headers on these need to be filled in */
4681 inbuf2 = orig_inbuf + smb_off2 + 4 - smb_wct;
4682 outbuf2 = orig_outbuf + SVAL(outbuf,smb_vwv1) + 4 - smb_wct;
4684 /* remember the original command type */
4685 smb_com1 = CVAL(orig_inbuf,smb_com);
4687 /* save the data which will be overwritten by the new headers */
4688 memcpy(inbuf_saved,inbuf2,smb_wct);
4689 memcpy(outbuf_saved,outbuf2,smb_wct);
4691 /* give the new packet the same header as the last part of the SMB */
4692 memmove(inbuf2,inbuf,smb_wct);
4694 /* create the in buffer */
4695 CVAL(inbuf2,smb_com) = smb_com2;
4697 /* create the out buffer */
4698 bzero(outbuf2,smb_size);
4699 set_message(outbuf2,0,0,True);
4700 CVAL(outbuf2,smb_com) = CVAL(inbuf2,smb_com);
4702 memcpy(outbuf2+4,inbuf2+4,4);
4703 CVAL(outbuf2,smb_rcls) = SMB_SUCCESS;
4704 CVAL(outbuf2,smb_reh) = 0;
4705 CVAL(outbuf2,smb_flg) = 0x80 | (CVAL(inbuf2,smb_flg) & 0x8); /* bit 7 set
4707 SSVAL(outbuf2,smb_flg2,1); /* say we support long filenames */
4708 SSVAL(outbuf2,smb_err,SMB_SUCCESS);
4709 SSVAL(outbuf2,smb_tid,SVAL(inbuf2,smb_tid));
4710 SSVAL(outbuf2,smb_pid,SVAL(inbuf2,smb_pid));
4711 SSVAL(outbuf2,smb_uid,SVAL(inbuf2,smb_uid));
4712 SSVAL(outbuf2,smb_mid,SVAL(inbuf2,smb_mid));
4714 DEBUG(3,("Chained message\n"));
4717 /* process the request */
4718 outsize2 = switch_message(smb_com2,inbuf2,outbuf2,size-chain_size,
4719 bufsize-chain_size);
4721 /* copy the new reply and request headers over the old ones, but
4722 preserve the smb_com field */
4723 memmove(orig_outbuf,outbuf2,smb_wct);
4724 CVAL(orig_outbuf,smb_com) = smb_com1;
4726 /* restore the saved data, being careful not to overwrite any
4727 data from the reply header */
4728 memcpy(inbuf2,inbuf_saved,smb_wct);
4730 int ofs = smb_wct - PTR_DIFF(outbuf2,orig_outbuf);
4731 if (ofs < 0) ofs = 0;
4732 memmove(outbuf2+ofs,outbuf_saved+ofs,smb_wct-ofs);
4740 /****************************************************************************
4741 construct a reply to the incoming packet
4742 ****************************************************************************/
4743 int construct_reply(char *inbuf,char *outbuf,int size,int bufsize)
4745 int type = CVAL(inbuf,smb_com);
4747 int msg_type = CVAL(inbuf,0);
4748 extern int chain_size;
4750 smb_last_time = time(NULL);
4756 bzero(outbuf,smb_size);
4759 return(reply_special(inbuf,outbuf));
4761 CVAL(outbuf,smb_com) = CVAL(inbuf,smb_com);
4762 set_message(outbuf,0,0,True);
4764 memcpy(outbuf+4,inbuf+4,4);
4765 CVAL(outbuf,smb_rcls) = SMB_SUCCESS;
4766 CVAL(outbuf,smb_reh) = 0;
4767 CVAL(outbuf,smb_flg) = 0x80 | (CVAL(inbuf,smb_flg) & 0x8); /* bit 7 set
4769 SSVAL(outbuf,smb_flg2,1); /* say we support long filenames */
4770 SSVAL(outbuf,smb_err,SMB_SUCCESS);
4771 SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
4772 SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
4773 SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
4774 SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
4776 outsize = switch_message(type,inbuf,outbuf,size,bufsize);
4778 outsize += chain_size;
4781 smb_setlen(outbuf,outsize - 4);
4785 /****************************************************************************
4786 process commands from the client
4787 ****************************************************************************/
4788 static void process(void)
4792 InBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
4793 OutBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
4794 if ((InBuffer == NULL) || (OutBuffer == NULL))
4797 InBuffer += SMB_ALIGNMENT;
4798 OutBuffer += SMB_ALIGNMENT;
4801 DEBUG(3,("priming nmbd\n"));
4804 ip = *interpret_addr2("localhost");
4805 if (zero_ip(ip)) ip = *interpret_addr2("127.0.0.1");
4807 send_one_packet(OutBuffer,1,ip,NMB_PORT,SOCK_DGRAM);
4811 /* re-initialise the timezone */
4816 int deadtime = lp_deadtime()*60;
4818 int last_keepalive=0;
4819 int service_load_counter = 0;
4820 BOOL got_smb = False;
4823 deadtime = DEFAULT_SMBD_TIMEOUT;
4825 #if USE_READ_PREDICTION
4826 if (lp_readprediction())
4827 do_read_prediction();
4832 for (counter=SMBD_SELECT_LOOP;
4833 !receive_message_or_smb(Client,oplock_sock,
4834 InBuffer,BUFFER_SIZE,SMBD_SELECT_LOOP*1000,&got_smb);
4835 counter += SMBD_SELECT_LOOP)
4839 BOOL allidle = True;
4840 extern int keepalive;
4842 if (counter > 365 * 3600) /* big number of seconds. */
4845 service_load_counter = 0;
4848 if (smb_read_error == READ_EOF)
4850 DEBUG(3,("end of file from client\n"));
4854 if (smb_read_error == READ_ERROR)
4856 DEBUG(3,("receive_smb error (%s) exiting\n",
4863 /* become root again if waiting */
4866 /* check for smb.conf reload */
4867 if (counter >= service_load_counter + SMBD_RELOAD_CHECK)
4869 service_load_counter = counter;
4871 /* reload services, if files have changed. */
4872 reload_services(True);
4875 /* automatic timeout if all connections are closed */
4876 if (num_connections_open==0 && counter >= IDLE_CLOSED_TIMEOUT)
4878 DEBUG(2,("%s Closing idle connection\n",timestring()));
4882 if (keepalive && (counter-last_keepalive)>keepalive)
4884 struct cli_state *cli = server_client();
4885 if (!send_keepalive(Client)) {
4886 DEBUG(2,("%s Keepalive failed - exiting\n",timestring()));
4889 /* also send a keepalive to the password server if its still
4891 if (cli && cli->initialised)
4892 send_keepalive(cli->fd);
4893 last_keepalive = counter;
4896 /* check for connection timeouts */
4897 for (i=0;i<MAX_CONNECTIONS;i++)
4898 if (Connections[i].open)
4900 /* close dirptrs on connections that are idle */
4901 if ((t-Connections[i].lastused)>DPTR_IDLE_TIMEOUT)
4904 if (Connections[i].num_files_open > 0 ||
4905 (t-Connections[i].lastused)<deadtime)
4909 if (allidle && num_connections_open>0)
4911 DEBUG(2,("%s Closing idle connection 2\n",timestring()));
4917 process_smb(InBuffer, OutBuffer);
4919 process_local_message(oplock_sock, InBuffer, BUFFER_SIZE);
4924 /****************************************************************************
4925 initialise connect, service and file structs
4926 ****************************************************************************/
4927 static void init_structs(void )
4930 get_myname(myhostname,NULL);
4932 for (i=0;i<MAX_CONNECTIONS;i++)
4934 Connections[i].open = False;
4935 Connections[i].num_files_open=0;
4936 Connections[i].lastused=0;
4937 Connections[i].used=False;
4938 string_init(&Connections[i].user,"");
4939 string_init(&Connections[i].dirpath,"");
4940 string_init(&Connections[i].connectpath,"");
4941 string_init(&Connections[i].origpath,"");
4944 for (i=0;i<MAX_OPEN_FILES;i++)
4946 Files[i].open = False;
4947 string_init(&Files[i].name,"");
4951 for (i=0;i<MAX_OPEN_FILES;i++)
4953 file_fd_struct *fd_ptr = &FileFd[i];
4954 fd_ptr->ref_count = 0;
4955 fd_ptr->dev = (int32)-1;
4956 fd_ptr->inode = (int32)-1;
4958 fd_ptr->fd_readonly = -1;
4959 fd_ptr->fd_writeonly = -1;
4960 fd_ptr->real_open_flags = -1;
4964 init_rpc_pipe_hnd();
4966 /* for LSA handles */
4967 init_lsa_policy_hnd();
4972 /****************************************************************************
4973 usage on the program
4974 ****************************************************************************/
4975 static void usage(char *pname)
4977 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
4979 printf("Usage: %s [-D] [-p port] [-d debuglevel] [-l log basename] [-s services file]\n",pname);
4980 printf("Version %s\n",VERSION);
4981 printf("\t-D become a daemon\n");
4982 printf("\t-p port listen on the specified port\n");
4983 printf("\t-d debuglevel set the debuglevel\n");
4984 printf("\t-l log basename. Basename for log/debug files\n");
4985 printf("\t-s services file. Filename of services file\n");
4986 printf("\t-P passive only\n");
4987 printf("\t-a overwrite log file, don't append\n");
4992 /****************************************************************************
4994 ****************************************************************************/
4995 int main(int argc,char *argv[])
4997 extern BOOL append_log;
4998 /* shall I run as a daemon */
4999 BOOL is_daemon = False;
5000 int port = SMB_PORT;
5002 extern char *optarg;
5004 #ifdef NEED_AUTH_PARAMETERS
5005 set_auth_parameters(argc,argv);
5016 strcpy(debugf,SMBLOGFILE);
5018 strcpy(remote_machine, "smb");
5020 setup_logging(argv[0],False);
5022 charset_initialise();
5024 /* make absolutely sure we run as root - to handle cases where people
5025 are crazy enough to have it setuid */
5035 fault_setup(exit_server);
5036 signal(SIGTERM , SIGNAL_CAST dflt_sig);
5038 /* we want total control over the permissions on created files,
5039 so set our umask to 0 */
5046 /* this is for people who can't start the program correctly */
5047 while (argc > 1 && (*argv[1] != '-'))
5053 while ((opt = getopt(argc, argv, "O:i:l:s:d:Dp:hPaf:")) != EOF)
5057 strcpy(user_socket_options,optarg);
5060 strcpy(scope,optarg);
5064 extern BOOL passive;
5069 strcpy(servicesf,optarg);
5072 strcpy(debugf,optarg);
5076 extern BOOL append_log;
5077 append_log = !append_log;
5087 DEBUGLEVEL = atoi(optarg);
5090 port = atoi(optarg);
5103 DEBUG(2,("%s smbd version %s started\n",timestring(),VERSION));
5104 DEBUG(2,("Copyright Andrew Tridgell 1992-1997\n"));
5106 #ifndef NO_GETRLIMIT
5107 #ifdef RLIMIT_NOFILE
5110 getrlimit(RLIMIT_NOFILE, &rlp);
5112 * Set the fd limit to be MAX_OPEN_FILES + 10 to account for the
5113 * extra fd we need to read directories, as well as the log files
5114 * and standard handles etc.
5116 rlp.rlim_cur = (MAX_OPEN_FILES+10>rlp.rlim_max)? rlp.rlim_max:MAX_OPEN_FILES+10;
5117 setrlimit(RLIMIT_NOFILE, &rlp);
5118 getrlimit(RLIMIT_NOFILE, &rlp);
5119 DEBUG(3,("Maximum number of open files per session is %d\n",rlp.rlim_cur));
5125 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
5126 getuid(),getgid(),geteuid(),getegid()));
5128 if (sizeof(uint16) < 2 || sizeof(uint32) < 4)
5130 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
5136 if (!reload_services(False))
5139 codepage_initialise(lp_client_code_page());
5141 strcpy(myworkgroup, lp_workgroup());
5143 #ifndef NO_SIGNAL_TEST
5144 signal(SIGHUP,SIGNAL_CAST sig_hup);
5147 /* Setup the signals that allow the debug log level
5148 to by dynamically changed. */
5150 /* If we are using the malloc debug code we can't use
5151 SIGUSR1 and SIGUSR2 to do debug level changes. */
5154 #if defined(SIGUSR1)
5155 signal( SIGUSR1, SIGNAL_CAST sig_usr1 );
5156 #endif /* SIGUSR1 */
5158 #if defined(SIGUSR2)
5159 signal( SIGUSR2, SIGNAL_CAST sig_usr2 );
5160 #endif /* SIGUSR2 */
5161 #endif /* MEM_MAN */
5163 DEBUG(3,("%s loaded services\n",timestring()));
5165 if (!is_daemon && !is_a_socket(0))
5167 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
5173 DEBUG(3,("%s becoming a daemon\n",timestring()));
5177 if (!directory_exist(lp_lockdir(), NULL)) {
5178 mkdir(lp_lockdir(), 0755);
5182 pidfile_create("smbd");
5185 if (!open_sockets(is_daemon,port))
5188 if (!locking_init(0))
5191 /* possibly reload the services file. */
5192 reload_services(True);
5194 max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
5198 if (sys_chroot(lp_rootdir()) == 0)
5199 DEBUG(2,("%s changed root to %s\n",timestring(),lp_rootdir()));
5202 /* Setup the oplock IPC socket. */
5203 if(!open_oplock_ipc())
5209 exit_server("normal exit");