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