コード例 #1
0
ファイル: searpc-utils.c プロジェクト: 9thsector/libsearpc
static gboolean json_deserialize_pspec (GValue *value, GParamSpec *pspec, json_t *node)
{ 
    switch (json_typeof(node)) {
        case JSON_OBJECT:
            if (g_type_is_a (G_VALUE_TYPE (value), G_TYPE_OBJECT)) {
                GObject *object;
                object = json_gobject_deserialize (G_VALUE_TYPE (value), node);
                if (object)
                  g_value_take_object (value, object);
                else
                  g_value_set_object (value, NULL);

                return TRUE;
            }
            break;
      case JSON_STRING:
          if (G_TYPE_FUNDAMENTAL (G_VALUE_TYPE (value)) == G_TYPE_STRING) {
              g_value_set_string(value, json_string_value(node));
              return TRUE;
          }
          break;
      case JSON_INTEGER:
          {
              json_int_t int_value = json_integer_value (node);
              switch (G_TYPE_FUNDAMENTAL (G_VALUE_TYPE (value))) {
                  case G_TYPE_CHAR:
                      g_value_set_schar(value, (gchar)int_value);
                      return TRUE;
                  case G_TYPE_UCHAR:
                      g_value_set_uchar (value, (guchar)int_value);
                      return TRUE;
                  case G_TYPE_INT:
                      g_value_set_int (value, (gint)int_value);
                      return TRUE;
                  case G_TYPE_UINT:
                      g_value_set_uint(value, (guint)int_value);
                      return TRUE;
                  case G_TYPE_LONG:
                      g_value_set_long(value, (glong)int_value);
                      return TRUE;
                  case G_TYPE_ULONG:
                      g_value_set_ulong(value, (gulong)int_value);
                      return TRUE;
                  case G_TYPE_INT64:
                      g_value_set_int64(value,(gint64)int_value);
                      return TRUE;
                  case G_TYPE_ENUM:
                      g_value_set_enum(value,(gint64)int_value);
                      return TRUE;
                  case G_TYPE_FLAGS:
                      g_value_set_flags(value,(gint64)int_value);
                      return TRUE;
              }
          }
          break;
      case JSON_REAL:
          {
              double real_value = json_real_value(node);
              switch (G_TYPE_FUNDAMENTAL (G_VALUE_TYPE (value))) {
                  case G_TYPE_FLOAT:
                    g_value_set_float(value,(gfloat)real_value);
                    return TRUE;
                  case G_TYPE_DOUBLE:
                    g_value_set_double(value,(gdouble)real_value);
                    return TRUE;
              }
          }
        break;
      case JSON_TRUE:
      case JSON_FALSE:
          if (G_TYPE_FUNDAMENTAL (G_VALUE_TYPE (value)) == G_TYPE_BOOLEAN) {
              g_value_set_boolean(value,(gboolean)json_is_true(node));
              return TRUE;
          }
          break;
      case JSON_NULL:
          if (G_TYPE_FUNDAMENTAL (G_VALUE_TYPE (value)) == G_TYPE_STRING) {
              g_value_set_string (value, NULL);
              return TRUE;
          }
          else if (G_TYPE_FUNDAMENTAL (G_VALUE_TYPE (value)) == G_TYPE_OBJECT) {
              g_value_set_object (value, NULL);
              return TRUE;
          }
          break;
      case JSON_ARRAY:
          return FALSE;
          break;
      default:
          return FALSE;
  }

  return FALSE;

}
コード例 #2
0
ファイル: ffigen.c プロジェクト: iamaaditya/cshore
enum CXChildVisitResult visit_program(CXCursor cursor, CXCursor parent, CXClientData data){
  json_t* program = (json_t*)data;
  json_t* js = NULL;
  enum CXChildVisitResult ret = CXChildVisit_Continue;
  switch (clang_getCursorKind(cursor)) {
  case CXCursor_FunctionDecl:
  case CXCursor_VarDecl:
    js = json_object();
    json_object_set_new(js, "name", render_string(clang_getCursorSpelling(cursor)));
    json_object_set_new(js, "display_name", render_string(clang_getCursorDisplayName(cursor)));
    json_object_set_new(js, "type", render_type(clang_getCursorType(cursor)));
    if (clang_getCursorKind(cursor) == CXCursor_FunctionDecl) {
      json_object_set_new(js, "argument_names", json_array());
      json_object_set_new(js, "kind", json_string("function"));
    } else {
      json_object_set_new(js, "kind", json_string("variable"));
    }
    switch (clang_getCursorLinkage(cursor)) {
    case CXLinkage_Internal:
      json_object_set_new(js, "linkage", json_string("static"));
      break;
    case CXLinkage_UniqueExternal:
      json_object_set_new(js, "linkage", json_string("anonymous"));
      break;
    case CXLinkage_External:
      break;
    default:
      json_object_set_new(js, "linkage", json_string("unknown"));
    }
    clang_visitChildren(cursor, visit_object, (CXClientData)js);
    
    break;
    
  case CXCursor_StructDecl:
  case CXCursor_UnionDecl:
    js = json_object();
    json_object_set_new(js, "kind", json_string(clang_getCursorKind(cursor) == CXCursor_UnionDecl ? 
                                                "union" : "struct"));
    json_object_set_new(js, "name", render_string(clang_getCursorSpelling(cursor)));
    json_object_set_new(js, "fields", json_array());
    clang_visitChildren(cursor, visit_structure, (CXClientData)js);
    ret = CXChildVisit_Recurse;
    break;

  case CXCursor_EnumDecl:
    js = json_object();
    json_object_set_new(js, "kind", json_string("enum"));
    json_object_set_new(js, "name", render_string(clang_getCursorSpelling(cursor)));
    json_object_set_new(js, "values", json_array());
    clang_visitChildren(cursor, visit_enum, (CXClientData)js);
    break;

  case CXCursor_TypedefDecl:
    js = json_object();
    json_object_set_new(js, "kind", json_string("typedef"));
    json_object_set_new(js, "name", render_string(clang_getCursorSpelling(cursor)));
    json_object_set_new(js, "type", render_type(clang_getTypedefDeclUnderlyingType(cursor)));
    ret = CXChildVisit_Recurse;
    break;


  case CXCursor_FieldDecl:
    break;

  case CXCursor_MacroDefinition:
    js = json_object();
    json_object_set_new(js, "kind", json_string("macro"));
    {
      CXToken* tokens;
      unsigned ntokens, i;
      CXString name = clang_getCursorSpelling(cursor);
      char value_buf[1024] = "";
      json_object_set_new(js, "name", render_string(clang_getCursorSpelling(cursor)));
      clang_tokenize(TU, clang_getCursorExtent(cursor), &tokens, &ntokens);
      for (i=0; i<ntokens; i++) {
        CXString str = clang_getTokenSpelling(TU, tokens[i]);
        CXTokenKind tkind = clang_getTokenKind(tokens[i]);
        if (i == 0 && !strcmp(clang_getCString(name), clang_getCString(str))) {
          // macro name
        } else if (i == ntokens - 1 && 
                   tkind == CXToken_Punctuation && !strcmp("#", clang_getCString(str))) {
          // weird clang terminator thingy
        } else if (tkind == CXToken_Comment) {
          // comment
        } else {
          if (strlen(value_buf) > 0) {
            strncat(value_buf, " ", sizeof(value_buf) - strlen(value_buf) - 1);
          }
          strncat(value_buf, clang_getCString(str), sizeof(value_buf) - strlen(value_buf) - 1);
        }
        clang_disposeString(str);
      }
      clang_disposeTokens(TU, tokens, ntokens);
      if (strlen(value_buf) > 0) {
        long int intval;
        double dblval;
        char* endptr_int;
        char* endptr_dbl;
        intval = strtol(value_buf, &endptr_int, 0);
        dblval = strtod(value_buf, &endptr_dbl);
        if (endptr_int[0] == 0 ||
            (endptr_int[1] == 0 && strchr("UuLl", endptr_int[0]) != NULL)) {
          json_object_set_new(js, "value", json_integer(intval));
        } else if (endptr_dbl[0] == 0 || 
                   (endptr_dbl[1] == 0 && strchr("fF", endptr_dbl[0]) != NULL)) {
          json_object_set_new(js, "value", json_real(dblval));
        } else {
          json_object_set_new(js, "value", json_string(value_buf));
        }
      }
    }
    break;

    /*
  case CXCursor_PreprocessingDirective:
  case CXCursor_MacroExpansion:
    js = json_object();
    json_object_set_new(js, "kind", json_string("macro"));
    json_object_set_new(js, "name", render_string(clang_getCursorSpelling(cursor)));
    putstring(clang_getCursorSpelling(cursor));
    putstring(clang_getCursorDisplayName(cursor));
    printf("%d\n", clang_getEnumConstantDeclValue(cursor));
    
    ret = CXChildVisit_Recurse;
    */

  default:
    js = json_object();
    json_object_set_new(js, "name", render_string(clang_getCursorSpelling(cursor)));
    json_object_set_new(js, "type", render_type(clang_getCursorType(cursor)));
    json_object_set_new(js, "kind", json_string("wtf"));
    json_object_set_new(js, "wtf", render_string(clang_getCursorKindSpelling(clang_getCursorKind(cursor))));
  }

  if (js) {
    json_t* str;
    if (!json_object_get(program, "")) json_object_set_new(program, "", json_array());
    str = render_string(clang_getCursorUSR(cursor));
    if (strlen(json_string_value(str)) == 0) {
      json_decref(str);
      json_array_append_new(json_object_get(program, ""), js);
    } else {
      json_object_set_with_key_new(program, render_string(clang_getCursorUSR(cursor)), js);
    }
  }

  return ret;
}
コード例 #3
0
pweibo_user weibo_user_create_json(json_t* pJson)
{
    if (!pJson) {
        PERR("could not parse json!\n");
        return NULL; 
    }

    void *iter = json_object_iter(pJson);
    pweibo_user pUser = weibo_user_init();

    while (iter) {
        const char* key = json_object_iter_key(iter);
        //DEBUG("%s\n", key);
        json_t *value = json_object_iter_value(iter);
        if(!value) {
            iter = json_object_iter_next(pJson, iter);
            continue;
        }
        //DEBUG("%d\n", value->type);

        if (0 == strcmp("id", key)) {
            pUser->m_szID = g_string_new("");
            g_string_printf(pUser->m_szID, "%"JSON_INTEGER_FORMAT, json_integer_value(value));
        } else if (0 == strcmp("screen_name", key)) {
            pUser->m_szScreenName = g_string_new(json_string_value(value));
        } else if (0 == strcmp("name", key)) {
            pUser->m_szName = g_string_new(json_string_value(value));
        } else if (0 == strcmp("province", key)) {
            pUser->m_nProvince = json_integer_value(value);
        } else if (0 == strcmp("city", key)) {
            pUser->m_nCity = json_integer_value(value);
        } else if (0 == strcmp("location", key)) {
            pUser->m_szLocation = g_string_new(json_string_value(value));
        } else if (0 == strcmp("description", key)) {
            pUser->m_szDescription = g_string_new(json_string_value(value));
        } else if (0 == strcmp("url", key)) {
            pUser->m_szUrl = g_string_new(json_string_value(value));
        } else if (0 == strcmp("profile_image_url", key)) {
            pUser->m_szProfileImageUrl = g_string_new(json_string_value(value));
        } else if (0 == strcmp("domain", key)) {
            pUser->m_szDomain = g_string_new(json_string_value(value));
        } else if (0 == strcmp("gender", key)) {
            pUser->m_szGender = g_string_new(json_string_value(value));
        } else if (0 == strcmp("followers_count", key)) {
            pUser->m_nFollowersCount = json_integer_value(value);
        } else if (0 == strcmp("friends_count", key)) {
            pUser->m_nFriendsCount = json_integer_value(value);
        } else if (0 == strcmp("statuses_count", key)) {
            pUser->m_nStatusesCount = json_integer_value(value);
        } else if (0 == strcmp("favourites_count", key)) {
            pUser->m_nFavouritesCount = json_integer_value(value);
        } else if (0 == strcmp("created_at", key)) {
            pUser->m_szCreatedAt = g_string_new(json_string_value(value));
        } else if (0 == strcmp("following", key)) {
            pUser->m_bFollowing = json_is_true(value) ? TRUE : FALSE;
        } else if (0 == strcmp("allow_all_act_msg", key)) {
            pUser->m_bAllowAllActMsg = json_is_true(value) ? TRUE : FALSE;
        } else if (0 == strcmp("geo_enabled", key)) {
            pUser->m_bGeoEnabled = json_is_true(value) ? TRUE : FALSE;
        } else if (0 == strcmp("verified", key)) {
            pUser->m_bVerified = json_is_true(value) ? TRUE : FALSE;
        } else if (0 == strcmp("status", key)) {
            PERR("%s-->%d\n", key, value->type);
            POS();
            pUser->m_pFeed = weibo_feed_create_json(value);
            PERR("%d\n", pUser->m_pFeed);
            PERR("%s\n", ((pweibo_feed)(pUser->m_pFeed))->m_szID->str);
        }

        iter = json_object_iter_next(pJson, iter);
    }
    json_decref(pJson);

    return pUser;
}
コード例 #4
0
ファイル: server.c プロジェクト: ebonical/spotify-api-server
static void put_playlist_patch(sp_playlist *playlist,
                               struct evhttp_request *request,
                               void *userdata) {
  struct state *state = userdata;
  struct evbuffer *buf = evhttp_request_get_input_buffer(request);
  size_t buflen = evbuffer_get_length(buf);

  if (buflen == 0) {
    send_error(request, HTTP_BADREQUEST, "No body");
    return;
  }

  // Read request body
  json_error_t loads_error;
  json_t *json = read_request_body_json(request, &loads_error);

  if (json == NULL) {
    send_error(request, HTTP_BADREQUEST,
               loads_error.text ? loads_error.text : "Unable to parse JSON");
    return;
  }

  if (!json_is_array(json)) {
    json_decref(json);
    send_error(request, HTTP_BADREQUEST, "Not valid JSON array");
    return;
  }

  // Handle empty array
  int num_tracks = json_array_size(json);

  if (num_tracks == 0) {
    send_reply(request, HTTP_OK, "OK", NULL);
    return;
  }

  sp_track **tracks = calloc(num_tracks, sizeof (sp_track *));
  int num_valid_tracks = 0;

  for (int i = 0; i < num_tracks; i++) {
    json_t *item = json_array_get(json, i);

    if (!json_is_string(item)) {
      json_decref(item);
      continue;
    }

    char *uri = strdup(json_string_value(item));
    sp_link *track_link = sp_link_create_from_string(uri);
    free(uri);

    if (track_link == NULL)
      continue;

    if (sp_link_type(track_link) != SP_LINKTYPE_TRACK) {
      sp_link_release(track_link);
      continue;
    }

    sp_track *track = sp_link_as_track(track_link);

    if (track == NULL)
      continue;

    tracks[num_valid_tracks++] = track;
  }

  json_decref(json);

  // Bail if no tracks could be read from input
  if (num_valid_tracks == 0) {
    send_error(request, HTTP_BADREQUEST, "No valid tracks");
    free(tracks);
    return;
  }

  tracks = realloc(tracks, num_valid_tracks * sizeof (sp_track *));

  // Apply diff
  apr_pool_t *pool = state->pool;
  svn_diff_t *diff;
  svn_error_t *diff_error = diff_playlist_tracks(&diff, playlist, tracks,
                                                 num_valid_tracks, pool);

  if (diff_error != SVN_NO_ERROR) {
    free(tracks);
    svn_handle_error2(diff_error, stderr, false, "Diff");
    send_error(request, HTTP_BADREQUEST, "Search failed");
    return;
  }

  svn_error_t *apply_error = diff_playlist_tracks_apply(diff, playlist, tracks,
                                                        num_valid_tracks,
                                                        state->session);

  if (apply_error != SVN_NO_ERROR) {
    free(tracks);
    svn_handle_error2(apply_error, stderr, false, "Updating playlist");
    send_error(request, HTTP_BADREQUEST, "Could not apply diff");
    return;
  }

  if (!sp_playlist_has_pending_changes(playlist)) {
    free(tracks);
    get_playlist(playlist, request, NULL);
    return;
  }

  free(tracks);
  register_playlist_callbacks(playlist, request, &get_playlist,
                              &playlist_update_in_progress_callbacks, NULL);
}
コード例 #5
0
ファイル: msg_invoke.c プロジェクト: ghalwasi/c-mlib
int broker_msg_handle_invoke(RemoteDSLink *link, json_t *req) {
    json_t *reqRid = json_object_get(req, "rid");
    json_t *reqPath = json_object_get(req, "path");
    if (!(reqRid && reqPath)) {
        return 1;
    }
    json_t *maxPermitJson = json_object_get(req, "permit");
    PermissionLevel maxPermit = PERMISSION_CONFIG;
    if (json_is_string(maxPermitJson)) {
        maxPermit = permission_str_level(json_string_value(maxPermitJson));
    }

    const char *path = json_string_value(reqPath);
    char *out = NULL;
    BrokerNode *node = broker_node_get(link->broker->root, path, &out);
    if (!node) {
        broker_utils_send_closed_resp(link, req, "disconnected");
        return 0;
    }

    Broker *broker = mainLoop->data;

    PermissionLevel permissionOnPath = get_permission(path, broker->root, link);
    if (permissionOnPath > maxPermit) {
        permissionOnPath = maxPermit;
    }

    if (permissionOnPath == PERMISSION_NONE) {
        broker_utils_send_closed_resp(link, req, "permissionDenied");
        return 0;
    }
    if (node->type == REGULAR_NODE) {
        json_t *invokableJson = json_object_get(node->meta, "$invokable");

        PermissionLevel level = permission_str_level(json_string_value(invokableJson));
        if (level > permissionOnPath) {
            broker_utils_send_closed_resp(link, req, "permissionDenied");
        } else if (node->on_invoke) {
            node->on_invoke(link, node, req, maxPermit);
        }
        return 0;
    } else if (node->type != DOWNSTREAM_NODE) {
        // Unknown node type
        broker_utils_send_closed_resp(link, req, "disconnected");
        return 0;
    }

    DownstreamNode *ds = (DownstreamNode *) node;
    uint32_t rid = broker_node_incr_rid(ds);

    if (!ds->link) {
        broker_utils_send_closed_resp(link, req, "disconnected");
        return 0;
    }

    BrokerInvokeStream *s = broker_stream_invoke_init();

    s->responder_rid = rid;
    s->responder = ds->link;
    s->resp_close_cb = remote_invoke_resp_disconnected;

    s->requester_rid = (uint32_t) json_integer_value(reqRid);
    s->requester = link;
    s->req_close_cb = remote_invoke_req_closed;

    ref_t *refStream = dslink_ref(s, NULL);
    dslink_map_set(&ds->link->responder_streams, dslink_int_ref(rid),
                   refStream);

    ref_t *findref = dslink_map_remove_get(&link->requester_streams, &s->requester_rid);
    if (findref) {
        BrokerStream *oldstream = findref->data;
        if (oldstream->req_close_cb) {
            oldstream->req_close_cb(oldstream, link);
        }
        broker_stream_free(oldstream);
        dslink_decref(findref);
    }
    dslink_map_set(&link->requester_streams,
                   dslink_int_ref(s->requester_rid),
                   dslink_incref(refStream));

    send_invoke_request(ds, req, rid, out, permissionOnPath);
    return 0;
}
コード例 #6
0
ファイル: proto.c プロジェクト: eugeniop/mod_auth_openidc
/*
 * validate the "aud" and "azp" claims in the id_token payload
 */
