/* Saves the union ipt_targinfo in parsable form to stdout. */
static void
save(const struct ipt_ip *ip, const struct ipt_entry_target *target)
{
	struct ipt_porttrigger_info *info = (struct ipt_porttrigger_info *)(target)->data;

	print_mode(info->mode);
	/* 
	  Modification: for protocol type==all(any) can't work
      Modified by: ken_chiang 
      Date:2007/8/21
    */
	//if( info->trigger_proto ) {
		printf("--trigger-proto:");
		print_proto(info->trigger_proto);
	//}

	//if( info->forward_proto ) {
		printf("--forward-proto:");
		print_proto(info->forward_proto);
	//}

	if( info->trigger_ports.ports[0]) {
		printf("--trigger-ports: ");
		print_multi_ports(info->trigger_ports);
	}

	if( info->forward_ports.ports[0] ) {
		printf("  --forward-ports: ");
		print_multi_ports(info->forward_ports);
	}

	if( info->timer >0) {
		printf("  --timer: %d", info->timer);
	}
}
static void print_entry(char *prefix, const struct ipt_policy_elem *e,
                        int numeric)
{
	if (e->match.reqid) {
		PRINT_INVERT(e->invert.reqid);
		printf("%sreqid %u ", prefix, e->reqid);
	}
	if (e->match.spi) {
		PRINT_INVERT(e->invert.spi);
		printf("%sspi 0x%x ", prefix, e->spi);
	}
	if (e->match.proto) {
		PRINT_INVERT(e->invert.proto);
		print_proto(prefix, e->proto, numeric);
	}
	if (e->match.mode) {
		PRINT_INVERT(e->invert.mode);
		print_mode(prefix, e->mode, numeric);
	}
	if (e->match.daddr) {
		PRINT_INVERT(e->invert.daddr);
		printf("%stunnel-dst %s%s ", prefix,
		       addr_to_dotted((struct in_addr *)&e->daddr),
		       mask_to_dotted((struct in_addr *)&e->dmask));
	}
	if (e->match.saddr) {
		PRINT_INVERT(e->invert.saddr);
		printf("%stunnel-src %s%s ", prefix,
		       addr_to_dotted((struct in_addr *)&e->saddr),
		       mask_to_dotted((struct in_addr *)&e->smask));
	}
}
Exemple #3
0
void
print_udp(
	int fd,
	char *datagram)
{
	struct udp_header *udph;
	udph = (struct udp_header *) datagram;
	print_proto(fd,"[UDP/ source port:%hu dest port:%hu udpdatalen:%hd "
		"checksum:%#x]",ntohs(udph->sourceport),ntohs(udph->destport),
		ntohs(udph->udpdatalen),udph->udpchecksum);
}
Exemple #4
0
static void print_tuple(const struct nlattr *nest)
{
	struct nlattr *tb[CTA_TUPLE_MAX+1] = {};

	mnl_attr_parse_nested(nest, parse_tuple_cb, tb);
	if (tb[CTA_TUPLE_IP]) {
		print_ip(tb[CTA_TUPLE_IP]);
	}
	if (tb[CTA_TUPLE_PROTO]) {
		print_proto(tb[CTA_TUPLE_PROTO]);
	}
}
Exemple #5
0
/**
 * change message status from not read to have read
 *  
 * @method change_msg_status
 * @param {int} msg_id id of message
 * @return {int} change_msg_status status.
 */
int change_msg_status(int msg_id, int room_id, int recipient_id, char *buf, int &send_len) {
    string respon_data;
    Response::HTTPResponse *http_res = new Response::HTTPResponse();
    string msg;
    int result;
    int ret;

    LOG_INFO << "msg_id is " << msg_id << endl;

    do {    
        // msg_id is not be found
        if (msg_id <= 0) {
            result = PARAM_ERROR;
            _set_http_head(result, false, "msg_id error", http_res);
            break;
        }

        // change message status
        map<string, string> update_params;

        Config *c = Config::get_instance();
        map<string, string> config = c->get_config();
        eagleMysql e(config["DOMAIN"].c_str(), config["USER_NAME"].c_str(), 
            config["PASSWORD"].c_str(), config["DATABASE"].c_str(), Tool::S2I(config["PORT"], 3306));
        
        update_params["status"] = Tool::mysql_filter(MSG_HAVE_READ);

        ret = e.update("t_msg", update_params, "where id<=" + Tool::mysql_filter(msg_id) 
            + " and room_id=" + Tool::mysql_filter(room_id)
            + " and recipient_id=" + Tool::mysql_filter(recipient_id)
            + ";");
        // exception
        if (ret != DB_OK) {
            result = CHANGE_MSG_STATUS_FAIL;
            _set_http_head(result, false, "change message status fail", http_res);
            break;
        }

        result = CHANGE_MSG_STATUS_SUCCESS;
        _set_http_head(result, true, "change message status success", http_res);
    } while(0);

    print_proto(http_res);

    http_res->SerializeToString(&respon_data);
    memcpy(buf, respon_data.c_str(), respon_data.length());
    send_len = respon_data.length();
    google::protobuf::ShutdownProtobufLibrary();

    return result;
}
Exemple #6
0
void
print_ipv4_simple(
	int fd,
	char *datagram,
	__u16 sourceport,
	__u16 destport)
{	
	struct ipv4_header *iph;

	iph = (struct ipv4_header *) datagram;

	print_proto(fd,"[%s:%hu->%s:%hu] ",
		get_ipv4_name(iph->sourceaddr),sourceport,
		get_ipv4_name(iph->destaddr),destport);
}
Exemple #7
0
void
print_ipv4(
	int fd,
	char *datagram)
{
	struct ipv4_header *iph;
	iph = (struct ipv4_header *) datagram;

	print_proto(fd,"[IPv4/ version:%hhd ipheaderlen:%hhd tos:%#x totlen:%d "
		"id:%#x fragoffset:%#x ttl:%hhu proto:%hhd checksum:%#x "
		"source:%s dest:%s]",FLAG_VAL(iph->lenvers,IPV4_VERS,4),
		FLAG_VAL(iph->lenvers,IPV4_HDRLEN,0),iph->tos,
		ntohs(iph->totlen),ntohs(iph->id), ntohs(iph->fragoffset),
		iph->ttl,iph->proto,ntohs(iph->ipchecksum),
		ipv4_ntoa(ntohl(iph->sourceaddr),sourceip),
		ipv4_ntoa(ntohl(iph->destaddr), destip));
}
Exemple #8
0
/**
 * check whether the username is exist or not
 *  
 * @method username_is_exist
 * @param {string} username username which is used for checking whether the username is exist or not.
 * @param {char *} buf respone data.
 * @return {int} username_is_exist status. 
 */
