Example #1
0
int main(int argc,char **argv)
{
	int sock_fd;
	struct sockaddr_in sin;

	if(argc != 3){
		fprintf(stderr,"Usage:%s <port> <IP>\n",argv[0]);
		exit(1);
	}
	/*build socket*/
	if((sock_fd = socket(AF_INET,SOCK_STREAM,0)) < 0){
		perror("socket");
		exit(1);
	}
	/*input ip and port*/
	bzero(&sin,sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(atoi(argv[1]));
	sin.sin_addr.s_addr = inet_addr(argv[2]);
	/*connect the server*/ 
	if((connect(sock_fd,(struct sockaddr*)&sin,sizeof(sin))) < 0){
		perror("connect");
		exit(1);
	}
	/*write and read*/
	char buf[BUFSIZ];
	while(1){
		bzero(buf,BUFSIZ);
		fgets(buf,BUFSIZ,stdin);

		/*-----------------encording json------------------------*/
		/*encording one record of database table*/
		struct json_object *my_json;
		my_json=json_object_new_object();

		json_object_object_add(my_json,"fla",json_object_new_int(11));
		//json_object_object_add(my_json,"name",json_object_new_string("猪肉炒牛肉"));

		/*encording one record of database table*/
		/*
		struct json_object *my_json2;
		my_json2=json_object_new_object();

		json_object_object_add(my_json2,"id",json_object_new_int(2));
		json_object_object_add(my_json2,"name",json_object_new_string("猪肉炒青菜"));
		*/

		/*encording one database table*/
		struct json_object *json_shuzu;
		json_shuzu=json_object_new_array();
		json_object_array_add(json_shuzu,my_json);
		//json_object_array_add(json_shuzu,my_json2);

		/*encording to char* */
		const char * buf_cst =json_object_to_json_string(json_shuzu);
		//write(cli_fd,buf_cst,strlen(buf_cst));

		if(write(sock_fd,buf_cst,strlen(buf_cst)) < 0){
		//if(write(sock_fd,buf,strlen(buf)) < 0){
			perror("write");
			exit(1);
		}
		if(strncmp(buf,"quit",4) == 0)
			break;
		bzero(buf,BUFSIZ);
		if(read(sock_fd,buf,BUFSIZ) < 0){
			perror("read");
			exit(1);
		}
		printf("read: %s",buf);
#ifdef JSON
		/*encording one table*/
		/*
		json_object *jiebao_json2, *jiebao_json3,*jiebao_name2;
		jiebao_json2=json_tokener_parse(buf);

		int i = json_object_array_length(jiebao_json2);
		printf("%d\n",i);
		const char *jiebao_str2;
		int ii = i;
		for(;i>0;){
			jiebao_json3=json_object_array_get_idx(jiebao_json2,--ii);
			jiebao_name2=json_object_object_get(jiebao_json3,"name");
			jiebao_str2 =json_object_get_string(jiebao_name2);
			*/

			/*encording one record of database table*/
			/*
			   json_object *jiebao_json,*jiebao_name;
			   jiebao_json=json_tokener_parse(jiebao_str2);
			   jiebao_name=json_object_object_get(jiebao_json,"name");
			   const char *jiebao_str =json_object_get_string(jiebao_name);
			   */
			//printf("read: %s\n",jiebao_str2);
			//i--;
		//}
#endif
		bzero(buf,BUFSIZ);
	}
	/*close socket*/
	close(sock_fd);

	return 0;
}
Example #2
0
// LOGIN: 用于表示客户端登录 LOGIN account:abalam password:123qwe ios_token:111 get_friend_list:1
int login_cmd(struct clients *client_t, char *pbuf, size_t pbuf_size)
{
	log_debug("pbuf:%s", pbuf);
	
	int sockfd = client_t->fd;
	char account[MAX_LINE] = {0};
	char password[MAX_LINE] = {0};
	char ios_token[MAX_LINE] = {0};
	int get_friend_list = 0;
	
	char tok[MAX_LINE] = {0};
	char *ptok = tok;
	
	int n = pbuf_size;
	while ((*pbuf != '\0') && (n > 0)) {
		char *psed = (char *)memchr(pbuf, ' ', strlen(pbuf));
		if (psed != NULL) {
			int m = (psed - pbuf);
			memcpy(ptok, pbuf, m);
			pbuf += (m + 1);
			n -= (m + 1);
		} else {
			ptok = pbuf;
			n -= strlen(pbuf);
		}
		
		log_debug("ptok:[%s]", ptok);
		if (strncasecmp(ptok, "account:", 8) == 0) {
			snprintf(account, sizeof(account), "%s", ptok+8);
		} else if (strncasecmp(ptok, "password:"******"%s", ptok+9);
		} else if (strncasecmp(ptok, "ios_token:", 10) == 0) {
			snprintf(ios_token, sizeof(ios_token), "%s", ptok+10);
		} else if (strncasecmp(ptok, "get_friend_list:", 16) == 0) {
			get_friend_list = atoi(ptok+16);
			
			break;
		} 
		
		memset(ptok, 0, strlen(ptok));
	}
	
	log_debug("get sockfd[%d] account[%s]", sockfd, account);
	log_debug("get sockfd[%d] account[%s]", sockfd, password);
	log_debug("get sockfd[%d] account[%s]", sockfd, ios_token);
	log_debug("get sockfd[%d] account[%d]", sockfd, get_friend_list);

	int result_size = 0;
	char *presult = NULL;
	size_t response_buf_size = 0;
	char *response_buf = NULL;
	
	
	// 调用认证接口
	char url[MAX_LINE] = {0};
	snprintf(url, sizeof(url), "%s/login.php", API_HTTP); 
	
	result_size = 0;
	presult = login_http_api(url, account, password, ios_token, get_friend_list, &result_size);
	log_debug("presult:[%d]%s", result_size, presult);
	if (result_size == 0 || presult == NULL) {
		log_error("get user info fail from API");
		return 1;
	}

	response_buf_size = 6 + 6 + result_size + 5;
	response_buf = (char *)calloc(1, response_buf_size);
	if (response_buf == NULL) {
		clean_mem_buf(presult);
		result_size = 0;

		return 1;	
	}

	n = snprintf(response_buf, response_buf_size, "%s OK %s%s", TAG_LOGIN, presult, DATA_END); 

	safe_write(client_t, response_buf, n);

	// 注册在线
	json_bool json_ret;
	struct array_list *tmp_array;
	struct json_object *tmp_obj;
	struct json_object *tmp_obj2;
	struct json_object *result_json;
	
	result_json = json_tokener_parse(presult);
	if ( result_json == NULL ) {
		log_error("get uid fail with json_tokener_parse");
		goto FINISH;
	}
	//tmp_obj = json_object_object_get(result_json, "myself");
	json_ret = json_object_object_get_ex(result_json, "myself", &tmp_obj);
	if ( json_ret == 0) {
		log_error("get uid fail with json_object_object_get key:myself");
		goto FINISH;
	}
	//tmp_obj2 = json_object_object_get(tmp_obj, "id");
	json_ret = json_object_object_get_ex(tmp_obj, "id", &tmp_obj2);
	if (json_ret == 0) {
		log_error("get uid fail with json_object_object_get key:id");
		goto FINISH;
	}

	char *uid = (char *)json_object_to_json_string(tmp_obj2);
	if (uid) {
		if (*(uid + (strlen(uid) - 1)) == '"') 
			*(uid + (strlen(uid) - 1)) = '\0';

		if (*uid == '"') 
			uid += 1;
	}
	log_debug("get uid[%s] from json", uid);

	// 注册在线	
	snprintf(client_t->uid, sizeof(client_t->uid), "%s", uid);
    snprintf(client_t->ios_token, sizeof(client_st->ios_token), "%s", ios_token);

	int ret = dictionary_set(online_d, uid, ios_token);
	if (ret != 0) {
		log_error("add to online failed uid[%s] sockfd[%d] ios_token[%s]", uid, sockfd, ios_token);
	} else {
		log_debug("registon online succ uid[%s] ios_token[%s] sockfd[%d]", uid, ios_token, sockfd);	
		//dictionary_dump(online_d, stderr);
	}


FINISH:	
	clean_mem_buf(presult);
	result_size = 0;

	clean_mem_buf(response_buf);
	response_buf_size = 0;

	return 0;
}
Example #3
0
 * @param gw pointer to gateway context
 *
 * @return TRUE on success, FALSE on failure
 */
bool_t cleanup(gw_t *gw)
{
	//TODO: cleanup module stuff
	gw_msg_t *msg;

	json_object *my_object;
	my_object = serialize(gw);
	printf("my_object=\n");
	json_object_object_foreach(my_object, key, val) {
	printf("\t%s: %s\n", key, json_object_to_json_string(val));
	}
	printf("my_object.to_string()=%s\n", json_object_to_json_string(my_object));
	json_object_put(my_object);

	msg = gw_msg_alloc();
	msg->type = GW_MSG_SYSTEM_QUIT;
	msg->dstsvc = applocate_svc.id;
	msg->srcsvc = applocate_svc.id;
	gw_msg_send(gw, msg);

	gw_thread_wait(msg_handle_thread);

	mod_unregister_service(gw, &mod_applocate, &applocate_svc);
	mod_unregister(gw, &mod_applocate);

	gw_msgq_destroy(applocate_msgq);
	gw_mutex_destroy(mod_applocate.lock);
int main()
{

//===========================================================================================
// Declarations
//===========================================================================================
	
	int i,j;
	int i2,j2;
	
	job_info_msg_t *job_ptr;	
	partition_info_msg_t *prt_ptr = NULL;
	node_info_msg_t *node_ptr = NULL;

	int err = SLURM_SUCCESS;
	err = slurm_load_partitions((time_t) NULL, &prt_ptr, 0);
	err = slurm_load_node((time_t) NULL, &node_ptr, 0);
	err = slurm_load_jobs((time_t) NULL, &job_ptr, 0);	

	Linked_List_Node* job_llist;
	struct json_object *partition = json_object_new_object();
	struct json_object *node = json_object_new_object();


//===========================================================================================
// Filling hash tables
//===========================================================================================

	j2 = 0;	
	i2 = 0;

	//fill node_job hash
	if (job_ptr->record_count > 0) {

		for (i = 0; i < job_ptr->record_count; i++) {
			
			
			j2=0;
			while( job_ptr->job_array[i].node_inx[j2] >= 0){
				
				i2 = 0;
								
				for(i2 = job_ptr->job_array[i].node_inx[j2];i2 <= job_ptr->job_array[i].node_inx[j2+1];i2++) {

					node_job_put(node_ptr->node_array[i2].name,job_ptr -> job_array[i]);
				}
				j2+=2;
			}
		
		}
	}
	

//============================================================================================
// Creating Output in Json
//============================================================================================

	// create json	

	int total_node_unknown = 0;
	int total_node_down = 0;
	int total_node_idle = 0;
	int total_node_allocated = 0;
	
	int current_node_unknown;
	int current_node_down;
	int current_node_idle;
	int current_node_allocated;

	int current_job_running;
	int current_job_waiting;
	int current_job_stopped;


	if(prt_ptr -> record_count > 0){	
	
		for (i = 0; i < prt_ptr->record_count; i++) {


			current_node_unknown = 0;
			current_node_down = 0;
			current_node_idle = 0;
			current_node_allocated = 0;

			current_job_running = 0;
			current_job_waiting = 0;			
			current_job_stopped = 0;
			
			
			int j2=0;
			while( prt_ptr->partition_array[i].node_inx[j2] >= 0){
				
				int i2 = 0;

				for(i2 = prt_ptr->partition_array[i].node_inx[j2];i2 <= prt_ptr->partition_array[i].node_inx[j2+1];i2++) {


					if(node_ptr->node_array[i2].node_state == 5 || node_ptr->node_array[i2].node_state == 3){   total_node_allocated++;   current_node_allocated++;}
					else if(node_ptr->node_array[i2].node_state == 1){ 	total_node_down++;      current_node_down++;}
					else if(node_ptr->node_array[i2].node_state == 2 || node_ptr->node_array[i2].node_state == 6){ 	total_node_idle++;      current_node_idle++;}
					else { 	total_node_unknown++; current_node_unknown++;}
	
					job_llist = node_job_get(node_ptr->node_array[i2].name); 			//get job name	
					while( job_llist != NULL){
						

						if(job_llist->value_job.job_state == 2 || job_llist->value_job.job_state == 8 || job_llist->value_job.job_state == 0) 	current_job_waiting++;
						else if(job_llist->value_job.job_state == 1) 	current_job_running++;
						else	current_job_stopped++;
					
						job_llist = job_llist->next;			
									
					}
				}	
				j2+=2;		
	
			}
			
			json_object_object_add(node, "Allocated", json_object_new_int(current_node_allocated));
			json_object_object_add(node, "Down", json_object_new_int(current_node_down));
			json_object_object_add(node, "Idle", json_object_new_int(current_node_idle));
			json_object_object_add(node, "Unknown", json_object_new_int(current_node_unknown));
			json_object_object_add(node, "Running", json_object_new_int(current_job_running));
			json_object_object_add(node, "Wating", json_object_new_int(current_job_waiting));
			json_object_object_add(node, "Stopped", json_object_new_int(current_job_stopped));

			json_object_object_add(partition, prt_ptr->partition_array[i].name , node);

		}
	
	}		
	
	node = json_object_new_object();
	json_object_object_add(node, "Unknown", json_object_new_int(total_node_unknown));
	json_object_object_add(node, "Down", json_object_new_int(total_node_down));
	json_object_object_add(node, "Idle", json_object_new_int(total_node_idle));
	json_object_object_add(node, "Allocated", json_object_new_int(total_node_allocated));
	
	json_object_object_add(partition, "General", node);
	printf("Content-type: text/html\n\n%s",json_object_to_json_string(partition));

	slurm_free_partition_info_msg(prt_ptr);
	slurm_free_node_info_msg(node_ptr);
	return 1;


}
void OGRCloudantTableLayer::WriteMetadata()
{
    if (pszSpatialDDoc == nullptr)
        OGRCloudantTableLayer::GetSpatialView();
    if( pszSpatialDDoc == nullptr )
        return;

    CPLString osURI;
    osURI = "/";
    osURI += osEscapedName;
    osURI += "/";
    osURI += pszSpatialDDoc;

   json_object* poDDocObj = poDS->GET(osURI);
    if (poDDocObj == nullptr)
        return;

    if ( !json_object_is_type(poDDocObj, json_type_object) )
    {
        CPLError(CE_Failure, CPLE_AppDefined, "WriteMetadata() failed");
        json_object_put(poDDocObj);
        return;
    }

    json_object* poError = CPL_json_object_object_get(poDDocObj, "error");
    const char* pszError = json_object_get_string(poError);
    if (pszError && strcmp(pszError, "not_found") == 0)
    {
        json_object_put(poDDocObj);
        return;
    }

    if (poDS->IsError(poDDocObj, "WriteMetadata() failed"))
    {
        json_object_put(poDDocObj);
        return;
    }

    if (poSRS)
    {
        // epsg codes are supported in Cloudant
        const char * pszEpsg = nullptr;
        const char * pszAuthName = nullptr;
        char szSrid[100];

        if (poSRS->IsProjected())
        {
            pszAuthName = poSRS->GetAuthorityName("PROJCS");
            if ((pszAuthName != nullptr) && (STARTS_WITH(pszAuthName, "EPSG")))
                pszEpsg = poSRS->GetAuthorityCode("PROJCS");
        }
        else
        {
            pszAuthName = poSRS->GetAuthorityName("GEOGCS");
            if ((pszAuthName != nullptr) && (STARTS_WITH(pszAuthName, "EPSG")))
                pszEpsg = poSRS->GetAuthorityCode("GEOGCS");
        }

        if (pszEpsg != nullptr)
        {
            const char * pszUrn = "urn:ogc:def:crs:epsg::";
            CPLStrlcpy(szSrid, pszUrn, sizeof(szSrid));
            if (CPLStrlcpy(szSrid + sizeof(pszUrn), pszEpsg, sizeof(szSrid)) <= sizeof(szSrid))
            {
                json_object_object_add(poDDocObj, "srsid",
                                   json_object_new_string(pszUrn));
            }
        }
    }

    if (eGeomType != wkbNone)
    {
        json_object_object_add(poDDocObj, "geomtype",
                    json_object_new_string(OGRToOGCGeomType(eGeomType)));
        if (wkbHasZ(poFeatureDefn->GetGeomType()))
        {
            json_object_object_add(poDDocObj, "is_25D",
                               json_object_new_boolean(TRUE));
        }
    }
    else
    {
        json_object_object_add(poDDocObj, "geomtype",
                               json_object_new_string("NONE"));
    }

    json_object_object_add(poDDocObj, "geojson_documents",
                           json_object_new_boolean(bGeoJSONDocument));

    json_object* poFields = json_object_new_array();
    json_object_object_add(poDDocObj, "fields", poFields);

    for(int i=COUCHDB_FIRST_FIELD;i<poFeatureDefn->GetFieldCount();i++)
    {
        json_object* poField = json_object_new_object();
        json_object_array_add(poFields, poField);

        json_object_object_add(poField, "name",
            json_object_new_string(poFeatureDefn->GetFieldDefn(i)->GetNameRef()));

        const char* pszType = nullptr;
        switch (poFeatureDefn->GetFieldDefn(i)->GetType())
        {
            case OFTInteger: pszType = "integer"; break;
            case OFTReal: pszType = "real"; break;
            case OFTString: pszType = "string"; break;
            case OFTIntegerList: pszType = "integerlist"; break;
            case OFTRealList: pszType = "reallist"; break;
            case OFTStringList: pszType = "stringlist"; break;
            default: pszType = "string"; break;
        }

        json_object_object_add(poField, "type",
                               json_object_new_string(pszType));
    }

    json_object* poAnswerObj = poDS->PUT(osURI,
                                         json_object_to_json_string(poDDocObj));

    json_object_put(poDDocObj);
    json_object_put(poAnswerObj);
}
Example #6
0
static char *print_json(switch_memory_pool_t *pool, http_data_t *http_data)
{
	struct json_object *top = NULL;
	struct json_object *headers = NULL;
	char *data = NULL;
	switch_curl_slist_t *header = http_data->headers;

	top = json_object_new_object();
	headers = json_object_new_array();
	json_object_object_add(top, "status_code", json_object_new_int(http_data->http_response_code));
	if (http_data->http_response) {
		json_object_object_add(top, "body", json_object_new_string(http_data->http_response));
	}

	/* parse header data */
	while (header) {
		struct json_object *obj = NULL;
		/* remove trailing \r */
		if ((data =  strrchr(header->data, '\r'))) {
			*data = '\0';
		}

		if (zstr(header->data)) {
			header = header->next;
			continue;
		}

		if ((data = strchr(header->data, ':'))) {
			*data = '\0';
			data++;
			while (*data == ' ' && *data != '\0') {
				data++;
			}
			obj = json_object_new_object();
			json_object_object_add(obj, "key", json_object_new_string(header->data));
			json_object_object_add(obj, "value", json_object_new_string(data));
			json_object_array_add(headers, obj);
		} else {
			if (!strncmp("HTTP", header->data, 4)) {
				char *argv[3] = { 0 };
				int argc;
				if ((argc = switch_separate_string(header->data, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
					if (argc > 2) {
						json_object_object_add(top, "version", json_object_new_string(argv[0]));
						json_object_object_add(top, "phrase", json_object_new_string(argv[2]));
					} else {
						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unparsable header: argc: %d\n", argc);
					}
				} else {
					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Starts with HTTP but not parsable: %s\n", header->data);
				}
			} else {
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unparsable header: %s\n", header->data);
			}
		}
		header = header->next;
	}
	json_object_object_add(top, "headers", headers);
	data = switch_core_strdup(pool, json_object_to_json_string(top));
	json_object_put(top);		/* should free up all children */

	return data;
}
/** Write accounting data to Couchbase documents
 *
 * Handle accounting requests and store the associated data into JSON documents
 * in couchbase mapping attribute names to JSON element names per the module configuration.
 *
 * When an existing document already exists for the same accounting section the new attributes
 * will be merged with the currently existing data.  When conflicts arrise the new attribute
 * value will replace or be added to the existing value.
 *
 * @param  instance The module instance.
 * @param  request  The accounting request object.
 * @return          Returns operation status (@p rlm_rcode_t).
 */
CC_HINT(nonnull) static rlm_rcode_t mod_accounting(void *instance, REQUEST *request) {
	rlm_couchbase_t *inst = instance;   /* our module instance */
	void *handle = NULL;                /* connection pool handle */
	VALUE_PAIR *vp;                     /* radius value pair linked list */
	char dockey[MAX_KEY_SIZE];          /* our document key */
	char document[MAX_VALUE_SIZE];      /* our document body */
	char element[MAX_KEY_SIZE];         /* mapped radius attribute to element name */
	int status = 0;                     /* account status type */
	int docfound = 0;                   /* document found toggle */
	lcb_error_t cb_error = LCB_SUCCESS; /* couchbase error holder */

	/* assert packet as not null */
	rad_assert(request->packet != NULL);

	/* sanity check */
	if ((vp = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE, 0, TAG_ANY)) == NULL) {
		/* log debug */
		RDEBUG("could not find status type in packet");
		/* return */
		return RLM_MODULE_NOOP;
	}

	/* set status */
	status = vp->vp_integer;

	/* acknowledge the request but take no action */
	if (status == PW_STATUS_ACCOUNTING_ON || status == PW_STATUS_ACCOUNTING_OFF) {
		/* log debug */
		RDEBUG("handling accounting on/off request without action");
		/* return */
		return RLM_MODULE_OK;
	}

	/* get handle */
	handle = fr_connection_get(inst->pool);

	/* check handle */
	if (!handle) return RLM_MODULE_FAIL;

	/* set handle pointer */
	rlm_couchbase_handle_t *handle_t = handle;

	/* set couchbase instance */
	lcb_t cb_inst = handle_t->handle;

	/* set cookie */
	cookie_t *cookie = handle_t->cookie;

	/* check cookie */
	if (cookie) {
		/* clear cookie */
		memset(cookie, 0, sizeof(cookie_t));
	} else {
		/* log error */
		RERROR("cookie not usable - possibly not allocated");
		/* free connection */
		if (handle) {
			fr_connection_release(inst->pool, handle);
		}
		/* return */
		return RLM_MODULE_FAIL;
	}

	/* attempt to build document key */
	if (radius_xlat(dockey, sizeof(dockey), request, inst->acct_key, NULL, NULL) < 0) {
		/* log error */
		RERROR("could not find accounting key attribute (%s) in packet", inst->acct_key);
		/* release handle */
		if (handle) {
			fr_connection_release(inst->pool, handle);
		}
		/* return */
		return RLM_MODULE_NOOP;
	}

	/* init cookie error status */
	cookie->jerr = json_tokener_success;

	/* attempt to fetch document */
	cb_error = couchbase_get_key(cb_inst, cookie, dockey);

	/* check error */
	if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success) {
		/* log error */
		RERROR("failed to execute get request or parse returned json object");
		/* free json object */
		if (cookie->jobj) {
			json_object_put(cookie->jobj);
		}
	} else {
		/* check cookie json object */
		if (cookie->jobj != NULL) {
			/* set doc found */
			docfound = 1;
			/* debugging */
			RDEBUG("parsed json body from couchbase: %s", json_object_to_json_string(cookie->jobj));
		}
	}

	/* start json document if needed */
	if (docfound != 1) {
		/* debugging */
		RDEBUG("document not found - creating new json document");
		/* create new json object */
		cookie->jobj = json_object_new_object();
		/* set 'docType' element for new document */
		json_object_object_add(cookie->jobj, "docType", json_object_new_string(inst->doctype));
		/* set start and stop times ... ensure we always have these elements */
		json_object_object_add(cookie->jobj, "startTimestamp", json_object_new_string("null"));
		json_object_object_add(cookie->jobj, "stopTimestamp", json_object_new_string("null"));
	}

	/* status specific replacements for start/stop time */
	switch (status) {
		case PW_STATUS_START:
			/* add start time */
			if ((vp = pairfind(request->packet->vps, PW_EVENT_TIMESTAMP, 0, TAG_ANY)) != NULL) {
				/* add to json object */
				json_object_object_add(cookie->jobj, "startTimestamp", mod_value_pair_to_json_object(request, vp));
			}
			break;

		case PW_STATUS_STOP:
			/* add stop time */
			if ((vp = pairfind(request->packet->vps, PW_EVENT_TIMESTAMP, 0, TAG_ANY)) != NULL) {
				/* add to json object */
				json_object_object_add(cookie->jobj, "stopTimestamp", mod_value_pair_to_json_object(request, vp));
			}
			/* check start timestamp and adjust if needed */
			mod_ensure_start_timestamp(cookie->jobj, request->packet->vps);
			break;

		case PW_STATUS_ALIVE:
			/* check start timestamp and adjust if needed */
			mod_ensure_start_timestamp(cookie->jobj, request->packet->vps);
			break;

		default:
			/* we shouldn't get here - free json object */
			if (cookie->jobj) {
				json_object_put(cookie->jobj);
			}
			/* release our connection handle */
			if (handle) {
				fr_connection_release(inst->pool, handle);
			}
			/* return without doing anything */
			return RLM_MODULE_NOOP;
	}

	/* loop through pairs and add to json document */
	for (vp = request->packet->vps; vp; vp = vp->next) {
		/* map attribute to element */
		if (mod_attribute_to_element(vp->da->name, inst->map, &element) == 0) {
			/* debug */
			RDEBUG("mapped attribute %s => %s", vp->da->name, element);
			/* add to json object with mapped name */
			json_object_object_add(cookie->jobj, element, mod_value_pair_to_json_object(request, vp));
		}
	}

	/* copy json string to document and check size */
	if (strlcpy(document, json_object_to_json_string(cookie->jobj), sizeof(document)) >= sizeof(document)) {
		/* this isn't good */
		RERROR("could not write json document - insufficient buffer space");
		/* free json output */
		if (cookie->jobj) {
			json_object_put(cookie->jobj);
		}
		/* release handle */
		if (handle) {
			fr_connection_release(inst->pool, handle);
		}
		/* return */
		return RLM_MODULE_FAIL;
	}

	/* free json output */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
	}

	/* debugging */
	RDEBUG("setting '%s' => '%s'", dockey, document);

	/* store document/key in couchbase */
	cb_error = couchbase_set_key(cb_inst, dockey, document, inst->expire);

	/* check return */
	if (cb_error != LCB_SUCCESS) {
		RERROR("failed to store document (%s): %s (0x%x)", dockey, lcb_strerror(NULL, cb_error), cb_error);
	}

	/* release handle */
	if (handle) {
		fr_connection_release(inst->pool, handle);
	}

	/* return */
	return RLM_MODULE_OK;
}
/** Check if a given user is already logged in.
 *
 * Process accounting data to determine if a user is already logged in. Sets request->simul_count
 * to the current session count for this user.
 *
 * Check twice. If on the first pass the user exceeds his maximum number of logins, do a second
 * pass and validate all logins by querying the terminal server.
 *
 * @param instance The module instance.
 * @param request  The checksimul request object.
 * @return Returns operation status (@p rlm_rcode_t).
 */
static rlm_rcode_t mod_checksimul(void *instance, REQUEST *request) {
	rlm_couchbase_t *inst = instance;      /* our module instance */
	rlm_rcode_t rcode = RLM_MODULE_OK;     /* return code */
	rlm_couchbase_handle_t *handle = NULL; /* connection pool handle */
	char vpath[256], vkey[MAX_KEY_SIZE];   /* view path and query key */
	char docid[MAX_KEY_SIZE];              /* document id returned from view */
	char error[512];                       /* view error return */
	int idx = 0;                           /* row array index counter */
	char element[MAX_KEY_SIZE];            /* mapped radius attribute to element name */
	lcb_error_t cb_error = LCB_SUCCESS;    /* couchbase error holder */
	json_object *json, *jval;              /* json object holders */
	json_object *jrows = NULL;             /* json object to hold view rows */
	VALUE_PAIR *vp;                        /* value pair */
	uint32_t client_ip_addr = 0;           /* current client ip address */
	char const *client_cs_id = NULL;       /* current client calling station id */
	char *user_name = NULL;                /* user name from accounting document */
	char *session_id = NULL;               /* session id from accounting document */
	char *cs_id = NULL;                    /* calling station id from accounting document */
	uint32_t nas_addr = 0;                 /* nas address from accounting document */
	uint32_t nas_port = 0;                 /* nas port from accounting document */
	uint32_t framed_ip_addr = 0;           /* framed ip address from accounting document */
	char framed_proto = 0;                 /* framed proto from accounting document */
	int session_time = 0;                  /* session time from accounting document */

	/* do nothing if this is not enabled */
	if (inst->check_simul != true) {
		RDEBUG3("mod_checksimul returning noop - not enabled");
		return RLM_MODULE_NOOP;
	}

	/* ensure valid username in request */
	if ((!request->username) || (request->username->vp_length == '\0')) {
		RDEBUG3("mod_checksimul - invalid username");
		return RLM_MODULE_INVALID;
	}

	/* attempt to build view key */
	if (radius_xlat(vkey, sizeof(vkey), request, inst->simul_vkey, NULL, NULL) < 0) {
		/* log error */
		RERROR("could not find simultaneous use view key attribute (%s) in packet", inst->simul_vkey);
		/* return */
		return RLM_MODULE_FAIL;
	}

	/* get handle */
	handle = fr_connection_get(inst->pool);

	/* check handle */
	if (!handle) return RLM_MODULE_FAIL;

	/* set couchbase instance */
	lcb_t cb_inst = handle->handle;

	/* set cookie */
	cookie_t *cookie = handle->cookie;

	/* build view path */
	snprintf(vpath, sizeof(vpath), "%s?key=\"%s\"&stale=update_after",
		 inst->simul_view, vkey);

	/* query view for document */
	cb_error = couchbase_query_view(cb_inst, cookie, vpath, NULL);

	/* check error and object */
	if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success || !cookie->jobj) {
		/* log error */
		RERROR("failed to execute view request or parse return");
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto free_and_return;
	}

	/* debugging */
	RDEBUG3("cookie->jobj == %s", json_object_to_json_string(cookie->jobj));

	/* check for error in json object */
	if (json_object_object_get_ex(cookie->jobj, "error", &json)) {
		/* build initial error buffer */
		strlcpy(error, json_object_get_string(json), sizeof(error));
		/* get error reason */
		if (json_object_object_get_ex(cookie->jobj, "reason", &json)) {
			/* append divider */
			strlcat(error, " - ", sizeof(error));
			/* append reason */
			strlcat(error, json_object_get_string(json), sizeof(error));
		}
		/* log error */
		RERROR("view request failed with error: %s", error);
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto free_and_return;
	}

	/* check for document id in return */
	if (!json_object_object_get_ex(cookie->jobj, "rows", &json)) {
		/* log error */
		RERROR("failed to fetch rows from view payload");
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto free_and_return;
	}

	/* get and hold rows */
	jrows = json_object_get(json);

	/* free cookie object */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
		cookie->jobj = NULL;
	}

	/* check for valid row value */
	if (!jrows || !json_object_is_type(jrows, json_type_array)) {
		/* log error */
		RERROR("no valid rows returned from view: %s", vpath);
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto free_and_return;
	}

	/* debugging */
	RDEBUG3("jrows == %s", json_object_to_json_string(jrows));

	/* set the count */
	request->simul_count = json_object_array_length(jrows);

	/* debugging */
	RDEBUG("found %d open sessions for %s", request->simul_count, request->username->vp_strvalue);

	/* check count */
	if (request->simul_count < request->simul_max) {
		rcode = RLM_MODULE_OK;
		goto free_and_return;
	}

	/*
	 * Current session count exceeds configured maximum.
	 * Continue on to verify the sessions if configured otherwise stop here.
	 */
	if (inst->verify_simul != true) {
		rcode = RLM_MODULE_OK;
		goto free_and_return;
	}

	/* debugging */
	RDEBUG("verifying session count");

	/* reset the count */
	request->simul_count = 0;

	/* get client ip address for MPP detection below */
	if ((vp = pairfind(request->packet->vps, PW_FRAMED_IP_ADDRESS, 0, TAG_ANY)) != NULL) {
		client_ip_addr = vp->vp_ipaddr;
	}

	/* get calling station id for MPP detection below */
	if ((vp = pairfind(request->packet->vps, PW_CALLING_STATION_ID, 0, TAG_ANY)) != NULL) {
		client_cs_id = vp->vp_strvalue;
	}

	/* loop across all row elements */
	for (idx = 0; idx < json_object_array_length(jrows); idx++) {
		/* clear docid */
		memset(docid, 0, sizeof(docid));

		/* fetch current index */
		json = json_object_array_get_idx(jrows, idx);

		/* get document id */
		if (json_object_object_get_ex(json, "id", &jval)) {
			/* copy and check length */
			if (strlcpy(docid, json_object_get_string(jval), sizeof(docid)) >= sizeof(docid)) {
				RERROR("document id from row longer than MAX_KEY_SIZE (%d)", MAX_KEY_SIZE);
				continue;
			}
		}

		/* check for valid doc id */
		if (docid[0] == 0) {
			RWARN("failed to fetch document id from row - skipping");
			continue;
		}

		/* fetch document */
		cb_error = couchbase_get_key(cb_inst, cookie, docid);

		/* check error and object */
		if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success || !cookie->jobj) {
			/* log error */
			RERROR("failed to execute get request or parse return");
			/* set return */
			rcode = RLM_MODULE_FAIL;
			/* return */
			goto free_and_return;
		}

		/* debugging */
		RDEBUG3("cookie->jobj == %s", json_object_to_json_string(cookie->jobj));

		/* get element name for User-Name attribute */
		if (mod_attribute_to_element("User-Name", inst->map, &element) == 0) {
			/* get and check username element */
			if (!json_object_object_get_ex(cookie->jobj, element, &jval)){
				RDEBUG("cannot zap stale entry without username");
				rcode = RLM_MODULE_FAIL;
				goto free_and_return;
			}
			/* copy json string value to user_name */
			user_name = talloc_typed_strdup(request, json_object_get_string(jval));
		} else {
			RDEBUG("failed to find map entry for User-Name attribute");
			rcode = RLM_MODULE_FAIL;
			goto free_and_return;
		}

		/* get element name for Acct-Session-Id attribute */
		if (mod_attribute_to_element("Acct-Session-Id", inst->map, &element) == 0) {
			/* get and check session id element */
			if (!json_object_object_get_ex(cookie->jobj, element, &jval)){
				RDEBUG("cannot zap stale entry without session id");
				rcode = RLM_MODULE_FAIL;
				goto free_and_return;
			}
			/* copy json string value to session_id */
			session_id = talloc_typed_strdup(request, json_object_get_string(jval));
		} else {
			RDEBUG("failed to find map entry for Acct-Session-Id attribute");
			rcode = RLM_MODULE_FAIL;
			goto free_and_return;
		}

		/* get element name for NAS-IP-Address attribute */
		if (mod_attribute_to_element("NAS-IP-Address", inst->map, &element) == 0) {
			/* attempt to get and nas address element */
			if (json_object_object_get_ex(cookie->jobj, element, &jval)){
				nas_addr = inet_addr(json_object_get_string(jval));
			}
		}

		/* get element name for NAS-Port attribute */
		if (mod_attribute_to_element("NAS-Port", inst->map, &element) == 0) {
			/* attempt to get nas port element */
			if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
				nas_port = (uint32_t) json_object_get_int(jval);
			}
		}

		/* check terminal server */
		int check = rad_check_ts(nas_addr, nas_port, user_name, session_id);

		/* take action based on check return */
		if (check == 0) {
			/* stale record - zap it if enabled */
			if (inst->delete_stale_sessions) {
				/* get element name for Framed-IP-Address attribute */
				if (mod_attribute_to_element("Framed-IP-Address", inst->map, &element) == 0) {
					/* attempt to get framed ip address element */
					if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
						framed_ip_addr = inet_addr(json_object_get_string(jval));
					}
				}

				/* get element name for Framed-Port attribute */
				if (mod_attribute_to_element("Framed-Port", inst->map, &element) == 0) {
					/* attempt to get framed port element */
					if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
						if (strcmp(json_object_get_string(jval), "PPP") == 0) {
							framed_proto = 'P';
						} else if (strcmp(json_object_get_string(jval), "SLIP") == 0) {
							framed_proto = 'S';
						}
					}
				}

				/* get element name for Acct-Session-Time attribute */
				if (mod_attribute_to_element("Acct-Session-Time", inst->map, &element) == 0) {
					/* attempt to get session time element */
					if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
						session_time = json_object_get_int(jval);
					}
				}

				/* zap session */
				session_zap(request, nas_addr, nas_port, user_name, session_id,
					    framed_ip_addr, framed_proto, session_time);
			}
		} else if (check == 1) {
			/* user is still logged in - increase count */
			++request->simul_count;

			/* get element name for Framed-IP-Address attribute */
			if (mod_attribute_to_element("Framed-IP-Address", inst->map, &element) == 0) {
				/* attempt to get framed ip address element */
				if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
					framed_ip_addr = inet_addr(json_object_get_string(jval));
				} else {
					/* ensure 0 if not found */
					framed_ip_addr = 0;
				}
			}

			/* get element name for Calling-Station-Id attribute */
			if (mod_attribute_to_element("Calling-Station-Id", inst->map, &element) == 0) {
				/* attempt to get framed ip address element */
				if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
					/* copy json string value to cs_id */
					cs_id = talloc_typed_strdup(request, json_object_get_string(jval));
				} else {
					/* ensure null if not found */
					cs_id = NULL;
				}
			}

			/* Does it look like a MPP attempt? */
			if (client_ip_addr && framed_ip_addr && framed_ip_addr == client_ip_addr) {
				request->simul_mpp = 2;
			} else if (client_cs_id && cs_id && !strncmp(cs_id, client_cs_id, 16)) {
				request->simul_mpp = 2;
			}

		} else {
			/* check failed - return error */
			REDEBUG("failed to check the terminal server for user '%s'", user_name);
			rcode = RLM_MODULE_FAIL;
			goto free_and_return;
		}

		/* free and reset document user name talloc */
		if (user_name) {
			talloc_free(user_name);
			user_name = NULL;
		}

		/* free and reset document calling station id talloc */
		if (cs_id) {
			talloc_free(cs_id);
			cs_id = NULL;
		}

		/* free and reset document session id talloc */
		if (session_id) {
			talloc_free(session_id);
			session_id = NULL;
		}

		/* free and reset json object before fetching next row */
		if (cookie->jobj) {
			json_object_put(cookie->jobj);
			cookie->jobj = NULL;
		}
	}

	/* debugging */
	RDEBUG("retained %d open sessions for %s after verification",
	       request->simul_count, request->username->vp_strvalue);

	free_and_return:

	/* free document user name talloc */
	if (user_name) {
		talloc_free(user_name);
	}

	/* free document calling station id talloc */
	if (cs_id) {
		talloc_free(cs_id);
	}

	/* free document session id talloc */
	if (session_id) {
		talloc_free(session_id);
	}

	/* free rows */
	if (jrows) {
		json_object_put(jrows);
	}

	/* free and reset json object */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
		cookie->jobj = NULL;
	}

	/* release handle */
	if (handle) {
		fr_connection_release(inst->pool, handle);
	}

	/*
	 * The Auth module apparently looks at request->simul_count,
	 * not the return value of this module when deciding to deny
	 * a call for too many sessions.
	 */
	return rcode;
}
Example #9
0
OGRErr OGRGeoJSONWriteLayer::ICreateFeature( OGRFeature* poFeature )
{
    VSILFILE* fp = poDS_->GetOutputFile();

    OGRFeature* poFeatureToWrite;
    if( poCT_ != nullptr || bRFC7946_ )
    {
        poFeatureToWrite = new OGRFeature(poFeatureDefn_);
        poFeatureToWrite->SetFrom( poFeature );
        poFeatureToWrite->SetFID( poFeature->GetFID() );
        OGRGeometry* poGeometry = poFeatureToWrite->GetGeometryRef();
        if( poGeometry )
        {
            const char* const apszOptions[] = { "WRAPDATELINE=YES", nullptr };
            OGRGeometry* poNewGeom =
                OGRGeometryFactory::transformWithOptions(
                    poGeometry, poCT_, const_cast<char**>(apszOptions),
                    oTransformCache_);
            if( poNewGeom == nullptr )
            {
                delete poFeatureToWrite;
                return OGRERR_FAILURE;
            }

            OGREnvelope sEnvelope;
            poNewGeom->getEnvelope(&sEnvelope);
            if( sEnvelope.MinX < -180.0 || sEnvelope.MaxX > 180.0 ||
                sEnvelope.MinY < -90.0 || sEnvelope.MaxY > 90.0 )
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Geometry extent outside of [-180.0,180.0]x[-90.0,90.0] bounds");
                delete poFeatureToWrite;
                return OGRERR_FAILURE;
            }

            poFeatureToWrite->SetGeometryDirectly( poNewGeom );
        }
    }
    else
    {
        poFeatureToWrite = poFeature;
    }

    json_object* poObj =
        OGRGeoJSONWriteFeature( poFeatureToWrite, oWriteOptions_ );
    CPLAssert( nullptr != poObj );

    if( nOutCounter_ > 0 )
    {
        /* Separate "Feature" entries in "FeatureCollection" object. */
        VSIFPrintfL( fp, ",\n" );
    }
    VSIFPrintfL( fp, "%s", json_object_to_json_string( poObj ) );

    json_object_put( poObj );

    ++nOutCounter_;

    OGRGeometry* poGeometry = poFeatureToWrite->GetGeometryRef();
    if( bWriteFC_BBOX && poGeometry != nullptr && !poGeometry->IsEmpty() )
    {
        OGREnvelope3D sEnvelope = OGRGeoJSONGetBBox( poGeometry,
                                                     oWriteOptions_ );
        if( poGeometry->getCoordinateDimension() == 3 )
            bBBOX3D = true;

        if( !sEnvelopeLayer.IsInit() )
        {
            sEnvelopeLayer = sEnvelope;
        }
        else if( oWriteOptions_.bBBOXRFC7946 )
        {
            const bool bEnvelopeCrossAM = ( sEnvelope.MinX > sEnvelope.MaxX );
            const bool bEnvelopeLayerCrossAM =
                                ( sEnvelopeLayer.MinX > sEnvelopeLayer.MaxX );
            if( bEnvelopeCrossAM )
            {
                if( bEnvelopeLayerCrossAM )
                {
                    sEnvelopeLayer.MinX = std::min(sEnvelopeLayer.MinX,
                                                   sEnvelope.MinX);
                    sEnvelopeLayer.MaxX = std::max(sEnvelopeLayer.MaxX,
                                                   sEnvelope.MaxX);
                }
                else
                {
                    if( sEnvelopeLayer.MinX > 0 )
                    {
                        sEnvelopeLayer.MinX = std::min(sEnvelopeLayer.MinX,
                                                       sEnvelope.MinX);
                        sEnvelopeLayer.MaxX = sEnvelope.MaxX;
                    }
                    else if( sEnvelopeLayer.MaxX < 0 )
                    {
                        sEnvelopeLayer.MaxX = std::max(sEnvelopeLayer.MaxX,
                                                       sEnvelope.MaxX);
                        sEnvelopeLayer.MinX = sEnvelope.MinX;
                    }
                    else
                    {
                        sEnvelopeLayer.MinX = -180.0;
                        sEnvelopeLayer.MaxX = 180.0;
                    }
                }
            }
            else if( bEnvelopeLayerCrossAM )
            {
                if( sEnvelope.MinX > 0 )
                {
                    sEnvelopeLayer.MinX = std::min(sEnvelopeLayer.MinX,
                                                   sEnvelope.MinX);
                }
                else if( sEnvelope.MaxX < 0 )
                {
                    sEnvelopeLayer.MaxX = std::max(sEnvelopeLayer.MaxX,
                                                   sEnvelope.MaxX);
                }
                else
                {
                    sEnvelopeLayer.MinX = -180.0;
                    sEnvelopeLayer.MaxX = 180.0;
                }
            }
            else
            {
                sEnvelopeLayer.MinX = std::min(sEnvelopeLayer.MinX,
                                               sEnvelope.MinX);
                sEnvelopeLayer.MaxX = std::max(sEnvelopeLayer.MaxX,
                                               sEnvelope.MaxX);
            }

            sEnvelopeLayer.MinY = std::min(sEnvelopeLayer.MinY, sEnvelope.MinY);
            sEnvelopeLayer.MaxY = std::max(sEnvelopeLayer.MaxY, sEnvelope.MaxY);
        }
        else
        {
            sEnvelopeLayer.Merge(sEnvelope);
        }
    }

    if( poFeatureToWrite != poFeature )
        delete poFeatureToWrite;

    return OGRERR_NONE;
}
Example #10
0
//static
PackageDescription* PackageDescription::fromJson(json_object* root, const std::string& folderPath)
{
	if (!root)
		return NULL;

	bool success = false;

	PackageDescription* packageDesc = new PackageDescription();

	packageDesc->m_folderPath = folderPath;

	struct json_object* label = NULL;
	// ID: mandatory
	label = JsonGetObject(root, "id");
	if (label) {
		packageDesc->m_id = json_object_get_string(label);
		if (packageDesc->m_id == "") {
			g_warning("package %s has an empty ID field", folderPath.c_str());
			goto Done;
		}
	} else {
		g_warning("package %s does not have an ID", folderPath.c_str());
		goto Done;
	}

	// app (or apps) json array: optional
	label = JsonGetObject(root, "app");
	if (label) {
		packageDesc->m_appIds.push_back(std::string(json_object_get_string(label)));
	} else {
		label = JsonGetObject(root, "apps");
		if (label) {
			for (int i = 0; i < json_object_array_length(label); i++) {
				struct json_object* app = json_object_array_get_idx(label, i);
				if (app && !is_error(app)) {
					packageDesc->m_appIds.push_back(std::string(json_object_get_string(app)));
				}
			}
		}
	}

	// services json array: optional
	label = JsonGetObject(root, "services");
	if (label) {
		for (int i = 0; i < json_object_array_length(label); i++) {
			struct json_object* service = json_object_array_get_idx(label, i);
			if (service && !is_error(service)) {
				packageDesc->m_serviceIds.push_back(std::string(json_object_get_string(service)));
			}
		}
	}

	if (packageDesc->m_appIds.empty() && packageDesc->m_serviceIds.empty()) {
		g_warning("package %s does not have any apps or services", folderPath.c_str());
		goto Done;
	}

	// Optional parameters
	success = true;

	// version: optional
	label = JsonGetObject(root, "version");
	if (label) {
		packageDesc->m_version = json_object_get_string(label);
	}

	// accounts json array: optional
	label = JsonGetObject(root, "accounts");
	if (label) {
		for (int i = 0; i < json_object_array_length(label); i++) {
			struct json_object* accountId = json_object_array_get_idx(label, i);
			if (accountId && !is_error(accountId)) {
				packageDesc->m_accountIds.push_back(std::string(json_object_get_string(accountId)));
			}
		}
	}

	packageDesc->m_jsonString = json_object_to_json_string(root);

	Done:

	if (!success) {
		delete packageDesc;
		return NULL;
	}

	return packageDesc;
}
Example #11
0
/** Handle authorization requests using Couchbase document data
 *
 * Attempt to fetch the document assocaited with the requested user by
 * using the deterministic key defined in the configuration.  When a valid
 * document is found it will be parsed and the containing value pairs will be
 * injected into the request.
 *
 * @param  instance The module instance.
 * @param  request  The authorization request.
 * @return          Returns operation status (@p rlm_rcode_t).
 */
