]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_rpc_json.cpp
DOH! Fix my muppetry of a segfault, and fix some warnings
[user/henk/code/inspircd.git] / src / modules / m_rpc_json.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "users.h"
16 #include "channels.h"
17 #include "modules.h"
18 #include "httpd.h"
19 #include "rpc.h"
20 #include <exception>
21
22 /* $ModDesc: Encode and decode JSON-RPC requests for modules */
23 /* $ModDep: httpd.h rpc.h */
24
25 class JsonException : public std::exception
26 {
27  private:
28         std::string _what;
29  public:
30         JsonException(const std::string &swhat)
31                 : _what(swhat)
32         {
33         }
34         
35         virtual ~JsonException() throw() { }
36         
37         virtual const char *what() const throw()
38         {
39                 return _what.c_str();
40         }
41 };
42
43 class ModuleRpcJson : public Module
44 {
45  private:
46         
47  public:
48         ModuleRpcJson(InspIRCd *Me) : Module(Me)
49         {
50                 ServerInstance->Modules->PublishInterface("RPC", this);
51                 Implementation eventlist[] = { I_OnEvent };
52                 ServerInstance->Modules->Attach(eventlist, this, 1);
53         }
54         
55         virtual ~ModuleRpcJson()
56         {
57                 ServerInstance->Modules->UnpublishInterface("RPC", this);
58         }
59         
60         virtual Version GetVersion()
61         {
62                 return Version(1, 2, 0, 0, VF_SERVICEPROVIDER | VF_VENDOR, API_VERSION);
63         }
64         
65         
66         virtual void OnEvent(Event *event)
67         {
68                 if (event->GetEventID() == "httpd_url")
69                 {
70                         HTTPRequest *req = (HTTPRequest*) event->GetData();
71                         
72                         if ((req->GetURI() == "/rpc/json") || (req->GetURI() == "/rpc/json/"))
73                         {
74                                 std::stringstream data;
75                                 
76                                 RPCValue *reqobj = NULL;
77                                 
78                                 try
79                                 {
80                                         reqobj = this->JSONParse(req->GetPostData());
81                                         
82                                         if (!reqobj || (reqobj->GetType() != RPCObject))
83                                                 throw JsonException("RPC requests must be in the form of a single object");
84                                         
85                                         RPCValue *method = reqobj->GetObject("method");
86                                         if (!method || method->GetType() != RPCString)
87                                                 throw JsonException("RPC requests must have a 'method' string field");
88                                         
89                                         RPCValue *params = reqobj->GetObject("params");
90                                         if (!params || params->GetType() != RPCArray)
91                                                 throw JsonException("RPC requests must have a 'params' array field");
92                                         
93                                         RPCRequest modreq("json", method->GetString(), params);
94                                         Event mev((char*) &modreq, this, "RPCMethod");
95                                         mev.Send(ServerInstance);
96                                         
97                                         if (!modreq.claimed)
98                                                 throw JsonException("Unrecognized method");
99                                         
100                                         if (!modreq.error.empty())
101                                         {
102                                                 data << "{\"result\":null,\"error\":\"" << modreq.error << "\"";
103                                         }
104                                         else
105                                         {
106                                                 data << "{\"result\":";
107                                                 this->JSONSerialize(modreq.result, data);
108                                                 data << ",\"error\":null";
109                                         }
110                                         
111                                         if (reqobj->GetObject("id"))
112                                         {
113                                                 data << ",\"id\":";
114                                                 this->JSONSerialize(reqobj->GetObject("id"), data);
115                                         }
116                                         data << "}";
117                                                                                 
118                                         delete reqobj;
119                                         reqobj = NULL;
120                                 }
121                                 catch (std::exception &e)
122                                 {
123                                         if (reqobj)
124                                                 delete reqobj;
125                                         data << "{\"result\":null,\"error\":\"" << e.what() << "\"}";
126                                 }
127                                 
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");
132                                 
133                                 Request rreq((char*) &response, (Module*) this, event->GetSource());
134                                 rreq.Send();
135                         }
136                 }
137         }
138         
139         void AttachToParent(RPCValue *parent, RPCValue *child, const std::string &key = "")
140         {
141                 if (!parent || !child)
142                         return;
143                 
144                 if (parent->GetType() == RPCArray)
145                         parent->ArrayAdd(child);
146                 else if (parent->GetType() == RPCObject)
147                         parent->ObjectAdd(key, child);
148                 else
149                         throw JsonException("Cannot add a value to a non-container");
150         }
151         
152         void AttachToParentReset(RPCValue *parent, RPCValue *&child, std::string &key)
153         {
154                 AttachToParent(parent, child, key);
155                 child = NULL;
156                 key.clear();
157         }
158         
159         RPCValue *JSONParse(const std::string &data)
160         {
161                 bool pisobject = false;
162                 bool instring = false;
163                 std::string stmp;
164                 std::string vkey;
165                 std::string pvkey;
166                 RPCValue *aparent = NULL;
167                 RPCValue *value = NULL;
168                 
169                 for (std::string::const_iterator i = data.begin(); i != data.end(); i++)
170                 {
171                         if (instring)
172                         {
173                                 // TODO escape sequences
174                                 if (*i == '"')
175                                 {
176                                         instring = false;
177                                         
178                                         if (pisobject && vkey.empty())
179                                                 vkey = stmp;
180                                         else
181                                                 value = new RPCValue(stmp);
182                                         
183                                         stmp.clear();
184                                 }
185                                 else
186                                         stmp += *i;
187                                 
188                                 continue;
189                         }
190                         
191                         if ((*i == ' ') || (*i == '\t') || (*i == '\r') || (*i == '\n'))
192                                 continue;
193                         
194                         if (*i == '{')
195                         {
196                                 // Begin object
197                                 if ((value) || (pisobject && vkey.empty()))
198                                         throw JsonException("Unexpected begin object token ('{')");
199                                 
200                                 RPCValue *nobj = new RPCValue(RPCObject, aparent);
201                                 aparent = nobj;
202                                 pvkey = vkey;
203                                 vkey.clear();
204                                 pisobject = true;
205                         }
206                         else if (*i == '}')
207                         {
208                                 // End object
209                                 if ((!aparent) || (!pisobject) || (!vkey.empty() && !value))
210                                         throw JsonException("Unexpected end object token ('}')");
211                                 
212                                 // End value
213                                 if (value)
214                                         AttachToParentReset(aparent, value, vkey);
215                                 
216                                 if (!aparent->parent)
217                                         return aparent;
218                                 
219                                 value = aparent;
220                                 aparent = aparent->parent;
221                                 vkey = pvkey;
222                                 pvkey.clear();
223                                 pisobject = (aparent->GetType() == RPCObject);
224                         }
225                         else if (*i == '"')
226                         {
227                                 // Begin string
228                                 if (value)
229                                         throw JsonException("Unexpected begin string token ('\"')");
230                                 
231                                 instring = true;
232                         }
233                         else if (*i == ':')
234                         {
235                                 if ((!aparent) || (!pisobject) || (vkey.empty()) || (value))
236                                         throw JsonException("Unexpected object value token (':')");
237                         }
238                         else if (*i == ',')
239                         {
240                                 if ((!aparent) || (!value) || ((pisobject) && (vkey.empty())))
241                                         throw JsonException("Unexpected value seperator token (',')");
242                                 
243                                 AttachToParentReset(aparent, value, vkey);
244                         }
245                         else if (*i == '[')
246                         {
247                                 // Begin array
248                                 if ((value) || (pisobject && vkey.empty()))
249                                         throw JsonException("Unexpected begin array token ('[')");
250                                 
251                                 RPCValue *nar = new RPCValue(RPCArray, aparent);
252                                 aparent = nar;
253                                 pvkey = vkey;
254                                 vkey.clear();
255                                 pisobject = false;
256                         }
257                         else if (*i == ']')
258                         {
259                                 // End array (also an end value delimiter)
260                                 if (!aparent || pisobject)
261                                         throw JsonException("Unexpected end array token (']')");
262                                 
263                                 if (value)
264                                         AttachToParentReset(aparent, value, vkey);
265                                 
266                                 if (!aparent->parent)
267                                         return aparent;
268                                 
269                                 value = aparent;
270                                 aparent = aparent->parent;
271                                 vkey = pvkey;
272                                 pvkey.clear();
273                                 pisobject = (aparent->GetType() == RPCObject);
274                         }
275                         else
276                         {
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'))
279                                 {
280                                         value = new RPCValue(true);
281                                         i += 3;
282                                 }
283                                 else if ((*i == 'f') && ((i + 4) < data.end()) && (*(i + 1) == 'a') && (*(i + 2) == 'l') && (*(i + 3) == 's') && (*(i + 4) == 'e'))
284                                 {
285                                         value = new RPCValue(false);
286                                         i += 4;
287                                 }
288                                 else if ((*i == 'n') && ((i + 3) < data.end()) && (*(i + 1) == 'u') && (*(i + 2) == 'l') && (*(i + 3) == 'l'))
289                                 {
290                                         value = new RPCValue();
291                                         i += 3;
292                                 }
293                                 else if ((*i == '-') || (*i == '+') || (*i == '.') || ((*i >= '0') && (*i <= '9')))
294                                 {
295                                         std::string ds = std::string(i, data.end());
296                                         char *eds = NULL;
297                                         
298                                         errno = 0;
299                                         double v = strtod(ds.c_str(), &eds);
300                                         
301                                         if (errno != 0)
302                                                 throw JsonException("Error parsing numeric value");
303                                         
304                                         value = new RPCValue(v);
305                                         
306                                         i += eds - ds.c_str() - 1;
307                                 }
308                                 else
309                                         throw JsonException("Unknown data in value portion");
310                         }
311                 }
312                 
313                 if (instring)
314                         throw JsonException("Unterminated string");
315                 
316                 if (aparent && pisobject)
317                         throw JsonException("Unterminated object");
318                 else if (aparent && !pisobject)
319                         throw JsonException("Unterminated array");
320                 
321                 if (value)
322                         return value;
323                 else
324                         throw JsonException("No JSON data found");
325         }
326         
327         void JSONSerialize(RPCValue *value, std::stringstream &re)
328         {
329                 int ac;
330                 switch (value->GetType())
331                 {
332                         case RPCNull:
333                                 re << "null";
334                                 break;
335                         case RPCBoolean:
336                                 re << ((value->GetBool()) ? "true" : "false");
337                                 break;
338                         case RPCInteger:
339                                 re << value->GetInt();
340                                 break;
341                         case RPCString:
342                                 re << "\"" << value->GetString() << "\"";
343                                 break;
344                         case RPCArray:
345                                 re << "[";
346                                 ac = value->ArraySize();
347                                 for (int i = 0; i < ac; i++)
348                                 {
349                                         this->JSONSerialize(value->GetArray(i), re);
350                                         if (i != (ac - 1))
351                                                 re << ",";
352                                 }
353                                 re << "]";
354                                 break;
355                         case RPCObject:
356                                 re << "{";
357                                 std::pair<RPCObjectContainer::iterator,RPCObjectContainer::iterator> its = value->GetObjectIterator();
358                                 while (its.first != its.second)
359                                 {
360                                         re << "\"" << its.first->first << "\":";
361                                         this->JSONSerialize(its.first->second, re);
362                                         if (++its.first != its.second)
363                                                 re << ",";
364                                 }
365                                 re << "}";
366                                 break;
367                 }
368         }
369 };
370
371 MODULE_INIT(ModuleRpcJson)