Shorter main function

This commit is contained in:
Bazsalanszky 2019-11-08 19:49:56 +01:00
parent 1828c99094
commit 98f5d50adf
Signed by: Bazsalanszky
GPG key ID: 0998CF5510B134D9
13 changed files with 225 additions and 143 deletions

View file

@ -7,11 +7,30 @@ set(GCC_COVERAGE_COMPILE_FLAGS "-Werror")
set(SOURCE_FILES modules/peer.h modules/peer.c utility.c utility.h modules/webio.h modules/webio.c modules/config.h modules/config.c lib/map.h lib/map.c lib/tcp-listener.c lib/tcp-listener.h)
option(BUILD_DOC "Build Documentation" ON)
find_package(Doxygen)
if(DOXYGEN_FOUND)
set(BUILD_DOC_DIR ${CMAKE_SOURCE_DIR}/build/docs)
if(NOT EXISTS ${BUILD_DOC_DIR})
file(MAKE_DIRECTORY ${BUILD_DOC_DIR})
endif()
set(DOXYGEN_IN ${CMAKE_CURRENT_SOURCE_DIR}/docs/Doxyfile)
set(DOXYGEN_OUT ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile)
configure_file(${DOXYGEN_IN} ${DOXYGEN_OUT} @ONLY)
add_executable(p2p main.c modules/peer.h modules/peer.c utility.c utility.h modules/webio.h modules/webio.c modules/config.h modules/config.c lib/map.h lib/map.c lib/tcp-listener.c lib/tcp-listener.h lib/net.h)
add_executable(p2p-2 main.c modules/peer.h modules/peer.c utility.c utility.h modules/webio.h modules/webio.c modules/config.h modules/config.c lib/map.h lib/map.c lib/tcp-listener.c lib/tcp-listener.h lib/net.h)
add_executable(p2p-3 main.c modules/peer.h modules/peer.c utility.c utility.h modules/webio.h modules/webio.c modules/config.h modules/config.c lib/map.h lib/map.c lib/tcp-listener.c lib/tcp-listener.h lib/net.h)
message("Doxygen build started")
add_custom_target(Doxygen ALL
COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_OUT}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMENT "Generating API documentation with Doxygen"
VERBATIM)
else(DOXYGEN_FOUND)
message("Doxygen needs to be installed to generate the documentation.")
endif(DOXYGEN_FOUND)
add_executable(p2p main.c modules/peer.h modules/peer.c utility.c utility.h modules/webio.h modules/webio.c modules/config.h modules/config.c lib/map.h lib/map.c lib/tcp-listener.c lib/tcp-listener.h lib/net.h modules/server.c modules/server.h)
add_executable(p2p-2 main.c modules/peer.h modules/peer.c utility.c utility.h modules/webio.h modules/webio.c modules/config.h modules/config.c lib/map.h lib/map.c lib/tcp-listener.c lib/tcp-listener.h lib/net.h modules/server.c modules/server.h)
add_executable(p2p-3 main.c modules/peer.h modules/peer.c utility.c utility.h modules/webio.h modules/webio.c modules/config.h modules/config.c lib/map.h lib/map.c lib/tcp-listener.c lib/tcp-listener.h lib/net.h modules/server.c modules/server.h)
set_target_properties( p2p-2 PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/p2p-2 )
set_target_properties( p2p-3 PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/p2p-3 )
# Függvények kipróbálására hoztam létre

View file