static apr_byte_t oidc_proto_validate_aud_and_azp(request_rec *r, oidc_cfg *cfg,
		oidc_provider_t *provider, apr_jwt_payload_t *id_token_payload) {

	char *azp = NULL;
	apr_jwt_get_string(r->pool, &id_token_payload->value, "azp", &azp);

	/*
	 * the "azp" claim is only needed when the id_token has a single audience value and that audience
	 * is different than the authorized party; it MAY be included even when the authorized party is
	 * the same as the sole audience.
	 */
	if ((azp != NULL) && (apr_strnatcmp(azp, provider->client_id) != 0)) {
		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
				"oidc_proto_validate_aud_and_azp: the \"azp\" claim (%s) is present in the id_token, but is not equal to the configured client_id (%s)",
				azp, provider->client_id);
		return FALSE;
	}

	/* get the "aud" value from the JSON payload */
	json_t *aud = json_object_get(id_token_payload->value.json, "aud");
	if (aud != NULL) {

		/* check if it is a single-value */
		if (json_is_string(aud)) {

			/* a single-valued audience must be equal to our client_id */
			if (apr_strnatcmp(json_string_value(aud), provider->client_id)
					!= 0) {
				ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
						"oidc_proto_validate_aud_and_azp: the configured client_id (%s) did not match the \"aud\" claim value (%s) in the id_token",
						provider->client_id, json_string_value(aud));
				return FALSE;
			}

			/* check if this is a multi-valued audience */
		} else if (json_is_array(aud)) {

			if ((json_array_size(aud) > 1) && (azp == NULL)) {
				ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
						"oidc_proto_validate_aud_and_azp: the \"aud\" claim value in the id_token is an array with more than 1 element, but \"azp\" claim is not present (a SHOULD in the spec...)");
			}

			if (oidc_util_json_array_has_value(r, aud,
					provider->client_id) == FALSE) {
				ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
						"oidc_proto_validate_aud_and_azp: our configured client_id (%s) could not be found in the array of values for \"aud\" claim",
						provider->client_id);
				return FALSE;
			}
		} else {
			ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
					"oidc_proto_validate_aud_and_azp: id_token JSON payload \"aud\" claim is not a string nor an array");
			return FALSE;
		}

	} else {
		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
				"oidc_proto_validate_aud_and_azp: id_token JSON payload did not contain an \"aud\" claim");
		return FALSE;
	}

	return TRUE;
}
コード例 #7
0
ファイル: proto.c プロジェクト: eugeniop/mod_auth_openidc
/*
 * resolves the code received from the OP in to an access_token and id_token and returns the parsed contents
 */
