]> WPIA git - cassiopeia.git/blob - src/db/psql.cpp
chg: make cassiopeia conform to db schema version 33
[cassiopeia.git] / src / db / psql.cpp
1 #include "psql.h"
2
3 #include <stdio.h>
4
5 #include <iostream>
6
7 #include <log/logger.hpp>
8 #include <exception>
9
10 PostgresJobProvider::PostgresJobProvider( const std::string& server, const std::string& user, const std::string& password, const std::string& database ):
11     c( "dbname=" + database + " host=" + server + " user=" + user + " password=" + password + " client_encoding=UTF-8 application_name=cassiopeia-client" ) {
12     // TODO better connection string generation??
13     pqxx::work txn( c );
14     pqxx::result version = txn.exec( "SELECT \"version\" FROM \"schemeVersion\"" );
15
16     if( version.size() != 1 ) {
17         throw std::runtime_error( "Only one version row expected but multiple found." );
18     }
19
20     if( version[0][0].as<int>() < 33 ) {
21         throw std::runtime_error( "Requires at least database schema version 33. Please update gigi before restarting cassiopeia." );
22     }
23 }
24
25
26 std::shared_ptr<Job> PostgresJobProvider::fetchJob() {
27     std::string q = "SELECT id, \"targetId\", task, \"executeFrom\", \"executeTo\", warning FROM jobs WHERE state='open' AND warning < 3";
28     pqxx::work txn( c );
29     pqxx::result result = txn.exec( q );
30
31
32     auto job = std::make_shared<Job>();
33
34     if( result.size() == 0 ) {
35         return nullptr;
36     }
37
38     job->id = result[0]["id"].as<std::string>();
39     job->target =  result[0]["\"targetId\""].as<std::string>();
40     job->task = result[0]["task"].as<std::string>();
41     job->from = result[0]["\"executeFrom\""].as<std::string>( "" );
42     job->to = result[0]["\"executeTo\""].as<std::string>( "" );
43     job->warning = result[0]["warning"].as<std::string>();
44
45     logger::notef( "Got a job: (id=%s, target=%s, task=%s, from=%s, to=%s, warnings=%s)", job->id, job->target, job->task, job->from, job->to, job->warning );
46
47     return job;
48 }
49
50 void PostgresJobProvider::finishJob( std::shared_ptr<Job> job ) {
51     pqxx::work txn( c );
52
53     std::string q = "UPDATE jobs SET state='done' WHERE id=" + txn.quote( job->id );
54     pqxx::result r = txn.exec( q );
55
56     if( r.affected_rows() != 1 ) {
57         throw std::runtime_error( "No database entry found." );
58     }
59
60     txn.commit();
61 }
62
63 void PostgresJobProvider::failJob( std::shared_ptr<Job> job ) {
64     pqxx::work txn( c );
65
66     std::string q = "UPDATE jobs SET warning = warning + 1 WHERE id=" + txn.quote( job->id );
67     pqxx::result r = txn.exec( q );
68
69     if( r.affected_rows() != 1 ) {
70         throw std::runtime_error( "No database entry found." );
71     }
72
73     txn.commit();
74 }
75
76 std::shared_ptr<TBSCertificate> PostgresJobProvider::fetchTBSCert( std::shared_ptr<Job> job ) {
77     pqxx::work txn( c );
78     auto cert = std::make_shared<TBSCertificate>();
79     std::string q = "SELECT md, profile, csr_type, keyname, att.content AS csr FROM certs INNER JOIN profiles ON profiles.id = certs.profile INNER JOIN \"certificateAttachment\" att ON att.certid=certs.id AND att.type='CSR' WHERE certs.id=" + txn.quote( job->target );
80     pqxx::result r = txn.exec( q );
81
82     if( r.size() != 1 ) {
83         throw std::runtime_error( "Error, no or multiple certs found" );
84     }
85
86     auto ro = r[0];
87
88     std::string profileName = ro["keyname"].as<std::string>();
89
90     cert->md = ro["md"].as<std::string>();
91     std::string profileId = ro["profile"].as<std::string>();
92
93     while( profileId.size() < 4 ) {
94         profileId = "0" + profileId;
95     }
96
97     cert->profile = profileId + "-" + profileName;
98
99     cert->csr_content = ro["csr"].as<std::string>();
100     cert->csr_type = ro["csr_type"].as<std::string>();
101
102     cert->SANs = std::vector<std::shared_ptr<SAN>>();
103
104     q = "SELECT contents, type FROM \"subjectAlternativeNames\" WHERE \"certId\"=" + txn.quote( job->target );
105     r = txn.exec( q );
106
107     std::cout << "Fetching SANs" << std::endl;
108
109     for( auto row = r.begin(); row != r.end(); ++row ) {
110         auto nSAN = std::make_shared<SAN>();
111         nSAN->content = row["contents"].as<std::string>();
112         nSAN->type = row["type"].as<std::string>();
113         cert->SANs.push_back( nSAN );
114     }
115
116     q = "SELECT name, value FROM \"certAvas\" WHERE \"certId\"=" + txn.quote( job->target );
117     r = txn.exec( q );
118
119     for( auto row = r.begin(); row != r.end(); ++row ) {
120         auto nAVA = std::make_shared<AVA>();
121         nAVA->name = row["name"].as<std::string>();
122         nAVA->value = row["value"].as<std::string>();
123         cert->AVAs.push_back( nAVA );
124     }
125
126     return cert;
127 }
128
129 std::string pgTime( std::string isoTime ) {
130     return isoTime.substr( 0, 8 ) + " " + isoTime.substr( 8, 6 );
131 }
132
133 void PostgresJobProvider::writeBack( std::shared_ptr<Job> job, std::shared_ptr<SignedCertificate> res ) {
134     pqxx::work txn( c );
135     std::string id = "SELECT id FROM cacerts WHERE keyname=" + txn.quote( res->ca_name );
136     pqxx::result r = txn.exec( id );
137
138     std::string read_id;
139
140     if( r.size() != 1 ) {
141         throw std::runtime_error( "Error while inserting new ca cert not found" );
142     } else {
143         read_id = r[0]["id"].as<std::string>();
144     }
145
146     std::string serial = res->serial;
147     std::transform( serial.begin(), serial.end(), serial.begin(), ::tolower );
148
149     if( serial[0] == '0' ) {
150         serial = serial.substr( 1 );
151     }
152
153     std::string q = "UPDATE certs SET serial=" + txn.quote( serial ) + ", \"caid\" = " + txn.quote( read_id ) + ", created=" + txn.quote( pgTime( res->before ) ) + ", expire=" + txn.quote( pgTime( res->after ) ) + "  WHERE id=" + txn.quote( job->target );
154     // TODO write more thingies back
155
156     r = txn.exec( q );
157
158     if( r.affected_rows() != 1 ) {
159         throw std::runtime_error( "Only one row should be updated." );
160     }
161
162     c.prepare( "insertCrt", "INSERT INTO \"certificateAttachment\"(\"certid\", \"type\", \"content\") VALUES($1,'CRT',$2)" );
163     txn.prepared( "insertCrt" )( job->target )( res->certificate ).exec();
164
165     txn.commit();
166 }
167
168 std::pair<std::string, std::string> PostgresJobProvider::getRevocationInfo( std::shared_ptr<Job> job ) {
169     pqxx::work txn( c );
170     std::string q = "SELECT certs.serial, cacerts.keyname FROM certs INNER JOIN cacerts ON certs.\"caid\" = cacerts.id WHERE certs.id = " + txn.quote( job->target );
171
172     pqxx::result r = txn.exec( q );
173
174     if( r.size() != 1 ) {
175         throw std::runtime_error( "Only one row expected but multiple found." );
176     }
177
178     return {r[0][0].as<std::string>(), r[0][1].as<std::string>()};
179 }
180
181 void PostgresJobProvider::writeBackRevocation( std::shared_ptr<Job> job, std::string date ) {
182     logger::notef( "Revoking at %s", date );
183     pqxx::work txn( c );
184     logger::note( "executing" );
185     pqxx::result r = txn.exec( "UPDATE certs SET revoked = " + txn.quote( pgTime( date ) ) + " WHERE id = " + txn.quote( job->target ) );
186
187     if( r.affected_rows() != 1 ) {
188         throw std::runtime_error( "Only one row should be updated." );
189     }
190
191     logger::note( "committing" );
192     txn.commit();
193     logger::note( "committed" );
194 }