jsonrpc: Make jsonrpc_error() internal.
[openvswitch] / lib / jsonrpc.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012 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 <assert.h>
22 #include <errno.h>
23
24 #include "byteq.h"
25 #include "dynamic-string.h"
26 #include "fatal-signal.h"
27 #include "json.h"
28 #include "list.h"
29 #include "ofpbuf.h"
30 #include "poll-loop.h"
31 #include "reconnect.h"
32 #include "stream.h"
33 #include "timeval.h"
34 #include "vlog.h"
35
36 VLOG_DEFINE_THIS_MODULE(jsonrpc);
37 \f
38 struct jsonrpc {
39     struct stream *stream;
40     char *name;
41     int status;
42
43     /* Input. */
44     struct byteq input;
45     struct json_parser *parser;
46     struct jsonrpc_msg *received;
47
48     /* Output. */
49     struct list output;         /* Contains "struct ofpbuf"s. */
50     size_t backlog;
51 };
52
53 /* Rate limit for error messages. */
54 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
55
56 static void jsonrpc_received(struct jsonrpc *);
57 static void jsonrpc_cleanup(struct jsonrpc *);
58 static void jsonrpc_error(struct jsonrpc *, int error);
59
60 /* This is just the same as stream_open() except that it uses the default
61  * JSONRPC ports if none is specified. */
62 int
63 jsonrpc_stream_open(const char *name, struct stream **streamp)
64 {
65     return stream_open_with_default_ports(name, JSONRPC_TCP_PORT,
66                                           JSONRPC_SSL_PORT, streamp);
67 }
68
69 /* This is just the same as pstream_open() except that it uses the default
70  * JSONRPC ports if none is specified. */
71 int
72 jsonrpc_pstream_open(const char *name, struct pstream **pstreamp)
73 {
74     return pstream_open_with_default_ports(name, JSONRPC_TCP_PORT,
75                                            JSONRPC_SSL_PORT, pstreamp);
76 }
77
78 struct jsonrpc *
79 jsonrpc_open(struct stream *stream)
80 {
81     struct jsonrpc *rpc;
82
83     assert(stream != NULL);
84
85     rpc = xzalloc(sizeof *rpc);
86     rpc->name = xstrdup(stream_get_name(stream));
87     rpc->stream = stream;
88     byteq_init(&rpc->input);
89     list_init(&rpc->output);
90
91     return rpc;
92 }
93
94 void
95 jsonrpc_close(struct jsonrpc *rpc)
96 {
97     if (rpc) {
98         jsonrpc_cleanup(rpc);
99         free(rpc->name);
100         free(rpc);
101     }
102 }
103
104 void
105 jsonrpc_run(struct jsonrpc *rpc)
106 {
107     if (rpc->status) {
108         return;
109     }
110
111     stream_run(rpc->stream);
112     while (!list_is_empty(&rpc->output)) {
113         struct ofpbuf *buf = ofpbuf_from_list(rpc->output.next);
114         int retval;
115
116         retval = stream_send(rpc->stream, buf->data, buf->size);
117         if (retval >= 0) {
118             rpc->backlog -= retval;
119             ofpbuf_pull(buf, retval);
120             if (!buf->size) {
121                 list_remove(&buf->list_node);
122                 ofpbuf_delete(buf);
123             }
124         } else {
125             if (retval != -EAGAIN) {
126                 VLOG_WARN_RL(&rl, "%s: send error: %s",
127                              rpc->name, strerror(-retval));
128                 jsonrpc_error(rpc, -retval);
129             }
130             break;
131         }
132     }
133 }
134
135 void
136 jsonrpc_wait(struct jsonrpc *rpc)
137 {
138     if (!rpc->status) {
139         stream_run_wait(rpc->stream);
140         if (!list_is_empty(&rpc->output)) {
141             stream_send_wait(rpc->stream);
142         }
143     }
144 }
145
146 /*
147  * Possible status values:
148  * - 0: no error yet
149  * - >0: errno value
150  * - EOF: end of file (remote end closed connection; not necessarily an error)
151  */
152 int
153 jsonrpc_get_status(const struct jsonrpc *rpc)
154 {
155     return rpc->status;
156 }
157
158 size_t
159 jsonrpc_get_backlog(const struct jsonrpc *rpc)
160 {
161     return rpc->status ? 0 : rpc->backlog;
162 }
163
164 const char *
165 jsonrpc_get_name(const struct jsonrpc *rpc)
166 {
167     return rpc->name;
168 }
169
170 static void
171 jsonrpc_log_msg(const struct jsonrpc *rpc, const char *title,
172                 const struct jsonrpc_msg *msg)
173 {
174     if (VLOG_IS_DBG_ENABLED()) {
175         struct ds s = DS_EMPTY_INITIALIZER;
176         if (msg->method) {
177             ds_put_format(&s, ", method=\"%s\"", msg->method);
178         }
179         if (msg->params) {
180             ds_put_cstr(&s, ", params=");
181             json_to_ds(msg->params, 0, &s);
182         }
183         if (msg->result) {
184             ds_put_cstr(&s, ", result=");
185             json_to_ds(msg->result, 0, &s);
186         }
187         if (msg->error) {
188             ds_put_cstr(&s, ", error=");
189             json_to_ds(msg->error, 0, &s);
190         }
191         if (msg->id) {
192             ds_put_cstr(&s, ", id=");
193             json_to_ds(msg->id, 0, &s);
194         }
195         VLOG_DBG("%s: %s %s%s", rpc->name, title,
196                  jsonrpc_msg_type_to_string(msg->type), ds_cstr(&s));
197         ds_destroy(&s);
198     }
199 }
200
201 /* Always takes ownership of 'msg', regardless of success. */
202 int
203 jsonrpc_send(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
204 {
205     struct ofpbuf *buf;
206     struct json *json;
207     size_t length;
208     char *s;
209
210     if (rpc->status) {
211         jsonrpc_msg_destroy(msg);
212         return rpc->status;
213     }
214
215     jsonrpc_log_msg(rpc, "send", msg);
216
217     json = jsonrpc_msg_to_json(msg);
218     s = json_to_string(json, 0);
219     length = strlen(s);
220     json_destroy(json);
221
222     buf = xmalloc(sizeof *buf);
223     ofpbuf_use(buf, s, length);
224     buf->size = length;
225     list_push_back(&rpc->output, &buf->list_node);
226     rpc->backlog += length;
227
228     if (rpc->backlog == length) {
229         jsonrpc_run(rpc);
230     }
231     return rpc->status;
232 }
233
234 int
235 jsonrpc_recv(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
236 {
237     *msgp = NULL;
238     if (rpc->status) {
239         return rpc->status;
240     }
241
242     while (!rpc->received) {
243         if (byteq_is_empty(&rpc->input)) {
244             size_t chunk;
245             int retval;
246
247             chunk = byteq_headroom(&rpc->input);
248             retval = stream_recv(rpc->stream, byteq_head(&rpc->input), chunk);
249             if (retval < 0) {
250                 if (retval == -EAGAIN) {
251                     return EAGAIN;
252                 } else {
253                     VLOG_WARN_RL(&rl, "%s: receive error: %s",
254                                  rpc->name, strerror(-retval));
255                     jsonrpc_error(rpc, -retval);
256                     return rpc->status;
257                 }
258             } else if (retval == 0) {
259                 jsonrpc_error(rpc, EOF);
260                 return EOF;
261             }
262             byteq_advance_head(&rpc->input, retval);
263         } else {
264             size_t n, used;
265
266             if (!rpc->parser) {
267                 rpc->parser = json_parser_create(0);
268             }
269             n = byteq_tailroom(&rpc->input);
270             used = json_parser_feed(rpc->parser,
271                                     (char *) byteq_tail(&rpc->input), n);
272             byteq_advance_tail(&rpc->input, used);
273             if (json_parser_is_done(rpc->parser)) {
274                 jsonrpc_received(rpc);
275                 if (rpc->status) {
276                     const struct byteq *q = &rpc->input;
277                     if (q->head <= BYTEQ_SIZE) {
278                         stream_report_content(q->buffer, q->head,
279                                               STREAM_JSONRPC,
280                                               THIS_MODULE, rpc->name);
281                     }
282                     return rpc->status;
283                 }
284             }
285         }
286     }
287
288     *msgp = rpc->received;
289     rpc->received = NULL;
290     return 0;
291 }
292
293 void
294 jsonrpc_recv_wait(struct jsonrpc *rpc)
295 {
296     if (rpc->status || rpc->received || !byteq_is_empty(&rpc->input)) {
297         (poll_immediate_wake)(rpc->name);
298     } else {
299         stream_recv_wait(rpc->stream);
300     }
301 }
302
303 /* Always takes ownership of 'msg', regardless of success. */
304 int
305 jsonrpc_send_block(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
306 {
307     int error;
308
309     fatal_signal_run();
310
311     error = jsonrpc_send(rpc, msg);
312     if (error) {
313         return error;
314     }
315
316     for (;;) {
317         jsonrpc_run(rpc);
318         if (list_is_empty(&rpc->output) || rpc->status) {
319             return rpc->status;
320         }
321         jsonrpc_wait(rpc);
322         poll_block();
323     }
324 }
325
326 int
327 jsonrpc_recv_block(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
328 {
329     for (;;) {
330         int error = jsonrpc_recv(rpc, msgp);
331         if (error != EAGAIN) {
332             fatal_signal_run();
333             return error;
334         }
335
336         jsonrpc_run(rpc);
337         jsonrpc_wait(rpc);
338         jsonrpc_recv_wait(rpc);
339         poll_block();
340     }
341 }
342
343 /* Always takes ownership of 'request', regardless of success. */
344 int
345 jsonrpc_transact_block(struct jsonrpc *rpc, struct jsonrpc_msg *request,
346                        struct jsonrpc_msg **replyp)
347 {
348     struct jsonrpc_msg *reply = NULL;
349     struct json *id;
350     int error;
351
352     id = json_clone(request->id);
353     error = jsonrpc_send_block(rpc, request);
354     if (!error) {
355         for (;;) {
356             error = jsonrpc_recv_block(rpc, &reply);
357             if (error
358                 || (reply->type == JSONRPC_REPLY
359                     && json_equal(id, reply->id))) {
360                 break;
361             }
362             jsonrpc_msg_destroy(reply);
363         }
364     }
365     *replyp = error ? NULL : reply;
366     json_destroy(id);
367     return error;
368 }
369
370 static void
371 jsonrpc_received(struct jsonrpc *rpc)
372 {
373     struct jsonrpc_msg *msg;
374     struct json *json;
375     char *error;
376
377     json = json_parser_finish(rpc->parser);
378     rpc->parser = NULL;
379     if (json->type == JSON_STRING) {
380         VLOG_WARN_RL(&rl, "%s: error parsing stream: %s",
381                      rpc->name, json_string(json));
382         jsonrpc_error(rpc, EPROTO);
383         json_destroy(json);
384         return;
385     }
386
387     error = jsonrpc_msg_from_json(json, &msg);
388     if (error) {
389         VLOG_WARN_RL(&rl, "%s: received bad JSON-RPC message: %s",
390                      rpc->name, error);
391         free(error);
392         jsonrpc_error(rpc, EPROTO);
393         return;
394     }
395
396     jsonrpc_log_msg(rpc, "received", msg);
397     rpc->received = msg;
398 }
399
400 static void
401 jsonrpc_error(struct jsonrpc *rpc, int error)
402 {
403     assert(error);
404     if (!rpc->status) {
405         rpc->status = error;
406         jsonrpc_cleanup(rpc);
407     }
408 }
409
410 static void
411 jsonrpc_cleanup(struct jsonrpc *rpc)
412 {
413     stream_close(rpc->stream);
414     rpc->stream = NULL;
415
416     json_parser_abort(rpc->parser);
417     rpc->parser = NULL;
418
419     jsonrpc_msg_destroy(rpc->received);
420     rpc->received = NULL;
421
422     ofpbuf_list_delete(&rpc->output);
423     rpc->backlog = 0;
424 }
425 \f
426 static struct jsonrpc_msg *
427 jsonrpc_create(enum jsonrpc_msg_type type, const char *method,
428                 struct json *params, struct json *result, struct json *error,
429                 struct json *id)
430 {
431     struct jsonrpc_msg *msg = xmalloc(sizeof *msg);
432     msg->type = type;
433     msg->method = method ? xstrdup(method) : NULL;
434     msg->params = params;
435     msg->result = result;
436     msg->error = error;
437     msg->id = id;
438     return msg;
439 }
440
441 static struct json *
442 jsonrpc_create_id(void)
443 {
444     static unsigned int id;
445     return json_integer_create(id++);
446 }
447
448 struct jsonrpc_msg *
449 jsonrpc_create_request(const char *method, struct json *params,
450                        struct json **idp)
451 {
452     struct json *id = jsonrpc_create_id();
453     if (idp) {
454         *idp = json_clone(id);
455     }
456     return jsonrpc_create(JSONRPC_REQUEST, method, params, NULL, NULL, id);
457 }
458
459 struct jsonrpc_msg *
460 jsonrpc_create_notify(const char *method, struct json *params)
461 {
462     return jsonrpc_create(JSONRPC_NOTIFY, method, params, NULL, NULL, NULL);
463 }
464
465 struct jsonrpc_msg *
466 jsonrpc_create_reply(struct json *result, const struct json *id)
467 {
468     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, result, NULL,
469                            json_clone(id));
470 }
471
472 struct jsonrpc_msg *
473 jsonrpc_create_error(struct json *error, const struct json *id)
474 {
475     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, NULL, error,
476                            json_clone(id));
477 }
478
479 const char *
480 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type)
481 {
482     switch (type) {
483     case JSONRPC_REQUEST:
484         return "request";
485
486     case JSONRPC_NOTIFY:
487         return "notification";
488
489     case JSONRPC_REPLY:
490         return "reply";
491
492     case JSONRPC_ERROR:
493         return "error";
494     }
495     return "(null)";
496 }
497
498 char *
499 jsonrpc_msg_is_valid(const struct jsonrpc_msg *m)
500 {
501     const char *type_name;
502     unsigned int pattern;
503
504     if (m->params && m->params->type != JSON_ARRAY) {
505         return xstrdup("\"params\" must be JSON array");
506     }
507
508     switch (m->type) {
509     case JSONRPC_REQUEST:
510         pattern = 0x11001;
511         break;
512
513     case JSONRPC_NOTIFY:
514         pattern = 0x11000;
515         break;
516
517     case JSONRPC_REPLY:
518         pattern = 0x00101;
519         break;
520
521     case JSONRPC_ERROR:
522         pattern = 0x00011;
523         break;
524
525     default:
526         return xasprintf("invalid JSON-RPC message type %d", m->type);
527     }
528
529     type_name = jsonrpc_msg_type_to_string(m->type);
530     if ((m->method != NULL) != ((pattern & 0x10000) != 0)) {
531         return xasprintf("%s must%s have \"method\"",
532                          type_name, (pattern & 0x10000) ? "" : " not");
533
534     }
535     if ((m->params != NULL) != ((pattern & 0x1000) != 0)) {
536         return xasprintf("%s must%s have \"params\"",
537                          type_name, (pattern & 0x1000) ? "" : " not");
538
539     }
540     if ((m->result != NULL) != ((pattern & 0x100) != 0)) {
541         return xasprintf("%s must%s have \"result\"",
542                          type_name, (pattern & 0x100) ? "" : " not");
543
544     }
545     if ((m->error != NULL) != ((pattern & 0x10) != 0)) {
546         return xasprintf("%s must%s have \"error\"",
547                          type_name, (pattern & 0x10) ? "" : " not");
548
549     }
550     if ((m->id != NULL) != ((pattern & 0x1) != 0)) {
551         return xasprintf("%s must%s have \"id\"",
552                          type_name, (pattern & 0x1) ? "" : " not");
553
554     }
555     return NULL;
556 }
557
558 void
559 jsonrpc_msg_destroy(struct jsonrpc_msg *m)
560 {
561     if (m) {
562         free(m->method);
563         json_destroy(m->params);
564         json_destroy(m->result);
565         json_destroy(m->error);
566         json_destroy(m->id);
567         free(m);
568     }
569 }
570
571 static struct json *
572 null_from_json_null(struct json *json)
573 {
574     if (json && json->type == JSON_NULL) {
575         json_destroy(json);
576         return NULL;
577     }
578     return json;
579 }
580
581 char *
582 jsonrpc_msg_from_json(struct json *json, struct jsonrpc_msg **msgp)
583 {
584     struct json *method = NULL;
585     struct jsonrpc_msg *msg = NULL;
586     struct shash *object;
587     char *error;
588
589     if (json->type != JSON_OBJECT) {
590         error = xstrdup("message is not a JSON object");
591         goto exit;
592     }
593     object = json_object(json);
594
595     method = shash_find_and_delete(object, "method");
596     if (method && method->type != JSON_STRING) {
597         error = xstrdup("method is not a JSON string");
598         goto exit;
599     }
600
601     msg = xzalloc(sizeof *msg);
602     msg->method = method ? xstrdup(method->u.string) : NULL;
603     msg->params = null_from_json_null(shash_find_and_delete(object, "params"));
604     msg->result = null_from_json_null(shash_find_and_delete(object, "result"));
605     msg->error = null_from_json_null(shash_find_and_delete(object, "error"));
606     msg->id = null_from_json_null(shash_find_and_delete(object, "id"));
607     msg->type = (msg->result ? JSONRPC_REPLY
608                  : msg->error ? JSONRPC_ERROR
609                  : msg->id ? JSONRPC_REQUEST
610                  : JSONRPC_NOTIFY);
611     if (!shash_is_empty(object)) {
612         error = xasprintf("message has unexpected member \"%s\"",
613                           shash_first(object)->name);
614         goto exit;
615     }
616     error = jsonrpc_msg_is_valid(msg);
617     if (error) {
618         goto exit;
619     }
620
621 exit:
622     json_destroy(method);
623     json_destroy(json);
624     if (error) {
625         jsonrpc_msg_destroy(msg);
626         msg = NULL;
627     }
628     *msgp = msg;
629     return error;
630 }
631
632 struct json *
633 jsonrpc_msg_to_json(struct jsonrpc_msg *m)
634 {
635     struct json *json = json_object_create();
636
637     if (m->method) {
638         json_object_put(json, "method", json_string_create_nocopy(m->method));
639     }
640
641     if (m->params) {
642         json_object_put(json, "params", m->params);
643     }
644
645     if (m->result) {
646         json_object_put(json, "result", m->result);
647     } else if (m->type == JSONRPC_ERROR) {
648         json_object_put(json, "result", json_null_create());
649     }
650
651     if (m->error) {
652         json_object_put(json, "error", m->error);
653     } else if (m->type == JSONRPC_REPLY) {
654         json_object_put(json, "error", json_null_create());
655     }
656
657     if (m->id) {
658         json_object_put(json, "id", m->id);
659     } else if (m->type == JSONRPC_NOTIFY) {
660         json_object_put(json, "id", json_null_create());
661     }
662
663     free(m);
664
665     return json;
666 }
667 \f
668 /* A JSON-RPC session with reconnection. */
669
670 struct jsonrpc_session {
671     struct reconnect *reconnect;
672     struct jsonrpc *rpc;
673     struct stream *stream;
674     struct pstream *pstream;
675     unsigned int seqno;
676 };
677
678 /* Creates and returns a jsonrpc_session to 'name', which should be a string
679  * acceptable to stream_open() or pstream_open().
680  *
681  * If 'name' is an active connection method, e.g. "tcp:127.1.2.3", the new
682  * jsonrpc_session connects and reconnects, with back-off, to 'name'.
683  *
684  * If 'name' is a passive connection method, e.g. "ptcp:", the new
685  * jsonrpc_session listens for connections to 'name'.  It maintains at most one
686  * connection at any given time.  Any new connection causes the previous one
687  * (if any) to be dropped. */
688 struct jsonrpc_session *
689 jsonrpc_session_open(const char *name)
690 {
691     struct jsonrpc_session *s;
692
693     s = xmalloc(sizeof *s);
694     s->reconnect = reconnect_create(time_msec());
695     reconnect_set_name(s->reconnect, name);
696     reconnect_enable(s->reconnect, time_msec());
697     s->rpc = NULL;
698     s->stream = NULL;
699     s->pstream = NULL;
700     s->seqno = 0;
701
702     if (!pstream_verify_name(name)) {
703         reconnect_set_passive(s->reconnect, true, time_msec());
704     }
705
706     return s;
707 }
708
709 /* Creates and returns a jsonrpc_session that is initially connected to
710  * 'jsonrpc'.  If the connection is dropped, it will not be reconnected.
711  *
712  * On the assumption that such connections are likely to be short-lived
713  * (e.g. from ovs-vsctl), informational logging for them is suppressed. */
714 struct jsonrpc_session *
715 jsonrpc_session_open_unreliably(struct jsonrpc *jsonrpc)
716 {
717     struct jsonrpc_session *s;
718
719     s = xmalloc(sizeof *s);
720     s->reconnect = reconnect_create(time_msec());
721     reconnect_set_quiet(s->reconnect, true);
722     reconnect_set_name(s->reconnect, jsonrpc_get_name(jsonrpc));
723     reconnect_set_max_tries(s->reconnect, 0);
724     reconnect_connected(s->reconnect, time_msec());
725     s->rpc = jsonrpc;
726     s->stream = NULL;
727     s->pstream = NULL;
728     s->seqno = 0;
729
730     return s;
731 }
732
733 void
734 jsonrpc_session_close(struct jsonrpc_session *s)
735 {
736     if (s) {
737         jsonrpc_close(s->rpc);
738         reconnect_destroy(s->reconnect);
739         stream_close(s->stream);
740         pstream_close(s->pstream);
741         free(s);
742     }
743 }
744
745 static void
746 jsonrpc_session_disconnect(struct jsonrpc_session *s)
747 {
748     if (s->rpc) {
749         jsonrpc_error(s->rpc, EOF);
750         jsonrpc_close(s->rpc);
751         s->rpc = NULL;
752         s->seqno++;
753     } else if (s->stream) {
754         stream_close(s->stream);
755         s->stream = NULL;
756         s->seqno++;
757     }
758 }
759
760 static void
761 jsonrpc_session_connect(struct jsonrpc_session *s)
762 {
763     const char *name = reconnect_get_name(s->reconnect);
764     int error;
765
766     jsonrpc_session_disconnect(s);
767     if (!reconnect_is_passive(s->reconnect)) {
768         error = jsonrpc_stream_open(name, &s->stream);
769         if (!error) {
770             reconnect_connecting(s->reconnect, time_msec());
771         }
772     } else {
773         error = s->pstream ? 0 : jsonrpc_pstream_open(name, &s->pstream);
774         if (!error) {
775             reconnect_listening(s->reconnect, time_msec());
776         }
777     }
778
779     if (error) {
780         reconnect_connect_failed(s->reconnect, time_msec(), error);
781     }
782     s->seqno++;
783 }
784
785 void
786 jsonrpc_session_run(struct jsonrpc_session *s)
787 {
788     if (s->pstream) {
789         struct stream *stream;
790         int error;
791
792         error = pstream_accept(s->pstream, &stream);
793         if (!error) {
794             if (s->rpc || s->stream) {
795                 VLOG_INFO_RL(&rl,
796                              "%s: new connection replacing active connection",
797                              reconnect_get_name(s->reconnect));
798                 jsonrpc_session_disconnect(s);
799             }
800             reconnect_connected(s->reconnect, time_msec());
801             s->rpc = jsonrpc_open(stream);
802         } else if (error != EAGAIN) {
803             reconnect_listen_error(s->reconnect, time_msec(), error);
804             pstream_close(s->pstream);
805             s->pstream = NULL;
806         }
807     }
808
809     if (s->rpc) {
810         int error;
811
812         jsonrpc_run(s->rpc);
813         error = jsonrpc_get_status(s->rpc);
814         if (error) {
815             reconnect_disconnected(s->reconnect, time_msec(), error);
816             jsonrpc_session_disconnect(s);
817         }
818     } else if (s->stream) {
819         int error;
820
821         stream_run(s->stream);
822         error = stream_connect(s->stream);
823         if (!error) {
824             reconnect_connected(s->reconnect, time_msec());
825             s->rpc = jsonrpc_open(s->stream);
826             s->stream = NULL;
827         } else if (error != EAGAIN) {
828             reconnect_connect_failed(s->reconnect, time_msec(), error);
829             stream_close(s->stream);
830             s->stream = NULL;
831         }
832     }
833
834     switch (reconnect_run(s->reconnect, time_msec())) {
835     case RECONNECT_CONNECT:
836         jsonrpc_session_connect(s);
837         break;
838
839     case RECONNECT_DISCONNECT:
840         reconnect_disconnected(s->reconnect, time_msec(), 0);
841         jsonrpc_session_disconnect(s);
842         break;
843
844     case RECONNECT_PROBE:
845         if (s->rpc) {
846             struct json *params;
847             struct jsonrpc_msg *request;
848
849             params = json_array_create_empty();
850             request = jsonrpc_create_request("echo", params, NULL);
851             json_destroy(request->id);
852             request->id = json_string_create("echo");
853             jsonrpc_send(s->rpc, request);
854         }
855         break;
856     }
857 }
858
859 void
860 jsonrpc_session_wait(struct jsonrpc_session *s)
861 {
862     if (s->rpc) {
863         jsonrpc_wait(s->rpc);
864     } else if (s->stream) {
865         stream_run_wait(s->stream);
866         stream_connect_wait(s->stream);
867     }
868     if (s->pstream) {
869         pstream_wait(s->pstream);
870     }
871     reconnect_wait(s->reconnect, time_msec());
872 }
873
874 size_t
875 jsonrpc_session_get_backlog(const struct jsonrpc_session *s)
876 {
877     return s->rpc ? jsonrpc_get_backlog(s->rpc) : 0;
878 }
879
880 /* Always returns a pointer to a valid C string, assuming 's' was initialized
881  * correctly. */
882 const char *
883 jsonrpc_session_get_name(const struct jsonrpc_session *s)
884 {
885     return reconnect_get_name(s->reconnect);
886 }
887
888 /* Always takes ownership of 'msg', regardless of success. */
889 int
890 jsonrpc_session_send(struct jsonrpc_session *s, struct jsonrpc_msg *msg)
891 {
892     if (s->rpc) {
893         return jsonrpc_send(s->rpc, msg);
894     } else {
895         jsonrpc_msg_destroy(msg);
896         return ENOTCONN;
897     }
898 }
899
900 struct jsonrpc_msg *
901 jsonrpc_session_recv(struct jsonrpc_session *s)
902 {
903     if (s->rpc) {
904         struct jsonrpc_msg *msg;
905         jsonrpc_recv(s->rpc, &msg);
906         if (msg) {
907             reconnect_received(s->reconnect, time_msec());
908             if (msg->type == JSONRPC_REQUEST && !strcmp(msg->method, "echo")) {
909                 /* Echo request.  Send reply. */
910                 struct jsonrpc_msg *reply;
911
912                 reply = jsonrpc_create_reply(json_clone(msg->params), msg->id);
913                 jsonrpc_session_send(s, reply);
914             } else if (msg->type == JSONRPC_REPLY
915                        && msg->id && msg->id->type == JSON_STRING
916                        && !strcmp(msg->id->u.string, "echo")) {
917                 /* It's a reply to our echo request.  Suppress it. */
918             } else {
919                 return msg;
920             }
921             jsonrpc_msg_destroy(msg);
922         }
923     }
924     return NULL;
925 }
926
927 void
928 jsonrpc_session_recv_wait(struct jsonrpc_session *s)
929 {
930     if (s->rpc) {
931         jsonrpc_recv_wait(s->rpc);
932     }
933 }
934
935 bool
936 jsonrpc_session_is_alive(const struct jsonrpc_session *s)
937 {
938     return s->rpc || s->stream || reconnect_get_max_tries(s->reconnect);
939 }
940
941 bool
942 jsonrpc_session_is_connected(const struct jsonrpc_session *s)
943 {
944     return s->rpc != NULL;
945 }
946
947 unsigned int
948 jsonrpc_session_get_seqno(const struct jsonrpc_session *s)
949 {
950     return s->seqno;
951 }
952
953 int
954 jsonrpc_session_get_status(const struct jsonrpc_session *s)
955 {
956     return s && s->rpc ? jsonrpc_get_status(s->rpc) : 0;
957 }
958
959 void
960 jsonrpc_session_get_reconnect_stats(const struct jsonrpc_session *s,
961                                     struct reconnect_stats *stats)
962 {
963     reconnect_get_stats(s->reconnect, time_msec(), stats);
964 }
965
966 void
967 jsonrpc_session_force_reconnect(struct jsonrpc_session *s)
968 {
969     reconnect_force_reconnect(s->reconnect, time_msec());
970 }
971
972 void
973 jsonrpc_session_set_max_backoff(struct jsonrpc_session *s, int max_backoff)
974 {
975     reconnect_set_backoff(s->reconnect, 0, max_backoff);
976 }
977
978 void
979 jsonrpc_session_set_probe_interval(struct jsonrpc_session *s,
980                                    int probe_interval)
981 {
982     reconnect_set_probe_interval(s->reconnect, probe_interval);
983 }