summaryrefslogtreecommitdiff
path: root/usr.sbin/lpd/frontend_lpr.c
blob: ad9c94f92afe080c896a558c01854e0fe9704174 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
/*	$OpenBSD: frontend_lpr.c,v 1.1 2018/04/27 16:14:35 eric Exp $	*/

/*
 * Copyright (c) 2017 Eric Faurot <eric@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <netdb.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "lpd.h"
#include "lp.h"

#include "io.h"
#include "log.h"
#include "proc.h"

#define SERVER_TIMEOUT	30000
#define CLIENT_TIMEOUT	 5000

#define	MAXARG	50

#define	F_ZOMBIE	0x1
#define	F_WAITADDRINFO	0x2

#define STATE_READ_COMMAND	0
#define STATE_READ_FILE		1

struct lpr_conn {
	SPLAY_ENTRY(lpr_conn)	 entry;
	uint32_t		 id;
	char			 hostname[NI_MAXHOST];
	struct io		*io;
	int			 state;
	int			 flags;
	int			 recvjob;
	int			 recvcf;
	size_t			 expect;
	FILE			*ofp;	/* output file when receiving data */
	int			 ifd;	/* input file for displayq/rmjob */

	char			*cmd;
	int			 ai_done;
	struct addrinfo		*ai;
	struct io		*iofwd;
};

SPLAY_HEAD(lpr_conn_tree, lpr_conn);

static int lpr_conn_cmp(struct lpr_conn *, struct lpr_conn *);
SPLAY_PROTOTYPE(lpr_conn_tree, lpr_conn, entry, lpr_conn_cmp);

static void lpr_on_allowedhost(struct lpr_conn *, const char *, const char *);
static void lpr_on_recvjob(struct lpr_conn *, int);
static void lpr_on_recvjob_file(struct lpr_conn *, int, size_t, int, int);
static void lpr_on_request(struct lpr_conn *, int, const char *, const char *);
static void lpr_on_getaddrinfo(void *, int, struct addrinfo *);

static void lpr_io_dispatch(struct io *, int, void *);
static int  lpr_readcommand(struct lpr_conn *);
static int  lpr_readfile(struct lpr_conn *);
static int  lpr_parsejobfilter(struct lpr_conn *, struct lp_jobfilter *,
    int, char **);

static void lpr_free(struct lpr_conn *);
static void lpr_close(struct lpr_conn *);
static void lpr_ack(struct lpr_conn *, char);
static void lpr_reply(struct lpr_conn *, const char *);
static void lpr_stream(struct lpr_conn *);
static void lpr_forward(struct lpr_conn *);

static void lpr_iofwd_dispatch(struct io *, int, void *);

static struct lpr_conn_tree conns;

void
lpr_init(void)
{
	SPLAY_INIT(&conns);
}

void
lpr_conn(uint32_t connid, struct listener *l, int sock,
    const struct sockaddr *sa)
{
	struct lpr_conn *conn;

	if ((conn = calloc(1, sizeof(*conn))) == NULL) {
		log_warn("%s: calloc", __func__);
		close(sock);
		frontend_conn_closed(connid);
		return;
	}
	conn->id = connid;
	conn->ifd = -1;
	conn->io = io_new();
	if (conn->io == NULL) {
		log_warn("%s: io_new", __func__);
		free(conn);
		close(sock);
		frontend_conn_closed(connid);
		return;
	}
	SPLAY_INSERT(lpr_conn_tree, &conns, conn);
	io_set_callback(conn->io, lpr_io_dispatch, conn);
	io_set_timeout(conn->io, CLIENT_TIMEOUT);
	io_set_write(conn->io);
	io_attach(conn->io, sock);

	conn->state = STATE_READ_COMMAND;
	m_create(p_engine, IMSG_LPR_ALLOWEDHOST, conn->id, 0, -1);
	m_add_sockaddr(p_engine, sa);
	m_close(p_engine);
}

