Debian Codegraph @

src/bnetd/storage_sql.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2002 TheUndying
3 * Copyright (C) 2002 zap-zero
4 * Copyright (C) 2002,2003 Dizzy
5 * Copyright (C) 2002 Zzzoom
6 * Copyright (C) 2014 HarpyWar
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 */
22
23 #include "common/setup_before.h"
24 #ifdef WITH_SQL
25 #include "storage_sql.h"
26
27 #include <cstring>
28 #include <cstdlib>
29 #include <vector>
30 #include <map>
31 #include <iterator>
32 #include <algorithm>
33
34 #include "common/eventlog.h"
35 #include "common/util.h"
36 #include "common/xstring.h"
37
38 #define SQL_INTERNAL
39 # include "sql_common.h"
40 #undef SQL_INTERNAL
41 #include "account.h"
42 #include "common/setup_after.h"
43
44 namespace pvpgn
45 {
46
47 namespace bnetd
48 {
49
50 static t_storage_info *sql_create_account(char const *);
51 static int sql_read_attrs(t_storage_info *, t_read_attr_func, void *, const char *);
52 static t_attr *sql_read_attr(t_storage_info *, const char *);
53 static int sql_write_attrs(t_storage_info *, const t_hlist *);
54 static t_storage_info * sql_read_account(const char *, unsigned);
55 static const char *sql_escape_key(const char *);
56
57 t_storage storage_sql = {
58 sql_init,
59 sql_close,
60 sql_read_maxuserid,
61 sql_create_account,
62 sql_get_defacct,
63 sql_free_info,
64 sql_read_attrs,
65 sql_write_attrs,
66 sql_read_attr,
67 sql_read_accounts,
68 sql_read_account,
69 sql_cmp_info,
70 sql_escape_key,
71 sql_load_clans,
72 sql_write_clan,
73 sql_remove_clan,
74 sql_remove_clanmember,
75 sql_load_teams,
76 sql_write_team,
77 sql_remove_team
78 };
79
80 // Attribute names that are assurance exist in database
81 std::map<std::string, std::vector<std::string> > knownattributes;
82
83 static char query[512];
84
85 #ifndef SQL_ON_DEMAND
86
87 static const char *_db_add_tab(const char *tab, const char *key)
88 {
89 static char nkey[DB_MAX_ATTRKEY];
90
91 std::strncpy(nkey, tab, sizeof(nkey)-1);
92 nkey[std::strlen(nkey) + 1] = '\0';
93 nkey[std::strlen(nkey)] = '_';
94 std::strncpy(nkey + std::strlen(nkey), key, sizeof(nkey)-std::strlen(nkey));
95 return nkey;
96 }
97
98 #endif /* SQL_ON_DEMAND */
99
100 static int _db_get_tab(const char *key, char **ptab, char **pcol)
101 {
102 static char tab[DB_MAX_ATTRKEY];
103 static char col[DB_MAX_ATTRKEY];
104
105 std::strncpy(tab, key, DB_MAX_TAB - 1);
106 tab[DB_MAX_TAB - 1] = 0;
107
108 if (!std::strchr(tab, '_'))
109 return -1;
110
111
112 *(std::strchr(tab, '_')) = 0;
113 std::strncpy(col, key + std::strlen(tab) + 1, DB_MAX_TAB - 1);
114 col[DB_MAX_TAB - 1] = 0;
115 /* return tab and col as 2 static buffers */
116 *ptab = tab;
117 *pcol = col;
118 return 0;
119 }
120
121 static t_storage_info *sql_create_account(char const *username)
122 {
123 t_sql_res *result = NULL;
124 t_sql_row *row;
125 int uid = maxuserid + 1;
126 t_storage_info *info;
127 char *user;
128
129 if (!sql)
130 {
131 eventlog(eventlog_level_error, __FUNCTION__, "sql layer not initilized");
132 return NULL;
133 }
134
135 user = xstrdup(username);
136 strtolower(user);
137 std::snprintf(query, sizeof(query), "SELECT count(*) FROM %sBNET WHERE username='%s'", tab_prefix, user);
138 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
139
140 if ((result = sql->query_res(query)) != NULL)
141 {
142 int num;
143
144 row = sql->fetch_row(result);
145 if (row == NULL || row[0] == NULL)
146 {
147 sql->free_result(result);
148 eventlog(eventlog_level_error, __FUNCTION__, "got NULL count");
149 goto err_dup;
150 }
151 num = std::atol(row[0]);
152 sql->free_result(result);
153 if (num > 0)
154 {
155 eventlog(eventlog_level_error, __FUNCTION__, "got existant username");
156 goto err_dup;
157 }
158 }
159 else
160 {
161 eventlog(eventlog_level_error, __FUNCTION__, "error trying query: \"{}\"", query);
162 goto err_dup;
163 }
164
165 info = xmalloc(sizeof(t_sql_info));
166 *((unsigned int *)info) = uid;
167 std::snprintf(query, sizeof(query), "DELETE FROM %sBNET WHERE " SQL_UID_FIELD " = '%u'", tab_prefix, uid);
168 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
169 sql->query(query);
170 std::snprintf(query, sizeof(query), "INSERT INTO %sBNET (" SQL_UID_FIELD ",username) VALUES('%u','%s')", tab_prefix, uid, user);
171 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
172 if (sql->query(query))
173 {
174 eventlog(eventlog_level_error, __FUNCTION__, "user insert failed (query: '{}')", query);
175 goto err_info;
176 }
177
178 std::snprintf(query, sizeof(query), "DELETE FROM %sprofile WHERE " SQL_UID_FIELD " = '%u'", tab_prefix, uid);
179 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
180 sql->query(query);
181 std::snprintf(query, sizeof(query), "INSERT INTO %sprofile (" SQL_UID_FIELD ") VALUES('%u')", tab_prefix, uid);
182 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
183 if (sql->query(query))
184 {
185 eventlog(eventlog_level_error, __FUNCTION__, "user insert failed (query: '{}')", query);
186 goto err_info;
187 }
188
189 std::snprintf(query, sizeof(query), "DELETE FROM %sRecord WHERE " SQL_UID_FIELD " = '%u'", tab_prefix, uid);
190 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
191 sql->query(query);
192 std::snprintf(query, sizeof(query), "INSERT INTO %sRecord (" SQL_UID_FIELD ") VALUES('%u')", tab_prefix, uid);
193 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
194 if (sql->query(query))
195 {
196 eventlog(eventlog_level_error, __FUNCTION__, "user insert failed (query: '{}')", query);
197 goto err_info;
198 }
199
200 std::snprintf(query, sizeof(query), "DELETE FROM %sfriend WHERE " SQL_UID_FIELD " = '%u'", tab_prefix, uid);
201 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
202 sql->query(query);
203 std::snprintf(query, sizeof(query), "INSERT INTO %sfriend (" SQL_UID_FIELD ") VALUES('%u')", tab_prefix, uid);
204 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
205 if (sql->query(query))
206 {
207 eventlog(eventlog_level_error, __FUNCTION__, "user insert failed (query: '{}')", query);
208 goto err_info;
209 }
210
211 xfree(user);
212 return info;
213
214 err_info:
215 xfree((void *)info);
216
217 err_dup:
218 xfree(user);
219
220 return NULL;
221 }
222
223 static int sql_read_attrs(t_storage_info * info, t_read_attr_func cb, void *data, const char *ktab)
224 {
225 #ifndef SQL_ON_DEMAND
226 t_sql_res *result = NULL;
227 t_sql_row *row;
228 char **tab;
229 unsigned int uid;
230 unsigned int num_fields;
231
232 if (!sql)
233 {
234 eventlog(eventlog_level_error, __FUNCTION__, "sql layer not initilized");
235 return -1;
236 }
237
238 if (info == NULL)
239 {
240 eventlog(eventlog_level_error, __FUNCTION__, "got NULL storage info");
241 return -1;
242 }
243
244 if (cb == NULL)
245 {
246 eventlog(eventlog_level_error, __FUNCTION__, "got NULL callback");
247 return -1;
248 }
249
250 uid = *((unsigned int *)info);
251
252 for (tab = const_cast<char **>(sql_tables); *tab; tab++)
253 {
254 // process only a table where the attribute is in
255 if (strcmp(ktab, *tab) != 0)
256 continue;
257
258 std::snprintf(query, sizeof(query), "SELECT * FROM %s%s WHERE " SQL_UID_FIELD "='%u'", tab_prefix, *tab, uid);
259 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
260
261 if ((result = sql->query_res(query)) != NULL && sql->num_rows(result) == 1 && (num_fields = sql->num_fields(result)) > 1)
262 {
263 unsigned int i;
264 t_sql_field *fields, *fentry;
265
266 if ((fields = sql->fetch_fields(result)) == NULL)
267 {
268 eventlog(eventlog_level_error, __FUNCTION__, "could not fetch the fields");
269 sql->free_result(result);
270 return -1;
271 }
272
273 if (!(row = sql->fetch_row(result)))
274 {
275 eventlog(eventlog_level_error, __FUNCTION__, "could not fetch row");
276 sql->free_fields(fields);
277 sql->free_result(result);
278 return -1;
279 }
280
281 for (i = 0, fentry = fields; *fentry; fentry++, i++)
282 {
283 char *output;
284
285 // (HarpyWar) fix for sqlite3, cause it return columns+rows in "fields", unlike only columns in other databases
286 // and this row[i] goes beyond the bounds of the array. This restriction handles it.
287 if (i >= num_fields)
288 break;
289
290 /* we have to skip "uid" */
291 /* we ignore the field used internally by sql */
292 if (std::strcmp(*fentry, SQL_UID_FIELD) == 0)
293 continue;
294
295 // eventlog(eventlog_level_trace, __FUNCTION__, "read key (step1): '{}' val: '{}'", _db_add_tab(*tab, *fentry), unescape_chars(row[i]));
296 if (row[i] == NULL)
297 continue; /* its an NULL value sql field */
298
299 // eventlog(eventlog_level_trace, __FUNCTION__, "read key (step2): '{}' val: '{}'", _db_add_tab(*tab, *fentry), unescape_chars(row[i]));
300 if (cb(_db_add_tab(*tab, *fentry), (output = unescape_chars(row[i])), data))
301 eventlog(eventlog_level_error, __FUNCTION__, "got error from callback on UID: {}", uid);
302 if (output)
303 xfree((void *)output);
304 // eventlog(eventlog_level_trace, __FUNCTION__, "read key (final): '{}' val: '{}'", _db_add_tab(*tab, *fentry), unescape_chars(row[i]));
305 }
306
307 sql->free_fields(fields);
308 }
309 if (result)
310 sql->free_result(result);
311 }
312 #endif /* SQL_ON_DEMAND */
313 return 0;
314 }
315
316 static t_attr *sql_read_attr(t_storage_info * info, const char *key)
317 {
318 #ifdef SQL_ON_DEMAND
319 t_sql_res *result = NULL;
320 t_sql_row *row;
321 char *tab, *col;
322 unsigned int uid;
323 t_attr *attr;
324
325 if (!sql)
326 {
327 eventlog(eventlog_level_error, __FUNCTION__, "sql layer not initilized");
328 return NULL;
329 }
330
331 if (info == NULL)
332 {
333 eventlog(eventlog_level_error, __FUNCTION__, "got NULL storage info");
334 return NULL;
335 }
336
337 if (key == NULL)
338 {
339 eventlog(eventlog_level_error, __FUNCTION__, "got NULL key");
340 return NULL;
341 }
342
343 uid = *((unsigned int *)info);
344
345 if (_db_get_tab(key, &tab, &col) < 0)
346 {
347 eventlog(eventlog_level_error, __FUNCTION__, "error from _db_get_tab");
348 return NULL;
349 }
350
351 std::snprintf(query, sizeof(query), "SELECT %s FROM %s%s WHERE " SQL_UID_FIELD " = %u", col, tab_prefix, tab, uid);
352 eventlog(eventlog_level_trace, __FUNCTION__, query);
353 if ((result = sql->query_res(query)) == NULL)
354 return NULL;
355
356 if (sql->num_rows(result) != 1)
357 {
358 // eventlog(eventlog_level_debug, __FUNCTION__, "wrong numer of rows from query ({})", query);
359 sql->free_result(result);
360 return NULL;
361 }
362
363 if (!(row = sql->fetch_row(result)))
364 {
365 eventlog(eventlog_level_error, __FUNCTION__, "could not fetch row");
366 sql->free_result(result);
367 return NULL;
368 }
369
370 if (row[0] == NULL)
371 {
372 // eventlog(eventlog_level_debug, __FUNCTION__, "NULL value from query ({})", query);
373 sql->free_result(result);
374 return NULL;
375 }
376
377 /* Because we are double quoting the column name
378 sqlite3 treats it as a string when the column does not exist
379 and returns the column name as the result.
380 We need to return NULL under this condition */
381 if (std::strcmp(row[0], col) == 0)
382 {
383 sql->free_result(result);
384 return NULL;
385 }
386
387 attr = attr_create(key, row[0]);
388 sql->free_result(result);
389
390 return attr;
391 #else
392 return NULL;
393 #endif /* SQL_ON_DEMAND */
394 }
395
396 /* write ONLY dirty attributes */
397 int sql_write_attrs(t_storage_info * info, const t_hlist *attrs)
398 {
399 char escape[DB_MAX_ATTRVAL * 2 + 1]; /* sql docs say the escape can take a maximum of double original size + 1 */
400 char safeval[DB_MAX_ATTRVAL];
401 char *p, *tab, *col;
402 t_attr *attr;
403 t_hlist *curr;
404 unsigned int uid;
405
406 if (!sql)
407 {
408 eventlog(eventlog_level_error, __FUNCTION__, "sql layer not initilized");
409 return -1;
410 }
411
412 if (info == NULL)
413 {
414 eventlog(eventlog_level_error, __FUNCTION__, "got NULL sql info");
415 return -1;
416 }
417
418 if (attrs == NULL)
419 {
420 eventlog(eventlog_level_error, __FUNCTION__, "got NULL attributes list");
421 return -1;
422 }
423
424 uid = *((unsigned int *)info);
425
426 std::map<std::string, std::string > queries;
427
428 hlist_for_each(curr, (t_hlist*)attrs)
429 {
430 attr = hlist_entry(curr, t_attr, link);
431
432 if (!attr_get_dirty(attr))
433 continue; /* save ONLY dirty attributes */
434
435 if (attr_get_key(attr) == NULL) {
436 eventlog(eventlog_level_error, __FUNCTION__, "found NULL key in attributes list");
437 continue;
438 }
439
440 if (attr_get_val(attr) == NULL) {
441 eventlog(eventlog_level_error, __FUNCTION__, "found NULL value in attributes list ({})", attr_get_key(attr));
442 continue;
443 }
444
445 if (_db_get_tab(attr_get_key(attr), &tab, &col) < 0) {
446 eventlog(eventlog_level_error, __FUNCTION__, "error from _db_get_tab");
447 continue;
448 }
449
450 std::strncpy(safeval, attr_get_val(attr), DB_MAX_ATTRVAL - 1);
451 safeval[DB_MAX_ATTRVAL - 1] = 0;
452 for (p = safeval; *p; p++)
453 if (*p == '\'') /* value shouldn't contain ' */
454 *p = '"';
455
456 sql->escape_string(escape, safeval, std::strlen(safeval));
457
458 // if attribute found in known attributes list
459 if (std::find(knownattributes[tab].begin(), knownattributes[tab].end(), col) != knownattributes[tab].end())
460 {
461 // append new field and value
462 queries[tab] += std::string(col) + " = '" + std::string(escape) + "', ";
463
464 /* PASS NEXT CODE EXECUTION
465 (MERGED QUERIES WILL BE EXECUTED AT THE END OF THE FUNCTION) */
466 continue;
467 }
468
469 /* FIRST TIME UPDATE EACH ATTRIBUTE IN A SINGLE QUERY AND SAVE ATTRIBUTE NAME IN 'knownattributes' */
470 std::snprintf(query, sizeof(query), "UPDATE %s%s SET %s = '%s' WHERE " SQL_UID_FIELD " = '%u'", tab_prefix, tab, col, escape, uid);
471 eventlog(eventlog_level_trace, "db_set", "{}", query);
472
473 if (sql->query(query) || !sql->affected_rows()) {
474 char query2[512];
475
476 // eventlog(eventlog_level_debug, __FUNCTION__, "trying to insert new column {}", col);
477 std::snprintf(query2, sizeof(query2), "ALTER TABLE %s%s ADD COLUMN %s VARCHAR(128)", tab_prefix, tab, col);
478 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query2);
479
480 sql->query(query2);
481
482 /* try query again */
483 // eventlog(eventlog_level_trace, "db_set", "retry insert query: {}", query);
484 if (sql->query(query) || !sql->affected_rows()) {
485 // Tried everything, now trying to insert that user to the table for the first time
486 std::snprintf(query2, sizeof(query2), "INSERT INTO %s%s (" SQL_UID_FIELD ",%s) VALUES ('%u','%s')", tab_prefix, tab, col, uid, escape);
487 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query2);
488 // eventlog(eventlog_level_error, __FUNCTION__, "update failed so tried INSERT for the last chance");
489 if (sql->query(query2))
490 {
491 eventlog(eventlog_level_error, __FUNCTION__, "could not INSERT attribute '{}'->'{}'", attr_get_key(attr), attr_get_val(attr));
492 continue;
493 }
494 else
495 knownattributes[tab].push_back(col); // if query success add attribute in known table
496 }
497 else
498 knownattributes[tab].push_back(col); // if query success add attribute in known table
499 }
500 else
501 knownattributes[tab].push_back(col); // if query success add attribute in known table
502
503 attr_clear_dirty(attr);
504 }
505
506 std::string query_s;
507 // iterate all queries
508 for (std::map<std::string, std::string>::iterator q = queries.begin(); q != queries.end(); ++q)
509 {
510 query_s = "UPDATE " + std::string(tab_prefix) + q->first + " SET ";
511 query_s += q->second.substr(0, q->second.size() - 2); // remove last reduntant comma at the end of the string with parameters
512 query_s += " WHERE " SQL_UID_FIELD " = '" + std_to_string(uid) + "'";
513
514 if (!sql->query(query_s.c_str()))
515 {
516 eventlog(eventlog_level_trace, __FUNCTION__, "multi-update query: {}", query_s.c_str());
517 }
518 else
519 {
520 eventlog(eventlog_level_error, __FUNCTION__, "sql error ({})", query_s.c_str());
521 }
522 }
523
524
525 return 0;
526 }
527
528 static t_storage_info * sql_read_account(const char *name, unsigned uid)
529 {
530 t_sql_res *result = NULL;
531 t_sql_row *row;
532 t_storage_info *info;
533
534 if (!sql)
535 {
536 eventlog(eventlog_level_error, __FUNCTION__, "sql layer not initilized");
537 return NULL;
538 }
539
540 /* SELECT uid from BNET WHERE uid=x sounds stupid, I agree but its a clean
541 * way to check for account existence by an uid */
542 if (name) {
543 char *user = xstrdup(name);
544 strtolower(user);
545
546 std::snprintf(query, sizeof(query), "SELECT " SQL_UID_FIELD " FROM %sBNET WHERE username='%s'", tab_prefix, user);
547 xfree(user);
548 }
549 else
550 std::snprintf(query, sizeof(query), "SELECT " SQL_UID_FIELD " FROM %sBNET WHERE " SQL_UID_FIELD " = '%u'", tab_prefix, uid);
551
552 eventlog(eventlog_level_trace, __FUNCTION__, "{}", query);
553
554 result = sql->query_res(query);
555 if (!result) {
556 eventlog(eventlog_level_error, __FUNCTION__, "error query db (query:\"{}\")", query);
557 return NULL;
558 }
559
560 if (sql->num_rows(result) < 1)
561 {
562 sql->free_result(result);
563 return NULL; /* empty user list */
564 }
565
566 row = sql->fetch_row(result);
567 if (!row) {
568 /* could not fetch row, this should not happen */
569 sql->free_result(result);
570 return NULL;
571 }
572
573 if (row[0] == NULL)
574 /* empty UID field */
575 eventlog(eventlog_level_error, __FUNCTION__, "got NULL uid from db");
576 else if ((unsigned int)std::atoi(row[0]) == sql_defacct);
577 /* skip default account */
578 else {
579 info = xmalloc(sizeof(t_sql_info));
580 *((unsigned int *)info) = std::atoi(row[0]);
581 sql->free_result(result);
582 return info;
583 }
584
585 sql->free_result(result);
586 return NULL;
587 }
588
589 static const char *sql_escape_key(const char *key)
590 {
591 const char *newkey = key;
592 char *p;
593 int idx;
594
595 for (idx = 0, p = (char *)newkey; *p; p++, idx++)
596 if (*p == '\\' || *p == '`' || *p == '"' || *p == '\'') {
597 newkey = xstrdup(key);
598 p = (char *)(newkey + idx);
599 *(p++) = '_';
600 for (; *p; p++)
601 if (*p == '\\' || *p == '`' || *p == '"' || *p == '\'')
602 *p = '_';
603 break;
604 }
605
606 return newkey;
607 }
608
609 }
610
611 }
612
613 #endif /* WITH_SQL */