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