void
lpr_dispatch_engine(struct imsgproc *proc, struct imsg *imsg)
{
	struct lpr_conn *conn = NULL, key;
	const char *hostname, *reject, *cmd;
	size_t sz;
	int ack, cf = 0;

	key.id = imsg->hdr.peerid;
	if (key.id) {
		conn = SPLAY_FIND(lpr_conn_tree, &conns, &key);
		if (conn == NULL) {
			log_debug("%08x dead-session", key.id);
			if (imsg->fd != -1)
				close(imsg->fd);
			return;
		}
	}

	switch (imsg->hdr.type) {
	case IMSG_LPR_ALLOWEDHOST:
		m_get_string(proc, &hostname);
		m_get_string(proc, &reject);
		m_end(proc);
		lpr_on_allowedhost(conn, hostname, reject[0] ? reject : NULL);
		break;

	case IMSG_LPR_RECVJOB:
		m_get_int(proc, &ack);
		m_end(proc);
		lpr_on_recvjob(conn, ack);
		break;

	case IMSG_LPR_RECVJOB_CF:
		cf = 1;
	case IMSG_LPR_RECVJOB_DF:
		m_get_int(proc, &ack);
		m_get_size(proc, &sz);
		m_end(proc);
		lpr_on_recvjob_file(conn, ack, sz, cf, imsg->fd);
		break;

	case IMSG_LPR_DISPLAYQ:
	case IMSG_LPR_RMJOB:
		m_get_string(proc, &hostname);
		m_get_string(proc, &cmd);
		m_end(proc);
		lpr_on_request(conn, imsg->fd, hostname[0] ? hostname : NULL,
		    cmd[0] ? cmd : NULL);
		break;

	default:
		fatalx("%s: unexpected imsg %s", __func__,
		    log_fmt_imsgtype(imsg->hdr.type));
	}
}

static void
lpr_on_allowedhost(struct lpr_conn *conn, const char *hostname,
    const char *reject)
{
	strlcpy(conn->hostname, hostname, sizeof(conn->hostname));
	if (reject)
		lpr_reply(conn, reject);
	else
		io_set_read(conn->io);
}

static void
lpr_on_recvjob(struct lpr_conn *conn, int ack)
{
	if (ack == LPR_ACK)
		conn->recvjob = 1;
	else
		log_debug("%08x recvjob failed", conn->id);
	lpr_ack(conn, ack);
}

static void
lpr_on_recvjob_file(struct lpr_conn *conn, int ack, size_t sz, int cf, int fd)
{
	if (ack != LPR_ACK) {
		lpr_ack(conn, ack);
		return;
	}

	if (fd == -1) {
		log_warnx("%s: failed to get fd", __func__);
		lpr_ack(conn, LPR_NACK);
		return;
	}

	conn->ofp = fdopen(fd, "w");
	if (conn->ofp == NULL) {
		log_warn("%s: fdopen", __func__);
		close(fd);
		lpr_ack(conn, LPR_NACK);
		return;
	}

	conn->expect = sz;
	if (cf)
		conn->recvcf = cf;
	conn->state = STATE_READ_FILE;

	lpr_ack(conn, LPR_ACK);
}

static void
lpr_on_request(struct lpr_conn *conn, int fd, const char *hostname,
    const char *cmd)
{
	struct addrinfo hints;

	if (fd == -1) {
		log_warnx("%s: no fd received", __func__);
		lpr_close(conn);
		return;
	}

	log_debug("%08x stream init", conn->id);
	conn->ifd = fd;

	/* Prepare for command forwarding if necessary. */
	if (cmd) {
		log_debug("%08x forwarding to %s: \\%d%s", conn->id, hostname,
		    cmd[0], cmd + 1);
		conn->cmd = strdup(cmd);
		if (conn->cmd == NULL)
			log_warn("%s: strdup", __func__);
		else {
			memset(&hints, 0, sizeof(hints));
			hints.ai_socktype = SOCK_STREAM;
			conn->flags |= F_WAITADDRINFO;
			/*
			 * The callback might run immediatly, so conn->ifd
			 * must be set before, to block lpr_forward().
			 */
			resolver_getaddrinfo(hostname, "printer", &hints,
			    lpr_on_getaddrinfo, conn);
		}
	}

	lpr_stream(conn);
}

static void
lpr_on_getaddrinfo(void *arg, int r, struct addrinfo *ai)
{
	struct lpr_conn *conn = arg;

	conn->flags &= ~F_WAITADDRINFO;
	if (conn->flags & F_ZOMBIE) {
		if (ai)
			freeaddrinfo(ai);
		lpr_free(conn);
	}
	else {
		conn->ai_done = 1;
		conn->ai = ai;
		lpr_forward(conn);
	}
}