@ -58,7 +58,7 @@ PROJECT_LOGO =
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.
OUTPUT_DIRECTORY = @PROJECT_SOURCE_DIR@\docs
OUTPUT_DIRECTORY = @PROJECT_SOURCE_DIR@/docs
# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-
# directories (in 2 levels) under the output directory of each output format and
@ -790,7 +790,7 @@ WARN_LOGFILE =
# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
# Note: If this tag is empty the current directory is searched.
INPUT = @PROJECT_SOURCE_DIR@ @PROJECT_SOURCE_DIR@\modules @PROJECT_SOURCE_DIR@\lib @PROJECT_SOURCE_DIR@\docs
INPUT = @PROJECT_SOURCE_DIR@ @PROJECT_SOURCE_DIR@/modules @PROJECT_SOURCE_DIR@/lib @PROJECT_SOURCE_DIR@/docs
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
@ -1138,7 +1138,7 @@ HTML_FILE_EXTENSION = .html
# of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_HEADER = @PROJECT_SOURCE_DIR@\docs\doxygen-bootstrapped\header.html
HTML_HEADER = @PROJECT_SOURCE_DIR@/docs/doxygen-bootstrapped/header.html
# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
# generated HTML page. If the tag is left blank doxygen will generate a standard
@ -1148,7 +1148,7 @@ HTML_HEADER = @PROJECT_SOURCE_DIR@\docs\doxygen-bootstrapped\header.h
# that doxygen normally uses.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FOOTER = @PROJECT_SOURCE_DIR@\docs\doxygen-bootstrapped\footer.html
HTML_FOOTER = @PROJECT_SOURCE_DIR@/docs/doxygen-bootstrapped/footer.html
# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
# sheet that is used by each HTML page. It can be used to fine-tune the look of
@ -1173,7 +1173,7 @@ HTML_STYLESHEET =
# list). For an example see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_STYLESHEET = @PROJECT_SOURCE_DIR@\docs\doxygen-bootstrapped\customdoxygen.css
HTML_EXTRA_STYLESHEET = @PROJECT_SOURCE_DIR@/docs/doxygen-bootstrapped/customdoxygen.css
# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the HTML output directory. Note
@ -1183,7 +1183,7 @@ HTML_EXTRA_STYLESHEET = @PROJECT_SOURCE_DIR@\docs\doxygen-bootstrapped\customdo
# files will be copied as-is; there are no commands or markers available.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_FILES = @PROJECT_SOURCE_DIR@\docs\doxygen-bootstrapped\doxy-boot.js
HTML_EXTRA_FILES = @PROJECT_SOURCE_DIR@/docs/doxygen-bootstrapped/doxy-boot.js
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
# will adjust the colors in the style sheet and background images according to

View file

View file

View file

