+/*
+ * Encrypting tunnel for userv-ipif tunnels, actual implementation
+ *
+ * usage:
+ * udptunnel-forwarder <public-local-fd> <private-in-fd> <private-out-fd>
+ * <mtu> <keepalive> <timeout>
+ * <public-remote-addr> [<public-remote-port>]
+ * <encdec-keys-fd> <encdec-keys-write>
+ * <mech1> [<mech1-params> ...]
+ * <mech2> [<mech2-params> ...]
+ * ''
+ *
+ * Remote addr may '' to mean wait to receive a packet and reply to
+ * whereever we get a good packet from first, in which case port
+ * should not be specified.
+ *
+ * <enc-keys-write> is '' to mean read, anything else to mean write.
+ *
+ * Every must be numeric. There is very little argument checking.
+ *
+ * Exit status:
+ * SIGALARM timed out
+ * 0 terminated due to outbound packet stream EOF
+ * 4 other error
+ * 8 system problem
+ * 12 usage error
+ * 16 bad trouble
+ */
+
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <sys/utsname.h>
+#include <sys/poll.h>
+
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+#include <stdlib.h>
+
+#include <unistd.h>
+#include <fcntl.h>
+
+#include "mech.h"
+
+#define MAXMECHS 10
+#define PROGRAM "udptunnel-forwarder"
+char programid[SYS_NMLN+sizeof(PROGRAM)+3];
+
+static const char *const *argv;
+static size_t buffer_size;
+
+static int public_local_fd, private_in_fd, private_out_fd;
+static int mtu2, keepalive, timeout;
+static int public_remote_specd;
+static struct sockaddr_in public_remote;
+static int encdec_keys_fd, encdec_keys_write;
+static int n_mechs;
+static const struct mechanism *mechs[MAXMECHS];
+
+static struct mechdata *md_in[MAXMECHS], *md_out[MAXMECHS];
+static size_t maxprefix, maxsuffix;
+
+static struct buffer buf_in, buf_out;
+static unsigned char *accum_buf;
+static size_t accum_used, accum_avail;
+
+static time_t nextsendka;
+
+
+void arg_assert_fail(const char *msg) {
+ fprintf(stderr, PROGRAM ": argument error: %s\n",msg);
+ exit(12);
+}
+
+void sysfail(const char *msg) {
+ fprintf(stderr, "%s: fatal system error: %s: %s\n", programid, msg, strerror(errno));
+ exit(8);
+}
+
+void fail(const char *msg) {
+ fprintf(stderr, "%s: fatal error: %s\n", programid, msg);
+ exit(4);
+}
+
+void sysdiag(const char *msg) {
+ fprintf(stderr, "%s: system/network error: %s: %s\n", programid, msg, strerror(errno));
+}
+
+void diag(const char *msg) {
+ fprintf(stderr, "%s: %s\n", programid, msg);
+}
+
+time_t now(void) {
+ time_t r;
+ if (time(&r) == (time_t)-1) sysfail("get time of day");
+ return r;
+}
+
+void *xmalloc(size_t sz) {
+ void *r;
+ r= malloc(sz);
+ if (!r) sysfail("allocate memory");
+ return r;
+}
+
+void get_random(void *ptr, size_t sz) {
+ static FILE *randfile;
+
+ size_t r;
+
+ if (!randfile) {
+ randfile= fopen("/dev/urandom","rb");
+ if (!randfile && errno==ENOENT) randfile= fopen("/dev/random","rb");
+ if (!randfile) sysfail("open random number generator");
+ }
+
+ r= fread(ptr,1,sz,randfile);
+ if (r == sz) return;
+ (ferror(randfile) ? sysfail : fail)("cannot read random number generator");
+}
+
+const char *getarg_string(void) {
+ const char *arg;
+
+ arg= *++argv;
+ arg_assert(arg);
+ return arg;
+}
+
+unsigned long getarg_ulong(void) {
+ char *ep;
+ unsigned long ul;
+
+ ul= strtoul(getarg_string(),&ep,0);
+ arg_assert(!*ep);
+ return ul;
+}
+
+static void setnonblock(int fd, int nonblock) {
+ int r;
+
+ r= fcntl(fd,F_GETFL);
+ if (r==-1) sysfail("fcntl F_GETFL");
+ r= fcntl(fd,F_SETFL, nonblock ? r|O_NONBLOCK : r&~O_NONBLOCK);
+ if (r==-1) sysfail("fcntl F_SETFL");
+}
+
+static const struct mechanism *getarg_mech(void) {
+ const char *name;
+ const struct mechanism *mech, *const *mechlist;
+
+ name= getarg_string();
+
+ for (mechlist= mechanismlists;
+ *mechlist;
+ mechlist++)
+ for (mech= *mechlist; mech->name; mech++)
+ if (!strcmp(mech->name,name)) return mech;
+
+ fprintf(stderr,"%s: unknown mechanism: %s\n",programid,name);
+ exit(4);
+}
+
+static void inbound(void) {
+ static int any_recvd;
+
+ struct sockaddr_in this_saddr;
+ int r, i, different, this_saddrlen;
+ const char *emsg;
+
+ alarm(timeout);
+
+ setnonblock(public_local_fd,1);
+ this_saddrlen= sizeof(this_saddr);
+ r= recvfrom(public_local_fd, buf_in.base, buffer_size-1, 0,
+ &this_saddr, &this_saddrlen);
+ if (!r) { diag("empty ciphertext"); return; }
+
+ if (r<0) {
+ if (errno != EAGAIN && errno != EINTR) sysdiag("receive");
+ return;
+ }
+ if (this_saddr.sin_family != AF_INET) {
+ fprintf(stderr,"%s: received unknown AF %lu",
+ programid, (unsigned long)this_saddr.sin_family);
+ return;
+ }
+ assert(this_saddrlen == sizeof(this_saddr));
+
+ buf_in.size= buffer_size;
+ buf_in.start= buf_in.base;
+ for (i=n_mechs-1; i>=0; i--) {
+ emsg= mechs[i]->decode(md_in[i],&buf_in);
+ if (emsg) {
+ fprintf(stderr, "%s: bad packet: %s: %s\n", programid, mechs[i]->name, emsg);
+ return;
+ }
+ }
+
+ different= !public_remote_specd ||
+ memcmp(&this_saddr,&public_remote,sizeof(this_saddr));
+
+ if (different) {
+
+ if (public_remote_specd==2) {
+ fprintf(stderr, "%s: packet from unexpected sender %s:%lu",
+ programid, inet_ntoa(this_saddr.sin_addr),
+ (unsigned long)this_saddr.sin_port);
+ return;
+ }
+
+ fprintf(stderr, "%s: tunnel open with peer %s:%lu",
+ programid, inet_ntoa(this_saddr.sin_addr),
+ (unsigned long)this_saddr.sin_port);
+ nextsendka= now();
+ public_remote_specd= 1;
+ memcpy(&public_remote,&this_saddr,sizeof(public_remote));
+
+ } else if (!any_recvd) {
+
+ diag("tunnel open");
+
+ }
+
+ any_recvd= 1;
+
+ buf_in.start[buf_in.size]= 0300;
+ *--buf_in.start= 0300;
+ buf_in.size+= 2;
+
+ setnonblock(private_in_fd,0);
+ while (buf_in.size) {
+ r= write(private_in_fd, buf_in.start, buf_in.size);
+ assert(r && r <= buf_in.size);
+ if (r<0) {
+ if (errno == EINTR) continue;
+ sysfail("write down");
+ }
+ buf_in.start += r;
+ buf_in.size -= r;
+ }
+}
+
+static void sendpacket(const unsigned char *message, size_t size) {
+ int i, r;
+
+ buf_out.start= buf_out.base+maxprefix;
+ buf_out.size= size;
+ memcpy(buf_out.start, message, size);
+
+ nextsendka= now() + keepalive;
+
+ for (i=0; i<n_mechs; i++) mechs[i]->encode(md_out[i],&buf_out);
+ assert(public_remote_specd);
+
+ setnonblock(public_local_fd,1);
+ for (;;) {
+ r= sendto(public_local_fd, buf_out.start, buf_out.size, 0,
+ &public_remote, sizeof(public_remote));
+ if (r == buf_out.size) break;
+ if (r >= 0) { diag("unexpected short send"); return; }
+ if (errno != EINTR) { sysdiag("send"); return; }
+ }
+}
+
+static void outbound(void) {
+ int r;
+ unsigned char *after_eaten, *delim;
+ size_t this_packet;
+
+ setnonblock(private_out_fd,1);
+
+ for (;;) {
+ r= read(private_out_fd, accum_buf + accum_used, accum_avail - accum_used);
+ if (!r) { diag("outbound datastream closed, quitting"); exit(0); }
+ if (r<0) {
+ if (errno == EAGAIN) return;
+ if (errno == EINTR) continue;
+ }
+ accum_used += r;
+ assert(accum_used<=accum_avail);
+
+ after_eaten= accum_buf;
+ while ((delim= memchr(after_eaten, 0300, accum_used))) {
+ this_packet= delim - after_eaten;
+ sendpacket(after_eaten, this_packet);
+ accum_used -= this_packet+1;
+ after_eaten = delim+1;
+ }
+ memmove(accum_buf, after_eaten, accum_used);
+
+ if (accum_used == accum_avail) {
+ diag("missing interpacket delimiter in output datastream");
+ accum_used= 0;
+ }
+ }
+}
+
+int main(int argc, const char *const *const argv_in) {
+ const char *arg;
+ struct pollfd pollfds[2];
+ struct utsname uname_result;
+ int i, polltimeout, r;
+ time_t tnow;
+
+ argv= argv_in;
+
+ if (uname(&uname_result)) { perror(PROGRAM ": uname failed"); exit(16); }
+ sprintf(programid, PROGRAM ": %.*s", SYS_NMLN, uname_result.nodename);
+
+ public_local_fd= getarg_ulong();
+ mtu2= getarg_ulong() * 2;
+ keepalive= getarg_ulong();
+ timeout= getarg_ulong();
+ private_in_fd= getarg_ulong();
+ private_out_fd= getarg_ulong();
+
+ arg= getarg_string();
+ if (*arg) {
+ public_remote_specd= 1;
+ arg_assert(inet_aton(arg,&public_remote.sin_addr));
+ public_remote.sin_port= getarg_ulong();
+ }
+
+ encdec_keys_fd= getarg_ulong();
+ encdec_keys_write= !!*getarg_string();
+
+ maxprefix= 0;
+ for (i=0; i<n_mechs; i++) mechs[i]= getarg_mech();
+ for (i=0; i<n_mechs; i++) mechs[i]->encsetup(&md_in[i], &maxprefix, &maxsuffix);
+ for (i=0; i<n_mechs; i++) mechs[i]->decsetup(&md_out[i]);
+
+ if (maxprefix<1) maxprefix= 1;
+ if (maxsuffix<1) maxsuffix= 1;
+ buffer_size= mtu2 + maxprefix + maxsuffix;
+ buf_in.base= xmalloc(buffer_size);
+ buf_out.base= xmalloc(buffer_size);
+ accum_avail= mtu2 + 1;
+ accum_buf= xmalloc(accum_avail);
+
+ alarm(timeout);
+
+ pollfds[0].fd= public_local_fd;
+ pollfds[0].events= POLLIN;
+ pollfds[1].fd= private_out_fd;
+ for (;;) {
+ pollfds[1].events= public_remote_specd ? POLLIN : 0;
+ pollfds[0].revents= 0;
+ pollfds[1].revents= 0;
+
+ if (keepalive) {
+ tnow= now();
+ if (tnow >= nextsendka) sendpacket("\300",1);
+ polltimeout= (nextsendka - tnow)*1000;
+ } else {
+ polltimeout= -1;
+ }
+
+ r= poll(pollfds,2,polltimeout);
+ if (!r) continue;
+ if (r==-1 && errno==EINTR) continue;
+ if (r==-1) sysfail("poll");
+
+ if (pollfds[0].revents & POLLIN) inbound();
+ if (pollfds[1].revents & POLLOUT) outbound();
+ }
+}