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