]> arthur.barton.de Git - netatalk.git/blob - libatalk/dsi/dsi_stream.c
Merge branch 'sendfile' into develop
[netatalk.git] / libatalk / dsi / dsi_stream.c
1 /*
2  * Copyright (c) 1998 Adrian Sun (asun@zoology.washington.edu)
3  * Copyright (c) 2010,2011,2012 Frank Lahm <franklahm@googlemail.com>
4  * All rights reserved. See COPYRIGHT.
5  *
6  * this file provides the following functions:
7  * dsi_stream_write:    just write a bunch of bytes.
8  * dsi_stream_read:     just read a bunch of bytes.
9  * dsi_stream_send:     send a DSI header + data.
10  * dsi_stream_receive:  read a DSI header + data.
11  */
12
13 #ifdef HAVE_CONFIG_H
14 #include "config.h"
15 #endif /* HAVE_CONFIG_H */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <sys/uio.h>
25
26 #ifdef HAVE_SENDFILEV
27 #include <sys/sendfile.h>
28 #endif
29
30 #include <atalk/logger.h>
31 #include <atalk/dsi.h>
32 #include <atalk/util.h>
33
34 #ifndef MSG_MORE
35 #define MSG_MORE 0x8000
36 #endif
37
38 #ifndef MSG_DONTWAIT
39 #define MSG_DONTWAIT 0x40
40 #endif
41
42 /* Pack a DSI header in wire format */
43 static void dsi_header_pack_reply(const DSI *dsi, char *buf)
44 {
45     buf[0] = dsi->header.dsi_flags;
46     buf[1] = dsi->header.dsi_command;
47     memcpy(buf + 2, &dsi->header.dsi_requestID, sizeof(dsi->header.dsi_requestID));           
48     memcpy(buf + 4, &dsi->header.dsi_code, sizeof(dsi->header.dsi_code));
49     memcpy(buf + 8, &dsi->header.dsi_len, sizeof(dsi->header.dsi_len));
50     memcpy(buf + 12, &dsi->header.dsi_reserved, sizeof(dsi->header.dsi_reserved));
51 }
52
53 /*
54  * afpd is sleeping too much while trying to send something.
55  * May be there's no reader or the reader is also sleeping in write,
56  * look if there's some data for us to read, hopefully it will wake up
57  * the reader so we can write again.
58  *
59  * @returns 0 when is possible to send again, -1 on error
60  */
61 static int dsi_peek(DSI *dsi)
62 {
63     static int warned = 0;
64     fd_set readfds, writefds;
65     int    len;
66     int    maxfd;
67     int    ret;
68
69     LOG(log_debug, logtype_dsi, "dsi_peek");
70
71     maxfd = dsi->socket + 1;
72
73     while (1) {
74         if (dsi->socket == -1)
75             /* eg dsi_disconnect() might have disconnected us */
76             return -1;
77         FD_ZERO(&readfds);
78         FD_ZERO(&writefds);
79
80         if (dsi->eof < dsi->end) {
81             /* space in read buffer */
82             FD_SET( dsi->socket, &readfds);
83         } else {
84             if (!warned) {
85                 warned = 1;
86                 LOG(log_note, logtype_dsi, "dsi_peek: readahead buffer is full, possibly increase -dsireadbuf option");
87                 LOG(log_note, logtype_dsi, "dsi_peek: dsireadbuf: %d, DSI quantum: %d, effective buffer size: %d",
88                     dsi->dsireadbuf,
89                     dsi->server_quantum ? dsi->server_quantum : DSI_SERVQUANT_DEF,
90                     dsi->end - dsi->buffer);
91             }
92         }
93
94         FD_SET( dsi->socket, &writefds);
95
96         /* No timeout: if there's nothing to read nor nothing to write,
97          * we've got nothing to do at all */
98         if ((ret = select( maxfd, &readfds, &writefds, NULL, NULL)) <= 0) {
99             if (ret == -1 && errno == EINTR)
100                 /* we might have been interrupted by out timer, so restart select */
101                 continue;
102             /* give up */
103             LOG(log_error, logtype_dsi, "dsi_peek: unexpected select return: %d %s",
104                 ret, ret < 0 ? strerror(errno) : "");
105             return -1;
106         }
107
108         if (FD_ISSET(dsi->socket, &writefds)) {
109             /* we can write again */
110             LOG(log_debug, logtype_dsi, "dsi_peek: can write again");
111             break;
112         }
113
114         /* Check if there's sth to read, hopefully reading that will unblock the client */
115         if (FD_ISSET(dsi->socket, &readfds)) {
116             len = dsi->end - dsi->eof; /* it's ensured above that there's space */
117
118             if ((len = read(dsi->socket, dsi->eof, len)) <= 0) {
119                 if (len == 0) {
120                     LOG(log_error, logtype_dsi, "dsi_peek: EOF");
121                     return -1;
122                 }
123                 LOG(log_error, logtype_dsi, "dsi_peek: read: %s", strerror(errno));
124                 if (errno == EAGAIN)
125                     continue;
126                 return -1;
127             }
128             LOG(log_debug, logtype_dsi, "dsi_peek: read %d bytes", len);
129
130             dsi->eof += len;
131         }
132     }
133
134     return 0;
135 }
136
137 /* 
138  * Return all bytes up to count from dsi->buffer if there are any buffered there
139  */
140 static size_t from_buf(DSI *dsi, uint8_t *buf, size_t count)
141 {
142     size_t nbe = 0;
143
144     if (dsi->buffer == NULL)
145         /* afpd master has no DSI buffering */
146         return 0;
147
148     LOG(log_maxdebug, logtype_dsi, "from_buf: %u bytes", count);
149     
150     nbe = dsi->eof - dsi->start;
151
152     if (nbe > 0) {
153         nbe = MIN((size_t)nbe, count);
154         memcpy(buf, dsi->start, nbe);
155         dsi->start += nbe;
156
157         if (dsi->eof == dsi->start)
158             dsi->start = dsi->eof = dsi->buffer;
159     }
160
161     LOG(log_debug, logtype_dsi, "from_buf(read: %u, unread:%u , space left: %u): returning %u",
162         dsi->start - dsi->buffer, dsi->eof - dsi->start, dsi->end - dsi->eof, nbe);
163
164     return nbe;
165 }
166
167 /*
168  * Get bytes from buffer dsi->buffer or read from socket
169  *
170  * 1. Check if there are bytes in the the dsi->buffer buffer.
171  * 2. Return bytes from (1) if yes.
172  *    Note: this may return fewer bytes then requested in count !!
173  * 3. If the buffer was empty, read from the socket.
174  */
175 static ssize_t buf_read(DSI *dsi, uint8_t *buf, size_t count)
176 {
177     ssize_t len;
178
179     LOG(log_maxdebug, logtype_dsi, "buf_read(%u bytes)", count);
180
181     if (!count)
182         return 0;
183
184     len = from_buf(dsi, buf, count); /* 1. */
185     if (len)
186         return len;             /* 2. */
187   
188     len = readt(dsi->socket, buf, count, 0, 1); /* 3. */
189
190     LOG(log_maxdebug, logtype_dsi, "buf_read(%u bytes): got: %d", count, len);
191
192     return len;
193 }
194
195 /*
196  * Get "length" bytes from buffer and/or socket. In order to avoid frequent small reads
197  * this tries to read larger chunks (8192 bytes) into a buffer.
198  */
199 static size_t dsi_buffered_stream_read(DSI *dsi, uint8_t *data, const size_t length)
200 {
201   size_t len;
202   size_t buflen;
203
204   LOG(log_maxdebug, logtype_dsi, "dsi_buffered_stream_read: %u bytes", length);
205   
206   len = from_buf(dsi, data, length); /* read from buffer dsi->buffer */
207   dsi->read_count += len;
208   if (len == length) {          /* got enough bytes from there ? */
209       return len;               /* yes */
210   }
211
212   /* fill the buffer with 8192 bytes or until buffer is full */
213   buflen = MIN(8192, dsi->end - dsi->eof);
214   if (buflen > 0) {
215       ssize_t ret;
216       ret = read(dsi->socket, dsi->eof, buflen);
217       if (ret > 0)
218           dsi->eof += ret;
219   }
220
221   /* now get the remaining data */
222   if ((buflen = dsi_stream_read(dsi, data + len, length - len)) != length - len)
223       return 0;
224   len += buflen;
225
226   return len;
227 }
228
229 /* ---------------------------------------
230 */
231 static void block_sig(DSI *dsi)
232 {
233   dsi->in_write++;
234 }
235
236 /* ---------------------------------------
237 */
238 static void unblock_sig(DSI *dsi)
239 {
240   dsi->in_write--;
241 }
242
243 /*********************************************************************************
244  * Public functions
245  *********************************************************************************/
246
247 /*!
248  * Communication error with the client, enter disconnected state
249  *
250  * 1. close the socket
251  * 2. set the DSI_DISCONNECTED flag, remove possible sleep flags
252  *
253  * @returns  0 if successfully entered disconnected state
254  *          -1 if ppid is 1 which means afpd master died
255  *             or euid == 0 ie where still running as root (unauthenticated session)
256  */
257 int dsi_disconnect(DSI *dsi)
258 {
259     LOG(log_note, logtype_dsi, "dsi_disconnect: entering disconnected state");
260     dsi->proto_close(dsi);          /* 1 */
261     dsi->flags &= ~(DSI_SLEEPING | DSI_EXTSLEEP); /* 2 */
262     dsi->flags |= DSI_DISCONNECTED;
263     if (geteuid() == 0)
264         return -1;
265     return 0;
266 }
267
268 /* ------------------------------
269  * write raw data. return actual bytes read. checks against EINTR
270  * aren't necessary if all of the signals have SA_RESTART
271  * specified. */
272 ssize_t dsi_stream_write(DSI *dsi, void *data, const size_t length, int mode)
273 {
274   size_t written;
275   ssize_t len;
276   unsigned int flags;
277
278   dsi->in_write++;
279   written = 0;
280
281   LOG(log_maxdebug, logtype_dsi, "dsi_stream_write(send: %zd bytes): START", length);
282
283   if (dsi->flags & DSI_DISCONNECTED)
284       return -1;
285
286   if (mode & DSI_MSG_MORE)
287       flags = MSG_MORE;
288   else
289       flags = 0;
290
291   while (written < length) {
292       len = send(dsi->socket, (uint8_t *) data + written, length - written, flags);
293       if (len >= 0) {
294           written += len;
295           continue;
296       }
297
298       if (errno == EINTR)
299           continue;
300
301       if (errno == EAGAIN || errno == EWOULDBLOCK) {
302           LOG(log_debug, logtype_dsi, "dsi_stream_write: send: %s", strerror(errno));
303
304           if (mode == DSI_NOWAIT && written == 0) {
305               /* DSI_NOWAIT is used by attention give up in this case. */
306               written = -1;
307               goto exit;
308           }
309
310           /* Try to read sth. in order to break up possible deadlock */
311           if (dsi_peek(dsi) != 0) {
312               written = -1;
313               goto exit;
314           }
315           /* Now try writing again */
316           continue;
317       }
318
319       LOG(log_error, logtype_dsi, "dsi_stream_write: %s", strerror(errno));
320       written = -1;
321       goto exit;
322   }
323
324   dsi->write_count += written;
325   LOG(log_maxdebug, logtype_dsi, "dsi_stream_write(send: %zd bytes): END", length);
326
327 exit:
328   dsi->in_write--;
329   return written;
330 }
331
332 /* ---------------------------------
333 */
334 #ifdef WITH_SENDFILE
335 ssize_t dsi_stream_read_file(DSI *dsi, const int fromfd, off_t offset, const size_t length, const int err)
336 {
337     int ret = 0;
338     size_t written = 0;
339     size_t total = length;
340     ssize_t len;
341     off_t pos = offset;
342     char block[DSI_BLOCKSIZ];
343 #ifdef HAVE_SENDFILEV
344     int sfvcnt;
345     struct sendfilevec vec[2];
346     ssize_t nwritten;
347 #endif
348
349     LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file(off: %jd, len: %zu)", (intmax_t)offset, length);
350
351     if (dsi->flags & DSI_DISCONNECTED)
352         return -1;
353
354     dsi->in_write++;
355
356     dsi->flags |= DSI_NOREPLY;
357     dsi->header.dsi_flags = DSIFL_REPLY;
358     dsi->header.dsi_len = htonl(length);
359     dsi->header.dsi_code = htonl(err);
360     dsi_header_pack_reply(dsi, block);
361
362 #ifdef HAVE_SENDFILEV
363     total += DSI_BLOCKSIZ;
364     sfvcnt = 2;
365     vec[0].sfv_fd = SFV_FD_SELF;
366     vec[0].sfv_flag = 0;
367     vec[0].sfv_off = block;
368     vec[0].sfv_len = DSI_BLOCKSIZ;
369     vec[1].sfv_fd = fromfd;
370     vec[1].sfv_flag = 0;
371     vec[1].sfv_off = offset;
372     vec[1].sfv_len = length;
373 #else
374     dsi_stream_write(dsi, block, sizeof(block), DSI_MSG_MORE);
375 #endif
376
377     while (written < total) {
378 #ifdef HAVE_SENDFILEV
379         nwritten = 0;
380         len = sendfilev(dsi->socket, vec, sfvcnt, &nwritten);
381 #else
382         len = sys_sendfile(dsi->socket, fromfd, &pos, total - written);
383 #endif
384         if (len < 0) {
385             switch (errno) {
386             case EINTR:
387             case EAGAIN:
388                 len = 0;
389 #ifdef HAVE_SENDFILEV
390                 len = (size_t)nwritten;
391 #else
392 #if defined(SOLARIS) || defined(FREEBSD)
393                 if (pos > offset) {
394                     /* we actually have sent sth., adjust counters and keep trying */
395                     len = pos - offset;
396                     offset = pos;
397                 }
398 #endif /* defined(SOLARIS) || defined(FREEBSD) */
399 #endif /* HAVE_SENDFILEV */
400
401                 if (dsi_peek(dsi)) {
402                     ret = -1;
403                     goto exit;
404                 }
405                 break;
406             default:
407                 LOG(log_error, logtype_dsi, "dsi_stream_read_file: %s", strerror(errno));
408                 ret = -1;
409                 goto exit;
410             }
411         } else if (len == 0) {
412             /* afpd is going to exit */
413             ret = -1;
414             goto exit;
415         }
416 #ifdef HAVE_SENDFILEV
417         if (sfvcnt == 2 && len >= vec[0].sfv_len) {
418             vec[1].sfv_off += len - vec[0].sfv_len;
419             vec[1].sfv_len -= len - vec[0].sfv_len;
420
421             vec[0] = vec[1];
422             sfvcnt = 1;
423         } else {
424             vec[0].sfv_off += len;
425             vec[0].sfv_len -= len;
426         }
427 #endif  /* HAVE_SENDFILEV */
428         LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file: wrote: %zd", len);
429         written += len;
430     }
431 #ifdef HAVE_SENDFILEV
432     written -= DSI_BLOCKSIZ;
433 #endif
434     dsi->write_count += written;
435
436 exit:
437     dsi->in_write--;
438     LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file: written: %zd", written);
439     if (ret != 0)
440         return -1;
441     return written;
442 }
443 #endif
444
445
446 /*
447  * Essentially a loop around buf_read() to ensure "length" bytes are read
448  * from dsi->buffer and/or the socket.
449  *
450  * @returns length on success, some value smaller then length indicates an error
451  */
452 size_t dsi_stream_read(DSI *dsi, void *data, const size_t length)
453 {
454   size_t stored;
455   ssize_t len;
456
457   if (dsi->flags & DSI_DISCONNECTED)
458       return 0;
459
460   LOG(log_maxdebug, logtype_dsi, "dsi_stream_read(%u bytes)", length);
461
462   stored = 0;
463   while (stored < length) {
464       len = buf_read(dsi, (uint8_t *) data + stored, length - stored);
465       if (len == -1 && (errno == EINTR || errno == EAGAIN)) {
466           LOG(log_maxdebug, logtype_dsi, "dsi_stream_read: select read loop");
467           continue;
468       } else if (len > 0) {
469           stored += len;
470       } else { /* eof or error */
471           /* don't log EOF error if it's just after connect (OSX 10.3 probe) */
472 #if 0
473           if (errno == ECONNRESET)
474               dsi->flags |= DSI_GOT_ECONNRESET;
475 #endif
476           if (len || stored || dsi->read_count) {
477               if (! (dsi->flags & DSI_DISCONNECTED)) {
478                   LOG(log_error, logtype_dsi, "dsi_stream_read: len:%d, %s",
479                       len, (len < 0) ? strerror(errno) : "unexpected EOF");
480               }
481               return 0;
482           }
483           break;
484       }
485   }
486
487   dsi->read_count += stored;
488
489   LOG(log_maxdebug, logtype_dsi, "dsi_stream_read(%u bytes): got: %u", length, stored);
490   return stored;
491 }
492
493 /* ---------------------------------------
494  * write data. 0 on failure. this assumes that dsi_len will never
495  * cause an overflow in the data buffer. 
496  */
497 int dsi_stream_send(DSI *dsi, void *buf, size_t length)
498 {
499   char block[DSI_BLOCKSIZ];
500   struct iovec iov[2];
501   size_t towrite;
502   ssize_t len;
503
504   LOG(log_maxdebug, logtype_dsi, "dsi_stream_send(%u bytes): START", length);
505
506   if (dsi->flags & DSI_DISCONNECTED)
507       return 0;
508
509   dsi_header_pack_reply(dsi, block);
510
511   if (!length) { /* just write the header */
512       LOG(log_maxdebug, logtype_dsi, "dsi_stream_send(%u bytes): DSI header, no data", sizeof(block));
513     length = (dsi_stream_write(dsi, block, sizeof(block), 0) == sizeof(block));
514     return length; /* really 0 on failure, 1 on success */
515   }
516   
517   /* block signals */
518   block_sig(dsi);
519   iov[0].iov_base = block;
520   iov[0].iov_len = sizeof(block);
521   iov[1].iov_base = buf;
522   iov[1].iov_len = length;
523   
524   towrite = sizeof(block) + length;
525   dsi->write_count += towrite;
526   while (towrite > 0) {
527       if (((len = writev(dsi->socket, iov, 2)) == -1 && errno == EINTR) || (len == 0))
528           continue;
529     
530       if ((size_t)len == towrite) /* wrote everything out */
531           break;
532       else if (len < 0) { /* error */
533           if (errno == EAGAIN || errno == EWOULDBLOCK) {
534               if (!dsi_peek(dsi)) {
535                   continue;
536               }
537           }
538           LOG(log_error, logtype_dsi, "dsi_stream_send: %s", strerror(errno));
539           unblock_sig(dsi);
540           return 0;
541       }
542     
543       towrite -= len;
544       if (towrite > length) { /* skip part of header */
545           iov[0].iov_base = (char *) iov[0].iov_base + len;
546           iov[0].iov_len -= len;
547       } else { /* skip to data */
548           if (iov[0].iov_len) {
549               len -= iov[0].iov_len;
550               iov[0].iov_len = 0;
551           }
552           iov[1].iov_base = (char *) iov[1].iov_base + len;
553           iov[1].iov_len -= len;
554       }
555   }
556
557   LOG(log_maxdebug, logtype_dsi, "dsi_stream_send(%u bytes): END", length);
558   
559   unblock_sig(dsi);
560   return 1;
561 }
562
563
564 /*!
565  * Read DSI command and data
566  *
567  * @param  dsi   (rw) DSI handle
568  *
569  * @return    DSI function on success, 0 on failure
570  */
571 int dsi_stream_receive(DSI *dsi)
572 {
573   char block[DSI_BLOCKSIZ];
574
575   LOG(log_maxdebug, logtype_dsi, "dsi_stream_receive: START");
576
577   if (dsi->flags & DSI_DISCONNECTED)
578       return 0;
579
580   /* read in the header */
581   if (dsi_buffered_stream_read(dsi, (uint8_t *)block, sizeof(block)) != sizeof(block)) 
582     return 0;
583
584   dsi->header.dsi_flags = block[0];
585   dsi->header.dsi_command = block[1];
586
587   if (dsi->header.dsi_command == 0)
588       return 0;
589
590   memcpy(&dsi->header.dsi_requestID, block + 2, sizeof(dsi->header.dsi_requestID));
591   memcpy(&dsi->header.dsi_code, block + 4, sizeof(dsi->header.dsi_code));
592   memcpy(&dsi->header.dsi_len, block + 8, sizeof(dsi->header.dsi_len));
593   memcpy(&dsi->header.dsi_reserved, block + 12, sizeof(dsi->header.dsi_reserved));
594   dsi->clientID = ntohs(dsi->header.dsi_requestID);
595   
596   /* make sure we don't over-write our buffers. */
597   dsi->cmdlen = MIN(ntohl(dsi->header.dsi_len), DSI_CMDSIZ);
598   if (dsi_stream_read(dsi, dsi->commands, dsi->cmdlen) != dsi->cmdlen) 
599     return 0;
600
601   LOG(log_debug, logtype_dsi, "dsi_stream_receive: DSI cmdlen: %zd", dsi->cmdlen);
602
603   return block[1];
604 }