Esempio n. 1
0
json_t *CreateJSONHeader(Packet *p, int direction_sensitive, char *event_type)
{
    char timebuf[64];
    char srcip[46], dstip[46];
    Port sp, dp;

    json_t *js = json_object();
    if (unlikely(js == NULL))
        return NULL;

    CreateIsoTimeString(&p->ts, timebuf, sizeof(timebuf));

    srcip[0] = '\0';
    dstip[0] = '\0';
    if (direction_sensitive) {
        if ((PKT_IS_TOSERVER(p))) {
            if (PKT_IS_IPV4(p)) {
                PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), srcip, sizeof(srcip));
                PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), dstip, sizeof(dstip));
            } else if (PKT_IS_IPV6(p)) {
                PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), srcip, sizeof(srcip));
                PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), dstip, sizeof(dstip));
            }
            sp = p->sp;
            dp = p->dp;
        } else {
            if (PKT_IS_IPV4(p)) {
                PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), srcip, sizeof(srcip));
                PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), dstip, sizeof(dstip));
            } else if (PKT_IS_IPV6(p)) {
                PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), srcip, sizeof(srcip));
                PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), dstip, sizeof(dstip));
            }
            sp = p->dp;
            dp = p->sp;
        }
    } else {
        if (PKT_IS_IPV4(p)) {
            PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), srcip, sizeof(srcip));
            PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), dstip, sizeof(dstip));
        } else if (PKT_IS_IPV6(p)) {
            PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), srcip, sizeof(srcip));
            PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), dstip, sizeof(dstip));
        }
        sp = p->sp;
        dp = p->dp;
    }

    char proto[16];
    if (SCProtoNameValid(IP_GET_IPPROTO(p)) == TRUE) {
        strlcpy(proto, known_proto[IP_GET_IPPROTO(p)], sizeof(proto));
    } else {
        snprintf(proto, sizeof(proto), "%03" PRIu32, IP_GET_IPPROTO(p));
    }

    /* time & tx */
    json_object_set_new(js, "timestamp", json_string(timebuf));

    /* sensor id */
    if (sensor_id >= 0)
        json_object_set_new(js, "sensor_id", json_integer(sensor_id));

    /* pcap_cnt */
    if (p->pcap_cnt != 0) {
        json_object_set_new(js, "pcap_cnt", json_integer(p->pcap_cnt));
    }

    if (event_type) {
        json_object_set_new(js, "event_type", json_string(event_type));
    }

    /* vlan */
    if (p->vlan_idx > 0) {
        json_t *js_vlan;
        switch (p->vlan_idx) {
        case 1:
            json_object_set_new(js, "vlan",
                                json_integer(VLAN_GET_ID1(p)));
            break;
        case 2:
            js_vlan = json_array();
            if (unlikely(js != NULL)) {
                json_array_append_new(js_vlan,
                                      json_integer(VLAN_GET_ID1(p)));
                json_array_append_new(js_vlan,
                                      json_integer(VLAN_GET_ID2(p)));
                json_object_set_new(js, "vlan", js_vlan);
            }
            break;
        default:
            /* shouldn't get here */
            break;
        }
    }

    /* tuple */
    json_object_set_new(js, "src_ip", json_string(srcip));
    switch(p->proto) {
    case IPPROTO_ICMP:
        break;
    case IPPROTO_UDP:
    case IPPROTO_TCP:
    case IPPROTO_SCTP:
        json_object_set_new(js, "src_port", json_integer(sp));
        break;
    }
    json_object_set_new(js, "dest_ip", json_string(dstip));
    switch(p->proto) {
    case IPPROTO_ICMP:
        break;
    case IPPROTO_UDP:
    case IPPROTO_TCP:
    case IPPROTO_SCTP:
        json_object_set_new(js, "dest_port", json_integer(dp));
        break;
    }
    json_object_set_new(js, "proto", json_string(proto));
    switch (p->proto) {
    case IPPROTO_ICMP:
        if (p->icmpv4h) {
            json_object_set_new(js, "icmp_type",
                                json_integer(p->icmpv4h->type));
            json_object_set_new(js, "icmp_code",
                                json_integer(p->icmpv4h->code));
        }
        break;
    case IPPROTO_ICMPV6:
        if (p->icmpv6h) {
            json_object_set_new(js, "icmp_type",
                                json_integer(p->icmpv6h->type));
            json_object_set_new(js, "icmp_code",
                                json_integer(p->icmpv6h->code));
        }
        break;
    }

    return js;
}
//----------------------------------------------------------------//
json_t* MOAIHarness::ConvertStackIndexToJSON(lua_State * L, int idx, bool shallow, std::vector<const void*> * carried_references)
{
	// Check to see if idx is negative.
	if (idx < 0)
		idx = lua_gettop(L) + (idx + 1);

	// What we do is going to be based on what is located at
	// the specified index.
	switch (lua_type(L, idx))
	{
	case LUA_TNIL:
		return json_null();
	case LUA_TNUMBER:
		return json_real(lua_tonumber(L, idx));
	case LUA_TSTRING:
		return json_string(lua_tostring(L, idx));
	case LUA_TBOOLEAN:
		return (lua_toboolean(L, idx) == 0) ? json_false() : json_true();
	case LUA_TFUNCTION:
		// Todo: fix pointer encoding for datapairs so that this will work
		// correctly on 64 bit systems
		return json_datapair("function", json_integer((int)lua_topointer(L, idx)));
	case LUA_TUSERDATA:
		return json_datapair("userdata", json_integer((int)lua_topointer(L, idx)));
	case LUA_TTHREAD:
		return json_datapair("thread", json_integer((int)lua_topointer(L, idx)));
	case LUA_TLIGHTUSERDATA:
		return json_datapair("lightuserdata", json_integer((int)lua_topointer(L, idx)));
	case LUA_TTABLE:
		// Unlike other data values, table must be recursively evaluated.  In addition
		// we must check for circular references since it's possible they may occur.
		char s[LUAI_MAXNUMBER2STR];
		std::vector<const void*> * references = (carried_references == NULL) ? new std::vector<const void*>() : carried_references;
		json_t* holder = shallow ? json_array() : json_object();
		lua_pushnil(L);
		while (lua_next(L, idx) != 0)
		{
			// Key is at index -2
			// Value is at index -1
			json_t* key = NULL;
			json_t* value = NULL;

			// Safely convert the key into a string if needed (we
			// can't use lua_tostring with lua_next).
			if (lua_isnumber(L, -2))
			{
				lua_Number n = lua_tonumber(L, -2);
				if (shallow)
				{
					key = json_real(n);
				}
				else
				{
					lua_number2str(s, n);
					key = json_string((const char*)&s);
				}
			}
			else if (lua_isboolean(L, -2))
			{
				key = json_string(lua_toboolean(L, -2) ? "true" : "false");
			}
			else if (!lua_isstring(L, -2))
			{
				int type = lua_type(L, -2);
				key = json_datapair(lua_typename(L, type), json_integer((int)lua_topointer(L, -2)));
			}
			else
				key = json_string(lua_tostring(L, -2));

			// If only a shallow result is requested, just add the key to an array
			if (shallow)
			{
				json_array_append_new(holder, key);
				lua_pop(L, 1);
				continue;
			}

			// Recursively convert the value ONLY if it doesn't
			// appear in our references vector.
			bool evaluate = true;
			if (lua_type(L, -1) == LUA_TTABLE)
			{
				const void* ptr = lua_topointer(L, -1);
				for (std::vector<const void*>::iterator it = references->begin(); it != references->end(); ++it)
				{
					if (*it == ptr)
					{
						evaluate = false;
						break;
					}
				}
			}

			// Now evaluate the value if we should.
			if (evaluate)
			{
				if (lua_type(L, -1) == LUA_TTABLE)
					references->insert(references->end(), lua_topointer(L, -1));
				value = MOAIHarness::ConvertStackIndexToJSON(L, -1, shallow, references);
			}
			else
				value = json_datapair("recursive", json_integer((int)lua_topointer(L, -1)));

			// Assign the key value pair to the holder object.
			json_object_set(holder, json_string_value(key), value);
			json_decref(key);
			json_decref(value);

			// Pop the value from the stack (lua_next will consume
			// the key on the next iterator).
			lua_pop(L, 1);
		}
		if (carried_references == NULL)
			delete references;
		return holder;
	}
	return json_datapair("unknown", json_integer((int)lua_topointer(L, idx)));
}
Esempio n. 3
0
static void
ccmd_list_games(json_t * params)
{
    char filename[1024];
    int completed, limit, show_all, count, i, fd;
    struct gamefile_info *files;
    enum nh_log_status status;
    struct nh_game_info gi;
    json_t *jarr, *jobj;

    if (json_unpack
        (params, "{si,si*}", "completed", &completed, "limit", &limit) == -1)
        exit_client("Bad parameters for list_games");
    if (json_unpack(params, "{si*}", "show_all", &show_all) == -1)
        show_all = 0;

    /* step 1: get a list of files from the db. */
    files =
        db_list_games(completed, show_all ? 0 : user_info.uid, limit, &count);

    jarr = json_array();
    /* step 2: get extra info for each file. */
    for (i = 0; i < count; i++) {
        if (completed)
            snprintf(filename, 1024, "%s/completed/%s", settings.workdir,
                     files[i].filename);
        else
            snprintf(filename, 1024, "%s/save/%s/%s", settings.workdir,
                     user_info.username, files[i].filename);
        fd = open(filename, O_RDWR);
        if (fd == -1) {
            log_msg("Game file %s could not be opened in ccmd_list_games.",
                    files[i].filename);
            continue;
        }

        status = nh_get_savegame_status(fd, &gi);
        jobj =
            json_pack("{si,si,si,ss,ss,ss,ss,ss}", "gameid", files[i].gid,
                      "status", status, "playmode", gi.playmode, "plname",
                      gi.name, "plrole", gi.plrole, "plrace", gi.plrace,
                      "plgend", gi.plgend, "plalign", gi.plalign);
        if (status == LS_SAVED) {
            json_object_set_new(jobj, "level_desc", json_string(gi.level_desc));
            json_object_set_new(jobj, "moves", json_integer(gi.moves));
            json_object_set_new(jobj, "depth", json_integer(gi.depth));
            json_object_set_new(jobj, "has_amulet",
                                json_integer(gi.has_amulet));
        } else if (status == LS_DONE) {
            json_object_set_new(jobj, "death", json_string(gi.death));
            json_object_set_new(jobj, "moves", json_integer(gi.moves));
            json_object_set_new(jobj, "depth", json_integer(gi.depth));
        }
        json_array_append_new(jarr, jobj);

        free((void *)files[i].username);
        free((void *)files[i].filename);

        close(fd);
    }
    free(files);

    client_msg("list_games", json_pack("{so}", "games", jarr));
}
Esempio n. 4
0
int main()
{
    json_t *json;
    char *result;

    /* Encode an empty object/array, add an item, encode again */

    json = json_object();
    result = json_dumps(json, 0);
    if(!result || strcmp(result, "{}"))
      fail("json_dumps failed");
    free(result);

    json_object_set_new(json, "foo", json_integer(5));
    result = json_dumps(json, 0);
    if(!result || strcmp(result, "{\"foo\": 5}"))
      fail("json_dumps failed");
    free(result);

    json_decref(json);

    json = json_array();
    result = json_dumps(json, 0);
    if(!result || strcmp(result, "[]"))
      fail("json_dumps failed");
    free(result);

    json_array_append_new(json, json_integer(5));
    result = json_dumps(json, 0);
    if(!result || strcmp(result, "[5]"))
      fail("json_dumps failed");
    free(result);

    json_decref(json);

    /* Construct a JSON object/array with a circular reference:

       object: {"a": {"b": {"c": <circular reference to $.a>}}}
       array: [[[<circular reference to the $[0] array>]]]

       Encode it, remove the circular reference and encode again.
    */
    json = json_object();
    json_object_set_new(json, "a", json_object());
    json_object_set_new(json_object_get(json, "a"), "b", json_object());
    json_object_set(json_object_get(json_object_get(json, "a"), "b"), "c",
                    json_object_get(json, "a"));

    if(json_dumps(json, 0))
        fail("json_dumps encoded a circular reference!");

    json_object_del(json_object_get(json_object_get(json, "a"), "b"), "c");

    result = json_dumps(json, 0);
    if(!result || strcmp(result, "{\"a\": {\"b\": {}}}"))
        fail("json_dumps failed!");
    free(result);

    json_decref(json);

    json = json_array();
    json_array_append_new(json, json_array());
    json_array_append_new(json_array_get(json, 0), json_array());
    json_array_append(json_array_get(json_array_get(json, 0), 0),
                      json_array_get(json, 0));

    if(json_dumps(json, 0))
        fail("json_dumps encoded a circular reference!");

    json_array_remove(json_array_get(json_array_get(json, 0), 0), 0);

    result = json_dumps(json, 0);
    if(!result || strcmp(result, "[[[]]]"))
        fail("json_dumps failed!");
    free(result);

    json_decref(json);

    return 0;
}
Esempio n. 5
0
static int AlertJsonDecoderEvent(ThreadVars *tv, JsonAlertLogThread *aft, const Packet *p)
{
    int i;
    char timebuf[64];
    json_t *js;

    if (p->alerts.cnt == 0)
        return TM_ECODE_OK;

    CreateIsoTimeString(&p->ts, timebuf, sizeof(timebuf));

    for (i = 0; i < p->alerts.cnt; i++) {
        MemBufferReset(aft->json_buffer);

        const PacketAlert *pa = &p->alerts.alerts[i];
        if (unlikely(pa->s == NULL)) {
            continue;
        }

        char *action = "allowed";
        if (pa->action & (ACTION_REJECT|ACTION_REJECT_DST|ACTION_REJECT_BOTH)) {
            action = "blocked";
        } else if ((pa->action & ACTION_DROP) && EngineModeIsIPS()) {
            action = "blocked";
        }

        char buf[(32 * 3) + 1];
        PrintRawLineHexBuf(buf, sizeof(buf), GET_PKT_DATA(p), GET_PKT_LEN(p) < 32 ? GET_PKT_LEN(p) : 32);

        js = json_object();
        if (js == NULL)
            return TM_ECODE_OK;

        json_t *ajs = json_object();
        if (ajs == NULL) {
            json_decref(js);
            return TM_ECODE_OK;
        }

        /* time & tx */
        json_object_set_new(js, "timestamp", json_string(timebuf));

        /* tuple */
        //json_object_set_new(js, "srcip", json_string(srcip));
        //json_object_set_new(js, "sp", json_integer(p->sp));
        //json_object_set_new(js, "dstip", json_string(dstip));
        //json_object_set_new(js, "dp", json_integer(p->dp));
        //json_object_set_new(js, "proto", json_integer(proto));

        json_object_set_new(ajs, "action", json_string(action));
        json_object_set_new(ajs, "gid", json_integer(pa->s->gid));
        json_object_set_new(ajs, "signature_id", json_integer(pa->s->id));
        json_object_set_new(ajs, "rev", json_integer(pa->s->rev));
        json_object_set_new(ajs, "signature",
                            json_string((pa->s->msg) ? pa->s->msg : ""));
        json_object_set_new(ajs, "category",
                            json_string((pa->s->class_msg) ? pa->s->class_msg : ""));
        json_object_set_new(ajs, "severity", json_integer(pa->s->prio));

        if (p->tenant_id > 0)
            json_object_set_new(ajs, "tenant_id", json_integer(p->tenant_id));

        /* alert */
        json_object_set_new(js, "alert", ajs);
        OutputJSONBuffer(js, aft->file_ctx, &aft->json_buffer);
        json_object_clear(js);
        json_decref(js);
    }

    return TM_ECODE_OK;
}
Esempio n. 6
0
/*====================================================================
 * 函数名    : vGenPASP2PCONFCREATEMsg
 * 功能      : PAS上报创建点对点会议信息消息
 * 算法实现  : 
 * 参数说明  : vpd 要上报的设备
 * 返回值说明: 成功 生成的消息
 *			   失败 NULL             
 * ----------------------------------------------------------------------
 * 修改记录:
 * 日  期        版本        修改人        走读人        修改记录
 * 2015/1/26       v1.0        YLI                          创建
 * ====================================================================*/
