Ejemplo n.º 1
0
LWGEOM*
lwgeom_from_geojson(const char *geojson, char **srs)
{
#ifndef HAVE_LIBJSON
	*srs = NULL;
	lwerror("You need JSON-C for lwgeom_from_geojson");
	return NULL;
#else /* HAVE_LIBJSON */

	/* size_t geojson_size = strlen(geojson); */

	LWGEOM *lwgeom;
	int hasz=LW_TRUE;
	json_tokener* jstok = NULL;
	json_object* poObj = NULL;
	json_object* poObjSrs = NULL;
	*srs = NULL;

	/* Begin to Parse json */
	jstok = json_tokener_new();
	poObj = json_tokener_parse_ex(jstok, geojson, -1);
	if( jstok->err != json_tokener_success)
	{
		char err[256];
		snprintf(err, 256, "%s (at offset %d)", json_tokener_error_desc(jstok->err), jstok->char_offset);
		json_tokener_free(jstok);
		json_object_put(poObj);
		geojson_lwerror(err, 1);
		return NULL;
	}
	json_tokener_free(jstok);

	poObjSrs = findMemberByName( poObj, "crs" );
	if (poObjSrs != NULL)
	{
		json_object* poObjSrsType = findMemberByName( poObjSrs, "type" );
		if (poObjSrsType != NULL)
		{
			json_object* poObjSrsProps = findMemberByName( poObjSrs, "properties" );
			if ( poObjSrsProps )
			{
				json_object* poNameURL = findMemberByName( poObjSrsProps, "name" );
				if ( poNameURL )
				{
					const char* pszName = json_object_get_string( poNameURL );
					if ( pszName )
					{
						*srs = lwalloc(strlen(pszName) + 1);
						strcpy(*srs, pszName);
					}
				}
			}
		}
	}

	lwgeom = parse_geojson(poObj, &hasz, 0);
	json_object_put(poObj);

	lwgeom_add_bbox(lwgeom);

	if (!hasz)
	{
		LWGEOM *tmp = lwgeom_force_2d(lwgeom);
		lwgeom_free(lwgeom);
		lwgeom = tmp;

		LWDEBUG(2, "geom_from_geojson called.");
	}

	return lwgeom;
#endif /* HAVE_LIBJSON } */
}
Ejemplo n.º 2
0
int main(int argc, char **argv)
{
	json_object *my_string, *my_int, *my_object, *my_array;
	int i;
#ifdef TEST_FORMATTED
	int sflags = 0;
#endif

	MC_SET_DEBUG(1);

#ifdef TEST_FORMATTED
	sflags = parse_flags(argc, argv);
#endif

	my_string = json_object_new_string("\t");
	printf("my_string=%s\n", json_object_get_string(my_string));
	printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));
	json_object_put(my_string);

	my_string = json_object_new_string("\\");
	printf("my_string=%s\n", json_object_get_string(my_string));
	printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));
	json_object_put(my_string);

	my_string = json_object_new_string("foo");
	printf("my_string=%s\n", json_object_get_string(my_string));
	printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));

	my_int = json_object_new_int(9);
	printf("my_int=%d\n", json_object_get_int(my_int));
	printf("my_int.to_string()=%s\n", json_object_to_json_string(my_int));

	my_array = json_object_new_array();
	json_object_array_add(my_array, json_object_new_int(1));
	json_object_array_add(my_array, json_object_new_int(2));
	json_object_array_add(my_array, json_object_new_int(3));
	json_object_array_put_idx(my_array, 4, json_object_new_int(5));
	printf("my_array=\n");
	for(i=0; i < json_object_array_length(my_array); i++)
	{
		json_object *obj = json_object_array_get_idx(my_array, i);
		printf("\t[%d]=%s\n", i, json_object_to_json_string(obj));
	}
	printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));    

	json_object_put(my_array);

	my_array = json_object_new_array();
	json_object_array_add(my_array, json_object_new_int(3));
	json_object_array_add(my_array, json_object_new_int(1));
	json_object_array_add(my_array, json_object_new_int(2));
	json_object_array_put_idx(my_array, 4, json_object_new_int(0));
	printf("my_array=\n");
	for(i=0; i < json_object_array_length(my_array); i++)
	{
		json_object *obj = json_object_array_get_idx(my_array, i);
		printf("\t[%d]=%s\n", i, json_object_to_json_string(obj));
	}
	printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));    
	json_object_array_sort(my_array, sort_fn);
	printf("my_array=\n");
	for(i=0; i < json_object_array_length(my_array); i++)
	{
		json_object *obj = json_object_array_get_idx(my_array, i);
		printf("\t[%d]=%s\n", i, json_object_to_json_string(obj));
	}
	printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));    

	my_object = json_object_new_object();
	json_object_object_add(my_object, "abc", json_object_new_int(12));
	json_object_object_add(my_object, "foo", json_object_new_string("bar"));
	json_object_object_add(my_object, "bool0", json_object_new_boolean(0));
	json_object_object_add(my_object, "bool1", json_object_new_boolean(1));
	json_object_object_add(my_object, "baz", json_object_new_string("bang"));

	json_object *baz_obj = json_object_new_string("fark");
	json_object_get(baz_obj);
	json_object_object_add(my_object, "baz", baz_obj);
	json_object_object_del(my_object, "baz");

	/* baz_obj should still be valid */
	printf("baz_obj.to_string()=%s\n", json_object_to_json_string(baz_obj));
	json_object_put(baz_obj);

	/*json_object_object_add(my_object, "arr", my_array);*/
	printf("my_object=\n");
	json_object_object_foreach(my_object, key, val)
	{
		printf("\t%s: %s\n", key, json_object_to_json_string(val));
	}
Ejemplo n.º 3
0
int monitor_machine (machine_t *machine)
{
    int rc = -1;
    char *url;

    /* create the machine url and init chunk */
    asprintf (&url, "%s%s", machine_detail_base_url, machine->uuid);
    chunk_t chunk;
    chunk.data = malloc (1);
    chunk.size = 0;

    /* fetch the new machine data */
    rc = fetch_curl (url, &chunk);
    if ((rc < 0) || (chunk.size == 0)) {
        printf ("fetching machine detail for machine %s failed\n", machine->uuid);
        return rc;
    }   

    /* fetch current and current alert */
    json_object *jdetail = json_tokener_parse (chunk.data);
    json_object *tmp = NULL;
    json_object_object_get_ex (jdetail, "current", &tmp);
    if (tmp == NULL) {
        printf ("ERROR: Could not get current for machine %s\n", machine->uuid);
        return rc;
    }
    machine->current_cur = json_object_get_double (tmp);
    json_object_object_get_ex (jdetail, "current_alert", &tmp);
    if (tmp == NULL) {
        printf ("ERROR: Could not get current_alert for machine %s\n", machine->uuid);
    }
    machine->current_threshold = json_object_get_double (tmp);
    //printf ("machine = %s, current = %f, current_alert = %f\n", machine->uuid, machine->current_cur, machine->current_threshold);

    /* Implementation with timestamp for each window entry */
    /* send alert if current is greater than threshold */
    int64_t timenow = epochtime ();
    if (machine->current_cur > machine->current_threshold) {
        int i = 0;
        double sum = 0, avg = 0;
        int count = 0;
        int head_dup = machine->head - 1;
        if (head_dup < 0) 
            head_dup = window_size - 1;
        
        while ((machine->current_avgwindow[head_dup].timestamp != 0) && (machine->current_avgwindow[head_dup].timestamp > timenow - seconds_history) && (head_dup != machine->head)) {
            sum += machine->current_avgwindow[head_dup].current;
            count++;
            head_dup -= 1;
            if (head_dup < 0) 
                head_dup = window_size - 1;
        }

        if (count > 0)
            avg = sum / count;
        else 
            avg = machine->current_avgwindow[head_dup].current;

        send_alert (machine, avg);
    }
    
    /* update the average window */
    machine->current_avgwindow[machine->head].current = machine->current_cur;
    machine->current_avgwindow[machine->head].timestamp = timenow;
    machine->head = (machine->head == window_size - 1) ? 0 : machine->head + 1; 

    /* update the period window */
    if (machine->phead == pwindow_size) {
        printf ("ERROR: phead on window_size. buffer needs clear up\n");
        return rc;
    }
    machine->current_periodwindow[machine->phead].current = machine->current_cur;
    machine->phead++;

    /* free memory */
    json_object_put (jdetail);
    free (chunk.data);
    
    rc = 0;
    return rc;
}
Ejemplo n.º 4
0
int main(int argc, char *argv[])
{
    struct md_exporter *mde;
    int32_t i;
    uint32_t packets = 0;
    uint8_t test_mode = 0, num_writers = 0, num_inputs = 0;
    const char *logfile_path = NULL;
    json_object *config = NULL;

    //Try to configure core before we set up the outputters
    if (configure_core(&mde))
        exit(EXIT_FAILURE);

    //Process core options, short options allowed. We do this here since we need
    //an allocated writers array
    opterr = 0;
    while ((i = getopt(argc, argv, "c:h")) != -1) {
        if (i == -1) {
            break;
        } else if (i == 'c') {
            read_config(optarg, &config);
        } else if (i == 'h') { 
            print_usage();
            exit(EXIT_SUCCESS);
        }
    }

    if (config == NULL) {
        META_PRINT_SYSLOG(mde, LOG_ERR, "Parameter -c is required to run.\n");
        exit(EXIT_FAILURE);
    }

    json_object_object_foreach(config, key, val) { 
        if (!strcmp(key, "netlink")) {
            mde->md_inputs[MD_INPUT_NETLINK] = calloc(sizeof(struct md_input_netlink),1);

            if (mde->md_inputs[MD_INPUT_NETLINK] == NULL) {
                META_PRINT_SYSLOG(mde, LOG_ERR, "Could not allocate Netlink input\n");
                exit(EXIT_FAILURE);
            }

            md_netlink_setup(mde, (struct md_input_netlink*) mde->md_inputs[MD_INPUT_NETLINK]);
            num_inputs++;
        }
#ifdef NSB_GPS
        else if (!strcmp(key, "nsb_gps")) {
            mde->md_inputs[MD_INPUT_GPS_NSB] = calloc(sizeof(struct md_input_gps_nsb), 1);

            if (mde->md_inputs[MD_INPUT_GPS_NSB] == NULL) {
                META_PRINT_SYSLOG(mde, LOG_ERR, "Could not allocate NSB GPS input\n");
                exit(EXIT_FAILURE);
            }

            md_gps_nsb_setup(mde, (struct md_input_gps_nsb*) mde->md_inputs[MD_INPUT_GPS_NSB]);
            num_inputs++;
        }
#endif
#ifdef NNE_SUPPORT
        else if (!strcmp(key, "nne")) {
            mde->md_writers[MD_WRITER_NNE] = calloc(sizeof(struct md_writer_nne), 1);

            if (mde->md_writers[MD_WRITER_NNE] == NULL) {
                META_PRINT_SYSLOG(mde, LOG_ERR, "Could not allocate NNE  writer\n");
                exit(EXIT_FAILURE);
            }

            md_nne_setup(mde, (struct md_writer_nne*) mde->md_writers[MD_WRITER_NNE]);
            num_writers++;
        }
#endif
#ifdef GPSD_SUPPORT
        else if (!strcmp(key, "gpsd")) {
            mde->md_inputs[MD_INPUT_GPSD] = calloc(sizeof(struct md_input_gpsd), 1);

            if (mde->md_inputs[MD_INPUT_GPSD] == NULL) {
                META_PRINT_SYSLOG(mde, LOG_ERR, "Could not allocate GPSD input\n");
                exit(EXIT_FAILURE);
            }

            md_gpsd_setup(mde, (struct md_input_gpsd*) mde->md_inputs[MD_INPUT_GPSD]);
            num_inputs++;
        }
#endif
#ifdef MUNIN_SUPPORT
        else if (!strcmp(key, "munin")) {
            mde->md_inputs[MD_INPUT_MUNIN] = calloc(sizeof(struct md_input_munin), 1);

            if (mde->md_inputs[MD_INPUT_MUNIN] == NULL) {
                META_PRINT_SYSLOG(mde, LOG_ERR, "Could not allocate Munin input\n");
                exit(EXIT_FAILURE);
            }

            md_munin_setup(mde, (struct md_input_munin*) mde->md_inputs[MD_INPUT_MUNIN]);
            num_inputs++;
        }
#endif
#ifdef SYSEVENT_SUPPORT
        else if (!strcmp(key, "sysevent")) {
            mde->md_inputs[MD_INPUT_SYSEVENT] = calloc(sizeof(struct md_input_sysevent), 1);

            if (mde->md_inputs[MD_INPUT_SYSEVENT] == NULL) {
                META_PRINT(mde->logfile, "Could not allocate Sysevent input\n");
                exit(EXIT_FAILURE);
            }

            md_sysevent_setup(mde, (struct md_input_sysevent*) mde->md_inputs[MD_INPUT_SYSEVENT]);
            num_inputs++;
        } 
#endif 
#ifdef SQLITE_SUPPORT
        else if (!strcmp(key, "sqlite")) {
            mde->md_writers[MD_WRITER_SQLITE] = calloc(sizeof(struct md_writer_sqlite), 1);

            if (mde->md_writers[MD_WRITER_SQLITE] == NULL) {
                META_PRINT_SYSLOG(mde, LOG_ERR, "Could not allocate SQLite writer\n");
                exit(EXIT_FAILURE);
            }

            md_sqlite_setup(mde, (struct md_writer_sqlite*) mde->md_writers[MD_WRITER_SQLITE]);
            num_writers++;
        }
#endif
#ifdef ZEROMQ_SUPPORT
        else if (!strcmp(key, "zmq")) {
            mde->md_writers[MD_WRITER_ZEROMQ] = calloc(sizeof(struct md_writer_zeromq), 1);

            if (mde->md_writers[MD_WRITER_ZEROMQ] == NULL) {
                META_PRINT_SYSLOG(mde, LOG_ERR, "Could not allocate SQLite writer\n");
                exit(EXIT_FAILURE);
            }

            md_zeromq_setup(mde, (struct md_writer_zeromq*) mde->md_writers[MD_WRITER_ZEROMQ]);
            num_writers++;
        }
#endif
        else if (!strcmp(key, "test")) {
            test_mode = 1;
        } 
        else if (!strcmp(key, "packets")) {
            packets = (uint32_t) json_object_get_int(val);
        } 
        else if (!strcmp(key, "logfile")) {
            logfile_path = json_object_get_string(val); 
        } 
        else if (!strcmp(key, "syslog")) {
            mde->use_syslog = json_object_get_int(val);
        }
    }

    if (num_writers == 0 || num_inputs == 0) {
        fprintf(stderr, "No input(s)/writer(s) specified\n");
        exit(EXIT_FAILURE);
    }

    if (logfile_path) {
        mde->logfile = fopen(logfile_path, "a");

        if (mde->logfile == NULL) {
            fprintf(stderr, "Could not open logfile: %s\n", logfile_path);
            exit(EXIT_FAILURE);
        }
    }

    for (i=0; i<=MD_INPUT_MAX; i++) {
        if (mde->md_inputs[i] != NULL) {
            META_PRINT_SYSLOG(mde, LOG_INFO, "Will configure input %d\n", i);
            //glic requires optind to be 0 for internal state to be reset when
            //using extensions
            optind = 0;
            if (mde->md_inputs[i]->init(mde->md_inputs[i], config))
                exit(EXIT_FAILURE);
        }
    }

    for (i=0; i<=MD_WRITER_MAX; i++) {
        if (mde->md_writers[i] != NULL) {
            META_PRINT_SYSLOG(mde, LOG_INFO, "Will configure writer %d\n", i);
            //glic requires optind to be 0 for internal state to be reset when
            //using extensions
            optind = 0;
            if (mde->md_writers[i]->init(mde->md_writers[i], config))
                exit(EXIT_FAILURE);
        }
    }

    json_object_put(config);

    if (test_mode)
        run_test_mode(mde, packets);
    else
        backend_event_loop_run(mde->event_loop);

    META_PRINT_SYSLOG(mde, LOG_ERR, "Threads should NEVER exit\n");
    exit(EXIT_FAILURE);
}
Ejemplo n.º 5
0
CJSONEntry::~CJSONEntry()
{
    if ( m_rootObject != 0 )
        json_object_put(m_rootObject);
}
Ejemplo n.º 6
0
/* Handle user message from cloud
 * Receive msg from cloud && do hardware operation
 */
