uncrustify as demanded.
[oweals/gnunet.git] / src / mysql / mysql.c
1
2 /*
3      This file is part of GNUnet
4      Copyright (C) 2012 GNUnet e.V.
5
6      GNUnet is free software: you can redistribute it and/or modify it
7      under the terms of the GNU Affero General Public License as published
8      by the Free Software Foundation, either version 3 of the License,
9      or (at your option) any later version.
10
11      GNUnet is distributed in the hope that it will be useful, but
12      WITHOUT ANY WARRANTY; without even the implied warranty of
13      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14      Affero General Public License for more details.
15
16      You should have received a copy of the GNU Affero General Public License
17      along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19      SPDX-License-Identifier: AGPL3.0-or-later
20  */
21 /**
22  * @file mysql/mysql.c
23  * @brief library to help with access to a MySQL database
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include <mysql/mysql.h>
28 #include "gnunet_mysql_lib.h"
29
30 /**
31  * Maximum number of supported parameters for a prepared
32  * statement.  Increase if needed.
33  */
34 #define MAX_PARAM 16
35
36
37 /**
38  * Die with an error message that indicates
39  * a failure of the command 'cmd' with the message given
40  * by strerror(errno).
41  */
42 #define DIE_MYSQL(cmd, dbh)                                       \
43   do                                                              \
44     {                                                               \
45       GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR,                     \
46                       "mysql",                                     \
47                       _("`%s' failed at %s:%d with error: %s\n"), \
48                       cmd,                                         \
49                       __FILE__,                                    \
50                       __LINE__,                                    \
51                       mysql_error((dbh)->dbf));                   \
52       GNUNET_assert(0);                                            \
53     } while (0);
54
55 /**
56  * Log an error message at log-level 'level' that indicates
57  * a failure of the command 'cmd' on file 'filename'
58  * with the message given by strerror(errno).
59  */
60 #define LOG_MYSQL(level, cmd, dbh)                                \
61   do                                                              \
62     {                                                               \
63       GNUNET_log_from(level,                                       \
64                       "mysql",                                     \
65                       _("`%s' failed at %s:%d with error: %s\n"), \
66                       cmd,                                         \
67                       __FILE__,                                    \
68                       __LINE__,                                    \
69                       mysql_error((dbh)->dbf));                   \
70     } while (0);
71
72
73 /**
74  * Mysql context.
75  */
76 struct GNUNET_MYSQL_Context {
77   /**
78    * Our configuration.
79    */
80   const struct GNUNET_CONFIGURATION_Handle *cfg;
81
82   /**
83    * Our section.
84    */
85   const char *section;
86
87   /**
88    * Handle to the mysql database.
89    */
90   MYSQL *dbf;
91
92   /**
93    * Head of list of our prepared statements.
94    */
95   struct GNUNET_MYSQL_StatementHandle *shead;
96
97   /**
98    * Tail of list of our prepared statements.
99    */
100   struct GNUNET_MYSQL_StatementHandle *stail;
101
102   /**
103    * Filename of "my.cnf" (msyql configuration).
104    */
105   char *cnffile;
106 };
107
108
109 /**
110  * Handle for a prepared statement.
111  */
112 struct GNUNET_MYSQL_StatementHandle {
113   /**
114    * Kept in a DLL.
115    */
116   struct GNUNET_MYSQL_StatementHandle *next;
117
118   /**
119    * Kept in a DLL.
120    */
121   struct GNUNET_MYSQL_StatementHandle *prev;
122
123   /**
124    * Mysql Context the statement handle belongs to.
125    */
126   struct GNUNET_MYSQL_Context *mc;
127
128   /**
129    * Original query string.
130    */
131   char *query;
132
133   /**
134    * Handle to MySQL prepared statement.
135    */
136   MYSQL_STMT *statement;
137
138   /**
139    * Is the MySQL prepared statement valid, or do we need to re-initialize it?
140    */
141   int valid;
142 };
143
144
145 /**
146  * Obtain the location of ".my.cnf".
147  *
148  * @param cfg our configuration
149  * @param section the section
150  * @return NULL on error
151  */
152 static char *
153 get_my_cnf_path(const struct GNUNET_CONFIGURATION_Handle *cfg,
154                 const char *section)
155 {
156   char *cnffile;
157   char *home_dir;
158   struct stat st;
159
160 #ifndef WINDOWS
161   struct passwd *pw;
162 #endif
163   int configured;
164
165 #ifndef WINDOWS
166   pw = getpwuid(getuid());
167   if (!pw)
168     {
169       GNUNET_log_from_strerror(GNUNET_ERROR_TYPE_ERROR, "mysql", "getpwuid");
170       return NULL;
171     }
172   if (GNUNET_YES == GNUNET_CONFIGURATION_have_value(cfg, section, "CONFIG"))
173     {
174       GNUNET_assert(GNUNET_OK ==
175                     GNUNET_CONFIGURATION_get_value_filename(cfg,
176                                                             section,
177                                                             "CONFIG",
178                                                             &cnffile));
179       configured = GNUNET_YES;
180     }
181   else
182     {
183       home_dir = GNUNET_strdup(pw->pw_dir);
184       GNUNET_asprintf(&cnffile, "%s/.my.cnf", home_dir);
185       GNUNET_free(home_dir);
186       configured = GNUNET_NO;
187     }
188 #else
189   home_dir = (char *)GNUNET_malloc(_MAX_PATH + 1);
190   plibc_conv_to_win_path("~/", home_dir);
191   GNUNET_asprintf(&cnffile, "%s/.my.cnf", home_dir);
192   GNUNET_free(home_dir);
193   configured = GNUNET_NO;
194 #endif
195   GNUNET_log_from(GNUNET_ERROR_TYPE_INFO,
196                   "mysql",
197                   _("Trying to use file `%s' for MySQL configuration.\n"),
198                   cnffile);
199   if ((0 != STAT(cnffile, &st)) || (0 != ACCESS(cnffile, R_OK)) ||
200       (!S_ISREG(st.st_mode)))
201     {
202       if (configured == GNUNET_YES)
203         GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR,
204                         "mysql",
205                         _("Could not access file `%s': %s\n"),
206                         cnffile,
207                         strerror(errno));
208       GNUNET_free(cnffile);
209       return NULL;
210     }
211   return cnffile;
212 }
213
214
215 /**
216  * Open the connection with the database (and initialize
217  * our default options).
218  *
219  * @param mc database context to initialze
220  * @return #GNUNET_OK on success
221  */
222 static int
223 iopen(struct GNUNET_MYSQL_Context *mc)
224 {
225   char *mysql_dbname;
226   char *mysql_server;
227   char *mysql_user;
228   char *mysql_password;
229   unsigned long long mysql_port;
230   my_bool reconnect;
231   unsigned int timeout;
232
233   mc->dbf = mysql_init(NULL);
234   if (mc->dbf == NULL)
235     return GNUNET_SYSERR;
236   if (mc->cnffile != NULL)
237     mysql_options(mc->dbf, MYSQL_READ_DEFAULT_FILE, mc->cnffile);
238   mysql_options(mc->dbf, MYSQL_READ_DEFAULT_GROUP, "client");
239   reconnect = 0;
240   mysql_options(mc->dbf, MYSQL_OPT_RECONNECT, &reconnect);
241   mysql_options(mc->dbf, MYSQL_OPT_CONNECT_TIMEOUT, (const void *)&timeout);
242   mysql_options(mc->dbf, MYSQL_SET_CHARSET_NAME, "UTF8");
243   timeout = 60; /* in seconds */
244   mysql_options(mc->dbf, MYSQL_OPT_READ_TIMEOUT, (const void *)&timeout);
245   mysql_options(mc->dbf, MYSQL_OPT_WRITE_TIMEOUT, (const void *)&timeout);
246   mysql_dbname = NULL;
247   if (GNUNET_YES ==
248       GNUNET_CONFIGURATION_have_value(mc->cfg, mc->section, "DATABASE"))
249     GNUNET_assert(GNUNET_OK ==
250                   GNUNET_CONFIGURATION_get_value_string(mc->cfg,
251                                                         mc->section,
252                                                         "DATABASE",
253                                                         &mysql_dbname));
254   else
255     mysql_dbname = GNUNET_strdup("gnunet");
256   mysql_user = NULL;
257   if (GNUNET_YES ==
258       GNUNET_CONFIGURATION_have_value(mc->cfg, mc->section, "USER"))
259     {
260       GNUNET_assert(GNUNET_OK ==
261                     GNUNET_CONFIGURATION_get_value_string(mc->cfg,
262                                                           mc->section,
263                                                           "USER",
264                                                           &mysql_user));
265     }
266   mysql_password = NULL;
267   if (GNUNET_YES ==
268       GNUNET_CONFIGURATION_have_value(mc->cfg, mc->section, "PASSWORD"))
269     {
270       GNUNET_assert(GNUNET_OK ==
271                     GNUNET_CONFIGURATION_get_value_string(mc->cfg,
272                                                           mc->section,
273                                                           "PASSWORD",
274                                                           &mysql_password));
275     }
276   mysql_server = NULL;
277   if (GNUNET_YES ==
278       GNUNET_CONFIGURATION_have_value(mc->cfg, mc->section, "HOST"))
279     {
280       GNUNET_assert(GNUNET_OK ==
281                     GNUNET_CONFIGURATION_get_value_string(mc->cfg,
282                                                           mc->section,
283                                                           "HOST",
284                                                           &mysql_server));
285     }
286   mysql_port = 0;
287   if (GNUNET_YES ==
288       GNUNET_CONFIGURATION_have_value(mc->cfg, mc->section, "PORT"))
289     {
290       GNUNET_assert(GNUNET_OK ==
291                     GNUNET_CONFIGURATION_get_value_number(mc->cfg,
292                                                           mc->section,
293                                                           "PORT",
294                                                           &mysql_port));
295     }
296
297   GNUNET_assert(mysql_dbname != NULL);
298   mysql_real_connect(mc->dbf,
299                      mysql_server,
300                      mysql_user,
301                      mysql_password,
302                      mysql_dbname,
303                      (unsigned int)mysql_port,
304                      NULL,
305                      CLIENT_IGNORE_SIGPIPE);
306   GNUNET_free_non_null(mysql_server);
307   GNUNET_free_non_null(mysql_user);
308   GNUNET_free_non_null(mysql_password);
309   GNUNET_free(mysql_dbname);
310   if (mysql_error(mc->dbf)[0])
311     {
312       LOG_MYSQL(GNUNET_ERROR_TYPE_ERROR, "mysql_real_connect", mc);
313       return GNUNET_SYSERR;
314     }
315   return GNUNET_OK;
316 }
317
318
319 /**
320  * Create a mysql context.
321  *
322  * @param cfg configuration
323  * @param section configuration section to use to get MySQL configuration options
324  * @return the mysql context
325  */
326 struct GNUNET_MYSQL_Context *
327 GNUNET_MYSQL_context_create(const struct GNUNET_CONFIGURATION_Handle *cfg,
328                             const char *section)
329 {
330   struct GNUNET_MYSQL_Context *mc;
331
332   mc = GNUNET_new(struct GNUNET_MYSQL_Context);
333   mc->cfg = cfg;
334   mc->section = section;
335   mc->cnffile = get_my_cnf_path(cfg, section);
336
337   return mc;
338 }
339
340
341 /**
342  * Close database connection and all prepared statements (we got a DB
343  * error).
344  *
345  * @param mc mysql context
346  */
347 void
348 GNUNET_MYSQL_statements_invalidate(struct GNUNET_MYSQL_Context *mc)
349 {
350   struct GNUNET_MYSQL_StatementHandle *sh;
351
352   for (sh = mc->shead; NULL != sh; sh = sh->next)
353     {
354       if (GNUNET_YES == sh->valid)
355         {
356           mysql_stmt_close(sh->statement);
357           sh->valid = GNUNET_NO;
358         }
359       sh->statement = NULL;
360     }
361   if (NULL != mc->dbf)
362     {
363       mysql_close(mc->dbf);
364       mc->dbf = NULL;
365     }
366 }
367
368
369 /**
370  * Destroy a mysql context.  Also frees all associated prepared statements.
371  *
372  * @param mc context to destroy
373  */
374 void
375 GNUNET_MYSQL_context_destroy(struct GNUNET_MYSQL_Context *mc)
376 {
377   struct GNUNET_MYSQL_StatementHandle *sh;
378
379   GNUNET_MYSQL_statements_invalidate(mc);
380   while (NULL != (sh = mc->shead))
381     {
382       GNUNET_CONTAINER_DLL_remove(mc->shead, mc->stail, sh);
383       GNUNET_free(sh->query);
384       GNUNET_free(sh);
385     }
386   GNUNET_free(mc);
387   mysql_library_end();
388 }
389
390
391 /**
392  * Prepare a statement.  Prepared statements are automatically discarded
393  * when the MySQL context is destroyed.
394  *
395  * @param mc mysql context
396  * @param query query text
397  * @return prepared statement, NULL on error
398  */
399 struct GNUNET_MYSQL_StatementHandle *
400 GNUNET_MYSQL_statement_prepare(struct GNUNET_MYSQL_Context *mc,
401                                const char *query)
402 {
403   struct GNUNET_MYSQL_StatementHandle *sh;
404
405   sh = GNUNET_new(struct GNUNET_MYSQL_StatementHandle);
406   sh->mc = mc;
407   sh->query = GNUNET_strdup(query);
408   GNUNET_CONTAINER_DLL_insert(mc->shead, mc->stail, sh);
409   return sh;
410 }
411
412
413 /**
414  * Run a SQL statement.
415  *
416  * @param mc mysql context
417  * @param sql SQL statement to run
418  * @return #GNUNET_OK on success
419  *         #GNUNET_SYSERR if there was a problem
420  */
421 int
422 GNUNET_MYSQL_statement_run(struct GNUNET_MYSQL_Context *mc, const char *sql)
423 {
424   if ((NULL == mc->dbf) && (GNUNET_OK != iopen(mc)))
425     return GNUNET_SYSERR;
426   mysql_query(mc->dbf, sql);
427   if (mysql_error(mc->dbf)[0])
428     {
429       LOG_MYSQL(GNUNET_ERROR_TYPE_ERROR, "mysql_query", mc);
430       GNUNET_MYSQL_statements_invalidate(mc);
431       return GNUNET_SYSERR;
432     }
433   return GNUNET_OK;
434 }
435
436
437 /**
438  * Prepare a statement for running.
439  *
440  * @param mc mysql context
441  * @param sh statement handle to prepare
442  * @return #GNUNET_OK on success
443  */
444 static int
445 prepare_statement(struct GNUNET_MYSQL_StatementHandle *sh)
446 {
447   struct GNUNET_MYSQL_Context *mc = sh->mc;
448
449   if (GNUNET_YES == sh->valid)
450     return GNUNET_OK;
451   if ((NULL == mc->dbf) && (GNUNET_OK != iopen(mc)))
452     return GNUNET_SYSERR;
453   sh->statement = mysql_stmt_init(mc->dbf);
454   if (NULL == sh->statement)
455     {
456       GNUNET_MYSQL_statements_invalidate(mc);
457       return GNUNET_SYSERR;
458     }
459   if (0 != mysql_stmt_prepare(sh->statement, sh->query, strlen(sh->query)))
460     {
461       GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR,
462                       "mysql",
463                       "prepare_statement: %s\n",
464                       sh->query);
465       LOG_MYSQL(GNUNET_ERROR_TYPE_ERROR, "mysql_stmt_prepare", mc);
466       mysql_stmt_close(sh->statement);
467       sh->statement = NULL;
468       GNUNET_MYSQL_statements_invalidate(mc);
469       return GNUNET_SYSERR;
470     }
471   sh->valid = GNUNET_YES;
472   return GNUNET_OK;
473 }
474
475
476 /**
477  * Get internal handle for a prepared statement.  This function should rarely
478  * be used, and if, with caution!  On failures during the interaction with
479  * the handle, you must call 'GNUNET_MYSQL_statements_invalidate'!
480  *
481  * @param sh prepared statement to introspect
482  * @return MySQL statement handle, NULL on error
483  */
484 MYSQL_STMT *
485 GNUNET_MYSQL_statement_get_stmt(struct GNUNET_MYSQL_StatementHandle *sh)
486 {
487   (void)prepare_statement(sh);
488   return sh->statement;
489 }
490
491
492 /* end of mysql.c */