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