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