Sync with FreeBSD. This adds read-only support for zip and ISO9660.
[dragonfly.git] / contrib / cvs-1.12.12 / src / buffer.c
1 /* Code for the buffer data structure.  */
2
3 #include "cvs.h"
4 #include "buffer.h"
5 #include "pagealign_alloc.h"
6
7 #if defined (SERVER_SUPPORT) || defined (CLIENT_SUPPORT)
8
9 # ifdef HAVE_WINSOCK_H
10 #   include <winsock.h>
11 # else
12 #  include <sys/socket.h>
13 # endif
14
15 /* OS/2 doesn't have EIO.  FIXME: this whole notion of turning
16    a different error into EIO strikes me as pretty dubious.  */
17 # if !defined( EIO )
18 #   define EIO EBADPOS
19 # endif
20
21 /* Local functions.  */
22 static void buf_default_memory_error (struct buffer *);
23 static struct buffer_data *get_buffer_data (void);
24
25
26
27 /* Initialize a buffer structure.  */
28 struct buffer *
29 buf_initialize (int (*input) (void *, char *, size_t, size_t, size_t *),
30                 int (*output) (void *, const char *, size_t, size_t *),
31                 int (*flush) (void *),
32                 int (*block) (void *, bool),
33                 int (*get_fd) (void *),
34                 int (*shutdown) (struct buffer *),
35                 void (*memory) (struct buffer *),
36                 void *closure)
37 {
38     struct buffer *buf;
39
40     buf = xmalloc (sizeof (struct buffer));
41     buf->data = NULL;
42     buf->last = NULL;
43     buf->nonblocking = false;
44     buf->input = input;
45     buf->output = output;
46     buf->flush = flush;
47     buf->block = block;
48     buf->get_fd = get_fd;
49     buf->shutdown = shutdown;
50     buf->memory_error = memory ? memory : buf_default_memory_error;
51     buf->closure = closure;
52     return buf;
53 }
54
55
56
57 /* Free a buffer structure.  */
58 void
59 buf_free (struct buffer *buf)
60 {
61     if (buf->closure != NULL)
62     {
63         free (buf->closure);
64         buf->closure = NULL;
65     }
66     buf_free_data (buf);
67     free (buf);
68 }
69
70
71
72 /* Initialize a buffer structure which is not to be used for I/O.  */
73 struct buffer *
74 buf_nonio_initialize( void (*memory) (struct buffer *) )
75 {
76     return buf_initialize (NULL, NULL, NULL, NULL, NULL, NULL, memory, NULL);
77 }
78
79
80
81 /* Default memory error handler.  */
82 static void
83 buf_default_memory_error (struct buffer *buf)
84 {
85     error (1, 0, "out of memory");
86 }
87
88
89
90 /* Allocate more buffer_data structures.  */
91 /* Get a new buffer_data structure.  */
92 static struct buffer_data *
93 get_buffer_data (void)
94 {
95     struct buffer_data *ret;
96
97     ret = xmalloc (sizeof (struct buffer_data));
98     ret->text = pagealign_xalloc (BUFFER_DATA_SIZE);
99
100     return ret;
101 }
102
103
104
105 /* See whether a buffer and its file descriptor is empty.  */
106 int
107 buf_empty (buf)
108     struct buffer *buf;
109 {
110         /* Try and read any data on the file descriptor first.
111          * We already know the descriptor is non-blocking.
112          */
113         buf_input_data (buf, NULL);
114         return buf_empty_p (buf);
115 }
116
117
118
119 /* See whether a buffer is empty.  */
120 int
121 buf_empty_p (struct buffer *buf)
122 {
123     struct buffer_data *data;
124
125     for (data = buf->data; data != NULL; data = data->next)
126         if (data->size > 0)
127             return 0;
128     return 1;
129 }
130
131
132
133 # if defined (SERVER_FLOWCONTROL) || defined (PROXY_SUPPORT)
134 /*
135  * Count how much data is stored in the buffer..
136  * Note that each buffer is a xmalloc'ed chunk BUFFER_DATA_SIZE.
137  */
138 int
139 buf_count_mem (struct buffer *buf)
140 {
141     struct buffer_data *data;
142     int mem = 0;
143
144     for (data = buf->data; data != NULL; data = data->next)
145         mem += BUFFER_DATA_SIZE;
146
147     return mem;
148 }
149 # endif /* SERVER_FLOWCONTROL || PROXY_SUPPORT */
150
151
152
153 /* Add data DATA of length LEN to BUF.  */
154 void
155 buf_output (struct buffer *buf, const char *data, size_t len)
156 {
157     if (buf->data != NULL
158         && (((buf->last->text + BUFFER_DATA_SIZE)
159              - (buf->last->bufp + buf->last->size))
160             >= len))
161     {
162         memcpy (buf->last->bufp + buf->last->size, data, len);
163         buf->last->size += len;
164         return;
165     }
166
167     while (1)
168     {
169         struct buffer_data *newdata;
170
171         newdata = get_buffer_data ();
172         if (newdata == NULL)
173         {
174             (*buf->memory_error) (buf);
175             return;
176         }
177
178         if (buf->data == NULL)
179             buf->data = newdata;
180         else
181             buf->last->next = newdata;
182         newdata->next = NULL;
183         buf->last = newdata;
184
185         newdata->bufp = newdata->text;
186
187         if (len <= BUFFER_DATA_SIZE)
188         {
189             newdata->size = len;
190             memcpy (newdata->text, data, len);
191             return;
192         }
193
194         newdata->size = BUFFER_DATA_SIZE;
195         memcpy (newdata->text, data, BUFFER_DATA_SIZE);
196
197         data += BUFFER_DATA_SIZE;
198         len -= BUFFER_DATA_SIZE;
199     }
200
201     /*NOTREACHED*/
202 }
203
204
205
206 /* Add a '\0' terminated string to BUF.  */
207 void
208 buf_output0 (struct buffer *buf, const char *string)
209 {
210     buf_output (buf, string, strlen (string));
211 }
212
213
214
215 /* Add a single character to BUF.  */
216 void
217 buf_append_char (struct buffer *buf, int ch)
218 {
219     if (buf->data != NULL
220         && (buf->last->text + BUFFER_DATA_SIZE
221             != buf->last->bufp + buf->last->size))
222     {
223         *(buf->last->bufp + buf->last->size) = ch;
224         ++buf->last->size;
225     }
226     else
227     {
228         char b;
229
230         b = ch;
231         buf_output (buf, &b, 1);
232     }
233 }
234
235
236
237 /* Free struct buffer_data's from the list starting with FIRST and ending at
238  * LAST, inclusive.
239  */
240 static inline void
241 buf_free_datas (struct buffer_data *first, struct buffer_data *last)
242 {
243     struct buffer_data *b, *n, *p;
244     b = first;
245     do
246     {
247         p = b;
248         n = b->next;
249         pagealign_free (b->text);
250         free (b);
251         b = n;
252     } while (p != last);
253 }
254
255
256
257 /*
258  * Send all the output we've been saving up.  Returns 0 for success or
259  * errno code.  If the buffer has been set to be nonblocking, this
260  * will just write until the write would block.
261  */
262 int
263 buf_send_output (struct buffer *buf)
264 {
265     assert (buf->output != NULL);
266
267     while (buf->data != NULL)
268     {
269         struct buffer_data *data;
270
271         data = buf->data;
272
273         if (data->size > 0)
274         {
275             int status;
276             size_t nbytes;
277
278             status = (*buf->output) (buf->closure, data->bufp, data->size,
279                                      &nbytes);
280             if (status != 0)
281             {
282                 /* Some sort of error.  Discard the data, and return.  */
283                 buf_free_data (buf);
284                 return status;
285             }
286
287             if (nbytes != data->size)
288             {
289                 /* Not all the data was written out.  This is only
290                    permitted in nonblocking mode.  Adjust the buffer,
291                    and return.  */
292
293                 assert (buf->nonblocking);
294
295                 data->size -= nbytes;
296                 data->bufp += nbytes;
297
298                 return 0;
299             }
300         }
301
302         buf->data = data->next;
303         buf_free_datas (data, data);
304     }
305
306     buf->last = NULL;
307
308     return 0;
309 }
310
311
312
313 /*
314  * Flush any data queued up in the buffer.  If BLOCK is nonzero, then
315  * if the buffer is in nonblocking mode, put it into blocking mode for
316  * the duration of the flush.  This returns 0 on success, or an error
317  * code.
318  */
319 int
320 buf_flush (struct buffer *buf, bool block)
321 {
322     int nonblocking;
323     int status;
324
325     assert (buf->flush != NULL);
326
327     nonblocking = buf->nonblocking;
328     if (nonblocking && block)
329     {
330         status = set_block (buf);
331         if (status != 0)
332             return status;
333     }
334
335     status = buf_send_output (buf);
336     if (status == 0)
337         status = (*buf->flush) (buf->closure);
338
339     if (nonblocking && block)
340     {
341         int blockstat;
342
343         blockstat = set_nonblock (buf);
344         if (status == 0)
345             status = blockstat;
346     }
347
348     return status;
349 }
350
351
352
353 /*
354  * Set buffer BUF to nonblocking I/O.  Returns 0 for success or errno
355  * code.
356  */
357 int
358 set_nonblock (struct buffer *buf)
359 {
360     int status;
361
362     if (buf->nonblocking)
363         return 0;
364     assert (buf->block != NULL);
365     status = (*buf->block) (buf->closure, 0);
366     if (status != 0)
367         return status;
368     buf->nonblocking = true;
369     return 0;
370 }
371
372
373
374 /*
375  * Set buffer BUF to blocking I/O.  Returns 0 for success or errno
376  * code.
377  */
378 int
379 set_block (struct buffer *buf)
380 {
381     int status;
382
383     if (! buf->nonblocking)
384         return 0;
385     assert (buf->block != NULL);
386     status = (*buf->block) (buf->closure, 1);
387     if (status != 0)
388         return status;
389     buf->nonblocking = false;
390     return 0;
391 }
392
393
394
395 /*
396  * Send a character count and some output.  Returns errno code or 0 for
397  * success.
398  *
399  * Sending the count in binary is OK since this is only used on a pipe
400  * within the same system.
401  */
402 int
403 buf_send_counted (struct buffer *buf)
404 {
405     int size;
406     struct buffer_data *data;
407
408     size = 0;
409     for (data = buf->data; data != NULL; data = data->next)
410         size += data->size;
411
412     data = get_buffer_data ();
413     if (data == NULL)
414     {
415         (*buf->memory_error) (buf);
416         return ENOMEM;
417     }
418
419     data->next = buf->data;
420     buf->data = data;
421     if (buf->last == NULL)
422         buf->last = data;
423
424     data->bufp = data->text;
425     data->size = sizeof (int);
426
427     *((int *) data->text) = size;
428
429     return buf_send_output (buf);
430 }
431
432
433
434 /*
435  * Send a special count.  COUNT should be negative.  It will be
436  * handled specially by buf_copy_counted.  This function returns 0 or
437  * an errno code.
438  *
439  * Sending the count in binary is OK since this is only used on a pipe
440  * within the same system.
441  */
442 int
443 buf_send_special_count (struct buffer *buf, int count)
444 {
445     struct buffer_data *data;
446
447     data = get_buffer_data ();
448     if (data == NULL)
449     {
450         (*buf->memory_error) (buf);
451         return ENOMEM;
452     }
453
454     data->next = buf->data;
455     buf->data = data;
456     if (buf->last == NULL)
457         buf->last = data;
458
459     data->bufp = data->text;
460     data->size = sizeof (int);
461
462     *((int *) data->text) = count;
463
464     return buf_send_output (buf);
465 }
466
467
468
469 /* Append a list of buffer_data structures to an buffer.  */
470 void
471 buf_append_data (struct buffer *buf, struct buffer_data *data,
472                  struct buffer_data *last)
473 {
474     if (data != NULL)
475     {
476         if (buf->data == NULL)
477             buf->data = data;
478         else
479             buf->last->next = data;
480         buf->last = last;
481     }
482 }
483
484
485
486 # ifdef PROXY_SUPPORT
487 /* Copy data structures and append them to a buffer.
488  *
489  * ERRORS
490  *   Failure to allocate memory here is fatal.
491  */
492 void
493 buf_copy_data (struct buffer *buf, struct buffer_data *data,
494                struct buffer_data *last)
495 {
496     struct buffer_data *first, *new, *cur, *prev;
497
498     assert (buf);
499     assert (data);
500
501     prev = first = NULL;
502     cur = data;
503     while (1)
504     {
505         new = get_buffer_data ();
506         if (!new) error (1, errno, "Failed to allocate buffer data.");
507
508         if (!first) first = new;
509         memcpy (new->text, cur->bufp, cur->size);
510         new->bufp = new->text;
511         new->size = cur->size;
512         new->next = NULL;
513         if (prev) prev->next = new;
514         if (cur == last) break;
515         prev = new;
516         cur = cur->next;
517     }
518
519     buf_append_data (buf, first, new);
520 }
521 # endif /* PROXY_SUPPORT */
522
523
524
525 /* Dispose of any remaining data in the buffer.  */
526 void
527 buf_free_data (struct buffer *buffer)
528 {
529     if (buf_empty_p (buffer)) return;
530     buf_free_datas (buffer->data, buffer->last);
531     buffer->data = buffer->last = NULL;
532 }
533
534
535
536 /* Append the data in one buffer to another.  This removes the data
537  * from the source buffer.
538  */
539 void
540 buf_append_buffer (struct buffer *to, struct buffer *from)
541 {
542     struct buffer_data *n;
543
544     /* Copy the data pointer to the new buf.  */
545     buf_append_data (to, from->data, from->last);
546
547     n = from->data;
548     while (n)
549     {
550         if (n == from->last) break;
551         n = n->next;
552     }
553
554     /* Remove from the original location.  */
555     from->data = NULL;
556     from->last = NULL;
557 }
558
559
560
561 /*
562  * Copy the contents of file F into buffer_data structures.  We can't
563  * copy directly into an buffer, because we want to handle failure and
564  * success differently.  Returns 0 on success, or -2 if out of
565  * memory, or a status code on error.  Since the caller happens to
566  * know the size of the file, it is passed in as SIZE.  On success,
567  * this function sets *RETP and *LASTP, which may be passed to
568  * buf_append_data.
569  */
570 int
571 buf_read_file (FILE *f, long int size, struct buffer_data **retp,
572                struct buffer_data **lastp)
573 {
574     int status;
575
576     *retp = NULL;
577     *lastp = NULL;
578
579     while (size > 0)
580     {
581         struct buffer_data *data;
582         int get;
583
584         data = get_buffer_data ();
585         if (data == NULL)
586         {
587             status = -2;
588             goto error_return;
589         }
590
591         if (*retp == NULL)
592             *retp = data;
593         else
594             (*lastp)->next = data;
595         data->next = NULL;
596         *lastp = data;
597
598         data->bufp = data->text;
599         data->size = 0;
600
601         if (size > BUFFER_DATA_SIZE)
602             get = BUFFER_DATA_SIZE;
603         else
604             get = size;
605
606         errno = EIO;
607         if (fread (data->text, get, 1, f) != 1)
608         {
609             status = errno;
610             goto error_return;
611         }
612
613         data->size += get;
614         size -= get;
615     }
616
617     return 0;
618
619   error_return:
620     if (*retp != NULL)
621         buf_free_datas (*retp, (*lastp)->next);
622     return status;
623 }
624
625
626
627 /*
628  * Copy the contents of file F into buffer_data structures.  We can't
629  * copy directly into an buffer, because we want to handle failure and
630  * success differently.  Returns 0 on success, or -2 if out of
631  * memory, or a status code on error.  On success, this function sets
632  * *RETP and *LASTP, which may be passed to buf_append_data.
633  */
634 int
635 buf_read_file_to_eof (FILE *f, struct buffer_data **retp,
636                       struct buffer_data **lastp)
637 {
638     int status;
639
640     *retp = NULL;
641     *lastp = NULL;
642
643     while (!feof (f))
644     {
645         struct buffer_data *data;
646         int get, nread;
647
648         data = get_buffer_data ();
649         if (data == NULL)
650         {
651             status = -2;
652             goto error_return;
653         }
654
655         if (*retp == NULL)
656             *retp = data;
657         else
658             (*lastp)->next = data;
659         data->next = NULL;
660         *lastp = data;
661
662         data->bufp = data->text;
663         data->size = 0;
664
665         get = BUFFER_DATA_SIZE;
666
667         errno = EIO;
668         nread = fread (data->text, 1, get, f);
669         if (nread == 0 && !feof (f))
670         {
671             status = errno;
672             goto error_return;
673         }
674
675         data->size = nread;
676     }
677
678     return 0;
679
680   error_return:
681     if (*retp != NULL)
682         buf_free_datas (*retp, (*lastp)->next);
683     return status;
684 }
685
686
687
688 /* Return the number of bytes in a chain of buffer_data structures.  */
689 int
690 buf_chain_length (struct buffer_data *buf)
691 {
692     int size = 0;
693     while (buf)
694     {
695         size += buf->size;
696         buf = buf->next;
697     }
698     return size;
699 }
700
701
702
703 /* Return the number of bytes in a buffer.  */
704 int
705 buf_length (struct buffer *buf)
706 {
707     return buf_chain_length (buf->data);
708 }
709
710
711
712 /*
713  * Read an arbitrary amount of data into an input buffer.  The buffer
714  * will be in nonblocking mode, and we just grab what we can.  Return
715  * 0 on success, or -1 on end of file, or -2 if out of memory, or an
716  * error code.  If COUNTP is not NULL, *COUNTP is set to the number of
717  * bytes read.
718  */
719 int
720 buf_input_data (struct buffer *buf, size_t *countp)
721 {
722     assert (buf->input != NULL);
723
724     if (countp != NULL)
725         *countp = 0;
726
727     while (1)
728     {
729         int status;
730         size_t get, nbytes;
731
732         if (buf->data == NULL
733             || (buf->last->bufp + buf->last->size
734                 == buf->last->text + BUFFER_DATA_SIZE))
735         {
736             struct buffer_data *data;
737
738             data = get_buffer_data ();
739             if (data == NULL)
740             {
741                 (*buf->memory_error) (buf);
742                 return -2;
743             }
744
745             if (buf->data == NULL)
746                 buf->data = data;
747             else
748                 buf->last->next = data;
749             data->next = NULL;
750             buf->last = data;
751
752             data->bufp = data->text;
753             data->size = 0;
754         }
755
756         get = ((buf->last->text + BUFFER_DATA_SIZE)
757                - (buf->last->bufp + buf->last->size));
758
759         status = (*buf->input) (buf->closure,
760                                 buf->last->bufp + buf->last->size,
761                                 0, get, &nbytes);
762         if (status != 0)
763             return status;
764
765         buf->last->size += nbytes;
766         if (countp != NULL)
767             *countp += nbytes;
768
769         if (nbytes < get)
770         {
771             /* If we did not fill the buffer, then presumably we read
772                all the available data.  */
773             return 0;
774         }
775     }
776
777     /*NOTREACHED*/
778 }
779
780
781
782 /*
783  * Read a line (characters up to a \012) from an input buffer.  (We
784  * use \012 rather than \n for the benefit of non Unix clients for
785  * which \n means something else).  This returns 0 on success, or -1
786  * on end of file, or -2 if out of memory, or an error code.  If it
787  * succeeds, it sets *LINE to an allocated buffer holding the contents
788  * of the line.  The trailing \012 is not included in the buffer.  If
789  * LENP is not NULL, then *LENP is set to the number of bytes read;
790  * strlen may not work, because there may be embedded null bytes.
791  */
792 int
793 buf_read_line (struct buffer *buf, char **line, size_t *lenp)
794 {
795     return buf_read_short_line (buf, line, lenp, SIZE_MAX);
796 }
797
798
799
800 /* Like buf_read_line, but return -2 if no newline is found in MAX characters.
801  */
802 int
803 buf_read_short_line (struct buffer *buf, char **line, size_t *lenp,
804                      size_t max)
805 {
806     assert (buf->input != NULL);
807
808     *line = NULL;
809
810     while (1)
811     {
812         size_t len, finallen, predicted_len;
813         struct buffer_data *data;
814         char *nl;
815
816         /* See if there is a newline in BUF.  */
817         len = 0;
818         for (data = buf->data; data != NULL; data = data->next)
819         {
820             nl = memchr (data->bufp, '\012', data->size);
821             if (nl != NULL)
822             {
823                 finallen = nl - data->bufp;
824                 if (xsum (len, finallen) >= max) return -2;
825                 len += finallen;
826                 break;
827             }
828             else if (xsum (len, data->size) >= max) return -2;
829             len += data->size;
830         }
831
832         /* If we found a newline, copy the line into a memory buffer,
833            and remove it from BUF.  */
834         if (data != NULL)
835         {
836             char *p;
837             struct buffer_data *nldata;
838
839             p = xmalloc (len + 1);
840             if (p == NULL)
841                 return -2;
842             *line = p;
843
844             nldata = data;
845             data = buf->data;
846             while (data != nldata)
847             {
848                 struct buffer_data *next;
849
850                 memcpy (p, data->bufp, data->size);
851                 p += data->size;
852                 next = data->next;
853                 buf_free_datas (data, data);
854                 data = next;
855             }
856
857             memcpy (p, data->bufp, finallen);
858             p[finallen] = '\0';
859
860             data->size -= finallen + 1;
861             data->bufp = nl + 1;
862             buf->data = data;
863
864             if (lenp != NULL)
865                 *lenp = len;
866
867             return 0;
868         }
869
870         /* Read more data until we get a newline or MAX characters.  */
871         predicted_len = 0;
872         while (1)
873         {
874             int status;
875             size_t size, nbytes;
876             char *mem;
877
878             if (buf->data == NULL
879                 || (buf->last->bufp + buf->last->size
880                     == buf->last->text + BUFFER_DATA_SIZE))
881             {
882                 data = get_buffer_data ();
883                 if (data == NULL)
884                 {
885                     (*buf->memory_error) (buf);
886                     return -2;
887                 }
888
889                 if (buf->data == NULL)
890                     buf->data = data;
891                 else
892                     buf->last->next = data;
893                 data->next = NULL;
894                 buf->last = data;
895
896                 data->bufp = data->text;
897                 data->size = 0;
898             }
899
900             mem = buf->last->bufp + buf->last->size;
901             size = (buf->last->text + BUFFER_DATA_SIZE) - mem;
902
903             /* We need to read at least 1 byte.  We can handle up to
904                SIZE bytes.  This will only be efficient if the
905                underlying communication stream does its own buffering,
906                or is clever about getting more than 1 byte at a time.  */
907             status = (*buf->input) (buf->closure, mem, 1, size, &nbytes);
908             if (status != 0)
909                 return status;
910
911             predicted_len += nbytes;
912             buf->last->size += nbytes;
913
914             /* Optimize slightly to avoid an unnecessary call to memchr.  */
915             if (nbytes == 1)
916             {
917                 if (*mem == '\012')
918                     break;
919             }
920             else
921             {
922                 if (memchr (mem, '\012', nbytes) != NULL)
923                     break;
924             }
925             if (xsum (len, predicted_len) >= max) return -2;
926         }
927     }
928 }
929
930
931
932 /*
933  * Extract data from the input buffer BUF.  This will read up to WANT
934  * bytes from the buffer.  It will set *RETDATA to point at the bytes,
935  * and set *GOT to the number of bytes to be found there.  Any buffer
936  * call which uses BUF may change the contents of the buffer at *DATA,
937  * so the data should be fully processed before any further calls are
938  * made.  This returns 0 on success, or -1 on end of file, or -2 if
939  * out of memory, or an error code.
940  */
941 int
942 buf_read_data (struct buffer *buf, size_t want, char **retdata, size_t *got)
943 {
944     assert (buf->input != NULL);
945
946     while (buf->data != NULL && buf->data->size == 0)
947     {
948         struct buffer_data *next;
949
950         next = buf->data->next;
951         buf_free_datas (buf->data, buf->data);
952         buf->data = next;
953         if (next == NULL)
954             buf->last = NULL;
955     }
956
957     if (buf->data == NULL)
958     {
959         struct buffer_data *data;
960         int status;
961         size_t get, nbytes;
962
963         data = get_buffer_data ();
964         if (data == NULL)
965         {
966             (*buf->memory_error) (buf);
967             return -2;
968         }
969
970         buf->data = data;
971         buf->last = data;
972         data->next = NULL;
973         data->bufp = data->text;
974         data->size = 0;
975
976         if (want < BUFFER_DATA_SIZE)
977             get = want;
978         else
979             get = BUFFER_DATA_SIZE;
980         status = (*buf->input) (buf->closure, data->bufp, get,
981                                 BUFFER_DATA_SIZE, &nbytes);
982         if (status != 0)
983             return status;
984
985         data->size = nbytes;
986     }
987
988     *retdata = buf->data->bufp;
989     if (want < buf->data->size)
990     {
991         *got = want;
992         buf->data->size -= want;
993         buf->data->bufp += want;
994     }
995     else
996     {
997         *got = buf->data->size;
998         buf->data->size = 0;
999     }
1000
1001     return 0;
1002 }
1003
1004
1005
1006 /*
1007  * Copy lines from an input buffer to an output buffer.
1008  * This copies all complete lines (characters up to a
1009  * newline) from INBUF to OUTBUF.  Each line in OUTBUF is preceded by the
1010  * character COMMAND and a space.
1011  */
1012 void
1013 buf_copy_lines (struct buffer *outbuf, struct buffer *inbuf, int command)
1014 {
1015     while (1)
1016     {
1017         struct buffer_data *data;
1018         struct buffer_data *nldata;
1019         char *nl;
1020         int len;
1021
1022         /* See if there is a newline in INBUF.  */
1023         nldata = NULL;
1024         nl = NULL;
1025         for (data = inbuf->data; data != NULL; data = data->next)
1026         {
1027             nl = memchr (data->bufp, '\n', data->size);
1028             if (nl != NULL)
1029             {
1030                 nldata = data;
1031                 break;
1032             }
1033         }
1034
1035         if (nldata == NULL)
1036         {
1037             /* There are no more lines in INBUF.  */
1038             return;
1039         }
1040
1041         /* Put in the command.  */
1042         buf_append_char (outbuf, command);
1043         buf_append_char (outbuf, ' ');
1044
1045         if (inbuf->data != nldata)
1046         {
1047             /*
1048              * Simply move over all the buffers up to the one containing
1049              * the newline.
1050              */
1051             for (data = inbuf->data; data->next != nldata; data = data->next);
1052             data->next = NULL;
1053             buf_append_data (outbuf, inbuf->data, data);
1054             inbuf->data = nldata;
1055         }
1056
1057         /*
1058          * If the newline is at the very end of the buffer, just move
1059          * the buffer onto OUTBUF.  Otherwise we must copy the data.
1060          */
1061         len = nl + 1 - nldata->bufp;
1062         if (len == nldata->size)
1063         {
1064             inbuf->data = nldata->next;
1065             if (inbuf->data == NULL)
1066                 inbuf->last = NULL;
1067
1068             nldata->next = NULL;
1069             buf_append_data (outbuf, nldata, nldata);
1070         }
1071         else
1072         {
1073             buf_output (outbuf, nldata->bufp, len);
1074             nldata->bufp += len;
1075             nldata->size -= len;
1076         }
1077     }
1078 }
1079
1080
1081
1082 /*
1083  * Copy counted data from one buffer to another.  The count is an
1084  * integer, host size, host byte order (it is only used across a
1085  * pipe).  If there is enough data, it should be moved over.  If there
1086  * is not enough data, it should remain on the original buffer.  A
1087  * negative count is a special case.  if one is seen, *SPECIAL is set
1088  * to the (negative) count value and no additional data is gathered
1089  * from the buffer; normally *SPECIAL is set to 0.  This function
1090  * returns the number of bytes it needs to see in order to actually
1091  * copy something over.
1092  */
1093 int
1094 buf_copy_counted (struct buffer *outbuf, struct buffer *inbuf, int *special)
1095 {
1096     *special = 0;
1097
1098     while (1)
1099     {
1100         struct buffer_data *data;
1101         int need;
1102         union
1103         {
1104             char intbuf[sizeof (int)];
1105             int i;
1106         } u;
1107         char *intp;
1108         int count;
1109         struct buffer_data *start;
1110         int startoff;
1111         struct buffer_data *stop;
1112         int stopwant;
1113
1114         /* See if we have enough bytes to figure out the count.  */
1115         need = sizeof (int);
1116         intp = u.intbuf;
1117         for (data = inbuf->data; data != NULL; data = data->next)
1118         {
1119             if (data->size >= need)
1120             {
1121                 memcpy (intp, data->bufp, need);
1122                 break;
1123             }
1124             memcpy (intp, data->bufp, data->size);
1125             intp += data->size;
1126             need -= data->size;
1127         }
1128         if (data == NULL)
1129         {
1130             /* We don't have enough bytes to form an integer.  */
1131             return need;
1132         }
1133
1134         count = u.i;
1135         start = data;
1136         startoff = need;
1137
1138         if (count < 0)
1139         {
1140             /* A negative COUNT is a special case meaning that we
1141                don't need any further information.  */
1142             stop = start;
1143             stopwant = 0;
1144         }
1145         else
1146         {
1147             /*
1148              * We have an integer in COUNT.  We have gotten all the
1149              * data from INBUF in all buffers before START, and we
1150              * have gotten STARTOFF bytes from START.  See if we have
1151              * enough bytes remaining in INBUF.
1152              */
1153             need = count - (start->size - startoff);
1154             if (need <= 0)
1155             {
1156                 stop = start;
1157                 stopwant = count;
1158             }
1159             else
1160             {
1161                 for (data = start->next; data != NULL; data = data->next)
1162                 {
1163                     if (need <= data->size)
1164                         break;
1165                     need -= data->size;
1166                 }
1167                 if (data == NULL)
1168                 {
1169                     /* We don't have enough bytes.  */
1170                     return need;
1171                 }
1172                 stop = data;
1173                 stopwant = need;
1174             }
1175         }
1176
1177         /*
1178          * We have enough bytes.  Free any buffers in INBUF before
1179          * START, and remove STARTOFF bytes from START, so that we can
1180          * forget about STARTOFF.
1181          */
1182         start->bufp += startoff;
1183         start->size -= startoff;
1184
1185         if (start->size == 0)
1186             start = start->next;
1187
1188         if (stop->size == stopwant)
1189         {
1190             stop = stop->next;
1191             stopwant = 0;
1192         }
1193
1194         while (inbuf->data != start)
1195         {
1196             data = inbuf->data;
1197             inbuf->data = data->next;
1198             buf_free_datas (data, data);
1199         }
1200
1201         /* If COUNT is negative, set *SPECIAL and get out now.  */
1202         if (count < 0)
1203         {
1204             *special = count;
1205             return 0;
1206         }
1207
1208         /*
1209          * We want to copy over the bytes from START through STOP.  We
1210          * only want STOPWANT bytes from STOP.
1211          */
1212
1213         if (start != stop)
1214         {
1215             /* Attach the buffers from START through STOP to OUTBUF.  */
1216             for (data = start; data->next != stop; data = data->next);
1217             inbuf->data = stop;
1218             data->next = NULL;
1219             buf_append_data (outbuf, start, data);
1220         }
1221
1222         if (stopwant > 0)
1223         {
1224             buf_output (outbuf, stop->bufp, stopwant);
1225             stop->bufp += stopwant;
1226             stop->size -= stopwant;
1227         }
1228     }
1229
1230     /*NOTREACHED*/
1231 }
1232
1233
1234
1235 int
1236 buf_get_fd (struct buffer *buf)
1237 {
1238     if (buf->get_fd)
1239         return (*buf->get_fd) (buf->closure);
1240     return -1;
1241 }
1242
1243
1244
1245 /* Shut down a buffer.  This returns 0 on success, or an errno code.  */
1246 int
1247 buf_shutdown (struct buffer *buf)
1248 {
1249     if (buf->shutdown) return (*buf->shutdown) (buf);
1250     return 0;
1251 }
1252
1253
1254
1255 /* Certain types of communication input and output data in packets,
1256    where each packet is translated in some fashion.  The packetizing
1257    buffer type supports that, given a buffer which handles lower level
1258    I/O and a routine to translate the data in a packet.
1259
1260    This code uses two bytes for the size of a packet, so packets are
1261    restricted to 65536 bytes in total.
1262
1263    The translation functions should just translate; they may not
1264    significantly increase or decrease the amount of data.  The actual
1265    size of the initial data is part of the translated data.  The
1266    output translation routine may add up to PACKET_SLOP additional
1267    bytes, and the input translation routine should shrink the data
1268    correspondingly.  */
1269
1270 # define PACKET_SLOP (100)
1271
1272 /* This structure is the closure field of a packetizing buffer.  */
1273
1274 struct packetizing_buffer
1275 {
1276     /* The underlying buffer.  */
1277     struct buffer *buf;
1278     /* The input translation function.  Exactly one of inpfn and outfn
1279        will be NULL.  The input translation function should
1280        untranslate the data in INPUT, storing the result in OUTPUT.
1281        SIZE is the amount of data in INPUT, and is also the size of
1282        OUTPUT.  This should return 0 on success, or an errno code.  */
1283     int (*inpfn) (void *fnclosure, const char *input, char *output,
1284                         size_t size);
1285     /* The output translation function.  This should translate the
1286        data in INPUT, storing the result in OUTPUT.  The first two
1287        bytes in INPUT will be the size of the data, and so will SIZE.
1288        This should set *TRANSLATED to the amount of translated data in
1289        OUTPUT.  OUTPUT is large enough to hold SIZE + PACKET_SLOP
1290        bytes.  This should return 0 on success, or an errno code.  */
1291     int (*outfn) (void *fnclosure, const char *input, char *output,
1292                         size_t size, size_t *translated);
1293     /* A closure for the translation function.  */
1294     void *fnclosure;
1295     /* For an input buffer, we may have to buffer up data here.  */
1296     /* This is non-zero if the buffered data has been translated.
1297        Otherwise, the buffered data has not been translated, and starts
1298        with the two byte packet size.  */
1299     bool translated;
1300     /* The amount of buffered data.  */
1301     size_t holdsize;
1302     /* The buffer allocated to hold the data.  */
1303     char *holdbuf;
1304     /* The size of holdbuf.  */
1305     size_t holdbufsize;
1306     /* If translated is set, we need another data pointer to track
1307        where we are in holdbuf.  If translated is clear, then this
1308        pointer is not used.  */
1309     char *holddata;
1310 };
1311
1312
1313
1314 static int packetizing_buffer_input (void *, char *, size_t, size_t, size_t *);
1315 static int packetizing_buffer_output (void *, const char *, size_t, size_t *);
1316 static int packetizing_buffer_flush (void *);
1317 static int packetizing_buffer_block (void *, bool);
1318 static int packetizing_buffer_get_fd (void *);
1319 static int packetizing_buffer_shutdown (struct buffer *);
1320
1321
1322
1323 /* Create a packetizing buffer.  */
1324 struct buffer *
1325 packetizing_buffer_initialize (struct buffer *buf,
1326                                int (*inpfn) (void *, const char *, char *,
1327                                              size_t),
1328                                int (*outfn) (void *, const char *, char *,
1329                                              size_t, size_t *),
1330                                void *fnclosure,
1331                                void (*memory) (struct buffer *))
1332 {
1333     struct packetizing_buffer *pb;
1334
1335     pb = xmalloc (sizeof *pb);
1336     memset (pb, 0, sizeof *pb);
1337
1338     pb->buf = buf;
1339     pb->inpfn = inpfn;
1340     pb->outfn = outfn;
1341     pb->fnclosure = fnclosure;
1342
1343     if (inpfn != NULL)
1344     {
1345         /* Add PACKET_SLOP to handle larger translated packets, and
1346            add 2 for the count.  This buffer is increased if
1347            necessary.  */
1348         pb->holdbufsize = BUFFER_DATA_SIZE + PACKET_SLOP + 2;
1349         pb->holdbuf = xmalloc (pb->holdbufsize);
1350     }
1351
1352     return buf_initialize (inpfn != NULL ? packetizing_buffer_input : NULL,
1353                            inpfn != NULL ? NULL : packetizing_buffer_output,
1354                            inpfn != NULL ? NULL : packetizing_buffer_flush,
1355                            packetizing_buffer_block,
1356                            packetizing_buffer_get_fd,
1357                            packetizing_buffer_shutdown,
1358                            memory,
1359                            pb);
1360 }
1361
1362
1363
1364 /* Input data from a packetizing buffer.  */
1365 static int
1366 packetizing_buffer_input (void *closure, char *data, size_t need, size_t size,
1367                           size_t *got)
1368 {
1369     struct packetizing_buffer *pb = closure;
1370
1371     *got = 0;
1372
1373     if (pb->holdsize > 0 && pb->translated)
1374     {
1375         size_t copy;
1376
1377         copy = pb->holdsize;
1378
1379         if (copy > size)
1380         {
1381             memcpy (data, pb->holddata, size);
1382             pb->holdsize -= size;
1383             pb->holddata += size;
1384             *got = size;
1385             return 0;
1386         }
1387
1388         memcpy (data, pb->holddata, copy);
1389         pb->holdsize = 0;
1390         pb->translated = false;
1391
1392         data += copy;
1393         need -= copy;
1394         size -= copy;
1395         *got = copy;
1396     }
1397
1398     while (need > 0 || *got == 0)
1399     {
1400         int status;
1401         size_t get, nread, count, tcount;
1402         char *bytes;
1403         static char *stackoutbuf = NULL;
1404         char *inbuf, *outbuf;
1405
1406         if (!stackoutbuf)
1407             stackoutbuf = xmalloc (BUFFER_DATA_SIZE + PACKET_SLOP);
1408
1409         /* If we don't already have the two byte count, get it.  */
1410         if (pb->holdsize < 2)
1411         {
1412             get = 2 - pb->holdsize;
1413             status = buf_read_data (pb->buf, get, &bytes, &nread);
1414             if (status != 0)
1415             {
1416                 /* buf_read_data can return -2, but a buffer input
1417                    function is only supposed to return -1, 0, or an
1418                    error code.  */
1419                 if (status == -2)
1420                     status = ENOMEM;
1421                 return status;
1422             }
1423
1424             if (nread == 0)
1425             {
1426                 /* The buffer is in nonblocking mode, and we didn't
1427                    manage to read anything.  */
1428                 return 0;
1429             }
1430
1431             if (get == 1)
1432                 pb->holdbuf[1] = bytes[0];
1433             else
1434             {
1435                 pb->holdbuf[0] = bytes[0];
1436                 if (nread < 2)
1437                 {
1438                     /* We only got one byte, but we needed two.  Stash
1439                        the byte we got, and try again.  */
1440                     pb->holdsize = 1;
1441                     continue;
1442                 }
1443                 pb->holdbuf[1] = bytes[1];
1444             }
1445             pb->holdsize = 2;
1446         }
1447
1448         /* Read the packet.  */
1449
1450         count = (((pb->holdbuf[0] & 0xff) << 8)
1451                  + (pb->holdbuf[1] & 0xff));
1452
1453         if (count + 2 > pb->holdbufsize)
1454         {
1455             char *n;
1456
1457             /* We didn't allocate enough space in the initialize
1458                function.  */
1459
1460             n = xrealloc (pb->holdbuf, count + 2);
1461             if (n == NULL)
1462             {
1463                 (*pb->buf->memory_error) (pb->buf);
1464                 return ENOMEM;
1465             }
1466             pb->holdbuf = n;
1467             pb->holdbufsize = count + 2;
1468         }
1469
1470         get = count - (pb->holdsize - 2);
1471
1472         status = buf_read_data (pb->buf, get, &bytes, &nread);
1473         if (status != 0)
1474         {
1475             /* buf_read_data can return -2, but a buffer input
1476                function is only supposed to return -1, 0, or an error
1477                code.  */
1478             if (status == -2)
1479                 status = ENOMEM;
1480             return status;
1481         }
1482
1483         if (nread == 0)
1484         {
1485             /* We did not get any data.  Presumably the buffer is in
1486                nonblocking mode.  */
1487             return 0;
1488         }
1489
1490         if (nread < get)
1491         {
1492             /* We did not get all the data we need to fill the packet.
1493                buf_read_data does not promise to return all the bytes
1494                requested, so we must try again.  */
1495             memcpy (pb->holdbuf + pb->holdsize, bytes, nread);
1496             pb->holdsize += nread;
1497             continue;
1498         }
1499
1500         /* We have a complete untranslated packet of COUNT bytes.  */
1501
1502         if (pb->holdsize == 2)
1503         {
1504             /* We just read the entire packet (the 2 bytes in
1505                PB->HOLDBUF are the size).  Save a memcpy by
1506                translating directly from BYTES.  */
1507             inbuf = bytes;
1508         }
1509         else
1510         {
1511             /* We already had a partial packet in PB->HOLDBUF.  We
1512                need to copy the new data over to make the input
1513                contiguous.  */
1514             memcpy (pb->holdbuf + pb->holdsize, bytes, nread);
1515             inbuf = pb->holdbuf + 2;
1516         }
1517
1518         if (count <= BUFFER_DATA_SIZE + PACKET_SLOP)
1519             outbuf = stackoutbuf;
1520         else
1521         {
1522             outbuf = xmalloc (count);
1523             if (outbuf == NULL)
1524             {
1525                 (*pb->buf->memory_error) (pb->buf);
1526                 return ENOMEM;
1527             }
1528         }
1529
1530         status = (*pb->inpfn) (pb->fnclosure, inbuf, outbuf, count);
1531         if (status != 0)
1532             return status;
1533
1534         /* The first two bytes in the translated buffer are the real
1535            length of the translated data.  */
1536         tcount = ((outbuf[0] & 0xff) << 8) + (outbuf[1] & 0xff);
1537
1538         if (tcount > count)
1539             error (1, 0, "Input translation failure");
1540
1541         if (tcount > size)
1542         {
1543             /* We have more data than the caller has provided space
1544                for.  We need to save some of it for the next call.  */
1545
1546             memcpy (data, outbuf + 2, size);
1547             *got += size;
1548
1549             pb->holdsize = tcount - size;
1550             memcpy (pb->holdbuf, outbuf + 2 + size, tcount - size);
1551             pb->holddata = pb->holdbuf;
1552             pb->translated = true;
1553
1554             if (outbuf != stackoutbuf)
1555                 free (outbuf);
1556
1557             return 0;
1558         }
1559
1560         memcpy (data, outbuf + 2, tcount);
1561
1562         if (outbuf != stackoutbuf)
1563             free (outbuf);
1564
1565         pb->holdsize = 0;
1566
1567         data += tcount;
1568         need -= tcount;
1569         size -= tcount;
1570         *got += tcount;
1571     }
1572
1573     return 0;
1574 }
1575
1576
1577
1578 /* Output data to a packetizing buffer.  */
1579 static int
1580 packetizing_buffer_output (void *closure, const char *data, size_t have,
1581                            size_t *wrote)
1582 {
1583     struct packetizing_buffer *pb = closure;
1584     static char *inbuf = NULL;  /* These two buffers are static so that they
1585                                  * depend on the size of BUFFER_DATA_SIZE yet
1586                                  * still only be allocated once per run.
1587                                  */
1588     static char *stack_outbuf = NULL;
1589     struct buffer_data *outdata = NULL; /* Initialize to silence -Wall.  Dumb.
1590                                          */
1591     char *outbuf;
1592     size_t size, translated;
1593     int status;
1594
1595     /* It would be easy to xmalloc a buffer, but I don't think this
1596        case can ever arise.  */
1597     assert (have <= BUFFER_DATA_SIZE);
1598
1599     if (!inbuf)
1600     {
1601         inbuf = xmalloc (BUFFER_DATA_SIZE + 2);
1602         stack_outbuf = xmalloc (BUFFER_DATA_SIZE + PACKET_SLOP + 4);
1603     }
1604
1605     inbuf[0] = (have >> 8) & 0xff;
1606     inbuf[1] = have & 0xff;
1607     memcpy (inbuf + 2, data, have);
1608
1609     size = have + 2;
1610
1611     /* The output function is permitted to add up to PACKET_SLOP
1612        bytes, and we need 2 bytes for the size of the translated data.
1613        If we can guarantee that the result will fit in a buffer_data,
1614        we translate directly into one to avoid a memcpy in buf_output.  */
1615     if (size + PACKET_SLOP + 2 > BUFFER_DATA_SIZE)
1616         outbuf = stack_outbuf;
1617     else
1618     {
1619         outdata = get_buffer_data ();
1620         if (outdata == NULL)
1621         {
1622             (*pb->buf->memory_error) (pb->buf);
1623             return ENOMEM;
1624         }
1625
1626         outdata->next = NULL;
1627         outdata->bufp = outdata->text;
1628
1629         outbuf = outdata->text;
1630     }
1631
1632     status = (*pb->outfn) (pb->fnclosure, inbuf, outbuf + 2, size,
1633                            &translated);
1634     if (status != 0)
1635         return status;
1636
1637     /* The output function is permitted to add up to PACKET_SLOP
1638        bytes.  */
1639     assert (translated <= size + PACKET_SLOP);
1640
1641     outbuf[0] = (translated >> 8) & 0xff;
1642     outbuf[1] = translated & 0xff;
1643
1644     if (outbuf == stack_outbuf)
1645         buf_output (pb->buf, outbuf, translated + 2);
1646     else
1647     {
1648         outdata->size = translated + 2;
1649         buf_append_data (pb->buf, outdata, outdata);
1650     }
1651
1652     *wrote = have;
1653
1654     /* We will only be here because buf_send_output was called on the
1655        packetizing buffer.  That means that we should now call
1656        buf_send_output on the underlying buffer.  */
1657     return buf_send_output (pb->buf);
1658 }
1659
1660
1661
1662 /* Flush data to a packetizing buffer.  */
1663 static int
1664 packetizing_buffer_flush (void *closure)
1665 {
1666     struct packetizing_buffer *pb = closure;
1667
1668     /* Flush the underlying buffer.  Note that if the original call to
1669        buf_flush passed 1 for the BLOCK argument, then the buffer will
1670        already have been set into blocking mode, so we should always
1671        pass 0 here.  */
1672     return buf_flush (pb->buf, 0);
1673 }
1674
1675
1676
1677 /* The block routine for a packetizing buffer.  */
1678 static int
1679 packetizing_buffer_block (void *closure, bool block)
1680 {
1681     struct packetizing_buffer *pb = closure;
1682
1683     if (block)
1684         return set_block (pb->buf);
1685     else
1686         return set_nonblock (pb->buf);
1687 }
1688
1689
1690
1691 /* Return the file descriptor underlying any child buffers.  */
1692 static int
1693 packetizing_buffer_get_fd (void *closure)
1694 {
1695     struct packetizing_buffer *cb = closure;
1696     return buf_get_fd (cb->buf);
1697 }
1698
1699
1700
1701 /* Shut down a packetizing buffer.  */
1702 static int
1703 packetizing_buffer_shutdown (struct buffer *buf)
1704 {
1705     struct packetizing_buffer *pb = buf->closure;
1706
1707     return buf_shutdown (pb->buf);
1708 }
1709
1710
1711
1712 /* All server communication goes through buffer structures.  Most of
1713    the buffers are built on top of a file descriptor.  This structure
1714    is used as the closure field in a buffer.  */
1715
1716 struct fd_buffer
1717 {
1718     /* The file descriptor.  */
1719     int fd;
1720     /* Nonzero if the file descriptor is in blocking mode.  */
1721     int blocking;
1722     /* The child process id when fd is a pipe.  */
1723     pid_t child_pid;
1724     /* The connection info, when fd is a pipe to a server.  */
1725     cvsroot_t *root;
1726 };
1727
1728 static int fd_buffer_input (void *, char *, size_t, size_t, size_t *);
1729 static int fd_buffer_output (void *, const char *, size_t, size_t *);
1730 static int fd_buffer_flush (void *);
1731 static int fd_buffer_block (void *, bool);
1732 static int fd_buffer_get_fd (void *);
1733 static int fd_buffer_shutdown (struct buffer *);
1734
1735 /* Initialize a buffer built on a file descriptor.  FD is the file
1736    descriptor.  INPUT is nonzero if this is for input, zero if this is
1737    for output.  MEMORY is the function to call when a memory error
1738    occurs.  */
1739
1740 struct buffer *
1741 fd_buffer_initialize (int fd, pid_t child_pid, cvsroot_t *root, bool input,
1742                       void (*memory) (struct buffer *))
1743 {
1744     struct fd_buffer *n;
1745
1746     n = xmalloc (sizeof *n);
1747     n->fd = fd;
1748     n->child_pid = child_pid;
1749     n->root = root;
1750     fd_buffer_block (n, true);
1751     return buf_initialize (input ? fd_buffer_input : NULL,
1752                            input ? NULL : fd_buffer_output,
1753                            input ? NULL : fd_buffer_flush,
1754                            fd_buffer_block, fd_buffer_get_fd,
1755                            fd_buffer_shutdown,
1756                            memory,
1757                            n);
1758 }
1759
1760
1761
1762 /* The buffer input function for a buffer built on a file descriptor.
1763  *
1764  * In non-blocing mode, this function will read as many bytes as it can in a
1765  * single try, up to SIZE bytes, and return.
1766  *
1767  * In blocking mode with NEED > 0, this function will read as many bytes as it
1768  * can but will not return until it has read at least NEED bytes.
1769  *
1770  * In blocking mode with NEED == 0, this function will block until it can read
1771  * either at least one byte or EOF, then read as many bytes as are available
1772  * and return.  At the very least, compress_buffer_shutdown depends on this
1773  * behavior to read EOF and can loop indefinitely without it.
1774  *
1775  * ASSUMPTIONS
1776  *   NEED <= SIZE.
1777  *
1778  * INPUTS
1779  *   closure    Our FD_BUFFER struct.
1780  *   data       The start of our input buffer.
1781  *   need       How many bytes our caller needs.
1782  *   size       How many bytes are available in DATA.
1783  *   got        Where to store the number of bytes read.
1784  *
1785  * OUTPUTS
1786  *   data       Filled with bytes read.
1787  *   *got       Number of bytes actually read into DATA.
1788  *
1789  * RETURNS
1790  *   errno      On error.
1791  *   -1         On EOF.
1792  *   0          Otherwise.
1793  *
1794  * ERRORS
1795  *   This function can return an error if fd_buffer_block(), or the system
1796  *   read() or select() calls do.
1797  */
1798 static int
1799 fd_buffer_input (void *closure, char *data, size_t need, size_t size,
1800                  size_t *got)
1801 {
1802     struct fd_buffer *fb = closure;
1803     int nbytes;
1804
1805     assert (need <= size);
1806
1807     *got = 0;
1808
1809     if (fb->blocking)
1810     {
1811         int status;
1812         fd_set readfds;
1813
1814         /* Set non-block.  */
1815         status = fd_buffer_block (fb, false);
1816         if (status != 0) return status;
1817
1818         FD_ZERO (&readfds);
1819         FD_SET (fb->fd, &readfds);
1820         do
1821         {
1822             int numfds;
1823
1824             do {
1825                 /* This used to select on exceptions too, but as far
1826                    as I know there was never any reason to do that and
1827                    SCO doesn't let you select on exceptions on pipes.  */
1828                 numfds = select (fb->fd + 1, &readfds, NULL, NULL, NULL);
1829                 if (numfds < 0 && errno != EINTR)
1830                 {
1831                     status = errno;
1832                     goto block_done;
1833                 }
1834             } while (numfds < 0);
1835
1836             nbytes = read (fb->fd, data + *got, size - *got);
1837
1838             if (nbytes == 0)
1839             {
1840                 /* End of file.  This assumes that we are using POSIX or BSD
1841                    style nonblocking I/O.  On System V we will get a zero
1842                    return if there is no data, even when not at EOF.  */
1843                 if (*got)
1844                 {
1845                     /* We already read some data, so return no error, counting
1846                      * on the fact that we will read EOF again next time.
1847                      */
1848                     status = 0;
1849                     break;
1850                 }
1851                 else
1852                 {
1853                     /* Return EOF.  */
1854                     status = -1;
1855                     break;
1856                 }
1857             }
1858
1859             if (nbytes < 0)
1860             {
1861                 /* Some error occurred.  */
1862                 if (!blocking_error (errno))
1863                 {
1864                     status = errno;
1865                     break;
1866                 }
1867                 /* else Everything's fine, we just didn't get any data.  */
1868             }
1869
1870             *got += nbytes;
1871         } while (*got < need);
1872
1873 block_done:
1874         if (status == 0 || status == -1)
1875         {
1876             int newstatus;
1877
1878             /* OK or EOF - Reset block.  */
1879             newstatus = fd_buffer_block (fb, true);
1880             if (newstatus) status = newstatus;
1881         }
1882         return status;
1883     }
1884
1885     /* The above will always return.  Handle non-blocking read.  */
1886     nbytes = read (fb->fd, data, size);
1887
1888     if (nbytes > 0)
1889     {
1890         *got = nbytes;
1891         return 0;
1892     }
1893
1894     if (nbytes == 0)
1895         /* End of file.  This assumes that we are using POSIX or BSD
1896            style nonblocking I/O.  On System V we will get a zero
1897            return if there is no data, even when not at EOF.  */
1898         return -1;
1899
1900     /* Some error occurred.  */
1901     if (blocking_error (errno))
1902         /* Everything's fine, we just didn't get any data.  */
1903         return 0;
1904
1905     return errno;
1906 }
1907
1908
1909
1910 /* The buffer output function for a buffer built on a file descriptor.  */
1911
1912 static int
1913 fd_buffer_output (void *closure, const char *data, size_t have, size_t *wrote)
1914 {
1915     struct fd_buffer *fd = closure;
1916
1917     *wrote = 0;
1918
1919     while (have > 0)
1920     {
1921         int nbytes;
1922
1923         nbytes = write (fd->fd, data, have);
1924
1925         if (nbytes <= 0)
1926         {
1927             if (! fd->blocking
1928                 && (nbytes == 0 || blocking_error (errno)))
1929             {
1930                 /* A nonblocking write failed to write any data.  Just
1931                    return.  */
1932                 return 0;
1933             }
1934
1935             /* Some sort of error occurred.  */
1936
1937             if (nbytes == 0)
1938                 return EIO;
1939
1940             return errno;
1941         }
1942
1943         *wrote += nbytes;
1944         data += nbytes;
1945         have -= nbytes;
1946     }
1947
1948     return 0;
1949 }
1950
1951
1952
1953 /* The buffer flush function for a buffer built on a file descriptor.  */
1954 static int
1955 fd_buffer_flush (void *closure)
1956 {
1957     /* We don't need to do anything here.  Our fd doesn't have its own buffer
1958      * and syncing won't do anything but slow us down.
1959      *
1960      * struct fd_buffer *fb = closure;
1961      *
1962      * if (fsync (fb->fd) < 0 && errno != EROFS && errno != EINVAL)
1963      *     return errno;
1964      */
1965     return 0;
1966 }
1967
1968
1969
1970 static struct stat devnull;
1971 static int devnull_set = -1;
1972
1973 /* The buffer block function for a buffer built on a file descriptor.  */
1974 static int
1975 fd_buffer_block (void *closure, bool block)
1976 {
1977     struct fd_buffer *fb = closure;
1978 # if defined (F_GETFL) && defined (O_NONBLOCK) && defined (F_SETFL)
1979     int flags;
1980
1981     flags = fcntl (fb->fd, F_GETFL, 0);
1982     if (flags < 0)
1983         return errno;
1984
1985     if (block)
1986         flags &= ~O_NONBLOCK;
1987     else
1988         flags |= O_NONBLOCK;
1989
1990     if (fcntl (fb->fd, F_SETFL, flags) < 0)
1991     {
1992         /*
1993          * BSD returns ENODEV when we try to set block/nonblock on /dev/null.
1994          * BSDI returns ENOTTY when we try to set block/nonblock on /dev/null.
1995          */
1996         struct stat sb;
1997         int save_errno = errno;
1998         bool isdevnull = false;
1999
2000         if (devnull_set == -1)
2001             devnull_set = stat ("/dev/null", &devnull);
2002
2003         if (devnull_set >= 0)
2004             /* Equivalent to /dev/null ? */
2005             isdevnull = (fstat (fb->fd, &sb) >= 0
2006                          && sb.st_dev == devnull.st_dev
2007                          && sb.st_ino == devnull.st_ino
2008                          && sb.st_mode == devnull.st_mode
2009                          && sb.st_uid == devnull.st_uid
2010                          && sb.st_gid == devnull.st_gid
2011                          && sb.st_size == devnull.st_size
2012                          && sb.st_blocks == devnull.st_blocks
2013                          && sb.st_blksize == devnull.st_blksize);
2014         if (isdevnull)
2015             errno = 0;
2016         else
2017         {
2018             errno = save_errno;
2019             return errno;
2020         }
2021     }
2022 # endif /* F_GETFL && O_NONBLOCK && F_SETFL */
2023
2024     fb->blocking = block;
2025
2026     return 0;
2027 }
2028
2029
2030
2031 static int
2032 fd_buffer_get_fd (void *closure)
2033 {
2034     struct fd_buffer *fb = closure;
2035     return fb->fd;
2036 }
2037
2038
2039
2040 /* The buffer shutdown function for a buffer built on a file descriptor.
2041  *
2042  * This function disposes of memory allocated for this buffer.
2043  */
2044 static int
2045 fd_buffer_shutdown (struct buffer *buf)
2046 {
2047     struct fd_buffer *fb = buf->closure;
2048     struct stat s;
2049     bool closefd, statted;
2050
2051     /* Must be an open pipe, socket, or file.  What could go wrong? */
2052     if (fstat (fb->fd, &s) == -1) statted = false;
2053     else statted = true;
2054     /* Don't bother to try closing the FD if we couldn't stat it.  This
2055      * probably won't work.
2056      *
2057      * (buf_shutdown() on some of the server/child communication pipes is
2058      * getting EBADF on both the fstat and the close.  I'm not sure why -
2059      * perhaps they were alredy closed somehow?
2060      */
2061     closefd = statted;
2062
2063     /* Flush the buffer if possible.  */
2064     if (buf->flush)
2065     {
2066         buf_flush (buf, 1);
2067         buf->flush = NULL;
2068     }
2069
2070     if (buf->input)
2071     {
2072         /* There used to be a check here for unread data in the buffer of
2073          * the pipe, but it was deemed unnecessary and possibly dangerous.  In
2074          * some sense it could be second-guessing the caller who requested it
2075          * closed, as well.
2076          */
2077
2078 /* FIXME:
2079  *
2080  * This mess of #ifdefs is hard to read.  There must be some relation between
2081  * the macros being checked which at least deserves comments - if
2082  * SHUTDOWN_SERVER, NO_SOCKET_TO_FD, & START_RSH_WITH_POPEN_RW were completely
2083  * independant, then the next few lines could easily refuse to compile.
2084  *
2085  * The note below about START_RSH_WITH_POPEN_RW never being set when
2086  * SHUTDOWN_SERVER is defined means that this code would always break on
2087  * systems with SHUTDOWN_SERVER defined and thus the comment must now be
2088  * incorrect or the code was broken since the comment was written.
2089  */
2090 # ifdef SHUTDOWN_SERVER
2091         if (fb->root && fb->root->method != server_method)
2092 # endif
2093 # ifndef NO_SOCKET_TO_FD
2094         {
2095             /* shutdown() sockets */
2096             if (statted && S_ISSOCK (s.st_mode))
2097                 shutdown (fb->fd, 0);
2098         }
2099 # endif /* NO_SOCKET_TO_FD */
2100 # ifdef START_RSH_WITH_POPEN_RW
2101 /* Can't be set with SHUTDOWN_SERVER defined */
2102         /* FIXME: This is now certainly broken since pclose is defined by ANSI
2103          * C to accept a FILE * argument.  The switch will need to happen at a
2104          * higher abstraction level to switch between initializing stdio & fd
2105          * buffers on systems that need this (or maybe an fd buffer that keeps
2106          * track of the FILE * could be used - I think flushing the stream
2107          * before beginning exclusive access via the FD is OK.
2108          */
2109         else if (fb->root && pclose (fb->fd) == EOF)
2110         {
2111             error (1, errno, "closing connection to %s",
2112                    fb->root->hostname);
2113             closefd = false;
2114         }
2115 # endif /* START_RSH_WITH_POPEN_RW */
2116
2117         buf->input = NULL;
2118     }
2119     else if (buf->output)
2120     {
2121 # ifdef SHUTDOWN_SERVER
2122         /* FIXME:  Should have a SHUTDOWN_SERVER_INPUT &
2123          * SHUTDOWN_SERVER_OUTPUT
2124          */
2125         if (fb->root && fb->root->method == server_method)
2126             SHUTDOWN_SERVER (fb->fd);
2127         else
2128 # endif
2129 # ifndef NO_SOCKET_TO_FD
2130         /* shutdown() sockets */
2131         if (statted && S_ISSOCK (s.st_mode))
2132             shutdown (fb->fd, 1);
2133 # else
2134         {
2135         /* I'm not sure I like this empty block, but the alternative
2136          * is another nested NO_SOCKET_TO_FD switch as above.
2137          */
2138         }
2139 # endif /* NO_SOCKET_TO_FD */
2140
2141         buf->output = NULL;
2142     }
2143
2144     if (statted && closefd && close (fb->fd) == -1)
2145     {
2146         if (0
2147 # ifdef SERVER_SUPPORT
2148             || server_active
2149 # endif /* SERVER_SUPPORT */
2150            )
2151         {
2152             /* Syslog this? */
2153         }
2154 # ifdef CLIENT_SUPPORT
2155         else if (fb->root)
2156             error (1, errno, "closing down connection to %s",
2157                    fb->root->hostname);
2158             /* EXITS */
2159 # endif /* CLIENT_SUPPORT */
2160
2161         error (0, errno, "closing down buffer");
2162     }
2163
2164     /* If we were talking to a process, make sure it exited */
2165     if (fb->child_pid)
2166     {
2167         int w;
2168
2169         do
2170             w = waitpid (fb->child_pid, NULL, 0);
2171         while (w == -1 && errno == EINTR);
2172         if (w == -1)
2173             error (1, errno, "waiting for process %d", fb->child_pid);
2174     }
2175
2176     free (buf->closure);
2177     buf->closure = NULL;
2178
2179     return 0;
2180 }
2181 #endif /* defined (SERVER_SUPPORT) || defined (CLIENT_SUPPORT) */