void downstream_thread(void* arg)
{
    user_log_trace();
    OSStatus err = kUnknownErr;
    mico_Context_t *app_context = (mico_Context_t *)arg;
    fogcloud_msg_t *recv_msg = NULL;
    json_object *recv_json_object = NULL;
    
    require(app_context, exit);
    
    while(1) {
        mico_thread_sleep(1);
        if(!MicoFogCloudIsConnect(app_context)) {
            user_log("appStatus.fogcloudStatus.isCloudConnected = false");
            //mico_thread_sleep(1);
            continue;
        }
        
        // recv_msg->data = <topic><data>
        err = MicoFogCloudMsgRecv(app_context, &recv_msg, 1000);
        user_log("err = %d", err);
        if(kNoErr == err){
            user_log("Msg recv: topic[%d]=[%.*s]\tdata[%d]=[%.*s]", 
                    recv_msg->topic_len, recv_msg->topic_len, recv_msg->data, 
                    recv_msg->data_len, recv_msg->data_len, recv_msg->data + recv_msg->topic_len);
            
            recv_json_object = json_tokener_parse((const char*)recv_msg->data + recv_msg->topic_len);
            if(NULL != recv_json_object) {
                user_log("recv_json_object != NULL");
                
                // parse json object
                char *key; struct json_object *val; struct lh_entry *entry;

                for(entry = json_object_get_object(recv_json_object)->head; \
                        (entry ? (key = (char*)entry->k, val = (struct json_object*)entry->v, entry) : 0); \
                        entry = entry->next) {
                    if(!strcmp(key, "energy")){
                        SetEnergyValue(json_object_get_int(val));
                    }
                    else if(!strcmp(key, "interval")) {
                        SetIntervalValue(json_object_get_int(val));
                    }
                    else if(!strcmp(key, "lights")) {
                        SetLightsValue(json_object_get_int(val));
                    }
                    else if(!strcmp(key, "remind")) {
                        SetRemindValue(json_object_get_int(val));
                    }
                    else if(!strcmp(key, "volume")) {
                        SetVolumeValue(json_object_get_int(val));
                    }
                    else if(!strcmp(key, "subscribe")) {
                        subscribe = json_object_get_boolean(val);
                        user_log("subscribe = %d", (int)subscribe);
                    }
                    else if(!strcmp(key, "track")) {
                        //track = json_object_get_string(val);
                    }
                    else if(!strcmp(key, "url_path")) {
                        //url_path = json_object_get_string(val);
                    }
                }
            }
            
            // free memory of json object
            json_object_put(recv_json_object);
            recv_json_object = NULL;
        }
        
        // NOTE: must free msg memory after been used.
        if(NULL != recv_msg){
            free(recv_msg);
            recv_msg = NULL;
        }
    }
    
exit:
    if(kNoErr != err){
        user_log("ERROR: downstream_thread_handle thread exit with err=%d", err);
    }
    
    mico_rtos_delete_thread(NULL);  // delete current thread
}
Ejemplo n.º 7
0
static void test_modem_metadata(uint8_t *snd_buf, int32_t sock_fd,
        struct sockaddr *netlink_addr)
{
    struct json_object *parsed_obj = NULL;

    parsed_obj = json_tokener_parse(IFACE_REGISTER_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface register object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_UNREGISTER_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface unregister object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_CONNECT_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface connect object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_DISCONNECT_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface connect object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_MODE_CHANGED_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface mode changed object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_SUBMODE_CHANGED_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface submode changed object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_RSSI_CHANGED_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface rssi changed object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_LTE_RSSI_CHANGED_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface lte rssi changed object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_LTE_BAND_CHANGED_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface lte rssi changed object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_ISP_NAME_CHANGED_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface isp name changed object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_EXTERNAL_ADDR_CHANGED_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface addr changed object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_LOCATION_CHANGED_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface location changed object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_UPDATE_TEST);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface lte rssi changed object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

