]> WPIA git - cassiopeia.git/blob - src/db/mysql.cpp
51cfdcbcfa486d0211d51dce2b5a118c4077e015
[cassiopeia.git] / src / db / mysql.cpp
1 #include "mysql.h"
2
3 #include <stdio.h>
4
5 #include <iostream>
6
7 #include <mysql/errmsg.h>
8
9 //This static variable exists to handle initializing and finalizing the MySQL driver library
10 std::shared_ptr<int> MySQLJobProvider::lib_ref(
11     //Initializer: Store the return code as a pointer to an integer
12     new int( mysql_library_init( 0, NULL, NULL ) ),
13
14     //Finalizer: Check the pointer and free resources
15     []( int* ref ) {
16         if( !ref ) {
17             //The library is not initialized
18             return;
19         }
20
21         if( *ref ) {
22             //The library did return an error when initializing
23             delete ref;
24             return;
25         }
26
27         delete ref;
28
29         mysql_library_end();
30     } );
31
32 MySQLJobProvider::MySQLJobProvider( const std::string& server, const std::string& user, const std::string& password, const std::string& database ) {
33     if( !lib_ref || *lib_ref ) {
34         throw "MySQL library not initialized!";
35     }
36
37     connect( server, user, password, database );
38 }
39
40 bool MySQLJobProvider::connect( const std::string& server, const std::string& user, const std::string& password, const std::string& database ) {
41     disconnect();
42     conn = _connect( server, user, password, database );
43
44     return !!conn;
45 }
46
47 std::shared_ptr<MYSQL> MySQLJobProvider::_connect( const std::string& server, const std::string& user, const std::string& password, const std::string& database ) {
48     MYSQL* tmp( mysql_init( NULL ) );
49
50     if( !tmp ) {
51         return nullptr;
52     }
53
54     tmp = mysql_real_connect( tmp, server.c_str(), user.c_str(), password.c_str(), database.c_str(), 3306, NULL, CLIENT_COMPRESS );
55
56     if( !tmp ) {
57         return nullptr;
58     }
59
60     auto l = lib_ref;
61     return std::shared_ptr<MYSQL>(
62         tmp,
63         [l]( MYSQL * c ) {
64             if( c ) {
65                 mysql_close( c );
66             }
67         } );
68 }
69
70 bool MySQLJobProvider::disconnect() {
71     if( !conn ) {
72         return false;
73     }
74
75     conn.reset();
76
77     return true;
78 }
79
80 std::pair< int, std::shared_ptr<MYSQL_RES> > MySQLJobProvider::query( const std::string& query ) {
81     if( !conn ) {
82         return std::make_pair( CR_SERVER_LOST, std::shared_ptr<MYSQL_RES>() );
83     }
84
85     int err = mysql_real_query( this->conn.get(), query.c_str(), query.size() );
86
87     if( err ) {
88         throw std::string( "MySQL error: " ) + mysql_error( this->conn.get() );
89     }
90
91     auto c = conn;
92     std::shared_ptr<MYSQL_RES> res(
93         mysql_store_result( conn.get() ),
94         [c]( MYSQL_RES * r ) {
95             if( !r ) {
96                 return;
97             }
98
99             mysql_free_result( r );
100         } );
101
102     return std::make_pair( err, res );
103 }
104
105 std::shared_ptr<Job> MySQLJobProvider::fetchJob() {
106     std::string q = "SELECT id, targetId, task, executeFrom, executeTo, warning FROM jobs WHERE state='open' AND warning < 3";
107
108     int err = 0;
109     std::shared_ptr<MYSQL_RES> res;
110
111     std::tie( err, res ) = query( q );
112
113     if( err ) {
114         return nullptr;
115     }
116
117     unsigned int num = mysql_num_fields( res.get() );
118
119     MYSQL_ROW row = mysql_fetch_row( res.get() );
120
121     if( !row ) {
122         return nullptr;
123     }
124
125     auto job = std::make_shared<Job>();
126
127     unsigned long* l = mysql_fetch_lengths( res.get() );
128
129     if( !l ) {
130         return nullptr;
131     }
132
133     job->id = std::string( row[0], row[0] + l[0] );
134     job->target = std::string( row[1], row[1] + l[1] );
135     job->task = std::string( row[2], row[2] + l[2] );
136     job->from = std::string( row[3], row[3] + l[3] );
137     job->to = std::string( row[4], row[4] + l[4] );
138     job->warning = std::string( row[5], row[5] + l[5] );
139
140     for( unsigned int i = 0; i < num; i++ ) {
141         printf( "[%.*s] ", ( int ) l[i], row[i] ? row[i] : "NULL" );
142     }
143
144     printf( "\n" );
145
146     return job;
147 }
148
149 std::string MySQLJobProvider::escape_string( const std::string& target ) {
150     if( !conn ) {
151         throw "Not connected!";
152     }
153
154     std::string result;
155
156     result.resize( target.size() * 2 );
157
158     long unsigned int len = mysql_real_escape_string( conn.get(), const_cast<char*>( result.data() ), target.c_str(), target.size() );
159
160     result.resize( len );
161
162     return result;
163 }
164
165 void MySQLJobProvider::finishJob( std::shared_ptr<Job> job ) {
166     if( !conn ) {
167         throw "Not connected!";
168     }
169
170     std::string q = "UPDATE jobs SET state='done' WHERE id='" + this->escape_string( job->id ) + "' LIMIT 1";
171
172     if( query( q ).first ) {
173         throw "No database entry found.";
174     }
175 }
176
177 void MySQLJobProvider::failJob( std::shared_ptr<Job> job ) {
178     if( !conn ) {
179         throw "Not connected!";
180     }
181
182     std::string q = "UPDATE jobs SET warning = warning + 1 WHERE id='" + this->escape_string( job->id ) + "' LIMIT 1";
183
184     if( query( q ).first ) {
185         throw "No database entry found.";
186     }
187 }
188
189 std::shared_ptr<TBSCertificate> MySQLJobProvider::fetchTBSCert( std::shared_ptr<Job> job ) {
190     auto cert = std::make_shared<TBSCertificate>();
191     std::string q = "SELECT md, profile, csr_name, csr_type, keyname FROM certs INNER JOIN profiles ON profiles.id = certs.profile WHERE certs.id='" + this->escape_string( job->target ) + "'";
192
193     int err = 0;
194
195     std::shared_ptr<MYSQL_RES> res;
196
197     std::tie( err, res ) = query( q );
198
199     if( err ) {
200         return nullptr;
201     }
202
203     MYSQL_ROW row = mysql_fetch_row( res.get() );
204
205     if( !row ) {
206         return nullptr;
207     }
208
209     unsigned long* l = mysql_fetch_lengths( res.get() );
210
211     if( !l ) {
212         return nullptr;
213     }
214
215     std::string profileName = std::string( row[4], row[4] + l[4] );
216
217     cert->md = std::string( row[0], row[0] + l[0] );
218     std::string profileId = std::string( row[1], row[1] + l[1] );
219
220     while( profileId.size() < 4 ) {
221         profileId = "0" + profileId;
222     }
223
224     cert->profile = profileId + "-" + profileName;
225
226     cert->csr = std::string( row[2], row[2] + l[2] );
227     cert->csr_type = std::string( row[3], row[3] + l[3] );
228
229     cert->SANs = std::vector<std::shared_ptr<SAN>>();
230
231     q = "SELECT contents, type FROM subjectAlternativeNames WHERE certId='" + this->escape_string( job->target ) + "'";
232     std::tie( err, res ) = query( q );
233
234     if( err ) {
235         std::cout << mysql_error( this->conn.get() );
236         return nullptr;
237     }
238
239     std::cout << "Fetching SANs" << std::endl;
240
241     while( ( row = mysql_fetch_row( res.get() ) ) ) {
242         unsigned long* l = mysql_fetch_lengths( res.get() );
243
244         if( !l ) {
245             return nullptr;
246         }
247
248         std::shared_ptr<SAN> nSAN = std::shared_ptr<SAN>( new SAN() );
249         nSAN->content = std::string( row[0], row[0] + l[0] );
250         nSAN->type = std::string( row[1], row[1] + l[1] );
251         cert->SANs.push_back( nSAN );
252     }
253
254     q = "SELECT name, value FROM certAvas WHERE certid='" + this->escape_string( job->target ) + "'";
255     std::tie( err, res ) = query( q );
256
257     if( err ) {
258         std::cout << mysql_error( this->conn.get() );
259         return nullptr;
260
261     }
262
263     while( ( row = mysql_fetch_row( res.get() ) ) ) {
264         unsigned long* l = mysql_fetch_lengths( res.get() );
265
266         if( !l ) {
267             return nullptr;
268         }
269
270         std::shared_ptr<AVA> nAVA = std::shared_ptr<AVA>( new AVA() );
271         nAVA->name = std::string( row[0], row[0] + l[0] );
272         nAVA->value = std::string( row[1], row[1] + l[1] );
273         cert->AVAs.push_back( nAVA );
274     }
275
276     return cert;
277 }
278
279 void MySQLJobProvider::writeBack( std::shared_ptr<Job> job, std::shared_ptr<SignedCertificate> res ) {
280     if( !conn ) {
281         throw "Error while writing back";
282     }
283
284     std::string id = "SELECT id FROM cacerts WHERE keyname='" + this->escape_string( res->ca_name ) + "'";
285
286     int err = 0;
287     std::shared_ptr<MYSQL_RES> resu;
288     std::tie( err, resu ) = query( id );
289
290     if( err ) {
291         throw "Error while looking ca cert id";
292     }
293
294     MYSQL_ROW row = mysql_fetch_row( resu.get() );
295     unsigned long* l = mysql_fetch_lengths( resu.get() );
296
297     std::string read_id;
298
299     if( !row || !l ) {
300         throw "Error while inserting new ca cert not found";
301     } else {
302         read_id = std::string( row[0], row[0] + l[0] );
303     }
304
305     std::string q = "UPDATE certs SET crt_name='" + this->escape_string( res->crt_name ) + "', serial='" + this->escape_string( res->serial ) + "', caId = '" + this->escape_string( read_id ) + "', created='" + this->escape_string( res->before ) + "', expire='" + this->escape_string( res->after ) + "'  WHERE id='" + this->escape_string( job->target ) + "' LIMIT 1";
306     // TODO write more thingies back
307
308     if( query( q ).first ) {
309         throw "Error while writing back";
310     }
311 }
312
313 std::pair<std::string, std::string> MySQLJobProvider::getRevocationInfo( std::shared_ptr<Job> job ) {
314     std::string q = "SELECT certs.serial, cacerts.keyname FROM certs INNER JOIN cacerts ON certs.caId = cacerts.id WHERE certs.id = '" + this->escape_string( job->target ) + "' ";
315     int err = 0;
316     std::shared_ptr<MYSQL_RES> resu;
317     std::tie( err, resu ) = query( q );
318
319     if( err ) {
320         throw "Error while looking ca cert id";
321     }
322
323     MYSQL_ROW row = mysql_fetch_row( resu.get() );
324     unsigned long* l = mysql_fetch_lengths( resu.get() );
325
326     if( !row || !l ) {
327         throw "Error while inserting new ca cert";
328     }
329
330     return std::pair<std::string, std::string>( std::string( row[0], row[0] + l[0] ), std::string( row[1], row[1] + l[1] ) );
331 }
332
333 void MySQLJobProvider::writeBackRevocation( std::shared_ptr<Job> job, std::string date ) {
334     if( query( "UPDATE certs SET revoked = '" + this->escape_string( date ) + "' WHERE id = '" + this->escape_string( job->target ) + "'" ).first ) {
335         throw "Error while writing back revocation";
336     }
337 }