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