    parsed_obj = json_tokener_parse(IFACE_NETWORK_MCC_CHANGED);
    if (parsed_obj == NULL) {
        fprintf(stderr, "Failed to create iface lte rssi changed object\n");
    } else {
        send_netlink_json(snd_buf, parsed_obj, sock_fd, netlink_addr);
        json_object_put(parsed_obj);
    }

}
Ejemplo n.º 8
0
static int
process_response(u1db_sync_target *st, void *context, u1db_doc_gen_callback cb,
                 char *response, int *target_gen, char **target_trans_id)
{
    int status = U1DB_OK;
    int i, doc_count;
    json_object *json = NULL, *obj = NULL, *attr = NULL;
    const char *doc_id, *content, *rev;
    const char *tmp = NULL;
    int gen;
    const char *trans_id = NULL;
    u1db_document *doc;

    json = json_tokener_parse(response);
    if (json == NULL || !json_object_is_type(json, json_type_array)) {
        status = U1DB_BROKEN_SYNC_STREAM;
        goto finish;
    }
    doc_count = json_object_array_length(json);
    if (doc_count < 1) {
        // the first response is the new_generation info, so it must exist
        status = U1DB_BROKEN_SYNC_STREAM;
        goto finish;
    }
    obj = json_object_array_get_idx(json, 0);
    attr = json_object_object_get(obj, "new_generation");
    if (attr == NULL) {
        status = U1DB_BROKEN_SYNC_STREAM;
        goto finish;
    }
    *target_gen = json_object_get_int(attr);
    attr = json_object_object_get(obj, "new_transaction_id");
    if (attr == NULL) {
        status = U1DB_BROKEN_SYNC_STREAM;
        goto finish;
    }
    tmp = json_object_get_string(attr);
    if (tmp == NULL) {
        status = U1DB_BROKEN_SYNC_STREAM;
        goto finish;
    }
    *target_trans_id = strdup(tmp);
    if (*target_trans_id == NULL) {
        status = U1DB_NOMEM;
        goto finish;
    }

    for (i = 1; i < doc_count; ++i) {
        obj = json_object_array_get_idx(json, i);
        attr = json_object_object_get(obj, "id");
        doc_id = json_object_get_string(attr);
        attr = json_object_object_get(obj, "rev");
        rev = json_object_get_string(attr);
        attr = json_object_object_get(obj, "content");
        content = json_object_get_string(attr);
        attr = json_object_object_get(obj, "gen");
        gen = json_object_get_int(attr);
        attr = json_object_object_get(obj, "trans_id");
        trans_id = json_object_get_string(attr);
        status = u1db__allocate_document(doc_id, rev, content, 0, &doc);
        if (status != U1DB_OK)
            goto finish;
        if (doc == NULL) {
            status = U1DB_NOMEM;
            goto finish;
        }
        status = cb(context, doc, gen, trans_id);
        if (status != U1DB_OK) { goto finish; }
    }
finish:
    if (json != NULL) {
        json_object_put(json);
    }
    return status;
}
Ejemplo n.º 9
0
Archivo: json.c Proyecto: 01org/murphy
void mrp_json_unref(mrp_json_t *o)
{
    json_object_put(o);
}
Ejemplo n.º 10
0
static int
st_http_get_sync_info(u1db_sync_target *st,
        const char *source_replica_uid,
        const char **st_replica_uid, int *st_gen, int *source_gen,
        char **trans_id)
{
    struct _http_state *state;
    struct _http_request req = {0};
    char *url = NULL;
    const char *tmp = NULL;
    int status;
    long http_code;
    struct curl_slist *headers = NULL;

    json_object *json = NULL, *obj = NULL;

    if (st == NULL || source_replica_uid == NULL || st_replica_uid == NULL
            || st_gen == NULL || source_gen == NULL
            || st->implementation == NULL)
    {
        return U1DB_INVALID_PARAMETER;
    }
    status = impl_as_http_state(st->implementation, &state);
    if (status != U1DB_OK) {
        return status;
    }

    headers = curl_slist_append(NULL, "Content-Type: application/json");
    if (headers == NULL) {
        status = U1DB_NOMEM;
        goto finish;
    }
    req.state = state;
    status = u1db__format_sync_url(st, source_replica_uid, &url);
    if (status != U1DB_OK) { goto finish; }
    status = curl_easy_setopt(state->curl, CURLOPT_HTTPGET, 1L);
    if (status != CURLE_OK) { goto finish; }
    // status = curl_easy_setopt(state->curl, CURLOPT_USERAGENT, "...");
    status = curl_easy_setopt(state->curl, CURLOPT_URL, url);
    if (status != CURLE_OK) { goto finish; }
    req.body_buffer = req.header_buffer = NULL;
    status = simple_set_curl_data(state->curl, &req, &req, NULL);
    if (status != CURLE_OK) { goto finish; }
    status = maybe_sign_url(st, "GET", url, &headers);
    if (status != U1DB_OK) { goto finish; }
    status = curl_easy_setopt(state->curl, CURLOPT_HTTPHEADER, headers);
    if (status != CURLE_OK) { goto finish; }
    // Now do the GET
    status = curl_easy_perform(state->curl);
    if (status != CURLE_OK) { goto finish; }
    status = curl_easy_getinfo(state->curl, CURLINFO_RESPONSE_CODE, &http_code);
    if (status != CURLE_OK) { goto finish; }
    if (http_code != 200) { // 201 for created? shouldn't happen on GET
        status = http_code;
        goto finish;
    }
    if (req.body_buffer == NULL) {
        status = U1DB_INVALID_HTTP_RESPONSE;
        goto finish;
    }
    json = json_tokener_parse(req.body_buffer);
    if (json == NULL) {
        status = U1DB_NOMEM;
        goto finish;
    }
    obj = json_object_object_get(json, "target_replica_uid");
    if (obj == NULL) {
        status = U1DB_INVALID_HTTP_RESPONSE;
        goto finish;
    }
    if (state->replica_uid == NULL) {
        // we cache this on the state object, because the api for get_sync_info
        // asserts that callers do not have to free the returned string.
        // This isn't a functional problem, because if the sync target ever
        // changed its replica uid we'd be seriously broken anyway.
        state->replica_uid = strdup(json_object_get_string(obj));
    } else {
        if (strcmp(state->replica_uid, json_object_get_string(obj)) != 0) {
            // Our http target changed replica_uid, this would be a really
            // strange bug
            status = U1DB_INVALID_HTTP_RESPONSE;
            goto finish;
        }
    }
    *st_replica_uid = state->replica_uid;
    if (*st_replica_uid == NULL) {
        status = U1DB_NOMEM;
        goto finish;
    }
    obj = json_object_object_get(json, "target_replica_generation");
    if (obj == NULL) {
        status = U1DB_INVALID_HTTP_RESPONSE;
        goto finish;
    }
    *st_gen = json_object_get_int(obj);
    obj = json_object_object_get(json, "source_replica_generation");
    if (obj == NULL) {
        status = U1DB_INVALID_HTTP_RESPONSE;
        goto finish;
    }
    *source_gen = json_object_get_int(obj);
    obj = json_object_object_get(json, "source_transaction_id");
    if (obj == NULL) {
        *trans_id = NULL;
    } else {
        tmp = json_object_get_string(obj);
        if (tmp == NULL) {
            *trans_id = NULL;
        } else {
            *trans_id = strdup(tmp);
            if (*trans_id == NULL) {
                status = U1DB_NOMEM;
            }
        }
    }
finish:
    if (req.header_buffer != NULL) {
        free(req.header_buffer);
    }
    if (req.body_buffer != NULL) {
        free(req.body_buffer);
    }
    if (json != NULL) {
        json_object_put(json);
    }
    if (url != NULL) {
        free(url);
    }
    curl_slist_free_all(headers);
    return status;
}
Ejemplo n.º 11
0
static int
st_http_record_sync_info(u1db_sync_target *st,
        const char *source_replica_uid, int source_gen, const char *trans_id)
{
    struct _http_state *state;
    struct _http_request req = {0};
    char *url = NULL;
    int status;
    long http_code;
    json_object *json = NULL;
    const char *raw_body = NULL;
    int raw_len;
    struct curl_slist *headers = NULL;

    if (st == NULL || source_replica_uid == NULL || st->implementation == NULL)
    {
        return U1DB_INVALID_PARAMETER;
    }
    status = impl_as_http_state(st->implementation, &state);
    if (status != U1DB_OK) {
        return status;
    }

    status = u1db__format_sync_url(st, source_replica_uid, &url);
    if (status != U1DB_OK) { goto finish; }
    json = json_object_new_object();
    if (json == NULL) {
        status = U1DB_NOMEM;
        goto finish;
    }
    json_object_object_add(json, "generation", json_object_new_int(source_gen));
    json_object_object_add(json, "transaction_id",
                           json_object_new_string(trans_id));
    raw_body = json_object_to_json_string(json);
    raw_len = strlen(raw_body);
    req.state = state;
    req.put_buffer = raw_body;
    req.num_put_bytes = raw_len;

    headers = curl_slist_append(headers, "Content-Type: application/json");
    // We know the message is going to be short, no reason to wait for server
    // confirmation of the post.
    headers = curl_slist_append(headers, "Expect:");

    status = curl_easy_setopt(state->curl, CURLOPT_URL, url);
    if (status != CURLE_OK) { goto finish; }
    status = curl_easy_setopt(state->curl, CURLOPT_HTTPHEADER, headers);
    if (status != CURLE_OK) { goto finish; }
    status = curl_easy_setopt(state->curl, CURLOPT_UPLOAD, 1L);
    if (status != CURLE_OK) { goto finish; }
    status = curl_easy_setopt(state->curl, CURLOPT_PUT, 1L);
    if (status != CURLE_OK) { goto finish; }
    status = simple_set_curl_data(state->curl, &req, &req, &req);
    if (status != CURLE_OK) { goto finish; }
    status = curl_easy_setopt(state->curl, CURLOPT_INFILESIZE_LARGE,
                              (curl_off_t)req.num_put_bytes);
    if (status != CURLE_OK) { goto finish; }
    status = maybe_sign_url(st, "PUT", url, &headers);
    if (status != U1DB_OK) { goto finish; }

    // Now actually send the data
    status = curl_easy_perform(state->curl);
    if (status != CURLE_OK) { goto finish; }
    status = curl_easy_getinfo(state->curl, CURLINFO_RESPONSE_CODE, &http_code);
    if (status != CURLE_OK) { goto finish; }
    if (http_code != 200 && http_code != 201) {
        status = http_code;
        goto finish;
    }
finish:
    if (req.header_buffer != NULL) {
        free(req.header_buffer);
    }
    if (req.body_buffer != NULL) {
        free(req.body_buffer);
    }
    if (json != NULL) {
        json_object_put(json);
    }
    if (url != NULL) {
        free(url);
    }
    if (headers != NULL) {
        curl_slist_free_all(headers);
    }
    return status;
}
Ejemplo n.º 12
0
int main(int argc, char *argv[]) {
    const char *lengthStr = getenv("CONTENT_LENGTH"); 
    if (!lengthStr) {
        badRequestResponse("Request Invaild");
        return EXIT_SUCCESS;
    }

    const size_t length = atoi(lengthStr);
    char content[MAX_CONTENT];
    fgets(content, min(length + 1, MAX_CONTENT), stdin);
    
    json_object *json = json_tokener_parse(content);
    UCIContext *ctx = uci_alloc_context();
    if (!json) {
        badRequestResponse("Invaild JSON");
        goto fail;
    }

    json_object *value = NULL;
    json_bool ret = json_object_object_get_ex(json, "mode", &value);
    if (!ret) {
        badRequestResponse("Incomplete Arguments");
        goto fail;
    }
    const char *mode = json_object_get_string(value);
    if (!strcmp(mode, "static")) {
        ret = json_object_object_get_ex(json, "ip", &value);
        if (!ret) {
            badRequestResponse("Incomplete Arguments");
            goto fail;
        }
        const char *ip = json_object_get_string(value);
        if (!isVaildIP(ip)) {
            badRequestResponse("Invaild Argument: ip");
            goto fail;
        }

        ret = json_object_object_get_ex(json, "netmask", &value);
        if (!ret) {
            badRequestResponse("Incomplete Arguments");
            goto fail;
        }
        const char *netmask = json_object_get_string(value);
        if (!isVaildIP(netmask)) {
            badRequestResponse("Invaild Argument: netmask");
            goto fail;
        }

        ret = json_object_object_get_ex(json, "gateway", &value);
        if (!ret) {
            badRequestResponse("Incomplete Arguments");
            goto fail;
        }
        const char *gateway = json_object_get_string(value);
        if (!isVaildIP(gateway)) {
            badRequestResponse("Invaild Argument: gateway");
            goto fail;
        }

        ret = json_object_object_get_ex(json, "dnsA", &value);
        if (!ret) {
            badRequestResponse("Incomplete Arguments");
            goto fail;
        }
        const char *dnsA = json_object_get_string(value);
        if (!isVaildIP(dnsA)) {
            badRequestResponse("Invaild Argument: dnsA");
            goto fail;
        }

        ret = json_object_object_get_ex(json, "dnsB", &value);
        if (!ret) {
            badRequestResponse("Incomplete Arguments");
            goto fail;
        }
        const char *dnsB = json_object_get_string(value);
        if (!isVaildIP(dnsB)) {
            badRequestResponse("Invaild Argument: dnsB");
            goto fail;
        }

        const char *commands[] = { 
                                    "network.lan.proto", 
                                    "network.lan.ipaddr", 
                                    "network.lan.netmask", 
                                    "network.lan.gateway", 
                                    "network.lan.dns", 
                                    NULL
                                 };
        const char *values[] = { mode, ip, netmask, gateway, dnsA, NULL };
        if (statusSetter(ctx, commands, values) < 0 || uci(ctx, UCI_COMMIT, "network.lan")) goto fail;

    } else if (!strcmp(mode, "dhcp")) {
        const char *commands[] = { 
                                    "network.lan.proto", 
                                    NULL
                                 };
        const char *values[] = { mode, NULL };
        if (statusSetter(ctx, commands, values) < 0 || uci(ctx, UCI_COMMIT, "network.lan")) goto fail;

    } else if (!strcmp(mode, "pppoe")) {
        ret = json_object_object_get_ex(json, "username", &value);
        if (!ret) {
            badRequestResponse("Incomplete Arguments");
            goto fail;
        }
        const char *username = json_object_get_string(value);
        if (strlen(username) > MAX_CONTENT) {
            badRequestResponse("Invaild Argument: username");
            goto fail;
        }

        ret = json_object_object_get_ex(json, "password", &value);
        if (!ret) {
            badRequestResponse("Incomplete Arguments");
            goto fail;
        }
        const char *password = json_object_get_string(value);
        if (strlen(password) > MAX_CONTENT) {
            badRequestResponse("Invaild Argument: password");
            goto fail;
        }

        const char *commands[] = { 
                                    "network.lan.proto", 
                                    "network.wan.username", 
                                    "network.wan.password", 
                                    NULL
                                 };
        const char *values[] = { mode, username, password, NULL };
        if (statusSetter(ctx, commands, values) < 0 || uci(ctx, UCI_COMMIT, "network.wan")) goto fail;

    } else {
        badRequestResponse("Invaild Argument: mode");
        goto fail;
    }
    
    printf("Content-Type:application/json\n\n");
    fflush(stdout);

fail:
    uci_free_context(ctx);
    json_object_put(json);

    return EXIT_SUCCESS;
}
Ejemplo n.º 13
0
telebot_error_e telebot_get_user_profile_photos(telebot_handler_t handle,
        int user_id, int offset, int limit, telebot_user_profile_photos_t **photos)
{
    if (photos == NULL)
        return TELEBOT_ERROR_INVALID_PARAMETER;

    telebot_hdata_t * _handle = (telebot_hdata_t *)handle;
    if (_handle == NULL)
        return TELEBOT_ERROR_NOT_SUPPORTED;

    if ((limit <= 0) || (limit > TELEBOT_USER_PROFILE_PHOTOS_LIMIT))
        limit = TELEBOT_USER_PROFILE_PHOTOS_LIMIT;

    *photos = malloc(sizeof(telebot_user_profile_photos_t));
    if (*photos == NULL)
        return TELEBOT_ERROR_OUT_OF_MEMORY;

    telebot_error_e ret = telebot_core_get_user_profile_photos(_handle->core_h,
            user_id, offset, limit);
    if (ret != TELEBOT_ERROR_NONE) {
        tb_sfree(*photos);
        return ret;
    }

    struct json_object *obj = telebot_parser_str_to_obj(_handle->core_h->resp_data);
    tb_sfree_zcnt(_handle->core_h->resp_data, _handle->core_h->resp_size);

    if (obj == NULL) {
        tb_sfree(*photos);
        return TELEBOT_ERROR_OPERATION_FAILED;
    }

    struct json_object *ok;
    if (!json_object_object_get_ex(obj, "ok", &ok)) {
        json_object_put(obj);
        tb_sfree(*photos);
        return TELEBOT_ERROR_OPERATION_FAILED;
    }

    if (!json_object_get_boolean(ok)) {
        json_object_put(obj);
        tb_sfree(*photos);
        return TELEBOT_ERROR_OPERATION_FAILED;
    }

    struct json_object *result;
    if (!json_object_object_get_ex(obj, "result", &result)) {
        json_object_put(obj);
        tb_sfree(*photos);
        return TELEBOT_ERROR_OPERATION_FAILED;
    }

    ret = telebot_parser_get_user_profile_photos(result, *photos);
    json_object_put(obj);

    if (ret != TELEBOT_ERROR_NONE) {
        tb_sfree(*photos);
        return ret;
    }

    return TELEBOT_ERROR_NONE;
}
Ejemplo n.º 14
0
telebot_error_e telebot_get_updates(telebot_handler_t handle, int offset,
        int limit, int timeout, telebot_update_type_e allowed_updates[],
        int allowed_updates_count, telebot_update_t **updates, int *count)
{
    telebot_hdata_t *_handle = (telebot_hdata_t *)handle;
    if (_handle == NULL)
        return TELEBOT_ERROR_NOT_SUPPORTED;

    if ((updates == NULL) || (count == NULL))
        return TELEBOT_ERROR_INVALID_PARAMETER;

    *updates = NULL;
    *count = 0;

    int i = 0;
    char allowed_updates_str[1024] = "";
    if (allowed_updates_count > 0) {
        snprintf(allowed_updates_str, 1024, "%s", "[");
        for (i=0;i<allowed_updates_count;i++) {
            if (i < (allowed_updates_count-1)) //intermediate element
                snprintf(allowed_updates_str, 1024, "%s%s,", allowed_updates_str,
                        telebot_update_type_str[allowed_updates[i]]);
            else // last element
                snprintf(allowed_updates_str, 1024, "%s%s", allowed_updates_str,
                        telebot_update_type_str[allowed_updates[i]]);
        }
        snprintf(allowed_updates_str, 1024, "%s%s", allowed_updates_str,"]");
    }

    int _offset = offset != 0 ? offset : _handle->offset;
    int _timeout = timeout > 0 ? timeout : 0;
    int _limit = TELEBOT_UPDATE_COUNT_MAX_LIMIT;
    if ((limit > 0) && (limit < TELEBOT_UPDATE_COUNT_MAX_LIMIT))
        _limit = limit;

    int ret = telebot_core_get_updates(_handle->core_h, _offset,
            _limit, _timeout, allowed_updates_str);
    if (ret != TELEBOT_ERROR_NONE)
        return ret;

    struct json_object *obj = telebot_parser_str_to_obj(_handle->core_h->resp_data);
    tb_sfree_zcnt(_handle->core_h->resp_data, _handle->core_h->resp_size);

    if (obj == NULL)
        return TELEBOT_ERROR_OPERATION_FAILED;

    struct json_object *ok;
    if (!json_object_object_get_ex(obj, "ok", &ok)) {
        json_object_put(obj);
        return TELEBOT_ERROR_OPERATION_FAILED;
    }

    if (!json_object_get_boolean(ok)) {
        json_object_put(obj);
        return TELEBOT_ERROR_OPERATION_FAILED;
    }

    struct json_object *result;
    if (!json_object_object_get_ex(obj, "result", &result)) {
        json_object_put(obj);
        return TELEBOT_ERROR_OPERATION_FAILED;
    }

    ret = telebot_parser_get_updates(result, updates, count);
    json_object_put(obj);

    if (ret != TELEBOT_ERROR_NONE)
        return ret;

    int index, cnt = *count;
    telebot_update_t *ups = *updates;
    for (index = 0;index < cnt; index++) {
        if (ups[index].update_id >= _handle->offset)
            _handle->offset = ups[index].update_id + 1;
    }

    return TELEBOT_ERROR_NONE;
}
Ejemplo n.º 15
0
bool EASPolicyManager::importOldPolicySettings()
{
	json_object *root = 0, *prop = 0, *key = 0;
	root = json_object_from_file((char*)s_policyFile);
	if (!root || is_error(root))
		return false;


	prop = json_object_object_get(root, "version");
	if (!prop) {

		g_message("converting version 1 schema to version %d", s_version);

		// migrate version 1 schema
		EASPolicy* p = new EASPolicy;
		if(p->fromJSON(root))
		    m_aggregate->merge (p);
	}
	else if (json_object_get_int(prop) == 2) {

		// parse version 2 schema
		g_message("parsing version 2 schema");
		
		// parse all policies and create aggregate
		prop = json_object_object_get(root, "policies");
		if (prop && !is_error(prop) && json_object_is_type(prop, json_type_array)) {

			for (int i = 0; i < json_object_array_length(prop); i++) {

				EASPolicy* p = new EASPolicy;
				key = json_object_array_get_idx(prop, i);
				if (p->fromJSON(key))
				    m_aggregate->merge(p);
                                delete p;
			}
		}
	}
	else {
		g_critical("unrecognized EAS policy schema version %d", json_object_get_int(prop));
		return false;
	}
	
	// status
	prop = json_object_object_get(root, "status");
	if (prop && !is_error(prop)) {
		
		key = json_object_object_get(prop, "enforced");
		m_isEnforced = (key == 0 ? false : json_object_get_boolean(key));

		
		key = json_object_object_get(prop, "retriesLeft");
		if (key)
			m_retriesLeft = json_object_get_int(key);
		else if (m_aggregate)
			m_retriesLeft = m_aggregate->maxRetries();
	}
	else {
		m_isEnforced = false;
		if (m_aggregate)
			m_retriesLeft = m_aggregate->maxRetries();
	}
	
	// check the installed policies against the set of email accounts

    json_object_put(root);
	return true;
}
Ejemplo n.º 16
0
static int rsem_post_impl(struct rsem_client *rcli, const char *name)
{
	char err[512] = { 0 };
	size_t err_len = sizeof(err);
	int res, ret, zfd = -1;
	struct json_object *jo = NULL;
	struct sockaddr_in addr;
	uint32_t ty, resp;
	struct rsem_release rel;

	rel.name = (char*)name;
	jo = JORM_TOJSON_rsem_release(&rel);
	if (!jo) {
		ret = -ENOMEM;
		glitch_log("rsem_post_impl: out of memory\n");
		goto done;
	}
	zfd = do_socket(AF_INET, SOCK_STREAM, 0, WANT_O_CLOEXEC);
	if (zfd < 0) {
		ret = zfd;
		glitch_log("rsem_post_impl: socket error: %d\n", ret);
		goto done;
	}
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(get_first_ipv4_addr(rcli->srv_host,
				err, err_len));
	if (err[0]) {
		/* couldn't resolve hostname */
		ret = -EIO;
		goto done;
	}
	addr.sin_port = htons(rcli->srv_port);
	if (connect(zfd, &addr, sizeof(addr)) < 0) {
		ret = errno;
		glitch_log("rsem_post_impl: failed to connect to %s: "
			   "error %d\n", rcli->srv_host, ret);
		ret = -EIO;
		goto done;
	}
	ty = htonl(RSEM_CLIENT_REL_SEM);
	if (safe_write(zfd, &ty, sizeof(uint32_t))) {
		glitch_log("rsem_post_impl: short write of message type %d\n",
			   RSEM_CLIENT_REL_SEM);
		ret = -EIO;
		goto done;
	}
	if (blocking_write_json_req("rsem_post_impl", zfd, jo)) {
		ret = -EIO;
		goto done;
	}
	if (safe_read(zfd, &resp, sizeof(uint32_t)) != sizeof(uint32_t)) {
		glitch_log("rsem_post_impl: short read of response\n");
		ret = -EIO;
		goto done;
	}
	resp = ntohl(resp);
	if (resp == RSEM_SERVER_ACK) {
		ret = 0;
	}
	else {
		glitch_log("rsem_post_impl: got unexpected server "
			   "response %d\n", resp);
		ret = -EIO;
	}

done:
	if (jo)
		json_object_put(jo);
	if (zfd >= 0)
		RETRY_ON_EINTR(res, close(zfd));
	return ret;
}
Ejemplo n.º 17
0
bool EASPolicyManager::cbDevicePolicySaved (LSHandle *sh, LSMessage *message, void *data)
{
    const char* str = LSMessageGetPayload(message);
    json_object *root = 0, *label = 0, *policy = 0, *results = 0;
    bool returnValue = false;
    int rev = 0;
    std::string id;

    if (!str)
		goto error;

    g_debug ("%s: response %s", __func__, str);

    root = json_tokener_parse(str);
    if (!root || is_error(root))
		goto error;

    label = json_object_object_get (root, "returnValue");
    if (!label)  {
		g_warning ("No returnValue available");
		goto error;
    }

    returnValue = json_object_get_boolean (label);
    if (!returnValue) {
		g_warning ("returnValue is false, call failed");
		goto error;
    }

    results = json_object_object_get (root, "results");
    if (!results) {
		g_warning ("No results in device policy, call to store device policy failed");
		goto error;
    }

    if (json_object_array_length (results) != 1) {
		g_warning ("Device policy != 1, BUG! Using the 1st");
    }

    policy = json_object_array_get_idx(results, 0);
    if (!policy) {
		g_warning ("No policy in list, cannot update id");
		goto error;
    }

    label = json_object_object_get (policy, "id");
    if (!label)  {
		g_warning ("No id available");
		goto error;
    }

    id = json_object_get_string (label);
    if (id.empty()) {
		g_warning ("Invalid id");
		goto error;
    }

    label = json_object_object_get (policy, "rev");
    if (!label)  {
		g_warning ("No rev available");
		goto error;
    }
 
    rev = json_object_get_int (label);
    if (rev <= 0) {
		g_warning ("Invalid rev");
		goto error;
    }

    if (EASPolicyManager::instance()->m_aggregate->m_id != id) {
	    EASPolicyManager::instance()->m_aggregate->m_id = id;
	    g_debug ("%s: updated id to %s", __func__, id.c_str());
    }

    // do not update the watch rev after saving the device policy
    // otherwise the watch will miss upates that might have
    // occured between the last query of the security policies
    // and the saving of this device policy.
    // Note, this will cause the watch to always get triggered
    // once after saving a device policy, due to the updated 
    // revision of the device policy

error:
    EASPolicyManager::instance()->watchSecurityPolicies();

    if (root && !is_error(root))
		json_object_put (root);
    return true;
}
Ejemplo n.º 18
0
int rsem_wait(struct rsem_client *rcli, const char *name)
{
	char err[512] = { 0 };
	size_t err_len = sizeof(err);
	int ret, res, port, zfd = -1, zsock = -1;
	struct rsem_request req;
	struct json_object *jo;
	uint32_t ty, resp;
	struct sockaddr_in addr;

	port = wait_for_next_free_port(rcli);
	zsock = do_bind_and_listen(port, err, err_len);
	if (err[0]) {
		glitch_log("rsem_wait: do_bind_and_listen failed with "
			   "error '%s'\n", err);
		ret = -EIO;
		zsock = -1;
		goto done;
	}
	zfd = do_socket(AF_INET, SOCK_STREAM, 0, WANT_O_CLOEXEC);
	if (zfd < 0) {
		glitch_log("rsem_wait: socket error: %d\n", zfd);
		ret = EIO;
		goto done;
	}
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(get_first_ipv4_addr(rcli->srv_host,
						err, err_len));
	if (err[0]) {
		/* couldn't resolve hostname */
		ret = EIO;
		goto done;
	}
	addr.sin_port = htons(rcli->srv_port);
	if (connect(zfd, &addr, sizeof(addr)) < 0) {
		ret = errno;
		glitch_log("rsem_wait: failed to connect to %s: error %d\n",
			   rcli->srv_host, ret);
		goto done;
	}
	ty = htonl(RSEM_CLIENT_REQ_SEM);
	if (safe_write(zfd, &ty, sizeof(uint32_t))) {
		glitch_log("rsem_wait: short write of message type\n");
		ret = -EIO;
		goto done;
	}
	memset(&req, 0, sizeof(req));
	req.name = (char*)name;
	req.port = port;
	jo = JORM_TOJSON_rsem_request(&req);
	if (!jo) {
		ret = -ENOMEM;
		glitch_log("rsem_wait: out of memory\n");
		goto done;
	}
	if (blocking_write_json_req("rsem_wait", zfd, jo)) {
		ret = -EIO;
		json_object_put(jo);
		goto done;
	}
	json_object_put(jo);
	if (safe_read(zfd, &resp, sizeof(uint32_t)) != sizeof(uint32_t)) {
		glitch_log("rsem_wait: short read of response\n");
		ret = -EIO;
		goto done;
	}
	resp = ntohl(resp);
	RETRY_ON_EINTR(res, close(zfd));
	zfd = -1;
	if (resp == RSEM_SERVER_GIVE_SEM) {
		ret = 0;
	}
	else if (resp == RSEM_SERVER_DELAY_SEM) {
		ret = rsem_wait_for_callback(name, zsock);
	}
	else {
		glitch_log("rsem_wait: unexpected server reply %d\n",
				resp);
		ret = -EIO;
	}

done:
	if (zsock >= 0)
		RETRY_ON_EINTR(res, close(zsock));
	if (zfd >= 0)
		RETRY_ON_EINTR(res, close(zfd));
	release_port(rcli, port);
	return ret;
}
Ejemplo n.º 19
0
static struct json_object *create_fake_conn_obj(uint64_t l3_id, uint64_t l4_id,
        uint8_t event_param, char *event_value_str, uint64_t tstamp)
{
	struct json_object *obj = NULL, *obj_add = NULL;
    uint8_t rand_value = 0;
    uint64_t rand_value_64 = 0;
    struct timeval tv;

	if (!(obj = json_object_new_object()))
		return NULL;

    gettimeofday(&tv, NULL);
	if (!(obj_add = json_object_new_int64(tv.tv_sec))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "timestamp", obj_add);

    if (l3_id)
        rand_value_64 = l3_id;
    else
        rand_value_64 = (uint64_t) random();

    if (!(obj_add = json_object_new_int64(rand_value_64))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "l3_session_id", obj_add);

    if (l4_id)
        rand_value_64 = l4_id;
    else
        rand_value_64 = (uint64_t) random();

    if (!(obj_add = json_object_new_int64(rand_value_64))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "l4_session_id", obj_add);

    if (!(obj_add = json_object_new_int(META_TYPE_CONNECTION))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "event_type", obj_add);

    rand_value = (uint8_t) random();
    if (!(obj_add = json_object_new_int(rand_value))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "interface_type", obj_add);

    rand_value = (uint8_t) random();
    if (!(obj_add = json_object_new_int(rand_value))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "network_address_family", obj_add);

    if (!event_param)
        rand_value = (uint8_t) random();
    else
        rand_value = event_param;

    if (!(obj_add = json_object_new_int(rand_value))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "event_param", obj_add);

    if (event_value_str) {
        if (!(obj_add = json_object_new_string(event_value_str))) {
            json_object_put(obj);
            return NULL;
        }
        json_object_object_add(obj, "event_value_str", obj_add);
    } else {
        rand_value = (uint8_t) random();
        if (!(obj_add = json_object_new_int(rand_value))) {
            json_object_put(obj);
            return NULL;
        }
        json_object_object_add(obj, "event_value", obj_add);
    }

    rand_value = (uint8_t) random();
    if (!(obj_add = json_object_new_int(rand_value))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "interface_id_type", obj_add);

    if (!(obj_add = json_object_new_string("89470000140710276612"))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "interface_id", obj_add);

    
    if (!(obj_add = json_object_new_string("1234567"))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "imei", obj_add);

    if (!(obj_add = json_object_new_string("22222"))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "imsi", obj_add);

    if (!(obj_add = json_object_new_string("192.168.0.153/24"))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "network_address", obj_add);

    rand_value = (uint8_t) random();
    if (rand_value % 2) {
        obj_add = json_object_new_int(24201);

        if (!obj_add) {
            json_object_put(obj);
            return NULL;
        }

        json_object_object_add(obj, "network_provider", obj_add);
    }

    if (!(obj_add = json_object_new_int(-99))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "signal_strength", obj_add);

    if (!(obj_add = json_object_new_int(100))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "rx_bytes", obj_add);

    if (!(obj_add = json_object_new_int(100))) {
        json_object_put(obj);
        return NULL;
    }
    json_object_object_add(obj, "tx_bytes", obj_add);

	return obj;	
}
Ejemplo n.º 20
0
void CJsonDecoder::DestroyJsonDecoder()
{
	json_object_put((json_object *)m_root);
}
Ejemplo n.º 21
0
//Test function which just generates some netlink messages that are sent to our
//group
static void test_netlink(uint32_t packets)
{
    struct mnl_socket *mnl_sock = NULL;
    struct sockaddr_nl netlink_addr;
	uint8_t snd_buf[MNL_SOCKET_BUFFER_SIZE];
    struct nlmsghdr *netlink_hdr;
    uint32_t i = 0;
	struct json_object *obj_to_send = NULL;
    struct timeval tv;


    mnl_sock = nlhelper_create_socket(NETLINK_USERSOCK, 0);

    if (mnl_sock == NULL) {
        fprintf(stderr, "Could not create netlink socket used for testing\n");
        return;
    }

    memset(&netlink_addr, 0, sizeof(netlink_addr));
    memset(snd_buf, 0, sizeof(snd_buf));

    netlink_hdr = mnl_nlmsg_put_header(snd_buf);
    netlink_hdr->nlmsg_type = 1;

    netlink_addr.nl_family = AF_NETLINK;

    //A message is broadcasted (multicasted) to all members of the group, except
    //the one where portid equals nl_pid (if any). Then it is unicasted to the
    //socket where portid equals nl_pid (if any). See af_netlink.c and
    //netlink_unicast()/netlink_broadcast().
    //
    //When testing, there is no need to multicast. We can just send to the PID
    netlink_addr.nl_pid = getpid();
    
    srand(time(NULL));

    //TODO: Specify number of packets from command line
    while(1) {
        gettimeofday(&tv, NULL);

        if (i == 0)
            obj_to_send = create_fake_conn_obj(0, 0, CONN_EVENT_META_UPDATE, "1,2,1,", i+1);
        else
            obj_to_send = create_fake_conn_obj(0, 0, CONN_EVENT_META_UPDATE, "1,2,1,4", i+1);

        /*if (i < 4)
            obj_to_send = create_fake_conn_obj(1, 2, CONN_EVENT_L3_UP, "1,2,1", i+1);
        else
            obj_to_send = create_fake_conn_obj(1, 2, CONN_EVENT_DATA_USAGE_UPDATE, "1,2,1,4", tv.tv_sec);*/

        if (!obj_to_send)
            continue;

        send_netlink_json(snd_buf, obj_to_send, mnl_socket_get_fd(mnl_sock),
                (struct sockaddr*) &netlink_addr);
        json_object_put(obj_to_send);

#if 0
        obj_to_send = create_fake_gps_gga_obj();
        send_netlink_json(snd_buf, obj_to_send, mnl_socket_get_fd(mnl_sock),
                (struct sockaddr*) &netlink_addr);
        json_object_put(obj_to_send);

        obj_to_send = create_fake_gps_rmc_obj();
        send_netlink_json(snd_buf, obj_to_send, mnl_socket_get_fd(mnl_sock),
                (struct sockaddr*) &netlink_addr);
        json_object_put(obj_to_send);
        test_modem_metadata(snd_buf, mnl_socket_get_fd(mnl_sock),
                (struct sockaddr*) &netlink_addr);
#endif
        if (packets && (++i >= packets))
            break;

        usleep(1000000);
    }
}
Ejemplo n.º 22
0
static void
mtev_capabilities_tobuff_json(mtev_capsvc_closure_t *cl, eventer_func_t curr) {
    const char **mod_names;
    struct utsname utsn;
    char vbuff[128];
    mtev_hash_table *lc;
    mtev_hash_iter iter = MTEV_HASH_ITER_ZERO;
    int i, nmods;
    struct timeval now;
    struct dso_type *t;

    struct json_object *doc;
    struct json_object *svcs, *bi, *ri, *mods, *feat;

    /* fill out capabilities */

    /* Create an XML Document */
    doc = json_object_new_object();

    /* Fill in the document */
    mtev_build_version(vbuff, sizeof(vbuff));
    json_object_object_add(doc, "version", json_object_new_string(vbuff));

    /* Build info */
    bi = json_object_new_object();
    json_object_object_add(bi, "bitwidth", json_object_new_int(sizeof(void *)*8));
    json_object_object_add(bi, "sysname", json_object_new_string(UNAME_S));
    json_object_object_add(bi, "nodename", json_object_new_string(UNAME_N));
    json_object_object_add(bi, "release", json_object_new_string(UNAME_R));
    json_object_object_add(bi, "version", json_object_new_string(UNAME_V));
    json_object_object_add(bi, "machine", json_object_new_string(UNAME_M));
    json_object_object_add(doc, "unameBuild", bi);

    /* Run info */
    ri = json_object_new_object();
    json_object_object_add(ri, "bitwidth", json_object_new_int(sizeof(void *)*8));
    if(uname(&utsn) < 0) {
      json_object_object_add(ri, "error", json_object_new_string(strerror(errno)));
    } else {
      json_object_object_add(ri, "sysname", json_object_new_string(utsn.sysname));
      json_object_object_add(ri, "nodename", json_object_new_string(utsn.nodename));
      json_object_object_add(ri, "release", json_object_new_string(utsn.release));
      json_object_object_add(ri, "version", json_object_new_string(utsn.version));
      json_object_object_add(ri, "machine", json_object_new_string(utsn.machine));
    }
    json_object_object_add(doc, "unameRun", ri);

    /* features */
    feat = json_object_new_object();
    if(mtev_hash_size(&features)) {
      mtev_hash_iter iter2 = MTEV_HASH_ITER_ZERO;
      while(mtev_hash_adv(&features, &iter2)) {
        struct json_object *featnode;
        featnode = json_object_new_object();
        if(iter2.value.str) json_object_object_add(featnode, "version", json_object_new_string(iter2.value.str));
        json_object_object_add(feat, iter2.key.str, featnode);
      }
    }
    json_object_object_add(doc, "features", feat);

    /* time (poor man's time check) */
    mtev_gettimeofday(&now, NULL);
    snprintf(vbuff, sizeof(vbuff), "%llu%03d", (unsigned long long)now.tv_sec,
             (int)(now.tv_usec / 1000));
    json_object_object_add(doc, "current_time", json_object_new_string(vbuff));

    svcs = json_object_new_object();
    lc = mtev_listener_commands();
    while(mtev_hash_adv(lc, &iter)) {
      struct json_object *cnode, *cmds;
      char hexcode[11];
      const char *name;
      eventer_func_t *f = (eventer_func_t *)iter.key.ptr;
      mtev_hash_table *sc = (mtev_hash_table *)iter.value.ptr;
      mtev_hash_iter sc_iter = MTEV_HASH_ITER_ZERO;

      name = eventer_name_for_callback(*f);
      cnode = json_object_new_object();
      if(iter.klen == 8)
        snprintf(hexcode, sizeof(hexcode), "0x%0llx",
                 (unsigned long long int)(vpsized_uint)**f);
      else
        snprintf(hexcode, sizeof(hexcode), "0x%0x",
                 (unsigned int)(vpsized_uint)**f);
      json_object_object_add(svcs, hexcode, cnode);
      if(name) json_object_object_add(cnode, name, json_object_new_string(name));
      cmds = json_object_new_object();
      json_object_object_add(cnode, "commands", cmds);
      while(mtev_hash_adv(sc, &sc_iter)) {
        struct json_object *scnode;
        char *name_copy, *version = NULL;
        eventer_func_t *f = (eventer_func_t *)sc_iter.value.ptr;

        scnode = json_object_new_object();
        snprintf(hexcode, sizeof(hexcode), "0x%08x", *((u_int32_t *)sc_iter.key.ptr));
        name = eventer_name_for_callback(*f);
        name_copy = strdup(name ? name : "[[unknown]]");
        version = strchr(name_copy, '/');
        if(version) *version++ = '\0';

        json_object_object_add(scnode, "name", json_object_new_string(name_copy));
        if(version) json_object_object_add(scnode, "version", json_object_new_string(version));
        json_object_object_add(cmds, hexcode, scnode);
        free(name_copy);
      }
    }
    json_object_object_add(doc, "services", svcs);

    mods = json_object_new_object();

#define list_modules_json(func, name) do { \
    nmods = func(&mod_names); \
    for(i=0; i<nmods; i++) { \
      struct json_object *pnode; \
      pnode = json_object_new_object(); \
      json_object_object_add(pnode, "type", json_object_new_string(name)); \
      json_object_object_add(mods, mod_names[i], pnode); \
    } \
    if(mod_names) free(mod_names); \
} while(0)
    for(t = mtev_dso_get_types(); t; t = t->next)
      list_modules_json(t->list, t->name);
    json_object_object_add(doc, "modules", mods);

    /* Write it out to a buffer and copy it for writing */
    cl->buff = strdup(json_object_to_json_string(doc));
    cl->towrite = strlen(cl->buff);

    /* Clean up after ourselves */
    json_object_put(doc);
}
Ejemplo n.º 23
0
CJSONStructIterator::~CJSONStructIterator(void)
{
    if ( m_rootObject != 0 )
        json_object_put(m_rootObject);
}
Ejemplo n.º 24
0
int main(int argc, char **argv, char **envp)
{
    struct json_object *jso;
    HDF *node;
    bson *doc;
    NEOERR *err;
    
    mtc_init("hdftest");

    mtimer_start();
    for (int i = 0; i < NUM_TOTAL_TEST; i++) {
        hdf_init(&node);
        //err = mjson_string_to_hdf(node, bdatam);
        OUTPUT_NOK(err);
        if (VERBERSE) hdf_dump(node, NULL);
        hdf_destroy(&node);
    }
    mtimer_stop("json => hdf");
    mtc_foo("%d per second", (int)(NUM_TOTAL_TEST/(elapsed/1000000.0f)));

    mtimer_start();
    for (int i = 0; i < NUM_TOTAL_TEST; i++) {
        doc = mbson_new_from_string(bdatam, true);
        if (!doc) printf("bson error");
        if (VERBERSE) printf("%s\n", mbson_string(doc));
        bson_free(doc);
    }
    mtimer_stop("json => bson");
    mtc_foo("%d per second", (int)(NUM_TOTAL_TEST/(elapsed/1000000.0f)));


    

    hdf_init(&node);
    hdf_set_value(node, NULL, bdatam);
    //err = mjson_string_to_hdf(node, bdatam);
    OUTPUT_NOK(err);
    
    mtimer_start();
    for (int i = 0; i < NUM_TOTAL_TEST; i++) {
        err = mjson_import_from_hdf(node, &jso);
        OUTPUT_NOK(err);
        if (VERBERSE) printf("%s\n", json_object_to_json_string(jso));
        json_object_put(jso);
    }
    mtimer_stop("hdf => json");
    mtc_foo("%d per second", (int)(NUM_TOTAL_TEST/(elapsed/1000000.0f)));

    mtimer_start();
    for (int i = 0; i < NUM_TOTAL_TEST; i++) {
        err = mbson_import_from_hdf(node, &doc, true);
        OUTPUT_NOK(err);
        if (VERBERSE) printf("%s\n", mbson_string(doc));
        bson_free(doc);
    }
    mtimer_stop("hdf => bson");
    mtc_foo("%d per second", (int)(NUM_TOTAL_TEST/(elapsed/1000000.0f)));





    doc = mbson_new_from_string(bdatam, true);
    if (!doc) printf("bson error");

    mtimer_start();
    for (int i = 0; i < NUM_TOTAL_TEST; i++) {
        char *s = mbson_string(doc);
        if (!s) printf("bson->string error");
        if (VERBERSE) printf("%s\n", s);
        free(s);
    }
    mtimer_stop("bson => json");
    mtc_foo("%d per second", (int)(NUM_TOTAL_TEST/(elapsed/1000000.0f)));

    mtimer_start();
    for (int i = 0; i < NUM_TOTAL_TEST; i++) {
        hdf_init(&node);
        //err = mbson_export_to_hdf(node, doc, false, false);
        OUTPUT_NOK(err);
        if (VERBERSE) hdf_dump(node, NULL);
        hdf_destroy(&node);
    }
    mtimer_stop("bson => hdf");
    //mtc_foo("%d per second", (int)(NUM_TOTAL_TEST/(elapsed/1000000.0f)));
    bson_free(doc);

    return 0;
}
Ejemplo n.º 25
0
CJSONArrayIterator::~CJSONArrayIterator(void)
{
    if ( m_rootObject != 0 )
        json_object_put(m_rootObject);
}
Ejemplo n.º 26
0
/* 设置bus当前线路的信息,可以被更新
 * 此buff被更新: 1.当前线路改变
 */
