Move "struct cli_request" from client.h to async_smb.h
[ira/wip.git] / source3 / libsmb / async_smb.c
1 /*
2    Unix SMB/CIFS implementation.
3    Infrastructure for async SMB client requests
4    Copyright (C) Volker Lendecke 2008
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 3 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, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21
22 static void cli_state_handler(struct event_context *event_ctx,
23                               struct fd_event *event, uint16 flags, void *p);
24
25 /**
26  * Fetch an error out of a NBT packet
27  * @param[in] buf       The SMB packet
28  * @retval              The error, converted to NTSTATUS
29  */
30
31 NTSTATUS cli_pull_error(char *buf)
32 {
33         uint32_t flags2 = SVAL(buf, smb_flg2);
34
35         if (flags2 & FLAGS2_32_BIT_ERROR_CODES) {
36                 return NT_STATUS(IVAL(buf, smb_rcls));
37         }
38
39         /* if the client uses dos errors, but there is no error,
40            we should return no error here, otherwise it looks
41            like an unknown bad NT_STATUS. jmcd */
42         if (CVAL(buf, smb_rcls) == 0)
43                 return NT_STATUS_OK;
44
45         return NT_STATUS_DOS(CVAL(buf, smb_rcls), SVAL(buf,smb_err));
46 }
47
48 /**
49  * Compatibility helper for the sync APIs: Fake NTSTATUS in cli->inbuf
50  * @param[in] cli       The client connection that just received an error
51  * @param[in] status    The error to set on "cli"
52  */
53
54 void cli_set_error(struct cli_state *cli, NTSTATUS status)
55 {
56         uint32_t flags2 = SVAL(cli->inbuf, smb_flg2);
57
58         if (NT_STATUS_IS_DOS(status)) {
59                 SSVAL(cli->inbuf, smb_flg2,
60                       flags2 & ~FLAGS2_32_BIT_ERROR_CODES);
61                 SCVAL(cli->inbuf, smb_rcls, NT_STATUS_DOS_CLASS(status));
62                 SSVAL(cli->inbuf, smb_err, NT_STATUS_DOS_CODE(status));
63                 return;
64         }
65
66         SSVAL(cli->inbuf, smb_flg2, flags2 | FLAGS2_32_BIT_ERROR_CODES);
67         SIVAL(cli->inbuf, smb_rcls, NT_STATUS_V(status));
68         return;
69 }
70
71 /**
72  * Allocate a new mid
73  * @param[in] cli       The client connection
74  * @retval              The new, unused mid
75  */
76
77 static uint16_t cli_new_mid(struct cli_state *cli)
78 {
79         uint16_t result;
80         struct cli_request *req;
81
82         while (true) {
83                 result = cli->mid++;
84                 if (result == 0) {
85                         continue;
86                 }
87
88                 for (req = cli->outstanding_requests; req; req = req->next) {
89                         if (result == req->mid) {
90                                 break;
91                         }
92                 }
93
94                 if (req == NULL) {
95                         return result;
96                 }
97         }
98 }
99
100 /**
101  * Print an async req that happens to be a cli_request
102  * @param[in] mem_ctx   The TALLOC_CTX to put the result on
103  * @param[in] req       The request to print
104  * @retval              The string representation of "req"
105  */
106
107 static char *cli_request_print(TALLOC_CTX *mem_ctx, struct async_req *req)
108 {
109         char *result = async_req_print(mem_ctx, req);
110         struct cli_request *cli_req = cli_request_get(req);
111
112         if (result == NULL) {
113                 return NULL;
114         }
115
116         return talloc_asprintf_append_buffer(
117                 result, "mid=%d\n", cli_req->mid);
118 }
119
120 /**
121  * Destroy a cli_request
122  * @param[in] req       The cli_request to kill
123  * @retval Can't fail
124  */
125
126 static int cli_request_destructor(struct cli_request *req)
127 {
128         if (req->enc_state != NULL) {
129                 common_free_enc_buffer(req->enc_state, req->outbuf);
130         }
131         DLIST_REMOVE(req->cli->outstanding_requests, req);
132         if (req->cli->outstanding_requests == NULL) {
133                 TALLOC_FREE(req->cli->fd_event);
134         }
135         return 0;
136 }
137
138 /*
139  * Create a fresh async smb request
140  */
141
142 static struct async_req *cli_request_new(TALLOC_CTX *mem_ctx,
143                                          struct event_context *ev,
144                                          struct cli_state *cli,
145                                          uint8_t num_words, size_t num_bytes,
146                                          struct cli_request **preq)
147 {
148         struct async_req *result;
149         struct cli_request *cli_req;
150         size_t bufsize = smb_size + num_words * 2 + num_bytes;
151
152         result = async_req_new(mem_ctx, ev);
153         if (result == NULL) {
154                 return NULL;
155         }
156
157         cli_req = (struct cli_request *)talloc_size(
158                 result, sizeof(*cli_req) + bufsize);
159         if (cli_req == NULL) {
160                 TALLOC_FREE(result);
161                 return NULL;
162         }
163         talloc_set_name_const(cli_req, "struct cli_request");
164         result->private_data = cli_req;
165         result->print = cli_request_print;
166
167         cli_req->async = result;
168         cli_req->cli = cli;
169         cli_req->outbuf = ((char *)cli_req + sizeof(*cli_req));
170         cli_req->sent = 0;
171         cli_req->mid = cli_new_mid(cli);
172         cli_req->inbuf = NULL;
173         cli_req->enc_state = NULL;
174
175         SCVAL(cli_req->outbuf, smb_wct, num_words);
176         SSVAL(cli_req->outbuf, smb_vwv + num_words * 2, num_bytes);
177
178         DLIST_ADD_END(cli->outstanding_requests, cli_req,
179                       struct cli_request *);
180         talloc_set_destructor(cli_req, cli_request_destructor);
181
182         DEBUG(10, ("cli_request_new: mid=%d\n", cli_req->mid));
183
184         *preq = cli_req;
185         return result;
186 }
187
188 /*
189  * Ship a new smb request to the server
190  */
191 struct async_req *cli_request_send(TALLOC_CTX *mem_ctx,
192                                    struct event_context *ev,
193                                    struct cli_state *cli,
194                                    uint8_t smb_command,
195                                    uint8_t additional_flags,
196                                    uint8_t wct, const uint16_t *vwv,
197                                    uint16_t num_bytes, const uint8_t *bytes)
198 {
199         struct async_req *result;
200         struct cli_request *req;
201
202         if (cli->fd_event == NULL) {
203                 SMB_ASSERT(cli->outstanding_requests == NULL);
204                 cli->fd_event = event_add_fd(ev, cli, cli->fd,
205                                              EVENT_FD_READ,
206                                              cli_state_handler, cli);
207                 if (cli->fd_event == NULL) {
208                         return NULL;
209                 }
210         }
211
212         result = cli_request_new(mem_ctx, ev, cli, wct, num_bytes, &req);
213         if (result == NULL) {
214                 DEBUG(0, ("cli_request_new failed\n"));
215                 TALLOC_FREE(cli->fd_event);
216                 return NULL;
217         }
218
219         cli_set_message(req->outbuf, wct, num_bytes, false);
220         SCVAL(req->outbuf, smb_com, smb_command);
221         SSVAL(req->outbuf, smb_tid, cli->cnum);
222         cli_setup_packet_buf(cli, req->outbuf);
223
224         memcpy(req->outbuf + smb_vwv0, vwv, sizeof(uint16_t) * wct);
225         memcpy(smb_buf(req->outbuf), bytes, num_bytes);
226         SSVAL(req->outbuf, smb_mid, req->mid);
227         SCVAL(cli->outbuf, smb_flg,
228               CVAL(cli->outbuf,smb_flg) | additional_flags);
229
230         cli_calculate_sign_mac(cli, req->outbuf);
231
232         if (cli_encryption_on(cli)) {
233                 NTSTATUS status;
234                 char *enc_buf;
235
236                 status = cli_encrypt_message(cli, req->outbuf, &enc_buf);
237                 if (!NT_STATUS_IS_OK(status)) {
238                         DEBUG(0, ("Error in encrypting client message. "
239                                   "Error %s\n", nt_errstr(status)));
240                         TALLOC_FREE(req);
241                         return NULL;
242                 }
243                 req->outbuf = enc_buf;
244                 req->enc_state = cli->trans_enc_state;
245         }
246
247         event_fd_set_writeable(cli->fd_event);
248
249         return result;
250 }
251
252 /**
253  * @brief Pull reply data out of a request
254  * @param[in] req               The request that we just received a reply for
255  * @param[out] pwct             How many words did the server send?
256  * @param[out] pvwv             The words themselves
257  * @param[out] pnum_bytes       How many bytes did the server send?
258  * @param[out] pbytes           The bytes themselves
259  * @retval Was the reply formally correct?
260  */
261
262 NTSTATUS cli_pull_reply(struct async_req *req,
263                         uint8_t *pwct, uint16_t **pvwv,
264                         uint16_t *pnum_bytes, uint8_t **pbytes)
265 {
266         struct cli_request *cli_req = cli_request_get(req);
267         uint8_t wct, cmd;
268         uint16_t num_bytes;
269         size_t wct_ofs, bytes_offset;
270         NTSTATUS status;
271
272         status = cli_pull_error(cli_req->inbuf);
273
274         if (NT_STATUS_IS_ERR(status)) {
275                 cli_set_error(cli_req->cli, status);
276                 return status;
277         }
278
279         cmd = CVAL(cli_req->inbuf, smb_com);
280         wct_ofs = smb_wct;
281
282         wct = CVAL(cli_req->inbuf, wct_ofs);
283
284         bytes_offset = wct_ofs + 1 + wct * sizeof(uint16_t);
285         num_bytes = SVAL(cli_req->inbuf, bytes_offset);
286
287         /*
288          * wct_ofs is a 16-bit value plus 4, wct is a 8-bit value, num_bytes
289          * is a 16-bit value. So bytes_offset being size_t should be far from
290          * wrapping.
291          */
292
293         if ((bytes_offset + 2 > talloc_get_size(cli_req->inbuf))
294             || (bytes_offset > 0xffff)) {
295                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
296         }
297
298         *pwct = wct;
299         *pvwv = (uint16_t *)(cli_req->inbuf + wct_ofs + 1);
300         *pnum_bytes = num_bytes;
301         *pbytes = (uint8_t *)cli_req->inbuf + bytes_offset + 2;
302
303         return NT_STATUS_OK;
304 }
305
306 /**
307  * Convenience function to get the SMB part out of an async_req
308  * @param[in] req       The request to look at
309  * @retval The private_data as struct cli_request
310  */
311
312 struct cli_request *cli_request_get(struct async_req *req)
313 {
314         if (req == NULL) {
315                 return NULL;
316         }
317         return talloc_get_type_abort(req->private_data, struct cli_request);
318 }
319
320 /**
321  * A PDU has arrived on cli->evt_inbuf
322  * @param[in] cli       The cli_state that received something
323  */
324
325 static void handle_incoming_pdu(struct cli_state *cli)
326 {
327         struct cli_request *req;
328         uint16_t mid;
329         size_t raw_pdu_len, buf_len, pdu_len, rest_len;
330         char *pdu;
331         NTSTATUS status;
332
333         /*
334          * The encrypted PDU len might differ from the unencrypted one
335          */
336         raw_pdu_len = smb_len(cli->evt_inbuf) + 4;
337         buf_len = talloc_get_size(cli->evt_inbuf);
338         rest_len = buf_len - raw_pdu_len;
339
340         if (buf_len == raw_pdu_len) {
341                 /*
342                  * Optimal case: Exactly one PDU was in the socket buffer
343                  */
344                 pdu = cli->evt_inbuf;
345                 cli->evt_inbuf = NULL;
346         }
347         else {
348                 DEBUG(11, ("buf_len = %d, raw_pdu_len = %d, splitting "
349                            "buffer\n", (int)buf_len, (int)raw_pdu_len));
350
351                 if (raw_pdu_len < rest_len) {
352                         /*
353                          * The PDU is shorter, talloc_memdup that one.
354                          */
355                         pdu = (char *)talloc_memdup(
356                                 cli, cli->evt_inbuf, raw_pdu_len);
357
358                         memmove(cli->evt_inbuf, cli->evt_inbuf + raw_pdu_len,
359                                 buf_len - raw_pdu_len);
360
361                         cli->evt_inbuf = TALLOC_REALLOC_ARRAY(
362                                 NULL, cli->evt_inbuf, char, rest_len);
363
364                         if (pdu == NULL) {
365                                 status = NT_STATUS_NO_MEMORY;
366                                 goto invalidate_requests;
367                         }
368                 }
369                 else {
370                         /*
371                          * The PDU is larger than the rest, talloc_memdup the
372                          * rest
373                          */
374                         pdu = cli->evt_inbuf;
375
376                         cli->evt_inbuf = (char *)talloc_memdup(
377                                 cli, pdu + raw_pdu_len, rest_len);
378
379                         if (cli->evt_inbuf == NULL) {
380                                 status = NT_STATUS_NO_MEMORY;
381                                 goto invalidate_requests;
382                         }
383                 }
384
385         }
386
387         /*
388          * TODO: Handle oplock break requests
389          */
390
391         if (cli_encryption_on(cli) && CVAL(pdu, 0) == 0) {
392                 uint16_t enc_ctx_num;
393
394                 status = get_enc_ctx_num((uint8_t *)pdu, &enc_ctx_num);
395                 if (!NT_STATUS_IS_OK(status)) {
396                         DEBUG(10, ("get_enc_ctx_num returned %s\n",
397                                    nt_errstr(status)));
398                         goto invalidate_requests;
399                 }
400
401                 if (enc_ctx_num != cli->trans_enc_state->enc_ctx_num) {
402                         DEBUG(10, ("wrong enc_ctx %d, expected %d\n",
403                                    enc_ctx_num,
404                                    cli->trans_enc_state->enc_ctx_num));
405                         status = NT_STATUS_INVALID_HANDLE;
406                         goto invalidate_requests;
407                 }
408
409                 status = common_decrypt_buffer(cli->trans_enc_state,
410                                                pdu);
411                 if (!NT_STATUS_IS_OK(status)) {
412                         DEBUG(10, ("common_decrypt_buffer returned %s\n",
413                                    nt_errstr(status)));
414                         goto invalidate_requests;
415                 }
416         }
417
418         if (!cli_check_sign_mac(cli, pdu)) {
419                 DEBUG(10, ("cli_check_sign_mac failed\n"));
420                 status = NT_STATUS_ACCESS_DENIED;
421                 goto invalidate_requests;
422         }
423
424         mid = SVAL(pdu, smb_mid);
425
426         DEBUG(10, ("handle_incoming_pdu: got mid %d\n", mid));
427
428         for (req = cli->outstanding_requests; req; req = req->next) {
429                 if (req->mid == mid) {
430                         break;
431                 }
432         }
433
434         pdu_len = smb_len(pdu) + 4;
435
436         if (req == NULL) {
437                 DEBUG(3, ("Request for mid %d not found, dumping PDU\n", mid));
438
439                 TALLOC_FREE(pdu);
440                 return;
441         }
442
443         req->inbuf = talloc_move(req, &pdu);
444
445         async_req_done(req->async);
446         return;
447
448  invalidate_requests:
449
450         DEBUG(10, ("handle_incoming_pdu: Aborting with %s\n",
451                    nt_errstr(status)));
452
453         for (req = cli->outstanding_requests; req; req = req->next) {
454                 async_req_error(req->async, status);
455         }
456         return;
457 }
458
459 /**
460  * fd event callback. This is the basic connection to the socket
461  * @param[in] event_ctx The event context that called us
462  * @param[in] event     The event that fired
463  * @param[in] flags     EVENT_FD_READ | EVENT_FD_WRITE
464  * @param[in] p         private_data, in this case the cli_state
465  */
466
467 static void cli_state_handler(struct event_context *event_ctx,
468                               struct fd_event *event, uint16 flags, void *p)
469 {
470         struct cli_state *cli = (struct cli_state *)p;
471         struct cli_request *req;
472
473         DEBUG(11, ("cli_state_handler called with flags %d\n", flags));
474
475         if (flags & EVENT_FD_READ) {
476                 int res, available;
477                 size_t old_size, new_size;
478                 char *tmp;
479
480                 res = ioctl(cli->fd, FIONREAD, &available);
481                 if (res == -1) {
482                         DEBUG(10, ("ioctl(FIONREAD) failed: %s\n",
483                                    strerror(errno)));
484                         goto sock_error;
485                 }
486
487                 if (available == 0) {
488                         /* EOF */
489                         goto sock_error;
490                 }
491
492                 old_size = talloc_get_size(cli->evt_inbuf);
493                 new_size = old_size + available;
494
495                 if (new_size < old_size) {
496                         /* wrap */
497                         goto sock_error;
498                 }
499
500                 tmp = TALLOC_REALLOC_ARRAY(cli, cli->evt_inbuf, char,
501                                            new_size);
502                 if (tmp == NULL) {
503                         /* nomem */
504                         goto sock_error;
505                 }
506                 cli->evt_inbuf = tmp;
507
508                 res = recv(cli->fd, cli->evt_inbuf + old_size, available, 0);
509                 if (res == -1) {
510                         DEBUG(10, ("recv failed: %s\n", strerror(errno)));
511                         goto sock_error;
512                 }
513
514                 DEBUG(11, ("cli_state_handler: received %d bytes, "
515                            "smb_len(evt_inbuf) = %d\n", (int)res,
516                            smb_len(cli->evt_inbuf)));
517
518                 /* recv *might* have returned less than announced */
519                 new_size = old_size + res;
520
521                 /* shrink, so I don't expect errors here */
522                 cli->evt_inbuf = TALLOC_REALLOC_ARRAY(cli, cli->evt_inbuf,
523                                                       char, new_size);
524
525                 while ((cli->evt_inbuf != NULL)
526                        && ((smb_len(cli->evt_inbuf) + 4) <= new_size)) {
527                         /*
528                          * we've got a complete NBT level PDU in evt_inbuf
529                          */
530                         handle_incoming_pdu(cli);
531                         new_size = talloc_get_size(cli->evt_inbuf);
532                 }
533         }
534
535         if (flags & EVENT_FD_WRITE) {
536                 size_t to_send;
537                 ssize_t sent;
538
539                 for (req = cli->outstanding_requests; req; req = req->next) {
540                         to_send = smb_len(req->outbuf)+4;
541                         if (to_send > req->sent) {
542                                 break;
543                         }
544                 }
545
546                 if (req == NULL) {
547                         if (cli->fd_event != NULL) {
548                                 event_fd_set_not_writeable(cli->fd_event);
549                         }
550                         return;
551                 }
552
553                 sent = send(cli->fd, req->outbuf + req->sent,
554                             to_send - req->sent, 0);
555
556                 if (sent < 0) {
557                         goto sock_error;
558                 }
559
560                 req->sent += sent;
561
562                 if (req->sent == to_send) {
563                         return;
564                 }
565         }
566         return;
567
568  sock_error:
569         for (req = cli->outstanding_requests; req; req = req->next) {
570                 req->async->state = ASYNC_REQ_ERROR;
571                 req->async->status = map_nt_error_from_unix(errno);
572         }
573         TALLOC_FREE(cli->fd_event);
574         close(cli->fd);
575         cli->fd = -1;
576 }