apr_byte_t oidc_proto_resolve_code(request_rec *r, oidc_cfg *cfg,
		oidc_provider_t *provider, const char *code, char **s_idtoken,
		char **s_access_token, char **s_token_type) {

	ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
			"oidc_proto_resolve_code: entering");
	const char *response = NULL;

	/* assemble the parameters for a call to the token endpoint */
	apr_table_t *params = apr_table_make(r->pool, 5);
	apr_table_addn(params, "grant_type", "authorization_code");
	apr_table_addn(params, "code", code);
	apr_table_addn(params, "redirect_uri", cfg->redirect_uri);

	/* see if we need to do basic auth or auth-through-post-params (both applied through the HTTP POST method though) */
	const char *basic_auth = NULL;
	if ((apr_strnatcmp(provider->token_endpoint_auth, "client_secret_basic"))
			== 0) {
		basic_auth = apr_psprintf(r->pool, "%s:%s", provider->client_id,
				provider->client_secret);
	} else {
		apr_table_addn(params, "client_id", provider->client_id);
		apr_table_addn(params, "client_secret", provider->client_secret);
	}

	/* see if we've configured any extra static parameters to the token endpoint */
	if (provider->token_endpoint_params != NULL) {
		const char *key, *val;
		const char *p = provider->token_endpoint_params;
		while (*p && (val = ap_getword(r->pool, &p, '&'))) {
			key = ap_getword(r->pool, &val, '=');
			ap_unescape_url((char *) key);
			ap_unescape_url((char *) val);
			apr_table_addn(params, key, val);
		}
	}

	/* resolve the code against the token endpoint */
	if (oidc_util_http_post_form(r, provider->token_endpoint_url, params,
			basic_auth, NULL, provider->ssl_validate_server, &response,
			cfg->http_timeout_long, cfg->outgoing_proxy) == FALSE) {
		ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
				"oidc_proto_resolve_code: could not successfully resolve the \"code\" (%s) against the token endpoint (%s)",
				code, provider->token_endpoint_url);
		return FALSE;
	}

	/* check for errors, the response itself will have been logged already */
	json_t *result = NULL;
	if (oidc_util_decode_json_and_check_error(r, response, &result) == FALSE)
		return FALSE;

	/* get the access_token from the parsed response */
	json_t *access_token = json_object_get(result, "access_token");
	if ((access_token != NULL) && (json_is_string(access_token))) {

		*s_access_token = apr_pstrdup(r->pool, json_string_value(access_token));

		/* log and set the obtained acces_token */
		ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
				"oidc_proto_resolve_code: returned access_token: %s",
				*s_access_token);

		/* the provider must return the token type */
		json_t *token_type = json_object_get(result, "token_type");
		if ((token_type == NULL) || (!json_is_string(token_type))) {
			ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
					"oidc_proto_resolve_code: response JSON object did not contain a token_type string");
			json_decref(result);
			return FALSE;
		}

		*s_token_type = apr_pstrdup(r->pool, json_string_value(token_type));

	} else {
		ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
				"oidc_proto_resolve_code: response JSON object did not contain an access_token string");
	}

	/* get the id_token from the response */
	json_t *id_token = json_object_get(result, "id_token");
	if ((id_token != NULL) && (json_is_string(id_token))) {
		*s_idtoken = apr_pstrdup(r->pool, json_string_value(id_token));

		/* log and set the obtained id_token */
		ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
				"oidc_proto_resolve_code: returned id_token: %s", *s_idtoken);
	}

	json_decref(result);

	return TRUE;
}
コード例 #8
0
ファイル: igc_parser.c プロジェクト: robchett/igc_parser
uint8_t _main_flight(json_t *data) {
    json_t *_source, *_destination, *_set_start, *_set_end, *_pilot, *_task;
    const char *source;
    char *destination, *pilot;
    size_t set_start, set_end;

    _source = json_object_get(data, "source");
    _destination = json_object_get(data, "destination");
    _set_start = json_object_get(data, "set_start");
    _set_end = json_object_get(data, "set_end");
    _pilot = json_object_get(data, "pilot");
    _task = json_object_get(data, "task");

    if (!json_is_string(_source)) {
        fprintf(stderr, "{\"error\": \"No source file provided\"}");
        return 0;
    }

    source = json_string_value(_source);

    if (!json_is_string(_destination)) {
        destination = calloc(strlen(source) + 1, sizeof(char));
        strcpy(destination, source);
        dirname(destination);
    } else {
        destination = (char *) json_string_value(_destination);
    }

    if (!json_is_string(_pilot)) {
        pilot = (char *) json_string_value(_pilot);
    }

    char out_file_1[strlen(destination) + 20];
    char out_file_2[strlen(destination) + 20];
    char out_file_3[strlen(destination) + 20];
    char out_file_4[strlen(destination) + 20];
    sprintf(out_file_1, "%s%s", destination, "/track.js");
    sprintf(out_file_2, "%s%s", destination, "/track.kml");
    sprintf(out_file_3, "%s%s", destination, "/track_earth.kml");
    sprintf(out_file_4, "%s%s", destination, "/track_split.kml");

    char *igc_file = load_file(source);
    if (igc_file != NULL) {
        coordinate_set_t *set = NEW(coordinate_set_t, 1);
        coordinate_set_init(set);

        task_t *read_task = NULL;
        coordinate_set_parse_igc(set, igc_file, &read_task);

        size_t initial_length = set->length;
        coordinate_set_trim(set);
        coordinate_set_repair(set);
        coordinate_set_simplify(set, 1500);
        coordinate_set_extrema(set);

        json_t *_section = json_object_get(data, "section");
        size_t section;
        if (_section) {
            section = json_integer_value(_section);
            coordinate_set_select_section(set, section, 0);
        }

        if (set->subset_count == 1) {

            task_t *task = parse_task(_task);
            if (!task) {
                task = read_task;
            }

            distance_map_t *map = NEW(distance_map_t, 1);
            distance_map_init(map, set);

            char *ids;

            printf("{");
            printf("\"validated\": %d,", validate_file(source));
            printf("\"total_points\": %d,", initial_length);
            printf("\"sets\": %d,", set->subset_count);
            printf("\"date\": \"%04d-%02d-%02d\",", set->year, set->month, set->day);
            printf("\"start_time\": %d,", set->first->timestamp);
            printf("\"duration\": %d,", set->last->timestamp - set->first->timestamp);
            printf("\"points\": %d,", set->length);
            printf("\"stats\": {", set->length);
            printf("\"height\" : {\"min\": %d, \"max\": %d},", set->first->ele, set->last->ele);
            printf("\"speed\" : {\"min\": %d, \"max\": %d},", set->first->speed, set->last->speed);
            printf("\"climb_rate\" : {\"min\": %d, \"max\": %d}", set->first->climb_rate, set->last->climb_rate);
            printf("},");
            printf("\"task\": {", set->length);

            task_t *od, *or, *tr, *ft;

            od = distance_map_score_open_distance_3tp(map);
            or = distance_map_score_out_and_return(map);
            tr = distance_map_score_triangle(map, 0.28);
            ft = distance_map_score_triangle(map, 0);

            format_task(od, "open_distance", OPEN_DISTANCE);
            printf(",");

            format_task(or, "out_and_return", OUT_AND_RETURN);
            printf(",");

            format_task(tr, "triangle", TRIANGLE);
            printf(",");

            format_task(ft, "flat_triangle", FLAT_TRIANGLE);

            if (task) {
                printf(",");
                format_task(task, "declared", task->type);
                printf(", \"complete\": %d", task_completes_task(task, set));
            }

            printf("}, \"output\": {\"js\": \"%s\",\"kml\": \"%s\",\"earth\": \"%s\"}", out_file_1, out_file_2, out_file_3);

            formatter_t *formatter;

            formatter = NEW(formatter_t, 1);
            formatter_js_init(formatter, set, 1, od, or, tr, ft);
            formatter_js_output(formatter, out_file_1);
            free(formatter);

            formatter = NEW(formatter_t, 1);
            formatter_kml_init(formatter, set, pilot ?: "N/A", od, or, tr, ft, task);
            formatter_kml_output(formatter, out_file_2);
            free(formatter);

            formatter = NEW(formatter_t, 1);
            formatter_kml_earth_init(formatter, set, pilot ?: "N/A", od, or, tr, ft, task);
            formatter_kml_earth_output(formatter, out_file_3);
            free(formatter);

            printf("}");

            if (od) {
                task_deinit(od);
            }
            if (or) {
                task_deinit(or);
            }
            if (tr) {
                task_deinit(tr);
            }
            distance_map_deinit(map);

        } else {
コード例 #9
0
ファイル: jt_msg_stats.c プロジェクト: tcharding/jittertrap
int jt_stats_unpacker(json_t *root, void **data)
{
	json_t *params;
	json_t *iface, *samples, *err_mean, *err_max, *err_sd;
	json_t *mts, *tv_sec, *tv_nsec;

	struct jt_msg_stats *stats;

	params = json_object_get(root, "p");
	assert(params);
	assert(JSON_OBJECT == json_typeof(params));
	assert(0 < json_object_size(params));

	stats = malloc(sizeof(struct jt_msg_stats));

	/* FIXME: this json_get_object() inteface sucks bricks,
	 * but the unpack API doesn't seem to work right now (jansson-2.7). :(
	 */
	iface = json_object_get(params, "iface");
	if (!json_is_string(iface)) {
		goto unpack_fail;
	}
	snprintf(stats->iface, MAX_IFACE_LEN, "%s", json_string_value(iface));

	samples = json_object_get(params, "s");
	if (!json_is_array(samples)) {
		goto unpack_fail;
	}

	stats->sample_count = json_array_size(samples);
	stats->samples =
	    malloc(stats->sample_count * sizeof(struct stats_sample));

	int i;
	for (i = 0; i < stats->sample_count; i++) {
		json_t *s = json_array_get(samples, i);
		assert(json_is_object(s));
		json_t *t;

		t = json_object_get(s, "rx");
		assert(json_is_integer(t));
		stats->samples[i].rx = json_integer_value(t);

		t = json_object_get(s, "tx");
		assert(json_is_integer(t));
		stats->samples[i].tx = json_integer_value(t);

		t = json_object_get(s, "rxP");
		assert(json_is_integer(t));
		stats->samples[i].rxPkt = json_integer_value(t);

		t = json_object_get(s, "txP");
		assert(json_is_integer(t));
		stats->samples[i].txPkt = json_integer_value(t);
	}

	/* get the stats sampling time error */
	err_mean = json_object_get(params, "whoosh_err_mean");
	if (!json_is_integer(err_mean)) {
		goto unpack_fail_free_samples;
	}
	stats->err.mean = json_integer_value(err_mean);

	err_max = json_object_get(params, "whoosh_err_max");
	if (!json_is_integer(err_max)) {
		goto unpack_fail_free_samples;
	}
	stats->err.max = json_integer_value(err_max);

	err_sd = json_object_get(params, "whoosh_err_sd");
	if (!json_is_integer(err_sd)) {
		goto unpack_fail_free_samples;
	}
	stats->err.sd = json_integer_value(err_sd);

	/* get the message timestamp */
	mts = json_object_get(params, "t");
	if (!json_is_object(mts)) {
		goto unpack_fail_free_samples;
	}

	tv_sec = json_object_get(mts, "tv_sec");
	if (!json_is_integer(tv_sec)) {
		goto unpack_fail_free_samples;
	}
	stats->mts.tv_sec = json_integer_value(tv_sec);

	tv_nsec = json_object_get(mts, "tv_nsec");
	if (!json_is_integer(tv_nsec)) {
		goto unpack_fail_free_samples;
	}
	stats->mts.tv_nsec = json_integer_value(tv_nsec);

	*data = stats;
	json_object_clear(params);
	return 0;

unpack_fail_free_samples:
	free(stats->samples);
unpack_fail:
	free(stats);
	return -1;
}
コード例 #10
0
ファイル: NDKHelper.cpp プロジェクト: yuanhaicong/comeon
CCObject* NDKHelper::GetCCObjectFromJson(json_t *obj)
{
    if (obj == NULL)
        return NULL;
    
    if (json_is_object(obj))
    {
        CCDictionary *dictionary = new CCDictionary();
        //CCDictionary::create();
        
        const char *key;
        json_t *value;
        
        void *iter = json_object_iter(obj);
        while(iter)
        {
            key = json_object_iter_key(iter);
            value = json_object_iter_value(iter);
            
            dictionary->setObject(NDKHelper::GetCCObjectFromJson(value)->autorelease(), string(key));
            
            iter = json_object_iter_next(obj, iter);
        }
        
        return dictionary;
    }
    else if (json_is_array(obj))
    {
        size_t sizeArray = json_array_size(obj);
        CCArray *array = new CCArray();
        //CCArray::createWithCapacity(sizeArray);
        
        for (unsigned int i = 0; i < sizeArray; i++)
        {
            array->addObject(NDKHelper::GetCCObjectFromJson(json_array_get(obj, i))->autorelease());
        }
        
        return array;
    }
    else if (json_is_boolean(obj))
    {
        stringstream str;
        if (json_is_true(obj))
            str << true;
        else if (json_is_false(obj))
            str << false;
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_integer(obj))
    {
        stringstream str;
        str << json_integer_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_real(obj))
    {
        stringstream str;
        str << json_real_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_string(obj))
    {
        stringstream str;
        str << json_string_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    
    return NULL;
}
コード例 #11
0
ui::Button* LHGameChat::gameChatButton(){
    auto bt = ui::Button::create("q.png");
    bt->addTouchEventListener([bt](Ref *ps,ui::Widget::TouchEventType type){
        if (type == ui::Widget::TouchEventType::ENDED) {
            if (_chatManager==nullptr) {
                LHDialog::showDialog(LHGameChat::waitView());
                
                _chatManager = new LHPomeloManager();
                _chatManager->connect("2dxhuji", "huji");
                _chatManager->onEnterChannel = [bt](int status,json_t *resp){
                    LHDialog::disMissDialog();
                    
                    int uc = 0;
                    json_t* users = json_object_get(resp,"users");
                    for (unsigned int i=0; i<json_array_size(users); i++) {
//                        json_t* val = json_array_get(users,i);
                        uc++;
                    }
                    _userCount = uc;
                    
                    if (_chatView == nullptr) {
                        float margin = 50;
                        Size vs = Director::getInstance()->getVisibleSize();
                        Vec2 vo = Director::getInstance()->getVisibleOrigin();
                        vs.width = vs.width - margin*2;
                        vs.height = vs.height - margin*2;
                        _chatView = new LHGameChatView();
                        _chatView->init(vs);
                        auto scene = Director::getInstance()->getRunningScene();
                        _chatView->setPosition(Vec2(vo.x+margin, vo.y+margin));
                        scene->addChild(_chatView);
                        _chatView->onSend = [](const std::string& content){
                            return _chatManager->send(content, "*");
                        };
                    }
                    
                    refreshUserCountLabel();
                };
                _chatManager->onMessage = [](json_t *resp){
                    //{"msg": "d", "from": "huji", "target": "*"}
                    json_t *msg = json_object_get(resp, "msg");
                    json_t *from = json_object_get(resp, "from");
                    const char *fromstr = json_string_value(from);
                    _chatView->addOne(fromstr, json_string_value(msg), LHGameChat_MsgType_Left);
                };
                _chatManager->onAdd = [](json_t *resp){
                    _userCount++;
                    refreshUserCountLabel();
                  
                    json_t *user = json_object_get(resp, "user");
                    const char *userstr = json_string_value(user);
                    auto msg = StringUtils::format("%s >>",userstr);
                    _chatView->addOne( "",msg, LHGameChat_MsgType_Middle);
                };
                _chatManager->onLeave = [](json_t *resp){
                    _userCount--;
                    refreshUserCountLabel();
                 
                    json_t *user = json_object_get(resp, "user");
                    const char *userstr = json_string_value(user);
                    auto msg = StringUtils::format("%s ~~",userstr);
                    _chatView->addOne("",msg,  LHGameChat_MsgType_Middle);
                };
            }else{
                if (!_chatView->isShowing()) {
                    auto scene = Director::getInstance()->getRunningScene();
                    scene->addChild(_chatView);
                }
            }
        }
    });
    return bt;
}
コード例 #12
0
ファイル: zyre_bridge.cpp プロジェクト: nhuebel/ubx
/* step */
void zyre_bridge_step(ubx_block_t *b)
{
    struct zyre_bridge_info *inf = (struct zyre_bridge_info*) b->private_data;

	/* Read data from port */
	ubx_port_t* port = inf->ports.zyre_out;
	assert(port != 0);

	char * tmp_str = (char*) malloc(inf->max_msg_length*sizeof(char*));

	ubx_data_t msg;
	checktype(port->block->ni, port->in_type, "unsigned char", port->name, 1);
	msg.type = port->in_type;
	msg.len = inf->max_msg_length;
	msg.data = tmp_str;
	//msg.data = inf->msg_buffer;

    int counter = 0;
    while (counter < inf->max_send) {
    	int read_bytes = __port_read(port, &msg);

    	//printf("zyrebridge: read bytes: %d\n",read_bytes);
    	//printf("step: read strlen: %lu\n",strlen((char*) msg.data));

    	if (read_bytes <= 0) {
    		//printf("zyre_bridge: No data recieved from port\n");
    		free(tmp_str);
    		return;
    	}
//    	printf("zyrebridge: read bytes: %d\n",read_bytes);
    	// port_read returns byte array. Need to add 0 termination manually to the string.
    	tmp_str[read_bytes] = '\0';

    	// create json object and...
    	json_t *pl;
		json_error_t error;
		pl= json_loads(tmp_str,0,&error);
		if(!pl) {
			printf("Error parsing JSON payload! line %d, column %d: %s\n", error.line, error.column, error.text);
			json_decref(pl);
			free(tmp_str);
			return;
		}
//    	printf("[zyrebridge] retrieving msg: %s\n", json_dumps(pl, JSON_ENCODE_ANY));
		// ...check for its type and embed it into msg envelope
		json_t *new_msg;
		new_msg = json_object();
		json_object_set(new_msg, "payload", pl);
		json_object_set(new_msg, "metamodel", json_string("SHERPA"));
		if(json_object_get(pl, "@worldmodeltype") == 0) {
			printf("[zyrebridge] retrieving msg: %s\n", json_dumps(pl, JSON_ENCODE_ANY));
			printf("[zyrebridge] Error parsing RSG payload! @worldmodeltype is missing.\n");
			json_decref(pl);
			free(tmp_str);
			return;
		}

		std::string tmp_type = json_string_value(json_object_get(pl, "@worldmodeltype")); //can segfault
		char *send_msg = NULL;
		int found = 0;
		for (int i=0; i < inf->output_type_list.size();i++)
		{
			if (tmp_type.compare(inf->output_type_list[i])) {
				found = 1;
				// need to handle exception for updates generated from RSG due to local updates
				if (tmp_type.compare("RSGUpdate") == 0) {
					json_object_set(new_msg, "model", json_string("RSGUpdate"));
					json_object_set(new_msg, "type", json_string("RSGUpdate_global"));

					//  If used with mediator, add send_request envelope
					ubx_data_t *dmy;
					dmy = ubx_config_get_data(b, "mediator");
					int mediator;
					mediator = *(int*) dmy->data;
					if (mediator == 1) {
						zuuid_t *query_uuid = zuuid_new ();
						assert (query_uuid);
						json_t *recip = json_array();
						assert((recip)&&(json_array_size(recip)==0));
						send_msg = send_request(zuuid_str(query_uuid),zyre_uuid(inf->node),recip,1000,"send_remote",new_msg);
					}
					else {
						send_msg = json_dumps(new_msg, JSON_ENCODE_ANY);
					}
				} else {
					json_object_set(new_msg, "model", json_string(tmp_type.c_str()));
					json_object_set(new_msg, "type", json_string(tmp_type.c_str()));
					send_msg = json_dumps(new_msg, JSON_ENCODE_ANY);
				}
				break;
			}
		}
		if (found == 0) {
			printf("[zyre_bridge] WARNING: Unknown output type: %s!\n",tmp_type.c_str());
		}

		printf("[zyrebridge] sending msg: %s\n", send_msg);
    	zyre_shouts(inf->node, inf->group, "%s", send_msg);
    	counter++;

    	json_decref(pl);
    	json_decref(new_msg);
    }

    free(tmp_str);
    return;
}
コード例 #13
0
ファイル: Skin.cpp プロジェクト: hanfer/WorkingTitle
void Skin::load()
{
	json_error_t error;
	json_t *root = json_load_file(filename.c_str(), 0, &error);

	auto getString = [root](const json_t* obj, const char* str) -> std::string
	{
		json_t *value = json_object_get(obj, str);
		if (!json_is_string(value))
			throw std::runtime_error("error: " + std::string(str) + "was expected to be a string");
		return std::string(json_string_value(value));

	};


	auto getColor = [root](const json_t* obj, const char* str) -> Color
	{
		Color result;
		json_t *value = json_object_get(obj, str);

		if (!json_is_array(value))
			throw std::runtime_error("error: " + std::string(str) + "was expected to be an arry");

		for (int i = 0; i < json_array_size(value); i++)
			result[i] = json_integer_value(json_array_get(value, i)); // this should check for error

		return result;

	};

	if (!root)
		throw std::runtime_error("error: on line " + std::to_string(error.line) + ": " + std::string(error.text));

	if (!json_is_array(root))
		throw std::runtime_error("error: root is not an array");


	for (int i = 0; i < json_array_size(root); i++)
	{
		json_t *data = json_array_get(root, i);

		if (!json_is_object(data))
			throw std::runtime_error("error: entry at " + std::to_string(i + 1) + " was expected to be a object");


		Entry entry;

		entry.name = getString(data, "name");
		entry.bgColor = getColor(data, "bgColor");
		entry.fontColor = getColor(data, "fontColor");


		/*
		json_t *layers = json_object_get(data, "layers");
		if (!json_is_array(layers))
			throw std::runtime_error("error: layers is not an array");

		for (int i = 0; i < json_array_size(layers); i++)
		{
			json_t *layer = json_array_get(layers, i);
		}
		*/
	}
}
コード例 #14
0
ファイル: rendezvous.c プロジェクト: SRI-CSL/jumpbox
static void
rdv_gen_request(httpsrv_client_t *hcl) {
	json_error_t	error;
	json_t		*root;
	const char	*server = NULL;
	bool		secure = false;

	if (hcl->method != HTTP_M_POST) {
		djb_error(hcl, 400, "gen_request requires a POST");
		return;
	}

	/* No body yet? Then allocate some memory to get it */
	if (hcl->readbody == NULL) {
		if (hcl->headers.content_length == 0) {
			djb_error(hcl, 400, "gen_request requires length");
			return;
		}

		if (httpsrv_readbody_alloc(hcl, 2, 0) < 0) {
			log_dbg("httpsrv_readbody_alloc() failed");
		}

		return;
	}

	log_dbg("data: %s", hcl->readbody);

	root = json_loads(hcl->readbody, 0, &error);
	httpsrv_readbody_free(hcl);

	if (root == NULL) {
		log_dbg("JSON load failed");
		return;

	} else if (json_is_object(root)) {
		json_t *server_val, *secure_val;

		secure_val = json_object_get(root, "secure");
		if (secure_val != NULL && json_is_true(secure_val)) {
			secure = true;
		}

		server_val = json_object_get(root, "server");

		if (server_val != NULL && json_is_string(server_val)) {
			server = json_string_value(server_val);
		}
	}

	if (server != NULL) {
		rdv_gen_request_aux(hcl, server, secure);
	} else {
		djb_error(hcl, 400, "POST data conundrum");

		if (root == NULL) {
			log_dbg("data: %s, error: line: %u, msg: %s",
				hcl->readbody, error.line, error.text);
		}
	}

	json_decref(root);
}
コード例 #15
0
ファイル: crypto.c プロジェクト: kyllikki/libnssync
enum nssync_error
nssync_crypto_decrypt_record(const char *record,
			     struct nssync_crypto_keybundle *keybundle,
			     uint8_t **plaintext_out,
			     size_t *plaintext_length_out)
{
	/* json objects */
	json_t *root;
	json_error_t error;
	json_t *hmac_hex16_json;
	json_t *ciphertext_b64_json;
	json_t *iv_b64_json;

	/* text from json */
	const char *hmac_hex16;
	const char *ciphertext_b64;
	const char *iv_b64;

	/* HMAC from record */
	uint8_t *record_hmac;
	size_t record_hmac_length = HMAC_KEY_LENGTH;

	/* HMAC computed from key */
	unsigned int local_hmac_length = HMAC_KEY_LENGTH;
	uint8_t local_hmac[HMAC_KEY_LENGTH];

	/* decoded ciphertext */
	uint8_t *ciphertext;
	size_t ciphertext_length;
	uint8_t *iv;
	size_t iv_length;

	/* AES state */
	AES_KEY aeskey;

	/* decypted data */
	uint8_t *plaintext;

	/* json load */
	root = json_loads(record, 0, &error);
	if (!root) {
		debugf("error: on line %d of reply: %s\n",
			error.line, error.text);
		return NSSYNC_ERROR_PROTOCOL;
	}

	if(!json_is_object(root)) {
		debugf("error: root is not an object\n");
		json_decref(root);
		return NSSYNC_ERROR_PROTOCOL;
	}

	/* extract ciphertext from record (undecoded) */

	hmac_hex16_json = json_object_get(root, "hmac");
	ciphertext_b64_json = json_object_get(root, "ciphertext");
	iv_b64_json = json_object_get(root, "IV");
	if ((!json_is_string(hmac_hex16_json)) ||
	    (!json_is_string(ciphertext_b64_json)) ||
	    (!json_is_string(iv_b64_json))) {
		debugf("missing or incorrectly formatted fields in record\n");
		json_decref(root);
		return NSSYNC_ERROR_PROTOCOL;
	}
	hmac_hex16 = json_string_value(hmac_hex16_json);
	ciphertext_b64 = json_string_value(ciphertext_b64_json);
	iv_b64 = json_string_value(iv_b64_json);

	/* hex16 decode hmac from record */
	record_hmac = hex16_decode((uint8_t *)hmac_hex16,
				   strlen(hmac_hex16),
				   &record_hmac_length);
	if (record_hmac_length != HMAC_KEY_LENGTH) {
		debugf("record hmac length %zu incorrect (should be %d)\n",
			record_hmac_length, HMAC_KEY_LENGTH);
		json_decref(root);
		return NSSYNC_ERROR_PROTOCOL;
	}

	/* calculate local hmac value */
	HMAC(EVP_sha256(),
	     keybundle->hmac, HMAC_KEY_LENGTH,
	     (uint8_t *)ciphertext_b64, strlen(ciphertext_b64),
	     local_hmac, &local_hmac_length);

	/* verify hmac */
	if (memcmp(record_hmac, local_hmac, SHA256_DIGEST_LENGTH) != 0) {
		debugf("record hmac does not match computed. bad key?\n");
		free(record_hmac);
		json_decref(root);
		return NSSYNC_ERROR_HMAC;
	}
	free(record_hmac);

	/* base64 decode iv from record */
	iv = base64_decode((uint8_t *)iv_b64,
			   strlen(iv_b64),
			   &iv_length);
	if ((iv == NULL) || (iv_length != IV_LENGTH)) {
		debugf("IV data was size %zu (expected %d)\n",
			iv_length, IV_LENGTH);
		json_decref(root);
		return NSSYNC_ERROR_PROTOCOL;
	}

	/* base64 decode ciphertext */
	ciphertext = base64_decode((uint8_t *)ciphertext_b64,
				   strlen(ciphertext_b64),
				   &ciphertext_length);
	if (ciphertext == NULL) {
		json_decref(root);
		free(iv);
		return NSSYNC_ERROR_NOMEM;
	}

	/* json unref */
	json_decref(root);

	/* decrypt data */
	plaintext = malloc(ciphertext_length + 1);
	if (plaintext == NULL) {
		free(ciphertext);
		free(iv);
		return NSSYNC_ERROR_NOMEM;
	}
	plaintext[ciphertext_length] = 0;

	AES_set_decrypt_key(keybundle->encryption, 256, &aeskey);
	AES_cbc_encrypt(ciphertext, plaintext, ciphertext_length, &aeskey, iv, AES_DECRYPT);

	free(ciphertext);
	free(iv);

	*plaintext_out = plaintext;
	if (plaintext_length_out != NULL) {
		*plaintext_length_out = ciphertext_length;
	}

	return NSSYNC_ERROR_OK;
}
コード例 #16
0
libtelemetry
  formats
    cef
    snmp
#endif
/*
   uses libtelemetry (github: smithee-us/libtelemetry)

   Copyright 2015-2016 Smithee,Spelvin,Agnew & Plinge, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

*/

#include <stdio.h>
#include <memory.h>

#include <jansson.h>

#include <gnutls/gnutls.h>


#include <libtelemetry.h>


int
  tlm_init
    (TLM_CONTEXT
      *ctx)
{ /* tlm_init */

  FILE
    *cfgf;
  char
    field [1024];
  int
    found_field;
  char
    json_string [1024];
  json_t
    *root;
  int
    status;
  int
    status_io;
  json_error_t
    status_json;
  json_t
    *value;
  char
    vstr [1024];


  status = ST_TLM_CFG_READ;
  memset (ctx, 0, sizeof (*ctx));
  ctx->verbosity = 1;
  cfgf = fopen ("libtelemetry_config.json", "r");
  if (cfgf != NULL)
  {
    status = ST_OK;
    status_io = fread (json_string, sizeof (json_string[0]), sizeof (json_string), cfgf);
    if (status_io > sizeof (json_string))
      status = ST_TLM_CFG_OVERFLOW;
    if (status_io < 0)
      status = ST_TLM_CFG_UNDERFLOW;
  };
  if (status EQUALS ST_OK)
  {
    root = json_loads (json_string, 0, &status_json);
    if (!root)
    {
      fprintf (stderr, "JSON parser failed.  String was ->%s<-\n",
        json_string);
      status = ST_TLM_CFG_ERROR;
    };
  };

  // set verbosity=n where n is typically 0..9

  if (status EQUALS ST_OK)
  {
    found_field = 1;
    strcpy (field, "verbosity");
    value = json_object_get (root, field);
    if (!json_is_string (value))
      found_field = 0;
    if (found_field)
    {
      int i;
      strcpy (vstr, json_string_value (value));
      sscanf (vstr, "%d", &i);
      ctx->verbosity = i;
    };
  };

  // set verify_server=enable or disable

  if (status EQUALS ST_OK)
  {
    found_field = 1;
    strcpy (field, "verify_server");
    value = json_object_get (root, field);
    if (!json_is_string (value))
      found_field = 0;
    if (found_field)
    {
      strcpy (vstr, json_string_value (value));
      if (0 EQUALS strcmp ("enable", vstr))
        ctx->verify_server = 1;
    };
  };

  return (status);
}
コード例 #17
0
ファイル: server.c プロジェクト: nudelfabrik/FidiStat
void worker(int connfd, struct tls* ctx) {

    // Process HEADER
    //--------------
    struct tls* cctx = NULL;
    tls_accept_socket(ctx, &cctx, connfd);
    json_t *header = recvOverTLS(cctx);
    const char* clientName = json_string_value(json_object_get(header, "from"));
    for (size_t i = 0; i < sizeof(clientName); i++) {
        if (clientName[i] == '/' || clientName[i] == '\\') {
            syslog(LOG_ERR, "ERROR in clientName!, aborting");
            return;
        }
    }
    const char* clientAuth = json_string_value(json_object_get(header, "auth"));
    if (strcmp(clientAuth, getClientAuth()) != 0) {
        syslog(LOG_ERR, "Authentication failed");
        return;
    }
    connType type = json_integer_value(json_object_get(header, "type"));
    int size = json_integer_value(json_object_get(header, "size"));

    // Process Payload
    //----------------

    // new Values for graphs
    if (type == NEWDATA) {

        for (int i = 0; i < size; i++) {
            json_t* payload = recvOverTLS(cctx);
            pasteJSON(payload, clientName);
        }
    } 

    // create .json or update displaysettings
    if (type == CREATE || type == UPDATE) {
        for (int i = 0; i < size; i++) {
            json_t* payload = recvOverTLS(cctx);
            const char * name = json_string_value(json_object_get(payload, "name"));
            if (name == NULL) {
                syslog(LOG_ERR, "Error in Message from Client");
                return;
            }

            json_t *root = json_object_get(payload, "payload");

            char* file = composeFileName(clientName, name, "json");
            if (type == CREATE) {
                dumpJSON(root, file);
            } else {
                mergeJSON(root,file);
            }
        }
    }

    // Look, which files are not available
    if (type == HELLO) {
        json_t *relist = json_array();

        json_t *list = recvOverTLS(cctx);

        for (int i = 0; i < size; i++) {
            const char * name = json_string_value(json_array_get(list, i));
            if (name == NULL) {
                syslog(LOG_ERR, "Error in Message from Client");
                return;
            }
            char* file = composeFileName(clientName, name, "json");
            if (access( file, F_OK ) == -1) {
                json_array_append_new(relist, json_string(name)); 
            }
        }
        char * relistStr = json_dumps(relist, JSON_COMPACT);
        sendOverTLS(cctx, relistStr);
        free(relistStr);
    }
    
    // Delete all files from this client
    if (type == DELETE) {
        json_t *list = recvOverTLS(cctx);

        for (int i = 0; i < size; i++) {
            const char * name = json_string_value(json_array_get(list, i));
            delete(clientName, name);
        }
    }

    tls_close(cctx);
    tls_free(cctx);

}
コード例 #18
0
ファイル: json.c プロジェクト: huangjingpei/asterisk
const char *ast_json_string_get(const struct ast_json *string)
{
	return json_string_value((json_t *)string);
}
コード例 #19
0
ファイル: proto.c プロジェクト: eugeniop/mod_auth_openidc
/*
 * get the key from the JWKs that corresponds with the key specified in the header
 */
static apr_byte_t oidc_proto_get_key_from_jwks(request_rec *r,
		apr_jwt_header_t *jwt_hdr, json_t *j_jwks, const char *type,
		apr_jwk_t **result) {

	char *x5t = NULL;
	apr_jwt_get_string(r->pool, &jwt_hdr->value, "x5t", &x5t);

	ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
			"oidc_proto_get_key_from_jwks: search for kid \"%s\" or thumbprint x5t \"%s\"",
			jwt_hdr->kid, x5t);

	/* get the "keys" JSON array from the JWKs object */
	json_t *keys = json_object_get(j_jwks, "keys");
	if ((keys == NULL) || !(json_is_array(keys))) {
		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
				"oidc_proto_get_key_from_jwks: \"keys\" array element is not a JSON array");
		return FALSE;
	}

	int i;
	for (i = 0; i < json_array_size(keys); i++) {

		/* get the next element in the array */
		json_t *elem = json_array_get(keys, i);

		/* check that it is a JSON object */
		if (!json_is_object(elem)) {
			ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
					"oidc_proto_get_key_from_jwks: \"keys\" array element is not a JSON object, skipping");
			continue;
		}

		/* get the key type and see if it is the RSA type that we are looking for */
		json_t *kty = json_object_get(elem, "kty");
		if ((!json_is_string(kty))
				|| (strcmp(json_string_value(kty), type) != 0))
			continue;

		/* see if we were looking for a specific kid, if not we'll return the first one found */
		if ((jwt_hdr->kid == NULL) && (x5t == NULL)) {
			ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
					"oidc_proto_get_key_from_jwks: no kid/x5t to match, return first key found");

			apr_jwk_parse_json(r->pool, elem, NULL, result);
			break;
		}

		/* we are looking for a specific kid, get the kid from the current element */
		json_t *ekid = json_object_get(elem, "kid");
		if ((ekid != NULL) && json_is_string(ekid) && (jwt_hdr->kid != NULL)) {
			/* compare the requested kid against the current element */
			if (apr_strnatcmp(jwt_hdr->kid, json_string_value(ekid)) == 0) {
				ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
						"oidc_proto_get_key_from_jwks: found matching kid: \"%s\"",
						jwt_hdr->kid);

				apr_jwk_parse_json(r->pool, elem, NULL, result);
				break;
			}
		}

		/* we are looking for a specific x5t, get the x5t from the current element */
		json_t *ex5t = json_object_get(elem, "kid");
		if ((ex5t != NULL) && json_is_string(ex5t) && (x5t != NULL)) {
			/* compare the requested kid against the current element */
			if (apr_strnatcmp(x5t, json_string_value(ex5t)) == 0) {
				ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
						"oidc_proto_get_key_from_jwks: found matching x5t: \"%s\"",
						x5t);

				apr_jwk_parse_json(r->pool, elem, NULL, result);
				break;
			}
		}

	}

	return TRUE;
}
コード例 #20
0
ファイル: schema.c プロジェクト: Neeke/avro-php
static int
avro_type_from_json_t(json_t *json, avro_type_t *type,
		      st_table *named_schemas, avro_schema_t *named_type)
{
	json_t *json_type;
	const char *type_str;

	if (json_is_array(json)) {
		*type = AVRO_UNION;
		return 0;
	} else if (json_is_object(json)) {
		json_type = json_object_get(json, "type");
	} else {
		json_type = json;
	}
	if (!json_is_string(json_type)) {
		avro_set_error("\"type\" field must be a string");
		return EINVAL;
	}
	type_str = json_string_value(json_type);
	if (!type_str) {
		avro_set_error("\"type\" field must be a string");
		return EINVAL;
	}
	/*
	 * TODO: gperf/re2c this 
	 */
	if (strcmp(type_str, "string") == 0) {
		*type = AVRO_STRING;
	} else if (strcmp(type_str, "bytes") == 0) {
		*type = AVRO_BYTES;
	} else if (strcmp(type_str, "int") == 0) {
		*type = AVRO_INT32;
	} else if (strcmp(type_str, "long") == 0) {
		*type = AVRO_INT64;
	} else if (strcmp(type_str, "float") == 0) {
		*type = AVRO_FLOAT;
	} else if (strcmp(type_str, "double") == 0) {
		*type = AVRO_DOUBLE;
	} else if (strcmp(type_str, "boolean") == 0) {
		*type = AVRO_BOOLEAN;
	} else if (strcmp(type_str, "null") == 0) {
		*type = AVRO_NULL;
	} else if (strcmp(type_str, "record") == 0) {
		*type = AVRO_RECORD;
	} else if (strcmp(type_str, "enum") == 0) {
		*type = AVRO_ENUM;
	} else if (strcmp(type_str, "array") == 0) {
		*type = AVRO_ARRAY;
	} else if (strcmp(type_str, "map") == 0) {
		*type = AVRO_MAP;
	} else if (strcmp(type_str, "fixed") == 0) {
		*type = AVRO_FIXED;
	} else if ((*named_type = find_named_schemas(type_str, named_schemas))) {
		*type = AVRO_LINK;
	} else {
		avro_set_error("Unknown Avro \"type\": %s", type_str);
		return EINVAL;
	}
	return 0;
}
コード例 #21
0
ファイル: proto.c プロジェクト: eugeniop/mod_auth_openidc
/*
 * based on an account name, perform OpenID Connect Provider Issuer Discovery to find out the issuer and obtain and store its metadata
 */