static void
lpr_io_dispatch(struct io *io, int evt, void *arg)
{
	struct lpr_conn *conn = arg;
	int r;

	switch (evt) {
	case IO_DATAIN:
		switch(conn->state) {
		case STATE_READ_COMMAND:
			r = lpr_readcommand(conn);
			break;
		case STATE_READ_FILE:
			r = lpr_readfile(conn);
			break;
		default:
			fatal("%s: unexpected state %d", __func__, conn->state);
		}

		if (r == 0)
			io_set_write(conn->io);
		return;

	case IO_LOWAT:
		if (conn->recvjob)
			io_set_read(conn->io);
		else if (conn->ifd != -1)
			lpr_stream(conn);
		else if (conn->cmd == NULL)
			lpr_close(conn);
		return;

	case IO_DISCONNECTED:
		log_debug("%08x disconnected", conn->id);
		/*
		 * Some clients don't wait for the last acknowledgment to close
		 * the session.  So just consider it is closed normally.
		 */
	case IO_CLOSED:
		if (conn->recvcf && conn->state == STATE_READ_COMMAND) {
			/*
			 * Commit the transaction if we received a control file
			 * and the last file was received correctly.
			 */
			m_compose(p_engine, IMSG_LPR_RECVJOB_COMMIT, conn->id,
			    0, -1, NULL, 0);
			conn->recvjob = 0;
		}
		break;

	case IO_TIMEOUT:
		log_debug("%08x timeout", conn->id);
		break;

	case IO_ERROR:
		log_debug("%08x io-error", conn->id);
		break;

	default:
		fatalx("%s: unexpected event %d", __func__, evt);
	}

	lpr_close(conn);
}

static int
lpr_readcommand(struct lpr_conn *conn)
{
	struct lp_jobfilter jf;
	size_t count;
	const char *errstr;
	char *argv[MAXARG], *line;
	int i, argc, cmd;

	line = io_getline(conn->io, NULL);
	if (line == NULL) {
		if (io_datalen(conn->io) >= LPR_MAXCMDLEN) {
			lpr_reply(conn, "Request line too long");
			return 0;
		}
		return -1;
	}

	cmd = line[0];
	line++;

	if (cmd == 0) {
		lpr_reply(conn, "No command");
		return 0;
	}

	log_debug("%08x cmd \\%d", conn->id, cmd);

	/* Parse the command. */
	for (argc = 0; argc < MAXARG; ) {
		argv[argc] = strsep(&line, " \t");
		if (argv[argc] == NULL)
			break;
		if (argv[argc][0] != '\0')
			argc++;
	}
	if (argc == MAXARG) {
		lpr_reply(conn, "Argument list too long");
		return 0;
	}

	if (argc == 0) {
		lpr_reply(conn, "No queue specified");
		return 0;
	}

#define CMD(c)    ((int)(c))
#define SUBCMD(c) (0x100 | (int)(c))

	if (conn->recvjob)
		cmd |= 0x100;
	switch (cmd) {
	case CMD('\1'):	/* PRINT <prn> */
		m_create(p_engine, IMSG_LPR_PRINTJOB, 0, 0, -1);
		m_add_string(p_engine, argv[0]);
		m_close(p_engine);
		lpr_ack(conn, LPR_ACK);
		return 0;

	case CMD('\2'):	/* RECEIVE JOB <prn> */
		m_create(p_engine, IMSG_LPR_RECVJOB, conn->id, 0, -1);
		m_add_string(p_engine, conn->hostname);
		m_add_string(p_engine, argv[0]);
		m_close(p_engine);
		return 0;

	case CMD('\3'):	/* QUEUE STATE SHORT <prn> [job#...] [user..] */
	case CMD('\4'):	/* QUEUE STATE LONG  <prn> [job#...] [user..] */
		if (lpr_parsejobfilter(conn, &jf, argc - 1, argv + 1) == -1)
			return 0;

		m_create(p_engine, IMSG_LPR_DISPLAYQ, conn->id, 0, -1);
		m_add_int(p_engine, (cmd == '\3') ? 0 : 1);
		m_add_string(p_engine, conn->hostname);
		m_add_string(p_engine, argv[0]);
		m_add_int(p_engine, jf.njob);
		for (i = 0; i < jf.njob; i++)
			m_add_int(p_engine, jf.jobs[i]);
		m_add_int(p_engine, jf.nuser);
		for (i = 0; i < jf.nuser; i++)
			m_add_string(p_engine, jf.users[i]);
		m_close(p_engine);
		return 0;

	case CMD('\5'):	/* REMOVE JOBS <prn> <agent> [job#...] [user..] */
		if (argc < 2) {
			lpr_reply(conn, "No agent specified");
			return 0;
		}
		if (lpr_parsejobfilter(conn, &jf, argc - 2, argv + 2) == -1)
			return 0;

		m_create(p_engine, IMSG_LPR_RMJOB, conn->id, 0, -1);
		m_add_string(p_engine, conn->hostname);
		m_add_string(p_engine, argv[0]);
		m_add_string(p_engine, argv[1]);
		m_add_int(p_engine, jf.njob);
		for (i = 0; i < jf.njob; i++)
			m_add_int(p_engine, jf.jobs[i]);
		m_add_int(p_engine, jf.nuser);
		for (i = 0; i < jf.nuser; i++)
			m_add_string(p_engine, jf.users[i]);
		m_close(p_engine);
		return 0;

	case SUBCMD('\1'):	/* ABORT */
		m_compose(p_engine, IMSG_LPR_RECVJOB_CLEAR, conn->id, 0, -1,
		    NULL, 0);
		conn->recvcf = 0;
		lpr_ack(conn, LPR_ACK);
		return 0;

	case SUBCMD('\2'):	/* CONTROL FILE <size> <filename> */
	case SUBCMD('\3'):	/* DATA FILE    <size> <filename> */
		if (argc != 2) {
			log_debug("%08x invalid number of argument", conn->id);
			lpr_ack(conn, LPR_NACK);
			return 0;
		}
		errstr = NULL;
		count = strtonum(argv[0], 1, LPR_MAXFILESIZE, &errstr);
		if (errstr) {
			log_debug("%08x invalid file size: %s", conn->id,
			    strerror(errno));
			lpr_ack(conn, LPR_NACK);
			return 0;
		}

		if (cmd == SUBCMD('\2')) {
			if (conn->recvcf) {
				log_debug("%08x cf file already received",
				    conn->id);
				lpr_ack(conn, LPR_NACK);
				return 0;
			}
			m_create(p_engine, IMSG_LPR_RECVJOB_CF, conn->id, 0,
			    -1);
		}
		else
			m_create(p_engine, IMSG_LPR_RECVJOB_DF, conn->id, 0,
			    -1);
		m_add_size(p_engine, count);
		m_add_string(p_engine, argv[1]);
		m_close(p_engine);
		return 0;

	default:
		if (conn->recvjob)
			lpr_reply(conn, "Protocol error");
		else
			lpr_reply(conn, "Illegal service request");
		return 0;
	}
}

