blob: 6351b8056b3faac75122dbe5ae5879c9b8f064e5 [file] [log] [blame]
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001//===--- JSONTransport.cpp - sending and receiving LSP messages over JSON -===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sam McCalldc8f3cf2018-10-17 07:32:05 +00006//
7//===----------------------------------------------------------------------===//
8#include "Logger.h"
9#include "Protocol.h" // For LSPError
Sam McCall19ac0eaf2019-11-25 19:51:07 +010010#include "Shutdown.h"
Sam McCalldc8f3cf2018-10-17 07:32:05 +000011#include "Transport.h"
12#include "llvm/Support/Errno.h"
Sam McCall19ac0eaf2019-11-25 19:51:07 +010013#include "llvm/Support/Error.h"
Sam McCalldc8f3cf2018-10-17 07:32:05 +000014
Sam McCalldc8f3cf2018-10-17 07:32:05 +000015namespace clang {
16namespace clangd {
17namespace {
18
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000019llvm::json::Object encodeError(llvm::Error E) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +000020 std::string Message;
21 ErrorCode Code = ErrorCode::UnknownErrorCode;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000022 if (llvm::Error Unhandled = llvm::handleErrors(
23 std::move(E), [&](const LSPError &L) -> llvm::Error {
Sam McCalldc8f3cf2018-10-17 07:32:05 +000024 Message = L.Message;
25 Code = L.Code;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000026 return llvm::Error::success();
Sam McCalldc8f3cf2018-10-17 07:32:05 +000027 }))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000028 Message = llvm::toString(std::move(Unhandled));
Sam McCalldc8f3cf2018-10-17 07:32:05 +000029
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000030 return llvm::json::Object{
Sam McCalldc8f3cf2018-10-17 07:32:05 +000031 {"message", std::move(Message)},
32 {"code", int64_t(Code)},
33 };
34}
35
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000036llvm::Error decodeError(const llvm::json::Object &O) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +000037 std::string Msg = O.getString("message").getValueOr("Unspecified error");
38 if (auto Code = O.getInteger("code"))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000039 return llvm::make_error<LSPError>(std::move(Msg), ErrorCode(*Code));
40 return llvm::make_error<llvm::StringError>(std::move(Msg),
41 llvm::inconvertibleErrorCode());
Sam McCalldc8f3cf2018-10-17 07:32:05 +000042}
43
44class JSONTransport : public Transport {
45public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000046 JSONTransport(std::FILE *In, llvm::raw_ostream &Out,
47 llvm::raw_ostream *InMirror, bool Pretty, JSONStreamStyle Style)
48 : In(In), Out(Out), InMirror(InMirror ? *InMirror : llvm::nulls()),
Sam McCalldc8f3cf2018-10-17 07:32:05 +000049 Pretty(Pretty), Style(Style) {}
50
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000051 void notify(llvm::StringRef Method, llvm::json::Value Params) override {
52 sendMessage(llvm::json::Object{
Sam McCalldc8f3cf2018-10-17 07:32:05 +000053 {"jsonrpc", "2.0"},
54 {"method", Method},
55 {"params", std::move(Params)},
56 });
57 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000058 void call(llvm::StringRef Method, llvm::json::Value Params,
59 llvm::json::Value ID) override {
60 sendMessage(llvm::json::Object{
Sam McCalldc8f3cf2018-10-17 07:32:05 +000061 {"jsonrpc", "2.0"},
62 {"id", std::move(ID)},
63 {"method", Method},
64 {"params", std::move(Params)},
65 });
66 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000067 void reply(llvm::json::Value ID,
68 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalldc8f3cf2018-10-17 07:32:05 +000069 if (Result) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000070 sendMessage(llvm::json::Object{
Sam McCalldc8f3cf2018-10-17 07:32:05 +000071 {"jsonrpc", "2.0"},
72 {"id", std::move(ID)},
73 {"result", std::move(*Result)},
74 });
75 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000076 sendMessage(llvm::json::Object{
Sam McCalldc8f3cf2018-10-17 07:32:05 +000077 {"jsonrpc", "2.0"},
78 {"id", std::move(ID)},
79 {"error", encodeError(Result.takeError())},
80 });
81 }
82 }
83
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000084 llvm::Error loop(MessageHandler &Handler) override {
Sam McCalldc8f3cf2018-10-17 07:32:05 +000085 while (!feof(In)) {
Sam McCall19ac0eaf2019-11-25 19:51:07 +010086 if (shutdownRequested())
87 return llvm::createStringError(
88 std::make_error_code(std::errc::operation_canceled),
89 "Got signal, shutting down");
Sam McCalldc8f3cf2018-10-17 07:32:05 +000090 if (ferror(In))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000091 return llvm::errorCodeToError(
92 std::error_code(errno, std::system_category()));
Sam McCalldc8f3cf2018-10-17 07:32:05 +000093 if (auto JSON = readRawMessage()) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000094 if (auto Doc = llvm::json::parse(*JSON)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +000095 vlog(Pretty ? "<<< {0:2}\n" : "<<< {0}\n", *Doc);
96 if (!handleMessage(std::move(*Doc), Handler))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000097 return llvm::Error::success(); // we saw the "exit" notification.
Sam McCalldc8f3cf2018-10-17 07:32:05 +000098 } else {
99 // Parse error. Log the raw message.
100 vlog("<<< {0}\n", *JSON);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000101 elog("JSON parse error: {0}", llvm::toString(Doc.takeError()));
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000102 }
103 }
104 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000105 return llvm::errorCodeToError(std::make_error_code(std::errc::io_error));
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000106 }
107
108private:
109 // Dispatches incoming message to Handler onNotify/onCall/onReply.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000110 bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000111 // Writes outgoing message to Out stream.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000112 void sendMessage(llvm::json::Value Message) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000113 std::string S;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000114 llvm::raw_string_ostream OS(S);
115 OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000116 OS.flush();
117 Out << "Content-Length: " << S.size() << "\r\n\r\n" << S;
118 Out.flush();
119 vlog(">>> {0}\n", S);
120 }
121
122 // Read raw string messages from input stream.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000123 llvm::Optional<std::string> readRawMessage() {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000124 return Style == JSONStreamStyle::Delimited ? readDelimitedMessage()
125 : readStandardMessage();
126 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000127 llvm::Optional<std::string> readDelimitedMessage();
128 llvm::Optional<std::string> readStandardMessage();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000129
130 std::FILE *In;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000131 llvm::raw_ostream &Out;
132 llvm::raw_ostream &InMirror;
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000133 bool Pretty;
134 JSONStreamStyle Style;
135};
136
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000137bool JSONTransport::handleMessage(llvm::json::Value Message,
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000138 MessageHandler &Handler) {
139 // Message must be an object with "jsonrpc":"2.0".
140 auto *Object = Message.getAsObject();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000141 if (!Object ||
142 Object->getString("jsonrpc") != llvm::Optional<llvm::StringRef>("2.0")) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000143 elog("Not a JSON-RPC 2.0 message: {0:2}", Message);
144 return false;
145 }
146 // ID may be any JSON value. If absent, this is a notification.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000147 llvm::Optional<llvm::json::Value> ID;
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000148 if (auto *I = Object->get("id"))
149 ID = std::move(*I);
150 auto Method = Object->getString("method");
151 if (!Method) { // This is a response.
152 if (!ID) {
153 elog("No method and no response ID: {0:2}", Message);
154 return false;
155 }
156 if (auto *Err = Object->getObject("error"))
157 return Handler.onReply(std::move(*ID), decodeError(*Err));
158 // Result should be given, use null if not.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000159 llvm::json::Value Result = nullptr;
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000160 if (auto *R = Object->get("result"))
161 Result = std::move(*R);
162 return Handler.onReply(std::move(*ID), std::move(Result));
163 }
164 // Params should be given, use null if not.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000165 llvm::json::Value Params = nullptr;
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000166 if (auto *P = Object->get("params"))
167 Params = std::move(*P);
168
169 if (ID)
170 return Handler.onCall(*Method, std::move(Params), std::move(*ID));
171 else
172 return Handler.onNotify(*Method, std::move(Params));
173}
174
175// Tries to read a line up to and including \n.
Sam McCall19ac0eaf2019-11-25 19:51:07 +0100176// If failing, feof(), ferror(), or shutdownRequested() will be set.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000177bool readLine(std::FILE *In, std::string &Out) {
178 static constexpr int BufSize = 1024;
179 size_t Size = 0;
180 Out.clear();
181 for (;;) {
182 Out.resize(Size + BufSize);
183 // Handle EINTR which is sent when a debugger attaches on some platforms.
Sam McCall19ac0eaf2019-11-25 19:51:07 +0100184 if (!retryAfterSignalUnlessShutdown(
185 nullptr, [&] { return std::fgets(&Out[Size], BufSize, In); }))
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000186 return false;
187 clearerr(In);
188 // If the line contained null bytes, anything after it (including \n) will
189 // be ignored. Fortunately this is not a legal header or JSON.
190 size_t Read = std::strlen(&Out[Size]);
191 if (Read > 0 && Out[Size + Read - 1] == '\n') {
192 Out.resize(Size + Read);
193 return true;
194 }
195 Size += Read;
196 }
197}
198
199// Returns None when:
Sam McCall19ac0eaf2019-11-25 19:51:07 +0100200// - ferror(), feof(), or shutdownRequested() are set.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000201// - Content-Length is missing or empty (protocol error)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000202llvm::Optional<std::string> JSONTransport::readStandardMessage() {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000203 // A Language Server Protocol message starts with a set of HTTP headers,
204 // delimited by \r\n, and terminated by an empty line (\r\n).
205 unsigned long long ContentLength = 0;
206 std::string Line;
207 while (true) {
208 if (feof(In) || ferror(In) || !readLine(In, Line))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000209 return llvm::None;
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000210 InMirror << Line;
211
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000212 llvm::StringRef LineRef(Line);
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000213
214 // We allow comments in headers. Technically this isn't part
215
216 // of the LSP specification, but makes writing tests easier.
217 if (LineRef.startswith("#"))
218 continue;
219
220 // Content-Length is a mandatory header, and the only one we handle.
221 if (LineRef.consume_front("Content-Length: ")) {
222 if (ContentLength != 0) {
223 elog("Warning: Duplicate Content-Length header received. "
224 "The previous value for this message ({0}) was ignored.",
225 ContentLength);
226 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000227 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000228 continue;
229 } else if (!LineRef.trim().empty()) {
230 // It's another header, ignore it.
231 continue;
232 } else {
233 // An empty line indicates the end of headers.
234 // Go ahead and read the JSON.
235 break;
236 }
237 }
238
239 // The fuzzer likes crashing us by sending "Content-Length: 9999999999999999"
240 if (ContentLength > 1 << 30) { // 1024M
241 elog("Refusing to read message with long Content-Length: {0}. "
242 "Expect protocol errors",
243 ContentLength);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000244 return llvm::None;
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000245 }
246 if (ContentLength == 0) {
247 log("Warning: Missing Content-Length header, or zero-length message.");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000248 return llvm::None;
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000249 }
250
251 std::string JSON(ContentLength, '\0');
252 for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
253 // Handle EINTR which is sent when a debugger attaches on some platforms.
Sam McCall19ac0eaf2019-11-25 19:51:07 +0100254 Read = retryAfterSignalUnlessShutdown(0, [&]{
255 return std::fread(&JSON[Pos], 1, ContentLength - Pos, In);
256 });
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000257 if (Read == 0) {
258 elog("Input was aborted. Read only {0} bytes of expected {1}.", Pos,
259 ContentLength);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000260 return llvm::None;
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000261 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000262 InMirror << llvm::StringRef(&JSON[Pos], Read);
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000263 clearerr(In); // If we're done, the error was transient. If we're not done,
264 // either it was transient or we'll see it again on retry.
265 Pos += Read;
266 }
267 return std::move(JSON);
268}
269
270// For lit tests we support a simplified syntax:
271// - messages are delimited by '---' on a line by itself
272// - lines starting with # are ignored.
273// This is a testing path, so favor simplicity over performance here.
Sam McCall19ac0eaf2019-11-25 19:51:07 +0100274// When returning None, feof(), ferror(), or shutdownRequested() will be set.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000275llvm::Optional<std::string> JSONTransport::readDelimitedMessage() {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000276 std::string JSON;
277 std::string Line;
278 while (readLine(In, Line)) {
279 InMirror << Line;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000280 auto LineRef = llvm::StringRef(Line).trim();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000281 if (LineRef.startswith("#")) // comment
282 continue;
283
284 // found a delimiter
285 if (LineRef.rtrim() == "---")
286 break;
287
288 JSON += Line;
289 }
290
Sam McCall19ac0eaf2019-11-25 19:51:07 +0100291 if (shutdownRequested())
292 return llvm::None;
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000293 if (ferror(In)) {
294 elog("Input error while reading message!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000295 return llvm::None;
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000296 }
297 return std::move(JSON); // Including at EOF
298}
299
300} // namespace
301
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000302std::unique_ptr<Transport> newJSONTransport(std::FILE *In,
303 llvm::raw_ostream &Out,
304 llvm::raw_ostream *InMirror,
305 bool Pretty,
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000306 JSONStreamStyle Style) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000307 return std::make_unique<JSONTransport>(In, Out, InMirror, Pretty, Style);
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000308}
309
310} // namespace clangd
311} // namespace clang