oops, forgot mainloop.c
[platform/upstream/openconnect.git] / mainloop.c
1 /*
2  * Open AnyConnect (SSL + DTLS) client
3  *
4  * © 2008 David Woodhouse <dwmw2@infradead.org>
5  *
6  * Permission to use, copy, modify, and/or distribute this software
7  * for any purpose with or without fee is hereby granted, provided
8  * that the above copyright notice and this permission notice appear
9  * in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
12  * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
13  * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
14  * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
15  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
16  * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
17  * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
18  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20
21 #include <errno.h>
22 #include <poll.h>
23 #include <limits.h>
24 #include <sys/select.h>
25 #include "anyconnect.h"
26
27 int queue_new_packet(struct pkt **q, int type, void *buf, int len)
28 {
29         while (*q)
30                 q = &(*q)->next;
31
32         *q = malloc(sizeof(struct pkt) + len);
33         if (!*q)
34                 return -ENOMEM;
35
36         (*q)->type = type;
37         (*q)->len = len;
38         (*q)->next = NULL;
39         memcpy((*q)->data, buf, len);
40         return 0;
41 }
42
43 int vpn_add_pollfd(struct anyconnect_info *vpninfo, int fd, short events)
44 {
45         vpninfo->nfds++;
46         vpninfo->pfds = realloc(vpninfo->pfds, sizeof(struct pollfd) * vpninfo->nfds);
47         if (!vpninfo->pfds) {
48                 fprintf(stderr, "Failed to reallocate pfds\n");
49                 exit(1);
50         }
51         vpninfo->pfds[vpninfo->nfds - 1].fd = fd;
52         vpninfo->pfds[vpninfo->nfds - 1].events = events;
53
54         return vpninfo->nfds - 1;
55 }
56
57 int vpn_mainloop(struct anyconnect_info *vpninfo)
58 {
59         while (1) {
60                 int did_work = 0;
61                 int timeout = INT_MAX;
62
63                 if (vpninfo->dtls_fd != -1)
64                         did_work += dtls_mainloop(vpninfo, &timeout);
65
66                 did_work += ssl_mainloop(vpninfo, &timeout);
67                 did_work += tun_mainloop(vpninfo, &timeout);
68                 
69                 if (did_work)
70                         continue;
71                 
72                 if (verbose)
73                         printf("Did no work; sleeping for %d ms...\n", timeout);
74
75                 poll(vpninfo->pfds, vpninfo->nfds, timeout);
76         }       
77         return 0;
78 }