29b942de81cc17e472873bf9319fb098f5de05b8
[samba.git] / source / smbd / process.c
1 /* 
2    Unix SMB/CIFS implementation.
3    process incoming packets - main loop
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Volker Lendecke 2005-2007
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 3 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, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22
23 extern struct auth_context *negprot_global_auth_context;
24 extern int smb_echo_count;
25
26 const int total_buffer_size = (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE + SAFETY_MARGIN);
27
28 /* 
29  * Size of data we can send to client. Set
30  *  by the client for all protocols above CORE.
31  *  Set by us for CORE protocol.
32  */
33 int max_send = BUFFER_SIZE;
34 /*
35  * Size of the data we can receive. Set by us.
36  * Can be modified by the max xmit parameter.
37  */
38 int max_recv = BUFFER_SIZE;
39
40 extern int last_message;
41 extern int smb_read_error;
42 SIG_ATOMIC_T reload_after_sighup = 0;
43 SIG_ATOMIC_T got_sig_term = 0;
44 extern BOOL global_machine_password_needs_changing;
45 extern int max_send;
46
47 /*
48  * Initialize a struct smb_request from an inbuf
49  */
50
51 void init_smb_request(struct smb_request *req, const uint8 *inbuf)
52 {
53         size_t req_size = smb_len(inbuf) + 4;
54         /* Ensure we have at least smb_size bytes. */
55         if (req_size < smb_size) {
56                 DEBUG(0,("init_smb_request: invalid request size %u\n",
57                         (unsigned int)req_size ));
58                 exit_server_cleanly("Invalid SMB request");
59         }
60         req->flags2 = SVAL(inbuf, smb_flg2);
61         req->smbpid = SVAL(inbuf, smb_pid);
62         req->mid    = SVAL(inbuf, smb_mid);
63         req->vuid   = SVAL(inbuf, smb_uid);
64         req->tid    = SVAL(inbuf, smb_tid);
65         req->wct    = CVAL(inbuf, smb_wct);
66         /* Ensure we have at least wct words and 2 bytes of bcc. */
67         if (smb_size + req->wct*2 > req_size) {
68                 DEBUG(0,("init_smb_request: invalid wct number %u (size %u)\n",
69                         (unsigned int)req->wct,
70                         (unsigned int)req_size));
71                 exit_server_cleanly("Invalid SMB request");
72         }
73         /* Ensure bcc is correct. */
74         if (((uint8 *)smb_buf(inbuf)) + smb_buflen(inbuf) > inbuf + req_size) {
75                 DEBUG(0,("init_smb_request: invalid bcc number %u "
76                         "(wct = %u, size %u)\n",
77                         (unsigned int)smb_buflen(inbuf),
78                         (unsigned int)req->wct,
79                         (unsigned int)req_size));
80                 exit_server_cleanly("Invalid SMB request");
81         }
82         req->inbuf  = inbuf;
83         req->outbuf = NULL;
84 }
85
86 /****************************************************************************
87  structure to hold a linked list of queued messages.
88  for processing.
89 ****************************************************************************/
90
91 static struct pending_message_list *deferred_open_queue;
92
93 /****************************************************************************
94  Function to push a message onto the tail of a linked list of smb messages
95  ready for processing.
96 ****************************************************************************/
97
98 static BOOL push_queued_message(struct smb_request *req,
99                                 struct timeval request_time,
100                                 struct timeval end_time,
101                                 char *private_data, size_t private_len)
102 {
103         int msg_len = smb_len(req->inbuf) + 4;
104         struct pending_message_list *msg;
105
106         msg = TALLOC_ZERO_P(NULL, struct pending_message_list);
107
108         if(msg == NULL) {
109                 DEBUG(0,("push_message: malloc fail (1)\n"));
110                 return False;
111         }
112
113         msg->buf = data_blob_talloc(msg, req->inbuf, msg_len);
114         if(msg->buf.data == NULL) {
115                 DEBUG(0,("push_message: malloc fail (2)\n"));
116                 TALLOC_FREE(msg);
117                 return False;
118         }
119
120         msg->request_time = request_time;
121         msg->end_time = end_time;
122
123         if (private_data) {
124                 msg->private_data = data_blob_talloc(msg, private_data,
125                                                      private_len);
126                 if (msg->private_data.data == NULL) {
127                         DEBUG(0,("push_message: malloc fail (3)\n"));
128                         TALLOC_FREE(msg);
129                         return False;
130                 }
131         }
132
133         DLIST_ADD_END(deferred_open_queue, msg, struct pending_message_list *);
134
135         DEBUG(10,("push_message: pushed message length %u on "
136                   "deferred_open_queue\n", (unsigned int)msg_len));
137
138         return True;
139 }
140
141 /****************************************************************************
142  Function to delete a sharing violation open message by mid.
143 ****************************************************************************/
144
145 void remove_deferred_open_smb_message(uint16 mid)
146 {
147         struct pending_message_list *pml;
148
149         for (pml = deferred_open_queue; pml; pml = pml->next) {
150                 if (mid == SVAL(pml->buf.data,smb_mid)) {
151                         DEBUG(10,("remove_deferred_open_smb_message: "
152                                   "deleting mid %u len %u\n",
153                                   (unsigned int)mid,
154                                   (unsigned int)pml->buf.length ));
155                         DLIST_REMOVE(deferred_open_queue, pml);
156                         TALLOC_FREE(pml);
157                         return;
158                 }
159         }
160 }
161
162 /****************************************************************************
163  Move a sharing violation open retry message to the front of the list and
164  schedule it for immediate processing.
165 ****************************************************************************/
166
167 void schedule_deferred_open_smb_message(uint16 mid)
168 {
169         struct pending_message_list *pml;
170         int i = 0;
171
172         for (pml = deferred_open_queue; pml; pml = pml->next) {
173                 uint16 msg_mid = SVAL(pml->buf.data,smb_mid);
174                 DEBUG(10, ("schedule_deferred_open_smb_message: [%d] "
175                            "msg_mid = %u\n", i++, (unsigned int)msg_mid ));
176                 if (mid == msg_mid) {
177                         DEBUG(10, ("schedule_deferred_open_smb_message: "
178                                    "scheduling mid %u\n", mid));
179                         pml->end_time.tv_sec = 0;
180                         pml->end_time.tv_usec = 0;
181                         DLIST_PROMOTE(deferred_open_queue, pml);
182                         return;
183                 }
184         }
185
186         DEBUG(10, ("schedule_deferred_open_smb_message: failed to find "
187                    "message mid %u\n", mid ));
188 }
189
190 /****************************************************************************
191  Return true if this mid is on the deferred queue.
192 ****************************************************************************/
193
194 BOOL open_was_deferred(uint16 mid)
195 {
196         struct pending_message_list *pml;
197
198         for (pml = deferred_open_queue; pml; pml = pml->next) {
199                 if (SVAL(pml->buf.data,smb_mid) == mid) {
200                         return True;
201                 }
202         }
203         return False;
204 }
205
206 /****************************************************************************
207  Return the message queued by this mid.
208 ****************************************************************************/
209
210 struct pending_message_list *get_open_deferred_message(uint16 mid)
211 {
212         struct pending_message_list *pml;
213
214         for (pml = deferred_open_queue; pml; pml = pml->next) {
215                 if (SVAL(pml->buf.data,smb_mid) == mid) {
216                         return pml;
217                 }
218         }
219         return NULL;
220 }
221
222 /****************************************************************************
223  Function to push a deferred open smb message onto a linked list of local smb
224  messages ready for processing.
225 ****************************************************************************/
226
227 BOOL push_deferred_smb_message(struct smb_request *req,
228                                struct timeval request_time,
229                                struct timeval timeout,
230                                char *private_data, size_t priv_len)
231 {
232         struct timeval end_time;
233
234         end_time = timeval_sum(&request_time, &timeout);
235
236         DEBUG(10,("push_deferred_open_smb_message: pushing message len %u mid %u "
237                   "timeout time [%u.%06u]\n",
238                   (unsigned int) smb_len(req->inbuf)+4, (unsigned int)req->mid,
239                   (unsigned int)end_time.tv_sec,
240                   (unsigned int)end_time.tv_usec));
241
242         return push_queued_message(req, request_time, end_time,
243                                    private_data, priv_len);
244 }
245
246 struct idle_event {
247         struct timed_event *te;
248         struct timeval interval;
249         char *name;
250         BOOL (*handler)(const struct timeval *now, void *private_data);
251         void *private_data;
252 };
253
254 static void idle_event_handler(struct event_context *ctx,
255                                struct timed_event *te,
256                                const struct timeval *now,
257                                void *private_data)
258 {
259         struct idle_event *event =
260                 talloc_get_type_abort(private_data, struct idle_event);
261
262         TALLOC_FREE(event->te);
263
264         if (!event->handler(now, event->private_data)) {
265                 /* Don't repeat, delete ourselves */
266                 TALLOC_FREE(event);
267                 return;
268         }
269
270         event->te = event_add_timed(ctx, event,
271                                     timeval_sum(now, &event->interval),
272                                     event->name,
273                                     idle_event_handler, event);
274
275         /* We can't do much but fail here. */
276         SMB_ASSERT(event->te != NULL);
277 }
278
279 struct idle_event *event_add_idle(struct event_context *event_ctx,
280                                   TALLOC_CTX *mem_ctx,
281                                   struct timeval interval,
282                                   const char *name,
283                                   BOOL (*handler)(const struct timeval *now,
284                                                   void *private_data),
285                                   void *private_data)
286 {
287         struct idle_event *result;
288         struct timeval now = timeval_current();
289
290         result = TALLOC_P(mem_ctx, struct idle_event);
291         if (result == NULL) {
292                 DEBUG(0, ("talloc failed\n"));
293                 return NULL;
294         }
295
296         result->interval = interval;
297         result->handler = handler;
298         result->private_data = private_data;
299
300         if (!(result->name = talloc_asprintf(result, "idle_evt(%s)", name))) {
301                 DEBUG(0, ("talloc failed\n"));
302                 TALLOC_FREE(result);
303                 return NULL;
304         }
305
306         result->te = event_add_timed(event_ctx, result,
307                                      timeval_sum(&now, &interval),
308                                      result->name,
309                                      idle_event_handler, result);
310         if (result->te == NULL) {
311                 DEBUG(0, ("event_add_timed failed\n"));
312                 TALLOC_FREE(result);
313                 return NULL;
314         }
315
316         return result;
317 }
318
319 /****************************************************************************
320  Do all async processing in here. This includes kernel oplock messages, change
321  notify events etc.
322 ****************************************************************************/
323
324 static void async_processing(fd_set *pfds)
325 {
326         DEBUG(10,("async_processing: Doing async processing.\n"));
327
328         process_aio_queue();
329
330         process_kernel_oplocks(smbd_messaging_context(), pfds);
331
332         /* Do the aio check again after receive_local_message as it does a
333            select and may have eaten our signal. */
334         /* Is this till true? -- vl */
335         process_aio_queue();
336
337         if (got_sig_term) {
338                 exit_server_cleanly("termination signal");
339         }
340
341         /* check for sighup processing */
342         if (reload_after_sighup) {
343                 change_to_root_user();
344                 DEBUG(1,("Reloading services after SIGHUP\n"));
345                 reload_services(False);
346                 reload_after_sighup = 0;
347         }
348 }
349
350 /****************************************************************************
351  Add a fd to the set we will be select(2)ing on.
352 ****************************************************************************/
353
354 static int select_on_fd(int fd, int maxfd, fd_set *fds)
355 {
356         if (fd != -1) {
357                 FD_SET(fd, fds);
358                 maxfd = MAX(maxfd, fd);
359         }
360
361         return maxfd;
362 }
363
364 /****************************************************************************
365   Do a select on an two fd's - with timeout. 
366
367   If a local udp message has been pushed onto the
368   queue (this can only happen during oplock break
369   processing) call async_processing()
370
371   If a pending smb message has been pushed onto the
372   queue (this can only happen during oplock break
373   processing) return this next.
374
375   If the first smbfd is ready then read an smb from it.
376   if the second (loopback UDP) fd is ready then read a message
377   from it and setup the buffer header to identify the length
378   and from address.
379   Returns False on timeout or error.
380   Else returns True.
381
382 The timeout is in milliseconds
383 ****************************************************************************/
384
385 static BOOL receive_message_or_smb(TALLOC_CTX *mem_ctx, char **buffer,
386                                    size_t *buffer_len, int timeout)
387 {
388         fd_set r_fds, w_fds;
389         int selrtn;
390         struct timeval to;
391         int maxfd = 0;
392         ssize_t len;
393
394         smb_read_error = 0;
395
396  again:
397
398         if (timeout >= 0) {
399                 to.tv_sec = timeout / 1000;
400                 to.tv_usec = (timeout % 1000) * 1000;
401         } else {
402                 to.tv_sec = SMBD_SELECT_TIMEOUT;
403                 to.tv_usec = 0;
404         }
405
406         /*
407          * Note that this call must be before processing any SMB
408          * messages as we need to synchronously process any messages
409          * we may have sent to ourselves from the previous SMB.
410          */
411         message_dispatch(smbd_messaging_context());
412
413         /*
414          * Check to see if we already have a message on the deferred open queue
415          * and it's time to schedule.
416          */
417         if(deferred_open_queue != NULL) {
418                 BOOL pop_message = False;
419                 struct pending_message_list *msg = deferred_open_queue;
420
421                 if (timeval_is_zero(&msg->end_time)) {
422                         pop_message = True;
423                 } else {
424                         struct timeval tv;
425                         SMB_BIG_INT tdif;
426
427                         GetTimeOfDay(&tv);
428                         tdif = usec_time_diff(&msg->end_time, &tv);
429                         if (tdif <= 0) {
430                                 /* Timed out. Schedule...*/
431                                 pop_message = True;
432                                 DEBUG(10,("receive_message_or_smb: queued message timed out.\n"));
433                         } else {
434                                 /* Make a more accurate select timeout. */
435                                 to.tv_sec = tdif / 1000000;
436                                 to.tv_usec = tdif % 1000000;
437                                 DEBUG(10,("receive_message_or_smb: select with timeout of [%u.%06u]\n",
438                                         (unsigned int)to.tv_sec, (unsigned int)to.tv_usec ));
439                         }
440                 }
441
442                 if (pop_message) {
443
444                         *buffer = (char *)talloc_memdup(mem_ctx, msg->buf.data,
445                                                         msg->buf.length);
446                         if (*buffer == NULL) {
447                                 DEBUG(0, ("talloc failed\n"));
448                                 smb_read_error = READ_ERROR;
449                                 return False;
450                         }
451                         *buffer_len = msg->buf.length;
452
453                         /* We leave this message on the queue so the open code can
454                            know this is a retry. */
455                         DEBUG(5,("receive_message_or_smb: returning deferred open smb message.\n"));
456                         return True;
457                 }
458         }
459
460         /*
461          * Setup the select fd sets.
462          */
463
464         FD_ZERO(&r_fds);
465         FD_ZERO(&w_fds);
466
467         /*
468          * Ensure we process oplock break messages by preference.
469          * We have to do this before the select, after the select
470          * and if the select returns EINTR. This is due to the fact
471          * that the selects called from async_processing can eat an EINTR
472          * caused by a signal (we can't take the break message there).
473          * This is hideously complex - *MUST* be simplified for 3.0 ! JRA.
474          */
475
476         if (oplock_message_waiting(&r_fds)) {
477                 DEBUG(10,("receive_message_or_smb: oplock_message is waiting.\n"));
478                 async_processing(&r_fds);
479                 /*
480                  * After async processing we must go and do the select again, as
481                  * the state of the flag in fds for the server file descriptor is
482                  * indeterminate - we may have done I/O on it in the oplock processing. JRA.
483                  */
484                 goto again;
485         }
486
487         /*
488          * Are there any timed events waiting ? If so, ensure we don't
489          * select for longer than it would take to wait for them.
490          */
491
492         {
493                 struct timeval now;
494                 GetTimeOfDay(&now);
495
496                 event_add_to_select_args(smbd_event_context(), &now,
497                                          &r_fds, &w_fds, &to, &maxfd);
498         }
499
500         if (timeval_is_zero(&to)) {
501                 /* Process a timed event now... */
502                 if (run_events(smbd_event_context(), 0, NULL, NULL)) {
503                         goto again;
504                 }
505         }
506         
507         {
508                 int sav;
509                 START_PROFILE(smbd_idle);
510
511                 maxfd = select_on_fd(smbd_server_fd(), maxfd, &r_fds);
512                 maxfd = select_on_fd(oplock_notify_fd(), maxfd, &r_fds);
513
514                 selrtn = sys_select(maxfd+1,&r_fds,&w_fds,NULL,&to);
515                 sav = errno;
516
517                 END_PROFILE(smbd_idle);
518                 errno = sav;
519         }
520
521         if (run_events(smbd_event_context(), selrtn, &r_fds, &w_fds)) {
522                 goto again;
523         }
524
525         /* if we get EINTR then maybe we have received an oplock
526            signal - treat this as select returning 1. This is ugly, but
527            is the best we can do until the oplock code knows more about
528            signals */
529         if (selrtn == -1 && errno == EINTR) {
530                 async_processing(&r_fds);
531                 /*
532                  * After async processing we must go and do the select again, as
533                  * the state of the flag in fds for the server file descriptor is
534                  * indeterminate - we may have done I/O on it in the oplock processing. JRA.
535                  */
536                 goto again;
537         }
538
539         /* Check if error */
540         if (selrtn == -1) {
541                 /* something is wrong. Maybe the socket is dead? */
542                 smb_read_error = READ_ERROR;
543                 return False;
544         } 
545     
546         /* Did we timeout ? */
547         if (selrtn == 0) {
548                 smb_read_error = READ_TIMEOUT;
549                 return False;
550         }
551
552         /*
553          * Ensure we process oplock break messages by preference.
554          * This is IMPORTANT ! Otherwise we can starve other processes
555          * sending us an oplock break message. JRA.
556          */
557
558         if (oplock_message_waiting(&r_fds)) {
559                 async_processing(&r_fds);
560                 /*
561                  * After async processing we must go and do the select again, as
562                  * the state of the flag in fds for the server file descriptor is
563                  * indeterminate - we may have done I/O on it in the oplock processing. JRA.
564                  */
565                 goto again;
566         }
567
568         len = receive_smb_talloc(mem_ctx, smbd_server_fd(), buffer, 0);
569
570         if (len == -1) {
571                 return False;
572         }
573
574         *buffer_len = (size_t)len;
575
576         return True;
577 }
578
579 /*
580  * Only allow 5 outstanding trans requests. We're allocating memory, so
581  * prevent a DoS.
582  */
583
584 NTSTATUS allow_new_trans(struct trans_state *list, int mid)
585 {
586         int count = 0;
587         for (; list != NULL; list = list->next) {
588
589                 if (list->mid == mid) {
590                         return NT_STATUS_INVALID_PARAMETER;
591                 }
592
593                 count += 1;
594         }
595         if (count > 5) {
596                 return NT_STATUS_INSUFFICIENT_RESOURCES;
597         }
598
599         return NT_STATUS_OK;
600 }
601
602 /****************************************************************************
603  We're terminating and have closed all our files/connections etc.
604  If there are any pending local messages we need to respond to them
605  before termination so that other smbds don't think we just died whilst
606  holding oplocks.
607 ****************************************************************************/
608
609 void respond_to_all_remaining_local_messages(void)
610 {
611         /*
612          * Assert we have no exclusive open oplocks.
613          */
614
615         if(get_number_of_exclusive_open_oplocks()) {
616                 DEBUG(0,("respond_to_all_remaining_local_messages: PANIC : we have %d exclusive oplocks.\n",
617                         get_number_of_exclusive_open_oplocks() ));
618                 return;
619         }
620
621         process_kernel_oplocks(smbd_messaging_context(), NULL);
622
623         return;
624 }
625
626
627 /*
628 These flags determine some of the permissions required to do an operation 
629
630 Note that I don't set NEED_WRITE on some write operations because they
631 are used by some brain-dead clients when printing, and I don't want to
632 force write permissions on print services.
633 */
634 #define AS_USER (1<<0)
635 #define NEED_WRITE (1<<1) /* Must be paired with AS_USER */
636 #define TIME_INIT (1<<2)
637 #define CAN_IPC (1<<3) /* Must be paired with AS_USER */
638 #define AS_GUEST (1<<5) /* Must *NOT* be paired with AS_USER */
639 #define DO_CHDIR (1<<6)
640
641 /* 
642    define a list of possible SMB messages and their corresponding
643    functions. Any message that has a NULL function is unimplemented -
644    please feel free to contribute implementations!
645 */
646 static const struct smb_message_struct {
647         const char *name;
648         void (*fn_new)(connection_struct *conn, struct smb_request *req);
649         int flags;
650 } smb_messages[256] = {
651
652 /* 0x00 */ { "SMBmkdir",reply_mkdir,AS_USER | NEED_WRITE},
653 /* 0x01 */ { "SMBrmdir",reply_rmdir,AS_USER | NEED_WRITE},
654 /* 0x02 */ { "SMBopen",reply_open,AS_USER },
655 /* 0x03 */ { "SMBcreate",reply_mknew,AS_USER},
656 /* 0x04 */ { "SMBclose",reply_close,AS_USER | CAN_IPC },
657 /* 0x05 */ { "SMBflush",reply_flush,AS_USER},
658 /* 0x06 */ { "SMBunlink",reply_unlink,AS_USER | NEED_WRITE },
659 /* 0x07 */ { "SMBmv",reply_mv,AS_USER | NEED_WRITE },
660 /* 0x08 */ { "SMBgetatr",reply_getatr,AS_USER},
661 /* 0x09 */ { "SMBsetatr",reply_setatr,AS_USER | NEED_WRITE},
662 /* 0x0a */ { "SMBread",reply_read,AS_USER},
663 /* 0x0b */ { "SMBwrite",reply_write,AS_USER | CAN_IPC },
664 /* 0x0c */ { "SMBlock",reply_lock,AS_USER},
665 /* 0x0d */ { "SMBunlock",reply_unlock,AS_USER},
666 /* 0x0e */ { "SMBctemp",reply_ctemp,AS_USER },
667 /* 0x0f */ { "SMBmknew",reply_mknew,AS_USER},
668 /* 0x10 */ { "SMBcheckpath",reply_checkpath,AS_USER},
669 /* 0x11 */ { "SMBexit",reply_exit,DO_CHDIR},
670 /* 0x12 */ { "SMBlseek",reply_lseek,AS_USER},
671 /* 0x13 */ { "SMBlockread",reply_lockread,AS_USER},
672 /* 0x14 */ { "SMBwriteunlock",reply_writeunlock,AS_USER},
673 /* 0x15 */ { NULL, NULL, 0 },
674 /* 0x16 */ { NULL, NULL, 0 },
675 /* 0x17 */ { NULL, NULL, 0 },
676 /* 0x18 */ { NULL, NULL, 0 },
677 /* 0x19 */ { NULL, NULL, 0 },
678 /* 0x1a */ { "SMBreadbraw",reply_readbraw,AS_USER},
679 /* 0x1b */ { "SMBreadBmpx",reply_readbmpx,AS_USER},
680 /* 0x1c */ { "SMBreadBs",reply_readbs,AS_USER },
681 /* 0x1d */ { "SMBwritebraw",reply_writebraw,AS_USER},
682 /* 0x1e */ { "SMBwriteBmpx",reply_writebmpx,AS_USER},
683 /* 0x1f */ { "SMBwriteBs",reply_writebs,AS_USER},
684 /* 0x20 */ { "SMBwritec", NULL,0},
685 /* 0x21 */ { NULL, NULL, 0 },
686 /* 0x22 */ { "SMBsetattrE",reply_setattrE,AS_USER | NEED_WRITE },
687 /* 0x23 */ { "SMBgetattrE",reply_getattrE,AS_USER },
688 /* 0x24 */ { "SMBlockingX",reply_lockingX,AS_USER },
689 /* 0x25 */ { "SMBtrans",reply_trans,AS_USER | CAN_IPC },
690 /* 0x26 */ { "SMBtranss",reply_transs,AS_USER | CAN_IPC},
691 /* 0x27 */ { "SMBioctl",reply_ioctl,0},
692 /* 0x28 */ { "SMBioctls", NULL,AS_USER},
693 /* 0x29 */ { "SMBcopy",reply_copy,AS_USER | NEED_WRITE },
694 /* 0x2a */ { "SMBmove", NULL,AS_USER | NEED_WRITE },
695 /* 0x2b */ { "SMBecho",reply_echo,0},
696 /* 0x2c */ { "SMBwriteclose",reply_writeclose,AS_USER},
697 /* 0x2d */ { "SMBopenX",reply_open_and_X,AS_USER | CAN_IPC },
698 /* 0x2e */ { "SMBreadX",reply_read_and_X,AS_USER | CAN_IPC },
699 /* 0x2f */ { "SMBwriteX",reply_write_and_X,AS_USER | CAN_IPC },
700 /* 0x30 */ { NULL, NULL, 0 },
701 /* 0x31 */ { NULL, NULL, 0 },
702 /* 0x32 */ { "SMBtrans2",reply_trans2, AS_USER | CAN_IPC },
703 /* 0x33 */ { "SMBtranss2",reply_transs2, AS_USER},
704 /* 0x34 */ { "SMBfindclose",reply_findclose,AS_USER},
705 /* 0x35 */ { "SMBfindnclose",reply_findnclose,AS_USER},
706 /* 0x36 */ { NULL, NULL, 0 },
707 /* 0x37 */ { NULL, NULL, 0 },
708 /* 0x38 */ { NULL, NULL, 0 },
709 /* 0x39 */ { NULL, NULL, 0 },
710 /* 0x3a */ { NULL, NULL, 0 },
711 /* 0x3b */ { NULL, NULL, 0 },
712 /* 0x3c */ { NULL, NULL, 0 },
713 /* 0x3d */ { NULL, NULL, 0 },
714 /* 0x3e */ { NULL, NULL, 0 },
715 /* 0x3f */ { NULL, NULL, 0 },
716 /* 0x40 */ { NULL, NULL, 0 },
717 /* 0x41 */ { NULL, NULL, 0 },
718 /* 0x42 */ { NULL, NULL, 0 },
719 /* 0x43 */ { NULL, NULL, 0 },
720 /* 0x44 */ { NULL, NULL, 0 },
721 /* 0x45 */ { NULL, NULL, 0 },
722 /* 0x46 */ { NULL, NULL, 0 },
723 /* 0x47 */ { NULL, NULL, 0 },
724 /* 0x48 */ { NULL, NULL, 0 },
725 /* 0x49 */ { NULL, NULL, 0 },
726 /* 0x4a */ { NULL, NULL, 0 },
727 /* 0x4b */ { NULL, NULL, 0 },
728 /* 0x4c */ { NULL, NULL, 0 },
729 /* 0x4d */ { NULL, NULL, 0 },
730 /* 0x4e */ { NULL, NULL, 0 },
731 /* 0x4f */ { NULL, NULL, 0 },
732 /* 0x50 */ { NULL, NULL, 0 },
733 /* 0x51 */ { NULL, NULL, 0 },
734 /* 0x52 */ { NULL, NULL, 0 },
735 /* 0x53 */ { NULL, NULL, 0 },
736 /* 0x54 */ { NULL, NULL, 0 },
737 /* 0x55 */ { NULL, NULL, 0 },
738 /* 0x56 */ { NULL, NULL, 0 },
739 /* 0x57 */ { NULL, NULL, 0 },
740 /* 0x58 */ { NULL, NULL, 0 },
741 /* 0x59 */ { NULL, NULL, 0 },
742 /* 0x5a */ { NULL, NULL, 0 },
743 /* 0x5b */ { NULL, NULL, 0 },
744 /* 0x5c */ { NULL, NULL, 0 },
745 /* 0x5d */ { NULL, NULL, 0 },
746 /* 0x5e */ { NULL, NULL, 0 },
747 /* 0x5f */ { NULL, NULL, 0 },
748 /* 0x60 */ { NULL, NULL, 0 },
749 /* 0x61 */ { NULL, NULL, 0 },
750 /* 0x62 */ { NULL, NULL, 0 },
751 /* 0x63 */ { NULL, NULL, 0 },
752 /* 0x64 */ { NULL, NULL, 0 },
753 /* 0x65 */ { NULL, NULL, 0 },
754 /* 0x66 */ { NULL, NULL, 0 },
755 /* 0x67 */ { NULL, NULL, 0 },
756 /* 0x68 */ { NULL, NULL, 0 },
757 /* 0x69 */ { NULL, NULL, 0 },
758 /* 0x6a */ { NULL, NULL, 0 },
759 /* 0x6b */ { NULL, NULL, 0 },
760 /* 0x6c */ { NULL, NULL, 0 },
761 /* 0x6d */ { NULL, NULL, 0 },
762 /* 0x6e */ { NULL, NULL, 0 },
763 /* 0x6f */ { NULL, NULL, 0 },
764 /* 0x70 */ { "SMBtcon",reply_tcon,0},
765 /* 0x71 */ { "SMBtdis",reply_tdis,DO_CHDIR},
766 /* 0x72 */ { "SMBnegprot",reply_negprot,0},
767 /* 0x73 */ { "SMBsesssetupX",reply_sesssetup_and_X,0},
768 /* 0x74 */ { "SMBulogoffX",reply_ulogoffX, 0}, /* ulogoff doesn't give a valid TID */
769 /* 0x75 */ { "SMBtconX",reply_tcon_and_X,0},
770 /* 0x76 */ { NULL, NULL, 0 },
771 /* 0x77 */ { NULL, NULL, 0 },
772 /* 0x78 */ { NULL, NULL, 0 },
773 /* 0x79 */ { NULL, NULL, 0 },
774 /* 0x7a */ { NULL, NULL, 0 },
775 /* 0x7b */ { NULL, NULL, 0 },
776 /* 0x7c */ { NULL, NULL, 0 },
777 /* 0x7d */ { NULL, NULL, 0 },
778 /* 0x7e */ { NULL, NULL, 0 },
779 /* 0x7f */ { NULL, NULL, 0 },
780 /* 0x80 */ { "SMBdskattr",reply_dskattr,AS_USER},
781 /* 0x81 */ { "SMBsearch",reply_search,AS_USER},
782 /* 0x82 */ { "SMBffirst",reply_search,AS_USER},
783 /* 0x83 */ { "SMBfunique",reply_search,AS_USER},
784 /* 0x84 */ { "SMBfclose",reply_fclose,AS_USER},
785 /* 0x85 */ { NULL, NULL, 0 },
786 /* 0x86 */ { NULL, NULL, 0 },
787 /* 0x87 */ { NULL, NULL, 0 },
788 /* 0x88 */ { NULL, NULL, 0 },
789 /* 0x89 */ { NULL, NULL, 0 },
790 /* 0x8a */ { NULL, NULL, 0 },
791 /* 0x8b */ { NULL, NULL, 0 },
792 /* 0x8c */ { NULL, NULL, 0 },
793 /* 0x8d */ { NULL, NULL, 0 },
794 /* 0x8e */ { NULL, NULL, 0 },
795 /* 0x8f */ { NULL, NULL, 0 },
796 /* 0x90 */ { NULL, NULL, 0 },
797 /* 0x91 */ { NULL, NULL, 0 },
798 /* 0x92 */ { NULL, NULL, 0 },
799 /* 0x93 */ { NULL, NULL, 0 },
800 /* 0x94 */ { NULL, NULL, 0 },
801 /* 0x95 */ { NULL, NULL, 0 },
802 /* 0x96 */ { NULL, NULL, 0 },
803 /* 0x97 */ { NULL, NULL, 0 },
804 /* 0x98 */ { NULL, NULL, 0 },
805 /* 0x99 */ { NULL, NULL, 0 },
806 /* 0x9a */ { NULL, NULL, 0 },
807 /* 0x9b */ { NULL, NULL, 0 },
808 /* 0x9c */ { NULL, NULL, 0 },
809 /* 0x9d */ { NULL, NULL, 0 },
810 /* 0x9e */ { NULL, NULL, 0 },
811 /* 0x9f */ { NULL, NULL, 0 },
812 /* 0xa0 */ { "SMBnttrans",reply_nttrans, AS_USER | CAN_IPC },
813 /* 0xa1 */ { "SMBnttranss",reply_nttranss, AS_USER | CAN_IPC },
814 /* 0xa2 */ { "SMBntcreateX",reply_ntcreate_and_X, AS_USER | CAN_IPC },
815 /* 0xa3 */ { NULL, NULL, 0 },
816 /* 0xa4 */ { "SMBntcancel",reply_ntcancel, 0 },
817 /* 0xa5 */ { "SMBntrename",reply_ntrename, AS_USER | NEED_WRITE },
818 /* 0xa6 */ { NULL, NULL, 0 },
819 /* 0xa7 */ { NULL, NULL, 0 },
820 /* 0xa8 */ { NULL, NULL, 0 },
821 /* 0xa9 */ { NULL, NULL, 0 },
822 /* 0xaa */ { NULL, NULL, 0 },
823 /* 0xab */ { NULL, NULL, 0 },
824 /* 0xac */ { NULL, NULL, 0 },
825 /* 0xad */ { NULL, NULL, 0 },
826 /* 0xae */ { NULL, NULL, 0 },
827 /* 0xaf */ { NULL, NULL, 0 },
828 /* 0xb0 */ { NULL, NULL, 0 },
829 /* 0xb1 */ { NULL, NULL, 0 },
830 /* 0xb2 */ { NULL, NULL, 0 },
831 /* 0xb3 */ { NULL, NULL, 0 },
832 /* 0xb4 */ { NULL, NULL, 0 },
833 /* 0xb5 */ { NULL, NULL, 0 },
834 /* 0xb6 */ { NULL, NULL, 0 },
835 /* 0xb7 */ { NULL, NULL, 0 },
836 /* 0xb8 */ { NULL, NULL, 0 },
837 /* 0xb9 */ { NULL, NULL, 0 },
838 /* 0xba */ { NULL, NULL, 0 },
839 /* 0xbb */ { NULL, NULL, 0 },
840 /* 0xbc */ { NULL, NULL, 0 },
841 /* 0xbd */ { NULL, NULL, 0 },
842 /* 0xbe */ { NULL, NULL, 0 },
843 /* 0xbf */ { NULL, NULL, 0 },
844 /* 0xc0 */ { "SMBsplopen",reply_printopen,AS_USER},
845 /* 0xc1 */ { "SMBsplwr",reply_printwrite,AS_USER},
846 /* 0xc2 */ { "SMBsplclose",reply_printclose,AS_USER},
847 /* 0xc3 */ { "SMBsplretq",reply_printqueue,AS_USER},
848 /* 0xc4 */ { NULL, NULL, 0 },
849 /* 0xc5 */ { NULL, NULL, 0 },
850 /* 0xc6 */ { NULL, NULL, 0 },
851 /* 0xc7 */ { NULL, NULL, 0 },
852 /* 0xc8 */ { NULL, NULL, 0 },
853 /* 0xc9 */ { NULL, NULL, 0 },
854 /* 0xca */ { NULL, NULL, 0 },
855 /* 0xcb */ { NULL, NULL, 0 },
856 /* 0xcc */ { NULL, NULL, 0 },
857 /* 0xcd */ { NULL, NULL, 0 },
858 /* 0xce */ { NULL, NULL, 0 },
859 /* 0xcf */ { NULL, NULL, 0 },
860 /* 0xd0 */ { "SMBsends",reply_sends,AS_GUEST},
861 /* 0xd1 */ { "SMBsendb", NULL,AS_GUEST},
862 /* 0xd2 */ { "SMBfwdname", NULL,AS_GUEST},
863 /* 0xd3 */ { "SMBcancelf", NULL,AS_GUEST},
864 /* 0xd4 */ { "SMBgetmac", NULL,AS_GUEST},
865 /* 0xd5 */ { "SMBsendstrt",reply_sendstrt,AS_GUEST},
866 /* 0xd6 */ { "SMBsendend",reply_sendend,AS_GUEST},
867 /* 0xd7 */ { "SMBsendtxt",reply_sendtxt,AS_GUEST},
868 /* 0xd8 */ { NULL, NULL, 0 },
869 /* 0xd9 */ { NULL, NULL, 0 },
870 /* 0xda */ { NULL, NULL, 0 },
871 /* 0xdb */ { NULL, NULL, 0 },
872 /* 0xdc */ { NULL, NULL, 0 },
873 /* 0xdd */ { NULL, NULL, 0 },
874 /* 0xde */ { NULL, NULL, 0 },
875 /* 0xdf */ { NULL, NULL, 0 },
876 /* 0xe0 */ { NULL, NULL, 0 },
877 /* 0xe1 */ { NULL, NULL, 0 },
878 /* 0xe2 */ { NULL, NULL, 0 },
879 /* 0xe3 */ { NULL, NULL, 0 },
880 /* 0xe4 */ { NULL, NULL, 0 },
881 /* 0xe5 */ { NULL, NULL, 0 },
882 /* 0xe6 */ { NULL, NULL, 0 },
883 /* 0xe7 */ { NULL, NULL, 0 },
884 /* 0xe8 */ { NULL, NULL, 0 },
885 /* 0xe9 */ { NULL, NULL, 0 },
886 /* 0xea */ { NULL, NULL, 0 },
887 /* 0xeb */ { NULL, NULL, 0 },
888 /* 0xec */ { NULL, NULL, 0 },
889 /* 0xed */ { NULL, NULL, 0 },
890 /* 0xee */ { NULL, NULL, 0 },
891 /* 0xef */ { NULL, NULL, 0 },
892 /* 0xf0 */ { NULL, NULL, 0 },
893 /* 0xf1 */ { NULL, NULL, 0 },
894 /* 0xf2 */ { NULL, NULL, 0 },
895 /* 0xf3 */ { NULL, NULL, 0 },
896 /* 0xf4 */ { NULL, NULL, 0 },
897 /* 0xf5 */ { NULL, NULL, 0 },
898 /* 0xf6 */ { NULL, NULL, 0 },
899 /* 0xf7 */ { NULL, NULL, 0 },
900 /* 0xf8 */ { NULL, NULL, 0 },
901 /* 0xf9 */ { NULL, NULL, 0 },
902 /* 0xfa */ { NULL, NULL, 0 },
903 /* 0xfb */ { NULL, NULL, 0 },
904 /* 0xfc */ { NULL, NULL, 0 },
905 /* 0xfd */ { NULL, NULL, 0 },
906 /* 0xfe */ { NULL, NULL, 0 },
907 /* 0xff */ { NULL, NULL, 0 }
908
909 };
910
911 /*******************************************************************
912  allocate and initialize a reply packet
913 ********************************************************************/
914
915 void reply_outbuf(struct smb_request *req, uint8 num_words, uint32 num_bytes)
916 {
917         /*
918          * Protect against integer wrap
919          */
920         if ((num_bytes > 0xffffff)
921             || ((num_bytes + smb_size + num_words*2) > 0xffffff)) {
922                 char *msg;
923                 asprintf(&msg, "num_bytes too large: %u",
924                          (unsigned)num_bytes);
925                 smb_panic(msg);
926         }
927
928         if (!(req->outbuf = TALLOC_ARRAY(
929                       req, uint8,
930                       smb_size + num_words*2 + num_bytes))) {
931                 smb_panic("could not allocate output buffer\n");
932         }
933
934         construct_reply_common((char *)req->inbuf, (char *)req->outbuf);
935         set_message((char *)req->inbuf, (char *)req->outbuf,
936                     num_words, num_bytes, False);
937         /*
938          * Zero out the word area, the caller has to take care of the bcc area
939          * himself
940          */
941         if (num_words != 0) {
942                 memset(req->outbuf + smb_vwv0, 0, num_words*2);
943         }
944
945         return;
946 }
947
948
949 /*******************************************************************
950  Dump a packet to a file.
951 ********************************************************************/
952
953 static void smb_dump(const char *name, int type, const char *data, ssize_t len)
954 {
955         int fd, i;
956         pstring fname;
957         if (DEBUGLEVEL < 50) return;
958
959         if (len < 4) len = smb_len(data)+4;
960         for (i=1;i<100;i++) {
961                 slprintf(fname,sizeof(fname)-1, "/tmp/%s.%d.%s", name, i,
962                                 type ? "req" : "resp");
963                 fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
964                 if (fd != -1 || errno != EEXIST) break;
965         }
966         if (fd != -1) {
967                 ssize_t ret = write(fd, data, len);
968                 if (ret != len)
969                         DEBUG(0,("smb_dump: problem: write returned %d\n", (int)ret ));
970                 close(fd);
971                 DEBUG(0,("created %s len %lu\n", fname, (unsigned long)len));
972         }
973 }
974
975 /****************************************************************************
976  Prepare everything for calling the actual request function, and potentially
977  call the request function via the "new" interface.
978
979  Return False if the "legacy" function needs to be called, everything is
980  prepared.
981
982  Return True if we're done.
983
984  I know this API sucks, but it is the one with the least code change I could
985  find.
986 ****************************************************************************/
987
988 static void switch_message(uint8 type, struct smb_request *req, int size)
989 {
990         int flags;
991         uint16 session_tag;
992         connection_struct *conn;
993
994         static uint16 last_session_tag = UID_FIELD_INVALID;
995
996         errno = 0;
997
998         last_message = type;
999
1000         /* Make sure this is an SMB packet. smb_size contains NetBIOS header
1001          * so subtract 4 from it. */
1002         if ((strncmp(smb_base(req->inbuf),"\377SMB",4) != 0)
1003             || (size < (smb_size - 4))) {
1004                 DEBUG(2,("Non-SMB packet of length %d. Terminating server\n",
1005                          smb_len(req->inbuf)));
1006                 exit_server_cleanly("Non-SMB packet");
1007         }
1008
1009         if (smb_messages[type].fn_new == NULL) {
1010                 DEBUG(0,("Unknown message type %d!\n",type));
1011                 smb_dump("Unknown", 1, (char *)req->inbuf, size);
1012                 reply_unknown_new(req, type);
1013                 return;
1014         }
1015
1016         flags = smb_messages[type].flags;
1017
1018         /* In share mode security we must ignore the vuid. */
1019         session_tag = (lp_security() == SEC_SHARE)
1020                 ? UID_FIELD_INVALID : req->vuid;
1021         conn = conn_find(req->tid);
1022
1023         DEBUG(3,("switch message %s (pid %d) conn 0x%lx\n", smb_fn_name(type),
1024                  (int)sys_getpid(), (unsigned long)conn));
1025
1026         smb_dump(smb_fn_name(type), 1, (char *)req->inbuf, size);
1027
1028         /* Ensure this value is replaced in the incoming packet. */
1029         SSVAL(req->inbuf,smb_uid,session_tag);
1030
1031         /*
1032          * Ensure the correct username is in current_user_info.  This is a
1033          * really ugly bugfix for problems with multiple session_setup_and_X's
1034          * being done and allowing %U and %G substitutions to work correctly.
1035          * There is a reason this code is done here, don't move it unless you
1036          * know what you're doing... :-).
1037          * JRA.
1038          */
1039
1040         if (session_tag != last_session_tag) {
1041                 user_struct *vuser = NULL;
1042
1043                 last_session_tag = session_tag;
1044                 if(session_tag != UID_FIELD_INVALID) {
1045                         vuser = get_valid_user_struct(session_tag);
1046                         if (vuser) {
1047                                 set_current_user_info(&vuser->user);
1048                         }
1049                 }
1050         }
1051
1052         /* Does this call need to be run as the connected user? */
1053         if (flags & AS_USER) {
1054
1055                 /* Does this call need a valid tree connection? */
1056                 if (!conn) {
1057                         /*
1058                          * Amazingly, the error code depends on the command
1059                          * (from Samba4).
1060                          */
1061                         if (type == SMBntcreateX) {
1062                                 reply_nterror(req, NT_STATUS_INVALID_HANDLE);
1063                         } else {
1064                                 reply_doserror(req, ERRSRV, ERRinvnid);
1065                         }
1066                         return;
1067                 }
1068
1069                 if (!change_to_user(conn,session_tag)) {
1070                         reply_nterror(req, NT_STATUS_DOS(ERRSRV, ERRbaduid));
1071                         return;
1072                 }
1073
1074                 /* All NEED_WRITE and CAN_IPC flags must also have AS_USER. */
1075
1076                 /* Does it need write permission? */
1077                 if ((flags & NEED_WRITE) && !CAN_WRITE(conn)) {
1078                         reply_nterror(req, NT_STATUS_MEDIA_WRITE_PROTECTED);
1079                         return;
1080                 }
1081
1082                 /* IPC services are limited */
1083                 if (IS_IPC(conn) && !(flags & CAN_IPC)) {
1084                         reply_doserror(req, ERRSRV,ERRaccess);
1085                         return;
1086                 }
1087         } else {
1088                 /* This call needs to be run as root */
1089                 change_to_root_user();
1090         }
1091
1092         /* load service specific parameters */
1093         if (conn) {
1094                 if (!set_current_service(conn,SVAL(req->inbuf,smb_flg),
1095                                          (flags & (AS_USER|DO_CHDIR)
1096                                           ?True:False))) {
1097                         reply_doserror(req, ERRSRV, ERRaccess);
1098                         return;
1099                 }
1100                 conn->num_smb_operations++;
1101         }
1102
1103         /* does this protocol need to be run as guest? */
1104         if ((flags & AS_GUEST)
1105             && (!change_to_guest() ||
1106                 !check_access(smbd_server_fd(), lp_hostsallow(-1),
1107                               lp_hostsdeny(-1)))) {
1108                 reply_doserror(req, ERRSRV, ERRaccess);
1109                 return;
1110         }
1111
1112         smb_messages[type].fn_new(conn, req);
1113 }
1114
1115 /****************************************************************************
1116  Construct a reply to the incoming packet.
1117 ****************************************************************************/
1118
1119 static void construct_reply(char *inbuf, int size)
1120 {
1121         uint8 type = CVAL(inbuf,smb_com);
1122         struct smb_request *req;
1123
1124         chain_size = 0;
1125         file_chain_reset();
1126         reset_chain_p();
1127
1128         if (!(req = talloc(talloc_tos(), struct smb_request))) {
1129                 smb_panic("could not allocate smb_request");
1130         }
1131         init_smb_request(req, (uint8 *)inbuf);
1132
1133         switch_message(type, req, size);
1134
1135         if (req->outbuf == NULL) {
1136                 return;
1137         }
1138
1139         if (CVAL(req->outbuf,0) == 0) {
1140                 show_msg((char *)req->outbuf);
1141         }
1142
1143         if (!send_smb(smbd_server_fd(), (char *)req->outbuf)) {
1144                 exit_server_cleanly("construct_reply: send_smb failed.");
1145         }
1146
1147         TALLOC_FREE(req);
1148
1149         return;
1150 }
1151
1152 /****************************************************************************
1153  Process an smb from the client
1154 ****************************************************************************/
1155
1156 static void process_smb(char *inbuf, size_t nread)
1157 {
1158         static int trans_num;
1159         int msg_type = CVAL(inbuf,0);
1160
1161         DO_PROFILE_INC(smb_count);
1162
1163         if (trans_num == 0) {
1164                 /* on the first packet, check the global hosts allow/ hosts
1165                 deny parameters before doing any parsing of the packet
1166                 passed to us by the client.  This prevents attacks on our
1167                 parsing code from hosts not in the hosts allow list */
1168                 if (!check_access(smbd_server_fd(), lp_hostsallow(-1),
1169                                   lp_hostsdeny(-1))) {
1170                         /* send a negative session response "not listening on calling name" */
1171                         static unsigned char buf[5] = {0x83, 0, 0, 1, 0x81};
1172                         DEBUG( 1, ( "Connection denied from %s\n", client_addr() ) );
1173                         (void)send_smb(smbd_server_fd(),(char *)buf);
1174                         exit_server_cleanly("connection denied");
1175                 }
1176         }
1177
1178         DEBUG( 6, ( "got message type 0x%x of len 0x%x\n", msg_type,
1179                     smb_len(inbuf) ) );
1180         DEBUG( 3, ( "Transaction %d of length %d\n", trans_num, (int)nread ) );
1181
1182         if (msg_type != 0) {
1183                 /*
1184                  * NetBIOS session request, keepalive, etc.
1185                  */
1186                 reply_special(inbuf);
1187                 return;
1188         }
1189
1190         show_msg(inbuf);
1191
1192         construct_reply(inbuf,nread);
1193       
1194         trans_num++;
1195 }
1196
1197 /****************************************************************************
1198  Return a string containing the function name of a SMB command.
1199 ****************************************************************************/
1200
1201 const char *smb_fn_name(int type)
1202 {
1203         const char *unknown_name = "SMBunknown";
1204
1205         if (smb_messages[type].name == NULL)
1206                 return(unknown_name);
1207
1208         return(smb_messages[type].name);
1209 }
1210
1211 /****************************************************************************
1212  Helper functions for contruct_reply.
1213 ****************************************************************************/
1214
1215 static uint32 common_flags2 = FLAGS2_LONG_PATH_COMPONENTS|FLAGS2_32_BIT_ERROR_CODES;
1216
1217 void add_to_common_flags2(uint32 v)
1218 {
1219         common_flags2 |= v;
1220 }
1221
1222 void remove_from_common_flags2(uint32 v)
1223 {
1224         common_flags2 &= ~v;
1225 }
1226
1227 void construct_reply_common(const char *inbuf, char *outbuf)
1228 {
1229         set_message(inbuf,outbuf,0,0,False);
1230
1231         SCVAL(outbuf,smb_com,CVAL(inbuf,smb_com));
1232         SIVAL(outbuf,smb_rcls,0);
1233         SCVAL(outbuf,smb_flg, FLAG_REPLY | (CVAL(inbuf,smb_flg) & FLAG_CASELESS_PATHNAMES)); 
1234         SSVAL(outbuf,smb_flg2,
1235                 (SVAL(inbuf,smb_flg2) & FLAGS2_UNICODE_STRINGS) |
1236                 common_flags2);
1237         memset(outbuf+smb_pidhigh,'\0',(smb_tid-smb_pidhigh));
1238
1239         SSVAL(outbuf,smb_tid,SVAL(inbuf,smb_tid));
1240         SSVAL(outbuf,smb_pid,SVAL(inbuf,smb_pid));
1241         SSVAL(outbuf,smb_uid,SVAL(inbuf,smb_uid));
1242         SSVAL(outbuf,smb_mid,SVAL(inbuf,smb_mid));
1243 }
1244
1245 /****************************************************************************
1246  Construct a chained reply and add it to the already made reply
1247 ****************************************************************************/
1248
1249 void chain_reply(struct smb_request *req)
1250 {
1251         static char *orig_inbuf;
1252
1253         /*
1254          * Dirty little const_discard: We mess with req->inbuf, which is
1255          * declared as const. If maybe at some point this routine gets
1256          * rewritten, this const_discard could go away.
1257          */
1258         char *inbuf = CONST_DISCARD(char *, req->inbuf);
1259         int size = smb_len(req->inbuf)+4;
1260
1261         int smb_com1, smb_com2 = CVAL(inbuf,smb_vwv0);
1262         unsigned smb_off2 = SVAL(inbuf,smb_vwv1);
1263         char *inbuf2;
1264         int outsize2;
1265         int new_size;
1266         char inbuf_saved[smb_wct];
1267         char *outbuf = (char *)req->outbuf;
1268         size_t outsize = smb_len(outbuf) + 4;
1269         size_t outsize_padded;
1270         size_t ofs, to_move;
1271
1272         struct smb_request *req2;
1273         size_t caller_outputlen;
1274         char *caller_output;
1275
1276         /* Maybe its not chained, or it's an error packet. */
1277         if (smb_com2 == 0xFF || SVAL(outbuf,smb_rcls) != 0) {
1278                 SCVAL(outbuf,smb_vwv0,0xFF);
1279                 return;
1280         }
1281
1282         if (chain_size == 0) {
1283                 /* this is the first part of the chain */
1284                 orig_inbuf = inbuf;
1285         }
1286
1287         /*
1288          * We need to save the output the caller added to the chain so that we
1289          * can splice it into the final output buffer later.
1290          */
1291
1292         caller_outputlen = outsize - smb_wct;
1293
1294         caller_output = (char *)memdup(outbuf + smb_wct, caller_outputlen);
1295
1296         if (caller_output == NULL) {
1297                 /* TODO: NT_STATUS_NO_MEMORY */
1298                 smb_panic("could not dup outbuf");
1299         }
1300
1301         /*
1302          * The original Win95 redirector dies on a reply to
1303          * a lockingX and read chain unless the chain reply is
1304          * 4 byte aligned. JRA.
1305          */
1306
1307         outsize_padded = (outsize + 3) & ~3;
1308
1309         /*
1310          * remember how much the caller added to the chain, only counting
1311          * stuff after the parameter words
1312          */
1313         chain_size += outsize_padded - smb_wct;
1314
1315         /*
1316          * work out pointers into the original packets. The
1317          * headers on these need to be filled in
1318          */
1319         inbuf2 = orig_inbuf + smb_off2 + 4 - smb_wct;
1320
1321         /* remember the original command type */
1322         smb_com1 = CVAL(orig_inbuf,smb_com);
1323
1324         /* save the data which will be overwritten by the new headers */
1325         memcpy(inbuf_saved,inbuf2,smb_wct);
1326
1327         /* give the new packet the same header as the last part of the SMB */
1328         memmove(inbuf2,inbuf,smb_wct);
1329
1330         /* create the in buffer */
1331         SCVAL(inbuf2,smb_com,smb_com2);
1332
1333         /* work out the new size for the in buffer. */
1334         new_size = size - (inbuf2 - inbuf);
1335         if (new_size < 0) {
1336                 DEBUG(0,("chain_reply: chain packet size incorrect "
1337                          "(orig size = %d, offset = %d)\n",
1338                          size, (int)(inbuf2 - inbuf) ));
1339                 exit_server_cleanly("Bad chained packet");
1340                 return;
1341         }
1342
1343         /* And set it in the header. */
1344         smb_setlen(inbuf, inbuf2, new_size - 4);
1345
1346         DEBUG(3,("Chained message\n"));
1347         show_msg(inbuf2);
1348
1349         if (!(req2 = talloc(talloc_tos(), struct smb_request))) {
1350                 smb_panic("could not allocate smb_request");
1351         }
1352         init_smb_request(req2, (uint8 *)inbuf2);
1353
1354         /* process the request */
1355         switch_message(smb_com2, req2, new_size);
1356
1357         /*
1358          * We don't accept deferred operations in chained requests.
1359          */
1360         SMB_ASSERT(req2->outbuf != NULL);
1361         outsize2 = smb_len(req2->outbuf)+4;
1362
1363         /*
1364          * Move away the new command output so that caller_output fits in,
1365          * copy in the caller_output saved above.
1366          */
1367
1368         SMB_ASSERT(outsize_padded >= smb_wct);
1369
1370         /*
1371          * "ofs" is the space we need for caller_output. Equal to
1372          * caller_outputlen plus the padding.
1373          */
1374
1375         ofs = outsize_padded - smb_wct;
1376
1377         /*
1378          * "to_move" is the amount of bytes the secondary routine gave us
1379          */
1380
1381         to_move = outsize2 - smb_wct;
1382
1383         if (to_move + ofs + smb_wct + chain_size > max_send) {
1384                 smb_panic("replies too large -- would have to cut");
1385         }
1386
1387         /*
1388          * In the "new" API "outbuf" is allocated via reply_outbuf, just for
1389          * the first request in the chain. So we have to re-allocate it. In
1390          * the "old" API the only outbuf ever used is the global OutBuffer
1391          * which is always large enough.
1392          */
1393
1394         outbuf = TALLOC_REALLOC_ARRAY(NULL, outbuf, char,
1395                                       to_move + ofs + smb_wct);
1396         if (outbuf == NULL) {
1397                 smb_panic("could not realloc outbuf");
1398         }
1399
1400         req->outbuf = (uint8 *)outbuf;
1401
1402         memmove(outbuf + smb_wct + ofs, req2->outbuf + smb_wct, to_move);
1403         memcpy(outbuf + smb_wct, caller_output, caller_outputlen);
1404
1405         /*
1406          * copy the new reply header over the old one but preserve the smb_com
1407          * field
1408          */
1409         memmove(outbuf, req2->outbuf, smb_wct);
1410         SCVAL(outbuf, smb_com, smb_com1);
1411
1412         /*
1413          * We've just copied in the whole "wct" area from the secondary
1414          * function. Fix up the chaining: com2 and the offset need to be
1415          * readjusted.
1416          */
1417
1418         SCVAL(outbuf, smb_vwv0, smb_com2);
1419         SSVAL(outbuf, smb_vwv1, chain_size + smb_wct - 4);
1420
1421         if (outsize_padded > outsize) {
1422
1423                 /*
1424                  * Due to padding we have some uninitialized bytes after the
1425                  * caller's output
1426                  */
1427
1428                 memset(outbuf + outsize, 0, outsize_padded - outsize);
1429         }
1430
1431         smb_setlen(NULL, outbuf, outsize2 + chain_size - 4);
1432
1433         /*
1434          * restore the saved data, being careful not to overwrite any data
1435          * from the reply header
1436          */
1437         memcpy(inbuf2,inbuf_saved,smb_wct);
1438
1439         SAFE_FREE(caller_output);
1440         TALLOC_FREE(req2);
1441
1442         return;
1443 }
1444
1445 /****************************************************************************
1446  Setup the needed select timeout in milliseconds.
1447 ****************************************************************************/
1448
1449 static int setup_select_timeout(void)
1450 {
1451         int select_timeout;
1452
1453         select_timeout = SMBD_SELECT_TIMEOUT*1000;
1454
1455         if (print_notify_messages_pending()) {
1456                 select_timeout = MIN(select_timeout, 1000);
1457         }
1458
1459         return select_timeout;
1460 }
1461
1462 /****************************************************************************
1463  Check if services need reloading.
1464 ****************************************************************************/
1465
1466 void check_reload(time_t t)
1467 {
1468         static pid_t mypid = 0;
1469         static time_t last_smb_conf_reload_time = 0;
1470         static time_t last_printer_reload_time = 0;
1471         time_t printcap_cache_time = (time_t)lp_printcap_cache_time();
1472
1473         if(last_smb_conf_reload_time == 0) {
1474                 last_smb_conf_reload_time = t;
1475                 /* Our printing subsystem might not be ready at smbd start up.
1476                    Then no printer is available till the first printers check
1477                    is performed.  A lower initial interval circumvents this. */
1478                 if ( printcap_cache_time > 60 )
1479                         last_printer_reload_time = t - printcap_cache_time + 60;
1480                 else
1481                         last_printer_reload_time = t;
1482         }
1483
1484         if (mypid != getpid()) { /* First time or fork happened meanwhile */
1485                 /* randomize over 60 second the printcap reload to avoid all
1486                  * process hitting cupsd at the same time */
1487                 int time_range = 60;
1488
1489                 last_printer_reload_time += random() % time_range;
1490                 mypid = getpid();
1491         }
1492
1493         if (reload_after_sighup || (t >= last_smb_conf_reload_time+SMBD_RELOAD_CHECK)) {
1494                 reload_services(True);
1495                 reload_after_sighup = False;
1496                 last_smb_conf_reload_time = t;
1497         }
1498
1499         /* 'printcap cache time = 0' disable the feature */
1500         
1501         if ( printcap_cache_time != 0 )
1502         { 
1503                 /* see if it's time to reload or if the clock has been set back */
1504                 
1505                 if ( (t >= last_printer_reload_time+printcap_cache_time) 
1506                         || (t-last_printer_reload_time  < 0) ) 
1507                 {
1508                         DEBUG( 3,( "Printcap cache time expired.\n"));
1509                         reload_printers();
1510                         last_printer_reload_time = t;
1511                 }
1512         }
1513 }
1514
1515 /****************************************************************************
1516  Process any timeout housekeeping. Return False if the caller should exit.
1517 ****************************************************************************/
1518
1519 static BOOL timeout_processing(int *select_timeout,
1520                                time_t *last_timeout_processing_time)
1521 {
1522         time_t t;
1523
1524         if (smb_read_error == READ_EOF) {
1525                 DEBUG(3,("timeout_processing: End of file from client (client has disconnected).\n"));
1526                 return False;
1527         }
1528
1529         if (smb_read_error == READ_ERROR) {
1530                 DEBUG(3,("timeout_processing: receive_smb error (%s) Exiting\n",
1531                         strerror(errno)));
1532                 return False;
1533         }
1534
1535         if (smb_read_error == READ_BAD_SIG) {
1536                 DEBUG(3,("timeout_processing: receive_smb error bad smb signature. Exiting\n"));
1537                 return False;
1538         }
1539
1540         *last_timeout_processing_time = t = time(NULL);
1541
1542         /* become root again if waiting */
1543         change_to_root_user();
1544
1545         /* check if we need to reload services */
1546         check_reload(t);
1547
1548         if(global_machine_password_needs_changing && 
1549                         /* for ADS we need to do a regular ADS password change, not a domain
1550                                         password change */
1551                         lp_security() == SEC_DOMAIN) {
1552
1553                 unsigned char trust_passwd_hash[16];
1554                 time_t lct;
1555
1556                 /*
1557                  * We're in domain level security, and the code that
1558                  * read the machine password flagged that the machine
1559                  * password needs changing.
1560                  */
1561
1562                 /*
1563                  * First, open the machine password file with an exclusive lock.
1564                  */
1565
1566                 if (secrets_lock_trust_account_password(lp_workgroup(), True) == False) {
1567                         DEBUG(0,("process: unable to lock the machine account password for \
1568 machine %s in domain %s.\n", global_myname(), lp_workgroup() ));
1569                         return True;
1570                 }
1571
1572                 if(!secrets_fetch_trust_account_password(lp_workgroup(), trust_passwd_hash, &lct, NULL)) {
1573                         DEBUG(0,("process: unable to read the machine account password for \
1574 machine %s in domain %s.\n", global_myname(), lp_workgroup()));
1575                         secrets_lock_trust_account_password(lp_workgroup(), False);
1576                         return True;
1577                 }
1578
1579                 /*
1580                  * Make sure someone else hasn't already done this.
1581                  */
1582
1583                 if(t < lct + lp_machine_password_timeout()) {
1584                         global_machine_password_needs_changing = False;
1585                         secrets_lock_trust_account_password(lp_workgroup(), False);
1586                         return True;
1587                 }
1588
1589                 /* always just contact the PDC here */
1590     
1591                 change_trust_account_password( lp_workgroup(), NULL);
1592                 global_machine_password_needs_changing = False;
1593                 secrets_lock_trust_account_password(lp_workgroup(), False);
1594         }
1595
1596         /* update printer queue caches if necessary */
1597   
1598         update_monitored_printq_cache();
1599   
1600         /*
1601          * Now we are root, check if the log files need pruning.
1602          * Force a log file check.
1603          */
1604         force_check_log_size();
1605         check_log_size();
1606
1607         /* Send any queued printer notify message to interested smbd's. */
1608
1609         print_notify_send_messages(smbd_messaging_context(), 0);
1610
1611         /*
1612          * Modify the select timeout depending upon
1613          * what we have remaining in our queues.
1614          */
1615
1616         *select_timeout = setup_select_timeout();
1617
1618         return True;
1619 }
1620
1621 /****************************************************************************
1622  Process commands from the client
1623 ****************************************************************************/
1624
1625 void smbd_process(void)
1626 {
1627         time_t last_timeout_processing_time = time(NULL);
1628         unsigned int num_smbs = 0;
1629
1630         max_recv = MIN(lp_maxxmit(),BUFFER_SIZE);
1631
1632         while (True) {
1633                 int select_timeout = setup_select_timeout();
1634                 int num_echos;
1635                 char *inbuf;
1636                 size_t inbuf_len;
1637                 TALLOC_CTX *frame = talloc_stackframe();
1638
1639                 errno = 0;      
1640                 
1641                 /* Did someone ask for immediate checks on things like blocking locks ? */
1642                 if (select_timeout == 0) {
1643                         if(!timeout_processing(&select_timeout,
1644                                                &last_timeout_processing_time))
1645                                 return;
1646                         num_smbs = 0; /* Reset smb counter. */
1647                 }
1648
1649                 run_events(smbd_event_context(), 0, NULL, NULL);
1650
1651                 while (!receive_message_or_smb(NULL, &inbuf, &inbuf_len,
1652                                                select_timeout)) {
1653                         if(!timeout_processing(&select_timeout,
1654                                                &last_timeout_processing_time))
1655                                 return;
1656                         num_smbs = 0; /* Reset smb counter. */
1657                 }
1658
1659
1660                 /*
1661                  * Ensure we do timeout processing if the SMB we just got was
1662                  * only an echo request. This allows us to set the select
1663                  * timeout in 'receive_message_or_smb()' to any value we like
1664                  * without worrying that the client will send echo requests
1665                  * faster than the select timeout, thus starving out the
1666                  * essential processing (change notify, blocking locks) that
1667                  * the timeout code does. JRA.
1668                  */ 
1669                 num_echos = smb_echo_count;
1670
1671                 process_smb(inbuf, inbuf_len);
1672
1673                 TALLOC_FREE(inbuf);
1674
1675                 if (smb_echo_count != num_echos) {
1676                         if(!timeout_processing( &select_timeout, &last_timeout_processing_time))
1677                                 return;
1678                         num_smbs = 0; /* Reset smb counter. */
1679                 }
1680
1681                 num_smbs++;
1682
1683                 /*
1684                  * If we are getting smb requests in a constant stream
1685                  * with no echos, make sure we attempt timeout processing
1686                  * every select_timeout milliseconds - but only check for this
1687                  * every 200 smb requests.
1688                  */
1689                 
1690                 if ((num_smbs % 200) == 0) {
1691                         time_t new_check_time = time(NULL);
1692                         if(new_check_time - last_timeout_processing_time >= (select_timeout/1000)) {
1693                                 if(!timeout_processing(
1694                                            &select_timeout,
1695                                            &last_timeout_processing_time))
1696                                         return;
1697                                 num_smbs = 0; /* Reset smb counter. */
1698                                 last_timeout_processing_time = new_check_time; /* Reset time. */
1699                         }
1700                 }
1701
1702                 /* The timeout_processing function isn't run nearly
1703                    often enough to implement 'max log size' without
1704                    overrunning the size of the file by many megabytes.
1705                    This is especially true if we are running at debug
1706                    level 10.  Checking every 50 SMBs is a nice
1707                    tradeoff of performance vs log file size overrun. */
1708
1709                 if ((num_smbs % 50) == 0 && need_to_check_log_size()) {
1710                         change_to_root_user();
1711                         check_log_size();
1712                 }
1713                 TALLOC_FREE(frame);
1714         }
1715 }