s3:libsmb: make use of cli_state_disconnect()
[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    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 #include "libsmb/libsmb.h"
23 #include "../lib/util/tevent_ntstatus.h"
24 #include "smb_signing.h"
25 #include "async_smb.h"
26
27 /*******************************************************************
28  Setup the word count and byte count for a client smb message.
29 ********************************************************************/
30
31 int cli_set_message(char *buf,int num_words,int num_bytes,bool zero)
32 {
33         if (zero && (num_words || num_bytes)) {
34                 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
35         }
36         SCVAL(buf,smb_wct,num_words);
37         SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
38         smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
39         return (smb_size + num_words*2 + num_bytes);
40 }
41
42 /****************************************************************************
43  Change the timeout (in milliseconds).
44 ****************************************************************************/
45
46 unsigned int cli_set_timeout(struct cli_state *cli, unsigned int timeout)
47 {
48         unsigned int old_timeout = cli->timeout;
49         cli->timeout = timeout;
50         return old_timeout;
51 }
52
53 /****************************************************************************
54  convenience routine to find if we negotiated ucs2
55 ****************************************************************************/
56
57 bool cli_ucs2(struct cli_state *cli)
58 {
59         return ((cli->capabilities & CAP_UNICODE) != 0);
60 }
61
62 /****************************************************************************
63  Setup basics in a outgoing packet.
64 ****************************************************************************/
65
66 void cli_setup_packet_buf(struct cli_state *cli, char *buf)
67 {
68         uint16 flags2;
69         cli->rap_error = 0;
70         SIVAL(buf,smb_rcls,0);
71         SSVAL(buf,smb_pid,cli->smb1.pid);
72         memset(buf+smb_pidhigh, 0, 12);
73         SSVAL(buf,smb_uid, cli_state_get_uid(cli));
74         SSVAL(buf,smb_mid,cli->smb1.mid);
75
76         if (cli->protocol <= PROTOCOL_CORE) {
77                 return;
78         }
79
80         if (cli->case_sensitive) {
81                 SCVAL(buf,smb_flg,0x0);
82         } else {
83                 /* Default setting, case insensitive. */
84                 SCVAL(buf,smb_flg,0x8);
85         }
86         flags2 = FLAGS2_LONG_PATH_COMPONENTS;
87         if (cli->capabilities & CAP_UNICODE)
88                 flags2 |= FLAGS2_UNICODE_STRINGS;
89         if ((cli->capabilities & CAP_DFS) && cli->dfsroot)
90                 flags2 |= FLAGS2_DFS_PATHNAMES;
91         if (cli->capabilities & CAP_STATUS32)
92                 flags2 |= FLAGS2_32_BIT_ERROR_CODES;
93         if (cli->use_spnego)
94                 flags2 |= FLAGS2_EXTENDED_SECURITY;
95         SSVAL(buf,smb_flg2, flags2);
96 }
97
98 /****************************************************************************
99  Initialize Domain, user or password.
100 ****************************************************************************/
101
102 NTSTATUS cli_set_domain(struct cli_state *cli, const char *domain)
103 {
104         TALLOC_FREE(cli->domain);
105         cli->domain = talloc_strdup(cli, domain ? domain : "");
106         if (cli->domain == NULL) {
107                 return NT_STATUS_NO_MEMORY;
108         }
109         return NT_STATUS_OK;
110 }
111
112 NTSTATUS cli_set_username(struct cli_state *cli, const char *username)
113 {
114         TALLOC_FREE(cli->user_name);
115         cli->user_name = talloc_strdup(cli, username ? username : "");
116         if (cli->user_name == NULL) {
117                 return NT_STATUS_NO_MEMORY;
118         }
119         return NT_STATUS_OK;
120 }
121
122 NTSTATUS cli_set_password(struct cli_state *cli, const char *password)
123 {
124         TALLOC_FREE(cli->password);
125
126         /* Password can be NULL. */
127         if (password) {
128                 cli->password = talloc_strdup(cli, password);
129                 if (cli->password == NULL) {
130                         return NT_STATUS_NO_MEMORY;
131                 }
132         } else {
133                 /* Use zero NTLMSSP hashes and session key. */
134                 cli->password = NULL;
135         }
136
137         return NT_STATUS_OK;
138 }
139
140 /****************************************************************************
141  Initialise credentials of a client structure.
142 ****************************************************************************/
143
144 NTSTATUS cli_init_creds(struct cli_state *cli, const char *username, const char *domain, const char *password)
145 {
146         NTSTATUS status = cli_set_username(cli, username);
147         if (!NT_STATUS_IS_OK(status)) {
148                 return status;
149         }
150         status = cli_set_domain(cli, domain);
151         if (!NT_STATUS_IS_OK(status)) {
152                 return status;
153         }
154         DEBUG(10,("cli_init_creds: user %s domain %s\n", cli->user_name, cli->domain));
155
156         return cli_set_password(cli, password);
157 }
158
159 /****************************************************************************
160  Initialise a client structure. Always returns a talloc'ed struct.
161  Set the signing state (used from the command line).
162 ****************************************************************************/
163
164 struct cli_state *cli_state_create(TALLOC_CTX *mem_ctx,
165                                    int fd,
166                                    const char *desthost,
167                                    int signing_state)
168 {
169         struct cli_state *cli = NULL;
170         bool allow_smb_signing = false;
171         bool mandatory_signing = false;
172         socklen_t ss_length;
173         int ret;
174
175         /* Check the effective uid - make sure we are not setuid */
176         if (is_setuid_root()) {
177                 DEBUG(0,("libsmb based programs must *NOT* be setuid root.\n"));
178                 return NULL;
179         }
180
181         cli = talloc_zero(mem_ctx, struct cli_state);
182         if (!cli) {
183                 return NULL;
184         }
185
186         cli->dfs_mountpoint = talloc_strdup(cli, "");
187         if (!cli->dfs_mountpoint) {
188                 goto error;
189         }
190         cli->fd = -1;
191         cli->raw_status = NT_STATUS_INTERNAL_ERROR;
192         cli->protocol = PROTOCOL_NT1;
193         cli->timeout = 20000; /* Timeout is in milliseconds. */
194         cli->max_xmit = CLI_BUFFER_SIZE+4;
195         cli->case_sensitive = false;
196
197         cli->use_spnego = lp_client_use_spnego();
198
199         cli->capabilities = CAP_UNICODE | CAP_STATUS32 | CAP_DFS;
200
201         /* Set the CLI_FORCE_DOSERR environment variable to test
202            client routines using DOS errors instead of STATUS32
203            ones.  This intended only as a temporary hack. */    
204         if (getenv("CLI_FORCE_DOSERR"))
205                 cli->force_dos_errors = true;
206
207         if (lp_client_signing()) {
208                 allow_smb_signing = true;
209         }
210
211         if (lp_client_signing() == Required) {
212                 mandatory_signing = true;
213         }
214
215         if (signing_state != Undefined) {
216                 allow_smb_signing = true;
217         }
218
219         if (signing_state == false) {
220                 allow_smb_signing = false;
221                 mandatory_signing = false;
222         }
223
224         if (signing_state == Required) {
225                 mandatory_signing = true;
226         }
227
228         /* initialise signing */
229         cli->signing_state = smb_signing_init(cli,
230                                               allow_smb_signing,
231                                               mandatory_signing);
232         if (!cli->signing_state) {
233                 goto error;
234         }
235
236         cli->conn.outgoing = tevent_queue_create(cli, "cli_outgoing");
237         if (cli->conn.outgoing == NULL) {
238                 goto error;
239         }
240         cli->conn.pending = NULL;
241
242         cli->desthost = talloc_strdup(cli, desthost);
243         if (cli->desthost == NULL) {
244                 goto error;
245         }
246
247         cli->fd = fd;
248
249         ss_length = sizeof(cli->src_ss);
250         ret = getsockname(fd,
251                           (struct sockaddr *)(void *)&cli->src_ss,
252                           &ss_length);
253         if (ret == -1) {
254                 goto error;
255         }
256         ss_length = sizeof(cli->dest_ss);
257         ret = getpeername(fd,
258                           (struct sockaddr *)(void *)&cli->dest_ss,
259                           &ss_length);
260         if (ret == -1) {
261                 goto error;
262         }
263
264         cli->smb1.mid = 1;
265         cli->smb1.pid = (uint16_t)sys_getpid();
266         cli->smb1.vc_num = cli->smb1.pid;
267         cli->smb1.tid = UINT16_MAX;
268         cli->smb1.uid = UID_FIELD_INVALID;
269
270         cli->initialised = 1;
271         return cli;
272
273         /* Clean up after malloc() error */
274
275  error:
276
277         TALLOC_FREE(cli);
278         return NULL;
279 }
280
281 bool cli_state_encryption_on(struct cli_state *cli)
282 {
283         return common_encryption_on(cli->trans_enc_state);
284 }
285
286
287 /****************************************************************************
288  Close all pipes open on this session.
289 ****************************************************************************/
290
291 void cli_nt_pipes_close(struct cli_state *cli)
292 {
293         while (cli->pipe_list != NULL) {
294                 /*
295                  * No TALLOC_FREE here!
296                  */
297                 talloc_free(cli->pipe_list);
298         }
299 }
300
301 /****************************************************************************
302  Shutdown a client structure.
303 ****************************************************************************/
304
305 static void _cli_shutdown(struct cli_state *cli)
306 {
307         cli_nt_pipes_close(cli);
308
309         /*
310          * tell our peer to free his resources.  Wihtout this, when an
311          * application attempts to do a graceful shutdown and calls
312          * smbc_free_context() to clean up all connections, some connections
313          * can remain active on the peer end, until some (long) timeout period
314          * later.  This tree disconnect forces the peer to clean up, since the
315          * connection will be going away.
316          */
317         if (cli_state_has_tcon(cli)) {
318                 cli_tdis(cli);
319         }
320         
321         data_blob_free(&cli->secblob);
322         data_blob_free(&cli->user_session_key);
323
324         cli_state_disconnect(cli);
325
326         /*
327          * Need to free pending first, they remove themselves
328          */
329         while (cli->conn.pending) {
330                 talloc_free(cli->conn.pending[0]);
331         }
332         TALLOC_FREE(cli);
333 }
334
335 void cli_shutdown(struct cli_state *cli)
336 {
337         struct cli_state *cli_head;
338         if (cli == NULL) {
339                 return;
340         }
341         DLIST_HEAD(cli, cli_head);
342         if (cli_head == cli) {
343                 /*
344                  * head of a DFS list, shutdown all subsidiary DFS
345                  * connections.
346                  */
347                 struct cli_state *p, *next;
348
349                 for (p = cli_head->next; p; p = next) {
350                         next = p->next;
351                         DLIST_REMOVE(cli_head, p);
352                         _cli_shutdown(p);
353                 }
354         } else {
355                 DLIST_REMOVE(cli_head, cli);
356         }
357
358         _cli_shutdown(cli);
359 }
360
361 /****************************************************************************
362  Set socket options on a open connection.
363 ****************************************************************************/
364
365 void cli_sockopt(struct cli_state *cli, const char *options)
366 {
367         set_socket_options(cli->fd, options);
368 }
369
370 uint16_t cli_state_get_vc_num(struct cli_state *cli)
371 {
372         return cli->smb1.vc_num;
373 }
374
375 /****************************************************************************
376  Set the PID to use for smb messages. Return the old pid.
377 ****************************************************************************/
378
379 uint16 cli_setpid(struct cli_state *cli, uint16 pid)
380 {
381         uint16_t ret = cli->smb1.pid;
382         cli->smb1.pid = pid;
383         return ret;
384 }
385
386 uint16_t cli_getpid(struct cli_state *cli)
387 {
388         return cli->smb1.pid;
389 }
390
391 bool cli_state_has_tcon(struct cli_state *cli)
392 {
393         if (cli->smb1.tid == UINT16_MAX) {
394                 return false;
395         }
396
397         return true;
398 }
399
400 uint16_t cli_state_get_tid(struct cli_state *cli)
401 {
402         return cli->smb1.tid;
403 }
404
405 uint16_t cli_state_set_tid(struct cli_state *cli, uint16_t tid)
406 {
407         uint16_t ret = cli->smb1.tid;
408         cli->smb1.tid = tid;
409         return ret;
410 }
411
412 uint16_t cli_state_get_uid(struct cli_state *cli)
413 {
414         return cli->smb1.uid;
415 }
416
417 uint16_t cli_state_set_uid(struct cli_state *cli, uint16_t uid)
418 {
419         uint16_t ret = cli->smb1.uid;
420         cli->smb1.uid = uid;
421         return ret;
422 }
423
424 /****************************************************************************
425  Set the case sensitivity flag on the packets. Returns old state.
426 ****************************************************************************/
427
428 bool cli_set_case_sensitive(struct cli_state *cli, bool case_sensitive)
429 {
430         bool ret = cli->case_sensitive;
431         cli->case_sensitive = case_sensitive;
432         return ret;
433 }
434
435 struct cli_echo_state {
436         uint16_t vwv[1];
437         DATA_BLOB data;
438         int num_echos;
439 };
440
441 static void cli_echo_done(struct tevent_req *subreq);
442
443 struct tevent_req *cli_echo_send(TALLOC_CTX *mem_ctx, struct event_context *ev,
444                                  struct cli_state *cli, uint16_t num_echos,
445                                  DATA_BLOB data)
446 {
447         struct tevent_req *req, *subreq;
448         struct cli_echo_state *state;
449
450         req = tevent_req_create(mem_ctx, &state, struct cli_echo_state);
451         if (req == NULL) {
452                 return NULL;
453         }
454         SSVAL(state->vwv, 0, num_echos);
455         state->data = data;
456         state->num_echos = num_echos;
457
458         subreq = cli_smb_send(state, ev, cli, SMBecho, 0, 1, state->vwv,
459                               data.length, data.data);
460         if (subreq == NULL) {
461                 goto fail;
462         }
463         tevent_req_set_callback(subreq, cli_echo_done, req);
464         return req;
465  fail:
466         TALLOC_FREE(req);
467         return NULL;
468 }
469
470 static void cli_echo_done(struct tevent_req *subreq)
471 {
472         struct tevent_req *req = tevent_req_callback_data(
473                 subreq, struct tevent_req);
474         struct cli_echo_state *state = tevent_req_data(
475                 req, struct cli_echo_state);
476         NTSTATUS status;
477         uint32_t num_bytes;
478         uint8_t *bytes;
479         uint8_t *inbuf;
480
481         status = cli_smb_recv(subreq, state, &inbuf, 0, NULL, NULL,
482                               &num_bytes, &bytes);
483         if (!NT_STATUS_IS_OK(status)) {
484                 tevent_req_nterror(req, status);
485                 return;
486         }
487         if ((num_bytes != state->data.length)
488             || (memcmp(bytes, state->data.data, num_bytes) != 0)) {
489                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
490                 return;
491         }
492
493         state->num_echos -=1;
494         if (state->num_echos == 0) {
495                 tevent_req_done(req);
496                 return;
497         }
498
499         if (!cli_smb_req_set_pending(subreq)) {
500                 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
501                 return;
502         }
503 }
504
505 /**
506  * Get the result out from an echo request
507  * @param[in] req       The async_req from cli_echo_send
508  * @retval Did the server reply correctly?
509  */
510
511 NTSTATUS cli_echo_recv(struct tevent_req *req)
512 {
513         return tevent_req_simple_recv_ntstatus(req);
514 }
515
516 /**
517  * @brief Send/Receive SMBEcho requests
518  * @param[in] mem_ctx   The memory context to put the async_req on
519  * @param[in] ev        The event context that will call us back
520  * @param[in] cli       The connection to send the echo to
521  * @param[in] num_echos How many times do we want to get the reply?
522  * @param[in] data      The data we want to get back
523  * @retval Did the server reply correctly?
524  */
525
526 NTSTATUS cli_echo(struct cli_state *cli, uint16_t num_echos, DATA_BLOB data)
527 {
528         TALLOC_CTX *frame = talloc_stackframe();
529         struct event_context *ev;
530         struct tevent_req *req;
531         NTSTATUS status = NT_STATUS_OK;
532
533         if (cli_has_async_calls(cli)) {
534                 /*
535                  * Can't use sync call while an async call is in flight
536                  */
537                 status = NT_STATUS_INVALID_PARAMETER;
538                 goto fail;
539         }
540
541         ev = event_context_init(frame);
542         if (ev == NULL) {
543                 status = NT_STATUS_NO_MEMORY;
544                 goto fail;
545         }
546
547         req = cli_echo_send(frame, ev, cli, num_echos, data);
548         if (req == NULL) {
549                 status = NT_STATUS_NO_MEMORY;
550                 goto fail;
551         }
552
553         if (!tevent_req_poll(req, ev)) {
554                 status = map_nt_error_from_unix(errno);
555                 goto fail;
556         }
557
558         status = cli_echo_recv(req);
559  fail:
560         TALLOC_FREE(frame);
561         return status;
562 }
563
564 /**
565  * Is the SMB command able to hold an AND_X successor
566  * @param[in] cmd       The SMB command in question
567  * @retval Can we add a chained request after "cmd"?
568  */
569 bool is_andx_req(uint8_t cmd)
570 {
571         switch (cmd) {
572         case SMBtconX:
573         case SMBlockingX:
574         case SMBopenX:
575         case SMBreadX:
576         case SMBwriteX:
577         case SMBsesssetupX:
578         case SMBulogoffX:
579         case SMBntcreateX:
580                 return true;
581                 break;
582         default:
583                 break;
584         }
585
586         return false;
587 }
588
589 NTSTATUS cli_smb(TALLOC_CTX *mem_ctx, struct cli_state *cli,
590                  uint8_t smb_command, uint8_t additional_flags,
591                  uint8_t wct, uint16_t *vwv,
592                  uint32_t num_bytes, const uint8_t *bytes,
593                  struct tevent_req **result_parent,
594                  uint8_t min_wct, uint8_t *pwct, uint16_t **pvwv,
595                  uint32_t *pnum_bytes, uint8_t **pbytes)
596 {
597         struct tevent_context *ev;
598         struct tevent_req *req = NULL;
599         NTSTATUS status = NT_STATUS_NO_MEMORY;
600
601         if (cli_has_async_calls(cli)) {
602                 return NT_STATUS_INVALID_PARAMETER;
603         }
604         ev = tevent_context_init(mem_ctx);
605         if (ev == NULL) {
606                 goto fail;
607         }
608         req = cli_smb_send(mem_ctx, ev, cli, smb_command, additional_flags,
609                            wct, vwv, num_bytes, bytes);
610         if (req == NULL) {
611                 goto fail;
612         }
613         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
614                 goto fail;
615         }
616         status = cli_smb_recv(req, NULL, NULL, min_wct, pwct, pvwv,
617                               pnum_bytes, pbytes);
618 fail:
619         TALLOC_FREE(ev);
620         if (NT_STATUS_IS_OK(status) && (result_parent != NULL)) {
621                 *result_parent = req;
622         }
623         return status;
624 }