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