fd9b23fd5e844ba395716c2065593ab6d93e61d6
[oweals/gnunet.git] / src / gns / gnunet-service-gns.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file gns/gnunet-service-gns.c
23  * @brief GNUnet GNS service
24  * @author Martin Schanzenbach
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_transport_service.h"
29 #include "gnunet_dns_service.h"
30 #include "gnunet_dnsparser_lib.h"
31 #include "gnunet_namestore_service.h"
32 #include "gnunet_gns_service.h"
33 #include "gns.h"
34
35
36 /* TODO into gnunet_protocols */
37 #define GNUNET_MESSAGE_TYPE_GNS_CLIENT_LOOKUP 23
38 #define GNUNET_MESSAGE_TYPE_GNS_CLIENT_RESULT 24
39
40 struct GNUNET_GNS_QueryRecordList
41 {
42   /**
43    * DLL
44    */
45   struct GNUNET_GNS_QueryRecordList * next;
46   struct GNUNET_GNS_QueryRecordList * prev;
47
48   struct GNUNET_DNSPARSER_Record * record;
49 };
50
51 /**
52  * A result list for namestore queries
53  */
54 struct GNUNET_GNS_PendingQuery
55 {
56   /* the answer packet */
57   struct GNUNET_DNSPARSER_Packet *answer;
58
59   /* records to put into answer packet */
60   struct GNUNET_GNS_QueryRecordList * records_head;
61   struct GNUNET_GNS_QueryRecordList * records_tail;
62
63   int num_records;
64   int num_authority_records; //FIXME are all of our replies auth?
65   
66   char *name;
67   uint16_t type;
68   /* the dns request id */
69   int id; // FIXME can handle->request_id also be used here?
70
71   /* the request handle to reply to */
72   struct GNUNET_DNS_RequestHandle *request_handle;
73
74   /* hast this query been answered? */
75   int answered;
76 };
77
78
79 /**
80  * Our handle to the DNS handler library
81  */
82 struct GNUNET_DNS_Handle *dns_handle;
83 struct GNUNET_DNS_Handle *dns_res_handle;
84
85 /**
86  * Our handle to the namestore service
87  */
88 struct GNUNET_NAMESTORE_Handle *namestore_handle;
89
90 /**
91  * The configuration the GNS service is running with
92  */
93 const struct GNUNET_CONFIGURATION_Handle *GNS_cfg;
94
95 /**
96  * Our notification context.
97  */
98 static struct GNUNET_SERVER_NotificationContext *nc;
99
100 /**
101  * Our zone hash
102  */
103 const GNUNET_HashCode *my_zone;
104
105 /**
106  * Task run during shutdown.
107  *
108  * @param cls unused
109  * @param tc unused
110  */
111 static void
112 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
113 {
114   GNUNET_DNS_disconnect(dns_handle);
115   GNUNET_NAMESTORE_disconnect(namestore_handle, 0);
116 }
117
118 /**
119  * Phase 2 of resolution.
120  */
121 void
122 lookup_dht()
123 {
124 }
125
126 void
127 reply_to_dns(struct GNUNET_GNS_PendingQuery *answer)
128 {
129   struct GNUNET_GNS_QueryRecordList *i;
130   struct GNUNET_DNSPARSER_Packet *packet;
131   struct GNUNET_DNSPARSER_Flags dnsflags;
132   int j;
133   size_t len;
134   int ret;
135   char *buf;
136   
137   packet = GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Packet));
138   packet->answers =
139     GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Record) * answer->num_records);
140   
141   len = sizeof(struct GNUNET_DNSPARSER_Record*);
142   j = 0;
143   for (i=answer->records_head; i != NULL; i=i->next)
144   {
145     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
146                "Adding %s to DNS response\n", i->record->name);
147     memcpy(&packet->answers[j], 
148            i->record,
149            sizeof (struct GNUNET_DNSPARSER_Record));
150     GNUNET_free(i->record);
151     j++;
152   }
153   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "after memcpy\n");
154   /* FIXME how to handle auth, additional etc */
155   packet->num_answers = answer->num_records;
156   packet->num_authority_records = answer->num_authority_records;
157
158   dnsflags.authoritative_answer = 1;
159   dnsflags.opcode = GNUNET_DNSPARSER_OPCODE_QUERY;
160   dnsflags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NO_ERROR; //not sure
161   dnsflags.query_or_response = 1;
162   packet->flags = dnsflags;
163
164   packet->id = answer->id;
165   ret = GNUNET_DNSPARSER_pack (packet,
166                                1024, /* FIXME magic from dns redirector */
167                                &buf,
168                                &len);
169   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
170              "Built DNS response! (ret=%d)\n", ret);
171   if (ret == GNUNET_OK)
172   {
173     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
174                "Answering DNS request\n");
175     GNUNET_DNS_request_answer(answer->request_handle,
176                               len,
177                               buf);
178     GNUNET_free(answer);
179     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Answered DNS request\n");
180     //FIXME return code, free datastructures
181   }
182   else
183   {
184     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
185                "Error building DNS response! (ret=%d)", ret);
186   }
187 }
188
189 static void
190 process_ns_result(void* cls, const GNUNET_HashCode *zone,
191                   const char *name, uint32_t record_type,
192                   struct GNUNET_TIME_Absolute expiration,
193                   enum GNUNET_NAMESTORE_RecordFlags flags,
194                   const struct GNUNET_NAMESTORE_SignatureLocation *sig_loc,
195                   size_t size, const void *data)
196 {
197   struct GNUNET_GNS_PendingQuery *query;
198   struct GNUNET_GNS_QueryRecordList *qrecord;
199   struct GNUNET_DNSPARSER_Record *record;
200   query = (struct GNUNET_GNS_PendingQuery *) cls;
201   char bufA[INET6_ADDRSTRLEN];
202
203
204   if (NULL == data)
205   {
206     /**
207      * Last result received (or none)
208      * Do we have what we need to answer?
209      * If not -> DHT Phase
210      * FIXME free memory
211      */
212     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
213                "Namestore lookup terminated. (answered=%d)", query->answered);
214
215     if (query->answered)
216       reply_to_dns(query);
217     else
218       lookup_dht(); //TODO
219
220   }
221   else
222   {
223     /**
224      * New result
225      */
226     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
227                "Processing additional result %s from namestore\n", name);
228
229     qrecord = GNUNET_malloc(sizeof(struct GNUNET_GNS_QueryRecordList));
230     record = GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Record));
231     qrecord->record = record;
232
233     record->name = (char*)name;
234     /* FIXME for gns records this requires the dnsparser to be modified!
235      * or use RAW
236      * */
237     if (record_type == GNUNET_DNSPARSER_TYPE_A)
238     {
239       GNUNET_log(GNUNET_ERROR_TYPE_INFO, "A record: %s\n", data);
240       record->data.raw.data = GNUNET_malloc(sizeof (struct in_addr));
241       GNUNET_assert(1 == inet_pton (AF_INET, data,
242                                     record->data.raw.data));
243       record->data.raw.data_len = sizeof (struct in_addr);
244     }
245     record->expiration_time = expiration;
246     record->type = record_type;
247     record->class = GNUNET_DNSPARSER_CLASS_INTERNET; /* srsly? */
248
249     if (flags == GNUNET_NAMESTORE_RF_AUTHORITY)
250     {
251       //query->num_authority_records++;
252     }
253
254     if ((0 == strcmp(query->name , name)) &&
255         (query->type == record_type))
256     {
257       GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Found answer to query!\n");
258       query->answered = 1;
259     }
260
261     query->num_records++;
262
263     //FIXME watch for leaks
264     GNUNET_CONTAINER_DLL_insert(query->records_head,
265                                 query->records_tail,
266                                 qrecord);
267   }
268 }
269
270
271 void
272 handle_dns_response(void *cls,
273                    struct GNUNET_DNS_RequestHandle *rh,
274                    size_t request_length,
275                    const char *request)
276 {
277   GNUNET_DNS_request_forward (rh);
278 }
279
280
281 /**
282  * Phase 1 of name resolution: Lookup local namestore
283  *
284  * @param name the name to look up
285  * @param id the id of the dns request (for the reply)
286  * @param type the record type to look for
287  */
288 void
289 lookup_namestore(struct GNUNET_DNS_RequestHandle *rh, char* name, uint16_t id, uint16_t type)
290 {
291   struct GNUNET_GNS_PendingQuery *answer;
292   
293   /**
294    * Do db lookup here. Make dht lookup if necessary 
295    * FIXME for now only local lookups for our zone!
296    */
297   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "This is .gnunet (%s)!\n", name);
298   answer = GNUNET_malloc(sizeof (struct GNUNET_GNS_PendingQuery));
299   answer->id = id;
300   answer->name = name;
301   answer->type =type;
302   answer->request_handle = rh;
303   
304   GNUNET_NAMESTORE_lookup_name(namestore_handle,
305                                my_zone,
306                                name,
307                                type,
308                                &process_ns_result,
309                                answer);
310 }
311
312 /**
313  * The DNS request handler
314  *
315  * @param cls closure
316  * @param rh request handle to user for reply
317  * @param request_length number of bytes in request
318  * @param request udp payload of the DNS request
319  */
320 void
321 handle_dns_request(void *cls,
322                    struct GNUNET_DNS_RequestHandle *rh,
323                    size_t request_length,
324                    const char *request)
325 {
326   /**
327    * parse request for tld
328    */
329   struct GNUNET_DNSPARSER_Packet *p;
330   int namelen;
331   int i;
332   char *tail;
333
334   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "hijacked a request...processing\n");
335   p = GNUNET_DNSPARSER_parse (request, request_length);
336   
337   if (NULL == p)
338   {
339     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
340                 "Received malformed DNS packet, leaving it untouched\n");
341     GNUNET_DNS_request_forward (rh);
342     return;
343   }
344   
345   /**
346    * Check tld and decide if we or
347    * legacy dns is responsible
348    */
349   for (i=0;i<p->num_queries;i++)
350   {
351     namelen = strlen(p->queries[i].name);
352     
353     if (namelen < 7) /* this can't be .gnunet */
354       continue;
355     /**
356      * FIXME off by 1?
357      * Move our tld/root to config file
358      * Generate fake DNS reply that replaces .gnunet with .org for testing?
359      */
360     tail = p->queries[i].name+(namelen-7);
361     if (0 == strcmp(tail, ".gnunet"))
362     {
363       /* FIXME we need to answer to ALL queries in ONE response...
364        * Like this we only answer one...
365        */
366       lookup_namestore(rh, p->queries[i].name, p->id, p->queries[i].type);
367     }
368     else
369     {
370       /**
371        * This request does not concern us. Forward to real DNS.
372        */
373       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
374                  "Request for %s is forwarded to DNS\n", p->queries[i].name);
375       GNUNET_DNS_request_forward (rh);
376     }
377   }
378 }
379
380 /*TODO*/
381 static void
382 handle_client_record_lookup(void *cls,
383                             struct GNUNET_SERVER_Client *client,
384                             const struct GNUNET_MessageHeader *message)
385 {
386 }
387
388 /**
389  * test function
390  */
391 void
392 put_some_records(void)
393 {
394   /* put a few records into namestore */
395   char* ipA = "1.2.3.4";
396   char* ipB = "5.6.7.8";
397   GNUNET_NAMESTORE_record_put (namestore_handle,
398                                my_zone,
399                                "alice.gnunet",
400                                GNUNET_GNS_RECORD_TYPE_A,
401                                GNUNET_TIME_absolute_get_forever(),
402                                GNUNET_NAMESTORE_RF_AUTHORITY,
403                                NULL, //sig loc
404                                strlen (ipA),
405                                ipA,
406                                NULL,
407                                NULL);
408   GNUNET_NAMESTORE_record_put (namestore_handle,
409                                my_zone,
410                                "bob.gnunet",
411                                GNUNET_GNS_RECORD_TYPE_A,
412                                GNUNET_TIME_absolute_get_forever(),
413                                GNUNET_NAMESTORE_RF_AUTHORITY,
414                                NULL, //sig loc
415                                strlen (ipB),
416                                ipB,
417                                NULL,
418                                NULL);
419 }
420
421 /**
422  * Process GNS requests.
423  *
424  * @param cls closure
425  * @param server the initialized server
426  * @param c configuration to use
427  */
428 static void
429 run (void *cls, struct GNUNET_SERVER_Handle *server,
430      const struct GNUNET_CONFIGURATION_Handle *c)
431 {
432   /* The IPC message types */
433   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
434     /* callback, cls, type, size */
435     {&handle_client_record_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_CLIENT_LOOKUP,
436       0},
437     {NULL, NULL, 0, 0}
438   };
439   
440   nc = GNUNET_SERVER_notification_context_create (server, 1);
441
442   /* FIXME - do some config parsing 
443    *       - Maybe only hijack dns if option is set (HIJACK_DNS=1)
444    */
445
446   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
447                                 NULL);
448   /**
449    * Do gnunet dns init here
450    */
451   dns_handle = GNUNET_DNS_connect(c,
452                                   GNUNET_DNS_FLAG_PRE_RESOLUTION,
453                                   &handle_dns_request, /* rh */
454                                   NULL); /* Closure */
455   
456   dns_res_handle = GNUNET_DNS_connect(c,
457                                       GNUNET_DNS_FLAG_PRE_RESOLUTION,
458                                       &handle_dns_response, /* rh */
459                                       NULL); /* Closure */
460
461   if (NULL == dns_handle)
462   {
463     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
464                "Failed to connect to the dnsservice!\n");
465   }
466
467   /**
468    * handle to our local namestore
469    */
470   namestore_handle = GNUNET_NAMESTORE_connect(c);
471
472   if (NULL == namestore_handle)
473   {
474     //FIXME do error handling;
475     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
476                "Failed to connect to the namestore!\n");
477   }
478
479   put_some_records();
480
481   GNUNET_SERVER_add_handlers (server, handlers);
482   /**
483    * Esp the lookup would require to keep track of the clients' context
484    * See dht.
485    * GNUNET_SERVER_disconnect_notify (server, &client_disconnect, NULL);
486    **/
487 }
488
489
490 /**
491  * The main function for the GNS service.
492  *
493  * @param argc number of arguments from the command line
494  * @param argv command line arguments
495  * @return 0 ok, 1 on error
496  */
497 int
498 main (int argc, char *const *argv)
499 {
500   int ret;
501
502   ret =
503       (GNUNET_OK ==
504        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
505                            NULL)) ? 0 : 1;
506   return ret;
507 }
508
509 /* end of gnunet-service-gns.c */