libcli/smb/smbXcli: remove unused if statement from smb2cli_conn_dispatch_incoming()
[ira/wip.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                                                        &iov[hdr_iov], num_iov - hdr_iov);
2627                         if (!NT_STATUS_IS_OK(status)) {
2628                                 return status;
2629                         }
2630                 }
2631
2632                 ret = smbXcli_req_set_pending(reqs[i]);
2633                 if (!ret) {
2634                         return NT_STATUS_NO_MEMORY;
2635                 }
2636         }
2637
2638         state = tevent_req_data(reqs[0], struct smbXcli_req_state);
2639         _smb_setlen_tcp(state->length_hdr, nbt_len);
2640         iov[0].iov_base = state->length_hdr;
2641         iov[0].iov_len  = sizeof(state->length_hdr);
2642
2643         if (state->conn->dispatch_incoming == NULL) {
2644                 state->conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
2645         }
2646
2647         subreq = writev_send(state, state->ev, state->conn->outgoing,
2648                              state->conn->write_fd, false, iov, num_iov);
2649         if (subreq == NULL) {
2650                 return NT_STATUS_NO_MEMORY;
2651         }
2652         tevent_req_set_callback(subreq, smb2cli_req_writev_done, reqs[0]);
2653         return NT_STATUS_OK;
2654 }
2655
2656 void smb2cli_req_set_credit_charge(struct tevent_req *req, uint16_t charge)
2657 {
2658         struct smbXcli_req_state *state =
2659                 tevent_req_data(req,
2660                 struct smbXcli_req_state);
2661
2662         state->smb2.credit_charge = charge;
2663 }
2664
2665 struct tevent_req *smb2cli_req_send(TALLOC_CTX *mem_ctx,
2666                                     struct tevent_context *ev,
2667                                     struct smbXcli_conn *conn,
2668                                     uint16_t cmd,
2669                                     uint32_t additional_flags,
2670                                     uint32_t clear_flags,
2671                                     uint32_t timeout_msec,
2672                                     uint32_t pid,
2673                                     uint32_t tid,
2674                                     struct smbXcli_session *session,
2675                                     const uint8_t *fixed,
2676                                     uint16_t fixed_len,
2677                                     const uint8_t *dyn,
2678                                     uint32_t dyn_len)
2679 {
2680         struct tevent_req *req;
2681         NTSTATUS status;
2682
2683         req = smb2cli_req_create(mem_ctx, ev, conn, cmd,
2684                                  additional_flags, clear_flags,
2685                                  timeout_msec,
2686                                  pid, tid, session,
2687                                  fixed, fixed_len, dyn, dyn_len);
2688         if (req == NULL) {
2689                 return NULL;
2690         }
2691         if (!tevent_req_is_in_progress(req)) {
2692                 return tevent_req_post(req, ev);
2693         }
2694         status = smb2cli_req_compound_submit(&req, 1);
2695         if (tevent_req_nterror(req, status)) {
2696                 return tevent_req_post(req, ev);
2697         }
2698         return req;
2699 }
2700
2701 static void smb2cli_req_writev_done(struct tevent_req *subreq)
2702 {
2703         struct tevent_req *req =
2704                 tevent_req_callback_data(subreq,
2705                 struct tevent_req);
2706         struct smbXcli_req_state *state =
2707                 tevent_req_data(req,
2708                 struct smbXcli_req_state);
2709         ssize_t nwritten;
2710         int err;
2711
2712         nwritten = writev_recv(subreq, &err);
2713         TALLOC_FREE(subreq);
2714         if (nwritten == -1) {
2715                 /* here, we need to notify all pending requests */
2716                 NTSTATUS status = map_nt_error_from_unix_common(err);
2717                 smbXcli_conn_disconnect(state->conn, status);
2718                 return;
2719         }
2720 }
2721
2722 static NTSTATUS smb2cli_inbuf_parse_compound(uint8_t *buf, TALLOC_CTX *mem_ctx,
2723                                              struct iovec **piov, int *pnum_iov)
2724 {
2725         struct iovec *iov;
2726         int num_iov;
2727         size_t buflen;
2728         size_t taken;
2729         uint8_t *first_hdr;
2730
2731         num_iov = 0;
2732
2733         iov = talloc_array(mem_ctx, struct iovec, num_iov);
2734         if (iov == NULL) {
2735                 return NT_STATUS_NO_MEMORY;
2736         }
2737
2738         buflen = smb_len_tcp(buf);
2739         taken = 0;
2740         first_hdr = buf + NBT_HDR_SIZE;
2741
2742         while (taken < buflen) {
2743                 size_t len = buflen - taken;
2744                 uint8_t *hdr = first_hdr + taken;
2745                 struct iovec *cur;
2746                 size_t full_size;
2747                 size_t next_command_ofs;
2748                 uint16_t body_size;
2749                 struct iovec *iov_tmp;
2750
2751                 /*
2752                  * We need the header plus the body length field
2753                  */
2754
2755                 if (len < SMB2_HDR_BODY + 2) {
2756                         DEBUG(10, ("%d bytes left, expected at least %d\n",
2757                                    (int)len, SMB2_HDR_BODY));
2758                         goto inval;
2759                 }
2760                 if (IVAL(hdr, 0) != SMB2_MAGIC) {
2761                         DEBUG(10, ("Got non-SMB2 PDU: %x\n",
2762                                    IVAL(hdr, 0)));
2763                         goto inval;
2764                 }
2765                 if (SVAL(hdr, 4) != SMB2_HDR_BODY) {
2766                         DEBUG(10, ("Got HDR len %d, expected %d\n",
2767                                    SVAL(hdr, 4), SMB2_HDR_BODY));
2768                         goto inval;
2769                 }
2770
2771                 full_size = len;
2772                 next_command_ofs = IVAL(hdr, SMB2_HDR_NEXT_COMMAND);
2773                 body_size = SVAL(hdr, SMB2_HDR_BODY);
2774
2775                 if (next_command_ofs != 0) {
2776                         if (next_command_ofs < (SMB2_HDR_BODY + 2)) {
2777                                 goto inval;
2778                         }
2779                         if (next_command_ofs > full_size) {
2780                                 goto inval;
2781                         }
2782                         full_size = next_command_ofs;
2783                 }
2784                 if (body_size < 2) {
2785                         goto inval;
2786                 }
2787                 body_size &= 0xfffe;
2788
2789                 if (body_size > (full_size - SMB2_HDR_BODY)) {
2790                         goto inval;
2791                 }
2792
2793                 iov_tmp = talloc_realloc(mem_ctx, iov, struct iovec,
2794                                          num_iov + 3);
2795                 if (iov_tmp == NULL) {
2796                         TALLOC_FREE(iov);
2797                         return NT_STATUS_NO_MEMORY;
2798                 }
2799                 iov = iov_tmp;
2800                 cur = &iov[num_iov];
2801                 num_iov += 3;
2802
2803                 cur[0].iov_base = hdr;
2804                 cur[0].iov_len  = SMB2_HDR_BODY;
2805                 cur[1].iov_base = hdr + SMB2_HDR_BODY;
2806                 cur[1].iov_len  = body_size;
2807                 cur[2].iov_base = hdr + SMB2_HDR_BODY + body_size;
2808                 cur[2].iov_len  = full_size - (SMB2_HDR_BODY + body_size);
2809
2810                 taken += full_size;
2811         }
2812
2813         *piov = iov;
2814         *pnum_iov = num_iov;
2815         return NT_STATUS_OK;
2816
2817 inval:
2818         TALLOC_FREE(iov);
2819         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2820 }
2821
2822 static struct tevent_req *smb2cli_conn_find_pending(struct smbXcli_conn *conn,
2823                                                     uint64_t mid)
2824 {
2825         size_t num_pending = talloc_array_length(conn->pending);
2826         size_t i;
2827
2828         for (i=0; i<num_pending; i++) {
2829                 struct tevent_req *req = conn->pending[i];
2830                 struct smbXcli_req_state *state =
2831                         tevent_req_data(req,
2832                         struct smbXcli_req_state);
2833
2834                 if (mid == BVAL(state->smb2.hdr, SMB2_HDR_MESSAGE_ID)) {
2835                         return req;
2836                 }
2837         }
2838         return NULL;
2839 }
2840
2841 static NTSTATUS smb2cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
2842                                                TALLOC_CTX *tmp_mem,
2843                                                uint8_t *inbuf)
2844 {
2845         struct tevent_req *req;
2846         struct smbXcli_req_state *state = NULL;
2847         struct iovec *iov;
2848         int i, num_iov;
2849         NTSTATUS status;
2850         bool defer = true;
2851         struct smbXcli_session *last_session = NULL;
2852
2853         status = smb2cli_inbuf_parse_compound(inbuf, tmp_mem,
2854                                               &iov, &num_iov);
2855         if (!NT_STATUS_IS_OK(status)) {
2856                 return status;
2857         }
2858
2859         for (i=0; i<num_iov; i+=3) {
2860                 uint8_t *inbuf_ref = NULL;
2861                 struct iovec *cur = &iov[i];
2862                 uint8_t *inhdr = (uint8_t *)cur[0].iov_base;
2863                 uint16_t opcode = SVAL(inhdr, SMB2_HDR_OPCODE);
2864                 uint32_t flags = IVAL(inhdr, SMB2_HDR_FLAGS);
2865                 uint64_t mid = BVAL(inhdr, SMB2_HDR_MESSAGE_ID);
2866                 uint16_t req_opcode;
2867                 uint32_t req_flags;
2868                 uint16_t credits = SVAL(inhdr, SMB2_HDR_CREDIT);
2869                 uint32_t new_credits;
2870                 struct smbXcli_session *session = NULL;
2871                 const DATA_BLOB *signing_key = NULL;
2872                 bool should_sign = false;
2873
2874                 new_credits = conn->smb2.cur_credits;
2875                 new_credits += credits;
2876                 if (new_credits > UINT16_MAX) {
2877                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2878                 }
2879                 conn->smb2.cur_credits += credits;
2880
2881                 req = smb2cli_conn_find_pending(conn, mid);
2882                 if (req == NULL) {
2883                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2884                 }
2885                 state = tevent_req_data(req, struct smbXcli_req_state);
2886
2887                 state->smb2.got_async = false;
2888
2889                 req_opcode = SVAL(state->smb2.hdr, SMB2_HDR_OPCODE);
2890                 if (opcode != req_opcode) {
2891                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2892                 }
2893                 req_flags = SVAL(state->smb2.hdr, SMB2_HDR_FLAGS);
2894
2895                 if (!(flags & SMB2_HDR_FLAG_REDIRECT)) {
2896                         return NT_STATUS_INVALID_NETWORK_RESPONSE;
2897                 }
2898
2899                 status = NT_STATUS(IVAL(inhdr, SMB2_HDR_STATUS));
2900                 if ((flags & SMB2_HDR_FLAG_ASYNC) &&
2901                     NT_STATUS_EQUAL(status, STATUS_PENDING)) {
2902                         uint64_t async_id = BVAL(inhdr, SMB2_HDR_ASYNC_ID);
2903
2904                         /*
2905                          * async interim responses are not signed,
2906                          * even if the SMB2_HDR_FLAG_SIGNED flag
2907                          * is set.
2908                          */
2909                         req_flags |= SMB2_HDR_FLAG_ASYNC;
2910                         SBVAL(state->smb2.hdr, SMB2_HDR_FLAGS, req_flags);
2911                         SBVAL(state->smb2.hdr, SMB2_HDR_ASYNC_ID, async_id);
2912
2913                         if (state->smb2.notify_async) {
2914                                 state->smb2.got_async = true;
2915                                 tevent_req_defer_callback(req, state->ev);
2916                                 tevent_req_notify_callback(req);
2917                         }
2918                         continue;
2919                 }
2920
2921                 session = state->session;
2922                 if (req_flags & SMB2_HDR_FLAG_CHAINED) {
2923                         session = last_session;
2924                 }
2925                 last_session = session;
2926
2927                 if (session) {
2928                         should_sign = session->smb2.should_sign;
2929                         if (opcode == SMB2_OP_SESSSETUP &&
2930                             session->smb2.signing_key.length != 0) {
2931                                 should_sign = true;
2932                         }
2933                 }
2934
2935                 if (should_sign) {
2936                         if (!(flags & SMB2_HDR_FLAG_SIGNED)) {
2937                                 return NT_STATUS_ACCESS_DENIED;
2938                         }
2939                 }
2940
2941                 if (flags & SMB2_HDR_FLAG_SIGNED) {
2942                         uint64_t uid = BVAL(inhdr, SMB2_HDR_SESSION_ID);
2943
2944                         if (session == NULL) {
2945                                 struct smbXcli_session *s;
2946
2947                                 s = state->conn->sessions;
2948                                 for (; s; s = s->next) {
2949                                         if (s->smb2.session_id != uid) {
2950                                                 continue;
2951                                         }
2952
2953                                         session = s;
2954                                         break;
2955                                 }
2956                         }
2957
2958                         if (session == NULL) {
2959                                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2960                         }
2961
2962                         last_session = session;
2963                         signing_key = &session->smb2.channel_signing_key;
2964                 }
2965
2966                 if (opcode == SMB2_OP_SESSSETUP) {
2967                         /*
2968                          * We prefer the channel signing key, if it is
2969                          * already there.
2970                          *
2971                          * If we do not have a channel signing key yet,
2972                          * we try the main signing key, if it is not
2973                          * the final response.
2974                          */
2975                         if (signing_key && signing_key->length == 0 &&
2976                             !NT_STATUS_IS_OK(status)) {
2977                                 signing_key = &session->smb2.signing_key;
2978                         }
2979
2980                         if (signing_key && signing_key->length == 0) {
2981                                 /*
2982                                  * If we do not have a session key to
2983                                  * verify the signature, we defer the
2984                                  * signing check to the caller.
2985                                  *
2986                                  * The caller gets NT_STATUS_OK, it
2987                                  * has to call
2988                                  * smb2cli_session_set_session_key()
2989                                  * or
2990                                  * smb2cli_session_set_channel_key()
2991                                  * which will check the signature
2992                                  * with the channel signing key.
2993                                  */
2994                                 signing_key = NULL;
2995                         }
2996                 }
2997
2998                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_SESSION_DELETED)) {
2999                         /*
3000                          * if the server returns NT_STATUS_USER_SESSION_DELETED
3001                          * the response is not signed and we should
3002                          * propagate the NT_STATUS_USER_SESSION_DELETED
3003                          * status to the caller.
3004                          */
3005                         signing_key = NULL;
3006                 }
3007
3008                 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_NAME_DELETED) ||
3009                     NT_STATUS_EQUAL(status, NT_STATUS_FILE_CLOSED) ||
3010                     NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER)) {
3011                         /*
3012                          * if the server returns
3013                          * NT_STATUS_NETWORK_NAME_DELETED
3014                          * NT_STATUS_FILE_CLOSED
3015                          * NT_STATUS_INVALID_PARAMETER
3016                          * the response might not be signed
3017                          * as this happens before the signing checks.
3018                          *
3019                          * If server echos the signature (or all zeros)
3020                          * we should report the status from the server
3021                          * to the caller.
3022                          */
3023                         if (signing_key) {
3024                                 int cmp;
3025
3026                                 cmp = memcmp(inhdr+SMB2_HDR_SIGNATURE,
3027                                              state->smb2.hdr+SMB2_HDR_SIGNATURE,
3028                                              16);
3029                                 if (cmp == 0) {
3030                                         state->smb2.signing_skipped = true;
3031                                         signing_key = NULL;
3032                                 }
3033                         }
3034                         if (signing_key) {
3035                                 int cmp;
3036                                 static const uint8_t zeros[16];
3037
3038                                 cmp = memcmp(inhdr+SMB2_HDR_SIGNATURE,
3039                                              zeros,
3040                                              16);
3041                                 if (cmp == 0) {
3042                                         state->smb2.signing_skipped = true;
3043                                         signing_key = NULL;
3044                                 }
3045                         }
3046                 }
3047
3048                 if (signing_key) {
3049                         status = smb2_signing_check_pdu(*signing_key, cur, 3);
3050                         if (!NT_STATUS_IS_OK(status)) {
3051                                 /*
3052                                  * If the signing check fails, we disconnect
3053                                  * the connection.
3054                                  */
3055                                 return status;
3056                         }
3057                 }
3058
3059                 smbXcli_req_unset_pending(req);
3060
3061                 /*
3062                  * There might be more than one response
3063                  * we need to defer the notifications
3064                  */
3065                 if ((num_iov == 4) && (talloc_array_length(conn->pending) == 0)) {
3066                         defer = false;
3067                 }
3068
3069                 if (defer) {
3070                         tevent_req_defer_callback(req, state->ev);
3071                 }
3072
3073                 /*
3074                  * Note: here we use talloc_reference() in a way
3075                  *       that does not expose it to the caller.
3076                  */
3077                 inbuf_ref = talloc_reference(state->smb2.recv_iov, inbuf);
3078                 if (tevent_req_nomem(inbuf_ref, req)) {
3079                         continue;
3080                 }
3081
3082                 /* copy the related buffers */
3083                 state->smb2.recv_iov[0] = cur[0];
3084                 state->smb2.recv_iov[1] = cur[1];
3085                 state->smb2.recv_iov[2] = cur[2];
3086
3087                 tevent_req_done(req);
3088         }
3089
3090         if (defer) {
3091                 return NT_STATUS_RETRY;
3092         }
3093
3094         return NT_STATUS_OK;
3095 }
3096
3097 NTSTATUS smb2cli_req_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
3098                           struct iovec **piov,
3099                           const struct smb2cli_req_expected_response *expected,
3100                           size_t num_expected)
3101 {
3102         struct smbXcli_req_state *state =
3103                 tevent_req_data(req,
3104                 struct smbXcli_req_state);
3105         NTSTATUS status;
3106         size_t body_size;
3107         bool found_status = false;
3108         bool found_size = false;
3109         size_t i;
3110
3111         if (piov != NULL) {
3112                 *piov = NULL;
3113         }
3114
3115         if (state->smb2.got_async) {
3116                 return STATUS_PENDING;
3117         }
3118
3119         if (tevent_req_is_nterror(req, &status)) {
3120                 for (i=0; i < num_expected; i++) {
3121                         if (NT_STATUS_EQUAL(status, expected[i].status)) {
3122                                 found_status = true;
3123                                 break;
3124                         }
3125                 }
3126
3127                 if (found_status) {
3128                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
3129                 }
3130
3131                 return status;
3132         }
3133
3134         if (num_expected == 0) {
3135                 found_status = true;
3136                 found_size = true;
3137         }
3138
3139         status = NT_STATUS(IVAL(state->smb2.recv_iov[0].iov_base, SMB2_HDR_STATUS));
3140         body_size = SVAL(state->smb2.recv_iov[1].iov_base, 0);
3141
3142         for (i=0; i < num_expected; i++) {
3143                 if (!NT_STATUS_EQUAL(status, expected[i].status)) {
3144                         continue;
3145                 }
3146
3147                 found_status = true;
3148                 if (expected[i].body_size == 0) {
3149                         found_size = true;
3150                         break;
3151                 }
3152
3153                 if (expected[i].body_size == body_size) {
3154                         found_size = true;
3155                         break;
3156                 }
3157         }
3158
3159         if (!found_status) {
3160                 return status;
3161         }
3162
3163         if (state->smb2.signing_skipped) {
3164                 if (num_expected > 0) {
3165                         return NT_STATUS_ACCESS_DENIED;
3166                 }
3167                 if (!NT_STATUS_IS_ERR(status)) {
3168                         return NT_STATUS_ACCESS_DENIED;
3169                 }
3170         }
3171
3172         if (!found_size) {
3173                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
3174         }
3175
3176         if (piov != NULL) {
3177                 *piov = talloc_move(mem_ctx, &state->smb2.recv_iov);
3178         }
3179
3180         return status;
3181 }
3182
3183 static const struct {
3184         enum protocol_types proto;
3185         const char *smb1_name;
3186 } smb1cli_prots[] = {
3187         {PROTOCOL_CORE,         "PC NETWORK PROGRAM 1.0"},
3188         {PROTOCOL_COREPLUS,     "MICROSOFT NETWORKS 1.03"},
3189         {PROTOCOL_LANMAN1,      "MICROSOFT NETWORKS 3.0"},
3190         {PROTOCOL_LANMAN1,      "LANMAN1.0"},
3191         {PROTOCOL_LANMAN2,      "LM1.2X002"},
3192         {PROTOCOL_LANMAN2,      "DOS LANMAN2.1"},
3193         {PROTOCOL_LANMAN2,      "LANMAN2.1"},
3194         {PROTOCOL_LANMAN2,      "Samba"},
3195         {PROTOCOL_NT1,          "NT LANMAN 1.0"},
3196         {PROTOCOL_NT1,          "NT LM 0.12"},
3197         {PROTOCOL_SMB2_02,      "SMB 2.002"},
3198         {PROTOCOL_SMB2_10,      "SMB 2.???"},
3199 };
3200
3201 static const struct {
3202         enum protocol_types proto;
3203         uint16_t smb2_dialect;
3204 } smb2cli_prots[] = {
3205         {PROTOCOL_SMB2_02,      SMB2_DIALECT_REVISION_202},
3206         {PROTOCOL_SMB2_10,      SMB2_DIALECT_REVISION_210},
3207         {PROTOCOL_SMB2_22,      SMB2_DIALECT_REVISION_222},
3208         {PROTOCOL_SMB2_24,      SMB2_DIALECT_REVISION_224},
3209 };
3210
3211 struct smbXcli_negprot_state {
3212         struct smbXcli_conn *conn;
3213         struct tevent_context *ev;
3214         uint32_t timeout_msec;
3215         enum protocol_types min_protocol;
3216         enum protocol_types max_protocol;
3217
3218         struct {
3219                 uint8_t fixed[36];
3220                 uint8_t dyn[ARRAY_SIZE(smb2cli_prots)*2];
3221         } smb2;
3222 };
3223
3224 static void smbXcli_negprot_invalid_done(struct tevent_req *subreq);
3225 static struct tevent_req *smbXcli_negprot_smb1_subreq(struct smbXcli_negprot_state *state);
3226 static void smbXcli_negprot_smb1_done(struct tevent_req *subreq);
3227 static struct tevent_req *smbXcli_negprot_smb2_subreq(struct smbXcli_negprot_state *state);
3228 static void smbXcli_negprot_smb2_done(struct tevent_req *subreq);
3229 static NTSTATUS smbXcli_negprot_dispatch_incoming(struct smbXcli_conn *conn,
3230                                                   TALLOC_CTX *frame,
3231                                                   uint8_t *inbuf);
3232
3233 struct tevent_req *smbXcli_negprot_send(TALLOC_CTX *mem_ctx,
3234                                         struct tevent_context *ev,
3235                                         struct smbXcli_conn *conn,
3236                                         uint32_t timeout_msec,
3237                                         enum protocol_types min_protocol,
3238                                         enum protocol_types max_protocol)
3239 {
3240         struct tevent_req *req, *subreq;
3241         struct smbXcli_negprot_state *state;
3242
3243         req = tevent_req_create(mem_ctx, &state,
3244                                 struct smbXcli_negprot_state);
3245         if (req == NULL) {
3246                 return NULL;
3247         }
3248         state->conn = conn;
3249         state->ev = ev;
3250         state->timeout_msec = timeout_msec;
3251         state->min_protocol = min_protocol;
3252         state->max_protocol = max_protocol;
3253
3254         if (min_protocol == PROTOCOL_NONE) {
3255                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3256                 return tevent_req_post(req, ev);
3257         }
3258
3259         if (max_protocol == PROTOCOL_NONE) {
3260                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3261                 return tevent_req_post(req, ev);
3262         }
3263
3264         if (min_protocol > max_protocol) {
3265                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER_MIX);
3266                 return tevent_req_post(req, ev);
3267         }
3268
3269         if ((min_protocol < PROTOCOL_SMB2_02) &&
3270             (max_protocol < PROTOCOL_SMB2_02)) {
3271                 /*
3272                  * SMB1 only...
3273                  */
3274                 conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
3275
3276                 subreq = smbXcli_negprot_smb1_subreq(state);
3277                 if (tevent_req_nomem(subreq, req)) {
3278                         return tevent_req_post(req, ev);
3279                 }
3280                 tevent_req_set_callback(subreq, smbXcli_negprot_smb1_done, req);
3281                 return req;
3282         }
3283
3284         if ((min_protocol >= PROTOCOL_SMB2_02) &&
3285             (max_protocol >= PROTOCOL_SMB2_02)) {
3286                 /*
3287                  * SMB2 only...
3288                  */
3289                 conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
3290
3291                 subreq = smbXcli_negprot_smb2_subreq(state);
3292                 if (tevent_req_nomem(subreq, req)) {
3293                         return tevent_req_post(req, ev);
3294                 }
3295                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
3296                 return req;
3297         }
3298
3299         /*
3300          * We send an SMB1 negprot with the SMB2 dialects
3301          * and expect a SMB1 or a SMB2 response.
3302          *
3303          * smbXcli_negprot_dispatch_incoming() will fix the
3304          * callback to match protocol of the response.
3305          */
3306         conn->dispatch_incoming = smbXcli_negprot_dispatch_incoming;
3307
3308         subreq = smbXcli_negprot_smb1_subreq(state);
3309         if (tevent_req_nomem(subreq, req)) {
3310                 return tevent_req_post(req, ev);
3311         }
3312         tevent_req_set_callback(subreq, smbXcli_negprot_invalid_done, req);
3313         return req;
3314 }
3315
3316 static void smbXcli_negprot_invalid_done(struct tevent_req *subreq)
3317 {
3318         struct tevent_req *req =
3319                 tevent_req_callback_data(subreq,
3320                 struct tevent_req);
3321         NTSTATUS status;
3322
3323         /*
3324          * we just want the low level error
3325          */
3326         status = tevent_req_simple_recv_ntstatus(subreq);
3327         TALLOC_FREE(subreq);
3328         if (tevent_req_nterror(req, status)) {
3329                 return;
3330         }
3331
3332         /* this should never happen */
3333         tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
3334 }
3335
3336 static struct tevent_req *smbXcli_negprot_smb1_subreq(struct smbXcli_negprot_state *state)
3337 {
3338         size_t i;
3339         DATA_BLOB bytes = data_blob_null;
3340         uint8_t flags;
3341         uint16_t flags2;
3342
3343         /* setup the protocol strings */
3344         for (i=0; i < ARRAY_SIZE(smb1cli_prots); i++) {
3345                 uint8_t c = 2;
3346                 bool ok;
3347
3348                 if (smb1cli_prots[i].proto < state->min_protocol) {
3349                         continue;
3350                 }
3351
3352                 if (smb1cli_prots[i].proto > state->max_protocol) {
3353                         continue;
3354                 }
3355
3356                 ok = data_blob_append(state, &bytes, &c, sizeof(c));
3357                 if (!ok) {
3358                         return NULL;
3359                 }
3360
3361                 /*
3362                  * We now it is already ascii and
3363                  * we want NULL termination.
3364                  */
3365                 ok = data_blob_append(state, &bytes,
3366                                       smb1cli_prots[i].smb1_name,
3367                                       strlen(smb1cli_prots[i].smb1_name)+1);
3368                 if (!ok) {
3369                         return NULL;
3370                 }
3371         }
3372
3373         smb1cli_req_flags(state->max_protocol,
3374                           state->conn->smb1.client.capabilities,
3375                           SMBnegprot,
3376                           0, 0, &flags,
3377                           0, 0, &flags2);
3378
3379         return smb1cli_req_send(state, state->ev, state->conn,
3380                                 SMBnegprot,
3381                                 flags, ~flags,
3382                                 flags2, ~flags2,
3383                                 state->timeout_msec,
3384                                 0xFFFE, 0, 0, /* pid, tid, uid */
3385                                 0, NULL, /* wct, vwv */
3386                                 bytes.length, bytes.data);
3387 }
3388
3389 static void smbXcli_negprot_smb1_done(struct tevent_req *subreq)
3390 {
3391         struct tevent_req *req =
3392                 tevent_req_callback_data(subreq,
3393                 struct tevent_req);
3394         struct smbXcli_negprot_state *state =
3395                 tevent_req_data(req,
3396                 struct smbXcli_negprot_state);
3397         struct smbXcli_conn *conn = state->conn;
3398         struct iovec *recv_iov = NULL;
3399         uint8_t *inhdr;
3400         uint8_t wct;
3401         uint16_t *vwv;
3402         uint32_t num_bytes;
3403         uint8_t *bytes;
3404         NTSTATUS status;
3405         uint16_t protnum;
3406         size_t i;
3407         size_t num_prots = 0;
3408         uint8_t flags;
3409         uint32_t client_capabilities = conn->smb1.client.capabilities;
3410         uint32_t both_capabilities;
3411         uint32_t server_capabilities = 0;
3412         uint32_t capabilities;
3413         uint32_t client_max_xmit = conn->smb1.client.max_xmit;
3414         uint32_t server_max_xmit = 0;
3415         uint32_t max_xmit;
3416         uint32_t server_max_mux = 0;
3417         uint16_t server_security_mode = 0;
3418         uint32_t server_session_key = 0;
3419         bool server_readbraw = false;
3420         bool server_writebraw = false;
3421         bool server_lockread = false;
3422         bool server_writeunlock = false;
3423         struct GUID server_guid = GUID_zero();
3424         DATA_BLOB server_gss_blob = data_blob_null;
3425         uint8_t server_challenge[8];
3426         char *server_workgroup = NULL;
3427         char *server_name = NULL;
3428         int server_time_zone = 0;
3429         NTTIME server_system_time = 0;
3430         static const struct smb1cli_req_expected_response expected[] = {
3431         {
3432                 .status = NT_STATUS_OK,
3433                 .wct = 0x11, /* NT1 */
3434         },
3435         {
3436                 .status = NT_STATUS_OK,
3437                 .wct = 0x0D, /* LM */
3438         },
3439         {
3440                 .status = NT_STATUS_OK,
3441                 .wct = 0x01, /* CORE */
3442         }
3443         };
3444
3445         ZERO_STRUCT(server_challenge);
3446
3447         status = smb1cli_req_recv(subreq, state,
3448                                   &recv_iov,
3449                                   &inhdr,
3450                                   &wct,
3451                                   &vwv,
3452                                   NULL, /* pvwv_offset */
3453                                   &num_bytes,
3454                                   &bytes,
3455                                   NULL, /* pbytes_offset */
3456                                   NULL, /* pinbuf */
3457                                   expected, ARRAY_SIZE(expected));
3458         TALLOC_FREE(subreq);
3459         if (tevent_req_nterror(req, status)) {
3460                 return;
3461         }
3462
3463         flags = CVAL(inhdr, HDR_FLG);
3464
3465         protnum = SVAL(vwv, 0);
3466
3467         for (i=0; i < ARRAY_SIZE(smb1cli_prots); i++) {
3468                 if (smb1cli_prots[i].proto < state->min_protocol) {
3469                         continue;
3470                 }
3471
3472                 if (smb1cli_prots[i].proto > state->max_protocol) {
3473                         continue;
3474                 }
3475
3476                 if (protnum != num_prots) {
3477                         num_prots++;
3478                         continue;
3479                 }
3480
3481                 conn->protocol = smb1cli_prots[i].proto;
3482                 break;
3483         }
3484
3485         if (conn->protocol == PROTOCOL_NONE) {
3486                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3487                 return;
3488         }
3489
3490         if ((conn->protocol < PROTOCOL_NT1) && conn->mandatory_signing) {
3491                 DEBUG(0,("smbXcli_negprot: SMB signing is mandatory "
3492                          "and the selected protocol level doesn't support it.\n"));
3493                 tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
3494                 return;
3495         }
3496
3497         if (flags & FLAG_SUPPORT_LOCKREAD) {
3498                 server_lockread = true;
3499                 server_writeunlock = true;
3500         }
3501
3502         if (conn->protocol >= PROTOCOL_NT1) {
3503                 const char *client_signing = NULL;
3504                 bool server_mandatory = false;
3505                 bool server_allowed = false;
3506                 const char *server_signing = NULL;
3507                 bool ok;
3508                 uint8_t key_len;
3509
3510                 if (wct != 0x11) {
3511                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3512                         return;
3513                 }
3514
3515                 /* NT protocol */
3516                 server_security_mode = CVAL(vwv + 1, 0);
3517                 server_max_mux = SVAL(vwv + 1, 1);
3518                 server_max_xmit = IVAL(vwv + 3, 1);
3519                 server_session_key = IVAL(vwv + 7, 1);
3520                 server_time_zone = SVALS(vwv + 15, 1);
3521                 server_time_zone *= 60;
3522                 /* this time arrives in real GMT */
3523                 server_system_time = BVAL(vwv + 11, 1);
3524                 server_capabilities = IVAL(vwv + 9, 1);
3525
3526                 key_len = CVAL(vwv + 16, 1);
3527
3528                 if (server_capabilities & CAP_RAW_MODE) {
3529                         server_readbraw = true;
3530                         server_writebraw = true;
3531                 }
3532                 if (server_capabilities & CAP_LOCK_AND_READ) {
3533                         server_lockread = true;
3534                 }
3535
3536                 if (server_capabilities & CAP_EXTENDED_SECURITY) {
3537                         DATA_BLOB blob1, blob2;
3538
3539                         if (num_bytes < 16) {
3540                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3541                                 return;
3542                         }
3543
3544                         blob1 = data_blob_const(bytes, 16);
3545                         status = GUID_from_data_blob(&blob1, &server_guid);
3546                         if (tevent_req_nterror(req, status)) {
3547                                 return;
3548                         }
3549
3550                         blob1 = data_blob_const(bytes+16, num_bytes-16);
3551                         blob2 = data_blob_dup_talloc(state, blob1);
3552                         if (blob1.length > 0 &&
3553                             tevent_req_nomem(blob2.data, req)) {
3554                                 return;
3555                         }
3556                         server_gss_blob = blob2;
3557                 } else {
3558                         DATA_BLOB blob1, blob2;
3559
3560                         if (num_bytes < key_len) {
3561                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3562                                 return;
3563                         }
3564
3565                         if (key_len != 0 && key_len != 8) {
3566                                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3567                                 return;
3568                         }
3569
3570                         if (key_len == 8) {
3571                                 memcpy(server_challenge, bytes, 8);
3572                         }
3573
3574                         blob1 = data_blob_const(bytes+key_len, num_bytes-key_len);
3575                         blob2 = data_blob_const(bytes+key_len, num_bytes-key_len);
3576                         if (blob1.length > 0) {
3577                                 size_t len;
3578
3579                                 len = utf16_len_n(blob1.data,
3580                                                   blob1.length);
3581                                 blob1.length = len;
3582
3583                                 ok = convert_string_talloc(state,
3584                                                            CH_UTF16LE,
3585                                                            CH_UNIX,
3586                                                            blob1.data,
3587                                                            blob1.length,
3588                                                            &server_workgroup,
3589                                                            &len);
3590                                 if (!ok) {
3591                                         status = map_nt_error_from_unix_common(errno);
3592                                         tevent_req_nterror(req, status);
3593                                         return;
3594                                 }
3595                         }
3596
3597                         blob2.data += blob1.length;
3598                         blob2.length -= blob1.length;
3599                         if (blob2.length > 0) {
3600                                 size_t len;
3601
3602                                 len = utf16_len_n(blob1.data,
3603                                                   blob1.length);
3604                                 blob1.length = len;
3605
3606                                 ok = convert_string_talloc(state,
3607                                                            CH_UTF16LE,
3608                                                            CH_UNIX,
3609                                                            blob2.data,
3610                                                            blob2.length,
3611                                                            &server_name,
3612                                                            &len);
3613                                 if (!ok) {
3614                                         status = map_nt_error_from_unix_common(errno);
3615                                         tevent_req_nterror(req, status);
3616                                         return;
3617                                 }
3618                         }
3619                 }
3620
3621                 client_signing = "disabled";
3622                 if (conn->allow_signing) {
3623                         client_signing = "allowed";
3624                 }
3625                 if (conn->mandatory_signing) {
3626                         client_signing = "required";
3627                 }
3628
3629                 server_signing = "not supported";
3630                 if (server_security_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLED) {
3631                         server_signing = "supported";
3632                         server_allowed = true;
3633                 }
3634                 if (server_security_mode & NEGOTIATE_SECURITY_SIGNATURES_REQUIRED) {
3635                         server_signing = "required";
3636                         server_mandatory = true;
3637                 }
3638
3639                 ok = smb_signing_set_negotiated(conn->smb1.signing,
3640                                                 server_allowed,
3641                                                 server_mandatory);
3642                 if (!ok) {
3643                         DEBUG(1,("cli_negprot: SMB signing is required, "
3644                                  "but client[%s] and server[%s] mismatch\n",
3645                                  client_signing, server_signing));
3646                         tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
3647                         return;
3648                 }
3649
3650         } else if (conn->protocol >= PROTOCOL_LANMAN1) {
3651                 DATA_BLOB blob1;
3652                 uint8_t key_len;
3653                 time_t t;
3654
3655                 if (wct != 0x0D) {
3656                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3657                         return;
3658                 }
3659
3660                 server_security_mode = SVAL(vwv + 1, 0);
3661                 server_max_xmit = SVAL(vwv + 2, 0);
3662                 server_max_mux = SVAL(vwv + 3, 0);
3663                 server_readbraw = ((SVAL(vwv + 5, 0) & 0x1) != 0);
3664                 server_writebraw = ((SVAL(vwv + 5, 0) & 0x2) != 0);
3665                 server_session_key = IVAL(vwv + 6, 0);
3666                 server_time_zone = SVALS(vwv + 10, 0);
3667                 server_time_zone *= 60;
3668                 /* this time is converted to GMT by make_unix_date */
3669                 t = pull_dos_date((const uint8_t *)(vwv + 8), server_time_zone);
3670                 unix_to_nt_time(&server_system_time, t);
3671                 key_len = SVAL(vwv + 11, 0);
3672
3673                 if (num_bytes < key_len) {
3674                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3675                         return;
3676                 }
3677
3678                 if (key_len != 0 && key_len != 8) {
3679                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3680                         return;
3681                 }
3682
3683                 if (key_len == 8) {
3684                         memcpy(server_challenge, bytes, 8);
3685                 }
3686
3687                 blob1 = data_blob_const(bytes+key_len, num_bytes-key_len);
3688                 if (blob1.length > 0) {
3689                         size_t len;
3690                         bool ok;
3691
3692                         len = utf16_len_n(blob1.data,
3693                                           blob1.length);
3694                         blob1.length = len;
3695
3696                         ok = convert_string_talloc(state,
3697                                                    CH_DOS,
3698                                                    CH_UNIX,
3699                                                    blob1.data,
3700                                                    blob1.length,
3701                                                    &server_workgroup,
3702                                                    &len);
3703                         if (!ok) {
3704                                 status = map_nt_error_from_unix_common(errno);
3705                                 tevent_req_nterror(req, status);
3706                                 return;
3707                         }
3708                 }
3709
3710         } else {
3711                 /* the old core protocol */
3712                 server_time_zone = get_time_zone(time(NULL));
3713                 server_max_xmit = 1024;
3714                 server_max_mux = 1;
3715         }
3716
3717         if (server_max_xmit < 1024) {
3718                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3719                 return;
3720         }
3721
3722         if (server_max_mux < 1) {
3723                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3724                 return;
3725         }
3726
3727         /*
3728          * Now calculate the negotiated capabilities
3729          * based on the mask for:
3730          * - client only flags
3731          * - flags used in both directions
3732          * - server only flags
3733          */
3734         both_capabilities = client_capabilities & server_capabilities;
3735         capabilities = client_capabilities & SMB_CAP_CLIENT_MASK;
3736         capabilities |= both_capabilities & SMB_CAP_BOTH_MASK;
3737         capabilities |= server_capabilities & SMB_CAP_SERVER_MASK;
3738
3739         max_xmit = MIN(client_max_xmit, server_max_xmit);
3740
3741         conn->smb1.server.capabilities = server_capabilities;
3742         conn->smb1.capabilities = capabilities;
3743
3744         conn->smb1.server.max_xmit = server_max_xmit;
3745         conn->smb1.max_xmit = max_xmit;
3746
3747         conn->smb1.server.max_mux = server_max_mux;
3748
3749         conn->smb1.server.security_mode = server_security_mode;
3750
3751         conn->smb1.server.readbraw = server_readbraw;
3752         conn->smb1.server.writebraw = server_writebraw;
3753         conn->smb1.server.lockread = server_lockread;
3754         conn->smb1.server.writeunlock = server_writeunlock;
3755
3756         conn->smb1.server.session_key = server_session_key;
3757
3758         talloc_steal(conn, server_gss_blob.data);
3759         conn->smb1.server.gss_blob = server_gss_blob;
3760         conn->smb1.server.guid = server_guid;
3761         memcpy(conn->smb1.server.challenge, server_challenge, 8);
3762         conn->smb1.server.workgroup = talloc_move(conn, &server_workgroup);
3763         conn->smb1.server.name = talloc_move(conn, &server_name);
3764
3765         conn->smb1.server.time_zone = server_time_zone;
3766         conn->smb1.server.system_time = server_system_time;
3767
3768         tevent_req_done(req);
3769 }
3770
3771 static struct tevent_req *smbXcli_negprot_smb2_subreq(struct smbXcli_negprot_state *state)
3772 {
3773         size_t i;
3774         uint8_t *buf;
3775         uint16_t dialect_count = 0;
3776
3777         buf = state->smb2.dyn;
3778         for (i=0; i < ARRAY_SIZE(smb2cli_prots); i++) {
3779                 if (smb2cli_prots[i].proto < state->min_protocol) {
3780                         continue;
3781                 }
3782
3783                 if (smb2cli_prots[i].proto > state->max_protocol) {
3784                         continue;
3785                 }
3786
3787                 SSVAL(buf, dialect_count*2, smb2cli_prots[i].smb2_dialect);
3788                 dialect_count++;
3789         }
3790
3791         buf = state->smb2.fixed;
3792         SSVAL(buf, 0, 36);
3793         SSVAL(buf, 2, dialect_count);
3794         SSVAL(buf, 4, state->conn->smb2.client.security_mode);
3795         SSVAL(buf, 6, 0);       /* Reserved */
3796         SSVAL(buf, 8, 0);       /* Capabilities */
3797         if (state->max_protocol >= PROTOCOL_SMB2_10) {
3798                 NTSTATUS status;
3799                 DATA_BLOB blob;
3800
3801                 status = GUID_to_ndr_blob(&state->conn->smb2.client.guid,
3802                                           state, &blob);
3803                 if (!NT_STATUS_IS_OK(status)) {
3804                         return NULL;
3805                 }
3806                 memcpy(buf+12, blob.data, 16); /* ClientGuid */
3807         } else {
3808                 memset(buf+12, 0, 16);  /* ClientGuid */
3809         }
3810         SBVAL(buf, 28, 0);      /* ClientStartTime */
3811
3812         return smb2cli_req_send(state, state->ev,
3813                                 state->conn, SMB2_OP_NEGPROT,
3814                                 0, 0, /* flags */
3815                                 state->timeout_msec,
3816                                 0xFEFF, 0, NULL, /* pid, tid, session */
3817                                 state->smb2.fixed, sizeof(state->smb2.fixed),
3818                                 state->smb2.dyn, dialect_count*2);
3819 }
3820
3821 static void smbXcli_negprot_smb2_done(struct tevent_req *subreq)
3822 {
3823         struct tevent_req *req =
3824                 tevent_req_callback_data(subreq,
3825                 struct tevent_req);
3826         struct smbXcli_negprot_state *state =
3827                 tevent_req_data(req,
3828                 struct smbXcli_negprot_state);
3829         struct smbXcli_conn *conn = state->conn;
3830         size_t security_offset, security_length;
3831         DATA_BLOB blob;
3832         NTSTATUS status;
3833         struct iovec *iov;
3834         uint8_t *body;
3835         size_t i;
3836         uint16_t dialect_revision;
3837         static const struct smb2cli_req_expected_response expected[] = {
3838         {
3839                 .status = NT_STATUS_OK,
3840                 .body_size = 0x41
3841         }
3842         };
3843
3844         status = smb2cli_req_recv(subreq, state, &iov,
3845                                   expected, ARRAY_SIZE(expected));
3846         TALLOC_FREE(subreq);
3847         if (tevent_req_nterror(req, status)) {
3848                 return;
3849         }
3850
3851         body = (uint8_t *)iov[1].iov_base;
3852
3853         dialect_revision = SVAL(body, 4);
3854
3855         for (i=0; i < ARRAY_SIZE(smb2cli_prots); i++) {
3856                 if (smb2cli_prots[i].proto < state->min_protocol) {
3857                         continue;
3858                 }
3859
3860                 if (smb2cli_prots[i].proto > state->max_protocol) {
3861                         continue;
3862                 }
3863
3864                 if (smb2cli_prots[i].smb2_dialect != dialect_revision) {
3865                         continue;
3866                 }
3867
3868                 conn->protocol = smb2cli_prots[i].proto;
3869                 break;
3870         }
3871
3872         if (conn->protocol == PROTOCOL_NONE) {
3873                 if (state->min_protocol >= PROTOCOL_SMB2_02) {
3874                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3875                         return;
3876                 }
3877
3878                 if (dialect_revision != SMB2_DIALECT_REVISION_2FF) {
3879                         tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3880                         return;
3881                 }
3882
3883                 /* make sure we do not loop forever */
3884                 state->min_protocol = PROTOCOL_SMB2_02;
3885
3886                 /*
3887                  * send a SMB2 negprot, in order to negotiate
3888                  * the SMB2 dialect.
3889                  */
3890                 subreq = smbXcli_negprot_smb2_subreq(state);
3891                 if (tevent_req_nomem(subreq, req)) {
3892                         return;
3893                 }
3894                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
3895                 return;
3896         }
3897
3898         conn->smb2.server.security_mode = SVAL(body, 2);
3899
3900         blob = data_blob_const(body + 8, 16);
3901         status = GUID_from_data_blob(&blob, &conn->smb2.server.guid);
3902         if (tevent_req_nterror(req, status)) {
3903                 return;
3904         }
3905
3906         conn->smb2.server.capabilities  = IVAL(body, 24);
3907         conn->smb2.server.max_trans_size= IVAL(body, 28);
3908         conn->smb2.server.max_read_size = IVAL(body, 32);
3909         conn->smb2.server.max_write_size= IVAL(body, 36);
3910         conn->smb2.server.system_time   = BVAL(body, 40);
3911         conn->smb2.server.start_time    = BVAL(body, 48);
3912
3913         security_offset = SVAL(body, 56);
3914         security_length = SVAL(body, 58);
3915
3916         if (security_offset != SMB2_HDR_BODY + iov[1].iov_len) {
3917                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3918                 return;
3919         }
3920
3921         if (security_length > iov[2].iov_len) {
3922                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
3923                 return;
3924         }
3925
3926         conn->smb2.server.gss_blob = data_blob_talloc(conn,
3927                                                 iov[2].iov_base,
3928                                                 security_length);
3929         if (tevent_req_nomem(conn->smb2.server.gss_blob.data, req)) {
3930                 return;
3931         }
3932
3933         tevent_req_done(req);
3934 }
3935
3936 static NTSTATUS smbXcli_negprot_dispatch_incoming(struct smbXcli_conn *conn,
3937                                                   TALLOC_CTX *tmp_mem,
3938                                                   uint8_t *inbuf)
3939 {
3940         size_t num_pending = talloc_array_length(conn->pending);
3941         struct tevent_req *subreq;
3942         struct smbXcli_req_state *substate;
3943         struct tevent_req *req;
3944         uint32_t protocol_magic = IVAL(inbuf, 4);
3945
3946         if (num_pending != 1) {
3947                 return NT_STATUS_INTERNAL_ERROR;
3948         }
3949
3950         subreq = conn->pending[0];
3951         substate = tevent_req_data(subreq, struct smbXcli_req_state);
3952         req = tevent_req_callback_data(subreq, struct tevent_req);
3953
3954         switch (protocol_magic) {
3955         case SMB_MAGIC:
3956                 tevent_req_set_callback(subreq, smbXcli_negprot_smb1_done, req);
3957                 conn->dispatch_incoming = smb1cli_conn_dispatch_incoming;
3958                 return smb1cli_conn_dispatch_incoming(conn, tmp_mem, inbuf);
3959
3960         case SMB2_MAGIC:
3961                 if (substate->smb2.recv_iov == NULL) {
3962                         /*
3963                          * For the SMB1 negprot we have move it.
3964                          */
3965                         substate->smb2.recv_iov = substate->smb1.recv_iov;
3966                         substate->smb1.recv_iov = NULL;
3967                 }
3968
3969                 /*
3970                  * we got an SMB2 answer, which consumed sequence number 0
3971                  * so we need to use 1 as the next one
3972                  */
3973                 conn->smb2.mid = 1;
3974                 tevent_req_set_callback(subreq, smbXcli_negprot_smb2_done, req);
3975                 conn->dispatch_incoming = smb2cli_conn_dispatch_incoming;
3976                 return smb2cli_conn_dispatch_incoming(conn, tmp_mem, inbuf);
3977         }
3978
3979         DEBUG(10, ("Got non-SMB PDU\n"));
3980         return NT_STATUS_INVALID_NETWORK_RESPONSE;
3981 }
3982
3983 NTSTATUS smbXcli_negprot_recv(struct tevent_req *req)
3984 {
3985         return tevent_req_simple_recv_ntstatus(req);
3986 }
3987
3988 NTSTATUS smbXcli_negprot(struct smbXcli_conn *conn,
3989                          uint32_t timeout_msec,
3990                          enum protocol_types min_protocol,
3991                          enum protocol_types max_protocol)
3992 {
3993         TALLOC_CTX *frame = talloc_stackframe();
3994         struct tevent_context *ev;
3995         struct tevent_req *req;
3996         NTSTATUS status = NT_STATUS_NO_MEMORY;
3997         bool ok;
3998
3999         if (smbXcli_conn_has_async_calls(conn)) {
4000                 /*
4001                  * Can't use sync call while an async call is in flight
4002                  */
4003                 status = NT_STATUS_INVALID_PARAMETER_MIX;
4004                 goto fail;
4005         }
4006         ev = tevent_context_init(frame);
4007         if (ev == NULL) {
4008                 goto fail;
4009         }
4010         req = smbXcli_negprot_send(frame, ev, conn, timeout_msec,
4011                                    min_protocol, max_protocol);
4012         if (req == NULL) {
4013                 goto fail;
4014         }
4015         ok = tevent_req_poll(req, ev);
4016         if (!ok) {
4017                 status = map_nt_error_from_unix_common(errno);
4018                 goto fail;
4019         }
4020         status = smbXcli_negprot_recv(req);
4021  fail:
4022         TALLOC_FREE(frame);
4023         return status;
4024 }
4025
4026 static int smbXcli_session_destructor(struct smbXcli_session *session)
4027 {
4028         if (session->conn == NULL) {
4029                 return 0;
4030         }
4031
4032         DLIST_REMOVE(session->conn->sessions, session);
4033         return 0;
4034 }
4035
4036 struct smbXcli_session *smbXcli_session_create(TALLOC_CTX *mem_ctx,
4037                                                struct smbXcli_conn *conn)
4038 {
4039         struct smbXcli_session *session;
4040
4041         session = talloc_zero(mem_ctx, struct smbXcli_session);
4042         if (session == NULL) {
4043                 return NULL;
4044         }
4045         talloc_set_destructor(session, smbXcli_session_destructor);
4046
4047         DLIST_ADD_END(conn->sessions, session, struct smbXcli_session *);
4048         session->conn = conn;
4049
4050         return session;
4051 }
4052
4053 uint8_t smb2cli_session_security_mode(struct smbXcli_session *session)
4054 {
4055         struct smbXcli_conn *conn = session->conn;
4056         uint8_t security_mode = 0;
4057
4058         if (conn == NULL) {
4059                 return security_mode;
4060         }
4061
4062         security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED;
4063         if (conn->mandatory_signing) {
4064                 security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED;
4065         }
4066
4067         return security_mode;
4068 }
4069
4070 uint64_t smb2cli_session_current_id(struct smbXcli_session *session)
4071 {
4072         return session->smb2.session_id;
4073 }
4074
4075 NTSTATUS smb2cli_session_application_key(struct smbXcli_session *session,
4076                                          TALLOC_CTX *mem_ctx,
4077                                          DATA_BLOB *key)
4078 {
4079         *key = data_blob_null;
4080
4081         if (session->smb2.application_key.length == 0) {
4082                 return NT_STATUS_NO_USER_SESSION_KEY;
4083         }
4084
4085         *key = data_blob_dup_talloc(mem_ctx, session->smb2.application_key);
4086         if (key->data == NULL) {
4087                 return NT_STATUS_NO_MEMORY;
4088         }
4089
4090         return NT_STATUS_OK;
4091 }
4092
4093 void smb2cli_session_set_id_and_flags(struct smbXcli_session *session,
4094                                       uint64_t session_id,
4095                                       uint16_t session_flags)
4096 {
4097         session->smb2.session_id = session_id;
4098         session->smb2.session_flags = session_flags;
4099 }
4100
4101 NTSTATUS smb2cli_session_set_session_key(struct smbXcli_session *session,
4102                                          const DATA_BLOB _session_key,
4103                                          const struct iovec *recv_iov)
4104 {
4105         struct smbXcli_conn *conn = session->conn;
4106         uint16_t no_sign_flags;
4107         uint8_t session_key[16];
4108         NTSTATUS status;
4109
4110         if (conn == NULL) {
4111                 return NT_STATUS_INVALID_PARAMETER_MIX;
4112         }
4113
4114         if (session->smb2.signing_key.length != 0) {
4115                 return NT_STATUS_INVALID_PARAMETER_MIX;
4116         }
4117
4118         no_sign_flags = SMB2_SESSION_FLAG_IS_GUEST | SMB2_SESSION_FLAG_IS_NULL;
4119
4120         if (session->smb2.session_flags & no_sign_flags) {
4121                 session->smb2.should_sign = false;
4122                 return NT_STATUS_OK;
4123         }
4124
4125         ZERO_STRUCT(session_key);
4126         memcpy(session_key, _session_key.data,
4127                MIN(_session_key.length, sizeof(session_key)));
4128
4129         session->smb2.signing_key = data_blob_talloc(session,
4130                                                      session_key,
4131                                                      sizeof(session_key));
4132         ZERO_STRUCT(session_key);
4133         if (session->smb2.signing_key.data == NULL) {
4134                 return NT_STATUS_NO_MEMORY;
4135         }
4136
4137         session->smb2.application_key = data_blob_dup_talloc(session,
4138                                                 session->smb2.signing_key);
4139         if (session->smb2.application_key.data == NULL) {
4140                 return NT_STATUS_NO_MEMORY;
4141         }
4142
4143         session->smb2.channel_signing_key = data_blob_dup_talloc(session,
4144                                                 session->smb2.signing_key);
4145         if (session->smb2.channel_signing_key.data == NULL) {
4146                 return NT_STATUS_NO_MEMORY;
4147         }
4148
4149         status = smb2_signing_check_pdu(session->smb2.channel_signing_key,
4150                                         recv_iov, 3);
4151         if (!NT_STATUS_IS_OK(status)) {
4152                 return status;
4153         }
4154
4155         session->smb2.should_sign = false;
4156
4157         if (conn->desire_signing) {
4158                 session->smb2.should_sign = true;
4159         }
4160
4161         if (conn->smb2.server.security_mode & SMB2_NEGOTIATE_SIGNING_REQUIRED) {
4162                 session->smb2.should_sign = true;
4163         }
4164
4165         return NT_STATUS_OK;
4166 }
4167
4168 NTSTATUS smb2cli_session_create_channel(TALLOC_CTX *mem_ctx,
4169                                         struct smbXcli_session *session1,
4170                                         struct smbXcli_conn *conn,
4171                                         struct smbXcli_session **_session2)
4172 {
4173         struct smbXcli_session *session2;
4174
4175         if (session1->smb2.signing_key.length == 0) {
4176                 return NT_STATUS_INVALID_PARAMETER_MIX;
4177         }
4178
4179         if (conn == NULL) {
4180                 return NT_STATUS_INVALID_PARAMETER_MIX;
4181         }
4182
4183         session2 = talloc_zero(mem_ctx, struct smbXcli_session);
4184         if (session2 == NULL) {
4185                 return NT_STATUS_NO_MEMORY;
4186         }
4187         session2->smb2.session_id = session1->smb2.session_id;
4188         session2->smb2.session_flags = session1->smb2.session_flags;
4189
4190         session2->smb2.signing_key = data_blob_dup_talloc(session2,
4191                                                 session1->smb2.signing_key);
4192         if (session2->smb2.signing_key.data == NULL) {
4193                 return NT_STATUS_NO_MEMORY;
4194         }
4195
4196         session2->smb2.should_sign = session1->smb2.should_sign;
4197
4198         talloc_set_destructor(session2, smbXcli_session_destructor);
4199         DLIST_ADD_END(conn->sessions, session2, struct smbXcli_session *);
4200         session2->conn = conn;
4201
4202         *_session2 = session2;
4203         return NT_STATUS_OK;
4204 }
4205
4206 NTSTATUS smb2cli_session_set_channel_key(struct smbXcli_session *session,
4207                                          const DATA_BLOB _channel_key,
4208                                          const struct iovec *recv_iov)
4209 {
4210         struct smbXcli_conn *conn = session->conn;
4211         uint8_t channel_key[16];
4212         NTSTATUS status;
4213
4214         if (conn == NULL) {
4215                 return NT_STATUS_INVALID_PARAMETER_MIX;
4216         }
4217
4218         if (session->smb2.channel_signing_key.length != 0) {
4219                 return NT_STATUS_INVALID_PARAMETER_MIX;
4220         }
4221
4222         ZERO_STRUCT(channel_key);
4223         memcpy(channel_key, _channel_key.data,
4224                MIN(_channel_key.length, sizeof(channel_key)));
4225
4226         session->smb2.channel_signing_key = data_blob_talloc(session,
4227                                                 channel_key,
4228                                                 sizeof(channel_key));
4229         ZERO_STRUCT(channel_key);
4230         if (session->smb2.channel_signing_key.data == NULL) {
4231                 return NT_STATUS_NO_MEMORY;
4232         }
4233
4234         status = smb2_signing_check_pdu(session->smb2.channel_signing_key,
4235                                         recv_iov, 3);
4236         if (!NT_STATUS_IS_OK(status)) {
4237                 return status;
4238         }
4239
4240         return NT_STATUS_OK;
4241 }