Example #1
0
static void
pretty_print(struct json_object * object, int first_indent, int indent)
{
	if (!object) {
        printf("%*s<NULL>", first_indent, "");
		return;
	}

    switch (json_object_get_type(object)) {
    case json_type_null:
    case json_type_boolean:
    case json_type_int:
    case json_type_double:
    case json_type_string:
        printf("%*s%s", first_indent, "", json_object_to_json_string(object));
        break;
    case json_type_array:
    {
        int len = json_object_array_length(object);
        int i;
        printf("%*s[", first_indent, "");
        bool first = true;
        for (i=0;i<len;i++) {
          if (first) {
            printf("\n");
            first = false;
          } else {
            printf(",\n");
          }
          pretty_print(json_object_array_get_idx(object, i), indent + INDENT_INCREMENT, indent + INDENT_INCREMENT);
        }
        printf("\n%*s]", indent, "");
        break;
    }
    case json_type_object:
    {
        printf("%*s{", first_indent, "");
        bool first = true;
        struct json_object_iterator it = json_object_iter_begin(object);
        struct json_object_iterator itEnd = json_object_iter_end(object);
        while (!json_object_iter_equal(&it, &itEnd)) {
          if (first) {
            printf("\n");
            first = false;
          } else {
            printf(",\n");
          }
          // FIXME: contents of key are not being escaped
          printf("%*s\"%s\": ", indent+INDENT_INCREMENT, "", json_object_iter_peek_name(&it));
          pretty_print(json_object_iter_peek_value(&it), 0, indent + INDENT_INCREMENT);
          json_object_iter_next(&it);
        }
        printf("\n%*s}", indent, "");
        break;
    }
	default:
        printf("%*s<unknown cjson type %d>", first_indent, "", json_object_get_type(object));
		break;
    }
}
Example #2
0
int
ln_fmtEventToRFC5424(struct json_object *json, es_str_t **str)
{
    int r = -1;
    struct json_object *tags;

    assert(json != NULL);
    assert(json_object_is_type(json, json_type_object));
    if((*str = es_newStr(256)) == NULL)
        goto done;

    es_addBuf(str, "[cee@115", 8);

    if(json_object_object_get_ex(json, "event.tags", &tags)) {
        CHKR(ln_addTags_Syslog(tags, str));
    }
    struct json_object_iterator it = json_object_iter_begin(json);
    struct json_object_iterator itEnd = json_object_iter_end(json);
    while (!json_object_iter_equal(&it, &itEnd)) {
        char *const name = (char*)json_object_iter_peek_name(&it);
        if (strcmp(name, "event.tags")) {
            es_addChar(str, ' ');
            ln_addField_Syslog(name, json_object_iter_peek_value(&it), str);
        }
        json_object_iter_next(&it);
    }
    es_addChar(str, ']');

done:
    return r;
}
Example #3
0
std::vector<tagged_feedurl> newsblur_api::get_subscribed_urls() {
	std::vector<tagged_feedurl> result;

	json_object * response = query_api("/reader/feeds", NULL);

	json_object * feeds = json_object_object_get(response, "feeds");

	json_object_iterator it = json_object_iter_begin(feeds);
	json_object_iterator itEnd = json_object_iter_end(feeds);

	while (!json_object_iter_equal(&it, &itEnd)) {
		const char * feed_id = json_object_iter_peek_name(&it);
		json_object * node;
		rsspp::feed current_feed;

		current_feed.rss_version = rsspp::NEWSBLUR_JSON;

		json_object * feed_json = json_object_iter_peek_value(&it);
		node = json_object_object_get(feed_json, "feed_title");
		current_feed.title = json_object_get_string(node);
		node = json_object_object_get(feed_json, "feed_link");
		current_feed.link = json_object_get_string(node);

		known_feeds[feed_id] = current_feed;

		std::vector<std::string> tags = std::vector<std::string>();
		result.push_back(tagged_feedurl(std::string(feed_id), tags));

		json_object_iter_next(&it);
	}

	return result;
}
Example #4
0
void HostContacts::deserialize(NetworkInterface *iface, GenericHost *h, json_object *o) {
  json_object *obj;
  IpAddress ip;

  if(!o) return;

  /* Reset all */
  memset(clientContacts, 0, sizeof(clientContacts));
  memset(serverContacts, 0, sizeof(serverContacts));

  if(json_object_object_get_ex(o, "client", &obj)) {
    struct json_object_iterator it = json_object_iter_begin(obj);
    struct json_object_iterator itEnd = json_object_iter_end(obj);

    while (!json_object_iter_equal(&it, &itEnd)) {
      char *key  = (char*)json_object_iter_peek_name(&it);
      int  value = json_object_get_int(json_object_iter_peek_value(&it));

      ip.set_from_string(key);
      incrContact(iface, h->get_host_serial(), &ip, true /* client */, value, HOST_FAMILY_ID, false);

      //ntop->getTrace()->traceEvent(TRACE_WARNING, "%s=%d", key, value);

      json_object_iter_next(&it);
    }
  }

  if(json_object_object_get_ex(o, "server", &obj)) {
    struct json_object_iterator it = json_object_iter_begin(obj);
    struct json_object_iterator itEnd = json_object_iter_end(obj);

    while (!json_object_iter_equal(&it, &itEnd)) {
      char *key  = (char*)json_object_iter_peek_name(&it);
      int  value = json_object_get_int(json_object_iter_peek_value(&it));

      ip.set_from_string(key);
      incrContact(iface, h->get_host_serial(), &ip, false /* server */, value, HOST_FAMILY_ID, false);

      // ntop->getTrace()->traceEvent(TRACE_WARNING, "%s=%d", key, value);

      json_object_iter_next(&it);
    }
  }
}
Example #5
0
/// @TODO we should print all with this function
static void
print_monitor_value_enrichment(struct printbuf *buf,
			       const json_object *const_enrichment) {
	json_object *enrichment = (json_object *)const_enrichment;

	for (struct json_object_iterator i = json_object_iter_begin(enrichment),
					 end = json_object_iter_end(enrichment);
	     !json_object_iter_equal(&i, &end);
	     json_object_iter_next(&i)) {
		const char *key = json_object_iter_peek_name(&i);
		json_object *val = json_object_iter_peek_value(&i);

		const json_type type = json_object_get_type(val);
		switch (type) {
		case json_type_string:
			print_monitor_value_enrichment_str(buf, key, val);
			break;

		case json_type_int:
			print_monitor_value_enrichment_int(buf, key, val);
			break;

		case json_type_null:
			sprintbuf(buf, ",\"%s\":null", key);
			break;

		case json_type_boolean: {
			const json_bool b = json_object_get_boolean(val);
			sprintbuf(buf,
				  ",\"%s\":%s",
				  key,
				  b == FALSE ? "false" : "true");
			break;
		}
		case json_type_double: {
			const double d = json_object_get_double(val);
			sprintbuf(buf, ",\"%s\":%lf", key, d);
			break;
		}
		case json_type_object:
		case json_type_array: {
			rdlog(LOG_ERR,
			      "Can't enrich with objects/array at this time");
			break;
		}
		default:
			rdlog(LOG_ERR,
			      "Don't know how to duplicate JSON type "
			      "%d",
			      type);
			break;
		};
	}
}
Example #6
0
int pv_json_iterate(json_t **obj, pv_param_t *pvp, json_name *id, pv_value_t *val)
{
	json_iter_t iter_end;

	if (json_object_is_type(*obj, json_type_object)) {

		if (pvp->pvi.u.ival != id->iter_prev_idx + 1) {
			id->iter_prev_idx = 0;
			id->iter = json_object_iter_begin(*obj);
		} else
			id->iter_prev_idx++;

		iter_end = json_object_iter_end(*obj);
		if (json_object_iter_equal(&id->iter, &iter_end))
			return pv_get_null(NULL, pvp, val);

		if (id->iter_type == ITER_KEYS) {
			val->flags = PV_VAL_STR;
			val->rs.s = (char *)json_object_iter_peek_name(&id->iter);
			val->rs.len = strlen(val->rs.s);
		} else
			*obj = json_object_iter_peek_value(&id->iter);

		json_object_iter_next(&id->iter);	

	} else if (json_object_is_type(*obj, json_type_array)) {

		if (id->iter_type != ITER_NONE) {
			LM_DBG("Invalid object-like iteration for arrays\n");
			return -1;
		}

		if (pvp->pvi.u.ival == json_object_array_length(*obj)) {
			id->iter_prev_idx = 0;
			return pv_get_null(NULL, pvp, val);
		}

		*obj = json_object_array_get_idx(*obj, pvp->pvi.u.ival);

	} else {
		LM_DBG("Can only iterate over arrays or objects\n");
		return -1;
	}

	return 0;
}
Example #7
0
Variant json_type_object_to_variant(json_object *new_obj, const bool assoc,
                                    const bool stable_maps,
                                    const bool collections) {
    struct json_object_iterator it, itEnd;
    json_object  *jobj;
    Variant       var, tmpvar;

  if (collections) {
    var = newobj<c_Map>();
  } else if (assoc) {
    var = Array::Create();
  } else {
    var = SystemLib::AllocStdClassObject();
  }

  it = json_object_iter_begin(new_obj);
  itEnd = json_object_iter_end(new_obj);

  while (!json_object_iter_equal(&it, &itEnd)) {
    String key(json_object_iter_peek_name(&it), CopyString);
    jobj = json_object_iter_peek_value(&it);
    tmpvar = json_object_to_variant(jobj, assoc, stable_maps, collections);

    if (!assoc) {
      if (key.empty()) {
        var.getObjectData()->o_set(s_empty, tmpvar);
      } else {
        var.getObjectData()->o_set(key, tmpvar);
      }
    } else {
      if (collections) {
        auto keyTV = make_tv<KindOfString>(key.get());
        collectionSet(var.getObjectData(), &keyTV, tmpvar.asCell());
      } else {
        forceToArray(var).set(key, tmpvar);
      }
    }
    json_object_iter_next(&it);
  }
  return var;
}
Example #8
0
std::vector<tagged_feedurl> newsblur_api::get_subscribed_urls() {
	std::vector<tagged_feedurl> result;

	json_object * response = query_api("/reader/feeds/", NULL);

	json_object * feeds {};
	json_object_object_get_ex(response, "feeds", &feeds);

	json_object_iterator it = json_object_iter_begin(feeds);
	json_object_iterator itEnd = json_object_iter_end(feeds);

	json_object * folders {};
	json_object_object_get_ex(response, "folders", &folders);

	std::map<std::string, std::vector<std::string>> feeds_to_tags = mk_feeds_to_tags(folders);

	while (!json_object_iter_equal(&it, &itEnd)) {
		const char * feed_id = json_object_iter_peek_name(&it);
		json_object * node {};
		rsspp::feed current_feed;

		current_feed.rss_version = rsspp::NEWSBLUR_JSON;

		json_object * feed_json = json_object_iter_peek_value(&it);
		json_object_object_get_ex(feed_json, "feed_title", &node);
		current_feed.title = json_object_get_string(node);
		json_object_object_get_ex(feed_json, "feed_link", &node);
		current_feed.link = json_object_get_string(node);

		known_feeds[feed_id] = current_feed;

		std::string std_feed_id(feed_id);
		std::vector<std::string> tags = feeds_to_tags[std_feed_id];
		result.push_back(tagged_feedurl(std_feed_id, tags));

		json_object_iter_next(&it);
	}

	return result;
}
Example #9
0
void ActivityStats::deserialize(json_object *o) {
  Uint32EWAHBoolArray *bitset = (Uint32EWAHBoolArray*)_bitset;
  struct json_object_iterator it, itEnd;

  if(!o) return;

  /* Reset all */
  bitset->reset();

  it = json_object_iter_begin(o), itEnd = json_object_iter_end(o);

  while (!json_object_iter_equal(&it, &itEnd)) {
    char *key  = (char*)json_object_iter_peek_name(&it);
    u_int32_t when = atol(key);

    when %= CONST_MAX_ACTIVITY_DURATION;
    bitset->set(when);
    // ntop->getTrace()->traceEvent(TRACE_WARNING, "%s=%d", key, 1);

    json_object_iter_next(&it);
  }
}
Example #10
0
symbols_t* drakvuf_get_symbols_from_rekall(const char *rekall_profile)
{

    symbols_t *ret = g_malloc0(sizeof(symbols_t));;
    json_object *root = json_object_from_file(rekall_profile);
    if(!root) {
        fprintf(stderr, "Rekall profile couldn't be opened!\n");
        goto err_exit;
    }

    json_object *functions = NULL;
    if (!json_object_object_get_ex(root, "$FUNCTIONS", &functions)) {
        PRINT_DEBUG("Rekall profile: no $FUNCTIONS section found\n");
        goto err_exit;
    }

    ret->count = json_object_object_length(functions);
    ret->symbols = g_malloc0(sizeof(symbols_t) * ret->count);

    struct json_object_iterator it = json_object_iter_begin(functions);
    struct json_object_iterator itEnd = json_object_iter_end(functions);
    uint32_t i=0;

    while (!json_object_iter_equal(&it, &itEnd) && i < ret->count) {
        ret->symbols[i].name = g_strdup(json_object_iter_peek_name(&it));
        ret->symbols[i].rva = json_object_get_int64(json_object_iter_peek_value(&it));
        i++;
        json_object_iter_next(&it);
    }

    json_object_put(functions);

    return ret;

    err_exit: free(ret);
    return NULL;
}
Example #11
0
bool settings_read(void)
{
  bool rv;
  bool bind_defaults;
  bool nonexistent_ok;

  rv             = true;
  bind_defaults  = true;
  nonexistent_ok = false;
  
  /* Read and delete the old versions first if it exists. */
  settings_read_v1();

  if(settings_read_v2())
    {
      bind_defaults = false;
      nonexistent_ok = true; // If we managed to read the old .lua file, then failing to read the new .json file should not cause any error messages.
    }


  /* Read the new version if it exists. */
  char * json;
  int    json_size;

  snprintf(filename, sizeof filename, "%s", get_save_filename("settings.json"));
  if(read_file(filename, &json, &json_size) == true)
    {
      enum json_tokener_error e;
      struct json_object * obj;

      obj = json_tokener_parse_verbose(json, &e);
      if(obj != NULL)
        {
          bool ok;
          struct json_object_iterator it;
          struct json_object_iterator itEnd;
          int active_questline;

          ok    = true;
          it    = json_object_iter_begin(obj);
          itEnd = json_object_iter_end(obj);

          active_questline = globals.active_questline;

          while(ok == true && !json_object_iter_equal(&it, &itEnd))
            {
              const char *         name;
              struct json_object * value;
              enum json_type       type;
              bool                 dummy_boolean;
              
              name  = json_object_iter_peek_name(&it);
              value = json_object_iter_peek_value(&it);
              type = json_object_get_type(value);

              struct
              {
                const char *   name;
                enum json_type type;
                bool (*callback)(struct json_object * value, void * value_ptr);
                void *         value_ptr;
              } stuff[] =
                  {
                    { "Fullscreen",                 json_type_boolean, cb_bool,                 &globals.fullscreen                   },
                    { "OpenGL",                     json_type_boolean, cb_bool,                 &globals.opengl                       },
                    { "OpenGL_POT",                 json_type_boolean, cb_opengl_pot,           NULL                                  },               
                    { "OpenGL_compressed_textures", json_type_boolean, cb_bool,                 &globals.opengl_compressed_textures   },
                    { "SFX",                        json_type_boolean, cb_bool,                 &globals.use_sfx                      },
                    { "Music",                      json_type_boolean, cb_bool,                 &globals.use_music                    },
                    { "SFX_max_channels",           json_type_int,     cb_int,                  &globals.max_channels                 },
                    { "Sound_volume",               json_type_int,     cb_sound_volume,         NULL                                  },
                    { "Joysticks",                  json_type_boolean, cb_bool,                 &globals.use_joysticks                },
                    { "CaveSelection",              json_type_string,  cb_cave_selection,       NULL                                  },
                    { "CaveSelectionLevel",         json_type_int,     cb_cave_selection_level, NULL                                  },
                    { "ShowFPS",                    json_type_boolean, cb_bool,                 &globals.fps_counter_active           },
                    { "GameMode",                   json_type_string,  cb_game_mode,            NULL                                  },
                    { "ActiveQuestline",            json_type_int,     cb_int,                  &active_questline                     },
                    { "TitleMidarea",               json_type_string,  cb_title_midarea,        NULL                                  },
                    { "IronGirlMode",               json_type_boolean, cb_bool,                 &globals.iron_girl_mode               },
                    { "Locale",                     json_type_string,  cb_locale,               NULL                                  },
                    { "MapTilting",                 json_type_boolean, cb_bool,                 &globals.map_tilting                  },
                    { "SmoothClassicMode",          json_type_boolean, cb_bool,                 &globals.smooth_classic_mode          },
                    { "Bindings",                   json_type_array,   cb_bindings,             NULL                                  },
                    { "Themes",                     json_type_array,   cb_themes,               NULL                                  },
                    { "WriteSettings",              json_type_boolean, cb_bool,                 &globals.write_settings               },
                    { "TestsCompleted",             json_type_boolean, cb_bool,                 &dummy_boolean                        }, // Ignored.
                    { NULL,                         json_type_int,     NULL,                    NULL                                  }
                  };
              
              int ind;

              ind = -1;
              for(int i = 0; ind == -1 && stuff[i].name != NULL; i++)
                if(!strcmp(stuff[i].name, name))
                  ind = i;

              if(ind >= 0)
                {
                  if(stuff[ind].type == type)
                    {
                      ok = stuff[ind].callback(value, stuff[ind].value_ptr);

                      /* Don't bind the default keybindings if we were able to read them from the settings.json. */
                      if(ok == true && !strcmp(name, "Bindings"))
                        bind_defaults = false;
                    }
                  else
                    {
                      fprintf(stderr, "%s: Incorrect value type %s for '%s', expected %s.\n", filename, json_type_to_name(type), name, json_type_to_name(stuff[ind].type));
                      ok = false;
                    }
                }
              else
                {
                  fprintf(stderr, "%s: Failed to parse: unknown variable '%s'.\n", filename, name);
                  ok = false;
                }

              json_object_iter_next(&it);
            }

          if(ok == true)
            globals.active_questline = active_questline;
          else
            rv = false;
        }
      else
        {
          fprintf(stderr, "%s: Failed to parse: %d: %s\n", filename, (int) e, json_tokener_error_desc(e));
        }
      free(json);
    }
  else
    {
      if(nonexistent_ok == false)
        fprintf(stderr, "%s: Failed to read '%s'.\n", __FUNCTION__, filename);
    }


  if(bind_defaults)
    ui_bindings_default(true);

  if(globals.iron_girl_mode)
    theme_set(THEME_TRAIT, "iron-girl");
  
  return rv;
}
Example #12
0
void SyslogInput_JSON( char *syslog_string, struct _SyslogInput *SyslogInput )
{

    struct json_object *json_obj = NULL;
    struct json_object *tmp = NULL;

    struct json_object_iterator it;
    struct json_object_iterator itEnd;

    const char *val_str = NULL;

    uint16_t json_str_count=1;
    uint16_t a;

    bool has_message = false;

    char json_str[JSON_MAX_NEST][JSON_MAX_SIZE] = { { 0 } };

    memset(SyslogInput, 0, sizeof(_SyslogInput));

    memcpy(SyslogInput->syslog_message, "UNDEFINED\0", sizeof(SyslogInput->syslog_message));
    memcpy(SyslogInput->syslog_program, "UNDEFINED\0", sizeof(SyslogInput->syslog_program));
    memcpy(SyslogInput->syslog_time, "UNDEFINED\0", sizeof(SyslogInput->syslog_time));
    memcpy(SyslogInput->syslog_date, "UNDEFINED\0", sizeof(SyslogInput->syslog_date));
    memcpy(SyslogInput->syslog_tag, "UNDEFINED\0", sizeof(SyslogInput->syslog_tag));
    memcpy(SyslogInput->syslog_level, "UNDEFINED\0", sizeof(SyslogInput->syslog_level));
    memcpy(SyslogInput->syslog_priority, "UNDEFINED\0", sizeof(SyslogInput->syslog_priority));
    memcpy(SyslogInput->syslog_facility, "UNDEFINED\0", sizeof(SyslogInput->syslog_facility));
    memcpy(SyslogInput->syslog_host, "UNDEFINED\0", sizeof(SyslogInput->syslog_host));

    /* If the json isn't nested,  we can do this the easy way */

    if ( Syslog_JSON_Map->is_nested == false )
        {

            json_obj = json_tokener_parse(syslog_string);

            if ( json_obj == NULL )
                {

                    if ( syslog_string != NULL )
                        {
                            Sagan_Log(WARN, "[%s, line %d] Libfastjson failed to decode JSON. Get: %s", __FILE__, __LINE__, syslog_string);
                        }
                    else
                        {
                            Sagan_Log(WARN, "[%s, line %d] Libfastjson failed to decode JSON. Got NULL data.", __FILE__, __LINE__);
                        }


                    json_object_put(json_obj);
                    __atomic_add_fetch(&counters->malformed_json_input_count, 1, __ATOMIC_SEQ_CST);
                    return;
                }


            __atomic_add_fetch(&counters->json_input_count, 1, __ATOMIC_SEQ_CST);

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_host, &tmp))
                {
                    strlcpy(SyslogInput->syslog_host, json_object_get_string(tmp), sizeof(SyslogInput->syslog_host));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_facility, &tmp))
                {
                    strlcpy(SyslogInput->syslog_facility, json_object_get_string(tmp), sizeof(SyslogInput->syslog_facility));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_priority, &tmp))
                {
                    strlcpy(SyslogInput->syslog_priority, json_object_get_string(tmp), sizeof(SyslogInput->syslog_priority));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_level, &tmp))
                {
                    strlcpy(SyslogInput->syslog_level, json_object_get_string(tmp), sizeof(SyslogInput->syslog_level));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_tag, &tmp))
                {
                    strlcpy(SyslogInput->syslog_tag, json_object_get_string(tmp), sizeof(SyslogInput->syslog_tag));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_date, &tmp))
                {
                    strlcpy(SyslogInput->syslog_date, json_object_get_string(tmp), sizeof(SyslogInput->syslog_date));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_time, &tmp))
                {
                    strlcpy(SyslogInput->syslog_time, json_object_get_string(tmp), sizeof(SyslogInput->syslog_time));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_program, &tmp))
                {
                    strlcpy(SyslogInput->syslog_program, json_object_get_string(tmp), sizeof(SyslogInput->syslog_program));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_message, &tmp))
                {
                    snprintf(SyslogInput->syslog_message, sizeof(SyslogInput->syslog_message)," %s", json_object_get_string(tmp));
                    SyslogInput->syslog_message[ (sizeof(SyslogInput->syslog_message) -1 ) ] = '\0';
                    has_message = true;
                }

        }
    else
        {

            /* The raw syslog is the first "nested" level".  Copy that */

            strlcpy(json_str[0], syslog_string, sizeof(json_str[0]));
            json_obj = json_tokener_parse(syslog_string);

            if ( json_obj == NULL )
                {

                    if ( debug->debugmalformed )
                        {
                            Sagan_Log(WARN, "[%s, line %d] Libfastjson failed to decode JSON input. The log line was: \"%s\"", __FILE__, __LINE__, syslog_string);
                        }

                    json_object_put(json_obj);
                    __atomic_add_fetch(&counters->malformed_json_input_count, 1, __ATOMIC_SEQ_CST);
                    return;
                }

            it = json_object_iter_begin(json_obj);
            itEnd = json_object_iter_end(json_obj);

            /* Search through all key/values looking for embedded JSON */

            while (!json_object_iter_equal(&it, &itEnd))
                {

                    struct json_object *const val = json_object_iter_peek_value(&it);
                    val_str = json_object_get_string(val);

                    if ( val_str[0] == '{' || val_str[1] == '{' )
                        {

                            /* If object looks like JSON, add it to array to be parsed later */

                            if ( json_str_count < JSON_MAX_NEST )
                                {
                                    strlcpy(json_str[json_str_count], val_str, sizeof(json_str[json_str_count]));
                                    json_str_count++;
                                }
                            else
                                {
                                    Sagan_Log(ERROR, "[%s, line %d] Detected JSON past max nest of %d! Skipping extra JSON.", __FILE__, __LINE__, JSON_MAX_NEST);
                                }
                        }

                    json_object_iter_next(&it);

                    /* Search through the nest to see if we can find out values */

                    for ( a = 0; a < json_str_count; a++ )
                        {

                            struct json_object *json_obj = NULL;
                            json_obj = json_tokener_parse(json_str[a]);

                            if ( json_obj == NULL )
                                {
                                    Sagan_Log(WARN, "[%s, line %d] Detected JSON nest but Libfastjson errors. The log line was: \"%s\"", __FILE__, __LINE__, json_str[a]);
                                    json_object_put(json_obj);
                                    __atomic_add_fetch(&counters->malformed_json_input_count, 1, __ATOMIC_SEQ_CST);
                                    return;
                                }

                            __atomic_add_fetch(&counters->json_input_count, 1, __ATOMIC_SEQ_CST);

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_message, &tmp))
                                {
                                    snprintf(SyslogInput->syslog_message, sizeof(SyslogInput->syslog_message)," %s", json_object_get_string(tmp));
                                    SyslogInput->syslog_message[ (sizeof(SyslogInput->syslog_message) -1 ) ] = '\0';
                                    has_message = true;
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_host, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_host, json_object_get_string(tmp), sizeof(SyslogInput->syslog_host));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_facility, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_facility, json_object_get_string(tmp), sizeof(SyslogInput->syslog_facility));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_priority, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_priority, json_object_get_string(tmp), sizeof(SyslogInput->syslog_priority));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_level, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_level, json_object_get_string(tmp), sizeof(SyslogInput->syslog_level));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_tag, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_tag, json_object_get_string(tmp), sizeof(SyslogInput->syslog_tag));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_date, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_date, json_object_get_string(tmp), sizeof(SyslogInput->syslog_date));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_time, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_time, json_object_get_string(tmp), sizeof(SyslogInput->syslog_time));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_program, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_program, json_object_get_string(tmp), sizeof(SyslogInput->syslog_program));
                                }

                        }

                }
        }


    if ( has_message == false )
        {
            Sagan_Log(WARN, "[%s, line %d] Received JSON which has no decoded 'message' value. The log line was: \"%s\"", __FILE__, __LINE__, syslog_string);
        }

    json_object_put(json_obj);
}
Example #13
0
/*
 * process an assertion using the hosted verifier.
 *
 * TODO: local verification
 */
VerifyResult processAssertion(request_rec *r, const char *verifier_url,
                              const char *assertion)
{
  VerifyResult res = apr_pcalloc(r->pool, sizeof(struct _VerifyResult));
  json_tokener *tok = json_tokener_new();
  json_object *jobj = NULL;
  enum json_tokener_error jerr;

  char *assertionResult =
    verifyAssertionRemote(r, verifier_url, (char *) assertion);

  if (assertionResult) {
    jobj =
      json_tokener_parse_ex(tok, assertionResult, strlen(assertionResult));
    jerr = json_tokener_get_error(tok);

    if (json_tokener_success != jerr) {

      res->errorResponse = apr_psprintf(r->pool, jsonErrorResponse,
                                        "malformed payload",
                                        json_tokener_error_desc(jerr));
      json_tokener_free(tok);
      return res;
    }

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r,
                  ERRTAG
                  "Assertion (parsed) recieved is : %s",
                  json_object_to_json_string(jobj));
  }
  else {
    // XXX: verifyAssertionRemote should return specific error message.
    res->errorResponse = apr_psprintf(r->pool, jsonErrorResponse,
                                      "communication error",
                                      "can't contact verification server");
    return res;
  }

  struct json_object_iterator it = json_object_iter_begin(jobj);
  struct json_object_iterator itEnd = json_object_iter_end(jobj);
  const char *reason = NULL;
  const char *status = "unknown";
  int success = 0;

  while (!json_object_iter_equal(&it, &itEnd)) {
    const char *key = json_object_iter_peek_name(&it);
    json_object *val = json_object_iter_peek_value(&it);

    if (strncmp("email", key, 6) == 0) {
      res->verifiedEmail = apr_pstrdup(r->pool, json_object_get_string(val));
    }
    else if (strncmp("issuer", key, 7) == 0) {
      res->identityIssuer = apr_pstrdup(r->pool, json_object_get_string(val));
    }
    else if (strncmp("audience", key, 9) == 0) {
      res->audience = apr_pstrdup(r->pool, json_object_get_string(val));
    }
    else if (strncmp("expires", key, 8) == 0) {
      apr_time_ansi_put(&res->expires, json_object_get_int64(val) / 1000);
    }
    else if (strncmp("reason", key, 7) == 0) {
      reason = json_object_get_string(val);
    }
    else if (strncmp("status", key, 7) == 0) {
      status = json_object_get_string(val);
      if (strncmp("okay", status, 5) == 0) {
        success = 1;
      }
    }
    json_object_iter_next(&it);
  }

  json_tokener_free(tok);

  // XXX: This is bad, doesn't catch multiple missing bits
  if (!res->verifiedEmail) {
    res->errorResponse = apr_pstrdup(r->pool, "Missing e-mail in assertion");
  }
  if (!res->identityIssuer) {
    res->errorResponse = apr_pstrdup(r->pool, "Missing issuer in assertion");
  }
  if (res->audience
      && strncmp(res->audience, r->server->server_hostname,
                 strlen(r->server->server_hostname)) != 0) {
    res->errorResponse =
      apr_psprintf(r->pool, "Audience %s doesn't match %s", res->audience,
                   r->server->server_hostname);
  }

  apr_time_t now = apr_time_now();
  if (res->expires && res->expires <= now) {
    char exp_time[APR_RFC822_DATE_LEN];
    apr_rfc822_date(exp_time, res->expires);
    res->errorResponse =
      apr_psprintf(r->pool, "Assertion expired on %s", exp_time);
  }

  if (!success) {
    if (reason) {
      res->errorResponse = apr_pstrdup(r->pool, reason);
    }
    else {
      res->errorResponse =
        apr_psprintf(r->pool, "Assertion failed with status '%s'", status);
    }
  }

  return res;
}
Example #14
0
static int ntop_zmq_receive(lua_State* vm) {
  NetworkInterface *ntop_interface;
  void *subscriber;
  int size;
  struct zmq_msg_hdr h;
  char *payload;
  int payload_len;
  zmq_pollitem_t item;
  int rc;

  lua_getglobal(vm, "zmq_subscriber");
  if((subscriber = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
    ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL subscriber");
    return(CONST_LUA_ERROR);
  }

  lua_getglobal(vm, "ntop_interface");
  if((ntop_interface = (NetworkInterface*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
    handle_null_interface(vm);
    return(CONST_LUA_ERROR);
    // ntop_interface = ntop->getInterfaceId(0);
  }

  item.socket = subscriber;
  item.events = ZMQ_POLLIN;
  do {
    rc = zmq_poll(&item, 1, 1000);
    if (rc < 0 || !ntop_interface->isRunning()) return(CONST_LUA_PARAM_ERROR);
  } while (rc == 0);

  size = zmq_recv(subscriber, &h, sizeof(h), 0);

  if(size != sizeof(h) || h.version != MSG_VERSION) {
    ntop->getTrace()->traceEvent(TRACE_WARNING, "Unsupported publisher version [%d]", h.version);
    return -1;
  }

  payload_len = h.size + 1;
  if((payload = (char*)malloc(payload_len)) != NULL) {
    size = zmq_recv(subscriber, payload, payload_len, 0);
    payload[h.size] = '\0';

    if(size > 0) {
      json_object *o = json_tokener_parse(payload);

      if(o != NULL) {
	struct json_object_iterator it = json_object_iter_begin(o);
	struct json_object_iterator itEnd = json_object_iter_end(o);

	while (!json_object_iter_equal(&it, &itEnd)) {
	  char *key   = (char*)json_object_iter_peek_name(&it);
	  const char *value = json_object_get_string(json_object_iter_peek_value(&it));

	  ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%s]=[%s]", key, value);

	  json_object_iter_next(&it);
	}

	json_object_put(o);
      }

      lua_pushfstring(vm, "%s", payload);
      ntop->getTrace()->traceEvent(TRACE_INFO, "[%u] %s", h.size, payload);
      free(payload);
      return(CONST_LUA_OK);
    } else {
      free(payload);
      return(CONST_LUA_PARAM_ERROR);
    }
  } else
    return(CONST_LUA_PARAM_ERROR);
}