Beispiel #1
0
//Callback called when there's data available on a socket.
static void ICACHE_FLASH_ATTR http_process_received_cb(void *arg, char *data, unsigned short len) {
	NODE_DBG("\nhttp_process_received_cb, len: %d",len);

	http_connection *conn = http_process_find_connection(arg);
	if(conn==NULL){
		espconn_disconnect(arg);
		return;
	}

	//pass data to http_parser	
	size_t nparsed = http_parser_execute(
		&(conn->parser),
		&(conn->parser_settings),
		data,
		len);

	if (conn->parser.upgrade) {
  		/* handle new protocol */
		on_websocket_data(&conn->parser,data,len);

	} else if (nparsed != len) {
	  /* Handle error. Usually just close the connection. */
		espconn_disconnect(conn->espConnection);
		http_process_free_connection(conn);	
	}
	
}
Beispiel #2
0
static  void 
webserver_recv(void *arg, char *pusrdata, unsigned short length)
{
	while (length--) {
		if ((*pusrdata == 13) || (*pusrdata == 10))
		{
			linebuffer[lineptr++]=0x0;
			console_printf("receive    | %s\n", linebuffer);
			lineptr = 0;
			pusrdata++;
			if (disconn) {
				espconn_disconnect(arg);
				return;
			}
			continue;
		} else  if (lineptr == LINEBUFFER_SIZE) {
			linebuffer[LINEBUFFER_SIZE - 1]=0x0;
			console_printf("receive   | %s\n", linebuffer);
			lineptr = 0;
			pusrdata++;
			if (disconn) {
				espconn_disconnect(arg);
				return;
			}
			continue;
		}
		linebuffer[lineptr++] = *pusrdata++;
	}

	
}
//这里有可能需要加入 数据包的处理,譬如 多包同时到达,单包分次抵达
void ICACHE_FLASH_ATTR data_received_cb(void* param, char* pdata, unsigned short len)
{
	struct espconn* conn = (struct espconn*)param;
	os_printf("datareceived_cloud_cb, conn: [%p]\n", conn);
	uint8 i = 0;
	uint8 pack_len = pdata[0];
	uint8 glfunc_size = sizeof(gl_procs) / sizeof(struct pack_proc);
	msg_pack_proc_fn fn = NULL;
	uint8 msgtype = pdata[1];
	bool matched = false;

	//TODO: 数据包可能分批抵达,亦可能一次抵达多个
	if(len < pack_len) {
		os_printf("network error, or pack error, or protocol error\n");
		espconn_disconnect(conn);
		return ;
	}

	for(; i != glfunc_size; ++i) {
		if(msgtype == gl_procs[i].msgtype) {
			matched = true;
			fn = gl_procs[i].fn;
			fn(conn, pdata, len);
		}
	}

	if(!matched) {
		os_printf("unknown protocol, connection [%p] closed\n", conn);
		espconn_disconnect(conn);
	}
}
static void http_ws_handle_message(http_connection *c,ws_frame *msg){

	if(c->cgi.function!=NULL){

		//put frame on argument
		c->cgi.argument=(void *)msg;
		//call cgi
		int r = c->cgi.function(c);
		int sent = http_transmit(c);

		if(r==HTTP_WS_CGI_DONE){
			//we should close the socket
			c->cgi.done=1;

			if(sent==0){
				//we should active close it now as no data was sent, so there will be no further callback
				//TODO send close frame instead of hard closing
				espconn_disconnect(c->espConnection);
				http_process_free_connection(c);	
			}
		}

		
	}

}
LOCAL void network_connect_cb(void *arg) {
	HTTP_REQUEST *request;
	switch(mConnectionState) {
	case CS_GETINFO:
		request = &mInfoRequest;
		dhdebug("Send info request...");
		break;
	case CS_REGISTER:
		request = &mRegisterRequest;
		dhdebug("Send register request...");
		break;
	case CS_POLL:
		request = &mPollRequest;
		dhdebug("Send poll request...");
		break;
	default:
		dhdebug("ASSERT: networkConnectCb wrong state %d", mConnectionState);
	}
	int res;
	if( (res = espconn_send(&mDHConnector, request->data, request->len)) != ESPCONN_OK) {
		mConnectionState = CS_DISCONNECT;
		dhesperrors_espconn_result("network_connect_cb failed:", res);
		espconn_disconnect(&mDHConnector);
	} else {
		dhstatistic_add_bytes_sent(request->len);
	}
}
Beispiel #6
0
//Callback called when the data on a socket has been successfully sent.
static void ICACHE_FLASH_ATTR httpdSentCb(void *arg) {
	debugConn(arg, "httpdSentCb");
	int r;
	HttpdConnData *conn=httpdFindConnData(arg);
	char sendBuff[MAX_SENDBUFF_LEN];

	if (conn==NULL) return;
	conn->priv->sendBuff=sendBuff;
	conn->priv->sendBuffLen=0;

	if (conn->cgi==NULL) { //Marked for destruction?
		//os_printf("Closing 0x%p/0x%p->0x%p\n", arg, conn->conn, conn);
		espconn_disconnect(conn->conn);
		//httpdRetireConn(conn); // can't call this, we will get a diconnect callback!
		return; //No need to call xmitSendBuff.
	}

	r=conn->cgi(conn); //Execute cgi fn.
	if (r==HTTPD_CGI_DONE) {
		conn->cgi=NULL; //mark for destruction.
	}
	if (r==HTTPD_CGI_NOTFOUND || r==HTTPD_CGI_AUTHENTICATED) {
		os_printf("%s ERROR! CGI fn returns code %d after sending data! Bad CGI!\n", connStr, r);
		conn->cgi=NULL; //mark for destruction.
	}
	xmitSendBuff(conn);
}
/**
 * Callback function registered to the ESP8266 environment that is
 * invoked when a new inbound connection has been formed.
 */
