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