1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
22 /* $ModDesc: Encode and decode JSON-RPC requests for modules */
23 /* $ModDep: httpd.h rpc.h */
25 class JsonException : public std::exception
30 JsonException(const std::string &what)
35 virtual ~JsonException() throw() { }
37 virtual const char *what() const throw()
43 class ModuleRpcJson : public Module
48 ModuleRpcJson(InspIRCd *Me)
51 ServerInstance->Modules->PublishInterface("RPC", this);
54 virtual ~ModuleRpcJson()
56 ServerInstance->Modules->UnpublishInterface("RPC", this);
59 virtual Version GetVersion()
61 return Version(1, 1, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
64 void Implements(char *List)
69 virtual void OnEvent(Event *event)
71 if (event->GetEventID() == "httpd_url")
73 HTTPRequest *req = (HTTPRequest*) event->GetData();
75 if ((req->GetURI() == "/rpc/json") || (req->GetURI() == "/rpc/json/"))
77 std::stringstream data;
79 RPCValue *reqobj = NULL;
83 reqobj = this->JSONParse(req->GetPostData());
85 if (!reqobj || (reqobj->GetType() != RPCObject))
86 throw JsonException("RPC requests must be in the form of a single object");
88 RPCValue *method = reqobj->GetObject("method");
89 if (!method || method->GetType() != RPCString)
90 throw JsonException("RPC requests must have a 'method' string field");
92 RPCValue *params = reqobj->GetObject("params");
93 if (!params || params->GetType() != RPCArray)
94 throw JsonException("RPC requests must have a 'params' array field");
96 RPCRequest modreq("json", method->GetString(), params);
97 Event mev((char*) &modreq, this, "RPCMethod");
98 mev.Send(ServerInstance);
101 throw JsonException("Unrecognized method");
103 if (!modreq.error.empty())
105 data << "{\"result\":null,\"error\":\"" << modreq.error << "\"";
109 data << "{\"result\":";
110 this->JSONSerialize(modreq.result, data);
111 data << ",\"error\":null";
114 if (reqobj->GetObject("id"))
117 this->JSONSerialize(reqobj->GetObject("id"), data);
124 catch (std::exception &e)
128 data << "{\"result\":null,\"error\":\"" << e.what() << "\"}";
131 HTTPDocument response(req->sock, &data, 200);
132 response.headers.SetHeader("X-Powered-By", "m_rpc_json.so");
133 response.headers.SetHeader("Content-Type", "application/json");
134 response.headers.SetHeader("Connection", "Keep-Alive");
136 Request rreq((char*) &response, (Module*) this, event->GetSource());
142 void AttachToParent(RPCValue *parent, RPCValue *child, const std::string &key = "")
144 if (!parent || !child)
147 if (parent->GetType() == RPCArray)
148 parent->ArrayAdd(child);
149 else if (parent->GetType() == RPCObject)
150 parent->ObjectAdd(key, child);
152 throw JsonException("Cannot add a value to a non-container");
155 void AttachToParentReset(RPCValue *parent, RPCValue *&child, std::string &key)
157 AttachToParent(parent, child, key);
162 RPCValue *JSONParse(const std::string &data)
164 bool pisobject = false;
165 bool instring = false;
169 RPCValue *aparent = NULL;
170 RPCValue *value = NULL;
172 for (std::string::const_iterator i = data.begin(); i != data.end(); i++)
176 // TODO escape sequences
181 if (pisobject && vkey.empty())
184 value = new RPCValue(stmp);
194 if ((*i == ' ') || (*i == '\t') || (*i == '\r') || (*i == '\n'))
200 if ((value) || (pisobject && vkey.empty()))
201 throw JsonException("Unexpected begin object token ('{')");
203 RPCValue *nobj = new RPCValue(RPCObject, aparent);
212 if ((!aparent) || (!pisobject) || (!vkey.empty() && !value))
213 throw JsonException("Unexpected end object token ('}')");
217 AttachToParentReset(aparent, value, vkey);
219 if (!aparent->parent)
223 aparent = aparent->parent;
226 pisobject = (aparent->GetType() == RPCObject);
232 throw JsonException("Unexpected begin string token ('\"')");
238 if ((!aparent) || (!pisobject) || (vkey.empty()) || (value))
239 throw JsonException("Unexpected object value token (':')");
243 if ((!aparent) || (!value) || ((pisobject) && (vkey.empty())))
244 throw JsonException("Unexpected value seperator token (',')");
246 AttachToParentReset(aparent, value, vkey);
251 if ((value) || (pisobject && vkey.empty()))
252 throw JsonException("Unexpected begin array token ('[')");
254 RPCValue *nar = new RPCValue(RPCArray, aparent);
262 // End array (also an end value delimiter)
263 if (!aparent || pisobject)
264 throw JsonException("Unexpected end array token (']')");
267 AttachToParentReset(aparent, value, vkey);
269 if (!aparent->parent)
273 aparent = aparent->parent;
276 pisobject = (aparent->GetType() == RPCObject);
280 // Numbers, false, null, and true fall under this heading.
281 if ((*i == 't') && ((i + 3) < data.end()) && (*(i + 1) == 'r') && (*(i + 2) == 'u') && (*(i + 3) == 'e'))
283 value = new RPCValue(true);
286 else if ((*i == 'f') && ((i + 4) < data.end()) && (*(i + 1) == 'a') && (*(i + 2) == 'l') && (*(i + 3) == 's') && (*(i + 4) == 'e'))
288 value = new RPCValue(false);
291 else if ((*i == 'n') && ((i + 3) < data.end()) && (*(i + 1) == 'u') && (*(i + 2) == 'l') && (*(i + 3) == 'l'))
293 value = new RPCValue();
296 else if ((*i == '-') || (*i == '+') || (*i == '.') || ((*i >= '0') && (*i <= '9')))
298 std::string ds = std::string(i, data.end());
302 double v = strtod(ds.c_str(), &eds);
305 throw JsonException("Error parsing numeric value");
307 value = new RPCValue(v);
309 i += eds - ds.c_str() - 1;
312 throw JsonException("Unknown data in value portion");
317 throw JsonException("Unterminated string");
319 if (aparent && pisobject)
320 throw JsonException("Unterminated object");
321 else if (aparent && !pisobject)
322 throw JsonException("Unterminated array");
327 throw JsonException("No JSON data found");
330 void JSONSerialize(RPCValue *value, std::stringstream &re)
333 switch (value->GetType())
339 re << ((value->GetBool()) ? "true" : "false");
342 re << value->GetInt();
345 re << "\"" << value->GetString() << "\"";
349 ac = value->ArraySize();
350 for (int i = 0; i < ac; i++)
352 this->JSONSerialize(value->GetArray(i), re);
360 std::pair<RPCObjectContainer::iterator,RPCObjectContainer::iterator> its = value->GetObjectIterator();
361 while (its.first != its.second)
363 re << "\"" << its.first->first << "\":";
364 this->JSONSerialize(its.first->second, re);
365 if (++its.first != its.second)
374 MODULE_INIT(ModuleRpcJson);