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