static int
lpr_readfile(struct lpr_conn *conn)
{
	size_t len, w;
	char *data;

	if (conn->expect) {
		/* Read file content. */
		data = io_data(conn->io);
		len = io_datalen(conn->io);
		if (len > conn->expect)
			len = conn->expect;

		log_debug("%08x %zu bytes received", conn->id, len);

		w = fwrite(data, 1, len, conn->ofp);
		if (w != len) {
			log_warnx("%s: fwrite", __func__);
			lpr_close(conn);
			return -1;
		}
		io_drop(conn->io, w);
		conn->expect -= w;
		if (conn->expect)
			return -1;

		fclose(conn->ofp);
		conn->ofp = NULL;

		log_debug("%08x file received", conn->id);
	}

	/* Try to read '\0'. */
	len = io_datalen(conn->io);
	if (len == 0)
		return -1;
	data = io_data(conn->io);
	io_drop(conn->io, 1);

	log_debug("%08x eof %d", conn->id, (int)*data);

	if (*data != '\0') {
		lpr_close(conn);
		return -1;
	}

	conn->state = STATE_READ_COMMAND;
	lpr_ack(conn, LPR_ACK);
	return 0;
}

static int
lpr_parsejobfilter(struct lpr_conn *conn, struct lp_jobfilter *jf, int argc,
    char **argv)
{
	const char *errstr;
	char *arg;
	int i, jobnum;

	memset(jf, 0, sizeof(*jf));

	for (i = 0; i < argc; i++) {
		arg = argv[i];
		if (isdigit((unsigned int)arg[0])) {
			if (jf->njob == LP_MAXREQUESTS) {
				lpr_reply(conn, "Too many requests");
				return -1;
			}
			errstr = NULL;
			jobnum = strtonum(arg, 0, INT_MAX, &errstr);
			if (errstr) {
				lpr_reply(conn, "Invalid job number");
				return -1;
			}
			jf->jobs[jf->njob++] = jobnum;
		}
		else {
			if (jf->nuser == LP_MAXUSERS) {
				lpr_reply(conn, "Too many users");
				return -1;
			}
			jf->users[jf->nuser++] = arg;
		}
	}

	return 0;
}

static void
lpr_free(struct lpr_conn *conn)
{
	if ((conn->flags & F_WAITADDRINFO) == 0)
		free(conn);
}

