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