2 * Copyright (c) 2008-2009 Fredrik Lindberg
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include <sys/types.h>
29 #include <sys/param.h>
30 #include <sys/socket.h>
31 #include <sys/sockio.h>
32 #include <sys/select.h>
34 #include <sys/sysctl.h>
36 #include <sys/queue.h>
38 #include <arpa/inet.h>
40 #include <net/if_var.h>
41 #include <net/if_dl.h>
42 #include <net/route.h>
43 #include <netinet/in.h>
44 #include <netinet/in_var.h>
63 * Connection utility to ease connectivity using the raw IP packet interface
64 * available on uhso(4) devices.
67 #define TTY_NAME "/dev/%s"
68 #define SYSCTL_TEST "dev.uhso.%d.%%driver"
69 #define SYSCTL_PORTS "dev.uhso.%d.ports"
70 #define SYSCTL_NETIF "dev.uhso.%d.netif"
71 #define SYSCTL_NAME_TTY "dev.uhso.%d.port.%s.tty"
72 #define SYSCTL_NAME_DESC "dev.uhso.%d.port.%s.desc"
73 #define RESOLV_PATH "/etc/resolv.conf"
74 #define PIDFILE "/var/run/uhsoctl.%s.pid"
76 static const char *network_access_type[] = {
86 static const char *network_reg_status[] = {
89 "Searching for network",
90 "Network registration denied",
92 "Registered (roaming)"
98 #define IPASSIGNED 0x01
99 #define FLG_NODAEMON 0x02 /* Don't detach from terminal */
100 #define FLG_DAEMON 0x04 /* Running as daemon */
101 #define FLG_DELAYED 0x08 /* Fork into background after connect */
102 #define FLG_NEWDATA 0x10
103 #define FLG_WATCHDOG 0x20 /* Watchdog enabled */
104 #define FLG_WDEXP 0x40 /* Watchdog expired */
106 const char *pin; /* device PIN */
113 /* PDP context settings */
116 const char *pdp_user;
119 /* Connection status */
120 int con_status; /* Connected? */
121 char *con_apn; /* Connected APN */
122 char *con_oper; /* Operator name */
123 int con_net_stat; /* Network connection status */
124 int con_net_type; /* Network connection type */
129 /* IP and nameserver settings */
132 const char *resolv_path;
133 char *resolv; /* Old resolv.conf */
137 static int readline_buf(const char *, const char *, char *, size_t);
138 static int readline(int, char *, size_t);
139 static void daemonize(struct ctx *);
141 static int at_cmd_async(int, const char *, ...);
150 typedef void (*resp_cb)(resp_arg *, const char *, const char *);
152 typedef void (*async_cb)(void *, const char *);
153 struct async_handle {
158 static void at_async_creg(void *, const char *);
159 static void at_async_cgreg(void *, const char *);
160 static void at_async_cops(void *, const char *);
161 static void at_async_owancall(void *, const char *);
162 static void at_async_owandata(void *, const char *);
163 static void at_async_csq(void *, const char *);
165 static struct async_handle async_cmd[] = {
166 { "+CREG", at_async_creg },
167 { "+CGREG", at_async_cgreg },
168 { "+COPS", at_async_cops },
169 { "+CSQ", at_async_csq },
170 { "_OWANCALL", at_async_owancall },
171 { "_OWANDATA", at_async_owandata },
177 TAILQ_HEAD(, timer_entry) head;
181 typedef void (*tmr_cb)(int, void *);
183 TAILQ_ENTRY(timer_entry) next;
191 static struct timers timers;
192 static volatile int running = 1;
193 static int syslog_open = 0;
194 static char syslog_title[64];
196 /* Periodic timer, runs ready timer tasks every tick */
198 tmr_run(struct timers *tmrs)
200 struct timer_entry *te, *te2;
202 te = TAILQ_FIRST(&tmrs->head);
206 te->timeout -= tmrs->res;
207 while (te->timeout <= 0) {
208 te2 = TAILQ_NEXT(te, next);
209 TAILQ_REMOVE(&tmrs->head, te, next);
211 te2->timeout -= tmrs->res;
213 te->func(te->id, te->arg);
221 /* Add a new timer */
223 tmr_add(struct timers *tmrs, int id, int timeout, tmr_cb func, void *arg)
225 struct timer_entry *te, *te2, *te3;
227 te = malloc(sizeof(struct timer_entry));
228 memset(te, 0, sizeof(struct timer_entry));
230 te->timeout = timeout;
235 te2 = TAILQ_FIRST(&tmrs->head);
237 if (TAILQ_EMPTY(&tmrs->head)) {
238 TAILQ_INSERT_HEAD(&tmrs->head, te, next);
239 } else if (te->timeout < te2->timeout) {
240 te2->timeout -= te->timeout;
241 TAILQ_INSERT_HEAD(&tmrs->head, te, next);
243 while (te->timeout >= te2->timeout) {
244 te->timeout -= te2->timeout;
245 te3 = TAILQ_NEXT(te2, next);
246 if (te3 == NULL || te3->timeout > te->timeout)
250 TAILQ_INSERT_AFTER(&tmrs->head, te2, te, next);
254 #define watchdog_enable(ctx) (ctx)->flags |= FLG_WATCHDOG
255 #define watchdog_disable(ctx) (ctx)->flags &= ~FLG_WATCHDOG
258 watchdog_reset(struct ctx *ctx, int timeout)
262 clock_gettime(CLOCK_MONOTONIC, &tp),
263 ctx->watchdog = tp.tv_sec + timeout;
265 watchdog_enable(ctx);
269 tmr_creg(int id, void *arg)
271 struct ctx *ctx = arg;
273 at_cmd_async(ctx->fd, "AT+CREG?\r\n");
274 watchdog_reset(ctx, 10);
278 tmr_cgreg(int id, void *arg)
280 struct ctx *ctx = arg;
282 at_cmd_async(ctx->fd, "AT+CGREG?\r\n");
283 watchdog_reset(ctx, 10);
287 tmr_status(int id, void *arg)
289 struct ctx *ctx = arg;
291 at_cmd_async(ctx->fd, "AT+CSQ\r\n");
292 watchdog_reset(ctx, 10);
296 tmr_watchdog(int id, void *arg)
298 struct ctx *ctx = arg;
302 tmr_add(&timers, 1, 5, tmr_watchdog, ctx);
304 if (!(ctx->flags & FLG_WATCHDOG))
307 clock_gettime(CLOCK_MONOTONIC, &tp);
309 if (tp.tv_sec >= ctx->watchdog) {
311 fprintf(stderr, "Watchdog expired\n");
313 ctx->flags |= FLG_WDEXP;
337 logger(int pri, const char *fmt, ...)
343 vasprintf(&buf, fmt, ap);
353 fprintf(stderr, "%s: %s\n", getprogname(), buf);
362 /* Add/remove IP address from an interface */
364 ifaddr_ad(int d, const char *ifnam, struct sockaddr *sa, struct sockaddr *mask)
366 struct ifaliasreq req;
369 fd = socket(AF_INET, SOCK_DGRAM, 0);
373 memset(&req, 0, sizeof(struct ifaliasreq));
374 strlcpy(req.ifra_name, ifnam, sizeof(req.ifra_name));
375 memcpy(&req.ifra_addr, sa, sa->sa_len);
376 memcpy(&req.ifra_mask, mask, mask->sa_len);
378 error = ioctl(fd, d, (char *)&req);
383 #define if_ifup(ifnam) if_setflags(ifnam, IFF_UP)
384 #define if_ifdown(ifnam) if_setflags(ifnam, -IFF_UP)
387 if_setflags(const char *ifnam, int flags)
391 unsigned int oflags = 0;
393 memset(&ifr, 0, sizeof(struct ifreq));
394 strlcpy(ifr.ifr_name, ifnam, sizeof(ifr.ifr_name));
396 fd = socket(AF_INET, SOCK_DGRAM, 0);
400 error = ioctl(fd, SIOCGIFFLAGS, &ifr);
402 oflags = (ifr.ifr_flags & 0xffff) | (ifr.ifr_flagshigh << 16);
410 ifr.ifr_flags = oflags & 0xffff;
411 ifr.ifr_flagshigh = oflags >> 16;
413 error = ioctl(fd, SIOCSIFFLAGS, &ifr);
415 warn("ioctl SIOCSIFFLAGS");
422 ifaddr_add(const char *ifnam, struct sockaddr *sa, struct sockaddr *mask)
426 error = ifaddr_ad(SIOCAIFADDR, ifnam, sa, mask);
428 warn("ioctl SIOCAIFADDR");
433 ifaddr_del(const char *ifnam, struct sockaddr *sa, struct sockaddr *mask)
437 error = ifaddr_ad(SIOCDIFADDR, ifnam, sa, mask);
439 warn("ioctl SIOCDIFADDR");
444 set_nameservers(struct ctx *ctx, const char *respath, int ns, ...)
453 if (ctx->ns != NULL) {
454 for (i = 0; ctx->ns[i] != NULL; i++) {
460 fd = open(respath, O_RDWR | O_CREAT | O_NOFOLLOW);
465 /* Attempt to restore old resolv.conf */
466 if (ctx->resolv != NULL) {
468 lseek(fd, 0, SEEK_SET);
469 write(fd, ctx->resolv, ctx->resolv_sz);
479 ctx->ns = malloc(sizeof(char *) * (ns + 1));
480 if (ctx->ns == NULL) {
486 for (i = 0; i < ns; i++) {
487 p = va_arg(ap, char *);
488 ctx->ns[i] = strdup(p);
493 /* Attempt to backup the old resolv.conf */
494 if (ctx->resolv == NULL) {
496 if (i == 0 && sb.st_size != 0) {
497 ctx->resolv_sz = sb.st_size;
498 ctx->resolv = malloc(sb.st_size);
499 if (ctx->resolv != NULL) {
500 n = read(fd, ctx->resolv, sb.st_size);
501 if (n != sb.st_size) {
511 lseek(fd, 0, SEEK_SET);
512 fp = fdopen(fd, "w");
515 * Write back everything other than nameserver entries to the
518 if (ctx->resolv != NULL) {
520 while ((i = readline_buf(p, ctx->resolv + ctx->resolv_sz, buf,
523 if (strncasecmp(buf, "nameserver", 10) == 0)
525 fprintf(fp, "%s", buf);
529 for (i = 0; ctx->ns[i] != NULL; i++) {
530 fprintf(fp, "nameserver %s\n", ctx->ns[i]);
536 /* Read a \n-terminated line from buffer */
538 readline_buf(const char *s, const char *e, char *buf, size_t bufsz)
546 if (pos >= (bufsz - 1))
555 /* Read a \n-terminated line from file */
557 readline(int fd, char *buf, size_t bufsz)
567 if (pos >= (bufsz - 1))
573 return (n <= 0 ? n : pos);
577 * Synchronous AT command
580 at_cmd(struct ctx *ctx, const char *resp, resp_cb cb, resp_arg *ra, const char *cf, ...)
583 int n, error, retval = 0;
590 vsnprintf(cmd, sizeof(cmd), cf, ap);
594 fprintf(stderr, "SYNC_CMD: %s", cmd);
598 n = write(ctx->fd, cmd, l);
605 fprintf(stderr, "SYNC_EXP: %s (%d)\n", resp, l);
610 bzero(buf, sizeof(buf));
613 watchdog_reset(ctx, 5);
615 FD_SET(ctx->fd, &set);
616 error = select(ctx->fd + 1, &set, NULL, NULL, NULL);
617 if (error < 0 && errno == EINTR && ctx->flags & FLG_WDEXP) {
618 watchdog_disable(ctx);
622 } while (error <= 0 && errno == EINTR);
629 n = readline(ctx->fd, buf, sizeof(buf));
635 if (strcmp(buf, "\r\n") == 0 || strcmp(buf, "\n") == 0)
639 fprintf(stderr, "SYNC_RESP: %s", buf);
642 if (strncmp(buf, "OK", 2) == 0) {
645 else if (strncmp(buf, "ERROR", 5) == 0) {
651 retval = strncmp(resp, buf, l);
652 if (retval == 0 && cb != NULL) {
658 fprintf(stderr, "SYNC_RETVAL=%d\n", retval);
664 at_cmd_async(int fd, const char *cf, ...)
671 vsnprintf(cmd, sizeof(cmd), cf, ap);
675 fprintf(stderr, "CMD: %s", cmd);
678 return (write(fd, cmd, l));
682 saveresp(resp_arg *ra, const char *cmd, const char *resp)
685 int i = ra->val[1].int32;
687 buf = realloc(ra->val[0].ptr, sizeof(char *) * (i + 1));
691 buf[i] = strdup(resp);
693 ra->val[0].ptr = buf;
694 ra->val[1].int32 = i + 1;
698 at_async_creg(void *arg, const char *resp)
700 struct ctx *ctx = arg;
703 n = sscanf(resp, "+CREG: %*d,%d", ®);
705 n = sscanf(resp, "+CREG: %d", ®);
710 if (ctx->con_net_stat != 1 && ctx->con_net_stat != 5) {
711 tmr_add(&timers, 1, 1, tmr_creg, ctx);
714 tmr_add(&timers, 1, 30, tmr_creg, ctx);
717 if (ctx->con_net_stat == reg)
720 ctx->con_net_stat = reg;
721 at_cmd_async(ctx->fd, "AT+COPS?\r\n");
725 at_async_cgreg(void *arg, const char *resp)
727 struct ctx *ctx = arg;
730 n = sscanf(resp, "+CGREG: %*d,%d", ®);
732 n = sscanf(resp, "+CGREG: %d", ®);
737 if (ctx->con_net_stat != 1 && ctx->con_net_stat != 5) {
738 tmr_add(&timers, 1, 1, tmr_cgreg, ctx);
741 tmr_add(&timers, 1, 30, tmr_cgreg, ctx);
744 if (ctx->con_net_stat == reg)
747 ctx->con_net_stat = reg;
748 at_cmd_async(ctx->fd, "AT+COPS?\r\n");
753 at_async_cops(void *arg, const char *resp)
755 struct ctx *ctx = arg;
759 n = sscanf(resp, "+COPS: %*d,%*d,\"%[^\"]\",%d",
764 if (ctx->con_oper != NULL) {
765 if (ctx->con_net_type == at &&
766 strcasecmp(opr, ctx->con_oper) == 0)
771 ctx->con_oper = strdup(opr);
772 ctx->con_net_type = at;
774 if (ctx->con_net_stat == 1 || ctx->con_net_stat == 5) {
775 logger(LOG_NOTICE, "%s to \"%s\" (%s)",
776 network_reg_status[ctx->con_net_stat],
777 ctx->con_oper, network_access_type[ctx->con_net_type]);
778 if (ctx->con_status != 1) {
779 at_cmd_async(ctx->fd, "AT_OWANCALL=%d,1,1\r\n",
784 logger(LOG_NOTICE, "%s (%s)",
785 network_reg_status[ctx->con_net_stat],
786 network_access_type[ctx->con_net_type]);
791 * Signal strength for pretty console output
793 * From 3GPP TS 27.007 V8.3.0, Section 8.5
794 * 0 = -113 dBm or less
796 * 2...30 = -109...-53 dBm
797 * 31 = -51 dBm or greater
799 * So, dbm = (rssi * 2) - 113
802 at_async_csq(void *arg, const char *resp)
804 struct ctx *ctx = arg;
807 n = sscanf(resp, "+CSQ: %d,%*d", &rssi);
813 ctx->dbm = (rssi * 2) - 113;
814 tmr_add(&timers, 1, 15, tmr_status, ctx);
817 ctx->flags |= FLG_NEWDATA;
821 at_async_owancall(void *arg, const char *resp)
823 struct ctx *ctx = arg;
826 n = sscanf(resp, "_OWANCALL: %*d,%d", &i);
830 if (i == ctx->con_status)
833 at_cmd_async(ctx->fd, "AT_OWANDATA=%d\r\n", ctx->pdp_ctx);
836 if (ctx->con_status == 1) {
837 logger(LOG_NOTICE, "Connected to \"%s\" (%s), %s",
838 ctx->con_oper, ctx->con_apn,
839 network_access_type[ctx->con_net_type]);
842 logger(LOG_NOTICE, "Disconnected from \"%s\" (%s)",
843 ctx->con_oper, ctx->con_apn);
848 at_async_owandata(void *arg, const char *resp)
850 struct ctx *ctx = arg;
851 char ip[40], ns1[40], ns2[40];
853 struct ifaddrs *ifap, *ifa;
854 struct sockaddr_in sin, mask;
855 struct sockaddr_dl sdl;
857 struct rt_msghdr rtm;
862 n = sscanf(resp, "_OWANDATA: %*d, %[^,], %*[^,], %[^,], %[^,]",
867 /* XXX: AF_INET assumption */
869 logger(LOG_NOTICE, "IP address: %s, Nameservers: %s, %s", ip, ns1, ns2);
871 sin.sin_len = mask.sin_len = sizeof(struct sockaddr_in);
872 memset(&mask.sin_addr.s_addr, 0xff, sizeof(mask.sin_addr.s_addr));
873 sin.sin_family = mask.sin_family = AF_INET;
875 if (ctx->flags & IPASSIGNED) {
876 memcpy(&sin.sin_addr.s_addr, &ctx->ip.s_addr,
877 sizeof(sin.sin_addr.s_addr));
878 ifaddr_del(ctx->ifnam, (struct sockaddr *)&sin,
879 (struct sockaddr *)&mask);
881 inet_pton(AF_INET, ip, &ctx->ip.s_addr);
882 memcpy(&sin.sin_addr.s_addr, &ctx->ip.s_addr,
883 sizeof(sin.sin_addr.s_addr));
885 error = ifaddr_add(ctx->ifnam, (struct sockaddr *)&sin,
886 (struct sockaddr *)&mask);
888 logger(LOG_ERR, "failed to set ip-address");
894 ctx->flags |= IPASSIGNED;
896 set_nameservers(ctx, ctx->resolv_path, 0);
897 error = set_nameservers(ctx, ctx->resolv_path, 2, ns1, ns2);
899 logger(LOG_ERR, "failed to set nameservers");
902 error = getifaddrs(&ifap);
904 logger(LOG_ERR, "getifaddrs: %s", strerror(errno));
908 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
909 if (ifa->ifa_addr->sa_family != AF_LINK)
911 if (strcmp(ctx->ifnam, ifa->ifa_name) == 0) {
912 memcpy(&sdl, (struct sockaddr_dl *)ifa->ifa_addr,
913 sizeof(struct sockaddr_dl));
920 rs = socket(PF_ROUTE, SOCK_RAW, 0);
922 logger(LOG_ERR, "socket PF_ROUTE: %s", strerror(errno));
926 memset(&r, 0, sizeof(r));
928 r.rtm.rtm_version = RTM_VERSION;
929 r.rtm.rtm_type = RTM_ADD;
930 r.rtm.rtm_flags = RTF_UP | RTF_STATIC;
931 r.rtm.rtm_pid = getpid();
932 memset(&sin, 0, sizeof(struct sockaddr_in));
933 sin.sin_family = AF_INET;
934 sin.sin_len = sizeof(struct sockaddr_in);
936 memcpy(cp, &sin, sin.sin_len);
938 memcpy(cp, &sdl, sdl.sdl_len);
940 memcpy(cp, &sin, sin.sin_len);
941 r.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
942 r.rtm.rtm_msglen = sizeof(r);
944 n = write(rs, &r, r.rtm.rtm_msglen);
945 if (n != r.rtm.rtm_msglen) {
946 r.rtm.rtm_type = RTM_DELETE;
947 n = write(rs, &r, r.rtm.rtm_msglen);
948 r.rtm.rtm_type = RTM_ADD;
949 n = write(rs, &r, r.rtm.rtm_msglen);
952 if (n != r.rtm.rtm_msglen) {
953 logger(LOG_ERR, "failed to set default route: %s",
958 /* Delayed daemonization */
959 if ((ctx->flags & FLG_DELAYED) && !(ctx->flags & FLG_NODAEMON))
964 at_async(struct ctx *ctx, void *arg)
970 watchdog_reset(ctx, 15);
972 bzero(buf, sizeof(buf));
973 n = readline(ctx->fd, buf, sizeof(buf));
975 return (n <= 0 ? -1 : 0);
978 fprintf(stderr, "AT_ASYNC_RESP: %s", buf);
980 for (i = 0; async_cmd[i].cmd != NULL; i++) {
981 l = strlen(async_cmd[i].cmd);
982 if (strncmp(buf, async_cmd[i].cmd, l) == 0) {
983 async_cmd[i].func(arg, buf);
989 static const char *port_type_list[] = {
990 "control", "application", "application2", NULL
994 * Attempts to find a list of control tty for the interface
995 * FreeBSD attaches USb devices per interface so we have to go through
996 * hoops to find which ttys that belong to our network interface.
999 get_tty(struct ctx *ctx)
1010 for (i = 0; ; i++) {
1011 /* Basic test to check if we're even in the right ballpark */
1012 snprintf(buf, 64, SYSCTL_TEST, i);
1014 error = sysctlbyname(buf, data, &len, NULL, 0);
1016 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1017 buf, error, error == 0 ? data : "FAILED");
1021 if (strcasecmp(data, "uhso") != 0)
1024 /* Check for interface */
1025 snprintf(buf, 64, SYSCTL_NETIF, i);
1027 error = sysctlbyname(buf, data, &len, NULL, 0);
1029 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1030 buf, error, error == 0 ? data : "FAILED");
1035 if (strcasecmp(data, ctx->ifnam) != 0)
1038 fprintf(stderr, "Found %s at %s\n", ctx->ifnam, buf);
1043 /* Add multiplexed ports */
1044 for (p = port_type_list; *p != NULL; p++) {
1045 snprintf(buf, 64, SYSCTL_NAME_TTY, i, *p);
1047 error = sysctlbyname(buf, data, &len, NULL, 0);
1049 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1050 buf, error, error == 0 ? data : "FAILED");
1053 list = realloc(list, (list_size + 1) * sizeof(char *));
1054 list[list_size] = malloc(strlen(data) + strlen(TTY_NAME));
1055 sprintf(list[list_size], TTY_NAME, data);
1061 * We can return directly if we found multiplexed serial ports because
1062 * devices with these ports only have additional diagnostic ports (useless)
1063 * and modem ports (for used with pppd).
1065 if (list_size > 0) {
1066 list = realloc(list, (list_size + 1) * sizeof(char *));
1067 list[list_size] = NULL;
1072 * The network port is on a high numbered interface so we walk backwards until
1073 * we hit anything other than application/control.
1076 for (--i; i >= 0; i--) {
1077 /* Basic test to check if we're even in the right ballpark */
1078 snprintf(buf, 64, SYSCTL_TEST, i);
1080 error = sysctlbyname(buf, data, &len, NULL, 0);
1082 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1083 buf, error, error == 0 ? data : "FAILED");
1087 if (strcasecmp(data, "uhso") != 0)
1090 /* Test for useable ports */
1091 for (p = port_type_list; *p != NULL; p++) {
1092 snprintf(buf, 64, SYSCTL_NAME_TTY, i, p);
1094 error = sysctlbyname(buf, data, &len, NULL, 0);
1096 list = realloc(list, (list_size + 1) * sizeof(char *));
1097 list[list_size] = malloc(strlen(data) + strlen(TTY_NAME));
1098 sprintf(list[list_size], TTY_NAME, data);
1103 /* HACK! first port is a diagnostic port, we abort here */
1104 snprintf(buf, 64, SYSCTL_NAME_TTY, i, "diagnostic");
1106 error = sysctlbyname(buf, data, &len, NULL, 0);
1108 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1109 buf, error, error == 0 ? data : "FAILED");
1115 list = realloc(list, (list_size + 1) * sizeof(char *));
1116 list[list_size] = NULL;
1121 do_connect(struct ctx *ctx, const char *tty)
1123 int i, error, needcfg;
1129 fprintf(stderr, "Attempting to open %s\n", tty);
1132 ctx->fd = open(tty, O_RDWR);
1135 fprintf(stderr, "Failed to open %s\n", tty);
1140 tcgetattr(ctx->fd, &t);
1143 t.c_cflag = CLOCAL | CREAD;
1145 tcsetattr(ctx->fd, TCSAFLUSH, &t);
1147 error = at_cmd(ctx, NULL, NULL, NULL, "AT\r\n");
1149 warnx("failed to read from device");
1154 error = at_cmd(ctx, "+CPIN: READY", NULL, NULL, "AT+CPIN?\r\n");
1156 if (ctx->pin == NULL) {
1157 errx(1, "device requires PIN");
1160 error = at_cmd(ctx, NULL, NULL, NULL, "AT+CPIN=\"%s\"\r\n",
1163 errx(1, "wrong PIN");
1168 * Check if a PDP context has been configured and configure one
1171 ra.val[0].ptr = NULL;
1172 ra.val[1].int32 = 0;
1173 error = at_cmd(ctx, "+CGDCONT", saveresp, &ra, "AT+CGDCONT?\r\n");
1174 buf = ra.val[0].ptr;
1176 for (i = 0; i < ra.val[1].int32; i++) {
1179 error = sscanf(buf[i], "+CGDCONT: %d,\"%*[^\"]\",\"%[^\"]\"",
1186 if (cid == ctx->pdp_ctx) {
1187 ctx->con_apn = strdup(apn);
1188 if (ctx->pdp_apn != NULL) {
1189 if (strcmp(apn, ctx->pdp_apn) == 0)
1201 if (ctx->pdp_apn == NULL)
1202 errx(1, "device is not configured and no APN given");
1204 error = at_cmd(ctx, NULL, NULL, NULL,
1205 "AT+CGDCONT=%d,,\"%s\"\r\n", ctx->pdp_ctx, ctx->pdp_apn);
1207 errx(1, "failed to configure device");
1209 ctx->con_apn = strdup(ctx->pdp_apn);
1212 if (ctx->pdp_user != NULL || ctx->pdp_pwd != NULL) {
1213 at_cmd(ctx, NULL, NULL, NULL,
1214 "AT$QCPDPP=%d,1,\"%s\",\"%s\"\r\n", ctx->pdp_ctx,
1215 (ctx->pdp_user != NULL) ? ctx->pdp_user : "",
1216 (ctx->pdp_pwd != NULL) ? ctx->pdp_pwd : "");
1219 error = at_cmd(ctx, NULL, NULL, NULL, "AT_OWANCALL=%d,0,0\r\n",
1224 at_cmd_async(ctx->fd, "AT+CGREG?\r\n");
1225 at_cmd_async(ctx->fd, "AT+CREG?\r\n");
1227 tmr_add(&timers, 1, 5, tmr_status, ctx);
1232 do_disconnect(struct ctx *ctx)
1234 struct sockaddr_in sin, mask;
1237 at_cmd(ctx, NULL, NULL, NULL, "AT_OWANCALL=%d,0,0\r\n",
1241 /* Remove ip-address from interface */
1242 if (ctx->flags & IPASSIGNED) {
1243 sin.sin_len = mask.sin_len = sizeof(struct sockaddr_in);
1244 memset(&mask.sin_addr.s_addr, 0xff,
1245 sizeof(mask.sin_addr.s_addr));
1246 sin.sin_family = mask.sin_family = AF_INET;
1247 memcpy(&sin.sin_addr.s_addr, &ctx->ip.s_addr,
1248 sizeof(sin.sin_addr.s_addr));
1249 ifaddr_del(ctx->ifnam, (struct sockaddr *)&sin,
1250 (struct sockaddr *)&mask);
1252 if_ifdown(ctx->ifnam);
1253 ctx->flags &= ~IPASSIGNED;
1256 /* Attempt to reset resolv.conf */
1257 set_nameservers(ctx, ctx->resolv_path, 0);
1261 daemonize(struct ctx *ctx)
1266 snprintf(ctx->pidfile, 127, PIDFILE, ctx->ifnam);
1268 pfh = pidfile_open(ctx->pidfile, 0600, &opid);
1270 warn("Cannot create pidfile %s", ctx->pidfile);
1274 if (daemon(0, 0) == -1) {
1275 warn("Cannot daemonize");
1276 pidfile_remove(pfh);
1282 ctx->flags |= FLG_DAEMON;
1284 snprintf(syslog_title, 63, "%s:%s", getprogname(), ctx->ifnam);
1285 openlog(syslog_title, LOG_PID, LOG_USER);
1290 send_disconnect(const char *ifnam)
1297 snprintf(pidfile, 127, PIDFILE, ifnam);
1298 fp = fopen(pidfile, "r");
1300 warn("Cannot open %s", pidfile);
1304 n = fscanf(fp, "%d", &pid);
1307 warnx("unable to read daemon pid");
1311 fprintf(stderr, "Sending SIGTERM to %d\n", pid);
1317 usage(const char *exec)
1320 printf("usage %s [-b] [-n] [-a apn] [-c cid] [-p pin] [-u username] "
1321 "[-k password] [-r resolvpath] [-f tty] interface\n", exec);
1322 printf("usage %s -d interface\n", exec);
1331 main(int argc, char *argv[])
1333 int ch, error, mode;
1334 const char *ifnam = NULL;
1336 char **p, **tty_list;
1339 struct itimerval it;
1341 TAILQ_INIT(&timers.head);
1345 ctx.pdp_apn = ctx.pdp_user = ctx.pdp_pwd = NULL;
1350 ctx.con_oper = NULL;
1351 ctx.con_net_stat = 0;
1352 ctx.con_net_type = -1;
1354 ctx.resolv_path = RESOLV_PATH;
1360 ctx.flags |= FLG_DELAYED;
1362 while ((ch = getopt(argc, argv, "?ha:p:c:u:k:r:f:dbn")) != -1) {
1365 ctx.pdp_apn = argv[optind - 1];
1368 ctx.pdp_ctx = strtol(argv[optind - 1], NULL, 10);
1369 if (ctx.pdp_ctx < 1) {
1370 warnx("Invalid context ID, defaulting to 1");
1375 ctx.pin = argv[optind - 1];
1378 ctx.pdp_user = argv[optind - 1];
1381 ctx.pdp_pwd = argv[optind - 1];
1384 ctx.resolv_path = argv[optind - 1];
1390 ctx.flags &= ~FLG_DELAYED;
1393 ctx.flags |= FLG_NODAEMON;
1396 tty = argv[optind - 1];
1410 errx(1, "no interface given");
1412 ifnam = argv[argc - 1];
1413 ctx.ifnam = strdup(ifnam);
1417 printf("Disconnecting %s\n", ifnam);
1418 send_disconnect(ifnam);
1424 signal(SIGHUP, sig_handle);
1425 signal(SIGINT, sig_handle);
1426 signal(SIGQUIT, sig_handle);
1427 signal(SIGTERM, sig_handle);
1428 signal(SIGALRM, sig_handle);
1430 it.it_interval.tv_sec = 1;
1431 it.it_interval.tv_usec = 0;
1432 it.it_value.tv_sec = 1;
1433 it.it_value.tv_usec = 0;
1434 error = setitimer(ITIMER_REAL, &it, NULL);
1436 errx(1, "setitimer");
1438 tmr_add(&timers, 1, 5, &tmr_watchdog, &ctx);
1439 watchdog_reset(&ctx, 15);
1442 error = do_connect(&ctx, tty);
1444 errx(1, "Failed to open %s", tty);
1447 tty_list = get_tty(&ctx);
1449 if (tty_list == NULL) {
1450 fprintf(stderr, "get_tty returned empty list\n");
1452 fprintf(stderr, "tty list:\n");
1453 for (p = tty_list; *p != NULL; p++) {
1454 fprintf(stderr, "\t %s\n", *p);
1458 for (p = tty_list; *p != NULL; p++) {
1459 error = do_connect(&ctx, *p);
1466 errx(1, "Failed to obtain a control port, "
1467 "try specifying one manually");
1470 if (!(ctx.flags & FLG_DELAYED) && !(ctx.flags & FLG_NODAEMON))
1475 FD_SET(ctx.fd, &set);
1478 watchdog_disable(&ctx);
1479 error = select(ctx.fd + 1, &set, NULL, NULL, NULL);
1481 if (running && errno == EINTR)
1483 if (ctx.flags & FLG_WDEXP) {
1484 ctx.flags &= ~FLG_WDEXP;
1485 watchdog_reset(&ctx, 5);
1486 do_disconnect(&ctx);
1487 watchdog_reset(&ctx, 15);
1488 do_connect(&ctx, tty);
1496 if (FD_ISSET(ctx.fd, &set)) {
1497 watchdog_reset(&ctx, 15);
1498 error = at_async(&ctx, &ctx);
1502 FD_SET(ctx.fd, &set);
1504 if (!(ctx.flags & FLG_DAEMON) && (ctx.flags & IPASSIGNED)) {
1505 printf("Status: %s (%s)",
1506 ctx.con_status ? "connected" : "disconnected",
1507 network_access_type[ctx.con_net_type]);
1509 printf(", signal: %d dBm", ctx.dbm);
1514 if (!(ctx.flags & FLG_DAEMON) && (ctx.flags & IPASSIGNED))
1517 signal(SIGHUP, SIG_DFL);
1518 signal(SIGINT, SIG_DFL);
1519 signal(SIGQUIT, SIG_DFL);
1520 signal(SIGTERM, SIG_DFL);
1521 signal(SIGALRM, SIG_IGN);
1523 do_disconnect(&ctx);
1525 if (ctx.flags & FLG_DAEMON) {
1526 pidfile_remove(ctx.pfh);