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