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