使用pthread库实现openssl多线程ssl服务端和客户端

服务端代码如下:

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <errno.h>
#ifndef    _WIN32
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#else
#include <winsock2.h>
#include <windows.h>
#endif
#include "pthread.h"
#include <openssl/rsa.h>
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define CERTF "certs/sslservercert.pem"
#define KEYF  "certs/sslserverkey.pem"
#define    CAFILE  "certs/cacert.pem"
pthread_mutex_t    mlock=PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t *lock_cs;
static long *lock_count;
#define CHK_NULL(x) if ((x)==NULL) { printf("null\n"); }
#define CHK_ERR(err,s) if ((err)==-1) { printf(" -1 \n"); }
#define CHK_SSL(err) if ((err)==-1) {  printf(" -1 \n");}
#define    CAFILE  "certs/cacert.pem"

int  verify_callback_server(int ok, X509_STORE_CTX *ctx)
{
              printf("verify_callback_server \n");
        return ok;
}

int    SSL_CTX_use_PrivateKey_file_pass(SSL_CTX *ctx,char *filename,char *pass)
{
       EVP_PKEY     *pkey=NULL;
       BIO               *key=NULL;

key=BIO_new(BIO_s_file());
       BIO_read_filename(key,filename);
       pkey=PEM_read_bio_PrivateKey(key,NULL,NULL,pass);
       if(pkey==NULL)
       {
              printf("PEM_read_bio_PrivateKey err");
              return -1;
       }
       if (SSL_CTX_use_PrivateKey(ctx,pkey) <= 0)
       {
              printf("SSL_CTX_use_PrivateKey err\n");
              return -1;
       }
       BIO_free(key);
       return 1;
}

static int s_server_verify=SSL_VERIFY_NONE;
void * thread_main(void *arg)

       SOCKET s,AcceptSocket;
       WORD wVersionRequested;
       WSADATA wsaData;
       struct sockaddr_in  service;
       int    err;
      size_t             client_len;                                                                                           SSL_CTX             *ctx;
      SSL        *ssl;
      X509             *client_cert;
      char        *str;
      char    buf[1024];
      SSL_METHOD     *meth;

ssl=(SSL *)arg;
       s=SSL_get_fd(ssl);
       err = SSL_accept (ssl);
      if(err<0)
       {
              printf("ssl accerr\n");
              return ;
       }
      printf ("SSL connection using %s\n", SSL_get_cipher (ssl));
      client_cert = SSL_get_peer_certificate (ssl);
      if (client_cert != NULL)
      {
                   printf ("Client certificate:\n");
                     str = X509_NAME_oneline (X509_get_subject_name (client_cert), 0, 0);
                   CHK_NULL(str);
                   printf ("\t subject: %s\n", str);
                   OPENSSL_free (str);
                     str = X509_NAME_oneline (X509_get_issuer_name  (client_cert), 0, 0);
                   CHK_NULL(str);
                   printf ("\t issuer: %s\n", str);
                   OPENSSL_free (str);
                     X509_free (client_cert);
      }
      else
                  printf ("Client does not have certificate.\n");
       memset(buf,0,1024);
       err = SSL_read (ssl, buf, sizeof(buf) - 1);
       if(err<0)
       {
              printf("ssl read err\n");
              closesocket(s);
              return;
       }
       printf("get : %s\n",buf);
#if 0
      buf[err] = '\0';
      err = SSL_write (ssl, "I hear you.", strlen("I hear you."));  CHK_SSL(err);
#endif
      SSL_free (ssl);
       closesocket(s);
}

pthread_t pthreads_thread_id(void)
{
       pthread_t ret;

ret=pthread_self();
       return(ret);
}

void pthreads_locking_callback(int mode, int type, char *file,
            int line)
{
       if (mode & CRYPTO_LOCK)
              {
              pthread_mutex_lock(&(lock_cs[type]));
              lock_count[type]++;
              }
       else
              {
              pthread_mutex_unlock(&(lock_cs[type]));
              }
}

