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 global_myworkgroup;
29 extern pstring global_myname;
31 char *InBuffer = NULL;
32 char *OutBuffer = NULL;
33 char *last_inbuf = NULL;
38 /* the last message the was processed */
39 int last_message = -1;
41 /* a useful macro to debug the last message processed */
42 #define LAST_MESSAGE() smb_fn_name(last_message)
45 extern int DEBUGLEVEL;
46 extern int case_default;
47 extern BOOL case_sensitive;
48 extern BOOL case_preserve;
49 extern BOOL use_mangled_map;
50 extern BOOL short_case_preserve;
51 extern BOOL case_mangle;
52 time_t smb_last_time=(time_t)0;
53 extern BOOL global_machine_pasword_needs_changing;
55 extern int smb_read_error;
57 extern pstring user_socket_options;
60 extern int dcelogin_atmost_once;
64 * This is set on startup - it defines the SID for this
67 extern DOM_SID global_machine_sid;
69 connection_struct Connections[MAX_CONNECTIONS];
70 files_struct Files[MAX_FNUMS];
73 * Indirection for file fd's. Needed as POSIX locking
74 * is based on file/process, not fd/process.
76 file_fd_struct FileFd[MAX_OPEN_FILES];
77 int max_file_fd_used = 0;
82 * Size of data we can send to client. Set
83 * by the client for all protocols above CORE.
84 * Set by us for CORE protocol.
86 int max_send = BUFFER_SIZE;
88 * Size of the data we can receive. Set by us.
89 * Can be modified by the max xmit parameter.
91 int max_recv = BUFFER_SIZE;
93 /* a fnum to use when chaining */
96 /* number of open connections */
97 static int num_connections_open = 0;
99 /* Oplock ipc UDP socket. */
100 int oplock_sock = -1;
101 uint16 oplock_port = 0;
102 /* Current number of oplocks we have outstanding. */
103 int32 global_oplocks_open = 0;
105 BOOL global_oplock_break = False;
107 extern fstring remote_machine;
109 extern pstring OriginalDir;
111 /* these can be set by some functions to override the error codes */
112 int unix_ERR_class=SMB_SUCCESS;
116 extern int extra_time_offset;
118 extern pstring myhostname;
120 static int find_free_connection(int hash);
122 /* for readability... */
123 #define IS_DOS_READONLY(test_mode) (((test_mode) & aRONLY) != 0)
124 #define IS_DOS_DIR(test_mode) (((test_mode) & aDIR) != 0)
125 #define IS_DOS_ARCHIVE(test_mode) (((test_mode) & aARCH) != 0)
126 #define IS_DOS_SYSTEM(test_mode) (((test_mode) & aSYSTEM) != 0)
127 #define IS_DOS_HIDDEN(test_mode) (((test_mode) & aHIDDEN) != 0)
129 /****************************************************************************
130 when exiting, take the whole family
131 ****************************************************************************/
134 exit_server("caught signal");
135 return 0; /* Keep -Wall happy :-) */
137 /****************************************************************************
138 Send a SIGTERM to our process group.
139 *****************************************************************************/
142 if(am_parent) kill(0,SIGTERM);
145 /****************************************************************************
146 change a dos mode to a unix mode
147 base permission for files:
148 everybody gets read bit set
149 dos readonly is represented in unix by removing everyone's write bit
150 dos archive is represented in unix by the user's execute bit
151 dos system is represented in unix by the group's execute bit
152 dos hidden is represented in unix by the other's execute bit
153 Then apply create mask,
155 base permission for directories:
156 dos directory is represented in unix by unix's dir bit and the exec bit
157 Then apply create mask,
159 ****************************************************************************/
160 mode_t unix_mode(int cnum,int dosmode)
162 mode_t result = (S_IRUSR | S_IRGRP | S_IROTH);
164 if ( !IS_DOS_READONLY(dosmode) )
165 result |= (S_IWUSR | S_IWGRP | S_IWOTH);
167 if (IS_DOS_DIR(dosmode)) {
168 /* We never make directories read only for the owner as under DOS a user
169 can always create a file in a read-only directory. */
170 result |= (S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH | S_IWUSR);
171 /* Apply directory mask */
172 result &= lp_dir_mode(SNUM(cnum));
173 /* Add in force bits */
174 result |= lp_force_dir_mode(SNUM(cnum));
176 if (MAP_ARCHIVE(cnum) && IS_DOS_ARCHIVE(dosmode))
179 if (MAP_SYSTEM(cnum) && IS_DOS_SYSTEM(dosmode))
182 if (MAP_HIDDEN(cnum) && IS_DOS_HIDDEN(dosmode))
185 /* Apply mode mask */
186 result &= lp_create_mode(SNUM(cnum));
187 /* Add in force bits */
188 result |= lp_force_create_mode(SNUM(cnum));
194 /****************************************************************************
195 change a unix mode to a dos mode
196 ****************************************************************************/
197 int dos_mode(int cnum,char *path,struct stat *sbuf)
200 extern struct current_user current_user;
202 DEBUG(8,("dos_mode: %d %s\n", cnum, path));
204 if (CAN_WRITE(cnum) && !lp_alternate_permissions(SNUM(cnum))) {
205 if (!((sbuf->st_mode & S_IWOTH) ||
206 Connections[cnum].admin_user ||
207 ((sbuf->st_mode & S_IWUSR) && current_user.uid==sbuf->st_uid) ||
208 ((sbuf->st_mode & S_IWGRP) &&
209 in_group(sbuf->st_gid,current_user.gid,
210 current_user.ngroups,current_user.igroups))))
213 if ((sbuf->st_mode & S_IWUSR) == 0)
217 if (MAP_ARCHIVE(cnum) && ((sbuf->st_mode & S_IXUSR) != 0))
220 if (MAP_SYSTEM(cnum) && ((sbuf->st_mode & S_IXGRP) != 0))
223 if (MAP_HIDDEN(cnum) && ((sbuf->st_mode & S_IXOTH) != 0))
226 if (S_ISDIR(sbuf->st_mode))
227 result = aDIR | (result & aRONLY);
231 if (S_ISLNK(sbuf->st_mode) && S_ISDIR(sbuf->st_mode))
236 /* hide files with a name starting with a . */
237 if (lp_hide_dot_files(SNUM(cnum)))
239 char *p = strrchr(path,'/');
245 if (p[0] == '.' && p[1] != '.' && p[1] != 0)
249 /* Optimization : Only call is_hidden_path if it's not already
251 if (!(result & aHIDDEN) && IS_HIDDEN_PATH(cnum,path))
256 DEBUG(8,("dos_mode returning "));
258 if (result & aHIDDEN) DEBUG(8, ("h"));
259 if (result & aRONLY ) DEBUG(8, ("r"));
260 if (result & aSYSTEM) DEBUG(8, ("s"));
261 if (result & aDIR ) DEBUG(8, ("d"));
262 if (result & aARCH ) DEBUG(8, ("a"));
269 /*******************************************************************
270 chmod a file - but preserve some bits
271 ********************************************************************/
272 int dos_chmod(int cnum,char *fname,int dosmode,struct stat *st)
281 if (sys_stat(fname,st)) return(-1);
284 if (S_ISDIR(st->st_mode)) dosmode |= aDIR;
286 if (dos_mode(cnum,fname,st) == dosmode) return(0);
288 unixmode = unix_mode(cnum,dosmode);
290 /* preserve the s bits */
291 mask |= (S_ISUID | S_ISGID);
293 /* preserve the t bit */
298 /* possibly preserve the x bits */
299 if (!MAP_ARCHIVE(cnum)) mask |= S_IXUSR;
300 if (!MAP_SYSTEM(cnum)) mask |= S_IXGRP;
301 if (!MAP_HIDDEN(cnum)) mask |= S_IXOTH;
303 unixmode |= (st->st_mode & mask);
305 /* if we previously had any r bits set then leave them alone */
306 if ((tmp = st->st_mode & (S_IRUSR|S_IRGRP|S_IROTH))) {
307 unixmode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
311 /* if we previously had any w bits set then leave them alone
312 if the new mode is not rdonly */
313 if (!IS_DOS_READONLY(dosmode) &&
314 (tmp = st->st_mode & (S_IWUSR|S_IWGRP|S_IWOTH))) {
315 unixmode &= ~(S_IWUSR|S_IWGRP|S_IWOTH);
319 return(sys_chmod(fname,unixmode));
322 /*******************************************************************
323 Wrapper around sys_utime that possibly allows DOS semantics rather
325 *******************************************************************/
327 int file_utime(int cnum, char *fname, struct utimbuf *times)
329 extern struct current_user current_user;
335 if(sys_utime(fname, times) == 0)
338 if((errno != EPERM) && (errno != EACCES))
341 if(!lp_dos_filetimes(SNUM(cnum)))
344 /* We have permission (given by the Samba admin) to
345 break POSIX semantics and allow a user to change
346 the time on a file they don't own but can write to
350 if(sys_stat(fname,&sb) != 0)
353 /* Check if we have write access. */
354 if (CAN_WRITE(cnum)) {
355 if (((sb.st_mode & S_IWOTH) ||
356 Connections[cnum].admin_user ||
357 ((sb.st_mode & S_IWUSR) && current_user.uid==sb.st_uid) ||
358 ((sb.st_mode & S_IWGRP) &&
359 in_group(sb.st_gid,current_user.gid,
360 current_user.ngroups,current_user.igroups)))) {
361 /* We are allowed to become root and change the filetime. */
363 ret = sys_utime(fname, times);
364 unbecome_root(False);
371 /*******************************************************************
372 Change a filetime - possibly allowing DOS semantics.
373 *******************************************************************/
375 BOOL set_filetime(int cnum, char *fname, time_t mtime)
377 struct utimbuf times;
379 if (null_mtime(mtime)) return(True);
381 times.modtime = times.actime = mtime;
383 if (file_utime(cnum, fname, ×)) {
384 DEBUG(4,("set_filetime(%s) failed: %s\n",fname,strerror(errno)));
390 /****************************************************************************
391 check if two filenames are equal
393 this needs to be careful about whether we are case sensitive
394 ****************************************************************************/
395 static BOOL fname_equal(char *name1, char *name2)
397 int l1 = strlen(name1);
398 int l2 = strlen(name2);
400 /* handle filenames ending in a single dot */
401 if (l1-l2 == 1 && name1[l1-1] == '.' && lp_strip_dot())
405 ret = fname_equal(name1,name2);
410 if (l2-l1 == 1 && name2[l2-1] == '.' && lp_strip_dot())
414 ret = fname_equal(name1,name2);
419 /* now normal filename handling */
421 return(strcmp(name1,name2) == 0);
423 return(strequal(name1,name2));
427 /****************************************************************************
428 mangle the 2nd name and check if it is then equal to the first name
429 ****************************************************************************/
430 static BOOL mangled_equal(char *name1, char *name2)
434 if (is_8_3(name2, True))
437 pstrcpy(tmpname,name2);
438 mangle_name_83(tmpname,sizeof(tmpname));
440 return(strequal(name1,tmpname));
444 /****************************************************************************
445 scan a directory to find a filename, matching without case sensitivity
447 If the name looks like a mangled name then try via the mangling functions
448 ****************************************************************************/
449 static BOOL scan_directory(char *path, char *name,int cnum,BOOL docache)
456 mangled = is_mangled(name);
458 /* handle null paths */
462 if (docache && (dname = DirCacheCheck(path,name,SNUM(cnum)))) {
463 pstrcpy(name, dname);
468 * The incoming name can be mangled, and if we de-mangle it
469 * here it will not compare correctly against the filename (name2)
470 * read from the directory and then mangled by the name_map_mangle()
471 * call. We need to mangle both names or neither.
475 mangled = !check_mangled_cache( name );
477 /* open the directory */
478 if (!(cur_dir = OpenDir(cnum, path, True)))
480 DEBUG(3,("scan dir didn't open dir [%s]\n",path));
484 /* now scan for matching names */
485 while ((dname = ReadDirName(cur_dir)))
488 (strequal(dname,".") || strequal(dname,"..")))
491 pstrcpy(name2,dname);
492 if (!name_map_mangle(name2,False,SNUM(cnum))) continue;
494 if ((mangled && mangled_equal(name,name2))
495 || fname_equal(name, name2))
497 /* we've found the file, change it's name and return */
498 if (docache) DirCacheAdd(path,name,dname,SNUM(cnum));
499 pstrcpy(name, dname);
509 /****************************************************************************
510 This routine is called to convert names from the dos namespace to unix
511 namespace. It needs to handle any case conversions, mangling, format
514 We assume that we have already done a chdir() to the right "root" directory
517 The function will return False if some part of the name except for the last
518 part cannot be resolved
520 If the saved_last_component != 0, then the unmodified last component
521 of the pathname is returned there. This is used in an exceptional
522 case in reply_mv (so far). If saved_last_component == 0 then nothing
525 The bad_path arg is set to True if the filename walk failed. This is
526 used to pick the correct error code to return between ENOENT and ENOTDIR
527 as Windows applications depend on ERRbadpath being returned if a component
528 of a pathname does not exist.
529 ****************************************************************************/
530 BOOL unix_convert(char *name,int cnum,pstring saved_last_component, BOOL *bad_path)
540 if(saved_last_component)
541 *saved_last_component = 0;
543 /* convert to basic unix format - removing \ chars and cleaning it up */
545 unix_clean_name(name);
547 /* names must be relative to the root of the service - trim any leading /.
548 also trim trailing /'s */
549 trim_string(name,"/","/");
552 * Ensure saved_last_component is valid even if file exists.
554 if(saved_last_component) {
555 end = strrchr(name, '/');
557 pstrcpy(saved_last_component, end + 1);
559 pstrcpy(saved_last_component, name);
562 if (!case_sensitive &&
563 (!case_preserve || (is_8_3(name, False) && !short_case_preserve)))
566 /* check if it's a printer file */
567 if (Connections[cnum].printer)
569 if ((! *name) || strchr(name,'/') || !is_8_3(name, True))
573 slprintf(name2,sizeof(name2)-1,"%.6s.XXXXXX",remote_machine);
574 /* sanitise the name */
575 for (s=name2 ; *s ; s++)
576 if (!issafe(*s)) *s = '_';
577 pstrcpy(name,(char *)mktemp(name2));
582 /* stat the name - if it exists then we are all done! */
583 if (sys_stat(name,&st) == 0)
588 DEBUG(5,("unix_convert(%s,%d)\n",name,cnum));
590 /* a special case - if we don't have any mangling chars and are case
591 sensitive then searching won't help */
592 if (case_sensitive && !is_mangled(name) &&
593 !lp_strip_dot() && !use_mangled_map && (saved_errno != ENOENT))
596 /* now we need to recursively match the name against the real
597 directory structure */
600 while (strncmp(start,"./",2) == 0)
603 /* now match each part of the path name separately, trying the names
604 as is first, then trying to scan the directory for matching names */
605 for (;start;start = (end?end+1:(char *)NULL))
607 /* pinpoint the end of this section of the filename */
608 end = strchr(start, '/');
610 /* chop the name at this point */
613 if(saved_last_component != 0)
614 pstrcpy(saved_last_component, end ? end + 1 : start);
616 /* check if the name exists up to this point */
617 if (sys_stat(name, &st) == 0)
619 /* it exists. it must either be a directory or this must be
620 the last part of the path for it to be OK */
621 if (end && !(st.st_mode & S_IFDIR))
623 /* an intermediate part of the name isn't a directory */
624 DEBUG(5,("Not a dir %s\n",start));
635 /* remember the rest of the pathname so it can be restored
637 if (end) pstrcpy(rest,end+1);
639 /* try to find this part of the path in the directory */
640 if (strchr(start,'?') || strchr(start,'*') ||
641 !scan_directory(dirpath, start, cnum, end?True:False))
645 /* an intermediate part of the name can't be found */
646 DEBUG(5,("Intermediate not found %s\n",start));
648 /* We need to return the fact that the intermediate
649 name resolution failed. This is used to return an
650 error of ERRbadpath rather than ERRbadfile. Some
651 Windows applications depend on the difference between
658 /* just the last part of the name doesn't exist */
659 /* we may need to strupper() or strlower() it in case
660 this conversion is being used for file creation
662 /* if the filename is of mixed case then don't normalise it */
663 if (!case_preserve &&
664 (!strhasupper(start) || !strhaslower(start)))
667 /* check on the mangled stack to see if we can recover the
668 base of the filename */
669 if (is_mangled(start))
670 check_mangled_cache( start );
672 DEBUG(5,("New file %s\n",start));
676 /* restore the rest of the string */
679 pstrcpy(start+strlen(start)+1,rest);
680 end = start + strlen(start);
684 /* add to the dirpath that we have resolved so far */
685 if (*dirpath) pstrcat(dirpath,"/");
686 pstrcat(dirpath,start);
688 /* restore the / that we wiped out earlier */
692 /* the name has been resolved */
693 DEBUG(5,("conversion finished %s\n",name));
698 /****************************************************************************
699 normalise for DOS usage
700 ****************************************************************************/
701 static void disk_norm(int *bsize,int *dfree,int *dsize)
703 /* check if the disk is beyond the max disk size */
704 int maxdisksize = lp_maxdisksize();
706 /* convert to blocks - and don't overflow */
707 maxdisksize = ((maxdisksize*1024)/(*bsize))*1024;
708 if (*dsize > maxdisksize) *dsize = maxdisksize;
709 if (*dfree > maxdisksize) *dfree = maxdisksize-1; /* the -1 should stop
714 while (*dfree > WORDMAX || *dsize > WORDMAX || *bsize < 512)
719 if (*bsize > WORDMAX )
722 if (*dsize > WORDMAX)
724 if (*dfree > WORDMAX)
731 /****************************************************************************
732 return number of 1K blocks available on a path and total number
733 ****************************************************************************/
734 int disk_free(char *path,int *bsize,int *dfree,int *dsize)
736 char *df_command = lp_dfree_command();
757 /* possibly use system() to get the result */
758 if (df_command && *df_command)
764 slprintf(outfile,sizeof(outfile)-1, "%s/dfree.smb.%d",tmpdir(),(int)getpid());
765 slprintf(syscmd,sizeof(syscmd)-1,"%s %s",df_command,path);
766 standard_sub_basic(syscmd);
768 ret = smbrun(syscmd,outfile,False);
769 DEBUG(3,("Running the command `%s' gave %d\n",syscmd,ret));
772 FILE *f = fopen(outfile,"r");
778 fscanf(f,"%d %d %d",dsize,dfree,bsize);
782 DEBUG(0,("Can't open %s\n",outfile));
786 disk_norm(bsize,dfree,dsize);
787 dfree_retval = ((*bsize)/1024)*(*dfree);
789 /* Ensure we return the min value between the users quota and
790 what's free on the disk. Thanks to Albrecht Gebhardt
791 <albrecht.gebhardt@uni-klu.ac.at> for this fix.
793 if (disk_quotas(path, &bsizeq, &dfreeq, &dsizeq))
795 disk_norm(&bsizeq, &dfreeq, &dsizeq);
796 dfreeq_retval = ((bsizeq)/1024)*(dfreeq);
797 dfree_retval = ( dfree_retval < dfreeq_retval ) ?
798 dfree_retval : dfreeq_retval ;
799 /* maybe dfree and dfreeq are calculated using different bsizes
800 so convert dfree from bsize into bsizeq */
801 /* avoid overflows due to multiplication, so do not:
802 *dfree = ((*dfree) * (*bsize)) / (bsizeq);
803 bsize and bsizeq are powers of 2 so its better to
804 to divide them getting a multiplication or division factor
805 for dfree. Rene Nieuwenhuizen (07-10-1997) */
806 if (*bsize >= bsizeq)
807 *dfree = *dfree * (*bsize / bsizeq);
809 *dfree = *dfree / (bsizeq / *bsize);
810 *dfree = ( *dfree < dfreeq ) ? *dfree : dfreeq ;
815 return(dfree_retval);
819 DEBUG(1,("Warning - no statfs function\n"));
823 if (statfs(path,&fs,sizeof(fs),0) != 0)
826 if (statvfs(path, &fs))
829 if (statfs(path,&fs,sizeof(fs)) == -1)
831 if (statfs(path,&fs) == -1)
833 #endif /* USE_STATVFS */
836 DEBUG(3,("dfree call failed code errno=%d\n",errno));
840 return(((*bsize)/1024)*(*dfree));
845 *dfree = fs.fd_req.bfree;
846 *dsize = fs.fd_req.btot;
849 *bsize = fs.f_frsize;
852 /* eg: osf1 has f_fsize = fundamental filesystem block size,
853 f_bsize = optimal transfer block size (MX: 94-04-19) */
858 #endif /* USE_STATVFS */
863 *dfree = fs.f_bavail;
865 *dsize = fs.f_blocks;
868 #if defined(SCO) || defined(ISC) || defined(MIPS)
872 /* handle rediculous bsize values - some OSes are broken */
873 if ((*bsize) < 512 || (*bsize)>0xFFFF) *bsize = 1024;
875 disk_norm(bsize,dfree,dsize);
881 DEBUG(0,("dfree seems to be broken on your system\n"));
882 *dsize = 20*1024*1024/(*bsize);
883 *dfree = MAX(1,*dfree);
885 dfree_retval = ((*bsize)/1024)*(*dfree);
887 /* Ensure we return the min value between the users quota and
888 what's free on the disk. Thanks to Albrecht Gebhardt
889 <albrecht.gebhardt@uni-klu.ac.at> for this fix.
891 if (disk_quotas(path, &bsizeq, &dfreeq, &dsizeq))
893 disk_norm(&bsizeq, &dfreeq, &dsizeq);
894 dfreeq_retval = ((bsizeq)/1024)*(dfreeq);
895 dfree_retval = ( dfree_retval < dfreeq_retval ) ?
896 dfree_retval : dfreeq_retval ;
897 /* maybe dfree and dfreeq are calculated using different bsizes
898 so convert dfree from bsize into bsizeq */
899 /* avoid overflows due to multiplication, so do not:
900 *dfree = ((*dfree) * (*bsize)) / (bsizeq);
901 bsize and bsizeq are powers of 2 so its better to
902 to divide them getting a multiplication or division factor
903 for dfree. Rene Nieuwenhuizen (07-10-1997) */
904 if (*bsize >= bsizeq)
905 *dfree = *dfree * (*bsize / bsizeq);
907 *dfree = *dfree / (bsizeq / *bsize);
908 *dfree = ( *dfree < dfreeq ) ? *dfree : dfreeq ;
913 return(dfree_retval);
918 /****************************************************************************
919 wrap it to get filenames right
920 ****************************************************************************/
921 int sys_disk_free(char *path,int *bsize,int *dfree,int *dsize)
923 return(disk_free(dos_to_unix(path,False),bsize,dfree,dsize));
928 /****************************************************************************
929 check a filename - possibly caling reducename
931 This is called by every routine before it allows an operation on a filename.
932 It does any final confirmation necessary to ensure that the filename is
933 a valid one for the user to access.
934 ****************************************************************************/
935 BOOL check_name(char *name,int cnum)
941 if( IS_VETO_PATH(cnum, name))
943 DEBUG(5,("file path name %s vetoed\n",name));
947 ret = reduce_name(name,Connections[cnum].connectpath,lp_widelinks(SNUM(cnum)));
949 /* Check if we are allowing users to follow symlinks */
950 /* Patch from David Clerc <David.Clerc@cui.unige.ch>
951 University of Geneva */
954 if (!lp_symlinks(SNUM(cnum)))
957 if ( (sys_lstat(name,&statbuf) != -1) &&
958 (S_ISLNK(statbuf.st_mode)) )
960 DEBUG(3,("check_name: denied: file path name %s is a symlink\n",name));
967 DEBUG(5,("check_name on %s failed\n",name));
972 /****************************************************************************
973 check a filename - possibly caling reducename
974 ****************************************************************************/
975 static void check_for_pipe(char *fname)
977 /* special case of pipe opens */
981 if (strstr(s,"pipe/"))
983 DEBUG(3,("Rejecting named pipe open for %s\n",fname));
984 unix_ERR_class = ERRSRV;
985 unix_ERR_code = ERRaccess;
989 /****************************************************************************
990 fd support routines - attempt to do a sys_open
991 ****************************************************************************/
992 static int fd_attempt_open(char *fname, int flags, int mode)
994 int fd = sys_open(fname,flags,mode);
996 /* Fix for files ending in '.' */
997 if((fd == -1) && (errno == ENOENT) &&
998 (strchr(fname,'.')==NULL))
1001 fd = sys_open(fname,flags,mode);
1004 #if (defined(ENAMETOOLONG) && defined(HAVE_PATHCONF))
1005 if ((fd == -1) && (errno == ENAMETOOLONG))
1008 char *p = strrchr(fname, '/');
1010 if (p == fname) /* name is "/xxx" */
1012 max_len = pathconf("/", _PC_NAME_MAX);
1015 else if ((p == NULL) || (p == fname))
1018 max_len = pathconf(".", _PC_NAME_MAX);
1023 max_len = pathconf(fname, _PC_NAME_MAX);
1027 if (strlen(p) > max_len)
1029 char tmp = p[max_len];
1032 if ((fd = sys_open(fname,flags,mode)) == -1)
1040 /****************************************************************************
1041 Cache a uid_t currently with this file open. This is an optimization only
1042 used when multiple sessionsetup's have been done to one smbd.
1043 ****************************************************************************/
1044 static void fd_add_to_uid_cache(file_fd_struct *fd_ptr, uid_t u)
1046 if(fd_ptr->uid_cache_count >= sizeof(fd_ptr->uid_users_cache)/sizeof(uid_t))
1048 fd_ptr->uid_users_cache[fd_ptr->uid_cache_count++] = u;
1051 /****************************************************************************
1052 Remove a uid_t that currently has this file open. This is an optimization only
1053 used when multiple sessionsetup's have been done to one smbd.
1054 ****************************************************************************/
1055 static void fd_remove_from_uid_cache(file_fd_struct *fd_ptr, uid_t u)
1058 for(i = 0; i < fd_ptr->uid_cache_count; i++)
1059 if(fd_ptr->uid_users_cache[i] == u) {
1060 if(i < (fd_ptr->uid_cache_count-1))
1061 memmove((char *)&fd_ptr->uid_users_cache[i], (char *)&fd_ptr->uid_users_cache[i+1],
1062 sizeof(uid_t)*(fd_ptr->uid_cache_count-1-i) );
1063 fd_ptr->uid_cache_count--;
1068 /****************************************************************************
1069 Check if a uid_t that currently has this file open is present. This is an
1070 optimization only used when multiple sessionsetup's have been done to one smbd.
1071 ****************************************************************************/
1072 static BOOL fd_is_in_uid_cache(file_fd_struct *fd_ptr, uid_t u)
1075 for(i = 0; i < fd_ptr->uid_cache_count; i++)
1076 if(fd_ptr->uid_users_cache[i] == u)
1081 /****************************************************************************
1082 fd support routines - attempt to find an already open file by dev
1083 and inode - increments the ref_count of the returned file_fd_struct *.
1084 ****************************************************************************/
1085 static file_fd_struct *fd_get_already_open(struct stat *sbuf)
1088 file_fd_struct *fd_ptr;
1093 for(i = 0; i <= max_file_fd_used; i++) {
1094 fd_ptr = &FileFd[i];
1095 if((fd_ptr->ref_count > 0) &&
1096 (((uint32)sbuf->st_dev) == fd_ptr->dev) &&
1097 (((uint32)sbuf->st_ino) == fd_ptr->inode)) {
1098 fd_ptr->ref_count++;
1100 ("Re-used file_fd_struct %d, dev = %x, inode = %x, ref_count = %d\n",
1101 i, fd_ptr->dev, fd_ptr->inode, fd_ptr->ref_count));
1108 /****************************************************************************
1109 fd support routines - attempt to find a empty slot in the FileFd array.
1110 Increments the ref_count of the returned entry.
1111 ****************************************************************************/
1112 static file_fd_struct *fd_get_new(void)
1114 extern struct current_user current_user;
1116 file_fd_struct *fd_ptr;
1118 for(i = 0; i < MAX_OPEN_FILES; i++) {
1119 fd_ptr = &FileFd[i];
1120 if(fd_ptr->ref_count == 0) {
1121 fd_ptr->dev = (uint32)-1;
1122 fd_ptr->inode = (uint32)-1;
1124 fd_ptr->fd_readonly = -1;
1125 fd_ptr->fd_writeonly = -1;
1126 fd_ptr->real_open_flags = -1;
1127 fd_ptr->uid_cache_count = 0;
1128 fd_add_to_uid_cache(fd_ptr, (uid_t)current_user.uid);
1129 fd_ptr->ref_count++;
1130 /* Increment max used counter if neccessary, cuts down
1131 on search time when re-using */
1132 if(i > max_file_fd_used)
1133 max_file_fd_used = i;
1134 DEBUG(3,("Allocated new file_fd_struct %d, dev = %x, inode = %x\n",
1135 i, fd_ptr->dev, fd_ptr->inode));
1139 DEBUG(1,("ERROR! Out of file_fd structures - perhaps increase MAX_OPEN_FILES?\n"));
1143 /****************************************************************************
1144 fd support routines - attempt to re-open an already open fd as O_RDWR.
1145 Save the already open fd (we cannot close due to POSIX file locking braindamage.
1146 ****************************************************************************/
1147 static void fd_attempt_reopen(char *fname, int mode, file_fd_struct *fd_ptr)
1149 int fd = sys_open( fname, O_RDWR, mode);
1154 if(fd_ptr->real_open_flags == O_RDONLY)
1155 fd_ptr->fd_readonly = fd_ptr->fd;
1156 if(fd_ptr->real_open_flags == O_WRONLY)
1157 fd_ptr->fd_writeonly = fd_ptr->fd;
1160 fd_ptr->real_open_flags = O_RDWR;
1163 /****************************************************************************
1164 fd support routines - attempt to close the file referenced by this fd.
1165 Decrements the ref_count and returns it.
1166 ****************************************************************************/
1167 static int fd_attempt_close(file_fd_struct *fd_ptr)
1169 extern struct current_user current_user;
1171 DEBUG(3,("fd_attempt_close on file_fd_struct %d, fd = %d, dev = %x, inode = %x, open_flags = %d, ref_count = %d.\n",
1172 fd_ptr - &FileFd[0],
1173 fd_ptr->fd, fd_ptr->dev, fd_ptr->inode,
1174 fd_ptr->real_open_flags,
1175 fd_ptr->ref_count));
1176 if(fd_ptr->ref_count > 0) {
1177 fd_ptr->ref_count--;
1178 if(fd_ptr->ref_count == 0) {
1179 if(fd_ptr->fd != -1)
1181 if(fd_ptr->fd_readonly != -1)
1182 close(fd_ptr->fd_readonly);
1183 if(fd_ptr->fd_writeonly != -1)
1184 close(fd_ptr->fd_writeonly);
1186 fd_ptr->fd_readonly = -1;
1187 fd_ptr->fd_writeonly = -1;
1188 fd_ptr->real_open_flags = -1;
1189 fd_ptr->dev = (uint32)-1;
1190 fd_ptr->inode = (uint32)-1;
1191 fd_ptr->uid_cache_count = 0;
1193 fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
1195 return fd_ptr->ref_count;
1198 /****************************************************************************
1199 fd support routines - check that current user has permissions
1200 to open this file. Used when uid not found in optimization cache.
1201 This is really ugly code, as due to POSIX locking braindamage we must
1202 fork and then attempt to open the file, and return success or failure
1204 ****************************************************************************/
1205 static BOOL check_access_allowed_for_current_user( char *fname, int accmode )
1209 if((child_pid = fork()) < 0) {
1210 DEBUG(0,("check_access_allowed_for_current_user: fork failed.\n"));
1220 if ((wpid = sys_waitpid(child_pid, &status_code, 0)) < 0) {
1221 DEBUG(0,("check_access_allowed_for_current_user: The process is no longer waiting!\n"));
1225 if (child_pid != wpid) {
1226 DEBUG(0,("check_access_allowed_for_current_user: We were waiting for the wrong process ID\n"));
1229 #if defined(WIFEXITED) && defined(WEXITSTATUS)
1230 if (WIFEXITED(status_code) == 0) {
1231 DEBUG(0,("check_access_allowed_for_current_user: The process exited while we were waiting\n"));
1234 if (WEXITSTATUS(status_code) != 0) {
1235 DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access denied.\n", status_code));
1238 #else /* defined(WIFEXITED) && defined(WEXITSTATUS) */
1239 if(status_code != 0) {
1240 DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access denied.\n", status_code));
1243 #endif /* defined(WIFEXITED) && defined(WEXITSTATUS) */
1246 * Success - the child could open the file.
1248 DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access allowed.\n", status_code));
1255 DEBUG(9,("check_access_allowed_for_current_user: Child - attempting to open %s with mode %d.\n", fname, accmode ));
1256 if((fd = fd_attempt_open( fname, accmode, 0)) < 0) {
1257 /* Access denied. */
1261 DEBUG(9,("check_access_allowed_for_current_user: Child - returning ok.\n"));
1268 /****************************************************************************
1270 ****************************************************************************/
1271 static void open_file(int fnum,int cnum,char *fname1,int flags,int mode, struct stat *sbuf)
1273 extern struct current_user current_user;
1275 struct stat statbuf;
1276 file_fd_struct *fd_ptr;
1277 files_struct *fsp = &Files[fnum];
1278 int accmode = (flags & (O_RDONLY | O_WRONLY | O_RDWR));
1282 fsp->granted_oplock = False;
1285 pstrcpy(fname,fname1);
1287 /* check permissions */
1290 * This code was changed after seeing a client open request
1291 * containing the open mode of (DENY_WRITE/read-only) with
1292 * the 'create if not exist' bit set. The previous code
1293 * would fail to open the file read only on a read-only share
1294 * as it was checking the flags parameter directly against O_RDONLY,
1295 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1299 if (!CAN_WRITE(cnum) && !Connections[cnum].printer) {
1300 /* It's a read-only share - fail if we wanted to write. */
1301 if(accmode != O_RDONLY) {
1302 DEBUG(3,("Permission denied opening %s\n",fname));
1303 check_for_pipe(fname);
1306 else if(flags & O_CREAT) {
1307 /* We don't want to write - but we must make sure that O_CREAT
1308 doesn't create the file if we have write access into the
1315 /* this handles a bug in Win95 - it doesn't say to create the file when it
1317 if (Connections[cnum].printer)
1321 if (flags == O_WRONLY)
1322 DEBUG(3,("Bug in client? Set O_WRONLY without O_CREAT\n"));
1326 * Ensure we have a valid struct stat so we can search the
1330 if(sys_stat(fname, &statbuf) < 0) {
1331 if(errno != ENOENT) {
1332 DEBUG(3,("Error doing stat on file %s (%s)\n",
1333 fname,strerror(errno)));
1335 check_for_pipe(fname);
1345 * Check to see if we have this file already
1346 * open. If we do, just use the already open fd and increment the
1347 * reference count (fd_get_already_open increments the ref_count).
1349 if((fd_ptr = fd_get_already_open(sbuf))!= 0) {
1351 * File was already open.
1355 * Check it wasn't open for exclusive use.
1357 if((flags & O_CREAT) && (flags & O_EXCL)) {
1358 fd_ptr->ref_count--;
1364 * Ensure that the user attempting to open
1365 * this file has permissions to do so, if
1366 * the user who originally opened the file wasn't
1367 * the same as the current user.
1370 if(!fd_is_in_uid_cache(fd_ptr, (uid_t)current_user.uid)) {
1371 if(!check_access_allowed_for_current_user( fname, accmode )) {
1372 /* Error - permission denied. */
1373 DEBUG(3,("Permission denied opening file %s (flags=%d, accmode = %d)\n",
1374 fname, flags, accmode));
1375 /* Ensure the ref_count is decremented. */
1376 fd_ptr->ref_count--;
1377 fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
1383 fd_add_to_uid_cache(fd_ptr, (uid_t)current_user.uid);
1386 * If not opened O_RDWR try
1387 * and do that here - a chmod may have been done
1388 * between the last open and now.
1390 if(fd_ptr->real_open_flags != O_RDWR)
1391 fd_attempt_reopen(fname, mode, fd_ptr);
1394 * Ensure that if we wanted write access
1395 * it has been opened for write, and if we wanted read it
1396 * was open for read.
1398 if(((accmode == O_WRONLY) && (fd_ptr->real_open_flags == O_RDONLY)) ||
1399 ((accmode == O_RDONLY) && (fd_ptr->real_open_flags == O_WRONLY)) ||
1400 ((accmode == O_RDWR) && (fd_ptr->real_open_flags != O_RDWR))) {
1401 DEBUG(3,("Error opening (already open for flags=%d) file %s (%s) (flags=%d)\n",
1402 fd_ptr->real_open_flags, fname,strerror(EACCES),flags));
1403 check_for_pipe(fname);
1404 fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
1405 fd_ptr->ref_count--;
1411 /* We need to allocate a new file_fd_struct (this increments the
1413 if((fd_ptr = fd_get_new()) == 0)
1416 * Whatever the requested flags, attempt read/write access,
1417 * as we don't know what flags future file opens may require.
1418 * If this fails, try again with the required flags.
1419 * Even if we open read/write when only read access was
1420 * requested the setting of the can_write flag in
1421 * the file_struct will protect us from errant
1422 * write requests. We never need to worry about O_APPEND
1423 * as this is not set anywhere in Samba.
1425 fd_ptr->real_open_flags = O_RDWR;
1426 /* Set the flags as needed without the read/write modes. */
1427 open_flags = flags & ~(O_RDWR|O_WRONLY|O_RDONLY);
1428 fd_ptr->fd = fd_attempt_open(fname, open_flags|O_RDWR, mode);
1430 * On some systems opening a file for R/W access on a read only
1431 * filesystems sets errno to EROFS.
1434 if((fd_ptr->fd == -1) && ((errno == EACCES) || (errno == EROFS))) {
1435 #else /* No EROFS */
1436 if((fd_ptr->fd == -1) && (errno == EACCES)) {
1438 if(flags & O_WRONLY) {
1439 fd_ptr->fd = fd_attempt_open(fname, open_flags|O_WRONLY, mode);
1440 fd_ptr->real_open_flags = O_WRONLY;
1442 fd_ptr->fd = fd_attempt_open(fname, open_flags|O_RDONLY, mode);
1443 fd_ptr->real_open_flags = O_RDONLY;
1448 if ((fd_ptr->fd >=0) &&
1449 Connections[cnum].printer && lp_minprintspace(SNUM(cnum))) {
1453 pstrcpy(dname,fname);
1454 p = strrchr(dname,'/');
1456 if (sys_disk_free(dname,&dum1,&dum2,&dum3) <
1457 lp_minprintspace(SNUM(cnum))) {
1458 fd_attempt_close(fd_ptr);
1460 if(fd_ptr->ref_count == 0)
1469 DEBUG(3,("Error opening file %s (%s) (flags=%d)\n",
1470 fname,strerror(errno),flags));
1471 /* Ensure the ref_count is decremented. */
1472 fd_attempt_close(fd_ptr);
1473 check_for_pipe(fname);
1477 if (fd_ptr->fd >= 0)
1481 if(fstat(fd_ptr->fd, &statbuf) == -1) {
1482 /* Error - backout !! */
1483 DEBUG(3,("Error doing fstat on fd %d, file %s (%s)\n",
1484 fd_ptr->fd, fname,strerror(errno)));
1485 /* Ensure the ref_count is decremented. */
1486 fd_attempt_close(fd_ptr);
1492 /* Set the correct entries in fd_ptr. */
1493 fd_ptr->dev = (uint32)sbuf->st_dev;
1494 fd_ptr->inode = (uint32)sbuf->st_ino;
1496 fsp->fd_ptr = fd_ptr;
1497 Connections[cnum].num_files_open++;
1498 fsp->mode = sbuf->st_mode;
1499 GetTimeOfDay(&fsp->open_time);
1500 fsp->vuid = current_user.vuid;
1504 fsp->mmap_ptr = NULL;
1506 fsp->can_lock = True;
1507 fsp->can_read = ((flags & O_WRONLY)==0);
1508 fsp->can_write = ((flags & (O_WRONLY|O_RDWR))!=0);
1509 fsp->share_mode = 0;
1510 fsp->print_file = Connections[cnum].printer;
1511 fsp->modified = False;
1512 fsp->granted_oplock = False;
1513 fsp->sent_oplock_break = False;
1514 fsp->is_directory = False;
1517 * Note that the file name here is the *untranslated* name
1518 * ie. it is still in the DOS codepage sent from the client.
1519 * All use of this filename will pass though the sys_xxxx
1520 * functions which will do the dos_to_unix translation before
1521 * mapping into a UNIX filename. JRA.
1523 string_set(&fsp->name,fname);
1524 fsp->wbmpx_ptr = NULL;
1527 * If the printer is marked as postscript output a leading
1528 * file identifier to ensure the file is treated as a raw
1530 * This has a similar effect as CtrlD=0 in WIN.INI file.
1531 * tim@fsg.com 09/06/94
1533 if (fsp->print_file && POSTSCRIPT(cnum) && fsp->can_write)
1535 DEBUG(3,("Writing postscript line\n"));
1536 write_file(fnum,"%!\n",3);
1539 DEBUG(2,("%s %s opened file %s read=%s write=%s (numopen=%d fnum=%d)\n",
1541 *sesssetup_user ? sesssetup_user : Connections[cnum].user,fname,
1542 BOOLSTR(fsp->can_read),BOOLSTR(fsp->can_write),
1543 Connections[cnum].num_files_open,fnum));
1548 /* mmap it if read-only */
1549 if (!fsp->can_write)
1551 fsp->mmap_size = file_size(fname);
1552 fsp->mmap_ptr = (char *)mmap(NULL,fsp->mmap_size,
1553 PROT_READ,MAP_SHARED,fsp->fd_ptr->fd,0);
1555 if (fsp->mmap_ptr == (char *)-1 || !fsp->mmap_ptr)
1557 DEBUG(3,("Failed to mmap() %s - %s\n",fname,strerror(errno)));
1558 fsp->mmap_ptr = NULL;
1564 /*******************************************************************
1566 ********************************************************************/
1567 void sync_file(int fnum)
1570 fsync(Files[fnum].fd_ptr->fd);
1574 /****************************************************************************
1575 run a file if it is a magic script
1576 ****************************************************************************/
1577 static void check_magic(int fnum,int cnum)
1579 if (!*lp_magicscript(SNUM(cnum)))
1582 DEBUG(5,("checking magic for %s\n",Files[fnum].name));
1586 if (!(p = strrchr(Files[fnum].name,'/')))
1587 p = Files[fnum].name;
1591 if (!strequal(lp_magicscript(SNUM(cnum)),p))
1597 pstring magic_output;
1599 pstrcpy(fname,Files[fnum].name);
1601 if (*lp_magicoutput(SNUM(cnum)))
1602 pstrcpy(magic_output,lp_magicoutput(SNUM(cnum)));
1604 slprintf(magic_output,sizeof(fname)-1, "%s.out",fname);
1607 ret = smbrun(fname,magic_output,False);
1608 DEBUG(3,("Invoking magic command %s gave %d\n",fname,ret));
1613 /****************************************************************************
1614 Common code to close a file or a directory.
1615 ****************************************************************************/
1617 static void close_filestruct(files_struct *fs_p)
1619 int cnum = fs_p->cnum;
1621 fs_p->reserved = False;
1623 fs_p->is_directory = False;
1625 Connections[cnum].num_files_open--;
1628 free((char *)fs_p->wbmpx_ptr);
1629 fs_p->wbmpx_ptr = NULL;
1635 munmap(fs_p->mmap_ptr,fs_p->mmap_size);
1636 fs_p->mmap_ptr = NULL;
1641 /****************************************************************************
1642 Close a file - possibly invalidating the read prediction.
1644 If normal_close is 1 then this came from a normal SMBclose (or equivalent)
1645 operation otherwise it came as the result of some other operation such as
1646 the closing of the connection. In the latter case printing and
1647 magic scripts are not run.
1648 ****************************************************************************/
1650 void close_file(int fnum, BOOL normal_close)
1652 files_struct *fs_p = &Files[fnum];
1653 int cnum = fs_p->cnum;
1654 uint32 dev = fs_p->fd_ptr->dev;
1655 uint32 inode = fs_p->fd_ptr->inode;
1658 close_filestruct(fs_p);
1660 #if USE_READ_PREDICTION
1661 invalidate_read_prediction(fs_p->fd_ptr->fd);
1664 if (lp_share_modes(SNUM(cnum)))
1666 lock_share_entry( cnum, dev, inode, &token);
1667 del_share_mode(token, fnum);
1670 fd_attempt_close(fs_p->fd_ptr);
1672 if (lp_share_modes(SNUM(cnum)))
1673 unlock_share_entry( cnum, dev, inode, token);
1675 /* NT uses smbclose to start a print - weird */
1676 if (normal_close && fs_p->print_file)
1679 /* check for magic scripts */
1681 check_magic(fnum,cnum);
1683 if(fs_p->granted_oplock == True)
1684 global_oplocks_open--;
1686 fs_p->sent_oplock_break = False;
1688 DEBUG(2,("%s %s closed file %s (numopen=%d)\n",
1689 timestring(),Connections[cnum].user,fs_p->name,
1690 Connections[cnum].num_files_open));
1693 string_free(&fs_p->name);
1696 /* we will catch bugs faster by zeroing this structure */
1697 memset(fs_p, 0, sizeof(*fs_p));
1700 /****************************************************************************
1701 Close a directory opened by an NT SMB call.
1702 ****************************************************************************/
1704 void close_directory(int fnum)
1706 files_struct *fs_p = &Files[fnum];
1709 * Do the code common to files and directories.
1711 close_filestruct(fs_p);
1714 string_free(&fs_p->name);
1717 /* we will catch bugs faster by zeroing this structure */
1718 memset(fs_p, 0, sizeof(*fs_p));
1721 /****************************************************************************
1722 Open a directory from an NT SMB call.
1723 ****************************************************************************/
1725 void open_directory(int fnum,int cnum,char *fname, int *action)
1727 extern struct current_user current_user;
1728 files_struct *fsp = &Files[fnum];
1731 Connections[cnum].num_files_open++;
1733 GetTimeOfDay(&fsp->open_time);
1734 fsp->vuid = current_user.vuid;
1738 fsp->mmap_ptr = NULL;
1740 fsp->can_lock = True;
1741 fsp->can_read = False;
1742 fsp->can_write = False;
1743 fsp->share_mode = 0;
1744 fsp->print_file = False;
1745 fsp->modified = False;
1746 fsp->granted_oplock = False;
1747 fsp->sent_oplock_break = False;
1748 fsp->is_directory = True;
1751 * Note that the file name here is the *untranslated* name
1752 * ie. it is still in the DOS codepage sent from the client.
1753 * All use of this filename will pass though the sys_xxxx
1754 * functions which will do the dos_to_unix translation before
1755 * mapping into a UNIX filename. JRA.
1757 string_set(&fsp->name,fname);
1758 fsp->wbmpx_ptr = NULL;
1760 *action = FILE_WAS_OPENED;
1763 enum {AFAIL,AREAD,AWRITE,AALL};
1765 /*******************************************************************
1766 reproduce the share mode access table
1767 ********************************************************************/
1768 static int access_table(int new_deny,int old_deny,int old_mode,
1769 int share_pid,char *fname)
1771 if (new_deny == DENY_ALL || old_deny == DENY_ALL) return(AFAIL);
1773 if (new_deny == DENY_DOS || old_deny == DENY_DOS) {
1775 if (old_deny == new_deny && share_pid == pid)
1778 if (old_mode == 0) return(AREAD);
1780 /* the new smbpub.zip spec says that if the file extension is
1781 .com, .dll, .exe or .sym then allow the open. I will force
1782 it to read-only as this seems sensible although the spec is
1783 a little unclear on this. */
1784 if ((fname = strrchr(fname,'.'))) {
1785 if (strequal(fname,".com") ||
1786 strequal(fname,".dll") ||
1787 strequal(fname,".exe") ||
1788 strequal(fname,".sym"))
1798 if (old_deny==DENY_WRITE && old_mode==0) return(AREAD);
1799 if (old_deny==DENY_READ && old_mode==0) return(AWRITE);
1800 if (old_deny==DENY_NONE && old_mode==0) return(AALL);
1803 if (old_deny==DENY_WRITE && old_mode==1) return(AREAD);
1804 if (old_deny==DENY_READ && old_mode==1) return(AWRITE);
1805 if (old_deny==DENY_NONE && old_mode==1) return(AALL);
1808 if (old_deny==DENY_WRITE) return(AREAD);
1809 if (old_deny==DENY_READ) return(AWRITE);
1810 if (old_deny==DENY_NONE) return(AALL);
1816 /*******************************************************************
1817 check if the share mode on a file allows it to be deleted or unlinked
1818 return True if sharing doesn't prevent the operation
1819 ********************************************************************/
1820 BOOL check_file_sharing(int cnum,char *fname, BOOL rename_op)
1824 share_mode_entry *old_shares = 0;
1825 int num_share_modes;
1831 if(!lp_share_modes(SNUM(cnum)))
1834 if (sys_stat(fname,&sbuf) == -1) return(True);
1836 dev = (uint32)sbuf.st_dev;
1837 inode = (uint32)sbuf.st_ino;
1839 lock_share_entry(cnum, dev, inode, &token);
1840 num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
1843 * Check if the share modes will give us access.
1846 if(num_share_modes != 0)
1853 broke_oplock = False;
1854 for(i = 0; i < num_share_modes; i++)
1856 share_mode_entry *share_entry = &old_shares[i];
1859 * Break oplocks before checking share modes. See comment in
1860 * open_file_shared for details.
1861 * Check if someone has an oplock on this file. If so we must
1862 * break it before continuing.
1864 if(share_entry->op_type & BATCH_OPLOCK)
1868 * It appears that the NT redirector may have a bug, in that
1869 * it tries to do an SMBmv on a file that it has open with a
1870 * batch oplock, and then fails to respond to the oplock break
1871 * request. This only seems to occur when the client is doing an
1872 * SMBmv to the smbd it is using - thus we try and detect this
1873 * condition by checking if the file being moved is open and oplocked by
1874 * this smbd process, and then not sending the oplock break in this
1875 * special case. If the file was open with a deny mode that
1876 * prevents the move the SMBmv will fail anyway with a share
1877 * violation error. JRA.
1879 if(rename_op && (share_entry->pid == pid))
1881 DEBUG(0,("check_file_sharing: NT redirector workaround - rename attempted on \
1882 batch oplocked file %s, dev = %x, inode = %x\n", fname, dev, inode));
1884 * This next line is a test that allows the deny-mode
1885 * processing to be skipped. This seems to be needed as
1886 * NT insists on the rename succeeding (in Office 9x no less !).
1887 * This should be removed as soon as (a) MS fix the redirector
1888 * bug or (b) NT SMB support in Samba makes NT not issue the
1889 * call (as is my fervent hope). JRA.
1895 DEBUG(5,("check_file_sharing: breaking oplock (%x) on file %s, \
1896 dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
1898 /* Oplock break.... */
1899 unlock_share_entry(cnum, dev, inode, token);
1900 if(request_oplock_break(share_entry, dev, inode) == False)
1902 free((char *)old_shares);
1903 DEBUG(0,("check_file_sharing: FAILED when breaking oplock (%x) on file %s, \
1904 dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
1907 lock_share_entry(cnum, dev, inode, &token);
1908 broke_oplock = True;
1913 /* someone else has a share lock on it, check to see
1915 if ((share_entry->share_mode != DENY_DOS) || (share_entry->pid != pid))
1922 free((char *)old_shares);
1923 num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
1925 } while(broke_oplock);
1928 /* XXXX exactly what share mode combinations should be allowed for
1929 deleting/renaming? */
1930 /* If we got here then either there were no share modes or
1931 all share modes were DENY_DOS and the pid == getpid() */
1936 unlock_share_entry(cnum, dev, inode, token);
1937 if(old_shares != NULL)
1938 free((char *)old_shares);
1942 /****************************************************************************
1944 Helper for open_file_shared.
1945 Truncate a file after checking locking; close file if locked.
1946 **************************************************************************/
1947 static void truncate_unless_locked(int fnum, int cnum, int token,
1950 if (Files[fnum].can_write){
1951 if (is_locked(fnum,cnum,0x3FFFFFFF,0)){
1952 /* If share modes are in force for this connection we
1953 have the share entry locked. Unlock it before closing. */
1954 if (*share_locked && lp_share_modes(SNUM(cnum)))
1955 unlock_share_entry( cnum, Files[fnum].fd_ptr->dev,
1956 Files[fnum].fd_ptr->inode, token);
1957 close_file(fnum,False);
1958 /* Share mode no longer locked. */
1959 *share_locked = False;
1961 unix_ERR_class = ERRDOS;
1962 unix_ERR_code = ERRlock;
1965 ftruncate(Files[fnum].fd_ptr->fd,0);
1969 /****************************************************************************
1970 check if we can open a file with a share mode
1971 ****************************************************************************/
1972 int check_share_mode( share_mode_entry *share, int deny_mode, char *fname,
1973 BOOL fcbopen, int *flags)
1975 int old_open_mode = share->share_mode &0xF;
1976 int old_deny_mode = (share->share_mode >>4)&7;
1978 if (old_deny_mode > 4 || old_open_mode > 2)
1980 DEBUG(0,("Invalid share mode found (%d,%d,%d) on file %s\n",
1981 deny_mode,old_deny_mode,old_open_mode,fname));
1986 int access_allowed = access_table(deny_mode,old_deny_mode,old_open_mode,
1989 if ((access_allowed == AFAIL) ||
1990 (!fcbopen && (access_allowed == AREAD && *flags == O_RDWR)) ||
1991 (access_allowed == AREAD && *flags == O_WRONLY) ||
1992 (access_allowed == AWRITE && *flags == O_RDONLY))
1994 DEBUG(2,("Share violation on file (%d,%d,%d,%d,%s,fcbopen = %d, flags = %d) = %d\n",
1995 deny_mode,old_deny_mode,old_open_mode,
1996 share->pid,fname, fcbopen, *flags, access_allowed));
2000 if (access_allowed == AREAD)
2003 if (access_allowed == AWRITE)
2010 /****************************************************************************
2011 open a file with a share mode
2012 ****************************************************************************/
2013 void open_file_shared(int fnum,int cnum,char *fname,int share_mode,int ofun,
2014 int mode,int oplock_request, int *Access,int *action)
2016 files_struct *fs_p = &Files[fnum];
2019 int deny_mode = (share_mode>>4)&7;
2021 BOOL file_existed = file_exist(fname,&sbuf);
2022 BOOL share_locked = False;
2023 BOOL fcbopen = False;
2027 int num_share_modes = 0;
2032 /* this is for OS/2 EAs - try and say we don't support them */
2033 if (strstr(fname,".+,;=[]."))
2035 unix_ERR_class = ERRDOS;
2036 /* OS/2 Workplace shell fix may be main code stream in a later release. */
2037 #if 1 /* OS2_WPS_FIX - Recent versions of OS/2 need this. */
2038 unix_ERR_code = ERRcannotopen;
2039 #else /* OS2_WPS_FIX */
2040 unix_ERR_code = ERROR_EAS_NOT_SUPPORTED;
2041 #endif /* OS2_WPS_FIX */
2046 if ((ofun & 0x3) == 0 && file_existed)
2054 if ((ofun & 0x3) == 2)
2057 /* note that we ignore the append flag as
2058 append does not mean the same thing under dos and unix */
2060 switch (share_mode&0xF)
2078 if (share_mode&(1<<14)) {
2083 if (flags != O_RDONLY && file_existed &&
2084 (!CAN_WRITE(cnum) || IS_DOS_READONLY(dos_mode(cnum,fname,&sbuf))))
2094 if (deny_mode > DENY_NONE && deny_mode!=DENY_FCB)
2096 DEBUG(2,("Invalid deny mode %d on file %s\n",deny_mode,fname));
2101 if (deny_mode == DENY_FCB) deny_mode = DENY_DOS;
2103 if (lp_share_modes(SNUM(cnum)))
2106 share_mode_entry *old_shares = 0;
2110 dev = (uint32)sbuf.st_dev;
2111 inode = (uint32)sbuf.st_ino;
2112 lock_share_entry(cnum, dev, inode, &token);
2113 share_locked = True;
2114 num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
2118 * Check if the share modes will give us access.
2121 if(share_locked && (num_share_modes != 0))
2128 broke_oplock = False;
2129 for(i = 0; i < num_share_modes; i++)
2131 share_mode_entry *share_entry = &old_shares[i];
2134 * By observation of NetBench, oplocks are broken *before* share
2135 * modes are checked. This allows a file to be closed by the client
2136 * if the share mode would deny access and the client has an oplock.
2137 * Check if someone has an oplock on this file. If so we must break
2138 * it before continuing.
2140 if(share_entry->op_type & (EXCLUSIVE_OPLOCK|BATCH_OPLOCK))
2143 DEBUG(5,("open_file_shared: breaking oplock (%x) on file %s, \
2144 dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
2146 /* Oplock break.... */
2147 unlock_share_entry(cnum, dev, inode, token);
2148 if(request_oplock_break(share_entry, dev, inode) == False)
2150 free((char *)old_shares);
2151 DEBUG(0,("open_file_shared: FAILED when breaking oplock (%x) on file %s, \
2152 dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
2154 unix_ERR_class = ERRDOS;
2155 unix_ERR_code = ERRbadshare;
2158 lock_share_entry(cnum, dev, inode, &token);
2159 broke_oplock = True;
2163 /* someone else has a share lock on it, check to see
2165 if(check_share_mode(share_entry, deny_mode, fname, fcbopen, &flags) == False)
2167 free((char *)old_shares);
2168 unlock_share_entry(cnum, dev, inode, token);
2170 unix_ERR_class = ERRDOS;
2171 unix_ERR_code = ERRbadshare;
2179 free((char *)old_shares);
2180 num_share_modes = get_share_modes(cnum, token, dev, inode, &old_shares);
2182 } while(broke_oplock);
2186 free((char *)old_shares);
2189 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o\n",
2190 flags,flags2,mode));
2192 open_file(fnum,cnum,fname,flags|(flags2&~(O_TRUNC)),mode,file_existed ? &sbuf : 0);
2193 if (!fs_p->open && flags==O_RDWR && errno!=ENOENT && fcbopen)
2196 open_file(fnum,cnum,fname,flags,mode,file_existed ? &sbuf : 0 );
2203 if((share_locked == False) && lp_share_modes(SNUM(cnum)))
2205 /* We created the file - thus we must now lock the share entry before creating it. */
2206 dev = fs_p->fd_ptr->dev;
2207 inode = fs_p->fd_ptr->inode;
2208 lock_share_entry(cnum, dev, inode, &token);
2209 share_locked = True;
2225 fs_p->share_mode = (deny_mode<<4) | open_mode;
2228 (*Access) = open_mode;
2232 if (file_existed && !(flags2 & O_TRUNC)) *action = FILE_WAS_OPENED;
2233 if (!file_existed) *action = FILE_WAS_CREATED;
2234 if (file_existed && (flags2 & O_TRUNC)) *action = FILE_WAS_OVERWRITTEN;
2236 /* We must create the share mode entry before truncate as
2237 truncate can fail due to locking and have to close the
2238 file (which expects the share_mode_entry to be there).
2240 if (lp_share_modes(SNUM(cnum)))
2243 /* JRA. Currently this only services Exlcusive and batch
2244 oplocks (no other opens on this file). This needs to
2245 be extended to level II oplocks (multiple reader
2248 if(oplock_request && (num_share_modes == 0) && lp_oplocks(SNUM(cnum)) &&
2249 !IS_VETO_OPLOCK_PATH(cnum,fname))
2251 fs_p->granted_oplock = True;
2252 fs_p->sent_oplock_break = False;
2253 global_oplocks_open++;
2256 DEBUG(5,("open_file_shared: granted oplock (%x) on file %s, \
2257 dev = %x, inode = %x\n", oplock_request, fname, dev, inode));
2265 set_share_mode(token, fnum, port, oplock_request);
2268 if ((flags2&O_TRUNC) && file_existed)
2269 truncate_unless_locked(fnum,cnum,token,&share_locked);
2272 if (share_locked && lp_share_modes(SNUM(cnum)))
2273 unlock_share_entry( cnum, dev, inode, token);
2276 /****************************************************************************
2277 seek a file. Try to avoid the seek if possible
2278 ****************************************************************************/
2279 int seek_file(int fnum,uint32 pos)
2282 if (Files[fnum].print_file && POSTSCRIPT(Files[fnum].cnum))
2285 Files[fnum].pos = (int)(lseek(Files[fnum].fd_ptr->fd,pos+offset,SEEK_SET)
2287 return(Files[fnum].pos);
2290 /****************************************************************************
2292 ****************************************************************************/
2293 int read_file(int fnum,char *data,uint32 pos,int n)
2297 #if USE_READ_PREDICTION
2298 if (!Files[fnum].can_write)
2300 ret = read_predict(Files[fnum].fd_ptr->fd,pos,data,NULL,n);
2309 if (Files[fnum].mmap_ptr)
2311 int num = (Files[fnum].mmap_size > pos) ? (Files[fnum].mmap_size - pos) : -1;
2315 memcpy(data,Files[fnum].mmap_ptr+pos,num);
2327 if (seek_file(fnum,pos) != pos)
2329 DEBUG(3,("Failed to seek to %d\n",pos));
2334 readret = read(Files[fnum].fd_ptr->fd,data,n);
2335 if (readret > 0) ret += readret;
2342 /****************************************************************************
2344 ****************************************************************************/
2345 int write_file(int fnum,char *data,int n)
2347 if (!Files[fnum].can_write) {
2352 if (!Files[fnum].modified) {
2354 Files[fnum].modified = True;
2355 if (fstat(Files[fnum].fd_ptr->fd,&st) == 0) {
2356 int dosmode = dos_mode(Files[fnum].cnum,Files[fnum].name,&st);
2357 if (MAP_ARCHIVE(Files[fnum].cnum) && !IS_DOS_ARCHIVE(dosmode)) {
2358 dos_chmod(Files[fnum].cnum,Files[fnum].name,dosmode | aARCH,&st);
2363 return(write_data(Files[fnum].fd_ptr->fd,data,n));
2367 /****************************************************************************
2368 load parameters specific to a connection/service
2369 ****************************************************************************/
2370 BOOL become_service(int cnum,BOOL do_chdir)
2372 extern char magic_char;
2373 static int last_cnum = -1;
2376 if (!OPEN_CNUM(cnum))
2382 Connections[cnum].lastused = smb_last_time;
2387 ChDir(Connections[cnum].connectpath) != 0 &&
2388 ChDir(Connections[cnum].origpath) != 0)
2390 DEBUG(0,("%s chdir (%s) failed cnum=%d\n",timestring(),
2391 Connections[cnum].connectpath,cnum));
2395 if (cnum == last_cnum)
2400 case_default = lp_defaultcase(snum);
2401 case_preserve = lp_preservecase(snum);
2402 short_case_preserve = lp_shortpreservecase(snum);
2403 case_mangle = lp_casemangle(snum);
2404 case_sensitive = lp_casesensitive(snum);
2405 magic_char = lp_magicchar(snum);
2406 use_mangled_map = (*lp_mangled_map(snum) ? True:False);
2411 /****************************************************************************
2412 find a service entry
2413 ****************************************************************************/
2414 int find_service(char *service)
2418 string_sub(service,"\\","/");
2420 iService = lp_servicenumber(service);
2422 /* now handle the special case of a home directory */
2425 char *phome_dir = get_home_dir(service);
2430 * Try mapping the servicename, it may
2431 * be a Windows to unix mapped user name.
2433 if(map_username(service))
2434 phome_dir = get_home_dir(service);
2437 DEBUG(3,("checking for home directory %s gave %s\n",service,
2438 phome_dir?phome_dir:"(NULL)"));
2443 if ((iHomeService = lp_servicenumber(HOMES_NAME)) >= 0)
2445 lp_add_home(service,iHomeService,phome_dir);
2446 iService = lp_servicenumber(service);
2451 /* If we still don't have a service, attempt to add it as a printer. */
2454 int iPrinterService;
2456 if ((iPrinterService = lp_servicenumber(PRINTERS_NAME)) >= 0)
2460 DEBUG(3,("checking whether %s is a valid printer name...\n", service));
2462 if ((pszTemp != NULL) && pcap_printername_ok(service, pszTemp))
2464 DEBUG(3,("%s is a valid printer name\n", service));
2465 DEBUG(3,("adding %s as a printer service\n", service));
2466 lp_add_printer(service,iPrinterService);
2467 iService = lp_servicenumber(service);
2469 DEBUG(0,("failed to add %s as a printer service!\n", service));
2472 DEBUG(3,("%s is not a valid printer name\n", service));
2476 /* just possibly it's a default service? */
2479 char *pdefservice = lp_defaultservice();
2480 if (pdefservice && *pdefservice && !strequal(pdefservice,service))
2483 * We need to do a local copy here as lp_defaultservice()
2484 * returns one of the rotating lp_string buffers that
2485 * could get overwritten by the recursive find_service() call
2486 * below. Fix from Josef Hinteregger <joehtg@joehtg.co.at>.
2489 pstrcpy(defservice, pdefservice);
2490 iService = find_service(defservice);
2493 string_sub(service,"_","/");
2494 iService = lp_add_service(service,iService);
2500 if (!VALID_SNUM(iService))
2502 DEBUG(0,("Invalid snum %d for %s\n",iService,service));
2507 DEBUG(3,("find_service() failed to find service %s\n", service));
2513 /****************************************************************************
2514 create an error packet from a cached error.
2515 ****************************************************************************/
2516 int cached_error_packet(char *inbuf,char *outbuf,int fnum,int line)
2518 write_bmpx_struct *wbmpx = Files[fnum].wbmpx_ptr;
2520 int32 eclass = wbmpx->wr_errclass;
2521 int32 err = wbmpx->wr_error;
2523 /* We can now delete the auxiliary struct */
2524 free((char *)wbmpx);
2525 Files[fnum].wbmpx_ptr = NULL;
2526 return error_packet(inbuf,outbuf,eclass,err,line);
2535 } unix_smb_errmap[] =
2537 {EPERM,ERRDOS,ERRnoaccess},
2538 {EACCES,ERRDOS,ERRnoaccess},
2539 {ENOENT,ERRDOS,ERRbadfile},
2540 {ENOTDIR,ERRDOS,ERRbadpath},
2541 {EIO,ERRHRD,ERRgeneral},
2542 {EBADF,ERRSRV,ERRsrverror},
2543 {EINVAL,ERRSRV,ERRsrverror},
2544 {EEXIST,ERRDOS,ERRfilexists},
2545 {ENFILE,ERRDOS,ERRnofids},
2546 {EMFILE,ERRDOS,ERRnofids},
2547 {ENOSPC,ERRHRD,ERRdiskfull},
2549 {EDQUOT,ERRHRD,ERRdiskfull},
2552 {ENOTEMPTY,ERRDOS,ERRnoaccess},
2555 {EXDEV,ERRDOS,ERRdiffdevice},
2557 {EROFS,ERRHRD,ERRnowrite},
2561 /****************************************************************************
2562 create an error packet from errno
2563 ****************************************************************************/
2564 int unix_error_packet(char *inbuf,char *outbuf,int def_class,uint32 def_code,int line)
2566 int eclass=def_class;
2570 if (unix_ERR_class != SMB_SUCCESS)
2572 eclass = unix_ERR_class;
2573 ecode = unix_ERR_code;
2574 unix_ERR_class = SMB_SUCCESS;
2579 while (unix_smb_errmap[i].smbclass != 0)
2581 if (unix_smb_errmap[i].unixerror == errno)
2583 eclass = unix_smb_errmap[i].smbclass;
2584 ecode = unix_smb_errmap[i].smbcode;
2591 return(error_packet(inbuf,outbuf,eclass,ecode,line));
2595 /****************************************************************************
2596 create an error packet. Normally called using the ERROR() macro
2597 ****************************************************************************/
2598 int error_packet(char *inbuf,char *outbuf,int error_class,uint32 error_code,int line)
2600 int outsize = set_message(outbuf,0,0,True);
2601 int cmd = CVAL(inbuf,smb_com);
2602 int flgs2 = SVAL(outbuf,smb_flg2);
2604 if ((flgs2 & FLAGS2_32_BIT_ERROR_CODES) == FLAGS2_32_BIT_ERROR_CODES)
2606 SIVAL(outbuf,smb_rcls,error_code);
2608 DEBUG(3,("%s 32 bit error packet at line %d cmd=%d (%s) eclass=%08x [%s]\n",
2609 timestring(), line, cmd, smb_fn_name(cmd), error_code, smb_errstr(outbuf)));
2613 CVAL(outbuf,smb_rcls) = error_class;
2614 SSVAL(outbuf,smb_err,error_code);
2615 DEBUG(3,("%s error packet at line %d cmd=%d (%s) eclass=%d ecode=%d\n",
2618 (int)CVAL(inbuf,smb_com),
2619 smb_fn_name(CVAL(inbuf,smb_com)),
2626 DEBUG(3,("error string = %s\n",strerror(errno)));
2632 #ifndef SIGCLD_IGNORE
2633 /****************************************************************************
2634 this prevents zombie child processes
2635 ****************************************************************************/
2636 static int sig_cld(void)
2638 static int depth = 0;
2641 DEBUG(0,("ERROR: Recursion in sig_cld? Perhaps you need `#define USE_WAITPID'?\n"));
2647 BlockSignals(True,SIGCLD);
2648 DEBUG(5,("got SIGCLD\n"));
2651 while (sys_waitpid((pid_t)-1,(int *)NULL, WNOHANG) > 0);
2655 /* Stevens, Adv. Unix Prog. says that on system V you must call
2656 wait before reinstalling the signal handler, because the kernel
2657 calls the handler from within the signal-call when there is a
2658 child that has exited. This would lead to an infinite recursion
2659 if done vice versa. */
2661 #ifndef DONT_REINSTALL_SIG
2662 #ifdef SIGCLD_IGNORE
2663 signal(SIGCLD, SIG_IGN);
2665 signal(SIGCLD, SIGNAL_CAST sig_cld);
2670 while (wait3(WAIT3_CAST1 NULL, WNOHANG, WAIT3_CAST2 NULL) > 0);
2673 BlockSignals(False,SIGCLD);
2678 /****************************************************************************
2679 this is called when the client exits abruptly
2680 **************************************************************************/
2681 static int sig_pipe(void)
2683 struct cli_state *cli;
2684 BlockSignals(True,SIGPIPE);
2686 if ((cli = server_client()) && cli->initialised) {
2687 DEBUG(3,("lost connection to password server\n"));
2689 #ifndef DONT_REINSTALL_SIG
2690 signal(SIGPIPE, SIGNAL_CAST sig_pipe);
2692 BlockSignals(False,SIGPIPE);
2696 exit_server("Got sigpipe\n");
2700 /****************************************************************************
2701 open the socket communication
2702 ****************************************************************************/
2703 static BOOL open_sockets(BOOL is_daemon,int port)
2709 int num_interfaces = iface_count();
2710 int fd_listenset[FD_SETSIZE];
2716 #ifdef SIGCLD_IGNORE
2717 signal(SIGCLD, SIG_IGN);
2719 signal(SIGCLD, SIGNAL_CAST sig_cld);
2725 FD_ZERO(&listen_set);
2727 if(lp_interfaces() && lp_bind_interfaces_only())
2729 /* We have been given an interfaces line, and been
2730 told to only bind to those interfaces. Create a
2731 socket per interface and bind to only these.
2734 if(num_interfaces > FD_SETSIZE)
2736 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
2737 max can be %d\n", num_interfaces, FD_SETSIZE));
2741 /* Now open a listen socket for each of the interfaces. */
2742 for(i = 0; i < num_interfaces; i++)
2744 struct in_addr *ifip = iface_n_ip(i);
2748 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
2751 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr);
2754 /* ready to listen */
2755 if (listen(s, 5) == -1)
2757 DEBUG(0,("listen: %s\n",strerror(errno)));
2761 FD_SET(s,&listen_set);
2766 /* Just bind to 0.0.0.0 - accept connections from anywhere. */
2769 /* open an incoming socket */
2770 s = open_socket_in(SOCK_STREAM, port, 0,interpret_addr(lp_socket_address()));
2774 /* ready to listen */
2775 if (listen(s, 5) == -1)
2777 DEBUG(0,("open_sockets: listen: %s\n",strerror(errno)));
2782 fd_listenset[0] = s;
2783 FD_SET(s,&listen_set);
2786 /* now accept incoming connections - forking a new process
2787 for each incoming connection */
2788 DEBUG(2,("waiting for a connection\n"));
2794 memcpy((char *)&lfds, (char *)&listen_set, sizeof(listen_set));
2796 num = sys_select(&lfds,NULL);
2798 if (num == -1 && errno == EINTR)
2801 /* Find the sockets that are read-ready - accept on these. */
2802 for( ; num > 0; num--)
2804 struct sockaddr addr;
2805 int in_addrlen = sizeof(addr);
2808 for(i = 0; i < num_interfaces; i++)
2810 if(FD_ISSET(fd_listenset[i],&lfds))
2812 s = fd_listenset[i];
2813 /* Clear this so we don't look at it again. */
2814 FD_CLR(fd_listenset[i],&lfds);
2819 Client = accept(s,&addr,&in_addrlen);
2821 if (Client == -1 && errno == EINTR)
2826 DEBUG(0,("open_sockets: accept: %s\n",strerror(errno)));
2830 #ifdef NO_FORK_DEBUG
2831 #ifndef NO_SIGNAL_TEST
2832 signal(SIGPIPE, SIGNAL_CAST sig_pipe);
2833 signal(SIGCLD, SIGNAL_CAST SIG_DFL);
2834 #endif /* NO_SIGNAL_TEST */
2836 #else /* NO_FORK_DEBUG */
2837 if (Client != -1 && fork()==0)
2839 /* Child code ... */
2841 #ifndef NO_SIGNAL_TEST
2842 signal(SIGPIPE, SIGNAL_CAST sig_pipe);
2843 signal(SIGCLD, SIGNAL_CAST SIG_DFL);
2844 #endif /* NO_SIGNAL_TEST */
2845 /* close the listening socket(s) */
2846 for(i = 0; i < num_interfaces; i++)
2847 close(fd_listenset[i]);
2849 /* close our standard file descriptors */
2853 set_socket_options(Client,"SO_KEEPALIVE");
2854 set_socket_options(Client,user_socket_options);
2856 /* Reset global variables in util.c so that
2857 client substitutions will be done correctly
2860 reset_globals_after_fork();
2863 close(Client); /* The parent doesn't need this socket */
2864 #endif /* NO_FORK_DEBUG */
2867 } /* end if is_daemon */
2870 /* Started from inetd. fd 0 is the socket. */
2871 /* We will abort gracefully when the client or remote system
2873 #ifndef NO_SIGNAL_TEST
2874 signal(SIGPIPE, SIGNAL_CAST sig_pipe);
2878 /* close our standard file descriptors */
2881 set_socket_options(Client,"SO_KEEPALIVE");
2882 set_socket_options(Client,user_socket_options);
2888 /****************************************************************************
2889 process an smb from the client - split out from the process() code so
2890 it can be used by the oplock break code.
2891 ****************************************************************************/
2893 static void process_smb(char *inbuf, char *outbuf)
2897 extern BOOL sslEnabled; /* don't use function for performance reasons */
2898 static int sslConnected = 0;
2899 #endif /* USE_SSL */
2900 static int trans_num;
2901 int msg_type = CVAL(inbuf,0);
2902 int32 len = smb_len(inbuf);
2903 int nread = len + 4;
2905 if (trans_num == 0) {
2906 /* on the first packet, check the global hosts allow/ hosts
2907 deny parameters before doing any parsing of the packet
2908 passed to us by the client. This prevents attacks on our
2909 parsing code from hosts not in the hosts allow list */
2910 if (!check_access(-1)) {
2911 /* send a negative session response "not listining on calling
2913 static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
2914 DEBUG(1,("%s Connection denied from %s\n",
2915 timestring(),client_addr(Client)));
2916 send_smb(Client,(char *)buf);
2917 exit_server("connection denied");
2921 DEBUG(6,("got message type 0x%x of len 0x%x\n",msg_type,len));
2922 DEBUG(3,("%s Transaction %d of length %d\n",timestring(),trans_num,nread));
2925 if(sslEnabled && !sslConnected){
2926 sslConnected = sslutil_negotiate_ssl(Client, msg_type);
2927 if(sslConnected < 0){ /* an error occured */
2928 exit_server("SSL negotiation failed");
2929 }else if(sslConnected){
2934 #endif /* USE_SSL */
2937 if(trans_num == 1 && VT_Check(inbuf))
2946 else if(msg_type == 0x85)
2947 return; /* Keepalive packet. */
2949 nread = construct_reply(inbuf,outbuf,nread,max_send);
2953 if (CVAL(outbuf,0) == 0)
2956 if (nread != smb_len(outbuf) + 4)
2958 DEBUG(0,("ERROR: Invalid message response size! %d %d\n",
2959 nread, smb_len(outbuf)));
2962 send_smb(Client,outbuf);
2967 /****************************************************************************
2968 open the oplock IPC socket communication
2969 ****************************************************************************/
2970 static BOOL open_oplock_ipc(void)
2972 struct sockaddr_in sock_name;
2973 int len = sizeof(sock_name);
2975 DEBUG(3,("open_oplock_ipc: opening loopback UDP socket.\n"));
2977 /* Open a lookback UDP socket on a random port. */
2978 oplock_sock = open_socket_in(SOCK_DGRAM, 0, 0, htonl(INADDR_LOOPBACK));
2979 if (oplock_sock == -1)
2981 DEBUG(0,("open_oplock_ipc: Failed to get local UDP socket for \
2982 address %x. Error was %s\n", htonl(INADDR_LOOPBACK), strerror(errno)));
2987 /* Find out the transient UDP port we have been allocated. */
2988 if(getsockname(oplock_sock, (struct sockaddr *)&sock_name, &len)<0)
2990 DEBUG(0,("open_oplock_ipc: Failed to get local UDP port. Error was %s\n",
2997 oplock_port = ntohs(sock_name.sin_port);
2999 DEBUG(3,("open_oplock ipc: pid = %d, oplock_port = %u\n",
3000 getpid(), oplock_port));
3005 /****************************************************************************
3006 process an oplock break message.
3007 ****************************************************************************/
3008 static BOOL process_local_message(int sock, char *buffer, int buf_size)
3014 msg_len = IVAL(buffer,UDP_CMD_LEN_OFFSET);
3015 from_port = SVAL(buffer,UDP_CMD_PORT_OFFSET);
3017 msg_start = &buffer[UDP_CMD_HEADER_LEN];
3019 DEBUG(5,("process_local_message: Got a message of length %d from port (%d)\n",
3020 msg_len, from_port));
3022 /* Switch on message command - currently OPLOCK_BREAK_CMD is the
3023 only valid request. */
3025 switch(SVAL(msg_start,UDP_MESSAGE_CMD_OFFSET))
3027 case OPLOCK_BREAK_CMD:
3028 /* Ensure that the msg length is correct. */
3029 if(msg_len != OPLOCK_BREAK_MSG_LEN)
3031 DEBUG(0,("process_local_message: incorrect length for OPLOCK_BREAK_CMD (was %d, \
3032 should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
3036 uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
3037 uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
3038 uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
3039 struct timeval tval;
3040 struct sockaddr_in toaddr;
3042 tval.tv_sec = IVAL(msg_start, OPLOCK_BREAK_SEC_OFFSET);
3043 tval.tv_usec = IVAL(msg_start, OPLOCK_BREAK_USEC_OFFSET);
3045 DEBUG(5,("process_local_message: oplock break request from \
3046 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
3049 * If we have no record of any currently open oplocks,
3050 * it's not an error, as a close command may have
3051 * just been issued on the file that was oplocked.
3052 * Just return success in this case.
3055 if(global_oplocks_open != 0)
3057 if(oplock_break(dev, inode, &tval) == False)
3059 DEBUG(0,("process_local_message: oplock break failed - \
3060 not returning udp message.\n"));
3066 DEBUG(3,("process_local_message: oplock break requested with no outstanding \
3067 oplocks. Returning success.\n"));
3070 /* Send the message back after OR'ing in the 'REPLY' bit. */
3071 SSVAL(msg_start,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD | CMD_REPLY);
3073 bzero((char *)&toaddr,sizeof(toaddr));
3074 toaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3075 toaddr.sin_port = htons(from_port);
3076 toaddr.sin_family = AF_INET;
3078 if(sendto( sock, msg_start, OPLOCK_BREAK_MSG_LEN, 0,
3079 (struct sockaddr *)&toaddr, sizeof(toaddr)) < 0)
3081 DEBUG(0,("process_local_message: sendto process %d failed. Errno was %s\n",
3082 remotepid, strerror(errno)));
3086 DEBUG(5,("process_local_message: oplock break reply sent to \
3087 pid %d, port %d, for file dev = %x, inode = %x\n", remotepid,
3088 from_port, dev, inode));
3093 * Keep this as a debug case - eventually we can remove it.
3096 DEBUG(0,("process_local_message: Received unsolicited break \
3097 reply - dumping info.\n"));
3099 if(msg_len != OPLOCK_BREAK_MSG_LEN)
3101 DEBUG(0,("process_local_message: ubr: incorrect length for reply \
3102 (was %d, should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
3107 uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
3108 uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
3109 uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
3111 DEBUG(0,("process_local_message: unsolicited oplock break reply from \
3112 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
3118 DEBUG(0,("process_local_message: unknown UDP message command code (%x) - ignoring.\n",
3119 (unsigned int)SVAL(msg_start,0)));
3125 /****************************************************************************
3126 Process an oplock break directly.
3127 ****************************************************************************/
3128 BOOL oplock_break(uint32 dev, uint32 inode, struct timeval *tval)
3130 extern struct current_user current_user;
3133 char *outbuf = NULL;
3134 files_struct *fsp = NULL;
3137 BOOL shutdown_server = False;
3142 DEBUG(3,("%s oplock_break: called for dev = %x, inode = %x. Current \
3143 global_oplocks_open = %d\n", timestring(), dev, inode, global_oplocks_open));
3145 /* We need to search the file open table for the
3146 entry containing this dev and inode, and ensure
3147 we have an oplock on it. */
3148 for( fnum = 0; fnum < MAX_FNUMS; fnum++)
3152 if((Files[fnum].fd_ptr->dev == dev) && (Files[fnum].fd_ptr->inode == inode) &&
3153 (Files[fnum].open_time.tv_sec == tval->tv_sec) &&
3154 (Files[fnum].open_time.tv_usec == tval->tv_usec)) {
3163 /* The file could have been closed in the meantime - return success. */
3164 DEBUG(0,("%s oplock_break: cannot find open file with dev = %x, inode = %x (fnum = %d) \
3165 allowing break to succeed.\n", timestring(), dev, inode, fnum));
3169 /* Ensure we have an oplock on the file */
3171 /* There is a potential race condition in that an oplock could
3172 have been broken due to another udp request, and yet there are
3173 still oplock break messages being sent in the udp message
3174 queue for this file. So return true if we don't have an oplock,
3175 as we may have just freed it.
3178 if(!fsp->granted_oplock)
3180 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));
3184 /* mark the oplock break as sent - we don't want to send twice! */
3185 if (fsp->sent_oplock_break)
3187 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));
3189 /* We have to fail the open here as we cannot send another oplock break on this
3190 file whilst we are awaiting a response from the client - neither can we
3191 allow another open to succeed while we are waiting for the client. */
3195 /* Now comes the horrid part. We must send an oplock break to the client,
3196 and then process incoming messages until we get a close or oplock release.
3197 At this point we know we need a new inbuf/outbuf buffer pair.
3198 We cannot use these staticaly as we may recurse into here due to
3199 messages crossing on the wire.
3202 if((inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
3204 DEBUG(0,("oplock_break: malloc fail for input buffer.\n"));
3208 if((outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
3210 DEBUG(0,("oplock_break: malloc fail for output buffer.\n"));
3216 /* Prepare the SMBlockingX message. */
3217 bzero(outbuf,smb_size);
3218 set_message(outbuf,8,0,True);
3220 SCVAL(outbuf,smb_com,SMBlockingX);
3221 SSVAL(outbuf,smb_tid,fsp->cnum);
3222 SSVAL(outbuf,smb_pid,0xFFFF);
3223 SSVAL(outbuf,smb_uid,0);
3224 SSVAL(outbuf,smb_mid,0xFFFF);
3225 SCVAL(outbuf,smb_vwv0,0xFF);
3226 SSVAL(outbuf,smb_vwv2,fnum);
3227 SCVAL(outbuf,smb_vwv3,LOCKING_ANDX_OPLOCK_RELEASE);
3228 /* Change this when we have level II oplocks. */
3229 SCVAL(outbuf,smb_vwv3+1,OPLOCKLEVEL_NONE);
3231 send_smb(Client, outbuf);
3233 /* Remember we just sent an oplock break on this file. */
3234 fsp->sent_oplock_break = True;
3236 /* We need this in case a readraw crosses on the wire. */
3237 global_oplock_break = True;
3239 /* Process incoming messages. */
3241 /* JRA - If we don't get a break from the client in OPLOCK_BREAK_TIMEOUT
3242 seconds we should just die.... */
3244 start_time = time(NULL);
3247 * Save the information we need to re-become the
3248 * user, then unbecome the user whilst we're doing this.
3250 saved_cnum = fsp->cnum;
3251 saved_vuid = current_user.vuid;
3255 while(OPEN_FNUM(fnum) && fsp->granted_oplock)
3257 if(receive_smb(Client,inbuf,OPLOCK_BREAK_TIMEOUT * 1000) == False)
3260 * Die if we got an error.
3263 if (smb_read_error == READ_EOF)
3264 DEBUG(0,("%s oplock_break: end of file from client\n", timestring()));
3266 if (smb_read_error == READ_ERROR)
3267 DEBUG(0,("%s oplock_break: receive_smb error (%s)\n",
3268 timestring(), strerror(errno)));
3270 if (smb_read_error == READ_TIMEOUT)
3271 DEBUG(0,("%s oplock_break: receive_smb timed out after %d seconds.\n",
3272 timestring(), OPLOCK_BREAK_TIMEOUT));
3274 DEBUG(0,("%s oplock_break failed for file %s (fnum = %d, dev = %x, \
3275 inode = %x).\n", timestring(), fsp->name, fnum, dev, inode));
3276 shutdown_server = True;
3281 * There are certain SMB requests that we shouldn't allow
3282 * to recurse. opens, renames and deletes are the obvious
3283 * ones. This is handled in the switch_message() function.
3284 * If global_oplock_break is set they will push the packet onto
3285 * the pending smb queue and return -1 (no reply).
3289 process_smb(inbuf, outbuf);
3292 * Die if we go over the time limit.
3295 if((time(NULL) - start_time) > OPLOCK_BREAK_TIMEOUT)
3297 DEBUG(0,("%s oplock_break: no break received from client within \
3298 %d seconds.\n", timestring(), OPLOCK_BREAK_TIMEOUT));
3299 DEBUG(0,("%s oplock_break failed for file %s (fnum = %d, dev = %x, \
3300 inode = %x).\n", timestring(), fsp->name, fnum, dev, inode));
3301 shutdown_server = True;
3307 * Go back to being the user who requested the oplock
3310 if(!become_user(&Connections[saved_cnum], saved_cnum, saved_vuid))
3312 DEBUG(0,("%s oplock_break: unable to re-become user ! Shutting down server\n",
3316 exit_server("unable to re-become user");
3318 /* Including the directory. */
3321 /* Free the buffers we've been using to recurse. */
3325 /* We need this in case a readraw crossed on the wire. */
3326 if(global_oplock_break)
3327 global_oplock_break = False;
3330 * If the client did not respond we must die.
3335 DEBUG(0,("%s oplock_break: client failure in break - shutting down this smbd.\n",
3339 exit_server("oplock break failure");
3344 /* The lockingX reply will have removed the oplock flag
3345 from the sharemode. */
3347 fsp->granted_oplock = False;
3348 fsp->sent_oplock_break = False;
3349 global_oplocks_open--;
3352 /* Santity check - remove this later. JRA */
3353 if(global_oplocks_open < 0)
3355 DEBUG(0,("oplock_break: global_oplocks_open < 0 (%d). PANIC ERROR\n",
3356 global_oplocks_open));
3357 exit_server("oplock_break: global_oplocks_open < 0");
3360 DEBUG(3,("%s oplock_break: returning success for fnum = %d, dev = %x, inode = %x. Current \
3361 global_oplocks_open = %d\n", timestring(), fnum, dev, inode, global_oplocks_open));
3366 /****************************************************************************
3367 Send an oplock break message to another smbd process. If the oplock is held
3368 by the local smbd then call the oplock break function directly.
3369 ****************************************************************************/
3371 BOOL request_oplock_break(share_mode_entry *share_entry,
3372 uint32 dev, uint32 inode)
3374 char op_break_msg[OPLOCK_BREAK_MSG_LEN];
3375 struct sockaddr_in addr_out;
3380 if(pid == share_entry->pid)
3382 /* We are breaking our own oplock, make sure it's us. */
3383 if(share_entry->op_port != oplock_port)
3385 DEBUG(0,("request_oplock_break: corrupt share mode entry - pid = %d, port = %d \
3386 should be %d\n", pid, share_entry->op_port, oplock_port));
3390 DEBUG(5,("request_oplock_break: breaking our own oplock\n"));
3392 /* Call oplock break direct. */
3393 return oplock_break(dev, inode, &share_entry->time);
3396 /* We need to send a OPLOCK_BREAK_CMD message to the
3397 port in the share mode entry. */
3399 SSVAL(op_break_msg,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD);
3400 SIVAL(op_break_msg,OPLOCK_BREAK_PID_OFFSET,pid);
3401 SIVAL(op_break_msg,OPLOCK_BREAK_DEV_OFFSET,dev);
3402 SIVAL(op_break_msg,OPLOCK_BREAK_INODE_OFFSET,inode);
3403 SIVAL(op_break_msg,OPLOCK_BREAK_SEC_OFFSET,(uint32)share_entry->time.tv_sec);
3404 SIVAL(op_break_msg,OPLOCK_BREAK_USEC_OFFSET,(uint32)share_entry->time.tv_usec);
3406 /* set the address and port */
3407 bzero((char *)&addr_out,sizeof(addr_out));
3408 addr_out.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3409 addr_out.sin_port = htons( share_entry->op_port );
3410 addr_out.sin_family = AF_INET;
3412 DEBUG(3,("%s request_oplock_break: sending a oplock break message to pid %d on port %d \
3413 for dev = %x, inode = %x\n", timestring(), share_entry->pid, share_entry->op_port, dev, inode));
3415 if(sendto(oplock_sock,op_break_msg,OPLOCK_BREAK_MSG_LEN,0,
3416 (struct sockaddr *)&addr_out,sizeof(addr_out)) < 0)
3418 DEBUG(0,("%s request_oplock_break: failed when sending a oplock break message \
3419 to pid %d on port %d for dev = %x, inode = %x. Error was %s\n",
3420 timestring(), share_entry->pid, share_entry->op_port, dev, inode,
3426 * Now we must await the oplock broken message coming back
3427 * from the target smbd process. Timeout if it fails to
3428 * return in (OPLOCK_BREAK_TIMEOUT + OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR) seconds.
3429 * While we get messages that aren't ours, loop.
3432 start_time = time(NULL);
3433 time_left = OPLOCK_BREAK_TIMEOUT+OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR;
3435 while(time_left >= 0)
3437 char op_break_reply[UDP_CMD_HEADER_LEN+OPLOCK_BREAK_MSG_LEN];
3438 int32 reply_msg_len;
3439 uint16 reply_from_port;
3440 char *reply_msg_start;
3442 if(receive_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply),
3443 time_left ? time_left * 1000 : 1) == False)
3445 if(smb_read_error == READ_TIMEOUT)
3447 DEBUG(0,("%s request_oplock_break: no response received to oplock break request to \
3448 pid %d on port %d for dev = %x, inode = %x\n", timestring(), share_entry->pid,
3449 share_entry->op_port, dev, inode));
3451 * This is a hack to make handling of failing clients more robust.
3452 * If a oplock break response message is not received in the timeout
3453 * period we may assume that the smbd servicing that client holding
3454 * the oplock has died and the client changes were lost anyway, so
3455 * we should continue to try and open the file.
3460 DEBUG(0,("%s request_oplock_break: error in response received to oplock break request to \
3461 pid %d on port %d for dev = %x, inode = %x. Error was (%s).\n", timestring, share_entry->pid,
3462 share_entry->op_port, dev, inode, strerror(errno)));
3466 reply_msg_len = IVAL(op_break_reply,UDP_CMD_LEN_OFFSET);
3467 reply_from_port = SVAL(op_break_reply,UDP_CMD_PORT_OFFSET);
3469 reply_msg_start = &op_break_reply[UDP_CMD_HEADER_LEN];
3471 if(reply_msg_len != OPLOCK_BREAK_MSG_LEN)
3474 DEBUG(0,("%s request_oplock_break: invalid message length received. Ignoring\n",
3480 * Test to see if this is the reply we are awaiting.
3483 if((SVAL(reply_msg_start,UDP_MESSAGE_CMD_OFFSET) & CMD_REPLY) &&
3484 (reply_from_port == share_entry->op_port) &&
3485 (memcmp(&reply_msg_start[OPLOCK_BREAK_PID_OFFSET],
3486 &op_break_msg[OPLOCK_BREAK_PID_OFFSET],
3487 OPLOCK_BREAK_MSG_LEN - OPLOCK_BREAK_PID_OFFSET) == 0))
3490 * This is the reply we've been waiting for.
3497 * This is another message - probably a break request.
3498 * Process it to prevent potential deadlock.
3499 * Note that the code in switch_message() prevents
3500 * us from recursing into here as any SMB requests
3501 * we might process that would cause another oplock
3502 * break request to be made will be queued.
3506 process_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply));
3509 time_left -= (time(NULL) - start_time);
3512 DEBUG(3,("%s request_oplock_break: broke oplock.\n", timestring()));
3517 /****************************************************************************
3518 Get the next SMB packet, doing the local message processing automatically.
3519 ****************************************************************************/
3521 BOOL receive_next_smb(int smbfd, int oplockfd, char *inbuf, int bufsize, int timeout)
3523 BOOL got_smb = False;
3528 ret = receive_message_or_smb(smbfd,oplockfd,inbuf,bufsize,
3533 /* Deal with oplock break requests from other smbd's. */
3534 process_local_message(oplock_sock, inbuf, bufsize);
3538 if(ret && (CVAL(inbuf,0) == 0x85))
3540 /* Keepalive packet. */
3545 while(ret && !got_smb);
3550 /****************************************************************************
3551 check if a snum is in use
3552 ****************************************************************************/
3553 BOOL snum_used(int snum)
3556 for (i=0;i<MAX_CONNECTIONS;i++)
3557 if (OPEN_CNUM(i) && (SNUM(i) == snum))
3562 /****************************************************************************
3563 reload the services file
3564 **************************************************************************/
3565 BOOL reload_services(BOOL test)
3572 pstrcpy(fname,lp_configfile());
3573 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf))
3575 pstrcpy(servicesf,fname);
3582 if (test && !lp_file_list_changed())
3585 lp_killunused(snum_used);
3587 ret = lp_load(servicesf,False,False,True);
3589 /* perhaps the config filename is now set */
3591 reload_services(True);
3600 set_socket_options(Client,"SO_KEEPALIVE");
3601 set_socket_options(Client,user_socket_options);
3605 reset_mangled_cache();
3607 /* this forces service parameters to be flushed */
3608 become_service(-1,True);
3615 /****************************************************************************
3616 this prevents zombie child processes
3617 ****************************************************************************/
3618 static BOOL reload_after_sighup = False;
3620 static int sig_hup(void)
3622 BlockSignals(True,SIGHUP);
3623 DEBUG(0,("Got SIGHUP\n"));
3626 * Fix from <branko.cibej@hermes.si> here.
3627 * We used to reload in the signal handler - this
3631 reload_after_sighup = True;
3632 #ifndef DONT_REINSTALL_SIG
3633 signal(SIGHUP,SIGNAL_CAST sig_hup);
3635 BlockSignals(False,SIGHUP);
3640 /****************************************************************************
3641 make a connection to a service
3642 ****************************************************************************/
3643 int make_connection(char *service,char *user,char *password, int pwlen, char *dev,uint16 vuid)
3647 struct passwd *pass = NULL;
3648 connection_struct *pcon;
3654 snum = find_service(service);
3658 if (strequal(service,"IPC$"))
3660 DEBUG(3,("%s refusing IPC connection\n",timestring()));
3664 DEBUG(0,("%s %s (%s) couldn't find service %s\n",timestring(),remote_machine,client_addr(Client),service));
3668 if (strequal(service,HOMES_NAME))
3670 if (*user && Get_Pwnam(user,True))
3671 return(make_connection(user,user,password,pwlen,dev,vuid));
3673 if(lp_security() != SEC_SHARE)
3675 if (validated_username(vuid))
3677 pstrcpy(user,validated_username(vuid));
3678 return(make_connection(user,user,password,pwlen,dev,vuid));
3684 * Security = share. Try with sesssetup_user as the username.
3688 pstrcpy(user,sesssetup_user);
3689 return(make_connection(user,user,password,pwlen,dev,vuid));
3694 if (!lp_snum_ok(snum) || !check_access(snum)) {
3698 /* you can only connect to the IPC$ service as an ipc device */
3699 if (strequal(service,"IPC$"))
3702 if (*dev == '?' || !*dev)
3704 if (lp_print_ok(snum))
3705 pstrcpy(dev,"LPT1:");
3710 /* if the request is as a printer and you can't print then refuse */
3712 if (!lp_print_ok(snum) && (strncmp(dev,"LPT",3) == 0)) {
3713 DEBUG(1,("Attempt to connect to non-printer as a printer\n"));
3717 /* lowercase the user name */
3720 /* add it as a possible user name */
3721 add_session_user(service);
3723 /* shall we let them in? */
3724 if (!authorise_login(snum,user,password,pwlen,&guest,&force,vuid))
3726 DEBUG(2,("%s invalid username/password for %s\n",timestring(),service));
3730 cnum = find_free_connection(str_checksum(service) + str_checksum(user));
3733 DEBUG(0,("%s couldn't find free connection\n",timestring()));
3737 pcon = &Connections[cnum];
3738 bzero((char *)pcon,sizeof(*pcon));
3740 /* find out some info about the user */
3741 pass = Get_Pwnam(user,True);
3745 DEBUG(0,("%s couldn't find account %s\n",timestring(),user));
3749 pcon->read_only = lp_readonly(snum);
3753 StrnCpy(list,lp_readlist(snum),sizeof(pstring)-1);
3754 string_sub(list,"%S",service);
3756 if (user_in_list(user,list))
3757 pcon->read_only = True;
3759 StrnCpy(list,lp_writelist(snum),sizeof(pstring)-1);
3760 string_sub(list,"%S",service);
3762 if (user_in_list(user,list))
3763 pcon->read_only = False;
3766 /* admin user check */
3768 /* JRA - original code denied admin user if the share was
3769 marked read_only. Changed as I don't think this is needed,
3770 but old code left in case there is a problem here.
3772 if (user_in_list(user,lp_admin_users(snum))
3774 && !pcon->read_only)
3779 pcon->admin_user = True;
3780 DEBUG(0,("%s logged in as admin user (root privileges)\n",user));
3783 pcon->admin_user = False;
3785 pcon->force_user = force;
3787 pcon->uid = pass->pw_uid;
3788 pcon->gid = pass->pw_gid;
3789 pcon->num_files_open = 0;
3790 pcon->lastused = time(NULL);
3791 pcon->service = snum;
3793 pcon->printer = (strncmp(dev,"LPT",3) == 0);
3794 pcon->ipc = (strncmp(dev,"IPC",3) == 0);
3795 pcon->dirptr = NULL;
3796 pcon->veto_list = NULL;
3797 pcon->hide_list = NULL;
3798 pcon->veto_oplock_list = NULL;
3799 string_set(&pcon->dirpath,"");
3800 string_set(&pcon->user,user);
3803 if (*lp_force_group(snum))
3808 StrnCpy(gname,lp_force_group(snum),sizeof(pstring)-1);
3809 /* default service may be a group name */
3810 string_sub(gname,"%S",service);
3811 gptr = (struct group *)getgrnam(gname);
3815 pcon->gid = gptr->gr_gid;
3816 DEBUG(3,("Forced group %s\n",gname));
3819 DEBUG(1,("Couldn't find group %s\n",gname));
3823 if (*lp_force_user(snum))
3825 struct passwd *pass2;
3827 fstrcpy(fuser,lp_force_user(snum));
3828 pass2 = (struct passwd *)Get_Pwnam(fuser,True);
3831 pcon->uid = pass2->pw_uid;
3832 string_set(&pcon->user,fuser);
3833 fstrcpy(user,fuser);
3834 pcon->force_user = True;
3835 DEBUG(3,("Forced user %s\n",fuser));
3838 DEBUG(1,("Couldn't find user %s\n",fuser));
3843 pstrcpy(s,lp_pathname(snum));
3844 standard_sub(cnum,s);
3845 string_set(&pcon->connectpath,s);
3846 DEBUG(3,("Connect path is %s\n",s));
3849 /* groups stuff added by ih */
3851 pcon->igroups = NULL;
3852 pcon->groups = NULL;
3857 /* Find all the groups this uid is in and store them. Used by become_user() */
3858 setup_groups(pcon->user,pcon->uid,pcon->gid,
3859 &pcon->ngroups,&pcon->igroups,&pcon->groups,&pcon->attrs);
3861 /* check number of connections */
3862 if (!claim_connection(cnum,
3863 lp_servicename(SNUM(cnum)),
3864 lp_max_connections(SNUM(cnum)),False))
3866 DEBUG(1,("too many connections - rejected\n"));
3870 if (lp_status(SNUM(cnum)))
3871 claim_connection(cnum,"STATUS.",MAXSTATUS,False);
3876 /* execute any "root preexec = " line */
3877 if (*lp_rootpreexec(SNUM(cnum)))
3880 pstrcpy(cmd,lp_rootpreexec(SNUM(cnum)));
3881 standard_sub(cnum,cmd);
3882 DEBUG(5,("cmd=%s\n",cmd));
3883 smbrun(cmd,NULL,False);
3886 if (!become_user(&Connections[cnum], cnum,pcon->vuid))
3888 DEBUG(0,("Can't become connected user!\n"));
3890 if (!IS_IPC(cnum)) {
3891 yield_connection(cnum,
3892 lp_servicename(SNUM(cnum)),
3893 lp_max_connections(SNUM(cnum)));
3894 if (lp_status(SNUM(cnum))) yield_connection(cnum,"STATUS.",MAXSTATUS);
3899 if (ChDir(pcon->connectpath) != 0)
3901 DEBUG(0,("Can't change directory to %s (%s)\n",
3902 pcon->connectpath,strerror(errno)));
3905 if (!IS_IPC(cnum)) {
3906 yield_connection(cnum,
3907 lp_servicename(SNUM(cnum)),
3908 lp_max_connections(SNUM(cnum)));
3909 if (lp_status(SNUM(cnum))) yield_connection(cnum,"STATUS.",MAXSTATUS);
3914 string_set(&pcon->origpath,pcon->connectpath);
3916 #if SOFTLINK_OPTIMISATION
3917 /* resolve any soft links early */
3920 pstrcpy(s,pcon->connectpath);
3922 string_set(&pcon->connectpath,s);
3923 ChDir(pcon->connectpath);
3927 num_connections_open++;
3928 add_session_user(user);
3930 /* execute any "preexec = " line */
3931 if (*lp_preexec(SNUM(cnum)))
3934 pstrcpy(cmd,lp_preexec(SNUM(cnum)));
3935 standard_sub(cnum,cmd);
3936 smbrun(cmd,NULL,False);
3939 /* we've finished with the sensitive stuff */
3942 /* Add veto/hide lists */
3943 if (!IS_IPC(cnum) && !IS_PRINT(cnum))
3945 set_namearray( &pcon->veto_list, lp_veto_files(SNUM(cnum)));
3946 set_namearray( &pcon->hide_list, lp_hide_files(SNUM(cnum)));
3947 set_namearray( &pcon->veto_oplock_list, lp_veto_oplocks(SNUM(cnum)));
3952 DEBUG(IS_IPC(cnum)?3:1,("%s %s (%s) connect to service %s as user %s (uid=%d,gid=%d) (pid %d)\n",
3955 client_addr(Client),
3956 lp_servicename(SNUM(cnum)),user,
3965 /****************************************************************************
3966 Attempt to break an oplock on a file (if oplocked).
3967 Returns True if the file was closed as a result of
3968 the oplock break, False otherwise.
3969 Used as a last ditch attempt to free a space in the
3970 file table when we have run out.
3971 ****************************************************************************/
3973 static BOOL attempt_close_oplocked_file(files_struct *fp)
3976 DEBUG(5,("attempt_close_oplocked_file: checking file %s.\n", fp->name));
3978 if (fp->open && fp->granted_oplock && !fp->sent_oplock_break) {
3980 /* Try and break the oplock. */
3981 file_fd_struct *fsp = fp->fd_ptr;
3982 if(oplock_break( fsp->dev, fsp->inode, &fp->open_time)) {
3983 if(!fp->open) /* Did the oplock break close the file ? */
3991 /****************************************************************************
3992 find first available file slot
3993 ****************************************************************************/
3994 int find_free_file(void )
3997 static int first_file;
3999 /* we want to give out file handles differently on each new
4000 connection because of a common bug in MS clients where they try to
4001 reuse a file descriptor from an earlier smb connection. This code
4002 increases the chance that the errant client will get an error rather
4003 than causing corruption */
4004 if (first_file == 0) {
4005 first_file = (getpid() ^ (int)time(NULL)) % MAX_FNUMS;
4006 if (first_file == 0) first_file = 1;
4009 if (first_file >= MAX_FNUMS)
4012 for (i=first_file;i<MAX_FNUMS;i++)
4013 if (!Files[i].open && !Files[i].reserved) {
4014 memset(&Files[i], 0, sizeof(Files[i]));
4016 Files[i].reserved = True;
4020 /* returning a file handle of 0 is a bad idea - so we start at 1 */
4021 for (i=1;i<first_file;i++)
4022 if (!Files[i].open && !Files[i].reserved) {
4023 memset(&Files[i], 0, sizeof(Files[i]));
4025 Files[i].reserved = True;
4030 * Before we give up, go through the open files
4031 * and see if there are any files opened with a
4032 * batch oplock. If so break the oplock and then
4033 * re-use that entry (if it becomes closed).
4034 * This may help as NT/95 clients tend to keep
4035 * files batch oplocked for quite a long time
4036 * after they have finished with them.
4038 for (i=first_file;i<MAX_FNUMS;i++) {
4039 if(attempt_close_oplocked_file( &Files[i])) {
4040 memset(&Files[i], 0, sizeof(Files[i]));
4042 Files[i].reserved = True;
4047 for (i=1;i<MAX_FNUMS;i++) {
4048 if(attempt_close_oplocked_file( &Files[i])) {
4049 memset(&Files[i], 0, sizeof(Files[i]));
4051 Files[i].reserved = True;
4056 DEBUG(1,("ERROR! Out of file structures - perhaps increase MAX_OPEN_FILES?\n"));
4060 /****************************************************************************
4061 find first available connection slot, starting from a random position.
4062 The randomisation stops problems with the server dieing and clients
4063 thinking the server is still available.
4064 ****************************************************************************/
4065 static int find_free_connection(int hash )
4069 hash = (hash % (MAX_CONNECTIONS-2))+1;
4073 for (i=hash+1;i!=hash;)
4075 if (!Connections[i].open && Connections[i].used == used)
4077 DEBUG(3,("found free connection number %d\n",i));
4081 if (i == MAX_CONNECTIONS)
4091 DEBUG(1,("ERROR! Out of connection structures\n"));
4096 /****************************************************************************
4097 reply for the core protocol
4098 ****************************************************************************/
4099 int reply_corep(char *outbuf)
4101 int outsize = set_message(outbuf,1,0,True);
4103 Protocol = PROTOCOL_CORE;
4109 /****************************************************************************
4110 reply for the coreplus protocol
4111 ****************************************************************************/
4112 int reply_coreplus(char *outbuf)
4114 int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
4115 int outsize = set_message(outbuf,13,0,True);
4116 SSVAL(outbuf,smb_vwv5,raw); /* tell redirector we support
4117 readbraw and writebraw (possibly) */
4118 CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
4119 SSVAL(outbuf,smb_vwv1,0x1); /* user level security, don't encrypt */
4121 Protocol = PROTOCOL_COREPLUS;
4127 /****************************************************************************
4128 reply for the lanman 1.0 protocol
4129 ****************************************************************************/
4130 int reply_lanman1(char *outbuf)
4132 int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
4134 BOOL doencrypt = SMBENCRYPT();
4135 time_t t = time(NULL);
4137 if (lp_security()>=SEC_USER) secword |= 1;
4138 if (doencrypt) secword |= 2;
4140 set_message(outbuf,13,doencrypt?8:0,True);
4141 SSVAL(outbuf,smb_vwv1,secword);
4142 /* Create a token value and add it to the outgoing packet. */
4144 generate_next_challenge(smb_buf(outbuf));
4146 Protocol = PROTOCOL_LANMAN1;
4148 CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
4149 SSVAL(outbuf,smb_vwv2,max_recv);
4150 SSVAL(outbuf,smb_vwv3,lp_maxmux()); /* maxmux */
4151 SSVAL(outbuf,smb_vwv4,1);
4152 SSVAL(outbuf,smb_vwv5,raw); /* tell redirector we support
4153 readbraw writebraw (possibly) */
4154 SIVAL(outbuf,smb_vwv6,getpid());
4155 SSVAL(outbuf,smb_vwv10, TimeDiff(t)/60);
4157 put_dos_date(outbuf,smb_vwv8,t);
4159 return (smb_len(outbuf)+4);
4163 /****************************************************************************
4164 reply for the lanman 2.0 protocol
4165 ****************************************************************************/
4166 int reply_lanman2(char *outbuf)
4168 int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
4170 BOOL doencrypt = SMBENCRYPT();
4171 time_t t = time(NULL);
4172 struct cli_state *cli = NULL;
4176 if (lp_security() == SEC_SERVER) {
4177 cli = server_cryptkey();
4181 DEBUG(3,("using password server validation\n"));
4182 doencrypt = ((cli->sec_mode & 2) != 0);
4185 if (lp_security()>=SEC_USER) secword |= 1;
4186 if (doencrypt) secword |= 2;
4191 generate_next_challenge(cryptkey);
4193 memcpy(cryptkey, cli->cryptkey, 8);
4194 set_challenge(cli->cryptkey);
4198 set_message(outbuf,13,crypt_len,True);
4199 SSVAL(outbuf,smb_vwv1,secword);
4200 SIVAL(outbuf,smb_vwv6,getpid());
4202 memcpy(smb_buf(outbuf), cryptkey, 8);
4204 Protocol = PROTOCOL_LANMAN2;
4206 CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
4207 SSVAL(outbuf,smb_vwv2,max_recv);
4208 SSVAL(outbuf,smb_vwv3,lp_maxmux());
4209 SSVAL(outbuf,smb_vwv4,1);
4210 SSVAL(outbuf,smb_vwv5,raw); /* readbraw and/or writebraw */
4211 SSVAL(outbuf,smb_vwv10, TimeDiff(t)/60);
4212 put_dos_date(outbuf,smb_vwv8,t);
4214 return (smb_len(outbuf)+4);
4218 /****************************************************************************
4219 reply for the nt protocol
4220 ****************************************************************************/
4221 int reply_nt1(char *outbuf)
4223 /* dual names + lock_and_read + nt SMBs + remote API calls */
4224 int capabilities = CAP_NT_FIND|CAP_LOCK_AND_READ|CAP_RPC_REMOTE_APIS
4227 #endif /* HAVE_NT_SMBS */
4231 other valid capabilities which we may support at some time...
4232 CAP_LARGE_FILES|CAP_NT_SMBS|CAP_RPC_REMOTE_APIS;
4233 CAP_LARGE_READX|CAP_STATUS32|CAP_LEVEL_II_OPLOCKS;
4237 BOOL doencrypt = SMBENCRYPT();
4238 time_t t = time(NULL);
4240 struct cli_state *cli = NULL;
4244 if (lp_security() == SEC_SERVER) {
4245 cli = server_cryptkey();
4249 DEBUG(3,("using password server validation\n"));
4250 doencrypt = ((cli->sec_mode & 2) != 0);
4256 generate_next_challenge(cryptkey);
4258 memcpy(cryptkey, cli->cryptkey, 8);
4259 set_challenge(cli->cryptkey);
4263 if (lp_readraw() && lp_writeraw()) {
4264 capabilities |= CAP_RAW_MODE;
4267 if (lp_security() >= SEC_USER) secword |= 1;
4268 if (doencrypt) secword |= 2;
4270 /* decide where (if) to put the encryption challenge, and
4271 follow it with the OEM'd domain name
4273 data_len = crypt_len + strlen(global_myworkgroup) + 1;
4275 set_message(outbuf,17,data_len,True);
4276 pstrcpy(smb_buf(outbuf)+crypt_len, global_myworkgroup);
4278 CVAL(outbuf,smb_vwv1) = secword;
4279 SSVALS(outbuf,smb_vwv16+1,crypt_len);
4281 memcpy(smb_buf(outbuf), cryptkey, 8);
4283 Protocol = PROTOCOL_NT1;
4285 SSVAL(outbuf,smb_vwv1+1,lp_maxmux()); /* maxmpx */
4286 SSVAL(outbuf,smb_vwv2+1,1); /* num vcs */
4287 SIVAL(outbuf,smb_vwv3+1,0xffff); /* max buffer. LOTS! */
4288 SIVAL(outbuf,smb_vwv5+1,0x10000); /* raw size. full 64k */
4289 SIVAL(outbuf,smb_vwv7+1,getpid()); /* session key */
4290 SIVAL(outbuf,smb_vwv9+1,capabilities); /* capabilities */
4291 put_long_date(outbuf+smb_vwv11+1,t);
4292 SSVALS(outbuf,smb_vwv15+1,TimeDiff(t)/60);
4293 SSVAL(outbuf,smb_vwv17,data_len); /* length of challenge+domain strings */
4295 return (smb_len(outbuf)+4);
4298 /* these are the protocol lists used for auto architecture detection:
4301 protocol [PC NETWORK PROGRAM 1.0]
4302 protocol [XENIX CORE]
4303 protocol [MICROSOFT NETWORKS 1.03]
4304 protocol [LANMAN1.0]
4305 protocol [Windows for Workgroups 3.1a]
4306 protocol [LM1.2X002]
4307 protocol [LANMAN2.1]
4308 protocol [NT LM 0.12]
4311 protocol [PC NETWORK PROGRAM 1.0]
4312 protocol [XENIX CORE]
4313 protocol [MICROSOFT NETWORKS 1.03]
4314 protocol [LANMAN1.0]
4315 protocol [Windows for Workgroups 3.1a]
4316 protocol [LM1.2X002]
4317 protocol [LANMAN2.1]
4318 protocol [NT LM 0.12]
4321 protocol [PC NETWORK PROGRAM 1.0]
4322 protocol [XENIX CORE]
4323 protocol [LANMAN1.0]
4324 protocol [LM1.2X002]
4325 protocol [LANMAN2.1]
4329 * Modified to recognize the architecture of the remote machine better.
4331 * This appears to be the matrix of which protocol is used by which
4333 Protocol WfWg Win95 WinNT OS/2
4334 PC NETWORK PROGRAM 1.0 1 1 1 1
4336 MICROSOFT NETWORKS 3.0 2 2
4338 MICROSOFT NETWORKS 1.03 3
4341 Windows for Workgroups 3.1a 5 5 5
4346 * tim@fsg.com 09/29/95
4349 #define ARCH_WFWG 0x3 /* This is a fudge because WfWg is like Win95 */
4350 #define ARCH_WIN95 0x2
4351 #define ARCH_OS2 0xC /* Again OS/2 is like NT */
4352 #define ARCH_WINNT 0x8
4353 #define ARCH_SAMBA 0x10
4355 #define ARCH_ALL 0x1F
4357 /* List of supported protocols, most desired first */
4361 int (*proto_reply_fn)(char *);
4363 } supported_protocols[] = {
4364 {"NT LANMAN 1.0", "NT1", reply_nt1, PROTOCOL_NT1},
4365 {"NT LM 0.12", "NT1", reply_nt1, PROTOCOL_NT1},
4366 {"LM1.2X002", "LANMAN2", reply_lanman2, PROTOCOL_LANMAN2},
4367 {"Samba", "LANMAN2", reply_lanman2, PROTOCOL_LANMAN2},
4368 {"DOS LM1.2X002", "LANMAN2", reply_lanman2, PROTOCOL_LANMAN2},
4369 {"LANMAN1.0", "LANMAN1", reply_lanman1, PROTOCOL_LANMAN1},
4370 {"MICROSOFT NETWORKS 3.0", "LANMAN1", reply_lanman1, PROTOCOL_LANMAN1},
4371 {"MICROSOFT NETWORKS 1.03", "COREPLUS", reply_coreplus, PROTOCOL_COREPLUS},
4372 {"PC NETWORK PROGRAM 1.0", "CORE", reply_corep, PROTOCOL_CORE},
4377 /****************************************************************************
4379 ****************************************************************************/
4380 static int reply_negprot(char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
4382 int outsize = set_message(outbuf,1,0,True);
4387 int bcc = SVAL(smb_buf(inbuf),-2);
4388 int arch = ARCH_ALL;
4390 p = smb_buf(inbuf)+1;
4391 while (p < (smb_buf(inbuf) + bcc))
4394 DEBUG(3,("Requested protocol [%s]\n",p));
4395 if (strcsequal(p,"Windows for Workgroups 3.1a"))
4396 arch &= ( ARCH_WFWG | ARCH_WIN95 | ARCH_WINNT );
4397 else if (strcsequal(p,"DOS LM1.2X002"))
4398 arch &= ( ARCH_WFWG | ARCH_WIN95 );
4399 else if (strcsequal(p,"DOS LANMAN2.1"))
4400 arch &= ( ARCH_WFWG | ARCH_WIN95 );
4401 else if (strcsequal(p,"NT LM 0.12"))
4402 arch &= ( ARCH_WIN95 | ARCH_WINNT );
4403 else if (strcsequal(p,"LANMAN2.1"))
4404 arch &= ( ARCH_WINNT | ARCH_OS2 );
4405 else if (strcsequal(p,"LM1.2X002"))
4406 arch &= ( ARCH_WINNT | ARCH_OS2 );
4407 else if (strcsequal(p,"MICROSOFT NETWORKS 1.03"))
4409 else if (strcsequal(p,"XENIX CORE"))
4410 arch &= ( ARCH_WINNT | ARCH_OS2 );
4411 else if (strcsequal(p,"Samba")) {
4421 set_remote_arch(RA_SAMBA);
4424 set_remote_arch(RA_WFWG);
4427 set_remote_arch(RA_WIN95);
4430 set_remote_arch(RA_WINNT);
4433 set_remote_arch(RA_OS2);
4436 set_remote_arch(RA_UNKNOWN);
4440 /* possibly reload - change of architecture */
4441 reload_services(True);
4443 /* a special case to stop password server loops */
4444 if (Index == 1 && strequal(remote_machine,myhostname) &&
4445 (lp_security()==SEC_SERVER || lp_security()==SEC_DOMAIN))
4446 exit_server("Password server loop!");
4448 /* Check for protocols, most desirable first */
4449 for (protocol = 0; supported_protocols[protocol].proto_name; protocol++)
4451 p = smb_buf(inbuf)+1;
4453 if (lp_maxprotocol() >= supported_protocols[protocol].protocol_level)
4454 while (p < (smb_buf(inbuf) + bcc))
4456 if (strequal(p,supported_protocols[protocol].proto_name))
4465 SSVAL(outbuf,smb_vwv0,choice);
4467 extern fstring remote_proto;
4468 fstrcpy(remote_proto,supported_protocols[protocol].short_name);
4469 reload_services(True);
4470 outsize = supported_protocols[protocol].proto_reply_fn(outbuf);
4471 DEBUG(3,("Selected protocol %s\n",supported_protocols[protocol].proto_name));
4474 DEBUG(0,("No protocol supported !\n"));
4476 SSVAL(outbuf,smb_vwv0,choice);
4478 DEBUG(5,("%s negprot index=%d\n",timestring(),choice));
4484 /****************************************************************************
4485 close all open files for a connection
4486 ****************************************************************************/
4487 static void close_open_files(int cnum)
4490 for (i=0;i<MAX_FNUMS;i++)
4491 if( Files[i].cnum == cnum && Files[i].open) {
4492 if(Files[i].is_directory)
4495 close_file(i,False);
4501 /****************************************************************************
4503 ****************************************************************************/
4504 void close_cnum(int cnum, uint16 vuid)
4507 DirCacheFlush(SNUM(cnum));
4511 if (!OPEN_CNUM(cnum))
4513 DEBUG(0,("Can't close cnum %d\n",cnum));
4517 DEBUG(IS_IPC(cnum)?3:1,("%s %s (%s) closed connection to service %s\n",
4519 remote_machine,client_addr(Client),
4520 lp_servicename(SNUM(cnum))));
4522 yield_connection(cnum,
4523 lp_servicename(SNUM(cnum)),
4524 lp_max_connections(SNUM(cnum)));
4526 if (lp_status(SNUM(cnum)))
4527 yield_connection(cnum,"STATUS.",MAXSTATUS);
4529 close_open_files(cnum);
4530 dptr_closecnum(cnum);
4532 /* execute any "postexec = " line */
4533 if (*lp_postexec(SNUM(cnum)) && become_user(&Connections[cnum], cnum,vuid))
4536 pstrcpy(cmd,lp_postexec(SNUM(cnum)));
4537 standard_sub(cnum,cmd);
4538 smbrun(cmd,NULL,False);
4543 /* execute any "root postexec = " line */
4544 if (*lp_rootpostexec(SNUM(cnum)))
4547 pstrcpy(cmd,lp_rootpostexec(SNUM(cnum)));
4548 standard_sub(cnum,cmd);
4549 smbrun(cmd,NULL,False);
4552 Connections[cnum].open = False;
4553 num_connections_open--;
4554 if (Connections[cnum].ngroups && Connections[cnum].groups)
4556 if (Connections[cnum].igroups != (int *)Connections[cnum].groups)
4557 free(Connections[cnum].groups);
4558 free(Connections[cnum].igroups);
4559 Connections[cnum].groups = NULL;
4560 Connections[cnum].igroups = NULL;
4561 Connections[cnum].ngroups = 0;
4564 free_namearray(Connections[cnum].veto_list);
4565 free_namearray(Connections[cnum].hide_list);
4566 free_namearray(Connections[cnum].veto_oplock_list);
4568 string_set(&Connections[cnum].user,"");
4569 string_set(&Connections[cnum].dirpath,"");
4570 string_set(&Connections[cnum].connectpath,"");
4576 /*******************************************************************
4577 prepare to dump a core file - carefully!
4578 ********************************************************************/
4579 static BOOL dump_core(void)
4583 pstrcpy(dname,debugf);
4584 if ((p=strrchr(dname,'/'))) *p=0;
4585 pstrcat(dname,"/corefiles");
4587 sys_chown(dname,getuid(),getgid());
4589 if (chdir(dname)) return(False);
4592 #ifndef NO_GETRLIMIT
4596 getrlimit(RLIMIT_CORE, &rlp);
4597 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
4598 setrlimit(RLIMIT_CORE, &rlp);
4599 getrlimit(RLIMIT_CORE, &rlp);
4600 DEBUG(3,("Core limits now %d %d\n",rlp.rlim_cur,rlp.rlim_max));
4606 DEBUG(0,("Dumping core in %s\n",dname));
4611 /****************************************************************************
4613 ****************************************************************************/
4614 void exit_server(char *reason)
4616 static int firsttime=1;
4619 if (!firsttime) exit(0);
4623 DEBUG(2,("Closing connections\n"));
4624 for (i=0;i<MAX_CONNECTIONS;i++)
4625 if (Connections[i].open)
4626 close_cnum(i,(uint16)-1);
4628 if (dcelogin_atmost_once)
4632 int oldlevel = DEBUGLEVEL;
4634 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
4636 show_msg(last_inbuf);
4637 DEBUGLEVEL = oldlevel;
4638 DEBUG(0,("===============================================================\n"));
4640 if (dump_core()) return;
4646 DEBUG(3,("%s Server exit (%s)\n",timestring(),reason?reason:""));
4650 /****************************************************************************
4651 do some standard substitutions in a string
4652 ****************************************************************************/
4653 void standard_sub(int cnum,char *str)
4655 if (VALID_CNUM(cnum)) {
4658 for ( s=str ; (p=strchr(s, '%')) != NULL ; s=p ) {
4660 case 'H' : if ((home = get_home_dir(Connections[cnum].user))!=NULL)
4661 string_sub(p,"%H",home);
4665 case 'P' : string_sub(p,"%P",Connections[cnum].connectpath); break;
4666 case 'S' : string_sub(p,"%S",lp_servicename(Connections[cnum].service)); break;
4667 case 'g' : string_sub(p,"%g",gidtoname(Connections[cnum].gid)); break;
4668 case 'u' : string_sub(p,"%u",Connections[cnum].user); break;
4670 * Patch from jkf@soton.ac.uk
4671 * Left the %N (NIS server name) in standard_sub_basic as it
4672 * is a feature for logon servers, hence uses the username.
4673 * The %p (NIS server path) code is here as it is used
4674 * instead of the default "path =" string in [homes] and so
4675 * needs the service name, not the username.
4677 case 'p' : string_sub(p,"%p",automount_path(lp_servicename(Connections[cnum].service))); break;
4678 case '\0' : p++; break; /* don't run off the end of the string */
4679 default : p+=2; break;
4683 standard_sub_basic(str);
4687 These flags determine some of the permissions required to do an operation
4689 Note that I don't set NEED_WRITE on some write operations because they
4690 are used by some brain-dead clients when printing, and I don't want to
4691 force write permissions on print services.
4693 #define AS_USER (1<<0)
4694 #define NEED_WRITE (1<<1)
4695 #define TIME_INIT (1<<2)
4696 #define CAN_IPC (1<<3)
4697 #define AS_GUEST (1<<5)
4698 #define QUEUE_IN_OPLOCK (1<<6)
4701 define a list of possible SMB messages and their corresponding
4702 functions. Any message that has a NULL function is unimplemented -
4703 please feel free to contribute implementations!
4705 struct smb_message_struct
4709 int (*fn)(char *, char *, int, int);
4719 {SMBnegprot,"SMBnegprot",reply_negprot,0},
4720 {SMBtcon,"SMBtcon",reply_tcon,0},
4721 {SMBtdis,"SMBtdis",reply_tdis,0},
4722 {SMBexit,"SMBexit",reply_exit,0},
4723 {SMBioctl,"SMBioctl",reply_ioctl,0},
4724 {SMBecho,"SMBecho",reply_echo,0},
4725 {SMBsesssetupX,"SMBsesssetupX",reply_sesssetup_and_X,0},
4726 {SMBtconX,"SMBtconX",reply_tcon_and_X,0},
4727 {SMBulogoffX, "SMBulogoffX", reply_ulogoffX, 0}, /* ulogoff doesn't give a valid TID */
4728 {SMBgetatr,"SMBgetatr",reply_getatr,AS_USER},
4729 {SMBsetatr,"SMBsetatr",reply_setatr,AS_USER | NEED_WRITE},
4730 {SMBchkpth,"SMBchkpth",reply_chkpth,AS_USER},
4731 {SMBsearch,"SMBsearch",reply_search,AS_USER},
4732 {SMBopen,"SMBopen",reply_open,AS_USER | QUEUE_IN_OPLOCK },
4734 /* note that SMBmknew and SMBcreate are deliberately overloaded */
4735 {SMBcreate,"SMBcreate",reply_mknew,AS_USER},
4736 {SMBmknew,"SMBmknew",reply_mknew,AS_USER},
4738 {SMBunlink,"SMBunlink",reply_unlink,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
4739 {SMBread,"SMBread",reply_read,AS_USER},
4740 {SMBwrite,"SMBwrite",reply_write,AS_USER},
4741 {SMBclose,"SMBclose",reply_close,AS_USER | CAN_IPC},
4742 {SMBmkdir,"SMBmkdir",reply_mkdir,AS_USER | NEED_WRITE},
4743 {SMBrmdir,"SMBrmdir",reply_rmdir,AS_USER | NEED_WRITE},
4744 {SMBdskattr,"SMBdskattr",reply_dskattr,AS_USER},
4745 {SMBmv,"SMBmv",reply_mv,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
4747 /* this is a Pathworks specific call, allowing the
4748 changing of the root path */
4749 {pSETDIR,"pSETDIR",reply_setdir,AS_USER},
4751 {SMBlseek,"SMBlseek",reply_lseek,AS_USER},
4752 {SMBflush,"SMBflush",reply_flush,AS_USER},
4753 {SMBctemp,"SMBctemp",reply_ctemp,AS_USER | QUEUE_IN_OPLOCK },
4754 {SMBsplopen,"SMBsplopen",reply_printopen,AS_USER | QUEUE_IN_OPLOCK },
4755 {SMBsplclose,"SMBsplclose",reply_printclose,AS_USER},
4756 {SMBsplretq,"SMBsplretq",reply_printqueue,AS_USER|AS_GUEST},
4757 {SMBsplwr,"SMBsplwr",reply_printwrite,AS_USER},
4758 {SMBlock,"SMBlock",reply_lock,AS_USER},
4759 {SMBunlock,"SMBunlock",reply_unlock,AS_USER},
4761 /* CORE+ PROTOCOL FOLLOWS */
4763 {SMBreadbraw,"SMBreadbraw",reply_readbraw,AS_USER},
4764 {SMBwritebraw,"SMBwritebraw",reply_writebraw,AS_USER},
4765 {SMBwriteclose,"SMBwriteclose",reply_writeclose,AS_USER},
4766 {SMBlockread,"SMBlockread",reply_lockread,AS_USER},
4767 {SMBwriteunlock,"SMBwriteunlock",reply_writeunlock,AS_USER},
4769 /* LANMAN1.0 PROTOCOL FOLLOWS */
4771 {SMBreadBmpx,"SMBreadBmpx",reply_readbmpx,AS_USER},
4772 {SMBreadBs,"SMBreadBs",NULL,AS_USER},
4773 {SMBwriteBmpx,"SMBwriteBmpx",reply_writebmpx,AS_USER},
4774 {SMBwriteBs,"SMBwriteBs",reply_writebs,AS_USER},
4775 {SMBwritec,"SMBwritec",NULL,AS_USER},
4776 {SMBsetattrE,"SMBsetattrE",reply_setattrE,AS_USER | NEED_WRITE},
4777 {SMBgetattrE,"SMBgetattrE",reply_getattrE,AS_USER},
4778 {SMBtrans,"SMBtrans",reply_trans,AS_USER | CAN_IPC},
4779 {SMBtranss,"SMBtranss",NULL,AS_USER | CAN_IPC},
4780 {SMBioctls,"SMBioctls",NULL,AS_USER},
4781 {SMBcopy,"SMBcopy",reply_copy,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
4782 {SMBmove,"SMBmove",NULL,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
4784 {SMBopenX,"SMBopenX",reply_open_and_X,AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
4785 {SMBreadX,"SMBreadX",reply_read_and_X,AS_USER | CAN_IPC },
4786 {SMBwriteX,"SMBwriteX",reply_write_and_X,AS_USER},
4787 {SMBlockingX,"SMBlockingX",reply_lockingX,AS_USER},
4789 {SMBffirst,"SMBffirst",reply_search,AS_USER},
4790 {SMBfunique,"SMBfunique",reply_search,AS_USER},
4791 {SMBfclose,"SMBfclose",reply_fclose,AS_USER},
4793 /* LANMAN2.0 PROTOCOL FOLLOWS */
4794 {SMBfindnclose, "SMBfindnclose", reply_findnclose, AS_USER},
4795 {SMBfindclose, "SMBfindclose", reply_findclose,AS_USER},
4796 {SMBtrans2, "SMBtrans2", reply_trans2, AS_USER },
4797 {SMBtranss2, "SMBtranss2", reply_transs2, AS_USER},
4800 /* NT PROTOCOL FOLLOWS */
4801 {SMBntcreateX, "SMBntcreateX", reply_ntcreate_and_X, AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
4802 {SMBnttrans, "SMBnttrans", reply_nttrans, AS_USER | CAN_IPC },
4803 {SMBnttranss, "SMBnttranss", reply_nttranss, AS_USER | CAN_IPC },
4804 {SMBntcancel, "SMBntcancel", reply_ntcancel, AS_USER },
4805 #endif /* HAVE_NT_SMBS */
4807 /* messaging routines */
4808 {SMBsends,"SMBsends",reply_sends,AS_GUEST},
4809 {SMBsendstrt,"SMBsendstrt",reply_sendstrt,AS_GUEST},
4810 {SMBsendend,"SMBsendend",reply_sendend,AS_GUEST},
4811 {SMBsendtxt,"SMBsendtxt",reply_sendtxt,AS_GUEST},
4813 /* NON-IMPLEMENTED PARTS OF THE CORE PROTOCOL */
4815 {SMBsendb,"SMBsendb",NULL,AS_GUEST},
4816 {SMBfwdname,"SMBfwdname",NULL,AS_GUEST},
4817 {SMBcancelf,"SMBcancelf",NULL,AS_GUEST},
4818 {SMBgetmac,"SMBgetmac",NULL,AS_GUEST}
4821 /****************************************************************************
4822 return a string containing the function name of a SMB command
4823 ****************************************************************************/
4824 char *smb_fn_name(int type)
4826 static char *unknown_name = "SMBunknown";
4827 static int num_smb_messages =
4828 sizeof(smb_messages) / sizeof(struct smb_message_struct);
4831 for (match=0;match<num_smb_messages;match++)
4832 if (smb_messages[match].code == type)
4835 if (match == num_smb_messages)
4836 return(unknown_name);
4838 return(smb_messages[match].name);
4842 /****************************************************************************
4843 do a switch on the message type, and return the response size
4844 ****************************************************************************/
4845 static int switch_message(int type,char *inbuf,char *outbuf,int size,int bufsize)
4849 static int num_smb_messages =
4850 sizeof(smb_messages) / sizeof(struct smb_message_struct);
4854 struct timeval msg_start_time;
4855 struct timeval msg_end_time;
4856 static unsigned long total_time = 0;
4858 GetTimeOfDay(&msg_start_time);
4865 last_message = type;
4867 /* make sure this is an SMB packet */
4868 if (strncmp(smb_base(inbuf),"\377SMB",4) != 0)
4870 DEBUG(2,("Non-SMB packet of length %d\n",smb_len(inbuf)));
4874 for (match=0;match<num_smb_messages;match++)
4875 if (smb_messages[match].code == type)
4878 if (match == num_smb_messages)
4880 DEBUG(0,("Unknown message type %d!\n",type));
4881 outsize = reply_unknown(inbuf,outbuf);
4885 DEBUG(3,("switch message %s (pid %d)\n",smb_messages[match].name,pid));
4887 if(global_oplock_break && (smb_messages[match].flags & QUEUE_IN_OPLOCK))
4890 * Queue this message as we are the process of an oplock break.
4893 DEBUG(2,("%s: switch_message: queueing message due to being in oplock break state.\n",
4896 push_smb_message( inbuf, size);
4900 if (smb_messages[match].fn)
4902 int cnum = SVAL(inbuf,smb_tid);
4903 int flags = smb_messages[match].flags;
4904 static uint16 last_session_tag = UID_FIELD_INVALID;
4905 /* In share mode security we must ignore the vuid. */
4906 uint16 session_tag = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : SVAL(inbuf,smb_uid);
4907 /* Ensure this value is replaced in the incoming packet. */
4908 SSVAL(inbuf,smb_uid,session_tag);
4911 * Ensure the correct username is in sesssetup_user.
4912 * This is a really ugly bugfix for problems with
4913 * multiple session_setup_and_X's being done and
4914 * allowing %U and %G substitutions to work correctly.
4915 * There is a reason this code is done here, don't
4916 * move it unless you know what you're doing... :-).
4919 if(session_tag != last_session_tag ) {
4920 user_struct *vuser = NULL;
4922 last_session_tag = session_tag;
4923 if(session_tag != UID_FIELD_INVALID)
4924 vuser = get_valid_user_struct(session_tag);
4926 pstrcpy( sesssetup_user, vuser->requested_name);
4929 /* does this protocol need to be run as root? */
4930 if (!(flags & AS_USER))
4933 /* does this protocol need to be run as the connected user? */
4934 if ((flags & AS_USER) && !become_user(&Connections[cnum], cnum,session_tag)) {
4935 if (flags & AS_GUEST)
4938 return(ERROR(ERRSRV,ERRinvnid));
4940 /* this code is to work around a bug is MS client 3 without
4941 introducing a security hole - it needs to be able to do
4942 print queue checks as guest if it isn't logged in properly */
4943 if (flags & AS_USER)
4946 /* does it need write permission? */
4947 if ((flags & NEED_WRITE) && !CAN_WRITE(cnum))
4948 return(ERROR(ERRSRV,ERRaccess));
4950 /* ipc services are limited */
4951 if (IS_IPC(cnum) && (flags & AS_USER) && !(flags & CAN_IPC))
4952 return(ERROR(ERRSRV,ERRaccess));
4954 /* load service specific parameters */
4955 if (OPEN_CNUM(cnum) && !become_service(cnum,(flags & AS_USER)?True:False))
4956 return(ERROR(ERRSRV,ERRaccess));
4958 /* does this protocol need to be run as guest? */
4959 if ((flags & AS_GUEST) && (!become_guest() || !check_access(-1)))
4960 return(ERROR(ERRSRV,ERRaccess));
4964 outsize = smb_messages[match].fn(inbuf,outbuf,size,bufsize);
4968 outsize = reply_unknown(inbuf,outbuf);
4973 GetTimeOfDay(&msg_end_time);
4974 if (!(smb_messages[match].flags & TIME_INIT))
4976 smb_messages[match].time = 0;
4977 smb_messages[match].flags |= TIME_INIT;
4980 unsigned long this_time =
4981 (msg_end_time.tv_sec - msg_start_time.tv_sec)*1e6 +
4982 (msg_end_time.tv_usec - msg_start_time.tv_usec);
4983 smb_messages[match].time += this_time;
4984 total_time += this_time;
4986 DEBUG(2,("TIME %s %d usecs %g pct\n",
4987 smb_fn_name(type),smb_messages[match].time,
4988 (100.0*smb_messages[match].time) / total_time));
4995 /****************************************************************************
4996 construct a chained reply and add it to the already made reply
4997 **************************************************************************/
4998 int chain_reply(char *inbuf,char *outbuf,int size,int bufsize)
5000 static char *orig_inbuf;
5001 static char *orig_outbuf;
5002 int smb_com1, smb_com2 = CVAL(inbuf,smb_vwv0);
5003 unsigned smb_off2 = SVAL(inbuf,smb_vwv1);
5004 char *inbuf2, *outbuf2;
5006 char inbuf_saved[smb_wct];
5007 char outbuf_saved[smb_wct];
5008 extern int chain_size;
5009 int wct = CVAL(outbuf,smb_wct);
5010 int outsize = smb_size + 2*wct + SVAL(outbuf,smb_vwv0+2*wct);
5012 /* maybe its not chained */
5013 if (smb_com2 == 0xFF) {
5014 CVAL(outbuf,smb_vwv0) = 0xFF;
5018 if (chain_size == 0) {
5019 /* this is the first part of the chain */
5021 orig_outbuf = outbuf;
5024 /* we need to tell the client where the next part of the reply will be */
5025 SSVAL(outbuf,smb_vwv1,smb_offset(outbuf+outsize,outbuf));
5026 CVAL(outbuf,smb_vwv0) = smb_com2;
5028 /* remember how much the caller added to the chain, only counting stuff
5029 after the parameter words */
5030 chain_size += outsize - smb_wct;
5032 /* work out pointers into the original packets. The
5033 headers on these need to be filled in */
5034 inbuf2 = orig_inbuf + smb_off2 + 4 - smb_wct;
5035 outbuf2 = orig_outbuf + SVAL(outbuf,smb_vwv1) + 4 - smb_wct;
5037 /* remember the original command type */
5038 smb_com1 = CVAL(orig_inbuf,smb_com);
5040 /* save the data which will be overwritten by the new headers */
5041 memcpy(inbuf_saved,inbuf2,smb_wct);
5042 memcpy(outbuf_saved,outbuf2,smb_wct);
5044 /* give the new packet the same header as the last part of the SMB */
5045 memmove(inbuf2,inbuf,smb_wct);
5047 /* create the in buffer */
5048 CVAL(inbuf2,smb_com) = smb_com2;
5050 /* create the out buffer */
5051 bzero(outbuf2,smb_size);
5052 set_message(outbuf2,0,0,True);
5053 CVAL(outbuf2,smb_com) = CVAL(inbuf2,smb_com);
5055 memcpy(outbuf2+4,inbuf2+4,4);
5056 CVAL(outbuf2,smb_rcls) = SMB_SUCCESS;
5057 CVAL(outbuf2,smb_reh) = 0;
5058 CVAL(outbuf2,smb_flg) = 0x80 | (CVAL(inbuf2,smb_flg) & 0x8); /* bit 7 set
5060 SSVAL(outbuf2,smb_flg2,1); /* say we support long filenames */
5061 SSVAL(outbuf2,smb_err,SMB_SUCCESS);
5062 SSVAL(outbuf2,smb_tid,SVAL(inbuf2,smb_tid));
5063 SSVAL(outbuf2,smb_pid,SVAL(inbuf2,smb_pid));
5064 SSVAL(outbuf2,smb_uid,SVAL(inbuf2,smb_uid));
5065 SSVAL(outbuf2,smb_mid,SVAL(inbuf2,smb_mid));
5067 DEBUG(3,("Chained message\n"));
5070 /* process the request */
5071 outsize2 = switch_message(smb_com2,inbuf2,outbuf2,size-chain_size,
5072 bufsize-chain_size);
5074 /* copy the new reply and request headers over the old ones, but
5075 preserve the smb_com field */
5076 memmove(orig_outbuf,outbuf2,smb_wct);
5077 CVAL(orig_outbuf,smb_com) = smb_com1;
5079 /* restore the saved data, being careful not to overwrite any
5080 data from the reply header */
5081 memcpy(inbuf2,inbuf_saved,smb_wct);
5083 int ofs = smb_wct - PTR_DIFF(outbuf2,orig_outbuf);
5084 if (ofs < 0) ofs = 0;
5085 memmove(outbuf2+ofs,outbuf_saved+ofs,smb_wct-ofs);
5093 /****************************************************************************
5094 construct a reply to the incoming packet
5095 ****************************************************************************/
5096 int construct_reply(char *inbuf,char *outbuf,int size,int bufsize)
5098 int type = CVAL(inbuf,smb_com);
5100 int msg_type = CVAL(inbuf,0);
5101 extern int chain_size;
5103 smb_last_time = time(NULL);
5109 bzero(outbuf,smb_size);
5112 return(reply_special(inbuf,outbuf));
5114 CVAL(outbuf,smb_com) = CVAL(inbuf,smb_com);
5115 set_message(outbuf,0,0,True);
5117 memcpy(outbuf+4,inbuf+4,4);
5118 CVAL(outbuf,smb_rcls) = SMB_SUCCESS;
5119 CVAL(outbuf,smb_reh) = 0;
5120 CVAL(outbuf,smb_flg) = 0x80 | (CVAL(inbuf,smb_flg) & 0x8); /* bit 7 set
5122 SSVAL(outbuf,smb_flg2,1); /* say we support long filenames */
5123 SSVAL(outbuf,smb_err,SMB_SUCCESS);
5124 SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
5125 SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
5126 SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
5127 SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
5129 outsize = switch_message(type,inbuf,outbuf,size,bufsize);
5131 outsize += chain_size;
5134 smb_setlen(outbuf,outsize - 4);
5138 /****************************************************************************
5139 process commands from the client
5140 ****************************************************************************/
5141 static void process(void)
5145 InBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
5146 OutBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
5147 if ((InBuffer == NULL) || (OutBuffer == NULL))
5150 InBuffer += SMB_ALIGNMENT;
5151 OutBuffer += SMB_ALIGNMENT;
5154 DEBUG(3,("priming nmbd\n"));
5157 ip = *interpret_addr2("localhost");
5158 if (zero_ip(ip)) ip = *interpret_addr2("127.0.0.1");
5160 send_one_packet(OutBuffer,1,ip,NMB_PORT,SOCK_DGRAM);
5164 /* re-initialise the timezone */
5169 int deadtime = lp_deadtime()*60;
5171 int last_keepalive=0;
5172 int service_load_counter = 0;
5173 BOOL got_smb = False;
5176 deadtime = DEFAULT_SMBD_TIMEOUT;
5178 #if USE_READ_PREDICTION
5179 if (lp_readprediction())
5180 do_read_prediction();
5185 for (counter=SMBD_SELECT_LOOP;
5186 !receive_message_or_smb(Client,oplock_sock,
5187 InBuffer,BUFFER_SIZE,SMBD_SELECT_LOOP*1000,&got_smb);
5188 counter += SMBD_SELECT_LOOP)
5192 BOOL allidle = True;
5193 extern int keepalive;
5195 if (counter > 365 * 3600) /* big number of seconds. */
5198 service_load_counter = 0;
5201 if (smb_read_error == READ_EOF)
5203 DEBUG(3,("end of file from client\n"));
5207 if (smb_read_error == READ_ERROR)
5209 DEBUG(3,("receive_smb error (%s) exiting\n",
5216 /* become root again if waiting */
5219 /* check for smb.conf reload */
5220 if (counter >= service_load_counter + SMBD_RELOAD_CHECK)
5222 service_load_counter = counter;
5224 /* reload services, if files have changed. */
5225 reload_services(True);
5229 * If reload_after_sighup == True then we got a SIGHUP
5230 * and are being asked to reload. Fix from <branko.cibej@hermes.si>
5233 if (reload_after_sighup)
5235 DEBUG(0,("Reloading services after SIGHUP\n"));
5236 reload_services(False);
5237 reload_after_sighup = False;
5240 /* automatic timeout if all connections are closed */
5241 if (num_connections_open==0 && counter >= IDLE_CLOSED_TIMEOUT)
5243 DEBUG(2,("%s Closing idle connection\n",timestring()));
5247 if (keepalive && (counter-last_keepalive)>keepalive)
5249 struct cli_state *cli = server_client();
5250 if (!send_keepalive(Client)) {
5251 DEBUG(2,("%s Keepalive failed - exiting\n",timestring()));
5254 /* also send a keepalive to the password server if its still
5256 if (cli && cli->initialised)
5257 send_keepalive(cli->fd);
5258 last_keepalive = counter;
5261 /* check for connection timeouts */
5262 for (i=0;i<MAX_CONNECTIONS;i++)
5263 if (Connections[i].open)
5265 /* close dirptrs on connections that are idle */
5266 if ((t-Connections[i].lastused)>DPTR_IDLE_TIMEOUT)
5269 if (Connections[i].num_files_open > 0 ||
5270 (t-Connections[i].lastused)<deadtime)
5274 if (allidle && num_connections_open>0)
5276 DEBUG(2,("%s Closing idle connection 2\n",timestring()));
5280 if(global_machine_pasword_needs_changing)
5282 unsigned char trust_passwd_hash[16];
5284 pstring remote_machine_list;
5287 * We're in domain level security, and the code that
5288 * read the machine password flagged that the machine
5289 * password needs changing.
5293 * First, open the machine password file with an exclusive lock.
5296 if(!trust_password_lock( global_myworkgroup, global_myname, True)) {
5297 DEBUG(0,("process: unable to open the machine account password file for \
5298 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
5302 if(!get_trust_account_password( trust_passwd_hash, &lct)) {
5303 DEBUG(0,("process: unable to read the machine account password for \
5304 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
5305 trust_password_unlock();
5310 * Make sure someone else hasn't already done this.
5313 if(t < lct + lp_machine_password_timeout()) {
5314 trust_password_unlock();
5315 global_machine_pasword_needs_changing = False;
5319 pstrcpy(remote_machine_list, lp_passwordserver());
5321 change_trust_account_password( global_myworkgroup, remote_machine_list);
5322 trust_password_unlock();
5323 global_machine_pasword_needs_changing = False;
5328 process_smb(InBuffer, OutBuffer);
5330 process_local_message(oplock_sock, InBuffer, BUFFER_SIZE);
5335 /****************************************************************************
5336 initialise connect, service and file structs
5337 ****************************************************************************/
5338 static void init_structs(void )
5341 get_myname(myhostname,NULL);
5344 * Set the machine NETBIOS name if not already
5345 * set from the config file.
5348 if (!*global_myname)
5351 fstrcpy( global_myname, myhostname );
5352 p = strchr( global_myname, '.' );
5356 strupper( global_myname );
5358 for (i=0;i<MAX_CONNECTIONS;i++)
5360 Connections[i].open = False;
5361 Connections[i].num_files_open=0;
5362 Connections[i].lastused=0;
5363 Connections[i].used=False;
5364 string_init(&Connections[i].user,"");
5365 string_init(&Connections[i].dirpath,"");
5366 string_init(&Connections[i].connectpath,"");
5367 string_init(&Connections[i].origpath,"");
5370 for (i=0;i<MAX_FNUMS;i++)
5372 Files[i].open = False;
5373 string_init(&Files[i].name,"");
5376 for (i=0;i<MAX_OPEN_FILES;i++)
5378 file_fd_struct *fd_ptr = &FileFd[i];
5379 fd_ptr->ref_count = 0;
5380 fd_ptr->dev = (int32)-1;
5381 fd_ptr->inode = (int32)-1;
5383 fd_ptr->fd_readonly = -1;
5384 fd_ptr->fd_writeonly = -1;
5385 fd_ptr->real_open_flags = -1;
5389 init_rpc_pipe_hnd();
5391 /* for LSA handles */
5392 init_lsa_policy_hnd();
5397 /****************************************************************************
5398 usage on the program
5399 ****************************************************************************/
5400 static void usage(char *pname)
5402 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
5404 printf("Usage: %s [-D] [-p port] [-d debuglevel] [-l log basename] [-s services file]\n",pname);
5405 printf("Version %s\n",VERSION);
5406 printf("\t-D become a daemon\n");
5407 printf("\t-p port listen on the specified port\n");
5408 printf("\t-d debuglevel set the debuglevel\n");
5409 printf("\t-l log basename. Basename for log/debug files\n");
5410 printf("\t-s services file. Filename of services file\n");
5411 printf("\t-P passive only\n");
5412 printf("\t-a overwrite log file, don't append\n");
5417 /****************************************************************************
5419 ****************************************************************************/
5420 int main(int argc,char *argv[])
5422 extern BOOL append_log;
5423 /* shall I run as a daemon */
5424 BOOL is_daemon = False;
5425 int port = SMB_PORT;
5427 extern char *optarg;
5429 #ifdef NEED_AUTH_PARAMETERS
5430 set_auth_parameters(argc,argv);
5441 pstrcpy(debugf,SMBLOGFILE);
5443 pstrcpy(remote_machine, "smb");
5445 setup_logging(argv[0],False);
5447 charset_initialise();
5449 /* make absolutely sure we run as root - to handle cases where people
5450 are crazy enough to have it setuid */
5460 fault_setup((void (*)(void *))exit_server);
5461 signal(SIGTERM , SIGNAL_CAST dflt_sig);
5463 /* we want total control over the permissions on created files,
5464 so set our umask to 0 */
5471 /* this is for people who can't start the program correctly */
5472 while (argc > 1 && (*argv[1] != '-'))
5478 while ((opt = getopt(argc, argv, "O:i:l:s:d:Dp:hPaf:")) != EOF)
5482 pstrcpy(user_socket_options,optarg);
5485 pstrcpy(scope,optarg);
5489 extern BOOL passive;
5494 pstrcpy(servicesf,optarg);
5497 pstrcpy(debugf,optarg);
5501 extern BOOL append_log;
5502 append_log = !append_log;
5512 DEBUGLEVEL = atoi(optarg);
5515 port = atoi(optarg);
5528 DEBUG(2,("%s smbd version %s started\n",timestring(),VERSION));
5529 DEBUG(2,("Copyright Andrew Tridgell 1992-1997\n"));
5531 #ifndef NO_GETRLIMIT
5532 #ifdef RLIMIT_NOFILE
5535 getrlimit(RLIMIT_NOFILE, &rlp);
5537 * Set the fd limit to be MAX_OPEN_FILES + 10 to account for the
5538 * extra fd we need to read directories, as well as the log files
5539 * and standard handles etc.
5541 rlp.rlim_cur = (MAX_OPEN_FILES+10>rlp.rlim_max)? rlp.rlim_max:MAX_OPEN_FILES+10;
5542 setrlimit(RLIMIT_NOFILE, &rlp);
5543 getrlimit(RLIMIT_NOFILE, &rlp);
5544 DEBUG(3,("Maximum number of open files per session is %d\n",rlp.rlim_cur));
5550 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
5551 getuid(),getgid(),geteuid(),getegid()));
5553 if (sizeof(uint16) < 2 || sizeof(uint32) < 4)
5555 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
5561 if (!reload_services(False))
5566 extern BOOL sslEnabled;
5567 sslEnabled = lp_ssl_enabled();
5571 #endif /* USE_SSL */
5573 codepage_initialise(lp_client_code_page());
5575 pstrcpy(global_myworkgroup, lp_workgroup());
5577 if(!pdb_generate_machine_sid())
5579 DEBUG(0,("ERROR: Samba cannot get a machine SID.\n"));
5583 #ifndef NO_SIGNAL_TEST
5584 signal(SIGHUP,SIGNAL_CAST sig_hup);
5587 /* Setup the signals that allow the debug log level
5588 to by dynamically changed. */
5590 /* If we are using the malloc debug code we can't use
5591 SIGUSR1 and SIGUSR2 to do debug level changes. */
5594 #if defined(SIGUSR1)
5595 signal( SIGUSR1, SIGNAL_CAST sig_usr1 );
5596 #endif /* SIGUSR1 */
5598 #if defined(SIGUSR2)
5599 signal( SIGUSR2, SIGNAL_CAST sig_usr2 );
5600 #endif /* SIGUSR2 */
5601 #endif /* MEM_MAN */
5603 DEBUG(3,("%s loaded services\n",timestring()));
5605 if (!is_daemon && !is_a_socket(0))
5607 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
5613 DEBUG(3,("%s becoming a daemon\n",timestring()));
5617 if (!directory_exist(lp_lockdir(), NULL)) {
5618 mkdir(lp_lockdir(), 0755);
5622 pidfile_create("smbd");
5625 if (!open_sockets(is_daemon,port))
5628 if (!locking_init(0))
5631 if(!initialize_password_db())
5634 /* possibly reload the services file. */
5635 reload_services(True);
5637 max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
5641 if (sys_chroot(lp_rootdir()) == 0)
5642 DEBUG(2,("%s changed root to %s\n",timestring(),lp_rootdir()));
5645 /* Setup the oplock IPC socket. */
5646 if(!open_oplock_ipc())
5652 exit_server("normal exit");