apr_byte_t oidc_proto_account_based_discovery(request_rec *r, oidc_cfg *cfg,
		const char *acct, char **issuer) {

	// TODO: maybe show intermediate/progress screen "discovering..."

	ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
			"oidc_proto_account_based_discovery: entering, acct=%s", acct);

	const char *resource = apr_psprintf(r->pool, "acct:%s", acct);
	const char *domain = strrchr(acct, '@');
	if (domain == NULL) {
		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
				"oidc_proto_account_based_discovery: invalid account name");
		return FALSE;
	}
	domain++;
	const char *url = apr_psprintf(r->pool, "https://%s/.well-known/webfinger",
			domain);

	apr_table_t *params = apr_table_make(r->pool, 1);
	apr_table_addn(params, "resource", resource);
	apr_table_addn(params, "rel", "http://openid.net/specs/connect/1.0/issuer");

	const char *response = NULL;
	if (oidc_util_http_get(r, url, params, NULL, NULL,
			cfg->provider.ssl_validate_server, &response,
			cfg->http_timeout_short, cfg->outgoing_proxy) == FALSE) {
		/* errors will have been logged by now */
		return FALSE;
	}

	/* decode and see if it is not an error response somehow */
	json_t *j_response = NULL;
	if (oidc_util_decode_json_and_check_error(r, response, &j_response) == FALSE)
		return FALSE;

	/* get the links parameter */
	json_t *j_links = json_object_get(j_response, "links");
	if ((j_links == NULL) || (!json_is_array(j_links))) {
		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
				"oidc_proto_account_based_discovery: response JSON object did not contain a \"links\" array");
		json_decref(j_response);
		return FALSE;
	}

	/* get the one-and-only object in the "links" array */
	json_t *j_object = json_array_get(j_links, 0);
	if ((j_object == NULL) || (!json_is_object(j_object))) {
		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
				"oidc_proto_account_based_discovery: response JSON object did not contain a JSON object as the first element in the \"links\" array");
		json_decref(j_response);
		return FALSE;
	}

	/* get the href from that object, which is the issuer value */
	json_t *j_href = json_object_get(j_object, "href");
	if ((j_href == NULL) || (!json_is_string(j_href))) {
		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
				"oidc_proto_account_based_discovery: response JSON object did not contain a \"href\" element in the first \"links\" array object");
		json_decref(j_response);
		return FALSE;
	}

	*issuer = apr_pstrdup(r->pool, json_string_value(j_href));

	ap_log_rerror(APLOG_MARK, OIDC_DEBUG, 0, r,
			"oidc_proto_account_based_discovery: returning issuer \"%s\" for account \"%s\" after doing successful webfinger-based discovery",
			*issuer, acct);

	json_decref(j_response);

	return TRUE;
}
コード例 #22
0
ファイル: schema.c プロジェクト: Neeke/avro-php
static int
avro_schema_from_json_t(json_t *json, avro_schema_t *schema,
			st_table *named_schemas)
{
#ifdef _WIN32
 #pragma message("#warning: Bug: '0' is not of type avro_type_t.")
#else
 #warning "Bug: '0' is not of type avro_type_t."
#endif
  /* We should really have an "AVRO_INVALID" type in
   * avro_type_t. Suppress warning below in which we set type to 0.
   */
	avro_type_t type = (avro_type_t) 0;
	unsigned int i;
	avro_schema_t named_type = NULL;

	if (avro_type_from_json_t(json, &type, named_schemas, &named_type)) {
		return EINVAL;
	}

	switch (type) {
	case AVRO_LINK:
		*schema = avro_schema_link(named_type);
		break;

	case AVRO_STRING:
		*schema = avro_schema_string();
		break;

	case AVRO_BYTES:
		*schema = avro_schema_bytes();
		break;

	case AVRO_INT32:
		*schema = avro_schema_int();
		break;

	case AVRO_INT64:
		*schema = avro_schema_long();
		break;

	case AVRO_FLOAT:
		*schema = avro_schema_float();
		break;

	case AVRO_DOUBLE:
		*schema = avro_schema_double();
		break;

	case AVRO_BOOLEAN:
		*schema = avro_schema_boolean();
		break;

	case AVRO_NULL:
		*schema = avro_schema_null();
		break;

	case AVRO_RECORD:
		{
			json_t *json_name = json_object_get(json, "name");
			json_t *json_namespace =
			    json_object_get(json, "namespace");
			json_t *json_fields = json_object_get(json, "fields");
			unsigned int num_fields;
			const char *record_name;
			const char *record_namespace;

			if (!json_is_string(json_name)) {
				avro_set_error("Record type must have a \"name\"");
				return EINVAL;
			}
			if (!json_is_array(json_fields)) {
				avro_set_error("Record type must have \"fields\"");
				return EINVAL;
			}
			num_fields = json_array_size(json_fields);
			if (num_fields == 0) {
				avro_set_error("Record type must have at least one field");
				return EINVAL;
			}
			record_name = json_string_value(json_name);
			if (!record_name) {
				avro_set_error("Record type must have a \"name\"");
				return EINVAL;
			}
			if (json_is_string(json_namespace)) {
				record_namespace =
				    json_string_value(json_namespace);
			} else {
				record_namespace = NULL;
			}
			*schema =
			    avro_schema_record(record_name, record_namespace);
			if (save_named_schemas(record_name, *schema, named_schemas)) {
				avro_set_error("Cannot save record schema");
				return ENOMEM;
			}
			for (i = 0; i < num_fields; i++) {
				json_t *json_field =
				    json_array_get(json_fields, i);
				json_t *json_field_name;
				json_t *json_field_type;
				json_t *json_field_default;
				avro_schema_t json_field_type_schema;
				int field_rval;

				if (!json_is_object(json_field)) {
					avro_set_error("Record field %d must be an object", i);
					avro_schema_decref(*schema);
					return EINVAL;
				}
				json_field_name =
				    json_object_get(json_field, "name");
				if (!json_field_name) {
					avro_set_error("Record field %d must have a \"name\"", i);
					avro_schema_decref(*schema);
					return EINVAL;
				}
				json_field_type =
				    json_object_get(json_field, "type");
				if (!json_field_type) {
					avro_set_error("Record field %d must have a \"type\"", i);
					avro_schema_decref(*schema);
					return EINVAL;
				}
				json_field_default =
				    json_object_get(json_field, "default");
				field_rval =
				    avro_schema_from_json_t(json_field_type,
							    &json_field_type_schema,
							    named_schemas);
				if (field_rval) {
					avro_schema_decref(*schema);
					return field_rval;
				}
				field_rval =
				    avro_schema_record_field_append(*schema,
								    json_string_value
								    (json_field_name),
								    json_field_type_schema);
				if (field_rval) {
					avro_schema_decref(*schema);
					return field_rval;
				}
                                if (json_field_default) {
                                    field_rval =
                                        avro_schema_record_field_default_set_by_index(*schema,
                                                                                      i,
                                                                                      json_field_default);
                                }
				avro_schema_decref(json_field_type_schema);
				if (field_rval != 0) {
					avro_schema_decref(*schema);
					return field_rval;
				}
			}
		}
		break;

	case AVRO_ENUM:
		{
			json_t *json_name = json_object_get(json, "name");
			json_t *json_symbols = json_object_get(json, "symbols");
			const char *name;
			unsigned int num_symbols;

			if (!json_is_string(json_name)) {
				avro_set_error("Enum type must have a \"name\"");
				return EINVAL;
			}
			if (!json_is_array(json_symbols)) {
				avro_set_error("Enum type must have \"symbols\"");
				return EINVAL;
			}

			name = json_string_value(json_name);
			if (!name) {
				avro_set_error("Enum type must have a \"name\"");
				return EINVAL;
			}
			num_symbols = json_array_size(json_symbols);
			if (num_symbols == 0) {
				avro_set_error("Enum type must have at least one symbol");
				return EINVAL;
			}
			*schema = avro_schema_enum(name);
			if (save_named_schemas(name, *schema, named_schemas)) {
				avro_set_error("Cannot save enum schema");
				return ENOMEM;
			}
			for (i = 0; i < num_symbols; i++) {
				int enum_rval;
				json_t *json_symbol =
				    json_array_get(json_symbols, i);
				const char *symbol;
				if (!json_is_string(json_symbol)) {
					avro_set_error("Enum symbol %d must be a string", i);
					avro_schema_decref(*schema);
					return EINVAL;
				}
				symbol = json_string_value(json_symbol);
				enum_rval =
				    avro_schema_enum_symbol_append(*schema,
								   symbol);
				if (enum_rval != 0) {
					avro_schema_decref(*schema);
					return enum_rval;
				}
			}
		}
		break;

	case AVRO_ARRAY:
		{
			int items_rval;
			json_t *json_items = json_object_get(json, "items");
			avro_schema_t items_schema;
			if (!json_items) {
				avro_set_error("Array type must have \"items\"");
				return EINVAL;
			}
			items_rval =
			    avro_schema_from_json_t(json_items, &items_schema,
						    named_schemas);
			if (items_rval) {
				return items_rval;
			}
			*schema = avro_schema_array(items_schema);
			avro_schema_decref(items_schema);
		}
		break;

	case AVRO_MAP:
		{
			int values_rval;
			json_t *json_values = json_object_get(json, "values");
			avro_schema_t values_schema;

			if (!json_values) {
				avro_set_error("Map type must have \"values\"");
				return EINVAL;
			}
			values_rval =
			    avro_schema_from_json_t(json_values, &values_schema,
						    named_schemas);
			if (values_rval) {
				return values_rval;
			}
			*schema = avro_schema_map(values_schema);
			avro_schema_decref(values_schema);
		}
		break;

	case AVRO_UNION:
		{
			unsigned int num_schemas = json_array_size(json);
			avro_schema_t s;
			if (num_schemas == 0) {
				avro_set_error("Union type must have at least one branch");
				return EINVAL;
			}
			*schema = avro_schema_union();
			for (i = 0; i < num_schemas; i++) {
				int schema_rval;
				json_t *schema_json = json_array_get(json, i);
				if (!schema_json) {
					avro_set_error("Cannot retrieve branch JSON");
					return EINVAL;
				}
				schema_rval =
				    avro_schema_from_json_t(schema_json, &s,
							    named_schemas);
				if (schema_rval != 0) {
					avro_schema_decref(*schema);
					return schema_rval;
				}
				schema_rval =
				    avro_schema_union_append(*schema, s);
				avro_schema_decref(s);
				if (schema_rval != 0) {
					avro_schema_decref(*schema);
					return schema_rval;
				}
			}
		}
		break;

	case AVRO_FIXED:
		{
			json_t *json_size = json_object_get(json, "size");
			json_t *json_name = json_object_get(json, "name");
			json_int_t size;
			const char *name;
			if (!json_is_integer(json_size)) {
				avro_set_error("Fixed type must have a \"size\"");
				return EINVAL;
			}
			if (!json_is_string(json_name)) {
				avro_set_error("Fixed type must have a \"name\"");
				return EINVAL;
			}
			size = json_integer_value(json_size);
			name = json_string_value(json_name);
			*schema = avro_schema_fixed(name, (int64_t) size);
			if (save_named_schemas(name, *schema, named_schemas)) {
				avro_set_error("Cannot save fixed schema");
				return ENOMEM;
			}
		}
		break;

	default:
		avro_set_error("Unknown schema type");
		return EINVAL;
	}
	return 0;
}
コード例 #23
0
int handle_response(json_t* response)
{
	int retval = 0;
	jsonrpc_request_t* req = NULL;
	json_t* return_obj = NULL;
	json_t* internal = NULL;
	char* freeme = NULL;


	/* check if json object */
	if(!json_is_object(response)){
		WARN("jsonrpc response is not an object\n");
		return -1;
	}

	/* check version */
	json_t* version = json_object_get(response, "jsonrpc");
	if(!version) {
		WARN("jsonrpc response does not have a version.\n");
		retval = -1;
		goto end;
	}

	const char* version_s = json_string_value(version);
	if(!version_s){
		WARN("jsonrpc response version is not a string.\n");
		retval = -1;
		goto end;
	}

	if (strlen(version_s) != (sizeof(JSONRPC_VERSION)-1)
			|| strncmp(version_s, JSONRPC_VERSION, sizeof(JSONRPC_VERSION)-1) != 0) {
		WARN("jsonrpc response version is not %s. version: %s\n",
				JSONRPC_VERSION, version_s);
		retval = -1;
		goto end;
	}

	/* check for an id */
	json_t* _id = json_object_get(response, "id");
	if(!_id) {
		WARN("jsonrpc response does not have an id.\n");
		retval = -1;
		goto end;
	}

	int id = json_integer_value(_id);
	if (!(req = pop_request(id))) {
		/* don't fail the server for an unrecognized id */
		retval = 0;
		goto end;
	}

	return_obj = json_object();

	json_t* error = json_object_get(response, "error");
	// if the error value is null, we don't care
	bool _error = error && (json_typeof(error) != JSON_NULL);

	json_t* result = json_object_get(response, "result");

	if(_error) {
		json_object_set(return_obj, "error", error);
	}

	if(result) {
		json_object_set(return_obj, "result", result);
	}

	if ((!result && !_error) || (result && _error)) {
		WARN("bad response\n");
		internal = internal_error(JRPC_ERR_BAD_RESP, req->payload);
		json_object_update(return_obj, internal);
		if(internal) json_decref(internal);
	}

	pv_value_t val;

	if(jsontoval(&val, &freeme, return_obj)<0) {
		fail_request(
				JRPC_ERR_TO_VAL,
				req,
				"Failed to convert response json to pv\n");
		retval = -1;
		goto end;
	}

	char* error_s = NULL;

	if(send_to_script(&val, req->cmd)>=0) {
		goto free_and_end;
	}

	if(_error) {
		// get code from error
		json_t* _code = json_object_get(error, "code");
		if(_code) {
			int code = json_integer_value(_code);

			// check if code is in global_retry_ranges
			retry_range_t* tmpr;
			for(tmpr = global_retry_ranges;
					tmpr != NULL;
					tmpr = tmpr->next) {
				if((tmpr->start < tmpr->end
						&& tmpr->start <= code && code <= tmpr->end)
				|| (tmpr->end < tmpr->start
						&& tmpr->end <= code && code <= tmpr->start)
				|| (tmpr->start == tmpr->end && tmpr->start == code)) {
					if(schedule_retry(req)==0) {
						goto end;
					}
					break;
				}
			}

		}
		error_s = json_dumps(error, JSON_COMPACT);
		if(error_s) {
			WARN("Request received an error: \n%s\n", error_s);
			free(error_s);
		} else {
			fail_request(
					JRPC_ERR_BAD_RESP,
					req,
					"Could not convert 'error' response to string");
			retval = -1;
			goto end;
		}
	}


free_and_end:
	free_req_cmd(req->cmd);
	free_request(req);

end:
	if(freeme) free(freeme);
	if(return_obj) json_decref(return_obj);
	return retval;
}
コード例 #24
0
ファイル: zeromq.c プロジェクト: skywave/uwsgi
static int uwsgi_mongrel2_json_parse(json_t * root, struct wsgi_request *wsgi_req) {

	char *json_val;
	char *query_string = NULL;
	size_t query_string_len = 0;
	size_t script_name_len = 0;
	void *json_iter;
	char *json_key;
	json_t *json_value;

	if ((json_val = uwsgi_mongrel2_json_get_string(root, "METHOD"))) {
		if (!strcmp(json_val, "JSON")) {
			return -1;
		}
		wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "REQUEST_METHOD", 14, json_val, strlen(json_val));
	}

	if ((json_val = uwsgi_mongrel2_json_get_string(root, "x-mongrel2-upload-done"))) {
		wsgi_req->async_post = fopen(json_val, "r");
		if (!wsgi_req->async_post) {
			uwsgi_error_open(json_val);
			return -1;
		}
	}
	else if (uwsgi_mongrel2_json_get_string(root, "x-mongrel2-upload-start")) {
		return -1;
	}


	wsgi_req->uh.pktsize += uwsgi_mongrel2_json_add(wsgi_req, root, "VERSION", "SERVER_PROTOCOL", 15, NULL, NULL);
	wsgi_req->uh.pktsize += uwsgi_mongrel2_json_add(wsgi_req, root, "QUERY", "QUERY_STRING", 12, &query_string, &query_string_len);
	if (query_string == NULL) {
		// always set QUERY_STRING
		wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "QUERY_STRING", 12, "", 0);
	}

	// set SCRIPT_NAME to an empty value
	wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "SCRIPT_NAME", 11, "", 0);

	if ((json_val = uwsgi_mongrel2_json_get_string(root, "PATH"))) {
		wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "PATH_INFO", 9, json_val + script_name_len, strlen(json_val + script_name_len));
		if (query_string_len) {
			char *request_uri = uwsgi_concat3n(json_val, strlen(json_val), "?", 1, query_string, query_string_len);
			wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "REQUEST_URI", 11, request_uri, strlen(json_val) + 1 + query_string_len);
			free(request_uri);
		}
		else {
			wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "REQUEST_URI", 11, json_val, strlen(json_val));
		}
	}

	if ((json_val = uwsgi_mongrel2_json_get_string(root, "host"))) {
		char *colon = strchr(json_val, ':');
		if (colon) {
			wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "SERVER_PORT", 11, colon + 1, strlen(colon + 1));
		}
		else {
			wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "SERVER_PORT", 11, "80", 2);
		}
	}

	if ((json_val = uwsgi_mongrel2_json_get_string(root, "x-forwarded-for"))) {
		char *colon = strchr(json_val, ',');
                if (colon) {
                	wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "REMOTE_ADDR", 11, colon + 1, (colon + 1) - json_val);
                }
                else {
                	wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "REMOTE_ADDR", 11, json_val, strlen(json_val));
                }
	}


	if ((json_val = uwsgi_mongrel2_json_get_string(root, "content-length"))) {
		wsgi_req->post_cl = atoi(json_val);
	}

	wsgi_req->uh.pktsize += proto_base_add_uwsgi_var(wsgi_req, "SERVER_NAME", 11, uwsgi.hostname, uwsgi.hostname_len);

	json_iter = json_object_iter(root);

	while (json_iter) {
		json_key = (char *) json_object_iter_key(json_iter);
		// is it a header ?
		if (json_key[0] >= 97) {
			json_value = json_object_iter_value(json_iter);
			if (json_is_string(json_value)) {
				json_val = (char *) json_string_value(json_value);
				wsgi_req->uh.pktsize += proto_base_add_uwsgi_header(wsgi_req, json_key, strlen(json_key), json_val, strlen(json_val));
			}
		}
		json_iter = json_object_iter_next(root, json_iter);
	}

	return 0;

}
コード例 #25
0
ファイル: schema.c プロジェクト: thirumg/Avro.NET
avro_schema_t avro_schema_string(void)
{
	static struct avro_obj_t obj = {
		.type = AVRO_STRING,
		.class_type = AVRO_SCHEMA,
		.refcount = 1
	};
	return &obj;
}