int username_is_exist(string username, char *buf, int &send_len) {
    string respon_data;
    Response::HTTPResponse *http_res = new Response ::HTTPResponse();
    string msg;
    int result;
    int ret;

    do {
        Config *c = Config::get_instance();
        map<string, string> config = c->get_config();
        eagleMysql e(config["DOMAIN"].c_str(), config["USER_NAME"].c_str(), 
            config["PASSWORD"].c_str(), config["DATABASE"].c_str(), Tool::S2I(config["PORT"], 3306));

        bool exist;

        ret = e.is_exist("t_user", "where username = '******'", exist);
        // exception
        if (ret != DB_OK) {
            result = DB_ERROR;
            _set_http_head(result, false, "DB ERROR|" + Tool::toString(ret), http_res);
            break;
        }
        // username already exist
        if (exist) {
            result = USERNAME_IS_EXIST;
            _set_http_head(result, false, "username is already exist", http_res);
            break;
        }

        result = USERNAME_AVAILABLE;
        _set_http_head(result, true, "username is available", http_res);
        UserResponse::UsernameExistResponse *username_exist_response = new UserResponse::UsernameExistResponse();
        username_exist_response->set_is_exist(exist);
        http_res->set_allocated_exist_username_response(username_exist_response);
    } while(0);

    print_proto(http_res);

    http_res->SerializeToString(&respon_data);
    memcpy(buf, respon_data.c_str(), respon_data.length());
    send_len = respon_data.length();
    google::protobuf::ShutdownProtobufLibrary();

    return result;
}
Exemple #9
0
static void print_entry(const char *prefix, const struct xt_policy_elem *e,
                        bool numeric, uint8_t family)
{
	if (e->match.reqid) {
		PRINT_INVERT(e->invert.reqid);
		printf("%sreqid %u ", prefix, e->reqid);
	}
	if (e->match.spi) {
		PRINT_INVERT(e->invert.spi);
		printf("%sspi 0x%x ", prefix, e->spi);
	}
	if (e->match.proto) {
		PRINT_INVERT(e->invert.proto);
		print_proto(prefix, e->proto, numeric);
	}
	if (e->match.mode) {
		PRINT_INVERT(e->invert.mode);
		print_mode(prefix, e->mode, numeric);
	}
	if (e->match.daddr) {
		PRINT_INVERT(e->invert.daddr);
		if (family == NFPROTO_IPV6)
			printf("%stunnel-dst %s%s ", prefix,
			       xtables_ip6addr_to_numeric(&e->daddr.a6),
			       xtables_ip6mask_to_numeric(&e->dmask.a6));
		else
			printf("%stunnel-dst %s%s ", prefix,
			       xtables_ipaddr_to_numeric(&e->daddr.a4),
			       xtables_ipmask_to_numeric(&e->dmask.a4));
	}
	if (e->match.saddr) {
		PRINT_INVERT(e->invert.saddr);
		if (family == NFPROTO_IPV6)
			printf("%stunnel-src %s%s ", prefix,
			       xtables_ip6addr_to_numeric(&e->saddr.a6),
			       xtables_ip6mask_to_numeric(&e->smask.a6));
		else
			printf("%stunnel-src %s%s ", prefix,
			       xtables_ipaddr_to_numeric(&e->saddr.a4),
			       xtables_ipmask_to_numeric(&e->smask.a4));
	}
}
Exemple #10
0
void print_addrinfo(struct addrinfo *aip) {
	print_flags(aip);
	putchar('\n');
	print_family(aip);
	putchar('\n');
	print_type(aip);
	putchar('\n');
	print_proto(aip);
	putchar('\n');
	printf("host: %s", aip->ai_canonname ? aip->ai_canonname : "-");
	putchar('\n');
	if (aip->ai_family == AF_INET) {
		struct sockaddr_in *sinp = (struct sockaddr_in *)aip->ai_addr;
		char abuf[INET_ADDRSTRLEN];
		const char *addr = inet_ntop(AF_INET, &sinp->sin_addr, abuf,
				INET_ADDRSTRLEN);
		printf("address: %s\n", addr ? addr : "unknown");
		printf("port: %d\n", ntohs(sinp->sin_port));
	}
	putchar('\n');
}
Exemple #11
0
/**
 * user logout
 *  
 * @method logout
 * @param {string} sid sid which is used for logout.
 * @param {char*} buf respone data.
 * @return {int} louout status. 
 */
int logout(string sid, char *buf, int &send_len) {
    string respon_data;
    int result;
    string msg;
    Response::HTTPResponse *http_res = new Response::HTTPResponse();

    LOG_INFO << " sid is " << sid << endl;

    do {    
        //sid is not be found
        if (Tool::trim(sid).empty()) {
            result = PARAM_ERROR;
            _set_http_head(result, false, "sid is null", http_res);
            break;
        }

        // session is not exist
        if (Session::get(sid) == NULL) {
            result = SESSION_NOT_EXIST;
            _set_http_head(result, false, "session not exist", http_res);
            break;
        }

        // remove session
        cout << Session::get(sid)->uid << endl;
        Session::remove(Session::get(sid)->uid);
        result = LOGOUT_SUCCESS;
        _set_http_head(result, true, "remove session success", http_res);
    } while(0);

    print_proto(http_res);

    http_res->SerializeToString(&respon_data);
    memcpy(buf, respon_data.c_str(), respon_data.length());
    send_len = respon_data.length();
    google::protobuf::ShutdownProtobufLibrary();

    return result;
}
Exemple #12
0
/**
 * user resiest
 *  
 * @method resiest
 * @param {string} username username which is used for regiested.
 * @param {string} password password which is used for regiested.
 * @param {char *} buf respone data.
 * @return {int} regiest status. 
 */
