Skip to content

Commit

Permalink
Removing Logger dependency, adding Psr/Log/LoggerInterface to compose…
Browse files Browse the repository at this point in the history
…r require-dev
  • Loading branch information
Stanislav Humplik committed Dec 14, 2015
1 parent e88a076 commit a9c6f4f
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 33 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
.idea/
composer.lock
vendor
79 changes: 46 additions & 33 deletions Lescript.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ class Lescript

private $certificatesDir;
private $webRootDir;

/** @var \Psr\Log\LoggerInterface */
private $logger;
private $client;
private $accountKeyPath;

public function __construct($certificatesDir, $webRootDir, $logger)
public function __construct($certificatesDir, $webRootDir, $logger = null)
{
$this->certificatesDir = $certificatesDir;
$this->webRootDir = $webRootDir;
Expand All @@ -32,25 +34,23 @@ public function initAccount()
// generate and save new private key for account
// ---------------------------------------------

$this->logger->info('Starting new account registration');
$this->log('Starting new account registration');
$this->generateKey(dirname($this->accountKeyPath));
$this->postNewReg();
$this->logger->info('New account certificate registered');
$this->log('New account certificate registered');

} else {

$this->logger->info('Account already registered. Continuing.');
$this->log('Account already registered. Continuing.');

}
}

public function signDomains(array $domains)
{
$this->logger->info('Starting certificate generation process for domains');
$this->log('Starting certificate generation process for domains');

if(($privateAccountKey = openssl_pkey_get_private('file://'.$this->accountKeyPath)) === FALSE) {
throw new \RuntimeException(openssl_error_string());
}
$privateAccountKey = $this->readPrivateKey($this->accountKeyPath);
$accountKeyDetails = openssl_pkey_get_details($privateAccountKey);

// start domains authentication
Expand All @@ -61,7 +61,7 @@ public function signDomains(array $domains)
// 1. getting available authentication options
// -------------------------------------------

$this->logger->info("Requesting challenge for $domain");
$this->log("Requesting challenge for $domain");

$response = $this->signedRequest(
"/acme/new-authz",
Expand All @@ -70,9 +70,9 @@ public function signDomains(array $domains)

// choose http-01 challange only
$challenge = array_reduce($response['challenges'], function($v, $w) { return $v ? $v : ($w['type'] == 'http-01' ? $w : false); });
if(!$challenge) throw new \RuntimeException("HTTP Challenge for $domain is not available");
if(!$challenge) throw new \RuntimeException("HTTP Challenge for $domain is not available. Whole response: ".json_encode($response));

$this->logger->info("Got challenge token for $domain");
$this->log("Got challenge token for $domain");
$location = $this->client->getLastLocation();


Expand Down Expand Up @@ -103,14 +103,14 @@ public function signDomains(array $domains)

$uri = "http://${domain}/.well-known/acme-challenge/${challenge['token']}";

$this->logger->info("Token for $domain saved at $tokenPath and should be available at $uri");
$this->log("Token for $domain saved at $tokenPath and should be available at $uri");

// simple self check
if($payload !== trim(@file_get_contents($uri))) {
throw new \RuntimeException("Please check $uri - token not available");
}

$this->logger->info("Sending request to challenge");
$this->log("Sending request to challenge");

// send request to challenge
$result = $this->signedRequest(
Expand All @@ -131,15 +131,15 @@ public function signDomains(array $domains)
$ended = !($result['status'] === "pending");

if(!$ended) {
$this->logger->info("Verification pending, sleeping 1s");
$this->log("Verification pending, sleeping 1s");
sleep(1);
}

$result = $this->client->get($location);

} while (!$ended);

$this->logger->info("Verification ended with status: ${result['status']}");
$this->log("Verification ended with status: ${result['status']}");
@unlink($tokenPath);
}

Expand All @@ -153,9 +153,7 @@ public function signDomains(array $domains)
}

