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_LOCATION "dev.uhso.%d.%%location"
70 #define SYSCTL_PORTS "dev.uhso.%d.ports"
71 #define SYSCTL_NETIF "dev.uhso.%d.netif"
72 #define SYSCTL_NAME_TTY "dev.uhso.%d.port.%s.tty"
73 #define SYSCTL_NAME_DESC "dev.uhso.%d.port.%s.desc"
74 #define RESOLV_PATH "/etc/resolv.conf"
75 #define PIDFILE "/var/run/uhsoctl.%s.pid"
77 static const char *network_access_type[] = {
87 static const char *network_reg_status[] = {
90 "Searching for network",
91 "Network registration denied",
93 "Registered (roaming)"
99 #define IPASSIGNED 0x01
100 #define FLG_NODAEMON 0x02 /* Don't detach from terminal */
101 #define FLG_DAEMON 0x04 /* Running as daemon */
102 #define FLG_DELAYED 0x08 /* Fork into background after connect */
103 #define FLG_NEWDATA 0x10
104 #define FLG_WATCHDOG 0x20 /* Watchdog enabled */
105 #define FLG_WDEXP 0x40 /* Watchdog expired */
107 const char *pin; /* device PIN */
114 /* PDP context settings */
117 const char *pdp_user;
120 /* Connection status */
121 int con_status; /* Connected? */
122 char *con_apn; /* Connected APN */
123 char *con_oper; /* Operator name */
124 int con_net_stat; /* Network connection status */
125 int con_net_type; /* Network connection type */
130 /* IP and nameserver settings */
133 const char *resolv_path;
134 char *resolv; /* Old resolv.conf */
138 static int readline_buf(const char *, const char *, char *, size_t);
139 static int readline(int, char *, size_t);
140 static void daemonize(struct ctx *);
142 static int at_cmd_async(int, const char *, ...);
151 typedef void (*resp_cb)(resp_arg *, const char *, const char *);
153 typedef void (*async_cb)(void *, const char *);
154 struct async_handle {
159 static void at_async_creg(void *, const char *);
160 static void at_async_cgreg(void *, const char *);
161 static void at_async_cops(void *, const char *);
162 static void at_async_owancall(void *, const char *);
163 static void at_async_owandata(void *, const char *);
164 static void at_async_csq(void *, const char *);
166 static struct async_handle async_cmd[] = {
167 { "+CREG", at_async_creg },
168 { "+CGREG", at_async_cgreg },
169 { "+COPS", at_async_cops },
170 { "+CSQ", at_async_csq },
171 { "_OWANCALL", at_async_owancall },
172 { "_OWANDATA", at_async_owandata },
178 TAILQ_HEAD(, timer_entry) head;
182 typedef void (*tmr_cb)(int, void *);
184 TAILQ_ENTRY(timer_entry) next;
192 static struct timers timers;
193 static volatile int running = 1;
194 static int syslog_open = 0;
195 static char syslog_title[64];
197 /* Periodic timer, runs ready timer tasks every tick */
199 tmr_run(struct timers *tmrs)
201 struct timer_entry *te, *te2;
203 te = TAILQ_FIRST(&tmrs->head);
207 te->timeout -= tmrs->res;
208 while (te->timeout <= 0) {
209 te2 = TAILQ_NEXT(te, next);
210 TAILQ_REMOVE(&tmrs->head, te, next);
211 te->func(te->id, te->arg);
219 /* Add a new timer */
221 tmr_add(struct timers *tmrs, int id, int timeout, tmr_cb func, void *arg)
223 struct timer_entry *te, *te2, *te3;
225 te = malloc(sizeof(struct timer_entry));
226 memset(te, 0, sizeof(struct timer_entry));
228 te->timeout = timeout;
233 te2 = TAILQ_FIRST(&tmrs->head);
235 if (TAILQ_EMPTY(&tmrs->head)) {
236 TAILQ_INSERT_HEAD(&tmrs->head, te, next);
237 } else if (te->timeout < te2->timeout) {
238 te2->timeout -= te->timeout;
239 TAILQ_INSERT_HEAD(&tmrs->head, te, next);
241 while (te->timeout >= te2->timeout) {
242 te->timeout -= te2->timeout;
243 te3 = TAILQ_NEXT(te2, next);
244 if (te3 == NULL || te3->timeout > te->timeout)
248 TAILQ_INSERT_AFTER(&tmrs->head, te2, te, next);
252 #define watchdog_enable(ctx) (ctx)->flags |= FLG_WATCHDOG
253 #define watchdog_disable(ctx) (ctx)->flags &= ~FLG_WATCHDOG
256 watchdog_reset(struct ctx *ctx, int timeout)
260 clock_gettime(CLOCK_MONOTONIC, &tp),
261 ctx->watchdog = tp.tv_sec + timeout;
263 watchdog_enable(ctx);
267 tmr_creg(int id, void *arg)
269 struct ctx *ctx = arg;
271 at_cmd_async(ctx->fd, "AT+CREG?\r\n");
272 watchdog_reset(ctx, 10);
276 tmr_cgreg(int id, void *arg)
278 struct ctx *ctx = arg;
280 at_cmd_async(ctx->fd, "AT+CGREG?\r\n");
281 watchdog_reset(ctx, 10);
285 tmr_status(int id, void *arg)
287 struct ctx *ctx = arg;
289 at_cmd_async(ctx->fd, "AT+CSQ\r\n");
290 watchdog_reset(ctx, 10);
294 tmr_watchdog(int id, void *arg)
296 struct ctx *ctx = arg;
300 tmr_add(&timers, 1, 5, tmr_watchdog, ctx);
302 if (!(ctx->flags & FLG_WATCHDOG))
305 clock_gettime(CLOCK_MONOTONIC, &tp);
307 if (tp.tv_sec >= ctx->watchdog) {
309 fprintf(stderr, "Watchdog expired\n");
311 ctx->flags |= FLG_WDEXP;
335 logger(int pri, const char *fmt, ...)
341 vasprintf(&buf, fmt, ap);
343 syslog(pri, "%s", buf);
351 fprintf(stderr, "%s: %s\n", getprogname(), buf);
360 /* Add/remove IP address from an interface */
362 ifaddr_ad(int d, const char *ifnam, struct sockaddr *sa, struct sockaddr *mask)
364 struct ifaliasreq req;
367 fd = socket(AF_INET, SOCK_DGRAM, 0);
371 memset(&req, 0, sizeof(struct ifaliasreq));
372 strlcpy(req.ifra_name, ifnam, sizeof(req.ifra_name));
373 memcpy(&req.ifra_addr, sa, sa->sa_len);
374 memcpy(&req.ifra_mask, mask, mask->sa_len);
376 error = ioctl(fd, d, (char *)&req);
381 #define if_ifup(ifnam) if_setflags(ifnam, IFF_UP)
382 #define if_ifdown(ifnam) if_setflags(ifnam, -IFF_UP)
385 if_setflags(const char *ifnam, int flags)
389 unsigned int oflags = 0;
391 memset(&ifr, 0, sizeof(struct ifreq));
392 strlcpy(ifr.ifr_name, ifnam, sizeof(ifr.ifr_name));
394 fd = socket(AF_INET, SOCK_DGRAM, 0);
398 error = ioctl(fd, SIOCGIFFLAGS, &ifr);
400 oflags = (ifr.ifr_flags & 0xffff) | (ifr.ifr_flagshigh << 16);
408 ifr.ifr_flags = oflags & 0xffff;
409 ifr.ifr_flagshigh = oflags >> 16;
411 error = ioctl(fd, SIOCSIFFLAGS, &ifr);
413 warn("ioctl SIOCSIFFLAGS");
420 ifaddr_add(const char *ifnam, struct sockaddr *sa, struct sockaddr *mask)
424 error = ifaddr_ad(SIOCAIFADDR, ifnam, sa, mask);
426 warn("ioctl SIOCAIFADDR");
431 ifaddr_del(const char *ifnam, struct sockaddr *sa, struct sockaddr *mask)
435 error = ifaddr_ad(SIOCDIFADDR, ifnam, sa, mask);
437 warn("ioctl SIOCDIFADDR");
442 set_nameservers(struct ctx *ctx, const char *respath, int ns, ...)
451 if (ctx->ns != NULL) {
452 for (i = 0; ctx->ns[i] != NULL; i++) {
458 fd = open(respath, O_RDWR | O_CREAT | O_NOFOLLOW, 0666);
463 /* Attempt to restore old resolv.conf */
464 if (ctx->resolv != NULL) {
466 lseek(fd, 0, SEEK_SET);
467 write(fd, ctx->resolv, ctx->resolv_sz);
477 ctx->ns = malloc(sizeof(char *) * (ns + 1));
478 if (ctx->ns == NULL) {
484 for (i = 0; i < ns; i++) {
485 p = va_arg(ap, char *);
486 ctx->ns[i] = strdup(p);
491 /* Attempt to backup the old resolv.conf */
492 if (ctx->resolv == NULL) {
494 if (i == 0 && sb.st_size != 0) {
495 ctx->resolv_sz = sb.st_size;
496 ctx->resolv = malloc(sb.st_size);
497 if (ctx->resolv != NULL) {
498 n = read(fd, ctx->resolv, sb.st_size);
499 if (n != sb.st_size) {
509 lseek(fd, 0, SEEK_SET);
510 fp = fdopen(fd, "w");
513 * Write back everything other than nameserver entries to the
516 if (ctx->resolv != NULL) {
518 while ((i = readline_buf(p, ctx->resolv + ctx->resolv_sz, buf,
521 if (strncasecmp(buf, "nameserver", 10) == 0)
523 fprintf(fp, "%s", buf);
527 for (i = 0; ctx->ns[i] != NULL; i++) {
528 fprintf(fp, "nameserver %s\n", ctx->ns[i]);
534 /* Read a \n-terminated line from buffer */
536 readline_buf(const char *s, const char *e, char *buf, size_t bufsz)
544 if (pos >= (bufsz - 1))
553 /* Read a \n-terminated line from file */
555 readline(int fd, char *buf, size_t bufsz)
565 if (pos >= (bufsz - 1))
571 return (n <= 0 ? n : pos);
575 * Synchronous AT command
578 at_cmd(struct ctx *ctx, const char *resp, resp_cb cb, resp_arg *ra, const char *cf, ...)
583 int n, error, retval = 0;
589 vsnprintf(cmd, sizeof(cmd), cf, ap);
593 fprintf(stderr, "SYNC_CMD: %s", cmd);
597 n = write(ctx->fd, cmd, l);
604 fprintf(stderr, "SYNC_EXP: %s (%d)\n", resp, l);
609 bzero(buf, sizeof(buf));
612 watchdog_reset(ctx, 5);
614 FD_SET(ctx->fd, &set);
615 error = select(ctx->fd + 1, &set, NULL, NULL, NULL);
616 if (ctx->flags & FLG_WDEXP) {
617 watchdog_disable(ctx);
620 } while (error <= 0 && errno == EINTR);
621 watchdog_disable(ctx);
628 n = readline(ctx->fd, buf, sizeof(buf));
634 if (strcmp(buf, "\r\n") == 0 || strcmp(buf, "\n") == 0)
637 if ((p = strchr(buf, '\r')) != NULL)
639 else if ((p = strchr(buf, '\n')) != NULL)
642 fprintf(stderr, "SYNC_RESP: %s\n", buf);
645 /* Skip local echo */
646 if (strncasecmp(cmd, buf, strlen(buf)) == 0)
652 if (strncmp(buf, "OK", 2) == 0) {
653 retval = retval ? retval : 0;
655 } else if (strstr(buf, "ERROR") != NULL) {
660 retval = strncmp(buf, resp, l);
663 fprintf(stderr, "SYNC_RETVAL=%d\n", retval);
669 at_cmd_async(int fd, const char *cf, ...)
676 vsnprintf(cmd, sizeof(cmd), cf, ap);
680 fprintf(stderr, "CMD: %s", cmd);
683 return (write(fd, cmd, l));
687 saveresp(resp_arg *ra, const char *cmd, const char *resp)
690 int i = ra->val[1].int32;
693 fprintf(stderr, "Save '%s'\n", resp);
696 buf = realloc(ra->val[0].ptr, sizeof(char *) * (i + 1));
700 buf[i] = strdup(resp);
702 ra->val[0].ptr = buf;
703 ra->val[1].int32 = i + 1;
707 freeresp(resp_arg *ra)
712 buf = ra->val[0].ptr;
713 for (i = 0; i < ra->val[1].int32; i++) {
720 at_async_creg(void *arg, const char *resp)
722 struct ctx *ctx = arg;
725 n = sscanf(resp, "+CREG: %*d,%d", ®);
727 n = sscanf(resp, "+CREG: %d", ®);
732 if (ctx->con_net_stat != 1 && ctx->con_net_stat != 5) {
733 tmr_add(&timers, 1, 1, tmr_creg, ctx);
736 tmr_add(&timers, 1, 30, tmr_creg, ctx);
739 if (ctx->con_net_stat == reg)
742 ctx->con_net_stat = reg;
743 at_cmd_async(ctx->fd, "AT+COPS?\r\n");
747 at_async_cgreg(void *arg, const char *resp)
749 struct ctx *ctx = arg;
752 n = sscanf(resp, "+CGREG: %*d,%d", ®);
754 n = sscanf(resp, "+CGREG: %d", ®);
759 if (ctx->con_net_stat != 1 && ctx->con_net_stat != 5) {
760 tmr_add(&timers, 1, 1, tmr_cgreg, ctx);
763 tmr_add(&timers, 1, 30, tmr_cgreg, ctx);
766 if (ctx->con_net_stat == reg)
769 ctx->con_net_stat = reg;
770 at_cmd_async(ctx->fd, "AT+COPS?\r\n");
775 at_async_cops(void *arg, const char *resp)
777 struct ctx *ctx = arg;
781 n = sscanf(resp, "+COPS: %*d,%*d,\"%[^\"]\",%d",
786 if (ctx->con_oper != NULL) {
787 if (ctx->con_net_type == at &&
788 strcasecmp(opr, ctx->con_oper) == 0)
793 ctx->con_oper = strdup(opr);
794 ctx->con_net_type = at;
796 if (ctx->con_net_stat == 1 || ctx->con_net_stat == 5) {
797 logger(LOG_NOTICE, "%s to \"%s\" (%s)",
798 network_reg_status[ctx->con_net_stat],
799 ctx->con_oper, network_access_type[ctx->con_net_type]);
800 if (ctx->con_status != 1) {
801 at_cmd_async(ctx->fd, "AT_OWANCALL=%d,1,1\r\n",
806 logger(LOG_NOTICE, "%s (%s)",
807 network_reg_status[ctx->con_net_stat],
808 network_access_type[ctx->con_net_type]);
813 * Signal strength for pretty console output
815 * From 3GPP TS 27.007 V8.3.0, Section 8.5
816 * 0 = -113 dBm or less
818 * 2...30 = -109...-53 dBm
819 * 31 = -51 dBm or greater
821 * So, dbm = (rssi * 2) - 113
824 at_async_csq(void *arg, const char *resp)
826 struct ctx *ctx = arg;
829 n = sscanf(resp, "+CSQ: %d,%*d", &rssi);
835 ctx->dbm = (rssi * 2) - 113;
836 tmr_add(&timers, 1, 15, tmr_status, ctx);
839 ctx->flags |= FLG_NEWDATA;
843 at_async_owancall(void *arg, const char *resp)
845 struct ctx *ctx = arg;
848 n = sscanf(resp, "_OWANCALL: %*d,%d", &i);
852 if (i == ctx->con_status)
855 at_cmd_async(ctx->fd, "AT_OWANDATA=%d\r\n", ctx->pdp_ctx);
858 if (ctx->con_status == 1) {
859 logger(LOG_NOTICE, "Connected to \"%s\" (%s), %s",
860 ctx->con_oper, ctx->con_apn,
861 network_access_type[ctx->con_net_type]);
864 logger(LOG_NOTICE, "Disconnected from \"%s\" (%s)",
865 ctx->con_oper, ctx->con_apn);
870 at_async_owandata(void *arg, const char *resp)
872 struct ctx *ctx = arg;
873 char ip[40], ns1[40], ns2[40];
875 struct ifaddrs *ifap, *ifa;
876 struct sockaddr_in sin, mask;
877 struct sockaddr_dl sdl;
879 struct rt_msghdr rtm;
884 n = sscanf(resp, "_OWANDATA: %*d, %[^,], %*[^,], %[^,], %[^,]",
889 /* XXX: AF_INET assumption */
891 logger(LOG_NOTICE, "IP address: %s, Nameservers: %s, %s", ip, ns1, ns2);
893 sin.sin_len = mask.sin_len = sizeof(struct sockaddr_in);
894 memset(&mask.sin_addr.s_addr, 0xff, sizeof(mask.sin_addr.s_addr));
895 sin.sin_family = mask.sin_family = AF_INET;
897 if (ctx->flags & IPASSIGNED) {
898 memcpy(&sin.sin_addr.s_addr, &ctx->ip.s_addr,
899 sizeof(sin.sin_addr.s_addr));
900 ifaddr_del(ctx->ifnam, (struct sockaddr *)&sin,
901 (struct sockaddr *)&mask);
903 inet_pton(AF_INET, ip, &ctx->ip.s_addr);
904 memcpy(&sin.sin_addr.s_addr, &ctx->ip.s_addr,
905 sizeof(sin.sin_addr.s_addr));
907 error = ifaddr_add(ctx->ifnam, (struct sockaddr *)&sin,
908 (struct sockaddr *)&mask);
910 logger(LOG_ERR, "failed to set ip-address");
916 ctx->flags |= IPASSIGNED;
918 set_nameservers(ctx, ctx->resolv_path, 0);
919 error = set_nameservers(ctx, ctx->resolv_path, 2, ns1, ns2);
921 logger(LOG_ERR, "failed to set nameservers");
924 error = getifaddrs(&ifap);
926 logger(LOG_ERR, "getifaddrs: %s", strerror(errno));
930 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
931 if (ifa->ifa_addr->sa_family != AF_LINK)
933 if (strcmp(ctx->ifnam, ifa->ifa_name) == 0) {
934 memcpy(&sdl, (struct sockaddr_dl *)ifa->ifa_addr,
935 sizeof(struct sockaddr_dl));
942 rs = socket(PF_ROUTE, SOCK_RAW, 0);
944 logger(LOG_ERR, "socket PF_ROUTE: %s", strerror(errno));
948 memset(&r, 0, sizeof(r));
950 r.rtm.rtm_version = RTM_VERSION;
951 r.rtm.rtm_type = RTM_ADD;
952 r.rtm.rtm_flags = RTF_UP | RTF_STATIC;
953 r.rtm.rtm_pid = getpid();
954 memset(&sin, 0, sizeof(struct sockaddr_in));
955 sin.sin_family = AF_INET;
956 sin.sin_len = sizeof(struct sockaddr_in);
958 memcpy(cp, &sin, sin.sin_len);
960 memcpy(cp, &sdl, sdl.sdl_len);
962 memcpy(cp, &sin, sin.sin_len);
963 r.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
964 r.rtm.rtm_msglen = sizeof(r);
966 n = write(rs, &r, r.rtm.rtm_msglen);
967 if (n != r.rtm.rtm_msglen) {
968 r.rtm.rtm_type = RTM_DELETE;
969 n = write(rs, &r, r.rtm.rtm_msglen);
970 r.rtm.rtm_type = RTM_ADD;
971 n = write(rs, &r, r.rtm.rtm_msglen);
974 if (n != r.rtm.rtm_msglen) {
975 logger(LOG_ERR, "failed to set default route: %s",
980 /* Delayed daemonization */
981 if ((ctx->flags & FLG_DELAYED) && !(ctx->flags & FLG_NODAEMON))
986 at_async(struct ctx *ctx, void *arg)
992 watchdog_reset(ctx, 15);
994 bzero(buf, sizeof(buf));
995 n = readline(ctx->fd, buf, sizeof(buf));
997 return (n <= 0 ? -1 : 0);
1000 fprintf(stderr, "AT_ASYNC_RESP: %s", buf);
1002 for (i = 0; async_cmd[i].cmd != NULL; i++) {
1003 l = strlen(async_cmd[i].cmd);
1004 if (strncmp(buf, async_cmd[i].cmd, l) == 0) {
1005 async_cmd[i].func(arg, buf);
1011 static const char *port_type_list[] = {
1012 "control", "application", "application2", NULL
1016 * Attempts to find a list of control tty for the interface
1017 * FreeBSD attaches USB devices per interface so we have to go through
1018 * hoops to find which ttys that belong to our network interface.
1021 get_tty(struct ctx *ctx)
1023 char buf[64], data[128];
1024 int error, i, usbport, usbport0, list_size = 0;
1030 * Look for the network interface first
1032 for (i = 0; ; i++) {
1033 /* Check if we still have uhso nodes to check */
1034 snprintf(buf, 64, SYSCTL_TEST, i);
1036 error = sysctlbyname(buf, data, &len, NULL, 0);
1039 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1040 buf, error, error == 0 ? data : "FAILED");
1042 if (error < 0 || strcasecmp(data, "uhso") != 0)
1045 /* Check if this node contains the network interface we want */
1046 snprintf(buf, 64, SYSCTL_NETIF, i);
1048 error = sysctlbyname(buf, data, &len, NULL, 0);
1051 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1052 buf, error, error == 0 ? data : "FAILED");
1054 if (error == 0 && strcasecmp(data, ctx->ifnam) == 0)
1058 /* Figure out the USB port location */
1059 snprintf(buf, 64, SYSCTL_LOCATION, i);
1061 error = sysctlbyname(buf, data, &len, NULL, 0);
1064 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1065 buf, error, error == 0 ? data : "FAILED");
1070 q = strstr(data, "port=");
1072 error = sscanf(q, " port=%d", &usbport);
1075 fprintf(stderr, "failed to read usb port location from '%s'\n", data);
1081 fprintf(stderr, "failed to parse location '%s'\n", data);
1086 fprintf(stderr, "USB port location=%d\n", usbport);
1090 * Now go through it all again but only look at those matching the
1091 * usb port location we found.
1093 for (i = 0; ; i++) {
1094 snprintf(buf, 64, SYSCTL_LOCATION, i);
1096 memset(&data, 0, sizeof(data));
1097 error = sysctlbyname(buf, data, &len, NULL, 0);
1101 q = strstr(data, "port=");
1104 sscanf(q, " port=%d", &usbport0);
1105 if (usbport != usbport0)
1108 /* Try to add ports */
1109 for (p = port_type_list; *p != NULL; p++) {
1110 snprintf(buf, 64, SYSCTL_NAME_TTY, i, *p);
1112 memset(&data, 0, sizeof(data));
1113 error = sysctlbyname(buf, data, &len, NULL, 0);
1116 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1117 buf, error, error == 0 ? data : "FAILED");
1120 list = realloc(list, (list_size + 1) * sizeof(char *));
1121 list[list_size] = malloc(strlen(data) + strlen(TTY_NAME));
1122 sprintf(list[list_size], TTY_NAME, data);
1127 list = realloc(list, (list_size + 1) * sizeof(char *));
1128 list[list_size] = NULL;
1133 do_connect(struct ctx *ctx, const char *tty)
1135 int i, error, needcfg;
1141 fprintf(stderr, "Attempting to open %s\n", tty);
1144 ctx->fd = open(tty, O_RDWR);
1147 fprintf(stderr, "Failed to open %s\n", tty);
1152 tcgetattr(ctx->fd, &t);
1155 t.c_cflag = CLOCAL | CREAD;
1157 tcsetattr(ctx->fd, TCSAFLUSH, &t);
1159 error = at_cmd(ctx, NULL, NULL, NULL, "AT\r\n");
1161 warnx("failed to read from device %s", tty);
1166 error = at_cmd(ctx, "+CPIN: READY", NULL, NULL, "AT+CPIN?\r\n");
1168 ra.val[0].ptr = NULL;
1169 ra.val[1].int32 = 0;
1170 error = at_cmd(ctx, "+CME ERROR", saveresp, &ra, "AT+CPIN?\r\n");
1171 if (ra.val[1].int32 > 0) {
1174 buf = ra.val[0].ptr;
1175 if (strstr(buf[0], "+CME ERROR:") != NULL) {
1177 errx(1, "%s", buf[0]);
1183 if (ctx->pin == NULL) {
1184 errx(1, "device requires PIN");
1187 error = at_cmd(ctx, NULL, NULL, NULL, "AT+CPIN=\"%s\"\r\n",
1190 errx(1, "wrong PIN");
1195 * Check if a PDP context has been configured and configure one
1198 ra.val[0].ptr = NULL;
1199 ra.val[1].int32 = 0;
1200 error = at_cmd(ctx, "+CGDCONT", saveresp, &ra, "AT+CGDCONT?\r\n");
1201 buf = ra.val[0].ptr;
1203 for (i = 0; i < ra.val[1].int32; i++) {
1206 error = sscanf(buf[i], "+CGDCONT: %d,\"%*[^\"]\",\"%[^\"]\"",
1213 if (cid == ctx->pdp_ctx) {
1214 ctx->con_apn = strdup(apn);
1215 if (ctx->pdp_apn != NULL) {
1216 if (strcmp(apn, ctx->pdp_apn) == 0)
1228 if (ctx->pdp_apn == NULL)
1229 errx(1, "device is not configured and no APN given");
1231 error = at_cmd(ctx, NULL, NULL, NULL,
1232 "AT+CGDCONT=%d,,\"%s\"\r\n", ctx->pdp_ctx, ctx->pdp_apn);
1234 errx(1, "failed to configure device");
1236 ctx->con_apn = strdup(ctx->pdp_apn);
1239 if (ctx->pdp_user != NULL || ctx->pdp_pwd != NULL) {
1240 at_cmd(ctx, NULL, NULL, NULL,
1241 "AT$QCPDPP=%d,1,\"%s\",\"%s\"\r\n", ctx->pdp_ctx,
1242 (ctx->pdp_user != NULL) ? ctx->pdp_user : "",
1243 (ctx->pdp_pwd != NULL) ? ctx->pdp_pwd : "");
1246 error = at_cmd(ctx, NULL, NULL, NULL, "AT_OWANCALL=%d,0,0\r\n",
1251 at_cmd_async(ctx->fd, "AT+CGREG?\r\n");
1252 at_cmd_async(ctx->fd, "AT+CREG?\r\n");
1254 tmr_add(&timers, 1, 5, tmr_status, ctx);
1259 do_disconnect(struct ctx *ctx)
1261 struct sockaddr_in sin, mask;
1264 at_cmd(ctx, NULL, NULL, NULL, "AT_OWANCALL=%d,0,0\r\n",
1268 /* Remove ip-address from interface */
1269 if (ctx->flags & IPASSIGNED) {
1270 sin.sin_len = mask.sin_len = sizeof(struct sockaddr_in);
1271 memset(&mask.sin_addr.s_addr, 0xff,
1272 sizeof(mask.sin_addr.s_addr));
1273 sin.sin_family = mask.sin_family = AF_INET;
1274 memcpy(&sin.sin_addr.s_addr, &ctx->ip.s_addr,
1275 sizeof(sin.sin_addr.s_addr));
1276 ifaddr_del(ctx->ifnam, (struct sockaddr *)&sin,
1277 (struct sockaddr *)&mask);
1279 if_ifdown(ctx->ifnam);
1280 ctx->flags &= ~IPASSIGNED;
1283 /* Attempt to reset resolv.conf */
1284 set_nameservers(ctx, ctx->resolv_path, 0);
1288 daemonize(struct ctx *ctx)
1293 snprintf(ctx->pidfile, 127, PIDFILE, ctx->ifnam);
1295 pfh = pidfile_open(ctx->pidfile, 0600, &opid);
1297 warn("Cannot create pidfile %s", ctx->pidfile);
1301 if (daemon(0, 0) == -1) {
1302 warn("Cannot daemonize");
1303 pidfile_remove(pfh);
1309 ctx->flags |= FLG_DAEMON;
1311 snprintf(syslog_title, 63, "%s:%s", getprogname(), ctx->ifnam);
1312 openlog(syslog_title, LOG_PID, LOG_USER);
1317 send_disconnect(const char *ifnam)
1324 snprintf(pidfile, 127, PIDFILE, ifnam);
1325 fp = fopen(pidfile, "r");
1327 warn("Cannot open %s", pidfile);
1331 n = fscanf(fp, "%d", &pid);
1334 warnx("unable to read daemon pid");
1338 fprintf(stderr, "Sending SIGTERM to %d\n", pid);
1344 usage(const char *exec)
1347 printf("usage %s [-b] [-n] [-a apn] [-c cid] [-p pin] [-u username] "
1348 "[-k password] [-r resolvpath] [-f tty] interface\n", exec);
1349 printf("usage %s -d interface\n", exec);
1358 main(int argc, char *argv[])
1360 int ch, error, mode;
1361 const char *ifnam = NULL;
1363 char **p, **tty_list;
1366 struct itimerval it;
1368 TAILQ_INIT(&timers.head);
1372 ctx.pdp_apn = ctx.pdp_user = ctx.pdp_pwd = NULL;
1377 ctx.con_oper = NULL;
1378 ctx.con_net_stat = 0;
1379 ctx.con_net_type = -1;
1381 ctx.resolv_path = RESOLV_PATH;
1387 ctx.flags |= FLG_DELAYED;
1389 while ((ch = getopt(argc, argv, "?ha:p:c:u:k:r:f:dbn")) != -1) {
1392 ctx.pdp_apn = argv[optind - 1];
1395 ctx.pdp_ctx = strtol(argv[optind - 1], NULL, 10);
1396 if (ctx.pdp_ctx < 1) {
1397 warnx("Invalid context ID, defaulting to 1");
1402 ctx.pin = argv[optind - 1];
1405 ctx.pdp_user = argv[optind - 1];
1408 ctx.pdp_pwd = argv[optind - 1];
1411 ctx.resolv_path = argv[optind - 1];
1417 ctx.flags &= ~FLG_DELAYED;
1420 ctx.flags |= FLG_NODAEMON;
1423 tty = argv[optind - 1];
1437 errx(1, "no interface given");
1439 ifnam = argv[argc - 1];
1440 ctx.ifnam = strdup(ifnam);
1444 printf("Disconnecting %s\n", ifnam);
1445 send_disconnect(ifnam);
1451 signal(SIGHUP, sig_handle);
1452 signal(SIGINT, sig_handle);
1453 signal(SIGQUIT, sig_handle);
1454 signal(SIGTERM, sig_handle);
1455 signal(SIGALRM, sig_handle);
1457 it.it_interval.tv_sec = 1;
1458 it.it_interval.tv_usec = 0;
1459 it.it_value.tv_sec = 1;
1460 it.it_value.tv_usec = 0;
1461 error = setitimer(ITIMER_REAL, &it, NULL);
1463 errx(1, "setitimer");
1465 tmr_add(&timers, 1, 5, &tmr_watchdog, &ctx);
1466 watchdog_reset(&ctx, 15);
1469 error = do_connect(&ctx, tty);
1471 errx(1, "Failed to open %s", tty);
1474 tty_list = get_tty(&ctx);
1475 if (tty_list == NULL)
1476 errx(1, "%s does not appear to be a uhso device", ifnam);
1478 if (tty_list == NULL) {
1479 fprintf(stderr, "get_tty returned empty list\n");
1481 fprintf(stderr, "tty list:\n");
1482 for (p = tty_list; *p != NULL; p++) {
1483 fprintf(stderr, "\t %s\n", *p);
1487 for (p = tty_list; *p != NULL; p++) {
1488 error = do_connect(&ctx, *p);
1495 errx(1, "Failed to obtain a control port, "
1496 "try specifying one manually");
1499 if (!(ctx.flags & FLG_DELAYED) && !(ctx.flags & FLG_NODAEMON))
1504 FD_SET(ctx.fd, &set);
1507 watchdog_disable(&ctx);
1508 error = select(ctx.fd + 1, &set, NULL, NULL, NULL);
1510 if (running && errno == EINTR)
1512 if (ctx.flags & FLG_WDEXP) {
1513 ctx.flags &= ~FLG_WDEXP;
1514 watchdog_reset(&ctx, 5);
1515 do_disconnect(&ctx);
1516 watchdog_reset(&ctx, 15);
1517 do_connect(&ctx, tty);
1525 if (FD_ISSET(ctx.fd, &set)) {
1526 watchdog_reset(&ctx, 15);
1527 error = at_async(&ctx, &ctx);
1531 FD_SET(ctx.fd, &set);
1533 if (!(ctx.flags & FLG_DAEMON) && (ctx.flags & IPASSIGNED)) {
1534 printf("Status: %s (%s)",
1535 ctx.con_status ? "connected" : "disconnected",
1536 network_access_type[ctx.con_net_type]);
1538 printf(", signal: %d dBm", ctx.dbm);
1543 if (!(ctx.flags & FLG_DAEMON) && (ctx.flags & IPASSIGNED))
1546 signal(SIGHUP, SIG_DFL);
1547 signal(SIGINT, SIG_DFL);
1548 signal(SIGQUIT, SIG_DFL);
1549 signal(SIGTERM, SIG_DFL);
1550 signal(SIGALRM, SIG_IGN);
1552 do_disconnect(&ctx);
1554 if (ctx.flags & FLG_DAEMON) {
1555 pidfile_remove(ctx.pfh);