Search code examples
csocketscurlnetwork-programmingposix-select

My C program is frozen upon accepting a connection when tested with CURL


I apologize if my code is extensively long, but I'm attempting to make a local server that handles multiple local clients. I even imported ideas from http://www.binarytides.com/multiple-socket-connections-fdset-select-linux/ to try to get it to work with no success.

I run it using 82 for a parameter, and see as expected:

Socket made and ready
Accepting 10 users

I then use CURL to connect to 127.0.0.1:82 and curl stalls. In my program I see as expected:

CLIENT CONNECTION MADE on socket# 0!

But the problem is data isn't being sent from the server to the client.

I tried forcing a break in CURL (via ctrl+c) to see if anything happened on the server and nothing did. I even tried using a web browser to connect and received similar results (a hang-up).

If I force a break on the server (via ctrl+c), then I got what I expect, a disconnection message (like "Empty Reply from server" from CURL).

What I expected to see in my browser is:

Error

This is a hack-ed-server

What could I be doing wrong here? I'm sort-of new to the select() calls so I'm not sure if I configured them correctly.

Here's the code:

#include <fcntl.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/errno.h>
#include <signal.h>
#include <time.h>

extern errno;
long asock=-1,nsock=-1;

void end_app(int s){
    struct sigaction si;
    si.sa_handler=SIG_DFL;si.sa_flags=0;
    sigaction(SIGCHLD,&si,NULL);
    sigaction(SIGTSTP,&si,NULL);
    sigaction(SIGTTOU,&si,NULL);
    sigaction(SIGTTIN,&si,NULL);
    sigaction(SIGSEGV,&si,NULL);
    sigaction(SIGTERM,&si,NULL);
    sigaction(SIGHUP,&si,NULL);
    char v[5000];
    sprintf(v,"Abrupt exit detected sig# %d. Closing sockets.\n",s);
    write(1,v,strlen(v));
    if (asock > -1){close(asock);}
    if (nsock > -1){close(nsock);}
}

const long trapsig(){
    struct sigaction s,si;
    si.sa_handler=SIG_IGN;si.sa_flags=0;
    s.sa_handler=end_app;s.sa_flags=0;
    sigaction(SIGCHLD,&si,NULL);sigaction(SIGTSTP,&si,NULL);sigaction(SIGTTOU,&si,NULL);sigaction(SIGTTIN,&si,NULL);
    if (sigaction(SIGSEGV,&s,NULL)==-1){printf("Cant trap signal!\n");return 1;}
    if (sigaction(SIGTERM,&s,NULL)==-1){printf("Cant trap signal!\n");return 1;}
    if (sigaction(SIGHUP,&s,NULL)==-1){printf("Cant trap signal!\n");return 1;}
}

//getreq params in:   req=external buffer for data
//            reqsz=size of external buffer. I set 10000
//            nsock=valid socket pointer from accept()
//
//getreq params out:  reqsz=actual size of data returned
//
void getreq(char* req,unsigned long *reqsz,long nsock){
    //bufsize=how many bytes to read at once. High values like 5000 cause a stall.
    //buffer=buffer of data from recv call
    const unsigned long ibs=*reqsz,bufsize=5000;
    char buffer[ibs],*rp=req;
    //spacect=# of spaces in data read
    //szct=iterator variable
    //mysz=total length of returned data
    //bufct=buffer counter to prevent segfault
    //recvsz=data size returned from recv or
    //       forced -2 if buffer hits capacity
    //       or 2nd space in returned data is found
    unsigned long spacect=0,szct=0,mysz=0,bufct=0;
    long recvsz=1;char *p=buffer;
    //
    //Expected data: GET /whatever HTTP/x.x but we
    //               want /whatever
    //
    //loop until 2nd space is found or 
    //ibs bytes of data have been processed
    while (recvsz > 0 && bufct < ibs){
        recvsz=recv(nsock, p, bufsize, 0);
        if (recvsz < 1){break;}
        for (szct=1;szct<=recvsz;szct++){
            if (*p==' '){spacect++;if (spacect > 2){spacect=2;recvsz=-2;break;}}
            if (spacect==1 && *p != ' '){mysz++;if (mysz <= *reqsz){*rp++=*p;}}
            p++;bufct++;if (bufct > ibs){recvsz=-2;break;}
        }
    }
    // Process rest of data to try to avoid client errors
    while (recvsz == -2){
        recvsz=recv(nsock, buffer, bufsize, 0);
    }
    *reqsz=mysz;
}

