#include "include/httpd.h"
#include "include/socket.h"
int getcon(int s,int y,hash *socket) {
int size,g,one=0;
struct sockaddr_in remote;
int bufnum, n;
fd_set fds;
struct timeval wait;
bufnum = 0;
if (y == 128) { y = 1; }
size = sizeof(struct sockaddr_in);
if (s==-1)
{
return(-1);
}
wait.tv_sec = 0L;
wait.tv_usec = 2500L;
FD_ZERO(&fds);
FD_SET(s, &fds);
if (select(s+1, &fds, NULL, 0, &wait) > 0)
{
y++;
if ((socket[y].socket = accept (s, (struct sockaddr *)&remote, &size))== -1) {
perror ("accept");
exit(1);
}
if (setsockopt(socket[y].socket, SOL_SOCKET, SO_KEEPALIVE, (char *) &one,sizeof(int)) < 0) {
perror("setsockopt");
exit(1);
}
getpeername(socket[y].socket,(struct sockaddr *)&remote,&size);
sprintf(socket[y].peername,inet_ntoa(remote.sin_addr));
printf("Con Sock ID: %i\n",socket[y].socket);
}
return y;
}
int serve(conf *cf) {
int s,one=1;
struct sockaddr_in local;
struct linger li;
local.sin_family = AF_INET;
local.sin_port = htons (cf[1].port);
local.sin_addr.s_addr = get_ip(cf[1].servername);
li.l_onoff = 1;
li.l_linger = 30;
if ((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
perror("socket");
exit(1);
}
/*
if (setsockopt(s, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof(struct linger)) < 0) {
perror("setsockopt");
exit(1);
}
*/
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(int)) < 0) {
perror("setsockopt");
exit(1);
}
if (bind (s, (struct sockaddr *)&local, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
if (listen(s, 5) == -1) {
perror("listen");
exit(1);
}
return s;
}
int sockread(int s,char *buf) {
char inc;
int bufnum, n;
fd_set fds;
struct timeval wait;
bufnum = 0;
if (s==-1) {
return(-1);
}
wait.tv_sec = 0L;
wait.tv_usec = 2500L;
FD_ZERO(&fds);
FD_SET(s, &fds);
if (select(s+1, &fds, NULL, 0, &wait) > 0) {
do {
n = recv(s, &inc, 1,0);
if (n == 0) {
return -1;
}
if (bufnum < BUFFER_SIZE - 1 ) {
if (inc != 13) {
buf[bufnum++] = inc;
}
}
}
while (inc != '\n');
{
buf[bufnum] = '\0';
}
brx += bufnum;
return bufnum;
}
return 0;
}
int get_ip(char *host) {
struct hostent *hp;
struct in_addr *in;
int ip;
if ((ip = inet_addr(host)) == -1) {
hp = gethostbyname(host);
if (!hp)
return(-1);
in = (struct in_addr*)(hp->h_addr_list[0]);
ip = (int)(in->s_addr);
return(ip);
}
return(ip);
}
//int send_to_sock(int socket, const char *fmt, ...) {
int send_to_sock(int s,char *string) {
/*
char *string;
va_list args;
string = malloc(MAXBUFLENGTH);
va_start(args, fmt);
vsnprintf(string, MAXBUFLENGTH, fmt, args);
va_end(args);
*/
/*
int bufnum, n;
fd_set fds;
struct timeval wait;
bufnum = 0;
if (s==-1) {
return(-1);
}
wait.tv_sec = 0L;
wait.tv_usec = 2500L;
FD_ZERO(&fds);
FD_SET(s, &fds);
if (select(s+1, NULL, &fds, 0, &wait) > 0) {
*/
send(s, string, strlen(string), 0);
//write(s,string,strlen(string));
// }
return(strlen(string));
}