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