PRIVATE int set_bus_config_bus_cur_line_info(){
	
	if(TEST_PRA_STR_NOT_VOLID(bus_num)){
		WEB_STRACE("param error");
		return RET_ERROR;
	}
	int ret_out = 0, ret_in=0, i = 0, ret;
	bus_line_info_t *info =NULL, *tmp_info = NULL, null_line;
	v_line_sta_info_t *out_all =NULL, *out_tmp =NULL,cond;
	v_line_sta_info_t *in_all =NULL, *in_tmp =NULL;
	int t_flag = 0;
	#define NOT_FOUND_LINE 	(1 << 0)
	#define NOT_FOUND_OUT	(1 << 1 )
	#define NOT_FOUND_IN	(1 << 2 )
	memset(&cond, 0, sizeof(&cond));
	
	WEB_STRACE("cur line name is %s\n", bus_num);
	//获取线路信息
	if( (ret = db_bus_line_info_findby_line_name(bus_num, &info, 1, SQL_SEARCH_EQUAL)) <=0 ){
		//使用模糊查询
		if( (ret = db_bus_line_info_findby_line_name(bus_num, &info, 1, SQL_SEARCH_FUZZY)) <=0 ){
			WEB_STRACE("db error return %d,please try use baidu",ret);
			//不再返回,而是单纯的保存线路和方向,用于后续直接使用百度数据
			//return RET_ERROR;
			t_flag |= NOT_FOUND_LINE;
			memset(&null_line, 0, sizeof(bus_line_info_t));
			info = &null_line;
		}
	}
	
	if(t_flag & NOT_FOUND_LINE){
		t_flag |= NOT_FOUND_OUT;
		t_flag |= NOT_FOUND_IN;
	}else{
		cond.id= info->id;
		cond.kind_id = KIND_OUTBOUND;
		cond.line_type_id = 0;
		//获取去程信息
		if( (ret_out = db_v_line_sta_info_findby_condition(&cond, &out_all, 1, SQL_SEARCH_EQUAL)) <=0 ){
			WEB_STRACE("db error return %d",ret);
			//return RET_ERROR;
			t_flag |= NOT_FOUND_OUT;
		}
		
		cond.id= info->id;
		cond.kind_id = KIND_INBOUND;
		cond.line_type_id = 0;
		//获取回程信息
		if( (ret_in = db_v_line_sta_info_findby_condition(&cond, &in_all, 1, SQL_SEARCH_EQUAL)) <=0 ){
			WEB_STRACE("db error return %d",ret);
			//return RET_ERROR;
			t_flag |= NOT_FOUND_IN;
		}
	}
	
	
	
	json_object *new_obj = NULL, *sta_obj = NULL;
	json_object *sta_out = NULL, *sta_in =NULL;
	json_object *tmp_sta=NULL, *tmp_sta2;
	
	sta_out = json_object_new_array();
	sta_in = json_object_new_array();
	new_obj = json_object_new_object();
	
	
	json_object_object_add(new_obj, "line_name", json_object_new_string(bus_num));
	json_object_object_add(new_obj, "cur_dec", json_object_new_int(bus_derection));

	json_object_object_add(new_obj, "line_type", json_object_new_string(info->line_type));
	json_object_object_add(new_obj, "line_out", json_object_new_string(info->out_sta));
	json_object_object_add(new_obj, "line_in", json_object_new_string(info->in_sta));
	json_object_object_add(new_obj, "line_out_time", json_object_new_string(info->outbound));
	json_object_object_add(new_obj, "line_in_time", json_object_new_string(info->inbound));
	json_object_object_add(new_obj, "line_ticket", json_object_new_string(info->ticket));
	json_object_object_add(new_obj, "line_bus_type", json_object_new_string(info->bus_type));
	json_object_object_add(new_obj, "out_sta", json_object_new_string(info->out_sta));
	json_object_object_add(new_obj, "in_sta", json_object_new_string(info->in_sta));
	json_object_object_add(new_obj, "line_company", json_object_new_string(info->company));
	if(info->line_type_id == KIND_LOOP){
		json_object_object_add(new_obj, "line_loop", json_object_new_boolean(TRUE));
	}else{
		json_object_object_add(new_obj, "line_loop", json_object_new_boolean(FALSE));
	}


	json_object_object_add(new_obj, "line_active", json_object_new_string(info->status));
	
	
#if 1
	if( !(t_flag & NOT_FOUND_IN ) ){
		
		for (in_tmp = in_all; ret_in > 0; ret_in --, in_tmp ++){
			tmp_sta2 = json_object_new_object();
			json_object_object_add(tmp_sta2, "id", json_object_new_int(in_tmp->seq));
			json_object_object_add(tmp_sta2, "name", json_object_new_string(in_tmp->sta_name));
			json_object_object_add(tmp_sta2, "lng", json_object_new_string(in_tmp->st_lng));
			json_object_object_add(tmp_sta2, "lat", json_object_new_string(in_tmp->st_lat));
			json_object_array_add(sta_in, tmp_sta2);
		}
	}
	json_object_object_add(new_obj, "line_in", sta_in);
#endif
	if( !(t_flag & NOT_FOUND_OUT ) ){
		for (out_tmp = out_all; ret_out > 0; ret_out --, out_tmp ++){
			tmp_sta = json_object_new_object();
			json_object_object_add(tmp_sta, "id", json_object_new_int(out_tmp->seq));
			json_object_object_add(tmp_sta, "name", json_object_new_string(out_tmp->sta_name));
			json_object_object_add(tmp_sta, "lng", json_object_new_string(out_tmp->st_lng));
			json_object_object_add(tmp_sta, "lat", json_object_new_string(out_tmp->st_lat));
			json_object_array_add(sta_out, tmp_sta);
		}
	}
	json_object_object_add(new_obj, "line_out", sta_out);

	
	WEB_STRACE(" %s\n",json_object_to_json_string(new_obj));
	snprintf(bus_cur_line_info, BUS_LINE_INFO_BUFF_SIZE, "[%s]",json_object_to_json_string(new_obj));
	
	
	ret = json_object_put(new_obj);
	if( !(t_flag & NOT_FOUND_LINE ) ){
		db_free(info);
	}
	if( !(t_flag & NOT_FOUND_OUT ) ){
		db_free(out_all);
	}
	if( !(t_flag & NOT_FOUND_IN ) ){
		db_free(in_all);
	}
	
	WEB_STRACE("ret:%d ,info NULL: %d, sta_in :%d, sta_out : %d, tmp_sta:%d\n", 
		ret,
		(new_obj == NULL)? 1:0,
		(sta_in == NULL) ?1:0,
		(sta_out == NULL) ?1:0,
		(tmp_sta == NULL) ?1:0);
	return RET_OK;
	
}
Ejemplo n.º 27
0
/* machines_init()
 * Initializes the machine and senor data by fetching from the URL
 */
