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