static rlm_rcode_t mod_authorize(void *instance, REQUEST *request)
{
	rlm_couchbase_t *inst = instance;       /* our module instance */
	rlm_couchbase_handle_t *handle = NULL;  /* connection pool handle */
	char dockey[MAX_KEY_SIZE];              /* our document key */
	lcb_error_t cb_error = LCB_SUCCESS;     /* couchbase error holder */
	rlm_rcode_t rcode = RLM_MODULE_OK;      /* return code */

	/* assert packet as not null */
	rad_assert(request->packet != NULL);

	/* attempt to build document key */
	if (radius_xlat(dockey, sizeof(dockey), request, inst->user_key, NULL, NULL) < 0) {
		/* log error */
		RERROR("could not find user key attribute (%s) in packet", inst->user_key);
		/* return */
		return RLM_MODULE_FAIL;
	}

	/* get handle */
	handle = fr_connection_get(inst->pool);

	/* check handle */
	if (!handle) return RLM_MODULE_FAIL;

	/* set couchbase instance */
	lcb_t cb_inst = handle->handle;

	/* set cookie */
	cookie_t *cookie = handle->cookie;

	/* fetch document */
	cb_error = couchbase_get_key(cb_inst, cookie, dockey);

	/* check error */
	if (cb_error != LCB_SUCCESS || !cookie->jobj) {
		/* log error */
		RERROR("failed to fetch document or parse return");
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto free_and_return;
	}

	/* debugging */
	RDEBUG3("parsed user document == %s", json_object_to_json_string(cookie->jobj));

	/* inject config value pairs defined in this json oblect */
	mod_json_object_to_value_pairs(cookie->jobj, "config", request);

	/* inject reply value pairs defined in this json oblect */
	mod_json_object_to_value_pairs(cookie->jobj, "reply", request);

	free_and_return:

	/* free json object */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
		cookie->jobj = NULL;
	}

	/* release handle */
	if (handle) {
		fr_connection_release(inst->pool, handle);
	}

	/* return */
	return rcode;
}
int json_object_get_string_len(json_object *obj) {
	if (json_object_get_type(obj) != json_type_string)
		return 0;
	return (int)strlen(json_object_to_json_string(obj));
}
Example #13
0
void json_metadata(FILE *file)
{
	char send_start_time[STRTIME_LEN+1];
	assert(dstrftime(send_start_time, STRTIME_LEN, "%Y-%m-%dT%H:%M:%S%z", zsend.start));
	char send_end_time[STRTIME_LEN+1];
	assert(dstrftime(send_end_time, STRTIME_LEN, "%Y-%m-%dT%H:%M:%S%z", zsend.finish));
	char recv_start_time[STRTIME_LEN+1];
	assert(dstrftime(recv_start_time, STRTIME_LEN, "%Y-%m-%dT%H:%M:%S%z", zrecv.start));
	char recv_end_time[STRTIME_LEN+1];
	assert(dstrftime(recv_end_time, STRTIME_LEN, "%Y-%m-%dT%H:%M:%S%z", zrecv.finish));
	double hitrate = ((double) 100 * zrecv.success_unique)/((double)zsend.sent);

	json_object *obj = json_object_new_object();

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

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

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


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

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

	json_object_object_add(obj, "ip_fragments",
            json_object_new_int(zrecv.ip_fragments));
	json_object_object_add(obj, "blacklist_total_allowed",
		json_object_new_int64(zconf.total_allowed));
	json_object_object_add(obj, "blacklist_total_not_allowed",
		json_object_new_int64(zconf.total_disallowed));
//	json_object_object_add(obj, "blacklisted",
//            json_object_new_int64(zsend.blacklisted));
//	json_object_object_add(obj, "whitelisted",
//            json_object_new_int64(zsend.whitelisted));
	json_object_object_add(obj, "first_scanned",
            json_object_new_int64(zsend.first_scanned));
	json_object_object_add(obj, "send_to_failures",
            json_object_new_int64(zsend.sendto_failures));
	json_object_object_add(obj, "total_sent",
            json_object_new_int64(zsend.sent));
	json_object_object_add(obj, "success_total",
            json_object_new_int64(zrecv.success_total));
	json_object_object_add(obj, "success_unique",
            json_object_new_int64(zrecv.success_unique));
	if (zconf.fsconf.app_success_index >= 0) {
		json_object_object_add(obj, "app_success_total",
                json_object_new_int64(zrecv.app_success_total));
		json_object_object_add(obj, "app_success_unique",
                json_object_new_int64(zrecv.app_success_unique));
	}
	json_object_object_add(obj, "success_cooldown_total",
            json_object_new_int64(zrecv.cooldown_total));
	json_object_object_add(obj, "success_cooldown_unique",
            json_object_new_int64(zrecv.cooldown_unique));
	json_object_object_add(obj, "failure_total",
            json_object_new_int64(zrecv.failure_total));

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

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

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

	if (zconf.destination_cidrs_len) {
		json_object *cli_dest_cidrs = json_object_new_array();
		for (int i=0; i < zconf.destination_cidrs_len; i++) {
			json_object_array_add(cli_dest_cidrs, json_object_new_string(zconf.destination_cidrs[i]));
		}
		json_object_object_add(obj, "cli_cidr_destinations",
				cli_dest_cidrs);
	}
	if (zconf.probe_args) {
		json_object_object_add(obj, "probe_args",
			json_object_new_string(zconf.probe_args));
	}
	if (zconf.output_args) {
		json_object_object_add(obj, "output_args",
			json_object_new_string(zconf.output_args));
	}
	{
		char mac_buf[(MAC_ADDR_LEN * 2) + (MAC_ADDR_LEN - 1) + 1];
		memset(mac_buf, 0, sizeof(mac_buf));
		char *p = mac_buf;
		for(int i=0; i < MAC_ADDR_LEN; i++) {
			if (i == MAC_ADDR_LEN-1) {
				snprintf(p, 3, "%.2x", zconf.gw_mac[i]);
				p += 2;
			} else {
				snprintf(p, 4, "%.2x:", zconf.gw_mac[i]);
				p += 3;
			}
		}
		json_object_object_add(obj, "gateway_mac", json_object_new_string(mac_buf));
	}
	if (zconf.gw_ip) {
		struct in_addr addr;
		addr.s_addr = zconf.gw_ip;
		json_object_object_add(obj, "gateway_ip", json_object_new_string(inet_ntoa(addr)));
	}
	{
		char mac_buf[(ETHER_ADDR_LEN * 2) + (ETHER_ADDR_LEN - 1) + 1];
		char *p = mac_buf;
		for(int i=0; i < ETHER_ADDR_LEN; i++) {
			if (i == ETHER_ADDR_LEN-1) {
				snprintf(p, 3, "%.2x", zconf.hw_mac[i]);
				p += 2;
			} else {
				snprintf(p, 4, "%.2x:", zconf.hw_mac[i]);
				p += 3;
			}
		}
		json_object_object_add(obj, "source_mac", json_object_new_string(mac_buf));
	}
	json_object_object_add(obj, "source_ip_first",
			json_object_new_string(zconf.source_ip_first));
	json_object_object_add(obj, "source_ip_last",
			json_object_new_string(zconf.source_ip_last));
	if (zconf.output_filename) {
		json_object_object_add(obj, "output_filename",
				json_object_new_string(zconf.output_filename));
	}
	if (zconf.blacklist_filename) {
		json_object_object_add(obj,
			"blacklist_filename",
			json_object_new_string(zconf.blacklist_filename));
	}
	if (zconf.whitelist_filename) {
		json_object_object_add(obj,
			"whitelist_filename",
			json_object_new_string(zconf.whitelist_filename));
	}
	if (zconf.list_of_ips_filename) {
		json_object_object_add(obj,
			"list_of_ips_filename",
			json_object_new_string(zconf.list_of_ips_filename));
		json_object_object_add(obj,
			"list_of_ips_count",
			json_object_new_int(zconf.list_of_ips_count));
		json_object_object_add(obj,
			"list_of_ips_tried_sent",
			json_object_new_int(zsend.tried_sent));

	}
	json_object_object_add(obj, "dryrun",
            json_object_new_int(zconf.dryrun));
	json_object_object_add(obj, "quiet",
            json_object_new_int(zconf.quiet));
	json_object_object_add(obj, "log_level",
            json_object_new_int(zconf.log_level));

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

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

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

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

	fprintf(file, "%s\n", json_object_to_json_string(obj));
	json_object_put(obj);
}
static void
mtev_capabilities_tobuff_json(mtev_capsvc_closure_t *cl, eventer_func_t curr) {
    const char **mod_names;
    struct utsname utsn;
    char vbuff[128];
    mtev_hash_table *lc;
    mtev_hash_iter iter = MTEV_HASH_ITER_ZERO;
    const char *k;
    int klen, i, nmods;
    void *data;
    struct timeval now;
    struct dso_type *t;

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

    /* fill out capabilities */

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

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

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

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

    /* features */
    feat = json_object_new_object();
    if(mtev_hash_size(&features)) {
      mtev_hash_iter iter2 = MTEV_HASH_ITER_ZERO;
      void *vfv;
      const char *f;
      int flen;
      while(mtev_hash_next(&features, &iter2, &f, &flen, &vfv)) {
        struct json_object *featnode;
        featnode = json_object_new_object();
        if(vfv) json_object_object_add(featnode, "version", json_object_new_string(vfv));
        json_object_object_add(feat, f, featnode);
      }
    }
    json_object_object_add(doc, "features", feat);

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

    svcs = json_object_new_object();
    lc = mtev_listener_commands();
    while(mtev_hash_next(lc, &iter, &k, &klen, &data)) {
      struct json_object *cnode, *cmds;
      char hexcode[11];
      const char *name;
      eventer_func_t *f = (eventer_func_t *)k;
      mtev_hash_table *sc = (mtev_hash_table *)data;
      mtev_hash_iter sc_iter = MTEV_HASH_ITER_ZERO;
      const char *sc_k;
      int sc_klen;
      void *sc_data;

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

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

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

    mods = json_object_new_object();

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

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

    /* Clean up after ourselves */
    json_object_put(doc);
}
Example #15
0
bool
_LSPrivateGetMallinfo(LSHandle* sh, LSMessage *message, void *ctx)
{
    LSError lserror;
    LSErrorInit(&lserror);

    struct json_object *ret_obj = NULL;
    struct json_object *true_obj = NULL;
    struct json_object *mallinfo_obj = NULL;
    struct json_object *allocator_name_obj = NULL;
    struct json_object *slot_a_obj = NULL;
    struct json_object *slot_d_obj = NULL;
    struct json_object *slot_e_obj = NULL;
    struct json_object *slot_f_obj = NULL;
    struct json_object *slot_h_obj = NULL;
    struct json_object *slot_i_obj = NULL;
    struct json_object *slot_j_obj = NULL;

    const char *sender = LSMessageGetSenderServiceName(message);

    if (!sender || strcmp(sender, MONITOR_NAME) != 0)
    {
        g_critical("WARNING: mallinfo debug method not called by monitor;"
                   " ignoring (service name: %s, unique_name: %s)",
                   sender, LSMessageGetSender(message));
        return true;
    }

    ret_obj = json_object_new_object();
    if (JSON_ERROR(ret_obj)) goto error;
       
    true_obj = json_object_new_boolean(true);
    if (JSON_ERROR(true_obj)) goto error;
 
    mallinfo_obj = json_object_new_object();
    if (JSON_ERROR(mallinfo_obj)) goto error;

    /* returnValue: true,
     * mallinfo: {key: int,...}
     */

    typedef struct mallinfo (*mallinfo_t)();
    static mallinfo_t mallinfo_p = NULL;

    if (mallinfo_p == NULL) {
        mallinfo_p = (mallinfo_t)dlsym(RTLD_DEFAULT, "mallinfo");
        if (mallinfo_p == NULL)
            mallinfo_p = (mallinfo_t)-1;
    }
    struct mallinfo mi;
    if (mallinfo_p != (mallinfo_t)-1) {
        mi = mallinfo_p();
    } else {
        memset(&mi, '\0', sizeof(mi));
    }
    
    allocator_name_obj = json_object_new_string("ptmalloc");
    if (JSON_ERROR(allocator_name_obj)) goto error;

    slot_a_obj = json_object_new_int(mi.arena);
    if (JSON_ERROR(slot_a_obj)) goto error;

    slot_d_obj = json_object_new_int(mi.hblks);
    if (JSON_ERROR(slot_d_obj)) goto error;

    slot_e_obj = json_object_new_int(mi.hblkhd);
    if (JSON_ERROR(slot_e_obj)) goto error;

    slot_f_obj = json_object_new_int(mi.usmblks);
    if (JSON_ERROR(slot_f_obj)) goto error;

    slot_h_obj = json_object_new_int(mi.uordblks);
    if (JSON_ERROR(slot_h_obj)) goto error;

    slot_i_obj = json_object_new_int(mi.fordblks);
    if (JSON_ERROR(slot_i_obj)) goto error;
    
    slot_j_obj = json_object_new_int(mi.keepcost);
    if (JSON_ERROR(slot_j_obj)) goto error;

    json_object_object_add(mallinfo_obj, "allocator", allocator_name_obj);
    json_object_object_add(mallinfo_obj, "sbrk_bytes", slot_a_obj);
    json_object_object_add(mallinfo_obj, "mmap_count", slot_d_obj);
    json_object_object_add(mallinfo_obj, "mmap_bytes", slot_e_obj);
    json_object_object_add(mallinfo_obj, "max_malloc_bytes", slot_f_obj);
    json_object_object_add(mallinfo_obj, "malloc_bytes", slot_h_obj);
    json_object_object_add(mallinfo_obj, "slack_bytes", slot_i_obj);
    json_object_object_add(mallinfo_obj, "trimmable_slack_bytes", slot_j_obj);
        
    json_object_object_add(ret_obj, "returnValue", true_obj);
    json_object_object_add(ret_obj, "mallinfo", mallinfo_obj);

    bool reply_ret = LSMessageReply(sh, message, json_object_to_json_string(ret_obj), &lserror);
    if (!reply_ret)
    {
        g_critical("%s: sending malloc info failed", __FUNCTION__);
        LSErrorPrint(&lserror, stderr);
        LSErrorFree(&lserror);
    }

    json_object_put(ret_obj);
    
    return true;

error:
    
    if (!JSON_ERROR(ret_obj)) json_object_put(ret_obj);
    if (!JSON_ERROR(true_obj)) json_object_put(true_obj);
    if (!JSON_ERROR(mallinfo_obj)) json_object_put(mallinfo_obj);
    
    if (!JSON_ERROR(allocator_name_obj)) json_object_put(allocator_name_obj);
    if (!JSON_ERROR(slot_a_obj)) json_object_put(slot_a_obj);
    if (!JSON_ERROR(slot_d_obj)) json_object_put(slot_d_obj);
    if (!JSON_ERROR(slot_e_obj)) json_object_put(slot_e_obj);
    if (!JSON_ERROR(slot_f_obj)) json_object_put(slot_f_obj);
    if (!JSON_ERROR(slot_h_obj)) json_object_put(slot_h_obj);
    if (!JSON_ERROR(slot_i_obj)) json_object_put(slot_i_obj);
    if (!JSON_ERROR(slot_j_obj)) json_object_put(slot_j_obj);
    
    return true;
}
static void
on_channel_message(hook_cmessage_data_t *data)
{
    
    if (data != NULL && data->msg != NULL) {	

        elog("nick and channel strings");
        // nick and channel strings
        char *nick = data->u->nick;
        char *channel = data->c->name;

        elog("the incoming message");
        // the incoming message
        char check_message[565];
        sprintf(check_message, "%s", data->msg);

        /*
        	This routine checks to see if the incoming message is a CTCP of type JSON, and if it is, stores the JSON object in jsonIn.

        	in ruby:

        	messages = check_message.split(" ")
        	if messages[0] == "JSON"
        		jsonIn = messages[1..-1].join(" ")
        	end

        */
        elog("parse for CTCP JSON");
        char jsonIn[565];
        char *pch;
        pch = strtok(check_message," ");
        int i = 0;
        int isJSONCTCP = 0;
        while (pch != NULL) {
            if (i == 0) { // if messages[0] == "JSON"
                if (strcmp(pch, "JSON") == 0) { // "JSON" has a \001 as that space, be warry of that!!!
                    isJSONCTCP = 1;
                }
                else { // might as well get out of here, right?
                    elog("not a valid CTCP JSON message, leaving");
                    return;
                }
            }
            if (i == 1 && isJSONCTCP == 1) { // messages[1..-1]
                strcpy(jsonIn, pch); 
            }
            if (i > 1 && isJSONCTCP == 1) { // .join(" ")
            	strcat(jsonIn, " ");
            	strcat(jsonIn, pch);
            }
            pch = strtok(NULL, " ");
            i++;
        }

        //printf("jsonIn: %s\n", jsonIn);
        //printf("strlen(jsonIn): %i\n", (int)strlen(jsonIn));

        elog("check if it was a CTCP JSON message");
        if ((int)strlen(jsonIn) > 0) { // if it was a JSON CTCP

            elog("parse the JSON");
            // parse the JSON
            json_object *new_obj;
            new_obj = json_tokener_parse(jsonIn);

            elog("check to see if it is valid JSON");
            // check to see if it is valid JSON
            json_type o_type;
            o_type = json_object_get_type(new_obj);
            if (o_type == json_type_null) {
                elog("not valid json, leaving");
                return;
            }

            elog("getting timestamps");
            // getting timestamps
            time_t clock = time(NULL);
            char *currentTime = ctime(&clock);
            long epoch_time = (long)clock;

            elog("adding to the incoming JSON a bunch of fields that shouldn't be set by clients");
            // adding to the incoming JSON a bunch of fields that shouldn't be set by clients
            json_object_object_add(new_obj, "epoch_time", json_object_new_int(epoch_time));
            json_object_object_add(new_obj, "time", json_object_new_string(currentTime));
            json_object_object_add(new_obj, "nick", json_object_new_string(nick));
            json_object_object_add(new_obj, "channel", json_object_new_string(channel));


            elog("I don't totally know why I need to load up the string like this... I need to know more about C!");
            // I don't totally know why I need to load up the string like this... I need to know more about C!
            char jsonSave[565];
            sprintf(jsonSave, "%s", json_object_to_json_string(new_obj));

            elog("connect to Redis");
            // connect to Redis
            redisContext *redis = redisConnect("127.0.0.1", 6379);
            redisReply *reply;

            elog("our Redis list name, based on the channel");
            // our Redis list name, based on the channel
            char list[100];
            sprintf(list, "channel_history:%s", channel);

            elog("save the JSON to the list");
            // save the JSON to the list
            reply = redisCommand(redis, "RPUSH %s %s", list, jsonSave);
            freeReplyObject(reply);
            
            reply = redisCommand(redis, "LLEN %s", list);
  	        if (reply->integer > 200) {
  	            redisCommand(redis, "LPOP %s", list);
  	        }
  	        freeReplyObject(reply);

            elog("free at last!");
            // free at last!
            redisFree(redis);
        }

    }
}
Example #17
0
/* get all the object's countes together as CEE. */
static rsRetVal
getStatsLineCEE(statsobj_t *pThis, cstr_t **ppcstr, const statsFmtType_t fmt, const int8_t bResetCtrs)
{
	cstr_t *pcstr;
	ctr_t *pCtr;
	json_object *root, *values;
	DEFiRet;

	root = values = NULL;

	CHKiRet(cstrConstruct(&pcstr));

	if (fmt == statsFmt_CEE)
		CHKiRet(rsCStrAppendStrWithLen(pcstr, UCHAR_CONSTANT("@cee: "), 6));

	CHKmalloc(root = json_object_new_object());

	CHKiRet(addContextForReporting(root, UCHAR_CONSTANT("name"), pThis->name));
	
	if(pThis->origin != NULL) {
		CHKiRet(addContextForReporting(root, UCHAR_CONSTANT("origin"), pThis->origin));
	}

	if (pThis->reporting_ns == NULL) {
		values = json_object_get(root);
	} else {
		CHKmalloc(values = json_object_new_object());
		json_object_object_add(root, (const char*) pThis->reporting_ns, json_object_get(values));
	}

	/* now add all counters to this line */
	pthread_mutex_lock(&pThis->mutCtr);
	for(pCtr = pThis->ctrRoot ; pCtr != NULL ; pCtr = pCtr->next) {
		if (fmt == statsFmt_JSON_ES) {
			/* work-around for broken Elasticsearch JSON implementation:
			 * we need to replace dots by a different char, we use bang.
			 * Note: ES 2.0 does not longer accept dot in name
			 */
			uchar esbuf[256];
			strncpy((char*)esbuf, (char*)pCtr->name, sizeof(esbuf)-1);
			esbuf[sizeof(esbuf)-1] = '\0';
			for(uchar *c = esbuf ; *c ; ++c) {
				if(*c == '.')
					*c = '!';
			}
			CHKiRet(addCtrForReporting(values, esbuf, accumulatedValue(pCtr)));
		} else {
			CHKiRet(addCtrForReporting(values, pCtr->name, accumulatedValue(pCtr)));
		}
		resetResettableCtr(pCtr, bResetCtrs);
	}
	pthread_mutex_unlock(&pThis->mutCtr);
	CHKiRet(rsCStrAppendStr(pcstr, (const uchar*) json_object_to_json_string(root)));

	cstrFinalize(pcstr);
	*ppcstr = pcstr;

finalize_it:
	if (root != NULL) {
		json_object_put(root);
	}
	if (values != NULL) {
		json_object_put(values);
	}
	
	RETiRet;
}
OSStatus _LocalConfigRespondInComingMessage(int fd, ECS_HTTPHeader_t* inHeader, mico_Context_t * const inContext)
{
  OSStatus err = kUnknownErr;
  const char * json_str;
  uint8_t *httpResponse = NULL;
  size_t httpResponseLen = 0;
  json_object* report = NULL;
  char err_msg[32] = {0};
  
  MVDActivateRequestData_t devActivateRequestData;
  MVDAuthorizeRequestData_t devAuthorizeRequestData;
  MVDResetRequestData_t devResetRequestData;
  MVDOTARequestData_t devOTARequestData;
  MVDGetStateRequestData_t devGetStateRequestData;
  
  fogcloud_config_log_trace();
  
  if(ECS_HTTPHeaderMatchURL( inHeader, kCONFIGURLDevState ) == kNoErr){
    if(inHeader->contentLength > 0){
      fogcloud_config_log("Recv device getState request.");
      memset((void*)&devGetStateRequestData, '\0', sizeof(devGetStateRequestData));
      err = getMVDGetStateRequestData(inHeader->extraDataPtr, &devGetStateRequestData);
      require_noerr( err, exit );
      report = json_object_new_object();
      err = MicoFogCloudGetState(inContext, devGetStateRequestData, report);
      require_noerr( err, exit );
      fogcloud_config_log("get device state success!");
      json_str = (char*)json_object_to_json_string(report);
      //config_log("json_str=%s", json_str);
      err = ECS_CreateSimpleHTTPMessage( ECS_kMIMEType_JSON, (uint8_t*)json_str, strlen(json_str),
                                        &httpResponse, &httpResponseLen );
      require( httpResponse, exit );
      err = SocketSend( fd, httpResponse, httpResponseLen );
      SocketClose(&fd);
    }
    goto exit;
  }
  else if(ECS_HTTPHeaderMatchURL( inHeader, kCONFIGURLDevActivate ) == kNoErr){
    if(inHeader->contentLength > 0){
      fogcloud_config_log("Recv device activate request.");
      memset((void*)&devActivateRequestData, '\0', sizeof(devActivateRequestData));
      err = getMVDActivateRequestData(inHeader->extraDataPtr, &devActivateRequestData);
      require_noerr( err, exit );
      err = MicoFogCloudActivate(inContext, devActivateRequestData);
      require_noerr( err, exit );
      fogcloud_config_log("Device activate success!");
      report = json_object_new_object();
      require_action(report, exit, err = kNoMemoryErr);
      json_object_object_add(report, "device_id",
                             json_object_new_string(inContext->flashContentInRam.appConfig.fogcloudConfig.deviceId));
      json_str = (char*)json_object_to_json_string(report);
      //config_log("json_str=%s", json_str);
      err = ECS_CreateSimpleHTTPMessage( ECS_kMIMEType_JSON, (uint8_t*)json_str, strlen(json_str),
                                        &httpResponse, &httpResponseLen );
      require_noerr( err, exit );
      require( httpResponse, exit );
      err = SocketSend( fd, httpResponse, httpResponseLen );
      SocketClose(&fd);
    }
    goto exit;
  }
  else if(ECS_HTTPHeaderMatchURL( inHeader, kCONFIGURLDevAuthorize ) == kNoErr){
    if(inHeader->contentLength > 0){
      fogcloud_config_log("Recv device authorize request.");
      memset((void*)&devAuthorizeRequestData, '\0', sizeof(devAuthorizeRequestData));
      err = getMVDAuthorizeRequestData( inHeader->extraDataPtr, &devAuthorizeRequestData);
      require_noerr( err, exit );
      err = MicoFogCloudAuthorize(inContext, devAuthorizeRequestData);
      require_noerr( err, exit );
      fogcloud_config_log("Device authorize success!");
      report = json_object_new_object();
      require_action(report, exit, err = kNoMemoryErr);
      json_object_object_add(report, "device_id",
                             json_object_new_string(inContext->flashContentInRam.appConfig.fogcloudConfig.deviceId));
      json_str = (char*)json_object_to_json_string(report);
      //config_log("json_str=%s", json_str);
      err = ECS_CreateSimpleHTTPMessage( ECS_kMIMEType_JSON, (uint8_t*)json_str, strlen(json_str),
                                        &httpResponse, &httpResponseLen );
      require( httpResponse, exit );
      err = SocketSend( fd, httpResponse, httpResponseLen );
      SocketClose(&fd);
    }
    goto exit;
  }
  else if(ECS_HTTPHeaderMatchURL( inHeader, kCONFIGURLResetCloudDevInfo ) == kNoErr){
    if(inHeader->contentLength > 0){
      fogcloud_config_log("Recv cloud device info reset request.");
      memset((void*)&devResetRequestData, '\0', sizeof(devResetRequestData));
      err = getMVDResetRequestData( inHeader->extraDataPtr, &devResetRequestData);
      require_noerr( err, exit );
      err = MicoFogCloudResetCloudDevInfo(inContext, devResetRequestData);
      require_noerr( err, exit );
      fogcloud_config_log("Device cloud reset success!");
      err = ECS_CreateSimpleHTTPOKMessage( &httpResponse, &httpResponseLen );
      require_noerr( err, exit );
      require( httpResponse, exit );
      err = SocketSend( fd, httpResponse, httpResponseLen );
      SocketClose(&fd);
     
      inContext->micoStatus.sys_state = eState_Software_Reset;
      require(inContext->micoStatus.sys_state_change_sem, exit);
      mico_rtos_set_semaphore(&inContext->micoStatus.sys_state_change_sem);
    }
    goto exit;
  }
#ifdef MICO_FLASH_FOR_UPDATE
  else if(ECS_HTTPHeaderMatchURL( inHeader, kCONFIGURLDevFWUpdate ) == kNoErr){
    if(inHeader->contentLength > 0){
      fogcloud_config_log("Recv device fw_update request.");
      memset((void*)&devOTARequestData, '\0', sizeof(devOTARequestData));
      err = getMVDOTARequestData( inHeader->extraDataPtr, &devOTARequestData);
      require_noerr( err, exit );
      err = MicoFogCloudFirmwareUpdate(inContext, devOTARequestData);
      require_noerr( err, exit );
      fogcloud_config_log("Device firmware update success!");
      err = ECS_CreateSimpleHTTPOKMessage( &httpResponse, &httpResponseLen );
      require_noerr( err, exit );
      require( httpResponse, exit );
      err = SocketSend( fd, httpResponse, httpResponseLen );
      SocketClose(&fd);
      fogcloud_config_log("OTA bin_size=%lld, bin_version=%s",
                          inContext->appStatus.fogcloudStatus.RecvRomFileSize,
                          inContext->flashContentInRam.appConfig.fogcloudConfig.romVersion );
      if(0 == inContext->appStatus.fogcloudStatus.RecvRomFileSize){
        //no need to update, return size = 0, no need to boot bootloader
        err = kNoErr;
        goto exit;
      }
      
      mico_rtos_lock_mutex(&inContext->flashContentInRam_mutex);
      memset(&inContext->flashContentInRam.bootTable, 0, sizeof(boot_table_t));
      inContext->flashContentInRam.bootTable.length = inContext->appStatus.fogcloudStatus.RecvRomFileSize;
      inContext->flashContentInRam.bootTable.start_address = UPDATE_START_ADDRESS;
      inContext->flashContentInRam.bootTable.type = 'A';
      inContext->flashContentInRam.bootTable.upgrade_type = 'U';
      MICOUpdateConfiguration(inContext);
      
      mico_rtos_unlock_mutex(&inContext->flashContentInRam_mutex);
      inContext->micoStatus.sys_state = eState_Software_Reset;
      require(inContext->micoStatus.sys_state_change_sem, exit);
      mico_rtos_set_semaphore(&inContext->micoStatus.sys_state_change_sem);
    }
    goto exit;
  }
#endif
  else{
    return kNotFoundErr;
  };
  
exit:
  if((kNoErr != err) && (fd > 0)){
    //ECS_CreateSimpleHTTPFailedMessage( &httpResponse, &httpResponseLen );
    sprintf(err_msg, "{\"error\": %d}", err);
    ECS_CreateHTTPFailedMessage("500", "FAILED", ECS_kMIMEType_JSON, strlen(err_msg),
                                (uint8_t*)err_msg, strlen(err_msg),
                                &httpResponse, &httpResponseLen );
    require( httpResponse, exit );
    SocketSend( fd, httpResponse, httpResponseLen );
    SocketClose(&fd);
  }
  if(httpResponse) free(httpResponse);
  if(report) json_object_put(report);
  return err;
}
/** Handle authorization requests using Couchbase document data
 *
 * Attempt to fetch the document assocaited with the requested user by
 * using the deterministic key defined in the configuration.  When a valid
 * document is found it will be parsed and the containing value pairs will be
 * injected into the request.
 *
 * @param  instance The module instance.
 * @param  request  The authorization request.
 * @return          Returns operation status (@p rlm_rcode_t).
 */
static rlm_rcode_t CC_HINT(nonnull) mod_authorize(void *instance, REQUEST *request) {
	rlm_couchbase_t *inst = instance;       /* our module instance */
	void *handle = NULL;                    /* connection pool handle */
	char dockey[MAX_KEY_SIZE];              /* our document key */
	lcb_error_t cb_error = LCB_SUCCESS;     /* couchbase error holder */

	/* assert packet as not null */
	rad_assert(request->packet != NULL);

	/* attempt to build document key */
	if (radius_xlat(dockey, sizeof(dockey), request, inst->user_key, NULL, NULL) < 0) {
		/* log error */
		RERROR("could not find user key attribute (%s) in packet", inst->user_key);
		/* return */
		return RLM_MODULE_FAIL;
	}

	/* get handle */
	handle = fr_connection_get(inst->pool);

	/* check handle */
	if (!handle) return RLM_MODULE_FAIL;

	/* set handle pointer */
	rlm_couchbase_handle_t *handle_t = handle;

	/* set couchbase instance */
	lcb_t cb_inst = handle_t->handle;

	/* set cookie */
	cookie_t *cookie = handle_t->cookie;

	/* check cookie */
	if (cookie) {
		/* clear cookie */
		memset(cookie, 0, sizeof(cookie_t));
	} else {
		/* log error */
		RERROR("cookie not usable - possibly not allocated");
		/* free connection */
		if (handle) {
			fr_connection_release(inst->pool, handle);
		}
		/* return */
		return RLM_MODULE_FAIL;
	}

	/* reset  cookie error status */
	cookie->jerr = json_tokener_success;

	/* fetch document */
	cb_error = couchbase_get_key(cb_inst, cookie, dockey);

	/* check error */
	if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success || cookie->jobj == NULL) {
		/* log error */
		RERROR("failed to fetch document or parse return");
		/* free json object */
		if (cookie->jobj) {
			json_object_put(cookie->jobj);
		}
		/* release handle */
		if (handle) {
			fr_connection_release(inst->pool, handle);
		}
		/* return */
		return RLM_MODULE_FAIL;
	}

	/* debugging */
	RDEBUG("parsed user document == %s", json_object_to_json_string(cookie->jobj));

	/* inject config value pairs defined in this json oblect */
	mod_json_object_to_value_pairs(cookie->jobj, "config", request);

	/* inject reply value pairs defined in this json oblect */
	mod_json_object_to_value_pairs(cookie->jobj, "reply", request);

	/* free json object */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
	}

	/* release handle */
	if (handle) {
		fr_connection_release(inst->pool, handle);
	}

	/* return okay */
	return RLM_MODULE_OK;
}
Example #20
0
static int vlan_find(struct ubus_context *ctx, struct ubus_object *obj,
		struct ubus_request_data *req, const char *method,
		struct blob_attr *msg)
{
	struct blob_attr *tb[__VLAN_FIND_MAX];
	u8 mode = 0;

