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