pkstream/pkstream.c: Fetch protocol family codes from addresses.
[tripe] / pkstream / pkstream.c
index 665b80e..c0deff7 100644 (file)
@@ -9,19 +9,18 @@
  *
  * This file is part of Trivial IP Encryption (TrIPE).
  *
- * TrIPE is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
+ * TrIPE is free software: you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 3 of the License, or (at your
+ * option) any later version.
  *
- * TrIPE is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
+ * TrIPE is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with TrIPE; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * along with TrIPE.  If not, see <https://www.gnu.org/licenses/>.
  */
 
 /*----- Header files ------------------------------------------------------*/
 #include <mLib/sel.h>
 #include <mLib/selpk.h>
 
+#include "util.h"
+
 /*----- Data structures ---------------------------------------------------*/
 
+typedef union addr {
+  struct sockaddr sa;
+  struct sockaddr_in sin;
+} addr;
+
 typedef struct pk {
   struct pk *next;                     /* Next packet in the chain */
   octet *p, *o;                                /* Buffer start and current posn */
@@ -72,9 +78,10 @@ typedef struct pkstream {
 } pkstream;
 
 typedef struct connwait {
+  unsigned f;                          /* Various flags */
+#define cwf_port 1u                    /*   Port is defined => listen */
   sel_file a;                          /* Selector */
-  struct sockaddr_in me;               /* Who I'm meant to be */
-  struct in_addr peer;                 /* Who my peer is */
+  addr me, peer;                      /* Who I'm meant to be; who peer is */
 } connwait;
 
 /*----- Static variables --------------------------------------------------*/
@@ -82,7 +89,7 @@ typedef struct connwait {
 static sel_state sel;
 static connwait cw;
 static int fd_udp;
-static size_t pk_nmax = 128, pk_szmax = 1024 * 1024;
+static size_t pk_nmax = 128, pk_szmax = 1024*1024;
 
 /*----- Main code ---------------------------------------------------------*/
 
@@ -92,6 +99,42 @@ static int nonblockify(int fd)
 static int cloexec(int fd)
   { return (fdflags(fd, 0, 0, FD_CLOEXEC, FD_CLOEXEC)); }
 
+static socklen_t addrsz(const addr *a)
+{
+  switch (a->sa.sa_family) {
+    case AF_INET: return sizeof(a->sin);
+    default: abort();
+  }
+}
+
+static const char *addrstr(const addr *a)
+{
+  static char buf[128];
+  socklen_t n = sizeof(buf);
+
+  if (getnameinfo(&a->sa, addrsz(a), buf, n, 0, 0, NI_NUMERICHOST))
+    return ("<addrstr failed>");
+  return (buf);
+}
+
+static int addreq(const addr *a, const addr *b)
+{
+  if (a->sa.sa_family != b->sa.sa_family) return (0);
+  switch (a->sa.sa_family) {
+    case AF_INET:
+      return (a->sin.sin_addr.s_addr == b->sin.sin_addr.s_addr);
+    default:
+      abort();
+  }
+}
+
+static void initaddr(addr *a)
+{
+  a->sin.sin_family = AF_INET;
+  a->sin.sin_addr.s_addr = INADDR_ANY;
+  a->sin.sin_port = 0;
+}
+
 static void dolisten(void);
 
 static void doclose(pkstream *p)
@@ -100,35 +143,27 @@ static void doclose(pkstream *p)
   close(p->w.fd);
   close(p->p.reader.fd);
   selpk_destroy(&p->p);
-  if (!(p->f & PKF_FULL))
-    sel_rmfile(&p->r);
-  if (p->npk)
-    sel_rmfile(&p->w);
+  if (!(p->f&PKF_FULL)) sel_rmfile(&p->r);
+  if (p->npk) sel_rmfile(&p->w);
   for (pk = p->pks; pk; pk = ppk) {
     ppk = pk->next;
     xfree(pk->p);
     xfree(pk);
   }
   xfree(p);
-  if (cw.me.sin_port != 0)
-    dolisten();
-  else
-    exit(0);
+  if (cw.f&cwf_port) dolisten();
+  else exit(0);
 }
 
 static void rdtcp(octet *b, size_t sz, pkbuf *pk, size_t *k, void *vp)
 {
   pkstream *p = vp;
   size_t pksz;
-  int hunoz;
 
-  if (!sz) {
-    doclose(p);
-    return;
-  }
+  if (!sz) { doclose(p); return; }
   pksz = LOAD16(b);
   if (pksz + 2 == sz) {
-    hunoz = write(fd_udp, b + 2, pksz);
+    DISCARD(write(fd_udp, b + 2, pksz));
     selpk_want(&p->p, 2);
   } else {
     selpk_want(&p->p, pksz + 2);
@@ -151,8 +186,7 @@ static void wrtcp(int fd, unsigned mode, void *vp)
   }
 
   if ((n = writev(fd, iov, i)) < 0) {
-    if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
-      return;
+    if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return;
     moan("couldn't write to TCP socket: %s", strerror(errno));
     doclose(p);
     return;
@@ -173,14 +207,9 @@ static void wrtcp(int fd, unsigned mode, void *vp)
     }
   }
   p->pks = pk;
-  if (!pk) {
-    p->pk_tail = &p->pks;
-    sel_rmfile(&p->w);
-  }
-  if ((p->f & PKF_FULL) && p->npk < pk_nmax && p->szpk < pk_szmax) {
-    p->f &= ~PKF_FULL;
-    sel_addfile(&p->r);
-  }
+  if (!pk) { p->pk_tail = &p->pks; sel_rmfile(&p->w); }
+  if ((p->f&PKF_FULL) && p->npk < pk_nmax && p->szpk < pk_szmax)
+    { p->f &= ~PKF_FULL; sel_addfile(&p->r); }
 }
 
 static void rdudp(int fd, unsigned mode, void *vp)