	int resCode = LR_SUCCESS;
	const char *pmsg =  getJsonMsg(LR_INVALID_PARAM);
	json_object *result = NULL;

	blobmsg_parse(vlan_find_policy, ARRAY_SIZE(vlan_find_policy), tb, blob_data(msg), blob_len(msg));

	if(!tb[VLAN_FIND_MODE]){
		resCode = LR_INVALID_PARAM;
		goto returnMsg;
	}
	mode = blobmsg_get_u8(tb[VLAN_FIND_MODE]);
	if(1 == mode){
		/* find a special VLAN ID */
		int vid;
		bool found;
		VLAN_ENTRY vlanEntry;
		if(!tb[VLAN_FIND_ID]){
			resCode = LR_INVALID_PARAM;
			goto returnMsg;
		}
		vid  = blobmsg_get_u16(tb[VLAN_FIND_ID]);
		
		resCode =  find_vlan_in_vlanDatabase(vid, &vlanEntry, &found);	
		if(resCode != LR_ERR_NONE){
			pmsg = getJsonMsg(resCode);
			goto returnMsg;
		}
		if(found){
			resCode = LR_FOUND;
			result = gen_json_object_vlan_entry(&vlanEntry);
			pmsg = json_object_to_json_string(result);
		}else{
			resCode = LR_NOT_FOUND;
			pmsg = getJsonMsg(LR_NOT_EXIST);
		}

	}else if( 3== mode){
		/* find all VLAN ID in the hardware VLAN LIST , include port attribute*/
		VLAN_ENTRY *vlanEntry = NULL;
		int vlanEntryCnt;

		resCode = find_all_vlan_in_vlanDatabase(&vlanEntry, &vlanEntryCnt);
		if(resCode != LR_ERR_NONE){
			pmsg = getJsonMsg(resCode);
			goto returnMsg;
		}
		json_object *vidList = json_object_new_array();
		result = json_object_new_object();
	    for(int i=0; i< vlanEntryCnt; i++){
			json_object *vlnEntry = gen_json_object_vlan_entry(vlanEntry+i);		
			json_object_array_add(vidList, vlnEntry);
		}

		json_object_object_add(result, "vlanlist", vidList);
		pmsg = json_object_to_json_string(result);

		//free vlan entry
		free_VLAN_ENTRY_pointer(vlanEntry, vlanEntryCnt);
	}else{
		/* find all VLAN ID in the hardware VLAN LIST */
		u8 vids[4095] = {0};
		int vidCnt;
		int i;
		memset(vids, 0, 4095);

		resCode = find_all_vlan_in_vlanDatabase_summary((u8 *)&vids, &vidCnt);
		if(resCode != LR_ERR_NONE){
			pmsg = getJsonMsg(resCode);
			goto returnMsg;
		}
		
		json_object *vidList = json_object_new_array();
		result = json_object_new_object();

		for(i=1; i< 4095; i++){
			if(vids[i] == 1){
				json_object_array_add(vidList, json_object_new_int(i));
			}
		}
		json_object_object_add(result, "vlanlist", vidList);

		pmsg = json_object_to_json_string(result);

	}

returnMsg:
	blob_buf_init(&b, 0);
	blobmsg_add_string(&b, "msg",pmsg);
	blobmsg_add_u16(&b,"resCode", resCode);