int regiest(string username, string password, char *buf, int &send_len) {
    string respon_data;
    Response::HTTPResponse *http_res = new Response ::HTTPResponse();
    string msg;
    int result;
    int ret;

    do {
        LOG_INFO << "regiest params: username is " << username << " password is " << password << endl;

        // username or password not be found
        if (Tool::trim(username).empty() || Tool::trim(password).empty()) {
            result = PARAM_ERROR;
            _set_http_head(result, false, "username or password is null", http_res);
            break;
        }

        // get database config
        Config *c = Config::get_instance();
        map<string, string> config = c->get_config();
        eagleMysql e(config["DOMAIN"].c_str(), config["USER_NAME"].c_str(), 
            config["PASSWORD"].c_str(), config["DATABASE"].c_str(), Tool::S2I(config["PORT"], 3306));

        bool exist;

        ret = e.is_exist("t_user", "where username = '******'", exist);
        // exception
        if (ret != DB_OK) {
            result = DB_ERROR;
            _set_http_head(result, false, "DB ERROR|" + Tool::toString(ret), http_res);
            break;
        }
        // username already exist
        if (exist) {
            result = USERNAME_IS_EXIST;
            _set_http_head(result, false, "username is already exist", http_res);
            break;
        }

        // save the user info to database
        map<string, string> reg_params;
        reg_params["username"] = Tool::mysql_filter(username);
        reg_params["password"] = Tool::mysql_filter(password);
        int insert_id = -1;
        ret = e.insert("t_user", reg_params, insert_id);
        // exception
        if (ret != DB_OK) {
            result = REGIEST_FAIL;
            _set_http_head(result, false, "REGIEST_FAIL|" + Tool::toString(ret), http_res);
            break;
        }

        // set HTTPResponse
        result = REGIEST_SUCCESS;
        _set_http_head(result, true, "regiest success", http_res);
    } while(0);

    print_proto(http_res);

    http_res->SerializeToString(&respon_data);
    memcpy(buf, respon_data.c_str(), respon_data.length());
    send_len = respon_data.length();
    google::protobuf::ShutdownProtobufLibrary();

    return result;
}
Exemple #13
0
/* We want this to be readable, so only print out neccessary fields.
* Because that's the kind of world I want to live in.  */
extern EXPORT const char* output_rule4(const struct ipt_entry *e, void *h, const char *chain, int counters)
{
	const struct xt_entry_target *t;
	const char *target_name;
	char buf[BUFSIZ];

	/* print counters for iptables-save */
	if (counters > 0)
		ptr += sprintf(ptr,"[%llu:%llu] ", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);

	/* print chain name */
	ptr += sprintf(ptr,"-A %s", chain);

	/* Print IP part. */
	print_ip("-s", e->ip.src.s_addr, e->ip.smsk.s_addr,
		e->ip.invflags & IPT_INV_SRCIP);

	print_ip("-d", e->ip.dst.s_addr, e->ip.dmsk.s_addr,
		e->ip.invflags & IPT_INV_DSTIP);

	print_iface('i', e->ip.iniface, e->ip.iniface_mask,
		e->ip.invflags & IPT_INV_VIA_IN);

	print_iface('o', e->ip.outiface, e->ip.outiface_mask,
		e->ip.invflags & IPT_INV_VIA_OUT);

	print_proto(e->ip.proto, e->ip.invflags & XT_INV_PROTO);

	if (e->ip.flags & IPT_F_FRAG)
		ptr += sprintf(ptr,"%s -f",
		e->ip.invflags & IPT_INV_FRAG ? " !" : "");

	/* Print matchinfo part */
	if (e->target_offset) {
		IPT_MATCH_ITERATE(e, print_match_save, &e->ip);
	}

	/* print counters for iptables -R */
	if (counters < 0)
		ptr += sprintf(ptr," -c %llu %llu", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);

	/* Print target name */
	target_name = iptc_get_target(e, h);
#ifdef OLD_IPTABLES
	if (target_name && (*target_name != '\0'))
#ifdef IPT_F_GOTO
		ptr += sprintf(ptr," -%c %s", e->ip.flags & IPT_F_GOTO ? 'g' : 'j', target_name);
#else
		ptr += sprintf(ptr," -j %s", target_name);
#endif
#endif

	/* Print targinfo part */
	t = ipt_get_target((struct ipt_entry *)e);
	if (t->u.user.name[0]) {
		const struct xtables_target *target =
			xtables_find_target(t->u.user.name, XTF_TRY_LOAD);

		if (!target) {
			fprintf(stderr, "Can't find library for target `%s'\n",
				t->u.user.name);
			return NULL;
		}
		
#ifndef OLD_IPTABLES
		ptr += sprintf(ptr, " -j %s", target->alias ? target->alias(t) : target_name);
#endif

		if (target){
			if (target->save){
				memset(buf, 0, sizeof(buf));
				switchStdout("/dev/null");
				setvbuf(stdout, buf, _IOLBF, BUFSIZ);
				target->save(&e->ip, t);
				fflush(stdout);
				setbuf(stdout, NULL);
				revertStdout();
				ptr += sprintf(ptr, "%s", buf);
			}
			else {
				/* If the target size is greater than xt_entry_target
				* there is something to be saved, we just don't know
				* how to print it */
				if (t->u.target_size !=
					sizeof(struct xt_entry_target)) {
					fprintf(stderr, "Target `%s' is missing "
						"save function\n",
						t->u.user.name);
					return NULL;
				}
			}
		}
	}

#ifndef OLD_IPTABLES
	else if (target_name && (*target_name != '\0')){
#ifdef IPT_F_GOTO
		ptr += sprintf(ptr, " -%c %s", e->ip.flags & IPT_F_GOTO ? 'g' : 'j', target_name);
#else
		ptr += sprintf(ptr, " -j %s", target_name);
#endif
	}
#endif

	*ptr = '\0';
	ptr = buffer;

	return buffer;
}
int show_user_room(map<string, string> param, char *buf, int &send_len)
{
    string respon_data;
    Response::HTTPResponse *http_res = new Response::HTTPResponse();
    string msg;
    int result = SHOW_USER_ROOM_SUCCESS;
    int ret;

    // database params
    Config *c = Config::get_instance();
    map<string, string> config = c->get_config();
    eagleMysql e(config["DOMAIN"].c_str(), config["USER_NAME"].c_str(), config["PASSWORD"].c_str(), config["DATABASE"].c_str(), Tool::S2I(config["PORT"], 3306));

    do
    {
        // param sid not exist
        if (param.count("sid") == 0)
        {
            result = PARAM_ERROR;
            http_res->set_code(PARAM_ERROR);
            msg = "param sid not exist";
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            break;
        }

        SESSION *ss = Session::get(Tool::trim(param["sid"]));
        // session is not exist
        if (ss == NULL) {
            result = SESSION_NOT_EXIST;
            http_res->set_code(SESSION_NOT_EXIST);
            msg = "session not exist";
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            break;
        }

        int room_status = Tool::S2I(param["roomStatus"]);
        int show_type = Tool::S2I(param["showType"]);
        int uid = Tool::S2I(ss->uid);
        int page_no = Tool::S2I(param["pageNo"]);
        int page_size = Tool::S2I(param["pageSize"]);

        LOG_INFO << "room_status:" << room_status << "|show_type:" << show_type << "|uid:" << uid << "|" 
        << "page_no:" << page_no << "|page_size:" << page_size << endl;

        if (room_status < 0 || show_type < 0 || uid < 0 || !(show_type == 0 || show_type == 1) || page_no < 0 || page_size < 0)
        {
            result = PARAM_ERROR;
            http_res->set_code(PARAM_ERROR);
            msg = "param error";
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            break;
        }
        int begin_pos = (page_no - 1) * page_size;


        string room_condition_sql;
        if (show_type == 0) {
            room_condition_sql = " (select id from t_room where owner_id = " + ss->uid + ") ";
        } else if (show_type == 1) {
            room_condition_sql = " (select room_id from t_room_user_relation where user_id = " + ss->uid + ") ";
        }
        string sql = 
        "SELECT r.id as room_id, r.title, r.owner_id, u.nickname, r.type, "
        "r.preview_pic_id, r.gender_type, (select count(1) from t_room_user_relation where room_id = r.id) as join_num, "
        "r.limit_person_num, r.record_id, r.create_time, r.begin_time, "
        "a.longitude, a.latitude, a.detail_addr, a.addr_remark "
        "FROM t_room r, t_address a, t_user u where r.id in " + room_condition_sql + 
        "and a.id = r.addr_id and r.owner_id = u.id and r.room_status = " + param["roomStatus"] + 
        " limit " + Tool::toString(begin_pos) + "," + Tool::toString(page_size);

        LOG_DEBUG << sql << endl;

        int count = 0;

        string count_condition_sql = " where r.id in " + room_condition_sql + 
        "and a.id = r.addr_id and r.owner_id = u.id and r.room_status = " + param["roomStatus"];

        ret = e.count(" t_room r, t_address a, t_user u ", count_condition_sql, count);


        // exception
        if (ret != DB_OK) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|count room|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }
        LOG_INFO << "total user room:" << Tool::toString(count);
        MYSQL mysql;

        // connect fail
        if (!e.connet()) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|get user room list|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }

        // get page data
        ret = e.excute(sql);

        // exception
        if (ret != DB_OK) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|excute sql error|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }

        mysql = e.get_mysql();
        MYSQL_RES *rst = NULL;
        MYSQL_FIELD *field = NULL;
        MYSQL_ROW row = NULL;

        rst = mysql_store_result(&mysql);
        int fieldcount = mysql_num_fields(rst);
        row = mysql_fetch_row(rst);

        Data::List *room_list = new Data::List();
        int data_num = begin_pos;
        while(NULL != row) 
        {
            RoomData::RoomInfo *room_info = room_list->add_room_info();
            RoomData::Address *addr = new RoomData::Address();
            for(int i = 0; i < fieldcount; i++) 
            {
                field = mysql_fetch_field_direct(rst, i);
                string key = field->name;
                if (row[i] == NULL)
                    continue;
                if (key == "room_id") {
                    room_info->set_room_id(Tool::fromString<int>(row[i]));
                } else if (key == "title") {
                    room_info->set_title(row[i]);
                } else if (key == "owner_id") {
                    room_info->set_owner_id(Tool::fromString<int>(row[i]));
                } else if (key == "nickname") {
                    room_info->set_owner_nickname(row[i]);
                } else if (key == "type") {
                    room_info->set_type(Tool::fromString<int>(row[i]));
                } else if (key == "preview_pic_id") {
                    room_info->set_pic_id(Tool::fromString<int>(row[i]));
                } else if (key == "gender_type") {
                    room_info->set_gender_type(Tool::fromString<int>(row[i]));
                } else if (key == "join_num") {
                    room_info->set_join_person_count(Tool::fromString<int>(row[i]) + 1);
                } else if (key == "limit_person_num") {
                    room_info->set_limit_person_count(Tool::fromString<int>(row[i]));
                } else if (key == "record_id") {
                    room_info->set_record_id(Tool::fromString<int>(row[i]));
                } else if (key == "create_time") {
                    room_info->set_create_time(row[i]);
                } else if (key == "begin_time") {
                    room_info->set_begin_time(row[i]);
                } else if (key == "latitude") {
                    addr->set_latitude(Tool::fromString<double>(row[i]));
                } else if (key == "longitude") {
                    addr->set_longitude(Tool::fromString<double>(row[i]));
                } else if (key == "detail_addr") {
                    addr->set_detail_addr(row[i]);
                } else if (key == "addr_remark") {
                    addr->set_addr_remark(row[i]);
                }
            }
            row = mysql_fetch_row(rst);
            data_num++;
            room_info->set_allocated_address(addr);
        }
        if (data_num == count) {
            room_list->set_is_end(true);
        }
        http_res->set_allocated_list(room_list);



        // success
        result = SHOW_USER_ROOM_SUCCESS;
        http_res->set_code(SHOW_USER_ROOM_SUCCESS);
        http_res->set_success(true);
        msg = "show user room success";
        LOG_INFO << msg << endl;
        http_res->set_msg(msg);
        e.close();

    } while(0);
    print_proto(http_res);

    http_res->SerializeToString(&respon_data);
    memcpy(buf, respon_data.c_str(), respon_data.length());
    send_len = respon_data.length();
    google::protobuf::ShutdownProtobufLibrary();

    return result;
}
int show_room_peo_list(map<string, string> param, char *buf, int &send_len)
{
    string respon_data;
    Response::HTTPResponse *http_res = new Response::HTTPResponse();
    string msg;
    int result;
    int ret;

    // database params
    Config *c = Config::get_instance();
    map<string, string> config = c->get_config();
    eagleMysql e(config["DOMAIN"].c_str(), config["USER_NAME"].c_str(), config["PASSWORD"].c_str(), config["DATABASE"].c_str(), Tool::S2I(config["PORT"], 3306));

    do
    {
        // param sid not exist
        if (param.count("sid") == 0)
        {
            result = PARAM_ERROR;
            http_res->set_code(PARAM_ERROR);
            msg = "param sid not exist";
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            break;
        }

        // session is not exist
        SESSION *se = Session::get(Tool::trim(param["sid"]));
        if (se == NULL) {
            result = SESSION_NOT_EXIST;
            http_res->set_code(SESSION_NOT_EXIST);
            msg = "session not exist";
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            break;
        }

        string s_user_id = se->uid;
        
        int room_id = Tool::S2I(param["roomId"]);
        int page_size = Tool::S2I(param["pageSize"]);
        int page_no = Tool::S2I(param["pageNo"]);

        if (room_id < 0 || page_size < 0 || page_no < 0)
        {
            result = PARAM_ERROR;
            http_res->set_code(PARAM_ERROR);
            msg = "param error";
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            break;
        }

        MYSQL mysql;

        // connect fail
        if (!e.connet()) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|join room|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }

        string sql_count = "select count(1) from t_user where id in "
        " (select user_id from t_room_user_relation where room_id = " + param["roomId"] + 
        " union select owner_id from t_room where id = " + param["roomId"] + ") ";
        LOG_DEBUG << sql_count << endl;

        ret = e.excute(sql_count);
        // exception
        if (ret != DB_OK) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|excute count user|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }

        mysql = e.get_mysql();
        MYSQL_RES *count_rst = mysql_store_result(&mysql);
        MYSQL_ROW count_row = mysql_fetch_row(count_rst);
        int total_num;
        if (count_row) {
            total_num = atoi(count_row[0]);
        } else {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|no data";
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }
        LOG_DEBUG << "total:" << total_num << endl;

        e.close();



        // connect fail
        if (!e.connet()) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|join room|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }
        int begin_pos = (page_no - 1) * page_size;

        string sql = "select u.id, u.username, u.nickname, u.sex, u.pic_id, "
        " (select count(1) from t_follow where followed_id = u.id and follow_id = " + s_user_id + ") as is_follow "
        " from t_user u where u.id in " 
        " (SELECT user_id FROM t_room_user_relation where room_id = " + param["roomId"] + 
        " union select owner_id from t_room where id = " + param["roomId"] + ") "
        "limit " + Tool::toString(begin_pos) + ", " + param["pageSize"];

        ret = e.excute(sql);
        // exception
        if (ret != DB_OK) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|get room people|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }

        mysql = e.get_mysql();

        MYSQL_RES *rst = NULL;
        MYSQL_FIELD *field = NULL;
        MYSQL_ROW row = NULL;

        rst = mysql_store_result(&mysql);
        int fieldcount = mysql_num_fields(rst);
        row = mysql_fetch_row(rst);

        Data::List *people_list = new Data::List();
        int data_num = begin_pos;
        while(NULL != row) 
        {
            UserResponse::DetailResponse *user_detail = people_list->add_user_detail();
            UserData::User_Info *info = new UserData::User_Info();
            int is_follow;
            for(int i = 0; i < fieldcount; i++) 
            {
                field = mysql_fetch_field_direct(rst, i);
                string key = field->name;
                if (row[i] == NULL)
                    continue;
                // LOG_DEBUG << row[i] << endl;
                if (key == "id") {
                    info->set_uid(Tool::S2I(row[i]));
                } else if (key == "username") {
                    info->set_username(row[i]);
                } else if (key == "nickname") {
                    info->set_nick_name(row[i]);
                } else if (key == "sex") {
                    info->set_sex(Tool::S2I(row[i]));
                } else if (key == "pic_id") {
                    info->set_pic_id(Tool::S2I(row[i]));
                } else if (key == "is_follow") {
                    is_follow = Tool::S2I(row[i]);
                }
            }
            is_follow > 0 ? user_detail->set_is_follow(true): user_detail->set_is_follow(false);
            user_detail->set_allocated_user_info(info);
            row = mysql_fetch_row(rst);
            data_num++;
        }
        if (data_num == total_num) {
            people_list->set_is_end(true);
        }
        http_res->set_allocated_list(people_list);

        // mysql_free_result(rst); 


        // success
        result = SHOW_ROOM_PEO_LIST_SUCCESS;
        http_res->set_code(SHOW_ROOM_PEO_LIST_SUCCESS);
        http_res->set_success(true);
        msg = "show room peo list success";
        LOG_INFO << msg << endl;
        http_res->set_msg(msg);
        e.close();

    } while(0);
    print_proto(http_res);

    http_res->SerializeToString(&respon_data);
    memcpy(buf, respon_data.c_str(), respon_data.length());
    send_len = respon_data.length();
    google::protobuf::ShutdownProtobufLibrary();

    return result;
}
Exemple #16
0
/**
 * user login
 *  
 * @method login
 * @param {string} username username which is used for login.
 * @param {string} password password which is used for login.
 * @param {char*} respone data. 
 * @return {int} login status.
 */
