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