SmartMailSvr.cpp
资源名称:SmartMailSvr [点击查看]
上传用户:qdlutongda
上传日期:2007-01-14
资源大小:133k
文件大小:94k
源码类别:
Email客户端
开发平台:
Visual C++
- // SmartMailSvr.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include "SmartMailSvr.h"
- #include "MailService.h"
- #include "dnsmx.h"
- #include "Encoder.h"
- #ifdef _DEBUG
- #define new DEBUG_NEW
- #undef THIS_FILE
- static char THIS_FILE[] = __FILE__;
- #endif
- #define MAXMESSAGELENGTH 255
- #define CURVER "1.0" //current version
- #define SOCKET_SIZE 1024
- /////////////////////////////////////////////////////////////////////////////
- // The one and only application object
- CWinApp theApp;
- typedef struct
- {
- char sender[50];
- char recver[50];
- char title[50];
- char time[20];
- long size;
- }_UDPPacketInfo;
- typedef struct
- {
- SOCKET sock;
- char fname[255];
- }_SendPop3Param;
- int gSocketUseCount = 0; //test
- /************* 变量 ****************/
- //TCP SOCKET服务对象
- SOCKET m_SocketPop3;
- SOCKET m_SocketSmtp;
- //UDP SOCKET对象
- UINT m_nUDPPort;
- CString m_strUDPIP;
- SOCKET m_UdpSocket;
- //FD_SET
- fd_set fdset, rfdset;
- //保存Socket连接的数组
- //CArray<SocketInfo,SocketInfo>m_SocketList;
- SocketInfo m_SocketList[SOCKET_SIZE];
- //要删除得邮件列表
- CArray<DeleteInfo,DeleteInfo>m_DeleteList;
- //m_DeleteList的临界区
- CRITICAL_SECTION m_csDeleteList;
- //通过其他SMTP Server发送的列表
- CArray<SMTPForwardInfo,SMTPForwardInfo> m_SMTPForwardList;
- //m_SMTPForwardList的临界区
- CRITICAL_SECTION m_csSMTPForward;
- //上述Socket对应的服务运行状态
- bool m_bPop3Allowed = false;
- bool m_bSmtpAllowed = false;
- bool m_bWebMailAllowed = false;
- bool m_bTelnetAllowed = false;
- //路径
- CString m_strExePath;
- //COM对象
- IMailSvrConfigCtrl* m_pMailConfig = NULL;
- IMailDB* m_pMailDB = NULL;
- //Log对象
- CLogFile m_logFile;
- //POP3 Message
- char pop3_msg00[MAXMESSAGELENGTH]; //+OK inetserv ready. %s
- char pop3_msg01[MAXMESSAGELENGTH]; //+OK HELO
- char pop3_msg02[MAXMESSAGELENGTH]; //-ERR unknown message
- char pop3_msg03[MAXMESSAGELENGTH]; //+OK user accepted
- char pop3_msg04[MAXMESSAGELENGTH]; //-ERR invalid username
- char pop3_msg05[MAXMESSAGELENGTH]; //welcome user!
- char pop3_msg06[MAXMESSAGELENGTH]; //wrong password for this user, try again!
- char pop3_msg07[MAXMESSAGELENGTH]; //OK closing connection
- char pop3_msg08[MAXMESSAGELENGTH]; // message not found
- char pop3_msg09[MAXMESSAGELENGTH]; // ok, rset
- char pop3_msg10[MAXMESSAGELENGTH]; // -ERR no data found
- char pop3_msg11[MAXMESSAGELENGTH]; // -ERR nothing to delete
- char pop3_msg12[MAXMESSAGELENGTH]; // +OK Message deleted
- char pop3_msg13[MAXMESSAGELENGTH]; // -ERR unknown command
- /************* 函数 ****************/
- bool Ini_MailCom(); //初始化COM,并连接数据库
- void Release_MailCom(); //释放COM
- UINT main_mailsvr(LPVOID); //主线程函数
- UINT Pop3_AcceptThread(LPVOID); //POP3接收连接线程函数
- UINT Smtp_AcceptThread(LPVOID); //SMTP接收连接线程函数
- UINT Pop3_ReceiveThread(LPVOID); //接收处理POP数据线程函数
- UINT Smtp_ReceiveThread(LPVOID); //接收处理SMTP数据线程函数
- void ReadPop3(char* buf, int nDataLen, int i); //处理POP3连接的数据处理
- void ReadSmtp(char* buf, int nDataLen, int i); //处理SMTP连接的数据处理
- void SendPop3Mail(SOCKET s, char* fileName); //向客户端发送Mail文件
- //UINT SendPop3Mail(LPVOID); //向客户端发送Mail文件
- void DeleteCRLF(char *string);
- void ProcessNewMail(CString CTL, CString Fname,CString Sender);
- void LogError (CString expr);
- void SendSMTP();
- int SendSmtpMail(int litem);
- int SendSmtpMailDirect(int litem);
- BOOL IsLocalUser(const char* tempstr); //判断是否是本地用户
- bool SendUDPData(_UDPPacketInfo udpData);
- bool WriteMailInfoToDB(CString strSender, CString strRecver, CString strTitle, CString strTime, long lSize);
- bool DealMailInfo(CString strFileName, CString strSender, CString strRecver);
- bool AddMessageID(CString strFileName); //加入Message-ID
- using namespace std;
- int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
- {
- int nRetCode = 0;
- // initialize MFC and print and error on failure
- if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
- {
- // TODO: change error code to suit your needs
- //cerr << _T("Fatal Error: MFC initialization failed") << endl;
- nRetCode = 1;
- }
- else
- {
- // TODO: code your application's behavior here.
- CMailService serv;
- // RegisterService() checks the parameterlist for predefined switches
- // (such as -d or -i etc.; see NTService.h for possible switches) and
- // starts the service's functionality.
- // You can use the return value from "RegisterService()"
- // as your exit-code.
- return serv.RegisterService(argc, argv);
- }
- return nRetCode;
- }
- bool Ini_MailCom()
- {
- //设置Log对象的路径
- CString strExePath;
- LPTSTR lpPath;
- lpPath = strExePath.GetBuffer(MAX_PATH);
- ::GetModuleFileName(NULL, lpPath, MAX_PATH);
- strExePath.ReleaseBuffer();
- int nPos = strExePath.ReverseFind('\');
- int nSize = strExePath.GetLength();
- m_logFile.SetLogFilePath(strExePath.Left(nPos + 1));
- CString strLog;
- //初始化COM库
- HRESULT hr;
- hr = ::CoInitialize(NULL);
- if(FAILED(hr))
- {
- m_logFile.WriteLog("CoInitialize() failed");
- return false;
- }
- //创建IMailSvrConfigCtrl接口指针
- hr = ::CoCreateInstance(CLSID_MailSvrConfigCtrl,
- NULL,
- CLSCTX_INPROC_SERVER,
- IID_IMailSvrConfigCtrl,
- (VOID FAR**)&m_pMailConfig);
- if(FAILED(hr))
- {
- m_logFile.WriteLog("CoCreateInstance() for IMailSvrConfigCtrl failed");
- return false;
- }
- //创建IMailDB接口指针
- hr = ::CoCreateInstance(CLSID_MailDB,
- NULL,
- CLSCTX_INPROC_SERVER,
- IID_IMailDB,
- (VOID FAR**)&m_pMailDB);
- if(FAILED(hr))
- {
- m_logFile.WriteLog("CoCreateInstance() for IMailDB failed");
- return false;
- }
- //检查参数配置是否正确
- short nCheckResult = 0;
- m_pMailConfig->CheckConfig(&nCheckResult);
- if(nCheckResult == 0)
- {
- m_logFile.WriteLog("Lack or Invalid Config In the Register");
- return false;
- }
- //连接数据库
- BSTR BstrConnectionString;
- m_pMailConfig->GetDBConnectionConfig(&BstrConnectionString);
- m_pMailDB->SetMailSvrDBConfig(BstrConnectionString);
- hr = m_pMailDB->ConnectMailSvrDB();
- if(FAILED(hr))
- {
- strLog.Format("Connect MailDB, ConnectionString=%S Failed", BstrConnectionString);
- m_logFile.WriteLog(strLog);
- return false;
- }
- strLog.Format("Connect MailDB, ConnectionString=%S Succeed", BstrConnectionString);
- m_logFile.WriteLog(strLog);
- //设置用户信息表名字段
- BSTR BstrUserTableName, BstrUserIDField, BstrUserPasswordField, BstrNameField;
- m_pMailConfig->GetUserTableConfig(&BstrUserTableName, &BstrUserIDField, &BstrUserPasswordField, &BstrNameField);
- m_pMailDB->SetMailUserTableConfig(BstrUserTableName, BstrUserIDField, BstrUserPasswordField, BstrNameField);
- strLog.Format("User Table Info: TableName=%S, UserIDField=%S, UserPasswordField=%S, UserNameField=%S",
- BstrUserTableName, BstrUserIDField, BstrUserPasswordField, BstrNameField);
- m_logFile.WriteLog(strLog);
- //设置接收的邮件信息表名和字段
- BSTR BstrRecvTableName, BstrTimeField, BstrTitleField, BstrSenderField, BstrRecverField, BstrSizeField;
- m_pMailConfig->GetRecvMailInfoTableConfig(&BstrRecvTableName, &BstrTimeField, &BstrTitleField,
- &BstrSenderField, &BstrRecverField, &BstrSizeField);
- m_pMailDB->SetMailRecvTableConfig(BstrRecvTableName, BstrTimeField, BstrTitleField,
- BstrSenderField, BstrRecverField, BstrSizeField);
- strLog.Format("RecvInfo Table Info: TableName=%S, TimeField=%S, TitleField=%S, SenderField=%S, RecverField=%S, SizeField=%S",
- BstrRecvTableName, BstrTimeField, BstrTitleField, BstrSenderField, BstrRecverField, BstrSizeField);
- m_logFile.WriteLog(strLog);
- WSADATA WSData;
- if (WSAStartup(MAKEWORD(1, 1), &WSData) )
- {
- m_logFile.WriteLog("Load socket lib failed");
- return false;
- }
- char chPath[256];
- GetModuleFileName(NULL,chPath,256);
- m_strExePath=chPath;
- for(int i=m_strExePath.GetLength();i>=0;i--)
- {
- if(m_strExePath.Mid(i,1)=="\"){
- m_strExePath=m_strExePath.Left(i);
- break;
- }
- }
- //创建默认文件夹
- CString strMailPath;
- strMailPath.Format("%s\mail", m_strExePath);
- CreateDirectory((LPCTSTR)strMailPath, NULL);
- strMailPath.Format("%s\mail\unknown", m_strExePath);
- CreateDirectory((LPCTSTR)strMailPath, NULL);
- // mkdir("mail");
- // mkdir("mail\unknown");
- short nCount;
- BSTR BstrUserID, BstrPass;
- CString strUserPath;
- m_pMailDB->GetUser(&nCount);
- for(int j=0; j<nCount; j++)
- {
- m_pMailDB->GetUserInfo(j, &BstrUserID, &BstrPass);
- bstr_t bstrUserID(BstrUserID, FALSE);
- strUserPath.Format("%s\mail\%s", m_strExePath, (char*)bstrUserID);
- CreateDirectory((LPCTSTR)strUserPath, NULL);
- }
- return true;
- }
- void Release_MailCom()
- {
- //释放IMailSvrConfigCtrl接口指针
- if(m_pMailConfig != NULL)
- m_pMailConfig->Release();
- //释放IMailDB接口指针
- if(m_pMailDB != NULL)
- {
- m_pMailDB->DisConnectMailSvrDB();
- m_pMailDB->Release();
- }
- //释放COM库
- ::CoUninitialize();
- //释放SOCKET库
- WSACleanup();
- }
- UINT main_mailsvr(LPVOID pParam)
- {
- if((m_pMailConfig == NULL)||(m_pMailDB == NULL))
- {
- m_logFile.WriteLog("Invalid IMailConfigCtrl or IMailDB pointer");
- return 0;
- }
- //初始化临界区
- ::InitializeCriticalSection(&m_csDeleteList);
- ::InitializeCriticalSection(&m_csSMTPForward);
- CString strLog;
- short nPop3Port, nSmtpPort;
- short nWebMailFlag, nWebMailPort;
- short nTelnetFlag, nTelnetPort;
- //读取参数
- m_pMailConfig->GetPop3Port(&nPop3Port);
- m_pMailConfig->GetSmtpPort(&nSmtpPort);
- m_pMailConfig->GetWebMailConfig(&nWebMailFlag, &nWebMailPort);
- m_pMailConfig->GetTelnetConfig(&nTelnetFlag, &nTelnetPort);
- //创建UDP SOCKET对象
- BSTR BstrUdpAdd;
- short nUdpPort;
- m_pMailConfig->GetUDPConfig(&BstrUdpAdd, &nUdpPort);
- _bstr_t bstrUdpAdd(BstrUdpAdd, FALSE);
- m_strUDPIP = (char*)bstrUdpAdd;
- m_nUDPPort = nUdpPort;
- FD_ZERO(&fdset);
- FD_ZERO(&rfdset);
- m_UdpSocket = socket(AF_INET, SOCK_DGRAM, 0);
- if(m_UdpSocket == INVALID_SOCKET)
- {
- m_logFile.WriteLog("FAILED to Create UDP Socket");
- closesocket(m_UdpSocket);
- }
- else
- m_logFile.WriteLog("Succeed to Create UDP Socket");
- //创建POP3侦听线程
- struct sockaddr_in pop3_add;
- m_SocketPop3 = socket(AF_INET, SOCK_STREAM, 0);
- if(m_SocketPop3 < 0)
- {
- strLog.Format("failed to create pop3 socket.");
- m_logFile.WriteLog(strLog);
- return 0;
- }
- strLog.Format("Succeed to Create POP3 Socket");
- m_logFile.WriteLog(strLog);
- memset((char*)&pop3_add, 0x0, sizeof(sockaddr_in));
- pop3_add.sin_family = AF_INET;
- pop3_add.sin_port = htons(nPop3Port);
- pop3_add.sin_addr.s_addr = htonl(INADDR_ANY);
- if(bind(m_SocketPop3, (struct sockaddr*)&pop3_add, sizeof(pop3_add)) < 0)
- {
- strLog.Format("failed to bind POP3 socket on Port %d.", nPop3Port);
- m_logFile.WriteLog(strLog);
- closesocket(m_SocketPop3);
- return 0;
- }
- strLog.Format("Succeed to bind Pop3 socket on Port %d", nPop3Port);
- m_logFile.WriteLog(strLog);
- if(listen(m_SocketPop3, 5) < 0)
- {
- strLog.Format("Failed to Listen Pop3 Socket");
- m_logFile.WriteLog(strLog);
- closesocket(m_SocketPop3);
- return 0;
- }
- strLog.Format("Succeed to Listen Pop3 Socket");
- m_logFile.WriteLog(strLog);
- FD_SET(m_SocketPop3, &fdset);
- //创建POP接受连接线程
- CWinThread * pop3_thread = NULL;
- pop3_thread = AfxBeginThread(Pop3_AcceptThread, NULL);
- if(pop3_thread == NULL)
- {
- strLog.Format("Failed to CreateThread for POP3");
- m_logFile.WriteLog(strLog);
- FD_CLR(m_SocketPop3, &fdset);
- closesocket(m_SocketPop3);
- return 0;
- }
- strLog.Format("Succeed to CreateThread for POP3");
- m_logFile.WriteLog(strLog);
- //创建SMTP侦听线程
- struct sockaddr_in smtp_add;
- m_SocketSmtp = socket(AF_INET, SOCK_STREAM, 0);
- if(m_SocketSmtp < 0)
- {
- strLog.Format("Failed to Create Socket for SMTP");
- m_logFile.WriteLog(strLog);
- return 0;
- }
- strLog.Format("Succeed to Create Socket for SMTP");
- m_logFile.WriteLog(strLog);
- memset((char*)&smtp_add, 0x0, sizeof(smtp_add));
- smtp_add.sin_family = AF_INET;
- smtp_add.sin_port = htons(nSmtpPort);
- smtp_add.sin_addr.s_addr = htonl(INADDR_ANY);
- if(bind(m_SocketSmtp, (struct sockaddr*)&smtp_add, sizeof(smtp_add)) < 0)
- {
- strLog.Format("Failed to bind SMTP Socket on Port %d", nSmtpPort);
- m_logFile.WriteLog(strLog);
- closesocket(m_SocketSmtp);
- TerminateThread(pop3_thread->m_hThread, 0);
- FD_CLR(m_SocketPop3, &fdset);
- closesocket(m_SocketPop3);
- return 0;
- }
- strLog.Format("Succeed to bind SMTP Socket on Port %d", nSmtpPort);
- m_logFile.WriteLog(strLog);
- if(listen(m_SocketSmtp, 5) < 0)
- {
- strLog.Format("Failed to listen SMTP Socket");
- m_logFile.WriteLog(strLog);
- closesocket(m_SocketSmtp);
- TerminateThread(pop3_thread->m_hThread, 0);
- FD_CLR(m_SocketPop3, &fdset);
- closesocket(m_SocketPop3);
- return 0;
- }
- strLog.Format("Succeed to listen SMTP Socket");
- m_logFile.WriteLog(strLog);
- FD_SET(m_SocketSmtp, &fdset);
- //创建SMTP Socket 接受线程
- CWinThread* smtp_thread = NULL;
- smtp_thread = AfxBeginThread(Smtp_AcceptThread, NULL);
- if(smtp_thread == NULL)
- {
- strLog.Format("Failed to CreateThread for SMTP");
- m_logFile.WriteLog(strLog);
- FD_CLR(m_SocketSmtp, &fdset);
- closesocket(m_SocketSmtp);
- TerminateThread(pop3_thread->m_hThread, 0);
- FD_CLR(m_SocketPop3, &fdset);
- closesocket(m_SocketPop3);
- return 0;
- }
- strLog.Format("Succeed to CreateThread for SMTP");
- m_logFile.WriteLog(strLog);
- //创建SMTP Realying处理线程
- unsigned long lThreadID;
- m_logFile.WriteLog("starting SMTP-Relay thread");
- HANDLE hSMTP = CreateThread(NULL,
- 0,
- (LPTHREAD_START_ROUTINE)SendSMTP,
- NULL,
- 0,
- &lThreadID);
- if(hSMTP == NULL)
- m_logFile.WriteLog("SMTP-Relay thread failed");
- else
- m_logFile.WriteLog("SMTP-Relay thread Started");
- sprintf(pop3_msg00,"");
- sprintf(pop3_msg01,"HELO d00d");
- sprintf(pop3_msg12,"no message found");
- sprintf(pop3_msg03,"user accepted");
- sprintf(pop3_msg04,"invalid username");
- sprintf(pop3_msg05,"welcome");
- sprintf(pop3_msg06,"wrong password for this user");
- sprintf(pop3_msg07,"closing connection");
- sprintf(pop3_msg08,"message not found");
- sprintf(pop3_msg09,"done");
- sprintf(pop3_msg10,"no data found");
- sprintf(pop3_msg11,"nothing to delete");
- sprintf(pop3_msg12,"Message deleted");
- sprintf(pop3_msg13,"unknown command");
- return 1;
- }
- UINT Pop3_AcceptThread(LPVOID pParam)
- {
- char send_data[255];
- CString strLog;
- CString strIP;
- UINT nPort;
- struct timeval timeout;
- struct sockaddr_in client_add;
- int nClientSock;
- int ret, len;
- len = sizeof(client_add);
- while(1)
- {
- if(FD_ISSET(m_SocketPop3, &fdset))
- {
- timeout.tv_sec = 60;
- timeout.tv_usec = 0;
- memcpy(&rfdset, &fdset, sizeof(fdset));
- ret = select(1, &rfdset, 0, 0, &timeout);
- if(ret < 0)
- {
- strLog.Format("select() failed for POP3 Socket");
- m_logFile.WriteLog(strLog);
- break;
- }
- memset(&client_add, 0x0, sizeof(client_add));
- nClientSock = accept(m_SocketPop3, (struct sockaddr*)&client_add, &len);
- if(nClientSock < 0)
- {
- strLog.Format("Pop3 Socket Accept Failed");
- m_logFile.WriteLog(strLog);
- break;
- }
- else
- {
- //test
- gSocketUseCount++;
- strLog.Format("*************Current Socket for POP3 Count=%d", gSocketUseCount);
- m_logFile.WriteLog(strLog);
- struct sockaddr_in peer_add;
- int nPeerLen = sizeof(peer_add);
- getpeername(nClientSock, (struct sockaddr*)&peer_add, &nPeerLen);
- strIP = inet_ntoa(peer_add.sin_addr);
- nPort = ntohs(peer_add.sin_port);
- strLog.Format("Get Pop3 Connection at IP=%s, PORT=%d", strIP, nPort);
- m_logFile.WriteLog(strLog);
- bool bFlag = false;
- for(int i=0; i<SOCKET_SIZE; i++)
- {
- if(m_SocketList[i].sock == -1)
- {
- bFlag = true;
- break;
- }
- }
- if(!bFlag)
- {
- strLog.Format("Not Enough Socket buff for the Connection");
- m_logFile.WriteLog(strLog);
- continue;
- }
- m_SocketList[i].typ = 1;
- m_SocketList[i].sock = nClientSock;
- m_SocketList[i].ip = strIP;
- FD_SET(nClientSock, &fdset);
- sprintf(send_data, "+OK POP3 on Smart Mail Server for M-Office (%s) ready. %srn",CURVER,pop3_msg00);
- send(nClientSock, send_data, strlen(send_data), 0);
- //启动接收数据线程
- AfxBeginThread(Pop3_ReceiveThread, (LPVOID)i);
- strLog.Format("Start Thread %d",i);
- m_logFile.WriteLog(strLog);
- }
- }
- else
- break;
- }
- return 0;
- }
- UINT Smtp_AcceptThread(LPVOID pParam)
- {
- char send_data[255];
- CString strLog;
- CString strIP;
- UINT nPort;
- struct timeval timeout;
- struct sockaddr_in client_add;
- int nClientSock;
- int ret, len;
- len = sizeof(client_add);
- //接收SMTP连接
- while(1)
- {
- if(FD_ISSET(m_SocketSmtp, &fdset))
- {
- timeout.tv_sec = 10;
- timeout.tv_usec = 0;
- memcpy(&rfdset, &fdset, sizeof(fdset));
- ret = select(1, &rfdset, 0, 0, &timeout);
- if(ret < 0)
- {
- strLog.Format("select() failed for SMTP socket");
- m_logFile.WriteLog(strLog);
- break;
- }
- memset(&client_add, 0x0, sizeof(client_add));
- nClientSock = accept(m_SocketSmtp, (struct sockaddr*)&client_add, &len);
- if(nClientSock < 0)
- {
- strLog.Format("SMTP Socket Accept Failed");
- m_logFile.WriteLog(strLog);
- break;
- }
- else
- {
- struct sockaddr_in peer_add;
- int nPeerLen = sizeof(peer_add);
- getpeername(nClientSock, (struct sockaddr*)&peer_add, &nPeerLen);
- strIP = inet_ntoa(peer_add.sin_addr);
- nPort = ntohs(peer_add.sin_port);
- strLog.Format("Get SMTP Connection at IP=%s, PORT=%d", strIP, nPort);
- m_logFile.WriteLog(strLog);
- bool bFlag = false;
- for(int i=0; i<SOCKET_SIZE; i++)
- {
- if(m_SocketList[i].sock == -1)
- {
- bFlag = true;
- break;
- }
- }
- if(!bFlag)
- {
- strLog.Format("Not Enough Socket buff for the Connection");
- m_logFile.WriteLog(strLog);
- continue;
- }
- m_SocketList[i].typ = 2;
- m_SocketList[i].sock = nClientSock;
- m_SocketList[i].ip = strIP;
- FD_SET(nClientSock, &fdset);
- sprintf(send_data, "220 SMTP on Smart Mail Server for M-Office(%s) ready.rn",CURVER);
- send(nClientSock, send_data, strlen(send_data), 0);
- //创建线程
- AfxBeginThread(Smtp_ReceiveThread, (LPVOID)i);
- }
- }
- else
- break;
- }
- return 1;
- }
- UINT Pop3_ReceiveThread(LPVOID pParam)
- {
- CString strLog;
- int index = (int)pParam;
- char buff[1025];
- while(1)
- {
- memset(buff, 0x0, sizeof(buff));
- int ret = recv(m_SocketList[index].sock, (char*)buff, 1024, 0);
- if(ret <= 0)
- {
- // strLog.Format("recv() from pop3 client failed");
- // m_logFile.WriteLog(strLog);
- if(m_SocketList[index].sock != -1)
- {
- FD_CLR(m_SocketList[index].sock, &fdset);
- closesocket(m_SocketList[index].sock);
- m_SocketList[index].sock = -1;
- //test
- gSocketUseCount--;
- strLog.Format("***********Close socket for Pop3 Connection, SocketCOunt=%d", gSocketUseCount);
- m_logFile.WriteLog(strLog);
- m_SocketList[index].showlog = FALSE;
- m_SocketList[index].status2 = 0;
- m_SocketList[index].status = 0;
- m_SocketList[index].typ = 0;
- m_SocketList[index].openf= 0;
- m_SocketList[index].Temp = "";
- m_SocketList[index].Username = "unknown";
- m_SocketList[index].dontwrite = FALSE;
- }
- break;
- }
- else
- {
- ReadPop3(buff, ret, index); //处理数据
- }
- }
- return 1;
- }
- UINT Smtp_ReceiveThread(LPVOID pParam)
- {
- CString strLog;
- int index = (int)pParam;
- char buff[1025];
- while(1)
- {
- int ret = recv(m_SocketList[index].sock, (char*)buff, 1024, 0);
- if(ret <= 0)
- {
- // strLog.Format("recv() from SMTP client failed");
- // m_logFile.WriteLog(strLog);
- if(m_SocketList[index].sock != -1)
- {
- FD_CLR(m_SocketList[index].sock, &fdset);
- closesocket(m_SocketList[index].sock);
- m_SocketList[index].sock = -1;
- }
- break;
- }
- else
- {
- ReadSmtp(buff, ret, index); //处理数据
- }
- }
- return 1;
- }
- void ReadPop3(char* buf, int nDataLen, int i)
- {
- CString strLog;
- SOCKET sock_temp = m_SocketList[i].sock;
- // char buf[1025];
- CString tempstr = "";
- // int nix = pSocket->Receive(&buf, 1024,0);
- int nix = nDataLen;
- buf[nix] = ' ';
- strLog.Format("SOCKET=%d Pop3 Received buf[%d]: %s", sock_temp, i, buf);
- m_logFile.WriteLog(strLog);
- CString tempcstr;
- tempstr = buf;
- char sendstr[255];
- tempcstr = tempstr;
- m_SocketList[i].Temp = m_SocketList[i].Temp + tempstr;
- if (m_SocketList[i].Temp.GetLength()>240)
- {
- m_SocketList[i].Temp = "";
- return;
- }; //buffer to large problem
- tempstr = m_SocketList[i].Temp;
- if(tempstr.GetLength() == 0)
- return ;
- if(tempstr.GetAt(tempstr.GetLength()-1) != 'n')
- return;
- strLog.Format("SOCKET=%d Pop3 Received aaaaaa[%d]: %s", sock_temp, i, tempstr);
- m_logFile.WriteLog(strLog);
- char tempstrU[255];
- sprintf(tempstrU,"%s",tempstr);
- strupr(tempstrU);
- //AUTH command
- if ((tempstrU[0] == 'A') && (tempstrU[1] == 'U')
- && (tempstrU[2] == 'T') && (tempstrU[3] == 'H')
- && (tempstrU[4] == ' ') )
- {
- sprintf(sendstr,"-ERR %srn",pop3_msg02);
- send (sock_temp, sendstr,strlen(sendstr),0);
- m_SocketList[i].Temp = "";
- return;
- }
- //USER command
- if ((tempstrU[0] == 'U') && (tempstrU[1] == 'S')
- && (tempstrU[2] == 'E') && (tempstrU[3] == 'R')
- && (tempstrU[4] == ' ') )
- {
- sprintf(sendstr,"+OK %srn",pop3_msg03);
- send(sock_temp, sendstr,strlen(sendstr),0);
- char tempstr2[255];
- sprintf(tempstr2,"%s",tempstr);
- for (UINT z = 5; z<= strlen(tempstr2);z++)
- {
- tempstr2[z-5] = tempstr2[z];
- }
- tempstr2[z-5] = ' ';
- CString tempcstr;
- if (tempstr2[strlen(tempstr2)-2] == 'n') tempstr2[strlen(tempstr2)-2] = ' ';
- if (tempstr2[strlen(tempstr2)-2] == 'r') tempstr2[strlen(tempstr2)-2] = ' ';
- tempcstr = tempstr2;
- m_SocketList[i].Username= tempcstr;
- m_SocketList[i].status = 1;
- m_SocketList[i].Temp = "";
- return;
- }
- //XSENDER command
- if ((tempstrU[0] == 'X') && (tempstrU[1] == 'S')
- && (tempstrU[2] == 'E') && (tempstrU[3] == 'N')
- && (tempstrU[4] == 'D') && (tempstrU[5] == 'E')
- && (tempstrU[6] == 'R') && (tempstrU[7] == ' '))
- {
- send(sock_temp, "+OKrn",5,0);
- m_SocketList[i].Temp = "";
- return;
- }
- //PASS command
- if (((tempstrU[0] == 'P') && (tempstrU[1] == 'A')
- && (tempstrU[2] == 'S') && (tempstrU[3] == 'S')
- && (tempstrU[4] == ' ') ) && (m_SocketList[i].status == 1))
- {
- bool bOK = false;
- //查询数据库,查找对应的用户
- HRESULT hr;
- BSTR BstrUserID, BstrPassword, BstrName;
- CString strUserID, strPassword;
- strUserID.Format("%s", m_SocketList[i].Username);
- BstrUserID = strUserID.AllocSysString();
- hr = m_pMailDB->FindUserByUserID(BstrUserID, &BstrPassword, &BstrName);
- if(FAILED(hr)) //查询失败
- m_logFile.WriteLog("Seach the UserID from DB Failed");
- else
- {
- _bstr_t bstrPassword(BstrPassword, FALSE);
- strPassword = (char*)bstrPassword;
- if(strPassword != "") //存在此用户,不存在该用户时Password返回空
- bOK = true;
- }
- if (!bOK)
- {
- strLog.Format("SOCKET=%d POP3 Login incorrect: User=%s not Exist from IP=%s", sock_temp, m_SocketList[i].Username, m_SocketList[i].ip);
- m_logFile.WriteLog(strLog);
- sprintf(sendstr,"-ERR %srn",pop3_msg04);
- send (sock_temp, sendstr,strlen(sendstr),0);
- m_SocketList[i].status = 0;
- m_SocketList[i].Temp = "";
- return;
- }
- char tempstr2[255];
- sprintf(tempstr2,"%s",tempstr);
- for (UINT z = 5; z<= strlen(tempstr2);z++)
- {
- tempstr2[z-5] = tempstr2[z];
- }
- tempstr2[z-5] = ' ';
- CString tempcstr;
- if (tempstr2[strlen(tempstr2)-2] == 'n') tempstr2[strlen(tempstr2)-2] = ' ';
- if (tempstr2[strlen(tempstr2)-2] == 'r') tempstr2[strlen(tempstr2)-2] = ' ';
- if (strPassword == tempstr2)
- {
- strLog.Format("SOCKET=%d User login: UserID=%s from IP=%s",sock_temp,m_SocketList[i].Username,m_SocketList[i].ip);
- m_logFile.WriteLog(strLog);
- sprintf(sendstr,"+OK %srn",pop3_msg05);
- send(sock_temp, sendstr,strlen(sendstr),0);
- strLog.Format("SOCKET=%d send:%s", sock_temp, sendstr);
- m_logFile.WriteLog(strLog);
- m_SocketList[i].Temp = "";
- m_SocketList[i].status = 2;
- }
- else
- {
- sprintf(sendstr,"-ERR %srn",pop3_msg06);
- send (sock_temp, sendstr,strlen(sendstr),0);
- m_SocketList[i].Temp = "";
- m_SocketList[i].status = 0;
- strLog.Format("Login incorrect: User=%s from IP=%s", m_SocketList[i].Username, m_SocketList[i].ip);
- m_logFile.WriteLog(strLog);
- }
- return;
- }
- //NOOP command
- if ((tempstrU[0] == 'N') && (tempstrU[1] == 'O')
- && (tempstrU[2] == 'O') && (tempstrU[3] == 'P') )
- {
- send (sock_temp, "+OKrn",5,0);
- m_SocketList[i].Temp = "";
- return;
- }
- //QUIT command
- if ((tempstrU[0] == 'Q') && (tempstrU[1] == 'U')
- && (tempstrU[2] == 'I') && (tempstrU[3] == 'T') )
- {
- sprintf(sendstr,"+OK %srn",pop3_msg07);
- send(sock_temp, sendstr,strlen(sendstr),0);
- for (int z = 0; z < m_DeleteList.GetSize(); z++)
- {
- if (m_SocketList[i].sock == m_DeleteList[z].sock)
- {
- int m = DeleteFile(m_strExePath + "\" +m_DeleteList[z].Filename);
- ::EnterCriticalSection(&m_csDeleteList);
- m_DeleteList.RemoveAt(z);
- ::LeaveCriticalSection(&m_csDeleteList);
- z--;
- }
- }
- //关闭该socket
- if(m_SocketList[i].sock != -1)
- {
- //test
- /* gSocketUseCount--;
- strLog.Format("***********Close socket for Pop3 Connection, SocketCOunt=%d", gSocketUseCount);
- m_logFile.WriteLog(strLog);
- FD_CLR(m_SocketList[i].sock, &fdset);
- closesocket(m_SocketList[i].sock);
- m_SocketList[i].sock = -1;
- strLog.Format("Connection closed for %s",m_SocketList[i].ip);
- m_logFile.WriteLog(strLog);
- m_SocketList[i].showlog = FALSE;
- m_SocketList[i].status2 = 0;
- m_SocketList[i].status = 0;
- m_SocketList[i].typ = 0;
- m_SocketList[i].openf= 0;
- m_SocketList[i].Temp = "";
- m_SocketList[i].Username = "unknown";
- m_SocketList[i].dontwrite = FALSE;
- */
- }
- return;
- }
- //LIST command
- if ((tempstrU[0] == 'L') && (tempstrU[1] == 'I')
- && (tempstrU[2] == 'S') && (tempstrU[3] == 'T')
- && (m_SocketList[i].status == 2))
- {
- char fstr[255];
- sprintf(fstr,"%s\mail\%s\*.in",m_strExePath, m_SocketList[i].Username);
- HANDLE hFind;
- WIN32_FIND_DATA findData = {0};
- char tempinf[255];
- char tempbuf[1024];
- sprintf(tempbuf,"");
- int c = 0;
- int length = 0;
- if(strlen(tempstrU) == 6)
- {
- hFind = FindFirstFile (fstr, &findData);
- if (hFind != INVALID_HANDLE_VALUE)
- {
- do
- {
- if (findData.cFileName[0] != '.')
- {
- c++;
- length = length + (findData.nFileSizeHigh * MAXDWORD) + findData.nFileSizeLow;
- }
- }while (FindNextFile(hFind, &findData));
- sprintf(tempbuf,"+OK %i %irn",c,length);
- FindClose (hFind);
- }
- c = 0;
- length = 0;
- hFind = FindFirstFile (fstr, &findData);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- send (sock_temp, "+OK 0 0rn.rn",9,0);
- strLog.Format("SOCKET=%d send:+OK 0 0rn.rn", sock_temp);
- m_logFile.WriteLog(strLog);
- }
- else
- {
- do
- {
- if (findData.cFileName[0] != '.')
- {
- c++;
- length = (findData.nFileSizeHigh * MAXDWORD) + findData.nFileSizeLow;
- sprintf(tempbuf,"%s%i %irn",tempbuf,c,length);
- }
- } while (FindNextFile(hFind, &findData));
- sprintf(tempbuf,"%s.rn",tempbuf);
- send (sock_temp, tempbuf,strlen(tempbuf),0);
- strLog.Format("SOCKET=%d send:%s", sock_temp, tempbuf);
- m_logFile.WriteLog(strLog);
- FindClose (hFind);
- }
- }
- else
- {
- int nr;
- hFind = FindFirstFile (fstr, &findData);
- DeleteCRLF(tempstrU);
- int foundit = 0;
- sscanf(tempstrU,"%s %i",tempinf,&nr);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- send (sock_temp, "+OK 0 0rn",9,0);
- strLog.Format("SOCKET=%d send:+OK 0 0rn", sock_temp);
- m_logFile.WriteLog(strLog);
- }
- else
- {
- do
- {
- if (findData.cFileName[0] != '.')
- {
- c++;
- if (c == nr)
- {
- foundit = 1;
- length = (findData.nFileSizeHigh * MAXDWORD) + findData.nFileSizeLow;
- }
- }
- } while (FindNextFile(hFind, &findData));
- if (foundit == 1)
- sprintf(tempinf,"+OK %i %irn",nr,length);
- if (foundit == 0)
- sprintf(tempinf,"-ERR %srn",pop3_msg08);
- send (sock_temp, tempinf,strlen(tempinf),0);
- strLog.Format("SOCKET=%d send:%s", sock_temp,tempinf);
- m_logFile.WriteLog(strLog);
- FindClose (hFind);
- }
- }
- m_SocketList[i].Temp = "";
- return;
- }
- //RSET command
- if ((tempstrU[0] == 'R') && (tempstrU[1] == 'S')
- && (tempstrU[2] == 'E') && (tempstrU[3] == 'T') )
- {
- sprintf(sendstr,"+OK %srn",pop3_msg09);
- send (sock_temp, sendstr,strlen(sendstr),0);
- m_SocketList[i].Temp = "";
- m_SocketList[i].status = 0;
- return;
- }
- //RETR command
- if ((tempstrU[0] == 'R') && (tempstrU[1] == 'E')
- && (tempstrU[2] == 'T') && (tempstrU[3] == 'R')
- && (tempstrU[4] == ' ')&& (m_SocketList[i].status >= 2) )
- {
- char tempstr2[255];
- sprintf(tempstr2,tempstr);
- for (UINT z = 5; z<= strlen(tempstr2);z++)
- {
- tempstr2[z-5] = tempstr2[z];
- }
- tempstr2[z-5] = ' ';
- CString tempcstr;
- if (tempstr2[strlen(tempstr2)-2] == 'n') tempstr2[strlen(tempstr2)-2] = ' ';
- if (tempstr2[strlen(tempstr2)-2] == 'r') tempstr2[strlen(tempstr2)-2] = ' ';
- tempcstr = tempstr2;
- int iretr = atoi(tempcstr); //the number of the mail...
- char fstr[255];
- sprintf(fstr,"%s\mail\%s\*.in", m_strExePath, m_SocketList[i].Username);
- HANDLE hFind;
- char fname[255];
- WIN32_FIND_DATA findData = {0};
- hFind = FindFirstFile (fstr, &findData);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- sprintf(sendstr,"-ERR %srn",pop3_msg10);
- send (sock_temp, sendstr,strlen(sendstr),0);
- }
- else
- {
- int c = 0;
- int length = 0;
- BOOL found = FALSE;
- int status1 = 0;
- do
- {
- if (findData.cFileName[0] != '.')
- {
- c++;
- length = length + (findData.nFileSizeHigh * MAXDWORD) + findData.nFileSizeLow;
- if (c == iretr)
- {
- found = TRUE;
- sprintf(sendstr,"+OK %i octetsrn",length);
- int len=strlen(sendstr);
- send(sock_temp, sendstr, strlen(sendstr), 0);
- sprintf(fname,"mail\%s\%s", m_SocketList[i].Username, findData.cFileName);
- //发送Mail内容
- SendPop3Mail(sock_temp, fname);
- /* _SendPop3Param* pSock_file = new _SendPop3Param;
- pSock_file->sock = sock_temp;
- memcpy(&pSock_file->fname, fname, sizeof(pSock_file->fname));
- AfxBeginThread(SendPop3Mail, (LPVOID)pSock_file );
- */
- }
- }
- }
- while (FindNextFile(hFind, &findData));
- FindClose (hFind);
- if (found == FALSE)
- {
- sprintf(sendstr,"-ERR %srn",pop3_msg10);
- send (sock_temp, sendstr,strlen(sendstr),0);
- }
- }
- m_SocketList[i].Temp = "";
- return;
- }
- //TOP command
- if ((tempstrU[0] == 'T') && (tempstrU[1] == 'O')
- && (tempstrU[2] == 'P') && (tempstrU[3] == ' ') && (m_SocketList[i].status == 2))
- {
- char tempstr2[255];
- sprintf(tempstr2,tempstr);
- CString tempcstr;
- if (tempstr2[strlen(tempstr2)-2] == 'n') tempstr2[strlen(tempstr2)-2] = ' ';
- if (tempstr2[strlen(tempstr2)-2] == 'r') tempstr2[strlen(tempstr2)-2] = ' ';
- tempcstr = tempstr2;
- char tempstr1[255];
- char mesgn[255];
- sprintf(mesgn,"");
- char lines[255];
- sprintf(lines,"");
- sscanf(tempcstr,"%s %s %s",tempstr1,mesgn,lines);
- int iretr = atoi(mesgn);
- char fstr[255];
- sprintf(fstr,"%s\mail\%s\*.in", m_strExePath, m_SocketList[i].Username);
- HANDLE hFind;
- char fname[255];
- WIN32_FIND_DATA findData = {0};
- char outstr[255];
- int err;
- BOOL found = FALSE;
- FILE *outmail;
- hFind = FindFirstFile (fstr, &findData);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- send (sock_temp, "-ERR No data foundrn",20,0);
- strLog.Format("SOCKET=%d send:-ERR No data foundrn", sock_temp);
- m_logFile.WriteLog(strLog);
- }
- else
- {
- int c = 0;
- int length = 0;
- int status1 = 0;
- do
- {
- if (findData.cFileName[0] != '.')
- {
- c++;
- length = length + (findData.nFileSizeHigh * MAXDWORD) + findData.nFileSizeLow;
- if (c == iretr)
- {
- char sendstr[255];
- int ilines = abs(atoi(lines));
- //if (ilines == 0) ilines = 10;
- //sprintf(sendstr,"+OK showing %i linesrn",ilines);
- sprintf(sendstr,"+OKrn");
- send (sock_temp, sendstr,strlen(sendstr),0);
- sprintf(fname,"%s\mail\%s\%s", m_strExePath,
- m_SocketList[i].Username, findData.cFileName);
- if( (outmail= fopen(fname, "rb" )) != NULL )
- {
- //for (int ii = 0;ii<ilines;ii++)
- int SendLines=0;
- for (;;)
- {
- memset(outstr,0x0,255);
- fgets(outstr,254,outmail);
- if (!feof(outmail))
- {
- //outstr[strlen(outstr)-2] = 'n';
- outstr[strlen(outstr)] = ' ';
- int nbyte;
- nbyte = send (sock_temp, outstr,strlen(outstr),0);
- strLog.Format("SOCKET=%d send:%s", sock_temp,outstr);
- m_logFile.WriteLog(strLog);
- if(nbyte < 0)
- {
- err = GetLastError();
- if(err == WSAEWOULDBLOCK)
- {
- while(err == WSAEWOULDBLOCK)
- {
- send (sock_temp, outstr,strlen(outstr),0);
- strLog.Format("SOCKET=%d send:%s", sock_temp,outstr);
- m_logFile.WriteLog(strLog);
- err = GetLastError();
- }
- }
- else
- {
- fclose(outmail);
- send (sock_temp, "-ERR Server Send Data Errorrn",20,0);
- strLog.Format("SOCKET=%d send:-ERR Server Send Data Errorrn", sock_temp);
- m_logFile.WriteLog(strLog);
- return;
- }
- }
- }else
- {
- break;
- }
- if((strlen(outstr)==2 && SendLines==0) || SendLines >0)
- SendLines++;
- if (SendLines > ilines)
- break;
- }
- found = TRUE;
- if (!feof(outmail))
- {
- send (sock_temp, ".rn",3,0);
- strLog.Format("SOCKET=%d send:.rn", sock_temp);
- m_logFile.WriteLog(strLog);
- }
- fclose(outmail);
- }
- }
- }
- }
- while (FindNextFile(hFind, &findData));
- FindClose (hFind);
- }
- if (found == FALSE)
- {
- send (sock_temp, "-ERR No data foundrn",20,0);
- strLog.Format("SOCKET=%d send:-ERR No data foundrn", sock_temp);
- m_logFile.WriteLog(strLog);
- }
- m_SocketList[i].Temp = "";
- return;
- }
- //DELE command
- if (((tempstrU[0] == 'D') && (tempstrU[1] == 'E')
- && (tempstrU[2] == 'L') && (tempstrU[3] == 'E')
- && (tempstrU[4] == ' ')) && (m_SocketList[i].status == 2))
- {
- char tempstr2[255];
- sprintf(tempstr2,tempstr);
- for (UINT z = 5; z<= strlen(tempstr2);z++)
- {
- tempstr2[z-5] = tempstr2[z];
- }
- tempstr2[z-5] = ' ';
- CString tempcstr;
- if (tempstr2[strlen(tempstr2)-2] == 'n') tempstr2[strlen(tempstr2)-2] = ' ';
- if (tempstr2[strlen(tempstr2)-2] == 'r') tempstr2[strlen(tempstr2)-2] = ' ';
- tempcstr = tempstr2;
- int iretr = atoi(tempcstr);
- char fstr[255];
- sprintf(fstr,"%s\mail\%s\*.in", m_strExePath, m_SocketList[i].Username);
- DeleteInfo Mydelinfo;
- Mydelinfo.sock = m_SocketList[i].sock;
- HANDLE hFind;
- char fname[255];
- WIN32_FIND_DATA findData = {0};
- hFind = FindFirstFile (fstr, &findData);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- sprintf(sendstr,"-ERR %srn",pop3_msg11);
- send (sock_temp, sendstr,strlen(sendstr),0);
- }
- else
- {
- int c = 0;
- BOOL found = FALSE;
- do
- {
- if (findData.cFileName[0] != '.')
- {
- c++;
- if (c == iretr)
- {
- sprintf(fname,"mail\%s\%s", m_SocketList[i].Username, findData.cFileName);
- Mydelinfo.Filename = fname;
- m_DeleteList.Add(Mydelinfo);
- sprintf(sendstr,"+OK %srn",pop3_msg12);
- send (sock_temp, sendstr,strlen(sendstr),0);
- found = TRUE;
- }
- }
- }while (FindNextFile(hFind, &findData));
- FindClose (hFind);
- if (found == FALSE)
- {
- sprintf(sendstr,"-ERR %srn",pop3_msg11);
- send (sock_temp, sendstr,strlen(sendstr),0);
- }
- }
- m_SocketList[i].Temp = "";
- return;
- }
- //STAT command
- if (((tempstrU[0] == 'S') && (tempstrU[1] == 'T')
- && (tempstrU[2] == 'A') && (tempstrU[3] == 'T')
- ) && (m_SocketList[i].status == 2))
- {
- char fstr[255];
- sprintf(fstr,"%s\mail\%s\*.in", m_strExePath, m_SocketList[i].Username);
- char tempinf[255];
- HANDLE hFind;
- WIN32_FIND_DATA findData = {0};
- hFind = FindFirstFile (fstr, &findData);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- send (sock_temp, "+OK 0 0rn",9,0);
- strLog.Format("SOCKET=%d send:+OK 0 0rn", sock_temp);
- m_logFile.WriteLog(strLog);
- }
- else
- {
- int c = 0;
- int length = 0;
- do
- {
- if (findData.cFileName[0] != '.')
- {
- c++;
- length = length + (findData.nFileSizeHigh * MAXDWORD) + findData.nFileSizeLow;
- }
- } while (FindNextFile(hFind, &findData));
- sprintf(tempinf,"+OK %i %irn",c,length);
- send (sock_temp, tempinf,strlen(tempinf),0);
- strLog.Format("SOCKET=%d send:%s", sock_temp, tempinf);
- m_logFile.WriteLog(strLog);
- FindClose (hFind);
- }
- m_SocketList[i].Temp = "";
- return;
- }
- sprintf(sendstr,"-ERR %srn",pop3_msg13);
- send (sock_temp, sendstr,strlen(sendstr),0);
- strLog.Format("SOCKET=%d send:%s", sock_temp, sendstr);
- m_logFile.WriteLog(strLog);
- if (tempstr[tempstr.GetLength()-1] == 'n')
- m_SocketList[i].Temp = "";
- }
- void ReadSmtp(char* buf, int nDataLen, int i)
- {
- CString strLog;
- SOCKET sock_temp = m_SocketList[i].sock;
- // char buf[1025];
- CString tempstr;
- FILE *stream;
- // int nix = pSocket->Receive(&buf, 1024,0);
- int nix = nDataLen;
- buf[nix] = ' ';
- if (m_SocketList[i].status >= 5) // get a mail... :)
- {
- //将收到的邮件内容以流的形式写入文件
- // fprintf(m_SocketList[i].mail,"%s",buf);
- m_SocketList[i].strHead = m_SocketList[i].strHead+ buf;
- if(m_SocketList[i].bTransHead == 0) //信件头部未传输完毕
- {
- if(m_SocketList[i].strHead.Find("rnrn") > -1)
- {
- m_SocketList[i].bTransHead = 1;
- CString strTemp=m_SocketList[i].strHead;
- strTemp.MakeUpper();
- if(strTemp.Find("rnMESSAGE-ID:") >-1 || strTemp.Find("MESSAGE-ID:") == 0)
- {
- fprintf(m_SocketList[i].mail,"%s",m_SocketList[i].strHead);
- m_SocketList[i].strHead="";
- }else
- {
- //产生message-id
- char chMessageID[100];
- time_t tm;
- time(&tm);
- srand((unsigned)time(NULL));
- sprintf(chMessageID, "Message-ID: <%d.%d.smartmailserver@m_office.com>rn", tm, rand());
- strTemp=chMessageID+m_SocketList[i].strHead;
- fprintf(m_SocketList[i].mail,"%s",strTemp);
- m_SocketList[i].strHead="";
- }
- }
- }else
- {
- if(m_SocketList[i].strHead.GetLength()>4096)
- {
- if(fprintf(m_SocketList[i].mail,"%s",m_SocketList[i].strHead)!=m_SocketList[i].strHead.GetLength())
- {
- CString strLog;
- strLog.Format("Write file %s error",m_SocketList[i].Fname);
- m_logFile.WriteLog(strLog);
- }
- m_SocketList[i].strHead = "";
- }
- }
- if (nix == 1)
- {
- m_SocketList[i].crstr[0] = m_SocketList[i].crstr[1];
- m_SocketList[i].crstr[1] = m_SocketList[i].crstr[2];
- m_SocketList[i].crstr[2] = m_SocketList[i].crstr[3];
- m_SocketList[i].crstr[3] = m_SocketList[i].crstr[4];
- m_SocketList[i].crstr[4] = buf[0];
- }
- if (nix == 2)
- {
- m_SocketList[i].crstr[0] = m_SocketList[i].crstr[2];
- m_SocketList[i].crstr[1] = m_SocketList[i].crstr[3];
- m_SocketList[i].crstr[2] = m_SocketList[i].crstr[4];
- m_SocketList[i].crstr[3] = buf[0];
- m_SocketList[i].crstr[4] = buf[1];
- }
- if (nix == 3)
- {
- m_SocketList[i].crstr[0] = m_SocketList[i].crstr[3];
- m_SocketList[i].crstr[1] = m_SocketList[i].crstr[4];
- m_SocketList[i].crstr[2] = buf[0];
- m_SocketList[i].crstr[3] = buf[1];
- m_SocketList[i].crstr[4] = buf[2];
- }
- if (nix == 4)
- {
- m_SocketList[i].crstr[0] = m_SocketList[i].crstr[1];
- m_SocketList[i].crstr[1] = buf[0];
- m_SocketList[i].crstr[2] = buf[1];
- m_SocketList[i].crstr[3] = buf[2];
- m_SocketList[i].crstr[4] = buf[3];
- }
- if (nix == 5)
- {
- m_SocketList[i].crstr[0] = buf[0];
- m_SocketList[i].crstr[1] = buf[1];
- m_SocketList[i].crstr[2] = buf[2];
- m_SocketList[i].crstr[3] = buf[3];
- m_SocketList[i].crstr[4] = buf[4];
- }
- if (nix > 5)
- {
- m_SocketList[i].crstr[0] = buf[nix-5];
- m_SocketList[i].crstr[1] = buf[nix-4];
- m_SocketList[i].crstr[2] = buf[nix-3];
- m_SocketList[i].crstr[3] = buf[nix-2];
- m_SocketList[i].crstr[4] = buf[nix-1];
- }
- /*
- if(m_SocketList[i].bTransHead == 0) //信件头部未传输完毕
- {
- CString strTemp=m_SocketList[i].crstr;
- strTemp=strTemp+buf;
- strTemp.MakeUpper();
- //查找Message-ID:
- if(strTemp.Find("rnMESSAGE-ID:") >-1)
- {
- m_SocketList[i].bFinded = 1;
- }
- int pos=strTemp.Find("rnrn");
- if(pos > -1)//信件头部已经传输完毕
- {
- m_SocketList[i].bTransHead = 1;
- if(m_SocketList[i].bFinded ==0) //在头部没有发现Message-ID
- {
- //产生message-id
- char chMessageID[100];
- time_t tm;
- time(&tm);
- srand((unsigned)time(NULL));
- sprintf(chMessageID, "Message-ID: <%d.%d.smartmailserver@m_office.com>rn", tm, rand());
- CString strBuf=m_SocketList[i].crstr;
- strBuf=strBuf+buf;
- CString WriteStr;
- WriteStr=strBuf.Left(pos+2)+chMessageID+strBuf.Right(strBuf.GetLength()-pos-2);
- fseek(m_SocketList[i].mail, -5, SEEK_CUR);
- fprintf(m_SocketList[i].mail,"%s",WriteStr);
- }
- }
- fprintf(m_SocketList[i].mail,"%s",buf);
- }else
- {
- fprintf(m_SocketList[i].mail,"%s",buf);
- }
- */
- if (strcmp(m_SocketList[i].crstr,"rn.rn") == 0)
- {
- fprintf(m_SocketList[i].mail,"%s",m_SocketList[i].strHead); //保存剩余部分
- m_SocketList[i].strHead = "";
- send (sock_temp, "250 OKrn",8,0); //TODO if ok
- if (m_SocketList[i].openf == 1)
- fclose(m_SocketList[i].mail);
- m_SocketList[i].status = 0;
- ProcessNewMail(m_SocketList[i].FnameCTL,m_SocketList[i].Fname,m_SocketList[i].Sender);
- if (m_SocketList[i].openf == 1)
- fclose(m_SocketList[i].mail);
- m_SocketList[i].FnameCTL = "";
- m_SocketList[i].Fname = "";
- }
- return;
- }
- CString tempcstr;
- tempstr = buf;
- tempcstr = tempstr;
- m_SocketList[i].Temp = m_SocketList[i].Temp + tempstr;
- if (m_SocketList[i].Temp.GetLength()>240)
- {
- m_SocketList[i].Temp = "";
- return;
- } //buffer to large problem
- tempstr = m_SocketList[i].Temp;
- if (tempstr[tempstr.GetLength()-1] != 'n')
- return;
- strLog.Format("Smtp Received[%d]: %s", i, tempstr);
- m_logFile.WriteLog(strLog);
- char tempstrU[255];
- sprintf(tempstrU,tempstr);
- strupr(tempstrU);
- if(m_SocketList[i].sLogin ==1) //已发送Auth login
- {
- char UserNameTemp[255];
- strcpy(UserNameTemp,tempstr);
- if (UserNameTemp[strlen(UserNameTemp)-2] == 'n') UserNameTemp[strlen(UserNameTemp)-2] = ' ';
- if (UserNameTemp[strlen(UserNameTemp)-2] == 'r') UserNameTemp[strlen(UserNameTemp)-2] = ' ';
- char UserName[255];
- memset(UserName,0x0,255);
- CEncoder base;
- base.Decode(UserNameTemp,strlen(UserNameTemp),UserName,254,0);
- m_SocketList[i].strLoginUserName =UserName;
- m_SocketList[i].sLogin=2;
- int dd=send (sock_temp, "334 UGFzc3dvcmQ6rn",18,0);
- m_SocketList[i].Temp = "";
- return;
- }else if(m_SocketList[i].sLogin ==2) //已发送用户名
- {
- char PasswordTemp[255];
- strcpy(PasswordTemp,tempstr);
- if (PasswordTemp[strlen(PasswordTemp)-2] == 'n') PasswordTemp[strlen(PasswordTemp)-2] = ' ';
- if (PasswordTemp[strlen(PasswordTemp)-2] == 'r') PasswordTemp[strlen(PasswordTemp)-2] = ' ';
- char Password[255];
- memset(Password,0x0,255);
- CEncoder base;
- base.Decode(PasswordTemp,strlen(PasswordTemp),Password,254,0);
- m_SocketList[i].strLoginPassword =Password;
- BSTR BstrUserID, BstrPassword,BstrName;
- CString strPassword;
- BstrUserID = m_SocketList[i].strLoginUserName.AllocSysString();
- m_pMailDB->FindUserByUserID(BstrUserID, &BstrPassword, &BstrName);
- _bstr_t bstrPassword(BstrPassword, FALSE);
- strPassword = (char*)bstrPassword;
- if(strPassword ==m_SocketList[i].strLoginPassword)
- {
- send (sock_temp, "235 Authentication successfulrn",31,0);
- m_SocketList[i].sLogin =3;
- }else
- {
- send (sock_temp, "501 Login Errorrn",17,0);
- m_SocketList[i].sLogin =4;
- }
- m_SocketList[i].Temp = "";
- return;
- }
- //EHLO command
- if ((tempstrU[0] == 'E') && (tempstrU[1] == 'H')
- && (tempstrU[2] == 'L') && (tempstrU[3] == 'O')
- && (tempstrU[4] == ' ') )
- {
- //send (sock_temp, "250 implementedrn",21,0);
- send (sock_temp, "250-Welcomern",12,0);
- send (sock_temp, "250-AUTH=LOGINrn",16,0);
- send (sock_temp, "250 AUTH LOGINrn",16,0);
- m_SocketList[i].sLogin =0;
- m_SocketList[i].Temp = "";
- return;
- }
- //AUTH LOGIN command
- if ((tempstrU[0] == 'A') && (tempstrU[1] == 'U')
- && (tempstrU[2] == 'T') && (tempstrU[3] == 'H')
- && (tempstrU[4] == ' ') && (tempstrU[5] == 'L')
- && (tempstrU[6] == 'O') && (tempstrU[7] == 'G')
- && (tempstrU[8] == 'I') && (tempstrU[9] == 'N'))
- {
- send (sock_temp, "334 VXNlcm5hbWU6rn",18,0);
- m_SocketList[i].sLogin =1;
- m_SocketList[i].Temp = "";
- return;
- }
- //HELO command
- if ((tempstrU[0] == 'H') && (tempstrU[1] == 'E')
- && (tempstrU[2] == 'L') && (tempstrU[3] == 'O')
- && (tempstrU[4] == ' ') )
- {
- send (sock_temp, "250 HELOrn",10,0);
- m_SocketList[i].sLogin =0;
- m_SocketList[i].Temp = "";
- return;
- }
- //NOOP command
- if ((tempstrU[0] == 'N') && (tempstrU[1] == 'O')
- && (tempstrU[2] == 'O') && (tempstrU[3] == 'P') )
- {
- send (sock_temp, "220 OKrn",8,0);
- m_SocketList[i].Temp = "";
- return;
- }
- //RSET command
- if ((tempstrU[0] == 'R') && (tempstrU[1] == 'S')
- && (tempstrU[2] == 'E') && (tempstrU[3] == 'T') )
- {
- send (sock_temp, "220 OKrn",8,0);
- m_SocketList[i].Temp = "";
- return;
- }
- //MAIL FROM command
- if ((tempstrU[0] == 'M') && (tempstrU[1] == 'A')
- && (tempstrU[2] == 'I') && (tempstrU[3] == 'L')
- && (tempstrU[4] == ' ')&& (tempstrU[5] == 'F')
- && (tempstrU[6] == 'R') && (tempstrU[7] == 'O')
- && (tempstrU[8] == 'M'))
- {
- send (sock_temp, "250 OKrn",8,0);
- m_SocketList[i].Temp = "";
- m_SocketList[i].Sender = tempstr;
- return;
- }
- //RCPT TO command
- if ((tempstrU[0] == 'R') && (tempstrU[1] == 'C')
- && (tempstrU[2] == 'P') && (tempstrU[3] == 'T')
- && (tempstrU[4] == ' ')&& (tempstrU[5] == 'T')
- && (tempstrU[6] == 'O'))
- {
- CString strRcpt=tempstr;
- if(!IsLocalUser((LPSTR)(LPCSTR)strRcpt) && m_SocketList[i].sLogin != 3) //不是本地用户并且没有通过验证
- {
- send (sock_temp, "501 Not loginrn",18,0);
- }else
- {
- if (m_SocketList[i].FnameCTL == "")
- {
- char tempstrA[255];
- CTime t = CTime::GetCurrentTime();
- SYSTEMTIME stime;
- GetSystemTime(&stime);
- sprintf(tempstrA,"%i%02i%02i%02i%02i%02i%i.in",t.GetYear(),t.GetMonth(),t.GetDay(),t.GetHour(),t.GetMinute(),t.GetSecond(),stime.wMilliseconds);
- int xxi = 0;
- m_SocketList[i].Fname = tempstrA;
- sprintf(tempstrA,"%i%02i%02i%02i%02i%02i%i.ctl",t.GetYear(),t.GetMonth(),t.GetDay(),t.GetHour(),t.GetMinute(),t.GetSecond(),stime.wMilliseconds);
- m_SocketList[i].FnameCTL = tempstrA;
- }
- if( (stream = fopen(m_strExePath+"\mail\" + m_SocketList[i].FnameCTL, "at" )) != NULL )
- {
- fprintf(stream,"%s",tempstr);
- fclose(stream);
- send (sock_temp, "250 OKrn",8,0);
- }
- else
- {
- send (sock_temp, "501 Server Errorrn",18,0);
- }
- m_SocketList[i].status = 4;
- }
- m_SocketList[i].Temp = "";
- return;
- }
- //DATA command
- if ( ((tempstrU[0] == 'D') && (tempstrU[1] == 'A')
- && (tempstrU[2] == 'T') && (tempstrU[3] == 'A')) && m_SocketList[i].status == 4)
- {
- send (sock_temp, "354 Enter your data, end with <crlf>.<crlf>rn",45,0);
- if( (m_SocketList[i].mail = fopen(m_strExePath+"\mail\" + m_SocketList[i].Fname, "wb" )) != NULL )
- {
- m_SocketList[i].crstr[0] = ' ';
- m_SocketList[i].crstr[1] = ' ';
- m_SocketList[i].crstr[2] = ' ';
- m_SocketList[i].crstr[3] = ' ';
- m_SocketList[i].crstr[4] = ' ';
- m_SocketList[i].crstr[5] = ' ';
- m_SocketList[i].status = 5;
- m_SocketList[i].openf = 1;
- m_SocketList[i].bTransHead = 0;
- m_SocketList[i].strHead="";
- //m_SocketList[i].bFinded = 0;
- }
- else
- {
- send (sock_temp, "502 Server Errorrn",18,0);
- }
- m_SocketList[i].Temp = "";
- return;
- }
- if ((tempstrU[0] == 'Q') && (tempstrU[1] == 'U')
- && (tempstrU[2] == 'I') && (tempstrU[3] == 'T') )
- {
- send(sock_temp, "221 Closing connectionrn",24,0);
- strLog.Format("Connection closed for %s", m_SocketList[i].ip);
- m_logFile.WriteLog(strLog);
- if(m_SocketList[i].sock != -1)
- {
- FD_CLR(m_SocketList[i].sock, &fdset);
- closesocket(m_SocketList[i].sock);
- m_SocketList[i].sock = -1;
- m_SocketList[i].showlog = FALSE;
- m_SocketList[i].status2 = 0;
- m_SocketList[i].status = 0;
- m_SocketList[i].typ = 0;
- m_SocketList[i].openf= 0;
- m_SocketList[i].Temp = "";
- m_SocketList[i].Username = "unknown";
- m_SocketList[i].dontwrite = FALSE;
- }
- return;
- }
- }
- void SendSMTP()
- {
- CString strLog;
- time_t the_time;
- int curitem = -1;
- for (;;)
- {
- Sleep(1000); //zzz, every second we check if we should send a mail
- if(m_SMTPForwardList.GetSize()>0)
- {
- for (int li= 0;li<=m_SMTPForwardList.GetSize()-1;li++)
- {
- curitem = li;
- if (m_SMTPForwardList[curitem].error == 0)
- {
- m_SMTPForwardList[curitem].sendnr = 0;
- strLog.Format("Trying to send mail (%s)", m_SMTPForwardList[curitem].Rcpt);
- m_logFile.WriteLog(strLog);
- // if (SendSmtpMail(curitem) == 0)
- if (SendSmtpMailDirect(curitem) == 0)
- {
- DeleteFile(m_strExePath+"\"+m_SMTPForwardList[curitem].Fname);
- strLog.Format("Successfull SMTP mail send (%s)", m_SMTPForwardList[curitem].Rcpt);
- m_logFile.WriteLog(strLog);
- ::EnterCriticalSection(&m_csSMTPForward);
- m_SMTPForwardList.RemoveAt(curitem);
- ::LeaveCriticalSection(&m_csSMTPForward);
- break;
- }
- else
- {
- strLog.Format("Sending of SMTP mail (%s) failed the first time.", m_SMTPForwardList[curitem].Rcpt);
- m_logFile.WriteLog(strLog);
- ::EnterCriticalSection(&m_csSMTPForward);
- time(&the_time);
- m_SMTPForwardList[curitem].timestamp = the_time;
- m_SMTPForwardList[curitem].error= 1;
- m_SMTPForwardList[curitem].sendnr++;
- ::LeaveCriticalSection(&m_csSMTPForward);
- }
- }
- else
- {
- short nMaxTries;
- m_pMailConfig->GetRelayMaxTries(&nMaxTries);
- if (nMaxTries < m_SMTPForwardList[curitem].sendnr)
- {
- strLog.Format("Send mail (%s) not possible after maximum tries.", m_SMTPForwardList[curitem].Rcpt);
- m_logFile.WriteLog(strLog);
- // SendErrorMail(curitem);
- DeleteFile(m_strExePath+"\"+m_SMTPForwardList[curitem].Fname);
- ::EnterCriticalSection(&m_csSMTPForward);
- m_SMTPForwardList.RemoveAt(curitem);
- ::LeaveCriticalSection(&m_csSMTPForward);
- break;
- }
- time(&the_time);
- short nTimeInterval;
- m_pMailConfig->GetRelayTimeInterval(&nTimeInterval);
- if (difftime(the_time, m_SMTPForwardList[curitem].timestamp) > nTimeInterval*60)
- {
- strLog.Format("Trying to send failed mail again (%s)", m_SMTPForwardList[curitem].Rcpt);
- m_logFile.WriteLog(strLog);
- m_SMTPForwardList[curitem].error = 0;
- // if (SendSmtpMail(curitem) == 0)
- if (SendSmtpMailDirect(curitem) == 0)
- {
- strLog.Format("Successfull SMTP mail send (%s)", m_SMTPForwardList[curitem].Rcpt);
- m_logFile.WriteLog(strLog);
- ::EnterCriticalSection(&m_csSMTPForward);
- DeleteFile(m_strExePath+"\"+m_SMTPForwardList[curitem].Fname);
- m_SMTPForwardList.RemoveAt(curitem);
- ::LeaveCriticalSection(&m_csSMTPForward);
- break;
- }
- else
- {
- time(&the_time);
- m_SMTPForwardList[curitem].timestamp = the_time;
- m_SMTPForwardList[curitem].error= 1;
- m_SMTPForwardList[curitem].sendnr++;
- strLog.Format("Could not send %s", m_SMTPForwardList[curitem].Rcpt);
- m_logFile.WriteLog(strLog);
- }
- }
- }
- }
- }
- }
- }
- int SendSmtpMail(int litem) //relay
- {
- SOCKET hServer;
- char szBuffer[4096];
- SOCKADDR_IN SockAddr;
- // WSADATA WSData;
- LPHOSTENT lpHostEntry;
- int iProtocolPort;
- char ServerName[255];
- BSTR BstrRelaySmtpServer;
- m_pMailConfig->GetRelayServerName(&BstrRelaySmtpServer);
- bstr_t bstrRelaySmtpServer(BstrRelaySmtpServer, FALSE);
- sprintf(ServerName,"%s",(char*)bstrRelaySmtpServer);
- lpHostEntry = gethostbyname(ServerName);
- if (lpHostEntry == NULL)
- {
- // WSACleanup();
- return 1;
- }
- hServer = socket( PF_INET, SOCK_STREAM, 0);
- if (hServer == INVALID_SOCKET)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- iProtocolPort = htons(25);
- SockAddr.sin_family = AF_INET;
- SockAddr.sin_port = iProtocolPort;
- SockAddr.sin_addr = *((LPIN_ADDR)*lpHostEntry->h_addr_list);
- int stimeout = 60000;
- int rtimeout = 60000;
- int err;
- if (stimeout != 0)
- {
- err = setsockopt(hServer ,
- SOL_SOCKET,
- SO_SNDTIMEO,
- (char *)&stimeout,
- sizeof(stimeout) );
- if (err != NO_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- }
- if (rtimeout != 0)
- {
- err = setsockopt(hServer ,
- SOL_SOCKET,
- SO_RCVTIMEO,
- (char *)&rtimeout,
- sizeof(rtimeout) );
- if (err != NO_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- }
- if (connect( hServer, (PSOCKADDR) &SockAddr, sizeof(SockAddr)))
- {
- closesocket(hServer);
- // WSACleanup();
- return 1;
- }
- //AskError();
- int cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- char sendstr[255];
- BSTR BstrHostName;
- m_pMailConfig->GetHostName(1, &BstrHostName);
- bstr_t bstrHostName(BstrHostName, FALSE);
- sprintf(sendstr,"HELO %srn",(char*)bstrHostName);
- cnt = send( hServer, sendstr, strlen(sendstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- sprintf(sendstr,"%s",m_SMTPForwardList[litem].Sender);
- cnt = send( hServer, sendstr, strlen(sendstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- sprintf(sendstr,"%srn", m_SMTPForwardList[litem].Rcpt);
- cnt = send( hServer, sendstr, strlen(sendstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- sprintf(sendstr,"DATArn");
- cnt = send( hServer, sendstr, strlen(sendstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '3')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- FILE *fp = fopen(m_strExePath+"\"+m_SMTPForwardList[litem].Fname,"rb");
- if (fp == NULL)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- char tempstr[255];
- while(!feof(fp))
- {
- fgets(tempstr,255,fp);
- tempstr[strlen(tempstr)-2] = 'n';
- tempstr[strlen(tempstr)-1] = ' ';
- if (!feof(fp))
- {
- cnt = send( hServer, tempstr, strlen(tempstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- fclose(fp);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- }
- }
- fclose(fp);
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- sprintf(sendstr,"QUITrn");
- cnt = send( hServer, sendstr, strlen(sendstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- closesocket( hServer );
- // WSACleanup();
- return 0;
- }
- //向客户端发送Mail文件
- void SendPop3Mail(SOCKET s, char* fileName)
- //UINT SendPop3Mail(LPVOID pParam)
- {
- // _SendPop3Param* psock_file = (_SendPop3Param*)pParam;
- // SOCKET s = psock_file->sock;
- // char* fileName = psock_file->fname;
- FILE *outmail;
- char outstr[255];
- int err = 0;
- if( (outmail= fopen(m_strExePath+"\"+fileName, "rb" )) != NULL )
- {
- while (!feof(outmail))
- {
- fgets(outstr,254,outmail);
- //outstr[strlen(outstr)-2] = 'n';
- outstr[strlen(outstr)] = ' ';
- if (!feof(outmail))
- {
- int nByte;
- nByte = send (s, outstr,strlen(outstr),0);
- if(nByte < 0)
- {
- err = GetLastError();
- if(err == WSAEWOULDBLOCK)
- {
- while(err == WSAEWOULDBLOCK)
- {
- send (s, outstr,strlen(outstr),0);
- err = GetLastError();
- }
- }
- else
- break;
- }
- }
- }
- fclose(outmail);
- }
- // return 0;
- }
- void DeleteCRLF(char *string)
- {
- if (string[strlen(string)-2] == 'n') string[strlen(string)-2] = ' ';
- if (string[strlen(string)-2] == 'r') string[strlen(string)-2] = ' ';
- if (string[strlen(string)-1] == 'n') string[strlen(string)-1] = ' ';
- if (string[strlen(string)-1] == 'r') string[strlen(string)-1] = ' ';
- }
- void ProcessNewMail(CString CTL, CString Fname,CString Sender)
- {
- if (Fname == "") return;
- CString strLog;
- //在邮件中加入Message-ID
- // AddMessageID(Fname);
- short nCopyAllFlag;
- BSTR BstrCopyDesUserID;
- CString strCopyDesUserID;
- m_pMailConfig->GetCopyAllMailConfig(&nCopyAllFlag, &BstrCopyDesUserID);
- if(nCopyAllFlag == 1)
- {
- _bstr_t bstrCopyDesUserID(BstrCopyDesUserID, FALSE);
- strCopyDesUserID = (char*)bstrCopyDesUserID;
- //this one should may be a extra thread:
- CopyFile(m_strExePath+"\mail\" + Fname, m_strExePath+"mail\" + strCopyDesUserID + "\" + Fname,FALSE );
- }
- CString rcpt;
- char srcpt[255];
- char srcptip[255];
- FILE *stream;
- CString rcptFull;
- char tempstr[255];
- if( (stream = fopen(m_strExePath+"\mail\" + CTL, "rt" )) != NULL )
- {
- m_logFile.WriteLog("Open Ctl Filen");
- while (!feof(stream))
- {
- fgets(tempstr,255,stream);
- if (!feof(stream))
- {
- if (tempstr[strlen(tempstr)-2] == 'n') tempstr[strlen(tempstr)-2] = ' ';
- if (tempstr[strlen(tempstr)-2] == 'r') tempstr[strlen(tempstr)-2] = ' ';
- rcptFull = tempstr;
- int beginsign= -1;
- int endsign= -1;
- int atsign= -1;
- for (UINT i = 0;i<= strlen(tempstr);i++)
- {
- if (tempstr[i] == '@') atsign = i;
- if (tempstr[i] == '<') beginsign = i;
- if (tempstr[i] == '>') endsign = i;
- }
- if ((beginsign== -1) || (endsign== -1) || (atsign== -1))
- {
- char err[255];
- sprintf(err,"wrong reciepment format: %s (mail\unknown\%s)",tempstr,Fname);
- m_logFile.WriteLog((CString)err);
- LogError(err);
- CopyFile(m_strExePath+"\mail\" + Fname,m_strExePath+"\mail\unknown\" + Fname,FALSE );
- }
- else
- {
- beginsign++;
- for (int z = beginsign;z<=atsign;z++)
- {
- srcpt[z-beginsign] = tempstr[z];
- }
- srcpt[z-beginsign-1] = ' ';
- atsign++;
- for (z = atsign;z<=endsign;z++)
- {
- srcptip[z-atsign] = tempstr[z];
- }
- srcptip[z-atsign-1] = ' ';
- rcpt = srcptip;
- BOOL aka_ok = FALSE;
- BOOL rcpt_ok = FALSE;
- /*
- for (int a = 0;a<= MyAkaList.GetSize()-1;a++)
- {
- if (strcmpi(MyAkaList[a].Text,rcpt) == 0)
- aka_ok = TRUE;
- }
- */
- CString strRcpt;
- strRcpt.Format("%s", rcpt);
- short nHostCount;
- BSTR BstrHostName;
- CString strHostName;
- m_pMailConfig->GetHostNameCount(&nHostCount);
- for(int i=1; i<=nHostCount; i++) //index begins from 1
- {
- m_pMailConfig->GetHostName(i, &BstrHostName);
- _bstr_t bstrHostName(BstrHostName, FALSE);
- strHostName = (char*)bstrHostName;
- if(strHostName == strRcpt)
- {
- aka_ok = TRUE;
- break;
- }
- }
- /*
- for (a = 0;a<= MailUserList.GetSize()-1;a++)
- {
- if (strcmpi(MailUserList[a].Username,srcpt)== 0)
- rcpt_ok = TRUE;
- }
- */
- BSTR BstrUserID, BstrPassword, BstrName;
- CString strUserID, strPassword;
- strUserID.Format("%s", srcpt);
- BstrUserID = strUserID.AllocSysString();
- m_pMailDB->FindUserByUserID(BstrUserID, &BstrPassword, &BstrName);
- _bstr_t bstrPassword(BstrPassword, FALSE);
- strPassword = (char*)bstrPassword;
- if(strPassword != "")
- rcpt_ok = TRUE;
- if ((aka_ok) && (rcpt_ok))
- {
- rcpt = srcpt;
- //创建收件用户的文件夹
- CString strFolder;
- strFolder.Format("%s\mail\%s", m_strExePath, rcpt);
- CreateDirectory((LPCTSTR)strFolder, NULL);
- //mkdir(chfolder);
- if (CopyFile(m_strExePath+"\mail\" + Fname,m_strExePath+"\mail\" + rcpt + "\" + Fname,FALSE ) == FALSE)
- {
- CopyFile(m_strExePath+"\mail\" + Fname,m_strExePath+"\mail\unknown\" + Fname,FALSE );
- strLog.Format("Count not send %s", tempstr);
- m_logFile.WriteLog(strLog);
- LogError(strLog);
- }
- else
- {
- //发送UDP包,并将相关的信息写入数据库
- CString strFileName, strRecver;
- strFileName.Format("mail\%s\%s", rcpt, Fname);
- strRecver.Format("%s", tempstr);
- DealMailInfo(strFileName, Sender, strRecver);
- strLog.Format("Mail Send To: %s", tempstr);
- m_logFile.WriteLog(strLog);
- }
- }
- else
- {
- //FORWARD Check
- BOOL fwd =FALSE;
- BOOL listmail = FALSE;
- if (aka_ok == TRUE)
- {
- FILE *fwdfp;
- fwdfp = fopen (m_strExePath+"\forward.ctl","rt");
- if (fwdfp != NULL)
- {
- char fwdstr[255];
- char fwdsrc[255];
- char fwddest[255];
- sprintf(fwdstr,"");
- while (!feof(fwdfp))
- {
- sprintf(fwdstr,"");
- fgets(fwdstr,255,fwdfp);
- if (strlen(fwdstr) > 3)
- {
- if (fwdstr[strlen(fwdstr)-2] == 'n') fwdstr[strlen(fwdstr)-2] = ' ';
- if (fwdstr[strlen(fwdstr)-2] == 'r') fwdstr[strlen(fwdstr)-2] = ' ';
- sscanf(fwdstr,"%s %s",fwdsrc,fwddest);
- rcpt = srcpt;
- if (strcmpi(fwdsrc,rcpt) == 0)
- {
- fwd =TRUE;
- //char mkd[255];
- CString strmkd;
- strmkd.Format("%s\mail\%s", m_strExePath, fwddest);
- CreateDirectory((LPCTSTR)strmkd, NULL);
- //sprintf(mkd,"mail\%s",fwddest);
- //mkdir(mkd);
- rcpt = fwddest;
- if (CopyFile(m_strExePath+"\mail\" + Fname,m_strExePath+"\mail\" + rcpt + "\" + Fname,FALSE ) == FALSE)
- {
- char logstr[255];
- sprintf(logstr,"Could not send mail (read error): %s (mail\unknown\%s)n",tempstr,Fname);
- LogError(logstr);
- CopyFile(m_strExePath+"\mail\" + Fname,m_strExePath+"\mail\unknown\" + Fname,FALSE );
- strLog.Format("Could not send %s",tempstr);
- m_logFile.WriteLog(strLog);
- }
- else
- {
- strLog.Format("Mail forward: %s->%s",fwdsrc,fwddest);
- m_logFile.WriteLog(strLog);
- }
- }
- }
- }
- fclose(fwdfp);
- //end alias-check
- }
- else
- {
- m_logFile.WriteLog("Cant read forward.ctl! Mail marked as bad.");
- }
- //is the user a list?
- char curname[255];
- strlwr(srcpt);
- HANDLE hFind;
- WIN32_FIND_DATA findData = {0};
- hFind = FindFirstFile (m_strExePath+"\lists\*.lst", &findData);
- if (hFind != INVALID_HANDLE_VALUE)
- {
- do
- {
- if (findData.cFileName[0] != '.')
- {
- sprintf(curname,"%s",findData.cFileName);
- strlwr(curname);
- if ((curname[strlen(curname)-3] == 'l') &&
- (curname[strlen(curname)-2] == 's') &&
- (curname[strlen(curname)-1] == 't'))
- {
- curname[strlen(curname)-4] = ' ';
- if (stricmp(srcpt,curname) == 0) //valid list
- {
- listmail = TRUE;
- strLog.Format("New Mailinglist ( %s ) mail", curname);
- m_logFile.WriteLog(strLog);
- HANDLE hFind1;
- WIN32_FIND_DATA findData1 = {0};
- hFind1 = FindFirstFile (m_strExePath + "\mail\" + Fname, &findData1);
- int mlsize = (findData1.nFileSizeHigh * MAXDWORD) + findData1.nFileSizeLow;
- FindClose(hFind1);
- FILE *fpf;
- char listfname[255];
- sprintf(listfname,"%s\lists\%s",m_strExePath,findData.cFileName);
- fpf = fopen (listfname,"rt");
- if (fpf == NULL) //this sucks
- {
- m_logFile.WriteLog("Couldn't read mailing list file");
- }
- else
- {
- int readstatus = 0;
- int maxsize = 0;
- char reply_to[255];
- char xtdsender[255];
- char subject_prefix[255];
- char templine[255];
- sprintf(reply_to,"");
- sprintf(subject_prefix,"");
- sprintf(xtdsender,"");
- while (!feof(fpf))
- {
- fgets(templine,255,fpf);
- if(!feof(fpf))
- {
- DeleteCRLF(templine);
- if ((templine[0] != '#') || (templine[0] != '['))
- {
- if (readstatus == 1)
- {
- char seps[] = "=";
- char *token;
- token = strtok( templine, seps );
- char lastoption[255];
- int xpos = 0;
- while( token != NULL )
- {
- if (xpos == 0)
- {
- sprintf(lastoption,"%s",token);
- }
- if (xpos == 1)
- {
- if (stricmp(lastoption,"reply_to") == 0)
- {
- sprintf(reply_to,"%s",token);
- }
- if (stricmp(lastoption,"maxlength") == 0)
- {
- maxsize = atoi(token);
- }
- if (stricmp(lastoption,"subject_prefix") == 0)
- {
- sprintf(subject_prefix,"%s",token);
- }
- if (stricmp(lastoption,"sender") == 0)
- {
- sprintf(xtdsender,"%s",token);
- }
- }
- xpos++;
- token = strtok( NULL, seps );
- }
- if (maxsize != 0)
- {
- if (mlsize >= maxsize)
- {
- m_logFile.WriteLog("Mail to large for mailing list");
- break;
- }
- }
- }
- if (readstatus == 2)
- {
- //mkdir("spool");
- CString strSpool;
- strSpool.Format("%s\spool", m_strExePath);
- CreateDirectory((LPCTSTR)strSpool, NULL);
- SMTPForwardInfo fwdinf;
- //we generate a new filename for each send
- //so we can easely delete the file
- CTime t = CTime::GetCurrentTime();
- SYSTEMTIME stime;
- GetSystemTime(&stime);
- char fnamenew[255];
- sprintf(fnamenew,"%i%02i%02i%02i%02i%02i%i.out",t.GetYear(),t.GetMonth(),t.GetDay(),t.GetHour(),t.GetMinute(),t.GetSecond(),stime.wMilliseconds);
- fwdinf.Fname = "spool\" + (CString)fnamenew;
- fwdinf.error= 0;
- fwdinf.sendnr = 0;
- fwdinf.Sender= "MAIL FROM: <" + (CString) xtdsender + ">rn";
- fwdinf.Rcpt= "RCPT TO: <" + (CString)templine + ">";
- time_t theTime;
- time(&theTime);
- fwdinf.timestamp = theTime;
- fwdinf.islocal = true;
- CopyFile(m_strExePath+"\mail\" + Fname,m_strExePath+"\"+fwdinf.Fname ,FALSE );
- strLog.Format("Posting mailing-list mail to %s", templine);
- m_logFile.WriteLog(strLog);
- ::EnterCriticalSection(&m_csSMTPForward);
- m_SMTPForwardList.Add(fwdinf); //have fun :)
- ::LeaveCriticalSection(&m_csSMTPForward);
- }
- }
- if (strcmp(templine,"[Setup]") == 0) readstatus = 1;
- if (strcmp(templine,"[Users]") == 0)
- {
- readstatus = 2;
- FILE *fpin = fopen(m_strExePath+"\mail\" + Fname,"rt");
- CTime t = CTime::GetCurrentTime();
- SYSTEMTIME stime;
- GetSystemTime(&stime);
- char tempfile[255];
- sprintf(tempfile,"mail\%i%02i%02i%02i%02i%02i%i.in",t.GetYear(),t.GetMonth(),t.GetDay(),t.GetHour(),t.GetMinute(),t.GetSecond(),stime.wMilliseconds);
- FILE *fpout = fopen(m_strExePath+"\"+tempfile,"wt");
- BOOL insideheader = TRUE;
- while(!feof(fpin))
- {
- fgets(templine,255,fpin);
- if(!feof(fpin))
- {
- if (insideheader)
- {
- if ((templine[0] == 'S') && (templine[1] == 'u') && (templine[2] == 'b')
- && (templine[3] == 'j') && (templine[4] == 'e') && (templine[5] == 'c')
- && (templine[6] == 't') && (templine[7] == ':'))
- {
- //modify subject?
- if (strlen(subject_prefix) != 0)
- {
- //is our new subject already in the text?
- if (strstr(templine,subject_prefix) == NULL)
- {
- //there isnt
- for (UINT x = 9;x<= strlen(templine);x++)
- {
- templine[x-9] = templine[x];
- }
- fprintf(fpout,"Subject: %s %s",subject_prefix,templine);
- sprintf(templine,"");
- }
- }
- }
- if ((templine[0] == 'S') && (templine[1] == 'e') && (templine[2] == 'n')
- && (templine[3] == 'd') && (templine[4] == 'e') && (templine[5] == 'r')
- && (templine[6] == ':') ) //sender already excist, use ours now
- {
- //if xtdsender is = 0 something is wrong or we already have it
- if (strlen(xtdsender) != 0)
- {
- fprintf(fpout,"Sender: %srn",xtdsender);
- sprintf(xtdsender,"");
- sprintf(templine,"");
- }
- }
- if (stricmp(templine,"rn") == 0)
- {
- if (strlen(xtdsender) != 0) fprintf(fpout,"Sender: %srn",xtdsender);
- if (strlen(reply_to) != 0) fprintf(fpout,"Reply-To: %srn",reply_to);
- fprintf(fpout,"rn");
- insideheader = FALSE;
- }
- else
- {
- fprintf(fpout,"%s",templine);
- }
- }
- else
- {
- fprintf(fpout,"%s",templine);
- }
- }
- }
- fclose(fpin);
- fclose(fpout);
- CopyFile(m_strExePath+"\" + tempfile,m_strExePath+"\mail\" + Fname,FALSE );
- DeleteFile(m_strExePath+"\"+tempfile);
- }
- }
- }
- fclose(fpf);
- }
- }
- }
- }
- } while (FindNextFile(hFind, &findData));
- FindClose (hFind);
- }
- }
- if ((fwd == FALSE) && (listmail == FALSE)) //dont know that user
- {
- //send to user who receives all unknown stuff
- short nUnknownFlag;
- BSTR BstrForwardUserID;
- CString strForwardUserID;
- m_pMailConfig->GetForwardUnknowMailUserConfig(&nUnknownFlag, &BstrForwardUserID);
- if(nUnknownFlag == 1)
- {
- _bstr_t bstrForwardUserID(BstrForwardUserID, FALSE);
- strForwardUserID = (char*)bstrForwardUserID;
- //char mkd[255];
- CString strmkd;
- strmkd.Format("%s\mail\%s", m_strExePath, strForwardUserID);
- CreateDirectory((LPCTSTR)strmkd, NULL);
- //sprintf(mkd,"mail\%s",strForwardUserID);
- //mkdir(mkd);
- CopyFile(m_strExePath+"\mail\" + Fname,m_strExePath+"\mail\" + strForwardUserID + "\" + Fname,FALSE );
- }
- //after that lets relay (if allowed)
- BOOL islocal = FALSE;
- if (aka_ok == FALSE)
- {
- char tempstra[255];
- sprintf(tempstra,"%s",Sender);
- int ps = 0;
- for (UINT ci = 0;ci<strlen(tempstra);ci++)
- {
- if(tempstra[ci] == '@')
- {
- ps = ci;
- }
- }
- for (UINT xi = ps;xi<strlen(tempstra);xi++)
- {
- tempstra[xi-ps] = tempstra[xi+1];
- }
- tempstra[xi-ps-4] = ' ';
- strlwr(tempstra);
- /* for (int bb = 0;bb<= MyAkaList.GetSize()-1;bb++)
- {
- if (strcmpi(MyAkaList[bb].Text,tempstra) == 0)
- {
- islocal = TRUE;
- }
- }
- */
- CString str_tempstra;
- str_tempstra.Format("%s", tempstra);
- short nHostCount;
- BSTR BstrHostName;
- CString strHostName;
- m_pMailConfig->GetHostNameCount(&nHostCount);
- for(int i=1; i<=nHostCount; i++) //index begins from 1
- {
- m_pMailConfig->GetHostName(i, &BstrHostName);
- _bstr_t bstrHostName(BstrHostName, FALSE);
- strHostName = (char*)bstrHostName;
- if(strHostName == str_tempstra)
- {
- islocal = TRUE;
- break;
- }
- }
- // char tempstr2[255];
- // sprintf(tempstr2,"%s",GetReg("Software\InetServ","SMTPRelayCheckHost"));
- BOOL sender_ok = TRUE;
- /* //lets check if we must validate hosts
- if (strcmp(tempstr2,"TRUE") == 0)
- {
- if (islocal == FALSE) sender_ok = FALSE;
- }
- */
- if (sender_ok == TRUE)
- {
- //mkdir("spool");
- CString str_spool;
- str_spool.Format("%s\spool", m_strExePath);
- CreateDirectory((LPCTSTR)str_spool, NULL);
- SMTPForwardInfo fwdinf;
- //we generate a new filename for each send
- //so we can easely delete the file
- CTime t = CTime::GetCurrentTime();
- SYSTEMTIME stime;
- GetSystemTime(&stime);
- char fnamenew[255];
- sprintf(fnamenew,"%i%02i%02i%02i%02i%02i%i.out",t.GetYear(),t.GetMonth(),t.GetDay(),t.GetHour(),t.GetMinute(),t.GetSecond(),stime.wMilliseconds);
- fwdinf.Fname = "spool\" + (CString)fnamenew;
- fwdinf.error= 0;
- fwdinf.sendnr = 0;
- fwdinf.Sender= Sender;
- fwdinf.Rcpt= rcptFull;
- //memset(fwdinf.RcptHostName,0x0,255);
- strcpy(fwdinf.RcptHostName,strRcpt);
- time_t theTime;
- time(&theTime);
- fwdinf.timestamp = theTime;
- fwdinf.islocal = true;
- CopyFile(m_strExePath+"\mail\" + Fname,m_strExePath+"\"+fwdinf.Fname ,FALSE );
- m_logFile.WriteLog("Relaying mail...");
- ::EnterCriticalSection(&m_csSMTPForward);
- m_SMTPForwardList.Add(fwdinf); //have fun :)
- ::LeaveCriticalSection(&m_csSMTPForward);
- }
- else
- {
- //user not known to me, mail dropped
- m_logFile.WriteLog("Relay tried to use by non local user: " + Sender);
- }
- }
- else
- {
- CopyFile(m_strExePath+"\mail\" + Fname,m_strExePath+"\mail\unknown\" + Fname,FALSE );
- char logstr[255];
- sprintf(logstr,"User not local: %s (mail\unknown\%s)n",tempstr,Fname);
- LogError(logstr);
- strLog.Format("Could not send %s",tempstr);
- m_logFile.WriteLog(strLog);
- }
- }
- }
- }
- }
- }
- fclose(stream);
- DeleteFile(m_strExePath+"\"+"mail\" + Fname);
- DeleteFile(m_strExePath+"\"+"mail\" + CTL);
- }
- else
- {
- m_logFile.WriteLog("WARNING! Could not process NewMail"); //this is a hard error!
- }
- }
- void LogError (CString expr)//log to logfiles\error.txt
- {
- CTime t = CTime::GetCurrentTime();
- FILE *x;
- CString logcstr = expr + "rn";
- CString strLogfiles;
- //mkdir ("logfiles");
- CString strLog;
- strLogfiles.Format("%s\logfiles", m_strExePath, NULL);
- CreateDirectory((LPCTSTR)strLogfiles, NULL);
- if( (x = fopen(m_strExePath+"\logfiles\error.txt", "at" )) != NULL )
- {
- fprintf(x,"%02i:%02i:%02i: %s",t.GetHour(),t.GetMinute(),t.GetSecond(),logcstr);
- fclose(x);
- }
- }
- bool AddMessageID(CString strFileName)
- {
- BOOL bHasMsgID = FALSE;
- int nLines = 0;
- char chMessageID[255];
- char chFile[255];
- sprintf(chFile, "%s\mail\%s", m_strExePath, strFileName);
- char filebuff[255], filebuff_temp[255];
- FILE* fstream = fopen(chFile, "a+t");
- if(fstream != NULL)
- {
- fseek(fstream, 0, SEEK_SET);
- while(!feof(fstream))
- {
- fgets(filebuff, 255, fstream);
- filebuff[strlen(filebuff)-2] = 'n';
- filebuff[strlen(filebuff)-1] = ' ';
- sprintf(filebuff_temp, "%s", filebuff);
- strupr(filebuff_temp);
- if(!feof(fstream))
- {
- nLines++;
- if((nLines > 10)||(bHasMsgID == TRUE))
- break;
- if((filebuff_temp[0] == 'M')&&(filebuff_temp[1] == 'E')
- &&(filebuff_temp[2] == 'S')&&(filebuff_temp[3] == 'S')
- &&(filebuff_temp[4] == 'A')&&(filebuff_temp[5] == 'G')
- &&(filebuff_temp[6] == 'E')&&(filebuff_temp[7] == '-')
- &&(filebuff_temp[8] == 'I')&&(filebuff_temp[9] == 'D')
- &&(filebuff_temp[10] == ' '))
- {
- bHasMsgID = TRUE;
- break;
- }
- }
- }
- if(bHasMsgID == FALSE)
- {
- fclose(fstream);
- char chFileNew[255];
- sprintf(chFileNew, "%s\mail\%s_temp", m_strExePath, strFileName);
- rename(chFile, chFileNew);
- FILE* fs = fopen(chFile, "w+b");
- if(fs != NULL)
- {
- //产生message-id
- time_t tm;
- time(&tm);
- srand((unsigned)time(NULL));
- sprintf(chMessageID, "Message-ID: <%d.%d.smartmailserver@m_office.com>rn", tm, rand());
- //写入MessageID
- fprintf(fs, "%s", chMessageID);
- FILE* fs_old = fopen(chFileNew, "rb");
- char file_content[255];
- int rdcount=0;
- if(fs_old != NULL)
- {
- while(!feof(fs_old))
- {
- rdcount = fread(file_content, sizeof(char), 255, fs_old);
- fwrite(file_content, sizeof(char), rdcount, fs);
- }
- fclose(fs);
- fclose(fs_old);
- DeleteFile(chFileNew);
- }
- else
- {
- fclose(fs);
- DeleteFile(chFile);
- rename(chFileNew, chFile);
- }
- }
- else
- {
- rename(chFileNew, chFile);
- }
- }
- else
- fclose(fstream);
- }
- return true;
- }
- bool DealMailInfo(CString strFileName, CString strSender, CString strRecver)
- {
- CString strLog;
- char chFile[255];
- sprintf(chFile, "%s\%s", m_strExePath, strFileName);
- //发送UDP数据包,并将相关的接收信息写入数据库
- HANDLE hFile = CreateFile(chFile,
- GENERIC_READ,
- FILE_SHARE_READ,
- NULL,
- OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL,
- NULL);
- if(hFile == NULL)
- {
- strLog.Format("Open File %s failed while Send UDP Info", strFileName);
- m_logFile.WriteLog(strLog);
- return false;
- }
- DWORD dwSize = GetFileSize(hFile, NULL);
- if(dwSize == -1)
- {
- strLog.Format("GetFileSize() failed, ErrorCode=%d", GetLastError());
- CloseHandle(hFile);
- return false;
- }
- CloseHandle(hFile);
- CString strTime, strSubject;
- char tempstr[255];
- long lSize = (long)(dwSize*0.75);
- char filebuff[255], filebuff_temp[255];
- short sFlag=0;
- FILE *fstream = fopen(chFile, "rt");
- if(fstream != NULL)
- {
- while(!feof(fstream))
- {
- fgets(filebuff, 255, fstream);
- //filebuff[strlen(filebuff)-2] = 'n';
- filebuff[strlen(filebuff)-1] = ' ';
- if(filebuff[0]==' ')
- break;
- sprintf(filebuff_temp, "%s", filebuff);
- strupr(filebuff_temp);
- if(!feof(fstream))
- {
- //Date:
- if((filebuff_temp[0] == 'D') && (filebuff_temp[1] == 'A') && (filebuff_temp[2] == 'T')
- && (filebuff_temp[3] == 'E') && (filebuff_temp[4] == ':'))
- {
- for(int i=0; i<strlen(filebuff); i++)
- tempstr[i] = filebuff[i+6];
- strTime.Format("%s", tempstr);
- strTime.TrimRight();
- sFlag++;
- continue;
- }
- //Subject
- if((filebuff_temp[0] == 'S') && (filebuff_temp[1] == 'U') && (filebuff_temp[2] == 'B')
- && (filebuff_temp[3] == 'J') && (filebuff_temp[4] == 'E') && (filebuff_temp[5] == 'C')
- && (filebuff_temp[6] == 'T') && (filebuff_temp[7] == ':'))
- {
- sprintf(tempstr, "%s", &filebuff[9]);
- strSubject.Format("%s", tempstr);
- strSubject.TrimRight();
- sFlag++;
- continue;
- }
- }
- }
- fclose(fstream);
- }
- if(sFlag != 2)
- return false;
- int npos, nlen;
- npos = strRecver.Find('<');
- nlen = strRecver.GetLength();
- strRecver = strRecver.Right(nlen - npos - 1);
- npos = strRecver.Find('>');
- strRecver = strRecver.Left(npos);
- npos = strSender.Find('<');
- nlen = strSender.GetLength();
- strSender = strSender.Right(nlen - npos - 1);
- npos = strSender.Find('>');
- strSender = strSender.Left(npos);
- _UDPPacketInfo data;
- sprintf(data.recver, "%s", strRecver);
- sprintf(data.sender, "%s", strSender);
- sprintf(data.title, "%s", strSubject);
- sprintf(data.time, "%s", strTime);
- data.size = htonl(lSize);
- if(!SendUDPData(data))
- {
- strLog.Format("Failed to Send UDP : Recver=%s, Sender=%s, Subject=%s, Date=%s, Size=%d",
- strRecver, strSender, strSubject, strTime, lSize);
- m_logFile.WriteLog(strLog);
- }
- else
- {
- strLog.Format("Succeed to Send UDP : Recver=%s, Sender=%s, Subject=%s, Date=%s, Size=%d",
- strRecver, strSender, strSubject, strTime, lSize);
- m_logFile.WriteLog(strLog);
- }
- if(!WriteMailInfoToDB(strSender, strRecver, strSubject, strTime, lSize))
- {
- strLog.Format("Failed to Insert RecvInfo to DB : Recver=%s, Sender=%s, Subject=%s, Date=%s, Size=%d",
- strRecver, strSender, strSubject, strTime, lSize);
- m_logFile.WriteLog(strLog);
- }
- else
- {
- strLog.Format("Succeed to Insert RecvInfo to DB : Recver=%s, Sender=%s, Subject=%s, Date=%s, Size=%d",
- strRecver, strSender, strSubject, strTime, lSize);
- m_logFile.WriteLog(strLog);
- }
- return true;
- }
- bool SendUDPData(_UDPPacketInfo udpData)
- {
- struct sockaddr_in udpadd;
- memset(&udpadd, 0x0, sizeof(sockaddr_in));
- udpadd.sin_family = AF_INET;
- udpadd.sin_port = htons(m_nUDPPort);
- udpadd.sin_addr.s_addr = inet_addr(m_strUDPIP);
- int nRet = sendto(m_UdpSocket, (char*)&udpData, sizeof(_UDPPacketInfo), 0, (struct sockaddr*)&udpadd, sizeof(udpadd));
- if(nRet < 0)
- return false;
- return true;
- }
- bool WriteMailInfoToDB(CString strSender, CString strRecver, CString strTitle, CString strTime, long lSize)
- {
- if(m_pMailDB == NULL)
- return false;
- BSTR BstrSender, BstrRecver, BstrTitle, BstrTime;
- BstrSender = strSender.AllocSysString();
- BstrRecver = strRecver.AllocSysString();
- BstrTitle = strTitle.AllocSysString();
- BstrTime = strTime.AllocSysString();
- HRESULT hr;
- hr = m_pMailDB->InsertRecvMailInfo(BstrTime, BstrTitle, BstrSender, BstrRecver, lSize);
- if(FAILED(hr))
- return false;
- return true;
- }
- //直接发送到目的地,
- int SendSmtpMailDirect(int litem) //relay
- {
- SOCKET hServer;
- char szBuffer[4096];
- SOCKADDR_IN SockAddr;
- // WSADATA WSData;
- LPHOSTENT lpHostEntry;
- int iProtocolPort;
- char ServerName[255];
- BSTR BstrDnsSmtpServer;
- m_pMailConfig->GetDnsServerName(&BstrDnsSmtpServer);
- bstr_t bstrDnsSmtpServer(BstrDnsSmtpServer, FALSE);
- sprintf(ServerName,"%s",(char*)bstrDnsSmtpServer);
- //加入获取Mx记录,把原来设置的转发服务器变为DNS服务器的设置
- char* pchDestMachine;
- pchDestMachine=GetMX(m_SMTPForwardList[litem].RcptHostName,ServerName,1);
- CString strDestMachine=pchDestMachine;
- if(strDestMachine.GetLength()<1)
- {
- return 1;
- }
- HeapFree(GetProcessHeap(),HEAP_NO_SERIALIZE,pchDestMachine);
- strDestMachine=strDestMachine.Left(strDestMachine.Find(" "));
- CString strLog;
- strLog.Format("Relay To:%s",strDestMachine);
- m_logFile.WriteLog(strLog);
- int nPos=strDestMachine.Find("n");
- if(nPos!=-1)
- {
- strDestMachine=strDestMachine.Left(strDestMachine.Find("n"));
- }
- lpHostEntry = gethostbyname(strDestMachine);
- if (lpHostEntry == NULL)
- {
- // WSACleanup();
- strLog.Format("Error1");
- m_logFile.WriteLog(strLog);
- return 1;
- }
- hServer = socket( PF_INET, SOCK_STREAM, 0);
- if (hServer == INVALID_SOCKET)
- {
- strLog.Format("Error2");
- m_logFile.WriteLog(strLog);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- iProtocolPort = htons(25);
- SockAddr.sin_family = AF_INET;
- SockAddr.sin_port = iProtocolPort;
- SockAddr.sin_addr = *((LPIN_ADDR)*lpHostEntry->h_addr_list);
- int stimeout = 60000;
- int rtimeout = 60000;
- int err;
- if (stimeout != 0)
- {
- err = setsockopt(hServer ,
- SOL_SOCKET,
- SO_SNDTIMEO,
- (char *)&stimeout,
- sizeof(stimeout) );
- if (err != NO_ERROR)
- {
- strLog.Format("Error3");
- m_logFile.WriteLog(strLog);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- }
- if (rtimeout != 0)
- {
- err = setsockopt(hServer ,
- SOL_SOCKET,
- SO_RCVTIMEO,
- (char *)&rtimeout,
- sizeof(rtimeout) );
- if (err != NO_ERROR)
- {
- strLog.Format("Error4");
- m_logFile.WriteLog(strLog);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- }
- if (connect( hServer, (PSOCKADDR) &SockAddr, sizeof(SockAddr)))
- {
- strLog.Format("Error5");
- m_logFile.WriteLog(strLog);
- closesocket(hServer);
- // WSACleanup();
- return 1;
- }
- //AskError();
- int cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- strLog.Format("Error6");
- m_logFile.WriteLog(strLog);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- strLog.Format("Error7");
- m_logFile.WriteLog(strLog);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- char sendstr[255];
- BSTR BstrHostName;
- m_pMailConfig->GetHostName(1, &BstrHostName);
- bstr_t bstrHostName(BstrHostName, FALSE);
- sprintf(sendstr,"HELO %srn",(char*)bstrHostName);
- cnt = send( hServer, sendstr, strlen(sendstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- strLog.Format("Error8");
- m_logFile.WriteLog(strLog);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- strLog.Format("Error9");
- m_logFile.WriteLog(strLog);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- sprintf(sendstr,"%s",m_SMTPForwardList[litem].Sender);
- cnt = send( hServer, sendstr, strlen(sendstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- sprintf(sendstr,"%srn", m_SMTPForwardList[litem].Rcpt);
- cnt = send( hServer, sendstr, strlen(sendstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- strLog.Format("Error12");
- m_logFile.WriteLog(strLog);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- strLog.Format("Error13");
- m_logFile.WriteLog(strLog);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- sprintf(sendstr,"DATArn");
- cnt = send( hServer, sendstr, strlen(sendstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '3')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- FILE *fp = fopen(m_strExePath+"\"+m_SMTPForwardList[litem].Fname,"rb");
- strLog.Format("Open file:%s",m_SMTPForwardList[litem].Fname);
- m_logFile.WriteLog(strLog);
- if (fp == NULL)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- char tempstr[255];
- while(!feof(fp))
- {
- fgets(tempstr,255,fp);
- //tempstr[strlen(tempstr)-2] = 'n';
- tempstr[strlen(tempstr)] = ' ';
- if (!feof(fp))
- {
- cnt = send( hServer, tempstr, strlen(tempstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- fclose(fp);
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- }
- }
- fclose(fp);
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- sprintf(sendstr,"QUITrn");
- cnt = send( hServer, sendstr, strlen(sendstr), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- cnt = recv( hServer, szBuffer, sizeof(szBuffer), 0);
- if (cnt == SOCKET_ERROR)
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- if (szBuffer[0] != '2')
- {
- closesocket( hServer );
- // WSACleanup();
- return 1;
- }
- closesocket( hServer );
- // WSACleanup();
- return 0;
- }
- BOOL IsLocalUser(const char* tempstr)
- {
- BOOL bRet;
- CString rcpt;
- char srcpt[255];
- char srcptip[255];
- CString rcptFull;
- rcptFull=tempstr;
- bRet=FALSE;
- if (rcptFull.GetAt(rcptFull.GetLength()-2) == 'n')
- rcptFull.SetAt(rcptFull.GetLength()-2,' ');
- if (rcptFull.GetAt(rcptFull.GetLength()-2) == 'r')
- rcptFull.SetAt(rcptFull.GetLength()-2,' ');
- int beginsign= -1;
- int endsign= -1;
- int atsign= -1;
- for (UINT i = 0;i<= strlen(rcptFull);i++)
- {
- if (rcptFull.GetAt(i) == '@') atsign = i;
- if (rcptFull.GetAt(i) == '<') beginsign = i;
- if (rcptFull.GetAt(i) == '>') endsign = i;
- }
- if ((beginsign== -1) || (endsign== -1) || (atsign== -1))
- {
- bRet=FALSE;
- }
- else
- {
- beginsign++;
- for (int z = beginsign;z<=atsign;z++)
- {
- srcpt[z-beginsign] = rcptFull[z];
- }
- srcpt[z-beginsign-1] = ' ';
- atsign++;
- for (z = atsign;z<=endsign;z++)
- {
- srcptip[z-atsign] = rcptFull[z];
- }
- srcptip[z-atsign-1] = ' ';
- rcpt = srcptip;
- BOOL aka_ok = FALSE;
- CString strRcpt;
- strRcpt.Format("%s", rcpt);
- short nHostCount;
- BSTR BstrHostName;
- CString strHostName;
- m_pMailConfig->GetHostNameCount(&nHostCount);
- for(int i=1; i<=nHostCount; i++) //index begins from 1
- {
- m_pMailConfig->GetHostName(i, &BstrHostName);
- _bstr_t bstrHostName(BstrHostName, FALSE);
- strHostName = (char*)bstrHostName;
- if(strHostName == strRcpt)
- {
- aka_ok = TRUE;
- break;
- }
- }
- if( aka_ok)
- {
- bRet=TRUE;
- }
- }
- return bRet;
- }