static void
lpr_close(struct lpr_conn *conn)
{
	uint32_t connid = conn->id;

	SPLAY_REMOVE(lpr_conn_tree, &conns, conn);

	if (conn->recvjob)
		m_compose(p_engine, IMSG_LPR_RECVJOB_ROLLBACK, conn->id, 0, -1,
		    NULL, 0);

	io_free(conn->io);
	free(conn->cmd);
	if (conn->ofp)
		fclose(conn->ofp);
	if (conn->ifd != -1)
		close(conn->ifd);
	if (conn->ai)
		freeaddrinfo(conn->ai);
	if (conn->iofwd)
		io_free(conn->iofwd);

	conn->flags |= F_ZOMBIE;
	lpr_free(conn);

	frontend_conn_closed(connid);
}

static void
lpr_ack(struct lpr_conn *conn, char c)
{
	if (c == 0)
		log_debug("%08x ack", conn->id);
	else
		log_debug("%08x nack %d", conn->id, (int)c);

	io_write(conn->io, &c, 1);
}

static void
lpr_reply(struct lpr_conn *conn, const char *s)
{
	log_debug("%08x reply: %s", conn->id, s);

	io_printf(conn->io, "%s\n", s);
}

/*
 * Stream reponse file to the client.
 */
static void
lpr_stream(struct lpr_conn *conn)
{
	char buf[BUFSIZ];
	ssize_t r;

	for (;;) {
		if (io_queued(conn->io) > 65536)
			return;

		r = read(conn->ifd, buf, sizeof(buf));
		if (r == -1) {
			if (errno == EINTR)
				continue;
			log_warn("%s: read", __func__);
			break;
		}

		if (r == 0) {
			log_debug("%08x stream done", conn->id);
			break;
		}
		log_debug("%08x stream %zu bytes", conn->id, r);

		if (io_write(conn->io, buf, r) == -1) {
			log_warn("%s: io_write", __func__);
			break;
		}
	}

	close(conn->ifd);
	conn->ifd = -1;

	if (conn->cmd)
		lpr_forward(conn);

	else if (io_queued(conn->io) == 0)
		lpr_close(conn);
}

/*
 * Forward request to the remote printer.
 */
static void
lpr_forward(struct lpr_conn *conn)
{
	/*
	 * Do not start forwarding the command if the address is not resolved
	 * or if the local response is still being sent to the client.
	 */
	if (!conn->ai_done || conn->ifd == -1)
		return;

	if (conn->ai == NULL) {
		if (io_queued(conn->io) == 0)
			lpr_close(conn);
		return;
	}

	log_debug("%08x forward start", conn->id);

	conn->iofwd = io_new();
	if (conn->iofwd == NULL) {
		log_warn("%s: io_new", __func__);
		if (io_queued(conn->io) == 0)
			lpr_close(conn);
		return;
	}
	io_set_callback(conn->iofwd, lpr_iofwd_dispatch, conn);
	io_set_timeout(conn->io, SERVER_TIMEOUT);
	io_connect(conn->iofwd, conn->ai);
	conn->ai = NULL;
}

static void
lpr_iofwd_dispatch(struct io *io, int evt, void *arg)
{
	struct lpr_conn *conn = arg;

	switch (evt) {
	case IO_CONNECTED:
		log_debug("%08x forward connected", conn->id);
		/* Send the request. */
		io_print(io, conn->cmd);
		io_print(io, "\n");
		io_set_write(io);
		return;

	case IO_DATAIN:
		/* Relay. */
		io_write(conn->io, io_data(io), io_datalen(io));
		io_drop(io, io_datalen(io));
		return;

	case IO_LOWAT:
		/* Read response. */
		io_set_read(io);
		return;

	case IO_CLOSED:
		break;

	case IO_DISCONNECTED:
		log_debug("%08x forward disconnected", conn->id);
		break;

	case IO_TIMEOUT:
		log_debug("%08x forward timeout", conn->id);
		break;

	case IO_ERROR:
		log_debug("%08x forward io-error", conn->id);
		break;

	default:
		fatalx("%s: unexpected event %d", __func__, evt);
	}

	log_debug("%08x forward done", conn->id);

	io_free(io);
	free(conn->cmd);
	conn->cmd = NULL;
	conn->iofwd = NULL;
	if (io_queued(conn->io) == 0)
		lpr_close(conn);
}

static int
lpr_conn_cmp(struct lpr_conn *a, struct lpr_conn *b)
{
	if (a->id < b->id)
		return -1;
	if (a->id > b->id)
		return 1;
	return 0;
}

SPLAY_GENERATE(lpr_conn_tree, lpr_conn, entry, lpr_conn_cmp);