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