Пример #1
0
void incref_and_decref()
{
    json_t *obj = json_object();
    json_t *jay = json_string("周杰伦");
    json_object_set_new(obj, "name", jay);

    json_t *albums = json_array();
    json_t *alb1 = json_object();
    json_object_set_new(alb1, "name", json_string("范特西"));
    json_object_set_new(alb1, "year", json_string("2001"));
    json_array_append_new(albums, alb1);
    json_t *alb2 = json_object();
    json_object_set_new(alb2, "name", json_string("八度空间"));
    json_object_set_new(alb2, "year", json_string("2002"));
    json_array_append_new(albums, alb2);
    json_object_set_new(obj, "albums", albums);

    json_t *tmp = json_object_get(obj, "name");
    json_incref(tmp);

    json_t *arr = json_object_get(obj, "albums");
    json_t *ele = json_array_get(arr, 1);
    json_incref(arr);
    json_incref(ele);

    json_decref(obj);
    json_decref(tmp);
    json_decref(ele);
    json_decref(arr);
}
Пример #2
0
// Compute the effective value of the root_files configuration and
// return a json reference.  The caller must decref the ref when done
// (we may synthesize this value).   Sets enforcing to indicate whether
// we will only allow watches on the root_files.
// The array returned by this function (if not NULL) is guaranteed to
// list .watchmanconfig as its zeroth element.
json_t *cfg_compute_root_files(bool *enforcing) {
  json_t *ref;

  // This is completely undocumented and will go away soon. Do not document or
  // use!
  bool ignore_watchmanconfig = cfg_get_bool(NULL, "_ignore_watchmanconfig",
                                            false);

  *enforcing = false;

  ref = cfg_get_json(NULL, "enforce_root_files");
  if (ref) {
    if (!json_is_boolean(ref)) {
      w_log(W_LOG_FATAL,
          "Expected config value enforce_root_files to be boolean\n");
    }
    *enforcing = json_is_true(ref);
  }

  ref = cfg_get_json(NULL, "root_files");
  if (ref) {
    if (!is_array_of_strings(ref)) {
      w_log(W_LOG_FATAL,
          "global config root_files must be an array of strings\n");
      *enforcing = false;
      return NULL;
    }
    prepend_watchmanconfig_to_array(ref);

    json_incref(ref);
    return ref;
  }

  // Try legacy root_restrict_files configuration
  ref = cfg_get_json(NULL, "root_restrict_files");
  if (ref) {
    if (!is_array_of_strings(ref)) {
      w_log(W_LOG_FATAL, "deprecated global config root_restrict_files "
          "must be an array of strings\n");
      *enforcing = false;
      return NULL;
    }
    if (!ignore_watchmanconfig) {
      prepend_watchmanconfig_to_array(ref);
    }
    json_incref(ref);
    *enforcing = true;
    return ref;
  }

  // Synthesize our conservative default value.
  // .watchmanconfig MUST be first
  if (!ignore_watchmanconfig) {
    return json_pack("[ssss]", ".watchmanconfig", ".hg", ".git", ".svn");
  } else {
    return json_pack("[sss]", ".hg", ".git", ".svn");
  }
}
Пример #3
0
bool dispatch_command(struct watchman_client *client, json_t *args, int mode)
{
  struct watchman_command_handler_def *def;
  char *errmsg = NULL;
  bool result = false;
  char sample_name[128];

  // Stash a reference to the current command to make it easier to log
  // the command context in some of the error paths
  client->current_command = args;
  json_incref(client->current_command);

  def = lookup(args, &errmsg, mode);

  if (!def) {
    send_error_response(client, "%s", errmsg);
    goto done;
  }

  if (poisoned_reason && (def->flags & CMD_POISON_IMMUNE) == 0) {
    send_error_response(client, "%s", poisoned_reason);
    goto done;
  }

  if (!client->client_is_owner && (def->flags & CMD_ALLOW_ANY_USER) == 0) {
    send_error_response(client, "you must be the process owner to execute '%s'",
                        def->name);
    return false;
  }

  w_log(W_LOG_DBG, "dispatch_command: %s\n", def->name);
  snprintf(sample_name, sizeof(sample_name), "dispatch_command:%s", def->name);
  w_perf_start(&client->perf_sample, sample_name);
  w_perf_set_wall_time_thresh(
      &client->perf_sample,
      cfg_get_double(NULL, "slow_command_log_threshold_seconds", 1.0));

  result = true;
  def->func(client, args);

  if (w_perf_finish(&client->perf_sample)) {
    json_incref(args);
    w_perf_add_meta(&client->perf_sample, "args", args);
    w_perf_log(&client->perf_sample);
  } else {
    w_log(W_LOG_DBG, "dispatch_command: %s (completed)\n", def->name);
  }

done:
  free(errmsg);
  json_decref(client->current_command);
  client->current_command = NULL;
  w_perf_destroy(&client->perf_sample);
  return result;
}
Пример #4
0
void JsonApi::buildJsonState(json_t *jroot, std::function<void(json_t *)> result_lambda)
{
    json_incref(jroot);
    json_t *jinputs = json_object();
    json_t *joutputs = json_object();
    json_t *jaudio = json_array();

    json_t *jin = json_object_get(jroot, "inputs");
    if (jin && json_is_array(jin))
    {
        uint idx;
        json_t *value;

        json_array_foreach(jin, idx, value)
        {
            string svalue;

            if (!json_is_string(value)) continue;

            svalue = json_string_value(value);
            Input *input = ListeRoom::Instance().get_input(svalue);
            if (input)
            {
                if (input->get_type() == TBOOL)
                    json_object_set_new(jinputs, svalue.c_str(), json_string(input->get_value_bool()?"true":"false"));
                else if (input->get_type() == TINT)
                    json_object_set_new(jinputs, svalue.c_str(), json_string(Utils::to_string(input->get_value_double()).c_str()));
                else if (input->get_type() == TSTRING)
                    json_object_set_new(jinputs, svalue.c_str(), json_string(input->get_value_string().c_str()));
            }
        }
Пример #5
0
Json::Json( json_t *rhd ): data(rhd)
{
	if ( data == NULL )
		data = json_null();
	else
		json_incref( data );
}
Пример #6
0
static json_t *get_opt_array(json_t *object, const char *name,
                             const char *key, const char *short_key,
                             baton_error_t *error) {
    json_t *array;

    if (!json_is_object(object)) {
        set_baton_error(error, CAT_INVALID_ARGUMENT,
                        "Invalid %s: not a JSON object", name);
        goto error;
    }

    array = json_object_get(object, key);
    if (!array && short_key) {
        array = json_object_get(object, short_key);
    }

    if (array && !json_is_array(array)) {
        set_baton_error(error, CAT_INVALID_ARGUMENT,
                        "Invalid %s %s: not a JSON array", name, key);
        goto error;
    }

    if (!array) {
        array = json_array();
    } else {
        json_incref(array);
    }

    return array;

error:
    return NULL;
}
Пример #7
0
struct ast_json *ast_json_ref(struct ast_json *json)
{
	/* Jansson refcounting is non-atomic; lock it. */
	SCOPED_JSON_LOCK(json);
	json_incref((json_t *)json);
	return json;
}
Пример #8
0
void send_error_response(struct watchman_client *client,
    const char *fmt, ...)
{
  char buf[WATCHMAN_NAME_MAX];
  va_list ap;
  json_t *resp = make_response();
  json_t *errstr;

  va_start(ap, fmt);
  vsnprintf(buf, sizeof(buf), fmt, ap);
  va_end(ap);

  errstr = typed_string_to_json(buf, W_STRING_MIXED);
  set_prop(resp, "error", errstr);

  json_incref(errstr);
  w_perf_add_meta(&client->perf_sample, "error", errstr);

  if (client->current_command) {
    char *command = NULL;
    command = json_dumps(client->current_command, 0);
    w_log(W_LOG_ERR, "send_error_response: %s failed: %s\n",
        command, buf);
    free(command);
  } else {
    w_log(W_LOG_ERR, "send_error_response: %s\n", buf);
  }

  send_and_dispose_response(client, resp);
}
Пример #9
0
MltRuntime::MltRuntime(json_t* script_serialed, int give) throw(Exception):
	json_version(0),
	producer_version(0),
	json_serialize(NULL),
	producer(NULL),
	consumer(NULL),
	status(StatusCreated)
{
	if ( !script_serialed || !json_is_object(script_serialed)
			|| !json_object_size(script_serialed)) {
		if ( give && script_serialed ) json_decref(script_serialed);
		throw_error_v(ErrorImplError,"Init MltRuntime with empty json");
	}
	if (give)
		json_serialize = script_serialed;
	else
		json_serialize = json_incref(script_serialed);

	try {
		parse_struct(json_serialize, JsonPath(), uuid_pathmap);
	}
	catch(Exception& e)
	{
		if (give && json_serialize) json_decref(json_serialize);
		throw;
	}
	json_version++;
	pthread_mutex_init(&run_lock,NULL);
}
Пример #10
0
	inline Json &operator=(const Json &from)
	{
		if (json)
			json_decref(json);
		json = json_incref(from.json);
		return *this;
	}
Пример #11
0
Json Json::get(const std::string& key) const {
   if (isObject()) { 
      return Json(json_incref(json_object_get(m_json, key.c_str())));
   } else { 
      throw std::domain_error("This method only applies to object type");
   }
}
Пример #12
0
json_t *tr_cfg_files_to_json_array(TR_CFG *cfg)
{
  guint ii;
  json_t *jarray = json_array();
  json_t *retval = NULL;

  if (jarray == NULL)
    goto cleanup;

  for (ii=0; ii<cfg->files->len; ii++) {
    ARRAY_APPEND_OR_FAIL(jarray,
                         tr_cfg_file_to_json(
                             &g_array_index(cfg->files, TR_CFG_FILE, ii)));
  }

  /* success */
  retval = jarray;
  json_incref(retval);

cleanup:
  if (jarray)
    json_decref(jarray);

  return retval;
}
Пример #13
0
static cxJson jsonToAny(json_t *v)
{
    CX_RETURN(v == NULL,NULL);
    cxJson rv = CX_CREATE(cxJson);
    rv->json = json_incref(v);
    return rv;
}
Пример #14
0
Json::Json( Json const &rhd ): data(rhd.data)
{
	if ( data == NULL )
		data = json_null();
	else
		json_incref( data );
}
Пример #15
0
//native Handle:json_object_iter_value(Handle:hIter, String:sValueBuffer[], maxlength);
static cell_t Native_json_object_iter_value(IPluginContext *pContext, const cell_t *params) {
	HandleError err;
	HandleSecurity sec;
	sec.pOwner = NULL;
	sec.pIdentity = myself->GetIdentity();

	// Param 1
    void *iter;
	Handle_t hndlIterator = static_cast<Handle_t>(params[1]);
	if ((err=g_pHandleSys->ReadHandle(hndlIterator, htJanssonIterator, &sec, (void **)&iter)) != HandleError_None)
    {
        pContext->ThrowNativeError("Invalid <JSON Iterator> handle %x (error %d)", hndlIterator, err);
        return BAD_HANDLE;
    }

    json_t *result = json_object_iter_value(iter);

	// Return
	if(result == NULL) {
		return BAD_HANDLE;
	}

	Handle_t hndlResult = g_pHandleSys->CreateHandle(htJanssonObject, result, pContext->GetIdentity(), myself->GetIdentity(), NULL);
	if(hndlResult == BAD_HANDLE) {
		pContext->ThrowNativeError("Could not create handle for iterator element.");
		return BAD_HANDLE;
	}

	// result is a borrowed reference, we don't know what will happen with it
	// so we increase the reference counter, which enforces the developer to
	// CloseHandle() it.
	json_incref(result);

	return hndlResult;
}
Пример #16
0
flux_kvsdir_t *kvsdir_create_fromobj (flux_t *handle, const char *rootref,
                                      const char *key, json_t *treeobj)
{
    flux_kvsdir_t *dir = NULL;

    if (!key || !treeobj || treeobj_validate (treeobj) < 0
                         || !treeobj_is_dir (treeobj)) {
        errno = EINVAL;
        goto error;
    }
    if (!(dir = calloc (1, sizeof (*dir))))
        goto error;

    dir->handle = handle;
    if (rootref) {
        if (!(dir->rootref = strdup (rootref)))
            goto error;
    }
    if (!(dir->key = strdup (key)))
        goto error;
    dir->dirobj = json_incref (treeobj);
    dir->usecount = 1;

    return dir;
error:
    flux_kvsdir_destroy (dir);
    return NULL;
}
Пример #17
0
static bool _cjose_jwe_build_hdr(
        cjose_jwe_t *jwe, 
        cjose_header_t *header,
        cjose_err *err)
{
    // save header object as part of the JWE (and incr. refcount)
    jwe->hdr = header;
    json_incref(jwe->hdr);

    // serialize the header
    char *hdr_str = json_dumps(header, JSON_ENCODE_ANY | JSON_PRESERVE_ORDER);
    if (NULL == hdr_str)
    {
        CJOSE_ERROR(err, CJOSE_ERR_NO_MEMORY);
        return false;
    }

    // copy the serialized header to JWE (hdr_str is owned by header object)
    jwe->part[0].raw = (uint8_t *)strdup(hdr_str);
    if (NULL == jwe->part[0].raw)
    {
        CJOSE_ERROR(err, CJOSE_ERR_NO_MEMORY);
        cjose_get_dealloc()(hdr_str);
        return false;
    }
    jwe->part[0].raw_len = strlen(hdr_str);
    cjose_get_dealloc()(hdr_str);
    
    return true;
}
Пример #18
0
TID_REQ *tid_dup_req (TID_REQ *orig_req) 
{
  TID_REQ *new_req = NULL;

  if (NULL == (new_req = talloc_zero(orig_req, TID_REQ))) {
    tr_crit("tid_dup_req: Can't allocated duplicate request.");
    return NULL;
  }

  /* Memcpy for flat fields, not valid until names are duped. */
  memcpy(new_req, orig_req, sizeof(TID_REQ));
  json_incref(new_req->json_references);
  new_req->free_conn = 0;
  
  if ((NULL == (new_req->rp_realm = tr_dup_name(orig_req->rp_realm))) ||
      (NULL == (new_req->realm = tr_dup_name(orig_req->realm))) ||
      (NULL == (new_req->comm = tr_dup_name(orig_req->comm)))) {
	tr_crit("tid_dup_req: Can't duplicate request (names).");
  }

  if (orig_req->orig_coi) {
    if (NULL == (new_req->orig_coi = tr_dup_name(orig_req->orig_coi))) {
      tr_crit("tid_dup_req: Can't duplicate request (orig_coi).");
    }
  }
  
  return new_req;
}
Пример #19
0
//## Json Json.new();
static KMETHOD Json_new (KonohaContext *kctx, KonohaStack *sfp)
{
	struct _kJson* json = (struct _kJson *)KLIB new_kObjectDontUseThis(kctx, KGetReturnType(sfp), 0);
	json->obj = json_object();
	json_incref(json->obj);
	KReturn(json);
}
Пример #20
0
//native Handle:json_array_get(Handle:hArray, iIndex);
static cell_t Native_json_array_get(IPluginContext *pContext, const cell_t *params) {
	HandleError err;
	HandleSecurity sec;
	sec.pOwner = NULL;
	sec.pIdentity = myself->GetIdentity();

	// Param 1
	json_t *object;
	Handle_t hndlObject = static_cast<Handle_t>(params[1]);
	if ((err=g_pHandleSys->ReadHandle(hndlObject, htJanssonObject, &sec, (void **)&object)) != HandleError_None)
    {
        return pContext->ThrowNativeError("Invalid <Array> handle %x (error %d)", hndlObject, err);
    }

	// Param 2
	int iIndex = params[2];
	json_t *result = json_array_get(object, iIndex);
	if(result == NULL) {
		return BAD_HANDLE;
	}

	Handle_t hndlResult = g_pHandleSys->CreateHandle(htJanssonObject, result, pContext->GetIdentity(), myself->GetIdentity(), NULL);
	if(hndlResult == BAD_HANDLE) {
		pContext->ThrowNativeError("Could not create handle for array element.");
		return BAD_HANDLE;
	}

	// result is a borrowed reference, we don't know what will happen with it
	// so we increase the reference counter, which enforces the developer to
	// CloseHandle() it.
	json_incref(result);

	return hndlResult;
}
Пример #21
0
// Compute the effective value of the root_files configuration and
// return a json reference.  The caller must decref the ref when done
// (we may synthesize this value).   Sets enforcing to indicate whether
// we will only allow watches on the root_files.
// The array returned by this function (if not NULL) is guaranteed to
// list .watchmanconfig as its zeroth element.
json_t *cfg_compute_root_files(bool *enforcing) {
  json_t *ref;

  *enforcing = false;

  ref = cfg_get_json(NULL, "enforce_root_files");
  if (ref) {
    if (!json_is_boolean(ref)) {
      w_log(W_LOG_FATAL,
          "Expected config value enforce_root_files to be boolean\n");
    }
    *enforcing = json_is_true(ref);
  }

  ref = cfg_get_json(NULL, "root_files");
  if (ref) {
    if (!is_array_of_strings(ref)) {
      w_log(W_LOG_FATAL,
          "global config root_files must be an array of strings\n");
      *enforcing = false;
      return NULL;
    }
    prepend_watchmanconfig_to_array(ref);

    json_incref(ref);
    return ref;
  }

  // Try legacy root_restrict_files configuration
  ref = cfg_get_json(NULL, "root_restrict_files");
  if (ref) {
    if (!is_array_of_strings(ref)) {
      w_log(W_LOG_FATAL, "deprecated global config root_restrict_files "
          "must be an array of strings\n");
      *enforcing = false;
      return NULL;
    }
    prepend_watchmanconfig_to_array(ref);
    json_incref(ref);
    *enforcing = true;
    return ref;
  }

  // Synthesize our conservative default value.
  // .watchmanconfig MUST be first
  return json_pack("[ssss]", ".watchmanconfig", ".hg", ".git", ".svn");
}
Пример #22
0
static void SetJsonBuf(struct JsonBuf *jsonbuf, json_t *json)
{
	json_incref(json);
	if(jsonbuf->jsonobj != NULL) {
		json_decref(jsonbuf->jsonobj);
	}
	jsonbuf->jsonobj = json;
}
Пример #23
0
void JSON::operator=(JSON const &o) {
	if(json) {
		json_decref(json);
	}
	if(o.json) {
		json = json_incref(o.json);
	}
}
Пример #24
0
Json &Json::operator=( const Json &other )
{
	json_t *cur = data;
	data = other.data;

	json_incref( data );
	json_decref( cur );
	return *this;
}
Пример #25
0
unknown &unknown::operator=(const unknown &o) {
	if (o.m_val) {
		json_decref(o.m_val);
	}
	if (m_val) {
		json_incref(m_val);
	}
	m_val = o.m_val;
	return *this;
}
Пример #26
0
/* trigger /root triggername [watch patterns] -- cmd to run
 * Sets up a trigger so that we can execute a command when a change
 * is detected */
void cmd_trigger(struct watchman_client *client, json_t *args)
{
  w_root_t *root;
  struct watchman_trigger_command *cmd;
  json_t *resp;
  json_t *trig;
  char *errmsg = NULL;

  root = resolve_root_or_err(client, args, 1, true);
  if (!root) {
    return;
  }

  if (json_array_size(args) < 3) {
    send_error_response(client, "not enough arguments");
    goto done;
  }

  trig = json_array_get(args, 2);
  if (json_is_string(trig)) {
    trig = build_legacy_trigger(client, args);
    if (!trig) {
      goto done;
    }
  } else {
    // Add a ref so that we don't need to conditionally decref later
    // for the legacy case later
    json_incref(trig);
  }

  cmd = w_build_trigger_from_def(root, trig, &errmsg);
  json_decref(trig);

  if (!cmd) {
    send_error_response(client, "%s", errmsg);
    goto done;
  }

  w_root_lock(root);
  w_ht_replace(root->commands, w_ht_ptr_val(cmd->triggername),
      w_ht_ptr_val(cmd));
  w_root_unlock(root);

  w_state_save();

  resp = make_response();
  set_prop(resp, "triggerid", json_string_nocheck(cmd->triggername->buf));
  send_and_dispose_response(client, resp);

done:
  if (errmsg) {
    free(errmsg);
  }
  w_root_delref(root);
}
Пример #27
0
/**
 * Loads a LoginPackage object from a string.
 */
tABC_CC ABC_LoginPackageDecode(tABC_LoginPackage **ppSelf,
                               char *szLoginPackage,
                               tABC_Error *pError)
{
    tABC_CC cc = ABC_CC_Ok;
    tABC_LoginPackage *pSelf = NULL;
    json_t  *pJSON_Root     = NULL;
    int     e;

    // Allocate self:
    ABC_NEW(pSelf, tABC_LoginPackage);

    // Parse the JSON:
    json_error_t error;
    pJSON_Root = json_loads(szLoginPackage, 0, &error);
    ABC_CHECK_ASSERT(pJSON_Root != NULL, ABC_CC_JSONError, "Error parsing LoginPackage JSON");
    ABC_CHECK_ASSERT(json_is_object(pJSON_Root), ABC_CC_JSONError, "Error parsing LoginPackage JSON");

    // Unpack the contents:
    e = json_unpack(pJSON_Root, "{s?o, s?o, s:o, s?o, s?o}",
                    JSON_ACCT_EMK_LP2_FIELD,     &pSelf->EMK_LP2,
                    JSON_ACCT_EMK_LRA3_FIELD,    &pSelf->EMK_LRA3,
                    JSON_ACCT_ESYNCKEY_FIELD,    &pSelf->ESyncKey,
                    JSON_ACCT_ELP1_FIELD,        &pSelf->ELP1,
                    JSON_ACCT_ELRA1_FIELD,       &pSelf->ELRA1);
    ABC_CHECK_SYS(!e, "Error parsing LoginPackage JSON");

    // Save everything:
    if (pSelf->EMK_LP2)     json_incref(pSelf->EMK_LP2);
    if (pSelf->EMK_LRA3)    json_incref(pSelf->EMK_LRA3);
    if (pSelf->ESyncKey)    json_incref(pSelf->ESyncKey);
    if (pSelf->ELP1)        json_incref(pSelf->ELP1);
    if (pSelf->ELRA1)       json_incref(pSelf->ELRA1);
    *ppSelf = pSelf;
    pSelf = NULL;

exit:
    if (pSelf)          ABC_LoginPackageFree(pSelf);
    if (pJSON_Root)     json_decref(pJSON_Root);

    return cc;
}
Пример #28
0
Json Json::at(int index) const { 
   if (isArray()) { 
      json_t* array = json_array_get(m_json, index); 
      if (array == NULL) { 
         std::out_of_range("array index is out of range or json entity is not an array");
      } 
      return Json(json_incref(array));
   } else { 
      throw std::domain_error("cannot use at(int index) with this json type");
   }
}
Пример #29
0
Json& Json::operator=(const Json& json) {
   json_t* old = m_json;
   m_json = json.m_json;
   if (m_json) {
      json_incref(m_json);
   }
   if (old) {
      json_decref(old);
   }
   return (*this);
}
Пример #30
0
bool parse_field_list(json_t *field_list,
    struct w_query_field_list *selected,
    char **errmsg)
{
  uint32_t i, f;

  memset(selected, 0, sizeof(*selected));

  if (field_list == NULL) {
    // Use the default list
    field_list = json_pack("[sssss]", "name", "exists", "new", "size", "mode");
  } else {
    // Add a ref so that we don't need complicated logic to deal with
    // whether we defaulted or not; just unconditionally delref on return
    json_incref(field_list);
  }

  if (!json_is_array(field_list)) {
    *errmsg = strdup("field list must be an array of strings");
    json_decref(field_list);
    return false;
  }

  for (i = 0; i < json_array_size(field_list); i++) {
    json_t *jname = json_array_get(field_list, i);
    const char *name;
    bool found = false;

    if (!json_is_string(jname)) {
      *errmsg = strdup("field list must be an array of strings");
      json_decref(field_list);
      return false;
    }

    name = json_string_value(jname);

    for (f = 0; field_defs[f].name; f++) {
      if (!strcmp(name, field_defs[f].name)) {
        found = true;
        selected->fields[selected->num_fields++] = &field_defs[f];
        break;
      }
    }

    if (!found) {
      ignore_result(asprintf(errmsg, "unknown field name '%s'", name));
      json_decref(field_list);
      return false;
    }
  }

  json_decref(field_list);
  return true;
}