modify zoneimport to deal with non-TLD zones due to difference in zone cuts between...
[oweals/gnunet.git] / src / namestore / plugin_namestore_postgres.c
1  /*
2   * This file is part of GNUnet
3   * Copyright (C) 2009-2013, 2016-2018 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18   * Boston, MA 02110-1301, USA.
19   */
20
21 /**
22  * @file namestore/plugin_namestore_postgres.c
23  * @brief postgres-based namestore backend
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_namestore_plugin.h"
28 #include "gnunet_namestore_service.h"
29 #include "gnunet_gnsrecord_lib.h"
30 #include "gnunet_pq_lib.h"
31 #include "namestore.h"
32
33
34 #define LOG(kind,...) GNUNET_log_from (kind, "namestore-postgres", __VA_ARGS__)
35
36
37 /**
38  * Context for all functions in this plugin.
39  */
40 struct Plugin
41 {
42
43   /**
44    * Our configuration.
45    */
46   const struct GNUNET_CONFIGURATION_Handle *cfg;
47
48   /**
49    * Native Postgres database handle.
50    */
51   PGconn *dbh;
52
53 };
54
55
56 /**
57  * Initialize the database connections and associated
58  * data structures (create tables and indices
59  * as needed as well).
60  *
61  * @param plugin the plugin context (state for this module)
62  * @return #GNUNET_OK on success
63  */
64 static int
65 database_setup (struct Plugin *plugin)
66 {
67   struct GNUNET_PQ_ExecuteStatement es_temporary =
68     GNUNET_PQ_make_execute ("CREATE TEMPORARY TABLE IF NOT EXISTS ns097records ("
69                             " zone_private_key BYTEA NOT NULL DEFAULT '',"
70                             " pkey BYTEA DEFAULT '',"
71                             " rvalue BYTEA NOT NULL DEFAULT '',"
72                             " record_count INTEGER NOT NULL DEFAULT 0,"
73                             " record_data BYTEA NOT NULL DEFAULT '',"
74                             " label TEXT NOT NULL DEFAULT ''"
75                             ")"
76                             "WITH OIDS");
77   struct GNUNET_PQ_ExecuteStatement es_default =
78     GNUNET_PQ_make_execute ("CREATE TABLE IF NOT EXISTS ns097records ("
79                             " zone_private_key BYTEA NOT NULL DEFAULT '',"
80                             " pkey BYTEA DEFAULT '',"
81                             " rvalue BYTEA NOT NULL DEFAULT '',"
82                             " record_count INTEGER NOT NULL DEFAULT 0,"
83                             " record_data BYTEA NOT NULL DEFAULT '',"
84                             " label TEXT NOT NULL DEFAULT ''"
85                             ")"
86                             "WITH OIDS");
87   const struct GNUNET_PQ_ExecuteStatement *cr;
88
89   plugin->dbh = GNUNET_PQ_connect_with_cfg (plugin->cfg,
90                                             "namestore-postgres");
91   if (NULL == plugin->dbh)
92     return GNUNET_SYSERR;
93   if (GNUNET_YES ==
94       GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg,
95                                             "namestore-postgres",
96                                             "ASYNC_COMMIT"))
97   {
98     struct GNUNET_PQ_ExecuteStatement es[] = {
99       GNUNET_PQ_make_try_execute ("SET synchronous_commit TO off"),
100       GNUNET_PQ_EXECUTE_STATEMENT_END
101     };
102
103     if (GNUNET_OK !=
104         GNUNET_PQ_exec_statements (plugin->dbh,
105                                    es))
106     {
107       PQfinish (plugin->dbh);
108       plugin->dbh = NULL;
109       return GNUNET_SYSERR;
110     }
111   }
112   if (GNUNET_YES ==
113       GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg,
114                                             "namestore-postgres",
115                                             "TEMPORARY_TABLE"))
116   {
117     cr = &es_temporary;
118   }
119   else
120   {
121     cr = &es_default;
122   }
123
124   {
125     struct GNUNET_PQ_ExecuteStatement es[] = {
126       *cr,
127       GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_reverse "
128                                   "ON ns097records (zone_private_key,pkey)"),
129       GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_iter "
130                                   "ON ns097records (zone_private_key,rvalue)"),
131       GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS it_iter "
132                                   "ON ns097records (rvalue)"),
133       GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_label "
134                                   "ON ns097records (label)"),
135       GNUNET_PQ_EXECUTE_STATEMENT_END
136     };
137
138     if (GNUNET_OK !=
139         GNUNET_PQ_exec_statements (plugin->dbh,
140                                    es))
141     {
142       PQfinish (plugin->dbh);
143       plugin->dbh = NULL;
144       return GNUNET_SYSERR;
145     }
146   }
147
148   {
149     struct GNUNET_PQ_PreparedStatement ps[] = {
150       GNUNET_PQ_make_prepare ("store_records",
151                               "INSERT INTO ns097records (zone_private_key, pkey, rvalue, record_count, record_data, label) VALUES "
152                               "($1, $2, $3, $4, $5, $6)", 6),
153       GNUNET_PQ_make_prepare ("delete_records",
154                               "DELETE FROM ns097records "
155                               "WHERE zone_private_key=$1 AND label=$2", 2),
156       GNUNET_PQ_make_prepare ("zone_to_name",
157                               "SELECT record_count,record_data,label FROM ns097records"
158                               " WHERE zone_private_key=$1 AND pkey=$2", 2),
159       GNUNET_PQ_make_prepare ("iterate_zone",
160                               "SELECT record_count,record_data,label FROM ns097records "
161                               "WHERE zone_private_key=$1 ORDER BY rvalue LIMIT 1 OFFSET $2", 2),
162       GNUNET_PQ_make_prepare ("iterate_all_zones",
163                               "SELECT record_count,record_data,label,zone_private_key"
164                               " FROM ns097records ORDER BY rvalue LIMIT 1 OFFSET $1", 1),
165       GNUNET_PQ_make_prepare ("lookup_label",
166                               "SELECT record_count,record_data,label "
167                               "FROM ns097records WHERE zone_private_key=$1 AND label=$2", 2),
168       GNUNET_PQ_PREPARED_STATEMENT_END
169     };
170
171     if (GNUNET_OK !=
172         GNUNET_PQ_prepare_statements (plugin->dbh,
173                                       ps))
174     {
175       PQfinish (plugin->dbh);
176       plugin->dbh = NULL;
177       return GNUNET_SYSERR;
178     }
179   }
180
181   return GNUNET_OK;
182 }
183
184
185 /**
186  * Store a record in the datastore.  Removes any existing record in the
187  * same zone with the same name.
188  *
189  * @param cls closure (internal context for the plugin)
190  * @param zone_key private key of the zone
191  * @param label name that is being mapped (at most 255 characters long)
192  * @param rd_count number of entries in @a rd array
193  * @param rd array of records with data to store
194  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
195  */
196 static int
197 namestore_postgres_store_records (void *cls,
198                                   const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
199                                   const char *label,
200                                   unsigned int rd_count,
201                                   const struct GNUNET_GNSRECORD_Data *rd)
202 {
203   struct Plugin *plugin = cls;
204   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
205   uint64_t rvalue;
206   uint32_t rd_count32 = (uint32_t) rd_count;
207   size_t data_size;
208
209   memset (&pkey, 0, sizeof (pkey));
210   for (unsigned int i=0;i<rd_count;i++)
211     if (GNUNET_GNSRECORD_TYPE_PKEY == rd[i].record_type)
212     {
213       GNUNET_break (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) == rd[i].data_size);
214       GNUNET_memcpy (&pkey,
215                      rd[i].data,
216                      rd[i].data_size);
217       break;
218     }
219   rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
220                                      UINT64_MAX);
221   data_size = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
222   if (data_size > 64 * 65536)
223   {
224     GNUNET_break (0);
225     return GNUNET_SYSERR;
226   }
227   {
228     char data[data_size];
229     struct GNUNET_PQ_QueryParam params[] = {
230       GNUNET_PQ_query_param_auto_from_type (zone_key),
231       GNUNET_PQ_query_param_auto_from_type (&pkey),
232       GNUNET_PQ_query_param_uint64 (&rvalue),
233       GNUNET_PQ_query_param_uint32 (&rd_count32),
234       GNUNET_PQ_query_param_fixed_size (data, data_size),
235       GNUNET_PQ_query_param_string (label),
236       GNUNET_PQ_query_param_end
237     };
238     enum GNUNET_DB_QueryStatus res;
239     ssize_t ret;
240
241     ret = GNUNET_GNSRECORD_records_serialize (rd_count,
242                                               rd,
243                                               data_size,
244                                               data);
245     if ( (ret < 0) ||
246          (data_size != (size_t) ret) )        
247     {
248       GNUNET_break (0);
249       return GNUNET_SYSERR;
250     }
251
252     res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh,
253                                               "store_records",
254                                               params);
255     if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != res)
256       return GNUNET_SYSERR;
257   }
258   return GNUNET_OK;
259 }
260
261
262 /**
263  * Closure for #parse_result_call_iterator.
264  */
265 struct ParserContext
266 {
267   /**
268    * Function to call for each result.
269    */
270   GNUNET_NAMESTORE_RecordIterator iter;
271
272   /**
273    * Closure for @e iter.
274    */
275   void *iter_cls;
276
277   /**
278    * Zone key, NULL if part of record.
279    */
280   const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key;
281 };
282
283
284 /**
285  * A statement has been run.  We should evaluate the result, and if possible
286  * call the @a iter in @a cls with the result.
287  *
288  * @param cls closure of type `struct ParserContext *`
289  * @param result the postgres result
290  * @param num_result the number of results in @a result
291  */
292 static void
293 parse_result_call_iterator (void *cls,
294                             PGresult *res,
295                             unsigned int num_results)
296 {
297   struct ParserContext *pc = cls;
298
299   for (unsigned int i=0;i<num_results;i++)
300   {
301     void *data;
302     size_t data_size;
303     uint32_t record_count;
304     char *label;
305     struct GNUNET_CRYPTO_EcdsaPrivateKey zk;
306     struct GNUNET_PQ_ResultSpec rs_with_zone[] = {
307       GNUNET_PQ_result_spec_uint32 ("record_count", &record_count),
308       GNUNET_PQ_result_spec_variable_size ("record_data", &data, &data_size),
309       GNUNET_PQ_result_spec_string ("label", &label),
310       GNUNET_PQ_result_spec_auto_from_type ("zone_private_key", &zk),
311       GNUNET_PQ_result_spec_end
312     };
313     struct GNUNET_PQ_ResultSpec rs_without_zone[] = {
314       GNUNET_PQ_result_spec_uint32 ("record_count", &record_count),
315       GNUNET_PQ_result_spec_variable_size ("record_data", &data, &data_size),
316       GNUNET_PQ_result_spec_string ("label", &label),
317       GNUNET_PQ_result_spec_end
318     };
319     struct GNUNET_PQ_ResultSpec *rs;
320
321     rs = (NULL == pc->zone_key) ? rs_with_zone : rs_without_zone;
322     if (GNUNET_YES !=
323         GNUNET_PQ_extract_result (res,
324                                   rs,
325                                   i))
326     {
327       GNUNET_break (0);
328       return;
329     }
330
331     if (record_count > 64 * 1024)
332     {
333       /* sanity check, don't stack allocate far too much just
334          because database might contain a large value here */
335       GNUNET_break (0);
336       GNUNET_PQ_cleanup_result (rs);
337       return;
338     }
339
340     {
341       struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL(record_count)];
342
343       if (GNUNET_OK !=
344           GNUNET_GNSRECORD_records_deserialize (data_size,
345                                                 data,
346                                                 record_count,
347                                                 rd))
348       {
349         GNUNET_break (0);
350         GNUNET_PQ_cleanup_result (rs);
351         return;
352       }
353       pc->iter (pc->iter_cls,
354                 (NULL == pc->zone_key) ? &zk : pc->zone_key,
355                 label,
356                 record_count,
357                 rd);
358     }
359     GNUNET_PQ_cleanup_result (rs);
360   }
361 }
362
363
364 /**
365  * Lookup records in the datastore for which we are the authority.
366  *
367  * @param cls closure (internal context for the plugin)
368  * @param zone private key of the zone
369  * @param label name of the record in the zone
370  * @param iter function to call with the result
371  * @param iter_cls closure for @a iter
372  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
373  */
374 static int
375 namestore_postgres_lookup_records (void *cls,
376                                    const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
377                                    const char *label,
378                                    GNUNET_NAMESTORE_RecordIterator iter,
379                                    void *iter_cls)
380 {
381   struct Plugin *plugin = cls;
382   struct GNUNET_PQ_QueryParam params[] = {
383     GNUNET_PQ_query_param_auto_from_type (zone),
384     GNUNET_PQ_query_param_string (label),
385     GNUNET_PQ_query_param_end
386   };
387   struct ParserContext pc;
388   enum GNUNET_DB_QueryStatus res;
389
390   pc.iter = iter;
391   pc.iter_cls = iter_cls;
392   pc.zone_key = zone;
393   res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
394                                               "lookup_label",
395                                               params,
396                                               &parse_result_call_iterator,
397                                               &pc);
398   if (res <= 0)
399     return GNUNET_SYSERR;
400   return GNUNET_OK;
401 }
402
403
404 /**
405  * Iterate over the results for a particular key and zone in the
406  * datastore.  Will return at most one result to the iterator.
407  *
408  * @param cls closure (internal context for the plugin)
409  * @param zone hash of public key of the zone, NULL to iterate over all zones
410  * @param offset offset in the list of all matching records
411  * @param iter function to call with the result
412  * @param iter_cls closure for @a iter
413  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
414  */
415 static int
416 namestore_postgres_iterate_records (void *cls,
417                                     const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
418                                     uint64_t offset,
419                                     GNUNET_NAMESTORE_RecordIterator iter,
420                                     void *iter_cls)
421 {
422   struct Plugin *plugin = cls;
423   enum GNUNET_DB_QueryStatus res;
424   struct ParserContext pc;
425
426   pc.iter = iter;
427   pc.iter_cls = iter_cls;
428   pc.zone_key = zone;
429   if (NULL == zone)
430   {
431     struct GNUNET_PQ_QueryParam params_without_zone[] = {
432       GNUNET_PQ_query_param_uint64 (&offset),
433       GNUNET_PQ_query_param_end
434     };
435
436     res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
437                                                 "iterate_all_zones",
438                                                 params_without_zone,
439                                                 &parse_result_call_iterator,
440                                                 &pc);
441   }
442   else
443   {
444     struct GNUNET_PQ_QueryParam params_with_zone[] = {
445       GNUNET_PQ_query_param_auto_from_type (zone),
446       GNUNET_PQ_query_param_uint64 (&offset),
447       GNUNET_PQ_query_param_end
448     };
449
450     res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
451                                                 "iterate_zone",
452                                                 params_with_zone,
453                                                 &parse_result_call_iterator,
454                                                 &pc);
455   }
456   if (res < 0)
457     return GNUNET_SYSERR;
458
459   if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res)
460     return GNUNET_NO;
461
462   return GNUNET_OK;
463 }
464
465
466 /**
467  * Look for an existing PKEY delegation record for a given public key.
468  * Returns at most one result to the iterator.
469  *
470  * @param cls closure (internal context for the plugin)
471  * @param zone private key of the zone to look up in, never NULL
472  * @param value_zone public key of the target zone (value), never NULL
473  * @param iter function to call with the result
474  * @param iter_cls closure for @a iter
475  * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
476  */
477 static int
478 namestore_postgres_zone_to_name (void *cls,
479                                  const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
480                                  const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone,
481                                  GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls)
482 {
483   struct Plugin *plugin = cls;
484   struct GNUNET_PQ_QueryParam params[] = {
485     GNUNET_PQ_query_param_auto_from_type (zone),
486     GNUNET_PQ_query_param_auto_from_type (value_zone),
487     GNUNET_PQ_query_param_end
488   };
489   enum GNUNET_DB_QueryStatus res;
490   struct ParserContext pc;
491
492   pc.iter = iter;
493   pc.iter_cls = iter_cls;
494   pc.zone_key = zone;
495   res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh,
496                                               "zone_to_name",
497                                               params,
498                                               &parse_result_call_iterator,
499                                               &pc);
500   if (res < 0)
501     return GNUNET_SYSERR;
502   return GNUNET_OK;
503 }
504
505
506 /**
507  * Shutdown database connection and associate data
508  * structures.
509  *
510  * @param plugin the plugin context (state for this module)
511  */
512 static void
513 database_shutdown (struct Plugin *plugin)
514 {
515   PQfinish (plugin->dbh);
516   plugin->dbh = NULL;
517 }
518
519
520 /**
521  * Entry point for the plugin.
522  *
523  * @param cls the `struct GNUNET_NAMESTORE_PluginEnvironment*`
524  * @return NULL on error, othrewise the plugin context
525  */
526 void *
527 libgnunet_plugin_namestore_postgres_init (void *cls)
528 {
529   static struct Plugin plugin;
530   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
531   struct GNUNET_NAMESTORE_PluginFunctions *api;
532
533   if (NULL != plugin.cfg)
534     return NULL;                /* can only initialize once! */
535   memset (&plugin, 0, sizeof (struct Plugin));
536   plugin.cfg = cfg;
537   if (GNUNET_OK != database_setup (&plugin))
538   {
539     database_shutdown (&plugin);
540     return NULL;
541   }
542   api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions);
543   api->cls = &plugin;
544   api->store_records = &namestore_postgres_store_records;
545   api->iterate_records = &namestore_postgres_iterate_records;
546   api->zone_to_name = &namestore_postgres_zone_to_name;
547   api->lookup_records = &namestore_postgres_lookup_records;
548   LOG (GNUNET_ERROR_TYPE_INFO,
549        "Postgres namestore plugin running\n");
550   return api;
551 }
552
553
554 /**
555  * Exit point from the plugin.
556  *
557  * @param cls the plugin context (as returned by "init")
558  * @return always NULL
559  */
560 void *
561 libgnunet_plugin_namestore_postgres_done (void *cls)
562 {
563   struct GNUNET_NAMESTORE_PluginFunctions *api = cls;
564   struct Plugin *plugin = api->cls;
565
566   database_shutdown (plugin);
567   plugin->cfg = NULL;
568   GNUNET_free (api);
569   LOG (GNUNET_ERROR_TYPE_DEBUG,
570        "Postgres namestore plugin is finished\n");
571   return NULL;
572 }
573
574 /* end of plugin_namestore_postgres.c */