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);
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);
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)
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;
439 return GNUNET_SYSERR;
441 sh->valid = GNUNET_YES;
447 * Bind the parameters for the given MySQL statement
450 * @param mc mysql context
451 * @param sh statement to bind and run
452 * @param ap arguments for the binding
453 * @return GNUNET_SYSERR on error, GNUNET_OK on success
456 init_params (struct GNUNET_MYSQL_Context *mc,
457 struct GNUNET_MYSQL_StatementHandle *sh,
460 MYSQL_BIND qbind[MAX_PARAM];
463 enum enum_field_types ft;
465 pc = mysql_stmt_param_count (sh->statement);
468 /* increase internal constant! */
470 return GNUNET_SYSERR;
472 memset (qbind, 0, sizeof (qbind));
475 while ((pc > 0) && (-1 != (int) (ft = va_arg (ap, enum enum_field_types))))
477 qbind[off].buffer_type = ft;
480 case MYSQL_TYPE_FLOAT:
481 qbind[off].buffer = va_arg (ap, float *);
484 case MYSQL_TYPE_LONGLONG:
485 qbind[off].buffer = va_arg (ap, unsigned long long *);
486 qbind[off].is_unsigned = va_arg (ap, int);
489 case MYSQL_TYPE_LONG:
490 qbind[off].buffer = va_arg (ap, unsigned int *);
491 qbind[off].is_unsigned = va_arg (ap, int);
494 case MYSQL_TYPE_VAR_STRING:
495 case MYSQL_TYPE_STRING:
496 case MYSQL_TYPE_BLOB:
497 qbind[off].buffer = va_arg (ap, void *);
498 qbind[off].buffer_length = va_arg (ap, unsigned long);
499 qbind[off].length = va_arg (ap, unsigned long *);
503 /* unsupported type */
505 return GNUNET_SYSERR;
510 if (!((pc == 0) && (-1 != (int) ft) && (va_arg (ap, int) == -1)))
513 return GNUNET_SYSERR;
515 if (mysql_stmt_bind_param (sh->statement, qbind))
517 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
519 _("`%s' failed at %s:%d with error: %s\n"),
520 "mysql_stmt_bind_param", __FILE__, __LINE__,
521 mysql_stmt_error (sh->statement));
523 return GNUNET_SYSERR;
525 if (mysql_stmt_execute (sh->statement))
527 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
529 _("`%s' failed at %s:%d with error: %s\n"),
530 "mysql_stmt_execute", __FILE__, __LINE__,
531 mysql_stmt_error (sh->statement));
533 return GNUNET_SYSERR;
540 * Run a prepared SELECT statement.
542 * @param mc mysql context
543 * @param sh handle to SELECT statment
544 * @param result_size number of elements in results array
545 * @param results pointer to already initialized MYSQL_BIND
546 * array (of sufficient size) for passing results
547 * @param processor function to call on each result
548 * @param processor_cls extra argument to processor
549 * @param ... pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
550 * values (size + buffer-reference for pointers); terminated
552 * @return GNUNET_SYSERR on error, otherwise
553 * the number of successfully affected (or queried) rows
556 GNUNET_MYSQL_statement_run_prepared_select (struct GNUNET_MYSQL_Context *mc,
557 struct GNUNET_MYSQL_StatementHandle *sh,
558 unsigned int result_size, MYSQL_BIND * results,
559 GNUNET_MYSQL_DataProcessor processor,
560 void *processor_cls, ...)
567 if (GNUNET_OK != prepare_statement (mc, sh))
570 return GNUNET_SYSERR;
572 va_start (ap, processor_cls);
573 if (GNUNET_OK != init_params (mc, sh, ap))
577 return GNUNET_SYSERR;
580 rsize = mysql_stmt_field_count (sh->statement);
581 if (rsize > result_size)
584 return GNUNET_SYSERR;
586 if (mysql_stmt_bind_result (sh->statement, results))
588 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
590 _("`%s' failed at %s:%d with error: %s\n"),
591 "mysql_stmt_bind_result", __FILE__, __LINE__,
592 mysql_stmt_error (sh->statement));
594 return GNUNET_SYSERR;
600 ret = mysql_stmt_fetch (sh->statement);
601 if (ret == MYSQL_NO_DATA)
605 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
607 _("`%s' failed at %s:%d with error: %s\n"),
608 "mysql_stmt_fetch", __FILE__, __LINE__,
609 mysql_stmt_error (sh->statement));
611 return GNUNET_SYSERR;
613 if (processor != NULL)
614 if (GNUNET_OK != processor (processor_cls, rsize, results))
618 mysql_stmt_reset (sh->statement);
624 * Run a prepared statement that does NOT produce results.
626 * @param mc mysql context
627 * @param sh handle to statment
628 * @param insert_id NULL or address where to store the row ID of whatever
629 * was inserted (only for INSERT statements!)
630 * @param ... pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
631 * values (size + buffer-reference for pointers); terminated
633 * @return GNUNET_SYSERR on error, otherwise
634 * the number of successfully affected rows
637 GNUNET_MYSQL_statement_run_prepared (struct GNUNET_MYSQL_Context *mc,
638 struct GNUNET_MYSQL_StatementHandle *sh,
639 unsigned long long *insert_id, ...)
644 if (GNUNET_OK != prepare_statement (mc, sh))
645 return GNUNET_SYSERR;
646 va_start (ap, insert_id);
647 if (GNUNET_OK != init_params (mc, sh, ap))
650 return GNUNET_SYSERR;
653 affected = mysql_stmt_affected_rows (sh->statement);
654 if (NULL != insert_id)
655 *insert_id = (unsigned long long) mysql_stmt_insert_id (sh->statement);
656 mysql_stmt_reset (sh->statement);