1/*
2 * Copyright (c) 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#if 0
35#ifndef lint
36static const char sccsid[] = "@(#)state.c	8.5 (Berkeley) 5/30/95";
37#endif
38#endif
39#include <sys/cdefs.h>
40__FBSDID("$FreeBSD: releng/10.3/contrib/telnet/telnetd/state.c 241021 2012-09-28 07:51:30Z kevlo $");
41
42#include <stdarg.h>
43#include "telnetd.h"
44#ifdef	AUTHENTICATION
45#include <libtelnet/auth.h>
46#endif
47#ifdef	ENCRYPTION
48#include <libtelnet/encrypt.h>
49#endif
50
51unsigned char	doopt[] = { IAC, DO, '%', 'c', 0 };
52unsigned char	dont[] = { IAC, DONT, '%', 'c', 0 };
53unsigned char	will[] = { IAC, WILL, '%', 'c', 0 };
54unsigned char	wont[] = { IAC, WONT, '%', 'c', 0 };
55int	not42 = 1;
56
57/*
58 * Buffer for sub-options, and macros
59 * for suboptions buffer manipulations
60 */
61unsigned char subbuffer[512], *subpointer= subbuffer, *subend= subbuffer;
62
63#define	SB_CLEAR()	subpointer = subbuffer
64#define	SB_TERM()	{ subend = subpointer; SB_CLEAR(); }
65#define	SB_ACCUM(c)	if (subpointer < (subbuffer+sizeof subbuffer)) { \
66				*subpointer++ = (c); \
67			}
68#define	SB_GET()	((*subpointer++)&0xff)
69#define	SB_EOF()	(subpointer >= subend)
70#define	SB_LEN()	(subend - subpointer)
71
72#ifdef	ENV_HACK
73unsigned char *subsave;
74#define SB_SAVE()	subsave = subpointer;
75#define	SB_RESTORE()	subpointer = subsave;
76#endif
77
78
79/*
80 * State for recv fsm
81 */
82#define	TS_DATA		0	/* base state */
83#define	TS_IAC		1	/* look for double IAC's */
84#define	TS_CR		2	/* CR-LF ->'s CR */
85#define	TS_SB		3	/* throw away begin's... */
86#define	TS_SE		4	/* ...end's (suboption negotiation) */
87#define	TS_WILL		5	/* will option negotiation */
88#define	TS_WONT		6	/* wont " */
89#define	TS_DO		7	/* do " */
90#define	TS_DONT		8	/* dont " */
91
92static void doclientstat(void);
93
94void
95telrcv(void)
96{
97	int c;
98	static int state = TS_DATA;
99
100	while (ncc > 0) {
101		if ((&ptyobuf[BUFSIZ] - pfrontp) < 2)
102			break;
103		c = *netip++ & 0377, ncc--;
104#ifdef	ENCRYPTION
105		if (decrypt_input)
106			c = (*decrypt_input)(c);
107#endif	/* ENCRYPTION */
108		switch (state) {
109
110		case TS_CR:
111			state = TS_DATA;
112			/* Strip off \n or \0 after a \r */
113			if ((c == 0) || (c == '\n')) {
114				break;
115			}
116			/* FALLTHROUGH */
117
118		case TS_DATA:
119			if (c == IAC) {
120				state = TS_IAC;
121				break;
122			}
123			/*
124			 * We now map \r\n ==> \r for pragmatic reasons.
125			 * Many client implementations send \r\n when
126			 * the user hits the CarriageReturn key.
127			 *
128			 * We USED to map \r\n ==> \n, since \r\n says
129			 * that we want to be in column 1 of the next
130			 * printable line, and \n is the standard
131			 * unix way of saying that (\r is only good
132			 * if CRMOD is set, which it normally is).
133			 */
134			if ((c == '\r') && his_state_is_wont(TELOPT_BINARY)) {
135				int nc = *netip;
136#ifdef	ENCRYPTION
137				if (decrypt_input)
138					nc = (*decrypt_input)(nc & 0xff);
139#endif	/* ENCRYPTION */
140#ifdef	LINEMODE
141				/*
142				 * If we are operating in linemode,
143				 * convert to local end-of-line.
144				 */
145				if (linemode && (ncc > 0) && (('\n' == nc) ||
146					 ((0 == nc) && tty_iscrnl())) ) {
147					netip++; ncc--;
148					c = '\n';
149				} else
150#endif
151				{
152#ifdef	ENCRYPTION
153					if (decrypt_input)
154						(void)(*decrypt_input)(-1);
155#endif	/* ENCRYPTION */
156					state = TS_CR;
157				}
158			}
159			*pfrontp++ = c;
160			break;
161
162		case TS_IAC:
163gotiac:			switch (c) {
164
165			/*
166			 * Send the process on the pty side an
167			 * interrupt.  Do this with a NULL or
168			 * interrupt char; depending on the tty mode.
169			 */
170			case IP:
171				DIAG(TD_OPTIONS,
172					printoption("td: recv IAC", c));
173				interrupt();
174				break;
175
176			case BREAK:
177				DIAG(TD_OPTIONS,
178					printoption("td: recv IAC", c));
179				sendbrk();
180				break;
181
182			/*
183			 * Are You There?
184			 */
185			case AYT:
186				DIAG(TD_OPTIONS,
187					printoption("td: recv IAC", c));
188				recv_ayt();
189				break;
190
191			/*
192			 * Abort Output
193			 */
194			case AO:
195			    {
196				DIAG(TD_OPTIONS,
197					printoption("td: recv IAC", c));
198				ptyflush();	/* half-hearted */
199				init_termbuf();
200
201				if (slctab[SLC_AO].sptr &&
202				    *slctab[SLC_AO].sptr != (cc_t)(_POSIX_VDISABLE)) {
203				    *pfrontp++ =
204					(unsigned char)*slctab[SLC_AO].sptr;
205				}
206
207				netclear();	/* clear buffer back */
208				output_data("%c%c", IAC, DM);
209				neturg = nfrontp-1; /* off by one XXX */
210				DIAG(TD_OPTIONS,
211					printoption("td: send IAC", DM));
212				break;
213			    }
214
215			/*
216			 * Erase Character and
217			 * Erase Line
218			 */
219			case EC:
220			case EL:
221			    {
222				cc_t ch;
223
224				DIAG(TD_OPTIONS,
225					printoption("td: recv IAC", c));
226				ptyflush();	/* half-hearted */
227				init_termbuf();
228				if (c == EC)
229					ch = *slctab[SLC_EC].sptr;
230				else
231					ch = *slctab[SLC_EL].sptr;
232				if (ch != (cc_t)(_POSIX_VDISABLE))
233					*pfrontp++ = (unsigned char)ch;
234				break;
235			    }
236
237			/*
238			 * Check for urgent data...
239			 */
240			case DM:
241				DIAG(TD_OPTIONS,
242					printoption("td: recv IAC", c));
243				SYNCHing = stilloob(net);
244				settimer(gotDM);
245				break;
246
247
248			/*
249			 * Begin option subnegotiation...
250			 */
251			case SB:
252				state = TS_SB;
253				SB_CLEAR();
254				continue;
255
256			case WILL:
257				state = TS_WILL;
258				continue;
259
260			case WONT:
261				state = TS_WONT;
262				continue;
263
264			case DO:
265				state = TS_DO;
266				continue;
267
268			case DONT:
269				state = TS_DONT;
270				continue;
271			case EOR:
272				if (his_state_is_will(TELOPT_EOR))
273					doeof();
274				break;
275
276			/*
277			 * Handle RFC 10xx Telnet linemode option additions
278			 * to command stream (EOF, SUSP, ABORT).
279			 */
280			case xEOF:
281				doeof();
282				break;
283
284			case SUSP:
285				sendsusp();
286				break;
287
288			case ABORT:
289				sendbrk();
290				break;
291
292			case IAC:
293				*pfrontp++ = c;
294				break;
295			}
296			state = TS_DATA;
297			break;
298
299		case TS_SB:
300			if (c == IAC) {
301				state = TS_SE;
302			} else {
303				SB_ACCUM(c);
304			}
305			break;
306
307		case TS_SE:
308			if (c != SE) {
309				if (c != IAC) {
310					/*
311					 * bad form of suboption negotiation.
312					 * handle it in such a way as to avoid
313					 * damage to local state.  Parse
314					 * suboption buffer found so far,
315					 * then treat remaining stream as
316					 * another command sequence.
317					 */
318
319					/* for DIAGNOSTICS */
320					SB_ACCUM(IAC);
321					SB_ACCUM(c);
322					subpointer -= 2;
323
324					SB_TERM();
325					suboption();
326					state = TS_IAC;
327					goto gotiac;
328				}
329				SB_ACCUM(c);
330				state = TS_SB;
331			} else {
332				/* for DIAGNOSTICS */
333				SB_ACCUM(IAC);
334				SB_ACCUM(SE);
335				subpointer -= 2;
336
337				SB_TERM();
338				suboption();	/* handle sub-option */
339				state = TS_DATA;
340			}
341			break;
342
343		case TS_WILL:
344			willoption(c);
345			state = TS_DATA;
346			continue;
347
348		case TS_WONT:
349			wontoption(c);
350			state = TS_DATA;
351			continue;
352
353		case TS_DO:
354			dooption(c);
355			state = TS_DATA;
356			continue;
357
358		case TS_DONT:
359			dontoption(c);
360			state = TS_DATA;
361			continue;
362
363		default:
364			syslog(LOG_ERR, "panic state=%d", state);
365			printf("telnetd: panic state=%d\n", state);
366			exit(1);
367		}
368	}
369}  /* end of telrcv */
370
371/*
372 * The will/wont/do/dont state machines are based on Dave Borman's
373 * Telnet option processing state machine.
374 *
375 * These correspond to the following states:
376 *	my_state = the last negotiated state
377 *	want_state = what I want the state to go to
378 *	want_resp = how many requests I have sent
379 * All state defaults are negative, and resp defaults to 0.
380 *
381 * When initiating a request to change state to new_state:
382 *
383 * if ((want_resp == 0 && new_state == my_state) || want_state == new_state) {
384 *	do nothing;
385 * } else {
386 *	want_state = new_state;
387 *	send new_state;
388 *	want_resp++;
389 * }
390 *
391 * When receiving new_state:
392 *
393 * if (want_resp) {
394 *	want_resp--;
395 *	if (want_resp && (new_state == my_state))
396 *		want_resp--;
397 * }
398 * if ((want_resp == 0) && (new_state != want_state)) {
399 *	if (ok_to_switch_to new_state)
400 *		want_state = new_state;
401 *	else
402 *		want_resp++;
403 *	send want_state;
404 * }
405 * my_state = new_state;
406 *
407 * Note that new_state is implied in these functions by the function itself.
408 * will and do imply positive new_state, wont and dont imply negative.
409 *
410 * Finally, there is one catch.  If we send a negative response to a
411 * positive request, my_state will be the positive while want_state will
412 * remain negative.  my_state will revert to negative when the negative
413 * acknowlegment arrives from the peer.  Thus, my_state generally tells
414 * us not only the last negotiated state, but also tells us what the peer
415 * wants to be doing as well.  It is important to understand this difference
416 * as we may wish to be processing data streams based on our desired state
417 * (want_state) or based on what the peer thinks the state is (my_state).
418 *
419 * This all works fine because if the peer sends a positive request, the data
420 * that we receive prior to negative acknowlegment will probably be affected
421 * by the positive state, and we can process it as such (if we can; if we
422 * can't then it really doesn't matter).  If it is that important, then the
423 * peer probably should be buffering until this option state negotiation
424 * is complete.
425 *
426 */
427void
428send_do(int option, int init)
429{
430	if (init) {
431		if ((do_dont_resp[option] == 0 && his_state_is_will(option)) ||
432		    his_want_state_is_will(option))
433			return;
434		/*
435		 * Special case for TELOPT_TM:  We send a DO, but pretend
436		 * that we sent a DONT, so that we can send more DOs if
437		 * we want to.
438		 */
439		if (option == TELOPT_TM)
440			set_his_want_state_wont(option);
441		else
442			set_his_want_state_will(option);
443		do_dont_resp[option]++;
444	}
445	output_data((const char *)doopt, option);
446
447	DIAG(TD_OPTIONS, printoption("td: send do", option));
448}
449
450void
451willoption(int option)
452{
453	int changeok = 0;
454	void (*func)(void) = 0;
455
456	/*
457	 * process input from peer.
458	 */
459
460	DIAG(TD_OPTIONS, printoption("td: recv will", option));
461
462	if (do_dont_resp[option]) {
463		do_dont_resp[option]--;
464		if (do_dont_resp[option] && his_state_is_will(option))
465			do_dont_resp[option]--;
466	}
467	if (do_dont_resp[option] == 0) {
468	    if (his_want_state_is_wont(option)) {
469		switch (option) {
470
471		case TELOPT_BINARY:
472			init_termbuf();
473			tty_binaryin(1);
474			set_termbuf();
475			changeok++;
476			break;
477
478		case TELOPT_ECHO:
479			/*
480			 * See comments below for more info.
481			 */
482			not42 = 0;	/* looks like a 4.2 system */
483			break;
484
485		case TELOPT_TM:
486#if	defined(LINEMODE) && defined(KLUDGELINEMODE)
487			/*
488			 * This telnetd implementation does not really
489			 * support timing marks, it just uses them to
490			 * support the kludge linemode stuff.  If we
491			 * receive a will or wont TM in response to our
492			 * do TM request that may have been sent to
493			 * determine kludge linemode support, process
494			 * it, otherwise TM should get a negative
495			 * response back.
496			 */
497			/*
498			 * Handle the linemode kludge stuff.
499			 * If we are not currently supporting any
500			 * linemode at all, then we assume that this
501			 * is the client telling us to use kludge
502			 * linemode in response to our query.  Set the
503			 * linemode type that is to be supported, note
504			 * that the client wishes to use linemode, and
505			 * eat the will TM as though it never arrived.
506			 */
507			if (lmodetype < KLUDGE_LINEMODE) {
508				lmodetype = KLUDGE_LINEMODE;
509				clientstat(TELOPT_LINEMODE, WILL, 0);
510				send_wont(TELOPT_SGA, 1);
511			} else if (lmodetype == NO_AUTOKLUDGE) {
512				lmodetype = KLUDGE_OK;
513			}
514#endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
515			/*
516			 * We never respond to a WILL TM, and
517			 * we leave the state WONT.
518			 */
519			return;
520
521		case TELOPT_LFLOW:
522			/*
523			 * If we are going to support flow control
524			 * option, then don't worry peer that we can't
525			 * change the flow control characters.
526			 */
527			slctab[SLC_XON].defset.flag &= ~SLC_LEVELBITS;
528			slctab[SLC_XON].defset.flag |= SLC_DEFAULT;
529			slctab[SLC_XOFF].defset.flag &= ~SLC_LEVELBITS;
530			slctab[SLC_XOFF].defset.flag |= SLC_DEFAULT;
531		case TELOPT_TTYPE:
532		case TELOPT_SGA:
533		case TELOPT_NAWS:
534		case TELOPT_TSPEED:
535		case TELOPT_XDISPLOC:
536		case TELOPT_NEW_ENVIRON:
537		case TELOPT_OLD_ENVIRON:
538			changeok++;
539			break;
540
541#ifdef	LINEMODE
542		case TELOPT_LINEMODE:
543# ifdef	KLUDGELINEMODE
544			/*
545			 * Note client's desire to use linemode.
546			 */
547			lmodetype = REAL_LINEMODE;
548# endif	/* KLUDGELINEMODE */
549			func = doclientstat;
550			changeok++;
551			break;
552#endif	/* LINEMODE */
553
554#ifdef	AUTHENTICATION
555		case TELOPT_AUTHENTICATION:
556			if (auth_level >= 0) {
557				func = auth_request;
558				changeok++;
559			}
560			break;
561#endif
562
563#ifdef	ENCRYPTION
564		case TELOPT_ENCRYPT:
565			func = encrypt_send_support;
566			changeok++;
567			break;
568#endif	/* ENCRYPTION */
569
570		default:
571			break;
572		}
573		if (changeok) {
574			set_his_want_state_will(option);
575			send_do(option, 0);
576		} else {
577			do_dont_resp[option]++;
578			send_dont(option, 0);
579		}
580	    } else {
581		/*
582		 * Option processing that should happen when
583		 * we receive conformation of a change in
584		 * state that we had requested.
585		 */
586		switch (option) {
587		case TELOPT_ECHO:
588			not42 = 0;	/* looks like a 4.2 system */
589			/*
590			 * Egads, he responded "WILL ECHO".  Turn
591			 * it off right now!
592			 */
593			send_dont(option, 1);
594			/*
595			 * "WILL ECHO".  Kludge upon kludge!
596			 * A 4.2 client is now echoing user input at
597			 * the tty.  This is probably undesireable and
598			 * it should be stopped.  The client will
599			 * respond WONT TM to the DO TM that we send to
600			 * check for kludge linemode.  When the WONT TM
601			 * arrives, linemode will be turned off and a
602			 * change propogated to the pty.  This change
603			 * will cause us to process the new pty state
604			 * in localstat(), which will notice that
605			 * linemode is off and send a WILL ECHO
606			 * so that we are properly in character mode and
607			 * all is well.
608			 */
609			break;
610#ifdef	LINEMODE
611		case TELOPT_LINEMODE:
612# ifdef	KLUDGELINEMODE
613			/*
614			 * Note client's desire to use linemode.
615			 */
616			lmodetype = REAL_LINEMODE;
617# endif	/* KLUDGELINEMODE */
618			func = doclientstat;
619			break;
620#endif	/* LINEMODE */
621
622#ifdef	AUTHENTICATION
623		case TELOPT_AUTHENTICATION:
624			func = auth_request;
625			break;
626#endif
627
628#ifdef	ENCRYPTION
629		case TELOPT_ENCRYPT:
630			func = encrypt_send_support;
631			break;
632#endif	/* ENCRYPTION */
633		case TELOPT_LFLOW:
634			func = flowstat;
635			break;
636		}
637	    }
638	}
639	set_his_state_will(option);
640	if (func)
641		(*func)();
642}  /* end of willoption */
643
644void
645send_dont(int option, int init)
646{
647	if (init) {
648		if ((do_dont_resp[option] == 0 && his_state_is_wont(option)) ||
649		    his_want_state_is_wont(option))
650			return;
651		set_his_want_state_wont(option);
652		do_dont_resp[option]++;
653	}
654	output_data((const char *)dont, option);
655
656	DIAG(TD_OPTIONS, printoption("td: send dont", option));
657}
658
659void
660wontoption(int option)
661{
662	/*
663	 * Process client input.
664	 */
665
666	DIAG(TD_OPTIONS, printoption("td: recv wont", option));
667
668	if (do_dont_resp[option]) {
669		do_dont_resp[option]--;
670		if (do_dont_resp[option] && his_state_is_wont(option))
671			do_dont_resp[option]--;
672	}
673	if (do_dont_resp[option] == 0) {
674	    if (his_want_state_is_will(option)) {
675		/* it is always ok to change to negative state */
676		switch (option) {
677		case TELOPT_ECHO:
678			not42 = 1; /* doesn't seem to be a 4.2 system */
679			break;
680
681		case TELOPT_BINARY:
682			init_termbuf();
683			tty_binaryin(0);
684			set_termbuf();
685			break;
686
687#ifdef	LINEMODE
688		case TELOPT_LINEMODE:
689# ifdef	KLUDGELINEMODE
690			/*
691			 * If real linemode is supported, then client is
692			 * asking to turn linemode off.
693			 */
694			if (lmodetype != REAL_LINEMODE)
695				break;
696			lmodetype = KLUDGE_LINEMODE;
697# endif	/* KLUDGELINEMODE */
698			clientstat(TELOPT_LINEMODE, WONT, 0);
699			break;
700#endif	/* LINEMODE */
701
702		case TELOPT_TM:
703			/*
704			 * If we get a WONT TM, and had sent a DO TM,
705			 * don't respond with a DONT TM, just leave it
706			 * as is.  Short circut the state machine to
707			 * achive this.
708			 */
709			set_his_want_state_wont(TELOPT_TM);
710			return;
711
712		case TELOPT_LFLOW:
713			/*
714			 * If we are not going to support flow control
715			 * option, then let peer know that we can't
716			 * change the flow control characters.
717			 */
718			slctab[SLC_XON].defset.flag &= ~SLC_LEVELBITS;
719			slctab[SLC_XON].defset.flag |= SLC_CANTCHANGE;
720			slctab[SLC_XOFF].defset.flag &= ~SLC_LEVELBITS;
721			slctab[SLC_XOFF].defset.flag |= SLC_CANTCHANGE;
722			break;
723
724#ifdef	AUTHENTICATION
725		case TELOPT_AUTHENTICATION:
726			auth_finished(0, AUTH_REJECT);
727			break;
728#endif
729
730		/*
731		 * For options that we might spin waiting for
732		 * sub-negotiation, if the client turns off the
733		 * option rather than responding to the request,
734		 * we have to treat it here as if we got a response
735		 * to the sub-negotiation, (by updating the timers)
736		 * so that we'll break out of the loop.
737		 */
738		case TELOPT_TTYPE:
739			settimer(ttypesubopt);
740			break;
741
742		case TELOPT_TSPEED:
743			settimer(tspeedsubopt);
744			break;
745
746		case TELOPT_XDISPLOC:
747			settimer(xdisplocsubopt);
748			break;
749
750		case TELOPT_OLD_ENVIRON:
751			settimer(oenvironsubopt);
752			break;
753
754		case TELOPT_NEW_ENVIRON:
755			settimer(environsubopt);
756			break;
757
758		default:
759			break;
760		}
761		set_his_want_state_wont(option);
762		if (his_state_is_will(option))
763			send_dont(option, 0);
764	    } else {
765		switch (option) {
766		case TELOPT_TM:
767#if	defined(LINEMODE) && defined(KLUDGELINEMODE)
768			if (lmodetype < NO_AUTOKLUDGE) {
769				lmodetype = NO_LINEMODE;
770				clientstat(TELOPT_LINEMODE, WONT, 0);
771				send_will(TELOPT_SGA, 1);
772				send_will(TELOPT_ECHO, 1);
773			}
774#endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
775			break;
776
777#ifdef AUTHENTICATION
778		case TELOPT_AUTHENTICATION:
779			auth_finished(0, AUTH_REJECT);
780			break;
781#endif
782		default:
783			break;
784		}
785	    }
786	}
787	set_his_state_wont(option);
788
789}  /* end of wontoption */
790
791void
792send_will(int option, int init)
793{
794	if (init) {
795		if ((will_wont_resp[option] == 0 && my_state_is_will(option))||
796		    my_want_state_is_will(option))
797			return;
798		set_my_want_state_will(option);
799		will_wont_resp[option]++;
800	}
801	output_data((const char *)will, option);
802
803	DIAG(TD_OPTIONS, printoption("td: send will", option));
804}
805
806#if	!defined(LINEMODE) || !defined(KLUDGELINEMODE)
807/*
808 * When we get a DONT SGA, we will try once to turn it
809 * back on.  If the other side responds DONT SGA, we
810 * leave it at that.  This is so that when we talk to
811 * clients that understand KLUDGELINEMODE but not LINEMODE,
812 * we'll keep them in char-at-a-time mode.
813 */
814int turn_on_sga = 0;
815#endif
816
817void
818dooption(int option)
819{
820	int changeok = 0;
821
822	/*
823	 * Process client input.
824	 */
825
826	DIAG(TD_OPTIONS, printoption("td: recv do", option));
827
828	if (will_wont_resp[option]) {
829		will_wont_resp[option]--;
830		if (will_wont_resp[option] && my_state_is_will(option))
831			will_wont_resp[option]--;
832	}
833	if ((will_wont_resp[option] == 0) && (my_want_state_is_wont(option))) {
834		switch (option) {
835		case TELOPT_ECHO:
836#ifdef	LINEMODE
837# ifdef	KLUDGELINEMODE
838			if (lmodetype == NO_LINEMODE)
839# else
840			if (his_state_is_wont(TELOPT_LINEMODE))
841# endif
842#endif
843			{
844				init_termbuf();
845				tty_setecho(1);
846				set_termbuf();
847			}
848			changeok++;
849			break;
850
851		case TELOPT_BINARY:
852			init_termbuf();
853			tty_binaryout(1);
854			set_termbuf();
855			changeok++;
856			break;
857
858		case TELOPT_SGA:
859#if	defined(LINEMODE) && defined(KLUDGELINEMODE)
860			/*
861			 * If kludge linemode is in use, then we must
862			 * process an incoming do SGA for linemode
863			 * purposes.
864			 */
865			if (lmodetype == KLUDGE_LINEMODE) {
866				/*
867				 * Receipt of "do SGA" in kludge
868				 * linemode is the peer asking us to
869				 * turn off linemode.  Make note of
870				 * the request.
871				 */
872				clientstat(TELOPT_LINEMODE, WONT, 0);
873				/*
874				 * If linemode did not get turned off
875				 * then don't tell peer that we did.
876				 * Breaking here forces a wont SGA to
877				 * be returned.
878				 */
879				if (linemode)
880					break;
881			}
882#else
883			turn_on_sga = 0;
884#endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
885			changeok++;
886			break;
887
888		case TELOPT_STATUS:
889			changeok++;
890			break;
891
892		case TELOPT_TM:
893			/*
894			 * Special case for TM.  We send a WILL, but
895			 * pretend we sent a WONT.
896			 */
897			send_will(option, 0);
898			set_my_want_state_wont(option);
899			set_my_state_wont(option);
900			return;
901
902		case TELOPT_LOGOUT:
903			/*
904			 * When we get a LOGOUT option, respond
905			 * with a WILL LOGOUT, make sure that
906			 * it gets written out to the network,
907			 * and then just go away...
908			 */
909			set_my_want_state_will(TELOPT_LOGOUT);
910			send_will(TELOPT_LOGOUT, 0);
911			set_my_state_will(TELOPT_LOGOUT);
912			(void)netflush();
913			cleanup(0);
914			/* NOT REACHED */
915			break;
916
917#ifdef	ENCRYPTION
918		case TELOPT_ENCRYPT:
919			changeok++;
920			break;
921#endif	/* ENCRYPTION */
922		case TELOPT_LINEMODE:
923		case TELOPT_TTYPE:
924		case TELOPT_NAWS:
925		case TELOPT_TSPEED:
926		case TELOPT_LFLOW:
927		case TELOPT_XDISPLOC:
928#ifdef	TELOPT_ENVIRON
929		case TELOPT_NEW_ENVIRON:
930#endif
931		case TELOPT_OLD_ENVIRON:
932		default:
933			break;
934		}
935		if (changeok) {
936			set_my_want_state_will(option);
937			send_will(option, 0);
938		} else {
939			will_wont_resp[option]++;
940			send_wont(option, 0);
941		}
942	}
943	set_my_state_will(option);
944
945}  /* end of dooption */
946
947void
948send_wont(int option, int init)
949{
950	if (init) {
951		if ((will_wont_resp[option] == 0 && my_state_is_wont(option)) ||
952		    my_want_state_is_wont(option))
953			return;
954		set_my_want_state_wont(option);
955		will_wont_resp[option]++;
956	}
957	output_data((const char *)wont, option);
958
959	DIAG(TD_OPTIONS, printoption("td: send wont", option));
960}
961
962void
963dontoption(int option)
964{
965	/*
966	 * Process client input.
967	 */
968
969
970	DIAG(TD_OPTIONS, printoption("td: recv dont", option));
971
972	if (will_wont_resp[option]) {
973		will_wont_resp[option]--;
974		if (will_wont_resp[option] && my_state_is_wont(option))
975			will_wont_resp[option]--;
976	}
977	if ((will_wont_resp[option] == 0) && (my_want_state_is_will(option))) {
978		switch (option) {
979		case TELOPT_BINARY:
980			init_termbuf();
981			tty_binaryout(0);
982			set_termbuf();
983			break;
984
985		case TELOPT_ECHO:	/* we should stop echoing */
986#ifdef	LINEMODE
987# ifdef	KLUDGELINEMODE
988			if ((lmodetype != REAL_LINEMODE) &&
989			    (lmodetype != KLUDGE_LINEMODE))
990# else
991			if (his_state_is_wont(TELOPT_LINEMODE))
992# endif
993#endif
994			{
995				init_termbuf();
996				tty_setecho(0);
997				set_termbuf();
998			}
999			break;
1000
1001		case TELOPT_SGA:
1002#if	defined(LINEMODE) && defined(KLUDGELINEMODE)
1003			/*
1004			 * If kludge linemode is in use, then we
1005			 * must process an incoming do SGA for
1006			 * linemode purposes.
1007			 */
1008			if ((lmodetype == KLUDGE_LINEMODE) ||
1009			    (lmodetype == KLUDGE_OK)) {
1010				/*
1011				 * The client is asking us to turn
1012				 * linemode on.
1013				 */
1014				lmodetype = KLUDGE_LINEMODE;
1015				clientstat(TELOPT_LINEMODE, WILL, 0);
1016				/*
1017				 * If we did not turn line mode on,
1018				 * then what do we say?  Will SGA?
1019				 * This violates design of telnet.
1020				 * Gross.  Very Gross.
1021				 */
1022			}
1023			break;
1024#else
1025			set_my_want_state_wont(option);
1026			if (my_state_is_will(option))
1027				send_wont(option, 0);
1028			set_my_state_wont(option);
1029			if (turn_on_sga ^= 1)
1030				send_will(option, 1);
1031			return;
1032#endif	/* defined(LINEMODE) && defined(KLUDGELINEMODE) */
1033
1034		default:
1035			break;
1036		}
1037
1038		set_my_want_state_wont(option);
1039		if (my_state_is_will(option))
1040			send_wont(option, 0);
1041	}
1042	set_my_state_wont(option);
1043
1044}  /* end of dontoption */
1045
1046#ifdef	ENV_HACK
1047int env_ovar = -1;
1048int env_ovalue = -1;
1049#else	/* ENV_HACK */
1050# define env_ovar OLD_ENV_VAR
1051# define env_ovalue OLD_ENV_VALUE
1052#endif	/* ENV_HACK */
1053
1054/*
1055 * suboption()
1056 *
1057 *	Look at the sub-option buffer, and try to be helpful to the other
1058 * side.
1059 *
1060 *	Currently we recognize:
1061 *
1062 *	Terminal type is
1063 *	Linemode
1064 *	Window size
1065 *	Terminal speed
1066 */
1067void
1068suboption(void)
1069{
1070    int subchar;
1071
1072    DIAG(TD_OPTIONS, {netflush(); printsub('<', subpointer, SB_LEN()+2);});
1073
1074    subchar = SB_GET();
1075    switch (subchar) {
1076    case TELOPT_TSPEED: {
1077	int xspeed, rspeed;
1078
1079	if (his_state_is_wont(TELOPT_TSPEED))	/* Ignore if option disabled */
1080		break;
1081
1082	settimer(tspeedsubopt);
1083
1084	if (SB_EOF() || SB_GET() != TELQUAL_IS)
1085		return;
1086
1087	xspeed = atoi((char *)subpointer);
1088
1089	while (SB_GET() != ',' && !SB_EOF());
1090	if (SB_EOF())
1091		return;
1092
1093	rspeed = atoi((char *)subpointer);
1094	clientstat(TELOPT_TSPEED, xspeed, rspeed);
1095
1096	break;
1097
1098    }  /* end of case TELOPT_TSPEED */
1099
1100    case TELOPT_TTYPE: {		/* Yaaaay! */
1101	static char terminalname[41];
1102
1103	if (his_state_is_wont(TELOPT_TTYPE))	/* Ignore if option disabled */
1104		break;
1105	settimer(ttypesubopt);
1106
1107	if (SB_EOF() || SB_GET() != TELQUAL_IS) {
1108	    return;		/* ??? XXX but, this is the most robust */
1109	}
1110
1111	terminaltype = terminalname;
1112
1113	while ((terminaltype < (terminalname + sizeof terminalname-1)) &&
1114								    !SB_EOF()) {
1115	    int c;
1116
1117	    c = SB_GET();
1118	    if (isupper(c)) {
1119		c = tolower(c);
1120	    }
1121	    *terminaltype++ = c;    /* accumulate name */
1122	}
1123	*terminaltype = 0;
1124	terminaltype = terminalname;
1125	break;
1126    }  /* end of case TELOPT_TTYPE */
1127
1128    case TELOPT_NAWS: {
1129	int xwinsize, ywinsize;
1130
1131	if (his_state_is_wont(TELOPT_NAWS))	/* Ignore if option disabled */
1132		break;
1133
1134	if (SB_EOF())
1135		return;
1136	xwinsize = SB_GET() << 8;
1137	if (SB_EOF())
1138		return;
1139	xwinsize |= SB_GET();
1140	if (SB_EOF())
1141		return;
1142	ywinsize = SB_GET() << 8;
1143	if (SB_EOF())
1144		return;
1145	ywinsize |= SB_GET();
1146	clientstat(TELOPT_NAWS, xwinsize, ywinsize);
1147
1148	break;
1149
1150    }  /* end of case TELOPT_NAWS */
1151
1152#ifdef	LINEMODE
1153    case TELOPT_LINEMODE: {
1154	int request;
1155
1156	if (his_state_is_wont(TELOPT_LINEMODE))	/* Ignore if option disabled */
1157		break;
1158	/*
1159	 * Process linemode suboptions.
1160	 */
1161	if (SB_EOF())
1162	    break;		/* garbage was sent */
1163	request = SB_GET();	/* get will/wont */
1164
1165	if (SB_EOF())
1166	    break;		/* another garbage check */
1167
1168	if (request == LM_SLC) {  /* SLC is not preceeded by WILL or WONT */
1169		/*
1170		 * Process suboption buffer of slc's
1171		 */
1172		start_slc(1);
1173		do_opt_slc(subpointer, subend - subpointer);
1174		(void) end_slc(0);
1175		break;
1176	} else if (request == LM_MODE) {
1177		if (SB_EOF())
1178		    return;
1179		useeditmode = SB_GET();  /* get mode flag */
1180		clientstat(LM_MODE, 0, 0);
1181		break;
1182	}
1183
1184	if (SB_EOF())
1185	    break;
1186	switch (SB_GET()) {  /* what suboption? */
1187	case LM_FORWARDMASK:
1188		/*
1189		 * According to spec, only server can send request for
1190		 * forwardmask, and client can only return a positive response.
1191		 * So don't worry about it.
1192		 */
1193
1194	default:
1195		break;
1196	}
1197	break;
1198    }  /* end of case TELOPT_LINEMODE */
1199#endif
1200    case TELOPT_STATUS: {
1201	int mode;
1202
1203	if (SB_EOF())
1204	    break;
1205	mode = SB_GET();
1206	switch (mode) {
1207	case TELQUAL_SEND:
1208	    if (my_state_is_will(TELOPT_STATUS))
1209		send_status();
1210	    break;
1211
1212	case TELQUAL_IS:
1213	    break;
1214
1215	default:
1216	    break;
1217	}
1218	break;
1219    }  /* end of case TELOPT_STATUS */
1220
1221    case TELOPT_XDISPLOC: {
1222	if (SB_EOF() || SB_GET() != TELQUAL_IS)
1223		return;
1224	settimer(xdisplocsubopt);
1225	subpointer[SB_LEN()] = '\0';
1226	(void)setenv("DISPLAY", (char *)subpointer, 1);
1227	break;
1228    }  /* end of case TELOPT_XDISPLOC */
1229
1230#ifdef	TELOPT_NEW_ENVIRON
1231    case TELOPT_NEW_ENVIRON:
1232#endif
1233    case TELOPT_OLD_ENVIRON: {
1234	int c;
1235	char *cp, *varp, *valp;
1236
1237	if (SB_EOF())
1238		return;
1239	c = SB_GET();
1240	if (c == TELQUAL_IS) {
1241		if (subchar == TELOPT_OLD_ENVIRON)
1242			settimer(oenvironsubopt);
1243		else
1244			settimer(environsubopt);
1245	} else if (c != TELQUAL_INFO) {
1246		return;
1247	}
1248
1249#ifdef	TELOPT_NEW_ENVIRON
1250	if (subchar == TELOPT_NEW_ENVIRON) {
1251	    while (!SB_EOF()) {
1252		c = SB_GET();
1253		if ((c == NEW_ENV_VAR) || (c == ENV_USERVAR))
1254			break;
1255	    }
1256	} else
1257#endif
1258	{
1259#ifdef	ENV_HACK
1260	    /*
1261	     * We only want to do this if we haven't already decided
1262	     * whether or not the other side has its VALUE and VAR
1263	     * reversed.
1264	     */
1265	    if (env_ovar < 0) {
1266		int last = -1;		/* invalid value */
1267		int empty = 0;
1268		int got_var = 0, got_value = 0, got_uservar = 0;
1269
1270		/*
1271		 * The other side might have its VALUE and VAR values
1272		 * reversed.  To be interoperable, we need to determine
1273		 * which way it is.  If the first recognized character
1274		 * is a VAR or VALUE, then that will tell us what
1275		 * type of client it is.  If the fist recognized
1276		 * character is a USERVAR, then we continue scanning
1277		 * the suboption looking for two consecutive
1278		 * VAR or VALUE fields.  We should not get two
1279		 * consecutive VALUE fields, so finding two
1280		 * consecutive VALUE or VAR fields will tell us
1281		 * what the client is.
1282		 */
1283		SB_SAVE();
1284		while (!SB_EOF()) {
1285			c = SB_GET();
1286			switch(c) {
1287			case OLD_ENV_VAR:
1288				if (last < 0 || last == OLD_ENV_VAR
1289				    || (empty && (last == OLD_ENV_VALUE)))
1290					goto env_ovar_ok;
1291				got_var++;
1292				last = OLD_ENV_VAR;
1293				break;
1294			case OLD_ENV_VALUE:
1295				if (last < 0 || last == OLD_ENV_VALUE
1296				    || (empty && (last == OLD_ENV_VAR)))
1297					goto env_ovar_wrong;
1298				got_value++;
1299				last = OLD_ENV_VALUE;
1300				break;
1301			case ENV_USERVAR:
1302				/* count strings of USERVAR as one */
1303				if (last != ENV_USERVAR)
1304					got_uservar++;
1305				if (empty) {
1306					if (last == OLD_ENV_VALUE)
1307						goto env_ovar_ok;
1308					if (last == OLD_ENV_VAR)
1309						goto env_ovar_wrong;
1310				}
1311				last = ENV_USERVAR;
1312				break;
1313			case ENV_ESC:
1314				if (!SB_EOF())
1315					c = SB_GET();
1316				/* FALLTHROUGH */
1317			default:
1318				empty = 0;
1319				continue;
1320			}
1321			empty = 1;
1322		}
1323		if (empty) {
1324			if (last == OLD_ENV_VALUE)
1325				goto env_ovar_ok;
1326			if (last == OLD_ENV_VAR)
1327				goto env_ovar_wrong;
1328		}
1329		/*
1330		 * Ok, the first thing was a USERVAR, and there
1331		 * are not two consecutive VAR or VALUE commands,
1332		 * and none of the VAR or VALUE commands are empty.
1333		 * If the client has sent us a well-formed option,
1334		 * then the number of VALUEs received should always
1335		 * be less than or equal to the number of VARs and
1336		 * USERVARs received.
1337		 *
1338		 * If we got exactly as many VALUEs as VARs and
1339		 * USERVARs, the client has the same definitions.
1340		 *
1341		 * If we got exactly as many VARs as VALUEs and
1342		 * USERVARS, the client has reversed definitions.
1343		 */
1344		if (got_uservar + got_var == got_value) {
1345	    env_ovar_ok:
1346			env_ovar = OLD_ENV_VAR;
1347			env_ovalue = OLD_ENV_VALUE;
1348		} else if (got_uservar + got_value == got_var) {
1349	    env_ovar_wrong:
1350			env_ovar = OLD_ENV_VALUE;
1351			env_ovalue = OLD_ENV_VAR;
1352			DIAG(TD_OPTIONS,
1353			    output_data("ENVIRON VALUE and VAR are reversed!\r\n"));
1354
1355		}
1356	    }
1357	    SB_RESTORE();
1358#endif
1359
1360	    while (!SB_EOF()) {
1361		c = SB_GET();
1362		if ((c == env_ovar) || (c == ENV_USERVAR))
1363			break;
1364	    }
1365	}
1366
1367	if (SB_EOF())
1368		return;
1369
1370	cp = varp = (char *)subpointer;
1371	valp = 0;
1372
1373	while (!SB_EOF()) {
1374		c = SB_GET();
1375		if (subchar == TELOPT_OLD_ENVIRON) {
1376			if (c == env_ovar)
1377				c = NEW_ENV_VAR;
1378			else if (c == env_ovalue)
1379				c = NEW_ENV_VALUE;
1380		}
1381		switch (c) {
1382
1383		case NEW_ENV_VALUE:
1384			*cp = '\0';
1385			cp = valp = (char *)subpointer;
1386			break;
1387
1388		case NEW_ENV_VAR:
1389		case ENV_USERVAR:
1390			*cp = '\0';
1391			if (valp)
1392				(void)setenv(varp, valp, 1);
1393			else
1394				unsetenv(varp);
1395			cp = varp = (char *)subpointer;
1396			valp = 0;
1397			break;
1398
1399		case ENV_ESC:
1400			if (SB_EOF())
1401				break;
1402			c = SB_GET();
1403			/* FALLTHROUGH */
1404		default:
1405			*cp++ = c;
1406			break;
1407		}
1408	}
1409	*cp = '\0';
1410	if (valp)
1411		(void)setenv(varp, valp, 1);
1412	else
1413		unsetenv(varp);
1414	break;
1415    }  /* end of case TELOPT_NEW_ENVIRON */
1416#ifdef	AUTHENTICATION
1417    case TELOPT_AUTHENTICATION:
1418	if (SB_EOF())
1419		break;
1420	switch(SB_GET()) {
1421	case TELQUAL_SEND:
1422	case TELQUAL_REPLY:
1423		/*
1424		 * These are sent by us and cannot be sent by
1425		 * the client.
1426		 */
1427		break;
1428	case TELQUAL_IS:
1429		auth_is(subpointer, SB_LEN());
1430		break;
1431	case TELQUAL_NAME:
1432		auth_name(subpointer, SB_LEN());
1433		break;
1434	}
1435	break;
1436#endif
1437#ifdef	ENCRYPTION
1438    case TELOPT_ENCRYPT:
1439	if (SB_EOF())
1440		break;
1441	switch(SB_GET()) {
1442	case ENCRYPT_SUPPORT:
1443		encrypt_support(subpointer, SB_LEN());
1444		break;
1445	case ENCRYPT_IS:
1446		encrypt_is(subpointer, SB_LEN());
1447		break;
1448	case ENCRYPT_REPLY:
1449		encrypt_reply(subpointer, SB_LEN());
1450		break;
1451	case ENCRYPT_START:
1452		encrypt_start(subpointer, SB_LEN());
1453		break;
1454	case ENCRYPT_END:
1455		encrypt_end();
1456		break;
1457	case ENCRYPT_REQSTART:
1458		encrypt_request_start(subpointer, SB_LEN());
1459		break;
1460	case ENCRYPT_REQEND:
1461		/*
1462		 * We can always send an REQEND so that we cannot
1463		 * get stuck encrypting.  We should only get this
1464		 * if we have been able to get in the correct mode
1465		 * anyhow.
1466		 */
1467		encrypt_request_end();
1468		break;
1469	case ENCRYPT_ENC_KEYID:
1470		encrypt_enc_keyid(subpointer, SB_LEN());
1471		break;
1472	case ENCRYPT_DEC_KEYID:
1473		encrypt_dec_keyid(subpointer, SB_LEN());
1474		break;
1475	default:
1476		break;
1477	}
1478	break;
1479#endif	/* ENCRYPTION */
1480
1481    default:
1482	break;
1483    }  /* end of switch */
1484
1485}  /* end of suboption */
1486
1487static void
1488doclientstat(void)
1489{
1490	clientstat(TELOPT_LINEMODE, WILL, 0);
1491}
1492
1493#define	ADD(c)	 *ncp++ = c
1494#define	ADD_DATA(c) { *ncp++ = c; if (c == SE || c == IAC) *ncp++ = c; }
1495void
1496send_status(void)
1497{
1498	unsigned char statusbuf[256];
1499	unsigned char *ncp;
1500	unsigned char i;
1501
1502	ncp = statusbuf;
1503
1504	netflush();	/* get rid of anything waiting to go out */
1505
1506	ADD(IAC);
1507	ADD(SB);
1508	ADD(TELOPT_STATUS);
1509	ADD(TELQUAL_IS);
1510
1511	/*
1512	 * We check the want_state rather than the current state,
1513	 * because if we received a DO/WILL for an option that we
1514	 * don't support, and the other side didn't send a DONT/WONT
1515	 * in response to our WONT/DONT, then the "state" will be
1516	 * WILL/DO, and the "want_state" will be WONT/DONT.  We
1517	 * need to go by the latter.
1518	 */
1519	for (i = 0; i < (unsigned char)NTELOPTS; i++) {
1520		if (my_want_state_is_will(i)) {
1521			ADD(WILL);
1522			ADD_DATA(i);
1523			if (i == IAC)
1524				ADD(IAC);
1525		}
1526		if (his_want_state_is_will(i)) {
1527			ADD(DO);
1528			ADD_DATA(i);
1529			if (i == IAC)
1530				ADD(IAC);
1531		}
1532	}
1533
1534	if (his_want_state_is_will(TELOPT_LFLOW)) {
1535		ADD(SB);
1536		ADD(TELOPT_LFLOW);
1537		if (flowmode) {
1538			ADD(LFLOW_ON);
1539		} else {
1540			ADD(LFLOW_OFF);
1541		}
1542		ADD(SE);
1543
1544		if (restartany >= 0) {
1545			ADD(SB);
1546			ADD(TELOPT_LFLOW);
1547			if (restartany) {
1548				ADD(LFLOW_RESTART_ANY);
1549			} else {
1550				ADD(LFLOW_RESTART_XON);
1551			}
1552			ADD(SE);
1553		}
1554	}
1555
1556#ifdef	LINEMODE
1557	if (his_want_state_is_will(TELOPT_LINEMODE)) {
1558		unsigned char *cp, *cpe;
1559		int len;
1560
1561		ADD(SB);
1562		ADD(TELOPT_LINEMODE);
1563		ADD(LM_MODE);
1564		ADD_DATA(editmode);
1565		ADD(SE);
1566
1567		ADD(SB);
1568		ADD(TELOPT_LINEMODE);
1569		ADD(LM_SLC);
1570		start_slc(0);
1571		send_slc();
1572		len = end_slc(&cp);
1573		for (cpe = cp + len; cp < cpe; cp++)
1574			ADD_DATA(*cp);
1575		ADD(SE);
1576	}
1577#endif	/* LINEMODE */
1578
1579	ADD(IAC);
1580	ADD(SE);
1581
1582	output_datalen(statusbuf, ncp - statusbuf);
1583	netflush();	/* Send it on its way */
1584
1585	DIAG(TD_OPTIONS,
1586		{printsub('>', statusbuf, ncp - statusbuf); netflush();});
1587}
1588
1589/*
1590 * This function appends data to nfrontp and advances nfrontp.
1591 * Returns the number of characters written altogether (the
1592 * buffer may have been flushed in the process).
1593 */
1594
1595int
1596output_data(const char *format, ...)
1597{
1598	va_list args;
1599	int len;
1600	char *buf;
1601
1602	va_start(args, format);
1603	if ((len = vasprintf(&buf, format, args)) == -1) {
1604		va_end(args);
1605		return -1;
1606	}
1607	output_datalen(buf, len);
1608	va_end(args);
1609	free(buf);
1610	return (len);
1611}
1612
1613void
1614output_datalen(const char *buf, int len)
1615{
1616	int remaining, copied;
1617
1618	remaining = BUFSIZ - (nfrontp - netobuf);
1619	while (len > 0) {
1620		/* Free up enough space if the room is too low*/
1621		if ((len > BUFSIZ ? BUFSIZ : len) > remaining) {
1622			netflush();
1623			remaining = BUFSIZ - (nfrontp - netobuf);
1624		}
1625
1626		/* Copy out as much as will fit */
1627		copied = remaining > len ? len : remaining;
1628		memmove(nfrontp, buf, copied);
1629		nfrontp += copied;
1630		len -= copied;
1631		remaining -= copied;
1632		buf += copied;
1633	}
1634	return;
1635}
1636