avro_schema_t avro_schema_bytes(void)
{
	static struct avro_obj_t obj = {
		.type = AVRO_BYTES,
		.class_type = AVRO_SCHEMA,
		.refcount = 1
	};
	return &obj;
}

avro_schema_t avro_schema_int(void)
{
	static struct avro_obj_t obj = {
		.type = AVRO_INT32,
		.class_type = AVRO_SCHEMA,
		.refcount = 1
	};
	return &obj;
}

avro_schema_t avro_schema_long(void)
{
	static struct avro_obj_t obj = {
		.type = AVRO_INT64,
		.class_type = AVRO_SCHEMA,
		.refcount = 1
	};
	return &obj;
}

avro_schema_t avro_schema_float(void)
{
	static struct avro_obj_t obj = {
		.type = AVRO_FLOAT,
		.class_type = AVRO_SCHEMA,
		.refcount = 1
	};
	return &obj;
}

avro_schema_t avro_schema_double(void)
{
	static struct avro_obj_t obj = {
		.type = AVRO_DOUBLE,
		.class_type = AVRO_SCHEMA,
		.refcount = 1
	};
	return &obj;
}

avro_schema_t avro_schema_boolean(void)
{
	static struct avro_obj_t obj = {
		.type = AVRO_BOOLEAN,
		.class_type = AVRO_SCHEMA,
		.refcount = 1
	};
	return &obj;
}

