Print correct error when /dev/net/tun open fails
[platform/upstream/openconnect.git] / tun.c
1 /*
2  * OpenConnect (SSL + DTLS) VPN client
3  *
4  * Copyright © 2008-2012 Intel Corporation.
5  *
6  * Author: David Woodhouse <dwmw2@infradead.org>
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * version 2.1, as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to:
19  *
20  *   Free Software Foundation, Inc.
21  *   51 Franklin Street, Fifth Floor,
22  *   Boston, MA 02110-1301 USA
23  */
24
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <sys/socket.h>
28 #include <sys/ioctl.h>
29 #include <string.h>
30 #include <signal.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <netdb.h>
34 #include <netinet/in_systm.h>
35 #include <netinet/in.h>
36 #include <netinet/ip.h>
37 #include <net/if.h>
38 #include <arpa/inet.h>
39 #include <errno.h>
40 #include <ctype.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #if defined(__sun__)
44 #include <stropts.h>
45 #include <sys/sockio.h>
46 #include <net/if_tun.h>
47 #ifndef TUNNEWPPA
48 #error "Install TAP driver from http://www.whiteboard.ne.jp/~admin2/tuntap/"
49 #endif
50 #endif
51
52 #include "openconnect-internal.h"
53
54 /*
55  * If an if_tun.h include file was found anywhere (by the Makefile), it's 
56  * included. Else, we end up assuming that we have BSD-style devices such
57  * as /dev/tun0 etc.
58  */
59 #ifdef IF_TUN_HDR
60 #include IF_TUN_HDR
61 #endif
62
63 /*
64  * The OS X tun/tap driver doesn't provide a header file; you're expected
65  * to define this for yourself.
66  */
67 #ifdef __APPLE__
68 #define TUNSIFHEAD  _IOW('t', 96, int)
69 #endif
70
71 /*
72  * OpenBSD always puts the protocol family prefix onto packets. Other
73  * systems let us enable that with the TUNSIFHEAD ioctl, and some of them
74  * (e.g. FreeBSD) _need_ it otherwise they'll interpret IPv6 packets as IPv4.
75  */
76 #if defined(__OpenBSD__) || defined(TUNSIFHEAD)
77 #define TUN_HAS_AF_PREFIX 1
78 #endif
79
80 static int set_tun_mtu(struct openconnect_info *vpninfo)
81 {
82 #ifndef __sun__ /* We don't know how to do this on Solaris */
83         struct ifreq ifr;
84         int net_fd;
85
86         net_fd = socket(PF_INET, SOCK_DGRAM, 0);
87         if (net_fd < 0) {
88                 perror(_("open net"));
89                 return -EINVAL;
90         }
91
92         memset(&ifr, 0, sizeof(ifr));
93         strncpy(ifr.ifr_name, vpninfo->ifname, sizeof(ifr.ifr_name) - 1);
94         ifr.ifr_mtu = vpninfo->mtu;
95
96         if (ioctl(net_fd, SIOCSIFMTU, &ifr) < 0)
97                 perror(_("SIOCSIFMTU"));
98
99         close(net_fd);
100 #endif
101         return 0;
102 }
103
104
105 static int setenv_int(const char *opt, int value)
106 {
107         char buf[16];
108         sprintf(buf, "%d", value);
109         return setenv(opt, buf, 1);
110 }
111
112 static int netmasklen(struct in_addr addr)
113 {
114         int masklen;
115
116         for (masklen = 0; masklen < 32; masklen++) {
117                 if (ntohl(addr.s_addr) >= (0xffffffff << masklen))
118                         break;
119         }
120         return 32 - masklen;
121 }
122
123 static int process_split_xxclude(struct openconnect_info *vpninfo,
124                                  int include, const char *route, int *v4_incs,
125                                  int *v6_incs)
126 {
127         struct in_addr addr;
128         const char *in_ex = include?"IN":"EX";
129         char envname[80];
130         char *slash;
131
132         slash = strchr(route, '/');
133         if (!slash) {
134         badinc:
135                 if (include)
136                         vpn_progress(vpninfo, PRG_ERR,
137                                      _("Discard bad split include: \"%s\"\n"),
138                                      route);
139                 else
140                         vpn_progress(vpninfo, PRG_ERR,
141                                      _("Discard bad split exclude: \"%s\"\n"),
142                                      route);
143                 return -EINVAL;
144         }
145
146         *slash = 0;
147
148         if (strchr(route, ':')) {
149                 snprintf(envname, 79, "CISCO_IPV6_SPLIT_%sC_%d_ADDR", in_ex,
150                          *v6_incs);
151                 setenv(envname, route, 1);
152
153                 snprintf(envname, 79, "CISCO_IPV6_SPLIT_%sC_%d_MASKLEN", in_ex,
154                          *v6_incs);
155                 setenv(envname, slash+1, 1);
156
157                 (*v6_incs)++;
158                 return 0;
159         }
160                 
161         if (!inet_aton(route, &addr)) {
162                 *slash = '/';
163                 goto badinc;
164         }
165
166         envname[79] = 0;
167         snprintf(envname, 79, "CISCO_SPLIT_%sC_%d_ADDR", in_ex, *v4_incs);
168         setenv(envname, route, 1);
169
170         /* Put it back how we found it */
171         *slash = '/';
172
173         if (!inet_aton(slash+1, &addr))
174                 goto badinc;
175
176         snprintf(envname, 79, "CISCO_SPLIT_%sC_%d_MASK", in_ex, *v4_incs);
177         setenv(envname, slash+1, 1);
178
179         snprintf(envname, 79, "CISCO_SPLIT_%sC_%d_MASKLEN", in_ex, *v4_incs);
180         setenv_int(envname, netmasklen(addr));
181
182         (*v4_incs)++;
183         return 0;
184 }
185
186 static int appendenv(const char *opt, const char *new)
187 {
188         char buf[1024];
189         char *old = getenv(opt);
190
191         buf[1023] = 0;
192         if (old)
193                 snprintf(buf, 1023, "%s %s", old, new);
194         else
195                 snprintf(buf, 1023, "%s", new);
196
197         return setenv(opt, buf, 1);
198 }
199
200 static void setenv_cstp_opts(struct openconnect_info *vpninfo)
201 {
202         char *env_buf;
203         int buflen = 0;
204         int bufofs = 0;
205         struct vpn_option *opt;
206
207         for (opt = vpninfo->cstp_options; opt; opt = opt->next)
208                 buflen += 2 + strlen(opt->option) + strlen(opt->value);
209
210         env_buf = malloc(buflen + 1);
211         if (!env_buf)
212                 return;
213
214         env_buf[buflen] = 0;
215
216         for (opt = vpninfo->cstp_options; opt; opt = opt->next)
217                 bufofs += snprintf(env_buf + bufofs, buflen - bufofs,
218                                    "%s=%s\n", opt->option, opt->value);
219
220         setenv("CISCO_CSTP_OPTIONS", env_buf, 1);
221         free(env_buf);
222 }
223
224 static void set_banner(struct openconnect_info *vpninfo)
225 {
226         char *banner, *q;
227         const char *p;
228
229         if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)+1))) {
230                 unsetenv("CISCO_BANNER");
231                 return;
232         }
233         p = vpninfo->banner;
234         q = banner;
235         
236         while (*p) {
237                 if (*p == '%' && isxdigit((int)(unsigned char)p[1]) &&
238                     isxdigit((int)(unsigned char)p[2])) {
239                         *(q++) = unhex(p + 1);
240                         p += 3;
241                 } else 
242                         *(q++) = *(p++);
243         }
244         *q = 0;
245         setenv("CISCO_BANNER", banner, 1);
246
247         free(banner);
248 }       
249
250 static void set_script_env(struct openconnect_info *vpninfo)
251 {
252         char host[80];
253         int ret = getnameinfo(vpninfo->peer_addr, vpninfo->peer_addrlen, host,
254                               sizeof(host), NULL, 0, NI_NUMERICHOST);
255         if (!ret)
256                 setenv("VPNGATEWAY", host, 1);
257
258         set_banner(vpninfo);
259         unsetenv("CISCO_SPLIT_INC");
260         unsetenv("CISCO_SPLIT_EXC");
261
262         setenv_int("INTERNAL_IP4_MTU", vpninfo->mtu);
263
264         if (vpninfo->vpn_addr) {
265                 setenv("INTERNAL_IP4_ADDRESS", vpninfo->vpn_addr, 1);
266                 if (vpninfo->vpn_netmask) {
267                         struct in_addr addr;
268                         struct in_addr mask;
269
270                         if (inet_aton(vpninfo->vpn_addr, &addr) &&
271                             inet_aton(vpninfo->vpn_netmask, &mask)) {
272                                 char *netaddr;
273
274                                 addr.s_addr &= mask.s_addr;
275                                 netaddr = inet_ntoa(addr);
276
277                                 setenv("INTERNAL_IP4_NETADDR", netaddr, 1);
278                                 setenv("INTERNAL_IP4_NETMASK", vpninfo->vpn_netmask, 1);
279                                 setenv_int("INTERNAL_IP4_NETMASKLEN", netmasklen(mask));
280                         }
281                 }
282         }
283         if (vpninfo->vpn_addr6) {
284                 setenv("INTERNAL_IP6_ADDRESS", vpninfo->vpn_addr6, 1);
285                 setenv("INTERNAL_IP6_NETMASK", vpninfo->vpn_netmask6, 1);
286         }
287
288         if (vpninfo->vpn_dns[0])
289                 setenv("INTERNAL_IP4_DNS", vpninfo->vpn_dns[0], 1);
290         else
291                 unsetenv("INTERNAL_IP4_DNS");
292         if (vpninfo->vpn_dns[1])
293                 appendenv("INTERNAL_IP4_DNS", vpninfo->vpn_dns[1]);
294         if (vpninfo->vpn_dns[2])
295                 appendenv("INTERNAL_IP4_DNS", vpninfo->vpn_dns[2]);
296
297         if (vpninfo->vpn_nbns[0])
298                 setenv("INTERNAL_IP4_NBNS", vpninfo->vpn_nbns[0], 1);
299         else
300                 unsetenv("INTERNAL_IP4_NBNS");
301         if (vpninfo->vpn_nbns[1])
302                 appendenv("INTERNAL_IP4_NBNS", vpninfo->vpn_nbns[1]);
303         if (vpninfo->vpn_nbns[2])
304                 appendenv("INTERNAL_IP4_NBNS", vpninfo->vpn_nbns[2]);
305
306         if (vpninfo->vpn_domain)
307                 setenv("CISCO_DEF_DOMAIN", vpninfo->vpn_domain, 1);
308         else unsetenv ("CISCO_DEF_DOMAIN");
309
310         if (vpninfo->vpn_proxy_pac)
311                 setenv("CISCO_PROXY_PAC", vpninfo->vpn_proxy_pac, 1);
312
313         if (vpninfo->split_dns) {
314                 char *list;
315                 int len = 0;
316                 struct split_include *dns = vpninfo->split_dns;
317
318                 while (dns) {
319                         len += strlen(dns->route) + 1;
320                         dns = dns->next;
321                 }
322                 list = malloc(len);
323                 if (list) {
324                         char *p = list;
325
326                         dns = vpninfo->split_dns;
327                         while (1) {
328                                 strcpy(p, dns->route);
329                                 p += strlen(p);
330                                 dns = dns->next;
331                                 if (!dns)
332                                         break;
333                                 *(p++) = ',';
334                         }
335                         setenv("CISCO_SPLIT_DNS", list, 1);
336                         free(list);
337                 }
338         }
339         if (vpninfo->split_includes) {
340                 struct split_include *this = vpninfo->split_includes;
341                 int nr_split_includes = 0;
342                 int nr_v6_split_includes = 0;
343
344                 while (this) {
345                         process_split_xxclude(vpninfo, 1, this->route,
346                                               &nr_split_includes,
347                                               &nr_v6_split_includes);
348                         this = this->next;
349                 }
350                 if (nr_split_includes)
351                         setenv_int("CISCO_SPLIT_INC", nr_split_includes);
352                 if (nr_v6_split_includes)
353                         setenv_int("CISCO_IPV6_SPLIT_INC", nr_v6_split_includes);
354         }
355         if (vpninfo->split_excludes) {
356                 struct split_include *this = vpninfo->split_excludes;
357                 int nr_split_excludes = 0;
358                 int nr_v6_split_excludes = 0;
359
360                 while (this) {
361                         process_split_xxclude(vpninfo, 0, this->route,
362                                               &nr_split_excludes,
363                                               &nr_v6_split_excludes);
364                         this = this->next;
365                 }
366                 if (nr_split_excludes)
367                         setenv_int("CISCO_SPLIT_EXC", nr_split_excludes);
368                 if (nr_v6_split_excludes)
369                         setenv_int("CISCO_IPV6_SPLIT_EXC", nr_v6_split_excludes);
370         }
371         setenv_cstp_opts(vpninfo);
372 }
373
374 int script_config_tun(struct openconnect_info *vpninfo, const char *reason)
375 {
376         if (!vpninfo->vpnc_script)
377                 return 0;
378
379         setenv("reason", reason, 1);
380         if (system(vpninfo->vpnc_script)) {
381                 int e = errno;
382                 vpn_progress(vpninfo, PRG_ERR,
383                              _("Failed to spawn script '%s' for %s: %s\n"),
384                              vpninfo->vpnc_script, reason, strerror(e));
385                 return -e;
386         }
387         return 0;
388 }
389
390 #ifdef __sun__
391 static int link_proto(int unit_nr, const char *devname, uint64_t flags)
392 {
393         int ip_fd, mux_id, tun2_fd;
394         struct lifreq ifr;
395
396         tun2_fd = open("/dev/tun", O_RDWR);
397         if (tun2_fd < 0) {
398                 perror(_("Could not /dev/tun for plumbing"));
399                 return -EIO;
400         }
401         if (ioctl(tun2_fd, I_PUSH, "ip") < 0) {
402                 perror(_("Can't push IP"));
403                 close(tun2_fd);
404                 return -EIO;
405         }
406
407         sprintf(ifr.lifr_name, "tun%d", unit_nr);
408         ifr.lifr_ppa = unit_nr;
409         ifr.lifr_flags = flags;
410
411         if (ioctl(tun2_fd, SIOCSLIFNAME, &ifr) < 0) {
412                 perror(_("Can't set ifname"));
413                 close(tun2_fd);
414                 return -1;
415         }
416
417         ip_fd = open(devname, O_RDWR);
418         if (ip_fd < 0) {
419                 fprintf(stderr, _("Can't open %s: %s"), devname,
420                         strerror(errno));
421                 close(tun2_fd);
422                 return -1;
423         }
424
425         mux_id = ioctl(ip_fd, I_LINK, tun2_fd);
426         if (mux_id < 0) {
427                 fprintf(stderr, _("Can't plumb %s for IPv%d: %s\n"),
428                          ifr.lifr_name, (flags == IFF_IPV4) ? 4 : 6,
429                          strerror(errno));
430                 close(tun2_fd);
431                 close(ip_fd);
432                 return -1;
433         }
434
435         close(tun2_fd);
436
437         return ip_fd;
438 }
439 #endif
440
441 #ifdef SIOCIFCREATE
442 static int bsd_open_tun(char *tun_name)
443 {
444         int fd;
445         int s;
446         struct ifreq ifr;
447
448         fd = open(tun_name, O_RDWR);
449         if (fd >= 0) {
450                 return fd;
451
452                 s = socket(AF_INET, SOCK_DGRAM, 0);
453                 if (s < 0)
454                         return -1;
455
456                 memset(&ifr, 0, sizeof(ifr));
457                 strncpy(ifr.ifr_name, tun_name + 5, sizeof(ifr.ifr_name) - 1);
458                 if (!ioctl(s, SIOCIFCREATE, &ifr))
459                         fd = open(tun_name, O_RDWR);
460
461                 close(s);
462         }
463         return fd;
464 }
465 #else
466 #define bsd_open_tun(tun_name) open(tun_name, O_RDWR)
467 #endif
468
469 static int os_setup_tun(struct openconnect_info *vpninfo)
470 {
471         int tun_fd = -1;
472
473 #ifdef IFF_TUN /* Linux */
474         struct ifreq ifr;
475         int tunerr;
476
477         tun_fd = open("/dev/net/tun", O_RDWR);
478         if (tun_fd < 0) {
479                 /* Android has /dev/tun instead of /dev/net/tun
480                    Since other systems might have too, just try it
481                    as a fallback instead of using ifdef __ANDROID__ */
482                 tunerr = errno;
483                 tun_fd = open("/dev/tun", O_RDWR);
484         }
485         if (tun_fd < 0) {
486                 /* If the error on /dev/tun is ENOENT, that's boring.
487                    Use the error we got on /dev/net/tun instead */
488                 if (errno != ENOENT)
489                         tunerr = errno;
490
491                 vpn_progress(vpninfo, PRG_ERR,
492                              _("Failed to open tun device: %s\n"),
493                              strerror(tunerr));
494                 exit(1);
495         }
496         memset(&ifr, 0, sizeof(ifr));
497         ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
498         if (vpninfo->ifname)
499                 strncpy(ifr.ifr_name, vpninfo->ifname,
500                         sizeof(ifr.ifr_name) - 1);
501         if (ioctl(tun_fd, TUNSETIFF, (void *) &ifr) < 0) {
502                 vpn_progress(vpninfo, PRG_ERR,
503                              _("TUNSETIFF failed: %s\n"),
504                              strerror(errno));
505                 exit(1);
506         }
507         if (!vpninfo->ifname)
508                 vpninfo->ifname = strdup(ifr.ifr_name);
509 #elif defined (__sun__)
510         static char tun_name[80];
511         int unit_nr;
512
513         tun_fd = open("/dev/tun", O_RDWR);
514         if (tun_fd < 0) {
515                 perror(_("open /dev/tun"));
516                 return -EIO;
517         }
518
519         unit_nr = ioctl(tun_fd, TUNNEWPPA, -1);
520         if (unit_nr < 0) {
521                 perror(_("Failed to create new tun"));
522                 close(tun_fd);
523                 return -EIO;
524         }
525
526         if (ioctl(tun_fd, I_SRDOPT, RMSGD) < 0) {
527                 perror(_("Failed to put tun file descriptor into message-discard mode"));
528                 close(tun_fd);
529                 return -EIO;
530         }
531
532         sprintf(tun_name, "tun%d", unit_nr);
533         vpninfo->ifname = strdup(tun_name);
534
535         vpninfo->ip_fd = link_proto(unit_nr, "/dev/udp", IFF_IPV4);
536         if (vpninfo->ip_fd < 0) {
537                 close(tun_fd);
538                 return -EIO;
539         }
540
541         if (vpninfo->vpn_addr6) {
542                 vpninfo->ip6_fd = link_proto(unit_nr, "/dev/udp6", IFF_IPV6);
543                 if (vpninfo->ip6_fd < 0) {
544                         close(tun_fd);
545                         close(vpninfo->ip_fd);
546                         vpninfo->ip_fd = -1;
547                         return -EIO;
548                 }
549         } else
550                 vpninfo->ip6_fd = -1;
551
552 #else /* BSD et al have /dev/tun$x devices */
553         static char tun_name[80];
554         int i;
555
556         if (vpninfo->ifname) {
557                 char *endp = NULL;
558                 if (strncmp(vpninfo->ifname, "tun", 3) ||
559                     ((void)strtol(vpninfo->ifname + 3, &endp, 10), !endp) ||
560                     *endp) {
561                         vpn_progress(vpninfo, PRG_ERR,
562                                      _("Invalid interface name '%s'; must match 'tun%%d'\n"),
563                                      vpninfo->ifname);
564                         return -EINVAL;
565                 }
566                 snprintf(tun_name, sizeof(tun_name),
567                          "/dev/%s", vpninfo->ifname);
568                 tun_fd = bsd_open_tun(tun_name);
569                 if (tun_fd < 0) {
570                         int err = errno;
571                         vpn_progress(vpninfo, PRG_ERR,
572                                      _("Cannot open '%s': %s\n"),
573                                      tun_name, strerror(err));
574                         return -EINVAL;
575                 }
576         }
577 #ifdef HAVE_FDEVNAME_R
578         /* We don't have to iterate over the possible devices; on FreeBSD
579            at least, opening /dev/tun will give us the next available
580            device. */
581         if (tun_fd < 0) {
582                 tun_fd = open("/dev/tun", O_RDWR);
583                 if (tun_fd >= 0) {
584                         if (!fdevname_r(tun_fd, tun_name, sizeof(tun_name)) ||
585                             strncmp(tun_name, "tun", 3)) {
586                                 close(tun_fd);
587                                 tun_fd = -1;
588                         } else
589                                 vpninfo->ifname = strdup(tun_name);
590                 }
591         }
592 #endif
593         if (tun_fd < 0) {
594                 for (i = 0; i < 255; i++) {
595                         sprintf(tun_name, "/dev/tun%d", i);
596                         tun_fd = bsd_open_tun(tun_name);
597                         if (tun_fd >= 0)
598                                 break;
599                 }
600                 if (tun_fd < 0) {
601                         perror(_("open tun"));
602                         exit(1);
603                 }
604                 vpninfo->ifname = strdup(tun_name + 5);
605         }
606 #ifdef TUNSIFHEAD
607         i = 1;
608         if (ioctl(tun_fd, TUNSIFHEAD, &i) < 0) {
609                 perror(_("TUNSIFHEAD"));
610                 exit(1);
611         }
612 #endif
613 #endif
614         return tun_fd;
615 }
616
617 /* Set up a tuntap device. */
618 int setup_tun(struct openconnect_info *vpninfo)
619 {
620         int tun_fd;
621
622         set_script_env(vpninfo);
623
624         if (vpninfo->script_tun) {
625                 pid_t child;
626                 int fds[2];
627
628                 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, fds)) {
629                         perror(_("socketpair"));
630                         exit(1);
631                 }
632                 tun_fd = fds[0];
633                 child = fork();
634                 if (child < 0) {
635                         perror(_("fork"));
636                         exit(1);
637                 } else if (!child) {
638                         close(tun_fd);
639                         setenv_int("VPNFD", fds[1]);
640                         execl("/bin/sh", "/bin/sh", "-c", vpninfo->vpnc_script, NULL);
641                         perror(_("execl"));
642                         exit(1);
643                 }
644                 close(fds[1]);
645                 vpninfo->script_tun = child;
646                 vpninfo->ifname = strdup(_("(script)"));
647         } else {
648                 script_config_tun(vpninfo, "pre-init");
649
650                 tun_fd = os_setup_tun(vpninfo);
651                 if (tun_fd < 0)
652                         return tun_fd;
653
654                 setenv("TUNDEV", vpninfo->ifname, 1);
655                 script_config_tun(vpninfo, "connect");
656
657                 /* Ancient vpnc-scripts might not get this right */
658                 set_tun_mtu(vpninfo);
659         }
660
661         fcntl(tun_fd, F_SETFD, FD_CLOEXEC);
662
663         vpninfo->tun_fd = tun_fd;
664
665         if (vpninfo->select_nfds <= tun_fd)
666                 vpninfo->select_nfds = tun_fd + 1;
667
668         FD_SET(tun_fd, &vpninfo->select_rfds);
669
670         fcntl(vpninfo->tun_fd, F_SETFL, fcntl(vpninfo->tun_fd, F_GETFL) | O_NONBLOCK);
671
672         return 0;
673 }
674
675 static struct pkt *out_pkt;
676
677 int tun_mainloop(struct openconnect_info *vpninfo, int *timeout)
678 {
679         int work_done = 0;
680         int prefix_size = 0;
681
682 #ifdef TUN_HAS_AF_PREFIX
683         if (!vpninfo->script_tun)
684                 prefix_size = sizeof(int);
685 #endif
686
687         if (FD_ISSET(vpninfo->tun_fd, &vpninfo->select_rfds)) {
688                 while (1) {
689                         int len = vpninfo->mtu;
690
691                         if (!out_pkt) {
692                                 out_pkt = malloc(sizeof(struct pkt) + len);
693                                 if (!out_pkt) {
694                                         vpn_progress(vpninfo, PRG_ERR, "Allocation failed\n");
695                                         break;
696                                 }
697                         }
698
699                         len = read(vpninfo->tun_fd, out_pkt->data - prefix_size, len + prefix_size);
700                         if (len <= prefix_size)
701                                 break;
702                         out_pkt->len = len - prefix_size;
703
704                         queue_packet(&vpninfo->outgoing_queue, out_pkt);
705                         out_pkt = NULL;
706
707                         work_done = 1;
708                         vpninfo->outgoing_qlen++;
709                         if (vpninfo->outgoing_qlen == vpninfo->max_qlen) {
710                                 FD_CLR(vpninfo->tun_fd, &vpninfo->select_rfds);
711                                 break;
712                         }
713                 }
714         } else if (vpninfo->outgoing_qlen < vpninfo->max_qlen) {
715                 FD_SET(vpninfo->tun_fd, &vpninfo->select_rfds);
716         }
717
718         /* The kernel returns -ENOMEM when the queue is full, so theoretically
719            we could handle that and retry... but it doesn't let us poll() for
720            the no-longer-full situation, so let's not bother. */
721         while (vpninfo->incoming_queue) {
722                 struct pkt *this = vpninfo->incoming_queue;
723                 unsigned char *data = this->data;
724                 int len = this->len;
725
726 #ifdef TUN_HAS_AF_PREFIX
727                 if (!vpninfo->script_tun) {
728                         struct ip *iph = (void *)data;
729                         int type;
730
731                         if (iph->ip_v == 6)
732                                 type = AF_INET6;
733                         else if (iph->ip_v == 4)
734                                 type = AF_INET;
735                         else {
736                                 static int complained = 0;
737                                 if (!complained) {
738                                         complained = 1;
739                                         vpn_progress(vpninfo, PRG_ERR,
740                                                      _("Unknown packet (len %d) received: %02x %02x %02x %02x...\n"),
741                                                      len, data[0], data[1], data[2], data[3]);
742                                 }
743                                 free(this);
744                                 continue;
745                         }
746                         data -= 4;
747                         len += 4;
748                         *(int *)data = htonl(type);
749                 }
750 #endif
751                 vpninfo->incoming_queue = this->next;
752
753                 if (write(vpninfo->tun_fd, data, len) < 0) {
754                         /* Handle death of "script" socket */
755                         if (vpninfo->script_tun && errno == ENOTCONN) {
756                                 vpninfo->quit_reason = "Client connection terminated";
757                                 return 1;
758                         }
759                         vpn_progress(vpninfo, PRG_ERR,
760                                      _("Failed to write incoming packet: %s\n"),
761                                      strerror(errno));
762                 }
763                 free(this);
764         }
765         /* Work is not done if we just got rid of packets off the queue */
766         return work_done;
767 }
768
769 void shutdown_tun(struct openconnect_info *vpninfo)
770 {       
771         if (vpninfo->script_tun) {
772                 kill(vpninfo->script_tun, SIGHUP);
773         } else {
774                 script_config_tun(vpninfo, "disconnect");
775 #ifdef __sun__
776                 close(vpninfo->ip_fd);
777                 vpninfo->ip_fd = -1;
778                 if (vpninfo->ip6_fd != -1) {
779                         close(vpninfo->ip6_fd);
780                         vpninfo->ip6_fd = -1;
781                 }
782 #endif
783         }
784
785         close(vpninfo->tun_fd);
786         vpninfo->tun_fd = -1;
787 }