r21993: Don't let keepalives interferece with sign or seal
[samba.git] / source / libsmb / clientgen.c
1 /* 
2    Unix SMB/CIFS implementation.
3    SMB client generic functions
4    Copyright (C) Andrew Tridgell 1994-1998
5    
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include "includes.h"
22
23 extern int smb_read_error;
24
25 /****************************************************************************
26  Change the timeout (in milliseconds).
27 ****************************************************************************/
28
29 unsigned int cli_set_timeout(struct cli_state *cli, unsigned int timeout)
30 {
31         unsigned int old_timeout = cli->timeout;
32         cli->timeout = timeout;
33         return old_timeout;
34 }
35
36 /****************************************************************************
37  Change the port number used to call on.
38 ****************************************************************************/
39
40 int cli_set_port(struct cli_state *cli, int port)
41 {
42         cli->port = port;
43         return port;
44 }
45
46 /****************************************************************************
47  Read an smb from a fd ignoring all keepalive packets. Note that the buffer 
48  *MUST* be of size BUFFER_SIZE+SAFETY_MARGIN.
49  The timeout is in milliseconds
50
51  This is exactly the same as receive_smb except that it can be set to never return
52  a session keepalive packet (just as receive_smb used to do).
53  receive_smb was changed to return keepalives as the oplock processing means this call
54  should never go into a blocking read.
55 ****************************************************************************/
56
57 static BOOL client_receive_smb(struct cli_state *cli, BOOL eat_keepalives)
58 {
59         BOOL ret;
60         int fd = cli->fd;
61         char *buffer = cli->inbuf;
62         unsigned int timeout = cli->timeout;
63
64         for(;;) {
65                 ret = receive_smb_raw(fd, buffer, timeout);
66
67                 if (!ret) {
68                         DEBUG(10,("client_receive_smb failed\n"));
69                         show_msg(buffer);
70                         return ret;
71                 }
72
73                 /* Ignore session keepalive packets. */
74                 if (eat_keepalives && (CVAL(buffer,0) == SMBkeepalive)) {
75                         continue;
76                 }
77                 break;
78         }
79
80         if (cli_encryption_on(cli)) {
81                 NTSTATUS status = cli_decrypt_message(cli);
82                 if (!NT_STATUS_IS_OK(status)) {
83                         DEBUG(0, ("SMB decryption failed on incoming packet! Error %s\n",
84                                 nt_errstr(status)));
85                         cli->smb_rw_error = READ_BAD_DECRYPT;
86                         close(cli->fd);
87                         cli->fd = -1;
88                         return False;
89                 }
90         }
91         show_msg(buffer);
92         return ret;
93 }
94
95 /****************************************************************************
96  Recv an smb.
97 ****************************************************************************/
98
99 BOOL cli_receive_smb_internal(struct cli_state *cli, BOOL eat_keepalives)
100 {
101         BOOL ret;
102
103         /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
104         if (cli->fd == -1)
105                 return False; 
106
107  again:
108         ret = client_receive_smb(cli, eat_keepalives);
109
110         if (!eat_keepalives && (CVAL(cli->inbuf,0) == SMBkeepalive)) {
111                 /* Give back the keepalive. */
112                 return True;
113         }
114         
115         if (ret) {
116                 /* it might be an oplock break request */
117                 if (!(CVAL(cli->inbuf, smb_flg) & FLAG_REPLY) &&
118                     CVAL(cli->inbuf,smb_com) == SMBlockingX &&
119                     SVAL(cli->inbuf,smb_vwv6) == 0 &&
120                     SVAL(cli->inbuf,smb_vwv7) == 0) {
121                         if (cli->oplock_handler) {
122                                 int fnum = SVAL(cli->inbuf,smb_vwv2);
123                                 unsigned char level = CVAL(cli->inbuf,smb_vwv3+1);
124                                 if (!cli->oplock_handler(cli, fnum, level)) return False;
125                         }
126                         /* try to prevent loops */
127                         SCVAL(cli->inbuf,smb_com,0xFF);
128                         goto again;
129                 }
130         }
131
132         /* If the server is not responding, note that now */
133         if (!ret) {
134                 DEBUG(0, ("Receiving SMB: Server stopped responding\n"));
135                 cli->smb_rw_error = smb_read_error;
136                 close(cli->fd);
137                 cli->fd = -1;
138                 return ret;
139         }
140
141         if (!cli_check_sign_mac(cli)) {
142                 DEBUG(0, ("SMB Signature verification failed on incoming packet!\n"));
143                 cli->smb_rw_error = READ_BAD_SIG;
144                 close(cli->fd);
145                 cli->fd = -1;
146                 return False;
147         }
148
149         return True;
150 }
151
152 /****************************************************************************
153  Recv an smb - eat keepalives.
154 ****************************************************************************/
155
156 BOOL cli_receive_smb(struct cli_state *cli)
157 {
158         return cli_receive_smb_internal(cli, True);
159 }
160
161 /****************************************************************************
162  Recv an smb - return keepalives.
163 ****************************************************************************/
164
165 BOOL cli_receive_smb_return_keepalive(struct cli_state *cli)
166 {
167         return cli_receive_smb_internal(cli, False);
168 }
169
170 static ssize_t write_socket(int fd, const char *buf, size_t len)
171 {
172         ssize_t ret=0;
173                                                                                                                                             
174         DEBUG(6,("write_socket(%d,%d)\n",fd,(int)len));
175         ret = write_data(fd,buf,len);
176
177         DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,(int)len,(int)ret));
178         if(ret <= 0)
179                 DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n",
180                         (int)len, fd, strerror(errno) ));
181                                                                                                                                             
182         return(ret);
183 }
184
185 /****************************************************************************
186  Send an smb to a fd.
187 ****************************************************************************/
188
189 BOOL cli_send_smb(struct cli_state *cli)
190 {
191         size_t len;
192         size_t nwritten=0;
193         ssize_t ret;
194         char *buf_out = cli->outbuf;
195         BOOL enc_on = cli_encryption_on(cli);
196
197         /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
198         if (cli->fd == -1) {
199                 return False;
200         }
201
202         cli_calculate_sign_mac(cli);
203
204         if (enc_on) {
205                 NTSTATUS status = cli_encrypt_message(cli, &buf_out);
206                 if (!NT_STATUS_IS_OK(status)) {
207                         close(cli->fd);
208                         cli->fd = -1;
209                         cli->smb_rw_error = WRITE_ERROR;
210                         DEBUG(0,("Error in encrypting client message. Error %s\n",
211                                 nt_errstr(status) ));
212                         return False;
213                 }
214         }
215
216         len = smb_len(buf_out) + 4;
217
218         while (nwritten < len) {
219                 ret = write_socket(cli->fd,buf_out+nwritten,len - nwritten);
220                 if (ret <= 0) {
221                         if (enc_on) {
222                                 cli_free_enc_buffer(cli, buf_out);
223                         }
224                         close(cli->fd);
225                         cli->fd = -1;
226                         cli->smb_rw_error = WRITE_ERROR;
227                         DEBUG(0,("Error writing %d bytes to client. %d (%s)\n",
228                                 (int)len,(int)ret, strerror(errno) ));
229                         return False;
230                 }
231                 nwritten += ret;
232         }
233
234         cli_free_enc_buffer(cli, buf_out);
235
236         /* Increment the mid so we can tell between responses. */
237         cli->mid++;
238         if (!cli->mid) {
239                 cli->mid++;
240         }
241         return True;
242 }
243
244 /****************************************************************************
245  Setup basics in a outgoing packet.
246 ****************************************************************************/
247
248 void cli_setup_packet(struct cli_state *cli)
249 {
250         cli->rap_error = 0;
251         SSVAL(cli->outbuf,smb_pid,cli->pid);
252         SSVAL(cli->outbuf,smb_uid,cli->vuid);
253         SSVAL(cli->outbuf,smb_mid,cli->mid);
254         if (cli->protocol > PROTOCOL_CORE) {
255                 uint16 flags2;
256                 if (cli->case_sensitive) {
257                         SCVAL(cli->outbuf,smb_flg,0x0);
258                 } else {
259                         /* Default setting, case insensitive. */
260                         SCVAL(cli->outbuf,smb_flg,0x8);
261                 }
262                 flags2 = FLAGS2_LONG_PATH_COMPONENTS;
263                 if (cli->capabilities & CAP_UNICODE)
264                         flags2 |= FLAGS2_UNICODE_STRINGS;
265                 if ((cli->capabilities & CAP_DFS) && cli->dfsroot)
266                         flags2 |= FLAGS2_DFS_PATHNAMES;
267                 if (cli->capabilities & CAP_STATUS32)
268                         flags2 |= FLAGS2_32_BIT_ERROR_CODES;
269                 if (cli->use_spnego)
270                         flags2 |= FLAGS2_EXTENDED_SECURITY;
271                 SSVAL(cli->outbuf,smb_flg2, flags2);
272         }
273 }
274
275 /****************************************************************************
276  Setup the bcc length of the packet from a pointer to the end of the data.
277 ****************************************************************************/
278
279 void cli_setup_bcc(struct cli_state *cli, void *p)
280 {
281         set_message_bcc(cli->outbuf, PTR_DIFF(p, smb_buf(cli->outbuf)));
282 }
283
284 /****************************************************************************
285  Initialise credentials of a client structure.
286 ****************************************************************************/
287
288 void cli_init_creds(struct cli_state *cli, const char *username, const char *domain, const char *password)
289 {
290         fstrcpy(cli->domain, domain);
291         fstrcpy(cli->user_name, username);
292         pwd_set_cleartext(&cli->pwd, password);
293         if (!*username) {
294                 cli->pwd.null_pwd = True;
295         }
296
297         DEBUG(10,("cli_init_creds: user %s domain %s\n", cli->user_name, cli->domain));
298 }
299
300 /****************************************************************************
301  Set the signing state (used from the command line).
302 ****************************************************************************/
303
304 void cli_setup_signing_state(struct cli_state *cli, int signing_state)
305 {
306         if (signing_state == Undefined)
307                 return;
308
309         if (signing_state == False) {
310                 cli->sign_info.allow_smb_signing = False;
311                 cli->sign_info.mandatory_signing = False;
312                 return;
313         }
314
315         cli->sign_info.allow_smb_signing = True;
316
317         if (signing_state == Required) 
318                 cli->sign_info.mandatory_signing = True;
319 }
320
321 /****************************************************************************
322  Initialise a client structure. Always returns a malloc'ed struct.
323 ****************************************************************************/
324
325 struct cli_state *cli_initialise(void)
326 {
327         struct cli_state *cli = NULL;
328
329         /* Check the effective uid - make sure we are not setuid */
330         if (is_setuid_root()) {
331                 DEBUG(0,("libsmb based programs must *NOT* be setuid root.\n"));
332                 return NULL;
333         }
334
335         cli = SMB_MALLOC_P(struct cli_state);
336         if (!cli) {
337                 return NULL;
338         }
339
340         ZERO_STRUCTP(cli);
341
342         cli->port = 0;
343         cli->fd = -1;
344         cli->cnum = -1;
345         cli->pid = (uint16)sys_getpid();
346         cli->mid = 1;
347         cli->vuid = UID_FIELD_INVALID;
348         cli->protocol = PROTOCOL_NT1;
349         cli->timeout = 20000; /* Timeout is in milliseconds. */
350         cli->bufsize = CLI_BUFFER_SIZE+4;
351         cli->max_xmit = cli->bufsize;
352         cli->outbuf = (char *)SMB_MALLOC(cli->bufsize+SAFETY_MARGIN);
353         cli->inbuf = (char *)SMB_MALLOC(cli->bufsize+SAFETY_MARGIN);
354         cli->oplock_handler = cli_oplock_ack;
355         cli->case_sensitive = False;
356         cli->smb_rw_error = 0;
357
358         cli->use_spnego = lp_client_use_spnego();
359
360         cli->capabilities = CAP_UNICODE | CAP_STATUS32 | CAP_DFS;
361
362         /* Set the CLI_FORCE_DOSERR environment variable to test
363            client routines using DOS errors instead of STATUS32
364            ones.  This intended only as a temporary hack. */    
365         if (getenv("CLI_FORCE_DOSERR"))
366                 cli->force_dos_errors = True;
367
368         if (lp_client_signing()) 
369                 cli->sign_info.allow_smb_signing = True;
370
371         if (lp_client_signing() == Required) 
372                 cli->sign_info.mandatory_signing = True;
373                                    
374         if (!cli->outbuf || !cli->inbuf)
375                 goto error;
376
377         if ((cli->mem_ctx = talloc_init("cli based talloc")) == NULL)
378                 goto error;
379
380         memset(cli->outbuf, 0, cli->bufsize);
381         memset(cli->inbuf, 0, cli->bufsize);
382
383
384 #if defined(DEVELOPER)
385         /* just because we over-allocate, doesn't mean it's right to use it */
386         clobber_region(FUNCTION_MACRO, __LINE__, cli->outbuf+cli->bufsize, SAFETY_MARGIN);
387         clobber_region(FUNCTION_MACRO, __LINE__, cli->inbuf+cli->bufsize, SAFETY_MARGIN);
388 #endif
389
390         /* initialise signing */
391         cli_null_set_signing(cli);
392
393         cli->initialised = 1;
394
395         return cli;
396
397         /* Clean up after malloc() error */
398
399  error:
400
401         SAFE_FREE(cli->inbuf);
402         SAFE_FREE(cli->outbuf);
403         SAFE_FREE(cli);
404         return NULL;
405 }
406
407 /****************************************************************************
408  External interface.
409  Close an open named pipe over SMB. Free any authentication data.
410  Returns False if the cli_close call failed.
411  ****************************************************************************/
412
413 BOOL cli_rpc_pipe_close(struct rpc_pipe_client *cli)
414 {
415         BOOL ret;
416
417         if (!cli) {
418                 return False;
419         }
420
421         ret = cli_close(cli->cli, cli->fnum);
422
423         if (!ret) {
424                 DEBUG(1,("cli_rpc_pipe_close: cli_close failed on pipe %s, "
425                          "fnum 0x%x "
426                          "to machine %s.  Error was %s\n",
427                          cli->pipe_name,
428                          (int) cli->fnum,
429                          cli->cli->desthost,
430                          cli_errstr(cli->cli)));
431         }
432
433         if (cli->auth.cli_auth_data_free_func) {
434                 (*cli->auth.cli_auth_data_free_func)(&cli->auth);
435         }
436
437         DEBUG(10,("cli_rpc_pipe_close: closed pipe %s to machine %s\n",
438                 cli->pipe_name, cli->cli->desthost ));
439
440         DLIST_REMOVE(cli->cli->pipe_list, cli);
441         talloc_destroy(cli->mem_ctx);
442         return ret;
443 }
444
445 /****************************************************************************
446  Close all pipes open on this session.
447 ****************************************************************************/
448
449 void cli_nt_pipes_close(struct cli_state *cli)
450 {
451         struct rpc_pipe_client *cp, *next;
452
453         for (cp = cli->pipe_list; cp; cp = next) {
454                 next = cp->next;
455                 cli_rpc_pipe_close(cp);
456         }
457 }
458
459 /****************************************************************************
460  Shutdown a client structure.
461 ****************************************************************************/
462
463 void cli_shutdown(struct cli_state *cli)
464 {
465         cli_nt_pipes_close(cli);
466
467         /*
468          * tell our peer to free his resources.  Wihtout this, when an
469          * application attempts to do a graceful shutdown and calls
470          * smbc_free_context() to clean up all connections, some connections
471          * can remain active on the peer end, until some (long) timeout period
472          * later.  This tree disconnect forces the peer to clean up, since the
473          * connection will be going away.
474          *
475          * Also, do not do tree disconnect when cli->smb_rw_error is DO_NOT_DO_TDIS
476          * the only user for this so far is smbmount which passes opened connection
477          * down to kernel's smbfs module.
478          */
479         if ( (cli->cnum != (uint16)-1) && (cli->smb_rw_error != DO_NOT_DO_TDIS ) ) {
480                 cli_tdis(cli);
481         }
482         
483         SAFE_FREE(cli->outbuf);
484         SAFE_FREE(cli->inbuf);
485
486         cli_free_signing_context(cli);
487         cli_free_encryption_context(cli);
488
489         data_blob_free(&cli->secblob);
490         data_blob_free(&cli->user_session_key);
491
492         if (cli->mem_ctx) {
493                 talloc_destroy(cli->mem_ctx);
494                 cli->mem_ctx = NULL;
495         }
496
497         if (cli->fd != -1) {
498                 close(cli->fd);
499         }
500         cli->fd = -1;
501         cli->smb_rw_error = 0;
502
503         SAFE_FREE(cli);
504 }
505
506 /****************************************************************************
507  Set socket options on a open connection.
508 ****************************************************************************/
509
510 void cli_sockopt(struct cli_state *cli, const char *options)
511 {
512         set_socket_options(cli->fd, options);
513 }
514
515 /****************************************************************************
516  Set the PID to use for smb messages. Return the old pid.
517 ****************************************************************************/
518
519 uint16 cli_setpid(struct cli_state *cli, uint16 pid)
520 {
521         uint16 ret = cli->pid;
522         cli->pid = pid;
523         return ret;
524 }
525
526 /****************************************************************************
527  Set the case sensitivity flag on the packets. Returns old state.
528 ****************************************************************************/
529
530 BOOL cli_set_case_sensitive(struct cli_state *cli, BOOL case_sensitive)
531 {
532         BOOL ret = cli->case_sensitive;
533         cli->case_sensitive = case_sensitive;
534         return ret;
535 }
536
537 /****************************************************************************
538 Send a keepalive packet to the server
539 ****************************************************************************/
540
541 BOOL cli_send_keepalive(struct cli_state *cli)
542 {
543         if (cli->fd == -1) {
544                 DEBUG(3, ("cli_send_keepalive: fd == -1\n"));
545                 return False;
546         }
547         if (!send_keepalive(cli->fd)) {
548                 close(cli->fd);
549                 cli->fd = -1;
550                 DEBUG(0,("Error sending keepalive packet to client.\n"));
551                 return False;
552         }
553         return True;
554 }
555
556 /****************************************************************************
557  Send/receive a SMBecho command: ping the server
558 ****************************************************************************/
559
560 BOOL cli_echo(struct cli_state *cli, unsigned char *data, size_t length)
561 {
562         char *p;
563
564         SMB_ASSERT(length < 1024);
565
566         memset(cli->outbuf,'\0',smb_size);
567         set_message(cli->outbuf,1,length,True);
568         SCVAL(cli->outbuf,smb_com,SMBecho);
569         SSVAL(cli->outbuf,smb_tid,65535);
570         SSVAL(cli->outbuf,smb_vwv0,1);
571         cli_setup_packet(cli);
572         p = smb_buf(cli->outbuf);
573         memcpy(p, data, length);
574         p += length;
575
576         cli_setup_bcc(cli, p);
577
578         cli_send_smb(cli);
579         if (!cli_receive_smb(cli)) {
580                 return False;
581         }
582
583         if (cli_is_error(cli)) {
584                 return False;
585         }
586         return True;
587 }