	req->deferred = false;
	ubus_send_reply(ctx, req, b.head);
	if(result != NULL)
		json_object_put(result);

	return UBUS_STATUS_OK;
}
Example #21
0
  printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));    

  my_object = json_object_new_object();
  json_object_object_add(my_object, "abc", json_object_new_int(12));
  json_object_object_add(my_object, "foo", json_object_new_string("bar"));
  json_object_object_add(my_object, "bool0", json_object_new_boolean(0));
  json_object_object_add(my_object, "bool1", json_object_new_boolean(1));
  json_object_object_add(my_object, "baz", json_object_new_string("bang"));
  json_object_object_add(my_object, "baz", json_object_new_string("fark"));
  json_object_object_del(my_object, "baz");
  /*json_object_object_add(my_object, "arr", my_array);*/
  printf("my_object=\n");
  json_object_object_foreach(my_object, key, val) {
    printf("\t%s: %s\n", key, json_object_to_json_string(val));
  }
  printf("my_object.to_string()=%s\n", json_object_to_json_string(my_object));

  new_obj = json_tokener_parse("\"\003\"");
  printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
  json_object_put(new_obj);

  new_obj = json_tokener_parse("/* hello */\"foo\"");
  printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
  json_object_put(new_obj);

  new_obj = json_tokener_parse("// hello\n\"foo\"");
  printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
  json_object_put(new_obj);

  new_obj = json_tokener_parse("\"\\u0041\\u0042\\u0043\"");
  printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
