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;
69 * Size of data we can send to client. Set
70 * by the client for all protocols above CORE.
71 * Set by us for CORE protocol.
73 int max_send = BUFFER_SIZE;
75 * Size of the data we can receive. Set by us.
76 * Can be modified by the max xmit parameter.
78 int max_recv = BUFFER_SIZE;
80 /* Oplock ipc UDP socket. */
82 uint16 oplock_port = 0;
83 /* Current number of oplocks we have outstanding. */
84 int32 global_oplocks_open = 0;
86 BOOL global_oplock_break = False;
88 extern fstring remote_machine;
90 extern pstring OriginalDir;
92 /* these can be set by some functions to override the error codes */
93 int unix_ERR_class=SMB_SUCCESS;
97 extern int extra_time_offset;
99 extern pstring myhostname;
101 /****************************************************************************
102 when exiting, take the whole family
103 ****************************************************************************/
106 exit_server("caught signal");
107 return 0; /* Keep -Wall happy :-) */
109 /****************************************************************************
110 Send a SIGTERM to our process group.
111 *****************************************************************************/
114 if(am_parent) kill(0,SIGTERM);
117 /*******************************************************************
118 Wrapper around sys_utime that possibly allows DOS semantics rather
120 *******************************************************************/
121 int file_utime(connection_struct *conn, char *fname, struct utimbuf *times)
123 extern struct current_user current_user;
129 if(sys_utime(fname, times) == 0)
132 if((errno != EPERM) && (errno != EACCES))
135 if(!lp_dos_filetimes(SNUM(conn)))
138 /* We have permission (given by the Samba admin) to
139 break POSIX semantics and allow a user to change
140 the time on a file they don't own but can write to
144 if(sys_stat(fname,&sb) != 0)
147 /* Check if we have write access. */
148 if (CAN_WRITE(conn)) {
149 if (((sb.st_mode & S_IWOTH) ||
151 ((sb.st_mode & S_IWUSR) && current_user.uid==sb.st_uid) ||
152 ((sb.st_mode & S_IWGRP) &&
153 in_group(sb.st_gid,current_user.gid,
154 current_user.ngroups,current_user.groups)))) {
155 /* We are allowed to become root and change the filetime. */
157 ret = sys_utime(fname, times);
158 unbecome_root(False);
165 /*******************************************************************
166 Change a filetime - possibly allowing DOS semantics.
167 *******************************************************************/
168 BOOL set_filetime(connection_struct *conn, char *fname, time_t mtime)
170 struct utimbuf times;
172 if (null_mtime(mtime)) return(True);
174 times.modtime = times.actime = mtime;
176 if (file_utime(conn, fname, ×)) {
177 DEBUG(4,("set_filetime(%s) failed: %s\n",fname,strerror(errno)));
184 /****************************************************************************
185 fd support routines - attempt to do a sys_open
186 ****************************************************************************/
187 static int fd_attempt_open(char *fname, int flags, int mode)
189 int fd = sys_open(fname,flags,mode);
191 /* Fix for files ending in '.' */
192 if((fd == -1) && (errno == ENOENT) &&
193 (strchr(fname,'.')==NULL))
196 fd = sys_open(fname,flags,mode);
199 #if (defined(ENAMETOOLONG) && defined(HAVE_PATHCONF))
200 if ((fd == -1) && (errno == ENAMETOOLONG))
203 char *p = strrchr(fname, '/');
205 if (p == fname) /* name is "/xxx" */
207 max_len = pathconf("/", _PC_NAME_MAX);
210 else if ((p == NULL) || (p == fname))
213 max_len = pathconf(".", _PC_NAME_MAX);
218 max_len = pathconf(fname, _PC_NAME_MAX);
222 if (strlen(p) > max_len)
224 char tmp = p[max_len];
227 if ((fd = sys_open(fname,flags,mode)) == -1)
235 /****************************************************************************
236 Cache a uid_t currently with this file open. This is an optimization only
237 used when multiple sessionsetup's have been done to one smbd.
238 ****************************************************************************/
239 void fd_add_to_uid_cache(file_fd_struct *fd_ptr, uid_t u)
241 if(fd_ptr->uid_cache_count >= sizeof(fd_ptr->uid_users_cache)/sizeof(uid_t))
243 fd_ptr->uid_users_cache[fd_ptr->uid_cache_count++] = u;
246 /****************************************************************************
247 Remove a uid_t that currently has this file open. This is an optimization only
248 used when multiple sessionsetup's have been done to one smbd.
249 ****************************************************************************/
250 static void fd_remove_from_uid_cache(file_fd_struct *fd_ptr, uid_t u)
253 for(i = 0; i < fd_ptr->uid_cache_count; i++)
254 if(fd_ptr->uid_users_cache[i] == u) {
255 if(i < (fd_ptr->uid_cache_count-1))
256 memmove((char *)&fd_ptr->uid_users_cache[i], (char *)&fd_ptr->uid_users_cache[i+1],
257 sizeof(uid_t)*(fd_ptr->uid_cache_count-1-i) );
258 fd_ptr->uid_cache_count--;
263 /****************************************************************************
264 Check if a uid_t that currently has this file open is present. This is an
265 optimization only used when multiple sessionsetup's have been done to one smbd.
266 ****************************************************************************/
267 static BOOL fd_is_in_uid_cache(file_fd_struct *fd_ptr, uid_t u)
270 for(i = 0; i < fd_ptr->uid_cache_count; i++)
271 if(fd_ptr->uid_users_cache[i] == u)
277 /****************************************************************************
278 fd support routines - attempt to re-open an already open fd as O_RDWR.
279 Save the already open fd (we cannot close due to POSIX file locking braindamage.
280 ****************************************************************************/
281 static void fd_attempt_reopen(char *fname, int mode, file_fd_struct *fd_ptr)
283 int fd = sys_open( fname, O_RDWR, mode);
288 if(fd_ptr->real_open_flags == O_RDONLY)
289 fd_ptr->fd_readonly = fd_ptr->fd;
290 if(fd_ptr->real_open_flags == O_WRONLY)
291 fd_ptr->fd_writeonly = fd_ptr->fd;
294 fd_ptr->real_open_flags = O_RDWR;
297 /****************************************************************************
298 fd support routines - attempt to close the file referenced by this fd.
299 Decrements the ref_count and returns it.
300 ****************************************************************************/
301 static int fd_attempt_close(file_fd_struct *fd_ptr)
303 extern struct current_user current_user;
305 DEBUG(3,("fd_attempt_close fd = %d, dev = %x, inode = %x, open_flags = %d, ref_count = %d.\n",
306 fd_ptr->fd, fd_ptr->dev, fd_ptr->inode,
307 fd_ptr->real_open_flags,
309 if(fd_ptr->ref_count > 0) {
311 if(fd_ptr->ref_count == 0) {
314 if(fd_ptr->fd_readonly != -1)
315 close(fd_ptr->fd_readonly);
316 if(fd_ptr->fd_writeonly != -1)
317 close(fd_ptr->fd_writeonly);
319 fd_ptr->fd_readonly = -1;
320 fd_ptr->fd_writeonly = -1;
321 fd_ptr->real_open_flags = -1;
322 fd_ptr->dev = (uint32)-1;
323 fd_ptr->inode = (uint32)-1;
324 fd_ptr->uid_cache_count = 0;
326 fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
329 return fd_ptr->ref_count;
332 /****************************************************************************
333 fd support routines - check that current user has permissions
334 to open this file. Used when uid not found in optimization cache.
335 This is really ugly code, as due to POSIX locking braindamage we must
336 fork and then attempt to open the file, and return success or failure
338 ****************************************************************************/
339 static BOOL check_access_allowed_for_current_user( char *fname, int accmode )
343 if((child_pid = fork()) < 0) {
344 DEBUG(0,("check_access_allowed_for_current_user: fork failed.\n"));
354 if ((wpid = sys_waitpid(child_pid, &status_code, 0)) < 0) {
355 DEBUG(0,("check_access_allowed_for_current_user: The process is no longer waiting!\n"));
359 if (child_pid != wpid) {
360 DEBUG(0,("check_access_allowed_for_current_user: We were waiting for the wrong process ID\n"));
363 #if defined(WIFEXITED) && defined(WEXITSTATUS)
364 if (WIFEXITED(status_code) == 0) {
365 DEBUG(0,("check_access_allowed_for_current_user: The process exited while we were waiting\n"));
368 if (WEXITSTATUS(status_code) != 0) {
369 DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access denied.\n", status_code));
372 #else /* defined(WIFEXITED) && defined(WEXITSTATUS) */
373 if(status_code != 0) {
374 DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access denied.\n", status_code));
377 #endif /* defined(WIFEXITED) && defined(WEXITSTATUS) */
380 * Success - the child could open the file.
382 DEBUG(9,("check_access_allowed_for_current_user: The status of the process exiting was %d. Returning access allowed.\n", status_code));
389 DEBUG(9,("check_access_allowed_for_current_user: Child - attempting to open %s with mode %d.\n", fname, accmode ));
390 if((fd = fd_attempt_open( fname, accmode, 0)) < 0) {
395 DEBUG(9,("check_access_allowed_for_current_user: Child - returning ok.\n"));
402 /****************************************************************************
403 check a filename for the pipe string
404 ****************************************************************************/
405 static void check_for_pipe(char *fname)
407 /* special case of pipe opens */
411 if (strstr(s,"pipe/")) {
412 DEBUG(3,("Rejecting named pipe open for %s\n",fname));
413 unix_ERR_class = ERRSRV;
414 unix_ERR_code = ERRaccess;
418 /****************************************************************************
420 ****************************************************************************/
421 static void open_file(files_struct *fsp,connection_struct *conn,
422 char *fname1,int flags,int mode, struct stat *sbuf)
424 extern struct current_user current_user;
427 file_fd_struct *fd_ptr;
428 int accmode = (flags & (O_RDONLY | O_WRONLY | O_RDWR));
432 fsp->granted_oplock = False;
435 pstrcpy(fname,fname1);
437 /* check permissions */
440 * This code was changed after seeing a client open request
441 * containing the open mode of (DENY_WRITE/read-only) with
442 * the 'create if not exist' bit set. The previous code
443 * would fail to open the file read only on a read-only share
444 * as it was checking the flags parameter directly against O_RDONLY,
445 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
449 if (conn->read_only && !conn->printer) {
450 /* It's a read-only share - fail if we wanted to write. */
451 if(accmode != O_RDONLY) {
452 DEBUG(3,("Permission denied opening %s\n",fname));
453 check_for_pipe(fname);
455 } else if(flags & O_CREAT) {
456 /* We don't want to write - but we must make sure that O_CREAT
457 doesn't create the file if we have write access into the
464 /* this handles a bug in Win95 - it doesn't say to create the file when it
471 if (flags == O_WRONLY)
472 DEBUG(3,("Bug in client? Set O_WRONLY without O_CREAT\n"));
476 * Ensure we have a valid struct stat so we can search the
480 if(sys_stat(fname, &statbuf) < 0) {
481 if(errno != ENOENT) {
482 DEBUG(3,("Error doing stat on file %s (%s)\n",
483 fname,strerror(errno)));
485 check_for_pipe(fname);
495 * Check to see if we have this file already
496 * open. If we do, just use the already open fd and increment the
497 * reference count (fd_get_already_open increments the ref_count).
499 if((fd_ptr = fd_get_already_open(sbuf))!= 0) {
501 * File was already open.
505 * Check it wasn't open for exclusive use.
507 if((flags & O_CREAT) && (flags & O_EXCL)) {
514 * Ensure that the user attempting to open
515 * this file has permissions to do so, if
516 * the user who originally opened the file wasn't
517 * the same as the current user.
520 if(!fd_is_in_uid_cache(fd_ptr, (uid_t)current_user.uid)) {
521 if(!check_access_allowed_for_current_user( fname, accmode )) {
522 /* Error - permission denied. */
523 DEBUG(3,("Permission denied opening file %s (flags=%d, accmode = %d)\n",
524 fname, flags, accmode));
525 /* Ensure the ref_count is decremented. */
527 fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
533 fd_add_to_uid_cache(fd_ptr, (uid_t)current_user.uid);
536 * If not opened O_RDWR try
537 * and do that here - a chmod may have been done
538 * between the last open and now.
540 if(fd_ptr->real_open_flags != O_RDWR)
541 fd_attempt_reopen(fname, mode, fd_ptr);
544 * Ensure that if we wanted write access
545 * it has been opened for write, and if we wanted read it
548 if(((accmode == O_WRONLY) && (fd_ptr->real_open_flags == O_RDONLY)) ||
549 ((accmode == O_RDONLY) && (fd_ptr->real_open_flags == O_WRONLY)) ||
550 ((accmode == O_RDWR) && (fd_ptr->real_open_flags != O_RDWR))) {
551 DEBUG(3,("Error opening (already open for flags=%d) file %s (%s) (flags=%d)\n",
552 fd_ptr->real_open_flags, fname,strerror(EACCES),flags));
553 check_for_pipe(fname);
554 fd_remove_from_uid_cache(fd_ptr, (uid_t)current_user.uid);
561 /* We need to allocate a new file_fd_struct (this increments the
563 if((fd_ptr = fd_get_new()) == 0)
566 * Whatever the requested flags, attempt read/write access,
567 * as we don't know what flags future file opens may require.
568 * If this fails, try again with the required flags.
569 * Even if we open read/write when only read access was
570 * requested the setting of the can_write flag in
571 * the file_struct will protect us from errant
572 * write requests. We never need to worry about O_APPEND
573 * as this is not set anywhere in Samba.
575 fd_ptr->real_open_flags = O_RDWR;
576 /* Set the flags as needed without the read/write modes. */
577 open_flags = flags & ~(O_RDWR|O_WRONLY|O_RDONLY);
578 fd_ptr->fd = fd_attempt_open(fname, open_flags|O_RDWR, mode);
580 * On some systems opening a file for R/W access on a read only
581 * filesystems sets errno to EROFS.
584 if((fd_ptr->fd == -1) && ((errno == EACCES) || (errno == EROFS))) {
586 if((fd_ptr->fd == -1) && (errno == EACCES)) {
588 if(accmode != O_RDWR) {
589 fd_ptr->fd = fd_attempt_open(fname, open_flags|accmode, mode);
590 fd_ptr->real_open_flags = accmode;
595 if ((fd_ptr->fd >=0) &&
596 conn->printer && lp_minprintspace(SNUM(conn))) {
600 pstrcpy(dname,fname);
601 p = strrchr(dname,'/');
603 if (sys_disk_free(dname,&dum1,&dum2,&dum3) <
604 lp_minprintspace(SNUM(conn))) {
605 fd_attempt_close(fd_ptr);
607 if(fd_ptr->ref_count == 0)
616 DEBUG(3,("Error opening file %s (%s) (flags=%d)\n",
617 fname,strerror(errno),flags));
618 /* Ensure the ref_count is decremented. */
619 fd_attempt_close(fd_ptr);
620 check_for_pipe(fname);
628 if(fstat(fd_ptr->fd, &statbuf) == -1) {
629 /* Error - backout !! */
630 DEBUG(3,("Error doing fstat on fd %d, file %s (%s)\n",
631 fd_ptr->fd, fname,strerror(errno)));
632 /* Ensure the ref_count is decremented. */
633 fd_attempt_close(fd_ptr);
639 /* Set the correct entries in fd_ptr. */
640 fd_ptr->dev = (uint32)sbuf->st_dev;
641 fd_ptr->inode = (uint32)sbuf->st_ino;
643 fsp->fd_ptr = fd_ptr;
644 conn->num_files_open++;
645 fsp->mode = sbuf->st_mode;
646 GetTimeOfDay(&fsp->open_time);
647 fsp->vuid = current_user.vuid;
651 fsp->mmap_ptr = NULL;
653 fsp->can_lock = True;
654 fsp->can_read = ((flags & O_WRONLY)==0);
655 fsp->can_write = ((flags & (O_WRONLY|O_RDWR))!=0);
657 fsp->print_file = conn->printer;
658 fsp->modified = False;
659 fsp->granted_oplock = False;
660 fsp->sent_oplock_break = False;
661 fsp->is_directory = False;
664 * Note that the file name here is the *untranslated* name
665 * ie. it is still in the DOS codepage sent from the client.
666 * All use of this filename will pass though the sys_xxxx
667 * functions which will do the dos_to_unix translation before
668 * mapping into a UNIX filename. JRA.
670 string_set(&fsp->fsp_name,fname);
671 fsp->wbmpx_ptr = NULL;
674 * If the printer is marked as postscript output a leading
675 * file identifier to ensure the file is treated as a raw
677 * This has a similar effect as CtrlD=0 in WIN.INI file.
678 * tim@fsg.com 09/06/94
680 if (fsp->print_file && lp_postscript(SNUM(conn)) && fsp->can_write) {
681 DEBUG(3,("Writing postscript line\n"));
682 write_file(fsp,"%!\n",3);
685 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
686 *sesssetup_user ? sesssetup_user : conn->user,fname,
687 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
688 conn->num_files_open));
693 /* mmap it if read-only */
694 if (!fsp->can_write) {
695 fsp->mmap_size = file_size(fname);
696 fsp->mmap_ptr = (char *)mmap(NULL,fsp->mmap_size,
697 PROT_READ,MAP_SHARED,fsp->fd_ptr->fd,0);
699 if (fsp->mmap_ptr == (char *)-1 || !fsp->mmap_ptr) {
700 DEBUG(3,("Failed to mmap() %s - %s\n",
701 fname,strerror(errno)));
702 fsp->mmap_ptr = NULL;
708 /****************************************************************************
709 run a file if it is a magic script
710 ****************************************************************************/
711 static void check_magic(files_struct *fsp,connection_struct *conn)
713 if (!*lp_magicscript(SNUM(conn)))
716 DEBUG(5,("checking magic for %s\n",fsp->fsp_name));
720 if (!(p = strrchr(fsp->fsp_name,'/')))
725 if (!strequal(lp_magicscript(SNUM(conn)),p))
731 pstring magic_output;
733 pstrcpy(fname,fsp->fsp_name);
735 if (*lp_magicoutput(SNUM(conn)))
736 pstrcpy(magic_output,lp_magicoutput(SNUM(conn)));
738 slprintf(magic_output,sizeof(fname)-1, "%s.out",fname);
741 ret = smbrun(fname,magic_output,False);
742 DEBUG(3,("Invoking magic command %s gave %d\n",fname,ret));
747 /****************************************************************************
748 Common code to close a file or a directory.
749 ****************************************************************************/
750 static void close_filestruct(files_struct *fsp)
752 connection_struct *conn = fsp->conn;
755 fsp->is_directory = False;
757 conn->num_files_open--;
759 free((char *)fsp->wbmpx_ptr);
760 fsp->wbmpx_ptr = NULL;
765 munmap(fsp->mmap_ptr,fsp->mmap_size);
766 fsp->mmap_ptr = NULL;
771 /****************************************************************************
772 Close a file - possibly invalidating the read prediction.
774 If normal_close is 1 then this came from a normal SMBclose (or equivalent)
775 operation otherwise it came as the result of some other operation such as
776 the closing of the connection. In the latter case printing and
777 magic scripts are not run.
778 ****************************************************************************/
779 void close_file(files_struct *fsp, BOOL normal_close)
781 uint32 dev = fsp->fd_ptr->dev;
782 uint32 inode = fsp->fd_ptr->inode;
784 connection_struct *conn = fsp->conn;
786 close_filestruct(fsp);
788 #if USE_READ_PREDICTION
789 invalidate_read_prediction(fsp->fd_ptr->fd);
792 if (lp_share_modes(SNUM(conn))) {
793 lock_share_entry(conn, dev, inode, &token);
794 del_share_mode(token, fsp);
797 fd_attempt_close(fsp->fd_ptr);
799 if (lp_share_modes(SNUM(conn)))
800 unlock_share_entry(conn, dev, inode, token);
802 /* NT uses smbclose to start a print - weird */
803 if (normal_close && fsp->print_file)
804 print_file(conn, fsp);
806 /* check for magic scripts */
808 check_magic(fsp,conn);
811 if(fsp->granted_oplock == True)
812 global_oplocks_open--;
814 fsp->sent_oplock_break = False;
816 DEBUG(2,("%s closed file %s (numopen=%d)\n",
817 conn->user,fsp->fsp_name,
818 conn->num_files_open));
821 string_free(&fsp->fsp_name);
827 /****************************************************************************
828 Close a directory opened by an NT SMB call.
829 ****************************************************************************/
831 void close_directory(files_struct *fsp)
833 /* TODO - walk the list of pending
834 change notify requests and free
835 any pertaining to this fsp. */
837 remove_pending_change_notify_requests_by_fid(fsp);
840 * Do the code common to files and directories.
842 close_filestruct(fsp);
845 string_free(&fsp->fsp_name);
850 /****************************************************************************
851 Open a directory from an NT SMB call.
852 ****************************************************************************/
853 int open_directory(files_struct *fsp,connection_struct *conn,
854 char *fname, int smb_ofun, int unixmode, int *action)
856 extern struct current_user current_user;
859 if (smb_ofun & 0x10) {
861 * Create the directory.
864 if(sys_mkdir(fname, unixmode) < 0) {
865 DEBUG(0,("open_directory: unable to create %s. Error was %s\n",
866 fname, strerror(errno) ));
870 *action = FILE_WAS_CREATED;
873 * Check that it *was* a directory.
876 if(sys_stat(fname, &st) < 0) {
877 DEBUG(0,("open_directory: unable to stat name = %s. Error was %s\n",
878 fname, strerror(errno) ));
882 if(!S_ISDIR(st.st_mode)) {
883 DEBUG(0,("open_directory: %s is not a directory !\n", fname ));
886 *action = FILE_WAS_OPENED;
889 DEBUG(5,("open_directory: opening directory %s\n",
893 * Setup the files_struct for it.
897 conn->num_files_open++;
899 GetTimeOfDay(&fsp->open_time);
900 fsp->vuid = current_user.vuid;
904 fsp->mmap_ptr = NULL;
906 fsp->can_lock = True;
907 fsp->can_read = False;
908 fsp->can_write = False;
910 fsp->print_file = False;
911 fsp->modified = False;
912 fsp->granted_oplock = False;
913 fsp->sent_oplock_break = False;
914 fsp->is_directory = True;
917 * Note that the file name here is the *untranslated* name
918 * ie. it is still in the DOS codepage sent from the client.
919 * All use of this filename will pass though the sys_xxxx
920 * functions which will do the dos_to_unix translation before
921 * mapping into a UNIX filename. JRA.
923 string_set(&fsp->fsp_name,fname);
924 fsp->wbmpx_ptr = NULL;
929 enum {AFAIL,AREAD,AWRITE,AALL};
931 /*******************************************************************
932 reproduce the share mode access table
933 ********************************************************************/
934 static int access_table(int new_deny,int old_deny,int old_mode,
935 int share_pid,char *fname)
937 if (new_deny == DENY_ALL || old_deny == DENY_ALL) return(AFAIL);
939 if (new_deny == DENY_DOS || old_deny == DENY_DOS) {
941 if (old_deny == new_deny && share_pid == pid)
944 if (old_mode == 0) return(AREAD);
946 /* the new smbpub.zip spec says that if the file extension is
947 .com, .dll, .exe or .sym then allow the open. I will force
948 it to read-only as this seems sensible although the spec is
949 a little unclear on this. */
950 if ((fname = strrchr(fname,'.'))) {
951 if (strequal(fname,".com") ||
952 strequal(fname,".dll") ||
953 strequal(fname,".exe") ||
954 strequal(fname,".sym"))
964 if (old_deny==DENY_WRITE && old_mode==0) return(AREAD);
965 if (old_deny==DENY_READ && old_mode==0) return(AWRITE);
966 if (old_deny==DENY_NONE && old_mode==0) return(AALL);
969 if (old_deny==DENY_WRITE && old_mode==1) return(AREAD);
970 if (old_deny==DENY_READ && old_mode==1) return(AWRITE);
971 if (old_deny==DENY_NONE && old_mode==1) return(AALL);
974 if (old_deny==DENY_WRITE) return(AREAD);
975 if (old_deny==DENY_READ) return(AWRITE);
976 if (old_deny==DENY_NONE) return(AALL);
982 /*******************************************************************
983 check if the share mode on a file allows it to be deleted or unlinked
984 return True if sharing doesn't prevent the operation
985 ********************************************************************/
986 BOOL check_file_sharing(connection_struct *conn,char *fname, BOOL rename_op)
990 share_mode_entry *old_shares = 0;
997 if(!lp_share_modes(SNUM(conn)))
1000 if (sys_stat(fname,&sbuf) == -1) return(True);
1002 dev = (uint32)sbuf.st_dev;
1003 inode = (uint32)sbuf.st_ino;
1005 lock_share_entry(conn, dev, inode, &token);
1006 num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1009 * Check if the share modes will give us access.
1012 if(num_share_modes != 0)
1019 broke_oplock = False;
1020 for(i = 0; i < num_share_modes; i++)
1022 share_mode_entry *share_entry = &old_shares[i];
1025 * Break oplocks before checking share modes. See comment in
1026 * open_file_shared for details.
1027 * Check if someone has an oplock on this file. If so we must
1028 * break it before continuing.
1030 if(share_entry->op_type & BATCH_OPLOCK)
1034 * It appears that the NT redirector may have a bug, in that
1035 * it tries to do an SMBmv on a file that it has open with a
1036 * batch oplock, and then fails to respond to the oplock break
1037 * request. This only seems to occur when the client is doing an
1038 * SMBmv to the smbd it is using - thus we try and detect this
1039 * condition by checking if the file being moved is open and oplocked by
1040 * this smbd process, and then not sending the oplock break in this
1041 * special case. If the file was open with a deny mode that
1042 * prevents the move the SMBmv will fail anyway with a share
1043 * violation error. JRA.
1045 if(rename_op && (share_entry->pid == pid))
1047 DEBUG(0,("check_file_sharing: NT redirector workaround - rename attempted on \
1048 batch oplocked file %s, dev = %x, inode = %x\n", fname, dev, inode));
1050 * This next line is a test that allows the deny-mode
1051 * processing to be skipped. This seems to be needed as
1052 * NT insists on the rename succeeding (in Office 9x no less !).
1053 * This should be removed as soon as (a) MS fix the redirector
1054 * bug or (b) NT SMB support in Samba makes NT not issue the
1055 * call (as is my fervent hope). JRA.
1061 DEBUG(5,("check_file_sharing: breaking oplock (%x) on file %s, \
1062 dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
1064 /* Oplock break.... */
1065 unlock_share_entry(conn, dev, inode, token);
1066 if(request_oplock_break(share_entry, dev, inode) == False)
1068 free((char *)old_shares);
1069 DEBUG(0,("check_file_sharing: FAILED when breaking oplock (%x) on file %s, \
1070 dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
1073 lock_share_entry(conn, dev, inode, &token);
1074 broke_oplock = True;
1079 /* someone else has a share lock on it, check to see
1081 if ((share_entry->share_mode != DENY_DOS) || (share_entry->pid != pid))
1088 free((char *)old_shares);
1089 num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1091 } while(broke_oplock);
1094 /* XXXX exactly what share mode combinations should be allowed for
1095 deleting/renaming? */
1096 /* If we got here then either there were no share modes or
1097 all share modes were DENY_DOS and the pid == getpid() */
1102 unlock_share_entry(conn, dev, inode, token);
1103 if(old_shares != NULL)
1104 free((char *)old_shares);
1108 /****************************************************************************
1110 Helper for open_file_shared.
1111 Truncate a file after checking locking; close file if locked.
1112 **************************************************************************/
1113 static void truncate_unless_locked(files_struct *fsp, connection_struct *conn, int token,
1116 if (fsp->can_write){
1117 if (is_locked(fsp,conn,0x3FFFFFFF,0,F_WRLCK)){
1118 /* If share modes are in force for this connection we
1119 have the share entry locked. Unlock it before closing. */
1120 if (*share_locked && lp_share_modes(SNUM(conn)))
1121 unlock_share_entry( conn, fsp->fd_ptr->dev,
1122 fsp->fd_ptr->inode, token);
1123 close_file(fsp,False);
1124 /* Share mode no longer locked. */
1125 *share_locked = False;
1127 unix_ERR_class = ERRDOS;
1128 unix_ERR_code = ERRlock;
1131 ftruncate(fsp->fd_ptr->fd,0);
1135 /****************************************************************************
1136 check if we can open a file with a share mode
1137 ****************************************************************************/
1138 int check_share_mode( share_mode_entry *share, int deny_mode, char *fname,
1139 BOOL fcbopen, int *flags)
1141 int old_open_mode = share->share_mode &0xF;
1142 int old_deny_mode = (share->share_mode >>4)&7;
1144 if (old_deny_mode > 4 || old_open_mode > 2)
1146 DEBUG(0,("Invalid share mode found (%d,%d,%d) on file %s\n",
1147 deny_mode,old_deny_mode,old_open_mode,fname));
1152 int access_allowed = access_table(deny_mode,old_deny_mode,old_open_mode,
1155 if ((access_allowed == AFAIL) ||
1156 (!fcbopen && (access_allowed == AREAD && *flags == O_RDWR)) ||
1157 (access_allowed == AREAD && *flags == O_WRONLY) ||
1158 (access_allowed == AWRITE && *flags == O_RDONLY))
1160 DEBUG(2,("Share violation on file (%d,%d,%d,%d,%s,fcbopen = %d, flags = %d) = %d\n",
1161 deny_mode,old_deny_mode,old_open_mode,
1162 share->pid,fname, fcbopen, *flags, access_allowed));
1166 if (access_allowed == AREAD)
1169 if (access_allowed == AWRITE)
1176 /****************************************************************************
1177 open a file with a share mode
1178 ****************************************************************************/
1179 void open_file_shared(files_struct *fsp,connection_struct *conn,char *fname,int share_mode,int ofun,
1180 int mode,int oplock_request, int *Access,int *action)
1184 int deny_mode = (share_mode>>4)&7;
1186 BOOL file_existed = file_exist(fname,&sbuf);
1187 BOOL share_locked = False;
1188 BOOL fcbopen = False;
1192 int num_share_modes = 0;
1197 /* this is for OS/2 EAs - try and say we don't support them */
1198 if (strstr(fname,".+,;=[]."))
1200 unix_ERR_class = ERRDOS;
1201 /* OS/2 Workplace shell fix may be main code stream in a later release. */
1202 #if 1 /* OS2_WPS_FIX - Recent versions of OS/2 need this. */
1203 unix_ERR_code = ERRcannotopen;
1204 #else /* OS2_WPS_FIX */
1205 unix_ERR_code = ERROR_EAS_NOT_SUPPORTED;
1206 #endif /* OS2_WPS_FIX */
1211 if ((ofun & 0x3) == 0 && file_existed)
1219 if ((ofun & 0x3) == 2)
1222 /* note that we ignore the append flag as
1223 append does not mean the same thing under dos and unix */
1225 switch (share_mode&0xF)
1243 if (share_mode&(1<<14)) {
1248 if (flags != O_RDONLY && file_existed &&
1249 (!CAN_WRITE(conn) || IS_DOS_READONLY(dos_mode(conn,fname,&sbuf))))
1259 if (deny_mode > DENY_NONE && deny_mode!=DENY_FCB)
1261 DEBUG(2,("Invalid deny mode %d on file %s\n",deny_mode,fname));
1266 if (deny_mode == DENY_FCB) deny_mode = DENY_DOS;
1268 if (lp_share_modes(SNUM(conn)))
1271 share_mode_entry *old_shares = 0;
1275 dev = (uint32)sbuf.st_dev;
1276 inode = (uint32)sbuf.st_ino;
1277 lock_share_entry(conn, dev, inode, &token);
1278 share_locked = True;
1279 num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1283 * Check if the share modes will give us access.
1286 if(share_locked && (num_share_modes != 0))
1293 broke_oplock = False;
1294 for(i = 0; i < num_share_modes; i++)
1296 share_mode_entry *share_entry = &old_shares[i];
1299 * By observation of NetBench, oplocks are broken *before* share
1300 * modes are checked. This allows a file to be closed by the client
1301 * if the share mode would deny access and the client has an oplock.
1302 * Check if someone has an oplock on this file. If so we must break
1303 * it before continuing.
1305 if(share_entry->op_type & (EXCLUSIVE_OPLOCK|BATCH_OPLOCK))
1308 DEBUG(5,("open_file_shared: breaking oplock (%x) on file %s, \
1309 dev = %x, inode = %x\n", share_entry->op_type, fname, dev, inode));
1311 /* Oplock break.... */
1312 unlock_share_entry(conn, dev, inode, token);
1313 if(request_oplock_break(share_entry, dev, inode) == False)
1315 free((char *)old_shares);
1316 DEBUG(0,("open_file_shared: FAILED when breaking oplock (%x) on file %s, \
1317 dev = %x, inode = %x\n", old_shares[i].op_type, fname, dev, inode));
1319 unix_ERR_class = ERRDOS;
1320 unix_ERR_code = ERRbadshare;
1323 lock_share_entry(conn, dev, inode, &token);
1324 broke_oplock = True;
1328 /* someone else has a share lock on it, check to see
1330 if(check_share_mode(share_entry, deny_mode, fname, fcbopen, &flags) == False)
1332 free((char *)old_shares);
1333 unlock_share_entry(conn, dev, inode, token);
1335 unix_ERR_class = ERRDOS;
1336 unix_ERR_code = ERRbadshare;
1344 free((char *)old_shares);
1345 num_share_modes = get_share_modes(conn, token, dev, inode, &old_shares);
1347 } while(broke_oplock);
1351 free((char *)old_shares);
1354 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o\n",
1355 flags,flags2,mode));
1357 open_file(fsp,conn,fname,flags|(flags2&~(O_TRUNC)),mode,file_existed ? &sbuf : 0);
1358 if (!fsp->open && flags==O_RDWR && errno!=ENOENT && fcbopen)
1361 open_file(fsp,conn,fname,flags,mode,file_existed ? &sbuf : 0 );
1368 if((share_locked == False) && lp_share_modes(SNUM(conn)))
1370 /* We created the file - thus we must now lock the share entry before creating it. */
1371 dev = fsp->fd_ptr->dev;
1372 inode = fsp->fd_ptr->inode;
1373 lock_share_entry(conn, dev, inode, &token);
1374 share_locked = True;
1390 fsp->share_mode = (deny_mode<<4) | open_mode;
1393 (*Access) = open_mode;
1397 if (file_existed && !(flags2 & O_TRUNC)) *action = FILE_WAS_OPENED;
1398 if (!file_existed) *action = FILE_WAS_CREATED;
1399 if (file_existed && (flags2 & O_TRUNC)) *action = FILE_WAS_OVERWRITTEN;
1401 /* We must create the share mode entry before truncate as
1402 truncate can fail due to locking and have to close the
1403 file (which expects the share_mode_entry to be there).
1405 if (lp_share_modes(SNUM(conn)))
1408 /* JRA. Currently this only services Exlcusive and batch
1409 oplocks (no other opens on this file). This needs to
1410 be extended to level II oplocks (multiple reader
1413 if(oplock_request && (num_share_modes == 0) && lp_oplocks(SNUM(conn)) &&
1414 !IS_VETO_OPLOCK_PATH(conn,fname))
1416 fsp->granted_oplock = True;
1417 fsp->sent_oplock_break = False;
1418 global_oplocks_open++;
1421 DEBUG(5,("open_file_shared: granted oplock (%x) on file %s, \
1422 dev = %x, inode = %x\n", oplock_request, fname, dev, inode));
1430 set_share_mode(token, fsp, port, oplock_request);
1433 if ((flags2&O_TRUNC) && file_existed)
1434 truncate_unless_locked(fsp,conn,token,&share_locked);
1437 if (share_locked && lp_share_modes(SNUM(conn)))
1438 unlock_share_entry( conn, dev, inode, token);
1442 /****************************************************************************
1443 load parameters specific to a connection/service
1444 ****************************************************************************/
1445 BOOL become_service(connection_struct *conn,BOOL do_chdir)
1447 extern char magic_char;
1448 static connection_struct *last_conn;
1456 conn->lastused = smb_last_time;
1461 ChDir(conn->connectpath) != 0 &&
1462 ChDir(conn->origpath) != 0) {
1463 DEBUG(0,("chdir (%s) failed\n",
1464 conn->connectpath));
1468 if (conn == last_conn)
1473 case_default = lp_defaultcase(snum);
1474 case_preserve = lp_preservecase(snum);
1475 short_case_preserve = lp_shortpreservecase(snum);
1476 case_mangle = lp_casemangle(snum);
1477 case_sensitive = lp_casesensitive(snum);
1478 magic_char = lp_magicchar(snum);
1479 use_mangled_map = (*lp_mangled_map(snum) ? True:False);
1484 /****************************************************************************
1485 find a service entry
1486 ****************************************************************************/
1487 int find_service(char *service)
1491 string_sub(service,"\\","/");
1493 iService = lp_servicenumber(service);
1495 /* now handle the special case of a home directory */
1498 char *phome_dir = get_home_dir(service);
1503 * Try mapping the servicename, it may
1504 * be a Windows to unix mapped user name.
1506 if(map_username(service))
1507 phome_dir = get_home_dir(service);
1510 DEBUG(3,("checking for home directory %s gave %s\n",service,
1511 phome_dir?phome_dir:"(NULL)"));
1516 if ((iHomeService = lp_servicenumber(HOMES_NAME)) >= 0)
1518 lp_add_home(service,iHomeService,phome_dir);
1519 iService = lp_servicenumber(service);
1524 /* If we still don't have a service, attempt to add it as a printer. */
1527 int iPrinterService;
1529 if ((iPrinterService = lp_servicenumber(PRINTERS_NAME)) >= 0)
1533 DEBUG(3,("checking whether %s is a valid printer name...\n", service));
1535 if ((pszTemp != NULL) && pcap_printername_ok(service, pszTemp))
1537 DEBUG(3,("%s is a valid printer name\n", service));
1538 DEBUG(3,("adding %s as a printer service\n", service));
1539 lp_add_printer(service,iPrinterService);
1540 iService = lp_servicenumber(service);
1542 DEBUG(0,("failed to add %s as a printer service!\n", service));
1545 DEBUG(3,("%s is not a valid printer name\n", service));
1549 /* just possibly it's a default service? */
1552 char *pdefservice = lp_defaultservice();
1553 if (pdefservice && *pdefservice && !strequal(pdefservice,service))
1556 * We need to do a local copy here as lp_defaultservice()
1557 * returns one of the rotating lp_string buffers that
1558 * could get overwritten by the recursive find_service() call
1559 * below. Fix from Josef Hinteregger <joehtg@joehtg.co.at>.
1562 pstrcpy(defservice, pdefservice);
1563 iService = find_service(defservice);
1566 string_sub(service,"_","/");
1567 iService = lp_add_service(service,iService);
1573 if (!VALID_SNUM(iService))
1575 DEBUG(0,("Invalid snum %d for %s\n",iService,service));
1580 DEBUG(3,("find_service() failed to find service %s\n", service));
1586 /****************************************************************************
1587 create an error packet from a cached error.
1588 ****************************************************************************/
1589 int cached_error_packet(char *inbuf,char *outbuf,files_struct *fsp,int line)
1591 write_bmpx_struct *wbmpx = fsp->wbmpx_ptr;
1593 int32 eclass = wbmpx->wr_errclass;
1594 int32 err = wbmpx->wr_error;
1596 /* We can now delete the auxiliary struct */
1597 free((char *)wbmpx);
1598 fsp->wbmpx_ptr = NULL;
1599 return error_packet(inbuf,outbuf,eclass,err,line);
1608 } unix_smb_errmap[] =
1610 {EPERM,ERRDOS,ERRnoaccess},
1611 {EACCES,ERRDOS,ERRnoaccess},
1612 {ENOENT,ERRDOS,ERRbadfile},
1613 {ENOTDIR,ERRDOS,ERRbadpath},
1614 {EIO,ERRHRD,ERRgeneral},
1615 {EBADF,ERRSRV,ERRsrverror},
1616 {EINVAL,ERRSRV,ERRsrverror},
1617 {EEXIST,ERRDOS,ERRfilexists},
1618 {ENFILE,ERRDOS,ERRnofids},
1619 {EMFILE,ERRDOS,ERRnofids},
1620 {ENOSPC,ERRHRD,ERRdiskfull},
1622 {EDQUOT,ERRHRD,ERRdiskfull},
1625 {ENOTEMPTY,ERRDOS,ERRnoaccess},
1628 {EXDEV,ERRDOS,ERRdiffdevice},
1630 {EROFS,ERRHRD,ERRnowrite},
1634 /****************************************************************************
1635 create an error packet from errno
1636 ****************************************************************************/
1637 int unix_error_packet(char *inbuf,char *outbuf,int def_class,uint32 def_code,int line)
1639 int eclass=def_class;
1643 if (unix_ERR_class != SMB_SUCCESS)
1645 eclass = unix_ERR_class;
1646 ecode = unix_ERR_code;
1647 unix_ERR_class = SMB_SUCCESS;
1652 while (unix_smb_errmap[i].smbclass != 0)
1654 if (unix_smb_errmap[i].unixerror == errno)
1656 eclass = unix_smb_errmap[i].smbclass;
1657 ecode = unix_smb_errmap[i].smbcode;
1664 return(error_packet(inbuf,outbuf,eclass,ecode,line));
1668 /****************************************************************************
1669 create an error packet. Normally called using the ERROR() macro
1670 ****************************************************************************/
1671 int error_packet(char *inbuf,char *outbuf,int error_class,uint32 error_code,int line)
1673 int outsize = set_message(outbuf,0,0,True);
1674 int cmd = CVAL(inbuf,smb_com);
1675 int flgs2 = SVAL(outbuf,smb_flg2);
1677 if ((flgs2 & FLAGS2_32_BIT_ERROR_CODES) == FLAGS2_32_BIT_ERROR_CODES)
1679 SIVAL(outbuf,smb_rcls,error_code);
1681 DEBUG( 3, ( "32 bit error packet at line %d cmd=%d (%s) eclass=%08x [%s]\n",
1682 line, cmd, smb_fn_name(cmd), error_code, smb_errstr(outbuf) ) );
1686 CVAL(outbuf,smb_rcls) = error_class;
1687 SSVAL(outbuf,smb_err,error_code);
1688 DEBUG( 3, ( "error packet at line %d cmd=%d (%s) eclass=%d ecode=%d\n",
1690 (int)CVAL(inbuf,smb_com),
1691 smb_fn_name(CVAL(inbuf,smb_com)),
1698 DEBUG(3,("error string = %s\n",strerror(errno)));
1704 /****************************************************************************
1705 this is called when the client exits abruptly
1706 **************************************************************************/
1707 static void sig_pipe(int sig)
1709 struct cli_state *cli;
1710 BlockSignals(True,SIGPIPE);
1712 if ((cli = server_client()) && cli->initialised) {
1713 DEBUG(3,("lost connection to password server\n"));
1715 BlockSignals(False,SIGPIPE);
1719 exit_server("Got sigpipe\n");
1722 /****************************************************************************
1723 open the socket communication
1724 ****************************************************************************/
1725 static BOOL open_sockets(BOOL is_daemon,int port)
1731 int num_interfaces = iface_count();
1732 int fd_listenset[FD_SETSIZE];
1738 static int atexit_set;
1739 if(atexit_set == 0) {
1749 FD_ZERO(&listen_set);
1751 if(lp_interfaces() && lp_bind_interfaces_only())
1753 /* We have been given an interfaces line, and been
1754 told to only bind to those interfaces. Create a
1755 socket per interface and bind to only these.
1758 if(num_interfaces > FD_SETSIZE)
1760 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
1761 max can be %d\n", num_interfaces, FD_SETSIZE));
1765 /* Now open a listen socket for each of the interfaces. */
1766 for(i = 0; i < num_interfaces; i++)
1768 struct in_addr *ifip = iface_n_ip(i);
1772 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
1775 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr);
1778 /* ready to listen */
1779 if (listen(s, 5) == -1)
1781 DEBUG(0,("listen: %s\n",strerror(errno)));
1785 FD_SET(s,&listen_set);
1790 /* Just bind to 0.0.0.0 - accept connections from anywhere. */
1793 /* open an incoming socket */
1794 s = open_socket_in(SOCK_STREAM, port, 0,interpret_addr(lp_socket_address()));
1798 /* ready to listen */
1799 if (listen(s, 5) == -1)
1801 DEBUG(0,("open_sockets: listen: %s\n",strerror(errno)));
1806 fd_listenset[0] = s;
1807 FD_SET(s,&listen_set);
1810 /* now accept incoming connections - forking a new process
1811 for each incoming connection */
1812 DEBUG(2,("waiting for a connection\n"));
1818 memcpy((char *)&lfds, (char *)&listen_set, sizeof(listen_set));
1820 num = sys_select(&lfds,NULL);
1822 if (num == -1 && errno == EINTR)
1825 /* Find the sockets that are read-ready - accept on these. */
1826 for( ; num > 0; num--)
1828 struct sockaddr addr;
1829 int in_addrlen = sizeof(addr);
1832 for(i = 0; i < num_interfaces; i++)
1834 if(FD_ISSET(fd_listenset[i],&lfds))
1836 s = fd_listenset[i];
1837 /* Clear this so we don't look at it again. */
1838 FD_CLR(fd_listenset[i],&lfds);
1843 Client = accept(s,&addr,&in_addrlen);
1845 if (Client == -1 && errno == EINTR)
1850 DEBUG(0,("open_sockets: accept: %s\n",strerror(errno)));
1854 if (Client != -1 && fork()==0)
1856 /* Child code ... */
1858 CatchSignal(SIGPIPE, SIGNAL_CAST sig_pipe);
1860 /* close the listening socket(s) */
1861 for(i = 0; i < num_interfaces; i++)
1862 close(fd_listenset[i]);
1864 /* close our standard file descriptors */
1868 set_socket_options(Client,"SO_KEEPALIVE");
1869 set_socket_options(Client,user_socket_options);
1871 /* Reset global variables in util.c so that
1872 client substitutions will be done correctly
1875 reset_globals_after_fork();
1878 close(Client); /* The parent doesn't need this socket */
1881 * Force parent to check log size after spawning child.
1882 * Fix from klausr@ITAP.Physik.Uni-Stuttgart.De.
1883 * The parent smbd will log to logserver.smb.
1884 * It writes only two messages for each child
1885 * started/finished. But each child writes, say, 50 messages also in
1886 * logserver.smb, begining with the debug_count of the parent, before the
1887 * child opens its own log file logserver.client. In a worst case
1888 * scenario the size of logserver.smb would be checked after about
1889 * 50*50=2500 messages (ca. 100kb).
1891 force_check_log_size();
1895 } /* end if is_daemon */
1898 /* Started from inetd. fd 0 is the socket. */
1899 /* We will abort gracefully when the client or remote system
1901 CatchSignal(SIGPIPE, SIGNAL_CAST sig_pipe);
1904 /* close our standard file descriptors */
1907 set_socket_options(Client,"SO_KEEPALIVE");
1908 set_socket_options(Client,user_socket_options);
1914 /****************************************************************************
1915 process an smb from the client - split out from the process() code so
1916 it can be used by the oplock break code.
1917 ****************************************************************************/
1919 static void process_smb(char *inbuf, char *outbuf)
1923 extern BOOL sslEnabled; /* don't use function for performance reasons */
1924 static int sslConnected = 0;
1925 #endif /* WITH_SSL */
1926 static int trans_num;
1927 int msg_type = CVAL(inbuf,0);
1928 int32 len = smb_len(inbuf);
1929 int nread = len + 4;
1931 if (trans_num == 0) {
1932 /* on the first packet, check the global hosts allow/ hosts
1933 deny parameters before doing any parsing of the packet
1934 passed to us by the client. This prevents attacks on our
1935 parsing code from hosts not in the hosts allow list */
1936 if (!check_access(Client, lp_hostsallow(-1), lp_hostsdeny(-1))) {
1937 /* send a negative session response "not listining on calling
1939 static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
1940 DEBUG( 1, ( "Connection denied from %s\n",
1941 client_addr(Client) ) );
1942 send_smb(Client,(char *)buf);
1943 exit_server("connection denied");
1947 DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type, len ) );
1948 DEBUG( 3, ( "Transaction %d of length %d\n", trans_num, nread ) );
1951 if(sslEnabled && !sslConnected){
1952 sslConnected = sslutil_negotiate_ssl(Client, msg_type);
1953 if(sslConnected < 0){ /* an error occured */
1954 exit_server("SSL negotiation failed");
1955 }else if(sslConnected){
1960 #endif /* WITH_SSL */
1963 if(trans_num == 1 && VT_Check(inbuf))
1972 else if(msg_type == 0x85)
1973 return; /* Keepalive packet. */
1975 nread = construct_reply(inbuf,outbuf,nread,max_send);
1979 if (CVAL(outbuf,0) == 0)
1982 if (nread != smb_len(outbuf) + 4)
1984 DEBUG(0,("ERROR: Invalid message response size! %d %d\n",
1985 nread, smb_len(outbuf)));
1988 send_smb(Client,outbuf);
1993 /****************************************************************************
1994 open the oplock IPC socket communication
1995 ****************************************************************************/
1996 static BOOL open_oplock_ipc(void)
1998 struct sockaddr_in sock_name;
1999 int len = sizeof(sock_name);
2001 DEBUG(3,("open_oplock_ipc: opening loopback UDP socket.\n"));
2003 /* Open a lookback UDP socket on a random port. */
2004 oplock_sock = open_socket_in(SOCK_DGRAM, 0, 0, htonl(INADDR_LOOPBACK));
2005 if (oplock_sock == -1)
2007 DEBUG(0,("open_oplock_ipc: Failed to get local UDP socket for \
2008 address %x. Error was %s\n", htonl(INADDR_LOOPBACK), strerror(errno)));
2013 /* Find out the transient UDP port we have been allocated. */
2014 if(getsockname(oplock_sock, (struct sockaddr *)&sock_name, &len)<0)
2016 DEBUG(0,("open_oplock_ipc: Failed to get local UDP port. Error was %s\n",
2023 oplock_port = ntohs(sock_name.sin_port);
2025 DEBUG(3,("open_oplock ipc: pid = %d, oplock_port = %u\n",
2026 (int)getpid(), oplock_port));
2031 /****************************************************************************
2032 process an oplock break message.
2033 ****************************************************************************/
2034 static BOOL process_local_message(int sock, char *buffer, int buf_size)
2040 msg_len = IVAL(buffer,UDP_CMD_LEN_OFFSET);
2041 from_port = SVAL(buffer,UDP_CMD_PORT_OFFSET);
2043 msg_start = &buffer[UDP_CMD_HEADER_LEN];
2045 DEBUG(5,("process_local_message: Got a message of length %d from port (%d)\n",
2046 msg_len, from_port));
2048 /* Switch on message command - currently OPLOCK_BREAK_CMD is the
2049 only valid request. */
2051 switch(SVAL(msg_start,UDP_MESSAGE_CMD_OFFSET))
2053 case OPLOCK_BREAK_CMD:
2054 /* Ensure that the msg length is correct. */
2055 if(msg_len != OPLOCK_BREAK_MSG_LEN)
2057 DEBUG(0,("process_local_message: incorrect length for OPLOCK_BREAK_CMD (was %d, \
2058 should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
2062 uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
2063 uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
2064 uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
2065 struct timeval tval;
2066 struct sockaddr_in toaddr;
2068 tval.tv_sec = IVAL(msg_start, OPLOCK_BREAK_SEC_OFFSET);
2069 tval.tv_usec = IVAL(msg_start, OPLOCK_BREAK_USEC_OFFSET);
2071 DEBUG(5,("process_local_message: oplock break request from \
2072 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
2075 * If we have no record of any currently open oplocks,
2076 * it's not an error, as a close command may have
2077 * just been issued on the file that was oplocked.
2078 * Just return success in this case.
2081 if(global_oplocks_open != 0)
2083 if(oplock_break(dev, inode, &tval) == False)
2085 DEBUG(0,("process_local_message: oplock break failed - \
2086 not returning udp message.\n"));
2092 DEBUG(3,("process_local_message: oplock break requested with no outstanding \
2093 oplocks. Returning success.\n"));
2096 /* Send the message back after OR'ing in the 'REPLY' bit. */
2097 SSVAL(msg_start,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD | CMD_REPLY);
2099 bzero((char *)&toaddr,sizeof(toaddr));
2100 toaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2101 toaddr.sin_port = htons(from_port);
2102 toaddr.sin_family = AF_INET;
2104 if(sendto( sock, msg_start, OPLOCK_BREAK_MSG_LEN, 0,
2105 (struct sockaddr *)&toaddr, sizeof(toaddr)) < 0)
2107 DEBUG(0,("process_local_message: sendto process %d failed. Errno was %s\n",
2108 remotepid, strerror(errno)));
2112 DEBUG(5,("process_local_message: oplock break reply sent to \
2113 pid %d, port %d, for file dev = %x, inode = %x\n", remotepid,
2114 from_port, dev, inode));
2119 * Keep this as a debug case - eventually we can remove it.
2122 DEBUG(0,("process_local_message: Received unsolicited break \
2123 reply - dumping info.\n"));
2125 if(msg_len != OPLOCK_BREAK_MSG_LEN)
2127 DEBUG(0,("process_local_message: ubr: incorrect length for reply \
2128 (was %d, should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
2133 uint32 remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
2134 uint32 dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
2135 uint32 inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
2137 DEBUG(0,("process_local_message: unsolicited oplock break reply from \
2138 pid %d, port %d, dev = %x, inode = %x\n", remotepid, from_port, dev, inode));
2144 DEBUG(0,("process_local_message: unknown UDP message command code (%x) - ignoring.\n",
2145 (unsigned int)SVAL(msg_start,0)));
2151 /****************************************************************************
2152 Process an oplock break directly.
2153 ****************************************************************************/
2154 BOOL oplock_break(uint32 dev, uint32 inode, struct timeval *tval)
2156 extern struct current_user current_user;
2159 char *outbuf = NULL;
2160 files_struct *fsp = NULL;
2162 BOOL shutdown_server = False;
2163 connection_struct *saved_conn;
2169 dbgtext( "oplock_break: called for dev = %x, inode = %x.\n", dev, inode );
2170 dbgtext( "Current global_oplocks_open = %d\n", global_oplocks_open );
2173 /* We need to search the file open table for the
2174 entry containing this dev and inode, and ensure
2175 we have an oplock on it. */
2176 fsp = file_find_dit(dev, inode, tval);
2180 /* The file could have been closed in the meantime - return success. */
2183 dbgtext( "oplock_break: cannot find open file with " );
2184 dbgtext( "dev = %x, inode = %x ", dev, inode);
2185 dbgtext( "allowing break to succeed.\n" );
2190 /* Ensure we have an oplock on the file */
2192 /* There is a potential race condition in that an oplock could
2193 have been broken due to another udp request, and yet there are
2194 still oplock break messages being sent in the udp message
2195 queue for this file. So return true if we don't have an oplock,
2196 as we may have just freed it.
2199 if(!fsp->granted_oplock)
2203 dbgtext( "oplock_break: file %s ", fsp->fsp_name );
2204 dbgtext( "(dev = %x, inode = %x) has no oplock.\n", dev, inode );
2205 dbgtext( "Allowing break to succeed regardless.\n" );
2210 /* mark the oplock break as sent - we don't want to send twice! */
2211 if (fsp->sent_oplock_break)
2215 dbgtext( "oplock_break: ERROR: oplock_break already sent for " );
2216 dbgtext( "file %s ", fsp->fsp_name);
2217 dbgtext( "(dev = %x, inode = %x)\n", dev, inode );
2220 /* We have to fail the open here as we cannot send another oplock break on
2221 this file whilst we are awaiting a response from the client - neither
2222 can we allow another open to succeed while we are waiting for the
2228 /* Now comes the horrid part. We must send an oplock break to the client,
2229 and then process incoming messages until we get a close or oplock release.
2230 At this point we know we need a new inbuf/outbuf buffer pair.
2231 We cannot use these staticaly as we may recurse into here due to
2232 messages crossing on the wire.
2235 if((inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
2237 DEBUG(0,("oplock_break: malloc fail for input buffer.\n"));
2241 if((outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
2243 DEBUG(0,("oplock_break: malloc fail for output buffer.\n"));
2249 /* Prepare the SMBlockingX message. */
2250 bzero(outbuf,smb_size);
2251 set_message(outbuf,8,0,True);
2253 SCVAL(outbuf,smb_com,SMBlockingX);
2254 SSVAL(outbuf,smb_tid,fsp->conn->cnum);
2255 SSVAL(outbuf,smb_pid,0xFFFF);
2256 SSVAL(outbuf,smb_uid,0);
2257 SSVAL(outbuf,smb_mid,0xFFFF);
2258 SCVAL(outbuf,smb_vwv0,0xFF);
2259 SSVAL(outbuf,smb_vwv2,fsp->fnum);
2260 SCVAL(outbuf,smb_vwv3,LOCKING_ANDX_OPLOCK_RELEASE);
2261 /* Change this when we have level II oplocks. */
2262 SCVAL(outbuf,smb_vwv3+1,OPLOCKLEVEL_NONE);
2264 send_smb(Client, outbuf);
2266 /* Remember we just sent an oplock break on this file. */
2267 fsp->sent_oplock_break = True;
2269 /* We need this in case a readraw crosses on the wire. */
2270 global_oplock_break = True;
2272 /* Process incoming messages. */
2274 /* JRA - If we don't get a break from the client in OPLOCK_BREAK_TIMEOUT
2275 seconds we should just die.... */
2277 start_time = time(NULL);
2280 * Save the information we need to re-become the
2281 * user, then unbecome the user whilst we're doing this.
2283 saved_conn = fsp->conn;
2284 saved_vuid = current_user.vuid;
2288 while(OPEN_FSP(fsp) && fsp->granted_oplock)
2290 if(receive_smb(Client,inbuf,OPLOCK_BREAK_TIMEOUT * 1000) == False)
2293 * Die if we got an error.
2296 if (smb_read_error == READ_EOF)
2297 DEBUG( 0, ( "oplock_break: end of file from client\n" ) );
2299 if (smb_read_error == READ_ERROR)
2300 DEBUG( 0, ("oplock_break: receive_smb error (%s)\n", strerror(errno)) );
2302 if (smb_read_error == READ_TIMEOUT)
2303 DEBUG( 0, ( "oplock_break: receive_smb timed out after %d seconds.\n",
2304 OPLOCK_BREAK_TIMEOUT ) );
2306 DEBUGADD( 0, ( "oplock_break failed for file %s ", fsp->fsp_name ) );
2307 DEBUGADD( 0, ( "(dev = %x, inode = %x).\n", dev, inode));
2308 shutdown_server = True;
2313 * There are certain SMB requests that we shouldn't allow
2314 * to recurse. opens, renames and deletes are the obvious
2315 * ones. This is handled in the switch_message() function.
2316 * If global_oplock_break is set they will push the packet onto
2317 * the pending smb queue and return -1 (no reply).
2321 process_smb(inbuf, outbuf);
2324 * Die if we go over the time limit.
2327 if((time(NULL) - start_time) > OPLOCK_BREAK_TIMEOUT)
2331 dbgtext( "oplock_break: no break received from client " );
2332 dbgtext( "within %d seconds.\n", OPLOCK_BREAK_TIMEOUT );
2333 dbgtext( "oplock_break failed for file %s ", fsp->fsp_name );
2334 dbgtext( "(dev = %x, inode = %x).\n", dev, inode );
2336 shutdown_server = True;
2342 * Go back to being the user who requested the oplock
2345 if(!become_user(saved_conn, saved_vuid))
2347 DEBUG( 0, ( "oplock_break: unable to re-become user!" ) );
2348 DEBUGADD( 0, ( "Shutting down server\n" ) );
2351 exit_server("unable to re-become user");
2353 /* Including the directory. */
2356 /* Free the buffers we've been using to recurse. */
2360 /* We need this in case a readraw crossed on the wire. */
2361 if(global_oplock_break)
2362 global_oplock_break = False;
2365 * If the client did not respond we must die.
2370 DEBUG( 0, ( "oplock_break: client failure in break - " ) );
2371 DEBUGADD( 0, ( "shutting down this smbd.\n" ) );
2374 exit_server("oplock break failure");
2379 /* The lockingX reply will have removed the oplock flag
2380 from the sharemode. */
2382 fsp->granted_oplock = False;
2383 fsp->sent_oplock_break = False;
2384 global_oplocks_open--;
2387 /* Santity check - remove this later. JRA */
2388 if(global_oplocks_open < 0)
2390 DEBUG(0,("oplock_break: global_oplocks_open < 0 (%d). PANIC ERROR\n",
2391 global_oplocks_open));
2392 exit_server("oplock_break: global_oplocks_open < 0");
2397 dbgtext( "oplock_break: returning success for " );
2398 dbgtext( "dev = %x, inode = %x.\n", dev, inode );
2399 dbgtext( "Current global_oplocks_open = %d\n", global_oplocks_open );
2405 /****************************************************************************
2406 Send an oplock break message to another smbd process. If the oplock is held
2407 by the local smbd then call the oplock break function directly.
2408 ****************************************************************************/
2410 BOOL request_oplock_break(share_mode_entry *share_entry,
2411 uint32 dev, uint32 inode)
2413 char op_break_msg[OPLOCK_BREAK_MSG_LEN];
2414 struct sockaddr_in addr_out;
2419 if(pid == share_entry->pid)
2421 /* We are breaking our own oplock, make sure it's us. */
2422 if(share_entry->op_port != oplock_port)
2424 DEBUG(0,("request_oplock_break: corrupt share mode entry - pid = %d, port = %d \
2425 should be %d\n", pid, share_entry->op_port, oplock_port));
2429 DEBUG(5,("request_oplock_break: breaking our own oplock\n"));
2431 /* Call oplock break direct. */
2432 return oplock_break(dev, inode, &share_entry->time);
2435 /* We need to send a OPLOCK_BREAK_CMD message to the
2436 port in the share mode entry. */
2438 SSVAL(op_break_msg,UDP_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD);
2439 SIVAL(op_break_msg,OPLOCK_BREAK_PID_OFFSET,pid);
2440 SIVAL(op_break_msg,OPLOCK_BREAK_DEV_OFFSET,dev);
2441 SIVAL(op_break_msg,OPLOCK_BREAK_INODE_OFFSET,inode);
2442 SIVAL(op_break_msg,OPLOCK_BREAK_SEC_OFFSET,(uint32)share_entry->time.tv_sec);
2443 SIVAL(op_break_msg,OPLOCK_BREAK_USEC_OFFSET,(uint32)share_entry->time.tv_usec);
2445 /* set the address and port */
2446 bzero((char *)&addr_out,sizeof(addr_out));
2447 addr_out.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2448 addr_out.sin_port = htons( share_entry->op_port );
2449 addr_out.sin_family = AF_INET;
2453 dbgtext( "request_oplock_break: sending a oplock break message to " );
2454 dbgtext( "pid %d on port %d ", share_entry->pid, share_entry->op_port );
2455 dbgtext( "for dev = %x, inode = %x\n", dev, inode );
2458 if(sendto(oplock_sock,op_break_msg,OPLOCK_BREAK_MSG_LEN,0,
2459 (struct sockaddr *)&addr_out,sizeof(addr_out)) < 0)
2463 dbgtext( "request_oplock_break: failed when sending a oplock " );
2464 dbgtext( "break message to pid %d ", share_entry->pid );
2465 dbgtext( "on port %d ", share_entry->op_port );
2466 dbgtext( "for dev = %x, inode = %x.\n", dev, inode );
2467 dbgtext( "Error was %s\n", strerror(errno) );
2473 * Now we must await the oplock broken message coming back
2474 * from the target smbd process. Timeout if it fails to
2475 * return in (OPLOCK_BREAK_TIMEOUT + OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR) seconds.
2476 * While we get messages that aren't ours, loop.
2479 start_time = time(NULL);
2480 time_left = OPLOCK_BREAK_TIMEOUT+OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR;
2482 while(time_left >= 0)
2484 char op_break_reply[UDP_CMD_HEADER_LEN+OPLOCK_BREAK_MSG_LEN];
2485 int32 reply_msg_len;
2486 uint16 reply_from_port;
2487 char *reply_msg_start;
2489 if(receive_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply),
2490 time_left ? time_left * 1000 : 1) == False)
2492 if(smb_read_error == READ_TIMEOUT)
2496 dbgtext( "request_oplock_break: no response received to oplock " );
2497 dbgtext( "break request to pid %d ", share_entry->pid );
2498 dbgtext( "on port %d ", share_entry->op_port );
2499 dbgtext( "for dev = %x, inode = %x\n", dev, inode );
2502 * This is a hack to make handling of failing clients more robust.
2503 * If a oplock break response message is not received in the timeout
2504 * period we may assume that the smbd servicing that client holding
2505 * the oplock has died and the client changes were lost anyway, so
2506 * we should continue to try and open the file.
2513 dbgtext( "request_oplock_break: error in response received " );
2514 dbgtext( "to oplock break request to pid %d ", share_entry->pid );
2515 dbgtext( "on port %d ", share_entry->op_port );
2516 dbgtext( "for dev = %x, inode = %x.\n", dev, inode );
2517 dbgtext( "Error was (%s).\n", strerror(errno) );
2522 reply_msg_len = IVAL(op_break_reply,UDP_CMD_LEN_OFFSET);
2523 reply_from_port = SVAL(op_break_reply,UDP_CMD_PORT_OFFSET);
2525 reply_msg_start = &op_break_reply[UDP_CMD_HEADER_LEN];
2527 if(reply_msg_len != OPLOCK_BREAK_MSG_LEN)
2530 DEBUG( 0, ( "request_oplock_break: invalid message length received." ) );
2531 DEBUGADD( 0, ( " Ignoring.\n" ) );
2536 * Test to see if this is the reply we are awaiting.
2539 if((SVAL(reply_msg_start,UDP_MESSAGE_CMD_OFFSET) & CMD_REPLY) &&
2540 (reply_from_port == share_entry->op_port) &&
2541 (memcmp(&reply_msg_start[OPLOCK_BREAK_PID_OFFSET],
2542 &op_break_msg[OPLOCK_BREAK_PID_OFFSET],
2543 OPLOCK_BREAK_MSG_LEN - OPLOCK_BREAK_PID_OFFSET) == 0))
2546 * This is the reply we've been waiting for.
2553 * This is another message - probably a break request.
2554 * Process it to prevent potential deadlock.
2555 * Note that the code in switch_message() prevents
2556 * us from recursing into here as any SMB requests
2557 * we might process that would cause another oplock
2558 * break request to be made will be queued.
2562 process_local_message(oplock_sock, op_break_reply, sizeof(op_break_reply));
2565 time_left -= (time(NULL) - start_time);
2568 DEBUG(3,("request_oplock_break: broke oplock.\n"));
2573 /****************************************************************************
2574 Get the next SMB packet, doing the local message processing automatically.
2575 ****************************************************************************/
2577 BOOL receive_next_smb(int smbfd, int oplockfd, char *inbuf, int bufsize, int timeout)
2579 BOOL got_smb = False;
2584 ret = receive_message_or_smb(smbfd,oplockfd,inbuf,bufsize,
2589 /* Deal with oplock break requests from other smbd's. */
2590 process_local_message(oplock_sock, inbuf, bufsize);
2594 if(ret && (CVAL(inbuf,0) == 0x85))
2596 /* Keepalive packet. */
2601 while(ret && !got_smb);
2606 /****************************************************************************
2607 reload the services file
2608 **************************************************************************/
2609 BOOL reload_services(BOOL test)
2615 pstrcpy(fname,lp_configfile());
2616 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
2617 pstrcpy(servicesf,fname);
2624 if (test && !lp_file_list_changed())
2627 lp_killunused(conn_snum_used);
2629 ret = lp_load(servicesf,False,False,True);
2633 /* perhaps the config filename is now set */
2635 reload_services(True);
2644 set_socket_options(Client,"SO_KEEPALIVE");
2645 set_socket_options(Client,user_socket_options);
2649 reset_mangled_cache();
2651 /* this forces service parameters to be flushed */
2652 become_service(NULL,True);
2659 /****************************************************************************
2660 this prevents zombie child processes
2661 ****************************************************************************/
2662 static BOOL reload_after_sighup = False;
2664 static void sig_hup(int sig)
2666 BlockSignals(True,SIGHUP);
2667 DEBUG(0,("Got SIGHUP\n"));
2670 * Fix from <branko.cibej@hermes.si> here.
2671 * We used to reload in the signal handler - this
2675 reload_after_sighup = True;
2676 BlockSignals(False,SIGHUP);
2680 /****************************************************************************
2681 make a connection to a service
2682 ****************************************************************************/
2683 connection_struct *make_connection(char *service,char *user,char *password, int pwlen, char *dev,uint16 vuid, int *ecode)
2686 struct passwd *pass = NULL;
2690 connection_struct *conn;
2694 snum = find_service(service);
2697 if (strequal(service,"IPC$")) {
2698 DEBUG(3,("refusing IPC connection\n"));
2703 DEBUG(0,("%s (%s) couldn't find service %s\n",
2704 remote_machine, client_addr(Client), service));
2705 *ecode = ERRinvnetname;
2709 if (strequal(service,HOMES_NAME)) {
2710 if (*user && Get_Pwnam(user,True))
2711 return(make_connection(user,user,password,
2712 pwlen,dev,vuid,ecode));
2714 if(lp_security() != SEC_SHARE) {
2715 if (validated_username(vuid)) {
2716 pstrcpy(user,validated_username(vuid));
2717 return(make_connection(user,user,password,pwlen,dev,vuid,ecode));
2720 /* Security = share. Try with sesssetup_user
2721 * as the username. */
2722 if(*sesssetup_user) {
2723 pstrcpy(user,sesssetup_user);
2724 return(make_connection(user,user,password,pwlen,dev,vuid,ecode));
2729 if (!lp_snum_ok(snum) ||
2730 !check_access(Client,
2731 lp_hostsallow(snum), lp_hostsdeny(snum))) {
2736 /* you can only connect to the IPC$ service as an ipc device */
2737 if (strequal(service,"IPC$"))
2740 if (*dev == '?' || !*dev) {
2741 if (lp_print_ok(snum)) {
2742 pstrcpy(dev,"LPT1:");
2748 /* if the request is as a printer and you can't print then refuse */
2750 if (!lp_print_ok(snum) && (strncmp(dev,"LPT",3) == 0)) {
2751 DEBUG(1,("Attempt to connect to non-printer as a printer\n"));
2752 *ecode = ERRinvdevice;
2756 /* lowercase the user name */
2759 /* add it as a possible user name */
2760 add_session_user(service);
2762 /* shall we let them in? */
2763 if (!authorise_login(snum,user,password,pwlen,&guest,&force,vuid)) {
2764 DEBUG( 2, ( "Invalid username/password for %s\n", service ) );
2771 DEBUG(0,("Couldn't find free connection.\n"));
2772 *ecode = ERRnoresource;
2777 /* find out some info about the user */
2778 pass = Get_Pwnam(user,True);
2781 DEBUG(0,( "Couldn't find account %s\n",user));
2787 conn->read_only = lp_readonly(snum);
2791 StrnCpy(list,lp_readlist(snum),sizeof(pstring)-1);
2792 string_sub(list,"%S",service);
2794 if (user_in_list(user,list))
2795 conn->read_only = True;
2797 StrnCpy(list,lp_writelist(snum),sizeof(pstring)-1);
2798 string_sub(list,"%S",service);
2800 if (user_in_list(user,list))
2801 conn->read_only = False;
2804 /* admin user check */
2806 /* JRA - original code denied admin user if the share was
2807 marked read_only. Changed as I don't think this is needed,
2808 but old code left in case there is a problem here.
2810 if (user_in_list(user,lp_admin_users(snum))
2815 conn->admin_user = True;
2816 DEBUG(0,("%s logged in as admin user (root privileges)\n",user));
2818 conn->admin_user = False;
2821 conn->force_user = force;
2823 conn->uid = pass->pw_uid;
2824 conn->gid = pass->pw_gid;
2825 conn->num_files_open = 0;
2826 conn->lastused = time(NULL);
2827 conn->service = snum;
2829 conn->printer = (strncmp(dev,"LPT",3) == 0);
2830 conn->ipc = (strncmp(dev,"IPC",3) == 0);
2831 conn->dirptr = NULL;
2832 conn->veto_list = NULL;
2833 conn->hide_list = NULL;
2834 conn->veto_oplock_list = NULL;
2835 string_set(&conn->dirpath,"");
2836 string_set(&conn->user,user);
2838 #ifdef HAVE_GETGRNAM
2839 if (*lp_force_group(snum)) {
2843 StrnCpy(gname,lp_force_group(snum),sizeof(pstring)-1);
2844 /* default service may be a group name */
2845 string_sub(gname,"%S",service);
2846 gptr = (struct group *)getgrnam(gname);
2849 conn->gid = gptr->gr_gid;
2850 DEBUG(3,("Forced group %s\n",gname));
2852 DEBUG(1,("Couldn't find group %s\n",gname));
2857 if (*lp_force_user(snum)) {
2858 struct passwd *pass2;
2860 fstrcpy(fuser,lp_force_user(snum));
2861 pass2 = (struct passwd *)Get_Pwnam(fuser,True);
2863 conn->uid = pass2->pw_uid;
2864 string_set(&conn->user,fuser);
2865 fstrcpy(user,fuser);
2866 conn->force_user = True;
2867 DEBUG(3,("Forced user %s\n",fuser));
2869 DEBUG(1,("Couldn't find user %s\n",fuser));
2875 pstrcpy(s,lp_pathname(snum));
2876 standard_sub(conn,s);
2877 string_set(&conn->connectpath,s);
2878 DEBUG(3,("Connect path is %s\n",s));
2881 /* groups stuff added by ih */
2883 conn->groups = NULL;
2885 if (!IS_IPC(conn)) {
2886 /* Find all the groups this uid is in and
2887 store them. Used by become_user() */
2888 setup_groups(conn->user,conn->uid,conn->gid,
2889 &conn->ngroups,&conn->groups);
2891 /* check number of connections */
2892 if (!claim_connection(conn,
2893 lp_servicename(SNUM(conn)),
2894 lp_max_connections(SNUM(conn)),
2896 DEBUG(1,("too many connections - rejected\n"));
2897 *ecode = ERRnoresource;
2902 if (lp_status(SNUM(conn)))
2903 claim_connection(conn,"STATUS.",
2907 /* execute any "root preexec = " line */
2908 if (*lp_rootpreexec(SNUM(conn))) {
2910 pstrcpy(cmd,lp_rootpreexec(SNUM(conn)));
2911 standard_sub(conn,cmd);
2912 DEBUG(5,("cmd=%s\n",cmd));
2913 smbrun(cmd,NULL,False);
2916 if (!become_user(conn, conn->vuid)) {
2917 DEBUG(0,("Can't become connected user!\n"));
2918 if (!IS_IPC(conn)) {
2919 yield_connection(conn,
2920 lp_servicename(SNUM(conn)),
2921 lp_max_connections(SNUM(conn)));
2922 if (lp_status(SNUM(conn))) {
2923 yield_connection(conn,"STATUS.",MAXSTATUS);
2931 if (ChDir(conn->connectpath) != 0) {
2932 DEBUG(0,("Can't change directory to %s (%s)\n",
2933 conn->connectpath,strerror(errno)));
2935 if (!IS_IPC(conn)) {
2936 yield_connection(conn,
2937 lp_servicename(SNUM(conn)),
2938 lp_max_connections(SNUM(conn)));
2939 if (lp_status(SNUM(conn)))
2940 yield_connection(conn,"STATUS.",MAXSTATUS);
2943 *ecode = ERRinvnetname;
2947 string_set(&conn->origpath,conn->connectpath);
2949 #if SOFTLINK_OPTIMISATION
2950 /* resolve any soft links early */
2953 pstrcpy(s,conn->connectpath);
2955 string_set(&conn->connectpath,s);
2956 ChDir(conn->connectpath);
2960 add_session_user(user);
2962 /* execute any "preexec = " line */
2963 if (*lp_preexec(SNUM(conn))) {
2965 pstrcpy(cmd,lp_preexec(SNUM(conn)));
2966 standard_sub(conn,cmd);
2967 smbrun(cmd,NULL,False);
2970 /* we've finished with the sensitive stuff */
2973 /* Add veto/hide lists */
2974 if (!IS_IPC(conn) && !IS_PRINT(conn)) {
2975 set_namearray( &conn->veto_list, lp_veto_files(SNUM(conn)));
2976 set_namearray( &conn->hide_list, lp_hide_files(SNUM(conn)));
2977 set_namearray( &conn->veto_oplock_list, lp_veto_oplocks(SNUM(conn)));
2980 if( DEBUGLVL( IS_IPC(conn) ? 3 : 1 ) ) {
2983 dbgtext( "%s (%s) ", remote_machine, client_addr(Client) );
2984 dbgtext( "connect to service %s ", lp_servicename(SNUM(conn)) );
2985 dbgtext( "as user %s ", user );
2986 dbgtext( "(uid=%d, gid=%d) ", conn->uid, conn->gid );
2987 dbgtext( "(pid %d)\n", (int)getpid() );
2993 /****************************************************************************
2994 Attempt to break an oplock on a file (if oplocked).
2995 Returns True if the file was closed as a result of
2996 the oplock break, False otherwise.
2997 Used as a last ditch attempt to free a space in the
2998 file table when we have run out.
2999 ****************************************************************************/
3000 BOOL attempt_close_oplocked_file(files_struct *fsp)
3003 DEBUG(5,("attempt_close_oplocked_file: checking file %s.\n", fsp->fsp_name));
3005 if (fsp->open && fsp->granted_oplock && !fsp->sent_oplock_break) {
3007 /* Try and break the oplock. */
3008 file_fd_struct *fd_ptr = fsp->fd_ptr;
3009 if(oplock_break( fd_ptr->dev, fd_ptr->inode, &fsp->open_time)) {
3010 if(!fsp->open) /* Did the oplock break close the file ? */
3020 /****************************************************************************
3022 ****************************************************************************/
3023 void close_cnum(connection_struct *conn, uint16 vuid)
3026 DirCacheFlush(SNUM(conn));
3030 DEBUG(IS_IPC(conn)?3:1, ("%s (%s) closed connection to service %s\n",
3031 remote_machine,client_addr(Client),
3032 lp_servicename(SNUM(conn))));
3034 yield_connection(conn,
3035 lp_servicename(SNUM(conn)),
3036 lp_max_connections(SNUM(conn)));
3038 if (lp_status(SNUM(conn)))
3039 yield_connection(conn,"STATUS.",MAXSTATUS);
3041 file_close_conn(conn);
3042 dptr_closecnum(conn);
3044 /* execute any "postexec = " line */
3045 if (*lp_postexec(SNUM(conn)) &&
3046 become_user(conn, vuid)) {
3048 pstrcpy(cmd,lp_postexec(SNUM(conn)));
3049 standard_sub(conn,cmd);
3050 smbrun(cmd,NULL,False);
3055 /* execute any "root postexec = " line */
3056 if (*lp_rootpostexec(SNUM(conn))) {
3058 pstrcpy(cmd,lp_rootpostexec(SNUM(conn)));
3059 standard_sub(conn,cmd);
3060 smbrun(cmd,NULL,False);
3069 /*******************************************************************
3070 prepare to dump a core file - carefully!
3071 ********************************************************************/
3072 static BOOL dump_core(void)
3076 pstrcpy(dname,debugf);
3077 if ((p=strrchr(dname,'/'))) *p=0;
3078 pstrcat(dname,"/corefiles");
3080 sys_chown(dname,getuid(),getgid());
3082 if (chdir(dname)) return(False);
3085 #ifdef HAVE_GETRLIMIT
3089 getrlimit(RLIMIT_CORE, &rlp);
3090 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
3091 setrlimit(RLIMIT_CORE, &rlp);
3092 getrlimit(RLIMIT_CORE, &rlp);
3093 DEBUG(3,("Core limits now %d %d\n",(int)rlp.rlim_cur,(int)rlp.rlim_max));
3099 DEBUG(0,("Dumping core in %s\n",dname));
3105 /****************************************************************************
3107 ****************************************************************************/
3108 void exit_server(char *reason)
3110 static int firsttime=1;
3112 if (!firsttime) exit(0);
3116 DEBUG(2,("Closing connections\n"));
3121 if (dcelogin_atmost_once) {
3126 int oldlevel = DEBUGLEVEL;
3128 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
3130 show_msg(last_inbuf);
3131 DEBUGLEVEL = oldlevel;
3132 DEBUG(0,("===============================================================\n"));
3134 if (dump_core()) return;
3140 DEBUG( 3, ( "Server exit (%s)\n", (reason ? reason : "") ) );
3145 These flags determine some of the permissions required to do an operation
3147 Note that I don't set NEED_WRITE on some write operations because they
3148 are used by some brain-dead clients when printing, and I don't want to
3149 force write permissions on print services.
3151 #define AS_USER (1<<0)
3152 #define NEED_WRITE (1<<1)
3153 #define TIME_INIT (1<<2)
3154 #define CAN_IPC (1<<3)
3155 #define AS_GUEST (1<<5)
3156 #define QUEUE_IN_OPLOCK (1<<6)
3159 define a list of possible SMB messages and their corresponding
3160 functions. Any message that has a NULL function is unimplemented -
3161 please feel free to contribute implementations!
3163 struct smb_message_struct
3167 int (*fn)(connection_struct *conn, char *, char *, int, int);
3177 {SMBnegprot,"SMBnegprot",reply_negprot,0},
3178 {SMBtcon,"SMBtcon",reply_tcon,0},
3179 {SMBtdis,"SMBtdis",reply_tdis,0},
3180 {SMBexit,"SMBexit",reply_exit,0},
3181 {SMBioctl,"SMBioctl",reply_ioctl,0},
3182 {SMBecho,"SMBecho",reply_echo,0},
3183 {SMBsesssetupX,"SMBsesssetupX",reply_sesssetup_and_X,0},
3184 {SMBtconX,"SMBtconX",reply_tcon_and_X,0},
3185 {SMBulogoffX, "SMBulogoffX", reply_ulogoffX, 0}, /* ulogoff doesn't give a valid TID */
3186 {SMBgetatr,"SMBgetatr",reply_getatr,AS_USER},
3187 {SMBsetatr,"SMBsetatr",reply_setatr,AS_USER | NEED_WRITE},
3188 {SMBchkpth,"SMBchkpth",reply_chkpth,AS_USER},
3189 {SMBsearch,"SMBsearch",reply_search,AS_USER},
3190 {SMBopen,"SMBopen",reply_open,AS_USER | QUEUE_IN_OPLOCK },
3192 /* note that SMBmknew and SMBcreate are deliberately overloaded */
3193 {SMBcreate,"SMBcreate",reply_mknew,AS_USER},
3194 {SMBmknew,"SMBmknew",reply_mknew,AS_USER},
3196 {SMBunlink,"SMBunlink",reply_unlink,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
3197 {SMBread,"SMBread",reply_read,AS_USER},
3198 {SMBwrite,"SMBwrite",reply_write,AS_USER},
3199 {SMBclose,"SMBclose",reply_close,AS_USER | CAN_IPC},
3200 {SMBmkdir,"SMBmkdir",reply_mkdir,AS_USER | NEED_WRITE},
3201 {SMBrmdir,"SMBrmdir",reply_rmdir,AS_USER | NEED_WRITE},
3202 {SMBdskattr,"SMBdskattr",reply_dskattr,AS_USER},
3203 {SMBmv,"SMBmv",reply_mv,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
3205 /* this is a Pathworks specific call, allowing the
3206 changing of the root path */
3207 {pSETDIR,"pSETDIR",reply_setdir,AS_USER},
3209 {SMBlseek,"SMBlseek",reply_lseek,AS_USER},
3210 {SMBflush,"SMBflush",reply_flush,AS_USER},
3211 {SMBctemp,"SMBctemp",reply_ctemp,AS_USER | QUEUE_IN_OPLOCK },
3212 {SMBsplopen,"SMBsplopen",reply_printopen,AS_USER | QUEUE_IN_OPLOCK },
3213 {SMBsplclose,"SMBsplclose",reply_printclose,AS_USER},
3214 {SMBsplretq,"SMBsplretq",reply_printqueue,AS_USER},
3215 {SMBsplwr,"SMBsplwr",reply_printwrite,AS_USER},
3216 {SMBlock,"SMBlock",reply_lock,AS_USER},
3217 {SMBunlock,"SMBunlock",reply_unlock,AS_USER},
3219 /* CORE+ PROTOCOL FOLLOWS */
3221 {SMBreadbraw,"SMBreadbraw",reply_readbraw,AS_USER},
3222 {SMBwritebraw,"SMBwritebraw",reply_writebraw,AS_USER},
3223 {SMBwriteclose,"SMBwriteclose",reply_writeclose,AS_USER},
3224 {SMBlockread,"SMBlockread",reply_lockread,AS_USER},
3225 {SMBwriteunlock,"SMBwriteunlock",reply_writeunlock,AS_USER},
3227 /* LANMAN1.0 PROTOCOL FOLLOWS */
3229 {SMBreadBmpx,"SMBreadBmpx",reply_readbmpx,AS_USER},
3230 {SMBreadBs,"SMBreadBs",NULL,AS_USER},
3231 {SMBwriteBmpx,"SMBwriteBmpx",reply_writebmpx,AS_USER},
3232 {SMBwriteBs,"SMBwriteBs",reply_writebs,AS_USER},
3233 {SMBwritec,"SMBwritec",NULL,AS_USER},
3234 {SMBsetattrE,"SMBsetattrE",reply_setattrE,AS_USER | NEED_WRITE},
3235 {SMBgetattrE,"SMBgetattrE",reply_getattrE,AS_USER},
3236 {SMBtrans,"SMBtrans",reply_trans,AS_USER | CAN_IPC},
3237 {SMBtranss,"SMBtranss",NULL,AS_USER | CAN_IPC},
3238 {SMBioctls,"SMBioctls",NULL,AS_USER},
3239 {SMBcopy,"SMBcopy",reply_copy,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
3240 {SMBmove,"SMBmove",NULL,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
3242 {SMBopenX,"SMBopenX",reply_open_and_X,AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
3243 {SMBreadX,"SMBreadX",reply_read_and_X,AS_USER | CAN_IPC },
3244 {SMBwriteX,"SMBwriteX",reply_write_and_X,AS_USER},
3245 {SMBlockingX,"SMBlockingX",reply_lockingX,AS_USER},
3247 {SMBffirst,"SMBffirst",reply_search,AS_USER},
3248 {SMBfunique,"SMBfunique",reply_search,AS_USER},
3249 {SMBfclose,"SMBfclose",reply_fclose,AS_USER},
3251 /* LANMAN2.0 PROTOCOL FOLLOWS */
3252 {SMBfindnclose, "SMBfindnclose", reply_findnclose, AS_USER},
3253 {SMBfindclose, "SMBfindclose", reply_findclose,AS_USER},
3254 {SMBtrans2, "SMBtrans2", reply_trans2, AS_USER },
3255 {SMBtranss2, "SMBtranss2", reply_transs2, AS_USER},
3257 /* NT PROTOCOL FOLLOWS */
3258 {SMBntcreateX, "SMBntcreateX", reply_ntcreate_and_X, AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
3259 {SMBnttrans, "SMBnttrans", reply_nttrans, AS_USER | CAN_IPC },
3260 {SMBnttranss, "SMBnttranss", reply_nttranss, AS_USER | CAN_IPC },
3261 {SMBntcancel, "SMBntcancel", reply_ntcancel, AS_USER },
3263 /* messaging routines */
3264 {SMBsends,"SMBsends",reply_sends,AS_GUEST},
3265 {SMBsendstrt,"SMBsendstrt",reply_sendstrt,AS_GUEST},
3266 {SMBsendend,"SMBsendend",reply_sendend,AS_GUEST},
3267 {SMBsendtxt,"SMBsendtxt",reply_sendtxt,AS_GUEST},
3269 /* NON-IMPLEMENTED PARTS OF THE CORE PROTOCOL */
3271 {SMBsendb,"SMBsendb",NULL,AS_GUEST},
3272 {SMBfwdname,"SMBfwdname",NULL,AS_GUEST},
3273 {SMBcancelf,"SMBcancelf",NULL,AS_GUEST},
3274 {SMBgetmac,"SMBgetmac",NULL,AS_GUEST}
3277 /****************************************************************************
3278 return a string containing the function name of a SMB command
3279 ****************************************************************************/
3280 char *smb_fn_name(int type)
3282 static char *unknown_name = "SMBunknown";
3283 static int num_smb_messages =
3284 sizeof(smb_messages) / sizeof(struct smb_message_struct);
3287 for (match=0;match<num_smb_messages;match++)
3288 if (smb_messages[match].code == type)
3291 if (match == num_smb_messages)
3292 return(unknown_name);
3294 return(smb_messages[match].name);
3298 /****************************************************************************
3299 do a switch on the message type, and return the response size
3300 ****************************************************************************/
3301 static int switch_message(int type,char *inbuf,char *outbuf,int size,int bufsize)
3305 static int num_smb_messages =
3306 sizeof(smb_messages) / sizeof(struct smb_message_struct);
3311 struct timeval msg_start_time;
3312 struct timeval msg_end_time;
3313 static unsigned long total_time = 0;
3315 GetTimeOfDay(&msg_start_time);
3322 last_message = type;
3324 /* make sure this is an SMB packet */
3325 if (strncmp(smb_base(inbuf),"\377SMB",4) != 0)
3327 DEBUG(2,("Non-SMB packet of length %d\n",smb_len(inbuf)));
3331 for (match=0;match<num_smb_messages;match++)
3332 if (smb_messages[match].code == type)
3335 if (match == num_smb_messages)
3337 DEBUG(0,("Unknown message type %d!\n",type));
3338 outsize = reply_unknown(inbuf,outbuf);
3342 DEBUG(3,("switch message %s (pid %d)\n",smb_messages[match].name,pid));
3344 if(global_oplock_break && (smb_messages[match].flags & QUEUE_IN_OPLOCK))
3347 * Queue this message as we are the process of an oplock break.
3350 DEBUG( 2, ( "switch_message: queueing message due to being in " ) );
3351 DEBUGADD( 2, ( "oplock break state.\n" ) );
3353 push_oplock_pending_smb_message( inbuf, size );
3357 if (smb_messages[match].fn)
3359 int flags = smb_messages[match].flags;
3360 static uint16 last_session_tag = UID_FIELD_INVALID;
3361 /* In share mode security we must ignore the vuid. */
3362 uint16 session_tag = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : SVAL(inbuf,smb_uid);
3363 connection_struct *conn = conn_find(SVAL(inbuf,smb_tid));
3366 /* Ensure this value is replaced in the incoming packet. */
3367 SSVAL(inbuf,smb_uid,session_tag);
3370 * Ensure the correct username is in sesssetup_user.
3371 * This is a really ugly bugfix for problems with
3372 * multiple session_setup_and_X's being done and
3373 * allowing %U and %G substitutions to work correctly.
3374 * There is a reason this code is done here, don't
3375 * move it unless you know what you're doing... :-).
3378 if (session_tag != last_session_tag) {
3379 user_struct *vuser = NULL;
3381 last_session_tag = session_tag;
3382 if(session_tag != UID_FIELD_INVALID)
3383 vuser = get_valid_user_struct(session_tag);
3385 pstrcpy( sesssetup_user, vuser->requested_name);
3388 /* does this protocol need to be run as root? */
3389 if (!(flags & AS_USER))
3392 /* does this protocol need to be run as the connected user? */
3393 if ((flags & AS_USER) && !become_user(conn,session_tag)) {
3394 if (flags & AS_GUEST)
3397 return(ERROR(ERRSRV,ERRinvnid));
3399 /* this code is to work around a bug is MS client 3 without
3400 introducing a security hole - it needs to be able to do
3401 print queue checks as guest if it isn't logged in properly */
3402 if (flags & AS_USER)
3405 /* does it need write permission? */
3406 if ((flags & NEED_WRITE) && !CAN_WRITE(conn))
3407 return(ERROR(ERRSRV,ERRaccess));
3409 /* ipc services are limited */
3410 if (IS_IPC(conn) && (flags & AS_USER) && !(flags & CAN_IPC)) {
3411 return(ERROR(ERRSRV,ERRaccess));
3414 /* load service specific parameters */
3416 !become_service(conn,(flags & AS_USER)?True:False)) {
3417 return(ERROR(ERRSRV,ERRaccess));
3420 /* does this protocol need to be run as guest? */
3421 if ((flags & AS_GUEST) &&
3423 !check_access(Client, lp_hostsallow(-1), lp_hostsdeny(-1)))) {
3424 return(ERROR(ERRSRV,ERRaccess));
3429 outsize = smb_messages[match].fn(conn, inbuf,outbuf,size,bufsize);
3433 outsize = reply_unknown(inbuf,outbuf);
3438 GetTimeOfDay(&msg_end_time);
3439 if (!(smb_messages[match].flags & TIME_INIT))
3441 smb_messages[match].time = 0;
3442 smb_messages[match].flags |= TIME_INIT;
3445 unsigned long this_time =
3446 (msg_end_time.tv_sec - msg_start_time.tv_sec)*1e6 +
3447 (msg_end_time.tv_usec - msg_start_time.tv_usec);
3448 smb_messages[match].time += this_time;
3449 total_time += this_time;
3451 DEBUG(2,("TIME %s %d usecs %g pct\n",
3452 smb_fn_name(type),smb_messages[match].time,
3453 (100.0*smb_messages[match].time) / total_time));
3460 /****************************************************************************
3461 construct a chained reply and add it to the already made reply
3462 **************************************************************************/
3463 int chain_reply(char *inbuf,char *outbuf,int size,int bufsize)
3465 static char *orig_inbuf;
3466 static char *orig_outbuf;
3467 int smb_com1, smb_com2 = CVAL(inbuf,smb_vwv0);
3468 unsigned smb_off2 = SVAL(inbuf,smb_vwv1);
3469 char *inbuf2, *outbuf2;
3471 char inbuf_saved[smb_wct];
3472 char outbuf_saved[smb_wct];
3473 extern int chain_size;
3474 int wct = CVAL(outbuf,smb_wct);
3475 int outsize = smb_size + 2*wct + SVAL(outbuf,smb_vwv0+2*wct);
3477 /* maybe its not chained */
3478 if (smb_com2 == 0xFF) {
3479 CVAL(outbuf,smb_vwv0) = 0xFF;
3483 if (chain_size == 0) {
3484 /* this is the first part of the chain */
3486 orig_outbuf = outbuf;
3489 /* we need to tell the client where the next part of the reply will be */
3490 SSVAL(outbuf,smb_vwv1,smb_offset(outbuf+outsize,outbuf));
3491 CVAL(outbuf,smb_vwv0) = smb_com2;
3493 /* remember how much the caller added to the chain, only counting stuff
3494 after the parameter words */
3495 chain_size += outsize - smb_wct;
3497 /* work out pointers into the original packets. The
3498 headers on these need to be filled in */
3499 inbuf2 = orig_inbuf + smb_off2 + 4 - smb_wct;
3500 outbuf2 = orig_outbuf + SVAL(outbuf,smb_vwv1) + 4 - smb_wct;
3502 /* remember the original command type */
3503 smb_com1 = CVAL(orig_inbuf,smb_com);
3505 /* save the data which will be overwritten by the new headers */
3506 memcpy(inbuf_saved,inbuf2,smb_wct);
3507 memcpy(outbuf_saved,outbuf2,smb_wct);
3509 /* give the new packet the same header as the last part of the SMB */
3510 memmove(inbuf2,inbuf,smb_wct);
3512 /* create the in buffer */
3513 CVAL(inbuf2,smb_com) = smb_com2;
3515 /* create the out buffer */
3516 bzero(outbuf2,smb_size);
3517 set_message(outbuf2,0,0,True);
3518 CVAL(outbuf2,smb_com) = CVAL(inbuf2,smb_com);
3520 memcpy(outbuf2+4,inbuf2+4,4);
3521 CVAL(outbuf2,smb_rcls) = SMB_SUCCESS;
3522 CVAL(outbuf2,smb_reh) = 0;
3523 CVAL(outbuf2,smb_flg) = 0x80 | (CVAL(inbuf2,smb_flg) & 0x8); /* bit 7 set
3525 SSVAL(outbuf2,smb_flg2,1); /* say we support long filenames */
3526 SSVAL(outbuf2,smb_err,SMB_SUCCESS);
3527 SSVAL(outbuf2,smb_tid,SVAL(inbuf2,smb_tid));
3528 SSVAL(outbuf2,smb_pid,SVAL(inbuf2,smb_pid));
3529 SSVAL(outbuf2,smb_uid,SVAL(inbuf2,smb_uid));
3530 SSVAL(outbuf2,smb_mid,SVAL(inbuf2,smb_mid));
3532 DEBUG(3,("Chained message\n"));
3535 /* process the request */
3536 outsize2 = switch_message(smb_com2,inbuf2,outbuf2,size-chain_size,
3537 bufsize-chain_size);
3539 /* copy the new reply and request headers over the old ones, but
3540 preserve the smb_com field */
3541 memmove(orig_outbuf,outbuf2,smb_wct);
3542 CVAL(orig_outbuf,smb_com) = smb_com1;
3544 /* restore the saved data, being careful not to overwrite any
3545 data from the reply header */
3546 memcpy(inbuf2,inbuf_saved,smb_wct);
3548 int ofs = smb_wct - PTR_DIFF(outbuf2,orig_outbuf);
3549 if (ofs < 0) ofs = 0;
3550 memmove(outbuf2+ofs,outbuf_saved+ofs,smb_wct-ofs);
3557 /****************************************************************************
3558 Helper function for contruct_reply.
3559 ****************************************************************************/
3561 void construct_reply_common(char *inbuf,char *outbuf)
3563 bzero(outbuf,smb_size);
3565 CVAL(outbuf,smb_com) = CVAL(inbuf,smb_com);
3566 set_message(outbuf,0,0,True);
3568 memcpy(outbuf+4,inbuf+4,4);
3569 CVAL(outbuf,smb_rcls) = SMB_SUCCESS;
3570 CVAL(outbuf,smb_reh) = 0;
3571 CVAL(outbuf,smb_flg) = 0x80 | (CVAL(inbuf,smb_flg) & 0x8); /* bit 7 set
3573 SSVAL(outbuf,smb_flg2,1); /* say we support long filenames */
3574 SSVAL(outbuf,smb_err,SMB_SUCCESS);
3575 SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
3576 SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
3577 SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
3578 SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
3581 /****************************************************************************
3582 construct a reply to the incoming packet
3583 ****************************************************************************/
3584 int construct_reply(char *inbuf,char *outbuf,int size,int bufsize)
3586 int type = CVAL(inbuf,smb_com);
3588 int msg_type = CVAL(inbuf,0);
3589 extern int chain_size;
3591 smb_last_time = time(NULL);
3598 return(reply_special(inbuf,outbuf));
3600 construct_reply_common(inbuf, outbuf);
3602 outsize = switch_message(type,inbuf,outbuf,size,bufsize);
3604 outsize += chain_size;
3607 smb_setlen(outbuf,outsize - 4);
3611 /****************************************************************************
3612 process commands from the client
3613 ****************************************************************************/
3614 static void process(void)
3618 InBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
3619 OutBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
3620 if ((InBuffer == NULL) || (OutBuffer == NULL))
3623 InBuffer += SMB_ALIGNMENT;
3624 OutBuffer += SMB_ALIGNMENT;
3627 DEBUG(3,("priming nmbd\n"));
3630 ip = *interpret_addr2("localhost");
3631 if (zero_ip(ip)) ip = *interpret_addr2("127.0.0.1");
3633 send_one_packet(OutBuffer,1,ip,NMB_PORT,SOCK_DGRAM);
3637 /* re-initialise the timezone */
3642 int deadtime = lp_deadtime()*60;
3644 int last_keepalive=0;
3645 int service_load_counter = 0;
3646 BOOL got_smb = False;
3649 deadtime = DEFAULT_SMBD_TIMEOUT;
3651 #if USE_READ_PREDICTION
3652 if (lp_readprediction())
3653 do_read_prediction();
3658 for (counter=SMBD_SELECT_LOOP;
3659 !receive_message_or_smb(Client,oplock_sock,
3660 InBuffer,BUFFER_SIZE,SMBD_SELECT_LOOP*1000,&got_smb);
3661 counter += SMBD_SELECT_LOOP)
3664 BOOL allidle = True;
3665 extern int keepalive;
3667 if (counter > 365 * 3600) /* big number of seconds. */
3670 service_load_counter = 0;
3673 if (smb_read_error == READ_EOF)
3675 DEBUG(3,("end of file from client\n"));
3679 if (smb_read_error == READ_ERROR)
3681 DEBUG(3,("receive_smb error (%s) exiting\n",
3688 /* become root again if waiting */
3691 /* check for smb.conf reload */
3692 if (counter >= service_load_counter + SMBD_RELOAD_CHECK)
3694 service_load_counter = counter;
3696 /* reload services, if files have changed. */
3697 reload_services(True);
3701 * If reload_after_sighup == True then we got a SIGHUP
3702 * and are being asked to reload. Fix from <branko.cibej@hermes.si>
3705 if (reload_after_sighup)
3707 DEBUG(0,("Reloading services after SIGHUP\n"));
3708 reload_services(False);
3709 reload_after_sighup = False;
3712 /* automatic timeout if all connections are closed */
3713 if (conn_num_open()==0 && counter >= IDLE_CLOSED_TIMEOUT)
3715 DEBUG( 2, ( "Closing idle connection\n" ) );
3719 if (keepalive && (counter-last_keepalive)>keepalive)
3721 struct cli_state *cli = server_client();
3722 if (!send_keepalive(Client)) {
3723 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
3726 /* also send a keepalive to the password server if its still
3728 if (cli && cli->initialised)
3729 send_keepalive(cli->fd);
3730 last_keepalive = counter;
3733 /* check for connection timeouts */
3734 allidle = conn_idle_all(t, deadtime);
3736 if (allidle && conn_num_open()>0) {
3737 DEBUG(2,("Closing idle connection 2.\n"));
3741 if(global_machine_pasword_needs_changing)
3743 unsigned char trust_passwd_hash[16];
3745 pstring remote_machine_list;
3748 * We're in domain level security, and the code that
3749 * read the machine password flagged that the machine
3750 * password needs changing.
3754 * First, open the machine password file with an exclusive lock.
3757 if(!trust_password_lock( global_myworkgroup, global_myname, True)) {
3758 DEBUG(0,("process: unable to open the machine account password file for \
3759 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
3763 if(!get_trust_account_password( trust_passwd_hash, &lct)) {
3764 DEBUG(0,("process: unable to read the machine account password for \
3765 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
3766 trust_password_unlock();
3771 * Make sure someone else hasn't already done this.
3774 if(t < lct + lp_machine_password_timeout()) {
3775 trust_password_unlock();
3776 global_machine_pasword_needs_changing = False;
3780 pstrcpy(remote_machine_list, lp_passwordserver());
3782 change_trust_account_password( global_myworkgroup, remote_machine_list);
3783 trust_password_unlock();
3784 global_machine_pasword_needs_changing = False;
3788 * Check to see if we have any change notifies
3789 * outstanding on the queue.
3791 process_pending_change_notify_queue(t);
3795 process_smb(InBuffer, OutBuffer);
3797 process_local_message(oplock_sock, InBuffer, BUFFER_SIZE);
3802 /****************************************************************************
3803 initialise connect, service and file structs
3804 ****************************************************************************/
3805 static void init_structs(void )
3807 get_myname(myhostname,NULL);
3810 * Set the machine NETBIOS name if not already
3811 * set from the config file.
3814 if (!*global_myname)
3817 fstrcpy( global_myname, myhostname );
3818 p = strchr( global_myname, '.' );
3822 strupper( global_myname );
3829 init_rpc_pipe_hnd();
3831 /* for LSA handles */
3832 init_lsa_policy_hnd();
3837 /****************************************************************************
3838 usage on the program
3839 ****************************************************************************/
3840 static void usage(char *pname)
3842 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
3844 printf("Usage: %s [-D] [-p port] [-d debuglevel] [-l log basename] [-s services file]\n",pname);
3845 printf("Version %s\n",VERSION);
3846 printf("\t-D become a daemon\n");
3847 printf("\t-p port listen on the specified port\n");
3848 printf("\t-d debuglevel set the debuglevel\n");
3849 printf("\t-l log basename. Basename for log/debug files\n");
3850 printf("\t-s services file. Filename of services file\n");
3851 printf("\t-P passive only\n");
3852 printf("\t-a overwrite log file, don't append\n");
3857 /****************************************************************************
3859 ****************************************************************************/
3860 int main(int argc,char *argv[])
3862 extern BOOL append_log;
3863 /* shall I run as a daemon */
3864 BOOL is_daemon = False;
3865 int port = SMB_PORT;
3867 extern char *optarg;
3869 #ifdef HAVE_SET_AUTH_PARAMETERS
3870 set_auth_parameters(argc,argv);
3874 /* needed for SecureWare on SCO */
3882 pstrcpy(debugf,SMBLOGFILE);
3884 pstrcpy(remote_machine, "smb");
3886 setup_logging(argv[0],False);
3888 charset_initialise();
3890 /* make absolutely sure we run as root - to handle cases where people
3891 are crazy enough to have it setuid */
3892 #ifdef HAVE_SETRESUID
3901 fault_setup((void (*)(void *))exit_server);
3902 CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
3904 /* we want total control over the permissions on created files,
3905 so set our umask to 0 */
3912 /* this is for people who can't start the program correctly */
3913 while (argc > 1 && (*argv[1] != '-'))
3919 while ((opt = getopt(argc, argv, "O:i:l:s:d:Dp:hPaf:")) != EOF)
3923 pstrcpy(user_socket_options,optarg);
3926 pstrcpy(scope,optarg);
3930 extern BOOL passive;
3935 pstrcpy(servicesf,optarg);
3938 pstrcpy(debugf,optarg);
3942 extern BOOL append_log;
3943 append_log = !append_log;
3953 DEBUGLEVEL = atoi(optarg);
3956 port = atoi(optarg);
3969 DEBUG( 1, ( "smbd version %s started.\n", VERSION ) );
3970 DEBUGADD( 1, ( "Copyright Andrew Tridgell 1992-1997\n" ) );
3972 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
3973 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
3975 if (sizeof(uint16) < 2 || sizeof(uint32) < 4)
3977 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
3983 if (!reload_services(False))
3988 extern BOOL sslEnabled;
3989 sslEnabled = lp_ssl_enabled();
3993 #endif /* WITH_SSL */
3995 codepage_initialise(lp_client_code_page());
3997 pstrcpy(global_myworkgroup, lp_workgroup());
3999 if(!pdb_generate_machine_sid()) {
4000 DEBUG(0,("ERROR: Samba cannot get a machine SID.\n"));
4004 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
4006 /* Setup the signals that allow the debug log level
4007 to by dynamically changed. */
4009 /* If we are using the malloc debug code we can't use
4010 SIGUSR1 and SIGUSR2 to do debug level changes. */
4013 #if defined(SIGUSR1)
4014 CatchSignal( SIGUSR1, SIGNAL_CAST sig_usr1 );
4015 #endif /* SIGUSR1 */
4017 #if defined(SIGUSR2)
4018 CatchSignal( SIGUSR2, SIGNAL_CAST sig_usr2 );
4019 #endif /* SIGUSR2 */
4020 #endif /* MEM_MAN */
4022 DEBUG( 3, ( "loaded services\n" ) );
4024 if (!is_daemon && !is_a_socket(0))
4026 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
4032 DEBUG( 3, ( "Becoming a daemon.\n" ) );
4036 if (!directory_exist(lp_lockdir(), NULL)) {
4037 mkdir(lp_lockdir(), 0755);
4041 pidfile_create("smbd");
4044 if (!open_sockets(is_daemon,port))
4047 if (!locking_init(0))
4050 if(!initialize_password_db())
4053 /* possibly reload the services file. */
4054 reload_services(True);
4056 max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
4060 if (sys_chroot(lp_rootdir()) == 0)
4061 DEBUG( 2, ( "Changed root to %s\n", lp_rootdir() ) );
4064 /* Setup the oplock IPC socket. */
4065 if( !open_oplock_ipc() )
4071 exit_server("normal exit");