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