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