int login(string username, string password, string dev_id, char *buf, int &send_len) {
    string respon_data;
    Response::HTTPResponse *http_res = new Response::HTTPResponse();
    string msg;
    int result;
    int ret;

    do {
        LOG_INFO << "login params: username is " << username << " password is " << password << "dev_id is " << dev_id << endl;
        
        // username or password not be found
        if (Tool::trim(username).empty() || Tool::trim(password).empty() || Tool::trim(dev_id).empty()) {
            result = PARAM_ERROR;
            _set_http_head(result, false, "username or password or dev_id is null", http_res);
            break;
        }

        // database params
        Config *c = Config::get_instance();
        map<string, string> config = c->get_config();
        eagleMysql e(config["DOMAIN"].c_str(), config["USER_NAME"].c_str(), config["PASSWORD"].c_str(), config["DATABASE"].c_str(), Tool::S2I(config["PORT"], 3306));
        bool exist;

        // check whether username and password match is database or not 
        ret = e.is_exist("t_user", "where username = '******' and password = '******'", exist);
        // exception
        if (ret != DB_OK) {
            result = DB_ERROR;
            _set_http_head(result, false, "DB ERROR|" + Tool::toString(ret), http_res);
            break;
        }
        // user not exist
        if (!exist) {
            result = USER_NOT_EXIST;
            _set_http_head(result, false, "user not exist", http_res);
            break;
        }

        // set session
        string sid;
        int uid;

        _get_uid(username, uid);

        ret = Session::set(Tool::toString(uid), dev_id, sid);
        LOG_INFO << "sid is: " << sid << endl;
        if (ret == LOGIN_REPLACE) {
            result = LOGIN_REPLACE;
            _set_http_head(result, true, "login success and replace session", http_res);
        } else {
            result = LOGIN_SUCCESS;
            _set_http_head(result, true, "login success", http_res);
        }

        UserData::User_Info *user_info = new UserData::User_Info();
        ret = _get_user_info(uid, user_info);
        // exception
        if (ret != DB_OK) {
            result = DB_ERROR;
            _set_http_head(result, false, "DB ERROR|" + Tool::toString(ret), http_res);
            break;
        }
        UserResponse::LoginResponse *login_res = new UserResponse::LoginResponse();
        login_res->set_allocated_user_info(user_info);
        login_res->set_sid(sid);
        http_res->set_allocated_login_response(login_res);
    } while(0);

    print_proto(http_res);

    http_res->SerializeToString(&respon_data);
    memcpy(buf, respon_data.c_str(), respon_data.length());
    send_len = respon_data.length();
    google::protobuf::ShutdownProtobufLibrary();

    return result;
}
int show_room_list(map<string, string> param, char *buf, int &send_len)
{
    string respon_data;
    Response::HTTPResponse *http_res = new Response::HTTPResponse();
    string msg;
    int result = SHOW_ROOM_LIST_SUCCESS;
    int ret;

    do
    {
        string sql_condition = "";
        // essential
        string room_type = Tool::trim(param["roomType"]);
        string lng = Tool::trim(param["longitude"]);
        string lat = Tool::trim(param["latitude"]);
        int page_no = Tool::S2I(param["pageNo"]);
        int page_size = Tool::S2I(param["pageSize"]);
        string dist = param["range"]; // km

        if (room_type.empty() || !Tool::isNum(lng) || !Tool::isNum(lat) || page_no < 0 || page_size < 0 || !Tool::isNum(param["range"]))
        {
            result = PARAM_ERROR;
            http_res->set_code(PARAM_ERROR);
            msg = "param error";
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            break;
        }

        LOG_INFO << "room_type:" << room_type << "|" << "longitude:" << lng << "|" << 
        "latitude:" << lat << "|" << "pageNo:" << page_no << "|" << "pageSize:" << page_size << endl;

        if (Tool::S2I(room_type) != 0) {
            sql_condition = sql_condition + " and r.type = " + room_type + " ";
        }
        int begin_pos = (page_no - 1) * page_size;
        
        // inessential
        if (param.count("genderType") > 0 && Tool::isNum(param["genderType"]))
        {
            // TODO:: judge legal?
            sql_condition = sql_condition + " and r.gender_type = " + param["genderType"] + " ";
        }
        if (param.count("roomStatus") > 0 && Tool::isNum(param["roomStatus"]))
        {
            // TODO:: judge legal?
            sql_condition = sql_condition + " and r.room_status = " + param["roomStatus"] + " ";
        }


        string er = "6366.564864";
        string lat_length = "(20003.93/180)";
        string lat_left = lat + "-(" + dist + "/" +  lat_length + ")";
        string lat_right = lat + "+(" + dist + "/" +  lat_length + ")";
        string lng_left = lng + "-" + dist + "/abs(cos(radians(" + lat + "))*" + lat_length + ")";
        string lng_right = lng + "+" + dist + "/abs(cos(radians(" + lat + "))*" + lat_length + ")";

        string dis_sql = "SELECT r.id, r.owner_id, u.nickname, r.title, r.type, r.room_status, "
        "  r.preview_pic_id, r.gender_type,  r.limit_person_num,  r.record_id, r.create_time, r.begin_time, a.latitude, a.longitude, a.detail_addr, a.addr_remark, " + 
        er + "*2*ASIN(SQRT(POWER(SIN((" + lat + " - a.latitude)*pi()/180 / 2), 2)" + 
        " +  COS(" + lat + " * pi()/180) * COS(a.latitude * pi()/180) *  POWER(SIN((" + lng + " - a.longitude) * pi()" + 
        "/180 / 2), 2) )) as dist, "
        "(select count(1) from t_room_user_relation where room_id = r.id) as join_person_num "
        " FROM t_address a, t_room r , t_user u WHERE a.latitude BETWEEN " + lat_left + " AND " + lat_right +
        " AND a.longitude BETWEEN " + lng_left + "AND " + lng_right + " AND r.addr_id = a.id and r.owner_id = u.id  "
         + sql_condition + " having dist < " + dist + " ORDER BY dist limit " + Tool::toString(begin_pos) + "," + Tool::toString(page_size) + ";";

        string dis_sql_total = "select count(1), " + 
        er + "*2*ASIN(SQRT(POWER(SIN((" + lat + " - a.latitude)*pi()/180 / 2), 2)" + 
        " +  COS(" + lat + " * pi()/180) * COS(a.latitude * pi()/180) *  POWER(SIN((" + lng + " - a.longitude) * pi()" + 
        "/180 / 2), 2) )) as dist "
        "from t_address a, t_room r , t_user u WHERE a.latitude BETWEEN "
         + lat_left + " AND " + lat_right + " AND a.longitude BETWEEN " + lng_left + "AND " + lng_right + " AND r.addr_id = a.id and r.owner_id = u.id "
          + sql_condition + " having dist < " + dist + ";";

        LOG_DEBUG << dis_sql << endl;
        LOG_DEBUG << dis_sql_total << endl;

         // get data from database
        Config *c = Config::get_instance();
        map<string, string> config = c->get_config();
        eagleMysql e(config["DOMAIN"].c_str(), config["USER_NAME"].c_str(), 
        config["PASSWORD"].c_str(), config["DATABASE"].c_str(), Tool::S2I(config["PORT"], 3306));
        // connect fail
        if (!e.connet()) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|get room list info|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }

        MYSQL mysql;

        // get total count
        ret = e.excute(dis_sql_total);
        // exception
        if (ret != DB_OK) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|excute dis_sql_total|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }

        mysql = e.get_mysql();
        MYSQL_RES *count_rst = mysql_store_result(&mysql);
        MYSQL_ROW count_row = mysql_fetch_row(count_rst);
        int total_num;
        if (count_row) {
            total_num = atoi(count_row[0]);
        } else {
            result = SHOW_ROOM_LIST_SUCCESS;
            http_res->set_code(SHOW_ROOM_LIST_SUCCESS);
            http_res->set_success(true);
            msg = "DB ERROR|no data";
            LOG_ERROR << msg << endl;
            Data::List *room_list = new Data::List();
            room_list->set_is_end(true);
            http_res->set_allocated_list(room_list);
            http_res->set_msg(msg);
            e.close();
            break;
        }

        e.close();


        // connect fail
        if (!e.connet()) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|get room list info|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }

        // get page data
        ret = e.excute(dis_sql);

        // exception
        if (ret != DB_OK) {
            result = DB_ERROR;
            http_res->set_code(DB_ERROR);
            msg = "DB ERROR|excute dis_sql error|" + Tool::toString(ret);
            LOG_ERROR << msg << endl;
            http_res->set_msg(msg);
            e.close();
            break;
        }

        mysql = e.get_mysql();
        MYSQL_RES *rst = NULL;
        MYSQL_FIELD *field = NULL;
        MYSQL_ROW row = NULL;

        rst = mysql_store_result(&mysql);
        int fieldcount = mysql_num_fields(rst);
        row = mysql_fetch_row(rst);

        Data::List *room_list = new Data::List();
        int data_num = begin_pos;
        while(NULL != row) 
        {
            RoomData::RoomInfo *room_info = room_list->add_room_info();
            RoomData::Address *addr = new RoomData::Address();
            for(int i = 0; i < fieldcount; i++) 
            {
                field = mysql_fetch_field_direct(rst, i);
                string key = field->name;
                if (row[i] == NULL)
                    continue;
                if (key == "id") {
                    room_info->set_room_id(Tool::fromString<int>(row[i]));
                } else if (key == "title") {
                    room_info->set_title(row[i]);
                } else if (key == "owner_id") {
                    room_info->set_owner_id(Tool::fromString<int>(row[i]));
                } else if (key == "nickname") {
                    room_info->set_owner_nickname(row[i]);
                } else if (key == "type") {
                    room_info->set_type(Tool::fromString<int>(row[i]));
                } else if (key == "room_status") {
                    room_info->set_status(Tool::fromString<int>(row[i]));
                } else if (key == "preview_pic_id") {
                    room_info->set_pic_id(Tool::fromString<int>(row[i]));
                } else if (key == "gender_type") {
                    room_info->set_gender_type(Tool::fromString<int>(row[i]));
                } else if (key == "dist") {
                    room_info->set_distance(Tool::fromString<double>(row[i]));
                } else if (key == "join_person_num") {
                    room_info->set_join_person_count(Tool::fromString<int>(row[i]) + 1);
                } else if (key == "limit_person_num") {
                    room_info->set_limit_person_count(Tool::fromString<int>(row[i]));
                } else if (key == "record_id") {
                    room_info->set_record_id(Tool::fromString<int>(row[i]));
                } else if (key == "create_time") {
                    room_info->set_create_time(row[i]);
                } else if (key == "begin_time") {
                    room_info->set_begin_time(row[i]);
                } else if (key == "latitude") {
                    addr->set_latitude(Tool::fromString<double>(row[i]));
                } else if (key == "longitude") {
                    addr->set_longitude(Tool::fromString<double>(row[i]));
                } else if (key == "detail_addr") {
                    addr->set_detail_addr(row[i]);
                } else if (key == "addr_remark") {
                    addr->set_addr_remark(row[i]);
                }
            }
            row = mysql_fetch_row(rst);
            data_num++;
            room_info->set_allocated_address(addr);
        }
        if (data_num == total_num) {
            room_list->set_is_end(true);
        }
        http_res->set_allocated_list(room_list);

        e.close();

        // success
        result = SHOW_ROOM_LIST_SUCCESS;
        http_res->set_code(SHOW_ROOM_LIST_SUCCESS);
        http_res->set_success(true);
        msg = "show room list success";
        LOG_INFO << msg << endl;
        http_res->set_msg(msg);
    } while(0);
    print_proto(http_res);

    http_res->SerializeToString(&respon_data);
    memcpy(buf, respon_data.c_str(), respon_data.length());
    send_len = respon_data.length();

    google::protobuf::ShutdownProtobufLibrary();

    return result;
}
/* We want this to be readable, so only print out neccessary fields.
 * Because that's the kind of world I want to live in.  */
