char *make_in_op_value(json_t *avu, baton_error_t *error) { json_t *op_value = NULL; init_baton_error(error); json_t *valarray = get_json_value(avu, "value", JSON_VALUE_KEY, JSON_VALUE_SHORT_KEY, error); if (error->code != 0) goto error; if (!json_is_array(valarray)) { set_baton_error(error, CAT_INVALID_ARGUMENT, "Invalid 'value' attribute: not a JSON array " "(required for `in` condition)"); goto error; } json_t *prev_value; // Open paren op_value = json_string("("); size_t index; json_t *value; json_array_foreach(valarray, index, value) { if (!json_is_string(value)) { set_baton_error(error, CAT_INVALID_ARGUMENT, "Invalid AVU value: not a JSON string " "in item %d of `in` array", index); goto error; } prev_value = op_value; json_t *tmp; if (index == 0) { tmp = json_pack("s+++", json_string_value(prev_value), "'", json_string_value(value), "'"); } else { tmp = json_pack("s+++", json_string_value(prev_value), ", '", json_string_value(value), "'"); } if (tmp) { op_value = tmp; json_decref(prev_value); } } // Close paren prev_value = op_value; json_t *tmp = json_pack("s+", json_string_value(op_value), ")"); if (tmp) { op_value = tmp; json_decref(prev_value); } logmsg(DEBUG, "Using IN value of %s", json_string_value(op_value)); char *copy = copy_str(json_string_value(op_value), MAX_STR_LEN); json_decref(op_value); return copy; error: if (op_value) json_decref(op_value); return NULL; }
int bgp_peer_log_msg(struct bgp_node *route, struct bgp_info *ri, safi_t safi, char *event_type, int output) { char log_rk[SRVBUFLEN]; struct bgp_peer *peer = ri->peer; struct bgp_attr *attr = ri->attr; int ret = 0, amqp_ret = 0, etype = BGP_LOGDUMP_ET_NONE; if (!strcmp(event_type, "dump")) etype = BGP_LOGDUMP_ET_DUMP; else if (!strcmp(event_type, "log")) etype = BGP_LOGDUMP_ET_LOG; #ifdef WITH_RABBITMQ if ((config.nfacctd_bgp_msglog_amqp_routing_key && etype == BGP_LOGDUMP_ET_LOG) || (config.bgp_table_dump_amqp_routing_key && etype == BGP_LOGDUMP_ET_DUMP)) p_amqp_set_routing_key(peer->log->amqp_host, peer->log->filename); #endif if (output == PRINT_OUTPUT_JSON) { #ifdef WITH_JANSSON char ip_address[INET6_ADDRSTRLEN]; json_t *obj = json_object(), *kv; char empty[] = ""; char prefix_str[INET6_ADDRSTRLEN], nexthop_str[INET6_ADDRSTRLEN]; char *aspath; /* no need for seq and timestamp for "dump" event_type */ if (etype == BGP_LOGDUMP_ET_LOG) { kv = json_pack("{sI}", "seq", log_seq); json_object_update_missing(obj, kv); json_decref(kv); bgp_peer_log_seq_increment(&log_seq); kv = json_pack("{ss}", "timestamp", log_tstamp_str); json_object_update_missing(obj, kv); json_decref(kv); } addr_to_str(ip_address, &peer->addr); kv = json_pack("{ss}", "peer_ip_src", ip_address); json_object_update_missing(obj, kv); json_decref(kv); kv = json_pack("{ss}", "event_type", event_type); json_object_update_missing(obj, kv); json_decref(kv); memset(prefix_str, 0, INET6_ADDRSTRLEN); prefix2str(&route->p, prefix_str, INET6_ADDRSTRLEN); kv = json_pack("{ss}", "ip_prefix", prefix_str); json_object_update_missing(obj, kv); json_decref(kv); memset(nexthop_str, 0, INET6_ADDRSTRLEN); if (attr->mp_nexthop.family) addr_to_str(nexthop_str, &attr->mp_nexthop); else inet_ntop(AF_INET, &attr->nexthop, nexthop_str, INET6_ADDRSTRLEN); kv = json_pack("{ss}", "bgp_nexthop", nexthop_str); json_object_update_missing(obj, kv); json_decref(kv); if (ri && ri->extra && ri->extra->path_id) { kv = json_pack("{sI}", "as_path_id", ri->extra->path_id); json_object_update_missing(obj, kv); json_decref(kv); } aspath = attr->aspath ? attr->aspath->str : empty; kv = json_pack("{ss}", "as_path", aspath); json_object_update_missing(obj, kv); json_decref(kv); if (attr->community) { kv = json_pack("{ss}", "comms", attr->community->str); json_object_update_missing(obj, kv); json_decref(kv); } if (attr->ecommunity) { kv = json_pack("{ss}", "ecomms", attr->ecommunity->str); json_object_update_missing(obj, kv); json_decref(kv); } kv = json_pack("{sI}", "origin", attr->origin); json_object_update_missing(obj, kv); json_decref(kv); kv = json_pack("{sI}", "local_pref", attr->local_pref); json_object_update_missing(obj, kv); json_decref(kv); if (attr->med) { kv = json_pack("{sI}", "med", attr->med); json_object_update_missing(obj, kv); json_decref(kv); } if (safi == SAFI_MPLS_VPN) { u_char rd_str[SRVBUFLEN]; bgp_rd2str(rd_str, &ri->extra->rd); kv = json_pack("{ss}", "rd", rd_str); json_object_update_missing(obj, kv); json_decref(kv); } if ((config.nfacctd_bgp_msglog_file && etype == BGP_LOGDUMP_ET_LOG) || (config.bgp_table_dump_file && etype == BGP_LOGDUMP_ET_DUMP)) write_and_free_json(peer->log->fd, obj); #ifdef WITH_RABBITMQ if ((config.nfacctd_bgp_msglog_amqp_routing_key && etype == BGP_LOGDUMP_ET_LOG) || (config.bgp_table_dump_amqp_routing_key && etype == BGP_LOGDUMP_ET_DUMP)) { amqp_ret = write_and_free_json_amqp(peer->log->amqp_host, obj); p_amqp_unset_routing_key(peer->log->amqp_host); } #endif #endif } return (ret | amqp_ret); }
int bgp_peer_log_close(struct bgp_peer *peer, int output, int type) { char event_type[] = "log_close", peer_ip_src[] = "peer_ip_src", bmp_router[] = "bmp_router"; struct bgp_peer_log *log_ptr; void *amqp_log_ptr; int ret = 0, amqp_ret = 0;; /* pointers to BGP or BMP vars */ char *file, *amqp_routing_key, *lts, *pa_str; u_int64_t *ls; if (type == FUNC_TYPE_BGP) { file = config.nfacctd_bgp_msglog_file; amqp_routing_key = config.nfacctd_bgp_msglog_amqp_routing_key; pa_str = peer_ip_src; lts = log_tstamp_str; ls = &log_seq; } else if (type == FUNC_TYPE_BMP) { file = config.nfacctd_bmp_msglog_file; amqp_routing_key = config.nfacctd_bmp_msglog_amqp_routing_key; pa_str = bmp_router; lts = bmp_log_tstamp_str; ls = &bmp_log_seq; } else return ret; if (!peer || peer->log) return ret; #ifdef WITH_RABBITMQ if (amqp_routing_key) p_amqp_set_routing_key(peer->log->amqp_host, peer->log->filename); #endif log_ptr = peer->log; amqp_log_ptr = peer->log->amqp_host; assert(peer->log->refcnt); peer->log->refcnt--; peer->log = NULL; if (output == PRINT_OUTPUT_JSON) { #ifdef WITH_JANSSON char ip_address[INET6_ADDRSTRLEN]; json_t *obj = json_object(), *kv; kv = json_pack("{sI}", "seq", (*ls)); json_object_update_missing(obj, kv); json_decref(kv); bgp_peer_log_seq_increment(ls); kv = json_pack("{ss}", "timestamp", lts); json_object_update_missing(obj, kv); json_decref(kv); addr_to_str(ip_address, &peer->addr); kv = json_pack("{ss}", pa_str, ip_address); json_object_update_missing(obj, kv); json_decref(kv); kv = json_pack("{ss}", "event_type", event_type); json_object_update_missing(obj, kv); json_decref(kv); if (file) write_and_free_json(log_ptr->fd, obj); #ifdef WITH_RABBITMQ if (amqp_routing_key) { amqp_ret = write_and_free_json_amqp(amqp_log_ptr, obj); p_amqp_unset_routing_key(amqp_log_ptr); } #endif #endif } if (!log_ptr->refcnt) { if (file && !log_ptr->refcnt) { fclose(log_ptr->fd); memset(log_ptr, 0, sizeof(struct bgp_peer_log)); } } return (ret | amqp_ret); }
int bgp_peer_log_init(struct bgp_peer *peer, int output, int type) { int peer_idx, have_it, ret = 0, amqp_ret = 0; char log_filename[SRVBUFLEN], event_type[] = "log_init"; char peer_ip_src[] = "peer_ip_src", bmp_router[] = "bmp_router"; /* pointers to BGP or BMP vars */ struct bgp_peer_log **bpl; char *file, *amqp_routing_key, *lts, *pa_str; int amqp_routing_key_rr, max_peers; u_int64_t *ls; if (type == FUNC_TYPE_BGP) { file = config.nfacctd_bgp_msglog_file; amqp_routing_key = config.nfacctd_bgp_msglog_amqp_routing_key; amqp_routing_key_rr = config.nfacctd_bgp_msglog_amqp_routing_key_rr; max_peers = config.nfacctd_bgp_max_peers; pa_str = peer_ip_src; lts = log_tstamp_str; ls = &log_seq; bpl = &peers_log; } else if (type == FUNC_TYPE_BMP) { file = config.nfacctd_bmp_msglog_file; amqp_routing_key = config.nfacctd_bmp_msglog_amqp_routing_key; amqp_routing_key_rr = config.nfacctd_bmp_msglog_amqp_routing_key_rr; max_peers = config.nfacctd_bmp_max_peers; pa_str = bmp_router; lts = bmp_log_tstamp_str; ls = &bmp_log_seq; bpl = &bmp_peers_log; } else if (type == FUNC_TYPE_SFLOW_COUNTER) { file = config.sfacctd_counter_file; amqp_routing_key = NULL; /* AMQP not supported */ amqp_routing_key_rr = 0; /* AMQP not supported */ max_peers = config.sfacctd_counter_max_nodes; pa_str = peer_ip_src; lts = sf_cnt_log_tstamp_str; ls = &sf_cnt_log_seq; bpl = &sf_cnt_log; } else return ret; if (!(*bpl) || !peer || peer->log) return ret; if (file) bgp_peer_log_dynname(log_filename, SRVBUFLEN, file, peer); if (amqp_routing_key) { bgp_peer_log_dynname(log_filename, SRVBUFLEN, amqp_routing_key, peer); } for (peer_idx = 0, have_it = 0; peer_idx < max_peers; peer_idx++) { if (!(*bpl)[peer_idx].refcnt) { if (file) (*bpl)[peer_idx].fd = open_logfile(log_filename, "a"); #ifdef WITH_RABBITMQ if (amqp_routing_key) (*bpl)[peer_idx].amqp_host = &bgp_daemon_msglog_amqp_host; #endif strcpy((*bpl)[peer_idx].filename, log_filename); have_it = TRUE; break; } else if (!strcmp(log_filename, (*bpl)[peer_idx].filename)) { have_it = TRUE; break; } } if (have_it) { peer->log = &(*bpl)[peer_idx]; (*bpl)[peer_idx].refcnt++; #ifdef WITH_RABBITMQ if (amqp_routing_key) p_amqp_set_routing_key(peer->log->amqp_host, peer->log->filename); if (amqp_routing_key_rr && !p_amqp_get_routing_key_rr(peer->log->amqp_host)) { p_amqp_init_routing_key_rr(peer->log->amqp_host); p_amqp_set_routing_key_rr(peer->log->amqp_host, amqp_routing_key_rr); } #endif if (output == PRINT_OUTPUT_JSON) { #ifdef WITH_JANSSON char ip_address[INET6_ADDRSTRLEN]; json_t *obj = json_object(), *kv; kv = json_pack("{sI}", "seq", (*ls)); json_object_update_missing(obj, kv); json_decref(kv); bgp_peer_log_seq_increment(ls); kv = json_pack("{ss}", "timestamp", lts); json_object_update_missing(obj, kv); json_decref(kv); addr_to_str(ip_address, &peer->addr); kv = json_pack("{ss}", pa_str, ip_address); json_object_update_missing(obj, kv); json_decref(kv); kv = json_pack("{ss}", "event_type", event_type); json_object_update_missing(obj, kv); json_decref(kv); if (file) write_and_free_json(peer->log->fd, obj); #ifdef WITH_RABBITMQ if (amqp_routing_key) { amqp_ret = write_and_free_json_amqp(peer->log->amqp_host, obj); p_amqp_unset_routing_key(peer->log->amqp_host); } #endif #endif } } return (ret | amqp_ret); }
static void run_tests() { json_t *value; int i; char buffer[4] = {'t', 'e', 's', 't'}; json_error_t error; /* * Simple, valid json_pack cases */ /* true */ value = json_pack("b", 1); if(!json_is_true(value)) fail("json_pack boolean failed"); if(value->refcount != (size_t)-1) fail("json_pack boolean refcount failed"); json_decref(value); /* false */ value = json_pack("b", 0); if(!json_is_false(value)) fail("json_pack boolean failed"); if(value->refcount != (size_t)-1) fail("json_pack boolean refcount failed"); json_decref(value); /* null */ value = json_pack("n"); if(!json_is_null(value)) fail("json_pack null failed"); if(value->refcount != (size_t)-1) fail("json_pack null refcount failed"); json_decref(value); /* integer */ value = json_pack("i", 1); if(!json_is_integer(value) || json_integer_value(value) != 1) fail("json_pack integer failed"); if(value->refcount != (size_t)1) fail("json_pack integer refcount failed"); json_decref(value); /* integer from json_int_t */ value = json_pack("I", (json_int_t)555555); if(!json_is_integer(value) || json_integer_value(value) != 555555) fail("json_pack json_int_t failed"); if(value->refcount != (size_t)1) fail("json_pack integer refcount failed"); json_decref(value); /* real */ value = json_pack("f", 1.0); if(!json_is_real(value) || json_real_value(value) != 1.0) fail("json_pack real failed"); if(value->refcount != (size_t)1) fail("json_pack real refcount failed"); json_decref(value); /* string */ value = json_pack("s", "test"); if(!json_is_string(value) || strcmp("test", json_string_value(value))) fail("json_pack string failed"); if(value->refcount != (size_t)1) fail("json_pack string refcount failed"); json_decref(value); /* nullable string (defined case) */ value = json_pack("s?", "test"); if(!json_is_string(value) || strcmp("test", json_string_value(value))) fail("json_pack nullable string (defined case) failed"); if(value->refcount != (size_t)1) fail("json_pack nullable string (defined case) refcount failed"); json_decref(value); /* nullable string (NULL case) */ value = json_pack("s?", NULL); if(!json_is_null(value)) fail("json_pack nullable string (NULL case) failed"); if(value->refcount != (size_t)-1) fail("json_pack nullable string (NULL case) refcount failed"); json_decref(value); /* string and length (int) */ value = json_pack("s#", "test asdf", 4); if(!json_is_string(value) || strcmp("test", json_string_value(value))) fail("json_pack string and length failed"); if(value->refcount != (size_t)1) fail("json_pack string and length refcount failed"); json_decref(value); /* string and length (size_t) */ value = json_pack("s%", "test asdf", (size_t)4); if(!json_is_string(value) || strcmp("test", json_string_value(value))) fail("json_pack string and length failed"); if(value->refcount != (size_t)1) fail("json_pack string and length refcount failed"); json_decref(value); /* string and length (int), non-NUL terminated string */ value = json_pack("s#", buffer, 4); if(!json_is_string(value) || strcmp("test", json_string_value(value))) fail("json_pack string and length (int) failed"); if(value->refcount != (size_t)1) fail("json_pack string and length (int) refcount failed"); json_decref(value); /* string and length (size_t), non-NUL terminated string */ value = json_pack("s%", buffer, (size_t)4); if(!json_is_string(value) || strcmp("test", json_string_value(value))) fail("json_pack string and length (size_t) failed"); if(value->refcount != (size_t)1) fail("json_pack string and length (size_t) refcount failed"); json_decref(value); /* string concatenation */ value = json_pack("s++", "te", "st", "ing"); if(!json_is_string(value) || strcmp("testing", json_string_value(value))) fail("json_pack string concatenation failed"); if(value->refcount != (size_t)1) fail("json_pack string concatenation refcount failed"); json_decref(value); /* string concatenation and length (int) */ value = json_pack("s#+#+", "test", 1, "test", 2, "test"); if(!json_is_string(value) || strcmp("ttetest", json_string_value(value))) fail("json_pack string concatenation and length (int) failed"); if(value->refcount != (size_t)1) fail("json_pack string concatenation and length (int) refcount failed"); json_decref(value); /* string concatenation and length (size_t) */ value = json_pack("s%+%+", "test", (size_t)1, "test", (size_t)2, "test"); if(!json_is_string(value) || strcmp("ttetest", json_string_value(value))) fail("json_pack string concatenation and length (size_t) failed"); if(value->refcount != (size_t)1) fail("json_pack string concatenation and length (size_t) refcount failed"); json_decref(value); /* empty object */ value = json_pack("{}", 1.0); if(!json_is_object(value) || json_object_size(value) != 0) fail("json_pack empty object failed"); if(value->refcount != (size_t)1) fail("json_pack empty object refcount failed"); json_decref(value); /* empty list */ value = json_pack("[]", 1.0); if(!json_is_array(value) || json_array_size(value) != 0) fail("json_pack empty list failed"); if(value->refcount != (size_t)1) fail("json_pack empty list failed"); json_decref(value); /* non-incref'd object */ value = json_pack("o", json_integer(1)); if(!json_is_integer(value) || json_integer_value(value) != 1) fail("json_pack object failed"); if(value->refcount != (size_t)1) fail("json_pack integer refcount failed"); json_decref(value); /* non-incref'd nullable object (defined case) */ value = json_pack("o?", json_integer(1)); if(!json_is_integer(value) || json_integer_value(value) != 1) fail("json_pack nullable object (defined case) failed"); if(value->refcount != (size_t)1) fail("json_pack nullable object (defined case) refcount failed"); json_decref(value); /* non-incref'd nullable object (NULL case) */ value = json_pack("o?", NULL); if(!json_is_null(value)) fail("json_pack nullable object (NULL case) failed"); if(value->refcount != (size_t)-1) fail("json_pack nullable object (NULL case) refcount failed"); json_decref(value); /* incref'd object */ value = json_pack("O", json_integer(1)); if(!json_is_integer(value) || json_integer_value(value) != 1) fail("json_pack object failed"); if(value->refcount != (size_t)2) fail("json_pack integer refcount failed"); json_decref(value); json_decref(value); /* incref'd nullable object (defined case) */ value = json_pack("O?", json_integer(1)); if(!json_is_integer(value) || json_integer_value(value) != 1) fail("json_pack incref'd nullable object (defined case) failed"); if(value->refcount != (size_t)2) fail("json_pack incref'd nullable object (defined case) refcount failed"); json_decref(value); json_decref(value); /* incref'd nullable object (NULL case) */ value = json_pack("O?", NULL); if(!json_is_null(value)) fail("json_pack incref'd nullable object (NULL case) failed"); if(value->refcount != (size_t)-1) fail("json_pack incref'd nullable object (NULL case) refcount failed"); /* simple object */ value = json_pack("{s:[]}", "foo"); if(!json_is_object(value) || json_object_size(value) != 1) fail("json_pack array failed"); if(!json_is_array(json_object_get(value, "foo"))) fail("json_pack array failed"); if(json_object_get(value, "foo")->refcount != (size_t)1) fail("json_pack object refcount failed"); json_decref(value); /* object with complex key */ value = json_pack("{s+#+: []}", "foo", "barbar", 3, "baz"); if(!json_is_object(value) || json_object_size(value) != 1) fail("json_pack array failed"); if(!json_is_array(json_object_get(value, "foobarbaz"))) fail("json_pack array failed"); if(json_object_get(value, "foobarbaz")->refcount != (size_t)1) fail("json_pack object refcount failed"); json_decref(value); /* simple array */ value = json_pack("[i,i,i]", 0, 1, 2); if(!json_is_array(value) || json_array_size(value) != 3) fail("json_pack object failed"); for(i=0; i<3; i++) { if(!json_is_integer(json_array_get(value, i)) || json_integer_value(json_array_get(value, i)) != i) fail("json_pack integer array failed"); } json_decref(value); /* Whitespace; regular string */ value = json_pack(" s ", "test"); if(!json_is_string(value) || strcmp("test", json_string_value(value))) fail("json_pack string (with whitespace) failed"); json_decref(value); /* Whitespace; empty array */ value = json_pack("[ ]"); if(!json_is_array(value) || json_array_size(value) != 0) fail("json_pack empty array (with whitespace) failed"); json_decref(value); /* Whitespace; array */ value = json_pack("[ i , i, i ] ", 1, 2, 3); if(!json_is_array(value) || json_array_size(value) != 3) fail("json_pack array (with whitespace) failed"); json_decref(value); /* * Invalid cases */ /* newline in format string */ if(json_pack_ex(&error, 0, "{\n\n1")) fail("json_pack failed to catch invalid format '1'"); check_error("Expected format 's', got '1'", "<format>", 3, 1, 4); /* mismatched open/close array/object */ if(json_pack_ex(&error, 0, "[}")) fail("json_pack failed to catch mismatched '}'"); check_error("Unexpected format character '}'", "<format>", 1, 2, 2); if(json_pack_ex(&error, 0, "{]")) fail("json_pack failed to catch mismatched ']'"); check_error("Expected format 's', got ']'", "<format>", 1, 2, 2); /* missing close array */ if(json_pack_ex(&error, 0, "[")) fail("json_pack failed to catch missing ']'"); check_error("Unexpected end of format string", "<format>", 1, 2, 2); /* missing close object */ if(json_pack_ex(&error, 0, "{")) fail("json_pack failed to catch missing '}'"); check_error("Unexpected end of format string", "<format>", 1, 2, 2); /* garbage after format string */ if(json_pack_ex(&error, 0, "[i]a", 42)) fail("json_pack failed to catch garbage after format string"); check_error("Garbage after format string", "<format>", 1, 4, 4); if(json_pack_ex(&error, 0, "ia", 42)) fail("json_pack failed to catch garbage after format string"); check_error("Garbage after format string", "<format>", 1, 2, 2); /* NULL string */ if(json_pack_ex(&error, 0, "s", NULL)) fail("json_pack failed to catch null argument string"); check_error("NULL string argument", "<args>", 1, 1, 1); /* + on its own */ if(json_pack_ex(&error, 0, "+", NULL)) fail("json_pack failed to a lone +"); check_error("Unexpected format character '+'", "<format>", 1, 1, 1); /* NULL format */ if(json_pack_ex(&error, 0, NULL)) fail("json_pack failed to catch NULL format string"); check_error("NULL or empty format string", "<format>", -1, -1, 0); /* NULL key */ if(json_pack_ex(&error, 0, "{s:i}", NULL, 1)) fail("json_pack failed to catch NULL key"); check_error("NULL string argument", "<args>", 1, 2, 2); /* More complicated checks for row/columns */ if(json_pack_ex(&error, 0, "{ {}: s }", "foo")) fail("json_pack failed to catch object as key"); check_error("Expected format 's', got '{'", "<format>", 1, 3, 3); /* Complex object */ if(json_pack_ex(&error, 0, "{ s: {}, s:[ii{} }", "foo", "bar", 12, 13)) fail("json_pack failed to catch missing ]"); check_error("Unexpected format character '}'", "<format>", 1, 19, 19); /* Complex array */ if(json_pack_ex(&error, 0, "[[[[[ [[[[[ [[[[ }]]]] ]]]] ]]]]]")) fail("json_pack failed to catch extra }"); check_error("Unexpected format character '}'", "<format>", 1, 21, 21); /* Invalid UTF-8 in object key */ if(json_pack_ex(&error, 0, "{s:i}", "\xff\xff", 42)) fail("json_pack failed to catch invalid UTF-8 in an object key"); check_error("Invalid UTF-8 object key", "<args>", 1, 2, 2); /* Invalid UTF-8 in a string */ if(json_pack_ex(&error, 0, "{s:s}", "foo", "\xff\xff")) fail("json_pack failed to catch invalid UTF-8 in a string"); check_error("Invalid UTF-8 string", "<args>", 1, 4, 4); }
void prf_br_list(httpsrv_client_t *hcl) { json_t *obj, *arr, *list, *bridge, *camouflage, *method, *scheme; const char *j; bool fail = false; size_t i; if (l_bridge_access_list == NULL) { djb_result(hcl, DJB_ERR, "No Bridge List set yet, perform ACS first"); return; } if (!json_is_object(l_bridge_access_list)) { djb_result(hcl, DJB_ERR, "Bridge List is not a valid JSON Object"); return; } list = json_object_get(l_bridge_access_list, "BR_Access_List"); if (list == NULL || !json_is_array(list)) { djb_result(hcl, DJB_ERR, "Bridge Access List array missing"); return; } arr = json_array(); if (arr == NULL) { djb_result(hcl, DJB_ERR, "Could not create a JSON array"); return; } for (i = 0; !fail && i < json_array_size(list); i++) { bridge = json_array_get(list, i); if (bridge == NULL || !json_is_object(bridge)) { djb_result(hcl, DJB_ERR, "Bridge missing in list"); fail = true; return; } camouflage = json_object_get(bridge, "Camouflage"); if (camouflage == NULL || !json_is_object(camouflage)) { djb_result(hcl, DJB_ERR, "BR Camouflage not found"); fail = true; break; } method = json_object_get(camouflage, "method"); if (method == NULL || !json_is_string(method)) { djb_result(hcl, DJB_ERR, "BR Camouflage method not found"); fail = true; break; } scheme = json_object_get(camouflage, "scheme"); if (scheme == NULL || !json_is_string(scheme)) { djb_result(hcl, DJB_ERR, "BR Camouflage scheme not found"); fail = true; break; } /* Add them to the array */ json_array_append_new(arr, json_pack( "{s:s, s:s}", "method", method, "scheme", scheme)); /* continue */ } if (fail) { /* Error reported already, just clean up and get out */ json_decref(arr); return; } /* arr becomes part of this hence no decref */ obj = json_pack("{s:o}", "bridges", arr); if (obj == NULL) { djb_result(hcl, DJB_ERR, "Could not pack JSON"); json_decref(arr); return; } j = json_dumps(obj, JSON_COMPACT | JSON_ENSURE_ASCII); if (j == NULL) { djb_result(hcl, DJB_ERR, "Could not dump JSON"); } else { /* Return the object */ djb_result(hcl, DJB_OK, j); } /* Done with it */ json_decref(obj); return; }
bool w_query_execute( w_query *query, w_root_t *root, w_query_res *res, w_query_generator generator, void *gendata) { struct w_query_ctx ctx; w_perf_t sample; int64_t num_walked = 0; memset(&ctx, 0, sizeof(ctx)); ctx.query = query; ctx.root = root; memset(res, 0, sizeof(*res)); w_perf_start(&sample, "query_execute"); if (query->sync_timeout && !w_root_sync_to_now(root, query->sync_timeout)) { ignore_result(asprintf(&res->errmsg, "synchronization failed: %s\n", strerror(errno))); return false; } /* The first stage of execution is generation. * We generate a series of file inputs to pass to * the query executor. * * We evaluate each of the generators one after the * other. If multiple generators are used, it is * possible and expected that the same file name * will be evaluated multiple times if those generators * both emit the same file. */ // Lock the root and begin generation if (!w_root_lock_with_timeout(root, "w_query_execute", query->lock_timeout)) { ignore_result(asprintf(&res->errmsg, "couldn't acquire root lock within " "lock_timeout of %dms. root is " "currently busy (%s)\n", query->lock_timeout, root->lock_reason)); return false; } res->root_number = root->number; res->ticks = root->ticks; // Evaluate the cursor for this root w_clockspec_eval(root, query->since_spec, &ctx.since); res->is_fresh_instance = !ctx.since.is_timestamp && ctx.since.clock.is_fresh_instance; if (!(res->is_fresh_instance && query->empty_on_fresh_instance)) { if (!generator) { generator = default_generators; } generator(query, root, &ctx, gendata, &num_walked); } if (w_perf_finish(&sample)) { w_perf_add_root_meta(&sample, root); w_perf_add_meta(&sample, "query_execute", json_pack("{s:b, s:i, s:i, s:O}", // "fresh_instance", res->is_fresh_instance, // "num_results", ctx.num_results, // "num_walked", num_walked, // "query", ctx.query->query_spec // )); w_perf_log(&sample); } w_root_unlock(root); w_perf_destroy(&sample); if (ctx.wholename) { w_string_delref(ctx.wholename); } if (ctx.last_parent_path) { w_string_delref(ctx.last_parent_path); } res->results = ctx.results; res->num_results = ctx.num_results; return true; }
/* * register the client with the OP using Dynamic Client Registration */ static apr_byte_t oidc_metadata_client_register(request_rec *r, oidc_cfg *cfg, oidc_provider_t *provider, json_t **j_client, const char **response) { /* assemble the JSON registration request */ json_t *data = json_object(); json_object_set_new(data, "client_name", json_string(provider->client_name)); json_object_set_new(data, "redirect_uris", json_pack("[s]", cfg->redirect_uri)); json_t *response_types = json_array(); apr_array_header_t *flows = oidc_proto_supported_flows(r->pool); int i; for (i = 0; i < flows->nelts; i++) { json_array_append_new(response_types, json_string(((const char**) flows->elts)[i])); } json_object_set_new(data, "response_types", response_types); if (provider->client_contact != NULL) { json_object_set_new(data, "contacts", json_pack("[s]", provider->client_contact)); } if (provider->client_jwks_uri) { json_object_set_new(data, "jwks_uri", json_string(provider->client_jwks_uri)); } else if (cfg->public_keys != NULL) { json_object_set_new(data, "jwks_uri", json_string( apr_psprintf(r->pool, "%s?jwks=rsa", cfg->redirect_uri))); } if (provider->id_token_signed_response_alg != NULL) { json_object_set_new(data, "id_token_signed_response_alg", json_string(provider->id_token_signed_response_alg)); } if (provider->id_token_encrypted_response_alg != NULL) { json_object_set_new(data, "id_token_encrypted_response_alg", json_string(provider->id_token_encrypted_response_alg)); } if (provider->id_token_encrypted_response_enc != NULL) { json_object_set_new(data, "id_token_encrypted_response_enc", json_string(provider->id_token_encrypted_response_enc)); } if (provider->userinfo_signed_response_alg != NULL) { json_object_set_new(data, "userinfo_signed_response_alg", json_string(provider->userinfo_signed_response_alg)); } if (provider->userinfo_encrypted_response_alg != NULL) { json_object_set_new(data, "userinfo_encrypted_response_alg", json_string(provider->userinfo_encrypted_response_alg)); } if (provider->userinfo_encrypted_response_enc != NULL) { json_object_set_new(data, "userinfo_encrypted_response_enc", json_string(provider->userinfo_encrypted_response_enc)); } json_object_set_new(data, "initiate_login_uri", json_string(cfg->redirect_uri)); if (provider->registration_endpoint_json != NULL) { json_error_t json_error; json_t *json = json_loads(provider->registration_endpoint_json, 0, &json_error); if (json == NULL) { oidc_error(r, "JSON parsing returned an error: %s", json_error.text); } else { if (!json_is_object(json)) { oidc_error(r, "parsed JSON did not contain a JSON object"); } else { const char *key; json_t *value; json_object_foreach(json, key, value) { json_object_set(data, key, value); } } json_decref(json); }
json_t *make_replicate(const char *resource, const char *location, const char *checksum, const char *replicate, const char *status, baton_error_t *error) { json_t *result = NULL; json_t *is_valid = NULL; // Ref to be stolen by result json_t *ck_value = NULL; // Ref to be stolen by result init_baton_error(error); int base = 10; char *endptr; int repl = strtoul(replicate, &endptr, base); if (*endptr) { set_baton_error(error, -1, "Failed to parse replicate number from string '%s'", replicate); goto error; } if (str_equals(status, INVALID_REPLICATE, 1)) { is_valid = json_false(); } else if (str_equals(status, VALID_REPLICATE, 1)) { is_valid = json_true(); } else { set_baton_error(error, CAT_INVALID_ARGUMENT, "Invalid replicate status '%s'", status); goto error; } if (checksum) { ck_value = json_string(checksum); } else { ck_value = json_null(); } result = json_pack("{s:s, s:s, s:o, s:i, s:o}", JSON_RESOURCE_KEY, resource, JSON_LOCATION_KEY, location, JSON_CHECKSUM_KEY, ck_value, JSON_REPLICATE_NUMBER_KEY, repl, JSON_REPLICATE_STATUS_KEY, is_valid); if (!result) { set_baton_error(error, -1, "Failed to pack replicate object"); goto error; } return result; error: if (result) { json_decref(result); } else { // Only decref these if they were not stolen by a succesfully // created result if (is_valid) json_decref(is_valid); if (ck_value) json_decref(ck_value); } return NULL; }
static void dump_val(json_t *jent, const char *key, uint8_t *val, size_t len) { json_object_set_new(jent, key, json_pack("s#", val, len)); }
/* query /root {query} */ static void cmd_query(struct watchman_client *client, json_t *args) { w_root_t *root; w_query *query; json_t *query_spec; char *errmsg = NULL; w_query_res res; json_t *response; json_t *file_list, *jfield_list; char clockbuf[128]; struct w_query_field_list field_list; if (json_array_size(args) != 3) { send_error_response(client, "wrong number of arguments for 'query'"); return; } root = resolve_root_or_err(client, args, 1, false); if (!root) { return; } query_spec = json_array_get(args, 2); jfield_list = json_object_get(query_spec, "fields"); if (!parse_field_list(jfield_list, &field_list, &errmsg)) { send_error_response(client, "invalid field list: %s", errmsg); free(errmsg); w_root_delref(root); return; } query = w_query_parse(root, query_spec, &errmsg); if (!query) { send_error_response(client, "failed to parse query: %s", errmsg); free(errmsg); w_root_delref(root); return; } if (client->client_mode) { query->sync_timeout = 0; } if (!w_query_execute(query, root, &res, NULL, NULL)) { send_error_response(client, "query failed: %s", res.errmsg); w_query_result_free(&res); w_root_delref(root); w_query_delref(query); return; } w_query_delref(query); file_list = w_query_results_to_json(&field_list, res.num_results, res.results); w_query_result_free(&res); response = make_response(); if (clock_id_string(res.root_number, res.ticks, clockbuf, sizeof(clockbuf))) { set_prop(response, "clock", json_string_nocheck(clockbuf)); } set_prop(response, "is_fresh_instance", json_pack("b", res.is_fresh_instance)); set_prop(response, "files", file_list); add_root_warnings_to_response(response, root); send_and_dispose_response(client, response); w_root_delref(root); }
int handle_file_p(struct provmsg *msg) { struct provmsg_file_p *m = (struct provmsg_file_p *) msg; json_t * obj; char * text; if (!(m->mask & MAY_READ) && !(m->mask & MAY_WRITE) && !(m->mask & MAY_APPEND) ) return 0; /* Extract provmsg fields */ char * uuid = print_uuid_be(&m->inode.sb_uuid); unsigned long inode = m->inode.ino; unsigned long version = m->inode_version; int mask = m->mask; int cred = m->msg.cred_id; /* Create InodeVersion node */ snprintf(cypher_req, MAXREQLEN, "CREATE (n:InodeVersion {id : \"%lu:%lu\", uuid : \"%s\", inode : %lu, version : %lu, mask : %d})", inode, version, uuid, inode, version, mask); obj = json_pack("{s:[{s:s}]}", "statements", "statement", cypher_req); text = post(NEO_URL,json_dumps(obj,0)); free(text); free(obj); /* Create Activity node */ snprintf(cypher_req, MAXREQLEN, "CREATE (n:Activity {id : \"%d\"})", cred); obj = json_pack("{s:[{s:s}]}", "statements", "statement", cypher_req); text = post(NEO_URL,json_dumps(obj,0)); free(text); free(obj); /* Create relationship */ int create_relationship = 0; if (m->mask & MAY_READ){ snprintf(cypher_req, MAXREQLEN, "MATCH (a:InodeVersion), (b:Activity) " "WHERE a.id = \"%lu:%lu\" AND b.id = \"%d\" " "CREATE (b)-[r:Used]->(a) " "RETURN r;", inode, version, cred);; create_relationship = 1; } else if ( m->mask & MAY_WRITE || m->mask & MAY_APPEND ) { snprintf(cypher_req, MAXREQLEN, "MATCH (a:InodeVersion), (b:Activity) " "WHERE a.id = \"%lu:%lu\" AND b.id = \"%d\" " "CREATE (a)-[r:WasGeneratedBy]->(b) ", //"RETURN r;", inode, version, cred); create_relationship = 1; } if ( create_relationship ) { obj = json_pack("{s:[{s:s}]}", "statements", "statement", cypher_req); text = post(NEO_URL,json_dumps(obj,0)); free(text); free(obj); } free(uuid); return 0; }
json_t *hackerboatStateClass::packTimeSpec (timespec t) { return json_pack("{s:i,s:i}", "tv_sec", t.tv_sec, "tv_nsec", t.tv_nsec); }
static json_t * derive(const jose_hook_alg_t *alg, jose_cfg_t *cfg, json_t *hdr, json_t *cek, const json_t *key) { const jose_hook_alg_t *halg = NULL; const char *name = alg->name; uint8_t pu[KEYMAX] = {}; uint8_t pv[KEYMAX] = {}; uint8_t dk[KEYMAX] = {}; uint8_t ky[KEYMAX] = {}; const char *enc = NULL; json_t *out = NULL; size_t dkl = 0; size_t pul = 0; size_t pvl = 0; size_t kyl = 0; halg = jose_hook_alg_find(JOSE_HOOK_ALG_KIND_HASH, "S256"); if (!halg) goto egress; if (json_unpack(hdr, "{s?s}", "enc", &enc) < 0) goto egress; if (!enc && json_unpack(cek, "{s:s}", "alg", &enc) < 0) goto egress; switch (str2enum(alg->name, NAMES, NULL)) { case 0: dkl = encr_alg_keylen(cfg, enc); name = enc; break; case 1: dkl = 16; break; case 2: dkl = 24; break; case 3: dkl = 32; break; default: goto egress; } if (dkl < 16 || dkl > sizeof(dk)) goto egress; pul = decode(hdr, "apu", pu, sizeof(pu)); if (pul > sizeof(pu)) goto egress; pvl = decode(hdr, "apv", pv, sizeof(pv)); if (pvl > sizeof(pv)) goto egress; kyl = decode(key, "x", ky, sizeof(ky)); if (kyl > sizeof(ky)) goto egress; if (!concatkdf(halg, cfg, dk, dkl, ky, kyl, name, strlen(name), pu, pul, pv, pvl, NULL)) goto egress; out = json_pack("{s:s,s:s,s:o}", "kty", "oct", "alg", enc, "k", jose_b64_enc(dk, dkl)); egress: OPENSSL_cleanse(ky, sizeof(ky)); OPENSSL_cleanse(pu, sizeof(pu)); OPENSSL_cleanse(pv, sizeof(pv)); OPENSSL_cleanse(dk, sizeof(dk)); return out; }
// Translate from the legacy array into the new style, then // delegate to the main parser. // We build a big anyof expression w_query *w_query_parse_legacy(w_root_t *root, json_t *args, char **errmsg, int start, uint32_t *next_arg, const char *clockspec, json_t **expr_p) { bool include = true; bool negated = false; uint32_t i; const char *term_name = "match"; json_t *query_array; json_t *included = NULL, *excluded = NULL; json_t *term; json_t *container; json_t *query_obj = json_object(); w_query *query; if (!json_is_array(args)) { *errmsg = strdup("Expected an array"); json_decref(query_obj); return NULL; } for (i = start; i < json_array_size(args); i++) { const char *arg = json_string_value(json_array_get(args, i)); if (!arg) { /* not a string value! */ ignore_result(asprintf(errmsg, "rule @ position %d is not a string value", i)); json_decref(query_obj); return NULL; } } for (i = start; i < json_array_size(args); i++) { const char *arg = json_string_value(json_array_get(args, i)); if (!strcmp(arg, "--")) { i++; break; } if (!strcmp(arg, "-X")) { include = false; continue; } if (!strcmp(arg, "-I")) { include = true; continue; } if (!strcmp(arg, "!")) { negated = true; continue; } if (!strcmp(arg, "-P")) { term_name = "ipcre"; continue; } if (!strcmp(arg, "-p")) { term_name = "pcre"; continue; } // Which group are we going to file it into if (include) { if (!included) { included = json_pack("[s]", "anyof"); } container = included; } else { if (!excluded) { excluded = json_pack("[s]", "anyof"); } container = excluded; } term = json_pack("[sss]", term_name, arg, "wholename"); if (negated) { term = json_pack("[so]", "not", term); } json_array_append_new(container, term); // Reset negated flag negated = false; term_name = "match"; } if (excluded) { term = json_pack("[so]", "not", excluded); excluded = term; } if (included && excluded) { query_array = json_pack("[soo]", "allof", excluded, included); } else if (included) { query_array = included; } else { query_array = excluded; } // query_array may be NULL, which means find me all files. // Otherwise, it is the expression we want to use. if (query_array) { json_object_set_new_nocheck(query_obj, "expression", query_array); } // For trigger if (next_arg) { *next_arg = i; } if (clockspec) { json_object_set_new_nocheck(query_obj, "since", json_string_nocheck(clockspec)); } /* compose the query with the field list */ query = w_query_parse(root, query_obj, errmsg); if (expr_p) { *expr_p = query_obj; } else { json_decref(query_obj); } return query; }
struct watchman_trigger_command *w_build_trigger_from_def( w_root_t *root, json_t *trig, char **errmsg) { struct watchman_trigger_command *cmd; json_t *ele, *query, *relative_root; json_int_t jint; const char *name = NULL; cmd = calloc(1, sizeof(*cmd)); if (!cmd) { *errmsg = strdup("no memory"); return NULL; } cmd->definition = trig; json_incref(cmd->definition); query = json_pack("{s:O}", "expression", json_object_get(cmd->definition, "expression")); relative_root = json_object_get(cmd->definition, "relative_root"); if (relative_root) { json_object_set_nocheck(query, "relative_root", relative_root); } cmd->query = w_query_parse(root, query, errmsg); json_decref(query); if (!cmd->query) { w_trigger_command_free(cmd); return NULL; } json_unpack(trig, "{s:s}", "name", &name); if (!name) { *errmsg = strdup("invalid or missing name"); w_trigger_command_free(cmd); return NULL; } cmd->triggername = w_string_new(name); cmd->command = json_object_get(trig, "command"); if (cmd->command) { json_incref(cmd->command); } if (!cmd->command || !json_is_array(cmd->command) || !json_array_size(cmd->command)) { *errmsg = strdup("invalid command array"); w_trigger_command_free(cmd); return NULL; } json_unpack(trig, "{s:b}", "append_files", &cmd->append_files); ele = json_object_get(trig, "stdin"); if (!ele) { cmd->stdin_style = input_dev_null; } else if (json_is_array(ele)) { cmd->stdin_style = input_json; if (!parse_field_list(ele, &cmd->field_list, errmsg)) { w_trigger_command_free(cmd); return NULL; } } else if (json_is_string(ele)) { const char *str = json_string_value(ele); if (!strcmp(str, "/dev/null")) { cmd->stdin_style = input_dev_null; } else if (!strcmp(str, "NAME_PER_LINE")) { cmd->stdin_style = input_name_list; } else { ignore_result(asprintf(errmsg, "invalid stdin value %s", str)); w_trigger_command_free(cmd); return NULL; } } else { *errmsg = strdup("invalid value for stdin"); w_trigger_command_free(cmd); return NULL; } jint = 0; // unlimited unless specified json_unpack(trig, "{s:I}", "max_files_stdin", &jint); if (jint < 0) { *errmsg = strdup("max_files_stdin must be >= 0"); w_trigger_command_free(cmd); return NULL; } cmd->max_files_stdin = (uint32_t)jint; json_unpack(trig, "{s:s}", "stdout", &cmd->stdout_name); json_unpack(trig, "{s:s}", "stderr", &cmd->stderr_name); if (!parse_redirection(&cmd->stdout_name, &cmd->stdout_flags, "stdout", errmsg)) { w_trigger_command_free(cmd); return NULL; } if (!parse_redirection(&cmd->stderr_name, &cmd->stderr_flags, "stderr", errmsg)) { w_trigger_command_free(cmd); return NULL; } // Copy current environment cmd->envht = w_envp_make_ht(); // Set some standard vars w_envp_set(cmd->envht, "WATCHMAN_ROOT", root->root_path); w_envp_set_cstring(cmd->envht, "WATCHMAN_SOCK", get_sock_name()); w_envp_set(cmd->envht, "WATCHMAN_TRIGGER", cmd->triggername); return cmd; }
/* Thread to handle incoming messages */ static void *janus_source_handler(void *data) { JANUS_LOG(LOG_VERB, "Joining SourcePlugin handler thread\n"); janus_source_message *msg = NULL; int error_code = 0; char *error_cause = g_malloc0(512); json_t *root = NULL; while (g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) { msg = g_async_queue_pop(messages); if (msg == NULL) continue; if (msg == &exit_message) break; if (msg->handle == NULL) { janus_source_message_free(msg); continue; } janus_source_session *session = NULL; janus_mutex_lock(&sessions_mutex); if (g_hash_table_lookup(sessions, msg->handle) != NULL) { session = (janus_source_session *)msg->handle->plugin_handle; } janus_mutex_unlock(&sessions_mutex); if (!session) { JANUS_LOG(LOG_ERR, "No session associated with this handle...\n"); janus_source_message_free(msg); continue; } if (session->destroyed) { janus_source_message_free(msg); continue; } /* Handle request */ error_code = 0; root = msg->message; if (msg->message == NULL) { JANUS_LOG(LOG_ERR, "No message??\n"); error_code = JANUS_SOURCE_ERROR_NO_MESSAGE; g_snprintf(error_cause, 512, "%s", "No message??"); goto error; } if (!json_is_object(root)) { JANUS_LOG(LOG_ERR, "JSON error: not an object\n"); error_code = JANUS_SOURCE_ERROR_INVALID_JSON; g_snprintf(error_cause, 512, "JSON error: not an object"); goto error; } /* Parse request */ const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type")); const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp")); json_t *audio = json_object_get(root, "audio"); if (audio && !json_is_boolean(audio)) { JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n"); error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT; g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)"); goto error; } json_t *video = json_object_get(root, "video"); if (video && !json_is_boolean(video)) { JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n"); error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT; g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)"); goto error; } json_t *bitrate = json_object_get(root, "bitrate"); if (bitrate && (!json_is_integer(bitrate) || json_integer_value(bitrate) < 0)) { JANUS_LOG(LOG_ERR, "Invalid element (bitrate should be a positive integer)\n"); error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT; g_snprintf(error_cause, 512, "Invalid value (bitrate should be a positive integer)"); goto error; } json_t *record = json_object_get(root, "record"); if (record && !json_is_boolean(record)) { JANUS_LOG(LOG_ERR, "Invalid element (record should be a boolean)\n"); error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT; g_snprintf(error_cause, 512, "Invalid value (record should be a boolean)"); goto error; } json_t *recfile = json_object_get(root, "filename"); if (recfile && !json_is_string(recfile)) { JANUS_LOG(LOG_ERR, "Invalid element (filename should be a string)\n"); error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT; g_snprintf(error_cause, 512, "Invalid value (filename should be a string)"); goto error; } json_t *id = json_object_get(root, "id"); if(id && !json_is_string(id)) { JANUS_LOG(LOG_ERR, "Invalid element (id should be a string)\n"); error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT; g_snprintf(error_cause, 512, "Invalid value (id should be positive string)"); goto error; } /* Enforce request */ if (audio) { session->audio_active = json_is_true(audio); JANUS_LOG(LOG_VERB, "Setting audio property: %s\n", session->audio_active ? "true" : "false"); } if (video) { if (!session->video_active && json_is_true(video)) { /* Send a PLI */ JANUS_LOG(LOG_VERB, "Just (re-)enabled video, sending a PLI to recover it\n"); char buf[12]; memset(buf, 0, 12); janus_rtcp_pli((char *)&buf, 12); gateway->relay_rtcp(session->handle, 1, buf, 12); } session->video_active = json_is_true(video); JANUS_LOG(LOG_VERB, "Setting video property: %s\n", session->video_active ? "true" : "false"); } if (bitrate) { session->bitrate = json_integer_value(bitrate); JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64"\n", session->bitrate); if (session->bitrate > 0) { /* FIXME Generate a new REMB (especially useful for Firefox, which doesn't send any we can cap later) */ char buf[24]; memset(buf, 0, 24); janus_rtcp_remb((char *)&buf, 24, session->bitrate); JANUS_LOG(LOG_VERB, "Sending REMB\n"); gateway->relay_rtcp(session->handle, 1, buf, 24); /* FIXME How should we handle a subsequent "no limit" bitrate? */ } } if(id) { session->id = g_strdup(json_string_value(id)); } if (!audio && !video && !bitrate && !record && !id && !msg_sdp) { JANUS_LOG(LOG_ERR, "No supported attributes (audio, video, bitrate, record, id, jsep) found\n"); error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT; g_snprintf(error_cause, 512, "Message error: no supported attributes (audio, video, bitrate, record, id, jsep) found"); goto error; } /* Prepare JSON event */ json_t *event = json_object(); json_object_set_new(event, "source", json_string("event")); json_object_set_new(event, "result", json_string("ok")); if(!msg_sdp) { int ret = gateway->push_event(msg->handle, &janus_source_plugin, msg->transaction, event, NULL); JANUS_LOG(LOG_VERB, " >> %d (%s)\n", ret, janus_get_api_error(ret)); json_decref(event); } else { /* Forward the same offer to the gateway, to start the source plugin */ const char *type = NULL; if (!strcasecmp(msg_sdp_type, "offer")) type = "answer"; if (!strcasecmp(msg_sdp_type, "answer")) type = "offer"; /* Any media direction that needs to be fixed? */ char *sdp = g_strdup(msg_sdp); if (strstr(sdp, "a=recvonly")) { /* Turn recvonly to inactive, as we simply bounce media back */ sdp = janus_string_replace(sdp, "a=recvonly", "a=inactive"); } else if (strstr(sdp, "a=sendonly")) { /* Turn sendonly to recvonly */ sdp = janus_string_replace(sdp, "a=sendonly", "a=recvonly"); /* FIXME We should also actually not echo this media back, though... */ } /* Make also sure we get rid of ULPfec, red, etc. */ if (strstr(sdp, "ulpfec")) { /* FIXME This really needs some better code */ sdp = janus_string_replace(sdp, "a=rtpmap:116 red/90000\r\n", ""); sdp = janus_string_replace(sdp, "a=rtpmap:117 ulpfec/90000\r\n", ""); sdp = janus_string_replace(sdp, "a=rtpmap:96 rtx/90000\r\n", ""); sdp = janus_string_replace(sdp, "a=fmtp:96 apt=100\r\n", ""); sdp = janus_string_replace(sdp, "a=rtpmap:97 rtx/90000\r\n", ""); sdp = janus_string_replace(sdp, "a=fmtp:97 apt=101\r\n", ""); sdp = janus_string_replace(sdp, "a=rtpmap:98 rtx/90000\r\n", ""); sdp = janus_string_replace(sdp, "a=fmtp:98 apt=116\r\n", ""); sdp = janus_string_replace(sdp, " 116", ""); sdp = janus_string_replace(sdp, " 117", ""); sdp = janus_string_replace(sdp, " 96", ""); sdp = janus_string_replace(sdp, " 97", ""); sdp = janus_string_replace(sdp, " 98", ""); } json_t *jsep = json_pack("{ssss}", "type", type, "sdp", sdp); sdp = janus_source_do_codec_negotiation(session, sdp); /* How long will the gateway take to push the event? */ g_atomic_int_set(&session->hangingup, 0); gint64 start = janus_get_monotonic_time(); int res = gateway->push_event(msg->handle, &janus_source_plugin, msg->transaction, event, jsep); JANUS_LOG(LOG_VERB, " >> Pushing event: %d (took %"SCNu64" us)\n", res, janus_get_monotonic_time() - start); g_free(sdp); /* We don't need the event and jsep anymore */ json_decref(event); json_decref(jsep); } janus_source_message_free(msg); continue; error: { /* Prepare JSON error event */ json_t *event = json_object(); json_object_set_new(event, "source", json_string("event")); json_object_set_new(event, "error_code", json_integer(error_code)); json_object_set_new(event, "error", json_string(error_cause)); int ret = gateway->push_event(msg->handle, &janus_source_plugin, msg->transaction, event, NULL); JANUS_LOG(LOG_VERB, " >> %d (%s)\n", ret, janus_get_api_error(ret)); janus_source_message_free(msg); /* We don't need the event anymore */ json_decref(event); } } g_free(error_cause); JANUS_LOG(LOG_VERB, "Leaving SourcePlugin handler thread\n"); return NULL; }
static void *perf_log_thread(void *unused) { json_t *samples = NULL; char **envp; json_t *perf_cmd; int64_t sample_batch; unused_parameter(unused); w_set_thread_name("perflog"); // Prep some things that we'll need each time we run a command { uint32_t env_size; w_ht_t *envpht = w_envp_make_ht(); char *statedir = dirname(strdup(watchman_state_file)); w_envp_set_cstring(envpht, "WATCHMAN_STATE_DIR", statedir); w_envp_set_cstring(envpht, "WATCHMAN_SOCK", get_sock_name()); envp = w_envp_make_from_ht(envpht, &env_size); } perf_cmd = cfg_get_json(NULL, "perf_logger_command"); if (json_is_string(perf_cmd)) { perf_cmd = json_pack("[O]", perf_cmd); } if (!json_is_array(perf_cmd)) { w_log( W_LOG_FATAL, "perf_logger_command must be either a string or an array of strings\n"); } sample_batch = cfg_get_int(NULL, "perf_logger_command_max_samples_per_call", 4); while (true) { pthread_mutex_lock(&perf_log_lock); if (!perf_log_samples) { pthread_cond_wait(&perf_log_cond, &perf_log_lock); } samples = perf_log_samples; perf_log_samples = NULL; pthread_mutex_unlock(&perf_log_lock); if (samples) { while (json_array_size(samples) > 0) { int i = 0; json_t *cmd = json_array(); posix_spawnattr_t attr; posix_spawn_file_actions_t actions; pid_t pid; char **argv = NULL; json_array_extend(cmd, perf_cmd); while (i < sample_batch && json_array_size(samples) > 0) { char *stringy = json_dumps(json_array_get(samples, 0), 0); json_array_append(cmd, typed_string_to_json(stringy, W_STRING_MIXED)); free(stringy); json_array_remove(samples, 0); i++; } argv = w_argv_copy_from_json(cmd, 0); if (!argv) { char *dumped = json_dumps(cmd, 0); w_log(W_LOG_FATAL, "error converting %s to an argv array\n", dumped); } posix_spawnattr_init(&attr); #ifdef POSIX_SPAWN_CLOEXEC_DEFAULT posix_spawnattr_setflags(&attr, POSIX_SPAWN_CLOEXEC_DEFAULT); #endif posix_spawn_file_actions_init(&actions); posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0666); posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, "/dev/null", O_WRONLY, 0666); posix_spawn_file_actions_addopen(&actions, STDERR_FILENO, "/dev/null", O_WRONLY, 0666); if (posix_spawnp(&pid, argv[0], &actions, &attr, argv, envp) == 0) { // There's no sense waiting here, because w_reap_children is called // by the reaper thread. } else { int err = errno; w_log(W_LOG_ERR, "failed to spawn %s: %s\n", argv[0], strerror(err)); } posix_spawnattr_destroy(&attr); posix_spawn_file_actions_destroy(&actions); free(argv); json_decref(cmd); } json_decref(samples); } } return NULL; }
void w_perf_log(w_perf_t *perf) { json_t *info; char *dumped = NULL; if (!perf->will_log) { return; } // Assemble a perf blob info = json_pack("{s:u, s:O, s:i, s:u}", // "description", perf->description, // "meta", perf->meta_data, // "pid", getpid(), // "version", PACKAGE_VERSION // ); #ifdef WATCHMAN_BUILD_INFO set_unicode_prop(info, "buildinfo", WATCHMAN_BUILD_INFO); #endif #define ADDTV(name, tv) \ set_prop(info, name, json_real(w_timeval_abs_seconds(tv))) ADDTV("elapsed_time", perf->duration); ADDTV("start_time", perf->time_begin); #ifdef HAVE_SYS_RESOURCE_H ADDTV("user_time", perf->usage.ru_utime); ADDTV("system_time", perf->usage.ru_stime); #define ADDU(n) set_prop(info, #n, json_integer(perf->usage.n)) ADDU(ru_maxrss); ADDU(ru_ixrss); ADDU(ru_idrss); ADDU(ru_minflt); ADDU(ru_majflt); ADDU(ru_nswap); ADDU(ru_inblock); ADDU(ru_oublock); ADDU(ru_msgsnd); ADDU(ru_msgrcv); ADDU(ru_nsignals); ADDU(ru_nvcsw); ADDU(ru_nivcsw); #endif // HAVE_SYS_RESOURCE_H #undef ADDU #undef ADDTV // Log to the log file dumped = json_dumps(info, 0); w_log(W_LOG_ERR, "PERF: %s\n", dumped); free(dumped); if (!cfg_get_json(NULL, "perf_logger_command")) { json_decref(info); return; } // Send this to our logging thread for async processing pthread_mutex_lock(&perf_log_lock); if (!perf_log_thread_started) { pthread_cond_init(&perf_log_cond, NULL); pthread_create(&perf_log_thr, NULL, perf_log_thread, NULL); perf_log_thread_started = true; } if (!perf_log_samples) { perf_log_samples = json_array(); } json_array_append_new(perf_log_samples, info); pthread_mutex_unlock(&perf_log_lock); pthread_cond_signal(&perf_log_cond); }
/* send a command to the server, handle callbacks (menus, getline, etc) and display data (map data, pline, player status, ...) and finally return the response to the command. A play_game response will longjmp() to the matching play_game request, so beware! */ json_t * send_receive_msg(const char *const volatile msgtype, json_t *volatile jmsg) { const char *volatile sendkey; char key[BUFSZ]; char oldkey[BUFSZ]; void *iter; volatile int retry_count = 3; if (conn_err && ex_jmp_buf_valid) longjmp(ex_jmp_buf, 1); /* quick connection sanity check and restoration attempt */ if (!test_restore_connection()) return NULL; if (!jmsg) return NULL; sendkey = msgtype; while (1) { /* send the message; keep the reference to jmsg */ json_t *send_msg = json_pack("{sO}", sendkey, jmsg); if (!send_json_msg(send_msg)) { json_decref(send_msg); if (retry_count-- > 0 && restart_connection()) continue; goto error; } json_decref(send_msg); receive_without_sending: ; /* receive the response */ json_t *recv_msg = receive_json_msg(); if (!recv_msg) { /* If no data is received, there must have been a network error. Presumably the send didn't succeed either and the sent data vanished, so reconnect. restart_connection() can longjmp back to play_game; if it doesn't, retry both send and receive. */ if (retry_count-- > 0 && restart_connection()) continue; goto error; } json_t *jdisplay = json_object_get(recv_msg, "display"); if (jdisplay) { if (json_is_array(jdisplay)) handle_display_list(jdisplay); else print_error ("New display list doesn't have the right data type."); json_object_del(recv_msg, "display"); } iter = json_object_iter(recv_msg); if (!iter) { print_error("Empty return object."); json_decref(recv_msg); json_decref(jmsg); return json_object(); } /* The string returned by json_object_iter_key is only valid while recv_msg exists. Since we still want the value afterwards, it must be copied. */ strncpy(key, json_object_iter_key(iter), BUFSZ - 1); if (!strcmp(key, "server_cancel")) { /* This message is special in that it can be called out of sequence, and has no response. */ json_decref(recv_msg); /* free it */ client_windowprocs.win_server_cancel(); goto receive_without_sending; } if (!strcmp(key, "load_progress")) { /* This message is only called in-sequence, but it still has no response. */ int progress; if (json_unpack(json_object_iter_value(iter), "{si!}", "progress", &progress) != -1) client_windowprocs.win_load_progress(progress); json_decref(recv_msg); /* free it */ goto receive_without_sending; } send_receive_recent_response = json_object_iter_value(iter); if (json_object_iter_next(recv_msg, iter)) print_error("Too many JSON objects in response data."); /* keep only the core of the response and throw away the wrapper */ json_incref(send_receive_recent_response); json_decref(recv_msg); if (strcmp(sendkey, "play_game") == 0) { /* We might need to longjmp back here. */ if (setjmp(playgame_jmp_buf) == 0) { playgame_jmp_buf_valid = 1; } else { playgame_jmp_buf_valid = 0; /* key, sendkey might have any value right now, but we know what they should be from the position in the control flow */ sendkey = "play_game"; memset(key, 0, sizeof key); strcpy(key, "play_game"); } } /* If the response type doesn't match the request type then either: - this is a callback that needs to be handled first; - this is a request to longjmp() back to nhnet_play_game. To simplify the control flow, our longjmp back upon receiving a play_game response is unconditional, and ends up cancelling itself out if a play_game message gets a play_game response. This also guarantees that playgame_jmp_buf_valid is only set while playgame_jmp_buf is actually on the call stack. */ if (strcmp(key, "play_game") == 0 && playgame_jmp_buf_valid) longjmp(playgame_jmp_buf, 1); if (strcmp(key, msgtype)) { json_t *srvmsg = send_receive_recent_response; /* The next line is unneccessary, but makes the control flow easier to follow in a debugger. */ send_receive_recent_response = 0; json_t *newmsg = handle_netcmd(key, msgtype, srvmsg); if (!newmsg) { /* server error */ if (error_retry_ok && retry_count-- > 0 && restart_connection()) continue; /* jmsg is still alive, use it again */ goto error; } json_decref(jmsg); jmsg = newmsg; strcpy(oldkey, key); sendkey = oldkey; /* send the callback data to the server and get a new response */ continue; } json_decref(jmsg); break; /* only loop via continue */ } json_t *response = send_receive_recent_response; send_receive_recent_response = 0; return response; error: json_decref(jmsg); close(sockfd); sockfd = -1; conn_err = TRUE; playgame_jmp_buf_valid = 0; if (ex_jmp_buf_valid) longjmp(ex_jmp_buf, 1); return NULL; }
static int do_connect(const char *host, int port, const char *user, const char *pass, const char *email, int reg_user) { int fd = -1, authresult; char ipv6_error[120], ipv4_error[120], errmsg[256]; json_t *jmsg, *jarr; /* try ipv6 */ if (fd == -1) fd = connect_server(host, port, FALSE, ipv6_error, 120); if (fd == -1) /* no ipv6 connection, try ipv4 */ fd = connect_server(host, port, TRUE, ipv4_error, 120); if (fd == -1) { /* both connection attempts failed: error message */ if (!ipv6_error[0] && !ipv4_error[0]) { snprintf(errmsg, 256, "No address for \"%s\" found!", host); print_error(errmsg); } if (ipv6_error[0]) { snprintf(errmsg, 256, "IPv6: %s", ipv6_error); print_error(errmsg); } if (ipv4_error[0]) { snprintf(errmsg, 256, "IPv4: %s", ipv4_error); print_error(errmsg); } sockfd = -1; net_active = FALSE; return NO_CONNECTION; } in_connect_disconnect = TRUE; sockfd = fd; jmsg = json_pack("{ss,ss}", "username", user, "password", pass); if (reg_user) { if (email) json_object_set_new(jmsg, "email", json_string(email)); jmsg = send_receive_msg("register", jmsg); } else { jmsg = send_receive_msg("auth", jmsg); } in_connect_disconnect = FALSE; if (!jmsg || json_unpack(jmsg, "{si*}", "return", &authresult) == -1) { if (jmsg) json_decref(jmsg); close(fd); net_active = FALSE; sockfd = -1; return NO_CONNECTION; } /* the "version" field in the response is optional */ if (json_unpack(jmsg, "{so*}", "version", &jarr) != -1 && json_is_array(jarr) && json_array_size(jarr) >= 3) { nhnet_server_ver.major = json_integer_value(json_array_get(jarr, 0)); nhnet_server_ver.minor = json_integer_value(json_array_get(jarr, 1)); nhnet_server_ver.patchlevel = json_integer_value(json_array_get(jarr, 2)); } json_decref(jmsg); if (host != saved_hostname) strncpy(saved_hostname, host, sizeof (saved_hostname)); if (user != saved_username) strncpy(saved_username, user, sizeof (saved_username)); if (pass != saved_password) strncpy(saved_password, pass, sizeof (saved_password)); saved_port = port; if (authresult == AUTH_SUCCESS_NEW) { conn_err = FALSE; net_active = TRUE; } else { net_active = FALSE; sockfd = -1; } return authresult; }
int main(int argc, char **argv) { redisContext *c; redisReply *reply; json_t *root; // json_error_t error; char *msg; int ret; char buf[BUFSIZ]; progname = argv[0]; // Capture signals signal(SIGINT, sig_handler); signal(SIGKILL, sig_handler); // Sleep for a bit so everything settles down // pve: was 64 sleep(2); fprintf(stderr, "%s started\n", progname); // This used to be portux.local, but portux is not great at spreading its address, so use IP // since it now runs on the portux, use localhost const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1"; int port = (argc > 2) ? atoi(argv[2]) : 6379; // initialize the stripping table init_table(); struct timeval timeout = { 1, 500000 }; // 1.5 seconds c = redisConnectWithTimeout(hostname, port, timeout); if (c == NULL || c->err) { if (c) { fprintf(stderr, "Connection error: %s\n", c->errstr); redisFree(c); } else { fprintf(stderr, "Connection error: can't allocate redis context\n"); } exit(1); } // open device for reading only if ((ret = initport(0)) == 0) { fprintf(stderr, "device opened ok\n"); } else { fprintf(stderr, "failed to initialize device\n"); close(fdDevice); fflush(stderr); exit(1); } // Create a JSON template root = json_object(); json_object_set (root, "t", json_pack("s", "all")); // set the type of message json_object_set (root, "e", json_pack("s", "newMessage")); // the event is newMessage // and the received entry goes into the parameter field // Main loop while ((ret = readln_time(buf,100))) { if (ret > 0 && strlen(buf) > 0) { // remove extraneous characters strip(buf, IS_CTRL); if (strlen(buf) > 0) { if (bStderr) fprintf (stderr, "Received Buf %s\n", buf); if (strncmp(buf, faulty, strlen(faulty)) != 0) { // and the received entry goes into the parameter field json_object_set (root, "p", json_pack("s", buf)); msg = json_dumps (root, JSON_COMPACT | JSON_ESCAPE_SLASH); if (bStderr) fprintf (stderr, "Publish %s\n", msg); /* Publish this set */ reply = redisCommand(c,"PUBLISH ss:event %s", msg); // printf("PUBLISH: %s\n", reply->str); freeReplyObject(reply); } } // if strlen > 0 } // if // Force the buffer to be empty buf[0] = (char) 0; } // while close(fdDevice); fprintf(stderr, "%s finished\n", progname); fflush(stderr); /* Disconnects and frees the context */ redisFree(c); return 0; }
static void run_tests() { json_t *j, *j2; int i1, i2, i3; json_int_t I1; int rv; size_t z; double f; char *s; json_error_t error; /* * Simple, valid json_pack cases */ /* true */ rv = json_unpack(json_true(), "b", &i1); if(rv || !i1) fail("json_unpack boolean failed"); /* false */ rv = json_unpack(json_false(), "b", &i1); if(rv || i1) fail("json_unpack boolean failed"); /* null */ if(json_unpack(json_null(), "n")) fail("json_unpack null failed"); /* integer */ j = json_integer(42); rv = json_unpack(j, "i", &i1); if(rv || i1 != 42) fail("json_unpack integer failed"); json_decref(j); /* json_int_t */ j = json_integer(5555555); rv = json_unpack(j, "I", &I1); if(rv || I1 != 5555555) fail("json_unpack json_int_t failed"); json_decref(j); /* real */ j = json_real(1.7); rv = json_unpack(j, "f", &f); if(rv || f != 1.7) fail("json_unpack real failed"); json_decref(j); /* number */ j = json_integer(12345); rv = json_unpack(j, "F", &f); if(rv || f != 12345.0) fail("json_unpack (real or) integer failed"); json_decref(j); j = json_real(1.7); rv = json_unpack(j, "F", &f); if(rv || f != 1.7) fail("json_unpack real (or integer) failed"); json_decref(j); /* string */ j = json_string("foo"); rv = json_unpack(j, "s", &s); if(rv || strcmp(s, "foo")) fail("json_unpack string failed"); json_decref(j); /* string with length (size_t) */ j = json_string("foo"); rv = json_unpack(j, "s%", &s, &z); if(rv || strcmp(s, "foo") || z != 3) fail("json_unpack string with length (size_t) failed"); json_decref(j); /* empty object */ j = json_object(); if(json_unpack(j, "{}")) fail("json_unpack empty object failed"); json_decref(j); /* empty list */ j = json_array(); if(json_unpack(j, "[]")) fail("json_unpack empty list failed"); json_decref(j); /* non-incref'd object */ j = json_object(); rv = json_unpack(j, "o", &j2); if(rv || j2 != j || j->refcount != 1) fail("json_unpack object failed"); json_decref(j); /* incref'd object */ j = json_object(); rv = json_unpack(j, "O", &j2); if(rv || j2 != j || j->refcount != 2) fail("json_unpack object failed"); json_decref(j); json_decref(j); /* simple object */ j = json_pack("{s:i}", "foo", 42); rv = json_unpack(j, "{s:i}", "foo", &i1); if(rv || i1 != 42) fail("json_unpack simple object failed"); json_decref(j); /* simple array */ j = json_pack("[iii]", 1, 2, 3); rv = json_unpack(j, "[i,i,i]", &i1, &i2, &i3); if(rv || i1 != 1 || i2 != 2 || i3 != 3) fail("json_unpack simple array failed"); json_decref(j); /* object with many items & strict checking */ j = json_pack("{s:i, s:i, s:i}", "a", 1, "b", 2, "c", 3); rv = json_unpack(j, "{s:i, s:i, s:i}", "a", &i1, "b", &i2, "c", &i3); if(rv || i1 != 1 || i2 != 2 || i3 != 3) fail("json_unpack object with many items failed"); json_decref(j); /* * Invalid cases */ j = json_integer(42); if(!json_unpack_ex(j, &error, 0, "z")) fail("json_unpack succeeded with invalid format character"); check_error("Unexpected format character 'z'", "<format>", 1, 1, 1); if(!json_unpack_ex(NULL, &error, 0, "[i]")) fail("json_unpack succeeded with NULL root"); check_error("NULL root value", "<root>", -1, -1, 0); json_decref(j); /* mismatched open/close array/object */ j = json_pack("[]"); if(!json_unpack_ex(j, &error, 0, "[}")) fail("json_unpack failed to catch mismatched ']'"); check_error("Unexpected format character '}'", "<format>", 1, 2, 2); json_decref(j); j = json_pack("{}"); if(!json_unpack_ex(j, &error, 0, "{]")) fail("json_unpack failed to catch mismatched '}'"); check_error("Expected format 's', got ']'", "<format>", 1, 2, 2); json_decref(j); /* missing close array */ j = json_pack("[]"); if(!json_unpack_ex(j, &error, 0, "[")) fail("json_unpack failed to catch missing ']'"); check_error("Unexpected end of format string", "<format>", 1, 2, 2); json_decref(j); /* missing close object */ j = json_pack("{}"); if(!json_unpack_ex(j, &error, 0, "{")) fail("json_unpack failed to catch missing '}'"); check_error("Unexpected end of format string", "<format>", 1, 2, 2); json_decref(j); /* garbage after format string */ j = json_pack("[i]", 42); if(!json_unpack_ex(j, &error, 0, "[i]a", &i1)) fail("json_unpack failed to catch garbage after format string"); check_error("Garbage after format string", "<format>", 1, 4, 4); json_decref(j); j = json_integer(12345); if(!json_unpack_ex(j, &error, 0, "ia", &i1)) fail("json_unpack failed to catch garbage after format string"); check_error("Garbage after format string", "<format>", 1, 2, 2); json_decref(j); /* NULL format string */ j = json_pack("[]"); if(!json_unpack_ex(j, &error, 0, NULL)) fail("json_unpack failed to catch null format string"); check_error("NULL or empty format string", "<format>", -1, -1, 0); json_decref(j); /* NULL string pointer */ j = json_string("foobie"); if(!json_unpack_ex(j, &error, 0, "s", NULL)) fail("json_unpack failed to catch null string pointer"); check_error("NULL string argument", "<args>", 1, 1, 1); json_decref(j); /* invalid types */ j = json_integer(42); j2 = json_string("foo"); if(!json_unpack_ex(j, &error, 0, "s")) fail("json_unpack failed to catch invalid type"); check_error("Expected string, got integer", "<validation>", 1, 1, 1); if(!json_unpack_ex(j, &error, 0, "n")) fail("json_unpack failed to catch invalid type"); check_error("Expected null, got integer", "<validation>", 1, 1, 1); if(!json_unpack_ex(j, &error, 0, "b")) fail("json_unpack failed to catch invalid type"); check_error("Expected true or false, got integer", "<validation>", 1, 1, 1); if(!json_unpack_ex(j2, &error, 0, "i")) fail("json_unpack failed to catch invalid type"); check_error("Expected integer, got string", "<validation>", 1, 1, 1); if(!json_unpack_ex(j2, &error, 0, "I")) fail("json_unpack failed to catch invalid type"); check_error("Expected integer, got string", "<validation>", 1, 1, 1); if(!json_unpack_ex(j, &error, 0, "f")) fail("json_unpack failed to catch invalid type"); check_error("Expected real, got integer", "<validation>", 1, 1, 1); if(!json_unpack_ex(j2, &error, 0, "F")) fail("json_unpack failed to catch invalid type"); check_error("Expected real or integer, got string", "<validation>", 1, 1, 1); if(!json_unpack_ex(j, &error, 0, "[i]")) fail("json_unpack failed to catch invalid type"); check_error("Expected array, got integer", "<validation>", 1, 1, 1); if(!json_unpack_ex(j, &error, 0, "{si}", "foo")) fail("json_unpack failed to catch invalid type"); check_error("Expected object, got integer", "<validation>", 1, 1, 1); json_decref(j); json_decref(j2); /* Array index out of range */ j = json_pack("[i]", 1); if(!json_unpack_ex(j, &error, 0, "[ii]", &i1, &i2)) fail("json_unpack failed to catch index out of array bounds"); check_error("Array index 1 out of range", "<validation>", 1, 3, 3); json_decref(j); /* NULL object key */ j = json_pack("{si}", "foo", 42); if(!json_unpack_ex(j, &error, 0, "{si}", NULL, &i1)) fail("json_unpack failed to catch null string pointer"); check_error("NULL object key", "<args>", 1, 2, 2); json_decref(j); /* Object key not found */ j = json_pack("{si}", "foo", 42); if(!json_unpack_ex(j, &error, 0, "{si}", "baz", &i1)) fail("json_unpack failed to catch null string pointer"); check_error("Object item not found: baz", "<validation>", 1, 3, 3); json_decref(j); /* * Strict validation */ j = json_pack("[iii]", 1, 2, 3); rv = json_unpack(j, "[iii!]", &i1, &i2, &i3); if(rv || i1 != 1 || i2 != 2 || i3 != 3) fail("json_unpack array with strict validation failed"); json_decref(j); j = json_pack("[iii]", 1, 2, 3); if(!json_unpack_ex(j, &error, 0, "[ii!]", &i1, &i2)) fail("json_unpack array with strict validation failed"); check_error("1 array item(s) left unpacked", "<validation>", 1, 5, 5); json_decref(j); /* Like above, but with JSON_STRICT instead of '!' format */ j = json_pack("[iii]", 1, 2, 3); if(!json_unpack_ex(j, &error, JSON_STRICT, "[ii]", &i1, &i2)) fail("json_unpack array with strict validation failed"); check_error("1 array item(s) left unpacked", "<validation>", 1, 4, 4); json_decref(j); j = json_pack("{s:s, s:i}", "foo", "bar", "baz", 42); rv = json_unpack(j, "{sssi!}", "foo", &s, "baz", &i1); if(rv || strcmp(s, "bar") != 0 || i1 != 42) fail("json_unpack object with strict validation failed"); json_decref(j); /* Unpack the same item twice */ j = json_pack("{s:s, s:i, s:b}", "foo", "bar", "baz", 42, "quux", 1); if(!json_unpack_ex(j, &error, 0, "{s:s,s:s!}", "foo", &s, "foo", &s)) fail("json_unpack object with strict validation failed"); { const char *possible_errors[] = { "2 object item(s) left unpacked: baz, quux", "2 object item(s) left unpacked: quux, baz" }; check_errors(possible_errors, 2, "<validation>", 1, 10, 10); } json_decref(j); j = json_pack("[i,{s:i,s:n},[i,i]]", 1, "foo", 2, "bar", 3, 4); if(json_unpack_ex(j, NULL, JSON_STRICT | JSON_VALIDATE_ONLY, "[i{sisn}[ii]]", "foo", "bar")) fail("json_unpack complex value with strict validation failed"); json_decref(j); /* ! and * must be last */ j = json_pack("[ii]", 1, 2); if(!json_unpack_ex(j, &error, 0, "[i!i]", &i1, &i2)) fail("json_unpack failed to catch ! in the middle of an array"); check_error("Expected ']' after '!', got 'i'", "<format>", 1, 4, 4); if(!json_unpack_ex(j, &error, 0, "[i*i]", &i1, &i2)) fail("json_unpack failed to catch * in the middle of an array"); check_error("Expected ']' after '*', got 'i'", "<format>", 1, 4, 4); json_decref(j); j = json_pack("{sssi}", "foo", "bar", "baz", 42); if(!json_unpack_ex(j, &error, 0, "{ss!si}", "foo", &s, "baz", &i1)) fail("json_unpack failed to catch ! in the middle of an object"); check_error("Expected '}' after '!', got 's'", "<format>", 1, 5, 5); if(!json_unpack_ex(j, &error, 0, "{ss*si}", "foo", &s, "baz", &i1)) fail("json_unpack failed to catch ! in the middle of an object"); check_error("Expected '}' after '*', got 's'", "<format>", 1, 5, 5); json_decref(j); /* Error in nested object */ j = json_pack("{s{snsn}}", "foo", "bar", "baz"); if(!json_unpack_ex(j, &error, 0, "{s{sn!}}", "foo", "bar")) fail("json_unpack nested object with strict validation failed"); check_error("1 object item(s) left unpacked: baz", "<validation>", 1, 7, 7); json_decref(j); /* Error in nested array */ j = json_pack("[[ii]]", 1, 2); if(!json_unpack_ex(j, &error, 0, "[[i!]]", &i1)) fail("json_unpack nested array with strict validation failed"); check_error("1 array item(s) left unpacked", "<validation>", 1, 5, 5); json_decref(j); /* Optional values */ j = json_object(); i1 = 0; if(json_unpack(j, "{s?i}", "foo", &i1)) fail("json_unpack failed for optional key"); if(i1 != 0) fail("json_unpack unpacked an optional key"); json_decref(j); i1 = 0; j = json_pack("{si}", "foo", 42); if(json_unpack(j, "{s?i}", "foo", &i1)) fail("json_unpack failed for an optional value"); if(i1 != 42) fail("json_unpack failed to unpack an optional value"); json_decref(j); j = json_object(); i1 = i2 = i3 = 0; if(json_unpack(j, "{s?[ii]s?{s{si}}}", "foo", &i1, &i2, "bar", "baz", "quux", &i3)) fail("json_unpack failed for complex optional values"); if(i1 != 0 || i2 != 0 || i3 != 0) fail("json_unpack unexpectedly unpacked something"); json_decref(j); j = json_pack("{s{si}}", "foo", "bar", 42); if(json_unpack(j, "{s?{s?i}}", "foo", "bar", &i1)) fail("json_unpack failed for complex optional values"); if(i1 != 42) fail("json_unpack failed to unpack"); json_decref(j); /* Combine ? and ! */ j = json_pack("{si}", "foo", 42); i1 = i2 = 0; if(json_unpack(j, "{sis?i!}", "foo", &i1, "bar", &i2)) fail("json_unpack failed for optional values with strict mode"); if(i1 != 42) fail("json_unpack failed to unpack"); if(i2 != 0) fail("json_unpack failed to unpack"); json_decref(j); /* But don't compensate a missing key with an optional one. */ j = json_pack("{sisi}", "foo", 42, "baz", 43); i1 = i2 = i3 = 0; if(!json_unpack_ex(j, &error, 0, "{sis?i!}", "foo", &i1, "bar", &i2)) fail("json_unpack failed for optional values with strict mode and compensation"); check_error("1 object item(s) left unpacked: baz", "<validation>", 1, 8, 8); json_decref(j); }
static int _nd_accum_recursively_build_json(nd_accum_t a, json_t *j_rows, json_t *j_row, int axis_idx, int offset) { int i, j, idx, next_offset; json_t *x; json_t *j_row_next; nd_axis_struct *axis; int result; result = 0; /* define the current axis */ axis = a->axes + axis_idx; /* terminate recursion */ if (axis_idx == a->ndim) { double d; d = _arb_get_d(a->data + offset); if (j_row) { j_row_next = json_deep_copy(j_row); x = json_real(d); json_array_append_new(j_row_next, x); } else { j_row_next = json_pack("[f]", d); } json_array_append_new(j_rows, j_row_next); return result; } if (axis->agg_weights) { /* skip aggregated axes */ next_offset = offset; result = _nd_accum_recursively_build_json( a, j_rows, j_row, axis_idx+1, next_offset); } else { /* add selections to the row, and update the offset */ for (i = 0; i < axis->k; i++) { idx = axis->selection[i]; if (j_row) { j_row_next = json_deep_copy(j_row); } else { j_row_next = json_array(); } if (axis->component_axes != NULL) { for (j = 0; j < axis->component_axis_count; j++) { int component_idx; component_idx = axis->component_axes[j].indices[i]; x = json_integer(component_idx); json_array_append_new(j_row_next, x); } } else { x = json_integer(idx); json_array_append_new(j_row_next, x); } next_offset = offset + idx * a->strides[axis_idx]; result = _nd_accum_recursively_build_json( a, j_rows, j_row_next, axis_idx+1, next_offset); if (result) return result; json_decref(j_row_next); } } return result; }
int __cdecl wmain(int argc, wchar_t *wargv[]) { int ret = 0; // Global URL cache to not download anything twice json_t *url_cache = json_object(); // Repository ID cache to prioritize the most local repository if more // than one repository with the same name is discovered in the network json_t *id_cache = json_object(); json_t *repo_list = NULL; const char *start_repo = "http://thcrap.nmlgc.net/repos/nmlgc/"; json_t *sel_stack = NULL; json_t *new_cfg = json_pack("{s[]}", "patches"); size_t cur_dir_len = GetCurrentDirectory(0, NULL) + 1; VLA(char, cur_dir, cur_dir_len); json_t *games = NULL; const char *run_cfg_fn = NULL; const char *run_cfg_fn_js = NULL; char *run_cfg_str = NULL; json_t *args = json_array_from_wchar_array(argc, wargv); wine_flag = GetProcAddress( GetModuleHandleA("kernel32.dll"), "wine_get_unix_file_name" ) != 0; strings_mod_init(); log_init(1); // Necessary to correctly process *any* input of non-ASCII characters // in the console subsystem w32u8_set_fallback_codepage(GetOEMCP()); GetCurrentDirectory(cur_dir_len, cur_dir); PathAddBackslashA(cur_dir); str_slash_normalize(cur_dir); // Maximize the height of the console window... unless we're running under // Wine, where this 1) doesn't work and 2) messes up the console buffer if(!wine_flag) { CONSOLE_SCREEN_BUFFER_INFO sbi = {0}; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); COORD largest = GetLargestConsoleWindowSize(console); HWND console_wnd = GetConsoleWindow(); RECT console_rect; GetWindowRect(console_wnd, &console_rect); SetWindowPos(console_wnd, NULL, console_rect.left, 0, 0, 0, SWP_NOSIZE); GetConsoleScreenBufferInfo(console, &sbi); sbi.srWindow.Bottom = largest.Y - 4; SetConsoleWindowInfo(console, TRUE, &sbi.srWindow); } http_init(); if(json_array_size(args) > 1) { start_repo = json_array_get_string(args, 1); } log_printf( "==========================================\n" "Touhou Community Reliant Automatic Patcher - Patch configuration tool\n" "==========================================\n" "\n" "\n" "This tool will create a new patch configuration for the\n" "Touhou Community Reliant Automatic Patcher.\n" "\n" "\n" "The configuration process has two steps:\n" "\n" "\t\t1. Selecting patches\n" "\t\t2. Download game-independent data\n" "\t\t3. Locating game installations\n" "\t\t4. Download game-specific data\n" "\n" "\n" "\n" "Patch repository discovery will start at\n" "\n" "\t%s\n" "\n" "You can specify a different URL as a command-line parameter.\n" "Additionally, all patches from previously discovered repositories, stored in\n" "subdirectories of the current directory, will be available for selection.\n" "\n" "\n", start_repo ); pause(); if(RepoDiscoverAtURL(start_repo, id_cache, url_cache)) { goto end; } if(RepoDiscoverFromLocal(id_cache, url_cache)) { goto end; } repo_list = RepoLoad(); if(!json_object_size(repo_list)) { log_printf("No patch repositories available...\n"); pause(); goto end; } sel_stack = SelectPatchStack(repo_list); if(json_array_size(sel_stack)) { json_t *new_cfg_patches = json_object_get(new_cfg, "patches"); size_t i; json_t *sel; log_printf("Downloading game-independent data...\n"); stack_update(update_filter_global, NULL); /// Build the new run configuration json_array_foreach(sel_stack, i, sel) { json_array_append_new(new_cfg_patches, patch_build(sel)); } }
/* since /root <timestamp> [patterns] */ static void cmd_since(struct watchman_client *client, json_t *args) { const char *clockspec; w_root_t *root; w_query *query; char *errmsg = NULL; struct w_query_field_list field_list; w_query_res res; json_t *response, *clock_ele; json_t *file_list; char clockbuf[128]; /* resolve the root */ if (json_array_size(args) < 3) { send_error_response(client, "not enough arguments for 'since'"); return; } root = resolve_root_or_err(client, args, 1, false); if (!root) { return; } clock_ele = json_array_get(args, 2); clockspec = json_string_value(clock_ele); if (!clockspec) { send_error_response(client, "expected argument 2 to be a valid clockspec"); w_root_delref(root); return; } query = w_query_parse_legacy(args, &errmsg, 3, NULL, clockspec, NULL); if (errmsg) { send_error_response(client, "%s", errmsg); free(errmsg); w_root_delref(root); return; } w_query_legacy_field_list(&field_list); if (!w_query_execute(query, root, &res, NULL, NULL)) { send_error_response(client, "query failed: %s", res.errmsg); w_query_result_free(&res); w_root_delref(root); w_query_delref(query); return; } w_query_delref(query); file_list = w_query_results_to_json(&field_list, res.num_results, res.results); w_query_result_free(&res); response = make_response(); if (clock_id_string(res.root_number, res.ticks, clockbuf, sizeof(clockbuf))) { set_prop(response, "clock", json_string_nocheck(clockbuf)); } set_prop(response, "is_fresh_instance", json_pack("b", res.is_fresh_instance)); set_prop(response, "files", file_list); send_and_dispose_response(client, response); w_root_delref(root); }
static int send_stats(struct mg_connection *conn) { struct brubeck_server *brubeck = conn->server_param; json_t *stats, *secure, *backends, *samplers; int i; backends = json_array(); for (i = 0; i < brubeck->active_backends; ++i) { struct brubeck_backend *backend = brubeck->backends[i]; if (backend->type == BRUBECK_BACKEND_CARBON) { struct brubeck_carbon *carbon = (struct brubeck_carbon *)backend; struct sockaddr_in *address = &carbon->out_sockaddr; char addr[INET_ADDRSTRLEN]; json_array_append_new(backends, json_pack("{s:s, s:i, s:b, s:s, s:i, s:I}", "type", "carbon", "sample_freq", (int)carbon->backend.sample_freq, "connected", (carbon->out_sock >= 0), "address", inet_ntop(AF_INET, &address->sin_addr.s_addr, addr, INET_ADDRSTRLEN), "port", (int)ntohs(address->sin_port), "sent", (json_int_t)carbon->sent )); } } samplers = json_array(); for (i = 0; i < brubeck->active_samplers; ++i) { struct brubeck_sampler *sampler = brubeck->samplers[i]; struct sockaddr_in *address = &sampler->addr; char addr[INET_ADDRSTRLEN]; const char *sampler_name = NULL; switch (sampler->type) { case BRUBECK_SAMPLER_STATSD: sampler_name = "statsd"; break; case BRUBECK_SAMPLER_STATSD_SECURE: sampler_name = "statsd_secure"; break; default: assert(0); } json_array_append_new(samplers, json_pack("{s:s, s:f, s:s, s:i}", "type", sampler_name, "sample_freq", (double)sampler->current_flow, "address", inet_ntop(AF_INET, &address->sin_addr.s_addr, addr, INET_ADDRSTRLEN), "port", (int)ntohs(address->sin_port) )); } secure = json_pack("{s:i, s:i, s:i, s:i}", "failed", brubeck->stats.secure.failed, "from_future", brubeck->stats.secure.from_future, "delayed", brubeck->stats.secure.delayed, "replayed", brubeck->stats.secure.replayed ); stats = json_pack("{s:s, s:i, s:i, s:i, s:i, s:o, s:o, s:o}", "version", "brubeck " GIT_SHA, "metrics", brubeck->stats.metrics, "errors", brubeck->stats.errors, "unique_keys", brubeck->stats.unique_keys, "memory", brubeck->stats.memory, "secure", secure, "backends", backends, "samplers", samplers); json_dump_callback(stats, &dump_json, (void *)conn, JSON_INDENT(4) | JSON_PRESERVE_ORDER); json_decref(stats); return MG_TRUE; }
// @todo - we need to construct the correct video resource json bool YouTubeModel::addVideoToUploadQueue(YouTubeVideo video) { if(!video.filename.size()) { RX_ERROR("Cannot add a video which has no filename set"); return false; } std::string filepath = video.filename; if(video.datapath) { filepath = rx_to_data_path(video.filename); } size_t fsize = rx_get_file_size(filepath); if(!fsize) { RX_ERROR("Filesize of %s returned %ld", filepath.c_str(), fsize); return false; } #if USE_JSON_PACK // @todo - libjansson is used as DLL, and json_dumps // is supposed to free() the memory; this is icky and // libjansson should free() any allocated mem as it's used // as a dll std::string video_json; char* video_resource = NULL; json_t* body = NULL; if(!video.video_resource_json.size()) { body = json_pack("{ s: {s:s}, s: { s:s, s:i, s:s, s:s } }", "status", "privacyStatus", "private", "snippet", "tags", video.tags.c_str(), "categoryId", video.category, "description", video.description.c_str(), "title", video.title.c_str()); video_resource = json_dumps(body, JSON_INDENT(0)); json_decref(body); video_json.assign(video_resource, strlen(video_resource)); if(!video_resource) { RX_ERROR("Cannot create JSON video resource string"); return false; } } else { video_json = video.video_resource_json; } #else std::string video_json; if(!video.video_resource_json.size()) { std::stringstream ss; ss << "{ \"status\": { \"privacyStatus\" : \"private\" }, " << "\"snippet\": {" << "\"title\":\"" << video.title << "\", " << "\"tags\":\"" << video.tags << "\", " << "\"categoryId\":" << video.category << ", " << "\"description\":\"" << video.description << "\"" << "}" << "}"; video_json = ss.str(); } else { video_json = video.video_resource_json; } #endif bool r = db.insert("videos") .use("filename", video.filename) .use("state", YT_VIDEO_STATE_NONE) .use("bytes_total", fsize) .use("video_resource_json", video_json) .use("datapath", (video.datapath) ? 1 : 0) .use("title", video.title) .use("description", video.description) .use("tags", video.tags) .use("privacy_status", video.privacy_status) .use("category", video.category) .execute(); #if USE_JSON_PACK if(video_resource) { free(video_resource); video_resource = NULL; } #endif if(r) { RX_VERBOSE("Added video to the queue: %s", video.filename.c_str()); } else { RX_ERROR("Error while trying to add: %s to the video upload queue", video.filename.c_str()); } return r; }
static bool alg_wrap_wrp(const jose_hook_alg_t *alg, jose_cfg_t *cfg, json_t *jwe, json_t *rcp, const json_t *jwk, json_t *cek) { const jose_hook_alg_t *ecdh = NULL; json_auto_t *exc = NULL; json_auto_t *hdr = NULL; json_auto_t *epk = NULL; json_auto_t *der = NULL; const char *wrap = NULL; json_t *h = NULL; if (json_object_get(cek, "k")) { if (strcmp(alg->name, "ECDH-ES") == 0) return false; } else if (!jose_jwk_gen(cfg, cek)) { return false; } hdr = jose_jwe_hdr(jwe, rcp); if (!hdr) return false; h = json_object_get(rcp, "header"); if (!h && json_object_set_new(rcp, "header", h = json_object()) == -1) return false; epk = json_pack("{s:s,s:O}", "kty", "EC", "crv", json_object_get(jwk, "crv")); if (!epk) return false; if (!jose_jwk_gen(cfg, epk)) return false; ecdh = jose_hook_alg_find(JOSE_HOOK_ALG_KIND_EXCH, "ECDH"); if (!ecdh) return false; exc = ecdh->exch.exc(ecdh, cfg, epk, jwk); if (!exc) return false; if (!jose_jwk_pub(cfg, epk)) return false; if (json_object_set(h, "epk", epk) == -1) return false; der = derive(alg, cfg, hdr, cek, exc); if (!der) return false; wrap = strchr(alg->name, '+'); if (wrap) { const jose_hook_alg_t *kw = NULL; kw = jose_hook_alg_find(JOSE_HOOK_ALG_KIND_WRAP, &wrap[1]); if (!kw) return false; return kw->wrap.wrp(kw, cfg, jwe, rcp, der, cek); } if (json_object_update(cek, der) < 0) return false; return add_entity(jwe, rcp, "recipients", "header", "encrypted_key", NULL); }
{ enableField (FIELD_SCOPE_KEY, true, false); enableField (FIELD_SCOPE_KIND_LONG, true, false); } for (k = FIELD_EXTENSION_START; k <= FIELD_BUILTIN_LAST; k++) renderExtensionFieldMaybe (k, tag, response); } static int writeJsonEntry (tagWriter *writer CTAGS_ATTR_UNUSED, MIO * mio, const tagEntryInfo *const tag) { json_t *pat = escapeFieldValue(tag, FIELD_PATTERN, true); json_t *response = json_pack ("{ss ss ss sO}", "_type", "tag", "name", tag->name, "path", tag->sourceFileName, "pattern", pat); json_decref (pat); if (includeExtensionFlags ()) { addExtensionFields (response, tag); addParserFields (response, tag); } char *buf = json_dumps (response, JSON_PRESERVE_ORDER); int length = mio_printf (mio, "%s\n", buf); free (buf); json_decref (response);