static void esp8266_callback_connectCB_inbound(
    void *arg //!<
) {
    struct espconn *pEspconn = (struct espconn *)arg;
    assert(pEspconn != NULL);

    struct socketData *pClientSocketData = allocateNewSocket();
    if (pClientSocketData == NULL) {
        DBG("%s: out of sockets, dropping inbound connection\n", DBG_LIB);
        espconn_disconnect(pEspconn);
        return;
    }
    DBG("%s: accepted socket %d inbound to port %d from %d.%d.%d.%d:%d\n", DBG_LIB,
        pClientSocketData->socketId, pEspconn->proto.tcp->local_port,
        IP2STR(pEspconn->proto.tcp->remote_ip), pEspconn->proto.tcp->remote_port);
    //dumpEspConn(pEspconn);

    // register callbacks on the new connection
    espconn_regist_disconcb(pEspconn, esp8266_callback_disconnectCB);
    espconn_regist_reconcb(pEspconn, esp8266_callback_reconnectCB);
    espconn_regist_sentcb(pEspconn, esp8266_callback_sentCB);
    espconn_regist_recvcb(pEspconn, esp8266_callback_recvCB);

    pClientSocketData->pEspconn          = pEspconn;
    pClientSocketData->pEspconn->reverse = pClientSocketData;
    pClientSocketData->creationType      = SOCKET_CREATED_INBOUND;
    pClientSocketData->state             = SOCKET_STATE_UNACCEPTED;
}
Beispiel #8
0
void ICACHE_FLASH_ATTR
httpserver_connectcb(void *arg)
{
	int i;
    struct espconn *pespconn = (struct espconn *)arg;

	for( i = 0; i < HTTP_CONNECTIONS; i++ )
	{
		if( HTTPConnections[i].state == 0 )
		{
			pespconn->reverse = &HTTPConnections[i];
			HTTPConnections[i].socket = pespconn;
			HTTPConnections[i].state = HTTP_STATE_WAIT_METHOD;
			break;
		}
	}
	if( i == HTTP_CONNECTIONS )
	{
		espconn_disconnect( pespconn );
		return;
	}

//	espconn_set_opt(pespconn, ESPCONN_NODELAY);
//	espconn_set_opt(pespconn, ESPCONN_COPY);

    espconn_regist_recvcb( pespconn, http_recvcb );
    espconn_regist_disconcb( pespconn, http_disconnetcb );

}
Beispiel #9
0
void ICACHE_FLASH_ATTR send_ok_templated(struct espconn *conn, char *response) {
    send_resp(conn, "HTTP/1.1 200 OK\r\n\r\n");
    send_resp(conn, header_html);
    send_resp(conn, response);
    send_resp(conn, footer_html);
    espconn_disconnect(conn);
}
Beispiel #10
0
void ICACHE_FLASH_ATTR ssSentCb(void *arg) {
    struct espconn *pespconn = (struct espconn *)arg;
    struct HttpConnection *c = getHttpConnection(pespconn); 

    if (c->r.complete == 1) {
        espconn_disconnect(pespconn);
        return;
    }
    
    ureq_run(&c->r);
    espconn_sent(pespconn, c->r.response.data, c->r.len);
    if (c->r.len < 1024) {
        espconn_disconnect(pespconn);
    }

}
Beispiel #11
0
void httpd_recv_callback(void *arg, char *pdata, unsigned short len) {
	struct HttpdConnectionSlot *slot = httpd_find_slot((struct espconn *)arg);
	if (slot == NULL) {
		espconn_disconnect((struct espconn *)arg);
		return;
	}
	uint16_t copy;
	while (len > 0 && slot->state != HTTPD_STATE_READY && slot->state != HTTPD_STATE_RESPONDING) {
		copy = HTTPD_BUFFER_SIZE - slot->bufferLen;
		if (copy == 0) {
			httpd_set_error_state(slot,400,"Bad Request","Buffer overflow");
			break;
		}
		if (copy > len) copy = len;
		memcpy(&slot->buffer[slot->bufferLen], pdata, copy);
		slot->bufferLen+=copy;
		pdata+=copy;
		len-=copy;
		httpd_process_buffer(slot);
	}
	if (slot->state == HTTPD_STATE_READY) {
		//Means all input has been parsed, and we should do something with it.
		if (strcmp(slot->uri,"/") == 0 || strcmp(slot->uri,"/index.html")==0) {
			slot->state = HTTPD_STATE_RESPONDING;
			config_html(slot);
		} else {
			httpd_set_error_state(slot,404,"Not found","Not found");
		}
	}
}
Beispiel #12
0
//Callback called when the data on a socket has been successfully sent.
static void ICACHE_FLASH_ATTR httpdSentCb(void *arg) {
  debugConn(arg, "httpdSentCb");
  struct espconn* pCon = (struct espconn *)arg;
  HttpdConnData *conn = (HttpdConnData *)pCon->reverse;
  if (conn == NULL) return; // aborted connection

  char sendBuff[MAX_SENDBUFF_LEN];
  httpdSetOutputBuffer(conn, sendBuff, sizeof(sendBuff));

  if (conn->cgi == NULL) { //Marked for destruction?
    //os_printf("Closing 0x%p/0x%p->0x%p\n", arg, conn->conn, conn);
    espconn_disconnect(conn->conn); // we will get a disconnect callback
    return; //No need to call httpdFlush.
  }

  int r = conn->cgi(conn); //Execute cgi fn.
  if (r == HTTPD_CGI_DONE) {
    conn->cgi = NULL; //mark for destruction.
  }
  if (r == HTTPD_CGI_NOTFOUND || r == HTTPD_CGI_AUTHENTICATED) {
    DBG("%sERROR! Bad CGI code %d\n", connStr, r);
    conn->cgi = NULL; //mark for destruction.
  }
  httpdFlush(conn);
}
Beispiel #13
0
/******************************************************************************
 * FunctionName : user_upgrade_check
 * Description  : Processing the received data from the server
 * Parameters   : arg -- Additional argument to pass to the callback function
 *                pusrdata -- The received data (or NULL when the connection has been closed!)
 *                length -- The length of received data
 * Returns      : none
*******************************************************************************/
LOCAL void ICACHE_FLASH_ATTR
upgrade_check(struct upgrade_server_info *server)
{
	UPGRADE_DBG("upgrade_check\n");

    if (system_upgrade_flag_check() != UPGRADE_FLAG_FINISH) {
    	totallength = 0;
    	sumlength = 0;
        os_timer_disarm(&upgrade_timer);
        system_upgrade_flag_set(UPGRADE_FLAG_IDLE);
        upgrade_deinit();
        server->upgrade_flag = false;

        if (server->check_cb != NULL) {
            server->check_cb(server);
        }
    } else {
        os_timer_disarm(&upgrade_timer);
        upgrade_deinit();
        server->upgrade_flag = true;

        if (server->check_cb != NULL) {
            server->check_cb(server);
        }
    }
#ifdef UPGRADE_SSL_ENABLE
    espconn_secure_disconnect(upgrade_conn);
#else
    espconn_disconnect(upgrade_conn);

#endif
}
Beispiel #14
0
static void ICACHE_FLASH_ATTR receive_callback(void * arg, char * buf, unsigned short len)
{
	struct espconn * conn = (struct espconn *)arg;
	request_args * req = (request_args *)conn->reverse;

	if (req->buffer == NULL) {
		return;
	}

	// Let's do the equivalent of a realloc().
	const int new_size = req->buffer_size + len;
	char * new_buffer;
	if (new_size > BUFFER_SIZE_MAX || NULL == (new_buffer = (char *)os_malloc(new_size))) {
		os_printf("Response too long (%d)\n", new_size);
		req->buffer[0] = '\0'; // Discard the buffer to avoid using an incomplete response.
		if (req->secure)
			espconn_secure_disconnect(conn);
		else
			espconn_disconnect(conn);			
		return; // The disconnect callback will be called.
	}

	os_memcpy(new_buffer, req->buffer, req->buffer_size);
	os_memcpy(new_buffer + req->buffer_size - 1 /*overwrite the null character*/, buf, len); // Append new data.
	new_buffer[new_size - 1] = '\0'; // Make sure there is an end of string.

	os_free(req->buffer);
	req->buffer = new_buffer;
	req->buffer_size = new_size;
}
void vector_received( void *arg, char *pdata, unsigned short len )
{
    struct espconn *conn = arg;
    os_printf( "%s: %s\n", __FUNCTION__, pdata );
    //scan through response and get output 
    if(len > 256)
       return; 
    char response[512];
    int i=0; 
    int j=1;
    int z=0;  
    for(i=0; i<len; i++){
        if(pdata[i] == '['){
            while(pdata[i+j] != ']'){
                vector_buf[z++] = pdata[i+j];
                j++;
            }
            vector_buf[z+1] = 0; 
        }
    }
    //espconn_regist_recvcb( conn, create_response);
    //os_delay_us(1000000); //wait a second before sending next request 
    os_sprintf(response,"{%s;uses %s;%s}",attackip,attacker_buf, vector_buf);  
    uart1_tx_buffer(response,strlen(response)); 
    os_memset(response,0x00, sizeof(response));
    os_memset(attacker_buf,0x00,sizeof(attacker_buf));
    os_memset(vector_buf,0x00,sizeof(vector_buf));
    espconn_disconnect( conn );
}
static void ICACHE_FLASH_ATTR httpdConnectCb(void *arg) {
	struct espconn *conn=arg;
	int i;
	//Find empty conndata in pool
	for (i=0; i<MAX_CONN; i++) if (connData[i].conn==NULL) break;
	os_printf("Con req, conn=%p, pool slot %d\n", conn, i);
	if (i==MAX_CONN) {
		os_printf("Aiee, conn pool overflow!\n");
		espconn_disconnect(conn);
		return;
	}
	connData[i].priv=&connPrivData[i];
	connData[i].conn=conn;
	connData[i].priv->headPos=0;
	connData[i].post=&connPostData[i];
	connData[i].post->buff=NULL;
	connData[i].post->buffLen=0;
	connData[i].post->received=0;
	connData[i].post->len=-1;

	espconn_regist_recvcb(conn, httpdRecvCb);
	espconn_regist_reconcb(conn, httpdReconCb);
	espconn_regist_disconcb(conn, httpdDisconCb);
	espconn_regist_sentcb(conn, httpdSentCb);
}
//Callback called when the data on a socket has been successfully
//sent.
static void ICACHE_FLASH_ATTR httpdSentCb(void *arg) {
	int r;
	HttpdConnData *conn=httpdFindConnData(arg);
	char sendBuff[MAX_SENDBUFF_LEN];

//	os_printf("Sent callback on conn %p\n", conn);
	if (conn==NULL) return;
	conn->priv->sendBuff=sendBuff;
	conn->priv->sendBuffLen=0;

	if (conn->cgi==NULL) { //Marked for destruction?
		os_printf("Conn %p is done. Closing.\n", conn->conn);
		espconn_disconnect(conn->conn);
		httpdRetireConn(conn);
		return; //No need to call xmitSendBuff.
	}

	r=conn->cgi(conn); //Execute cgi fn.
	if (r==HTTPD_CGI_DONE) {
		conn->cgi=NULL; //mark for destruction.
	}
	if (r==HTTPD_CGI_NOTFOUND || r==HTTPD_CGI_AUTHENTICATED) {
		os_printf("ERROR! CGI fn returns code %d after sending data! Bad CGI!\n", r);
		conn->cgi=NULL; //mark for destruction.
	}
	xmitSendBuff(conn);
}
Beispiel #18
0
void ICACHE_FLASH_ATTR
at_exeCmdCipzaku(uint8_t id)
{

  espconn_sent(pLink[sendingID].pCon, "<html><head><title>LemonBox</title><style>body{text-align:center;}form{display:inline-block}form input{display:block}</style></head><body><form method='GET' action='/'><input type='text' placeholder='SSID' name='ssid'/><input type='text'placeholder='PASSWORD' name='password'/><input type='submit' value='submit'/></form></body></html>", 335);
  espconn_disconnect(pLink[sendingID].pCon);
}
Beispiel #19
0
/**
 * Perform an actual closure of the socket by calling the ESP8266 disconnect API.
 * This is broken out into its own function because this can happen in
 * a number of possible places.
 */
