Compare commits

...

4 Commits

Author SHA1 Message Date
ubuntu201711081
a7457281e5 add comment thread safe 2020-12-04 05:25:10 +00:00
ubuntu201711081
923349635d change implement of timeout_recv 2020-12-04 04:39:58 +00:00
ubuntu201711081
eca169cd4f fix source swapped 2020-12-03 23:21:37 +00:00
ubuntu201711081
2880b0791e add reuseaddr 2020-12-03 23:16:51 +00:00
5 changed files with 325 additions and 315 deletions

View File

@ -1,17 +1,19 @@
CC = gcc CC = gcc
CFLAGS = -lm -Wall -O2 CFLAGS = -lm -Wall -O2
Bin = server client
all: all:
make client make $(Bin)
make server
socket_wrapper.o: socket_wrapper.c socket_wrapper.h socket_wrapper.o: socket_wrapper.c socket_wrapper.h
$(CC) -c socket_wrapper.c -o socket_wrapper.o $(CFLAGS) $(CC) -c socket_wrapper.c -o socket_wrapper.o $(CFLAGS)
client: socket_wrapper.o client.c client: socket_wrapper.o client.c
$(CC) -o client client.c socket_wrapper.o $(CFLAGS) $(CC) -o client client.c socket_wrapper.o $(CFLAGS)
server: server:
$(CC) -o server server.c socket_wrapper.o $(CFLAGS) $(CC) -o server server.c socket_wrapper.o $(CFLAGS)
.PHONY: clean
clean: clean:
rm *.o server client rm *.o $(Bin)

271
client.c
View File

