2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2008-2009 Fredrik Lindberg
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include <sys/types.h>
31 #include <sys/param.h>
32 #include <sys/socket.h>
33 #include <sys/sockio.h>
34 #include <sys/select.h>
36 #include <sys/sysctl.h>
38 #include <sys/queue.h>
40 #include <arpa/inet.h>
42 #include <net/if_dl.h>
43 #include <net/route.h>
44 #include <netinet/in.h>
45 #include <netinet/in_var.h>
64 * Connection utility to ease connectivity using the raw IP packet interface
65 * available on uhso(4) devices.
68 #define TTY_NAME "/dev/%s"
69 #define SYSCTL_TEST "dev.uhso.%d.%%driver"
70 #define SYSCTL_LOCATION "dev.uhso.%d.%%location"
71 #define SYSCTL_PORTS "dev.uhso.%d.ports"
72 #define SYSCTL_NETIF "dev.uhso.%d.netif"
73 #define SYSCTL_NAME_TTY "dev.uhso.%d.port.%s.tty"
74 #define SYSCTL_NAME_DESC "dev.uhso.%d.port.%s.desc"
75 #define RESOLV_PATH "/etc/resolv.conf"
76 #define PIDFILE "/var/run/uhsoctl.%s.pid"
78 static const char *network_access_type[] = {
88 static const char *network_reg_status[] = {
91 "Searching for network",
92 "Network registration denied",
94 "Registered (roaming)"
100 #define IPASSIGNED 0x01
101 #define FLG_NODAEMON 0x02 /* Don't detach from terminal */
102 #define FLG_DAEMON 0x04 /* Running as daemon */
103 #define FLG_DELAYED 0x08 /* Fork into background after connect */
104 #define FLG_NEWDATA 0x10
105 #define FLG_WATCHDOG 0x20 /* Watchdog enabled */
106 #define FLG_WDEXP 0x40 /* Watchdog expired */
108 const char *pin; /* device PIN */
115 /* PDP context settings */
118 const char *pdp_user;
121 /* Connection status */
122 int con_status; /* Connected? */
123 char *con_apn; /* Connected APN */
124 char *con_oper; /* Operator name */
125 int con_net_stat; /* Network connection status */
126 int con_net_type; /* Network connection type */
131 /* IP and nameserver settings */
134 const char *resolv_path;
135 char *resolv; /* Old resolv.conf */
139 static int readline_buf(const char *, const char *, char *, size_t);
140 static int readline(int, char *, size_t);
141 static void daemonize(struct ctx *);
143 static int at_cmd_async(int, const char *, ...);
152 typedef void (*resp_cb)(resp_arg *, const char *, const char *);
154 typedef void (*async_cb)(void *, const char *);
155 struct async_handle {
160 static void at_async_creg(void *, const char *);
161 static void at_async_cgreg(void *, const char *);
162 static void at_async_cops(void *, const char *);
163 static void at_async_owancall(void *, const char *);
164 static void at_async_owandata(void *, const char *);
165 static void at_async_csq(void *, const char *);
167 static struct async_handle async_cmd[] = {
168 { "+CREG", at_async_creg },
169 { "+CGREG", at_async_cgreg },
170 { "+COPS", at_async_cops },
171 { "+CSQ", at_async_csq },
172 { "_OWANCALL", at_async_owancall },
173 { "_OWANDATA", at_async_owandata },
179 TAILQ_HEAD(, timer_entry) head;
183 typedef void (*tmr_cb)(int, void *);
185 TAILQ_ENTRY(timer_entry) next;
193 static struct timers timers;
194 static volatile int running = 1;
195 static int syslog_open = 0;
196 static char syslog_title[64];
198 /* Periodic timer, runs ready timer tasks every tick */
200 tmr_run(struct timers *tmrs)
202 struct timer_entry *te, *te2;
204 te = TAILQ_FIRST(&tmrs->head);
208 te->timeout -= tmrs->res;
209 while (te->timeout <= 0) {
210 te2 = TAILQ_NEXT(te, next);
211 TAILQ_REMOVE(&tmrs->head, te, next);
212 te->func(te->id, te->arg);
220 /* Add a new timer */
222 tmr_add(struct timers *tmrs, int id, int timeout, tmr_cb func, void *arg)
224 struct timer_entry *te, *te2, *te3;
226 te = malloc(sizeof(struct timer_entry));
227 memset(te, 0, sizeof(struct timer_entry));
229 te->timeout = timeout;
234 te2 = TAILQ_FIRST(&tmrs->head);
236 if (TAILQ_EMPTY(&tmrs->head)) {
237 TAILQ_INSERT_HEAD(&tmrs->head, te, next);
238 } else if (te->timeout < te2->timeout) {
239 te2->timeout -= te->timeout;
240 TAILQ_INSERT_HEAD(&tmrs->head, te, next);
242 while (te->timeout >= te2->timeout) {
243 te->timeout -= te2->timeout;
244 te3 = TAILQ_NEXT(te2, next);
245 if (te3 == NULL || te3->timeout > te->timeout)
249 TAILQ_INSERT_AFTER(&tmrs->head, te2, te, next);
253 #define watchdog_enable(ctx) (ctx)->flags |= FLG_WATCHDOG
254 #define watchdog_disable(ctx) (ctx)->flags &= ~FLG_WATCHDOG
257 watchdog_reset(struct ctx *ctx, int timeout)
261 clock_gettime(CLOCK_MONOTONIC, &tp),
262 ctx->watchdog = tp.tv_sec + timeout;
264 watchdog_enable(ctx);
268 tmr_creg(int id, void *arg)
270 struct ctx *ctx = arg;
272 at_cmd_async(ctx->fd, "AT+CREG?\r\n");
273 watchdog_reset(ctx, 10);
277 tmr_cgreg(int id, void *arg)
279 struct ctx *ctx = arg;
281 at_cmd_async(ctx->fd, "AT+CGREG?\r\n");
282 watchdog_reset(ctx, 10);
286 tmr_status(int id, void *arg)
288 struct ctx *ctx = arg;
290 at_cmd_async(ctx->fd, "AT+CSQ\r\n");
291 watchdog_reset(ctx, 10);
295 tmr_watchdog(int id, void *arg)
297 struct ctx *ctx = arg;
301 tmr_add(&timers, 1, 5, tmr_watchdog, ctx);
303 if (!(ctx->flags & FLG_WATCHDOG))
306 clock_gettime(CLOCK_MONOTONIC, &tp);
308 if (tp.tv_sec >= ctx->watchdog) {
310 fprintf(stderr, "Watchdog expired\n");
312 ctx->flags |= FLG_WDEXP;
336 logger(int pri, const char *fmt, ...)
342 vasprintf(&buf, fmt, ap);
344 syslog(pri, "%s", buf);
352 fprintf(stderr, "%s: %s\n", getprogname(), buf);
361 /* Add/remove IP address from an interface */
363 ifaddr_ad(unsigned long d, const char *ifnam, struct sockaddr *sa, struct sockaddr *mask)
365 struct ifaliasreq req;
368 fd = socket(AF_INET, SOCK_DGRAM, 0);
372 memset(&req, 0, sizeof(struct ifaliasreq));
373 strlcpy(req.ifra_name, ifnam, sizeof(req.ifra_name));
374 memcpy(&req.ifra_addr, sa, sa->sa_len);
375 memcpy(&req.ifra_mask, mask, mask->sa_len);
377 error = ioctl(fd, d, (char *)&req);
382 #define if_ifup(ifnam) if_setflags(ifnam, IFF_UP)
383 #define if_ifdown(ifnam) if_setflags(ifnam, -IFF_UP)
386 if_setflags(const char *ifnam, int flags)
390 unsigned int oflags = 0;
392 memset(&ifr, 0, sizeof(struct ifreq));
393 strlcpy(ifr.ifr_name, ifnam, sizeof(ifr.ifr_name));
395 fd = socket(AF_INET, SOCK_DGRAM, 0);
399 error = ioctl(fd, SIOCGIFFLAGS, &ifr);
401 oflags = (ifr.ifr_flags & 0xffff) | (ifr.ifr_flagshigh << 16);
409 ifr.ifr_flags = oflags & 0xffff;
410 ifr.ifr_flagshigh = oflags >> 16;
412 error = ioctl(fd, SIOCSIFFLAGS, &ifr);
414 warn("ioctl SIOCSIFFLAGS");
421 ifaddr_add(const char *ifnam, struct sockaddr *sa, struct sockaddr *mask)
425 error = ifaddr_ad(SIOCAIFADDR, ifnam, sa, mask);
427 warn("ioctl SIOCAIFADDR");
432 ifaddr_del(const char *ifnam, struct sockaddr *sa, struct sockaddr *mask)
436 error = ifaddr_ad(SIOCDIFADDR, ifnam, sa, mask);
438 warn("ioctl SIOCDIFADDR");
443 set_nameservers(struct ctx *ctx, const char *respath, int ns, ...)
452 if (ctx->ns != NULL) {
453 for (i = 0; ctx->ns[i] != NULL; i++) {
460 fd = open(respath, O_RDWR | O_CREAT | O_NOFOLLOW, 0666);
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, ...)
585 int n, error, retval = 0;
591 vsnprintf(cmd, sizeof(cmd), cf, ap);
595 fprintf(stderr, "SYNC_CMD: %s", cmd);
599 n = write(ctx->fd, cmd, l);
606 fprintf(stderr, "SYNC_EXP: %s (%zu)\n", resp, l);
611 bzero(buf, sizeof(buf));
614 watchdog_reset(ctx, 5);
616 FD_SET(ctx->fd, &set);
617 error = select(ctx->fd + 1, &set, NULL, NULL, NULL);
618 if (ctx->flags & FLG_WDEXP) {
619 watchdog_disable(ctx);
622 } while (error <= 0 && errno == EINTR);
623 watchdog_disable(ctx);
630 n = readline(ctx->fd, buf, sizeof(buf));
636 if (strcmp(buf, "\r\n") == 0 || strcmp(buf, "\n") == 0)
639 if ((p = strchr(buf, '\r')) != NULL)
641 else if ((p = strchr(buf, '\n')) != NULL)
644 fprintf(stderr, "SYNC_RESP: %s\n", buf);
647 /* Skip local echo */
648 if (strncasecmp(cmd, buf, strlen(buf)) == 0)
654 if (strncmp(buf, "OK", 2) == 0) {
655 retval = retval ? retval : 0;
657 } else if (strstr(buf, "ERROR") != NULL) {
662 retval = strncmp(buf, resp, l);
665 fprintf(stderr, "SYNC_RETVAL=%d\n", retval);
671 at_cmd_async(int fd, const char *cf, ...)
678 vsnprintf(cmd, sizeof(cmd), cf, ap);
682 fprintf(stderr, "CMD: %s", cmd);
685 return (write(fd, cmd, l));
689 saveresp(resp_arg *ra, const char *cmd, const char *resp)
692 int i = ra->val[1].int32;
695 fprintf(stderr, "Save '%s'\n", resp);
698 buf = realloc(ra->val[0].ptr, sizeof(char *) * (i + 1));
702 buf[i] = strdup(resp);
704 ra->val[0].ptr = buf;
705 ra->val[1].int32 = i + 1;
709 freeresp(resp_arg *ra)
714 buf = ra->val[0].ptr;
715 for (i = 0; i < ra->val[1].int32; i++) {
722 at_async_creg(void *arg, const char *resp)
724 struct ctx *ctx = arg;
727 n = sscanf(resp, "+CREG: %*d,%d", ®);
729 n = sscanf(resp, "+CREG: %d", ®);
734 if (ctx->con_net_stat != 1 && ctx->con_net_stat != 5) {
735 tmr_add(&timers, 1, 1, tmr_creg, ctx);
738 tmr_add(&timers, 1, 30, tmr_creg, ctx);
741 if (ctx->con_net_stat == reg)
744 ctx->con_net_stat = reg;
745 at_cmd_async(ctx->fd, "AT+COPS?\r\n");
749 at_async_cgreg(void *arg, const char *resp)
751 struct ctx *ctx = arg;
754 n = sscanf(resp, "+CGREG: %*d,%d", ®);
756 n = sscanf(resp, "+CGREG: %d", ®);
761 if (ctx->con_net_stat != 1 && ctx->con_net_stat != 5) {
762 tmr_add(&timers, 1, 1, tmr_cgreg, ctx);
765 tmr_add(&timers, 1, 30, tmr_cgreg, ctx);
768 if (ctx->con_net_stat == reg)
771 ctx->con_net_stat = reg;
772 at_cmd_async(ctx->fd, "AT+COPS?\r\n");
777 at_async_cops(void *arg, const char *resp)
779 struct ctx *ctx = arg;
783 n = sscanf(resp, "+COPS: %*d,%*d,\"%[^\"]\",%d",
788 if (ctx->con_oper != NULL) {
789 if (ctx->con_net_type == at &&
790 strcasecmp(opr, ctx->con_oper) == 0)
795 ctx->con_oper = strdup(opr);
796 ctx->con_net_type = at;
798 if (ctx->con_net_stat == 1 || ctx->con_net_stat == 5) {
799 logger(LOG_NOTICE, "%s to \"%s\" (%s)",
800 network_reg_status[ctx->con_net_stat],
801 ctx->con_oper, network_access_type[ctx->con_net_type]);
802 if (ctx->con_status != 1) {
803 at_cmd_async(ctx->fd, "AT_OWANCALL=%d,1,1\r\n",
808 logger(LOG_NOTICE, "%s (%s)",
809 network_reg_status[ctx->con_net_stat],
810 network_access_type[ctx->con_net_type]);
815 * Signal strength for pretty console output
817 * From 3GPP TS 27.007 V8.3.0, Section 8.5
818 * 0 = -113 dBm or less
820 * 2...30 = -109...-53 dBm
821 * 31 = -51 dBm or greater
823 * So, dbm = (rssi * 2) - 113
826 at_async_csq(void *arg, const char *resp)
828 struct ctx *ctx = arg;
831 n = sscanf(resp, "+CSQ: %d,%*d", &rssi);
837 ctx->dbm = (rssi * 2) - 113;
838 tmr_add(&timers, 1, 15, tmr_status, ctx);
841 ctx->flags |= FLG_NEWDATA;
845 at_async_owancall(void *arg, const char *resp)
847 struct ctx *ctx = arg;
850 n = sscanf(resp, "_OWANCALL: %*d,%d", &i);
854 if (i == ctx->con_status)
857 at_cmd_async(ctx->fd, "AT_OWANDATA=%d\r\n", ctx->pdp_ctx);
860 if (ctx->con_status == 1) {
861 logger(LOG_NOTICE, "Connected to \"%s\" (%s), %s",
862 ctx->con_oper, ctx->con_apn,
863 network_access_type[ctx->con_net_type]);
866 logger(LOG_NOTICE, "Disconnected from \"%s\" (%s)",
867 ctx->con_oper, ctx->con_apn);
872 at_async_owandata(void *arg, const char *resp)
874 struct ctx *ctx = arg;
875 char ip[40], ns1[40], ns2[40];
877 struct ifaddrs *ifap, *ifa;
878 struct sockaddr_in sin, mask;
879 struct sockaddr_dl sdl;
881 struct rt_msghdr rtm;
886 n = sscanf(resp, "_OWANDATA: %*d, %[^,], %*[^,], %[^,], %[^,]",
891 /* XXX: AF_INET assumption */
893 logger(LOG_NOTICE, "IP address: %s, Nameservers: %s, %s", ip, ns1, ns2);
895 sin.sin_len = mask.sin_len = sizeof(struct sockaddr_in);
896 memset(&mask.sin_addr.s_addr, 0xff, sizeof(mask.sin_addr.s_addr));
897 sin.sin_family = mask.sin_family = AF_INET;
899 if (ctx->flags & IPASSIGNED) {
900 memcpy(&sin.sin_addr.s_addr, &ctx->ip.s_addr,
901 sizeof(sin.sin_addr.s_addr));
902 ifaddr_del(ctx->ifnam, (struct sockaddr *)&sin,
903 (struct sockaddr *)&mask);
905 inet_pton(AF_INET, ip, &ctx->ip.s_addr);
906 memcpy(&sin.sin_addr.s_addr, &ctx->ip.s_addr,
907 sizeof(sin.sin_addr.s_addr));
909 error = ifaddr_add(ctx->ifnam, (struct sockaddr *)&sin,
910 (struct sockaddr *)&mask);
912 logger(LOG_ERR, "failed to set ip-address");
918 ctx->flags |= IPASSIGNED;
920 set_nameservers(ctx, ctx->resolv_path, 0);
921 error = set_nameservers(ctx, ctx->resolv_path, 2, ns1, ns2);
923 logger(LOG_ERR, "failed to set nameservers");
926 error = getifaddrs(&ifap);
928 logger(LOG_ERR, "getifaddrs: %s", strerror(errno));
932 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
933 if (ifa->ifa_addr->sa_family != AF_LINK)
935 if (strcmp(ctx->ifnam, ifa->ifa_name) == 0) {
936 memcpy(&sdl, (struct sockaddr_dl *)ifa->ifa_addr,
937 sizeof(struct sockaddr_dl));
944 rs = socket(PF_ROUTE, SOCK_RAW, 0);
946 logger(LOG_ERR, "socket PF_ROUTE: %s", strerror(errno));
950 memset(&r, 0, sizeof(r));
952 r.rtm.rtm_version = RTM_VERSION;
953 r.rtm.rtm_type = RTM_ADD;
954 r.rtm.rtm_flags = RTF_UP | RTF_STATIC;
955 r.rtm.rtm_pid = getpid();
956 memset(&sin, 0, sizeof(struct sockaddr_in));
957 sin.sin_family = AF_INET;
958 sin.sin_len = sizeof(struct sockaddr_in);
960 memcpy(cp, &sin, sin.sin_len);
962 memcpy(cp, &sdl, sdl.sdl_len);
964 memcpy(cp, &sin, sin.sin_len);
965 r.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
966 r.rtm.rtm_msglen = sizeof(r);
968 n = write(rs, &r, r.rtm.rtm_msglen);
969 if (n != r.rtm.rtm_msglen) {
970 r.rtm.rtm_type = RTM_DELETE;
971 n = write(rs, &r, r.rtm.rtm_msglen);
972 r.rtm.rtm_type = RTM_ADD;
973 n = write(rs, &r, r.rtm.rtm_msglen);
976 if (n != r.rtm.rtm_msglen) {
977 logger(LOG_ERR, "failed to set default route: %s",
982 /* Delayed daemonization */
983 if ((ctx->flags & FLG_DELAYED) && !(ctx->flags & FLG_NODAEMON))
988 at_async(struct ctx *ctx, void *arg)
994 watchdog_reset(ctx, 15);
996 bzero(buf, sizeof(buf));
997 n = readline(ctx->fd, buf, sizeof(buf));
999 return (n <= 0 ? -1 : 0);
1002 fprintf(stderr, "AT_ASYNC_RESP: %s", buf);
1004 for (i = 0; async_cmd[i].cmd != NULL; i++) {
1005 l = strlen(async_cmd[i].cmd);
1006 if (strncmp(buf, async_cmd[i].cmd, l) == 0) {
1007 async_cmd[i].func(arg, buf);
1013 static const char *port_type_list[] = {
1014 "control", "application", "application2", NULL
1018 * Attempts to find a list of control tty for the interface
1019 * FreeBSD attaches USB devices per interface so we have to go through
1020 * hoops to find which ttys that belong to our network interface.
1023 get_tty(struct ctx *ctx)
1025 char buf[64], data[128];
1026 int error, i, usbport, usbport0, list_size = 0;
1032 * Look for the network interface first
1034 for (i = 0; ; i++) {
1035 /* Check if we still have uhso nodes to check */
1036 snprintf(buf, 64, SYSCTL_TEST, i);
1038 error = sysctlbyname(buf, data, &len, NULL, 0);
1041 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1042 buf, error, error == 0 ? data : "FAILED");
1044 if (error < 0 || strcasecmp(data, "uhso") != 0)
1047 /* Check if this node contains the network interface we want */
1048 snprintf(buf, 64, SYSCTL_NETIF, i);
1050 error = sysctlbyname(buf, data, &len, NULL, 0);
1053 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1054 buf, error, error == 0 ? data : "FAILED");
1056 if (error == 0 && strcasecmp(data, ctx->ifnam) == 0)
1060 /* Figure out the USB port location */
1061 snprintf(buf, 64, SYSCTL_LOCATION, i);
1063 error = sysctlbyname(buf, data, &len, NULL, 0);
1066 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1067 buf, error, error == 0 ? data : "FAILED");
1072 q = strstr(data, "port=");
1074 error = sscanf(q, " port=%d", &usbport);
1077 fprintf(stderr, "failed to read usb port location from '%s'\n", data);
1083 fprintf(stderr, "failed to parse location '%s'\n", data);
1088 fprintf(stderr, "USB port location=%d\n", usbport);
1092 * Now go through it all again but only look at those matching the
1093 * usb port location we found.
1095 for (i = 0; ; i++) {
1096 snprintf(buf, 64, SYSCTL_LOCATION, i);
1098 memset(&data, 0, sizeof(data));
1099 error = sysctlbyname(buf, data, &len, NULL, 0);
1103 q = strstr(data, "port=");
1106 sscanf(q, " port=%d", &usbport0);
1107 if (usbport != usbport0)
1110 /* Try to add ports */
1111 for (p = port_type_list; *p != NULL; p++) {
1112 snprintf(buf, 64, SYSCTL_NAME_TTY, i, *p);
1114 memset(&data, 0, sizeof(data));
1115 error = sysctlbyname(buf, data, &len, NULL, 0);
1118 fprintf(stderr, "sysctl %s returned(%d): %s\n",
1119 buf, error, error == 0 ? data : "FAILED");
1122 list = realloc(list, (list_size + 1) * sizeof(char *));
1123 list[list_size] = malloc(strlen(data) + strlen(TTY_NAME));
1124 sprintf(list[list_size], TTY_NAME, data);
1129 list = realloc(list, (list_size + 1) * sizeof(char *));
1130 list[list_size] = NULL;
1135 do_connect(struct ctx *ctx, const char *tty)
1137 int i, error, needcfg;
1143 fprintf(stderr, "Attempting to open %s\n", tty);
1146 ctx->fd = open(tty, O_RDWR);
1149 fprintf(stderr, "Failed to open %s\n", tty);
1154 tcgetattr(ctx->fd, &t);
1157 t.c_cflag = CLOCAL | CREAD;
1159 tcsetattr(ctx->fd, TCSAFLUSH, &t);
1161 error = at_cmd(ctx, NULL, NULL, NULL, "AT\r\n");
1163 warnx("failed to read from device %s", tty);
1168 error = at_cmd(ctx, "+CPIN: READY", NULL, NULL, "AT+CPIN?\r\n");
1170 ra.val[0].ptr = NULL;
1171 ra.val[1].int32 = 0;
1172 error = at_cmd(ctx, "+CME ERROR", saveresp, &ra, "AT+CPIN?\r\n");
1173 if (ra.val[1].int32 > 0) {
1176 buf = ra.val[0].ptr;
1177 if (strstr(buf[0], "+CME ERROR:") != NULL) {
1179 errx(1, "%s", buf[0]);
1185 if (ctx->pin == NULL) {
1186 errx(1, "device requires PIN");
1189 error = at_cmd(ctx, NULL, NULL, NULL, "AT+CPIN=\"%s\"\r\n",
1192 errx(1, "wrong PIN");
1197 * Check if a PDP context has been configured and configure one
1200 ra.val[0].ptr = NULL;
1201 ra.val[1].int32 = 0;
1202 error = at_cmd(ctx, "+CGDCONT", saveresp, &ra, "AT+CGDCONT?\r\n");
1203 buf = ra.val[0].ptr;
1205 for (i = 0; i < ra.val[1].int32; i++) {
1208 error = sscanf(buf[i], "+CGDCONT: %d,\"%*[^\"]\",\"%[^\"]\"",
1215 if (cid == ctx->pdp_ctx) {
1216 ctx->con_apn = strdup(apn);
1217 if (ctx->pdp_apn != NULL) {
1218 if (strcmp(apn, ctx->pdp_apn) == 0)
1230 if (ctx->pdp_apn == NULL)
1231 errx(1, "device is not configured and no APN given");
1233 error = at_cmd(ctx, NULL, NULL, NULL,
1234 "AT+CGDCONT=%d,,\"%s\"\r\n", ctx->pdp_ctx, ctx->pdp_apn);
1236 errx(1, "failed to configure device");
1238 ctx->con_apn = strdup(ctx->pdp_apn);
1241 if (ctx->pdp_user != NULL || ctx->pdp_pwd != NULL) {
1242 at_cmd(ctx, NULL, NULL, NULL,
1243 "AT$QCPDPP=%d,1,\"%s\",\"%s\"\r\n", ctx->pdp_ctx,
1244 (ctx->pdp_user != NULL) ? ctx->pdp_user : "",
1245 (ctx->pdp_pwd != NULL) ? ctx->pdp_pwd : "");
1248 error = at_cmd(ctx, NULL, NULL, NULL, "AT_OWANCALL=%d,0,0\r\n",
1253 at_cmd_async(ctx->fd, "AT+CGREG?\r\n");
1254 at_cmd_async(ctx->fd, "AT+CREG?\r\n");
1256 tmr_add(&timers, 1, 5, tmr_status, ctx);
1261 do_disconnect(struct ctx *ctx)
1263 struct sockaddr_in sin, mask;
1266 at_cmd(ctx, NULL, NULL, NULL, "AT_OWANCALL=%d,0,0\r\n",
1270 /* Remove ip-address from interface */
1271 if (ctx->flags & IPASSIGNED) {
1272 sin.sin_len = mask.sin_len = sizeof(struct sockaddr_in);
1273 memset(&mask.sin_addr.s_addr, 0xff,
1274 sizeof(mask.sin_addr.s_addr));
1275 sin.sin_family = mask.sin_family = AF_INET;
1276 memcpy(&sin.sin_addr.s_addr, &ctx->ip.s_addr,
1277 sizeof(sin.sin_addr.s_addr));
1278 ifaddr_del(ctx->ifnam, (struct sockaddr *)&sin,
1279 (struct sockaddr *)&mask);
1281 if_ifdown(ctx->ifnam);
1282 ctx->flags &= ~IPASSIGNED;
1285 /* Attempt to reset resolv.conf */
1286 set_nameservers(ctx, ctx->resolv_path, 0);
1290 daemonize(struct ctx *ctx)
1295 snprintf(ctx->pidfile, 127, PIDFILE, ctx->ifnam);
1297 pfh = pidfile_open(ctx->pidfile, 0600, &opid);
1299 warn("Cannot create pidfile %s", ctx->pidfile);
1303 if (daemon(0, 0) == -1) {
1304 warn("Cannot daemonize");
1305 pidfile_remove(pfh);
1311 ctx->flags |= FLG_DAEMON;
1313 snprintf(syslog_title, 63, "%s:%s", getprogname(), ctx->ifnam);
1314 openlog(syslog_title, LOG_PID, LOG_USER);
1319 send_disconnect(const char *ifnam)
1326 snprintf(pidfile, 127, PIDFILE, ifnam);
1327 fp = fopen(pidfile, "r");
1329 warn("Cannot open %s", pidfile);
1333 n = fscanf(fp, "%d", &pid);
1336 warnx("unable to read daemon pid");
1340 fprintf(stderr, "Sending SIGTERM to %d\n", pid);
1346 usage(const char *exec)
1349 printf("usage %s [-b] [-n] [-a apn] [-c cid] [-p pin] [-u username] "
1350 "[-k password] [-r resolvpath] [-f tty] interface\n", exec);
1351 printf("usage %s -d interface\n", exec);
1360 main(int argc, char *argv[])
1362 int ch, error, mode;
1363 const char *ifnam = NULL;
1365 char **p, **tty_list;
1368 struct itimerval it;
1370 TAILQ_INIT(&timers.head);
1374 ctx.pdp_apn = ctx.pdp_user = ctx.pdp_pwd = NULL;
1379 ctx.con_oper = NULL;
1380 ctx.con_net_stat = 0;
1381 ctx.con_net_type = -1;
1383 ctx.resolv_path = RESOLV_PATH;
1389 ctx.flags |= FLG_DELAYED;
1391 while ((ch = getopt(argc, argv, "?ha:p:c:u:k:r:f:dbn")) != -1) {
1394 ctx.pdp_apn = argv[optind - 1];
1397 ctx.pdp_ctx = strtol(argv[optind - 1], NULL, 10);
1398 if (ctx.pdp_ctx < 1) {
1399 warnx("Invalid context ID, defaulting to 1");
1404 ctx.pin = argv[optind - 1];
1407 ctx.pdp_user = argv[optind - 1];
1410 ctx.pdp_pwd = argv[optind - 1];
1413 ctx.resolv_path = argv[optind - 1];
1419 ctx.flags &= ~FLG_DELAYED;
1422 ctx.flags |= FLG_NODAEMON;
1425 tty = argv[optind - 1];
1439 errx(1, "no interface given");
1441 ifnam = argv[argc - 1];
1442 ctx.ifnam = strdup(ifnam);
1446 printf("Disconnecting %s\n", ifnam);
1447 send_disconnect(ifnam);
1453 signal(SIGHUP, sig_handle);
1454 signal(SIGINT, sig_handle);
1455 signal(SIGQUIT, sig_handle);
1456 signal(SIGTERM, sig_handle);
1457 signal(SIGALRM, sig_handle);
1459 it.it_interval.tv_sec = 1;
1460 it.it_interval.tv_usec = 0;
1461 it.it_value.tv_sec = 1;
1462 it.it_value.tv_usec = 0;
1463 error = setitimer(ITIMER_REAL, &it, NULL);
1465 errx(1, "setitimer");
1467 tmr_add(&timers, 1, 5, &tmr_watchdog, &ctx);
1468 watchdog_reset(&ctx, 15);
1471 error = do_connect(&ctx, tty);
1473 errx(1, "Failed to open %s", tty);
1476 tty_list = get_tty(&ctx);
1477 if (tty_list == NULL)
1478 errx(1, "%s does not appear to be a uhso device", ifnam);
1480 if (tty_list == NULL) {
1481 fprintf(stderr, "get_tty returned empty list\n");
1483 fprintf(stderr, "tty list:\n");
1484 for (p = tty_list; *p != NULL; p++) {
1485 fprintf(stderr, "\t %s\n", *p);
1489 for (p = tty_list; *p != NULL; p++) {
1490 error = do_connect(&ctx, *p);
1497 errx(1, "Failed to obtain a control port, "
1498 "try specifying one manually");
1501 if (!(ctx.flags & FLG_DELAYED) && !(ctx.flags & FLG_NODAEMON))
1506 FD_SET(ctx.fd, &set);
1509 watchdog_disable(&ctx);
1510 error = select(ctx.fd + 1, &set, NULL, NULL, NULL);
1512 if (running && errno == EINTR)
1514 if (ctx.flags & FLG_WDEXP) {
1515 ctx.flags &= ~FLG_WDEXP;
1516 watchdog_reset(&ctx, 5);
1517 do_disconnect(&ctx);
1518 watchdog_reset(&ctx, 15);
1519 do_connect(&ctx, tty);
1527 if (FD_ISSET(ctx.fd, &set)) {
1528 watchdog_reset(&ctx, 15);
1529 error = at_async(&ctx, &ctx);
1533 FD_SET(ctx.fd, &set);
1535 if (!(ctx.flags & FLG_DAEMON) && (ctx.flags & IPASSIGNED)) {
1536 printf("Status: %s (%s)",
1537 ctx.con_status ? "connected" : "disconnected",
1538 network_access_type[ctx.con_net_type]);
1540 printf(", signal: %d dBm", ctx.dbm);
1545 if (!(ctx.flags & FLG_DAEMON) && (ctx.flags & IPASSIGNED))
1548 signal(SIGHUP, SIG_DFL);
1549 signal(SIGINT, SIG_DFL);
1550 signal(SIGQUIT, SIG_DFL);
1551 signal(SIGTERM, SIG_DFL);
1552 signal(SIGALRM, SIG_IGN);
1554 do_disconnect(&ctx);
1556 if (ctx.flags & FLG_DAEMON) {
1557 pidfile_remove(ctx.pfh);