json_t * vGenPASP2PCONFCREATEMsg(VPD vpd)
{
	json_t *root;
	json_t *p2pconfinfo;
	char saLocalTime[256];

	root = json_object();
	//eventid
	if (json_object_set(root,"eventid",
		json_string("EV_PAS_INFO")) == FAILUER)
	{
		json_decref(root);
		vLogErr("eventid set error!!!");
		return NULL;
	}
	//devid
	if (json_object_set(root,"devid",
		json_string(vpd.saDevId)) == FAILUER)
	{
		json_decref(root);
		vLogErr("devtype set error!!!");
		return NULL;
	}
	//devtype
	if (json_object_set(root,"devtype",
		json_string(vpd.saDevType)) == FAILUER)
	{
		json_decref(root);
		vLogErr("devtype set error!!!");
		return NULL;
	}
	//rpttime
	memset(saLocalTime,0x00,sizeof saLocalTime);
	GetLocalTime(saLocalTime);
	if (json_object_set(root,"rpttime",
		json_string(saLocalTime)) == FAILUER)
	{
		json_decref(root);
		vLogErr("rpttime set error!!!");
		return NULL;
	}
	//version
	json_object_set(root,"version",json_string("1.06"));
	//pidchange
	json_object_set(root,"pidchange",json_false());
	//belongphy
	json_object_set(root,"belongphy",json_string("1123"));
	/*p2pconfinfo*/
	p2pconfinfo = json_object();
	//confe164
	json_object_set(p2pconfinfo,"confe164",json_string("e164"));
	//confname
	json_object_set(p2pconfinfo,"confname",json_string("Share"));
	//bitrate
	json_object_set(p2pconfinfo,"bitrate",json_string("Share"));
	//begintime
	json_object_set(p2pconfinfo,"begintime",json_string(saLocalTime));
	//duration
	json_object_set(p2pconfinfo,"duration",json_integer(1));
	//caller
	json_object_set(p2pconfinfo,"caller",
		json_pack("{s:s,s:s,s:s,s:s}",
			"devtype",vpd.saDevType,
			"devname","sm",
			"deve164","e164",
			"devguid",vpd.saDevId));
	//callee
	json_object_set(p2pconfinfo,"callee",
		json_pack("{s:s,s:s,s:s,s:s}",
			"devtype",vpd.saDevType,
			"devname","sm",
			"deve164","e164",
			"devguid",vpd.saDevId));
	//endtime
	memset(saLocalTime,0x00,sizeof saLocalTime);
	GetLocalTime(saLocalTime);
	json_object_set(p2pconfinfo,"endtime",json_string(saLocalTime));

	json_decref(p2pconfinfo);
	json_object_set(root,"p2pconfinfo",p2pconfinfo);

	return root;
}
Esempio n. 7
0
/*====================================================================
 * 函数名    : vGenRegTermMsg
 * 功能      : 生成终端注册消息
 * 算法实现  : 
 * 参数说明  : 
 *				nIdx 标识是哪个的base
 * 返回值说明: 成功 生成的json字符串
 *			   失败 NULL             
 * ----------------------------------------------------------------------
 * 修改记录:
 * 日  期        版本        修改人        走读人        修改记录
 * 2015/1/13       v1.0        YLI                          创建
 * ====================================================================*/
json_t *vGenRegTermMsg(int nIdx)
{
	json_t *root;
	json_t *mt_info;
	json_t *netinfo;
	json_t *aps_addr;
	json_t *jt;
	const char *key;
	json_t *value;
	int n,size;
	char saCfgPath[L_PATH_MAX_LEN];
	char tmp[100];
	root = json_object();
	memset(tmp,0x00,sizeof tmp);
	memset(saCfgPath,0x00,sizeof saCfgPath);
	
	srand((unsigned)time(NULL));

	//set eventid
	if (json_object_set(root,"eventid",
		json_string("EV_REG_REQ")) == FAILUER)
	{
		json_decref(root);
		vLogErr("eventid set error!!!");
		return NULL;
	}
	//devid
	n = rand() % (S_RAND_RANG + _gstrpPid[nIdx].nTermCount);
	sprintf(tmp,"1.2.%02d",n);
	if (json_object_set(root,"devid",
		json_string(tmp)) == FAILUER)
	{
		json_decref(root);
		vLogErr("devid set error!!!");
		return NULL;
	}
	//devtype
	if(getenv("APP_PROFILE_PATH") == NULL)
	{
		json_decref(root);
		vLogErr("devtypes config file path error,please check evn value!!!");
		return NULL;
	}
	strcpy(saCfgPath,getenv("APP_PROFILE_PATH"));
	strcat(saCfgPath,"/devtypes.json");
	jt = tPflGetJsonObj(saCfgPath,K_DEVTYPE_KEY);
	if (jt == NULL)
	{
		json_decref(root);
		vLogErr("devtypes file open error,please check devtypes.json is exist!!!");
		return NULL;
	}
	
	
	if (json_is_array(jt))
	{
		size = json_array_size(jt);
		n = rand()%size;
		if (json_object_set(root,"devtype",
		json_array_get(jt,n)) == FAILUER)
		{
			json_decref(root);
			vLogErr("devtype set error!!!");
			return NULL;
		}	
	}

	/*mt_info*/
	mt_info = json_object();
	//devver
	if (json_object_set(mt_info,"devver",
		json_string("123")) == FAILUER)
	{
		json_decref(root);
		vLogErr("devver set error!!!");
		return NULL;
	}
	//devname
	json_object_set(mt_info,"devname",json_string("truelink"));
	//netinfo
	netinfo = json_object();
	json_object_set(netinfo,"ip",
		json_string(_gstrpShm->rc.nSrvIP));
	json_object_set(netinfo,"dns",
		json_string("172.16.0.65"));
	json_object_set(mt_info,"netinfo",netinfo);

	//aps_addr
	aps_addr = json_object();
	json_object_set(aps_addr,"domain",
		json_string("fdaf"));
	json_object_set(aps_addr,"ip",
		json_string(_gstrpShm->rc.nSrvIP));
	json_object_set(mt_info,"aps_addr",aps_addr);

	//oem
	json_object_set(mt_info,"oem",json_string("dfd"));
	//os
	json_object_set(mt_info,"os",json_string("Centos 6.4"));
	//cpu_num
	json_object_set(mt_info,"cpu_num",json_integer(4));
	//cpu_type
	//cpu_freq
	json_decref(jt);
	jt = GetCpuInfo();
	json_object_foreach(jt,key,value)
	{
		if(strncmp(key,"cpuMHz",6) == 0)
		{
			json_object_set(mt_info,"cpu_freq",value);
		}
		if (strncmp(key,"modelname",9) == 0)
		{
			json_object_set(mt_info,"cpu_type",value);
		}
	}
	json_decref(jt);
	jt = GetMemInfo();
	//memory
	json_object_foreach(jt,key,value)
	{
		if(strncmp(key,"MemTotal",8) == 0)
		{
			json_object_set(mt_info,"memory",value);
		}
	}
	json_object_set(root,"mt_info",mt_info);
	json_decref(mt_info);
	return root;
}
Esempio n. 8
0
static json_t *member_data_to_json(const json_t *member, const qeocore_data_t *data)
{
    json_t  *json_data  = NULL;
    json_t  *id         = json_object_get(member, KEY_ID);            // Mandatory
    json_t  *type       = json_object_get(member, KEY_QEO_TYPE_CODE); // Mandatory

    if ((NULL == id) || (!json_is_integer(id)) ||
        (NULL == type) || (!json_is_integer(type))) {
        return json_data;
    }

    qeocore_member_id_t qeo_member_id = (qeocore_member_id_t) json_integer_value(id);
    qeocore_typecode_t  qeoTypeCode   = (qeocore_typecode_t) json_integer_value(type);

    switch (qeoTypeCode) {
        case QEOCORE_TYPECODE_BOOLEAN:
        {
            qeo_boolean_t bool_value = 0;
            if (QEO_OK == qeocore_data_get_member(data, qeo_member_id, &bool_value)) {
                json_data = bool_value ? (json_true()) : (json_false());
            }
        }
        break;

        case QEOCORE_TYPECODE_INT8:
        {
            int8_t int_value;
            if (QEO_OK == qeocore_data_get_member(data, qeo_member_id, &int_value)) {
                json_data = json_integer(int_value);
            }
        }
        break;

        case QEOCORE_TYPECODE_INT16:
        {
            int16_t int_value;
            if (QEO_OK == qeocore_data_get_member(data, qeo_member_id, &int_value)) {
                json_data = json_integer(int_value);
            }
        }
        break;

        case QEOCORE_TYPECODE_INT32:
        {
            int32_t int_value;
            if (QEO_OK == qeocore_data_get_member(data, qeo_member_id, &int_value)) {
                json_data = json_integer(int_value);
            }
        }
        break;

        case QEOCORE_TYPECODE_INT64:
        {
            int64_t int_value;
            if (QEO_OK == qeocore_data_get_member(data, qeo_member_id, &int_value)) {
                char *char_value = NULL;
                if (-1 != asprintf(&char_value, "%" PRId64 "", int_value)) {
                    json_data = json_string(char_value);
                    free(char_value);
                }
            }
        }
        break;

        case QEOCORE_TYPECODE_FLOAT32:
        {
            float float_value;
            if (QEO_OK == qeocore_data_get_member(data, qeo_member_id, &float_value)) {
                json_data = json_real(float_value);
            }
        }
        break;

        case QEOCORE_TYPECODE_STRING:
        {
            char *char_value;
            if (QEO_OK == qeocore_data_get_member(data, qeo_member_id, &char_value)) {
                json_data = json_string(char_value);
                free(char_value);
            }
        }
        break;

        case QEOCORE_TYPECODE_STRUCT:
        {
            qeocore_data_t *qeo_data = NULL;
            do {
                json_t *item = json_object_get(member, KEY_ITEM);
                if (NULL == item) {
                    qeo_log_e("NULL == item");
                    break;
                }

                if (!json_is_object(item)) {
                    qeo_log_e("not an object");
                    break;
                }

                if (QEO_OK != qeocore_data_get_member(data, qeo_member_id, &qeo_data)) {
                    qeo_log_e("qeocore_data_get_member failed");
                    break;
                }

                if (NULL == qeo_data) {
                    qeo_log_e("NULL == qeo_data");
                    break;
                }

                json_data = object_data_to_json(item, qeo_data);
            } while (0);

            if (NULL != qeo_data) {
                qeocore_data_free(qeo_data);
            }
        }
        break;

        case QEOCORE_TYPECODE_SEQUENCE:
        {
            json_t *items = json_object_get(member, KEY_ITEMS);
            if ((NULL != items) && json_is_object(items)) {
                qeocore_data_t *seqdata = NULL;
                if ((QEO_OK == qeocore_data_get_member(data, qeo_member_id, &seqdata)) && (NULL != seqdata)) {
                    json_data = array_data_to_json(items, seqdata);
                    qeocore_data_free(seqdata);
                }
            }
        }
        break;
        case QEOCORE_TYPECODE_ENUM:
        {
            qeo_enum_value_t enum_value;
            if (QEO_OK != qeocore_data_get_member(data, qeo_member_id, &enum_value)) {
                qeo_log_e("Could not get member");
                break;
            } 
            if (is_valid_enum_value(member, enum_value) == false){
                qeo_log_e("Not a valid enum value");
                break;
            }
            json_data = json_integer(enum_value);

        }
        break;
    }
    return json_data;
}
Esempio n. 9
0
/**
 *  \internal
 *  \brief Write meta data on a single line json record
 */