@ -9,188 +9,155 @@
#include <arpa/inet.h> #include <arpa/inet.h>
#include <errno.h> #include <errno.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <signal.h>
#include <assert.h> #include <assert.h>
#include <fcntl.h> #include <fcntl.h>
#include "socket_wrapper.h" #include "socket_wrapper.h"
#ifdef USE_SENDFILE
#include <sys/sendfile.h>
const size_t SEND_FILE_CHUNK_SIZE = 0x100000; /*1MB*/
#endif
/*======== /*========
*Operation *Operation
*========*/ *========*/
/*send user error message
80 character limit int sendReadOp(int sock,const char * filename){
*/ struct ReadOp op;
int send_fail(int sock,const char * msg){ op.file_url_size = strlen(filename);
struct TransferResult res; op.padding0 = 0;
res.res = RES_USR_ERR; if(send(sock,&op,sizeof(op),0)<0){
res.file_size = 0; perror("readop send fail");
res.err_number = 0;
res.error_msg_size = strlen(msg);
//os will be combining if tcp_autocorking emabled.
if(send(sock,&res,sizeof(res),0) < 0){
perror("error msg send");
return -1; return -1;
} }
if (send(sock,msg,res.error_msg_size,0) < 0){ if(send(sock,filename,op.file_url_size,0)<0){
perror("error msg send"); perror("readop filename send fail");
return -1; return -1;
} }
return 0; return 0;
} }
int send_errno(int sock){ int recvFile(int sock, const char * filename,size_t file_size){
struct TransferResult r;
r.res = RES_ERR;
r.err_number = errno;
r.file_size = 0;
r.error_msg_size = 0;
if(send(sock,&r,sizeof(r),0)){
perror("errno send");
return -1;
}
return 0;
}
/* return fd, if success.
otherwise, return -1.
*/
int read_request(int sock,uint8_t * buf,size_t bufsize){
struct ReadOp p;
int fd; int fd;
ssize_t n = recv_until_byte(sock,&p,sizeof(p),TIMEOUT); size_t count = 0;
if (n < 0){ int i;
if (n == -2) fprintf(stderr,"timeout!"); int cur_progress = 1;
else perror("receive fail"); int return_value = 0;
int buf_sz = getBufferSizeFrom(sock);
uint8_t * buf = malloc(buf_sz*sizeof(*buf));
if (buf == NULL){
return -1; return -1;
} }
if(bufsize <= p.file_url_size + sizeof(p) + 1){ fd = open(filename,O_WRONLY|O_CREAT|O_TRUNC,S_IRWXU|S_IRWXG|S_IROTH);
send_fail(sock,"buffer overflow"); if (fd < 0)
return -1;
}
else if(p.file_url_size + 1 > MAX_PATH_SIZE){
send_fail(sock,"max path fail");
return -1;
}
else if(p.file_url_size == 0){
send_fail(sock,"filename zero fail");
return -1;
}
n = recv_until_byte(sock,buf,p.file_url_size,TIMEOUT);
buf[p.file_url_size] = '\0';
printf("str size: %d, request %s\n",p.file_url_size,buf);
if(strchr((char *)buf,'/') != NULL){
send_fail(sock,"Illegal character /");
return -1;
}
fd = open((char *)buf,O_RDONLY);
if(fd < 0){
send_errno(sock);
close(fd);
return -1;
}
return fd;
}
int send_response(int sock,int fd, uint8_t * buf, size_t bufsize){
struct TransferResult r;
struct stat st;
off_t offset = 0;
ssize_t readed = 0;
r.res = RES_OK;
r.err_number = 0;
r.error_msg_size = 0;
if(fstat(fd,&st) < 0){
return send_errno(sock);
}
if(S_ISDIR(st.st_mode)){
return send_fail(sock,"is a directory");
}
r.file_size = st.st_size;
if(send(sock,&r,sizeof(r),0)<0){
perror("send fail");
return -1;
}
#ifdef USE_SENDFILE
while (r.file_size != offset)
{ {
size_t count = SEND_FILE_CHUNK_SIZE < (r.file_size - offset) ? SEND_FILE_CHUNK_SIZE : (r.file_size - offset); perror("file open fail");
if((readed = sendfile(sock,fd,&offset,count)) < 0){ return -1;
perror("send file fail");
return -1;
}
}
#else
while (offset < r.file_size)
{
readed = bufsize < (r.file_size - offset) ? bufsize : r.file_size - offset;
if(read(fd,buf,readed)<0){
perror("send response read fail");
return -1;
}
if(send(sock,buf,readed,0)<0){
perror("send response send fail");
return -1;
}
offset += readed;
} }
#endif while (file_size - count > 0)
{
int readed = buf_sz < file_size - count ? buf_sz : file_size - count;
if((i = recv_until_byte(sock,buf,readed,TIMEOUT)) < 0){
if(i == -2)
fprintf(stderr,"recv file failed : timeout connetion lost\n");
else perror("recv file failed");
return_value = -1;
goto END;
}
if(write(fd,buf,readed)<0){
perror("file write failed");
return_value = -1;
goto END;
}
if( ((double)count / (double)file_size) * 100.0 > ((double)cur_progress) ){
printf("\rprogress : %d%% current bytes: %ld bytes",cur_progress,count);
cur_progress = (int)((((double)count / (double)file_size)) * 100.0 + 1.0);
fflush(stdout);
}
count += readed;
}
printf("\rprogress : 100.00%% current bytes: %ld bytes\n",count);
END:
free(buf);
return return_value;
}
int recvData(int sock,const char * filename){
struct TransferResult res;
int i=0;
if((i=recv_until_byte(sock,&res,sizeof(res),TIMEOUT)) < 0){
if (i == -2) fprintf(stderr,"timeout");
else perror("recv fail");
return -1;
}
static char error_meesage_buf[80] = "";
switch(res.res){
case RES_ERR:
fprintf(stderr,"Server Fail: %s", strerror(res.err_number));
return -1;
case RES_USR_ERR:
assert(res.error_msg_size < 80);/*todo : fix*/
if((i=recv_until_byte(sock,error_meesage_buf,res.error_msg_size,TIMEOUT)) < 0){
if (i == -2) fprintf(stderr,"timeout");
else perror("recv fail");
return -1;
}
fprintf(stderr,"Error Message From Server: %s",error_meesage_buf);
return -1;
case RES_OK:
return recvFile(sock,filename,res.file_size);
break;
default:
fprintf(stderr,"unknown value!");
return -1;
}
return 0; return 0;
} }
static int sock;
void safe_exit(){
close(sock);
}
int main(int argc, const char *argv[]){ int main(int argc, const char *argv[]){
uint8_t * buf;
struct sockaddr_in addr; struct sockaddr_in addr;
struct sockaddr_in client_addr; const char * filename;
socklen_t client_addr_len = sizeof(client_addr); const char * server_name;
int csock; in_port_t server_port = SERVER_PORT;
int bufsize; int sock;
register_alarm(); if (argc != 4){
fprintf(stderr,"invaild arguments number.");
return 1;
}
server_name = argv[1];
server_port = atoi(argv[2]);
filename = argv[3];
if (server_port == 0)
{
fprintf(stderr,"port invalid");
return 1;
}
sock = socket(AF_INET,SOCK_STREAM,0); sock = socket(AF_INET,SOCK_STREAM,0);
atexit(safe_exit);
if(sock < 0){ if(sock < 0){
perror("sock create fail"); perror("sock create fail");
return 1; return 1;
} }
bufsize = getBufferSizeFrom(sock);
buf = malloc(bufsize * sizeof(*buf));
if (buf == NULL){
fprintf(stderr,"lack of memory");
return 1;
}
addr.sin_addr.s_addr = htonl(INADDR_ANY); /*0.0.0.0 모든 네트워크 인터페이스에 묶임.*/
addr.sin_family = AF_INET;
addr.sin_port = htons(SERVER_PORT);
if(bind(sock, (struct sockaddr *)&addr,sizeof(addr)) < 0){
perror("bind failed");
return 1;
}
fprintf(stderr,"server bind on %s:%d\n",inet_ntoa(addr.sin_addr),SERVER_PORT);
if(listen(sock,1) < 0){
perror("listen failed");
return 1;
}
while ((csock = accept(sock, (struct sockaddr *)&client_addr,&client_addr_len)) >= 0)
{ {
int fd; int option = 1;
/*inet_ntoa is not reentrant function. do not use it in signal handler.*/ if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&option,sizeof(option)) < 0){
printf("Connect : %s\n",(inet_ntoa(client_addr.sin_addr))); perror("setsockopt");
if((fd = read_request(csock,buf,bufsize)) > 0){
send_response(csock,fd,buf,bufsize);
close(fd);
} }
if(close(csock) < 0)
perror("csock close error");
} }
free(buf); addr.sin_addr.s_addr = inet_addr(server_name);
perror("accept error"); addr.sin_family = AF_INET;
return 1; addr.sin_port = htons(server_port);
if(connect(sock,(struct sockaddr *)&addr,sizeof(addr)) < 0){
perror("connect failed");
return 1;
}
if(sendReadOp(sock,filename) == 0){
int ret = recvData(sock,filename);
close(sock);
return ret;
}
close(sock);
return 0;
} }

