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