static void FileWriteJsonRecord(JsonFileLogThread *aft, const Packet *p, const File *ff) {
    MemBuffer *buffer = (MemBuffer *)aft->buffer;
    json_t *js = CreateJSONHeader((Packet *)p, 0, "file"); //TODO const
    if (unlikely(js == NULL))
        return;

    /* reset */
    MemBufferReset(buffer);

    json_t *hjs = json_object();
    if (unlikely(hjs == NULL)) {
        json_decref(js);
        return;
    }

    json_object_set_new(hjs, "url", LogFileMetaGetUri(p, ff));
    json_object_set_new(hjs, "hostname", LogFileMetaGetHost(p, ff));
    json_object_set_new(hjs, "http_refer", LogFileMetaGetReferer(p, ff));
    json_object_set_new(hjs, "http_user_agent", LogFileMetaGetUserAgent(p, ff));
    json_object_set_new(js, "http", hjs);

    json_t *fjs = json_object();
    if (unlikely(fjs == NULL)) {
        json_decref(hjs);
        json_decref(js);
        return;
    }

    char *s = BytesToString(ff->name, ff->name_len);
    json_object_set_new(fjs, "filename", json_string(s));
    if (s != NULL)
        SCFree(s);
    if (ff->magic)
        json_object_set_new(fjs, "magic", json_string((char *)ff->magic));
    else
        json_object_set_new(fjs, "magic", json_string("unknown"));
    switch (ff->state) {
        case FILE_STATE_CLOSED:
            json_object_set_new(fjs, "state", json_string("CLOSED"));
#ifdef HAVE_NSS
            if (ff->flags & FILE_MD5) {
                size_t x;
                int i;
                char *s = SCMalloc(256);
                if (likely(s != NULL)) {
                    for (i = 0, x = 0; x < sizeof(ff->md5); x++) {
                        i += snprintf(&s[i], 255-i, "%02x", ff->md5[x]);
                    }
                    json_object_set_new(fjs, "md5", json_string(s));
                    SCFree(s);
                }
            }
#endif
            break;
        case FILE_STATE_TRUNCATED:
            json_object_set_new(fjs, "state", json_string("TRUNCATED"));
            break;
        case FILE_STATE_ERROR:
            json_object_set_new(fjs, "state", json_string("ERROR"));
            break;
        default:
            json_object_set_new(fjs, "state", json_string("UNKNOWN"));
            break;
    }
    json_object_set_new(fjs, "stored",
                        (ff->flags & FILE_STORED) ? json_true() : json_false());
    json_object_set_new(fjs, "size", json_integer(ff->size));

    json_object_set_new(js, "file", fjs);
    OutputJSONBuffer(js, aft->filelog_ctx->file_ctx, buffer);
    json_object_del(js, "file");
    json_object_del(js, "http");

    json_object_clear(js);
    json_decref(js);
}
Esempio n. 10
0
static json_t *array_data_to_json(const json_t *typedesc, qeocore_data_t *data)
{
    json_t          *json_data  = NULL;
    qeo_sequence_t  seq         = { 0 };

    json_t *type = json_object_get(typedesc, KEY_QEO_TYPE_CODE); // Mandatory

    if ((NULL == type) || (!json_is_integer(type)) ||
        (QEO_OK != qeocore_data_sequence_get(data, &seq, 0, QEOCORE_SIZE_UNLIMITED))) {
        return json_data;
    }
    json_data = json_array();
    qeocore_typecode_t qeoTypeCode = (qeocore_typecode_t) json_integer_value(type);

    int i;
    int numOfElem = DDS_SEQ_LENGTH(seq);
    for (i = 0; i < numOfElem; ++i) {
        switch (qeoTypeCode) {
            case QEOCORE_TYPECODE_BOOLEAN:
            {
                qeo_boolean_t bool_value = ((qeo_boolean_t *)DDS_SEQ_DATA(seq))[i];
                json_array_append_new(json_data, bool_value ? (json_true()) : (json_false()));
            }
            break;

            case QEOCORE_TYPECODE_INT8:
            {
                int8_t int_value = ((int8_t *)DDS_SEQ_DATA(seq))[i];
                json_array_append_new(json_data, json_integer((json_int_t)int_value));
            }
            break;

            case QEOCORE_TYPECODE_INT16:
            {
                int8_t int_value = ((int16_t *)DDS_SEQ_DATA(seq))[i];
                json_array_append_new(json_data, json_integer((json_int_t)int_value));
            }
            break;

            case QEOCORE_TYPECODE_INT32:
            {
                int8_t int_value = ((int32_t *)DDS_SEQ_DATA(seq))[i];
                json_array_append_new(json_data, json_integer((json_int_t)int_value));
            }
            break;

            case QEOCORE_TYPECODE_INT64:
            {
                int64_t int_value   = ((int64_t *)DDS_SEQ_DATA(seq))[i];
                char    *char_value = NULL;
                if (-1 != asprintf(&char_value, "%" PRId64 "", int_value)) {
                    json_array_append_new(json_data, json_string(char_value));
                    free(char_value);
                }
            }
            break;

            case QEOCORE_TYPECODE_STRING:
            {
                char *char_value = ((char **)DDS_SEQ_DATA(seq))[i];
                json_array_append_new(json_data, json_string(char_value));
            }
            break;

            case QEOCORE_TYPECODE_STRUCT:
            {
                json_t *item = json_object_get(typedesc, KEY_ITEM);
                if ((NULL != item) && json_is_object(item)) {
                    qeocore_data_t  *object_value = ((qeocore_data_t **)DDS_SEQ_DATA(seq))[i];
                    json_t          *json_element = object_data_to_json(item, object_value);
                    if (NULL != json_element) {
                        json_array_append_new(json_data, json_element);
                    }
                    else {
                        json_decref(json_data);
                        json_data = NULL;
                    }
                }
                else {
                    json_decref(json_data);
                    json_data = NULL;
                }
            }
            break;

            case QEOCORE_TYPECODE_SEQUENCE:
            {
                json_t *items = json_object_get(typedesc, KEY_ITEMS);
                if ((NULL != items) && json_is_object(items)) {
                    qeocore_data_t  *element_value  = ((qeocore_data_t **)DDS_SEQ_DATA(seq))[i];
                    json_t          *json_element   = array_data_to_json(items, element_value);
                    if (NULL != json_element) {
                        json_array_append_new(json_data, json_element);
                    }
                    else {
                        json_decref(json_data);
                        json_data = NULL;
                    }
                }
                else {
                    json_decref(json_data);
                    json_data = NULL;
                }
            }
            break;
            case QEOCORE_TYPECODE_ENUM:
            {
                qeo_enum_value_t enum_value = ((qeo_enum_value_t *)DDS_SEQ_DATA(seq))[i];
                if (is_valid_enum_value(typedesc, enum_value) == false){
                    qeo_log_e("Not a valid enum value");
                    break;
                }
                json_t *json_enum = json_integer(enum_value);
                json_array_append_new(json_data, json_enum);
            }
            break;
            case QEOCORE_TYPECODE_FLOAT32:
            {
                float float_value = ((float *)DDS_SEQ_DATA(seq))[i];
                json_array_append_new(json_data, json_real(float_value));
            }
            break;

        }

        if (NULL == json_data) {
            break;
        }
    }
    qeocore_data_sequence_free(data, &seq);
    return json_data;
}
Esempio n. 11
0
static qeocore_type_t *build_member_type(const qeo_factory_t *factory, json_t *member)
{
    qeocore_type_t      *memberType = NULL;
    qeocore_typecode_t  qeoTypeCode;
    json_t              *member_type = json_object_get(member, KEY_TYPE);

    if (!((NULL != member_type) && (json_is_string(member_type)))) {
        qeo_log_e("Could not retrieve type");
        return memberType;
    }

    const char *jsonTypeCode = json_string_value(member_type);

    do {
        if (!strcmp(jsonTypeCode, "boolean")) {
            memberType  = qeocore_type_primitive_new(QEOCORE_TYPECODE_BOOLEAN);
            qeoTypeCode = QEOCORE_TYPECODE_BOOLEAN;
        }
        else if (!strcmp(jsonTypeCode, "byte")) {
            memberType  = qeocore_type_primitive_new(QEOCORE_TYPECODE_INT8);
            qeoTypeCode = QEOCORE_TYPECODE_INT8;
        }
        else if (!strcmp(jsonTypeCode, "int16")) {
            memberType  = qeocore_type_primitive_new(QEOCORE_TYPECODE_INT16);
            qeoTypeCode = QEOCORE_TYPECODE_INT16;
        }
        else if (!strcmp(jsonTypeCode, "int32")) {
            memberType  = qeocore_type_primitive_new(QEOCORE_TYPECODE_INT32);
            qeoTypeCode = QEOCORE_TYPECODE_INT32;
        }
        else if (!strcmp(jsonTypeCode, "int64")) {
            memberType  = qeocore_type_primitive_new(QEOCORE_TYPECODE_INT64);
            qeoTypeCode = QEOCORE_TYPECODE_INT64;
        }
        else if (!strcmp(jsonTypeCode, "float32")) {
            memberType  = qeocore_type_primitive_new(QEOCORE_TYPECODE_FLOAT32);
            qeoTypeCode = QEOCORE_TYPECODE_FLOAT32;
        }
        else if (!strcmp(jsonTypeCode, "string")) {
            size_t size = 0;
            memberType  = qeocore_type_string_new(size);
            qeoTypeCode = QEOCORE_TYPECODE_STRING;
        }
        else if (!strcmp(jsonTypeCode, "object")) {
            json_t *item = json_object_get(member, KEY_ITEM);
            if ((NULL == item) || !json_is_object(item)) {
                qeo_log_e("Could not find item");
                break;
            }
            memberType  = build_object(factory, item);
            qeoTypeCode = QEOCORE_TYPECODE_STRUCT;
        }
        else if (!strcmp(jsonTypeCode, "array")) {
            json_t *items = json_object_get(member, KEY_ITEMS);
            if ((NULL == items) || !json_is_object(items)) {
                qeo_log_e("Could not find items");
                break;
            }

            qeocore_type_t *elemtype = build_member_type(factory, items);
            if (elemtype == NULL){
                qeo_log_e("Could not build member for array");
                break;
            }

            memberType  = qeocore_type_sequence_new(elemtype);
            qeocore_type_free(elemtype);
            qeoTypeCode = QEOCORE_TYPECODE_SEQUENCE;
        }
        else if (!strcmp(jsonTypeCode, "enum")){
            json_t *item = json_object_get(member, KEY_ITEM);
            if ((NULL == item) || !json_is_object(item)) {
                qeo_log_e("Could not find item");
                break;
            }
            memberType  = build_enum(factory, item);
            qeoTypeCode = QEOCORE_TYPECODE_ENUM;

        }
        else {
            qeo_log_e("Unsupported jsonTypeCode %s", jsonTypeCode);
        }
    } while (0);

    if (NULL == memberType) {
        qeo_log_e("Could not make type (%s)", jsonTypeCode);
        return memberType;
    }

    json_object_set_new(member, KEY_QEO_TYPE_CODE, json_integer(qeoTypeCode));

    return memberType;
}
Esempio n. 12
0
static json_t *json_integer_copy(json_t *integer)
{
    return json_integer(json_integer_value(integer));
}
Esempio n. 13
0
Json::Json( int64_t v ): data(json_integer(v))
{
}
Esempio n. 14
0
Json::Json( unsigned v ): data(json_integer(v))
{
}
Esempio n. 15
0
void AsisScript::pre_judge() throw (Exception)
{
    ScriptProps::Property& service_prop = type_spec_props->get_property("service");
    if (!service_prop.Evaluable::finished())
        throw_error_v(ErrorScriptFmtError,"asis producer script service should be determinated");

    ScriptProps::Property& resource_prop = type_spec_props->get_property("resource");
    if (!resource_prop.Evaluable::finished())
        throw_error_v(ErrorScriptFmtError,"asis producer script resource should be determinated");

    json_t* svc_value = service_prop.compile();
    json_t* res_value = resource_prop.compile();
    JsonWrap svc_wrap(svc_value,1);
    JsonWrap res_wrap(res_value,1);

    if ( !svc_value || !json_is_string(svc_value) || !strlen(json_string_value(svc_value)))
        throw_error_v(ErrorScriptFmtError,"asis producer script service should be string value");
    if ( !res_value || !json_is_string(res_value) || !strlen(json_string_value(res_value)))
        throw_error_v(ErrorScriptFmtError,"asis producer script resource should be string value");

    mlt_profile prof = mlt_profile_clone(MltLoader::global_profile);
    mlt_producer tmp_prod = mlt_factory_producer(prof, json_string_value(svc_value), json_string_value(res_value));
    MltSvcWrap prod_wrap(mlt_producer_service(tmp_prod), 1);

    if (tmp_prod == NULL) {
        throw_error_v(ErrorRuntimeLoadFailed, "producer %s load failed", json_string_value(svc_value));
    }

    if ( mlt_props ) {
        ScriptProps::PropIter it = mlt_props->begin();
        for ( ; it!=mlt_props->end(); it++) {
            if ( it->second->Evaluable::finished() ) {
                json_t* prop_v = it->second->compile();
                JsonWrap prop_wrap(prop_v, 1);

                switch(prop_v->type) {
                case JSON_INTEGER:
                    mlt_properties_set_int64(mlt_producer_properties(tmp_prod),
                                             it->first.c_str(), json_integer_value(prop_v));
                    break;
                case JSON_REAL:
                    mlt_properties_set_double(mlt_producer_properties(tmp_prod),
                                              it->first.c_str(), json_real_value(prop_v));
                    break;
                case JSON_STRING:
                    mlt_properties_set(mlt_producer_properties(tmp_prod),
                                       it->first.c_str(), json_string_value(prop_v));
                    break;
                case JSON_TRUE:
                    mlt_properties_set_int(mlt_producer_properties(tmp_prod),
                                           it->first.c_str(), 1);
                    break;
                case JSON_FALSE:
                    mlt_properties_set_int(mlt_producer_properties(tmp_prod),
                                           it->first.c_str(), 0);
                    break;
                default:
                    throw_error_v(ErrorRuntimeLoadFailed, "producer %s load failed. %s prop invalid",
                                  json_string_value(svc_value), it->first.c_str());
                }
            }
        }
    }

    int in = mlt_producer_get_in(tmp_prod);
    int out = mlt_producer_get_out(tmp_prod);
    set_frame_range(in, out);

    if ( !mlt_props.get()) {
        mlt_props.reset(new ScriptProps(*this, NULL));
    }
    json_t* jv = json_integer(in);
    mlt_props->add_property("in", jv);
    json_decref(jv);

    jv = json_integer(out);
    mlt_props->add_property("out", jv);
    json_decref(jv);

    string uuid = Vm::uuid();
    type_spec_props->add_property("uuid", JsonWrap(json_string(uuid.c_str()),1).h);
    prod_wrap.obj = NULL;
    MltLoader::push_mlt_registry(mlt_producer_service(tmp_prod), uuid.c_str());
}
Esempio n. 16
0
void Patch::writeChannels(json_t *jContainer, vector<channel_t> *channels)
{
  json_t *jChannels = json_array();
  for (unsigned i=0; i<channels->size(); i++) {
    json_t    *jChannel = json_object();
    channel_t  channel  = channels->at(i);
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_TYPE,                 json_integer(channel.type));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_INDEX,                json_integer(channel.index));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_COLUMN,               json_integer(channel.column));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MUTE,                 json_integer(channel.mute));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MUTE_S,               json_integer(channel.mute_s));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_SOLO,                 json_integer(channel.solo));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_VOLUME,               json_real(channel.volume));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_PAN_LEFT,             json_real(channel.panLeft));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_PAN_RIGHT,            json_real(channel.panRight));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_IN,              json_boolean(channel.midiIn));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_IN_KEYPRESS,     json_integer(channel.midiInKeyPress));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_IN_KEYREL,       json_integer(channel.midiInKeyRel));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_IN_KILL,         json_integer(channel.midiInKill));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_IN_ARM,          json_integer(channel.midiInArm));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_IN_VOLUME,       json_integer(channel.midiInVolume));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_IN_MUTE,         json_integer(channel.midiInMute));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_IN_SOLO,         json_integer(channel.midiInSolo));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_OUT_L,           json_boolean(channel.midiOutL));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_OUT_L_PLAYING,   json_integer(channel.midiOutLplaying));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_OUT_L_MUTE,      json_integer(channel.midiOutLmute));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_OUT_L_SOLO,      json_integer(channel.midiOutLsolo));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_SAMPLE_PATH,          json_string(channel.samplePath.c_str()));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_KEY,                  json_integer(channel.key));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MODE,                 json_integer(channel.mode));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_BEGIN,                json_integer(channel.begin));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_END,                  json_integer(channel.end));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_BOOST,                json_real(channel.boost));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_REC_ACTIVE,           json_integer(channel.recActive));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_PITCH,                json_real(channel.pitch));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_IN_READ_ACTIONS, json_integer(channel.midiInReadActions));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_IN_PITCH,        json_integer(channel.midiInPitch));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_OUT,             json_integer(channel.midiOut));
    json_object_set_new(jChannel, PATCH_KEY_CHANNEL_MIDI_OUT_CHAN,        json_integer(channel.midiOutChan));
    json_array_append_new(jChannels, jChannel);

    writeActions(jChannel, &channel.actions);

