Exemplo n.º 1
0
void start_protocol(const int clientSocket) 
{

	char readBuffer[BUFFERSIZE];
	int readBytes;
	char *cmdString;
	char *ptr;
	char *token;
	char *accessRoute;

	
		cmdString = (char *) calloc(255,1);
		while((readBytes = read(clientSocket,readBuffer,MAXBYTESREAD))>0)
		{
				cmdString = (char *) realloc(cmdString,strlen(cmdString)+readBytes+1);
				strncat(cmdString,readBuffer,readBytes);
				//Read the last 4 characters to determine the EOF
				ptr = cmdString+(strlen(cmdString)-4);
				if(strcmp(ptr,"\r\n\r\n")==0) 
				{	
					*ptr = '\0';
					break;
				}
		}	
			
			debug(4,"<- %s",cmdString);

			token = strtok(cmdString," \t\b");
			debug(4,"%s",token);
			if(strcmp(token,"GET")==0)
			{
				token = strtok(NULL," \t\b");
				if(token == NULL) 
				{
					sendLine(clientSocket, "ERROR ( Acces Route )\r\n\r\n");
				}
				else
				{
					accessRoute = token;
					token = strtok(NULL," \t\b"); 
					if(strcmp(token,"HTTP"))
					{
						doGet(clientSocket,accessRoute);
					}
					else
					{
						sendLine(clientSocket, "Missing Protocol\r\n");
					}
				}
			}
			else
			{
				sendLine(clientSocket, "Unkown command\r\n\r\n");
			}	
			
			if(cmdString != NULL)
				free(cmdString);
	
	
}
Exemplo n.º 2
0
void IRCServer::connectedEvent() {
	resetIRCState();

	// reset reconnection attempts
	connectionAttempt = 1;

	printf("[IRCServer:%p] connectedEvent\n", this);
	status.pushMessage("Connected, identifying to IRC...");

	char buf[2048];

	if (config.password.size() > 0) {
		sprintf(buf, "PASS %s", config.password.c_str());
		sendLine(buf);
	}

	sprintf(buf, "USER %s 0 * :%s\r\nNICK %s",
		config.username.c_str(),
		config.realname.c_str(),
		config.nickname.c_str());

	sendLine(buf);


	// Initialise currentNick with the nick we *think* we have,
	// because FurNet sends us a VERSION request as the very first
	// thing-- before any other commands, including RPL_WELCOME
	strncpy(currentNick, config.nickname.c_str(), sizeof(currentNick));
	currentNick[sizeof(currentNick) - 1] = 0;

	ircStringToLowercase(currentNick, currentNickLower, sizeof(currentNickLower));
}
Exemplo n.º 3
0
/**
 * @brief steps to the next action in the preset simulation sequence
 */
