]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqlite3.cpp
Sync helpop chmodes s and p with docs
[user/henk/code/inspircd.git] / src / modules / extra / m_sqlite3.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
5  *   Copyright (C) 2015 Daniel Vassdal <shutter@canternet.org>
6  *   Copyright (C) 2013-2014, 2016-2019 Sadie Powell <sadie@witchery.services>
7  *   Copyright (C) 2013-2014, 2016 Attila Molnar <attilamolnar@hush.com>
8  *   Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
9  *   Copyright (C) 2012, 2016 Adam <Adam@anope.org>
10  *   Copyright (C) 2012 ChrisTX <xpipe@hotmail.de>
11  *   Copyright (C) 2010 Daniel De Graaf <danieldg@inspircd.org>
12  *   Copyright (C) 2007, 2009 Craig Edwards <brain@inspircd.org>
13  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
14  *
15  * This file is part of InspIRCd.  InspIRCd is free software: you can
16  * redistribute it and/or modify it under the terms of the GNU General Public
17  * License as published by the Free Software Foundation, version 2.
18  *
19  * This program is distributed in the hope that it will be useful, but WITHOUT
20  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26  */
27
28 /// $CompilerFlags: find_compiler_flags("sqlite3")
29 /// $LinkerFlags: find_linker_flags("sqlite3" "-lsqlite3")
30
31 /// $PackageInfo: require_system("arch") pkgconf sqlite
32 /// $PackageInfo: require_system("centos") pkgconfig sqlite-devel
33 /// $PackageInfo: require_system("darwin") pkg-config sqlite3
34 /// $PackageInfo: require_system("debian") libsqlite3-dev pkg-config
35 /// $PackageInfo: require_system("ubuntu") libsqlite3-dev pkg-config
36
37 #include "inspircd.h"
38 #include "modules/sql.h"
39
40 #ifdef __GNUC__
41 # pragma GCC diagnostic push
42 #endif
43
44 // Fix warnings about the use of `long long` on C++03.
45 #if defined __clang__
46 # pragma clang diagnostic ignored "-Wc++11-long-long"
47 #elif defined __GNUC__
48 # pragma GCC diagnostic ignored "-Wlong-long"
49 #endif
50
51 #include <sqlite3.h>
52
53 #ifdef __GNUC__
54 # pragma GCC diagnostic pop
55 #endif
56
57 #ifdef _WIN32
58 # pragma comment(lib, "sqlite3.lib")
59 #endif
60
61 class SQLConn;
62 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
63
64 class SQLite3Result : public SQL::Result
65 {
66  public:
67         int currentrow;
68         int rows;
69         std::vector<std::string> columns;
70         std::vector<SQL::Row> fieldlists;
71
72         SQLite3Result() : currentrow(0), rows(0)
73         {
74         }
75
76         int Rows() CXX11_OVERRIDE
77         {
78                 return rows;
79         }
80
81         bool GetRow(SQL::Row& result) CXX11_OVERRIDE
82         {
83                 if (currentrow < rows)
84                 {
85                         result.assign(fieldlists[currentrow].begin(), fieldlists[currentrow].end());
86                         currentrow++;
87                         return true;
88                 }
89                 else
90                 {
91                         result.clear();
92                         return false;
93                 }
94         }
95
96         void GetCols(std::vector<std::string>& result) CXX11_OVERRIDE
97         {
98                 result.assign(columns.begin(), columns.end());
99         }
100
101         bool HasColumn(const std::string& column, size_t& index) CXX11_OVERRIDE
102         {
103                 for (size_t i = 0; i < columns.size(); ++i)
104                 {
105                         if (columns[i] == column)
106                         {
107                                 index = i;
108                                 return true;
109                         }
110                 }
111                 return false;
112         }
113 };
114
115 class SQLConn : public SQL::Provider
116 {
117         sqlite3* conn;
118         reference<ConfigTag> config;
119
120  public:
121         SQLConn(Module* Parent, ConfigTag* tag)
122                 : SQL::Provider(Parent, tag->getString("id"))
123                 , config(tag)
124         {
125                 std::string host = tag->getString("hostname");
126                 if (sqlite3_open_v2(host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0) != SQLITE_OK)
127                 {
128                         // Even in case of an error conn must be closed
129                         sqlite3_close(conn);
130                         conn = NULL;
131                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not open DB with id: " + tag->getString("id"));
132                 }
133         }
134
135         ~SQLConn()
136         {
137                 if (conn)
138                 {
139                         sqlite3_interrupt(conn);
140                         sqlite3_close(conn);
141                 }
142         }
143
144         void Query(SQL::Query* query, const std::string& q)
145         {
146                 SQLite3Result res;
147                 sqlite3_stmt *stmt;
148                 int err = sqlite3_prepare_v2(conn, q.c_str(), q.length(), &stmt, NULL);
149                 if (err != SQLITE_OK)
150                 {
151                         SQL::Error error(SQL::QSEND_FAIL, sqlite3_errmsg(conn));
152                         query->OnError(error);
153                         return;
154                 }
155                 int cols = sqlite3_column_count(stmt);
156                 res.columns.resize(cols);
157                 for(int i=0; i < cols; i++)
158                 {
159                         res.columns[i] = sqlite3_column_name(stmt, i);
160                 }
161                 while (1)
162                 {
163                         err = sqlite3_step(stmt);
164                         if (err == SQLITE_ROW)
165                         {
166                                 // Add the row
167                                 res.fieldlists.resize(res.rows + 1);
168                                 res.fieldlists[res.rows].resize(cols);
169                                 for(int i=0; i < cols; i++)
170                                 {
171                                         const char* txt = (const char*)sqlite3_column_text(stmt, i);
172                                         if (txt)
173                                                 res.fieldlists[res.rows][i] = SQL::Field(txt);
174                                 }
175                                 res.rows++;
176                         }
177                         else if (err == SQLITE_DONE)
178                         {
179                                 query->OnResult(res);
180                                 break;
181                         }
182                         else
183                         {
184                                 SQL::Error error(SQL::QREPLY_FAIL, sqlite3_errmsg(conn));
185                                 query->OnError(error);
186                                 break;
187                         }
188                 }
189                 sqlite3_finalize(stmt);
190         }
191
192         void Submit(SQL::Query* query, const std::string& q) CXX11_OVERRIDE
193         {
194                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Executing SQLite3 query: " + q);
195                 Query(query, q);
196                 delete query;
197         }
198
199         void Submit(SQL::Query* query, const std::string& q, const SQL::ParamList& p) CXX11_OVERRIDE
200         {
201                 std::string res;
202                 unsigned int param = 0;
203                 for(std::string::size_type i = 0; i < q.length(); i++)
204                 {
205                         if (q[i] != '?')
206                                 res.push_back(q[i]);
207                         else
208                         {
209                                 if (param < p.size())
210                                 {
211                                         char* escaped = sqlite3_mprintf("%q", p[param++].c_str());
212                                         res.append(escaped);
213                                         sqlite3_free(escaped);
214                                 }
215                         }
216                 }
217                 Submit(query, res);
218         }
219
220         void Submit(SQL::Query* query, const std::string& q, const SQL::ParamMap& p) CXX11_OVERRIDE
221         {
222                 std::string res;
223                 for(std::string::size_type i = 0; i < q.length(); i++)
224                 {
225                         if (q[i] != '$')
226                                 res.push_back(q[i]);
227                         else
228                         {
229                                 std::string field;
230                                 i++;
231                                 while (i < q.length() && isalnum(q[i]))
232                                         field.push_back(q[i++]);
233                                 i--;
234
235                                 SQL::ParamMap::const_iterator it = p.find(field);
236                                 if (it != p.end())
237                                 {
238                                         char* escaped = sqlite3_mprintf("%q", it->second.c_str());
239                                         res.append(escaped);
240                                         sqlite3_free(escaped);
241                                 }
242                         }
243                 }
244                 Submit(query, res);
245         }
246 };
247
248 class ModuleSQLite3 : public Module
249 {
250         ConnMap conns;
251
252  public:
253         ~ModuleSQLite3()
254         {
255                 ClearConns();
256         }
257
258         void ClearConns()
259         {
260                 for(ConnMap::iterator i = conns.begin(); i != conns.end(); i++)
261                 {
262                         SQLConn* conn = i->second;
263                         ServerInstance->Modules->DelService(*conn);
264                         delete conn;
265                 }
266                 conns.clear();
267         }
268
269         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
270         {
271                 ClearConns();
272                 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
273                 for(ConfigIter i = tags.first; i != tags.second; i++)
274                 {
275                         if (!stdalgo::string::equalsci(i->second->getString("module"), "sqlite"))
276                                 continue;
277                         SQLConn* conn = new SQLConn(this, i->second);
278                         conns.insert(std::make_pair(i->second->getString("id"), conn));
279                         ServerInstance->Modules->AddService(*conn);
280                 }
281         }
282
283         Version GetVersion() CXX11_OVERRIDE
284         {
285                 return Version("Provides the ability for SQL modules to query a SQLite 3 database.", VF_VENDOR);
286         }
287 };
288
289 MODULE_INIT(ModuleSQLite3)