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