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