]> WPIA git - cassiopeia.git/commitdiff
fmt: whitespace, padding and indentation formatting
authorBenny Baumann <BenBE1987@gmx.net>
Wed, 22 Mar 2017 22:39:44 +0000 (23:39 +0100)
committerBenny Baumann <BenBE1987@gmx.net>
Tue, 28 Mar 2017 18:53:39 +0000 (20:53 +0200)
Change-Id: I10baff23ab801e4b6fa47f3e943172bbce726ba5

21 files changed:
src/apps/client.cpp
src/apps/signer.cpp
src/config.cpp
src/crypto/CRL.cpp
src/crypto/X509.cpp
src/crypto/remoteSigner.cpp
src/crypto/simpleOpensslSigner.cpp
src/crypto/sslUtil.cpp
src/crypto/sslUtil.h
src/db/psql.cpp
src/io/bios.h
src/io/opensslBIO.cpp
src/io/opensslBIO.h
src/io/record.cpp
src/io/record.h
src/io/recordHandler.cpp
src/io/slipBio.cpp
src/util.cpp
src/util.h [changed mode: 0755->0644]
test/src/X509Req.cpp
test/src/bioWrapper.cpp

index 87447431665c9c31340aedc737d734f3e5d36648..c3a011531306e35685af4a7fc62413cea0b3f958 100644 (file)
@@ -59,6 +59,7 @@ int main( int argc, const char* argv[] ) {
     if( argc == 2 && std::string( "--once" ) == argv[1] ) {
         once = true;
     }
+
     if( argc == 2 && std::string( "--reset" ) == argv[1] ) {
         resetOnly = true;
     }
@@ -80,9 +81,10 @@ int main( int argc, const char* argv[] ) {
         logger::fatal( "Error: no serial device is given!" );
         return -1;
     }
+
     std::shared_ptr<JobProvider> jp = std::make_shared<PostgresJobProvider>( sqlHost, sqlUser, sqlPass, sqlDB );
     std::shared_ptr<BIO> b = openSerial( serialPath );
-    std::shared_ptr<BIO_METHOD> m( toBio<SlipBIO>(), BIO_meth_free);
+    std::shared_ptr<BIO_METHOD> m( toBio<SlipBIO>(), BIO_meth_free );
     std::shared_ptr<BIO> slip1( BIO_new( m.get() ), BIO_free );
     static_cast<SlipBIO*>( slip1->ptr )->setTarget( std::make_shared<OpensslBIOWrapper>( b ), false );
     auto sign = std::make_shared<RemoteSigner>( slip1, generateSSLContext( false ) );
@@ -98,7 +100,7 @@ int main( int argc, const char* argv[] ) {
     time_t lastCRLCheck = 0;
 
     while( true ) {
-       try {
+        try {
             time_t current;
             time( &current );
 
@@ -114,11 +116,13 @@ int main( int argc, const char* argv[] ) {
             }
 
             std::shared_ptr<Job> job;
+
             try {
                 job = jp->fetchJob();
             } catch ( std::exception &e ){
-                logger::errorf ( "Exception while fetchJob: %s", e.what() );
-           }
+                logger::errorf( "Exception while fetchJob: %s", e.what() );
+            }
+
             if( !job ) {
                 sleep( 5 );
                 continue;
@@ -126,7 +130,7 @@ int main( int argc, const char* argv[] ) {
 
             std::shared_ptr<std::ofstream> logPtr = openLogfile( std::string( "logs/" ) + job->id + std::string( "_" ) + job->warning + std::string( ".log" ) );
 
-            logger::logger_set log_set({logger::log_target(*logPtr, logger::level::debug)}, logger::auto_register::on);
+            logger::logger_set log_set( {logger::log_target( *logPtr, logger::level::debug )}, logger::auto_register::on );
 
             logger::note( "TASK ID: ", job->id );
             logger::note( "TRY:     ", job->warning );
@@ -168,7 +172,7 @@ int main( int argc, const char* argv[] ) {
                     }
 
                     logger::note( "FINE: CERTIFICATE LOG:\n", res->log,
-                                 "FINE: CERTIFICATE:\n", res->certificate );
+                                  "FINE: CERTIFICATE:\n", res->certificate );
 
                     std::string fn = writeBackFile( job->target.c_str(), res->certificate, keyDir );
 
@@ -222,7 +226,7 @@ int main( int argc, const char* argv[] ) {
                 return 0;
             }
         } catch ( std::exception &e ){
-            logger::errorf ( "std::exception in mainloop: %s", e.what() );
+            logger::errorf( "std::exception in mainloop: %s", e.what() );
         }
 
     }
index 1db3e14ecaa0a039e6808b385fcf669b1daa3824..80b5a71a7d8f472eef14113c01a202917e2c613a 100644 (file)
@@ -54,6 +54,7 @@ int main( int argc, const char* argv[] ) try {
     DefaultRecordHandler* dh = new DefaultRecordHandler( std::shared_ptr<Signer>( new SimpleOpensslSigner( ) ), slip1 );
 
     logger::note( "Entering mainloop" );
+
     while( true ) {
         try {
             dh->handle();
@@ -72,12 +73,14 @@ int main( int argc, const char* argv[] ) try {
     }catch( std::exception &e){
         printf( "Fatal Error (+logger failed): %s!\n", e.what() );
     }
+
     return -1;
 } catch( ... ) {
-    try{
+    try {
         logger::fatal( "Fatal Error: Unknown Exception!\n" );
     }catch( std::exception &e){
         printf( "Fatal Error (+ logger failed): %s!\n", e.what() );
     }
+
     return -1;
 }
index 164e0bbadef6e43eb989ddfad665833bfc4594a9..a4d32848ecb7de4e3e4609adc5a83e997d927d47 100644 (file)
@@ -23,7 +23,7 @@ std::shared_ptr<std::unordered_map<std::string, std::string>> parseConf( std::st
 
     if( !config.is_open() ) {
         logger::notef( "Where is \"%s\"?", path );
-        throw std::runtime_error("Config missing");
+        throw std::runtime_error( "Config missing" );
     }
 
     std::string line1;
@@ -117,7 +117,7 @@ int parseProfiles() {
 
             closedir( dir );
         } else {
-            throw std::runtime_error("Directory with CAConfigs not found");
+            throw std::runtime_error( "Directory with CAConfigs not found" );
         }
 
         profiles.emplace( profileName, prof );
index 01f8af5320b73def166310920010e24362458b1a..f9159fc7683ab934f6f1d88085d988d236d657ba 100644 (file)
@@ -16,34 +16,36 @@ CRL::CRL( std::string path ) {
 std::string CRL::revoke( std::string serial, std::string time ) {
     BIGNUM* serBN = 0;
 
-    logger::note("parsing serial");
+    logger::note( "parsing serial" );
+
     if( ! BN_hex2bn( &serBN, serial.c_str() ) ) {
-        throw std::runtime_error("hex2bn malloc fail");
+        throw std::runtime_error( "hex2bn malloc fail" );
     }
 
     std::shared_ptr<BIGNUM> serBNP( serBN, BN_free );
     std::shared_ptr<ASN1_INTEGER> ser( BN_to_ASN1_INTEGER( serBN, NULL ), ASN1_INTEGER_free );
 
     if( !ser ) {
-        throw std::runtime_error("BN Malloc fail");
+        throw std::runtime_error( "BN Malloc fail" );
     }
 
-    logger::note("building current time");
+    logger::note( "building current time" );
     std::shared_ptr<ASN1_TIME> tmptm( ASN1_TIME_new(), ASN1_TIME_free );
 
     if( !tmptm ) {
-        throw std::runtime_error("ASN1-Time Malloc fail");
+        throw std::runtime_error( "ASN1-Time Malloc fail" );
     }
 
     X509_gmtime_adj( tmptm.get(), 0 );
 
-    logger::note("creating entry");
+    logger::note( "creating entry" );
     X509_REVOKED* rev = X509_REVOKED_new();
     X509_REVOKED_set_serialNumber( rev, ser.get() );
 
     if( time != "" ) {
-      ASN1_TIME_set_string( tmptm.get(), time.data() );
+        ASN1_TIME_set_string( tmptm.get(), time.data() );
     }
+
     X509_REVOKED_set_revocationDate( rev, tmptm.get() );
 
     X509_CRL_add0_revoked( crl.get(), rev );
@@ -58,38 +60,39 @@ std::string CRL::revoke( std::string serial, std::string time ) {
 }
 
 void CRL::sign( std::shared_ptr<CAConfig> ca ) {
-    if(!ca->caKey){
-        throw new std::invalid_argument("Cannot sign CRL with CA " + ca->name + " because it has no private key.");
+    if( !ca->caKey ) {
+        throw new std::invalid_argument( "Cannot sign CRL with CA " + ca->name + " because it has no private key." );
     }
 
     // Updating necessary CRL props
     std::shared_ptr<ASN1_TIME> tmptm( ASN1_TIME_new(), ASN1_TIME_free );
 
     if( !tmptm ) {
-        throw std::runtime_error("ASN1-Time Malloc fail");
+        throw std::runtime_error( "ASN1-Time Malloc fail" );
     }
 
     X509_gmtime_adj( tmptm.get(), 0 );
 
-    logger::note("setting issuer");
+    logger::note( "setting issuer" );
+
     if( !X509_CRL_set_issuer_name( crl.get(), X509_get_subject_name( ca->ca.get() ) ) ) {
-        throw std::runtime_error("Setting issuer failed");
+        throw std::runtime_error( "Setting issuer failed" );
     }
 
-    logger::note("setting update");
+    logger::note( "setting update" );
     X509_CRL_set_lastUpdate( crl.get(), tmptm.get() );
 
     if( !X509_time_adj_ex( tmptm.get(), 1, 10, NULL ) ) {
-        throw std::runtime_error("Updating time failed");
+        throw std::runtime_error( "Updating time failed" );
     }
 
-    logger::note("setting next update");
+    logger::note( "setting next update" );
     X509_CRL_set_nextUpdate( crl.get(), tmptm.get() );
 
-    logger::note("sorting");
+    logger::note( "sorting" );
     // Sorting and signing
     X509_CRL_sort( crl.get() );
-    logger::note("signing");
+    logger::note( "signing" );
     X509_CRL_sign( crl.get(), ca->caKey.get(), EVP_sha256() );
 }
 
@@ -112,18 +115,18 @@ std::string CRL::getSignature() {
     const X509_ALGOR *palg;
     const ASN1_BIT_STRING *psig;
 
-    X509_CRL_get0_signature(crl.get(), &psig, &palg);
-    int len = i2d_X509_ALGOR( const_cast<X509_ALGOR*>(palg), NULL );
-    len += i2d_ASN1_BIT_STRING( const_cast<ASN1_BIT_STRING*>(psig), NULL );
-    len += i2d_ASN1_TIME( const_cast<ASN1_TIME*>(X509_CRL_get0_lastUpdate(crl.get())), NULL );
-    len += i2d_ASN1_TIME( const_cast<ASN1_TIME*>(X509_CRL_get0_nextUpdate(crl.get())), NULL );
+    X509_CRL_get0_signature( crl.get(), &psig, &palg );
+    int len = i2d_X509_ALGOR( const_cast<X509_ALGOR*>( palg ), NULL );
+    len += i2d_ASN1_BIT_STRING( const_cast<ASN1_BIT_STRING*>( psig ), NULL );
+    len += i2d_ASN1_TIME( const_cast<ASN1_TIME*>( X509_CRL_get0_lastUpdate( crl.get() ) ), NULL );
+    len += i2d_ASN1_TIME( const_cast<ASN1_TIME*>( X509_CRL_get0_nextUpdate( crl.get() ) ), NULL );
 
     unsigned char* buffer = ( unsigned char* ) OPENSSL_malloc( len );
     unsigned char* pos = buffer;
-    i2d_X509_ALGOR( const_cast<X509_ALGOR*>(palg), &pos );
-    i2d_ASN1_BIT_STRING( const_cast<ASN1_BIT_STRING*>(psig), &pos );
-    i2d_ASN1_TIME( const_cast<ASN1_TIME*>(X509_CRL_get0_lastUpdate(crl.get())), &pos );
-    i2d_ASN1_TIME( const_cast<ASN1_TIME*>(X509_CRL_get0_nextUpdate(crl.get())), &pos );
+    i2d_X509_ALGOR( const_cast<X509_ALGOR*>( palg ), &pos );
+    i2d_ASN1_BIT_STRING( const_cast<ASN1_BIT_STRING*>( psig ), &pos );
+    i2d_ASN1_TIME( const_cast<ASN1_TIME*>( X509_CRL_get0_lastUpdate( crl.get() ) ), &pos );
+    i2d_ASN1_TIME( const_cast<ASN1_TIME*>( X509_CRL_get0_nextUpdate( crl.get() ) ), &pos );
     std::string res = std::string( ( char* ) buffer, len );
     OPENSSL_free( buffer );
 
index f9dbc7a7ff65aef55e4fefd0edd4d01ba1ae8d4a..e304b908abb5a8d0cee172f62961e9697ac25df5 100644 (file)
@@ -11,7 +11,7 @@ X509Req::X509Req( X509_REQ* csr ) : req( csr, X509_REQ_free ) {
     EVP_PKEY* pkt = X509_REQ_get_pubkey( req.get() );
 
     if( !pkt ) {
-        throw std::runtime_error("Error extracting public key");
+        throw std::runtime_error( "Error extracting public key" );
     }
 
     pk = std::shared_ptr<EVP_PKEY>( pkt, EVP_PKEY_free );
@@ -19,21 +19,21 @@ X509Req::X509Req( X509_REQ* csr ) : req( csr, X509_REQ_free ) {
 
 X509Req::X509Req( std::string spkac ) {
     if( spkac.compare( 0, 6, "SPKAC=" ) != 0 ) {
-        throw std::runtime_error("Error: not a SPKAC");
+        throw std::runtime_error( "Error: not a SPKAC" );
     }
 
     spkac = spkac.substr( 6 );
     NETSCAPE_SPKI* spki_p = NETSCAPE_SPKI_b64_decode( spkac.c_str(), spkac.size() );
 
     if( !spki_p ) {
-        throw std::runtime_error("Error: decode failed");
+        throw std::runtime_error( "Error: decode failed" );
     }
 
     spki = std::shared_ptr<NETSCAPE_SPKI>( spki_p, NETSCAPE_SPKI_free );
     EVP_PKEY* pkt_p = NETSCAPE_SPKI_get_pubkey( spki.get() );
 
     if( !pkt_p ) {
-        throw std::runtime_error("Error: reading SPKAC Pubkey failed");
+        throw std::runtime_error( "Error: reading SPKAC Pubkey failed" );
     }
 
     pk = std::shared_ptr<EVP_PKEY>( pkt_p, EVP_PKEY_free );
@@ -56,10 +56,10 @@ std::shared_ptr<X509Req> X509Req::parseCSR( std::string content ) {
     X509_REQ* req = PEM_read_bio_X509_REQ( in.get(), NULL, NULL, NULL );
 
     if( !req ) {
-        throw std::runtime_error("Error parsing CSR");
+        throw std::runtime_error( "Error parsing CSR" );
     }
 
-    return std::shared_ptr<X509Req>( new X509Req( req )); // TODO ask
+    return std::shared_ptr<X509Req>( new X509Req( req ) ); // TODO ask
 }
 
 std::shared_ptr<X509Req> X509Req::parseSPKAC( std::string content ) {
@@ -94,19 +94,19 @@ X509Cert::X509Cert() {
     X509* c = X509_new();
 
     if( !c ) {
-        throw std::runtime_error("malloc failed");
+        throw std::runtime_error( "malloc failed" );
     }
 
     target = std::shared_ptr<X509>( c, X509_free );
 
     if( !X509_set_version( c, 2 ) ) {
-        throw std::runtime_error("Setting X509-version to 3 failed");
+        throw std::runtime_error( "Setting X509-version to 3 failed" );
     }
 
     X509_NAME* subjectP = X509_NAME_new();
 
     if( !subjectP ) {
-        throw std::runtime_error("malloc failure in construct.");
+        throw std::runtime_error( "malloc failure in construct." );
     }
 
     subject = std::shared_ptr<X509_NAME>( subjectP, X509_NAME_free );
@@ -114,13 +114,13 @@ X509Cert::X509Cert() {
 
 void X509Cert::addRDN( int nid, std::string data ) {
     if( ! X509_NAME_add_entry_by_NID( subject.get(), nid, MBSTRING_UTF8, ( unsigned char* )const_cast<char*>( data.data() ), data.size(), -1, 0 ) ) {
-        throw std::runtime_error("malloc failure in RDN");
+        throw std::runtime_error( "malloc failure in RDN" );
     }
 }
 
 void X509Cert::setIssuerNameFrom( std::shared_ptr<X509> caCert ) {
     if( !X509_set_issuer_name( target.get(), X509_get_subject_name( caCert.get() ) ) ) {
-        throw std::runtime_error("Error setting Issuer name");
+        throw std::runtime_error( "Error setting Issuer name" );
     }
 }
 
@@ -128,14 +128,14 @@ void X509Cert::setPubkeyFrom( std::shared_ptr<X509Req> req ) {
     std::shared_ptr<EVP_PKEY> pktmp = req->getPkey();
 
     if( !X509_set_pubkey( target.get(), pktmp.get() ) ) {
-        throw std::runtime_error("Setting public key failed.");
+        throw std::runtime_error( "Setting public key failed." );
     }
 }
 
 void X509Cert::setSerialNumber( BIGNUM* num ) {
     ASN1_INTEGER *i = BN_to_ASN1_INTEGER( num, NULL);
-    X509_set_serialNumber(target.get(), i);
-    ASN1_INTEGER_free(i);
+    X509_set_serialNumber( target.get(), i );
+    ASN1_INTEGER_free( i );
 }
 
 void X509Cert::setTimes( uint32_t before, uint32_t after ) {
@@ -173,7 +173,7 @@ static X509_EXTENSION* do_ext_i2d( int ext_nid, int crit, ASN1_VALUE* ext_struc
     return ext;
 
 merr:
-    throw std::runtime_error("memerr");
+    throw std::runtime_error( "memerr" );
 }
 
 void X509Cert::setExtensions( std::shared_ptr<X509> caCert, std::vector<std::shared_ptr<SAN>>& sans, Profile& prof, std::string crlURL, std::string crtURL ) {
@@ -183,8 +183,8 @@ void X509Cert::setExtensions( std::shared_ptr<X509> caCert, std::vector<std::sha
     std::string ku = std::string( "critical," ) + prof.ku;
     add_ext( caCert, target, NID_key_usage, ku.c_str() );
     add_ext( caCert, target, NID_ext_key_usage, prof.eku.c_str() );
-    add_ext( caCert, target, NID_info_access, ("OCSP;URI:http://ocsp.cacert.org,caIssuers;URI:" + crtURL).c_str() );
-    add_ext( caCert, target, NID_crl_distribution_points, ("URI:" + crlURL).c_str() );
+    add_ext( caCert, target, NID_info_access, ( "OCSP;URI:http://ocsp.cacert.org,caIssuers;URI:" + crtURL ).c_str() );
+    add_ext( caCert, target, NID_crl_distribution_points, ( "URI:" + crlURL ).c_str() );
 
     if( sans.empty() ) {
         return;
@@ -202,7 +202,7 @@ void X509Cert::setExtensions( std::shared_ptr<X509> caCert, std::vector<std::sha
         GENERAL_NAME* gen = GENERAL_NAME_new();
 
         if( !gen ) {
-            throw std::runtime_error("Malloc failure.");
+            throw std::runtime_error( "Malloc failure." );
         }
 
         gen->type = name->type == "DNS" ? GEN_DNS : name->type == "email" ? GEN_EMAIL : 0; // GEN_EMAIL;
@@ -211,7 +211,7 @@ void X509Cert::setExtensions( std::shared_ptr<X509> caCert, std::vector<std::sha
                 || !( gen->d.ia5 = ASN1_IA5STRING_new() )
                 || !ASN1_STRING_set( gen->d.ia5, name->content.data(), name->content.size() ) ) {
             GENERAL_NAME_free( gen );
-            throw std::runtime_error("initing iasting5 failed");
+            throw std::runtime_error( "initing iasting5 failed" );
         }
 
         sk_GENERAL_NAME_push( gens.get(), gen );
@@ -225,7 +225,7 @@ void X509Cert::setExtensions( std::shared_ptr<X509> caCert, std::vector<std::sha
 
 std::shared_ptr<SignedCertificate> X509Cert::sign( std::shared_ptr<EVP_PKEY> caKey, std::string signAlg ) {
     if( !X509_set_subject_name( target.get(), subject.get() ) ) {
-        throw std::runtime_error("error setting subject");
+        throw std::runtime_error( "error setting subject" );
     }
 
     const EVP_MD* md;
@@ -237,15 +237,15 @@ std::shared_ptr<SignedCertificate> X509Cert::sign( std::shared_ptr<EVP_PKEY> caK
     } else if( signAlg == "sha256" ) {
         md = EVP_sha256();
     } else if( signAlg == "sha1" ) {
-        throw std::runtime_error("Refusing to sign with weak signature algorithm (SHA-1).");
+        throw std::runtime_error( "Refusing to sign with weak signature algorithm (SHA-1)." );
     } else if( signAlg == "md5" ) {
-        throw std::runtime_error("Refusing to sign with weak signature algorithm (MD5).");
+        throw std::runtime_error( "Refusing to sign with weak signature algorithm (MD5)." );
     } else {
-        throw std::runtime_error("Unknown signature algorithm");
+        throw std::runtime_error( "Unknown signature algorithm" );
     }
 
     if( !X509_sign( target.get(), caKey.get(), md ) ) {
-        throw std::runtime_error("Signing failed.");
+        throw std::runtime_error( "Signing failed." );
     }
 
     //X509_print_fp( stdout, target.get() );
@@ -253,7 +253,7 @@ std::shared_ptr<SignedCertificate> X509Cert::sign( std::shared_ptr<EVP_PKEY> caK
     std::shared_ptr<BIO> mem = std::shared_ptr<BIO>( BIO_new( BIO_s_mem() ), BIO_free );
 
     if( !mem ) {
-        throw std::runtime_error("Failed to allocate memory for the signed certificate.");
+        throw std::runtime_error( "Failed to allocate memory for the signed certificate." );
     }
 
     PEM_write_bio_X509( mem.get(), target.get() );
@@ -264,10 +264,10 @@ std::shared_ptr<SignedCertificate> X509Cert::sign( std::shared_ptr<EVP_PKEY> caK
     auto res = std::make_shared<SignedCertificate>();
     res->certificate = std::string( buf->data, buf->data + buf->length );
 
-    std::shared_ptr<BIGNUM> ser( ASN1_INTEGER_to_BN( X509_get_serialNumber(target.get()), NULL ), BN_free );
+    std::shared_ptr<BIGNUM> ser( ASN1_INTEGER_to_BN( X509_get_serialNumber( target.get() ), NULL ), BN_free );
 
     if( !ser ) {
-        throw std::runtime_error("Failed to retrieve certificate serial of signed certificate.");
+        throw std::runtime_error( "Failed to retrieve certificate serial of signed certificate." );
     }
 
     std::shared_ptr<char> serStr(
index a953458d8842f11f006afef1ab350d60c7ea8864..c52936b8bc2afe26e78f0341a0fbfd2ce7276819 100644 (file)
@@ -75,7 +75,7 @@ std::shared_ptr<SignedCertificate> RemoteSigner::sign( std::shared_ptr<TBSCertif
             RecordHeader head;
             std::string payload = parseCommandChunked( head, conn );
 
-            switch( static_cast<RecordHeader::SignerResult>( head.command )) {
+            switch( static_cast<RecordHeader::SignerResult>( head.command ) ) {
             case RecordHeader::SignerResult::CERTIFICATE:
                 result->certificate = payload;
                 break;
@@ -107,7 +107,7 @@ std::shared_ptr<SignedCertificate> RemoteSigner::sign( std::shared_ptr<TBSCertif
             int dlen = BIO_write( bios.get(), buf, len );
 
             if( dlen <= 0 ) {
-                throw std::runtime_error("Memory error.");
+                throw std::runtime_error( "Memory error." );
             }
 
             len -= dlen;
@@ -117,10 +117,10 @@ std::shared_ptr<SignedCertificate> RemoteSigner::sign( std::shared_ptr<TBSCertif
         std::shared_ptr<X509> pem( PEM_read_bio_X509( bios.get(), NULL, 0, NULL ), X509_free );
 
         if( !pem ) {
-            throw std::runtime_error("Pem was not readable");
+            throw std::runtime_error( "Pem was not readable" );
         }
 
-        std::shared_ptr<BIGNUM> ser( ASN1_INTEGER_to_BN( X509_get_serialNumber(pem.get()), NULL), BN_free );
+        std::shared_ptr<BIGNUM> ser( ASN1_INTEGER_to_BN( X509_get_serialNumber( pem.get() ), NULL ), BN_free );
         std::shared_ptr<char> serStr(
             BN_bn2hex( ser.get() ),
             []( char* p ) {
@@ -133,9 +133,11 @@ std::shared_ptr<SignedCertificate> RemoteSigner::sign( std::shared_ptr<TBSCertif
     }
 
     logger::note( "Closing SSL connection" );
+
     if( !SSL_shutdown( ssl.get() ) && !SSL_shutdown( ssl.get() ) ) { // need to close the connection twice
         logger::warn( "SSL shutdown failed" );
     }
+
     logger::note( "SSL connection closed" );
 
     return result;
@@ -169,7 +171,7 @@ std::pair<std::shared_ptr<CRL>, std::string> RemoteSigner::revoke( std::shared_p
     std::string date;
 
     if( static_cast<RecordHeader::SignerResult>( head.command ) != RecordHeader::SignerResult::REVOKED ) {
-        throw std::runtime_error("Protocol violation");
+        throw std::runtime_error( "Protocol violation" );
     }
 
     const unsigned char* buffer2 = reinterpret_cast<const unsigned char*>( payload.data() );
@@ -196,7 +198,7 @@ std::pair<std::shared_ptr<CRL>, std::string> RemoteSigner::revoke( std::shared_p
         payload = parseCommandChunked( head, conn );
 
         if( static_cast<RecordHeader::SignerResult>( head.command ) != RecordHeader::SignerResult::FULL_CRL ) {
-            throw std::runtime_error("Protocol violation");
+            throw std::runtime_error( "Protocol violation" );
         }
 
         std::string name_bak = ca->path + std::string( "/ca.crl.bak" );
@@ -204,9 +206,10 @@ std::pair<std::shared_ptr<CRL>, std::string> RemoteSigner::revoke( std::shared_p
         crl = std::make_shared<CRL>( name_bak );
 
         if( crl->verify( ca ) ) {
-            if( rename( name_bak.c_str(), tgtName.c_str() ) != 0 ){
+            if( rename( name_bak.c_str(), tgtName.c_str() ) != 0 ) {
                 logger::warn( "Moving new CRL over old CRL failed" );
             }
+
             logger::note( "CRL is now valid again" );
         } else {
             logger::warn( "CRL is still broken... Please, help me" );
@@ -214,9 +217,11 @@ std::pair<std::shared_ptr<CRL>, std::string> RemoteSigner::revoke( std::shared_p
     }
 
     logger::note( "Closing SSL connection" );
+
     if( !SSL_shutdown( ssl.get() ) && !SSL_shutdown( ssl.get() ) ) { // need to close the connection twice
         logger::warn( "SSL shutdown failed" );
     }
+
     logger::note( "SSL connection closed" );
 
     return { crl, date };
index 6987d2c4e84085c25c3349f5c334e42e82475dbe..b569ef2fa5789544b101d7e8653b3cb76a9d9a54 100644 (file)
@@ -36,12 +36,12 @@ std::pair<std::shared_ptr<BIGNUM>, std::string> SimpleOpensslSigner::nextSerial(
     if( res == "" ) {
         bn = BN_new();
 
-        if( !bn || !BN_hex2bn( &bn, "1" )) {
-            throw std::runtime_error("Initing serial failed");
+        if( !bn || !BN_hex2bn( &bn, "1" ) ) {
+            throw std::runtime_error( "Initing serial failed" );
         }
     } else {
         if( !BN_hex2bn( &bn, res.c_str() ) ) {
-            throw std::runtime_error("Parsing serial failed.");
+            throw std::runtime_error( "Parsing serial failed." );
         }
     }
 
@@ -57,7 +57,7 @@ std::pair<std::shared_ptr<BIGNUM>, std::string> SimpleOpensslSigner::nextSerial(
     data.get()[len + 3] = profile & 0xFF; // profile id
 
     if( !RAND_bytes( data.get() + len + 4, 16 ) || !BN_add_word( serial.get(), 1 ) ) {
-        throw std::runtime_error("Big number math failed while fetching random data for serial number.");
+        throw std::runtime_error( "Big number math failed while fetching random data for serial number." );
     }
 
     std::shared_ptr<char> serStr = std::shared_ptr<char>(
@@ -68,12 +68,12 @@ std::pair<std::shared_ptr<BIGNUM>, std::string> SimpleOpensslSigner::nextSerial(
 
     writeFile( ca->path + "/serial", serStr.get() );
 
-    return std::pair<std::shared_ptr<BIGNUM>, std::string>( std::shared_ptr<BIGNUM>( BN_bin2bn( data.get(), len + 4 + 16 , 0 ), BN_free ), std::string( serStr.get() ) );
+    return std::pair<std::shared_ptr<BIGNUM>, std::string>( std::shared_ptr<BIGNUM>( BN_bin2bn( data.get(), len + 4 + 16, 0 ), BN_free ), std::string( serStr.get() ) );
 }
 
 std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TBSCertificate> cert ) {
     std::stringstream signlog;
-    logger::logger_set log_set_sign({logger::log_target(signlog, logger::level::debug)}, logger::auto_register::on);
+    logger::logger_set log_set_sign( {logger::log_target( signlog, logger::level::debug )}, logger::auto_register::on );
 
     logger::note( "FINE: Profile name is: ", cert->profile );
 
@@ -84,10 +84,11 @@ std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TB
 
     if( !ca ) {
         logger::error( "ERROR: Signing CA specified in profile could not be loaded." );
-        throw std::runtime_error("CA-key not found");
+        throw std::runtime_error( "CA-key not found" );
     }
-    if(!ca->caKey){
-        throw std::runtime_error("Cannot sign certificate with CA " + ca->name + " because it has no private key.");
+
+    if( !ca->caKey ) {
+        throw std::runtime_error( "Cannot sign certificate with CA " + ca->name + " because it has no private key." );
     }
 
     logger::note( "FINE: Key for Signing CA is correctly loaded." );
@@ -106,15 +107,15 @@ std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TB
         req = X509Req::parseCSR( cert->csr_content );
     } else {
         logger::errorf( "ERROR: Unknown type (\"%s\") of certification in request.", cert->csr_type );
-        throw std::runtime_error("Error, unknown REQ rype " + cert->csr_type ); //! \fixme: Pointer instead of string, please use proper exception classe)s
+        throw std::runtime_error( "Error, unknown REQ rype " + cert->csr_type ); //! \fixme: Pointer instead of string, please use proper exception classe)s
     }
 
     int i = req->verify();
 
     if( i < 0 ) {
-        throw std::runtime_error("Request contains a Signature with problems ... ");
+        throw std::runtime_error( "Request contains a Signature with problems ... " );
     } else if( i == 0 ) {
-        throw std::runtime_error("Request contains a Signature that does not match ...");
+        throw std::runtime_error( "Request contains a Signature that does not match ..." );
     } else {
         logger::note( "FINE: Request contains valid self-signature." );
     }
@@ -126,10 +127,12 @@ std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TB
 
     for( std::shared_ptr<AVA> a : cert->AVAs ) {
         logger::notef( "INFO: Trying to add RDN: %s: %s", a->name, a->value );
+
         if( a->value.empty() ) {
-            logger::notef( "INFO: Removing empty RDN: %s", a->name);
+            logger::notef( "INFO: Removing empty RDN: %s", a->name );
             continue;
         }
+
         if( a->name == "CN" ) {
             c.addRDN( NID_commonName, a->value );
         } else if( a->name == "EMAIL" ) {
@@ -146,7 +149,7 @@ std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TB
             c.addRDN( NID_organizationalUnitName, a->value );
         } else {
             logger::error( "ERROR: Trying to add illegal RDN/AVA type: ", a->name );
-            throw std::runtime_error("Unhandled/Illegal AVA type");
+            throw std::runtime_error( "Unhandled/Illegal AVA type" );
         }
     }
 
@@ -248,7 +251,7 @@ std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TB
 
         if( fn.empty() ) {
             logger::error( "ERROR: failed to get filename for storage of signed certificate." );
-            throw std::runtime_error("Storage location could not be determined");
+            throw std::runtime_error( "Storage location could not be determined" );
         }
 
         logger::note( "FINE: Certificate signed successfully." );
@@ -268,6 +271,7 @@ std::pair<std::shared_ptr<CRL>, std::string> SimpleOpensslSigner::revoke( std::s
     std::string date = "";
 
     logger::note( "adding serials" );
+
     for( std::string serial : serials ) {
         date = crl->revoke( serial, "" );
     }
index d7fddfe40fd4a54557e907cfe16bacdd212acfeb..8a68c61ef45e13f677dbaf56deb84c64c32139a3 100644 (file)
@@ -97,7 +97,7 @@ std::shared_ptr<SSL_CTX> generateSSLContext( bool server ) {
         } );
 
     if( !SSL_CTX_set_cipher_list( ctx.get(), "HIGH:+CAMELLIA256:!eNull:!aNULL:!ADH:!MD5:-RSA+AES+SHA1:!RC4:!DES:!3DES:!SEED:!EXP:!AES128:!CAMELLIA128" ) ) {
-        throw std::runtime_error("Cannot set cipher list. Your source is broken.");
+        throw std::runtime_error( "Cannot set cipher list. Your source is broken." );
     }
 
     SSL_CTX_set_verify( ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback );
@@ -105,7 +105,7 @@ std::shared_ptr<SSL_CTX> generateSSLContext( bool server ) {
     SSL_CTX_use_PrivateKey_file( ctx.get(), server ? "keys/signer_server.key" : "keys/signer_client.key", SSL_FILETYPE_PEM );
 
     if( 1 != SSL_CTX_load_verify_locations( ctx.get(), "keys/ca.crt", 0 ) ) {
-        throw std::runtime_error("Cannot load CA store for certificate validation.");
+        throw std::runtime_error( "Cannot load CA store for certificate validation." );
     }
 
     if( server ) {
@@ -126,12 +126,13 @@ std::shared_ptr<SSL_CTX> generateSSLContext( bool server ) {
                 dh_param = std::shared_ptr<DH>( DH_new(), DH_free );
                 logger::note( "Generating DH params" );
                 BN_GENCB *cb = BN_GENCB_new();
-               BN_GENCB_set(cb, gencb, NULL);
+                BN_GENCB_set( cb, gencb, NULL );
 
                 if( !DH_generate_parameters_ex( dh_param.get(), 2048, 5, cb ) ) {
-                    throw std::runtime_error("DH generation failed");
+                    throw std::runtime_error( "DH generation failed" );
                 }
-               BN_GENCB_free(cb);
+
+                BN_GENCB_free( cb );
 
                 std::cout << std::endl;
                 paramfile = std::shared_ptr<FILE>( fopen( "dh_param.pem", "w" ), fclose );
@@ -143,7 +144,7 @@ std::shared_ptr<SSL_CTX> generateSSLContext( bool server ) {
         }
 
         if( !SSL_CTX_set_tmp_dh( ctx.get(), dh_param.get() ) ) {
-            throw std::runtime_error("Cannot set tmp dh.");
+            throw std::runtime_error( "Cannot set tmp dh." );
         }
     }
 
@@ -154,7 +155,7 @@ void setupSerial( std::shared_ptr<FILE> f ) {
     struct termios attr;
 
     if( tcgetattr( fileno( f.get() ), &attr ) ) {
-        throw std::runtime_error("failed to get attrs");
+        throw std::runtime_error( "failed to get attrs" );
     }
 
     attr.c_iflag &= ~( IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON );
@@ -167,7 +168,7 @@ void setupSerial( std::shared_ptr<FILE> f ) {
     cfsetospeed( &attr, B115200 );
 
     if( tcsetattr( fileno( f.get() ), TCSANOW, &attr ) ) {
-        throw std::runtime_error("failed to get attrs");
+        throw std::runtime_error( "failed to get attrs" );
     }
 }
 
@@ -192,35 +193,40 @@ extern std::string crtPrefix;
 
 CAConfig::CAConfig( const std::string& name ) : path( "ca/" + name ), name( name ) {
     ca = loadX509FromFile( path + "/ca.crt" );
-    if (!ca) {
-        throw new std::invalid_argument("ca name: " + name + " contains unreadable certificate.");
+
+    if( !ca ) {
+        throw new std::invalid_argument( "ca name: " + name + " contains unreadable certificate." );
     }
 
     caKey = loadPkeyFromFile( path + "/ca.key" );
 
     ASN1_TIME* tm = X509_get_notBefore( ca.get() ); // tm MUST NOT be free'd; duplicate for owning copy.
-    notBefore = std::shared_ptr<ASN1_TIME>( ASN1_STRING_dup(tm), ASN1_TIME_free );
+    notBefore = std::shared_ptr<ASN1_TIME>( ASN1_STRING_dup( tm ), ASN1_TIME_free );
+
+    std::size_t pos = name.find( "_" );
 
-    std::size_t pos = name.find("_");
-    if (pos == std::string::npos) {
-        throw new std::invalid_argument("ca name: " + name + " is malformed.");
+    if( pos == std::string::npos ) {
+        throw new std::invalid_argument( "ca name: " + name + " is malformed." );
     }
-    std::size_t pos2 = name.find("_", pos + 1);
-    if (pos2 == std::string::npos) {
-        throw new std::invalid_argument("ca name: " + name + " is malformed.");
+
+    std::size_t pos2 = name.find( "_", pos + 1 );
+
+    if( pos2 == std::string::npos ) {
+        throw new std::invalid_argument( "ca name: " + name + " is malformed." );
     }
 
-    crlURL = crlPrefix + "/g2/" + name.substr(pos+1, pos2-pos - 1) + "/" + name.substr(0,pos) + "-" + name.substr(pos2+1) + ".crl";
-    crtURL = crtPrefix + "/g2/" + name.substr(pos+1, pos2-pos - 1) + "/" + name.substr(0,pos) + "-" + name.substr(pos2+1) + ".crt";
+    crlURL = crlPrefix + "/g2/" + name.substr( pos + 1, pos2 - pos - 1 ) + "/" + name.substr( 0, pos ) + "-" + name.substr( pos2 + 1 ) + ".crl";
+    crtURL = crtPrefix + "/g2/" + name.substr( pos + 1, pos2 - pos - 1 ) + "/" + name.substr( 0, pos ) + "-" + name.substr( pos2 + 1 ) + ".crt";
 }
 
 std::string timeToString( std::shared_ptr<ASN1_TIME> time ) {
-  std::shared_ptr<ASN1_GENERALIZEDTIME> gtime( ASN1_TIME_to_generalizedtime( time.get(), 0 ), ASN1_GENERALIZEDTIME_free );
+    std::shared_ptr<ASN1_GENERALIZEDTIME> gtime( ASN1_TIME_to_generalizedtime( time.get(), 0 ), ASN1_GENERALIZEDTIME_free );
     std::string strdate( ( char* ) ASN1_STRING_get0_data( gtime.get() ), ASN1_STRING_length( gtime.get() ) );
 
-    logger::notef("openssl formatted me a date: %s", strdate);
+    logger::notef( "openssl formatted me a date: %s", strdate );
+
     if( strdate[strdate.size() - 1] != 'Z' ) {
-        throw std::runtime_error("Got invalid date?");
+        throw std::runtime_error( "Got invalid date?" );
     }
 
     return strdate.substr( 0, strdate.size() - 1 );
index 569c20058eccd47dac2c2125e7e138bd6b774d96..2ecba42b9874686014d7c72ac77919de321a1b63 100644 (file)
@@ -36,14 +36,15 @@ struct Profile {
     std::time_t maxValidity;
     std::shared_ptr<CAConfig> getCA() {
         std::shared_ptr<CAConfig> min = nullptr;
+
         for( auto it = ca.rbegin(); it != ca.rend(); it++ ) {
-            if( X509_cmp_current_time( ( *it )->notBefore.get() ) < 0) {
-                if(min != nullptr){
-                    if(strcmp(min->name.c_str(), (*it)->name.c_str()) < 0){
+            if( X509_cmp_current_time( ( *it )->notBefore.get() ) < 0 ) {
+                if( min != nullptr ) {
+                    if( strcmp( min->name.c_str(), ( *it )->name.c_str() ) < 0 ) {
                         min = *it;
                     }
-                }else{
-                    min=*it;
+                } else {
+                    min = *it;
                 }
             }
         }
index 053f11be95879646ae6a5093f90339a03e65687a..41219944f0258d8c257d9e8f16d25d412df2b107 100644 (file)
@@ -8,15 +8,15 @@
 #include <exception>
 
 PostgresJobProvider::PostgresJobProvider( const std::string& server, const std::string& user, const std::string& password, const std::string& database ):
-    c("dbname="+database+" host="+server+" user="+user+" password=" + password + " client_encoding=UTF-8 application_name=cassiopeia-client"){
+    c( "dbname=" + database + " host=" + server + " user=" + user + " password=" + password + " client_encoding=UTF-8 application_name=cassiopeia-client" ) {
     // TODO better connection string generation??
 }
 
 
 std::shared_ptr<Job> PostgresJobProvider::fetchJob() {
     std::string q = "SELECT id, \"targetId\", task, \"executeFrom\", \"executeTo\", warning FROM jobs WHERE state='open' AND warning < 3";
-    pqxx::work txn(c);
-    pqxx::result result = txn.exec(q);
+    pqxx::work txn( c );
+    pqxx::result result = txn.exec( q );
 
 
     auto job = std::make_shared<Job>();
@@ -28,8 +28,8 @@ std::shared_ptr<Job> PostgresJobProvider::fetchJob() {
     job->id = result[0]["id"].as<std::string>();
     job->target =  result[0]["\"targetId\""].as<std::string>();
     job->task = result[0]["task"].as<std::string>();
-    job->from = result[0]["\"executeFrom\""].as<std::string>("");
-    job->to = result[0]["\"executeTo\""].as<std::string>("");
+    job->from = result[0]["\"executeFrom\""].as<std::string>( "" );
+    job->to = result[0]["\"executeTo\""].as<std::string>( "" );
     job->warning = result[0]["warning"].as<std::string>();
 
     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 );
@@ -38,38 +38,41 @@ std::shared_ptr<Job> PostgresJobProvider::fetchJob() {
 }
 
 void PostgresJobProvider::finishJob( std::shared_ptr<Job> job ) {
-    pqxx::work txn(c);
+    pqxx::work txn( c );
 
     std::string q = "UPDATE jobs SET state='done' WHERE id=" + txn.quote( job->id );
-    pqxx::result r = txn.exec(q);
+    pqxx::result r = txn.exec( q );
 
     if( r.affected_rows() != 1 ) {
-        throw std::runtime_error("No database entry found.");
+        throw std::runtime_error( "No database entry found." );
     }
+
     txn.commit();
 }
 
 void PostgresJobProvider::failJob( std::shared_ptr<Job> job ) {
-    pqxx::work txn(c);
+    pqxx::work txn( c );
 
     std::string q = "UPDATE jobs SET warning = warning + 1 WHERE id=" + txn.quote( job->id );
-    pqxx::result r = txn.exec(q);
+    pqxx::result r = txn.exec( q );
 
     if( r.affected_rows() != 1 ) {
-        throw std::runtime_error("No database entry found.");
+        throw std::runtime_error( "No database entry found." );
     }
+
     txn.commit();
 }
 
 std::shared_ptr<TBSCertificate> PostgresJobProvider::fetchTBSCert( std::shared_ptr<Job> job ) {
-    pqxx::work txn(c);
+    pqxx::work txn( c );
     auto cert = std::make_shared<TBSCertificate>();
     std::string q = "SELECT md, profile, csr_name, csr_type, keyname FROM certs INNER JOIN profiles ON profiles.id = certs.profile WHERE certs.id=" + txn.quote( job->target );
-    pqxx::result r = txn.exec(q);
+    pqxx::result r = txn.exec( q );
 
     if( r.size() != 1 ) {
-        throw std::runtime_error("Error, no or multiple certs found");
-     }
+        throw std::runtime_error( "Error, no or multiple certs found" );
+    }
+
     auto ro = r[0];
 
     std::string profileName = ro["keyname"].as<std::string>();
@@ -93,7 +96,7 @@ std::shared_ptr<TBSCertificate> PostgresJobProvider::fetchTBSCert( std::shared_p
 
     std::cout << "Fetching SANs" << std::endl;
 
-    for( auto row = r.begin(); row != r.end(); ++row) {
+    for( auto row = r.begin(); row != r.end(); ++row ) {
         auto nSAN = std::make_shared<SAN>();
         nSAN->content = row["contents"].as<std::string>();
         nSAN->type = row["type"].as<std::string>();
@@ -103,7 +106,7 @@ std::shared_ptr<TBSCertificate> PostgresJobProvider::fetchTBSCert( std::shared_p
     q = "SELECT name, value FROM \"certAvas\" WHERE \"certId\"=" + txn.quote( job->target );
     r = txn.exec( q );
 
-    for( auto row = r.begin(); row != r.end(); ++row) {
+    for( auto row = r.begin(); row != r.end(); ++row ) {
         auto nAVA = std::make_shared<AVA>();
         nAVA->name = row["name"].as<std::string>();
         nAVA->value = row["value"].as<std::string>();
@@ -113,58 +116,65 @@ std::shared_ptr<TBSCertificate> PostgresJobProvider::fetchTBSCert( std::shared_p
     return cert;
 }
 
-std::string pgTime( std::string isoTime){
-       return isoTime.substr(0, 8) + " " + isoTime.substr(8, 6);
+std::string pgTime( std::string isoTime ) {
+    return isoTime.substr( 0, 8 ) + " " + isoTime.substr( 8, 6 );
 }
 
 void PostgresJobProvider::writeBack( std::shared_ptr<Job> job, std::shared_ptr<SignedCertificate> res ) {
-    pqxx::work txn(c);
+    pqxx::work txn( c );
     std::string id = "SELECT id FROM cacerts WHERE keyname=" + txn.quote( res->ca_name );
-    pqxx::result r = txn.exec(id);
+    pqxx::result r = txn.exec( id );
 
     std::string read_id;
 
-    if( r.size() != 1) {
-        throw std::runtime_error("Error while inserting new ca cert not found");
+    if( r.size() != 1 ) {
+        throw std::runtime_error( "Error while inserting new ca cert not found" );
     } else {
         read_id = r[0]["id"].as<std::string>();
     }
+
     std::string serial = res->serial;
-    std::transform(serial.begin(), serial.end(), serial.begin(), ::tolower);
-    if(serial[0] == '0'){
-        serial = serial.substr(1);
+    std::transform( serial.begin(), serial.end(), serial.begin(), ::tolower );
+
+    if( serial[0] == '0' ) {
+        serial = serial.substr( 1 );
     }
-    std::string q = "UPDATE certs SET crt_name=" + txn.quote( res->crt_name ) + ", 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 );
+
+    std::string q = "UPDATE certs SET crt_name=" + txn.quote( res->crt_name ) + ", 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 );
     // TODO write more thingies back
 
     r = txn.exec( q );
-    if( r.affected_rows() != 1 ){
-        throw std::runtime_error("Only one row should be updated.");
+
+    if( r.affected_rows() != 1 ) {
+        throw std::runtime_error( "Only one row should be updated." );
     }
+
     txn.commit();
 }
 
 std::pair<std::string, std::string> PostgresJobProvider::getRevocationInfo( std::shared_ptr<Job> job ) {
-    pqxx::work txn(c);
+    pqxx::work txn( c );
     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 );
 
     pqxx::result r = txn.exec( q );
-    if( r.size() != 1) {
-        throw std::runtime_error("Only one row expected but multiple found.");
+
+    if( r.size() != 1 ) {
+        throw std::runtime_error( "Only one row expected but multiple found." );
     }
 
-    
     return {r[0][0].as<std::string>(), r[0][1].as<std::string>()};
 }
 
 void PostgresJobProvider::writeBackRevocation( std::shared_ptr<Job> job, std::string date ) {
-    logger::notef( "Revoking at %s", date);
-    pqxx::work txn(c);
+    logger::notef( "Revoking at %s", date );
+    pqxx::work txn( c );
     logger::note( "executing" );
     pqxx::result r = txn.exec( "UPDATE certs SET revoked = " + txn.quote( pgTime( date ) ) + " WHERE id = " + txn.quote( job->target ) );
-    if( r.affected_rows() != 1 ){
-        throw std::runtime_error("Only one row should be updated.");
+
+    if( r.affected_rows() != 1 ) {
+        throw std::runtime_error( "Only one row should be updated." );
     }
+
     logger::note( "committing" );
     txn.commit();
     logger::note( "committed" );
index b1acf18f06794ab3c9d5833459a14b5493a1fb09..3bbb66b02b660f245bf959a6bbd3f946c2c9b3f9 100644 (file)
@@ -68,14 +68,14 @@ BIO_METHOD* toBio() {
 
 template <typename T>
 BIO_METHOD* toBio( int ( *newfunc )( BIO* ) ) {
-    BIO_METHOD *meth = BIO_meth_new(T::typeID, T::getName());
-    BIO_meth_set_write(meth, BIOWrapper::write);
-    BIO_meth_set_read(meth, BIOWrapper::read);
-    BIO_meth_set_puts(meth, BIOWrapper::puts);
-    BIO_meth_set_gets(meth, BIOWrapper::gets);
-    BIO_meth_set_ctrl(meth, BIOWrapper::ctrl);
-    BIO_meth_set_destroy(meth, BIOWrapper::free);
-    BIO_meth_set_create(meth, newfunc);
+    BIO_METHOD *meth = BIO_meth_new( T::typeID, T::getName() );
+    BIO_meth_set_write( meth, BIOWrapper::write );
+    BIO_meth_set_read( meth, BIOWrapper::read );
+    BIO_meth_set_puts( meth, BIOWrapper::puts );
+    BIO_meth_set_gets( meth, BIOWrapper::gets );
+    BIO_meth_set_ctrl( meth, BIOWrapper::ctrl );
+    BIO_meth_set_destroy( meth, BIOWrapper::free );
+    BIO_meth_set_create( meth, newfunc );
 
     return meth;
 }
index 02fd4728a10f2396d8f9d00ee162b1c09181f801..13699605bf2827b90b5b54c2696c95b7d4bb56ce 100644 (file)
@@ -1,7 +1,7 @@
 #include "opensslBIO.h"
 #include <log/logger.hpp>
 
-OpensslBIOWrapper::OpensslBIOWrapper( std::shared_ptr<BIO> _b ) : b( _b ), buffer( 2*0xFFFF+20, 0 ), pos(0) {
+OpensslBIOWrapper::OpensslBIOWrapper( std::shared_ptr<BIO> _b ) : b( _b ), buffer( 2 * 0xFFFF + 20, 0 ), pos( 0 ) {
 }
 
 OpensslBIOWrapper::~OpensslBIOWrapper() {
@@ -30,31 +30,37 @@ int OpensslBIOWrapper::gets( char* str, int size ) {
 const char* OpensslBIOWrapper::getName() {
     return "OpenSSLWrapper";
 }
-std::string OpensslBIOWrapper::readLine(){
+std::string OpensslBIOWrapper::readLine() {
     int target = 0;
-    while(1){
-        logger::debug("doing data");
-        while(target < pos){
-            if(buffer[target] == '\n'){
+
+    while( 1 ) {
+        logger::debug( "doing data" );
+
+        while( target < pos ) {
+            if( buffer[target] == '\n' ) {
                 target++;
-                std::string res(buffer.data(), 0, target);
-                std::copy(buffer.data() + target, buffer.data() + pos, buffer.data() );
+                std::string res( buffer.data(), 0, target );
+                std::copy( buffer.data() + target, buffer.data() + pos, buffer.data() );
                 pos -= target;
-                logger::debug("emit");
+                logger::debug( "emit" );
                 return res;
             }
+
             target++;
         }
+
         std::stringstream ss;
         ss << "target: " << target << ", pos:" << pos;
-        logger::debug(ss.str());
-        int dlen = read(buffer.data() + pos, buffer.size() - pos);
-        if ( dlen <= 0 ){
+        logger::debug( ss.str() );
+        int dlen = read( buffer.data() + pos, buffer.size() - pos );
+
+        if( dlen <= 0 ) {
             throw eof_exception();
         }
+
         std::stringstream ss2;
         ss2 << "done: " << dlen;
-        logger::debug(ss2.str());
+        logger::debug( ss2.str() );
         pos += dlen;
     }
 }
index 994b7bcafb383e0e11a6c5c277f50d73c69b4ca8..1cf96f89a82c6cefe96223552d004778a9970059 100644 (file)
@@ -26,5 +26,5 @@ public:
     std::string readLine();
 };
 
-class eof_exception : public std::exception{
+class eof_exception : public std::exception {
 };
index 4cc5b898bab50e377d71df9b8017cd2932a3dc91..268897d79e2cdf5626e3dca35a1a9bd5af28bb3f 100644 (file)
@@ -27,17 +27,18 @@ std::string toHexAndChecksum( const std::string& src ) {
 void sendCommand( RecordHeader& head, const std::string& data, std::shared_ptr<OpensslBIO> bio ) {
     std::stringstream ss;
     ss << data.size();
-    logger::debugf( "Record payload length: %s", ss.str() ); 
+    logger::debugf( "Record payload length: %s", ss.str() );
     size_t pos = 0;
     head.offset = 0;
     head.totalLength = data.size();
+
     do {
-        size_t toTransfer = std::min(static_cast<size_t>(0xF000), data.size() - pos);
+        size_t toTransfer = std::min( static_cast<size_t>( 0xF000 ), data.size() - pos );
         head.payloadLength = toTransfer;
 
         std::string s;
         s += head.packToString();
-        s += data.substr(pos, toTransfer);
+        s += data.substr( pos, toTransfer );
 
         std::string res = toHexAndChecksum( s );
 
@@ -47,7 +48,7 @@ void sendCommand( RecordHeader& head, const std::string& data, std::shared_ptr<O
 
         pos += toTransfer;
         head.offset += 1;
-    } while(pos < data.size());
+    } while( pos < data.size() );
 }
 
 int32_t fromHexDigit( char c ) {
@@ -64,7 +65,7 @@ int32_t fromHexDigit( char c ) {
     return res;
 }
 
-std::string parseCommand( RecordHeader& head, const std::string& input) {
+std::string parseCommand( RecordHeader& head, const std::string& input ) {
     logger::debug( "FINE: RECORD input: ", input );
 
     int32_t dlen = ( input.size() - 2 ) / 2;
@@ -96,35 +97,43 @@ std::string parseCommand( RecordHeader& head, const std::string& input) {
         std::stringstream ss;
         ss << "Expected: " << expectedTotalLength << ", Got: " << input.size();
         logger::error( ss.str() );
-        throw std::length_error("Error, invalid length");
+        throw std::length_error( "Error, invalid length" );
     }
+
     if( checksum != -1 || error || dlen < RECORD_HEADER_SIZE ) {
-        throw std::runtime_error("Error, invalid checksum");
+        throw std::runtime_error( "Error, invalid checksum" );
     }
 
     data.pop_back();
 
     return data;
 }
-std::string parseCommandChunked( RecordHeader& head, std::shared_ptr<OpensslBIOWrapper> io){
-    logger::note("reading");
+std::string parseCommandChunked( RecordHeader& head, std::shared_ptr<OpensslBIOWrapper> io ) {
+    logger::note( "reading" );
     std::string payload = parseCommand( head, io->readLine() );
-    std::string all(head.totalLength, ' ');
+    std::string all( head.totalLength, ' ' );
     auto target = all.begin();
     size_t pos = 0;
     RecordHeader head2;
-    while(true) {
+
+    while( true ) {
         pos += head.payloadLength;
-        target = std::copy ( payload.begin(), payload.end(), target);
-        if(pos >= head.totalLength) {
+        target = std::copy( payload.begin(), payload.end(), target );
+
+        if( pos >= head.totalLength ) {
             break;
         }
-        logger::note("chunk digested, reading next one");
+
+        logger::note( "chunk digested, reading next one" );
+
         payload = parseCommand( head2, io->readLine() );
-        if(!head2.isFollowupOf(head)){
-            throw std::runtime_error("Error, header of follow up chunk was malformed");
+
+        if( !head2.isFollowupOf( head ) ) {
+            throw std::runtime_error( "Error, header of follow up chunk was malformed" );
         }
+
         head = head2;
     }
+
     return all;
 }
index 48dd8afee59fe37e8551f527c16172ef2722c8b8..5d6e659b7439689157c704a303eefbf7cfcc0d64 100644 (file)
@@ -90,7 +90,7 @@ public:
 
     void unpackFromString( const std::string& str ) {
         if( str.size() != RECORD_HEADER_SIZE ) {
-            throw std::runtime_error("Invalid string length");
+            throw std::runtime_error( "Invalid string length" );
         }
 
         auto it =  str.cbegin();
@@ -108,6 +108,6 @@ public:
 };
 
 std::string parseCommand( RecordHeader& head, const std::string& input );
-std::string parseCommandChunked( RecordHeader& head, std::shared_ptr<OpensslBIOWrapper> conn);
+std::string parseCommandChunked( RecordHeader& head, std::shared_ptr<OpensslBIOWrapper> conn );
 
 void sendCommand( RecordHeader& head, const std::string& data, std::shared_ptr<OpensslBIO> bio );
index f8c2185f395bdcba617e32d5e5410af74947549f..2eb8358a567c55f19c117c231f6fc8ca8c1c28c3 100644 (file)
@@ -45,7 +45,7 @@ public:
 
     RecordHandlerSession( DefaultRecordHandler* parent, std::shared_ptr<Signer> signer, std::shared_ptr<SSL_CTX> ctx, std::shared_ptr<BIO> output ) :
         tbs( std::make_shared<TBSCertificate>() ),
-        logFile(openLogfile( "logs/log_" + timestamp() ) ),
+        logFile( openLogfile( "logs/log_" + timestamp() ) ),
         logger{ std::cout, *logFile } {
         this->parent = parent;
         this->signer = signer;
@@ -160,9 +160,11 @@ public:
             }
 
             logger::note( "Shutting down SSL" );
+
             if( !SSL_shutdown( ssl.get() ) && !SSL_shutdown( ssl.get() ) ) {
                 logger::warn( "ERROR: SSL shutdown failed." );
             }
+
             io->ctrl( BIO_CTRL_FLUSH, 0, NULL );
             logger::note( "Shutted down SSL" );
 
@@ -207,7 +209,7 @@ public:
             break;
 
         default:
-            throw std::runtime_error("Unimplemented");
+            throw std::runtime_error( "Unimplemented" );
         }
     }
 };
@@ -222,13 +224,14 @@ void DefaultRecordHandler::reset() {
 
 void DefaultRecordHandler::handle() {
     if( !currentSession ) {
-        (void) BIO_reset( bio.get() );
+        ( void ) BIO_reset( bio.get() );
         logger::note( "New session allocated." );
         currentSession = std::make_shared<RecordHandlerSession>( this, signer, ctx, bio );
     }
+
     try {
         currentSession->work();
-    } catch( eof_exception e ){
+    } catch( eof_exception e ) {
         reset();
     }
 }
index 29bc41e328d663179e7b19c02fde4dafc9bddfec..619159f1bc36cab7253a7bd84e669b9b38bd33c8 100644 (file)
@@ -61,6 +61,7 @@ int SlipBIO::write( const char* buf, int num ) {
 #ifdef SLIP_IO_DEBUG
     logger::notef( "slip-out: %s", toHex( buf, num ) );
 #endif
+
     if( waitForReset ) {
         logger::note( "denying read because of reset-need!" );
         return -1;
@@ -111,7 +112,7 @@ int SlipBIO::write( const char* buf, int num ) {
 #endif
 
         if( dlen < 0 ) {
-            throw std::runtime_error("Error, target write failed");
+            throw std::runtime_error( "Error, target write failed" );
         } else if( dlen == 0 ) {
             // sleep
             logger::note( "waiting for write ability" );
@@ -132,25 +133,30 @@ int SlipBIO::read( char* buf, int size ) {
 #ifdef UNMASK_DEBUG
     logger::note( "starting read" );
 #endif
+
     // while we have no data to decode or unmasking does not yield a full package
     while( decodeTarget == 0 ) {
         if( waitForReset ) {
             logger::note( "denying read because of reset-need!" );
             return -1;
         }
-        if(decodePos < rawPos) {
+
+        if( decodePos < rawPos ) {
             int res = unmask();
+
             if( res == 1 ) {
                 continue; // probably Packet :-)
-            } else if(res == -1) {
+            } else if( res == -1 ) {
                 logger::note( "sending reset because of malfomed packet" );
-               return -1;
+                return -1;
             }
         }
-        if( decodeTarget != 0 ){
+
+        if( decodeTarget != 0 ) {
             // we have data now, emit it!
             break;
         }
+
         // we have no data, read more
         if( buffer.size() - rawPos < 64 ) {
             // not enough space... package is too big
@@ -171,19 +177,23 @@ int SlipBIO::read( char* buf, int size ) {
 #endif
         int len = target->read( buffer.data() + rawPos, buffer.size() - rawPos );
 #ifdef RAW_IO_DEBUG
-        logger::note( toHex(buffer.data() + rawPos, len ) );
+        logger::note( toHex( buffer.data() + rawPos, len ) );
 #endif
+
         if( len > 0 ) {
             rawPos += len;
         } else {
-            logger::note("Reporting EOS from slip");
+            logger::note( "Reporting EOS from slip" );
             return -1;
             //decodeTarget = 0;
             //failed = true;
         }
 
     }
-    if( waitForReset ) return -1;
+
+    if( waitForReset ) {
+        return -1;
+    }
 
     int len = std::min( decodeTarget, ( unsigned int ) size );
     // a package finished, return it
@@ -197,8 +207,8 @@ int SlipBIO::read( char* buf, int size ) {
     convert << ", requested were: " << size;
     logger::note( convert.str() );
 #endif
-    
-    if(decodeTarget == 0 && rawPos <= decodePos + 1){
+
+    if( decodeTarget == 0 && rawPos <= decodePos + 1 ) {
         // compact the remaining at most 1 byte of raw data
         buffer[0] = buffer[decodePos];
         rawPos -= decodePos;
@@ -219,23 +229,25 @@ long SlipBIO::ctrl( int cmod, long arg1, void* arg2 ) {
 
     if( cmod == BIO_CTRL_RESET ) {
         decodeTarget = 0;
+
         if( server ) {
             waitForReset = false;
             waitForConnection = true;
             resetCounter = -1;
         } else {
             static char ctr = 8;
-            char resetSequence[] = {SLIP_CONNECTION, 1,2,3,4,5,6,7, ctr};
+            char resetSequence[] = {SLIP_CONNECTION, 1, 2, 3, 4, 5, 6, 7, ctr};
             target->write( resetSequence, 9 );
             header = {1, 2, 3, 4, 5, 6, 7, ctr};
             resetCounter = -1;
             waitForConnection = true;
             logger::note( "Resetting SLIP layer" );
         }
+
         return 0;
-    }else if(cmod == BIO_CTRL_FLUSH ){
+    } else if( cmod == BIO_CTRL_FLUSH ) {
 #ifdef UNMASK_DEBUG
-        logger::note( "flush requested ");
+        logger::note( "flush requested " );
 #endif
     }
 
@@ -257,82 +269,94 @@ int SlipBIO::unmask() {
     }
     logger::note( "unmasking" );
 #endif
-    if( waitForConnection ){
+
+    if( waitForConnection ) {
 #ifdef UNMASK_DEBUG
         logger::note( "scanning for connection" );
 #endif
         decodeTarget = 0;
+
         if( server ) {
 #ifdef UNMASK_DEBUG
-            logger::note( "on server site, waiting for CONNECTION-byte");
+            logger::note( "on server site, waiting for CONNECTION-byte" );
 #endif
-            while(decodePos < rawPos) {
-                if(buffer[decodePos] == SLIP_CONNECTION) {
+
+            while( decodePos < rawPos ) {
+                if( buffer[decodePos] == SLIP_CONNECTION ) {
                     resetCounter = 0;
 #ifdef UNMASK_DEBUG
                     logger::note( "got connection byte" );
 #endif
-                } else if(resetCounter >= 0) {
+                } else if( resetCounter >= 0 ) {
                     header[resetCounter] = buffer[decodePos];
                     resetCounter++;
                 }
+
                 decodePos++;
-                if( resetCounter >= ((int) header.size()) ){
+
+                if( resetCounter >= ( ( int ) header.size() ) ) {
                     waitForConnection = false;
                     char data[] = { SLIP_CONNECTION };
-                    target->write( data, 1);
+                    target->write( data, 1 );
 #ifdef UNMASK_DEBUG
-                    logger::notef( "SLIP, initing connection with ping-seq %s:", toHex(header.data(), header.size()) );
+                    logger::notef( "SLIP, initing connection with ping-seq %s:", toHex( header.data(), header.size() ) );
 #endif
                     target->write( header.data(), header.size() );
                     break;
                 }
             }
-            if( decodePos >= rawPos ){
+
+            if( decodePos >= rawPos ) {
                 decodePos = 0;
                 rawPos = 0;
                 return 0; // no package
             }
-            
+
         } else {
-            while(decodePos < rawPos) {
-                if(buffer[decodePos] == SLIP_CONNECTION) {
+            while( decodePos < rawPos ) {
+                if( buffer[decodePos] == SLIP_CONNECTION ) {
 #ifdef UNMASK_DEBUG
                     logger::note( "got connbyte" );
 #endif
                     resetCounter = 0;
-                } else if(resetCounter >= 0) {
+                } else if( resetCounter >= 0 ) {
 #ifdef UNMASK_DEBUG
                     logger::note( "got head-byte" );
 #endif
-                    if(buffer[decodePos] == header[resetCounter]) {
+
+                    if( buffer[decodePos] == header[resetCounter] ) {
                         resetCounter++;
                     } else {
                         resetCounter = -1;
                     }
                 }
+
                 decodePos++;
-                if( resetCounter >= ((int) header.size()) ){
+
+                if( resetCounter >= ( ( int ) header.size() ) ) {
                     waitForConnection = false;
 #ifdef UNMASK_DEBUG
-                    logger::note("connection found! :-)!");
+                    logger::note( "connection found! :-)!" );
 #endif
                     break;
                 }
             }
-            if( decodePos >= rawPos ){
+
+            if( decodePos >= rawPos ) {
                 rawPos = 0;
                 decodePos = 0;
                 return 0; // no package
             }
         }
     }
+
     unsigned int j = decodeTarget;
 
     for( unsigned int i = decodePos; i < rawPos; i++ ) {
-        if(waitForConnection && buffer[i] != SLIP_CONNECTION ) {
+        if( waitForConnection && buffer[i] != SLIP_CONNECTION ) {
             continue;
         }
+
         if( buffer[i] == SLIP_ESCAPE_CHAR ) {
             i++;
 
@@ -374,6 +398,7 @@ int SlipBIO::unmask() {
                 logger::note( "error connection failed" );
                 return -1;
             }
+
             logger::note( "got package border; slip re-validated SHOULD NEVER HAPPEN!!" );
             decodeTarget = 0;
             waitForConnection = false;
index e721021b0de6d2105014ea4b05b42188010ab5b7..55d586405d738cf94343de66361b0f4490e6319b 100644 (file)
@@ -29,7 +29,7 @@ std::string writeBackFile( const std::string& serial, const std::string& cert, c
 
     if( 0 != mkdir( filename.c_str(), 0755 ) ) {
         if( EEXIST != errno ) {
-            throw std::runtime_error("Storage location could not be determined");
+            throw std::runtime_error( "Storage location could not be determined" );
         }
 
         //! \FIXME: Check this is a directory
@@ -144,7 +144,7 @@ std::pair<bool, time_t> parseMonthInterval( std::time_t t, const std::string& da
 
     try {
         size_t end = 0;
-        int num = std::stoi( date.substr( 0, date.size() - 1 ) , &end );
+        int num = std::stoi( date.substr( 0, date.size() - 1 ), &end );
 
         if( end != date.size() - 1 ) {
             return  std::pair<bool, time_t>( false, 0 );
@@ -191,16 +191,18 @@ std::unique_ptr<std::ofstream> openLogfile( const std::string &name ) {
     auto res = std::make_unique<std::ofstream>( tname );
 
     if( ! res->good() ) {
-        throw std::runtime_error( std::string("Failed to open file for logging: " ) + name );
+        throw std::runtime_error( std::string( "Failed to open file for logging: " ) + name );
     }
 
     return res;
 }
 
-std::string timestamp(){
+std::string timestamp() {
     time_t c_time;
+
     if( time( &c_time ) == -1 ) {
         throw std::runtime_error( "Error while fetching time?" );
     }
+
     return std::to_string( c_time );
 }
old mode 100755 (executable)
new mode 100644 (file)
index 0d8300be374e7ac01adef1dba6a38e04c05d43d5..f8bb6044c2df33540c2a4d15345d0d40fb97b277 100644 (file)
@@ -15,7 +15,7 @@ BOOST_AUTO_TEST_CASE( CSR ) {
     ERR_load_crypto_strings();
     ERR_free_strings();
     SSL_load_error_strings();
-    ERR_print_errors_fp(stdout);
+    ERR_print_errors_fp( stdout );
     BOOST_REQUIRE( ERR_peek_error() == 0 );
 
     // Testing a valid CSR
index 1f6d705829de279fbd5c7f58a2580ed5459d8db4..dbf6a6d42cf5c82c002fb4d58bc94886a84416c7 100644 (file)
@@ -40,7 +40,7 @@ const char* OpensslBIO1::getName() {
 BOOST_AUTO_TEST_SUITE( TestBioWrapper )
 
 BOOST_AUTO_TEST_CASE( BasicCalls ) {
-    std::shared_ptr<BIO_METHOD> m(toBio<OpensslBIO1>(), BIO_meth_free);
+    std::shared_ptr<BIO_METHOD> m( toBio<OpensslBIO1>(), BIO_meth_free );
     std::shared_ptr<BIO> n( BIO_new( m.get() ), BIO_free );
     OpensslBIO* o = new OpensslBIOWrapper( n );
     OpensslBIO1* data = ( OpensslBIO1* ) n->ptr;