Example #22
0
OSStatus _LocalConfigRespondInComingMessage(int fd, HTTPHeader_t* inHeader, mico_Context_t * const inContext)
{
  OSStatus err = kUnknownErr;
  const char *  json_str;
  uint8_t *httpResponse = NULL;
  size_t httpResponseLen = 0;
  json_object* report = NULL;
  config_log_trace();

  if(HTTPHeaderMatchURL( inHeader, kCONFIGURLRead ) == kNoErr){    
    report = ConfigCreateReportJsonMessage( inContext );
    require( report, exit );
    json_str = json_object_to_json_string(report);
    require_action( json_str, exit, err = kNoMemoryErr );
    config_log("Send config object=%s", json_str);
    err =  CreateSimpleHTTPMessageNoCopy( kMIMEType_JSON, strlen(json_str), &httpResponse, &httpResponseLen );
    require_noerr( err, exit );
    require( httpResponse, exit );
    err = SocketSend( fd, httpResponse, httpResponseLen );
    require_noerr( err, exit );
    err = SocketSend( fd, (uint8_t *)json_str, strlen(json_str) );
    require_noerr( err, exit );
    config_log("Current configuration sent");
    goto exit;
  }
  else if(HTTPHeaderMatchURL( inHeader, kCONFIGURLWrite ) == kNoErr){
    if(inHeader->contentLength > 0){
      config_log("Recv new configuration, apply and reset");
      err = ConfigIncommingJsonMessage( inHeader->extraDataPtr, inContext);
      require_noerr( err, exit );
      inContext->flashContentInRam.micoSystemConfig.configured = allConfigured;
      MICOUpdateConfiguration(inContext);

      err =  CreateSimpleHTTPOKMessage( &httpResponse, &httpResponseLen );
      require_noerr( err, exit );
      require( httpResponse, exit );
      err = SocketSend( fd, httpResponse, httpResponseLen );
      SocketClose(&fd);
      inContext->micoStatus.sys_state = eState_Software_Reset;
      if(inContext->micoStatus.sys_state_change_sem != NULL );
        mico_rtos_set_semaphore(&inContext->micoStatus.sys_state_change_sem);
      mico_thread_sleep(MICO_WAIT_FOREVER);
    }
    goto exit;
  }
else if(HTTPHeaderMatchURL( inHeader, kCONFIGURLWriteByUAP ) == kNoErr){
    if(inHeader->contentLength > 0){
      config_log("Recv new configuration from uAP, apply and connect to AP");
      err = ConfigIncommingJsonMessageUAP( inHeader->extraDataPtr, inContext);
      require_noerr( err, exit );
      MICOUpdateConfiguration(inContext);

      err =  CreateSimpleHTTPOKMessage( &httpResponse, &httpResponseLen );
      require_noerr( err, exit );
      require( httpResponse, exit );

      err = SocketSend( fd, httpResponse, httpResponseLen );
      require_noerr( err, exit );
      sleep(1);

      micoWlanSuspendSoftAP();
      _easylinkConnectWiFi( inContext );

      err = kConnectionErr; //Return an err to close socket and exit the current thread
    }
    goto exit;
  }
#ifdef MICO_FLASH_FOR_UPDATE
  else if(HTTPHeaderMatchURL( inHeader, kCONFIGURLOTA ) == kNoErr){
    if(inHeader->contentLength > 0){
      config_log("Receive OTA data!");
      memset(&inContext->flashContentInRam.bootTable, 0, sizeof(boot_table_t));
      inContext->flashContentInRam.bootTable.length = inHeader->contentLength;
      inContext->flashContentInRam.bootTable.start_address = UPDATE_START_ADDRESS;
      inContext->flashContentInRam.bootTable.type = 'A';
      inContext->flashContentInRam.bootTable.upgrade_type = 'U';
      if(inContext->flashContentInRam.micoSystemConfig.configured != allConfigured)
        inContext->flashContentInRam.micoSystemConfig.easyLinkByPass = EASYLINK_SOFT_AP_BYPASS;
      MICOUpdateConfiguration(inContext);
      SocketClose(&fd);
      inContext->micoStatus.sys_state = eState_Software_Reset;
      if(inContext->micoStatus.sys_state_change_sem != NULL );
        mico_rtos_set_semaphore(&inContext->micoStatus.sys_state_change_sem);
      mico_thread_sleep(MICO_WAIT_FOREVER);
    }
    goto exit;
  }
#endif
  else{
    return kNotFoundErr;
  };

 exit:
  if(inHeader->persistent == false)  //Return an err to close socket and exit the current thread
    err = kConnectionErr;
  if(httpResponse)  free(httpResponse);
  if(report)        json_object_put(report);

  return err;

}
Example #23
0
/*	prepare piano request (initializes request type, urlpath and postData)
 *	@param piano handle
 *	@param request structure
 *	@param request type
 */
