static void get_address_from_ip(const char *text, std::string &ipstr, std::string &address)
{
	GMatchInfo *match_info;
	GRegex *regex = g_regex_new ("(((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.){3}((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))", (GRegexCompileFlags)0, (GRegexMatchFlags)0, NULL);
	g_regex_match (regex, text, (GRegexMatchFlags)0, &match_info);
	if (g_match_info_matches(match_info)) {
		gchar *word = g_match_info_fetch (match_info, 0);
		ipstr = word;
		g_free (word);
	}
	g_match_info_free (match_info);
	g_regex_unref (regex);
	if (ipstr.empty())
		return;
	std::string datafilename = plugin_info->datadir;
	datafilename += G_DIR_SEPARATOR_S "data" G_DIR_SEPARATOR_S "QQWry.Dat";
	FILE *fp = g_fopen(datafilename.c_str(), "rb");
	if (!fp) {
		gchar *msg = g_strdup_printf(_("Error: Open file %s failed!"), datafilename.c_str());
		address = msg;
		g_free(msg);
		return;
	}
	unsigned long index_start,index_end;
	getHead(fp,&index_start,&index_end);
	unsigned long ip = getIP(ipstr.c_str());
	unsigned long current=searchIP(fp,index_start,index_end,ip);
	std::string country,location;
	getAddress(fp,getValue(fp,current+4,3),country,location);
	gchar *c = g_convert(country.c_str(), -1, "UTF-8", "GB18030", NULL, NULL, NULL);
	if (c) {
		address += c;
		address += ' ';
		g_free(c);
	}
	gchar *l = g_convert(location.c_str(), -1, "UTF-8", "GB18030", NULL, NULL, NULL);
	if (l) {
		address += l;
		g_free(l);
	}
	fclose(fp);
}
void Widget::hasPendingFile(QString usrname, QString srvaddr,QString clntaddr, QString filename)
{
    QString ipAddr = getIP();
    if(ipAddr == clntaddr)
    {
        int btn = QMessageBox::information(this,tr("接受文件"),tr("来自%1(%2)的文件:%3,是否接收?").arg(usrname).arg(srvaddr).arg(filename),QMessageBox::Yes,QMessageBox::No);
        if (btn == QMessageBox::Yes) {
            QString name = QFileDialog::getSaveFileName(0,tr("保存文件"),filename);
            if(!name.isEmpty())
            {
                Client *clnt = new Client(this);
                clnt->setFileName(name);
                clnt->setHostAddr(QHostAddress(srvaddr));
                clnt->show();
            }
        } else {
            sndMsg(Refuse, srvaddr);
        }
    }
}
Exemple #3
0
std::tuple<int, int> Peer::GetRemotePeer(const std::string address) const {
	Print("resolving host (getremotepeer string)... '%s'\n", address);
	IPaddress IP;
	int dns;
	int count = 0;
	do
	{
		dns = SDLNet_ResolveHost(&IP,address.c_str(),0);
		if (!dns)
		{
			Print("found dns match: %i\n", getIP(IP.host));
			return GetRemotePeer(&IP);
		}
		count++;
	} while (count < 100 && !dns);

	if (!dns) Print("DNS Failed, tried: %i\n", count);
	
	return std::make_tuple(-1,-1);
}
void Connection::parseHeader(const boost::system::error_code& error)
{
	std::lock_guard<std::recursive_mutex> lockClass(connectionLock);
	readTimer.cancel();

	int32_t size = msg.decodeHeader();
	if (error || size <= 0 || size >= NETWORKMESSAGE_MAXSIZE - 16) {
		close(FORCE_CLOSE);
	}

	if (connectionState != CONNECTION_STATE_OPEN) {
		return;
	}

	uint32_t timePassed = std::max<uint32_t>(1, (time(nullptr) - timeConnected) + 1);
	if ((++packetsSent / timePassed) > static_cast<uint32_t>(g_config.getNumber(ConfigManager::MAX_PACKETS_PER_SECOND))) {
		std::cout << convertIPToString(getIP()) << " disconnected for exceeding packet per second limit." << std::endl;
		close();
		return;
	}

	if (timePassed > 2) {
		timeConnected = time(nullptr);
		packetsSent = 0;
	}

	try {
		readTimer.expires_from_now(boost::posix_time::seconds(Connection::read_timeout));
		readTimer.async_wait(std::bind(&Connection::handleTimeout, std::weak_ptr<Connection>(shared_from_this()),
		                                    std::placeholders::_1));

		// Read packet content
		msg.setLength(size + NetworkMessage::HEADER_LENGTH);
		boost::asio::async_read(socket, boost::asio::buffer(msg.getBodyBuffer(), size),
		                        std::bind(&Connection::parsePacket, shared_from_this(), std::placeholders::_1));
	} catch (boost::system::system_error& e) {
		std::cout << "[Network error - Connection::parseHeader] " << e.what() << std::endl;
		close(FORCE_CLOSE);
	}
}
Exemple #5
0
// Fonction enregistré au près du bouton pour être executé sur les events
void buttonEvent(TS_button* button, int event, void* args) {
	if (event == 0) { // cf ts.c pour les codes d'event, en bref : 0 = clic
		GUI* gui = args;
		if (button->label[0] == 'T') { // Le label du bouton indiqué « Team » → affichage team
		
			FB_background(gui, 0, 0, 0); // Font d'écran noir
			
			// On charge la bonne police pour les crédits, on set la taille, la couleurs
			FT_setFont(gui, "/home/elie/FreeSans.ttf");
			FT_setSize(gui, 40);
			FT_setColor(gui, 31, 0, 0);
			FT_printString(gui, "Djanos - Lockidor", -1, 75); // -1 → centré suivant x (cf ft.c)
			FT_setSize(gui, 35);
			FT_setColor(gui, 0, 0, 31);
			FT_printString(gui, "ENSEEIHT", -1, 150);
			FT_setSize(gui, 35);
			FT_setColor(gui, 0, 50, 20);
			FT_printString(gui, "Octobre 2011", -1, 225);
			
			// On change le label du bouton et on le re-dessine
			button->label = "IP";
			TS_printButton(gui, button);
			
		} else { // Le label du bouton indiqué « Retour » → affichage IP
		
			FB_background(gui, 31, 0, 0); // Font d'écran rouge (cachier des charges)
			
			FT_setFont(gui, gui->ip_font); // Police trouvé sur la carte SD
			FT_setSize(gui, gui->ip_size); // Taille contenu dans le nom du fichier
			FT_setColor(gui, 0, 0, 0); // En noir (cahier des charges)
			FT_printString(gui, getIP("eth0"), -1, -1); // cf ip.c pour l'obtention de l'ip (ioctl)
			
			// On change le label du bouton et on le re-dessine
			button->label = "Team";
			FT_setFont(gui, "/home/elie/FreeSans.ttf"); // avec la police non aléatoire, c'est mieux
			TS_printButton(gui, button);
			
		}
	}
}
Exemple #6
0
void ProtocolAdmin::onRecvFirstMessage(NetworkMessage& msg)
{
	//is the remote admin protocol enabled?
	if (!g_adminConfig->isEnabled()) {
		getConnection()->closeConnection();
		return;
	}

	m_state = NO_CONNECTED;

	//is allowed this ip?
	if (!g_adminConfig->allowIP(getIP())) {
		addLogLine(this, LOGTYPE_EVENT, 1, "ip not allowed");
		getConnection()->closeConnection();
		return;
	}

	//max connections limit
	if (!g_adminConfig->addConnection()) {
		addLogLine(this, LOGTYPE_EVENT, 1, "cannot add new connection");
		getConnection()->closeConnection();
		return;
	}

	addLogLine(this, LOGTYPE_EVENT, 1, "sending HELLO");
	//send hello
	OutputMessage_ptr output = OutputMessagePool::getInstance()->getOutputMessage(this, false);

	if (output) {
		output->AddByte(AP_MSG_HELLO);
		output->AddU32(1); //version
		output->AddString("OTADMIN");
		output->AddU16(g_adminConfig->getProtocolPolicy()); //security policy
		output->AddU32(g_adminConfig->getProtocolOptions()); //protocol options(encryption, ...)
		OutputMessagePool::getInstance()->send(output);
	}

	m_lastCommand = time(NULL);
	m_state = ENCRYPTION_NO_SET;
}
Exemple #7
0
void ProtocolAdmin::onRecvFirstMessage(NetworkMessage& msg)
{
	m_state = NO_CONNECTED;
	if(g_config.getString(ConfigManager::ADMIN_PASSWORD).empty())
	{
		addLogLine(LOGTYPE_EVENT, "connection attempt on disabled protocol");
		getConnection()->close();
		return;
	}

	if(!Admin::getInstance()->allow(getIP()))
	{
		addLogLine(LOGTYPE_EVENT, "ip not allowed");
		getConnection()->close();
		return;
	}

	if(!Admin::getInstance()->addConnection())
	{
		addLogLine(LOGTYPE_EVENT, "cannot add new connection");
		getConnection()->close();
		return;
	}

	addLogLine(LOGTYPE_EVENT, "sending HELLO");
	if(OutputMessage_ptr output = OutputMessagePool::getInstance()->getOutputMessage(this, false))
	{
		TRACK_MESSAGE(output);
		output->put<char>(AP_MSG_HELLO);
		output->put<uint32_t>(1); //version
		output->putString("OTADMIN");

		output->put<uint16_t>(Admin::getInstance()->getPolicy()); //security policy
		output->put<uint32_t>(Admin::getInstance()->getOptions()); //protocol options(encryption, ...)
		OutputMessagePool::getInstance()->send(output);
	}

	m_lastCommand = time(NULL);
	m_state = ENCRYPTION_NO_SET;
}
Exemple #8
0
// 使用UDP广播发送信息
void Widget::sendMessage(MessageType type, QString serverAddress)
{
    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);
    QString localHostName = QHostInfo::localHostName();
    QString address = getIP();
    out << type << getUserName() << localHostName;

    switch(type)
    {
    case Message :
        if (ui->messageTextEdit->toPlainText() == "") {
            QMessageBox::warning(0,tr("警告"),tr("发送内容不能为空"),QMessageBox::Ok);
            return;
        }
        out << address << getMessage();
        ui->messageBrowser->verticalScrollBar()
                ->setValue(ui->messageBrowser->verticalScrollBar()->maximum());
        break;

    case NewParticipant :
        out << address;
        break;

    case ParticipantLeft :
        break;

    case FileName : {
        int row = ui->userTableWidget->currentRow();
        QString clientAddress = ui->userTableWidget->item(row, 2)->text();
        out << address << clientAddress << fileName;
        break;
    }

    case Refuse :
        out << serverAddress;
        break;
    }
    udpSocket->writeDatagram(data,data.length(),QHostAddress::Broadcast, port);
}
void WifiConnetionEspAT::begin(){
	tcpTimeout.enable();
	statusTimeout.enable();
	memset(ipaddress, 0, 15);

	if((_mode == WIFI_AP || _mode == WIFI_AP_STA) && !softAPEnabled /* => Avoid duplicate config*/ ){
		softAP(Config.moduleName, ""); // no password
	}

	bool status = ESP->enableMUX();

#if DEBUG_SETUP
	Logger.debug("MUX", (status ? "OK" : "FAIL")); // FIXME: use F("...") to reduce memory.
#endif

	status = ESP->startTCPServer(DEFAULT_SERVER_PORT);

#if DEBUG_SETUP
	Logger.debug("TCP", (status ? "OK" : "FAIL")); // FIXME: use F("...") to reduce memory.
#endif

	if(status) ESP->setTCPServerTimeout(20000);

	if(status){
		_statusTcp = WL_CONNECTED;
		delay(500);
		getIP(); // required.
		Logger.debug("IP", ipaddress);
		ESP->registerUDP(DISCOVERY_ID, "", DISCOVERY_PORT); // enable discovery port
	}else{
		_statusTcp = WL_CONNECT_FAILED;
	}

	DeviceConnection::begin();

#if DEBUG_SETUP
	Logger.debug("Begin", (status ? "OK" : "FAIL")); // FIXME: use F("...") to reduce memory.
#endif

}
Exemple #10
0
static VOID CmdStartComSpec32(VOID)
{
    DWORD Result;

    // TODO: improve: this code has strong similarities with the
    // 'default' case of DosCreateProcess and with the 'case 0x08'.

    CHAR CmdLine[sizeof("cmd.exe") + 1] = "";

    /* Spawn a user-defined 32-bit command preprocessor */

    // FIXME: Use COMSPEC env var!!
    strcpy(CmdLine, "cmd.exe");

    DPRINT1("CMD Run 32-bit Command Interpreter '%s'\n", CmdLine);

    /*
     * No need to prepare the stack for DosStartComSpec since we won't start it.
     */
    Result = DosStartProcess32(CmdLine, CmdLine,
                               SEG_OFF_TO_PTR(getES(), 0) /*Environment*/,
                               MAKELONG(getIP(), getCS()) /*ReturnAddress*/,
                               FALSE);
    if (Result != ERROR_SUCCESS)
    {
        DosDisplayMessage("Failed to start 32-bit Command Interpreter '%s'. Error: %u\n", CmdLine, Result);
        setCF(0);
        setAL((UCHAR)Result);
    }
    else
    {
        DosDisplayMessage("32-bit Command Interpreter '%s' started successfully.\n", CmdLine);
#ifndef STANDALONE
        setCF(Repeat); // Set CF if we need to start a 16-bit process
#else
        setCF(0);
#endif
    }
}
/*	Opens tcp server on port.
*	Sets connection mode to multiple.
*/
bool ArduEsp8266::openServer(int port){
	if( setMode(ESP8266_CON_MODE_MULTI) ){
		// wait for ip
		int vErrors = 0;
		String vIP = "";
		while( vErrors < _ESP8266_WAIT_ERROR_MAX ){
			vIP = getIP();
			if( vIP.length() == 0 || vIP.compareTo(ESP8266_NO_IP) == 0 ){
				vErrors++;
				delay(_ESP8266_WAIT_ERROR_DELAY);
			} else {
				break;
			}
		}
	
		// open server
		writeCommandSet( _EPS8266_SERVER_MODE, "1," + String(port) );
		if( read().endsWith(_ESP8266_OK) )
			return true;
	}
	return false;
}
Exemple #12
0
void Client::sendCredentials()
{
	if (!credentialsSent)
	{
		credentialsSent = true;

		new QListWidgetItem("-> Sending Credentials...", ui.messageList);
		ui.messageList->scrollToBottom();

		QByteArray block;
		QDataStream out(&block, QIODevice::WriteOnly);
		out.setVersion(QDataStream::Qt_4_0);

		QString command = "_USR_";
		QString username = promptConnect->usernameEdit->text();
		out << command;
		out << username;
		tcpSocket->write(block);

		setWindowTitle("Chat - " + promptConnect->usernameEdit->text() + " on " + getIP());
	}
}
void Widget::sndMsg(MsgType type, QString srvaddr)
{
    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);
    QString address = getIP();
    out << type << getUsr();

    switch(type)
    {
    case Msg :
        if (ui->msgTxtEdit->toPlainText() == "") {
            QMessageBox::warning(0,tr("警告"),tr("发送内容不能为空"),QMessageBox::Ok);
            return;
        }
        out << address << getMsg();
        ui->msgBrowser->verticalScrollBar()->setValue(ui->msgBrowser->verticalScrollBar()->maximum());
        break;

    case UsrEnter :
        out << address;
        break;

    case UsrLeft :
        break;

    case FileName : {
        int row = ui->usrTblWidget->currentRow();
        QString clntaddr = ui->usrTblWidget->item(row, 1)->text();
        out << address << clntaddr << fileName;
        break;
    }

    case Refuse :
        out << srvaddr;
        break;
    }
    udpSocket->writeDatagram(data,data.length(),QHostAddress::Broadcast, port);
}
int main(int argc, char *argv[]){

	if(argc==2) {
		int correctSyntax=checkSyntax(argv[1]);
		if(correctSyntax){
			printf("Sintaxe correcta\n");

			char *user,*password,*host,*urlpath,*ip;
			int ret,sock1fd,pasvPort,sock2fd;

			user=ALLOCSTRING;
			password=ALLOCSTRING;
			host=ALLOCSTRING;
			urlpath=ALLOCSTRING;
			ip=ALLOCSTRING;

			ret = parseParams(argv[1],user,password,host,urlpath);
			getIP(host,ip);

			sock1fd=createSocket(ip,FTPPORT);
			if(ret == 0)
				loginUserPass(sock1fd,user,password);
			else if(ret == 1)
				loginUser(sock1fd,user);
			else if(ret == 2)
				loginUserPass(sock1fd,"anonymous","foo");
			pasvPort = enterPassiveMode(sock1fd);
			sock2fd = createSocket(ip,pasvPort);
			download(sock1fd,sock2fd,urlpath);
			close(sock1fd);
			close(sock2fd);
		}
		else printf("Sintaxe errada!\n");

	}
	else return -1;
	return 0;
}
Exemple #15
0
/*-----------------------------------------------------------------------------*/
int main(int argc, char *argv[]) {

        Input input = validateInput(argc, argv);
	printf("awget:\n\tRequest: %s\n\t", input.URL);

	char ** fileLines = readFile(input.filename);	

	printf("chainlist is\n\t");
        for(int j = 1; fileLines[j] != NULL; j++) {
	    printf("%s\n\t", fileLines[j]);
	}

	Packet * aPacket = buildPacket(fileLines, input.URL);

	int randStepNum = getRandStepNum(aPacket->chainFile[0]); //Get random stepping stone number
	
	char * steppingStone = fileLines[randStepNum]; //Get random stepping stone

	printf("next SS is %s\n\t", steppingStone);

	//Connect to stepping stone
        int socketfd = setupSocket(getIP(steppingStone), atoi(getPort(steppingStone)));

	//Remove stepping stone from file
	removeSS(randStepNum, aPacket); 

	//Write to stepping stone
	socketfd = writeSocket(socketfd, aPacket);

	printf("waiting for file...\n..\n");	

	//Read the data
	char *filename = getFilename(input.URL);
	makeFile(socketfd, filename);
	printf("\tReceived file <%s>\n\tGoodbye!\n", filename);
	close(socketfd);
        free (aPacket);
}
int main(int argc, char **argv) {
	pthread_t tid;	
	int listenid, connfd;

	ssize_t n;
	// socklen_t len;
	struct sockaddr_in servaddr;

	init();
	userAccount.clear();
	accountUser.clear();

	system("mkdir Folder_server");
	chdir("Folder_server");
	// server filelist
	// initServerFilelist();

	userAccount.clear();
	accountUser.clear();
	SERV_PORT=argc>1?atoi(argv[1]):7122;
	// TCP 
	TCPlisten(listenid, connfd, servaddr, SERV_PORT);
	
	signal(SIGCHLD, sig_chld);/* must call waitpid() */
	while(1){
		ClientSock * clientSock; 
		clientSock = (ClientSock*)malloc(sizeof(ClientSock));
		socklen_t clilen = sizeof(clientSock->addr);
		clientSock->connfd = accept(listenid, (struct sockaddr*)&(clientSock->addr), &clilen);
		printf("TCP connect from IP %s (port %d)\n", getIP(clientSock->addr), getPort(clientSock->addr));
		pthread_create(&tid, NULL, &run, (void *)clientSock);
	}


	sqlite3_close(db);

	return 0;
}
int main() {
    init();
    while (1) {
        getTime();
        getSleep();
        getBattery();
        getIP();
        getDisk();
        s = getMasterStatus();

        sprintf(bar, "  %ld%c | %s | %s %d%% | %s | %s%s | %d-%02d-%02d %02d:%02d:%02d",
                remaining, unit,
                IPString,
                batteryIcon(), level,
                timeout ? " true" : " false",
                volIcon(), !s.status ? "Muted" : s.percent,
                1900 + date->tm_year, date->tm_mon + 1, date->tm_mday, date->tm_hour, date->tm_min, date->tm_sec);

        XStoreName(dpy, root, bar);
        nanosleep(&sleepval, NULL);
    }
    destroy();
}
Exemple #18
0
/* cerca  <REF=mhttp://130.136.2.34:9876/piri/picchio> */
static int isREF(char *buf, int i, int *plenparsed, int len, char *objectURL){

	int ris;
	char temppath[MAXLENREQ];
#define REFMHTTP "REF=mhttp://"

	if( ((strlen(REFMHTTP)) +1 /*nomefile almeno 1 char*/ +1 /* il > */ ) > (len-i) ) {
		/* formato errato */
		return(-1);
	}
	if( strncmp(REFMHTTP,buf+i,strlen(REFMHTTP))==0 ) {

		int port;
		struct in_addr inaddr;

		int len1=i+strlen(REFMHTTP);
		ris=getIP(buf,len,&len1,&inaddr);
		if(ris!=1) return(ris);
		ris=getDuePunti(buf,len,&len1);
		if(ris!=1) return(ris);
		ris=getPort(buf,len,&len1,&port);
		if(ris!=1) return(ris);
		ris=getSlash(buf,len,&len1);
		if(ris!=1) return(ris);
		ris=getPathAndMAGGIORE(buf,len,&len1,temppath);
		if(ris!=1) return(ris);

		sprintf(objectURL,"mhttp://%s:%i/%s",inet_ntoa(inaddr),port,temppath);
		*plenparsed=len1;
		return(1);
	}
	else {
		/* NON e' un REF */
		return(-1);
	}

}
Exemple #19
0
void ProtocolManager::onRecvFirstMessage(NetworkMessage&)
{
	m_state = NO_CONNECTED;
	if(g_config.getString(ConfigManager::MANAGER_PASSWORD).empty())
	{
		addLogLine(LOGTYPE_WARNING, "Connection attempt on disabled protocol");
		getConnection()->close();
		return;
	}

	if(!Manager::getInstance()->allow(getIP()))
	{
		addLogLine(LOGTYPE_WARNING, "IP not allowed");
		getConnection()->close();
		return;
	}

	if(!Manager::getInstance()->addConnection(this))
	{
		addLogLine(LOGTYPE_WARNING, "Cannot add more connections");
		getConnection()->close();
		return;
	}

	if(NetworkMessage_ptr msg = getOutputBuffer())
	{
		TRACK_MESSAGE(msg);
		msg->put<char>(MP_MSG_HELLO);

		msg->put<uint32_t>(1); //version
		msg->putString("TFMANAGER");
	}

	m_lastCommand = time(NULL);
	m_state = NO_LOGGED_IN;
}
Exemple #20
0
//有文件需要接收//收到发送文件的请求信息,对应的处理函数
void Widget::hasPendingFile(QString localHostName, QString serverAddress, QString clientAddress, QString fileName)
{
    if(clientAddress == getIP())
    {
        int btn = QMessageBox::information(this, tr("接受文件"), tr("来自%1(%2)的文件:%3,是否接收?")\
                           .arg(localHostName).arg(serverAddress).arg(fileName), QMessageBox::Yes, QMessageBox::No);
        if(btn == QMessageBox::Yes)
        {
            QString name = QFileDialog::getSaveFileName(0, tr("保存文件"), fileName);//提供对话框,允许用户选择文件或目录的类 静态函数
            if(!name.isEmpty())
            {
                fileReceiver *receiver = new fileReceiver(this);
                receiver->setFileName(name);
                receiver->setHostAddress(QHostAddress(serverAddress));
                receiver->move(500, 200);
                receiver->show();
            }
        }
        else
        {
            sendMessage(Refuse, serverAddress);
        }
    }
}
Exemple #21
0
//startBtn按键按下触发的槽函数
void MainWindow::listenBtnClicked()
{
    //调试信息:测试工具类(静态成员类)
    // qDebug()<<"test "<<Utils::SET_TEMP_MAX;
    //调试信息
    //qDebug()<<"listenBtnClicked ok";
    //初始化清空infoPad
    ui->infoPad->clear();
    //向infopad追加状态信息
    ui->infoPad->append("SER:start listen ...");
    //tcpServer开始在本地8888端口监听
    tcpServer->listen(QHostAddress::Any,8888);
    //判断tcpServer是否开始监听
    if(tcpServer->isListening())
    {
        //调试信息
        //qDebug()<<getIP();
        //向infopad追加状态信息
       ui->infoPad->append(getIP()+" listen on 8888");
       //更新按键状态
       ui->startBtn->setEnabled(false);
       ui->stopBtn->setEnabled(true);
    }
}
Exemple #22
0
 void refreshDebugInfo() {
     ipaddress = getIP();
     networkName = getWirelessNetwork();
 }
