Implement JSON-RPC protocol.
[cascardo/ovs.git] / lib / jsonrpc.c
1 /*
2  * Copyright (c) 2009 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "jsonrpc.h"
20
21 #include <errno.h>
22
23 #include "byteq.h"
24 #include "json.h"
25 #include "list.h"
26 #include "ofpbuf.h"
27 #include "poll-loop.h"
28 #include "queue.h"
29 #include "stream.h"
30
31 #define THIS_MODULE VLM_jsonrpc
32 #include "vlog.h"
33 \f
34 struct jsonrpc {
35     struct stream *stream;
36     char *name;
37     int status;
38
39     /* Input. */
40     struct byteq input;
41     struct json_parser *parser;
42     struct jsonrpc_msg *received;
43
44     /* Output. */
45     struct ovs_queue output;
46     size_t backlog;
47 };
48
49 /* Rate limit for error messages. */
50 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
51
52 static void jsonrpc_received(struct jsonrpc *);
53 static void jsonrpc_cleanup(struct jsonrpc *);
54
55 struct jsonrpc *
56 jsonrpc_open(struct stream *stream)
57 {
58     struct jsonrpc *rpc;
59
60     assert(stream != NULL);
61
62     rpc = xzalloc(sizeof *rpc);
63     rpc->name = xstrdup(stream_get_name(stream));
64     rpc->stream = stream;
65     byteq_init(&rpc->input);
66     queue_init(&rpc->output);
67
68     return rpc;
69 }
70
71 void
72 jsonrpc_close(struct jsonrpc *rpc)
73 {
74     if (rpc) {
75         jsonrpc_cleanup(rpc);
76         free(rpc->name);
77         free(rpc);
78     }
79 }
80
81 void
82 jsonrpc_run(struct jsonrpc *rpc)
83 {
84     if (rpc->status) {
85         return;
86     }
87
88     while (!queue_is_empty(&rpc->output)) {
89         struct ofpbuf *buf = rpc->output.head;
90         int retval;
91
92         retval = stream_send(rpc->stream, buf->data, buf->size);
93         if (retval >= 0) {
94             rpc->backlog -= retval;
95             ofpbuf_pull(buf, retval);
96             if (!buf->size) {
97                 ofpbuf_delete(queue_pop_head(&rpc->output));
98             }
99         } else {
100             if (retval != -EAGAIN) {
101                 VLOG_WARN_RL(&rl, "%s: send error: %s",
102                              rpc->name, strerror(-retval));
103                 jsonrpc_error(rpc, -retval);
104             }
105             break;
106         }
107     }
108 }
109
110 void
111 jsonrpc_wait(struct jsonrpc *rpc)
112 {
113     if (!rpc->status && !queue_is_empty(&rpc->output)) {
114         stream_send_wait(rpc->stream);
115     }
116 }
117
118 int
119 jsonrpc_get_status(const struct jsonrpc *rpc)
120 {
121     return rpc->status;
122 }
123
124 size_t
125 jsonrpc_get_backlog(const struct jsonrpc *rpc)
126 {
127     return rpc->status ? 0 : rpc->backlog;
128 }
129
130 const char *
131 jsonrpc_get_name(const struct jsonrpc *rpc)
132 {
133     return rpc->name;
134 }
135
136 int
137 jsonrpc_send(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
138 {
139     struct ofpbuf *buf;
140     struct json *json;
141     size_t length;
142     char *s;
143
144     if (rpc->status) {
145         jsonrpc_msg_destroy(msg);
146         return rpc->status;
147     }
148
149     json = jsonrpc_msg_to_json(msg);
150     s = json_to_string(json, 0);
151     length = strlen(s);
152     json_destroy(json);
153
154     buf = xmalloc(sizeof *buf);
155     ofpbuf_use(buf, s, length);
156     buf->size = length;
157     queue_push_tail(&rpc->output, buf);
158     rpc->backlog += length;
159
160     if (rpc->output.n == 1) {
161         jsonrpc_run(rpc);
162     }
163     return rpc->status;
164 }
165
166 int
167 jsonrpc_recv(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
168 {
169     *msgp = NULL;
170     if (rpc->status) {
171         return rpc->status;
172     }
173
174     while (!rpc->received) {
175         if (byteq_is_empty(&rpc->input)) {
176             size_t chunk;
177             int retval;
178
179             chunk = byteq_headroom(&rpc->input);
180             retval = stream_recv(rpc->stream, byteq_head(&rpc->input), chunk);
181             if (retval < 0) {
182                 if (retval == -EAGAIN) {
183                     return EAGAIN;
184                 } else {
185                     VLOG_WARN_RL(&rl, "%s: receive error: %s",
186                                  rpc->name, strerror(-retval));
187                     jsonrpc_error(rpc, -retval);
188                     return rpc->status;
189                 }
190             } else if (retval == 0) {
191                 VLOG_INFO_RL(&rl, "%s: connection closed", rpc->name);
192                 jsonrpc_error(rpc, EOF);
193                 return EOF;
194             }
195             byteq_advance_head(&rpc->input, retval);
196         } else {
197             size_t n, used;
198
199             if (!rpc->parser) {
200                 rpc->parser = json_parser_create(0);
201             }
202             n = byteq_tailroom(&rpc->input);
203             used = json_parser_feed(rpc->parser,
204                                     (char *) byteq_tail(&rpc->input), n);
205             byteq_advance_tail(&rpc->input, used);
206             if (json_parser_is_done(rpc->parser)) {
207                 jsonrpc_received(rpc);
208                 if (rpc->status) {
209                     return rpc->status;
210                 }
211             }
212         }
213     }
214
215     *msgp = rpc->received;
216     rpc->received = NULL;
217     return 0;
218 }
219
220 void
221 jsonrpc_recv_wait(struct jsonrpc *rpc)
222 {
223     if (rpc->status || rpc->received || !byteq_is_empty(&rpc->input)) {
224         poll_immediate_wake();
225     } else {
226         stream_recv_wait(rpc->stream);
227     }
228 }
229
230 int
231 jsonrpc_send_block(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
232 {
233     int error;
234
235     error = jsonrpc_send(rpc, msg);
236     if (error) {
237         return error;
238     }
239
240     while (!queue_is_empty(&rpc->output) && !rpc->status) {
241         jsonrpc_run(rpc);
242         jsonrpc_wait(rpc);
243         poll_block();
244     }
245     return rpc->status;
246 }
247
248 int
249 jsonrpc_recv_block(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
250 {
251     for (;;) {
252         int error = jsonrpc_recv(rpc, msgp);
253         if (error != EAGAIN) {
254             return error;
255         }
256
257         jsonrpc_run(rpc);
258         jsonrpc_wait(rpc);
259         jsonrpc_recv_wait(rpc);
260         poll_block();
261     }
262 }
263
264 static void
265 jsonrpc_received(struct jsonrpc *rpc)
266 {
267     struct jsonrpc_msg *msg;
268     struct json *json;
269     char *error;
270
271     json = json_parser_finish(rpc->parser);
272     rpc->parser = NULL;
273     if (json->type == JSON_STRING) {
274         VLOG_WARN_RL(&rl, "%s: error parsing stream: %s",
275                      rpc->name, json_string(json));
276         jsonrpc_error(rpc, EPROTO);
277         json_destroy(json);
278         return;
279     }
280
281     error = jsonrpc_msg_from_json(json, &msg);
282     if (error) {
283         VLOG_WARN_RL(&rl, "%s: received bad JSON-RPC message: %s",
284                      rpc->name, error);
285         free(error);
286         jsonrpc_error(rpc, EPROTO);
287         return;
288     }
289
290     rpc->received = msg;
291 }
292
293 void
294 jsonrpc_error(struct jsonrpc *rpc, int error)
295 {
296     assert(error);
297     if (!rpc->status) {
298         rpc->status = error;
299         jsonrpc_cleanup(rpc);
300     }
301 }
302
303 static void
304 jsonrpc_cleanup(struct jsonrpc *rpc)
305 {
306     stream_close(rpc->stream);
307     rpc->stream = NULL;
308
309     json_parser_abort(rpc->parser);
310     rpc->parser = NULL;
311
312     jsonrpc_msg_destroy(rpc->received);
313     rpc->received = NULL;
314
315     queue_clear(&rpc->output);
316     rpc->backlog = 0;
317 }
318 \f
319 static struct jsonrpc_msg *
320 jsonrpc_create(enum jsonrpc_msg_type type, const char *method,
321                 struct json *params, struct json *result, struct json *error,
322                 struct json *id)
323 {
324     struct jsonrpc_msg *msg = xmalloc(sizeof *msg);
325     msg->type = type;
326     msg->method = method ? xstrdup(method) : NULL;
327     msg->params = params;
328     msg->result = result;
329     msg->error = error;
330     msg->id = id;
331     return msg;
332 }
333
334 static struct json *
335 jsonrpc_create_id(void)
336 {
337     static unsigned int id;
338     return json_integer_create(id++);
339 }
340
341 struct jsonrpc_msg *
342 jsonrpc_create_request(const char *method, struct json *params)
343 {
344     return jsonrpc_create(JSONRPC_REQUEST, method, params, NULL, NULL,
345                            jsonrpc_create_id());
346 }
347
348 struct jsonrpc_msg *
349 jsonrpc_create_notify(const char *method, struct json *params)
350 {
351     return jsonrpc_create(JSONRPC_NOTIFY, method, params, NULL, NULL, NULL);
352 }
353
354 struct jsonrpc_msg *
355 jsonrpc_create_reply(struct json *result, const struct json *id)
356 {
357     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, result, NULL,
358                            json_clone(id));
359 }
360
361 struct jsonrpc_msg *
362 jsonrpc_create_error(struct json *error, const struct json *id)
363 {
364     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, NULL, error,
365                            json_clone(id));
366 }
367
368 const char *
369 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type)
370 {
371     switch (type) {
372     case JSONRPC_REQUEST:
373         return "request";
374
375     case JSONRPC_NOTIFY:
376         return "notification";
377
378     case JSONRPC_REPLY:
379         return "reply";
380
381     case JSONRPC_ERROR:
382         return "error";
383     }
384     return "(null)";
385 }
386
387 char *
388 jsonrpc_msg_is_valid(const struct jsonrpc_msg *m)
389 {
390     const char *type_name;
391     unsigned int pattern;
392
393     if (m->params && m->params->type != JSON_ARRAY) {
394         return xstrdup("\"params\" must be JSON array");
395     }
396
397     switch (m->type) {
398     case JSONRPC_REQUEST:
399         pattern = 0x11001;
400         break;
401
402     case JSONRPC_NOTIFY:
403         pattern = 0x11000;
404         break;
405
406     case JSONRPC_REPLY:
407         pattern = 0x00101;
408         break;
409
410     case JSONRPC_ERROR:
411         pattern = 0x00011;
412         break;
413
414     default:
415         return xasprintf("invalid JSON-RPC message type %d", m->type);
416     }
417
418     type_name = jsonrpc_msg_type_to_string(m->type);
419     if ((m->method != NULL) != ((pattern & 0x10000) != 0)) {
420         return xasprintf("%s must%s have \"method\"",
421                          type_name, (pattern & 0x10000) ? "" : " not");
422
423     }
424     if ((m->params != NULL) != ((pattern & 0x1000) != 0)) {
425         return xasprintf("%s must%s have \"params\"",
426                          type_name, (pattern & 0x1000) ? "" : " not");
427
428     }
429     if ((m->result != NULL) != ((pattern & 0x100) != 0)) {
430         return xasprintf("%s must%s have \"result\"",
431                          type_name, (pattern & 0x100) ? "" : " not");
432
433     }
434     if ((m->error != NULL) != ((pattern & 0x10) != 0)) {
435         return xasprintf("%s must%s have \"error\"",
436                          type_name, (pattern & 0x10) ? "" : " not");
437
438     }
439     if ((m->id != NULL) != ((pattern & 0x1) != 0)) {
440         return xasprintf("%s must%s have \"id\"",
441                          type_name, (pattern & 0x1) ? "" : " not");
442
443     }
444     return NULL;
445 }
446
447 void
448 jsonrpc_msg_destroy(struct jsonrpc_msg *m)
449 {
450     if (m) {
451         free(m->method);
452         json_destroy(m->params);
453         json_destroy(m->result);
454         json_destroy(m->error);
455         json_destroy(m->id);
456         free(m);
457     }
458 }
459
460 static struct json *
461 null_from_json_null(struct json *json)
462 {
463     if (json && json->type == JSON_NULL) {
464         json_destroy(json);
465         return NULL;
466     }
467     return json;
468 }
469
470 char *
471 jsonrpc_msg_from_json(struct json *json, struct jsonrpc_msg **msgp)
472 {
473     struct json *method = NULL;
474     struct jsonrpc_msg *msg = NULL;
475     struct shash *object;
476     char *error;
477
478     if (json->type != JSON_OBJECT) {
479         error = xstrdup("message is not a JSON object");
480         goto exit;
481     }
482     object = json_object(json);
483
484     method = shash_find_and_delete(object, "method");
485     if (method && method->type != JSON_STRING) {
486         error = xstrdup("method is not a JSON string");
487         goto exit;
488     }
489
490     msg = xzalloc(sizeof *msg);
491     msg->method = method ? xstrdup(method->u.string) : NULL;
492     msg->params = null_from_json_null(shash_find_and_delete(object, "params"));
493     msg->result = null_from_json_null(shash_find_and_delete(object, "result"));
494     msg->error = null_from_json_null(shash_find_and_delete(object, "error"));
495     msg->id = null_from_json_null(shash_find_and_delete(object, "id"));
496     msg->type = (msg->result ? JSONRPC_REPLY
497                  : msg->error ? JSONRPC_ERROR
498                  : msg->id ? JSONRPC_REQUEST
499                  : JSONRPC_NOTIFY);
500     if (!shash_is_empty(object)) {
501         error = xasprintf("message has unexpected member \"%s\"",
502                           shash_first(object)->name);
503         goto exit;
504     }
505     error = jsonrpc_msg_is_valid(msg);
506     if (error) {
507         goto exit;
508     }
509
510 exit:
511     json_destroy(method);
512     json_destroy(json);
513     if (error) {
514         jsonrpc_msg_destroy(msg);
515         msg = NULL;
516     }
517     *msgp = msg;
518     return error;
519 }
520
521 struct json *
522 jsonrpc_msg_to_json(struct jsonrpc_msg *m)
523 {
524     struct json *json = json_object_create();
525
526     if (m->method) {
527         json_object_put(json, "method", json_string_create_nocopy(m->method));
528     }
529
530     if (m->params) {
531         json_object_put(json, "params", m->params);
532     }
533
534     if (m->result) {
535         json_object_put(json, "result", m->result);
536     } else if (m->type == JSONRPC_ERROR) {
537         json_object_put(json, "result", json_null_create());
538     }
539
540     if (m->error) {
541         json_object_put(json, "error", m->error);
542     } else if (m->type == JSONRPC_REPLY) {
543         json_object_put(json, "error", json_null_create());
544     }
545
546     if (m->id) {
547         json_object_put(json, "id", m->id);
548     } else if (m->type == JSONRPC_NOTIFY) {
549         json_object_put(json, "id", json_null_create());
550     }
551
552     free(m);
553
554     return json;
555 }