288
server.c
View File

@ -9,151 +9,197 @@
#include <arpa/inet.h> #include <arpa/inet.h>
#include <errno.h> #include <errno.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <signal.h>
#include <assert.h> #include <assert.h>
#include <fcntl.h> #include <fcntl.h>
#include "socket_wrapper.h" #include "socket_wrapper.h"
#ifdef USE_SENDFILE
#include <sys/sendfile.h>
const size_t SEND_FILE_CHUNK_SIZE = 0x100000; /*1MB*/
#endif
/*======== /*========
*Operation *Operation
*========*/ *========*/
int sendReadOp(int sock,const char * filename){ /**
struct ReadOp op; * send user error message
op.file_url_size = strlen(filename); * 80 character limit
op.padding0 = 0; * thread safe
if(send(sock,&op,sizeof(op),0)<0){ */
perror("readop send fail"); int send_fail(int sock,const char * msg){
return -1;
}
if(send(sock,filename,op.file_url_size,0)<0){
perror("readop filename send fail");
return -1;
}
return 0;
}
int recvFile(int sock, const char * filename,size_t file_size){
int fd;
size_t count = 0;
int i;
int cur_progress = 1;
int return_value = 0;
int buf_sz = getBufferSizeFrom(sock);
uint8_t * buf = malloc(buf_sz*sizeof(*buf));
if (buf == NULL){
return -1;
}
fd = open(filename,O_WRONLY|O_CREAT|O_TRUNC,S_IRWXU|S_IRWXG|S_IROTH);
if (fd < 0)
{
perror("file open fail");
return -1;
}
while (file_size - count > 0)
{
int readed = buf_sz < file_size - count ? buf_sz : file_size - count;
if((i = recv_until_byte(sock,buf,readed,TIMEOUT)) < 0){
if(i == -2)
fprintf(stderr,"recv file failed : timeout connetion lost\n");
else perror("recv file failed");
return_value = -1;
goto END;
}
if(write(fd,buf,readed)<0){
perror("file write failed");
return_value = -1;
goto END;
}
if( ((double)count / (double)file_size) * 100.0 > ((double)cur_progress) ){
printf("\rprogress : %d%% current bytes: %ld bytes",cur_progress,count);
cur_progress = (int)((((double)count / (double)file_size)) * 100.0 + 1.0);
fflush(stdout);
}
count += readed;
}
printf("\rprogress : 100.00%% current bytes: %ld bytes\n",count);
END:
free(buf);
return return_value;
}
int recvData(int sock,const char * filename){
struct TransferResult res; struct TransferResult res;
int i=0; res.res = RES_USR_ERR;
if((i=recv_until_byte(sock,&res,sizeof(res),TIMEOUT)) < 0){ res.file_size = 0;
if (i == -2) fprintf(stderr,"timeout"); res.err_number = 0;
else perror("recv fail"); res.error_msg_size = strlen(msg);
//os will be combining if tcp_autocorking emabled.
if(send(sock,&res,sizeof(res),0) < 0){
perror("error msg send");
return -1; return -1;
} }
static char error_meesage_buf[80] = ""; if (send(sock,msg,res.error_msg_size,0) < 0){
switch(res.res){ perror("error msg send");
case RES_ERR: return -1;
fprintf(stderr,"Server Fail: %s", strerror(res.err_number));
return -1;
case RES_USR_ERR:
assert(res.error_msg_size < 80);/*todo : fix*/
if((i=recv_until_byte(sock,error_meesage_buf,res.error_msg_size,TIMEOUT)) < 0){
if (i == -2) fprintf(stderr,"timeout");
else perror("recv fail");
return -1;
}
fprintf(stderr,"Error Message From Server: %s",error_meesage_buf);
return -1;
case RES_OK:
return recvFile(sock,filename,res.file_size);
break;
default:
fprintf(stderr,"unknown value!");
return -1;
} }
return 0; return 0;
} }
/**
int main(int argc, const char *argv[]){ * send errno to client
struct sockaddr_in addr; * thread safe
const char * filename; */
const char * server_name; int send_errno(int sock){
in_port_t server_port = SERVER_PORT; struct TransferResult r;
int sock; r.res = RES_ERR;
register_alarm(); r.err_number = errno;
if (argc != 4){ r.file_size = 0;
fprintf(stderr,"invaild arguments number."); r.error_msg_size = 0;
return 1; if(send(sock,&r,sizeof(r),0)){
perror("errno send");
return -1;
} }
server_name = argv[1]; return 0;
server_port = atoi(argv[2]); }
filename = argv[3]; /**
if (server_port == 0) * return fd, if success. otherwise, return -1.
* thread safe
*/
int read_request(int sock,uint8_t * buf,size_t bufsize){
struct ReadOp p;
int fd;
ssize_t n = recv_until_byte(sock,&p,sizeof(p),TIMEOUT);
if (n < 0){
if (n == -2) fprintf(stderr,"timeout!");
else perror("receive fail");
return -1;
}
if(bufsize <= ((size_t)p.file_url_size) + sizeof(p) + 1){
send_fail(sock,"buffer overflow");
return -1;
}
else if(p.file_url_size + 1 > MAX_PATH_SIZE){
send_fail(sock,"max path fail");
return -1;
}
else if(p.file_url_size == 0){
send_fail(sock,"filename zero fail");
return -1;
}
n = recv_until_byte(sock,buf,p.file_url_size,TIMEOUT);
buf[p.file_url_size] = '\0'; //truncate
fprintf(stdout,"str size: %d, request %s\n",p.file_url_size,buf);
if(strchr((char *)buf,'/') != NULL){
send_fail(sock,"Illegal character /");
return -1;
}
fd = open((char *)buf,O_RDONLY);
if(fd < 0){
send_errno(sock);
close(fd);
return -1;
}
return fd;
}
/**
* send response to client
* thread safe
*/
int send_response(int sock,int fd, uint8_t * buf, size_t bufsize){
struct TransferResult r;
struct stat st;
off_t offset = 0;
ssize_t readed = 0;
r.res = RES_OK;
r.err_number = 0;
r.error_msg_size = 0;
if(fstat(fd,&st) < 0){
return send_errno(sock);
}
if(S_ISDIR(st.st_mode)){
return send_fail(sock,"is a directory");
}
r.file_size = st.st_size;
if(send(sock,&r,sizeof(r),0)<0){
perror("send fail");
return -1;
}
#ifdef USE_SENDFILE
while (r.file_size != offset)
{ {
fprintf(stderr,"port invalid"); size_t count = SEND_FILE_CHUNK_SIZE < (r.file_size - offset) ? SEND_FILE_CHUNK_SIZE : (r.file_size - offset);
return 1; if((readed = sendfile(sock,fd,&offset,count)) < 0){
perror("send file fail");
return -1;
}
}
#else
while (offset < r.file_size)
{
readed = bufsize < (r.file_size - offset) ? bufsize : r.file_size - offset;
if(read(fd,buf,readed)<0){
perror("send response read fail");
return -1;
}
if(send(sock,buf,readed,0)<0){
perror("send response send fail");
return -1;
}
offset += readed;
} }
#endif
return 0;
}
static int sock;
void safe_exit(){
close(sock);
}
int main(int argc, const char *argv[]){
uint8_t * buf;
struct sockaddr_in addr;
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int csock;
int bufsize;
sock = socket(AF_INET,SOCK_STREAM,0); sock = socket(AF_INET,SOCK_STREAM,0);
atexit(safe_exit);
if(sock < 0){ if(sock < 0){
perror("sock create fail"); perror("sock create fail");
return 1; return 1;
} }
addr.sin_addr.s_addr = inet_addr(server_name); bufsize = getBufferSizeFrom(sock);
addr.sin_family = AF_INET; buf = malloc(bufsize * sizeof(*buf));
addr.sin_port = htons(server_port); if (buf == NULL){
if(connect(sock,(struct sockaddr *)&addr,sizeof(addr)) < 0){ fprintf(stderr,"lack of memory");
perror("connect failed");
return 1; return 1;
} }
if(sendReadOp(sock,filename) == 0){
int ret = recvData(sock,filename); addr.sin_addr.s_addr = htonl(INADDR_ANY); /*0.0.0.0 모든 네트워크 인터페이스에 묶임.*/
close(sock); addr.sin_family = AF_INET;
return ret; addr.sin_port = htons(SERVER_PORT);
if(bind(sock, (struct sockaddr *)&addr,sizeof(addr)) < 0){
perror("bind failed");
return 1;
} }
close(sock); fprintf(stderr,"server bind on %s:%d\n",inet_ntoa(addr.sin_addr),SERVER_PORT);
return 0;
if(listen(sock,1) < 0){
perror("listen failed");
return 1;
}
while ((csock = accept(sock, (struct sockaddr *)&client_addr,&client_addr_len)) >= 0)
{
int fd;
/*inet_ntoa is not reentrant function. do not use it in signal handler.*/
printf("Connect : %s\n",(inet_ntoa(client_addr.sin_addr)));
if((fd = read_request(csock,buf,bufsize)) > 0){
send_response(csock,fd,buf,bufsize);
close(fd);
}
if(close(csock) < 0)
perror("csock close error");
}
free(buf);
perror("accept error");
return 1;
} }

