Determine URL file type from path, strip query parameters first
[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                     'me'           => $userUrl,
130                     'code'         => $code,
131                     'redirect_uri' => $redirect_uri,
132                     'client_id'    => static::$client_id,
133                     'state'        => $state,
134                 ]
135             )
136         );
137         $res = $req->send();
138         if (intval($res->getStatus() / 100) !== 2) {
139             Log::err('Failed to fetch access token');
140             Log::err('Server responded with HTTP status code ' . $res->getStatus());
141             Log::err($res->getBody());
142             exit(2);
143         }
144         if ($res->getHeader('content-type') != 'application/x-www-form-urlencoded') {
145             Log::err('Wrong content type in auth verification response');
146             exit(2);
147         }
148         parse_str($res->getBody(), $tokenParams);
149         if (!isset($tokenParams['access_token'])) {
150             Log::err('"access_token" missing');
151             exit(2);
152         }
153
154         $accessToken = $tokenParams['access_token'];
155         return $accessToken;
156     }
157
158     protected function getBrowserAuthUrl($host, $user, $redirect_uri, $state)
159     {
160         return $host->endpoints->authorization
161             . '?me=' . urlencode($user)
162             . '&client_id=' . urlencode(static::$client_id)
163             . '&redirect_uri=' . urlencode($redirect_uri)
164             . '&state=' . $state
165             . '&scope=post'
166             . '&response_type=code';
167     }
168
169     protected function getHost($keyOrServer, $force)
170     {
171         $host = new Config_Host();
172         $key = $this->cfg->getHostByName($keyOrServer);
173         if ($key !== null) {
174             $host = $this->cfg->hosts[$key];
175             if (!$force && $host->token != '') {
176                 Log::err('Token already available');
177                 return;
178             }
179         }
180         return $host;
181     }
182
183     protected function getHttpServerData()
184     {
185         $ip   = '127.0.0.1';
186         $port = 12345;
187
188         if (isset($_SERVER['SSH_CONNECTION'])) {
189             $parts = explode(' ', $_SERVER['SSH_CONNECTION']);
190             if (count($parts) >= 3) {
191                 $ip = $parts[2];
192             }
193         }
194         if (strpos($ip, ':') !== false) {
195             //ipv6
196             $ip = '[' . $ip . ']';
197         }
198
199         $redirect_uri = 'http://' . $ip . ':' . $port . '/callback';
200         $socketStr    = 'tcp://' . $ip . ':' . $port;
201         return [$redirect_uri, $socketStr];
202     }
203
204     protected function startHttpServer($socketStr)
205     {
206         $responseOk = "HTTP/1.0 200 OK\r\n"
207             . "Content-Type: text/plain\r\n"
208             . "\r\n"
209             . "Ok. You may close this tab and return to the shell.\r\n";
210         $responseErr = "HTTP/1.0 400 Bad Request\r\n"
211             . "Content-Type: text/plain\r\n"
212             . "\r\n"
213             . "Bad Request\r\n";
214
215         //5 minutes should be enough for the user to confirm
216         ini_set('default_socket_timeout', 60 * 5);
217         $server = stream_socket_server($socketStr, $errno, $errstr);
218         if (!$server) {
219             Log::err('Error starting HTTP server');
220             return false;
221         }
222
223         do {
224             $sock = stream_socket_accept($server);
225             if (!$sock) {
226                 Log::err('Error accepting socket connection');
227                 exit(1);
228             }
229
230             $headers = [];
231             $body    = null;
232             $content_length = 0;
233             //read request headers
234             while (false !== ($line = trim(fgets($sock)))) {
235                 if ('' === $line) {
236                     break;
237                 }
238                 $regex = '#^Content-Length:\s*([[:digit:]]+)\s*$#i';
239                 if (preg_match($regex, $line, $matches)) {
240                     $content_length = (int) $matches[1];
241                 }
242                 $headers[] = $line;
243             }
244
245             // read content/body
246             if ($content_length > 0) {
247                 $body = fread($sock, $content_length);
248             }
249
250             // send response
251             list($method, $url, $httpver) = explode(' ', $headers[0]);
252             if ($method == 'GET') {
253                 $parts = parse_url($url);
254                 if (isset($parts['path']) && $parts['path'] == '/callback'
255                     && isset($parts['query'])
256                 ) {
257                     parse_str($parts['query'], $query);
258                     if (isset($query['code'])
259                         && isset($query['state'])
260                         && isset($query['me'])
261                     ) {
262                         fwrite($sock, $responseOk);
263                         fclose($sock);
264                         return $query;
265                     }
266                 }
267             }
268
269             fwrite($sock, $responseErr);
270             fclose($sock);
271         } while (true);
272     }
273 }
274 ?>