1 //===--- JSONTransport.cpp - sending and receiving LSP messages over JSON -===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 #include "Protocol.h" // For LSPError
9 #include "Transport.h"
10 #include "support/Cancellation.h"
11 #include "support/Logger.h"
12 #include "support/Shutdown.h"
13 #include "llvm/Support/Errno.h"
14 #include "llvm/Support/Error.h"
15 #include <system_error>
16 
17 namespace clang {
18 namespace clangd {
19 namespace {
20 
21 llvm::json::Object encodeError(llvm::Error E) {
22   std::string Message;
23   ErrorCode Code = ErrorCode::UnknownErrorCode;
24   // FIXME: encode cancellation errors using RequestCancelled or ContentModified
25   // as appropriate.
26   if (llvm::Error Unhandled = llvm::handleErrors(
27           std::move(E),
28           [&](const CancelledError &C) -> llvm::Error {
29             switch (C.Reason) {
30             case static_cast<int>(ErrorCode::ContentModified):
31               Code = ErrorCode::ContentModified;
32               Message = "Request cancelled because the document was modified";
33               break;
34             default:
35               Code = ErrorCode::RequestCancelled;
36               Message = "Request cancelled";
37               break;
38             }
39             return llvm::Error::success();
40           },
41           [&](const LSPError &L) -> llvm::Error {
42             Message = L.Message;
43             Code = L.Code;
44             return llvm::Error::success();
45           }))
46     Message = llvm::toString(std::move(Unhandled));
47 
48   return llvm::json::Object{
49       {"message", std::move(Message)},
50       {"code", int64_t(Code)},
51   };
52 }
53 
54 llvm::Error decodeError(const llvm::json::Object &O) {
55   llvm::StringRef Msg = O.getString("message").getValueOr("Unspecified error");
56   if (auto Code = O.getInteger("code"))
57     return llvm::make_error<LSPError>(Msg.str(), ErrorCode(*Code));
58   return error(Msg.str());
59 }
60 
61 class JSONTransport : public Transport {
62 public:
63   JSONTransport(std::FILE *In, llvm::raw_ostream &Out,
64                 llvm::raw_ostream *InMirror, bool Pretty, JSONStreamStyle Style)
65       : In(In), Out(Out), InMirror(InMirror ? *InMirror : llvm::nulls()),
66         Pretty(Pretty), Style(Style) {}
67 
68   void notify(llvm::StringRef Method, llvm::json::Value Params) override {
69     sendMessage(llvm::json::Object{
70         {"jsonrpc", "2.0"},
71         {"method", Method},
72         {"params", std::move(Params)},
73     });
74   }
75   void call(llvm::StringRef Method, llvm::json::Value Params,
76             llvm::json::Value ID) override {
77     sendMessage(llvm::json::Object{
78         {"jsonrpc", "2.0"},
79         {"id", std::move(ID)},
80         {"method", Method},
81         {"params", std::move(Params)},
82     });
83   }
84   void reply(llvm::json::Value ID,
85              llvm::Expected<llvm::json::Value> Result) override {
86     if (Result) {
87       sendMessage(llvm::json::Object{
88           {"jsonrpc", "2.0"},
89           {"id", std::move(ID)},
90           {"result", std::move(*Result)},
91       });
92     } else {
93       sendMessage(llvm::json::Object{
94           {"jsonrpc", "2.0"},
95           {"id", std::move(ID)},
96           {"error", encodeError(Result.takeError())},
97       });
98     }
99   }
100 
101   llvm::Error loop(MessageHandler &Handler) override {
102     while (!feof(In)) {
103       if (shutdownRequested())
104         return error(std::make_error_code(std::errc::operation_canceled),
105                      "Got signal, shutting down");
106       if (ferror(In))
107         return llvm::errorCodeToError(
108             std::error_code(errno, std::system_category()));
109       if (auto JSON = readRawMessage()) {
110         if (auto Doc = llvm::json::parse(*JSON)) {
111           vlog(Pretty ? "<<< {0:2}\n" : "<<< {0}\n", *Doc);
112           if (!handleMessage(std::move(*Doc), Handler))
113             return llvm::Error::success(); // we saw the "exit" notification.
114         } else {
115           // Parse error. Log the raw message.
116           vlog("<<< {0}\n", *JSON);
117           elog("JSON parse error: {0}", llvm::toString(Doc.takeError()));
118         }
119       }
120     }
121     return llvm::errorCodeToError(std::make_error_code(std::errc::io_error));
122   }
123 
124 private:
125   // Dispatches incoming message to Handler onNotify/onCall/onReply.
126   bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
127   // Writes outgoing message to Out stream.
128   void sendMessage(llvm::json::Value Message) {
129     OutputBuffer.clear();
130     llvm::raw_svector_ostream OS(OutputBuffer);
131     OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
132     Out << "Content-Length: " << OutputBuffer.size() << "\r\n\r\n"
133         << OutputBuffer;
134     Out.flush();
135     vlog(">>> {0}\n", OutputBuffer);
136   }
137 
138   // Read raw string messages from input stream.
139   llvm::Optional<std::string> readRawMessage() {
140     return Style == JSONStreamStyle::Delimited ? readDelimitedMessage()
141                                                : readStandardMessage();
142   }
143   llvm::Optional<std::string> readDelimitedMessage();
144   llvm::Optional<std::string> readStandardMessage();
145 
146   llvm::SmallVector<char, 0> OutputBuffer;
147   std::FILE *In;
148   llvm::raw_ostream &Out;
149   llvm::raw_ostream &InMirror;
150   bool Pretty;
151   JSONStreamStyle Style;
152 };
153 
154 bool JSONTransport::handleMessage(llvm::json::Value Message,
155                                   MessageHandler &Handler) {
156   // Message must be an object with "jsonrpc":"2.0".
157   auto *Object = Message.getAsObject();
158   if (!Object ||
159       Object->getString("jsonrpc") != llvm::Optional<llvm::StringRef>("2.0")) {
160     elog("Not a JSON-RPC 2.0 message: {0:2}", Message);
161     return false;
162   }
163   // ID may be any JSON value. If absent, this is a notification.
164   llvm::Optional<llvm::json::Value> ID;
165   if (auto *I = Object->get("id"))
166     ID = std::move(*I);
167   auto Method = Object->getString("method");
168   if (!Method) { // This is a response.
169     if (!ID) {
170       elog("No method and no response ID: {0:2}", Message);
171       return false;
172     }
173     if (auto *Err = Object->getObject("error"))
174       return Handler.onReply(std::move(*ID), decodeError(*Err));
175     // Result should be given, use null if not.
176     llvm::json::Value Result = nullptr;
177     if (auto *R = Object->get("result"))
178       Result = std::move(*R);
179     return Handler.onReply(std::move(*ID), std::move(Result));
180   }
181   // Params should be given, use null if not.
182   llvm::json::Value Params = nullptr;
183   if (auto *P = Object->get("params"))
184     Params = std::move(*P);
185 
186   if (ID)
187     return Handler.onCall(*Method, std::move(Params), std::move(*ID));
188   else
189     return Handler.onNotify(*Method, std::move(Params));
190 }
191 
192 // Tries to read a line up to and including \n.
193 // If failing, feof(), ferror(), or shutdownRequested() will be set.
194 bool readLine(std::FILE *In, std::string &Out) {
195   static constexpr int BufSize = 1024;
196   size_t Size = 0;
197   Out.clear();
198   for (;;) {
199     Out.resize(Size + BufSize);
200     // Handle EINTR which is sent when a debugger attaches on some platforms.
201     if (!retryAfterSignalUnlessShutdown(
202             nullptr, [&] { return std::fgets(&Out[Size], BufSize, In); }))
203       return false;
204     clearerr(In);
205     // If the line contained null bytes, anything after it (including \n) will
206     // be ignored. Fortunately this is not a legal header or JSON.
207     size_t Read = std::strlen(&Out[Size]);
208     if (Read > 0 && Out[Size + Read - 1] == '\n') {
209       Out.resize(Size + Read);
210       return true;
211     }
212     Size += Read;
213   }
214 }
215 
216 // Returns None when:
217 //  - ferror(), feof(), or shutdownRequested() are set.
218 //  - Content-Length is missing or empty (protocol error)
219 llvm::Optional<std::string> JSONTransport::readStandardMessage() {
220   // A Language Server Protocol message starts with a set of HTTP headers,
221   // delimited  by \r\n, and terminated by an empty line (\r\n).
222   unsigned long long ContentLength = 0;
223   std::string Line;
224   while (true) {
225     if (feof(In) || ferror(In) || !readLine(In, Line))
226       return llvm::None;
227     InMirror << Line;
228 
229     llvm::StringRef LineRef(Line);
230 
231     // We allow comments in headers. Technically this isn't part
232 
233     // of the LSP specification, but makes writing tests easier.
234     if (LineRef.startswith("#"))
235       continue;
236 
237     // Content-Length is a mandatory header, and the only one we handle.
238     if (LineRef.consume_front("Content-Length: ")) {
239       if (ContentLength != 0) {
240         elog("Warning: Duplicate Content-Length header received. "
241              "The previous value for this message ({0}) was ignored.",
242              ContentLength);
243       }
244       llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
245       continue;
246     } else if (!LineRef.trim().empty()) {
247       // It's another header, ignore it.
248       continue;
249     } else {
250       // An empty line indicates the end of headers.
251       // Go ahead and read the JSON.
252       break;
253     }
254   }
255 
256   // The fuzzer likes crashing us by sending "Content-Length: 9999999999999999"
257   if (ContentLength > 1 << 30) { // 1024M
258     elog("Refusing to read message with long Content-Length: {0}. "
259          "Expect protocol errors",
260          ContentLength);
261     return llvm::None;
262   }
263   if (ContentLength == 0) {
264     log("Warning: Missing Content-Length header, or zero-length message.");
265     return llvm::None;
266   }
267 
268   std::string JSON(ContentLength, '\0');
269   for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
270     // Handle EINTR which is sent when a debugger attaches on some platforms.
271     Read = retryAfterSignalUnlessShutdown(0, [&]{
272       return std::fread(&JSON[Pos], 1, ContentLength - Pos, In);
273     });
274     if (Read == 0) {
275       elog("Input was aborted. Read only {0} bytes of expected {1}.", Pos,
276            ContentLength);
277       return llvm::None;
278     }
279     InMirror << llvm::StringRef(&JSON[Pos], Read);
280     clearerr(In); // If we're done, the error was transient. If we're not done,
281                   // either it was transient or we'll see it again on retry.
282     Pos += Read;
283   }
284   return std::move(JSON);
285 }
286 
287 // For lit tests we support a simplified syntax:
288 // - messages are delimited by '---' on a line by itself
289 // - lines starting with # are ignored.
290 // This is a testing path, so favor simplicity over performance here.
291 // When returning None, feof(), ferror(), or shutdownRequested() will be set.
292 llvm::Optional<std::string> JSONTransport::readDelimitedMessage() {
293   std::string JSON;
294   std::string Line;
295   while (readLine(In, Line)) {
296     InMirror << Line;
297     auto LineRef = llvm::StringRef(Line).trim();
298     if (LineRef.startswith("#")) // comment
299       continue;
300 
301     // found a delimiter
302     if (LineRef.rtrim() == "---")
303       break;
304 
305     JSON += Line;
306   }
307 
308   if (shutdownRequested())
309     return llvm::None;
310   if (ferror(In)) {
311     elog("Input error while reading message!");
312     return llvm::None;
313   }
314   return std::move(JSON); // Including at EOF
315 }
316 
317 } // namespace
318 
319 std::unique_ptr<Transport> newJSONTransport(std::FILE *In,
320                                             llvm::raw_ostream &Out,
321                                             llvm::raw_ostream *InMirror,
322                                             bool Pretty,
323                                             JSONStreamStyle Style) {
324   return std::make_unique<JSONTransport>(In, Out, InMirror, Pretty, Style);
325 }
326 
327 } // namespace clangd
328 } // namespace clang
329