cache server endpoint URLs
[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     }
69
70     protected function fetchAccessToken(
71         $host, $userUrl, $code, $redirect_uri, $state
72     ) {
73         $req = new \HTTP_Request2($host->endpoints->token, 'POST');
74         $req->setHeader('Content-Type: application/x-www-form-urlencoded');
75         $req->setBody(
76             http_build_query(
77                 [
78                     'me'           => $userUrl,
79                     'code'         => $code,
80                     'redirect_uri' => $redirect_uri,
81                     'client_id'    => static::$client_id,
82                     'state'        => $state,
83                 ]
84             )
85         );
86         $res = $req->send();
87         if ($res->getHeader('content-type') != 'application/x-www-form-urlencoded') {
88             Log::err('Wrong content type in auth verification response');
89             exit(2);
90         }
91         parse_str($res->getBody(), $tokenParams);
92         if (!isset($tokenParams['access_token'])) {
93             Log::err('"access_token" missing');
94             exit(2);
95         }
96
97         $accessToken = $tokenParams['access_token'];
98         return $accessToken;
99     }
100
101     protected function getBrowserAuthUrl($host, $user, $redirect_uri, $state)
102     {
103         return $host->endpoints->authorization
104             . '?me=' . urlencode($user)
105             . '&client_id=' . urlencode(static::$client_id)
106             . '&redirect_uri=' . urlencode($redirect_uri)
107             . '&state=' . $state
108             . '&scope=post'
109             . '&response_type=code';
110     }
111
112     protected function getHost($keyOrServer, $force)
113     {
114         $host = new Config_Host();
115         $key = $this->cfg->getHostByName($keyOrServer);
116         if ($key !== null) {
117             $host = $this->cfg->hosts[$key];
118             if (!$force && $host->token != '') {
119                 Log::err('Token already available');
120                 return;
121             }
122         }
123         return $host;
124     }
125
126     protected function getHttpServerData()
127     {
128         //FIXME: get IP from SSH_CONNECTION
129         $ip   = '127.0.0.1';
130         $port = 12345;
131         $redirect_uri = 'http://' . $ip . ':' . $port . '/callback';
132         $socketStr    = 'tcp://' . $ip . ':' . $port;
133         return [$redirect_uri, $socketStr];
134     }
135
136     protected function verifyAuthCode($host, $code, $state, $redirect_uri, $me)
137     {
138         $req = new \HTTP_Request2($host->endpoints->authorization, 'POST');
139         $req->setHeader('Content-Type: application/x-www-form-urlencoded');
140         $req->setBody(
141             http_build_query(
142                 [
143                     'code'         => $code,
144                     'state'        => $state,
145                     'client_id'    => static::$client_id,
146                     'redirect_uri' => $redirect_uri,
147                 ]
148             )
149         );
150         $res = $req->send();
151         if ($res->getHeader('content-type') != 'application/x-www-form-urlencoded') {
152             Log::err('Wrong content type in auth verification response');
153             exit(2);
154         }
155         parse_str($res->getBody(), $verifiedParams);
156         if (!isset($verifiedParams['me'])
157             || $verifiedParams['me'] !== $me
158         ) {
159             Log::err('Non-matching "me" values');
160             exit(2);
161         }
162     }
163
164     protected function startHttpServer($socketStr)
165     {
166         $responseOk = "HTTP/1.0 200 OK\r\n"
167             . "Content-Type: text/plain\r\n"
168             . "\r\n"
169             . "Ok. You may close this tab and return to the shell.\r\n";
170         $responseErr = "HTTP/1.0 400 Bad Request\r\n"
171             . "Content-Type: text/plain\r\n"
172             . "\r\n"
173             . "Bad Request\r\n";
174
175         //5 minutes should be enough for the user to confirm
176         ini_set('default_socket_timeout', 60 * 5);
177         $server = stream_socket_server($socketStr, $errno, $errstr);
178         if (!$server) {
179             Log::err('Error starting HTTP server');
180             return false;
181         }
182
183         do {
184             $sock = stream_socket_accept($server);
185             if (!$sock) {
186                 Log::err('Error accepting socket connection');
187                 exit(1);
188             }
189
190             $headers = [];
191             $body    = null;
192             $content_length = 0;
193             //read request headers
194             while (false !== ($line = trim(fgets($sock)))) {
195                 if ('' === $line) {
196                     break;
197                 }
198                 $regex = '#^Content-Length:\s*([[:digit:]]+)\s*$#i';
199                 if (preg_match($regex, $line, $matches)) {
200                     $content_length = (int) $matches[1];
201                 }
202                 $headers[] = $line;
203             }
204
205             // read content/body
206             if ($content_length > 0) {
207                 $body = fread($sock, $content_length);
208             }
209
210             // send response
211             list($method, $url, $httpver) = explode(' ', $headers[0]);
212             if ($method == 'GET') {
213                 $parts = parse_url($url);
214                 if (isset($parts['path']) && $parts['path'] == '/callback'
215                     && isset($parts['query'])
216                 ) {
217                     parse_str($parts['query'], $query);
218                     if (isset($query['code'])
219                         && isset($query['state'])
220                         && isset($query['me'])
221                     ) {
222                         fwrite($sock, $responseOk);
223                         fclose($sock);
224                         return $query;
225                     }
226                 }
227             }
228
229             fwrite($sock, $responseErr);
230             fclose($sock);
231         } while (true);
232     }
233 }
234 ?>