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 iclose (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;
355 while (NULL != (sh = mc->shead))
357 GNUNET_CONTAINER_DLL_remove (mc->shead, mc->stail, sh);
358 GNUNET_free (sh->query);
366 * Prepare a statement. Prepared statements are automatically discarded
367 * when the MySQL context is destroyed.
369 * @param mc mysql context
370 * @param query query text
371 * @return prepared statement, NULL on error
373 struct GNUNET_MYSQL_StatementHandle *
374 GNUNET_MYSQL_statement_prepare (struct GNUNET_MYSQL_Context *mc,
377 struct GNUNET_MYSQL_StatementHandle *sh;
379 sh = GNUNET_malloc (sizeof (struct GNUNET_MYSQL_StatementHandle));
380 sh->query = GNUNET_strdup (query);
381 GNUNET_CONTAINER_DLL_insert (mc->shead, mc->stail, sh);
387 * Run a SQL statement.
389 * @param mc mysql context
390 * @param sql SQL statement to run
391 * @return GNUNET_OK on success
392 * GNUNET_SYSERR if there was a problem
395 GNUNET_MYSQL_statement_run (struct GNUNET_MYSQL_Context *mc,
398 if ((NULL == mc->dbf) && (GNUNET_OK != iopen (mc)))
399 return GNUNET_SYSERR;
400 mysql_query (mc->dbf, sql);
401 if (mysql_error (mc->dbf)[0])
403 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_query", mc);
405 return GNUNET_SYSERR;
412 * Prepare a statement for running.
414 * @param mc mysql context
415 * @param sh statement handle to prepare
416 * @return GNUNET_OK on success
419 prepare_statement (struct GNUNET_MYSQL_Context *mc,
420 struct GNUNET_MYSQL_StatementHandle *sh)
422 if (GNUNET_YES == sh->valid)
424 if ((NULL == mc->dbf) && (GNUNET_OK != iopen (mc)))
425 return GNUNET_SYSERR;
426 sh->statement = mysql_stmt_init (mc->dbf);
427 if (NULL == sh->statement)
430 return GNUNET_SYSERR;
432 if (0 != mysql_stmt_prepare (sh->statement, sh->query, strlen (sh->query)))
434 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_stmt_prepare", mc);
435 mysql_stmt_close (sh->statement);
436 sh->statement = NULL;
438 return GNUNET_SYSERR;
440 sh->valid = GNUNET_YES;
446 * Bind the parameters for the given MySQL statement
449 * @param mc mysql context
450 * @param sh statement to bind and run
451 * @param ap arguments for the binding
452 * @return GNUNET_SYSERR on error, GNUNET_OK on success
455 init_params (struct GNUNET_MYSQL_Context *mc,
456 struct GNUNET_MYSQL_StatementHandle *sh,
459 MYSQL_BIND qbind[MAX_PARAM];
462 enum enum_field_types ft;
464 pc = mysql_stmt_param_count (sh->statement);
467 /* increase internal constant! */
469 return GNUNET_SYSERR;
471 memset (qbind, 0, sizeof (qbind));
474 while ((pc > 0) && (-1 != (int) (ft = va_arg (ap, enum enum_field_types))))
476 qbind[off].buffer_type = ft;
479 case MYSQL_TYPE_FLOAT:
480 qbind[off].buffer = va_arg (ap, float *);
483 case MYSQL_TYPE_LONGLONG:
484 qbind[off].buffer = va_arg (ap, unsigned long long *);
485 qbind[off].is_unsigned = va_arg (ap, int);
488 case MYSQL_TYPE_LONG:
489 qbind[off].buffer = va_arg (ap, unsigned int *);
490 qbind[off].is_unsigned = va_arg (ap, int);
493 case MYSQL_TYPE_VAR_STRING:
494 case MYSQL_TYPE_STRING:
495 case MYSQL_TYPE_BLOB:
496 qbind[off].buffer = va_arg (ap, void *);
497 qbind[off].buffer_length = va_arg (ap, unsigned long);
498 qbind[off].length = va_arg (ap, unsigned long *);
502 /* unsupported type */
504 return GNUNET_SYSERR;
509 if (!((pc == 0) && (-1 != (int) ft) && (va_arg (ap, int) == -1)))
512 return GNUNET_SYSERR;
514 if (mysql_stmt_bind_param (sh->statement, qbind))
516 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
518 _("`%s' failed at %s:%d with error: %s\n"),
519 "mysql_stmt_bind_param", __FILE__, __LINE__,
520 mysql_stmt_error (sh->statement));
522 return GNUNET_SYSERR;
524 if (mysql_stmt_execute (sh->statement))
526 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
528 _("`%s' failed at %s:%d with error: %s\n"),
529 "mysql_stmt_execute", __FILE__, __LINE__,
530 mysql_stmt_error (sh->statement));
532 return GNUNET_SYSERR;
539 * Run a prepared SELECT statement.
541 * @param mc mysql context
542 * @param sh handle to SELECT statment
543 * @param result_size number of elements in results array
544 * @param results pointer to already initialized MYSQL_BIND
545 * array (of sufficient size) for passing results
546 * @param processor function to call on each result
547 * @param processor_cls extra argument to processor
548 * @param ... pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
549 * values (size + buffer-reference for pointers); terminated
551 * @return GNUNET_SYSERR on error, otherwise
552 * the number of successfully affected (or queried) rows
555 GNUNET_MYSQL_statement_run_prepared_select (struct GNUNET_MYSQL_Context *mc,
556 struct GNUNET_MYSQL_StatementHandle *sh,
557 unsigned int result_size, MYSQL_BIND * results,
558 GNUNET_MYSQL_DataProcessor processor,
559 void *processor_cls, ...)
566 if (GNUNET_OK != prepare_statement (mc, sh))
569 return GNUNET_SYSERR;
571 va_start (ap, processor_cls);
572 if (GNUNET_OK != init_params (mc, sh, ap))
576 return GNUNET_SYSERR;
579 rsize = mysql_stmt_field_count (sh->statement);
580 if (rsize > result_size)
583 return GNUNET_SYSERR;
585 if (mysql_stmt_bind_result (sh->statement, results))
587 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
589 _("`%s' failed at %s:%d with error: %s\n"),
590 "mysql_stmt_bind_result", __FILE__, __LINE__,
591 mysql_stmt_error (sh->statement));
593 return GNUNET_SYSERR;
599 ret = mysql_stmt_fetch (sh->statement);
600 if (ret == MYSQL_NO_DATA)
604 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
606 _("`%s' failed at %s:%d with error: %s\n"),
607 "mysql_stmt_fetch", __FILE__, __LINE__,
608 mysql_stmt_error (sh->statement));
610 return GNUNET_SYSERR;
612 if (processor != NULL)
613 if (GNUNET_OK != processor (processor_cls, rsize, results))
617 mysql_stmt_reset (sh->statement);
623 * Run a prepared statement that does NOT produce results.
625 * @param mc mysql context
626 * @param sh handle to statment
627 * @param insert_id NULL or address where to store the row ID of whatever
628 * was inserted (only for INSERT statements!)
629 * @param ... pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
630 * values (size + buffer-reference for pointers); terminated
632 * @return GNUNET_SYSERR on error, otherwise
633 * the number of successfully affected rows
636 GNUNET_MYSQL_statement_run_prepared (struct GNUNET_MYSQL_Context *mc,
637 struct GNUNET_MYSQL_StatementHandle *sh,
638 unsigned long long *insert_id, ...)
643 if (GNUNET_OK != prepare_statement (mc, sh))
644 return GNUNET_SYSERR;
645 va_start (ap, insert_id);
646 if (GNUNET_OK != init_params (mc, sh, ap))
649 return GNUNET_SYSERR;
652 affected = mysql_stmt_affected_rows (sh->statement);
653 if (NULL != insert_id)
654 *insert_id = (unsigned long long) mysql_stmt_insert_id (sh->statement);
655 mysql_stmt_reset (sh->statement);