Merge Samba3 and Samba4 together
[tprouty/samba.git] / source3 / libsmb / async_smb.c
1 /*
2    Unix SMB/CIFS implementation.
3    Infrastructure for async SMB client requests
4    Copyright (C) Volker Lendecke 2008
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21
22 static void cli_state_handler(struct event_context *event_ctx,
23                               struct fd_event *event, uint16 flags, void *p);
24
25 /**
26  * Fetch an error out of a NBT packet
27  * @param[in] buf       The SMB packet
28  * @retval              The error, converted to NTSTATUS
29  */
30
31 NTSTATUS cli_pull_error(char *buf)
32 {
33         uint32_t flags2 = SVAL(buf, smb_flg2);
34
35         if (flags2 & FLAGS2_32_BIT_ERROR_CODES) {
36                 return NT_STATUS(IVAL(buf, smb_rcls));
37         }
38
39         /* if the client uses dos errors, but there is no error,
40            we should return no error here, otherwise it looks
41            like an unknown bad NT_STATUS. jmcd */
42         if (CVAL(buf, smb_rcls) == 0)
43                 return NT_STATUS_OK;
44
45         return NT_STATUS_DOS(CVAL(buf, smb_rcls), SVAL(buf,smb_err));
46 }
47
48 /**
49  * Compatibility helper for the sync APIs: Fake NTSTATUS in cli->inbuf
50  * @param[in] cli       The client connection that just received an error
51  * @param[in] status    The error to set on "cli"
52  */
53
54 void cli_set_error(struct cli_state *cli, NTSTATUS status)
55 {
56         uint32_t flags2 = SVAL(cli->inbuf, smb_flg2);
57
58         if (NT_STATUS_IS_DOS(status)) {
59                 SSVAL(cli->inbuf, smb_flg2,
60                       flags2 & ~FLAGS2_32_BIT_ERROR_CODES);
61                 SCVAL(cli->inbuf, smb_rcls, NT_STATUS_DOS_CLASS(status));
62                 SSVAL(cli->inbuf, smb_err, NT_STATUS_DOS_CODE(status));
63                 return;
64         }
65
66         SSVAL(cli->inbuf, smb_flg2, flags2 | FLAGS2_32_BIT_ERROR_CODES);
67         SIVAL(cli->inbuf, smb_rcls, NT_STATUS_V(status));
68         return;
69 }
70
71 /**
72  * Allocate a new mid
73  * @param[in] cli       The client connection
74  * @retval              The new, unused mid
75  */
76
77 static uint16_t cli_new_mid(struct cli_state *cli)
78 {
79         uint16_t result;
80         struct cli_request *req;
81
82         while (true) {
83                 result = cli->mid++;
84                 if (result == 0) {
85                         continue;
86                 }
87
88                 for (req = cli->outstanding_requests; req; req = req->next) {
89                         if (result == req->mid) {
90                                 break;
91                         }
92                 }
93
94                 if (req == NULL) {
95                         return result;
96                 }
97         }
98 }
99
100 /**
101  * Print an async req that happens to be a cli_request
102  * @param[in] mem_ctx   The TALLOC_CTX to put the result on
103  * @param[in] req       The request to print
104  * @retval              The string representation of "req"
105  */
106
107 static char *cli_request_print(TALLOC_CTX *mem_ctx, struct async_req *req)
108 {
109         char *result = async_req_print(mem_ctx, req);
110         struct cli_request *cli_req = talloc_get_type_abort(
111                 req->private_data, struct cli_request);
112
113         if (result == NULL) {
114                 return NULL;
115         }
116
117         return talloc_asprintf_append_buffer(
118                 result, "mid=%d\n", cli_req->mid);
119 }
120
121 /**
122  * Destroy a cli_request
123  * @param[in] req       The cli_request to kill
124  * @retval Can't fail
125  */
126
127 static int cli_request_destructor(struct cli_request *req)
128 {
129         if (req->enc_state != NULL) {
130                 common_free_enc_buffer(req->enc_state, req->outbuf);
131         }
132         DLIST_REMOVE(req->cli->outstanding_requests, req);
133         if (req->cli->outstanding_requests == NULL) {
134                 TALLOC_FREE(req->cli->fd_event);
135         }
136         return 0;
137 }
138
139 /**
140  * Are there already requests waiting in the chain_accumulator?
141  * @param[in] cli       The cli_state we want to check
142  * @retval reply :-)
143  */
144
145 bool cli_in_chain(struct cli_state *cli)
146 {
147         if (cli->chain_accumulator == NULL) {
148                 return false;
149         }
150
151         return (cli->chain_accumulator->num_async != 0);
152 }
153
154 /**
155  * Is the SMB command able to hold an AND_X successor
156  * @param[in] cmd       The SMB command in question
157  * @retval Can we add a chained request after "cmd"?
158  */
159
160 static bool is_andx_req(uint8_t cmd)
161 {
162         switch (cmd) {
163         case SMBtconX:
164         case SMBlockingX:
165         case SMBopenX:
166         case SMBreadX:
167         case SMBwriteX:
168         case SMBsesssetupX:
169         case SMBulogoffX:
170         case SMBntcreateX:
171                 return true;
172                 break;
173         default:
174                 break;
175         }
176
177         return false;
178 }
179
180 /**
181  * @brief Find the smb_cmd offset of the last command pushed
182  * @param[in] buf       The buffer we're building up
183  * @retval              Where can we put our next andx cmd?
184  *
185  * While chaining requests, the "next" request we're looking at needs to put
186  * its SMB_Command before the data the previous request already built up added
187  * to the chain. Find the offset to the place where we have to put our cmd.
188  */
189
190 static bool find_andx_cmd_ofs(char *buf, size_t *pofs)
191 {
192         uint8_t cmd;
193         size_t ofs;
194
195         cmd = CVAL(buf, smb_com);
196
197         SMB_ASSERT(is_andx_req(cmd));
198
199         ofs = smb_vwv0;
200
201         while (CVAL(buf, ofs) != 0xff) {
202
203                 if (!is_andx_req(CVAL(buf, ofs))) {
204                         return false;
205                 }
206
207                 /*
208                  * ofs is from start of smb header, so add the 4 length
209                  * bytes. The next cmd is right after the wct field.
210                  */
211                 ofs = SVAL(buf, ofs+2) + 4 + 1;
212
213                 SMB_ASSERT(ofs+4 < talloc_get_size(buf));
214         }
215
216         *pofs = ofs;
217         return true;
218 }
219
220 /**
221  * @brief Destroy an async_req that is the visible part of a cli_request
222  * @param[in] req       The request to kill
223  * @retval Return 0 to make talloc happy
224  *
225  * This destructor is a bit tricky: Because a cli_request can host more than
226  * one async_req for chained requests, we need to make sure that the
227  * "cli_request" that we were part of is correctly destroyed at the right
228  * time. This is done by NULLing out ourself from the "async" member of our
229  * "cli_request". If there is none left, then also TALLOC_FREE() the
230  * cli_request, which was a talloc child of the client connection cli_state.
231  */
232
233 static int cli_async_req_destructor(struct async_req *req)
234 {
235         struct cli_request *cli_req = talloc_get_type_abort(
236                 req->private_data, struct cli_request);
237         int i, pending;
238         bool found = false;
239
240         pending = 0;
241
242         for (i=0; i<cli_req->num_async; i++) {
243                 if (cli_req->async[i] == req) {
244                         cli_req->async[i] = NULL;
245                         found = true;
246                 }
247                 if (cli_req->async[i] != NULL) {
248                         pending += 1;
249                 }
250         }
251
252         SMB_ASSERT(found);
253
254         if (pending == 0) {
255                 TALLOC_FREE(cli_req);
256         }
257
258         return 0;
259 }
260
261 /**
262  * @brief Chain up a request
263  * @param[in] mem_ctx           The TALLOC_CTX for the result
264  * @param[in] ev                The event context that will call us back
265  * @param[in] cli               The cli_state we queue the request up for
266  * @param[in] smb_command       The command that we want to issue
267  * @param[in] additional_flags  open_and_x wants to add oplock header flags
268  * @param[in] wct               How many words?
269  * @param[in] vwv               The words, already in network order
270  * @param[in] num_bytes         How many bytes?
271  * @param[in] bytes             The data the request ships
272  *
273  * cli_request_chain() is the core of the SMB request marshalling routine. It
274  * will create a new async_req structure in the cli->chain_accumulator->async
275  * array and marshall the smb_cmd, the vwv array and the bytes into
276  * cli->chain_accumulator->outbuf.
277  */
278
279 static struct async_req *cli_request_chain(TALLOC_CTX *mem_ctx,
280                                            struct event_context *ev,
281                                            struct cli_state *cli,
282                                            uint8_t smb_command,
283                                            uint8_t additional_flags,
284                                            uint8_t wct, const uint16_t *vwv,
285                                            uint16_t num_bytes,
286                                            const uint8_t *bytes)
287 {
288         struct async_req **tmp_reqs;
289         char *tmp_buf;
290         struct cli_request *req;
291         size_t old_size, new_size;
292         size_t ofs;
293
294         req = cli->chain_accumulator;
295
296         tmp_reqs = TALLOC_REALLOC_ARRAY(req, req->async, struct async_req *,
297                                         req->num_async + 1);
298         if (tmp_reqs == NULL) {
299                 DEBUG(0, ("talloc failed\n"));
300                 return NULL;
301         }
302         req->async = tmp_reqs;
303         req->num_async += 1;
304
305         req->async[req->num_async-1] = async_req_new(mem_ctx, ev);
306         if (req->async[req->num_async-1] == NULL) {
307                 DEBUG(0, ("async_req_new failed\n"));
308                 req->num_async -= 1;
309                 return NULL;
310         }
311         req->async[req->num_async-1]->private_data = req;
312         req->async[req->num_async-1]->print = cli_request_print;
313         talloc_set_destructor(req->async[req->num_async-1],
314                               cli_async_req_destructor);
315
316         old_size = talloc_get_size(req->outbuf);
317
318         /*
319          * We need space for the wct field, the words, the byte count field
320          * and the bytes themselves.
321          */
322         new_size = old_size + 1 + wct * sizeof(uint16_t) + 2 + num_bytes;
323
324         if (new_size > 0xffff) {
325                 DEBUG(1, ("cli_request_chain: %u bytes won't fit\n",
326                           (unsigned)new_size));
327                 goto fail;
328         }
329
330         tmp_buf = TALLOC_REALLOC_ARRAY(NULL, req->outbuf, char, new_size);
331         if (tmp_buf == NULL) {
332                 DEBUG(0, ("talloc failed\n"));
333                 goto fail;
334         }
335         req->outbuf = tmp_buf;
336
337         if (old_size == smb_wct) {
338                 SCVAL(req->outbuf, smb_com, smb_command);
339         } else {
340                 size_t andx_cmd_ofs;
341                 if (!find_andx_cmd_ofs(req->outbuf, &andx_cmd_ofs)) {
342                         DEBUG(1, ("invalid command chain\n"));
343                         goto fail;
344                 }
345                 SCVAL(req->outbuf, andx_cmd_ofs, smb_command);
346                 SSVAL(req->outbuf, andx_cmd_ofs + 2, old_size - 4);
347         }
348
349         ofs = old_size;
350
351         SCVAL(req->outbuf, ofs, wct);
352         ofs += 1;
353
354         memcpy(req->outbuf + ofs, vwv, sizeof(uint16_t) * wct);
355         ofs += sizeof(uint16_t) * wct;
356
357         SSVAL(req->outbuf, ofs, num_bytes);
358         ofs += sizeof(uint16_t);
359
360         memcpy(req->outbuf + ofs, bytes, num_bytes);
361
362         return req->async[req->num_async-1];
363
364  fail:
365         TALLOC_FREE(req->async[req->num_async-1]);
366         req->num_async -= 1;
367         return NULL;
368 }
369
370 /**
371  * @brief prepare a cli_state to accept a chain of requests
372  * @param[in] cli       The cli_state we want to queue up in
373  * @param[in] ev        The event_context that will call us back for the socket
374  * @param[in] size_hint How many bytes are expected, just an optimization
375  * @retval Did we have enough memory?
376  *
377  * cli_chain_cork() sets up a new cli_request in cli->chain_accumulator. If
378  * cli is used in an async fashion, i.e. if we have outstanding requests, then
379  * we do not have to create a fd event. If cli is used only with the sync
380  * helpers, we need to create the fd_event here.
381  *
382  * If you want to issue a chained request to the server, do a
383  * cli_chain_cork(), then do you cli_open_send(), cli_read_and_x_send(),
384  * cli_close_send() and so on. The async requests that come out of
385  * cli_xxx_send() are normal async requests with the difference that they
386  * won't be shipped individually. But the event_context will still trigger the
387  * req->async.fn to be called on every single request.
388  *
389  * You have to take care yourself that you only issue chainable requests in
390  * the middle of the chain.
391  */
392
393 bool cli_chain_cork(struct cli_state *cli, struct event_context *ev,
394                     size_t size_hint)
395 {
396         struct cli_request *req = NULL;
397
398         SMB_ASSERT(cli->chain_accumulator == NULL);
399
400         if (cli->fd == -1) {
401                 DEBUG(10, ("cli->fd closed\n"));
402                 return false;
403         }
404
405         if (cli->fd_event == NULL) {
406                 SMB_ASSERT(cli->outstanding_requests == NULL);
407                 cli->fd_event = event_add_fd(ev, cli, cli->fd,
408                                              EVENT_FD_READ,
409                                              cli_state_handler, cli);
410                 if (cli->fd_event == NULL) {
411                         return false;
412                 }
413         }
414
415         req = talloc(cli, struct cli_request);
416         if (req == NULL) {
417                 goto fail;
418         }
419         req->cli = cli;
420
421         if (size_hint == 0) {
422                 size_hint = 100;
423         }
424         req->outbuf = talloc_array(req, char, smb_wct + size_hint);
425         if (req->outbuf == NULL) {
426                 goto fail;
427         }
428         req->outbuf = TALLOC_REALLOC_ARRAY(NULL, req->outbuf, char, smb_wct);
429
430         req->num_async = 0;
431         req->async = NULL;
432
433         req->enc_state = NULL;
434         req->recv_helper.fn = NULL;
435
436         SSVAL(req->outbuf, smb_tid, cli->cnum);
437         cli_setup_packet_buf(cli, req->outbuf);
438
439         req->mid = cli_new_mid(cli);
440
441         cli->chain_accumulator = req;
442
443         DEBUG(10, ("cli_chain_cork: mid=%d\n", req->mid));
444
445         return true;
446  fail:
447         TALLOC_FREE(req);
448         if (cli->outstanding_requests == NULL) {
449                 TALLOC_FREE(cli->fd_event);
450         }
451         return false;
452 }
453
454 /**
455  * Ship a request queued up via cli_request_chain()
456  * @param[in] cl        The connection
457  */
458
459 void cli_chain_uncork(struct cli_state *cli)
460 {
461         struct cli_request *req = cli->chain_accumulator;
462
463         SMB_ASSERT(req != NULL);
464
465         DLIST_ADD_END(cli->outstanding_requests, req, struct cli_request *);
466         talloc_set_destructor(req, cli_request_destructor);
467
468         cli->chain_accumulator = NULL;
469
470         SSVAL(req->outbuf, smb_mid, req->mid);
471         smb_setlen(req->outbuf, talloc_get_size(req->outbuf) - 4);
472
473         cli_calculate_sign_mac(cli, req->outbuf);
474
475         if (cli_encryption_on(cli)) {
476                 NTSTATUS status;
477                 char *enc_buf;
478
479                 status = cli_encrypt_message(cli, req->outbuf, &enc_buf);
480                 if (!NT_STATUS_IS_OK(status)) {
481                         DEBUG(0, ("Error in encrypting client message. "
482                                   "Error %s\n", nt_errstr(status)));
483                         TALLOC_FREE(req);
484                         return;
485                 }
486                 req->outbuf = enc_buf;
487                 req->enc_state = cli->trans_enc_state;
488         }
489
490         req->sent = 0;
491
492         event_fd_set_writeable(cli->fd_event);
493 }
494
495 /**
496  * @brief Send a request to the server
497  * @param[in] mem_ctx           The TALLOC_CTX for the result
498  * @param[in] ev                The event context that will call us back
499  * @param[in] cli               The cli_state we queue the request up for
500  * @param[in] smb_command       The command that we want to issue
501  * @param[in] additional_flags  open_and_x wants to add oplock header flags
502  * @param[in] wct               How many words?
503  * @param[in] vwv               The words, already in network order
504  * @param[in] num_bytes         How many bytes?
505  * @param[in] bytes             The data the request ships
506  *
507  * This is the generic routine to be used by the cli_xxx_send routines.
508  */
509
510 struct async_req *cli_request_send(TALLOC_CTX *mem_ctx,
511                                    struct event_context *ev,
512                                    struct cli_state *cli,
513                                    uint8_t smb_command,
514                                    uint8_t additional_flags,
515                                    uint8_t wct, const uint16_t *vwv,
516                                    uint16_t num_bytes, const uint8_t *bytes)
517 {
518         struct async_req *result;
519         bool uncork = false;
520
521         if (cli->chain_accumulator == NULL) {
522                 if (!cli_chain_cork(cli, ev,
523                                     wct * sizeof(uint16_t) + num_bytes + 3)) {
524                         DEBUG(1, ("cli_chain_cork failed\n"));
525                         return NULL;
526                 }
527                 uncork = true;
528         }
529
530         result = cli_request_chain(mem_ctx, ev, cli, smb_command,
531                                    additional_flags, wct, vwv,
532                                    num_bytes, bytes);
533
534         if (result == NULL) {
535                 DEBUG(1, ("cli_request_chain failed\n"));
536         }
537
538         if (uncork) {
539                 cli_chain_uncork(cli);
540         }
541
542         return result;
543 }
544
545 /**
546  * Figure out if there is an andx command behind the current one
547  * @param[in] buf       The smb buffer to look at
548  * @param[in] ofs       The offset to the wct field that is followed by the cmd
549  * @retval Is there a command following?
550  */
551
552 static bool have_andx_command(const char *buf, uint16_t ofs)
553 {
554         uint8_t wct;
555         size_t buflen = talloc_get_size(buf);
556
557         if ((ofs == buflen-1) || (ofs == buflen)) {
558                 return false;
559         }
560
561         wct = CVAL(buf, ofs);
562         if (wct < 2) {
563                 /*
564                  * Not enough space for the command and a following pointer
565                  */
566                 return false;
567         }
568         return (CVAL(buf, ofs+1) != 0xff);
569 }
570
571 /**
572  * @brief Pull reply data out of a request
573  * @param[in] req               The request that we just received a reply for
574  * @param[out] pwct             How many words did the server send?
575  * @param[out] pvwv             The words themselves
576  * @param[out] pnum_bytes       How many bytes did the server send?
577  * @param[out] pbytes           The bytes themselves
578  * @retval Was the reply formally correct?
579  */
580
581 NTSTATUS cli_pull_reply(struct async_req *req,
582                         uint8_t *pwct, uint16_t **pvwv,
583                         uint16_t *pnum_bytes, uint8_t **pbytes)
584 {
585         struct cli_request *cli_req = talloc_get_type_abort(
586                 req->private_data, struct cli_request);
587         uint8_t wct, cmd;
588         uint16_t num_bytes;
589         size_t wct_ofs, bytes_offset;
590         int i, j;
591         NTSTATUS status;
592
593         for (i = 0; i < cli_req->num_async; i++) {
594                 if (req == cli_req->async[i]) {
595                         break;
596                 }
597         }
598
599         if (i == cli_req->num_async) {
600                 cli_set_error(cli_req->cli, NT_STATUS_INVALID_PARAMETER);
601                 return NT_STATUS_INVALID_PARAMETER;
602         }
603
604         /**
605          * The status we pull here is only relevant for the last reply in the
606          * chain.
607          */
608
609         status = cli_pull_error(cli_req->inbuf);
610
611         if (i == 0) {
612                 if (NT_STATUS_IS_ERR(status)
613                     && !have_andx_command(cli_req->inbuf, smb_wct)) {
614                         cli_set_error(cli_req->cli, status);
615                         return status;
616                 }
617                 wct_ofs = smb_wct;
618                 goto done;
619         }
620
621         cmd = CVAL(cli_req->inbuf, smb_com);
622         wct_ofs = smb_wct;
623
624         for (j = 0; j < i; j++) {
625                 if (j < i-1) {
626                         if (cmd == 0xff) {
627                                 return NT_STATUS_REQUEST_ABORTED;
628                         }
629                         if (!is_andx_req(cmd)) {
630                                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
631                         }
632                 }
633
634                 if (!have_andx_command(cli_req->inbuf, wct_ofs)) {
635                         /*
636                          * This request was not completed because a previous
637                          * request in the chain had received an error.
638                          */
639                         return NT_STATUS_REQUEST_ABORTED;
640                 }
641
642                 wct_ofs = SVAL(cli_req->inbuf, wct_ofs + 3);
643
644                 /*
645                  * Skip the all-present length field. No overflow, we've just
646                  * put a 16-bit value into a size_t.
647                  */
648                 wct_ofs += 4;
649
650                 if (wct_ofs+2 > talloc_get_size(cli_req->inbuf)) {
651                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
652                 }
653
654                 cmd = CVAL(cli_req->inbuf, wct_ofs + 1);
655         }
656
657         if (!have_andx_command(cli_req->inbuf, wct_ofs)
658             && NT_STATUS_IS_ERR(status)) {
659                 /*
660                  * The last command takes the error code. All further commands
661                  * down the requested chain will get a
662                  * NT_STATUS_REQUEST_ABORTED.
663                  */
664                 return status;
665         }
666
667  done:
668         wct = CVAL(cli_req->inbuf, wct_ofs);
669
670         bytes_offset = wct_ofs + 1 + wct * sizeof(uint16_t);
671         num_bytes = SVAL(cli_req->inbuf, bytes_offset);
672
673         /*
674          * wct_ofs is a 16-bit value plus 4, wct is a 8-bit value, num_bytes
675          * is a 16-bit value. So bytes_offset being size_t should be far from
676          * wrapping.
677          */
678
679         if ((bytes_offset + 2 > talloc_get_size(cli_req->inbuf))
680             || (bytes_offset > 0xffff)) {
681                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
682         }
683
684         *pwct = wct;
685         *pvwv = (uint16_t *)(cli_req->inbuf + wct_ofs + 1);
686         *pnum_bytes = num_bytes;
687         *pbytes = (uint8_t *)cli_req->inbuf + bytes_offset + 2;
688
689         return NT_STATUS_OK;
690 }
691
692 /**
693  * Decrypt a PDU, check the signature
694  * @param[in] cli       The cli_state that received something
695  * @param[in] pdu       The incoming bytes
696  * @retval error code
697  */
698
699
700 static NTSTATUS validate_smb_crypto(struct cli_state *cli, char *pdu)
701 {
702         NTSTATUS status;
703
704         if ((IVAL(pdu, 4) != 0x424d53ff) /* 0xFF"SMB" */
705             && (SVAL(pdu, 4) != 0x45ff)) /* 0xFF"E" */ {
706                 DEBUG(10, ("Got non-SMB PDU\n"));
707                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
708         }
709
710         if (cli_encryption_on(cli) && CVAL(pdu, 0) == 0) {
711                 uint16_t enc_ctx_num;
712
713                 status = get_enc_ctx_num((uint8_t *)pdu, &enc_ctx_num);
714                 if (!NT_STATUS_IS_OK(status)) {
715                         DEBUG(10, ("get_enc_ctx_num returned %s\n",
716                                    nt_errstr(status)));
717                         return status;
718                 }
719
720                 if (enc_ctx_num != cli->trans_enc_state->enc_ctx_num) {
721                         DEBUG(10, ("wrong enc_ctx %d, expected %d\n",
722                                    enc_ctx_num,
723                                    cli->trans_enc_state->enc_ctx_num));
724                         return NT_STATUS_INVALID_HANDLE;
725                 }
726
727                 status = common_decrypt_buffer(cli->trans_enc_state, pdu);
728                 if (!NT_STATUS_IS_OK(status)) {
729                         DEBUG(10, ("common_decrypt_buffer returned %s\n",
730                                    nt_errstr(status)));
731                         return status;
732                 }
733         }
734
735         if (!cli_check_sign_mac(cli, pdu)) {
736                 DEBUG(10, ("cli_check_sign_mac failed\n"));
737                 return NT_STATUS_ACCESS_DENIED;
738         }
739
740         return NT_STATUS_OK;
741 }
742
743 /**
744  * A PDU has arrived on cli->evt_inbuf
745  * @param[in] cli       The cli_state that received something
746  */
747
748 static void handle_incoming_pdu(struct cli_state *cli)
749 {
750         struct cli_request *req;
751         uint16_t mid;
752         size_t raw_pdu_len, buf_len, pdu_len, rest_len;
753         char *pdu;
754         int i;
755         NTSTATUS status;
756
757         int num_async;
758
759         /*
760          * The encrypted PDU len might differ from the unencrypted one
761          */
762         raw_pdu_len = smb_len(cli->evt_inbuf) + 4;
763         buf_len = talloc_get_size(cli->evt_inbuf);
764         rest_len = buf_len - raw_pdu_len;
765
766         if (buf_len == raw_pdu_len) {
767                 /*
768                  * Optimal case: Exactly one PDU was in the socket buffer
769                  */
770                 pdu = cli->evt_inbuf;
771                 cli->evt_inbuf = NULL;
772         }
773         else {
774                 DEBUG(11, ("buf_len = %d, raw_pdu_len = %d, splitting "
775                            "buffer\n", (int)buf_len, (int)raw_pdu_len));
776
777                 if (raw_pdu_len < rest_len) {
778                         /*
779                          * The PDU is shorter, talloc_memdup that one.
780                          */
781                         pdu = (char *)talloc_memdup(
782                                 cli, cli->evt_inbuf, raw_pdu_len);
783
784                         memmove(cli->evt_inbuf, cli->evt_inbuf + raw_pdu_len,
785                                 buf_len - raw_pdu_len);
786
787                         cli->evt_inbuf = TALLOC_REALLOC_ARRAY(
788                                 NULL, cli->evt_inbuf, char, rest_len);
789
790                         if (pdu == NULL) {
791                                 status = NT_STATUS_NO_MEMORY;
792                                 goto invalidate_requests;
793                         }
794                 }
795                 else {
796                         /*
797                          * The PDU is larger than the rest, talloc_memdup the
798                          * rest
799                          */
800                         pdu = cli->evt_inbuf;
801
802                         cli->evt_inbuf = (char *)talloc_memdup(
803                                 cli, pdu + raw_pdu_len, rest_len);
804
805                         if (cli->evt_inbuf == NULL) {
806                                 status = NT_STATUS_NO_MEMORY;
807                                 goto invalidate_requests;
808                         }
809                 }
810         }
811
812         status = validate_smb_crypto(cli, pdu);
813         if (!NT_STATUS_IS_OK(status)) {
814                 goto invalidate_requests;
815         }
816
817         mid = SVAL(pdu, smb_mid);
818
819         DEBUG(10, ("handle_incoming_pdu: got mid %d\n", mid));
820
821         for (req = cli->outstanding_requests; req; req = req->next) {
822                 if (req->mid == mid) {
823                         break;
824                 }
825         }
826
827         pdu_len = smb_len(pdu) + 4;
828
829         if (req == NULL) {
830                 DEBUG(3, ("Request for mid %d not found, dumping PDU\n", mid));
831
832                 TALLOC_FREE(pdu);
833                 return;
834         }
835
836         req->inbuf = talloc_move(req, &pdu);
837
838         /*
839          * Freeing the last async_req will free the req (see
840          * cli_async_req_destructor). So make a copy of req->num_async, we
841          * can't reference it in the last round.
842          */
843
844         num_async = req->num_async;
845
846         for (i=0; i<num_async; i++) {
847                 /**
848                  * A request might have been talloc_free()'ed before we arrive
849                  * here. It will have removed itself from req->async via its
850                  * destructor cli_async_req_destructor().
851                  */
852                 if (req->async[i] != NULL) {
853                         if (req->recv_helper.fn != NULL) {
854                                 req->recv_helper.fn(req->async[i]);
855                         } else {
856                                 async_req_done(req->async[i]);
857                         }
858                 }
859         }
860         return;
861
862  invalidate_requests:
863
864         DEBUG(10, ("handle_incoming_pdu: Aborting with %s\n",
865                    nt_errstr(status)));
866
867         for (req = cli->outstanding_requests; req; req = req->next) {
868                 async_req_error(req->async[0], status);
869         }
870         return;
871 }
872
873 /**
874  * fd event callback. This is the basic connection to the socket
875  * @param[in] event_ctx The event context that called us
876  * @param[in] event     The event that fired
877  * @param[in] flags     EVENT_FD_READ | EVENT_FD_WRITE
878  * @param[in] p         private_data, in this case the cli_state
879  */
880
881 static void cli_state_handler(struct event_context *event_ctx,
882                               struct fd_event *event, uint16 flags, void *p)
883 {
884         struct cli_state *cli = (struct cli_state *)p;
885         struct cli_request *req;
886         NTSTATUS status;
887
888         DEBUG(11, ("cli_state_handler called with flags %d\n", flags));
889
890         if (flags & EVENT_FD_READ) {
891                 int res, available;
892                 size_t old_size, new_size;
893                 char *tmp;
894
895                 res = ioctl(cli->fd, FIONREAD, &available);
896                 if (res == -1) {
897                         DEBUG(10, ("ioctl(FIONREAD) failed: %s\n",
898                                    strerror(errno)));
899                         status = map_nt_error_from_unix(errno);
900                         goto sock_error;
901                 }
902
903                 if (available == 0) {
904                         /* EOF */
905                         status = NT_STATUS_END_OF_FILE;
906                         goto sock_error;
907                 }
908
909                 old_size = talloc_get_size(cli->evt_inbuf);
910                 new_size = old_size + available;
911
912                 if (new_size < old_size) {
913                         /* wrap */
914                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
915                         goto sock_error;
916                 }
917
918                 tmp = TALLOC_REALLOC_ARRAY(cli, cli->evt_inbuf, char,
919                                            new_size);
920                 if (tmp == NULL) {
921                         /* nomem */
922                         status = NT_STATUS_NO_MEMORY;
923                         goto sock_error;
924                 }
925                 cli->evt_inbuf = tmp;
926
927                 res = recv(cli->fd, cli->evt_inbuf + old_size, available, 0);
928                 if (res == -1) {
929                         DEBUG(10, ("recv failed: %s\n", strerror(errno)));
930                         status = map_nt_error_from_unix(errno);
931                         goto sock_error;
932                 }
933
934                 DEBUG(11, ("cli_state_handler: received %d bytes, "
935                            "smb_len(evt_inbuf) = %d\n", (int)res,
936                            smb_len(cli->evt_inbuf)));
937
938                 /* recv *might* have returned less than announced */
939                 new_size = old_size + res;
940
941                 /* shrink, so I don't expect errors here */
942                 cli->evt_inbuf = TALLOC_REALLOC_ARRAY(cli, cli->evt_inbuf,
943                                                       char, new_size);
944
945                 while ((cli->evt_inbuf != NULL)
946                        && ((smb_len(cli->evt_inbuf) + 4) <= new_size)) {
947                         /*
948                          * we've got a complete NBT level PDU in evt_inbuf
949                          */
950                         handle_incoming_pdu(cli);
951                         new_size = talloc_get_size(cli->evt_inbuf);
952                 }
953         }
954
955         if (flags & EVENT_FD_WRITE) {
956                 size_t to_send;
957                 ssize_t sent;
958
959                 for (req = cli->outstanding_requests; req; req = req->next) {
960                         to_send = smb_len(req->outbuf)+4;
961                         if (to_send > req->sent) {
962                                 break;
963                         }
964                 }
965
966                 if (req == NULL) {
967                         if (cli->fd_event != NULL) {
968                                 event_fd_set_not_writeable(cli->fd_event);
969                         }
970                         return;
971                 }
972
973                 sent = send(cli->fd, req->outbuf + req->sent,
974                             to_send - req->sent, 0);
975
976                 if (sent < 0) {
977                         status = map_nt_error_from_unix(errno);
978                         goto sock_error;
979                 }
980
981                 req->sent += sent;
982
983                 if (req->sent == to_send) {
984                         return;
985                 }
986         }
987         return;
988
989  sock_error:
990         for (req = cli->outstanding_requests; req; req = req->next) {
991                 int i;
992                 for (i=0; i<req->num_async; i++) {
993                         async_req_error(req->async[i], status);
994                 }
995         }
996         TALLOC_FREE(cli->fd_event);
997         close(cli->fd);
998         cli->fd = -1;
999 }