int main ()
{
       int                  err;                
       int                  i;
       SOCKET        s,AcceptSocket;
       WORD           wVersionRequested;
       WSADATA            wsaData;
       struct sockaddr_in  service;
       pthread_tpid;
      size_t             client_len;
      SSL_CTX             *ctx;
      SSL               *ssl;
      X509             *client_cert;
       char        *str;
      char    buf[1024];
      SSL_METHOD     *meth;

SSL_load_error_strings();
      SSLeay_add_ssl_algorithms();
      meth = SSLv3_server_method();
      ctx = SSL_CTX_new (meth);
      if (!ctx)
      {
                  ERR_print_errors_fp(stderr);
                  exit(2);
      }
       if ((!SSL_CTX_load_verify_locations(ctx,CAFILE,NULL)) ||
                (!SSL_CTX_set_default_verify_paths(ctx)))
    {
              printf("err\n");
              exit(1);
    }
      if (SSL_CTX_use_certificate_file(ctx, CERTF, SSL_FILETYPE_PEM) <= 0)
      {
           ERR_print_errors_fp(stderr);
           exit(3);
      }
      if (SSL_CTX_use_PrivateKey_file_pass(ctx, KEYF, "123456") <= 0)
      {
                  ERR_print_errors_fp(stderr);
                  exit(4);
      }
       if (!SSL_CTX_check_private_key(ctx))
       {
                  fprintf(stderr,"Private key does not match the certificate public key\n");
                  exit(5);
      }
       s_server_verify=SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT|
                                SSL_VERIFY_CLIENT_ONCE;
       SSL_CTX_set_verify(ctx,s_server_verify,verify_callback_server);
       SSL_CTX_set_client_CA_list(ctx,SSL_load_client_CA_file(CAFILE));
       wVersionRequested = MAKEWORD( 2, 2 );
       err = WSAStartup( wVersionRequested, &wsaData );
       if ( err != 0 )
       {
              printf("err\n");     
              return -1;
       }
       s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
       if(s<0) return -1;
       service.sin_family = AF_INET;
       service.sin_addr.s_addr = inet_addr("127.0.0.1");
       service.sin_port = htons(1111);
       if (bind( s, (SOCKADDR*) &service, sizeof(service)) == SOCKET_ERROR)
       {
              printf("bind() failed.\n");
              closesocket(s);
              return -1;
       }
    if (listen( s, 1 ) == SOCKET_ERROR)
              printf("Error listening on socket.\n");

printf("recv .....\n");
       lock_cs=OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
       lock_count=OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
       for (i=0; i<CRYPTO_num_locks(); i++)
       {
              lock_count[i]=0;
              pthread_mutex_init(&(lock_cs[i]),NULL);
       }
       CRYPTO_set_id_callback((unsigned long (*)())pthreads_thread_id);
       CRYPTO_set_locking_callback((void (*)())pthreads_locking_callback);
       while(1)
       {
              struct timeval tv;
              fd_set fdset;
              tv.tv_sec = 1;
              tv.tv_usec = 0;
              FD_ZERO(&fdset);
              FD_SET(s, &fdset);
           select(s+1, &fdset, NULL, NULL, (struct timeval *)&tv);
           if(FD_ISSET(s, &fdset))
              {
                     AcceptSocket=accept(s, NULL,NULL);
                     ssl = SSL_new (ctx);     
                    CHK_NULL(ssl);
                     err=SSL_set_fd (ssl, AcceptSocket);
                     if(err>0)
                     {
                            err=pthread_create(&pid,NULL,&thread_main,(void *)ssl);
                            pthread_detach(pid);
                     }
                     else
                            continue;
              }
       }
      SSL_CTX_free (ctx);
      return 0;
}

客户端代码如下:

代码如下:

#include <stdio.h>
#include <memory.h>
#include <errno.h>
#ifndef    _WIN32
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#else
#include <windows.h>
#endif
#include "pthread.h"
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define    MAX_T 1000
#define    CLIENTCERT       "certs/sslclientcert.pem"
#define    CLIENTKEY  "certs/sslclientkey.pem"
#define    CAFILE         "certs/cacert.pem"
static pthread_mutex_t *lock_cs;
static long *lock_count;

pthread_t pthreads_thread_id(void)
{
       pthread_t ret;

ret=pthread_self();
       return(ret);
}

void pthreads_locking_callback(int mode, int type, char *file,
            int line)
{
       if (mode & CRYPTO_LOCK)
              {
              pthread_mutex_lock(&(lock_cs[type]));
              lock_count[type]++;
              }
       else
              {
              pthread_mutex_unlock(&(lock_cs[type]));
              }
}

int    verify_callback(int ok, X509_STORE_CTX *ctx)
{
       printf("verify_callback\n");
       return ok;
}

int    SSL_CTX_use_PrivateKey_file_pass(SSL_CTX *ctx,char *filename,char *pass)
{
       EVP_PKEY     *pkey=NULL;
       BIO               *key=NULL;

key=BIO_new(BIO_s_file());
       BIO_read_filename(key,filename);
       pkey=PEM_read_bio_PrivateKey(key,NULL,NULL,pass);
       if(pkey==NULL)
       {
              printf("PEM_read_bio_PrivateKey err");
              return -1;
       }
       if (SSL_CTX_use_PrivateKey(ctx,pkey) <= 0)
       {
              printf("SSL_CTX_use_PrivateKey err\n");
              return -1;
       }
       BIO_free(key);
       return 1;
}

void*thread_main(void *arg)
{
       int          err,buflen,read;
      int          sd;
       SSL_CTX             *ctx=(SSL_CTX *)arg;
       struct            sockaddr_in dest_sin;
       SOCKET        sock;
       PHOSTENT   phe;
       WORD           wVersionRequested;
       WSADATA            wsaData;
      SSL               *ssl;
      X509             *server_cert;
      char     *str;
      char        buf [1024];
      SSL_METHOD     *meth;
       FILE              *fp;

wVersionRequested = MAKEWORD( 2, 2 );
       err = WSAStartup( wVersionRequested, &wsaData );
       if ( err != 0 )
       {
              printf("WSAStartup err\n");     
              return -1;
       }
       sock = socket(AF_INET, SOCK_STREAM, 0);
       dest_sin.sin_family = AF_INET;
       dest_sin.sin_addr.s_addr = inet_addr( "127.0.0.1" );
       dest_sin.sin_port = htons( 1111 );

again:
       err=connect( sock,(PSOCKADDR) &dest_sin, sizeof( dest_sin));
       if(err<0)
       {
              Sleep(1);
              goto again;
       }
    ssl = SSL_new (ctx);                       
       if(ssl==NULL)
       {
              printf("ss new err\n");
              return ;
       }
       SSL_set_fd(ssl,sock);
      err = SSL_connect (ssl);                   
      if(err<0)
       {
              printf("SSL_connect err\n");
              return;
       }
      printf ("SSL connection using %s\n", SSL_get_cipher (ssl));
      server_cert = SSL_get_peer_certificate (ssl);     
      printf ("Server certificate:\n");
      str = X509_NAME_oneline (X509_get_subject_name (server_cert),0,0);
      printf ("\t subject: %s\n", str);
      OPENSSL_free (str);
      str = X509_NAME_oneline (X509_get_issuer_name  (server_cert),0,0);
      printf ("\t issuer: %s\n", str);
      OPENSSL_free (str); 
      X509_free (server_cert);
       err = SSL_write (ssl, "Hello World!", strlen("Hello World!"));
       if(err<0)
       {
              printf("ssl write err\n");
              return ;
       }
#if 0
       memset(buf,0,ONE_BUF_SIZE);
      err = SSL_read (ssl, buf, sizeof(buf) - 1);                 
       if(err<0)
       {
              printf("ssl read err\n");
              return ;
       }
      buf[err] = '\0';
      printf ("Got %d chars:'%s'\n", err, buf);
#endif
      SSL_shutdown (ssl);  /* send SSL/TLS close_notify */
      SSL_free (ssl);
       closesocket(sock);
}

int    main ()
{
       int          err,buflen,read;
      int          sd;

struct            sockaddr_in dest_sin;
       SOCKETsock;
       PHOSTENT phe;
       WORD wVersionRequested;
       WSADATA wsaData;
      SSL_CTX             *ctx;
      SSL        *ssl;
      X509             *server_cert;
      char     *str;
      char        buf [1024];
      SSL_METHOD     *meth;
       int           i;
       pthread_tpid[MAX_T];

SSLeay_add_ssl_algorithms();
      meth = SSLv3_client_method();
      SSL_load_error_strings();
      ctx = SSL_CTX_new (meth);                     
       if(ctx==NULL)
       {
              printf("ssl ctx new eer\n");
              return -1;
       }

if (SSL_CTX_use_certificate_file(ctx, CLIENTCERT, SSL_FILETYPE_PEM) <= 0)
    {
        ERR_print_errors_fp(stderr);
        exit(3);
    }
    if (SSL_CTX_use_PrivateKey_file_pass(ctx, CLIENTKEY, "123456") <= 0)
    {
         ERR_print_errors_fp(stderr);
         exit(4);
     }
       lock_cs=OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
       lock_count=OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
       for (i=0; i<CRYPTO_num_locks(); i++)
       {
              lock_count[i]=0;
              pthread_mutex_init(&(lock_cs[i]),NULL);
       }
       CRYPTO_set_id_callback((unsigned long (*)())pthreads_thread_id);
       CRYPTO_set_locking_callback((void (*)())pthreads_locking_callback);
       for(i=0;i<MAX_T;i++)
       {          
              err=pthread_create(&(pid[i]),NULL,&thread_main,(void *)ctx);
              if(err!=0)
              {
                     printf("pthread_create err\n");
                     continue;
              }
       }
       for (i=0; i<MAX_T; i++)
       {
              pthread_join(pid[i],NULL);
       }
      SSL_CTX_free (ctx);
      printf("test ok\n");
       return 0;
}

上述程序在windows下运行成功,采用了windows下的开源pthread库。
需要注意的是,如果多线程用openssl,需要设置两个回调函数

代码如下:

CRYPTO_set_id_callback((unsigned long (*)())pthreads_thread_id);
CRYPTO_set_locking_callback((void (*)())pthreads_locking_callback);

(0)

相关推荐

  • 基于pthread_create,readlink,getpid等函数的学习与总结

    pthread_create是UNIX环境创建线程函数     具体格式:   #include<pthread.h>   int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void*(*start_rtn)(void*),void *restrict arg);   返回值:若成功则返回0,否则返回出错编号   返回成功时,由tidp指向的内存单元被设置为新创建线程的线程ID.att

  • pthread_cond_wait() 用法深入分析

    很久没看APUE,今天一位朋友问道关于一个mutex的问题,又翻到了以前讨论过的东西,为了不让自己忘记,把曾经的东西总结一下.先大体看下网上很多地方都有的关于pthread_cond_wait()的说明: 条件变量   条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起:另一个线程使"条件成立"(给出条件成立信号).为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起. 1.创建和注销   条件变量和互

  • undefined reference to 'pthread_create'的解决方法

    照着GUN/Linux编程指南中的一个例子输入编译,结果出现如下错误: undefined reference to 'pthread_create'undefined reference to 'pthread_join' 问题原因:    pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库. 问题解决:    在

  • 使用pthread库实现openssl多线程ssl服务端和客户端

    服务端代码如下: 复制代码 代码如下: #include <stdio.h>#include <stdlib.h>#include <memory.h>#include <errno.h>#ifndef    _WIN32#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#inclu

  • WIN7下ORACLE10g服务端和客户端的安装图文教程

    win7下安装oracle10g服务端和客户端方法如下所示: 如何卸载Oracle 10g 软件环境: 1.Windows XP + Oracle 10g 2.Oracle安装路径为:d:\Oracle 实现方法: 1.开始->设置->控制面板->管理工具->服务停止所有Oracle服务; 2.开始->程序->Oracle – OraDb10g_home1>Oracle Installation Products-> Universal Installer

  • 使用socket进行服务端与客户端传文件的方法

    逻辑: 1.客户端将需要查找的文件名以流的形式传给服务端 2.服务端接受客户端的连接,把流转化为字符串,进行一个目录的遍历,查找是否存在需要的文件,若未找到,则输出未找到,若找到,则将文件转化为流,传给客户端 3.客户端准备接受,将服务端传过来的流转化为文件,存储下载. 4,至此,完成一个简单的客户端与服务端传输文件的小栗子~ Client.Java package com.ysk; import java.io.BufferedReader; import java.io.FileOutput

  • ASP.NET简单获取服务端和客户端计算机名称的方法

    本文实例讲述了ASP.NET简单获取服务端和客户端计算机名称的方法.分享给大家供大家参考,具体如下: //获取服务端计算机名称 string serverPCName = System.Net.Dns.GetHostName(); //获取客户端计算机名称 System.Net.IPAddress clientIP = System.Net.IPAddress.Parse(Request.UserHostAddress);//根据目标IP地址获取IP对象 System.Net.IPHostEnt

  • nodejs socket实现的服务端和客户端功能示例

    本文实例讲述了nodejs socket实现的服务端和客户端功能.分享给大家供大家参考,具体如下: 使用node.js的net模块能很快的开发出基于TCP的服务端和客户端.直接贴代码. server.js /** * Created with JetBrains WebStorm. * User: Administrator * Date: 12-10-26 * Time: 下午3:44 * To change this template use File | Settings | File T

  • nodejs socket服务端和客户端简单通信功能

    本文实例讲述了通过node.js的net模块实现nodejs socket服务端和客户端简单通信功能,可以用作客户端对服务端的端口监听以及事件回执. server端代码 var net = require('net'); //模块引入 var listenPort = 8080;//监听端口 var server = net.createServer(function(socket){ // 创建socket服务端 console.log('connect: ' + socket.remoteA

  • golang实现简单的udp协议服务端与客户端示例

    本文实例讲述了golang实现简单的udp协议服务端与客户端.分享给大家供大家参考,具体如下: 其实udp没有什么服务端和客户端的概念了,只是一个发一个收而已,只是这样较方便能识别和理解. 服务端: 复制代码 代码如下: package main import (     "fmt"     "net" ) func main() {     // 创建监听     socket, err := net.ListenUDP("udp4", &am

  • Nodejs之TCP服务端与客户端聊天程序详解

    TCP是用来计算机之间进行通信的,通过编写客户端和服务端聊天的代码,对于服务器与客户端的工作步骤有了深刻的了解,在这里根据了不起的Node.js一书来总结一下. TCP聊天程序需要用到Nodejs中的net模块,net模块是对TCP的封装,用于创建TCP服务端与客户端的. 服务器端 count:连接的客户端个数: users:用于存储客户端用户昵称的对象,对象值都为该客户端的Socket,Socket是一个接口,用于服务端与客户端通信. net.createServer:是用来创建TCP服务器,

  • C#聊天程序服务端与客户端完整实例代码

    本文所述为基于C#实现的多人聊天程序服务端与客户端完整代码.本实例省略了结构定义部分,服务端主要是逻辑处理部分代码,因此使用时需要完善一些窗体按钮之类的. 先看服务端代码如下: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net; using

  • python thrift搭建服务端和客户端测试程序

    本文生动简洁介绍了如何通过python搭建一个服务端和客户端的简单测试程序. 一.简介 thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发.它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 这些编程语言间无缝结合的.高效的服务. 二.安装 1.下载地址 http://www

随机推荐