@@ -205,15 +234,12 @@ static void rdudp(int fd, unsigned mode, void *vp)
   pk->n = n + 2;
   *p->pk_tail = pk;
   p->pk_tail = &pk->next;
-  if (!p->npk)
-    sel_addfile(&p->w);
+  if (!p->npk) sel_addfile(&p->w);
   sel_force(&p->w);
   p->npk++;
   p->szpk += n + 2;
-  if (p->npk >= pk_nmax || p->szpk >= pk_szmax) {
-    sel_rmfile(&p->r);
-    p->f |= PKF_FULL;
-  }
+  if (p->npk >= pk_nmax || p->szpk >= pk_szmax)
+    { sel_rmfile(&p->r); p->f |= PKF_FULL; }
 }
 
 static void dofwd(int fd_in, int fd_out)
@@ -233,25 +259,21 @@ static void dofwd(int fd_in, int fd_out)
 static void doaccept(int fd_s, unsigned mode, void *p)
 {
   int fd;
-  struct sockaddr_in sin;
-  socklen_t sz = sizeof(sin);
+  addr a;
+  socklen_t sz = sizeof(a);
 
-  if ((fd = accept(fd_s, (struct sockaddr *)&sin, &sz)) < 0) {
-    if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
-      return;
+  if ((fd = accept(fd_s, &a.sa, &sz)) < 0) {
+    if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return;
     moan("couldn't accept incoming connection: %s", strerror(errno));
     return;
   }
-  if (cw.peer.s_addr != INADDR_ANY &&
-      cw.peer.s_addr != sin.sin_addr.s_addr) {
-    close(fd);
-    moan("rejecting connection from %s", inet_ntoa(sin.sin_addr));
-    return;
+  if (cw.peer.sin.sin_addr.s_addr != INADDR_ANY && !addreq(&a, &cw.peer)) {
+    moan("rejecting connection from %s", addrstr(&a));
+    close(fd); return;
   }
   if (nonblockify(fd) || cloexec(fd)) {
-    close(fd);
     moan("couldn't accept incoming connection: %s", strerror(errno));
-    return;
+    close(fd); return;
   }
   dofwd(fd, fd);
   close(fd_s);
@@ -263,46 +285,46 @@ static void dolisten(void)
   int fd;
   int opt = 1;
 
-  if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0 ||
+  if ((fd = socket(cw.me.sa.sa_family, SOCK_STREAM, 0)) < 0 ||
       setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) ||
-      bind(fd, (struct sockaddr *)&cw.me, sizeof(cw.me)) ||
+      bind(fd, &cw.me.sa, addrsz(&cw.me)) ||
       listen(fd, 1) || nonblockify(fd) || cloexec(fd))
     die(1, "couldn't set up listening socket: %s", strerror(errno));
   sel_initfile(&sel, &cw.a, fd, SEL_READ, doaccept, 0);
   sel_addfile(&cw.a);
 }
 
-static void parseaddr(const char *pp, struct in_addr *a, unsigned short *pt)
+#define paf_parse 1u
+static void parseaddr(const char *host, const char *svc, unsigned f, addr *a)
 {
-  char *p = xstrdup(pp);
-  char *q = 0;
-  if (a && pt) {
-    strtok(p, ":");
-    q = strtok(0, "");
-    if (!q)
-      die(1, "missing port number in address `%s'", p);
-  } else if (pt) {
-    q = p;
+  char *alloc = 0, *sep;
+  struct hostent *h;
+  struct servent *s;
+  char *qq;
+  unsigned long n;
+
+  if (f&paf_parse) {
+    alloc = xstrdup(host);
+    if ((sep = strchr(alloc, ':')) == 0)
+      die(1, "missing port number in address `%s'", host);
+    host = alloc; *sep = 0; svc = sep + 1;
   }
 
-  if (a) {
-    struct hostent *h;
-    if ((h = gethostbyname(p)) == 0)
-      die(1, "unknown host `%s'", p);
-    memcpy(a, h->h_addr, sizeof(*a));
+  if (host) {
+    if ((h = gethostbyname(host)) == 0) die(1, "unknown host `%s'", host);
+    memcpy(&a->sin.sin_addr, h->h_addr, sizeof(a->sin.sin_addr));
   }
 
-  if (pt) {
-    struct servent *s;
-    char *qq;
-    unsigned long n;
-    if ((s = getservbyname(q, "tcp")) != 0)
-      *pt = s->s_port;
-    else if ((n = strtoul(q, &qq, 0)) == 0 || *qq || n > 0xffff)
-      die(1, "bad port number `%s'", q);
+  if (svc) {
+    if ((n = strtoul(svc, &qq, 0)) > 0 && !*qq && n <= 0xffff)
+      a->sin.sin_port = htons(n);
+    else if ((s = getservbyname(svc, "tcp")) != 0)
+      a->sin.sin_port = s->s_port;
     else
-      *pt = htons(n);
+      die(1, "bad service name/number `%s'", svc);
   }
+
+  xfree(alloc);
 }
 
 static void usage(FILE *fp)
@@ -340,23 +362,18 @@ stdout; though it can use TCP sockets instead.\n\
 int main(int argc, char *argv[])
 {
   unsigned f = 0;
-  unsigned short pt;
-  struct sockaddr_in connaddr, bindaddr;
-  struct sockaddr_in udp_me, udp_peer;
+  const char *bindhost = 0, *bindsvc = 0, *peerhost = 0;
+  addr bindaddr;
+  const char *connhost = 0;
+  addr tmpaddr;
+  int fd = -1;
   int len = 65536;
 
 #define f_bogus 1u
 
+  cw.f = 0;
+
   ego(argv[0]);
-  bindaddr.sin_family = AF_INET;
-  bindaddr.sin_addr.s_addr = INADDR_ANY;
-  bindaddr.sin_port = 0;
-  connaddr.sin_family = AF_INET;
-  connaddr.sin_addr.s_addr = INADDR_ANY;
-  cw.me.sin_family = AF_INET;
-  cw.me.sin_addr.s_addr = INADDR_ANY;
-  cw.me.sin_port = 0;
-  cw.peer.s_addr = INADDR_ANY;
   sel_init(&sel);
   for (;;) {
     static struct option opt[] = {
@@ -375,68 +392,71 @@ int main(int argc, char *argv[])
     if (i < 0)
       break;
     switch (i) {
-      case 'h':
-       help(stdout);
-       exit(0);
-      case 'v':
-       version(stdout);
-       exit(0);
-      case 'u':
-       usage(stdout);
-       exit(0);
-      case 'l':
-       parseaddr(optarg, 0, &pt);
-       cw.me.sin_port = pt;
-       break;
-      case 'p':
-       parseaddr(optarg, &cw.peer, 0);
-       break;
-      case 'b':
-       parseaddr(optarg, &bindaddr.sin_addr, 0);
-       break;
-      case 'c':
-       parseaddr(optarg, &connaddr.sin_addr, &pt);
-       connaddr.sin_port = pt;
-       break;
-      default:
-       f |= f_bogus;
-       break;
+      case 'h': help(stdout); exit(0);
+      case 'v': version(stdout); exit(0);
+      case 'u': usage(stdout); exit(0);
+      case 'l': bindsvc = optarg; break;
+      case 'p': peerhost = optarg; break;
+      case 'b': bindhost = optarg; break;
+      case 'c': connhost = optarg; break;
+      default: f |= f_bogus; break;
     }
   }
-  if (optind + 2 != argc || (f & f_bogus)) {
-    usage(stderr);
-    exit(1);
+  if (optind + 2 != argc || (f&f_bogus)) { usage(stderr); exit(1); }
+
+  if (bindhost && !bindsvc && !connhost)
+    die(1, "bind addr only makes sense when listening or connecting");
+  if (peerhost && !bindsvc)
+    die(1, "peer addr only makes sense when listening");
+  if (bindsvc && connhost)
+    die(1, "can't listen and connect");
+
+  if (bindhost || bindsvc) {
+    initaddr(&bindaddr);
+    if (!bindsvc) parseaddr(bindhost, 0, 0, &bindaddr);
+    else {
+      initaddr(&cw.me);
+      parseaddr(bindhost, bindsvc, 0, &cw.me);
+      cw.f |= cwf_port;
+    }
   }
 
-  udp_me.sin_family = udp_peer.sin_family = AF_INET;
-  parseaddr(argv[optind], &udp_me.sin_addr, &pt);
-  udp_me.sin_port = pt;
-  parseaddr(argv[optind + 1], &udp_peer.sin_addr, &pt);
-  udp_peer.sin_port = pt;
+  initaddr(&cw.peer);
+  if (peerhost) parseaddr(peerhost, 0, 0, &cw.peer);
+
+  if (connhost) {
+    initaddr(&tmpaddr);
+    parseaddr(connhost, 0, paf_parse, &tmpaddr);
+    if ((fd = socket(tmpaddr.sa.sa_family, SOCK_STREAM, IPPROTO_TCP)) < 0 ||
+       (bindhost &&
+        bind(fd, &bindaddr.sa, addrsz(&bindaddr))) ||
+       connect(fd, &tmpaddr.sa, addrsz(&tmpaddr)))
+      die(1, "couldn't connect to TCP server: %s", strerror(errno));
+    if (nonblockify(fd) || cloexec(fd))
+      die(1, "couldn't connect to TCP server: %s", strerror(errno));
+  }
 
-  if ((fd_udp = socket(PF_INET, SOCK_DGRAM, 0)) < 0 ||
-      bind(fd_udp, (struct sockaddr *)&udp_me, sizeof(udp_me)) ||
-      connect(fd_udp, (struct sockaddr *)&udp_peer, sizeof(udp_peer)) ||
+  initaddr(&tmpaddr);
+  parseaddr(argv[optind], 0, paf_parse, &tmpaddr);
+  if ((fd_udp = socket(tmpaddr.sa.sa_family, SOCK_DGRAM, IPPROTO_UDP)) < 0 ||
+      nonblockify(fd_udp) || cloexec(fd_udp) ||
       setsockopt(fd_udp, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len)) ||
       setsockopt(fd_udp, SOL_SOCKET, SO_SNDBUF, &len, sizeof(len)) ||
-      nonblockify(fd_udp) || cloexec(fd_udp))
+      bind(fd_udp, &tmpaddr.sa, addrsz(&tmpaddr)))
+    die(1, "couldn't set up UDP socket: %s", strerror(errno));
+  initaddr(&tmpaddr);
+  parseaddr(argv[optind + 1], 0, paf_parse, &tmpaddr);
+  if (connect(fd_udp, &tmpaddr.sa, addrsz(&tmpaddr)))
     die(1, "couldn't set up UDP socket: %s", strerror(errno));
 
-  if (cw.me.sin_port != 0)
-    dolisten();
-  else if (connaddr.sin_addr.s_addr != INADDR_ANY) {
-    int fd;
-    if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0 ||
-       bind(fd, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) ||
-       connect(fd, (struct sockaddr *)&connaddr, sizeof(connaddr)) ||
-       nonblockify(fd) || cloexec(fd))
-      die(1, "couldn't connect to TCP server: %s", strerror(errno));
-    dofwd(fd, fd);
-  } else
-    dofwd(STDIN_FILENO, STDOUT_FILENO);
+  if (bindsvc) dolisten();
+  else if (connhost) dofwd(fd, fd);
+  else dofwd(STDIN_FILENO, STDOUT_FILENO);
 
-  for (;;)
-    sel_select(&sel);
+  for (;;) {
+    if (sel_select(&sel) && errno != EINTR)
+      die(1, "select failed: %s", strerror(errno));
+  }
   return (0);
 }