7d6e171d0532f1e9006bf58baed0998ad2cd23de
[tprouty/samba.git] / source / smbd / process.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    process incoming packets - main loop
5    Copyright (C) Andrew Tridgell 1992-1998
6    
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.
11    
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.
16    
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.
20 */
21
22 #include "includes.h"
23
24 extern int DEBUGLEVEL;
25
26 struct timeval smb_last_time;
27
28 static char *InBuffer = NULL;
29 char *OutBuffer = NULL;
30 char *last_inbuf = NULL;
31
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.
36  */
37 int max_send = BUFFER_SIZE;
38 /*
39  * Size of the data we can receive. Set by us.
40  * Can be modified by the max xmit parameter.
41  */
42 int max_recv = BUFFER_SIZE;
43
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;
56
57 /****************************************************************************
58  structure to hold a linked list of queued messages.
59  for processing.
60 ****************************************************************************/
61
62 typedef struct {
63    ubi_slNode msg_next;
64    char *msg_buf;
65    int msg_len;
66 } pending_message_list;
67
68 static ubi_slList smb_oplock_queue = { NULL, (ubi_slNodePtr)&smb_oplock_queue, 0};
69
70 /****************************************************************************
71  Function to push a message onto the tail of a linked list of smb messages ready
72  for processing.
73 ****************************************************************************/
74
75 static BOOL push_message(ubi_slList *list_head, char *buf, int msg_len)
76 {
77   pending_message_list *msg = (pending_message_list *)
78                                malloc(sizeof(pending_message_list));
79
80   if(msg == NULL)
81   {
82     DEBUG(0,("push_message: malloc fail (1)\n"));
83     return False;
84   }
85
86   msg->msg_buf = (char *)malloc(msg_len);
87   if(msg->msg_buf == NULL)
88   {
89     DEBUG(0,("push_message: malloc fail (2)\n"));
90     free((char *)msg);
91     return False;
92   }
93
94   memcpy(msg->msg_buf, buf, msg_len);
95   msg->msg_len = msg_len;
96
97   ubi_slAddTail( list_head, msg);
98
99   return True;
100 }
101
102 /****************************************************************************
103  Function to push a smb message onto a linked list of local smb messages ready
104  for processing.
105 ****************************************************************************/
106
107 BOOL push_oplock_pending_smb_message(char *buf, int msg_len)
108 {
109   return push_message(&smb_oplock_queue, buf, msg_len);
110 }
111
112 /****************************************************************************
113   Do a select on an two fd's - with timeout. 
114
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.
118
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.
122
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.
129
130 The timeout is in milli seconds
131 ****************************************************************************/
132
133 static BOOL receive_message_or_smb(char *buffer, int buffer_len, 
134                                    int timeout, BOOL *got_smb)
135 {
136   extern int Client;
137   fd_set fds;
138   int selrtn;
139   struct timeval to;
140   int maxfd;
141
142   smb_read_error = 0;
143
144   *got_smb = False;
145
146   /*
147    * Check to see if we already have a message on the smb queue.
148    * If so - copy and return it.
149    */
150   
151   if(ubi_slCount(&smb_oplock_queue) != 0)
152   {
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));
155   
156     /* Free the message we just copied. */
157     free((char *)msg->msg_buf);
158     free((char *)msg);
159     *got_smb = True;
160
161     DEBUG(5,("receive_message_or_smb: returning queued smb message.\n"));
162     return True;
163   }
164
165   /*
166    * Setup the select read fd set.
167    */
168
169   FD_ZERO(&fds);
170   FD_SET(Client,&fds);
171   maxfd = setup_oplock_select_set(&fds);
172
173   to.tv_sec = timeout / 1000;
174   to.tv_usec = (timeout % 1000) * 1000;
175
176   selrtn = sys_select(MAX(maxfd,Client)+1,&fds,timeout>0?&to:NULL);
177
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;
183   } 
184     
185   /* Did we timeout ? */
186   if (selrtn == 0) {
187     smb_read_error = READ_TIMEOUT;
188     return False;
189   }
190
191   if (FD_ISSET(Client,&fds))
192   {
193     *got_smb = True;
194     return receive_smb(Client, buffer, 0);
195   }
196   else
197   {
198     return receive_local_message(&fds, buffer, buffer_len, 0);
199   }
200 }
201
202 /****************************************************************************
203 Get the next SMB packet, doing the local message processing automatically.
204 ****************************************************************************/
205
206 BOOL receive_next_smb(char *inbuf, int bufsize, int timeout)
207 {
208   BOOL got_smb = False;
209   BOOL ret;
210
211   do
212   {
213     ret = receive_message_or_smb(inbuf,bufsize,timeout,&got_smb);
214
215     if(ret && !got_smb)
216     {
217       /* Deal with oplock break requests from other smbd's. */
218       process_local_message(inbuf, bufsize);
219       continue;
220     }
221
222     if(ret && (CVAL(inbuf,0) == 0x85))
223     {
224       /* Keepalive packet. */
225       got_smb = False;
226     }
227
228   }
229   while(ret && !got_smb);
230
231   return ret;
232 }
233
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 ****************************************************************************/
240
241 void respond_to_all_remaining_local_messages(void)
242 {
243   char buffer[1024];
244   fd_set fds;
245
246   /*
247    * Assert we have no exclusive open oplocks.
248    */
249
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;
254   }
255
256   /*
257    * Setup the select read fd set.
258    */
259
260   FD_ZERO(&fds);
261   if(!setup_oplock_select_set(&fds))
262     return;
263
264   /*
265    * Keep doing receive_local_message with a 1 ms timeout until
266    * we have no more messages.
267    */
268
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));
272
273     FD_ZERO(&fds);
274     (void)setup_oplock_select_set(&fds);
275   }
276
277   return;
278 }
279
280
281 /*
282 These flags determine some of the permissions required to do an operation 
283
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.
287 */
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)
294
295 /* 
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!
299 */
300 struct smb_message_struct
301 {
302   int code;
303   char *name;
304   int (*fn)(connection_struct *conn, char *, char *, int, int);
305   int flags;
306 }
307  smb_messages[] = {
308
309     /* CORE PROTOCOL */
310
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 },
325
326    /* note that SMBmknew and SMBcreate are deliberately overloaded */   
327    {SMBcreate,"SMBcreate",reply_mknew,AS_USER},
328    {SMBmknew,"SMBmknew",reply_mknew,AS_USER}, 
329
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},
338
339    /* this is a Pathworks specific call, allowing the 
340       changing of the root path */
341    {pSETDIR,"pSETDIR",reply_setdir,AS_USER}, 
342
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    {SMBsplopen,"SMBsplopen",reply_printopen,AS_USER | QUEUE_IN_OPLOCK },
347    {SMBsplclose,"SMBsplclose",reply_printclose,AS_USER},
348    {SMBsplretq,"SMBsplretq",reply_printqueue,AS_USER},
349    {SMBsplwr,"SMBsplwr",reply_printwrite,AS_USER},
350    {SMBlock,"SMBlock",reply_lock,AS_USER},
351    {SMBunlock,"SMBunlock",reply_unlock,AS_USER},
352    
353    /* CORE+ PROTOCOL FOLLOWS */
354    
355    {SMBreadbraw,"SMBreadbraw",reply_readbraw,AS_USER},
356    {SMBwritebraw,"SMBwritebraw",reply_writebraw,AS_USER},
357    {SMBwriteclose,"SMBwriteclose",reply_writeclose,AS_USER},
358    {SMBlockread,"SMBlockread",reply_lockread,AS_USER},
359    {SMBwriteunlock,"SMBwriteunlock",reply_writeunlock,AS_USER},
360    
361    /* LANMAN1.0 PROTOCOL FOLLOWS */
362    
363    {SMBreadBmpx,"SMBreadBmpx",reply_readbmpx,AS_USER},
364    {SMBreadBs,"SMBreadBs",NULL,AS_USER},
365    {SMBwriteBmpx,"SMBwriteBmpx",reply_writebmpx,AS_USER},
366    {SMBwriteBs,"SMBwriteBs",reply_writebs,AS_USER},
367    {SMBwritec,"SMBwritec",NULL,AS_USER},
368    {SMBsetattrE,"SMBsetattrE",reply_setattrE,AS_USER | NEED_WRITE },
369    {SMBgetattrE,"SMBgetattrE",reply_getattrE,AS_USER },
370    {SMBtrans,"SMBtrans",reply_trans,AS_USER | CAN_IPC | QUEUE_IN_OPLOCK},
371    {SMBtranss,"SMBtranss",NULL,AS_USER | CAN_IPC},
372    {SMBioctls,"SMBioctls",NULL,AS_USER},
373    {SMBcopy,"SMBcopy",reply_copy,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
374    {SMBmove,"SMBmove",NULL,AS_USER | NEED_WRITE | QUEUE_IN_OPLOCK },
375    
376    {SMBopenX,"SMBopenX",reply_open_and_X,AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
377    {SMBreadX,"SMBreadX",reply_read_and_X,AS_USER | CAN_IPC },
378    {SMBwriteX,"SMBwriteX",reply_write_and_X,AS_USER | CAN_IPC },
379    {SMBlockingX,"SMBlockingX",reply_lockingX,AS_USER },
380    
381    {SMBffirst,"SMBffirst",reply_search,AS_USER},
382    {SMBfunique,"SMBfunique",reply_search,AS_USER},
383    {SMBfclose,"SMBfclose",reply_fclose,AS_USER},
384
385    /* LANMAN2.0 PROTOCOL FOLLOWS */
386    {SMBfindnclose, "SMBfindnclose", reply_findnclose, AS_USER},
387    {SMBfindclose, "SMBfindclose", reply_findclose,AS_USER},
388    {SMBtrans2, "SMBtrans2", reply_trans2, AS_USER | QUEUE_IN_OPLOCK },
389    {SMBtranss2, "SMBtranss2", reply_transs2, AS_USER},
390
391    /* NT PROTOCOL FOLLOWS */
392    {SMBntcreateX, "SMBntcreateX", reply_ntcreate_and_X, AS_USER | CAN_IPC | QUEUE_IN_OPLOCK },
393    {SMBnttrans, "SMBnttrans", reply_nttrans, AS_USER | CAN_IPC | QUEUE_IN_OPLOCK},
394    {SMBnttranss, "SMBnttranss", reply_nttranss, AS_USER | CAN_IPC },
395    {SMBntcancel, "SMBntcancel", reply_ntcancel, 0 },
396
397    /* messaging routines */
398    {SMBsends,"SMBsends",reply_sends,AS_GUEST},
399    {SMBsendstrt,"SMBsendstrt",reply_sendstrt,AS_GUEST},
400    {SMBsendend,"SMBsendend",reply_sendend,AS_GUEST},
401    {SMBsendtxt,"SMBsendtxt",reply_sendtxt,AS_GUEST},
402
403    /* NON-IMPLEMENTED PARTS OF THE CORE PROTOCOL */
404    
405    {SMBsendb,"SMBsendb",NULL,AS_GUEST},
406    {SMBfwdname,"SMBfwdname",NULL,AS_GUEST},
407    {SMBcancelf,"SMBcancelf",NULL,AS_GUEST},
408    {SMBgetmac,"SMBgetmac",NULL,AS_GUEST}
409  };
410
411
412 /****************************************************************************
413 do a switch on the message type, and return the response size
414 ****************************************************************************/
415 static int switch_message(int type,char *inbuf,char *outbuf,int size,int bufsize)
416 {
417   static pid_t pid= (pid_t)-1;
418   int outsize = 0;
419   static int num_smb_messages = 
420     sizeof(smb_messages) / sizeof(struct smb_message_struct);
421   int match;
422   extern int Client;
423   extern int global_smbpid;
424
425   if (pid == (pid_t)-1)
426     pid = getpid();
427
428   errno = 0;
429   last_message = type;
430
431   /* make sure this is an SMB packet */
432   if (strncmp(smb_base(inbuf),"\377SMB",4) != 0)
433   {
434     DEBUG(2,("Non-SMB packet of length %d\n",smb_len(inbuf)));
435     return(-1);
436   }
437
438   for (match=0;match<num_smb_messages;match++)
439     if (smb_messages[match].code == type)
440       break;
441
442   /* yuck! this is an interim measure before we get rid of our
443      current inbuf/outbuf system */
444   global_smbpid = SVAL(inbuf,smb_pid);
445
446   if (match == num_smb_messages)
447   {
448     DEBUG(0,("Unknown message type %d!\n",type));
449     outsize = reply_unknown(inbuf,outbuf);
450   }
451   else
452   {
453     DEBUG(3,("switch message %s (pid %d)\n",smb_messages[match].name,(int)pid));
454
455     if(global_oplock_break)
456     {
457       int flags = smb_messages[match].flags;
458
459       if(flags & QUEUE_IN_OPLOCK)
460       {
461         /* 
462          * Queue this message as we are the process of an oplock break.
463          */
464
465         DEBUG( 2, ( "switch_message: queueing message due to being in " ) );
466         DEBUGADD( 2, ( "oplock break state.\n" ) );
467
468         push_oplock_pending_smb_message( inbuf, size );
469         return -1;
470       }          
471     }
472     if (smb_messages[match].fn)
473     {
474       int flags = smb_messages[match].flags;
475       static uint16 last_session_tag = UID_FIELD_INVALID;
476       /* In share mode security we must ignore the vuid. */
477       uint16 session_tag = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : SVAL(inbuf,smb_uid);
478       connection_struct *conn = conn_find(SVAL(inbuf,smb_tid));
479
480
481       /* Ensure this value is replaced in the incoming packet. */
482       SSVAL(inbuf,smb_uid,session_tag);
483
484       /*
485        * Ensure the correct username is in sesssetup_user.
486        * This is a really ugly bugfix for problems with
487        * multiple session_setup_and_X's being done and
488        * allowing %U and %G substitutions to work correctly.
489        * There is a reason this code is done here, don't
490        * move it unless you know what you're doing... :-).
491        * JRA.
492        */
493       if (session_tag != last_session_tag) {
494         user_struct *vuser = NULL;
495
496         last_session_tag = session_tag;
497         if(session_tag != UID_FIELD_INVALID)
498           vuser = get_valid_user_struct(session_tag);           
499         if(vuser != NULL)
500           pstrcpy( sesssetup_user, vuser->requested_name);
501       }
502
503       /* does this protocol need to be run as root? */
504       if (!(flags & AS_USER))
505         unbecome_user();
506
507       /* does this protocol need to be run as the connected user? */
508       if ((flags & AS_USER) && !become_user(conn,session_tag)) {
509         if (flags & AS_GUEST) 
510           flags &= ~AS_USER;
511         else
512           return(ERROR(ERRSRV,ERRaccess));
513       }
514       /* this code is to work around a bug is MS client 3 without
515          introducing a security hole - it needs to be able to do
516          print queue checks as guest if it isn't logged in properly */
517       if (flags & AS_USER)
518         flags &= ~AS_GUEST;
519
520       /* does it need write permission? */
521       if ((flags & NEED_WRITE) && !CAN_WRITE(conn))
522         return(ERROR(ERRSRV,ERRaccess));
523
524       /* ipc services are limited */
525       if (IS_IPC(conn) && (flags & AS_USER) && !(flags & CAN_IPC)) {
526         return(ERROR(ERRSRV,ERRaccess));            
527       }
528
529       /* load service specific parameters */
530       if (conn && 
531           !become_service(conn,(flags & AS_USER)?True:False)) {
532         return(ERROR(ERRSRV,ERRaccess));
533       }
534
535       /* does this protocol need to be run as guest? */
536       if ((flags & AS_GUEST) && 
537           (!become_guest() || 
538            !check_access(Client, lp_hostsallow(-1), lp_hostsdeny(-1)))) {
539         return(ERROR(ERRSRV,ERRaccess));
540       }
541
542       last_inbuf = inbuf;
543
544       outsize = smb_messages[match].fn(conn, inbuf,outbuf,size,bufsize);
545     }
546     else
547     {
548       outsize = reply_unknown(inbuf,outbuf);
549     }
550   }
551
552   return(outsize);
553 }
554
555
556 /****************************************************************************
557   construct a reply to the incoming packet
558 ****************************************************************************/
559 static int construct_reply(char *inbuf,char *outbuf,int size,int bufsize)
560 {
561   int type = CVAL(inbuf,smb_com);
562   int outsize = 0;
563   int msg_type = CVAL(inbuf,0);
564
565   GetTimeOfDay(&smb_last_time);
566
567   chain_size = 0;
568   file_chain_reset();
569   reset_chain_p();
570
571   if (msg_type != 0)
572     return(reply_special(inbuf,outbuf));  
573
574   construct_reply_common(inbuf, outbuf);
575
576   outsize = switch_message(type,inbuf,outbuf,size,bufsize);
577
578   outsize += chain_size;
579
580   if(outsize > 4)
581     smb_setlen(outbuf,outsize - 4);
582   return(outsize);
583 }
584
585
586 /****************************************************************************
587   process an smb from the client - split out from the process() code so
588   it can be used by the oplock break code.
589 ****************************************************************************/
590 void process_smb(char *inbuf, char *outbuf)
591 {
592   extern int Client;
593 #ifdef WITH_SSL
594   extern BOOL sslEnabled;     /* don't use function for performance reasons */
595   static int sslConnected = 0;
596 #endif /* WITH_SSL */
597   static int trans_num;
598   int msg_type = CVAL(inbuf,0);
599   int32 len = smb_len(inbuf);
600   int nread = len + 4;
601
602 #ifdef WITH_PROFILE
603   profile_p->smb_count++;
604 #endif
605
606   if (trans_num == 0) {
607           /* on the first packet, check the global hosts allow/ hosts
608              deny parameters before doing any parsing of the packet
609              passed to us by the client.  This prevents attacks on our
610              parsing code from hosts not in the hosts allow list */
611           if (!check_access(Client, lp_hostsallow(-1), lp_hostsdeny(-1))) {
612                   /* send a negative session response "not listining on calling
613                    name" */
614                   static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
615                   DEBUG( 1, ( "Connection denied from %s\n",
616                               client_addr(Client) ) );
617                   send_smb(Client,(char *)buf);
618                   exit_server("connection denied");
619           }
620   }
621
622   DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type, len ) );
623   DEBUG( 3, ( "Transaction %d of length %d\n", trans_num, nread ) );
624
625 #ifdef WITH_SSL
626     if(sslEnabled && !sslConnected){
627         sslConnected = sslutil_negotiate_ssl(Client, msg_type);
628         if(sslConnected < 0){   /* an error occured */
629             exit_server("SSL negotiation failed");
630         }else if(sslConnected){
631             trans_num++;
632             return;
633         }
634     }
635 #endif  /* WITH_SSL */
636
637 #ifdef WITH_VTP
638   if(trans_num == 1 && VT_Check(inbuf)) 
639   {
640     VT_Process();
641     return;
642   }
643 #endif
644
645   if (msg_type == 0)
646     show_msg(inbuf);
647   else if(msg_type == 0x85)
648     return; /* Keepalive packet. */
649
650   nread = construct_reply(inbuf,outbuf,nread,max_send);
651       
652   if(nread > 0) 
653   {
654     if (CVAL(outbuf,0) == 0)
655       show_msg(outbuf);
656         
657     if (nread != smb_len(outbuf) + 4) 
658     {
659       DEBUG(0,("ERROR: Invalid message response size! %d %d\n",
660                  nread, smb_len(outbuf)));
661     }
662     else
663       send_smb(Client,outbuf);
664   }
665   trans_num++;
666 }
667
668
669
670 /****************************************************************************
671 return a string containing the function name of a SMB command
672 ****************************************************************************/
673 char *smb_fn_name(int type)
674 {
675         static char *unknown_name = "SMBunknown";
676         static int num_smb_messages = 
677                 sizeof(smb_messages) / sizeof(struct smb_message_struct);
678         int match;
679
680         for (match=0;match<num_smb_messages;match++)
681                 if (smb_messages[match].code == type)
682                         break;
683
684         if (match == num_smb_messages)
685                 return(unknown_name);
686
687         return(smb_messages[match].name);
688 }
689
690
691 /****************************************************************************
692  Helper function for contruct_reply.
693 ****************************************************************************/
694
695 void construct_reply_common(char *inbuf,char *outbuf)
696 {
697   memset(outbuf,'\0',smb_size);
698
699   set_message(outbuf,0,0,True);
700   CVAL(outbuf,smb_com) = CVAL(inbuf,smb_com);
701
702   memcpy(outbuf+4,inbuf+4,4);
703   CVAL(outbuf,smb_rcls) = SMB_SUCCESS;
704   CVAL(outbuf,smb_reh) = 0;
705   SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES)); /* bit 7 set
706                                  means a reply */
707   SSVAL(outbuf,smb_flg2,FLAGS2_LONG_PATH_COMPONENTS); /* say we support long filenames */
708   SSVAL(outbuf,smb_err,SMB_SUCCESS);
709   SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
710   SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
711   SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
712   SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
713 }
714
715 /****************************************************************************
716   construct a chained reply and add it to the already made reply
717   **************************************************************************/
718 int chain_reply(char *inbuf,char *outbuf,int size,int bufsize)
719 {
720   static char *orig_inbuf;
721   static char *orig_outbuf;
722   int smb_com1, smb_com2 = CVAL(inbuf,smb_vwv0);
723   unsigned smb_off2 = SVAL(inbuf,smb_vwv1);
724   char *inbuf2, *outbuf2;
725   int outsize2;
726   char inbuf_saved[smb_wct];
727   char outbuf_saved[smb_wct];
728   int wct = CVAL(outbuf,smb_wct);
729   int outsize = smb_size + 2*wct + SVAL(outbuf,smb_vwv0+2*wct);
730
731   /* maybe its not chained */
732   if (smb_com2 == 0xFF) {
733     CVAL(outbuf,smb_vwv0) = 0xFF;
734     return outsize;
735   }
736
737   if (chain_size == 0) {
738     /* this is the first part of the chain */
739     orig_inbuf = inbuf;
740     orig_outbuf = outbuf;
741   }
742
743   /*
744    * The original Win95 redirector dies on a reply to
745    * a lockingX and read chain unless the chain reply is
746    * 4 byte aligned. JRA.
747    */
748
749   outsize = (outsize + 3) & ~3;
750
751   /* we need to tell the client where the next part of the reply will be */
752   SSVAL(outbuf,smb_vwv1,smb_offset(outbuf+outsize,outbuf));
753   CVAL(outbuf,smb_vwv0) = smb_com2;
754
755   /* remember how much the caller added to the chain, only counting stuff
756      after the parameter words */
757   chain_size += outsize - smb_wct;
758
759   /* work out pointers into the original packets. The
760      headers on these need to be filled in */
761   inbuf2 = orig_inbuf + smb_off2 + 4 - smb_wct;
762   outbuf2 = orig_outbuf + SVAL(outbuf,smb_vwv1) + 4 - smb_wct;
763
764   /* remember the original command type */
765   smb_com1 = CVAL(orig_inbuf,smb_com);
766
767   /* save the data which will be overwritten by the new headers */
768   memcpy(inbuf_saved,inbuf2,smb_wct);
769   memcpy(outbuf_saved,outbuf2,smb_wct);
770
771   /* give the new packet the same header as the last part of the SMB */
772   memmove(inbuf2,inbuf,smb_wct);
773
774   /* create the in buffer */
775   CVAL(inbuf2,smb_com) = smb_com2;
776
777   /* create the out buffer */
778   construct_reply_common(inbuf2, outbuf2);
779
780   DEBUG(3,("Chained message\n"));
781   show_msg(inbuf2);
782
783   /* process the request */
784   outsize2 = switch_message(smb_com2,inbuf2,outbuf2,size-chain_size,
785                             bufsize-chain_size);
786
787   /* copy the new reply and request headers over the old ones, but
788      preserve the smb_com field */
789   memmove(orig_outbuf,outbuf2,smb_wct);
790   CVAL(orig_outbuf,smb_com) = smb_com1;
791
792   /* restore the saved data, being careful not to overwrite any
793    data from the reply header */
794   memcpy(inbuf2,inbuf_saved,smb_wct);
795   {
796     int ofs = smb_wct - PTR_DIFF(outbuf2,orig_outbuf);
797     if (ofs < 0) ofs = 0;
798     memmove(outbuf2+ofs,outbuf_saved+ofs,smb_wct-ofs);
799   }
800
801   return outsize2;
802 }
803
804 /****************************************************************************
805  Setup the needed select timeout.
806 ****************************************************************************/
807
808 static int setup_select_timeout(void)
809 {
810   int change_notify_timeout = lp_change_notify_timeout() * 1000;
811   int select_timeout;
812
813   /*
814    * Increase the select timeout back to SMBD_SELECT_TIMEOUT if we
815    * have removed any blocking locks. JRA.
816    */
817
818   select_timeout = blocking_locks_pending() ? SMBD_SELECT_TIMEOUT_WITH_PENDING_LOCKS*1000 :
819                                               SMBD_SELECT_TIMEOUT*1000;
820
821   if (change_notifies_pending())
822     select_timeout = MIN(select_timeout, change_notify_timeout);
823
824   return select_timeout;
825 }
826
827 /****************************************************************************
828  Check if services need reloading.
829 ****************************************************************************/
830
831 void check_reload(int t)
832 {
833   static time_t last_smb_conf_reload_time = 0;
834
835   if(last_smb_conf_reload_time == 0)
836     last_smb_conf_reload_time = t;
837
838   if (reload_after_sighup || (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK))
839   {
840     reload_services(True);
841     reload_after_sighup = False;
842     last_smb_conf_reload_time = t;
843   }
844 }
845
846 /****************************************************************************
847  Process any timeout housekeeping. Return False if the caller should exit.
848 ****************************************************************************/
849
850 static BOOL timeout_processing(int deadtime, int *select_timeout, time_t *last_timeout_processing_time)
851 {
852   extern int Client;
853   static time_t last_keepalive_sent_time = 0;
854   static time_t last_idle_closed_check = 0;
855   time_t t;
856   BOOL allidle = True;
857   extern int keepalive;
858
859   if (smb_read_error == READ_EOF) 
860   {
861     DEBUG(3,("end of file from client\n"));
862     return False;
863   }
864
865   if (smb_read_error == READ_ERROR) 
866   {
867     DEBUG(3,("receive_smb error (%s) exiting\n",
868               strerror(errno)));
869     return False;
870   }
871
872   *last_timeout_processing_time = t = time(NULL);
873
874   if(last_keepalive_sent_time == 0)
875     last_keepalive_sent_time = t;
876
877   if(last_idle_closed_check == 0)
878     last_idle_closed_check = t;
879
880   /* become root again if waiting */
881   unbecome_user();
882
883   /* check if we need to reload services */
884   check_reload(t);
885
886   /* automatic timeout if all connections are closed */      
887   if (conn_num_open()==0 && (t - last_idle_closed_check) >= IDLE_CLOSED_TIMEOUT) 
888   {
889     DEBUG( 2, ( "Closing idle connection\n" ) );
890     return False;
891   }
892   else
893     last_idle_closed_check = t;
894
895   if (keepalive && (t - last_keepalive_sent_time)>keepalive) 
896   {
897     struct cli_state *cli = server_client();
898     if (!send_keepalive(Client)) {
899       DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
900       return False;
901     }       
902     /* also send a keepalive to the password server if its still
903        connected */
904     if (cli && cli->initialised)
905       send_keepalive(cli->fd);
906     last_keepalive_sent_time = t;
907   }
908
909   /* check for connection timeouts */
910   allidle = conn_idle_all(t, deadtime);
911
912   if (allidle && conn_num_open()>0) {
913     DEBUG(2,("Closing idle connection 2.\n"));
914     return False;
915   }
916
917   if(global_machine_password_needs_changing)
918   {
919     unsigned char trust_passwd_hash[16];
920     time_t lct;
921     pstring remote_machine_list;
922
923     /*
924      * We're in domain level security, and the code that
925      * read the machine password flagged that the machine
926      * password needs changing.
927      */
928
929     /*
930      * First, open the machine password file with an exclusive lock.
931      */
932
933     if(!trust_password_lock( global_myworkgroup, global_myname, True)) {
934       DEBUG(0,("process: unable to open the machine account password file for \
935 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
936       return True;
937     }
938
939     if(!get_trust_account_password( trust_passwd_hash, &lct)) {
940       DEBUG(0,("process: unable to read the machine account password for \
941 machine %s in domain %s.\n", global_myname, global_myworkgroup ));
942       trust_password_unlock();
943       return True;
944     }
945
946     /*
947      * Make sure someone else hasn't already done this.
948      */
949
950     if(t < lct + lp_machine_password_timeout()) {
951       trust_password_unlock();
952       global_machine_password_needs_changing = False;
953       return True;
954     }
955
956     pstrcpy(remote_machine_list, lp_passwordserver());
957
958     change_trust_account_password( global_myworkgroup, remote_machine_list);
959     trust_password_unlock();
960     global_machine_password_needs_changing = False;
961   }
962
963   /*
964    * Check to see if we have any blocking locks
965    * outstanding on the queue.
966    */
967   process_blocking_lock_queue(t);
968
969   /*
970    * Check to see if we have any change notifies 
971    * outstanding on the queue.
972    */
973   process_pending_change_notify_queue(t);
974
975   /*
976    * Modify the select timeout depending upon
977    * what we have remaining in our queues.
978    */
979
980   *select_timeout = setup_select_timeout();
981
982   return True;
983 }
984
985 /****************************************************************************
986   process commands from the client
987 ****************************************************************************/
988
989 void smbd_process(void)
990 {
991   extern int smb_echo_count;
992   time_t last_timeout_processing_time = time(NULL);
993   unsigned int num_smbs = 0;
994
995   InBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
996   OutBuffer = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
997   if ((InBuffer == NULL) || (OutBuffer == NULL)) 
998     return;
999
1000   InBuffer += SMB_ALIGNMENT;
1001   OutBuffer += SMB_ALIGNMENT;
1002
1003   max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
1004
1005   /* re-initialise the timezone */
1006   TimeInit();
1007
1008   while (True)
1009   {
1010     int deadtime = lp_deadtime()*60;
1011     BOOL got_smb = False;
1012     int select_timeout = setup_select_timeout();
1013
1014     if (deadtime <= 0)
1015       deadtime = DEFAULT_SMBD_TIMEOUT;
1016
1017 #if USE_READ_PREDICTION
1018     if (lp_readprediction())
1019       do_read_prediction();
1020 #endif
1021
1022     errno = 0;      
1023
1024     /* free up temporary memory */
1025     lp_talloc_free();
1026
1027     while(!receive_message_or_smb(InBuffer,BUFFER_SIZE,select_timeout,&got_smb))
1028     {
1029       if(!timeout_processing( deadtime, &select_timeout, &last_timeout_processing_time))
1030         return;
1031       num_smbs = 0; /* Reset smb counter. */
1032     }
1033
1034     if(got_smb) {
1035       /*
1036        * Ensure we do timeout processing if the SMB we just got was
1037        * only an echo request. This allows us to set the select
1038        * timeout in 'receive_message_or_smb()' to any value we like
1039        * without worrying that the client will send echo requests
1040        * faster than the select timeout, thus starving out the
1041        * essential processing (change notify, blocking locks) that
1042        * the timeout code does. JRA.
1043        */ 
1044       int num_echos = smb_echo_count;
1045
1046       process_smb(InBuffer, OutBuffer);
1047
1048       if(smb_echo_count != num_echos) {
1049         if(!timeout_processing( deadtime, &select_timeout, &last_timeout_processing_time))
1050           return;
1051         num_smbs = 0; /* Reset smb counter. */
1052       }
1053
1054       num_smbs++;
1055
1056       /*
1057        * If we are getting smb requests in a constant stream
1058        * with no echos, make sure we attempt timeout processing
1059        * every select_timeout milliseconds - but only check for this
1060        * every 200 smb requests.
1061        */
1062
1063       if((num_smbs % 200) == 0) {
1064         time_t new_check_time = time(NULL);
1065         if(last_timeout_processing_time - new_check_time >= (select_timeout/1000)) {
1066           if(!timeout_processing( deadtime, &select_timeout, &last_timeout_processing_time))
1067             return;
1068           num_smbs = 0; /* Reset smb counter. */
1069           last_timeout_processing_time = new_check_time; /* Reset time. */
1070         }
1071       }
1072     }
1073     else
1074       process_local_message(InBuffer, BUFFER_SIZE);
1075   }
1076 }