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