当前位置:   article > 正文

c/c++编写window服务的授权服务(三)

c/c++编写window服务的授权服务(三)

 c/c++编写window服务的授权服务(三)

//实现授权服务的函数体LicenseService.cpp

#pragma once #include "LicenseService.h" #include "hex_md5.h" //安装入口点 void main(int argc, char* argv[]) { //初始化全局变量 //获取exe所在目录 CurExeDir=GetCurDir(); //printf("\n当前exe所在目录为:%s\n",CurExeDir); //获取ServerConfig.ini配置参数并初始化全局变量 GetServerConfig_ini(); //开始初始化服务 WCHAR* TServiceName=CharPtr2ACharPtr(ServiceName); //方法一 SERVICE_TABLE_ENTRY ServiceTable[2]; //设置服务名称和服务入口函数 ServiceTable[0].lpServiceName=TServiceName; ServiceTable[0].lpServiceProc=(LPSERVICE_MAIN_FUNCTION)ServiceMain; ServiceTable[1].lpServiceName=NULL; ServiceTable[1].lpServiceProc=NULL; //方法二 /*SERVICE_TABLE_ENTRY ServiceTable[]= { {TEXT(ServiceName),(LPSERVICE_MAIN_FUNCTION)ServiceMain}, { NULL,NULL} };*/ //注册为服务和反注册 //------------------------------------------------- //引数 if(argc<=1) { //usage(使用方法)表示 cout<<"使用方法:"<<endl; //cout<<"zxz\"zxz"<<ENDL; //"install" cout<<"\"install\""; //"or" cout<<"or"; //"uninstall" cout<<"\"uninstall\""; //"exec" cout<<"\"exec \""; cout<<" parameter required in the command line"<<endl; } if(argc>1) { if(_stricmp("install",argv[1])==0) { //install(InstallService) InstallService(); cout<<"installService Succed!"<<endl; } else if(_stricmp("uninstall",argv[1])==0) { //uninstall(UninstallService) UninstallService(); cout<<"UninstallService Succed!"<<endl; } else if(_stricmp("exec",argv[1])==0) { //exec(ServiceMain) RunService(TServiceName); } else { //usage(使用方法)表示 cout<<"使用方法 :"<<endl; //"install" cout<<"\"install\""; //"or" cout<<"or"; //"uninstall" cout<<"\"uninstall\""; //"exec" cout<<"\"exec \""; //"or" cout<<"or"; cout<<" parameter required in the command line"<<endl; } } //------------------------------------------------- //启动服务的控制分派机线程(启动并执行一个新线程) StartServiceCtrlDispatcher(ServiceTable); } //服务入口点(主线程) void ServiceMain(int argc,char** argv) { WCHAR* TServiceName=CharPtr2ACharPtr(ServiceName); int success; //success=InitService(); //if(!success) //{ // //初始化失败,终止服务 // WriteToLog("ServiceMain::InitService初始化失败,终止服务"); // ServiceStatus.dwCurrentState=SERVICE_STOPPED; // ServiceStatus.dwWin32ExitCode=-1; // SetServiceStatus(hStatus,&ServiceStatus); // //退出ServiceMain // return; //} //开始服务 RunService(TServiceName); //注册服务控制处理函数 hStatus = RegisterServiceCtrlHandler(TServiceName,(LPHANDLER_FUNCTION)ControlHandler); if(!hStatus) { WriteToLog("ServiceMain函数中注册服务控制处理函数失败!\n"); return; } //向SCM报告工作状态 RunState=EnumRunState::Running; ServiceStatus.dwCurrentState=SERVICE_RUNNING; ServiceStatus.dwServiceType=SERVICE_WIN32; ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN; /*SetServiceStatus(hStatus,&ServiceStatus);*/ 启动工作循环(这个模块在另外一个线程中执行) //while(RunState==EnumRunState::Running) //{ // WriteToLog("ServiceMain函数写日志\n"); // Sleep(500); //} //创建一个终结事件 terminateEvent = CreateEvent (0,TRUE,FALSE,0); if (!terminateEvent) { terminate(GetLastError()); return; } // success = SendStatusToSCM(SERVICE_START_PENDING,NO_ERROR,0,2,1000); if (!success) { terminate(GetLastError()); return; } //初始化 success = InitService(); if (!success) { terminate(GetLastError()); return; } success = SendStatusToSCM(SERVICE_RUNNING,NO_ERROR,0,0,0); if (!success) { terminate(GetLastError()); return; } //等待停止 WaitForSingleObject ( terminateEvent, INFINITE); terminate(0); WriteToLog("ServiceMain函数执行完毕!"); } //服务控制台命令处理函数 void ControlHandler(DWORD request) { DWORD currentState = 0; BOOL success; switch(request) { case SERVICE_CONTROL_STOP: RunState=EnumRunState::Stoped; currentState = SERVICE_STOP_PENDING; ServiceStatus.dwCurrentState=currentState; SetServiceStatus(hStatus,&ServiceStatus); StopService(); return; case SERVICE_CONTROL_PAUSE: RunState=EnumRunState::Pause; currentState = SERVICE_PAUSED; ServiceStatus.dwCurrentState=currentState; SetServiceStatus(hStatus,&ServiceStatus); PauseService(); break; case SERVICE_CONTROL_CONTINUE: RunState=EnumRunState::Running; currentState = SERVICE_RUNNING; ServiceStatus.dwCurrentState=currentState; SetServiceStatus(hStatus,&ServiceStatus); ResumeService(); break; case SERVICE_CONTROL_INTERROGATE: // it will fall to bottom and send status break; // Do nothing in a shutdown. Could do cleanup // here but it must be very quick. case SERVICE_CONTROL_SHUTDOWN: // Do nothing on shutdown return; default: break; } //ServiceStatus.dwCurrentState=currentState; //SetServiceStatus(hStatus,&ServiceStatus); } //初始化服务(开始服务时执行) int InitService() { //重新获取ServerConfig.ini配置参数 GetServerConfig_ini(); int result; WCHAR* TServiceName=CharPtr2ACharPtr(ServiceName); //写日志信息 result=WriteToLog("Monitoring started."); //start listening... //开始一个线程 Start the service's thread DWORD id; threadHandle = CreateThread(0, 0,(LPTHREAD_START_ROUTINE)ServiceThread,0, 0, &id); if (threadHandle==0) { result=0; } else { result=1; } WriteToLog("InitService一个线程开始了!"); return result; } DWORD WINAPI ServiceThread(LPDWORD param) { //线程操作 WriteToLog("线程操作ServiceThread开始!"); StartHostPortListen(host,atoi(port)); WriteToLog("线程操作ServiceThread完成!"); return 0; } //实现 开始主机+端口监听函数 void StartHostPortListen(char* ipaddr,int port) { //port=9998; WORD wVersionRequested; WSADATA wsaData; int err; //版本请求 wVersionRequested = MAKEWORD(2, 2); //初始化WinSock(WSAStartup函数) err = WSAStartup( wVersionRequested, &wsaData); if ( err != 0 ) { //初始化出错了退出函数 return; } //初始化成功!但版本不一致! 退出函数 if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { WSACleanup( ); //清除Socket return; //退出函数 } //生成一个socket(sockSrv变量) //SOCK_STREAM 用于TCP协议 //SOCK_DGRAM 用于UDP协议 SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0); //使用TCP协议 //设置一个地址Socket(addrSrv变量) SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr=inet_addr(ipaddr); //本机IP地址 addrSrv.sin_family=AF_INET; addrSrv.sin_port=htons(port); //端口9998 //绑定函数(指定本地IP地址所使用的端口号时候使用) //(把sockSrv变量与addrSrv变量绑定在一起) bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); //监听端口开始 if(listen(sockSrv,MAX_PENDING_CONNECTS)!=0) { printf("监听socket失败:%d\n ",::WSAGetLastError()); return;//ExitProcess(STATUS_FAILED); } printf("开始监听..."); //接收来自客户端的请求连接 SOCKET sockClient; SOCKADDR_IN addrClient;//定义一个客户端Socket地址 int len=sizeof(SOCKADDR); char recvBuf[100]; int recv_len=-1; // sockaddr_in acc_sin; int acc_sin_len; acc_sin_len=sizeof(acc_sin); // while(true) { //接收Socket请求 来自客户端的Connect sockClient=accept(sockSrv,(struct sockaddr*)&acc_sin, &acc_sin_len); if(sockClient>=0) { //创建一个线程来处理socket请求threadHandle DWORD id; HANDLE threadHandle = CreateThread(0, 0,(LPTHREAD_START_ROUTINE)HandleSocket,(LPVOID)sockClient, 0, &id); // } else { //没有客户端接入 printf("没有客户端接入2\n"); } Sleep(200); } //关闭Socket变量sockSrv closesocket(sockSrv); //清除Socket WSACleanup(); } //实现 处理Socket请求函数 DWORD WINAPI HandleSocket(LPVOID lpParam) { SOCKET sockClient=(SOCKET)lpParam; //接收数据并保存到recvBuf变量中 char recvBuf[100]; int recv_len=-1; bool Exits=false; while(Exits==false) { recv_len=recv(sockClient,recvBuf,100,0); //recv_len=recvfrom(sockClient,recvBuf,100,0,(SOCKADDR*)&addrClient,&len); if(recv_len>0) { //输出数据 recvBuf[recv_len]='\0'; //在末尾加入字符串结束符号 '\0 ' printf("%s\n",recvBuf); printf("本次数据接收结束。\n "); //处理(传入请求类型) char* ret; ret=new char[recv_len]; strcpy(ret,recvBuf); bool rlcmd=false,stop=false; rlcmd=EqStr(ret,"RequestLicenseCommand"); stop=EqStr(ret,"stop"); if(rlcmd==true) { //请求类型为:RequestLicenseCommand bool LicenseAbled=false; //计算License是否可用 LicenseAbled=false;//true; //需进一步判断 LicenseAbled=IsLencense(); //----- char* retmsg="stop"; if(LicenseAbled==true )//&& recvBuf==reqCmd { //可用 retmsg="start"; } else { //不可用 retmsg="stop"; } WriteToLog(retmsg); if(send(sockClient,retmsg,strlen(retmsg),0)==SOCKET_ERROR) { printf("回发信息报错了: %d\n ",WSAGetLastError()); } printf("本次数据处理结束。\n "); } if(stop==true) { //请求类型为:stop Exits=true; //退出(结束本线程) } } } printf("退出(结束本线程)\n "); return 0; } //运行服务函数 BOOL RunService(WCHAR* sSvcName) { SC_HANDLE schSCManager; SC_HANDLE scHandle; BOOL boolRet; // open to SCM schSCManager = OpenSCManager( 0, 0, SC_MANAGER_ALL_ACCESS ); //Open scHandle = OpenService( schSCManager, sSvcName, SERVICE_ALL_ACCESS ); //start boolRet = StartService( scHandle, 0, NULL); return boolRet; } VOID ResumeService() { //pauseService=FALSE; //ResumeThread(threadHandle); return; } VOID PauseService() { //pauseService = TRUE; //SuspendThread(threadHandle); return; } VOID StopService() { RunState=EnumRunState::Stoped;//=FALSE; // Set the event that is holding ServiceMain // so that ServiceMain can return SetEvent(terminateEvent); } //安装函数 void InstallService() { SC_HANDLE schService; SC_HANDLE schSCManager; TCHAR szPath[512]; WCHAR* TServiceName=CharPtr2ACharPtr(ServiceName); //Install Starting... //获取模块文件路径名称 if(!GetModuleFileName(NULL,szPath,512)) { return; } // open to SCM  schSCManager = OpenSCManager( 0, // pointer to machine name string 0, // pointer to database name string SC_MANAGER_CREATE_SERVICE // type of access ); if (!schSCManager) { //WriteToLog("OpenScManagerErrorID:"+GetLastError()); return; } // Install 新服务 schService = CreateService( schSCManager, // handle to service control manager database TServiceName, // pointer to name of service to start TServiceName, // pointer to display name SERVICE_ALL_ACCESS,// type of access to service SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS ,// type of service SERVICE_DEMAND_START,// when to start service SERVICE_ERROR_NORMAL,// severity if service fails to start szPath, // pointer to name of binary file NULL, // pointer to name of load ordering group NULL, // pointer to variable to get tag identifier NULL, // pointer to array of dependency names NULL, // pointer to account name of service NULL // pointer to password for service account ); if (!schService) { WriteToLog("服务安装出错了"); //WriteToLog("CreateServiceErrorID:"+GetLastError()); return; } else { WriteToLog("服务已安装Service installed\n"); } // clean up CloseServiceHandle(schService); CloseServiceHandle(schSCManager); WriteToLog("安装服务已结束Install Ended...\n"); } //反安装函数 void UninstallService() { SC_HANDLE schService; SC_HANDLE schSCManager; BOOL success; SERVICE_STATUS svcStatus; WCHAR* TServiceName=CharPtr2ACharPtr(ServiceName); WriteToLog("反安装开始Uninstall Starting..."); // open to SCM  schSCManager = OpenSCManager( 0,// pointer to machine name string 0,// pointer to database name string SC_MANAGER_CREATE_SERVICE // type of access ); if (!schSCManager) { //WriteToLog("OpenScManagerErrorID:"+GetLastError()); return; } //打开一个服务 schService = OpenService( schSCManager, // handle to service control manager database TServiceName, // pointer to name of service to start SERVICE_ALL_ACCESS | DELETE// type of access to service ); if (!schService) { WriteToLog("OpenServiceErrorID:"+GetLastError()); return; } //(if necessary) success = QueryServiceStatus(schService, &svcStatus); if (!success) { WriteToLog("In QueryServiceStatus ErrorID:"+GetLastError()); return; } if (svcStatus.dwCurrentState != SERVICE_STOPPED) { WriteToLog("Stopping service..."); success = ControlService( schService, // handle to service SERVICE_CONTROL_STOP, // control code &svcStatus // pointer to service status structure ); if (!success) { WriteToLog("In ControlServiceErrorID:"+GetLastError()); return; } } //等待 do { QueryServiceStatus(schService,&svcStatus); Sleep(500); }while(SERVICE_STOP_PENDING==svcStatus.dwCurrentState); if(SERVICE_STOPPED!=svcStatus.dwCurrentState) { WriteToLog("Failed to Stop Service ErrorID:"+GetLastError()); return; } //删除服务 success = DeleteService(schService); if (success) { WriteToLog("Service removed\n"); } else { WriteToLog("In DeleteService ErrorID:"+GetLastError()); return; } //Clean up CloseServiceHandle(schService); CloseServiceHandle(schSCManager); WriteToLog("反安装结束Uninstal Ended..."); } //实现 发送状态到SCM服务控制管理器 BOOL SendStatusToSCM (DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint) { BOOL success; SERVICE_STATUS serviceStatus; // Fill in all of the SERVICE_STATUS fields serviceStatus.dwServiceType =SERVICE_WIN32_OWN_PROCESS; serviceStatus.dwCurrentState = dwCurrentState; // If in the process of something, then accept // no control events, else accept anything if (dwCurrentState == SERVICE_START_PENDING) serviceStatus.dwControlsAccepted = 0; else serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN; // if a specific exit code is defines, set up // the win32 exit code properly if (dwServiceSpecificExitCode == 0) serviceStatus.dwWin32ExitCode =dwWin32ExitCode; else serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; serviceStatus.dwServiceSpecificExitCode =dwServiceSpecificExitCode; serviceStatus.dwCheckPoint = dwCheckPoint; serviceStatus.dwWaitHint = dwWaitHint; // Pass the status record to the SCM //SERVICE_STATUS_HANDLE serviceStatusHandle; success = SetServiceStatus (hStatus,&serviceStatus); if (!success) { StopService(); } return success; } //实现 服务终结函数 VOID terminate(DWORD error) { // if terminateEvent has been created, close it. if (terminateEvent) { CloseHandle(terminateEvent); } // Send a message to the scm to tell about // stop age if (hStatus) { SendStatusToSCM(SERVICE_STOPPED, error,0, 0, 0); } // If the thread has started kill it off if (threadHandle) { CloseHandle(threadHandle); } // Do not need to close serviceStatusHandle } //---------------------------------------------------- //通用函数的实现 //实现 字符串格式转换 char*转为WCHAR* WCHAR* CharPtr2ACharPtr(const char* src) { // Convert to a wchar_t* size_t srcsize = strlen(src) + 1; size_t newsize = srcsize; size_t convertedChars = 0; wchar_t *wcstring; wcstring=new wchar_t[newsize]; mbstowcs_s(&convertedChars, wcstring, srcsize, src, _TRUNCATE); //wcscat_s(wcstring, L" (wchar_t *)"); //wcout << wcstring << endl; return wcstring; } //实现 写日志 int WriteToLog(char* str) { FILE* log; char* curdir; if(CurExeDir==NULL) { CurExeDir=GetCurDir(); } curdir=CurExeDir; char* Logfile=UnionStr(curdir,LogFileName); log=fopen(Logfile,"a+"); if(log==NULL) return 0; fprintf(log,"%s\n",str); fclose(log); return 1; } //实现 获取当前可执行文件所在目录 char* GetCurDir(void) { //推荐用如下方法来得到当前程序所在目录比较安全: //void _splitpath( const char *path, char *drive, char *dir, char *fname, char *ext ); //函数来分解开始提到的_pgmptr,然后再用 //void _makepath( char *path, const char *drive, const char *dir, const char *fname, const char *ext ); //函数来对分解后的路径进行组合。这两个函数结合起来功能强大,使用灵活, //基本上所有的有关目录和路径方面的操作都可以搞定. //(1) char* szFilePath=new char[MAX_PATH]; memset(szFilePath,0,MAX_PATH); GetModuleFileNameA(NULL,szFilePath,MAX_PATH); //GetModuleFileNameW(NULL,szFilePath,MAX_PATH); char* szfp=new char[strlen(szFilePath)+1]; strcpy(szfp,szFilePath); int srcLen=strlen(szfp)+1; char* Driver=new char[srcLen]; char* dir=new char[srcLen]; char* fn=new char[srcLen]; char* ext=new char[srcLen]; // memset(Driver,0,srcLen); memset(dir,0,srcLen); memset(fn,0,srcLen); memset(ext,0,srcLen); //分解路径 _splitpath(szfp,Driver,dir,fn,ext); char* dri=new char[strlen(Driver)+1]; strcpy(dri,Driver); char* dir_t=new char[strlen(dir)+1]; strcpy(dir_t,dir); //组合目录 int len=strlen(dri)+strlen(dir_t); char* result=new char[len]; memset(result,0,len); sprintf(result, "%s\\%s",dri,dir_t); char* r=new char[strlen(result)+1]; strcpy(r,result); return r; } //实现 替换字符串中特征字符串为指定字符串 int ReplaceStr(char *sSrc, char *sMatchStr, char *sReplaceStr) { int StringLen; int MAX_MSG_LENGTH=strlen(sSrc)+1; char* caNewString=new char[MAX_MSG_LENGTH]; char *FindPos = strstr(sSrc, sMatchStr); if( (!FindPos) || (!sMatchStr) ) return -1; while( FindPos ) { memset(caNewString, 0, sizeof(caNewString)); StringLen = FindPos - sSrc; strncpy(caNewString, sSrc, StringLen); strcat(caNewString, sReplaceStr); strcat(caNewString, FindPos + strlen(sMatchStr)); strcpy(sSrc, caNewString); FindPos = strstr(sSrc, sMatchStr); } return 0; } //实现 合并字符串函数 char* UnionStr(const char* A,const char* B) { int len=strlen(A)+strlen(B); char* result=new char[len]; memset(result,0,len); sprintf(result, "%s%s",A,B); char* r=new char[strlen(result)+1]; strcpy(r,result); return r; } //实现 字符串是否相等函数 bool EqStr(const char* A,const char* B) { bool r=true; char* t_A=new char[strlen(A)+1]; strcpy(t_A,A); char* t_B=new char[strlen(B)+1]; strcpy(t_B,B); int ALen=strlen(t_A); int BLen=strlen(t_B); if(ALen>=BLen) ALen=BLen; { for(int i=0;i<ALen;i++) { if(t_A[i]!=t_B[i]) { r=false; break; } } } return r; } //实现 是数字check函数 bool IsNumber(string str) { bool r=true; const char* t=str.c_str(); int Len=strlen(t); for(int i=0;i<Len;i++) { if(!isdigit(t[i])) { r=false; break; } } return r; } //实现 获取当前系统的年-月-日格式的时间 char* WinApi_Year_Month_Day() { SYSTEMTIME sys; GetLocalTime(&sys); char* s=new char[10]; sprintf(s,"%4d-%02d-%02d",sys.wYear,sys.wMonth,sys.wDay); return s; } //实现 比较日期字符串函数 unsigned long Compare_To_Date(char* datetime1,char* datetime2) { //return 3表示日期格式不正确 //return 2表示datetime1>datetime2 //return 1表示datetime1=datetime2 //return 0表示datetime1<datetime2 unsigned short year1; unsigned short month1; unsigned short day1; unsigned short year2; unsigned short month2; unsigned short day2; unsigned long bValidate; bValidate=Validate_Date(datetime1,&year1,&month1,&day1); if(bValidate==false){ return 3; } bValidate=Validate_Date(datetime2,&year2,&month2,&day2); if(bValidate==false){ return 3; } if(year1<year2) return 0; if(year1>year2) return 2; if(month1<month2) return 0; if(month1>month2) return 2; if(day1<day2) return 0; if(day1>day2) return 2; return 1; } //实现 比较当前日期字符串函数 unsigned long Compare_To_Current_Date(char* datetime){ unsigned short year; unsigned short month; unsigned short day; unsigned long bValidate=Validate_Date(datetime,&year,&month,&day); if(bValidate==false){ return 3; } SYSTEMTIME CurTime; GetLocalTime(&CurTime); if(CurTime.wYear>year) return 2; else if(CurTime.wYear<year) return 0; if(CurTime.wMonth>month) return 2; else if(CurTime.wMonth<month) return 0; if(CurTime.wDay>day) return 2; else if(CurTime.wDay<day) return 0; return 1; } //实现 验证日期字符串格式正确性函数 unsigned long Validate_Date(char* date,unsigned short * year,unsigned short * month,unsigned short * day){ if(strlen(date)<10) return false; std:string s(date); string _1=s.substr(4,1); string _2=s.substr(7,1); if(!EqStr(_1.c_str(),"-")) return false; if(!EqStr(_2.c_str(),"-")) return false; string szyear=s.substr(0,4);//yyyy-mm-dd string szmonth=s.substr(5,2); string szday=s.substr(8,2); if(IsNumber(szyear)==false) return false; if(IsNumber(szmonth)==false) return false; if(IsNumber(szday)==false) return false; unsigned long bResult; try { *year=(unsigned short)atol(szyear.c_str()); *month=(unsigned short)atol(szmonth.c_str()); *day=(unsigned short)atol(szday.c_str()); bResult= true; } catch(...) { bResult=false; } return bResult; } //实现 获取机器码函数 char* GetMachineCode(void) { char* cpuid=GetCpuId(); char* ret; for(int i=0;i<=2;i++) { ret=md5(cpuid); cpuid=ret; } return ret; } //实现 获取Cpu编号函数 char* GetCpuId(void) { unsigned long s1,s2; __asm { mov eax,01h xor edx,edx cpuid mov s1,edx mov s2,eax } //CString CPUID; //CPUID.Format("%08X%08X",s1,s2); //return CPUID; char ret[255]; sprintf(ret,"%08X%08X",s1,s2); char* lpmac=ret; char* RetVal=new char[strlen(lpmac)+1]; strcpy(RetVal,lpmac); return RetVal; } //实现 md5加密算法函数 char* md5(char* src) { char md5[64] = {0}; hex_md5(src, md5, 32); char* ret; ret=new char[strlen(md5)+1]; strcpy(ret,md5); return ret; } //实现 是否有使用权的函数 bool IsLencense(void) { bool r=true; char* cpuid=GetCpuId(); char* curdate=WinApi_Year_Month_Day(); //char* todate="2011-12-31"; char* tmpmachinecode=UnionStr(cpuid,todate); char* regcode=md5(tmpmachinecode); //printf("%s\n",regcode);printf("%s\n",code); //WriteToLog(regcode);WriteToLog(code); if(EqStr(regcode,code)==true) { printf("注册码有效(%s=%s)\n",code,regcode); //时间是否过期 //curdate<=todate //printf("curdate=%s\n",curdate);printf("todate=%s\n",todate); int retval=Compare_To_Date(curdate,todate); //printf("retval=%d\n",retval); if(retval==0 || retval==1) { r=true; } else { r=false; } } else { r=false; printf("注册码无效(%s=%s)\n",code,regcode); } return r; } //实现 获取ServerConfig.ini参数函数 bool GetServerConfig_ini(void) { char* curdir; if(CurExeDir==NULL) { CurExeDir=GetCurDir(); } curdir=CurExeDir; //获取ini文件中的数据 char* inifn="ServerConfig.ini"; int len=strlen(curdir)+strlen(inifn)+1; char* inipath=new char[len]; sprintf(inipath, "%s\\%s", curdir, inifn); //printf(inipath); //--------- char* line; filepath =inipath; if(OpenFile()==true) { char* line; while(!EndFile()) { line=NextLine(); if(line!=NULL) { //printf("%s\n",line); int lineLen=strlen(line); if(lineLen>0) { if(line[0]!=';') { if(strstr(line,"LicenseServerHost=")!=NULL) { host=line; } if(strstr(line,"Port=")!=NULL) { port=line; } if(strstr(line,"ToDate=")!=NULL) { todate=line; } if(strstr(line,"LicenseCode=")!=NULL) { code=line; } } } } } CloseFile(); } ReplaceStr(host,"LicenseServerHost=",""); ReplaceStr(port,"Port=",""); ReplaceStr(todate,"ToDate=",""); ReplaceStr(code,"LicenseCode=",""); printf("host->%s\n",host); printf("port->%s\n",port); printf("todate->%s\n",todate); printf("code->%s\n",code); return true; } //实现 打开文件操作 bool OpenFile(void) { char* path=filepath; if((fp=fopen(path,"r"))==NULL) { printf("file cannot be opened\n"); return false; } return true; } //实现 检查文件是否结束函数 int EndFile(void) { return feof(fp); } //实现 读取下一行函数 char* NextLine() { char line[4000]; if(fgets(line,4000,fp)!=NULL) { char* ret=new char[strlen(line)+1]; strcpy(ret,line); return ret; } return NULL; } //实现 关闭文件函数 int CloseFile(void) { if(fp!=NULL) { return fclose(fp); } return -1; } //---the---end---

转载于:https://www.cnblogs.com/sqlite3/archive/2011/12/03/2566773.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/959184
推荐阅读
相关标签
  

闽ICP备14008679号