Exemple #1
0
//-----------------------------------------------------------------------------
// PING and PONG are handled differently to all other flags.  It will be
// actioned straight away, and does not require an EXECUTE.
static void cmdPing(void *base)
{
 	node_t *node = (node_t *) base;

 	assert(node != NULL);
 	assert(node->handle >= 0);
 	
	sendPong(node);
}
void loop()
{

    if (wifly.available() > 0) {

    	/* See if there is a request */
		if (wifly.gets(buf, sizeof(buf))) {
		    if (strncmp_P(buf, PSTR("GET /ping"), 9) == 0) {

				/* GET request */
#ifdef DEBUG
				Serial.println(F("PONG XML requested"));
#endif
				while (wifly.gets(buf, sizeof(buf)) > 0) {
				    //Skip rest of request
				}

				sendPong();

	   	 	} else if (strncmp_P(buf, PSTR("GET /data"), 9) == 0) {

	        	/* POST request */
#ifdef DEBUG
	        	Serial.println(F("DATACOLLECTOR XML: sendind sensors data"));
#endif

				while (wifly.gets(buf, sizeof(buf)) > 0) {
				    //Skip rest of request
				}

                // discard rest of input
		    	// wifly.flushRx();		
				sendSensorsDataXML();

	    	} else {

	       		// Unexpected request
#ifdef DEBUG
				Serial.print(F("Unexpected: "));
				Serial.println(buf);
				Serial.println(F("Sending 404"));
#endif
				while (wifly.gets(buf, sizeof(buf)) > 0) {
				    //Skip rest of request
				}

                // discard rest of input
				wifly.flushRx();		
				send404();

	    	}
		}
    }
}
Exemple #3
0
///////////////////////
// Ping
void IRCClient::parsePing(const IRCClient::IRCCommand &cmd)
{
	// Check
	if (cmd.params.size() == 0)
		return;

	// Send reply
	sendPong(cmd.params[0]);

	// Progress with authorisation if not yet connected
	if (m_authorizedState == AUTH_NICK_SENT)
		sendUserAuth();
}
Exemple #4
0
void NetworkPlugin::handleDataRead(std::string &data) {
	m_data.insert(m_data.end(), data.begin(), data.end());

	while (m_data.size() != 0) {
		unsigned int expected_size;

		if (m_data.size() >= 4) {
			expected_size = *((unsigned int*) &m_data[0]);
			expected_size = ntohl(expected_size);
			if (m_data.size() - 4 < expected_size)
				return;
		}
		else {
			return;
		}

		pbnetwork::WrapperMessage wrapper;
		if (wrapper.ParseFromArray(&m_data[4], expected_size) == false) {
			m_data.erase(m_data.begin(), m_data.begin() + 4 + expected_size);
			return;
		}
		m_data.erase(m_data.begin(), m_data.begin() + 4 + expected_size);

		switch(wrapper.type()) {
			case pbnetwork::WrapperMessage_Type_TYPE_LOGIN:
				handleLoginPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_LOGOUT:
				handleLogoutPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_PING:
				sendPong();
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_CONV_MESSAGE:
				handleConvMessagePayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_JOIN_ROOM:
				handleJoinRoomPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_LEAVE_ROOM:
				handleLeaveRoomPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_VCARD:
				handleVCardPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_BUDDY_CHANGED:
				handleBuddyChangedPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_BUDDY_REMOVED:
				handleBuddyRemovedPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_STATUS_CHANGED:
				handleStatusChangedPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_BUDDY_TYPING:
				handleChatStatePayload(wrapper.payload(), pbnetwork::WrapperMessage_Type_TYPE_BUDDY_TYPING);
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_BUDDY_TYPED:
				handleChatStatePayload(wrapper.payload(), pbnetwork::WrapperMessage_Type_TYPE_BUDDY_TYPED);
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_BUDDY_STOPPED_TYPING:
				handleChatStatePayload(wrapper.payload(), pbnetwork::WrapperMessage_Type_TYPE_BUDDY_STOPPED_TYPING);
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_ATTENTION:
				handleAttentionPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_FT_START:
				handleFTStartPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_FT_FINISH:
				handleFTFinishPayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_FT_PAUSE:
				handleFTPausePayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_FT_CONTINUE:
				handleFTContinuePayload(wrapper.payload());
				break;
			case pbnetwork::WrapperMessage_Type_TYPE_EXIT:
				handleExitRequest();
				break;
			default:
				return;
		}
	}
}
Exemple #5
0
void ircbot::start() {
    int result;
    struct addrinfo hints;
    struct addrinfo *serverInfo;
 
    checkProperties();
 
    //ensure that serverInfo is clear
    memset(&hints, 0, sizeof(hints)); // make sure the struct is empty
 
    //setup hints
    
    // don't care IPv4 or IPv6
    hints.ai_family = AF_UNSPEC;      
    
    // TCP stream sockets
    hints.ai_socktype = SOCK_STREAM;  
 
    //Setup the structs if error print why
    if ((result = getaddrinfo(address.c_str(), port.c_str(), &hints, &serverInfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(result));
        exit(-1);
    }
 
    //setup the socket
    setupSocket(serverInfo);
 
    //Connect
    openConnection(serverInfo);

    //Free the space used for serverInfo
    freeaddrinfo(serverInfo);
 
    //Receive some data
    int numbytes;
    char buf[MAXDATASIZE];
 
    int count = 0;
    while (1) {
        count++;
        switch (count) {
            case 3: {
                //after 3 receives send data to server (as per IRC protacol)
                setNick();
                setUser();
                break;
            }
            case 4: {
                //Join a channel after we connect, this time we choose beaker
                string joinStr = "JOIN " + channel + "\r\n";
                char *joinCStr = new char[ joinStr.length() + 1 ];
                strcpy( joinCStr, joinStr.c_str() );
                sendData(joinCStr);
                joinMessageSent = true;
                break;
            }
            default: {
                break;
            }
        }
 
        //Recv & print Data
        numbytes = recv(sock, buf, MAXDATASIZE - 1, 0);
        buf[numbytes] = '\0';

        linesReceived++;

        fprintf(stderr, "%s", buf);
        
        //If Ping Recived, must respond with PONG otherwise connection will close
        if ( strstr(buf, "PING") != NULL ) {
            sendPong(buf);
        }
        // check for motd to verify connection status
        else if ( checkForMOTD(buf) ) {
            connected = true;
        }
        else if ( joinMessageSent && strstr(buf, "End of /NAMES list.") != NULL ) {
            joinedChannel = true;
        }
        else if ( joinMessageSent && !joinedChannel ) {
            string joinStr = "JOIN " + channel + "\r\n";
            char *joinCStr = new char[ joinStr.length() + 1 ];
            strcpy( joinCStr, joinStr.c_str() );
            sendData(joinCStr);
            joinMessageSent = true;
        }
        else {
            msgHandle(buf);
        }
 
        //break if connection closed
        if (numbytes==0) {
            printf("CONNECTION CLOSED\n");
            break;
        }
    }
}
Exemple #6
0
void ircInterface::onMessage(std::string msg){
/*	while(pkge.find("\r\n") != std::string::npos){
		std::string msg = pkge.substr(0, pkge.find("\r\n"));
		pkge = pkge.substr(pkge.find("\r\n") + 2);
*/
		//std::cout << "ircInterface: raw message is : "<<msg<<std::endl;
		ircLog::instance()->logf(FILENAME, "raw message is: %s", msg.c_str());
		
		//alot of the control strings will start with  the type sperated from the 
		//contents of the message with a space
		std::string type = msg.substr(0, msg.find_first_of(' '));


		//first check for messages that start with message names
		//check for ping
		if(!type.compare(PING))
		{
			_connStatus->pingRcvd();	
			sendPong();
			return;
		}

		else if(!type.compare(ERROR))
		{	
			//TODO need to figure out hwat to do here
			//for now lets just try and not spam the other levels
			return;
		}

		else if(!type.compare("IRCERROR"))
		{
			//handle connection errors in conn status
			_connStatus->connectionIoError();

		}

		//now check for messages that start with nicks or server titles
		else 
		{	
			_connStatus->pingRcvd();	
			//type is actually a prefix containing the host mask etc
			std::string prefix = type;
			// the actual message past the prefix
			msg = msg.substr(msg.find_first_of(' ')+1);
			//the first part of that message should be the type
			type = msg.substr(0, msg.find_first_of(' '));

			//check first to see if it is a private message
			//most irc messaages are private messages
			if(!type.compare(PRIVMSG))
			{
				handle_privmsg(msg, prefix);
			}
			else if(!type.compare(NOTICE))
			{	
				if(_connStatus->state() == CS_IDLE)
				{
				 	_connStatus->connected();
				}
				handle_notice(msg, prefix);
			}
			else if(!type.compare(QUIT))

			{
				ircEvent e = handle_quit(msg, prefix);
				notifyEvent(e);
			}
			else if(!type.compare(JOIN))
			{
				ircEvent e = handle_join(msg, prefix);
				notifyEvent(e);
			}
			else if(!type.compare(PART))
			{
				ircEvent e = handle_part(msg, prefix);
				notifyEvent(e);
			}

			else if(!type.compare(NICK))
			{
				ircEvent e = handle_nick(msg, prefix);
				notifyEvent(e);
			}

			else if(!type.compare(INSPIRCDVARS))
			{
				handle_vars(msg);
			}

			else if(!type.compare(NICKLIST))
			{
				//add function to parse the nicklist
				std::vector<ircEvent> e = handle_nicklist(msg);
				for(unsigned int i = 0; i < e.size(); ++i)
				{
					notifyEvent(e[i]);
				}
			}
			else if(!type.compare("001"))
			{
				_connStatus->registered();
			}
		}
//	}
}
 }    bool
 RTMPSession::handleMessage(uint8_t *p, uint8_t msgTypeId)
 {
     bool ret = true;
     
     switch(msgTypeId) {
         case RTMP_PT_BYTES_READ:
         {
             //DLog("received bytes read: %d\n", get_be32(p));
         }
             break;
             
         case RTMP_PT_CHUNK_SIZE:
         {
             unsigned long newChunkSize = get_be32(p);
             DLog("Request to change incoming chunk size from %zu -> %zu\n", m_inChunkSize, newChunkSize);
             m_inChunkSize = newChunkSize;
         }
             break;
             
         case RTMP_PT_PING:
         {
             DLog("received ping, sending pong.\n");
             sendPong();
         }
             break;
             
         case RTMP_PT_SERVER_WINDOW:
         {
             DLog("received server window size: %d\n", get_be32(p));
         }
             break;
             
         case RTMP_PT_PEER_BW:
         {
             DLog("received peer bandwidth limit: %d type: %d\n", get_be32(p), p[4]);
         }
             break;
             
         case RTMP_PT_INVOKE:
         {
             DLog("Received invoke\n");
             handleInvoke(p);
         }
             break;
         case RTMP_PT_VIDEO:
         {
             DLog("received video\n");
         }
             break;
             
         case RTMP_PT_AUDIO:
         {
             DLog("received audio\n");
         }
             break;
             
         case RTMP_PT_METADATA:
         {
             DLog("received metadata\n");
         }
             break;
             
         case RTMP_PT_NOTIFY:
         {
             DLog("received notify\n");
         }
             break;
             
         default:
         {
             DLog("received unknown packet type: 0x%02X\n", msgTypeId);
             ret = false;
         }
             break;
     }
     return ret;
 }
