]> arthur.barton.de Git - netatalk.git/blob - libatalk/dsi/dsi_stream.c
154297748fbd235ce5ffb325d4f7e356d4c67156
[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     /* Cast to unsigned long to prevent sign extension of the
368      * pointer value for the LFS case; see Apache PR 39463. */
369     vec[0].sfv_off = (unsigned long)block;
370     vec[0].sfv_len = DSI_BLOCKSIZ;
371     vec[1].sfv_fd = fromfd;
372     vec[1].sfv_flag = 0;
373     vec[1].sfv_off = offset;
374     vec[1].sfv_len = length;
375 #else
376     dsi_stream_write(dsi, block, sizeof(block), DSI_MSG_MORE);
377 #endif
378
379     while (written < total) {
380 #ifdef HAVE_SENDFILEV
381         nwritten = 0;
382         len = sendfilev(dsi->socket, vec, sfvcnt, &nwritten);
383 #else
384         len = sys_sendfile(dsi->socket, fromfd, &pos, total - written);
385 #endif
386         if (len < 0) {
387             switch (errno) {
388             case EINTR:
389             case EAGAIN:
390                 len = 0;
391 #ifdef HAVE_SENDFILEV
392                 len = (size_t)nwritten;
393 #else
394 #if defined(SOLARIS) || defined(FREEBSD)
395                 if (pos > offset) {
396                     /* we actually have sent sth., adjust counters and keep trying */
397                     len = pos - offset;
398                     offset = pos;
399                 }
400 #endif /* defined(SOLARIS) || defined(FREEBSD) */
401 #endif /* HAVE_SENDFILEV */
402
403                 if (dsi_peek(dsi) != 0) {
404                     ret = -1;
405                     goto exit;
406                 }
407                 break;
408             default:
409                 LOG(log_error, logtype_dsi, "dsi_stream_read_file: %s", strerror(errno));
410                 ret = -1;
411                 goto exit;
412             }
413         } else if (len == 0) {
414             /* afpd is going to exit */
415             ret = -1;
416             goto exit;
417         }
418 #ifdef HAVE_SENDFILEV
419         if (sfvcnt == 2 && len >= vec[0].sfv_len) {
420             vec[1].sfv_off += len - vec[0].sfv_len;
421             vec[1].sfv_len -= len - vec[0].sfv_len;
422
423             vec[0] = vec[1];
424             sfvcnt = 1;
425         } else {
426             vec[0].sfv_off += len;
427             vec[0].sfv_len -= len;
428         }
429 #endif  /* HAVE_SENDFILEV */
430         LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file: wrote: %zd", len);
431         written += len;
432     }
433 #ifdef HAVE_SENDFILEV
434     written -= DSI_BLOCKSIZ;
435 #endif
436     dsi->write_count += written;
437
438 exit:
439     dsi->in_write--;
440     LOG(log_maxdebug, logtype_dsi, "dsi_stream_read_file: written: %zd", written);
441     if (ret != 0)
442         return -1;
443     return written;
444 }
445 #endif
446
447
448 /*
449  * Essentially a loop around buf_read() to ensure "length" bytes are read
450  * from dsi->buffer and/or the socket.
451  *
452  * @returns length on success, some value smaller then length indicates an error
453  */
454 size_t dsi_stream_read(DSI *dsi, void *data, const size_t length)
455 {
456   size_t stored;
457   ssize_t len;
458
459   if (dsi->flags & DSI_DISCONNECTED)
460       return 0;
461
462   LOG(log_maxdebug, logtype_dsi, "dsi_stream_read(%u bytes)", length);
463
464   stored = 0;
465   while (stored < length) {
466       len = buf_read(dsi, (uint8_t *) data + stored, length - stored);
467       if (len == -1 && (errno == EINTR || errno == EAGAIN)) {
468           LOG(log_maxdebug, logtype_dsi, "dsi_stream_read: select read loop");
469           continue;
470       } else if (len > 0) {
471           stored += len;
472       } else { /* eof or error */
473           /* don't log EOF error if it's just after connect (OSX 10.3 probe) */
474 #if 0
475           if (errno == ECONNRESET)
476               dsi->flags |= DSI_GOT_ECONNRESET;
477 #endif
478           if (len || stored || dsi->read_count) {
479               if (! (dsi->flags & DSI_DISCONNECTED)) {
480                   LOG(log_error, logtype_dsi, "dsi_stream_read: len:%d, %s",
481                       len, (len < 0) ? strerror(errno) : "unexpected EOF");
482               }
483               return 0;
484           }
485           break;
486       }
487   }
488
489   dsi->read_count += stored;
490
491   LOG(log_maxdebug, logtype_dsi, "dsi_stream_read(%u bytes): got: %u", length, stored);
492   return stored;
493 }
494
495 /* ---------------------------------------
496  * write data. 0 on failure. this assumes that dsi_len will never
497  * cause an overflow in the data buffer. 
498  */
499 int dsi_stream_send(DSI *dsi, void *buf, size_t length)
500 {
501   char block[DSI_BLOCKSIZ];
502   struct iovec iov[2];
503   size_t towrite;
504   ssize_t len;
505
506   LOG(log_maxdebug, logtype_dsi, "dsi_stream_send(%u bytes): START", length);
507
508   if (dsi->flags & DSI_DISCONNECTED)
509       return 0;
510
511   dsi_header_pack_reply(dsi, block);
512
513   if (!length) { /* just write the header */
514       LOG(log_maxdebug, logtype_dsi, "dsi_stream_send(%u bytes): DSI header, no data", sizeof(block));
515     length = (dsi_stream_write(dsi, block, sizeof(block), 0) == sizeof(block));
516     return length; /* really 0 on failure, 1 on success */
517   }
518   
519   /* block signals */
520   block_sig(dsi);
521   iov[0].iov_base = block;
522   iov[0].iov_len = sizeof(block);
523   iov[1].iov_base = buf;
524   iov[1].iov_len = length;
525   
526   towrite = sizeof(block) + length;
527   dsi->write_count += towrite;
528   while (towrite > 0) {
529       if (((len = writev(dsi->socket, iov, 2)) == -1 && errno == EINTR) || (len == 0))
530           continue;
531     
532       if ((size_t)len == towrite) /* wrote everything out */
533           break;
534       else if (len < 0) { /* error */
535           if (errno == EAGAIN || errno == EWOULDBLOCK) {
536               if (dsi_peek(dsi) == 0) {
537                   continue;
538               }
539           }
540           LOG(log_error, logtype_dsi, "dsi_stream_send: %s", strerror(errno));
541           unblock_sig(dsi);
542           return 0;
543       }
544     
545       towrite -= len;
546       if (towrite > length) { /* skip part of header */
547           iov[0].iov_base = (char *) iov[0].iov_base + len;
548           iov[0].iov_len -= len;
549       } else { /* skip to data */
550           if (iov[0].iov_len) {
551               len -= iov[0].iov_len;
552               iov[0].iov_len = 0;
553           }
554           iov[1].iov_base = (char *) iov[1].iov_base + len;
555           iov[1].iov_len -= len;
556       }
557   }
558
559   LOG(log_maxdebug, logtype_dsi, "dsi_stream_send(%u bytes): END", length);
560   
561   unblock_sig(dsi);
562   return 1;
563 }
564
565
566 /*!
567  * Read DSI command and data
568  *
569  * @param  dsi   (rw) DSI handle
570  *
571  * @return    DSI function on success, 0 on failure
572  */
573 int dsi_stream_receive(DSI *dsi)
574 {
575   char block[DSI_BLOCKSIZ];
576
577   LOG(log_maxdebug, logtype_dsi, "dsi_stream_receive: START");
578
579   if (dsi->flags & DSI_DISCONNECTED)
580       return 0;
581
582   /* read in the header */
583   if (dsi_buffered_stream_read(dsi, (uint8_t *)block, sizeof(block)) != sizeof(block)) 
584     return 0;
585
586   dsi->header.dsi_flags = block[0];
587   dsi->header.dsi_command = block[1];
588
589   if (dsi->header.dsi_command == 0)
590       return 0;
591
592   memcpy(&dsi->header.dsi_requestID, block + 2, sizeof(dsi->header.dsi_requestID));
593   memcpy(&dsi->header.dsi_code, block + 4, sizeof(dsi->header.dsi_code));
594   memcpy(&dsi->header.dsi_len, block + 8, sizeof(dsi->header.dsi_len));
595   memcpy(&dsi->header.dsi_reserved, block + 12, sizeof(dsi->header.dsi_reserved));
596   dsi->clientID = ntohs(dsi->header.dsi_requestID);
597   
598   /* make sure we don't over-write our buffers. */
599   dsi->cmdlen = MIN(ntohl(dsi->header.dsi_len), DSI_CMDSIZ);
600   if (dsi_stream_read(dsi, dsi->commands, dsi->cmdlen) != dsi->cmdlen) 
601     return 0;
602
603   LOG(log_debug, logtype_dsi, "dsi_stream_receive: DSI cmdlen: %zd", dsi->cmdlen);
604
605   return block[1];
606 }