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