// load domain key
if(($privateDomainKey = openssl_pkey_get_private('file://'.$domainPath.'/private.pem')) === FALSE) {
throw new \RuntimeException(openssl_error_string());
}
$privateDomainKey = $this->readPrivateKey($domainPath.'/private.pem');

$this->client->getLastLinks();

Expand All @@ -178,17 +176,17 @@ public function signDomains(array $domains)

if($this->client->getLastCode() == 202) {

$this->logger->info("Certificate generation pending, sleeping 1s");
$this->log("Certificate generation pending, sleeping 1s");
sleep(1);

} else if ($this->client->getLastCode() == 200) {

$this->logger->info("Got certificate! YAY!");
$this->log("Got certificate! YAY!");
$certificates[] = $this->parsePemFromBody($result);


foreach($this->client->getLastLinks() as $link) {
$this->logger->info("Requesting chained cert at $link");
$this->log("Requesting chained cert at $link");
$result = $this->client->get($link);
$certificates[] = $this->parsePemFromBody($result);
}
Expand All @@ -203,16 +201,25 @@ public function signDomains(array $domains)

if(empty($certificates)) throw new \RuntimeException('No certificates generated');

$this->logger->info("Saving fullchain.pem");
$this->log("Saving fullchain.pem");
file_put_contents($domainPath.'/fullchain.pem', implode("\n", $certificates));

$this->logger->info("Saving cert.pem");
$this->log("Saving cert.pem");
file_put_contents($domainPath.'/cert.pem', array_shift($certificates));

$this->logger->info("Saving chain.pem");
$this->log("Saving chain.pem");
file_put_contents($domainPath."/chain.pem", implode("\n", $certificates));

$this->logger->info("Done !!§§!");
$this->log("Done !!§§!");
}

private function readPrivateKey($path)
{
if(($key = openssl_pkey_get_private('file://'.$path)) === FALSE) {
throw new \RuntimeException(openssl_error_string());
}

return $key;
}

private function parsePemFromBody($body)
Expand All @@ -228,7 +235,7 @@ private function getDomainPath($domain)

private function postNewReg()
{
$this->logger->info('Sending registration to letsencrypt server');
$this->log('Sending registration to letsencrypt server');

return $this->signedRequest(
'/acme/new-reg',
Expand Down Expand Up @@ -305,12 +312,9 @@ private function generateKey($outputDirectory)
file_put_contents($outputDirectory.'/public.pem', $details['key']);
}

private function signedRequest($uri, array $payload) {

if(($privateKey = openssl_pkey_get_private('file://'.$this->accountKeyPath)) === FALSE) {
throw new \RuntimeException(openssl_error_string());
}

private function signedRequest($uri, array $payload)
{
$privateKey = $this->readPrivateKey($this->accountKeyPath);
$details = openssl_pkey_get_details($privateKey);

$header = array(
Expand Down Expand Up @@ -340,10 +344,19 @@ private function signedRequest($uri, array $payload) {
'signature' => $signed64
);

$this->logger->info("Sending signed request to $uri");
$this->log("Sending signed request to $uri");

return $this->client->post($uri, json_encode($data));
}

protected function log($message)
{
if($this->logger) {
$this->logger->info($message);
} else {
echo $message."\n";
}
}
}

class Client
Expand Down
2 changes: 2 additions & 0 deletions _example.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ class Logger { function __call($name, $arguments) { echo date('Y-m-d H:i:s')." [
try {

$le = new Analogic\ACME\Lescript('/certificate/storage', '/var/www/test.com', $logger);
# or without logger:
# $le = new Analogic\ACME\Lescript('/certificate/storage', '/var/www/test.com');
$le->initAccount();
$le->signDomains(array('test.com', 'www.test.com'));

Expand Down
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
"ext-curl": "*",
"ext-openssl": "*"
},
"require-dev": {
"psr/log": "^1"
},
"autoload": {
"files": ["Lescript.php"]
}
Expand Down

0 comments on commit a9c6f4f

Please sign in to comment.