SSL_accept hangs after calling fork() - c++

I'm writing an app in C++ using openssl, and I can't seem to get the ssl socket connection to work.
I have an abstract class, with multiple functions implemented using various protocols by the inheriting classes and simple TCP and UDP ( posix sockets ) work fine.
I could not get the ssl working though and after some code browsing and tweaking I found out, that it is the fork() function which causes problems.
I wrote a very simple program to check things out, and this is what I get:
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <iostream>
#include <errno.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/timeb.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <netdb.h>
#include <time.h>
#include </usr/local/include/ssl/ssl.h>
#include "SSL_CA.cpp"
int main( int argc, char **argv ) {
int retval;
SSL_CTX *ctx;
SSL *con;
int port = atoi(argv[1]);
sockaddr_in client_addr;
sockaddr_in serv_addr;
socklen_t client_len;
int max_clients = 40;
int serv_sock, client_sock;
if ( ( serv_sock = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
return -12;
SSL_library_init();
int SSL_CA = NowySSL();
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = port;
cout << "Conf " << endl;
if ( bind( serv_sock, ( sockaddr * ) &serv_addr, sizeof( serv_addr ) ) < 0 )
return -1;
if ( listen( serv_sock, max_clients ) < 0 )
return -1;
while (1) {
cout << "Waiting" << endl;
if ( ( client_sock = accept( serv_sock, ( sockaddr * ) &client_addr, &client_len ) ) < 0 )
return -1;
pid_t pid = fork();
if ( pid = 0 ) {
con = NULL;
ctx = NULL;
ctx = (SSL_CTX *)SSL_CTX_new( SSLv23_server_method() );
con = (SSL *)SSL_new( (SSL_CTX *)ctx );
if (
!( ( ( !SSL_CA ) && ( SSL_NO_CA_RUN( con, ctx, client_sock, 0 ) ) ) ||
( ( SSL_CA ) && ( SSL_CA_RUN( con, ctx, client_sock, true ) ) ) )
)
return -1;
char buf[10];
if ( ( retval = SSL_read( con, buf, 10 ) ) <= 0 )
return -16;
cout << "Got msg " << buf << " " << retval << endl;
sprintf(buf, "12345" );
if ( ( retval = SSL_write( con, buf, strlen(buf) ) ) <= 0 )
return -1;
cout << "Sent" << endl;
}
else cout << "Parent " << endl;
}
return 0;
}
These are the SSL_CA_RUN and SSL_NO_CA_RUN functions - not written by me, but i have to use it
int SSL_NO_CA_RUN (SSL *con, SSL_CTX *ctx, int msgsock, int exit_now)
{
// printf ("SSL NO CA\n");
// SSL_library_init();
// ctx=(SSL_CTX *)SSL_CTX_new(SSLv23_server_method());
// con=(SSL *)SSL_new((SSL_CTX *)ctx);
if ((!SSL_set_fd (con,msgsock))||
(!SSL_use_RSAPrivateKey_file (con,"ktsa_u_linux.k",1))||
(!SSL_use_certificate_file (con,"ktsa_u_linux.c",1))||
(!SSL_accept (con)))
{
printf ("SSL ERROR (%s)\n",strerror(errno));
if (exit_now)
{
zamknij_polaczenie (con,ctx,msgsock);
exit(0);
}
return false;
}
// printf ("SSL NO CA OK!!!\n");
return true;
}
int SSL_CA_RUN (SSL *con, SSL_CTX *ctx, int msgsock, int exit_now)
{
int ret, ok=true;
X509 *peer;
FILE *fp;
char error[250];
// printf ("SSL CA\n");
//MARCIN (START)
//robimy linki do certyfikatow Marcin
certhash(CA_DIR,CRL_DIR,getpid());
//dostep_read (890);
// SSL_library_init();
// printf("\n");
// ctx=(SSL_CTX *)SSL_CTX_new(SSLv23_server_method());
// con=(SSL *)SSL_new((SSL_CTX *)ctx);
cb=pem_passwd_cb;
SSL_CTX_set_default_passwd_cb_userdata(ctx,haslo);
SSL_CTX_set_default_passwd_cb(ctx,cb);
//SSL_set_verify_depth(con,10); default = 9
SSL_set_verify(con,SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,NULL);
// SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,NULL);
//SSL_CTX_set_cipher_list(ctx,"SHA1+3DES:+RSA:HIGH");
//SSL_set_cipher_list(con,"SHA1+3DES:+RSA:HIGH");
if ((!SSL_set_fd (con,msgsock))||
(!SSL_use_RSAPrivateKey_file (con,KEY_FILE,1))||
(!SSL_use_certificate_file (con,CERT_FILE,1))||
// (!SSL_CTX_load_verify_locations(ctx,CA_FILE,NULL))||
(!SSL_CTX_load_verify_locations(ctx,NULL,linkdir))||
(!SSL_accept (con))
)
{
if (exit_now)
{
remove_symdir(getpid());
// printf("error connect\n");
zamknij_polaczenie (con,ctx,msgsock);
exit(0);
} else remove_symdir(getpid());
ok=false;
}
if (ok)
{
peer=SSL_get_peer_certificate(con);
if(peer!=NULL)
{
//ret=1 - odwolany
//ret=0 - wszystko ok
//ret = inne - jakis inny blad, np. brak wlasciwej listy crl
//ret=check_peer_crl_dir(peer,error,CRL_DIR); //sprawdzenie odwolania certyfikatu przychodzacego
ret=check_peera(peer,error,0); //sprawdzenie odwolania certyfikatu przychodzacego
// printf("peer certyfikat:%s:%i\n",error,ret);
}
if ((peer==NULL)||(ret==1))
{
//nie akceptujemy polaczenia bo nie dostalismy certyfikatu lub certyfikat jest odwolany
// printf("polaczenie odrzucone - certyfikat peera odwolany, brak certyfikatu lub wystawiony przez inne CA \n");
if (exit_now)
{
remove_symdir(getpid());
zamknij_polaczenie (con,ctx,msgsock);
exit(2);
}
ok=false;
}
}
if (ok)
{
X509_free(peer); //potrzebne?
peer=NULL;
//mozna sprawdzic tez nasz certyfikat
if (!(fp = fopen (CERT_FILE, "r"))) //"/router/ssl/cert/sslcert.cer"
printf ("Error reading my certificate file\n");
if (!(peer = PEM_read_X509 (fp, NULL, NULL, NULL)))
printf ("Error reading my certificate in file\n");
if (fp)fclose (fp);
if(peer!=NULL)
{
//ret=1 - odwolany
//ret=0 - wszystko ok
//ret = inne - jakis inny blad, np. brak wlasciwej listy crl
//ret=check_peer_crl_dir(peer,error,CRL_DIR); //sprawdzenie odwolania certyfikatu przychodzacego
ret=check_peera(peer,error,0); //sprawdzenie odwolania certyfikatu naszego
// printf("nasz certyfikat:%s:%i\n",error,ret);
}
if ((peer==NULL)||(ret==1))
{
//nie akceptujemy polaczenia bo nasz certyfikat ma problem lub jest odwolany
// printf("polaczenie odrzucone- nasz certyfikat odwolany\n");
if (exit_now)
{
remove_symdir(getpid());
zamknij_polaczenie (con,ctx,msgsock);
exit(2);
}
ok=false;
}
}
if (ok)
{
X509_free(peer); //potrzebne?
peer=NULL;
}
// printf("connected...ok\n");
remove_symdir(getpid());
return ok;
}
If I don't call fork, all works fine, the message gets through, if the fork's there it gets stuck on ssl_accept.
Any help?

Not sure if this is just a typo or your real problem but this isn't going to do what you intend:
pid_t pid = fork();
if ( pid = 0 )
{
con = NULL;
//.............
Your child code is not going to execute.

Related

TCP Echo Server Using thread command line not showing

In my project wants when client side write like LIST the server side will directory list documents and after when I write like GET filename.txt but in the server side not shows me any thing ı think is stop how can I solve this problem my project describer in photo enter image description here
enter image description here
source code is
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdbool.h>
#include <dirent.h>
/* Definations */
#define DEFAULT_BUFLEN 1024
#define PORT 1888
void PANIC(char* msg);
#define PANIC(msg) { perror(msg); exit(-1); }
bool StartsWith(const char *a, const char *b)
{
if(strncmp(a, b, strlen(b)) == 0) return 1;
return 0;
}
void* Child(void* arg)
{ char line[DEFAULT_BUFLEN];
int bytes_read;
int client = *(int *)arg;
send(client,"Welcome to Vepa Server\n",strlen("Welcome to Vepa Server\n"),0);
do
{
bytes_read = recv(client, line, sizeof(line), 0);
if (bytes_read > 0) {
printf("%s",line);
// list command in here
if (strcmp(line,"LIST\n") ==0)
{
while(1)
{
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
send(client,dir->d_name,strlen(dir->d_name),0);
send(client,"\n",strlen("\n"),0);
}
closedir(d);
}
return(0);
}
}
if (StartsWith(line,"GET") == 1)
{
printf(line);
}
if ( (bytes_read=send(client, line, bytes_read, 0)) < 0 ) {
printf("Send failed\n");
break;
}
} else if (bytes_read == 0 ) {
printf("Connection closed by client\n");
break;
} else {
printf("Connection has problem\n");
break;
}
} while (bytes_read > 0);
close(client);
return arg;
}
int main(int argc, char *argv[])
{
int sd,opt,optval;
struct sockaddr_in addr;
unsigned short port=0;
while ((opt = getopt(argc, argv, "p:")) != -1) {
switch (opt) {
case 'p':
port=atoi(optarg);
break;
}
}
if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
PANIC("Socket");
addr.sin_family = AF_INET;
if ( port > 0 )
addr.sin_port = htons(port);
else
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = INADDR_ANY;
// set SO_REUSEADDR on a socket to true (1):
optval = 1;
setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
PANIC("Bind");
if ( listen(sd, SOMAXCONN) != 0 )
PANIC("Listen");
printf("System ready on port %d\n",ntohs(addr.sin_port));
while (1)
{
int client, addr_size = sizeof(addr);
pthread_t child;
client = accept(sd, (struct sockaddr*)&addr, &addr_size);
printf("Connected: %s:%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
if ( pthread_create(&child, NULL, Child, &client) != 0 )
perror("Thread creation");
else
pthread_detach(child); /* disassociate from parent */
}
return 0;
}

Prompt user for Username Password in browser while using winsock

I have written code in C++ with Winsock. It converts a video to mjpeg stream and sends it over TCP using Winsock in windows. Now I am able to see the video in any browser with the link.
But the problem is that anyone with the link can see it. I want to prompt the user to enter username and password to access the feed, whenever he types the IP address.
Here is my code:
#include <winsock.h>
#include <windows.h>
#include <time.h>
#define PORT unsigned long
#define ADDRPOINTER int*
struct _INIT_W32DATA
{
WSADATA w;
_INIT_W32DATA() { WSAStartup( MAKEWORD( 2, 1 ), &w ); }
} _init_once;
#include <iostream>
using std::cerr;
using std::endl;
#include <iostream>
#pragma comment(lib, "wsock32.lib")
using namespace std;
class MJPGWriter
{
SOCKET sock;
fd_set master;
int timeout; // master sock timeout, shutdown after timeout millis.
int quality; // jpeg compression [1..100]
int _write( int sock, char *s, int len )
{
if ( len < 1 ) { len = strlen(s); }
return ::send( sock, s, len, 0 );
}
public:
MJPGWriter(int port = 0)
: sock(INVALID_SOCKET)
, timeout(20000)
, quality(30)
{
FD_ZERO( &master );
if (port)
open(port);
}
~MJPGWriter()
{
release();
}
bool release()
{
if ( sock != INVALID_SOCKET )
::shutdown( sock, 2 );
sock = (INVALID_SOCKET);
return false;
}
bool open( int port )
{
sock = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP) ;
SOCKADDR_IN address;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_family = AF_INET;
address.sin_port = ::htons(port);
if ( ::bind( sock, (SOCKADDR*) &address, sizeof(SOCKADDR_IN) ) == SOCKET_ERROR )
{
cerr << "error : couldn't bind sock "<<sock<<" to port "<<port<<"!" << endl;
return release();
}
if ( ::listen( sock, 10 ) == SOCKET_ERROR )
{
cerr << "error : couldn't listen on sock "<<sock<<" on port "<<port<<" !" << endl;
return release();
}
FD_SET( sock, &master );
return true;
}
bool isOpened()
{
return sock != INVALID_SOCKET;
}
bool write(const cv::Mat & frame)
{
fd_set rread = master;
struct timeval to = {0,timeout};
SOCKET maxfd = sock+1;
if ( ::select( maxfd, &rread, NULL, NULL, &to ) <= 0 )
return true; // nothing broken, there's just noone listening
std::vector<uchar>outbuf;
std::vector<int> params;
params.push_back(cv::IMWRITE_JPEG_QUALITY);
params.push_back(quality);
cv::imencode(".jpg", frame, outbuf, params);
int outlen = outbuf.size();
#ifdef _WIN32
for ( unsigned i=0; i<rread.fd_count; i++ )
{
SOCKET s = rread.fd_array[i]; // fd_set on win is an array, while ...
#else
for ( int s=0; s<maxfd; s++ )
{
if ( ! FD_ISSET(s,&rread) ) // ... on linux it's a bitmask ;)
continue;
#endif
if ( s == sock ) // request on master socket, accept and send main header.
{
int addrlen = sizeof(SOCKADDR);
SOCKADDR_IN address = {0};
SOCKET client = ::accept( sock, (SOCKADDR*)&address, &addrlen );
if ( client == SOCKET_ERROR )
{
cerr << "error : couldn't accept connection on sock " << sock<< " !" << endl;
return false;
}
maxfd=(maxfd>client?maxfd:client);
FD_SET( client, &master );
_write( client,"HTTP/1.0 200 OK\r\n",0);
_write( client,
"Server: Mozarella/2.2\r\n"
"Accept-Range: bytes\r\n"
"Connection: close\r\n"
"Max-Age: 0\r\n"
"Expires: 0\r\n"
"Cache-Control: no-cache, private\r\n"
"Pragma: no-cache\r\n"
"Content-Type: multipart/x-mixed-replace; boundary=mjpegstream\r\n"
"\r\n",0);
cerr << "new client " << client << endl;
}
else // existing client, just stream pix
{
char head[400];
sprintf(head,"--mjpegstream\r\nContent-Type: image/jpeg\r\nContent-Length: %lu\r\n\r\n",outlen);
_write(s,head,0);
int n = _write(s,(char*)(&outbuf[0]),outlen);
//cerr << "known client " << s << " " << n << endl;
if ( n < outlen )
{
cerr << "kill client " << s << endl;
::shutdown(s,2);
FD_CLR(s,&master);
}
}
}
return true;
}
};
I am using it by sending image frame and port number to writer.

Errno code 88 in send() function (Socket programming)

I'm doing an implementation of FTP, now I'm implementing the RETR command, I take the errno code 88 when I try to do "get FILENAME".
I think that the error can be the conversion of unsigned to uint32_t and uint16_t in the port command.
#include <cstring>
#include <cstdarg>
#include <cstdio>
#include <cerrno>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <locale.h>
#include <langinfo.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <iostream>
#include <dirent.h>
#include "common.h"
#include "ClientConnection.h"
ClientConnection::ClientConnection(int s) {
int sock = (int)(s);
char buffer[MAX_BUFF];
control_socket = s;
// Consultar la documentación para conocer el funcionamiento de fdopen.
fd = fdopen(s, "a+");
if (fd == NULL){
std::cout << "Connection closed" << std::endl;
fclose(fd);
close(control_socket);
ok = false;
return ;
}
ok = true;
data_socket = -1;
};
ClientConnection::~ClientConnection() {
fclose(fd);
close(control_socket);
}
int connect_TCP(uint32_t address, uint16_t port) {
struct sockaddr_in sin;
struct hostent
*hent;
int s;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = address;
//if(hent = gethostbyname(address))
//memcpy(&sin.sin_addr,hent->h_addr,hent->h_length);
//else if ((sin.sin_addr.s_addr = inet_addr((char*)address)) == INADDR_NONE)
//errexit("No puedo resolver el nombre \"%s\"\n", address);
s = socket(AF_INET, SOCK_STREAM, 0);
if(s < 0){
printf("No se puede crear el socket\n");
return 0;
}
if(connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0){
printf("No se puede conectar con %u\n", address);
return 0;
}
return s;
}
void ClientConnection::stop() {
close(data_socket);
close(control_socket);
parar = true;
}
#define COMMAND(cmd) strcmp(command, cmd)==0
void ClientConnection::WaitForRequests() {
if (!ok) {
return;
}
fprintf(fd, "220 Service ready\n");
while(!parar) {
fscanf(fd, "%s", command);
if (COMMAND("USER")) {
fscanf(fd, "%s", arg);
fprintf(fd, "331 User name ok, need password\n");
}
else if (COMMAND("PWD")) {
}
else if (COMMAND("PASS")) {
char pass[30];
fscanf(fd,"%s",pass);
fprintf(fd,"230 User logged in\n");
}
else if (COMMAND("PORT")) {
unsigned ip[4];
unsigned port[2];
fscanf(fd,"%u,%u,%u,%u,%u,%u",&ip[0],&ip[1],&ip[2],&ip[3],&port[0],&port[1]);
uint32_t aux1;
uint16_t aux2;
aux1 = ip[3] << 24 | ip[2] << 16 | ip[1] << 8 | ip[0];
aux2 = port[1]*256 + port[0];
data_socket = connect_TCP(aux1,aux2);
fprintf(fd,"200 OK\n");
}
else if (COMMAND("PASV")) {
}
else if (COMMAND("CWD")) {
}
else if (COMMAND("STOR") ) { //put
FILE* fp = fopen("filename","w+");
int size_buffer = 512;
char buffer[size_buffer];
int recived_datas;
while(recived_datas == size_buffer){
datos_recibidos = recv(data_socket,buffer,size_buffer,0);
fwrite(buffer,1,recived_datas,fp);
}
close(data_socket);
fclose(fp);
}
else if (COMMAND("SYST")) {
fprintf(fd,"SYSTEM DETAILS\n");
}
else if (COMMAND("TYPE")) {
fprintf(fd,"type 1");
}
else if (COMMAND("RETR")) {
fscanf(fd,"%s",arg);
std::cout << "Argument: " << arg << std::endl;
FILE* fp = fopen(arg,"r+");
int sent_datas;
int size_buffer = 512;
char buffer[size_buffer];
std::cout << "Buffer size = " << size_buffer << std::endl;
do{
sent_datas = fread(buffer,size_buffer,1,fp);
printf("Code %d | %s\n",errno,strerror(errno));
send(data_socket,buffer,sent_datas,0);
printf("Code %d | %s\n",errno,strerror(errno));
}while(sent_datas == size_buffer);
close(data_socket);
fclose(fp);
fprintf(fd,"Transferencia completada");
}
else if (COMMAND("QUIT")) {
}
else if (COMMAND("LIST")) {
}
else {
fprintf(fd, "502 Command not implemented.\n"); fflush(fd);
printf("Comando : %s %s\n", command, arg);
printf("Error interno del servidor\n");
}
}
fclose(fd);
return;
};
Error code 88 is ENOTSOCK meaning that your tried to do a socket operation on "not a socket".
The offending line, I believe is:
send(data_socket,buffer,sent_datas,0);
It looks like in your RETR section you never set data_socket to a valid socket with your connect_TCP function, as you did in PORT. Are you certain that data_socket is a valid fd when you call your RETR function?

writing tcp server -- buffering a stream

#include <sys/socket.h> // for socket(), bind(), listen(), accept()
#include <netinet/in.h> // for PF_INET, SOCK_STREAM, IPPROTO_TCP
#include <stdio.h> // for printf(), perror()
#include <unistd.h> // for read(), write(), close()
#include <string.h> // for bzero()
#define DEMO_PORT 9723
int main( void )
{
//-----------------------------------------
// create an unnamed socket for the server
//-----------------------------------------
int sock = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( sock < 0 )
{
perror( "opening stream socket" );
return -1;
}
printf( "\nsock=%d \n", sock );
//----------------------------------------
// construct a name for the server socket
//----------------------------------------
struct sockaddr_in self;
socklen_t nlen = sizeof self;
bzero( &self, sizeof self );
self.sin_family = AF_INET;
self.sin_port = htons( DEMO_PORT );
self.sin_addr.s_addr = htonl( INADDR_ANY );
if ( bind( sock, (sockaddr *)&self, nlen ) < 0 )
{
perror( "bind failed" );
return -1;
}
printf( "bind succeeded port: %d\n",DEMO_PORT);
//---------------------------------------------------------
// now create a connection queue and wait for some clients
//---------------------------------------------------------
if ( listen( sock, 5 ) < 0 )
{
perror( "listen failed" );
return -1;
}
printf( "listen succeeded \n" );
//---------------------------------------------------
// main loop to process clients' connection-requests
//---------------------------------------------------
while ( 1 )
{
sockaddr_in peer;
socklen_t plen = sizeof peer;
bzero( &peer, plen );
printf( "server waiting \n" );
int client = accept( sock, (sockaddr *)&peer, &plen );
if ( client < 0 ) { perror( "accept" ); break; }
//---------------------------------------------
// we can now read from or write to the client
//---------------------------------------------
char ch;
int index = 0;
char get[1024];
if ( read( client, &ch, 1 ) < 0 )
{
perror( "read" );
}
bool go = true;
while(go){
if(ch != '/' && ch != '\r'){
printf("read: %hhd\n", ch);
get[index] = ch;
printf( "got stuff: %s\n", get );
index++;
read(index, &ch, 1);
} else {
go = false;
index = 0;
close( client );
printf( "server responded, connection closed" );
}
}
//if ( write( client, &ch, 1 ) < 0 ) { perror( "write" ); break; }
}
close( sock );
printf( "\n" );
}
the while(go) look never works and it buffers incorrectly. I do not see the pattern within the buffer or how it works.
What is the correct way to do this? to except a certain amount of bytes, store them in a string, then terminate the read if it reaches a newline character?
You are passing index into the second read call where you should be passing client.
This may not be your only problem but I think it is one of them.

epoll loops on disconnection of a client

I am trying to implement a socket server by using epoll. I have 2 threads doing 2 tasks:
listening to incoming connection
writing on screen the data the client is sending.
For my test I have the client and the server on the same machine with 3 or 4 clients running.
The server works fine until I don't kill one of the client by issuing a CTRL-C: as soon I do that the server starts looping and printing at a very fast rate data from other client. The strange thing is that
the client sends data each 2 seconds but the rate of the server is higher
epoll_wait is also supposed to print something when one of the client disconnects as it is checking also for EPOLLHUP or EPOLLERR
epoll_wait should wait a bit before printing since I gave him a timeout of 3000 milliseconds.
Can you help? Could it be that I am passing in a wrong way the epoll descriptor to the other thread? I cannot understand since the code looks similar to many examples around.
Thanks a lot
Mn
// server.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
extern "C" {
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <pthread.h>
}
#define MAX_BACKLOG 10
void* readerthread(void* args){
int epfd = *((int*)args);
epoll_event outwait[10];
while(true){
int retpw = epoll_wait( epfd, outwait,20, 3000 );
if( retpw == -1 ){
printf("epoll error %m\n");
}else if( retpw == 0 ){
printf("nothing is ready yet\n");
continue;
}else{
for( int i=0;i<retpw;i++){
if( outwait[i].events & EPOLLIN ){
int fd = outwait[i].data.fd;
char buf[64];
if( -1 == read(fd,buf,64) ){
printf("error reading %m\n");
}
printf("%s\n",buf);
}else{
std::cout << "other event" << std::endl;
}
}
}
}
}
int main(){
int epfd = epoll_create(10);
if( -1 == epfd ){
std::cerr << "error creating EPOLL server" << std::endl;
return -1;
}
pthread_t reader;
int rt = pthread_create( &reader, NULL, readerthread, (void*)&epfd );
if( -1 == rt ){
printf("thread creation %m\n");
return -1;
}
struct addrinfo addr;
memset(&addr,0,sizeof(addrinfo));
addr.ai_family = AF_INET;
addr.ai_socktype = SOCK_STREAM;
addr.ai_protocol = 0;
addr.ai_flags = AI_PASSIVE;
struct addrinfo * rp,* result;
getaddrinfo( "localhost","59000",&addr,&result );
for( rp = result; rp != NULL; rp = rp->ai_next ){
// we want to take the first ( it could be IP_V4
// or IP_V6 )
break;
}
int sd = socket( AF_INET, SOCK_STREAM, 0 );
if(-1==sd ){
std::cerr << "error creating the socket" << std::endl;
return -1;
}
// to avoid error 'Address already in Use'
int optval = 1;
setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
if( -1==bind( sd, result->ai_addr, result->ai_addrlen ) ){
printf("%m\n");
std::cerr << "error binding" << std::endl;
return -1;
}
while(true){
std::cout << "listen" << std::endl;
if( -1== listen(sd, MAX_BACKLOG ) ){
std::cerr << "listen didn't work" << std::endl;
return -1;
}
std::cout << "accept" << std::endl;
sockaddr peer;
socklen_t addr_size;
int pfd = accept( sd, &peer ,&addr_size );
if( pfd == -1 ){
std::cerr << "error calling accept()" << std::endl;
return -1;
}
epoll_event ev;
ev.data.fd = pfd;
ev.events = EPOLLIN;
std::cout << "adding to epoll list" << std::endl;
if( -1 == epoll_ctl( epfd, EPOLL_CTL_ADD, pfd, &ev ) ){
printf("epoll_ctl error %m\n");
return -1;
}
}
}
// end of server.cpp
// client.cpp
#include <iostream>
#include <cstring>
#include <cstdio>
extern "C"{
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
}
int main(){
const char* servername = "localhost";
const char* serverport = "59000";
struct addrinfo server_address;
memset( &server_address, 0, sizeof(struct addrinfo) );
server_address.ai_family = AF_INET;
server_address.ai_socktype = SOCK_STREAM;
server_address.ai_protocol = 0; // any protocol
server_address.ai_flags = 0;
struct addrinfo * result, * rp;
int res = getaddrinfo( servername, serverport, &server_address, &result );
if( -1 == res ){
std::cout << "I cannot getaddress " << servername << std::endl;
return -1;
}
int fd = socket( server_address.ai_family
, server_address.ai_socktype
, server_address.ai_protocol );
if( -1 == fd ){
printf("I cannot open a socket %m\n");
return -1;
}
for( rp = result; rp != NULL; rp = rp->ai_next ){
std::cout << "************" << std::endl;
if( -1 == connect( fd, rp->ai_addr, rp->ai_addrlen ) ){
close(fd);
}else{
std::cout << "connected" << std::endl;
break;
}
}
if( rp == NULL ){
std::cerr << "I couldn't connect server " << servername << std::endl;
}
while(true){
sleep(2);
pid_t me = getpid();
char buf[64];
bzero( buf,sizeof(buf));
sprintf( buf,"%ld",me );
write(fd,buf,sizeof(buf));
printf("%s\n",buf);
}
}
// end of client.cpp
A client disconnection is signalled by an EOF condition on the file descriptor. The system considers EOF to be a state in which the file descriptor is 'readable'. But, of course, the EOF condition cannot be read. This is the source of your looping. epoll is acting like the file descriptor for the disconnected client is always readable. You can detect that you have an EOF condition by checking when read returns 0 bytes read.
The only way to deal with an EOF condition is to close the file descriptor in some way. Depending on exactly how the flow of things go, this could be with shutdown(sockfd, SHUT_RD), shutdown(sockfd, SHUT_RDWR) or close(sockfd);.
Unless you know that you need the shutdown(2) call for whatever reason, I would recommend you use close. Of course, you should remember to tell epoll that the file descriptor is no longer of interest before you close. I'm not sure what will happen if you don't, but one possibility is that epoll will error. Another is that epoll will mysteriously begin reporting events for a new file descriptor that has the same numeric value before you add it to the list epoll should care about.
Socket cleanly closed by the other side will become readable and read(2) will return 0, you have to check for that. As coded now - level-triggered poll - epoll_wait(2) returns every time without waiting telling that you still haven't read that end-of-stream.
Alternatively, you can switch to edge-triggered poll (EPOLLET) and react to EPOLLRDHUP too.