2 This file is part of GNUnet.
3 (C) 2012-2013 Christian Grothoff (and other contributing authors)
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.
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.
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.
21 * @file gnunet-namestore-fcfsd.c
22 * @brief HTTP daemon that offers first-come-first-serve GNS domain registration
23 * @author Christian Grothoff
26 * - need to track active zone info requests so we can cancel them
27 * during shutdown, right?
28 * - the code currently contains a 'race' between checking that the
29 * domain name is available and allocating it to the new public key
30 * (should this race be solved by namestore or by fcfsd?)
31 * - nicer error reporting to browser
34 #include <microhttpd.h>
35 #include "gnunet_util_lib.h"
36 #include "gnunet_identity_service.h"
37 #include "gnunet_gnsrecord_lib.h"
38 #include "gnunet_namestore_service.h"
41 * Invalid method page.
43 #define METHOD_ERROR "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"><html><head><title>Illegal request</title></head><body>Go away.</body></html>"
48 #define MAIN_PAGE "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"><html><head><title>GNUnet FCFS Authority Name Registration Service</title></head><body><form action=\"S\" method=\"post\">What is your desired domain name? (at most 63 lowercase characters, no dots allowed.) <input type=\"text\" name=\"domain\" /> <p> What is your public key? (Copy from gnunet-setup.) <input type=\"text\" name=\"pkey\" /> <input type=\"submit\" value=\"Next\" /><br/><a href=./Zoneinfo> List of all registered names </a></body></html>"
53 #define SUBMIT_PAGE "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"><html><head><title>%s</title></head><body>%s</body></html>"
56 * Fcfs zoneinfo page (/Zoneinfo)
58 #define ZONEINFO_PAGE "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"><html><head><title>FCFS Zoneinfo</title></head><body><h1> FCFS Zoneinfo </h1><table border=\"1\"><th>name</th><th>PKEY</th>%s</table></body></html>"
60 #define FCFS_ZONEINFO_URL "/Zoneinfo"
63 * Mime type for HTML pages.
65 #define MIME_HTML "text/html"
70 #define COOKIE_NAME "namestore-fcfsd"
72 #define DEFAULT_ZONEINFO_BUFSIZE 2048
75 * Phases a request goes through.
80 * Start phase (parsing POST, checking).
85 * Lookup to see if the domain name is taken.
90 * Storing of the record.
95 * We're done with success.
100 * Send failure message.
107 * Data kept per request.
113 * Associated session.
115 struct Session *session;
118 * Post processor handling form data (IF this is
121 struct MHD_PostProcessor *pp;
124 * URL to serve in response to this POST (if this request
127 const char *post_url;
130 * Active request with the namestore.
132 struct GNUNET_NAMESTORE_QueueEntry *qe;
135 * Active iteration with the namestore.
137 struct GNUNET_NAMESTORE_ZoneIterator *zi;
140 * Current processing phase.
145 * Domain name submitted via form.
147 char domain_name[64];
150 * Public key submitted via form.
152 char public_key[128];
159 struct ZoneinfoRequest
164 struct MHD_Connection *connection;
169 struct GNUNET_NAMESTORE_ZoneIterator *list_it;
182 * Buffer write offset
188 * MHD deamon reference.
190 static struct MHD_Daemon *httpd;
195 static GNUNET_SCHEDULER_TaskIdentifier httpd_task;
198 * Handle to the namestore.
200 static struct GNUNET_NAMESTORE_Handle *ns;
203 * Private key for the fcfsd zone.
205 static struct GNUNET_CRYPTO_EcdsaPrivateKey fcfs_zone_pkey;
208 * Connection to identity service.
210 static struct GNUNET_IDENTITY_Handle *identity;
213 * Request for our ego.
215 static struct GNUNET_IDENTITY_Operation *id_op;
218 * Port we use for the HTTP server.
220 static unsigned long long port;
224 * Task run whenever HTTP server operations are pending.
227 * @param tc scheduler context
231 const struct GNUNET_SCHEDULER_TaskContext *tc);
235 * Schedule task to run MHD server now.
240 if (GNUNET_SCHEDULER_NO_TASK != httpd_task)
242 GNUNET_SCHEDULER_cancel (httpd_task);
243 httpd_task = GNUNET_SCHEDULER_NO_TASK;
245 httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd, NULL);
250 iterate_cb (void *cls,
251 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
254 const struct GNUNET_GNSRECORD_Data *rd)
256 struct ZoneinfoRequest *zr = cls;
257 struct MHD_Response *response;
268 /* return static form */
269 GNUNET_asprintf (&full_page,
273 response = MHD_create_response_from_buffer (strlen (full_page),
275 MHD_RESPMEM_MUST_FREE);
276 MHD_add_response_header (response,
277 MHD_HTTP_HEADER_CONTENT_TYPE,
279 MHD_queue_response (zr->connection,
282 MHD_destroy_response (response);
283 GNUNET_free (zr->zoneinfo);
291 GNUNET_NAMESTORE_zone_iterator_next (zr->list_it);
295 if (GNUNET_GNSRECORD_TYPE_PKEY != rd->record_type)
297 GNUNET_NAMESTORE_zone_iterator_next (zr->list_it);
301 bytes_free = zr->buf_len - zr->write_offset;
302 pkey = GNUNET_GNSRECORD_value_to_string (rd->record_type,
306 if (bytes_free < (strlen (name) + strlen (pkey) + 40))
308 new_buf = GNUNET_malloc (zr->buf_len * 2);
309 memcpy (new_buf, zr->zoneinfo, zr->write_offset);
310 GNUNET_free (zr->zoneinfo);
311 zr->zoneinfo = new_buf;
314 sprintf (zr->zoneinfo + zr->write_offset,
315 "<tr><td>%s</td><td>%s</td></tr>",
318 zr->write_offset = strlen (zr->zoneinfo);
319 GNUNET_NAMESTORE_zone_iterator_next (zr->list_it);
326 * Handler that returns FCFS zoneinfo page.
328 * @param connection connection to use
329 * @return MHD_YES on success
332 serve_zoneinfo_page (struct MHD_Connection *connection)
334 struct ZoneinfoRequest *zr;
336 zr = GNUNET_new (struct ZoneinfoRequest);
337 zr->zoneinfo = GNUNET_malloc (DEFAULT_ZONEINFO_BUFSIZE);
338 zr->buf_len = DEFAULT_ZONEINFO_BUFSIZE;
339 zr->connection = connection;
340 zr->write_offset = 0;
341 zr->list_it = GNUNET_NAMESTORE_zone_iteration_start (ns,
350 * Handler that returns a simple static HTTP page.
352 * @param connection connection to use
353 * @return MHD_YES on success
356 serve_main_page (struct MHD_Connection *connection)
359 struct MHD_Response *response;
361 /* return static form */
362 response = MHD_create_response_from_buffer (strlen (MAIN_PAGE),
364 MHD_RESPMEM_PERSISTENT);
365 MHD_add_response_header (response,
366 MHD_HTTP_HEADER_CONTENT_TYPE,
368 ret = MHD_queue_response (connection,
371 MHD_destroy_response (response);
377 * Send the 'SUBMIT_PAGE'.
379 * @param info information string to send to the user
380 * @param request request information
381 * @param connection connection to use
384 fill_s_reply (const char *info,
385 struct Request *request,
386 struct MHD_Connection *connection)
390 struct MHD_Response *response;
392 GNUNET_asprintf (&reply,
396 /* return static form */
397 response = MHD_create_response_from_buffer (strlen (reply),
399 MHD_RESPMEM_MUST_FREE);
400 MHD_add_response_header (response,
401 MHD_HTTP_HEADER_CONTENT_TYPE,
403 ret = MHD_queue_response (connection,
406 MHD_destroy_response (response);
412 * Iterator over key-value pairs where the value
413 * maybe made available in increments and/or may
414 * not be zero-terminated. Used for processing
417 * @param cls user-specified closure
418 * @param kind type of the value
419 * @param key 0-terminated key for the value
420 * @param filename name of the uploaded file, NULL if not known
421 * @param content_type mime-type of the data, NULL if not known
422 * @param transfer_encoding encoding of the data, NULL if not known
423 * @param data pointer to size bytes of data at the
425 * @param off offset of data in the overall value
426 * @param size number of bytes in data available
427 * @return MHD_YES to continue iterating,
428 * MHD_NO to abort the iteration
431 post_iterator (void *cls,
432 enum MHD_ValueKind kind,
434 const char *filename,
435 const char *content_type,
436 const char *transfer_encoding,
437 const char *data, uint64_t off, size_t size)
439 struct Request *request = cls;
441 if (0 == strcmp ("domain", key))
443 if (size + off >= sizeof(request->domain_name))
444 size = sizeof (request->domain_name) - off - 1;
445 memcpy (&request->domain_name[off],
448 request->domain_name[size+off] = '\0';
451 if (0 == strcmp ("pkey", key))
453 if (size + off >= sizeof(request->public_key))
454 size = sizeof (request->public_key) - off - 1;
455 memcpy (&request->public_key[off],
458 request->public_key[size+off] = '\0';
461 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
462 _("Unsupported form value `%s'\n"),
469 * Continuation called to notify client about result of the
473 * @param success #GNUNET_SYSERR on failure (including timeout/queue drop/failure to validate)
474 * #GNUNET_NO if content was already there
475 * #GNUNET_YES (or other positive value) on success
476 * @param emsg NULL on success, otherwise an error message
479 put_continuation (void *cls,
483 struct Request *request = cls;
488 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
489 _("Failed to create record for domain `%s': %s\n"),
490 request->domain_name,
492 request->phase = RP_FAIL;
495 request->phase = RP_SUCCESS;
501 * Test if a name mapping was found, if so, refuse. If not, initiate storing of the record.
504 * @param zone_key public key of the zone
505 * @param name name that is being mapped (at most 255 characters long)
506 * @param rd_count number of entries in @a rd array
507 * @param rd array of records with data to store
510 zone_to_name_cb (void *cls,
511 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
513 unsigned int rd_count,
514 const struct GNUNET_GNSRECORD_Data *rd)
516 struct Request *request = cls;
517 struct GNUNET_GNSRECORD_Data r;
518 struct GNUNET_CRYPTO_EcdsaPublicKey pub;
523 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
524 _("Found existing name `%s' for the given key\n"),
526 request->phase = RP_FAIL;
530 GNUNET_CRYPTO_ecdsa_key_get_public (zone_key,
533 r.data_size = sizeof (pub);
534 r.expiration_time = UINT64_MAX;
535 r.record_type = GNUNET_GNSRECORD_TYPE_PKEY;
536 r.flags = GNUNET_GNSRECORD_RF_NONE;
537 request->qe = GNUNET_NAMESTORE_records_store (ns,
539 request->domain_name,
547 * We got a block back from the namestore. Decrypt it
548 * and continue to process the result.
550 * @param cls the 'struct Request' we are processing
551 * @param zone private key of the zone; NULL on disconnect
552 * @param label label of the records; NULL on disconnect
553 * @param rd_count number of entries in @a rd array, 0 if label was deleted
554 * @param rd array of records with data to store
557 lookup_block_processor (void *cls,
558 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
560 unsigned int rd_count,
561 const struct GNUNET_GNSRECORD_Data *rd)
563 struct Request *request = cls;
564 struct GNUNET_CRYPTO_EcdsaPublicKey pub;
571 GNUNET_CRYPTO_ecdsa_public_key_from_string (request->public_key,
572 strlen (request->public_key),
576 request->phase = RP_FAIL;
580 request->qe = GNUNET_NAMESTORE_zone_to_name (ns,
587 GNUNET_break (0 != strcmp (label, request->domain_name));
588 GNUNET_break (0 != rd_count);
589 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
590 _("Found %u existing records for domain `%s'\n"),
592 request->domain_name);
593 request->phase = RP_FAIL;
600 * Main MHD callback for handling requests.
603 * @param connection MHD connection handle
604 * @param url the requested url
605 * @param method the HTTP method used ("GET", "PUT", etc.)
606 * @param version the HTTP version string (i.e. "HTTP/1.1")
607 * @param upload_data the data being uploaded (excluding HEADERS,
608 * for a POST that fits into memory and that is encoded
609 * with a supported encoding, the POST data will NOT be
610 * given in upload_data and is instead available as
611 * part of MHD_get_connection_values; very large POST
612 * data *will* be made available incrementally in
614 * @param upload_data_size set initially to the size of the
615 * @a upload_data provided; the method must update this
616 * value to the number of bytes NOT processed;
617 * @param ptr pointer to location where we store the 'struct Request'
618 * @return MHD_YES if the connection was handled successfully,
619 * MHD_NO if the socket must be closed due to a serious
620 * error while handling the request
623 create_response (void *cls,
624 struct MHD_Connection *connection,
628 const char *upload_data,
629 size_t *upload_data_size,
632 struct MHD_Response *response;
633 struct Request *request;
634 struct GNUNET_CRYPTO_EcdsaPublicKey pub;
637 if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) ||
638 (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) )
640 if (0 == strcmp (url, FCFS_ZONEINFO_URL))
641 ret = serve_zoneinfo_page (connection);
643 ret = serve_main_page (connection);
645 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
646 _("Failed to create page for `%s'\n"),
650 if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
655 request = GNUNET_malloc (sizeof (struct Request));
657 request->pp = MHD_create_post_processor (connection, 1024,
658 &post_iterator, request);
659 if (NULL == request->pp)
661 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
662 _("Failed to setup post processor for `%s'\n"),
664 return MHD_NO; /* internal error */
668 if (NULL != request->pp)
670 /* evaluate POST data */
671 MHD_post_process (request->pp,
674 if (0 != *upload_data_size)
676 *upload_data_size = 0;
679 /* done with POST data, serve response */
680 MHD_destroy_post_processor (request->pp);
684 GNUNET_CRYPTO_ecdsa_public_key_from_string (request->public_key,
685 strlen (request->public_key),
689 return fill_s_reply ("Failed to parse given public key",
690 request, connection);
692 switch (request->phase)
695 if (NULL != strchr (request->domain_name, (int) '.'))
697 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
698 _("Domain name must not contain `.'\n"));
699 request->phase = RP_FAIL;
700 return fill_s_reply ("Domain name must not contain `.', sorry.",
701 request, connection);
703 if (NULL != strchr (request->domain_name, (int) '+'))
705 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
706 _("Domain name must not contain `+'\n"));
707 request->phase = RP_FAIL;
708 return fill_s_reply ("Domain name must not contain `+', sorry.",
709 request, connection);
711 request->phase = RP_LOOKUP;
712 request->qe = GNUNET_NAMESTORE_records_lookup (ns,
714 request->domain_name,
715 &lookup_block_processor,
723 return fill_s_reply ("Request failed, sorry.",
724 request, connection);
726 return fill_s_reply ("Success.",
727 request, connection);
732 return MHD_YES; /* will have a reply later... */
734 /* unsupported HTTP method */
735 response = MHD_create_response_from_buffer (strlen (METHOD_ERROR),
736 (void *) METHOD_ERROR,
737 MHD_RESPMEM_PERSISTENT);
738 ret = MHD_queue_response (connection,
739 MHD_HTTP_METHOD_NOT_ACCEPTABLE,
741 MHD_destroy_response (response);
747 * Callback called upon completion of a request.
748 * Decrements session reference counter.
750 * @param cls not used
751 * @param connection connection that completed
752 * @param con_cls session handle
753 * @param toe status code
756 request_completed_callback (void *cls,
757 struct MHD_Connection *connection,
759 enum MHD_RequestTerminationCode toe)
761 struct Request *request = *con_cls;
765 if (NULL != request->pp)
766 MHD_destroy_post_processor (request->pp);
767 if (NULL != request->qe)
768 GNUNET_NAMESTORE_cancel (request->qe);
769 GNUNET_free (request);
773 #define UNSIGNED_MHD_LONG_LONG unsigned MHD_LONG_LONG
777 * Schedule tasks to run MHD server.
785 struct GNUNET_NETWORK_FDSet *wrs;
786 struct GNUNET_NETWORK_FDSet *wws;
787 struct GNUNET_NETWORK_FDSet *wes;
790 UNSIGNED_MHD_LONG_LONG timeout;
791 struct GNUNET_TIME_Relative tv;
796 wrs = GNUNET_NETWORK_fdset_create ();
797 wes = GNUNET_NETWORK_fdset_create ();
798 wws = GNUNET_NETWORK_fdset_create ();
800 GNUNET_assert (MHD_YES == MHD_get_fdset (httpd, &rs, &ws, &es, &max));
801 haveto = MHD_get_timeout (httpd, &timeout);
802 if (haveto == MHD_YES)
803 tv.rel_value_us = (uint64_t) timeout * 1000LL;
805 tv = GNUNET_TIME_UNIT_FOREVER_REL;
806 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
807 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
808 GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
810 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
813 GNUNET_NETWORK_fdset_destroy (wrs);
814 GNUNET_NETWORK_fdset_destroy (wws);
815 GNUNET_NETWORK_fdset_destroy (wes);
820 * Task run whenever HTTP server operations are pending.
823 * @param tc scheduler context
827 const struct GNUNET_SCHEDULER_TaskContext *tc)
829 httpd_task = GNUNET_SCHEDULER_NO_TASK;
836 * Task run on shutdown. Cleans up everything.
839 * @param tc scheduler context
842 do_shutdown (void *cls,
843 const struct GNUNET_SCHEDULER_TaskContext *tc)
845 if (GNUNET_SCHEDULER_NO_TASK != httpd_task)
847 GNUNET_SCHEDULER_cancel (httpd_task);
848 httpd_task = GNUNET_SCHEDULER_NO_TASK;
852 GNUNET_NAMESTORE_disconnect (ns);
857 MHD_stop_daemon (httpd);
862 GNUNET_IDENTITY_cancel (id_op);
865 if (NULL != identity)
867 GNUNET_IDENTITY_disconnect (identity);
874 * Method called to inform about the egos of this peer.
876 * When used with #GNUNET_IDENTITY_create or #GNUNET_IDENTITY_get,
877 * this function is only called ONCE, and 'NULL' being passed in
878 * @a ego does indicate an error (i.e. name is taken or no default
879 * value is known). If @a ego is non-NULL and if '*ctx'
880 * is set in those callbacks, the value WILL be passed to a subsequent
881 * call to the identity callback of #GNUNET_IDENTITY_connect (if
882 * that one was not NULL).
884 * @param cls closure, NULL
885 * @param ego ego handle
886 * @param ctx context for application to store data for this ego
887 * (during the lifetime of this process, initially NULL)
888 * @param name name assigned by the user for this ego,
889 * NULL if the user just deleted the ego and it
890 * must thus no longer be used
893 identity_cb (void *cls,
894 struct GNUNET_IDENTITY_Ego *ego,
903 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
904 _("No ego configured for `fcfsd` subsystem\n"));
907 fcfs_zone_pkey = *GNUNET_IDENTITY_ego_get_private_key (ego);
909 options = MHD_USE_DUAL_STACK | MHD_USE_DEBUG;
912 httpd = MHD_start_daemon (options,
915 &create_response, NULL,
916 MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 128,
917 MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
918 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
919 MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (4 * 1024),
920 MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL,
922 if (MHD_USE_DEBUG == options)
924 options = MHD_USE_DEBUG;
926 while (NULL == httpd);
929 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
930 _("Failed to start HTTP server\n"));
931 GNUNET_SCHEDULER_shutdown ();
939 * Main function that will be run.
942 * @param args remaining command-line arguments
943 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
944 * @param cfg configuration
947 run (void *cls, char *const *args, const char *cfgfile,
948 const struct GNUNET_CONFIGURATION_Handle *cfg)
951 GNUNET_CONFIGURATION_get_value_number (cfg,
956 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
957 "fcfsd", "HTTPPORT");
960 ns = GNUNET_NAMESTORE_connect (cfg);
963 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
964 _("Failed to connect to namestore\n"));
967 identity = GNUNET_IDENTITY_connect (cfg,
969 id_op = GNUNET_IDENTITY_get (identity, "fcfsd",
971 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
977 * The main function for the fcfs daemon.
979 * @param argc number of arguments from the command line
980 * @param argv command line arguments
981 * @return 0 ok, 1 on error
984 main (int argc, char *const *argv)
986 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
987 GNUNET_GETOPT_OPTION_END
992 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
995 GNUNET_log_setup ("fcfsd", "WARNING", NULL);
998 GNUNET_PROGRAM_run (argc, argv, "fcfsd",
999 _("GNU Name System First Come First Serve name registration service"),
1001 &run, NULL)) ? 0 : 1;
1002 GNUNET_free ((void*) argv);
1003 GNUNET_CRYPTO_ecdsa_key_clear (&fcfs_zone_pkey);
1007 /* end of gnunet-namestore-fcfsd.c */