View File

@ -4,11 +4,14 @@
#include <errno.h> #include <errno.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include <poll.h>
#include "socket_wrapper.h" #include "socket_wrapper.h"
int getBufferSizeFrom(int sock){ int getBufferSizeFrom(int sock){
int buffer_sz; int buffer_sz;
socklen_t len = sizeof(buffer_sz); socklen_t len = sizeof(buffer_sz);
//getsockopt is thread-safe
if(getsockopt(sock,SOL_SOCKET,SO_SNDBUF,&buffer_sz,&len) < 0){ if(getsockopt(sock,SOL_SOCKET,SO_SNDBUF,&buffer_sz,&len) < 0){
perror("failed to get sock buffer size: getsockopt"); perror("failed to get sock buffer size: getsockopt");
buffer_sz = DEFAULT_BUF_SIZE;/*set to default*/ buffer_sz = DEFAULT_BUF_SIZE;/*set to default*/
@ -18,41 +21,30 @@ int getBufferSizeFrom(int sock){
return buffer_sz; return buffer_sz;
} }
static uint64_t timer_ticks = 0;
static void alarm_handler(int signum){
timer_ticks++;
}
void register_alarm(){
struct sigaction sigact;
sigact.sa_flags = SA_INTERRUPT;
sigemptyset(&sigact.sa_mask);
sigaddset(&sigact.sa_mask,SIGALRM);
sigact.sa_handler = alarm_handler;
sigaction(SIGALRM, &sigact ,NULL);
}
ssize_t timeout_recv(int fd,void * buf,size_t n,int timeout) ssize_t timeout_recv(int fd,void * buf,size_t n,int timeout)
{ {
ssize_t ret; ssize_t ret;
uint64_t cur = timer_ticks; int poll_ret;
int die_count = 0; struct pollfd fd_single;
for(;;){ fd_single.fd = fd;
alarm(timeout); fd_single.events = POLL_IN;
poll_ret = (poll(&fd_single,1,timeout * 1000));
if (poll_ret < 0) return -1;
else if(poll_ret == 0) return -2;
switch (fd_single.revents){
case POLLHUP: //We'll treat hangups state like timeouts state.
return -2;
case POLLERR:
case POLLNVAL:
return -1;
case POLL_IN:
ret = recv(fd,buf,n,0); ret = recv(fd,buf,n,0);
if (ret < 0 && errno == EINTR && cur != timer_ticks) assert(ret != 0);
return -2; return ret;
alarm(0); default:
if (ret == 0){ assert(0 && "unreachable");
usleep(100000);
die_count++;
if(die_count > timeout*10){
return -2;
}
}
else break;
} }
return ret; assert(0 && "unreachable");
} }
ssize_t recv_until_byte(int fd,void * buf, size_t n,int timeout){ ssize_t recv_until_byte(int fd,void * buf, size_t n,int timeout){

View File

@ -41,19 +41,22 @@ struct TransferResult{
#endif #endif
/**
* find buffer size from sock
* thread safe
*/
int getBufferSizeFrom(int sock); int getBufferSizeFrom(int sock);
/*register alarm for timeout_recv()*/ /**
void register_alarm(); * return -2 if timeout occur.
/* * otherwise, implement equal to 'recv'.
return -2 if timeout occur. * `timeout` unit is second.
otherwise, implement equal to 'recv'. * thread safe
you must call register_alarm() before you use this.
Since alarm() is called by internal implementation, don't use it if other alarms already exist.
*/ */
ssize_t timeout_recv(int fd,void * buf,size_t n,int timeout); ssize_t timeout_recv(int fd,void * buf,size_t n,int timeout);
/* /*
recieve data to buf until all bytes. * recieve data to buf until all bytes.
* thread safe
*/ */
ssize_t recv_until_byte(int fd,void * buf, size_t n,int timeout); ssize_t recv_until_byte(int fd,void * buf, size_t n,int timeout);