Add cli_pull_reply
[metze/samba/wip.git] / source3 / libsmb / clireadwrite.c
1 /*
2    Unix SMB/CIFS implementation.
3    client file read/write routines
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 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 /****************************************************************************
23   Calculate the recommended read buffer size
24 ****************************************************************************/
25 static size_t cli_read_max_bufsize(struct cli_state *cli)
26 {
27         if (!client_is_signing_on(cli) && !cli_encryption_on(cli)
28             && (cli->posix_capabilities & CIFS_UNIX_LARGE_READ_CAP)) {
29                 return CLI_SAMBA_MAX_POSIX_LARGE_READX_SIZE;
30         }
31         if (cli->capabilities & CAP_LARGE_READX) {
32                 return cli->is_samba
33                         ? CLI_SAMBA_MAX_LARGE_READX_SIZE
34                         : CLI_WINDOWS_MAX_LARGE_READX_SIZE;
35         }
36         return (cli->max_xmit - (smb_size+32)) & ~1023;
37 }
38
39 /*
40  * Send a read&x request
41  */
42
43 struct async_req *cli_read_andx_send(TALLOC_CTX *mem_ctx,
44                                      struct event_context *ev,
45                                      struct cli_state *cli, int fnum,
46                                      off_t offset, size_t size)
47 {
48         struct async_req *result;
49         struct cli_request *req;
50         bool bigoffset = False;
51
52         uint16_t vwv[12];
53         uint8_t wct = 10;
54
55         if (size > cli_read_max_bufsize(cli)) {
56                 DEBUG(0, ("cli_read_andx_send got size=%d, can only handle "
57                           "size=%d\n", (int)size,
58                           (int)cli_read_max_bufsize(cli)));
59                 return NULL;
60         }
61
62         SCVAL(vwv + 0, 0, 0xFF);
63         SCVAL(vwv + 0, 1, 0);
64         SSVAL(vwv + 1, 0, 0);
65         SSVAL(vwv + 2, 0, fnum);
66         SIVAL(vwv + 3, 0, offset);
67         SSVAL(vwv + 5, 0, size);
68         SSVAL(vwv + 6, 0, size);
69         SSVAL(vwv + 7, 0, (size >> 16));
70         SSVAL(vwv + 8, 0, 0);
71         SSVAL(vwv + 9, 0, 0);
72
73         if ((SMB_BIG_UINT)offset >> 32) {
74                 bigoffset = True;
75                 SIVAL(vwv + 10, 0,
76                       (((SMB_BIG_UINT)offset)>>32) & 0xffffffff);
77                 wct += 2;
78         }
79
80         result = cli_request_send(mem_ctx, ev, cli, SMBreadX, 0, wct, vwv,
81                                   0, NULL);
82         if (result == NULL) {
83                 return NULL;
84         }
85
86         req = cli_request_get(result);
87
88         req->data.read.ofs = offset;
89         req->data.read.size = size;
90         req->data.read.received = 0;
91         req->data.read.rcvbuf = NULL;
92
93         return result;
94 }
95
96 /*
97  * Pull the data out of a finished async read_and_x request. rcvbuf is
98  * talloced from the request, so better make sure that you copy it away before
99  * you talloc_free(req). "rcvbuf" is NOT a talloc_ctx of its own, so do not
100  * talloc_move it!
101  */
102
103 NTSTATUS cli_read_andx_recv(struct async_req *req, ssize_t *received,
104                             uint8_t **rcvbuf)
105 {
106         struct cli_request *cli_req = cli_request_get(req);
107         uint8_t wct;
108         uint16_t *vwv;
109         uint16_t num_bytes;
110         uint8_t *bytes;
111         NTSTATUS status;
112         size_t size;
113
114         SMB_ASSERT(req->state >= ASYNC_REQ_DONE);
115         if (req->state == ASYNC_REQ_ERROR) {
116                 return req->status;
117         }
118
119         status = cli_pull_reply(req, &wct, &vwv, &num_bytes, &bytes);
120
121         if (NT_STATUS_IS_ERR(status)) {
122                 return status;
123         }
124
125         if (wct < 12) {
126                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
127         }
128
129         /* size is the number of bytes the server returned.
130          * Might be zero. */
131         size = SVAL(vwv + 5, 0);
132         size |= (((unsigned int)SVAL(vwv + 7, 0)) << 16);
133
134         if (size > cli_req->data.read.size) {
135                 DEBUG(5,("server returned more than we wanted!\n"));
136                 return NT_STATUS_UNEXPECTED_IO_ERROR;
137         }
138
139         *rcvbuf = (uint8_t *)(smb_base(cli_req->inbuf) + SVAL(vwv + 6, 0));
140         *received = size;
141         return NT_STATUS_OK;
142 }
143
144 /*
145  * Parallel read support.
146  *
147  * cli_pull sends as many read&x requests as the server would allow via
148  * max_mux at a time. When replies flow back in, the data is written into
149  * the callback function "sink" in the right order.
150  */
151
152 struct cli_pull_state {
153         struct async_req *req;
154
155         struct event_context *ev;
156         struct cli_state *cli;
157         uint16_t fnum;
158         off_t start_offset;
159         SMB_OFF_T size;
160
161         NTSTATUS (*sink)(char *buf, size_t n, void *priv);
162         void *priv;
163
164         size_t chunk_size;
165
166         /*
167          * Outstanding requests
168          */
169         int num_reqs;
170         struct async_req **reqs;
171
172         /*
173          * For how many bytes did we send requests already?
174          */
175         SMB_OFF_T requested;
176
177         /*
178          * Next request index to push into "sink". This walks around the "req"
179          * array, taking care that the requests are pushed to "sink" in the
180          * right order. If necessary (i.e. replies don't come in in the right
181          * order), replies are held back in "reqs".
182          */
183         int top_req;
184
185         /*
186          * How many bytes did we push into "sink"?
187          */
188
189         SMB_OFF_T pushed;
190 };
191
192 static char *cli_pull_print(TALLOC_CTX *mem_ctx, struct async_req *req)
193 {
194         struct cli_pull_state *state = talloc_get_type_abort(
195                 req->private_data, struct cli_pull_state);
196         char *result;
197
198         result = async_req_print(mem_ctx, req);
199         if (result == NULL) {
200                 return NULL;
201         }
202
203         return talloc_asprintf_append_buffer(
204                 result, "num_reqs=%d, top_req=%d",
205                 state->num_reqs, state->top_req);
206 }
207
208 static void cli_pull_read_done(struct async_req *read_req);
209
210 /*
211  * Prepare an async pull request
212  */
213
214 struct async_req *cli_pull_send(TALLOC_CTX *mem_ctx,
215                                 struct event_context *ev,
216                                 struct cli_state *cli,
217                                 uint16_t fnum, off_t start_offset,
218                                 SMB_OFF_T size, size_t window_size,
219                                 NTSTATUS (*sink)(char *buf, size_t n,
220                                                  void *priv),
221                                 void *priv)
222 {
223         struct async_req *result;
224         struct cli_pull_state *state;
225         int i;
226
227         result = async_req_new(mem_ctx, ev);
228         if (result == NULL) {
229                 goto failed;
230         }
231         state = talloc(result, struct cli_pull_state);
232         if (state == NULL) {
233                 goto failed;
234         }
235         result->private_data = state;
236         result->print = cli_pull_print;
237         state->req = result;
238
239         state->cli = cli;
240         state->ev = ev;
241         state->fnum = fnum;
242         state->start_offset = start_offset;
243         state->size = size;
244         state->sink = sink;
245         state->priv = priv;
246
247         state->pushed = 0;
248         state->top_req = 0;
249
250         if (size == 0) {
251                 if (!async_post_status(result, NT_STATUS_OK)) {
252                         goto failed;
253                 }
254                 return result;
255         }
256
257         state->chunk_size = cli_read_max_bufsize(cli);
258
259         state->num_reqs = MAX(window_size/state->chunk_size, 1);
260         state->num_reqs = MIN(state->num_reqs, cli->max_mux);
261
262         state->reqs = TALLOC_ZERO_ARRAY(state, struct async_req *,
263                                         state->num_reqs);
264         if (state->reqs == NULL) {
265                 goto failed;
266         }
267
268         state->requested = 0;
269
270         for (i=0; i<state->num_reqs; i++) {
271                 SMB_OFF_T size_left;
272                 size_t request_thistime;
273
274                 if (state->requested >= size) {
275                         state->num_reqs = i;
276                         break;
277                 }
278
279                 size_left = size - state->requested;
280                 request_thistime = MIN(size_left, state->chunk_size);
281
282                 state->reqs[i] = cli_read_andx_send(
283                         state->reqs, ev, cli, fnum,
284                         state->start_offset + state->requested,
285                         request_thistime);
286
287                 if (state->reqs[i] == NULL) {
288                         goto failed;
289                 }
290
291                 state->reqs[i]->async.fn = cli_pull_read_done;
292                 state->reqs[i]->async.priv = result;
293
294                 state->requested += request_thistime;
295         }
296         return result;
297
298 failed:
299         TALLOC_FREE(result);
300         return NULL;
301 }
302
303 /*
304  * Handle incoming read replies, push the data into sink and send out new
305  * requests if necessary.
306  */
307
308 static void cli_pull_read_done(struct async_req *read_req)
309 {
310         struct async_req *pull_req = talloc_get_type_abort(
311                 read_req->async.priv, struct async_req);
312         struct cli_pull_state *state = talloc_get_type_abort(
313                 pull_req->private_data, struct cli_pull_state);
314         struct cli_request *read_state = cli_request_get(read_req);
315         NTSTATUS status;
316
317         status = cli_read_andx_recv(read_req, &read_state->data.read.received,
318                                     &read_state->data.read.rcvbuf);
319         if (!NT_STATUS_IS_OK(status)) {
320                 async_req_error(state->req, status);
321                 return;
322         }
323
324         /*
325          * This loop is the one to take care of out-of-order replies. All
326          * pending requests are in state->reqs, state->reqs[top_req] is the
327          * one that is to be pushed next. If however a request later than
328          * top_req is replied to, then we can't push yet. If top_req is
329          * replied to at a later point then, we need to push all the finished
330          * requests.
331          */
332
333         while (state->reqs[state->top_req] != NULL) {
334                 struct cli_request *top_read;
335
336                 DEBUG(11, ("cli_pull_read_done: top_req = %d\n",
337                            state->top_req));
338
339                 if (state->reqs[state->top_req]->state < ASYNC_REQ_DONE) {
340                         DEBUG(11, ("cli_pull_read_done: top request not yet "
341                                    "done\n"));
342                         return;
343                 }
344
345                 top_read = cli_request_get(state->reqs[state->top_req]);
346
347                 DEBUG(10, ("cli_pull_read_done: Pushing %d bytes, %d already "
348                            "pushed\n", (int)top_read->data.read.received,
349                            (int)state->pushed));
350
351                 status = state->sink((char *)top_read->data.read.rcvbuf,
352                                      top_read->data.read.received,
353                                      state->priv);
354                 if (!NT_STATUS_IS_OK(status)) {
355                         async_req_error(state->req, status);
356                         return;
357                 }
358                 state->pushed += top_read->data.read.received;
359
360                 TALLOC_FREE(state->reqs[state->top_req]);
361
362                 if (state->requested < state->size) {
363                         struct async_req *new_req;
364                         SMB_OFF_T size_left;
365                         size_t request_thistime;
366
367                         size_left = state->size - state->requested;
368                         request_thistime = MIN(size_left, state->chunk_size);
369
370                         DEBUG(10, ("cli_pull_read_done: Requesting %d bytes "
371                                    "at %d, position %d\n",
372                                    (int)request_thistime,
373                                    (int)(state->start_offset
374                                          + state->requested),
375                                    state->top_req));
376
377                         new_req = cli_read_andx_send(
378                                 state->reqs, state->ev, state->cli,
379                                 state->fnum,
380                                 state->start_offset + state->requested,
381                                 request_thistime);
382
383                         if (async_req_nomem(new_req, state->req)) {
384                                 return;
385                         }
386
387                         new_req->async.fn = cli_pull_read_done;
388                         new_req->async.priv = pull_req;
389
390                         state->reqs[state->top_req] = new_req;
391                         state->requested += request_thistime;
392                 }
393
394                 state->top_req = (state->top_req+1) % state->num_reqs;
395         }
396
397         async_req_done(pull_req);
398 }
399
400 NTSTATUS cli_pull_recv(struct async_req *req, SMB_OFF_T *received)
401 {
402         struct cli_pull_state *state = talloc_get_type_abort(
403                 req->private_data, struct cli_pull_state);
404
405         SMB_ASSERT(req->state >= ASYNC_REQ_DONE);
406         if (req->state == ASYNC_REQ_ERROR) {
407                 return req->status;
408         }
409         *received = state->pushed;
410         return NT_STATUS_OK;
411 }
412
413 NTSTATUS cli_pull(struct cli_state *cli, uint16_t fnum,
414                   off_t start_offset, SMB_OFF_T size, size_t window_size,
415                   NTSTATUS (*sink)(char *buf, size_t n, void *priv),
416                   void *priv, SMB_OFF_T *received)
417 {
418         TALLOC_CTX *frame = talloc_stackframe();
419         struct event_context *ev;
420         struct async_req *req;
421         NTSTATUS result = NT_STATUS_NO_MEMORY;
422
423         if (cli->fd_event != NULL) {
424                 /*
425                  * Can't use sync call while an async call is in flight
426                  */
427                 return NT_STATUS_INVALID_PARAMETER;
428         }
429
430         ev = event_context_init(frame);
431         if (ev == NULL) {
432                 goto nomem;
433         }
434
435         req = cli_pull_send(frame, ev, cli, fnum, start_offset, size,
436                             window_size, sink, priv);
437         if (req == NULL) {
438                 goto nomem;
439         }
440
441         while (req->state < ASYNC_REQ_DONE) {
442                 event_loop_once(ev);
443         }
444
445         result = cli_pull_recv(req, received);
446  nomem:
447         TALLOC_FREE(frame);
448         return result;
449 }
450
451 static NTSTATUS cli_read_sink(char *buf, size_t n, void *priv)
452 {
453         char **pbuf = (char **)priv;
454         memcpy(*pbuf, buf, n);
455         *pbuf += n;
456         return NT_STATUS_OK;
457 }
458
459 ssize_t cli_read(struct cli_state *cli, int fnum, char *buf,
460                  off_t offset, size_t size)
461 {
462         NTSTATUS status;
463         SMB_OFF_T ret;
464
465         status = cli_pull(cli, fnum, offset, size, size,
466                           cli_read_sink, &buf, &ret);
467         if (!NT_STATUS_IS_OK(status)) {
468                 cli_set_error(cli, status);
469                 return -1;
470         }
471         return ret;
472 }
473
474 /****************************************************************************
475  Issue a single SMBwrite and don't wait for a reply.
476 ****************************************************************************/
477
478 static bool cli_issue_write(struct cli_state *cli,
479                                 int fnum,
480                                 off_t offset,
481                                 uint16 mode,
482                                 const char *buf,
483                                 size_t size,
484                                 int i)
485 {
486         char *p;
487         bool large_writex = false;
488         /* We can only do direct writes if not signing and not encrypting. */
489         bool direct_writes = !client_is_signing_on(cli) && !cli_encryption_on(cli);
490
491         if (!direct_writes && size + 1 > cli->bufsize) {
492                 cli->outbuf = (char *)SMB_REALLOC(cli->outbuf, size + 1024);
493                 if (!cli->outbuf) {
494                         return False;
495                 }
496                 cli->inbuf = (char *)SMB_REALLOC(cli->inbuf, size + 1024);
497                 if (cli->inbuf == NULL) {
498                         SAFE_FREE(cli->outbuf);
499                         return False;
500                 }
501                 cli->bufsize = size + 1024;
502         }
503
504         memset(cli->outbuf,'\0',smb_size);
505         memset(cli->inbuf,'\0',smb_size);
506
507         if (cli->capabilities & CAP_LARGE_FILES) {
508                 large_writex = True;
509         }
510
511         if (large_writex) {
512                 cli_set_message(cli->outbuf,14,0,True);
513         } else {
514                 cli_set_message(cli->outbuf,12,0,True);
515         }
516
517         SCVAL(cli->outbuf,smb_com,SMBwriteX);
518         SSVAL(cli->outbuf,smb_tid,cli->cnum);
519         cli_setup_packet(cli);
520
521         SCVAL(cli->outbuf,smb_vwv0,0xFF);
522         SSVAL(cli->outbuf,smb_vwv2,fnum);
523
524         SIVAL(cli->outbuf,smb_vwv3,offset);
525         SIVAL(cli->outbuf,smb_vwv5,0);
526         SSVAL(cli->outbuf,smb_vwv7,mode);
527
528         SSVAL(cli->outbuf,smb_vwv8,(mode & 0x0008) ? size : 0);
529         /*
530          * According to CIFS-TR-1p00, this following field should only
531          * be set if CAP_LARGE_WRITEX is set. We should check this
532          * locally. However, this check might already have been
533          * done by our callers.
534          */
535         SSVAL(cli->outbuf,smb_vwv9,(size>>16));
536         SSVAL(cli->outbuf,smb_vwv10,size);
537         /* +1 is pad byte. */
538         SSVAL(cli->outbuf,smb_vwv11,
539               smb_buf(cli->outbuf) - smb_base(cli->outbuf) + 1);
540
541         if (large_writex) {
542                 SIVAL(cli->outbuf,smb_vwv12,(((SMB_BIG_UINT)offset)>>32) & 0xffffffff);
543         }
544
545         p = smb_base(cli->outbuf) + SVAL(cli->outbuf,smb_vwv11) -1;
546         *p++ = '\0'; /* pad byte. */
547         if (!direct_writes) {
548                 memcpy(p, buf, size);
549         }
550         if (size > 0x1FFFF) {
551                 /* This is a POSIX 14 word large write. */
552                 set_message_bcc(cli->outbuf, 0); /* Set bcc to zero. */
553                 _smb_setlen_large(cli->outbuf,smb_size + 28 + 1 /* pad */ + size - 4);
554         } else {
555                 cli_setup_bcc(cli, p+size);
556         }
557
558         SSVAL(cli->outbuf,smb_mid,cli->mid + i);
559
560         show_msg(cli->outbuf);
561         if (direct_writes) {
562                 /* For direct writes we now need to write the data
563                  * directly out of buf. */
564                 return cli_send_smb_direct_writeX(cli, buf, size);
565         } else {
566                 return cli_send_smb(cli);
567         }
568 }
569
570 /****************************************************************************
571   write to a file
572   write_mode: 0x0001 disallow write cacheing
573               0x0002 return bytes remaining
574               0x0004 use raw named pipe protocol
575               0x0008 start of message mode named pipe protocol
576 ****************************************************************************/
577
578 ssize_t cli_write(struct cli_state *cli,
579                  int fnum, uint16 write_mode,
580                  const char *buf, off_t offset, size_t size)
581 {
582         ssize_t bwritten = 0;
583         unsigned int issued = 0;
584         unsigned int received = 0;
585         int mpx = 1;
586         size_t writesize;
587         int blocks;
588
589         if(cli->max_mux > 1) {
590                 mpx = cli->max_mux-1;
591         } else {
592                 mpx = 1;
593         }
594
595         /* Default (small) writesize. */
596         writesize = (cli->max_xmit - (smb_size+32)) & ~1023;
597
598         if (write_mode == 0 &&
599                         !client_is_signing_on(cli) &&
600                         !cli_encryption_on(cli) &&
601                         (cli->posix_capabilities & CIFS_UNIX_LARGE_WRITE_CAP) &&
602                         (cli->capabilities & CAP_LARGE_FILES)) {
603                 /* Only do massive writes if we can do them direct
604                  * with no signing or encrypting - not on a pipe. */
605                 writesize = CLI_SAMBA_MAX_POSIX_LARGE_WRITEX_SIZE;
606         } else if ((cli->capabilities & CAP_LARGE_WRITEX) &&
607                         (strcmp(cli->dev, "LPT1:") != 0)) {
608
609                 /* Printer devices are restricted to max_xmit
610                  * writesize in Vista and XPSP3. */
611
612                 if (cli->is_samba) {
613                         writesize = CLI_SAMBA_MAX_LARGE_WRITEX_SIZE;
614                 } else if (!client_is_signing_on(cli)) {
615                         /* Windows restricts signed writes to max_xmit.
616                          * Found by Volker. */
617                         writesize = CLI_WINDOWS_MAX_LARGE_WRITEX_SIZE;
618                 }
619         }
620
621         blocks = (size + (writesize-1)) / writesize;
622
623         while (received < blocks) {
624
625                 while ((issued - received < mpx) && (issued < blocks)) {
626                         ssize_t bsent = issued * writesize;
627                         ssize_t size1 = MIN(writesize, size - bsent);
628
629                         if (!cli_issue_write(cli, fnum, offset + bsent,
630                                         write_mode,
631                                         buf + bsent,
632                                         size1, issued))
633                                 return -1;
634                         issued++;
635                 }
636
637                 if (!cli_receive_smb(cli)) {
638                         return bwritten;
639                 }
640
641                 received++;
642
643                 if (cli_is_error(cli))
644                         break;
645
646                 bwritten += SVAL(cli->inbuf, smb_vwv2);
647                 if (writesize > 0xFFFF) {
648                         bwritten += (((int)(SVAL(cli->inbuf, smb_vwv4)))<<16);
649                 }
650         }
651
652         while (received < issued && cli_receive_smb(cli)) {
653                 received++;
654         }
655
656         return bwritten;
657 }
658
659 /****************************************************************************
660   write to a file using a SMBwrite and not bypassing 0 byte writes
661 ****************************************************************************/
662
663 ssize_t cli_smbwrite(struct cli_state *cli,
664                      int fnum, char *buf, off_t offset, size_t size1)
665 {
666         char *p;
667         ssize_t total = 0;
668
669         do {
670                 size_t size = MIN(size1, cli->max_xmit - 48);
671
672                 memset(cli->outbuf,'\0',smb_size);
673                 memset(cli->inbuf,'\0',smb_size);
674
675                 cli_set_message(cli->outbuf,5, 0,True);
676
677                 SCVAL(cli->outbuf,smb_com,SMBwrite);
678                 SSVAL(cli->outbuf,smb_tid,cli->cnum);
679                 cli_setup_packet(cli);
680
681                 SSVAL(cli->outbuf,smb_vwv0,fnum);
682                 SSVAL(cli->outbuf,smb_vwv1,size);
683                 SIVAL(cli->outbuf,smb_vwv2,offset);
684                 SSVAL(cli->outbuf,smb_vwv4,0);
685
686                 p = smb_buf(cli->outbuf);
687                 *p++ = 1;
688                 SSVAL(p, 0, size); p += 2;
689                 memcpy(p, buf + total, size); p += size;
690
691                 cli_setup_bcc(cli, p);
692
693                 if (!cli_send_smb(cli))
694                         return -1;
695
696                 if (!cli_receive_smb(cli))
697                         return -1;
698
699                 if (cli_is_error(cli))
700                         return -1;
701
702                 size = SVAL(cli->inbuf,smb_vwv0);
703                 if (size == 0)
704                         break;
705
706                 size1 -= size;
707                 total += size;
708                 offset += size;
709
710         } while (size1);
711
712         return total;
713 }