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