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