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