Exemple #8
0
bool IrcBot::bot()
{
    char *text;
    char buf[1024];
    int bytes_read;
    int bytes_send;

    string sendCommands[5] = { "PONG", "USER "+userName+" 8 * :"+userName, "NICK "+nickName, "PRIVMSG nickserv identify "+userPass, "JOIN "+channelName };

    printf("Connecting to %s:%s\nNick: %s | Channel: %s\n", hostName.c_str(), portString.c_str(), nickName.c_str(), channelName.c_str());

    ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;
    const char *sendbuf = "\nPONG :Bot\n";
    char recvbuf[DEFAULT_BUFLEN] = { };
    int recvbuflen = DEFAULT_BUFLEN;

    #ifdef WIN32
    // start WinSock Initialization
    WSADATA wsaData;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }
    #endif // WIN32

    ZeroMemory( &hints, sizeof(hints) );
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    iResult = getaddrinfo(hostName.c_str(), portString.c_str(), &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        #ifdef WIN32
        WSACleanup();
        #endif // WIN32
        return 1;
    }

    // Attempt to connect to an address until one succeeds
    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            return 1;
        }

        // Connect to server.
        iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR)
        {
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (ConnectSocket == INVALID_SOCKET) {
        printf("Unable to connect to server!\n");
        #ifdef WIN32
        WSACleanup();
        #endif // WIN32
        return 1;
    }

    // Send an initial buffer
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if(DEBUG == true)
        printf("Sendbuf: %s\n", sendbuf);
    if (iResult == SOCKET_ERROR)
    {
        #ifdef WIN32
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        #endif // WIN32
        return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

    // Receive until the peer closes the connection
    int count = 0;
    while(1)
    {
        count++;

        switch(count)
        {
            case 2:
                // we send data to server after 3 counts
                // nick
                sendCommand(ConnectSocket, "\nUSER %s Bot Bot : %s\n", userName.c_str(), userName.c_str());
                // user
                sendCommand(ConnectSocket, "\nNICK %s\r\n", nickName.c_str());
                break;
            case 11:
                // register
                sendCommand(ConnectSocket, "\nPRIVMSG nickserv identify %s\r\n", userPass.c_str());
                break;
            case 12:
                // we join channel
                sendCommand(ConnectSocket, "\nJOIN %s\r\n", channelName.c_str());
            default:
                break;
        }

        // Recv and print data
        bytes_read = recv(ConnectSocket, buf, MAXDATASIZE-1, 0);
        buf[bytes_read]='\0';
        cout << buf << endl;
        // buf is the data that is recieved

        // pass buffer to message handler
        msgHandler(buf);

        // if we get ping
        if(charSearch(buf,"PING"))
        {
            sendPong(buf);
        }

        //break if connection closed
        if(bytes_read == 0)
        {
            cout << "Connection closed!" << endl;
            cout << timeNow() << endl;

            break;
        }
    }
#ifdef WIN32
    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
#elif LINUX
    close(ConnectSocket);
#endif
    return true;
}
err_t WebsocketClient::onReceive(pbuf* buf)
{
	if (buf == NULL)
	{
		// Disconnected, close it
		TcpClient::onReceive(buf);
	}
	else
	{
		uint16_t size = buf->tot_len;
		uint8_t* data = new uint8_t[size];

		pbuf_copy_partial(buf, data, size, 0);

		switch (_mode)
		{
		case wsMode::Connecting:
			if (_verifyKey((char*)data, size) == true)
			{
				_mode = wsMode::Connected;
				//   debugf("Key Verified. Websocket Handshake completed");
				sendPing();
			}
			else
			{
				_mode = wsMode::Disconnected; // Handshake was not proper.
			}

			if (wsConnect)
			{
				wsConnect(*this, _mode);
			}
			break;

		case wsMode::Connected:
			WebsocketFrameClass wsFrame;
			do
			{
				if (wsFrame.decodeFrame(data, size))
				{
					switch (wsFrame._frameType)
					{
					case WSFrameType::text:
					{
//						debugf("Got text frame");
						String msg;
						msg.setString((char*)wsFrame._payload, wsFrame._payloadLength);
						if (wsMessage)
						{
							wsMessage(*this, msg.c_str());
						}
						break;
					}
					case WSFrameType::binary:
					{
//						debugf("Got binary frame");
						if (wsBinary)
						{
							wsBinary(*this, wsFrame._payload, wsFrame._payloadLength);
						}
						break;
					}
					case WSFrameType::close:
					{
						debugf("Got Disconnect request from server.\n");
						//RFC requires we return a close op code before closing the connection
						disconnect();
						break;
					}
					case WSFrameType::ping:
					{
						debugf("Got ping ...");
						sendPong(); //Need to send Pong in response to Ping
						break;
					}
					case WSFrameType::pong:
					{
						debugf("Got pong ...");
						//A pong can contain app data, but shouldnt if we didnt send any...
						break;
					}
					case WSFrameType::error:
					{
						debugf("ERROR parsing frame!");
						break;
					}
					case WSFrameType::incomplete:
					{
						debugf("INCOMPLETE websocket frame!");
						break;
					}
					default:
					{
						debugf("Unknown frameType: %d", wsFrame._frameType);
						break;
					}
					}
				}
			}
			while (wsFrame._nextReadOffset > 0);

			break;
		}

		delete[] data;
		TcpClient::onReceive(buf);
	}
}