Exemple #23
0
/*=========================================================================
* FUNCTION:      tVM_Execute
* TYPE:          public interface
* OVERVIEW:      execute a basic function
* INTERFACE:
*   parameters:  
*   returns:     
*                the result of the basic function
*=======================================================================*/
int tVM_Execute()
{
	int       running = 1;
	u8        bytecode;
	u8        type;
	u8        ac_flag;
	s32       integer;
	s32       stackindex,index;
	tVMValue  value1,value2,value3;
	tVMValue  retValue;// = (tVMValue*)mem_alloc(sizeof(tVMValue));

	/* initialize the running Stack FP */
	setFP(FirstFP);

	/* seek to the entry function */
	setFI(0);
	
	/* initialize the code reader */
	tVM_InitializeCodeReader();

	/* execute the byte codes in loop  */
	while(running)
	{
		bytecode = ReadCode();
		switch(bytecode)
		{
		case C_NOP:
			break;
		case C_CONST:
			{
				ReadVMValue(&value1);
				PushVMValue(&value1);
				break;
			}
		case C_LOAD:
			{
				ac_flag  =ReadAccessFlag();
				if(ac_flag == ACCESS_FLAG_GLOBAL)
					stackindex = ReadIndex();
				else
					stackindex = ReadIndex() + getFP();
				LoadVMValue(stackindex,&value1);
				PushVMValue(&value1);
				break;
			}
		case C_STORE:
			{
				ac_flag  =ReadAccessFlag();
				if(ac_flag == ACCESS_FLAG_GLOBAL)
					stackindex = ReadIndex();
				else
					stackindex = ReadIndex() + getFP();
				PopVMValue(&value1); /* pop the source value */
				StoreVMValue(stackindex,&value1);
				break;
			}
		case C_HEAP_LOAD:
			{
				type = ReadDataType();

				PopVMValue(&value2); /* Pop Addr */
				PopVMValue(&value1); /* Pop Base */	
				tVMValue_HeapLoad(value1.value.ptr_val+value2.value.int_val,type,&value3); /* load the heap memory */
				PushVMValue(&value3); /* push the loaded value */
				break;
			}
		case C_HEAP_STORE:
			{
				ptr32 addr;
				type = ReadDataType();

				PopVMValue(&value3); /* Pop Addr */
				PopVMValue(&value2); /* Pop Base */
				PopVMValue(&value1); /* Pop Value */
				addr = (ptr32)(value2.value.ptr_val + value3.value.int_val);
				if(value1.type != type)
				{
					tVMValue_ConvertType(&value1,type);
				}
				tVMValue_HeapStore(addr,&value1);
				break;
			}
		case C_FORCE_LOAD:
			{
				ac_flag  =ReadAccessFlag();
				if(ac_flag == ACCESS_FLAG_GLOBAL)
					stackindex = ReadIndex();
				else
					stackindex = ReadIndex() + getFP();
				type = ReadDataType();

				ForceLoadVMValue(stackindex,type,&value1);
				PushVMValue(&value1);
				break;
			}
		case C_ALLOC:
			{
				PopVMValue(&value1);
				value2.type = PtrType;
				value2.value.ptr_val = (ptr32)mem_alloc(value1.value.int_val);
				memset(value2.value.ptr_val,0,value1.value.int_val);
				PushVMValue(&value2);
				break;
			}
		case C_ALLOC_ARRAY:
			{
				s32   i;
				s32  dimension; 
				s32* index_ranges;
				
				dimension = ReadInteger();
				if(dimension < 1)
					break;
				index_ranges = (s32*)mem_alloc(sizeof(s32)*dimension);
				for(i=0;i<dimension;i++)
				{
					PopVMValue(&value1);
					index_ranges[dimension-i-1] = value1.value.int_val;
				}
				value1.type = PtrType;
				value1.value.ptr_val = tVMValue_HeapAllocMultiArray(dimension,index_ranges,0);
				PushVMValue(&value1);
				
				mem_free(index_ranges);
				break;
			}
		case C_FREE:
			{
				PopVMValue(&value1);
				if(value1.value.ptr_val != NULL)
					mem_free(value1.value.ptr_val);
				break;
			}
		case C_FREE_ARRAY:
			{
				break;
			}
		case C_PUSH:
			{
				value1.type  = ReadDataType();
				value1.value.int_val = 0;
				PushVMValue(&value1);
				break;
			}
		case C_POP:
			{
				s32 i;
				integer = ReadInteger();
				for(i=0;i<integer;i++)
				{
					PopVMValue(&value1);
					tVMValue_FreeSelf(&value1);
				}
				break;
			}
		case C_POP_RESTOP:
			{
				s32 i;
				integer = ReadInteger();
				PopVMValue(&value2); /* reserve top value */
				for(i=0;i<integer;i++)
				{
					PopVMValue(&value1);
					tVMValue_FreeSelf(&value1);
				}
				PushVMValue(&value2); /* push back top value */
				break;
			}
		case C_CONVERT:
			{
				u8 type = (u8)ReadDataType();
				PopVMValue(&value1);
				tVMValue_ConvertType(&value1,type);
				PushVMValue(&value1);
				break;
			}
		case C_ADD:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_Add(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_SUB:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_Sub(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_MUL:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_Mul(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_DIV:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_Div(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_MOD:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_Mod(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_OPP:
			{
				PopVMValue(&value1);
				tVMValue_Opp(&value1,&value2);
				PushVMValue(&value2);

				tVMValue_FreeSelf(&value1);
				break;
			}
		case C_AND:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_AND(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_OR:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_OR(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_EQ:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_EQ(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_NOT_EQ:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_NOTEQ(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_LT:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_LT(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_LG:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_LG(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_LT_EQ:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_LTEQ(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_LG_EQ:
			{
				PopVMValue(&value2);
				PopVMValue(&value1);
				tVMValue_LGEQ(&value1,&value2,&value3);
				PushVMValue(&value3);

				tVMValue_FreeSelf(&value1);
				tVMValue_FreeSelf(&value2);
				break;
			}
		case C_FJP:
			{
				s32 size = ReadIndex();
				PopVMValue(&value1);
				if(value1.value.int_val == 0) /* if it is false */
					addIP(size);
				break;
			}
		case C_TJP:
			{
				s32 size = ReadIndex();
				PopVMValue(&value1);
				if(value1.value.int_val != 0) /* if it is true */
					addIP(size);
				break;
			}
		case C_JMP:
			{
				s32 size = ReadIndex();
				addIP(size);
				break;
			}
		case C_CALL:
			{
				/* read function name */
				integer = ReadIndex();
				/* push the stack frame */
				PushInteger(getIP());
				PushInteger(getFI());
				PushInteger(getFP());
				/* goto the call function code */
				tVM_ReleaseCodeReader();
				setFI(integer);
				tVM_InitializeCodeReader();
				/* set new FP,RP */
				setFP(getSP());
				break;
			}
		case C_INVOKE:
			{
				/* read function name */
				index = ReadIndex();
				/* execute the native function */
				tNativeFunction_Invoke(index);
				break;
			}
		case C_RET:
			{
				u32 param_bytes = ReadIndex();

				/* get the result of the function */
				retValue.type = NullType;
				PopVMValue(&retValue); 
				
				/* if this is the start function,then exit the loop */
				if(getFP() == FirstFP)
				{
					running = 0; /* set flag to stop while */
					break;
				}

				/* restore last stack frame and return to last function code */
				tVM_ReleaseCodeReader();
				PopInteger(integer);
				setFP(integer); 
				PopInteger(integer);
				setFI(integer);
				tVM_InitializeCodeReader();
				PopInteger(integer);
				setIP(integer);
				
				/* pop the old parameters */
				PopBytes(param_bytes);

				/* push back result of last function */
				PushVMValue(&retValue);
				break;
			}
		}
	}

	/* close the code reader */
	tVM_ReleaseCodeReader();
	return 1;
}
Exemple #24
0
int main(int argc, char *argv[]) {
	fd_set rset;
	struct timeval timeout;
	char * IP; //IP address of socket
	char * PTY; //Pseudo Terminal Name
	
	unsigned char cBuff[BUFFER];
	//char c[BUFFER];
	
	int csize;
	int pty = -1; //Pseudo Terminal File Descriptor
	int sockfd1, sockfd2 = -1;
	int x;
	int args = 0;
	int tmp;
	
	char argSerial[] = "-serial";
	char argHelp[]   = "-help";
	char argPort[]   = "-port";
	char argPTY[]    = "-pty";
	char argStrip[]  = "-strip";
	char argBaud[]   = "-baud";
	char argDebug[]  = "-debug";
	
	int SOCKET_PORT, BAUD, STRIP, DEBUG = 0;
	char SERIAL[100];


	for (x = 0; x < argc; x++){//Cycle through the command line arguments
		if (!strcmp(argSerial,argv[x])) {//Look for the -serial option
			strcpy(SERIAL,argv[x+1]); //Copies the port to SERIAL
			if(BAUD>0){ //If the baud option has been passed
				sockfd2 = connectSerial(SERIAL, BAUD); //Open the serial port and return the file descriptor
				if (sockfd2 < 0) {
					close(sockfd2);
					if(sockfd1>=0)
						close(sockfd1);
					if(pty>=0)
						close(pty);
					return -1;
				}else{
					args+=3;
				}
			}else{ 
				args+=3;
			}
		}
		else if (!strcmp(argPort,argv[x])) {  //Look for -port  option
			SOCKET_PORT = atoi(argv[x+1]); //Convert string address into int
			sockfd1 = makeSocket(SOCKET_PORT);  //Make the socket and return the file descriptor
			if (sockfd1 < 0) {
				close(sockfd1);
				if(sockfd2>=0)
					close(sockfd2);
				if(pty>=0)
					close(pty);
				return -1;
			}else{
				args+=5;
			}
		}
		else if (!strcmp(argPTY,argv[x])) {  //Look for -pty  option
			pty = pseudoTY(&PTY);
			if(pty<0){
				close(pty);
				if(sockfd2>=0)
					close(sockfd2);
				if(sockfd1>=0)
					close(sockfd1);
				return -1;
			}else{
				args+=7;
			}
		}
		else if (!strcmp(argBaud,argv[x])) { //Look for -baud option
			tmp = atoi(argv[x+1]); //Convert string baud rate to int
			switch (tmp) { //Make sure the value is supported
				case 115200:
					BAUD = B115200;
					break;
				case 38400:
					BAUD = B38400;
					break;
				case 19200:
					BAUD = B19200;
					break;
				case 9600:
					BAUD = B9600;
					break;
				default:
					printf("ERROR!: Unknown baud rate.\n");
					return -1;
					break;
			}
			
			if(strlen(SERIAL) != 0) //If we got the tag for a serial port, create the serial port
				sockfd2 = connectSerial(SERIAL, BAUD); //Open the serial port and return the file descriptor
			args+=1;
		}
		else if ( (args != 9 &&  args != 11 && args !=16 && x == argc-1) || (!strcmp(argHelp,argv[x]))) { 
                        //If not enough arguments, output usage directions and exit
			// Serial <=> Socket  w/ baud  = 9
			// Serial <=> PTY  w/ baud = 11
			// Serial <=> Socket, Serial <=> PTY w/ baud = 16
			printf("--------------------------------------\n");
			printf("------------ SerialDaemon ------------\n");
			printf("--------------------------------------\n");
			printf("Usage:");
			printf("\t./serialdaemon [options] [arguments]\n");
			printf("\t-serial [Use to indicate which serial port to connect to. E.G. /dev/ttyS1]\n");
			printf("\t-port   [Use to indicate which TCP/IP port of the local host to connect to. E.G. 5000]\n");
			printf("\t-pty    [Create a pseudo terminal for the serial port to connect to.]\n");
			printf("\t-baud   [Serial port baudrate.]\n");
			printf("\t\t115200\n");
			printf("\t\t38400\n");
			printf("\t\t19200\n");
			printf("\t\t9600\n");
			printf("\t-strip  [Strip the endline character and replace with a space.]\n");
			printf("\t-debug  [Set the verbose debug mode for help.]\n");
			printf("\t-help   [For this help screen.]\n\n");
			printf("Example Usage:\t./serialdaemon -serial /dev/ttyS1 -baud 115200 -pty -port 5000\n");
			printf("This will link ttyS1 to localhost:5000 and ttyS1 to a pseudo terminal.  The connection to ttyS1 will have a baudrate of 115200.\n");
			return -1;
		}
		else if (!strcmp(argStrip,argv[x])){STRIP = 1;}  //Look for the -strip option
		else if (!strcmp(argDebug,argv[x])){DEBUG = 1; printf ("DEBUG: debug mode on!\n");}  //Look for the -debug option
		
	}
	
	signal(SIGINT, controlC);	// catch ^C so we can close sockets & exit cleanly

	IP = getIP(); //Get the local IP address

	if(args == 9)//Serial to Socket
		printf("Connections made: \n\t\t\t%s < = > http://%s:%d\n",SERIAL,IP,SOCKET_PORT); 
	else if(args == 11)//Serial to PTY
		printf("Connections made: \n\t\t\t%s < = > %s\n",SERIAL,PTY); 
	else if(args == 16)//Serial to PTY  &  Serial to Socket
		printf("Connections made: \n\t\t\t%s < = > http://%s:%d\n\t\t\t%s < = > %s\n",SERIAL,IP,SOCKET_PORT,SERIAL,PTY); 

	sd1 = waitOnSocket(sockfd1); //Check for a connection to the socket

	while(1){
		/* Select on sockets */
		if(sd1 > 0){ //If There is a connection to the socket then potentially set up these connections:  tty < = > socket and tty < = > pty
			if (DEBUG)
				printf("DEBUG: New client socket opened.\n");
			if (sd1 < 0) { //Error in creating connection
				close(sd1); 
				return -1;
			}
			sd2 = sockfd2; //File descriptor of the serial port
			if (sd2 < 0) { //If an error
				close(sd1);
				close(sd2); 
				return -1;
			}
			FD_ZERO(&rset); //Clear file descriptors in the rset set
			while(1) {
				FD_SET(sd1,&rset);//Set sd1 in rset
				FD_SET(sd2,&rset);//Set sd2 in rset
				if(pty!=-1) {//If a virtual port is requested
					FD_SET(pty,&rset);
					select(max(max(sd1,sd2),pty)+1,&rset,NULL,NULL,NULL); 
                                       //Select specifies which of the file descriptors is ready for reading or writing
				}else {
					select(max(sd1,sd2)+1,&rset,NULL,NULL,NULL); 
					//Select tests file descriptors in the range of 0 to nfds-1 or in this case 0 to max(sd1,sd2).
				}
				//----------------Check The Socket For Data ------------------
				if (FD_ISSET(sd1,&rset)) {  //Is there stuff to read from the socket
					/* There's stuff to read */
					if ((csize= read(sd1, &cBuff, BUFFER)) >= 1) { //If there's something worth reading
						if (STRIP==1) { //Remove endline characters and replace with space
							for(x = 0 ; x < csize; x++) {
								if (cBuff[x] == '\n' ) {
									cBuff[x] = ' ';
									if (DEBUG)
										printf ("DEBUG: **STRIPPED**\n");
								}
							}
						}
						if (DEBUG) {
							//Replace &cBuff and cBuff with c
							//cBuff[csize] = '\0';
							printf("\nDEBUG: %s <== ",SERIAL);
							for(x=0; x<csize;x++){
								printf("%#.2x ",cBuff[x]);
							}
							printf("\n");
						}
						write(sd2, &cBuff, csize);//Write data from sd1 to sd2
					}else{break;}// Failed  -- port closed
				}
				
				//----------------Check The Serial Port For Data ------------------
				if (FD_ISSET(sd2,&rset)) {//Is there stuff to read from the serial port
					if ((csize = read(sd2, &cBuff, BUFFER)) >= 1) {//If there is something worth reading from the serial port
						write(sd1, &cBuff, csize); //Write this data to the socket
						if(pty != -1){write(pty,&cBuff,csize);} //Write this data to the virtual com port
						if (DEBUG) {
							//Replace &cBuff and cBuff with c
							//cBuff[csize] = '\0';
							printf("DEBUG: http://%s:%d <== ",IP,SOCKET_PORT);
							for(x=0; x<csize;x++){
								printf("%#.2x ",cBuff[x]);
							}
							printf("\n");
							
							if(pty !=-1){
								printf("DEBUG: %s <== ",PTY);
								for(x=0; x<csize;x++){
									printf("%#.2x ",cBuff[x]);
								}
								printf("\n");
							}
						}
					}
					//else break;           /* Failed */
				}
				//----------------Check The PTY Port For Data ------------------
				if (pty != -1 && FD_ISSET(pty,&rset)) {//If there is a virtual port, and data is ready, write data from 
					if ((csize = read(pty, &cBuff, BUFFER)) >= 1) {//If there is something worth reading from the serial port
						write(sd2, &cBuff, csize); //Write this data to the serial port
						if (DEBUG) {
							//Replace &cBuff and cBuff with c
							//cBuff[csize] = '\0';
							printf("\nDEBUG: %s <== ",SERIAL);
							for(x=0; x<csize;x++){
								printf("%#.2x ",cBuff[x]);
							}
							printf("\n");
						}
					}
					//else break;           /* Failed */
				}
			}
			printf("Restarting\n");
			close(sd1);/* clean up */
			sd1 = waitOnSocket(sockfd1); //Check for a connection to the socket

		}else if(pty != -1) {//Else, if there is a virtual port then tty <=> pty
			sd2 = sockfd2; //File descriptor of the serial port
			if (sd2 < 0) { //If an error
				close(sd2); 
				close(pty);
				return -1;
			}
			FD_ZERO(&rset); //Clear file descriptors in the rset set
			while(1) {
				FD_SET(sd2,&rset);//Set sd2 in rset
				FD_SET(pty,&rset);//Set pty in rset
				sd1 = waitOnSocket(sockfd1);
				if(sd1 >= 0){break;} //Check for socket connection, if there is, break out of this loop.
				select(max(sd2,pty)+1,&rset,NULL,NULL,NULL); // Specifies which of the file descriptors is ready for reading or writing
				if (FD_ISSET(pty,&rset)) { //If there is a virtual port, and data is ready, write data from 
					if ((csize = read(pty, &cBuff, BUFFER)) >= 1) {//If there is something worth reading from the serial port
						write(sd2, &cBuff, csize); //Write this data to the serial port
						if (DEBUG) {
							//Replace &cBuff and cBuff with c
							//cBuff[csize] = '\0';
							printf("\nDEBUG: %s <== ",SERIAL);
							for(x=0; x<csize;x++){
								printf("%#.2x ",cBuff[x]);
							}
							printf("\n");
						}
					}
					//else break;           // Failed 
				}


				if (FD_ISSET(sd2,&rset)) {//Is there stuff to read from the serial port				  
					if ((csize = read(sd2, &cBuff, BUFFER)) >= 1) { //If there is something worth reading from the serial port
						write(pty, &cBuff, csize); //Write this data to the virtual com port
						if (DEBUG) {
							//Replace &cBuff and cBuff with c
							//cBuff[csize] = '\0';
							printf("DEBUG: %s <== ",PTY);
							for(x=0; x<csize;x++){
								printf("%#.2x ",cBuff[x]);
							}
							printf("\n");
						}
					}
					//else break;           /* Failed */
				}

			}
		}else {//If there isn't a pty, then check the socket for a connection once a second
			if(DEBUG)
				printf("\rWaiting on the socket connection...\n");
			sd1 = waitOnSocket(sockfd1); //Check for a connection to the socket
			sleep(1);
		}
	}
}
void ProtocolSpectator::onRecvFirstMessage(NetworkMessage& msg)
{
	if (g_game.getGameState() == GAME_STATE_SHUTDOWN) {
		getConnection()->close();
		return;
	}

	operatingSystem = (OperatingSystem_t)msg.get<uint16_t>();
	version = msg.get<uint16_t>();

	msg.skipBytes(7); // U32 clientVersion, U8 clientType

	if (!RSA_decrypt(msg)) {
		getConnection()->close();
		return;
	}

	uint32_t key[4];
	key[0] = msg.get<uint32_t>();
	key[1] = msg.get<uint32_t>();
	key[2] = msg.get<uint32_t>();
	key[3] = msg.get<uint32_t>();
	enableXTEAEncryption();
	setXTEAKey(key);

	if (operatingSystem >= CLIENTOS_OTCLIENT_LINUX) {
		NetworkMessage opcodeMessage;
		opcodeMessage.addByte(0x32);
		opcodeMessage.addByte(0x00);
		opcodeMessage.add<uint16_t>(0x00);
		writeToOutputBuffer(opcodeMessage);
	}

	msg.skipBytes(1); // gamemaster flag
	std::string password = msg.getString();
	std::string characterName = msg.getString();
	

	uint32_t timeStamp = msg.get<uint32_t>();
	uint8_t randNumber = msg.getByte();
	if (m_challengeTimestamp != timeStamp || m_challengeRandom != randNumber) {
		getConnection()->close();
		return;
	}
	auto dispatchDisconnectClient = [this](const std::string& msg) {
		g_dispatcher.addTask(createTask(
					std::bind(&ProtocolSpectator::disconnectSpectator, this, msg)));
	};
	if (version < CLIENT_VERSION_MIN || version > CLIENT_VERSION_MAX) {
		
		dispatchDisconnectClient("Only clients with protocol " CLIENT_VERSION_STR " allowed!");
		return;
	}

	if (g_game.getGameState() == GAME_STATE_STARTUP) {
		dispatchDisconnectClient("Gameworld is starting up. Please wait.");
		return;
	}

	if (g_game.getGameState() == GAME_STATE_MAINTAIN) {
		dispatchDisconnectClient("Gameworld is under maintenance. Please re-connect in a while.");
		return;
	}
	
	BanInfo banInfo;
	if (IOBan::isIpBanned(getIP(), banInfo)) {
		if (banInfo.reason.empty()) {
			banInfo.reason = "(none)";
		}

		std::ostringstream ss;
		ss << "Your IP has been banned until " << formatDateShort(banInfo.expiresAt) << " by " << banInfo.bannedBy << ".\n\nReason specified:\n" << banInfo.reason;
		dispatchDisconnectClient(ss.str());
		return;
	}
	password.erase(password.begin());
	g_dispatcher.addTask(createTask(std::bind(&ProtocolSpectator::login, this, characterName, password)));
}
Exemple #26
0
/*
 * Function: do_stateful_checks(FTP_SESSION *Session, Packet *p,
 *                            FTP_CLIENT_REQ *req, int rsp_code)
 *
 * Purpose: Handle stateful checks and state updates for FTP response
 *          packets.
 *
 * Arguments: Session        => Pointer to session info
 *            p              => Pointer to the current packet struct
 *            req            => Pointer to current response from packet
 *                              (this function may be called multiple
 *                              times for pipelined requests).
 *            rsp_code       => Integer response value for server response
 *
 * Returns: int => return code indicating error or success
 *
 */
int do_stateful_checks(FTP_SESSION *Session, SFSnortPacket *p,
                       FTP_CLIENT_REQ *req, int rsp_code)
{
    int iRet = FTPP_SUCCESS;
    if (Session->server_conf->data_chan)
    {
        if (rsp_code == 226)
        {
            /* Just ignore this code -- end of transfer...
             * If we saw all the other dat for this channel
             * Session->data_chan_state should be NO_STATE. */
        }
        else if (Session->data_chan_state & DATA_CHAN_PASV_CMD_ISSUED)
        {
            if (ftp_cmd_pipe_index == Session->data_chan_index)
            {
                if (Session->data_xfer_index == -1)
                    ftp_cmd_pipe_index = 0;
                Session->data_chan_index = -1;
                if (rsp_code == 227)
                {
                    u_int32_t ip=0;
                    u_int16_t port=0;
                    char *ip_begin = req->param_begin;
                    Session->data_chan_state &= ~DATA_CHAN_PASV_CMD_ISSUED;
                    Session->data_chan_state |= DATA_CHAN_PASV_CMD_ACCEPT;
                    Session->data_chan_index = -1;
                    /* Interpret response message to identify the
                     * Server IP/Port.  Server response is inside
                     * a pair of ()s.  Find the left (, and use same
                     * means to find IP/Port as is done for the PORT
                     * command. */
                    while ((*ip_begin != '(') &&
                           (ip_begin < req->param_end))
                    {
                        ip_begin++;
                    }

                    if (ip_begin < req->param_end)
                    {
                        ip_begin++;
                        iRet = getIP(&ip_begin, req->param_end, ')',
                                     &ip, &port);
                        if (iRet == FTPP_SUCCESS)
                        {
                            Session->serverIP = htonl(ip);
                            Session->serverPort = port;
                            Session->clientIP = 0;
                            Session->clientPort = 0;
                        }
                    }
                    else
                    {
                        iRet = FTPP_MALFORMED_FTP_RESPONSE;
                    }
                }
                else
                {
                    Session->data_chan_index = -1;
                    Session->data_chan_state &= ~DATA_CHAN_PASV_CMD_ISSUED;
                }
            }
        }
        else if (Session->data_chan_state & DATA_CHAN_PORT_CMD_ISSUED)
        {
            if (ftp_cmd_pipe_index == Session->data_chan_index)
            {
                if (Session->data_xfer_index == -1)
                    ftp_cmd_pipe_index = 0;
                Session->data_chan_index = -1;
                if (rsp_code == 200)
                {
                    Session->data_chan_state &= ~DATA_CHAN_PORT_CMD_ISSUED;
                    Session->data_chan_state |= DATA_CHAN_PORT_CMD_ACCEPT;
                    Session->data_chan_index = -1;
                }
                else if (ftp_cmd_pipe_index == Session->data_chan_index)
                {
                    Session->data_chan_index = -1;
                    Session->data_chan_state &= ~DATA_CHAN_PORT_CMD_ISSUED;
                }
            }
        }
        else if (Session->data_chan_state & DATA_CHAN_XFER_CMD_ISSUED)
        {
            if (ftp_cmd_pipe_index == Session->data_xfer_index)
            {
                if (Session->data_chan_index == -1)
                    ftp_cmd_pipe_index = 0;
                Session->data_xfer_index = -1;
                if ((rsp_code == 150) || (rsp_code == 125))
                {
                    struct in_addr client, server;
                    Session->data_chan_state &= ~DATA_CHAN_XFER_CMD_ISSUED;
                    Session->data_chan_state = DATA_CHAN_XFER_STARTED;
                    if (Session->serverIP == 0)
                    {
                        /* This means we're not in passive mode. */
                        /* Server is listening/sending from its own IP,
                         * FTP Port -1 */ 
                        /* Client IP, Port specified via PORT command */
                        Session->serverIP = p->ip4_header->source.s_addr;
                    
                        /* Can't necessarily guarantee this, especially
                         * in the case of a proxy'd connection where the
                         * data channel might not be on port 20 (or server
                         * port-1).  Comment it out for now.
                         */
                        /*
                        Session->serverPort = ntohs(p->tcph->th_sport) -1;
                        */
                    }
                    if (Session->clientIP == 0)
                    {
                        /* This means we're in passive mode. */
                        /* Server info is known. */
                        /* Client IP is known from response packet, but
                         * port is unknown */
                        Session->clientIP = p->ip4_header->destination.s_addr;
                    }
                    client.s_addr = Session->clientIP;
                    server.s_addr = Session->serverIP;

                    if (Session->server_conf->data_chan)
                    {
                        /* Call into Streams to mark data channel as something
                         * to ignore. */
                        _dpd.streamAPI->ignore_session(Session->clientIP,
                                Session->clientPort, Session->serverIP,
                                Session->serverPort,
                                p->ip4_header->proto, SSN_DIR_BOTH,
                                0 /* Not permanent */ );
                    }
                }
                /* Clear the session info for next transfer -->
                 * reset host/port */
                Session->serverIP = Session->clientIP = 0;
                Session->serverPort = Session->clientPort = 0;

                Session->data_chan_state = NO_STATE;
            }
        }
    } /* if (Session->server_conf->data_chan) */

    if (Session->global_conf->encrypted.on)
    {
        switch(Session->encr_state)
        {
        case AUTH_TLS_CMD_ISSUED:
            if (rsp_code == 234)
            {
                /* Could check that response msg includes "TLS" */
                Session->encr_state = AUTH_TLS_ENCRYPTED;
                if (Session->global_conf->encrypted.alert)
                {
                    /* Alert on encrypted channel */
                    ftp_eo_event_log(Session, FTP_EO_ENCRYPTED,
                        NULL, NULL);
                }
                DEBUG_WRAP(_dpd.debugMsg(DEBUG_FTPTELNET, 
                    "FTP stream is now TLS encrypted\n"););
            }
            break;
        case AUTH_SSL_CMD_ISSUED:
            if (rsp_code == 234)
            {
                /* Could check that response msg includes "SSL" */
                Session->encr_state = AUTH_SSL_ENCRYPTED;
                if (Session->global_conf->encrypted.alert)
                {
                    /* Alert on encrypted channel */
                    ftp_eo_event_log(Session, FTP_EO_ENCRYPTED,
                        NULL, NULL);
                }
                DEBUG_WRAP(_dpd.debugMsg(DEBUG_FTPTELNET, 
                    "FTP stream is now SSL encrypted\n"););
Exemple #27
0
/*
 * Function: validate_param(
 *                            Packet *p
 *                            char *param
 *                            char *end
 *                            FTP_PARAM_FMT *param_format,
 *                            FTP_SESSION *Session)
 *
 * Purpose: Validates the current parameter against the format
 *          specified.
 *
 * Arguments: p              => Pointer to the current packet
 *            params_begin   => Pointer to beginning of parameters
 *            params_end     => End of params buffer
 *            param_format   => Parameter format specifier for this command
 *            Session        => Pointer to the session info
 *
 * Returns: int => return code indicating error or success
 *
 */
int validate_param(SFSnortPacket *p,
                char *param,
                char *end,
                FTP_PARAM_FMT *ThisFmt,
                FTP_SESSION *Session)
{
    int iRet;
    char *this_param = param;

    if (param > end)
        return FTPP_ALERT;

    switch (ThisFmt->type)
    {
    case e_head:
        /* shouldn't get here, but just in case */
        break;
    case e_unrestricted:
        /* strings/filenames only occur as the last param,
         * so move to the end of the param buffer. */
        {
            do
            {
                this_param++;
            }
            while (this_param < end);
        }
        break;
    case e_strformat:
        /* Check for 2 % signs within the parameter for an FTP command
         * 2 % signs is the magic number per existing rules (24 Sep 2004)
         */
#define MAX_PERCENT_SIGNS 2
        {
            int numPercents = 0;
            do
            {
                if (*this_param == '%')
                {
                    numPercents++;
                    if (numPercents >= MAX_PERCENT_SIGNS)
                    {
                        break;
                    }
                }
                this_param++;
            }
            while ((this_param < end) &&
                   (*this_param != ' '));

            if (numPercents >= MAX_PERCENT_SIGNS)
            {
                /* Alert on string format attack in parameter */
                ftp_eo_event_log(Session, FTP_EO_PARAMETER_STR_FORMAT,
                    NULL, NULL);
                return FTPP_ALERTED;
            }
        }
        break;
    case e_int:
        /* check that this_param is all digits up to next space */
        {
            do
            {
                if (!isdigit(*this_param))
                {
                    /* Alert on non-digit */
                    return FTPP_INVALID_PARAM;
                }
                this_param++;
            }
            while ((this_param < end) && (*this_param != ' ') );
        }
        break;
    case e_number:
        /* check that this_param is all digits up to next space
         * and value is between 1 & 255 */
        {
            int iValue = 0;
            do
            {
                if (!isdigit(*this_param))
                {
                    /* Alert on non-digit */
                    return FTPP_INVALID_PARAM;
                }
                iValue = iValue * 10 + (*this_param - '0');
                this_param++;
            }
            while ((this_param < end) && (*this_param != ' ') );

            if ((iValue > 255) || (iValue == 0))
                return FTPP_INVALID_PARAM;
        }
        break;
    case e_char:
        /* check that this_param is one of chars specified */
        {
            int bitNum = (*this_param & 0x1f);
            if (!isalpha(*this_param))
            {
                /* Alert on non-char */
                return FTPP_INVALID_PARAM;
            }
            else
            {
                if (!(ThisFmt->format.chars_allowed & (1 << (bitNum-1))) )
                {
                    /* Alert on unexpected char */
                    return FTPP_INVALID_PARAM;
                }
            }
            this_param++; /* should be a space */
        }
        break;
    case e_date:
        /* check that this_param conforms to date specified */
        {
            char *tmp_ch = this_param;
            iRet = validate_date_format(ThisFmt->format.date_fmt, &tmp_ch);
            if (iRet != FTPP_SUCCESS)
            {
                /* Alert invalid date */
                return FTPP_INVALID_PARAM;
            }
            if (!isspace(*tmp_ch))
            {
                /* Alert invalid date -- didn't make it to end of parameter.
                Overflow attempt? */
                return FTPP_INVALID_PARAM;
            }
            this_param = tmp_ch;
        }
        break;
    case e_host_port:
        /* check that this_param is #,#,#,#,#,# */
        {
            u_int32_t ip;
            u_int16_t port=0;
            int iRet;
            iRet = getIP(&this_param, end, ' ', &ip, &port);
            switch (iRet)
            {
            case FTPP_NON_DIGIT:
                /* Alert on non-digit */
                return FTPP_INVALID_PARAM;
                break;
            case FTPP_INVALID_ARG:
                /* Alert on number > 255 */
                return FTPP_INVALID_PARAM;
                break;
            case FTPP_MALFORMED_IP_PORT:
                /* Alert on malformed host-port */
                return FTPP_INVALID_PARAM;
                break;
            }

            if ((Session->client_conf->bounce.on) &&
                (Session->client_conf->bounce.alert))
            {
                if (ip != ntohl(p->ip4_header->source.s_addr))
                {
                    int alert = 1;
                    char *ipPtr = (char *)&ip;
                    FTP_BOUNCE_TO *BounceTo = ftp_bounce_lookup_find(
                        Session->client_conf->bounce_lookup, ipPtr, 4, &iRet);
                    if (BounceTo)
                    {
                        if (BounceTo->portlo)
                        {
                            if (BounceTo->porthi)
                            {
                                if ((port >= BounceTo->portlo) &&
                                    (port <= BounceTo->porthi))
                                    alert = 0;
                            }
                            else
                            {
                                if (port == BounceTo->portlo)
                                    alert = 0;
                            }
                        }
                    }
                    
                    /* Alert on invalid IP address for PORT */
                    if (alert)
                    {
                        ftp_eo_event_log(Session, FTP_EO_BOUNCE, NULL, NULL);
                        /* Return here -- because we will likely want to
                         * inspect the data traffic over a bounced data
                         * connection */
                        return FTPP_PORT_ATTACK;
                    }
                }
            }

            Session->clientIP = htonl(ip);
            Session->clientPort = port;
            Session->data_chan_state |= DATA_CHAN_PORT_CMD_ISSUED;
            if (Session->data_chan_state & DATA_CHAN_PASV_CMD_ISSUED)
            {
                /*
                 * If there was a PORT command previously in
                 * a series of pipelined requests, this
                 * cancels it.
                 */
                Session->data_chan_state &= ~DATA_CHAN_PASV_CMD_ISSUED;
            }

            Session->serverIP = 0;
            Session->serverPort = 0;
        }
        break;
    }

    ThisFmt->next_param = this_param;

    return FTPP_SUCCESS;
}
Exemple #28
0
bool NetworkDevice::init() {
    debugAssert(! initialized);

    // Used for combining the MAC and ip information
    typedef Table<std::string, EthernetAdapter> AdapterTable;

    AdapterTable table;

    // Head of a linked list of network interfaces on this machine
    ifaddrs* ifap = NULL;

    int r = getifaddrs(&ifap);

    if (r != 0) {
        logPrintf("ERROR: getifaddrs returned %d\n", r);
        return false;
    }

    ifaddrs* current = ifap;

    if (current == NULL) {
        logPrintf("WARNING: No network interfaces found\n");
        EthernetAdapter a;
        a.name = "fallback";
        a.hostname = "localhost";
        a.ip = (127 << 24) | 1;       
        a.broadcast = 0xFFFFFFFF;
        a.subnet    = 0x000000FF;
        addAdapter(a);

    } else {

        while (current != NULL) {

            bool up = (current->ifa_flags & IFF_UP); 
            bool loopback = (current->ifa_flags & IFF_LOOPBACK);

            if (! up || loopback) {
                // Skip this adapter; it is offline or is a loopback
                current = current->ifa_next;
                continue;
            }

            if (! table.containsKey(current->ifa_name)) {
                EthernetAdapter a;
                a.name = current->ifa_name;
                table.set(a.name, a);
            }

            // This adapter must exist because it was created above
            EthernetAdapter& adapter = table[current->ifa_name];

            const sockaddr_in* interfaceAddress = castToIP4(current->ifa_addr);
            const sockaddr_in* broadcastAddress = castToIP4(current->ifa_dstaddr);
            const sockaddr_in* subnetMask       = castToIP4(current->ifa_netmask);

            uint32 ip = getIP(interfaceAddress);
            uint32 ba = getIP(broadcastAddress);
            uint32 sn = getIP(subnetMask);
            
            if (ip != 0) {
                adapter.ip = ip;
            }

            if (ba != 0) {
                adapter.broadcast = ba;
            }

            if (sn != 0) {
                adapter.subnet = sn;
            }

            uint8_t* MAC = NULL;
            // Extract MAC address
            if ((current->ifa_addr != NULL) && (current->ifa_addr->sa_family == AF_LINK)) {
#               ifdef __linux__
                {
                    // Linux
                    struct ifreq ifr;
                    
                    int fd = socket(AF_INET, SOCK_DGRAM, 0);
                    
                    ifr.ifr_addr.sa_family = AF_INET;
                    strcpy(ifr.ifr_name, current->ifa_name);
                    ioctl(fd, SIOCGIFHWADDR, &ifr);
                    close(fd);
                    
                    MAC = reinterpret_cast<uint8_t*>(ifr.ifr_hwaddr.sa_data);
                }
#               else
                {
                    // The MAC address and the interfaceAddress come in as
                    // different interfaces with the same name.
                    
                    // Posix/FreeBSD/Mac OS
                    sockaddr_dl* sdl = (struct sockaddr_dl *)current->ifa_addr;
                    MAC = reinterpret_cast<uint8_t*>(LLADDR(sdl));
                }
#               endif
                
                // See if there was a MAC address
                if (MAC != NULL) {
                    bool anyNonZero = false;
                    for (int i = 0; i < 6; ++i) {
                        anyNonZero = anyNonZero || (MAC[i] != 0);
                    }
                    if (anyNonZero) {
                        System::memcpy(adapter.mac, MAC, 6);
                    }
                }
            }
     
            current = current->ifa_next;
        }

        freeifaddrs(ifap);
        ifap = NULL;
    }

    // Extract all interesting adapters from the table
    for (AdapterTable::Iterator it = table.begin(); it.isValid(); ++it) {
        const EthernetAdapter& adapter = it->value;
        
        // Only add adapters that have IP addresses
        if (adapter.ip != 0) {
            addAdapter(adapter);
        } else {
            logPrintf("NetworkDevice: Ignored adapter %s because ip = 0\n", adapter.name.c_str());
        }
    }

    initialized = true;

    return true;
}
void *run(void *arg){
	pthread_detach(pthread_self());
	vector<string>tok;
	Account currentUser;
	int n;
	char  mesg[MAXLINE], sendline[MAXLINE], recvline[MAXLINE];
	ClientSock clientSock=*(ClientSock*)arg;
	int connfd=clientSock.connfd;
	struct sockaddr_in cliaddr=clientSock.addr;
	free(arg);

	while((n=receive(connfd, recvline)) >0) {

		recvline[n]=0; /* null terminate */
		printf("from client IP %s port %d\n", getIP(cliaddr), getPort(cliaddr));
		printf("connfd = %d\n", connfd);
		tok.clear();
		tok=parse(recvline);
		

		if(userAccount.find(User(getIP(cliaddr), getPort(cliaddr), cliaddr))==userAccount.end()){
			if(tok[0][0]=='R'){
				writeRecv(connfd, recvline, strlen(recvline));// send to client
				//register
				currentUser=Account(tok[1], tok[2]);
				currentUser.state=Normal;
				userAccount[User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd)]=currentUser;
				accountUser[currentUser]=User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd);
				
				if(insertUser(currentUser)){
					puts("register sucess");
					write(connfd, SUCCESS, strlen(SUCCESS));

					// update filelist
					recvFilelist(connfd, currentUser.ID);


				}
				else{
					puts("register fail");

					write(connfd, FAIL, strlen(FAIL));
				}
			}
			else if(tok[0][0]=='L'){
				writeRecv(connfd, recvline, strlen(recvline));// send to client
				if(login(Account(tok[1], tok[2]))){
					currentUser=Account(tok[1], tok[2]);
					currentUser.state=Normal;
					userAccount[User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd)]=currentUser;
					accountUser[currentUser]=User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd);
					puts("login sucess");
					write(connfd, SUCCESS, strlen(SUCCESS));	
					// update filelist
					recvFilelist(connfd, currentUser.ID);

				}
				else{
					puts("login fail");
					write(connfd, FAIL, strlen(FAIL));
				}
			}
		}
		else{ // login already
			currentUser=userAccount[User(getIP(cliaddr), getPort(cliaddr), cliaddr)];
			accountUser[currentUser]=User(getIP(cliaddr), getPort(cliaddr), cliaddr);
			if(currentUser.state==Normal){
				if(tok[0]=="Del"){// delete account
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					puts("Delete account");
					deleteUser(currentUser);// delete in db
					userAccount.erase(User(getIP(cliaddr), getPort(cliaddr), cliaddr));
					accountUser.erase(currentUser);
					
					write(connfd, SUCCESS, strlen(SUCCESS));
				}
				else if(tok[0]=="L"){// logout
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					puts("Logout");
					userAccount.erase(User(getIP(cliaddr), getPort(cliaddr), cliaddr));
					accountUser.erase(currentUser);
					deleteFile(currentUser.ID);
					write(connfd, SUCCESS, strlen(SUCCESS));
				}
			
				//------------------------------------------------
				// show filelist/ show user
				else if(tok[0]=="SU"){// show user
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					writeRecv(connfd, SUCCESS, strlen(SUCCESS));
					sendUser(connfd);
				}
				else if(tok[0]=="SF"){// show filelist
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					writeRecv(connfd, SUCCESS, strlen(SUCCESS));
					showFilelist();
					sendResult(connfd, 2, result);
				}
				//------------------------------------------------
				// upload download
				else if(tok[0]=="D"){// download
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					int numFile=existNumFile(tok[1]);
					printf("number of file = %d\n", numFile);
					
					// total authors
					if(numFile){
						vector<string>author=getFileAuthor();
						writeRecv(connfd, SUCCESS, strlen(SUCCESS));
						string str=toString((int)author.size());
						// how many author
						write(connfd, str.c_str(), str.length());
						// to user A
						recvWrite(connfd, recvline);// tell B connect to "port"
						// to user A
						User userA=accountUser[currentUser];
						for(int i=0;i<author.size();i++){
							cout<<author[i]<<endl;

							
							User userB=accountUser[Account(author[i])];
							
							// user B
							str=string(DOWNLOAD)+" "+userA.IP+" "+recvline+" "+tok[1]+" "+toString(i)+" "+toString((int)author.size());
							write(userB.connfd, str.c_str(), str.length());// tell B :(A's) IP port path idx total

						}

						// update filelist
						puts("update filelist");
						addFile(currentUser.ID, tok[1]);
					}
					else{
						write(connfd, FAIL, strlen(FAIL));
					}
					


				}
				else if(tok[0]=="U"){// upload
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					if(accountUser.find(Account(tok[1]))!=accountUser.end()){
						// to user A
						write(connfd, SUCCESS, strlen(SUCCESS));
						User userA=accountUser[currentUser];
						User userB=accountUser[Account(tok[1])];
						string str;
						// to user A
						recvWrite(connfd, recvline);// tell B connect to "port"
						// user B
						str=string(UPLOAD)+" "+userA.IP+" "+recvline+" "+tok[2];
						write(userB.connfd, str.c_str(), str.length());// tell B :(A's) IP port

						// update B's filelist
						addFile(tok[1], tok[2]);
					}
					else{
						write(connfd, FAIL, strlen(FAIL));
					}
					
				}
				//------------------------------------------------
				else if(tok[0]=="T"){// A tell B
					writeRecv(connfd, recvline, strlen(recvline));// send to client
					if(accountUser.find(Account(tok[1]))!=accountUser.end()){
						currentUser.state=Tell;
						userAccount[User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd)]=currentUser;
						// to user A
						write(connfd, SUCCESS, strlen(SUCCESS));
						User userA=accountUser[currentUser];
						User userB=accountUser[Account(tok[1])];
						Account accountB=userAccount[userB];
						accountB.state=Tell;
						userAccount[userB]=accountB;
						
						string str;
						// to user A
						recvWrite(connfd, recvline);// tell B connect to "port"
						// user B
						printf("user B connfd = %d\n", userB.connfd);
						str=string(TALK)+" "+userA.IP+" "+recvline;
						// write(userB.connfd, TALK, strlen(TALK));
						
						
						write(userB.connfd, str.c_str(), str.length());// tell B :(A's) IP port

						// string str=userB.IP+" "+toString(userB.port);
						// writeWithSleep(connfd, str.c_str(), str.length());

					}
					else{
						write(connfd, FAIL, strlen(FAIL));
					}
					
				}
			
			}
			else if(currentUser.state==Tell){
				if(tok[0]=="EXIT"){
					printf("%s EXIT~\n", currentUser.ID.c_str());
					currentUser.state=Normal;
					userAccount[User(getIP(cliaddr), getPort(cliaddr), cliaddr, connfd)]=currentUser;
				}
				else{
					printf("%s tell~\n", currentUser.ID.c_str());
				}
			}		
		}
		puts(recvline);
		
		
		// write(connfd, recvline, strlen(recvline));
	}
	close(connfd);

	return NULL;
}
Exemple #30
0
/*
 * For Receive Clients Request
 */
int createTCPServer(int port)
{
    int server_s;
	int sock_opt = 1;
	char localIP[IP_LENGTH] = {0};

    server_s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (-1 == server_s) 
    {
		perror("socket:");
		return -1;
    }

    /* server socket is nonblocking */
    if (-1 == set_nonblock_fd(server_s))
    {
    	close(server_s);
    	perror("set_nonblock_fd:");
		return -1;
    }

    /* close server socket on exec so cgi's can't write to it */
    if (-1 == fcntl(server_s, F_SETFD, 1)) 
    {
    	close(server_s);
    	perror("fcntl:");
		return -1;
    }

    /* reuse socket addr */
    if (-1 == setsockopt(server_s, SOL_SOCKET, SO_REUSEADDR, (void *)&sock_opt, sizeof(sock_opt)))
    {
    	close(server_s);
		perror("setsockopt:");
		return -1;
    }

    /* internet family-specific code encapsulated in bind_server()  */

    if (-1 == getIP(ETH_NAME, localIP))
    {
    	close(server_s);
    	printf("[%s][%d] ERROR: get IP addr. \n", __FILE__, __LINE__);
    	return -1;
    }
    
    if (-1 == bindServer(server_s, NULL, port)) 
    {
    	close(server_s);
    	perror("bind:");
		return -1;
    }

    /* listen: large number just in case your kernel is nicely tweaked */
    if (listen(server_s, ONVIF_TCP_MAXCONN) == -1) 
    {
    	close(server_s);
		perror("listen:");
		return -1;
    }

    return server_s;
}