Merge branch 'v3-2-test' of git://git.samba.org/samba into v3-2-test
[metze/samba/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    Copyright (C) Jeremy Allison 2007.
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
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 ssize_t client_receive_smb(struct cli_state *cli, size_t maxlen)
56 {
57         ssize_t len;
58
59         for(;;) {
60                 len = receive_smb_raw(cli->fd, cli->inbuf, cli->timeout,
61                                 maxlen, &cli->smb_rw_error);
62
63                 if (len < 0) {
64                         DEBUG(10,("client_receive_smb failed\n"));
65                         show_msg(cli->inbuf);
66                         return len;
67                 }
68
69                 /* Ignore session keepalive packets. */
70                 if(CVAL(cli->inbuf,0) != SMBkeepalive) {
71                         break;
72                 }
73         }
74         show_msg(cli->inbuf);
75         return len;
76 }
77
78 /****************************************************************************
79  Recv an smb.
80 ****************************************************************************/
81
82 bool cli_receive_smb(struct cli_state *cli)
83 {
84         ssize_t len;
85
86         /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
87         if (cli->fd == -1)
88                 return False; 
89
90  again:
91         len = client_receive_smb(cli, 0);
92         
93         if (len > 0) {
94                 /* it might be an oplock break request */
95                 if (!(CVAL(cli->inbuf, smb_flg) & FLAG_REPLY) &&
96                     CVAL(cli->inbuf,smb_com) == SMBlockingX &&
97                     SVAL(cli->inbuf,smb_vwv6) == 0 &&
98                     SVAL(cli->inbuf,smb_vwv7) == 0) {
99                         if (cli->oplock_handler) {
100                                 int fnum = SVAL(cli->inbuf,smb_vwv2);
101                                 unsigned char level = CVAL(cli->inbuf,smb_vwv3+1);
102                                 if (!cli->oplock_handler(cli, fnum, level)) {
103                                         return False;
104                                 }
105                         }
106                         /* try to prevent loops */
107                         SCVAL(cli->inbuf,smb_com,0xFF);
108                         goto again;
109                 }
110         }
111
112         /* If the server is not responding, note that now */
113         if (len < 0) {
114                 DEBUG(0, ("Receiving SMB: Server stopped responding\n"));
115                 close(cli->fd);
116                 cli->fd = -1;
117                 return False;
118         }
119
120         if (!cli_check_sign_mac(cli)) {
121                 /*
122                  * If we get a signature failure in sessionsetup, then
123                  * the server sometimes just reflects the sent signature
124                  * back to us. Detect this and allow the upper layer to
125                  * retrieve the correct Windows error message.
126                  */
127                 if (CVAL(cli->outbuf,smb_com) == SMBsesssetupX &&
128                         (smb_len(cli->inbuf) > (smb_ss_field + 8 - 4)) &&
129                         (SVAL(cli->inbuf,smb_flg2) & FLAGS2_SMB_SECURITY_SIGNATURES) &&
130                         memcmp(&cli->outbuf[smb_ss_field],&cli->inbuf[smb_ss_field],8) == 0 &&
131                         cli_is_error(cli)) {
132
133                         /*
134                          * Reflected signature on login error. 
135                          * Set bad sig but don't close fd.
136                          */
137                         cli->smb_rw_error = SMB_READ_BAD_SIG;
138                         return True;
139                 }
140
141                 DEBUG(0, ("SMB Signature verification failed on incoming packet!\n"));
142                 cli->smb_rw_error = SMB_READ_BAD_SIG;
143                 close(cli->fd);
144                 cli->fd = -1;
145                 return False;
146         };
147         return True;
148 }
149
150 /****************************************************************************
151  Read the data portion of a readX smb.
152  The timeout is in milliseconds
153 ****************************************************************************/
154
155 ssize_t cli_receive_smb_data(struct cli_state *cli, char *buffer, size_t len)
156 {
157         if (cli->timeout > 0) {
158                 return read_socket_with_timeout(cli->fd, buffer, len,
159                                                 len, cli->timeout, &cli->smb_rw_error);
160         } else {
161                 return read_data(cli->fd, buffer, len, &cli->smb_rw_error);
162         }
163 }
164
165 /****************************************************************************
166  Read a smb readX header.
167 ****************************************************************************/
168
169 bool cli_receive_smb_readX_header(struct cli_state *cli)
170 {
171         ssize_t len, offset;
172
173         if (cli->fd == -1)
174                 return False; 
175
176  again:
177
178         /* Read up to the size of a readX header reply. */
179         len = client_receive_smb(cli, (smb_size - 4) + 24);
180         
181         if (len > 0) {
182                 /* it might be an oplock break request */
183                 if (!(CVAL(cli->inbuf, smb_flg) & FLAG_REPLY) &&
184                     CVAL(cli->inbuf,smb_com) == SMBlockingX &&
185                     SVAL(cli->inbuf,smb_vwv6) == 0 &&
186                     SVAL(cli->inbuf,smb_vwv7) == 0) {
187                         ssize_t total_len = smb_len(cli->inbuf);
188
189                         if (total_len > CLI_SAMBA_MAX_LARGE_READX_SIZE+SAFETY_MARGIN) {
190                                 goto read_err;
191                         }
192
193                         /* Read the rest of the data. */
194                         if ((total_len - len > 0) &&
195                             !cli_receive_smb_data(cli,cli->inbuf+len,total_len - len)) {
196                                 goto read_err;
197                         }
198
199                         if (cli->oplock_handler) {
200                                 int fnum = SVAL(cli->inbuf,smb_vwv2);
201                                 unsigned char level = CVAL(cli->inbuf,smb_vwv3+1);
202                                 if (!cli->oplock_handler(cli, fnum, level)) return False;
203                         }
204                         /* try to prevent loops */
205                         SCVAL(cli->inbuf,smb_com,0xFF);
206                         goto again;
207                 }
208         }
209
210         /* If it's not the above size it probably was an error packet. */
211
212         if ((len == (smb_size - 4) + 24) && !cli_is_error(cli)) {
213                 /* Check it's a non-chained readX reply. */
214                 if (!(CVAL(cli->inbuf, smb_flg) & FLAG_REPLY) ||
215                         (CVAL(cli->inbuf,smb_vwv0) != 0xFF) ||
216                         (CVAL(cli->inbuf,smb_com) != SMBreadX)) {
217                         /* 
218                          * We're not coping here with asnyc replies to
219                          * other calls. Punt here - we need async client
220                          * libs for this.
221                          */
222                         goto read_err;
223                 }
224
225                 /* 
226                  * We know it's a readX reply - ensure we've read the
227                  * padding bytes also.
228                  */
229
230                 offset = SVAL(cli->inbuf,smb_vwv6);
231                 if (offset > len) {
232                         ssize_t ret;
233                         size_t padbytes = offset - len;
234                         ret = cli_receive_smb_data(cli,smb_buf(cli->inbuf),padbytes);
235                         if (ret != padbytes) {
236                                 goto read_err;
237                         }
238                 }
239         }
240
241         return True;
242
243   read_err:
244
245         cli->smb_rw_error = SMB_READ_ERROR;
246         close(cli->fd);
247         cli->fd = -1;
248         return False;
249 }
250
251 static ssize_t write_socket(int fd, const char *buf, size_t len)
252 {
253         ssize_t ret=0;
254
255         DEBUG(6,("write_socket(%d,%d)\n",fd,(int)len));
256         ret = write_data(fd,buf,len);
257
258         DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,(int)len,(int)ret));
259         if(ret <= 0)
260                 DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n",
261                         (int)len, fd, strerror(errno) ));
262
263         return(ret);
264 }
265
266 /****************************************************************************
267  Send an smb to a fd.
268 ****************************************************************************/
269
270 bool cli_send_smb(struct cli_state *cli)
271 {
272         size_t len;
273         size_t nwritten=0;
274         ssize_t ret;
275
276         /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
277         if (cli->fd == -1)
278                 return False;
279
280         cli_calculate_sign_mac(cli);
281
282         len = smb_len(cli->outbuf) + 4;
283
284         while (nwritten < len) {
285                 ret = write_socket(cli->fd,cli->outbuf+nwritten,len - nwritten);
286                 if (ret <= 0) {
287                         close(cli->fd);
288                         cli->fd = -1;
289                         cli->smb_rw_error = SMB_WRITE_ERROR;
290                         DEBUG(0,("Error writing %d bytes to client. %d (%s)\n",
291                                 (int)len,(int)ret, strerror(errno) ));
292                         return False;
293                 }
294                 nwritten += ret;
295         }
296         /* Increment the mid so we can tell between responses. */
297         cli->mid++;
298         if (!cli->mid)
299                 cli->mid++;
300         return True;
301 }
302
303 /****************************************************************************
304  Send a "direct" writeX smb to a fd.
305 ****************************************************************************/
306
307 bool cli_send_smb_direct_writeX(struct cli_state *cli,
308                                 const char *p,
309                                 size_t extradata)
310 {
311         /* First length to send is the offset to the data. */
312         size_t len = SVAL(cli->outbuf,smb_vwv11) + 4;
313         size_t nwritten=0;
314         ssize_t ret;
315
316         /* fd == -1 causes segfaults -- Tom (tom@ninja.nl) */
317         if (cli->fd == -1) {
318                 return false;
319         }
320
321         if (client_is_signing_on(cli)) {
322                 DEBUG(0,("cli_send_smb_large: cannot send signed packet.\n"));
323                 return false;
324         }
325
326         while (nwritten < len) {
327                 ret = write_socket(cli->fd,cli->outbuf+nwritten,len - nwritten);
328                 if (ret <= 0) {
329                         close(cli->fd);
330                         cli->fd = -1;
331                         cli->smb_rw_error = SMB_WRITE_ERROR;
332                         DEBUG(0,("Error writing %d bytes to client. %d (%s)\n",
333                                 (int)len,(int)ret, strerror(errno) ));
334                         return false;
335                 }
336                 nwritten += ret;
337         }
338
339         /* Now write the extra data. */
340         nwritten=0;
341         while (nwritten < extradata) {
342                 ret = write_socket(cli->fd,p+nwritten,extradata - nwritten);
343                 if (ret <= 0) {
344                         close(cli->fd);
345                         cli->fd = -1;
346                         cli->smb_rw_error = SMB_WRITE_ERROR;
347                         DEBUG(0,("Error writing %d extradata "
348                                 "bytes to client. %d (%s)\n",
349                                 (int)extradata,(int)ret, strerror(errno) ));
350                         return False;
351                 }
352                 nwritten += ret;
353         }
354
355         /* Increment the mid so we can tell between responses. */
356         cli->mid++;
357         if (!cli->mid)
358                 cli->mid++;
359         return true;
360 }
361
362 /****************************************************************************
363  Setup basics in a outgoing packet.
364 ****************************************************************************/
365
366 void cli_setup_packet(struct cli_state *cli)
367 {
368         cli->rap_error = 0;
369         SSVAL(cli->outbuf,smb_pid,cli->pid);
370         SSVAL(cli->outbuf,smb_uid,cli->vuid);
371         SSVAL(cli->outbuf,smb_mid,cli->mid);
372         if (cli->protocol > PROTOCOL_CORE) {
373                 uint16 flags2;
374                 if (cli->case_sensitive) {
375                         SCVAL(cli->outbuf,smb_flg,0x0);
376                 } else {
377                         /* Default setting, case insensitive. */
378                         SCVAL(cli->outbuf,smb_flg,0x8);
379                 }
380                 flags2 = FLAGS2_LONG_PATH_COMPONENTS;
381                 if (cli->capabilities & CAP_UNICODE)
382                         flags2 |= FLAGS2_UNICODE_STRINGS;
383                 if ((cli->capabilities & CAP_DFS) && cli->dfsroot)
384                         flags2 |= FLAGS2_DFS_PATHNAMES;
385                 if (cli->capabilities & CAP_STATUS32)
386                         flags2 |= FLAGS2_32_BIT_ERROR_CODES;
387                 if (cli->use_spnego)
388                         flags2 |= FLAGS2_EXTENDED_SECURITY;
389                 SSVAL(cli->outbuf,smb_flg2, flags2);
390         }
391 }
392
393 /****************************************************************************
394  Setup the bcc length of the packet from a pointer to the end of the data.
395 ****************************************************************************/
396
397 void cli_setup_bcc(struct cli_state *cli, void *p)
398 {
399         set_message_bcc(cli->outbuf, PTR_DIFF(p, smb_buf(cli->outbuf)));
400 }
401
402 /****************************************************************************
403  Initialise credentials of a client structure.
404 ****************************************************************************/
405
406 void cli_init_creds(struct cli_state *cli, const char *username, const char *domain, const char *password)
407 {
408         fstrcpy(cli->domain, domain);
409         fstrcpy(cli->user_name, username);
410         pwd_set_cleartext(&cli->pwd, password);
411         if (!*username) {
412                 cli->pwd.null_pwd = True;
413         }
414
415         DEBUG(10,("cli_init_creds: user %s domain %s\n", cli->user_name, cli->domain));
416 }
417
418 /****************************************************************************
419  Set the signing state (used from the command line).
420 ****************************************************************************/
421
422 void cli_setup_signing_state(struct cli_state *cli, int signing_state)
423 {
424         if (signing_state == Undefined)
425                 return;
426
427         if (signing_state == False) {
428                 cli->sign_info.allow_smb_signing = False;
429                 cli->sign_info.mandatory_signing = False;
430                 return;
431         }
432
433         cli->sign_info.allow_smb_signing = True;
434
435         if (signing_state == Required) 
436                 cli->sign_info.mandatory_signing = True;
437 }
438
439 /****************************************************************************
440  Initialise a client structure. Always returns a malloc'ed struct.
441 ****************************************************************************/
442
443 struct cli_state *cli_initialise(void)
444 {
445         struct cli_state *cli = NULL;
446
447         /* Check the effective uid - make sure we are not setuid */
448         if (is_setuid_root()) {
449                 DEBUG(0,("libsmb based programs must *NOT* be setuid root.\n"));
450                 return NULL;
451         }
452
453         cli = SMB_MALLOC_P(struct cli_state);
454         if (!cli) {
455                 return NULL;
456         }
457
458         ZERO_STRUCTP(cli);
459
460         cli->port = 0;
461         cli->fd = -1;
462         cli->cnum = -1;
463         cli->pid = (uint16)sys_getpid();
464         cli->mid = 1;
465         cli->vuid = UID_FIELD_INVALID;
466         cli->protocol = PROTOCOL_NT1;
467         cli->timeout = 20000; /* Timeout is in milliseconds. */
468         cli->bufsize = CLI_BUFFER_SIZE+4;
469         cli->max_xmit = cli->bufsize;
470         cli->outbuf = (char *)SMB_MALLOC(cli->bufsize+SAFETY_MARGIN);
471         cli->inbuf = (char *)SMB_MALLOC(cli->bufsize+SAFETY_MARGIN);
472         cli->oplock_handler = cli_oplock_ack;
473         cli->case_sensitive = False;
474         cli->smb_rw_error = SMB_READ_OK;
475
476         cli->use_spnego = lp_client_use_spnego();
477
478         cli->capabilities = CAP_UNICODE | CAP_STATUS32 | CAP_DFS;
479
480         /* Set the CLI_FORCE_DOSERR environment variable to test
481            client routines using DOS errors instead of STATUS32
482            ones.  This intended only as a temporary hack. */    
483         if (getenv("CLI_FORCE_DOSERR"))
484                 cli->force_dos_errors = True;
485
486         if (lp_client_signing()) 
487                 cli->sign_info.allow_smb_signing = True;
488
489         if (lp_client_signing() == Required) 
490                 cli->sign_info.mandatory_signing = True;
491                                    
492         if (!cli->outbuf || !cli->inbuf)
493                 goto error;
494
495         memset(cli->outbuf, 0, cli->bufsize);
496         memset(cli->inbuf, 0, cli->bufsize);
497
498
499 #if defined(DEVELOPER)
500         /* just because we over-allocate, doesn't mean it's right to use it */
501         clobber_region(FUNCTION_MACRO, __LINE__, cli->outbuf+cli->bufsize, SAFETY_MARGIN);
502         clobber_region(FUNCTION_MACRO, __LINE__, cli->inbuf+cli->bufsize, SAFETY_MARGIN);
503 #endif
504
505         /* initialise signing */
506         cli_null_set_signing(cli);
507
508         cli->initialised = 1;
509
510         return cli;
511
512         /* Clean up after malloc() error */
513
514  error:
515
516         SAFE_FREE(cli->inbuf);
517         SAFE_FREE(cli->outbuf);
518         SAFE_FREE(cli);
519         return NULL;
520 }
521
522 /****************************************************************************
523  External interface.
524  Close an open named pipe over SMB. Free any authentication data.
525  Returns False if the cli_close call failed.
526  ****************************************************************************/
527
528 bool cli_rpc_pipe_close(struct rpc_pipe_client *cli)
529 {
530         bool ret;
531
532         if (!cli) {
533                 return False;
534         }
535
536         ret = cli_close(cli->cli, cli->fnum);
537
538         if (!ret) {
539                 DEBUG(1,("cli_rpc_pipe_close: cli_close failed on pipe %s, "
540                          "fnum 0x%x "
541                          "to machine %s.  Error was %s\n",
542                          cli->pipe_name,
543                          (int) cli->fnum,
544                          cli->cli->desthost,
545                          cli_errstr(cli->cli)));
546         }
547
548         if (cli->auth.cli_auth_data_free_func) {
549                 (*cli->auth.cli_auth_data_free_func)(&cli->auth);
550         }
551
552         DEBUG(10,("cli_rpc_pipe_close: closed pipe %s to machine %s\n",
553                 cli->pipe_name, cli->cli->desthost ));
554
555         DLIST_REMOVE(cli->cli->pipe_list, cli);
556         talloc_destroy(cli->mem_ctx);
557         return ret;
558 }
559
560 /****************************************************************************
561  Close all pipes open on this session.
562 ****************************************************************************/
563
564 void cli_nt_pipes_close(struct cli_state *cli)
565 {
566         struct rpc_pipe_client *cp, *next;
567
568         for (cp = cli->pipe_list; cp; cp = next) {
569                 next = cp->next;
570                 cli_rpc_pipe_close(cp);
571         }
572 }
573
574 /****************************************************************************
575  Shutdown a client structure.
576 ****************************************************************************/
577
578 void cli_shutdown(struct cli_state *cli)
579 {
580         cli_nt_pipes_close(cli);
581
582         /*
583          * tell our peer to free his resources.  Wihtout this, when an
584          * application attempts to do a graceful shutdown and calls
585          * smbc_free_context() to clean up all connections, some connections
586          * can remain active on the peer end, until some (long) timeout period
587          * later.  This tree disconnect forces the peer to clean up, since the
588          * connection will be going away.
589          *
590          * Also, do not do tree disconnect when cli->smb_rw_error is SMB_DO_NOT_DO_TDIS
591          * the only user for this so far is smbmount which passes opened connection
592          * down to kernel's smbfs module.
593          */
594         if ( (cli->cnum != (uint16)-1) && (cli->smb_rw_error != SMB_DO_NOT_DO_TDIS ) ) {
595                 cli_tdis(cli);
596         }
597         
598         SAFE_FREE(cli->outbuf);
599         SAFE_FREE(cli->inbuf);
600
601         cli_free_signing_context(cli);
602         data_blob_free(&cli->secblob);
603         data_blob_free(&cli->user_session_key);
604
605         if (cli->fd != -1) {
606                 close(cli->fd);
607         }
608         cli->fd = -1;
609         cli->smb_rw_error = SMB_READ_OK;
610
611         SAFE_FREE(cli);
612 }
613
614 /****************************************************************************
615  Set socket options on a open connection.
616 ****************************************************************************/
617
618 void cli_sockopt(struct cli_state *cli, const char *options)
619 {
620         set_socket_options(cli->fd, options);
621 }
622
623 /****************************************************************************
624  Set the PID to use for smb messages. Return the old pid.
625 ****************************************************************************/
626
627 uint16 cli_setpid(struct cli_state *cli, uint16 pid)
628 {
629         uint16 ret = cli->pid;
630         cli->pid = pid;
631         return ret;
632 }
633
634 /****************************************************************************
635  Set the case sensitivity flag on the packets. Returns old state.
636 ****************************************************************************/
637
638 bool cli_set_case_sensitive(struct cli_state *cli, bool case_sensitive)
639 {
640         bool ret = cli->case_sensitive;
641         cli->case_sensitive = case_sensitive;
642         return ret;
643 }
644
645 /****************************************************************************
646 Send a keepalive packet to the server
647 ****************************************************************************/
648
649 bool cli_send_keepalive(struct cli_state *cli)
650 {
651         if (cli->fd == -1) {
652                 DEBUG(3, ("cli_send_keepalive: fd == -1\n"));
653                 return False;
654         }
655         if (!send_keepalive(cli->fd)) {
656                 close(cli->fd);
657                 cli->fd = -1;
658                 DEBUG(0,("Error sending keepalive packet to client.\n"));
659                 return False;
660         }
661         return True;
662 }
663
664 /****************************************************************************
665  Send/receive a SMBecho command: ping the server
666 ****************************************************************************/
667
668 bool cli_echo(struct cli_state *cli, uint16 num_echos,
669               unsigned char *data, size_t length)
670 {
671         char *p;
672         int i;
673
674         SMB_ASSERT(length < 1024);
675
676         memset(cli->outbuf,'\0',smb_size);
677         set_message(cli->outbuf,1,length,True);
678         SCVAL(cli->outbuf,smb_com,SMBecho);
679         SSVAL(cli->outbuf,smb_tid,65535);
680         SSVAL(cli->outbuf,smb_vwv0,num_echos);
681         cli_setup_packet(cli);
682         p = smb_buf(cli->outbuf);
683         memcpy(p, data, length);
684         p += length;
685
686         cli_setup_bcc(cli, p);
687
688         cli_send_smb(cli);
689
690         for (i=0; i<num_echos; i++) {
691                 if (!cli_receive_smb(cli)) {
692                         return False;
693                 }
694
695                 if (cli_is_error(cli)) {
696                         return False;
697                 }
698         }
699
700         return True;
701 }