b62e81d98b3615dbf3d399d231d6da083ea762e4
[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                 return (smb2cli_conn_server_capabilities(conn) & SMB2_CAP_DFS);
2476         }
2477
2478         return (smb1cli_conn_capabilities(conn) & CAP_DFS);
2479 }
2480
2481 uint32_t smb2cli_conn_server_capabilities(struct smbXcli_conn *conn)
2482 {
2483         return conn->smb2.server.capabilities;
2484 }
2485
2486 uint16_t smb2cli_conn_server_security_mode(struct smbXcli_conn *conn)
2487 {
2488         return conn->smb2.server.security_mode;
2489 }
2490
2491 uint32_t smb2cli_conn_max_trans_size(struct smbXcli_conn *conn)
2492 {
2493         return conn->smb2.server.max_trans_size;
2494 }
2495
2496 uint32_t smb2cli_conn_max_read_size(struct smbXcli_conn *conn)
2497 {
2498         return conn->smb2.server.max_read_size;
2499 }
2500
2501 uint32_t smb2cli_conn_max_write_size(struct smbXcli_conn *conn)
2502 {
2503         return conn->smb2.server.max_write_size;
2504 }
2505
2506 void smb2cli_conn_set_max_credits(struct smbXcli_conn *conn,
2507                                   uint16_t max_credits)
2508 {
2509         conn->smb2.max_credits = max_credits;
2510 }
2511
2512 static void smb2cli_req_cancel_done(struct tevent_req *subreq);
2513
2514 static bool smb2cli_req_cancel(struct tevent_req *req)
2515 {
2516         struct smbXcli_req_state *state =
2517                 tevent_req_data(req,
2518                 struct smbXcli_req_state);
2519         uint32_t flags = IVAL(state->smb2.hdr, SMB2_HDR_FLAGS);
2520         uint64_t mid = BVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID);
2521         uint64_t aid = BVAL(state->smb2.hdr, SMB2_HDR_ASYNC_ID);
2522         struct smbXcli_tcon *tcon = state->tcon;
2523         struct smbXcli_session *session = state->session;
2524         uint8_t *fixed = state->smb2.pad;
2525         uint16_t fixed_len = 4;
2526         struct tevent_req *subreq;
2527         struct smbXcli_req_state *substate;
2528         NTSTATUS status;
2529
2530         SSVAL(fixed, 0, 0x04);
2531         SSVAL(fixed, 2, 0);
2532
2533         subreq = smb2cli_req_create(state, state->ev,
2534                                     state->conn,
2535                                     SMB2_OP_CANCEL,
2536                                     flags, 0,
2537                                     0, /* timeout */
2538                                     tcon, session,
2539                                     fixed, fixed_len,
2540                                     NULL, 0);
2541         if (subreq == NULL) {
2542                 return false;
2543         }
2544         substate = tevent_req_data(subreq, struct smbXcli_req_state);
2545
2546         /*
2547          * clear everything but the SMB2_HDR_FLAG_ASYNC flag
2548          * e.g. if SMB2_HDR_FLAG_CHAINED is set we get INVALID_PARAMETER back
2549          */
2550         flags &= SMB2_HDR_FLAG_ASYNC;
2551
2552         if (flags & SMB2_HDR_FLAG_ASYNC) {
2553                 mid = 0;
2554         }
2555
2556         SIVAL(substate->smb2.hdr, SMB2_HDR_FLAGS, flags);
2557         SBVAL(substate->smb2.hdr, SMB2_HDR_MESSAGE_ID, mid);
2558         SBVAL(substate->smb2.hdr, SMB2_HDR_ASYNC_ID, aid);
2559
2560         status = smb2cli_req_compound_submit(&subreq, 1);
2561         if (!NT_STATUS_IS_OK(status)) {
2562                 TALLOC_FREE(subreq);
2563                 return false;
2564         }
2565
2566         tevent_req_set_callback(subreq, smb2cli_req_cancel_done, NULL);
2567
2568         return true;
2569 }
2570
2571 static void smb2cli_req_cancel_done(struct tevent_req *subreq)
2572 {
2573         /* we do not care about the result */
2574         TALLOC_FREE(subreq);
2575 }
2576
2577 struct tevent_req *smb2cli_req_create(TALLOC_CTX *mem_ctx,
2578                                       struct tevent_context *ev,
2579                                       struct smbXcli_conn *conn,
2580                                       uint16_t cmd,
2581                                       uint32_t additional_flags,
2582                                       uint32_t clear_flags,
2583                                       uint32_t timeout_msec,
2584                                       struct smbXcli_tcon *tcon,
2585                                       struct smbXcli_session *session,
2586                                       const uint8_t *fixed,
2587                                       uint16_t fixed_len,
2588                                       const uint8_t *dyn,
2589                                       uint32_t dyn_len)
2590 {
2591         struct tevent_req *req;
2592         struct smbXcli_req_state *state;
2593         uint32_t flags = 0;
2594         uint32_t tid = 0;
2595         uint64_t uid = 0;
2596         bool use_channel_sequence = false;
2597         uint16_t channel_sequence = 0;
2598
2599         req = tevent_req_create(mem_ctx, &state,
2600                                 struct smbXcli_req_state);
2601         if (req == NULL) {
2602                 return NULL;
2603         }
2604
2605         state->ev = ev;
2606         state->conn = conn;
2607         state->session = session;
2608         state->tcon = tcon;
2609
2610         if (conn->smb2.server.capabilities & SMB2_CAP_PERSISTENT_HANDLES) {
2611                 use_channel_sequence = true;
2612         } else if (conn->smb2.server.capabilities & SMB2_CAP_MULTI_CHANNEL) {
2613                 use_channel_sequence = true;
2614         }
2615
2616         if (session) {
2617                 uid = session->smb2->session_id;
2618
2619                 if (use_channel_sequence) {
2620                         channel_sequence = session->smb2->channel_sequence;
2621                 }
2622
2623                 state->smb2.should_sign = session->smb2->should_sign;
2624                 state->smb2.should_encrypt = session->smb2->should_encrypt;
2625
2626                 if (cmd == SMB2_OP_SESSSETUP &&
2627                     session->smb2->signing_key.length != 0) {
2628                         state->smb2.should_sign = true;
2629                 }
2630
2631                 if (cmd == SMB2_OP_SESSSETUP &&
2632                     session->smb2_channel.signing_key.length == 0) {
2633                         state->smb2.should_encrypt = false;
2634                 }
2635         }
2636
2637         if (tcon) {
2638                 tid = tcon->smb2.tcon_id;
2639
2640                 if (tcon->smb2.should_encrypt) {
2641                         state->smb2.should_encrypt = true;
2642                 }
2643         }
2644
2645         if (state->smb2.should_encrypt) {
2646                 state->smb2.should_sign = false;
2647         }
2648
2649         state->smb2.recv_iov = talloc_zero_array(state, struct iovec, 3);
2650         if (state->smb2.recv_iov == NULL) {
2651                 TALLOC_FREE(req);
2652                 return NULL;
2653         }
2654
2655         flags |= additional_flags;
2656         flags &= ~clear_flags;
2657
2658         state->smb2.fixed = fixed;
2659         state->smb2.fixed_len = fixed_len;
2660         state->smb2.dyn = dyn;
2661         state->smb2.dyn_len = dyn_len;
2662
2663         if (state->smb2.should_encrypt) {
2664                 SIVAL(state->smb2.transform, SMB2_TF_PROTOCOL_ID, SMB2_TF_MAGIC);
2665                 SBVAL(state->smb2.transform, SMB2_TF_SESSION_ID, uid);
2666         }
2667
2668         SIVAL(state->smb2.hdr, SMB2_HDR_PROTOCOL_ID,    SMB2_MAGIC);
2669         SSVAL(state->smb2.hdr, SMB2_HDR_LENGTH,         SMB2_HDR_BODY);
2670         SSVAL(state->smb2.hdr, SMB2_HDR_OPCODE,         cmd);
2671         SSVAL(state->smb2.hdr, SMB2_HDR_CHANNEL_SEQUENCE, channel_sequence);
2672         SIVAL(state->smb2.hdr, SMB2_HDR_FLAGS,          flags);
2673         SIVAL(state->smb2.hdr, SMB2_HDR_PID,            0); /* reserved */
2674         SIVAL(state->smb2.hdr, SMB2_HDR_TID,            tid);
2675         SBVAL(state->smb2.hdr, SMB2_HDR_SESSION_ID,     uid);
2676
2677         switch (cmd) {
2678         case SMB2_OP_CANCEL:
2679                 state->one_way = true;
2680                 break;
2681         case SMB2_OP_BREAK:
2682                 /*
2683                  * If this is a dummy request, it will have
2684                  * UINT64_MAX as message id.
2685                  * If we send on break acknowledgement,
2686                  * this gets overwritten later.
2687                  */
2688                 SBVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID, UINT64_MAX);
2689                 break;
2690         }
2691
2692         if (timeout_msec > 0) {
2693                 struct timeval endtime;
2694
2695                 endtime = timeval_current_ofs_msec(timeout_msec);
2696                 if (!tevent_req_set_endtime(req, ev, endtime)) {
2697                         return req;
2698                 }
2699         }
2700
2701         return req;
2702 }
2703
2704 void smb2cli_req_set_notify_async(struct tevent_req *req)
2705 {
2706         struct smbXcli_req_state *state =
2707                 tevent_req_data(req,
2708                 struct smbXcli_req_state);
2709
2710         state->smb2.notify_async = true;
2711 }
2712
2713 static void smb2cli_req_writev_done(struct tevent_req *subreq);
2714 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
2715                                                TALLOC_CTX *tmp_mem,
2716                                                uint8_t *inbuf);
2717
2718 NTSTATUS smb2cli_req_compound_submit(struct tevent_req **reqs,
2719                                      int num_reqs)
2720 {
2721         struct smbXcli_req_state *state;
2722         struct tevent_req *subreq;
2723         struct iovec *iov;
2724         int i, num_iov, nbt_len;
2725         int tf_iov = -1;
2726         const DATA_BLOB *encryption_key = NULL;
2727         uint64_t encryption_session_id = 0;
2728
2729         /*
2730          * 1 for the nbt length, optional TRANSFORM
2731          * per request: HDR, fixed, dyn, padding
2732          * -1 because the last one does not need padding
2733          */
2734
2735         iov = talloc_array(reqs[0], struct iovec, 1 + 1 + 4*num_reqs - 1);
2736         if (iov == NULL) {
2737                 return NT_STATUS_NO_MEMORY;
2738         }
2739
2740         num_iov = 1;
2741         nbt_len = 0;
2742
2743         /*
2744          * the session of the first request that requires encryption
2745          * specifies the encryption key.
2746          */
2747         for (i=0; i<num_reqs; i++) {
2748                 if (!tevent_req_is_in_progress(reqs[i])) {
2749                         return NT_STATUS_INTERNAL_ERROR;
2750                 }
2751
2752                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2753
2754                 if (!smbXcli_conn_is_connected(state->conn)) {
2755                         return NT_STATUS_CONNECTION_DISCONNECTED;
2756                 }
2757
2758                 if ((state->conn->protocol != PROTOCOL_NONE) &&
2759                     (state->conn->protocol < PROTOCOL_SMB2_02)) {
2760                         return NT_STATUS_REVISION_MISMATCH;
2761                 }
2762
2763                 if (state->session == NULL) {
2764                         continue;
2765                 }
2766
2767                 if (!state->smb2.should_encrypt) {
2768                         continue;
2769                 }
2770
2771                 encryption_key = &state->session->smb2->encryption_key;
2772                 if (encryption_key->length == 0) {
2773                         return NT_STATUS_INVALID_PARAMETER_MIX;
2774                 }
2775
2776                 encryption_session_id = state->session->smb2->session_id;
2777
2778                 tf_iov = num_iov;
2779                 iov[num_iov].iov_base = state->smb2.transform;
2780                 iov[num_iov].iov_len  = sizeof(state->smb2.transform);
2781                 num_iov += 1;
2782
2783                 SBVAL(state->smb2.transform, SMB2_TF_PROTOCOL_ID, SMB2_TF_MAGIC);
2784                 SBVAL(state->smb2.transform, SMB2_TF_NONCE,
2785                       state->session->smb2->nonce_low);
2786                 SBVAL(state->smb2.transform, SMB2_TF_NONCE+8,
2787                       state->session->smb2->nonce_high);
2788                 SBVAL(state->smb2.transform, SMB2_TF_SESSION_ID,
2789                       encryption_session_id);
2790
2791                 state->session->smb2->nonce_low += 1;
2792                 if (state->session->smb2->nonce_low == 0) {
2793                         state->session->smb2->nonce_high += 1;
2794                         state->session->smb2->nonce_low += 1;
2795                 }
2796
2797                 nbt_len += SMB2_TF_HDR_SIZE;
2798                 break;
2799         }
2800
2801         for (i=0; i<num_reqs; i++) {
2802                 int hdr_iov;
2803                 size_t reqlen;
2804                 bool ret;
2805                 uint16_t opcode;
2806                 uint64_t avail;
2807                 uint16_t charge;
2808                 uint16_t credits;
2809                 uint64_t mid;
2810                 const DATA_BLOB *signing_key = NULL;
2811
2812                 if (!tevent_req_is_in_progress(reqs[i])) {
2813                         return NT_STATUS_INTERNAL_ERROR;
2814                 }
2815
2816                 state = tevent_req_data(reqs[i], struct smbXcli_req_state);
2817
2818                 if (!smbXcli_conn_is_connected(state->conn)) {
2819                         return NT_STATUS_CONNECTION_DISCONNECTED;
2820                 }
2821
2822                 if ((state->conn->protocol != PROTOCOL_NONE) &&
2823                     (state->conn->protocol < PROTOCOL_SMB2_02)) {
2824                         return NT_STATUS_REVISION_MISMATCH;
2825                 }
2826
2827                 opcode = SVAL(state->smb2.hdr, SMB2_HDR_OPCODE);
2828                 if (opcode == SMB2_OP_CANCEL) {
2829                         goto skip_credits;
2830                 }
2831
2832                 avail = UINT64_MAX - state->conn->smb2.mid;
2833                 if (avail < 1) {
2834                         return NT_STATUS_CONNECTION_ABORTED;
2835                 }
2836
2837                 if (state->conn->smb2.server.capabilities & SMB2_CAP_LARGE_MTU) {
2838                         charge = (MAX(state->smb2.dyn_len, 1) - 1)/ 65536 + 1;
2839                 } else {
2840                         charge = 1;
2841                 }
2842
2843                 charge = MAX(state->smb2.credit_charge, charge);
2844
2845                 avail = MIN(avail, state->conn->smb2.cur_credits);
2846                 if (avail < charge) {
2847                         return NT_STATUS_INTERNAL_ERROR;
2848                 }
2849
2850                 credits = 0;
2851                 if (state->conn->smb2.max_credits > state->conn->smb2.cur_credits) {
2852                         credits = state->conn->smb2.max_credits -
2853                                   state->conn->smb2.cur_credits;
2854                 }
2855                 if (state->conn->smb2.max_credits >= state->conn->smb2.cur_credits) {
2856                         credits += 1;
2857                 }
2858
2859                 mid = state->conn->smb2.mid;
2860                 state->conn->smb2.mid += charge;
2861                 state->conn->smb2.cur_credits -= charge;
2862
2863                 if (state->conn->smb2.server.capabilities & SMB2_CAP_LARGE_MTU) {
2864                         SSVAL(state->smb2.hdr, SMB2_HDR_CREDIT_CHARGE, charge);
2865                 }
2866                 SSVAL(state->smb2.hdr, SMB2_HDR_CREDIT, credits);
2867                 SBVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID, mid);
2868
2869 skip_credits:
2870                 if (state->session && encryption_key == NULL) {
2871                         /*
2872                          * We prefer the channel signing key if it is
2873                          * already there.
2874                          */
2875                         if (state->smb2.should_sign) {
2876                                 signing_key = &state->session->smb2_channel.signing_key;
2877                         }
2878
2879                         /*
2880                          * If it is a channel binding, we already have the main
2881                          * signing key and try that one.
2882                          */
2883                         if (signing_key && signing_key->length == 0) {
2884                                 signing_key = &state->session->smb2->signing_key;
2885                         }
2886
2887                         /*
2888                          * If we do not have any session key yet, we skip the
2889                          * signing of SMB2_OP_SESSSETUP requests.
2890                          */
2891                         if (signing_key && signing_key->length == 0) {
2892                                 signing_key = NULL;
2893                         }
2894                 }
2895
2896                 hdr_iov = num_iov;
2897                 iov[num_iov].iov_base = state->smb2.hdr;
2898                 iov[num_iov].iov_len  = sizeof(state->smb2.hdr);
2899                 num_iov += 1;
2900
2901                 iov[num_iov].iov_base = discard_const(state->smb2.fixed);
2902                 iov[num_iov].iov_len  = state->smb2.fixed_len;
2903                 num_iov += 1;
2904
2905                 if (state->smb2.dyn != NULL) {
2906                         iov[num_iov].iov_base = discard_const(state->smb2.dyn);
2907                         iov[num_iov].iov_len  = state->smb2.dyn_len;
2908                         num_iov += 1;
2909                 }
2910
2911                 reqlen  = sizeof(state->smb2.hdr);
2912                 reqlen += state->smb2.fixed_len;
2913                 reqlen += state->smb2.dyn_len;
2914
2915                 if (i < num_reqs-1) {
2916                         if ((reqlen % 8) > 0) {
2917                                 uint8_t pad = 8 - (reqlen % 8);
2918                                 iov[num_iov].iov_base = state->smb2.pad;
2919                                 iov[num_iov].iov_len = pad;
2920                                 num_iov += 1;
2921                                 reqlen += pad;
2922                         }
2923                         SIVAL(state->smb2.hdr, SMB2_HDR_NEXT_COMMAND, reqlen);
2924                 }
2925
2926                 state->smb2.encryption_session_id = encryption_session_id;
2927
2928                 if (signing_key != NULL) {
2929                         NTSTATUS status;
2930
2931                         status = smb2_signing_sign_pdu(*signing_key,
2932                                                        state->session->conn->protocol,
2933                                                        &iov[hdr_iov], num_iov - hdr_iov);
2934                         if (!NT_STATUS_IS_OK(status)) {
2935                                 return status;
2936                         }
2937                 }
2938
2939                 nbt_len += reqlen;
2940
2941                 ret = smbXcli_req_set_pending(reqs[i]);
2942                 if (!ret) {
2943                         return NT_STATUS_NO_MEMORY;
2944                 }
2945         }
2946
2947         state = tevent_req_data(reqs[0], struct smbXcli_req_state);
2948         _smb_setlen_tcp(state->length_hdr, nbt_len);
2949         iov[0].iov_base = state->length_hdr;
2950         iov[0].iov_len  = sizeof(state->length_hdr);
2951
2952         if (encryption_key != NULL) {
2953                 NTSTATUS status;
2954                 size_t buflen = nbt_len - SMB2_TF_HDR_SIZE;
2955                 uint8_t *buf;
2956                 int vi;
2957
2958                 buf = talloc_array(iov, uint8_t, buflen);
2959                 if (buf == NULL) {
2960                         return NT_STATUS_NO_MEMORY;
2961                 }
2962
2963                 /*
2964                  * We copy the buffers before encrypting them,
2965                  * this is at least currently needed for the
2966                  * to keep state->smb2.hdr.
2967                  *
2968                  * Also the callers may expect there buffers
2969                  * to be const.
2970                  */
2971                 for (vi = tf_iov + 1; vi < num_iov; vi++) {
2972                         struct iovec *v = &iov[vi];
2973                         const uint8_t *o = (const uint8_t *)v->iov_base;
2974
2975                         memcpy(buf, o, v->iov_len);
2976                         v->iov_base = (void *)buf;
2977                         buf += v->iov_len;
2978                 }
2979
2980                 status = smb2_signing_encrypt_pdu(*encryption_key,
2981                                         state->conn->protocol,
2982                                         &iov[tf_iov], num_iov - tf_iov);
2983                 if (!NT_STATUS_IS_OK(status)) {
2984                         return status;
2985                 }
2986         }
2987
2988         if (state->conn->dispatch_incoming == NULL) {
2989                 state->conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
2990         }
2991
2992         subreq = writev_send(state, state->ev, state->conn->outgoing,
2993                              state->conn->write_fd, false, iov, num_iov);
2994         if (subreq == NULL) {
2995                 return NT_STATUS_NO_MEMORY;
2996         }
2997         tevent_req_set_callback(subreq, smb2cli_req_writev_done, reqs[0]);
2998         return NT_STATUS_OK;
2999 }
3000
3001 void smb2cli_req_set_credit_charge(struct tevent_req *req, uint16_t charge)
3002 {
3003         struct smbXcli_req_state *state =
3004                 tevent_req_data(req,
3005                 struct smbXcli_req_state);
3006
3007         state->smb2.credit_charge = charge;
3008 }
3009
3010 struct tevent_req *smb2cli_req_send(TALLOC_CTX *mem_ctx,
3011                                     struct tevent_context *ev,
3012                                     struct smbXcli_conn *conn,
3013                                     uint16_t cmd,
3014                                     uint32_t additional_flags,
3015                                     uint32_t clear_flags,
3016                                     uint32_t timeout_msec,
3017                                     struct smbXcli_tcon *tcon,
3018                                     struct smbXcli_session *session,
3019                                     const uint8_t *fixed,
3020                                     uint16_t fixed_len,
3021                                     const uint8_t *dyn,
3022                                     uint32_t dyn_len)
3023 {
3024         struct tevent_req *req;
3025         NTSTATUS status;
3026
3027         req = smb2cli_req_create(mem_ctx, ev, conn, cmd,
3028                                  additional_flags, clear_flags,
3029                                  timeout_msec,
3030                                  tcon, session,
3031                                  fixed, fixed_len, dyn, dyn_len);
3032         if (req == NULL) {
3033                 return NULL;
3034         }
3035         if (!tevent_req_is_in_progress(req)) {
3036                 return tevent_req_post(req, ev);
3037         }
3038         status = smb2cli_req_compound_submit(&req, 1);
3039         if (tevent_req_nterror(req, status)) {
3040                 return tevent_req_post(req, ev);
3041         }
3042         return req;
3043 }
3044
3045 static void smb2cli_req_writev_done(struct tevent_req *subreq)
3046 {
3047         struct tevent_req *req =
3048                 tevent_req_callback_data(subreq,
3049                 struct tevent_req);
3050         struct smbXcli_req_state *state =
3051                 tevent_req_data(req,
3052                 struct smbXcli_req_state);
3053         ssize_t nwritten;
3054         int err;
3055
3056         nwritten = writev_recv(subreq, &err);
3057         TALLOC_FREE(subreq);
3058         if (nwritten == -1) {
3059                 /* here, we need to notify all pending requests */
3060                 NTSTATUS status = map_nt_error_from_unix_common(err);
3061                 smbXcli_conn_disconnect(state->conn, status);
3062                 return;
3063         }
3064 }
3065
3066 static NTSTATUS smb2cli_inbuf_parse_compound(struct smbXcli_conn *conn,
3067                                              uint8_t *buf,
3068                                              size_t buflen,
3069                                              TALLOC_CTX *mem_ctx,
3070                                              struct iovec **piov, int *pnum_iov)
3071 {
3072         struct iovec *iov;
3073         int num_iov = 0;
3074         size_t taken = 0;
3075         uint8_t *first_hdr = buf;
3076         size_t verified_buflen = 0;
3077         uint8_t *tf = NULL;
3078         size_t tf_len = 0;
3079
3080         iov = talloc_array(mem_ctx, struct iovec, num_iov);
3081         if (iov == NULL) {
3082                 return NT_STATUS_NO_MEMORY;
3083         }
3084
3085         while (taken < buflen) {
3086                 size_t len = buflen - taken;
3087                 uint8_t *hdr = first_hdr + taken;
3088                 struct iovec *cur;
3089                 size_t full_size;
3090                 size_t next_command_ofs;
3091                 uint16_t body_size;
3092                 struct iovec *iov_tmp;
3093
3094                 if (verified_buflen > taken) {
3095                         len = verified_buflen - taken;
3096                 } else {
3097                         tf = NULL;
3098                         tf_len = 0;
3099                 }
3100
3101                 if (len < 4) {
3102                         DEBUG(10, ("%d bytes left, expected at least %d\n",
3103                                    (int)len, 4));
3104                         goto inval;
3105                 }
3106                 if (IVAL(hdr, 0) == SMB2_TF_MAGIC) {
3107                         struct smbXcli_session *s;
3108                         uint64_t uid;
3109                         struct iovec tf_iov[2];
3110                         size_t enc_len;
3111                         NTSTATUS status;
3112
3113                         if (len < SMB2_TF_HDR_SIZE) {
3114                                 DEBUG(10, ("%d bytes left, expected at least %d\n",
3115                                            (int)len, SMB2_TF_HDR_SIZE));
3116                                 goto inval;
3117                         }
3118                         tf = hdr;
3119                         tf_len = SMB2_TF_HDR_SIZE;
3120                         taken += tf_len;
3121
3122                         hdr = first_hdr + taken;
3123                         enc_len = IVAL(tf, SMB2_TF_MSG_SIZE);
3124                         uid = BVAL(tf, SMB2_TF_SESSION_ID);
3125
3126                         if (len < SMB2_TF_HDR_SIZE + enc_len) {
3127                                 DEBUG(10, ("%d bytes left, expected at least %d\n",
3128                                            (int)len,
3129                                            (int)(SMB2_TF_HDR_SIZE + enc_len)));
3130                                 goto inval;
3131                         }
3132
3133                         s = conn->sessions;
3134                         for (; s; s = s->next) {
3135                                 if (s->smb2->session_id != uid) {
3136                                         continue;
3137                                 }
3138                                 break;
3139                         }
3140
3141                         if (s == NULL) {
3142                                 DEBUG(10, ("unknown session_id %llu\n",
3143                                            (unsigned long long)uid));
3144                                 goto inval;
3145                         }
3146
3147                         tf_iov[0].iov_base = (void *)tf;
3148                         tf_iov[0].iov_len = tf_len;
3149                         tf_iov[1].iov_base = (void *)hdr;
3150                         tf_iov[1].iov_len = enc_len;
3151
3152                         status = smb2_signing_decrypt_pdu(s->smb2->decryption_key,
3153                                                           conn->protocol,
3154                                                           tf_iov, 2);
3155                         if (!NT_STATUS_IS_OK(status)) {
3156                                 TALLOC_FREE(iov);
3157                                 return status;
3158                         }
3159
3160                         verified_buflen = taken + enc_len;
3161                         len = enc_len;
3162                 }
3163
3164                 /*
3165                  * We need the header plus the body length field
3166                  */
3167
3168                 if (len < SMB2_HDR_BODY + 2) {
3169                         DEBUG(10, ("%d bytes left, expected at least %d\n",
3170                                    (int)len, SMB2_HDR_BODY));
3171                         goto inval;
3172                 }
3173                 if (IVAL(hdr, 0) != SMB2_MAGIC) {
3174                         DEBUG(10, ("Got non-SMB2 PDU: %x\n",
3175                                    IVAL(hdr, 0)));
3176                         goto inval;
3177                 }
3178                 if (SVAL(hdr, 4) != SMB2_HDR_BODY) {
3179                         DEBUG(10, ("Got HDR len %d, expected %d\n",
3180                                    SVAL(hdr, 4), SMB2_HDR_BODY));
3181                         goto inval;
3182                 }
3183
3184                 full_size = len;
3185                 next_command_ofs = IVAL(hdr, SMB2_HDR_NEXT_COMMAND);
3186                 body_size = SVAL(hdr, SMB2_HDR_BODY);
3187
3188                 if (next_command_ofs != 0) {
3189                         if (next_command_ofs < (SMB2_HDR_BODY + 2)) {
3190                                 goto inval;
3191                         }
3192                         if (next_command_ofs > full_size) {
3193                                 goto inval;
3194                         }
3195                         full_size = next_command_ofs;
3196                 }
3197                 if (body_size < 2) {
3198                         goto inval;
3199                 }
3200                 body_size &= 0xfffe;
3201
3202                 if (body_size > (full_size - SMB2_HDR_BODY)) {
3203                         goto inval;
3204                 }
3205
3206                 iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
3207                                          num_iov + 4);
3208                 if (iov_tmp == NULL) {
3209                         TALLOC_FREE(iov);
3210                         return NT_STATUS_NO_MEMORY;
3211                 }
3212                 iov = iov_tmp;
3213                 cur = &iov[num_iov];
3214                 num_iov += 4;
3215
3216                 cur[0].iov_base = tf;
3217                 cur[0].iov_len  = tf_len;
3218                 cur[1].iov_base = hdr;
3219                 cur[1].iov_len  = SMB2_HDR_BODY;
3220                 cur[2].iov_base = hdr + SMB2_HDR_BODY;
3221                 cur[2].iov_len  = body_size;
3222                 cur[3].iov_base = hdr + SMB2_HDR_BODY + body_size;
3223                 cur[3].iov_len  = full_size - (SMB2_HDR_BODY + body_size);
3224
3225                 taken += full_size;
3226         }
3227
3228         *piov = iov;
3229         *pnum_iov = num_iov;
3230         return NT_STATUS_OK;
3231
3232 inval:
3233         TALLOC_FREE(iov);
3234         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3235 }
3236
3237 static struct tevent_req *smb2cli_conn_find_pending(struct smbXcli_conn *conn,
3238                                                     uint64_t mid)
3239 {
3240         size_t num_pending = talloc_array_length(conn->pending);
3241         size_t i;
3242
3243         for (i=0; i<num_pending; i++) {
3244                 struct tevent_req *req = conn->pending[i];
3245                 struct smbXcli_req_state *state =
3246                         tevent_req_data(req,
3247                         struct smbXcli_req_state);
3248
3249                 if (mid == BVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID)) {
3250                         return req;
3251                 }
3252         }
3253         return NULL;
3254 }
3255
3256 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
3257                                                TALLOC_CTX *tmp_mem,
3258                                                uint8_t *inbuf)
3259 {
3260         struct tevent_req *req;
3261         struct smbXcli_req_state *state = NULL;
3262         struct iovec *iov;
3263         int i, num_iov;
3264         NTSTATUS status;
3265         bool defer = true;
3266         struct smbXcli_session *last_session = NULL;
3267         size_t inbuf_len = smb_len_tcp(inbuf);
3268
3269         status = smb2cli_inbuf_parse_compound(conn,
3270                                               inbuf + NBT_HDR_SIZE,
3271                                               inbuf_len,
3272                                               tmp_mem,
3273                                               &iov, &num_iov);
3274         if (!NT_STATUS_IS_OK(status)) {
3275                 return status;
3276         }
3277
3278         for (i=0; i<num_iov; i+=4) {
3279                 uint8_t *inbuf_ref = NULL;
3280                 struct iovec *cur = &iov[i];
3281                 uint8_t *inhdr = (uint8_t *)cur[1].iov_base;
3282                 uint16_t opcode = SVAL(inhdr, SMB2_HDR_OPCODE);
3283                 uint32_t flags = IVAL(inhdr, SMB2_HDR_FLAGS);
3284                 uint64_t mid = BVAL(inhdr, SMB2_HDR_MESSAGE_ID);
3285                 uint16_t req_opcode;
3286                 uint32_t req_flags;
3287                 uint16_t credits = SVAL(inhdr, SMB2_HDR_CREDIT);
3288                 uint32_t new_credits;
3289                 struct smbXcli_session *session = NULL;
3290                 const DATA_BLOB *signing_key = NULL;
3291                 bool was_encrypted = false;
3292
3293                 new_credits = conn->smb2.cur_credits;
3294                 new_credits += credits;
3295                 if (new_credits > UINT16_MAX) {
3296                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3297                 }
3298                 conn->smb2.cur_credits += credits;
3299
3300                 req = smb2cli_conn_find_pending(conn, mid);
3301                 if (req == NULL) {
3302                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3303                 }
3304                 state = tevent_req_data(req, struct smbXcli_req_state);
3305
3306                 state->smb2.got_async = false;
3307
3308                 req_opcode = SVAL(state->smb2.hdr, SMB2_HDR_OPCODE);
3309                 if (opcode != req_opcode) {
3310                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3311                 }
3312                 req_flags = SVAL(state->smb2.hdr, SMB2_HDR_FLAGS);
3313
3314                 if (!(flags & SMB2_HDR_FLAG_REDIRECT)) {
3315                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3316                 }
3317
3318                 status = NT_STATUS(IVAL(inhdr, SMB2_HDR_STATUS));
3319                 if ((flags & SMB2_HDR_FLAG_ASYNC) &&
3320                     NT_STATUS_EQUAL(status, STATUS_PENDING)) {
3321                         uint64_t async_id = BVAL(inhdr, SMB2_HDR_ASYNC_ID);
3322
3323                         /*
3324                          * async interim responses are not signed,
3325                          * even if the SMB2_HDR_FLAG_SIGNED flag
3326                          * is set.
3327                          */
3328                         req_flags |= SMB2_HDR_FLAG_ASYNC;
3329                         SBVAL(state->smb2.hdr, SMB2_HDR_FLAGS, req_flags);
3330                         SBVAL(state->smb2.hdr, SMB2_HDR_ASYNC_ID, async_id);
3331
3332                         if (state->smb2.notify_async) {
3333                                 state->smb2.got_async = true;
3334                                 tevent_req_defer_callback(req, state->ev);
3335                                 tevent_req_notify_callback(req);
3336                         }
3337                         continue;
3338                 }
3339
3340                 session = state->session;
3341                 if (req_flags & SMB2_HDR_FLAG_CHAINED) {
3342                         session = last_session;
3343                 }
3344                 last_session = session;
3345
3346                 if (state->smb2.should_sign) {
3347                         if (!(flags & SMB2_HDR_FLAG_SIGNED)) {
3348                                 return NT_STATUS_ACCESS_DENIED;
3349                         }
3350                 }
3351
3352                 if (flags & SMB2_HDR_FLAG_SIGNED) {
3353                         uint64_t uid = BVAL(inhdr, SMB2_HDR_SESSION_ID);
3354
3355                         if (session == NULL) {
3356                                 struct smbXcli_session *s;
3357
3358                                 s = state->conn->sessions;
3359                                 for (; s; s = s->next) {
3360                                         if (s->smb2->session_id != uid) {
3361                                                 continue;
3362                                         }
3363
3364                                         session = s;
3365                                         break;
3366                                 }
3367                         }
3368
3369                         if (session == NULL) {
3370                                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
3371                         }
3372
3373                         last_session = session;
3374                         signing_key = &session->smb2_channel.signing_key;
3375                 }
3376
3377                 if (opcode == SMB2_OP_SESSSETUP) {
3378                         /*
3379                          * We prefer the channel signing key, if it is
3380                          * already there.
3381                          *
3382                          * If we do not have a channel signing key yet,
3383                          * we try the main signing key, if it is not
3384                          * the final response.
3385                          */
3386                         if (signing_key && signing_key->length == 0 &&
3387                             !NT_STATUS_IS_OK(status)) {
3388                                 signing_key = &session->smb2->signing_key;
3389                         }
3390
3391                         if (signing_key && signing_key->length == 0) {
3392                                 /*
3393                                  * If we do not have a session key to
3394                                  * verify the signature, we defer the
3395                                  * signing check to the caller.
3396                                  *
3397                                  * The caller gets NT_STATUS_OK, it
3398                                  * has to call
3399                                  * smb2cli_session_set_session_key()
3400                                  * or
3401                                  * smb2cli_session_set_channel_key()
3402                                  * which will check the signature
3403                                  * with the channel signing key.
3404                                  */
3405                                 signing_key = NULL;
3406                         }
3407                 }
3408
3409                 if (cur[0].iov_len == SMB2_TF_HDR_SIZE) {
3410                         const uint8_t *tf = (const uint8_t *)cur[0].iov_base;
3411                         uint64_t uid = BVAL(tf, SMB2_TF_SESSION_ID);
3412
3413                         /*
3414                          * If the response was encrypted in a SMB2_TRANSFORM
3415                          * pdu, which belongs to the correct session,
3416                          * we do not need to do signing checks
3417                          *
3418                          * It could be the session the response belongs to
3419                          * or the session that was used to encrypt the
3420                          * SMB2_TRANSFORM request.
3421                          */
3422                         if ((session && session->smb2->session_id == uid) ||
3423                             (state->smb2.encryption_session_id == uid)) {
3424                                 signing_key = NULL;
3425                                 was_encrypted = true;
3426                         }
3427                 }
3428
3429                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_SESSION_DELETED)) {
3430                         /*
3431                          * if the server returns NT_STATUS_USER_SESSION_DELETED
3432                          * the response is not signed and we should
3433                          * propagate the NT_STATUS_USER_SESSION_DELETED
3434                          * status to the caller.
3435                          */
3436                         state->smb2.signing_skipped = true;
3437                         signing_key = NULL;
3438                 }
3439
3440                 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER)) {
3441                         /*
3442                          * if the server returns
3443                          * NT_STATUS_INVALID_PARAMETER
3444                          * the response might not be encrypted.
3445                          */
3446                         if (state->smb2.should_encrypt && !was_encrypted) {
3447                                 state->smb2.signing_skipped = true;
3448                                 signing_key = NULL;
3449                         }
3450                 }
3451
3452                 if (state->smb2.should_encrypt && !was_encrypted) {
3453                         if (!state->smb2.signing_skipped) {
3454                                 return NT_STATUS_ACCESS_DENIED;
3455                         }
3456                 }
3457
3458                 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_NAME_DELETED) ||
3459                     NT_STATUS_EQUAL(status, NT_STATUS_FILE_CLOSED) ||
3460                     NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER)) {
3461                         /*
3462                          * if the server returns
3463                          * NT_STATUS_NETWORK_NAME_DELETED
3464                          * NT_STATUS_FILE_CLOSED
3465                          * NT_STATUS_INVALID_PARAMETER
3466                          * the response might not be signed
3467                          * as this happens before the signing checks.
3468                          *
3469                          * If server echos the signature (or all zeros)
3470                          * we should report the status from the server
3471                          * to the caller.
3472                          */
3473                         if (signing_key) {
3474                                 int cmp;
3475
3476                                 cmp = memcmp(inhdr+SMB2_HDR_SIGNATURE,
3477                                              state->smb2.hdr+SMB2_HDR_SIGNATURE,
3478                                              16);
3479                                 if (cmp == 0) {
3480                                         state->smb2.signing_skipped = true;
3481                                         signing_key = NULL;
3482                                 }
3483                         }
3484                         if (signing_key) {
3485                                 int cmp;
3486                                 static const uint8_t zeros[16];
3487
3488                                 cmp = memcmp(inhdr+SMB2_HDR_SIGNATURE,
3489                                              zeros,
3490                                              16);
3491                                 if (cmp == 0) {
3492                                         state->smb2.signing_skipped = true;
3493                                         signing_key = NULL;
3494                                 }
3495                         }
3496                 }
3497
3498                 if (signing_key) {
3499                         status = smb2_signing_check_pdu(*signing_key,
3500                                                         state->conn->protocol,
3501                                                         &cur[1], 3);
3502                         if (!NT_STATUS_IS_OK(status)) {
3503                                 /*
3504                                  * If the signing check fails, we disconnect
3505                                  * the connection.
3506                                  */
3507                                 return status;
3508                         }
3509                 }
3510
3511                 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED) &&
3512                     (session != NULL) && session->disconnect_expired)
3513                 {
3514                         /*
3515                          * this should be a short term hack
3516                          * until the upper layers have implemented
3517                          * re-authentication.
3518                          */
3519                         return status;
3520                 }
3521
3522                 smbXcli_req_unset_pending(req);
3523
3524                 /*
3525                  * There might be more than one response
3526                  * we need to defer the notifications
3527                  */
3528                 if ((num_iov == 5) && (talloc_array_length(conn->pending) == 0)) {
3529                         defer = false;
3530                 }
3531
3532                 if (defer) {
3533                         tevent_req_defer_callback(req, state->ev);
3534                 }
3535
3536                 /*
3537                  * Note: here we use talloc_reference() in a way
3538                  *       that does not expose it to the caller.
3539                  */
3540                 inbuf_ref = talloc_reference(state->smb2.recv_iov, inbuf);
3541                 if (tevent_req_nomem(inbuf_ref, req)) {
3542                         continue;
3543                 }
3544
3545                 /* copy the related buffers */
3546                 state->smb2.recv_iov[0] = cur[1];
3547                 state->smb2.recv_iov[1] = cur[2];
3548                 state->smb2.recv_iov[2] = cur[3];
3549
3550                 tevent_req_done(req);
3551         }
3552
3553         if (defer) {
3554                 return NT_STATUS_RETRY;
3555         }
3556
3557         return NT_STATUS_OK;
3558 }
3559
3560 NTSTATUS smb2cli_req_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
3561                           struct iovec **piov,
3562                           const struct smb2cli_req_expected_response *expected,
3563                           size_t num_expected)
3564 {
3565         struct smbXcli_req_state *state =
3566                 tevent_req_data(req,
3567                 struct smbXcli_req_state);
3568         NTSTATUS status;
3569         size_t body_size;
3570         bool found_status = false;
3571         bool found_size = false;
3572         size_t i;
3573
3574         if (piov != NULL) {
3575                 *piov = NULL;
3576         }
3577
3578         if (state->smb2.got_async) {
3579                 return STATUS_PENDING;
3580         }
3581
3582         if (tevent_req_is_nterror(req, &status)) {
3583                 for (i=0; i < num_expected; i++) {
3584                         if (NT_STATUS_EQUAL(status, expected[i].status)) {
3585                                 found_status = true;
3586                                 break;
3587                         }
3588                 }
3589
3590                 if (found_status) {
3591                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
3592                 }
3593
3594                 return status;
3595         }
3596
3597         if (num_expected == 0) {
3598                 found_status = true;
3599                 found_size = true;
3600         }
3601
3602         status = NT_STATUS(IVAL(state->smb2.recv_iov[0].iov_base, SMB2_HDR_STATUS));
3603         body_size = SVAL(state->smb2.recv_iov[1].iov_base, 0);
3604
3605         for (i=0; i < num_expected; i++) {
3606                 if (!NT_STATUS_EQUAL(status, expected[i].status)) {
3607                         continue;
3608                 }
3609
3610                 found_status = true;
3611                 if (expected[i].body_size == 0) {
3612                         found_size = true;
3613                         break;
3614                 }
3615
3616                 if (expected[i].body_size == body_size) {
3617                         found_size = true;
3618                         break;
3619                 }
3620         }
3621
3622         if (!found_status) {
3623                 return status;
3624         }
3625
3626         if (state->smb2.signing_skipped) {
3627                 if (num_expected > 0) {
3628                         return NT_STATUS_ACCESS_DENIED;
3629                 }
3630                 if (!NT_STATUS_IS_ERR(status)) {
3631                         return NT_STATUS_ACCESS_DENIED;
3632                 }
3633         }
3634
3635         if (!found_size) {
3636                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
3637         }
3638
3639         if (piov != NULL) {
3640                 *piov = talloc_move(mem_ctx, &state->smb2.recv_iov);
3641         }
3642
3643         return status;
3644 }
3645
3646 static const struct {
3647         enum protocol_types proto;
3648         const char *smb1_name;
3649 } smb1cli_prots[] = {
3650         {PROTOCOL_CORE,         "PC NETWORK PROGRAM 1.0"},
3651         {PROTOCOL_COREPLUS,     "MICROSOFT NETWORKS 1.03"},
3652         {PROTOCOL_LANMAN1,      "MICROSOFT NETWORKS 3.0"},
3653         {PROTOCOL_LANMAN1,      "LANMAN1.0"},
3654         {PROTOCOL_LANMAN2,      "LM1.2X002"},
3655         {PROTOCOL_LANMAN2,      "DOS LANMAN2.1"},
3656         {PROTOCOL_LANMAN2,      "LANMAN2.1"},
3657         {PROTOCOL_LANMAN2,      "Samba"},
3658         {PROTOCOL_NT1,          "NT LANMAN 1.0"},
3659         {PROTOCOL_NT1,          "NT LM 0.12"},
3660         {PROTOCOL_SMB2_02,      "SMB 2.002"},
3661         {PROTOCOL_SMB2_10,      "SMB 2.???"},
3662 };
3663
3664 static const struct {
3665         enum protocol_types proto;
3666         uint16_t smb2_dialect;
3667 } smb2cli_prots[] = {
3668         {PROTOCOL_SMB2_02,      SMB2_DIALECT_REVISION_202},
3669         {PROTOCOL_SMB2_10,      SMB2_DIALECT_REVISION_210},
3670         {PROTOCOL_SMB2_22,      SMB2_DIALECT_REVISION_222},
3671         {PROTOCOL_SMB2_24,      SMB2_DIALECT_REVISION_224},
3672         {PROTOCOL_SMB3_00,      SMB3_DIALECT_REVISION_300},
3673 };
3674
3675 struct smbXcli_negprot_state {
3676         struct smbXcli_conn *conn;
3677         struct tevent_context *ev;
3678         uint32_t timeout_msec;
3679         enum protocol_types min_protocol;
3680         enum protocol_types max_protocol;
3681
3682         struct {
3683                 uint8_t fixed[36];
3684                 uint8_t dyn[ARRAY_SIZE(smb2cli_prots)*2];
3685         } smb2;
3686 };
3687
3688 static void smbXcli_negprot_invalid_done(struct tevent_req *subreq);
3689 static struct tevent_req *smbXcli_negprot_smb1_subreq(struct smbXcli_negprot_state *state);
3690 static void smbXcli_negprot_smb1_done(struct tevent_req *subreq);
3691 static struct tevent_req *smbXcli_negprot_smb2_subreq(struct smbXcli_negprot_state *state);
3692 static void smbXcli_negprot_smb2_done(struct tevent_req *subreq);
3693 static NTSTATUS smbXcli_negprot_dispatch_incoming(struct smbXcli_conn *conn,
3694                                                   TALLOC_CTX *frame,
3695                                                   uint8_t *inbuf);
3696
3697 struct tevent_req *smbXcli_negprot_send(TALLOC_CTX *mem_ctx,
3698                                         struct tevent_context *ev,
3699                                         struct smbXcli_conn *conn,
3700                                         uint32_t timeout_msec,
3701                                         enum protocol_types min_protocol,
3702                                         enum protocol_types max_protocol)
3703 {
3704         struct tevent_req *req, *subreq;
3705         struct smbXcli_negprot_state *state;
3706
3707         req = tevent_req_create(mem_ctx, &state,
3708                                 struct smbXcli_negprot_state);
3709         if (req == NULL) {
3710                 return NULL;
3711         }
3712         state->conn = conn;
3713         state->ev = ev;
3714         state->timeout_msec = timeout_msec;
3715         state->min_protocol = min_protocol;
3716         state->max_protocol = max_protocol;
3717
3718         if (min_protocol == PROTOCOL_NONE) {
3719                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3720                 return tevent_req_post(req, ev);
3721         }
3722
3723         if (max_protocol == PROTOCOL_NONE) {
3724                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3725                 return tevent_req_post(req, ev);
3726         }
3727
3728         if (min_protocol > max_protocol) {
3729                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3730                 return tevent_req_post(req, ev);
3731         }
3732
3733         if ((min_protocol < PROTOCOL_SMB2_02) &&
3734             (max_protocol < PROTOCOL_SMB2_02)) {
3735                 /*
3736                  * SMB1 only...
3737                  */
3738                 conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
3739
3740                 subreq = smbXcli_negprot_smb1_subreq(state);
3741                 if (tevent_req_nomem(subreq, req)) {
3742                         return tevent_req_post(req, ev);
3743                 }
3744                 tevent_req_set_callback(subreq, smbXcli_negprot_smb1_done, req);
3745                 return req;
3746         }
3747
3748         if ((min_protocol >= PROTOCOL_SMB2_02) &&
3749             (max_protocol >= PROTOCOL_SMB2_02)) {
3750                 /*
3751                  * SMB2 only...
3752                  */
3753                 conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
3754
3755                 subreq = smbXcli_negprot_smb2_subreq(state);
3756                 if (tevent_req_nomem(subreq, req)) {
3757                         return tevent_req_post(req, ev);
3758                 }
3759                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
3760                 return req;
3761         }
3762
3763         /*
3764          * We send an SMB1 negprot with the SMB2 dialects
3765          * and expect a SMB1 or a SMB2 response.
3766          *
3767          * smbXcli_negprot_dispatch_incoming() will fix the
3768          * callback to match protocol of the response.
3769          */
3770         conn->dispatch_incoming = smbXcli_negprot_dispatch_incoming;
3771
3772         subreq = smbXcli_negprot_smb1_subreq(state);
3773         if (tevent_req_nomem(subreq, req)) {
3774                 return tevent_req_post(req, ev);
3775         }
3776         tevent_req_set_callback(subreq, smbXcli_negprot_invalid_done, req);
3777         return req;
3778 }
3779
3780 static void smbXcli_negprot_invalid_done(struct tevent_req *subreq)
3781 {
3782         struct tevent_req *req =
3783                 tevent_req_callback_data(subreq,
3784                 struct tevent_req);
3785         NTSTATUS status;
3786
3787         /*
3788          * we just want the low level error
3789          */
3790         status = tevent_req_simple_recv_ntstatus(subreq);
3791         TALLOC_FREE(subreq);
3792         if (tevent_req_nterror(req, status)) {
3793                 return;
3794         }
3795
3796         /* this should never happen */
3797         tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
3798 }
3799
3800 static struct tevent_req *smbXcli_negprot_smb1_subreq(struct smbXcli_negprot_state *state)
3801 {
3802         size_t i;
3803         DATA_BLOB bytes = data_blob_null;
3804         uint8_t flags;
3805         uint16_t flags2;
3806
3807         /* setup the protocol strings */
3808         for (i=0; i < ARRAY_SIZE(smb1cli_prots); i++) {
3809                 uint8_t c = 2;
3810                 bool ok;
3811
3812                 if (smb1cli_prots[i].proto < state->min_protocol) {
3813                         continue;
3814                 }
3815
3816                 if (smb1cli_prots[i].proto > state->max_protocol) {
3817                         continue;
3818                 }
3819
3820                 ok = data_blob_append(state, &bytes, &c, sizeof(c));
3821                 if (!ok) {
3822                         return NULL;
3823                 }
3824
3825                 /*
3826                  * We now it is already ascii and
3827                  * we want NULL termination.
3828                  */
3829                 ok = data_blob_append(state, &bytes,
3830                                       smb1cli_prots[i].smb1_name,
3831                                       strlen(smb1cli_prots[i].smb1_name)+1);
3832                 if (!ok) {
3833                         return NULL;
3834                 }
3835         }
3836
3837         smb1cli_req_flags(state->max_protocol,
3838                           state->conn->smb1.client.capabilities,
3839                           SMBnegprot,
3840                           0, 0, &flags,
3841                           0, 0, &flags2);
3842
3843         return smb1cli_req_send(state, state->ev, state->conn,
3844                                 SMBnegprot,
3845                                 flags, ~flags,
3846                                 flags2, ~flags2,
3847                                 state->timeout_msec,
3848                                 0xFFFE, 0, NULL, /* pid, tid, session */
3849                                 0, NULL, /* wct, vwv */
3850                                 bytes.length, bytes.data);
3851 }
3852
3853 static void smbXcli_negprot_smb1_done(struct tevent_req *subreq)
3854 {
3855         struct tevent_req *req =
3856                 tevent_req_callback_data(subreq,
3857                 struct tevent_req);
3858         struct smbXcli_negprot_state *state =
3859                 tevent_req_data(req,
3860                 struct smbXcli_negprot_state);
3861         struct smbXcli_conn *conn = state->conn;
3862         struct iovec *recv_iov = NULL;
3863         uint8_t *inhdr;
3864         uint8_t wct;
3865         uint16_t *vwv;
3866         uint32_t num_bytes;
3867         uint8_t *bytes;
3868         NTSTATUS status;
3869         uint16_t protnum;
3870         size_t i;
3871         size_t num_prots = 0;
3872         uint8_t flags;
3873         uint32_t client_capabilities = conn->smb1.client.capabilities;
3874         uint32_t both_capabilities;
3875         uint32_t server_capabilities = 0;
3876         uint32_t capabilities;
3877         uint32_t client_max_xmit = conn->smb1.client.max_xmit;
3878         uint32_t server_max_xmit = 0;
3879         uint32_t max_xmit;
3880         uint32_t server_max_mux = 0;
3881         uint16_t server_security_mode = 0;
3882         uint32_t server_session_key = 0;
3883         bool server_readbraw = false;
3884         bool server_writebraw = false;
3885         bool server_lockread = false;
3886         bool server_writeunlock = false;
3887         struct GUID server_guid = GUID_zero();
3888         DATA_BLOB server_gss_blob = data_blob_null;
3889         uint8_t server_challenge[8];
3890         char *server_workgroup = NULL;
3891         char *server_name = NULL;
3892         int server_time_zone = 0;
3893         NTTIME server_system_time = 0;
3894         static const struct smb1cli_req_expected_response expected[] = {
3895         {
3896                 .status = NT_STATUS_OK,
3897                 .wct = 0x11, /* NT1 */
3898         },
3899         {
3900                 .status = NT_STATUS_OK,
3901                 .wct = 0x0D, /* LM */
3902         },
3903         {
3904                 .status = NT_STATUS_OK,
3905                 .wct = 0x01, /* CORE */
3906         }
3907         };
3908
3909         ZERO_STRUCT(server_challenge);
3910
3911         status = smb1cli_req_recv(subreq, state,
3912                                   &recv_iov,
3913                                   &inhdr,
3914                                   &wct,
3915                                   &vwv,
3916                                   NULL, /* pvwv_offset */
3917                                   &num_bytes,
3918                                   &bytes,
3919                                   NULL, /* pbytes_offset */
3920                                   NULL, /* pinbuf */
3921                                   expected, ARRAY_SIZE(expected));
3922         TALLOC_FREE(subreq);
3923         if (tevent_req_nterror(req, status)) {
3924                 return;
3925         }
3926
3927         flags = CVAL(inhdr, HDR_FLG);
3928
3929         protnum = SVAL(vwv, 0);
3930
3931         for (i=0; i < ARRAY_SIZE(smb1cli_prots); i++) {
3932                 if (smb1cli_prots[i].proto < state->min_protocol) {
3933                         continue;
3934                 }
3935
3936                 if (smb1cli_prots[i].proto > state->max_protocol) {
3937                         continue;
3938                 }
3939
3940                 if (protnum != num_prots) {
3941                         num_prots++;
3942                         continue;
3943                 }
3944
3945                 conn->protocol = smb1cli_prots[i].proto;
3946                 break;
3947         }
3948
3949         if (conn->protocol == PROTOCOL_NONE) {
3950                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3951                 return;
3952         }
3953
3954         if ((conn->protocol < PROTOCOL_NT1) && conn->mandatory_signing) {
3955                 DEBUG(0,("smbXcli_negprot: SMB signing is mandatory "
3956                          "and the selected protocol level doesn't support it.\n"));
3957                 tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
3958                 return;
3959         }
3960
3961         if (flags & FLAG_SUPPORT_LOCKREAD) {
3962                 server_lockread = true;
3963                 server_writeunlock = true;
3964         }
3965
3966         if (conn->protocol >= PROTOCOL_NT1) {
3967                 const char *client_signing = NULL;
3968                 bool server_mandatory = false;
3969                 bool server_allowed = false;
3970                 const char *server_signing = NULL;
3971                 bool ok;
3972                 uint8_t key_len;
3973
3974                 if (wct != 0x11) {
3975                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3976                         return;
3977                 }
3978
3979                 /* NT protocol */
3980                 server_security_mode = CVAL(vwv + 1, 0);
3981                 server_max_mux = SVAL(vwv + 1, 1);
3982                 server_max_xmit = IVAL(vwv + 3, 1);
3983                 server_session_key = IVAL(vwv + 7, 1);
3984                 server_time_zone = SVALS(vwv + 15, 1);
3985                 server_time_zone *= 60;
3986                 /* this time arrives in real GMT */
3987                 server_system_time = BVAL(vwv + 11, 1);
3988                 server_capabilities = IVAL(vwv + 9, 1);
3989
3990                 key_len = CVAL(vwv + 16, 1);
3991
3992                 if (server_capabilities & CAP_RAW_MODE) {
3993                         server_readbraw = true;
3994                         server_writebraw = true;
3995                 }
3996                 if (server_capabilities & CAP_LOCK_AND_READ) {
3997                         server_lockread = true;
3998                 }
3999
4000                 if (server_capabilities & CAP_EXTENDED_SECURITY) {
4001                         DATA_BLOB blob1, blob2;
4002
4003                         if (num_bytes < 16) {
4004                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4005                                 return;
4006                         }
4007
4008                         blob1 = data_blob_const(bytes, 16);
4009                         status = GUID_from_data_blob(&blob1, &server_guid);
4010                         if (tevent_req_nterror(req, status)) {
4011                                 return;
4012                         }
4013
4014                         blob1 = data_blob_const(bytes+16, num_bytes-16);
4015                         blob2 = data_blob_dup_talloc(state, blob1);
4016                         if (blob1.length > 0 &&
4017                             tevent_req_nomem(blob2.data, req)) {
4018                                 return;
4019                         }
4020                         server_gss_blob = blob2;
4021                 } else {
4022                         DATA_BLOB blob1, blob2;
4023
4024                         if (num_bytes < key_len) {
4025                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4026                                 return;
4027                         }
4028
4029                         if (key_len != 0 && key_len != 8) {
4030                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4031                                 return;
4032                         }
4033
4034                         if (key_len == 8) {
4035                                 memcpy(server_challenge, bytes, 8);
4036                         }
4037
4038                         blob1 = data_blob_const(bytes+key_len, num_bytes-key_len);
4039                         blob2 = data_blob_const(bytes+key_len, num_bytes-key_len);
4040                         if (blob1.length > 0) {
4041                                 size_t len;
4042
4043                                 len = utf16_len_n(blob1.data,
4044                                                   blob1.length);
4045                                 blob1.length = len;
4046
4047                                 ok = convert_string_talloc(state,
4048                                                            CH_UTF16LE,
4049                                                            CH_UNIX,
4050                                                            blob1.data,
4051                                                            blob1.length,
4052                                                            &server_workgroup,
4053                                                            &len);
4054                                 if (!ok) {
4055                                         status = map_nt_error_from_unix_common(errno);
4056                                         tevent_req_nterror(req, status);
4057                                         return;
4058                                 }
4059                         }
4060
4061                         blob2.data += blob1.length;
4062                         blob2.length -= blob1.length;
4063                         if (blob2.length > 0) {
4064                                 size_t len;
4065
4066                                 len = utf16_len_n(blob1.data,
4067                                                   blob1.length);
4068                                 blob1.length = len;
4069
4070                                 ok = convert_string_talloc(state,
4071                                                            CH_UTF16LE,
4072                                                            CH_UNIX,
4073                                                            blob2.data,
4074                                                            blob2.length,
4075                                                            &server_name,
4076                                                            &len);
4077                                 if (!ok) {
4078                                         status = map_nt_error_from_unix_common(errno);
4079                                         tevent_req_nterror(req, status);
4080                                         return;
4081                                 }
4082                         }
4083                 }
4084
4085                 client_signing = "disabled";
4086                 if (conn->allow_signing) {
4087                         client_signing = "allowed";
4088                 }
4089                 if (conn->mandatory_signing) {
4090                         client_signing = "required";
4091                 }
4092
4093                 server_signing = "not supported";
4094                 if (server_security_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLED) {
4095                         server_signing = "supported";
4096                         server_allowed = true;
4097                 } else if (conn->mandatory_signing) {
4098                         /*
4099                          * We have mandatory signing as client
4100                          * lets assume the server will look at our
4101                          * FLAGS2_SMB_SECURITY_SIGNATURES_REQUIRED
4102                          * flag in the session setup
4103                          */
4104                         server_signing = "not announced";
4105                         server_allowed = true;
4106                 }
4107                 if (server_security_mode & NEGOTIATE_SECURITY_SIGNATURES_REQUIRED) {
4108                         server_signing = "required";
4109                         server_mandatory = true;
4110                 }
4111
4112                 ok = smb_signing_set_negotiated(conn->smb1.signing,
4113                                                 server_allowed,
4114                                                 server_mandatory);
4115                 if (!ok) {
4116                         DEBUG(1,("cli_negprot: SMB signing is required, "
4117                                  "but client[%s] and server[%s] mismatch\n",
4118                                  client_signing, server_signing));
4119                         tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
4120                         return;
4121                 }
4122
4123         } else if (conn->protocol >= PROTOCOL_LANMAN1) {
4124                 DATA_BLOB blob1;
4125                 uint8_t key_len;
4126                 time_t t;
4127
4128                 if (wct != 0x0D) {
4129                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4130                         return;
4131                 }
4132
4133                 server_security_mode = SVAL(vwv + 1, 0);
4134                 server_max_xmit = SVAL(vwv + 2, 0);
4135                 server_max_mux = SVAL(vwv + 3, 0);
4136                 server_readbraw = ((SVAL(vwv + 5, 0) & 0x1) != 0);
4137                 server_writebraw = ((SVAL(vwv + 5, 0) & 0x2) != 0);
4138                 server_session_key = IVAL(vwv + 6, 0);
4139                 server_time_zone = SVALS(vwv + 10, 0);
4140                 server_time_zone *= 60;
4141                 /* this time is converted to GMT by make_unix_date */
4142                 t = pull_dos_date((const uint8_t *)(vwv + 8), server_time_zone);
4143                 unix_to_nt_time(&server_system_time, t);
4144                 key_len = SVAL(vwv + 11, 0);
4145
4146                 if (num_bytes < key_len) {
4147                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4148                         return;
4149                 }
4150
4151                 if (key_len != 0 && key_len != 8) {
4152                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4153                         return;
4154                 }
4155
4156                 if (key_len == 8) {
4157                         memcpy(server_challenge, bytes, 8);
4158                 }
4159
4160                 blob1 = data_blob_const(bytes+key_len, num_bytes-key_len);
4161                 if (blob1.length > 0) {
4162                         size_t len;
4163                         bool ok;
4164
4165                         len = utf16_len_n(blob1.data,
4166                                           blob1.length);
4167                         blob1.length = len;
4168
4169                         ok = convert_string_talloc(state,
4170                                                    CH_DOS,
4171                                                    CH_UNIX,
4172                                                    blob1.data,
4173                                                    blob1.length,
4174                                                    &server_workgroup,
4175                                                    &len);
4176                         if (!ok) {
4177                                 status = map_nt_error_from_unix_common(errno);
4178                                 tevent_req_nterror(req, status);
4179                                 return;
4180                         }
4181                 }
4182
4183         } else {
4184                 /* the old core protocol */
4185                 server_time_zone = get_time_zone(time(NULL));
4186                 server_max_xmit = 1024;
4187                 server_max_mux = 1;
4188         }
4189
4190         if (server_max_xmit < 1024) {
4191                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4192                 return;
4193         }
4194
4195         if (server_max_mux < 1) {
4196                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4197                 return;
4198         }
4199
4200         /*
4201          * Now calculate the negotiated capabilities
4202          * based on the mask for:
4203          * - client only flags
4204          * - flags used in both directions
4205          * - server only flags
4206          */
4207         both_capabilities = client_capabilities & server_capabilities;
4208         capabilities = client_capabilities & SMB_CAP_CLIENT_MASK;
4209         capabilities |= both_capabilities & SMB_CAP_BOTH_MASK;
4210         capabilities |= server_capabilities & SMB_CAP_SERVER_MASK;
4211
4212         max_xmit = MIN(client_max_xmit, server_max_xmit);
4213
4214         conn->smb1.server.capabilities = server_capabilities;
4215         conn->smb1.capabilities = capabilities;
4216
4217         conn->smb1.server.max_xmit = server_max_xmit;
4218         conn->smb1.max_xmit = max_xmit;
4219
4220         conn->smb1.server.max_mux = server_max_mux;
4221
4222         conn->smb1.server.security_mode = server_security_mode;
4223
4224         conn->smb1.server.readbraw = server_readbraw;
4225         conn->smb1.server.writebraw = server_writebraw;
4226         conn->smb1.server.lockread = server_lockread;
4227         conn->smb1.server.writeunlock = server_writeunlock;
4228
4229         conn->smb1.server.session_key = server_session_key;
4230
4231         talloc_steal(conn, server_gss_blob.data);
4232         conn->smb1.server.gss_blob = server_gss_blob;
4233         conn->smb1.server.guid = server_guid;
4234         memcpy(conn->smb1.server.challenge, server_challenge, 8);
4235         conn->smb1.server.workgroup = talloc_move(conn, &server_workgroup);
4236         conn->smb1.server.name = talloc_move(conn, &server_name);
4237
4238         conn->smb1.server.time_zone = server_time_zone;
4239         conn->smb1.server.system_time = server_system_time;
4240
4241         tevent_req_done(req);
4242 }
4243
4244 static struct tevent_req *smbXcli_negprot_smb2_subreq(struct smbXcli_negprot_state *state)
4245 {
4246         size_t i;
4247         uint8_t *buf;
4248         uint16_t dialect_count = 0;
4249
4250         buf = state->smb2.dyn;
4251         for (i=0; i < ARRAY_SIZE(smb2cli_prots); i++) {
4252                 if (smb2cli_prots[i].proto < state->min_protocol) {
4253                         continue;
4254                 }
4255
4256                 if (smb2cli_prots[i].proto > state->max_protocol) {
4257                         continue;
4258                 }
4259
4260                 SSVAL(buf, dialect_count*2, smb2cli_prots[i].smb2_dialect);
4261                 dialect_count++;
4262         }
4263
4264         buf = state->smb2.fixed;
4265         SSVAL(buf, 0, 36);
4266         SSVAL(buf, 2, dialect_count);
4267         SSVAL(buf, 4, state->conn->smb2.client.security_mode);
4268         SSVAL(buf, 6, 0);       /* Reserved */
4269         if (state->max_protocol >= PROTOCOL_SMB2_22) {
4270                 SIVAL(buf, 8, state->conn->smb2.client.capabilities);
4271         } else {
4272                 SIVAL(buf, 8, 0);       /* Capabilities */
4273         }
4274         if (state->max_protocol >= PROTOCOL_SMB2_10) {
4275                 NTSTATUS status;
4276                 DATA_BLOB blob;
4277
4278                 status = GUID_to_ndr_blob(&state->conn->smb2.client.guid,
4279                                           state, &blob);
4280                 if (!NT_STATUS_IS_OK(status)) {
4281                         return NULL;
4282                 }
4283                 memcpy(buf+12, blob.data, 16); /* ClientGuid */
4284         } else {
4285                 memset(buf+12, 0, 16);  /* ClientGuid */
4286         }
4287         SBVAL(buf, 28, 0);      /* ClientStartTime */
4288
4289         return smb2cli_req_send(state, state->ev,
4290                                 state->conn, SMB2_OP_NEGPROT,
4291                                 0, 0, /* flags */
4292                                 state->timeout_msec,
4293                                 NULL, NULL, /* tcon, session */
4294                                 state->smb2.fixed, sizeof(state->smb2.fixed),
4295                                 state->smb2.dyn, dialect_count*2);
4296 }
4297
4298 static void smbXcli_negprot_smb2_done(struct tevent_req *subreq)
4299 {
4300         struct tevent_req *req =
4301                 tevent_req_callback_data(subreq,
4302                 struct tevent_req);
4303         struct smbXcli_negprot_state *state =
4304                 tevent_req_data(req,
4305                 struct smbXcli_negprot_state);
4306         struct smbXcli_conn *conn = state->conn;
4307         size_t security_offset, security_length;
4308         DATA_BLOB blob;
4309         NTSTATUS status;
4310         struct iovec *iov;
4311         uint8_t *body;
4312         size_t i;
4313         uint16_t dialect_revision;
4314         static const struct smb2cli_req_expected_response expected[] = {
4315         {
4316                 .status = NT_STATUS_OK,
4317                 .body_size = 0x41
4318         }
4319         };
4320
4321         status = smb2cli_req_recv(subreq, state, &iov,
4322                                   expected, ARRAY_SIZE(expected));
4323         TALLOC_FREE(subreq);
4324         if (tevent_req_nterror(req, status)) {
4325                 return;
4326         }
4327
4328         body = (uint8_t *)iov[1].iov_base;
4329
4330         dialect_revision = SVAL(body, 4);
4331
4332         for (i=0; i < ARRAY_SIZE(smb2cli_prots); i++) {
4333                 if (smb2cli_prots[i].proto < state->min_protocol) {
4334                         continue;
4335                 }
4336
4337                 if (smb2cli_prots[i].proto > state->max_protocol) {
4338                         continue;
4339                 }
4340
4341                 if (smb2cli_prots[i].smb2_dialect != dialect_revision) {
4342                         continue;
4343                 }
4344
4345                 conn->protocol = smb2cli_prots[i].proto;
4346                 break;
4347         }
4348
4349         if (conn->protocol == PROTOCOL_NONE) {
4350                 if (state->min_protocol >= PROTOCOL_SMB2_02) {
4351                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4352                         return;
4353                 }
4354
4355                 if (dialect_revision != SMB2_DIALECT_REVISION_2FF) {
4356                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4357                         return;
4358                 }
4359
4360                 /* make sure we do not loop forever */
4361                 state->min_protocol = PROTOCOL_SMB2_02;
4362
4363                 /*
4364                  * send a SMB2 negprot, in order to negotiate
4365                  * the SMB2 dialect.
4366                  */
4367                 subreq = smbXcli_negprot_smb2_subreq(state);
4368                 if (tevent_req_nomem(subreq, req)) {
4369                         return;
4370                 }
4371                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
4372                 return;
4373         }
4374
4375         conn->smb2.server.security_mode = SVAL(body, 2);
4376
4377         blob = data_blob_const(body + 8, 16);
4378         status = GUID_from_data_blob(&blob, &conn->smb2.server.guid);
4379         if (tevent_req_nterror(req, status)) {
4380                 return;
4381         }
4382
4383         conn->smb2.server.capabilities  = IVAL(body, 24);
4384         conn->smb2.server.max_trans_size= IVAL(body, 28);
4385         conn->smb2.server.max_read_size = IVAL(body, 32);
4386         conn->smb2.server.max_write_size= IVAL(body, 36);
4387         conn->smb2.server.system_time   = BVAL(body, 40);
4388         conn->smb2.server.start_time    = BVAL(body, 48);
4389
4390         security_offset = SVAL(body, 56);
4391         security_length = SVAL(body, 58);
4392
4393         if (security_offset != SMB2_HDR_BODY + iov[1].iov_len) {
4394                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4395                 return;
4396         }
4397
4398         if (security_length > iov[2].iov_len) {
4399                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
4400                 return;
4401         }
4402
4403         conn->smb2.server.gss_blob = data_blob_talloc(conn,
4404                                                 iov[2].iov_base,
4405                                                 security_length);
4406         if (tevent_req_nomem(conn->smb2.server.gss_blob.data, req)) {
4407                 return;
4408         }
4409
4410         tevent_req_done(req);
4411 }
4412
4413 static NTSTATUS smbXcli_negprot_dispatch_incoming(struct smbXcli_conn *conn,
4414                                                   TALLOC_CTX *tmp_mem,
4415                                                   uint8_t *inbuf)
4416 {
4417         size_t num_pending = talloc_array_length(conn->pending);
4418         struct tevent_req *subreq;
4419         struct smbXcli_req_state *substate;
4420         struct tevent_req *req;
4421         uint32_t protocol_magic;
4422         size_t inbuf_len = smb_len_nbt(inbuf);
4423
4424         if (num_pending != 1) {
4425                 return NT_STATUS_INTERNAL_ERROR;
4426         }
4427
4428         if (inbuf_len < 4) {
4429                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
4430         }
4431
4432         subreq = conn->pending[0];
4433         substate = tevent_req_data(subreq, struct smbXcli_req_state);
4434         req = tevent_req_callback_data(subreq, struct tevent_req);
4435
4436         protocol_magic = IVAL(inbuf, 4);
4437
4438         switch (protocol_magic) {
4439         case SMB_MAGIC:
4440                 tevent_req_set_callback(subreq, smbXcli_negprot_smb1_done, req);
4441                 conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
4442                 return smb1cli_conn_dispatch_incoming(conn, tmp_mem, inbuf);
4443
4444         case SMB2_MAGIC:
4445                 if (substate->smb2.recv_iov == NULL) {
4446                         /*
4447                          * For the SMB1 negprot we have move it.
4448                          */
4449                         substate->smb2.recv_iov = substate->smb1.recv_iov;
4450                         substate->smb1.recv_iov = NULL;
4451                 }
4452
4453                 /*
4454                  * we got an SMB2 answer, which consumed sequence number 0
4455                  * so we need to use 1 as the next one
4456                  */
4457                 conn->smb2.mid = 1;
4458                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
4459                 conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
4460                 return smb2cli_conn_dispatch_incoming(conn, tmp_mem, inbuf);
4461         }
4462
4463         DEBUG(10, ("Got non-SMB PDU\n"));
4464         return NT_STATUS_INVALID_NETWORK_RESPONSE;
4465 }
4466
4467 NTSTATUS smbXcli_negprot_recv(struct tevent_req *req)
4468 {
4469         return tevent_req_simple_recv_ntstatus(req);
4470 }
4471
4472 NTSTATUS smbXcli_negprot(struct smbXcli_conn *conn,
4473                          uint32_t timeout_msec,
4474                          enum protocol_types min_protocol,
4475                          enum protocol_types max_protocol)
4476 {
4477         TALLOC_CTX *frame = talloc_stackframe();
4478         struct tevent_context *ev;
4479         struct tevent_req *req;
4480         NTSTATUS status = NT_STATUS_NO_MEMORY;
4481         bool ok;
4482
4483         if (smbXcli_conn_has_async_calls(conn)) {
4484                 /*
4485                  * Can't use sync call while an async call is in flight
4486                  */
4487                 status = NT_STATUS_INVALID_PARAMETER_MIX;
4488                 goto fail;
4489         }
4490         ev = samba_tevent_context_init(frame);
4491         if (ev == NULL) {
4492                 goto fail;
4493         }
4494         req = smbXcli_negprot_send(frame, ev, conn, timeout_msec,
4495                                    min_protocol, max_protocol);
4496         if (req == NULL) {
4497                 goto fail;
4498         }
4499         ok = tevent_req_poll(req, ev);
4500         if (!ok) {
4501                 status = map_nt_error_from_unix_common(errno);
4502                 goto fail;
4503         }
4504         status = smbXcli_negprot_recv(req);
4505  fail:
4506         TALLOC_FREE(frame);
4507         return status;
4508 }
4509
4510 static int smbXcli_session_destructor(struct smbXcli_session *session)
4511 {
4512         if (session->conn == NULL) {
4513                 return 0;
4514         }
4515
4516         DLIST_REMOVE(session->conn->sessions, session);
4517         return 0;
4518 }
4519
4520 struct smbXcli_session *smbXcli_session_create(TALLOC_CTX *mem_ctx,
4521                                                struct smbXcli_conn *conn)
4522 {
4523         struct smbXcli_session *session;
4524
4525         session = talloc_zero(mem_ctx, struct smbXcli_session);
4526         if (session == NULL) {
4527                 return NULL;
4528         }
4529         session->smb2 = talloc_zero(session, struct smb2cli_session);
4530         if (session->smb2 == NULL) {
4531                 talloc_free(session);
4532                 return NULL;
4533         }
4534         talloc_set_destructor(session, smbXcli_session_destructor);
4535
4536         DLIST_ADD_END(conn->sessions, session, struct smbXcli_session *);
4537         session->conn = conn;
4538
4539         return session;
4540 }
4541
4542 struct smbXcli_session *smbXcli_session_copy(TALLOC_CTX *mem_ctx,
4543                                                 struct smbXcli_session *src)
4544 {
4545         struct smbXcli_session *session;
4546
4547         session = talloc_zero(mem_ctx, struct smbXcli_session);
4548         if (session == NULL) {
4549                 return NULL;
4550         }
4551         session->smb2 = talloc_zero(session, struct smb2cli_session);
4552         if (session->smb2 == NULL) {
4553                 talloc_free(session);
4554                 return NULL;
4555         }
4556
4557         session->conn = src->conn;
4558         *session->smb2 = *src->smb2;
4559         session->smb2_channel = src->smb2_channel;
4560         session->disconnect_expired = src->disconnect_expired;
4561
4562         DLIST_ADD_END(src->conn->sessions, session, struct smbXcli_session *);
4563         talloc_set_destructor(session, smbXcli_session_destructor);
4564
4565         return session;
4566 }
4567
4568
4569 NTSTATUS smbXcli_session_application_key(struct smbXcli_session *session,
4570                                          TALLOC_CTX *mem_ctx,
4571                                          DATA_BLOB *key)
4572 {
4573         const DATA_BLOB *application_key;
4574
4575         *key = data_blob_null;
4576
4577         if (session->conn == NULL) {
4578                 return NT_STATUS_NO_USER_SESSION_KEY;
4579         }
4580
4581         if (session->conn->protocol >= PROTOCOL_SMB2_02) {
4582                 application_key = &session->smb2->application_key;
4583         } else {
4584                 application_key = &session->smb1.application_key;
4585         }
4586
4587         if (application_key->length == 0) {
4588                 return NT_STATUS_NO_USER_SESSION_KEY;
4589         }
4590
4591         *key = data_blob_dup_talloc(mem_ctx, *application_key);
4592         if (key->data == NULL) {
4593                 return NT_STATUS_NO_MEMORY;
4594         }
4595
4596         return NT_STATUS_OK;
4597 }
4598
4599 void smbXcli_session_set_disconnect_expired(struct smbXcli_session *session)
4600 {
4601         session->disconnect_expired = true;
4602 }
4603
4604 uint16_t smb1cli_session_current_id(struct smbXcli_session *session)
4605 {
4606         return session->smb1.session_id;
4607 }
4608
4609 void smb1cli_session_set_id(struct smbXcli_session *session,
4610                             uint16_t session_id)
4611 {
4612         session->smb1.session_id = session_id;
4613 }
4614
4615 NTSTATUS smb1cli_session_set_session_key(struct smbXcli_session *session,
4616                                          const DATA_BLOB _session_key)
4617 {
4618         struct smbXcli_conn *conn = session->conn;
4619         uint8_t session_key[16];
4620
4621         if (conn == NULL) {
4622                 return NT_STATUS_INVALID_PARAMETER_MIX;
4623         }
4624
4625         if (session->smb1.application_key.length != 0) {
4626                 /*
4627                  * TODO: do not allow this...
4628                  *
4629                  * return NT_STATUS_INVALID_PARAMETER_MIX;
4630                  */
4631                 data_blob_clear_free(&session->smb1.application_key);
4632                 session->smb1.protected_key = false;
4633         }
4634
4635         if (_session_key.length == 0) {
4636                 return NT_STATUS_OK;
4637         }
4638
4639         ZERO_STRUCT(session_key);
4640         memcpy(session_key, _session_key.data,
4641                MIN(_session_key.length, sizeof(session_key)));
4642
4643         session->smb1.application_key = data_blob_talloc(session,
4644                                                          session_key,
4645                                                          sizeof(session_key));
4646         ZERO_STRUCT(session_key);
4647         if (session->smb1.application_key.data == NULL) {
4648                 return NT_STATUS_NO_MEMORY;
4649         }
4650
4651         session->smb1.protected_key = false;
4652
4653         return NT_STATUS_OK;
4654 }
4655
4656 NTSTATUS smb1cli_session_protect_session_key(struct smbXcli_session *session)
4657 {
4658         if (session->smb1.protected_key) {
4659                 /* already protected */
4660                 return NT_STATUS_OK;
4661         }
4662
4663         if (session->smb1.application_key.length != 16) {
4664                 return NT_STATUS_INVALID_PARAMETER_MIX;
4665         }
4666
4667         smb_key_derivation(session->smb1.application_key.data,
4668                            session->smb1.application_key.length,
4669                            session->smb1.application_key.data);
4670
4671         session->smb1.protected_key = true;
4672
4673         return NT_STATUS_OK;
4674 }
4675
4676 uint8_t smb2cli_session_security_mode(struct smbXcli_session *session)
4677 {
4678         struct smbXcli_conn *conn = session->conn;
4679         uint8_t security_mode = 0;
4680
4681         if (conn == NULL) {
4682                 return security_mode;
4683         }
4684
4685         security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED;
4686         if (conn->mandatory_signing) {
4687                 security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED;
4688         }
4689
4690         return security_mode;
4691 }
4692
4693 uint64_t smb2cli_session_current_id(struct smbXcli_session *session)
4694 {
4695         return session->smb2->session_id;
4696 }
4697
4698 uint16_t smb2cli_session_get_flags(struct smbXcli_session *session)
4699 {
4700         return session->smb2->session_flags;
4701 }
4702
4703 void smb2cli_session_set_id_and_flags(struct smbXcli_session *session,
4704                                       uint64_t session_id,
4705                                       uint16_t session_flags)
4706 {
4707         session->smb2->session_id = session_id;
4708         session->smb2->session_flags = session_flags;
4709 }
4710
4711 void smb2cli_session_increment_channel_sequence(struct smbXcli_session *session)
4712 {
4713         session->smb2->channel_sequence += 1;
4714 }
4715
4716 NTSTATUS smb2cli_session_set_session_key(struct smbXcli_session *session,
4717                                          const DATA_BLOB _session_key,
4718                                          const struct iovec *recv_iov)
4719 {
4720         struct smbXcli_conn *conn = session->conn;
4721         uint16_t no_sign_flags;
4722         uint8_t session_key[16];
4723         NTSTATUS status;
4724
4725         if (conn == NULL) {
4726                 return NT_STATUS_INVALID_PARAMETER_MIX;
4727         }
4728
4729         no_sign_flags = SMB2_SESSION_FLAG_IS_GUEST | SMB2_SESSION_FLAG_IS_NULL;
4730
4731         if (session->smb2->session_flags & no_sign_flags) {
4732                 session->smb2->should_sign = false;
4733                 return NT_STATUS_OK;
4734         }
4735
4736         if (session->smb2->signing_key.length != 0) {
4737                 return NT_STATUS_INVALID_PARAMETER_MIX;
4738         }
4739
4740         ZERO_STRUCT(session_key);
4741         memcpy(session_key, _session_key.data,
4742                MIN(_session_key.length, sizeof(session_key)));
4743
4744         session->smb2->signing_key = data_blob_talloc(session,
4745                                                      session_key,
4746                                                      sizeof(session_key));
4747         if (session->smb2->signing_key.data == NULL) {
4748                 ZERO_STRUCT(session_key);
4749                 return NT_STATUS_NO_MEMORY;
4750         }
4751
4752         if (conn->protocol >= PROTOCOL_SMB2_24) {
4753                 const DATA_BLOB label = data_blob_string_const_null("SMB2AESCMAC");
4754                 const DATA_BLOB context = data_blob_string_const_null("SmbSign");
4755
4756                 smb2_key_derivation(session_key, sizeof(session_key),
4757                                     label.data, label.length,
4758                                     context.data, context.length,
4759                                     session->smb2->signing_key.data);
4760         }
4761
4762         session->smb2->encryption_key = data_blob_dup_talloc(session,
4763                                                 session->smb2->signing_key);
4764         if (session->smb2->encryption_key.data == NULL) {
4765                 ZERO_STRUCT(session_key);
4766                 return NT_STATUS_NO_MEMORY;
4767         }
4768
4769         if (conn->protocol >= PROTOCOL_SMB2_24) {
4770                 const DATA_BLOB label = data_blob_string_const_null("SMB2AESCCM");
4771                 const DATA_BLOB context = data_blob_string_const_null("ServerIn ");
4772
4773                 smb2_key_derivation(session_key, sizeof(session_key),
4774                                     label.data, label.length,
4775                                     context.data, context.length,
4776                                     session->smb2->encryption_key.data);
4777         }
4778
4779         session->smb2->decryption_key = data_blob_dup_talloc(session,
4780                                                 session->smb2->signing_key);
4781         if (session->smb2->decryption_key.data == NULL) {
4782                 ZERO_STRUCT(session_key);
4783                 return NT_STATUS_NO_MEMORY;
4784         }
4785
4786         if (conn->protocol >= PROTOCOL_SMB2_24) {
4787                 const DATA_BLOB label = data_blob_string_const_null("SMB2AESCCM");
4788                 const DATA_BLOB context = data_blob_string_const_null("ServerOut");
4789
4790                 smb2_key_derivation(session_key, sizeof(session_key),
4791                                     label.data, label.length,
4792                                     context.data, context.length,
4793                                     session->smb2->decryption_key.data);
4794         }
4795
4796         session->smb2->application_key = data_blob_dup_talloc(session,
4797                                                 session->smb2->signing_key);
4798         if (session->smb2->application_key.data == NULL) {
4799                 ZERO_STRUCT(session_key);
4800                 return NT_STATUS_NO_MEMORY;
4801         }
4802
4803         if (conn->protocol >= PROTOCOL_SMB2_24) {
4804                 const DATA_BLOB label = data_blob_string_const_null("SMB2APP");
4805                 const DATA_BLOB context = data_blob_string_const_null("SmbRpc");
4806
4807                 smb2_key_derivation(session_key, sizeof(session_key),
4808                                     label.data, label.length,
4809                                     context.data, context.length,
4810                                     session->smb2->application_key.data);
4811         }
4812         ZERO_STRUCT(session_key);
4813
4814         session->smb2_channel.signing_key = data_blob_dup_talloc(session,
4815                                                 session->smb2->signing_key);
4816         if (session->smb2_channel.signing_key.data == NULL) {
4817                 return NT_STATUS_NO_MEMORY;
4818         }
4819
4820         status = smb2_signing_check_pdu(session->smb2_channel.signing_key,
4821                                         session->conn->protocol,
4822                                         recv_iov, 3);
4823         if (!NT_STATUS_IS_OK(status)) {
4824                 return status;
4825         }
4826
4827         session->smb2->should_sign = false;
4828         session->smb2->should_encrypt = false;
4829
4830         if (conn->desire_signing) {
4831                 session->smb2->should_sign = true;
4832         }
4833
4834         if (conn->smb2.server.security_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED) {
4835                 session->smb2->should_sign = true;
4836         }
4837
4838         if (session->smb2->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) {
4839                 session->smb2->should_encrypt = true;
4840         }
4841
4842         if (conn->protocol < PROTOCOL_SMB2_24) {
4843                 session->smb2->should_encrypt = false;
4844         }
4845
4846         if (!(conn->smb2.server.capabilities & SMB2_CAP_ENCRYPTION)) {
4847                 session->smb2->should_encrypt = false;
4848         }
4849
4850         generate_random_buffer((uint8_t *)&session->smb2->nonce_high,
4851                                sizeof(session->smb2->nonce_high));
4852         session->smb2->nonce_low = 1;
4853
4854         return NT_STATUS_OK;
4855 }
4856
4857 NTSTATUS smb2cli_session_create_channel(TALLOC_CTX *mem_ctx,
4858                                         struct smbXcli_session *session1,
4859                                         struct smbXcli_conn *conn,
4860                                         struct smbXcli_session **_session2)
4861 {
4862         struct smbXcli_session *session2;
4863
4864         if (session1->smb2->signing_key.length == 0) {
4865                 return NT_STATUS_INVALID_PARAMETER_MIX;
4866         }
4867
4868         if (conn == NULL) {
4869                 return NT_STATUS_INVALID_PARAMETER_MIX;
4870         }
4871
4872         session2 = talloc_zero(mem_ctx, struct smbXcli_session);
4873         if (session2 == NULL) {
4874                 return NT_STATUS_NO_MEMORY;
4875         }
4876         session2->smb2 = talloc_reference(session2, session1->smb2);
4877         if (session2->smb2 == NULL) {
4878                 talloc_free(session2);
4879                 return NT_STATUS_NO_MEMORY;
4880         }
4881
4882         talloc_set_destructor(session2, smbXcli_session_destructor);
4883         DLIST_ADD_END(conn->sessions, session2, struct smbXcli_session *);
4884         session2->conn = conn;
4885
4886         *_session2 = session2;
4887         return NT_STATUS_OK;
4888 }
4889
4890 NTSTATUS smb2cli_session_set_channel_key(struct smbXcli_session *session,
4891                                          const DATA_BLOB _channel_key,
4892                                          const struct iovec *recv_iov)
4893 {
4894         struct smbXcli_conn *conn = session->conn;
4895         uint8_t channel_key[16];
4896         NTSTATUS status;
4897
4898         if (conn == NULL) {
4899                 return NT_STATUS_INVALID_PARAMETER_MIX;
4900         }
4901
4902         if (session->smb2_channel.signing_key.length != 0) {
4903                 return NT_STATUS_INVALID_PARAMETER_MIX;
4904         }
4905
4906         ZERO_STRUCT(channel_key);
4907         memcpy(channel_key, _channel_key.data,
4908                MIN(_channel_key.length, sizeof(channel_key)));
4909
4910         session->smb2_channel.signing_key = data_blob_talloc(session,
4911                                                 channel_key,
4912                                                 sizeof(channel_key));
4913         if (session->smb2_channel.signing_key.data == NULL) {
4914                 ZERO_STRUCT(channel_key);
4915                 return NT_STATUS_NO_MEMORY;
4916         }
4917
4918         if (conn->protocol >= PROTOCOL_SMB2_24) {
4919                 const DATA_BLOB label = data_blob_string_const_null("SMB2AESCMAC");
4920                 const DATA_BLOB context = data_blob_string_const_null("SmbSign");
4921
4922                 smb2_key_derivation(channel_key, sizeof(channel_key),
4923                                     label.data, label.length,
4924                                     context.data, context.length,
4925                                     session->smb2_channel.signing_key.data);
4926         }
4927         ZERO_STRUCT(channel_key);
4928
4929         status = smb2_signing_check_pdu(session->smb2_channel.signing_key,
4930                                         session->conn->protocol,
4931                                         recv_iov, 3);
4932         if (!NT_STATUS_IS_OK(status)) {
4933                 return status;
4934         }
4935
4936         return NT_STATUS_OK;
4937 }
4938
4939 struct smbXcli_tcon *smbXcli_tcon_create(TALLOC_CTX *mem_ctx)
4940 {
4941         struct smbXcli_tcon *tcon;
4942
4943         tcon = talloc_zero(mem_ctx, struct smbXcli_tcon);
4944         if (tcon == NULL) {
4945                 return NULL;
4946         }
4947
4948         return tcon;
4949 }
4950
4951 uint16_t smb1cli_tcon_current_id(struct smbXcli_tcon *tcon)
4952 {
4953         return tcon->smb1.tcon_id;
4954 }
4955
4956 void smb1cli_tcon_set_id(struct smbXcli_tcon *tcon, uint16_t tcon_id)
4957 {
4958         tcon->smb1.tcon_id = tcon_id;
4959 }
4960
4961 bool smb1cli_tcon_set_values(struct smbXcli_tcon *tcon,
4962                              uint16_t tcon_id,
4963                              uint16_t optional_support,
4964                              uint32_t maximal_access,
4965                              uint32_t guest_maximal_access,
4966                              const char *service,
4967                              const char *fs_type)
4968 {
4969         tcon->smb1.tcon_id = tcon_id;
4970         tcon->smb1.optional_support = optional_support;
4971         tcon->smb1.maximal_access = maximal_access;
4972         tcon->smb1.guest_maximal_access = guest_maximal_access;
4973
4974         TALLOC_FREE(tcon->smb1.service);
4975         tcon->smb1.service = talloc_strdup(tcon, service);
4976         if (service != NULL && tcon->smb1.service == NULL) {
4977                 return false;
4978         }
4979
4980         TALLOC_FREE(tcon->smb1.fs_type);
4981         tcon->smb1.fs_type = talloc_strdup(tcon, fs_type);
4982         if (fs_type != NULL && tcon->smb1.fs_type == NULL) {
4983                 return false;
4984         }
4985
4986         return true;
4987 }
4988
4989 uint32_t smb2cli_tcon_current_id(struct smbXcli_tcon *tcon)
4990 {
4991         return tcon->smb2.tcon_id;
4992 }
4993
4994 uint32_t smb2cli_tcon_capabilities(struct smbXcli_tcon *tcon)
4995 {
4996         return tcon->smb2.capabilities;
4997 }
4998
4999 void smb2cli_tcon_set_values(struct smbXcli_tcon *tcon,
5000                              struct smbXcli_session *session,
5001                              uint32_t tcon_id,
5002                              uint8_t type,
5003                              uint32_t flags,
5004                              uint32_t capabilities,
5005                              uint32_t maximal_access)
5006 {
5007         tcon->smb2.tcon_id = tcon_id;
5008         tcon->smb2.type = type;
5009         tcon->smb2.flags = flags;
5010         tcon->smb2.capabilities = capabilities;
5011         tcon->smb2.maximal_access = maximal_access;
5012
5013         tcon->smb2.should_encrypt = false;
5014
5015         if (session == NULL) {
5016                 return;
5017         }
5018
5019         tcon->smb2.should_encrypt = session->smb2->should_encrypt;
5020
5021         if (flags & SMB2_SHAREFLAG_ENCRYPT_DATA) {
5022                 tcon->smb2.should_encrypt = true;
5023         }
5024 }