smbXcli: simplify smb1cli_req_chain_submit()
[kai/samba.git] / libcli / smb / smbXcli_base.c
1 /*
2    Unix SMB/CIFS implementation.
3    Infrastructure for async SMB client requests
4    Copyright (C) Volker Lendecke 2008
5    Copyright (C) Stefan Metzmacher 2011
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "system/network.h"
23 #include "../lib/async_req/async_sock.h"
24 #include "../lib/util/tevent_ntstatus.h"
25 #include "../lib/util/tevent_unix.h"
26 #include "lib/util/util_net.h"
27 #include "../libcli/smb/smb_common.h"
28 #include "../libcli/smb/smb_seal.h"
29 #include "../libcli/smb/smb_signing.h"
30 #include "../libcli/smb/read_smb.h"
31 #include "smbXcli_base.h"
32 #include "librpc/ndr/libndr.h"
33
34 struct smbXcli_conn {
35         int fd;
36         struct sockaddr_storage local_ss;
37         struct sockaddr_storage remote_ss;
38         const char *remote_name;
39
40         struct tevent_queue *outgoing;
41         struct tevent_req **pending;
42         struct tevent_req *read_smb_req;
43
44         enum protocol_types protocol;
45         bool allow_signing;
46         bool desire_signing;
47         bool mandatory_signing;
48
49         /*
50          * The incoming dispatch function should return:
51          * - NT_STATUS_RETRY, if more incoming PDUs are expected.
52          * - NT_STATUS_OK, if no more processing is desired, e.g.
53          *                 the dispatch function called
54          *                 tevent_req_done().
55          * - All other return values disconnect the connection.
56          */
57         NTSTATUS (*dispatch_incoming)(struct smbXcli_conn *conn,
58                                       TALLOC_CTX *tmp_mem,
59                                       uint8_t *inbuf);
60
61         struct {
62                 struct {
63                         uint32_t capabilities;
64                         uint32_t max_xmit;
65                 } client;
66
67                 struct {
68                         uint32_t capabilities;
69                         uint32_t max_xmit;
70                         uint16_t max_mux;
71                         uint16_t security_mode;
72                         bool readbraw;
73                         bool writebraw;
74                         bool lockread;
75                         bool writeunlock;
76                         uint32_t session_key;
77                         struct GUID guid;
78                         DATA_BLOB gss_blob;
79                         uint8_t challenge[8];
80                         const char *workgroup;
81                         int time_zone;
82                         NTTIME system_time;
83                 } server;
84
85                 uint32_t capabilities;
86                 uint32_t max_xmit;
87
88                 uint16_t mid;
89
90                 struct smb_signing_state *signing;
91                 struct smb_trans_enc_state *trans_enc;
92         } smb1;
93
94         struct {
95                 struct {
96                         uint16_t security_mode;
97                 } client;
98
99                 struct {
100                         uint32_t capabilities;
101                         uint16_t security_mode;
102                         struct GUID guid;
103                         uint32_t max_trans_size;
104                         uint32_t max_read_size;
105                         uint32_t max_write_size;
106                         NTTIME system_time;
107                         NTTIME start_time;
108                         DATA_BLOB gss_blob;
109                 } server;
110
111                 uint64_t mid;
112         } smb2;
113 };
114
115 struct smbXcli_req_state {
116         struct tevent_context *ev;
117         struct smbXcli_conn *conn;
118
119         uint8_t length_hdr[4];
120
121         bool one_way;
122
123         uint8_t *inbuf;
124
125         struct {
126                 /* Space for the header including the wct */
127                 uint8_t hdr[HDR_VWV];
128
129                 /*
130                  * For normal requests, smb1cli_req_send chooses a mid.
131                  * SecondaryV trans requests need to use the mid of the primary
132                  * request, so we need a place to store it.
133                  * Assume it is set if != 0.
134                  */
135                 uint16_t mid;
136
137                 uint16_t *vwv;
138                 uint8_t bytecount_buf[2];
139
140 #define MAX_SMB_IOV 5
141                 /* length_hdr, hdr, words, byte_count, buffers */
142                 struct iovec iov[1 + 3 + MAX_SMB_IOV];
143                 int iov_count;
144
145                 uint32_t seqnum;
146                 struct tevent_req **chained_requests;
147
148                 uint8_t recv_cmd;
149                 NTSTATUS recv_status;
150                 /* always an array of 3 talloc elements */
151                 struct iovec *recv_iov;
152         } smb1;
153
154         struct {
155                 const uint8_t *fixed;
156                 uint16_t fixed_len;
157                 const uint8_t *dyn;
158                 uint32_t dyn_len;
159
160                 uint8_t hdr[64];
161                 uint8_t pad[7]; /* padding space for compounding */
162
163                 /* always an array of 3 talloc elements */
164                 struct iovec *recv_iov;
165         } smb2;
166 };
167
168 static int smbXcli_conn_destructor(struct smbXcli_conn *conn)
169 {
170         /*
171          * NT_STATUS_OK, means we do not notify the callers
172          */
173         smbXcli_conn_disconnect(conn, NT_STATUS_OK);
174
175         if (conn->smb1.trans_enc) {
176                 common_free_encryption_state(&conn->smb1.trans_enc);
177         }
178
179         return 0;
180 }
181
182 struct smbXcli_conn *smbXcli_conn_create(TALLOC_CTX *mem_ctx,
183                                          int fd,
184                                          const char *remote_name,
185                                          enum smb_signing_setting signing_state,
186                                          uint32_t smb1_capabilities)
187 {
188         struct smbXcli_conn *conn = NULL;
189         void *ss = NULL;
190         struct sockaddr *sa = NULL;
191         socklen_t sa_length;
192         int ret;
193
194         conn = talloc_zero(mem_ctx, struct smbXcli_conn);
195         if (!conn) {
196                 return NULL;
197         }
198
199         conn->remote_name = talloc_strdup(conn, remote_name);
200         if (conn->remote_name == NULL) {
201                 goto error;
202         }
203
204         conn->fd = fd;
205
206         ss = (void *)&conn->local_ss;
207         sa = (struct sockaddr *)ss;
208         sa_length = sizeof(conn->local_ss);
209         ret = getsockname(fd, sa, &sa_length);
210         if (ret == -1) {
211                 goto error;
212         }
213         ss = (void *)&conn->remote_ss;
214         sa = (struct sockaddr *)ss;
215         sa_length = sizeof(conn->remote_ss);
216         ret = getpeername(fd, sa, &sa_length);
217         if (ret == -1) {
218                 goto error;
219         }
220
221         conn->outgoing = tevent_queue_create(conn, "smbXcli_outgoing");
222         if (conn->outgoing == NULL) {
223                 goto error;
224         }
225         conn->pending = NULL;
226
227         conn->protocol = PROTOCOL_NONE;
228
229         switch (signing_state) {
230         case SMB_SIGNING_OFF:
231                 /* never */
232                 conn->allow_signing = false;
233                 conn->desire_signing = false;
234                 conn->mandatory_signing = false;
235                 break;
236         case SMB_SIGNING_DEFAULT:
237         case SMB_SIGNING_IF_REQUIRED:
238                 /* if the server requires it */
239                 conn->allow_signing = true;
240                 conn->desire_signing = false;
241                 conn->mandatory_signing = false;
242                 break;
243         case SMB_SIGNING_REQUIRED:
244                 /* always */
245                 conn->allow_signing = true;
246                 conn->desire_signing = true;
247                 conn->mandatory_signing = true;
248                 break;
249         }
250
251         conn->smb1.client.capabilities = smb1_capabilities;
252         conn->smb1.client.max_xmit = UINT16_MAX;
253
254         conn->smb1.capabilities = conn->smb1.client.capabilities;
255         conn->smb1.max_xmit = 1024;
256
257         conn->smb1.mid = 1;
258
259         /* initialise signing */
260         conn->smb1.signing = smb_signing_init(conn,
261                                               conn->allow_signing,
262                                               conn->desire_signing,
263                                               conn->mandatory_signing);
264         if (!conn->smb1.signing) {
265                 goto error;
266         }
267
268         conn->smb2.client.security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED;
269         if (conn->mandatory_signing) {
270                 conn->smb2.client.security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED;
271         }
272
273         talloc_set_destructor(conn, smbXcli_conn_destructor);
274         return conn;
275
276  error:
277         TALLOC_FREE(conn);
278         return NULL;
279 }
280
281 bool smbXcli_conn_is_connected(struct smbXcli_conn *conn)
282 {
283         if (conn == NULL) {
284                 return false;
285         }
286
287         if (conn->fd == -1) {
288                 return false;
289         }
290
291         return true;
292 }
293
294 enum protocol_types smbXcli_conn_protocol(struct smbXcli_conn *conn)
295 {
296         return conn->protocol;
297 }
298
299 bool smbXcli_conn_use_unicode(struct smbXcli_conn *conn)
300 {
301         if (conn->protocol >= PROTOCOL_SMB2_02) {
302                 return true;
303         }
304
305         if (conn->smb1.capabilities & CAP_UNICODE) {
306                 return true;
307         }
308
309         return false;
310 }
311
312 void smbXcli_conn_set_sockopt(struct smbXcli_conn *conn, const char *options)
313 {
314         set_socket_options(conn->fd, options);
315 }
316
317 const struct sockaddr_storage *smbXcli_conn_local_sockaddr(struct smbXcli_conn *conn)
318 {
319         return &conn->local_ss;
320 }
321
322 const struct sockaddr_storage *smbXcli_conn_remote_sockaddr(struct smbXcli_conn *conn)
323 {
324         return &conn->remote_ss;
325 }
326
327 const char *smbXcli_conn_remote_name(struct smbXcli_conn *conn)
328 {
329         return conn->remote_name;
330 }
331
332 bool smb1cli_conn_activate_signing(struct smbXcli_conn *conn,
333                                    const DATA_BLOB user_session_key,
334                                    const DATA_BLOB response)
335 {
336         return smb_signing_activate(conn->smb1.signing,
337                                     user_session_key,
338                                     response);
339 }
340
341 bool smb1cli_conn_check_signing(struct smbXcli_conn *conn,
342                                 const uint8_t *buf, uint32_t seqnum)
343 {
344         return smb_signing_check_pdu(conn->smb1.signing, buf, seqnum);
345 }
346
347 bool smb1cli_conn_signing_is_active(struct smbXcli_conn *conn)
348 {
349         return smb_signing_is_active(conn->smb1.signing);
350 }
351
352 void smb1cli_conn_set_encryption(struct smbXcli_conn *conn,
353                                  struct smb_trans_enc_state *es)
354 {
355         /* Replace the old state, if any. */
356         if (conn->smb1.trans_enc) {
357                 common_free_encryption_state(&conn->smb1.trans_enc);
358         }
359         conn->smb1.trans_enc = es;
360 }
361
362 bool smb1cli_conn_encryption_on(struct smbXcli_conn *conn)
363 {
364         return common_encryption_on(conn->smb1.trans_enc);
365 }
366
367
368 static NTSTATUS smb1cli_pull_raw_error(const uint8_t *hdr)
369 {
370         uint32_t flags2 = SVAL(hdr, HDR_FLG2);
371         NTSTATUS status = NT_STATUS(IVAL(hdr, HDR_RCLS));
372
373         if (NT_STATUS_IS_OK(status)) {
374                 return NT_STATUS_OK;
375         }
376
377         if (flags2 & FLAGS2_32_BIT_ERROR_CODES) {
378                 return status;
379         }
380
381         return NT_STATUS_DOS(CVAL(hdr, HDR_RCLS), SVAL(hdr, HDR_ERR));
382 }
383
384 /**
385  * Is the SMB command able to hold an AND_X successor
386  * @param[in] cmd       The SMB command in question
387  * @retval Can we add a chained request after "cmd"?
388  */
389 bool smb1cli_is_andx_req(uint8_t cmd)
390 {
391         switch (cmd) {
392         case SMBtconX:
393         case SMBlockingX:
394         case SMBopenX:
395         case SMBreadX:
396         case SMBwriteX:
397         case SMBsesssetupX:
398         case SMBulogoffX:
399         case SMBntcreateX:
400                 return true;
401                 break;
402         default:
403                 break;
404         }
405
406         return false;
407 }
408
409 static uint16_t smb1cli_alloc_mid(struct smbXcli_conn *conn)
410 {
411         size_t num_pending = talloc_array_length(conn->pending);
412         uint16_t result;
413
414         while (true) {
415                 size_t i;
416
417                 result = conn->smb1.mid++;
418                 if ((result == 0) || (result == 0xffff)) {
419                         continue;
420                 }
421
422                 for (i=0; i<num_pending; i++) {
423                         if (result == smb1cli_req_mid(conn->pending[i])) {
424                                 break;
425                         }
426                 }
427
428                 if (i == num_pending) {
429                         return result;
430                 }
431         }
432 }
433
434 void smbXcli_req_unset_pending(struct tevent_req *req)
435 {
436         struct smbXcli_req_state *state =
437                 tevent_req_data(req,
438                 struct smbXcli_req_state);
439         struct smbXcli_conn *conn = state->conn;
440         size_t num_pending = talloc_array_length(conn->pending);
441         size_t i;
442
443         if (state->smb1.mid != 0) {
444                 /*
445                  * This is a [nt]trans[2] request which waits
446                  * for more than one reply.
447                  */
448                 return;
449         }
450
451         talloc_set_destructor(req, NULL);
452
453         if (num_pending == 1) {
454                 /*
455                  * The pending read_smb tevent_req is a child of
456                  * conn->pending. So if nothing is pending anymore, we need to
457                  * delete the socket read fde.
458                  */
459                 TALLOC_FREE(conn->pending);
460                 conn->read_smb_req = NULL;
461                 return;
462         }
463
464         for (i=0; i<num_pending; i++) {
465                 if (req == conn->pending[i]) {
466                         break;
467                 }
468         }
469         if (i == num_pending) {
470                 /*
471                  * Something's seriously broken. Just returning here is the
472                  * right thing nevertheless, the point of this routine is to
473                  * remove ourselves from conn->pending.
474                  */
475                 return;
476         }
477
478         /*
479          * Remove ourselves from the conn->pending array
480          */
481         for (; i < (num_pending - 1); i++) {
482                 conn->pending[i] = conn->pending[i+1];
483         }
484
485         /*
486          * No NULL check here, we're shrinking by sizeof(void *), and
487          * talloc_realloc just adjusts the size for this.
488          */
489         conn->pending = talloc_realloc(NULL, conn->pending, struct tevent_req *,
490                                        num_pending - 1);
491         return;
492 }
493
494 static int smbXcli_req_destructor(struct tevent_req *req)
495 {
496         struct smbXcli_req_state *state =
497                 tevent_req_data(req,
498                 struct smbXcli_req_state);
499
500         /*
501          * Make sure we really remove it from
502          * the pending array on destruction.
503          */
504         state->smb1.mid = 0;
505         smbXcli_req_unset_pending(req);
506         return 0;
507 }
508
509 static bool smbXcli_conn_receive_next(struct smbXcli_conn *conn);
510
511 bool smbXcli_req_set_pending(struct tevent_req *req)
512 {
513         struct smbXcli_req_state *state =
514                 tevent_req_data(req,
515                 struct smbXcli_req_state);
516         struct smbXcli_conn *conn;
517         struct tevent_req **pending;
518         size_t num_pending;
519
520         conn = state->conn;
521
522         if (!smbXcli_conn_is_connected(conn)) {
523                 return false;
524         }
525
526         num_pending = talloc_array_length(conn->pending);
527
528         pending = talloc_realloc(conn, conn->pending, struct tevent_req *,
529                                  num_pending+1);
530         if (pending == NULL) {
531                 return false;
532         }
533         pending[num_pending] = req;
534         conn->pending = pending;
535         talloc_set_destructor(req, smbXcli_req_destructor);
536
537         if (!smbXcli_conn_receive_next(conn)) {
538                 /*
539                  * the caller should notify the current request
540                  *
541                  * And all other pending requests get notified
542                  * by smbXcli_conn_disconnect().
543                  */
544                 smbXcli_req_unset_pending(req);
545                 smbXcli_conn_disconnect(conn, NT_STATUS_NO_MEMORY);
546                 return false;
547         }
548
549         return true;
550 }
551
552 static void smbXcli_conn_received(struct tevent_req *subreq);
553
554 static bool smbXcli_conn_receive_next(struct smbXcli_conn *conn)
555 {
556         size_t num_pending = talloc_array_length(conn->pending);
557         struct tevent_req *req;
558         struct smbXcli_req_state *state;
559
560         if (conn->read_smb_req != NULL) {
561                 return true;
562         }
563
564         if (num_pending == 0) {
565                 if (conn->smb2.mid < UINT64_MAX) {
566                         /* no more pending requests, so we are done for now */
567                         return true;
568                 }
569
570                 /*
571                  * If there are no more SMB2 requests possible,
572                  * because we are out of message ids,
573                  * we need to disconnect.
574                  */
575                 smbXcli_conn_disconnect(conn, NT_STATUS_CONNECTION_ABORTED);
576                 return true;
577         }
578
579         req = conn->pending[0];
580         state = tevent_req_data(req, struct smbXcli_req_state);
581
582         /*
583          * We're the first ones, add the read_smb request that waits for the
584          * answer from the server
585          */
586         conn->read_smb_req = read_smb_send(conn->pending, state->ev, conn->fd);
587         if (conn->read_smb_req == NULL) {
588                 return false;
589         }
590         tevent_req_set_callback(conn->read_smb_req, smbXcli_conn_received, conn);
591         return true;
592 }
593
594 void smbXcli_conn_disconnect(struct smbXcli_conn *conn, NTSTATUS status)
595 {
596         if (conn->fd != -1) {
597                 close(conn->fd);
598         }
599         conn->fd = -1;
600
601         /*
602          * Cancel all pending requests. We do not do a for-loop walking
603          * conn->pending because that array changes in
604          * smbXcli_req_unset_pending.
605          */
606         while (talloc_array_length(conn->pending) > 0) {
607                 struct tevent_req *req;
608                 struct smbXcli_req_state *state;
609
610                 req = conn->pending[0];
611                 state = tevent_req_data(req, struct smbXcli_req_state);
612
613                 /*
614                  * We're dead. No point waiting for trans2
615                  * replies.
616                  */
617                 state->smb1.mid = 0;
618
619                 smbXcli_req_unset_pending(req);
620
621                 if (NT_STATUS_IS_OK(status)) {
622                         /* do not notify the callers */
623                         continue;
624                 }
625
626                 /*
627                  * we need to defer the callback, because we may notify more
628                  * then one caller.
629                  */
630                 tevent_req_defer_callback(req, state->ev);
631                 tevent_req_nterror(req, status);
632         }
633 }
634
635 /*
636  * Fetch a smb request's mid. Only valid after the request has been sent by
637  * smb1cli_req_send().
638  */
639 uint16_t smb1cli_req_mid(struct tevent_req *req)
640 {
641         struct smbXcli_req_state *state =
642                 tevent_req_data(req,
643                 struct smbXcli_req_state);
644
645         if (state->smb1.mid != 0) {
646                 return state->smb1.mid;
647         }
648
649         return SVAL(state->smb1.hdr, HDR_MID);
650 }
651
652 void smb1cli_req_set_mid(struct tevent_req *req, uint16_t mid)
653 {
654         struct smbXcli_req_state *state =
655                 tevent_req_data(req,
656                 struct smbXcli_req_state);
657
658         state->smb1.mid = mid;
659 }
660
661 uint32_t smb1cli_req_seqnum(struct tevent_req *req)
662 {
663         struct smbXcli_req_state *state =
664                 tevent_req_data(req,
665                 struct smbXcli_req_state);
666
667         return state->smb1.seqnum;
668 }
669
670 void smb1cli_req_set_seqnum(struct tevent_req *req, uint32_t seqnum)
671 {
672         struct smbXcli_req_state *state =
673                 tevent_req_data(req,
674                 struct smbXcli_req_state);
675
676         state->smb1.seqnum = seqnum;
677 }
678
679 static size_t smbXcli_iov_len(const struct iovec *iov, int count)
680 {
681         size_t result = 0;
682         int i;
683         for (i=0; i<count; i++) {
684                 result += iov[i].iov_len;
685         }
686         return result;
687 }
688
689 static uint8_t *smbXcli_iov_concat(TALLOC_CTX *mem_ctx,
690                                    const struct iovec *iov,
691                                    int count)
692 {
693         size_t len = smbXcli_iov_len(iov, count);
694         size_t copied;
695         uint8_t *buf;
696         int i;
697
698         buf = talloc_array(mem_ctx, uint8_t, len);
699         if (buf == NULL) {
700                 return NULL;
701         }
702         copied = 0;
703         for (i=0; i<count; i++) {
704                 memcpy(buf+copied, iov[i].iov_base, iov[i].iov_len);
705                 copied += iov[i].iov_len;
706         }
707         return buf;
708 }
709
710 static void smb1cli_req_flags(enum protocol_types protocol,
711                               uint32_t smb1_capabilities,
712                               uint8_t smb_command,
713                               uint8_t additional_flags,
714                               uint8_t clear_flags,
715                               uint8_t *_flags,
716                               uint16_t additional_flags2,
717                               uint16_t clear_flags2,
718                               uint16_t *_flags2)
719 {
720         uint8_t flags = 0;
721         uint16_t flags2 = 0;
722
723         if (protocol >= PROTOCOL_LANMAN1) {
724                 flags |= FLAG_CASELESS_PATHNAMES;
725                 flags |= FLAG_CANONICAL_PATHNAMES;
726         }
727
728         if (protocol >= PROTOCOL_LANMAN2) {
729                 flags2 |= FLAGS2_LONG_PATH_COMPONENTS;
730                 flags2 |= FLAGS2_EXTENDED_ATTRIBUTES;
731         }
732
733         if (protocol >= PROTOCOL_NT1) {
734                 flags2 |= FLAGS2_IS_LONG_NAME;
735
736                 if (smb1_capabilities & CAP_UNICODE) {
737                         flags2 |= FLAGS2_UNICODE_STRINGS;
738                 }
739                 if (smb1_capabilities & CAP_STATUS32) {
740                         flags2 |= FLAGS2_32_BIT_ERROR_CODES;
741                 }
742                 if (smb1_capabilities & CAP_EXTENDED_SECURITY) {
743                         flags2 |= FLAGS2_EXTENDED_SECURITY;
744                 }
745         }
746
747         flags |= additional_flags;
748         flags &= ~clear_flags;
749         flags2 |= additional_flags2;
750         flags2 &= ~clear_flags2;
751
752         *_flags = flags;
753         *_flags2 = flags2;
754 }
755
756 struct tevent_req *smb1cli_req_create(TALLOC_CTX *mem_ctx,
757                                       struct tevent_context *ev,
758                                       struct smbXcli_conn *conn,
759                                       uint8_t smb_command,
760                                       uint8_t additional_flags,
761                                       uint8_t clear_flags,
762                                       uint16_t additional_flags2,
763                                       uint16_t clear_flags2,
764                                       uint32_t timeout_msec,
765                                       uint32_t pid,
766                                       uint16_t tid,
767                                       uint16_t uid,
768                                       uint8_t wct, uint16_t *vwv,
769                                       int iov_count,
770                                       struct iovec *bytes_iov)
771 {
772         struct tevent_req *req;
773         struct smbXcli_req_state *state;
774         uint8_t flags = 0;
775         uint16_t flags2 = 0;
776
777         if (iov_count > MAX_SMB_IOV) {
778                 /*
779                  * Should not happen :-)
780                  */
781                 return NULL;
782         }
783
784         req = tevent_req_create(mem_ctx, &state,
785                                 struct smbXcli_req_state);
786         if (req == NULL) {
787                 return NULL;
788         }
789         state->ev = ev;
790         state->conn = conn;
791
792         state->smb1.recv_cmd = 0xFF;
793         state->smb1.recv_status = NT_STATUS_INTERNAL_ERROR;
794         state->smb1.recv_iov = talloc_zero_array(state, struct iovec, 3);
795         if (state->smb1.recv_iov == NULL) {
796                 TALLOC_FREE(req);
797                 return NULL;
798         }
799
800         smb1cli_req_flags(conn->protocol,
801                           conn->smb1.capabilities,
802                           smb_command,
803                           additional_flags,
804                           clear_flags,
805                           &flags,
806                           additional_flags2,
807                           clear_flags2,
808                           &flags2);
809
810         SIVAL(state->smb1.hdr, 0,           SMB_MAGIC);
811         SCVAL(state->smb1.hdr, HDR_COM,     smb_command);
812         SIVAL(state->smb1.hdr, HDR_RCLS,    NT_STATUS_V(NT_STATUS_OK));
813         SCVAL(state->smb1.hdr, HDR_FLG,     flags);
814         SSVAL(state->smb1.hdr, HDR_FLG2,    flags2);
815         SSVAL(state->smb1.hdr, HDR_PIDHIGH, pid >> 16);
816         SSVAL(state->smb1.hdr, HDR_TID,     tid);
817         SSVAL(state->smb1.hdr, HDR_PID,     pid);
818         SSVAL(state->smb1.hdr, HDR_UID,     uid);
819         SSVAL(state->smb1.hdr, HDR_MID,     0); /* this comes later */
820         SSVAL(state->smb1.hdr, HDR_WCT,     wct);
821
822         state->smb1.vwv = vwv;
823
824         SSVAL(state->smb1.bytecount_buf, 0, smbXcli_iov_len(bytes_iov, iov_count));
825
826         state->smb1.iov[0].iov_base = (void *)state->length_hdr;
827         state->smb1.iov[0].iov_len  = sizeof(state->length_hdr);
828         state->smb1.iov[1].iov_base = (void *)state->smb1.hdr;
829         state->smb1.iov[1].iov_len  = sizeof(state->smb1.hdr);
830         state->smb1.iov[2].iov_base = (void *)state->smb1.vwv;
831         state->smb1.iov[2].iov_len  = wct * sizeof(uint16_t);
832         state->smb1.iov[3].iov_base = (void *)state->smb1.bytecount_buf;
833         state->smb1.iov[3].iov_len  = sizeof(uint16_t);
834
835         if (iov_count != 0) {
836                 memcpy(&state->smb1.iov[4], bytes_iov,
837                        iov_count * sizeof(*bytes_iov));
838         }
839         state->smb1.iov_count = iov_count + 4;
840
841         if (timeout_msec > 0) {
842                 struct timeval endtime;
843
844                 endtime = timeval_current_ofs_msec(timeout_msec);
845                 if (!tevent_req_set_endtime(req, ev, endtime)) {
846                         return req;
847                 }
848         }
849
850         switch (smb_command) {
851         case SMBtranss:
852         case SMBtranss2:
853         case SMBnttranss:
854         case SMBntcancel:
855                 state->one_way = true;
856                 break;
857         case SMBlockingX:
858                 if ((wct == 8) &&
859                     (CVAL(vwv+3, 0) == LOCKING_ANDX_OPLOCK_RELEASE)) {
860                         state->one_way = true;
861                 }
862                 break;
863         }
864
865         return req;
866 }
867
868 static NTSTATUS smb1cli_conn_signv(struct smbXcli_conn *conn,
869                                    struct iovec *iov, int iov_count,
870                                    uint32_t *seqnum)
871 {
872         uint8_t *buf;
873
874         /*
875          * Obvious optimization: Make cli_calculate_sign_mac work with struct
876          * iovec directly. MD5Update would do that just fine.
877          */
878
879         if (iov_count < 4) {
880                 return NT_STATUS_INVALID_PARAMETER_MIX;
881         }
882         if (iov[0].iov_len != NBT_HDR_SIZE) {
883                 return NT_STATUS_INVALID_PARAMETER_MIX;
884         }
885         if (iov[1].iov_len != (MIN_SMB_SIZE-sizeof(uint16_t))) {
886                 return NT_STATUS_INVALID_PARAMETER_MIX;
887         }
888         if (iov[2].iov_len > (0xFF * sizeof(uint16_t))) {
889                 return NT_STATUS_INVALID_PARAMETER_MIX;
890         }
891         if (iov[3].iov_len != sizeof(uint16_t)) {
892                 return NT_STATUS_INVALID_PARAMETER_MIX;
893         }
894
895         buf = smbXcli_iov_concat(talloc_tos(), iov, iov_count);
896         if (buf == NULL) {
897                 return NT_STATUS_NO_MEMORY;
898         }
899
900         *seqnum = smb_signing_next_seqnum(conn->smb1.signing, false);
901         smb_signing_sign_pdu(conn->smb1.signing, buf, *seqnum);
902         memcpy(iov[1].iov_base, buf+4, iov[1].iov_len);
903
904         TALLOC_FREE(buf);
905         return NT_STATUS_OK;
906 }
907
908 static void smb1cli_req_writev_done(struct tevent_req *subreq);
909 static NTSTATUS smb1cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
910                                                TALLOC_CTX *tmp_mem,
911                                                uint8_t *inbuf);
912
913 static NTSTATUS smb1cli_req_writev_submit(struct tevent_req *req,
914                                           struct smbXcli_req_state *state,
915                                           struct iovec *iov, int iov_count)
916 {
917         struct tevent_req *subreq;
918         NTSTATUS status;
919         uint16_t mid;
920
921         if (!smbXcli_conn_is_connected(state->conn)) {
922                 return NT_STATUS_CONNECTION_DISCONNECTED;
923         }
924
925         if (state->conn->protocol > PROTOCOL_NT1) {
926                 return NT_STATUS_REVISION_MISMATCH;
927         }
928
929         if (iov_count < 4) {
930                 return NT_STATUS_INVALID_PARAMETER_MIX;
931         }
932         if (iov[0].iov_len != NBT_HDR_SIZE) {
933                 return NT_STATUS_INVALID_PARAMETER_MIX;
934         }
935         if (iov[1].iov_len != (MIN_SMB_SIZE-sizeof(uint16_t))) {
936                 return NT_STATUS_INVALID_PARAMETER_MIX;
937         }
938         if (iov[2].iov_len > (0xFF * sizeof(uint16_t))) {
939                 return NT_STATUS_INVALID_PARAMETER_MIX;
940         }
941         if (iov[3].iov_len != sizeof(uint16_t)) {
942                 return NT_STATUS_INVALID_PARAMETER_MIX;
943         }
944
945         if (state->smb1.mid != 0) {
946                 mid = state->smb1.mid;
947         } else {
948                 mid = smb1cli_alloc_mid(state->conn);
949         }
950         SSVAL(iov[1].iov_base, HDR_MID, mid);
951
952         _smb_setlen_nbt(iov[0].iov_base, smbXcli_iov_len(&iov[1], iov_count-1));
953
954         status = smb1cli_conn_signv(state->conn, iov, iov_count,
955                                     &state->smb1.seqnum);
956
957         if (!NT_STATUS_IS_OK(status)) {
958                 return status;
959         }
960
961         /*
962          * If we supported multiple encrytion contexts
963          * here we'd look up based on tid.
964          */
965         if (common_encryption_on(state->conn->smb1.trans_enc)) {
966                 char *buf, *enc_buf;
967
968                 buf = (char *)smbXcli_iov_concat(talloc_tos(), iov, iov_count);
969                 if (buf == NULL) {
970                         return NT_STATUS_NO_MEMORY;
971                 }
972                 status = common_encrypt_buffer(state->conn->smb1.trans_enc,
973                                                (char *)buf, &enc_buf);
974                 TALLOC_FREE(buf);
975                 if (!NT_STATUS_IS_OK(status)) {
976                         DEBUG(0, ("Error in encrypting client message: %s\n",
977                                   nt_errstr(status)));
978                         return status;
979                 }
980                 buf = (char *)talloc_memdup(state, enc_buf,
981                                             smb_len_nbt(enc_buf)+4);
982                 SAFE_FREE(enc_buf);
983                 if (buf == NULL) {
984                         return NT_STATUS_NO_MEMORY;
985                 }
986                 iov[0].iov_base = (void *)buf;
987                 iov[0].iov_len = talloc_get_size(buf);
988                 iov_count = 1;
989         }
990
991         if (state->conn->dispatch_incoming == NULL) {
992                 state->conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
993         }
994
995         subreq = writev_send(state, state->ev, state->conn->outgoing,
996                              state->conn->fd, false, iov, iov_count);
997         if (subreq == NULL) {
998                 return NT_STATUS_NO_MEMORY;
999         }
1000         tevent_req_set_callback(subreq, smb1cli_req_writev_done, req);
1001         return NT_STATUS_OK;
1002 }
1003
1004 struct tevent_req *smb1cli_req_send(TALLOC_CTX *mem_ctx,
1005                                     struct tevent_context *ev,
1006                                     struct smbXcli_conn *conn,
1007                                     uint8_t smb_command,
1008                                     uint8_t additional_flags,
1009                                     uint8_t clear_flags,
1010                                     uint16_t additional_flags2,
1011                                     uint16_t clear_flags2,
1012                                     uint32_t timeout_msec,
1013                                     uint32_t pid,
1014                                     uint16_t tid,
1015                                     uint16_t uid,
1016                                     uint8_t wct, uint16_t *vwv,
1017                                     uint32_t num_bytes,
1018                                     const uint8_t *bytes)
1019 {
1020         struct tevent_req *req;
1021         struct iovec iov;
1022         NTSTATUS status;
1023
1024         iov.iov_base = discard_const_p(void, bytes);
1025         iov.iov_len = num_bytes;
1026
1027         req = smb1cli_req_create(mem_ctx, ev, conn, smb_command,
1028                                  additional_flags, clear_flags,
1029                                  additional_flags2, clear_flags2,
1030                                  timeout_msec,
1031                                  pid, tid, uid,
1032                                  wct, vwv, 1, &iov);
1033         if (req == NULL) {
1034                 return NULL;
1035         }
1036         if (!tevent_req_is_in_progress(req)) {
1037                 return tevent_req_post(req, ev);
1038         }
1039         status = smb1cli_req_chain_submit(&req, 1);
1040         if (tevent_req_nterror(req, status)) {
1041                 return tevent_req_post(req, ev);
1042         }
1043         return req;
1044 }
1045
1046 static void smb1cli_req_writev_done(struct tevent_req *subreq)
1047 {
1048         struct tevent_req *req =
1049                 tevent_req_callback_data(subreq,
1050                 struct tevent_req);
1051         struct smbXcli_req_state *state =
1052                 tevent_req_data(req,
1053                 struct smbXcli_req_state);
1054         ssize_t nwritten;
1055         int err;
1056
1057         nwritten = writev_recv(subreq, &err);
1058         TALLOC_FREE(subreq);
1059         if (nwritten == -1) {
1060                 NTSTATUS status = map_nt_error_from_unix_common(err);
1061                 smbXcli_conn_disconnect(state->conn, status);
1062                 return;
1063         }
1064
1065         if (state->one_way) {
1066                 state->inbuf = NULL;
1067                 tevent_req_done(req);
1068                 return;
1069         }
1070
1071         if (!smbXcli_req_set_pending(req)) {
1072                 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
1073                 return;
1074         }
1075 }
1076
1077 static void smbXcli_conn_received(struct tevent_req *subreq)
1078 {
1079         struct smbXcli_conn *conn =
1080                 tevent_req_callback_data(subreq,
1081                 struct smbXcli_conn);
1082         TALLOC_CTX *frame = talloc_stackframe();
1083         NTSTATUS status;
1084         uint8_t *inbuf;
1085         ssize_t received;
1086         int err;
1087
1088         if (subreq != conn->read_smb_req) {
1089                 DEBUG(1, ("Internal error: cli_smb_received called with "
1090                           "unexpected subreq\n"));
1091                 status = NT_STATUS_INTERNAL_ERROR;
1092                 smbXcli_conn_disconnect(conn, status);
1093                 TALLOC_FREE(frame);
1094                 return;
1095         }
1096         conn->read_smb_req = NULL;
1097
1098         received = read_smb_recv(subreq, frame, &inbuf, &err);
1099         TALLOC_FREE(subreq);
1100         if (received == -1) {
1101                 status = map_nt_error_from_unix_common(err);
1102                 smbXcli_conn_disconnect(conn, status);
1103                 TALLOC_FREE(frame);
1104                 return;
1105         }
1106
1107         status = conn->dispatch_incoming(conn, frame, inbuf);
1108         TALLOC_FREE(frame);
1109         if (NT_STATUS_IS_OK(status)) {
1110                 /*
1111                  * We should not do any more processing
1112                  * as the dispatch function called
1113                  * tevent_req_done().
1114                  */
1115                 return;
1116         } else if (!NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
1117                 /*
1118                  * We got an error, so notify all pending requests
1119                  */
1120                 smbXcli_conn_disconnect(conn, status);
1121                 return;
1122         }
1123
1124         /*
1125          * We got NT_STATUS_RETRY, so we may ask for a
1126          * next incoming pdu.
1127          */
1128         if (!smbXcli_conn_receive_next(conn)) {
1129                 smbXcli_conn_disconnect(conn, NT_STATUS_NO_MEMORY);
1130         }
1131 }
1132
1133 static NTSTATUS smb1cli_inbuf_parse_chain(uint8_t *buf, TALLOC_CTX *mem_ctx,
1134                                           struct iovec **piov, int *pnum_iov)
1135 {
1136         struct iovec *iov;
1137         int num_iov;
1138         size_t buflen;
1139         size_t taken;
1140         size_t remaining;
1141         uint8_t *hdr;
1142         uint8_t cmd;
1143         uint32_t wct_ofs;
1144
1145         buflen = smb_len_nbt(buf);
1146         taken = 0;
1147
1148         hdr = buf + NBT_HDR_SIZE;
1149
1150         if (buflen < MIN_SMB_SIZE) {
1151                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1152         }
1153
1154         /*
1155          * This returns iovec elements in the following order:
1156          *
1157          * - SMB header
1158          *
1159          * - Parameter Block
1160          * - Data Block
1161          *
1162          * - Parameter Block
1163          * - Data Block
1164          *
1165          * - Parameter Block
1166          * - Data Block
1167          */
1168         num_iov = 1;
1169
1170         iov = talloc_array(mem_ctx, struct iovec, num_iov);
1171         if (iov == NULL) {
1172                 return NT_STATUS_NO_MEMORY;
1173         }
1174         iov[0].iov_base = hdr;
1175         iov[0].iov_len = HDR_WCT;
1176         taken += HDR_WCT;
1177
1178         cmd = CVAL(hdr, HDR_COM);
1179         wct_ofs = HDR_WCT;
1180
1181         while (true) {
1182                 size_t len = buflen - taken;
1183                 struct iovec *cur;
1184                 struct iovec *iov_tmp;
1185                 uint8_t wct;
1186                 uint32_t bcc_ofs;
1187                 uint16_t bcc;
1188                 size_t needed;
1189
1190                 /*
1191                  * we need at least WCT and BCC
1192                  */
1193                 needed = sizeof(uint8_t) + sizeof(uint16_t);
1194                 if (len < needed) {
1195                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1196                                    __location__, (int)len, (int)needed));
1197                         goto inval;
1198                 }
1199
1200                 /*
1201                  * Now we check if the specified words are there
1202                  */
1203                 wct = CVAL(hdr, wct_ofs);
1204                 needed += wct * sizeof(uint16_t);
1205                 if (len < needed) {
1206                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1207                                    __location__, (int)len, (int)needed));
1208                         goto inval;
1209                 }
1210
1211                 /*
1212                  * Now we check if the specified bytes are there
1213                  */
1214                 bcc_ofs = wct_ofs + sizeof(uint8_t) + wct * sizeof(uint16_t);
1215                 bcc = SVAL(hdr, bcc_ofs);
1216                 needed += bcc * sizeof(uint8_t);
1217                 if (len < needed) {
1218                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1219                                    __location__, (int)len, (int)needed));
1220                         goto inval;
1221                 }
1222
1223                 /*
1224                  * we allocate 2 iovec structures for words and bytes
1225                  */
1226                 iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
1227                                          num_iov + 2);
1228                 if (iov_tmp == NULL) {
1229                         TALLOC_FREE(iov);
1230                         return NT_STATUS_NO_MEMORY;
1231                 }
1232                 iov = iov_tmp;
1233                 cur = &iov[num_iov];
1234                 num_iov += 2;
1235
1236                 cur[0].iov_len = wct * sizeof(uint16_t);
1237                 cur[0].iov_base = hdr + (wct_ofs + sizeof(uint8_t));
1238                 cur[1].iov_len = bcc * sizeof(uint8_t);
1239                 cur[1].iov_base = hdr + (bcc_ofs + sizeof(uint16_t));
1240
1241                 taken += needed;
1242
1243                 if (!smb1cli_is_andx_req(cmd)) {
1244                         /*
1245                          * If the current command does not have AndX chanining
1246                          * we are done.
1247                          */
1248                         break;
1249                 }
1250
1251                 if (wct == 0 && bcc == 0) {
1252                         /*
1253                          * An empty response also ends the chain,
1254                          * most likely with an error.
1255                          */
1256                         break;
1257                 }
1258
1259                 if (wct < 2) {
1260                         DEBUG(10, ("%s: wct[%d] < 2 for cmd[0x%02X]\n",
1261                                    __location__, (int)wct, (int)cmd));
1262                         goto inval;
1263                 }
1264                 cmd = CVAL(cur[0].iov_base, 0);
1265                 if (cmd == 0xFF) {
1266                         /*
1267                          * If it is the end of the chain we are also done.
1268                          */
1269                         break;
1270                 }
1271                 wct_ofs = SVAL(cur[0].iov_base, 2);
1272
1273                 if (wct_ofs < taken) {
1274                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1275                 }
1276                 if (wct_ofs > buflen) {
1277                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1278                 }
1279
1280                 /*
1281                  * we consumed everything up to the start of the next
1282                  * parameter block.
1283                  */
1284                 taken = wct_ofs;
1285         }
1286
1287         remaining = buflen - taken;
1288
1289         if (remaining > 0 && num_iov >= 3) {
1290                 /*
1291                  * The last DATA block gets the remaining
1292                  * bytes, this is needed to support
1293                  * CAP_LARGE_WRITEX and CAP_LARGE_READX.
1294                  */
1295                 iov[num_iov-1].iov_len += remaining;
1296         }
1297
1298         *piov = iov;
1299         *pnum_iov = num_iov;
1300         return NT_STATUS_OK;
1301
1302 inval:
1303         TALLOC_FREE(iov);
1304         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1305 }
1306
1307 static NTSTATUS smb1cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
1308                                                TALLOC_CTX *tmp_mem,
1309                                                uint8_t *inbuf)
1310 {
1311         struct tevent_req *req;
1312         struct smbXcli_req_state *state;
1313         NTSTATUS status;
1314         size_t num_pending;
1315         size_t i;
1316         uint8_t cmd;
1317         uint16_t mid;
1318         bool oplock_break;
1319         const uint8_t *inhdr = inbuf + NBT_HDR_SIZE;
1320         struct iovec *iov = NULL;
1321         int num_iov = 0;
1322         struct tevent_req **chain = NULL;
1323         size_t num_chained = 0;
1324         size_t num_responses = 0;
1325
1326         if ((IVAL(inhdr, 0) != SMB_MAGIC) /* 0xFF"SMB" */
1327             && (SVAL(inhdr, 0) != 0x45ff)) /* 0xFF"E" */ {
1328                 DEBUG(10, ("Got non-SMB PDU\n"));
1329                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1330         }
1331
1332         /*
1333          * If we supported multiple encrytion contexts
1334          * here we'd look up based on tid.
1335          */
1336         if (common_encryption_on(conn->smb1.trans_enc)
1337             && (CVAL(inbuf, 0) == 0)) {
1338                 uint16_t enc_ctx_num;
1339
1340                 status = get_enc_ctx_num(inbuf, &enc_ctx_num);
1341                 if (!NT_STATUS_IS_OK(status)) {
1342                         DEBUG(10, ("get_enc_ctx_num returned %s\n",
1343                                    nt_errstr(status)));
1344                         return status;
1345                 }
1346
1347                 if (enc_ctx_num != conn->smb1.trans_enc->enc_ctx_num) {
1348                         DEBUG(10, ("wrong enc_ctx %d, expected %d\n",
1349                                    enc_ctx_num,
1350                                    conn->smb1.trans_enc->enc_ctx_num));
1351                         return NT_STATUS_INVALID_HANDLE;
1352                 }
1353
1354                 status = common_decrypt_buffer(conn->smb1.trans_enc,
1355                                                (char *)inbuf);
1356                 if (!NT_STATUS_IS_OK(status)) {
1357                         DEBUG(10, ("common_decrypt_buffer returned %s\n",
1358                                    nt_errstr(status)));
1359                         return status;
1360                 }
1361         }
1362
1363         mid = SVAL(inhdr, HDR_MID);
1364         num_pending = talloc_array_length(conn->pending);
1365
1366         for (i=0; i<num_pending; i++) {
1367                 if (mid == smb1cli_req_mid(conn->pending[i])) {
1368                         break;
1369                 }
1370         }
1371         if (i == num_pending) {
1372                 /* Dump unexpected reply */
1373                 return NT_STATUS_RETRY;
1374         }
1375
1376         oplock_break = false;
1377
1378         if (mid == 0xffff) {
1379                 /*
1380                  * Paranoia checks that this is really an oplock break request.
1381                  */
1382                 oplock_break = (smb_len_nbt(inbuf) == 51); /* hdr + 8 words */
1383                 oplock_break &= ((CVAL(inhdr, HDR_FLG) & FLAG_REPLY) == 0);
1384                 oplock_break &= (CVAL(inhdr, HDR_COM) == SMBlockingX);
1385                 oplock_break &= (SVAL(inhdr, HDR_VWV+VWV(6)) == 0);
1386                 oplock_break &= (SVAL(inhdr, HDR_VWV+VWV(7)) == 0);
1387
1388                 if (!oplock_break) {
1389                         /* Dump unexpected reply */
1390                         return NT_STATUS_RETRY;
1391                 }
1392         }
1393
1394         req = conn->pending[i];
1395         state = tevent_req_data(req, struct smbXcli_req_state);
1396
1397         if (!oplock_break /* oplock breaks are not signed */
1398             && !smb_signing_check_pdu(conn->smb1.signing,
1399                                       inbuf, state->smb1.seqnum+1)) {
1400                 DEBUG(10, ("cli_check_sign_mac failed\n"));
1401                 return NT_STATUS_ACCESS_DENIED;
1402         }
1403
1404         status = smb1cli_inbuf_parse_chain(inbuf, tmp_mem,
1405                                            &iov, &num_iov);
1406         if (!NT_STATUS_IS_OK(status)) {
1407                 DEBUG(10,("smb1cli_inbuf_parse_chain - %s\n",
1408                           nt_errstr(status)));
1409                 return status;
1410         }
1411
1412         cmd = CVAL(inhdr, HDR_COM);
1413         status = smb1cli_pull_raw_error(inhdr);
1414
1415         if (state->smb1.chained_requests == NULL) {
1416                 if (num_iov != 3) {
1417                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1418                 }
1419
1420                 smbXcli_req_unset_pending(req);
1421
1422                 state->smb1.recv_cmd = cmd;
1423                 state->smb1.recv_status = status;
1424                 state->inbuf = talloc_move(state->smb1.recv_iov, &inbuf);
1425
1426                 state->smb1.recv_iov[0] = iov[0];
1427                 state->smb1.recv_iov[1] = iov[1];
1428                 state->smb1.recv_iov[2] = iov[2];
1429
1430                 if (talloc_array_length(conn->pending) == 0) {
1431                         tevent_req_done(req);
1432                         return NT_STATUS_OK;
1433                 }
1434
1435                 tevent_req_defer_callback(req, state->ev);
1436                 tevent_req_done(req);
1437                 return NT_STATUS_RETRY;
1438         }
1439
1440         chain = talloc_move(tmp_mem, &state->smb1.chained_requests);
1441         num_chained = talloc_array_length(chain);
1442         num_responses = (num_iov - 1)/2;
1443
1444         if (num_responses > num_chained) {
1445                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1446         }
1447
1448         for (i=0; i<num_chained; i++) {
1449                 size_t iov_idx = 1 + (i*2);
1450                 struct iovec *cur = &iov[iov_idx];
1451                 uint8_t *inbuf_ref;
1452
1453                 req = chain[i];
1454                 state = tevent_req_data(req, struct smbXcli_req_state);
1455
1456                 smbXcli_req_unset_pending(req);
1457
1458                 /*
1459                  * as we finish multiple requests here
1460                  * we need to defer the callbacks as
1461                  * they could destroy our current stack state.
1462                  */
1463                 tevent_req_defer_callback(req, state->ev);
1464
1465                 if (i >= num_responses) {
1466                         tevent_req_nterror(req, NT_STATUS_REQUEST_ABORTED);
1467                         continue;
1468                 }
1469
1470                 state->smb1.recv_cmd = cmd;
1471
1472                 if (i == (num_responses - 1)) {
1473                         /*
1474                          * The last request in the chain gets the status
1475                          */
1476                         state->smb1.recv_status = status;
1477                 } else {
1478                         cmd = CVAL(cur[0].iov_base, 0);
1479                         state->smb1.recv_status = NT_STATUS_OK;
1480                 }
1481
1482                 state->inbuf = inbuf;
1483
1484                 /*
1485                  * Note: here we use talloc_reference() in a way
1486                  *       that does not expose it to the caller.
1487                  */
1488                 inbuf_ref = talloc_reference(state->smb1.recv_iov, inbuf);
1489                 if (tevent_req_nomem(inbuf_ref, req)) {
1490                         continue;
1491                 }
1492
1493                 /* copy the related buffers */
1494                 state->smb1.recv_iov[0] = iov[0];
1495                 state->smb1.recv_iov[1] = cur[0];
1496                 state->smb1.recv_iov[2] = cur[1];
1497
1498                 tevent_req_done(req);
1499         }
1500
1501         return NT_STATUS_RETRY;
1502 }
1503
1504 NTSTATUS smb1cli_req_recv(struct tevent_req *req,
1505                           TALLOC_CTX *mem_ctx,
1506                           struct iovec **piov,
1507                           uint8_t **phdr,
1508                           uint8_t *pwct,
1509                           uint16_t **pvwv,
1510                           uint32_t *pvwv_offset,
1511                           uint32_t *pnum_bytes,
1512                           uint8_t **pbytes,
1513                           uint32_t *pbytes_offset,
1514                           uint8_t **pinbuf,
1515                           const struct smb1cli_req_expected_response *expected,
1516                           size_t num_expected)
1517 {
1518         struct smbXcli_req_state *state =
1519                 tevent_req_data(req,
1520                 struct smbXcli_req_state);
1521         NTSTATUS status = NT_STATUS_OK;
1522         struct iovec *recv_iov = NULL;
1523         uint8_t *hdr = NULL;
1524         uint8_t wct = 0;
1525         uint32_t vwv_offset = 0;
1526         uint16_t *vwv = NULL;
1527         uint32_t num_bytes = 0;
1528         uint32_t bytes_offset = 0;
1529         uint8_t *bytes = NULL;
1530         size_t i;
1531         bool found_status = false;
1532         bool found_size = false;
1533
1534         if (piov != NULL) {
1535                 *piov = NULL;
1536         }
1537         if (phdr != NULL) {
1538                 *phdr = 0;
1539         }
1540         if (pwct != NULL) {
1541                 *pwct = 0;
1542         }
1543         if (pvwv != NULL) {
1544                 *pvwv = NULL;
1545         }
1546         if (pvwv_offset != NULL) {
1547                 *pvwv_offset = 0;
1548         }
1549         if (pnum_bytes != NULL) {
1550                 *pnum_bytes = 0;
1551         }
1552         if (pbytes != NULL) {
1553                 *pbytes = NULL;
1554         }
1555         if (pbytes_offset != NULL) {
1556                 *pbytes_offset = 0;
1557         }
1558         if (pinbuf != NULL) {
1559                 *pinbuf = NULL;
1560         }
1561
1562         if (state->inbuf != NULL) {
1563                 recv_iov = state->smb1.recv_iov;
1564                 hdr = (uint8_t *)recv_iov[0].iov_base;
1565                 wct = recv_iov[1].iov_len/2;
1566                 vwv = (uint16_t *)recv_iov[1].iov_base;
1567                 vwv_offset = PTR_DIFF(vwv, hdr);
1568                 num_bytes = recv_iov[2].iov_len;
1569                 bytes = (uint8_t *)recv_iov[2].iov_base;
1570                 bytes_offset = PTR_DIFF(bytes, hdr);
1571         }
1572
1573         if (tevent_req_is_nterror(req, &status)) {
1574                 for (i=0; i < num_expected; i++) {
1575                         if (NT_STATUS_EQUAL(status, expected[i].status)) {
1576                                 found_status = true;
1577                                 break;
1578                         }
1579                 }
1580
1581                 if (found_status) {
1582                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
1583                 }
1584
1585                 return status;
1586         }
1587
1588         if (num_expected == 0) {
1589                 found_status = true;
1590                 found_size = true;
1591         }
1592
1593         status = state->smb1.recv_status;
1594
1595         for (i=0; i < num_expected; i++) {
1596                 if (!NT_STATUS_EQUAL(status, expected[i].status)) {
1597                         continue;
1598                 }
1599
1600                 found_status = true;
1601                 if (expected[i].wct == 0) {
1602                         found_size = true;
1603                         break;
1604                 }
1605
1606                 if (expected[i].wct == wct) {
1607                         found_size = true;
1608                         break;
1609                 }
1610         }
1611
1612         if (!found_status) {
1613                 return status;
1614         }
1615
1616         if (!found_size) {
1617                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1618         }
1619
1620         if (piov != NULL) {
1621                 *piov = talloc_move(mem_ctx, &recv_iov);
1622         }
1623
1624         if (phdr != NULL) {
1625                 *phdr = hdr;
1626         }
1627         if (pwct != NULL) {
1628                 *pwct = wct;
1629         }
1630         if (pvwv != NULL) {
1631                 *pvwv = vwv;
1632         }
1633         if (pvwv_offset != NULL) {
1634                 *pvwv_offset = vwv_offset;
1635         }
1636         if (pnum_bytes != NULL) {
1637                 *pnum_bytes = num_bytes;
1638         }
1639         if (pbytes != NULL) {
1640                 *pbytes = bytes;
1641         }
1642         if (pbytes_offset != NULL) {
1643                 *pbytes_offset = bytes_offset;
1644         }
1645         if (pinbuf != NULL) {
1646                 *pinbuf = state->inbuf;
1647         }
1648
1649         return status;
1650 }
1651
1652 size_t smb1cli_req_wct_ofs(struct tevent_req **reqs, int num_reqs)
1653 {
1654         size_t wct_ofs;
1655         int i;
1656
1657         wct_ofs = HDR_WCT;
1658
1659         for (i=0; i<num_reqs; i++) {
1660                 struct smbXcli_req_state *state;
1661                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
1662                 wct_ofs += smbXcli_iov_len(state->smb1.iov+2,
1663                                            state->smb1.iov_count-2);
1664                 wct_ofs = (wct_ofs + 3) & ~3;
1665         }
1666         return wct_ofs;
1667 }
1668
1669 NTSTATUS smb1cli_req_chain_submit(struct tevent_req **reqs, int num_reqs)
1670 {
1671         struct smbXcli_req_state *first_state =
1672                 tevent_req_data(reqs[0],
1673                 struct smbXcli_req_state);
1674         struct smbXcli_req_state *state;
1675         size_t wct_offset;
1676         size_t chain_padding = 0;
1677         int i, iovlen;
1678         struct iovec *iov = NULL;
1679         struct iovec *this_iov;
1680         NTSTATUS status;
1681         size_t nbt_len;
1682
1683         if (num_reqs == 1) {
1684                 return smb1cli_req_writev_submit(reqs[0], first_state,
1685                                                  first_state->smb1.iov,
1686                                                  first_state->smb1.iov_count);
1687         }
1688
1689         iovlen = 0;
1690         for (i=0; i<num_reqs; i++) {
1691                 if (!tevent_req_is_in_progress(reqs[i])) {
1692                         return NT_STATUS_INTERNAL_ERROR;
1693                 }
1694
1695                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
1696
1697                 if (state->smb1.iov_count < 4) {
1698                         return NT_STATUS_INVALID_PARAMETER_MIX;
1699                 }
1700
1701                 if (i == 0) {
1702                         /*
1703                          * The NBT and SMB header
1704                          */
1705                         iovlen += 2;
1706                 } else {
1707                         /*
1708                          * Chain padding
1709                          */
1710                         iovlen += 1;
1711                 }
1712
1713                 /*
1714                  * words and bytes
1715                  */
1716                 iovlen += state->smb1.iov_count - 2;
1717         }
1718
1719         iov = talloc_zero_array(first_state, struct iovec, iovlen);
1720         if (iov == NULL) {
1721                 return NT_STATUS_NO_MEMORY;
1722         }
1723
1724         first_state->smb1.chained_requests = (struct tevent_req **)talloc_memdup(
1725                 first_state, reqs, sizeof(*reqs) * num_reqs);
1726         if (first_state->smb1.chained_requests == NULL) {
1727                 TALLOC_FREE(iov);
1728                 return NT_STATUS_NO_MEMORY;
1729         }
1730
1731         wct_offset = HDR_WCT;
1732         this_iov = iov;
1733
1734         for (i=0; i<num_reqs; i++) {
1735                 size_t next_padding = 0;
1736                 uint16_t *vwv;
1737
1738                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
1739
1740                 if (i < num_reqs-1) {
1741                         if (!smb1cli_is_andx_req(CVAL(state->smb1.hdr, HDR_COM))
1742                             || CVAL(state->smb1.hdr, HDR_WCT) < 2) {
1743                                 TALLOC_FREE(iov);
1744                                 TALLOC_FREE(first_state->smb1.chained_requests);
1745                                 return NT_STATUS_INVALID_PARAMETER_MIX;
1746                         }
1747                 }
1748
1749                 wct_offset += smbXcli_iov_len(state->smb1.iov+2,
1750                                               state->smb1.iov_count-2) + 1;
1751                 if ((wct_offset % 4) != 0) {
1752                         next_padding = 4 - (wct_offset % 4);
1753                 }
1754                 wct_offset += next_padding;
1755                 vwv = state->smb1.vwv;
1756
1757                 if (i < num_reqs-1) {
1758                         struct smbXcli_req_state *next_state =
1759                                 tevent_req_data(reqs[i+1],
1760                                 struct smbXcli_req_state);
1761                         SCVAL(vwv+0, 0, CVAL(next_state->smb1.hdr, HDR_COM));
1762                         SCVAL(vwv+0, 1, 0);
1763                         SSVAL(vwv+1, 0, wct_offset);
1764                 } else if (smb1cli_is_andx_req(CVAL(state->smb1.hdr, HDR_COM))) {
1765                         /* properly end the chain */
1766                         SCVAL(vwv+0, 0, 0xff);
1767                         SCVAL(vwv+0, 1, 0xff);
1768                         SSVAL(vwv+1, 0, 0);
1769                 }
1770
1771                 if (i == 0) {
1772                         /*
1773                          * The NBT and SMB header
1774                          */
1775                         this_iov[0] = state->smb1.iov[0];
1776                         this_iov[1] = state->smb1.iov[1];
1777                         this_iov += 2;
1778                 } else {
1779                         /*
1780                          * This one is a bit subtle. We have to add
1781                          * chain_padding bytes between the requests, and we
1782                          * have to also include the wct field of the
1783                          * subsequent requests. We use the subsequent header
1784                          * for the padding, it contains the wct field in its
1785                          * last byte.
1786                          */
1787                         this_iov[0].iov_len = chain_padding+1;
1788                         this_iov[0].iov_base = (void *)&state->smb1.hdr[
1789                                 sizeof(state->smb1.hdr) - this_iov[0].iov_len];
1790                         memset(this_iov[0].iov_base, 0, this_iov[0].iov_len-1);
1791                         this_iov += 1;
1792                 }
1793
1794                 /*
1795                  * copy the words and bytes
1796                  */
1797                 memcpy(this_iov, state->smb1.iov+2,
1798                        sizeof(struct iovec) * (state->smb1.iov_count-2));
1799                 this_iov += state->smb1.iov_count - 2;
1800                 chain_padding = next_padding;
1801         }
1802
1803         nbt_len = smbXcli_iov_len(&iov[1], iovlen-1);
1804         if (nbt_len > first_state->conn->smb1.max_xmit) {
1805                 TALLOC_FREE(iov);
1806                 TALLOC_FREE(first_state->smb1.chained_requests);
1807                 return NT_STATUS_INVALID_PARAMETER_MIX;
1808         }
1809
1810         status = smb1cli_req_writev_submit(reqs[0], first_state, iov, iovlen);
1811         if (!NT_STATUS_IS_OK(status)) {
1812                 TALLOC_FREE(iov);
1813                 TALLOC_FREE(first_state->smb1.chained_requests);
1814                 return status;
1815         }
1816
1817         return NT_STATUS_OK;
1818 }
1819
1820 bool smbXcli_conn_has_async_calls(struct smbXcli_conn *conn)
1821 {
1822         return ((tevent_queue_length(conn->outgoing) != 0)
1823                 || (talloc_array_length(conn->pending) != 0));
1824 }
1825
1826 struct tevent_req *smb2cli_req_create(TALLOC_CTX *mem_ctx,
1827                                       struct tevent_context *ev,
1828                                       struct smbXcli_conn *conn,
1829                                       uint16_t cmd,
1830                                       uint32_t additional_flags,
1831                                       uint32_t clear_flags,
1832                                       uint32_t timeout_msec,
1833                                       uint32_t pid,
1834                                       uint32_t tid,
1835                                       uint64_t uid,
1836                                       const uint8_t *fixed,
1837                                       uint16_t fixed_len,
1838                                       const uint8_t *dyn,
1839                                       uint32_t dyn_len)
1840 {
1841         struct tevent_req *req;
1842         struct smbXcli_req_state *state;
1843         uint32_t flags = 0;
1844
1845         req = tevent_req_create(mem_ctx, &state,
1846                                 struct smbXcli_req_state);
1847         if (req == NULL) {
1848                 return NULL;
1849         }
1850
1851         state->ev = ev;
1852         state->conn = conn;
1853
1854         state->smb2.recv_iov = talloc_zero_array(state, struct iovec, 3);
1855         if (state->smb2.recv_iov == NULL) {
1856                 TALLOC_FREE(req);
1857                 return NULL;
1858         }
1859
1860         flags |= additional_flags;
1861         flags &= ~clear_flags;
1862
1863         state->smb2.fixed = fixed;
1864         state->smb2.fixed_len = fixed_len;
1865         state->smb2.dyn = dyn;
1866         state->smb2.dyn_len = dyn_len;
1867
1868         SIVAL(state->smb2.hdr, SMB2_HDR_PROTOCOL_ID,    SMB2_MAGIC);
1869         SSVAL(state->smb2.hdr, SMB2_HDR_LENGTH,         SMB2_HDR_BODY);
1870         SSVAL(state->smb2.hdr, SMB2_HDR_CREDIT_CHARGE,  1);
1871         SIVAL(state->smb2.hdr, SMB2_HDR_STATUS,         NT_STATUS_V(NT_STATUS_OK));
1872         SSVAL(state->smb2.hdr, SMB2_HDR_OPCODE,         cmd);
1873         SSVAL(state->smb2.hdr, SMB2_HDR_CREDIT,         31);
1874         SIVAL(state->smb2.hdr, SMB2_HDR_FLAGS,          flags);
1875         SIVAL(state->smb2.hdr, SMB2_HDR_PID,            pid);
1876         SIVAL(state->smb2.hdr, SMB2_HDR_TID,            tid);
1877         SBVAL(state->smb2.hdr, SMB2_HDR_SESSION_ID,     uid);
1878
1879         switch (cmd) {
1880         case SMB2_OP_CANCEL:
1881                 state->one_way = true;
1882                 break;
1883         case SMB2_OP_BREAK:
1884                 /*
1885                  * If this is a dummy request, it will have
1886                  * UINT64_MAX as message id.
1887                  * If we send on break acknowledgement,
1888                  * this gets overwritten later.
1889                  */
1890                 SBVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID, UINT64_MAX);
1891                 break;
1892         }
1893
1894         if (timeout_msec > 0) {
1895                 struct timeval endtime;
1896
1897                 endtime = timeval_current_ofs_msec(timeout_msec);
1898                 if (!tevent_req_set_endtime(req, ev, endtime)) {
1899                         return req;
1900                 }
1901         }
1902
1903         return req;
1904 }
1905
1906 static void smb2cli_writev_done(struct tevent_req *subreq);
1907 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
1908                                                TALLOC_CTX *tmp_mem,
1909                                                uint8_t *inbuf);
1910
1911 NTSTATUS smb2cli_req_compound_submit(struct tevent_req **reqs,
1912                                      int num_reqs)
1913 {
1914         struct smbXcli_req_state *state;
1915         struct tevent_req *subreq;
1916         struct iovec *iov;
1917         int i, num_iov, nbt_len;
1918
1919         /*
1920          * 1 for the nbt length
1921          * per request: HDR, fixed, dyn, padding
1922          * -1 because the last one does not need padding
1923          */
1924
1925         iov = talloc_array(reqs[0], struct iovec, 1 + 4*num_reqs - 1);
1926         if (iov == NULL) {
1927                 return NT_STATUS_NO_MEMORY;
1928         }
1929
1930         num_iov = 1;
1931         nbt_len = 0;
1932
1933         for (i=0; i<num_reqs; i++) {
1934                 size_t reqlen;
1935                 bool ret;
1936                 uint64_t mid;
1937
1938                 if (!tevent_req_is_in_progress(reqs[i])) {
1939                         return NT_STATUS_INTERNAL_ERROR;
1940                 }
1941
1942                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
1943
1944                 if (!smbXcli_conn_is_connected(state->conn)) {
1945                         return NT_STATUS_CONNECTION_DISCONNECTED;
1946                 }
1947
1948                 if ((state->conn->protocol != PROTOCOL_NONE) &&
1949                     (state->conn->protocol < PROTOCOL_SMB2_02)) {
1950                         return NT_STATUS_REVISION_MISMATCH;
1951                 }
1952
1953                 if (state->conn->smb2.mid == UINT64_MAX) {
1954                         return NT_STATUS_CONNECTION_ABORTED;
1955                 }
1956
1957                 mid = state->conn->smb2.mid;
1958                 state->conn->smb2.mid += 1;
1959
1960                 SBVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID, mid);
1961
1962                 iov[num_iov].iov_base = state->smb2.hdr;
1963                 iov[num_iov].iov_len  = sizeof(state->smb2.hdr);
1964                 num_iov += 1;
1965
1966                 iov[num_iov].iov_base = discard_const(state->smb2.fixed);
1967                 iov[num_iov].iov_len  = state->smb2.fixed_len;
1968                 num_iov += 1;
1969
1970                 if (state->smb2.dyn != NULL) {
1971                         iov[num_iov].iov_base = discard_const(state->smb2.dyn);
1972                         iov[num_iov].iov_len  = state->smb2.dyn_len;
1973                         num_iov += 1;
1974                 }
1975
1976                 reqlen  = sizeof(state->smb2.hdr);
1977                 reqlen += state->smb2.fixed_len;
1978                 reqlen += state->smb2.dyn_len;
1979
1980                 if (i < num_reqs-1) {
1981                         if ((reqlen % 8) > 0) {
1982                                 uint8_t pad = 8 - (reqlen % 8);
1983                                 iov[num_iov].iov_base = state->smb2.pad;
1984                                 iov[num_iov].iov_len = pad;
1985                                 num_iov += 1;
1986                                 reqlen += pad;
1987                         }
1988                         SIVAL(state->smb2.hdr, SMB2_HDR_NEXT_COMMAND, reqlen);
1989                 }
1990                 nbt_len += reqlen;
1991
1992                 ret = smbXcli_req_set_pending(reqs[i]);
1993                 if (!ret) {
1994                         return NT_STATUS_NO_MEMORY;
1995                 }
1996         }
1997
1998         /*
1999          * TODO: Do signing here
2000          */
2001
2002         state = tevent_req_data(reqs[0], struct smbXcli_req_state);
2003         _smb_setlen_tcp(state->length_hdr, nbt_len);
2004         iov[0].iov_base = state->length_hdr;
2005         iov[0].iov_len  = sizeof(state->length_hdr);
2006
2007         if (state->conn->dispatch_incoming == NULL) {
2008                 state->conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
2009         }
2010
2011         subreq = writev_send(state, state->ev, state->conn->outgoing,
2012                              state->conn->fd, false, iov, num_iov);
2013         if (subreq == NULL) {
2014                 return NT_STATUS_NO_MEMORY;
2015         }
2016         tevent_req_set_callback(subreq, smb2cli_writev_done, reqs[0]);
2017         return NT_STATUS_OK;
2018 }
2019
2020 struct tevent_req *smb2cli_req_send(TALLOC_CTX *mem_ctx,
2021                                     struct tevent_context *ev,
2022                                     struct smbXcli_conn *conn,
2023                                     uint16_t cmd,
2024                                     uint32_t additional_flags,
2025                                     uint32_t clear_flags,
2026                                     uint32_t timeout_msec,
2027                                     uint32_t pid,
2028                                     uint32_t tid,
2029                                     uint64_t uid,
2030                                     const uint8_t *fixed,
2031                                     uint16_t fixed_len,
2032                                     const uint8_t *dyn,
2033                                     uint32_t dyn_len)
2034 {
2035         struct tevent_req *req;
2036         NTSTATUS status;
2037
2038         req = smb2cli_req_create(mem_ctx, ev, conn, cmd,
2039                                  additional_flags, clear_flags,
2040                                  timeout_msec,
2041                                  pid, tid, uid,
2042                                  fixed, fixed_len, dyn, dyn_len);
2043         if (req == NULL) {
2044                 return NULL;
2045         }
2046         if (!tevent_req_is_in_progress(req)) {
2047                 return tevent_req_post(req, ev);
2048         }
2049         status = smb2cli_req_compound_submit(&req, 1);
2050         if (tevent_req_nterror(req, status)) {
2051                 return tevent_req_post(req, ev);
2052         }
2053         return req;
2054 }
2055
2056 static void smb2cli_writev_done(struct tevent_req *subreq)
2057 {
2058         struct tevent_req *req =
2059                 tevent_req_callback_data(subreq,
2060                 struct tevent_req);
2061         struct smbXcli_req_state *state =
2062                 tevent_req_data(req,
2063                 struct smbXcli_req_state);
2064         ssize_t nwritten;
2065         int err;
2066
2067         nwritten = writev_recv(subreq, &err);
2068         TALLOC_FREE(subreq);
2069         if (nwritten == -1) {
2070                 /* here, we need to notify all pending requests */
2071                 NTSTATUS status = map_nt_error_from_unix_common(err);
2072                 smbXcli_conn_disconnect(state->conn, status);
2073                 return;
2074         }
2075 }
2076
2077 static NTSTATUS smb2cli_inbuf_parse_compound(uint8_t *buf, TALLOC_CTX *mem_ctx,
2078                                              struct iovec **piov, int *pnum_iov)
2079 {
2080         struct iovec *iov;
2081         int num_iov;
2082         size_t buflen;
2083         size_t taken;
2084         uint8_t *first_hdr;
2085
2086         num_iov = 0;
2087
2088         iov = talloc_array(mem_ctx, struct iovec, num_iov);
2089         if (iov == NULL) {
2090                 return NT_STATUS_NO_MEMORY;
2091         }
2092
2093         buflen = smb_len_tcp(buf);
2094         taken = 0;
2095         first_hdr = buf + NBT_HDR_SIZE;
2096
2097         while (taken < buflen) {
2098                 size_t len = buflen - taken;
2099                 uint8_t *hdr = first_hdr + taken;
2100                 struct iovec *cur;
2101                 size_t full_size;
2102                 size_t next_command_ofs;
2103                 uint16_t body_size;
2104                 struct iovec *iov_tmp;
2105
2106                 /*
2107                  * We need the header plus the body length field
2108                  */
2109
2110                 if (len < SMB2_HDR_BODY + 2) {
2111                         DEBUG(10, ("%d bytes left, expected at least %d\n",
2112                                    (int)len, SMB2_HDR_BODY));
2113                         goto inval;
2114                 }
2115                 if (IVAL(hdr, 0) != SMB2_MAGIC) {
2116                         DEBUG(10, ("Got non-SMB2 PDU: %x\n",
2117                                    IVAL(hdr, 0)));
2118                         goto inval;
2119                 }
2120                 if (SVAL(hdr, 4) != SMB2_HDR_BODY) {
2121                         DEBUG(10, ("Got HDR len %d, expected %d\n",
2122                                    SVAL(hdr, 4), SMB2_HDR_BODY));
2123                         goto inval;
2124                 }
2125
2126                 full_size = len;
2127                 next_command_ofs = IVAL(hdr, SMB2_HDR_NEXT_COMMAND);
2128                 body_size = SVAL(hdr, SMB2_HDR_BODY);
2129
2130                 if (next_command_ofs != 0) {
2131                         if (next_command_ofs < (SMB2_HDR_BODY + 2)) {
2132                                 goto inval;
2133                         }
2134                         if (next_command_ofs > full_size) {
2135                                 goto inval;
2136                         }
2137                         full_size = next_command_ofs;
2138                 }
2139                 if (body_size < 2) {
2140                         goto inval;
2141                 }
2142                 body_size &= 0xfffe;
2143
2144                 if (body_size > (full_size - SMB2_HDR_BODY)) {
2145                         goto inval;
2146                 }
2147
2148                 iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
2149                                          num_iov + 3);
2150                 if (iov_tmp == NULL) {
2151                         TALLOC_FREE(iov);
2152                         return NT_STATUS_NO_MEMORY;
2153                 }
2154                 iov = iov_tmp;
2155                 cur = &iov[num_iov];
2156                 num_iov += 3;
2157
2158                 cur[0].iov_base = hdr;
2159                 cur[0].iov_len  = SMB2_HDR_BODY;
2160                 cur[1].iov_base = hdr + SMB2_HDR_BODY;
2161                 cur[1].iov_len  = body_size;
2162                 cur[2].iov_base = hdr + SMB2_HDR_BODY + body_size;
2163                 cur[2].iov_len  = full_size - (SMB2_HDR_BODY + body_size);
2164
2165                 taken += full_size;
2166         }
2167
2168         *piov = iov;
2169         *pnum_iov = num_iov;
2170         return NT_STATUS_OK;
2171
2172 inval:
2173         TALLOC_FREE(iov);
2174         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2175 }
2176
2177 static struct tevent_req *smb2cli_conn_find_pending(struct smbXcli_conn *conn,
2178                                                     uint64_t mid)
2179 {
2180         size_t num_pending = talloc_array_length(conn->pending);
2181         size_t i;
2182
2183         for (i=0; i<num_pending; i++) {
2184                 struct tevent_req *req = conn->pending[i];
2185                 struct smbXcli_req_state *state =
2186                         tevent_req_data(req,
2187                         struct smbXcli_req_state);
2188
2189                 if (mid == BVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID)) {
2190                         return req;
2191                 }
2192         }
2193         return NULL;
2194 }
2195
2196 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
2197                                                TALLOC_CTX *tmp_mem,
2198                                                uint8_t *inbuf)
2199 {
2200         struct tevent_req *req;
2201         struct smbXcli_req_state *state = NULL;
2202         struct iovec *iov;
2203         int i, num_iov;
2204         NTSTATUS status;
2205         bool defer = true;
2206
2207         status = smb2cli_inbuf_parse_compound(inbuf, tmp_mem,
2208                                               &iov, &num_iov);
2209         if (!NT_STATUS_IS_OK(status)) {
2210                 return status;
2211         }
2212
2213         for (i=0; i<num_iov; i+=3) {
2214                 uint8_t *inbuf_ref = NULL;
2215                 struct iovec *cur = &iov[i];
2216                 uint8_t *inhdr = (uint8_t *)cur[0].iov_base;
2217                 uint16_t opcode = SVAL(inhdr, SMB2_HDR_OPCODE);
2218                 uint32_t flags = IVAL(inhdr, SMB2_HDR_FLAGS);
2219                 uint64_t mid = BVAL(inhdr, SMB2_HDR_MESSAGE_ID);
2220                 uint16_t req_opcode;
2221
2222                 req = smb2cli_conn_find_pending(conn, mid);
2223                 if (req == NULL) {
2224                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2225                 }
2226                 state = tevent_req_data(req, struct smbXcli_req_state);
2227
2228                 req_opcode = SVAL(state->smb2.hdr, SMB2_HDR_OPCODE);
2229                 if (opcode != req_opcode) {
2230                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2231                 }
2232
2233                 if (!(flags & SMB2_HDR_FLAG_REDIRECT)) {
2234                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2235                 }
2236
2237                 status = NT_STATUS(IVAL(inhdr, SMB2_HDR_STATUS));
2238                 if ((flags & SMB2_HDR_FLAG_ASYNC) &&
2239                     NT_STATUS_EQUAL(status, STATUS_PENDING)) {
2240                         uint32_t req_flags = IVAL(state->smb2.hdr, SMB2_HDR_FLAGS);
2241                         uint64_t async_id = BVAL(inhdr, SMB2_HDR_ASYNC_ID);
2242
2243                         req_flags |= SMB2_HDR_FLAG_ASYNC;
2244                         SBVAL(state->smb2.hdr, SMB2_HDR_FLAGS, req_flags);
2245                         SBVAL(state->smb2.hdr, SMB2_HDR_ASYNC_ID, async_id);
2246                         continue;
2247                 }
2248
2249                 smbXcli_req_unset_pending(req);
2250
2251                 /*
2252                  * There might be more than one response
2253                  * we need to defer the notifications
2254                  */
2255                 if ((num_iov == 4) && (talloc_array_length(conn->pending) == 0)) {
2256                         defer = false;
2257                 }
2258
2259                 if (defer) {
2260                         tevent_req_defer_callback(req, state->ev);
2261                 }
2262
2263                 /*
2264                  * Note: here we use talloc_reference() in a way
2265                  *       that does not expose it to the caller.
2266                  */
2267                 inbuf_ref = talloc_reference(state->smb2.recv_iov, inbuf);
2268                 if (tevent_req_nomem(inbuf_ref, req)) {
2269                         continue;
2270                 }
2271
2272                 /* copy the related buffers */
2273                 state->smb2.recv_iov[0] = cur[0];
2274                 state->smb2.recv_iov[1] = cur[1];
2275                 state->smb2.recv_iov[2] = cur[2];
2276
2277                 tevent_req_done(req);
2278         }
2279
2280         if (defer) {
2281                 return NT_STATUS_RETRY;
2282         }
2283
2284         return NT_STATUS_OK;
2285 }
2286
2287 NTSTATUS smb2cli_req_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
2288                           struct iovec **piov,
2289                           const struct smb2cli_req_expected_response *expected,
2290                           size_t num_expected)
2291 {
2292         struct smbXcli_req_state *state =
2293                 tevent_req_data(req,
2294                 struct smbXcli_req_state);
2295         NTSTATUS status;
2296         size_t body_size;
2297         bool found_status = false;
2298         bool found_size = false;
2299         size_t i;
2300
2301         if (piov != NULL) {
2302                 *piov = NULL;
2303         }
2304
2305         if (tevent_req_is_nterror(req, &status)) {
2306                 for (i=0; i < num_expected; i++) {
2307                         if (NT_STATUS_EQUAL(status, expected[i].status)) {
2308                                 found_status = true;
2309                                 break;
2310                         }
2311                 }
2312
2313                 if (found_status) {
2314                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
2315                 }
2316
2317                 return status;
2318         }
2319
2320         if (num_expected == 0) {
2321                 found_status = true;
2322                 found_size = true;
2323         }
2324
2325         status = NT_STATUS(IVAL(state->smb2.recv_iov[0].iov_base, SMB2_HDR_STATUS));
2326         body_size = SVAL(state->smb2.recv_iov[1].iov_base, 0);
2327
2328         for (i=0; i < num_expected; i++) {
2329                 if (!NT_STATUS_EQUAL(status, expected[i].status)) {
2330                         continue;
2331                 }
2332
2333                 found_status = true;
2334                 if (expected[i].body_size == 0) {
2335                         found_size = true;
2336                         break;
2337                 }
2338
2339                 if (expected[i].body_size == body_size) {
2340                         found_size = true;
2341                         break;
2342                 }
2343         }
2344
2345         if (!found_status) {
2346                 return status;
2347         }
2348
2349         if (!found_size) {
2350                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2351         }
2352
2353         if (piov != NULL) {
2354                 *piov = talloc_move(mem_ctx, &state->smb2.recv_iov);
2355         }
2356
2357         return status;
2358 }