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