c855e66690b8b91ab2cbe302d484fcc8e386da72
[shpub.git] / src / shpub / Command / Connect.php
1 <?php
2 namespace shpub;
3
4 /**
5  * Connect to a micropub server to get an access token.
6  *
7  * @author  Christian Weiske <cweiske@cweiske.de>
8  * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3
9  * @link    http://cweiske.de/shpub.htm
10  * @link    http://micropub.net/draft/
11  * @link    http://indieweb.org/authorization-endpoint
12  */
13 class Command_Connect
14 {
15     public static $client_id = 'http://cweiske.de/shpub.htm';
16
17     public function __construct(Config $cfg)
18     {
19         $this->cfg = $cfg;
20     }
21
22     public static function opts(\Console_CommandLine $optParser)
23     {
24         $cmd = $optParser->addCommand('connect');
25         $cmd->description = 'Obtain access token from a micropub server';
26         $cmd->addOption(
27             'force',
28             array(
29                 'short_name'  => '-f',
30                 'long_name'   => '--force-update',
31                 'description' => 'Force token update if token already available',
32                 'action'      => 'StoreTrue',
33                 'default'     => false,
34             )
35         );
36         $cmd->addOption(
37             'scope',
38             array(
39                 'short_name'  => '-s',
40                 'long_name'   => '--scope',
41                 'description' => 'Space-separated list of scopes to request'
42                     . ' (default: create)',
43                 'action'      => 'StoreString',
44                 'default'     => 'create',
45             )
46         );
47         $cmd->addArgument(
48             'server',
49             [
50                 'optional'    => false,
51                 'description' => 'Server URL',
52             ]
53         );
54         $cmd->addArgument(
55             'user',
56             [
57                 'optional'    => true,
58                 'description' => 'User URL',
59             ]
60         );
61         $cmd->addArgument(
62             'key',
63             [
64                 'optional'    => true,
65                 'description' => 'Short name (key)',
66             ]
67         );
68     }
69
70     public function run($server, $user, $newKey, $force, $scope)
71     {
72         $server = Validator::url($server, 'server');
73         if ($user === null) {
74             //indieweb: homepage is your identity
75             $user = $server;
76         } else {
77             $user = Validator::url($user, 'user');
78         }
79
80         $host = $this->getHost($newKey != '' ? $newKey : $server, $force);
81         if ($host === null) {
82             //already taken
83             return;
84         }
85         if ($host->endpoints->incomplete()) {
86             $host->server = $server;
87             $host->loadEndpoints();
88         }
89
90         list($redirect_uri, $socketStr) = $this->getHttpServerData();
91         $state = time();
92         Log::msg(
93             "To authenticate, open the following URL:\n"
94             . $this->getBrowserAuthUrl($host, $user, $redirect_uri, $state, $scope)
95         );
96
97         $authParams = $this->startHttpServer($socketStr);
98         if ($authParams['state'] != $state) {
99             Log::err('Wrong "state" parameter value: ' . $authParams['state']);
100             exit(2);
101         }
102         $code    = $authParams['code'];
103         $userUrl = $authParams['me'];
104
105         $accessToken = $this->fetchAccessToken(
106             $host, $userUrl, $code, $redirect_uri, $state
107         );
108
109         //all fine. update config
110         $host->user  = $userUrl;
111         $host->token = $accessToken;
112
113         if ($newKey != '') {
114             $hostKey = $newKey;
115         } else {
116             $hostKey = $this->cfg->getHostByName($server);
117             if ($hostKey === null) {
118                 $keyBase = parse_url($host->server, PHP_URL_HOST);
119                 $newKey  = $keyBase;
120                 $count = 0;
121                 while (isset($this->cfg->hosts[$newKey])) {
122                     $newKey = $keyBase . ++$count;
123                 }
124                 $hostKey = $newKey;
125             }
126         }
127         $this->cfg->hosts[$hostKey] = $host;
128         $this->cfg->save();
129         Log::info("Server configuration $hostKey saved successfully.");
130     }
131
132     protected function fetchAccessToken(
133         $host, $userUrl, $code, $redirect_uri, $state
134     ) {
135         $req = new \HTTP_Request2($host->endpoints->token, 'POST');
136         if (version_compare(PHP_VERSION, '5.6.0', '<')) {
137             //correct ssl validation on php 5.5 is a pain, so disable
138             $req->setConfig('ssl_verify_host', false);
139             $req->setConfig('ssl_verify_peer', false);
140         }
141         $req->setHeader('Content-Type: application/x-www-form-urlencoded');
142         $req->setBody(
143             http_build_query(
144                 [
145                     'grant_type'   => 'authorization_code',
146                     'me'           => $userUrl,
147                     'code'         => $code,
148                     'redirect_uri' => $redirect_uri,
149                     'client_id'    => static::$client_id,
150                     'state'        => $state,
151                 ]
152             )
153         );
154         $res = $req->send();
155         if (intval($res->getStatus() / 100) !== 2) {
156             Log::err('Failed to fetch access token');
157             Log::err('Server responded with HTTP status code ' . $res->getStatus());
158             Log::err($res->getBody());
159             exit(2);
160         }
161         if ($res->getHeader('content-type') == 'application/x-www-form-urlencoded') {
162             parse_str($res->getBody(), $tokenParams);
163         } elseif ($res->getHeader('content-type') == 'application/json') {
164             $tokenParams = json_decode($res->getBody(), true);
165         } else {
166             Log::err('Wrong content type in auth verification response');
167             exit(2);
168         }
169         if (!isset($tokenParams['access_token'])) {
170             Log::err('"access_token" missing');
171             exit(2);
172         }
173
174         $accessToken = $tokenParams['access_token'];
175         return $accessToken;
176     }
177
178     protected function getBrowserAuthUrl($host, $user, $redirect_uri, $state, $scope)
179     {
180         return $host->endpoints->authorization
181             . '?me=' . urlencode($user)
182             . '&client_id=' . urlencode(static::$client_id)
183             . '&redirect_uri=' . urlencode($redirect_uri)
184             . '&state=' . $state
185             . '&scope=' . urlencode($scope)
186             . '&response_type=code';
187     }
188
189     protected function getHost($keyOrServer, $force)
190     {
191         $host = new Config_Host();
192         $key = $this->cfg->getHostByName($keyOrServer);
193         if ($key !== null) {
194             $host = $this->cfg->hosts[$key];
195             if (!$force && $host->token != '') {
196                 Log::err('Token already available');
197                 return;
198             }
199         }
200         return $host;
201     }
202
203     protected function getHttpServerData()
204     {
205         $ip   = '127.0.0.1';
206         $port = 12345;
207
208         if (isset($_SERVER['SSH_CONNECTION'])) {
209             $parts = explode(' ', $_SERVER['SSH_CONNECTION']);
210             if (count($parts) >= 3) {
211                 $ip = $parts[2];
212             }
213         }
214         if (strpos($ip, ':') !== false) {
215             //ipv6
216             $ip = '[' . $ip . ']';
217         }
218
219         $redirect_uri = 'http://' . $ip . ':' . $port . '/callback';
220         $socketStr    = 'tcp://' . $ip . ':' . $port;
221         return [$redirect_uri, $socketStr];
222     }
223
224     protected function startHttpServer($socketStr)
225     {
226         $responseOk = "HTTP/1.0 200 OK\r\n"
227             . "Content-Type: text/plain\r\n"
228             . "\r\n"
229             . "Ok. You may close this tab and return to the shell.\r\n";
230         $responseErr = "HTTP/1.0 400 Bad Request\r\n"
231             . "Content-Type: text/plain\r\n"
232             . "\r\n"
233             . "Bad Request\r\n";
234
235         //5 minutes should be enough for the user to confirm
236         ini_set('default_socket_timeout', 60 * 5);
237         $server = stream_socket_server($socketStr, $errno, $errstr);
238         if (!$server) {
239             Log::err('Error starting HTTP server');
240             return false;
241         }
242
243         do {
244             $sock = stream_socket_accept($server);
245             if (!$sock) {
246                 Log::err('Error accepting socket connection');
247                 exit(1);
248             }
249
250             $headers = [];
251             $body    = null;
252             $content_length = 0;
253             //read request headers
254             while (false !== ($line = trim(fgets($sock)))) {
255                 if ('' === $line) {
256                     break;
257                 }
258                 $regex = '#^Content-Length:\s*([[:digit:]]+)\s*$#i';
259                 if (preg_match($regex, $line, $matches)) {
260                     $content_length = (int) $matches[1];
261                 }
262                 $headers[] = $line;
263             }
264
265             // read content/body
266             if ($content_length > 0) {
267                 $body = fread($sock, $content_length);
268             }
269
270             // send response
271             list($method, $url, $httpver) = explode(' ', $headers[0]);
272             if ($method == 'GET') {
273                 $parts = parse_url($url);
274                 if (isset($parts['path']) && $parts['path'] == '/callback'
275                     && isset($parts['query'])
276                 ) {
277                     parse_str($parts['query'], $query);
278                     if (isset($query['code'])
279                         && isset($query['state'])
280                         && isset($query['me'])
281                     ) {
282                         fwrite($sock, $responseOk);
283                         fclose($sock);
284                         return $query;
285                     }
286                 }
287             }
288
289             fwrite($sock, $responseErr);
290             fclose($sock);
291         } while (true);
292     }
293 }
294 ?>