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