fix: close forgotten open file descriptors for recvfile and sendfile

This commit is contained in:
ngn
2024-07-01 06:54:44 +03:00
parent 3c603fef22
commit f50e5c42b4

92
src/mptp/util.c Normal file
View File

@ -0,0 +1,92 @@
#include "../../include/mptp.h"
#include "../../include/error.h"
#include "../../include/util.h"
#include <errno.h>
#include <error.h>
#include <stdio.h>
#include <unistd.h>
bool lm_mptp_sendfile(int sock, struct sockaddr *addr, char *path){
if (NULL == path){
lm_error_set(LM_ERR_ArgNULL);
return false;
}
lm_mptp_t packet;
bool ret = false;
FILE *file = fopen(path, "r");
size_t read = 0;
if(NULL == file){
pdebug(__func__, "failed to open file: %s", path);
lm_error_set(LM_ERR_SendOpenFail);
lm_mptp_init(&packet, false, MPTP_S2C_BRUH, true);
goto end;
}
lm_mptp_init(&packet, false, MPTP_S2C_COOL, false);
while ((read = fread(packet.data, 1, MPTP_DATA_MAX, file)) > 0) {
packet.header.data_size = read;
if(!lm_mptp_server_send(sock, &packet, addr))
goto end;
lm_mptp_init(&packet, false, MPTP_S2C_COOL, false);
}
lm_mptp_init(&packet, false, MPTP_S2C_COOL, true);
ret = true;
end:
if(NULL != file)
fclose(file);
lm_mptp_server_send(sock, &packet, addr);
return ret;
}
bool lm_mptp_recvfile(int sock, char *path){
if(NULL == path){
lm_error_set(LM_ERR_ArgNULL);
return false;
}
if(unlink(path) < 0 && errno != ENOENT){
lm_error_set(LM_ERR_RecvDelFail);
return false;
}
FILE *file = fopen(path, "a");
bool ret = false;
lm_mptp_t packet;
if(NULL == file){
pdebug(__func__, "failed to open file: %s", path);
lm_error_set(LM_ERR_RecvOpenFail);
goto end;
}
while(lm_mptp_client_recv(sock, &packet)){
if(!lm_mptp_client_verify(&packet))
goto end;
if(MPTP_FLAGS_CODE(&packet) != MPTP_S2C_COOL){
lm_error_set(LM_ERR_RecvBadCode);
goto end;
}
if(MPTP_IS_LAST(&packet))
break;
if(fwrite(packet.data, 1, packet.header.data_size, file)==0){
lm_error_set(LM_ERR_RecvWriteFail);
goto end;
}
}
ret = true;
end:
if(NULL != file)
fclose(file);
return ret;
}