#ifdef WITH_VST

    writePlugins(jChannel, &channel.plugins, PATCH_KEY_CHANNEL_PLUGINS);

#endif
  }
  json_object_set_new(jContainer, PATCH_KEY_CHANNELS, jChannels);
}
Esempio n. 17
0
void VideoScript::pre_judge() throw (Exception)
{
    const ScriptParam* inparam = get_param_info("in");
    const ScriptParam* outparam = get_param_info("out");
    const ScriptParam* resparam = get_param_info("resource");

    if ( !inparam || inparam->param_style != ScriptParams::PosParam ||
            !outparam || outparam->param_style != ScriptParams::PosParam) {
        throw_error_v(ErrorScriptArgInvalid, "in/out position param is required for %s script",
                      Vm::proc_type_names[VIDEO_RESOURCE_SCRIPT]);
    }

    if ( !resparam || resparam->param_style != ScriptParams::ScalarParam ) {
        throw_error_v(ErrorScriptArgInvalid, "resource scalar param is required for %s script",
                      Vm::proc_type_names[VIDEO_RESOURCE_SCRIPT]);
    }

    json_t* res_arg = get_arg_value("resource");
    json_t* in = get_arg_value("in");
    json_t* out = get_arg_value("out");

    if (!res_arg || !json_is_string(res_arg) || !strlen(json_string_value(res_arg))) {
        throw_error_v(ErrorScriptArgInvalid, "resource arg is required for %s script",
                      Vm::proc_type_names[VIDEO_RESOURCE_SCRIPT]);
    }

    if ( !in || !json_is_integer(in) ) {
        throw_error_v(ErrorScriptArgInvalid, "in arg is required for %s script",
                      Vm::proc_type_names[VIDEO_RESOURCE_SCRIPT]);
    }

    if ( !out || !json_is_integer(out) ) {
        throw_error_v(ErrorScriptArgInvalid, "out arg is required for %s script",
                      Vm::proc_type_names[VIDEO_RESOURCE_SCRIPT]);
    }

    string path(json_string_value(res_arg));

    mlt_profile profile = mlt_profile_clone(MltLoader::global_profile);
    mlt_producer prod = mlt_factory_producer(profile, "loader", path.c_str());

    if  ( prod == NULL ) {
        throw_error_v(ErrorScriptArgInvalid, "out arg is required for %s script",
                      Vm::proc_type_names[VIDEO_RESOURCE_SCRIPT]);
    }

    uuid = Vm::uuid();
    MltLoader::push_mlt_registry(mlt_producer_service(prod), uuid.c_str());

    //mlt_producer prod = Vm::get_stream_resource(path);
    int length = mlt_producer_get_length(prod);
    int inframe = json_integer_value(in), outframe = json_integer_value(out);

    json_decref(in);
    json_decref(out);

    switch (inparam->pos_type) {
    case ScriptParams::FramePos:
        if ( inframe == -1  || inframe >= length) {
            inframe = length - 1;
        }
        else if ( inframe < 0 ) {
            inframe = length + inframe;
            if (inframe < 0)inframe = 0;
        }
        break;
    case ScriptParams::TimePos: {
        int total_time = length * 40;
        if ( inframe == -1 ) {
            inframe = length - 1;
        }
        else if ( inframe >= 0  ) {
            if ( inframe > total_time) {
                inframe = length -1;
            }
            else {
                inframe = (double)inframe / 40 ;
            }
        }
        else {
            inframe = total_time + inframe;
            if ( inframe < 0 ) {
                inframe = length - 1;
            }
            else {
                inframe = (double)inframe/40;
            }
        }
    }
    break;
    }


    switch (outparam->pos_type) {
    case ScriptParams::FramePos:
        if ( outframe == -1  || outframe >= length) {
            outframe = length - 1;
        }
        else if ( outframe < 0 ) {
            outframe = length + outframe;
            if (outframe < 0)outframe = 0;
        }
        break;
    case ScriptParams::TimePos: {
        int total_time = length * 40;
        if ( outframe == -1 ) {
            outframe = length - 1;
        }
        else if ( outframe >= 0  ) {
            if ( outframe > total_time) {
                outframe = length -1;
            }
            else {
                outframe = (double)outframe / 40 ;
            }
        }
        else {
            outframe = total_time + outframe;
            if ( outframe < 0 ) {
                outframe = length - 1;
            }
            else {
                outframe = (double)outframe/40;
            }
        }
    }
    break;
    }

    if ( inframe > outframe ) {
        inframe ^= outframe ^= inframe ^= outframe;
    }

    set_frame_range(inframe,outframe);

    if ( !type_spec_props.get() ) {
        type_spec_props.reset(new ScriptProps(*this, NULL));
    }

    type_spec_props->add_property("resource", res_arg);
    json_decref(res_arg);

    type_spec_props->add_property("uuid", JsonWrap(json_string(uuid.c_str()),1).h);
    if ( !mlt_props.get()) {
        mlt_props.reset(new ScriptProps(*this, NULL));
    }
    json_t* jv = json_integer(inframe);
    mlt_props->add_property("in", jv);
    json_decref(jv);

    jv = json_integer(outframe);
    mlt_props->add_property("out", jv);
    json_decref(jv);

    //mlt_producer_set_in_and_out(prod, inframe, outframe);
#ifdef DEBUG
    std::cout << mlt_producer_properties(prod);
#endif

    this->path  = path;
    //todo: check format info
    return;
}
/* Thread to handle incoming messages */
static void *janus_streaming_handler(void *data) {
	JANUS_LOG(LOG_VERB, "Joining thread\n");
	janus_streaming_message *msg = NULL;
	int error_code = 0;
	char *error_cause = calloc(1024, sizeof(char));
	if(error_cause == NULL) {
		JANUS_LOG(LOG_FATAL, "Memory error!\n");
		return NULL;
	}
	while(initialized && !stopping) {
		if(!messages || (msg = g_queue_pop_head(messages)) == NULL) {
			usleep(50000);
			continue;
		}
		janus_streaming_session *session = (janus_streaming_session *)msg->handle->plugin_handle;
		if(!session) {
			JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
			janus_streaming_message_free(msg);
			continue;
		}
		if(session->destroy) {
			janus_streaming_message_free(msg);
			continue;
		}
		/* Handle request */
		error_code = 0;
		JANUS_LOG(LOG_VERB, "Handling message: %s\n", msg->message);
		if(msg->message == NULL) {
			JANUS_LOG(LOG_ERR, "No message??\n");
			error_code = JANUS_STREAMING_ERROR_NO_MESSAGE;
			sprintf(error_cause, "%s", "No message??");
			goto error;
		}
		json_error_t error;
		json_t *root = json_loads(msg->message, 0, &error);
		if(!root) {
			JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
			error_code = JANUS_STREAMING_ERROR_INVALID_JSON;
			sprintf(error_cause, "JSON error: on line %d: %s", error.line, error.text);
			goto error;
		}
		if(!json_is_object(root)) {
			JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
			error_code = JANUS_STREAMING_ERROR_INVALID_JSON;
			sprintf(error_cause, "JSON error: not an object");
			goto error;
		}
		json_t *request = json_object_get(root, "request");
		if(!request) {
			JANUS_LOG(LOG_ERR, "Missing element (request)\n");
			error_code = JANUS_STREAMING_ERROR_MISSING_ELEMENT;
			sprintf(error_cause, "Missing element (request)");
			goto error;
		}
		if(!json_is_string(request)) {
			JANUS_LOG(LOG_ERR, "Invalid element (request should be a string)\n");
			error_code = JANUS_STREAMING_ERROR_INVALID_ELEMENT;
			sprintf(error_cause, "Invalid element (request should be a string)");
			goto error;
		}
		const char *request_text = json_string_value(request);
		json_t *result = NULL;
		char *sdp_type = NULL, *sdp = NULL;
		if(!strcasecmp(request_text, "list")) {
			result = json_object();
			json_t *list = json_array();
			JANUS_LOG(LOG_VERB, "Request for the list of mountpoints\n");
			/* Return a list of all available mountpoints */
			GList *mountpoints_list = g_hash_table_get_values(mountpoints);
			GList *m = mountpoints_list;
			while(m) {
				janus_streaming_mountpoint *mp = (janus_streaming_mountpoint *)m->data;
				json_t *ml = json_object();
				json_object_set_new(ml, "id", json_integer(mp->id));
				json_object_set_new(ml, "description", json_string(mp->description));
				json_object_set_new(ml, "type", json_string(mp->streaming_type == janus_streaming_type_live ? "live" : "on demand"));
				json_array_append_new(list, ml);
				m = m->next;
			}
			json_object_set_new(result, "list", list);
			g_list_free(mountpoints_list);
		} else if(!strcasecmp(request_text, "watch")) {
			json_t *id = json_object_get(root, "id");
			if(id && !json_is_integer(id)) {
				JANUS_LOG(LOG_ERR, "Invalid element (id should be an integer)\n");
				error_code = JANUS_STREAMING_ERROR_INVALID_ELEMENT;
				sprintf(error_cause, "Invalid element (id should be an integer)");
				goto error;
			}
			gint64 id_value = json_integer_value(id);
			janus_streaming_mountpoint *mp = g_hash_table_lookup(mountpoints, GINT_TO_POINTER(id_value));
			if(mp == NULL) {
				JANUS_LOG(LOG_VERB, "No such mountpoint/stream %"SCNu64"\n", id_value);
				error_code = JANUS_STREAMING_ERROR_NO_SUCH_MOUNTPOINT;
				sprintf(error_cause, "No such mountpoint/stream %"SCNu64"", id_value);
				goto error;
			}
			JANUS_LOG(LOG_VERB, "Request to watch mountpoint/stream %"SCNu64"\n", id_value);
			session->stopping = FALSE;
			session->mountpoint = mp;
			if(mp->streaming_type == janus_streaming_type_on_demand) {
				g_thread_new(session->mountpoint->name, &janus_streaming_ondemand_thread, session);
			}
			/* TODO Check if user is already watching a stream, if the video is active, etc. */
			mp->listeners = g_list_append(mp->listeners, session);
			sdp_type = "offer";	/* We're always going to do the offer ourselves, never answer */
			char sdptemp[1024];
			memset(sdptemp, 0, 1024);
			gchar buffer[100];
			memset(buffer, 0, 100);
			gint64 sessid = janus_get_monotonic_time();
			gint64 version = sessid;	/* FIXME This needs to be increased when it changes, so time should be ok */
			g_sprintf(buffer,
				"v=0\r\no=%s %"SCNu64" %"SCNu64" IN IP4 127.0.0.1\r\n",
					"-", sessid, version);
			g_strlcat(sdptemp, buffer, 1024);
			g_strlcat(sdptemp, "s=Streaming Test\r\nt=0 0\r\n", 1024);
			if(mp->codecs.audio_pt >= 0) {
				/* Add audio line */
				g_sprintf(buffer,
					"m=audio 1 RTP/SAVPF %d\r\n"
					"c=IN IP4 1.1.1.1\r\n",
					mp->codecs.audio_pt);
				g_strlcat(sdptemp, buffer, 1024);
				if(mp->codecs.audio_rtpmap) {
					g_sprintf(buffer,
						"a=rtpmap:%d %s\r\n",
						mp->codecs.audio_pt, mp->codecs.audio_rtpmap);
					g_strlcat(sdptemp, buffer, 1024);
				}
				g_strlcat(sdptemp, "a=sendonly\r\n", 1024);
			}
			if(mp->codecs.video_pt >= 0) {
				/* Add video line */
				g_sprintf(buffer,
					"m=video 1 RTP/SAVPF %d\r\n"
					"c=IN IP4 1.1.1.1\r\n",
					mp->codecs.video_pt);
				g_strlcat(sdptemp, buffer, 1024);
				if(mp->codecs.video_rtpmap) {
					g_sprintf(buffer,
						"a=rtpmap:%d %s\r\n",
						mp->codecs.video_pt, mp->codecs.video_rtpmap);
					g_strlcat(sdptemp, buffer, 1024);
				}
				g_strlcat(sdptemp, "a=sendonly\r\n", 1024);
			}
			sdp = g_strdup(sdptemp);
			JANUS_LOG(LOG_VERB, "Going to offer this SDP:\n%s\n", sdp);
			result = json_object();
			json_object_set_new(result, "status", json_string("preparing"));
		} else if(!strcasecmp(request_text, "start")) {
			JANUS_LOG(LOG_VERB, "Starting the streaming\n");
			result = json_object();
			/* We wait for the setup_media event to start: on the other hand, it may have already arrived */
			json_object_set_new(result, "status", json_string(session->started ? "started" : "starting"));
		} else if(!strcasecmp(request_text, "pause")) {
			JANUS_LOG(LOG_VERB, "Pausing the streaming\n");
			session->started = FALSE;
			result = json_object();
			json_object_set_new(result, "status", json_string("pausing"));
		} else if(!strcasecmp(request_text, "stop")) {
			JANUS_LOG(LOG_VERB, "Stopping the streaming\n");
			session->stopping = TRUE;
			session->started = FALSE;
			result = json_object();
			json_object_set_new(result, "status", json_string("stopping"));
			if(session->mountpoint) {
				JANUS_LOG(LOG_VERB, "  -- Removing the session from the mountpoint listeners\n");
				if(g_list_find(session->mountpoint->listeners, session) != NULL) {
					JANUS_LOG(LOG_VERB, "  -- -- Found!\n");
				}
				session->mountpoint->listeners = g_list_remove_all(session->mountpoint->listeners, session);
			}
			session->mountpoint = NULL;
		} else {
			JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
			error_code = JANUS_STREAMING_ERROR_INVALID_REQUEST;
			sprintf(error_cause, "Unknown request '%s'", request_text);
			goto error;
		}
		
		/* Any SDP to handle? */
		if(msg->sdp) {
			JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well (but we really don't care):\n%s\n", msg->sdp_type, msg->sdp);
		}

		json_decref(root);
		/* Prepare JSON event */
		json_t *event = json_object();
		json_object_set_new(event, "streaming", json_string("event"));
		if(result != NULL)
			json_object_set(event, "result", result);
		char *event_text = json_dumps(event, JSON_INDENT(3));
		json_decref(event);
		if(result != NULL)
			json_decref(result);
		JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
		int ret = gateway->push_event(msg->handle, &janus_streaming_plugin, msg->transaction, event_text, sdp_type, sdp);
		JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
		g_free(event_text);
		if(sdp)
			g_free(sdp);
		janus_streaming_message_free(msg);
		continue;
		
error:
		{
			if(root != NULL)
				json_decref(root);
			/* Prepare JSON error event */
			json_t *event = json_object();
			json_object_set_new(event, "streaming", json_string("event"));
			json_object_set_new(event, "error_code", json_integer(error_code));
			json_object_set_new(event, "error", json_string(error_cause));
			char *event_text = json_dumps(event, JSON_INDENT(3));
			json_decref(event);
			JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
			int ret = gateway->push_event(msg->handle, &janus_streaming_plugin, msg->transaction, event_text, NULL, NULL);
			JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
			g_free(event_text);
			janus_streaming_message_free(msg);
		}
	}
	g_free(error_cause);
	JANUS_LOG(LOG_VERB, "Leaving thread\n");
	return NULL;
}
Esempio n. 19
0
/*====================================================================
 * 函数名    : vGenMCUINFOMsg
 * 功能      : 12.1	MCU上报逻辑服务器基本信息消息
 * 算法实现  : 
 * 参数说明  : vpd 要上报的设备
 * 返回值说明: 成功 生成的消息
 *			   失败 NULL             
 * ----------------------------------------------------------------------
 * 修改记录:
 * 日  期        版本        修改人        走读人        修改记录
 * 2015/1/26       v1.0        YLI                          创建
 * ====================================================================*/
json_t * vGenMCUINFOMsg(VPD vpd)
{
	json_t *root;
	json_t *mcuinfo;
	int res;
	char saLocalTime[256];

	root = json_object();
	//eventid
	if (json_object_set(root,"eventid",
		json_string("EV_MCU_INFO")) == FAILUER)
	{
		json_decref(root);
		vLogErr("eventid set error!!!");
		return NULL;
	}
	//devid
	if (json_object_set(root,"devid",
		json_string(vpd.saDevId)) == FAILUER)
	{
		json_decref(root);
		vLogErr("devtype set error!!!");
		return NULL;
	}
	//devtype
	if (json_object_set(root,"devtype",
		json_string(vpd.saDevType)) == FAILUER)
	{
		json_decref(root);
		vLogErr("devtype set error!!!");
		return NULL;
	}
	//rpttime
	memset(saLocalTime,0x00,sizeof saLocalTime);
	GetLocalTime(saLocalTime);
	if (json_object_set(root,"rpttime",
		json_string(saLocalTime)) == FAILUER)
	{
		json_decref(root);
		vLogErr("rpttime set error!!!");
		return NULL;
	}
	//pidchange
	json_object_set(root,"pidchange",json_false());
	//version
	json_object_set(root,"version",json_string("1.06"));
	//belongphy
	json_object_set(root,"belongphy",json_string("1123"));
	/*mcuinfo*/
	mcuinfo = json_object();
	//traditionconfcount
	json_object_set(mcuinfo,"traditionconfcount",json_integer(123));
	//portconfcount
	json_object_set(mcuinfo,"portconfcount",json_integer(123));
	//spttraditionconfcount
	json_object_set(mcuinfo,"spttraditionconfcount",json_integer(123));
	//sptportconfcount
	json_object_set(mcuinfo,"sptportconfcount",json_integer(123));
	//multiconfmtcount
	json_object_set(mcuinfo,"multiconfmtcount",json_integer(123));
	//connectedmpcd
	json_object_set(mcuinfo,"connectedmpcd",json_true());
	//connectedbmc
	json_object_set(mcuinfo,"connectedbmc",json_true());
	//connectednucount
	json_object_set(mcuinfo,"connectednucount",json_integer(123));
	//connectedmpcount
	json_object_set(mcuinfo,"connectedmpcount",json_integer(123));
	//connectedmpcadaptcount
	json_object_set(mcuinfo,"connectedmpcadaptcount",json_integer(123));
	//connectedprscount
	json_object_set(mcuinfo,"connectedprscount",json_integer(123));
	
	//connectednuinfo
	res = json_object_set(mpcdinfo,"connectednuinfo",
		json_pack("[{s:b,s:s},{s:b,s:s}]",
			"connectedstate",1,
			"connectedip",_gstrpShm->rc.nSrvIP,
			"connectedstate",1,
			"connectedip",_gstrpShm->rc.nSrvIP));

	if (res == FAILUER)
	{
		json_decref(root);
		vLogErr("connectednuinfo set error!!!");
		return NULL;
	}
	//connectedmpinfo
	res = json_object_set(mpcdinfo,"connectedmpinfo",
		json_pack("[{s:b,s:s},{s:b,s:s}]",
			"connectedstate",1,
			"connectedip",_gstrpShm->rc.nSrvIP,
			"connectedstate",1,
			"connectedip",_gstrpShm->rc.nSrvIP));

	if (res == FAILUER)
	{
		json_decref(root);
		vLogErr("connectedmpinfo set error!!!");
		return NULL;
	}
	//connectedmpcadaptinfo
	res = json_object_set(mpcdinfo,"connectedmpcadaptinfo",
		json_pack("[{s:b,s:s},{s:b,s:s}]",
			"connectedstate",1,
			"connectedip",_gstrpShm->rc.nSrvIP,
			"connectedstate",1,
			"connectedip",_gstrpShm->rc.nSrvIP));

	if (res == FAILUER)
	{
		json_decref(root);
		vLogErr("connectedmpcadaptinfo set error!!!");
		return NULL;
	}
	//connectedprsinfo
	res = json_object_set(mpcdinfo,"connectedprsinfo",
		json_pack("[{s:b,s:s},{s:b,s:s}]",
			"connectedstate",1,
			"connectedip",_gstrpShm->rc.nSrvIP,
			"connectedstate",1,
			"connectedip",_gstrpShm->rc.nSrvIP));

	if (res == FAILUER)
	{
		json_decref(root);
		vLogErr("connectedprsinfo set error!!!");
		return NULL;
	}
	json_object_set(root,"mpcdinfo",mpcdinfo);
	json_decref(mpcdinfo);

	return root;
}
Esempio n. 20
0
/* Call the simple functions not covered by other tests of the public API */
static void run_tests()
{
    json_t *value;

    value = json_boolean(1);
    if(!json_is_true(value))
        fail("json_boolean(1) failed");
    json_decref(value);

    value = json_boolean(-123);
    if(!json_is_true(value))
        fail("json_boolean(-123) failed");
    json_decref(value);

    value = json_boolean(0);
    if(!json_is_false(value))
        fail("json_boolean(0) failed");
    json_decref(value);


    value = json_integer(1);
    if(json_typeof(value) != JSON_INTEGER)
        fail("json_typeof failed");

    if(json_is_object(value))
        fail("json_is_object failed");

    if(json_is_array(value))
        fail("json_is_array failed");

    if(json_is_string(value))
        fail("json_is_string failed");

    if(!json_is_integer(value))
        fail("json_is_integer failed");

    if(json_is_real(value))
        fail("json_is_real failed");

    if(!json_is_number(value))
        fail("json_is_number failed");

    if(json_is_true(value))
        fail("json_is_true failed");

    if(json_is_false(value))
        fail("json_is_false failed");

    if(json_is_boolean(value))
        fail("json_is_boolean failed");

    if(json_is_null(value))
        fail("json_is_null failed");

    json_decref(value);


    value = json_string("foo");
    if(!value)
        fail("json_string failed");
    if(strcmp(json_string_value(value), "foo"))
        fail("invalid string value");
    if (json_string_length(value) != 3)
        fail("invalid string length");

    if(json_string_set(value, "barr"))
        fail("json_string_set failed");
    if(strcmp(json_string_value(value), "barr"))
        fail("invalid string value");
    if (json_string_length(value) != 4)
        fail("invalid string length");

    if(json_string_setn(value, "hi\0ho", 5))
        fail("json_string_set failed");
    if(memcmp(json_string_value(value), "hi\0ho\0", 6))
        fail("invalid string value");
    if (json_string_length(value) != 5)
        fail("invalid string length");

    json_decref(value);

    value = json_string(NULL);
    if(value)
        fail("json_string(NULL) failed");

    /* invalid UTF-8  */
    value = json_string("a\xefz");
    if(value)
        fail("json_string(<invalid utf-8>) failed");

    value = json_string_nocheck("foo");
    if(!value)
        fail("json_string_nocheck failed");
    if(strcmp(json_string_value(value), "foo"))
        fail("invalid string value");
    if (json_string_length(value) != 3)
        fail("invalid string length");

    if(json_string_set_nocheck(value, "barr"))
        fail("json_string_set_nocheck failed");
    if(strcmp(json_string_value(value), "barr"))
        fail("invalid string value");
    if (json_string_length(value) != 4)
        fail("invalid string length");

    if(json_string_setn_nocheck(value, "hi\0ho", 5))
        fail("json_string_set failed");
    if(memcmp(json_string_value(value), "hi\0ho\0", 6))
        fail("invalid string value");
    if (json_string_length(value) != 5)
        fail("invalid string length");

    json_decref(value);

    /* invalid UTF-8 */
    value = json_string_nocheck("qu\xff");
    if(!value)
        fail("json_string_nocheck failed");
    if(strcmp(json_string_value(value), "qu\xff"))
        fail("invalid string value");
    if (json_string_length(value) != 3)
        fail("invalid string length");

    if(json_string_set_nocheck(value, "\xfd\xfe\xff"))
        fail("json_string_set_nocheck failed");
    if(strcmp(json_string_value(value), "\xfd\xfe\xff"))
        fail("invalid string value");
    if (json_string_length(value) != 3)
        fail("invalid string length");

    json_decref(value);


    value = json_integer(123);
    if(!value)
        fail("json_integer failed");
    if(json_integer_value(value) != 123)
        fail("invalid integer value");
    if(json_number_value(value) != 123.0)
        fail("invalid number value");

    if(json_integer_set(value, 321))
        fail("json_integer_set failed");
    if(json_integer_value(value) != 321)
        fail("invalid integer value");
    if(json_number_value(value) != 321.0)
        fail("invalid number value");

    json_decref(value);

    value = json_real(123.123);
    if(!value)
        fail("json_real failed");
    if(json_real_value(value) != 123.123)
        fail("invalid integer value");
    if(json_number_value(value) != 123.123)
        fail("invalid number value");

    if(json_real_set(value, 321.321))
        fail("json_real_set failed");
    if(json_real_value(value) != 321.321)
        fail("invalid real value");
    if(json_number_value(value) != 321.321)
        fail("invalid number value");

    json_decref(value);

    value = json_true();
    if(!value)
        fail("json_true failed");
    json_decref(value);

    value = json_false();
    if(!value)
        fail("json_false failed");
    json_decref(value);

    value = json_null();
    if(!value)
        fail("json_null failed");
    json_decref(value);

    /* Test reference counting on singletons (true, false, null) */
    value = json_true();
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");

    value = json_false();
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");

    value = json_null();
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");
}
Esempio n. 21
0
/*====================================================================
 * 函数名    : vGenPFMINFONETCARDMsg
 * 功能      : 主动上报设备NETCARD性能
 * 算法实现  : 
 * 参数说明  : vpd 要上报的设备
 * 返回值说明: 成功 生成的消息
 *			   失败 NULL             
 * ----------------------------------------------------------------------
 * 修改记录:
 * 日  期        版本        修改人        走读人        修改记录
 * 2015/1/21       v1.0        YLI                          创建
 * ====================================================================*/
json_t * vGenPFMINFONETCARDMsg(VPD vpd)
{
	json_t *root;
	json_t *netcardinfo;
	json_t *netcards;
	char saLocalTime[256];
	root = json_object();
	//devid
	if (json_object_set(root,"devid",
		json_string(vpd.saDevId)) == FAILUER)
	{
		json_decref(root);
		vLogErr("devid set error!!!");
		return NULL;
	}
	//devtype
	if (json_object_set(root,"devtype",
		json_string(vpd.saDevType)) == FAILUER)
	{
		json_decref(root);
		vLogErr("devtype set error!!!");
		return NULL;
	}
	//eventid
	if (json_object_set(root,"eventid",
		json_string("EV_PFMINFO_NETCARD")) == FAILUER)
	{
		json_decref(root);
		vLogErr("eventid set error!!!");
		return NULL;
	}
	//rpttime
	memset(saLocalTime,0x00,sizeof saLocalTime);
	GetLocalTime(saLocalTime);
	json_object_set(root,"rpttime",json_string(saLocalTime));

	/*netcardinfo*/
	netcardinfo = json_object();
	//netcardcount
	json_object_set(netcardinfo,"netcardcount",json_integer(3));
	//sendkbps
	json_object_set(netcardinfo,"sendkbps",json_integer(3000));
	//recvkbps
	json_object_set(netcardinfo,"recvkbps",json_integer(3000));
	//recvpktloserate
	json_object_set(netcardinfo,"recvpktloserate",json_integer(3));
	//netcards
	netcards = json_array();

	json_array_insert(netcards,0,
		json_pack("{s:{s:i,s:i,s:i}}",
				"netcard1",
				"sendkbps",234,
				"recvkbps",234,
				"recvpktloserate",23));

	json_array_insert(netcards,1,
		json_pack("{s:{s:i,s:i,s:i}}",
				"netcard2",
				"sendkbps",234,
				"recvkbps",234,
				"recvpktloserate",23));

	json_array_insert(netcards,2,
		json_pack("{s:{s:i,s:i,s:i}}",
				"netcard3",
				"sendkbps",234,
				"recvkbps",234,
				"recvpktloserate",23));

	json_object_set(netcardinfo,"netcards",netcards);
	json_object_set(root,"netcardinfo",netcardinfo);
	json_decref(netcards);
	json_decref(netcardinfo);
	return root;
}
Esempio n. 22
0
static void test_misc(void)
{
    json_t *array, *five, *seven, *value;
    int i;

    array = json_array();
    five = json_integer(5);
    seven = json_integer(7);

    if(!array)
        fail("unable to create array");
    if(!five || !seven)
        fail("unable to create integer");

    if(json_array_size(array) != 0)
        fail("empty array has nonzero size");

    if(!json_array_append(array, NULL))
        fail("able to append NULL");

    if(json_array_append(array, five))
        fail("unable to append");

    if(json_array_size(array) != 1)
        fail("wrong array size");

    value = json_array_get(array, 0);
    if(!value)
        fail("unable to get item");
    if(value != five)
        fail("got wrong value");

    if(json_array_append(array, seven))
        fail("unable to append value");

    if(json_array_size(array) != 2)
        fail("wrong array size");

    value = json_array_get(array, 1);
    if(!value)
        fail("unable to get item");
    if(value != seven)
        fail("got wrong value");

    if(json_array_set(array, 0, seven))
        fail("unable to set value");

    if(!json_array_set(array, 0, NULL))
        fail("able to set NULL");

    if(json_array_size(array) != 2)
        fail("wrong array size");

    value = json_array_get(array, 0);
    if(!value)
        fail("unable to get item");
    if(value != seven)
        fail("got wrong value");

    if(json_array_get(array, 2) != NULL)
        fail("able to get value out of bounds");

    if(!json_array_set(array, 2, seven))
        fail("able to set value out of bounds");

    for(i = 2; i < 30; i++) {
        if(json_array_append(array, seven))
            fail("unable to append value");

        if(json_array_size(array) != i + 1)
            fail("wrong array size");
    }

    for(i = 0; i < 30; i++) {
        value = json_array_get(array, i);
        if(!value)
            fail("unable to get item");
        if(value != seven)
            fail("got wrong value");
    }

    if(json_array_set_new(array, 15, json_integer(123)))
        fail("unable to set new value");

    value = json_array_get(array, 15);
    if(!json_is_integer(value) || json_integer_value(value) != 123)
        fail("json_array_set_new works incorrectly");

    if(!json_array_set_new(array, 15, NULL))
        fail("able to set_new NULL value");

    if(json_array_append_new(array, json_integer(321)))
        fail("unable to append new value");

    value = json_array_get(array, json_array_size(array) - 1);
    if(!json_is_integer(value) || json_integer_value(value) != 321)
        fail("json_array_append_new works incorrectly");

    if(!json_array_append_new(array, NULL))
        fail("able to append_new NULL value");

    json_decref(five);
    json_decref(seven);
    json_decref(array);
}
Esempio n. 23
0
static int AlertJson(ThreadVars *tv, JsonAlertLogThread *aft, const Packet *p)
{
    MemBuffer *payload = aft->payload_buffer;
    AlertJsonOutputCtx *json_output_ctx = aft->json_output_ctx;
    json_t *hjs = NULL;

    int i;

    if (p->alerts.cnt == 0 && !(p->flags & PKT_HAS_TAG))
        return TM_ECODE_OK;

    json_t *js = CreateJSONHeader((Packet *)p, 0, "alert");
    if (unlikely(js == NULL))
        return TM_ECODE_OK;

    for (i = 0; i < p->alerts.cnt; i++) {
        const PacketAlert *pa = &p->alerts.alerts[i];
        if (unlikely(pa->s == NULL)) {
            continue;
        }

        MemBufferReset(aft->json_buffer);

        /* alert */
        AlertJsonHeader(p, pa, js);

        if (json_output_ctx->flags & LOG_JSON_HTTP) {
            if (p->flow != NULL) {
                uint16_t proto = FlowGetAppProtocol(p->flow);

                /* http alert */
                if (proto == ALPROTO_HTTP) {
                    hjs = JsonHttpAddMetadata(p->flow, pa->tx_id);
                    if (hjs)
                        json_object_set_new(js, "http", hjs);
                }
            }
        }

        if (json_output_ctx->flags & LOG_JSON_TLS) {
            if (p->flow != NULL) {
                uint16_t proto = FlowGetAppProtocol(p->flow);

                /* http alert */
                if (proto == ALPROTO_TLS)
                    AlertJsonTls(p->flow, js);
            }
        }

        if (json_output_ctx->flags & LOG_JSON_SSH) {
            if (p->flow != NULL) {
                uint16_t proto = FlowGetAppProtocol(p->flow);

                /* http alert */
                if (proto == ALPROTO_SSH)
                    AlertJsonSsh(p->flow, js);
            }
        }

        if (json_output_ctx->flags & LOG_JSON_SMTP) {
            if (p->flow != NULL) {
                uint16_t proto = FlowGetAppProtocol(p->flow);

                /* http alert */
                if (proto == ALPROTO_SMTP) {
                    hjs = JsonSMTPAddMetadata(p->flow, pa->tx_id);
                    if (hjs)
                        json_object_set_new(js, "smtp", hjs);

                    hjs = JsonEmailAddMetadata(p->flow, pa->tx_id);
                    if (hjs)
                        json_object_set_new(js, "email", hjs);
                }
            }
        }

        /* payload */
        if (json_output_ctx->flags & (LOG_JSON_PAYLOAD | LOG_JSON_PAYLOAD_BASE64)) {
            int stream = (p->proto == IPPROTO_TCP) ?
                         (pa->flags & (PACKET_ALERT_FLAG_STATE_MATCH | PACKET_ALERT_FLAG_STREAM_MATCH) ?
                         1 : 0) : 0;

            /* Is this a stream?  If so, pack part of it into the payload field */
            if (stream) {
                uint8_t flag;

                MemBufferReset(payload);

                if (p->flowflags & FLOW_PKT_TOSERVER) {
                    flag = FLOW_PKT_TOCLIENT;
                } else {
                    flag = FLOW_PKT_TOSERVER;
                }

                StreamSegmentForEach((const Packet *)p, flag,
                                    AlertJsonDumpStreamSegmentCallback,
                                    (void *)payload);

                if (json_output_ctx->flags & LOG_JSON_PAYLOAD_BASE64) {
                    unsigned long len = json_output_ctx->payload_buffer_size * 2;
                    uint8_t encoded[len];
                    Base64Encode(payload->buffer, payload->offset, encoded, &len);
                    json_object_set_new(js, "payload", json_string((char *)encoded));
                }

                if (json_output_ctx->flags & LOG_JSON_PAYLOAD) {
                    uint8_t printable_buf[payload->offset + 1];
                    uint32_t offset = 0;
                    PrintStringsToBuffer(printable_buf, &offset,
                                     sizeof(printable_buf),
                                     payload->buffer, payload->offset);
                    json_object_set_new(js, "payload_printable",
                                        json_string((char *)printable_buf));
                }
            } else {
                /* This is a single packet and not a stream */
                if (json_output_ctx->flags & LOG_JSON_PAYLOAD_BASE64) {
                    unsigned long len = p->payload_len * 2 + 1;
                    uint8_t encoded[len];
                    Base64Encode(p->payload, p->payload_len, encoded, &len);
                    json_object_set_new(js, "payload", json_string((char *)encoded));
                }

                if (json_output_ctx->flags & LOG_JSON_PAYLOAD) {
                    uint8_t printable_buf[p->payload_len + 1];
                    uint32_t offset = 0;
                    PrintStringsToBuffer(printable_buf, &offset,
                                     p->payload_len + 1,
                                     p->payload, p->payload_len);
                    json_object_set_new(js, "payload_printable", json_string((char *)printable_buf));
                }
            }

            json_object_set_new(js, "stream", json_integer(stream));
        }

        /* base64-encoded full packet */
        if (json_output_ctx->flags & LOG_JSON_PACKET) {
            AlertJsonPacket(p, js);
        }

        HttpXFFCfg *xff_cfg = json_output_ctx->xff_cfg;

        /* xff header */
        if ((xff_cfg != NULL) && !(xff_cfg->flags & XFF_DISABLED) && p->flow != NULL) {
            int have_xff_ip = 0;
            char buffer[XFF_MAXLEN];

            if (FlowGetAppProtocol(p->flow) == ALPROTO_HTTP) {
                if (pa->flags & PACKET_ALERT_FLAG_TX) {
                    have_xff_ip = HttpXFFGetIPFromTx(p, pa->tx_id, xff_cfg, buffer, XFF_MAXLEN);
                } else {
                    have_xff_ip = HttpXFFGetIP(p, xff_cfg, buffer, XFF_MAXLEN);
                }
            }

            if (have_xff_ip) {
                if (xff_cfg->flags & XFF_EXTRADATA) {
                    json_object_set_new(js, "xff", json_string(buffer));
                }
                else if (xff_cfg->flags & XFF_OVERWRITE) {
                    if (p->flowflags & FLOW_PKT_TOCLIENT) {
                        json_object_set(js, "dest_ip", json_string(buffer));
                    } else {
                        json_object_set(js, "src_ip", json_string(buffer));
                    }
                }
            }
        }

        OutputJSONBuffer(js, aft->file_ctx, &aft->json_buffer);
        json_object_del(js, "alert");
    }
    json_object_clear(js);
    json_decref(js);

    if ((p->flags & PKT_HAS_TAG) && (json_output_ctx->flags &
            LOG_JSON_TAGGED_PACKETS)) {
        MemBufferReset(aft->json_buffer);
        json_t *packetjs = CreateJSONHeader((Packet *)p, 0, "packet");
        if (unlikely(packetjs != NULL)) {
            AlertJsonPacket(p, packetjs);
            OutputJSONBuffer(packetjs, aft->file_ctx, &aft->json_buffer);
            json_decref(packetjs);
        }
    }

    return TM_ECODE_OK;
}
Esempio n. 24
0
static void test_insert(void)
{
    json_t *array, *five, *seven, *eleven, *value;
    int i;

    array = json_array();
    five = json_integer(5);
    seven = json_integer(7);
    eleven = json_integer(11);

    if(!array)
        fail("unable to create array");
    if(!five || !seven || !eleven)
        fail("unable to create integer");


    if(!json_array_insert(array, 1, five))
        fail("able to insert value out of bounds");


    if(json_array_insert(array, 0, five))
        fail("unable to insert value in an empty array");

    if(json_array_get(array, 0) != five)
        fail("json_array_insert works incorrectly");

    if(json_array_size(array) != 1)
        fail("array size is invalid after insertion");


    if(json_array_insert(array, 1, seven))
        fail("unable to insert value at the end of an array");

    if(json_array_get(array, 0) != five)
        fail("json_array_insert works incorrectly");

    if(json_array_get(array, 1) != seven)
        fail("json_array_insert works incorrectly");

    if(json_array_size(array) != 2)
        fail("array size is invalid after insertion");


    if(json_array_insert(array, 1, eleven))
        fail("unable to insert value in the middle of an array");

    if(json_array_get(array, 0) != five)
        fail("json_array_insert works incorrectly");

    if(json_array_get(array, 1) != eleven)
        fail("json_array_insert works incorrectly");

    if(json_array_get(array, 2) != seven)
        fail("json_array_insert works incorrectly");

    if(json_array_size(array) != 3)
        fail("array size is invalid after insertion");


    if(json_array_insert_new(array, 2, json_integer(123)))
        fail("unable to insert value in the middle of an array");

    value = json_array_get(array, 2);
    if(!json_is_integer(value) || json_integer_value(value) != 123)
        fail("json_array_insert_new works incorrectly");

    if(json_array_size(array) != 4)
        fail("array size is invalid after insertion");


    for(i = 0; i < 20; i++) {
        if(json_array_insert(array, 0, seven))
            fail("unable to insert value at the begining of an array");
    }

    for(i = 0; i < 20; i++) {
        if(json_array_get(array, i) != seven)
            fail("json_aray_insert works incorrectly");
    }

    if(json_array_size(array) != 24)
        fail("array size is invalid after loop insertion");

    json_decref(five);
    json_decref(seven);
    json_decref(eleven);
    json_decref(array);
}
Esempio n. 25
0
int janus_recorder_save_frame(janus_recorder *recorder, char *buffer, uint length) {
	if(!recorder)
		return -1;
	janus_mutex_lock_nodebug(&recorder->mutex);
	if(!buffer || length < 1) {
		janus_mutex_unlock_nodebug(&recorder->mutex);
		return -2;
	}
	if(!recorder->file) {
		janus_mutex_unlock_nodebug(&recorder->mutex);
		return -3;
	}
	if(!g_atomic_int_get(&recorder->writable)) {
		janus_mutex_unlock_nodebug(&recorder->mutex);
		return -4;
	}
	if(!g_atomic_int_get(&recorder->header)) {
		/* Write info header as a JSON formatted info */
		json_t *info = json_object();
		/* FIXME Codecs should be configurable in the future */
		const char *type = NULL;
		if(recorder->type == JANUS_RECORDER_AUDIO)
			type = "a";
		else if(recorder->type == JANUS_RECORDER_VIDEO)
			type = "v";
		else if(recorder->type == JANUS_RECORDER_DATA)
			type = "d";
		json_object_set_new(info, "t", json_string(type));								/* Audio/Video/Data */
		json_object_set_new(info, "c", json_string(recorder->codec));					/* Media codec */
		json_object_set_new(info, "s", json_integer(recorder->created));				/* Created time */
		json_object_set_new(info, "u", json_integer(janus_get_real_time()));			/* First frame written time */
		gchar *info_text = json_dumps(info, JSON_PRESERVE_ORDER);
		json_decref(info);
		uint16_t info_bytes = htons(strlen(info_text));
		fwrite(&info_bytes, sizeof(uint16_t), 1, recorder->file);
		fwrite(info_text, sizeof(char), strlen(info_text), recorder->file);
		free(info_text);
		/* Done */
		g_atomic_int_set(&recorder->header, 1);
	}
	/* Write frame header */
	fwrite(frame_header, sizeof(char), strlen(frame_header), recorder->file);
	uint16_t header_bytes = htons(recorder->type == JANUS_RECORDER_DATA ? (length+sizeof(gint64)) : length);
	fwrite(&header_bytes, sizeof(uint16_t), 1, recorder->file);
	if(recorder->type == JANUS_RECORDER_DATA) {
		/* If it's data, then we need to prepend timing related info, as it's not there by itself */
		gint64 now = htonll(janus_get_real_time());
		fwrite(&now, sizeof(gint64), 1, recorder->file);
	}
	/* Save packet on file */
	int temp = 0, tot = length;
	while(tot > 0) {
		temp = fwrite(buffer+length-tot, sizeof(char), tot, recorder->file);
		if(temp <= 0) {
			JANUS_LOG(LOG_ERR, "Error saving frame...\n");
			janus_mutex_unlock_nodebug(&recorder->mutex);
			return -5;
		}
		tot -= temp;
	}
	/* Done */
	janus_mutex_unlock_nodebug(&recorder->mutex);
	return 0;
}
Esempio n. 26
0
void janus_serial_slow_link(janus_plugin_session *handle, int uplink, int video) {
	/* The core is informing us that our peer got or sent too many NACKs, are we pushing media too hard? */
	if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
		return;
	janus_serial_session *session = (janus_serial_session *)handle->plugin_handle;	
	if(!session) {
		JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
		return;
	}
	if(session->destroyed)
		return;
	session->slowlink_count++;
	if(uplink && !video && !session->audio_active) {
		/* We're not relaying audio and the peer is expecting it, so NACKs are normal */
		JANUS_LOG(LOG_VERB, "Getting a lot of NACKs (slow uplink) for audio, but that's expected, a configure disabled the audio forwarding\n");
	} else if(uplink && video && !session->video_active) {
		/* We're not relaying video and the peer is expecting it, so NACKs are normal */
		JANUS_LOG(LOG_VERB, "Getting a lot of NACKs (slow uplink) for video, but that's expected, a configure disabled the video forwarding\n");
	} else {
		/* Slow uplink or downlink, maybe we set the bitrate cap too high? */
		if(video) {
			/* Halve the bitrate, but don't go too low... */
			session->bitrate = session->bitrate > 0 ? session->bitrate : 512*1024;
			session->bitrate = session->bitrate/2;
			if(session->bitrate < 64*1024)
				session->bitrate = 64*1024;
			JANUS_LOG(LOG_WARN, "Getting a lot of NACKs (slow %s) for %s, forcing a lower REMB: %"SCNu64"\n",
				uplink ? "uplink" : "downlink", video ? "video" : "audio", session->bitrate);
			/* ... and send a new REMB back */
			char rtcpbuf[200];
			memset(rtcpbuf, 0, 200);
			/* FIXME First put a RR (fake)... */
			int rrlen = 32;
			rtcp_rr *rr = (rtcp_rr *)&rtcpbuf;
			rr->header.version = 2;
			rr->header.type = RTCP_RR;
			rr->header.rc = 1;
			rr->header.length = htons((rrlen/4)-1);
			/* ... then put a SDES... */
			int sdeslen = janus_rtcp_sdes((char *)(&rtcpbuf)+rrlen, 200-rrlen, "janusvideo", 10);
			if(sdeslen > 0) {
				/* ... and then finally a REMB */
				janus_rtcp_remb((char *)(&rtcpbuf)+rrlen+sdeslen, 24, session->bitrate);
				gateway->relay_rtcp(handle, 1, rtcpbuf, rrlen+sdeslen+24);
			}
			/* As a last thing, notify the user about this */
			json_t *event = json_object();
			json_object_set_new(event, "serial", json_string("event"));
			json_t *result = json_object();
			json_object_set_new(result, "status", json_string("slow_link"));
			json_object_set_new(result, "bitrate", json_integer(session->bitrate));
			json_object_set_new(event, "result", result);
			char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
			json_decref(event);
			json_decref(result);
			event = NULL;
			gateway->push_event(session->handle, &janus_serial_plugin, NULL, event_text, NULL, NULL);
			g_free(event_text);
		}
	}
}
Esempio n. 27
0
static json_t *parse_value(lex_t *lex, size_t flags, json_error_t *error)
{
    json_t *json;
    double value;

    switch(lex->token) {
        case TOKEN_STRING: {
            json = json_string_nocheck(lex->value.string);
            break;
        }

        case TOKEN_INTEGER: {
            if (flags & JSON_DECODE_INT_AS_REAL) {
                if(jsonp_strtod(&lex->saved_text, &value)) {
                    error_set(error, lex, "real number overflow");
                    return NULL;
                }
                json = json_real(value);
            } else {
                json = json_integer(lex->value.integer);
            }
            break;
        }

        case TOKEN_REAL: {
            json = json_real(lex->value.real);
            break;
        }

        case TOKEN_TRUE:
            json = json_true();
            break;

        case TOKEN_FALSE:
            json = json_false();
            break;

        case TOKEN_NULL:
            json = json_null();
            break;

        case '{':
            json = parse_object(lex, flags, error);
            break;

        case '[':
            json = parse_array(lex, flags, error);
            break;

        case TOKEN_INVALID:
            error_set(error, lex, "invalid token");
            return NULL;

        default:
            error_set(error, lex, "unexpected token");
            return NULL;
    }

    if(!json)
        return NULL;

    return json;
}
Esempio n. 28
0
/* Thread to handle incoming messages */
static void *janus_serial_handler(void *data) {
	JANUS_LOG(LOG_VERB, "Joining Serial handler thread\n");
	janus_serial_message *msg = NULL;
	int error_code = 0;
	char *error_cause = calloc(512, sizeof(char));
	if(error_cause == NULL) {
		JANUS_LOG(LOG_FATAL, "Memory error!\n");
		return NULL;
	}
	json_t *root = NULL;
	while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
		if(!messages || (msg = g_async_queue_try_pop(messages)) == NULL) {
			usleep(50000);
			continue;
		}
		janus_serial_session *session = (janus_serial_session *)msg->handle->plugin_handle;
		if(!session) {
			JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
			janus_serial_message_free(msg);
			continue;
		}
		if(session->destroyed) {
			janus_serial_message_free(msg);
			continue;
		}
		/* Handle request */
		error_code = 0;
		root = NULL;
		JANUS_LOG(LOG_VERB, "Handling message: %s\n", msg->message);
		if(msg->message == NULL) {
			JANUS_LOG(LOG_ERR, "No message??\n");
			error_code = JANUS_SERIAL_ERROR_NO_MESSAGE;
			g_snprintf(error_cause, 512, "%s", "No message??");
			goto error;
		}
		json_error_t error;
		root = json_loads(msg->message, 0, &error);
		if(!root) {
			JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
			error_code = JANUS_SERIAL_ERROR_INVALID_JSON;
			g_snprintf(error_cause, 512, "JSON error: on line %d: %s", error.line, error.text);
			goto error;
		}
		if(!json_is_object(root)) {
			JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
			error_code = JANUS_SERIAL_ERROR_INVALID_JSON;
			g_snprintf(error_cause, 512, "JSON error: not an object");
			goto error;
		}
		/* Parse request */
		json_t *audio = json_object_get(root, "audio");
		if(audio && !json_is_boolean(audio)) {
			JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n");
			error_code = JANUS_SERIAL_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)");
			goto error;
		}
		json_t *video = json_object_get(root, "video");
		if(video && !json_is_boolean(video)) {
			JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n");
			error_code = JANUS_SERIAL_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)");
			goto error;
		}
		json_t *bitrate = json_object_get(root, "bitrate");
		if(bitrate && (!json_is_integer(bitrate) || json_integer_value(bitrate) < 0)) {
			JANUS_LOG(LOG_ERR, "Invalid element (bitrate should be a positive integer)\n");
			error_code = JANUS_SERIAL_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (bitrate should be a positive integer)");
			goto error;
		}
		json_t *record = json_object_get(root, "record");
		if(record && !json_is_boolean(record)) {
			JANUS_LOG(LOG_ERR, "Invalid element (record should be a boolean)\n");
			error_code = JANUS_SERIAL_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (record should be a boolean)");
			goto error;
		}
		json_t *recfile = json_object_get(root, "filename");
		if(recfile && !json_is_string(recfile)) {
			JANUS_LOG(LOG_ERR, "Invalid element (filename should be a string)\n");
			error_code = JANUS_SERIAL_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (filename should be a string)");
			goto error;
		}
		/* Enforce request */
		if(audio) {
			session->audio_active = json_is_true(audio);
			JANUS_LOG(LOG_VERB, "Setting audio property: %s\n", session->audio_active ? "true" : "false");
		}
		if(video) {
			if(!session->video_active && json_is_true(video)) {
				/* Send a PLI */
				JANUS_LOG(LOG_VERB, "Just (re-)enabled video, sending a PLI to recover it\n");
				char buf[12];
				memset(buf, 0, 12);
				janus_rtcp_pli((char *)&buf, 12);
				gateway->relay_rtcp(session->handle, 1, buf, 12);
			}
			session->video_active = json_is_true(video);
			JANUS_LOG(LOG_VERB, "Setting video property: %s\n", session->video_active ? "true" : "false");
		}
		if(bitrate) {
			session->bitrate = json_integer_value(bitrate);
			JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64"\n", session->bitrate);
			if(session->bitrate > 0) {
				/* FIXME Generate a new REMB (especially useful for Firefox, which doesn't send any we can cap later) */
				char buf[24];
				memset(buf, 0, 24);
				janus_rtcp_remb((char *)&buf, 24, session->bitrate);
				JANUS_LOG(LOG_VERB, "Sending REMB\n");
				gateway->relay_rtcp(session->handle, 1, buf, 24);
				/* FIXME How should we handle a subsequent "no limit" bitrate? */
			}
		}
		if(record) {
			if(msg->sdp) {
				session->has_audio = (strstr(msg->sdp, "m=audio") != NULL);
				session->has_video = (strstr(msg->sdp, "m=video") != NULL);
			}
			gboolean recording = json_is_true(record);
			const char *recording_base = json_string_value(recfile);
			JANUS_LOG(LOG_VERB, "Recording %s (base filename: %s)\n", recording ? "enabled" : "disabled", recording_base ? recording_base : "not provided");
			if(!recording) {
				/* Not recording (anymore?) */
				if(session->arc) {
					janus_recorder_close(session->arc);
					JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
					janus_recorder_free(session->arc);
				}
				session->arc = NULL;
				if(session->vrc) {
					janus_recorder_close(session->vrc);
					JANUS_LOG(LOG_INFO, "Closed video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
					janus_recorder_free(session->vrc);
				}
				session->vrc = NULL;
			} else {
				/* We've started recording, send a PLI and go on */
				char filename[255];
				gint64 now = janus_get_monotonic_time();
				if(session->has_audio) {
					memset(filename, 0, 255);
					if(recording_base) {
						/* Use the filename and path we have been provided */
						g_snprintf(filename, 255, "%s-audio", recording_base);
						session->arc = janus_recorder_create(NULL, 0, filename);
						if(session->arc == NULL) {
							/* FIXME We should notify the fact the recorder could not be created */
							JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this EchoTest user!\n");
						}
					} else {
						/* Build a filename */
						g_snprintf(filename, 255, "serial-%p-%"SCNi64"-audio", session, now);
						session->arc = janus_recorder_create(NULL, 0, filename);
						if(session->arc == NULL) {
							/* FIXME We should notify the fact the recorder could not be created */
							JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this EchoTest user!\n");
						}
					}
				}
				if(session->has_video) {
					memset(filename, 0, 255);
					if(recording_base) {
						/* Use the filename and path we have been provided */
						g_snprintf(filename, 255, "%s-video", recording_base);
						session->vrc = janus_recorder_create(NULL, 1, filename);
						if(session->vrc == NULL) {
							/* FIXME We should notify the fact the recorder could not be created */
							JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this EchoTest user!\n");
						}
					} else {
						/* Build a filename */
						g_snprintf(filename, 255, "serial-%p-%"SCNi64"-video", session, now);
						session->vrc = janus_recorder_create(NULL, 1, filename);
						if(session->vrc == NULL) {
							/* FIXME We should notify the fact the recorder could not be created */
							JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this EchoTest user!\n");
						}
					}
					/* Send a PLI */
					JANUS_LOG(LOG_VERB, "Recording video, sending a PLI to kickstart it\n");
					char buf[12];
					memset(buf, 0, 12);
					janus_rtcp_pli((char *)&buf, 12);
					gateway->relay_rtcp(session->handle, 1, buf, 12);
				}
			}
		}
		/* Any SDP to handle? */
		if(msg->sdp) {
			JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
			session->has_audio = (strstr(msg->sdp, "m=audio") != NULL);
			session->has_video = (strstr(msg->sdp, "m=video") != NULL);
		}
/*
		if(!audio && !video && !bitrate && !record && !msg->sdp) {
			JANUS_LOG(LOG_ERR, "No supported attributes (audio, video, bitrate, record, jsep) found\n");
			error_code = JANUS_SERIAL_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Message error: no supported attributes (audio, video, bitrate, record, jsep) found");
			goto error;
		}
*/
		json_decref(root);
		/* Prepare JSON event */
		json_t *event = json_object();
		json_object_set_new(event, "serial", json_string("event"));
		json_object_set_new(event, "result", json_string("ok"));
		char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
		json_decref(event);
		JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
		if(!msg->sdp) {
			int ret = gateway->push_event(msg->handle, &janus_serial_plugin, msg->transaction, event_text, NULL, NULL);
			JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
		} else {
			/* Forward the same offer to the gateway, to start the echo test */
			const char *type = NULL;
			if(!strcasecmp(msg->sdp_type, "offer"))
				type = "answer";
			if(!strcasecmp(msg->sdp_type, "answer"))
				type = "offer";
			/* Any media direction that needs to be fixed? */
			char *sdp = g_strdup(msg->sdp);
			if(strstr(sdp, "a=recvonly")) {
				/* Turn recvonly to inactive, as we simply bounce media back */
				sdp = janus_string_replace(sdp, "a=recvonly", "a=inactive");
			} else if(strstr(sdp, "a=sendonly")) {
				/* Turn sendonly to recvonly */
				sdp = janus_string_replace(sdp, "a=sendonly", "a=recvonly");
				/* FIXME We should also actually not echo this media back, though... */
			}
			/* Make also sure we get rid of ULPfec, red, etc. */
			if(strstr(sdp, "ulpfec")) {
				sdp = janus_string_replace(sdp, "100 116 117 96", "100");
				sdp = janus_string_replace(sdp, "a=rtpmap:116 red/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:117 ulpfec/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:96 rtx/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=fmtp:96 apt=100\r\n", "");
			}
			/* How long will the gateway take to push the event? */
			gint64 start = janus_get_monotonic_time();
			int res = gateway->push_event(msg->handle, &janus_serial_plugin, msg->transaction, event_text, type, sdp);
			JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n",
				res, janus_get_monotonic_time()-start);
			g_free(sdp);
		}
		g_free(event_text);
		janus_serial_message_free(msg);
		continue;
		
