blob: 0aa1f396a9e98813f3874396f0d72d5e8b3d51b0 [file] [log] [blame]
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +00001//===--- JSONRPCDispatcher.cpp - Main JSON parser entry point -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "JSONRPCDispatcher.h"
11#include "ProtocolHandlers.h"
12#include "llvm/ADT/SmallString.h"
13#include "llvm/Support/SourceMgr.h"
14#include "llvm/Support/YAMLParser.h"
Ilya Biryukov687b92a2017-05-16 15:23:55 +000015#include <istream>
16
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000017using namespace clang;
18using namespace clangd;
19
Benjamin Kramerd0b2ccd2017-02-10 14:08:40 +000020void JSONOutput::writeMessage(const Twine &Message) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000021 llvm::SmallString<128> Storage;
22 StringRef M = Message.toStringRef(Storage);
23
Benjamin Kramerd0b2ccd2017-02-10 14:08:40 +000024 std::lock_guard<std::mutex> Guard(StreamMutex);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000025 // Log without headers.
26 Logs << "--> " << M << '\n';
27 Logs.flush();
28
29 // Emit message with header.
30 Outs << "Content-Length: " << M.size() << "\r\n\r\n" << M;
31 Outs.flush();
32}
33
Benjamin Kramere14bd422017-02-15 16:44:11 +000034void JSONOutput::log(const Twine &Message) {
35 std::lock_guard<std::mutex> Guard(StreamMutex);
36 Logs << Message;
37 Logs.flush();
38}
39
Ilya Biryukove6dbb582017-10-10 09:08:47 +000040void JSONOutput::mirrorInput(const Twine &Message) {
41 if (!InputMirror)
42 return;
43
44 *InputMirror << Message;
45 InputMirror->flush();
46}
47
Sam McCall8a5dded2017-10-12 13:29:58 +000048void RequestContext::reply(const llvm::Twine &Result) {
49 if (ID.empty()) {
50 Out.log("Attempted to reply to a notification!\n");
51 return;
52 }
53 Out.writeMessage(llvm::Twine(R"({"jsonrpc":"2.0","id":)") + ID +
54 R"(,"result":)" + Result + "}");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000055}
56
Sam McCall8a5dded2017-10-12 13:29:58 +000057void RequestContext::replyError(int code, const llvm::StringRef &Message) {
58 Out.log("Error " + llvm::Twine(code) + ": " + Message + "\n");
59 if (!ID.empty()) {
60 Out.writeMessage(llvm::Twine(R"({"jsonrpc":"2.0","id":)") + ID +
61 R"(,"error":{"code":)" + llvm::Twine(code) +
62 R"(,"message":")" + llvm::yaml::escape(Message) +
63 R"("}})");
64 }
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000065}
66
Sam McCall8a5dded2017-10-12 13:29:58 +000067void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000068 assert(!Handlers.count(Method) && "Handler already registered!");
69 Handlers[Method] = std::move(H);
70}
71
72static void
Sam McCall8a5dded2017-10-12 13:29:58 +000073callHandler(const llvm::StringMap<JSONRPCDispatcher::Handler> &Handlers,
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000074 llvm::yaml::ScalarNode *Method, llvm::yaml::ScalarNode *Id,
Sam McCall8a5dded2017-10-12 13:29:58 +000075 llvm::yaml::MappingNode *Params,
76 const JSONRPCDispatcher::Handler &UnknownHandler, JSONOutput &Out) {
77 llvm::SmallString<64> MethodStorage;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000078 auto I = Handlers.find(Method->getValue(MethodStorage));
Sam McCall8a5dded2017-10-12 13:29:58 +000079 auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
80 Handler(RequestContext(Out, Id ? Id->getRawValue() : ""), Params);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000081}
82
Sam McCall8a5dded2017-10-12 13:29:58 +000083bool JSONRPCDispatcher::call(StringRef Content, JSONOutput &Out) const {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000084 llvm::SourceMgr SM;
85 llvm::yaml::Stream YAMLStream(Content, SM);
86
87 auto Doc = YAMLStream.begin();
88 if (Doc == YAMLStream.end())
89 return false;
90
Benjamin Kramerdecd8a72017-10-27 16:33:15 +000091 auto *Object = dyn_cast_or_null<llvm::yaml::MappingNode>(Doc->getRoot());
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000092 if (!Object)
93 return false;
94
95 llvm::yaml::ScalarNode *Version = nullptr;
96 llvm::yaml::ScalarNode *Method = nullptr;
97 llvm::yaml::MappingNode *Params = nullptr;
98 llvm::yaml::ScalarNode *Id = nullptr;
99 for (auto &NextKeyValue : *Object) {
Benjamin Kramerdecd8a72017-10-27 16:33:15 +0000100 auto *KeyString =
101 dyn_cast_or_null<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000102 if (!KeyString)
103 return false;
104
105 llvm::SmallString<10> KeyStorage;
106 StringRef KeyValue = KeyString->getValue(KeyStorage);
107 llvm::yaml::Node *Value = NextKeyValue.getValue();
108 if (!Value)
109 return false;
110
111 if (KeyValue == "jsonrpc") {
112 // This should be "2.0". Always.
113 Version = dyn_cast<llvm::yaml::ScalarNode>(Value);
114 if (!Version || Version->getRawValue() != "\"2.0\"")
115 return false;
116 } else if (KeyValue == "method") {
117 Method = dyn_cast<llvm::yaml::ScalarNode>(Value);
118 } else if (KeyValue == "id") {
119 Id = dyn_cast<llvm::yaml::ScalarNode>(Value);
120 } else if (KeyValue == "params") {
121 if (!Method)
122 return false;
123 // We have to interleave the call of the function here, otherwise the
124 // YAMLParser will die because it can't go backwards. This is unfortunate
125 // because it will break clients that put the id after params. A possible
126 // fix would be to split the parsing and execution phases.
127 Params = dyn_cast<llvm::yaml::MappingNode>(Value);
Sam McCall8a5dded2017-10-12 13:29:58 +0000128 callHandler(Handlers, Method, Id, Params, UnknownHandler, Out);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000129 return true;
130 } else {
131 return false;
132 }
133 }
134
135 // In case there was a request with no params, call the handler on the
136 // leftovers.
137 if (!Method)
138 return false;
Sam McCall8a5dded2017-10-12 13:29:58 +0000139 callHandler(Handlers, Method, Id, nullptr, UnknownHandler, Out);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000140
141 return true;
142}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000143
144void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,
145 JSONRPCDispatcher &Dispatcher,
146 bool &IsDone) {
147 while (In.good()) {
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000148 // A Language Server Protocol message starts with a set of HTTP headers,
149 // delimited by \r\n, and terminated by an empty line (\r\n).
150 unsigned long long ContentLength = 0;
151 while (In.good()) {
152 std::string Line;
153 std::getline(In, Line);
154 if (!In.good() && errno == EINTR) {
155 In.clear();
156 continue;
157 }
158
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000159 Out.mirrorInput(Line);
160 // Mirror '\n' that gets consumed by std::getline, but is not included in
161 // the resulting Line.
162 // Note that '\r' is part of Line, so we don't need to mirror it
163 // separately.
164 if (!In.eof())
165 Out.mirrorInput("\n");
166
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000167 llvm::StringRef LineRef(Line);
168
169 // We allow YAML-style comments in headers. Technically this isn't part
170 // of the LSP specification, but makes writing tests easier.
171 if (LineRef.startswith("#"))
172 continue;
173
174 // Content-Type is a specified header, but does nothing.
175 // Content-Length is a mandatory header. It specifies the length of the
176 // following JSON.
177 // It is unspecified what sequence headers must be supplied in, so we
178 // allow any sequence.
179 // The end of headers is signified by an empty line.
180 if (LineRef.consume_front("Content-Length: ")) {
181 if (ContentLength != 0) {
182 Out.log("Warning: Duplicate Content-Length header received. "
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000183 "The previous value for this message (" +
184 std::to_string(ContentLength) + ") was ignored.\n");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000185 }
186
187 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
188 continue;
189 } else if (!LineRef.trim().empty()) {
190 // It's another header, ignore it.
191 continue;
192 } else {
193 // An empty line indicates the end of headers.
194 // Go ahead and read the JSON.
195 break;
196 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000197 }
198
Benjamin Kramer1d053792017-10-27 17:06:41 +0000199 // Guard against large messages. This is usually a bug in the client code
200 // and we don't want to crash downstream because of it.
201 if (ContentLength > 1 << 30) { // 1024M
202 In.ignore(ContentLength);
203 Out.log("Skipped overly large message of " + Twine(ContentLength) +
204 " bytes.\n");
205 continue;
206 }
207
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000208 if (ContentLength > 0) {
209 // Now read the JSON. Insert a trailing null byte as required by the YAML
210 // parser.
211 std::vector<char> JSON(ContentLength + 1, '\0');
212 In.read(JSON.data(), ContentLength);
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000213 Out.mirrorInput(StringRef(JSON.data(), In.gcount()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000214
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000215 // If the stream is aborted before we read ContentLength bytes, In
216 // will have eofbit and failbit set.
217 if (!In) {
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000218 Out.log("Input was aborted. Read only " + std::to_string(In.gcount()) +
219 " bytes of expected " + std::to_string(ContentLength) + ".\n");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000220 break;
221 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000222
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000223 llvm::StringRef JSONRef(JSON.data(), ContentLength);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000224 // Log the message.
225 Out.log("<-- " + JSONRef + "\n");
226
227 // Finally, execute the action for this JSON message.
Sam McCall8a5dded2017-10-12 13:29:58 +0000228 if (!Dispatcher.call(JSONRef, Out))
Ilya Biryukovafb55542017-05-16 14:40:30 +0000229 Out.log("JSON dispatch failed!\n");
230
231 // If we're done, exit the loop.
232 if (IsDone)
233 break;
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000234 } else {
Ilya Biryukove6dbb582017-10-10 09:08:47 +0000235 Out.log("Warning: Missing Content-Length header, or message has zero "
236 "length.\n");
Ilya Biryukovafb55542017-05-16 14:40:30 +0000237 }
238 }
239}