s3-build: only include smb_signing.h where needed.
[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                 DEBUG(0, ("Receiving SMB: Server stopped responding\n"));
251                 close(cli->fd);
252                 cli->fd = -1;
253                 return false;
254         }
255
256         mid = SVAL(cli->inbuf,smb_mid);
257         seqnum = cli_state_get_seqnum(cli, mid);
258
259         if (!cli_check_sign_mac(cli, cli->inbuf, seqnum+1)) {
260                 /*
261                  * If we get a signature failure in sessionsetup, then
262                  * the server sometimes just reflects the sent signature
263                  * back to us. Detect this and allow the upper layer to
264                  * retrieve the correct Windows error message.
265                  */
266                 if (CVAL(cli->outbuf,smb_com) == SMBsesssetupX &&
267                         (smb_len(cli->inbuf) > (smb_ss_field + 8 - 4)) &&
268                         (SVAL(cli->inbuf,smb_flg2) & FLAGS2_SMB_SECURITY_SIGNATURES) &&
269                         memcmp(&cli->outbuf[smb_ss_field],&cli->inbuf[smb_ss_field],8) == 0 &&
270                         cli_is_error(cli)) {
271
272                         /*
273                          * Reflected signature on login error. 
274                          * Set bad sig but don't close fd.
275                          */
276                         cli->smb_rw_error = SMB_READ_BAD_SIG;
277                         return true;
278                 }
279
280                 DEBUG(0, ("SMB Signature verification failed on incoming packet!\n"));
281                 cli->smb_rw_error = SMB_READ_BAD_SIG;
282                 close(cli->fd);
283                 cli->fd = -1;
284                 return false;
285         };
286         return true;
287 }
288
289 static ssize_t write_socket(int fd, const char *buf, size_t len)
290 {
291         ssize_t ret=0;
292
293         DEBUG(6,("write_socket(%d,%d)\n",fd,(int)len));
294         ret = write_data(fd,buf,len);
295
296         DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,(int)len,(int)ret));
297         if(ret <= 0)
298                 DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n",
299                         (int)len, fd, strerror(errno) ));
300
301         return(ret);
302 }
303
304 /****************************************************************************
305  Send an smb to a fd.
306 ****************************************************************************/
307
308 bool cli_send_smb(struct cli_state *cli)
309 {
310         size_t len;
311         size_t nwritten=0;
312         ssize_t ret;
313         char *buf_out = cli->outbuf;
314         bool enc_on = cli_encryption_on(cli);
315         uint32_t seqnum;
316
317         /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
318         if (cli->fd == -1)
319                 return false;
320
321         cli_calculate_sign_mac(cli, cli->outbuf, &seqnum);
322
323         if (!cli_state_set_seqnum(cli, cli->mid, seqnum)) {
324                 DEBUG(0,("Failed to store mid[%u]/seqnum[%u]\n",
325                         (unsigned int)cli->mid,
326                         (unsigned int)seqnum));
327                 return false;
328         }
329
330         if (enc_on) {
331                 NTSTATUS status = cli_encrypt_message(cli, cli->outbuf,
332                                                       &buf_out);
333                 if (!NT_STATUS_IS_OK(status)) {
334                         close(cli->fd);
335                         cli->fd = -1;
336                         cli->smb_rw_error = SMB_WRITE_ERROR;
337                         DEBUG(0,("Error in encrypting client message. Error %s\n",
338                                 nt_errstr(status) ));
339                         return false;
340                 }
341         }
342
343         len = smb_len(buf_out) + 4;
344
345         while (nwritten < len) {
346                 ret = write_socket(cli->fd,buf_out+nwritten,len - nwritten);
347                 if (ret <= 0) {
348                         if (enc_on) {
349                                 cli_free_enc_buffer(cli, buf_out);
350                         }
351                         close(cli->fd);
352                         cli->fd = -1;
353                         cli->smb_rw_error = SMB_WRITE_ERROR;
354                         DEBUG(0,("Error writing %d bytes to client. %d (%s)\n",
355                                 (int)len,(int)ret, strerror(errno) ));
356                         return false;
357                 }
358                 nwritten += ret;
359         }
360
361         if (enc_on) {
362                 cli_free_enc_buffer(cli, buf_out);
363         }
364
365         /* Increment the mid so we can tell between responses. */
366         cli->mid++;
367         if (!cli->mid)
368                 cli->mid++;
369         return true;
370 }
371
372 /****************************************************************************
373  Send a "direct" writeX smb to a fd.
374 ****************************************************************************/
375
376 bool cli_send_smb_direct_writeX(struct cli_state *cli,
377                                 const char *p,
378                                 size_t extradata)
379 {
380         /* First length to send is the offset to the data. */
381         size_t len = SVAL(cli->outbuf,smb_vwv11) + 4;
382         size_t nwritten=0;
383         struct iovec iov[2];
384
385         /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
386         if (cli->fd == -1) {
387                 return false;
388         }
389
390         if (client_is_signing_on(cli)) {
391                 DEBUG(0,("cli_send_smb_large: cannot send signed packet.\n"));
392                 return false;
393         }
394
395         iov[0].iov_base = (void *)cli->outbuf;
396         iov[0].iov_len = len;
397         iov[1].iov_base = CONST_DISCARD(void *, p);
398         iov[1].iov_len = extradata;
399
400         nwritten = write_data_iov(cli->fd, iov, 2);
401         if (nwritten < (len + extradata)) {
402                 close(cli->fd);
403                 cli->fd = -1;
404                 cli->smb_rw_error = SMB_WRITE_ERROR;
405                 DEBUG(0,("Error writing %d bytes to client. (%s)\n",
406                          (int)(len+extradata), strerror(errno)));
407                 return false;
408         }
409
410         /* Increment the mid so we can tell between responses. */
411         cli->mid++;
412         if (!cli->mid)
413                 cli->mid++;
414         return true;
415 }
416
417 /****************************************************************************
418  Setup basics in a outgoing packet.
419 ****************************************************************************/
420
421 void cli_setup_packet_buf(struct cli_state *cli, char *buf)
422 {
423         uint16 flags2;
424         cli->rap_error = 0;
425         SIVAL(buf,smb_rcls,0);
426         SSVAL(buf,smb_pid,cli->pid);
427         memset(buf+smb_pidhigh, 0, 12);
428         SSVAL(buf,smb_uid,cli->vuid);
429         SSVAL(buf,smb_mid,cli->mid);
430
431         if (cli->protocol <= PROTOCOL_CORE) {
432                 return;
433         }
434
435         if (cli->case_sensitive) {
436                 SCVAL(buf,smb_flg,0x0);
437         } else {
438                 /* Default setting, case insensitive. */
439                 SCVAL(buf,smb_flg,0x8);
440         }
441         flags2 = FLAGS2_LONG_PATH_COMPONENTS;
442         if (cli->capabilities & CAP_UNICODE)
443                 flags2 |= FLAGS2_UNICODE_STRINGS;
444         if ((cli->capabilities & CAP_DFS) && cli->dfsroot)
445                 flags2 |= FLAGS2_DFS_PATHNAMES;
446         if (cli->capabilities & CAP_STATUS32)
447                 flags2 |= FLAGS2_32_BIT_ERROR_CODES;
448         if (cli->use_spnego)
449                 flags2 |= FLAGS2_EXTENDED_SECURITY;
450         SSVAL(buf,smb_flg2, flags2);
451 }
452
453 void cli_setup_packet(struct cli_state *cli)
454 {
455         cli_setup_packet_buf(cli, cli->outbuf);
456 }
457
458 /****************************************************************************
459  Setup the bcc length of the packet from a pointer to the end of the data.
460 ****************************************************************************/
461
462 void cli_setup_bcc(struct cli_state *cli, void *p)
463 {
464         set_message_bcc(cli->outbuf, PTR_DIFF(p, smb_buf(cli->outbuf)));
465 }
466
467 /****************************************************************************
468  Initialize Domain, user or password.
469 ****************************************************************************/
470
471 NTSTATUS cli_set_domain(struct cli_state *cli, const char *domain)
472 {
473         TALLOC_FREE(cli->domain);
474         cli->domain = talloc_strdup(cli, domain ? domain : "");
475         if (cli->domain == NULL) {
476                 return NT_STATUS_NO_MEMORY;
477         }
478         return NT_STATUS_OK;
479 }
480
481 NTSTATUS cli_set_username(struct cli_state *cli, const char *username)
482 {
483         TALLOC_FREE(cli->user_name);
484         cli->user_name = talloc_strdup(cli, username ? username : "");
485         if (cli->user_name == NULL) {
486                 return NT_STATUS_NO_MEMORY;
487         }
488         return NT_STATUS_OK;
489 }
490
491 NTSTATUS cli_set_password(struct cli_state *cli, const char *password)
492 {
493         TALLOC_FREE(cli->password);
494
495         /* Password can be NULL. */
496         if (password) {
497                 cli->password = talloc_strdup(cli, password);
498                 if (cli->password == NULL) {
499                         return NT_STATUS_NO_MEMORY;
500                 }
501         } else {
502                 /* Use zero NTLMSSP hashes and session key. */
503                 cli->password = NULL;
504         }
505
506         return NT_STATUS_OK;
507 }
508
509 /****************************************************************************
510  Initialise credentials of a client structure.
511 ****************************************************************************/
512
513 NTSTATUS cli_init_creds(struct cli_state *cli, const char *username, const char *domain, const char *password)
514 {
515         NTSTATUS status = cli_set_username(cli, username);
516         if (!NT_STATUS_IS_OK(status)) {
517                 return status;
518         }
519         status = cli_set_domain(cli, domain);
520         if (!NT_STATUS_IS_OK(status)) {
521                 return status;
522         }
523         DEBUG(10,("cli_init_creds: user %s domain %s\n", cli->user_name, cli->domain));
524
525         return cli_set_password(cli, password);
526 }
527
528 /****************************************************************************
529  Initialise a client structure. Always returns a talloc'ed struct.
530  Set the signing state (used from the command line).
531 ****************************************************************************/
532
533 struct cli_state *cli_initialise_ex(int signing_state)
534 {
535         struct cli_state *cli = NULL;
536         bool allow_smb_signing = false;
537         bool mandatory_signing = false;
538
539         /* Check the effective uid - make sure we are not setuid */
540         if (is_setuid_root()) {
541                 DEBUG(0,("libsmb based programs must *NOT* be setuid root.\n"));
542                 return NULL;
543         }
544
545         cli = TALLOC_ZERO_P(NULL, struct cli_state);
546         if (!cli) {
547                 return NULL;
548         }
549
550         cli->dfs_mountpoint = talloc_strdup(cli, "");
551         if (!cli->dfs_mountpoint) {
552                 goto error;
553         }
554         cli->port = 0;
555         cli->fd = -1;
556         cli->cnum = -1;
557         cli->pid = (uint16)sys_getpid();
558         cli->mid = 1;
559         cli->vuid = UID_FIELD_INVALID;
560         cli->protocol = PROTOCOL_NT1;
561         cli->timeout = 20000; /* Timeout is in milliseconds. */
562         cli->bufsize = CLI_BUFFER_SIZE+4;
563         cli->max_xmit = cli->bufsize;
564         cli->outbuf = (char *)SMB_MALLOC(cli->bufsize+SAFETY_MARGIN);
565         cli->seqnum = 0;
566         cli->inbuf = (char *)SMB_MALLOC(cli->bufsize+SAFETY_MARGIN);
567         cli->oplock_handler = cli_oplock_ack;
568         cli->case_sensitive = false;
569         cli->smb_rw_error = SMB_READ_OK;
570
571         cli->use_spnego = lp_client_use_spnego();
572
573         cli->capabilities = CAP_UNICODE | CAP_STATUS32 | CAP_DFS;
574
575         /* Set the CLI_FORCE_DOSERR environment variable to test
576            client routines using DOS errors instead of STATUS32
577            ones.  This intended only as a temporary hack. */    
578         if (getenv("CLI_FORCE_DOSERR"))
579                 cli->force_dos_errors = true;
580
581         if (lp_client_signing()) {
582                 allow_smb_signing = true;
583         }
584
585         if (lp_client_signing() == Required) {
586                 mandatory_signing = true;
587         }
588
589         if (signing_state != Undefined) {
590                 allow_smb_signing = true;
591         }
592
593         if (signing_state == false) {
594                 allow_smb_signing = false;
595                 mandatory_signing = false;
596         }
597
598         if (signing_state == Required) {
599                 mandatory_signing = true;
600         }
601
602         if (!cli->outbuf || !cli->inbuf)
603                 goto error;
604
605         memset(cli->outbuf, 0, cli->bufsize);
606         memset(cli->inbuf, 0, cli->bufsize);
607
608
609 #if defined(DEVELOPER)
610         /* just because we over-allocate, doesn't mean it's right to use it */
611         clobber_region(FUNCTION_MACRO, __LINE__, cli->outbuf+cli->bufsize, SAFETY_MARGIN);
612         clobber_region(FUNCTION_MACRO, __LINE__, cli->inbuf+cli->bufsize, SAFETY_MARGIN);
613 #endif
614
615         /* initialise signing */
616         cli->signing_state = smb_signing_init(cli,
617                                               allow_smb_signing,
618                                               mandatory_signing);
619         if (!cli->signing_state) {
620                 goto error;
621         }
622
623         cli->outgoing = tevent_queue_create(cli, "cli_outgoing");
624         if (cli->outgoing == NULL) {
625                 goto error;
626         }
627         cli->pending = NULL;
628
629         cli->initialised = 1;
630
631         return cli;
632
633         /* Clean up after malloc() error */
634
635  error:
636
637         SAFE_FREE(cli->inbuf);
638         SAFE_FREE(cli->outbuf);
639         TALLOC_FREE(cli);
640         return NULL;
641 }
642
643 struct cli_state *cli_initialise(void)
644 {
645         return cli_initialise_ex(Undefined);
646 }
647
648 /****************************************************************************
649  Close all pipes open on this session.
650 ****************************************************************************/
651
652 void cli_nt_pipes_close(struct cli_state *cli)
653 {
654         while (cli->pipe_list != NULL) {
655                 /*
656                  * No TALLOC_FREE here!
657                  */
658                 talloc_free(cli->pipe_list);
659         }
660 }
661
662 /****************************************************************************
663  Shutdown a client structure.
664 ****************************************************************************/
665
666 static void _cli_shutdown(struct cli_state *cli)
667 {
668         cli_nt_pipes_close(cli);
669
670         /*
671          * tell our peer to free his resources.  Wihtout this, when an
672          * application attempts to do a graceful shutdown and calls
673          * smbc_free_context() to clean up all connections, some connections
674          * can remain active on the peer end, until some (long) timeout period
675          * later.  This tree disconnect forces the peer to clean up, since the
676          * connection will be going away.
677          *
678          * Also, do not do tree disconnect when cli->smb_rw_error is SMB_DO_NOT_DO_TDIS
679          * the only user for this so far is smbmount which passes opened connection
680          * down to kernel's smbfs module.
681          */
682         if ( (cli->cnum != (uint16)-1) && (cli->smb_rw_error != SMB_DO_NOT_DO_TDIS ) ) {
683                 cli_tdis(cli);
684         }
685         
686         SAFE_FREE(cli->outbuf);
687         SAFE_FREE(cli->inbuf);
688
689         data_blob_free(&cli->secblob);
690         data_blob_free(&cli->user_session_key);
691
692         if (cli->fd != -1) {
693                 close(cli->fd);
694         }
695         cli->fd = -1;
696         cli->smb_rw_error = SMB_READ_OK;
697
698         /*
699          * Need to free pending first, they remove themselves
700          */
701         while (cli->pending) {
702                 talloc_free(cli->pending[0]);
703         }
704         TALLOC_FREE(cli);
705 }
706
707 void cli_shutdown(struct cli_state *cli)
708 {
709         struct cli_state *cli_head;
710         if (cli == NULL) {
711                 return;
712         }
713         DLIST_HEAD(cli, cli_head);
714         if (cli_head == cli) {
715                 /*
716                  * head of a DFS list, shutdown all subsidiary DFS
717                  * connections.
718                  */
719                 struct cli_state *p, *next;
720
721                 for (p = cli_head->next; p; p = next) {
722                         next = p->next;
723                         DLIST_REMOVE(cli_head, p);
724                         _cli_shutdown(p);
725                 }
726         } else {
727                 DLIST_REMOVE(cli_head, cli);
728         }
729
730         _cli_shutdown(cli);
731 }
732
733 /****************************************************************************
734  Set socket options on a open connection.
735 ****************************************************************************/
736
737 void cli_sockopt(struct cli_state *cli, const char *options)
738 {
739         set_socket_options(cli->fd, options);
740 }
741
742 /****************************************************************************
743  Set the PID to use for smb messages. Return the old pid.
744 ****************************************************************************/
745
746 uint16 cli_setpid(struct cli_state *cli, uint16 pid)
747 {
748         uint16 ret = cli->pid;
749         cli->pid = pid;
750         return ret;
751 }
752
753 /****************************************************************************
754  Set the case sensitivity flag on the packets. Returns old state.
755 ****************************************************************************/
756
757 bool cli_set_case_sensitive(struct cli_state *cli, bool case_sensitive)
758 {
759         bool ret = cli->case_sensitive;
760         cli->case_sensitive = case_sensitive;
761         return ret;
762 }
763
764 /****************************************************************************
765 Send a keepalive packet to the server
766 ****************************************************************************/
767
768 bool cli_send_keepalive(struct cli_state *cli)
769 {
770         if (cli->fd == -1) {
771                 DEBUG(3, ("cli_send_keepalive: fd == -1\n"));
772                 return false;
773         }
774         if (!send_keepalive(cli->fd)) {
775                 close(cli->fd);
776                 cli->fd = -1;
777                 DEBUG(0,("Error sending keepalive packet to client.\n"));
778                 return false;
779         }
780         return true;
781 }
782
783 struct cli_echo_state {
784         uint16_t vwv[1];
785         DATA_BLOB data;
786         int num_echos;
787 };
788
789 static void cli_echo_done(struct tevent_req *subreq);
790
791 struct tevent_req *cli_echo_send(TALLOC_CTX *mem_ctx, struct event_context *ev,
792                                  struct cli_state *cli, uint16_t num_echos,
793                                  DATA_BLOB data)
794 {
795         struct tevent_req *req, *subreq;
796         struct cli_echo_state *state;
797
798         req = tevent_req_create(mem_ctx, &state, struct cli_echo_state);
799         if (req == NULL) {
800                 return NULL;
801         }
802         SSVAL(state->vwv, 0, num_echos);
803         state->data = data;
804         state->num_echos = num_echos;
805
806         subreq = cli_smb_send(state, ev, cli, SMBecho, 0, 1, state->vwv,
807                               data.length, data.data);
808         if (subreq == NULL) {
809                 goto fail;
810         }
811         tevent_req_set_callback(subreq, cli_echo_done, req);
812         return req;
813  fail:
814         TALLOC_FREE(req);
815         return NULL;
816 }
817
818 static void cli_echo_done(struct tevent_req *subreq)
819 {
820         struct tevent_req *req = tevent_req_callback_data(
821                 subreq, struct tevent_req);
822         struct cli_echo_state *state = tevent_req_data(
823                 req, struct cli_echo_state);
824         NTSTATUS status;
825         uint32_t num_bytes;
826         uint8_t *bytes;
827         uint8_t *inbuf;
828
829         status = cli_smb_recv(subreq, state, &inbuf, 0, NULL, NULL,
830                               &num_bytes, &bytes);
831         if (!NT_STATUS_IS_OK(status)) {
832                 tevent_req_nterror(req, status);
833                 return;
834         }
835         if ((num_bytes != state->data.length)
836             || (memcmp(bytes, state->data.data, num_bytes) != 0)) {
837                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
838                 return;
839         }
840
841         state->num_echos -=1;
842         if (state->num_echos == 0) {
843                 tevent_req_done(req);
844                 return;
845         }
846
847         if (!cli_smb_req_set_pending(subreq)) {
848                 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
849                 return;
850         }
851 }
852
853 /**
854  * Get the result out from an echo request
855  * @param[in] req       The async_req from cli_echo_send
856  * @retval Did the server reply correctly?
857  */
858
859 NTSTATUS cli_echo_recv(struct tevent_req *req)
860 {
861         return tevent_req_simple_recv_ntstatus(req);
862 }
863
864 /**
865  * @brief Send/Receive SMBEcho requests
866  * @param[in] mem_ctx   The memory context to put the async_req on
867  * @param[in] ev        The event context that will call us back
868  * @param[in] cli       The connection to send the echo to
869  * @param[in] num_echos How many times do we want to get the reply?
870  * @param[in] data      The data we want to get back
871  * @retval Did the server reply correctly?
872  */
873
874 NTSTATUS cli_echo(struct cli_state *cli, uint16_t num_echos, DATA_BLOB data)
875 {
876         TALLOC_CTX *frame = talloc_stackframe();
877         struct event_context *ev;
878         struct tevent_req *req;
879         NTSTATUS status = NT_STATUS_OK;
880
881         if (cli_has_async_calls(cli)) {
882                 /*
883                  * Can't use sync call while an async call is in flight
884                  */
885                 status = NT_STATUS_INVALID_PARAMETER;
886                 goto fail;
887         }
888
889         ev = event_context_init(frame);
890         if (ev == NULL) {
891                 status = NT_STATUS_NO_MEMORY;
892                 goto fail;
893         }
894
895         req = cli_echo_send(frame, ev, cli, num_echos, data);
896         if (req == NULL) {
897                 status = NT_STATUS_NO_MEMORY;
898                 goto fail;
899         }
900
901         if (!tevent_req_poll(req, ev)) {
902                 status = map_nt_error_from_unix(errno);
903                 goto fail;
904         }
905
906         status = cli_echo_recv(req);
907  fail:
908         TALLOC_FREE(frame);
909         if (!NT_STATUS_IS_OK(status)) {
910                 cli_set_error(cli, status);
911         }
912         return status;
913 }
914
915 /**
916  * Is the SMB command able to hold an AND_X successor
917  * @param[in] cmd       The SMB command in question
918  * @retval Can we add a chained request after "cmd"?
919  */
920 bool is_andx_req(uint8_t cmd)
921 {
922         switch (cmd) {
923         case SMBtconX:
924         case SMBlockingX:
925         case SMBopenX:
926         case SMBreadX:
927         case SMBwriteX:
928         case SMBsesssetupX:
929         case SMBulogoffX:
930         case SMBntcreateX:
931                 return true;
932                 break;
933         default:
934                 break;
935         }
936
937         return false;
938 }
939
940 NTSTATUS cli_smb(TALLOC_CTX *mem_ctx, struct cli_state *cli,
941                  uint8_t smb_command, uint8_t additional_flags,
942                  uint8_t wct, uint16_t *vwv,
943                  uint32_t num_bytes, const uint8_t *bytes,
944                  struct tevent_req **result_parent,
945                  uint8_t min_wct, uint8_t *pwct, uint16_t **pvwv,
946                  uint32_t *pnum_bytes, uint8_t **pbytes)
947 {
948         struct tevent_context *ev;
949         struct tevent_req *req = NULL;
950         NTSTATUS status = NT_STATUS_NO_MEMORY;
951
952         if (cli_has_async_calls(cli)) {
953                 return NT_STATUS_INVALID_PARAMETER;
954         }
955         ev = tevent_context_init(mem_ctx);
956         if (ev == NULL) {
957                 goto fail;
958         }
959         req = cli_smb_send(mem_ctx, ev, cli, smb_command, additional_flags,
960                            wct, vwv, num_bytes, bytes);
961         if (req == NULL) {
962                 goto fail;
963         }
964         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
965                 goto fail;
966         }
967         status = cli_smb_recv(req, NULL, NULL, min_wct, pwct, pvwv,
968                               pnum_bytes, pbytes);
969 fail:
970         TALLOC_FREE(ev);
971         if (NT_STATUS_IS_OK(status)) {
972                 *result_parent = req;
973         }
974         return status;
975 }