⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 authen.c

📁 采用非对称密钥加密方式的应用系统认证系统
💻 C
📖 第 1 页 / 共 2 页
字号:
#include <pthread.h>
#include "common.h"

pthread_mutex_t DatabaseMutex;
pthread_mutex_t KeyMutex;
pthread_mutex_t TailMutex;
pthread_mutex_t LogMutex;
R_RSA_PUBLIC_KEY  ServerPublicKey;
R_RSA_PRIVATE_KEY ServerPrivateKey;
CTL_INFO *lpCtlInfo;
int       CtlShmid;
TAIL_INFO *lpTailInfo;
int       TailShmid;
pid_t     mypid; 
FILE *fplog=NULL;

void *ComServer(void* ConnFdBuf);

/************************************************************/ 
void SendMessage(char *message)
{
  if (lpCtlInfo->IsDebug) {      
      pthread_mutex_lock(&TailMutex);
      (lpTailInfo->pos)++;
      if (lpTailInfo->pos<0 || lpTailInfo->pos>=MAX_TAIL_ROWS)
          lpTailInfo->pos=0;
      if (strlen(message)>=MAX_TAIL_MESSAGE_SIZE) 
          *(message+MAX_TAIL_MESSAGE_SIZE-1)=0;
      strcpy(lpTailInfo->queue[lpTailInfo->pos].data, message);
      pthread_mutex_unlock(&TailMutex);
  }
}
/************************************************************/ 
void CommonShow(char *w)
{
    char message[200];
    GetSysTime(message);
    sprintf(message+14," :%8d: %s\n",mypid,w);
    SendMessage(message);
}
/************************************************************/ 
void SubShow(int tid, char *w)
{
    char message[200];
    GetSysTime(message);
    sprintf(message+14," :%8d: %s\n",tid,w);
    SendMessage(message);
}
void SysDate(int *year,int *mon,int *day)
{
    struct tm *tt;
    time_t secs;
    time(&secs);
    tt=localtime(&secs);
    *year=tt->tm_year+1900;
    *mon=tt->tm_mon+1;
    *day=tt->tm_mday;
}
/************************************************************/ 
int main(int argc, char* argv[])
{ 
        char HomePath[100];
        char Username[21]; char Password[21];
	char *ptr;
	int ChildPid;
	R_RSA_PROTO_KEY protoKey;
        R_RANDOM_STRUCT randomStruct;       	
        
	ptr=getenv(HomePath);      /*读取环境变量和配置文件*/
	if (ptr!=NULL) strcpy(HomePath,ptr);
	else strcpy(HomePath, "/usr/authen");
	
	if (argc<2) {
            printf("\nDatabase Username:");
            scanf("%s", Username);
            printf("Password for %s:", Username);
            scanf("%s", Password);
	}
	else if (argc<3) {
	        if (strcmp(argv[1],"default")==0) {
	            strcpy(Username, "newgsm");
	            strcpy(Password, "pengxl");
	        }
	        else {
	            strcpy(Username, argv[1]);
	            printf("\nPassword for %s:", Username);
	            scanf("%s", Password);
	        }
	    }
	    else {
	        strcpy(Username, argv[1]);
	        strcpy(Password, argv[2]);
	        } 
	
	if (ConnectToDatabase(Username, Password) < 0) {
	    CommonShow("连接数据库失败...程序即将退出!");
	    pthread_exit(NULL);
	}
	/*初始化共享内存*/
	
	if (CreateTailShm()<0) {
	    CommonShow("初始化共享内存失败...程序即将退出!");
	    pthread_exit(NULL);
	} 	
	
        pthread_mutex_init(&DatabaseMutex,NULL);
        pthread_mutex_init(&KeyMutex,NULL);
        pthread_mutex_init(&TailMutex,NULL);        
        pthread_mutex_init(&LogMutex,NULL);        
        R_RandomCreate(&randomStruct);
        protoKey.bits=KEY_BITS;
        protoKey.useFermat4 = 1;
        
        if (R_GeneratePEMKeys(&ServerPublicKey, &ServerPrivateKey, &protoKey, &randomStruct)==0) {            
            if ((ChildPid=fork())<0) {
                CommonShow("fork子进程出错!程序退出!");
                FreeTailShm();
                return(0);
            }
            else if (ChildPid==0) {
                mypid=getpid();
                lpCtlInfo->pid=mypid;
                ShowVersion();    
                ListenServer();        
                if (fplog) fclose(fplog);
                CommonShow("程序正常退出。。。");
            } 
            else return(0); 
        }
	else {
            CommonShow("生成钥匙对出错,程序退出。。");
        }
        FreeTailShm(); 
	return(0);
}
/****************************************************************************/	
ShowVersion()
{
  int i;      
  for(i=0;i<18;i++) printf("\n");        
  printf("             ############################################\n");
  printf("             #                                          #\n");
  printf("             #                                          #\n");
  printf("             #         安 全 登 录 验 证 服 务          #\n");
  printf("             #                                          #\n");
  printf("             #             版本号:1.01                 #\n");
  printf("             #            2001年11月01日                #\n");
  printf("             #             (Ctrl+C退出)                 #\n");
  printf("             #                                          #\n");
  printf("             ############################################\n\n");
}
/****************************************************************************/	
FreeTailShm()
{
  shmdt((void*)lpCtlInfo);
  shmctl(CtlShmid, IPC_RMID, NULL);
  shmdt((void*)lpTailInfo);
  shmctl(TailShmid, IPC_RMID, NULL);
  return(0);
}
int CreateTailShm()
{
  int iShmSize;
  int ShmID;
  void *pShm;

  iShmSize=sizeof(CTL_INFO);
  if ((ShmID=shmget((key_t)CTL_SHM_KEY,iShmSize,IPC_CREAT|0666))<0 && (ShmID=shmget((key_t)CTL_SHM_KEY,iShmSize,0666))<0) {        
      CommonShow("shmget: CTL_SHM_KEY");
      return(-1);
  }   
  if ((pShm=shmat(ShmID,NULL,0))==(void *)-1) {
      CommonShow("shmat: CTL_SHM_KEY");
      return(-2);
  }
  lpCtlInfo=(CTL_INFO *)pShm;
  CtlShmid=ShmID;
  
  iShmSize=sizeof(TAIL_INFO);
  if ((ShmID=shmget((key_t)TAIL_SHM_KEY,iShmSize,IPC_CREAT|0666))<0 && (ShmID=shmget((key_t)TAIL_SHM_KEY,iShmSize,0666))<0) {
      CommonShow("shmget: TAIL_SHM_KEY");
      return(-3);
  }   
  if ((pShm=shmat(ShmID,NULL,0))==(void *)-1) {
      CommonShow("shmat: TAIL_SHM_KEY");
      return(-4);
  }
  lpTailInfo=(TAIL_INFO *)pShm;
  TailShmid=ShmID;
  
  lpCtlInfo->IsDebug=1;
  lpCtlInfo->IsStop=0;
  lpCtlInfo->IsLog=1;
  lpCtlInfo->pid=getpid();
  lpTailInfo->pos=0;  
  return(0);
}
/****************************************************************************/	
void sig_pipe(int signo)
{
  CommonShow("程序收到SIGPIPE信号!!");
  CommonShow("程序收到SIGPIPE信号!!");
}

