ovsdb: Add new ovsdb-client program.
[sliver-openvswitch.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 int
265 jsonrpc_transact_block(struct jsonrpc *rpc, struct jsonrpc_msg *request,
266                        struct jsonrpc_msg **replyp)
267 {
268     struct jsonrpc_msg *reply = NULL;
269     struct json *id;
270     int error;
271
272     id = json_clone(request->id);
273     error = jsonrpc_send_block(rpc, request);
274     if (!error) {
275         for (;;) {
276             error = jsonrpc_recv_block(rpc, &reply);
277             if (error
278                 || (reply->type == JSONRPC_REPLY
279                     && json_equal(id, reply->id))) {
280                 break;
281             }
282             jsonrpc_msg_destroy(reply);
283         }
284     }
285     *replyp = error ? NULL : reply;
286     json_destroy(id);
287     return error;
288 }
289
290 static void
291 jsonrpc_received(struct jsonrpc *rpc)
292 {
293     struct jsonrpc_msg *msg;
294     struct json *json;
295     char *error;
296
297     json = json_parser_finish(rpc->parser);
298     rpc->parser = NULL;
299     if (json->type == JSON_STRING) {
300         VLOG_WARN_RL(&rl, "%s: error parsing stream: %s",
301                      rpc->name, json_string(json));
302         jsonrpc_error(rpc, EPROTO);
303         json_destroy(json);
304         return;
305     }
306
307     error = jsonrpc_msg_from_json(json, &msg);
308     if (error) {
309         VLOG_WARN_RL(&rl, "%s: received bad JSON-RPC message: %s",
310                      rpc->name, error);
311         free(error);
312         jsonrpc_error(rpc, EPROTO);
313         return;
314     }
315
316     rpc->received = msg;
317 }
318
319 void
320 jsonrpc_error(struct jsonrpc *rpc, int error)
321 {
322     assert(error);
323     if (!rpc->status) {
324         rpc->status = error;
325         jsonrpc_cleanup(rpc);
326     }
327 }
328
329 static void
330 jsonrpc_cleanup(struct jsonrpc *rpc)
331 {
332     stream_close(rpc->stream);
333     rpc->stream = NULL;
334
335     json_parser_abort(rpc->parser);
336     rpc->parser = NULL;
337
338     jsonrpc_msg_destroy(rpc->received);
339     rpc->received = NULL;
340
341     queue_clear(&rpc->output);
342     rpc->backlog = 0;
343 }
344 \f
345 static struct jsonrpc_msg *
346 jsonrpc_create(enum jsonrpc_msg_type type, const char *method,
347                 struct json *params, struct json *result, struct json *error,
348                 struct json *id)
349 {
350     struct jsonrpc_msg *msg = xmalloc(sizeof *msg);
351     msg->type = type;
352     msg->method = method ? xstrdup(method) : NULL;
353     msg->params = params;
354     msg->result = result;
355     msg->error = error;
356     msg->id = id;
357     return msg;
358 }
359
360 static struct json *
361 jsonrpc_create_id(void)
362 {
363     static unsigned int id;
364     return json_integer_create(id++);
365 }
366
367 struct jsonrpc_msg *
368 jsonrpc_create_request(const char *method, struct json *params)
369 {
370     return jsonrpc_create(JSONRPC_REQUEST, method, params, NULL, NULL,
371                            jsonrpc_create_id());
372 }
373
374 struct jsonrpc_msg *
375 jsonrpc_create_notify(const char *method, struct json *params)
376 {
377     return jsonrpc_create(JSONRPC_NOTIFY, method, params, NULL, NULL, NULL);
378 }
379
380 struct jsonrpc_msg *
381 jsonrpc_create_reply(struct json *result, const struct json *id)
382 {
383     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, result, NULL,
384                            json_clone(id));
385 }
386
387 struct jsonrpc_msg *
388 jsonrpc_create_error(struct json *error, const struct json *id)
389 {
390     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, NULL, error,
391                            json_clone(id));
392 }
393
394 const char *
395 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type)
396 {
397     switch (type) {
398     case JSONRPC_REQUEST:
399         return "request";
400
401     case JSONRPC_NOTIFY:
402         return "notification";
403
404     case JSONRPC_REPLY:
405         return "reply";
406
407     case JSONRPC_ERROR:
408         return "error";
409     }
410     return "(null)";
411 }
412
413 char *
414 jsonrpc_msg_is_valid(const struct jsonrpc_msg *m)
415 {
416     const char *type_name;
417     unsigned int pattern;
418
419     if (m->params && m->params->type != JSON_ARRAY) {
420         return xstrdup("\"params\" must be JSON array");
421     }
422
423     switch (m->type) {
424     case JSONRPC_REQUEST:
425         pattern = 0x11001;
426         break;
427
428     case JSONRPC_NOTIFY:
429         pattern = 0x11000;
430         break;
431
432     case JSONRPC_REPLY:
433         pattern = 0x00101;
434         break;
435
436     case JSONRPC_ERROR:
437         pattern = 0x00011;
438         break;
439
440     default:
441         return xasprintf("invalid JSON-RPC message type %d", m->type);
442     }
443
444     type_name = jsonrpc_msg_type_to_string(m->type);
445     if ((m->method != NULL) != ((pattern & 0x10000) != 0)) {
446         return xasprintf("%s must%s have \"method\"",
447                          type_name, (pattern & 0x10000) ? "" : " not");
448
449     }
450     if ((m->params != NULL) != ((pattern & 0x1000) != 0)) {
451         return xasprintf("%s must%s have \"params\"",
452                          type_name, (pattern & 0x1000) ? "" : " not");
453
454     }
455     if ((m->result != NULL) != ((pattern & 0x100) != 0)) {
456         return xasprintf("%s must%s have \"result\"",
457                          type_name, (pattern & 0x100) ? "" : " not");
458
459     }
460     if ((m->error != NULL) != ((pattern & 0x10) != 0)) {
461         return xasprintf("%s must%s have \"error\"",
462                          type_name, (pattern & 0x10) ? "" : " not");
463
464     }
465     if ((m->id != NULL) != ((pattern & 0x1) != 0)) {
466         return xasprintf("%s must%s have \"id\"",
467                          type_name, (pattern & 0x1) ? "" : " not");
468
469     }
470     return NULL;
471 }
472
473 void
474 jsonrpc_msg_destroy(struct jsonrpc_msg *m)
475 {
476     if (m) {
477         free(m->method);
478         json_destroy(m->params);
479         json_destroy(m->result);
480         json_destroy(m->error);
481         json_destroy(m->id);
482         free(m);
483     }
484 }
485
486 static struct json *
487 null_from_json_null(struct json *json)
488 {
489     if (json && json->type == JSON_NULL) {
490         json_destroy(json);
491         return NULL;
492     }
493     return json;
494 }
495
496 char *
497 jsonrpc_msg_from_json(struct json *json, struct jsonrpc_msg **msgp)
498 {
499     struct json *method = NULL;
500     struct jsonrpc_msg *msg = NULL;
501     struct shash *object;
502     char *error;
503
504     if (json->type != JSON_OBJECT) {
505         error = xstrdup("message is not a JSON object");
506         goto exit;
507     }
508     object = json_object(json);
509
510     method = shash_find_and_delete(object, "method");
511     if (method && method->type != JSON_STRING) {
512         error = xstrdup("method is not a JSON string");
513         goto exit;
514     }
515
516     msg = xzalloc(sizeof *msg);
517     msg->method = method ? xstrdup(method->u.string) : NULL;
518     msg->params = null_from_json_null(shash_find_and_delete(object, "params"));
519     msg->result = null_from_json_null(shash_find_and_delete(object, "result"));
520     msg->error = null_from_json_null(shash_find_and_delete(object, "error"));
521     msg->id = null_from_json_null(shash_find_and_delete(object, "id"));
522     msg->type = (msg->result ? JSONRPC_REPLY
523                  : msg->error ? JSONRPC_ERROR
524                  : msg->id ? JSONRPC_REQUEST
525                  : JSONRPC_NOTIFY);
526     if (!shash_is_empty(object)) {
527         error = xasprintf("message has unexpected member \"%s\"",
528                           shash_first(object)->name);
529         goto exit;
530     }
531     error = jsonrpc_msg_is_valid(msg);
532     if (error) {
533         goto exit;
534     }
535
536 exit:
537     json_destroy(method);
538     json_destroy(json);
539     if (error) {
540         jsonrpc_msg_destroy(msg);
541         msg = NULL;
542     }
543     *msgp = msg;
544     return error;
545 }
546
547 struct json *
548 jsonrpc_msg_to_json(struct jsonrpc_msg *m)
549 {
550     struct json *json = json_object_create();
551
552     if (m->method) {
553         json_object_put(json, "method", json_string_create_nocopy(m->method));
554     }
555
556     if (m->params) {
557         json_object_put(json, "params", m->params);
558     }
559
560     if (m->result) {
561         json_object_put(json, "result", m->result);
562     } else if (m->type == JSONRPC_ERROR) {
563         json_object_put(json, "result", json_null_create());
564     }
565
566     if (m->error) {
567         json_object_put(json, "error", m->error);
568     } else if (m->type == JSONRPC_REPLY) {
569         json_object_put(json, "error", json_null_create());
570     }
571
572     if (m->id) {
573         json_object_put(json, "id", m->id);
574     } else if (m->type == JSONRPC_NOTIFY) {
575         json_object_put(json, "id", json_null_create());
576     }
577
578     free(m);
579
580     return json;
581 }