static void print_rule(const struct ipt_entry *e, 
		iptc_handle_t *h, const char *chain, int counters)
{
	struct ipt_entry_target *t;
	const char *target_name;

	/* print counters */
	if (counters)
		printf("[%llu:%llu] ", e->counters.pcnt, e->counters.bcnt);

	/* print chain name */
	printf("-A %s ", chain);

	/* Print IP part. */
	print_ip("-s", e->ip.src.s_addr,e->ip.smsk.s_addr,
			e->ip.invflags & IPT_INV_SRCIP);	

	print_ip("-d", e->ip.dst.s_addr, e->ip.dmsk.s_addr,
			e->ip.invflags & IPT_INV_DSTIP);

	print_iface('i', e->ip.iniface, e->ip.iniface_mask,
		    e->ip.invflags & IPT_INV_VIA_IN);

	print_iface('o', e->ip.outiface, e->ip.outiface_mask,
		    e->ip.invflags & IPT_INV_VIA_OUT);

	print_proto(e->ip.proto, e->ip.invflags & IPT_INV_PROTO);

	if (e->ip.flags & IPT_F_FRAG)
		printf("%s-f ",
		       e->ip.invflags & IPT_INV_FRAG ? "! " : "");

	/* Print matchinfo part */
	if (e->target_offset) {
		IPT_MATCH_ITERATE(e, print_match, &e->ip);
	}

	/* Print target name */	
	target_name = iptc_get_target(e, h);
	if (target_name && (*target_name != '\0'))
		printf("-j %s ", target_name);

	/* Print targinfo part */
	t = ipt_get_target((struct ipt_entry *)e);
	if (t->u.user.name[0]) {
		struct iptables_target *target
			= find_target(t->u.user.name, TRY_LOAD);

		if (!target) {
			fprintf(stderr, "Can't find library for target `%s'\n",
				t->u.user.name);
			exit(1);
		}

		if (target->save)
			target->save(&e->ip, t);
		else {
			/* If the target size is greater than ipt_entry_target
			 * there is something to be saved, we just don't know
			 * how to print it */
			if (t->u.target_size != 
			    sizeof(struct ipt_entry_target)) {
				fprintf(stderr, "Target `%s' is missing "
						"save function\n",
					t->u.user.name);
				exit(1);
			}
		}
	}
	printf("\n");
}
Exemple #19
0
/* We want this to be readable, so only print out neccessary fields.
 * Because that's the kind of world I want to live in.  */