int main(int argc,char* argv[]){
    if (trapsig() < 0){return 1;}
    //set maximum users to 10 and allocate space for each
    long maxusers=10;long csock[11];memset(csock,0,11);
    //do sanity checks and bind local socket
    if (!argv[1]){printf("Port # required\n");return 1;}
    if ((asock=socket(AF_INET, SOCK_STREAM, 0)) < 1){printf("Can't make socket! %s\n",strerror(errno));return 1;}
    struct sockaddr_in a;
    memset(&a,0,sizeof(a));
    a.sin_family=AF_INET;
    a.sin_addr.s_addr=inet_addr("127.0.0.1");
    a.sin_port=htons(strtol(argv[1],NULL,10));
    if (bind(asock,(struct sockaddr*)&a, sizeof(a))==-1){printf("Can't bind socket! %s\n",strerror(errno));return 1;}
    if (listen(asock,10) < 0){printf("Can't listen! %s\n",strerror(errno));return 1;}
    printf("Socket made and ready\nAccepting %d users\n",maxusers);
    while(1){
        usleep(10); //sleep incase processor is overloaded
        fd_set SR;long SMAX=asock,n,canadd=0;
        FD_ZERO(&SR);FD_SET(asock,&SR);
        for (n=0;n<maxusers;n++){
            if (csock[n] > 0){FD_SET(csock[n],&SR);}else{canadd=1;}
            if (csock[n] > SMAX){SMAX=csock[n];}
        }
        long act=select(SMAX+1,&SR,0,0,0);
        if (act != EINTR && act < 0){printf("Select error\n");}
        if (canadd==1 && FD_ISSET(asock,&SR)){
            //incoming connection detected
            socklen_t alen=sizeof(a);
            if (nsock=accept(asock, (struct sockaddr*)&a, &alen)< 0){printf("Can't accept! %s\n",strerror(errno));close(asock);return -1;}
            for (n=0;n<maxusers;n++){if (csock[n]==0){csock[n]=nsock;break;}}
            printf("CLIENT CONNECTION MADE on socket# %d!\n",n);
            fcntl(nsock, F_SETFD, O_NONBLOCK);
            //program reaches here when client first connects
        }
        for (n=0;n<maxusers;n++){
            if (csock[n] > 0 && FD_ISSET(csock[n],&SR)){
                //this section never seems to execute
                unsigned long reqsz=10000;
                char req[reqsz];
                printf("Checking incoming data...\n",n);
                getreq(req,&reqsz,csock[n]);
                if (reqsz > 0){
                printf("Received %d bytes\nData: %s\n",reqsz,req);
                const char buf[10000]={"HTTP/1.0 200 OK\nConnection: close\nContent-type: text/html\n\n<html><head><title>hacked</title></head><body><H1>Error</h1><p>This is a hack-ed-server</p></body></html>\n\n"};
                send(csock[n],buf,strlen(buf),0);
                }else{
                printf("Received no data\n");
                }
                printf("Closing.\n");
                close(csock[n]);
                csock[n]=0;
            }
        }
    }
    printf("Closing sockets\n");
    close(asock);
    return 0;
}

Solution

  • This

    long csock[11];memset(csock,0,11);
    

    does not initialize csock completely -- just the first 11 bytes. You want memset(csock, 0, sizeof(csock));