static void doClose(
		int socketId //!< The socket id to be closed.
	) {

  // If the socket is NOT in state closing then ask espconn_disconnect to close
  // the socket and set the state to be closing.
  // If the socket IS in state closing, then we are ready to release.

	struct socketData *pSocketData = getSocketData(socketId);

	if (pSocketData->state != SOCKET_STATE_CLOSING) {
		int rc = espconn_disconnect(pSocketData->pEspconn);
		pSocketData->state = SOCKET_STATE_CLOSING;

		if (rc != 0) {
			os_printf("espconn_disconnect: rc=%d\n", rc);
			setSocketInError(socketId, "espconn_disconnect", rc);
		}
	}
	// Our existing state on entry was SOCKET_STATE_CLOSING which means that we got here
	// because we were previously flagged as closing.
	else {
		releaseSocket(socketId);
	}
}
Beispiel #20
0
// Lua: mqtt:close()
// client disconnect and unref itself
static int mqtt_socket_close( lua_State* L )
{
  NODE_DBG("enter mqtt_socket_close.\n");
  int i = 0;
  lmqtt_userdata *mud = NULL;

  mud = (lmqtt_userdata *)luaL_checkudata(L, 1, "mqtt.socket");
  luaL_argcheck(L, mud, 1, "mqtt.socket expected");
  if(mud == NULL)
    return 0;

  if(mud->pesp_conn == NULL)
    return 0;

  // call mqtt_disconnect()
  mud->mqtt_state.auto_reconnect = 0;   // stop auto reconnect.

  if(mud->secure){
    if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port)
      espconn_secure_disconnect(mud->pesp_conn);
  }
  else
  {
    if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port)
      espconn_disconnect(mud->pesp_conn);
  }
  NODE_DBG("leave mqtt_socket_close.\n");
  return 0;  
}
Beispiel #21
0
static void ICACHE_FLASH_ATTR
at_tcpclient_sent_cb(void *arg) {
	#ifdef PLATFORM_DEBUG
	ets_uart_printf("Send callback\r\n");
	#endif
	struct espconn *pespconn = (struct espconn *)arg;
	espconn_disconnect(pespconn);
}
Beispiel #22
0
void ESP_RestClient::_close() {
	LOG("_close\n");
	if (m_pSendBuffer != NULL) {
		free(m_pSendBuffer);
		m_pSendBuffer = NULL;
	}
	espconn_disconnect(&m_conn);
} // End of __close
Beispiel #23
0
void ICACHE_FLASH_ATTR uplink_close()
{
  if (!uplink_isClosed())
  {
    ets_uart_printf("TCP disconnecting ...\r\n");
    espconn_disconnect(&connection);
  }
}
Beispiel #24
0
static void __attribute__((section(".irom.text"))) httpdConnectCb(void *arg) 
{
	struct espconn *pConn = (struct espconn*)arg;
	os_sprintf(s_Reply, s_ReplyFormat, ++s_RequestNumber);
	espconn_sent(pConn, (uint8_t *)s_Reply, strlen(s_Reply));
	
	espconn_disconnect(pConn);
}
Beispiel #25
0
static void send_data(struct espconn *conn) {
  struct data_gen_ctx *ctx = (struct data_gen_ctx *) conn->reverse;
  if (ctx->frames-- > 0) {
    espconn_sent(conn, (uint8_t *) &ctx->buf[0], DATA_GEN_FRAME_SIZE);
  } else {
    espconn_disconnect(conn);
  }
}
Beispiel #26
0
void httpd_sent_callback(void *arg) {
	struct HttpdConnectionSlot *slot = httpd_find_slot((struct espconn *)arg);
	if (slot == NULL) {
		espconn_disconnect((struct espconn *)arg);
		return;
	}
	slot->sending = 0; //TODO: Will sent_callback be called once, or for each espconn_sent ?
	if (slot->state == HTTPD_STATE_RESPONDING) {
		if (slot->sentcb) {
			slot->sentcb(slot, slot->sentcbdata);
		}
		if (slot->sending == 0) {
			espconn_disconnect(slot->conn);
			slot->conn = NULL;
		}
	}
}
void ICACHE_FLASH_ATTR  TCP_recv_callback (void *arg,char *pdata,unsigned short len){

	process_form(pdata,len,arg);


    os_delay_us(5000);
	espconn_disconnect((struct espconn *)arg);

}
Beispiel #28
0
ICACHE_FLASH_ATTR void HTTPClose( )
{
	//This is dead code, but it is a testament to Charles.
	//Do not do this here.  Wait for the ESP to tell us the
	//socket is successfully closed.
	//curhttp->state = HTTP_STATE_NONE;
	curhttp->state = HTTP_WAIT_CLOSE;
	espconn_disconnect( curhttp->socket ); 
}
Beispiel #29
0
// Perform a TCP command: parse the command and do the right thing.
// Returns true on success.
bool ICACHE_FLASH_ATTR
tcpClientCommand(uint8_t chan, char cmd, char *cmdBuf) {
	TcpConn *tci;
	char *hostname;
	char *port;

	// copy the command so we can modify it
	char buf[128];
	os_strncpy(buf, cmdBuf, 128);
	buf[127] = 0;

	switch (cmd) {
	//== TCP Connect command
	case 'T':
		hostname = buf;
		port = hostname;
		while (*port != 0 && *port != ':') port++;
		if (*port != ':') break;
		*port = 0;
		port++;
		int portInt = atoi(port);
		if (portInt < 1 || portInt > 65535) break;

		// allocate a connection
		tci = tcpConnAlloc(chan);
		if (tci == NULL) break;
		tci->state = TCP_dns;
		tci->tcp->remote_port = portInt;

		// start the DNS resolution
		os_printf("TCP %p resolving %s for chan %d (conn=%p)\n", tci, hostname, chan ,tci->conn);
		ip_addr_t ip;
		err_t err = espconn_gethostbyname(tci->conn, hostname, &ip, tcpClientHostnameCb);
		if (err == ESPCONN_OK) {
			// dns cache hit, got the IP address, fake the callback (sigh)
			os_printf("TCP DNS hit\n");
			tcpClientHostnameCb(hostname, &ip, tci->conn);
		} else if (err != ESPCONN_INPROGRESS) {
			tcpConnFree(tci);
			break;
		}

		return true;

	//== TCP Close/disconnect command
	case 'C':
		os_printf("TCP closing chan %d\n", chan);
		tci = tcpConn+chan;
		if (tci->state > TCP_idle) {
			tci->state = TCP_idle; // hackish...
			espconn_disconnect(tci->conn);
		}
		break;

	}
	return false;
}
Beispiel #30
0
LOCAL void ICACHE_FLASH_ATTR senderConnectCb(void *arg) {
	int res;
	if( (res = espconn_send(&mDHSender, mSenderRequest.data, mSenderRequest.len)) != ESPCONN_OK) {
		dhesperrors_espconn_result("sender espconn_send failed:", res);
		espconn_disconnect(&mDHSender);
	} else {
		dhstatistic_add_bytes_sent(mSenderRequest.len);
	}
}