status_t windows_system_map_symbol_to_address( vmi_instance_t vmi, const char *symbol, const char *subsymbol, addr_t *address) { status_t ret = VMI_FAILURE; windows_instance_t windows = vmi->os_data; if(!windows || !symbol) { goto exit; } json_error_t error; json_t *root = json_load_file(windows->sysmap, 0, &error); if(!root) { errprint("Rekall profile error on line %d: %s\n", error.line, error.text); goto exit; } if(!json_is_object(root)) { errprint("Rekall profile: root is not an objet\n"); goto err_exit; } if(!subsymbol) { json_t *constants = json_object_get(root, "$CONSTANTS"); json_t *jsymbol = json_object_get(constants, symbol); if(!jsymbol) { dbprint(VMI_DEBUG_MISC, "Rekall profile: symbol '%s' not found\n", symbol); goto err_exit; } *address = json_integer_value(jsymbol); ret = VMI_SUCCESS; } else { json_t *structs = json_object_get(root, "$STRUCTS"); json_t *jstruct = json_object_get(structs, symbol); if(!jstruct) { dbprint(VMI_DEBUG_MISC, "Rekall profile: structure '%s' not found\n", symbol); goto err_exit; } json_t *jstruct2 = json_array_get(jstruct, 1); json_t *jmember = json_object_get(jstruct2, subsymbol); if(!jmember) { dbprint(VMI_DEBUG_MISC, "Rekall profile: structure member '%s' not found\n", subsymbol); goto err_exit; } json_t *jvalue = json_array_get(jmember, 0); *address = json_integer_value(jvalue); ret = VMI_SUCCESS; } err_exit: json_decref(root); exit: return ret; }
void JsonApiV3::processApi(const string &data) { Params jsonRoot; Params jsonData; //parse the json data json_error_t jerr; json_t *jroot = json_loads(data.c_str(), 0, &jerr); if (!jroot || !json_is_object(jroot)) { cDebugDom("network") << "Error loading json : " << jerr.text; return; } char *d = json_dumps(jroot, JSON_INDENT(4)); if (d) { cDebugDom("network") << d; free(d); } //decode the json root object into jsonParam jansson_decode_object(jroot, jsonRoot); json_t *jdata = json_object_get(jroot, "data"); if (jdata) jansson_decode_object(jdata, jsonData); //Format: { msg: "type", msg_id: id, data: {} } if (jsonRoot["msg"] == "login") { //check for if username/password matches string user = Utils::get_config_option("calaos_user"); string pass = Utils::get_config_option("calaos_password"); if (Utils::get_config_option("cn_user") != "" && Utils::get_config_option("cn_pass") != "") { user = Utils::get_config_option("cn_user"); pass = Utils::get_config_option("cn_pass"); } //Not logged in, need to wait for a correct login if (user != jsonData["cn_user"] || pass != jsonData["cn_pass"]) { cDebugDom("network") << "Login failed!"; json_t *jret = json_object(); json_object_set_new(jret, "success", json_string("false")); sendJson("login", jret, jsonRoot["msg_id"]); //Close the connection on login failure closeConnection.emit(WebSocket::CloseCodeNormal, "login failed!"); } else { json_t *jret = json_object(); json_object_set_new(jret, "success", json_string("true")); sendJson("login", jret, jsonRoot["msg_id"]); loggedin = true; } } else if (loggedin) //only process other api if loggedin { if (jsonRoot["msg"] == "get_home") processGetHome(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_state") processGetState(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "set_state") processSetState(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_playlist") processGetPlaylist(jsonData, jsonRoot["msg_id"]); // else if (jsonParam["action"] == "get_cover") // processGetCover(); // else if (jsonParam["action"] == "get_camera_pic") // processGetCameraPic(); // else if (jsonParam["action"] == "config") // processConfig(jroot); } json_decref(jroot); json_decref(jdata); }
int sendOrder(Parameters& params, std::string direction, double quantity, double price){ *params.logFile << "<SevenNintySix> Authenticating API credentials..." << std::endl; std::ostringstream oss; oss << "appid=" << params.sevennintysixAppId << "×tamp=" << time(0) << "&apikey=" << params.sevennintysixApi << "&sig=" << params.sevennintysixSecret; std::string signature = oss.str(); // Initialize HMAC object. HMAC_CTX ctx; HMAC_CTX_init(&ctx); // Set HMAC key. HMAC_Init_ex(&ctx, reinterpret_cast<const unsigned char*>(params.sevennintysixSecret.c_str()), params.sevennintysixSecret.length(), EVP_sha1(), NULL); // May be called repeatedly to insert all your data. HMAC_Update(&ctx, reinterpret_cast<const unsigned char*>(signature.c_str()), signature.length()); unsigned int result_len; unsigned char * result; // Finish HMAC computation and fetch result. HMAC_Final(&ctx, result, &result_len); // Done with HMAC object. HMAC_CTX_cleanup(&ctx); *params.logFile << result << std::endl; std::string api_sign_header = base64_encode(result, sizeof(result)/sizeof(*result) ); signature += "&sig=" + api_sign_header; json_t* root = authRequest(params, "https://796.com/oauth/token", "", signature); const char* access_token = json_string_value(json_object_get(root, "access_token")); if (access_token != NULL) *params.logFile << "ACCESS TOKEN: " << access_token << std::endl; else exit(1); *params.logFile << "<SevenNintySix> Trying to send a \"" << direction << "\" limit order: " << quantity << "@$" << limPrice << "..." << std::endl; oss.clear(); oss << "times=" << "10" << "&sell_num=" << quantity << "&sell_price=" << limPrice << "&access_token=" << access_token; std::string options = oss.str(); int orderId; if (direction.compare("sell") == 0){ json_t* root= authRequest(params, "https://796.com/v1/weeklyfutures/open_sell", "", options); orderId = json_integer_value(json_object_get(root, "id")); *params.logFile << "<SevenNintySix> Done (order ID: " << orderId << ")\n" << std::endl; } else{ json_t* root= authRequest(params, "https://796.com/v1/weeklyfutures/close_sell", "", options); orderId = json_integer_value(json_object_get(root, "id")); *params.logFile << "<SevenNintySix> Done (order ID: " << orderId << ")\n" << std::endl; } json_decref(root); return orderId; }
/** * Parse internal configuration JSON * * @param trc configuration structure to fill in * @param jint internal configuration JSON object * @return TR_CFG_SUCCESS or an error code */ TR_CFG_RC tr_cfg_parse_internal(TR_CFG *trc, json_t *jint) { json_t *jtmp = NULL; const char *s = NULL; if ((!trc) || (!jint)) return TR_CFG_BAD_PARAMS; /* If we don't yet have an internal config, allocate one and set defaults. If it * already exists, do not disturb existing settings. */ if (NULL == trc->internal) { if (NULL == (trc->internal = talloc_zero(trc, TR_CFG_INTERNAL))) return TR_CFG_NOMEM; set_defaults(trc->internal); /* Install defaults for any unspecified settings */ } const char *allowed_keys[] = {"hostname", "cfg_poll_interval", "cfg_settling_time", "logging", "tid_protocol", "tr_protocol", "monitoring", "tids_port", 0}; const char *obsolete_keys[] = {"tids_port", "trps_port", "trp_connect_interval", "trp_sweep_interval", "trp_update_interval", "tid_request_timeout", "tid_response_numerator", "tid_response_denominator", 0}; if (!check_allowed_keys(jint, allowed_keys, obsolete_keys)) return TR_CFG_NOPARSE; /* Parse the main section */ NOPARSE_UNLESS(tr_cfg_parse_string(jint, "hostname", &(trc->internal->hostname))); talloc_steal(trc->internal, trc->internal->hostname); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jint, "cfg_poll_interval", &(trc->internal->cfg_poll_interval))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jint, "cfg_settling_time", &(trc->internal->cfg_settling_time))); NOPARSE_UNLESS(tr_cfg_parse_integer(jint, "tids_port", &(trc->internal->tids_port))); NOPARSE_UNLESS(tr_cfg_parse_integer(jint, "trps_port", &(trc->internal->trps_port))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jint, "trp_connect_interval", &(trc->internal->trp_connect_interval))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jint, "trp_sweep_interval", &(trc->internal->trp_sweep_interval))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jint, "trp_update_interval", &(trc->internal->trp_update_interval))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jint, "tid_request_timeout", &(trc->internal->tid_req_timeout))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jint, "tid_response_numerator", &(trc->internal->tid_resp_numer))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jint, "tid_response_denominator", &(trc->internal->tid_resp_denom))); /* Parse the logging section */ if (NULL != (jtmp = json_object_get(jint, "logging"))) { const char *allowed_keys[] = {"log_threshold", "console_threshold", 0}; if (!check_allowed_keys(jtmp, allowed_keys, NULL)) return TR_CFG_NOPARSE; NOPARSE_UNLESS(tr_cfg_parse_string(jtmp, "log_threshold", &s)); if (s) { trc->internal->log_threshold = str2sev(s); talloc_free((void *) s); } NOPARSE_UNLESS(tr_cfg_parse_string(jtmp, "console_threshold", &s)); if (s) { trc->internal->console_threshold = str2sev(s); talloc_free((void *) s); } } /* Parse the monitoring section */ if (NULL != (jtmp = json_object_get(jint, "monitoring"))) { NOPARSE_UNLESS(tr_cfg_parse_monitoring(trc, jtmp)); } /* Parse the tid_protocol section */ if (NULL != (jtmp = json_object_get(jint, "tid_protocol"))) { const char *allowed_keys[] = {"port", "request_timeout", "response_numerator", "response_denominator", 0}; if (!check_allowed_keys(jtmp, allowed_keys, NULL)) return TR_CFG_NOPARSE; NOPARSE_UNLESS(tr_cfg_parse_integer(jtmp, "port", &(trc->internal->tids_port))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jtmp, "request_timeout", &(trc->internal->tid_req_timeout))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jtmp, "response_numerator", &(trc->internal->tid_resp_numer))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jtmp, "response_denominator", &(trc->internal->tid_resp_denom))); } /* Parse the tr_protocol section */ if (NULL != (jtmp = json_object_get(jint, "tr_protocol"))) { const char *allowed_keys[] = {"port", "connect_interval", "sweep_interval", "update_interval", 0}; if (!check_allowed_keys(jtmp, allowed_keys, NULL)) return TR_CFG_NOPARSE; NOPARSE_UNLESS(tr_cfg_parse_integer(jtmp, "port", &(trc->internal->trps_port))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jtmp, "connect_interval", &(trc->internal->trp_connect_interval))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jtmp, "sweep_interval", &(trc->internal->trp_sweep_interval))); NOPARSE_UNLESS(tr_cfg_parse_unsigned(jtmp, "update_interval", &(trc->internal->trp_update_interval))); } tr_debug("tr_cfg_parse_internal: Internal config parsed."); return TR_CFG_SUCCESS; }
void MessageListener::handleMessage(CcnetMessage *message) { // qWarning("got a message: %s %s.", message->app, message->body); char *type = NULL; char *content = NULL; if (IS_APP_MSG(message, kAppletCommandsMQ)) { if (g_strcmp0(message->body, "quit") == 0) { qWarning("[Message Listener] Got a quit command. Quit now."); QCoreApplication::exit(0); return; } if (g_strcmp0(message->body, "syn_activate") == 0) { qWarning("[Message Listener] Got an activate command."); CcnetMessage *ack_message; ack_message = ccnet_message_new(async_client_->base.id, async_client_->base.id, kAppletCommandsMQ, "ack_activate", 0); ccnet_mqclient_proc_put_message(mqclient_proc_, ack_message); ccnet_message_free(ack_message); seafApplet->mainWindow()->showWindow(); } const char *kOpenLocalFilePrefix = "open-local-file\t"; if (strstr(message->body, kOpenLocalFilePrefix) == message->body) { OpenLocalHelper::instance()->openLocalFile(QUrl::fromEncoded(message->body + strlen(kOpenLocalFilePrefix))); } } else if (IS_APP_MSG(message, kSeafileNotificationsMQ)) { if (parse_seafile_notification (message->body, &type, &content) < 0) return; if (strcmp(type, "transfer") == 0) { // empty } else if (strcmp(type, "repo.deleted_on_relay") == 0) { QString buf = tr("\"%1\" is unsynced. \nReason: Deleted on server").arg(QString::fromUtf8(content)); seafApplet->trayIcon()->showMessage(getBrand(), buf); } else if (strcmp(type, "sync.done") == 0) { /* format: repo_name \t repo_id \t description */ QStringList slist = QString::fromUtf8(content).split("\t"); if (slist.count() != 3) { qWarning("Bad sync.done message format"); return; } QString title = tr("\"%1\" is synchronized").arg(slist.at(0)); QString repo_id = slist.at(1).trimmed(); QString buf = slist.at(2).trimmed(); seafApplet->trayIcon()->showMessageWithRepo(repo_id, title, translateCommitDesc(buf)); } else if (strcmp(type, "sync.conflict") == 0) { json_error_t error; json_t *object = json_loads(content, 0, &error); if (!object) { qWarning("Failed to parse json: %s", error.text); return; } QString title = QString::fromUtf8(json_string_value(json_object_get(object, "repo_name"))); QString path = QString::fromUtf8(json_string_value(json_object_get(object, "path"))); QString msg = tr("File %1 conflict").arg(path); seafApplet->trayIcon()->showMessage(title, msg); json_decref(object); } else if (strcmp(type, "sync.access_denied") == 0) { /* format: <repo_name\trepo_id> */ QStringList slist = QString::fromUtf8(content).split("\t"); if (slist.count() != 2) { qWarning("Bad sync.access_denied message format"); return; } QString buf = tr("\"%1\" failed to sync. \nAccess denied to service").arg(slist.at(0)); seafApplet->trayIcon()->showMessage(getBrand(), buf); } else if (strcmp(type, "sync.quota_full") == 0) { /* format: <repo_name\trepo_id> */ QStringList slist = QString::fromUtf8(content).split("\t"); if (slist.count() != 2) { qWarning("Bad sync.quota_full message format"); return; } QString buf = tr("\"%1\" failed to sync.\nThe library owner's storage space is used up.").arg(slist.at(0)); seafApplet->trayIcon()->showMessage(getBrand(), buf); #if defined(Q_OS_MAC) } else if (strcmp(type, "repo.setwktree") == 0) { //seafile_set_repofolder_icns (content); } else if (strcmp(type, "repo.unsetwktree") == 0) { //seafile_unset_repofolder_icns (content); #endif } } }
static void run_tests() { json_t *value; int i; 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 != (ssize_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 != (ssize_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 != (ssize_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 != (ssize_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 != (ssize_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 != (ssize_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 != (ssize_t)1) fail("json_pack string 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 != (ssize_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 != (ssize_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 != (ssize_t)1) fail("json_pack integer 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 != (ssize_t)2) fail("json_pack integer refcount failed"); json_decref(value); json_decref(value); /* 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 != (ssize_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); /* 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 object key", "<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 in 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); }
static TID_REQ *tr_msg_decode_tidreq(json_t *jreq) { TID_REQ *treq = NULL; json_t *jrp_realm = NULL; json_t *jrealm = NULL; json_t *jcomm = NULL; json_t *jorig_coi = NULL; json_t *jdh = NULL; json_t *jpath = NULL; json_t *jexpire_interval = NULL; if (!(treq =tid_req_new())) { tr_crit("tr_msg_decode_tidreq(): Error allocating TID_REQ structure."); return NULL; } /* store required fields from request */ if ((NULL == (jrp_realm = json_object_get(jreq, "rp_realm"))) || (NULL == (jrealm = json_object_get(jreq, "target_realm"))) || (NULL == (jcomm = json_object_get(jreq, "community")))) { tr_notice("tr_msg_decode(): Error parsing required fields."); tid_req_free(treq); return NULL; } jpath = json_object_get(jreq, "path"); jexpire_interval = json_object_get(jreq, "expiration_interval"); treq->rp_realm = tr_new_name((char *)json_string_value(jrp_realm)); treq->realm = tr_new_name((char *)json_string_value(jrealm)); treq->comm = tr_new_name((char *)json_string_value(jcomm)); /* Get DH Info from the request */ if (NULL == (jdh = json_object_get(jreq, "dh_info"))) { tr_debug("tr_msg_decode(): Error parsing dh_info."); tid_req_free(treq); return NULL; } treq->tidc_dh = tr_msg_decode_dh(jdh); /* store optional "orig_coi" field */ if (NULL != (jorig_coi = json_object_get(jreq, "orig_coi"))) { treq->orig_coi = tr_new_name((char *)json_string_value(jorig_coi)); } treq->cons = (TR_CONSTRAINT_SET *) json_object_get(jreq, "constraints"); if (treq->cons) { if (!tr_constraint_set_validate(treq->cons)) { tr_debug("Constraint set validation failed"); tid_req_free(treq); return NULL; } json_incref((json_t *) treq->cons); tid_req_cleanup_json(treq, (json_t *) treq->cons); } if (jpath) { json_incref(jpath); treq->path = jpath; tid_req_cleanup_json(treq, jpath); } if (jexpire_interval) treq->expiration_interval = json_integer_value(jexpire_interval); return treq; }
/*=========================================================================*\ Get services from cloud type - only consider services of this type (might be NULL) reset - first delete all cloud services (of type if given) return -1 on error \*=========================================================================*/ int ickServiceAddFromCloud( const char *type, bool reset ) { const char *token; ServiceListItem *service; json_t *jParams; json_t *jResult; json_t *jObj; int i; DBGMSG( "ickServiceAddFromCloud: type=\"%s\" reset=%s", type?type:"(no type)", reset?"On":"Off" ); /*------------------------------------------------------------------------*\ Need token for cloud access... \*------------------------------------------------------------------------*/ token = ickCloudGetAccessToken(); if( !token ) { logwarn( "ickServiceAddFromCloud: Device not registered (no access token)." ); return -1; } /*------------------------------------------------------------------------*\ Collect parameters \*------------------------------------------------------------------------*/ jParams = json_object(); if( type ) json_object_set_new( jParams, "type", json_string(type) ); /*------------------------------------------------------------------------*\ Interact with cloud \*------------------------------------------------------------------------*/ jResult = ickCloudRequestSync( NULL, token, "findServices", jParams, NULL ); json_decref( jParams ); if( !jResult ) { DBGMSG( "ickServiceAddFromCloud: No answer from cloud." ); return -1; } /*------------------------------------------------------------------------*\ Server indicated error? \*------------------------------------------------------------------------*/ jObj = json_object_get( jResult, "error" ); if( jObj ) { DBGMSG( "ickServiceAddFromCloud: Error %s.", json_rpcerrstr(jObj) ); json_decref( jResult ); return -1; } /*------------------------------------------------------------------------*\ Get result \*------------------------------------------------------------------------*/ jObj = json_object_get( jResult, "result" ); if( !jObj ) { DBGMSG( "ickServiceAddFromCloud: No \"result\" object in answer." ); json_decref( jResult ); return -1; } jObj = json_object_get( jObj, "items" ); if( !jObj ) { DBGMSG( "ickServiceAddFromCloud: No \"items\" object in answer." ); json_decref( jResult ); return -1; } /*------------------------------------------------------------------------*\ Remove existing services from cloud if requested \*------------------------------------------------------------------------*/ if( reset ) { pthread_mutex_lock( &serviceListMutex ); while( (service=_getService(NULL,NULL,type,ServiceCloud)) != NULL ) _removeService( service ); pthread_mutex_unlock( &serviceListMutex ); } /*------------------------------------------------------------------------*\ Loop over all items and add them to list \*------------------------------------------------------------------------*/ for( i=0; i<json_array_size(jObj); i++ ) { json_t *jItem = json_array_get( jObj, i ); if( ickServiceAdd(jItem,ServiceCloud) ) logerr( "ickServiceAddFromCloud: Could not add service item #%d.", i ); } /*------------------------------------------------------------------------*\ That's it \*------------------------------------------------------------------------*/ json_decref( jResult ); return 0; }
/*=========================================================================*\ Get streaming reference for an item from cloud item - the item to be resolved returns a json list containing one element (equivalent to streamingRefs feature of items) returns NULL on error \*=========================================================================*/ json_t *ickServiceGetStreamingRef( PlaylistItem *item ) { const char *token; char *sid; ServiceListItem *service; json_t *jParams; json_t *jResult; json_t *jObj; json_t *jStreamingRefs; DBGMSG( "ickServiceGetStreamingRef: Item \"%s\" (%s)", playlistItemGetText(item), playlistItemGetId(item) ); /*------------------------------------------------------------------------*\ Need token for cloud access... \*------------------------------------------------------------------------*/ token = ickCloudGetAccessToken(); if( !token ) { logwarn( "ickServiceGetStreamingRef: Device not registered (no access token)." ); return NULL; } /*------------------------------------------------------------------------*\ Get service id from item id \*------------------------------------------------------------------------*/ if( !playlistItemGetId(item) ) { playlistItemLock( item ); logwarn( "ickServiceGetStreamingRef (%s): Item contains no id!", playlistItemGetText(item) ); playlistItemUnlock( item ); return NULL; } sid = strdup( playlistItemGetId(item) ); if( !sid ) { logwarn( "ickServiceGetStreamingRef: out of memory!" ); return NULL; } if( !strchr(sid,':') ) { playlistItemLock( item ); logwarn( "ickServiceGetStreamingRef (%s,%s): Malformed id (missing ':')!", playlistItemGetText(item), playlistItemGetId(item) ); playlistItemUnlock( item ); Sfree ( sid ); return NULL; } *strchr( sid, ':' ) = 0; /*------------------------------------------------------------------------*\ Find service descriptor \*------------------------------------------------------------------------*/ service = ickServiceFind( NULL, sid, NULL, ServiceCloud ); if( !service ) { playlistItemLock( item ); logwarn( "ickServiceGetStreamingRef (%s,%s): No such service \"%s\"!", playlistItemGetText(item), playlistItemGetId(item), sid ); playlistItemUnlock( item ); Sfree ( sid ); return NULL; } Sfree ( sid ); DBGMSG( "ickServiceGetStreamingRef (%s,%s): using service \"%s\" (%s)", playlistItemGetText(item), playlistItemGetId(item), service->name, service->type ); /*------------------------------------------------------------------------*\ Collect parameters \*------------------------------------------------------------------------*/ jParams = json_object(); json_object_set_new( jParams, "itemId", json_string(playlistItemGetId(item)) ); //Fixme: collect supported formats /*------------------------------------------------------------------------*\ Interact with cloud \*------------------------------------------------------------------------*/ jResult = ickCloudRequestSync( service->url, token, "getItemStreamingRef", jParams, NULL ); json_decref( jParams ); if( !jResult ) { logwarn( "ickServiceGetStreamingRef: No answer from cloud." ); return NULL; } /*------------------------------------------------------------------------*\ Server indicated error? \*------------------------------------------------------------------------*/ jObj = json_object_get( jResult, "error" ); if( jObj ) { logwarn( "ickServiceGetStreamingRef: Error %s.", json_rpcerrstr(jObj) ); json_decref( jResult ); return NULL; } /*------------------------------------------------------------------------*\ Get result \*------------------------------------------------------------------------*/ jObj = json_object_get( jResult, "result" ); if( !jObj ) { logerr( "ickServiceGetStreamingRef: No \"result\" object in answer." ); json_decref( jResult ); return NULL; } /*------------------------------------------------------------------------*\ Convert to list to be compatible with streamingRefs feature of items \*------------------------------------------------------------------------*/ jStreamingRefs = json_array(); if( !jObj ) { logerr( "ickServiceGetStreamingRef: out of memory!" ); json_decref( jResult ); return NULL; } if( json_array_append(jStreamingRefs,jObj) ) { logerr( "ickServiceGetStreamingRef: json_arry_append() failed." ); json_decref( jResult ); return NULL; } /*------------------------------------------------------------------------*\ That's it \*------------------------------------------------------------------------*/ json_decref( jResult ); return jStreamingRefs; }
static void twitch_parse_followers() { struct AudienceMember { const char *name; bool isFollower; bool isInChat; bool isMod; bool exists; bool shouldTrack; }; std::vector<AudienceMember> members; http_json_response *jsonResponse = _twitchJsonResponse; if (json_is_array(jsonResponse->root)) { int audienceCount = json_array_size(jsonResponse->root); for (int i = 0; i < audienceCount; i++) { json_t *audienceMember = json_array_get(jsonResponse->root, i); if (!json_is_object(audienceMember)) continue; json_t *name = json_object_get(audienceMember, "name"); json_t *isFollower = json_object_get(audienceMember, "isFollower"); json_t *isInChat = json_object_get(audienceMember, "inChat"); json_t *isMod = json_object_get(audienceMember, "isMod"); AudienceMember member; member.name = json_string_value(name); member.isFollower = json_boolean_value(isFollower); member.isInChat = json_boolean_value(isInChat); member.isMod = json_boolean_value(isMod); member.exists = false; member.shouldTrack = false; if (member.name == NULL || member.name[0] == 0) continue; if (member.isInChat && gConfigTwitch.enable_chat_peep_tracking) member.shouldTrack = true; else if (member.isFollower && gConfigTwitch.enable_follower_peep_tracking) member.shouldTrack = true; if (gConfigTwitch.enable_chat_peep_names && member.isInChat) members.push_back(member); else if (gConfigTwitch.enable_follower_peep_names && member.isFollower) members.push_back(member); } uint16 spriteIndex; rct_peep *peep; char buffer[256]; // Check what followers are already in the park FOR_ALL_GUESTS(spriteIndex, peep) { if (is_user_string_id(peep->name_string_idx)) { format_string(buffer, peep->name_string_idx, NULL); AudienceMember *member = NULL; for (size_t i = 0; i < members.size(); i++) { if (_strcmpi(buffer, members[i].name) == 0) { member = &members[i]; members[i].exists = true; break; } } if (peep->flags & PEEP_FLAGS_TWITCH) { if (member == NULL) { // Member no longer peep name worthy peep->flags &= ~(PEEP_FLAGS_TRACKING | PEEP_FLAGS_TWITCH); // TODO set peep name back to number / real name } else { if (member->shouldTrack) peep->flags |= (PEEP_FLAGS_TRACKING); else if (!member->shouldTrack) peep->flags &= ~(PEEP_FLAGS_TRACKING); } } else if (member != NULL && !(peep->flags & PEEP_FLAGS_LEAVING_PARK)) { // Peep with same name already exists but not twitch peep->flags |= PEEP_FLAGS_TWITCH; if (member->shouldTrack) peep->flags |= PEEP_FLAGS_TRACKING; } } } // Rename non-named peeps to followers that aren't currently in the park. if (members.size() > 0) { int memberIndex = -1; FOR_ALL_GUESTS(spriteIndex, peep) { int originalMemberIndex = memberIndex; for (size_t i = memberIndex + 1; i < members.size(); i++) { if (!members[i].exists) { memberIndex = i; break; } } if (originalMemberIndex == memberIndex) break; AudienceMember *member = &members[memberIndex]; if (!is_user_string_id(peep->name_string_idx) && !(peep->flags & PEEP_FLAGS_LEAVING_PARK)) { // Rename peep and add flags rct_string_id newStringId = user_string_allocate(4, member->name); if (newStringId != 0) { peep->name_string_idx = newStringId; peep->flags |= PEEP_FLAGS_TWITCH; if (member->shouldTrack) peep->flags |= PEEP_FLAGS_TRACKING; } } else { // Peep still yet to be found for member memberIndex--; } }
/*=========================================================================*\ Add a new service jService is the result part of a getServiceInformation answer \*=========================================================================*/ int ickServiceAdd( json_t *jService, ServiceOrigin origin ) { ServiceListItem *item; json_t *jObj; /*------------------------------------------------------------------------*\ Allocate header \*------------------------------------------------------------------------*/ item = calloc( 1, sizeof(ServiceListItem) ); if( !item ) { logerr( "ickServiceAdd: out of memory!" ); return -1; } item->origin = origin; item->jItem = json_incref( jService ); /*------------------------------------------------------------------------*\ Extract id for quick access (weak ref.) \*------------------------------------------------------------------------*/ jObj = json_object_get( jService, "id" ); if( !jObj || !json_is_string(jObj) ) { logerr( "ickServiceAdd: Missing field \"id\"!" ); Sfree( item ); json_decref( jService ); return -1; } item->id = json_string_value( jObj ); /*------------------------------------------------------------------------*\ Extract name for quick access (weak ref.) \*------------------------------------------------------------------------*/ jObj = json_object_get( jService, "name" ); if( !jObj || !json_is_string(jObj) ) { logerr( "ickServiceAdd (%s): Missing field \"name\"!", item->id ); Sfree( item ); json_decref( jService ); return -1; } item->name = json_string_value( jObj ); /*------------------------------------------------------------------------*\ Extract type for quick access (weak ref.) \*------------------------------------------------------------------------*/ jObj = json_object_get( jService, "type" ); if( !jObj || !json_is_string(jObj) ) { logerr( "ickServiceAdd (%s): Missing field \"type\"!", item->id ); Sfree( item ); json_decref( jService ); return -1; } item->type = json_string_value( jObj ); /*------------------------------------------------------------------------*\ Extract url for quick access (optional, weak ref.) \*------------------------------------------------------------------------*/ jObj = json_object_get( jService, "url" ); if( jObj ) item->url = json_string_value( jObj ); /*------------------------------------------------------------------------*\ Extract service url for quick access (optional, weak ref.) \*------------------------------------------------------------------------*/ jObj = json_object_get( jService, "serviceUrl" ); if( jObj ) item->serviceUrl = json_string_value( jObj ); /*------------------------------------------------------------------------*\ Insert or replace item \*------------------------------------------------------------------------*/ pthread_mutex_lock( &serviceListMutex ); // Check for duplicates ServiceListItem *oldItem = _getService( NULL, item->id, item->type, origin ); if( oldItem ) { DBGMSG( "ickServiceAdd (%s): Replacing service (%s:%s).", item->id, item->type, item->name ); _removeService( oldItem ); } // Insert new item in list item->next = serviceList; serviceList = item; pthread_mutex_unlock( &serviceListMutex ); /*------------------------------------------------------------------------*\ Be verbose \*------------------------------------------------------------------------*/ DBGMSG( "ickServiceAdd (%s): Added (%s:%s), origin %d.", item->id, item->type, item->name, item->origin ); /*------------------------------------------------------------------------*\ That's it \*------------------------------------------------------------------------*/ return 0; }
int dslink_request_handle(DSLink *link, json_t *req) { const char *method = json_string_value(json_object_get(req, "method")); if (!method) { return 1; } if (strcmp(method, "list") == 0) { const char *path = json_string_value(json_object_get(req, "path")); DSNode *node = dslink_node_get_path(link->responder->super_root, path); return dslink_response_list(link, req, node); } else if (strcmp(method, "subscribe") == 0) { json_t *paths = json_object_get(req, "paths"); json_t *rid = json_object_get(req, "rid"); return dslink_response_sub(link, paths, rid); } else if (strcmp(method, "unsubscribe") == 0) { json_t *sids = json_object_get(req, "sids"); json_t *rid = json_object_get(req, "rid"); return dslink_response_unsub(link, sids, rid); } else if (strcmp(method, "invoke") == 0) { const char *path = json_string_value(json_object_get(req, "path")); DSNode *node = dslink_node_get_path(link->responder->super_root, path); if (node && node->on_invocation) { Stream *stream = dslink_malloc(sizeof(Stream)); if (!stream) { return 1; } stream->type = INVOCATION_STREAM; stream->path = dslink_strdup(node->path); ref_t *stream_ref = dslink_ref(stream, free_stream); json_t *jsonRid = json_object_get(req, "rid"); json_t *params = json_object_get(req, "params"); node->on_invocation(link, node, jsonRid, params, stream_ref); if (stream->unused != 1) { dslink_decref(stream_ref); } else { ref_t *rid = dslink_ref(dslink_malloc(sizeof(uint32_t)), dslink_free); { uint32_t r = (uint32_t) json_integer_value(jsonRid); *((uint32_t *) rid->data) = r; } if (dslink_map_set(link->responder->open_streams, rid, stream_ref) != 0) { dslink_free(rid); dslink_free(stream_ref); free_stream(stream); return 1; } } } } else if (strcmp(method, "set") == 0) { const char *path = json_string_value(json_object_get(req, "path")); json_t *value = json_object_get(req, "value"); DSNode *node = dslink_node_get_path(link->responder->super_root, path); if (node) { ref_t *writable_ref = dslink_map_get(node->meta_data, "$writable"); if (writable_ref && json_is_string((json_t*) writable_ref->data)) { if (node->on_value_set) { node->on_value_set(link, node, value); } else { dslink_node_update_value(link, node, value); } } } } else if (strcmp(method, "close") == 0) { json_t *rid = json_object_get(req, "rid"); uint32_t ridi = (uint32_t) json_integer_value(rid); ref_t *stream_ref = dslink_map_remove_get(link->responder->open_streams, &ridi); if (stream_ref) { Stream *stream = stream_ref->data; DSNode *node = NULL; if (stream->path) { node = dslink_node_get_path(link->responder->super_root, stream->path); } if (stream->on_close != NULL) { stream->on_close(link, node, stream); } if (stream->type == LIST_STREAM) { dslink_map_remove(link->responder->list_subs, (void *) stream->path); } dslink_decref(stream_ref); } } else { log_warn("Unrecognized method: %s\n", method); } return 0; }
struct_data *s_data(const char *json) { log4c_category_log(log_tracer, LOG4C_PRIORITY_TRACE, "%s: %s() -> entering s_data()", s_prgrm_name , __func__); json_t *js_root, *js_data, *js_program, *js_tmp, *js_result, *js_result_obj, *js_array_obj; json_error_t error; uint8_t u8_array_pos = 0; struct_data *sd_data; sd_data = malloc(sizeof(struct_data)); js_root = NULL; js_data = NULL; js_result = NULL; js_result_obj = NULL; js_array_obj = NULL; sd_data = s_data_init(sd_data); u8_array_pos = 0; js_root = json_loads(json, 0, &error); if (!js_root) { log4c_category_log(log_debug, LOG4C_PRIORITY_ERROR, "%s: %s() -> error while creating json object: %s", s_prgrm_name , __func__, error.text); } if (!(js_data = json_object_get(js_root, "data"))) { log4c_category_log(log_debug, LOG4C_PRIORITY_ERROR, "%s: %s() -> error while reading the JSON-object: \"data\"", s_prgrm_name , __func__); } if (!(js_result = json_object_get(js_data, "result"))) { log4c_category_log(log_debug, LOG4C_PRIORITY_ERROR, "%s: %s() -> error while reading the JSON-object: \"result\"", s_prgrm_name , __func__); } while ((js_result_obj = json_array_get(js_result, u8_array_pos))) { /* writing the keyword in struct */ js_array_obj = json_object_get(js_result_obj, "s_keyword"); sd_data->s_search_keyword[u8_array_pos] = strdup(json_string_value(js_array_obj)); js_array_obj = json_object_get(js_result_obj, "u16_result"); sd_data->u16_matches[u8_array_pos] = json_integer_value(js_array_obj); log4c_category_log(log_tracer, LOG4C_PRIORITY_DEBUG, "%s: %s() -> keyword: %s, value: %d", s_prgrm_name , __func__, sd_data->s_search_keyword[u8_array_pos], sd_data->u16_matches[u8_array_pos]); ++u8_array_pos; } /* indicates how many keywords are available, necessary to build the table */ log4c_category_log(log_tracer, LOG4C_PRIORITY_DEBUG, "%s: %s() -> keywords available: %d", s_prgrm_name , __func__, u8_array_pos); sd_data->u8_keywords_present = u8_array_pos; if ((js_tmp = json_object_get(js_data, "source"))) { sd_data->s_source = strdup(json_string_value(js_tmp)); log4c_category_log(log_tracer, LOG4C_PRIORITY_DEBUG, "%s: %s() -> source: %s", s_prgrm_name , __func__, sd_data->s_source); } if ((js_tmp = json_object_get(js_data, "customer"))) { sd_data->s_customer = strdup(json_string_value(js_tmp)); log4c_category_log(log_tracer, LOG4C_PRIORITY_DEBUG, "%s: %s() -> customer: %s", s_prgrm_name , __func__, sd_data->s_customer); } if ((js_tmp = json_object_get(js_data, "pub_date"))) { /* pub date is not processed actually */ log4c_category_log(log_tracer, LOG4C_PRIORITY_DEBUG, "%s: %s() -> pub_date: %s", s_prgrm_name , __func__, json_string_value(js_tmp)); } if ((js_tmp = json_object_get(js_data, "sys_time"))) { sd_data->u32_sys_timestamp = json_integer_value(js_tmp); log4c_category_log(log_tracer, LOG4C_PRIORITY_DEBUG, "%s: %s() -> system time: %d", s_prgrm_name , __func__, sd_data->u32_sys_timestamp); } if ((js_program = json_object_get(js_root, "PRGRM"))) { sd_data->s_program = strdup(json_string_value(js_program)); log4c_category_log(log_tracer, LOG4C_PRIORITY_DEBUG, "%s: %s() -> program name: %s", s_prgrm_name , __func__, sd_data->s_program); } json_decref(js_root); return sd_data; }
json_t *json_rpc_call(CURL *curl, const char *url, const char *userpass, const char *rpc_req, int *curl_err, int flags) { json_t *val, *err_val, *res_val; int rc; long http_rc; struct data_buffer all_data = {0}; struct upload_buffer upload_data; char *json_buf; json_error_t err; struct curl_slist *headers = NULL; char len_hdr[64]; char curl_err_str[CURL_ERROR_SIZE]; long timeout = (flags & JSON_RPC_LONGPOLL) ? opt_timeout : 30; struct header_info hi = {0}; /* it is assumed that 'curl' is freshly [re]initialized at this pt */ if (opt_protocol) curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(curl, CURLOPT_URL, url); if (opt_cert) curl_easy_setopt(curl, CURLOPT_CAINFO, opt_cert); curl_easy_setopt(curl, CURLOPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data); curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb); curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data); #if LIBCURL_VERSION_NUM >= 0x071200 curl_easy_setopt(curl, CURLOPT_SEEKFUNCTION, &seek_data_cb); curl_easy_setopt(curl, CURLOPT_SEEKDATA, &upload_data); #endif curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str); if (opt_redirect) curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi); if (opt_proxy) { curl_easy_setopt(curl, CURLOPT_PROXY, opt_proxy); curl_easy_setopt(curl, CURLOPT_PROXYTYPE, opt_proxy_type); } if (userpass) { curl_easy_setopt(curl, CURLOPT_USERPWD, userpass); curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); } #if LIBCURL_VERSION_NUM >= 0x070f06 if (flags & JSON_RPC_LONGPOLL) curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_keepalive_cb); #endif curl_easy_setopt(curl, CURLOPT_POST, 1); if (opt_protocol) applog(LOG_DEBUG, "JSON protocol request:\n%s\n", rpc_req); upload_data.buf = rpc_req; upload_data.len = strlen(rpc_req); upload_data.pos = 0; sprintf(len_hdr, "Content-Length: %lu", (unsigned long) upload_data.len); headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, len_hdr); headers = curl_slist_append(headers, "User-Agent: " USER_AGENT); headers = curl_slist_append(headers, "X-Mining-Extensions: midstate"); headers = curl_slist_append(headers, "Accept:"); /* disable Accept hdr*/ headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); rc = curl_easy_perform(curl); if (curl_err != NULL) *curl_err = rc; if (rc) { curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_rc); if (!((flags & JSON_RPC_LONGPOLL) && rc == CURLE_OPERATION_TIMEDOUT) && !((flags & JSON_RPC_QUIET_404) && http_rc == 404)) applog(LOG_ERR, "HTTP request failed: %s", curl_err_str); if (curl_err && (flags & JSON_RPC_QUIET_404) && http_rc == 404) *curl_err = CURLE_OK; goto err_out; } /* If X-Stratum was found, activate Stratum */ if (want_stratum && hi.stratum_url && !strncasecmp(hi.stratum_url, "stratum+tcp://", 14)) { have_stratum = true; tq_push(thr_info[stratum_thr_id].q, hi.stratum_url); hi.stratum_url = NULL; } /* If X-Long-Polling was found, activate long polling */ if (!have_longpoll && want_longpoll && hi.lp_path && !have_gbt && allow_getwork && !have_stratum) { have_longpoll = true; tq_push(thr_info[longpoll_thr_id].q, hi.lp_path); hi.lp_path = NULL; } if (!all_data.buf) { applog(LOG_ERR, "Empty data received in json_rpc_call."); goto err_out; } json_buf = hack_json_numbers(all_data.buf); errno = 0; /* needed for Jansson < 2.1 */ val = JSON_LOADS(json_buf, &err); free(json_buf); if (!val) { applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text); goto err_out; } if (opt_protocol) { char *s = json_dumps(val, JSON_INDENT(3)); applog(LOG_DEBUG, "JSON protocol response:\n%s", s); free(s); } /* JSON-RPC valid response returns a 'result' and a null 'error'. */ res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val || (err_val && !json_is_null(err_val))) { char *s; if (err_val) s = json_dumps(err_val, JSON_INDENT(3)); else s = strdup("(unknown reason)"); applog(LOG_ERR, "JSON-RPC call failed: %s", s); free(s); goto err_out; } if (hi.reason) json_object_set_new(val, "reject-reason", json_string(hi.reason)); databuf_free(&all_data); curl_slist_free_all(headers); curl_easy_reset(curl); return val; err_out: free(hi.lp_path); free(hi.reason); free(hi.stratum_url); databuf_free(&all_data); curl_slist_free_all(headers); curl_easy_reset(curl); return NULL; }
/* ****************************************************************************** * dgadmin_rest_sync_version_get_from_buf -- *//** * * \brief This routine extracts create version and update version from a buffer * * \param [in] buf A pointer to a buffer. * * \param [out] version_create The creation version. * \param [out] version_update The last update version. * * \retval 0 Success * \retval >0 Failure * *****************************************************************************/ int dgadmin_rest_sync_version_get_from_buf(char *buf, char *target_uri, int *version_create, int *version_update, int *is_tombstone, int *is_uuid, char *deluri) { json_t *js_root = NULL; json_t *js_version_create = NULL, *js_version_update = NULL; json_error_t jerror; int ret = DOVE_STATUS_ERROR; char *object_name = NULL; do { /* extract both create_version and update_version */ js_root = json_loads(buf, 0, &jerror); if (!js_root) { log_notice(ServiceUtilLogLevel,"JSON body NULL"); break; } object_name = get_object_name_from_uri(target_uri); if (object_name == NULL) { log_notice(ServiceUtilLogLevel,"JSON OBJECT NULL for uri %s", target_uri); break; } js_root = json_object_get(js_root, object_name); if (!js_root) { log_notice(ServiceUtilLogLevel,"ERROR: Failed to get JSON object %s", object_name); break; } /* Borrowed reference, no need to decref */ js_version_create = json_object_get(js_root, "create_version"); if (!js_version_create || !json_is_integer(js_version_create)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } *version_create = json_integer_value(js_version_create); js_version_update = json_object_get(js_root, "change_version"); if (!js_version_update || !json_is_integer(js_version_update)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } *version_update = json_integer_value(js_version_update); js_version_update = json_object_get(js_root, "is_tombstone"); if (!js_version_update || !json_is_integer(js_version_update)) { /* does not have is_tombstone * take it as 0 */ *is_tombstone = 0; } else { *is_tombstone = json_integer_value(js_version_update); } js_version_update = json_object_get(js_root, "uuid"); if (js_version_update && json_is_string(js_version_update)) { const char *uuid = json_string_value(js_version_update); if(uuid) { if(strcmp(uuid,g_node_uuid)) { log_notice(ServiceUtilLogLevel,"UUID NOT match\n"); *is_uuid=0; } else { *is_uuid=1; } } else { *is_uuid=0; log_notice(ServiceUtilLogLevel,"ERROR"); } } else { /* NO UUID : This is a generic config for * all dgw nodes (subnet) * */ *is_uuid=1; } if(*is_tombstone) { /* make the delete URI */ char new_uri[DGADMIN_URI_LEN]; char *ptr=NULL; int retval=0; memset(new_uri,0,sizeof(new_uri)); strcpy(new_uri, target_uri); ptr = new_uri + strlen(target_uri); while (*ptr != '/') { ptr--; } *ptr = '\0'; retval = get_del_uri(new_uri,deluri,js_root); if(retval==0) { break; } } ret = DOVE_STATUS_OK; } while(0); if (js_root) { json_decref(js_root); } return ret; }
void TypeReader::deserializeClass(Type *type, json_t *classJSON) { utString sbaseType = json_string_value( json_object_get(classJSON, "baseType")); if (sbaseType.size() > 0) { Type *baseType = type->getModule()->getAssembly()->getLuaState()->getType( sbaseType.c_str()); lmAssert(baseType != NULL, "Unable to resolve type '%s' referenced as base of type '%s'", sbaseType.c_str(), type->getFullName().c_str()); type->setBaseType(baseType); } json_t *jinterfaces = json_object_get(classJSON, "interfaces"); for (size_t i = 0; i < json_array_size(jinterfaces); i++) { json_t *o = json_array_get(jinterfaces, i); utString sface = json_string_value(o); Type *itype = type->getModule()->getAssembly()->getLuaState()->getType( sface.c_str()); assert(itype); type->addInterface(itype); } json_t *jdelegateTypes = json_object_get(classJSON, "delegateTypes"); for (size_t i = 0; i < json_array_size(jdelegateTypes); i++) { json_t *o = json_array_get(jdelegateTypes, i); utString stype = json_string_value(o); Type *itype = type->getModule()->getAssembly()->getLuaState()->getType( stype.c_str()); assert(itype); type->addDelegateType(itype); } utString sdelegateReturnType = json_string_value( json_object_get(classJSON, "delegateReturnType")); if (sdelegateReturnType.size() > 0) { Type *delegateReturnType = type->getModule()->getAssembly()->getLuaState()->getType( sdelegateReturnType.c_str()); assert(delegateReturnType); type->setDelegateReturnType(delegateReturnType); } // meta data MemberInfoReader::deserializeMetaInfo(type, json_object_get(classJSON, "metainfo")); // handle imports json_t *iarray = json_object_get(classJSON, "imports"); for (size_t i = 0; i < json_array_size(iarray); i++) { json_t *jimport = json_array_get(iarray, i); utString import = json_string_value(jimport); Type *timport = type->getModule()->getAssembly()->getLuaState()->getType( import.c_str()); type->addImport(timport); } json_t *jconstructor = json_object_get(classJSON, "constructor"); if (jconstructor) { MethodBase *m = NULL; m = MethodReader::deserializeConstructorInfo(type, jconstructor); type->addMember(m); } // handle fields json_t *farray = json_object_get(classJSON, "fields"); for (size_t i = 0; i < json_array_size(farray); i++) { json_t *fo = json_array_get(farray, i); FieldInfo *f = FieldInfoReader::deserializeFieldInfo(type, fo); type->addMember(f); } // handle properties json_t *parray = json_object_get(classJSON, "properties"); for (size_t i = 0; i < json_array_size(parray); i++) { json_t *po = json_array_get(parray, i); PropertyInfo *p = PropertyInfoReader::deserializePropertyInfo(type, po); type->addMember(p); } // handle methods farray = json_object_get(classJSON, "methods"); for (size_t i = 0; i < json_array_size(farray); i++) { json_t *fo = json_array_get(farray, i); MethodBase *m = NULL; m = MethodReader::deserializeMethodInfo(type, fo); type->addMember(m); } const char *bc = json_string_value( json_object_get(classJSON, "bytecode_staticinitializer")); type->setBCStaticInitializer(ByteCode::decode64(bc)); bc = json_string_value( json_object_get(classJSON, "bytecode_instanceinitializer")); type->setBCInstanceInitializer(ByteCode::decode64(bc)); }
/* ****************************************************************************** * dgadmin_rest_sync_version_resp_parser -- *//** * * \brief This routine parses response of version GET request * * \param [in] body_buf A pointer to a version response buffer. * * \param [out] version The version. * \param [out] target_uri The URI of the HTTP request. * \param [out] operation The operation which acts on the URI. Now * support GET and DELETE. * * \retval 0 Success * \retval >0 Failure * *****************************************************************************/ static int dgadmin_rest_sync_version_resp_parser(char *body_buf, int *version, char *target_uri, int *operation) { json_t *js_root = NULL; json_t *js_version = NULL, *js_uri = NULL, *js_operation = NULL; json_error_t jerror; const char *uri, *operation_str; int ret = DOVE_STATUS_ERROR; do { js_root = json_loads(body_buf, 0, &jerror); if (!js_root) { log_notice(ServiceUtilLogLevel,"JSON body NULL"); break; } /* Borrowed reference, no need to decref */ js_version = json_object_get(js_root, "next_change"); if (!json_is_integer(js_version)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } *version = json_integer_value(js_version); js_uri = json_object_get(js_root, "uri"); if (!json_is_string(js_uri)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } if ((uri = json_string_value(js_uri)) == NULL) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } strcpy(target_uri, uri); js_operation = json_object_get(js_root, "method"); if (!json_is_string(js_operation)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } if ((operation_str = json_string_value(js_operation)) == NULL) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } if (!strcmp(operation_str, "GET")) { *operation = DGADMIN_REST_SYNC_OPERATION_GET; } else if (!strcmp(operation_str, "DELETE")) { *operation = DGADMIN_REST_SYNC_OPERATION_DELETE; } else { if(uri && (strlen(uri))) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } } ret = DOVE_STATUS_OK; } while(0); if (js_root) { json_decref(js_root); } return ret; }
Type *TypeReader::deserialize(Module *module, json_t *json) { Type *type = NULL; const char *stype = json_string_value(json_object_get(json, "type")); utString packageName = json_string_value(json_object_get(json, "package")); utString name = json_string_value(json_object_get(json, "name")); utString fullName = packageName + "."; fullName += name; type = module->getType(fullName); assert(type); //, "Cannot get type for %s", fullName.c_str()); json_t *jtypeid = json_object_get(json, "typeid"); assert(jtypeid && json_is_number(jtypeid)); type->setTypeID((LSTYPEID)json_number_value(jtypeid)); if (!strcmp(stype, "CLASS")) { type->attr.isClass = true; } else if (!strcmp(stype, "INTERFACE")) { type->attr.isInterface = true; } else if (!strcmp(stype, "STRUCT")) { type->attr.isStruct = true; } else if (!strcmp(stype, "DELEGATE")) { type->attr.isDelegate = true; } else if (!strcmp(stype, "ENUM")) { type->attr.isEnum = true; } else { assert(0); //, "Unknown type: %s", stype); } json_t *jsource = json_object_get(json, "source"); if (jsource && json_is_string(jsource)) { type->source = json_string_value(jsource); type->lineNumber = (int)json_integer_value(json_object_get(json, "line")); } json_t *jdocstring = json_object_get(json, "docString"); if (jdocstring && json_is_string(jdocstring)) { if (strlen(json_string_value(jdocstring))) { type->setDocString(json_string_value(jdocstring)); } } deserializeClass(type, json); assert(type); return type; }
/** Load client entries from Couchbase client documents on startup * * This function executes the view defined in the module configuration and loops * through all returned rows. The view is called with "stale=false" to ensure the * most accurate data available when the view is called. This will force an index * rebuild on this design document in Couchbase. However, since this function is only * run once at sever startup this should not be a concern. * * @param inst The module instance. * @param tmpl Default values for new clients. * @param map The client attribute configuration section. * @return * - 0 on success. * - -1 on failure. */ int mod_load_client_documents(rlm_couchbase_t *inst, CONF_SECTION *tmpl, CONF_SECTION *map) { rlm_couchbase_handle_t *handle = NULL; /* connection pool handle */ char vpath[256], vid[MAX_KEY_SIZE], vkey[MAX_KEY_SIZE]; /* view path and fields */ char error[512]; /* view error return */ int idx = 0; /* row array index counter */ int retval = 0; /* return value */ lcb_error_t cb_error = LCB_SUCCESS; /* couchbase error holder */ json_object *json, *jval; /* json object holders */ json_object *jrows = NULL; /* json object to hold view rows */ CONF_SECTION *client; /* freeradius config section */ RADCLIENT *c; /* freeradius client */ /* get handle */ handle = fr_connection_get(inst->pool); /* check handle */ if (!handle) return -1; /* set couchbase instance */ lcb_t cb_inst = handle->handle; /* set cookie */ cookie_t *cookie = handle->cookie; /* build view path */ snprintf(vpath, sizeof(vpath), "%s?stale=false", inst->client_view); /* query view for document */ cb_error = couchbase_query_view(cb_inst, cookie, vpath, NULL); /* check error and object */ if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success || !cookie->jobj) { /* log error */ ERROR("rlm_couchbase: failed to execute view request or parse return"); /* set return */ retval = -1; /* return */ goto free_and_return; } /* debugging */ DEBUG3("rlm_couchbase: cookie->jobj == %s", json_object_to_json_string(cookie->jobj)); /* check for error in json object */ if (json_object_object_get_ex(cookie->jobj, "error", &json)) { /* build initial error buffer */ strlcpy(error, json_object_get_string(json), sizeof(error)); /* get error reason */ if (json_object_object_get_ex(cookie->jobj, "reason", &json)) { /* append divider */ strlcat(error, " - ", sizeof(error)); /* append reason */ strlcat(error, json_object_get_string(json), sizeof(error)); } /* log error */ ERROR("rlm_couchbase: view request failed with error: %s", error); /* set return */ retval = -1; /* return */ goto free_and_return; } /* check for document id in return */ if (!json_object_object_get_ex(cookie->jobj, "rows", &json)) { /* log error */ ERROR("rlm_couchbase: failed to fetch rows from view payload"); /* set return */ retval = -1; /* return */ goto free_and_return; } /* get and hold rows */ jrows = json_object_get(json); /* free cookie object */ if (cookie->jobj) { json_object_put(cookie->jobj); cookie->jobj = NULL; } /* debugging */ DEBUG3("rlm_couchbase: jrows == %s", json_object_to_json_string(jrows)); /* check for valid row value */ if (!fr_json_object_is_type(jrows, json_type_array) || json_object_array_length(jrows) < 1) { /* log error */ ERROR("rlm_couchbase: no valid rows returned from view: %s", vpath); /* set return */ retval = -1; /* return */ goto free_and_return; } /* loop across all row elements */ for (idx = 0; idx < json_object_array_length(jrows); idx++) { /* fetch current index */ json = json_object_array_get_idx(jrows, idx); /* get view id */ if (json_object_object_get_ex(json, "id", &jval)) { /* clear view id */ memset(vid, 0, sizeof(vid)); /* copy and check length */ if (strlcpy(vid, json_object_get_string(jval), sizeof(vid)) >= sizeof(vid)) { ERROR("rlm_couchbase: id from row longer than MAX_KEY_SIZE (%d)", MAX_KEY_SIZE); continue; } } else { WARN("rlm_couchbase: failed to fetch id from row - skipping"); continue; } /* get view key */ if (json_object_object_get_ex(json, "key", &jval)) { /* clear view key */ memset(vkey, 0, sizeof(vkey)); /* copy and check length */ if (strlcpy(vkey, json_object_get_string(jval), sizeof(vkey)) >= sizeof(vkey)) { ERROR("rlm_couchbase: key from row longer than MAX_KEY_SIZE (%d)", MAX_KEY_SIZE); continue; } } else { WARN("rlm_couchbase: failed to fetch key from row - skipping"); continue; } /* fetch document */ cb_error = couchbase_get_key(cb_inst, cookie, vid); /* check error and object */ if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success || !cookie->jobj) { /* log error */ ERROR("rlm_couchbase: failed to execute get request or parse return"); /* set return */ retval = -1; /* return */ goto free_and_return; } /* debugging */ DEBUG3("rlm_couchbase: cookie->jobj == %s", json_object_to_json_string(cookie->jobj)); /* allocate conf section */ client = tmpl ? cf_section_dup(NULL, tmpl, "client", vkey, true) : cf_section_alloc(NULL, "client", vkey); if (client_map_section(client, map, _get_client_value, cookie->jobj) < 0) { /* free config setion */ talloc_free(client); /* set return */ retval = -1; /* return */ goto free_and_return; } /* * @todo These should be parented from something. */ c = client_afrom_cs(NULL, client, false, false); if (!c) { ERROR("rlm_couchbase: failed to allocate client"); /* free config setion */ talloc_free(client); /* set return */ retval = -1; /* return */ goto free_and_return; } /* * Client parents the CONF_SECTION which defined it. */ talloc_steal(c, client); /* attempt to add client */ if (!client_add(NULL, c)) { ERROR("rlm_couchbase: failed to add client '%s' from '%s', possible duplicate?", vkey, vid); /* free client */ client_free(c); /* set return */ retval = -1; /* return */ goto free_and_return; } /* debugging */ DEBUG("rlm_couchbase: client '%s' added", c->longname); /* free json object */ if (cookie->jobj) { json_object_put(cookie->jobj); cookie->jobj = NULL; } } free_and_return: /* free rows */ if (jrows) { json_object_put(jrows); } /* free json object */ if (cookie->jobj) { json_object_put(cookie->jobj); cookie->jobj = NULL; } /* release handle */ if (handle) { fr_connection_release(inst->pool, handle); } /* return */ return retval; }
int dslink_init(int argc, char **argv, const char *name, uint8_t isRequester, uint8_t isResponder, DSLinkCallbacks *cbs) { mbedtls_ecdh_context ctx; DSLinkConfig config; Url *url = NULL; json_t *handshake = NULL; char *dsId = NULL; Socket *sock = NULL; DSLink link; memset(&link, 0, sizeof(DSLink)); int ret = 0; config.name = name; if ((ret = dslink_parse_opts(argc, argv, &config)) != 0) { if (ret == DSLINK_ALLOC_ERR) { log_fatal("Failed to allocate memory during argument parsing\n"); } return 1; } // TODO: move .key as a parameter if ((ret = dslink_handshake_key_pair_fs(&ctx, ".key")) != 0) { if (ret == DSLINK_CRYPT_KEY_DECODE_ERR) { log_fatal("Failed to decode existing key\n"); } else if (ret == DSLINK_OPEN_FILE_ERR) { log_fatal("Failed to write generated key to disk\n"); } else if (ret == DSLINK_CRYPT_KEY_PAIR_GEN_ERR) { log_fatal("Failed to generated key\n"); } else { log_fatal("Unknown error occurred during key handling: %d\n", ret); } ret = 1; goto exit; } url = dslink_url_parse(config.broker_url); if (!url) { log_fatal("Failed to parse url: %s\n", config.broker_url); ret = 1; goto exit; } if (isResponder) { link.responder = calloc(1, sizeof(Responder)); if (!link.responder) { log_fatal("Failed to create responder\n"); goto exit; } if (dslink_init_responder(link.responder) != 0) { log_fatal("Failed to initialize responder\n"); goto exit; } } if (cbs->init_cb) { cbs->init_cb(&link); } if ((ret = dslink_handshake_generate(url, &ctx, config.name, isRequester, isResponder, &handshake, &dsId)) != 0) { log_fatal("Handshake failed: %d\n", ret); ret = 1; goto exit; } const char *uri = json_string_value(json_object_get(handshake, "wsUri")); const char *tKey = json_string_value(json_object_get(handshake, "tempKey")); const char *salt = json_string_value(json_object_get(handshake, "salt")); if (!(uri && tKey && salt)) { log_fatal("Handshake didn't return the " "necessary parameters to complete\n"); ret = 1; goto exit; } if ((ret = dslink_handshake_connect_ws(url, &ctx, uri, tKey, salt, dsId, &sock)) != 0) { log_fatal("Failed to connect to the broker: %d\n", ret); ret = 1; goto exit; } else { log_info("Successfully connected to the broker\n"); } if (cbs->on_connected_cb) { cbs->on_connected_cb(&link); } link._socket = sock; dslink_handshake_handle_ws(&link); // TODO: automatic reconnecting log_warn("Disconnected from the broker\n") if (cbs->on_disconnected_cb) { cbs->on_disconnected_cb(&link); } exit: mbedtls_ecdh_free(&ctx); DSLINK_CHECKED_EXEC(dslink_socket_close, sock); if (link.responder) { if (link.responder->super_root) { dslink_node_tree_free(NULL, link.responder->super_root); } if (link.responder->open_streams) { DSLINK_MAP_FREE(link.responder->open_streams, { free(entry->key); free(entry->value); });
static TID_RESP *tr_msg_decode_tidresp(json_t *jresp) { TID_RESP *tresp = NULL; json_t *jresult = NULL; json_t *jrp_realm = NULL; json_t *jrealm = NULL; json_t *jcomm = NULL; json_t *jorig_coi = NULL; json_t *jservers = NULL; json_t *jerr_msg = NULL; if (!(tresp=tid_resp_new(NULL))) { tr_crit("tr_msg_decode_tidresp(): Error allocating TID_RESP structure."); return NULL; } /* store required fields from response */ if ((NULL == (jresult = json_object_get(jresp, "result"))) || (!json_is_string(jresult)) || (NULL == (jrp_realm = json_object_get(jresp, "rp_realm"))) || (!json_is_string(jrp_realm)) || (NULL == (jrealm = json_object_get(jresp, "target_realm"))) || (!json_is_string(jrealm)) || (NULL == (jcomm = json_object_get(jresp, "comm"))) || (!json_is_string(jcomm))) { tr_debug("tr_msg_decode_tidresp(): Error parsing response."); talloc_free(tresp); return NULL; } if (0 == (strcmp(json_string_value(jresult), "success"))) { tr_debug("tr_msg_decode_tidresp(): Success! result = %s.", json_string_value(jresult)); if ((NULL != (jservers = json_object_get(jresp, "servers"))) || (!json_is_array(jservers))) { tresp->servers = tr_msg_decode_servers(tresp, jservers, &tresp->num_servers); } else { talloc_free(tresp); return NULL; } tresp->result = TID_SUCCESS; } else { tresp->result = TID_ERROR; tr_debug("tr_msg_decode_tidresp(): Error! result = %s.", json_string_value(jresult)); if ((NULL != (jerr_msg = json_object_get(jresp, "err_msg"))) || (!json_is_string(jerr_msg))) { tresp->err_msg = tr_new_name((char *)json_string_value(jerr_msg)); } } tresp->rp_realm = tr_new_name((char *)json_string_value(jrp_realm)); tresp->realm = tr_new_name((char *)json_string_value(jrealm)); tresp->comm = tr_new_name((char *)json_string_value(jcomm)); /* store optional "orig_coi" field */ if ((NULL != (jorig_coi = json_object_get(jresp, "orig_coi"))) && (!json_is_object(jorig_coi))) { tresp->orig_coi = tr_new_name((char *)json_string_value(jorig_coi)); } return tresp; }
int main (int argc, char *argv[]) { const int q_size = 16; struct queue *q; struct job *j; json_t *attrs; json_t *badattrs; json_t *o; json_t *el; json_t *id_o; flux_jobid_t id; plan (NO_PLAN); q = make_test_queue (q_size); if (!(attrs = json_pack ("[s]", "id"))) BAIL_OUT ("json_pack failed"); /* list_job_array */ o = list_job_array (q, 0, attrs); ok (o != NULL && json_is_array (o), "list_job_array returns array"); ok (json_array_size (o) == q_size, "array has expected size"); json_decref (o); o = list_job_array (q, 4, attrs); ok (o != NULL && json_is_array (o), "list_job_array max_entries=4 returns array"); ok (json_array_size (o) == 4, "array has expected size"); el = json_array_get (o, 1); ok (el != NULL && json_is_object (el), "array[1] is an object"); ok ((id_o = json_object_get (el, "id")) != NULL, "array[1] id is set"); id = json_integer_value (id_o); ok (id == 1, "array[1] id=1"); if (id != 1) diag ("id=%d", (int)id); ok (json_object_size (el) == 1, "array[1] size=1"); json_decref (o); errno = 0; ok (list_job_array (q, -1, attrs) == NULL && errno == EPROTO, "list_job_array max_entries < 0 fails with EPROTO"); errno = 0; ok (list_job_array (q, -1, NULL) == NULL && errno == EPROTO, "list_job_array attrs=NULL fails with EPROTO"); /* list_one_job */ if (!(j = queue_lookup_by_id (q, 0))) BAIL_OUT ("queue_lookup_by_id 0 failed"); if (!(badattrs = json_pack ("[s]", "foo"))) BAIL_OUT ("json_pack failed"); errno = 0; ok (list_one_job (j, badattrs) == NULL && errno == EINVAL, "list_one_job attrs=[\"foo\"] fails with EINVAL"); json_decref (badattrs); if (!(badattrs = json_pack ("[i]", 42))) BAIL_OUT ("json_pack failed"); errno = 0; ok (list_one_job (j, badattrs) == NULL && errno == EPROTO, "list_one_job attrs=[42] fails with EPROTO"); json_decref (badattrs); json_decref (attrs); queue_destroy (q); done_testing (); }
int patts_init (uint8_t db_type, const char *host, const char *user, const char *passwd, const char *database, const char *port) { int rc = 0; const char *fmt = "SELECT isAdmin FROM User WHERE dbUser='******'"; char *query, *user_info, *esc_user; const char *isAdmin; json_t *list, *user_cols; size_t qlen = 1; if (strlen (user) >= 8) return PATTS_OVERFLOW; strcpy (user_id, user); sqon_init (); PATTSDB = sqon_new_connection (db_type, host, user, passwd, database, port); rc = sqon_escape (patts_get_db (), user, &esc_user, false); if (rc) return rc; qlen += strlen (fmt) - 2; qlen += strlen (esc_user); query = sqon_malloc (qlen * sizeof (char)); if (NULL == query) { sqon_free (esc_user); return PATTS_MEMORYERROR; } snprintf (query, qlen, fmt, esc_user); rc = sqon_query (patts_get_db (), query, &user_info, NULL); sqon_free (query); sqon_free (esc_user); if (rc) return rc; list = json_loads (user_info, 0, NULL); sqon_free (user_info); if (NULL == list) return PATTS_LOADERROR; if (0 == json_array_size (list)) return PATTS_NOSUCHUSER; user_cols = json_array_get (list, 0); isAdmin = json_string_value (json_object_get (user_cols, "isAdmin")); if (!strcmp (isAdmin, "\001") || !strcmp (isAdmin, "1")) HAVE_ADMIN = true; else if (!strcmp (isAdmin, "") || !strcmp (isAdmin, "0")) HAVE_ADMIN = false; else rc = PATTS_UNEXPECTED; json_decref (list); return rc; }
void Login::requstGateCallback(pc_request_t *req, int status, json_t *resp) { if(status == -1) { CCLOG("Fail to send request to server.\n"); } else if(status == 0) { connectorHost = json_string_value(json_object_get(resp, "host")); connectorPort = json_number_value(json_object_get(resp, "port")); CCLOG("%s %d", connectorHost,connectorPort); pc_client_t *client = pc_client_new(); struct sockaddr_in address; memset(&address, 0, sizeof(struct sockaddr_in)); address.sin_family = AF_INET; address.sin_port = htons(connectorPort); address.sin_addr.s_addr = inet_addr(connectorHost); // add pomelo events listener void (*on_disconnect)(pc_client_t *client, const char *event, void *data) = &Login::onDisconnectCallback; void (*on_chat)(pc_client_t *client, const char *event, void *data) = &Login::onChatCallback; void (*on_add)(pc_client_t *client, const char *event, void *data) = &Login::onAddCallback; void (*on_leave)(pc_client_t *client, const char *event, void *data) = &Login::onLeaveCallback; pc_add_listener(client, "disconnect", on_disconnect); pc_add_listener(client, "onChat", on_chat); pc_add_listener(client, "onAdd", on_add); pc_add_listener(client, "onLeave", on_leave); // try to connect to server. if(pc_client_connect(client, &address)) { CCLOG("fail to connect server.\n"); pc_client_destroy(client); return ; } const char *route = "connector.entryHandler.enter"; json_t *msg = json_object(); json_t *str = json_string(username.c_str()); json_t *channel_str = json_string(channel.c_str()); json_object_set(msg, "username", str); json_object_set(msg, "rid", channel_str); // decref for json object json_decref(str); json_decref(channel_str); pc_request_t *request = pc_request_new(); void (*connect_cb)(pc_request_t *req, int status, json_t *resp )= &Login::requstConnectorCallback; pc_request(client, request, route, msg, connect_cb); /* char *json_str = json_dumps(resp, 0); if(json_str != NULL) { CCLOG("server response: %s %d\n", connectorHost, connectorPort); free(json_str); } */ } // release relative resource with pc_request_t json_t *pc_msg = req->msg; pc_client_t *pc_client = req->client; json_decref(pc_msg); pc_request_destroy(req); pc_client_stop(pc_client); }
void axis2_json_write_node(json_object* parent, axiom_node_t* om_node, const axutil_env_t* env) { axiom_element_t* elem; axiom_node_t* child_node; const axis2_char_t* local_name; json_object* obj; json_object* array = NULL; if (!om_node || axiom_node_get_node_type(om_node, env) != AXIOM_ELEMENT) return; elem = (axiom_element_t*)axiom_node_get_data_element(om_node, env); local_name = axiom_element_get_localname(elem, env); child_node = axiom_node_get_first_element(om_node, env); /* find existing object */ if (json_object_object_get_ex(parent, local_name, &obj)) { /* check that object is array? */ if (!json_object_is_type(obj, json_type_array)) { /* convert to array */ obj = json_object_get(obj); array = json_object_new_array(); json_object_array_add(array, obj); json_object_object_del(parent, local_name); json_object_object_add(parent, local_name, array); } else array = obj; } if (!child_node) { /* this is a leaf node */ json_object* json_value = NULL; /* check for nillable */ if (!axis2_json_element_is_nil(elem, env)) { const axis2_char_t* value = axiom_element_get_text(elem, env, om_node); json_value = json_object_new_string(value ? value : ""); } if (array) json_object_array_add(array, json_value); else json_object_object_add(parent, local_name, json_value); return; } /* iterate through children elements */ obj = json_object_new_object(); if (array) json_object_array_add(array, obj); else json_object_object_add(parent, local_name, obj); for (; child_node; child_node = axiom_node_get_next_sibling(child_node, env)) if (axiom_node_get_node_type(child_node, env) == AXIOM_ELEMENT) axis2_json_write_node(obj, child_node, env); }
/* subscribe /root subname {query} * Subscribes the client connection to the specified root. */ static void cmd_subscribe(struct watchman_client *client, json_t *args) { w_root_t *root; struct watchman_client_subscription *sub; json_t *resp; const char *name; json_t *jfield_list; w_query *query; json_t *query_spec; struct w_query_field_list field_list; char *errmsg; if (json_array_size(args) != 4) { send_error_response(client, "wrong number of arguments for subscribe"); return; } root = resolve_root_or_err(client, args, 1, true); if (!root) { return; } name = json_string_value(json_array_get(args, 2)); if (!name) { send_error_response(client, "expected 2nd parameter to be subscription name"); goto done; } query_spec = json_array_get(args, 3); 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); goto done; } query = w_query_parse(root, query_spec, &errmsg); if (!query) { send_error_response(client, "failed to parse query: %s", errmsg); free(errmsg); goto done; } sub = calloc(1, sizeof(*sub)); if (!sub) { send_error_response(client, "no memory!"); goto done; } sub->name = w_string_new(name); sub->query = query; memcpy(&sub->field_list, &field_list, sizeof(field_list)); sub->root = root; pthread_mutex_lock(&w_client_lock); w_ht_replace(client->subscriptions, w_ht_ptr_val(sub->name), w_ht_ptr_val(sub)); pthread_mutex_unlock(&w_client_lock); resp = make_response(); annotate_with_clock(root, resp); set_prop(resp, "subscribe", json_string(name)); send_and_dispose_response(client, resp); resp = build_subscription_results(sub, root); if (resp) { send_and_dispose_response(client, resp); } done: w_root_delref(root); }
static int json_find(void *handle, uschar *filename, const uschar *keystring, int length, uschar **result, uschar **errmsg, uint *do_cache) { FILE * f = handle; json_t * j, * j0; json_error_t jerr; uschar * key; int sep = 0; length = length; /* Keep picky compilers happy */ do_cache = do_cache; /* Keep picky compilers happy */ rewind(f); if (!(j = json_loadf(f, 0, &jerr))) { *errmsg = string_sprintf("json error on open: %.*s\n", JSON_ERROR_TEXT_LENGTH, jerr.text); return FAIL; } j0 = j; for (int k = 1; (key = string_nextinlist(&keystring, &sep, NULL, 0)); k++) { BOOL numeric = TRUE; for (uschar * s = key; *s; s++) if (!isdigit(*s)) { numeric = FALSE; break; } if (!(j = numeric ? json_array_get(j, (size_t) strtoul(CS key, NULL, 10)) : json_object_get(j, CCS key) ) ) { DEBUG(D_lookup) debug_printf("%s, for key %d: '%s'\n", numeric ? US"bad index, or not json array" : US"no such key, or not json object", k, key); json_decref(j0); return FAIL; } } switch (json_typeof(j)) { case JSON_STRING: *result = string_copyn(CUS json_string_value(j), json_string_length(j)); break; case JSON_INTEGER: *result = string_sprintf("%" JSON_INTEGER_FORMAT, json_integer_value(j)); break; case JSON_REAL: *result = string_sprintf("%f", json_real_value(j)); break; case JSON_TRUE: *result = US"true"; break; case JSON_FALSE: *result = US"false"; break; case JSON_NULL: *result = NULL; break; default: *result = US json_dumps(j, 0); break; } json_decref(j0); return OK; }
/* Get delete uri * 1-Success * 0-Fail * */ static int get_del_uri(char *new_uri, char *deluri, json_t *js_root) { int retval=0; json_t *js_objt = NULL; do { if(strcmp(DGW_SERVICE_IPV4S_URI, new_uri)==0) { struct in_addr ip; const char *ip_str = NULL; js_objt = json_object_get(js_root, "ip"); if (js_objt && json_is_string(js_objt)) { ip_str = json_string_value(js_objt); } else { log_notice(ServiceUtilLogLevel,"ERROR"); break; } inet_pton(AF_INET, ip_str, (void *)&ip); sprintf(deluri,"%s/%u",new_uri,ip.s_addr); log_notice(ServiceUtilLogLevel,"DELURI:%s",deluri); retval=1; } else if(strcmp(DGW_SERVICE_EXTERNAL_VIPS_URI,new_uri)==0) { struct in_addr min_ip; struct in_addr max_ip; const char *min_ip_str = NULL; const char *max_ip_str = NULL; char ip_id[IP_ID_LEN + 1] = {0}; char *ptr = NULL; char gw_id_str[2*IP_ID_LEN + 1] = {0}; int net_id=0; memset(ip_id,0,sizeof(ip_id)); memset(gw_id_str,0,sizeof(gw_id_str)); js_objt = json_object_get(js_root, "min_ip"); if (js_objt && json_is_string(js_objt)) { min_ip_str = json_string_value(js_objt); } else { log_notice(ServiceUtilLogLevel,"ERROR"); break; } js_objt = json_object_get(js_root, "max_ip"); if (js_objt && json_is_string(js_objt)) { max_ip_str = json_string_value(js_objt); } else { log_notice(ServiceUtilLogLevel,"ERROR"); break; } js_objt = json_object_get(js_root, "net_id"); if (js_objt && json_is_integer(js_objt)) { net_id = json_integer_value(js_objt); } else { log_notice(ServiceUtilLogLevel,"ERROR"); break; } inet_pton(AF_INET, min_ip_str, (void *)&min_ip); inet_pton(AF_INET, max_ip_str, (void *)&max_ip); v4_addr_to_ip_id(ip_id, ntohl(min_ip.s_addr)); strcpy(gw_id_str, ip_id); ptr = gw_id_str; ptr = ptr + strlen(gw_id_str); memset(ip_id, 0, sizeof(ip_id)); v4_addr_to_ip_id(ip_id, ntohl(max_ip.s_addr)); strcpy(ptr, ip_id); sprintf(deluri,"%s/%s%010d",new_uri,gw_id_str,net_id); log_notice(ServiceUtilLogLevel,"DELURI:%s",deluri); retval=1; } else if(strcmp(DGW_SERVICE_RULES_URI,new_uri)==0) { int net_id = 0; int protocol = 0; int port = 0; const char *ip_str = NULL; char ip_id[IP_ID_LEN + 1] = {0}; struct in_addr ip; js_objt = json_object_get(js_root, "net_id"); if(!js_objt || !json_is_integer(js_objt)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } net_id = json_integer_value(js_objt); js_objt = json_object_get(js_root, "protocol"); if(!js_objt || !json_is_integer(js_objt)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } protocol = json_integer_value(js_objt); js_objt = json_object_get(js_root, "port"); if(!js_objt || !json_is_integer(js_objt)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } port = json_integer_value(js_objt); js_objt = json_object_get(js_root, "ip"); if (js_objt && json_is_string(js_objt)) { ip_str = json_string_value(js_objt); } else { log_notice(ServiceUtilLogLevel,"ERROR"); break; } memset(ip_id,0,sizeof(ip_id)); inet_pton(AF_INET, ip_str, (void *)&ip); v4_addr_to_ip_id(ip_id, ntohl(ip.s_addr)); sprintf(deluri,"%s/%05d%05d%03d%s",new_uri,net_id, port,protocol,ip_id); log_notice(ServiceUtilLogLevel,"DELURI:%s",deluri); retval=1; } else if(strcmp(DGW_SERVICE_VLANMAPS_URI,new_uri)==0) { int net_id = 0; int vlan = 0; js_objt = json_object_get(js_root, "net_id"); if(!js_objt || !json_is_integer(js_objt)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } net_id = json_integer_value(js_objt); js_objt = json_object_get(js_root, "vlan"); if(!js_objt || !json_is_integer(js_objt)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } vlan = json_integer_value(js_objt); sprintf(deluri,"%s/%05d%05d",new_uri,net_id,vlan); log_notice(ServiceUtilLogLevel,"DELURI:%s",deluri); retval=1; } else if(strcmp(DGW_SERVICE_SUBNETS_URI, new_uri)==0) { struct in_addr ip; char ip_id[IP_ID_LEN + 1] = {0}; const char *ip_str = NULL; int net_id; js_objt = json_object_get(js_root, "ip"); if (js_objt && json_is_string(js_objt)) { ip_str = json_string_value(js_objt); } else { log_notice(ServiceUtilLogLevel,"ERROR"); break; } js_objt = json_object_get(js_root, "net_id"); if(!js_objt || !json_is_integer(js_objt)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } net_id = json_integer_value(js_objt); memset(ip_id,0,sizeof(ip_id)); inet_pton(AF_INET, ip_str, (void *)&ip); v4_addr_to_ip_id(ip_id, ntohl(ip.s_addr)); sprintf(deluri,"%s/%05d%s",new_uri,net_id,ip_id); log_notice(ServiceUtilLogLevel,"DELURI:%s",deluri); retval=1; } else if(strcmp(DGW_SERVICE_NETWORKS, new_uri)==0) { int net_id;int domainid;int type; js_objt = json_object_get(js_root, "net_id"); if(!js_objt || !json_is_integer(js_objt)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } net_id = json_integer_value(js_objt); js_objt = json_object_get(js_root, "domainid"); if(!js_objt || !json_is_integer(js_objt)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } domainid = json_integer_value(js_objt); js_objt = json_object_get(js_root, "type"); if(!js_objt || !json_is_integer(js_objt)) { log_notice(ServiceUtilLogLevel,"ERROR"); break; } type = json_integer_value(js_objt); sprintf(deluri,"%s/%d,%d,%d",new_uri,net_id,domainid,type); log_notice(ServiceUtilLogLevel,"DELURI:%s",deluri); retval=1; } else { log_notice(ServiceUtilLogLevel,"ERROR"); } }while(0); return retval; }
static void get_node_id_from_rsp(json_t *rsp, int64 *node_id) { json_t *jnode_id = json_object_get(rsp, JRPC_NODE_ID); *node_id = json_integer_value(jnode_id); }
static qeojson_writer_t *qeojson_writer_open(const qeo_factory_t *factory, qeojson_writer_type_t writer_type, void *listener, const char *json_type, uintptr_t userdata) { qeo_retcode_t ret = QEO_EFAIL; qeojson_writer_t *jsonwriter = NULL; qeocore_type_t *typedesc = NULL; json_writer_dispatcher_cookie_t *dc = NULL; json_t *jsonTypeDesc = NULL; json_t *behavior = NULL; const char *expected_behaviour = NULL; int flags = QEOCORE_EFLAG_NONE; qeocore_writer_listener_t l = { 0 }; if ((NULL == factory) || (NULL == json_type)) { return NULL; } do { dc = calloc(1, sizeof(json_writer_dispatcher_cookie_t)); if (NULL == dc) { break; } dc->userdata = userdata; switch (writer_type) { case QEOJSON_WRITER_TYPE_EVENT_WRITER: flags = QEOCORE_EFLAG_EVENT_DATA; expected_behaviour = "event"; qeo_json_event_writer_listener_t *event_listener = (qeo_json_event_writer_listener_t *) listener; dc->etype = QEO_ETYPE_EVENT_DATA; dc->listener.event = *event_listener; if (NULL != event_listener->on_policy_update) { l.on_policy_update = qeojson_core_writer_policy_update_callback_dispatcher; } break; case QEOJSON_WRITER_TYPE_STATE_WRITER: flags = QEOCORE_EFLAG_STATE_DATA; expected_behaviour = "state"; qeo_json_state_writer_listener_t *state_listener = (qeo_json_state_writer_listener_t *)listener; dc->etype = QEO_ETYPE_STATE_DATA; dc->listener.state = *state_listener; if (NULL != state_listener->on_policy_update) { l.on_policy_update = qeojson_core_writer_policy_update_callback_dispatcher; } break; } jsonTypeDesc = json_loads(json_type, 0, NULL); if (NULL == jsonTypeDesc) { break; } if (!json_is_object(jsonTypeDesc)) { break; } behavior = json_object_get(jsonTypeDesc, KEY_BEHAVIOR); if (!json_is_string(behavior)) { break; } if (0 != strcmp(json_string_value(behavior), expected_behaviour)) { qeo_log_e("not matching expected behaviour %s", expected_behaviour); break; } jsonwriter = calloc(1, sizeof(qeojson_writer_t)); if (jsonwriter == NULL) { break; } jsonwriter->policy_cache = json_object(); json_object_set_new(jsonwriter->policy_cache, "users", json_array()); jsonwriter->policy = json_object(); json_object_set_new(jsonwriter->policy, "users", json_array()); #ifdef __USE_GNU /* compile with -D_GNU_SOURCE */ #ifndef NDEBUG jsonwriter->policy_mutex = (pthread_mutex_t)PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; #else jsonwriter->policy_mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER; #endif #else jsonwriter->policy_mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER; #endif typedesc = types_from_json(factory, jsonTypeDesc); if (NULL == typedesc) { qeo_log_e("typedesc == NULL"); break; } dc->typedesc = jsonTypeDesc; l.userdata = (uintptr_t)dc; dc->jsonwriter = jsonwriter; jsonwriter->writer = qeocore_writer_open(factory, // factory typedesc, // type NULL, // callback dispatcher flags, // flags &l, // callback cookie NULL); // return code qeocore_type_free(typedesc); if (NULL == jsonwriter->writer) { break; } ret = QEO_OK; } while (0); if (QEO_OK != ret) { json_decref(jsonTypeDesc); qeojson_writer_close(jsonwriter); jsonwriter = NULL; free(dc); } return jsonwriter; }