error:
		{
			if(root != NULL)
				json_decref(root);
			/* Prepare JSON error event */
			json_t *event = json_object();
			json_object_set_new(event, "serial", json_string("event"));
			json_object_set_new(event, "error_code", json_integer(error_code));
			json_object_set_new(event, "error", json_string(error_cause));
			char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
			json_decref(event);
			JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
			int ret = gateway->push_event(msg->handle, &janus_serial_plugin, msg->transaction, event_text, NULL, NULL);
			JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
			g_free(event_text);
			janus_serial_message_free(msg);
		}
	}
	g_free(error_cause);
	JANUS_LOG(LOG_VERB, "Leaving Serial handler thread\n");
	return NULL;
}
Esempio n. 29
0
static void
ccmd_get_roles(json_t * params)
{
    int i, len;
    struct nh_roles_info *ri;
    json_t *jmsg, *jarr, *j_tmp;
    void *iter;

    iter = json_object_iter(params);
    if (iter)
        exit_client("non-empty parameter list for get_roles");

    ri = nh_get_roles();
    jmsg =
        json_pack("{si,si,si,si,si,si,si,si}", "num_roles", ri->num_roles,
                  "num_races", ri->num_races, "num_genders", ri->num_genders,
                  "num_aligns", ri->num_aligns, "def_role", ri->def_role,
                  "def_race", ri->def_race, "def_gend", ri->def_gend,
                  "def_align", ri->def_align);

    /* rolenames_m */
    jarr = json_array();
    for (i = 0; i < ri->num_roles; i++) {
        j_tmp =
            ri->rolenames_m[i] ? json_string(ri->rolenames_m[i]) : json_null();
        json_array_append_new(jarr, j_tmp);
    }
    json_object_set_new(jmsg, "rolenames_m", jarr);

    /* rolenames_f */
    jarr = json_array();
    for (i = 0; i < ri->num_roles; i++) {
        j_tmp =
            ri->rolenames_f[i] ? json_string(ri->rolenames_f[i]) : json_null();
        json_array_append_new(jarr, j_tmp);
    }
    json_object_set_new(jmsg, "rolenames_f", jarr);

    /* racenames */
    jarr = json_array();
    for (i = 0; i < ri->num_races; i++) {
        j_tmp = ri->racenames[i] ? json_string(ri->racenames[i]) : json_null();
        json_array_append_new(jarr, j_tmp);
    }
    json_object_set_new(jmsg, "racenames", jarr);

    /* gendnames */
    jarr = json_array();
    for (i = 0; i < ri->num_genders; i++) {
        j_tmp = ri->gendnames[i] ? json_string(ri->gendnames[i]) : json_null();
        json_array_append_new(jarr, j_tmp);
    }
    json_object_set_new(jmsg, "gendnames", jarr);

    /* alignnames */
    jarr = json_array();
    for (i = 0; i < ri->num_aligns; i++) {
        j_tmp =
            ri->alignnames[i] ? json_string(ri->alignnames[i]) : json_null();
        json_array_append_new(jarr, j_tmp);
    }
    json_object_set_new(jmsg, "alignnames", jarr);

    /* matrix */
    len = ri->num_roles * ri->num_races * ri->num_genders * ri->num_aligns;
    jarr = json_array();
    for (i = 0; i < len; i++) {
        json_array_append_new(jarr, json_integer(ri->matrix[i]));
    }
    json_object_set_new(jmsg, "matrix", jarr);

    client_msg("get_roles", jmsg);
}
Esempio n. 30
0
// arguments: [ttl <int>] [name <string>] [target <string>]
// (in any order)
// if we change record's name (subDomain), we need to update records cache
static command_status_t record_update(COMMAND_ARGS)
{
    domain_t *d;
    record_t *r;
    bool success;
    domain_record_argument_t *args;

    USED(mainopts);
    args = (domain_record_argument_t *) arg;
    assert(NULL != args->domain);
    assert(NULL != args->record);
    if ((success = (COMMAND_SUCCESS == get_domain_records(args->domain, &d, FALSE, error)))) {
        json_document_t *reqdoc;

        size_t matches;

        matches = find_record(d->records, args->record, &r);
        switch (matches) {
            case 1:
                // NOP : OK
                break;
            case 0:
                error_set(error, WARN, "Abort, no record match '%s'", args->record);
                return COMMAND_FAILURE;
            default:
                error_set(error, WARN, "Abort, more than one record match '%s'", args->record);
                return COMMAND_FAILURE;
        }
        // data
        {
            json_value_t root;

            reqdoc = json_document_new();
            root = json_object();
            if (NULL != args->value) {
                json_object_set_property(root, "target", json_string(args->value));
            }
            if (NULL != args->name) {
                json_object_set_property(root, "subDomain", json_string(args->name));
            }
            json_object_set_property(root, "ttl", json_integer(args->ttl));
            json_document_set_root(reqdoc, root);
        }
        // request
        {
            request_t *req;

            req = request_new(REQUEST_FLAG_SIGN | REQUEST_FLAG_JSON, HTTP_PUT, reqdoc, error, API_BASE_URL "/domain/zone/%s/record/%" PRIu32, args->domain, r->id);
            success = request_execute(req, RESPONSE_IGNORE, NULL, error);
            request_destroy(req);
            json_document_destroy(reqdoc);
        }
        if (success) {
            if (NULL != args->value) {
                FREE(r, target);
                r->target = strdup(args->value);
            }
            if (NULL != args->name) {
                FREE(r, name);
                r->name = strdup(args->name);
            }
            r->ttl = args->ttl;
            ask_for_refresh(RELAY_COMMAND_ARGS);
        }
    }
//     debug("request update of %s.%s to %s.%s with TTL = %" PRIu32 " and value = '%s'", args->record, args->domain, args->name, args->domain, args->ttl, args->value);

    return COMMAND_SUCCESS;
}