int machines_init (machine_t machines[], sensor_t *sensor) 
{
    int i = 0;
    int rc = -1;
    json_object *mlist;
    int len = 0;

    /* init the chunk */
    chunk_t chunk;
    chunk.data = malloc (1);
    chunk.size = 0;
    
    /* Fetch the data */
    rc = fetch_curl (machine_list_url, &chunk);
    if ((rc < 0) || (chunk.size == 0)) {
        printf ("fetching machine list failed\n");
        return rc;
    }
    rc = -1;

    /* parse and create json */
    mlist = json_tokener_parse (chunk.data);
    len = json_object_array_length (mlist);
    if (len == 0) {
        printf ("FATAL ERROR: machine list is not an array\n");
        return rc;
    }

    window_size = (int)ceil((1/frequency)*seconds_history);
    pwindow_size = (int)ceil(PERIOD_SHORT*60*60 / frequency);
    printf ("Window size to be created = %d\n", (int)ceil((1/frequency)*seconds_history));
    
    /* iterate and store machine uuids */
    for (i = 0; i < len; i++) {
        const char *mstr = json_object_get_string (json_object_array_get_idx (mlist, i));
        strncpy (machines[i].uuid, &mstr[18], 36);
        machines[i].uuid[36] = '\0';
        machines[i].current_cur = 0;
        machines[i].current_threshold = 0;
        machines[i].current_avgwindow = (cw_t *) malloc (sizeof (cw_t) * window_size);
        memset (machines[i].current_avgwindow, 0, sizeof(cw_t) * window_size);
        machines[i].current_periodwindow = (cw_t *) malloc (sizeof (cw_t) * (pwindow_size + 1));
        memset (machines[i].current_periodwindow, 0, sizeof(cw_t) * pwindow_size);
        machines[i].head = 0;
        machines[i].phead = 0;
    }

    /* Fetch all the machine names/types */
    for (i = 0; i < NUM_TOTAL; i++) {
        rc = machine_single_init (&machines[i]);
        if (rc < 0) {
            printf ("ERROR: Could not init machine i: %d\n", i);
        }
    }
    
    /* Allocate memory for sensor data */
    sensor->pressure = (double *) malloc (sizeof (double) * (pwindow_size + 1));
    sensor->temperature = (double *) malloc (sizeof (double) * (pwindow_size + 1));
    sensor->humidity = (double *) malloc (sizeof (double) * (pwindow_size + 1));

    /* free memory */
    json_object_put (mlist);    
    free (chunk.data);

    printf ("Initiation Complete\n");

    rc = 0;
    return rc;
}
Ejemplo n.º 28
0
json_object *Normalize_Liblognorm(char *syslog_msg, struct _SaganNormalizeLiblognorm *SaganNormalizeLiblognorm)
{

    char buf[10*1024] = { 0 };
    char tmp_host[254] = { 0 };

    int rc_normalize = 0;

    const char *cstr = NULL;
    const char *tmp = NULL;

    struct json_object *json = NULL;

    json_object *string_obj;

    SaganNormalizeLiblognorm->ip_src[0] = '0';
    SaganNormalizeLiblognorm->ip_src[1] = '\0';
    SaganNormalizeLiblognorm->ip_dst[0] = '0';
    SaganNormalizeLiblognorm->ip_dst[1] = '\0';

    SaganNormalizeLiblognorm->username[0] = '\0';
    SaganNormalizeLiblognorm->src_host[0] = '\0';
    SaganNormalizeLiblognorm->dst_host[0] = '\0';

    SaganNormalizeLiblognorm->hash_sha1[0] = '\0';
    SaganNormalizeLiblognorm->hash_sha256[0] = '\0';
    SaganNormalizeLiblognorm->hash_md5[0] = '\0';

    SaganNormalizeLiblognorm->http_uri[0] = '\0';
    SaganNormalizeLiblognorm->http_hostname[0] = '\0';

    SaganNormalizeLiblognorm->src_port = 0;
    SaganNormalizeLiblognorm->dst_port = 0;

    snprintf(buf, sizeof(buf),"%s", syslog_msg);

    /* int ln_normalize(ln_ctx ctx, const char *str, size_t strLen, struct json_object **json_p); */

    rc_normalize = ln_normalize(ctx, buf, strlen(buf), &json);
    if (json == NULL)
        {
            return NULL;
        }

    cstr = (char*)json_object_to_json_string(json);

    /* Get source address information */

    json_object_object_get_ex(json, "src-ip", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL)
        {
            snprintf(SaganNormalizeLiblognorm->ip_src, sizeof(SaganNormalizeLiblognorm->ip_src), "%s", tmp);
        }

    json_object_object_get_ex(json, "dst-ip", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            snprintf(SaganNormalizeLiblognorm->ip_dst, sizeof(SaganNormalizeLiblognorm->ip_dst), "%s", tmp);
        }

    /* Get username information - Will be used in the future */

    json_object_object_get_ex(json, "username", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            snprintf(SaganNormalizeLiblognorm->username, sizeof(SaganNormalizeLiblognorm->username), "%s", tmp);
        }


    /* Do DNS lookup for source hostname */

    json_object_object_get_ex(json, "src-host", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            strlcpy(SaganNormalizeLiblognorm->src_host, tmp, sizeof(SaganNormalizeLiblognorm->src_host));

            if ( SaganNormalizeLiblognorm->ip_src[0] == '0' && config->syslog_src_lookup)
                {

                    if (!DNS_Lookup(SaganNormalizeLiblognorm->src_host, tmp_host, sizeof(tmp_host)))
                        {
                            strlcpy(SaganNormalizeLiblognorm->ip_src, tmp_host, sizeof(SaganNormalizeLiblognorm->ip_src));
                        }

                }

        }

    json_object_object_get_ex(json, "dst-host", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            strlcpy(SaganNormalizeLiblognorm->dst_host, tmp, sizeof(SaganNormalizeLiblognorm->dst_host));

            if ( SaganNormalizeLiblognorm->ip_dst[0] == '0' && config->syslog_src_lookup)
                {

                    if (!DNS_Lookup(SaganNormalizeLiblognorm->dst_host, tmp_host, sizeof(tmp_host)))
                        {
                            strlcpy(SaganNormalizeLiblognorm->ip_dst, tmp_host, sizeof(SaganNormalizeLiblognorm->ip_dst));
                        }
                }
        }

    /* Get port information */

    json_object_object_get_ex(json, "src-port", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            SaganNormalizeLiblognorm->src_port = atoi(tmp);
        }

    json_object_object_get_ex(json, "dst-port", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            SaganNormalizeLiblognorm->dst_port = atoi(tmp);
        }


    json_object_object_get_ex(json, "hash-md5", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            strlcpy(SaganNormalizeLiblognorm->hash_md5, tmp, sizeof(SaganNormalizeLiblognorm->hash_md5));
        }


    json_object_object_get_ex(json, "hash-sha1", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            strlcpy(SaganNormalizeLiblognorm->hash_sha1, tmp, sizeof(SaganNormalizeLiblognorm->hash_sha1));
        }

    json_object_object_get_ex(json, "hash-sha256", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            strlcpy(SaganNormalizeLiblognorm->hash_sha256, tmp, sizeof(SaganNormalizeLiblognorm->hash_sha256));
        }


    json_object_object_get_ex(json, "http_uri", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            strlcpy(SaganNormalizeLiblognorm->http_uri, tmp, sizeof(SaganNormalizeLiblognorm->http_uri));
        }

    json_object_object_get_ex(json, "http_hostname", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            strlcpy(SaganNormalizeLiblognorm->http_hostname, tmp, sizeof(SaganNormalizeLiblognorm->http_hostname));
        }

    json_object_object_get_ex(json, "filename", &string_obj);
    tmp = json_object_get_string(string_obj);

    if ( tmp != NULL )
        {
            strlcpy(SaganNormalizeLiblognorm->filename, tmp, sizeof(SaganNormalizeLiblognorm->filename));
        }

    if ( debug->debugnormalize )
        {
            Sagan_Log(DEBUG, "Liblognorm DEBUG output: %d", rc_normalize);
            Sagan_Log(DEBUG, "---------------------------------------------------");
            Sagan_Log(DEBUG, "Log message to normalize: |%s|", syslog_msg);
            Sagan_Log(DEBUG, "Parsed: %s", cstr);
            Sagan_Log(DEBUG, "Source IP: %s", SaganNormalizeLiblognorm->ip_src);
            Sagan_Log(DEBUG, "Destination IP: %s", SaganNormalizeLiblognorm->ip_dst);
            Sagan_Log(DEBUG, "Source Port: %d", SaganNormalizeLiblognorm->src_port);
            Sagan_Log(DEBUG, "Destination Port: %d", SaganNormalizeLiblognorm->dst_port);
            Sagan_Log(DEBUG, "Source Host: %s", SaganNormalizeLiblognorm->src_host);
            Sagan_Log(DEBUG, "Destination Host: %s", SaganNormalizeLiblognorm->dst_host);
            Sagan_Log(DEBUG, "Username: %s", SaganNormalizeLiblognorm->username);
            Sagan_Log(DEBUG, "MD5 Hash: %s", SaganNormalizeLiblognorm->hash_md5);
            Sagan_Log(DEBUG, "SHA1 Hash: %s", SaganNormalizeLiblognorm->hash_sha1);
            Sagan_Log(DEBUG, "SHA265 Hash: %s", SaganNormalizeLiblognorm->hash_sha256);
            Sagan_Log(DEBUG, "HTTP URI: %s", SaganNormalizeLiblognorm->http_uri);
            Sagan_Log(DEBUG, "HTTP HOSTNAME: %s", SaganNormalizeLiblognorm->http_hostname);
            Sagan_Log(DEBUG, "Filename: %s", SaganNormalizeLiblognorm->filename);

            Sagan_Log(DEBUG, "");
        }


    if (0 != rc_normalize && json)
        {
            json_object_put(json);
            json = NULL;
        }
    return json;
}
Ejemplo n.º 29
0
static void test_incremental_parse()
{
	json_object *new_obj;
	enum json_tokener_error jerr;
	json_tokener *tok;
	const char *string_to_parse;
	int ii;
	int num_ok, num_error;

	num_ok = 0;
	num_error = 0;

	printf("Starting incremental tests.\n");
	printf("Note: quotes and backslashes seen in the output here are literal values passed\n");
	printf("     to the parse functions.  e.g. this is 4 characters: \"\\f\"\n");

	string_to_parse = "{ \"foo"; /* } */
	printf("json_tokener_parse(%s) ... ", string_to_parse);
	new_obj = json_tokener_parse(string_to_parse);
	if (new_obj == NULL) printf("got error as expected\n");

	/* test incremental parsing in various forms */
	tok = json_tokener_new();
	for (ii = 0; incremental_steps[ii].string_to_parse != NULL; ii++)
	{
		int this_step_ok = 0;
		struct incremental_step *step = &incremental_steps[ii];
		int length = step->length;
		int expected_char_offset = step->char_offset;

		if (step->reset_tokener & 2)
			json_tokener_set_flags(tok, JSON_TOKENER_STRICT);
		else
			json_tokener_set_flags(tok, 0);

		if (length == -1)
			length = strlen(step->string_to_parse);
		if (expected_char_offset == -1)
			expected_char_offset = length;

		printf("json_tokener_parse_ex(tok, %-12s, %3d) ... ",
			step->string_to_parse, length);
		new_obj = json_tokener_parse_ex(tok, step->string_to_parse, length);

		jerr = json_tokener_get_error(tok);
		if (step->expected_error != json_tokener_success)
		{
			if (new_obj != NULL)
				printf("ERROR: invalid object returned: %s\n",
					json_object_to_json_string(new_obj));
			else if (jerr != step->expected_error)
				printf("ERROR: got wrong error: %s\n",
					json_tokener_error_desc(jerr));
			else if (tok->char_offset != expected_char_offset)
				printf("ERROR: wrong char_offset %d != expected %d\n",
					tok->char_offset,
					expected_char_offset);
			else
			{
				printf("OK: got correct error: %s\n", json_tokener_error_desc(jerr));
				this_step_ok = 1;
			}
		}
		else
		{
			if (new_obj == NULL)
				printf("ERROR: expected valid object, instead: %s\n",
					json_tokener_error_desc(jerr));
			else if (tok->char_offset != expected_char_offset)
				printf("ERROR: wrong char_offset %d != expected %d\n",
					tok->char_offset,
					expected_char_offset);
			else
			{
				printf("OK: got object of type [%s]: %s\n",
					json_type_to_name(json_object_get_type(new_obj)),
					json_object_to_json_string(new_obj));
				this_step_ok = 1;
			}
		}

		if (new_obj)
			json_object_put(new_obj);

		if (step->reset_tokener & 1)
			json_tokener_reset(tok);

		if (this_step_ok)
			num_ok++;
		else
			num_error++;
	}

	json_tokener_free(tok);

	printf("End Incremental Tests OK=%d ERROR=%d\n", num_ok, num_error);

	return;
}
Ejemplo n.º 30
0
void json_metadata(FILE *file)
{
	char send_start_time[STRTIME_LEN+1];
	assert(dstrftime(send_start_time, STRTIME_LEN, "%Y-%m-%dT%H:%M:%S%z", zsend.start));
	char send_end_time[STRTIME_LEN+1];
	assert(dstrftime(send_end_time, STRTIME_LEN, "%Y-%m-%dT%H:%M:%S%z", zsend.finish));
	char recv_start_time[STRTIME_LEN+1];
	assert(dstrftime(recv_start_time, STRTIME_LEN, "%Y-%m-%dT%H:%M:%S%z", zrecv.start));
	char recv_end_time[STRTIME_LEN+1];
	assert(dstrftime(recv_end_time, STRTIME_LEN, "%Y-%m-%dT%H:%M:%S%z", zrecv.finish));
	double hitrate = ((double) 100 * zrecv.success_unique)/((double)zsend.sent);

	json_object *obj = json_object_new_object();

	// scanner host name
	char hostname[1024];
	if (gethostname(hostname, 1023) < 0) {
		log_error("json_metadata", "unable to retrieve local hostname");
	} else {
		hostname[1023] = '\0';
		json_object_object_add(obj, "local_hostname",
                json_object_new_string(hostname));
		struct hostent* h = gethostbyname(hostname);
		if (h) {
			json_object_object_add(obj, "full_hostname",
                    json_object_new_string(h->h_name));
		} else {
			log_error("json_metadata", "unable to retrieve complete hostname");
		}
	}

	json_object_object_add(obj, "target_port",
			json_object_new_int(zconf.target_port));
	json_object_object_add(obj, "source_port_first",
			json_object_new_int(zconf.source_port_first));
	json_object_object_add(obj, "source_port_last",
			json_object_new_int(zconf.source_port_last));
	json_object_object_add(obj, "max_targets",
            json_object_new_int(zconf.max_targets));
	json_object_object_add(obj, "max_runtime",
            json_object_new_int(zconf.max_runtime));
	json_object_object_add(obj, "max_results",
            json_object_new_int(zconf.max_results));
	if (zconf.iface) {
		json_object_object_add(obj, "iface",
                json_object_new_string(zconf.iface));
	}
	json_object_object_add(obj, "rate",
            json_object_new_int(zconf.rate));
	json_object_object_add(obj, "bandwidth",
            json_object_new_int(zconf.bandwidth));
	json_object_object_add(obj, "cooldown_secs",
            json_object_new_int(zconf.cooldown_secs));
	json_object_object_add(obj, "senders",
            json_object_new_int(zconf.senders));
	json_object_object_add(obj, "use_seed",
            json_object_new_int(zconf.use_seed));
	json_object_object_add(obj, "seed",
            json_object_new_int64(zconf.seed));
	json_object_object_add(obj, "generator",
            json_object_new_int64(zconf.generator));
	json_object_object_add(obj, "hitrate",
            json_object_new_double(hitrate));
	json_object_object_add(obj, "shard_num",
            json_object_new_int(zconf.shard_num));
	json_object_object_add(obj, "total_shards",
            json_object_new_int(zconf.total_shards));

	json_object_object_add(obj, "min_hitrate",
            json_object_new_double(zconf.min_hitrate));
	json_object_object_add(obj, "max_sendto_failures",
            json_object_new_int(zconf.max_sendto_failures));


	json_object_object_add(obj, "syslog",
            json_object_new_int(zconf.syslog));
	json_object_object_add(obj, "filter_duplicates",
            json_object_new_int(zconf.filter_duplicates));
	json_object_object_add(obj, "filter_unsuccessful",
            json_object_new_int(zconf.filter_unsuccessful));

	json_object_object_add(obj, "pcap_recv",
            json_object_new_int(zrecv.pcap_recv));
	json_object_object_add(obj, "pcap_drop",
            json_object_new_int(zrecv.pcap_drop));
	json_object_object_add(obj, "pcap_ifdrop",
            json_object_new_int(zrecv.pcap_ifdrop));

	json_object_object_add(obj, "blacklist_total_allowed",
		json_object_new_int64(zconf.total_allowed));
	json_object_object_add(obj, "blacklist_total_not_allowed",
		json_object_new_int64(zconf.total_disallowed));
//	json_object_object_add(obj, "blacklisted",
//            json_object_new_int64(zsend.blacklisted));
//	json_object_object_add(obj, "whitelisted",
//            json_object_new_int64(zsend.whitelisted));
	json_object_object_add(obj, "first_scanned",
            json_object_new_int64(zsend.first_scanned));
	json_object_object_add(obj, "send_to_failures",
            json_object_new_int64(zsend.sendto_failures));
	json_object_object_add(obj, "total_sent",
            json_object_new_int64(zsend.sent));

	json_object_object_add(obj, "success_total",
            json_object_new_int64(zrecv.success_total));
	json_object_object_add(obj, "success_unique",
            json_object_new_int64(zrecv.success_unique));
	if (zconf.fsconf.app_success_index >= 0) {
		json_object_object_add(obj, "app_success_total",
                json_object_new_int64(zrecv.app_success_total));
		json_object_object_add(obj, "app_success_unique",
                json_object_new_int64(zrecv.app_success_unique));
	}
	json_object_object_add(obj, "success_cooldown_total",
            json_object_new_int64(zrecv.cooldown_total));
	json_object_object_add(obj, "success_cooldown_unique",
            json_object_new_int64(zrecv.cooldown_unique));
	json_object_object_add(obj, "failure_total",
            json_object_new_int64(zrecv.failure_total));

	json_object_object_add(obj, "packet_streams",
			json_object_new_int(zconf.packet_streams));
	json_object_object_add(obj, "probe_module",
			json_object_new_string(((probe_module_t *)zconf.probe_module)->name));
	json_object_object_add(obj, "output_module",
			json_object_new_string(((output_module_t *)zconf.output_module)->name));

	json_object_object_add(obj, "send_start_time",
			json_object_new_string(send_start_time));
	json_object_object_add(obj, "send_end_time",
			json_object_new_string(send_end_time));
	json_object_object_add(obj, "recv_start_time",
			json_object_new_string(recv_start_time));
	json_object_object_add(obj, "recv_end_time",
			json_object_new_string(recv_end_time));

	if (zconf.output_filter_str) {
		json_object_object_add(obj, "output_filter",
				json_object_new_string(zconf.output_filter_str));
	}
	if (zconf.log_file) {
		json_object_object_add(obj, "log_file",
				json_object_new_string(zconf.log_file));
	}
	if (zconf.log_directory) {
		json_object_object_add(obj, "log_directory",
				json_object_new_string(zconf.log_directory));
	}

	if (zconf.destination_cidrs_len) {
		json_object *cli_dest_cidrs = json_object_new_array();
		for (int i=0; i < zconf.destination_cidrs_len; i++) {
			json_object_array_add(cli_dest_cidrs, json_object_new_string(zconf.destination_cidrs[i]));
		}
		json_object_object_add(obj, "cli_cidr_destinations",
				cli_dest_cidrs);
	}
	if (zconf.probe_args) {
		json_object_object_add(obj, "probe_args",
			json_object_new_string(zconf.probe_args));
	}
	if (zconf.output_args) {
		json_object_object_add(obj, "output_args",
			json_object_new_string(zconf.output_args));
	}

	if (zconf.gw_mac) {
		char mac_buf[ (MAC_ADDR_LEN * 2) + (MAC_ADDR_LEN - 1) + 1 ];
		memset(mac_buf, 0, sizeof(mac_buf));
		char *p = mac_buf;
		for(int i=0; i < MAC_ADDR_LEN; i++) {
			if (i == MAC_ADDR_LEN-1) {
				snprintf(p, 3, "%.2x", zconf.gw_mac[i]);
				p += 2;
			} else {
				snprintf(p, 4, "%.2x:", zconf.gw_mac[i]);
				p += 3;
			}
		}
		json_object_object_add(obj, "gateway_mac", json_object_new_string(mac_buf));
	}
	if (zconf.gw_ip) {
		struct in_addr addr;
		addr.s_addr = zconf.gw_ip;
		json_object_object_add(obj, "gateway_ip", json_object_new_string(inet_ntoa(addr)));
	}
	if (zconf.hw_mac) {
		char mac_buf[(ETHER_ADDR_LEN * 2) + (ETHER_ADDR_LEN - 1) + 1];
		char *p = mac_buf;
		for(int i=0; i < ETHER_ADDR_LEN; i++) {
			if (i == ETHER_ADDR_LEN-1) {
				snprintf(p, 3, "%.2x", zconf.hw_mac[i]);
				p += 2;
			} else {
				snprintf(p, 4, "%.2x:", zconf.hw_mac[i]);
				p += 3;
			}
		}
		json_object_object_add(obj, "source_mac", json_object_new_string(mac_buf));
	}

	json_object_object_add(obj, "source_ip_first",
			json_object_new_string(zconf.source_ip_first));
	json_object_object_add(obj, "source_ip_last",
			json_object_new_string(zconf.source_ip_last));
	if (zconf.output_filename) {
		json_object_object_add(obj, "output_filename",
				json_object_new_string(zconf.output_filename));
	}
	if (zconf.blacklist_filename) {
		json_object_object_add(obj,
			"blacklist_filename",
			json_object_new_string(zconf.blacklist_filename));
	}
	if (zconf.whitelist_filename) {
		json_object_object_add(obj,
			"whitelist_filename",
			json_object_new_string(zconf.whitelist_filename));
	}
	json_object_object_add(obj, "dryrun",
            json_object_new_int(zconf.dryrun));
	json_object_object_add(obj, "quiet",
            json_object_new_int(zconf.quiet));
	json_object_object_add(obj, "log_level",
            json_object_new_int(zconf.log_level));

    // parse out JSON metadata that was supplied on the command-line
    if (zconf.custom_metadata_str) {
        json_object *user = json_tokener_parse(zconf.custom_metadata_str);
        if (!user) {
            log_error("json-metadata", "unable to parse user metadata");
        } else {
	        json_object_object_add(obj, "user-metadata", user);
        }
    }

    if (zconf.notes) {
        json_object_object_add(obj, "notes",
                json_object_new_string(zconf.notes));
    }

	// add blacklisted and whitelisted CIDR blocks
	bl_cidr_node_t *b = get_blacklisted_cidrs();
	if (b) {
		json_object *blacklisted_cidrs = json_object_new_array();
		do {
			char cidr[50];
			struct in_addr addr;
			addr.s_addr = b->ip_address;
			sprintf(cidr, "%s/%i", inet_ntoa(addr), b->prefix_len);
			json_object_array_add(blacklisted_cidrs,
					json_object_new_string(cidr));
		} while (b && (b = b->next));
		json_object_object_add(obj, "blacklisted_networks", blacklisted_cidrs);
	}

	b = get_whitelisted_cidrs();
	if (b) {
		json_object *whitelisted_cidrs = json_object_new_array();
		do {
			char cidr[50];
			struct in_addr addr;
			addr.s_addr = b->ip_address;
			sprintf(cidr, "%s/%i", inet_ntoa(addr), b->prefix_len);
			json_object_array_add(whitelisted_cidrs,
					json_object_new_string(cidr));
		} while (b && (b = b->next));
		json_object_object_add(obj, "whitelisted_networks", whitelisted_cidrs);
	}

	fprintf(file, "%s\n", json_object_to_json_string(obj));
	json_object_put(obj);
}