static json_t *read_json_pdu(w_jbuffer_t *jr, w_stm_t stm, json_error_t *jerr) { char *nl; int r; json_t *res; /* look for a newline; that indicates the end of * a json packet */ nl = memchr(jr->buf + jr->rpos, '\n', jr->wpos - jr->rpos); // If we don't have a newline, we need to fill the // buffer while (!nl) { if (!fill_buffer(jr, stm)) { if (errno == 0 && stm == w_stm_stdin()) { // Ugly-ish hack to support the -j CLI option. This allows // us to consume a JSON input that doesn't end with a newline. // We only allow this on EOF when reading from stdin nl = jr->buf + jr->wpos; break; } return NULL; } nl = memchr(jr->buf + jr->rpos, '\n', jr->wpos - jr->rpos); } // buflen r = (int)(nl - (jr->buf + jr->rpos)); res = json_loadb(jr->buf + jr->rpos, r, 0, jerr); // update read pos to look beyond this point jr->rpos += r + 1; return res; }
static bool read_and_detect_pdu(w_jbuffer_t *jr, w_stm_t stm, json_error_t *jerr) { enum w_pdu_type pdu; shunt_down(jr); pdu = detect_pdu(jr); if (pdu == need_data) { if (!fill_buffer(jr, stm)) { if (errno != EAGAIN) { snprintf(jerr->text, sizeof(jerr->text), "fill_buffer: %s", errno ? strerror(errno) : "EOF"); } return false; } pdu = detect_pdu(jr); } if (pdu == is_json_compact && stm == w_stm_stdin()) { // Minor hack for the `-j` option for reading pretty printed // json from stdin pdu = is_json_pretty; } jr->pdu_type = pdu; return true; }
static json_t *build_command(int argc, char **argv) { json_t *cmd; int i; // Read blob from stdin if (json_input_arg) { json_error_t err; w_jbuffer_t buf; memset(&err, 0, sizeof(err)); w_json_buffer_init(&buf); cmd = w_json_buffer_next(&buf, w_stm_stdin(), &err); if (buf.pdu_type == is_bser) { // If they used bser for the input, select bser for output // unless they explicitly requested something else if (!server_encoding) { server_pdu = is_bser; } if (!output_encoding) { output_pdu = is_bser; } } else if (buf.pdu_type == is_bser_v2) { // If they used bser v2 for the input, select bser v2 for output // unless they explicitly requested something else if (!server_encoding) { server_pdu = is_bser_v2; } if (!output_encoding) { output_pdu = is_bser_v2; } } w_json_buffer_free(&buf); if (cmd == NULL) { fprintf(stderr, "failed to parse command from stdin: %s\n", err.text); exit(1); } return cmd; } // Special case: no arguments means that we just want // to verify that the service is up, starting it if // needed if (argc == 0) { return NULL; } cmd = json_array(); for (i = 0; i < argc; i++) { json_array_append_new(cmd, json_string(argv[i])); } return cmd; }