avro_schema_t avro_schema_null(void)
{
	static struct avro_obj_t obj = {
		.type = AVRO_NULL,
		.class_type = AVRO_SCHEMA,
		.refcount = 1
	};
	return &obj;
}

avro_schema_t avro_schema_fixed(const char *name, const int64_t size)
{
	struct avro_fixed_schema_t *fixed =
	    malloc(sizeof(struct avro_fixed_schema_t));
	if (!fixed) {
		return NULL;
	}
	if (!is_avro_id(name)) {
		return NULL;
	}
	fixed->name = strdup(name);
	fixed->size = size;
	avro_schema_init(&fixed->obj, AVRO_FIXED);
	return &fixed->obj;
}

avro_schema_t avro_schema_union(void)
{
	struct avro_union_schema_t *schema =
	    malloc(sizeof(struct avro_union_schema_t));
	if (!schema) {
		return NULL;
	}
	schema->branches = st_init_numtable_with_size(DEFAULT_TABLE_SIZE);
	if (!schema->branches) {
		free(schema);
		return NULL;
	}

	avro_schema_init(&schema->obj, AVRO_UNION);
	return &schema->obj;
}

int
avro_schema_union_append(const avro_schema_t union_schema,
			 const avro_schema_t schema)
{
	struct avro_union_schema_t *unionp;
	if (!union_schema || !schema || !is_avro_union(union_schema)) {
		return EINVAL;
	}
	unionp = avro_schema_to_union(union_schema);
	st_insert(unionp->branches, unionp->branches->num_entries,
		  (st_data_t) schema);
	avro_schema_incref(schema);
	return 0;
}

avro_schema_t avro_schema_array(const avro_schema_t items)
{
	struct avro_array_schema_t *array =
	    malloc(sizeof(struct avro_array_schema_t));
	if (!array) {
		return NULL;
	}
	array->items = avro_schema_incref(items);
	avro_schema_init(&array->obj, AVRO_ARRAY);
	return &array->obj;
}

avro_schema_t avro_schema_map(const avro_schema_t values)
{
	struct avro_map_schema_t *map =
	    malloc(sizeof(struct avro_map_schema_t));
	if (!map) {
		return NULL;
	}
	map->values = avro_schema_incref(values);
	avro_schema_init(&map->obj, AVRO_MAP);
	return &map->obj;
}

avro_schema_t avro_schema_enum(const char *name)
{
	struct avro_enum_schema_t *enump;

	if (!is_avro_id(name)) {
		return NULL;
	}
	enump = malloc(sizeof(struct avro_enum_schema_t));
	if (!enump) {
		return NULL;
	}
	enump->name = strdup(name);
	if (!enump->name) {
		free(enump);
		return NULL;
	}
	enump->symbols = st_init_numtable_with_size(DEFAULT_TABLE_SIZE);
	if (!enump->symbols) {
		free(enump->name);
		free(enump);
		return NULL;
	}
	enump->symbols_byname = st_init_strtable_with_size(DEFAULT_TABLE_SIZE);
	if (!enump->symbols_byname) {
		st_free_table(enump->symbols);
		free(enump->name);
		free(enump);
		return NULL;
	}
	avro_schema_init(&enump->obj, AVRO_ENUM);
	return &enump->obj;
}

int
avro_schema_enum_symbol_append(const avro_schema_t enum_schema,
			       const char *symbol)
{
	struct avro_enum_schema_t *enump;
	char *sym;
	long idx;
	if (!enum_schema || !symbol || !is_avro_enum(enum_schema)) {
		return EINVAL;
	}
	enump = avro_schema_to_enum(enum_schema);
	sym = strdup(symbol);
	if (!sym) {
		return ENOMEM;
	}
	idx = enump->symbols->num_entries;
	st_insert(enump->symbols, (st_data_t) idx, (st_data_t) sym);
	st_insert(enump->symbols_byname, (st_data_t) sym, (st_data_t) idx);
	return 0;
}

int
avro_schema_record_field_append(const avro_schema_t record_schema,
				const char *field_name,
				const avro_schema_t field_schema)
{
	struct avro_record_schema_t *record;
	struct avro_record_field_t *new_field;
	if (!field_name || !field_schema || !is_avro_schema(record_schema)
	    || !is_avro_record(record_schema) || record_schema == field_schema
	    || !is_avro_id(field_name)) {
		return EINVAL;
	}
	record = avro_schema_to_record(record_schema);
	new_field = malloc(sizeof(struct avro_record_field_t));
	if (!new_field) {
		return ENOMEM;
	}
	new_field->name = strdup(field_name);
	new_field->type = avro_schema_incref(field_schema);
	st_insert(record->fields, record->fields->num_entries,
		  (st_data_t) new_field);
	st_insert(record->fields_byname, (st_data_t) new_field->name,
		  (st_data_t) new_field);
	return 0;
}

avro_schema_t avro_schema_record(const char *name, const char *space)
{
	struct avro_record_schema_t *record;
	if (!is_avro_id(name)) {
		return NULL;
	}
	record = malloc(sizeof(struct avro_record_schema_t));
	if (!record) {
		return NULL;
	}
	record->name = strdup(name);
	if (!record->name) {
		free(record);
		return NULL;
	}
	record->space = space ? strdup(space) : NULL;
	if (space && !record->space) {
		free(record->name);
		free(record);
		return NULL;
	}
	record->fields = st_init_numtable_with_size(DEFAULT_TABLE_SIZE);
	if (!record->fields) {
		if (record->space) {
			free(record->space);
		}
		free(record->name);
		free(record);
		return NULL;
	}
	record->fields_byname = st_init_strtable_with_size(DEFAULT_TABLE_SIZE);
	if (!record->fields_byname) {
		st_free_table(record->fields);
		free(record->name);
		free(record);
		return NULL;
	}

	avro_schema_init(&record->obj, AVRO_RECORD);
	return &record->obj;
}

static int
save_named_schemas(const char *name, avro_schema_t schema,
		   avro_schema_error_t * error)
{
	st_table *st = (*error)->named_schemas;
	return st_insert(st, (st_data_t) name, (st_data_t) schema);
}

static avro_schema_t
find_named_schemas(const char *name, avro_schema_error_t * error)
{
	st_table *st = (*error)->named_schemas;
	union {
		avro_schema_t schema;
		st_data_t data;
	} val;
	if (st_lookup(st, (st_data_t) name, &(val.data))) {
		return val.schema;
	}
	return NULL;
};

avro_schema_t avro_schema_link(avro_schema_t to)
{
	struct avro_link_schema_t *link;
	if (!is_avro_named_type(to)) {
		return NULL;
	}
	link = malloc(sizeof(struct avro_link_schema_t));
	if (!link) {
		return NULL;
	}
	link->to = avro_schema_incref(to);
	avro_schema_init(&link->obj, AVRO_LINK);
	return &link->obj;
}

static int
avro_type_from_json_t(json_t * json, avro_type_t * type,
		      avro_schema_error_t * error, avro_schema_t * named_type)
{
	json_t *json_type;
	const char *type_str;

	if (json_is_array(json)) {
		*type = AVRO_UNION;
		return 0;
	} else if (json_is_object(json)) {
		json_type = json_object_get(json, "type");
	} else {
		json_type = json;
	}
	if (!json_is_string(json_type)) {
		return EINVAL;
	}
	type_str = json_string_value(json_type);
	if (!type_str) {
		return EINVAL;
	}
	/*
	 * TODO: gperf/re2c this 
	 */
	if (strcmp(type_str, "string") == 0) {
		*type = AVRO_STRING;
	} else if (strcmp(type_str, "bytes") == 0) {
		*type = AVRO_BYTES;
	} else if (strcmp(type_str, "int") == 0) {
		*type = AVRO_INT32;
	} else if (strcmp(type_str, "long") == 0) {
		*type = AVRO_INT64;
	} else if (strcmp(type_str, "float") == 0) {
		*type = AVRO_FLOAT;
	} else if (strcmp(type_str, "double") == 0) {
		*type = AVRO_DOUBLE;
	} else if (strcmp(type_str, "boolean") == 0) {
		*type = AVRO_BOOLEAN;
	} else if (strcmp(type_str, "null") == 0) {
		*type = AVRO_NULL;
	} else if (strcmp(type_str, "record") == 0) {
		*type = AVRO_RECORD;
	} else if (strcmp(type_str, "enum") == 0) {
		*type = AVRO_ENUM;
	} else if (strcmp(type_str, "array") == 0) {
		*type = AVRO_ARRAY;
	} else if (strcmp(type_str, "map") == 0) {
		*type = AVRO_MAP;
	} else if (strcmp(type_str, "fixed") == 0) {
		*type = AVRO_FIXED;
	} else if ((*named_type = find_named_schemas(type_str, error))) {
		*type = AVRO_LINK;
	} else {
		return EINVAL;
	}
	return 0;
}

