dnsproxy: Add function __connman_dnsproxy_add/remove_listener()
[platform/upstream/connman.git] / src / dnsproxy.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2010  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <errno.h>
27 #include <unistd.h>
28 #include <string.h>
29 #include <stdint.h>
30 #include <arpa/inet.h>
31 #include <netinet/in.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <netdb.h>
35
36 #include <glib.h>
37
38 #include "connman.h"
39
40 #if __BYTE_ORDER == __LITTLE_ENDIAN
41 struct domain_hdr {
42         uint16_t id;
43         uint8_t rd:1;
44         uint8_t tc:1;
45         uint8_t aa:1;
46         uint8_t opcode:4;
47         uint8_t qr:1;
48         uint8_t rcode:4;
49         uint8_t z:3;
50         uint8_t ra:1;
51         uint16_t qdcount;
52         uint16_t ancount;
53         uint16_t nscount;
54         uint16_t arcount;
55 } __attribute__ ((packed));
56 #elif __BYTE_ORDER == __BIG_ENDIAN
57 struct domain_hdr {
58         uint16_t id;
59         uint8_t qr:1;
60         uint8_t opcode:4;
61         uint8_t aa:1;
62         uint8_t tc:1;
63         uint8_t rd:1;
64         uint8_t ra:1;
65         uint8_t z:3;
66         uint8_t rcode:4;
67         uint16_t qdcount;
68         uint16_t ancount;
69         uint16_t nscount;
70         uint16_t arcount;
71 } __attribute__ ((packed));
72 #else
73 #error "Unknown byte order"
74 #endif
75
76 struct partial_reply {
77         uint16_t len;
78         uint16_t received;
79         unsigned char buf[];
80 };
81
82 struct server_data {
83         char *interface;
84         GList *domains;
85         char *server;
86         int protocol;
87         GIOChannel *channel;
88         guint watch;
89         guint timeout;
90         gboolean enabled;
91         gboolean connected;
92         struct partial_reply *incoming_reply;
93 };
94
95 struct request_data {
96         union {
97                 struct sockaddr_in6 __sin6; /* Only for the length */
98                 struct sockaddr sa;
99         };
100         socklen_t sa_len;
101         int client_sk;
102         int protocol;
103         guint16 srcid;
104         guint16 dstid;
105         guint16 altid;
106         guint timeout;
107         guint watch;
108         guint numserv;
109         guint numresp;
110         gpointer request;
111         gsize request_len;
112         gpointer name;
113         gpointer resp;
114         gsize resplen;
115         struct listener_data *ifdata;
116 };
117
118 struct listener_data {
119         char *ifname;
120         GIOChannel *udp_listener_channel;
121         guint udp_listener_watch;
122         GIOChannel *tcp_listener_channel;
123         guint tcp_listener_watch;
124 };
125
126 static GSList *server_list = NULL;
127 static GSList *request_list = NULL;
128 static GSList *request_pending_list = NULL;
129 static guint16 request_id = 0x0000;
130 static GHashTable *listener_table = NULL;
131
132 static int protocol_offset(int protocol)
133 {
134         switch (protocol) {
135         case IPPROTO_UDP:
136                 return 0;
137
138         case IPPROTO_TCP:
139                 return 2;
140
141         default:
142                 return -EINVAL;
143         }
144
145 }
146
147 static struct request_data *find_request(guint16 id)
148 {
149         GSList *list;
150
151         for (list = request_list; list; list = list->next) {
152                 struct request_data *req = list->data;
153
154                 if (req->dstid == id || req->altid == id)
155                         return req;
156         }
157
158         return NULL;
159 }
160
161 static struct server_data *find_server(const char *interface,
162                                         const char *server,
163                                                 int protocol)
164 {
165         GSList *list;
166
167         DBG("interface %s server %s", interface, server);
168
169         for (list = server_list; list; list = list->next) {
170                 struct server_data *data = list->data;
171
172                 if (interface == NULL && data->interface == NULL &&
173                                 g_str_equal(data->server, server) == TRUE &&
174                                 data->protocol == protocol)
175                         return data;
176
177                 if (interface == NULL ||
178                                 data->interface == NULL || data->server == NULL)
179                         continue;
180
181                 if (g_str_equal(data->interface, interface) == TRUE &&
182                                 g_str_equal(data->server, server) == TRUE &&
183                                 data->protocol == protocol)
184                         return data;
185         }
186
187         return NULL;
188 }
189
190
191 static void send_response(int sk, unsigned char *buf, int len,
192                                 const struct sockaddr *to, socklen_t tolen,
193                                 int protocol)
194 {
195         struct domain_hdr *hdr;
196         int err, offset = protocol_offset(protocol);
197
198         DBG("");
199
200         if (offset < 0)
201                 return;
202
203         if (len < 12)
204                 return;
205
206         hdr = (void *) (buf + offset);
207
208         DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
209
210         hdr->qr = 1;
211         hdr->rcode = 2;
212
213         hdr->ancount = 0;
214         hdr->nscount = 0;
215         hdr->arcount = 0;
216
217         err = sendto(sk, buf, len, 0, to, tolen);
218 }
219
220 static gboolean request_timeout(gpointer user_data)
221 {
222         struct request_data *req = user_data;
223         struct listener_data *ifdata;
224
225         DBG("id 0x%04x", req->srcid);
226
227         if (req == NULL)
228                 return FALSE;
229
230         ifdata = req->ifdata;
231
232         request_list = g_slist_remove(request_list, req);
233         req->numserv--;
234
235         if (req->resplen > 0 && req->resp != NULL) {
236                 int sk, err;
237
238                 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
239
240                 err = sendto(sk, req->resp, req->resplen, 0,
241                              &req->sa, req->sa_len);
242         } else if (req->request && req->numserv == 0) {
243                 struct domain_hdr *hdr;
244
245                 if (req->protocol == IPPROTO_TCP) {
246                         hdr = (void *) (req->request + 2);
247                         hdr->id = req->srcid;
248                         send_response(req->client_sk, req->request,
249                                         req->request_len, NULL, 0, IPPROTO_TCP);
250
251                 } else if (req->protocol == IPPROTO_UDP) {
252                         int sk;
253
254                         hdr = (void *) (req->request);
255                         hdr->id = req->srcid;
256                         sk = g_io_channel_unix_get_fd(
257                                                 ifdata->udp_listener_channel);
258                         send_response(sk, req->request, req->request_len,
259                                       &req->sa, req->sa_len, IPPROTO_UDP);
260                 }
261         }
262
263         g_free(req->resp);
264         g_free(req);
265
266         return FALSE;
267 }
268
269 static int append_query(unsigned char *buf, unsigned int size,
270                                 const char *query, const char *domain)
271 {
272         unsigned char *ptr = buf;
273         char *offset;
274
275         DBG("query %s domain %s", query, domain);
276
277         offset = (char *) query;
278         while (offset != NULL) {
279                 char *tmp;
280
281                 tmp = strchr(offset, '.');
282                 if (tmp == NULL) {
283                         if (strlen(offset) == 0)
284                                 break;
285                         *ptr = strlen(offset);
286                         memcpy(ptr + 1, offset, strlen(offset));
287                         ptr += strlen(offset) + 1;
288                         break;
289                 }
290
291                 *ptr = tmp - offset;
292                 memcpy(ptr + 1, offset, tmp - offset);
293                 ptr += tmp - offset + 1;
294
295                 offset = tmp + 1;
296         }
297
298         offset = (char *) domain;
299         while (offset != NULL) {
300                 char *tmp;
301
302                 tmp = strchr(offset, '.');
303                 if (tmp == NULL) {
304                         if (strlen(offset) == 0)
305                                 break;
306                         *ptr = strlen(offset);
307                         memcpy(ptr + 1, offset, strlen(offset));
308                         ptr += strlen(offset) + 1;
309                         break;
310                 }
311
312                 *ptr = tmp - offset;
313                 memcpy(ptr + 1, offset, tmp - offset);
314                 ptr += tmp - offset + 1;
315
316                 offset = tmp + 1;
317         }
318
319         *ptr++ = 0x00;
320
321         return ptr - buf;
322 }
323
324 static int ns_resolv(struct server_data *server, struct request_data *req,
325                                 gpointer request, gpointer name)
326 {
327         GList *list;
328         int sk, err;
329         char *dot, *lookup = (char *) name;
330
331         sk = g_io_channel_unix_get_fd(server->channel);
332
333         err = send(sk, request, req->request_len, 0);
334
335         req->numserv++;
336
337         /* If we have more than one dot, we don't add domains */
338         dot = strchr(lookup, '.');
339         if (dot != NULL && dot != lookup + strlen(lookup) - 1)
340                 return 0;
341
342         for (list = server->domains; list; list = list->next) {
343                 char *domain;
344                 unsigned char alt[1024];
345                 struct domain_hdr *hdr = (void *) &alt;
346                 int altlen, domlen, offset;
347
348                 domain = list->data;
349
350                 if (domain == NULL)
351                         continue;
352
353                 offset = protocol_offset(server->protocol);
354                 if (offset < 0)
355                         return offset;
356
357                 domlen = strlen(domain) + 1;
358                 if (domlen < 5)
359                         return -EINVAL;
360
361                 alt[offset] = req->altid & 0xff;
362                 alt[offset + 1] = req->altid >> 8;
363
364                 memcpy(alt + offset + 2, request + offset + 2, 10);
365                 hdr->qdcount = htons(1);
366
367                 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
368                                         name, domain);
369                 if (altlen < 0)
370                         return -EINVAL;
371
372                 altlen += 12;
373
374                 memcpy(alt + offset + altlen,
375                         request + offset + altlen - domlen,
376                                 req->request_len - altlen + domlen);
377
378                 if (server->protocol == IPPROTO_TCP) {
379                         int req_len = req->request_len + domlen - 1;
380
381                         alt[0] = (req_len >> 8) & 0xff;
382                         alt[1] = req_len & 0xff;
383                 }
384
385                 err = send(sk, alt, req->request_len + domlen + 1, 0);
386
387                 req->numserv++;
388         }
389
390         return 0;
391 }
392
393 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol)
394 {
395         struct domain_hdr *hdr;
396         struct request_data *req;
397         int dns_id, sk, err, offset = protocol_offset(protocol);
398         struct listener_data *ifdata;
399
400         if (offset < 0)
401                 return offset;
402
403         hdr = (void *)(reply + offset);
404         dns_id = reply[offset] | reply[offset + 1] << 8;
405
406         DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
407
408         req = find_request(dns_id);
409         if (req == NULL)
410                 return -EINVAL;
411
412         DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
413
414         ifdata = req->ifdata;
415
416         reply[offset] = req->srcid & 0xff;
417         reply[offset + 1] = req->srcid >> 8;
418
419         req->numresp++;
420
421         if (hdr->rcode == 0 || req->resp == NULL) {
422                 g_free(req->resp);
423                 req->resplen = 0;
424
425                 req->resp = g_try_malloc(reply_len);
426                 if (req->resp == NULL)
427                         return -ENOMEM;
428
429                 memcpy(req->resp, reply, reply_len);
430                 req->resplen = reply_len;
431         }
432
433         if (hdr->rcode > 0 && req->numresp < req->numserv)
434                 return -EINVAL;
435
436         if (req->timeout > 0)
437                 g_source_remove(req->timeout);
438
439         request_list = g_slist_remove(request_list, req);
440
441         if (protocol == IPPROTO_UDP) {
442                 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
443                 err = sendto(sk, req->resp, req->resplen, 0,
444                              &req->sa, req->sa_len);
445         } else {
446                 sk = req->client_sk;
447                 err = send(sk, req->resp, req->resplen, 0);
448                 close(sk);
449         }
450
451         g_free(req->resp);
452         g_free(req);
453
454         return err;
455 }
456
457 static void destroy_server(struct server_data *server)
458 {
459         GList *list;
460
461         DBG("interface %s server %s", server->interface, server->server);
462
463         server_list = g_slist_remove(server_list, server);
464
465         if (server->watch > 0)
466                 g_source_remove(server->watch);
467
468         if (server->timeout > 0)
469                 g_source_remove(server->timeout);
470
471         g_io_channel_unref(server->channel);
472
473         if (server->protocol == IPPROTO_UDP)
474                 connman_info("Removing DNS server %s", server->server);
475
476         g_free(server->incoming_reply);
477         g_free(server->server);
478         for (list = server->domains; list; list = list->next) {
479                 char *domain = list->data;
480
481                 server->domains = g_list_remove(server->domains, domain);
482                 g_free(domain);
483         }
484         g_free(server->interface);
485         g_free(server);
486 }
487
488 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
489                                                         gpointer user_data)
490 {
491         unsigned char buf[4096];
492         int sk, err, len;
493
494         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
495                 struct server_data *data = user_data;
496
497                 connman_error("Error with UDP server %s", data->server);
498                 data->watch = 0;
499                 return FALSE;
500         }
501
502         sk = g_io_channel_unix_get_fd(channel);
503
504         len = recv(sk, buf, sizeof(buf), 0);
505         if (len < 12)
506                 return TRUE;
507
508         err = forward_dns_reply(buf, len, IPPROTO_UDP);
509
510         return TRUE;
511 }
512
513 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
514                                                         gpointer user_data)
515 {
516         int sk;
517         struct server_data *server = user_data;
518
519         sk = g_io_channel_unix_get_fd(channel);
520         if (sk == 0)
521                 return FALSE;
522
523         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
524                 GSList *list;
525 hangup:
526                 DBG("TCP server channel closed");
527
528                 /*
529                  * Discard any partial response which is buffered; better
530                  * to get a proper response from a working server.
531                  */
532                 g_free(server->incoming_reply);
533                 server->incoming_reply = NULL;
534
535                 for (list = request_list; list; list = list->next) {
536                         struct request_data *req = list->data;
537                         struct domain_hdr *hdr;
538
539                         if (req->protocol == IPPROTO_UDP)
540                                 continue;
541
542                         if (req->request == NULL)
543                                 continue;
544
545                         /*
546                          * If we're not waiting for any further response
547                          * from another name server, then we send an error
548                          * response to the client.
549                          */
550                         if (req->numserv && --(req->numserv))
551                                 continue;
552
553                         hdr = (void *) (req->request + 2);
554                         hdr->id = req->srcid;
555                         send_response(req->client_sk, req->request,
556                                         req->request_len, NULL, 0, IPPROTO_TCP);
557
558                         request_list = g_slist_remove(request_list, req);
559                 }
560
561                 destroy_server(server);
562
563                 return FALSE;
564         }
565
566         if ((condition & G_IO_OUT) && !server->connected) {
567                 GSList *list;
568                 GList *domains;
569                 struct server_data *udp_server;
570
571                 udp_server = find_server(server->interface, server->server,
572                                                                 IPPROTO_UDP);
573                 if (udp_server != NULL) {
574                         for (domains = udp_server->domains; domains;
575                                                 domains = domains->next) {
576                                 char *dom = domains->data;
577
578                                 DBG("Adding domain %s to %s",
579                                                 dom, server->server);
580
581                                 server->domains = g_list_append(server->domains,
582                                                                 g_strdup(dom));
583                         }
584                 }
585
586                 server->connected = TRUE;
587                 server_list = g_slist_append(server_list, server);
588
589                 if (server->timeout > 0) {
590                         g_source_remove(server->timeout);
591                         server->timeout = 0;
592                 }
593
594                 for (list = request_list; list; list = list->next) {
595                         struct request_data *req = list->data;
596
597                         if (req->protocol == IPPROTO_UDP)
598                                 continue;
599
600                         DBG("Sending req %s over TCP", (char *)req->name);
601
602                         if (req->timeout > 0)
603                                 g_source_remove(req->timeout);
604
605                         req->timeout = g_timeout_add_seconds(30,
606                                                 request_timeout, req);
607                         ns_resolv(server, req, req->request, req->name);
608                 }
609
610         } else if (condition & G_IO_IN) {
611                 struct partial_reply *reply = server->incoming_reply;
612                 int bytes_recv;
613
614                 if (!reply) {
615                         unsigned char reply_len_buf[2];
616                         uint16_t reply_len;
617
618                         bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
619                         if (!bytes_recv) {
620                                 goto hangup;
621                         } else if (bytes_recv < 0) {
622                                 if (errno == EAGAIN || errno == EWOULDBLOCK)
623                                         return TRUE;
624
625                                 connman_error("DNS proxy error %s",
626                                                 strerror(errno));
627                                 goto hangup;
628                         } else if (bytes_recv < 2)
629                                 return TRUE;
630
631                         reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
632                         reply_len += 2;
633
634                         DBG("TCP reply %d bytes", reply_len);
635
636                         reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
637                         if (!reply)
638                                 return TRUE;
639
640                         reply->len = reply_len;
641                         reply->received = 0;
642
643                         server->incoming_reply = reply;
644                 }
645
646                 while (reply->received < reply->len) {
647                         bytes_recv = recv(sk, reply->buf + reply->received,
648                                         reply->len - reply->received, 0);
649                         if (!bytes_recv) {
650                                 connman_error("DNS proxy TCP disconnect");
651                                 break;
652                         } else if (bytes_recv < 0) {
653                                 if (errno == EAGAIN || errno == EWOULDBLOCK)
654                                         return TRUE;
655
656                                 connman_error("DNS proxy error %s",
657                                                 strerror(errno));
658                                 break;
659                         }
660                         reply->received += bytes_recv;
661                 }
662
663                 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP);
664
665                 g_free(reply);
666                 server->incoming_reply = NULL;
667
668                 destroy_server(server);
669
670                 return FALSE;
671         }
672
673         return TRUE;
674 }
675
676 static gboolean tcp_idle_timeout(gpointer user_data)
677 {
678         struct server_data *server = user_data;
679
680         DBG("");
681
682         if (server == NULL)
683                 return FALSE;
684
685         destroy_server(server);
686
687         return FALSE;
688 }
689
690 static struct server_data *create_server(const char *interface,
691                                         const char *domain, const char *server,
692                                         int protocol)
693 {
694         struct addrinfo hints, *rp;
695         struct server_data *data;
696         int sk, ret;
697
698         DBG("interface %s server %s", interface, server);
699
700         memset(&hints, 0, sizeof(hints));
701
702         switch (protocol) {
703         case IPPROTO_UDP:
704                 hints.ai_socktype = SOCK_DGRAM;
705                 break;
706
707         case IPPROTO_TCP:
708                 hints.ai_socktype = SOCK_STREAM;
709                 break;
710
711         default:
712                 return NULL;
713         }
714         hints.ai_family = AF_UNSPEC;
715         hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
716
717         ret = getaddrinfo(server, "53", &hints, &rp);
718         if (ret) {
719                 connman_error("Failed to parse server %s address: %s\n",
720                               server, gai_strerror(ret));
721                 return NULL;
722         }
723         /* Do not blindly copy this code elsewhere; it doesn't loop over the
724            results using ->ai_next as it should. That's OK in *this* case
725            because it was a numeric lookup; we *know* there's only one. */
726
727         sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
728         if (sk < 0) {
729                 connman_error("Failed to create server %s socket", server);
730                 freeaddrinfo(rp);
731                 return NULL;
732         }
733
734         if (interface != NULL) {
735                 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
736                                 interface, strlen(interface) + 1) < 0) {
737                         connman_error("Failed to bind server %s "
738                                                 "to interface %s",
739                                                         server, interface);
740                         freeaddrinfo(rp);
741                         close(sk);
742                         return NULL;
743                 }
744         }
745
746         data = g_try_new0(struct server_data, 1);
747         if (data == NULL) {
748                 connman_error("Failed to allocate server %s data", server);
749                 freeaddrinfo(rp);
750                 close(sk);
751                 return NULL;
752         }
753
754         data->channel = g_io_channel_unix_new(sk);
755         if (data->channel == NULL) {
756                 connman_error("Failed to create server %s channel", server);
757                 freeaddrinfo(rp);
758                 close(sk);
759                 g_free(data);
760                 return NULL;
761         }
762
763         g_io_channel_set_close_on_unref(data->channel, TRUE);
764
765         if (protocol == IPPROTO_TCP) {
766                 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
767                 data->watch = g_io_add_watch(data->channel,
768                         G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
769                                                 tcp_server_event, data);
770                 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
771                                                                 data);
772         } else
773                 data->watch = g_io_add_watch(data->channel,
774                         G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
775                                                 udp_server_event, data);
776
777         data->interface = g_strdup(interface);
778         if (domain)
779                 data->domains = g_list_append(data->domains, g_strdup(domain));
780         data->server = g_strdup(server);
781         data->protocol = protocol;
782
783         ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
784         freeaddrinfo(rp);
785         if (ret < 0) {
786                 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
787                                 protocol == IPPROTO_UDP) {
788                         GList *list;
789
790                         connman_error("Failed to connect to server %s", server);
791                         if (data->watch > 0)
792                                 g_source_remove(data->watch);
793                         if (data->timeout > 0)
794                                 g_source_remove(data->timeout);
795
796                         g_io_channel_unref(data->channel);
797                         close(sk);
798
799                         g_free(data->server);
800                         g_free(data->interface);
801                         for (list = data->domains; list; list = list->next) {
802                                 char *domain = list->data;
803
804                                 data->domains = g_list_remove(data->domains,
805                                                                         domain);
806                                 g_free(domain);
807                         }
808                         g_free(data);
809                         return NULL;
810                 }
811         }
812
813         if (protocol == IPPROTO_UDP) {
814                 /* Enable new servers by default */
815                 data->enabled = TRUE;
816                 connman_info("Adding DNS server %s", data->server);
817
818                 server_list = g_slist_append(server_list, data);
819
820                 return data;
821         }
822
823         return NULL;
824 }
825
826 static gboolean resolv(struct request_data *req,
827                                 gpointer request, gpointer name)
828 {
829         GSList *list;
830
831         for (list = server_list; list; list = list->next) {
832                 struct server_data *data = list->data;
833
834                 DBG("server %s enabled %d", data->server, data->enabled);
835
836                 if (data->enabled == FALSE)
837                         continue;
838
839                 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
840                         data->watch = g_io_add_watch(data->channel,
841                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
842                                                 udp_server_event, data);
843
844                 if (ns_resolv(data, req, request, name) < 0)
845                         continue;
846         }
847
848         return TRUE;
849 }
850
851 static void append_domain(const char *interface, const char *domain)
852 {
853         GSList *list;
854
855         DBG("interface %s domain %s", interface, domain);
856
857         if (domain == NULL)
858                 return;
859
860         for (list = server_list; list; list = list->next) {
861                 struct server_data *data = list->data;
862                 GList *dom_list;
863                 char *dom;
864                 gboolean dom_found = FALSE;
865
866                 if (data->interface == NULL)
867                         continue;
868
869                 if (g_str_equal(data->interface, interface) == FALSE)
870                         continue;
871
872                 for (dom_list = data->domains; dom_list;
873                                 dom_list = dom_list->next) {
874                         dom = dom_list->data;
875
876                         if (g_str_equal(dom, domain)) {
877                                 dom_found = TRUE;
878                                 break;
879                         }
880                 }
881
882                 if (dom_found == FALSE) {
883                         data->domains =
884                                 g_list_append(data->domains, g_strdup(domain));
885                 }
886         }
887 }
888
889 int __connman_dnsproxy_append(const char *interface, const char *domain,
890                                                         const char *server)
891 {
892         struct server_data *data;
893
894         DBG("interface %s server %s", interface, server);
895
896         if (server == NULL && domain == NULL)
897                 return -EINVAL;
898
899         if (server == NULL) {
900                 append_domain(interface, domain);
901
902                 return 0;
903         }
904
905         if (g_str_equal(server, "127.0.0.1") == TRUE)
906                 return -ENODEV;
907
908         data = find_server(interface, server, IPPROTO_UDP);
909         if (data != NULL) {
910                 append_domain(interface, domain);
911                 return 0;
912         }
913
914         data = create_server(interface, domain, server, IPPROTO_UDP);
915         if (data == NULL)
916                 return -EIO;
917
918         return 0;
919 }
920
921 static void remove_server(const char *interface, const char *domain,
922                         const char *server, int protocol)
923 {
924         struct server_data *data;
925
926         data = find_server(interface, server, protocol);
927         if (data == NULL)
928                 return;
929
930         destroy_server(data);
931 }
932
933 int __connman_dnsproxy_remove(const char *interface, const char *domain,
934                                                         const char *server)
935 {
936         DBG("interface %s server %s", interface, server);
937
938         if (server == NULL)
939                 return -EINVAL;
940
941         if (g_str_equal(server, "127.0.0.1") == TRUE)
942                 return -ENODEV;
943
944         remove_server(interface, domain, server, IPPROTO_UDP);
945         remove_server(interface, domain, server, IPPROTO_TCP);
946
947         return 0;
948 }
949
950 void __connman_dnsproxy_flush(void)
951 {
952         GSList *list;
953
954         list = request_pending_list;
955         while (list) {
956                 struct request_data *req = list->data;
957
958                 list = list->next;
959
960                 request_pending_list =
961                                 g_slist_remove(request_pending_list, req);
962                 resolv(req, req->request, req->name);
963                 g_free(req->request);
964                 g_free(req->name);
965         }
966 }
967
968 static void dnsproxy_offline_mode(connman_bool_t enabled)
969 {
970         GSList *list;
971
972         DBG("enabled %d", enabled);
973
974         for (list = server_list; list; list = list->next) {
975                 struct server_data *data = list->data;
976
977                 if (enabled == FALSE) {
978                         connman_info("Enabling DNS server %s", data->server);
979                         data->enabled = TRUE;
980                 } else {
981                         connman_info("Disabling DNS server %s", data->server);
982                         data->enabled = FALSE;
983                 }
984         }
985 }
986
987 static void dnsproxy_default_changed(struct connman_service *service)
988 {
989         GSList *list;
990         char *interface;
991
992         DBG("service %p", service);
993
994         if (service == NULL) {
995                 /* When no services are active, then disable DNS proxying */
996                 dnsproxy_offline_mode(TRUE);
997                 return;
998         }
999
1000         interface = connman_service_get_interface(service);
1001         if (interface == NULL)
1002                 return;
1003
1004         for (list = server_list; list; list = list->next) {
1005                 struct server_data *data = list->data;
1006
1007                 if (g_strcmp0(data->interface, interface) == 0) {
1008                         connman_info("Enabling DNS server %s", data->server);
1009                         data->enabled = TRUE;
1010                 } else {
1011                         connman_info("Disabling DNS server %s", data->server);
1012                         data->enabled = FALSE;
1013                 }
1014         }
1015
1016         g_free(interface);
1017 }
1018
1019 static struct connman_notifier dnsproxy_notifier = {
1020         .name                   = "dnsproxy",
1021         .default_changed        = dnsproxy_default_changed,
1022         .offline_mode           = dnsproxy_offline_mode,
1023 };
1024
1025 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
1026
1027 static int parse_request(unsigned char *buf, int len,
1028                                         char *name, unsigned int size)
1029 {
1030         struct domain_hdr *hdr = (void *) buf;
1031         uint16_t qdcount = ntohs(hdr->qdcount);
1032         uint16_t arcount = ntohs(hdr->arcount);
1033         unsigned char *ptr;
1034         char *last_label = NULL;
1035         unsigned int remain, used = 0;
1036
1037         if (len < 12)
1038                 return -EINVAL;
1039
1040         DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
1041                                         hdr->id, hdr->qr, hdr->opcode,
1042                                                         qdcount, arcount);
1043
1044         if (hdr->qr != 0 || qdcount != 1)
1045                 return -EINVAL;
1046
1047         memset(name, 0, size);
1048
1049         ptr = buf + sizeof(struct domain_hdr);
1050         remain = len - sizeof(struct domain_hdr);
1051
1052         while (remain > 0) {
1053                 uint8_t len = *ptr;
1054
1055                 if (len == 0x00) {
1056                         last_label = (char *) (ptr + 1);
1057                         break;
1058                 }
1059
1060                 if (used + len + 1 > size)
1061                         return -ENOBUFS;
1062
1063                 strncat(name, (char *) (ptr + 1), len);
1064                 strcat(name, ".");
1065
1066                 used += len + 1;
1067
1068                 ptr += len + 1;
1069                 remain -= len + 1;
1070         }
1071
1072         if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
1073                                 !memcmp(last_label + 5, opt_edns0_type, 2)) {
1074                 uint16_t edns0_bufsize;
1075
1076                 edns0_bufsize = last_label[7] << 8 | last_label[8];
1077
1078                 DBG("EDNS0 buffer size %u", edns0_bufsize);
1079
1080                 /* This is an evil hack until full TCP support has been
1081                  * implemented.
1082                  *
1083                  * Somtimes the EDNS0 request gets send with a too-small
1084                  * buffer size. Since glibc doesn't seem to crash when it
1085                  * gets a response biffer then it requested, just bump
1086                  * the buffer size up to 4KiB.
1087                  */
1088                 if (edns0_bufsize < 0x1000) {
1089                         last_label[7] = 0x10;
1090                         last_label[8] = 0x00;
1091                 }
1092         }
1093
1094         DBG("query %s", name);
1095
1096         return 0;
1097 }
1098
1099 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
1100                                                         gpointer user_data)
1101 {
1102         unsigned char buf[768];
1103         char query[512];
1104         struct request_data *req;
1105         struct server_data *server;
1106         int sk, client_sk, len, err;
1107         struct sockaddr_in6 client_addr;
1108         socklen_t client_addr_len = sizeof(client_addr);
1109         GSList *list;
1110         struct listener_data *ifdata = user_data;
1111
1112         DBG("condition 0x%x", condition);
1113
1114         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1115                 if (ifdata->tcp_listener_watch > 0)
1116                         g_source_remove(ifdata->tcp_listener_watch);
1117                 ifdata->tcp_listener_watch = 0;
1118
1119                 connman_error("Error with TCP listener channel");
1120
1121                 return FALSE;
1122         }
1123
1124         sk = g_io_channel_unix_get_fd(channel);
1125
1126         client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
1127         if (client_sk < 0) {
1128                 connman_error("Accept failure on TCP listener");
1129                 ifdata->tcp_listener_watch = 0;
1130                 return FALSE;
1131         }
1132
1133         len = recv(client_sk, buf, sizeof(buf), 0);
1134         if (len < 2)
1135                 return TRUE;
1136
1137         DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
1138
1139         err = parse_request(buf + 2, len - 2, query, sizeof(query));
1140         if (err < 0 || (g_slist_length(server_list) == 0)) {
1141                 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
1142                 return TRUE;
1143         }
1144
1145         req = g_try_new0(struct request_data, 1);
1146         if (req == NULL)
1147                 return TRUE;
1148
1149         memcpy(&req->sa, &client_addr, client_addr_len);
1150         req->sa_len = client_addr_len;
1151         req->client_sk = client_sk;
1152         req->protocol = IPPROTO_TCP;
1153
1154         request_id += 2;
1155         if (request_id == 0x0000 || request_id == 0xffff)
1156                 request_id += 2;
1157
1158         req->srcid = buf[2] | (buf[3] << 8);
1159         req->dstid = request_id;
1160         req->altid = request_id + 1;
1161         req->request_len = len;
1162
1163         buf[2] = req->dstid & 0xff;
1164         buf[3] = req->dstid >> 8;
1165
1166         req->numserv = 0;
1167         req->ifdata = (struct listener_data *) ifdata;
1168         request_list = g_slist_append(request_list, req);
1169
1170         for (list = server_list; list; list = list->next) {
1171                 struct server_data *data = list->data;
1172                 GList *domains;
1173
1174                 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
1175                         continue;
1176
1177                 server = create_server(data->interface, NULL,
1178                                         data->server, IPPROTO_TCP);
1179
1180                 /*
1181                  * If server is NULL, we're not connected yet.
1182                  * Copy the relevant buffers and continue with
1183                  * the next nameserver.
1184                  * The request will actually be sent once we're
1185                  * properly connected over TCP to this nameserver.
1186                  */
1187                 if (server == NULL) {
1188                         req->request = g_try_malloc0(req->request_len);
1189                         if (req->request == NULL)
1190                                 return TRUE;
1191
1192                         memcpy(req->request, buf, req->request_len);
1193
1194                         req->name = g_try_malloc0(sizeof(query));
1195                         if (req->name == NULL) {
1196                                 g_free(req->request);
1197                                 return TRUE;
1198                         }
1199                         memcpy(req->name, query, sizeof(query));
1200
1201                         continue;
1202                 }
1203
1204                 if (req->timeout > 0)
1205                         g_source_remove(req->timeout);
1206
1207                 for (domains = data->domains; domains;
1208                                 domains = domains->next) {
1209                         char *dom = domains->data;
1210
1211                         DBG("Adding domain %s to %s", dom, server->server);
1212
1213                         server->domains = g_list_append(server->domains,
1214                                                 g_strdup(dom));
1215                 }
1216
1217                 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
1218                 ns_resolv(server, req, buf, query);
1219         }
1220
1221         return TRUE;
1222 }
1223
1224 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
1225                                                         gpointer user_data)
1226 {
1227         unsigned char buf[768];
1228         char query[512];
1229         struct request_data *req;
1230         struct sockaddr_in6 client_addr;
1231         socklen_t client_addr_len = sizeof(client_addr);
1232         int sk, err, len;
1233         struct listener_data *ifdata = user_data;
1234
1235         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1236                 connman_error("Error with UDP listener channel");
1237                 ifdata->udp_listener_watch = 0;
1238                 return FALSE;
1239         }
1240
1241         sk = g_io_channel_unix_get_fd(channel);
1242
1243         memset(&client_addr, 0, client_addr_len);
1244         len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
1245                        &client_addr_len);
1246         if (len < 2)
1247                 return TRUE;
1248
1249         DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
1250
1251         err = parse_request(buf, len, query, sizeof(query));
1252         if (err < 0 || (g_slist_length(server_list) == 0)) {
1253                 send_response(sk, buf, len, (void *)&client_addr,
1254                               client_addr_len, IPPROTO_UDP);
1255                 return TRUE;
1256         }
1257
1258         req = g_try_new0(struct request_data, 1);
1259         if (req == NULL)
1260                 return TRUE;
1261
1262         memcpy(&req->sa, &client_addr, client_addr_len);
1263         req->sa_len = client_addr_len;
1264         req->client_sk = 0;
1265         req->protocol = IPPROTO_UDP;
1266
1267         request_id += 2;
1268         if (request_id == 0x0000 || request_id == 0xffff)
1269                 request_id += 2;
1270
1271         req->srcid = buf[0] | (buf[1] << 8);
1272         req->dstid = request_id;
1273         req->altid = request_id + 1;
1274         req->request_len = len;
1275
1276         buf[0] = req->dstid & 0xff;
1277         buf[1] = req->dstid >> 8;
1278
1279         req->numserv = 0;
1280         req->ifdata = (struct listener_data *) ifdata;
1281         req->timeout = g_timeout_add_seconds(5, request_timeout, req);
1282         request_list = g_slist_append(request_list, req);
1283
1284         return resolv(req, buf, query);
1285 }
1286
1287 static int create_dns_listener(int protocol, const char *ifname)
1288 {
1289         GIOChannel *channel;
1290         const char *proto;
1291         union {
1292                 struct sockaddr sa;
1293                 struct sockaddr_in6 sin6;
1294                 struct sockaddr_in sin;
1295         } s;
1296         socklen_t slen;
1297         int sk, type, v6only = 0;
1298         int family = AF_INET6;
1299         struct listener_data *ifdata;
1300
1301         DBG("interface %s", ifname);
1302
1303         ifdata = g_hash_table_lookup(listener_table, ifname);
1304         if (ifdata == NULL)
1305                 return -ENODEV;
1306
1307         switch (protocol) {
1308         case IPPROTO_UDP:
1309                 proto = "UDP";
1310                 type = SOCK_DGRAM;
1311                 break;
1312
1313         case IPPROTO_TCP:
1314                 proto = "TCP";
1315                 type = SOCK_STREAM;
1316                 break;
1317
1318         default:
1319                 return -EINVAL;
1320         }
1321
1322         sk = socket(family, type, protocol);
1323         if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
1324                 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
1325                 family = AF_INET;
1326                 sk = socket(family, type, protocol);
1327         }
1328         if (sk < 0) {
1329                 connman_error("Failed to create %s listener socket", proto);
1330                 return -EIO;
1331         }
1332
1333         if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1334                                         ifname, strlen(ifname) + 1) < 0) {
1335                 connman_error("Failed to bind %s listener interface", proto);
1336                 close(sk);
1337                 return -EIO;
1338         }
1339         /* Ensure it accepts Legacy IP connections too */
1340         if (family == AF_INET6 &&
1341                         setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
1342                                         &v6only, sizeof(v6only)) < 0) {
1343                 connman_error("Failed to clear V6ONLY on %s listener socket",
1344                               proto);
1345                 close(sk);
1346                 return -EIO;
1347         }
1348
1349         if (family == AF_INET) {
1350                 memset(&s.sin, 0, sizeof(s.sin));
1351                 s.sin.sin_family = AF_INET;
1352                 s.sin.sin_port = htons(53);
1353                 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
1354                 slen = sizeof(s.sin);
1355         } else {
1356                 memset(&s.sin6, 0, sizeof(s.sin6));
1357                 s.sin6.sin6_family = AF_INET6;
1358                 s.sin6.sin6_port = htons(53);
1359                 s.sin6.sin6_addr = in6addr_any;
1360                 slen = sizeof(s.sin6);
1361         }
1362
1363         if (bind(sk, &s.sa, slen) < 0) {
1364                 connman_error("Failed to bind %s listener socket", proto);
1365                 close(sk);
1366                 return -EIO;
1367         }
1368
1369         if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
1370                 connman_error("Failed to listen on TCP socket");
1371                 close(sk);
1372                 return -EIO;
1373         }
1374
1375         channel = g_io_channel_unix_new(sk);
1376         if (channel == NULL) {
1377                 connman_error("Failed to create %s listener channel", proto);
1378                 close(sk);
1379                 return -EIO;
1380         }
1381
1382         g_io_channel_set_close_on_unref(channel, TRUE);
1383
1384         if (protocol == IPPROTO_TCP) {
1385                 ifdata->tcp_listener_channel = channel;
1386                 ifdata->tcp_listener_watch = g_io_add_watch(channel,
1387                                 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
1388         } else {
1389                 ifdata->udp_listener_channel = channel;
1390                 ifdata->udp_listener_watch = g_io_add_watch(channel,
1391                                 G_IO_IN, udp_listener_event, (gpointer) ifdata);
1392         }
1393
1394         return 0;
1395 }
1396
1397 static void destroy_udp_listener(const char *interface)
1398 {
1399         struct listener_data *ifdata;
1400
1401         DBG("interface %s", interface);
1402
1403         ifdata = g_hash_table_lookup(listener_table, interface);
1404         if (ifdata == NULL)
1405                 return;
1406
1407         if (ifdata->udp_listener_watch > 0)
1408                 g_source_remove(ifdata->udp_listener_watch);
1409
1410         g_io_channel_unref(ifdata->udp_listener_channel);
1411 }
1412
1413 static void destroy_tcp_listener(const char *interface)
1414 {
1415         struct listener_data *ifdata;
1416
1417         DBG("interface %s", interface);
1418
1419         ifdata = g_hash_table_lookup(listener_table, interface);
1420         if (ifdata == NULL)
1421                 return;
1422
1423         if (ifdata->tcp_listener_watch > 0)
1424                 g_source_remove(ifdata->tcp_listener_watch);
1425
1426         g_io_channel_unref(ifdata->tcp_listener_channel);
1427 }
1428
1429 static int create_listener(const char *interface)
1430 {
1431         int err;
1432
1433         err = create_dns_listener(IPPROTO_UDP, interface);
1434         if (err < 0)
1435                 return err;
1436
1437         err = create_dns_listener(IPPROTO_TCP, interface);
1438         if (err < 0) {
1439                 destroy_udp_listener(interface);
1440                 return err;
1441         }
1442
1443         if (g_strcmp0(interface, "lo") == 0)
1444                 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
1445
1446         return 0;
1447 }
1448
1449 static void destroy_listener(const char *interface)
1450 {
1451         GSList *list;
1452
1453         if (interface == NULL)
1454                 return;
1455
1456         if (g_strcmp0(interface, "lo") == 0)
1457                 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
1458
1459         for (list = request_pending_list; list; list = list->next) {
1460                 struct request_data *req = list->data;
1461
1462                 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
1463                                                 req->srcid, req->dstid);
1464
1465                 g_free(req->resp);
1466                 g_free(req->request);
1467                 g_free(req->name);
1468                 g_free(req);
1469                 list->data = NULL;
1470         }
1471
1472         g_slist_free(request_pending_list);
1473         request_pending_list = NULL;
1474
1475         for (list = request_list; list; list = list->next) {
1476                 struct request_data *req = list->data;
1477
1478                 DBG("Dropping request (id 0x%04x -> 0x%04x)",
1479                                                 req->srcid, req->dstid);
1480
1481                 g_free(req->resp);
1482                 g_free(req->request);
1483                 g_free(req->name);
1484                 g_free(req);
1485                 list->data = NULL;
1486         }
1487
1488         g_slist_free(request_list);
1489         request_list = NULL;
1490
1491         destroy_tcp_listener(interface);
1492         destroy_udp_listener(interface);
1493 }
1494
1495 int __connman_dnsproxy_add_listener(const char *interface)
1496 {
1497         struct listener_data *ifdata;
1498         int err;
1499
1500         DBG("interface %s", interface);
1501
1502         if (g_hash_table_lookup(listener_table, interface) != NULL)
1503                 return 0;
1504
1505         ifdata = g_try_new0(struct listener_data, 1);
1506         if (ifdata == NULL)
1507                 return -ENOMEM;
1508
1509         ifdata->ifname = g_strdup(interface);
1510         ifdata->udp_listener_channel = NULL;
1511         ifdata->udp_listener_watch = 0;
1512         ifdata->tcp_listener_channel = NULL;
1513         ifdata->tcp_listener_watch = 0;
1514         g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
1515
1516         err = create_listener(interface);
1517         if (err < 0)
1518                 return err;
1519         return 0;
1520 }
1521
1522 void __connman_dnsproxy_remove_listener(const char *interface)
1523 {
1524         DBG("interface %s", interface);
1525
1526         destroy_listener(interface);
1527
1528         g_hash_table_remove(listener_table, interface);
1529 }
1530
1531 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
1532 {
1533         __connman_dnsproxy_remove_listener(key);
1534 }
1535
1536 int __connman_dnsproxy_init(void)
1537 {
1538         int err;
1539
1540         DBG("");
1541
1542         listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
1543                                                         g_free, g_free);
1544         err = __connman_dnsproxy_add_listener("lo");
1545         if (err < 0)
1546                 return err;
1547
1548         err = connman_notifier_register(&dnsproxy_notifier);
1549         if (err < 0)
1550                 goto destroy;
1551
1552         return 0;
1553
1554 destroy:
1555         __connman_dnsproxy_remove_listener("lo");
1556         g_hash_table_destroy(listener_table);
1557
1558         return err;
1559 }
1560
1561 void __connman_dnsproxy_cleanup(void)
1562 {
1563         DBG("");
1564
1565         connman_notifier_unregister(&dnsproxy_notifier);
1566
1567         g_hash_table_foreach(listener_table, remove_listener, NULL);
1568
1569         g_hash_table_destroy(listener_table);
1570 }