aboutsummaryrefslogtreecommitdiff
path: root/kamirepl.c
blob: 15e7e7bf93516a927cc870960e3b520cbcebc1d1 (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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
/*
 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
 *
 * 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 "compat.h"

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

#include <netdb.h>

#include <assert.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <tls.h>
#include <unistd.h>

#include "kamid.h"
#include "log.h"
#include "utils.h"

#define DEBUG_PACKETS 0

#define PROMPT "=% "

/* flags */
int			 verbose;
int			 tls;
const char		*keypath;
const char		*crtpath;
const char		*host;
const char		*port;

/* state */
struct tls_config	*tlsconf;
struct tls		*ctx;
struct bufferevent	*bev, *inbev;

static void ATTR_DEAD	 usage(int);

static void		 sig_handler(int, short, void *);

static int		 openconn(void);
static void		 mark_nonblock(int);

static void		 tls_readcb(int, short, void *);
static void		 tls_writecb(int, short, void *);

static void		 client_read(struct bufferevent *, void *);
static void		 client_write(struct bufferevent *, void *);
static void		 client_error(struct bufferevent *, short, void *);

static void		 repl_read(struct bufferevent *, void *);
static void		 repl_error(struct bufferevent *, short, void *);
static void		 write_hdr(uint32_t, uint8_t, uint16_t);
static void		 write_hdr_auto(uint32_t, uint8_t);
static void		 write_str(uint16_t, const char *);
static void		 write_str_auto(const char *);
static void		 write_fid(uint32_t);
static void		 write_tag(uint16_t);

static void		 excmd_version(const char **, int);
static void		 excmd_attach(const char **, int);
static void		 excmd_clunk(const char **, int);
static void		 excmd_flush(const char **, int);
static void		 excmd_walk(const char ** , int);
static void		 excmd(const char **, int);

static const char	*pp_qid_type(uint8_t);
static void		 pp_qid(const uint8_t *, uint32_t);
static void		 pp_msg(uint32_t, uint8_t, uint16_t, const uint8_t *);
static void		 handle_9p(const uint8_t *, size_t);
static void		 clr(void);
static void		 prompt(void);

static void ATTR_DEAD
usage(int ret)
{
	fprintf(stderr,
	    "usage: %s [-chv] [-C crt] [-K key] [-H host] [-P port]\n",
	    getprogname());
	fprintf(stderr, PACKAGE_NAME " suite version " PACKAGE_VERSION "\n");
	exit(ret);
}

static void
sig_handler(int sig, short event, void *d)
{
	/*
	 * Normal signal handler rules don't apply because libevent
	 * decouples for us.
	 */

	switch (sig) {
	case SIGINT:
	case SIGTERM:
		clr();
		log_warnx("Shutting down...");
		event_loopbreak();
		return;
	default:
		fatalx("unexpected signal %d", sig);
	}
}

static int
openconn(void)
{
	struct addrinfo hints, *res, *res0;
	int error;
	int save_errno;
	int s;
	const char *cause = NULL;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	if ((error = getaddrinfo(host, port, &hints, &res0))) {
		warnx("%s", gai_strerror(error));
		return -1;
	}

	s = -1;
	for (res = res0; res; res = res->ai_next) {
		s = socket(res->ai_family, res->ai_socktype,
		    res->ai_protocol);
		if (s == -1) {
			cause = "socket";
			continue;
		}

		if (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
			cause = "connect";
			save_errno = errno;
			close(s);
			errno = save_errno;
			s = -1;
			continue;
		}

		break;
	}

	freeaddrinfo(res0);

	if (s == -1)
		warn("%s", cause);

	return s;
}

static void
mark_nonblock(int fd)
{
	int flags;

	if ((flags = fcntl(fd, F_GETFL)) == -1)
		fatal("fcntl(F_GETFL)");
	if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
		fatal("fcntl(F_SETFL)");
}

static void
tls_readcb(int fd, short event, void *d)
{
	struct bufferevent	*bufev = d;
	char			 buf[IBUF_READ_SIZE];
	int			 what = EVBUFFER_READ;
	int			 howmuch = IBUF_READ_SIZE;
	ssize_t			 ret;
	size_t			 len;

	if (event == EV_TIMEOUT) {
		what |= EVBUFFER_TIMEOUT;
		goto err;
	}

	if (bufev->wm_read.high != 0)
		howmuch = MIN(sizeof(buf), bufev->wm_read.high);

	switch (ret = tls_read(ctx, buf, howmuch)) {
	case TLS_WANT_POLLIN:
	case TLS_WANT_POLLOUT:
		goto retry;
	case -1:
		what |= EVBUFFER_ERROR;
		goto err;
	}
	len = ret;

	if (len == 0) {
		what |= EVBUFFER_EOF;
		goto err;
	}

	if (evbuffer_add(bufev->input, buf, len) == -1) {
		what |= EVBUFFER_ERROR;
		goto err;
	}

	event_add(&bufev->ev_read, NULL);

	len = EVBUFFER_LENGTH(bufev->input);
	if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
		return;
	if (bufev->readcb != NULL)
		(*bufev->readcb)(bufev, bufev->cbarg);
	return;

retry:
	event_add(&bufev->ev_read, NULL);
	return;

err:
	(*bufev->errorcb)(bufev, what, bufev->cbarg);
}

static void
tls_writecb(int fd, short event, void *d)
{
	struct bufferevent	*bufev = d;
	ssize_t			 ret;
	size_t			 len;
	short			 what = EVBUFFER_WRITE;
	void			*data;

	if (event == EV_TIMEOUT) {
		what |= EVBUFFER_TIMEOUT;
		goto err;
	}

	len = EVBUFFER_LENGTH(bufev->output);
	if (len != 0) {
		data = EVBUFFER_DATA(bufev->output);

#if DEBUG_PACKETS
		hexdump("outgoing msg", data, len);
#endif

		switch (ret = tls_write(ctx, data, len)) {
		case TLS_WANT_POLLIN:
		case TLS_WANT_POLLOUT:
			goto retry;
		case -1:
			what |= EVBUFFER_ERROR;
			goto err;
		}
		evbuffer_drain(bufev->output, ret);
	}

	if (EVBUFFER_LENGTH(bufev->output) != 0)
		event_add(&bufev->ev_write, NULL);

	if (bufev->writecb != NULL &&
	    EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
		(*bufev->writecb)(bufev, bufev->cbarg);
	return;

retry:
	event_add(&bufev->ev_write, NULL);
	return;
err:
	(*bufev->errorcb)(bufev, what, bufev->cbarg);
}

static void
client_read(struct bufferevent *bev, void *d)
{
	struct evbuffer	*src = EVBUFFER_INPUT(bev);
	uint32_t	 len;
	uint8_t		*data;

	for (;;) {
		if (EVBUFFER_LENGTH(src) < sizeof(len))
			return;

		data = EVBUFFER_DATA(src);

		memcpy(&len, data, sizeof(len));
		len = le32toh(len);

		if (len < HEADERSIZE)
			fatal("incoming message is too small! (%d bytes)",
			    len);

		if (len > EVBUFFER_LENGTH(src))
			return;

#if DEBUG_PACKETS
		hexdump("incoming msg", data, len);
#endif

		handle_9p(data, len);
		evbuffer_drain(src, len);
	}
}

static void
client_write(struct bufferevent *bev, void *data)
{
	return; /* nothing to do */
}

static void
client_error(struct bufferevent *bev, short err, void *data)
{
	if (err & EVBUFFER_ERROR)
		fatal("buffer event error");

	if (err & EVBUFFER_EOF) {
		clr();
		log_info("EOF");
		event_loopbreak();
		return;
	}

	clr();
	log_warnx("unknown event error");
	event_loopbreak();
}

static void
repl_read(struct bufferevent *bev, void *d)
{
	size_t		 len;
	int		 argc;
	const char	*argv[10], **ap;
	char		*line;

	line = evbuffer_readln(bev->input, &len, EVBUFFER_EOL_LF);
	if (line == NULL)
		return;

	for (argc = 0, ap = argv; ap < &argv[9] &&
	    (*ap = strsep(&line, " \t")) != NULL;) {
		if (**ap != '\0')
			ap++, argc++;
	}

	clr();
	excmd(argv, argc);
	prompt();

	free(line);
}

static void
repl_error(struct bufferevent *bev, short error, void *d)
{
	fatalx("an error occurred");
}

static void
write_hdr(uint32_t len, uint8_t type, uint16_t tag)
{
	len += HEADERSIZE;

	log_debug("enqueuing a packet; len=%"PRIu32" type=%d[%s] tag=%d",
	    len, type, pp_msg_type(type), tag);

	len = htole32(len);
	/* type is one byte, no endiannes issues */
	tag = htole16(tag);

	bufferevent_write(bev, &len, sizeof(len));
	bufferevent_write(bev, &type, sizeof(type));
	bufferevent_write(bev, &tag, sizeof(tag));
}

static void
write_hdr_auto(uint32_t len, uint8_t type)
{
        static uint16_t tag = 0;

	if (++tag == NOTAG)
		++tag;

	write_hdr(len, type, tag);
}

static void
write_str(uint16_t len, const char *str)
{
	uint16_t l = len;

	len = htole16(len);
	bufferevent_write(bev, &len, sizeof(len));
	bufferevent_write(bev, str, l);
}

static void
write_str_auto(const char *str)
{
	write_str(strlen(str), str);
}

static void
write_fid(uint32_t fid)
{
	fid = htole32(fid);
	bufferevent_write(bev, &fid, sizeof(fid));
}

static void
write_tag(uint16_t tag)
{
	tag = htole16(tag);
	bufferevent_write(bev, &tag, sizeof(tag));
}

/* version [version-str] */
static void
excmd_version(const char **argv, int argc)
{
	uint32_t	 len, msize;
	uint16_t	 sl;
	const char	*s;

	s = VERSION9P;
	if (argc == 2)
		s = argv[1];

	sl = strlen(s);

	/* msize[4] version[s] */
	len = 4 + sizeof(sl) + sl;
	write_hdr(len, Tversion, NOTAG);

	msize = htole32(MSIZE9P);
	bufferevent_write(bev, &msize, sizeof(msize));

	write_str(sl, s);
}

/* attach fid uname aname */
static void
excmd_attach(const char **argv, int argc)
{
	uint32_t	 len, fid;
	uint16_t	 sl, tl;
	const char	*s, *t, *errstr;

	if (argc != 4)
		goto usage;

        fid = strtonum(argv[1], 0, UINT32_MAX, &errstr);
	if (errstr != NULL) {
		log_warnx("fid is %s: %s", errstr, argv[1]);
		return;
	}

	s = argv[2];
	sl = strlen(s);
	t = argv[3];
	tl = strlen(t);

	/* fid[4] afid[4] uname[s] aname[s] */
	len = 4 + 4 + sizeof(sl) + sl + sizeof(tl) + tl;
	write_hdr_auto(len, Tattach);
	write_fid(fid);
	write_fid(NOFID);
	write_str(sl, s);
	write_str(tl, t);

	return;

usage:
	log_warnx("usage: attach fid uname aname");
}

/* clunk fid */
static void
excmd_clunk(const char **argv, int argc)
{
	uint32_t	 len, fid;
	const char	*errstr;

	if (argc != 2)
		goto usage;

	fid = strtonum(argv[1], 0, UINT32_MAX, &errstr);
	if (errstr != NULL) {
		log_warnx("fid is %s: %s", errstr, argv[1]);
		return;
	}

	/* fid[4] */
	len = sizeof(fid);
	write_hdr_auto(len, Tclunk);
	write_fid(fid);
	return;

usage:
	log_warnx("usage: clunk fid");
}

/* flush oldtag */
static void
excmd_flush(const char **argv, int argc)
{
	uint32_t	 len;
	uint16_t	 oldtag;
	const char	*errstr;

	if (argc != 2)
		goto usage;

	oldtag = strtonum(argv[1], 0, UINT16_MAX, &errstr);
	if (errstr != NULL) {
		log_warnx("oldtag is %s: %s", errstr, argv[1]);
		return;
	}

	/* oldtag[2] */
	len = sizeof(oldtag);
	write_hdr_auto(len, Tflush);
	write_tag(oldtag);
	return;

usage:
	log_warnx("usage: flush oldtag");
}

/* walk fid newfid wnames... */
static void
excmd_walk(const char **argv, int argc)
{
	int		 i;
	uint32_t	 len, fid, newfid;
	const char	*errstr;

	if (argc < 3)
		goto usage;

	/* fid[4] newfid[4] nwname[2] nwname*(wname[s]) */

	/* two bytes for wnames count */
	len = sizeof(fid) + sizeof(newfid) + 2;
	for (i = 3; i < argc; ++i)
		len += 2 + strlen(argv[i]);

	fid = strtonum(argv[1], 0, UINT32_MAX, &errstr);
	if (errstr != NULL) {
		log_warnx("fid is %s: %s", errstr, argv[1]);
		return;
	}

	newfid = strtonum(argv[2], 0, UINT32_MAX, &errstr);
	if (errstr != NULL) {
		log_warnx("newfid is %s: %s", errstr, argv[1]);
		return;
	}

	write_hdr_auto(len, Twalk);
	write_fid(fid);
	write_fid(newfid);
	write_tag(argc - 3);
	for (i = 3; i < argc; ++i)
		write_str_auto(argv[i]);

	return;

usage:
	log_warnx("usage: walk fid newfid wnames...");
}

static void
excmd(const char **argv, int argc)
{
	struct cmd {
		const char	*name;
		void		(*fn)(const char **, int);
	} cmds[] = {
		{"version",	excmd_version},
		{"attach",	excmd_attach},
		{"clunk",	excmd_clunk},
		{"flush",	excmd_flush},
		{"walk",	excmd_walk},
	};
	size_t i;

	if (argc == 0)
		return;

	for (i = 0; i < sizeof(cmds)/sizeof(cmds[0]); ++i) {
		if (!strcmp(cmds[i].name, argv[0])) {
			cmds[i].fn(argv, argc);
			return;
		}
	}

	log_warnx("Unknown command %s", *argv);
}

static const char *
pp_qid_type(uint8_t type)
{
        switch (type) {
	case QTDIR:	return "dir";
	case QTAPPEND:	return "append-only";
	case QTEXCL:	return "exclusive";
	case QTMOUNT:	return "mounted-channel";
	case QTAUTH:	return "authentication";
	case QTTMP:	return "non-backed-up";
	case QTSYMLINK: return "symlink";
	case QTFILE:	return "file";
	}

	return "unknown";
}

static void
pp_qid(const uint8_t *d, uint32_t len)
{
	uint64_t	path;
	uint32_t	vers;
	uint8_t		type;

	if (len < 13) {
		printf("invalid");
		return;
	}

	type = *d++;

	memcpy(&vers, d, sizeof(vers));
	d += sizeof(vers);
	vers = le64toh(vers);

	memcpy(&path, d, sizeof(path));
	d += sizeof(path);
	path = le64toh(path);

	printf("qid{path=%"PRIu64" version=%"PRIu32" type=0x%x\"%s\"}",
	    path, vers, type, pp_qid_type(type));
}

static void
pp_msg(uint32_t len, uint8_t type, uint16_t tag, const uint8_t *d)
{
	uint32_t	msize;
	uint16_t	slen;

	printf("len=%"PRIu32" type=%d[%s] tag=0x%x[%d] ", len,
	    type, pp_msg_type(type), tag, tag);

	len -= HEADERSIZE;

	switch (type) {
	case Rversion:
		if (len < 6) {
			printf("invalid: not enough space for msize "
			    "and version provided.");
			break;
		}

		memcpy(&msize, d, sizeof(msize));
		d += sizeof(msize);
		len -= sizeof(msize);
		msize = le32toh(msize);

		memcpy(&slen, d, sizeof(slen));
		d += sizeof(slen);
		len -= sizeof(slen);
		slen = le16toh(slen);

		if (len != slen) {
			printf("invalid: version string length doesn't "
			    "match.  Got %d; want %d", slen, len);
			break;
		}

		printf("msize=%"PRIu32" version[%"PRIu16"]=\"",
		    msize, slen);
		fwrite(d, 1, slen, stdout);
		printf("\"");

		break;

	case Rattach:
		pp_qid(d, len);
		break;

	case Rclunk:
		if (len != 0)
			printf("invalid Rclunk: %"PRIu32" extra bytes", len);
		break;

	case Rflush:
		if (len != 0)
			printf("invalid Rflush: %"PRIu32" extra bytes", len);
		break;

	case Rwalk:
		if (len < 2) {
			printf("invaild Rwalk: less than two bytes (%d)",
			    (int)len);
			break;
		}

		memcpy(&slen, d, sizeof(slen));
		d += sizeof(slen);
		len -= sizeof(slen);
		slen = le16toh(slen);

		if (len != QIDSIZE * slen) {
			printf("invalid Rwalk: wanted %d bytes for %d qids "
			    "but got %"PRIu32" bytes instead",
			    QIDSIZE*slen, slen, len);
			break;
		}

		printf("nwqid=%"PRIu16, slen);

		for (; slen != 0; slen--) {
			printf(" ");
			pp_qid(d, len);
			d += QIDSIZE;
			len -= QIDSIZE;
		}

		break;

	case Rerror:
		memcpy(&slen, d, sizeof(slen));
		d += sizeof(slen);
		len -= sizeof(slen);
		slen = le16toh(slen);

		if (slen != len) {
			printf("invalid: error string length doesn't "
			    "match.  Got %d; want %d", slen, len);
			break;
		}

		printf("error=\"");
		fwrite(d, 1, slen, stdout);
		printf("\"");

		break;

	default:
		printf("unknown command type");
	}

	printf("\n");
}

static void
handle_9p(const uint8_t *data, size_t size)
{
        uint32_t len;
	uint16_t tag;
	uint8_t type;

	assert(size >= HEADERSIZE);

	memcpy(&len, data, sizeof(len));
	data += sizeof(len);

	memcpy(&type, data, sizeof(type));
	data += sizeof(type);

	memcpy(&tag, data, sizeof(tag));
	data += sizeof(tag);

	len = le32toh(len);
	/* type is one byte long, no endianness issues */
	tag = le16toh(tag);

	clr();
	pp_msg(len, type, tag, data);
	prompt();
}

static void
clr(void)
{
	printf("\r");
	fflush(stdout);
}

static void
prompt(void)
{
	printf("%s", PROMPT);
	fflush(stdout);
}

int
main(int argc, char **argv)
{
	int		 ch, sock, handshake;
	struct event	 ev_sigint, ev_sigterm;

	signal(SIGPIPE, SIG_IGN);

	while ((ch = getopt(argc, argv, "C:cH:hK:P:v")) != -1) {
		switch (ch) {
		case 'C':
			crtpath = optarg;
			break;
		case 'c':
			tls = 1;
			break;
		case 'H':
			host = optarg;
			break;
		case 'h':
			usage(0);
			break;
		case 'K':
			keypath = optarg;
			break;
		case 'P':
			port = optarg;
			break;
		case 'v':
			verbose = 1;
			break;
		default:
			usage(1);
		}
	}

	if (host == NULL)
		host = "localhost";
	if (port == NULL)
		port = "1337";

	argc -= optind;
	argv += optind;

	if (argc != 0)
		usage(1);
	/* if (!tls || (crtpath != NULL || keypath != NULL)) */
		/* usage(1); */
	if (!tls)
                errx(1, "must enable tls (for now)");

	log_init(1, LOG_DAEMON);
	log_setverbose(verbose);
	log_procinit(getprogname());

	if ((tlsconf = tls_config_new()) == NULL)
		fatalx("tls_config_new");
	tls_config_insecure_noverifycert(tlsconf);
	tls_config_insecure_noverifyname(tlsconf);
	if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
		fatalx("can't load certs (%s, %s)", crtpath, keypath);

	if ((ctx = tls_client()) == NULL)
		fatal("tls_client");
	if (tls_configure(ctx, tlsconf) == -1)
		fatalx("tls_configure: %s", tls_error(ctx));

	log_info("connecting to %s:%s...", host, port);

	if ((sock = openconn()) == -1)
		fatalx("can't connect to %s:%s", host, port);

	if (tls_connect_socket(ctx, sock, host) == -1)
		fatalx("tls_connect_socket: %s", tls_error(ctx));

	for (handshake = 0; !handshake;) {
		switch (tls_handshake(ctx)) {
		case -1:
			fatalx("tls_handshake: %s", tls_error(ctx));
		case 0:
			handshake = 1;
			break;
		}
	}

	log_info("connected!");

	mark_nonblock(sock);

	event_init();

	signal_set(&ev_sigint, SIGINT, sig_handler, NULL);
	signal_set(&ev_sigterm, SIGINT, sig_handler, NULL);

	signal_add(&ev_sigint, NULL);
	signal_add(&ev_sigterm, NULL);

	bev = bufferevent_new(sock, client_read, client_write, client_error,
	    NULL);
	if (bev == NULL)
		fatal("bufferevent_new");

	/* setup tls/io */
	event_set(&bev->ev_read, sock, EV_READ, tls_readcb, bev);
	event_set(&bev->ev_write, sock, EV_WRITE, tls_writecb, bev);

	bufferevent_enable(bev, EV_READ|EV_WRITE);

	mark_nonblock(0);
	inbev = bufferevent_new(0, repl_read, NULL, repl_error, NULL);
	bufferevent_enable(inbev, EV_READ);

	prompt();
	event_dispatch();

	bufferevent_free(bev);
	tls_free(ctx);
	tls_config_free(tlsconf);
	close(sock);

	return 0;
}