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