1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
19 /* $ModDesc: Encode and decode JSON-RPC requests for modules */
20 /* $ModDep: httpd.h rpc.h */
22 class JsonException : public std::exception
27 JsonException(const std::string &swhat)
32 virtual ~JsonException() throw() { }
34 virtual const char *what() const throw()
40 class ModuleRpcJson : public Module
45 ModuleRpcJson(InspIRCd *Me) : Module(Me)
47 ServerInstance->Modules->PublishInterface("RPC", this);
48 Implementation eventlist[] = { I_OnEvent };
49 ServerInstance->Modules->Attach(eventlist, this, 1);
52 virtual ~ModuleRpcJson()
54 ServerInstance->Modules->UnpublishInterface("RPC", this);
57 virtual Version GetVersion()
59 return Version("$Id$", VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
63 virtual void OnEvent(Event *event)
65 if (event->GetEventID() == "httpd_url")
67 HTTPRequest *req = (HTTPRequest*) event->GetData();
69 if ((req->GetURI() == "/rpc/json") || (req->GetURI() == "/rpc/json/"))
71 std::stringstream data;
73 RPCValue *reqobj = NULL;
77 reqobj = this->JSONParse(req->GetPostData());
79 if (!reqobj || (reqobj->GetType() != RPCObject))
80 throw JsonException("RPC requests must be in the form of a single object");
82 RPCValue *method = reqobj->GetObject("method");
83 if (!method || method->GetType() != RPCString)
84 throw JsonException("RPC requests must have a 'method' string field");
86 RPCValue *params = reqobj->GetObject("params");
87 if (!params || params->GetType() != RPCArray)
88 throw JsonException("RPC requests must have a 'params' array field");
90 RPCRequest modreq("json", method->GetString(), params);
91 Event mev((char*) &modreq, this, "RPCMethod");
92 mev.Send(ServerInstance);
95 throw JsonException("Unrecognized method");
97 if (!modreq.error.empty())
99 data << "{\"result\":null,\"error\":\"" << modreq.error << "\"";
103 data << "{\"result\":";
104 this->JSONSerialize(modreq.result, data);
105 data << ",\"error\":null";
108 if (reqobj->GetObject("id"))
111 this->JSONSerialize(reqobj->GetObject("id"), data);
118 catch (std::exception &e)
122 data << "{\"result\":null,\"error\":\"" << e.what() << "\"}";
125 HTTPDocument response(req->sock, &data, 200);
126 response.headers.SetHeader("X-Powered-By", "m_rpc_json.so");
127 response.headers.SetHeader("Content-Type", "application/json");
128 response.headers.SetHeader("Connection", "Keep-Alive");
130 Request rreq((char*) &response, (Module*) this, event->GetSource());
136 void AttachToParent(RPCValue *parent, RPCValue *child, const std::string &key = "")
138 if (!parent || !child)
141 if (parent->GetType() == RPCArray)
142 parent->ArrayAdd(child);
143 else if (parent->GetType() == RPCObject)
144 parent->ObjectAdd(key, child);
146 throw JsonException("Cannot add a value to a non-container");
149 void AttachToParentReset(RPCValue *parent, RPCValue *&child, std::string &key)
151 AttachToParent(parent, child, key);
156 RPCValue *JSONParse(const std::string &data)
158 bool pisobject = false;
159 bool instring = false;
163 RPCValue *aparent = NULL;
164 RPCValue *value = NULL;
166 for (std::string::const_iterator i = data.begin(); i != data.end(); i++)
170 // TODO escape sequences
175 if (pisobject && vkey.empty())
178 value = new RPCValue(stmp);
188 if ((*i == ' ') || (*i == '\t') || (*i == '\r') || (*i == '\n'))
194 if ((value) || (pisobject && vkey.empty()))
195 throw JsonException("Unexpected begin object token ('{')");
197 RPCValue *nobj = new RPCValue(RPCObject, aparent);
206 if ((!aparent) || (!pisobject) || (!vkey.empty() && !value))
207 throw JsonException("Unexpected end object token ('}')");
211 AttachToParentReset(aparent, value, vkey);
213 if (!aparent->parent)
217 aparent = aparent->parent;
220 pisobject = (aparent->GetType() == RPCObject);
226 throw JsonException("Unexpected begin string token ('\"')");
232 if ((!aparent) || (!pisobject) || (vkey.empty()) || (value))
233 throw JsonException("Unexpected object value token (':')");
237 if ((!aparent) || (!value) || ((pisobject) && (vkey.empty())))
238 throw JsonException("Unexpected value seperator token (',')");
240 AttachToParentReset(aparent, value, vkey);
245 if ((value) || (pisobject && vkey.empty()))
246 throw JsonException("Unexpected begin array token ('[')");
248 RPCValue *nar = new RPCValue(RPCArray, aparent);
256 // End array (also an end value delimiter)
257 if (!aparent || pisobject)
258 throw JsonException("Unexpected end array token (']')");
261 AttachToParentReset(aparent, value, vkey);
263 if (!aparent->parent)
267 aparent = aparent->parent;
270 pisobject = (aparent->GetType() == RPCObject);
274 // Numbers, false, null, and true fall under this heading.
275 if ((*i == 't') && ((i + 3) < data.end()) && (*(i + 1) == 'r') && (*(i + 2) == 'u') && (*(i + 3) == 'e'))
277 value = new RPCValue(true);
280 else if ((*i == 'f') && ((i + 4) < data.end()) && (*(i + 1) == 'a') && (*(i + 2) == 'l') && (*(i + 3) == 's') && (*(i + 4) == 'e'))
282 value = new RPCValue(false);
285 else if ((*i == 'n') && ((i + 3) < data.end()) && (*(i + 1) == 'u') && (*(i + 2) == 'l') && (*(i + 3) == 'l'))
287 value = new RPCValue();
290 else if ((*i == '-') || (*i == '+') || (*i == '.') || ((*i >= '0') && (*i <= '9')))
292 std::string ds = std::string(i, data.end());
296 double v = strtod(ds.c_str(), &eds);
299 throw JsonException("Error parsing numeric value");
301 value = new RPCValue(v);
303 i += eds - ds.c_str() - 1;
306 throw JsonException("Unknown data in value portion");
311 throw JsonException("Unterminated string");
313 if (aparent && pisobject)
314 throw JsonException("Unterminated object");
315 else if (aparent && !pisobject)
316 throw JsonException("Unterminated array");
321 throw JsonException("No JSON data found");
324 void JSONSerialize(RPCValue *value, std::stringstream &re)
327 switch (value->GetType())
333 re << ((value->GetBool()) ? "true" : "false");
336 re << value->GetInt();
339 re << "\"" << value->GetString() << "\"";
343 ac = value->ArraySize();
344 for (int i = 0; i < ac; i++)
346 this->JSONSerialize(value->GetArray(i), re);
354 std::pair<RPCObjectContainer::iterator,RPCObjectContainer::iterator> its = value->GetObjectIterator();
355 while (its.first != its.second)
357 re << "\"" << its.first->first << "\":";
358 this->JSONSerialize(its.first->second, re);
359 if (++its.first != its.second)
368 MODULE_INIT(ModuleRpcJson)