static void print_rule(const struct ip6t_entry *e, 
		ip6tc_handle_t *h, const char *chain, int counters)
{
	struct ip6t_entry_target *t;
	const char *target_name;

	/* print counters */
	if (counters)
		printf("[%llu:%llu] ", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);

	/* print chain name */
	printf("-A %s ", chain);

	/* Print IP part. */
	print_ip("-s", &(e->ipv6.src), &(e->ipv6.smsk),
			e->ipv6.invflags & IP6T_INV_SRCIP);	

	print_ip("-d", &(e->ipv6.dst), &(e->ipv6.dmsk),
			e->ipv6.invflags & IP6T_INV_DSTIP);

	print_iface('i', e->ipv6.iniface, e->ipv6.iniface_mask,
		    e->ipv6.invflags & IP6T_INV_VIA_IN);

	print_iface('o', e->ipv6.outiface, e->ipv6.outiface_mask,
		    e->ipv6.invflags & IP6T_INV_VIA_OUT);

	print_proto(e->ipv6.proto, e->ipv6.invflags & IP6T_INV_PROTO);

#if 0
	/* not definied in ipv6
	 * FIXME: linux/netfilter_ipv6/ip6_tables: IP6T_INV_FRAG why definied? */
	if (e->ipv6.flags & IPT_F_FRAG)
		printf("%s-f ",
		       e->ipv6.invflags & IP6T_INV_FRAG ? "! " : "");
#endif

	if (e->ipv6.flags & IP6T_F_TOS)
		printf("%s-? %d ",
		       e->ipv6.invflags & IP6T_INV_TOS ? "! " : "", 
		       e->ipv6.tos);

	/* Print matchinfo part */
	if (e->target_offset) {
		IP6T_MATCH_ITERATE(e, print_match, &e->ipv6);
	}

	/* Print target name */	
	target_name = ip6tc_get_target(e, h);
	if (target_name && (*target_name != '\0'))
		printf("-j %s ", target_name);

	/* Print targinfo part */
	t = ip6t_get_target((struct ip6t_entry *)e);
	if (t->u.user.name[0]) {
		struct ip6tables_target *target
			= find_target(t->u.user.name, TRY_LOAD);

		if (!target) {
			fprintf(stderr, "Can't find library for target `%s'\n",
				t->u.user.name);
			exit(1);
		}

		if (target->save)
			target->save(&e->ipv6, t);
		else {
			/* If the target size is greater than ip6t_entry_target
			 * there is something to be saved, we just don't know
			 * how to print it */
			if (t->u.target_size != 
			    sizeof(struct ip6t_entry_target)) {
				fprintf(stderr, "Target `%s' is missing "
						"save function\n",
					t->u.user.name);
				exit(1);
			}
		}
	}
	printf("\n");
}
Exemple #20
0
/*
 * get new messages
 *  
 * @method get_new_msgs
 * @param {int} current_id current message id.
 * @return {int} get_new_msgs status.
 */
