]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqlite3.cpp
Allow Channel::WriteNotice send to other servers and status ranks.
[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("arch") pkgconf sqlite
26 /// $PackageInfo: require_system("centos") pkgconfig sqlite-devel
27 /// $PackageInfo: require_system("darwin") pkg-config sqlite3
28 /// $PackageInfo: require_system("debian") libsqlite3-dev pkg-config
29 /// $PackageInfo: require_system("ubuntu") libsqlite3-dev pkg-config
30
31 #include "inspircd.h"
32 #include "modules/sql.h"
33
34 #ifdef __GNUC__
35 # pragma GCC diagnostic push
36 #endif
37
38 // Fix warnings about the use of `long long` on C++03.
39 #if defined __clang__
40 # pragma clang diagnostic ignored "-Wc++11-long-long"
41 #elif defined __GNUC__
42 # pragma GCC diagnostic ignored "-Wlong-long"
43 #endif
44
45 #include <sqlite3.h>
46
47 #ifdef __GNUC__
48 # pragma GCC diagnostic pop
49 #endif
50
51 #ifdef _WIN32
52 # pragma comment(lib, "sqlite3.lib")
53 #endif
54
55 class SQLConn;
56 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
57
58 class SQLite3Result : public SQL::Result
59 {
60  public:
61         int currentrow;
62         int rows;
63         std::vector<std::string> columns;
64         std::vector<SQL::Row> fieldlists;
65
66         SQLite3Result() : currentrow(0), rows(0)
67         {
68         }
69
70         int Rows() CXX11_OVERRIDE
71         {
72                 return rows;
73         }
74
75         bool GetRow(SQL::Row& result) CXX11_OVERRIDE
76         {
77                 if (currentrow < rows)
78                 {
79                         result.assign(fieldlists[currentrow].begin(), fieldlists[currentrow].end());
80                         currentrow++;
81                         return true;
82                 }
83                 else
84                 {
85                         result.clear();
86                         return false;
87                 }
88         }
89
90         void GetCols(std::vector<std::string>& result) CXX11_OVERRIDE
91         {
92                 result.assign(columns.begin(), columns.end());
93         }
94
95         bool HasColumn(const std::string& column, size_t& index) CXX11_OVERRIDE
96         {
97                 for (size_t i = 0; i < columns.size(); ++i)
98                 {
99                         if (columns[i] == column)
100                         {
101                                 index = i;
102                                 return true;
103                         }
104                 }
105                 return false;
106         }
107 };
108
109 class SQLConn : public SQL::Provider
110 {
111         sqlite3* conn;
112         reference<ConfigTag> config;
113
114  public:
115         SQLConn(Module* Parent, ConfigTag* tag)
116                 : SQL::Provider(Parent, tag->getString("id"))
117                 , config(tag)
118         {
119                 std::string host = tag->getString("hostname");
120                 if (sqlite3_open_v2(host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0) != SQLITE_OK)
121                 {
122                         // Even in case of an error conn must be closed
123                         sqlite3_close(conn);
124                         conn = NULL;
125                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not open DB with id: " + tag->getString("id"));
126                 }
127         }
128
129         ~SQLConn()
130         {
131                 if (conn)
132                 {
133                         sqlite3_interrupt(conn);
134                         sqlite3_close(conn);
135                 }
136         }
137
138         void Query(SQL::Query* query, const std::string& q)
139         {
140                 SQLite3Result res;
141                 sqlite3_stmt *stmt;
142                 int err = sqlite3_prepare_v2(conn, q.c_str(), q.length(), &stmt, NULL);
143                 if (err != SQLITE_OK)
144                 {
145                         SQL::Error error(SQL::QSEND_FAIL, sqlite3_errmsg(conn));
146                         query->OnError(error);
147                         return;
148                 }
149                 int cols = sqlite3_column_count(stmt);
150                 res.columns.resize(cols);
151                 for(int i=0; i < cols; i++)
152                 {
153                         res.columns[i] = sqlite3_column_name(stmt, i);
154                 }
155                 while (1)
156                 {
157                         err = sqlite3_step(stmt);
158                         if (err == SQLITE_ROW)
159                         {
160                                 // Add the row
161                                 res.fieldlists.resize(res.rows + 1);
162                                 res.fieldlists[res.rows].resize(cols);
163                                 for(int i=0; i < cols; i++)
164                                 {
165                                         const char* txt = (const char*)sqlite3_column_text(stmt, i);
166                                         if (txt)
167                                                 res.fieldlists[res.rows][i] = SQL::Field(txt);
168                                 }
169                                 res.rows++;
170                         }
171                         else if (err == SQLITE_DONE)
172                         {
173                                 query->OnResult(res);
174                                 break;
175                         }
176                         else
177                         {
178                                 SQL::Error error(SQL::QREPLY_FAIL, sqlite3_errmsg(conn));
179                                 query->OnError(error);
180                                 break;
181                         }
182                 }
183                 sqlite3_finalize(stmt);
184         }
185
186         void Submit(SQL::Query* query, const std::string& q) CXX11_OVERRIDE
187         {
188                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Executing SQLite3 query: " + q);
189                 Query(query, q);
190                 delete query;
191         }
192
193         void Submit(SQL::Query* query, const std::string& q, const SQL::ParamList& p) CXX11_OVERRIDE
194         {
195                 std::string res;
196                 unsigned int param = 0;
197                 for(std::string::size_type i = 0; i < q.length(); i++)
198                 {
199                         if (q[i] != '?')
200                                 res.push_back(q[i]);
201                         else
202                         {
203                                 if (param < p.size())
204                                 {
205                                         char* escaped = sqlite3_mprintf("%q", p[param++].c_str());
206                                         res.append(escaped);
207                                         sqlite3_free(escaped);
208                                 }
209                         }
210                 }
211                 Submit(query, res);
212         }
213
214         void Submit(SQL::Query* query, const std::string& q, const SQL::ParamMap& p) CXX11_OVERRIDE
215         {
216                 std::string res;
217                 for(std::string::size_type i = 0; i < q.length(); i++)
218                 {
219                         if (q[i] != '$')
220                                 res.push_back(q[i]);
221                         else
222                         {
223                                 std::string field;
224                                 i++;
225                                 while (i < q.length() && isalnum(q[i]))
226                                         field.push_back(q[i++]);
227                                 i--;
228
229                                 SQL::ParamMap::const_iterator it = p.find(field);
230                                 if (it != p.end())
231                                 {
232                                         char* escaped = sqlite3_mprintf("%q", it->second.c_str());
233                                         res.append(escaped);
234                                         sqlite3_free(escaped);
235                                 }
236                         }
237                 }
238                 Submit(query, res);
239         }
240 };
241
242 class ModuleSQLite3 : public Module
243 {
244         ConnMap conns;
245
246  public:
247         ~ModuleSQLite3()
248         {
249                 ClearConns();
250         }
251
252         void ClearConns()
253         {
254                 for(ConnMap::iterator i = conns.begin(); i != conns.end(); i++)
255                 {
256                         SQLConn* conn = i->second;
257                         ServerInstance->Modules->DelService(*conn);
258                         delete conn;
259                 }
260                 conns.clear();
261         }
262
263         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
264         {
265                 ClearConns();
266                 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
267                 for(ConfigIter i = tags.first; i != tags.second; i++)
268                 {
269                         if (!stdalgo::string::equalsci(i->second->getString("module"), "sqlite"))
270                                 continue;
271                         SQLConn* conn = new SQLConn(this, i->second);
272                         conns.insert(std::make_pair(i->second->getString("id"), conn));
273                         ServerInstance->Modules->AddService(*conn);
274                 }
275         }
276
277         Version GetVersion() CXX11_OVERRIDE
278         {
279                 return Version("Provides SQLite3 support", VF_VENDOR);
280         }
281 };
282
283 MODULE_INIT(ModuleSQLite3)