Beispiel #1
0
// 리스트에 새 클라이언트를 추가합니다.
Client* addClient(Client* newClient) {
    char buffer[256];
    char head[HEAD_SIZE], value[VALUE_SIZE];

    int n;

    if (newClient == 0) return 0;

    // 우선 클라이언트가 일반 클라이언트이지, shell 클라이언트인지를 알아냅니다.
    readMsg(newClient->socket, head, value);
    if ( !strcmp(head, MODE) && !strcmp(value, MODE_CLIENT) ) {
        // 일반 client 모드면 싱글 링크드리스트에 추가합니다.
        newClient->nextClient = 0;
        if (front != 0)
            newClient->nextClient = front;
        // 그냥 맨 앞에 넣습니다. 순서는 중요하지 않습니다.
        front = newClient;
        newClient->isShell = false;

    } else
    if ( !strcmp(head, MODE) && !strcmp(value, MODE_SHELL) ) {
        // shell client 모드면 shell 모드로 접속한 다른 클라이언트가 없는지 확인합니다.
        if (shellClient != 0) {
            writeMsg(newClient->socket, ERR, "SHELL_DUP");
            exit(1);
        }

        // shell 클라이언트는 리스트에 넣지 않고 따로 관리합니다.
        shellClient = newClient;
        newClient->isShell = true;
    } else {
        // 알 수 없는 client 접속
        writeMsg(newClient->socket, ERR, PROTO_ERR);
        return 0;
    }

    // 클라이언트의 이름을 설정합니다.
    sprintf(buffer, "Client(%d)", clientCount);
    clientCount++;
    writeMsg(newClient->socket, SET_NAME, buffer);

    // 클라이언트 정보를 출력합니다.
    Notice("Client");
    printf("(%d) connected, IP: %s, Port: %d\n", clientCount, newClient->ip, newClient->port);

    // 끝났습니다. 클라이언트에게 정상적으로 접속했다고 알립니다.
    readMsg(newClient->socket, head, value);
    writeMsg(newClient->socket, ACCEPT, "server_ok");

    return newClient;
}
Beispiel #2
0
int main(int argc, char** argv) {
  char msg[SIZE];
		int len=0;
		int start=0;
		int *pstart=&start; 
		int end=0;
		int *pend=&end;
		int count=0;
		// read in every line of the tweets
  while ((len = readMsg(msg)) != EOF) {
    // get every word in the current line
    *pstart=0;
				*pend=0;
    while (getWord(msg,len,pstart,pend)) {
      // turn the word to small case
//	printf("start %d\n", *pend - *pstart);
//	printf("end %d\n", *pend);
      count = *pstart;
						while(count <= *pend) {
							unCapitalize(msg+count);
							count++;
      }
      // check and process the word
	printf("word %s\n",(msg+*pstart));
      checkWord((msg+*pstart),*pend-*pstart,argv,argc); 
    		
	}
    // output the processed message
    for(count=0;count<len;count++) {
   // putchar(*(msg+count));
    }
  }
  return 0;
}
// ------------------------------Main Loop---------------------------------------
void mainLoop()
{
	writeMsg(ESTOP);
	while(killFlg == 0)
	{	
		readMsg(1,0);
		// shared memory access
			// update system states in shared memory
			if (last_input == CONVEYORON)
				memData.conveyorOn = ON;
			else if ((last_input == CONVEYOROFF) || (last_input == ESTOP))
				memData.conveyorOn = OFF;
			if ((last_input == MANUALON) || (last_input == ESTOP))
				memData.autoModeOn = OFF;
			else if (last_input == MANUALOFF || last_input == HOMEROBOT)
				memData.autoModeOn = ON;	
			memData.upperByte = readUpperByte.hiInputSetByte;
			memData.lowerByte = readLowerByte.lowInputSetByte;
			memData.blkType = blockNumG;
		sem_wait(sem);
			*memLocation = memData;
		sem_post(sem);
		//  request status from GUIport and write to shared memory for every 50 ms
		delay(50);
	}
}
Beispiel #4
0
/*
 * Handle for common functions
 * Register Led Control with System after spawning
 */
