2 This file is part of GNUnet
3 (C) 2012 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.
22 * @brief library to help with access to a MySQL database
23 * @author Christian Grothoff
26 #include <mysql/mysql.h>
27 #include "gnunet_mysql_lib.h"
30 * Maximum number of supported parameters for a prepared
31 * statement. Increase if needed.
37 * Die with an error message that indicates
38 * a failure of the command 'cmd' with the message given
41 #define DIE_MYSQL(cmd, dbh) do { GNUNET_log_from (GNUNET_ERROR_TYPE__ERROR, "mysql", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, mysql_error((dbh)->dbf)); GNUNET_abort(); } while(0);
44 * Log an error message at log-level 'level' that indicates
45 * a failure of the command 'cmd' on file 'filename'
46 * with the message given by strerror(errno).
48 #define LOG_MYSQL(level, cmd, dbh) do { GNUNET_log_from (level, "mysql", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, mysql_error((dbh)->dbf)); } while(0);
54 struct GNUNET_MYSQL_Context
60 const struct GNUNET_CONFIGURATION_Handle *cfg;
68 * Handle to the mysql database.
73 * Head of list of our prepared statements.
75 struct GNUNET_MYSQL_StatementHandle *shead;
78 * Tail of list of our prepared statements.
80 struct GNUNET_MYSQL_StatementHandle *stail;
83 * Filename of "my.cnf" (msyql configuration).
91 * Handle for a prepared statement.
93 struct GNUNET_MYSQL_StatementHandle
99 struct GNUNET_MYSQL_StatementHandle *next;
104 struct GNUNET_MYSQL_StatementHandle *prev;
107 * Original query string.
112 * Handle to MySQL prepared statement.
114 MYSQL_STMT *statement;
117 * Is the MySQL prepared statement valid, or do we need to re-initialize it?
125 * Obtain the location of ".my.cnf".
127 * @param cfg our configuration
128 * @return NULL on error
131 get_my_cnf_path (const struct GNUNET_CONFIGURATION_Handle *cfg,
144 pw = getpwuid (getuid ());
147 GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_ERROR, "mysql", "getpwuid");
151 GNUNET_CONFIGURATION_have_value (cfg, section, "CONFIG"))
153 GNUNET_assert (GNUNET_OK ==
154 GNUNET_CONFIGURATION_get_value_filename (cfg,
158 configured = GNUNET_YES;
162 home_dir = GNUNET_strdup (pw->pw_dir);
163 GNUNET_asprintf (&cnffile, "%s/.my.cnf", home_dir);
164 GNUNET_free (home_dir);
165 configured = GNUNET_NO;
168 home_dir = (char *) GNUNET_malloc (_MAX_PATH + 1);
169 plibc_conv_to_win_path ("~/", home_dir);
170 GNUNET_asprintf (&cnffile, "%s/.my.cnf", home_dir);
171 GNUNET_free (home_dir);
172 configured = GNUNET_NO;
174 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
176 _("Trying to use file `%s' for MySQL configuration.\n"), cnffile);
177 if ((0 != STAT (cnffile, &st)) || (0 != ACCESS (cnffile, R_OK)) ||
178 (!S_ISREG (st.st_mode)))
180 if (configured == GNUNET_YES)
181 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
183 _("Could not access file `%s': %s\n"), cnffile,
185 GNUNET_free (cnffile);
193 * Open the connection with the database (and initialize
194 * our default options).
196 * @param mc database context to initialze
197 * @return GNUNET_OK on success
200 iopen (struct GNUNET_MYSQL_Context *mc)
205 char *mysql_password;
206 unsigned long long mysql_port;
208 unsigned int timeout;
210 mc->dbf = mysql_init (NULL);
212 return GNUNET_SYSERR;
213 if (mc->cnffile != NULL)
214 mysql_options (mc->dbf, MYSQL_READ_DEFAULT_FILE, mc->cnffile);
215 mysql_options (mc->dbf, MYSQL_READ_DEFAULT_GROUP, "client");
217 mysql_options (mc->dbf, MYSQL_OPT_RECONNECT, &reconnect);
218 mysql_options (mc->dbf, MYSQL_OPT_CONNECT_TIMEOUT, (const void *) &timeout);
219 mysql_options (mc->dbf, MYSQL_SET_CHARSET_NAME, "UTF8");
220 timeout = 60; /* in seconds */
221 mysql_options (mc->dbf, MYSQL_OPT_READ_TIMEOUT, (const void *) &timeout);
222 mysql_options (mc->dbf, MYSQL_OPT_WRITE_TIMEOUT, (const void *) &timeout);
225 GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section,
227 GNUNET_assert (GNUNET_OK ==
228 GNUNET_CONFIGURATION_get_value_string (mc->cfg,
233 mysql_dbname = GNUNET_strdup ("gnunet");
236 GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section,
239 GNUNET_assert (GNUNET_OK ==
240 GNUNET_CONFIGURATION_get_value_string (mc->cfg,
242 "USER", &mysql_user));
244 mysql_password = NULL;
246 GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section,
249 GNUNET_assert (GNUNET_OK ==
250 GNUNET_CONFIGURATION_get_value_string (mc->cfg,
257 GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section,
260 GNUNET_assert (GNUNET_OK ==
261 GNUNET_CONFIGURATION_get_value_string (mc->cfg,
268 GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section,
271 GNUNET_assert (GNUNET_OK ==
272 GNUNET_CONFIGURATION_get_value_number (mc->cfg,
274 "PORT", &mysql_port));
277 GNUNET_assert (mysql_dbname != NULL);
278 mysql_real_connect (mc->dbf, mysql_server, mysql_user, mysql_password,
279 mysql_dbname, (unsigned int) mysql_port, NULL,
280 CLIENT_IGNORE_SIGPIPE);
281 GNUNET_free_non_null (mysql_server);
282 GNUNET_free_non_null (mysql_user);
283 GNUNET_free_non_null (mysql_password);
284 GNUNET_free (mysql_dbname);
285 if (mysql_error (mc->dbf)[0])
287 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_real_connect", mc);
288 return GNUNET_SYSERR;
295 * Create a mysql context.
297 * @param cfg configuration
298 * @param section configuration section to use to get MySQL configuration options
299 * @return the mysql context
301 struct GNUNET_MYSQL_Context *
302 GNUNET_MYSQL_context_create (const struct GNUNET_CONFIGURATION_Handle *cfg,
305 struct GNUNET_MYSQL_Context *mc;
307 mc = GNUNET_malloc (sizeof (struct GNUNET_MYSQL_Context));
309 mc->section = section;
310 mc->cnffile = get_my_cnf_path (cfg, section);
317 * Close database connection and all prepared statements (we got a DB
320 * @param mc mysql context
323 GNUNET_MYSQL_statements_invalidate (struct GNUNET_MYSQL_Context *mc)
325 struct GNUNET_MYSQL_StatementHandle *sh;
327 for (sh = mc->shead; NULL != sh; sh = sh->next)
329 if (GNUNET_YES == sh->valid)
331 mysql_stmt_close (sh->statement);
332 sh->valid = GNUNET_NO;
334 sh->statement = NULL;
338 mysql_close (mc->dbf);
345 * Destroy a mysql context. Also frees all associated prepared statements.
347 * @param mc context to destroy
350 GNUNET_MYSQL_context_destroy (struct GNUNET_MYSQL_Context *mc)
352 struct GNUNET_MYSQL_StatementHandle *sh;
354 GNUNET_MYSQL_statements_invalidate (mc);
355 while (NULL != (sh = mc->shead))
357 GNUNET_CONTAINER_DLL_remove (mc->shead, mc->stail, sh);
358 GNUNET_free (sh->query);
362 mysql_library_end ();
367 * Prepare a statement. Prepared statements are automatically discarded
368 * when the MySQL context is destroyed.
370 * @param mc mysql context
371 * @param query query text
372 * @return prepared statement, NULL on error
374 struct GNUNET_MYSQL_StatementHandle *
375 GNUNET_MYSQL_statement_prepare (struct GNUNET_MYSQL_Context *mc,
378 struct GNUNET_MYSQL_StatementHandle *sh;
380 sh = GNUNET_malloc (sizeof (struct GNUNET_MYSQL_StatementHandle));
381 sh->query = GNUNET_strdup (query);
382 GNUNET_CONTAINER_DLL_insert (mc->shead, mc->stail, sh);
388 * Run a SQL statement.
390 * @param mc mysql context
391 * @param sql SQL statement to run
392 * @return GNUNET_OK on success
393 * GNUNET_SYSERR if there was a problem
396 GNUNET_MYSQL_statement_run (struct GNUNET_MYSQL_Context *mc,
399 if ((NULL == mc->dbf) && (GNUNET_OK != iopen (mc)))
400 return GNUNET_SYSERR;
401 mysql_query (mc->dbf, sql);
402 if (mysql_error (mc->dbf)[0])
404 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_query", mc);
405 GNUNET_MYSQL_statements_invalidate (mc);
406 return GNUNET_SYSERR;
413 * Prepare a statement for running.
415 * @param mc mysql context
416 * @param sh statement handle to prepare
417 * @return GNUNET_OK on success
420 prepare_statement (struct GNUNET_MYSQL_Context *mc,
421 struct GNUNET_MYSQL_StatementHandle *sh)
423 if (GNUNET_YES == sh->valid)
425 if ((NULL == mc->dbf) && (GNUNET_OK != iopen (mc)))
426 return GNUNET_SYSERR;
427 sh->statement = mysql_stmt_init (mc->dbf);
428 if (NULL == sh->statement)
430 GNUNET_MYSQL_statements_invalidate (mc);
431 return GNUNET_SYSERR;
433 if (0 != mysql_stmt_prepare (sh->statement, sh->query, strlen (sh->query)))
435 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_stmt_prepare", mc);
436 mysql_stmt_close (sh->statement);
437 sh->statement = NULL;
438 GNUNET_MYSQL_statements_invalidate (mc);
439 return GNUNET_SYSERR;
441 sh->valid = GNUNET_YES;
447 * Get internal handle for a prepared statement. This function should rarely
448 * be used, and if, with caution! On failures during the interaction with
449 * the handle, you must call 'GNUNET_MYSQL_statements_invalidate'!
451 * @param mc mysql context
452 * @param sh prepared statement to introspect
453 * @return MySQL statement handle, NULL on error
456 GNUNET_MYSQL_statement_get_stmt (struct GNUNET_MYSQL_Context *mc,
457 struct GNUNET_MYSQL_StatementHandle *sh)
459 (void) prepare_statement (mc, sh);
460 return sh->statement;
465 * Bind the parameters for the given MySQL statement
468 * @param mc mysql context
469 * @param sh statement to bind and run
470 * @param ap arguments for the binding
471 * @return GNUNET_SYSERR on error, GNUNET_OK on success
474 init_params (struct GNUNET_MYSQL_Context *mc,
475 struct GNUNET_MYSQL_StatementHandle *sh,
478 MYSQL_BIND qbind[MAX_PARAM];
481 enum enum_field_types ft;
483 pc = mysql_stmt_param_count (sh->statement);
486 /* increase internal constant! */
488 return GNUNET_SYSERR;
490 memset (qbind, 0, sizeof (qbind));
493 while ((pc > 0) && (-1 != (int) (ft = va_arg (ap, enum enum_field_types))))
495 qbind[off].buffer_type = ft;
498 case MYSQL_TYPE_FLOAT:
499 qbind[off].buffer = va_arg (ap, float *);
502 case MYSQL_TYPE_LONGLONG:
503 qbind[off].buffer = va_arg (ap, unsigned long long *);
504 qbind[off].is_unsigned = va_arg (ap, int);
507 case MYSQL_TYPE_LONG:
508 qbind[off].buffer = va_arg (ap, unsigned int *);
509 qbind[off].is_unsigned = va_arg (ap, int);
512 case MYSQL_TYPE_VAR_STRING:
513 case MYSQL_TYPE_STRING:
514 case MYSQL_TYPE_BLOB:
515 qbind[off].buffer = va_arg (ap, void *);
516 qbind[off].buffer_length = va_arg (ap, unsigned long);
517 qbind[off].length = va_arg (ap, unsigned long *);
521 /* unsupported type */
523 return GNUNET_SYSERR;
528 if (!((pc == 0) && (-1 != (int) ft) && (va_arg (ap, int) == -1)))
531 return GNUNET_SYSERR;
533 if (mysql_stmt_bind_param (sh->statement, qbind))
535 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
537 _("`%s' failed at %s:%d with error: %s\n"),
538 "mysql_stmt_bind_param", __FILE__, __LINE__,
539 mysql_stmt_error (sh->statement));
540 GNUNET_MYSQL_statements_invalidate (mc);
541 return GNUNET_SYSERR;
543 if (mysql_stmt_execute (sh->statement))
545 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
547 _("`%s' failed at %s:%d with error: %s\n"),
548 "mysql_stmt_execute", __FILE__, __LINE__,
549 mysql_stmt_error (sh->statement));
550 GNUNET_MYSQL_statements_invalidate (mc);
551 return GNUNET_SYSERR;
559 * Run a prepared SELECT statement.
561 * @param mc mysql context
562 * @param s statement to run
563 * @param result_size number of elements in results array
564 * @param results pointer to already initialized MYSQL_BIND
565 * array (of sufficient size) for passing results
566 * @param ap pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
567 * values (size + buffer-reference for pointers); terminated
569 * @return GNUNET_SYSERR on error, otherwise
570 * the number of successfully affected (or queried) rows
573 GNUNET_MYSQL_statement_run_prepared_select_va (struct GNUNET_MYSQL_Context *mc,
574 struct GNUNET_MYSQL_StatementHandle *s,
575 unsigned int result_size,
576 MYSQL_BIND * results,
577 GNUNET_MYSQL_DataProcessor processor,
585 if (GNUNET_OK != prepare_statement (mc, s))
588 return GNUNET_SYSERR;
590 if (GNUNET_OK != init_params (mc, s, ap))
593 return GNUNET_SYSERR;
595 rsize = mysql_stmt_field_count (s->statement);
596 if (rsize > result_size)
599 return GNUNET_SYSERR;
601 if (mysql_stmt_bind_result (s->statement, results))
603 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
604 _("`%s' failed at %s:%d with error: %s\n"),
605 "mysql_stmt_bind_result", __FILE__, __LINE__,
606 mysql_stmt_error (s->statement));
607 GNUNET_MYSQL_statements_invalidate (mc);
608 return GNUNET_SYSERR;
614 ret = mysql_stmt_fetch (s->statement);
615 if (ret == MYSQL_NO_DATA)
619 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
621 _("`%s' failed at %s:%d with error: %s\n"),
622 "mysql_stmt_fetch", __FILE__, __LINE__,
623 mysql_stmt_error (s->statement));
624 GNUNET_MYSQL_statements_invalidate (mc);
625 return GNUNET_SYSERR;
628 if ( (NULL == processor) ||
629 (GNUNET_OK != processor (processor_cls, rsize, results)) )
632 mysql_stmt_reset (s->statement);
638 * Run a prepared SELECT statement.
640 * @param mc mysql context
641 * @param sh handle to SELECT statment
642 * @param result_size number of elements in results array
643 * @param results pointer to already initialized MYSQL_BIND
644 * array (of sufficient size) for passing results
645 * @param processor function to call on each result
646 * @param processor_cls extra argument to processor
647 * @param ... pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
648 * values (size + buffer-reference for pointers); terminated
650 * @return GNUNET_SYSERR on error, otherwise
651 * the number of successfully affected (or queried) rows
654 GNUNET_MYSQL_statement_run_prepared_select (struct GNUNET_MYSQL_Context *mc,
655 struct GNUNET_MYSQL_StatementHandle *sh,
656 unsigned int result_size, MYSQL_BIND * results,
657 GNUNET_MYSQL_DataProcessor processor,
658 void *processor_cls, ...)
663 va_start (ap, processor_cls);
664 ret = GNUNET_MYSQL_statement_run_prepared_select_va (mc, sh, result_size, results, processor, processor_cls, ap);
671 * Run a prepared statement that does NOT produce results.
673 * @param mc mysql context
674 * @param sh handle to statment
675 * @param insert_id NULL or address where to store the row ID of whatever
676 * was inserted (only for INSERT statements!)
677 * @param ... pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
678 * values (size + buffer-reference for pointers); terminated
680 * @return GNUNET_SYSERR on error, otherwise
681 * the number of successfully affected rows
684 GNUNET_MYSQL_statement_run_prepared (struct GNUNET_MYSQL_Context *mc,
685 struct GNUNET_MYSQL_StatementHandle *sh,
686 unsigned long long *insert_id, ...)
691 if (GNUNET_OK != prepare_statement (mc, sh))
692 return GNUNET_SYSERR;
693 va_start (ap, insert_id);
694 if (GNUNET_OK != init_params (mc, sh, ap))
697 return GNUNET_SYSERR;
700 affected = mysql_stmt_affected_rows (sh->statement);
701 if (NULL != insert_id)
702 *insert_id = (unsigned long long) mysql_stmt_insert_id (sh->statement);
703 mysql_stmt_reset (sh->statement);