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