Add some comments
[metze/samba/wip.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 Do the smb chaining at a buffer level
222  * @param[in] poutbuf           Pointer to the talloc'ed buffer to be modified
223  * @param[in] smb_command       The command that we want to issue
224  * @param[in] wct               How many words?
225  * @param[in] vwv               The words, already in network order
226  * @param[in] bytes_alignment   How shall we align "bytes"?
227  * @param[in] num_bytes         How many bytes?
228  * @param[in] bytes             The data the request ships
229  *
230  * smb_splice_chain() adds the vwv and bytes to the request already present in
231  * *poutbuf.
232  */
233
234 bool smb_splice_chain(char **poutbuf, uint8_t smb_command,
235                       uint8_t wct, const uint16_t *vwv,
236                       size_t bytes_alignment,
237                       uint16_t num_bytes, const uint8_t *bytes)
238 {
239         char *outbuf;
240         size_t old_size, new_size;
241         size_t ofs;
242         size_t chain_padding = 0;
243         size_t bytes_padding = 0;
244         bool first_request;
245
246         old_size = talloc_get_size(*poutbuf);
247
248         /*
249          * old_size == smb_wct means we're pushing the first request in for
250          * libsmb/
251          */
252
253         first_request = (old_size == smb_wct);
254
255         if (!first_request && ((old_size % 4) != 0)) {
256                 /*
257                  * Align the wct field of subsequent requests to a 4-byte
258                  * boundary
259                  */
260                 chain_padding = 4 - (old_size % 4);
261         }
262
263         /*
264          * After the old request comes the new wct field (1 byte), the vwv's
265          * and the num_bytes field. After at we might need to align the bytes
266          * given to us to "bytes_alignment", increasing the num_bytes value.
267          */
268
269         new_size = old_size + chain_padding + 1 + wct * sizeof(uint16_t) + 2;
270
271         if ((bytes_alignment != 0) && ((new_size % bytes_alignment) != 0)) {
272                 bytes_padding = bytes_alignment - (new_size % bytes_alignment);
273         }
274
275         new_size += bytes_padding + num_bytes;
276
277         if (new_size > 0xffff) {
278                 DEBUG(1, ("splice_chain: %u bytes won't fit\n",
279                           (unsigned)new_size));
280                 return false;
281         }
282
283         outbuf = TALLOC_REALLOC_ARRAY(NULL, *poutbuf, char, new_size);
284         if (outbuf == NULL) {
285                 DEBUG(0, ("talloc failed\n"));
286                 return false;
287         }
288         *poutbuf = outbuf;
289
290         if (first_request) {
291                 SCVAL(outbuf, smb_com, smb_command);
292         } else {
293                 size_t andx_cmd_ofs;
294
295                 if (!find_andx_cmd_ofs(outbuf, &andx_cmd_ofs)) {
296                         DEBUG(1, ("invalid command chain\n"));
297                         *poutbuf = TALLOC_REALLOC_ARRAY(
298                                 NULL, *poutbuf, char, old_size);
299                         return false;
300                 }
301
302                 if (chain_padding != 0) {
303                         memset(outbuf + old_size, 0, chain_padding);
304                         old_size += chain_padding;
305                 }
306
307                 SCVAL(outbuf, andx_cmd_ofs, smb_command);
308                 SSVAL(outbuf, andx_cmd_ofs + 2, old_size - 4);
309         }
310
311         ofs = old_size;
312
313         /*
314          * Push the chained request:
315          *
316          * wct field
317          */
318
319         SCVAL(outbuf, ofs, wct);
320         ofs += 1;
321
322         /*
323          * vwv array
324          */
325
326         memcpy(outbuf + ofs, vwv, sizeof(uint16_t) * wct);
327         ofs += sizeof(uint16_t) * wct;
328
329         /*
330          * bcc (byte count)
331          */
332
333         SSVAL(outbuf, ofs, num_bytes + bytes_padding);
334         ofs += sizeof(uint16_t);
335
336         /*
337          * padding
338          */
339
340         if (bytes_padding != 0) {
341                 memset(outbuf + ofs, 0, bytes_padding);
342                 ofs += bytes_padding;
343         }
344
345         /*
346          * The bytes field
347          */
348
349         memcpy(outbuf + ofs, bytes, num_bytes);
350
351         return true;
352 }
353
354 /**
355  * @brief Destroy an async_req that is the visible part of a cli_request
356  * @param[in] req       The request to kill
357  * @retval Return 0 to make talloc happy
358  *
359  * This destructor is a bit tricky: Because a cli_request can host more than
360  * one async_req for chained requests, we need to make sure that the
361  * "cli_request" that we were part of is correctly destroyed at the right
362  * time. This is done by NULLing out ourself from the "async" member of our
363  * "cli_request". If there is none left, then also TALLOC_FREE() the
364  * cli_request, which was a talloc child of the client connection cli_state.
365  */
366
367 static int cli_async_req_destructor(struct async_req *req)
368 {
369         struct cli_request *cli_req = talloc_get_type_abort(
370                 req->private_data, struct cli_request);
371         int i, pending;
372         bool found = false;
373
374         pending = 0;
375
376         for (i=0; i<cli_req->num_async; i++) {
377                 if (cli_req->async[i] == req) {
378                         cli_req->async[i] = NULL;
379                         found = true;
380                 }
381                 if (cli_req->async[i] != NULL) {
382                         pending += 1;
383                 }
384         }
385
386         SMB_ASSERT(found);
387
388         if (pending == 0) {
389                 TALLOC_FREE(cli_req);
390         }
391
392         return 0;
393 }
394
395 /**
396  * @brief Chain up a request
397  * @param[in] mem_ctx           The TALLOC_CTX for the result
398  * @param[in] ev                The event context that will call us back
399  * @param[in] cli               The cli_state we queue the request up for
400  * @param[in] smb_command       The command that we want to issue
401  * @param[in] additional_flags  open_and_x wants to add oplock header flags
402  * @param[in] wct               How many words?
403  * @param[in] vwv               The words, already in network order
404  * @param[in] num_bytes         How many bytes?
405  * @param[in] bytes             The data the request ships
406  *
407  * cli_request_chain() is the core of the SMB request marshalling routine. It
408  * will create a new async_req structure in the cli->chain_accumulator->async
409  * array and marshall the smb_cmd, the vwv array and the bytes into
410  * cli->chain_accumulator->outbuf.
411  */
412
413 static struct async_req *cli_request_chain(TALLOC_CTX *mem_ctx,
414                                            struct event_context *ev,
415                                            struct cli_state *cli,
416                                            uint8_t smb_command,
417                                            uint8_t additional_flags,
418                                            uint8_t wct, const uint16_t *vwv,
419                                            size_t bytes_alignment,
420                                            uint16_t num_bytes,
421                                            const uint8_t *bytes)
422 {
423         struct async_req **tmp_reqs;
424         struct cli_request *req;
425
426         req = cli->chain_accumulator;
427
428         tmp_reqs = TALLOC_REALLOC_ARRAY(req, req->async, struct async_req *,
429                                         req->num_async + 1);
430         if (tmp_reqs == NULL) {
431                 DEBUG(0, ("talloc failed\n"));
432                 return NULL;
433         }
434         req->async = tmp_reqs;
435         req->num_async += 1;
436
437         req->async[req->num_async-1] = async_req_new(mem_ctx, ev);
438         if (req->async[req->num_async-1] == NULL) {
439                 DEBUG(0, ("async_req_new failed\n"));
440                 req->num_async -= 1;
441                 return NULL;
442         }
443         req->async[req->num_async-1]->private_data = req;
444         req->async[req->num_async-1]->print = cli_request_print;
445         talloc_set_destructor(req->async[req->num_async-1],
446                               cli_async_req_destructor);
447
448         if (!smb_splice_chain(&req->outbuf, smb_command, wct, vwv,
449                               bytes_alignment, num_bytes, bytes)) {
450                 goto fail;
451         }
452
453         return req->async[req->num_async-1];
454
455  fail:
456         TALLOC_FREE(req->async[req->num_async-1]);
457         req->num_async -= 1;
458         return NULL;
459 }
460
461 /**
462  * @brief prepare a cli_state to accept a chain of requests
463  * @param[in] cli       The cli_state we want to queue up in
464  * @param[in] ev        The event_context that will call us back for the socket
465  * @param[in] size_hint How many bytes are expected, just an optimization
466  * @retval Did we have enough memory?
467  *
468  * cli_chain_cork() sets up a new cli_request in cli->chain_accumulator. If
469  * cli is used in an async fashion, i.e. if we have outstanding requests, then
470  * we do not have to create a fd event. If cli is used only with the sync
471  * helpers, we need to create the fd_event here.
472  *
473  * If you want to issue a chained request to the server, do a
474  * cli_chain_cork(), then do you cli_open_send(), cli_read_and_x_send(),
475  * cli_close_send() and so on. The async requests that come out of
476  * cli_xxx_send() are normal async requests with the difference that they
477  * won't be shipped individually. But the event_context will still trigger the
478  * req->async.fn to be called on every single request.
479  *
480  * You have to take care yourself that you only issue chainable requests in
481  * the middle of the chain.
482  */
483
484 bool cli_chain_cork(struct cli_state *cli, struct event_context *ev,
485                     size_t size_hint)
486 {
487         struct cli_request *req = NULL;
488
489         SMB_ASSERT(cli->chain_accumulator == NULL);
490
491         if (cli->fd == -1) {
492                 DEBUG(10, ("cli->fd closed\n"));
493                 return false;
494         }
495
496         if (cli->fd_event == NULL) {
497                 SMB_ASSERT(cli->outstanding_requests == NULL);
498                 cli->fd_event = event_add_fd(ev, cli, cli->fd,
499                                              EVENT_FD_READ,
500                                              cli_state_handler, cli);
501                 if (cli->fd_event == NULL) {
502                         return false;
503                 }
504         }
505
506         req = talloc(cli, struct cli_request);
507         if (req == NULL) {
508                 goto fail;
509         }
510         req->cli = cli;
511
512         if (size_hint == 0) {
513                 size_hint = 100;
514         }
515         req->outbuf = talloc_array(req, char, smb_wct + size_hint);
516         if (req->outbuf == NULL) {
517                 goto fail;
518         }
519         req->outbuf = TALLOC_REALLOC_ARRAY(NULL, req->outbuf, char, smb_wct);
520
521         req->num_async = 0;
522         req->async = NULL;
523
524         req->enc_state = NULL;
525         req->recv_helper.fn = NULL;
526
527         SSVAL(req->outbuf, smb_tid, cli->cnum);
528         cli_setup_packet_buf(cli, req->outbuf);
529
530         req->mid = cli_new_mid(cli);
531
532         cli->chain_accumulator = req;
533
534         DEBUG(10, ("cli_chain_cork: mid=%d\n", req->mid));
535
536         return true;
537  fail:
538         TALLOC_FREE(req);
539         if (cli->outstanding_requests == NULL) {
540                 TALLOC_FREE(cli->fd_event);
541         }
542         return false;
543 }
544
545 /**
546  * Ship a request queued up via cli_request_chain()
547  * @param[in] cl        The connection
548  */
549
550 void cli_chain_uncork(struct cli_state *cli)
551 {
552         struct cli_request *req = cli->chain_accumulator;
553
554         SMB_ASSERT(req != NULL);
555
556         DLIST_ADD_END(cli->outstanding_requests, req, struct cli_request *);
557         talloc_set_destructor(req, cli_request_destructor);
558
559         cli->chain_accumulator = NULL;
560
561         SSVAL(req->outbuf, smb_mid, req->mid);
562         smb_setlen(req->outbuf, talloc_get_size(req->outbuf) - 4);
563
564         cli_calculate_sign_mac(cli, req->outbuf);
565
566         if (cli_encryption_on(cli)) {
567                 NTSTATUS status;
568                 char *enc_buf;
569
570                 status = cli_encrypt_message(cli, req->outbuf, &enc_buf);
571                 if (!NT_STATUS_IS_OK(status)) {
572                         DEBUG(0, ("Error in encrypting client message. "
573                                   "Error %s\n", nt_errstr(status)));
574                         TALLOC_FREE(req);
575                         return;
576                 }
577                 req->outbuf = enc_buf;
578                 req->enc_state = cli->trans_enc_state;
579         }
580
581         req->sent = 0;
582
583         event_fd_set_writeable(cli->fd_event);
584 }
585
586 /**
587  * @brief Send a request to the server
588  * @param[in] mem_ctx           The TALLOC_CTX for the result
589  * @param[in] ev                The event context that will call us back
590  * @param[in] cli               The cli_state we queue the request up for
591  * @param[in] smb_command       The command that we want to issue
592  * @param[in] additional_flags  open_and_x wants to add oplock header flags
593  * @param[in] wct               How many words?
594  * @param[in] vwv               The words, already in network order
595  * @param[in] bytes_alignment   How shall we align "bytes"?
596  * @param[in] num_bytes         How many bytes?
597  * @param[in] bytes             The data the request ships
598  *
599  * This is the generic routine to be used by the cli_xxx_send routines.
600  */
601
602 struct async_req *cli_request_send(TALLOC_CTX *mem_ctx,
603                                    struct event_context *ev,
604                                    struct cli_state *cli,
605                                    uint8_t smb_command,
606                                    uint8_t additional_flags,
607                                    uint8_t wct, const uint16_t *vwv,
608                                    size_t bytes_alignment,
609                                    uint16_t num_bytes, const uint8_t *bytes)
610 {
611         struct async_req *result;
612         bool uncork = false;
613
614         if (cli->chain_accumulator == NULL) {
615                 if (!cli_chain_cork(cli, ev,
616                                     wct * sizeof(uint16_t) + num_bytes + 3)) {
617                         DEBUG(1, ("cli_chain_cork failed\n"));
618                         return NULL;
619                 }
620                 uncork = true;
621         }
622
623         result = cli_request_chain(mem_ctx, ev, cli, smb_command,
624                                    additional_flags, wct, vwv, bytes_alignment,
625                                    num_bytes, bytes);
626
627         if (result == NULL) {
628                 DEBUG(1, ("cli_request_chain failed\n"));
629         }
630
631         if (uncork) {
632                 cli_chain_uncork(cli);
633         }
634
635         return result;
636 }
637
638 /**
639  * Figure out if there is an andx command behind the current one
640  * @param[in] buf       The smb buffer to look at
641  * @param[in] ofs       The offset to the wct field that is followed by the cmd
642  * @retval Is there a command following?
643  */
644
645 static bool have_andx_command(const char *buf, uint16_t ofs)
646 {
647         uint8_t wct;
648         size_t buflen = talloc_get_size(buf);
649
650         if ((ofs == buflen-1) || (ofs == buflen)) {
651                 return false;
652         }
653
654         wct = CVAL(buf, ofs);
655         if (wct < 2) {
656                 /*
657                  * Not enough space for the command and a following pointer
658                  */
659                 return false;
660         }
661         return (CVAL(buf, ofs+1) != 0xff);
662 }
663
664 /**
665  * @brief Pull reply data out of a request
666  * @param[in] req               The request that we just received a reply for
667  * @param[out] pwct             How many words did the server send?
668  * @param[out] pvwv             The words themselves
669  * @param[out] pnum_bytes       How many bytes did the server send?
670  * @param[out] pbytes           The bytes themselves
671  * @retval Was the reply formally correct?
672  */
673
674 NTSTATUS cli_pull_reply(struct async_req *req,
675                         uint8_t *pwct, uint16_t **pvwv,
676                         uint16_t *pnum_bytes, uint8_t **pbytes)
677 {
678         struct cli_request *cli_req = talloc_get_type_abort(
679                 req->private_data, struct cli_request);
680         uint8_t wct, cmd;
681         uint16_t num_bytes;
682         size_t wct_ofs, bytes_offset;
683         int i, j;
684         NTSTATUS status;
685
686         for (i = 0; i < cli_req->num_async; i++) {
687                 if (req == cli_req->async[i]) {
688                         break;
689                 }
690         }
691
692         if (i == cli_req->num_async) {
693                 cli_set_error(cli_req->cli, NT_STATUS_INVALID_PARAMETER);
694                 return NT_STATUS_INVALID_PARAMETER;
695         }
696
697         /**
698          * The status we pull here is only relevant for the last reply in the
699          * chain.
700          */
701
702         status = cli_pull_error(cli_req->inbuf);
703
704         if (i == 0) {
705                 if (NT_STATUS_IS_ERR(status)
706                     && !have_andx_command(cli_req->inbuf, smb_wct)) {
707                         cli_set_error(cli_req->cli, status);
708                         return status;
709                 }
710                 wct_ofs = smb_wct;
711                 goto done;
712         }
713
714         cmd = CVAL(cli_req->inbuf, smb_com);
715         wct_ofs = smb_wct;
716
717         for (j = 0; j < i; j++) {
718                 if (j < i-1) {
719                         if (cmd == 0xff) {
720                                 return NT_STATUS_REQUEST_ABORTED;
721                         }
722                         if (!is_andx_req(cmd)) {
723                                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
724                         }
725                 }
726
727                 if (!have_andx_command(cli_req->inbuf, wct_ofs)) {
728                         /*
729                          * This request was not completed because a previous
730                          * request in the chain had received an error.
731                          */
732                         return NT_STATUS_REQUEST_ABORTED;
733                 }
734
735                 wct_ofs = SVAL(cli_req->inbuf, wct_ofs + 3);
736
737                 /*
738                  * Skip the all-present length field. No overflow, we've just
739                  * put a 16-bit value into a size_t.
740                  */
741                 wct_ofs += 4;
742
743                 if (wct_ofs+2 > talloc_get_size(cli_req->inbuf)) {
744                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
745                 }
746
747                 cmd = CVAL(cli_req->inbuf, wct_ofs + 1);
748         }
749
750         if (!have_andx_command(cli_req->inbuf, wct_ofs)
751             && NT_STATUS_IS_ERR(status)) {
752                 /*
753                  * The last command takes the error code. All further commands
754                  * down the requested chain will get a
755                  * NT_STATUS_REQUEST_ABORTED.
756                  */
757                 return status;
758         }
759
760  done:
761         wct = CVAL(cli_req->inbuf, wct_ofs);
762
763         bytes_offset = wct_ofs + 1 + wct * sizeof(uint16_t);
764         num_bytes = SVAL(cli_req->inbuf, bytes_offset);
765
766         /*
767          * wct_ofs is a 16-bit value plus 4, wct is a 8-bit value, num_bytes
768          * is a 16-bit value. So bytes_offset being size_t should be far from
769          * wrapping.
770          */
771
772         if ((bytes_offset + 2 > talloc_get_size(cli_req->inbuf))
773             || (bytes_offset > 0xffff)) {
774                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
775         }
776
777         *pwct = wct;
778         *pvwv = (uint16_t *)(cli_req->inbuf + wct_ofs + 1);
779         *pnum_bytes = num_bytes;
780         *pbytes = (uint8_t *)cli_req->inbuf + bytes_offset + 2;
781
782         return NT_STATUS_OK;
783 }
784
785 /**
786  * Decrypt a PDU, check the signature
787  * @param[in] cli       The cli_state that received something
788  * @param[in] pdu       The incoming bytes
789  * @retval error code
790  */
791
792
793 static NTSTATUS validate_smb_crypto(struct cli_state *cli, char *pdu)
794 {
795         NTSTATUS status;
796
797         if ((IVAL(pdu, 4) != 0x424d53ff) /* 0xFF"SMB" */
798             && (SVAL(pdu, 4) != 0x45ff)) /* 0xFF"E" */ {
799                 DEBUG(10, ("Got non-SMB PDU\n"));
800                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
801         }
802
803         if (cli_encryption_on(cli) && CVAL(pdu, 0) == 0) {
804                 uint16_t enc_ctx_num;
805
806                 status = get_enc_ctx_num((uint8_t *)pdu, &enc_ctx_num);
807                 if (!NT_STATUS_IS_OK(status)) {
808                         DEBUG(10, ("get_enc_ctx_num returned %s\n",
809                                    nt_errstr(status)));
810                         return status;
811                 }
812
813                 if (enc_ctx_num != cli->trans_enc_state->enc_ctx_num) {
814                         DEBUG(10, ("wrong enc_ctx %d, expected %d\n",
815                                    enc_ctx_num,
816                                    cli->trans_enc_state->enc_ctx_num));
817                         return NT_STATUS_INVALID_HANDLE;
818                 }
819
820                 status = common_decrypt_buffer(cli->trans_enc_state, pdu);
821                 if (!NT_STATUS_IS_OK(status)) {
822                         DEBUG(10, ("common_decrypt_buffer returned %s\n",
823                                    nt_errstr(status)));
824                         return status;
825                 }
826         }
827
828         if (!cli_check_sign_mac(cli, pdu)) {
829                 DEBUG(10, ("cli_check_sign_mac failed\n"));
830                 return NT_STATUS_ACCESS_DENIED;
831         }
832
833         return NT_STATUS_OK;
834 }
835
836 /**
837  * A PDU has arrived on cli->evt_inbuf
838  * @param[in] cli       The cli_state that received something
839  */
840
841 static void handle_incoming_pdu(struct cli_state *cli)
842 {
843         struct cli_request *req;
844         uint16_t mid;
845         size_t raw_pdu_len, buf_len, pdu_len, rest_len;
846         char *pdu;
847         int i;
848         NTSTATUS status;
849
850         int num_async;
851
852         /*
853          * The encrypted PDU len might differ from the unencrypted one
854          */
855         raw_pdu_len = smb_len(cli->evt_inbuf) + 4;
856         buf_len = talloc_get_size(cli->evt_inbuf);
857         rest_len = buf_len - raw_pdu_len;
858
859         if (buf_len == raw_pdu_len) {
860                 /*
861                  * Optimal case: Exactly one PDU was in the socket buffer
862                  */
863                 pdu = cli->evt_inbuf;
864                 cli->evt_inbuf = NULL;
865         }
866         else {
867                 DEBUG(11, ("buf_len = %d, raw_pdu_len = %d, splitting "
868                            "buffer\n", (int)buf_len, (int)raw_pdu_len));
869
870                 if (raw_pdu_len < rest_len) {
871                         /*
872                          * The PDU is shorter, talloc_memdup that one.
873                          */
874                         pdu = (char *)talloc_memdup(
875                                 cli, cli->evt_inbuf, raw_pdu_len);
876
877                         memmove(cli->evt_inbuf, cli->evt_inbuf + raw_pdu_len,
878                                 buf_len - raw_pdu_len);
879
880                         cli->evt_inbuf = TALLOC_REALLOC_ARRAY(
881                                 NULL, cli->evt_inbuf, char, rest_len);
882
883                         if (pdu == NULL) {
884                                 status = NT_STATUS_NO_MEMORY;
885                                 goto invalidate_requests;
886                         }
887                 }
888                 else {
889                         /*
890                          * The PDU is larger than the rest, talloc_memdup the
891                          * rest
892                          */
893                         pdu = cli->evt_inbuf;
894
895                         cli->evt_inbuf = (char *)talloc_memdup(
896                                 cli, pdu + raw_pdu_len, rest_len);
897
898                         if (cli->evt_inbuf == NULL) {
899                                 status = NT_STATUS_NO_MEMORY;
900                                 goto invalidate_requests;
901                         }
902                 }
903         }
904
905         status = validate_smb_crypto(cli, pdu);
906         if (!NT_STATUS_IS_OK(status)) {
907                 goto invalidate_requests;
908         }
909
910         mid = SVAL(pdu, smb_mid);
911
912         DEBUG(10, ("handle_incoming_pdu: got mid %d\n", mid));
913
914         for (req = cli->outstanding_requests; req; req = req->next) {
915                 if (req->mid == mid) {
916                         break;
917                 }
918         }
919
920         pdu_len = smb_len(pdu) + 4;
921
922         if (req == NULL) {
923                 DEBUG(3, ("Request for mid %d not found, dumping PDU\n", mid));
924
925                 TALLOC_FREE(pdu);
926                 return;
927         }
928
929         req->inbuf = talloc_move(req, &pdu);
930
931         /*
932          * Freeing the last async_req will free the req (see
933          * cli_async_req_destructor). So make a copy of req->num_async, we
934          * can't reference it in the last round.
935          */
936
937         num_async = req->num_async;
938
939         for (i=0; i<num_async; i++) {
940                 /**
941                  * A request might have been talloc_free()'ed before we arrive
942                  * here. It will have removed itself from req->async via its
943                  * destructor cli_async_req_destructor().
944                  */
945                 if (req->async[i] != NULL) {
946                         if (req->recv_helper.fn != NULL) {
947                                 req->recv_helper.fn(req->async[i]);
948                         } else {
949                                 async_req_done(req->async[i]);
950                         }
951                 }
952         }
953         return;
954
955  invalidate_requests:
956
957         DEBUG(10, ("handle_incoming_pdu: Aborting with %s\n",
958                    nt_errstr(status)));
959
960         for (req = cli->outstanding_requests; req; req = req->next) {
961                 async_req_error(req->async[0], status);
962         }
963         return;
964 }
965
966 /**
967  * fd event callback. This is the basic connection to the socket
968  * @param[in] event_ctx The event context that called us
969  * @param[in] event     The event that fired
970  * @param[in] flags     EVENT_FD_READ | EVENT_FD_WRITE
971  * @param[in] p         private_data, in this case the cli_state
972  */
973
974 static void cli_state_handler(struct event_context *event_ctx,
975                               struct fd_event *event, uint16 flags, void *p)
976 {
977         struct cli_state *cli = (struct cli_state *)p;
978         struct cli_request *req;
979         NTSTATUS status;
980
981         DEBUG(11, ("cli_state_handler called with flags %d\n", flags));
982
983         if (flags & EVENT_FD_WRITE) {
984                 size_t to_send;
985                 ssize_t sent;
986
987                 for (req = cli->outstanding_requests; req; req = req->next) {
988                         to_send = smb_len(req->outbuf)+4;
989                         if (to_send > req->sent) {
990                                 break;
991                         }
992                 }
993
994                 if (req == NULL) {
995                         if (cli->fd_event != NULL) {
996                                 event_fd_set_not_writeable(cli->fd_event);
997                         }
998                         return;
999                 }
1000
1001                 sent = sys_send(cli->fd, req->outbuf + req->sent,
1002                             to_send - req->sent, 0);
1003
1004                 if (sent < 0) {
1005                         status = map_nt_error_from_unix(errno);
1006                         goto sock_error;
1007                 }
1008
1009                 req->sent += sent;
1010
1011                 if (req->sent == to_send) {
1012                         return;
1013                 }
1014         }
1015
1016         if (flags & EVENT_FD_READ) {
1017                 int res, available;
1018                 size_t old_size, new_size;
1019                 char *tmp;
1020
1021                 res = ioctl(cli->fd, FIONREAD, &available);
1022                 if (res == -1) {
1023                         DEBUG(10, ("ioctl(FIONREAD) failed: %s\n",
1024                                    strerror(errno)));
1025                         status = map_nt_error_from_unix(errno);
1026                         goto sock_error;
1027                 }
1028
1029                 if (available == 0) {
1030                         /* EOF */
1031                         status = NT_STATUS_END_OF_FILE;
1032                         goto sock_error;
1033                 }
1034
1035                 old_size = talloc_get_size(cli->evt_inbuf);
1036                 new_size = old_size + available;
1037
1038                 if (new_size < old_size) {
1039                         /* wrap */
1040                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
1041                         goto sock_error;
1042                 }
1043
1044                 tmp = TALLOC_REALLOC_ARRAY(cli, cli->evt_inbuf, char,
1045                                            new_size);
1046                 if (tmp == NULL) {
1047                         /* nomem */
1048                         status = NT_STATUS_NO_MEMORY;
1049                         goto sock_error;
1050                 }
1051                 cli->evt_inbuf = tmp;
1052
1053                 res = sys_recv(cli->fd, cli->evt_inbuf + old_size, available, 0);
1054                 if (res == -1) {
1055                         DEBUG(10, ("recv failed: %s\n", strerror(errno)));
1056                         status = map_nt_error_from_unix(errno);
1057                         goto sock_error;
1058                 }
1059
1060                 DEBUG(11, ("cli_state_handler: received %d bytes, "
1061                            "smb_len(evt_inbuf) = %d\n", (int)res,
1062                            smb_len(cli->evt_inbuf)));
1063
1064                 /* recv *might* have returned less than announced */
1065                 new_size = old_size + res;
1066
1067                 /* shrink, so I don't expect errors here */
1068                 cli->evt_inbuf = TALLOC_REALLOC_ARRAY(cli, cli->evt_inbuf,
1069                                                       char, new_size);
1070
1071                 while ((cli->evt_inbuf != NULL)
1072                        && ((smb_len(cli->evt_inbuf) + 4) <= new_size)) {
1073                         /*
1074                          * we've got a complete NBT level PDU in evt_inbuf
1075                          */
1076                         handle_incoming_pdu(cli);
1077                         new_size = talloc_get_size(cli->evt_inbuf);
1078                 }
1079         }
1080
1081         return;
1082
1083  sock_error:
1084         for (req = cli->outstanding_requests; req; req = req->next) {
1085                 int i;
1086                 for (i=0; i<req->num_async; i++) {
1087                         async_req_error(req->async[i], status);
1088                 }
1089         }
1090         TALLOC_FREE(cli->fd_event);
1091         close(cli->fd);
1092         cli->fd = -1;
1093 }