PianoReturn_t PianoRequest (PianoHandle_t *ph, PianoRequest_t *req,
		PianoRequestType_t type) {
	PianoReturn_t ret = PIANO_RET_OK;
	const char *jsonSendBuf;
	const char *method = NULL;
	json_object *j = json_object_new_object ();
	/* corrected timestamp */
	time_t timestamp = time (NULL) - ph->timeOffset;
	bool encrypted = true;

	assert (ph != NULL);
	assert (req != NULL);

	req->type = type;
	/* no tls by default */
	req->secure = false;

	switch (req->type) {
		case PIANO_REQUEST_LOGIN: {
			/* authenticate user */
			PianoRequestDataLogin_t *logindata = req->data;

			assert (logindata != NULL);

			switch (logindata->step) {
				case 0:
					encrypted = false;
					req->secure = true;

					json_object_object_add (j, "username",
							json_object_new_string (ph->partner.user));
					json_object_object_add (j, "password",
							json_object_new_string (ph->partner.password));
					json_object_object_add (j, "deviceModel",
							json_object_new_string (ph->partner.device));
					json_object_object_add (j, "version",
							json_object_new_string ("5"));
					json_object_object_add (j, "includeUrls",
							json_object_new_boolean (true));
					snprintf (req->urlPath, sizeof (req->urlPath),
							PIANO_RPC_PATH "method=auth.partnerLogin");
					break;

				case 1: {
					char *urlencAuthToken;

					req->secure = true;

					json_object_object_add (j, "loginType",
							json_object_new_string ("user"));
					json_object_object_add (j, "username",
							json_object_new_string (logindata->user));
					json_object_object_add (j, "password",
							json_object_new_string (logindata->password));
					json_object_object_add (j, "partnerAuthToken",
							json_object_new_string (ph->partner.authToken));
					json_object_object_add (j, "syncTime",
							json_object_new_int (timestamp));

					urlencAuthToken = WaitressUrlEncode (ph->partner.authToken);
					assert (urlencAuthToken != NULL);
					snprintf (req->urlPath, sizeof (req->urlPath),
							PIANO_RPC_PATH "method=auth.userLogin&"
							"auth_token=%s&partner_id=%i", urlencAuthToken,
							ph->partner.id);
					free (urlencAuthToken);

					break;
				}
			}
			break;
		}

		case PIANO_REQUEST_GET_STATIONS: {
			/* get stations, user must be authenticated */
			assert (ph->user.listenerId != NULL);
			method = "user.getStationList";
			break;
		}

		case PIANO_REQUEST_GET_PLAYLIST: {
			/* get playlist for specified station */
			PianoRequestDataGetPlaylist_t *reqData = req->data;

			assert (reqData != NULL);
			assert (reqData->station != NULL);
			assert (reqData->station->id != NULL);

			req->secure = true;

			json_object_object_add (j, "stationToken",
					json_object_new_string (reqData->station->id));
			json_object_object_add (j, "includeTrackLength",
					json_object_new_boolean (true));

			method = "station.getPlaylist";
			break;
		}

		case PIANO_REQUEST_ADD_FEEDBACK: {
			/* low-level, don't use directly (see _RATE_SONG and _MOVE_SONG) */
			PianoRequestDataAddFeedback_t *reqData = req->data;
			
			assert (reqData != NULL);
			assert (reqData->trackToken != NULL);
			assert (reqData->stationId != NULL);
			assert (reqData->rating != PIANO_RATE_NONE);

			json_object_object_add (j, "stationToken",
					json_object_new_string (reqData->stationId));
			json_object_object_add (j, "trackToken",
					json_object_new_string (reqData->trackToken));
			json_object_object_add (j, "isPositive",
					json_object_new_boolean (reqData->rating == PIANO_RATE_LOVE));

			method = "station.addFeedback";
			break;
		}

		case PIANO_REQUEST_RENAME_STATION: {
			PianoRequestDataRenameStation_t *reqData = req->data;

			assert (reqData != NULL);
			assert (reqData->station != NULL);
			assert (reqData->newName != NULL);

			json_object_object_add (j, "stationToken",
					json_object_new_string (reqData->station->id));
			json_object_object_add (j, "stationName",
					json_object_new_string (reqData->newName));

			method = "station.renameStation";
			break;
		}

		case PIANO_REQUEST_DELETE_STATION: {
			/* delete station */
			PianoStation_t *station = req->data;

			assert (station != NULL);
			assert (station->id != NULL);

			json_object_object_add (j, "stationToken",
					json_object_new_string (station->id));

			method = "station.deleteStation";
			break;
		}

		case PIANO_REQUEST_SEARCH: {
			/* search for artist/song title */
			PianoRequestDataSearch_t *reqData = req->data;

			assert (reqData != NULL);
			assert (reqData->searchStr != NULL);

			json_object_object_add (j, "searchText",
					json_object_new_string (reqData->searchStr));

			method = "music.search";
			break;
		}

		case PIANO_REQUEST_CREATE_STATION: {
			/* create new station from specified musicToken or station number */
			PianoRequestDataCreateStation_t *reqData = req->data;

			assert (reqData != NULL);
			assert (reqData->token != NULL);

			if (reqData->type == PIANO_MUSICTYPE_INVALID) {
				json_object_object_add (j, "musicToken",
						json_object_new_string (reqData->token));
			} else {
				json_object_object_add (j, "trackToken",
						json_object_new_string (reqData->token));
				switch (reqData->type) {
					case PIANO_MUSICTYPE_SONG:
						json_object_object_add (j, "musicType",
								json_object_new_string ("song"));
						break;

					case PIANO_MUSICTYPE_ARTIST:
						json_object_object_add (j, "musicType",
								json_object_new_string ("artist"));
						break;

					default:
						assert (0);
						break;
				}
			}

			method = "station.createStation";
			break;
		}

		case PIANO_REQUEST_ADD_SEED: {
			/* add another seed to specified station */
			PianoRequestDataAddSeed_t *reqData = req->data;

			assert (reqData != NULL);
			assert (reqData->station != NULL);
			assert (reqData->musicId != NULL);

			json_object_object_add (j, "musicToken",
					json_object_new_string (reqData->musicId));
			json_object_object_add (j, "stationToken",
					json_object_new_string (reqData->station->id));

			method = "station.addMusic";
			break;
		}

		case PIANO_REQUEST_ADD_TIRED_SONG: {
			/* ban song for a month from all stations */
			PianoSong_t *song = req->data;

			assert (song != NULL);

			json_object_object_add (j, "trackToken",
					json_object_new_string (song->trackToken));

			method = "user.sleepSong";
			break;
		}

		case PIANO_REQUEST_SET_QUICKMIX: {
			/* select stations included in quickmix (see useQuickMix flag of
			 * PianoStation_t) */
			PianoStation_t *curStation = ph->stations;
			json_object *a = json_object_new_array ();

			PianoListForeachP (curStation) {
				/* quick mix can't contain itself */
				if (curStation->useQuickMix && !curStation->isQuickMix) {
					json_object_array_add (a,
							json_object_new_string (curStation->id));
				}
			}

			json_object_object_add (j, "quickMixStationIds", a);

			method = "user.setQuickMix";
			break;
		}

		case PIANO_REQUEST_GET_GENRE_STATIONS: {
			/* receive list of pandora's genre stations */
			method = "station.getGenreStations";
			break;
		}

		case PIANO_REQUEST_TRANSFORM_STATION: {
			/* transform shared station into private */
			PianoStation_t *station = req->data;

			assert (station != NULL);

			json_object_object_add (j, "stationToken",
					json_object_new_string (station->id));

			method = "station.transformSharedStation";
			break;
		}

		case PIANO_REQUEST_EXPLAIN: {
			/* explain why particular song was played */
			PianoRequestDataExplain_t *reqData = req->data;

			assert (reqData != NULL);
			assert (reqData->song != NULL);

			json_object_object_add (j, "trackToken",
					json_object_new_string (reqData->song->trackToken));

			method = "track.explainTrack";
			break;
		}

		case PIANO_REQUEST_BOOKMARK_SONG: {
			/* bookmark song */
			PianoSong_t *song = req->data;

			assert (song != NULL);

			json_object_object_add (j, "trackToken",
					json_object_new_string (song->trackToken));

			method = "bookmark.addSongBookmark";
			break;
		}

		case PIANO_REQUEST_BOOKMARK_ARTIST: {
			/* bookmark artist */
			PianoSong_t *song = req->data;

			assert (song != NULL);

			json_object_object_add (j, "trackToken",
					json_object_new_string (song->trackToken));

			method = "bookmark.addArtistBookmark";
			break;
		}

		case PIANO_REQUEST_GET_STATION_INFO: {
			/* get station information (seeds and feedback) */
			PianoRequestDataGetStationInfo_t *reqData = req->data;

			assert (reqData != NULL);
			assert (reqData->station != NULL);

			json_object_object_add (j, "stationToken",
					json_object_new_string (reqData->station->id));
			json_object_object_add (j, "includeExtendedAttributes",
					json_object_new_boolean (true));

			method = "station.getStation";
			break;
		}

		case PIANO_REQUEST_DELETE_FEEDBACK: {
			PianoSong_t *song = req->data;

			assert (song != NULL);

			json_object_object_add (j, "feedbackId",
					json_object_new_string (song->feedbackId));

			method = "station.deleteFeedback";
			break;
		}

		case PIANO_REQUEST_DELETE_SEED: {
			PianoRequestDataDeleteSeed_t *reqData = req->data;
			char *seedId = NULL;

			assert (reqData != NULL);
			assert (reqData->song != NULL || reqData->artist != NULL ||
					reqData->station != NULL);

			if (reqData->song != NULL) {
				seedId = reqData->song->seedId;
			} else if (reqData->artist != NULL) {
				seedId = reqData->artist->seedId;
			} else if (reqData->station != NULL) {
				seedId = reqData->station->seedId;
			}

			assert (seedId != NULL);

			json_object_object_add (j, "seedId",
					json_object_new_string (seedId));

			method = "station.deleteMusic";
			break;
		}

		/* "high-level" wrapper */
		case PIANO_REQUEST_RATE_SONG: {
			/* love/ban song */
			PianoRequestDataRateSong_t *reqData = req->data;

			assert (reqData != NULL);
			assert (reqData->song != NULL);
			assert (reqData->rating != PIANO_RATE_NONE);

			PianoRequestDataAddFeedback_t transformedReqData;
			transformedReqData.stationId = reqData->song->stationId;
			transformedReqData.trackToken = reqData->song->trackToken;
			transformedReqData.rating = reqData->rating;
			req->data = &transformedReqData;

			/* create request data (url, post data) */
			ret = PianoRequest (ph, req, PIANO_REQUEST_ADD_FEEDBACK);
			/* and reset request type/data */
			req->type = PIANO_REQUEST_RATE_SONG;
			req->data = reqData;

			goto cleanup;
			break;
		}
	}

	/* standard parameter */
	if (method != NULL) {
		char *urlencAuthToken;

		assert (ph->user.authToken != NULL);

		urlencAuthToken = WaitressUrlEncode (ph->user.authToken);
		assert (urlencAuthToken != NULL);

		snprintf (req->urlPath, sizeof (req->urlPath), PIANO_RPC_PATH
				"method=%s&auth_token=%s&partner_id=%i&user_id=%s", method,
				urlencAuthToken, ph->partner.id, ph->user.listenerId);

		free (urlencAuthToken);

		json_object_object_add (j, "userAuthToken",
				json_object_new_string (ph->user.authToken));
		json_object_object_add (j, "syncTime",
				json_object_new_int (timestamp));
	}

	/* json to string */
	jsonSendBuf = json_object_to_json_string (j);
	if (encrypted) {
		if ((req->postData = PianoEncryptString (ph->partner.out,
				jsonSendBuf)) == NULL) {
			ret = PIANO_RET_OUT_OF_MEMORY;
		}
	} else {
		req->postData = strdup (jsonSendBuf);
	}

cleanup:
	json_object_put (j);

	return ret;
}
Example #24
0
/** Build value pairs from the passed JSON object and add to the request
 *
 * Parse the passed JSON object and create value pairs that will be injected into
 * the given request for authorization.
 *
 * Example JSON document structure:
 * @code{.json}
 * {
 *   "docType": "raduser",
 *   "userName": "******",
 *   "config": {
 *     "SHA-Password": {
 *       "value": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3",
 *       "op": ":="
 *     }
 *   },
 *   "reply": {
 *     "Reply-Message": {
 *       "value": "Hidey Ho!",
 *       "op": "="
 *     }
 *   }
 * }
 * @endcode
 *
 * @param  json    The JSON object representation of the user documnent.
 * @param  section The pair section ("config" or "reply").
 * @param  request The request to which the generated pairs should be added.
 */
void *mod_json_object_to_value_pairs(json_object *json, const char *section, REQUEST *request)
{
	json_object *jobj, *jval, *jop;     /* json object pointers */
	TALLOC_CTX *ctx;                    /* talloc context for pairmake */
	VALUE_PAIR *vp, **ptr;              /* value pair and value pair pointer for pairmake */

	/* assign ctx and vps for pairmake based on section */
	if (strcmp(section, "config") == 0) {
		ctx = request;
		ptr = &(request->config_items);
	} else if (strcmp(section, "reply") == 0) {
		ctx = request->reply;
		ptr = &(request->reply->vps);
	} else {
		/* log error - this shouldn't happen */
		RERROR("invalid section passed for pairmake");
		/* return */
		return NULL;
	}

	/* get config payload */
	if (json_object_object_get_ex(json, section, &jobj)) {
		/* make sure we have the correct type */
		if (!json_object_is_type(jobj, json_type_object)) {
			/* log error */
			RERROR("invalid json type for '%s' section - sections must be json objects", section);
			/* reuturn */
			return NULL;
		}
		/* loop through object */
		json_object_object_foreach(jobj, attribute, json_vp) {
			/* check for appropriate type in value and op */
			if (!json_object_is_type(json_vp, json_type_object)) {
				/* log error */
				RERROR("invalid json type for '%s' attribute - attributes must be json objects", attribute);
				/* return */
				return NULL;
			}
			/* debugging */
			RDEBUG("parsing '%s' attribute: %s => %s", section, attribute, json_object_to_json_string(json_vp));
			/* create pair from json object */
			if (json_object_object_get_ex(json_vp, "value", &jval) &&
				json_object_object_get_ex(json_vp, "op", &jop)) {
				/* make correct pairs based on json object type */
				switch (json_object_get_type(jval)) {
				case json_type_double:
				case json_type_int:
				case json_type_string:
					/* debugging */
					RDEBUG("adding '%s' attribute to '%s' section", attribute, section);
					/* add pair */
					vp = pairmake(ctx, ptr, attribute, json_object_get_string(jval),
						fr_str2int(fr_tokens, json_object_get_string(jop), 0));
					/* check pair */
					if (!vp) {
						RERROR("could not build value pair for '%s' attribute (%s)", attribute, fr_strerror());
						/* return */
						return NULL;
					}
					break;

				case json_type_object:
				case json_type_array:
					/* log error - we want to handle these eventually */
					RERROR("skipping unhandled nested json object or array value pair object");
					break;

				default:
					/* log error - this shouldn't ever happen */
					RERROR("skipping unhandled json type in value pair object");
					break;
				}
			} else {
				/* log error */
				RERROR("failed to get 'value' or 'op' element for '%s' attribute", attribute);
			}
		}
		/* return NULL */
		return NULL;
	}

	/* debugging */
	RDEBUG("couldn't find '%s' section in json object - not adding value pairs for this section", section);

	/* return NULL */
	return NULL;
}
Example #25
0
/**
 * Parses a comment returning an intermediate array representation
 */
