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