aad999d737a065ff18667e61c88dae4313c5862f
[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 "lib/util/dlinklist.h"
28 #include "../libcli/smb/smb_common.h"
29 #include "../libcli/smb/smb_seal.h"
30 #include "../libcli/smb/smb_signing.h"
31 #include "../libcli/smb/read_smb.h"
32 #include "smbXcli_base.h"
33 #include "librpc/ndr/libndr.h"
34
35 struct smbXcli_conn;
36 struct smbXcli_req;
37 struct smbXcli_session;
38
39 struct smbXcli_conn {
40         int read_fd;
41         int write_fd;
42         struct sockaddr_storage local_ss;
43         struct sockaddr_storage remote_ss;
44         const char *remote_name;
45
46         struct tevent_queue *outgoing;
47         struct tevent_req **pending;
48         struct tevent_req *read_smb_req;
49
50         enum protocol_types protocol;
51         bool allow_signing;
52         bool desire_signing;
53         bool mandatory_signing;
54
55         /*
56          * The incoming dispatch function should return:
57          * - NT_STATUS_RETRY, if more incoming PDUs are expected.
58          * - NT_STATUS_OK, if no more processing is desired, e.g.
59          *                 the dispatch function called
60          *                 tevent_req_done().
61          * - All other return values disconnect the connection.
62          */
63         NTSTATUS (*dispatch_incoming)(struct smbXcli_conn *conn,
64                                       TALLOC_CTX *tmp_mem,
65                                       uint8_t *inbuf);
66
67         struct {
68                 struct {
69                         uint32_t capabilities;
70                         uint32_t max_xmit;
71                 } client;
72
73                 struct {
74                         uint32_t capabilities;
75                         uint32_t max_xmit;
76                         uint16_t max_mux;
77                         uint16_t security_mode;
78                         bool readbraw;
79                         bool writebraw;
80                         bool lockread;
81                         bool writeunlock;
82                         uint32_t session_key;
83                         struct GUID guid;
84                         DATA_BLOB gss_blob;
85                         uint8_t challenge[8];
86                         const char *workgroup;
87                         const char *name;
88                         int time_zone;
89                         NTTIME system_time;
90                 } server;
91
92                 uint32_t capabilities;
93                 uint32_t max_xmit;
94
95                 uint16_t mid;
96
97                 struct smb_signing_state *signing;
98                 struct smb_trans_enc_state *trans_enc;
99
100                 struct tevent_req *read_braw_req;
101         } smb1;
102
103         struct {
104                 struct {
105                         uint32_t capabilities;
106                         uint16_t security_mode;
107                         struct GUID guid;
108                 } client;
109
110                 struct {
111                         uint32_t capabilities;
112                         uint16_t security_mode;
113                         struct GUID guid;
114                         uint32_t max_trans_size;
115                         uint32_t max_read_size;
116                         uint32_t max_write_size;
117                         NTTIME system_time;
118                         NTTIME start_time;
119                         DATA_BLOB gss_blob;
120                 } server;
121
122                 uint64_t mid;
123                 uint16_t cur_credits;
124                 uint16_t max_credits;
125         } smb2;
126
127         struct smbXcli_session *sessions;
128 };
129
130 struct smbXcli_session {
131         struct smbXcli_session *prev, *next;
132         struct smbXcli_conn *conn;
133
134         struct {
135                 uint64_t session_id;
136                 uint16_t session_flags;
137                 DATA_BLOB application_key;
138                 DATA_BLOB signing_key;
139                 bool should_sign;
140                 DATA_BLOB channel_signing_key;
141         } smb2;
142 };
143
144 struct smbXcli_req_state {
145         struct tevent_context *ev;
146         struct smbXcli_conn *conn;
147         struct smbXcli_session *session; /* maybe NULL */
148
149         uint8_t length_hdr[4];
150
151         bool one_way;
152
153         uint8_t *inbuf;
154
155         struct {
156                 /* Space for the header including the wct */
157                 uint8_t hdr[HDR_VWV];
158
159                 /*
160                  * For normal requests, smb1cli_req_send chooses a mid.
161                  * SecondaryV trans requests need to use the mid of the primary
162                  * request, so we need a place to store it.
163                  * Assume it is set if != 0.
164                  */
165                 uint16_t mid;
166
167                 uint16_t *vwv;
168                 uint8_t bytecount_buf[2];
169
170 #define MAX_SMB_IOV 10
171                 /* length_hdr, hdr, words, byte_count, buffers */
172                 struct iovec iov[1 + 3 + MAX_SMB_IOV];
173                 int iov_count;
174
175                 bool one_way_seqnum;
176                 uint32_t seqnum;
177                 struct tevent_req **chained_requests;
178
179                 uint8_t recv_cmd;
180                 NTSTATUS recv_status;
181                 /* always an array of 3 talloc elements */
182                 struct iovec *recv_iov;
183         } smb1;
184
185         struct {
186                 const uint8_t *fixed;
187                 uint16_t fixed_len;
188                 const uint8_t *dyn;
189                 uint32_t dyn_len;
190
191                 uint8_t hdr[64];
192                 uint8_t pad[7]; /* padding space for compounding */
193
194                 /* always an array of 3 talloc elements */
195                 struct iovec *recv_iov;
196
197                 uint16_t credit_charge;
198
199                 bool signing_skipped;
200                 bool notify_async;
201                 bool got_async;
202         } smb2;
203 };
204
205 static int smbXcli_conn_destructor(struct smbXcli_conn *conn)
206 {
207         /*
208          * NT_STATUS_OK, means we do not notify the callers
209          */
210         smbXcli_conn_disconnect(conn, NT_STATUS_OK);
211
212         while (conn->sessions) {
213                 conn->sessions->conn = NULL;
214                 DLIST_REMOVE(conn->sessions, conn->sessions);
215         }
216
217         if (conn->smb1.trans_enc) {
218                 TALLOC_FREE(conn->smb1.trans_enc);
219         }
220
221         return 0;
222 }
223
224 struct smbXcli_conn *smbXcli_conn_create(TALLOC_CTX *mem_ctx,
225                                          int fd,
226                                          const char *remote_name,
227                                          enum smb_signing_setting signing_state,
228                                          uint32_t smb1_capabilities,
229                                          struct GUID *client_guid,
230                                          uint32_t smb2_capabilities)
231 {
232         struct smbXcli_conn *conn = NULL;
233         void *ss = NULL;
234         struct sockaddr *sa = NULL;
235         socklen_t sa_length;
236         int ret;
237
238         conn = talloc_zero(mem_ctx, struct smbXcli_conn);
239         if (!conn) {
240                 return NULL;
241         }
242
243         conn->read_fd = fd;
244         conn->write_fd = dup(fd);
245         if (conn->write_fd == -1) {
246                 goto error;
247         }
248
249         conn->remote_name = talloc_strdup(conn, remote_name);
250         if (conn->remote_name == NULL) {
251                 goto error;
252         }
253
254
255         ss = (void *)&conn->local_ss;
256         sa = (struct sockaddr *)ss;
257         sa_length = sizeof(conn->local_ss);
258         ret = getsockname(fd, sa, &sa_length);
259         if (ret == -1) {
260                 goto error;
261         }
262         ss = (void *)&conn->remote_ss;
263         sa = (struct sockaddr *)ss;
264         sa_length = sizeof(conn->remote_ss);
265         ret = getpeername(fd, sa, &sa_length);
266         if (ret == -1) {
267                 goto error;
268         }
269
270         conn->outgoing = tevent_queue_create(conn, "smbXcli_outgoing");
271         if (conn->outgoing == NULL) {
272                 goto error;
273         }
274         conn->pending = NULL;
275
276         conn->protocol = PROTOCOL_NONE;
277
278         switch (signing_state) {
279         case SMB_SIGNING_OFF:
280                 /* never */
281                 conn->allow_signing = false;
282                 conn->desire_signing = false;
283                 conn->mandatory_signing = false;
284                 break;
285         case SMB_SIGNING_DEFAULT:
286         case SMB_SIGNING_IF_REQUIRED:
287                 /* if the server requires it */
288                 conn->allow_signing = true;
289                 conn->desire_signing = false;
290                 conn->mandatory_signing = false;
291                 break;
292         case SMB_SIGNING_REQUIRED:
293                 /* always */
294                 conn->allow_signing = true;
295                 conn->desire_signing = true;
296                 conn->mandatory_signing = true;
297                 break;
298         }
299
300         conn->smb1.client.capabilities = smb1_capabilities;
301         conn->smb1.client.max_xmit = UINT16_MAX;
302
303         conn->smb1.capabilities = conn->smb1.client.capabilities;
304         conn->smb1.max_xmit = 1024;
305
306         conn->smb1.mid = 1;
307
308         /* initialise signing */
309         conn->smb1.signing = smb_signing_init(conn,
310                                               conn->allow_signing,
311                                               conn->desire_signing,
312                                               conn->mandatory_signing);
313         if (!conn->smb1.signing) {
314                 goto error;
315         }
316
317         conn->smb2.client.security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED;
318         if (conn->mandatory_signing) {
319                 conn->smb2.client.security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED;
320         }
321         if (client_guid) {
322                 conn->smb2.client.guid = *client_guid;
323         }
324         conn->smb2.client.capabilities = smb2_capabilities;
325
326         conn->smb2.cur_credits = 1;
327         conn->smb2.max_credits = 0;
328
329         talloc_set_destructor(conn, smbXcli_conn_destructor);
330         return conn;
331
332  error:
333         if (conn->write_fd != -1) {
334                 close(conn->write_fd);
335         }
336         TALLOC_FREE(conn);
337         return NULL;
338 }
339
340 bool smbXcli_conn_is_connected(struct smbXcli_conn *conn)
341 {
342         if (conn == NULL) {
343                 return false;
344         }
345
346         if (conn->read_fd == -1) {
347                 return false;
348         }
349
350         return true;
351 }
352
353 enum protocol_types smbXcli_conn_protocol(struct smbXcli_conn *conn)
354 {
355         return conn->protocol;
356 }
357
358 bool smbXcli_conn_use_unicode(struct smbXcli_conn *conn)
359 {
360         if (conn->protocol >= PROTOCOL_SMB2_02) {
361                 return true;
362         }
363
364         if (conn->smb1.capabilities & CAP_UNICODE) {
365                 return true;
366         }
367
368         return false;
369 }
370
371 void smbXcli_conn_set_sockopt(struct smbXcli_conn *conn, const char *options)
372 {
373         set_socket_options(conn->read_fd, options);
374 }
375
376 const struct sockaddr_storage *smbXcli_conn_local_sockaddr(struct smbXcli_conn *conn)
377 {
378         return &conn->local_ss;
379 }
380
381 const struct sockaddr_storage *smbXcli_conn_remote_sockaddr(struct smbXcli_conn *conn)
382 {
383         return &conn->remote_ss;
384 }
385
386 const char *smbXcli_conn_remote_name(struct smbXcli_conn *conn)
387 {
388         return conn->remote_name;
389 }
390
391 uint16_t smbXcli_conn_max_requests(struct smbXcli_conn *conn)
392 {
393         if (conn->protocol >= PROTOCOL_SMB2_02) {
394                 /*
395                  * TODO...
396                  */
397                 return 1;
398         }
399
400         return conn->smb1.server.max_mux;
401 }
402
403 NTTIME smbXcli_conn_server_system_time(struct smbXcli_conn *conn)
404 {
405         if (conn->protocol >= PROTOCOL_SMB2_02) {
406                 return conn->smb2.server.system_time;
407         }
408
409         return conn->smb1.server.system_time;
410 }
411
412 const DATA_BLOB *smbXcli_conn_server_gss_blob(struct smbXcli_conn *conn)
413 {
414         if (conn->protocol >= PROTOCOL_SMB2_02) {
415                 return &conn->smb2.server.gss_blob;
416         }
417
418         return &conn->smb1.server.gss_blob;
419 }
420
421 const struct GUID *smbXcli_conn_server_guid(struct smbXcli_conn *conn)
422 {
423         if (conn->protocol >= PROTOCOL_SMB2_02) {
424                 return &conn->smb2.server.guid;
425         }
426
427         return &conn->smb1.server.guid;
428 }
429
430 struct smbXcli_conn_samba_suicide_state {
431         struct smbXcli_conn *conn;
432         struct iovec iov;
433         uint8_t buf[9];
434 };
435
436 static void smbXcli_conn_samba_suicide_done(struct tevent_req *subreq);
437
438 struct tevent_req *smbXcli_conn_samba_suicide_send(TALLOC_CTX *mem_ctx,
439                                                    struct tevent_context *ev,
440                                                    struct smbXcli_conn *conn,
441                                                    uint8_t exitcode)
442 {
443         struct tevent_req *req, *subreq;
444         struct smbXcli_conn_samba_suicide_state *state;
445
446         req = tevent_req_create(mem_ctx, &state,
447                                 struct smbXcli_conn_samba_suicide_state);
448         if (req == NULL) {
449                 return NULL;
450         }
451         state->conn = conn;
452         SIVAL(state->buf, 4, 0x74697865);
453         SCVAL(state->buf, 8, exitcode);
454         _smb_setlen_nbt(state->buf, sizeof(state->buf)-4);
455
456         state->iov.iov_base = state->buf;
457         state->iov.iov_len = sizeof(state->buf);
458
459         subreq = writev_send(state, ev, conn->outgoing, conn->write_fd,
460                              false, &state->iov, 1);
461         if (tevent_req_nomem(subreq, req)) {
462                 return tevent_req_post(req, ev);
463         }
464         tevent_req_set_callback(subreq, smbXcli_conn_samba_suicide_done, req);
465         return req;
466 }
467
468 static void smbXcli_conn_samba_suicide_done(struct tevent_req *subreq)
469 {
470         struct tevent_req *req = tevent_req_callback_data(
471                 subreq, struct tevent_req);
472         struct smbXcli_conn_samba_suicide_state *state = tevent_req_data(
473                 req, struct smbXcli_conn_samba_suicide_state);
474         ssize_t nwritten;
475         int err;
476
477         nwritten = writev_recv(subreq, &err);
478         TALLOC_FREE(subreq);
479         if (nwritten == -1) {
480                 NTSTATUS status = map_nt_error_from_unix_common(err);
481                 smbXcli_conn_disconnect(state->conn, status);
482                 return;
483         }
484         tevent_req_done(req);
485 }
486
487 NTSTATUS smbXcli_conn_samba_suicide_recv(struct tevent_req *req)
488 {
489         return tevent_req_simple_recv_ntstatus(req);
490 }
491
492 NTSTATUS smbXcli_conn_samba_suicide(struct smbXcli_conn *conn,
493                                     uint8_t exitcode)
494 {
495         TALLOC_CTX *frame = talloc_stackframe();
496         struct tevent_context *ev;
497         struct tevent_req *req;
498         NTSTATUS status = NT_STATUS_NO_MEMORY;
499         bool ok;
500
501         if (smbXcli_conn_has_async_calls(conn)) {
502                 /*
503                  * Can't use sync call while an async call is in flight
504                  */
505                 status = NT_STATUS_INVALID_PARAMETER_MIX;
506                 goto fail;
507         }
508         ev = tevent_context_init(frame);
509         if (ev == NULL) {
510                 goto fail;
511         }
512         req = smbXcli_conn_samba_suicide_send(frame, ev, conn, exitcode);
513         if (req == NULL) {
514                 goto fail;
515         }
516         ok = tevent_req_poll(req, ev);
517         if (!ok) {
518                 status = map_nt_error_from_unix_common(errno);
519                 goto fail;
520         }
521         status = smbXcli_conn_samba_suicide_recv(req);
522  fail:
523         TALLOC_FREE(frame);
524         return status;
525 }
526
527 uint32_t smb1cli_conn_capabilities(struct smbXcli_conn *conn)
528 {
529         return conn->smb1.capabilities;
530 }
531
532 uint32_t smb1cli_conn_max_xmit(struct smbXcli_conn *conn)
533 {
534         return conn->smb1.max_xmit;
535 }
536
537 uint32_t smb1cli_conn_server_session_key(struct smbXcli_conn *conn)
538 {
539         return conn->smb1.server.session_key;
540 }
541
542 const uint8_t *smb1cli_conn_server_challenge(struct smbXcli_conn *conn)
543 {
544         return conn->smb1.server.challenge;
545 }
546
547 uint16_t smb1cli_conn_server_security_mode(struct smbXcli_conn *conn)
548 {
549         return conn->smb1.server.security_mode;
550 }
551
552 bool smb1cli_conn_server_readbraw(struct smbXcli_conn *conn)
553 {
554         return conn->smb1.server.readbraw;
555 }
556
557 bool smb1cli_conn_server_writebraw(struct smbXcli_conn *conn)
558 {
559         return conn->smb1.server.writebraw;
560 }
561
562 bool smb1cli_conn_server_lockread(struct smbXcli_conn *conn)
563 {
564         return conn->smb1.server.lockread;
565 }
566
567 bool smb1cli_conn_server_writeunlock(struct smbXcli_conn *conn)
568 {
569         return conn->smb1.server.writeunlock;
570 }
571
572 int smb1cli_conn_server_time_zone(struct smbXcli_conn *conn)
573 {
574         return conn->smb1.server.time_zone;
575 }
576
577 bool smb1cli_conn_activate_signing(struct smbXcli_conn *conn,
578                                    const DATA_BLOB user_session_key,
579                                    const DATA_BLOB response)
580 {
581         return smb_signing_activate(conn->smb1.signing,
582                                     user_session_key,
583                                     response);
584 }
585
586 bool smb1cli_conn_check_signing(struct smbXcli_conn *conn,
587                                 const uint8_t *buf, uint32_t seqnum)
588 {
589         return smb_signing_check_pdu(conn->smb1.signing, buf, seqnum);
590 }
591
592 bool smb1cli_conn_signing_is_active(struct smbXcli_conn *conn)
593 {
594         return smb_signing_is_active(conn->smb1.signing);
595 }
596
597 void smb1cli_conn_set_encryption(struct smbXcli_conn *conn,
598                                  struct smb_trans_enc_state *es)
599 {
600         /* Replace the old state, if any. */
601         if (conn->smb1.trans_enc) {
602                 TALLOC_FREE(conn->smb1.trans_enc);
603         }
604         conn->smb1.trans_enc = es;
605 }
606
607 bool smb1cli_conn_encryption_on(struct smbXcli_conn *conn)
608 {
609         return common_encryption_on(conn->smb1.trans_enc);
610 }
611
612
613 static NTSTATUS smb1cli_pull_raw_error(const uint8_t *hdr)
614 {
615         uint32_t flags2 = SVAL(hdr, HDR_FLG2);
616         NTSTATUS status = NT_STATUS(IVAL(hdr, HDR_RCLS));
617
618         if (NT_STATUS_IS_OK(status)) {
619                 return NT_STATUS_OK;
620         }
621
622         if (flags2 & FLAGS2_32_BIT_ERROR_CODES) {
623                 return status;
624         }
625
626         return NT_STATUS_DOS(CVAL(hdr, HDR_RCLS), SVAL(hdr, HDR_ERR));
627 }
628
629 /**
630  * Is the SMB command able to hold an AND_X successor
631  * @param[in] cmd       The SMB command in question
632  * @retval Can we add a chained request after "cmd"?
633  */
634 bool smb1cli_is_andx_req(uint8_t cmd)
635 {
636         switch (cmd) {
637         case SMBtconX:
638         case SMBlockingX:
639         case SMBopenX:
640         case SMBreadX:
641         case SMBwriteX:
642         case SMBsesssetupX:
643         case SMBulogoffX:
644         case SMBntcreateX:
645                 return true;
646                 break;
647         default:
648                 break;
649         }
650
651         return false;
652 }
653
654 static uint16_t smb1cli_alloc_mid(struct smbXcli_conn *conn)
655 {
656         size_t num_pending = talloc_array_length(conn->pending);
657         uint16_t result;
658
659         while (true) {
660                 size_t i;
661
662                 result = conn->smb1.mid++;
663                 if ((result == 0) || (result == 0xffff)) {
664                         continue;
665                 }
666
667                 for (i=0; i<num_pending; i++) {
668                         if (result == smb1cli_req_mid(conn->pending[i])) {
669                                 break;
670                         }
671                 }
672
673                 if (i == num_pending) {
674                         return result;
675                 }
676         }
677 }
678
679 void smbXcli_req_unset_pending(struct tevent_req *req)
680 {
681         struct smbXcli_req_state *state =
682                 tevent_req_data(req,
683                 struct smbXcli_req_state);
684         struct smbXcli_conn *conn = state->conn;
685         size_t num_pending = talloc_array_length(conn->pending);
686         size_t i;
687
688         if (state->smb1.mid != 0) {
689                 /*
690                  * This is a [nt]trans[2] request which waits
691                  * for more than one reply.
692                  */
693                 return;
694         }
695
696         talloc_set_destructor(req, NULL);
697
698         if (num_pending == 1) {
699                 /*
700                  * The pending read_smb tevent_req is a child of
701                  * conn->pending. So if nothing is pending anymore, we need to
702                  * delete the socket read fde.
703                  */
704                 TALLOC_FREE(conn->pending);
705                 conn->read_smb_req = NULL;
706                 return;
707         }
708
709         for (i=0; i<num_pending; i++) {
710                 if (req == conn->pending[i]) {
711                         break;
712                 }
713         }
714         if (i == num_pending) {
715                 /*
716                  * Something's seriously broken. Just returning here is the
717                  * right thing nevertheless, the point of this routine is to
718                  * remove ourselves from conn->pending.
719                  */
720                 return;
721         }
722
723         /*
724          * Remove ourselves from the conn->pending array
725          */
726         for (; i < (num_pending - 1); i++) {
727                 conn->pending[i] = conn->pending[i+1];
728         }
729
730         /*
731          * No NULL check here, we're shrinking by sizeof(void *), and
732          * talloc_realloc just adjusts the size for this.
733          */
734         conn->pending = talloc_realloc(NULL, conn->pending, struct tevent_req *,
735                                        num_pending - 1);
736         return;
737 }
738
739 static int smbXcli_req_destructor(struct tevent_req *req)
740 {
741         struct smbXcli_req_state *state =
742                 tevent_req_data(req,
743                 struct smbXcli_req_state);
744
745         /*
746          * Make sure we really remove it from
747          * the pending array on destruction.
748          */
749         state->smb1.mid = 0;
750         smbXcli_req_unset_pending(req);
751         return 0;
752 }
753
754 static bool smb1cli_req_cancel(struct tevent_req *req);
755 static bool smb2cli_req_cancel(struct tevent_req *req);
756
757 static bool smbXcli_req_cancel(struct tevent_req *req)
758 {
759         struct smbXcli_req_state *state =
760                 tevent_req_data(req,
761                 struct smbXcli_req_state);
762
763         if (!smbXcli_conn_is_connected(state->conn)) {
764                 return false;
765         }
766
767         if (state->conn->protocol == PROTOCOL_NONE) {
768                 return false;
769         }
770
771         if (state->conn->protocol >= PROTOCOL_SMB2_02) {
772                 return smb2cli_req_cancel(req);
773         }
774
775         return smb1cli_req_cancel(req);
776 }
777
778 static bool smbXcli_conn_receive_next(struct smbXcli_conn *conn);
779
780 bool smbXcli_req_set_pending(struct tevent_req *req)
781 {
782         struct smbXcli_req_state *state =
783                 tevent_req_data(req,
784                 struct smbXcli_req_state);
785         struct smbXcli_conn *conn;
786         struct tevent_req **pending;
787         size_t num_pending;
788
789         conn = state->conn;
790
791         if (!smbXcli_conn_is_connected(conn)) {
792                 return false;
793         }
794
795         num_pending = talloc_array_length(conn->pending);
796
797         pending = talloc_realloc(conn, conn->pending, struct tevent_req *,
798                                  num_pending+1);
799         if (pending == NULL) {
800                 return false;
801         }
802         pending[num_pending] = req;
803         conn->pending = pending;
804         talloc_set_destructor(req, smbXcli_req_destructor);
805         tevent_req_set_cancel_fn(req, smbXcli_req_cancel);
806
807         if (!smbXcli_conn_receive_next(conn)) {
808                 /*
809                  * the caller should notify the current request
810                  *
811                  * And all other pending requests get notified
812                  * by smbXcli_conn_disconnect().
813                  */
814                 smbXcli_req_unset_pending(req);
815                 smbXcli_conn_disconnect(conn, NT_STATUS_NO_MEMORY);
816                 return false;
817         }
818
819         return true;
820 }
821
822 static void smbXcli_conn_received(struct tevent_req *subreq);
823
824 static bool smbXcli_conn_receive_next(struct smbXcli_conn *conn)
825 {
826         size_t num_pending = talloc_array_length(conn->pending);
827         struct tevent_req *req;
828         struct smbXcli_req_state *state;
829
830         if (conn->read_smb_req != NULL) {
831                 return true;
832         }
833
834         if (num_pending == 0) {
835                 if (conn->smb2.mid < UINT64_MAX) {
836                         /* no more pending requests, so we are done for now */
837                         return true;
838                 }
839
840                 /*
841                  * If there are no more SMB2 requests possible,
842                  * because we are out of message ids,
843                  * we need to disconnect.
844                  */
845                 smbXcli_conn_disconnect(conn, NT_STATUS_CONNECTION_ABORTED);
846                 return true;
847         }
848
849         req = conn->pending[0];
850         state = tevent_req_data(req, struct smbXcli_req_state);
851
852         /*
853          * We're the first ones, add the read_smb request that waits for the
854          * answer from the server
855          */
856         conn->read_smb_req = read_smb_send(conn->pending,
857                                            state->ev,
858                                            conn->read_fd);
859         if (conn->read_smb_req == NULL) {
860                 return false;
861         }
862         tevent_req_set_callback(conn->read_smb_req, smbXcli_conn_received, conn);
863         return true;
864 }
865
866 void smbXcli_conn_disconnect(struct smbXcli_conn *conn, NTSTATUS status)
867 {
868         tevent_queue_stop(conn->outgoing);
869
870         if (conn->read_fd != -1) {
871                 close(conn->read_fd);
872         }
873         if (conn->write_fd != -1) {
874                 close(conn->write_fd);
875         }
876         conn->read_fd = -1;
877         conn->write_fd = -1;
878
879         /*
880          * Cancel all pending requests. We do not do a for-loop walking
881          * conn->pending because that array changes in
882          * smbXcli_req_unset_pending.
883          */
884         while (talloc_array_length(conn->pending) > 0) {
885                 struct tevent_req *req;
886                 struct smbXcli_req_state *state;
887                 struct tevent_req **chain;
888                 size_t num_chained;
889                 size_t i;
890
891                 req = conn->pending[0];
892                 state = tevent_req_data(req, struct smbXcli_req_state);
893
894                 if (state->smb1.chained_requests == NULL) {
895                         /*
896                          * We're dead. No point waiting for trans2
897                          * replies.
898                          */
899                         state->smb1.mid = 0;
900
901                         smbXcli_req_unset_pending(req);
902
903                         if (NT_STATUS_IS_OK(status)) {
904                                 /* do not notify the callers */
905                                 continue;
906                         }
907
908                         /*
909                          * we need to defer the callback, because we may notify
910                          * more then one caller.
911                          */
912                         tevent_req_defer_callback(req, state->ev);
913                         tevent_req_nterror(req, status);
914                         continue;
915                 }
916
917                 chain = talloc_move(conn, &state->smb1.chained_requests);
918                 num_chained = talloc_array_length(chain);
919
920                 for (i=0; i<num_chained; i++) {
921                         req = chain[i];
922                         state = tevent_req_data(req, struct smbXcli_req_state);
923
924                         /*
925                          * We're dead. No point waiting for trans2
926                          * replies.
927                          */
928                         state->smb1.mid = 0;
929
930                         smbXcli_req_unset_pending(req);
931
932                         if (NT_STATUS_IS_OK(status)) {
933                                 /* do not notify the callers */
934                                 continue;
935                         }
936
937                         /*
938                          * we need to defer the callback, because we may notify
939                          * more than one caller.
940                          */
941                         tevent_req_defer_callback(req, state->ev);
942                         tevent_req_nterror(req, status);
943                 }
944                 TALLOC_FREE(chain);
945         }
946 }
947
948 /*
949  * Fetch a smb request's mid. Only valid after the request has been sent by
950  * smb1cli_req_send().
951  */
952 uint16_t smb1cli_req_mid(struct tevent_req *req)
953 {
954         struct smbXcli_req_state *state =
955                 tevent_req_data(req,
956                 struct smbXcli_req_state);
957
958         if (state->smb1.mid != 0) {
959                 return state->smb1.mid;
960         }
961
962         return SVAL(state->smb1.hdr, HDR_MID);
963 }
964
965 void smb1cli_req_set_mid(struct tevent_req *req, uint16_t mid)
966 {
967         struct smbXcli_req_state *state =
968                 tevent_req_data(req,
969                 struct smbXcli_req_state);
970
971         state->smb1.mid = mid;
972 }
973
974 uint32_t smb1cli_req_seqnum(struct tevent_req *req)
975 {
976         struct smbXcli_req_state *state =
977                 tevent_req_data(req,
978                 struct smbXcli_req_state);
979
980         return state->smb1.seqnum;
981 }
982
983 void smb1cli_req_set_seqnum(struct tevent_req *req, uint32_t seqnum)
984 {
985         struct smbXcli_req_state *state =
986                 tevent_req_data(req,
987                 struct smbXcli_req_state);
988
989         state->smb1.seqnum = seqnum;
990 }
991
992 static size_t smbXcli_iov_len(const struct iovec *iov, int count)
993 {
994         size_t result = 0;
995         int i;
996         for (i=0; i<count; i++) {
997                 result += iov[i].iov_len;
998         }
999         return result;
1000 }
1001
1002 static uint8_t *smbXcli_iov_concat(TALLOC_CTX *mem_ctx,
1003                                    const struct iovec *iov,
1004                                    int count)
1005 {
1006         size_t len = smbXcli_iov_len(iov, count);
1007         size_t copied;
1008         uint8_t *buf;
1009         int i;
1010
1011         buf = talloc_array(mem_ctx, uint8_t, len);
1012         if (buf == NULL) {
1013                 return NULL;
1014         }
1015         copied = 0;
1016         for (i=0; i<count; i++) {
1017                 memcpy(buf+copied, iov[i].iov_base, iov[i].iov_len);
1018                 copied += iov[i].iov_len;
1019         }
1020         return buf;
1021 }
1022
1023 static void smb1cli_req_flags(enum protocol_types protocol,
1024                               uint32_t smb1_capabilities,
1025                               uint8_t smb_command,
1026                               uint8_t additional_flags,
1027                               uint8_t clear_flags,
1028                               uint8_t *_flags,
1029                               uint16_t additional_flags2,
1030                               uint16_t clear_flags2,
1031                               uint16_t *_flags2)
1032 {
1033         uint8_t flags = 0;
1034         uint16_t flags2 = 0;
1035
1036         if (protocol >= PROTOCOL_LANMAN1) {
1037                 flags |= FLAG_CASELESS_PATHNAMES;
1038                 flags |= FLAG_CANONICAL_PATHNAMES;
1039         }
1040
1041         if (protocol >= PROTOCOL_LANMAN2) {
1042                 flags2 |= FLAGS2_LONG_PATH_COMPONENTS;
1043                 flags2 |= FLAGS2_EXTENDED_ATTRIBUTES;
1044         }
1045
1046         if (protocol >= PROTOCOL_NT1) {
1047                 flags2 |= FLAGS2_IS_LONG_NAME;
1048
1049                 if (smb1_capabilities & CAP_UNICODE) {
1050                         flags2 |= FLAGS2_UNICODE_STRINGS;
1051                 }
1052                 if (smb1_capabilities & CAP_STATUS32) {
1053                         flags2 |= FLAGS2_32_BIT_ERROR_CODES;
1054                 }
1055                 if (smb1_capabilities & CAP_EXTENDED_SECURITY) {
1056                         flags2 |= FLAGS2_EXTENDED_SECURITY;
1057                 }
1058         }
1059
1060         flags |= additional_flags;
1061         flags &= ~clear_flags;
1062         flags2 |= additional_flags2;
1063         flags2 &= ~clear_flags2;
1064
1065         *_flags = flags;
1066         *_flags2 = flags2;
1067 }
1068
1069 static void smb1cli_req_cancel_done(struct tevent_req *subreq);
1070
1071 static bool smb1cli_req_cancel(struct tevent_req *req)
1072 {
1073         struct smbXcli_req_state *state =
1074                 tevent_req_data(req,
1075                 struct smbXcli_req_state);
1076         uint8_t flags;
1077         uint16_t flags2;
1078         uint32_t pid;
1079         uint16_t tid;
1080         uint16_t uid;
1081         uint16_t mid;
1082         struct tevent_req *subreq;
1083         NTSTATUS status;
1084
1085         flags = CVAL(state->smb1.hdr, HDR_FLG);
1086         flags2 = SVAL(state->smb1.hdr, HDR_FLG2);
1087         pid  = SVAL(state->smb1.hdr, HDR_PID);
1088         pid |= SVAL(state->smb1.hdr, HDR_PIDHIGH)<<16;
1089         tid = SVAL(state->smb1.hdr, HDR_TID);
1090         uid = SVAL(state->smb1.hdr, HDR_UID);
1091         mid = SVAL(state->smb1.hdr, HDR_MID);
1092
1093         subreq = smb1cli_req_create(state, state->ev,
1094                                     state->conn,
1095                                     SMBntcancel,
1096                                     flags, 0,
1097                                     flags2, 0,
1098                                     0, /* timeout */
1099                                     pid, tid, uid,
1100                                     0, NULL, /* vwv */
1101                                     0, NULL); /* bytes */
1102         if (subreq == NULL) {
1103                 return false;
1104         }
1105         smb1cli_req_set_mid(subreq, mid);
1106
1107         status = smb1cli_req_chain_submit(&subreq, 1);
1108         if (!NT_STATUS_IS_OK(status)) {
1109                 TALLOC_FREE(subreq);
1110                 return false;
1111         }
1112         smb1cli_req_set_mid(subreq, 0);
1113
1114         tevent_req_set_callback(subreq, smb1cli_req_cancel_done, NULL);
1115
1116         return true;
1117 }
1118
1119 static void smb1cli_req_cancel_done(struct tevent_req *subreq)
1120 {
1121         /* we do not care about the result */
1122         TALLOC_FREE(subreq);
1123 }
1124
1125 struct tevent_req *smb1cli_req_create(TALLOC_CTX *mem_ctx,
1126                                       struct tevent_context *ev,
1127                                       struct smbXcli_conn *conn,
1128                                       uint8_t smb_command,
1129                                       uint8_t additional_flags,
1130                                       uint8_t clear_flags,
1131                                       uint16_t additional_flags2,
1132                                       uint16_t clear_flags2,
1133                                       uint32_t timeout_msec,
1134                                       uint32_t pid,
1135                                       uint16_t tid,
1136                                       uint16_t uid,
1137                                       uint8_t wct, uint16_t *vwv,
1138                                       int iov_count,
1139                                       struct iovec *bytes_iov)
1140 {
1141         struct tevent_req *req;
1142         struct smbXcli_req_state *state;
1143         uint8_t flags = 0;
1144         uint16_t flags2 = 0;
1145
1146         if (iov_count > MAX_SMB_IOV) {
1147                 /*
1148                  * Should not happen :-)
1149                  */
1150                 return NULL;
1151         }
1152
1153         req = tevent_req_create(mem_ctx, &state,
1154                                 struct smbXcli_req_state);
1155         if (req == NULL) {
1156                 return NULL;
1157         }
1158         state->ev = ev;
1159         state->conn = conn;
1160
1161         state->smb1.recv_cmd = 0xFF;
1162         state->smb1.recv_status = NT_STATUS_INTERNAL_ERROR;
1163         state->smb1.recv_iov = talloc_zero_array(state, struct iovec, 3);
1164         if (state->smb1.recv_iov == NULL) {
1165                 TALLOC_FREE(req);
1166                 return NULL;
1167         }
1168
1169         smb1cli_req_flags(conn->protocol,
1170                           conn->smb1.capabilities,
1171                           smb_command,
1172                           additional_flags,
1173                           clear_flags,
1174                           &flags,
1175                           additional_flags2,
1176                           clear_flags2,
1177                           &flags2);
1178
1179         SIVAL(state->smb1.hdr, 0,           SMB_MAGIC);
1180         SCVAL(state->smb1.hdr, HDR_COM,     smb_command);
1181         SIVAL(state->smb1.hdr, HDR_RCLS,    NT_STATUS_V(NT_STATUS_OK));
1182         SCVAL(state->smb1.hdr, HDR_FLG,     flags);
1183         SSVAL(state->smb1.hdr, HDR_FLG2,    flags2);
1184         SSVAL(state->smb1.hdr, HDR_PIDHIGH, pid >> 16);
1185         SSVAL(state->smb1.hdr, HDR_TID,     tid);
1186         SSVAL(state->smb1.hdr, HDR_PID,     pid);
1187         SSVAL(state->smb1.hdr, HDR_UID,     uid);
1188         SSVAL(state->smb1.hdr, HDR_MID,     0); /* this comes later */
1189         SCVAL(state->smb1.hdr, HDR_WCT,     wct);
1190
1191         state->smb1.vwv = vwv;
1192
1193         SSVAL(state->smb1.bytecount_buf, 0, smbXcli_iov_len(bytes_iov, iov_count));
1194
1195         state->smb1.iov[0].iov_base = (void *)state->length_hdr;
1196         state->smb1.iov[0].iov_len  = sizeof(state->length_hdr);
1197         state->smb1.iov[1].iov_base = (void *)state->smb1.hdr;
1198         state->smb1.iov[1].iov_len  = sizeof(state->smb1.hdr);
1199         state->smb1.iov[2].iov_base = (void *)state->smb1.vwv;
1200         state->smb1.iov[2].iov_len  = wct * sizeof(uint16_t);
1201         state->smb1.iov[3].iov_base = (void *)state->smb1.bytecount_buf;
1202         state->smb1.iov[3].iov_len  = sizeof(uint16_t);
1203
1204         if (iov_count != 0) {
1205                 memcpy(&state->smb1.iov[4], bytes_iov,
1206                        iov_count * sizeof(*bytes_iov));
1207         }
1208         state->smb1.iov_count = iov_count + 4;
1209
1210         if (timeout_msec > 0) {
1211                 struct timeval endtime;
1212
1213                 endtime = timeval_current_ofs_msec(timeout_msec);
1214                 if (!tevent_req_set_endtime(req, ev, endtime)) {
1215                         return req;
1216                 }
1217         }
1218
1219         switch (smb_command) {
1220         case SMBtranss:
1221         case SMBtranss2:
1222         case SMBnttranss:
1223                 state->one_way = true;
1224                 break;
1225         case SMBntcancel:
1226                 state->one_way = true;
1227                 state->smb1.one_way_seqnum = true;
1228                 break;
1229         case SMBlockingX:
1230                 if ((wct == 8) &&
1231                     (CVAL(vwv+3, 0) == LOCKING_ANDX_OPLOCK_RELEASE)) {
1232                         state->one_way = true;
1233                 }
1234                 break;
1235         }
1236
1237         return req;
1238 }
1239
1240 static NTSTATUS smb1cli_conn_signv(struct smbXcli_conn *conn,
1241                                    struct iovec *iov, int iov_count,
1242                                    uint32_t *seqnum,
1243                                    bool one_way_seqnum)
1244 {
1245         TALLOC_CTX *frame = NULL;
1246         uint8_t *buf;
1247
1248         /*
1249          * Obvious optimization: Make cli_calculate_sign_mac work with struct
1250          * iovec directly. MD5Update would do that just fine.
1251          */
1252
1253         if (iov_count < 4) {
1254                 return NT_STATUS_INVALID_PARAMETER_MIX;
1255         }
1256         if (iov[0].iov_len != NBT_HDR_SIZE) {
1257                 return NT_STATUS_INVALID_PARAMETER_MIX;
1258         }
1259         if (iov[1].iov_len != (MIN_SMB_SIZE-sizeof(uint16_t))) {
1260                 return NT_STATUS_INVALID_PARAMETER_MIX;
1261         }
1262         if (iov[2].iov_len > (0xFF * sizeof(uint16_t))) {
1263                 return NT_STATUS_INVALID_PARAMETER_MIX;
1264         }
1265         if (iov[3].iov_len != sizeof(uint16_t)) {
1266                 return NT_STATUS_INVALID_PARAMETER_MIX;
1267         }
1268
1269         frame = talloc_stackframe();
1270
1271         buf = smbXcli_iov_concat(frame, iov, iov_count);
1272         if (buf == NULL) {
1273                 return NT_STATUS_NO_MEMORY;
1274         }
1275
1276         *seqnum = smb_signing_next_seqnum(conn->smb1.signing,
1277                                           one_way_seqnum);
1278         smb_signing_sign_pdu(conn->smb1.signing, buf, *seqnum);
1279         memcpy(iov[1].iov_base, buf+4, iov[1].iov_len);
1280
1281         TALLOC_FREE(frame);
1282         return NT_STATUS_OK;
1283 }
1284
1285 static void smb1cli_req_writev_done(struct tevent_req *subreq);
1286 static NTSTATUS smb1cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
1287                                                TALLOC_CTX *tmp_mem,
1288                                                uint8_t *inbuf);
1289
1290 static NTSTATUS smb1cli_req_writev_submit(struct tevent_req *req,
1291                                           struct smbXcli_req_state *state,
1292                                           struct iovec *iov, int iov_count)
1293 {
1294         struct tevent_req *subreq;
1295         NTSTATUS status;
1296         uint8_t cmd;
1297         uint16_t mid;
1298
1299         if (!smbXcli_conn_is_connected(state->conn)) {
1300                 return NT_STATUS_CONNECTION_DISCONNECTED;
1301         }
1302
1303         if (state->conn->protocol > PROTOCOL_NT1) {
1304                 return NT_STATUS_REVISION_MISMATCH;
1305         }
1306
1307         if (iov_count < 4) {
1308                 return NT_STATUS_INVALID_PARAMETER_MIX;
1309         }
1310         if (iov[0].iov_len != NBT_HDR_SIZE) {
1311                 return NT_STATUS_INVALID_PARAMETER_MIX;
1312         }
1313         if (iov[1].iov_len != (MIN_SMB_SIZE-sizeof(uint16_t))) {
1314                 return NT_STATUS_INVALID_PARAMETER_MIX;
1315         }
1316         if (iov[2].iov_len > (0xFF * sizeof(uint16_t))) {
1317                 return NT_STATUS_INVALID_PARAMETER_MIX;
1318         }
1319         if (iov[3].iov_len != sizeof(uint16_t)) {
1320                 return NT_STATUS_INVALID_PARAMETER_MIX;
1321         }
1322
1323         cmd = CVAL(iov[1].iov_base, HDR_COM);
1324         if (cmd == SMBreadBraw) {
1325                 if (smbXcli_conn_has_async_calls(state->conn)) {
1326                         return NT_STATUS_INVALID_PARAMETER_MIX;
1327                 }
1328                 state->conn->smb1.read_braw_req = req;
1329         }
1330
1331         if (state->smb1.mid != 0) {
1332                 mid = state->smb1.mid;
1333         } else {
1334                 mid = smb1cli_alloc_mid(state->conn);
1335         }
1336         SSVAL(iov[1].iov_base, HDR_MID, mid);
1337
1338         _smb_setlen_nbt(iov[0].iov_base, smbXcli_iov_len(&iov[1], iov_count-1));
1339
1340         status = smb1cli_conn_signv(state->conn, iov, iov_count,
1341                                     &state->smb1.seqnum,
1342                                     state->smb1.one_way_seqnum);
1343
1344         if (!NT_STATUS_IS_OK(status)) {
1345                 return status;
1346         }
1347
1348         /*
1349          * If we supported multiple encrytion contexts
1350          * here we'd look up based on tid.
1351          */
1352         if (common_encryption_on(state->conn->smb1.trans_enc)) {
1353                 char *buf, *enc_buf;
1354
1355                 buf = (char *)smbXcli_iov_concat(talloc_tos(), iov, iov_count);
1356                 if (buf == NULL) {
1357                         return NT_STATUS_NO_MEMORY;
1358                 }
1359                 status = common_encrypt_buffer(state->conn->smb1.trans_enc,
1360                                                (char *)buf, &enc_buf);
1361                 TALLOC_FREE(buf);
1362                 if (!NT_STATUS_IS_OK(status)) {
1363                         DEBUG(0, ("Error in encrypting client message: %s\n",
1364                                   nt_errstr(status)));
1365                         return status;
1366                 }
1367                 buf = (char *)talloc_memdup(state, enc_buf,
1368                                             smb_len_nbt(enc_buf)+4);
1369                 SAFE_FREE(enc_buf);
1370                 if (buf == NULL) {
1371                         return NT_STATUS_NO_MEMORY;
1372                 }
1373                 iov[0].iov_base = (void *)buf;
1374                 iov[0].iov_len = talloc_get_size(buf);
1375                 iov_count = 1;
1376         }
1377
1378         if (state->conn->dispatch_incoming == NULL) {
1379                 state->conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
1380         }
1381
1382         tevent_req_set_cancel_fn(req, smbXcli_req_cancel);
1383
1384         subreq = writev_send(state, state->ev, state->conn->outgoing,
1385                              state->conn->write_fd, false, iov, iov_count);
1386         if (subreq == NULL) {
1387                 return NT_STATUS_NO_MEMORY;
1388         }
1389         tevent_req_set_callback(subreq, smb1cli_req_writev_done, req);
1390         return NT_STATUS_OK;
1391 }
1392
1393 struct tevent_req *smb1cli_req_send(TALLOC_CTX *mem_ctx,
1394                                     struct tevent_context *ev,
1395                                     struct smbXcli_conn *conn,
1396                                     uint8_t smb_command,
1397                                     uint8_t additional_flags,
1398                                     uint8_t clear_flags,
1399                                     uint16_t additional_flags2,
1400                                     uint16_t clear_flags2,
1401                                     uint32_t timeout_msec,
1402                                     uint32_t pid,
1403                                     uint16_t tid,
1404                                     uint16_t uid,
1405                                     uint8_t wct, uint16_t *vwv,
1406                                     uint32_t num_bytes,
1407                                     const uint8_t *bytes)
1408 {
1409         struct tevent_req *req;
1410         struct iovec iov;
1411         NTSTATUS status;
1412
1413         iov.iov_base = discard_const_p(void, bytes);
1414         iov.iov_len = num_bytes;
1415
1416         req = smb1cli_req_create(mem_ctx, ev, conn, smb_command,
1417                                  additional_flags, clear_flags,
1418                                  additional_flags2, clear_flags2,
1419                                  timeout_msec,
1420                                  pid, tid, uid,
1421                                  wct, vwv, 1, &iov);
1422         if (req == NULL) {
1423                 return NULL;
1424         }
1425         if (!tevent_req_is_in_progress(req)) {
1426                 return tevent_req_post(req, ev);
1427         }
1428         status = smb1cli_req_chain_submit(&req, 1);
1429         if (tevent_req_nterror(req, status)) {
1430                 return tevent_req_post(req, ev);
1431         }
1432         return req;
1433 }
1434
1435 static void smb1cli_req_writev_done(struct tevent_req *subreq)
1436 {
1437         struct tevent_req *req =
1438                 tevent_req_callback_data(subreq,
1439                 struct tevent_req);
1440         struct smbXcli_req_state *state =
1441                 tevent_req_data(req,
1442                 struct smbXcli_req_state);
1443         ssize_t nwritten;
1444         int err;
1445
1446         nwritten = writev_recv(subreq, &err);
1447         TALLOC_FREE(subreq);
1448         if (nwritten == -1) {
1449                 NTSTATUS status = map_nt_error_from_unix_common(err);
1450                 smbXcli_conn_disconnect(state->conn, status);
1451                 return;
1452         }
1453
1454         if (state->one_way) {
1455                 state->inbuf = NULL;
1456                 tevent_req_done(req);
1457                 return;
1458         }
1459
1460         if (!smbXcli_req_set_pending(req)) {
1461                 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
1462                 return;
1463         }
1464 }
1465
1466 static void smbXcli_conn_received(struct tevent_req *subreq)
1467 {
1468         struct smbXcli_conn *conn =
1469                 tevent_req_callback_data(subreq,
1470                 struct smbXcli_conn);
1471         TALLOC_CTX *frame = talloc_stackframe();
1472         NTSTATUS status;
1473         uint8_t *inbuf;
1474         ssize_t received;
1475         int err;
1476
1477         if (subreq != conn->read_smb_req) {
1478                 DEBUG(1, ("Internal error: cli_smb_received called with "
1479                           "unexpected subreq\n"));
1480                 status = NT_STATUS_INTERNAL_ERROR;
1481                 smbXcli_conn_disconnect(conn, status);
1482                 TALLOC_FREE(frame);
1483                 return;
1484         }
1485         conn->read_smb_req = NULL;
1486
1487         received = read_smb_recv(subreq, frame, &inbuf, &err);
1488         TALLOC_FREE(subreq);
1489         if (received == -1) {
1490                 status = map_nt_error_from_unix_common(err);
1491                 smbXcli_conn_disconnect(conn, status);
1492                 TALLOC_FREE(frame);
1493                 return;
1494         }
1495
1496         status = conn->dispatch_incoming(conn, frame, inbuf);
1497         TALLOC_FREE(frame);
1498         if (NT_STATUS_IS_OK(status)) {
1499                 /*
1500                  * We should not do any more processing
1501                  * as the dispatch function called
1502                  * tevent_req_done().
1503                  */
1504                 return;
1505         } else if (!NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
1506                 /*
1507                  * We got an error, so notify all pending requests
1508                  */
1509                 smbXcli_conn_disconnect(conn, status);
1510                 return;
1511         }
1512
1513         /*
1514          * We got NT_STATUS_RETRY, so we may ask for a
1515          * next incoming pdu.
1516          */
1517         if (!smbXcli_conn_receive_next(conn)) {
1518                 smbXcli_conn_disconnect(conn, NT_STATUS_NO_MEMORY);
1519         }
1520 }
1521
1522 static NTSTATUS smb1cli_inbuf_parse_chain(uint8_t *buf, TALLOC_CTX *mem_ctx,
1523                                           struct iovec **piov, int *pnum_iov)
1524 {
1525         struct iovec *iov;
1526         int num_iov;
1527         size_t buflen;
1528         size_t taken;
1529         size_t remaining;
1530         uint8_t *hdr;
1531         uint8_t cmd;
1532         uint32_t wct_ofs;
1533
1534         buflen = smb_len_nbt(buf);
1535         taken = 0;
1536
1537         hdr = buf + NBT_HDR_SIZE;
1538
1539         if (buflen < MIN_SMB_SIZE) {
1540                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1541         }
1542
1543         /*
1544          * This returns iovec elements in the following order:
1545          *
1546          * - SMB header
1547          *
1548          * - Parameter Block
1549          * - Data Block
1550          *
1551          * - Parameter Block
1552          * - Data Block
1553          *
1554          * - Parameter Block
1555          * - Data Block
1556          */
1557         num_iov = 1;
1558
1559         iov = talloc_array(mem_ctx, struct iovec, num_iov);
1560         if (iov == NULL) {
1561                 return NT_STATUS_NO_MEMORY;
1562         }
1563         iov[0].iov_base = hdr;
1564         iov[0].iov_len = HDR_WCT;
1565         taken += HDR_WCT;
1566
1567         cmd = CVAL(hdr, HDR_COM);
1568         wct_ofs = HDR_WCT;
1569
1570         while (true) {
1571                 size_t len = buflen - taken;
1572                 struct iovec *cur;
1573                 struct iovec *iov_tmp;
1574                 uint8_t wct;
1575                 uint32_t bcc_ofs;
1576                 uint16_t bcc;
1577                 size_t needed;
1578
1579                 /*
1580                  * we need at least WCT and BCC
1581                  */
1582                 needed = sizeof(uint8_t) + sizeof(uint16_t);
1583                 if (len < needed) {
1584                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1585                                    __location__, (int)len, (int)needed));
1586                         goto inval;
1587                 }
1588
1589                 /*
1590                  * Now we check if the specified words are there
1591                  */
1592                 wct = CVAL(hdr, wct_ofs);
1593                 needed += wct * sizeof(uint16_t);
1594                 if (len < needed) {
1595                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1596                                    __location__, (int)len, (int)needed));
1597                         goto inval;
1598                 }
1599
1600                 /*
1601                  * Now we check if the specified bytes are there
1602                  */
1603                 bcc_ofs = wct_ofs + sizeof(uint8_t) + wct * sizeof(uint16_t);
1604                 bcc = SVAL(hdr, bcc_ofs);
1605                 needed += bcc * sizeof(uint8_t);
1606                 if (len < needed) {
1607                         DEBUG(10, ("%s: %d bytes left, expected at least %d\n",
1608                                    __location__, (int)len, (int)needed));
1609                         goto inval;
1610                 }
1611
1612                 /*
1613                  * we allocate 2 iovec structures for words and bytes
1614                  */
1615                 iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
1616                                          num_iov + 2);
1617                 if (iov_tmp == NULL) {
1618                         TALLOC_FREE(iov);
1619                         return NT_STATUS_NO_MEMORY;
1620                 }
1621                 iov = iov_tmp;
1622                 cur = &iov[num_iov];
1623                 num_iov += 2;
1624
1625                 cur[0].iov_len = wct * sizeof(uint16_t);
1626                 cur[0].iov_base = hdr + (wct_ofs + sizeof(uint8_t));
1627                 cur[1].iov_len = bcc * sizeof(uint8_t);
1628                 cur[1].iov_base = hdr + (bcc_ofs + sizeof(uint16_t));
1629
1630                 taken += needed;
1631
1632                 if (!smb1cli_is_andx_req(cmd)) {
1633                         /*
1634                          * If the current command does not have AndX chanining
1635                          * we are done.
1636                          */
1637                         break;
1638                 }
1639
1640                 if (wct == 0 && bcc == 0) {
1641                         /*
1642                          * An empty response also ends the chain,
1643                          * most likely with an error.
1644                          */
1645                         break;
1646                 }
1647
1648                 if (wct < 2) {
1649                         DEBUG(10, ("%s: wct[%d] < 2 for cmd[0x%02X]\n",
1650                                    __location__, (int)wct, (int)cmd));
1651                         goto inval;
1652                 }
1653                 cmd = CVAL(cur[0].iov_base, 0);
1654                 if (cmd == 0xFF) {
1655                         /*
1656                          * If it is the end of the chain we are also done.
1657                          */
1658                         break;
1659                 }
1660                 wct_ofs = SVAL(cur[0].iov_base, 2);
1661
1662                 if (wct_ofs < taken) {
1663                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1664                 }
1665                 if (wct_ofs > buflen) {
1666                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1667                 }
1668
1669                 /*
1670                  * we consumed everything up to the start of the next
1671                  * parameter block.
1672                  */
1673                 taken = wct_ofs;
1674         }
1675
1676         remaining = buflen - taken;
1677
1678         if (remaining > 0 && num_iov >= 3) {
1679                 /*
1680                  * The last DATA block gets the remaining
1681                  * bytes, this is needed to support
1682                  * CAP_LARGE_WRITEX and CAP_LARGE_READX.
1683                  */
1684                 iov[num_iov-1].iov_len += remaining;
1685         }
1686
1687         *piov = iov;
1688         *pnum_iov = num_iov;
1689         return NT_STATUS_OK;
1690
1691 inval:
1692         TALLOC_FREE(iov);
1693         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1694 }
1695
1696 static NTSTATUS smb1cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
1697                                                TALLOC_CTX *tmp_mem,
1698                                                uint8_t *inbuf)
1699 {
1700         struct tevent_req *req;
1701         struct smbXcli_req_state *state;
1702         NTSTATUS status;
1703         size_t num_pending;
1704         size_t i;
1705         uint8_t cmd;
1706         uint16_t mid;
1707         bool oplock_break;
1708         const uint8_t *inhdr = inbuf + NBT_HDR_SIZE;
1709         struct iovec *iov = NULL;
1710         int num_iov = 0;
1711         struct tevent_req **chain = NULL;
1712         size_t num_chained = 0;
1713         size_t num_responses = 0;
1714
1715         if (conn->smb1.read_braw_req != NULL) {
1716                 req = conn->smb1.read_braw_req;
1717                 conn->smb1.read_braw_req = NULL;
1718                 state = tevent_req_data(req, struct smbXcli_req_state);
1719
1720                 smbXcli_req_unset_pending(req);
1721
1722                 if (state->smb1.recv_iov == NULL) {
1723                         /*
1724                          * For requests with more than
1725                          * one response, we have to readd the
1726                          * recv_iov array.
1727                          */
1728                         state->smb1.recv_iov = talloc_zero_array(state,
1729                                                                  struct iovec,
1730                                                                  3);
1731                         if (tevent_req_nomem(state->smb1.recv_iov, req)) {
1732                                 return NT_STATUS_OK;
1733                         }
1734                 }
1735
1736                 state->smb1.recv_iov[0].iov_base = (void *)(inbuf + NBT_HDR_SIZE);
1737                 state->smb1.recv_iov[0].iov_len = smb_len_nbt(inbuf);
1738                 ZERO_STRUCT(state->smb1.recv_iov[1]);
1739                 ZERO_STRUCT(state->smb1.recv_iov[2]);
1740
1741                 state->smb1.recv_cmd = SMBreadBraw;
1742                 state->smb1.recv_status = NT_STATUS_OK;
1743                 state->inbuf = talloc_move(state->smb1.recv_iov, &inbuf);
1744
1745                 tevent_req_done(req);
1746                 return NT_STATUS_OK;
1747         }
1748
1749         if ((IVAL(inhdr, 0) != SMB_MAGIC) /* 0xFF"SMB" */
1750             && (SVAL(inhdr, 0) != 0x45ff)) /* 0xFF"E" */ {
1751                 DEBUG(10, ("Got non-SMB PDU\n"));
1752                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1753         }
1754
1755         /*
1756          * If we supported multiple encrytion contexts
1757          * here we'd look up based on tid.
1758          */
1759         if (common_encryption_on(conn->smb1.trans_enc)
1760             && (CVAL(inbuf, 0) == 0)) {
1761                 uint16_t enc_ctx_num;
1762
1763                 status = get_enc_ctx_num(inbuf, &enc_ctx_num);
1764                 if (!NT_STATUS_IS_OK(status)) {
1765                         DEBUG(10, ("get_enc_ctx_num returned %s\n",
1766                                    nt_errstr(status)));
1767                         return status;
1768                 }
1769
1770                 if (enc_ctx_num != conn->smb1.trans_enc->enc_ctx_num) {
1771                         DEBUG(10, ("wrong enc_ctx %d, expected %d\n",
1772                                    enc_ctx_num,
1773                                    conn->smb1.trans_enc->enc_ctx_num));
1774                         return NT_STATUS_INVALID_HANDLE;
1775                 }
1776
1777                 status = common_decrypt_buffer(conn->smb1.trans_enc,
1778                                                (char *)inbuf);
1779                 if (!NT_STATUS_IS_OK(status)) {
1780                         DEBUG(10, ("common_decrypt_buffer returned %s\n",
1781                                    nt_errstr(status)));
1782                         return status;
1783                 }
1784         }
1785
1786         mid = SVAL(inhdr, HDR_MID);
1787         num_pending = talloc_array_length(conn->pending);
1788
1789         for (i=0; i<num_pending; i++) {
1790                 if (mid == smb1cli_req_mid(conn->pending[i])) {
1791                         break;
1792                 }
1793         }
1794         if (i == num_pending) {
1795                 /* Dump unexpected reply */
1796                 return NT_STATUS_RETRY;
1797         }
1798
1799         oplock_break = false;
1800
1801         if (mid == 0xffff) {
1802                 /*
1803                  * Paranoia checks that this is really an oplock break request.
1804                  */
1805                 oplock_break = (smb_len_nbt(inbuf) == 51); /* hdr + 8 words */
1806                 oplock_break &= ((CVAL(inhdr, HDR_FLG) & FLAG_REPLY) == 0);
1807                 oplock_break &= (CVAL(inhdr, HDR_COM) == SMBlockingX);
1808                 oplock_break &= (SVAL(inhdr, HDR_VWV+VWV(6)) == 0);
1809                 oplock_break &= (SVAL(inhdr, HDR_VWV+VWV(7)) == 0);
1810
1811                 if (!oplock_break) {
1812                         /* Dump unexpected reply */
1813                         return NT_STATUS_RETRY;
1814                 }
1815         }
1816
1817         req = conn->pending[i];
1818         state = tevent_req_data(req, struct smbXcli_req_state);
1819
1820         if (!oplock_break /* oplock breaks are not signed */
1821             && !smb_signing_check_pdu(conn->smb1.signing,
1822                                       inbuf, state->smb1.seqnum+1)) {
1823                 DEBUG(10, ("cli_check_sign_mac failed\n"));
1824                 return NT_STATUS_ACCESS_DENIED;
1825         }
1826
1827         status = smb1cli_inbuf_parse_chain(inbuf, tmp_mem,
1828                                            &iov, &num_iov);
1829         if (!NT_STATUS_IS_OK(status)) {
1830                 DEBUG(10,("smb1cli_inbuf_parse_chain - %s\n",
1831                           nt_errstr(status)));
1832                 return status;
1833         }
1834
1835         cmd = CVAL(inhdr, HDR_COM);
1836         status = smb1cli_pull_raw_error(inhdr);
1837
1838         if (state->smb1.chained_requests == NULL) {
1839                 if (num_iov != 3) {
1840                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
1841                 }
1842
1843                 smbXcli_req_unset_pending(req);
1844
1845                 if (state->smb1.recv_iov == NULL) {
1846                         /*
1847                          * For requests with more than
1848                          * one response, we have to readd the
1849                          * recv_iov array.
1850                          */
1851                         state->smb1.recv_iov = talloc_zero_array(state,
1852                                                                  struct iovec,
1853                                                                  3);
1854                         if (tevent_req_nomem(state->smb1.recv_iov, req)) {
1855                                 return NT_STATUS_OK;
1856                         }
1857                 }
1858
1859                 state->smb1.recv_cmd = cmd;
1860                 state->smb1.recv_status = status;
1861                 state->inbuf = talloc_move(state->smb1.recv_iov, &inbuf);
1862
1863                 state->smb1.recv_iov[0] = iov[0];
1864                 state->smb1.recv_iov[1] = iov[1];
1865                 state->smb1.recv_iov[2] = iov[2];
1866
1867                 if (talloc_array_length(conn->pending) == 0) {
1868                         tevent_req_done(req);
1869                         return NT_STATUS_OK;
1870                 }
1871
1872                 tevent_req_defer_callback(req, state->ev);
1873                 tevent_req_done(req);
1874                 return NT_STATUS_RETRY;
1875         }
1876
1877         chain = talloc_move(tmp_mem, &state->smb1.chained_requests);
1878         num_chained = talloc_array_length(chain);
1879         num_responses = (num_iov - 1)/2;
1880
1881         if (num_responses > num_chained) {
1882                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1883         }
1884
1885         for (i=0; i<num_chained; i++) {
1886                 size_t iov_idx = 1 + (i*2);
1887                 struct iovec *cur = &iov[iov_idx];
1888                 uint8_t *inbuf_ref;
1889
1890                 req = chain[i];
1891                 state = tevent_req_data(req, struct smbXcli_req_state);
1892
1893                 smbXcli_req_unset_pending(req);
1894
1895                 /*
1896                  * as we finish multiple requests here
1897                  * we need to defer the callbacks as
1898                  * they could destroy our current stack state.
1899                  */
1900                 tevent_req_defer_callback(req, state->ev);
1901
1902                 if (i >= num_responses) {
1903                         tevent_req_nterror(req, NT_STATUS_REQUEST_ABORTED);
1904                         continue;
1905                 }
1906
1907                 if (state->smb1.recv_iov == NULL) {
1908                         /*
1909                          * For requests with more than
1910                          * one response, we have to readd the
1911                          * recv_iov array.
1912                          */
1913                         state->smb1.recv_iov = talloc_zero_array(state,
1914                                                                  struct iovec,
1915                                                                  3);
1916                         if (tevent_req_nomem(state->smb1.recv_iov, req)) {
1917                                 continue;
1918                         }
1919                 }
1920
1921                 state->smb1.recv_cmd = cmd;
1922
1923                 if (i == (num_responses - 1)) {
1924                         /*
1925                          * The last request in the chain gets the status
1926                          */
1927                         state->smb1.recv_status = status;
1928                 } else {
1929                         cmd = CVAL(cur[0].iov_base, 0);
1930                         state->smb1.recv_status = NT_STATUS_OK;
1931                 }
1932
1933                 state->inbuf = inbuf;
1934
1935                 /*
1936                  * Note: here we use talloc_reference() in a way
1937                  *       that does not expose it to the caller.
1938                  */
1939                 inbuf_ref = talloc_reference(state->smb1.recv_iov, inbuf);
1940                 if (tevent_req_nomem(inbuf_ref, req)) {
1941                         continue;
1942                 }
1943
1944                 /* copy the related buffers */
1945                 state->smb1.recv_iov[0] = iov[0];
1946                 state->smb1.recv_iov[1] = cur[0];
1947                 state->smb1.recv_iov[2] = cur[1];
1948
1949                 tevent_req_done(req);
1950         }
1951
1952         return NT_STATUS_RETRY;
1953 }
1954
1955 NTSTATUS smb1cli_req_recv(struct tevent_req *req,
1956                           TALLOC_CTX *mem_ctx,
1957                           struct iovec **piov,
1958                           uint8_t **phdr,
1959                           uint8_t *pwct,
1960                           uint16_t **pvwv,
1961                           uint32_t *pvwv_offset,
1962                           uint32_t *pnum_bytes,
1963                           uint8_t **pbytes,
1964                           uint32_t *pbytes_offset,
1965                           uint8_t **pinbuf,
1966                           const struct smb1cli_req_expected_response *expected,
1967                           size_t num_expected)
1968 {
1969         struct smbXcli_req_state *state =
1970                 tevent_req_data(req,
1971                 struct smbXcli_req_state);
1972         NTSTATUS status = NT_STATUS_OK;
1973         struct iovec *recv_iov = NULL;
1974         uint8_t *hdr = NULL;
1975         uint8_t wct = 0;
1976         uint32_t vwv_offset = 0;
1977         uint16_t *vwv = NULL;
1978         uint32_t num_bytes = 0;
1979         uint32_t bytes_offset = 0;
1980         uint8_t *bytes = NULL;
1981         size_t i;
1982         bool found_status = false;
1983         bool found_size = false;
1984
1985         if (piov != NULL) {
1986                 *piov = NULL;
1987         }
1988         if (phdr != NULL) {
1989                 *phdr = 0;
1990         }
1991         if (pwct != NULL) {
1992                 *pwct = 0;
1993         }
1994         if (pvwv != NULL) {
1995                 *pvwv = NULL;
1996         }
1997         if (pvwv_offset != NULL) {
1998                 *pvwv_offset = 0;
1999         }
2000         if (pnum_bytes != NULL) {
2001                 *pnum_bytes = 0;
2002         }
2003         if (pbytes != NULL) {
2004                 *pbytes = NULL;
2005         }
2006         if (pbytes_offset != NULL) {
2007                 *pbytes_offset = 0;
2008         }
2009         if (pinbuf != NULL) {
2010                 *pinbuf = NULL;
2011         }
2012
2013         if (state->inbuf != NULL) {
2014                 recv_iov = state->smb1.recv_iov;
2015                 state->smb1.recv_iov = NULL;
2016                 if (state->smb1.recv_cmd != SMBreadBraw) {
2017                         hdr = (uint8_t *)recv_iov[0].iov_base;
2018                         wct = recv_iov[1].iov_len/2;
2019                         vwv = (uint16_t *)recv_iov[1].iov_base;
2020                         vwv_offset = PTR_DIFF(vwv, hdr);
2021                         num_bytes = recv_iov[2].iov_len;
2022                         bytes = (uint8_t *)recv_iov[2].iov_base;
2023                         bytes_offset = PTR_DIFF(bytes, hdr);
2024                 }
2025         }
2026
2027         if (tevent_req_is_nterror(req, &status)) {
2028                 for (i=0; i < num_expected; i++) {
2029                         if (NT_STATUS_EQUAL(status, expected[i].status)) {
2030                                 found_status = true;
2031                                 break;
2032                         }
2033                 }
2034
2035                 if (found_status) {
2036                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
2037                 }
2038
2039                 return status;
2040         }
2041
2042         if (num_expected == 0) {
2043                 found_status = true;
2044                 found_size = true;
2045         }
2046
2047         status = state->smb1.recv_status;
2048
2049         for (i=0; i < num_expected; i++) {
2050                 if (!NT_STATUS_EQUAL(status, expected[i].status)) {
2051                         continue;
2052                 }
2053
2054                 found_status = true;
2055                 if (expected[i].wct == 0) {
2056                         found_size = true;
2057                         break;
2058                 }
2059
2060                 if (expected[i].wct == wct) {
2061                         found_size = true;
2062                         break;
2063                 }
2064         }
2065
2066         if (!found_status) {
2067                 return status;
2068         }
2069
2070         if (!found_size) {
2071                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2072         }
2073
2074         if (piov != NULL) {
2075                 *piov = talloc_move(mem_ctx, &recv_iov);
2076         }
2077
2078         if (phdr != NULL) {
2079                 *phdr = hdr;
2080         }
2081         if (pwct != NULL) {
2082                 *pwct = wct;
2083         }
2084         if (pvwv != NULL) {
2085                 *pvwv = vwv;
2086         }
2087         if (pvwv_offset != NULL) {
2088                 *pvwv_offset = vwv_offset;
2089         }
2090         if (pnum_bytes != NULL) {
2091                 *pnum_bytes = num_bytes;
2092         }
2093         if (pbytes != NULL) {
2094                 *pbytes = bytes;
2095         }
2096         if (pbytes_offset != NULL) {
2097                 *pbytes_offset = bytes_offset;
2098         }
2099         if (pinbuf != NULL) {
2100                 *pinbuf = state->inbuf;
2101         }
2102
2103         return status;
2104 }
2105
2106 size_t smb1cli_req_wct_ofs(struct tevent_req **reqs, int num_reqs)
2107 {
2108         size_t wct_ofs;
2109         int i;
2110
2111         wct_ofs = HDR_WCT;
2112
2113         for (i=0; i<num_reqs; i++) {
2114                 struct smbXcli_req_state *state;
2115                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2116                 wct_ofs += smbXcli_iov_len(state->smb1.iov+2,
2117                                            state->smb1.iov_count-2);
2118                 wct_ofs = (wct_ofs + 3) & ~3;
2119         }
2120         return wct_ofs;
2121 }
2122
2123 NTSTATUS smb1cli_req_chain_submit(struct tevent_req **reqs, int num_reqs)
2124 {
2125         struct smbXcli_req_state *first_state =
2126                 tevent_req_data(reqs[0],
2127                 struct smbXcli_req_state);
2128         struct smbXcli_req_state *state;
2129         size_t wct_offset;
2130         size_t chain_padding = 0;
2131         int i, iovlen;
2132         struct iovec *iov = NULL;
2133         struct iovec *this_iov;
2134         NTSTATUS status;
2135         size_t nbt_len;
2136
2137         if (num_reqs == 1) {
2138                 return smb1cli_req_writev_submit(reqs[0], first_state,
2139                                                  first_state->smb1.iov,
2140                                                  first_state->smb1.iov_count);
2141         }
2142
2143         iovlen = 0;
2144         for (i=0; i<num_reqs; i++) {
2145                 if (!tevent_req_is_in_progress(reqs[i])) {
2146                         return NT_STATUS_INTERNAL_ERROR;
2147                 }
2148
2149                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2150
2151                 if (state->smb1.iov_count < 4) {
2152                         return NT_STATUS_INVALID_PARAMETER_MIX;
2153                 }
2154
2155                 if (i == 0) {
2156                         /*
2157                          * The NBT and SMB header
2158                          */
2159                         iovlen += 2;
2160                 } else {
2161                         /*
2162                          * Chain padding
2163                          */
2164                         iovlen += 1;
2165                 }
2166
2167                 /*
2168                  * words and bytes
2169                  */
2170                 iovlen += state->smb1.iov_count - 2;
2171         }
2172
2173         iov = talloc_zero_array(first_state, struct iovec, iovlen);
2174         if (iov == NULL) {
2175                 return NT_STATUS_NO_MEMORY;
2176         }
2177
2178         first_state->smb1.chained_requests = (struct tevent_req **)talloc_memdup(
2179                 first_state, reqs, sizeof(*reqs) * num_reqs);
2180         if (first_state->smb1.chained_requests == NULL) {
2181                 TALLOC_FREE(iov);
2182                 return NT_STATUS_NO_MEMORY;
2183         }
2184
2185         wct_offset = HDR_WCT;
2186         this_iov = iov;
2187
2188         for (i=0; i<num_reqs; i++) {
2189                 size_t next_padding = 0;
2190                 uint16_t *vwv;
2191
2192                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2193
2194                 if (i < num_reqs-1) {
2195                         if (!smb1cli_is_andx_req(CVAL(state->smb1.hdr, HDR_COM))
2196                             || CVAL(state->smb1.hdr, HDR_WCT) < 2) {
2197                                 TALLOC_FREE(iov);
2198                                 TALLOC_FREE(first_state->smb1.chained_requests);
2199                                 return NT_STATUS_INVALID_PARAMETER_MIX;
2200                         }
2201                 }
2202
2203                 wct_offset += smbXcli_iov_len(state->smb1.iov+2,
2204                                               state->smb1.iov_count-2) + 1;
2205                 if ((wct_offset % 4) != 0) {
2206                         next_padding = 4 - (wct_offset % 4);
2207                 }
2208                 wct_offset += next_padding;
2209                 vwv = state->smb1.vwv;
2210
2211                 if (i < num_reqs-1) {
2212                         struct smbXcli_req_state *next_state =
2213                                 tevent_req_data(reqs[i+1],
2214                                 struct smbXcli_req_state);
2215                         SCVAL(vwv+0, 0, CVAL(next_state->smb1.hdr, HDR_COM));
2216                         SCVAL(vwv+0, 1, 0);
2217                         SSVAL(vwv+1, 0, wct_offset);
2218                 } else if (smb1cli_is_andx_req(CVAL(state->smb1.hdr, HDR_COM))) {
2219                         /* properly end the chain */
2220                         SCVAL(vwv+0, 0, 0xff);
2221                         SCVAL(vwv+0, 1, 0xff);
2222                         SSVAL(vwv+1, 0, 0);
2223                 }
2224
2225                 if (i == 0) {
2226                         /*
2227                          * The NBT and SMB header
2228                          */
2229                         this_iov[0] = state->smb1.iov[0];
2230                         this_iov[1] = state->smb1.iov[1];
2231                         this_iov += 2;
2232                 } else {
2233                         /*
2234                          * This one is a bit subtle. We have to add
2235                          * chain_padding bytes between the requests, and we
2236                          * have to also include the wct field of the
2237                          * subsequent requests. We use the subsequent header
2238                          * for the padding, it contains the wct field in its
2239                          * last byte.
2240                          */
2241                         this_iov[0].iov_len = chain_padding+1;
2242                         this_iov[0].iov_base = (void *)&state->smb1.hdr[
2243                                 sizeof(state->smb1.hdr) - this_iov[0].iov_len];
2244                         memset(this_iov[0].iov_base, 0, this_iov[0].iov_len-1);
2245                         this_iov += 1;
2246                 }
2247
2248                 /*
2249                  * copy the words and bytes
2250                  */
2251                 memcpy(this_iov, state->smb1.iov+2,
2252                        sizeof(struct iovec) * (state->smb1.iov_count-2));
2253                 this_iov += state->smb1.iov_count - 2;
2254                 chain_padding = next_padding;
2255         }
2256
2257         nbt_len = smbXcli_iov_len(&iov[1], iovlen-1);
2258         if (nbt_len > first_state->conn->smb1.max_xmit) {
2259                 TALLOC_FREE(iov);
2260                 TALLOC_FREE(first_state->smb1.chained_requests);
2261                 return NT_STATUS_INVALID_PARAMETER_MIX;
2262         }
2263
2264         status = smb1cli_req_writev_submit(reqs[0], first_state, iov, iovlen);
2265         if (!NT_STATUS_IS_OK(status)) {
2266                 TALLOC_FREE(iov);
2267                 TALLOC_FREE(first_state->smb1.chained_requests);
2268                 return status;
2269         }
2270
2271         return NT_STATUS_OK;
2272 }
2273
2274 bool smbXcli_conn_has_async_calls(struct smbXcli_conn *conn)
2275 {
2276         return ((tevent_queue_length(conn->outgoing) != 0)
2277                 || (talloc_array_length(conn->pending) != 0));
2278 }
2279
2280 uint32_t smb2cli_conn_server_capabilities(struct smbXcli_conn *conn)
2281 {
2282         return conn->smb2.server.capabilities;
2283 }
2284
2285 uint16_t smb2cli_conn_server_security_mode(struct smbXcli_conn *conn)
2286 {
2287         return conn->smb2.server.security_mode;
2288 }
2289
2290 uint32_t smb2cli_conn_max_trans_size(struct smbXcli_conn *conn)
2291 {
2292         return conn->smb2.server.max_trans_size;
2293 }
2294
2295 uint32_t smb2cli_conn_max_read_size(struct smbXcli_conn *conn)
2296 {
2297         return conn->smb2.server.max_read_size;
2298 }
2299
2300 uint32_t smb2cli_conn_max_write_size(struct smbXcli_conn *conn)
2301 {
2302         return conn->smb2.server.max_write_size;
2303 }
2304
2305 void smb2cli_conn_set_max_credits(struct smbXcli_conn *conn,
2306                                   uint16_t max_credits)
2307 {
2308         conn->smb2.max_credits = max_credits;
2309 }
2310
2311 static void smb2cli_req_cancel_done(struct tevent_req *subreq);
2312
2313 static bool smb2cli_req_cancel(struct tevent_req *req)
2314 {
2315         struct smbXcli_req_state *state =
2316                 tevent_req_data(req,
2317                 struct smbXcli_req_state);
2318         uint32_t flags = IVAL(state->smb2.hdr, SMB2_HDR_FLAGS);
2319         uint32_t pid = IVAL(state->smb2.hdr, SMB2_HDR_PID);
2320         uint32_t tid = IVAL(state->smb2.hdr, SMB2_HDR_TID);
2321         uint64_t mid = BVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID);
2322         uint64_t aid = BVAL(state->smb2.hdr, SMB2_HDR_ASYNC_ID);
2323         struct smbXcli_session *session = state->session;
2324         uint8_t *fixed = state->smb2.pad;
2325         uint16_t fixed_len = 4;
2326         struct tevent_req *subreq;
2327         struct smbXcli_req_state *substate;
2328         NTSTATUS status;
2329
2330         SSVAL(fixed, 0, 0x04);
2331         SSVAL(fixed, 2, 0);
2332
2333         subreq = smb2cli_req_create(state, state->ev,
2334                                     state->conn,
2335                                     SMB2_OP_CANCEL,
2336                                     flags, 0,
2337                                     0, /* timeout */
2338                                     pid, tid, session,
2339                                     fixed, fixed_len,
2340                                     NULL, 0);
2341         if (subreq == NULL) {
2342                 return false;
2343         }
2344         substate = tevent_req_data(subreq, struct smbXcli_req_state);
2345
2346         if (flags & SMB2_HDR_FLAG_ASYNC) {
2347                 mid = 0;
2348         }
2349
2350         SIVAL(substate->smb2.hdr, SMB2_HDR_FLAGS, flags);
2351         SIVAL(substate->smb2.hdr, SMB2_HDR_PID, pid);
2352         SIVAL(substate->smb2.hdr, SMB2_HDR_TID, tid);
2353         SBVAL(substate->smb2.hdr, SMB2_HDR_MESSAGE_ID, mid);
2354         SBVAL(substate->smb2.hdr, SMB2_HDR_ASYNC_ID, aid);
2355
2356         status = smb2cli_req_compound_submit(&subreq, 1);
2357         if (!NT_STATUS_IS_OK(status)) {
2358                 TALLOC_FREE(subreq);
2359                 return false;
2360         }
2361
2362         tevent_req_set_callback(subreq, smb2cli_req_cancel_done, NULL);
2363
2364         return true;
2365 }
2366
2367 static void smb2cli_req_cancel_done(struct tevent_req *subreq)
2368 {
2369         /* we do not care about the result */
2370         TALLOC_FREE(subreq);
2371 }
2372
2373 struct tevent_req *smb2cli_req_create(TALLOC_CTX *mem_ctx,
2374                                       struct tevent_context *ev,
2375                                       struct smbXcli_conn *conn,
2376                                       uint16_t cmd,
2377                                       uint32_t additional_flags,
2378                                       uint32_t clear_flags,
2379                                       uint32_t timeout_msec,
2380                                       uint32_t pid,
2381                                       uint32_t tid,
2382                                       struct smbXcli_session *session,
2383                                       const uint8_t *fixed,
2384                                       uint16_t fixed_len,
2385                                       const uint8_t *dyn,
2386                                       uint32_t dyn_len)
2387 {
2388         struct tevent_req *req;
2389         struct smbXcli_req_state *state;
2390         uint32_t flags = 0;
2391         uint64_t uid = 0;
2392
2393         req = tevent_req_create(mem_ctx, &state,
2394                                 struct smbXcli_req_state);
2395         if (req == NULL) {
2396                 return NULL;
2397         }
2398
2399         state->ev = ev;
2400         state->conn = conn;
2401         state->session = session;
2402
2403         if (session) {
2404                 uid = session->smb2.session_id;
2405         }
2406
2407         state->smb2.recv_iov = talloc_zero_array(state, struct iovec, 3);
2408         if (state->smb2.recv_iov == NULL) {
2409                 TALLOC_FREE(req);
2410                 return NULL;
2411         }
2412
2413         flags |= additional_flags;
2414         flags &= ~clear_flags;
2415
2416         state->smb2.fixed = fixed;
2417         state->smb2.fixed_len = fixed_len;
2418         state->smb2.dyn = dyn;
2419         state->smb2.dyn_len = dyn_len;
2420
2421         SIVAL(state->smb2.hdr, SMB2_HDR_PROTOCOL_ID,    SMB2_MAGIC);
2422         SSVAL(state->smb2.hdr, SMB2_HDR_LENGTH,         SMB2_HDR_BODY);
2423         SSVAL(state->smb2.hdr, SMB2_HDR_OPCODE,         cmd);
2424         SIVAL(state->smb2.hdr, SMB2_HDR_FLAGS,          flags);
2425         SIVAL(state->smb2.hdr, SMB2_HDR_PID,            pid);
2426         SIVAL(state->smb2.hdr, SMB2_HDR_TID,            tid);
2427         SBVAL(state->smb2.hdr, SMB2_HDR_SESSION_ID,     uid);
2428
2429         switch (cmd) {
2430         case SMB2_OP_CANCEL:
2431                 state->one_way = true;
2432                 break;
2433         case SMB2_OP_BREAK:
2434                 /*
2435                  * If this is a dummy request, it will have
2436                  * UINT64_MAX as message id.
2437                  * If we send on break acknowledgement,
2438                  * this gets overwritten later.
2439                  */
2440                 SBVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID, UINT64_MAX);
2441                 break;
2442         }
2443
2444         if (timeout_msec > 0) {
2445                 struct timeval endtime;
2446
2447                 endtime = timeval_current_ofs_msec(timeout_msec);
2448                 if (!tevent_req_set_endtime(req, ev, endtime)) {
2449                         return req;
2450                 }
2451         }
2452
2453         return req;
2454 }
2455
2456 void smb2cli_req_set_notify_async(struct tevent_req *req)
2457 {
2458         struct smbXcli_req_state *state =
2459                 tevent_req_data(req,
2460                 struct smbXcli_req_state);
2461
2462         state->smb2.notify_async = true;
2463 }
2464
2465 static void smb2cli_req_writev_done(struct tevent_req *subreq);
2466 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
2467                                                TALLOC_CTX *tmp_mem,
2468                                                uint8_t *inbuf);
2469
2470 NTSTATUS smb2cli_req_compound_submit(struct tevent_req **reqs,
2471                                      int num_reqs)
2472 {
2473         struct smbXcli_req_state *state;
2474         struct tevent_req *subreq;
2475         struct iovec *iov;
2476         int i, num_iov, nbt_len;
2477
2478         /*
2479          * 1 for the nbt length
2480          * per request: HDR, fixed, dyn, padding
2481          * -1 because the last one does not need padding
2482          */
2483
2484         iov = talloc_array(reqs[0], struct iovec, 1 + 4*num_reqs - 1);
2485         if (iov == NULL) {
2486                 return NT_STATUS_NO_MEMORY;
2487         }
2488
2489         num_iov = 1;
2490         nbt_len = 0;
2491
2492         for (i=0; i<num_reqs; i++) {
2493                 int hdr_iov;
2494                 size_t reqlen;
2495                 bool ret;
2496                 uint16_t opcode;
2497                 uint64_t avail;
2498                 uint16_t charge;
2499                 uint16_t credits;
2500                 uint64_t mid;
2501                 const DATA_BLOB *signing_key = NULL;
2502
2503                 if (!tevent_req_is_in_progress(reqs[i])) {
2504                         return NT_STATUS_INTERNAL_ERROR;
2505                 }
2506
2507                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2508
2509                 if (!smbXcli_conn_is_connected(state->conn)) {
2510                         return NT_STATUS_CONNECTION_DISCONNECTED;
2511                 }
2512
2513                 if ((state->conn->protocol != PROTOCOL_NONE) &&
2514                     (state->conn->protocol < PROTOCOL_SMB2_02)) {
2515                         return NT_STATUS_REVISION_MISMATCH;
2516                 }
2517
2518                 opcode = SVAL(state->smb2.hdr, SMB2_HDR_OPCODE);
2519                 if (opcode == SMB2_OP_CANCEL) {
2520                         goto skip_credits;
2521                 }
2522
2523                 avail = UINT64_MAX - state->conn->smb2.mid;
2524                 if (avail < 1) {
2525                         return NT_STATUS_CONNECTION_ABORTED;
2526                 }
2527
2528                 if (state->conn->smb2.server.capabilities & SMB2_CAP_LARGE_MTU) {
2529                         charge = (MAX(state->smb2.dyn_len, 1) - 1)/ 65536 + 1;
2530                 } else {
2531                         charge = 1;
2532                 }
2533
2534                 charge = MAX(state->smb2.credit_charge, charge);
2535
2536                 avail = MIN(avail, state->conn->smb2.cur_credits);
2537                 if (avail < charge) {
2538                         return NT_STATUS_INTERNAL_ERROR;
2539                 }
2540
2541                 credits = 0;
2542                 if (state->conn->smb2.max_credits > state->conn->smb2.cur_credits) {
2543                         credits = state->conn->smb2.max_credits -
2544                                   state->conn->smb2.cur_credits;
2545                 }
2546                 if (state->conn->smb2.max_credits >= state->conn->smb2.cur_credits) {
2547                         credits += 1;
2548                 }
2549
2550                 mid = state->conn->smb2.mid;
2551                 state->conn->smb2.mid += charge;
2552                 state->conn->smb2.cur_credits -= charge;
2553
2554                 if (state->conn->smb2.server.capabilities & SMB2_CAP_LARGE_MTU) {
2555                         SSVAL(state->smb2.hdr, SMB2_HDR_CREDIT_CHARGE, charge);
2556                 }
2557                 SSVAL(state->smb2.hdr, SMB2_HDR_CREDIT, credits);
2558                 SBVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID, mid);
2559
2560 skip_credits:
2561                 hdr_iov = num_iov;
2562                 iov[num_iov].iov_base = state->smb2.hdr;
2563                 iov[num_iov].iov_len  = sizeof(state->smb2.hdr);
2564                 num_iov += 1;
2565
2566                 iov[num_iov].iov_base = discard_const(state->smb2.fixed);
2567                 iov[num_iov].iov_len  = state->smb2.fixed_len;
2568                 num_iov += 1;
2569
2570                 if (state->smb2.dyn != NULL) {
2571                         iov[num_iov].iov_base = discard_const(state->smb2.dyn);
2572                         iov[num_iov].iov_len  = state->smb2.dyn_len;
2573                         num_iov += 1;
2574                 }
2575
2576                 reqlen  = sizeof(state->smb2.hdr);
2577                 reqlen += state->smb2.fixed_len;
2578                 reqlen += state->smb2.dyn_len;
2579
2580                 if (i < num_reqs-1) {
2581                         if ((reqlen % 8) > 0) {
2582                                 uint8_t pad = 8 - (reqlen % 8);
2583                                 iov[num_iov].iov_base = state->smb2.pad;
2584                                 iov[num_iov].iov_len = pad;
2585                                 num_iov += 1;
2586                                 reqlen += pad;
2587                         }
2588                         SIVAL(state->smb2.hdr, SMB2_HDR_NEXT_COMMAND, reqlen);
2589                 }
2590                 nbt_len += reqlen;
2591
2592                 if (state->session) {
2593                         bool should_sign = state->session->smb2.should_sign;
2594
2595                         if (opcode == SMB2_OP_SESSSETUP &&
2596                             state->session->smb2.signing_key.length != 0) {
2597                                 should_sign = true;
2598                         }
2599
2600                         /*
2601                          * We prefer the channel signing key if it is
2602                          * already there.
2603                          */
2604                         if (should_sign) {
2605                                 signing_key = &state->session->smb2.channel_signing_key;
2606                         }
2607
2608                         /*
2609                          * If it is a channel binding, we already have the main
2610                          * signing key and try that one.
2611                          */
2612                         if (signing_key && signing_key->length == 0) {
2613                                 signing_key = &state->session->smb2.signing_key;
2614                         }
2615
2616                         /*
2617                          * If we do not have any session key yet, we skip the
2618                          * signing of SMB2_OP_SESSSETUP requests.
2619                          */
2620                         if (signing_key && signing_key->length == 0) {
2621                                 signing_key = NULL;
2622                         }
2623                 }
2624
2625                 if (signing_key) {
2626                         NTSTATUS status;
2627
2628                         status = smb2_signing_sign_pdu(*signing_key,
2629                                                        state->session->conn->protocol,
2630                                                        &iov[hdr_iov], num_iov - hdr_iov);
2631                         if (!NT_STATUS_IS_OK(status)) {
2632                                 return status;
2633                         }
2634                 }
2635
2636                 ret = smbXcli_req_set_pending(reqs[i]);
2637                 if (!ret) {
2638                         return NT_STATUS_NO_MEMORY;
2639                 }
2640         }
2641
2642         state = tevent_req_data(reqs[0], struct smbXcli_req_state);
2643         _smb_setlen_tcp(state->length_hdr, nbt_len);
2644         iov[0].iov_base = state->length_hdr;
2645         iov[0].iov_len  = sizeof(state->length_hdr);
2646
2647         if (state->conn->dispatch_incoming == NULL) {
2648                 state->conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
2649         }
2650
2651         subreq = writev_send(state, state->ev, state->conn->outgoing,
2652                              state->conn->write_fd, false, iov, num_iov);
2653         if (subreq == NULL) {
2654                 return NT_STATUS_NO_MEMORY;
2655         }
2656         tevent_req_set_callback(subreq, smb2cli_req_writev_done, reqs[0]);
2657         return NT_STATUS_OK;
2658 }
2659
2660 void smb2cli_req_set_credit_charge(struct tevent_req *req, uint16_t charge)
2661 {
2662         struct smbXcli_req_state *state =
2663                 tevent_req_data(req,
2664                 struct smbXcli_req_state);
2665
2666         state->smb2.credit_charge = charge;
2667 }
2668
2669 struct tevent_req *smb2cli_req_send(TALLOC_CTX *mem_ctx,
2670                                     struct tevent_context *ev,
2671                                     struct smbXcli_conn *conn,
2672                                     uint16_t cmd,
2673                                     uint32_t additional_flags,
2674                                     uint32_t clear_flags,
2675                                     uint32_t timeout_msec,
2676                                     uint32_t pid,
2677                                     uint32_t tid,
2678                                     struct smbXcli_session *session,
2679                                     const uint8_t *fixed,
2680                                     uint16_t fixed_len,
2681                                     const uint8_t *dyn,
2682                                     uint32_t dyn_len)
2683 {
2684         struct tevent_req *req;
2685         NTSTATUS status;
2686
2687         req = smb2cli_req_create(mem_ctx, ev, conn, cmd,
2688                                  additional_flags, clear_flags,
2689                                  timeout_msec,
2690                                  pid, tid, session,
2691                                  fixed, fixed_len, dyn, dyn_len);
2692         if (req == NULL) {
2693                 return NULL;
2694         }
2695         if (!tevent_req_is_in_progress(req)) {
2696                 return tevent_req_post(req, ev);
2697         }
2698         status = smb2cli_req_compound_submit(&req, 1);
2699         if (tevent_req_nterror(req, status)) {
2700                 return tevent_req_post(req, ev);
2701         }
2702         return req;
2703 }
2704
2705 static void smb2cli_req_writev_done(struct tevent_req *subreq)
2706 {
2707         struct tevent_req *req =
2708                 tevent_req_callback_data(subreq,
2709                 struct tevent_req);
2710         struct smbXcli_req_state *state =
2711                 tevent_req_data(req,
2712                 struct smbXcli_req_state);
2713         ssize_t nwritten;
2714         int err;
2715
2716         nwritten = writev_recv(subreq, &err);
2717         TALLOC_FREE(subreq);
2718         if (nwritten == -1) {
2719                 /* here, we need to notify all pending requests */
2720                 NTSTATUS status = map_nt_error_from_unix_common(err);
2721                 smbXcli_conn_disconnect(state->conn, status);
2722                 return;
2723         }
2724 }
2725
2726 static NTSTATUS smb2cli_inbuf_parse_compound(uint8_t *buf, TALLOC_CTX *mem_ctx,
2727                                              struct iovec **piov, int *pnum_iov)
2728 {
2729         struct iovec *iov;
2730         int num_iov;
2731         size_t buflen;
2732         size_t taken;
2733         uint8_t *first_hdr;
2734
2735         num_iov = 0;
2736
2737         iov = talloc_array(mem_ctx, struct iovec, num_iov);
2738         if (iov == NULL) {
2739                 return NT_STATUS_NO_MEMORY;
2740         }
2741
2742         buflen = smb_len_tcp(buf);
2743         taken = 0;
2744         first_hdr = buf + NBT_HDR_SIZE;
2745
2746         while (taken < buflen) {
2747                 size_t len = buflen - taken;
2748                 uint8_t *hdr = first_hdr + taken;
2749                 struct iovec *cur;
2750                 size_t full_size;
2751                 size_t next_command_ofs;
2752                 uint16_t body_size;
2753                 struct iovec *iov_tmp;
2754
2755                 /*
2756                  * We need the header plus the body length field
2757                  */
2758
2759                 if (len < SMB2_HDR_BODY + 2) {
2760                         DEBUG(10, ("%d bytes left, expected at least %d\n",
2761                                    (int)len, SMB2_HDR_BODY));
2762                         goto inval;
2763                 }
2764                 if (IVAL(hdr, 0) != SMB2_MAGIC) {
2765                         DEBUG(10, ("Got non-SMB2 PDU: %x\n",
2766                                    IVAL(hdr, 0)));
2767                         goto inval;
2768                 }
2769                 if (SVAL(hdr, 4) != SMB2_HDR_BODY) {
2770                         DEBUG(10, ("Got HDR len %d, expected %d\n",
2771                                    SVAL(hdr, 4), SMB2_HDR_BODY));
2772                         goto inval;
2773                 }
2774
2775                 full_size = len;
2776                 next_command_ofs = IVAL(hdr, SMB2_HDR_NEXT_COMMAND);
2777                 body_size = SVAL(hdr, SMB2_HDR_BODY);
2778
2779                 if (next_command_ofs != 0) {
2780                         if (next_command_ofs < (SMB2_HDR_BODY + 2)) {
2781                                 goto inval;
2782                         }
2783                         if (next_command_ofs > full_size) {
2784                                 goto inval;
2785                         }
2786                         full_size = next_command_ofs;
2787                 }
2788                 if (body_size < 2) {
2789                         goto inval;
2790                 }
2791                 body_size &= 0xfffe;
2792
2793                 if (body_size > (full_size - SMB2_HDR_BODY)) {
2794                         goto inval;
2795                 }
2796
2797                 iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
2798                                          num_iov + 3);
2799                 if (iov_tmp == NULL) {
2800                         TALLOC_FREE(iov);
2801                         return NT_STATUS_NO_MEMORY;
2802                 }
2803                 iov = iov_tmp;
2804                 cur = &iov[num_iov];
2805                 num_iov += 3;
2806
2807                 cur[0].iov_base = hdr;
2808                 cur[0].iov_len  = SMB2_HDR_BODY;
2809                 cur[1].iov_base = hdr + SMB2_HDR_BODY;
2810                 cur[1].iov_len  = body_size;
2811                 cur[2].iov_base = hdr + SMB2_HDR_BODY + body_size;
2812                 cur[2].iov_len  = full_size - (SMB2_HDR_BODY + body_size);
2813
2814                 taken += full_size;
2815         }
2816
2817         *piov = iov;
2818         *pnum_iov = num_iov;
2819         return NT_STATUS_OK;
2820
2821 inval:
2822         TALLOC_FREE(iov);
2823         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2824 }
2825
2826 static struct tevent_req *smb2cli_conn_find_pending(struct smbXcli_conn *conn,
2827                                                     uint64_t mid)
2828 {
2829         size_t num_pending = talloc_array_length(conn->pending);
2830         size_t i;
2831
2832         for (i=0; i<num_pending; i++) {
2833                 struct tevent_req *req = conn->pending[i];
2834                 struct smbXcli_req_state *state =
2835                         tevent_req_data(req,
2836                         struct smbXcli_req_state);
2837
2838                 if (mid == BVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID)) {
2839                         return req;
2840                 }
2841         }
2842         return NULL;
2843 }
2844
2845 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
2846                                                TALLOC_CTX *tmp_mem,
2847                                                uint8_t *inbuf)
2848 {
2849         struct tevent_req *req;
2850         struct smbXcli_req_state *state = NULL;
2851         struct iovec *iov;
2852         int i, num_iov;
2853         NTSTATUS status;
2854         bool defer = true;
2855         struct smbXcli_session *last_session = NULL;
2856
2857         status = smb2cli_inbuf_parse_compound(inbuf, tmp_mem,
2858                                               &iov, &num_iov);
2859         if (!NT_STATUS_IS_OK(status)) {
2860                 return status;
2861         }
2862
2863         for (i=0; i<num_iov; i+=3) {
2864                 uint8_t *inbuf_ref = NULL;
2865                 struct iovec *cur = &iov[i];
2866                 uint8_t *inhdr = (uint8_t *)cur[0].iov_base;
2867                 uint16_t opcode = SVAL(inhdr, SMB2_HDR_OPCODE);
2868                 uint32_t flags = IVAL(inhdr, SMB2_HDR_FLAGS);
2869                 uint64_t mid = BVAL(inhdr, SMB2_HDR_MESSAGE_ID);
2870                 uint16_t req_opcode;
2871                 uint32_t req_flags;
2872                 uint16_t credits = SVAL(inhdr, SMB2_HDR_CREDIT);
2873                 uint32_t new_credits;
2874                 struct smbXcli_session *session = NULL;
2875                 const DATA_BLOB *signing_key = NULL;
2876                 bool should_sign = false;
2877
2878                 new_credits = conn->smb2.cur_credits;
2879                 new_credits += credits;
2880                 if (new_credits > UINT16_MAX) {
2881                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2882                 }
2883                 conn->smb2.cur_credits += credits;
2884
2885                 req = smb2cli_conn_find_pending(conn, mid);
2886                 if (req == NULL) {
2887                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2888                 }
2889                 state = tevent_req_data(req, struct smbXcli_req_state);
2890
2891                 state->smb2.got_async = false;
2892
2893                 req_opcode = SVAL(state->smb2.hdr, SMB2_HDR_OPCODE);
2894                 if (opcode != req_opcode) {
2895                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2896                 }
2897                 req_flags = SVAL(state->smb2.hdr, SMB2_HDR_FLAGS);
2898
2899                 if (!(flags & SMB2_HDR_FLAG_REDIRECT)) {
2900                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2901                 }
2902
2903                 status = NT_STATUS(IVAL(inhdr, SMB2_HDR_STATUS));
2904                 if ((flags & SMB2_HDR_FLAG_ASYNC) &&
2905                     NT_STATUS_EQUAL(status, STATUS_PENDING)) {
2906                         uint64_t async_id = BVAL(inhdr, SMB2_HDR_ASYNC_ID);
2907
2908                         /*
2909                          * async interim responses are not signed,
2910                          * even if the SMB2_HDR_FLAG_SIGNED flag
2911                          * is set.
2912                          */
2913                         req_flags |= SMB2_HDR_FLAG_ASYNC;
2914                         SBVAL(state->smb2.hdr, SMB2_HDR_FLAGS, req_flags);
2915                         SBVAL(state->smb2.hdr, SMB2_HDR_ASYNC_ID, async_id);
2916
2917                         if (state->smb2.notify_async) {
2918                                 state->smb2.got_async = true;
2919                                 tevent_req_defer_callback(req, state->ev);
2920                                 tevent_req_notify_callback(req);
2921                         }
2922                         continue;
2923                 }
2924
2925                 session = state->session;
2926                 if (req_flags & SMB2_HDR_FLAG_CHAINED) {
2927                         session = last_session;
2928                 }
2929                 last_session = session;
2930
2931                 if (session) {
2932                         should_sign = session->smb2.should_sign;
2933                         if (opcode == SMB2_OP_SESSSETUP &&
2934                             session->smb2.signing_key.length != 0) {
2935                                 should_sign = true;
2936                         }
2937                 }
2938
2939                 if (should_sign) {
2940                         if (!(flags & SMB2_HDR_FLAG_SIGNED)) {
2941                                 return NT_STATUS_ACCESS_DENIED;
2942                         }
2943                 }
2944
2945                 if (flags & SMB2_HDR_FLAG_SIGNED) {
2946                         uint64_t uid = BVAL(inhdr, SMB2_HDR_SESSION_ID);
2947
2948                         if (session == NULL) {
2949                                 struct smbXcli_session *s;
2950
2951                                 s = state->conn->sessions;
2952                                 for (; s; s = s->next) {
2953                                         if (s->smb2.session_id != uid) {
2954                                                 continue;
2955                                         }
2956
2957                                         session = s;
2958                                         break;
2959                                 }
2960                         }
2961
2962                         if (session == NULL) {
2963                                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2964                         }
2965
2966                         last_session = session;
2967                         signing_key = &session->smb2.channel_signing_key;
2968                 }
2969
2970                 if (opcode == SMB2_OP_SESSSETUP) {
2971                         /*
2972                          * We prefer the channel signing key, if it is
2973                          * already there.
2974                          *
2975                          * If we do not have a channel signing key yet,
2976                          * we try the main signing key, if it is not
2977                          * the final response.
2978                          */
2979                         if (signing_key && signing_key->length == 0 &&
2980                             !NT_STATUS_IS_OK(status)) {
2981                                 signing_key = &session->smb2.signing_key;
2982                         }
2983
2984                         if (signing_key && signing_key->length == 0) {
2985                                 /*
2986                                  * If we do not have a session key to
2987                                  * verify the signature, we defer the
2988                                  * signing check to the caller.
2989                                  *
2990                                  * The caller gets NT_STATUS_OK, it
2991                                  * has to call
2992                                  * smb2cli_session_set_session_key()
2993                                  * or
2994                                  * smb2cli_session_set_channel_key()
2995                                  * which will check the signature
2996                                  * with the channel signing key.
2997                                  */
2998                                 signing_key = NULL;
2999                         }
3000                 }
3001
3002                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_SESSION_DELETED)) {
3003                         /*
3004                          * if the server returns NT_STATUS_USER_SESSION_DELETED
3005                          * the response is not signed and we should
3006                          * propagate the NT_STATUS_USER_SESSION_DELETED
3007                          * status to the caller.
3008                          */
3009                         signing_key = NULL;
3010                 }
3011
3012                 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_NAME_DELETED) ||
3013                     NT_STATUS_EQUAL(status, NT_STATUS_FILE_CLOSED) ||
3014                     NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER)) {
3015                         /*
3016                          * if the server returns
3017                          * NT_STATUS_NETWORK_NAME_DELETED
3018                          * NT_STATUS_FILE_CLOSED
3019                          * NT_STATUS_INVALID_PARAMETER
3020                          * the response might not be signed
3021                          * as this happens before the signing checks.
3022                          *
3023                          * If server echos the signature (or all zeros)
3024                          * we should report the status from the server
3025                          * to the caller.
3026                          */
3027                         if (signing_key) {
3028                                 int cmp;
3029
3030                                 cmp = memcmp(inhdr+SMB2_HDR_SIGNATURE,
3031                                              state->smb2.hdr+SMB2_HDR_SIGNATURE,
3032                                              16);
3033                                 if (cmp == 0) {
3034                                         state->smb2.signing_skipped = true;
3035                                         signing_key = NULL;
3036                                 }
3037                         }
3038                         if (signing_key) {
3039                                 int cmp;
3040                                 static const uint8_t zeros[16];
3041
3042                                 cmp = memcmp(inhdr+SMB2_HDR_SIGNATURE,
3043                                              zeros,
3044                                              16);
3045                                 if (cmp == 0) {
3046                                         state->smb2.signing_skipped = true;
3047                                         signing_key = NULL;
3048                                 }
3049                         }
3050                 }
3051
3052                 if (signing_key) {
3053                         status = smb2_signing_check_pdu(*signing_key,
3054                                                         state->conn->protocol,
3055                                                         cur, 3);
3056                         if (!NT_STATUS_IS_OK(status)) {
3057                                 /*
3058                                  * If the signing check fails, we disconnect
3059                                  * the connection.
3060                                  */
3061                                 return status;
3062                         }
3063                 }
3064
3065                 smbXcli_req_unset_pending(req);
3066
3067                 /*
3068                  * There might be more than one response
3069                  * we need to defer the notifications
3070                  */
3071                 if ((num_iov == 4) && (talloc_array_length(conn->pending) == 0)) {
3072                         defer = false;
3073                 }
3074
3075                 if (defer) {
3076                         tevent_req_defer_callback(req, state->ev);
3077                 }
3078
3079                 /*
3080                  * Note: here we use talloc_reference() in a way
3081                  *       that does not expose it to the caller.
3082                  */
3083                 inbuf_ref = talloc_reference(state->smb2.recv_iov, inbuf);
3084                 if (tevent_req_nomem(inbuf_ref, req)) {
3085                         continue;
3086                 }
3087
3088                 /* copy the related buffers */
3089                 state->smb2.recv_iov[0] = cur[0];
3090                 state->smb2.recv_iov[1] = cur[1];
3091                 state->smb2.recv_iov[2] = cur[2];
3092
3093                 tevent_req_done(req);
3094         }
3095
3096         if (defer) {
3097                 return NT_STATUS_RETRY;
3098         }
3099
3100         return NT_STATUS_OK;
3101 }
3102
3103 NTSTATUS smb2cli_req_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
3104                           struct iovec **piov,
3105                           const struct smb2cli_req_expected_response *expected,
3106                           size_t num_expected)
3107 {
3108         struct smbXcli_req_state *state =
3109                 tevent_req_data(req,
3110                 struct smbXcli_req_state);
3111         NTSTATUS status;
3112         size_t body_size;
3113         bool found_status = false;
3114         bool found_size = false;
3115         size_t i;
3116
3117         if (piov != NULL) {
3118                 *piov = NULL;
3119         }
3120
3121         if (state->smb2.got_async) {
3122                 return STATUS_PENDING;
3123         }
3124
3125         if (tevent_req_is_nterror(req, &status)) {
3126                 for (i=0; i < num_expected; i++) {
3127                         if (NT_STATUS_EQUAL(status, expected[i].status)) {
3128                                 found_status = true;
3129                                 break;
3130                         }
3131                 }
3132
3133                 if (found_status) {
3134                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
3135                 }
3136
3137                 return status;
3138         }
3139
3140         if (num_expected == 0) {
3141                 found_status = true;
3142                 found_size = true;
3143         }
3144
3145         status = NT_STATUS(IVAL(state->smb2.recv_iov[0].iov_base, SMB2_HDR_STATUS));
3146         body_size = SVAL(state->smb2.recv_iov[1].iov_base, 0);
3147
3148         for (i=0; i < num_expected; i++) {
3149                 if (!NT_STATUS_EQUAL(status, expected[i].status)) {
3150                         continue;
3151                 }
3152
3153                 found_status = true;
3154                 if (expected[i].body_size == 0) {
3155                         found_size = true;
3156                         break;
3157                 }
3158
3159                 if (expected[i].body_size == body_size) {
3160                         found_size = true;
3161                         break;
3162                 }
3163         }
3164
3165         if (!found_status) {
3166                 return status;
3167         }
3168
3169         if (state->smb2.signing_skipped) {
3170                 if (num_expected > 0) {
3171                         return NT_STATUS_ACCESS_DENIED;
3172                 }
3173                 if (!NT_STATUS_IS_ERR(status)) {
3174                         return NT_STATUS_ACCESS_DENIED;
3175                 }
3176         }
3177
3178         if (!found_size) {
3179                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
3180         }
3181
3182         if (piov != NULL) {
3183                 *piov = talloc_move(mem_ctx, &state->smb2.recv_iov);
3184         }
3185
3186         return status;
3187 }
3188
3189 static const struct {
3190         enum protocol_types proto;
3191         const char *smb1_name;
3192 } smb1cli_prots[] = {
3193         {PROTOCOL_CORE,         "PC NETWORK PROGRAM 1.0"},
3194         {PROTOCOL_COREPLUS,     "MICROSOFT NETWORKS 1.03"},
3195         {PROTOCOL_LANMAN1,      "MICROSOFT NETWORKS 3.0"},
3196         {PROTOCOL_LANMAN1,      "LANMAN1.0"},
3197         {PROTOCOL_LANMAN2,      "LM1.2X002"},
3198         {PROTOCOL_LANMAN2,      "DOS LANMAN2.1"},
3199         {PROTOCOL_LANMAN2,      "LANMAN2.1"},
3200         {PROTOCOL_LANMAN2,      "Samba"},
3201         {PROTOCOL_NT1,          "NT LANMAN 1.0"},
3202         {PROTOCOL_NT1,          "NT LM 0.12"},
3203         {PROTOCOL_SMB2_02,      "SMB 2.002"},
3204         {PROTOCOL_SMB2_10,      "SMB 2.???"},
3205 };
3206
3207 static const struct {
3208         enum protocol_types proto;
3209         uint16_t smb2_dialect;
3210 } smb2cli_prots[] = {
3211         {PROTOCOL_SMB2_02,      SMB2_DIALECT_REVISION_202},
3212         {PROTOCOL_SMB2_10,      SMB2_DIALECT_REVISION_210},
3213         {PROTOCOL_SMB2_22,      SMB2_DIALECT_REVISION_222},
3214         {PROTOCOL_SMB2_24,      SMB2_DIALECT_REVISION_224},
3215 };
3216
3217 struct smbXcli_negprot_state {
3218         struct smbXcli_conn *conn;
3219         struct tevent_context *ev;
3220         uint32_t timeout_msec;
3221         enum protocol_types min_protocol;
3222         enum protocol_types max_protocol;
3223
3224         struct {
3225                 uint8_t fixed[36];
3226                 uint8_t dyn[ARRAY_SIZE(smb2cli_prots)*2];
3227         } smb2;
3228 };
3229
3230 static void smbXcli_negprot_invalid_done(struct tevent_req *subreq);
3231 static struct tevent_req *smbXcli_negprot_smb1_subreq(struct smbXcli_negprot_state *state);
3232 static void smbXcli_negprot_smb1_done(struct tevent_req *subreq);
3233 static struct tevent_req *smbXcli_negprot_smb2_subreq(struct smbXcli_negprot_state *state);
3234 static void smbXcli_negprot_smb2_done(struct tevent_req *subreq);
3235 static NTSTATUS smbXcli_negprot_dispatch_incoming(struct smbXcli_conn *conn,
3236                                                   TALLOC_CTX *frame,
3237                                                   uint8_t *inbuf);
3238
3239 struct tevent_req *smbXcli_negprot_send(TALLOC_CTX *mem_ctx,
3240                                         struct tevent_context *ev,
3241                                         struct smbXcli_conn *conn,
3242                                         uint32_t timeout_msec,
3243                                         enum protocol_types min_protocol,
3244                                         enum protocol_types max_protocol)
3245 {
3246         struct tevent_req *req, *subreq;
3247         struct smbXcli_negprot_state *state;
3248
3249         req = tevent_req_create(mem_ctx, &state,
3250                                 struct smbXcli_negprot_state);
3251         if (req == NULL) {
3252                 return NULL;
3253         }
3254         state->conn = conn;
3255         state->ev = ev;
3256         state->timeout_msec = timeout_msec;
3257         state->min_protocol = min_protocol;
3258         state->max_protocol = max_protocol;
3259
3260         if (min_protocol == PROTOCOL_NONE) {
3261                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3262                 return tevent_req_post(req, ev);
3263         }
3264
3265         if (max_protocol == PROTOCOL_NONE) {
3266                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3267                 return tevent_req_post(req, ev);
3268         }
3269
3270         if (min_protocol > max_protocol) {
3271                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3272                 return tevent_req_post(req, ev);
3273         }
3274
3275         if ((min_protocol < PROTOCOL_SMB2_02) &&
3276             (max_protocol < PROTOCOL_SMB2_02)) {
3277                 /*
3278                  * SMB1 only...
3279                  */
3280                 conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
3281
3282                 subreq = smbXcli_negprot_smb1_subreq(state);
3283                 if (tevent_req_nomem(subreq, req)) {
3284                         return tevent_req_post(req, ev);
3285                 }
3286                 tevent_req_set_callback(subreq, smbXcli_negprot_smb1_done, req);
3287                 return req;
3288         }
3289
3290         if ((min_protocol >= PROTOCOL_SMB2_02) &&
3291             (max_protocol >= PROTOCOL_SMB2_02)) {
3292                 /*
3293                  * SMB2 only...
3294                  */
3295                 conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
3296
3297                 subreq = smbXcli_negprot_smb2_subreq(state);
3298                 if (tevent_req_nomem(subreq, req)) {
3299                         return tevent_req_post(req, ev);
3300                 }
3301                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
3302                 return req;
3303         }
3304
3305         /*
3306          * We send an SMB1 negprot with the SMB2 dialects
3307          * and expect a SMB1 or a SMB2 response.
3308          *
3309          * smbXcli_negprot_dispatch_incoming() will fix the
3310          * callback to match protocol of the response.
3311          */
3312         conn->dispatch_incoming = smbXcli_negprot_dispatch_incoming;
3313
3314         subreq = smbXcli_negprot_smb1_subreq(state);
3315         if (tevent_req_nomem(subreq, req)) {
3316                 return tevent_req_post(req, ev);
3317         }
3318         tevent_req_set_callback(subreq, smbXcli_negprot_invalid_done, req);
3319         return req;
3320 }
3321
3322 static void smbXcli_negprot_invalid_done(struct tevent_req *subreq)
3323 {
3324         struct tevent_req *req =
3325                 tevent_req_callback_data(subreq,
3326                 struct tevent_req);
3327         NTSTATUS status;
3328
3329         /*
3330          * we just want the low level error
3331          */
3332         status = tevent_req_simple_recv_ntstatus(subreq);
3333         TALLOC_FREE(subreq);
3334         if (tevent_req_nterror(req, status)) {
3335                 return;
3336         }
3337
3338         /* this should never happen */
3339         tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
3340 }
3341
3342 static struct tevent_req *smbXcli_negprot_smb1_subreq(struct smbXcli_negprot_state *state)
3343 {
3344         size_t i;
3345         DATA_BLOB bytes = data_blob_null;
3346         uint8_t flags;
3347         uint16_t flags2;
3348
3349         /* setup the protocol strings */
3350         for (i=0; i < ARRAY_SIZE(smb1cli_prots); i++) {
3351                 uint8_t c = 2;
3352                 bool ok;
3353
3354                 if (smb1cli_prots[i].proto < state->min_protocol) {
3355                         continue;
3356                 }
3357
3358                 if (smb1cli_prots[i].proto > state->max_protocol) {
3359                         continue;
3360                 }
3361
3362                 ok = data_blob_append(state, &bytes, &c, sizeof(c));
3363                 if (!ok) {
3364                         return NULL;
3365                 }
3366
3367                 /*
3368                  * We now it is already ascii and
3369                  * we want NULL termination.
3370                  */
3371                 ok = data_blob_append(state, &bytes,
3372                                       smb1cli_prots[i].smb1_name,
3373                                       strlen(smb1cli_prots[i].smb1_name)+1);
3374                 if (!ok) {
3375                         return NULL;
3376                 }
3377         }
3378
3379         smb1cli_req_flags(state->max_protocol,
3380                           state->conn->smb1.client.capabilities,
3381                           SMBnegprot,
3382                           0, 0, &flags,
3383                           0, 0, &flags2);
3384
3385         return smb1cli_req_send(state, state->ev, state->conn,
3386                                 SMBnegprot,
3387                                 flags, ~flags,
3388                                 flags2, ~flags2,
3389                                 state->timeout_msec,
3390                                 0xFFFE, 0, 0, /* pid, tid, uid */
3391                                 0, NULL, /* wct, vwv */
3392                                 bytes.length, bytes.data);
3393 }
3394
3395 static void smbXcli_negprot_smb1_done(struct tevent_req *subreq)
3396 {
3397         struct tevent_req *req =
3398                 tevent_req_callback_data(subreq,
3399                 struct tevent_req);
3400         struct smbXcli_negprot_state *state =
3401                 tevent_req_data(req,
3402                 struct smbXcli_negprot_state);
3403         struct smbXcli_conn *conn = state->conn;
3404         struct iovec *recv_iov = NULL;
3405         uint8_t *inhdr;
3406         uint8_t wct;
3407         uint16_t *vwv;
3408         uint32_t num_bytes;
3409         uint8_t *bytes;
3410         NTSTATUS status;
3411         uint16_t protnum;
3412         size_t i;
3413         size_t num_prots = 0;
3414         uint8_t flags;
3415         uint32_t client_capabilities = conn->smb1.client.capabilities;
3416         uint32_t both_capabilities;
3417         uint32_t server_capabilities = 0;
3418         uint32_t capabilities;
3419         uint32_t client_max_xmit = conn->smb1.client.max_xmit;
3420         uint32_t server_max_xmit = 0;
3421         uint32_t max_xmit;
3422         uint32_t server_max_mux = 0;
3423         uint16_t server_security_mode = 0;
3424         uint32_t server_session_key = 0;
3425         bool server_readbraw = false;
3426         bool server_writebraw = false;
3427         bool server_lockread = false;
3428         bool server_writeunlock = false;
3429         struct GUID server_guid = GUID_zero();
3430         DATA_BLOB server_gss_blob = data_blob_null;
3431         uint8_t server_challenge[8];
3432         char *server_workgroup = NULL;
3433         char *server_name = NULL;
3434         int server_time_zone = 0;
3435         NTTIME server_system_time = 0;
3436         static const struct smb1cli_req_expected_response expected[] = {
3437         {
3438                 .status = NT_STATUS_OK,
3439                 .wct = 0x11, /* NT1 */
3440         },
3441         {
3442                 .status = NT_STATUS_OK,
3443                 .wct = 0x0D, /* LM */
3444         },
3445         {
3446                 .status = NT_STATUS_OK,
3447                 .wct = 0x01, /* CORE */
3448         }
3449         };
3450
3451         ZERO_STRUCT(server_challenge);
3452
3453         status = smb1cli_req_recv(subreq, state,
3454                                   &recv_iov,
3455                                   &inhdr,
3456                                   &wct,
3457                                   &vwv,
3458                                   NULL, /* pvwv_offset */
3459                                   &num_bytes,
3460                                   &bytes,
3461                                   NULL, /* pbytes_offset */
3462                                   NULL, /* pinbuf */
3463                                   expected, ARRAY_SIZE(expected));
3464         TALLOC_FREE(subreq);
3465         if (tevent_req_nterror(req, status)) {
3466                 return;
3467         }
3468
3469         flags = CVAL(inhdr, HDR_FLG);
3470
3471         protnum = SVAL(vwv, 0);
3472
3473         for (i=0; i < ARRAY_SIZE(smb1cli_prots); i++) {
3474                 if (smb1cli_prots[i].proto < state->min_protocol) {
3475                         continue;
3476                 }
3477
3478                 if (smb1cli_prots[i].proto > state->max_protocol) {
3479                         continue;
3480                 }
3481
3482                 if (protnum != num_prots) {
3483                         num_prots++;
3484                         continue;
3485                 }
3486
3487                 conn->protocol = smb1cli_prots[i].proto;
3488                 break;
3489         }
3490
3491         if (conn->protocol == PROTOCOL_NONE) {
3492                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3493                 return;
3494         }
3495
3496         if ((conn->protocol < PROTOCOL_NT1) && conn->mandatory_signing) {
3497                 DEBUG(0,("smbXcli_negprot: SMB signing is mandatory "
3498                          "and the selected protocol level doesn't support it.\n"));
3499                 tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
3500                 return;
3501         }
3502
3503         if (flags & FLAG_SUPPORT_LOCKREAD) {
3504                 server_lockread = true;
3505                 server_writeunlock = true;
3506         }
3507
3508         if (conn->protocol >= PROTOCOL_NT1) {
3509                 const char *client_signing = NULL;
3510                 bool server_mandatory = false;
3511                 bool server_allowed = false;
3512                 const char *server_signing = NULL;
3513                 bool ok;
3514                 uint8_t key_len;
3515
3516                 if (wct != 0x11) {
3517                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3518                         return;
3519                 }
3520
3521                 /* NT protocol */
3522                 server_security_mode = CVAL(vwv + 1, 0);
3523                 server_max_mux = SVAL(vwv + 1, 1);
3524                 server_max_xmit = IVAL(vwv + 3, 1);
3525                 server_session_key = IVAL(vwv + 7, 1);
3526                 server_time_zone = SVALS(vwv + 15, 1);
3527                 server_time_zone *= 60;
3528                 /* this time arrives in real GMT */
3529                 server_system_time = BVAL(vwv + 11, 1);
3530                 server_capabilities = IVAL(vwv + 9, 1);
3531
3532                 key_len = CVAL(vwv + 16, 1);
3533
3534                 if (server_capabilities & CAP_RAW_MODE) {
3535                         server_readbraw = true;
3536                         server_writebraw = true;
3537                 }
3538                 if (server_capabilities & CAP_LOCK_AND_READ) {
3539                         server_lockread = true;
3540                 }
3541
3542                 if (server_capabilities & CAP_EXTENDED_SECURITY) {
3543                         DATA_BLOB blob1, blob2;
3544
3545                         if (num_bytes < 16) {
3546                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3547                                 return;
3548                         }
3549
3550                         blob1 = data_blob_const(bytes, 16);
3551                         status = GUID_from_data_blob(&blob1, &server_guid);
3552                         if (tevent_req_nterror(req, status)) {
3553                                 return;
3554                         }
3555
3556                         blob1 = data_blob_const(bytes+16, num_bytes-16);
3557                         blob2 = data_blob_dup_talloc(state, blob1);
3558                         if (blob1.length > 0 &&
3559                             tevent_req_nomem(blob2.data, req)) {
3560                                 return;
3561                         }
3562                         server_gss_blob = blob2;
3563                 } else {
3564                         DATA_BLOB blob1, blob2;
3565
3566                         if (num_bytes < key_len) {
3567                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3568                                 return;
3569                         }
3570
3571                         if (key_len != 0 && key_len != 8) {
3572                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3573                                 return;
3574                         }
3575
3576                         if (key_len == 8) {
3577                                 memcpy(server_challenge, bytes, 8);
3578                         }
3579
3580                         blob1 = data_blob_const(bytes+key_len, num_bytes-key_len);
3581                         blob2 = data_blob_const(bytes+key_len, num_bytes-key_len);
3582                         if (blob1.length > 0) {
3583                                 size_t len;
3584
3585                                 len = utf16_len_n(blob1.data,
3586                                                   blob1.length);
3587                                 blob1.length = len;
3588
3589                                 ok = convert_string_talloc(state,
3590                                                            CH_UTF16LE,
3591                                                            CH_UNIX,
3592                                                            blob1.data,
3593                                                            blob1.length,
3594                                                            &server_workgroup,
3595                                                            &len);
3596                                 if (!ok) {
3597                                         status = map_nt_error_from_unix_common(errno);
3598                                         tevent_req_nterror(req, status);
3599                                         return;
3600                                 }
3601                         }
3602
3603                         blob2.data += blob1.length;
3604                         blob2.length -= blob1.length;
3605                         if (blob2.length > 0) {
3606                                 size_t len;
3607
3608                                 len = utf16_len_n(blob1.data,
3609                                                   blob1.length);
3610                                 blob1.length = len;
3611
3612                                 ok = convert_string_talloc(state,
3613                                                            CH_UTF16LE,
3614                                                            CH_UNIX,
3615                                                            blob2.data,
3616                                                            blob2.length,
3617                                                            &server_name,
3618                                                            &len);
3619                                 if (!ok) {
3620                                         status = map_nt_error_from_unix_common(errno);
3621                                         tevent_req_nterror(req, status);
3622                                         return;
3623                                 }
3624                         }
3625                 }
3626
3627                 client_signing = "disabled";
3628                 if (conn->allow_signing) {
3629                         client_signing = "allowed";
3630                 }
3631                 if (conn->mandatory_signing) {
3632                         client_signing = "required";
3633                 }
3634
3635                 server_signing = "not supported";
3636                 if (server_security_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLED) {
3637                         server_signing = "supported";
3638                         server_allowed = true;
3639                 }
3640                 if (server_security_mode & NEGOTIATE_SECURITY_SIGNATURES_REQUIRED) {
3641                         server_signing = "required";
3642                         server_mandatory = true;
3643                 }
3644
3645                 ok = smb_signing_set_negotiated(conn->smb1.signing,
3646                                                 server_allowed,
3647                                                 server_mandatory);
3648                 if (!ok) {
3649                         DEBUG(1,("cli_negprot: SMB signing is required, "
3650                                  "but client[%s] and server[%s] mismatch\n",
3651                                  client_signing, server_signing));
3652                         tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
3653                         return;
3654                 }
3655
3656         } else if (conn->protocol >= PROTOCOL_LANMAN1) {
3657                 DATA_BLOB blob1;
3658                 uint8_t key_len;
3659                 time_t t;
3660
3661                 if (wct != 0x0D) {
3662                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3663                         return;
3664                 }
3665
3666                 server_security_mode = SVAL(vwv + 1, 0);
3667                 server_max_xmit = SVAL(vwv + 2, 0);
3668                 server_max_mux = SVAL(vwv + 3, 0);
3669                 server_readbraw = ((SVAL(vwv + 5, 0) & 0x1) != 0);
3670                 server_writebraw = ((SVAL(vwv + 5, 0) & 0x2) != 0);
3671                 server_session_key = IVAL(vwv + 6, 0);
3672                 server_time_zone = SVALS(vwv + 10, 0);
3673                 server_time_zone *= 60;
3674                 /* this time is converted to GMT by make_unix_date */
3675                 t = pull_dos_date((const uint8_t *)(vwv + 8), server_time_zone);
3676                 unix_to_nt_time(&server_system_time, t);
3677                 key_len = SVAL(vwv + 11, 0);
3678
3679                 if (num_bytes < key_len) {
3680                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3681                         return;
3682                 }
3683
3684                 if (key_len != 0 && key_len != 8) {
3685                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3686                         return;
3687                 }
3688
3689                 if (key_len == 8) {
3690                         memcpy(server_challenge, bytes, 8);
3691                 }
3692
3693                 blob1 = data_blob_const(bytes+key_len, num_bytes-key_len);
3694                 if (blob1.length > 0) {
3695                         size_t len;
3696                         bool ok;
3697
3698                         len = utf16_len_n(blob1.data,
3699                                           blob1.length);
3700                         blob1.length = len;
3701
3702                         ok = convert_string_talloc(state,
3703                                                    CH_DOS,
3704                                                    CH_UNIX,
3705                                                    blob1.data,
3706                                                    blob1.length,
3707                                                    &server_workgroup,
3708                                                    &len);
3709                         if (!ok) {
3710                                 status = map_nt_error_from_unix_common(errno);
3711                                 tevent_req_nterror(req, status);
3712                                 return;
3713                         }
3714                 }
3715
3716         } else {
3717                 /* the old core protocol */
3718                 server_time_zone = get_time_zone(time(NULL));
3719                 server_max_xmit = 1024;
3720                 server_max_mux = 1;
3721         }
3722
3723         if (server_max_xmit < 1024) {
3724                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3725                 return;
3726         }
3727
3728         if (server_max_mux < 1) {
3729                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3730                 return;
3731         }
3732
3733         /*
3734          * Now calculate the negotiated capabilities
3735          * based on the mask for:
3736          * - client only flags
3737          * - flags used in both directions
3738          * - server only flags
3739          */
3740         both_capabilities = client_capabilities & server_capabilities;
3741         capabilities = client_capabilities & SMB_CAP_CLIENT_MASK;
3742         capabilities |= both_capabilities & SMB_CAP_BOTH_MASK;
3743         capabilities |= server_capabilities & SMB_CAP_SERVER_MASK;
3744
3745         max_xmit = MIN(client_max_xmit, server_max_xmit);
3746
3747         conn->smb1.server.capabilities = server_capabilities;
3748         conn->smb1.capabilities = capabilities;
3749
3750         conn->smb1.server.max_xmit = server_max_xmit;
3751         conn->smb1.max_xmit = max_xmit;
3752
3753         conn->smb1.server.max_mux = server_max_mux;
3754
3755         conn->smb1.server.security_mode = server_security_mode;
3756
3757         conn->smb1.server.readbraw = server_readbraw;
3758         conn->smb1.server.writebraw = server_writebraw;
3759         conn->smb1.server.lockread = server_lockread;
3760         conn->smb1.server.writeunlock = server_writeunlock;
3761
3762         conn->smb1.server.session_key = server_session_key;
3763
3764         talloc_steal(conn, server_gss_blob.data);
3765         conn->smb1.server.gss_blob = server_gss_blob;
3766         conn->smb1.server.guid = server_guid;
3767         memcpy(conn->smb1.server.challenge, server_challenge, 8);
3768         conn->smb1.server.workgroup = talloc_move(conn, &server_workgroup);
3769         conn->smb1.server.name = talloc_move(conn, &server_name);
3770
3771         conn->smb1.server.time_zone = server_time_zone;
3772         conn->smb1.server.system_time = server_system_time;
3773
3774         tevent_req_done(req);
3775 }
3776
3777 static struct tevent_req *smbXcli_negprot_smb2_subreq(struct smbXcli_negprot_state *state)
3778 {
3779         size_t i;
3780         uint8_t *buf;
3781         uint16_t dialect_count = 0;
3782
3783         buf = state->smb2.dyn;
3784         for (i=0; i < ARRAY_SIZE(smb2cli_prots); i++) {
3785                 if (smb2cli_prots[i].proto < state->min_protocol) {
3786                         continue;
3787                 }
3788
3789                 if (smb2cli_prots[i].proto > state->max_protocol) {
3790                         continue;
3791                 }
3792
3793                 SSVAL(buf, dialect_count*2, smb2cli_prots[i].smb2_dialect);
3794                 dialect_count++;
3795         }
3796
3797         buf = state->smb2.fixed;
3798         SSVAL(buf, 0, 36);
3799         SSVAL(buf, 2, dialect_count);
3800         SSVAL(buf, 4, state->conn->smb2.client.security_mode);
3801         SSVAL(buf, 6, 0);       /* Reserved */
3802         if (state->max_protocol >= PROTOCOL_SMB2_22) {
3803                 SIVAL(buf, 8, state->conn->smb2.client.capabilities);
3804         } else {
3805                 SIVAL(buf, 8, 0);       /* Capabilities */
3806         }
3807         if (state->max_protocol >= PROTOCOL_SMB2_10) {
3808                 NTSTATUS status;
3809                 DATA_BLOB blob;
3810
3811                 status = GUID_to_ndr_blob(&state->conn->smb2.client.guid,
3812                                           state, &blob);
3813                 if (!NT_STATUS_IS_OK(status)) {
3814                         return NULL;
3815                 }
3816                 memcpy(buf+12, blob.data, 16); /* ClientGuid */
3817         } else {
3818                 memset(buf+12, 0, 16);  /* ClientGuid */
3819         }
3820         SBVAL(buf, 28, 0);      /* ClientStartTime */
3821
3822         return smb2cli_req_send(state, state->ev,
3823                                 state->conn, SMB2_OP_NEGPROT,
3824                                 0, 0, /* flags */
3825                                 state->timeout_msec,
3826                                 0xFEFF, 0, NULL, /* pid, tid, session */
3827                                 state->smb2.fixed, sizeof(state->smb2.fixed),
3828                                 state->smb2.dyn, dialect_count*2);
3829 }
3830
3831 static void smbXcli_negprot_smb2_done(struct tevent_req *subreq)
3832 {
3833         struct tevent_req *req =
3834                 tevent_req_callback_data(subreq,
3835                 struct tevent_req);
3836         struct smbXcli_negprot_state *state =
3837                 tevent_req_data(req,
3838                 struct smbXcli_negprot_state);
3839         struct smbXcli_conn *conn = state->conn;
3840         size_t security_offset, security_length;
3841         DATA_BLOB blob;
3842         NTSTATUS status;
3843         struct iovec *iov;
3844         uint8_t *body;
3845         size_t i;
3846         uint16_t dialect_revision;
3847         static const struct smb2cli_req_expected_response expected[] = {
3848         {
3849                 .status = NT_STATUS_OK,
3850                 .body_size = 0x41
3851         }
3852         };
3853
3854         status = smb2cli_req_recv(subreq, state, &iov,
3855                                   expected, ARRAY_SIZE(expected));
3856         TALLOC_FREE(subreq);
3857         if (tevent_req_nterror(req, status)) {
3858                 return;
3859         }
3860
3861         body = (uint8_t *)iov[1].iov_base;
3862
3863         dialect_revision = SVAL(body, 4);
3864
3865         for (i=0; i < ARRAY_SIZE(smb2cli_prots); i++) {
3866                 if (smb2cli_prots[i].proto < state->min_protocol) {
3867                         continue;
3868                 }
3869
3870                 if (smb2cli_prots[i].proto > state->max_protocol) {
3871                         continue;
3872                 }
3873
3874                 if (smb2cli_prots[i].smb2_dialect != dialect_revision) {
3875                         continue;
3876                 }
3877
3878                 conn->protocol = smb2cli_prots[i].proto;
3879                 break;
3880         }
3881
3882         if (conn->protocol == PROTOCOL_NONE) {
3883                 if (state->min_protocol >= PROTOCOL_SMB2_02) {
3884                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3885                         return;
3886                 }
3887
3888                 if (dialect_revision != SMB2_DIALECT_REVISION_2FF) {
3889                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3890                         return;
3891                 }
3892
3893                 /* make sure we do not loop forever */
3894                 state->min_protocol = PROTOCOL_SMB2_02;
3895
3896                 /*
3897                  * send a SMB2 negprot, in order to negotiate
3898                  * the SMB2 dialect.
3899                  */
3900                 subreq = smbXcli_negprot_smb2_subreq(state);
3901                 if (tevent_req_nomem(subreq, req)) {
3902                         return;
3903                 }
3904                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
3905                 return;
3906         }
3907
3908         conn->smb2.server.security_mode = SVAL(body, 2);
3909
3910         blob = data_blob_const(body + 8, 16);
3911         status = GUID_from_data_blob(&blob, &conn->smb2.server.guid);
3912         if (tevent_req_nterror(req, status)) {
3913                 return;
3914         }
3915
3916         conn->smb2.server.capabilities  = IVAL(body, 24);
3917         conn->smb2.server.max_trans_size= IVAL(body, 28);
3918         conn->smb2.server.max_read_size = IVAL(body, 32);
3919         conn->smb2.server.max_write_size= IVAL(body, 36);
3920         conn->smb2.server.system_time   = BVAL(body, 40);
3921         conn->smb2.server.start_time    = BVAL(body, 48);
3922
3923         security_offset = SVAL(body, 56);
3924         security_length = SVAL(body, 58);
3925
3926         if (security_offset != SMB2_HDR_BODY + iov[1].iov_len) {
3927                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3928                 return;
3929         }
3930
3931         if (security_length > iov[2].iov_len) {
3932                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3933                 return;
3934         }
3935
3936         conn->smb2.server.gss_blob = data_blob_talloc(conn,
3937                                                 iov[2].iov_base,
3938                                                 security_length);
3939         if (tevent_req_nomem(conn->smb2.server.gss_blob.data, req)) {
3940                 return;
3941         }
3942
3943         tevent_req_done(req);
3944 }
3945
3946 static NTSTATUS smbXcli_negprot_dispatch_incoming(struct smbXcli_conn *conn,
3947                                                   TALLOC_CTX *tmp_mem,
3948                                                   uint8_t *inbuf)
3949 {
3950         size_t num_pending = talloc_array_length(conn->pending);
3951         struct tevent_req *subreq;
3952         struct smbXcli_req_state *substate;
3953         struct tevent_req *req;
3954         uint32_t protocol_magic = IVAL(inbuf, 4);
3955
3956         if (num_pending != 1) {
3957                 return NT_STATUS_INTERNAL_ERROR;
3958         }
3959
3960         subreq = conn->pending[0];
3961         substate = tevent_req_data(subreq, struct smbXcli_req_state);
3962         req = tevent_req_callback_data(subreq, struct tevent_req);
3963
3964         switch (protocol_magic) {
3965         case SMB_MAGIC:
3966                 tevent_req_set_callback(subreq, smbXcli_negprot_smb1_done, req);
3967                 conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
3968                 return smb1cli_conn_dispatch_incoming(conn, tmp_mem, inbuf);
3969
3970         case SMB2_MAGIC:
3971                 if (substate->smb2.recv_iov == NULL) {
3972                         /*
3973                          * For the SMB1 negprot we have move it.
3974                          */
3975                         substate->smb2.recv_iov = substate->smb1.recv_iov;
3976                         substate->smb1.recv_iov = NULL;
3977                 }
3978
3979                 /*
3980                  * we got an SMB2 answer, which consumed sequence number 0
3981                  * so we need to use 1 as the next one
3982                  */
3983                 conn->smb2.mid = 1;
3984                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
3985                 conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
3986                 return smb2cli_conn_dispatch_incoming(conn, tmp_mem, inbuf);
3987         }
3988
3989         DEBUG(10, ("Got non-SMB PDU\n"));
3990         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3991 }
3992
3993 NTSTATUS smbXcli_negprot_recv(struct tevent_req *req)
3994 {
3995         return tevent_req_simple_recv_ntstatus(req);
3996 }
3997
3998 NTSTATUS smbXcli_negprot(struct smbXcli_conn *conn,
3999                          uint32_t timeout_msec,
4000                          enum protocol_types min_protocol,
4001                          enum protocol_types max_protocol)
4002 {
4003         TALLOC_CTX *frame = talloc_stackframe();
4004         struct tevent_context *ev;
4005         struct tevent_req *req;
4006         NTSTATUS status = NT_STATUS_NO_MEMORY;
4007         bool ok;
4008
4009         if (smbXcli_conn_has_async_calls(conn)) {
4010                 /*
4011                  * Can't use sync call while an async call is in flight
4012                  */
4013                 status = NT_STATUS_INVALID_PARAMETER_MIX;
4014                 goto fail;
4015         }
4016         ev = tevent_context_init(frame);
4017         if (ev == NULL) {
4018                 goto fail;
4019         }
4020         req = smbXcli_negprot_send(frame, ev, conn, timeout_msec,
4021                                    min_protocol, max_protocol);
4022         if (req == NULL) {
4023                 goto fail;
4024         }
4025         ok = tevent_req_poll(req, ev);
4026         if (!ok) {
4027                 status = map_nt_error_from_unix_common(errno);
4028                 goto fail;
4029         }
4030         status = smbXcli_negprot_recv(req);
4031  fail:
4032         TALLOC_FREE(frame);
4033         return status;
4034 }
4035
4036 static int smbXcli_session_destructor(struct smbXcli_session *session)
4037 {
4038         if (session->conn == NULL) {
4039                 return 0;
4040         }
4041
4042         DLIST_REMOVE(session->conn->sessions, session);
4043         return 0;
4044 }
4045
4046 struct smbXcli_session *smbXcli_session_create(TALLOC_CTX *mem_ctx,
4047                                                struct smbXcli_conn *conn)
4048 {
4049         struct smbXcli_session *session;
4050
4051         session = talloc_zero(mem_ctx, struct smbXcli_session);
4052         if (session == NULL) {
4053                 return NULL;
4054         }
4055         talloc_set_destructor(session, smbXcli_session_destructor);
4056
4057         DLIST_ADD_END(conn->sessions, session, struct smbXcli_session *);
4058         session->conn = conn;
4059
4060         return session;
4061 }
4062
4063 uint8_t smb2cli_session_security_mode(struct smbXcli_session *session)
4064 {
4065         struct smbXcli_conn *conn = session->conn;
4066         uint8_t security_mode = 0;
4067
4068         if (conn == NULL) {
4069                 return security_mode;
4070         }
4071
4072         security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED;
4073         if (conn->mandatory_signing) {
4074                 security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED;
4075         }
4076
4077         return security_mode;
4078 }
4079
4080 uint64_t smb2cli_session_current_id(struct smbXcli_session *session)
4081 {
4082         return session->smb2.session_id;
4083 }
4084
4085 uint16_t smb2cli_session_get_flags(struct smbXcli_session *session)
4086 {
4087         return session->smb2.session_flags;
4088 }
4089
4090 NTSTATUS smb2cli_session_application_key(struct smbXcli_session *session,
4091                                          TALLOC_CTX *mem_ctx,
4092                                          DATA_BLOB *key)
4093 {
4094         *key = data_blob_null;
4095
4096         if (session->smb2.application_key.length == 0) {
4097                 return NT_STATUS_NO_USER_SESSION_KEY;
4098         }
4099
4100         *key = data_blob_dup_talloc(mem_ctx, session->smb2.application_key);
4101         if (key->data == NULL) {
4102                 return NT_STATUS_NO_MEMORY;
4103         }
4104
4105         return NT_STATUS_OK;
4106 }
4107
4108 void smb2cli_session_set_id_and_flags(struct smbXcli_session *session,
4109                                       uint64_t session_id,
4110                                       uint16_t session_flags)
4111 {
4112         session->smb2.session_id = session_id;
4113         session->smb2.session_flags = session_flags;
4114 }
4115
4116 NTSTATUS smb2cli_session_set_session_key(struct smbXcli_session *session,
4117                                          const DATA_BLOB _session_key,
4118                                          const struct iovec *recv_iov)
4119 {
4120         struct smbXcli_conn *conn = session->conn;
4121         uint16_t no_sign_flags;
4122         uint8_t session_key[16];
4123         NTSTATUS status;
4124
4125         if (conn == NULL) {
4126                 return NT_STATUS_INVALID_PARAMETER_MIX;
4127         }
4128
4129         no_sign_flags = SMB2_SESSION_FLAG_IS_GUEST | SMB2_SESSION_FLAG_IS_NULL;
4130
4131         if (session->smb2.session_flags & no_sign_flags) {
4132                 session->smb2.should_sign = false;
4133                 return NT_STATUS_OK;
4134         }
4135
4136         if (session->smb2.signing_key.length != 0) {
4137                 return NT_STATUS_INVALID_PARAMETER_MIX;
4138         }
4139
4140         ZERO_STRUCT(session_key);
4141         memcpy(session_key, _session_key.data,
4142                MIN(_session_key.length, sizeof(session_key)));
4143
4144         session->smb2.signing_key = data_blob_talloc(session,
4145                                                      session_key,
4146                                                      sizeof(session_key));
4147         if (session->smb2.signing_key.data == NULL) {
4148                 ZERO_STRUCT(session_key);
4149                 return NT_STATUS_NO_MEMORY;
4150         }
4151
4152         if (conn->protocol >= PROTOCOL_SMB2_24) {
4153                 const DATA_BLOB label = data_blob_string_const_null("SMB2AESCMAC");
4154                 const DATA_BLOB context = data_blob_string_const_null("SmbSign");
4155
4156                 smb2_key_derivation(session_key, sizeof(session_key),
4157                                     label.data, label.length,
4158                                     context.data, context.length,
4159                                     session->smb2.signing_key.data);
4160         }
4161
4162         session->smb2.application_key = data_blob_dup_talloc(session,
4163                                                 session->smb2.signing_key);
4164         if (session->smb2.application_key.data == NULL) {
4165                 ZERO_STRUCT(session_key);
4166                 return NT_STATUS_NO_MEMORY;
4167         }
4168
4169         if (conn->protocol >= PROTOCOL_SMB2_24) {
4170                 const DATA_BLOB label = data_blob_string_const_null("SMB2APP");
4171                 const DATA_BLOB context = data_blob_string_const_null("SmbRpc");
4172
4173                 smb2_key_derivation(session_key, sizeof(session_key),
4174                                     label.data, label.length,
4175                                     context.data, context.length,
4176                                     session->smb2.application_key.data);
4177         }
4178         ZERO_STRUCT(session_key);
4179
4180         session->smb2.channel_signing_key = data_blob_dup_talloc(session,
4181                                                 session->smb2.signing_key);
4182         if (session->smb2.channel_signing_key.data == NULL) {
4183                 return NT_STATUS_NO_MEMORY;
4184         }
4185
4186         status = smb2_signing_check_pdu(session->smb2.channel_signing_key,
4187                                         session->conn->protocol,
4188                                         recv_iov, 3);
4189         if (!NT_STATUS_IS_OK(status)) {
4190                 return status;
4191         }
4192
4193         session->smb2.should_sign = false;
4194
4195         if (conn->desire_signing) {
4196                 session->smb2.should_sign = true;
4197         }
4198
4199         if (conn->smb2.server.security_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED) {
4200                 session->smb2.should_sign = true;
4201         }
4202
4203         return NT_STATUS_OK;
4204 }
4205
4206 NTSTATUS smb2cli_session_create_channel(TALLOC_CTX *mem_ctx,
4207                                         struct smbXcli_session *session1,
4208                                         struct smbXcli_conn *conn,
4209                                         struct smbXcli_session **_session2)
4210 {
4211         struct smbXcli_session *session2;
4212
4213         if (session1->smb2.signing_key.length == 0) {
4214                 return NT_STATUS_INVALID_PARAMETER_MIX;
4215         }
4216
4217         if (conn == NULL) {
4218                 return NT_STATUS_INVALID_PARAMETER_MIX;
4219         }
4220
4221         session2 = talloc_zero(mem_ctx, struct smbXcli_session);
4222         if (session2 == NULL) {
4223                 return NT_STATUS_NO_MEMORY;
4224         }
4225         session2->smb2.session_id = session1->smb2.session_id;
4226         session2->smb2.session_flags = session1->smb2.session_flags;
4227
4228         session2->smb2.signing_key = data_blob_dup_talloc(session2,
4229                                                 session1->smb2.signing_key);
4230         if (session2->smb2.signing_key.data == NULL) {
4231                 return NT_STATUS_NO_MEMORY;
4232         }
4233
4234         session2->smb2.should_sign = session1->smb2.should_sign;
4235
4236         talloc_set_destructor(session2, smbXcli_session_destructor);
4237         DLIST_ADD_END(conn->sessions, session2, struct smbXcli_session *);
4238         session2->conn = conn;
4239
4240         *_session2 = session2;
4241         return NT_STATUS_OK;
4242 }
4243
4244 NTSTATUS smb2cli_session_set_channel_key(struct smbXcli_session *session,
4245                                          const DATA_BLOB _channel_key,
4246                                          const struct iovec *recv_iov)
4247 {
4248         struct smbXcli_conn *conn = session->conn;
4249         uint8_t channel_key[16];
4250         NTSTATUS status;
4251
4252         if (conn == NULL) {
4253                 return NT_STATUS_INVALID_PARAMETER_MIX;
4254         }
4255
4256         if (session->smb2.channel_signing_key.length != 0) {
4257                 return NT_STATUS_INVALID_PARAMETER_MIX;
4258         }
4259
4260         ZERO_STRUCT(channel_key);
4261         memcpy(channel_key, _channel_key.data,
4262                MIN(_channel_key.length, sizeof(channel_key)));
4263
4264         session->smb2.channel_signing_key = data_blob_talloc(session,
4265                                                 channel_key,
4266                                                 sizeof(channel_key));
4267         if (session->smb2.channel_signing_key.data == NULL) {
4268                 ZERO_STRUCT(channel_key);
4269                 return NT_STATUS_NO_MEMORY;
4270         }
4271
4272         if (conn->protocol >= PROTOCOL_SMB2_24) {
4273                 const DATA_BLOB label = data_blob_string_const_null("SMB2AESCMAC");
4274                 const DATA_BLOB context = data_blob_string_const_null("SmbSign");
4275
4276                 smb2_key_derivation(channel_key, sizeof(channel_key),
4277                                     label.data, label.length,
4278                                     context.data, context.length,
4279                                     session->smb2.channel_signing_key.data);
4280         }
4281         ZERO_STRUCT(channel_key);
4282
4283         status = smb2_signing_check_pdu(session->smb2.channel_signing_key,
4284                                         session->conn->protocol,
4285                                         recv_iov, 3);
4286         if (!NT_STATUS_IS_OK(status)) {
4287                 return status;
4288         }
4289
4290         return NT_STATUS_OK;
4291 }