Correct PPTP server firewall rules chain.
[tomato/davidwu.git] / release / src / router / samba / source / smbd / process.c
blob7a0d629a123d31fa22850a1d441b16bf5e556499
1 /*
2 Unix SMB/Netbios implementation.
3 Version 1.9.
4 process incoming packets - main loop
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.
22 #include "includes.h"
24 extern int DEBUGLEVEL;
26 struct timeval smb_last_time;
28 char *InBuffer = NULL;
29 char *OutBuffer = NULL;
30 char *last_inbuf = NULL;
32 /*
33 * Size of data we can send to client. Set
34 * by the client for all protocols above CORE.
35 * Set by us for CORE protocol.
37 int max_send = BUFFER_SIZE;
39 * Size of the data we can receive. Set by us.
40 * Can be modified by the max xmit parameter.
42 int max_recv = BUFFER_SIZE;
44 extern int last_message;
45 extern int global_oplock_break;
46 extern pstring sesssetup_user;
47 extern char *last_inbuf;
48 extern char *InBuffer;
49 extern char *OutBuffer;
50 extern int smb_read_error;
51 extern VOLATILE SIG_ATOMIC_T reload_after_sighup;
52 extern BOOL global_machine_password_needs_changing;
53 extern fstring global_myworkgroup;
54 extern pstring global_myname;
55 extern int max_send;
57 /****************************************************************************
58 structure to hold a linked list of queued messages.
59 for processing.
60 ****************************************************************************/
62 typedef struct {
63 ubi_slNode msg_next;
64 char *msg_buf;
65 int msg_len;
66 } pending_message_list;
68 static ubi_slList smb_oplock_queue = { NULL, (ubi_slNodePtr)&smb_oplock_queue, 0};
70 /****************************************************************************
71 Function to push a message onto the tail of a linked list of smb messages ready
72 for processing.
73 ****************************************************************************/
75 static BOOL push_message(ubi_slList *list_head, char *buf, int msg_len)
77 pending_message_list *msg = (pending_message_list *)
78 malloc(sizeof(pending_message_list));
80 if(msg == NULL)
82 DEBUG(0,("push_message: malloc fail (1)\n"));
83 return False;
86 msg->msg_buf = (char *)malloc(msg_len);
87 if(msg->msg_buf == NULL)
89 DEBUG(0,("push_message: malloc fail (2)\n"));
90 free((char *)msg);
91 return False;
94 memcpy(msg->msg_buf, buf, msg_len);
95 msg->msg_len = msg_len;
97 ubi_slAddTail( list_head, msg);
99 return True;
102 /****************************************************************************
103 Function to push a smb message onto a linked list of local smb messages ready
104 for processing.
105 ****************************************************************************/
107 BOOL push_oplock_pending_smb_message(char *buf, int msg_len)
109 return push_message(&smb_oplock_queue, buf, msg_len);
112 /****************************************************************************
113 Do a select on an two fd's - with timeout.
115 If a local udp message has been pushed onto the
116 queue (this can only happen during oplock break
117 processing) return this first.
119 If a pending smb message has been pushed onto the
120 queue (this can only happen during oplock break
121 processing) return this next.
123 If the first smbfd is ready then read an smb from it.
124 if the second (loopback UDP) fd is ready then read a message
125 from it and setup the buffer header to identify the length
126 and from address.
127 Returns False on timeout or error.
128 Else returns True.
130 The timeout is in milli seconds
131 ****************************************************************************/
133 static BOOL receive_message_or_smb(char *buffer, int buffer_len,
134 int timeout, BOOL *got_smb)
136 extern int Client;
137 fd_set fds;
138 int selrtn;
139 struct timeval to;
140 int maxfd;
142 smb_read_error = 0;
144 *got_smb = False;
147 * Check to see if we already have a message on the smb queue.
148 * If so - copy and return it.
151 if(ubi_slCount(&smb_oplock_queue) != 0)
153 pending_message_list *msg = (pending_message_list *)ubi_slRemHead(&smb_oplock_queue);
154 memcpy(buffer, msg->msg_buf, MIN(buffer_len, msg->msg_len));
156 /* Free the message we just copied. */
157 free((char *)msg->msg_buf);
158 free((char *)msg);
159 *got_smb = True;
161 DEBUG(5,("receive_message_or_smb: returning queued smb message.\n"));
162 return True;
166 * Setup the select read fd set.
169 FD_ZERO(&fds);
170 FD_SET(Client,&fds);
171 maxfd = setup_oplock_select_set(&fds);
173 to.tv_sec = timeout / 1000;
174 to.tv_usec = (timeout % 1000) * 1000;
176 selrtn = sys_select(MAX(maxfd,Client)+1,&fds,timeout>0?&to:NULL);
178 /* Check if error */
179 if(selrtn == -1) {
180 /* something is wrong. Maybe the socket is dead? */
181 smb_read_error = READ_ERROR;
182 return False;
185 /* Did we timeout ? */
186 if (selrtn == 0) {
187 smb_read_error = READ_TIMEOUT;
188 return False;
191 if (FD_ISSET(Client,&fds))
193 *got_smb = True;
194 return receive_smb(Client, buffer, 0);
196 else
198 return receive_local_message(&fds, buffer, buffer_len, 0);
202 /****************************************************************************
203 Get the next SMB packet, doing the local message processing automatically.
204 ****************************************************************************/
206 BOOL receive_next_smb(char *inbuf, int bufsize, int timeout)
208 BOOL got_smb = False;
209 BOOL ret;
213 ret = receive_message_or_smb(inbuf,bufsize,timeout,&got_smb);
215 if(ret && !got_smb)
217 /* Deal with oplock break requests from other smbd's. */
218 process_local_message(inbuf, bufsize);
219 continue;
222 if(ret && (CVAL(inbuf,0) == 0x85))
224 /* Keepalive packet. */
225 got_smb = False;
229 while(ret && !got_smb);
231 return ret;
234 /****************************************************************************
235 We're terminating and have closed all our files/connections etc.
236 If there are any pending local messages we need to respond to them
237 before termination so that other smbds don't think we just died whilst
238 holding oplocks.
239 ****************************************************************************/
241 void respond_to_all_remaining_local_messages(void)
243 char buffer[1024];
244 fd_set fds;
247 * Assert we have no exclusive open oplocks.
250 if(get_number_of_exclusive_open_oplocks()) {
251 DEBUG(0,("respond_to_all_remaining_local_messages: PANIC : we have %d exclusive oplocks.\n",
252 get_number_of_exclusive_open_oplocks() ));
253 return;
257 * Setup the select read fd set.
260 FD_ZERO(&fds);
261 if(!setup_oplock_select_set(&fds))
262 return;
265 * Keep doing receive_local_message with a 1 ms timeout until
266 * we have no more messages.
269 while(receive_local_message(&fds, buffer, sizeof(buffer), 1)) {
270 /* Deal with oplock break requests from other smbd's. */
271 process_local_message(buffer, sizeof(buffer));
273 FD_ZERO(&fds);
274 (void)setup_oplock_select_set(&fds);
277 return;
282 These flags determine some of the permissions required to do an operation
284 Note that I don't set NEED_WRITE on some write operations because they
285 are used by some brain-dead clients when printing, and I don't want to
286 force write permissions on print services.
288 #define AS_USER (1<<0)
289 #define NEED_WRITE (1<<1)
290 #define TIME_INIT (1<<2)
291 #define CAN_IPC (1<<3)
292 #define AS_GUEST (1<<5)
293 #define QUEUE_IN_OPLOCK (1<<6)
296 define a list of possible SMB messages and their corresponding
297 functions. Any message that has a NULL function is unimplemented -
298 please feel free to contribute implementations!
300 struct smb_message_struct
302 int code;
303 char *name;
304 int (*fn)(connection_struct *conn, char *, char *, int, int);
305 int flags;
307 smb_messages[] = {
309 /* CORE PROTOCOL */
311 {SMBnegprot,"SMBnegprot",reply_negprot,0},
312 {SMBtcon,"SMBtcon",reply_tcon,0},
313 {SMBtdis,"SMBtdis",reply_tdis,0},
314 {SMBexit,"SMBexit",reply_exit,0},
315 {SMBioctl,"SMBioctl",reply_ioctl,0},
316 {SMBecho,"SMBecho",reply_echo,0},
317 {SMBsesssetupX,"SMBsesssetupX",reply_sesssetup_and_X,0},
318 {SMBtconX,"SMBtconX",reply_tcon_and_X,0},
319 {SMBulogoffX, "SMBulogoffX", reply_ulogoffX, 0}, /* ulogoff doesn't give a valid TID */
320 {SMBgetatr,"SMBgetatr",reply_getatr,AS_USER},
321 {SMBsetatr,"SMBsetatr",reply_setatr,AS_USER | NEED_WRITE},
322 {SMBchkpth,"SMBchkpth",reply_chkpth,AS_USER},
323 {SMBsearch,"SMBsearch",reply_search,AS_USER},
324 {SMBopen,"SMBopen",reply_open,AS_USER | QUEUE_IN_OPLOCK },
326 /* note that SMBmknew and SMBcreate are deliberately overloaded */
327 {SMBcreate,"SMBcreate",reply_mknew,AS_USER},
328 {SMBmknew,"SMBmknew",reply_mknew,AS_USER},
330 {SMBunlink,"SMBunlink",reply_unlink,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
331 {SMBread,"SMBread",reply_read,AS_USER},
332 {SMBwrite,"SMBwrite",reply_write,AS_USER | CAN_IPC },
333 {SMBclose,"SMBclose",reply_close,AS_USER | CAN_IPC },
334 {SMBmkdir,"SMBmkdir",reply_mkdir,AS_USER | NEED_WRITE},
335 {SMBrmdir,"SMBrmdir",reply_rmdir,AS_USER | NEED_WRITE},
336 {SMBdskattr,"SMBdskattr",reply_dskattr,AS_USER},
337 {SMBmv,"SMBmv",reply_mv,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK},
339 /* this is a Pathworks specific call, allowing the
340 changing of the root path */
341 {pSETDIR,"pSETDIR",reply_setdir,AS_USER},
343 {SMBlseek,"SMBlseek",reply_lseek,AS_USER},
344 {SMBflush,"SMBflush",reply_flush,AS_USER},
345 {SMBctemp,"SMBctemp",reply_ctemp,AS_USER | QUEUE_IN_OPLOCK },
346 #ifdef PRINTING
347 {SMBsplopen,"SMBsplopen",reply_printopen,AS_USER | QUEUE_IN_OPLOCK },
348 {SMBsplclose,"SMBsplclose",reply_printclose,AS_USER},
349 {SMBsplretq,"SMBsplretq",reply_printqueue,AS_USER},
350 {SMBsplwr,"SMBsplwr",reply_printwrite,AS_USER},
351 #endif
352 {SMBlock,"SMBlock",reply_lock,AS_USER},
353 {SMBunlock,"SMBunlock",reply_unlock,AS_USER},
355 /* CORE+ PROTOCOL FOLLOWS */
357 {SMBreadbraw,"SMBreadbraw",reply_readbraw,AS_USER},
358 {SMBwritebraw,"SMBwritebraw",reply_writebraw,AS_USER},
359 {SMBwriteclose,"SMBwriteclose",reply_writeclose,AS_USER},
360 {SMBlockread,"SMBlockread",reply_lockread,AS_USER},
361 {SMBwriteunlock,"SMBwriteunlock",reply_writeunlock,AS_USER},
363 /* LANMAN1.0 PROTOCOL FOLLOWS */
365 {SMBreadBmpx,"SMBreadBmpx",reply_readbmpx,AS_USER},
366 {SMBreadBs,"SMBreadBs",NULL,AS_USER},
367 {SMBwriteBmpx,"SMBwriteBmpx",reply_writebmpx,AS_USER},
368 {SMBwriteBs,"SMBwriteBs",reply_writebs,AS_USER},
369 {SMBwritec,"SMBwritec",NULL,AS_USER},
370 {SMBsetattrE,"SMBsetattrE",reply_setattrE,AS_USER | NEED_WRITE },
371 {SMBgetattrE,"SMBgetattrE",reply_getattrE,AS_USER },
372 {SMBtrans,"SMBtrans",reply_trans,AS_USER | CAN_IPC | QUEUE_IN_OPLOCK},
373 {SMBtranss,"SMBtranss",NULL,AS_USER | CAN_IPC},
374 {SMBioctls,"SMBioctls",NULL,AS_USER},
375 {SMBcopy,"SMBcopy",reply_copy,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
376 {SMBmove,"SMBmove",NULL,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
378 {SMBopenX,"SMBopenX",reply_open_and_X,AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
379 {SMBreadX,"SMBreadX",reply_read_and_X,AS_USER | CAN_IPC },
380 {SMBwriteX,"SMBwriteX",reply_write_and_X,AS_USER | CAN_IPC },
381 {SMBlockingX,"SMBlockingX",reply_lockingX,AS_USER },
383 {SMBffirst,"SMBffirst",reply_search,AS_USER},
384 {SMBfunique,"SMBfunique",reply_search,AS_USER},
385 {SMBfclose,"SMBfclose",reply_fclose,AS_USER},
387 /* LANMAN2.0 PROTOCOL FOLLOWS */
388 {SMBfindnclose, "SMBfindnclose", reply_findnclose, AS_USER},
389 {SMBfindclose, "SMBfindclose", reply_findclose,AS_USER},
390 {SMBtrans2, "SMBtrans2", reply_trans2, AS_USER | CAN_IPC },
391 {SMBtranss2, "SMBtranss2", reply_transs2, AS_USER},
393 /* NT PROTOCOL FOLLOWS */
394 {SMBntcreateX, "SMBntcreateX", reply_ntcreate_and_X, AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
395 {SMBnttrans, "SMBnttrans", reply_nttrans, AS_USER | CAN_IPC | QUEUE_IN_OPLOCK},
396 {SMBnttranss, "SMBnttranss", reply_nttranss, AS_USER | CAN_IPC },
397 {SMBntcancel, "SMBntcancel", reply_ntcancel, 0 },
399 /* messaging routines */
400 {SMBsends,"SMBsends",reply_sends,AS_GUEST},
401 {SMBsendstrt,"SMBsendstrt",reply_sendstrt,AS_GUEST},
402 {SMBsendend,"SMBsendend",reply_sendend,AS_GUEST},
403 {SMBsendtxt,"SMBsendtxt",reply_sendtxt,AS_GUEST},
405 /* NON-IMPLEMENTED PARTS OF THE CORE PROTOCOL */
407 {SMBsendb,"SMBsendb",NULL,AS_GUEST},
408 {SMBfwdname,"SMBfwdname",NULL,AS_GUEST},
409 {SMBcancelf,"SMBcancelf",NULL,AS_GUEST},
410 {SMBgetmac,"SMBgetmac",NULL,AS_GUEST}
414 /****************************************************************************
415 do a switch on the message type, and return the response size
416 ****************************************************************************/
417 static int switch_message(int type,char *inbuf,char *outbuf,int size,int bufsize)
419 static pid_t pid= (pid_t)-1;
420 int outsize = 0;
421 static int num_smb_messages =
422 sizeof(smb_messages) / sizeof(struct smb_message_struct);
423 int match;
424 extern int Client;
426 if (pid == (pid_t)-1)
427 pid = getpid();
429 errno = 0;
430 last_message = type;
432 /* make sure this is an SMB packet */
433 if (strncmp(smb_base(inbuf),"\377SMB",4) != 0)
435 DEBUG(2,("Non-SMB packet of length %d\n",smb_len(inbuf)));
436 return(-1);
439 for (match=0;match<num_smb_messages;match++)
440 if (smb_messages[match].code == type)
441 break;
443 if (match == num_smb_messages)
445 DEBUG(0,("Unknown message type %d!\n",type));
446 outsize = reply_unknown(inbuf,outbuf);
448 else
450 DEBUG(3,("switch message %s (pid %d)\n",smb_messages[match].name,(int)pid));
452 if(global_oplock_break)
454 int flags = smb_messages[match].flags;
456 if(flags & QUEUE_IN_OPLOCK)
459 * Queue this message as we are the process of an oplock break.
462 DEBUG( 2, ( "switch_message: queueing message due to being in " ) );
463 DEBUGADD( 2, ( "oplock break state.\n" ) );
465 push_oplock_pending_smb_message( inbuf, size );
466 return -1;
469 if (smb_messages[match].fn)
471 int flags = smb_messages[match].flags;
472 static uint16 last_session_tag = UID_FIELD_INVALID;
473 /* In share mode security we must ignore the vuid. */
474 uint16 session_tag = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : SVAL(inbuf,smb_uid);
475 connection_struct *conn = conn_find(SVAL(inbuf,smb_tid));
478 /* Ensure this value is replaced in the incoming packet. */
479 SSVAL(inbuf,smb_uid,session_tag);
482 * Ensure the correct username is in sesssetup_user.
483 * This is a really ugly bugfix for problems with
484 * multiple session_setup_and_X's being done and
485 * allowing %U and %G substitutions to work correctly.
486 * There is a reason this code is done here, don't
487 * move it unless you know what you're doing... :-).
488 * JRA.
490 if (session_tag != last_session_tag) {
491 user_struct *vuser = NULL;
493 last_session_tag = session_tag;
494 if(session_tag != UID_FIELD_INVALID)
495 vuser = get_valid_user_struct(session_tag);
496 if(vuser != NULL)
497 pstrcpy( sesssetup_user, vuser->requested_name);
500 /* does this protocol need to be run as root? */
501 if (!(flags & AS_USER))
502 unbecome_user();
504 /* does this protocol need to be run as the connected user? */
505 if ((flags & AS_USER) && !become_user(conn,session_tag)) {
506 if (flags & AS_GUEST)
507 flags &= ~AS_USER;
508 else
509 return(ERROR(ERRSRV,ERRaccess));
511 /* this code is to work around a bug is MS client 3 without
512 introducing a security hole - it needs to be able to do
513 print queue checks as guest if it isn't logged in properly */
514 if (flags & AS_USER)
515 flags &= ~AS_GUEST;
517 /* does it need write permission? */
518 if ((flags & NEED_WRITE) && !CAN_WRITE(conn))
519 return(ERROR(ERRSRV,ERRaccess));
521 /* ipc services are limited */
522 if (IS_IPC(conn) && (flags & AS_USER) && !(flags & CAN_IPC)) {
523 return(ERROR(ERRSRV,ERRaccess));
526 /* load service specific parameters */
527 if (conn &&
528 !become_service(conn,(flags & AS_USER)?True:False)) {
529 return(ERROR(ERRSRV,ERRaccess));
532 /* does this protocol need to be run as guest? */
533 if ((flags & AS_GUEST) &&
534 (!become_guest() ||
535 !check_access(Client, lp_hostsallow(-1), lp_hostsdeny(-1)))) {
536 return(ERROR(ERRSRV,ERRaccess));
539 last_inbuf = inbuf;
541 outsize = smb_messages[match].fn(conn, inbuf,outbuf,size,bufsize);
543 else
545 outsize = reply_unknown(inbuf,outbuf);
549 return(outsize);
553 /****************************************************************************
554 construct a reply to the incoming packet
555 ****************************************************************************/
556 static int construct_reply(char *inbuf,char *outbuf,int size,int bufsize)
558 int type = CVAL(inbuf,smb_com);
559 int outsize = 0;
560 int msg_type = CVAL(inbuf,0);
562 GetTimeOfDay(&smb_last_time);
564 chain_size = 0;
565 file_chain_reset();
566 reset_chain_p();
568 if (msg_type != 0)
569 return(reply_special(inbuf,outbuf));
571 construct_reply_common(inbuf, outbuf);
573 outsize = switch_message(type,inbuf,outbuf,size,bufsize);
575 outsize += chain_size;
577 if(outsize > 4)
578 smb_setlen(outbuf,outsize - 4);
579 return(outsize);
583 /****************************************************************************
584 process an smb from the client - split out from the process() code so
585 it can be used by the oplock break code.
586 ****************************************************************************/
587 void process_smb(char *inbuf, char *outbuf)
589 extern int Client;
590 #ifdef WITH_SSL
591 extern BOOL sslEnabled; /* don't use function for performance reasons */
592 static int sslConnected = 0;
593 #endif /* WITH_SSL */
594 static int trans_num;
595 int msg_type = CVAL(inbuf,0);
596 int32 len = smb_len(inbuf);
597 int nread = len + 4;
599 #ifdef WITH_PROFILE
600 profile_p->smb_count++;
601 #endif
603 if (trans_num == 0) {
604 /* on the first packet, check the global hosts allow/ hosts
605 deny parameters before doing any parsing of the packet
606 passed to us by the client. This prevents attacks on our
607 parsing code from hosts not in the hosts allow list */
608 if (!check_access(Client, lp_hostsallow(-1), lp_hostsdeny(-1))) {
609 /* send a negative session response "not listining on calling
610 name" */
611 static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
612 DEBUG( 1, ( "Connection denied from %s\n",
613 client_addr(Client) ) );
614 send_smb(Client,(char *)buf);
615 exit_server("connection denied");
619 DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type, len ) );
620 DEBUG( 3, ( "Transaction %d of length %d\n", trans_num, nread ) );
622 #ifdef WITH_SSL
623 if(sslEnabled && !sslConnected){
624 sslConnected = sslutil_negotiate_ssl(Client, msg_type);
625 if(sslConnected < 0){ /* an error occured */
626 exit_server("SSL negotiation failed");
627 }else if(sslConnected){
628 trans_num++;
629 return;
632 #endif /* WITH_SSL */
634 #ifdef WITH_VTP
635 if(trans_num == 1 && VT_Check(inbuf))
637 VT_Process();
638 return;
640 #endif
642 if (msg_type == 0)
643 show_msg(inbuf);
644 else if(msg_type == 0x85)
645 return; /* Keepalive packet. */
647 nread = construct_reply(inbuf,outbuf,nread,max_send);
649 if(nread > 0)
651 if (CVAL(outbuf,0) == 0)
652 show_msg(outbuf);
654 if (nread != smb_len(outbuf) + 4)
656 DEBUG(0,("ERROR: Invalid message response size! %d %d\n",
657 nread, smb_len(outbuf)));
659 else
660 send_smb(Client,outbuf);
662 trans_num++;
667 /****************************************************************************
668 return a string containing the function name of a SMB command
669 ****************************************************************************/
670 char *smb_fn_name(int type)
672 static char *unknown_name = "SMBunknown";
673 static int num_smb_messages =
674 sizeof(smb_messages) / sizeof(struct smb_message_struct);
675 int match;
677 for (match=0;match<num_smb_messages;match++)
678 if (smb_messages[match].code == type)
679 break;
681 if (match == num_smb_messages)
682 return(unknown_name);
684 return(smb_messages[match].name);
688 /****************************************************************************
689 Helper function for contruct_reply.
690 ****************************************************************************/
692 void construct_reply_common(char *inbuf,char *outbuf)
694 memset(outbuf,'\0',smb_size);
696 set_message(outbuf,0,0,True);
697 CVAL(outbuf,smb_com) = CVAL(inbuf,smb_com);
699 memcpy(outbuf+4,inbuf+4,4);
700 CVAL(outbuf,smb_rcls) = SMB_SUCCESS;
701 CVAL(outbuf,smb_reh) = 0;
702 SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES)); /* bit 7 set
703 means a reply */
704 SSVAL(outbuf,smb_flg2,FLAGS2_LONG_PATH_COMPONENTS); /* say we support long filenames */
705 SSVAL(outbuf,smb_err,SMB_SUCCESS);
706 SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
707 SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
708 SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
709 SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
712 /****************************************************************************
713 construct a chained reply and add it to the already made reply
714 **************************************************************************/
715 int chain_reply(char *inbuf,char *outbuf,int size,int bufsize)
717 static char *orig_inbuf;
718 static char *orig_outbuf;
719 int smb_com1, smb_com2 = CVAL(inbuf,smb_vwv0);
720 unsigned smb_off2 = SVAL(inbuf,smb_vwv1);
721 char *inbuf2, *outbuf2;
722 int outsize2;
723 char inbuf_saved[smb_wct];
724 char outbuf_saved[smb_wct];
725 int wct = CVAL(outbuf,smb_wct);
726 int outsize = smb_size + 2*wct + SVAL(outbuf,smb_vwv0+2*wct);
728 /* maybe its not chained */
729 if (smb_com2 == 0xFF) {
730 CVAL(outbuf,smb_vwv0) = 0xFF;
731 return outsize;
734 if (chain_size == 0) {
735 /* this is the first part of the chain */
736 orig_inbuf = inbuf;
737 orig_outbuf = outbuf;
741 * The original Win95 redirector dies on a reply to
742 * a lockingX and read chain unless the chain reply is
743 * 4 byte aligned. JRA.
746 outsize = (outsize + 3) & ~3;
748 /* we need to tell the client where the next part of the reply will be */
749 SSVAL(outbuf,smb_vwv1,smb_offset(outbuf+outsize,outbuf));
750 CVAL(outbuf,smb_vwv0) = smb_com2;
752 /* remember how much the caller added to the chain, only counting stuff
753 after the parameter words */
754 chain_size += outsize - smb_wct;
756 /* work out pointers into the original packets. The
757 headers on these need to be filled in */
758 inbuf2 = orig_inbuf + smb_off2 + 4 - smb_wct;
759 outbuf2 = orig_outbuf + SVAL(outbuf,smb_vwv1) + 4 - smb_wct;
761 /* remember the original command type */
762 smb_com1 = CVAL(orig_inbuf,smb_com);
764 /* save the data which will be overwritten by the new headers */
765 memcpy(inbuf_saved,inbuf2,smb_wct);
766 memcpy(outbuf_saved,outbuf2,smb_wct);
768 /* give the new packet the same header as the last part of the SMB */
769 memmove(inbuf2,inbuf,smb_wct);
771 /* create the in buffer */
772 CVAL(inbuf2,smb_com) = smb_com2;
774 /* create the out buffer */
775 construct_reply_common(inbuf2, outbuf2);
777 DEBUG(3,("Chained message\n"));
778 show_msg(inbuf2);
780 /* process the request */
781 outsize2 = switch_message(smb_com2,inbuf2,outbuf2,size-chain_size,
782 bufsize-chain_size);
784 /* copy the new reply and request headers over the old ones, but
785 preserve the smb_com field */
786 memmove(orig_outbuf,outbuf2,smb_wct);
787 CVAL(orig_outbuf,smb_com) = smb_com1;
789 /* restore the saved data, being careful not to overwrite any
790 data from the reply header */
791 memcpy(inbuf2,inbuf_saved,smb_wct);
793 int ofs = smb_wct - PTR_DIFF(outbuf2,orig_outbuf);
794 if (ofs < 0) ofs = 0;
795 memmove(outbuf2+ofs,outbuf_saved+ofs,smb_wct-ofs);
798 return outsize2;
801 /****************************************************************************
802 Setup the needed select timeout.
803 ****************************************************************************/
805 static int setup_select_timeout(void)
807 int change_notify_timeout = lp_change_notify_timeout() * 1000;
808 int select_timeout;
811 * Increase the select timeout back to SMBD_SELECT_TIMEOUT if we
812 * have removed any blocking locks. JRA.
815 select_timeout = blocking_locks_pending() ? SMBD_SELECT_TIMEOUT_WITH_PENDING_LOCKS*1000 :
816 SMBD_SELECT_TIMEOUT*1000;
818 if (change_notifies_pending())
819 select_timeout = MIN(select_timeout, change_notify_timeout);
821 return select_timeout;
824 /****************************************************************************
825 Check if services need reloading.
826 ****************************************************************************/
828 void check_reload(int t)
830 static time_t last_smb_conf_reload_time = 0;
832 if(last_smb_conf_reload_time == 0)
833 last_smb_conf_reload_time = t;
835 if (reload_after_sighup || (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK))
837 reload_services(True);
838 reload_after_sighup = False;
839 last_smb_conf_reload_time = t;
843 /****************************************************************************
844 Process any timeout housekeeping. Return False if the caler should exit.
845 ****************************************************************************/
847 static BOOL timeout_processing(int deadtime, int *select_timeout, time_t *last_timeout_processing_time)
849 extern int Client;
850 static time_t last_keepalive_sent_time = 0;
851 static time_t last_idle_closed_check = 0;
852 time_t t;
853 BOOL allidle = True;
854 extern int keepalive;
856 if (smb_read_error == READ_EOF)
858 DEBUG(3,("end of file from client\n"));
859 return False;
862 if (smb_read_error == READ_ERROR)
864 DEBUG(3,("receive_smb error (%s) exiting\n",
865 strerror(errno)));
866 return False;
869 *last_timeout_processing_time = t = time(NULL);
871 if(last_keepalive_sent_time == 0)
872 last_keepalive_sent_time = t;
874 if(last_idle_closed_check == 0)
875 last_idle_closed_check = t;
877 /* become root again if waiting */
878 unbecome_user();
880 /* check if we need to reload services */
881 check_reload(t);
883 /* automatic timeout if all connections are closed */
884 if (conn_num_open()==0 && (t - last_idle_closed_check) >= IDLE_CLOSED_TIMEOUT)
886 DEBUG( 2, ( "Closing idle connection\n" ) );
887 return False;
889 else
890 last_idle_closed_check = t;
892 if (keepalive && (t - last_keepalive_sent_time)>keepalive)
894 struct cli_state *cli = server_client();
895 if (!send_keepalive(Client)) {
896 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
897 return False;
899 /* also send a keepalive to the password server if its still
900 connected */
901 if (cli && cli->initialised)
902 send_keepalive(cli->fd);
903 last_keepalive_sent_time = t;
906 /* check for connection timeouts */
907 allidle = conn_idle_all(t, deadtime);
909 if (allidle && conn_num_open()>0) {
910 DEBUG(2,("Closing idle connection 2.\n"));
911 return False;
913 #ifdef RPCLIENT
914 if(global_machine_password_needs_changing)
916 unsigned char trust_passwd_hash[16];
917 time_t lct;
918 pstring remote_machine_list;
921 * We're in domain level security, and the code that
922 * read the machine password flagged that the machine
923 * password needs changing.
927 * First, open the machine password file with an exclusive lock.
930 if(!trust_password_lock( global_myworkgroup, global_myname, True)) {
931 DEBUG(0,("process: unable to open the machine account password file for \
932 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
933 return True;
936 if(!get_trust_account_password( trust_passwd_hash, &lct)) {
937 DEBUG(0,("process: unable to read the machine account password for \
938 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
939 trust_password_unlock();
940 return True;
944 * Make sure someone else hasn't already done this.
947 if(t < lct + lp_machine_password_timeout()) {
948 trust_password_unlock();
949 global_machine_password_needs_changing = False;
950 return True;
953 pstrcpy(remote_machine_list, lp_passwordserver());
955 change_trust_account_password( global_myworkgroup, remote_machine_list);
956 trust_password_unlock();
957 global_machine_password_needs_changing = False;
959 #endif
961 * Check to see if we have any blocking locks
962 * outstanding on the queue.
964 process_blocking_lock_queue(t);
967 * Check to see if we have any change notifies
968 * outstanding on the queue.
970 process_pending_change_notify_queue(t);
973 * Now we are root, check if the log files need pruning.
975 if(need_to_check_log_size())
976 check_log_size();
979 * Modify the select timeout depending upon
980 * what we have remaining in our queues.
983 *select_timeout = setup_select_timeout();
985 return True;
988 /****************************************************************************
989 process commands from the client
990 ****************************************************************************/
992 void smbd_process(void)
994 extern int smb_echo_count;
995 time_t last_timeout_processing_time = time(NULL);
996 unsigned int num_smbs = 0;
998 InBuffer = (char *)malloc(BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE + SAFETY_MARGIN);
999 OutBuffer = (char *)malloc(BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE + SAFETY_MARGIN);
1000 if ((InBuffer == NULL) || (OutBuffer == NULL))
1001 return;
1003 InBuffer += SMB_ALIGNMENT;
1004 OutBuffer += SMB_ALIGNMENT;
1006 max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
1008 /* re-initialise the timezone */
1009 TimeInit();
1011 while (True)
1013 int deadtime = lp_deadtime()*60;
1014 BOOL got_smb = False;
1015 int select_timeout = setup_select_timeout();
1017 if (deadtime <= 0)
1018 deadtime = DEFAULT_SMBD_TIMEOUT;
1020 #if USE_READ_PREDICTION
1021 if (lp_readprediction())
1022 do_read_prediction();
1023 #endif
1025 errno = 0;
1027 /* free up temporary memory */
1028 lp_talloc_free();
1030 while(!receive_message_or_smb(InBuffer,BUFFER_SIZE+LARGE_WRITEX_HDR_SIZE,select_timeout,&got_smb))
1032 if(!timeout_processing( deadtime, &select_timeout, &last_timeout_processing_time))
1033 return;
1034 num_smbs = 0; /* Reset smb counter. */
1037 if(got_smb) {
1039 * Ensure we do timeout processing if the SMB we just got was
1040 * only an echo request. This allows us to set the select
1041 * timeout in 'receive_message_or_smb()' to any value we like
1042 * without worrying that the client will send echo requests
1043 * faster than the select timeout, thus starving out the
1044 * essential processing (change notify, blocking locks) that
1045 * the timeout code does. JRA.
1047 int num_echos = smb_echo_count;
1049 process_smb(InBuffer, OutBuffer);
1051 if(smb_echo_count != num_echos) {
1052 if(!timeout_processing( deadtime, &select_timeout, &last_timeout_processing_time))
1053 return;
1054 num_smbs = 0; /* Reset smb counter. */
1057 num_smbs++;
1060 * If we are getting smb requests in a constant stream
1061 * with no echos, make sure we attempt timeout processing
1062 * every select_timeout milliseconds - but only check for this
1063 * every 200 smb requests.
1066 if((num_smbs % 200) == 0) {
1067 time_t new_check_time = time(NULL);
1068 if(last_timeout_processing_time - new_check_time >= (select_timeout/1000)) {
1069 if(!timeout_processing( deadtime, &select_timeout, &last_timeout_processing_time))
1070 return;
1071 num_smbs = 0; /* Reset smb counter. */
1072 last_timeout_processing_time = new_check_time; /* Reset time. */
1076 else
1077 process_local_message(InBuffer, BUFFER_SIZE);