virtual void Execute(SActivationInfo *pActInfo) { bool bResult = false; // did the socket connect okay? if (socketWorking) { if (ReceiveLine() != -1) { string r = recMessage; //string value = r.c_str(); int indice = r.find("|",0); string cvar = r.substr(0,indice);//r.Left(r.find("|",0)); string value = r.substr(indice+1,r.length()-(indice+1)); CryLogAlways(r); ActivateOutput(pActInfo, EOP_CVAR, cvar); ActivateOutput(pActInfo, EOP_Value, value); bResult = true; } } // return false if socket error, or no message if (bResult) ActivateOutput(pActInfo, EOP_Received, true); return; }
int CFtpTransfer::Receive(const int client_sockfd) { long int n; char buffer[BUFFER_SIZE]; bzero(buffer,BUFFER_SIZE); n = ReceiveLine(client_sockfd,buffer,BUFFER_SIZE); if(n > 0){ cout << "From client command: " << buffer << endl; CClient *pClient = m_ClientManager.FindClient(client_sockfd); if(pClient){ CCommand *pCommand = m_ClientManager.FindCommand(string(buffer)); if(pCommand){ pCommand->doWhat(pClient); EFTPSTATE state = pClient->GetClientState(); if(state == QUIT){ m_ClientManager.EarseClient(client_sockfd); m_CurrentConnetions--; //cout << "one con disconnected and current con is: " << m_CurrentConnetions << endl; } } else{ pClient->sendErrorMsg(); } } } else{ m_ClientManager.EarseClient(client_sockfd); m_CurrentConnetions--; //cout << "one con disconnected and current con is: " << m_CurrentConnetions << endl; } }
/******************************************************************** GetNumMsgs The objective of this function is to retrieve the number of messages stored in the server for the user maildrop. NOTE: Server should not include any messages marked for deletion in the response PARAM: int *number - pionter to the number of available messages RETURN: UTE_NOCONNECTION - NOT connected UTE_SVR_NO_RESPONSE - no response from Server UTE_STAT_FAILED - STAT command was not reponded to positivly UTE_INVALID_RESPONSE - Malformed response *********************************************************************/ int CUT_POP3Client::GetNumMsgs(int *number){ char param[MAX_PATH+1]; //check to see if the connection is made if(!IsConnected()) return OnError(UTE_NOCONNECTION); //send the STAT command Send("STAT\r\n"); //get the response if(ReceiveLine(m_szBuf,sizeof(m_szBuf),m_nPOP3TimeOut) <= 0) return OnError(UTE_SVR_NO_RESPONSE); if(m_szBuf[0] != '+') return OnError(UTE_STAT_FAILED); CUT_StrMethods::RemoveCRLF(m_szBuf); if(CUT_StrMethods::ParseString(m_szBuf," ",1,param,sizeof(param)) != UTE_SUCCESS) return OnError(UTE_INVALID_RESPONSE); *number = atoi(param); return OnError(UTE_SUCCESS); }
void MemCacheClient::HandleStoreResponse( Server * a_pServer, MemRequest & a_oItem ) { // get the value string_t sValue; ReceiveLine(a_pServer, sValue); // success if (sValue == "STORED\r\n") { a_oItem.mResult = MCERR_OK; return; } // data was not stored, but not because of an error. // This normally means that either that the condition for // an "add" or a "replace" command wasn't met, or that the // item is in a delete queue. if (sValue == "NOT_STORED\r\n") { a_oItem.mResult = MCERR_NOTSTORED; return; } // unknown response, connection may be bad a_pServer->Disconnect(); throw ServerSocket::Exception("bad response"); }
/******************************** CloseTop() Close the currently open message by reading all availabe lines of the Top response if any. PARAM NONE RETURN UTE_SUCCESS - Success UTE_NOCONNECTION - NOT connected *********************************/ int CUT_POP3Client::CloseTop(){ int error = UTE_SUCCESS; if(m_bTopOpen == FALSE) return OnError(UTE_SUCCESS); //check to see if the connection is made if(!IsConnected()) return OnError(UTE_NOCONNECTION); int len; while(!m_bReadTopFinished) { if(IsAborted()) { // Test for abortion flag error = UTE_ABORTED; break; } //read in a line len = ReceiveLine(m_szBuf,sizeof(m_szBuf),m_nPOP3TimeOut); if( len <= 0 ) break; if(m_szBuf[0] == '.' && len <= 3) break; } m_bTopOpen = FALSE; m_bReadTopFinished = FALSE; return OnError(error); }
/******************************** GetMsgSize() Retrieve the size of the message specified by the index. When this function is invoked on a valid connection and the message specified by the Index is not marked for deletion, The POP3 server issues a positive response with a line containing information for the message. PARAM int index - the message number long *size - pointer to the message size RETURN UTE_NOCONNECTION - NOT connected UTE_SVR_NO_RESPONSE - no response from Server UTE_LIST_FAILED - LIST command was not reponded to positivly UTE_INVALID_RESPONSE - Malformed response *********************************/ int CUT_POP3Client::GetMsgSize(int index,long *size){ char param[MAX_PATH+1]; //check to see if the connection is made if(!IsConnected()) return OnError(UTE_NOCONNECTION); //send the LIST command _snprintf(m_szBuf,sizeof(m_szBuf)-1,"LIST %d\r\n",index); Send(m_szBuf); //get the response if(ReceiveLine(m_szBuf,sizeof(m_szBuf),m_nPOP3TimeOut) <= 0) return OnError(UTE_SVR_NO_RESPONSE); if(m_szBuf[0] != '+') return OnError(UTE_LIST_FAILED); CUT_StrMethods::RemoveCRLF(m_szBuf); // a server response to a LIST command that includes an argument // should have +OK[SPACE]messageNumber[SPACE]size // Hence we will be looking for the third octet of the server response if(CUT_StrMethods::ParseString(m_szBuf," ()",2,param,sizeof(param)) != UTE_SUCCESS) return OnError(UTE_INVALID_RESPONSE); *size = atol(param); return OnError(UTE_SUCCESS); }
status_t POP3Protocol::Open(const char* server, int port, int) { ReportProgress(0, 0, B_TRANSLATE("Connecting to POP3 server" B_UTF8_ELLIPSIS)); if (port <= 0) port = fUseSSL ? 995 : 110; fLog = ""; // Prime the error message BString errorMessage(B_TRANSLATE("Error while connecting to server %serv")); errorMessage.ReplaceFirst("%serv", server); if (port != 110) errorMessage << ":" << port; delete fServerConnection; fServerConnection = NULL; BNetworkAddress address(server, port); if (fUseSSL) fServerConnection = new(std::nothrow) BSecureSocket(address); else fServerConnection = new(std::nothrow) BSocket(address); status_t status = B_NO_MEMORY; if (fServerConnection != NULL) status = fServerConnection->InitCheck(); BString line; if (status == B_OK) { ssize_t length = ReceiveLine(line); if (length < 0) status = length; } if (status != B_OK) { fServerConnection->Disconnect(); errorMessage << ": " << strerror(status); ShowError(errorMessage.String()); return status; } if (strncmp(line.String(), "+OK", 3) != 0) { if (line.Length() > 0) { errorMessage << B_TRANSLATE(". The server said:\n") << line.String(); } else errorMessage << B_TRANSLATE(": No reply.\n"); ShowError(errorMessage.String()); fServerConnection->Disconnect(); return B_ERROR; } fLog = line; return B_OK; }
BOOL CUT_POP3Client::GetResponseCode(int timeOut){ if(ReceiveLine(m_szBuf,sizeof(m_szBuf), timeOut) <=0) return FALSE; if(m_szBuf[0] == '+') return TRUE; return FALSE; }
status_t POP3Protocol::SendCommand(const char* cmd) { //printf(cmd); // Flush any accumulated garbage data before we send our command, so we // don't misinterrpret responses from previous commands (that got left over // due to bugs) as being from this command. while (fServerConnection->WaitForReadable(1000) == B_OK) { int amountReceived; char tempString [1024]; amountReceived = fServerConnection->Read(tempString, sizeof(tempString) - 1); if (amountReceived < 0) return errno; tempString [amountReceived] = 0; printf ("POP3Protocol::SendCommand Bug! Had to flush %d bytes: %s\n", amountReceived, tempString); //if (amountReceived == 0) // break; } if (fServerConnection->Write(cmd, ::strlen(cmd)) < 0) { fLog = strerror(errno); printf("POP3Protocol::SendCommand Send \"%s\" failed, code %d: %s\n", cmd, errno, fLog.String()); return errno; } fLog = ""; status_t err = B_OK; while (true) { int32 len = ReceiveLine(fLog); if (len <= 0 || fLog.ICompare("+OK", 3) == 0) break; if (fLog.ICompare("-ERR", 4) == 0) { printf("POP3Protocol::SendCommand \"%s\" got error message " "from server: %s\n", cmd, fLog.String()); err = B_ERROR; break; } else { printf("POP3Protocol::SendCommand \"%s\" got nonsense message " "from server: %s\n", cmd, fLog.String()); err = B_BAD_VALUE; // If it's not +OK, and it's not -ERR, then what the heck // is it? Presume an error break; } } return err; }
status_t POP3Protocol::_RetrieveUniqueIDs() { fUniqueIDs.MakeEmpty(); fSizes.clear(); fTotalSize = 0; status_t status = SendCommand("UIDL" CRLF); if (status != B_OK) return status; BString result; int32 uidOffset; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; uidOffset = result.FindFirst(' ') + 1; result.Remove(0, uidOffset); fUniqueIDs.Add(result); } if (SendCommand("LIST" CRLF) != B_OK) return B_ERROR; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; int32 index = result.FindLast(" "); int32 size; if (index >= 0) size = atol(&result.String()[index]); else size = 0; fTotalSize += size; fSizes.push_back(size); } return B_OK; }
status_t POP3Protocol::_UniqueIDs() { fUniqueIDs.MakeEmpty(); status_t ret = B_OK; ret = SendCommand("UIDL" CRLF); if (ret != B_OK) return ret; BString result; int32 uid_offset; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; uid_offset = result.FindFirst(' ') + 1; result.Remove(0,uid_offset); fUniqueIDs.AddItem(result.String()); } if (SendCommand("LIST" CRLF) != B_OK) return B_ERROR; int32 b; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; b = result.FindLast(" "); if (b >= 0) b = atol(&(result.String()[b])); else b = 0; fSizes.AddItem((void *)(b)); } return ret; }
status_t POP3Protocol::UniqueIDs() { status_t ret = B_OK; runner->ReportProgress(0, 0, MDR_DIALECT_CHOICE("Getting UniqueIDs...", "固有のIDを取得中...")); ret = SendCommand("UIDL" CRLF); if (ret != B_OK) return ret; BString result; int32 uid_offset; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; uid_offset = result.FindFirst(' ') + 1; result.Remove(0,uid_offset); unique_ids->AddItem(result.String()); } if (SendCommand("LIST" CRLF) != B_OK) return B_ERROR; int32 b; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; b = result.FindLast(" "); if (b >= 0) b = atol(&(result.String()[b])); else b = 0; fSizes.AddItem((void *)(b)); } return ret; }
int CUT_POP3Client::ReadTopLine(LPSTR buf,int bufLen){ if (m_bTopOpen == FALSE) return -1; int rt = ReceiveLine(buf,bufLen); if(buf[0] == '.' && rt <= 3) { m_bReadTopFinished = TRUE; return 0; } return rt; }
virtual void Execute(SActivationInfo *pActInfo) { bool bResult = false; // did the socket connect okay? if (socketWorking) { if (ReceiveLine() != -1) { string value = base64Message.c_str(); ActivateOutput(pActInfo, EOP_Value, value); bResult = true; } } // return false if socket error, or no message if (bResult) ActivateOutput(pActInfo, EOP_Received, true); return; }
/******************************** ResetDelete() If any messages have been marked as deleted by the pop3 server they are unmarked. PARAM NONE RETURN UTE_SUCCESS - Success UTE_NOCONNECTION - NOT connected UTE_SVR_NO_RESPONSE - no response from Server UTE_RSET_FAILED - RSET command has timed out without a response from the server *********************************/ int CUT_POP3Client::ResetDelete(){ //check to see if the connection is made if(!IsConnected()) return OnError(UTE_NOCONNECTION); //send the DELE command Send("RSET\r\n"); //get the response if(ReceiveLine(m_szBuf,sizeof(m_szBuf),m_nPOP3TimeOut) <= 0) return OnError(UTE_SVR_NO_RESPONSE); if(m_szBuf[0] != '+') return OnError(UTE_RSET_FAILED); return OnError(UTE_SUCCESS); }
/******************************** DeleteMsg() Mark a message for deletion. the message will be deleted after the transaction closure PARAM index - index of the message to be marked for deletion RETURN UTE_SUCCESS - Success UTE_NOCONNECTION - NOT connected UTE_SVR_NO_RESPONSE - no response from Server UTE_DELE_FAILED - DELE command has timed out without a response from the server *********************************/ int CUT_POP3Client::DeleteMsg(int index){ //check to see if the connection is made if(!IsConnected()) return OnError(UTE_NOCONNECTION); //send the DELE command _snprintf(m_szBuf,sizeof(m_szBuf)-1,"DELE %d\r\n",index); Send(m_szBuf); //get the response if(ReceiveLine(m_szBuf,sizeof(m_szBuf),m_nPOP3TimeOut) <= 0) return OnError(UTE_SVR_NO_RESPONSE); if(m_szBuf[0] != '+') return OnError(UTE_DELE_FAILED); return OnError(UTE_SUCCESS); }
status_t POP3Protocol::SendCommand(const char* cmd) { // Flush any accumulated garbage data before we send our command, so we // don't misinterrpret responses from previous commands (that got left over // due to bugs) as being from this command. while (fServerConnection->WaitForReadable(1000) == B_OK) { char buffer[4096]; ssize_t amountReceived = fServerConnection->Read(buffer, sizeof(buffer) - 1); if (amountReceived < 0) return amountReceived; buffer[amountReceived] = 0; printf("POP3Protocol::SendCommand Bug! Had to flush %" B_PRIdSSIZE " bytes: %s\n", amountReceived, buffer); } if (fServerConnection->Write(cmd, ::strlen(cmd)) < 0) { fLog = strerror(errno); printf("POP3Protocol::SendCommand Send \"%s\" failed, code %d: %s\n", cmd, errno, fLog.String()); return errno; } fLog = ""; int32 length = ReceiveLine(fLog); if (length <= 0 || fLog.ICompare("+OK", 3) == 0) return B_OK; if (fLog.ICompare("-ERR", 4) == 0) { printf("POP3Protocol::SendCommand \"%s\" got error message " "from server: %s\n", cmd, fLog.String()); return B_ERROR; } printf("POP3Protocol::SendCommand \"%s\" got nonsense message " "from server: %s\n", cmd, fLog.String()); return B_BAD_DATA; // If it's not +OK, and it's not -ERR, then what the heck // is it? Presume an error }
/*************************************************** OnConnect This function needs to be overridden for the server to do anything useful. This function is called whenever a new connection is made. This function should not return until the connection is to be closed. Params none Return none ****************************************************/ void CUT_WSThread::OnConnect(){ // This is a minimal default implementation long len = 100; LPSTR data = new char[100]; // Get the first line len = ReceiveLine(data,len); if(len > 0) { // Remove all outstanding data ClearReceiveBuffer(); // Send a message back Send("Connect Successful ... Now Disconnecting."); } delete[] data; }
/******************************** OpenTop(int index) To allow us to read the top part of the message without having to download it all. We will issue a TOP command and receive only the response from the server If the server response is positive then we will flag the TopOpen. By doing so the message will be available to us on the receive buffer where we can either read the whole message Top or receive it by line by line. NOTE This function must be called prior to a call to ReadTopLine(). A message for TOP can't be opened if another message is already open for TOP. The other message should be closed first PARAM index - The index of the message to be opened ( 1 based ) RETURN UTE_SUCCESS - Success UTE_NOCONNECTION - NOT connected UTE_SVR_NO_RESPONSE - no response from Server UTE_TOP_FAILED - TOP command has timed out without a response from the server *********************************/ int CUT_POP3Client::OpenTop(int index,int msgLines){ //check to see if the connection is made if(!IsConnected()) return OnError(UTE_NOCONNECTION); //send the TOP command _snprintf(m_szBuf,sizeof(m_szBuf)-1,"TOP %d %d\r\n",index,msgLines); Send(m_szBuf); //get the response if(ReceiveLine(m_szBuf,sizeof(m_szBuf),m_nPOP3TimeOut) <= 0) return OnError(UTE_SVR_NO_RESPONSE); if(m_szBuf[0] != '+') // '-' response probably flags 'not implemented'. return OnError(UTE_TOP_FAILED); // TOP was/is an optional POP3 option m_bTopOpen = TRUE; m_bReadTopFinished = FALSE; return OnError(UTE_SUCCESS); }
/******************************** OpenMsg(int index) To allow us read part of the message without having to download it all we will issue a RETR command and receive only the response from the server If the server response is positive then we will flag the MessageOpen. By doing so the message will be available to us on the receive buffer where we can either read the whole message or receive it by line by line NOTE This function must be called prior to a call to ReadMsgLine(). A message can't be opened if another message is already open. The other message should be closed first PARAM index - The index of the message to be opened ( 1 based ) RETURN UTE_SUCCESS - Success UTE_NOCONNECTION - NOT connected UTE_SVR_NO_RESPONSE - no response from Server UTE_RETR_FAILED - RETR command has timed out without a response from the server *********************************/ int CUT_POP3Client::OpenMsg(int index){ //check to see if the connection is made if(!IsConnected()) return OnError(UTE_NOCONNECTION); //send the RETR command _snprintf(m_szBuf,sizeof(m_szBuf)-1,"RETR %d\r\n",index); Send(m_szBuf); //get the response if(ReceiveLine(m_szBuf,sizeof(m_szBuf),m_nPOP3TimeOut) <= 0) return OnError(UTE_SVR_NO_RESPONSE); if(m_szBuf[0] != '+') return OnError(UTE_RETR_FAILED); m_bMsgOpen = TRUE; m_bReadMsgFinished = FALSE; return OnError(UTE_SUCCESS); }
void RemoteContainerManager::Receive(ProtocolAnswer* answer) { string answerLine = ReceiveLine(); ParseAnswerLine(answerLine, answer); if(answer->pendingDataSize == 0) return; if(response_.size() < answer->pendingDataSize) asio::read(socket_, response_, asio::transfer_at_least(answer->pendingDataSize - response_.size())); BOOST_ASSERT(response_.size() >= answer->pendingDataSize); ExtractFieldsFromBuffer( answer->fieldSet, asio::buffer_cast<const void*>(response_.data()), answer->pendingDataSize, &answer->key, &answer->value, &answer->metadata); response_.consume(answer->pendingDataSize); }
int MemCacheClient::HandleDelResponse( Server * a_pServer, MemRequest ** a_ppBegin, MemRequest ** a_ppEnd ) { string_t sValue; int nResponses = 0; for (MemRequest ** p = a_ppBegin; p < a_ppEnd; ++p) { MemRequest * pItem = *p; // no response for this entry if (pItem->mResult == MCERR_NOREPLY) continue; // get the value ReceiveLine(a_pServer, sValue); // success if (sValue == "DELETED\r\n") { pItem->mResult = MCERR_OK; ++nResponses; continue; } // the item with this key was not found if (sValue == "NOT_FOUND\r\n") { pItem->mResult = MCERR_NOTFOUND; ++nResponses; continue; } a_pServer->Disconnect(); throw ServerSocket::Exception("bad response"); } return nResponses; }
/*************************************************** OnConnect This member is called when a connection is made and accepted. Do all processing here, since the connection is automatically terminated when this function returns. Plus the thread that this function runs in is terminated as well. This function is the main engine that process all clients commands. PARAM NONE RETURN VOID ****************************************************/ void CUT_HTTPThread::OnConnect(){ char command[30]; int success = TRUE; // Clear the data variables m_szFileName[0] = 0; m_szBuf[0] = 0; m_szData[0] = 0; // Get the current tick count long tickCount = GetTickCount(); // Get the first line int len = ReceiveLine(m_szData, WSS_BUFFER_SIZE*2); // Break on error or disconnect if(len <= 0) return; // Remove the CRLF pair from the string CUT_StrMethods::RemoveCRLF(m_szData); // Parse the line if(CUT_StrMethods::ParseString(m_szData," ",0,command,30) != UTE_SUCCESS) { // Command not reconized Send("Command Not Reconized\r\n"); return; } // Get the command ID int commandID = GetCommandID(command); if(commandID == CUT_NA) { Send("Command Not Reconized\r\n"); return; } //********************************** // Check for GET //********************************** if(commandID == CUT_GET || commandID == CUT_HEAD ){ // Get the filename if(CUT_StrMethods::ParseString(m_szData," ?",1,m_szBuf, WSS_BUFFER_SIZE) != UTE_SUCCESS) { // Command not reconized Send("Command Not Reconized\r\n"); return; } // Get the absolute path if(MakePath(m_szFileName,m_szBuf) != UTE_SUCCESS) { Send("HTTP/1.0 404 Requested file not found\r\n"); return; } // Send a start notification if(OnNotify(CUT_START,commandID,m_szFileName,sizeof(m_szFileName),success) == FALSE) { // If FALSE is returned then do not continue ClearReceiveBuffer(); return; } // Open the file // v4.2 using CreateFileA here HANDLE hFile = CreateFileA(m_szFileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL); if(hFile == INVALID_HANDLE_VALUE) { Send("HTTP/1.0 404 Requested file not found\r\n"); success = FALSE; } else { // Send the MIME header Send("HTTP/1.0 200 OK\r\n"); _snprintf(m_szBuf,sizeof(m_szBuf)-1,"Date:%s\r\n",GetGMTStamp()); Send(m_szBuf); Send("Server: The Ultimate Toolbox WWW Server\r\n"); Send("MIME-verion: 1.0\r\n"); _snprintf(m_szBuf,sizeof(m_szBuf)-1,"Content-type: %s\r\n",GetContentType(m_szFileName)); Send(m_szBuf); _snprintf(m_szBuf,sizeof(m_szBuf)-1,"Last-modified: %s\r\n",GetFileModifiedTime(hFile)); Send(m_szBuf); DWORD hiVal; long OrigFileSize = GetFileSize(hFile,&hiVal); _snprintf(m_szBuf,sizeof(m_szBuf)-1,"Content-length: %ld\r\n",OrigFileSize); Send(m_szBuf); Send("\r\n"); // Send the file only for a GET if(commandID == CUT_GET) { // Get the max send size to send at once len = GetMaxSend(); if(len > WSS_BUFFER_SIZE*2) len = WSS_BUFFER_SIZE*2; // Send the file DWORD readLen; int rt; long totalLen = 0; // v4.2 change - was while(1) - gave conditional expression is constant warning for (;;) { rt = ReadFile(hFile,m_szData,len,&readLen,NULL); if(rt == FALSE || readLen ==0) break; if(Send(m_szData,readLen) == SOCKET_ERROR) break; totalLen+= readLen; } if(totalLen != OrigFileSize) success = FALSE; } CloseHandle(hFile); ClearReceiveBuffer(); } // Send a finish notification OnNotify(CUT_FINISH,commandID,m_szFileName,sizeof(m_szFileName),success); } //********************************** // Check for POST //********************************** else if(commandID == CUT_POST) { while(IsDataWaiting()) { len = ReceiveLine(m_szData, WSS_BUFFER_SIZE*2); CUT_StrMethods::RemoveCRLF(m_szData); ((CUT_HTTPServer *)m_winsockclass_this)->OnStatus(m_szData); } } //********************************** // Check for PUT //********************************** else if(commandID == CUT_PUT){ Send("HTTP/1.0 501 Not Implemented\r\n\r\n"); Send("Server: The Ultimate Toolbox WWW Server\r\n"); Send("MIME-verion: 1.0\r\n"); return; } //********************************** // Check for PLACE //********************************** else if(commandID == CUT_PLACE) { Send("HTTP/1.0 501 Not Implemented\r\n\r\n"); return; } //********************************** // Check for DELETE //********************************** else if(commandID == CUT_DELETE) { // Get the filename if(CUT_StrMethods::ParseString(m_szData," ",1,m_szBuf, WSS_BUFFER_SIZE) != UTE_SUCCESS) { // Command not reconized Send("HTTP/1.0 400 Bad Request\r\n\r\n"); return; } // Get the absolute path if(MakePath(m_szFileName,m_szBuf) != UTE_SUCCESS) { Send("HTTP/1.0 404 Requested file not found\r\n\r\n"); return; } // Send a start notification if(OnNotify(CUT_START,commandID,m_szFileName,sizeof(m_szFileName),success) == FALSE) { // If FALSE is returned then do not continue Send("HTTP/1.0 405 Method Not Allowed\r\n"); Send("Content-Type: text/html\r\n\r\n"); Send("<html><body>DELETE Method Not Allowed</body></html>"); ClearReceiveBuffer(); return; } // Send the finish notify // v4.2 using DeleteFileA here if(DeleteFileA(m_szFileName) == FALSE) { Send("HTTP/1.0 500 Internal Server Error\r\n"); success = FALSE; return ; } // Send a start notification OnNotify(CUT_FINISH,commandID,m_szFileName,sizeof(m_szFileName),success); } //********************************** // Allow handling for custom commands //********************************** else { // Get the rest of the data after the command char* pData = strstr(m_szData, " "); if (pData) strncpy(m_szBuf, pData+1, sizeof(m_szBuf)); if(OnNotify(CUT_START,commandID,m_szBuf,sizeof(m_szBuf),success) == FALSE) { // If FALSE is returned then do not continue ClearReceiveBuffer(); return; } OnCustomCommand(commandID,m_szBuf,WSS_BUFFER_SIZE); // Send a finish notification OnNotify(CUT_FINISH,commandID,m_szBuf,sizeof(m_szBuf),success); //Returns so the default OnSendStatus() implementation is not called. // If needed OnStatus() can be called in the OnNotify(CUT_FINISH)! return; } // Send a status line to the server history window OnSendStatus(commandID,m_szFileName,success,tickCount); }
/********************************************* Finger Performs the finger for the specified address the information that is returned can be retrieved with the GetReturnLine function. If filename parameter was specified all the received data is saved in the file. In this case you can't access data with GetReturnLine function. Params address - address to perform the finger on. address format is: @domain.com or [email protected] dest - data source for saving received data [fileType] - -1 - don't use UTM_OM_WRITING - open writing UTM_OM_APPEND - open for appending Return UTE_SUCCESS - success UTE_INVALID_ADDRESS_FORMAT - invalid address format UTE_INVALID_ADDRESS - invalid address UTE_CONNECT_FAILED - connection failed UTE_NO_RESPONSE - no response UTE_ABORTED - aborted UTE_CONNECT_TIMEOUT - time out **********************************************/ int CUT_FingerClient::Finger(LPTSTR address, CUT_DataSource & dest, OpenMsgType fileType) { int error = UTE_SUCCESS; int len; char buf[MAX_PATH+1]; char domain[MAX_PATH+1]; //delete prev finger information m_listReturnLines.ClearList(); //split the address apart // v4.2 address splitting into name and domain allows AC macro, hence LPTSTR in interface. if(SplitAddress(buf,domain,AC(address)) != UTE_SUCCESS) return OnError(UTE_INVALID_ADDRESS_FORMAT); //check to see if the domain is a name or address if(IsIPAddress(domain) != TRUE) { //get the name from the address if(GetAddressFromName(domain,domain,sizeof(domain)) != UTE_SUCCESS) return OnError(UTE_INVALID_ADDRESS); } //connect using a timeout if((error=Connect(m_nPort, domain, m_nConnectTimeout)) != UTE_SUCCESS) return OnError(error); if(IsAborted()) // Test abort flag error = UTE_ABORTED; // Aborted if(error == UTE_SUCCESS) { //send the name to finger Send(buf); Send("\r\n"); // Read data into the file if(fileType != -1) { error = Receive(dest, fileType, m_nReceiveTimeout); } // Read data line by line & save it in the string list else { //read in the return lines // v4.2 change to eliminate C4127:conditional expression is constant for(;;) { if(IsAborted()) { // Test abort flag error = UTE_ABORTED; // Aborted break; } //wait for a receive if(WaitForReceive(m_nReceiveTimeout, 0)!= UTE_SUCCESS) break; //get the information len = ReceiveLine(buf, sizeof(buf)-1); if(len <= 0) break; buf[len]=0; CUT_StrMethods::RemoveCRLF(buf); //store the information m_listReturnLines.AddString(buf); } if (error == UTE_SUCCESS && m_listReturnLines.GetCount() == 0) error = UTE_NO_RESPONSE; // No response } } // Close connection CloseConnection(); return OnError(error); }
status_t POP3Protocol::SendCommand(const char *cmd) { if (fSocket < 0 || fSocket > FD_SETSIZE) return B_FILE_ERROR; //printf(cmd); // Flush any accumulated garbage data before we send our command, so we // don't misinterrpret responses from previous commands (that got left over // due to bugs) as being from this command. struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 1000; /* very short timeout, hangs with 0 in R5 */ struct fd_set readSet; FD_ZERO(&readSet); FD_SET(fSocket, &readSet); int result; #ifdef USE_SSL if (fUseSSL && SSL_pending(fSSL)) result = 1; else #endif result = select(fSocket + 1, &readSet, NULL, NULL, &tv); if (result > 0) { int amountReceived; char tempString [1025]; #ifdef USE_SSL if (fUseSSL) amountReceived = SSL_read(fSSL, tempString, sizeof(tempString) - 1); else #endif amountReceived = recv(fSocket, tempString, sizeof(tempString) - 1, 0); if (amountReceived < 0) return errno; tempString [amountReceived] = 0; printf ("POP3Protocol::SendCommand Bug! Had to flush %d bytes: %s\n", amountReceived, tempString); //if (amountReceived == 0) // break; } #ifdef USE_SSL if (fUseSSL) { SSL_write(fSSL, cmd,::strlen(cmd)); } else #endif if (send(fSocket, cmd, ::strlen(cmd), 0) < 0) { fLog = strerror(errno); printf("POP3Protocol::SendCommand Send \"%s\" failed, code %d: %s\n", cmd, errno, fLog.String()); return errno; } fLog = ""; status_t err = B_OK; while (true) { int32 len = ReceiveLine(fLog); if (len <= 0 || fLog.ICompare("+OK", 3) == 0) break; if (fLog.ICompare("-ERR", 4) == 0) { printf("POP3Protocol::SendCommand \"%s\" got error message " "from server: %s\n", cmd, fLog.String()); err = B_ERROR; break; } else { printf("POP3Protocol::SendCommand \"%s\" got nonsense message " "from server: %s\n", cmd, fLog.String()); err = B_BAD_VALUE; // If it's not +OK, and it's not -ERR, then what the heck // is it? Presume an error break; } } return err; }
status_t POP3Protocol::Open(const char *server, int port, int) { runner->ReportProgress(0, 0, MDR_DIALECT_CHOICE("Connecting to POP3 server...", "POP3サーバに接続しています...")); if (port <= 0) { #ifdef USE_SSL port = fUseSSL ? 995 : 110; #else port = 110; #endif } fLog = ""; // Prime the error message BString error_msg; error_msg << MDR_DIALECT_CHOICE("Error while connecting to server ", "サーバに接続中にエラーが発生しました ") << server; if (port != 110) error_msg << ":" << port; uint32 hostIP = inet_addr(server); // first see if we can parse it as a numeric address if (hostIP == 0 || hostIP == ~0UL) { struct hostent * he = gethostbyname(server); hostIP = he ? *((uint32*)he->h_addr) : 0; } if (hostIP == 0) { error_msg << MDR_DIALECT_CHOICE(": Connection refused or host not found", ": :接続が拒否されたかサーバーが見つかりません"); runner->ShowError(error_msg.String()); return B_NAME_NOT_FOUND; } #ifndef ANTARES_TARGET_PLATFORM_BEOS fSocket = socket(AF_INET, SOCK_STREAM, 0); #else fSocket = socket(AF_INET, 2, 0); #endif if (fSocket >= 0) { struct sockaddr_in saAddr; memset(&saAddr, 0, sizeof(saAddr)); saAddr.sin_family = AF_INET; saAddr.sin_port = htons(port); saAddr.sin_addr.s_addr = hostIP; int result = connect(fSocket, (struct sockaddr *) &saAddr, sizeof(saAddr)); if (result < 0) { #ifndef ANTARES_TARGET_PLATFORM_BEOS close(fSocket); #else closesocket(fSocket); #endif fSocket = -1; error_msg << ": " << strerror(errno); runner->ShowError(error_msg.String()); return errno; } } else { error_msg << ": Could not allocate socket."; runner->ShowError(error_msg.String()); return B_ERROR; } #ifdef USE_SSL if (fUseSSL) { SSL_library_init(); SSL_load_error_strings(); RAND_seed(this,sizeof(POP3Protocol)); /*--- Because we're an add-on loaded at an unpredictable time, all the memory addresses and things contained in ourself are esssentially random. */ fSSLContext = SSL_CTX_new(SSLv23_method()); fSSL = SSL_new(fSSLContext); fSSLBio = BIO_new_socket(fSocket, BIO_NOCLOSE); SSL_set_bio(fSSL, fSSLBio, fSSLBio); if (SSL_connect(fSSL) <= 0) { BString error; error << "Could not connect to POP3 server " << settings->FindString("server"); if (port != 995) error << ":" << port; error << ". (SSL connection error)"; runner->ShowError(error.String()); SSL_CTX_free(fSSLContext); #ifndef ANTARES_TARGET_PLATFORM_BEOS close(fSocket); #else closesocket(fSocket); #endif runner->Stop(true); return B_ERROR; } } #endif BString line; status_t err; #ifndef ANTARES_TARGET_PLATFORM_BEOS err = ReceiveLine(line); #else int32 tries = 200000; // no endless loop here while ((err = ReceiveLine(line)) == 0) { if (tries-- < 0) return B_ERROR; } #endif if (err < 0) { #ifndef ANTARES_TARGET_PLATFORM_BEOS close(fSocket); #else closesocket(fSocket); #endif fSocket = -1; error_msg << ": " << strerror(err); runner->ShowError(error_msg.String()); return B_ERROR; } if (strncmp(line.String(), "+OK", 3) != 0) { if (line.Length() > 0) { error_msg << MDR_DIALECT_CHOICE(". The server said:\n", "サーバのメッセージです\n") << line.String(); } else error_msg << ": No reply.\n"; runner->ShowError(error_msg.String()); return B_ERROR; } fLog = line; return B_OK; }
bool FlytecDevice::ReadFlightList(RecordedFlightList &flight_list, OperationEnvironment &env) { port.StopRxThread(); char buffer[256]; strcpy(buffer, "$PBRTL,"); AppendNMEAChecksum(buffer); strcat(buffer, "\r\n"); port.Write(buffer); if (!ExpectXOff(port, env, 1000)) return false; unsigned tracks = 0; while (true) { // Check if the user cancelled the operation if (env.IsCancelled()) return false; // Receive the next line if (!ReceiveLine(port, buffer, ARRAY_SIZE(buffer), 1000)) return false; // XON was received, last record was read already if (StringIsEmpty(buffer)) break; // $PBRTL Identifier // AA total number of stored tracks // BB actual number of track (0 indicates the most actual track) // DD.MM.YY date of recorded track (UTC)(e.g. 24.03.04) // hh:mm:ss starttime (UTC)(e.g. 08:23:15) // HH:MM:SS duration (e.g. 03:23:15) // *ZZ Checksum as defined by NMEA RecordedFlightInfo flight; NMEAInputLine line(buffer); // Skip $PBRTL line.Skip(); if (tracks == 0) { // If number of tracks not read yet // .. read and save it if (!line.ReadChecked(tracks)) continue; env.SetProgressRange(tracks); } else line.Skip(); if (!line.ReadChecked(flight.internal.flytec)) continue; if (tracks != 0 && flight.internal.flytec < tracks) env.SetProgressPosition(flight.internal.flytec); char field_buffer[16]; line.Read(field_buffer, ARRAY_SIZE(field_buffer)); if (!ParseDate(field_buffer, flight.date)) continue; line.Read(field_buffer, ARRAY_SIZE(field_buffer)); if (!ParseTime(field_buffer, flight.start_time)) continue; BrokenTime duration; line.Read(field_buffer, ARRAY_SIZE(field_buffer)); if (!ParseTime(field_buffer, duration)) continue; flight.end_time = flight.start_time + duration; flight_list.append(flight); } return true; }
/******************************** RetrieveUID Retrieves the unique-id of one or all messages. You can use the GetUID(...) method to get the unique-id string. "The unique-id of a message is an arbitrary server-determined string, consisting of one to 70 characters in the range 0x21 to 0x7E, which uniquely identifies a message within a maildrop and which persists across sessions. This persistence is required even if a session ends without entering the UPDATE state. The server should never reuse an unique-id in a given maildrop, for as long as the entity using the unique-id exists. Note that messages marked as deleted are not listed." RFC 1939 PARAM [msgNumber] - the number of message to get UID for. If set to -1 (default) retieve UIDs for all messages RETURN UTE_SUCCESS - Success UTE_NOCONNECTION - NOT connected UTE_SVR_NO_RESPONSE - no response from Server UTE_UIDL_FAILED - UIDL command has timed out without a response from the server *********************************/ int CUT_POP3Client::RetrieveUID(int msgNumber) { int error = UTE_SUCCESS; // clear the current vector m_vecUID.erase(m_vecUID.begin(), m_vecUID.end()); //check to see if the connection is made if(!IsConnected()) return OnError(UTE_NOCONNECTION); //send the UIDL command if(msgNumber >= 1) _snprintf(m_szBuf,sizeof(m_szBuf)-1,"UIDL %d\r\n", msgNumber); else _snprintf(m_szBuf,sizeof(m_szBuf)-1,"UIDL\r\n"); Send(m_szBuf); //get the response if(ReceiveLine(m_szBuf,sizeof(m_szBuf),m_nPOP3TimeOut) <= 0) return OnError(UTE_SVR_NO_RESPONSE); if(m_szBuf[0] != '+') // '-' response probably flags 'not implemented'. return OnError(UTE_UIDL_FAILED); // UIDL was/is an optional POP3 option // If we are getting only one UID - get it from the response char szBuffer[MAX_UID_STRING_LENGTH + 1]; MessageUID messageID; if(msgNumber >= 1) { if(CUT_StrMethods::ParseString(m_szBuf," \r\n", 2, szBuffer, MAX_UID_STRING_LENGTH) != UTE_SUCCESS) return OnError(UTE_INVALID_RESPONSE); // Initialize UID structure messageID.m_nMessageNumber = msgNumber; messageID.m_strUID = szBuffer; // Add UID structure to the vector m_vecUID.push_back(messageID); } // We should get the multiline response with UIDs else { int len; while(!m_bReadTopFinished) { if(IsAborted()) { // Test for abortion flag error = UTE_ABORTED; break; } // read in a line len = ReceiveLine(m_szBuf,sizeof(m_szBuf),m_nPOP3TimeOut); if( len <= 0 ) { error = UTE_SOCK_TIMEOUT; break; } // end of multiline response if(m_szBuf[0] == '.' && len <= 3) break; // Get message number if(CUT_StrMethods::ParseString(m_szBuf," \r\n", 0, &messageID.m_nMessageNumber) != UTE_SUCCESS) { error = UTE_INVALID_RESPONSE; break; } // Get message UID if(CUT_StrMethods::ParseString(m_szBuf," \r\n", 1, szBuffer, MAX_UID_STRING_LENGTH) != UTE_SUCCESS) { error = UTE_INVALID_RESPONSE; break; } // Initialize UID structure messageID.m_strUID = szBuffer; // Add UID structure to the vector m_vecUID.push_back(messageID); } } return OnError(error); }
bool FlytecDevice::DownloadFlight(const RecordedFlightInfo &flight, Path path, OperationEnvironment &env) { port.StopRxThread(); PeriodClock status_clock; status_clock.Update(); // Request flight record char buffer[256]; sprintf(buffer, "$PBRTR,%02d", flight.internal.flytec); AppendNMEAChecksum(buffer); strcat(buffer, "\r\n"); port.Write(buffer); if (!ExpectXOff(port, env, 1000)) return false; // Open file writer FileHandle writer(path, _T("wb")); if (!writer.IsOpen()) return false; unsigned start_sec = flight.start_time.GetSecondOfDay(); unsigned end_sec = flight.end_time.GetSecondOfDay(); if (end_sec < start_sec) end_sec += 24 * 60 * 60; unsigned range = end_sec - start_sec; env.SetProgressRange(range); while (true) { // Check if the user cancelled the operation if (env.IsCancelled()) return false; // Receive the next line if (!ReceiveLine(port, buffer, ARRAY_SIZE(buffer), 1000)) return false; // XON was received if (StringIsEmpty(buffer)) break; if (status_clock.CheckUpdate(250) && *buffer == 'B') { // Parse the fix time BrokenTime time; if (IGCParseTime(buffer + 1, time)) { unsigned time_sec = time.GetSecondOfDay(); if (time_sec < start_sec) time_sec += 24 * 60 * 60; if (time_sec > end_sec + 5 * 60) time_sec = start_sec; unsigned position = time_sec - start_sec; if (position > range) position = range; env.SetProgressPosition(position); } } // Write line to the file writer.Write(buffer); } return true; }
/******************************** SaveMsg() Retrives (RETR) and Saves the specified message to the data source NOTE Message index is 1 based NOT zero based PARAM index - Index of the message to be saved dest - destination data source RETURN UTE_SUCCESS - Success UTE_NOCONNECTION - NOT connected UTE_SVR_NO_RESPONSE - no response from Server UTE_FILE_OPEN_ERROR - Not able to open file for writing UTE_RETR_FAILED - RETR command has timed out without a response from the server UTE_SOCK_TIMEOUT - Timed out while receiving parts of the message UTE_ABORTED - User canceled the Save to file process *********************************/ int CUT_POP3Client::SaveMsg(int index, CUT_DataSource & dest) { int error = UTE_SUCCESS; int len; UINT bytesReceived = 0; //check to see if the connection is made if(!IsConnected()) return OnError(UTE_NOCONNECTION); //open the destination file if(dest.Open(UTM_OM_WRITING) == -1) return OnError(UTE_FILE_OPEN_ERROR); //send the RETR command _snprintf(m_szBuf,sizeof(m_szBuf)-1,"RETR %d\r\n",index); Send(m_szBuf); //get the response if(ReceiveLine(m_szBuf,sizeof(m_szBuf)-1, m_nPOP3TimeOut) <= 0) return OnError(UTE_SVR_NO_RESPONSE); if(m_szBuf[0] != '+') return OnError(UTE_RETR_FAILED); //read in and save the message // v4.2 change to eliminate C4127: conditional expression is constant for(;;) { if(IsAborted()) { // Test for abortion flag error = UTE_ABORTED; break; } //read in a line len = ReceiveLine(m_szBuf,sizeof(m_szBuf)-1,m_nPOP3TimeOut); if( len <= 0 ) { error = UTE_SOCK_TIMEOUT; break; } bytesReceived += len; if (OnSaveMsg(bytesReceived) != TRUE) { error = UTE_ABORTED; // User cancel the save message break; // call status func } //if a period is found at the beginning of a line then //check to see if it is the end of the message if(m_szBuf[0] == '.') { //end of message if(len == 3) break; //save line else dest.Write(&m_szBuf[1], len-1); } else dest.Write(m_szBuf, len); } // Close data source dest.Close(); return OnError(error); }