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