@ -30,10 +30,11 @@ function submitForm() {
var fetch_messages = new XMLHttpRequest();
var url = "/peers/" +window.location.pathname+ ".txt";
var last_text ="";
setInterval(function(){
fetch_messages.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) loadMessages(this.responseText.split("\n"));
last_text = this.responseText;
};
fetch_messages.open("GET", url, true);
fetch_messages.send();
@ -65,7 +66,7 @@ function loadMessages(arr) {
for(i = 0; i < arr.length; i++) {
if(arr[i] == '') continue;
if(arr[i].indexOf("Me:") == -1){
out += '<div class="card"><div class="card-body"><h6 class="text-muted card-subtitle mb-2">cfcf5b70adee41b91df434291dfa6377<br></h6><p class="card-text">' + joypixels.toImage(decodeURIComponent(arr[i].replaceAll('+',' '))) + '</p></div></div>';
out += '<div class="card"><div class="card-body"><h6 class="text-muted card-subtitle mb-2">'+window.location.pathname.replace("/","")+'<br></h6><p class="card-text">' + joypixels.toImage(decodeURIComponent(arr[i].replaceAll('+',' '))) + '</p></div></div>';
}else{
var msg = arr[i].replace("Me: ","");
out += '<div class="card"><div class="card-body"><h6 class="text-muted card-subtitle mb-2" style="text-align:right;">You<br></h6><p class="card-text" style="text-align:right;">' + joypixels.toImage((decodeURIComponent(msg.replaceAll('+',' ')))) + '</p></div></div>';

View file

@ -13,6 +13,8 @@
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
//Mappákhoz
#include <sys/stat.h>
//Winsock2 kompatiblitás érdekében
#ifndef SOCKET_ERROR
#define SOCKET_ERROR -1

137
main.c
View file

@ -1,58 +1,35 @@
#define CRT_SECURE_NO_WARNINGS
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include "modules/peer.h"
#include "modules/webio.h"
#include "modules/config.h"
#include "modules/server.h"
#include "lib/tcp-listener.h"
#pragma comment(lib, "ws2_32.lib")
SOCKET listening;
SOCKET web_sock;
void closeSocks(){
logger_log("Closing socket...");
close(listening);
close(web_sock);
}
int main(void) {
atexit(closeSocks);
Map config = config_load();
FILE *seed_file;
seed_file = fopen("seed.txt", "r");
char seed[17];
if (seed_file == NULL) {
logger_log("Seed not found! Generating a new one...");
strcpy(seed, generateSeed(16));
seed_file = fopen("seed.txt", "w");
fprintf(seed_file, "%s", seed);
} else {
fgets(seed, 512, seed_file);
}
fclose(seed_file);
char id[18];
strcpy(id, seed);
char buf[513];
Node_data mynode;
strcpy(mynode.id, id);
char *nickname = map_getValue(config, "nickname");
if (nickname != NULL) {
strcpy(mynode.nick, nickname);
} else strcpy(mynode.nick, "");
char *port = map_getValue(config, "port");
if (port != NULL)
mynode.port = atoi(port);
else
mynode.port = atoi(DEFAULT_PORT);
Node_data mynode = construct_Mynodedata(config);
logger_log("Initialising core...");
//TODO: Ezt a részt külön függvénybe tenni egy külön file-ban
struct addrinfo *result = NULL;
SOCKET listening;
result = tcp_createIPv4Socket(&listening, mynode.port, true);
if (result == NULL) {
return EXIT_FAILURE;
@ -75,97 +52,21 @@ int main(void) {
PeerList peerList1;
peer_initList(&peerList1);
FILE *peer_file;
peer_file = fopen("peers.txt", "r");
if (peer_file == NULL) {
logger_log("peers.txt not found!");
peer_file = fopen("peers.txt", "w");
fprintf(peer_file, "\n");
} else {
char ip[NI_MAXHOST];
int port;
while (fscanf(peer_file, "%[^:]:%d", ip, &port) != EOF) {
if (peer_ConnetctTo(ip, port, &peerList1, mynode, &master) != 0)
logger_log("Error while connecting to peer...");
}
}
fclose(peer_file);
WebIO webIo;
port = map_getValue(config, "interface-port");
if (port == NULL)
port = DEFAULT_INTERFACE_PORT;
char *folder = map_getValue(config, "interface-folder");
if (folder == NULL)
folder = DEFAULT_WWW_FOLDER;
char *local_mode_str = map_getValue(config, "interface-local");
bool local_mode = false;
if (strcmp(local_mode_str, "true") == 0)
local_mode = true;
res = webio_create(atoi(port), folder, mynode, !local_mode, &webIo);
res = webio_create(config,mynode, &webIo);
if (res != 0) {
return EXIT_FAILURE;
}
FD_SET(webIo.socket, &master);
web_sock = webIo.socket;
logger_log("Started web interface at http://127.0.0.1:%d", tcp_getSockPort(webIo.socket));
peer_loadPeerList(&peerList1,mynode,&master);
logger_log("Starting main loop...");
bool run = true;
while (run) {
fd_set copy = master;
SOCKET last = (peerList1.length > 0) ? peerList1.array[peerList1.length-1].socket : webIo.socket;
int count = select(last+1, &copy, NULL, NULL, NULL);
if (FD_ISSET(listening, &copy)) {
if (peer_HandleConnection(listening, &peerList1, mynode, &master) != 0)
logger_log("Error while receiving connection...");
} else if (FD_ISSET(webIo.socket, &copy)) {
res = webio_handleRequest(webIo, &peerList1);
if (res == -2) {
run = false;
}
} else {
for (int i = 0; i < peerList1.length; i++) {
SOCKET sock = peerList1.array[i].socket;
if(!FD_ISSET(sock,&copy))
continue;
char buf[DEFAULT_BUFLEN];
memset(buf, 0, DEFAULT_BUFLEN);
int inBytes = recv(sock, buf, DEFAULT_BUFLEN, 0);
if (inBytes <= 0) {
//Peer disconnect
int k = peer_getPeer(peerList1, sock);
if (k != -1) {
logger_log("Peer disconnected(%s->%s)", inet_ntoa(peerList1.array[k].sockaddr.sin_addr),
peerList1.array[k].peerData.id);
peer_removeFromList(&peerList1, k);
FD_CLR(sock, &master);
}
} else {
if (strlen(buf) == 0)
continue;
Map m = getPacketData(buf);
char file[64];
int k = peer_getPeer(peerList1, sock);
sprintf(file, "%speers/%s.txt", DEFAULT_WWW_FOLDER, peerList1.array[k].peerData.id);
logger_log("Message received from %s", peerList1.array[k].peerData.id);
FILE *fp;
fp = fopen(file, "a");
fprintf(fp, "%s\n", map_getValue(m, "message"));
fclose(fp);
free(m.pairs);
}
}
}
}
serverThread(listening,&master,webIo,peerList1,mynode);
free(peerList1.array);
free(config.pairs);
logger_log("Closing socket...");
close(listening);
return 0;
}

View file

@ -101,7 +101,7 @@ int peer_ConnetctTo(char* ip, int port, PeerList* peerList, Node_data my, fd_set
}
}
free(m.pairs);
logger_log("Peer validated (%s->%s)!",node.ip,node.id);
logger_log("Peer validated (%s->%s)!",inet_ntoa(hint.sin_addr),node.id);
return 0;
}
@ -154,9 +154,11 @@ int peer_HandleConnection(SOCKET listening, PeerList *peerList, Node_data my, fd
}
char * nickname = map_getValue(m, "nickname");
if(map_isFound(m,"nickname")) {
strcpy(node.nick, nickname);
strncpy(node.nick, nickname,29);
logger_log("Username: %s",node.nick);
}
if(peer_ID_isFound(*peerList,node.id)){
bool t = peer_ID_isFound(*peerList,node.id);
if(t){
logger_log("Handshake received, but the id sent is taken! Dropping peer...");
char handshake[1024] = "@valid=false&error=ID_TAKEN";
int res = send(sock, handshake, strlen(handshake), 0);
@ -273,3 +275,23 @@ int peer_ID_getPeer(struct PeerList list, char* c) {
return -1;
}
void peer_loadPeerList(PeerList *list,Node_data mynode,fd_set * master) {
FILE *peer_file;
peer_file = fopen("peers.txt", "r");
if (peer_file == NULL) {
logger_log("peers.txt not found!");
peer_file = fopen("peers.txt", "w");
fprintf(peer_file, "");
} else {
char ip[NI_MAXHOST];
int port;
while (fscanf(peer_file, "%[^:]:%d\n", ip, &port) == 2) {
if (peer_ConnetctTo(ip, port, list, mynode, master) != 0) {
logger_log("Error while connecting to peer...");
}
}
}
fclose(peer_file);
}

View file

@ -4,6 +4,7 @@
*/
#pragma once
#include "../utility.h"
#include "config.h"
//! A különböző gépek adatait tároló struktúra
typedef struct Node_data { //! A node IP címe(IPV4)
char ip[NI_MAXHOST]; //! A node azonosítója
@ -99,4 +100,4 @@ int peer_getPeer(struct PeerList list, SOCKET socket);
* @return A keresett peer indexe a listában.
* @note Ha nem találta a megadott azonosítót akkor (-1)-el tér vissza.
*/
int peer_ID_getPeer(struct PeerList list, char *id);
int peer_ID_getPeer(struct PeerList list, char *id);

91
modules/server.c Normal file
View file

@ -0,0 +1,91 @@
//
// Created by balazs on 2019. 11. 07..
//
#include "server.h"
void getSeed(char*output){
FILE *seed_file;
seed_file = fopen("seed.txt", "r");
if (seed_file == NULL) {
logger_log("Seed not found! Generating a new one...");
char* string = generateSeed(16);
strcpy(output, string);
free(string);
seed_file = fopen("seed.txt", "w");
fprintf(seed_file, "%s", output);
} else {
fgets(output, 512, seed_file);
}
fclose(seed_file);
}
Node_data construct_Mynodedata(Config cfg) {
Node_data result;
getSeed(result.id);
char *nickname = map_getValue(cfg, "nickname");
if (nickname != NULL) {
strcpy(result.nick, nickname);
} else strcpy(result.nick, "");
char *port = map_getValue(cfg, "port");
if (port != NULL)
result.port = atoi(port);
else
result.port = atoi(DEFAULT_PORT);
return result;
}
void serverThread(SOCKET listening, fd_set *master, WebIO webIo, PeerList list,Node_data mynode) {
bool run = true;
while (run) {
fd_set copy = *master;
SOCKET last = (list.length > 0) ? list.array[list.length - 1].socket : webIo.socket;
int count = select(last+1, &copy, NULL, NULL, NULL);
if (FD_ISSET(listening, &copy)) {
if (peer_HandleConnection(listening, &list, mynode, master) != 0)
logger_log("Error while receiving connection...");
} else if (FD_ISSET(webIo.socket, &copy)) {
int res = webio_handleRequest(webIo, &list);
if (res == -2) {
run = false;
}
} else {
for (int i = 0; i < list.length; i++) {
SOCKET sock = list.array[i].socket;
if(!FD_ISSET(sock,&copy))
continue;
char buf[DEFAULT_BUFLEN];
memset(buf, 0, DEFAULT_BUFLEN);
int inBytes = recv(sock, buf, DEFAULT_BUFLEN, 0);
if (inBytes <= 0) {
//Peer disconnect
int k = peer_getPeer(list, sock);
if (k != -1) {
logger_log("Peer disconnected(%s->%s)", inet_ntoa(list.array[k].sockaddr.sin_addr),
list.array[k].peerData.id);
peer_removeFromList(&list, k);
FD_CLR(sock, master);
}
} else {
if (strlen(buf) == 0)
continue;
Map m = getPacketData(buf);
char file[64];
int k = peer_getPeer(list, sock);
sprintf(file, "%speers/%s.txt", DEFAULT_WWW_FOLDER, list.array[k].peerData.id);
logger_log("Message received from %s", list.array[k].peerData.id);
FILE *fp;
fp = fopen(file, "a");
fprintf(fp, "%s\n", map_getValue(m, "message"));
fclose(fp);
free(m.pairs);
}
}
}
}
}

20
modules/server.h Normal file
View file

@ -0,0 +1,20 @@
//
// Készítette: Toldi Balázs Ádám
// Dátum: 2019. 11. 07.
//
#pragma once
#include "peer.h"
#include "webio.h"
void peer_loadPeerList(PeerList *list,Node_data mynode,fd_set * master);
/*!
*
* @param[out] output
*/
void getSeed(char*output);
/*!
*
* @param[in] cfg
* @return
*/
Node_data construct_Mynodedata(Config cfg);
void serverThread(SOCKET listening, fd_set* master, WebIO webIo, PeerList list,Node_data mynode);

View file

@ -11,15 +11,28 @@
#endif
int webio_create(int port,char* folder,struct Node_data myData,bool wildcard,WebIO *webIo){
int webio_create(Config config, struct Node_data myData, WebIO *webIo){
char *port = map_getValue(config, "interface-port");
if (port == NULL)
port = DEFAULT_INTERFACE_PORT;
char *folder = map_getValue(config, "interface-folder");
if (folder == NULL)
folder = DEFAULT_WWW_FOLDER;
char *local_mode_str = map_getValue(config, "interface-local");
bool local_mode = false;
if (local_mode_str != NULL && strcmp(local_mode_str, "true") == 0)
local_mode = true;
struct addrinfo *result = NULL;
SOCKET listening;
result = tcp_createIPv4Socket(&listening,port,wildcard);
result = tcp_createIPv4Socket(&listening,atoi(port),!local_mode);
if(result == NULL){
return 1;
}
tcp_bindnlisten(listening,result,SOMAXCONN);
int res = tcp_bindnlisten(listening,result,SOMAXCONN);
if(res != 0){
return 2;
}
WebIO wio;
wio.sockaddr = tcp_getAddr_in(listening);
@ -30,7 +43,7 @@ int webio_create(int port,char* folder,struct Node_data myData,bool wildcard,Web
return 0;
}
int webio_handleRequest(WebIO wio,const PeerList *list){
int webio_handleRequest(WebIO wio, const PeerList *list){
SOCKET client = accept(wio.socket,NULL,NULL);
char buf[8192];
memset(buf,0,8192);
@ -104,7 +117,7 @@ char* webio_getFiletype(char* filename){
return type;
}
int webio_handleGETrequest(SOCKET client,WebIO wio,char* file,const PeerList *list){
int webio_handleGETrequest(SOCKET client, WebIO wio, char* file, const PeerList *list){
char buf[8192];
sscanf(buf,"%*s %s",file);
@ -205,7 +218,16 @@ int webio_handlePOSTrequest(SOCKET client, WebIO wio, const PeerList *list, Map
if(map_isFound(post,"id") && map_isFound(post,"message") && strcmp(map_getValue(post,"message"),"%0D%0A") != 0){
char file[64];
sprintf(file,"%speers/%s.txt",wio.folder,map_getValue(post,"id"));
char folder[72];
sprintf(folder,"%s/peers/",wio.folder);
DIR *d = opendir(folder);
if(d == NULL)
#if defined(_WIN32)
_mkdir(folder);
#else
mkdir(folder, 0777); // notice that 777 is different than 0777
#endif
sprintf(file,"%s%s.txt",folder,map_getValue(post,"id"));
FILE * f;
f = fopen(file,"a");
fprintf(f,"Me: %s\n",map_getValue(post,"message"));

View file

@ -3,9 +3,11 @@
// Dátum: 2019. 10. 14..
//
#pragma once
#include <dirent.h>
#include "../utility.h"
#include "../lib/tcp-listener.h"
#include "peer.h"
#include "config.h"
typedef struct webio{
@ -15,11 +17,11 @@ typedef struct webio{
struct Node_data nodeData;
} WebIO;
int webio_create(int port,char* folder,struct Node_data myData,bool wildcard,WebIO *webIo);
int webio_create(Config config, struct Node_data myData, WebIO *webIo);
int webio_handleRequest(WebIO wio,const PeerList *list);
int webio_handleRequest(WebIO wio, const PeerList *list);
int webio_handleGETrequest(SOCKET client,WebIO wio,char * file,const PeerList *list);
int webio_handleGETrequest(SOCKET client, WebIO wio, char * file, const PeerList *list);
int webio_handlePOSTrequest(SOCKET client, WebIO wio, const PeerList *list, Map post);
@ -33,4 +35,5 @@ void webio_getIndex(char* folder, const PeerList *list, char *outputBuffer);
void webio_getPeerPage(char* folder, char *id, bool online, char *outputBuffer);
bool webio_isPeerFound(char* folder,char* id);
bool webio_isPeerFound(char* folder,char* id);