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