static int
avro_schema_from_json_t(json_t * json, avro_schema_t * schema,
			avro_schema_error_t * error)
{
	avro_type_t type = 0;
	unsigned int i;
	avro_schema_t named_schemas = NULL;

	if (avro_type_from_json_t(json, &type, error, &named_schemas)) {
		return EINVAL;
	}

	switch (type) {
	case AVRO_LINK:
		*schema = avro_schema_link(named_schemas);
		break;

	case AVRO_STRING:
		*schema = avro_schema_string();
		break;

	case AVRO_BYTES:
		*schema = avro_schema_bytes();
		break;

	case AVRO_INT32:
		*schema = avro_schema_int();
		break;

	case AVRO_INT64:
		*schema = avro_schema_long();
		break;

	case AVRO_FLOAT:
		*schema = avro_schema_float();
		break;

	case AVRO_DOUBLE:
		*schema = avro_schema_double();
		break;

	case AVRO_BOOLEAN:
		*schema = avro_schema_boolean();
		break;

	case AVRO_NULL:
		*schema = avro_schema_null();
		break;

	case AVRO_RECORD:
		{
			json_t *json_name = json_object_get(json, "name");
			json_t *json_namespace =
			    json_object_get(json, "namespace");
			json_t *json_fields = json_object_get(json, "fields");
			unsigned int num_fields;
			const char *record_name;
			const char *record_namespace;

			if (!json_is_string(json_name)) {
				return EINVAL;
			}
			if (!json_is_array(json_fields)) {
				return EINVAL;
			}
			num_fields = json_array_size(json_fields);
			if (num_fields == 0) {
				return EINVAL;
			}
			record_name = json_string_value(json_name);
			if (!record_name) {
				return EINVAL;
			}
			if (json_is_string(json_namespace)) {
				record_namespace =
				    json_string_value(json_namespace);
			} else {
				record_namespace = NULL;
			}
			*schema =
			    avro_schema_record(record_name, record_namespace);
			if (save_named_schemas(record_name, *schema, error)) {
				return ENOMEM;
			}
			for (i = 0; i < num_fields; i++) {
				json_t *json_field =
				    json_array_get(json_fields, i);
				json_t *json_field_name;
				json_t *json_field_type;
				avro_schema_t json_field_type_schema;
				int field_rval;

				if (!json_is_object(json_field)) {
					avro_schema_decref(*schema);
					return EINVAL;
				}
				json_field_name =
				    json_object_get(json_field, "name");
				if (!json_field_name) {
					avro_schema_decref(*schema);
					return EINVAL;
				}
				json_field_type =
				    json_object_get(json_field, "type");
				if (!json_field_type) {
					avro_schema_decref(*schema);
					return EINVAL;
				}
				field_rval =
				    avro_schema_from_json_t(json_field_type,
							    &json_field_type_schema,
							    error);
				if (field_rval) {
					avro_schema_decref(*schema);
					return field_rval;
				}
				field_rval =
				    avro_schema_record_field_append(*schema,
								    json_string_value
								    (json_field_name),
								    json_field_type_schema);
				avro_schema_decref(json_field_type_schema);
				if (field_rval != 0) {
					avro_schema_decref(*schema);
					return field_rval;
				}
			}
		}
		break;

	case AVRO_ENUM:
		{
			json_t *json_name = json_object_get(json, "name");
			json_t *json_symbols = json_object_get(json, "symbols");
			const char *name;
			unsigned int num_symbols;

			if (!json_is_string(json_name)) {
				return EINVAL;
			}
			if (!json_is_array(json_symbols)) {
				return EINVAL;
			}

			name = json_string_value(json_name);
			if (!name) {
				return EINVAL;
			}
			num_symbols = json_array_size(json_symbols);
			if (num_symbols == 0) {
				return EINVAL;
			}
			*schema = avro_schema_enum(name);
			if (save_named_schemas(name, *schema, error)) {
				return ENOMEM;
			}
			for (i = 0; i < num_symbols; i++) {
				int enum_rval;
				json_t *json_symbol =
				    json_array_get(json_symbols, i);
				const char *symbol;
				if (!json_is_string(json_symbol)) {
					avro_schema_decref(*schema);
					return EINVAL;
				}
				symbol = json_string_value(json_symbol);
				enum_rval =
				    avro_schema_enum_symbol_append(*schema,
								   symbol);
				if (enum_rval != 0) {
					avro_schema_decref(*schema);
					return enum_rval;
				}
			}
		}
		break;

	case AVRO_ARRAY:
		{
			int items_rval;
			json_t *json_items = json_object_get(json, "items");
			avro_schema_t items_schema;
			if (!json_items) {
				return EINVAL;
			}
			items_rval =
			    avro_schema_from_json_t(json_items, &items_schema,
						    error);
			if (items_rval) {
				return items_rval;
			}
			*schema = avro_schema_array(items_schema);
			avro_schema_decref(items_schema);
		}
		break;

	case AVRO_MAP:
		{
			int values_rval;
			json_t *json_values = json_object_get(json, "values");
			avro_schema_t values_schema;

			if (!json_values) {
				return EINVAL;
			}
			values_rval =
			    avro_schema_from_json_t(json_values, &values_schema,
						    error);
			if (values_rval) {
				return values_rval;
			}
			*schema = avro_schema_map(values_schema);
			avro_schema_decref(values_schema);
		}
		break;

	case AVRO_UNION:
		{
			unsigned int num_schemas = json_array_size(json);
			avro_schema_t s;
			if (num_schemas == 0) {
				return EINVAL;
			}
			*schema = avro_schema_union();
			for (i = 0; i < num_schemas; i++) {
				int schema_rval;
				json_t *schema_json = json_array_get(json, i);
				if (!schema_json) {
					return EINVAL;
				}
				schema_rval =
				    avro_schema_from_json_t(schema_json, &s,
							    error);
				if (schema_rval != 0) {
					avro_schema_decref(*schema);
					return schema_rval;
				}
				schema_rval =
				    avro_schema_union_append(*schema, s);
				avro_schema_decref(s);
				if (schema_rval != 0) {
					avro_schema_decref(*schema);
					return schema_rval;
				}
			}
		}
		break;

	case AVRO_FIXED:
		{
			json_t *json_size = json_object_get(json, "size");
			json_t *json_name = json_object_get(json, "name");
			int size;
			const char *name;
			if (!json_is_integer(json_size)) {
				return EINVAL;
			}
			if (!json_is_string(json_name)) {
				return EINVAL;
			}
			size = json_integer_value(json_size);
			name = json_string_value(json_name);
			*schema = avro_schema_fixed(name, size);
			if (save_named_schemas(name, *schema, error)) {
				return ENOMEM;
			}
		}
		break;

	default:
		return EINVAL;
	}
	return 0;
}

int
avro_schema_from_json(const char *jsontext, const int32_t len,
		      avro_schema_t * schema, avro_schema_error_t * e)
{
	json_t *root;
	int rval = 0;
	avro_schema_error_t error;

	AVRO_UNUSED(len);

	if (!jsontext || !schema) {
		return EINVAL;
	}

	error = malloc(sizeof(struct avro_schema_error_t_));
	if (!error) {
		return ENOMEM;
	}
	*e = error;

	error->named_schemas = st_init_strtable_with_size(DEFAULT_TABLE_SIZE);
	if (!error->named_schemas) {
		free(error);
		return ENOMEM;
	}

	root = json_loads(jsontext, &error->json_error);
	if (!root) {
		st_free_table(error->named_schemas);
		free(error);
		return EINVAL;
	}

	/*
	 * json_dumpf(root, stderr, 0); 
	 */
	rval = avro_schema_from_json_t(root, schema, e);
	json_decref(root);
	st_free_table(error->named_schemas);
	if (rval == 0) {
		/* no need for an error return */
		free(error);
	}
	return rval;
}

avro_schema_t avro_schema_copy(avro_schema_t schema)
{
	long i;
	avro_schema_t new_schema = NULL;
	if (!schema) {
		return NULL;
	}
	switch (avro_typeof(schema)) {
	case AVRO_STRING:
	case AVRO_BYTES:
	case AVRO_INT32:
	case AVRO_INT64:
	case AVRO_FLOAT:
	case AVRO_DOUBLE:
	case AVRO_BOOLEAN:
	case AVRO_NULL:
		/*
		 * No need to copy primitives since they're static 
		 */
		new_schema = schema;
		break;

	case AVRO_RECORD:
		{
			struct avro_record_schema_t *record_schema =
			    avro_schema_to_record(schema);
			new_schema =
			    avro_schema_record(record_schema->name,
					       record_schema->space);
			for (i = 0; i < record_schema->fields->num_entries; i++) {
				union {
					st_data_t data;
					struct avro_record_field_t *field;
				} val;
				st_lookup(record_schema->fields, i, &val.data);
				avro_schema_t type_copy =
				    avro_schema_copy(val.field->type);
				avro_schema_record_field_append(new_schema,
								val.field->name,
								type_copy);
			}
		}
		break;

	case AVRO_ENUM:
		{
			struct avro_enum_schema_t *enum_schema =
			    avro_schema_to_enum(schema);
			new_schema = avro_schema_enum(enum_schema->name);
			for (i = 0; i < enum_schema->symbols->num_entries; i++) {
				union {
					st_data_t data;
					char *sym;
				} val;
				st_lookup(enum_schema->symbols, i, &val.data);
				avro_schema_enum_symbol_append(new_schema,
							       val.sym);
			}
		}
		break;

	case AVRO_FIXED:
		{
			struct avro_fixed_schema_t *fixed_schema =
			    avro_schema_to_fixed(schema);
			new_schema =
			    avro_schema_fixed(fixed_schema->name,
					      fixed_schema->size);
		}
		break;

	case AVRO_MAP:
		{
			struct avro_map_schema_t *map_schema =
			    avro_schema_to_map(schema);
			avro_schema_t values_copy =
			    avro_schema_copy(map_schema->values);
			if (!values_copy) {
				return NULL;
			}
			new_schema = avro_schema_map(values_copy);
		}
		break;

	case AVRO_ARRAY:
		{
			struct avro_array_schema_t *array_schema =
			    avro_schema_to_array(schema);
			avro_schema_t items_copy =
			    avro_schema_copy(array_schema->items);
			if (!items_copy) {
				return NULL;
			}
			new_schema = avro_schema_array(items_copy);
		}
		break;

	case AVRO_UNION:
		{
			struct avro_union_schema_t *union_schema =
			    avro_schema_to_union(schema);

			new_schema = avro_schema_union();
			for (i = 0; i < union_schema->branches->num_entries;
			     i++) {
				avro_schema_t schema_copy;
				union {
					st_data_t data;
					avro_schema_t schema;
				} val;
				st_lookup(union_schema->branches, i, &val.data);
				schema_copy = avro_schema_copy(val.schema);
				if (avro_schema_union_append
				    (new_schema, schema_copy)) {
					avro_schema_decref(new_schema);
					return NULL;
				}
			}
		}
		break;

	case AVRO_LINK:
		{
			struct avro_link_schema_t *link_schema =
			    avro_schema_to_link(schema);
			/*
			 * TODO: use an avro_schema_copy of to instead of pointing to
			 * the same reference 
			 */
			avro_schema_incref(link_schema->to);
			new_schema = avro_schema_link(link_schema->to);
		}
		break;

	default:
		return NULL;
	}
	return new_schema;
}

const char *avro_schema_name(const avro_schema_t schema)
{
	if (is_avro_record(schema)) {
		return (avro_schema_to_record(schema))->name;
	} else if (is_avro_enum(schema)) {
		return (avro_schema_to_enum(schema))->name;
	} else if (is_avro_fixed(schema)) {
		return (avro_schema_to_fixed(schema))->name;
	}
	return NULL;
}

/* simple helper for writing strings */
static int avro_write_str(avro_writer_t out, const char *str)
{
	return avro_write(out, (char *)str, strlen(str));
}

static int write_field(avro_writer_t out, struct avro_record_field_t *field)
{
	int rval;
	check(rval, avro_write_str(out, "{\"name\":\""));
	check(rval, avro_write_str(out, field->name));
	check(rval, avro_write_str(out, "\",\"type\":"));
	check(rval, avro_schema_to_json(field->type, out));
	return avro_write_str(out, "}");
}

static int write_record(avro_writer_t out, struct avro_record_schema_t *record)
{
	int rval;
	long i;

	check(rval, avro_write_str(out, "{\"type\":\"record\",\"name\":\""));
	check(rval, avro_write_str(out, record->name));
	check(rval, avro_write_str(out, "\","));
	if (record->space) {
		check(rval, avro_write_str(out, "\"namespace\":\""));
		check(rval, avro_write_str(out, record->space));
		check(rval, avro_write_str(out, "\","));
	}
	check(rval, avro_write_str(out, "\"fields\":["));
	for (i = 0; i < record->fields->num_entries; i++) {
		union {
			st_data_t data;
			struct avro_record_field_t *field;
		} val;
		st_lookup(record->fields, i, &val.data);
		if (i) {
			check(rval, avro_write_str(out, ","));
		}
		check(rval, write_field(out, val.field));
	}
	return avro_write_str(out, "]}");
}
コード例 #26
0
ファイル: esdm-config.c プロジェクト: ESiWACE/ESD-Middleware
/**
 *	Fetches backends
 *
 *
 */
