s3-tevent: only include ../lib/util/tevent wrappers where needed.
[bbaumbach/samba-autobuild/.git] / source3 / libsmb / clientgen.c
1 /* 
2    Unix SMB/CIFS implementation.
3    SMB client generic functions
4    Copyright (C) Andrew Tridgell 1994-1998
5    Copyright (C) Jeremy Allison 2007.
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 "../lib/util/tevent_ntstatus.h"
23 #include "smb_signing.h"
24 #include "async_smb.h"
25
26 /*******************************************************************
27  Setup the word count and byte count for a client smb message.
28 ********************************************************************/
29
30 int cli_set_message(char *buf,int num_words,int num_bytes,bool zero)
31 {
32         if (zero && (num_words || num_bytes)) {
33                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
34         }
35         SCVAL(buf,smb_wct,num_words);
36         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
37         smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
38         return (smb_size + num_words*2 + num_bytes);
39 }
40
41 /****************************************************************************
42  Change the timeout (in milliseconds).
43 ****************************************************************************/
44
45 unsigned int cli_set_timeout(struct cli_state *cli, unsigned int timeout)
46 {
47         unsigned int old_timeout = cli->timeout;
48         cli->timeout = timeout;
49         return old_timeout;
50 }
51
52 /****************************************************************************
53  Change the port number used to call on.
54 ****************************************************************************/
55
56 void cli_set_port(struct cli_state *cli, int port)
57 {
58         cli->port = port;
59 }
60
61 /****************************************************************************
62  convenience routine to find if we negotiated ucs2
63 ****************************************************************************/
64
65 bool cli_ucs2(struct cli_state *cli)
66 {
67         return ((cli->capabilities & CAP_UNICODE) != 0);
68 }
69
70
71 /****************************************************************************
72  Read an smb from a fd ignoring all keepalive packets.
73  The timeout is in milliseconds
74
75  This is exactly the same as receive_smb except that it never returns
76  a session keepalive packet (just as receive_smb used to do).
77  receive_smb was changed to return keepalives as the oplock processing means this call
78  should never go into a blocking read.
79 ****************************************************************************/
80
81 static ssize_t client_receive_smb(struct cli_state *cli, size_t maxlen)
82 {
83         size_t len;
84
85         for(;;) {
86                 NTSTATUS status;
87
88                 set_smb_read_error(&cli->smb_rw_error, SMB_READ_OK);
89
90                 status = receive_smb_raw(cli->fd, cli->inbuf, cli->bufsize,
91                                         cli->timeout, maxlen, &len);
92                 if (!NT_STATUS_IS_OK(status)) {
93                         DEBUG(10,("client_receive_smb failed\n"));
94                         show_msg(cli->inbuf);
95
96                         if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) {
97                                 set_smb_read_error(&cli->smb_rw_error,
98                                                    SMB_READ_EOF);
99                                 return -1;
100                         }
101
102                         if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
103                                 set_smb_read_error(&cli->smb_rw_error,
104                                                    SMB_READ_TIMEOUT);
105                                 return -1;
106                         }
107
108                         set_smb_read_error(&cli->smb_rw_error, SMB_READ_ERROR);
109                         return -1;
110                 }
111
112                 /*
113                  * I don't believe len can be < 0 with NT_STATUS_OK
114                  * returned above, but this check doesn't hurt. JRA.
115                  */
116
117                 if ((ssize_t)len < 0) {
118                         return len;
119                 }
120
121                 /* Ignore session keepalive packets. */
122                 if(CVAL(cli->inbuf,0) != SMBkeepalive) {
123                         break;
124                 }
125         }
126
127         if (cli_encryption_on(cli)) {
128                 NTSTATUS status = cli_decrypt_message(cli);
129                 if (!NT_STATUS_IS_OK(status)) {
130                         DEBUG(0, ("SMB decryption failed on incoming packet! Error %s\n",
131                                 nt_errstr(status)));
132                         cli->smb_rw_error = SMB_READ_BAD_DECRYPT;
133                         return -1;
134                 }
135         }
136
137         show_msg(cli->inbuf);
138         return len;
139 }
140
141 static bool cli_state_set_seqnum(struct cli_state *cli, uint16_t mid, uint32_t seqnum)
142 {
143         struct cli_state_seqnum *c;
144
145         for (c = cli->seqnum; c; c = c->next) {
146                 if (c->mid == mid) {
147                         c->seqnum = seqnum;
148                         return true;
149                 }
150         }
151
152         c = talloc_zero(cli, struct cli_state_seqnum);
153         if (!c) {
154                 return false;
155         }
156
157         c->mid = mid;
158         c->seqnum = seqnum;
159         c->persistent = false;
160         DLIST_ADD_END(cli->seqnum, c, struct cli_state_seqnum *);
161
162         return true;
163 }
164
165 bool cli_state_seqnum_persistent(struct cli_state *cli,
166                                  uint16_t mid)
167 {
168         struct cli_state_seqnum *c;
169
170         for (c = cli->seqnum; c; c = c->next) {
171                 if (c->mid == mid) {
172                         c->persistent = true;
173                         return true;
174                 }
175         }
176
177         return false;
178 }
179
180 bool cli_state_seqnum_remove(struct cli_state *cli,
181                              uint16_t mid)
182 {
183         struct cli_state_seqnum *c;
184
185         for (c = cli->seqnum; c; c = c->next) {
186                 if (c->mid == mid) {
187                         DLIST_REMOVE(cli->seqnum, c);
188                         TALLOC_FREE(c);
189                         return true;
190                 }
191         }
192
193         return false;
194 }
195
196 static uint32_t cli_state_get_seqnum(struct cli_state *cli, uint16_t mid)
197 {
198         struct cli_state_seqnum *c;
199
200         for (c = cli->seqnum; c; c = c->next) {
201                 if (c->mid == mid) {
202                         uint32_t seqnum = c->seqnum;
203                         if (!c->persistent) {
204                                 DLIST_REMOVE(cli->seqnum, c);
205                                 TALLOC_FREE(c);
206                         }
207                         return seqnum;
208                 }
209         }
210
211         return 0;
212 }
213
214 /****************************************************************************
215  Recv an smb.
216 ****************************************************************************/
217
218 bool cli_receive_smb(struct cli_state *cli)
219 {
220         ssize_t len;
221         uint16_t mid;
222         uint32_t seqnum;
223
224         /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
225         if (cli->fd == -1)
226                 return false; 
227
228  again:
229         len = client_receive_smb(cli, 0);
230         
231         if (len > 0) {
232                 /* it might be an oplock break request */
233                 if (!(CVAL(cli->inbuf, smb_flg) & FLAG_REPLY) &&
234                     CVAL(cli->inbuf,smb_com) == SMBlockingX &&
235                     SVAL(cli->inbuf,smb_vwv6) == 0 &&
236                     SVAL(cli->inbuf,smb_vwv7) == 0) {
237                         if (cli->oplock_handler) {
238                                 int fnum = SVAL(cli->inbuf,smb_vwv2);
239                                 unsigned char level = CVAL(cli->inbuf,smb_vwv3+1);
240                                 if (!NT_STATUS_IS_OK(cli->oplock_handler(cli, fnum, level))) {
241                                         return false;
242                                 }
243                         }
244                         /* try to prevent loops */
245                         SCVAL(cli->inbuf,smb_com,0xFF);
246                         goto again;
247                 }
248         }
249
250         /* If the server is not responding, note that now */
251         if (len < 0) {
252                 /*
253                  * only log if the connection should still be open and not when
254                  * the connection was closed due to a dropped ip message
255                  */
256                 if (cli->fd != -1) {
257                         char addr[INET6_ADDRSTRLEN];
258                         print_sockaddr(addr, sizeof(addr), &cli->dest_ss);
259                         DEBUG(0, ("Receiving SMB: Server %s stopped responding\n",
260                                 addr));
261                         close(cli->fd);
262                         cli->fd = -1;
263                 }
264                 return false;
265         }
266
267         mid = SVAL(cli->inbuf,smb_mid);
268         seqnum = cli_state_get_seqnum(cli, mid);
269
270         if (!cli_check_sign_mac(cli, cli->inbuf, seqnum+1)) {
271                 /*
272                  * If we get a signature failure in sessionsetup, then
273                  * the server sometimes just reflects the sent signature
274                  * back to us. Detect this and allow the upper layer to
275                  * retrieve the correct Windows error message.
276                  */
277                 if (CVAL(cli->outbuf,smb_com) == SMBsesssetupX &&
278                         (smb_len(cli->inbuf) > (smb_ss_field + 8 - 4)) &&
279                         (SVAL(cli->inbuf,smb_flg2) & FLAGS2_SMB_SECURITY_SIGNATURES) &&
280                         memcmp(&cli->outbuf[smb_ss_field],&cli->inbuf[smb_ss_field],8) == 0 &&
281                         cli_is_error(cli)) {
282
283                         /*
284                          * Reflected signature on login error. 
285                          * Set bad sig but don't close fd.
286                          */
287                         cli->smb_rw_error = SMB_READ_BAD_SIG;
288                         return true;
289                 }
290
291                 DEBUG(0, ("SMB Signature verification failed on incoming packet!\n"));
292                 cli->smb_rw_error = SMB_READ_BAD_SIG;
293                 close(cli->fd);
294                 cli->fd = -1;
295                 return false;
296         };
297         return true;
298 }
299
300 static ssize_t write_socket(int fd, const char *buf, size_t len)
301 {
302         ssize_t ret=0;
303
304         DEBUG(6,("write_socket(%d,%d)\n",fd,(int)len));
305         ret = write_data(fd,buf,len);
306
307         DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,(int)len,(int)ret));
308         if(ret <= 0)
309                 DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n",
310                         (int)len, fd, strerror(errno) ));
311
312         return(ret);
313 }
314
315 /****************************************************************************
316  Send an smb to a fd.
317 ****************************************************************************/
318
319 bool cli_send_smb(struct cli_state *cli)
320 {
321         size_t len;
322         size_t nwritten=0;
323         ssize_t ret;
324         char *buf_out = cli->outbuf;
325         bool enc_on = cli_encryption_on(cli);
326         uint32_t seqnum;
327
328         /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
329         if (cli->fd == -1)
330                 return false;
331
332         cli_calculate_sign_mac(cli, cli->outbuf, &seqnum);
333
334         if (!cli_state_set_seqnum(cli, cli->mid, seqnum)) {
335                 DEBUG(0,("Failed to store mid[%u]/seqnum[%u]\n",
336                         (unsigned int)cli->mid,
337                         (unsigned int)seqnum));
338                 return false;
339         }
340
341         if (enc_on) {
342                 NTSTATUS status = cli_encrypt_message(cli, cli->outbuf,
343                                                       &buf_out);
344                 if (!NT_STATUS_IS_OK(status)) {
345                         close(cli->fd);
346                         cli->fd = -1;
347                         cli->smb_rw_error = SMB_WRITE_ERROR;
348                         DEBUG(0,("Error in encrypting client message. Error %s\n",
349                                 nt_errstr(status) ));
350                         return false;
351                 }
352         }
353
354         len = smb_len(buf_out) + 4;
355
356         while (nwritten < len) {
357                 ret = write_socket(cli->fd,buf_out+nwritten,len - nwritten);
358                 if (ret <= 0) {
359                         if (enc_on) {
360                                 cli_free_enc_buffer(cli, buf_out);
361                         }
362                         close(cli->fd);
363                         cli->fd = -1;
364                         cli->smb_rw_error = SMB_WRITE_ERROR;
365                         DEBUG(0,("Error writing %d bytes to client. %d (%s)\n",
366                                 (int)len,(int)ret, strerror(errno) ));
367                         return false;
368                 }
369                 nwritten += ret;
370         }
371
372         if (enc_on) {
373                 cli_free_enc_buffer(cli, buf_out);
374         }
375
376         /* Increment the mid so we can tell between responses. */
377         cli->mid++;
378         if (!cli->mid)
379                 cli->mid++;
380         return true;
381 }
382
383 /****************************************************************************
384  Setup basics in a outgoing packet.
385 ****************************************************************************/
386
387 void cli_setup_packet_buf(struct cli_state *cli, char *buf)
388 {
389         uint16 flags2;
390         cli->rap_error = 0;
391         SIVAL(buf,smb_rcls,0);
392         SSVAL(buf,smb_pid,cli->pid);
393         memset(buf+smb_pidhigh, 0, 12);
394         SSVAL(buf,smb_uid,cli->vuid);
395         SSVAL(buf,smb_mid,cli->mid);
396
397         if (cli->protocol <= PROTOCOL_CORE) {
398                 return;
399         }
400
401         if (cli->case_sensitive) {
402                 SCVAL(buf,smb_flg,0x0);
403         } else {
404                 /* Default setting, case insensitive. */
405                 SCVAL(buf,smb_flg,0x8);
406         }
407         flags2 = FLAGS2_LONG_PATH_COMPONENTS;
408         if (cli->capabilities & CAP_UNICODE)
409                 flags2 |= FLAGS2_UNICODE_STRINGS;
410         if ((cli->capabilities & CAP_DFS) && cli->dfsroot)
411                 flags2 |= FLAGS2_DFS_PATHNAMES;
412         if (cli->capabilities & CAP_STATUS32)
413                 flags2 |= FLAGS2_32_BIT_ERROR_CODES;
414         if (cli->use_spnego)
415                 flags2 |= FLAGS2_EXTENDED_SECURITY;
416         SSVAL(buf,smb_flg2, flags2);
417 }
418
419 void cli_setup_packet(struct cli_state *cli)
420 {
421         cli_setup_packet_buf(cli, cli->outbuf);
422 }
423
424 /****************************************************************************
425  Setup the bcc length of the packet from a pointer to the end of the data.
426 ****************************************************************************/
427
428 void cli_setup_bcc(struct cli_state *cli, void *p)
429 {
430         set_message_bcc(cli->outbuf, PTR_DIFF(p, smb_buf(cli->outbuf)));
431 }
432
433 /****************************************************************************
434  Initialize Domain, user or password.
435 ****************************************************************************/
436
437 NTSTATUS cli_set_domain(struct cli_state *cli, const char *domain)
438 {
439         TALLOC_FREE(cli->domain);
440         cli->domain = talloc_strdup(cli, domain ? domain : "");
441         if (cli->domain == NULL) {
442                 return NT_STATUS_NO_MEMORY;
443         }
444         return NT_STATUS_OK;
445 }
446
447 NTSTATUS cli_set_username(struct cli_state *cli, const char *username)
448 {
449         TALLOC_FREE(cli->user_name);
450         cli->user_name = talloc_strdup(cli, username ? username : "");
451         if (cli->user_name == NULL) {
452                 return NT_STATUS_NO_MEMORY;
453         }
454         return NT_STATUS_OK;
455 }
456
457 NTSTATUS cli_set_password(struct cli_state *cli, const char *password)
458 {
459         TALLOC_FREE(cli->password);
460
461         /* Password can be NULL. */
462         if (password) {
463                 cli->password = talloc_strdup(cli, password);
464                 if (cli->password == NULL) {
465                         return NT_STATUS_NO_MEMORY;
466                 }
467         } else {
468                 /* Use zero NTLMSSP hashes and session key. */
469                 cli->password = NULL;
470         }
471
472         return NT_STATUS_OK;
473 }
474
475 /****************************************************************************
476  Initialise credentials of a client structure.
477 ****************************************************************************/
478
479 NTSTATUS cli_init_creds(struct cli_state *cli, const char *username, const char *domain, const char *password)
480 {
481         NTSTATUS status = cli_set_username(cli, username);
482         if (!NT_STATUS_IS_OK(status)) {
483                 return status;
484         }
485         status = cli_set_domain(cli, domain);
486         if (!NT_STATUS_IS_OK(status)) {
487                 return status;
488         }
489         DEBUG(10,("cli_init_creds: user %s domain %s\n", cli->user_name, cli->domain));
490
491         return cli_set_password(cli, password);
492 }
493
494 /****************************************************************************
495  Initialise a client structure. Always returns a talloc'ed struct.
496  Set the signing state (used from the command line).
497 ****************************************************************************/
498
499 struct cli_state *cli_initialise_ex(int signing_state)
500 {
501         struct cli_state *cli = NULL;
502         bool allow_smb_signing = false;
503         bool mandatory_signing = false;
504
505         /* Check the effective uid - make sure we are not setuid */
506         if (is_setuid_root()) {
507                 DEBUG(0,("libsmb based programs must *NOT* be setuid root.\n"));
508                 return NULL;
509         }
510
511         cli = TALLOC_ZERO_P(NULL, struct cli_state);
512         if (!cli) {
513                 return NULL;
514         }
515
516         cli->dfs_mountpoint = talloc_strdup(cli, "");
517         if (!cli->dfs_mountpoint) {
518                 goto error;
519         }
520         cli->port = 0;
521         cli->fd = -1;
522         cli->cnum = -1;
523         cli->pid = (uint16)sys_getpid();
524         cli->mid = 1;
525         cli->vuid = UID_FIELD_INVALID;
526         cli->protocol = PROTOCOL_NT1;
527         cli->timeout = 20000; /* Timeout is in milliseconds. */
528         cli->bufsize = CLI_BUFFER_SIZE+4;
529         cli->max_xmit = cli->bufsize;
530         cli->outbuf = (char *)SMB_MALLOC(cli->bufsize+SAFETY_MARGIN);
531         cli->seqnum = 0;
532         cli->inbuf = (char *)SMB_MALLOC(cli->bufsize+SAFETY_MARGIN);
533         cli->oplock_handler = cli_oplock_ack;
534         cli->case_sensitive = false;
535         cli->smb_rw_error = SMB_READ_OK;
536
537         cli->use_spnego = lp_client_use_spnego();
538
539         cli->capabilities = CAP_UNICODE | CAP_STATUS32 | CAP_DFS;
540
541         /* Set the CLI_FORCE_DOSERR environment variable to test
542            client routines using DOS errors instead of STATUS32
543            ones.  This intended only as a temporary hack. */    
544         if (getenv("CLI_FORCE_DOSERR"))
545                 cli->force_dos_errors = true;
546
547         if (lp_client_signing()) {
548                 allow_smb_signing = true;
549         }
550
551         if (lp_client_signing() == Required) {
552                 mandatory_signing = true;
553         }
554
555         if (signing_state != Undefined) {
556                 allow_smb_signing = true;
557         }
558
559         if (signing_state == false) {
560                 allow_smb_signing = false;
561                 mandatory_signing = false;
562         }
563
564         if (signing_state == Required) {
565                 mandatory_signing = true;
566         }
567
568         if (!cli->outbuf || !cli->inbuf)
569                 goto error;
570
571         memset(cli->outbuf, 0, cli->bufsize);
572         memset(cli->inbuf, 0, cli->bufsize);
573
574         /* initialise signing */
575         cli->signing_state = smb_signing_init(cli,
576                                               allow_smb_signing,
577                                               mandatory_signing);
578         if (!cli->signing_state) {
579                 goto error;
580         }
581
582         cli->outgoing = tevent_queue_create(cli, "cli_outgoing");
583         if (cli->outgoing == NULL) {
584                 goto error;
585         }
586         cli->pending = NULL;
587
588         cli->initialised = 1;
589
590         return cli;
591
592         /* Clean up after malloc() error */
593
594  error:
595
596         SAFE_FREE(cli->inbuf);
597         SAFE_FREE(cli->outbuf);
598         TALLOC_FREE(cli);
599         return NULL;
600 }
601
602 struct cli_state *cli_initialise(void)
603 {
604         return cli_initialise_ex(Undefined);
605 }
606
607 /****************************************************************************
608  Close all pipes open on this session.
609 ****************************************************************************/
610
611 void cli_nt_pipes_close(struct cli_state *cli)
612 {
613         while (cli->pipe_list != NULL) {
614                 /*
615                  * No TALLOC_FREE here!
616                  */
617                 talloc_free(cli->pipe_list);
618         }
619 }
620
621 /****************************************************************************
622  Shutdown a client structure.
623 ****************************************************************************/
624
625 static void _cli_shutdown(struct cli_state *cli)
626 {
627         cli_nt_pipes_close(cli);
628
629         /*
630          * tell our peer to free his resources.  Wihtout this, when an
631          * application attempts to do a graceful shutdown and calls
632          * smbc_free_context() to clean up all connections, some connections
633          * can remain active on the peer end, until some (long) timeout period
634          * later.  This tree disconnect forces the peer to clean up, since the
635          * connection will be going away.
636          *
637          * Also, do not do tree disconnect when cli->smb_rw_error is SMB_DO_NOT_DO_TDIS
638          * the only user for this so far is smbmount which passes opened connection
639          * down to kernel's smbfs module.
640          */
641         if ( (cli->cnum != (uint16)-1) && (cli->smb_rw_error != SMB_DO_NOT_DO_TDIS ) ) {
642                 cli_tdis(cli);
643         }
644         
645         SAFE_FREE(cli->outbuf);
646         SAFE_FREE(cli->inbuf);
647
648         data_blob_free(&cli->secblob);
649         data_blob_free(&cli->user_session_key);
650
651         if (cli->fd != -1) {
652                 close(cli->fd);
653         }
654         cli->fd = -1;
655         cli->smb_rw_error = SMB_READ_OK;
656
657         /*
658          * Need to free pending first, they remove themselves
659          */
660         while (cli->pending) {
661                 talloc_free(cli->pending[0]);
662         }
663         TALLOC_FREE(cli);
664 }
665
666 void cli_shutdown(struct cli_state *cli)
667 {
668         struct cli_state *cli_head;
669         if (cli == NULL) {
670                 return;
671         }
672         DLIST_HEAD(cli, cli_head);
673         if (cli_head == cli) {
674                 /*
675                  * head of a DFS list, shutdown all subsidiary DFS
676                  * connections.
677                  */
678                 struct cli_state *p, *next;
679
680                 for (p = cli_head->next; p; p = next) {
681                         next = p->next;
682                         DLIST_REMOVE(cli_head, p);
683                         _cli_shutdown(p);
684                 }
685         } else {
686                 DLIST_REMOVE(cli_head, cli);
687         }
688
689         _cli_shutdown(cli);
690 }
691
692 /****************************************************************************
693  Set socket options on a open connection.
694 ****************************************************************************/
695
696 void cli_sockopt(struct cli_state *cli, const char *options)
697 {
698         set_socket_options(cli->fd, options);
699 }
700
701 /****************************************************************************
702  Set the PID to use for smb messages. Return the old pid.
703 ****************************************************************************/
704
705 uint16 cli_setpid(struct cli_state *cli, uint16 pid)
706 {
707         uint16 ret = cli->pid;
708         cli->pid = pid;
709         return ret;
710 }
711
712 /****************************************************************************
713  Set the case sensitivity flag on the packets. Returns old state.
714 ****************************************************************************/
715
716 bool cli_set_case_sensitive(struct cli_state *cli, bool case_sensitive)
717 {
718         bool ret = cli->case_sensitive;
719         cli->case_sensitive = case_sensitive;
720         return ret;
721 }
722
723 struct cli_echo_state {
724         uint16_t vwv[1];
725         DATA_BLOB data;
726         int num_echos;
727 };
728
729 static void cli_echo_done(struct tevent_req *subreq);
730
731 struct tevent_req *cli_echo_send(TALLOC_CTX *mem_ctx, struct event_context *ev,
732                                  struct cli_state *cli, uint16_t num_echos,
733                                  DATA_BLOB data)
734 {
735         struct tevent_req *req, *subreq;
736         struct cli_echo_state *state;
737
738         req = tevent_req_create(mem_ctx, &state, struct cli_echo_state);
739         if (req == NULL) {
740                 return NULL;
741         }
742         SSVAL(state->vwv, 0, num_echos);
743         state->data = data;
744         state->num_echos = num_echos;
745
746         subreq = cli_smb_send(state, ev, cli, SMBecho, 0, 1, state->vwv,
747                               data.length, data.data);
748         if (subreq == NULL) {
749                 goto fail;
750         }
751         tevent_req_set_callback(subreq, cli_echo_done, req);
752         return req;
753  fail:
754         TALLOC_FREE(req);
755         return NULL;
756 }
757
758 static void cli_echo_done(struct tevent_req *subreq)
759 {
760         struct tevent_req *req = tevent_req_callback_data(
761                 subreq, struct tevent_req);
762         struct cli_echo_state *state = tevent_req_data(
763                 req, struct cli_echo_state);
764         NTSTATUS status;
765         uint32_t num_bytes;
766         uint8_t *bytes;
767         uint8_t *inbuf;
768
769         status = cli_smb_recv(subreq, state, &inbuf, 0, NULL, NULL,
770                               &num_bytes, &bytes);
771         if (!NT_STATUS_IS_OK(status)) {
772                 tevent_req_nterror(req, status);
773                 return;
774         }
775         if ((num_bytes != state->data.length)
776             || (memcmp(bytes, state->data.data, num_bytes) != 0)) {
777                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
778                 return;
779         }
780
781         state->num_echos -=1;
782         if (state->num_echos == 0) {
783                 tevent_req_done(req);
784                 return;
785         }
786
787         if (!cli_smb_req_set_pending(subreq)) {
788                 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
789                 return;
790         }
791 }
792
793 /**
794  * Get the result out from an echo request
795  * @param[in] req       The async_req from cli_echo_send
796  * @retval Did the server reply correctly?
797  */
798
799 NTSTATUS cli_echo_recv(struct tevent_req *req)
800 {
801         return tevent_req_simple_recv_ntstatus(req);
802 }
803
804 /**
805  * @brief Send/Receive SMBEcho requests
806  * @param[in] mem_ctx   The memory context to put the async_req on
807  * @param[in] ev        The event context that will call us back
808  * @param[in] cli       The connection to send the echo to
809  * @param[in] num_echos How many times do we want to get the reply?
810  * @param[in] data      The data we want to get back
811  * @retval Did the server reply correctly?
812  */
813
814 NTSTATUS cli_echo(struct cli_state *cli, uint16_t num_echos, DATA_BLOB data)
815 {
816         TALLOC_CTX *frame = talloc_stackframe();
817         struct event_context *ev;
818         struct tevent_req *req;
819         NTSTATUS status = NT_STATUS_OK;
820
821         if (cli_has_async_calls(cli)) {
822                 /*
823                  * Can't use sync call while an async call is in flight
824                  */
825                 status = NT_STATUS_INVALID_PARAMETER;
826                 goto fail;
827         }
828
829         ev = event_context_init(frame);
830         if (ev == NULL) {
831                 status = NT_STATUS_NO_MEMORY;
832                 goto fail;
833         }
834
835         req = cli_echo_send(frame, ev, cli, num_echos, data);
836         if (req == NULL) {
837                 status = NT_STATUS_NO_MEMORY;
838                 goto fail;
839         }
840
841         if (!tevent_req_poll(req, ev)) {
842                 status = map_nt_error_from_unix(errno);
843                 goto fail;
844         }
845
846         status = cli_echo_recv(req);
847  fail:
848         TALLOC_FREE(frame);
849         if (!NT_STATUS_IS_OK(status)) {
850                 cli_set_error(cli, status);
851         }
852         return status;
853 }
854
855 /**
856  * Is the SMB command able to hold an AND_X successor
857  * @param[in] cmd       The SMB command in question
858  * @retval Can we add a chained request after "cmd"?
859  */
860 bool is_andx_req(uint8_t cmd)
861 {
862         switch (cmd) {
863         case SMBtconX:
864         case SMBlockingX:
865         case SMBopenX:
866         case SMBreadX:
867         case SMBwriteX:
868         case SMBsesssetupX:
869         case SMBulogoffX:
870         case SMBntcreateX:
871                 return true;
872                 break;
873         default:
874                 break;
875         }
876
877         return false;
878 }
879
880 NTSTATUS cli_smb(TALLOC_CTX *mem_ctx, struct cli_state *cli,
881                  uint8_t smb_command, uint8_t additional_flags,
882                  uint8_t wct, uint16_t *vwv,
883                  uint32_t num_bytes, const uint8_t *bytes,
884                  struct tevent_req **result_parent,
885                  uint8_t min_wct, uint8_t *pwct, uint16_t **pvwv,
886                  uint32_t *pnum_bytes, uint8_t **pbytes)
887 {
888         struct tevent_context *ev;
889         struct tevent_req *req = NULL;
890         NTSTATUS status = NT_STATUS_NO_MEMORY;
891
892         if (cli_has_async_calls(cli)) {
893                 return NT_STATUS_INVALID_PARAMETER;
894         }
895         ev = tevent_context_init(mem_ctx);
896         if (ev == NULL) {
897                 goto fail;
898         }
899         req = cli_smb_send(mem_ctx, ev, cli, smb_command, additional_flags,
900                            wct, vwv, num_bytes, bytes);
901         if (req == NULL) {
902                 goto fail;
903         }
904         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
905                 goto fail;
906         }
907         status = cli_smb_recv(req, NULL, NULL, min_wct, pwct, pvwv,
908                               pnum_bytes, pbytes);
909 fail:
910         TALLOC_FREE(ev);
911         if (NT_STATUS_IS_OK(status) && (result_parent != NULL)) {
912                 *result_parent = req;
913         }
914         return status;
915 }