int xx_parse_program(char *program, unsigned int program_length, char *file_path) {

	char *error;
	xx_scanner_state *state;
	xx_scanner_token token;
	int scanner_status, status = SUCCESS, start_lines;
	xx_parser_status *parser_status = NULL;
	void* xx_parser;

	/**
	 * Check if the program has any length
	 */
	if (!program_length) {
		return FAILURE;
	}

	if (program_length < 2) {
		return SUCCESS;
	}

	/**
	 * Start the reentrant parser
	 */
	xx_parser = xx_Alloc(xx_wrapper_alloc);

	parser_status = malloc(sizeof(xx_parser_status));
	state = malloc(sizeof(xx_scanner_state));

	parser_status->status = XX_PARSING_OK;
	parser_status->scanner_state = state;
	parser_status->ret = NULL;
	parser_status->token = &token;
	parser_status->syntax_error = NULL;
	parser_status->number_brackets = 0;

	/**
	 * Initialize the scanner state
	 */
	state->active_token = 0;
	state->start = program;
	state->start_length = 0;
	state->active_file = file_path;
	state->active_line = 1;
	state->active_char = 1;

	state->end = state->start;

	while (0 <= (scanner_status = xx_get_token(state, &token))) {

		state->active_token = token.opcode;

		state->start_length = (program + program_length - state->start);

		switch (token.opcode) {

			case XX_T_IGNORE:
				break;

			case XX_T_NAMESPACE:
				xx_(xx_parser, XX_NAMESPACE, NULL, parser_status);
				break;
			case XX_T_ABSTRACT:
				xx_(xx_parser, XX_ABSTRACT, NULL, parser_status);
				break;
			case XX_T_CLASS:
				xx_(xx_parser, XX_CLASS, NULL, parser_status);
				break;
			case XX_T_INTERFACE:
				xx_(xx_parser, XX_INTERFACE, NULL, parser_status);
				break;
			case XX_T_EXTENDS:
				xx_(xx_parser, XX_EXTENDS, NULL, parser_status);
				break;
			case XX_T_IMPLEMENTS:
				xx_(xx_parser, XX_IMPLEMENTS, NULL, parser_status);
				break;
			case XX_T_PUBLIC:
				xx_(xx_parser, XX_PUBLIC, NULL, parser_status);
				break;
			case XX_T_PROTECTED:
				xx_(xx_parser, XX_PROTECTED, NULL, parser_status);
				break;
			case XX_T_PRIVATE:
				xx_(xx_parser, XX_PRIVATE, NULL, parser_status);
				break;
			case XX_T_STATIC:
				xx_(xx_parser, XX_STATIC, NULL, parser_status);
				break;
			case XX_T_INLINE:
				xx_(xx_parser, XX_INLINE, NULL, parser_status);
				break;
			case XX_T_FINAL:
				xx_(xx_parser, XX_FINAL, NULL, parser_status);
				break;
			case XX_T_FUNCTION:
				xx_(xx_parser, XX_FUNCTION, NULL, parser_status);
				break;
			case XX_T_LET:
				xx_(xx_parser, XX_LET, NULL, parser_status);
				break;
			case XX_T_ECHO:
				xx_(xx_parser, XX_ECHO, NULL, parser_status);
				break;
			case XX_T_RETURN:
				xx_(xx_parser, XX_RETURN, NULL, parser_status);
				break;
			case XX_T_REQUIRE:
				xx_(xx_parser, XX_REQUIRE, NULL, parser_status);
				break;
			case XX_T_CLONE:
				xx_(xx_parser, XX_CLONE, NULL, parser_status);
				break;
			case XX_T_EMPTY:
				xx_(xx_parser, XX_EMPTY, NULL, parser_status);
				break;
			case XX_T_IF:
				xx_(xx_parser, XX_IF, NULL, parser_status);
				break;
			case XX_T_ELSE:
				xx_(xx_parser, XX_ELSE, NULL, parser_status);
				break;
			case XX_T_LOOP:
				xx_(xx_parser, XX_LOOP, NULL, parser_status);
				break;
			case XX_T_CONTINUE:
				xx_(xx_parser, XX_CONTINUE, NULL, parser_status);
				break;
			case XX_T_BREAK:
				xx_(xx_parser, XX_BREAK, NULL, parser_status);
				break;
			case XX_T_WHILE:
				xx_(xx_parser, XX_WHILE, NULL, parser_status);
				break;
			case XX_T_DO:
				xx_(xx_parser, XX_DO, NULL, parser_status);
				break;
			case XX_T_NEW:
				xx_(xx_parser, XX_NEW, NULL, parser_status);
				break;
			case XX_T_CONST:
				xx_(xx_parser, XX_CONST, NULL, parser_status);
				break;
			case XX_T_TYPEOF:
				xx_(xx_parser, XX_TYPEOF, NULL, parser_status);
				break;
			case XX_T_INSTANCEOF:
				xx_(xx_parser, XX_INSTANCEOF, NULL, parser_status);
				break;
			case XX_T_ISSET:
				xx_(xx_parser, XX_ISSET, NULL, parser_status);
				break;
			case XX_T_UNSET:
				xx_(xx_parser, XX_UNSET, NULL, parser_status);
				break;
			case XX_T_THROW:
				xx_(xx_parser, XX_THROW, NULL, parser_status);
				break;
			case XX_T_FOR:
				xx_(xx_parser, XX_FOR, NULL, parser_status);
				break;
			case XX_T_IN:
				xx_(xx_parser, XX_IN, NULL, parser_status);
				break;
			case XX_T_REVERSE:
				xx_(xx_parser, XX_REVERSE, NULL, parser_status);
				break;

			case XX_T_DOTCOMMA:
				xx_(xx_parser, XX_DOTCOMMA, NULL, parser_status);
				break;
			case XX_T_COMMA:
				xx_(xx_parser, XX_COMMA, NULL, parser_status);
				break;
			case XX_T_ASSIGN:
				xx_(xx_parser, XX_ASSIGN, NULL, parser_status);
				break;
			case XX_T_ADDASSIGN:
				xx_(xx_parser, XX_ADDASSIGN, NULL, parser_status);
				break;
			case XX_T_SUBASSIGN:
				xx_(xx_parser, XX_SUBASSIGN, NULL, parser_status);
				break;
			case XX_T_MULASSIGN:
				xx_(xx_parser, XX_MULASSIGN, NULL, parser_status);
				break;
			case XX_T_CONCATASSIGN:
				xx_(xx_parser, XX_CONCATASSIGN, NULL, parser_status);
				break;
			case XX_T_EQUALS:
				xx_(xx_parser, XX_EQUALS, NULL, parser_status);
				break;
			case XX_T_NOTEQUALS:
				xx_(xx_parser, XX_NOTEQUALS, NULL, parser_status);
				break;
			case XX_T_IDENTICAL:
				xx_(xx_parser, XX_IDENTICAL, NULL, parser_status);
				break;
			case XX_T_NOTIDENTICAL:
				xx_(xx_parser, XX_NOTIDENTICAL, NULL, parser_status);
				break;
			case XX_T_LESS:
				xx_(xx_parser, XX_LESS, NULL, parser_status);
				break;
			case XX_T_GREATER:
				xx_(xx_parser, XX_GREATER, NULL, parser_status);
				break;
			case XX_T_LESSEQUAL:
				xx_(xx_parser, XX_LESSEQUAL, NULL, parser_status);
				break;
			case XX_T_GREATEREQUAL:
				xx_(xx_parser, XX_GREATEREQUAL, NULL, parser_status);
				break;
			case XX_T_COLON:
				xx_(xx_parser, XX_COLON, NULL, parser_status);
				break;
			case XX_T_ARROW:
				xx_(xx_parser, XX_ARROW, NULL, parser_status);
				break;
			case XX_T_DOUBLECOLON:
				xx_(xx_parser, XX_DOUBLECOLON, NULL, parser_status);
				break;
			case XX_T_NOT:
				xx_(xx_parser, XX_NOT, NULL, parser_status);
				break;
			case XX_T_FETCH:
				xx_(xx_parser, XX_FETCH, NULL, parser_status);
				break;
			case XX_T_SWITCH:
				xx_(xx_parser, XX_SWITCH, NULL, parser_status);
				break;
			case XX_T_CASE:
				xx_(xx_parser, XX_CASE, NULL, parser_status);
				break;
			case XX_T_DEFAULT:
				xx_(xx_parser, XX_DEFAULT, NULL, parser_status);
				break;

			case XX_T_PARENTHESES_OPEN:
				xx_(xx_parser, XX_PARENTHESES_OPEN, NULL, parser_status);
				break;
			case XX_T_PARENTHESES_CLOSE:
				xx_(xx_parser, XX_PARENTHESES_CLOSE, NULL, parser_status);
				break;

			case XX_T_BRACKET_OPEN:
				parser_status->number_brackets++;
				xx_(xx_parser, XX_BRACKET_OPEN, NULL, parser_status);
				break;
			case XX_T_BRACKET_CLOSE:
				parser_status->number_brackets--;
				xx_(xx_parser, XX_BRACKET_CLOSE, NULL, parser_status);
				break;

			case XX_T_SBRACKET_OPEN:
				xx_(xx_parser, XX_SBRACKET_OPEN, NULL, parser_status);
				break;
			case XX_T_SBRACKET_CLOSE:
				xx_(xx_parser, XX_SBRACKET_CLOSE, NULL, parser_status);
				break;

			case XX_T_NULL:
				xx_(xx_parser, XX_NULL, NULL, parser_status);
				break;
			case XX_T_TRUE:
				xx_(xx_parser, XX_TRUE, NULL, parser_status);
				break;
			case XX_T_FALSE:
				xx_(xx_parser, XX_FALSE, NULL, parser_status);
				break;
			case XX_T_COMMENT:
				if (parser_status->number_brackets <= 1) {
					xx_parse_with_token(xx_parser, XX_T_COMMENT, XX_COMMENT, &token, parser_status);
				}
				break;

			case XX_T_TYPE_INTEGER:
				xx_(xx_parser, XX_TYPE_INTEGER, NULL, parser_status);
				break;
			case XX_T_TYPE_UINTEGER:
				xx_(xx_parser, XX_TYPE_UINTEGER, NULL, parser_status);
				break;
			case XX_T_TYPE_CHAR:
				xx_(xx_parser, XX_TYPE_CHAR, NULL, parser_status);
				break;
			case XX_T_TYPE_UCHAR:
				xx_(xx_parser, XX_TYPE_UCHAR, NULL, parser_status);
				break;
			case XX_T_TYPE_LONG:
				xx_(xx_parser, XX_TYPE_LONG, NULL, parser_status);
				break;
			case XX_T_TYPE_ULONG:
				xx_(xx_parser, XX_TYPE_ULONG, NULL, parser_status);
				break;
			case XX_T_TYPE_DOUBLE:
				xx_(xx_parser, XX_TYPE_DOUBLE, NULL, parser_status);
				break;
			case XX_T_TYPE_STRING:
				xx_(xx_parser, XX_TYPE_STRING, NULL, parser_status);
				break;
			case XX_T_TYPE_BOOL:
				xx_(xx_parser, XX_TYPE_BOOL, NULL, parser_status);
				break;
			case XX_T_TYPE_VAR:
				xx_(xx_parser, XX_TYPE_VAR, NULL, parser_status);
				break;

			case XX_T_ADD:
				xx_(xx_parser, XX_ADD, NULL, parser_status);
				break;
			case XX_T_SUB:
				xx_(xx_parser, XX_SUB, NULL, parser_status);
				break;
			case XX_T_MUL:
				xx_(xx_parser, XX_MUL, NULL, parser_status);
				break;
			case XX_T_DIV:
				xx_(xx_parser, XX_DIV, NULL, parser_status);
				break;
			case XX_T_MOD:
				xx_(xx_parser, XX_MOD, NULL, parser_status);
				break;
			case XX_T_DOT:
				xx_(xx_parser, XX_CONCAT, NULL, parser_status);
				break;
			case XX_T_INCR:
				xx_(xx_parser, XX_INCR, NULL, parser_status);
				break;
			case XX_T_DECR:
				xx_(xx_parser, XX_DECR, NULL, parser_status);
				break;
			case XX_T_AND:
				xx_(xx_parser, XX_AND, NULL, parser_status);
				break;
			case XX_T_OR:
				xx_(xx_parser, XX_OR, NULL, parser_status);
				break;
			case XX_T_BITWISE_AND:
				xx_(xx_parser, XX_BITWISE_AND, NULL, parser_status);
				break;
			case XX_T_BITWISE_OR:
				xx_(xx_parser, XX_BITWISE_OR, NULL, parser_status);
				break;

			case XX_T_INTEGER:
				xx_parse_with_token(xx_parser, XX_T_INTEGER, XX_INTEGER, &token, parser_status);
				break;
			case XX_T_DOUBLE:
				xx_parse_with_token(xx_parser, XX_T_DOUBLE, XX_DOUBLE, &token, parser_status);
				break;
			case XX_T_STRING:
				xx_parse_with_token(xx_parser, XX_T_STRING, XX_STRING, &token, parser_status);
				break;
			case XX_T_CHAR:
				xx_parse_with_token(xx_parser, XX_T_CHAR, XX_CHAR, &token, parser_status);
				break;
			case XX_T_IDENTIFIER:
				xx_parse_with_token(xx_parser, XX_T_IDENTIFIER, XX_IDENTIFIER, &token, parser_status);
				break;
			case XX_T_CONSTANT:
				xx_parse_with_token(xx_parser, XX_T_CONSTANT, XX_CONSTANT, &token, parser_status);
				break;

			case XX_T_VOID:
				xx_(xx_parser, XX_VOID, NULL, parser_status);
				break;
			case XX_T_LIKELY:
				xx_(xx_parser, XX_LIKELY, NULL, parser_status);
				break;
			case XX_T_UNLIKELY:
				xx_(xx_parser, XX_UNLIKELY, NULL, parser_status);
				break;

			default:
				parser_status->status = XX_PARSING_FAILED;
				fprintf(stderr, "Scanner: unknown opcode %d\n", token.opcode);
				/*if (!*error_msg) {
					error = emalloc(sizeof(char) * (48 + Z_STRLEN_P(state->active_file)));
					sprintf(error, "Scanner: unknown opcode %d on in %s line %d", token.opcode, Z_STRVAL_P(state->active_file), state->active_line);
					//PHALCON_INIT_VAR(*error_msg);
					ALLOC_INIT_ZVAL(*error_msg);
					ZVAL_STRING(*error_msg, error, 1);
					efree(error);
				}*/
				break;
		}

		if (parser_status->status != XX_PARSING_OK) {
			status = FAILURE;
			break;
		}

		state->end = state->start;
	}

	if (status != FAILURE) {
		switch (scanner_status) {
			case XX_SCANNER_RETCODE_ERR:
			case XX_SCANNER_RETCODE_IMPOSSIBLE:
				{
					char *x = malloc(sizeof(char) * 10000);
					if (state->start) {
						sprintf(x, "Scanner error: %d %s", scanner_status, state->start);
					} else {
						sprintf(x, "Scanner error: %d", scanner_status);
					}
					json_object *syntax_error = json_object_new_object();
					json_object_object_add(syntax_error, "type", json_object_new_string("error"));
					json_object_object_add(syntax_error, "message", json_object_new_string(x));
					//free(x);
					parser_status->ret = syntax_error;
					status = FAILURE;
				}
				break;
			default:
				xx_(xx_parser, 0, NULL, parser_status);
		}
	}

	state->active_token = 0;
	state->start = NULL;

	if (parser_status->status != XX_PARSING_OK) {
		status = FAILURE;
		/*if (parser_status->syntax_error) {
			if (!*error_msg) {
				//PHALCON_INIT_VAR(*error_msg);
				ALLOC_INIT_ZVAL(*error_msg);
				ZVAL_STRING(*error_msg, parser_status->syntax_error, 1);
			}
			efree(parser_status->syntax_error);
		}*/
		//fprintf(stderr, "error!\n");
	}

	xx_Free(xx_parser, xx_wrapper_free);

	if (status != FAILURE) {
		if (parser_status->status == XX_PARSING_OK) {
			//printf("%s\n", json_object_to_json_string(parser_status->ret));
			/*if (parser_status->ret) {
				ZVAL_ZVAL(*result, parser_status->ret, 0, 0);
				ZVAL_NULL(parser_status->ret);
				zval_ptr_dtor(&parser_status->ret);
			} else {
				array_init(*result);
			}*/
		}
	}

	if (parser_status->ret) {
		printf("%s\n", json_object_to_json_string(parser_status->ret));
	}

	//efree(Z_STRVAL(processed_comment));*/

	free(parser_status);
	free(state);

	return status;
}
Example #26
0
/** Load client entries from Couchbase client documents on startup
 *
 * This function executes the view defined in the module configuration and loops
 * through all returned rows.  The view is called with "stale=false" to ensure the
 * most accurate data available when the view is called.  This will force an index
 * rebuild on this design document in Couchbase.  However, since this function is only
 * run once at sever startup this should not be a concern.
 *
 * @param  inst The module instance.
 * @param  cs   The client attribute configuration section.
 * @return      Returns 0 on success, -1 on error.
 */