int get_msg_list(int recipient_id, char *buf, int &send_len) {
    string respon_data;
    Response::HTTPResponse *http_res = new Response::HTTPResponse();
    string msg;
    int result;
    int ret;

    LOG_INFO << " recipient_id is " << recipient_id << endl;

    do {
        if (recipient_id < 0) {
            result = PARAM_ERROR;
            _set_http_head(result, false, "recipient_id is not exist", http_res);
            break; 
        }

        Config *c = Config::get_instance();
        map<string, string> config = c->get_config();
        eagleMysql e(config["DOMAIN"].c_str(), config["USER_NAME"].c_str(), 
            config["PASSWORD"].c_str(), config["DATABASE"].c_str(), Tool::S2I(config["PORT"], 3306));

        if (!e.connet()) {
            result = SQL_CONNECT_FAIL;
            _set_http_head(result, false, "sql connet fail", http_res);
        }

        ret = e.excute("select id,sender_id,recipient_id from t_msg where recipient_id=" + Tool::mysql_filter(recipient_id) 
            + " and sender_id<>" + Tool::mysql_filter(recipient_id)
            + " and status=" + Tool::mysql_filter(MSG_NOT_READ)
            + " and type=" + Tool::mysql_filter(PRIVATE_CHAT) + ";");

        if (ret != DB_OK) {
            result = DB_ERROR;
            _set_http_head(result, false, "DB ERROR|" + Tool::toString(ret), http_res);
            break;
        }

        MYSQL mysql;
        mysql = e.get_mysql();

        MYSQL_RES *mysql_result = NULL;
        MYSQL_ROW row = NULL;

        mysql_result = mysql_store_result(&mysql);
        row = mysql_fetch_row(mysql_result);

        // follow_list construtor
        Data::List *message_list = new Data::List();
        while(NULL != row) {
            int follow_count = 0;
            int message_id = Tool::S2I(row[0]);
            int sender_id = Tool::S2I(row[1]);
            int recipient_id = Tool::S2I(row[2]);

            e.count("t_msg", "where id>=" + Tool::mysql_filter(message_id)
            + " and recipient_id=" + Tool::mysql_filter(recipient_id) 
            + " and sender_id=" + Tool::mysql_filter(sender_id)
            + " and status=" + Tool::mysql_filter(MSG_NOT_READ)
            + " and type=" + Tool::mysql_filter(PRIVATE_CHAT) + ";", follow_count);

            cout << "follow_count is " << follow_count << endl;

            if (follow_count == 1) {
                UserResponse::UserMessageResponse *user_message_info = message_list->add_user_message_info();
            
                MessageData::Message_Info *message_info = new MessageData::Message_Info();
                 _get_message_info(message_id, message_info);
                 user_message_info->set_allocated_message_info(message_info);

                UserData::User_Info *sender_info = new UserData::User_Info();
                ret = _get_user_info(sender_id, sender_info);
                // exception
                if (ret != DB_OK) {
                    result = DB_ERROR;
                    _set_http_head(result, false, "DB ERROR|" + Tool::toString(ret), http_res);
                    break;
                }
                user_message_info->set_allocated_sender(sender_info);
                
                UserData::User_Info *recipient_info = new UserData::User_Info();
                ret = _get_user_info(recipient_id, recipient_info);
                // exception
                if (ret != DB_OK) {
                    result = DB_ERROR;
                    _set_http_head(result, false, "DB ERROR|" + Tool::toString(ret), http_res);
                    break;
                }
                user_message_info->set_allocated_recipient(recipient_info);

                int count = 0;
                e.count("t_msg", "where recipient_id=" + Tool::mysql_filter(recipient_id)
                + " and sender_id=" + Tool::mysql_filter(sender_id)
                + " and status=" + Tool::mysql_filter(MSG_NOT_READ)
                + " and type=" + Tool::mysql_filter(PRIVATE_CHAT) + ";", count);            
                user_message_info->set_message_count(count);
            }

            row = mysql_fetch_row(mysql_result);
        }
        message_list->set_is_end(true);

        e.close();

        result = GET_MSG_LIST_SUCCESS;
        _set_http_head(result, true, "get message list success", http_res);
        http_res->set_allocated_list(message_list);
    } while(0);

    print_proto(http_res);

    http_res->SerializeToString(&respon_data);
    memcpy(buf, respon_data.c_str(), respon_data.length());
    send_len = respon_data.length();
    google::protobuf::ShutdownProtobufLibrary();

    return result;
}