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;
37 /* the last message the was processed */
38 int last_message = -1;
40 /* a useful macro to debug the last message processed */
41 #define LAST_MESSAGE() smb_fn_name(last_message)
44 extern int DEBUGLEVEL;
45 extern int case_default;
46 extern BOOL case_sensitive;
47 extern BOOL case_preserve;
48 extern BOOL use_mangled_map;
49 extern BOOL short_case_preserve;
50 extern BOOL case_mangle;
51 time_t smb_last_time=(time_t)0;
52 extern BOOL global_machine_pasword_needs_changing;
54 extern int smb_read_error;
56 extern pstring user_socket_options;
59 extern int dcelogin_atmost_once;
63 * This is set on startup - it defines the SID for this
66 extern DOM_SID global_machine_sid;
68 static connection_struct Connections[MAX_CONNECTIONS];
73 * Size of data we can send to client. Set
74 * by the client for all protocols above CORE.
75 * Set by us for CORE protocol.
77 int max_send = BUFFER_SIZE;
79 * Size of the data we can receive. Set by us.
80 * Can be modified by the max xmit parameter.
82 int max_recv = BUFFER_SIZE;
84 /* a fsp to use when chaining */
85 files_struct *chain_fsp = NULL;
87 /* number of open connections */
88 static int num_connections_open = 0;
90 /* Oplock ipc UDP socket. */
92 uint16 oplock_port = 0;
93 /* Current number of oplocks we have outstanding. */
94 int32 global_oplocks_open = 0;
96 BOOL global_oplock_break = False;
98 extern fstring remote_machine;
100 extern pstring OriginalDir;
102 /* these can be set by some functions to override the error codes */
103 int unix_ERR_class=SMB_SUCCESS;
107 extern int extra_time_offset;
109 extern pstring myhostname;
111 /* for readability... */
112 #define IS_DOS_READONLY(test_mode) (((test_mode) & aRONLY) != 0)
113 #define IS_DOS_DIR(test_mode) (((test_mode) & aDIR) != 0)
114 #define IS_DOS_ARCHIVE(test_mode) (((test_mode) & aARCH) != 0)
115 #define IS_DOS_SYSTEM(test_mode) (((test_mode) & aSYSTEM) != 0)
116 #define IS_DOS_HIDDEN(test_mode) (((test_mode) & aHIDDEN) != 0)
118 /****************************************************************************
119 when exiting, take the whole family
120 ****************************************************************************/
123 exit_server("caught signal");
124 return 0; /* Keep -Wall happy :-) */
126 /****************************************************************************
127 Send a SIGTERM to our process group.
128 *****************************************************************************/
131 if(am_parent) kill(0,SIGTERM);
134 /****************************************************************************
135 change a dos mode to a unix mode
136 base permission for files:
137 everybody gets read bit set
138 dos readonly is represented in unix by removing everyone's write bit
139 dos archive is represented in unix by the user's execute bit
140 dos system is represented in unix by the group's execute bit
141 dos hidden is represented in unix by the other's execute bit
142 Then apply create mask,
144 base permission for directories:
145 dos directory is represented in unix by unix's dir bit and the exec bit
146 Then apply create mask,
148 ****************************************************************************/
149 mode_t unix_mode(connection_struct *conn,int dosmode)
151 mode_t result = (S_IRUSR | S_IRGRP | S_IROTH);
153 if ( !IS_DOS_READONLY(dosmode) )
154 result |= (S_IWUSR | S_IWGRP | S_IWOTH);
156 if (IS_DOS_DIR(dosmode)) {
157 /* We never make directories read only for the owner as under DOS a user
158 can always create a file in a read-only directory. */
159 result |= (S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH | S_IWUSR);
160 /* Apply directory mask */
161 result &= lp_dir_mode(SNUM(conn));
162 /* Add in force bits */
163 result |= lp_force_dir_mode(SNUM(conn));
165 if (lp_map_archive(SNUM(conn)) && IS_DOS_ARCHIVE(dosmode))
168 if (lp_map_system(SNUM(conn)) && IS_DOS_SYSTEM(dosmode))
171 if (lp_map_hidden(SNUM(conn)) && IS_DOS_HIDDEN(dosmode))
174 /* Apply mode mask */
175 result &= lp_create_mode(SNUM(conn));
176 /* Add in force bits */
177 result |= lp_force_create_mode(SNUM(conn));
183 /****************************************************************************
184 change a unix mode to a dos mode
185 ****************************************************************************/
186 int dos_mode(connection_struct *conn,char *path,struct stat *sbuf)
189 extern struct current_user current_user;
191 DEBUG(8,("dos_mode: %s\n", path));
193 if (CAN_WRITE(conn) && !lp_alternate_permissions(SNUM(conn))) {
194 if (!((sbuf->st_mode & S_IWOTH) ||
196 ((sbuf->st_mode & S_IWUSR) && current_user.uid==sbuf->st_uid) ||
197 ((sbuf->st_mode & S_IWGRP) &&
198 in_group(sbuf->st_gid,current_user.gid,
199 current_user.ngroups,current_user.groups))))
202 if ((sbuf->st_mode & S_IWUSR) == 0)
206 if (MAP_ARCHIVE(conn) && ((sbuf->st_mode & S_IXUSR) != 0))
209 if (MAP_SYSTEM(conn) && ((sbuf->st_mode & S_IXGRP) != 0))
212 if (MAP_HIDDEN(conn) && ((sbuf->st_mode & S_IXOTH) != 0))
215 if (S_ISDIR(sbuf->st_mode))
216 result = aDIR | (result & aRONLY);
220 if (S_ISLNK(sbuf->st_mode) && S_ISDIR(sbuf->st_mode))
225 /* hide files with a name starting with a . */
226 if (lp_hide_dot_files(SNUM(conn)))
228 char *p = strrchr(path,'/');
234 if (p[0] == '.' && p[1] != '.' && p[1] != 0)
238 /* Optimization : Only call is_hidden_path if it's not already
240 if (!(result & aHIDDEN) && IS_HIDDEN_PATH(conn,path))
245 DEBUG(8,("dos_mode returning "));
247 if (result & aHIDDEN) DEBUG(8, ("h"));
248 if (result & aRONLY ) DEBUG(8, ("r"));
249 if (result & aSYSTEM) DEBUG(8, ("s"));
250 if (result & aDIR ) DEBUG(8, ("d"));
251 if (result & aARCH ) DEBUG(8, ("a"));
258 /*******************************************************************
259 chmod a file - but preserve some bits
260 ********************************************************************/
261 int dos_chmod(connection_struct *conn,char *fname,int dosmode,struct stat *st)
270 if (sys_stat(fname,st)) return(-1);
273 if (S_ISDIR(st->st_mode)) dosmode |= aDIR;
275 if (dos_mode(conn,fname,st) == dosmode) return(0);
277 unixmode = unix_mode(conn,dosmode);
279 /* preserve the s bits */
280 mask |= (S_ISUID | S_ISGID);
282 /* preserve the t bit */
287 /* possibly preserve the x bits */
288 if (!MAP_ARCHIVE(conn)) mask |= S_IXUSR;
289 if (!MAP_SYSTEM(conn)) mask |= S_IXGRP;
290 if (!MAP_HIDDEN(conn)) mask |= S_IXOTH;
292 unixmode |= (st->st_mode & mask);
294 /* if we previously had any r bits set then leave them alone */
295 if ((tmp = st->st_mode & (S_IRUSR|S_IRGRP|S_IROTH))) {
296 unixmode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
300 /* if we previously had any w bits set then leave them alone
301 if the new mode is not rdonly */
302 if (!IS_DOS_READONLY(dosmode) &&
303 (tmp = st->st_mode & (S_IWUSR|S_IWGRP|S_IWOTH))) {
304 unixmode &= ~(S_IWUSR|S_IWGRP|S_IWOTH);
308 return(sys_chmod(fname,unixmode));
311 /*******************************************************************
312 Wrapper around sys_utime that possibly allows DOS semantics rather
314 *******************************************************************/
316 int file_utime(connection_struct *conn, char *fname, struct utimbuf *times)
318 extern struct current_user current_user;
324 if(sys_utime(fname, times) == 0)
327 if((errno != EPERM) && (errno != EACCES))
330 if(!lp_dos_filetimes(SNUM(conn)))
333 /* We have permission (given by the Samba admin) to
334 break POSIX semantics and allow a user to change
335 the time on a file they don't own but can write to
339 if(sys_stat(fname,&sb) != 0)
342 /* Check if we have write access. */
343 if (CAN_WRITE(conn)) {
344 if (((sb.st_mode & S_IWOTH) ||
346 ((sb.st_mode & S_IWUSR) && current_user.uid==sb.st_uid) ||
347 ((sb.st_mode & S_IWGRP) &&
348 in_group(sb.st_gid,current_user.gid,
349 current_user.ngroups,current_user.groups)))) {
350 /* We are allowed to become root and change the filetime. */
352 ret = sys_utime(fname, times);
353 unbecome_root(False);
360 /*******************************************************************
361 Change a filetime - possibly allowing DOS semantics.
362 *******************************************************************/
364 BOOL set_filetime(connection_struct *conn, char *fname, time_t mtime)
366 struct utimbuf times;
368 if (null_mtime(mtime)) return(True);
370 times.modtime = times.actime = mtime;
372 if (file_utime(conn, fname, ×)) {
373 DEBUG(4,("set_filetime(%s) failed: %s\n",fname,strerror(errno)));
379 /****************************************************************************
380 check if two filenames are equal
382 this needs to be careful about whether we are case sensitive
383 ****************************************************************************/
384 static BOOL fname_equal(char *name1, char *name2)
386 int l1 = strlen(name1);
387 int l2 = strlen(name2);
389 /* handle filenames ending in a single dot */
390 if (l1-l2 == 1 && name1[l1-1] == '.' && lp_strip_dot())
394 ret = fname_equal(name1,name2);
399 if (l2-l1 == 1 && name2[l2-1] == '.' && lp_strip_dot())
403 ret = fname_equal(name1,name2);
408 /* now normal filename handling */
410 return(strcmp(name1,name2) == 0);
412 return(strequal(name1,name2));
416 /****************************************************************************
417 mangle the 2nd name and check if it is then equal to the first name
418 ****************************************************************************/
419 static BOOL mangled_equal(char *name1, char *name2)
423 if (is_8_3(name2, True))
426 pstrcpy(tmpname,name2);
427 mangle_name_83(tmpname,sizeof(tmpname));
429 return(strequal(name1,tmpname));
433 /****************************************************************************
434 scan a directory to find a filename, matching without case sensitivity
436 If the name looks like a mangled name then try via the mangling functions
437 ****************************************************************************/
438 static BOOL scan_directory(char *path, char *name,connection_struct *conn,BOOL docache)
445 mangled = is_mangled(name);
447 /* handle null paths */
451 if (docache && (dname = DirCacheCheck(path,name,SNUM(conn)))) {
452 pstrcpy(name, dname);
457 * The incoming name can be mangled, and if we de-mangle it
458 * here it will not compare correctly against the filename (name2)
459 * read from the directory and then mangled by the name_map_mangle()
460 * call. We need to mangle both names or neither.
464 mangled = !check_mangled_cache( name );
466 /* open the directory */
467 if (!(cur_dir = OpenDir(conn, path, True)))
469 DEBUG(3,("scan dir didn't open dir [%s]\n",path));
473 /* now scan for matching names */
474 while ((dname = ReadDirName(cur_dir)))
477 (strequal(dname,".") || strequal(dname,"..")))
480 pstrcpy(name2,dname);
481 if (!name_map_mangle(name2,False,SNUM(conn))) continue;
483 if ((mangled && mangled_equal(name,name2))
484 || fname_equal(name, name2))
486 /* we've found the file, change it's name and return */
487 if (docache) DirCacheAdd(path,name,dname,SNUM(conn));
488 pstrcpy(name, dname);
498 /****************************************************************************
499 This routine is called to convert names from the dos namespace to unix
500 namespace. It needs to handle any case conversions, mangling, format
503 We assume that we have already done a chdir() to the right "root" directory
506 The function will return False if some part of the name except for the last
507 part cannot be resolved
509 If the saved_last_component != 0, then the unmodified last component
510 of the pathname is returned there. This is used in an exceptional
511 case in reply_mv (so far). If saved_last_component == 0 then nothing
514 The bad_path arg is set to True if the filename walk failed. This is
515 used to pick the correct error code to return between ENOENT and ENOTDIR
516 as Windows applications depend on ERRbadpath being returned if a component
517 of a pathname does not exist.
518 ****************************************************************************/
519 BOOL unix_convert(char *name,connection_struct *conn,char *saved_last_component, BOOL *bad_path)
529 if(saved_last_component)
530 *saved_last_component = 0;
532 /* convert to basic unix format - removing \ chars and cleaning it up */
534 unix_clean_name(name);
536 /* names must be relative to the root of the service - trim any leading /.
537 also trim trailing /'s */
538 trim_string(name,"/","/");
541 * Ensure saved_last_component is valid even if file exists.
543 if(saved_last_component) {
544 end = strrchr(name, '/');
546 pstrcpy(saved_last_component, end + 1);
548 pstrcpy(saved_last_component, name);
551 if (!case_sensitive &&
552 (!case_preserve || (is_8_3(name, False) && !short_case_preserve)))
555 /* check if it's a printer file */
558 if ((! *name) || strchr(name,'/') || !is_8_3(name, True))
562 slprintf(name2,sizeof(name2)-1,"%.6s.XXXXXX",remote_machine);
563 /* sanitise the name */
564 for (s=name2 ; *s ; s++)
565 if (!issafe(*s)) *s = '_';
566 pstrcpy(name,(char *)mktemp(name2));
571 /* stat the name - if it exists then we are all done! */
572 if (sys_stat(name,&st) == 0)
577 DEBUG(5,("unix_convert(%s)\n",name));
579 /* a special case - if we don't have any mangling chars and are case
580 sensitive then searching won't help */
581 if (case_sensitive && !is_mangled(name) &&
582 !lp_strip_dot() && !use_mangled_map && (saved_errno != ENOENT))
585 /* now we need to recursively match the name against the real
586 directory structure */
589 while (strncmp(start,"./",2) == 0)
592 /* now match each part of the path name separately, trying the names
593 as is first, then trying to scan the directory for matching names */
594 for (;start;start = (end?end+1:(char *)NULL))
596 /* pinpoint the end of this section of the filename */
597 end = strchr(start, '/');
599 /* chop the name at this point */
602 if(saved_last_component != 0)
603 pstrcpy(saved_last_component, end ? end + 1 : start);
605 /* check if the name exists up to this point */
606 if (sys_stat(name, &st) == 0)
608 /* it exists. it must either be a directory or this must be
609 the last part of the path for it to be OK */
610 if (end && !(st.st_mode & S_IFDIR))
612 /* an intermediate part of the name isn't a directory */
613 DEBUG(5,("Not a dir %s\n",start));
624 /* remember the rest of the pathname so it can be restored
626 if (end) pstrcpy(rest,end+1);
628 /* try to find this part of the path in the directory */
629 if (strchr(start,'?') || strchr(start,'*') ||
630 !scan_directory(dirpath, start, conn, end?True:False))
634 /* an intermediate part of the name can't be found */
635 DEBUG(5,("Intermediate not found %s\n",start));
637 /* We need to return the fact that the intermediate
638 name resolution failed. This is used to return an
639 error of ERRbadpath rather than ERRbadfile. Some
640 Windows applications depend on the difference between
647 /* just the last part of the name doesn't exist */
648 /* we may need to strupper() or strlower() it in case
649 this conversion is being used for file creation
651 /* if the filename is of mixed case then don't normalise it */
652 if (!case_preserve &&
653 (!strhasupper(start) || !strhaslower(start)))
656 /* check on the mangled stack to see if we can recover the
657 base of the filename */
658 if (is_mangled(start))
659 check_mangled_cache( start );
661 DEBUG(5,("New file %s\n",start));
665 /* restore the rest of the string */
668 pstrcpy(start+strlen(start)+1,rest);
669 end = start + strlen(start);
673 /* add to the dirpath that we have resolved so far */
674 if (*dirpath) pstrcat(dirpath,"/");
675 pstrcat(dirpath,start);
677 /* restore the / that we wiped out earlier */
681 /* the name has been resolved */
682 DEBUG(5,("conversion finished %s\n",name));
687 /****************************************************************************
688 check a filename - possibly caling reducename
690 This is called by every routine before it allows an operation on a filename.
691 It does any final confirmation necessary to ensure that the filename is
692 a valid one for the user to access.
693 ****************************************************************************/
694 BOOL check_name(char *name,connection_struct *conn)
700 if (IS_VETO_PATH(conn, name)) {
701 DEBUG(5,("file path name %s vetoed\n",name));
705 ret = reduce_name(name,conn->connectpath,lp_widelinks(SNUM(conn)));
707 /* Check if we are allowing users to follow symlinks */
708 /* Patch from David Clerc <David.Clerc@cui.unige.ch>
709 University of Geneva */
712 if (!lp_symlinks(SNUM(conn)))
715 if ( (sys_lstat(name,&statbuf) != -1) &&
716 (S_ISLNK(statbuf.st_mode)) )
718 DEBUG(3,("check_name: denied: file path name %s is a symlink\n",name));
725 DEBUG(5,("check_name on %s failed\n",name));
730 /****************************************************************************
731 check a filename - possibly caling reducename
732 ****************************************************************************/
733 static void check_for_pipe(char *fname)
735 /* special case of pipe opens */
739 if (strstr(s,"pipe/"))
741 DEBUG(3,("Rejecting named pipe open for %s\n",fname));
742 unix_ERR_class = ERRSRV;
743 unix_ERR_code = ERRaccess;
747 /****************************************************************************
748 fd support routines - attempt to do a sys_open
749 ****************************************************************************/
750 static int fd_attempt_open(char *fname, int flags, int mode)
752 int fd = sys_open(fname,flags,mode);
754 /* Fix for files ending in '.' */
755 if((fd == -1) && (errno == ENOENT) &&
756 (strchr(fname,'.')==NULL))
759 fd = sys_open(fname,flags,mode);
762 #if (defined(ENAMETOOLONG) && defined(HAVE_PATHCONF))
763 if ((fd == -1) && (errno == ENAMETOOLONG))
766 char *p = strrchr(fname, '/');
768 if (p == fname) /* name is "/xxx" */
770 max_len = pathconf("/", _PC_NAME_MAX);
773 else if ((p == NULL) || (p == fname))
776 max_len = pathconf(".", _PC_NAME_MAX);
781 max_len = pathconf(fname, _PC_NAME_MAX);
785 if (strlen(p) > max_len)
787 char tmp = p[max_len];
790 if ((fd = sys_open(fname,flags,mode)) == -1)
798 /****************************************************************************
799 Cache a uid_t currently with this file open. This is an optimization only
800 used when multiple sessionsetup's have been done to one smbd.
801 ****************************************************************************/
802 void fd_add_to_uid_cache(file_fd_struct *fd_ptr, uid_t u)
804 if(fd_ptr->uid_cache_count >= sizeof(fd_ptr->uid_users_cache)/sizeof(uid_t))
806 fd_ptr->uid_users_cache[fd_ptr->uid_cache_count++] = u;
809 /****************************************************************************
810 Remove a uid_t that currently has this file open. This is an optimization only
811 used when multiple sessionsetup's have been done to one smbd.
812 ****************************************************************************/
813 static void fd_remove_from_uid_cache(file_fd_struct *fd_ptr, uid_t u)
816 for(i = 0; i < fd_ptr->uid_cache_count; i++)
817 if(fd_ptr->uid_users_cache[i] == u) {
818 if(i < (fd_ptr->uid_cache_count-1))
819 memmove((char *)&fd_ptr->uid_users_cache[i], (char *)&fd_ptr->uid_users_cache[i+1],
820 sizeof(uid_t)*(fd_ptr->uid_cache_count-1-i) );
821 fd_ptr->uid_cache_count--;
826 /****************************************************************************
827 Check if a uid_t that currently has this file open is present. This is an
828 optimization only used when multiple sessionsetup's have been done to one smbd.
829 ****************************************************************************/
830 static BOOL fd_is_in_uid_cache(file_fd_struct *fd_ptr, uid_t u)
833 for(i = 0; i < fd_ptr->uid_cache_count; i++)
834 if(fd_ptr->uid_users_cache[i] == u)
840 /****************************************************************************
841 fd support routines - attempt to re-open an already open fd as O_RDWR.
842 Save the already open fd (we cannot close due to POSIX file locking braindamage.
843 ****************************************************************************/
844 static void fd_attempt_reopen(char *fname, int mode, file_fd_struct *fd_ptr)
846 int fd = sys_open( fname, O_RDWR, mode);
851 if(fd_ptr->real_open_flags == O_RDONLY)
852 fd_ptr->fd_readonly = fd_ptr->fd;
853 if(fd_ptr->real_open_flags == O_WRONLY)
854 fd_ptr->fd_writeonly = fd_ptr->fd;
857 fd_ptr->real_open_flags = O_RDWR;
860 /****************************************************************************
861 fd support routines - attempt to close the file referenced by this fd.
862 Decrements the ref_count and returns it.
863 ****************************************************************************/
864 static int fd_attempt_close(file_fd_struct *fd_ptr)
866 extern struct current_user current_user;
868 DEBUG(3,("fd_attempt_close fd = %d, dev = %x, inode = %x, open_flags = %d, ref_count = %d.\n",
869 fd_ptr->fd, fd_ptr->dev, fd_ptr->inode,
870 fd_ptr->real_open_flags,
872 if(fd_ptr->ref_count > 0) {
874 if(fd_ptr->ref_count == 0) {
877 if(fd_ptr->fd_readonly != -1)
878 close(fd_ptr->fd_readonly);
879 if(fd_ptr->fd_writeonly != -1)
880 close(fd_ptr->fd_writeonly);
882 fd_ptr->fd_readonly = -1;
883 fd_ptr->fd_writeonly = -1;
884 fd_ptr->real_open_flags = -1;
885 fd_ptr->dev = (uint32)-1;
886 fd_ptr->inode = (uint32)-1;
887 fd_ptr->uid_cache_count = 0;
889 fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
891 return fd_ptr->ref_count;
894 /****************************************************************************
895 fd support routines - check that current user has permissions
896 to open this file. Used when uid not found in optimization cache.
897 This is really ugly code, as due to POSIX locking braindamage we must
898 fork and then attempt to open the file, and return success or failure
900 ****************************************************************************/
901 static BOOL check_access_allowed_for_current_user( char *fname, int accmode )
905 if((child_pid = fork()) < 0) {
906 DEBUG(0,("check_access_allowed_for_current_user: fork failed.\n"));
916 if ((wpid = sys_waitpid(child_pid, &status_code, 0)) < 0) {
917 DEBUG(0,("check_access_allowed_for_current_user: The process is no longer waiting!\n"));
921 if (child_pid != wpid) {
922 DEBUG(0,("check_access_allowed_for_current_user: We were waiting for the wrong process ID\n"));
925 #if defined(WIFEXITED) && defined(WEXITSTATUS)
926 if (WIFEXITED(status_code) == 0) {
927 DEBUG(0,("check_access_allowed_for_current_user: The process exited while we were waiting\n"));
930 if (WEXITSTATUS(status_code) != 0) {
931 DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access denied.\n", status_code));
934 #else /* defined(WIFEXITED) && defined(WEXITSTATUS) */
935 if(status_code != 0) {
936 DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access denied.\n", status_code));
939 #endif /* defined(WIFEXITED) && defined(WEXITSTATUS) */
942 * Success - the child could open the file.
944 DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access allowed.\n", status_code));
951 DEBUG(9,("check_access_allowed_for_current_user: Child - attempting to open %s with mode %d.\n", fname, accmode ));
952 if((fd = fd_attempt_open( fname, accmode, 0)) < 0) {
957 DEBUG(9,("check_access_allowed_for_current_user: Child - returning ok.\n"));
964 /****************************************************************************
966 ****************************************************************************/
967 static void open_file(files_struct *fsp,connection_struct *conn,
968 char *fname1,int flags,int mode, struct stat *sbuf)
970 extern struct current_user current_user;
973 file_fd_struct *fd_ptr;
974 int accmode = (flags & (O_RDONLY | O_WRONLY | O_RDWR));
978 fsp->granted_oplock = False;
981 pstrcpy(fname,fname1);
983 /* check permissions */
986 * This code was changed after seeing a client open request
987 * containing the open mode of (DENY_WRITE/read-only) with
988 * the 'create if not exist' bit set. The previous code
989 * would fail to open the file read only on a read-only share
990 * as it was checking the flags parameter directly against O_RDONLY,
991 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
995 if (conn->read_only && !conn->printer) {
996 /* It's a read-only share - fail if we wanted to write. */
997 if(accmode != O_RDONLY) {
998 DEBUG(3,("Permission denied opening %s\n",fname));
999 check_for_pipe(fname);
1001 } else if(flags & O_CREAT) {
1002 /* We don't want to write - but we must make sure that O_CREAT
1003 doesn't create the file if we have write access into the
1010 /* this handles a bug in Win95 - it doesn't say to create the file when it
1012 if (conn->printer) {
1017 if (flags == O_WRONLY)
1018 DEBUG(3,("Bug in client? Set O_WRONLY without O_CREAT\n"));
1022 * Ensure we have a valid struct stat so we can search the
1026 if(sys_stat(fname, &statbuf) < 0) {
1027 if(errno != ENOENT) {
1028 DEBUG(3,("Error doing stat on file %s (%s)\n",
1029 fname,strerror(errno)));
1031 check_for_pipe(fname);
1041 * Check to see if we have this file already
1042 * open. If we do, just use the already open fd and increment the
1043 * reference count (fd_get_already_open increments the ref_count).
1045 if((fd_ptr = fd_get_already_open(sbuf))!= 0) {
1047 * File was already open.
1051 * Check it wasn't open for exclusive use.
1053 if((flags & O_CREAT) && (flags & O_EXCL)) {
1054 fd_ptr->ref_count--;
1060 * Ensure that the user attempting to open
1061 * this file has permissions to do so, if
1062 * the user who originally opened the file wasn't
1063 * the same as the current user.
1066 if(!fd_is_in_uid_cache(fd_ptr, (uid_t)current_user.uid)) {
1067 if(!check_access_allowed_for_current_user( fname, accmode )) {
1068 /* Error - permission denied. */
1069 DEBUG(3,("Permission denied opening file %s (flags=%d, accmode = %d)\n",
1070 fname, flags, accmode));
1071 /* Ensure the ref_count is decremented. */
1072 fd_ptr->ref_count--;
1073 fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
1079 fd_add_to_uid_cache(fd_ptr, (uid_t)current_user.uid);
1082 * If not opened O_RDWR try
1083 * and do that here - a chmod may have been done
1084 * between the last open and now.
1086 if(fd_ptr->real_open_flags != O_RDWR)
1087 fd_attempt_reopen(fname, mode, fd_ptr);
1090 * Ensure that if we wanted write access
1091 * it has been opened for write, and if we wanted read it
1092 * was open for read.
1094 if(((accmode == O_WRONLY) && (fd_ptr->real_open_flags == O_RDONLY)) ||
1095 ((accmode == O_RDONLY) && (fd_ptr->real_open_flags == O_WRONLY)) ||
1096 ((accmode == O_RDWR) && (fd_ptr->real_open_flags != O_RDWR))) {
1097 DEBUG(3,("Error opening (already open for flags=%d) file %s (%s) (flags=%d)\n",
1098 fd_ptr->real_open_flags, fname,strerror(EACCES),flags));
1099 check_for_pipe(fname);
1100 fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
1101 fd_ptr->ref_count--;
1107 /* We need to allocate a new file_fd_struct (this increments the
1109 if((fd_ptr = fd_get_new()) == 0)
1112 * Whatever the requested flags, attempt read/write access,
1113 * as we don't know what flags future file opens may require.
1114 * If this fails, try again with the required flags.
1115 * Even if we open read/write when only read access was
1116 * requested the setting of the can_write flag in
1117 * the file_struct will protect us from errant
1118 * write requests. We never need to worry about O_APPEND
1119 * as this is not set anywhere in Samba.
1121 fd_ptr->real_open_flags = O_RDWR;
1122 /* Set the flags as needed without the read/write modes. */
1123 open_flags = flags & ~(O_RDWR|O_WRONLY|O_RDONLY);
1124 fd_ptr->fd = fd_attempt_open(fname, open_flags|O_RDWR, mode);
1126 * On some systems opening a file for R/W access on a read only
1127 * filesystems sets errno to EROFS.
1130 if((fd_ptr->fd == -1) && ((errno == EACCES) || (errno == EROFS))) {
1131 #else /* No EROFS */
1132 if((fd_ptr->fd == -1) && (errno == EACCES)) {
1134 if(accmode != O_RDWR) {
1135 fd_ptr->fd = fd_attempt_open(fname, open_flags|accmode, mode);
1136 fd_ptr->real_open_flags = accmode;
1141 if ((fd_ptr->fd >=0) &&
1142 conn->printer && lp_minprintspace(SNUM(conn))) {
1146 pstrcpy(dname,fname);
1147 p = strrchr(dname,'/');
1149 if (sys_disk_free(dname,&dum1,&dum2,&dum3) <
1150 lp_minprintspace(SNUM(conn))) {
1151 fd_attempt_close(fd_ptr);
1153 if(fd_ptr->ref_count == 0)
1162 DEBUG(3,("Error opening file %s (%s) (flags=%d)\n",
1163 fname,strerror(errno),flags));
1164 /* Ensure the ref_count is decremented. */
1165 fd_attempt_close(fd_ptr);
1166 check_for_pipe(fname);
1170 if (fd_ptr->fd >= 0)
1174 if(fstat(fd_ptr->fd, &statbuf) == -1) {
1175 /* Error - backout !! */
1176 DEBUG(3,("Error doing fstat on fd %d, file %s (%s)\n",
1177 fd_ptr->fd, fname,strerror(errno)));
1178 /* Ensure the ref_count is decremented. */
1179 fd_attempt_close(fd_ptr);
1185 /* Set the correct entries in fd_ptr. */
1186 fd_ptr->dev = (uint32)sbuf->st_dev;
1187 fd_ptr->inode = (uint32)sbuf->st_ino;
1189 fsp->fd_ptr = fd_ptr;
1190 conn->num_files_open++;
1191 fsp->mode = sbuf->st_mode;
1192 GetTimeOfDay(&fsp->open_time);
1193 fsp->vuid = current_user.vuid;
1197 fsp->mmap_ptr = NULL;
1199 fsp->can_lock = True;
1200 fsp->can_read = ((flags & O_WRONLY)==0);
1201 fsp->can_write = ((flags & (O_WRONLY|O_RDWR))!=0);
1202 fsp->share_mode = 0;
1203 fsp->print_file = conn->printer;
1204 fsp->modified = False;
1205 fsp->granted_oplock = False;
1206 fsp->sent_oplock_break = False;
1207 fsp->is_directory = False;
1210 * Note that the file name here is the *untranslated* name
1211 * ie. it is still in the DOS codepage sent from the client.
1212 * All use of this filename will pass though the sys_xxxx
1213 * functions which will do the dos_to_unix translation before
1214 * mapping into a UNIX filename. JRA.
1216 string_set(&fsp->fsp_name,fname);
1217 fsp->wbmpx_ptr = NULL;
1220 * If the printer is marked as postscript output a leading
1221 * file identifier to ensure the file is treated as a raw
1223 * This has a similar effect as CtrlD=0 in WIN.INI file.
1224 * tim@fsg.com 09/06/94
1226 if (fsp->print_file && lp_postscript(SNUM(conn)) && fsp->can_write) {
1227 DEBUG(3,("Writing postscript line\n"));
1228 write_file(fsp,"%!\n",3);
1231 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1232 *sesssetup_user ? sesssetup_user : conn->user,fname,
1233 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1234 conn->num_files_open));
1239 /* mmap it if read-only */
1240 if (!fsp->can_write) {
1241 fsp->mmap_size = file_size(fname);
1242 fsp->mmap_ptr = (char *)mmap(NULL,fsp->mmap_size,
1243 PROT_READ,MAP_SHARED,fsp->fd_ptr->fd,0);
1245 if (fsp->mmap_ptr == (char *)-1 || !fsp->mmap_ptr) {
1246 DEBUG(3,("Failed to mmap() %s - %s\n",
1247 fname,strerror(errno)));
1248 fsp->mmap_ptr = NULL;
1254 /*******************************************************************
1256 ********************************************************************/
1257 void sync_file(connection_struct *conn, files_struct *fsp)
1260 if(lp_strict_sync(SNUM(conn)))
1261 fsync(fsp->fd_ptr->fd);
1265 /****************************************************************************
1266 run a file if it is a magic script
1267 ****************************************************************************/
1268 static void check_magic(files_struct *fsp,connection_struct *conn)
1270 if (!*lp_magicscript(SNUM(conn)))
1273 DEBUG(5,("checking magic for %s\n",fsp->fsp_name));
1277 if (!(p = strrchr(fsp->fsp_name,'/')))
1282 if (!strequal(lp_magicscript(SNUM(conn)),p))
1288 pstring magic_output;
1290 pstrcpy(fname,fsp->fsp_name);
1292 if (*lp_magicoutput(SNUM(conn)))
1293 pstrcpy(magic_output,lp_magicoutput(SNUM(conn)));
1295 slprintf(magic_output,sizeof(fname)-1, "%s.out",fname);
1298 ret = smbrun(fname,magic_output,False);
1299 DEBUG(3,("Invoking magic command %s gave %d\n",fname,ret));
1304 /****************************************************************************
1305 Common code to close a file or a directory.
1306 ****************************************************************************/
1307 static void close_filestruct(files_struct *fsp)
1309 connection_struct *conn = fsp->conn;
1313 fsp->is_directory = False;
1315 conn->num_files_open--;
1316 if(fsp->wbmpx_ptr) {
1317 free((char *)fsp->wbmpx_ptr);
1318 fsp->wbmpx_ptr = NULL;
1323 munmap(fsp->mmap_ptr,fsp->mmap_size);
1324 fsp->mmap_ptr = NULL;
1329 /****************************************************************************
1330 Close a file - possibly invalidating the read prediction.
1332 If normal_close is 1 then this came from a normal SMBclose (or equivalent)
1333 operation otherwise it came as the result of some other operation such as
1334 the closing of the connection. In the latter case printing and
1335 magic scripts are not run.
1336 ****************************************************************************/
1337 void close_file(files_struct *fsp, BOOL normal_close)
1339 uint32 dev = fsp->fd_ptr->dev;
1340 uint32 inode = fsp->fd_ptr->inode;
1342 connection_struct *conn = fsp->conn;
1344 close_filestruct(fsp);
1346 #if USE_READ_PREDICTION
1347 invalidate_read_prediction(fsp->fd_ptr->fd);
1350 if (lp_share_modes(SNUM(conn))) {
1351 lock_share_entry(conn, dev, inode, &token);
1352 del_share_mode(token, fsp);
1355 fd_attempt_close(fsp->fd_ptr);
1357 if (lp_share_modes(SNUM(conn)))
1358 unlock_share_entry(conn, dev, inode, token);
1360 /* NT uses smbclose to start a print - weird */
1361 if (normal_close && fsp->print_file)
1362 print_file(conn, fsp);
1364 /* check for magic scripts */
1366 check_magic(fsp,conn);
1369 if(fsp->granted_oplock == True)
1370 global_oplocks_open--;
1372 fsp->sent_oplock_break = False;
1374 DEBUG(2,("%s closed file %s (numopen=%d)\n",
1375 conn->user,fsp->fsp_name,
1376 conn->num_files_open));
1378 if (fsp->fsp_name) {
1379 string_free(&fsp->fsp_name);
1385 /****************************************************************************
1386 Close a directory opened by an NT SMB call.
1387 ****************************************************************************/
1389 void close_directory(files_struct *fsp)
1392 /* TODO - walk the list of pending
1393 change notify requests and free
1394 any pertaining to this fsp. */
1396 remove_pending_change_notify_requests_by_fid(fsp);
1399 * Do the code common to files and directories.
1401 close_filestruct(fsp);
1404 string_free(&fsp->fsp_name);
1409 /****************************************************************************
1410 Open a directory from an NT SMB call.
1411 ****************************************************************************/
1412 int open_directory(files_struct *fsp,connection_struct *conn,
1413 char *fname, int smb_ofun, int unixmode, int *action)
1415 extern struct current_user current_user;
1418 if (smb_ofun & 0x10) {
1420 * Create the directory.
1423 if(sys_mkdir(fname, unixmode) < 0) {
1424 DEBUG(0,("open_directory: unable to create %s. Error was %s\n",
1425 fname, strerror(errno) ));
1429 *action = FILE_WAS_CREATED;
1432 * Check that it *was* a directory.
1435 if(sys_stat(fname, &st) < 0) {
1436 DEBUG(0,("open_directory: unable to stat name = %s. Error was %s\n",
1437 fname, strerror(errno) ));
1441 if(!S_ISDIR(st.st_mode)) {
1442 DEBUG(0,("open_directory: %s is not a directory !\n", fname ));
1445 *action = FILE_WAS_OPENED;
1448 DEBUG(5,("open_directory: opening directory %s\n",
1452 * Setup the files_struct for it.
1456 conn->num_files_open++;
1458 GetTimeOfDay(&fsp->open_time);
1459 fsp->vuid = current_user.vuid;
1463 fsp->mmap_ptr = NULL;
1465 fsp->can_lock = True;
1466 fsp->can_read = False;
1467 fsp->can_write = False;
1468 fsp->share_mode = 0;
1469 fsp->print_file = False;
1470 fsp->modified = False;
1471 fsp->granted_oplock = False;
1472 fsp->sent_oplock_break = False;
1473 fsp->is_directory = True;
1476 * Note that the file name here is the *untranslated* name
1477 * ie. it is still in the DOS codepage sent from the client.
1478 * All use of this filename will pass though the sys_xxxx
1479 * functions which will do the dos_to_unix translation before
1480 * mapping into a UNIX filename. JRA.
1482 string_set(&fsp->fsp_name,fname);
1483 fsp->wbmpx_ptr = NULL;
1488 enum {AFAIL,AREAD,AWRITE,AALL};
1490 /*******************************************************************
1491 reproduce the share mode access table
1492 ********************************************************************/
1493 static int access_table(int new_deny,int old_deny,int old_mode,
1494 int share_pid,char *fname)
1496 if (new_deny == DENY_ALL || old_deny == DENY_ALL) return(AFAIL);
1498 if (new_deny == DENY_DOS || old_deny == DENY_DOS) {
1500 if (old_deny == new_deny && share_pid == pid)
1503 if (old_mode == 0) return(AREAD);
1505 /* the new smbpub.zip spec says that if the file extension is
1506 .com, .dll, .exe or .sym then allow the open. I will force
1507 it to read-only as this seems sensible although the spec is
1508 a little unclear on this. */
1509 if ((fname = strrchr(fname,'.'))) {
1510 if (strequal(fname,".com") ||
1511 strequal(fname,".dll") ||
1512 strequal(fname,".exe") ||
1513 strequal(fname,".sym"))
1523 if (old_deny==DENY_WRITE && old_mode==0) return(AREAD);
1524 if (old_deny==DENY_READ && old_mode==0) return(AWRITE);
1525 if (old_deny==DENY_NONE && old_mode==0) return(AALL);
1528 if (old_deny==DENY_WRITE && old_mode==1) return(AREAD);
1529 if (old_deny==DENY_READ && old_mode==1) return(AWRITE);
1530 if (old_deny==DENY_NONE && old_mode==1) return(AALL);
1533 if (old_deny==DENY_WRITE) return(AREAD);
1534 if (old_deny==DENY_READ) return(AWRITE);
1535 if (old_deny==DENY_NONE) return(AALL);
1541 /*******************************************************************
1542 check if the share mode on a file allows it to be deleted or unlinked
1543 return True if sharing doesn't prevent the operation
1544 ********************************************************************/
1545 BOOL check_file_sharing(connection_struct *conn,char *fname, BOOL rename_op)
1549 share_mode_entry *old_shares = 0;
1550 int num_share_modes;
1556 if(!lp_share_modes(SNUM(conn)))
1559 if (sys_stat(fname,&sbuf) == -1) return(True);
1561 dev = (uint32)sbuf.st_dev;
1562 inode = (uint32)sbuf.st_ino;
1564 lock_share_entry(conn, dev, inode, &token);
1565 num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1568 * Check if the share modes will give us access.
1571 if(num_share_modes != 0)
1578 broke_oplock = False;
1579 for(i = 0; i < num_share_modes; i++)
1581 share_mode_entry *share_entry = &old_shares[i];
1584 * Break oplocks before checking share modes. See comment in
1585 * open_file_shared for details.
1586 * Check if someone has an oplock on this file. If so we must
1587 * break it before continuing.
1589 if(share_entry->op_type & BATCH_OPLOCK)
1593 * It appears that the NT redirector may have a bug, in that
1594 * it tries to do an SMBmv on a file that it has open with a
1595 * batch oplock, and then fails to respond to the oplock break
1596 * request. This only seems to occur when the client is doing an
1597 * SMBmv to the smbd it is using - thus we try and detect this
1598 * condition by checking if the file being moved is open and oplocked by
1599 * this smbd process, and then not sending the oplock break in this
1600 * special case. If the file was open with a deny mode that
1601 * prevents the move the SMBmv will fail anyway with a share
1602 * violation error. JRA.
1604 if(rename_op && (share_entry->pid == pid))
1606 DEBUG(0,("check_file_sharing: NT redirector workaround - rename attempted on \
1607 batch oplocked file %s, dev = %x, inode = %x\n", fname, dev, inode));
1609 * This next line is a test that allows the deny-mode
1610 * processing to be skipped. This seems to be needed as
1611 * NT insists on the rename succeeding (in Office 9x no less !).
1612 * This should be removed as soon as (a) MS fix the redirector
1613 * bug or (b) NT SMB support in Samba makes NT not issue the
1614 * call (as is my fervent hope). JRA.
1620 DEBUG(5,("check_file_sharing: breaking oplock (%x) on file %s, \
1621 dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
1623 /* Oplock break.... */
1624 unlock_share_entry(conn, dev, inode, token);
1625 if(request_oplock_break(share_entry, dev, inode) == False)
1627 free((char *)old_shares);
1628 DEBUG(0,("check_file_sharing: FAILED when breaking oplock (%x) on file %s, \
1629 dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
1632 lock_share_entry(conn, dev, inode, &token);
1633 broke_oplock = True;
1638 /* someone else has a share lock on it, check to see
1640 if ((share_entry->share_mode != DENY_DOS) || (share_entry->pid != pid))
1647 free((char *)old_shares);
1648 num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1650 } while(broke_oplock);
1653 /* XXXX exactly what share mode combinations should be allowed for
1654 deleting/renaming? */
1655 /* If we got here then either there were no share modes or
1656 all share modes were DENY_DOS and the pid == getpid() */
1661 unlock_share_entry(conn, dev, inode, token);
1662 if(old_shares != NULL)
1663 free((char *)old_shares);
1667 /****************************************************************************
1669 Helper for open_file_shared.
1670 Truncate a file after checking locking; close file if locked.
1671 **************************************************************************/
1672 static void truncate_unless_locked(files_struct *fsp, connection_struct *conn, int token,
1675 if (fsp->can_write){
1676 if (is_locked(fsp,conn,0x3FFFFFFF,0,F_WRLCK)){
1677 /* If share modes are in force for this connection we
1678 have the share entry locked. Unlock it before closing. */
1679 if (*share_locked && lp_share_modes(SNUM(conn)))
1680 unlock_share_entry( conn, fsp->fd_ptr->dev,
1681 fsp->fd_ptr->inode, token);
1682 close_file(fsp,False);
1683 /* Share mode no longer locked. */
1684 *share_locked = False;
1686 unix_ERR_class = ERRDOS;
1687 unix_ERR_code = ERRlock;
1690 ftruncate(fsp->fd_ptr->fd,0);
1694 /****************************************************************************
1695 check if we can open a file with a share mode
1696 ****************************************************************************/
1697 int check_share_mode( share_mode_entry *share, int deny_mode, char *fname,
1698 BOOL fcbopen, int *flags)
1700 int old_open_mode = share->share_mode &0xF;
1701 int old_deny_mode = (share->share_mode >>4)&7;
1703 if (old_deny_mode > 4 || old_open_mode > 2)
1705 DEBUG(0,("Invalid share mode found (%d,%d,%d) on file %s\n",
1706 deny_mode,old_deny_mode,old_open_mode,fname));
1711 int access_allowed = access_table(deny_mode,old_deny_mode,old_open_mode,
1714 if ((access_allowed == AFAIL) ||
1715 (!fcbopen && (access_allowed == AREAD && *flags == O_RDWR)) ||
1716 (access_allowed == AREAD && *flags == O_WRONLY) ||
1717 (access_allowed == AWRITE && *flags == O_RDONLY))
1719 DEBUG(2,("Share violation on file (%d,%d,%d,%d,%s,fcbopen = %d, flags = %d) = %d\n",
1720 deny_mode,old_deny_mode,old_open_mode,
1721 share->pid,fname, fcbopen, *flags, access_allowed));
1725 if (access_allowed == AREAD)
1728 if (access_allowed == AWRITE)
1735 /****************************************************************************
1736 open a file with a share mode
1737 ****************************************************************************/
1738 void open_file_shared(files_struct *fsp,connection_struct *conn,char *fname,int share_mode,int ofun,
1739 int mode,int oplock_request, int *Access,int *action)
1743 int deny_mode = (share_mode>>4)&7;
1745 BOOL file_existed = file_exist(fname,&sbuf);
1746 BOOL share_locked = False;
1747 BOOL fcbopen = False;
1751 int num_share_modes = 0;
1756 /* this is for OS/2 EAs - try and say we don't support them */
1757 if (strstr(fname,".+,;=[]."))
1759 unix_ERR_class = ERRDOS;
1760 /* OS/2 Workplace shell fix may be main code stream in a later release. */
1761 #if 1 /* OS2_WPS_FIX - Recent versions of OS/2 need this. */
1762 unix_ERR_code = ERRcannotopen;
1763 #else /* OS2_WPS_FIX */
1764 unix_ERR_code = ERROR_EAS_NOT_SUPPORTED;
1765 #endif /* OS2_WPS_FIX */
1770 if ((ofun & 0x3) == 0 && file_existed)
1778 if ((ofun & 0x3) == 2)
1781 /* note that we ignore the append flag as
1782 append does not mean the same thing under dos and unix */
1784 switch (share_mode&0xF)
1802 if (share_mode&(1<<14)) {
1807 if (flags != O_RDONLY && file_existed &&
1808 (!CAN_WRITE(conn) || IS_DOS_READONLY(dos_mode(conn,fname,&sbuf))))
1818 if (deny_mode > DENY_NONE && deny_mode!=DENY_FCB)
1820 DEBUG(2,("Invalid deny mode %d on file %s\n",deny_mode,fname));
1825 if (deny_mode == DENY_FCB) deny_mode = DENY_DOS;
1827 if (lp_share_modes(SNUM(conn)))
1830 share_mode_entry *old_shares = 0;
1834 dev = (uint32)sbuf.st_dev;
1835 inode = (uint32)sbuf.st_ino;
1836 lock_share_entry(conn, dev, inode, &token);
1837 share_locked = True;
1838 num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1842 * Check if the share modes will give us access.
1845 if(share_locked && (num_share_modes != 0))
1852 broke_oplock = False;
1853 for(i = 0; i < num_share_modes; i++)
1855 share_mode_entry *share_entry = &old_shares[i];
1858 * By observation of NetBench, oplocks are broken *before* share
1859 * modes are checked. This allows a file to be closed by the client
1860 * if the share mode would deny access and the client has an oplock.
1861 * Check if someone has an oplock on this file. If so we must break
1862 * it before continuing.
1864 if(share_entry->op_type & (EXCLUSIVE_OPLOCK|BATCH_OPLOCK))
1867 DEBUG(5,("open_file_shared: breaking oplock (%x) on file %s, \
1868 dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
1870 /* Oplock break.... */
1871 unlock_share_entry(conn, dev, inode, token);
1872 if(request_oplock_break(share_entry, dev, inode) == False)
1874 free((char *)old_shares);
1875 DEBUG(0,("open_file_shared: FAILED when breaking oplock (%x) on file %s, \
1876 dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
1878 unix_ERR_class = ERRDOS;
1879 unix_ERR_code = ERRbadshare;
1882 lock_share_entry(conn, dev, inode, &token);
1883 broke_oplock = True;
1887 /* someone else has a share lock on it, check to see
1889 if(check_share_mode(share_entry, deny_mode, fname, fcbopen, &flags) == False)
1891 free((char *)old_shares);
1892 unlock_share_entry(conn, dev, inode, token);
1894 unix_ERR_class = ERRDOS;
1895 unix_ERR_code = ERRbadshare;
1903 free((char *)old_shares);
1904 num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1906 } while(broke_oplock);
1910 free((char *)old_shares);
1913 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o\n",
1914 flags,flags2,mode));
1916 open_file(fsp,conn,fname,flags|(flags2&~(O_TRUNC)),mode,file_existed ? &sbuf : 0);
1917 if (!fsp->open && flags==O_RDWR && errno!=ENOENT && fcbopen)
1920 open_file(fsp,conn,fname,flags,mode,file_existed ? &sbuf : 0 );
1927 if((share_locked == False) && lp_share_modes(SNUM(conn)))
1929 /* We created the file - thus we must now lock the share entry before creating it. */
1930 dev = fsp->fd_ptr->dev;
1931 inode = fsp->fd_ptr->inode;
1932 lock_share_entry(conn, dev, inode, &token);
1933 share_locked = True;
1949 fsp->share_mode = (deny_mode<<4) | open_mode;
1952 (*Access) = open_mode;
1956 if (file_existed && !(flags2 & O_TRUNC)) *action = FILE_WAS_OPENED;
1957 if (!file_existed) *action = FILE_WAS_CREATED;
1958 if (file_existed && (flags2 & O_TRUNC)) *action = FILE_WAS_OVERWRITTEN;
1960 /* We must create the share mode entry before truncate as
1961 truncate can fail due to locking and have to close the
1962 file (which expects the share_mode_entry to be there).
1964 if (lp_share_modes(SNUM(conn)))
1967 /* JRA. Currently this only services Exlcusive and batch
1968 oplocks (no other opens on this file). This needs to
1969 be extended to level II oplocks (multiple reader
1972 if(oplock_request && (num_share_modes == 0) && lp_oplocks(SNUM(conn)) &&
1973 !IS_VETO_OPLOCK_PATH(conn,fname))
1975 fsp->granted_oplock = True;
1976 fsp->sent_oplock_break = False;
1977 global_oplocks_open++;
1980 DEBUG(5,("open_file_shared: granted oplock (%x) on file %s, \
1981 dev = %x, inode = %x\n", oplock_request, fname, dev, inode));
1989 set_share_mode(token, fsp, port, oplock_request);
1992 if ((flags2&O_TRUNC) && file_existed)
1993 truncate_unless_locked(fsp,conn,token,&share_locked);
1996 if (share_locked && lp_share_modes(SNUM(conn)))
1997 unlock_share_entry( conn, dev, inode, token);
2000 /****************************************************************************
2001 seek a file. Try to avoid the seek if possible
2002 ****************************************************************************/
2003 int seek_file(files_struct *fsp,uint32 pos)
2007 if (fsp->print_file && lp_postscript(fsp->conn->service))
2010 fsp->pos = (int)(lseek(fsp->fd_ptr->fd,pos+offset,SEEK_SET) - offset);
2014 /****************************************************************************
2016 ****************************************************************************/
2017 int read_file(files_struct *fsp,char *data,uint32 pos,int n)
2021 #if USE_READ_PREDICTION
2022 if (!fsp->can_write)
2024 ret = read_predict(fsp->fd_ptr->fd,pos,data,NULL,n);
2035 int num = (fsp->mmap_size > pos) ? (fsp->mmap_size - pos) : -1;
2039 memcpy(data,fsp->mmap_ptr+pos,num);
2051 if (seek_file(fsp,pos) != pos)
2053 DEBUG(3,("Failed to seek to %d\n",pos));
2058 readret = read(fsp->fd_ptr->fd,data,n);
2059 if (readret > 0) ret += readret;
2066 /****************************************************************************
2068 ****************************************************************************/
2069 int write_file(files_struct *fsp,char *data,int n)
2072 if (!fsp->can_write) {
2077 if (!fsp->modified) {
2079 fsp->modified = True;
2080 if (fstat(fsp->fd_ptr->fd,&st) == 0) {
2081 int dosmode = dos_mode(fsp->conn,fsp->fsp_name,&st);
2082 if (MAP_ARCHIVE(fsp->conn) && !IS_DOS_ARCHIVE(dosmode)) {
2083 dos_chmod(fsp->conn,fsp->fsp_name,dosmode | aARCH,&st);
2088 return(write_data(fsp->fd_ptr->fd,data,n));
2092 /****************************************************************************
2093 load parameters specific to a connection/service
2094 ****************************************************************************/
2095 BOOL become_service(connection_struct *conn,BOOL do_chdir)
2097 extern char magic_char;
2098 static connection_struct *last_conn;
2101 if (!conn || !conn->open) {
2106 conn->lastused = smb_last_time;
2111 ChDir(conn->connectpath) != 0 &&
2112 ChDir(conn->origpath) != 0) {
2113 DEBUG(0,("chdir (%s) failed\n",
2114 conn->connectpath));
2118 if (conn == last_conn)
2123 case_default = lp_defaultcase(snum);
2124 case_preserve = lp_preservecase(snum);
2125 short_case_preserve = lp_shortpreservecase(snum);
2126 case_mangle = lp_casemangle(snum);
2127 case_sensitive = lp_casesensitive(snum);
2128 magic_char = lp_magicchar(snum);
2129 use_mangled_map = (*lp_mangled_map(snum) ? True:False);
2134 /****************************************************************************
2135 find a service entry
2136 ****************************************************************************/
2137 int find_service(char *service)
2141 string_sub(service,"\\","/");
2143 iService = lp_servicenumber(service);
2145 /* now handle the special case of a home directory */
2148 char *phome_dir = get_home_dir(service);
2153 * Try mapping the servicename, it may
2154 * be a Windows to unix mapped user name.
2156 if(map_username(service))
2157 phome_dir = get_home_dir(service);
2160 DEBUG(3,("checking for home directory %s gave %s\n",service,
2161 phome_dir?phome_dir:"(NULL)"));
2166 if ((iHomeService = lp_servicenumber(HOMES_NAME)) >= 0)
2168 lp_add_home(service,iHomeService,phome_dir);
2169 iService = lp_servicenumber(service);
2174 /* If we still don't have a service, attempt to add it as a printer. */
2177 int iPrinterService;
2179 if ((iPrinterService = lp_servicenumber(PRINTERS_NAME)) >= 0)
2183 DEBUG(3,("checking whether %s is a valid printer name...\n", service));
2185 if ((pszTemp != NULL) && pcap_printername_ok(service, pszTemp))
2187 DEBUG(3,("%s is a valid printer name\n", service));
2188 DEBUG(3,("adding %s as a printer service\n", service));
2189 lp_add_printer(service,iPrinterService);
2190 iService = lp_servicenumber(service);
2192 DEBUG(0,("failed to add %s as a printer service!\n", service));
2195 DEBUG(3,("%s is not a valid printer name\n", service));
2199 /* just possibly it's a default service? */
2202 char *pdefservice = lp_defaultservice();
2203 if (pdefservice && *pdefservice && !strequal(pdefservice,service))
2206 * We need to do a local copy here as lp_defaultservice()
2207 * returns one of the rotating lp_string buffers that
2208 * could get overwritten by the recursive find_service() call
2209 * below. Fix from Josef Hinteregger <joehtg@joehtg.co.at>.
2212 pstrcpy(defservice, pdefservice);
2213 iService = find_service(defservice);
2216 string_sub(service,"_","/");
2217 iService = lp_add_service(service,iService);
2223 if (!VALID_SNUM(iService))
2225 DEBUG(0,("Invalid snum %d for %s\n",iService,service));
2230 DEBUG(3,("find_service() failed to find service %s\n", service));
2236 /****************************************************************************
2237 create an error packet from a cached error.
2238 ****************************************************************************/
2239 int cached_error_packet(char *inbuf,char *outbuf,files_struct *fsp,int line)
2241 write_bmpx_struct *wbmpx = fsp->wbmpx_ptr;
2243 int32 eclass = wbmpx->wr_errclass;
2244 int32 err = wbmpx->wr_error;
2246 /* We can now delete the auxiliary struct */
2247 free((char *)wbmpx);
2248 fsp->wbmpx_ptr = NULL;
2249 return error_packet(inbuf,outbuf,eclass,err,line);
2258 } unix_smb_errmap[] =
2260 {EPERM,ERRDOS,ERRnoaccess},
2261 {EACCES,ERRDOS,ERRnoaccess},
2262 {ENOENT,ERRDOS,ERRbadfile},
2263 {ENOTDIR,ERRDOS,ERRbadpath},
2264 {EIO,ERRHRD,ERRgeneral},
2265 {EBADF,ERRSRV,ERRsrverror},
2266 {EINVAL,ERRSRV,ERRsrverror},
2267 {EEXIST,ERRDOS,ERRfilexists},
2268 {ENFILE,ERRDOS,ERRnofids},
2269 {EMFILE,ERRDOS,ERRnofids},
2270 {ENOSPC,ERRHRD,ERRdiskfull},
2272 {EDQUOT,ERRHRD,ERRdiskfull},
2275 {ENOTEMPTY,ERRDOS,ERRnoaccess},
2278 {EXDEV,ERRDOS,ERRdiffdevice},
2280 {EROFS,ERRHRD,ERRnowrite},
2284 /****************************************************************************
2285 create an error packet from errno
2286 ****************************************************************************/
2287 int unix_error_packet(char *inbuf,char *outbuf,int def_class,uint32 def_code,int line)
2289 int eclass=def_class;
2293 if (unix_ERR_class != SMB_SUCCESS)
2295 eclass = unix_ERR_class;
2296 ecode = unix_ERR_code;
2297 unix_ERR_class = SMB_SUCCESS;
2302 while (unix_smb_errmap[i].smbclass != 0)
2304 if (unix_smb_errmap[i].unixerror == errno)
2306 eclass = unix_smb_errmap[i].smbclass;
2307 ecode = unix_smb_errmap[i].smbcode;
2314 return(error_packet(inbuf,outbuf,eclass,ecode,line));
2318 /****************************************************************************
2319 create an error packet. Normally called using the ERROR() macro
2320 ****************************************************************************/
2321 int error_packet(char *inbuf,char *outbuf,int error_class,uint32 error_code,int line)
2323 int outsize = set_message(outbuf,0,0,True);
2324 int cmd = CVAL(inbuf,smb_com);
2325 int flgs2 = SVAL(outbuf,smb_flg2);
2327 if ((flgs2 & FLAGS2_32_BIT_ERROR_CODES) == FLAGS2_32_BIT_ERROR_CODES)
2329 SIVAL(outbuf,smb_rcls,error_code);
2331 DEBUG( 3, ( "32 bit error packet at line %d cmd=%d (%s) eclass=%08x [%s]\n",
2332 line, cmd, smb_fn_name(cmd), error_code, smb_errstr(outbuf) ) );
2336 CVAL(outbuf,smb_rcls) = error_class;
2337 SSVAL(outbuf,smb_err,error_code);
2338 DEBUG( 3, ( "error packet at line %d cmd=%d (%s) eclass=%d ecode=%d\n",
2340 (int)CVAL(inbuf,smb_com),
2341 smb_fn_name(CVAL(inbuf,smb_com)),
2348 DEBUG(3,("error string = %s\n",strerror(errno)));
2354 /****************************************************************************
2355 this is called when the client exits abruptly
2356 **************************************************************************/
2357 static void sig_pipe(int sig)
2359 struct cli_state *cli;
2360 BlockSignals(True,SIGPIPE);
2362 if ((cli = server_client()) && cli->initialised) {
2363 DEBUG(3,("lost connection to password server\n"));
2365 BlockSignals(False,SIGPIPE);
2369 exit_server("Got sigpipe\n");
2372 /****************************************************************************
2373 open the socket communication
2374 ****************************************************************************/
2375 static BOOL open_sockets(BOOL is_daemon,int port)
2381 int num_interfaces = iface_count();
2382 int fd_listenset[FD_SETSIZE];
2388 static int atexit_set;
2389 if(atexit_set == 0) {
2399 FD_ZERO(&listen_set);
2401 if(lp_interfaces() && lp_bind_interfaces_only())
2403 /* We have been given an interfaces line, and been
2404 told to only bind to those interfaces. Create a
2405 socket per interface and bind to only these.
2408 if(num_interfaces > FD_SETSIZE)
2410 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
2411 max can be %d\n", num_interfaces, FD_SETSIZE));
2415 /* Now open a listen socket for each of the interfaces. */
2416 for(i = 0; i < num_interfaces; i++)
2418 struct in_addr *ifip = iface_n_ip(i);
2422 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
2425 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr);
2428 /* ready to listen */
2429 if (listen(s, 5) == -1)
2431 DEBUG(0,("listen: %s\n",strerror(errno)));
2435 FD_SET(s,&listen_set);
2440 /* Just bind to 0.0.0.0 - accept connections from anywhere. */
2443 /* open an incoming socket */
2444 s = open_socket_in(SOCK_STREAM, port, 0,interpret_addr(lp_socket_address()));
2448 /* ready to listen */
2449 if (listen(s, 5) == -1)
2451 DEBUG(0,("open_sockets: listen: %s\n",strerror(errno)));
2456 fd_listenset[0] = s;
2457 FD_SET(s,&listen_set);
2460 /* now accept incoming connections - forking a new process
2461 for each incoming connection */
2462 DEBUG(2,("waiting for a connection\n"));
2468 memcpy((char *)&lfds, (char *)&listen_set, sizeof(listen_set));
2470 num = sys_select(&lfds,NULL);
2472 if (num == -1 && errno == EINTR)
2475 /* Find the sockets that are read-ready - accept on these. */
2476 for( ; num > 0; num--)
2478 struct sockaddr addr;
2479 int in_addrlen = sizeof(addr);
2482 for(i = 0; i < num_interfaces; i++)
2484 if(FD_ISSET(fd_listenset[i],&lfds))
2486 s = fd_listenset[i];
2487 /* Clear this so we don't look at it again. */
2488 FD_CLR(fd_listenset[i],&lfds);
2493 Client = accept(s,&addr,&in_addrlen);
2495 if (Client == -1 && errno == EINTR)
2500 DEBUG(0,("open_sockets: accept: %s\n",strerror(errno)));
2504 if (Client != -1 && fork()==0)
2506 /* Child code ... */
2508 CatchSignal(SIGPIPE, SIGNAL_CAST sig_pipe);
2510 /* close the listening socket(s) */
2511 for(i = 0; i < num_interfaces; i++)
2512 close(fd_listenset[i]);
2514 /* close our standard file descriptors */
2518 set_socket_options(Client,"SO_KEEPALIVE");
2519 set_socket_options(Client,user_socket_options);
2521 /* Reset global variables in util.c so that
2522 client substitutions will be done correctly
2525 reset_globals_after_fork();
2528 close(Client); /* The parent doesn't need this socket */
2531 * Force parent to check log size after spawning child.
2532 * Fix from klausr@ITAP.Physik.Uni-Stuttgart.De.
2533 * The parent smbd will log to logserver.smb.
2534 * It writes only two messages for each child
2535 * started/finished. But each child writes, say, 50 messages also in
2536 * logserver.smb, begining with the debug_count of the parent, before the
2537 * child opens its own log file logserver.client. In a worst case
2538 * scenario the size of logserver.smb would be checked after about
2539 * 50*50=2500 messages (ca. 100kb).
2541 force_check_log_size();
2545 } /* end if is_daemon */
2548 /* Started from inetd. fd 0 is the socket. */
2549 /* We will abort gracefully when the client or remote system
2551 CatchSignal(SIGPIPE, SIGNAL_CAST sig_pipe);
2554 /* close our standard file descriptors */
2557 set_socket_options(Client,"SO_KEEPALIVE");
2558 set_socket_options(Client,user_socket_options);
2564 /****************************************************************************
2565 process an smb from the client - split out from the process() code so
2566 it can be used by the oplock break code.
2567 ****************************************************************************/
2569 static void process_smb(char *inbuf, char *outbuf)
2573 extern BOOL sslEnabled; /* don't use function for performance reasons */
2574 static int sslConnected = 0;
2575 #endif /* WITH_SSL */
2576 static int trans_num;
2577 int msg_type = CVAL(inbuf,0);
2578 int32 len = smb_len(inbuf);
2579 int nread = len + 4;
2581 if (trans_num == 0) {
2582 /* on the first packet, check the global hosts allow/ hosts
2583 deny parameters before doing any parsing of the packet
2584 passed to us by the client. This prevents attacks on our
2585 parsing code from hosts not in the hosts allow list */
2586 if (!check_access(Client, lp_hostsallow(-1), lp_hostsdeny(-1))) {
2587 /* send a negative session response "not listining on calling
2589 static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
2590 DEBUG( 1, ( "Connection denied from %s\n",
2591 client_addr(Client) ) );
2592 send_smb(Client,(char *)buf);
2593 exit_server("connection denied");
2597 DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type, len ) );
2598 DEBUG( 3, ( "Transaction %d of length %d\n", trans_num, nread ) );
2601 if(sslEnabled && !sslConnected){
2602 sslConnected = sslutil_negotiate_ssl(Client, msg_type);
2603 if(sslConnected < 0){ /* an error occured */
2604 exit_server("SSL negotiation failed");
2605 }else if(sslConnected){
2610 #endif /* WITH_SSL */
2613 if(trans_num == 1 && VT_Check(inbuf))
2622 else if(msg_type == 0x85)
2623 return; /* Keepalive packet. */
2625 nread = construct_reply(inbuf,outbuf,nread,max_send);
2629 if (CVAL(outbuf,0) == 0)
2632 if (nread != smb_len(outbuf) + 4)
2634 DEBUG(0,("ERROR: Invalid message response size! %d %d\n",
2635 nread, smb_len(outbuf)));
2638 send_smb(Client,outbuf);
2643 /****************************************************************************
2644 open the oplock IPC socket communication
2645 ****************************************************************************/
2646 static BOOL open_oplock_ipc(void)
2648 struct sockaddr_in sock_name;
2649 int len = sizeof(sock_name);
2651 DEBUG(3,("open_oplock_ipc: opening loopback UDP socket.\n"));
2653 /* Open a lookback UDP socket on a random port. */
2654 oplock_sock = open_socket_in(SOCK_DGRAM, 0, 0, htonl(INADDR_LOOPBACK));
2655 if (oplock_sock == -1)
2657 DEBUG(0,("open_oplock_ipc: Failed to get local UDP socket for \
2658 address %x. Error was %s\n", htonl(INADDR_LOOPBACK), strerror(errno)));
2663 /* Find out the transient UDP port we have been allocated. */
2664 if(getsockname(oplock_sock, (struct sockaddr *)&sock_name, &len)<0)
2666 DEBUG(0,("open_oplock_ipc: Failed to get local UDP port. Error was %s\n",
2673 oplock_port = ntohs(sock_name.sin_port);
2675 DEBUG(3,("open_oplock ipc: pid = %d, oplock_port = %u\n",
2676 (int)getpid(), oplock_port));
2681 /****************************************************************************
2682 process an oplock break message.
2683 ****************************************************************************/
2684 static BOOL process_local_message(int sock, char *buffer, int buf_size)
2690 msg_len = IVAL(buffer,UDP_CMD_LEN_OFFSET);
2691 from_port = SVAL(buffer,UDP_CMD_PORT_OFFSET);
2693 msg_start = &buffer[UDP_CMD_HEADER_LEN];
2695 DEBUG(5,("process_local_message: Got a message of length %d from port (%d)\n",
2696 msg_len, from_port));
2698 /* Switch on message command - currently OPLOCK_BREAK_CMD is the
2699 only valid request. */
2701 switch(SVAL(msg_start,UDP_MESSAGE_CMD_OFFSET))
2703 case OPLOCK_BREAK_CMD:
2704 /* Ensure that the msg length is correct. */
2705 if(msg_len != OPLOCK_BREAK_MSG_LEN)
2707 DEBUG(0,("process_local_message: incorrect length for OPLOCK_BREAK_CMD (was %d, \
2708 should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
2712 uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
2713 uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
2714 uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
2715 struct timeval tval;
2716 struct sockaddr_in toaddr;
2718 tval.tv_sec = IVAL(msg_start, OPLOCK_BREAK_SEC_OFFSET);
2719 tval.tv_usec = IVAL(msg_start, OPLOCK_BREAK_USEC_OFFSET);
2721 DEBUG(5,("process_local_message: oplock break request from \
2722 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
2725 * If we have no record of any currently open oplocks,
2726 * it's not an error, as a close command may have
2727 * just been issued on the file that was oplocked.
2728 * Just return success in this case.
2731 if(global_oplocks_open != 0)
2733 if(oplock_break(dev, inode, &tval) == False)
2735 DEBUG(0,("process_local_message: oplock break failed - \
2736 not returning udp message.\n"));
2742 DEBUG(3,("process_local_message: oplock break requested with no outstanding \
2743 oplocks. Returning success.\n"));
2746 /* Send the message back after OR'ing in the 'REPLY' bit. */
2747 SSVAL(msg_start,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD | CMD_REPLY);
2749 bzero((char *)&toaddr,sizeof(toaddr));
2750 toaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2751 toaddr.sin_port = htons(from_port);
2752 toaddr.sin_family = AF_INET;
2754 if(sendto( sock, msg_start, OPLOCK_BREAK_MSG_LEN, 0,
2755 (struct sockaddr *)&toaddr, sizeof(toaddr)) < 0)
2757 DEBUG(0,("process_local_message: sendto process %d failed. Errno was %s\n",
2758 remotepid, strerror(errno)));
2762 DEBUG(5,("process_local_message: oplock break reply sent to \
2763 pid %d, port %d, for file dev = %x, inode = %x\n", remotepid,
2764 from_port, dev, inode));
2769 * Keep this as a debug case - eventually we can remove it.
2772 DEBUG(0,("process_local_message: Received unsolicited break \
2773 reply - dumping info.\n"));
2775 if(msg_len != OPLOCK_BREAK_MSG_LEN)
2777 DEBUG(0,("process_local_message: ubr: incorrect length for reply \
2778 (was %d, should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
2783 uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
2784 uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
2785 uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
2787 DEBUG(0,("process_local_message: unsolicited oplock break reply from \
2788 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
2794 DEBUG(0,("process_local_message: unknown UDP message command code (%x) - ignoring.\n",
2795 (unsigned int)SVAL(msg_start,0)));
2801 /****************************************************************************
2802 Process an oplock break directly.
2803 ****************************************************************************/
2804 BOOL oplock_break(uint32 dev, uint32 inode, struct timeval *tval)
2806 extern struct current_user current_user;
2809 char *outbuf = NULL;
2810 files_struct *fsp = NULL;
2812 BOOL shutdown_server = False;
2813 connection_struct *saved_conn;
2819 dbgtext( "oplock_break: called for dev = %x, inode = %x.\n", dev, inode );
2820 dbgtext( "Current global_oplocks_open = %d\n", global_oplocks_open );
2823 /* We need to search the file open table for the
2824 entry containing this dev and inode, and ensure
2825 we have an oplock on it. */
2826 fsp = file_find_dit(dev, inode, tval);
2830 /* The file could have been closed in the meantime - return success. */
2833 dbgtext( "oplock_break: cannot find open file with " );
2834 dbgtext( "dev = %x, inode = %x ", dev, inode);
2835 dbgtext( "allowing break to succeed.\n" );
2840 /* Ensure we have an oplock on the file */
2842 /* There is a potential race condition in that an oplock could
2843 have been broken due to another udp request, and yet there are
2844 still oplock break messages being sent in the udp message
2845 queue for this file. So return true if we don't have an oplock,
2846 as we may have just freed it.
2849 if(!fsp->granted_oplock)
2853 dbgtext( "oplock_break: file %s ", fsp->fsp_name );
2854 dbgtext( "(dev = %x, inode = %x) has no oplock.\n", dev, inode );
2855 dbgtext( "Allowing break to succeed regardless.\n" );
2860 /* mark the oplock break as sent - we don't want to send twice! */
2861 if (fsp->sent_oplock_break)
2865 dbgtext( "oplock_break: ERROR: oplock_break already sent for " );
2866 dbgtext( "file %s ", fsp->fsp_name);
2867 dbgtext( "(dev = %x, inode = %x)\n", dev, inode );
2870 /* We have to fail the open here as we cannot send another oplock break on
2871 this file whilst we are awaiting a response from the client - neither
2872 can we allow another open to succeed while we are waiting for the
2878 /* Now comes the horrid part. We must send an oplock break to the client,
2879 and then process incoming messages until we get a close or oplock release.
2880 At this point we know we need a new inbuf/outbuf buffer pair.
2881 We cannot use these staticaly as we may recurse into here due to
2882 messages crossing on the wire.
2885 if((inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
2887 DEBUG(0,("oplock_break: malloc fail for input buffer.\n"));
2891 if((outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
2893 DEBUG(0,("oplock_break: malloc fail for output buffer.\n"));
2899 /* Prepare the SMBlockingX message. */
2900 bzero(outbuf,smb_size);
2901 set_message(outbuf,8,0,True);
2903 SCVAL(outbuf,smb_com,SMBlockingX);
2904 SSVAL(outbuf,smb_tid,fsp->conn->cnum);
2905 SSVAL(outbuf,smb_pid,0xFFFF);
2906 SSVAL(outbuf,smb_uid,0);
2907 SSVAL(outbuf,smb_mid,0xFFFF);
2908 SCVAL(outbuf,smb_vwv0,0xFF);
2909 SSVAL(outbuf,smb_vwv2,fsp->fnum);
2910 SCVAL(outbuf,smb_vwv3,LOCKING_ANDX_OPLOCK_RELEASE);
2911 /* Change this when we have level II oplocks. */
2912 SCVAL(outbuf,smb_vwv3+1,OPLOCKLEVEL_NONE);
2914 send_smb(Client, outbuf);
2916 /* Remember we just sent an oplock break on this file. */
2917 fsp->sent_oplock_break = True;
2919 /* We need this in case a readraw crosses on the wire. */
2920 global_oplock_break = True;
2922 /* Process incoming messages. */
2924 /* JRA - If we don't get a break from the client in OPLOCK_BREAK_TIMEOUT
2925 seconds we should just die.... */
2927 start_time = time(NULL);
2930 * Save the information we need to re-become the
2931 * user, then unbecome the user whilst we're doing this.
2933 saved_conn = fsp->conn;
2934 saved_vuid = current_user.vuid;
2938 while(OPEN_FSP(fsp) && fsp->granted_oplock)
2940 if(receive_smb(Client,inbuf,OPLOCK_BREAK_TIMEOUT * 1000) == False)
2943 * Die if we got an error.
2946 if (smb_read_error == READ_EOF)
2947 DEBUG( 0, ( "oplock_break: end of file from client\n" ) );
2949 if (smb_read_error == READ_ERROR)
2950 DEBUG( 0, ("oplock_break: receive_smb error (%s)\n", strerror(errno)) );
2952 if (smb_read_error == READ_TIMEOUT)
2953 DEBUG( 0, ( "oplock_break: receive_smb timed out after %d seconds.\n",
2954 OPLOCK_BREAK_TIMEOUT ) );
2956 DEBUGADD( 0, ( "oplock_break failed for file %s ", fsp->fsp_name ) );
2957 DEBUGADD( 0, ( "(dev = %x, inode = %x).\n", dev, inode));
2958 shutdown_server = True;
2963 * There are certain SMB requests that we shouldn't allow
2964 * to recurse. opens, renames and deletes are the obvious
2965 * ones. This is handled in the switch_message() function.
2966 * If global_oplock_break is set they will push the packet onto
2967 * the pending smb queue and return -1 (no reply).
2971 process_smb(inbuf, outbuf);
2974 * Die if we go over the time limit.
2977 if((time(NULL) - start_time) > OPLOCK_BREAK_TIMEOUT)
2981 dbgtext( "oplock_break: no break received from client " );
2982 dbgtext( "within %d seconds.\n", OPLOCK_BREAK_TIMEOUT );
2983 dbgtext( "oplock_break failed for file %s ", fsp->fsp_name );
2984 dbgtext( "(dev = %x, inode = %x).\n", dev, inode );
2986 shutdown_server = True;
2992 * Go back to being the user who requested the oplock
2995 if(!become_user(saved_conn, saved_vuid))
2997 DEBUG( 0, ( "oplock_break: unable to re-become user!" ) );
2998 DEBUGADD( 0, ( "Shutting down server\n" ) );
3001 exit_server("unable to re-become user");
3003 /* Including the directory. */
3006 /* Free the buffers we've been using to recurse. */
3010 /* We need this in case a readraw crossed on the wire. */
3011 if(global_oplock_break)
3012 global_oplock_break = False;
3015 * If the client did not respond we must die.
3020 DEBUG( 0, ( "oplock_break: client failure in break - " ) );
3021 DEBUGADD( 0, ( "shutting down this smbd.\n" ) );
3024 exit_server("oplock break failure");
3029 /* The lockingX reply will have removed the oplock flag
3030 from the sharemode. */
3032 fsp->granted_oplock = False;
3033 fsp->sent_oplock_break = False;
3034 global_oplocks_open--;
3037 /* Santity check - remove this later. JRA */
3038 if(global_oplocks_open < 0)
3040 DEBUG(0,("oplock_break: global_oplocks_open < 0 (%d). PANIC ERROR\n",
3041 global_oplocks_open));
3042 exit_server("oplock_break: global_oplocks_open < 0");
3047 dbgtext( "oplock_break: returning success for " );
3048 dbgtext( "dev = %x, inode = %x.\n", dev, inode );
3049 dbgtext( "Current global_oplocks_open = %d\n", global_oplocks_open );
3055 /****************************************************************************
3056 Send an oplock break message to another smbd process. If the oplock is held
3057 by the local smbd then call the oplock break function directly.
3058 ****************************************************************************/
3060 BOOL request_oplock_break(share_mode_entry *share_entry,
3061 uint32 dev, uint32 inode)
3063 char op_break_msg[OPLOCK_BREAK_MSG_LEN];
3064 struct sockaddr_in addr_out;
3069 if(pid == share_entry->pid)
3071 /* We are breaking our own oplock, make sure it's us. */
3072 if(share_entry->op_port != oplock_port)
3074 DEBUG(0,("request_oplock_break: corrupt share mode entry - pid = %d, port = %d \
3075 should be %d\n", pid, share_entry->op_port, oplock_port));
3079 DEBUG(5,("request_oplock_break: breaking our own oplock\n"));
3081 /* Call oplock break direct. */
3082 return oplock_break(dev, inode, &share_entry->time);
3085 /* We need to send a OPLOCK_BREAK_CMD message to the
3086 port in the share mode entry. */
3088 SSVAL(op_break_msg,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD);
3089 SIVAL(op_break_msg,OPLOCK_BREAK_PID_OFFSET,pid);
3090 SIVAL(op_break_msg,OPLOCK_BREAK_DEV_OFFSET,dev);
3091 SIVAL(op_break_msg,OPLOCK_BREAK_INODE_OFFSET,inode);
3092 SIVAL(op_break_msg,OPLOCK_BREAK_SEC_OFFSET,(uint32)share_entry->time.tv_sec);
3093 SIVAL(op_break_msg,OPLOCK_BREAK_USEC_OFFSET,(uint32)share_entry->time.tv_usec);
3095 /* set the address and port */
3096 bzero((char *)&addr_out,sizeof(addr_out));
3097 addr_out.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3098 addr_out.sin_port = htons( share_entry->op_port );
3099 addr_out.sin_family = AF_INET;
3103 dbgtext( "request_oplock_break: sending a oplock break message to " );
3104 dbgtext( "pid %d on port %d ", share_entry->pid, share_entry->op_port );
3105 dbgtext( "for dev = %x, inode = %x\n", dev, inode );
3108 if(sendto(oplock_sock,op_break_msg,OPLOCK_BREAK_MSG_LEN,0,
3109 (struct sockaddr *)&addr_out,sizeof(addr_out)) < 0)
3113 dbgtext( "request_oplock_break: failed when sending a oplock " );
3114 dbgtext( "break message to pid %d ", share_entry->pid );
3115 dbgtext( "on port %d ", share_entry->op_port );
3116 dbgtext( "for dev = %x, inode = %x.\n", dev, inode );
3117 dbgtext( "Error was %s\n", strerror(errno) );
3123 * Now we must await the oplock broken message coming back
3124 * from the target smbd process. Timeout if it fails to
3125 * return in (OPLOCK_BREAK_TIMEOUT + OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR) seconds.
3126 * While we get messages that aren't ours, loop.
3129 start_time = time(NULL);
3130 time_left = OPLOCK_BREAK_TIMEOUT+OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR;
3132 while(time_left >= 0)
3134 char op_break_reply[UDP_CMD_HEADER_LEN+OPLOCK_BREAK_MSG_LEN];
3135 int32 reply_msg_len;
3136 uint16 reply_from_port;
3137 char *reply_msg_start;
3139 if(receive_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply),
3140 time_left ? time_left * 1000 : 1) == False)
3142 if(smb_read_error == READ_TIMEOUT)
3146 dbgtext( "request_oplock_break: no response received to oplock " );
3147 dbgtext( "break request to pid %d ", share_entry->pid );
3148 dbgtext( "on port %d ", share_entry->op_port );
3149 dbgtext( "for dev = %x, inode = %x\n", dev, inode );
3152 * This is a hack to make handling of failing clients more robust.
3153 * If a oplock break response message is not received in the timeout
3154 * period we may assume that the smbd servicing that client holding
3155 * the oplock has died and the client changes were lost anyway, so
3156 * we should continue to try and open the file.
3163 dbgtext( "request_oplock_break: error in response received " );
3164 dbgtext( "to oplock break request to pid %d ", share_entry->pid );
3165 dbgtext( "on port %d ", share_entry->op_port );
3166 dbgtext( "for dev = %x, inode = %x.\n", dev, inode );
3167 dbgtext( "Error was (%s).\n", strerror(errno) );
3172 reply_msg_len = IVAL(op_break_reply,UDP_CMD_LEN_OFFSET);
3173 reply_from_port = SVAL(op_break_reply,UDP_CMD_PORT_OFFSET);
3175 reply_msg_start = &op_break_reply[UDP_CMD_HEADER_LEN];
3177 if(reply_msg_len != OPLOCK_BREAK_MSG_LEN)
3180 DEBUG( 0, ( "request_oplock_break: invalid message length received." ) );
3181 DEBUGADD( 0, ( " Ignoring.\n" ) );
3186 * Test to see if this is the reply we are awaiting.
3189 if((SVAL(reply_msg_start,UDP_MESSAGE_CMD_OFFSET) & CMD_REPLY) &&
3190 (reply_from_port == share_entry->op_port) &&
3191 (memcmp(&reply_msg_start[OPLOCK_BREAK_PID_OFFSET],
3192 &op_break_msg[OPLOCK_BREAK_PID_OFFSET],
3193 OPLOCK_BREAK_MSG_LEN - OPLOCK_BREAK_PID_OFFSET) == 0))
3196 * This is the reply we've been waiting for.
3203 * This is another message - probably a break request.
3204 * Process it to prevent potential deadlock.
3205 * Note that the code in switch_message() prevents
3206 * us from recursing into here as any SMB requests
3207 * we might process that would cause another oplock
3208 * break request to be made will be queued.
3212 process_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply));
3215 time_left -= (time(NULL) - start_time);
3218 DEBUG(3,("request_oplock_break: broke oplock.\n"));
3223 /****************************************************************************
3224 Get the next SMB packet, doing the local message processing automatically.
3225 ****************************************************************************/
3227 BOOL receive_next_smb(int smbfd, int oplockfd, char *inbuf, int bufsize, int timeout)
3229 BOOL got_smb = False;
3234 ret = receive_message_or_smb(smbfd,oplockfd,inbuf,bufsize,
3239 /* Deal with oplock break requests from other smbd's. */
3240 process_local_message(oplock_sock, inbuf, bufsize);
3244 if(ret && (CVAL(inbuf,0) == 0x85))
3246 /* Keepalive packet. */
3251 while(ret && !got_smb);
3256 /****************************************************************************
3257 check if a snum is in use
3258 ****************************************************************************/
3259 BOOL snum_used(int snum)
3262 for (i=0;i<MAX_CONNECTIONS;i++) {
3263 if (Connections[i].open && (Connections[i].service == snum)) {
3270 /****************************************************************************
3271 reload the services file
3272 **************************************************************************/
3273 BOOL reload_services(BOOL test)
3279 pstrcpy(fname,lp_configfile());
3280 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
3281 pstrcpy(servicesf,fname);
3288 if (test && !lp_file_list_changed())
3291 lp_killunused(snum_used);
3293 ret = lp_load(servicesf,False,False,True);
3297 /* perhaps the config filename is now set */
3299 reload_services(True);
3308 set_socket_options(Client,"SO_KEEPALIVE");
3309 set_socket_options(Client,user_socket_options);
3313 reset_mangled_cache();
3315 /* this forces service parameters to be flushed */
3316 become_service(NULL,True);
3323 /****************************************************************************
3324 this prevents zombie child processes
3325 ****************************************************************************/
3326 static BOOL reload_after_sighup = False;
3328 static void sig_hup(int sig)
3330 BlockSignals(True,SIGHUP);
3331 DEBUG(0,("Got SIGHUP\n"));
3334 * Fix from <branko.cibej@hermes.si> here.
3335 * We used to reload in the signal handler - this
3339 reload_after_sighup = True;
3340 BlockSignals(False,SIGHUP);
3343 /****************************************************************************
3344 find first available connection slot, starting from a random position.
3345 The randomisation stops problems with the server dieing and clients
3346 thinking the server is still available.
3347 ****************************************************************************/
3348 static connection_struct *find_free_connection(int hash)
3352 hash = (hash % (MAX_CONNECTIONS-2))+1;
3356 for (i=hash+1;i!=hash;) {
3357 if (!Connections[i].open && Connections[i].used == used) {
3358 DEBUG(3,("found free connection number %d\n",i));
3359 memset(&Connections[i], 0, sizeof(&Connections[i]));
3360 Connections[i].cnum = i;
3361 return &Connections[i];
3364 if (i == MAX_CONNECTIONS) {
3374 DEBUG(1,("ERROR! Out of connection structures\n"));
3380 /****************************************************************************
3381 make a connection to a service
3382 ****************************************************************************/
3383 connection_struct *make_connection(char *service,char *user,char *password, int pwlen, char *dev,uint16 vuid, int *ecode)
3386 struct passwd *pass = NULL;
3390 connection_struct *conn;
3394 snum = find_service(service);
3397 if (strequal(service,"IPC$")) {
3398 DEBUG(3,("refusing IPC connection\n"));
3403 DEBUG(0,("%s (%s) couldn't find service %s\n",
3404 remote_machine, client_addr(Client), service));
3405 *ecode = ERRinvnetname;
3409 if (strequal(service,HOMES_NAME)) {
3410 if (*user && Get_Pwnam(user,True))
3411 return(make_connection(user,user,password,
3412 pwlen,dev,vuid,ecode));
3414 if(lp_security() != SEC_SHARE) {
3415 if (validated_username(vuid)) {
3416 pstrcpy(user,validated_username(vuid));
3417 return(make_connection(user,user,password,pwlen,dev,vuid,ecode));
3420 /* Security = share. Try with sesssetup_user
3421 * as the username. */
3422 if(*sesssetup_user) {
3423 pstrcpy(user,sesssetup_user);
3424 return(make_connection(user,user,password,pwlen,dev,vuid,ecode));
3429 if (!lp_snum_ok(snum) ||
3430 !check_access(Client,
3431 lp_hostsallow(snum), lp_hostsdeny(snum))) {
3436 /* you can only connect to the IPC$ service as an ipc device */
3437 if (strequal(service,"IPC$"))
3440 if (*dev == '?' || !*dev) {
3441 if (lp_print_ok(snum)) {
3442 pstrcpy(dev,"LPT1:");
3448 /* if the request is as a printer and you can't print then refuse */
3450 if (!lp_print_ok(snum) && (strncmp(dev,"LPT",3) == 0)) {
3451 DEBUG(1,("Attempt to connect to non-printer as a printer\n"));
3452 *ecode = ERRinvdevice;
3456 /* lowercase the user name */
3459 /* add it as a possible user name */
3460 add_session_user(service);
3462 /* shall we let them in? */
3463 if (!authorise_login(snum,user,password,pwlen,&guest,&force,vuid)) {
3464 DEBUG( 2, ( "Invalid username/password for %s\n", service ) );
3469 conn = find_free_connection(str_checksum(service) + str_checksum(user));
3471 DEBUG(0,("Couldn't find free connection.\n"));
3472 *ecode = ERRnoresource;
3476 /* find out some info about the user */
3477 pass = Get_Pwnam(user,True);
3480 DEBUG(0,( "Couldn't find account %s\n",user));
3485 conn->read_only = lp_readonly(snum);
3489 StrnCpy(list,lp_readlist(snum),sizeof(pstring)-1);
3490 string_sub(list,"%S",service);
3492 if (user_in_list(user,list))
3493 conn->read_only = True;
3495 StrnCpy(list,lp_writelist(snum),sizeof(pstring)-1);
3496 string_sub(list,"%S",service);
3498 if (user_in_list(user,list))
3499 conn->read_only = False;
3502 /* admin user check */
3504 /* JRA - original code denied admin user if the share was
3505 marked read_only. Changed as I don't think this is needed,
3506 but old code left in case there is a problem here.
3508 if (user_in_list(user,lp_admin_users(snum))
3513 conn->admin_user = True;
3514 DEBUG(0,("%s logged in as admin user (root privileges)\n",user));
3516 conn->admin_user = False;
3519 conn->force_user = force;
3521 conn->uid = pass->pw_uid;
3522 conn->gid = pass->pw_gid;
3523 conn->num_files_open = 0;
3524 conn->lastused = time(NULL);
3525 conn->service = snum;
3527 conn->printer = (strncmp(dev,"LPT",3) == 0);
3528 conn->ipc = (strncmp(dev,"IPC",3) == 0);
3529 conn->dirptr = NULL;
3530 conn->veto_list = NULL;
3531 conn->hide_list = NULL;
3532 conn->veto_oplock_list = NULL;
3533 string_set(&conn->dirpath,"");
3534 string_set(&conn->user,user);
3536 #ifdef HAVE_GETGRNAM
3537 if (*lp_force_group(snum)) {
3541 StrnCpy(gname,lp_force_group(snum),sizeof(pstring)-1);
3542 /* default service may be a group name */
3543 string_sub(gname,"%S",service);
3544 gptr = (struct group *)getgrnam(gname);
3547 conn->gid = gptr->gr_gid;
3548 DEBUG(3,("Forced group %s\n",gname));
3550 DEBUG(1,("Couldn't find group %s\n",gname));
3555 if (*lp_force_user(snum)) {
3556 struct passwd *pass2;
3558 fstrcpy(fuser,lp_force_user(snum));
3559 pass2 = (struct passwd *)Get_Pwnam(fuser,True);
3561 conn->uid = pass2->pw_uid;
3562 string_set(&conn->user,fuser);
3563 fstrcpy(user,fuser);
3564 conn->force_user = True;
3565 DEBUG(3,("Forced user %s\n",fuser));
3567 DEBUG(1,("Couldn't find user %s\n",fuser));
3573 pstrcpy(s,lp_pathname(snum));
3574 standard_sub(conn,s);
3575 string_set(&conn->connectpath,s);
3576 DEBUG(3,("Connect path is %s\n",s));
3579 /* groups stuff added by ih */
3581 conn->groups = NULL;
3583 if (!IS_IPC(conn)) {
3584 /* Find all the groups this uid is in and
3585 store them. Used by become_user() */
3586 setup_groups(conn->user,conn->uid,conn->gid,
3587 &conn->ngroups,&conn->groups);
3589 /* check number of connections */
3590 if (!claim_connection(conn,
3591 lp_servicename(SNUM(conn)),
3592 lp_max_connections(SNUM(conn)),
3594 DEBUG(1,("too many connections - rejected\n"));
3595 *ecode = ERRnoresource;
3599 if (lp_status(SNUM(conn)))
3600 claim_connection(conn,"STATUS.",
3606 /* execute any "root preexec = " line */
3607 if (*lp_rootpreexec(SNUM(conn))) {
3609 pstrcpy(cmd,lp_rootpreexec(SNUM(conn)));
3610 standard_sub(conn,cmd);
3611 DEBUG(5,("cmd=%s\n",cmd));
3612 smbrun(cmd,NULL,False);
3615 if (!become_user(conn, conn->vuid)) {
3616 DEBUG(0,("Can't become connected user!\n"));
3618 if (!IS_IPC(conn)) {
3619 yield_connection(conn,
3620 lp_servicename(SNUM(conn)),
3621 lp_max_connections(SNUM(conn)));
3622 if (lp_status(SNUM(conn))) {
3623 yield_connection(conn,"STATUS.",MAXSTATUS);
3630 if (ChDir(conn->connectpath) != 0) {
3631 DEBUG(0,("Can't change directory to %s (%s)\n",
3632 conn->connectpath,strerror(errno)));
3635 if (!IS_IPC(conn)) {
3636 yield_connection(conn,
3637 lp_servicename(SNUM(conn)),
3638 lp_max_connections(SNUM(conn)));
3639 if (lp_status(SNUM(conn)))
3640 yield_connection(conn,"STATUS.",MAXSTATUS);
3642 *ecode = ERRinvnetname;
3646 string_set(&conn->origpath,conn->connectpath);
3648 #if SOFTLINK_OPTIMISATION
3649 /* resolve any soft links early */
3652 pstrcpy(s,conn->connectpath);
3654 string_set(&conn->connectpath,s);
3655 ChDir(conn->connectpath);
3659 num_connections_open++;
3660 add_session_user(user);
3662 /* execute any "preexec = " line */
3663 if (*lp_preexec(SNUM(conn))) {
3665 pstrcpy(cmd,lp_preexec(SNUM(conn)));
3666 standard_sub(conn,cmd);
3667 smbrun(cmd,NULL,False);
3670 /* we've finished with the sensitive stuff */
3673 /* Add veto/hide lists */
3674 if (!IS_IPC(conn) && !IS_PRINT(conn)) {
3675 set_namearray( &conn->veto_list, lp_veto_files(SNUM(conn)));
3676 set_namearray( &conn->hide_list, lp_hide_files(SNUM(conn)));
3677 set_namearray( &conn->veto_oplock_list, lp_veto_oplocks(SNUM(conn)));
3680 if( DEBUGLVL( IS_IPC(conn) ? 3 : 1 ) ) {
3683 dbgtext( "%s (%s) ", remote_machine, client_addr(Client) );
3684 dbgtext( "connect to service %s ", lp_servicename(SNUM(conn)) );
3685 dbgtext( "as user %s ", user );
3686 dbgtext( "(uid=%d, gid=%d) ", conn->uid, conn->gid );
3687 dbgtext( "(pid %d)\n", (int)getpid() );
3693 /****************************************************************************
3694 Attempt to break an oplock on a file (if oplocked).
3695 Returns True if the file was closed as a result of
3696 the oplock break, False otherwise.
3697 Used as a last ditch attempt to free a space in the
3698 file table when we have run out.
3699 ****************************************************************************/
3700 BOOL attempt_close_oplocked_file(files_struct *fsp)
3703 DEBUG(5,("attempt_close_oplocked_file: checking file %s.\n", fsp->fsp_name));
3705 if (fsp->open && fsp->granted_oplock && !fsp->sent_oplock_break) {
3707 /* Try and break the oplock. */
3708 file_fd_struct *fd_ptr = fsp->fd_ptr;
3709 if(oplock_break( fd_ptr->dev, fd_ptr->inode, &fsp->open_time)) {
3710 if(!fsp->open) /* Did the oplock break close the file ? */
3719 /****************************************************************************
3720 reply for the core protocol
3721 ****************************************************************************/
3722 int reply_corep(char *outbuf)
3724 int outsize = set_message(outbuf,1,0,True);
3726 Protocol = PROTOCOL_CORE;
3732 /****************************************************************************
3733 reply for the coreplus protocol
3734 ****************************************************************************/
3735 int reply_coreplus(char *outbuf)
3737 int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
3738 int outsize = set_message(outbuf,13,0,True);
3739 SSVAL(outbuf,smb_vwv5,raw); /* tell redirector we support
3740 readbraw and writebraw (possibly) */
3741 CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
3742 SSVAL(outbuf,smb_vwv1,0x1); /* user level security, don't encrypt */
3744 Protocol = PROTOCOL_COREPLUS;
3750 /****************************************************************************
3751 reply for the lanman 1.0 protocol
3752 ****************************************************************************/
3753 int reply_lanman1(char *outbuf)
3755 int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
3757 BOOL doencrypt = SMBENCRYPT();
3758 time_t t = time(NULL);
3760 if (lp_security()>=SEC_USER) secword |= 1;
3761 if (doencrypt) secword |= 2;
3763 set_message(outbuf,13,doencrypt?8:0,True);
3764 SSVAL(outbuf,smb_vwv1,secword);
3765 /* Create a token value and add it to the outgoing packet. */
3767 generate_next_challenge(smb_buf(outbuf));
3769 Protocol = PROTOCOL_LANMAN1;
3771 CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
3772 SSVAL(outbuf,smb_vwv2,max_recv);
3773 SSVAL(outbuf,smb_vwv3,lp_maxmux()); /* maxmux */
3774 SSVAL(outbuf,smb_vwv4,1);
3775 SSVAL(outbuf,smb_vwv5,raw); /* tell redirector we support
3776 readbraw writebraw (possibly) */
3777 SIVAL(outbuf,smb_vwv6,getpid());
3778 SSVAL(outbuf,smb_vwv10, TimeDiff(t)/60);
3780 put_dos_date(outbuf,smb_vwv8,t);
3782 return (smb_len(outbuf)+4);
3786 /****************************************************************************
3787 reply for the lanman 2.0 protocol
3788 ****************************************************************************/
3789 int reply_lanman2(char *outbuf)
3791 int raw = (lp_readraw()?1:0) | (lp_writeraw()?2:0);
3793 BOOL doencrypt = SMBENCRYPT();
3794 time_t t = time(NULL);
3795 struct cli_state *cli = NULL;
3799 if (lp_security() == SEC_SERVER) {
3800 cli = server_cryptkey();
3804 DEBUG(3,("using password server validation\n"));
3805 doencrypt = ((cli->sec_mode & 2) != 0);
3808 if (lp_security()>=SEC_USER) secword |= 1;
3809 if (doencrypt) secword |= 2;
3814 generate_next_challenge(cryptkey);
3816 memcpy(cryptkey, cli->cryptkey, 8);
3817 set_challenge(cli->cryptkey);
3821 set_message(outbuf,13,crypt_len,True);
3822 SSVAL(outbuf,smb_vwv1,secword);
3823 SIVAL(outbuf,smb_vwv6,getpid());
3825 memcpy(smb_buf(outbuf), cryptkey, 8);
3827 Protocol = PROTOCOL_LANMAN2;
3829 CVAL(outbuf,smb_flg) = 0x81; /* Reply, SMBlockread, SMBwritelock supported */
3830 SSVAL(outbuf,smb_vwv2,max_recv);
3831 SSVAL(outbuf,smb_vwv3,lp_maxmux());
3832 SSVAL(outbuf,smb_vwv4,1);
3833 SSVAL(outbuf,smb_vwv5,raw); /* readbraw and/or writebraw */
3834 SSVAL(outbuf,smb_vwv10, TimeDiff(t)/60);
3835 put_dos_date(outbuf,smb_vwv8,t);
3837 return (smb_len(outbuf)+4);
3841 /****************************************************************************
3842 reply for the nt protocol
3843 ****************************************************************************/
3844 int reply_nt1(char *outbuf)
3846 /* dual names + lock_and_read + nt SMBs + remote API calls */
3847 int capabilities = CAP_NT_FIND|CAP_LOCK_AND_READ|CAP_RPC_REMOTE_APIS |CAP_NT_SMBS;
3850 other valid capabilities which we may support at some time...
3852 CAP_LARGE_READX|CAP_STATUS32|CAP_LEVEL_II_OPLOCKS;
3856 BOOL doencrypt = SMBENCRYPT();
3857 time_t t = time(NULL);
3859 struct cli_state *cli = NULL;
3863 if (lp_security() == SEC_SERVER) {
3864 cli = server_cryptkey();
3868 DEBUG(3,("using password server validation\n"));
3869 doencrypt = ((cli->sec_mode & 2) != 0);
3875 generate_next_challenge(cryptkey);
3877 memcpy(cryptkey, cli->cryptkey, 8);
3878 set_challenge(cli->cryptkey);
3882 if (lp_readraw() && lp_writeraw()) {
3883 capabilities |= CAP_RAW_MODE;
3886 if (lp_security() >= SEC_USER) secword |= 1;
3887 if (doencrypt) secword |= 2;
3889 /* decide where (if) to put the encryption challenge, and
3890 follow it with the OEM'd domain name
3892 data_len = crypt_len + strlen(global_myworkgroup) + 1;
3894 set_message(outbuf,17,data_len,True);
3895 pstrcpy(smb_buf(outbuf)+crypt_len, global_myworkgroup);
3897 CVAL(outbuf,smb_vwv1) = secword;
3898 SSVALS(outbuf,smb_vwv16+1,crypt_len);
3900 memcpy(smb_buf(outbuf), cryptkey, 8);
3902 Protocol = PROTOCOL_NT1;
3904 SSVAL(outbuf,smb_vwv1+1,lp_maxmux()); /* maxmpx */
3905 SSVAL(outbuf,smb_vwv2+1,1); /* num vcs */
3906 SIVAL(outbuf,smb_vwv3+1,0xffff); /* max buffer. LOTS! */
3907 SIVAL(outbuf,smb_vwv5+1,0x10000); /* raw size. full 64k */
3908 SIVAL(outbuf,smb_vwv7+1,getpid()); /* session key */
3909 SIVAL(outbuf,smb_vwv9+1,capabilities); /* capabilities */
3910 put_long_date(outbuf+smb_vwv11+1,t);
3911 SSVALS(outbuf,smb_vwv15+1,TimeDiff(t)/60);
3912 SSVAL(outbuf,smb_vwv17,data_len); /* length of challenge+domain strings */
3914 return (smb_len(outbuf)+4);
3917 /* these are the protocol lists used for auto architecture detection:
3920 protocol [PC NETWORK PROGRAM 1.0]
3921 protocol [XENIX CORE]
3922 protocol [MICROSOFT NETWORKS 1.03]
3923 protocol [LANMAN1.0]
3924 protocol [Windows for Workgroups 3.1a]
3925 protocol [LM1.2X002]
3926 protocol [LANMAN2.1]
3927 protocol [NT LM 0.12]
3930 protocol [PC NETWORK PROGRAM 1.0]
3931 protocol [XENIX CORE]
3932 protocol [MICROSOFT NETWORKS 1.03]
3933 protocol [LANMAN1.0]
3934 protocol [Windows for Workgroups 3.1a]
3935 protocol [LM1.2X002]
3936 protocol [LANMAN2.1]
3937 protocol [NT LM 0.12]
3940 protocol [PC NETWORK PROGRAM 1.0]
3941 protocol [XENIX CORE]
3942 protocol [LANMAN1.0]
3943 protocol [LM1.2X002]
3944 protocol [LANMAN2.1]
3948 * Modified to recognize the architecture of the remote machine better.
3950 * This appears to be the matrix of which protocol is used by which
3952 Protocol WfWg Win95 WinNT OS/2
3953 PC NETWORK PROGRAM 1.0 1 1 1 1
3955 MICROSOFT NETWORKS 3.0 2 2
3957 MICROSOFT NETWORKS 1.03 3
3960 Windows for Workgroups 3.1a 5 5 5
3965 * tim@fsg.com 09/29/95
3968 #define ARCH_WFWG 0x3 /* This is a fudge because WfWg is like Win95 */
3969 #define ARCH_WIN95 0x2
3970 #define ARCH_OS2 0xC /* Again OS/2 is like NT */
3971 #define ARCH_WINNT 0x8
3972 #define ARCH_SAMBA 0x10
3974 #define ARCH_ALL 0x1F
3976 /* List of supported protocols, most desired first */
3980 int (*proto_reply_fn)(char *);
3982 } supported_protocols[] = {
3983 {"NT LANMAN 1.0", "NT1", reply_nt1, PROTOCOL_NT1},
3984 {"NT LM 0.12", "NT1", reply_nt1, PROTOCOL_NT1},
3985 {"LM1.2X002", "LANMAN2", reply_lanman2, PROTOCOL_LANMAN2},
3986 {"Samba", "LANMAN2", reply_lanman2, PROTOCOL_LANMAN2},
3987 {"DOS LM1.2X002", "LANMAN2", reply_lanman2, PROTOCOL_LANMAN2},
3988 {"LANMAN1.0", "LANMAN1", reply_lanman1, PROTOCOL_LANMAN1},
3989 {"MICROSOFT NETWORKS 3.0", "LANMAN1", reply_lanman1, PROTOCOL_LANMAN1},
3990 {"MICROSOFT NETWORKS 1.03", "COREPLUS", reply_coreplus, PROTOCOL_COREPLUS},
3991 {"PC NETWORK PROGRAM 1.0", "CORE", reply_corep, PROTOCOL_CORE},
3996 /****************************************************************************
3998 ****************************************************************************/
3999 static int reply_negprot(connection_struct *conn,
4000 char *inbuf,char *outbuf, int dum_size,
4003 int outsize = set_message(outbuf,1,0,True);
4008 int bcc = SVAL(smb_buf(inbuf),-2);
4009 int arch = ARCH_ALL;
4011 p = smb_buf(inbuf)+1;
4012 while (p < (smb_buf(inbuf) + bcc))
4015 DEBUG(3,("Requested protocol [%s]\n",p));
4016 if (strcsequal(p,"Windows for Workgroups 3.1a"))
4017 arch &= ( ARCH_WFWG | ARCH_WIN95 | ARCH_WINNT );
4018 else if (strcsequal(p,"DOS LM1.2X002"))
4019 arch &= ( ARCH_WFWG | ARCH_WIN95 );
4020 else if (strcsequal(p,"DOS LANMAN2.1"))
4021 arch &= ( ARCH_WFWG | ARCH_WIN95 );
4022 else if (strcsequal(p,"NT LM 0.12"))
4023 arch &= ( ARCH_WIN95 | ARCH_WINNT );
4024 else if (strcsequal(p,"LANMAN2.1"))
4025 arch &= ( ARCH_WINNT | ARCH_OS2 );
4026 else if (strcsequal(p,"LM1.2X002"))
4027 arch &= ( ARCH_WINNT | ARCH_OS2 );
4028 else if (strcsequal(p,"MICROSOFT NETWORKS 1.03"))
4030 else if (strcsequal(p,"XENIX CORE"))
4031 arch &= ( ARCH_WINNT | ARCH_OS2 );
4032 else if (strcsequal(p,"Samba")) {
4042 set_remote_arch(RA_SAMBA);
4045 set_remote_arch(RA_WFWG);
4048 set_remote_arch(RA_WIN95);
4051 set_remote_arch(RA_WINNT);
4054 set_remote_arch(RA_OS2);
4057 set_remote_arch(RA_UNKNOWN);
4061 /* possibly reload - change of architecture */
4062 reload_services(True);
4064 /* a special case to stop password server loops */
4065 if (Index == 1 && strequal(remote_machine,myhostname) &&
4066 (lp_security()==SEC_SERVER || lp_security()==SEC_DOMAIN))
4067 exit_server("Password server loop!");
4069 /* Check for protocols, most desirable first */
4070 for (protocol = 0; supported_protocols[protocol].proto_name; protocol++)
4072 p = smb_buf(inbuf)+1;
4074 if (lp_maxprotocol() >= supported_protocols[protocol].protocol_level)
4075 while (p < (smb_buf(inbuf) + bcc))
4077 if (strequal(p,supported_protocols[protocol].proto_name))
4086 SSVAL(outbuf,smb_vwv0,choice);
4088 extern fstring remote_proto;
4089 fstrcpy(remote_proto,supported_protocols[protocol].short_name);
4090 reload_services(True);
4091 outsize = supported_protocols[protocol].proto_reply_fn(outbuf);
4092 DEBUG(3,("Selected protocol %s\n",supported_protocols[protocol].proto_name));
4095 DEBUG(0,("No protocol supported !\n"));
4097 SSVAL(outbuf,smb_vwv0,choice);
4099 DEBUG( 5, ( "negprot index=%d\n", choice ) );
4105 /****************************************************************************
4107 ****************************************************************************/
4108 void close_cnum(connection_struct *conn, uint16 vuid)
4111 DirCacheFlush(SNUM(conn));
4116 DEBUG(0,("cnum not open\n"));
4120 DEBUG(IS_IPC(conn)?3:1, ("%s (%s) closed connection to service %s\n",
4121 remote_machine,client_addr(Client),
4122 lp_servicename(SNUM(conn))));
4124 yield_connection(conn,
4125 lp_servicename(SNUM(conn)),
4126 lp_max_connections(SNUM(conn)));
4128 if (lp_status(SNUM(conn)))
4129 yield_connection(conn,"STATUS.",MAXSTATUS);
4131 file_close_conn(conn);
4132 dptr_closecnum(conn);
4134 /* execute any "postexec = " line */
4135 if (*lp_postexec(SNUM(conn)) &&
4136 become_user(conn, vuid)) {
4138 pstrcpy(cmd,lp_postexec(SNUM(conn)));
4139 standard_sub(conn,cmd);
4140 smbrun(cmd,NULL,False);
4145 /* execute any "root postexec = " line */
4146 if (*lp_rootpostexec(SNUM(conn))) {
4148 pstrcpy(cmd,lp_rootpostexec(SNUM(conn)));
4149 standard_sub(conn,cmd);
4150 smbrun(cmd,NULL,False);
4154 num_connections_open--;
4155 if (conn->ngroups && conn->groups) {
4157 conn->groups = NULL;
4161 free_namearray(conn->veto_list);
4162 free_namearray(conn->hide_list);
4163 free_namearray(conn->veto_oplock_list);
4165 string_set(&conn->user,"");
4166 string_set(&conn->dirpath,"");
4167 string_set(&conn->connectpath,"");
4173 /*******************************************************************
4174 prepare to dump a core file - carefully!
4175 ********************************************************************/
4176 static BOOL dump_core(void)
4180 pstrcpy(dname,debugf);
4181 if ((p=strrchr(dname,'/'))) *p=0;
4182 pstrcat(dname,"/corefiles");
4184 sys_chown(dname,getuid(),getgid());
4186 if (chdir(dname)) return(False);
4189 #ifdef HAVE_GETRLIMIT
4193 getrlimit(RLIMIT_CORE, &rlp);
4194 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
4195 setrlimit(RLIMIT_CORE, &rlp);
4196 getrlimit(RLIMIT_CORE, &rlp);
4197 DEBUG(3,("Core limits now %d %d\n",(int)rlp.rlim_cur,(int)rlp.rlim_max));
4203 DEBUG(0,("Dumping core in %s\n",dname));
4209 /****************************************************************************
4211 ****************************************************************************/
4212 void exit_server(char *reason)
4214 static int firsttime=1;
4217 if (!firsttime) exit(0);
4221 DEBUG(2,("Closing connections\n"));
4222 for (i=0;i<MAX_CONNECTIONS;i++)
4223 if (Connections[i].open)
4224 close_cnum(&Connections[i],(uint16)-1);
4226 if (dcelogin_atmost_once) {
4231 int oldlevel = DEBUGLEVEL;
4233 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
4235 show_msg(last_inbuf);
4236 DEBUGLEVEL = oldlevel;
4237 DEBUG(0,("===============================================================\n"));
4239 if (dump_core()) return;
4245 DEBUG( 3, ( "Server exit (%s)\n", (reason ? reason : "") ) );
4250 These flags determine some of the permissions required to do an operation
4252 Note that I don't set NEED_WRITE on some write operations because they
4253 are used by some brain-dead clients when printing, and I don't want to
4254 force write permissions on print services.
4256 #define AS_USER (1<<0)
4257 #define NEED_WRITE (1<<1)
4258 #define TIME_INIT (1<<2)
4259 #define CAN_IPC (1<<3)
4260 #define AS_GUEST (1<<5)
4261 #define QUEUE_IN_OPLOCK (1<<6)
4264 define a list of possible SMB messages and their corresponding
4265 functions. Any message that has a NULL function is unimplemented -
4266 please feel free to contribute implementations!
4268 struct smb_message_struct
4272 int (*fn)(connection_struct *conn, char *, char *, int, int);
4282 {SMBnegprot,"SMBnegprot",reply_negprot,0},
4283 {SMBtcon,"SMBtcon",reply_tcon,0},
4284 {SMBtdis,"SMBtdis",reply_tdis,0},
4285 {SMBexit,"SMBexit",reply_exit,0},
4286 {SMBioctl,"SMBioctl",reply_ioctl,0},
4287 {SMBecho,"SMBecho",reply_echo,0},
4288 {SMBsesssetupX,"SMBsesssetupX",reply_sesssetup_and_X,0},
4289 {SMBtconX,"SMBtconX",reply_tcon_and_X,0},
4290 {SMBulogoffX, "SMBulogoffX", reply_ulogoffX, 0}, /* ulogoff doesn't give a valid TID */
4291 {SMBgetatr,"SMBgetatr",reply_getatr,AS_USER},
4292 {SMBsetatr,"SMBsetatr",reply_setatr,AS_USER | NEED_WRITE},
4293 {SMBchkpth,"SMBchkpth",reply_chkpth,AS_USER},
4294 {SMBsearch,"SMBsearch",reply_search,AS_USER},
4295 {SMBopen,"SMBopen",reply_open,AS_USER | QUEUE_IN_OPLOCK },
4297 /* note that SMBmknew and SMBcreate are deliberately overloaded */
4298 {SMBcreate,"SMBcreate",reply_mknew,AS_USER},
4299 {SMBmknew,"SMBmknew",reply_mknew,AS_USER},
4301 {SMBunlink,"SMBunlink",reply_unlink,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
4302 {SMBread,"SMBread",reply_read,AS_USER},
4303 {SMBwrite,"SMBwrite",reply_write,AS_USER},
4304 {SMBclose,"SMBclose",reply_close,AS_USER | CAN_IPC},
4305 {SMBmkdir,"SMBmkdir",reply_mkdir,AS_USER | NEED_WRITE},
4306 {SMBrmdir,"SMBrmdir",reply_rmdir,AS_USER | NEED_WRITE},
4307 {SMBdskattr,"SMBdskattr",reply_dskattr,AS_USER},
4308 {SMBmv,"SMBmv",reply_mv,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
4310 /* this is a Pathworks specific call, allowing the
4311 changing of the root path */
4312 {pSETDIR,"pSETDIR",reply_setdir,AS_USER},
4314 {SMBlseek,"SMBlseek",reply_lseek,AS_USER},
4315 {SMBflush,"SMBflush",reply_flush,AS_USER},
4316 {SMBctemp,"SMBctemp",reply_ctemp,AS_USER | QUEUE_IN_OPLOCK },
4317 {SMBsplopen,"SMBsplopen",reply_printopen,AS_USER | QUEUE_IN_OPLOCK },
4318 {SMBsplclose,"SMBsplclose",reply_printclose,AS_USER},
4319 {SMBsplretq,"SMBsplretq",reply_printqueue,AS_USER},
4320 {SMBsplwr,"SMBsplwr",reply_printwrite,AS_USER},
4321 {SMBlock,"SMBlock",reply_lock,AS_USER},
4322 {SMBunlock,"SMBunlock",reply_unlock,AS_USER},
4324 /* CORE+ PROTOCOL FOLLOWS */
4326 {SMBreadbraw,"SMBreadbraw",reply_readbraw,AS_USER},
4327 {SMBwritebraw,"SMBwritebraw",reply_writebraw,AS_USER},
4328 {SMBwriteclose,"SMBwriteclose",reply_writeclose,AS_USER},
4329 {SMBlockread,"SMBlockread",reply_lockread,AS_USER},
4330 {SMBwriteunlock,"SMBwriteunlock",reply_writeunlock,AS_USER},
4332 /* LANMAN1.0 PROTOCOL FOLLOWS */
4334 {SMBreadBmpx,"SMBreadBmpx",reply_readbmpx,AS_USER},
4335 {SMBreadBs,"SMBreadBs",NULL,AS_USER},
4336 {SMBwriteBmpx,"SMBwriteBmpx",reply_writebmpx,AS_USER},
4337 {SMBwriteBs,"SMBwriteBs",reply_writebs,AS_USER},
4338 {SMBwritec,"SMBwritec",NULL,AS_USER},
4339 {SMBsetattrE,"SMBsetattrE",reply_setattrE,AS_USER | NEED_WRITE},
4340 {SMBgetattrE,"SMBgetattrE",reply_getattrE,AS_USER},
4341 {SMBtrans,"SMBtrans",reply_trans,AS_USER | CAN_IPC},
4342 {SMBtranss,"SMBtranss",NULL,AS_USER | CAN_IPC},
4343 {SMBioctls,"SMBioctls",NULL,AS_USER},
4344 {SMBcopy,"SMBcopy",reply_copy,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
4345 {SMBmove,"SMBmove",NULL,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
4347 {SMBopenX,"SMBopenX",reply_open_and_X,AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
4348 {SMBreadX,"SMBreadX",reply_read_and_X,AS_USER | CAN_IPC },
4349 {SMBwriteX,"SMBwriteX",reply_write_and_X,AS_USER},
4350 {SMBlockingX,"SMBlockingX",reply_lockingX,AS_USER},
4352 {SMBffirst,"SMBffirst",reply_search,AS_USER},
4353 {SMBfunique,"SMBfunique",reply_search,AS_USER},
4354 {SMBfclose,"SMBfclose",reply_fclose,AS_USER},
4356 /* LANMAN2.0 PROTOCOL FOLLOWS */
4357 {SMBfindnclose, "SMBfindnclose", reply_findnclose, AS_USER},
4358 {SMBfindclose, "SMBfindclose", reply_findclose,AS_USER},
4359 {SMBtrans2, "SMBtrans2", reply_trans2, AS_USER },
4360 {SMBtranss2, "SMBtranss2", reply_transs2, AS_USER},
4362 /* NT PROTOCOL FOLLOWS */
4363 {SMBntcreateX, "SMBntcreateX", reply_ntcreate_and_X, AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
4364 {SMBnttrans, "SMBnttrans", reply_nttrans, AS_USER | CAN_IPC },
4365 {SMBnttranss, "SMBnttranss", reply_nttranss, AS_USER | CAN_IPC },
4366 {SMBntcancel, "SMBntcancel", reply_ntcancel, AS_USER },
4368 /* messaging routines */
4369 {SMBsends,"SMBsends",reply_sends,AS_GUEST},
4370 {SMBsendstrt,"SMBsendstrt",reply_sendstrt,AS_GUEST},
4371 {SMBsendend,"SMBsendend",reply_sendend,AS_GUEST},
4372 {SMBsendtxt,"SMBsendtxt",reply_sendtxt,AS_GUEST},
4374 /* NON-IMPLEMENTED PARTS OF THE CORE PROTOCOL */
4376 {SMBsendb,"SMBsendb",NULL,AS_GUEST},
4377 {SMBfwdname,"SMBfwdname",NULL,AS_GUEST},
4378 {SMBcancelf,"SMBcancelf",NULL,AS_GUEST},
4379 {SMBgetmac,"SMBgetmac",NULL,AS_GUEST}
4382 /****************************************************************************
4383 return a string containing the function name of a SMB command
4384 ****************************************************************************/
4385 char *smb_fn_name(int type)
4387 static char *unknown_name = "SMBunknown";
4388 static int num_smb_messages =
4389 sizeof(smb_messages) / sizeof(struct smb_message_struct);
4392 for (match=0;match<num_smb_messages;match++)
4393 if (smb_messages[match].code == type)
4396 if (match == num_smb_messages)
4397 return(unknown_name);
4399 return(smb_messages[match].name);
4403 /****************************************************************************
4404 do a switch on the message type, and return the response size
4405 ****************************************************************************/
4406 static int switch_message(int type,char *inbuf,char *outbuf,int size,int bufsize)
4410 static int num_smb_messages =
4411 sizeof(smb_messages) / sizeof(struct smb_message_struct);
4416 struct timeval msg_start_time;
4417 struct timeval msg_end_time;
4418 static unsigned long total_time = 0;
4420 GetTimeOfDay(&msg_start_time);
4427 last_message = type;
4429 /* make sure this is an SMB packet */
4430 if (strncmp(smb_base(inbuf),"\377SMB",4) != 0)
4432 DEBUG(2,("Non-SMB packet of length %d\n",smb_len(inbuf)));
4436 for (match=0;match<num_smb_messages;match++)
4437 if (smb_messages[match].code == type)
4440 if (match == num_smb_messages)
4442 DEBUG(0,("Unknown message type %d!\n",type));
4443 outsize = reply_unknown(inbuf,outbuf);
4447 DEBUG(3,("switch message %s (pid %d)\n",smb_messages[match].name,pid));
4449 if(global_oplock_break && (smb_messages[match].flags & QUEUE_IN_OPLOCK))
4452 * Queue this message as we are the process of an oplock break.
4455 DEBUG( 2, ( "switch_message: queueing message due to being in " ) );
4456 DEBUGADD( 2, ( "oplock break state.\n" ) );
4458 push_oplock_pending_smb_message( inbuf, size );
4462 if (smb_messages[match].fn)
4464 int cnum = SVAL(inbuf,smb_tid);
4465 int flags = smb_messages[match].flags;
4466 static uint16 last_session_tag = UID_FIELD_INVALID;
4467 /* In share mode security we must ignore the vuid. */
4468 uint16 session_tag = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : SVAL(inbuf,smb_uid);
4469 connection_struct *conn = NULL;
4471 if (VALID_CNUM(cnum) && Connections[cnum].open) {
4472 conn = &Connections[cnum];
4475 /* Ensure this value is replaced in the incoming packet. */
4476 SSVAL(inbuf,smb_uid,session_tag);
4479 * Ensure the correct username is in sesssetup_user.
4480 * This is a really ugly bugfix for problems with
4481 * multiple session_setup_and_X's being done and
4482 * allowing %U and %G substitutions to work correctly.
4483 * There is a reason this code is done here, don't
4484 * move it unless you know what you're doing... :-).
4487 if (session_tag != last_session_tag) {
4488 user_struct *vuser = NULL;
4490 last_session_tag = session_tag;
4491 if(session_tag != UID_FIELD_INVALID)
4492 vuser = get_valid_user_struct(session_tag);
4494 pstrcpy( sesssetup_user, vuser->requested_name);
4497 /* does this protocol need to be run as root? */
4498 if (!(flags & AS_USER))
4501 /* does this protocol need to be run as the connected user? */
4502 if ((flags & AS_USER) && !become_user(conn,session_tag)) {
4503 if (flags & AS_GUEST)
4506 return(ERROR(ERRSRV,ERRinvnid));
4508 /* this code is to work around a bug is MS client 3 without
4509 introducing a security hole - it needs to be able to do
4510 print queue checks as guest if it isn't logged in properly */
4511 if (flags & AS_USER)
4514 /* does it need write permission? */
4515 if ((flags & NEED_WRITE) && !CAN_WRITE(conn))
4516 return(ERROR(ERRSRV,ERRaccess));
4518 /* ipc services are limited */
4519 if (IS_IPC(conn) && (flags & AS_USER) && !(flags & CAN_IPC)) {
4520 return(ERROR(ERRSRV,ERRaccess));
4523 /* load service specific parameters */
4524 if (OPEN_CONN(conn) &&
4525 !become_service(conn,(flags & AS_USER)?True:False)) {
4526 return(ERROR(ERRSRV,ERRaccess));
4529 /* does this protocol need to be run as guest? */
4530 if ((flags & AS_GUEST) &&
4532 !check_access(Client, lp_hostsallow(-1), lp_hostsdeny(-1)))) {
4533 return(ERROR(ERRSRV,ERRaccess));
4538 outsize = smb_messages[match].fn(conn, inbuf,outbuf,size,bufsize);
4542 outsize = reply_unknown(inbuf,outbuf);
4547 GetTimeOfDay(&msg_end_time);
4548 if (!(smb_messages[match].flags & TIME_INIT))
4550 smb_messages[match].time = 0;
4551 smb_messages[match].flags |= TIME_INIT;
4554 unsigned long this_time =
4555 (msg_end_time.tv_sec - msg_start_time.tv_sec)*1e6 +
4556 (msg_end_time.tv_usec - msg_start_time.tv_usec);
4557 smb_messages[match].time += this_time;
4558 total_time += this_time;
4560 DEBUG(2,("TIME %s %d usecs %g pct\n",
4561 smb_fn_name(type),smb_messages[match].time,
4562 (100.0*smb_messages[match].time) / total_time));
4569 /****************************************************************************
4570 construct a chained reply and add it to the already made reply
4571 **************************************************************************/
4572 int chain_reply(char *inbuf,char *outbuf,int size,int bufsize)
4574 static char *orig_inbuf;
4575 static char *orig_outbuf;
4576 int smb_com1, smb_com2 = CVAL(inbuf,smb_vwv0);
4577 unsigned smb_off2 = SVAL(inbuf,smb_vwv1);
4578 char *inbuf2, *outbuf2;
4580 char inbuf_saved[smb_wct];
4581 char outbuf_saved[smb_wct];
4582 extern int chain_size;
4583 int wct = CVAL(outbuf,smb_wct);
4584 int outsize = smb_size + 2*wct + SVAL(outbuf,smb_vwv0+2*wct);
4586 /* maybe its not chained */
4587 if (smb_com2 == 0xFF) {
4588 CVAL(outbuf,smb_vwv0) = 0xFF;
4592 if (chain_size == 0) {
4593 /* this is the first part of the chain */
4595 orig_outbuf = outbuf;
4598 /* we need to tell the client where the next part of the reply will be */
4599 SSVAL(outbuf,smb_vwv1,smb_offset(outbuf+outsize,outbuf));
4600 CVAL(outbuf,smb_vwv0) = smb_com2;
4602 /* remember how much the caller added to the chain, only counting stuff
4603 after the parameter words */
4604 chain_size += outsize - smb_wct;
4606 /* work out pointers into the original packets. The
4607 headers on these need to be filled in */
4608 inbuf2 = orig_inbuf + smb_off2 + 4 - smb_wct;
4609 outbuf2 = orig_outbuf + SVAL(outbuf,smb_vwv1) + 4 - smb_wct;
4611 /* remember the original command type */
4612 smb_com1 = CVAL(orig_inbuf,smb_com);
4614 /* save the data which will be overwritten by the new headers */
4615 memcpy(inbuf_saved,inbuf2,smb_wct);
4616 memcpy(outbuf_saved,outbuf2,smb_wct);
4618 /* give the new packet the same header as the last part of the SMB */
4619 memmove(inbuf2,inbuf,smb_wct);
4621 /* create the in buffer */
4622 CVAL(inbuf2,smb_com) = smb_com2;
4624 /* create the out buffer */
4625 bzero(outbuf2,smb_size);
4626 set_message(outbuf2,0,0,True);
4627 CVAL(outbuf2,smb_com) = CVAL(inbuf2,smb_com);
4629 memcpy(outbuf2+4,inbuf2+4,4);
4630 CVAL(outbuf2,smb_rcls) = SMB_SUCCESS;
4631 CVAL(outbuf2,smb_reh) = 0;
4632 CVAL(outbuf2,smb_flg) = 0x80 | (CVAL(inbuf2,smb_flg) & 0x8); /* bit 7 set
4634 SSVAL(outbuf2,smb_flg2,1); /* say we support long filenames */
4635 SSVAL(outbuf2,smb_err,SMB_SUCCESS);
4636 SSVAL(outbuf2,smb_tid,SVAL(inbuf2,smb_tid));
4637 SSVAL(outbuf2,smb_pid,SVAL(inbuf2,smb_pid));
4638 SSVAL(outbuf2,smb_uid,SVAL(inbuf2,smb_uid));
4639 SSVAL(outbuf2,smb_mid,SVAL(inbuf2,smb_mid));
4641 DEBUG(3,("Chained message\n"));
4644 /* process the request */
4645 outsize2 = switch_message(smb_com2,inbuf2,outbuf2,size-chain_size,
4646 bufsize-chain_size);
4648 /* copy the new reply and request headers over the old ones, but
4649 preserve the smb_com field */
4650 memmove(orig_outbuf,outbuf2,smb_wct);
4651 CVAL(orig_outbuf,smb_com) = smb_com1;
4653 /* restore the saved data, being careful not to overwrite any
4654 data from the reply header */
4655 memcpy(inbuf2,inbuf_saved,smb_wct);
4657 int ofs = smb_wct - PTR_DIFF(outbuf2,orig_outbuf);
4658 if (ofs < 0) ofs = 0;
4659 memmove(outbuf2+ofs,outbuf_saved+ofs,smb_wct-ofs);
4666 /****************************************************************************
4667 Helper function for contruct_reply.
4668 ****************************************************************************/
4670 void construct_reply_common(char *inbuf,char *outbuf)
4672 bzero(outbuf,smb_size);
4674 CVAL(outbuf,smb_com) = CVAL(inbuf,smb_com);
4675 set_message(outbuf,0,0,True);
4677 memcpy(outbuf+4,inbuf+4,4);
4678 CVAL(outbuf,smb_rcls) = SMB_SUCCESS;
4679 CVAL(outbuf,smb_reh) = 0;
4680 CVAL(outbuf,smb_flg) = 0x80 | (CVAL(inbuf,smb_flg) & 0x8); /* bit 7 set
4682 SSVAL(outbuf,smb_flg2,1); /* say we support long filenames */
4683 SSVAL(outbuf,smb_err,SMB_SUCCESS);
4684 SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
4685 SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
4686 SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
4687 SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
4690 /****************************************************************************
4691 construct a reply to the incoming packet
4692 ****************************************************************************/
4693 int construct_reply(char *inbuf,char *outbuf,int size,int bufsize)
4695 int type = CVAL(inbuf,smb_com);
4697 int msg_type = CVAL(inbuf,0);
4698 extern int chain_size;
4700 smb_last_time = time(NULL);
4707 return(reply_special(inbuf,outbuf));
4709 construct_reply_common(inbuf, outbuf);
4711 outsize = switch_message(type,inbuf,outbuf,size,bufsize);
4713 outsize += chain_size;
4716 smb_setlen(outbuf,outsize - 4);
4720 /****************************************************************************
4721 process commands from the client
4722 ****************************************************************************/
4723 static void process(void)
4727 InBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
4728 OutBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
4729 if ((InBuffer == NULL) || (OutBuffer == NULL))
4732 InBuffer += SMB_ALIGNMENT;
4733 OutBuffer += SMB_ALIGNMENT;
4736 DEBUG(3,("priming nmbd\n"));
4739 ip = *interpret_addr2("localhost");
4740 if (zero_ip(ip)) ip = *interpret_addr2("127.0.0.1");
4742 send_one_packet(OutBuffer,1,ip,NMB_PORT,SOCK_DGRAM);
4746 /* re-initialise the timezone */
4751 int deadtime = lp_deadtime()*60;
4753 int last_keepalive=0;
4754 int service_load_counter = 0;
4755 BOOL got_smb = False;
4758 deadtime = DEFAULT_SMBD_TIMEOUT;
4760 #if USE_READ_PREDICTION
4761 if (lp_readprediction())
4762 do_read_prediction();
4767 for (counter=SMBD_SELECT_LOOP;
4768 !receive_message_or_smb(Client,oplock_sock,
4769 InBuffer,BUFFER_SIZE,SMBD_SELECT_LOOP*1000,&got_smb);
4770 counter += SMBD_SELECT_LOOP)
4774 BOOL allidle = True;
4775 extern int keepalive;
4777 if (counter > 365 * 3600) /* big number of seconds. */
4780 service_load_counter = 0;
4783 if (smb_read_error == READ_EOF)
4785 DEBUG(3,("end of file from client\n"));
4789 if (smb_read_error == READ_ERROR)
4791 DEBUG(3,("receive_smb error (%s) exiting\n",
4798 /* become root again if waiting */
4801 /* check for smb.conf reload */
4802 if (counter >= service_load_counter + SMBD_RELOAD_CHECK)
4804 service_load_counter = counter;
4806 /* reload services, if files have changed. */
4807 reload_services(True);
4811 * If reload_after_sighup == True then we got a SIGHUP
4812 * and are being asked to reload. Fix from <branko.cibej@hermes.si>
4815 if (reload_after_sighup)
4817 DEBUG(0,("Reloading services after SIGHUP\n"));
4818 reload_services(False);
4819 reload_after_sighup = False;
4822 /* automatic timeout if all connections are closed */
4823 if (num_connections_open==0 && counter >= IDLE_CLOSED_TIMEOUT)
4825 DEBUG( 2, ( "Closing idle connection\n" ) );
4829 if (keepalive && (counter-last_keepalive)>keepalive)
4831 struct cli_state *cli = server_client();
4832 if (!send_keepalive(Client)) {
4833 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
4836 /* also send a keepalive to the password server if its still
4838 if (cli && cli->initialised)
4839 send_keepalive(cli->fd);
4840 last_keepalive = counter;
4843 /* check for connection timeouts */
4844 for (i=0;i<MAX_CONNECTIONS;i++) {
4845 if (Connections[i].open) {
4846 /* close dirptrs on connections that are idle */
4847 if ((t-Connections[i].lastused)>DPTR_IDLE_TIMEOUT)
4848 dptr_idlecnum(&Connections[i]);
4850 if (Connections[i].num_files_open > 0 ||
4851 (t-Connections[i].lastused)<deadtime)
4856 if (allidle && num_connections_open>0) {
4857 DEBUG(2,("Closing idle connection 2.\n"));
4861 if(global_machine_pasword_needs_changing)
4863 unsigned char trust_passwd_hash[16];
4865 pstring remote_machine_list;
4868 * We're in domain level security, and the code that
4869 * read the machine password flagged that the machine
4870 * password needs changing.
4874 * First, open the machine password file with an exclusive lock.
4877 if(!trust_password_lock( global_myworkgroup, global_myname, True)) {
4878 DEBUG(0,("process: unable to open the machine account password file for \
4879 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
4883 if(!get_trust_account_password( trust_passwd_hash, &lct)) {
4884 DEBUG(0,("process: unable to read the machine account password for \
4885 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
4886 trust_password_unlock();
4891 * Make sure someone else hasn't already done this.
4894 if(t < lct + lp_machine_password_timeout()) {
4895 trust_password_unlock();
4896 global_machine_pasword_needs_changing = False;
4900 pstrcpy(remote_machine_list, lp_passwordserver());
4902 change_trust_account_password( global_myworkgroup, remote_machine_list);
4903 trust_password_unlock();
4904 global_machine_pasword_needs_changing = False;
4908 * Check to see if we have any change notifies
4909 * outstanding on the queue.
4911 process_pending_change_notify_queue(t);
4915 process_smb(InBuffer, OutBuffer);
4917 process_local_message(oplock_sock, InBuffer, BUFFER_SIZE);
4922 /****************************************************************************
4923 initialise connect, service and file structs
4924 ****************************************************************************/
4925 static void init_structs(void )
4928 get_myname(myhostname,NULL);
4931 * Set the machine NETBIOS name if not already
4932 * set from the config file.
4935 if (!*global_myname)
4938 fstrcpy( global_myname, myhostname );
4939 p = strchr( global_myname, '.' );
4943 strupper( global_myname );
4945 for (i=0;i<MAX_CONNECTIONS;i++)
4947 Connections[i].open = False;
4948 Connections[i].num_files_open=0;
4949 Connections[i].lastused=0;
4950 Connections[i].used=False;
4951 string_init(&Connections[i].user,"");
4952 string_init(&Connections[i].dirpath,"");
4953 string_init(&Connections[i].connectpath,"");
4954 string_init(&Connections[i].origpath,"");
4960 init_rpc_pipe_hnd();
4962 /* for LSA handles */
4963 init_lsa_policy_hnd();
4968 /****************************************************************************
4969 usage on the program
4970 ****************************************************************************/
4971 static void usage(char *pname)
4973 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
4975 printf("Usage: %s [-D] [-p port] [-d debuglevel] [-l log basename] [-s services file]\n",pname);
4976 printf("Version %s\n",VERSION);
4977 printf("\t-D become a daemon\n");
4978 printf("\t-p port listen on the specified port\n");
4979 printf("\t-d debuglevel set the debuglevel\n");
4980 printf("\t-l log basename. Basename for log/debug files\n");
4981 printf("\t-s services file. Filename of services file\n");
4982 printf("\t-P passive only\n");
4983 printf("\t-a overwrite log file, don't append\n");
4988 /****************************************************************************
4990 ****************************************************************************/
4991 int main(int argc,char *argv[])
4993 extern BOOL append_log;
4994 /* shall I run as a daemon */
4995 BOOL is_daemon = False;
4996 int port = SMB_PORT;
4998 extern char *optarg;
5000 #ifdef HAVE_SET_AUTH_PARAMETERS
5001 set_auth_parameters(argc,argv);
5005 /* needed for SecureWare on SCO */
5013 pstrcpy(debugf,SMBLOGFILE);
5015 pstrcpy(remote_machine, "smb");
5017 setup_logging(argv[0],False);
5019 charset_initialise();
5021 /* make absolutely sure we run as root - to handle cases where people
5022 are crazy enough to have it setuid */
5023 #ifdef HAVE_SETRESUID
5032 fault_setup((void (*)(void *))exit_server);
5033 CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
5035 /* we want total control over the permissions on created files,
5036 so set our umask to 0 */
5043 /* this is for people who can't start the program correctly */
5044 while (argc > 1 && (*argv[1] != '-'))
5050 while ((opt = getopt(argc, argv, "O:i:l:s:d:Dp:hPaf:")) != EOF)
5054 pstrcpy(user_socket_options,optarg);
5057 pstrcpy(scope,optarg);
5061 extern BOOL passive;
5066 pstrcpy(servicesf,optarg);
5069 pstrcpy(debugf,optarg);
5073 extern BOOL append_log;
5074 append_log = !append_log;
5084 DEBUGLEVEL = atoi(optarg);
5087 port = atoi(optarg);
5100 DEBUG( 1, ( "smbd version %s started.\n", VERSION ) );
5101 DEBUGADD( 1, ( "Copyright Andrew Tridgell 1992-1997\n" ) );
5103 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
5104 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
5106 if (sizeof(uint16) < 2 || sizeof(uint32) < 4)
5108 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
5114 if (!reload_services(False))
5119 extern BOOL sslEnabled;
5120 sslEnabled = lp_ssl_enabled();
5124 #endif /* WITH_SSL */
5126 codepage_initialise(lp_client_code_page());
5128 pstrcpy(global_myworkgroup, lp_workgroup());
5130 if(!pdb_generate_machine_sid()) {
5131 DEBUG(0,("ERROR: Samba cannot get a machine SID.\n"));
5135 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
5137 /* Setup the signals that allow the debug log level
5138 to by dynamically changed. */
5140 /* If we are using the malloc debug code we can't use
5141 SIGUSR1 and SIGUSR2 to do debug level changes. */
5144 #if defined(SIGUSR1)
5145 CatchSignal( SIGUSR1, SIGNAL_CAST sig_usr1 );
5146 #endif /* SIGUSR1 */
5148 #if defined(SIGUSR2)
5149 CatchSignal( SIGUSR2, SIGNAL_CAST sig_usr2 );
5150 #endif /* SIGUSR2 */
5151 #endif /* MEM_MAN */
5153 DEBUG( 3, ( "loaded services\n" ) );
5155 if (!is_daemon && !is_a_socket(0))
5157 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
5163 DEBUG( 3, ( "Becoming a daemon.\n" ) );
5167 if (!directory_exist(lp_lockdir(), NULL)) {
5168 mkdir(lp_lockdir(), 0755);
5172 pidfile_create("smbd");
5175 if (!open_sockets(is_daemon,port))
5178 if (!locking_init(0))
5181 if(!initialize_password_db())
5184 /* possibly reload the services file. */
5185 reload_services(True);
5187 max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
5191 if (sys_chroot(lp_rootdir()) == 0)
5192 DEBUG( 2, ( "Changed root to %s\n", lp_rootdir() ) );
5195 /* Setup the oplock IPC socket. */
5196 if( !open_oplock_ipc() )
5202 exit_server("normal exit");