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 * @param section the section
129 * @return NULL on error
132 get_my_cnf_path (const struct GNUNET_CONFIGURATION_Handle *cfg,
145 pw = getpwuid (getuid ());
148 GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_ERROR, "mysql", "getpwuid");
151 if (GNUNET_YES == GNUNET_CONFIGURATION_have_value (cfg, section, "CONFIG"))
153 GNUNET_assert (GNUNET_OK ==
154 GNUNET_CONFIGURATION_get_value_filename (cfg, section,
157 configured = GNUNET_YES;
161 home_dir = GNUNET_strdup (pw->pw_dir);
162 GNUNET_asprintf (&cnffile, "%s/.my.cnf", home_dir);
163 GNUNET_free (home_dir);
164 configured = GNUNET_NO;
167 home_dir = (char *) GNUNET_malloc (_MAX_PATH + 1);
168 plibc_conv_to_win_path ("~/", home_dir);
169 GNUNET_asprintf (&cnffile, "%s/.my.cnf", home_dir);
170 GNUNET_free (home_dir);
171 configured = GNUNET_NO;
173 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "mysql",
174 _("Trying to use file `%s' for MySQL configuration.\n"),
176 if ((0 != STAT (cnffile, &st)) || (0 != ACCESS (cnffile, R_OK)) ||
177 (!S_ISREG (st.st_mode)))
179 if (configured == GNUNET_YES)
180 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "mysql",
181 _("Could not access file `%s': %s\n"), cnffile,
183 GNUNET_free (cnffile);
191 * Open the connection with the database (and initialize
192 * our default options).
194 * @param mc database context to initialze
195 * @return GNUNET_OK on success
198 iopen (struct GNUNET_MYSQL_Context *mc)
203 char *mysql_password;
204 unsigned long long mysql_port;
206 unsigned int timeout;
208 mc->dbf = mysql_init (NULL);
210 return GNUNET_SYSERR;
211 if (mc->cnffile != NULL)
212 mysql_options (mc->dbf, MYSQL_READ_DEFAULT_FILE, mc->cnffile);
213 mysql_options (mc->dbf, MYSQL_READ_DEFAULT_GROUP, "client");
215 mysql_options (mc->dbf, MYSQL_OPT_RECONNECT, &reconnect);
216 mysql_options (mc->dbf, MYSQL_OPT_CONNECT_TIMEOUT, (const void *) &timeout);
217 mysql_options (mc->dbf, MYSQL_SET_CHARSET_NAME, "UTF8");
218 timeout = 60; /* in seconds */
219 mysql_options (mc->dbf, MYSQL_OPT_READ_TIMEOUT, (const void *) &timeout);
220 mysql_options (mc->dbf, MYSQL_OPT_WRITE_TIMEOUT, (const void *) &timeout);
223 GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section, "DATABASE"))
224 GNUNET_assert (GNUNET_OK ==
225 GNUNET_CONFIGURATION_get_value_string (mc->cfg, mc->section,
229 mysql_dbname = GNUNET_strdup ("gnunet");
232 GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section, "USER"))
234 GNUNET_assert (GNUNET_OK ==
235 GNUNET_CONFIGURATION_get_value_string (mc->cfg, mc->section,
236 "USER", &mysql_user));
238 mysql_password = NULL;
240 GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section, "PASSWORD"))
242 GNUNET_assert (GNUNET_OK ==
243 GNUNET_CONFIGURATION_get_value_string (mc->cfg, mc->section,
249 GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section, "HOST"))
251 GNUNET_assert (GNUNET_OK ==
252 GNUNET_CONFIGURATION_get_value_string (mc->cfg, mc->section,
258 GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section, "PORT"))
260 GNUNET_assert (GNUNET_OK ==
261 GNUNET_CONFIGURATION_get_value_number (mc->cfg, mc->section,
262 "PORT", &mysql_port));
265 GNUNET_assert (mysql_dbname != NULL);
266 mysql_real_connect (mc->dbf, mysql_server, mysql_user, mysql_password,
267 mysql_dbname, (unsigned int) mysql_port, NULL,
268 CLIENT_IGNORE_SIGPIPE);
269 GNUNET_free_non_null (mysql_server);
270 GNUNET_free_non_null (mysql_user);
271 GNUNET_free_non_null (mysql_password);
272 GNUNET_free (mysql_dbname);
273 if (mysql_error (mc->dbf)[0])
275 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_real_connect", mc);
276 return GNUNET_SYSERR;
283 * Create a mysql context.
285 * @param cfg configuration
286 * @param section configuration section to use to get MySQL configuration options
287 * @return the mysql context
289 struct GNUNET_MYSQL_Context *
290 GNUNET_MYSQL_context_create (const struct GNUNET_CONFIGURATION_Handle *cfg,
293 struct GNUNET_MYSQL_Context *mc;
295 mc = GNUNET_new (struct GNUNET_MYSQL_Context);
297 mc->section = section;
298 mc->cnffile = get_my_cnf_path (cfg, section);
305 * Close database connection and all prepared statements (we got a DB
308 * @param mc mysql context
311 GNUNET_MYSQL_statements_invalidate (struct GNUNET_MYSQL_Context *mc)
313 struct GNUNET_MYSQL_StatementHandle *sh;
315 for (sh = mc->shead; NULL != sh; sh = sh->next)
317 if (GNUNET_YES == sh->valid)
319 mysql_stmt_close (sh->statement);
320 sh->valid = GNUNET_NO;
322 sh->statement = NULL;
326 mysql_close (mc->dbf);
333 * Destroy a mysql context. Also frees all associated prepared statements.
335 * @param mc context to destroy
338 GNUNET_MYSQL_context_destroy (struct GNUNET_MYSQL_Context *mc)
340 struct GNUNET_MYSQL_StatementHandle *sh;
342 GNUNET_MYSQL_statements_invalidate (mc);
343 while (NULL != (sh = mc->shead))
345 GNUNET_CONTAINER_DLL_remove (mc->shead, mc->stail, sh);
346 GNUNET_free (sh->query);
350 mysql_library_end ();
355 * Prepare a statement. Prepared statements are automatically discarded
356 * when the MySQL context is destroyed.
358 * @param mc mysql context
359 * @param query query text
360 * @return prepared statement, NULL on error
362 struct GNUNET_MYSQL_StatementHandle *
363 GNUNET_MYSQL_statement_prepare (struct GNUNET_MYSQL_Context *mc,
366 struct GNUNET_MYSQL_StatementHandle *sh;
368 sh = GNUNET_new (struct GNUNET_MYSQL_StatementHandle);
369 sh->query = GNUNET_strdup (query);
370 GNUNET_CONTAINER_DLL_insert (mc->shead, mc->stail, sh);
376 * Run a SQL statement.
378 * @param mc mysql context
379 * @param sql SQL statement to run
380 * @return GNUNET_OK on success
381 * GNUNET_SYSERR if there was a problem
384 GNUNET_MYSQL_statement_run (struct GNUNET_MYSQL_Context *mc, const char *sql)
386 if ((NULL == mc->dbf) && (GNUNET_OK != iopen (mc)))
387 return GNUNET_SYSERR;
388 mysql_query (mc->dbf, sql);
389 if (mysql_error (mc->dbf)[0])
391 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_query", mc);
392 GNUNET_MYSQL_statements_invalidate (mc);
393 return GNUNET_SYSERR;
400 * Prepare a statement for running.
402 * @param mc mysql context
403 * @param sh statement handle to prepare
404 * @return GNUNET_OK on success
407 prepare_statement (struct GNUNET_MYSQL_Context *mc,
408 struct GNUNET_MYSQL_StatementHandle *sh)
410 if (GNUNET_YES == sh->valid)
412 if ((NULL == mc->dbf) && (GNUNET_OK != iopen (mc)))
413 return GNUNET_SYSERR;
414 sh->statement = mysql_stmt_init (mc->dbf);
415 if (NULL == sh->statement)
417 GNUNET_MYSQL_statements_invalidate (mc);
418 return GNUNET_SYSERR;
420 if (0 != mysql_stmt_prepare (sh->statement, sh->query, strlen (sh->query)))
422 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_stmt_prepare", mc);
423 mysql_stmt_close (sh->statement);
424 sh->statement = NULL;
425 GNUNET_MYSQL_statements_invalidate (mc);
426 return GNUNET_SYSERR;
428 sh->valid = GNUNET_YES;
434 * Get internal handle for a prepared statement. This function should rarely
435 * be used, and if, with caution! On failures during the interaction with
436 * the handle, you must call 'GNUNET_MYSQL_statements_invalidate'!
438 * @param mc mysql context
439 * @param sh prepared statement to introspect
440 * @return MySQL statement handle, NULL on error
443 GNUNET_MYSQL_statement_get_stmt (struct GNUNET_MYSQL_Context * mc,
444 struct GNUNET_MYSQL_StatementHandle * sh)
446 (void) prepare_statement (mc, sh);
447 return sh->statement;
452 * Bind the parameters for the given MySQL statement
455 * @param mc mysql context
456 * @param sh statement to bind and run
457 * @param ap arguments for the binding
458 * @return GNUNET_SYSERR on error, GNUNET_OK on success
461 init_params (struct GNUNET_MYSQL_Context *mc,
462 struct GNUNET_MYSQL_StatementHandle *sh, va_list ap)
464 MYSQL_BIND qbind[MAX_PARAM];
467 enum enum_field_types ft;
469 pc = mysql_stmt_param_count (sh->statement);
472 /* increase internal constant! */
474 return GNUNET_SYSERR;
476 memset (qbind, 0, sizeof (qbind));
479 while ((pc > 0) && (-1 != (int) (ft = va_arg (ap, enum enum_field_types))))
481 qbind[off].buffer_type = ft;
484 case MYSQL_TYPE_FLOAT:
485 qbind[off].buffer = va_arg (ap, float *);
488 case MYSQL_TYPE_LONGLONG:
489 qbind[off].buffer = va_arg (ap, unsigned long long *);
490 qbind[off].is_unsigned = va_arg (ap, int);
493 case MYSQL_TYPE_LONG:
494 qbind[off].buffer = va_arg (ap, unsigned int *);
495 qbind[off].is_unsigned = va_arg (ap, int);
498 case MYSQL_TYPE_VAR_STRING:
499 case MYSQL_TYPE_STRING:
500 case MYSQL_TYPE_BLOB:
501 qbind[off].buffer = va_arg (ap, void *);
502 qbind[off].buffer_length = va_arg (ap, unsigned long);
503 qbind[off].length = va_arg (ap, unsigned long *);
507 /* unsupported type */
509 return GNUNET_SYSERR;
514 if (!((pc == 0) && (-1 != (int) ft) && (va_arg (ap, int) == -1)))
517 return GNUNET_SYSERR;
519 if (mysql_stmt_bind_param (sh->statement, qbind))
521 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "mysql",
522 _("`%s' failed at %s:%d with error: %s\n"),
523 "mysql_stmt_bind_param", __FILE__, __LINE__,
524 mysql_stmt_error (sh->statement));
525 GNUNET_MYSQL_statements_invalidate (mc);
526 return GNUNET_SYSERR;
528 if (mysql_stmt_execute (sh->statement))
530 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "mysql",
531 _("`%s' failed at %s:%d with error: %s\n"),
532 "mysql_stmt_execute", __FILE__, __LINE__,
533 mysql_stmt_error (sh->statement));
534 GNUNET_MYSQL_statements_invalidate (mc);
535 return GNUNET_SYSERR;
543 * Run a prepared SELECT statement.
545 * @param mc mysql context
546 * @param s statement to run
547 * @param result_size number of elements in results array
548 * @param results pointer to already initialized MYSQL_BIND
549 * array (of sufficient size) for passing results
550 * @param processor function to call on each result
551 * @param processor_cls extra argument to processor
552 * @param ap pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
553 * values (size + buffer-reference for pointers); terminated
555 * @return GNUNET_SYSERR on error, otherwise
556 * the number of successfully affected (or queried) rows
559 GNUNET_MYSQL_statement_run_prepared_select_va (struct GNUNET_MYSQL_Context *mc,
561 GNUNET_MYSQL_StatementHandle *s,
562 unsigned int result_size,
563 MYSQL_BIND * results,
564 GNUNET_MYSQL_DataProcessor
565 processor, void *processor_cls,
572 if (GNUNET_OK != prepare_statement (mc, s))
575 return GNUNET_SYSERR;
577 if (GNUNET_OK != init_params (mc, s, ap))
580 return GNUNET_SYSERR;
582 rsize = mysql_stmt_field_count (s->statement);
583 if (rsize > result_size)
586 return GNUNET_SYSERR;
588 if (mysql_stmt_bind_result (s->statement, results))
590 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
591 _("`%s' failed at %s:%d with error: %s\n"),
592 "mysql_stmt_bind_result", __FILE__, __LINE__,
593 mysql_stmt_error (s->statement));
594 GNUNET_MYSQL_statements_invalidate (mc);
595 return GNUNET_SYSERR;
601 ret = mysql_stmt_fetch (s->statement);
602 if (ret == MYSQL_NO_DATA)
606 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "mysql",
607 _("`%s' failed at %s:%d with error: %s\n"),
608 "mysql_stmt_fetch", __FILE__, __LINE__,
609 mysql_stmt_error (s->statement));
610 GNUNET_MYSQL_statements_invalidate (mc);
611 return GNUNET_SYSERR;
614 if ((NULL == processor) ||
615 (GNUNET_OK != processor (processor_cls, rsize, results)))
618 mysql_stmt_reset (s->statement);
624 * Run a prepared SELECT statement.
626 * @param mc mysql context
627 * @param sh handle to SELECT statment
628 * @param result_size number of elements in results array
629 * @param results pointer to already initialized MYSQL_BIND
630 * array (of sufficient size) for passing results
631 * @param processor function to call on each result
632 * @param processor_cls extra argument to processor
633 * @param ... pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
634 * values (size + buffer-reference for pointers); terminated
636 * @return GNUNET_SYSERR on error, otherwise
637 * the number of successfully affected (or queried) rows
640 GNUNET_MYSQL_statement_run_prepared_select (struct GNUNET_MYSQL_Context *mc,
641 struct GNUNET_MYSQL_StatementHandle
642 *sh, unsigned int result_size,
643 MYSQL_BIND * results,
644 GNUNET_MYSQL_DataProcessor
645 processor, void *processor_cls, ...)
650 va_start (ap, processor_cls);
652 GNUNET_MYSQL_statement_run_prepared_select_va (mc, sh, result_size,
661 * Run a prepared statement that does NOT produce results.
663 * @param mc mysql context
664 * @param sh handle to statment
665 * @param insert_id NULL or address where to store the row ID of whatever
666 * was inserted (only for INSERT statements!)
667 * @param ... pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
668 * values (size + buffer-reference for pointers); terminated
670 * @return GNUNET_SYSERR on error, otherwise
671 * the number of successfully affected rows
674 GNUNET_MYSQL_statement_run_prepared (struct GNUNET_MYSQL_Context *mc,
675 struct GNUNET_MYSQL_StatementHandle *sh,
676 unsigned long long *insert_id, ...)
681 if (GNUNET_OK != prepare_statement (mc, sh))
682 return GNUNET_SYSERR;
683 va_start (ap, insert_id);
684 if (GNUNET_OK != init_params (mc, sh, ap))
687 return GNUNET_SYSERR;
690 affected = mysql_stmt_affected_rows (sh->statement);
691 if (NULL != insert_id)
692 *insert_id = (unsigned long long) mysql_stmt_insert_id (sh->statement);
693 mysql_stmt_reset (sh->statement);