void CommandInterpreter::SendNext(){
	//checking for breakpoints
	for (int i = 0; i < breakPointList.size(); i++){
		if ((commandIndex + runFromAdjust) == breakPointList[i]){
			CommandInterpreter::pausePaintingCommands();
			breakPointList[i] = -50;
			list->item(commandIndex + runFromAdjust)->setTextColor(Qt::black);
			return;
		}
	}

	if (CurrentCommandType == "Line") {
		sendLine(); //Continue an old line command
	} else if (CurrentCommandType == "Solid") {
		sendSolid(); //Continue an old solid command
	} else if (commandIndex >= finishIndex) {
		updateTimer.stop(); //Quit!  We're done
		paused = false;
		stopped = true;
		finished = true;
	} else if (listOfCommandTypes.front() == QString("Line")) {
		CurrentCommandType = *listOfCommandTypes.front();
		sendLine(); //Start a new line command
	} else if (listOfCommandTypes.front() == QString("Solid")) {
		CurrentCommandType = *listOfCommandTypes.front();
		sendSolid(); //Start a new solid command
	}
}
/*****************************************************************************
*
* Exosite_Write
*
*  \param  pbuf - string buffer containing data to be sent
*          bufsize - number of bytes to send
*
*  \return 1 success; 0 failure
*
*  \brief  Writes data to Exosite cloud
*
*****************************************************************************/
int
Exosite_Write(char * pbuf, unsigned int bufsize)
{
  int success = 0;
  int http_status = 0;
  char bufCIK[41];
  char strBuf[10];

  if (!exosite_initialized) {
    status_code = EXO_STATUS_INIT;
    return success;
  }

  if (!Exosite_GetCIK(bufCIK))
  {
    return success;
  }


  long sock = connect_to_exosite();
  if (sock < 0) {
    status_code = EXO_STATUS_BAD_TCP;
    return 0;
  }


// This is an example write POST...
//  s.send('POST /onep:v1/stack/alias HTTP/1.1\r\n')
//  s.send('Host: m2.exosite.com\r\n')
//  s.send('X-Exosite-CIK: 5046454a9a1666c3acfae63bc854ec1367167815\r\n')
//  s.send('Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n')
//  s.send('Content-Length: 6\r\n\r\n')
//  s.send('temp=2')

  itoa((int)bufsize, strBuf, 10); //make a string for length

  sendLine(sock, POSTDATA_LINE, "/onep:v1/stack/alias");
  sendLine(sock, HOST_LINE, NULL);
  sendLine(sock, CIK_LINE, bufCIK);
  sendLine(sock, CONTENT_LINE, NULL);
  sendLine(sock, LENGTH_LINE, strBuf);
  exoHAL_SocketSend(sock, pbuf, bufsize);

  http_status = get_http_status(sock);

  exoHAL_SocketClose(sock);

  if (401 == http_status)
  {
    status_code = EXO_STATUS_NOAUTH;
  }
  if (204 == http_status)
  {
    success = 1;
    status_code = EXO_STATUS_OK;
  }

  return success;
}
Exemplo n.º 5
0
int
Exosite_SyncTime()
{
  char day[11];
  char time[9];
  int http_status = 0;
  int strLen;
  char *testStr = "GET /ip HTTP/1.1\r\n";
  unsigned char serverAddr[6] = {54, 183, 115, 21, 0, 80};
  char strBuf[RX_SIZE];
  DateTime datetime;

  if (!exosite_initialized)
  {
    return -1;
  }

  long sock = connect_to_exosite_with_server_addr("", serverAddr);
  if (sock < 0)
  {
    return -1;
  }

  exoHAL_SocketSend(sock, testStr, strlen(testStr));
  sendLine(sock, HOST_LINE, NULL);
  sendLine(sock, ACCEPT_LINE, "\r\n");

  http_status = get_http_status(sock);
  if (200 != http_status)
     return -1;

  strLen = exoHAL_SocketRecv(sock, strBuf, RX_SIZE);

  exoHAL_SocketClose(sock);

  if(strLen <= 0)
    return -1;
     
  if(parse_datetime(strBuf, strLen, &datetime) < 0)
    return -1;

  sprintf(day, "%s/%02d/%s", datetime.dayStr, month_to_num(datetime.monStr), datetime.yearStr);
  sprintf(time, "%s:%s:%s", datetime.hourStr, datetime.minStr, datetime.secStr);

  if(AtLibGs_SetTime(day, time) != ATLIBGS_MSG_ID_OK)
    return -1;

  return 0;
}
Exemplo n.º 6
0
void Worker::commandReceived(const QByteArray command)
{
    if (m_currentState == StoppedState)
    {
        return;
    }

    if (command == "ok")
    {
        m_waitingCount--;
        emit currentLineChanged(m_currentLine - m_waitingCount + 1);

        if (m_waitingCount < m_bufferSize)
        {
            if ((m_currentLine < m_commandList.size())
                    && (m_currentState == RunningState)) // a new command needs to be sent
            {
                sendLine();
            }
        }

        if ((m_waitingCount == 0)
                && (m_currentLine == m_commandList.size())) // we have finished
        {
            stopQueue();
            m_currentState = StoppedState;
            emit currentStateChanged(m_currentState);
            emit finished();
        }
    }
}
Exemplo n.º 7
0
void Smtp::readLiner()
{
    if (isconnect)
    {
        QTextCodec *codecx;
        codecx = QTextCodec::codecForMib(106);
        t = new QTextStream( smtpsocket );
        t->setCodec(codecx);

        int loops = 0;
        while (!t->atEnd())
        {
            loops++;
            response = t->readLine();
        }
        if (response.size() > 0)
        {
            RemoteServerName = response;
            mailstatus = response.left(3);
            if (mailstatus == "220")
            {
                response="";
                linesend = 1;
                emit sendLine();
            }
        }
        else
        {
            emit errorCloseAll();
        }
    }
}
Exemplo n.º 8
0
//ответ на команду RETR
void MailHandler::getMessage(SOCKET client_socket, string req, User& curUser){
	string request = req;
	string answer;
	int cnt = 0, cap = 0, num=0;
	cnt = curUser.lettersCount();
	if (req.size() > 5){
		string temp = request.substr(5, 1);
		try{
			num = stoi(temp, nullptr);			
		}
		catch (invalid_argument){
			cout << "Error! Invalid argument!" << endl;
			answer.append("-ERR Invalid argument!");
		}
		if (num <= cnt && num > 0) {			
			Letter let = Letter();
			let = curUser.getLetter(num);
			if (let.getMarker() == false){
				cout << "number is " << num << endl;
				answer.append(responses[1] + to_string(curUser.letterSize(num)) + " octets\r\n");
				answer.append("From: " + let.getFrom());
				answer.append("\r\nTo: " + let.getTo());
				answer.append("\r\nSubject: " + let.getSubject());
				answer.append("\r\nData: " + let.getData() + "\r\n.");
			}
			else answer.append("-ERR message " + to_string(num) + " was deleted\r\n");			
		}
		else answer.append(responses[0]);
	}
	else answer.append(responses[0]);
	sendLine(client_socket, answer.c_str());
}
Exemplo n.º 9
0
bool Protocol::accely(int idx, double val){
	//Set the desired accelaration in x axis to the specified value in hovertank mode.
	char char_buff[20];
	sprintf(char_buff, "accely %d %f", idx, val);
	sendLine(char_buff);
	readAck();
	return readBool();
}
Exemplo n.º 10
0
//Funcion GET
void doGet(const int clientSocket, const char  baseDir[], const char *fileName) {
	
	char *writeBuffer = (char *) malloc(256);
	u_int writeBytes = 0;
	char *readBuffer;
	u_int readBytes = 0;
	char *fullPath;
	int fd;
	int localError;
	struct stat fs;
	
	fullPath = (char *) malloc(strlen(baseDir)+strlen(fileName)+1);
	strcpy(fullPath,baseDir);
	strcat(fullPath,fileName);
	
	fd = open(fullPath,O_RDONLY);
	free(fullPath);
	
	if(fd == -1) {
		//Debug del archivo
		localError = errno;
		debug(1,"Can't open Requested File (%s)",strerror(localError));
		sprintf(writeBuffer,"NOT_FOUND %s\r\n\r\n",fileName);
		sendLine(clientSocket, writeBuffer);
		free(writeBuffer);
		return;
	} 

	sendLine(clientSocket, "OK\r\n");
	fstat(fd, &fs);
	sprintf(writeBuffer,"Size: %u\r\n",(u_int)fs.st_size);
	sendLine(clientSocket,writeBuffer);
	sendLine(clientSocket,"\r\n");	
	
	readBuffer = (char *) malloc(102400);	
	while((readBytes = read(fd,readBuffer,102400))>0) {
	writeBytes = 0;
	while(writeBytes < readBytes) {
	writeBytes += write(clientSocket,readBuffer+writeBytes,readBytes-writeBytes);
		}
	}
	
	free(readBuffer);
	free(writeBuffer);
	close(fd);
}
Exemplo n.º 11
0
bool Protocol::angvel(int idx, double val){
	//Set the desired angular velocity to the specified value.
	char char_buff[20];
	sprintf(char_buff, "angvel %d %f", idx, val);
	sendLine(char_buff);
	readAck();
	return readBool();
}
Exemplo n.º 12
0
//ответ на команду STAT
void MailHandler::status(SOCKET client_socket, User& curUser){
	int cnt = 0, cap = 0;
	cnt = curUser.lettersCount();
	cap = curUser.overallSize();
	string answer;
	answer.append(responses[1]+to_string(cnt)+" "+to_string(cap)+"\r\n");
	sendLine(client_socket, answer.c_str());
}
Exemplo n.º 13
0
bool Protocol::speed(int idx, double val){
	//Set the desired speed to the specified value.
	char char_buff[20];
	sprintf(char_buff, "speed %d %f", idx, val);
	sendLine(char_buff);
	readAck();
	return readBool();
}
Exemplo n.º 14
0
//Tank commands
bool Protocol::shoot(int idx){
	//Perform a shoot request.
	char char_buff[20];
	sprintf(char_buff, "shoot %d", idx);
	sendLine(char_buff);
	readAck();
	return readBool();
}
Exemplo n.º 15
0
void doGet(const int clientSocket, const char  baseDir[])
{
	char *writeBuffer = (char *) malloc(256);
	u_int writeBytes = 0;
	char *readBuffer;
	u_int readBytes = 0;
	int fd;
	int localError;
	struct stat fs;
	debug(1,"%s",baseDir);
	
	
	if(strcmp(baseDir,"/download")==0)
	{
		fd = open(FILEPATH,O_RDONLY);
		debug(1,"%s","Si se encontro la palabra download");
		sendLine(clientSocket, "HTTP/1.1 200 OK\r\n");	
		sprintf(writeBuffer,"Content-Disposition: attachment; filename=%s\r\n",OUTNAME);
		sendLine(clientSocket,writeBuffer);
		writeBuffer = (char *) malloc(256);
		fstat(fd, &fs);
		sprintf(writeBuffer,"Content-Length: %u\r\n",(u_int)fs.st_size);
		sendLine(clientSocket,writeBuffer);
	}
	
	else
	{
		fd = open(NOTFOUND,O_RDONLY);
		debug(1,"%s","Abriendo error 404");
		sendLine(clientSocket, "HTTP/1.1 240 No Content\r\n");	
		sendLine(clientSocket,"Content-Type: text/html\r\n");
	}
	
	if(fd == -1)
	{	
		localError = errno;
		debug(1,"Can't open Requested File (%s)",strerror(localError));
		sprintf(writeBuffer,"NOT_FOUND file\r\n\r\n");
		sendLine(clientSocket, writeBuffer);
		free(writeBuffer);
		return;
	}
	
	sendLine(clientSocket,"\r\n");
	readBuffer = (char *) malloc(BUFFERSIZE);
	
	while((readBytes = read(fd,readBuffer,BUFFERSIZE))>0) 
	{
		writeBytes = 0;
		while(writeBytes < readBytes) 
		{
			writeBytes += write(clientSocket,readBuffer+writeBytes,readBytes-writeBytes);
		}
	}
	
	free(readBuffer);
	free(writeBuffer);
	close(fd);
	
}
Exemplo n.º 16
0
ResultStatus Worker::execute(const string& line, vector<string>& result, time_t timeout)
{
	WriteLocker locker(&mutex);

	result.clear();

	if (status != WORKER_RUNNING) {
		return RESULT_FAILED;
	}

	Context::getContext()->check();

	if (numFailures >= maxFailures) {
		// SVS failed to execute the required command, has to be recovered manually by administrator
		throw WorkerException("SVS script error, can't recover, contact administrator.", false);
	}

	boost::shared_ptr<PaloSession> s = PaloSession::findSession(session, false);
	s->setWorkerContext(Context::getContext());

	while (true) {
		bool ok = sendLine(line, timeout);

		if (!ok) {
			if (timeout == 0) {
				ok = restart();
			}

			if (!ok) {
				s->setWorkerContext(0);
				return RESULT_FAILED;
			}

			continue;
		}

		ok = readResult(timeout);

		if (!ok) {
			if (timeout == 0) {
				ok = restart();
			}

			if (!ok) {
				s->setWorkerContext(0);
				return RESULT_FAILED;
			}

			continue;
		}

		result = this->result;

		s->setWorkerContext(0);
		return RESULT_OK;
	}
}
Exemplo n.º 17
0
//Funcion protocolo
void start_protocol(const int socket,const char *remoteFilename,const char *localFilename) {

	char writeBuffer[1024];
	char readBuffer[10240];
	int readBytes;
	char *cmdString;
	char *freeCmdString;
	char *ptr;
	char *token;

	sprintf(writeBuffer,"GET %s\r\n\r\n",remoteFilename);
	sendLine(socket,writeBuffer);
	
	//LEEMOS LA RESPUESTA AL GET
	cmdString = (char *) malloc(254);
	while((readBytes = read(socket,readBuffer,1))>0) {
		cmdString = (char *) realloc(cmdString,strlen(cmdString)+readBytes+1);
		strncat(cmdString,readBuffer,readBytes);
		ptr = cmdString+(strlen(cmdString)-4);
		if(strcmp(ptr,"\r\n\r\n")==0) {
			*ptr = '\0';
			break;
		}
	}
	
	freeCmdString = cmdString;
	
	debug(4,"Recibimos: %s\n",cmdString);
	token = strsep(&cmdString,"\r");
	cmdString++; // Eliminamos el \n de igual manera.
	
	if(strcmp(token,"NOT_FOUND")==0) {
		debug(1,"ERROR: Archivo no encontrado(%s)",token);
		return;
	} else if(strcmp(token,"OK")==0) {
		token = strstr(cmdString,":");
		doGet(socket,localFilename,strtol(token+2,NULL,10));
	} else {
		debug(1,"ERROR UNKOWN ANSWER (%s)",token);
	}
	
	sendLine(socket,"QUIT\r\n\r\n");
	free(freeCmdString);
}
Exemplo n.º 18
0
//Funcion Protocolo
void start_protocol(const int clientSocket,const char baseDir[]) {

	char readBuffer[1024];
	int readBytes;
	char *cmdString;
	char *ptr;
	char *token;

	while(true) {
		cmdString = (char *) calloc(255,1);
		while((readBytes = read(clientSocket,readBuffer,1))>0) {
			cmdString = (char *) realloc(cmdString,strlen(cmdString)+readBytes+1);
			strncat(cmdString,readBuffer,readBytes);
			ptr = cmdString+(strlen(cmdString)-4);
			if(strcmp(ptr,"\r\n\r\n")==0) {
				*ptr = '\0';
				break;
			}
		}

		debug(4,"<- %s",cmdString);

		token = strtok(cmdString," \t\b");
		if(strcmp(token,"GET")==0) {
			token = strtok(NULL," \t\b");
			if(token == NULL) {
				sendLine(clientSocket, "ERROR ( Missing FileName )\r\n\r\n");
			} else {
				doGet(clientSocket,baseDir, token);
			}
		} else if(strcmp(token,"LIST")==0) {
			doList(clientSocket,baseDir);
		} else if(strcmp(token,"QUIT")==0) {
					break;
		} else {
			sendLine(clientSocket, "UNKOWN METHOD\r\n\r\n");
		}

		if(cmdString != NULL) free(cmdString);
	}

}
Exemplo n.º 19
0
void beginProtocol(const int socket,const char *remoteFilename,const char *localFilename) {

	char writeBuffer[1024];
	char readBuffer[10240];
	int readBytes;
	char *commandStr;
	//char *freecommandStr;
	char *end;
	char *token;
	//Para iniciar, mandamos un GET con el archivo especificado en remoteFilename
	sprintf(writeBuffer,"GET %s\r\n\r\n",remoteFilename);
	sendLine(socket,writeBuffer);
	
	//leemos la respuesta al GET
	commandStr = (char *) calloc(1,254);
	while((readBytes = read(socket,readBuffer,1))>0) { //leemos byte por byte readBuffer
		commandStr = (char *) realloc(commandStr,strlen(commandStr)+readBytes+1);
		strncat(commandStr,readBuffer,readBytes); //concatenamos en commandStr lo que se haya leido
		end = commandStr+(strlen(commandStr)-4);//colocamos end 4 bytes antes del final de commandStr
		if(strcmp(end,"\r\n\r\n")==0) {//si hemos llegado al final del bufer:
			*end = '\0'; //Colocamos un caracter nulo
			break; //Solo entonces dejamos de leer
		}
	}
	
	//freecommandStr = commandStr;
	//debug(4,"Received: %s\n",commandStr); //Imprimimos el header que recibimos
	token = strsep(&commandStr,"\r"); // = strtok()
	commandStr++; 
	if(strcmp(token,"NOT_FOUND")==0) { //Si el server envió un header NOT_FOUND...
		fprintf(stderr,"ERROR: File not Found (%s)",token); //mostramos el error en pantalla
		return;
	} else if(strcmp(token,"OK")==0) { //Si se recibió un OK del server, 
		token = strstr(commandStr,":"); //separa hasta los : y en los sig. 2 Bytes... 
		processGET(socket,localFilename,strtol(token+2,NULL,10)); //Convierte la cadena a un long
	} else {
		fprintf(stderr,"ERROR UNKOWN ANSWER (%s)",token);
	}
	
	sendLine(socket,"QUIT\r\n\r\n");
	//free(freecommandStr);
}
Exemplo n.º 20
0
void		Input::keyPressEvent(QKeyEvent *e)
{
	int	 key = e->key();

	if (key == Qt::Key_Return)
		emit sendLine(text());
	else if (key == Qt::Key_Up || key == Qt::Key_Down)
		emit browseHist(text(), key);
	else
		QLineEdit::keyPressEvent(e);
}
Exemplo n.º 21
0
//Funcion List
void doList(const int clientSocket, const char baseDir[]) {
	
	DIR *dir;
	struct dirent *ent;
	char writeBuffer[1024];

	if ((dir = opendir (baseDir)) != NULL) {
		while ((ent = readdir (dir)) != NULL) {
			if(strcmp(ent->d_name,".")==0) continue;
			if(strcmp(ent->d_name,"..")==0) continue;			
			sprintf(writeBuffer,"%s\r\n",ent->d_name);
			sendLine(clientSocket,writeBuffer);
		}
		closedir (dir);
		sendLine(clientSocket,"\r\n");
	} else {
		sendLine(clientSocket, "INTENRAL ERROR ( Can't open directory)\r\n\r\n");
	}
		
}
Exemplo n.º 22
0
//процесс аутентификации
int MailHandler::authentication(SOCKET client_socket, int& status, User& curUser){
	char buf[SIZE_OF_BUF] = "/0";
	int len = recvLine(client_socket, buf, SIZE_OF_BUF);
	cout << buf << endl;  
	int res=-1;
	if (len>0){
		string request = string(buf);
		string pass;		
		request.erase(request.size() - 1);
		cout << "request = " << request << endl;
		if (request.find("USER") != string::npos){
			request.erase(request.begin(), request.begin() + 5);
			int check = checkUser(request);
			if (check == -1){
				sendLine(client_socket, responses[4]);//ответ о том, что нет такого пользователя
				res = -1;
			}
			else{
				sendLine(client_socket, responses[3]);//ответ о том, что есть такой пользователь
				len = recvLine(client_socket, buf, SIZE_OF_BUF);
				if (len>0){
					pass = string(buf);
					pass.erase(pass.size() - 1);
					if (pass.find("PASS") != string::npos){
						pass.erase(pass.begin(), pass.begin() + 5);
						if (users[check].getPass() == pass){
							curUser = users[check];
							curUser.setOnline();
							string answer = connectedUser(curUser);
							sendLine(client_socket, answer.c_str());//правильный пароль
							res = 1;
						}
						else {
							sendLine(client_socket, responses[6]);//неправильный пароль
							res = -1;
						}
					}
					else if (pass.find("QUIT") != string::npos){
						status = 0;
						sendLine(client_socket, responses[16]);
					}
				}
			}
		}
		else if (request.find("QUIT") != string::npos){
			status = 0;
			sendLine(client_socket, responses[16]);
		}
		else if (request.find("CAPA") != string::npos){
			string ans;
			ans.append("+OK Capability list follows\r\nUSER\r\n.");
			sendLine(client_socket, ans.c_str());
		}
	}
	return res;
}
Exemplo n.º 23
0
DWORD WINAPI MailHandler::clientHandler(LPVOID param){
	SOCKET client_socket = (SOCKET)param;
	if (client_socket == INVALID_SOCKET) {
		printf("error with accept socket. GetLasterror= %d\n", GetLastError());
		return 1003;
	}
	char buf[SIZE_OF_BUF] = "/0";
	//пересылаем код ответа номер 2 (ready) через клиентский сокет
	//POP3-коды ответа отпределены в Responses.h как двумерный массив
	sendLine(client_socket, responses[2]);
	//значение устанавливается в answer(), по смыслу номер состояния после принятия запроса
	int status = 1;
	int aut;
	User curUs = User();
	do {
		aut = authentication(client_socket, status, curUs); //процесс аутентификации клиента
		if (status == 0) {
			break;//Проверка на выход
		}
	} while (aut < 0);
	while (recvLine(client_socket, buf, SIZE_OF_BUF)>0){
		//принимаем сообщения размером buf из клиентского сокета, записываем в buf
		//int len = recvLine(client_socket, buf, SIZE_OF_BUF);
		//if (len > 2){
			//если что-то пришло, отвечаем
			string request=string(buf);
			request.erase(request.size() - 1);
			if (request.find("STAT") != string::npos){
				MailHandler::status(client_socket, curUs);
			}
			else if (request.find("LIST") != string::npos){
				getList(client_socket, request, curUs);
			}
			else if (request.find("RETR") != string::npos){
				getMessage(client_socket, request, curUs);
			}
			else if (request.find("DELE") != string::npos){
				deleteMessage(client_socket, request, curUs);
			}
			else if (request.find("RSET") != string::npos){
				reset(client_socket, curUs);
			}
			else if (request.find("QUIT") != string::npos){
				disconnect(client_socket, status, curUs);
			}
		//}
		if (status == 0) {
			break;//Проверка на выход
		}
	}
	closesocket(client_socket);
}
Exemplo n.º 24
0
//сброс установленных флагов на удаление
void MailHandler::reset(SOCKET client_socket, User& curUser){
	string answer;
	int cnt = 0;
	cnt = curUser.lettersCount();
	for (int i = 1; i <= cnt; i++){
		if (curUser.getLetter(i).getMarker() == true){
			//curUser.getLetter(i).setMarker(false);
			curUser.recoverLetter(i);
		}
	}
	answer.append(responses[13] + to_string(cnt) + " messages\r\n");
	sendLine(client_socket, answer.c_str());
}
Exemplo n.º 25
0
bool Protocol::handshake() {
	char str[kBufferSize];
	char *LineText;
	LineText = str;
	readLine(LineText);
	if (DEBUG) cout << LineText << endl;
	if (!strcmp(LineText, "bzrobots 1")){
		const char * Command="agent 1";
		int temp = sendLine(Command);
		if(temp == 1)	return 1;
		else resetReplyBuffer();
		return false;
	}
	return true;
}
Exemplo n.º 26
0
void Worker::startQueue()
{
    if (m_commandList.size() == 0)
    {
        return;
    }

    // send the first 3 commands
    m_currentLine = 0;
    m_waitingCount = 0;
    for (int i = 0; i < m_bufferSize; ++i)
    {
        sendLine();
    }
}
Exemplo n.º 27
0
bool Worker::sendSession()
{
	bool ok = sendLine("SESSION;" + session, 0);

	if (!ok) {
		return false;
	}

	ok = readResult(0);

	if (!ok) {
		return false;
	}

	return true;
}
Exemplo n.º 28
0
//завершение сеанса
void MailHandler::disconnect(SOCKET client_socket, int& status, User& curUser){
	string answer;
	int cnt = 0;
	cnt = curUser.lettersCount();
	for (int i = cnt; i > 0; i--){
		if (curUser.getLetter(i).getMarker() == true){
			curUser.eraseLetter(i-1);
		}
	}
	int fin = curUser.lettersCount();
	if (fin == 0) answer.append(responses[20]);
	else answer.append(responses[19] + to_string(fin) + " messages left)");
	curUser.setOfline();
	status = 0;
	sendLine(client_socket, answer.c_str());
}
Exemplo n.º 29
0
void Worker::terminate(const string& line, time_t timeout)
{
	WriteLocker locker(&mutex);

	if (status != WORKER_RUNNING) {
		return;
	}

	bool ok = sendLine(line, timeout);

	if (ok) {
		ok = readResult(timeout);
	}

	terminateProcess();
}
Exemplo n.º 30
0
//--------------------------------------------------------------
void ofApp::update(){

    
    fbo.begin();
    mClient.draw(0, 0);
    fbo.end();
    
    fbo.readToPixels(pixels);
    
    fboTour.begin();
    tClient.draw(0, 0);
    fboTour.end();
    
    fboTour.readToPixels(pixTour);
    
    while(receiver.hasWaitingMessages()){
        // get the next message
        ofxOscMessage m;
        receiver.getNextMessage(m);
        
        if(m.getAddress() == "/b"){
            //ofLog() << "b" << m.getArgAsInt32(0);
            for (int i=0; i<3; i++){
                setBrightness(i, m.getArgAsInt32(0));
            }
        }
        else if(m.getAddress() == "/t"){
            //ofLog() << "t" << m.getArgAsInt32(0);
            setBrightness(3, m.getArgAsInt32(0));
        }
        else if(m.getAddress() == "/d"){
            for (int i=0; i<3; i++){
                setDither(i, m.getArgAsInt32(0));
            }
            //ofLog() << "d" << m.getArgAsInt32(0);
        }
        else if(m.getAddress() == "/dt"){
            setDither(3, m.getArgAsInt32(0));
            //ofLog() << "d" << m.getArgAsInt32(0);
        }
    }
  
    for (int i=0; i<4; i++) {
    sendLine(i);
    }
    
}