/** * @brief This function processes the delete port to IGD(Internet Gateway Device). * @return 0: success, -2: Invalid UPnP Step, -1: reply packet timeout, 1: received xml parse error, other: UPnP error code */ signed short DeletePortProcess( SOCKET sockfd, /**< a socket number. */ const char* protocol, /**< a procotol name. "TCP" or "UDP" */ const unsigned int extertnal_port /**< an external port number. */ ) { short len=0; long endTime=0; uint32 ipaddr; uint16 port; // Check UPnP Step if(UPnP_Step < 2) return -2; // Make "Delete Port" XML(SOAP) memset(content, '\0', MAX_BUFFER); MakeSOAPDeleteControl(content, protocol, extertnal_port); // Make HTTP POST Header memset(send_buffer, '\0', MAX_BUFFER); len = strlen(content); MakePOSTHeader(send_buffer, len, DELETE_PORT); strcat(send_buffer, content); #ifdef UPNP_DEBUG printf("%s\r\n", send_buffer); #endif ipaddr = inet_addr((uint8*)descIP); ipaddr = swapl(ipaddr); port = ATOI(descPORT, 10); // Connect to IGD(Internet Gateway Device) if(TCPClientOpen(sockfd, PORT_UPNP, (uint8*)&ipaddr, port) == FAIL) printf("TCP Socket Error!!\r\n"); // Send "Delete Port" Message while(GetTCPSocketStatus(sockfd) != STATUS_ESTABLISHED); TCPSend(sockfd, (void *)send_buffer, strlen(send_buffer)); // Receive Reply memset(recv_buffer, '\0', MAX_BUFFER); Delay_ms(500); endTime = my_time + 3; while (TCPRecv(sockfd, (void *)recv_buffer, MAX_BUFFER) <= 0 && my_time < endTime); // Check Receive Buffer of W5200 if(my_time >= endTime){ // Check Timeout TCPClose(sockfd); return -1; } // TCP Socket Close TCPClose(sockfd); #ifdef UPNP_DEBUG printf("\r\nReceiveData\r\n%s\r\n", recv_buffer); #endif // Parse Replied Message return parseDeletePort(recv_buffer); }
void Send_cmd(uint8 sock, char* msg) { uint16 len; char new_msg[STR_SIZE]; char dat[STR_SIZE]; if( strstr(msg,"ls") != NULL ) { TCPSend(sock,ls,strlen(ls)); } else if( strstr(msg,"get") != NULL ) { memset(dat, 0, sizeof(dat)); memset(new_msg, 0, sizeof(new_msg)); memcpy(new_msg, msg+4, strlen(msg+4)); len = sprintf(dat, "RETR %s\r\n",new_msg); TCPSend(sock, (uint8*)dat, len); } else if( strstr(msg, "put") != NULL ) { memset(dat, 0, sizeof(dat)); memset(new_msg, 0, sizeof(new_msg)); memcpy(new_msg, msg+4, strlen(msg+4)); len = sprintf(dat, "STOR %s\r\n",new_msg); TCPSend(sock, (uint8*)dat, len); bRunPutFile = 1; } else if( strstr(msg, "cd") != NULL ) { memset(dat, 0, sizeof(dat)); memset(new_msg, 0, sizeof(new_msg)); memcpy(new_msg, msg+3, strlen(msg+3)); len = sprintf(dat, "CWD %s\r\n", new_msg); TCPSend(sock, (uint8*)dat, len); } else if( strstr(msg, "bye") != NULL ) { TCPSend(sock, bye, strlen(bye) ); TCPClose(FTP_CLIENT_DTP_SOCK); TCPClose(FTP_CLIENT_PI_SOCK); JumpAddress = *(volatile unsigned long*) (ApplicationAddress + 4); Jump_To_Application = (pFunction) JumpAddress; Jump_To_Application(); while(1); } else { printf("\r\n Sorry, this FTP client only support ls, put and get commands!"); TCPClose(FTP_CLIENT_DTP_SOCK); Send_Port(sock, IP, DTP_Port); } }
/** * @brief This function gets the description message from IGD(Internet Gateway Device). * @return 0: success, -2: Invalid UPnP Step, -1: reply packet timeout, 1: received xml parse error */ signed char GetDescriptionProcess( SOCKET sockfd /**< a socket number. */ ) { char ret_value=0; long endTime=0; uint32 ipaddr; uint16 port; // Check UPnP Step if(UPnP_Step < 1) return -2; // Make HTTP GET Header memset(send_buffer, '\0', MAX_BUFFER); MakeGETHeader(send_buffer); #ifdef UPNP_DEBUG printf("%s\r\n", send_buffer); #endif ipaddr = inet_addr((uint8*)descIP); ipaddr = swapl(ipaddr); port = ATOI(descPORT, 10); // Connect to IGD(Internet Gateway Device) if(TCPClientOpen(sockfd, PORT_UPNP, (uint8*)&ipaddr, port) == FAIL) printf("TCP Socket Error!!\r\n"); // Send Get Discription Message while(GetTCPSocketStatus(sockfd) != STATUS_ESTABLISHED); TCPSend(sockfd, (void *)send_buffer, strlen(send_buffer)); // Receive Reply memset(recv_buffer, '\0', MAX_BUFFER); Delay_ms(500); endTime = my_time + 3; while (TCPRecv(sockfd, (void *)recv_buffer, MAX_BUFFER) <= 0 && my_time < endTime); // Check Receive Buffer of W5200 if(my_time >= endTime){ // Check Timeout TCPClose(sockfd); return -1; } // TCP Socket Close TCPClose(sockfd); #ifdef UPNP_DEBUG printf("\r\nReceiveData\r\n%s\r\n", recv_buffer); #endif // Parse Discription Message if((ret_value = parseDescription(recv_buffer)) == 0) UPnP_Step = 2; return ret_value; }
/* * FUNCTION: Closes an address file object * ARGUMENTS: * Request = Pointer to TDI request structure for this request * RETURNS: * Status of operation */ NTSTATUS FileCloseAddress( PTDI_REQUEST Request) { PADDRESS_FILE AddrFile = Request->Handle.AddressHandle; KIRQL OldIrql; if (!Request->Handle.AddressHandle) return STATUS_INVALID_PARAMETER; LockObject(AddrFile, &OldIrql); if (InterlockedDecrement(&AddrFile->Sharers) != 0) { /* Still other guys have open handles to this, so keep it around */ UnlockObject(AddrFile, OldIrql); return STATUS_SUCCESS; } /* We have to close this listener because we started it */ if( AddrFile->Listener ) { TCPClose( AddrFile->Listener ); } UnlockObject(AddrFile, OldIrql); DereferenceObject(AddrFile); TI_DbgPrint(MAX_TRACE, ("Leaving.\n")); return STATUS_SUCCESS; }
void loopback_udp(uint8 ch, uint16 port) { int ret; uint32 destip = 0; uint16 destport; ret = UDPRecv(ch, data_buf, TX_RX_MAX_BUF_SIZE, (uint8*)&destip, &destport); if(ret > 0) { // Received ret = UDPSend(ch, data_buf, ret, (uint8*)&destip ,destport); if(ret == ERROR_TIME_OUT) { ERR("Timeout"); UDPClose(ch); DBG("UDP Socket Close"); } } else if(ret == ERROR_NOT_UDP_SOCKET) { // Not UDP Socket, It's TCP Socket DBG("TCP Socket Close"); TCPClose(ch); } else if(ret == ERROR_CLOSED) { // Socket Closed LOGA("UDP Loop-Back Started - ch(%d)",(uint16)ch); UDPOpen(ch, port); } }
/* * Checks the file request response. */ BOOL PeerFileAccept (Connection *peer, UWORD ackstatus, UDWORD port) { Connection *flist, *fpeer; flist = PeerFileCreate (peer->serv); fpeer = ServerFindChild (flist->serv, peer->cont, TYPE_FILEDIRECT); if (!flist || !fpeer || !port || (ackstatus == TCP_ACK_REFUSE)) { if (fpeer) TCPClose (fpeer); return 0; } ASSERT_MSGDIRECT(peer); ASSERT_FILELISTEN(flist); ASSERT_FILEDIRECT(fpeer); fpeer->connect = 0; fpeer->oscar_dc_seq = 0; fpeer->port = port; fpeer->ip = peer->ip; s_repl (&fpeer->server, s_ip (fpeer->ip)); if (prG->verbose) rl_printf (i18n (2520, "Opening file transfer connection to %s:%s%ld%s... \n"), s_wordquote (fpeer->server), COLQUOTE, UD2UL (fpeer->port), COLNONE); TCPDispatchConn (fpeer); return 1; }
/***************************************************************************** Function: uint16_t SMTPEndUsage(void) Summary: Releases control of the SMTP client module. Description: Call this function to release control of the SMTP client module once an application is finished using it. This function releases the lock obtained by SMTPBeginUsage, and frees the SMTP client to be used by another application. Precondition: SMTPBeginUsage returned true on a previous call. Parameters: None Return Values: SMTP_SUCCESS - A message was successfully sent SMTP_RESOLVE_ERROR - The SMTP server could not be resolved SMTP_CONNECT_ERROR - The connection to the SMTP server failed or was prematurely terminated 1-199 and 300-399 - The last SMTP server response code ***************************************************************************/ uint16_t SMTPEndUsage(void) { if(!SMTPFlags.bits.SMTPInUse) return 0xFFFF; // Release the DNS module, if in use if(TransportState == TRANSPORT_NAME_RESOLVE) DNSEndUsage(0); // Release the TCP socket, if in use if(MySocket != INVALID_SOCKET) { TCPClose(MySocket); MySocket = INVALID_SOCKET; } // Release the SMTP module SMTPFlags.bits.SMTPInUse = false; TransportState = TRANSPORT_HOME; if(SMTPFlags.bits.SentSuccessfully) { return 0; } else { return ResponseCode; } }
/* ******************************************* */ TINT SBAErrRet(TSOCK Sock, TINT nErr) { if ( Sock > 0 ) TCPClose(Sock); return nErr; }
/* ******************************************* */ TINT SBAErrRecv(TSOCK Sock) { char szBuf[CONST_BUF]; TINT nLen; if ( Sock > 0 ) { if ( !TCPRecvData(Sock, szBuf, &nLen) ) { TCPClose(Sock); return ERT_RECV_DATA; } szBuf[nLen] = 0x00; nLen = atoi(szBuf); TCPClose(Sock); } return nLen; }
void loopback_tcps(uint8 ch, uint16 port) { int ret; int SendLen, ReSendLen; ret = TCPRecv(ch, data_buf, TX_RX_MAX_BUF_SIZE); if(ret > 0) { // Received SendLen = TCPSend(ch, data_buf, ret); if(SendLen < ret) { while(SendLen != ret) { ReSendLen = TCPReSend(ch); if(ReSendLen > 0) { SendLen += ReSendLen; } else if(ReSendLen == ERROR_WINDOW_FULL) { LOG("Window Full"); TCPClose(ch); DBG("TCP Socket Close"); while(1); } else { break; } } } } else if(ret == ERROR_NOT_TCP_SOCKET) { // Not TCP Socket, It's UDP Socket DBG("UDP Socket Close"); UDPClose(ch); } else if(ret == ERROR_CLOSED) { // Socket Closed LOGA("TCP Loop-Back Started - ch(%d)",(uint16)ch); TCPServerOpen(ch, port); } if(GetTCPSocketStatus(ch) == STATUS_CLOSE_WAIT) { // Close waiting TCPClose(ch); } }
/** @brief This Socket function open TCP server socket. @return 1 - success, 0 - fail. */ int8 TCPServerOpen(SOCKET s, uint16 port) { uint8 ret; #ifdef __DEF_IINCHIP_DBG__ printf("TCPServerOpen()\r\n"); #endif TCPClose(s); IINCHIP_WRITE(Sn_MR(s),Sn_MR_TCP); if (port != 0) { IINCHIP_WRITE(Sn_PORT0(s),(uint8)((port & 0xff00) >> 8)); IINCHIP_WRITE((Sn_PORT0(s) + 1),(uint8)(port & 0x00ff)); } else {
/***************************************************************************** Function: static BOOL HandlePossibleTCPDisconnection(SOCKET s) Summary: Internal function that checks for asynchronous TCP connection state changes and resynchs the BSD socket descriptor state to match. Description: Internal function that checks for asynchronous TCP connection state changes and resynchs the BSD socket descriptor state to match. Precondition: None Parameters: s - TCP type socket descriptor returned from a previous call to socket. This socket must be in the SKT_LISTEN, SKT_IN_PROGRESS, SKT_EST, or SKT_DISCONNECTED states. Returns: TRUE - Socket is disconnected FALSE - Socket is ***************************************************************************/ static BOOL HandlePossibleTCPDisconnection(SOCKET s) { struct BSDSocket *socket; BYTE i; BOOL bSocketWasReset; socket = &BSDSocketArray[s]; // Nothing to do if disconnection has already been handled if(socket->bsdState == SKT_DISCONNECTED) return TRUE; // Find out if a disconnect has occurred bSocketWasReset = TCPWasReset(socket->SocketID); // For server sockets, if the parent listening socket is still open, // then return this socket to the queue for future backlog processing. if(socket->isServer) { for(i = 0; i < sizeof(BSDSocketArray)/sizeof(BSDSocketArray[0]); i++) { if(BSDSocketArray[i].bsdState != SKT_BSD_LISTEN) continue; if(BSDSocketArray[i].localPort == socket->localPort) { // Nothing to do if a disconnect has not occurred if(!bSocketWasReset) return FALSE; // Listener socket is still open, so just return to the // listening state so that the user must call accept() again to // reuse this BSD socket socket->bsdState = SKT_LISTEN; return TRUE; } } } // If we get down here and the socket was reset, then this socket // should be closed so that no more clients can connect to it. However, // we can't go to the BSD SKT_CLOSED state directly since the user still // has to call closesocket() with this s SOCKET descriptor first. if(bSocketWasReset) { TCPClose(socket->SocketID); socket->bsdState = SKT_DISCONNECTED; return TRUE; } return FALSE; }
void HTTPServer(void) { if (SocketStatus & SOCK_CONNECTED) // check if somebody has connected to our TCP { if (SocketStatus & SOCK_DATA_AVAILABLE) // check if remote TCP sent data TCPReleaseRxBuffer(); // and throw it away if (SocketStatus & SOCK_TX_BUF_RELEASED) // check if buffer is free for TX { if (!(HTTPStatus & HTTP_SEND_PAGE)) // init byte-counter and pointer to webside { // if called the 1st time HTTPBytesToSend = strlen(WebSide) - 1; // get HTML length, ignore trailing zero PWebSide = (unsigned char *)WebSide; // pointer to HTML-code } if (HTTPBytesToSend > MAX_TCP_TX_DATA_SIZE) // transmit a segment of MAX_SIZE { if (!(HTTPStatus & HTTP_SEND_PAGE)) // 1st time, include HTTP-header { memcpy(TCP_TX_BUF, GetResponse, sizeof(GetResponse) - 1); memcpy(TCP_TX_BUF + sizeof(GetResponse) - 1, PWebSide, MAX_TCP_TX_DATA_SIZE - sizeof(GetResponse) + 1); HTTPBytesToSend -= MAX_TCP_TX_DATA_SIZE - sizeof(GetResponse) + 1; PWebSide += MAX_TCP_TX_DATA_SIZE - sizeof(GetResponse) + 1; } else { memcpy(TCP_TX_BUF, PWebSide, MAX_TCP_TX_DATA_SIZE); HTTPBytesToSend -= MAX_TCP_TX_DATA_SIZE; PWebSide += MAX_TCP_TX_DATA_SIZE; } TCPTxDataCount = MAX_TCP_TX_DATA_SIZE; // bytes to xfer InsertDynamicValues(); // exchange some strings... TCPTransmitTxBuffer(); // xfer buffer } else if (HTTPBytesToSend) // transmit leftover bytes { memcpy(TCP_TX_BUF, PWebSide, HTTPBytesToSend); TCPTxDataCount = HTTPBytesToSend; // bytes to xfer InsertDynamicValues(); // exchange some strings... TCPTransmitTxBuffer(); // send last segment TCPClose(); // and close connection HTTPBytesToSend = 0; // all data sent } HTTPStatus |= HTTP_SEND_PAGE; // ok, 1st loop executed } } else HTTPStatus &= ~HTTP_SEND_PAGE; // reset help-flag if not connected }
/*** void TCPSocket::close(void) ** ** Synopsis: ** Closes the socket and clears the TCPSocket instance; ** Returns the instance to a just constructed state releasing ** all resources. ** ** Parameters: ** None ** ** Return Values: ** None ** ** Errors: ** None ** ** Notes: ** ** Returns the TCPSocket instance to ** a state just as if the instance had just been ** constructed. It also, Close the connection if ** if it is still active. ** */ void TCPSocket::close(void) { if(_classState != ipsNotInitialized) { // clean out the buffer TCPDiscard(&_socket); // release the resources back to stack TCPClose(&_socket, NULL); } // reset our member variables clear(false); }
//processing http protocol , and excuting the followed fuction. void WebServer(uint8 s) { int ret; uint32 header_len=0, content_len=0, received_len=0; char sub[10]; /* http service start */ ret = TCPRecv(s, (int8*)rx_buf, MAX_URI_SIZE); if(ret > 0){ // If Received.. *(((uint8*)rx_buf)+ret) = '\0'; if(strstr(rx_buf, "Content-Length: ")){ mid((char*)rx_buf, "Content-Length: ", "\r\n", sub); content_len=atoi(sub); header_len = (uint32)(strstr(rx_buf, "\r\n\r\n") - rx_buf + 4); received_len = ret; while(received_len!=(content_len+header_len)) { ret = TCPRecv(s, (int8*)rx_buf+received_len, MAX_URI_SIZE); received_len+=ret; } *(((uint8*)rx_buf)+received_len) = '\0'; } HTTPProcessor(s, (char*)rx_buf); // request is processed memset(rx_buf,0x00,MAX_URI_SIZE); TCPDisconnect(s); } else if(ret == SOCKERR_NOT_TCP){ // Not TCP Socket, It's UDP Socket DBG("UDP Socket Close"); UDPClose(s); } else if(ret == SOCKERR_CLOSED){ // Socket Closed LOGA("HTTP Server Started - ch(%d)",(uint16)s); TCPServerOpen(s, DEFAULT_HTTP_PORT); } if(GetTCPSocketStatus(s) == SOCKERR_CLOSE_WAIT){// Close waiting TCPClose(s); } }
/***************************************************************************** * * exoHAL_SocketClose * * \param socket - socket handle * * \return None * * \brief Closes a socket * *****************************************************************************/ void exoHAL_SocketClose(long socket) { // Send everything immediately if (GenericTCPState == EX_DISCONNECT) { if (TCPIsConnected((TCP_SOCKET)exSocket) && socket_crush == 1) { TCPClose((TCP_SOCKET)exSocket); socket_crush = 0; exSocket = INVALID_SOCKET; socket = exSocket; } send_count = 0; GenericTCPState = EX_DONE; } return; }
/*** void TcpClient::close(void) ** ** Synopsis: ** Closes the socket and clears the TcpClient instance; ** Returns the instance to a just constructed state releasing ** all resources. ** ** Parameters: ** None ** ** Return Values: ** None ** ** Errors: ** None ** ** Notes: ** ** Returns the TcpClient instance to ** a state just as if the instance had just been ** constructed. It also, Close the connection if ** if it is still active. ** */ void TcpClient::close(void) { if(_hTCP < INVALID_SOCKET) { // clean out the buffer TCPDiscard(_hTCP); // release the resources back to the MAL TCPClose(_hTCP); } // we are just closed _hTCP = INVALID_SOCKET; _classState = DNETcK::NotConnected; // say the enpoints are gone too _fEndPointsSetUp = false; }
/* * FUNCTION: Closes an connection file object * ARGUMENTS: * Request = Pointer to TDI request structure for this request * RETURNS: * Status of operation */ NTSTATUS FileCloseConnection( PTDI_REQUEST Request) { PCONNECTION_ENDPOINT Connection; TI_DbgPrint(MID_TRACE, ("Called.\n")); Connection = Request->Handle.ConnectionContext; if (!Connection) return STATUS_INVALID_PARAMETER; TCPClose( Connection ); Request->Handle.ConnectionContext = NULL; TI_DbgPrint(MAX_TRACE, ("Leaving.\n")); return STATUS_SUCCESS; }
/** * @brief This function listenes the eventing message from IGD(Internet Gateway Device). */ void eventing_listener( SOCKET sockfd /**< a socket number. */ ) { uint16 len; const uint8 HTTP_OK[] = "HTTP/1.1 200 OK\r\n\r\n"; switch (getSn_SR(sockfd)) { case SOCK_ESTABLISHED: /* if connection is established */ Delay_ms(500); if((len = getSn_RX_RSR(sockfd)) > 0){ TCPRecv(sockfd, (void *)recv_buffer, len); TCPSend(sockfd, (void *)HTTP_OK, strlen((void *)HTTP_OK)); parseEventing(recv_buffer); #ifdef UPNP_DEBUG printf("\r\nReceiveData\r\n%s\r\n", recv_buffer); #endif } break; case SOCK_CLOSE_WAIT: /* If the client request to close */ if ((len = getSn_RX_RSR(sockfd)) > 0) /* check Rx data */ { TCPRecv(sockfd, (void *)recv_buffer, len); /* read the received data */ } TCPClose(sockfd); break; case SOCK_CLOSED: /* if a socket is closed */ if(TCPServerOpen(sockfd,PORT_UPNP_EVENTING) == FAIL) /* reinitialize the socket */ { printf("\r\n%d : Fail to create socket.",sockfd); } break; default: break; } }
/**************************************************************************** Function: TCP_SOCKET ChipKITClientConnect(unsigned int dwOpenVal, BYTE vRemoteHostType, unsigned short wPort, unsigned int cSecTimout) Description: This routine opens a socket and for clients only, attempts to connect to the server. DNS lookups are done if a URL is specifed for dwOpenVal and vRemoteHostType == TCP_OPEN_RAM_HOST Precondition: None Parameters: dwOpenVal - Same as in TCPOpen vRemoteHostType - Same as in TCPOpen wPort - Same as in TCPOpen cSecTimout - If this is a client connecting to a host, this is the number of seconds to wait for a successful connection to occur Returns: The valid socket if the open was successful, or INVALID_SOCKET if no sockets were avaiable or the connection was not made (in the case of a client) Remarks: This routine will attempt to wait until the connection is made for client, but will return immediately for servers as servers listen for connections. For the client case, if cSecTimout is exceeded, the connection is close and the socket released back to the stack for reuse. ***************************************************************************/ TCP_SOCKET ChipKITClientConnect(unsigned int dwOpenVal, BYTE vRemoteHostType, unsigned short wPort, unsigned int cSecTimout) { TCP_SOCKET hTCP = UNKNOWN_SOCKET; DWORD t = 0; hTCP = TCPOpen((DWORD) dwOpenVal, vRemoteHostType, (WORD) wPort, TCP_PURPOSE_DEFAULT); ChipKITPeriodicTasks(); // if it just fails, don't even attempt a retry if(hTCP == INVALID_SOCKET) { return(hTCP); } // if this is a client, we have to wait until we connect // No need to do this for servers as they connect when some one comes in on the listen if(vRemoteHostType != TCP_OPEN_SERVER) { t = TickGet(); // so we don't loop forever while(!TCPIsConnected(hTCP)) { ChipKITPeriodicTasks(); // if after 10 seconds we do not connect, just fail and clean up if( (TickGet() - t) >= (cSecTimout * TICK_SECOND)) { TCPClose(hTCP); TCPDiscard(hTCP); hTCP = INVALID_SOCKET; // make sure we run tasks again to get for the close to take effect // so don't return here, break out of the while to clean up break; } } ChipKITPeriodicTasks(); } return(hTCP); }
/*** void TcpServer::close(void) ** ** Synopsis: ** Stops Listening and closes all unaccepted sockets/connections ** and clears everything back to it's originally constructed state. ** ** Parameters: ** None ** ** Return Values: ** None ** ** Errors: ** None ** ** Notes: ** ** Returns the TcpServer instance to ** a state just as if the instance had just been ** constructed. It also, Close all connections ** and releases all resources (sockets). ** */ void TcpServer::close(void) { stopListening(); for(int i = 0; i<_cMaxPendingAllowed; i++) { if(_rghTCP[i] < INVALID_SOCKET) { // clean out the buffer TCPDiscard(_rghTCP[i]); // release the resources back to the MAL TCPClose(_rghTCP[i]); // invalidate the socket _rghTCP[i] = INVALID_SOCKET; } } clear(); }
/*** void TcpServer::stopListening(void) ** ** Synopsis: ** This stops listening on the server port, but does not shutdown TcpServer ** ** Parameters: ** None ** ** Return Values: ** None ** ** Errors: ** None ** ** Notes: ** To resume listening, just call ResumeListening ** This is a soft stop listening in that only the server stops listening on the port ** however the instance is still valid and you can continue to accept pending client. ** and you can resume the listening. ** */ void TcpServer::stopListening(void) { // DO NOT blow away pending clients. // that will be done on a close() // update the pending count so we have them all. availableClients(); if(_cPending < _cPendingMax && _rghTCP[_cPending] < INVALID_SOCKET) { // clean out the buffer TCPDiscard(_rghTCP[_cPending]); // release the resources back to the MAL TCPClose(_rghTCP[_cPending]); // only invalidate if this is the listening socket _rghTCP[_cPending] = INVALID_SOCKET; } // no longer listening _fListening = false; }
/**************************************************************************** Function: void ChipKITClientStop(TCP_SOCKET hTCP) Description: This routine closes the socket, discards the input buffer, and returns the socket to the TCPIP stack. Precondition: hTCP must be open and valid. Parameters: hTCP - The socket to close Returns: none Remarks: This is to match functionality of the Arduino Client class stop method ***************************************************************************/ void ChipKITClientStop(TCP_SOCKET hTCP) { // the MAL can hang if you attempt to close an invalid socket if(hTCP == INVALID_SOCKET || hTCP == UNKNOWN_SOCKET) { return; } // close the handle TCPClose(hTCP); // empty the receive buffer because we are killing it. TCPDiscard(hTCP); // loop until it is acknowledged to be closed do { ChipKITPeriodicTasks(); } while(TCPIsConnected(hTCP)); }
/***************************************************************************** * * Cloud_GetCmd * * \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 Cloud_GetCmd() { int length; char DataLen[10]; // int http_status = 0; char *cmp_ss = "Content-Length:"; char *cmp = cmp_ss; DWORD serverip = 0; const unsigned char server[6] = SERVERIP ; serverip = (server[3] << 24 & 0xff000000) | (server[2] << 16 & 0xff0000) | (server[1] << 8 & 0xff00) | (server[0] & 0xff); long w, r; char rev[300]; unsigned char len; char *p; unsigned char crlf = 0; int time_out = 0; int tx_buff_size = 250; int tmp_len =0 ; if(status_code == STATUS_INIT||status_code == STATUS_END){ if (sock == INVALID_SOCKET) { sock = TCPOpen(serverip, TCP_OPEN_IP_ADDRESS, HTTP_PORT, TCP_PURPOSE_TCP_CLIENT); // TCP_OPEN_RAM_HOST for using dns name as server name // TCPOpen(serverip, TCP_OPEN_IP_ADDRESS, server_port, TCP_PURPOSE_GENERIC_TCP_CLIENT); if (sock == INVALID_SOCKET) { status_code = STATUS_INIT; // LEDS_OFF(); // LEDS_ON(); return 0; } status_code = STATUS_READY; } else status_code == STATUS_READY; } else if(status_code == STATUS_READY) { if(sent_header) DelayMs(20); w = TCPIsPutReady(sock); if(w<=250ul) { return 0; } if(sent_header){ memset(header, 0, sizeof(header)); length = PostHeaderGenerate("/sendcmd.php", command, 0, 0); remain_count =0 ; sent_header = FALSE; sent_count = 0; } // LED2_ON(); LED1_OFF(); int send_len = strlen(&header[remain_count]); // LED2_ON(); LED1_OFF(); //if(send_len > 254) {LED2_ON(); LED1_OFF()}; /* The max size of sliding window for TCP packet is 254? after testing. * Don't know the reason, but if we set the number of sending data to 250, * the program works fine. * */ tmp_len = send_len>250? 250:send_len; // int tmp_len = IHMS_SocketSend(sock, &header[sent_count], send_len ); tmp_len = TCPPutArray(sock, (BYTE *) &header[remain_count], tmp_len); TCPFlush((TCP_SOCKET)sock); LED2_ON(); LED1_OFF(); if(tmp_len<send_len) { remain_count += tmp_len; return 0; } memset(header, 0, sizeof(header)); sent_count = 0; remain_count = 0; status_code = STATUS_RCV; } else if(status_code == STATUS_RCV) { DelayMs(20); r = TCPIsGetReady((TCP_SOCKET) sock); if(r<200u){ LED2_ON(); return 0;} // now read all data in RX buffer int count = 0; do { r = TCPGetArray((TCP_SOCKET)sock, (BYTE *)&rev[count], 300); count = count + r; rev[count]=0; r = TCPIsGetReady((TCP_SOCKET) sock); }while(r>0u); rev[count] = 0 ; TCPClose((TCP_SOCKET)sock); status_code = STATUS_END; sock = INVALID_SOCKET; status_code = STATUS_END; sent_header = TRUE; //now it's time to read time command = GetServerCmd(rev, "cmd="); cmd_no = GetServerCmd(rev, "no="); return 1; } return 0; }
/***************************************************************************** Function: int closesocket( SOCKET s ) Summary: The closesocket function closes an existing socket. Description: The closesocket function closes an existing socket. This function releases the socket descriptor s. Any data buffered at the socket is discarded. If the socket s is no longer needed, closesocket() must be called in order to release all resources associated with s. Precondition: None. Parameters: s - Socket descriptor returned from a previous call to socket Returns: If closesocket is successful, a value of 0 is returned. A return value of SOCKET_ERROR (-1) indicates an error. Remarks: None. ***************************************************************************/ int closesocket( SOCKET s ) { BYTE i; struct BSDSocket *socket; if( s >= BSD_SOCKET_COUNT ) return SOCKET_ERROR; socket = &BSDSocketArray[s]; if(socket->bsdState == SKT_CLOSED) return 0; // Nothing to do, so return success if(socket->SocketType == SOCK_STREAM) { if(socket->bsdState == SKT_BSD_LISTEN) { // This is a listerner handle, so when we close it we also should // close all TCP sockets that were opened for backlog processing // but didn't actually get connected for(i = 0; i < sizeof(BSDSocketArray)/sizeof(BSDSocketArray[0]); i++) { if(BSDSocketArray[i].bsdState != SKT_LISTEN) continue; if(BSDSocketArray[i].localPort == socket->localPort) { TCPClose(BSDSocketArray[i].SocketID); BSDSocketArray[i].bsdState = SKT_CLOSED; } } } else if(socket->bsdState >= SKT_LISTEN) { // For server sockets, if the parent listening socket is still open, // then return this socket to the queue for future backlog processing. if(socket->isServer) { for(i = 0; i < sizeof(BSDSocketArray)/sizeof(BSDSocketArray[0]); i++) { if(BSDSocketArray[i].bsdState != SKT_BSD_LISTEN) continue; if(BSDSocketArray[i].localPort == socket->localPort) { TCPDisconnect(socket->SocketID); // Listener socket is still open, so just return to the // listening state so that the user must call accept() again to // reuse this BSD socket socket->bsdState = SKT_LISTEN; return 0; } } // If we get down here, then the parent listener socket has // apparently already been closed, so this socket can not be // reused. Close it complete. TCPClose(socket->SocketID); } else if(socket->bsdState != SKT_DISCONNECTED) // this is a client socket that isn't already disconnected { TCPClose(socket->SocketID); } } } else //udp sockets { if(socket->bsdState == SKT_BOUND) UDPClose(socket->SocketID); } socket->bsdState = SKT_CLOSED; return 0; //success }
//**************************************************************************** // Only internal use: // TCPGenericClose callback function //**************************************************************************** int cTCPGenericClose() { TCPClose(xSocket); return 0; }
void ftp_client_PI (uint8 sock) { int ret; int idx; char msg[STR_SIZE]; uint16 status; static uint16 any_port = 50000; memset(cmd_buf, 0, sizeof(cmd_buf)); ret = TCPRecv(sock, cmd_buf, TX_RX_MAX_BUF_SIZE); if(ret > 0) // Received { for( idx=0; idx < ret; idx++ ) { if( idx == 0 ) printf("\r\n"); printf("%c",cmd_buf[idx]); } switch( status = Parse_FTPServer_Statuscode(cmd_buf) ) { case R_220: // Service ready for new user. printf("\r\nInput your User ID > "); GetInputString(msg); Send_USER_ID(sock,msg); break; case R_331: // User name okay, need password. printf("\r\nInput your Password > "); GetInputString(msg); Send_PW(sock,msg); break; case R_230: // User logged in, proceed printf("\r\nUser logged in, proceed"); TCPClose(FTP_CLIENT_DTP_SOCK); Send_Port(sock, IP, DTP_Port); break; case R_200: // 'Generic' command ok printf("\r\nInput FTP CMD > "); GetInputString(msg); Send_cmd(sock, msg); break; case R_150: // File Status ok: opening data conn bRunDTP = 1; break; case R_250: TCPClose(FTP_CLIENT_DTP_SOCK); Send_Port(sock, IP, DTP_Port); break; case R_226: /* Closing data connection. File transfer/abort successful */ TCPClose(FTP_CLIENT_DTP_SOCK); Send_Port(sock, IP, DTP_Port); break; case R_425: TCPClose(FTP_CLIENT_DTP_SOCK); Send_Port(sock, IP, DTP_Port); break; default: printf("\r\nDefault Status = %d",(uint16)status); JumpAddress = *(volatile unsigned long*) (ApplicationAddress + 4); // reset app Jump_To_Application = (pFunction) JumpAddress; Jump_To_Application(); while(1); } } else if(ret == ERROR_CLOSED || ret == ERROR_CLOSE_WAIT ) { printf("\r\n%d : FTP Client Start.\r\n",(u16)sock); if( TCPClientOpen( sock, any_port++, FTP_SERVER_IP, FTP_Server_CMD_Port ) == 0 ) printf("< Fail : Socket Connect >\r\n"); } }
void ftp_client_DTP(uint8 sock) { int len; int idx; switch( GetTCPSocketStatus(sock) ) { case STATUS_ESTABLISHED: if(bRunDTP) { bRunDTP = 0; #ifdef Debug printf("< FTP_DTP Connect OK>\r\n"); #endif } len = TCPRecv(sock, data_buf, TX_RX_MAX_BUF_SIZE); if( len > 0 ) { for( idx = 0; idx < len; idx++ ) { if( idx == 0 ) printf("\r\n"); printf("%c",data_buf[idx]); } } if( bRunPutFile ) { bRunPutFile = 0; TCPSend(sock, (void *)PUTFILE, strlen(PUTFILE)); TCPClose(sock); } break; case STATUS_CLOSE_WAIT: len = TCPRecv(sock, data_buf, TX_RX_MAX_BUF_SIZE); if( len > 0 ) { for( idx = 0; idx < len; idx++ ) { if( idx == 0 ) printf("\r\n"); printf("%c",data_buf[idx]); } } if( bRunPutFile ) { bRunPutFile = 0; TCPSend(sock, (void *)PUTFILE, strlen(PUTFILE)); } TCPClose(sock); break; case STATUS_CLOSED: TCPClose(sock); if( TCPServerOpen( sock, DTP_Port++ ) == 0 ) { printf("\r\nDTP Socket Open Error"); break; } if( DTP_Port > 70000 ) DTP_Port = FTP_Client_TCPS_Port; bRunDTP = 1; break; } }
void ReceiveEthernetCmds() { WORD wMaxGet, wBytesRead; BYTE b; static enum _TCPServerState { SM_HOME = 0, SM_LISTENING, SM_CLOSING, } TCPServerState = SM_HOME; switch(TCPServerState) { case SM_HOME: // Allocate a socket for this server to listen and accept connections on MySocket = TCPOpen(0, TCP_OPEN_SERVER, SERVER_PORT, TCP_PURPOSE_GENERIC_TCP_SERVER); if(MySocket == INVALID_SOCKET) return; TCPServerState = SM_LISTENING; break; case SM_LISTENING: // See if anyone is connected to us if(!TCPIsConnected(MySocket)) return; // Figure out how many bytes have been received and how many we can transmit. wMaxGet = TCPIsGetReady(MySocket); // Get TCP RX FIFO byte count // Read the data into the buffer wBytesRead = 0; while (wBytesRead < wMaxGet) { if(!TCPGet(MySocket, &b)) break; // Byte NOT read... (No connection or no data to read) if(b == 10 || b == 13) { // Ignore newline characters } else { EthernetBuffer[EB_Write] = b; if( (EB_Write+1) % ETHERNET_BUFFER_SIZE != EB_Read) // check if buffer full EB_Write++; EB_Write %= ETHERNET_BUFFER_SIZE; } wBytesRead++; } break; case SM_CLOSING: // Close the socket connection. TCPClose(MySocket); TCPServerState = SM_HOME; break; } ProcessBufferData(); }
/***************************************************************************** * * Cloud_Activate * * \param None * * \return 1 - activation success * 0 - activation failure * * \brief Called after Init has been run in the past, but maybe comms were * down and we have to keep trying * *****************************************************************************/ int Cloud_Activate(void) { int length; char DataLen[5]; int newcik = 0; // int http_status = 0; char *cmp_ss = "Content-Length:"; char *cmp = cmp_ss; DWORD serverip = 0; const unsigned char server[6] = SERVERIP; serverip = (server[3] << 24 & 0xff000000) | (server[2] << 16 & 0xff0000) | (server[1] << 8 & 0xff00) | (server[0] & 0xff); long w, r; char rev[300]; unsigned char strLen, len; unsigned char cik_len_valid = 0; char *p; unsigned char crlf = 0; unsigned char ciklen = 0; int time_out = 0; // Flag cloud_initialized is set by Cloud_Init() /* if (!cloud_initialized) { status_code = STATUS_INIT; return newcik; } */ // clean the content of http header array if(status_code == STATUS_INIT||status_code == STATUS_END){ //to launch a new HTTP POST operation, clean the content of header at first if (sock == INVALID_SOCKET) { sock = TCPOpen(serverip, TCP_OPEN_IP_ADDRESS, HTTP_PORT, TCP_PURPOSE_TCP_CLIENT); // TCP_OPEN_RAM_HOST for using dns name as server name // TCPOpen(serverip, TCP_OPEN_IP_ADDRESS, server_port, TCP_PURPOSE_GENERIC_TCP_CLIENT); if (sock == INVALID_SOCKET) { status_code = STATUS_INIT; // LEDS_OFF(); // LEDS_ON(); return 0; } status_code = STATUS_READY; } status_code == STATUS_READY; } else if(status_code == STATUS_READY) { // Get activation Serial Number DelayMs(20); w = TCPIsPutReady(sock); if(w<2000ul) { // StackTask(); // TCPFlush((TCP_SOCKET)sock); return 0; } // LED1_ON(); LED2_OFF(); // if(w>2000ul) { LED2_ON(); LED1_OFF();} // DelayMs(100); length = strlen(provision_info); IHMS_itoa(DataLen, length, 10); //make a string for length sendLine(sock, POSTDATA_LINE, "/activate.php"); sendLine(sock, HOST_LINE, NULL); sendLine(sock, CONTENT_LINE, NULL); // IHMS_SocketSend(sock, "Connection: close\r\n", sizeof("Connection: close\r\n")-1); sendLine(sock, LENGTH_LINE, DataLen); IHMS_SocketSend(sock, provision_info, length); status_code = STATUS_RCV; } else if(status_code == STATUS_RCV) { DelayMs(20); r = TCPIsGetReady((TCP_SOCKET) sock); if(r<234u){ LED2_ON(); return 0;} // now read all data in RX buffer int count = 0; do { r = TCPGetArray((TCP_SOCKET)sock, (BYTE *)&rev[count], 300); count = count + r; rev[count]=0; r = TCPIsGetReady((TCP_SOCKET) sock); }while(r>0u); rev[count] = 0 ; strLen = strlen(rev); len = strLen; p = rev; // Find 4 consecutive \r or \n - should be: \r\n\r\n while (0 < len && 4 > crlf) { if ('\r' == *p || '\n' == *p) { ++crlf; } else { crlf = 0; if (*cmp == *p) { // check the cik length from http response cmp++; if (cmp > cmp_ss + strlen(cmp_ss) - 1) cik_len_valid = 1; } else cmp = cmp_ss; } ++p; --len; } if(len>0) { LED1_ON(); LED2_OFF(); } // The body is the cik // TODO, be more robust - match Content-Length header value to CIK_LENGTH strncpy(CIK, p, CIK_LENGTH); CIK[40] = 0; newcik = 1; //IHMS_SocketClose(sock); TCPClose((TCP_SOCKET)sock); status_code = STATUS_END; sock = INVALID_SOCKET; return newcik; } // status_code = STATUS_INIT; return newcik; }