| 1185 | } |
| 1186 | |
| 1187 | static struct io_plan *read_json(struct io_conn *conn, |
| 1188 | struct json_connection *jcon) |
| 1189 | { |
| 1190 | bool in_transaction = false; |
| 1191 | struct timemono start_time = time_mono(); |
| 1192 | size_t len_read; |
| 1193 | const jsmntok_t *toks; |
| 1194 | const char *buffer, *error; |
| 1195 | size_t num_parsed = 0; |
| 1196 | const char *last_method = NULL; |
| 1197 | u64 msec; |
| 1198 | |
| 1199 | buffer = jsonrpc_newly_read(jcon->json_in, &len_read); |
| 1200 | if (len_read) |
| 1201 | log_io(jcon->log, LOG_IO_IN, NULL, "", buffer, len_read); |
| 1202 | |
| 1203 | /* We wait for pending output to be consumed, to avoid DoS */ |
| 1204 | if (!list_empty(&jcon->jsouts)) { |
| 1205 | return io_wait(conn, conn, read_json, jcon); |
| 1206 | } |
| 1207 | |
| 1208 | again: |
| 1209 | error = jsonrpc_io_parse(tmpctx, jcon->json_in, &toks, &buffer); |
| 1210 | if (error) { |
| 1211 | json_command_malformed(jcon, "null", error); |
| 1212 | if (in_transaction) |
| 1213 | db_commit_transaction(jcon->ld->wallet->db); |
| 1214 | return io_halfclose(conn); |
| 1215 | } |
| 1216 | |
| 1217 | if (!toks) |
| 1218 | goto read_more; |
| 1219 | |
| 1220 | if (!in_transaction) { |
| 1221 | db_begin_transaction(jcon->ld->wallet->db); |
| 1222 | in_transaction = true; |
| 1223 | } |
| 1224 | parse_request(jcon, buffer, toks, &last_method); |
| 1225 | jsonrpc_io_parse_done(jcon->json_in); |
| 1226 | |
| 1227 | /* Don't ever process for more than 100 commands or 250 msec |
| 1228 | * without giving others a chance */ |
| 1229 | msec = time_to_msec(timemono_between(time_mono(), start_time)); |
| 1230 | if (num_parsed++ == 100 || msec > 250) { |
| 1231 | static bool printed_once = false; |
| 1232 | db_commit_transaction(jcon->ld->wallet->db); |
| 1233 | log_debug(jcon->log, "Pausing parsing after %zu requests and %"PRIu64"msec (last method=%s)", |
| 1234 | num_parsed, |
| 1235 | msec, |
| 1236 | last_method ? last_method : "NONE"); |
| 1237 | if (msec > 5000 && last_method && !printed_once) { |
| 1238 | log_unusual(jcon->log, |
| 1239 | CI_UNEXPECTED "Request %s took %"PRIu64" milliseconds", |
| 1240 | last_method, msec); |
| 1241 | printed_once = true; |
| 1242 | } |
| 1243 | /* Call us back, as if we read nothing new */ |
| 1244 | return io_always(conn, read_json, jcon); |
no test coverage detected