void sig_seg_fault(int signo)
{
  pthread_t tid;
  char MessageBuf[100];
  tid=pthread_self(); 
  pthread_mutex_unlock(&KeyMutex);
  bzero(MessageBuf,100);
  if (tid==getpid()) {
      strcpy(MessageBuf,"警告:进程发生Segmentation Fault错误!!");
      }
  else {
      pthread_kill(tid,SIGKILL);
      sprintf(MessageBuf,"警告:线程%d发生Segmentation Fault错误!!",tid);
      }
  CommonShow(MessageBuf);
  CommonShow(MessageBuf);
}

void sig_term(int signo)
{
  CommonShow("警告:程序即将结束运行!!");
  CommonShow("警告:程序即将结束运行!!");
  if (lpCtlInfo) {
     lpCtlInfo->IsStop=1;
     kill(getpid(), SIGINT);
     }
  else exit(0);
}

int ListenServer()
{	
  struct sockaddr_in servaddr, Cliaddr;
  size_t Clilen;
  int ListenFd,ConnFd;
  char ConnFdBuf[21];
  char MessageBuf[100];
  char FileName[21];
  int OptionValue;
  fd_set SocketSet;
  fd_set AllSocketSet;
  int nReady;
  struct timeval tvTimeOut;
  pthread_t tid;
  pthread_attr_t pattr;
  int iYear,iMonth,iDay;
  int newYear,newMonth,newDay;
  struct sigaction pipeact;
  struct sigaction encryptact;
  struct sigaction downact;
 
  if((ListenFd=socket(PF_INET,SOCK_STREAM,0))<0) {
      CommonShow("socket创建出错!"); 
      close(ListenFd);
      return(-1); 
  }
  bzero(&servaddr,sizeof(servaddr));  
  servaddr.sin_family=AF_INET;
  servaddr.sin_addr.s_addr=htons(INADDR_ANY);
  servaddr.sin_port=htons(LISTEN_PORT);

  OptionValue=1; 
  if (setsockopt(ListenFd,SOL_SOCKET,SO_REUSEADDR,&OptionValue,sizeof(OptionValue))<0) {
      CommonShow("setsockopt出错!");
      close(ListenFd);
      return(-2);
  }
  if (bind(ListenFd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr))<0)  { 	
      CommonShow("bind出错!"); 
      close(ListenFd);
      return(-3);
  } 
  if (listen(ListenFd,MAX_REQUEST)<0) { 	
      CommonShow("listen出错!"); 
      close(ListenFd);
      return(-4);
  } 
  if (SetNonblock(ListenFd)<0) {
      CommonShow("SetNonBlock出错!"); 
      close(ListenFd);
      return(-5);
  }   
  bzero(FileName,21);
  SysDate(&iYear,&iMonth,&iDay);
  sprintf(FileName, "%04d%02d%02d.log", iYear,iMonth,iDay);
  if ((fplog=fopen(FileName,"a+"))==NULL) {
      CommonShow("fopen出错!"); 
  }  
  
  tvTimeOut.tv_sec=TIME_OUT;
  tvTimeOut.tv_usec=0;
  pthread_attr_init(&pattr);
  pthread_attr_setdetachstate(&pattr,PTHREAD_CREATE_DETACHED);
  /*忽略SIGPIPE信号*/
  pipeact.sa_handler=sig_pipe;
  pipeact.sa_flags=SA_RESTART;
  sigfillset(&pipeact.sa_mask);
  if(sigaction(SIGPIPE,&pipeact,NULL)<0) {
      CommonShow("sigaction SIGPIPE出错!"); 
      close(ListenFd);
      return(-9);
  }
  /*处理SIGSEGV信号(当发生Segmentation Fault时,调用函数sig_seg_fault结束线程)*/
  encryptact.sa_handler=sig_seg_fault;
  encryptact.sa_flags=SA_RESTART;
  sigfillset(&pipeact.sa_mask);
  if(sigaction(SIGSEGV,&encryptact,NULL)<0) {
      CommonShow("sigaction SIGSEGV出错!"); 
      close(ListenFd);
      return(-9);
  }
  /*处理SIGTERM信号(当主机关机时,结束运行!!)*/
  downact.sa_handler=sig_term;
  downact.sa_flags=0;
  sigemptyset(&downact.sa_mask);
  sigaddset(&downact.sa_mask,SIGTERM);
  if(sigaction(SIGTERM,&downact,NULL)<0) {
      CommonShow("sigaction SIGTERM出错!"); 
      close(ListenFd);
      return(-9);
  } 
  
  FD_ZERO(&AllSocketSet);
  FD_SET(ListenFd, &AllSocketSet); 
  /*开始主循环*/ 
  while(1) { 
      SocketSet=AllSocketSet;
      /*处理控制信息*/
      if (MessageServer()<0) break;
      CommonShow("正在监听......");
      if ((nReady=select(ListenFd+1,&SocketSet,NULL,NULL,&tvTimeOut))<0) {
          if (errno==EINTR) {
              CommonShow("select程序侦听被中断!,ListenServer"); 
              continue;
          } 
          else {
              CommonShow("select侦听取状态出错!,ListenServer"); 
              close(ListenFd);
              return(-6);        
          }
      } 
      /*nReady==0 Timeout
        nReady>0  a new connect request */
      if (FD_ISSET(ListenFd, &SocketSet)) {
          Clilen=sizeof(Cliaddr);
          if ((ConnFd=accept(ListenFd,(struct sockaddr *)&Cliaddr,&Clilen))<0) {
              if (errno==EINTR) continue; 
              else {
                  CommonShow("accept出错!");
                  close(ListenFd);
                  return(-7); 
              }
          } /*end of accept*/                    
          bzero(ConnFdBuf,21);
          sprintf(ConnFdBuf, "%d", ConnFd);
          if (pthread_create(&tid, &pattr, ComServer, (void *)ConnFdBuf)!=0) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -