我正在尝试编写一个使用 OpenSSL 的简单 Web 服务器。我不断收到“断管”错误。即使我处理了错误,似乎套接字也永远不会打开写入。
我究竟做错了什么?
这是我的代码:
/*
* I created tempory certificates like this:
*
* openssl req -newkey rsa:1024 -x509 -keyout key.pem -out root.pem
*
* I compile like this:
*
* gcc -g -o webssl webssl.c -lssl -lcrypto
*
* I get this error:
*
* Program received signal SIGPIPE, Broken pipe.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "openssl/bio.h"
#include "openssl/ssl.h"
#include "openssl/err.h"
const char *password = "jake";
const char *KEY_FILE = "key.pem";
const char *CA_LIST = "root.pem";
const char *response = "HTTP/1.0 200 OK\r\nServer : webssl\r\n\r\n<html><head><title>Hello World!</title></head><body><h1>Hello world!</h1></body></html>";
void sigpipe_handle(int x)
{
printf("broken pipe\n");
}
int password_cb(char *buf, int num, int rwflag, void *userdata)
{
if(num<strlen(password)+1)
return 0;
strcpy(buf, password);
return strlen(password);
}
int main(int argc, char *argv[])
{
SSL *ssl = NULL;
SSL_CTX *ctx = NULL;
int listenfd, clientfd;
struct sockaddr_in clientaddr;
socklen_t addrlen;
char *port = "8080";
struct addrinfo hints, *res;
char buffer[5000];
SSL_library_init();
/* Set up a SIGPIPE handler */
signal(SIGPIPE,sigpipe_handle);
ctx = SSL_CTX_new(SSLv23_server_method());
SSL_CTX_use_certificate_chain_file(ctx, KEY_FILE);
SSL_CTX_set_default_passwd_cb(ctx, password_cb);
SSL_CTX_use_PrivateKey_file(ctx, KEY_FILE, SSL_FILETYPE_PEM);
SSL_CTX_load_verify_locations(ctx, CA_LIST, 0);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, port, &hints, &res);
listenfd = socket(res->ai_family, res->ai_socktype, 0);
bind(listenfd, res->ai_addr, res->ai_addrlen);
freeaddrinfo(res);
listen(listenfd, 15);
while (1) {
addrlen = sizeof(clientaddr);
clientfd = accept(listenfd, (struct sockaddr *)&clientaddr, &addrlen);
ssl = SSL_new(ctx);
SSL_set_fd(ssl, clientfd);
SSL_accept(ssl);
SSL_read(ssl, buffer, 5000);
SSL_write(ssl, response, strlen(response));
SSL_free(ssl);
close(clientfd);
}
return 0;
}