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