1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 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 &swhat)
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);
51 Implementation eventlist[] = { I_OnEvent };
52 ServerInstance->Modules->Attach(eventlist, this, 1);
55 virtual ~ModuleRpcJson()
57 ServerInstance->Modules->UnpublishInterface("RPC", this);
60 virtual Version GetVersion()
62 return Version(1, 2, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
66 virtual void OnEvent(Event *event)
68 if (event->GetEventID() == "httpd_url")
70 HTTPRequest *req = (HTTPRequest*) event->GetData();
72 if ((req->GetURI() == "/rpc/json") || (req->GetURI() == "/rpc/json/"))
74 std::stringstream data;
76 RPCValue *reqobj = NULL;
80 reqobj = this->JSONParse(req->GetPostData());
82 if (!reqobj || (reqobj->GetType() != RPCObject))
83 throw JsonException("RPC requests must be in the form of a single object");
85 RPCValue *method = reqobj->GetObject("method");
86 if (!method || method->GetType() != RPCString)
87 throw JsonException("RPC requests must have a 'method' string field");
89 RPCValue *params = reqobj->GetObject("params");
90 if (!params || params->GetType() != RPCArray)
91 throw JsonException("RPC requests must have a 'params' array field");
93 RPCRequest modreq("json", method->GetString(), params);
94 Event mev((char*) &modreq, this, "RPCMethod");
95 mev.Send(ServerInstance);
98 throw JsonException("Unrecognized method");
100 if (!modreq.error.empty())
102 data << "{\"result\":null,\"error\":\"" << modreq.error << "\"";
106 data << "{\"result\":";
107 this->JSONSerialize(modreq.result, data);
108 data << ",\"error\":null";
111 if (reqobj->GetObject("id"))
114 this->JSONSerialize(reqobj->GetObject("id"), data);
121 catch (std::exception &e)
125 data << "{\"result\":null,\"error\":\"" << e.what() << "\"}";
128 HTTPDocument response(req->sock, &data, 200);
129 response.headers.SetHeader("X-Powered-By", "m_rpc_json.so");
130 response.headers.SetHeader("Content-Type", "application/json");
131 response.headers.SetHeader("Connection", "Keep-Alive");
133 Request rreq((char*) &response, (Module*) this, event->GetSource());
139 void AttachToParent(RPCValue *parent, RPCValue *child, const std::string &key = "")
141 if (!parent || !child)
144 if (parent->GetType() == RPCArray)
145 parent->ArrayAdd(child);
146 else if (parent->GetType() == RPCObject)
147 parent->ObjectAdd(key, child);
149 throw JsonException("Cannot add a value to a non-container");
152 void AttachToParentReset(RPCValue *parent, RPCValue *&child, std::string &key)
154 AttachToParent(parent, child, key);
159 RPCValue *JSONParse(const std::string &data)
161 bool pisobject = false;
162 bool instring = false;
166 RPCValue *aparent = NULL;
167 RPCValue *value = NULL;
169 for (std::string::const_iterator i = data.begin(); i != data.end(); i++)
173 // TODO escape sequences
178 if (pisobject && vkey.empty())
181 value = new RPCValue(stmp);
191 if ((*i == ' ') || (*i == '\t') || (*i == '\r') || (*i == '\n'))
197 if ((value) || (pisobject && vkey.empty()))
198 throw JsonException("Unexpected begin object token ('{')");
200 RPCValue *nobj = new RPCValue(RPCObject, aparent);
209 if ((!aparent) || (!pisobject) || (!vkey.empty() && !value))
210 throw JsonException("Unexpected end object token ('}')");
214 AttachToParentReset(aparent, value, vkey);
216 if (!aparent->parent)
220 aparent = aparent->parent;
223 pisobject = (aparent->GetType() == RPCObject);
229 throw JsonException("Unexpected begin string token ('\"')");
235 if ((!aparent) || (!pisobject) || (vkey.empty()) || (value))
236 throw JsonException("Unexpected object value token (':')");
240 if ((!aparent) || (!value) || ((pisobject) && (vkey.empty())))
241 throw JsonException("Unexpected value seperator token (',')");
243 AttachToParentReset(aparent, value, vkey);
248 if ((value) || (pisobject && vkey.empty()))
249 throw JsonException("Unexpected begin array token ('[')");
251 RPCValue *nar = new RPCValue(RPCArray, aparent);
259 // End array (also an end value delimiter)
260 if (!aparent || pisobject)
261 throw JsonException("Unexpected end array token (']')");
264 AttachToParentReset(aparent, value, vkey);
266 if (!aparent->parent)
270 aparent = aparent->parent;
273 pisobject = (aparent->GetType() == RPCObject);
277 // Numbers, false, null, and true fall under this heading.
278 if ((*i == 't') && ((i + 3) < data.end()) && (*(i + 1) == 'r') && (*(i + 2) == 'u') && (*(i + 3) == 'e'))
280 value = new RPCValue(true);
283 else if ((*i == 'f') && ((i + 4) < data.end()) && (*(i + 1) == 'a') && (*(i + 2) == 'l') && (*(i + 3) == 's') && (*(i + 4) == 'e'))
285 value = new RPCValue(false);
288 else if ((*i == 'n') && ((i + 3) < data.end()) && (*(i + 1) == 'u') && (*(i + 2) == 'l') && (*(i + 3) == 'l'))
290 value = new RPCValue();
293 else if ((*i == '-') || (*i == '+') || (*i == '.') || ((*i >= '0') && (*i <= '9')))
295 std::string ds = std::string(i, data.end());
299 double v = strtod(ds.c_str(), &eds);
302 throw JsonException("Error parsing numeric value");
304 value = new RPCValue(v);
306 i += eds - ds.c_str() - 1;
309 throw JsonException("Unknown data in value portion");
314 throw JsonException("Unterminated string");
316 if (aparent && pisobject)
317 throw JsonException("Unterminated object");
318 else if (aparent && !pisobject)
319 throw JsonException("Unterminated array");
324 throw JsonException("No JSON data found");
327 void JSONSerialize(RPCValue *value, std::stringstream &re)
330 switch (value->GetType())
336 re << ((value->GetBool()) ? "true" : "false");
339 re << value->GetInt();
342 re << "\"" << value->GetString() << "\"";
346 ac = value->ArraySize();
347 for (int i = 0; i < ac; i++)
349 this->JSONSerialize(value->GetArray(i), re);
357 std::pair<RPCObjectContainer::iterator,RPCObjectContainer::iterator> its = value->GetObjectIterator();
358 while (its.first != its.second)
360 re << "\"" << its.first->first << "\":";
361 this->JSONSerialize(its.first->second, re);
362 if (++its.first != its.second)
371 MODULE_INIT(ModuleRpcJson)