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