int mod_load_client_documents(rlm_couchbase_t *inst, CONF_SECTION *cs)
{
	void *handle = NULL;                   /* connection pool handle */
	char vpath[256], docid[MAX_KEY_SIZE];  /* view path and document id */
	char error[512];                       /* view error return */
	int idx = 0;                           /* row array index counter */
	int retval = 0;                        /* return value */
	lcb_error_t cb_error = LCB_SUCCESS;    /* couchbase error holder */
	json_object *json, *jval;              /* json object holders */
	json_object *jrows = NULL;             /* json object to hold view rows */
	CONF_SECTION *client;                  /* freeradius config section */
	RADCLIENT *c;                          /* freeradius client */

	/* get handle */
	handle = fr_connection_get(inst->pool);

	/* check handle */
	if (!handle) return -1;

	/* set handle pointer */
	rlm_couchbase_handle_t *handle_t = handle;

	/* set couchbase instance */
	lcb_t cb_inst = handle_t->handle;

	/* set cookie */
	cookie_t *cookie = handle_t->cookie;

	/* check cookie */
	if (cookie) {
		/* clear cookie */
		memset(cookie, 0, sizeof(cookie_t));
	} else {
		/* log error */
		ERROR("rlm_couchbase: cookie not usable - possibly not allocated");
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* build view path */
	snprintf(vpath, sizeof(vpath), "%s?stale=false", inst->client_view);

	/* init cookie error status */
	cookie->jerr = json_tokener_success;

	/* setup cookie tokener */
	cookie->jtok = json_tokener_new();

	/* query view for document */
	cb_error = couchbase_query_view(cb_inst, cookie, vpath, NULL);

	/* free json token */
	json_tokener_free(cookie->jtok);

	/* check error */
	if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success) {
		/* log error */
		ERROR("rlm_couchbase: failed to execute view request or parse return");
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* debugging */
	DEBUG("rlm_couchbase: cookie->jobj == %s", json_object_to_json_string(cookie->jobj));

	/* check cookie */
	if (!cookie->jobj) {
		/* log error */
		ERROR("rlm_couchbase: failed to fetch view");
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* check for error in json object */
	if (json_object_object_get_ex(cookie->jobj, "error", &json)) {
		/* build initial error buffer */
		strlcpy(error, json_object_get_string(json), sizeof(error));
		/* get error reason */
		if (json_object_object_get_ex(cookie->jobj, "reason", &json)) {
			/* append divider */
			strlcat(error, " - ", sizeof(error));
			/* append reason */
			strlcat(error, json_object_get_string(json), sizeof(error));
		}
		/* log error */
		ERROR("rlm_couchbase: view request failed with error: %s", error);
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* check for document id in return */
	if (!json_object_object_get_ex(cookie->jobj, "rows", &json)) {
		/* log error */
		ERROR("rlm_couchbase: failed to fetch rows from view payload");
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* get and hold rows */
	jrows = json_object_get(json);

	/* free cookie object */
	json_object_put(cookie->jobj);

	/* debugging */
	DEBUG("rlm_couchbase: jrows == %s", json_object_to_json_string(jrows));

	/* check for valid row value */
	if (!json_object_is_type(jrows, json_type_array) && json_object_array_length(jrows) < 1) {
		/* log error */
		ERROR("rlm_couchbase: couldn't find valid rows in view return");
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* loop across all row elements */
	for (idx = 0; idx < json_object_array_length(jrows); idx++) {
		/* fetch current index */
		json = json_object_array_get_idx(jrows, idx);

		/* get document id */
		if (json_object_object_get_ex(json, "id", &jval)) {
			/* clear docid */
			memset(docid, 0, sizeof(docid));
			/* copy and check length */
			if (strlcpy(docid, json_object_get_string(jval), sizeof(docid)) >= sizeof(docid)) {
				ERROR("rlm_couchbase: document id from row longer than MAX_KEY_SIZE (%d)", MAX_KEY_SIZE);
				continue;
			}
		}

		/* check for valid doc id */
		if (docid[0] == 0) {
			WARN("rlm_couchbase: failed to fetch document id from row - skipping");
			continue;
		}

		/* debugging */
		DEBUG("rlm_couchbase: preparing to fetch docid '%s'", docid);

		/* reset  cookie error status */
		cookie->jerr = json_tokener_success;

		/* fetch document */
		cb_error = couchbase_get_key(cb_inst, cookie, docid);

		/* check error */
		if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success) {
			/* log error */
			ERROR("rlm_couchbase: failed to execute get request or parse return");
			/* set return */
			retval = -1;
			/* return */
			goto free_and_return;
		}

		/* debugging */
		DEBUG("rlm_couchbase: cookie->jobj == %s", json_object_to_json_string(cookie->jobj));

		/* allocate conf section */
		client = cf_section_alloc(NULL, "client", docid);

		if (_mod_client_map_section(client, cs, cookie->jobj, docid) != 0) {
			/* free config setion */
			talloc_free(client);
			/* set return */
			retval = -1;
			/* return */
			goto free_and_return;
		}

		/*
		 * @todo These should be parented from something.
		 */
		c = client_afrom_cs(NULL, client, false);
		if (!c) {
			ERROR("rlm_couchbase: failed to allocate client");
			/* free config setion */
			talloc_free(client);
			/* set return */
			retval = -1;
			/* return */
			goto free_and_return;
		}

		/*
		 * Client parents the CONF_SECTION which defined it.
		 */
		talloc_steal(c, client);

		/* attempt to add client */
		if (!client_add(NULL, c)) {
			ERROR("rlm_couchbase: failed to add client from %s, possible duplicate?", docid);
			/* free client */
			client_free(c);
			/* set return */
			retval = -1;
			/* return */
			goto free_and_return;
		}

		/* debugging */
		DEBUG("rlm_couchbase: client '%s' added", c->longname);

		/* free json object */
		json_object_put(cookie->jobj);
	}

	free_and_return:

	/* free json object */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
	}

	/* free rows */
	if (jrows) {
		json_object_put(jrows);
	}

	/* release handle */
	if (handle) {
		fr_connection_release(inst->pool, handle);
	}

	/* return */
	return retval;
}
Example #27
0
/*cli pthread:deal the client data*/
void *fun(void *arg)
{
	int cli_fd_t = cli_fd;
	char buf_fun[BUFSIZ];
	bzero(buf_fun,BUFSIZ);
	memcpy(buf_fun,(char *)arg,BUFSIZ);
	/*pose sem let main function continue*/
	sem_post(&sem);
#if DEBUG
	printf("thread original data :---------------------------------\n%s\n",buf_fun);
	printf("strlen of buf_fun :---------------------------------%d\n",strlen(buf_fun));
#endif
	//if(strncmp(buf_fun,"\n",1) == 0)
	//	pthread_exit(0);
	if(strlen(buf_fun) <= 9)
		pthread_exit(0);

	/*decording json*/
	json_object *jiebao, *jiebao_cmd, *jiebao_flag;
	jiebao= json_tokener_parse(buf_fun);

	const char *pstr;
	jiebao_cmd=json_object_array_get_idx(jiebao,0);
	jiebao_flag=json_object_object_get(jiebao_cmd,"fla");
	pstr =json_object_get_string(jiebao_flag);
	int int_pstr = atoi(pstr);
	switch(int_pstr){
#if DEBUG
		printf("pstr == %s\n",pstr);
#endif
		/*search for seat*/
	case 11:
		{
			int re;	
			char **result;
			int nrow = 0;
			int ncolumn = 0;
			char *errmsg;

			if(pthread_mutex_lock(&mutex)){
				printf("database lock failed!\n");
				pthread_exit(NULL);
			}
			//pthread_mutex_unlock(&mutex);
			/*search db*/
			re=sqlite3_get_table(db,"select * from tbmenu",&result,&nrow,&ncolumn,&errmsg);
			if(re != SQLITE_OK){
				printf("%s\n",errmsg);
				//exit(-1);
			}
			pthread_mutex_unlock(&mutex);

			int x = 0,y = 0,index = 0;
			index = ncolumn;
			/*pakage json*/
			struct json_object *my_json[nrow];

			for( x=0; x<nrow; x++){
				my_json[x]=json_object_new_object();
			}

			for( x=0; x<nrow; x++){
				for( y=0; y<ncolumn; y++){
					//printf("%s\t",result[index++]);
					json_object_object_add(my_json[x],result[y],json_object_new_string(result[index++]));
				}
			}

			sqlite3_free_table(result);

			struct json_object *json_shuzu;
			json_shuzu=json_object_new_array();
			for( x=0; x<nrow; x++){
				json_object_array_add(json_shuzu,my_json[x]);
			}

			const char * buf_cst =json_object_to_json_string(json_shuzu);
			write(cli_fd_t,buf_cst,strlen(buf_cst));
#if DEBUG
			printf("return seat json:--------------------------------\n%s\n",buf_cst);
#endif
		}break;
		/*choose one table*/
	case 12:
		{
			int json_length = json_object_array_length(jiebao);
			if(json_length != 2){
				char *buf_no= "NO";
				//write(cli_fd_t,buf_no,strlen(buf_no));
				//break;
				pthread_exit(0);
			}
			else {
				char *buf_ok="OK";
				//write(cli_fd_t,buf_ok,strlen(buf_ok));
			}
			json_object *json_seat,*json_seat_tmp;
			json_seat = json_object_array_get_idx(jiebao,1);
			int tb_id;
			char cust_name[30];
			const char *ppstr;
			json_seat_tmp = json_object_object_get(json_seat,"id1");
			ppstr =json_object_get_string(json_seat_tmp);
			tb_id = atoi(ppstr);
			sprintf(cust_name,"cli_id_%d",cli_fd_t);

			if(pthread_mutex_lock(&mutex)){
				printf("database lock failed!\n");
				pthread_exit(NULL);
			}
			cust(tb_id,cust_name);
			pthread_mutex_unlock(&mutex);
#if DEBUG
			printf("booking seat OK!--------------------------------------\n");
#endif
		}break;
		/*search for food*/
	case 21:
		{
			int re;	
			char **result;
			int nrow = 0;
			int ncolumn = 0;
			char *errmsg;

			if(pthread_mutex_lock(&mutex)){
				printf("database lock failed!\n");
				pthread_exit(NULL);
			}
			/*search db*/
			re=sqlite3_get_table(db,"select * from fdmenu",&result,&nrow,&ncolumn,&errmsg);
			if(re != SQLITE_OK){
				printf("%s\n",errmsg);
				exit(-1);
			}
			pthread_mutex_unlock(&mutex);

			int x = 0,y = 0,index = 0;
			index = ncolumn;

			/*pakage json*/
			struct json_object *my_json[nrow];

			for( x=0; x<nrow; x++){
				my_json[x]=json_object_new_object();
			}

			for( x=0; x<nrow; x++){
				for( y=0; y<ncolumn; y++){
					//printf("%s\t",result[index++]);
					json_object_object_add(my_json[x],result[y],json_object_new_string(result[index++]));
				}
			}

			sqlite3_free_table(result);

			struct json_object *json_shuzu;
			json_shuzu=json_object_new_array();
			for( x=0; x<nrow; x++){
				json_object_array_add(json_shuzu,my_json[x]);
			}

			const char * buf_cst =json_object_to_json_string(json_shuzu);


			write(cli_fd_t,buf_cst,strlen(buf_cst));
#if DEBUG
			printf("send food table to client:------------------------------------\n%s\n",buf_cst);
#endif
		}break;
		/*add food*/
	case 23:;
			/*hand up the food tab*/
	case 22:
			{
				int json_length = json_object_array_length(jiebao);

				if(json_length == 1){
					char *buf_no= "NO";
					//write(cli_fd_t,buf_no,strlen(buf_no));
					//break;
					pthread_exit(0);
				}
				else {
					char *buf_ok="OK";
					//write(cli_fd_t,buf_ok,strlen(buf_ok));
					if(int_pstr == 22)
						total_client++;
				}
				json_object *json_fd[json_length],*json_fd_tmp[3];
				int i;
				const char *ptmp[3];
				char cust_name22[30];
				sprintf(cust_name22,"cli_id_%d",cli_fd_t);
				//char tmpchar[20];
				for(i = 1; i < json_length; i++){
					json_fd[i]= json_object_array_get_idx(jiebao,i);
					json_fd_tmp[0] = json_object_object_get(json_fd[i],"id1");//fd_id
					json_fd_tmp[1] = json_object_object_get(json_fd[i],"foodname");//fd_name
					json_fd_tmp[2] = json_object_object_get(json_fd[i],"prices");//prices
					int n;
					for(n = 0; n < 3; n++){
						ptmp[n] = json_object_get_string(json_fd_tmp[n]);
					}
					//bzero(tmpchar,20);
					//strcpy(tmpchar,ptmp[1]);
					//insert_cust(cust_name22, atoi(ptmp[0]),tmpchar,atoi(ptmp[2]));
					if(pthread_mutex_lock(&mutex)){
						printf("database lock failed!\n");
						pthread_exit(NULL);
					}
					add(atoi(ptmp[0]),cust_name22);
					pthread_mutex_unlock(&mutex);
				}

				struct message msg;
				int pid;
				pid = init_msg(&msg);
				msg.msg_type = 1;
				strncpy(msg.msg_text,cust_name22,strlen(cust_name22));
				if(msgsnd(pid, &msg, strlen(msg.msg_text),0) == -1)
					handle_error("msgsnd");

#if DEBUG
				printf("got food table from client.----------------------------------\n");
				printf("it is waiting to be cook.----------------------------------\n");
#endif
			}break;

			/*ask for faster*/
	case 31:
			{
				int re;	
				char **result;
				int nrow = 0;
				int ncolumn = 0;
				char *errmsg;

				if(pthread_mutex_lock(&mutex)){
					printf("database lock failed!\n");
					pthread_exit(NULL);
				}
				/*search db*/
				re=sqlite3_get_table(db,"select condition from tbmenu where condition = 1",&result,&nrow,&ncolumn,&errmsg);
				if(re != SQLITE_OK){
					printf("%s\n",errmsg);
					exit(-1);
				}
				pthread_mutex_unlock(&mutex);
				sqlite3_free_table(result);

#if DEBUG
				printf("get asking :%d pepeo---\n",nrow);
#endif
				struct message msg;
				int pid;
				pid = init_msg(&msg);
				msg.msg_type = 2;
				bzero(msg.msg_text,BUFSIZ);
				char buf[100];
				bzero(buf,100);
				sprintf(buf,"%d",nrow);
				strncpy(msg.msg_text,buf,strlen(buf));
#if DEBUG
				printf("msgsnd contain %s\n", msg.msg_text);
#endif
				if(msgsnd(pid, &msg, strlen(msg.msg_text),0) == -1)
					handle_error("msgsnd");
#if DEBUG
				printf("msgsnd ok\n");
#endif
			}break;
			/*apply for money*/
	case 41:
			{
#if DEBUG
				printf("come into 41: \n");
#endif
				int json_length = json_object_array_length(jiebao);
				if(json_length != 2){
					char *buf_no= "NO";
					//write(cli_fd_t,buf_no,strlen(buf_no));
					break;
				}
#if DEBUG
				printf("not break here: \n");
#endif
				json_object *json_moy,*json_moy_tmp;
				json_moy_tmp = json_object_array_get_idx(jiebao,1);
				json_moy = json_object_object_get(json_moy_tmp,"prices");	
				char cust_name31[30];
				sprintf(cust_name31,"cli_id_%d",cli_fd_t);
				const char *moy_tmp = json_object_get_string(json_moy);

				if(pthread_mutex_lock(&mutex)){
					printf("database lock failed!\n");
					pthread_exit(NULL);
				}
				insert_cust(cust_name31, 0,NULL,atoi(moy_tmp));//total money
				total_money += atoi(moy_tmp);
#if DEBUG
				printf("money is :%s\n",moy_tmp);
				printf("%d\n",total_money);
#endif
				pthread_mutex_unlock(&mutex);
#if DEBUG
				printf("client apply for money.---------------------------------------\n");
#endif
			}break;

			/*client off line or have applied the money*/
	case 51:
			{
				if(pthread_mutex_lock(&mutex)){
					printf("database lock failed!\n");
					pthread_exit(NULL);
				}
				char cust_name_delete[30];
				sprintf(cust_name_delete,"cli_id_%d",cli_fd_t);//delete the table of a client
				cust_delete(cust_name_delete);
				pthread_mutex_unlock(&mutex);
			}break;
	default:break;
	}
	pthread_exit(0);
}
Example #28
0
bool
_LSPrivateDoMallocTrim(LSHandle* sh, LSMessage *message, void *ctx)
{
    LSError lserror;
    LSErrorInit(&lserror);

    struct json_object *ret_obj = NULL;
    struct json_object *true_obj = NULL;
    struct json_object *malloc_trim_obj = NULL;

    ret_obj = json_object_new_object();
    if (JSON_ERROR(ret_obj)) goto error;
       
    true_obj = json_object_new_boolean(true);
    if (JSON_ERROR(true_obj)) goto error;
 

    /* returnValue: true,
     * malloc_trim: int
     */

    typedef int (*malloc_trim_t)(size_t);
    static malloc_trim_t malloc_trim_p = NULL;

    if (malloc_trim_p == NULL) {
        malloc_trim_p = (malloc_trim_t)dlsym(RTLD_DEFAULT, "malloc_trim");
        if (malloc_trim_p == NULL)
            malloc_trim_p = (malloc_trim_t)-1;
    }
    
    int result;
    if (malloc_trim_p != (malloc_trim_t)-1) {
        result = malloc_trim_p(0);
    } else {
        result = -1;
    }

    malloc_trim_obj = json_object_new_int(result);
    if (JSON_ERROR(malloc_trim_obj)) goto error;
        
    json_object_object_add(ret_obj, "returnValue", true_obj);
    json_object_object_add(ret_obj, "malloc_trim", malloc_trim_obj);

    bool reply_ret = LSMessageReply(sh, message, json_object_to_json_string(ret_obj), &lserror);
    if (!reply_ret)
    {
        g_critical("%s: sending malloc trim result failed", __FUNCTION__);
        LSErrorPrint(&lserror, stderr);
        LSErrorFree(&lserror);
    }

    json_object_put(ret_obj);
    
    return true;

error:
    
    if (!JSON_ERROR(ret_obj)) json_object_put(ret_obj);
    if (!JSON_ERROR(true_obj)) json_object_put(true_obj);
    if (!JSON_ERROR(malloc_trim_obj)) json_object_put(malloc_trim_obj);
    
    return true;
}
Example #29
0
//! A single sensor pass. Runs each sensor and emits the result using
//! the configured emitter.
//! 
int internal_sensor_pass(int return_on_fail) {
    LOGTRACE("Executing internal sensor pass\n");
    json_object *result;
    int i = 0;
    int is_enabled = FALSE;
    int ret = EUCA_OK;
    //Get the sensor list from the config
    char **names = NULL;
    char *tmpstr = configFileValue(SENSOR_LIST_CONF_PARAM_NAME);
    if (tmpstr == NULL) {
        LOGDEBUG("%s parameter is missing from config file\n", SENSOR_LIST_CONF_PARAM_NAME);
    } else {
        names = from_var_to_char_list(tmpstr);
        EUCA_FREE(tmpstr);
    }

    char **sensors = { NULL }; // if no config value or an empty list
    if (names != NULL) {
        sensors = names;
    }

    //Enter the execution loop
    if(get_lock_fn != NULL) {
        get_lock_fn();
    } else {
        LOGERROR("Cannot run internal sensor pass because no lock provided to protect data.\n");

        //Free up the sensor listing
        if (names) {
            for (int i=0; names[i]; i++) {
                EUCA_FREE(names[i]);
            }
            EUCA_FREE(names);
        }

        return EUCA_ERROR;
    }

    LOGTRACE("Running %d sensors\n", sensor_registry.sensor_count);
    for(i = 0; i < sensor_registry.sensor_count; i++) {
        LOGTRACE("Checking sensor %s is enabled\n", sensor_registry.sensors[i]->sensor_name);
        is_enabled = get_new_config_status(sensor_registry.sensors[i]->config_name, (const char**)sensors);
        if(is_enabled && sensor_registry.sensors[i]->sensor_function != NULL) {
            result = sensor_registry.sensors[i]->sensor_function(); 
            if(result == NULL) {
                LOGERROR("Error encountered getting internal sensor output from sensor %s\n", sensor_registry.sensors[i]->sensor_name);
                ret = EUCA_ERROR;
            } else {
                LOGTRACE("Offering event for emitter: %s\n", json_object_to_json_string(result));
                if(emitter_offer_event(result) != EUCA_OK) {
                    LOGERROR("Error emitting event from internal sensor %s\n", sensor_registry.sensors[i]->sensor_name);
                    ret = EUCA_ERROR;
                } else {
                    LOGTRACE("Event offered to emitter successfully\n");
                }
            }
        } else {
            LOGTRACE("Sensor %s not enabled, skipping execution\n", sensor_registry.sensors[i]->sensor_name);
        }
        
        //Update the state of the sensor as needed.
        if(sensor_registry.sensors[i]->state_toggle_callback != NULL) {
            //Must be idempotent
            LOGTRACE("Calling toggle callback on sensor %s with enabled=%d\n", sensor_registry.sensors[i]->sensor_name, is_enabled);
            sensor_registry.sensors[i]->state_toggle_callback(is_enabled);
        }

        if(return_on_fail && ret != EUCA_OK) {
            goto cleanup;
        }
    }
    
 cleanup:
    if(release_lock_fn != NULL) {
        release_lock_fn();
        LOGTRACE("Released lock for stats during sensor pass\n");
    } else {
        LOGERROR("No lock release function found, this could result in deadlock or leaks. Continuing to exit sensor pass function\n");       
    }

    //Free up the sensor listing
    if (names) {
        for (int i=0; names[i]; i++) {
            EUCA_FREE(names[i]);
        }
        EUCA_FREE(names);
    }
    return ret;
}
Example #30
0
void PrefsDb::synchronizePlatformDefaults() {
	
	char* jsonStr = Utils::readFile(s_defaultPlatformPrefsFile);
	if (!jsonStr) {
		g_warning("PrefsDb::synchronizePlatformDefaults(): Failed to load default platform prefs file: %s", s_defaultPlatformPrefsFile);
		return;
	}

	json_object* root = 0;
	json_object* label = 0;
	std::string ccnumber;
	int ret;
	gchar* queryStr;

	root = json_tokener_parse(jsonStr);
	if (!root || is_error(root)) {
		g_warning("PrefsDb::synchronizePlatformDefaults(): Failed to parse file contents into json");
		return;
	}

	label = json_object_object_get(root, "preferences");
	if (!label || is_error(label)) {
		g_warning("PrefsDb::synchronizePlatformDefaults(): Failed to get preferences entry from file");
		json_object_put(root);
		return;
	}

	json_object_object_foreach(label, key, val) {

		if (val == NULL)
			continue;		//TODO: really should delete this key if it is in the database
		char * p_cDbv = json_object_to_json_string(val);
		if (p_cDbv == NULL)
			continue;
		//check the key to see if it exists in the db already
		
		std::string cv = getPref(key);
		std::string dbv(p_cDbv);
		
		if (cv.length() == 0) {
			queryStr = g_strdup_printf("INSERT INTO Preferences "
					"VALUES ('%s', '%s')",
					key, json_object_to_json_string(val));
			if (!queryStr) {
				g_warning("PrefsDb::synchronizePlatformDefaults(): Failed to allocate query string for key %s",key);
				continue;
			}

			ret = sqlite3_exec(m_prefsDb, queryStr, NULL, NULL, NULL);
			g_free(queryStr);

			if (ret) {
				g_warning("PrefsDb::synchronizePlatformDefaults(): Failed to execute query for key %s", key);
				continue;
			}
		}
		
	}
	
	json_object_put(root);
		
}