2 #include "../port/lib.h"
6 #include "../port/netif.h"
7 #include "../port/error.h"
10 #include "../port/thwack.h"
13 * sdp - secure datagram protocol
16 typedef struct Sdp Sdp;
17 typedef struct Conv Conv;
18 typedef struct OneWay OneWay;
19 typedef struct Stats Stats;
20 typedef struct AckPkt AckPkt;
21 typedef struct Algorithm Algorithm;
22 typedef struct CipherRc4 CipherRc4;
26 Qtopdir= 1, /* top level directory */
28 Qsdpdir, /* sdp directory */
32 Qconvdir, /* directory per conversation */
34 Qdata, /* unreliable packet channel */
35 Qcontrol, /* reliable control channel */
42 Maxconv= 256, // power of 2
43 Nfs= 4, // number of file systems
45 KeepAlive = 300, // keep alive in seconds - should probably be about 60 but is higher to avoid linksys bug
46 SecretLength= 32, // a secret per direction
52 #define TYPE(x) (((ulong)(x).path) & 0xff)
53 #define CONV(x) ((((ulong)(x).path) >> 8)&(Maxconv-1))
54 #define QID(x, y) (((x)<<8) | (y))
61 ulong outCompDataBytes;
63 ulong outCompStats[NCompStats];
67 ulong inCompDataBytes;
81 ulong seqwrap; // number of wraps of the sequence number
85 uchar secret[SecretLength];
89 Block *controlpkt; // control channel
92 void *cipherstate; // state cipher
93 int cipherivlen; // initial vector length
94 int cipherblklen; // block length
95 int (*cipher)(OneWay*, uchar *buf, int len);
97 void *authstate; // auth state
98 int authlen; // auth data length in bytes
99 int (*auth)(OneWay*, uchar *buf, int len);
102 int (*comp)(Conv*, int subtype, ulong seq, Block **);
122 int ref; // holds conv up
126 int dataopen; // ref count of opens on Qdata
127 int controlopen; // ref count of opens on Qcontrol
128 int reader; // reader proc has been started
133 ulong lastrecv; // time last packet was received
137 // the following pair uniquely define conversation on this port
141 QLock readlk; // protects readproc
144 Chan *chan; // packet channel
147 char owner[KNAMELEN]; /* protections */
198 uchar outDataPackets[4];
199 uchar outDataBytes[4];
200 uchar outCompDataBytes[4];
201 uchar outCompStats[4*NCompStats];
203 uchar inDataPackets[4];
204 uchar inDataBytes[4];
205 uchar inCompDataBytes[4];
218 int keylen; // in bytes
223 RC4forward = 10*1024*1024, // maximum skip forward
224 RC4back = 100*1024, // maximum look back
229 ulong cseq; // current byte sequence number
232 int ovalid; // old is valid
233 ulong lgseq; // last good sequence
234 ulong oseq; // old byte sequence number
238 static Dirtab sdpdirtab[]={
239 "log", {Qlog}, 0, 0666,
240 "clone", {Qclone}, 0, 0666,
243 static Dirtab convdirtab[]={
244 "ctl", {Qctl}, 0, 0666,
245 "data", {Qdata}, 0, 0666,
246 "control", {Qcontrol}, 0, 0666,
247 "status", {Qstatus}, 0, 0444,
248 "stats", {Qstats}, 0, 0444,
249 "rstats", {Qrstats}, 0, 0444,
264 static Logflag logflags[] =
266 { "compress", Logcompress, },
267 { "auth", Logauth, },
268 { "hmac", Loghmac, },
272 static Dirtab *dirtab[MaxQ];
273 static Sdp sdptab[Nfs];
274 static char *convstatename[] = {
280 [CLocalClose] "LocalClose",
281 [CRemoteClose] "RemoteClose",
285 static int sdpgen(Chan *c, char*, Dirtab*, int, int s, Dir *dp);
286 static Conv *sdpclone(Sdp *sdp);
287 static void sdpackproc(void *a);
288 static void onewaycleanup(OneWay *ow);
289 static int readready(void *a);
290 static int controlread();
291 static void convsetstate(Conv *c, int state);
292 static Block *readcontrol(Conv *c, int n);
293 static void writecontrol(Conv *c, void *p, int n, int wait);
294 static Block *readdata(Conv *c, int n);
295 static long writedata(Conv *c, Block *b);
296 static void convderef(Conv *c);
297 static Block *conviput(Conv *c, Block *b, int control);
298 static void conviconnect(Conv *c, int op, Block *b);
299 static void convicontrol(Conv *c, int op, Block *b);
300 static Block *convicomp(Conv *c, int op, ulong, Block *b);
301 static void convoput(Conv *c, int type, int subtype, Block *b);
302 static void convoconnect(Conv *c, int op, ulong dialid, ulong acceptid);
303 static void convopenchan(Conv *c, char *path);
304 static void convstats(Conv *c, int local, char *buf, int n);
305 static void convreader(void *a);
307 static void setalg(Conv *c, char *name, Algorithm *tab, Algorithm **);
308 static void setsecret(OneWay *cc, char *secret);
310 static void nullcipherinit(Conv*c);
311 static void descipherinit(Conv*c);
312 static void rc4cipherinit(Conv*c);
313 static void nullauthinit(Conv*c);
314 static void shaauthinit(Conv*c);
315 static void md5authinit(Conv*c);
316 static void nullcompinit(Conv*c);
317 static void thwackcompinit(Conv*c);
319 static Algorithm cipheralg[] =
321 "null", 0, nullcipherinit,
322 "des_56_cbc", 7, descipherinit,
323 "rc4_128", 16, rc4cipherinit,
324 "rc4_256", 32, rc4cipherinit,
328 static Algorithm authalg[] =
330 "null", 0, nullauthinit,
331 "hmac_sha1_96", 16, shaauthinit,
332 "hmac_md5_96", 16, md5authinit,
336 static Algorithm compalg[] =
338 "null", 0, nullcompinit,
339 "thwack", 0, thwackcompinit,
350 // setup dirtab with non directory entries
351 for(i=0; i<nelem(sdpdirtab); i++) {
353 dirtab[TYPE(dt->qid)] = dt;
356 for(i=0; i<nelem(convdirtab); i++) {
358 dirtab[TYPE(dt->qid)] = dt;
364 sdpattach(char* spec)
373 if(dev<0 || dev >= Nfs)
374 error("bad specification");
376 c = devattach('E', spec);
377 c->qid = (Qid){QID(0, Qtopdir), 0, QTDIR};
382 start = sdp->ackproc == 0;
387 snprint(buf, sizeof(buf), "sdpackproc%d", dev);
388 kproc(buf, sdpackproc, sdp);
395 sdpwalk(Chan *c, Chan *nc, char **name, int nname)
397 return devwalk(c, nc, name, nname, 0, 0, sdpgen);
401 sdpstat(Chan* c, uchar* db, int n)
403 return devstat(c, db, n, nil, 0, sdpgen);
407 sdpopen(Chan* ch, int omode)
417 sdp = sdptab + ch->dev;
419 switch(TYPE(ch->qid)) {
435 ch->qid.path = QID(c->id, Qctl);
443 c = sdp->conv[CONV(ch->qid)];
449 if((perm & (c->perm>>6)) != perm)
450 if(strcmp(up->user, c->owner) != 0 || (perm & c->perm) != perm)
454 if(TYPE(ch->qid) == Qdata) {
456 // kill reader if Qdata is opened for the first time
458 if(c->readproc != nil)
459 postnote(c->readproc, 1, "interrupt", 0);
460 } else if(TYPE(ch->qid) == Qcontrol) {
467 ch->mode = openmode(omode);
476 Sdp *sdp = sdptab + ch->dev;
479 if(!(ch->flag & COPEN))
481 switch(TYPE(ch->qid)) {
489 c = sdp->conv[CONV(ch->qid)];
496 c = sdp->conv[CONV(ch->qid)];
504 kproc("convreader", convreader, c);
513 c = sdp->conv[CONV(ch->qid)];
517 if(c->controlopen == 0 && c->ref != 0) {
520 convsetstate(c, CClosed);
524 convsetstate(c, CLocalClose);
534 sdpread(Chan *ch, void *a, long n, vlong off)
538 Sdp *sdp = sdptab + ch->dev;
544 switch(TYPE(ch->qid)) {
550 return devdirread(ch, a, n, 0, 0, sdpgen);
552 return logread(sdp, a, off, n);
554 c = sdp->conv[CONV(ch->qid)];
556 n = readstr(off, a, n, convstatename[c->state]);
560 sprint(buf, "%lud", CONV(ch->qid));
561 return readstr(off, a, n, buf);
563 b = readcontrol(sdp->conv[CONV(ch->qid)], n);
568 memmove(a, b->rp, n);
572 b = readdata(sdp->conv[CONV(ch->qid)], n);
577 memmove(a, b->rp, n);
582 c = sdp->conv[CONV(ch->qid)];
584 convstats(c, TYPE(ch->qid) == Qstats, s, 1000);
585 rv = readstr(off, a, n, s);
592 sdpbread(Chan* ch, long n, ulong offset)
594 Sdp *sdp = sdptab + ch->dev;
596 if(TYPE(ch->qid) != Qdata)
597 return devbread(ch, n, offset);
598 return readdata(sdp->conv[CONV(ch->qid)], n);
603 sdpwrite(Chan *ch, void *a, long n, vlong off)
605 Sdp *sdp = sdptab + ch->dev;
613 switch(TYPE(ch->qid)) {
617 c = sdp->conv[CONV(ch->qid)];
626 error("short write");
628 if(strcmp(arg0, "accept") == 0) {
630 error("usage: accept file");
631 convopenchan(c, cb->f[1]);
632 } else if(strcmp(arg0, "dial") == 0) {
634 error("usage: dial file");
635 convopenchan(c, cb->f[1]);
636 convsetstate(c, CDial);
637 } else if(strcmp(arg0, "drop") == 0) {
639 error("usage: drop permil");
640 c->drop = atoi(cb->f[1]);
641 } else if(strcmp(arg0, "cipher") == 0) {
643 error("usage: cipher alg");
644 setalg(c, cb->f[1], cipheralg, &c->cipher);
645 } else if(strcmp(arg0, "auth") == 0) {
647 error("usage: auth alg");
648 setalg(c, cb->f[1], authalg, &c->auth);
649 } else if(strcmp(arg0, "comp") == 0) {
651 error("usage: comp alg");
652 setalg(c, cb->f[1], compalg, &c->comp);
653 } else if(strcmp(arg0, "insecret") == 0) {
655 error("usage: insecret secret");
656 setsecret(&c->in, cb->f[1]);
661 } else if(strcmp(arg0, "outsecret") == 0) {
663 error("usage: outsecret secret");
664 setsecret(&c->out, cb->f[1]);
670 error("unknown control request");
677 p = logctl(sdp, cb->nf, cb->f, logflags);
683 writecontrol(sdp->conv[CONV(ch->qid)], a, n, 0);
687 memmove(b->wp, a, n);
689 return writedata(sdp->conv[CONV(ch->qid)], b);
694 sdpbwrite(Chan *ch, Block *bp, ulong offset)
696 Sdp *sdp = sdptab + ch->dev;
698 if(TYPE(ch->qid) != Qdata)
699 return devbwrite(ch, bp, offset);
700 return writedata(sdp->conv[CONV(ch->qid)], bp);
704 sdpgen(Chan *c, char*, Dirtab*, int, int s, Dir *dp)
706 Sdp *sdp = sdptab + c->dev;
707 int type = TYPE(c->qid);
712 switch(TYPE(c->qid)){
715 snprint(up->genbuf, sizeof(up->genbuf), "#E%ld", c->dev);
716 mkqid(&qid, Qtopdir, 0, QTDIR);
717 devdir(c, qid, up->genbuf, 0, eve, 0555, dp);
720 snprint(up->genbuf, sizeof(up->genbuf), "%d", s);
721 mkqid(&qid, Qsdpdir, 0, QTDIR);
722 devdir(c, qid, up->genbuf, 0, eve, 0555, dp);
725 panic("sdpwalk %llux", c->qid.path);
732 // non directory entries end up here
733 if(c->qid.type & QTDIR)
734 panic("sdpgen: unexpected directory");
737 dt = dirtab[TYPE(c->qid)];
739 panic("sdpgen: unknown type: %lud", TYPE(c->qid));
740 devdir(c, c->qid, dt->name, dt->length, eve, dt->perm, dp);
745 mkqid(&qid, QID(0, Qsdpdir), 0, QTDIR);
746 devdir(c, qid, "sdp", 0, eve, 0555, dp);
749 if(s<nelem(sdpdirtab)) {
751 devdir(c, dt->qid, dt->name, dt->length, eve, dt->perm, dp);
754 s -= nelem(sdpdirtab);
757 mkqid(&qid, QID(s, Qconvdir), 0, QTDIR);
758 snprint(up->genbuf, sizeof(up->genbuf), "%d", s);
759 devdir(c, qid, up->genbuf, 0, eve, 0555, dp);
762 if(s>=nelem(convdirtab))
765 mkqid(&qid, QID(CONV(c->qid),TYPE(dt->qid)), 0, QTFILE);
766 devdir(c, qid, dt->name, dt->length, eve, dt->perm, dp);
777 ep = sdp->conv + nelem(sdp->conv);
783 for(pp = sdp->conv; pp < ep; pp++) {
786 c = malloc(sizeof(Conv));
789 memset(c, 0, sizeof(Conv));
792 c->id = pp - sdp->conv;
797 if(c->ref == 0 && canqlock(c)){
809 assert(c->state == CFree);
810 // set ref to 2 - 1 ref for open - 1 ref for channel state
814 strncpy(c->owner, up->user, sizeof(c->owner)-1);
815 c->owner[sizeof(c->owner)-1] = 0;
822 // assume c is locked
824 convretryinit(Conv *c)
827 // +2 to avoid rounding effects.
828 c->timeout = TK2SEC(m->ticks) + 2;
831 // assume c is locked
833 convretry(Conv *c, int reset)
836 if(c->retries > MaxRetries) {
838 convoconnect(c, ConReset, c->dialid, c->acceptid);
839 convsetstate(c, CClosed);
842 c->timeout = TK2SEC(m->ticks) + (c->retries+1);
846 // assumes c is locked
848 convtimer(Conv *c, ulong sec)
860 convoconnect(c, ConOpenRequest, c->dialid, 0);
864 convoconnect(c, ConOpenAck, c->dialid, c->acceptid);
867 b = c->out.controlpkt;
870 convoput(c, TControl, ControlMesg, copyblock(b, blocklen(b)));
874 c->timeout = c->lastrecv + KeepAlive;
877 // keepalive - randomly spaced between KeepAlive and 2*KeepAlive
878 if(c->timeout + KeepAlive > sec && nrand(c->lastrecv + 2*KeepAlive - sec) > 0)
880 // can not use writecontrol
883 hnputl(b->wp, c->out.controlseq);
885 c->out.controlpkt = b;
888 convoput(c, TControl, ControlMesg, copyblock(b, blocklen(b)));
894 convoconnect(c, ConClose, c->dialid, c->acceptid);
914 tsleep(&up->sleep, return0, 0, 1000);
915 sec = TK2SEC(m->ticks);
917 for(i=0; i<sdp->nconv; i++) {
923 if(c->ref > 0 && !waserror()) {
955 // assume hold lock on c
957 convsetstate(Conv *c, int state)
960 if(0)print("convsetstate %d: %s -> %s\n", c->id, convstatename[c->state], convstatename[state]);
964 panic("setstate: bad state: %d", state);
966 assert(c->state == CInit);
967 c->dialid = (rand()<<16) + rand();
969 convoconnect(c, ConOpenRequest, c->dialid, 0);
972 assert(c->state == CInit);
973 c->acceptid = (rand()<<16) + rand();
975 convoconnect(c, ConOpenAck, c->dialid, c->acceptid);
978 assert(c->state == CDial || c->state == CAccept);
979 c->lastrecv = TK2SEC(m->ticks);
980 if(c->state == CDial) {
982 convoconnect(c, ConOpenAckAck, c->dialid, c->acceptid);
983 hnputl(c->in.secret, c->acceptid);
984 hnputl(c->in.secret+4, c->dialid);
985 hnputl(c->out.secret, c->dialid);
986 hnputl(c->out.secret+4, c->acceptid);
988 hnputl(c->in.secret, c->dialid);
989 hnputl(c->in.secret+4, c->acceptid);
990 hnputl(c->out.secret, c->acceptid);
991 hnputl(c->out.secret+4, c->dialid);
993 setalg(c, "hmac_md5_96", authalg, &c->auth);
996 assert(c->state == CAccept || c->state == COpen);
998 convoconnect(c, ConClose, c->dialid, c->acceptid);
1001 wakeup(&c->in.controlready);
1002 wakeup(&c->out.controlready);
1005 wakeup(&c->in.controlready);
1006 wakeup(&c->out.controlready);
1008 postnote(c->readproc, 1, "interrupt", 0);
1009 if(c->state != CClosed)
1017 //assumes c is locked
1025 assert(c->ref == 0);
1026 assert(c->dataopen == 0);
1027 assert(c->controlopen == 0);
1028 if(0)print("convderef: %d: ref == 0!\n", c->id);
1041 strcpy(c->owner, "network");
1048 onewaycleanup(&c->in);
1049 onewaycleanup(&c->out);
1050 memset(&c->lstats, 0, sizeof(Stats));
1051 memset(&c->rstats, 0, sizeof(Stats));
1055 onewaycleanup(OneWay *ow)
1058 freeb(ow->controlpkt);
1059 secfree(ow->authstate);
1060 secfree(ow->cipherstate);
1062 free(ow->compstate);
1063 memset(ow, 0, sizeof(OneWay));
1067 // assumes conv is locked
1069 convopenchan(Conv *c, char *path)
1071 if(c->state != CInit || c->chan != nil)
1072 error("already connected");
1073 c->chan = namec(path, Aopen, ORDWR, 0);
1074 c->channame = smalloc(strlen(path)+1);
1075 strcpy(c->channame, path);
1083 kproc("convreader", convreader, c);
1085 assert(c->reader == 0 && c->ref > 0);
1086 // after kproc in case it fails
1094 convstats(Conv *c, int local, char *buf, int n)
1104 writecontrol(c, 0, 0, 1);
1113 p += snprint(p, ep-p, "outPackets: %lud\n", stats->outPackets);
1114 p += snprint(p, ep-p, "outDataPackets: %lud\n", stats->outDataPackets);
1115 p += snprint(p, ep-p, "outDataBytes: %lud\n", stats->outDataBytes);
1116 p += snprint(p, ep-p, "outCompDataBytes: %lud\n", stats->outCompDataBytes);
1117 for(i=0; i<NCompStats; i++) {
1118 if(stats->outCompStats[i] == 0)
1120 p += snprint(p, ep-p, "outCompStats[%d]: %lud\n", i, stats->outCompStats[i]);
1122 p += snprint(p, ep-p, "inPackets: %lud\n", stats->inPackets);
1123 p += snprint(p, ep-p, "inDataPackets: %lud\n", stats->inDataPackets);
1124 p += snprint(p, ep-p, "inDataBytes: %lud\n", stats->inDataBytes);
1125 p += snprint(p, ep-p, "inCompDataBytes: %lud\n", stats->inCompDataBytes);
1126 p += snprint(p, ep-p, "inMissing: %lud\n", stats->inMissing);
1127 p += snprint(p, ep-p, "inDup: %lud\n", stats->inDup);
1128 p += snprint(p, ep-p, "inReorder: %lud\n", stats->inReorder);
1129 p += snprint(p, ep-p, "inBadComp: %lud\n", stats->inBadComp);
1130 p += snprint(p, ep-p, "inBadAuth: %lud\n", stats->inBadAuth);
1131 p += snprint(p, ep-p, "inBadSeq: %lud\n", stats->inBadSeq);
1132 p += snprint(p, ep-p, "inBadOther: %lud\n", stats->inBadOther);
1146 b = allocb(sizeof(AckPkt));
1147 ack = (AckPkt*)b->wp;
1148 b->wp += sizeof(AckPkt);
1150 hnputl(ack->cseq, c->in.controlseq);
1151 hnputl(ack->outPackets, s->outPackets);
1152 hnputl(ack->outDataPackets, s->outDataPackets);
1153 hnputl(ack->outDataBytes, s->outDataBytes);
1154 hnputl(ack->outCompDataBytes, s->outCompDataBytes);
1155 for(i=0; i<NCompStats; i++)
1156 hnputl(ack->outCompStats+i*4, s->outCompStats[i]);
1157 hnputl(ack->inPackets, s->inPackets);
1158 hnputl(ack->inDataPackets, s->inDataPackets);
1159 hnputl(ack->inDataBytes, s->inDataBytes);
1160 hnputl(ack->inCompDataBytes, s->inCompDataBytes);
1161 hnputl(ack->inMissing, s->inMissing);
1162 hnputl(ack->inDup, s->inDup);
1163 hnputl(ack->inReorder, s->inReorder);
1164 hnputl(ack->inBadComp, s->inBadComp);
1165 hnputl(ack->inBadAuth, s->inBadAuth);
1166 hnputl(ack->inBadSeq, s->inBadSeq);
1167 hnputl(ack->inBadOther, s->inBadOther);
1168 convoput(c, TControl, ControlAck, b);
1172 // assume we hold lock for c
1174 conviput(Conv *c, Block *b, int control)
1181 c->lstats.inPackets++;
1184 c->lstats.inBadOther++;
1189 type = b->rp[0] >> 4;
1190 subtype = b->rp[0] & 0xf;
1192 if(type == TConnect) {
1193 conviconnect(c, subtype, b);
1200 c->lstats.inBadOther++;
1201 convoconnect(c, ConReset, c->dialid, c->acceptid);
1202 convsetstate(c, CClosed);
1207 c->lstats.inBadOther++;
1212 seq = (b->rp[0]<<16) + (b->rp[1]<<8) + b->rp[2];
1215 seqwrap = c->in.seqwrap;
1216 seqdiff = seq - c->in.seq;
1217 if(seqdiff < -(SeqMax*3/4)) {
1220 } else if(seqdiff > SeqMax*3/4) {
1226 if(seqdiff <= -SeqWindow) {
1227 if(0)print("old sequence number: %ld (%ld %ld)\n", seq, c->in.seqwrap, seqdiff);
1228 c->lstats.inBadSeq++;
1233 if(c->in.window & (1<<-seqdiff)) {
1234 if(0)print("dup sequence number: %ld (%ld %ld)\n", seq, c->in.seqwrap, seqdiff);
1240 c->lstats.inReorder++;
1243 // ok the sequence number looks ok
1244 if(0) print("coniput seq=%ulx\n", seq);
1245 if(c->in.auth != 0) {
1246 if(!(*c->in.auth)(&c->in, b->rp-4, BLEN(b)+4)) {
1247 if(0)print("bad auth %ld\n", BLEN(b)+4);
1248 c->lstats.inBadAuth++;
1252 b->wp -= c->in.authlen;
1255 if(c->in.cipher != 0) {
1256 if(!(*c->in.cipher)(&c->in, b->rp, BLEN(b))) {
1257 if(0)print("bad cipher\n");
1258 c->lstats.inBadOther++;
1262 b->rp += c->in.cipherivlen;
1263 if(c->in.cipherblklen > 1) {
1266 if(0)print("pad too big\n");
1267 c->lstats.inBadOther++;
1275 // ok the packet is good
1277 while(seqdiff > 0 && c->in.window != 0) {
1278 if((c->in.window & (1<<(SeqWindow-1))) == 0) {
1279 c->lstats.inMissing++;
1285 c->lstats.inMissing += seqdiff;
1289 c->in.seqwrap = seqwrap;
1291 c->in.window |= 1<<-seqdiff;
1292 c->lastrecv = TK2SEC(m->ticks);
1296 convicontrol(c, subtype, b);
1299 c->lstats.inDataPackets++;
1300 c->lstats.inDataBytes += BLEN(b);
1305 c->lstats.inDataPackets++;
1306 c->lstats.inCompDataBytes += BLEN(b);
1307 b = convicomp(c, subtype, seq, b);
1309 c->lstats.inBadComp++;
1312 c->lstats.inDataBytes += BLEN(b);
1317 if(0)print("dropping packet id=%d: type=%d n=%ld control=%d\n", c->id, type, BLEN(b), control);
1318 c->lstats.inBadOther++;
1323 // assume hold conv lock
1325 conviconnect(Conv *c, int subtype, Block *b)
1334 dialid = nhgetl(b->rp);
1335 acceptid = nhgetl(b->rp + 4);
1338 if(0)print("sdp: conviconnect: %s: %d %uld %uld\n", convstatename[c->state], subtype, dialid, acceptid);
1340 if(subtype == ConReset) {
1341 convsetstate(c, CClosed);
1347 panic("unknown state: %d", c->state);
1351 if(dialid != c->dialid)
1358 if(dialid != c->dialid
1359 || subtype != ConOpenRequest && acceptid != c->acceptid)
1367 case ConOpenRequest:
1371 convsetstate(c, CAccept);
1375 // duplicate ConOpenRequest that we ignore
1382 c->acceptid = acceptid;
1383 convsetstate(c, COpen);
1386 // duplicate that we have to ack
1387 convoconnect(c, ConOpenAckAck, acceptid, dialid);
1394 convsetstate(c, COpen);
1399 // duplicate that we ignore
1406 convoconnect(c, ConCloseAck, dialid, acceptid);
1407 convsetstate(c, CRemoteClose);
1410 // duplicate ConClose
1411 convoconnect(c, ConCloseAck, dialid, acceptid);
1418 convsetstate(c, CClosed);
1424 // invalid connection message - reset to sender
1425 if(1)print("sdp: invalid conviconnect - sending reset\n");
1426 convoconnect(c, ConReset, dialid, acceptid);
1427 convsetstate(c, CClosed);
1431 convicontrol(Conv *c, int subtype, Block *b)
1439 cseq = nhgetl(b->rp);
1443 if(cseq == c->in.controlseq) {
1444 if(0)print("duplicate control packet: %ulx\n", cseq);
1445 // duplicate control packet
1447 if(c->in.controlpkt == nil)
1452 if(cseq != c->in.controlseq+1)
1454 c->in.controlseq = cseq;
1461 c->in.controlpkt = b;
1462 if(0) print("recv %ld size=%ld\n", cseq, BLEN(b));
1463 wakeup(&c->in.controlready);
1467 if(cseq != c->out.controlseq)
1469 if(BLEN(b) < sizeof(AckPkt))
1471 ack = (AckPkt*)(b->rp);
1472 c->rstats.outPackets = nhgetl(ack->outPackets);
1473 c->rstats.outDataPackets = nhgetl(ack->outDataPackets);
1474 c->rstats.outDataBytes = nhgetl(ack->outDataBytes);
1475 c->rstats.outCompDataBytes = nhgetl(ack->outCompDataBytes);
1476 for(i=0; i<NCompStats; i++)
1477 c->rstats.outCompStats[i] = nhgetl(ack->outCompStats + 4*i);
1478 c->rstats.inPackets = nhgetl(ack->inPackets);
1479 c->rstats.inDataPackets = nhgetl(ack->inDataPackets);
1480 c->rstats.inDataBytes = nhgetl(ack->inDataBytes);
1481 c->rstats.inCompDataBytes = nhgetl(ack->inCompDataBytes);
1482 c->rstats.inMissing = nhgetl(ack->inMissing);
1483 c->rstats.inDup = nhgetl(ack->inDup);
1484 c->rstats.inReorder = nhgetl(ack->inReorder);
1485 c->rstats.inBadComp = nhgetl(ack->inBadComp);
1486 c->rstats.inBadAuth = nhgetl(ack->inBadAuth);
1487 c->rstats.inBadSeq = nhgetl(ack->inBadSeq);
1488 c->rstats.inBadOther = nhgetl(ack->inBadOther);
1490 freeb(c->out.controlpkt);
1491 c->out.controlpkt = nil;
1492 c->timeout = c->lastrecv + KeepAlive;
1493 wakeup(&c->out.controlready);
1499 convicomp(Conv *c, int subtype, ulong seq, Block *b)
1501 if(c->in.comp == nil) {
1505 if(!(*c->in.comp)(c, subtype, seq, &b))
1512 convwriteblock(Conv *c, Block *b)
1515 if(c->drop && nrand(c->drop) == 0)
1519 convsetstate(c, CClosed);
1522 devtab[c->chan->type]->bwrite(c->chan, b, 0);
1527 // assume hold conv lock
1529 convoput(Conv *c, int type, int subtype, Block *b)
1533 c->lstats.outPackets++;
1534 /* Make room for sdp trailer */
1535 if(c->out.cipherblklen > 1)
1536 pad = c->out.cipherblklen - (BLEN(b) + c->out.cipherivlen) % c->out.cipherblklen;
1540 b = padblock(b, -(pad+c->out.authlen));
1543 memset(b->wp, 0, pad-1);
1548 /* Make space to fit sdp header */
1549 b = padblock(b, 4 + c->out.cipherivlen);
1550 b->rp[0] = (type << 4) | subtype;
1552 if(c->out.seq == (1<<24)) {
1556 b->rp[1] = c->out.seq>>16;
1557 b->rp[2] = c->out.seq>>8;
1558 b->rp[3] = c->out.seq;
1561 (*c->out.cipher)(&c->out, b->rp+4, BLEN(b)-4);
1565 b->wp += c->out.authlen;
1566 (*c->out.auth)(&c->out, b->rp, BLEN(b));
1569 convwriteblock(c, b);
1572 // assume hold conv lock
1574 convoconnect(Conv *c, int op, ulong dialid, ulong acceptid)
1578 c->lstats.outPackets++;
1579 assert(c->chan != nil);
1581 b->wp[0] = (TConnect << 4) | op;
1582 hnputl(b->wp+1, dialid);
1583 hnputl(b->wp+5, acceptid);
1587 convwriteblock(c, b);
1593 convreadblock(Conv *c, int n)
1601 qunlock(&c->readlk);
1605 if(c->state == CClosed) {
1614 b = devtab[ch->type]->bread(ch, n, 0);
1617 qunlock(&c->readlk);
1627 return c->in.controlpkt != nil || (c->state == CClosed) || (c->state == CRemoteClose);
1631 readcontrol(Conv *c, int n)
1637 qlock(&c->in.controllk);
1639 qunlock(&c->in.controllk);
1642 qlock(c); // this lock is not held during the sleep below
1645 if(c->chan == nil || c->state == CClosed) {
1647 if(0)print("readcontrol: return error - state = %s\n", convstatename[c->state]);
1648 error("conversation closed");
1651 if(c->in.controlpkt != nil)
1654 if(c->state == CRemoteClose) {
1656 if(0)print("readcontrol: return nil - state = %s\n", convstatename[c->state]);
1661 sleep(&c->in.controlready, readready, c);
1667 b = c->in.controlpkt;
1668 c->in.controlpkt = nil;
1671 qunlock(&c->in.controllk);
1681 return c->out.controlpkt == nil || (c->state == CClosed) || (c->state == CRemoteClose);
1689 if(c->state == CFree || c->state == CInit ||
1690 c->state == CClosed || c->state == CRemoteClose)
1691 error("conversation closed");
1693 if(c->state == COpen && c->out.controlpkt == nil)
1701 sleep(&c->out.controlready, writeready, c);
1708 writecontrol(Conv *c, void *p, int n, int wait)
1712 qlock(&c->out.controllk);
1716 qunlock(&c->out.controllk);
1721 c->out.controlseq++;
1722 hnputl(b->wp, c->out.controlseq);
1723 memmove(b->wp+4, p, n);
1725 c->out.controlpkt = b;
1727 convoput(c, TControl, ControlMesg, copyblock(b, blocklen(b)));
1732 qunlock(&c->out.controllk);
1736 readdata(Conv *c, int n)
1743 // some slack for tunneling overhead
1746 // make sure size is big enough for control messages
1749 b = convreadblock(c, nn);
1757 b = conviput(c, b, 0);
1769 writedata(Conv *c, Block *b)
1781 if(c->state != COpen) {
1783 error("conversation not open");
1787 c->lstats.outDataPackets++;
1788 c->lstats.outDataBytes += n;
1790 if(c->out.comp != nil) {
1791 // must generate same value as convoput
1792 seq = (c->out.seq + 1) & (SeqMax-1);
1794 subtype = (*c->out.comp)(c, 0, seq, &b);
1795 c->lstats.outCompDataBytes += BLEN(b);
1796 convoput(c, TCompData, subtype, b);
1798 convoput(c, TData, 0, b);
1812 assert(c->reader == 1);
1813 while(c->dataopen == 0 && c->state != CClosed) {
1817 b = convreadblock(c, 2000);
1822 if(strcmp(up->errstr, Eintr) != 0) {
1823 convsetstate(c, CClosed);
1826 } else if(!waserror()) {
1838 /* ciphers, authenticators, and compressors */
1841 setalg(Conv *c, char *name, Algorithm *alg, Algorithm **p)
1843 for(; alg->name; alg++)
1844 if(strcmp(name, alg->name) == 0)
1846 if(alg->name == nil)
1847 error("unknown algorithm");
1854 setsecret(OneWay *ow, char *secret)
1860 memset(ow->secret, 0, sizeof(ow->secret));
1861 for(p=secret; *p; p++) {
1862 if(i >= sizeof(ow->secret)*2)
1865 if(c >= '0' && c <= '9')
1867 else if(c >= 'a' && c <= 'f')
1869 else if(c >= 'A' && c <= 'F')
1872 error("bad character in secret");
1875 ow->secret[i>>1] |= c;
1881 setkey(uchar *key, int n, OneWay *ow, char *prefix)
1883 uchar ibuf[SHA1dlen], obuf[MD5dlen], salt[10];
1887 for(i=0; i<round+1; i++)
1888 salt[i] = 'A'+round;
1889 sha1((uchar*)prefix, strlen(prefix), ibuf, sha1(salt, round+1, nil, nil));
1890 md5(ibuf, SHA1dlen, obuf, md5(ow->secret, sizeof(ow->secret), nil, nil));
1891 i = (n<MD5dlen) ? n : MD5dlen;
1892 memmove(key, obuf, i);
1895 if(++round > sizeof salt)
1896 panic("setkey: you ask too much");
1903 if(c->in.cipherstate) {
1904 free(c->in.cipherstate);
1905 c->in.cipherstate = nil;
1907 if(c->out.cipherstate) {
1908 free(c->out.cipherstate);
1909 c->out.cipherstate = nil;
1912 c->in.cipherblklen = 0;
1913 c->out.cipherblklen = 0;
1914 c->in.cipherivlen = 0;
1915 c->out.cipherivlen = 0;
1921 secfree(c->in.authstate);
1922 secfree(c->out.authstate);
1923 c->in.authstate = nil;
1924 c->out.authstate = nil;
1933 if(c->in.compstate) {
1934 free(c->in.compstate);
1935 c->in.compstate = nil;
1937 if(c->out.compstate) {
1938 free(c->out.compstate);
1939 c->out.compstate = nil;
1945 nullcipherinit(Conv *c)
1951 desencrypt(OneWay *ow, uchar *p, int n)
1953 uchar *pp, *ip, *eip, *ep;
1954 DESstate *ds = ow->cipherstate;
1956 if(n < 8 || (n & 0x7 != 0))
1959 memmove(p, ds->ivec, 8);
1960 for(p += 8; p < ep; p += 8){
1963 for(eip = ip+8; ip < eip; )
1965 block_cipher(ds->expanded, p, 0);
1966 memmove(ds->ivec, p, 8);
1972 desdecrypt(OneWay *ow, uchar *p, int n)
1975 uchar *tp, *ip, *eip, *ep;
1976 DESstate *ds = ow->cipherstate;
1978 if(n < 8 || (n & 0x7 != 0))
1981 memmove(ds->ivec, p, 8);
1985 block_cipher(ds->expanded, p, 1);
1988 for(eip = ip+8; ip < eip; ){
1997 descipherinit(Conv *c)
2001 int n = c->cipher->keylen;
2009 memset(key, 0, sizeof(key));
2010 setkey(key, n, &c->in, "cipher");
2011 memset(ivec, 0, sizeof(ivec));
2012 c->in.cipherblklen = 8;
2013 c->in.cipherivlen = 8;
2014 c->in.cipher = desdecrypt;
2015 c->in.cipherstate = secalloc(sizeof(DESstate));
2016 setupDESstate(c->in.cipherstate, key, ivec);
2019 memset(key, 0, sizeof(key));
2020 setkey(key, n, &c->out, "cipher");
2022 c->out.cipherblklen = 8;
2023 c->out.cipherivlen = 8;
2024 c->out.cipher = desencrypt;
2025 c->out.cipherstate = secalloc(sizeof(DESstate));
2026 setupDESstate(c->out.cipherstate, key, ivec);
2030 rc4encrypt(OneWay *ow, uchar *p, int n)
2032 CipherRc4 *cr = ow->cipherstate;
2037 hnputl(p, cr->cseq);
2040 rc4(&cr->current, p, n);
2046 rc4decrypt(OneWay *ow, uchar *p, int n)
2048 CipherRc4 *cr = ow->cipherstate;
2061 rc4(&cr->current, p, n);
2064 dd = cr->cseq - cr->lgseq;
2069 //print("missing packet: %uld %ld\n", seq, d);
2070 // this link is hosed
2076 cr->oseq = cr->cseq;
2077 memmove(&cr->old, &cr->current, sizeof(RC4state));
2079 rc4skip(&cr->current, d);
2080 rc4(&cr->current, p, n);
2083 //print("reordered packet: %uld %ld\n", seq, d);
2084 dd = seq - cr->oseq;
2085 if(!cr->ovalid || -d > RC4back || dd < 0)
2087 memmove(&tmpstate, &cr->old, sizeof(RC4state));
2088 rc4skip(&tmpstate, dd);
2089 rc4(&tmpstate, p, n);
2093 // move old state up
2095 dd = cr->cseq - RC4back - cr->oseq;
2097 rc4skip(&cr->old, dd);
2106 rc4cipherinit(Conv *c)
2114 n = c->cipher->keylen;
2119 memset(key, 0, sizeof(key));
2120 setkey(key, n, &c->in, "cipher");
2121 c->in.cipherblklen = 1;
2122 c->in.cipherivlen = 4;
2123 c->in.cipher = rc4decrypt;
2124 cr = secalloc(sizeof(CipherRc4));
2125 memset(cr, 0, sizeof(*cr));
2126 setupRC4state(&cr->current, key, n);
2127 c->in.cipherstate = cr;
2130 memset(key, 0, sizeof(key));
2131 setkey(key, n, &c->out, "cipher");
2132 c->out.cipherblklen = 1;
2133 c->out.cipherivlen = 4;
2134 c->out.cipher = rc4encrypt;
2135 cr = secalloc(sizeof(CipherRc4));
2136 memset(cr, 0, sizeof(*cr));
2137 setupRC4state(&cr->current, key, n);
2138 c->out.cipherstate = cr;
2142 nullauthinit(Conv *c)
2148 shaauthinit(Conv *c)
2154 seanq_hmac_md5(uchar hash[MD5dlen], ulong wrap, uchar *t, long tlen, uchar *key, long klen)
2156 uchar ipad[65], opad[65], wbuf[4];
2158 DigestState *digest;
2159 uchar innerhash[MD5dlen];
2161 for(i=0; i<64; i++){
2165 ipad[64] = opad[64] = 0;
2166 for(i=0; i<klen; i++){
2171 digest = md5(ipad, 64, nil, nil);
2172 digest = md5(wbuf, sizeof(wbuf), nil, digest);
2173 md5(t, tlen, innerhash, digest);
2174 digest = md5(opad, 64, nil, nil);
2175 md5(innerhash, MD5dlen, hash, digest);
2179 md5auth(OneWay *ow, uchar *t, int tlen)
2181 uchar hash[MD5dlen];
2184 if(tlen < ow->authlen)
2186 tlen -= ow->authlen;
2188 memset(hash, 0, MD5dlen);
2189 seanq_hmac_md5(hash, ow->seqwrap, t, tlen, (uchar*)ow->authstate, 16);
2190 r = tsmemcmp(t+tlen, hash, ow->authlen) == 0;
2191 memmove(t+tlen, hash, ow->authlen);
2196 md5authinit(Conv *c)
2202 keylen = c->auth->keylen;
2207 c->in.authstate = secalloc(16);
2208 memset(c->in.authstate, 0, 16);
2209 setkey(c->in.authstate, keylen, &c->in, "auth");
2211 c->in.auth = md5auth;
2214 c->out.authstate = secalloc(16);
2215 memset(c->out.authstate, 0, 16);
2216 setkey(c->out.authstate, keylen, &c->out, "auth");
2217 c->out.authlen = 12;
2218 c->out.auth = md5auth;
2222 nullcompinit(Conv *c)
2228 thwackcomp(Conv *c, int, ulong seq, Block **bp)
2236 b = padblock(*bp, 4);
2238 ackseq = unthwackstate(c->in.compstate, &mask);
2240 b->rp[1] = ackseq>>16;
2241 b->rp[2] = ackseq>>8;
2244 bb = allocb(BLEN(b));
2245 nn = thwack(c->out.compstate, bb->wp, b->rp, BLEN(b), seq, c->lstats.outCompStats);
2259 thwackuncomp(Conv *c, int subtype, ulong seq, Block **bp)
2272 mseq = (b->rp[1]<<16) | (b->rp[2]<<8) | b->rp[3];
2274 thwackack(c->out.compstate, mseq, mask);
2278 b = allocb(ThwMaxBlock);
2279 n = unthwack(c->in.compstate, b->wp, ThwMaxBlock, bb->rp, BLEN(bb), seq);
2283 if(0)print("unthwack failed: %d\n", n);
2289 mseq = (b->rp[1]<<16) | (b->rp[2]<<8) | b->rp[3];
2290 thwackack(c->out.compstate, mseq, mask);
2298 thwackcompinit(Conv *c)
2302 c->in.compstate = malloc(sizeof(Unthwack));
2303 if(c->in.compstate == nil)
2305 unthwackinit(c->in.compstate);
2306 c->out.compstate = malloc(sizeof(Thwack));
2307 if(c->out.compstate == nil)
2309 thwackinit(c->out.compstate);
2310 c->in.comp = thwackuncomp;
2311 c->out.comp = thwackcomp;