bool Led_Ctr::ctrRegister()
{
	generic_msg *msg = NULL;
	sys_msg *sys = NULL;

	msg = prepHelloMsg(LED_C);
	writeMsg(msg);
	desMsg(msg);

	log->LOG_IN("Send REG message");
	/* Wait for REG_ACK from system with led configuration */
	while(true)
	{
		msg = readMsg();
		if (msg == NULL)
			continue;

		log->LOG_IN("Received a message from System: " + msg->msgType);
		if (msg->msgType == SYS)
		{
			sys = (sys_msg*)msg->data;
			if (sys->sysMsgType == SYS_REGISTER_OK)
			{
				/* Initialize Led agent instances from configuration */

				desMsg(msg);
				break;
			}
		}
	}

	return true;
}
Beispiel #5
0
errorcode helper_fsm_start_buddy_bday(connlist_t *list, connlist_item_t *peer,
				connlist_item_t *buddy) {

	/* declare local variables */
	comm_msg_syn_ack_flood_seq_num_t msg;

	/* error check arguments */
	CHECK_NOT_NULL(list,ERROR_NULL_ARG_1);
	CHECK_NOT_NULL(peer,ERROR_NULL_ARG_2);
	CHECK_NOT_NULL(buddy,ERROR_NULL_ARG_3);

	/* do function */

	CHECK_FAILED(readMsg(peer->info.socks.peer,
		COMM_MSG_WAITING_TO_SYN_ACK_FLOOD,NULL,0),ERROR_NETWORK_READ);
	DEBUG(DBG_PROTOCOL,"PROTOCOL:received WAITING_TO_SYN_ACK_FLOOD\n");

	/* as soon as the bday.seq_num_set flag is set, it is time for this
	 * peer to flood synacks */
	CHECK_FAILED(wait_for_buddy_syn_flood(&buddy->info),ERROR_1);

	/* make the message... */
	msg.seq_num = buddy->info.bday.seq_num;
	/* ...and sent it */
	CHECK_FAILED(sendMsg(peer->info.socks.peer,
		COMM_MSG_SYN_ACK_FLOOD_SEQ_NUM,&msg,sizeof(msg)),
		ERROR_NETWORK_SEND);
	DEBUG(DBG_PROTOCOL,"PROTOCOL:sent SYN_ACK_FLOOD_SEQ_NUM\n");

	/* enter the next state */
	CHECK_FAILED(helper_fsm_end_buddy_bday(list,peer,buddy),
		ERROR_CALLED_FUNCTION);

	return ERROR_1;
}
Beispiel #6
0
//-----------------------------------------------------------------------------
KMMessage* KMFolder::take(int idx)
{
  KMMsgBase* mb;
  KMMessage* msg;

  assert(mStream!=NULL);
  assert(idx>=0 && idx<=mMsgList.high());

  mb = mMsgList[idx];
  if (!mb) return NULL;
  if (!mb->isMessage()) readMsg(idx);

  msg = (KMMessage*)mMsgList.take(idx);
  if (msg->status()==KMMsgStatusUnread ||
	  msg->status()==KMMsgStatusNew) {
	--unreadMsgs;
	emit numUnreadMsgsChanged( this );
  }
  msg->setParent(NULL);
  mDirty = TRUE;
  needsCompact=true; // message is taken from here - needs to be compacted
  if (!mQuiet) emit msgRemoved(idx);

  return msg;
}
Beispiel #7
0
errorcode helper_fsm_start_peer_bday(connlist_t *list, connlist_item_t *peer, 
				connlist_item_t *buddy) {

	/* declare local variables */
	comm_msg_syn_flooded_t msg;

	/* error check arguments */
	CHECK_NOT_NULL(list,ERROR_NULL_ARG_1);
	CHECK_NOT_NULL(peer,ERROR_NULL_ARG_2);
	CHECK_NOT_NULL(buddy,ERROR_NULL_ARG_3);

	/* do function */

	/* receive message indicating that the flood happened */
	CHECK_FAILED(readMsg(peer->info.socks.peer,COMM_MSG_SYN_FLOODED,
		&msg,sizeof(msg)),ERROR_NETWORK_READ);
	DEBUG(DBG_PROTOCOL,"PROTOCOL:received SYN_FLOODED\n");

	/* set the value for the sequence number in the peer's info */
	peer->info.bday.seq_num = msg.seq_num;
	peer->info.bday.seq_num_set = FLAG_SET;

	/* send message indicating the buddy is about to commence sending the
	 * SYN/ACKs */
	CHECK_FAILED(sendMsg(peer->info.socks.peer,
		COMM_MSG_BUDDY_SYN_ACK_FLOODED,NULL,0),ERROR_NETWORK_SEND);

	/* enter next state */
	CHECK_FAILED(helper_fsm_end_peer_bday(list,peer,buddy),
		ERROR_CALLED_FUNCTION);

	return ERROR_1;
}
Beispiel #8
0
int main(int argc, char**argv) {
  char msg[SIZE];
  int len=0;
  // read in every line of the tweets
  // till there are no more lines
  while ((len=readMsg(msg)) != EOF) {
    msg[len]='\0';
    lowerStringCase(msg, len);
    // turn the string to lower case
    int wL=0;
    int prevEnd = 0;
    // get every word in the current line
    // until there are no more words
    do {
      //get length of the current word
      wL = wordLen(msg, len, prevEnd);
      // check the word against each keyword
      for(int i = 1; i < argc; i++) {
      matchAndEraseWord(msg,prevEnd,wL,argv[i]);
      }

    } while ((prevEnd = getNextWordIndex(msg,len,(prevEnd+wL))) != -1); 
    // output the processed message
  printf("%s", msg);
  }
  
  return 0;
}
Beispiel #9
0
void RS232_1::execute(void* arg)
{
	int lenRead = 0;
	while (!isStopped()) {
		if ((lenRead = readMsg(&recvbuf)) < 0) {
			printf("recieving from devfile1 failed\n");
		}

		switch (recvbuf) {
		case MSG_TEST:
			printf("Testmessage recved on devfile1: %c\n", recvbuf);
			break;
		case MSG_TIMEOUT:
#ifdef DEBUG_RS232
			printf("Debug RS232_1: Timeout recved\n");
#endif
			break;
		default:
#ifdef DEBUG_RS232
			printf("Debug RS232_1: Unknown msg recved: %c\n", recvbuf);
#endif
			break;
		}

		recvbuf = 0;
	}
}
Beispiel #10
0
void doNormalMode(int socket) {
    char head[HEAD_SIZE], value[VALUE_SIZE];
    char fileBuffer[FILE_BUFFER_SIZE + 1];
    char fileChunk[FILE_CHUNK_SIZE];
    char filename[256];
    long filesize;
    int fd;

    // 일반 모드로 작동합니다...
    while (true) {
        // 서버의 메시지를 받아 작동합니다.
        readMsg(socket, head, value);

        // 파일 삭제
        if ( !strcmp(head, DEL) ) {
            FDEBUG(("get del message from server\n"));
            remove(value);
        } else
        // 파일 추가
        if ( !strcmp(head, ADD) ) {
            FDEBUG(("get add message from server\n"));

            // 파일 이름을 저장하고, 해당 이름으로 파일을 생성합니다.
            strcpy(filename, value);
            fd = open(filename, O_WRONLY | O_CREAT, 0644);

            // 파일 구분자를 받아옵니다.
            readMsg(socket, head, fileChunk);

            while(true) {
                // 데이터를 받아서 그대로 파일에 기록합니다.
                readData(socket, fileBuffer);
                // 단, 구분자만 보내는 경우는 파일 전송이 끝났다는 신호입니다.
                if ( !strcmp(fileBuffer, fileChunk) ) break;

                writeData(fd, fileBuffer);
            }

            // 작성하고 있는 파일을 닫습니다.
            close(fd);
            // EOF 메시지를 확인합니다.
            readMsg(socket, head, value);
        }
    }
}
Beispiel #11
0
//定时器触发(从串口读取数据)
void ZigBee::timeout_slot()
{
      buff = myCom->readAll();
          
      if(!buff.isEmpty()&&buff.length()==26){
         qDebug()<<QString(buff.toHex().data());
	 readMsg(QString(buff.toHex().data()));
         buff.clear();//给buff清零
       }	
}
Beispiel #12
0
int
DCMessenger::receiveMsgCallback(Stream *sock)
{
	Stopwatch watch; watch.start();
	int passes = 0;
	pending_operation_enum cur_state = m_pending_operation;
	do
	{
		// If we've gone through the loop once and there's not another ready message,
		// wait for DC to call us back.
		if (passes)
		{
			if (!static_cast<Sock*>(sock)->msgReady())
			{
				dprintf(D_NETWORK, "No messages left to process (done %d).\n", passes);
				break;
			}
			dprintf(D_NETWORK, "DC Messenger is processing message %d.\n", passes+1);
		}
		passes++;

		classy_counted_ptr<DCMsg> msg = m_callback_msg;
		ASSERT(msg.get());

		m_callback_msg = NULL;
		m_callback_sock = NULL;
		m_pending_operation = NOTHING_PENDING;

		daemonCore->Cancel_Socket( sock );

		ASSERT( sock );

			// Invoke readMsg() to read and process the message.
			// Note that in some cases, the callback to process the
			// message will invoke startReceiveMsg() if it wants to
			// receive another message; this is the case
			// in class ScheddNegotiate for instance.  When this
			// happens, m_pending_operation will get reset to
			// RECEIVE_MSG_PENDING, and we may end up looping
			// again via the do/while block below to read the
			// next message if it is ready without going back to DC.
			// See gt #4928.
		readMsg( msg, (Sock *)sock );

		cur_state = m_pending_operation;
		decRefCount();
	}
		// Note that we do not access m_pending_operation after
		// decRefCount is called - that may have deleted our object.
	while ((cur_state == RECEIVE_MSG_PENDING) &&
		   (m_receive_messages_duration_ms > 0) &&
		   (watch.get_ms() < m_receive_messages_duration_ms));

	return KEEP_STREAM;
}
Beispiel #13
0
bool Client::init(std::string host, int port)
{
	_socket = socket(AF_INET, SOCK_STREAM, 0);
	if (_socket < 0)
	{
		std::cerr << "Failed to create socket." << std::endl;
		return false;
	}

	// Set timeout on socket read
	struct timeval timeout;

	timeout.tv_sec = 50;
	timeout.tv_usec = 0;

	setsockopt(_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,sizeof(struct timeval));

	// Resolves hostname into IP address
	hostent *he = gethostbyname(host.c_str());

	if (he == NULL || he->h_length == 0)
	{
		std::cerr << "Failed to resolve host name." << std::endl;
		return false;
	}

	in_addr** addr_list = (in_addr **) he->h_addr_list;

	// Create address for socket
	sockaddr_in address;
	// Initialize address
	memset(&address, 0, sizeof(address));
	// Set address to IPv4 family
	address.sin_family = AF_INET;
	// Set destination IP address
	address.sin_addr = *(addr_list[0]);
	// Set destination port
	address.sin_port = htons(port);

	int res = connect(_socket, (sockaddr*)&address, sizeof(address));
	if (res < 0)
	{
		std::cerr << "Failed to connect to socket." << std::endl;
		return false;
	}

	// Handshaking on connection
	if (!readMsg(HELLO) ||
		!sendMsg(HELLO))
	{
		std::cerr << "Handshake with server failed." << std::endl;
		return false;
	}
	return true;
}
Beispiel #14
0
MojErr MojSocketService::Connection::start()
{
	// todo: set no-delay
	m_state = StateInit;
	MojErr err = writeOpen();
	MojErrCheck(err);
	err = readMsg();
	MojErrCheck(err);

	return MojErrNone;
}
Beispiel #15
0
void readLoop(socklen_t socket) {
    uint8_t header[HEADER_SIZE];
    uint8_t msg[MSG_SIZE];
    uint16_t length = 0;
    struct msgheader headerstr;
    FILE* fd;

    fd = createNewFile(par.path);
    while(1) {
        if(length == 0) {
            if(readHeader(socket, header) < 0)
                return;
            writeToFile(fd, header, HEADER_SIZE);
            
            headerstr = parseHeader(header);
            bytecounter += ntohs(headerstr.length);
            length = ntohs(headerstr.length)-HEADER_SIZE;
        }

        if(length >= MSG_SIZE) {
            if(readMsg(socket, msg, MSG_SIZE) < 0)
                return;

            writeToFile(fd, msg, MSG_SIZE);
            length-=MSG_SIZE;
        }
        else {
            if(readMsg(socket, msg, length) < 0)
                return;
            writeToFile(fd, msg, length);
            length = 0;
        }

        if ((bytecounter >= par.size) && (length == 0)) {
            bytecounter = 0;
            fclose(fd);
            close(socket);
        }
    }
}
Beispiel #16
0
//-----------------------------------------------------------------------------
KMMessage* KMFolder::getMsg(int idx)
{
  KMMsgBase* mb;

  // assert(idx>=0 && idx<=mMsgList.high());
  if(!(idx >= 0 && idx <= mMsgList.high()))
    return 0L;

  mb = mMsgList[idx];
  if (!mb) return NULL;

  if (mb->isMessage()) return ((KMMessage*)mb);
  return readMsg(idx);
}
Beispiel #17
0
errorcode helper_fsm_end_peer_bday(connlist_t *list, connlist_item_t *peer,
				connlist_item_t *buddy) {

	/* declare local variables */
	comm_msg_bday_success_port_t receive_msg;
	comm_msg_buddy_port_t send_msg;

	/* error check arguments */
	CHECK_NOT_NULL(list,ERROR_NULL_ARG_1);
	CHECK_NOT_NULL(peer,ERROR_NULL_ARG_2);
	CHECK_NOT_NULL(buddy,ERROR_NULL_ARG_3);

	/* do function */

	if (FAILED(readMsg(peer->info.socks.peer,COMM_MSG_BDAY_SUCCESS_PORT,
		&receive_msg,sizeof(receive_msg)))) {
		peer->info.bday.status = FLAG_FAILED;
		return ERROR_NETWORK_READ;
	}

	/* set the port value */
	peer->info.bday.port               = receive_msg.port;
	peer->info.bday.port_set           = FLAG_SET;
	peer->info.bday.status             = FLAG_SUCCESS;
	/* this location for the external port is no longer valid, since the
	 * flag was already set, but I set it here just in case I screwed up
	 * somewhere else in the code and look at it */
	peer->info.port_alloc.ext_port     = receive_msg.port;
	peer->info.port_alloc.ext_port_set = FLAG_SET;

	/* send a message with the buddy's port, to go back to the buddy port
	 * state.  there is no need to wait for the port value to be set, it
	 * is obviously set, since it was set before */
	send_msg.ext_port = buddy->info.port_alloc.ext_port;
	send_msg.bday     =  COMM_BDAY_NOT_NEEDED;

	CHECK_FAILED(sendMsg(peer->info.socks.peer,COMM_MSG_BUDDY_PORT,
		&send_msg,sizeof(send_msg)),ERROR_NETWORK_SEND);
	DEBUG(DBG_PROTOCOL,"PROTOCOL:sent BUDDY_PORT...again\n");

	/* go to the start direct conncetion state now that all ports are
	 * known */
	CHECK_FAILED(helper_fsm_start_direct_conn(list,peer,buddy),
		ERROR_CALLED_FUNCTION);

	return SUCCESS;

}
Beispiel #18
0
errorcode helper_fsm_hello(connlist_t *list, connlist_item_t *item) {

	/* declare variables */
	comm_msg_hello_t hello;

	/* error check arguments */
	CHECK_NOT_NULL(list,ERROR_NULL_ARG_1);
	CHECK_NOT_NULL(item,ERROR_NULL_ARG_2);

	/* do function */
	/* this is a strange case, but it is OK if no acceptable message
	 * is received on this read.  It was probably a port prediction
	 * second connection */
	CHECK_FAILED(readMsg(item->info.socks.peer, COMM_MSG_HELLO,
				&hello, sizeof(hello)), ERROR_NETWORK_READ);

	DEBUG(DBG_PROTOCOL,"PROTOCOL:received HELLO\n");

	/* save out info from the message */
	item->info.peer.port         = hello.peer_port;
	item->info.peer.ip           = hello.peer_ip;
	item->info.peer.set          = FLAG_SET;
	item->info.buddy.int_ip      = hello.buddy_int_ip;
	item->info.buddy.int_port    = hello.buddy_int_port;
	item->info.buddy.ext_ip      = hello.buddy_ext_ip;
	item->info.buddy.identifier  = FLAG_SET;

	DEBUG(DBG_VERBOSE,"VERBOSE:Information from peer hello\n");
	DEBUG(DBG_VERBOSE,"VERBOSE:peer.............%s:%u\n",
		DBG_IP(item->info.peer.ip),
		DBG_PORT(item->info.peer.port));
	DEBUG(DBG_VERBOSE,"VERBOSE:buddy internal...%s:%u\n",
		DBG_IP(item->info.buddy.int_ip),
		DBG_PORT(item->info.buddy.int_port));
	DEBUG(DBG_VERBOSE,"VERBOSE:buddy external...%s\n",
		DBG_IP(item->info.buddy.ext_ip));

	/* send the next message */
	CHECK_FAILED(sendMsg(item->info.socks.peer, COMM_MSG_CONNECT_AGAIN,
		NULL, 0),ERROR_NETWORK_SEND);

	DEBUG(DBG_PROTOCOL,"PROTOCOL:sent CONNECT_AGAIN\n");

	/* go to next state */
	CHECK_FAILED(helper_fsm_conn2(list,item),ERROR_CALLED_FUNCTION);

	return SUCCESS;
}
Beispiel #19
0
void VDispatcher::dispatchMsg(){
    StringList datas;
    while ((!m_isInExit)&&readMsg(datas)){
        const String& Msg_ID=datas[0];
        TDisposerMap::iterator it=m_disposerMap.find(Msg_ID);
        if (it!=m_disposerMap.end()){
            IMsgDisposer*    msgDisposer=it->second.msgDisposer;
            TMsgDisposerProc msgDisposerProc=it->second.msgDisposerProc;
            if (m_listener!=0)
                m_listener->disposeDispatchMsg(this,datas);
            msgDisposerProc(msgDisposer,datas);
        }else{
            //assert(false);
        }
    }
}
int SocketService::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: receiveMsgFromSocket((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 1: readMsg(); break;
        case 2: sendMsg(); break;
        case 3: acceptConnection(); break;
        default: ;
        }
        _id -= 4;
    }
    return _id;
}
Beispiel #21
0
int
DCMessenger::receiveMsgCallback(Stream *sock)
{
	classy_counted_ptr<DCMsg> msg = m_callback_msg;
	ASSERT(msg.get());

	m_callback_msg = NULL;
	m_callback_sock = NULL;
	m_pending_operation = NOTHING_PENDING;

	daemonCore->Cancel_Socket( sock );

	ASSERT( sock );
	readMsg( msg, (Sock *)sock );

	decRefCount();
	return KEEP_STREAM;
}
Beispiel #22
0
errorcode helper_fsm_start_direct_conn(connlist_t *list, connlist_item_t *peer,
					connlist_item_t *buddy) {

	/* declare local variables */
	comm_msg_buddy_syn_seq_t buddy_syn_msg;
	comm_msg_peer_syn_seq_t peer_syn_msg;

	/* error check arguments */
	CHECK_NOT_NULL(list,ERROR_NULL_ARG_1);
	CHECK_NOT_NULL(peer,ERROR_NULL_ARG_2);
	CHECK_NOT_NULL(buddy,ERROR_NULL_ARG_3);

	/* do function */

	/* get message from peer with buddy seq num */
	CHECK_FAILED(readMsg(peer->info.socks.peer,COMM_MSG_BUDDY_SYN_SEQ,
		&buddy_syn_msg,sizeof(buddy_syn_msg)),ERROR_NETWORK_READ);
	DEBUG(DBG_PROTOCOL,"PROTOCOL:received BUDDY_SYN_SEQ\n");
	DEBUG(DBG_VERBOSE,"VERBOSE:sequence number is %u\n",
		DBG_SEQ_NUM(buddy_syn_msg.seq_num));

	/* fill in the information about this syn sequence number */
	peer->info.buddy_syn.seq_num     = buddy_syn_msg.seq_num;
	peer->info.buddy_syn.seq_num_set = FLAG_SET;

	/* make payload to send in next message. first wait for the seq num
	 * and then fill it in the payload */
	CHECK_FAILED(wait_for_buddy_syn_seq_num(&(buddy->info)),ERROR_1);
	peer_syn_msg.seq_num = buddy->info.buddy_syn.seq_num;

	/* send the message */
	CHECK_FAILED(sendMsg(peer->info.socks.peer,COMM_MSG_PEER_SYN_SEQ,
		&peer_syn_msg,sizeof(peer_syn_msg)),ERROR_NETWORK_SEND);
	DEBUG(DBG_PROTOCOL,"PROTOCOL:sent PEER_SYN_SEQ\n");

	/* enter next state */
	CHECK_FAILED(helper_fsm_goodbye(list,peer,buddy),
		ERROR_CALLED_FUNCTION);

	return SUCCESS;
}
Beispiel #23
0
errorcode helper_fsm_end_buddy_bday(connlist_t *list, connlist_item_t *peer,
				connlist_item_t *buddy) {

	/* declare local variables */
	comm_msg_buddy_port_t msg;

	/* error check arguments */
	CHECK_NOT_NULL(list,ERROR_NULL_ARG_1);
	CHECK_NOT_NULL(peer,ERROR_NULL_ARG_2);
	CHECK_NOT_NULL(buddy,ERROR_NULL_ARG_3);

	/* do function */

	/* receive the message indicating the synack flood was done */
	CHECK_FAILED(readMsg(peer->info.socks.peer,COMM_MSG_SYN_ACK_FLOOD_DONE,
		NULL,0),ERROR_NETWORK_READ);
	DEBUG(DBG_PROTOCOL,"PROTOCOL:received SYN_ACK_FLOOD_DONE\n");

	/* wait for the buddy to set the external port */
	CHECK_FAILED(wait_for_buddy_bday_port(&(buddy->info)),ERROR_1);

	/* now, resend the COMM_MSG_BUDDY_PORT message, but this time mark
	 * the bday flag as unneeded
	 */
	msg.ext_port = buddy->info.bday.port;
	msg.bday     = COMM_BDAY_NOT_NEEDED;

	/* now send the message */
	CHECK_FAILED(sendMsg(peer->info.socks.peer,COMM_MSG_BUDDY_PORT,
		&msg,sizeof(msg)),ERROR_NETWORK_SEND);
	DEBUG(DBG_PROTOCOL,"PROTOCOL:sent BUDDY_PORT...again\n");

	/* go to the start direct conncetion state now that all ports are
	 * known */
	CHECK_FAILED(helper_fsm_start_direct_conn(list,peer,buddy),
		ERROR_CALLED_FUNCTION);

	return SUCCESS;

}
Beispiel #24
0
int main(int argc, char** argv) {
	int ch=255;
	char a=ch;
	char msg[]="hkyhuyfytfy ytytuy iu";
	msg[0]=a;
	int len;
	int start=0;
	int end=0;
	char* index=msg;
	int i=0;
	

  // read in every line of the tweets
  while ((len=readMsg(msg))!=EOF) {
      start=0;
      end=0;


    // get every word in the current line
    while (getWord(msg,len,&start,&end)) {
	    i=0;
	    while (i<len){
		unCapitalize(index+i);
	    i++;
	      
	    }
      // turn the word to small case
		checkWord(index+start,end-start,argv+1,argc-1);

      // check and process the word
    }
    i=0;
    while(i<len){
      printf("%c", msg[i]);
      i++;
    }
    // output the processed message
  }
  return 0;
}
Beispiel #25
0
errorcode helper_fsm_goodbye(connlist_t *list, connlist_item_t *peer,
				connlist_item_t *buddy) {

	/* declare local variables */
	comm_msg_goodbye_t goodbye;

	/* error check arguments */
	CHECK_NOT_NULL(list,ERROR_NULL_ARG_1);
	CHECK_NOT_NULL(peer,ERROR_NULL_ARG_2);
	CHECK_NOT_NULL(buddy,ERROR_NULL_ARG_2);

	/* do function */

	/* receive the message */
	CHECK_FAILED(readMsg(peer->info.socks.peer,COMM_MSG_GOODBYE, &goodbye,
		sizeof(goodbye)),ERROR_NETWORK_READ);

	DEBUG(DBG_PROTOCOL,"PROTOCOL:received GOODBYE\n");

	DEBUG(DBG_VERBOSE,"VERBOSE:peer's connection was %sa success!\n",
		((goodbye.success_or_failure==FLAG_FAILED) ? "not ": ""));

	return SUCCESS;
}
Beispiel #26
0
int main(int argc, char** argv) {
  char msg[SIZE];
  // read in every line of the tweets 
  //int counter = 0; 
  int length = 0 ; 
  int  start = 0;
  int  end  = 0;  
  while (length = readMsg(msg) != EOF) 
   {

	 unCapitalize (msg); 
	
	    while ( getWord(msg,length,&start, &end) ) 
	   {
	     
		 
	      checkWord(msg,length,argv , argc);	      // check and process the word
	    }
    // output the processed message 
  	
  }
printf("%s", msg);
 return 0;
}
Beispiel #27
0
void SocketService::acceptConnection()
{
    QTcpSocket *client = server->nextPendingConnection();
    clients_list.append(client);
    connect(client, SIGNAL(readyRead()), this, SLOT(readMsg()));
}
Beispiel #28
0
//====================================
int main(int argc, char *argv[])
//====================================
{
  char syscom[120];
  int ch,i,x;

  currentStep = 1;
  currentLoop = 0;



  strcpy(gplFile,"gpl.txt");

  inrpt[0] = IR0;
  inrpt[1] = IR1;
  inrpt[2] = IR2;
  inrpt[3] = IR3;
  inrpt[4] = IR4;
  inrpt[5] = IR5;


  sprintf(syscom,"ls *.conf > %s;",fileProjList);
  x=system(syscom);
  sprintf(syscom,"rm %s;touch %s;",fileTemp,fileTemp);
  x=system(syscom);
  sprintf(syscom,"rm %s;touch %s;",fileError,fileError);
  x=system(syscom);
  sprintf(syscom,"rm %s;touch %s;",fileServError,fileServError);
  x=system(syscom);
  sprintf(syscom,"rm %s;touch %s;",fileCopyError,fileCopyError);
  x=system(syscom);

  err = fopen(fileError,"w"); // Issue 15

  readSetting();
  readConfig(currentConf);


  initSim();

  resetSim();

  readSimulation();

  readSketchInfo();

  setRange(confBoardType);

  init(confWinMode);

  unoInfo();
  show(slog);

  if(confLogFile == S_YES)resetFile("log.txt");

  readMsg(gplFile);

  openCommand();
  
  delwin(uno);
  delwin(ser);
  delwin(slog);
  delwin(msg);
  endwin();

  fclose(err);

}
Beispiel #29
0
//====================================
void runMode(int stop)
//====================================
{
  int ch,x,step,tmp,res=0,a=0,b=0,ir,ok=0,n=0;
  char tempName[80],syscom[120],temp[80];
  char command[40][40];

  strcpy(tempName,"help.txt");

  s_mode = S_RUN;


  if(stop > 1)
    {
      if(stop > g_steps)stop = g_steps;
      //if(stop > currentStep)
	runAll(stop);
      return;
    }

  putMsg(3,"Run Mode. Press h for help.");

  while(1)  
    {
      anyErrors();
      if(g_silent==S_NO )mvwprintw(uno,board_h-2,1,"R%1d>",confWinMode);
      if(g_silent==S_YES)mvwprintw(uno,board_h-2,1,"R%1d<",confWinMode);
      unoInfo();

      if(g_debug == 1) 
	readFile(confSketchFile,g_lineSketch[currentStep]);


      ch = getchar();

      if (ch=='q')
	{
	  return;
	}

      if (ch=='h')
        {
          readMsg(fileInfoRun);
        }
      else if (ch=='c')
        {
          readMsg(currentConf);
        }
      else if (ch=='d')
        {
          readMsg(fileServTime);
        }
      else if(ch=='y' ) // scenario
	{
	  readMsg(fileServScen);
	}
      else if (ch=='x')
	{
	  readMsg(fileServScenario);
	}
      else if (ch=='G')
	{
	  runAll(g_steps);
	}
      else if (ch=='l')
	{
	  showLoops();
	}
      else if (ch=='s')
	{
	  g_debug++;
	  if(g_debug > 1)g_debug = 0;
	}
      else if (ch=='w')
	{
	  confWinMode++;
	  if(confWinMode > WIN_MODES)confWinMode = 0;
          init(confWinMode);
	  mvwprintw(uno,board_h-2,1,"R%1d>",confWinMode);
	  unoInfo();
	}
      else if (ch=='a')
	{
          goStep(1);
	}
      else if (ch=='r')
	{
          goStep(loopStep[currentLoop+1]);
	}
      else if (ch=='o')
	{
          goStep(loopStep[currentLoop]);
	}
      else if (ch=='p')
	{
          goStep(loopStep[currentLoop-1]);
	}
      else if (ch=='z')
	{
          goStep(g_steps);
	}
      else if (ch=='k')
	{
	  resetSim();
	  init(confWinMode);
	  unoInfo();
	  mvwprintw(uno,board_h-2,1,"R%1d>",confWinMode);
	  show(uno);
	}
      else if (ch=='f')// Up Arrow 
	{
	  goStep(currentStep+1);
	}
      else if (ch=='b')// Down Arrow
	{
	  goStep(currentStep-1);
	}
      else if (ch=='R') // Right Arrow
	{
	  runLoop(S_FORWARD);
	}
      else if (ch=='P') // Left Arrow
	{
	  runLoop(S_BACKWARD);
	}
      else if (ch=='t')
	{
	  runNextRead();
	}
      else if (ch=='j')
	{
	  runPrevRead();
	}
      else if (ch=='i') 
	{
          step = currentStep;
	  sprintf(temp,"(Step:%d) Enter: d/a pin value (q - cancel)",step);
          putMsg(2,temp);
	  wgetstr(uno,temp);
	  n = tokCommand(command,temp);
      
	  if(strstr(command[0],"q") == NULL && n == 3)
	    {
	      g_pinNo = atoi(command[1]);
	      x = atoi(command[2]);
	      printf("%s %d %d",command[0],g_pinNo,x);
	      if(strstr(command[0],"a"))
		{
		  ok = ok + checkRange(S_OK,"anapin",g_pinNo);
		  ok = ok + checkRange(S_OK,"anaval",x);
		  g_pinType = ANA;
		}
	      if(strstr(command[0],"d"))
		{
		  ok = ok + checkRange(S_OK,"digpin",g_pinNo);
		  ok = ok + checkRange(S_OK,"digval",x);
		  g_pinType = DIG;
		}
	      if(ok == S_OK)
		{ 
		  g_scenSource = 1;
		  // steps, source, pintype, pinno, pinvalue, pinstep
		  sprintf(syscom,"cd servuino;./servuino %d %d %d %d %d %d %d;",confSteps,g_scenSource,g_pinType,g_pinNo,x,currentStep,S_ADD);
		  tmp=system(syscom);
		  initSim();
		  readSketchInfo();
		  readSimulation();
		  goStep(currentStep);
		  readMsg(fileServScen);
		}
	    }
	  else
	    putMsg(2,"Cancelled!");
	}
      else if (ch=='v') 
	{
          step = currentStep ;
	  sprintf(temp," Enter value to be read at step %d (q - cancel)",step);
          putMsg(2,temp);
	  res = analyzeEvent(simulation[step]);
          if(res > 0)
	    {
	      wgetstr(uno,temp);

	      if(strstr(temp,"q") == NULL)
		{
		  x = atoi(temp); 
		  ok = S_OK;
		  if(res == ANA)ok = ok + checkRange(S_OK,"anaval",x);
		  if(res == DIG)ok = ok + checkRange(S_OK,"digval",x);
		  if(ok == S_OK)
		    {         
		      g_scenSource = 1;
		      // steps, source, pintype, pinno, pinvalue, pinstep
		      sprintf(syscom,"cd servuino;./servuino %d %d %d %d %d %d %d;",confSteps,g_scenSource,g_pinType,g_pinNo,x,currentStep,S_ADD);
		      tmp=system(syscom);
		      initSim();
		      readSketchInfo();
		      readSimulation();
		      goStep(currentStep);
		      readMsg(fileServScen);
		    }
		}
	      else
		putMsg(2,"Cancelled!");
	    }
	  else
	    putMsg(2,"Next step is not a Read event");
	}
      else
	{
	  sprintf(temp,"Unknown command: %c",ch);
	  putMsg(msg_h-2,temp);
	}
    }
  return;
}
Beispiel #30
0
//====================================
void openCommand()
//====================================
{
  struct stat st;
  int ch,nsteps=1000,x,i,n,stop=0,loop,projNo = 0,ok=0,tmp;
  char *p,str[120],sstr[20],fileName[120],temp[120],syscom[120];
  char command[40][40];

  s_mode = S_ADMIN;
  g_silent = 0;

  readMsg(gplFile);

  while(strstr(str,"ex") == NULL)
    {
      anyErrors();
      unoInfo();

      wmove(uno,board_h-2,1);
      wprintw(uno,"                                                  ");
      if(g_silent==S_NO )mvwprintw(uno,board_h-2,1,"A%1d>",confWinMode);
      if(g_silent==S_YES)mvwprintw(uno,board_h-2,1,"A%1d<",confWinMode);

      strcpy(command[0],"");

      wgetstr(uno,str);

      n = tokCommand(command,str);

      strcpy(sstr,command[0]);

      p = str;

      projNo = atoi(sstr);

      if(strstr(sstr,"gpl"))
        {
          readMsg(gplFile);
        }
      else if(strstr(sstr,"err"))
        {
          readMsg(fileTemp);
        }
      else if(strstr(sstr,"run"))
	{
	  stop = 1;
          if(n == 2)stop = atoi(command[1]);
	  stop = checkRange(HEAL,"step",stop);

	  runMode(stop);
          if(stop==0)putMsg(2,"Back in Admin Mode!");
	}
      else if(strstr(sstr,"res")) // reset simulation
	{
	  resetSim();
	  init(confWinMode);
	  unoInfo();
	  readMsg(currentConf);
	}
      else if(strstr(sstr,"help")) //
	{
	  strcpy(fileName,fileInfoAdmin);
	  readMsg(fileName);
	}
      else if(strstr(sstr,"rem")) //
	{
	  if(n == 4)
	    {
	      if(strstr(command[1],"a"))g_pinType = ANA;
	      if(strstr(command[1],"d"))g_pinType = DIG;
	      g_pinNo   = atoi(command[2]);
	      g_pinStep = atoi(command[3]);
	      if(g_pinType == ANA)
		ok = checkRange(S_OK,"anapin",g_pinNo);
	      if(g_pinType == DIG)
		ok = checkRange(S_OK,"digpin",g_pinNo);
	      if(ok == S_OK)
		{
		  g_scenSource = 1;
		  sprintf(syscom,"cd servuino;./servuino %d %d %d %d %d %d %d;",confSteps,g_scenSource,g_pinType,g_pinNo,0,g_pinStep,S_DELETE);
		  //putMsg(2,syscom);
		  tmp=system(syscom);
		  initSim();
		  readSketchInfo();
		  readSimulation();
		  runStep(S_FORWARD);
		  readMsg(fileServScen);
		}
	      else
		putMsg(2,"Wrong pin number or pin type!");
	    }
	  else
	    putMsg(2,"Syntax: rem <a or d> <pin> <step>");
	}
      else if(strstr(sstr,"add")) //
	{
	  if(n == 5)
	    {
	      if(strstr(command[1],"a"))g_pinType = ANA;
	      if(strstr(command[1],"d"))g_pinType = DIG;

	      g_pinNo    = atoi(command[2]);
	      g_pinStep  = atoi(command[3]);
	      g_pinValue = atoi(command[4]);

	      ok = S_OK;
	      if(g_pinType == ANA)
		ok = checkRange(S_OK,"anapin",g_pinNo);
	      if(g_pinType == DIG)
		ok = checkRange(S_OK,"digpin",g_pinNo);

	      ok = ok + checkRange(S_OK,"step",g_pinStep);

	      if(ok == S_OK)
		{
		  g_scenSource = 1;
		  sprintf(syscom,"cd servuino;./servuino %d %d %d %d %d %d %d;",confSteps,g_scenSource,g_pinType,g_pinNo,g_pinValue,g_pinStep,S_ADD);
		  tmp=system(syscom);
		  initSim();
		  readSketchInfo();
		  readSimulation();
		  runStep(S_FORWARD);
		  readMsg(fileServScen);
		}
	    }
	  else
	    putMsg(2,"Syntax: add <a or d> <pin> <step> <value>");
	}
      else if(strstr(sstr,"info"))
	{
	  if(n == 2)
	    {
	      if(strstr(command[1],"conf"))
		{
		  readMsg(fileDefault);
		}
	      else if(strstr(command[1],"err"))
		{
		  readMsg(fileServError);
		}
	      else if(strstr(command[1],"g++"))
		{
		  readMsg(fileServComp);
		}
	      else if(strstr(command[1],"help"))
		{
		  readMsg(fileInfoAdmin);
		}
	      else if(strstr(command[1],"loop")) 
		{
		  showLoops();
		}
	      else if(strstr(command[1],"scen")) // scenario
		{
		  readMsg(fileServScen);
		}
	    }
	  else
	    {
	      readMsg(fileInfoAdmin);
	    }
	}

      else if(strstr(sstr,"proj"))
	{
	  if(n == 2)
	    {
	      strcpy(currentConf,command[1]);
	      strcat(currentConf,".conf");
	      readConfig(currentConf);
              g_warning = S_YES;
	      unoInfo();
	    }
	  readMsg(currentConf);
	}
      else if(strstr(sstr,"list"))
	{
	  readMsg(fileProjList);	
	}
      else if(strstr(sstr,"sketch"))
	{
	  if(n == 2)
	    {
	      if(strstr(command[1],"conf"))
		{
		  readMsg(confSketchFile);
		}
	      else if(strstr(command[1],"work"))
		{
		  readMsg(fileServSketch);
		}
	    }
	  else
	    readMsg(fileServSketch);	
	}
      else if(strstr(sstr,"conf"))
	{
	  if(n == 3)
	    {
	      if(strstr(command[1],"sim"))
		{
		  confSteps = atoi(command[2]);	
		}
	      else if(strstr(command[1],"win"))
		{
		  confWinMode = atoi(command[2]);
		  if(confWinMode > WIN_MODES)confWinMode = 0;
		  init(confWinMode);
		  unoInfo();
		}
	      else if(strstr(command[1],"sketch"))
		{
		  strcpy(temp,command[2]);
		  if(stat(temp,&st) == 0)
		    {
		      strcpy(confSketchFile,command[2]);
		    }
		  else
		    {
		      sprintf(temp,"Sketch not found: %s",command[2]);// Issue 16
		      putMsg(msg_h-2,temp);
		    }
		}
	      saveConfig(currentConf);
	    }
	  readMsg(currentConf); 
	}
      
      
      else if(strstr(sstr,"sav")) //save config
	{
	  if(n == 2)
	    {
	      strcpy(currentConf,command[1]);
	      strcat(currentConf,".conf");
              
	    }
	  saveConfig(currentConf);
	  readMsg(currentConf);
	  sprintf(syscom,"ls *.conf > %s;",fileProjList);
	  x=system(syscom);
	}
      else if(strstr(sstr,"del")) //delete config
	{
	  if(n == 2)
	    {
	      strcpy(currentConf,command[1]);
	      strcat(currentConf,".conf");
              
	    }
          if(strstr(currentConf,"default") == NULL)
	    {
	      sprintf(syscom,"rm %s;",currentConf);
	      x=system(syscom);
	      sprintf(syscom,"ls *.conf > %s;",fileProjList);
	      x=system(syscom);
	      readMsg(fileProjList);
	      strcpy(currentConf,fileDefault);
	    }	
	}
      else if(strstr(sstr,"win")) //windows layout
        {
          if(n == 2)
	    {
              confWinMode = atoi(command[1]);
              if(confWinMode > WIN_MODES)confWinMode = 0;
              init(confWinMode);
              unoInfo();
	    }
        }
      else if(strstr(sstr,"loop"))
	{
          if(n == 2)loop = atoi(command[1]);
	  loop = checkRange(HEAL,"loop",loop);
	  runLoops(loop);
	}
      else if(strstr(sstr,"clear"))
	{
	  sprintf(syscom,"rm servuino/sketch.ino;rm servuino/data.su;rm servuino/data.scen;");
	  x=system(syscom);
	}
      else if(strstr(sstr,"load"))
	{
          if(n == 2)
	    {
	      confSteps = atoi(command[1]);
	    }
          g_scenSource = 0;
	  loadCurrentProj();
	}
      else if(projNo > 0 && projNo < 10)
        {
	  selectProj(projNo,currentConf);
	  readConfig(currentConf);
	  g_warning = S_YES;
	  unoInfo();
	  readMsg(currentConf);   
        }
      else if(strstr(sstr,"data"))
	{
	  if(n == 2)
	    {
	      if(strstr(command[1],"ard"))
		{
		  readMsg(fileServArduino);
		}
	      else if(strstr(command[1],"cus"))
		{
		  readMsg(fileServCustom);
		}
	      else if(strstr(command[1],"cod"))
		{
		  readMsg(fileServCode);
		}
	      else if(strstr(command[1],"err"))
		{
		  readMsg(fileServError);
		}
	      else if(strstr(command[1],"sce"))
		{
		  readMsg(fileServScen);
		}
	    }
	  else
	    readMsg(fileServArduino);
	}
      else 
	{
	  putMsg(msg_h-2,"Unknown Admin command");
	}
    }
}