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