慕神4583458 的学生作业:
file_transfer.c
#include "file_transfer.h"
#include "debug.h"
int recv_protocol_head(int cfd, file_protocol_t *p_head) {
int total_size = sizeof(file_protocol_t);
int total_recevied = 0;
char *buf = (char *)p_head;
ssize_t rbytes;
for (;;) {
rbytes = tcp_recv_pack(cfd, buf+ total_recevied, total_size - total_recevied);
if (rbytes == -1) {
DEBUG_INFO("[ERROR]: %s", strerror(errno));
return -1;
} else if (rbytes == 0) {
DEBUG_INFO("[INFO]: client is shutdown");
break;
} else if (rbytes > 0) {
total_recevied += rbytes;
if (total_recevied >= total_size) break;
}
}
if (total_recevied > total_size) {
DEBUG_INFO("[INFO]: recevied failed");
return -1;
}
return 0;
}
int recv_filedata(int cfd,const char *filename,size_t targetsize) {
int total_recevied = 0;
ssize_t rbytes, wbytes;
int fd = open(filename, O_RDWR | O_TRUNC | O_CREAT);
if (fd == -1) {
DEBUG_INFO("[INFO]: recevied failed");
return -1;
}
char buf[1024];
for(;;) {
memset(buf, 0, sizeof(buf));
rbytes = recv(cfd, buf, sizeof(buf), 0);
if (rbytes == -1) {
DEBUG_INFO("[ERROR]: %s", strerror(errno));
return -1;
} else if (rbytes == 0) {
DEBUG_INFO("[INFO]: client is shutdown");
break;
} else if (rbytes > 0) {
wbytes = write(fd, buf, rbytes);
if (rbytes != wbytes) {
DEBUG_INFO("[INFO]: recevied fail");
return -1;
}
total_recevied += rbytes;
if (total_recevied >= targetsize) break;
}
}
if (total_recevied > targetsize) {
DEBUG_INFO("[INFO]: recevied too large");
return -1;
}
close(fd);
return total_recevied;
}
int client_upload_file(int cfd) {
file_protocol_t file_protocol;
int ret;
ret = recv_protocol_head(cfd, &file_protocol);
if (ret == -1) return -1;
ret = recv_filedata(cfd, file_protocol.filename, file_protocol.filesize);
if (ret == -1) return -1;
printf("file recevied size = %d", ret);
return 0;
}
int send_protocol_head(const char *filename,int sockfd) {
file_protocol_t file_protocol;
int fd = open(filename, O_RDONLY);
if (fd == -1) {
DEBUG_INFO("[ERROR]: %s", strerror(errno));
return -1;
}
int pos = lseek(fd, 0, SEEK_END);
strcpy(file_protocol.filename, filename);
file_protocol.filesize = pos;
close(fd);
int wbytes = tcp_send_pack(sockfd, &file_protocol, sizeof(file_protocol_t));
if (wbytes == -1) {
DEBUG_INFO("[ERROR]: %s", strerror(errno));
return -1;
}
return pos;
}
int upload_file(const char *filename,int sockfd) {
int file_size, wbytes, rbytes, total_sended;
file_size = send_protocol_head(filename, sockfd);
if (file_size == -1) return -1;
int fd = open(filename, O_RDONLY);
if (fd == -1) return -1;
char buf[1024];
for(;;) {
memset(buf, 0, sizeof(buf));
rbytes = read(fd, buf, sizeof(buf));
if (rbytes == -1) {
DEBUG_INFO("[ERROR]: %s", strerror(errno));
return -1;
}
wbytes = tcp_send_pack(sockfd, buf, rbytes);
if (wbytes != rbytes) {
DEBUG_INFO("[INFO] send failed");
return -1;
}
total_sended += rbytes;
if (total_sended >= rbytes) break;
}
close(fd);
return total_sended;
}