esdm_config_backends_t* esdm_config_get_backends(esdm_instance_t* esdm)
{
	ESDM_DEBUG(__func__);

	json_t *root = (json_t*) esdm->config->json;

	// fetch configured backends
	json_t *element = json_path_get(root, "$.esdm.backends");

	esdm_config_backends_t* config_backends = (esdm_config_backends_t*) malloc(sizeof(esdm_config_backends_t));

	if (element)
	{
		if (json_typeof(element) == JSON_ARRAY)
		{
			// Element is array, therefor may contain valid backend configurations
			size_t size = json_array_size(element);

			esdm_config_backend_t* backends;
			backends = (esdm_config_backend_t*) malloc(sizeof(esdm_config_backend_t)*size);

			//printf("JSON Array of %ld element%s:\n", size, json_plural(size));

			size_t i, j;
			for (i = 0; i < size; i++) {
				//print_json_aux(json_array_get(element, i), 0);

				json_t *backend = json_array_get(element, i);
				json_t *elem = NULL;

				elem = json_object_get(backend, "type");
				backends[i].type = json_string_value(elem);

				elem = json_object_get(backend, "id");
				backends[i].id = json_string_value(elem);
				for (j = 0; j < i; j++) {
					if(strcmp(backends[i].id, backends[j].id) == 0){
						printf("ERROR two backends with the same ID found: %s\n", backends[i].id);
						ESDM_ERROR("Aborting!");
					}
				}

				elem = json_object_get(backend, "target");
				backends[i].target = json_string_value(elem);
				backends[i].performance_model = json_object_get(backend, "performance-model");
				DEBUG("type=%s id = %s target=%s\n", backends[i].type,
					backends[i].id,
					backends[i].target);

				elem = json_object_get(backend, "max-threads-per-node");
				if (elem == NULL){
					backends[i].max_threads_per_node = 0;
				}else{
					backends[i].max_threads_per_node = json_integer_value(elem);
				}

				elem = json_object_get(backend, "max-global-threads");
				if (elem == NULL){
					backends[i].max_global_threads = 0;
				}else{
					backends[i].max_global_threads = json_integer_value(elem);
				}

				elem = json_object_get(backend, "accessibility");
				if (elem != NULL){
					const char * str = json_string_value(elem);
					if (strcasecmp(str, "global") == 0){
						backends[i].data_accessibility = ESDM_ACCESSIBILITY_GLOBAL;
					}else if (strcasecmp(str, "local") == 0){
						backends[i].data_accessibility = ESDM_ACCESSIBILITY_NODELOCAL;
					}else{
						ESDM_ERROR("Unknown accessibility!");
					}
				} else
					backends[i].data_accessibility = ESDM_ACCESSIBILITY_GLOBAL;

				elem = json_object_get(backend, "max-fragment-size");
				if (elem == NULL){
					backends[i].max_fragment_size = 10*1024*1024;
				}else{
					backends[i].max_fragment_size = json_integer_value(elem);
				}

				backends[i].esdm = root;
				backends[i].backend = backend;
			}

			config_backends->count = size;
			config_backends->backends = backends;

		}
	} else {
		ESDM_ERROR("Invalid configuration! /esdm/backends is not an array.");
	}


	return config_backends;
}
コード例 #27
0
ファイル: ffigen.c プロジェクト: iamaaditya/cshore
void json_object_set_with_key_new(json_t* json, json_t* key, json_t* value) {
  assert(json_is_string(key));
  json_object_set_new(json, json_string_value(key), value);
  json_decref(key);
}
コード例 #28
0
ファイル: il.c プロジェクト: johnjohnsp1/c-utils
int jsonparser(char jsonfilename[160], char username[50]) {

FILE* fp;
char line[15000];
size_t i;
json_t *root;
json_error_t error;

// open the saved json file: ./username/username.json

fp=fopen(jsonfilename, "r");

if (fp == NULL) {
        printf("Error reading json file\n");
        exit(1);
}

fgets(line, sizeof line, fp);

// remove newline

size_t ln = strlen(line) - 1;
if (line[ln] == '\n') {
        line[ln] = '\0';
}

// load the root of the json file

root=json_loads(line, 0, &error);
//free(line);

if (!root) {
        printf("Json error on line:%d. text:%s\n", error.line, error.text);
        exit(1);
}

// requires object to start and end with [ & ]  ?

if (!json_is_array(root)) {
        printf("Error: root not array\n");
        json_decref(root);
        exit(1);
}

// now loop thru it

json_t *data;
json_t *title;
json_t *type;
char* msg;
char* urlarr[1000];

//char* codearr[10000];
// other potential arrs of items from the json file

for (i=0; i < json_array_size(root); i++) {

        data = json_array_get(root, i);

        if(!json_is_object(data)) {
                printf("Error: %d data is not object\n", i+1);
                json_decref(root);
                return 1;
        }

	title = json_object_get(data, "code");
	type = json_object_get(data, "display_src");

	// so as of here, get the url for each image and put in urlarr[i]

	urlarr[i]=malloc(strlen(json_string_value(type))+1);
	strcpy(urlarr[i], json_string_value(type));
	printf("%d: %s\n", i, urlarr[i]);
}

fclose(fp);

// Download the images. First create subdir to save the images: ./username/img

char imagedir[60];

strcpy(imagedir, "./");
strcat(imagedir, username);
strcat(imagedir, "/img/");

// create if it doesn't exist

if (access(imagedir, F_OK) == -1) {
	if (mkdir(imagedir, S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH) == -1) {
		printf("Unable to create image dir\n");
		exit(1);
	}
}

//printf("%d - %s\n", i, imagedir);

// now download the images to ./username/img/imgname.

int x;
char snbuff[300];

for (x=0; x < i; x++) {
	snprintf(snbuff, sizeof snbuff, "wget -P %s -nc %s", imagedir, urlarr[x]);
	system(snbuff);
}

exit(0);

}
コード例 #29
0
static json_t *mbp_process_update(json_t *req, int32 idx, struct rest_uri_param *param)
{
	json_t *result = NULL;
	int8 *image_data = NULL;
	json_t *image_obj = NULL;
	int32 rc = -1;
	int32 cm_lid = 0;
	int8 cm_dev[64] = {0};

	/* check update capability */
	if(libwrap_check_update_capability() != RESULT_OK) {
		HTTPD_ERR("firmware update is not supported.\n");
		return NULL;
	}

	if (!libwrap_get_firmware_update_status()) {
		HTTPD_ERR("get firmware update status fail\n");
		return NULL;
	}

	libwrap_set_firmware_update_status(0);

	result = json_object();
	if (result == NULL) {
		update_response_info(param, HTTP_APPLICATION_ERROR);
		libwrap_set_firmware_update_status(1);
		return NULL;
	}
	rc = libwrap_check_tftp_service();
	if (rc == -1) {
		json_free(req);
		json_object_add(result, RMM_JSON_FRU_RESULT, json_string("tftp server not ready"));
		update_response_info(param, HTTP_NOT_ACCEPTABLE);
		libwrap_set_firmware_update_status(1);
		return result;
	}

	image_obj = json_object_get(req, RMM_JSON_IMAGE);
	if (image_obj == NULL) {
		json_free(req);
		json_object_add(result, RMM_JSON_FRU_RESULT, json_string("invalid image"));
		update_response_info(param, HTTP_NOT_ACCEPTABLE);
		libwrap_set_firmware_update_status(1);
		return result;
	}

	image_data = json_string_value(image_obj);
	if (image_data == NULL) {
		json_free(req);
		json_object_add(result, RMM_JSON_FRU_RESULT, json_string("invalid image"));
		update_response_info(param, HTTP_NOT_ACCEPTABLE);
		libwrap_set_firmware_update_status(1);
		return result;
	}

	cm_lid = idx;
	if ((cm_lid == 1) || (cm_lid == 2)) {
		snprintf(cm_dev, sizeof(cm_dev), "/dev/ttyCm%dIPMI", cm_lid);
		rc = process_firmware_update(cm_lid, cm_dev, image_data, strlen(image_data));
	} else {
		HTTPD_ERR("invalid cm loc id\n");
		json_free(req);
		libwrap_set_firmware_update_status(1);
		return NULL;
	}

	if (rc == 0) {
		json_free(req);
		json_object_add(result, RMM_JSON_FRU_RESULT, json_string(RMM_JSON_UPDATING));
		update_response_info(param, HTTP_ACCEPTED);
		return result;
	} else {
		libwrap_set_firmware_update_status(1);
	}

	json_free(req);

	int8 buff[128] = {};
	snprintf(buff, sizeof(buff), "%d", idx);
	rf_snmp_evt(INFO, MSGMbpChange, buff, RMM_JSON_UPDATE_BIG);
	return NULL;
}
コード例 #30
0
/* Thread to handle incoming messages */
static void *janus_source_handler(void *data) {
	JANUS_LOG(LOG_VERB, "Joining SourcePlugin handler thread\n");
	janus_source_message *msg = NULL;
	int error_code = 0;
	char *error_cause = g_malloc0(512);
	json_t *root = NULL;
	while (g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
		msg = g_async_queue_pop(messages);
		if (msg == NULL)
			continue;
		if (msg == &exit_message)
			break;
		if (msg->handle == NULL) {
			janus_source_message_free(msg);
			continue;
		}
		janus_source_session *session = NULL;
		janus_mutex_lock(&sessions_mutex);
		if (g_hash_table_lookup(sessions, msg->handle) != NULL) {
			session = (janus_source_session *)msg->handle->plugin_handle;
		}
		janus_mutex_unlock(&sessions_mutex);
		if (!session) {
			JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
			janus_source_message_free(msg);
			continue;
		}
		if (session->destroyed) {
			janus_source_message_free(msg);
			continue;
		}
		/* Handle request */
		error_code = 0;
		root = msg->message;
		if (msg->message == NULL) {
			JANUS_LOG(LOG_ERR, "No message??\n");
			error_code = JANUS_SOURCE_ERROR_NO_MESSAGE;
			g_snprintf(error_cause, 512, "%s", "No message??");
			goto error;
		}
		if (!json_is_object(root)) {
			JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_JSON;
			g_snprintf(error_cause, 512, "JSON error: not an object");
			goto error;
		}
		/* Parse request */
		const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
		const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
		json_t *audio = json_object_get(root, "audio");
		if (audio && !json_is_boolean(audio)) {
			JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)");
			goto error;
		}
		json_t *video = json_object_get(root, "video");
		if (video && !json_is_boolean(video)) {
			JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)");
			goto error;
		}
		json_t *bitrate = json_object_get(root, "bitrate");
		if (bitrate && (!json_is_integer(bitrate) || json_integer_value(bitrate) < 0)) {
			JANUS_LOG(LOG_ERR, "Invalid element (bitrate should be a positive integer)\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (bitrate should be a positive integer)");
			goto error;
		}
		json_t *record = json_object_get(root, "record");
		if (record && !json_is_boolean(record)) {
			JANUS_LOG(LOG_ERR, "Invalid element (record should be a boolean)\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (record should be a boolean)");
			goto error;
		}
		json_t *recfile = json_object_get(root, "filename");
		if (recfile && !json_is_string(recfile)) {
			JANUS_LOG(LOG_ERR, "Invalid element (filename should be a string)\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (filename should be a string)");
			goto error;
		}
		
		json_t *id = json_object_get(root, "id");
		if(id && !json_is_string(id)) {
				JANUS_LOG(LOG_ERR, "Invalid element (id should be a string)\n");
				error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
				g_snprintf(error_cause, 512, "Invalid value (id should be positive string)");
				goto error;
		}
		/* Enforce request */
		if (audio) {
			session->audio_active = json_is_true(audio);
			JANUS_LOG(LOG_VERB, "Setting audio property: %s\n", session->audio_active ? "true" : "false");
		}
		if (video) {
			if (!session->video_active && json_is_true(video)) {
				/* Send a PLI */
				JANUS_LOG(LOG_VERB, "Just (re-)enabled video, sending a PLI to recover it\n");
				char buf[12];
				memset(buf, 0, 12);
				janus_rtcp_pli((char *)&buf, 12);
				gateway->relay_rtcp(session->handle, 1, buf, 12);
			}
			session->video_active = json_is_true(video);
			JANUS_LOG(LOG_VERB, "Setting video property: %s\n", session->video_active ? "true" : "false");
		}
		if (bitrate) {
			session->bitrate = json_integer_value(bitrate);
			JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64"\n", session->bitrate);
			if (session->bitrate > 0) {
				/* FIXME Generate a new REMB (especially useful for Firefox, which doesn't send any we can cap later) */
				char buf[24];
				memset(buf, 0, 24);
				janus_rtcp_remb((char *)&buf, 24, session->bitrate);
				JANUS_LOG(LOG_VERB, "Sending REMB\n");
				gateway->relay_rtcp(session->handle, 1, buf, 24);
				/* FIXME How should we handle a subsequent "no limit" bitrate? */
			}
		}
		if(id) {
			session->id = g_strdup(json_string_value(id));			
		}


		if (!audio && !video && !bitrate && !record && !id && !msg_sdp) {
			JANUS_LOG(LOG_ERR, "No supported attributes (audio, video, bitrate, record, id, jsep) found\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Message error: no supported attributes (audio, video, bitrate, record, id, jsep) found");
			goto error;
		}

		/* Prepare JSON event */
		json_t *event = json_object();
		json_object_set_new(event, "source", json_string("event"));
		json_object_set_new(event, "result", json_string("ok"));
		if(!msg_sdp) {
			int ret = gateway->push_event(msg->handle, &janus_source_plugin, msg->transaction, event, NULL);
			JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
			json_decref(event);
		}
		else {
			/* Forward the same offer to the gateway, to start the source plugin */
			const char *type = NULL;
			if (!strcasecmp(msg_sdp_type, "offer"))
				type = "answer";
			if (!strcasecmp(msg_sdp_type, "answer"))
				type = "offer";
			/* Any media direction that needs to be fixed? */
			char *sdp = g_strdup(msg_sdp);
			if (strstr(sdp, "a=recvonly")) {
				/* Turn recvonly to inactive, as we simply bounce media back */
				sdp = janus_string_replace(sdp, "a=recvonly", "a=inactive");
			}
			else if (strstr(sdp, "a=sendonly")) {
				/* Turn sendonly to recvonly */
				sdp = janus_string_replace(sdp, "a=sendonly", "a=recvonly");
				/* FIXME We should also actually not echo this media back, though... */
			}
			/* Make also sure we get rid of ULPfec, red, etc. */
			if (strstr(sdp, "ulpfec")) {
				/* FIXME This really needs some better code */
				sdp = janus_string_replace(sdp, "a=rtpmap:116 red/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:117 ulpfec/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:96 rtx/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=fmtp:96 apt=100\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:97 rtx/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=fmtp:97 apt=101\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:98 rtx/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=fmtp:98 apt=116\r\n", "");
				sdp = janus_string_replace(sdp, " 116", "");
				sdp = janus_string_replace(sdp, " 117", "");
				sdp = janus_string_replace(sdp, " 96", "");
				sdp = janus_string_replace(sdp, " 97", "");
				sdp = janus_string_replace(sdp, " 98", "");
			}
			json_t *jsep = json_pack("{ssss}", "type", type, "sdp", sdp);
			sdp = janus_source_do_codec_negotiation(session, sdp);
			
			/* How long will the gateway take to push the event? */
			g_atomic_int_set(&session->hangingup, 0);
			gint64 start = janus_get_monotonic_time();
			int res = gateway->push_event(msg->handle, &janus_source_plugin, msg->transaction, event, jsep);
			JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n",
				res, janus_get_monotonic_time() - start);
			g_free(sdp);
			/* We don't need the event and jsep anymore */
			json_decref(event);
			json_decref(jsep);
		}
		janus_source_message_free(msg);
		continue;

	error:
		{
			/* Prepare JSON error event */
			json_t *event = json_object();
			json_object_set_new(event, "source", json_string("event"));
			json_object_set_new(event, "error_code", json_integer(error_code));
			json_object_set_new(event, "error", json_string(error_cause));
			int ret = gateway->push_event(msg->handle, &janus_source_plugin, msg->transaction, event, NULL);
			JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
			janus_source_message_free(msg);
			/* We don't need the event anymore */
			json_decref(event);
		}
	}
	g_free(error_cause);
	JANUS_LOG(LOG_VERB, "Leaving SourcePlugin handler thread\n");
	return NULL;
}