Talk about server information in README
[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 (Util::getMimeType($res) == 'application/x-www-form-urlencoded') {
162             parse_str($res->getBody(), $tokenParams);
163         } elseif (Util::getMimeType($res) == '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         $sep = strpos($host->endpoints->authorization, '?') === false
181             ? '?' : '&';
182         return $host->endpoints->authorization
183             . $sep . 'me=' . urlencode($user)
184             . '&client_id=' . urlencode(static::$client_id)
185             . '&redirect_uri=' . urlencode($redirect_uri)
186             . '&state=' . urlencode($state)
187             . '&scope=' . urlencode($scope)
188             . '&response_type=code';
189     }
190
191     protected function getHost($keyOrServer, $force)
192     {
193         $host = new Config_Host();
194         $key = $this->cfg->getHostByName($keyOrServer);
195         if ($key !== null) {
196             $host = $this->cfg->hosts[$key];
197             if (!$force && $host->token != '') {
198                 Log::err('Token already available');
199                 return;
200             }
201         }
202         return $host;
203     }
204
205     protected function getHttpServerData()
206     {
207         $ip   = '127.0.0.1';
208         $port = 12345;
209
210         if (isset($_SERVER['SSH_CONNECTION'])) {
211             $parts = explode(' ', $_SERVER['SSH_CONNECTION']);
212             if (count($parts) >= 3) {
213                 $ip = $parts[2];
214             }
215         }
216         if (strpos($ip, ':') !== false) {
217             //ipv6
218             $ip = '[' . $ip . ']';
219         }
220
221         $redirect_uri = 'http://' . $ip . ':' . $port . '/callback';
222         $socketStr    = 'tcp://' . $ip . ':' . $port;
223         return [$redirect_uri, $socketStr];
224     }
225
226     protected function startHttpServer($socketStr)
227     {
228         $responseOk = "HTTP/1.0 200 OK\r\n"
229             . "Content-Type: text/plain\r\n"
230             . "\r\n"
231             . "Ok. You may close this tab and return to the shell.\r\n";
232         $responseErr = "HTTP/1.0 400 Bad Request\r\n"
233             . "Content-Type: text/plain\r\n"
234             . "\r\n"
235             . "Bad Request\r\n";
236
237         //5 minutes should be enough for the user to confirm
238         ini_set('default_socket_timeout', 60 * 5);
239         $server = stream_socket_server($socketStr, $errno, $errstr);
240         if (!$server) {
241             Log::err('Error starting HTTP server');
242             return false;
243         }
244
245         do {
246             $sock = stream_socket_accept($server);
247             if (!$sock) {
248                 Log::err('Error accepting socket connection');
249                 exit(1);
250             }
251
252             $headers = [];
253             $body    = null;
254             $content_length = 0;
255             //read request headers
256             while (false !== ($line = trim(fgets($sock)))) {
257                 if ('' === $line) {
258                     break;
259                 }
260                 $regex = '#^Content-Length:\s*([[:digit:]]+)\s*$#i';
261                 if (preg_match($regex, $line, $matches)) {
262                     $content_length = (int) $matches[1];
263                 }
264                 $headers[] = $line;
265             }
266
267             // read content/body
268             if ($content_length > 0) {
269                 $body = fread($sock, $content_length);
270             }
271
272             // send response
273             list($method, $url, $httpver) = explode(' ', $headers[0]);
274             if ($method == 'GET') {
275                 $parts = parse_url($url);
276                 if (isset($parts['path']) && $parts['path'] == '/callback'
277                     && isset($parts['query'])
278                 ) {
279                     parse_str($parts['query'], $query);
280                     if (isset($query['code'])
281                         && isset($query['state'])
282                         && isset($query['me'])
283                     ) {
284                         fwrite($sock, $responseOk);
285                         fclose($sock);
286                         return $query;
287                     }
288                 }
289             }
290
291             fwrite($sock, $responseErr);
292             fclose($sock);
293         } while (true);
294     }
295 }
296 ?>