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) : Module(Me)
50 ServerInstance->Modules->PublishInterface("RPC", this);
53 virtual ~ModuleRpcJson()
55 ServerInstance->Modules->UnpublishInterface("RPC", this);
58 virtual Version GetVersion()
60 return Version(1, 1, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
63 void Implements(char *List)
68 virtual void OnEvent(Event *event)
70 if (event->GetEventID() == "httpd_url")
72 HTTPRequest *req = (HTTPRequest*) event->GetData();
74 if ((req->GetURI() == "/rpc/json") || (req->GetURI() == "/rpc/json/"))
76 std::stringstream data;
78 RPCValue *reqobj = NULL;
82 reqobj = this->JSONParse(req->GetPostData());
84 if (!reqobj || (reqobj->GetType() != RPCObject))
85 throw JsonException("RPC requests must be in the form of a single object");
87 RPCValue *method = reqobj->GetObject("method");
88 if (!method || method->GetType() != RPCString)
89 throw JsonException("RPC requests must have a 'method' string field");
91 RPCValue *params = reqobj->GetObject("params");
92 if (!params || params->GetType() != RPCArray)
93 throw JsonException("RPC requests must have a 'params' array field");
95 RPCRequest modreq("json", method->GetString(), params);
96 Event mev((char*) &modreq, this, "RPCMethod");
97 mev.Send(ServerInstance);
100 throw JsonException("Unrecognized method");
102 if (!modreq.error.empty())
104 data << "{\"result\":null,\"error\":\"" << modreq.error << "\"";
108 data << "{\"result\":";
109 this->JSONSerialize(modreq.result, data);
110 data << ",\"error\":null";
113 if (reqobj->GetObject("id"))
116 this->JSONSerialize(reqobj->GetObject("id"), data);
123 catch (std::exception &e)
127 data << "{\"result\":null,\"error\":\"" << e.what() << "\"}";
130 HTTPDocument response(req->sock, &data, 200);
131 response.headers.SetHeader("X-Powered-By", "m_rpc_json.so");
132 response.headers.SetHeader("Content-Type", "application/json");
133 response.headers.SetHeader("Connection", "Keep-Alive");
135 Request rreq((char*) &response, (Module*) this, event->GetSource());
141 void AttachToParent(RPCValue *parent, RPCValue *child, const std::string &key = "")
143 if (!parent || !child)
146 if (parent->GetType() == RPCArray)
147 parent->ArrayAdd(child);
148 else if (parent->GetType() == RPCObject)
149 parent->ObjectAdd(key, child);
151 throw JsonException("Cannot add a value to a non-container");
154 void AttachToParentReset(RPCValue *parent, RPCValue *&child, std::string &key)
156 AttachToParent(parent, child, key);
161 RPCValue *JSONParse(const std::string &data)
163 bool pisobject = false;
164 bool instring = false;
168 RPCValue *aparent = NULL;
169 RPCValue *value = NULL;
171 for (std::string::const_iterator i = data.begin(); i != data.end(); i++)
175 // TODO escape sequences
180 if (pisobject && vkey.empty())
183 value = new RPCValue(stmp);
193 if ((*i == ' ') || (*i == '\t') || (*i == '\r') || (*i == '\n'))
199 if ((value) || (pisobject && vkey.empty()))
200 throw JsonException("Unexpected begin object token ('{')");
202 RPCValue *nobj = new RPCValue(RPCObject, aparent);
211 if ((!aparent) || (!pisobject) || (!vkey.empty() && !value))
212 throw JsonException("Unexpected end object token ('}')");
216 AttachToParentReset(aparent, value, vkey);
218 if (!aparent->parent)
222 aparent = aparent->parent;
225 pisobject = (aparent->GetType() == RPCObject);
231 throw JsonException("Unexpected begin string token ('\"')");
237 if ((!aparent) || (!pisobject) || (vkey.empty()) || (value))
238 throw JsonException("Unexpected object value token (':')");
242 if ((!aparent) || (!value) || ((pisobject) && (vkey.empty())))
243 throw JsonException("Unexpected value seperator token (',')");
245 AttachToParentReset(aparent, value, vkey);
250 if ((value) || (pisobject && vkey.empty()))
251 throw JsonException("Unexpected begin array token ('[')");
253 RPCValue *nar = new RPCValue(RPCArray, aparent);
261 // End array (also an end value delimiter)
262 if (!aparent || pisobject)
263 throw JsonException("Unexpected end array token (']')");
266 AttachToParentReset(aparent, value, vkey);
268 if (!aparent->parent)
272 aparent = aparent->parent;
275 pisobject = (aparent->GetType() == RPCObject);
279 // Numbers, false, null, and true fall under this heading.
280 if ((*i == 't') && ((i + 3) < data.end()) && (*(i + 1) == 'r') && (*(i + 2) == 'u') && (*(i + 3) == 'e'))
282 value = new RPCValue(true);
285 else if ((*i == 'f') && ((i + 4) < data.end()) && (*(i + 1) == 'a') && (*(i + 2) == 'l') && (*(i + 3) == 's') && (*(i + 4) == 'e'))
287 value = new RPCValue(false);
290 else if ((*i == 'n') && ((i + 3) < data.end()) && (*(i + 1) == 'u') && (*(i + 2) == 'l') && (*(i + 3) == 'l'))
292 value = new RPCValue();
295 else if ((*i == '-') || (*i == '+') || (*i == '.') || ((*i >= '0') && (*i <= '9')))
297 std::string ds = std::string(i, data.end());
301 double v = strtod(ds.c_str(), &eds);
304 throw JsonException("Error parsing numeric value");
306 value = new RPCValue(v);
308 i += eds - ds.c_str() - 1;
311 throw JsonException("Unknown data in value portion");
316 throw JsonException("Unterminated string");
318 if (aparent && pisobject)
319 throw JsonException("Unterminated object");
320 else if (aparent && !pisobject)
321 throw JsonException("Unterminated array");
326 throw JsonException("No JSON data found");
329 void JSONSerialize(RPCValue *value, std::stringstream &re)
332 switch (value->GetType())
338 re << ((value->GetBool()) ? "true" : "false");
341 re << value->GetInt();
344 re << "\"" << value->GetString() << "\"";
348 ac = value->ArraySize();
349 for (int i = 0; i < ac; i++)
351 this->JSONSerialize(value->GetArray(i), re);
359 std::pair<RPCObjectContainer::iterator,RPCObjectContainer::iterator> its = value->GetObjectIterator();
360 while (its.first != its.second)
362 re << "\"" << its.first->first << "\":";
363 this->JSONSerialize(its.first->second, re);
364 if (++its.first != its.second)
373 MODULE_INIT(ModuleRpcJson);