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