Added webserver, parse args, A1066

This commit is contained in:
BitHeaven 2023-03-22 06:45:51 +05:00
parent dc9a742471
commit 4f74b0a1b8
9 changed files with 272 additions and 68 deletions

8
.idea/Bit.ASICmon.iml generated
View File

@ -1,8 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<module type="CPP_MODULE" version="4"> <module classpath="CMake" type="CPP_MODULE" version="4" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

5
.idea/codeStyles/codeStyleConfig.xml generated Normal file
View File

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

4
.idea/misc.xml generated Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" />
</project>

View File

@ -5,5 +5,5 @@ set(CMAKE_CXX_STANDARD 23)
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++") set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")
add_executable(bitwi2dl main.cpp inc/getosname.hpp inc/json.hpp) add_executable(bitasicmon main.cpp inc/getosname.hpp inc/json.hpp inc/args.hpp inc/macros.hpp inc/colors.hpp)
target_link_libraries(bitwi2dl "-lcurl") target_link_libraries(bitasicmon "-lcurl")

28
inc/args.hpp Normal file
View File

@ -0,0 +1,28 @@
#include <cstdio>
#include <string>
#include <algorithm>
class InputParser {
public:
InputParser (int &argc, char **argv){
for (int i=1; i < argc; ++i)
this->tokens.push_back(std::string(argv[i]));
}
/// @author iain
const std::string& getCmdOption(const std::string &option) const{
std::vector<std::string>::const_iterator itr;
itr = std::find(this->tokens.begin(), this->tokens.end(), option);
if (itr != this->tokens.end() && ++itr != this->tokens.end()){
return *itr;
}
static const std::string empty_string("");
return empty_string;
}
/// @author iain
bool cmdOptionExists(const std::string &option) const{
return std::find(this->tokens.begin(), this->tokens.end(), option) != this->tokens.end();
}
private:
std::vector <std::string> tokens;
};

15
inc/colors.hpp Normal file
View File

@ -0,0 +1,15 @@
#ifndef BIT_COLORS_HPP
#define BIT_COLORS_HPP
#define RESET "\033[0m"
#define BLACK "\033[30m"
#define RED "\033[31m"
#define GREEN "\033[32m"
#define YELLOW "\033[33m"
#define BLUE "\033[34m"
#define MAGENTA "\033[35m"
#define CYAN "\033[36m"
#define WHITE "\033[37m"
#define BOLD "\033[1m"
#endif //BIT_COLORS_HPP

View File

@ -1,15 +1,15 @@
#ifndef BITWI2DL_GETOSNAME_H #ifndef BIT_GETOSNAME_H
#define BITWI2DL_GETOSNAME_H #define BIT_GETOSNAME_H
#include <string> #include <string>
std::string getOsName() { std::string getOsName() {
#ifdef _WIN64 #ifdef _WIN64
return "windows 64-bit"; return "mustdie64";
#elif _WIN32 #elif _WIN32
return "windows 32-bit"; return "mustdie32";
#elif __APPLE__ || __MACH__ #elif __APPLE__ || __MACH__
return "mac osx"; return "osx";
#elif __linux__ #elif __linux__
return "linux"; return "linux";
#elif __FreeBSD__ #elif __FreeBSD__

24
inc/macros.hpp Normal file
View File

@ -0,0 +1,24 @@
#include "colors.hpp"
#ifndef BIT_MACROS_HPP
#define BIT_MACROS_HPP
#define INFO(...) std::cout , "[INFO] " , __VA_ARGS__ , std::endl;
#define WARN(...) std::cout , YELLOW , "[WARN] " , __VA_ARGS__ , RESET , std::endl;
#define ERR(...) std::cout , RED , "[ERROR] " , __VA_ARGS__ , RESET , std::endl;
#define CRIT(...) std::cout , BOLD , RED , "[CRIT] " , __VA_ARGS__ , RESET , std::endl;
template <typename T>
std::ostream& operator,(std::ostream& out, const T& t) {
out << t;
return out;
}
//overloaded version to handle all those special std::endl and others...
std::ostream& operator,(std::ostream& out, std::ostream&(*f)(std::ostream&)) {
out << f;
return out;
}
#endif //BIT_MACROS_HPP

242
main.cpp
View File

@ -1,37 +1,44 @@
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <stdio.h> #include <cstdio>
#include <sys/types.h> #include <sys/types.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <stdlib.h> #include <cstdlib>
#include <unistd.h> #include <unistd.h>
#include <string.h> #include <cstring>
#include <netdb.h> #include <netdb.h>
#include <sys/uio.h> #include <sys/uio.h>
#include <sys/time.h> #include <sys/time.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <fcntl.h> #include <fcntl.h>
#include <fstream> #include <fstream>
#include <regex>
#include "inc/args.hpp"
#include "inc/json.hpp"
#include "inc/macros.hpp"
using namespace std; using namespace std;
//Client side int port = 9070;
int main(int argc, char *argv[])
{
//we need 2 things: ip address and port number, in that order char* getFrom1066(char* ip, char* cmd) {
if(argc != 3) INFO("------ AVALON 1066 ------")
{ INFO("IP: ", ip)
cerr << "Usage: ip_address port" << endl; exit(0); INFO("Command: ", cmd)
} //grab the IP address and port number
char *serverIp = argv[1]; int port = atoi(argv[2]); int port = 4028;
//create a message buffer int msglen = 1024*8;
char msg[1500]; char* msg = new char[msglen];
//setup a socket and connection tools
struct hostent* host = gethostbyname(serverIp); struct hostent* host = gethostbyname(ip);
sockaddr_in sendSockAddr; sockaddr_in sendSockAddr;
bzero((char*)&sendSockAddr, sizeof(sendSockAddr)); bzero((char*)&sendSockAddr, sizeof(sendSockAddr));
sendSockAddr.sin_family = AF_INET; sendSockAddr.sin_family = AF_INET;
@ -40,45 +47,172 @@ int main(int argc, char *argv[])
int clientSd = socket(AF_INET, SOCK_STREAM, 0); int clientSd = socket(AF_INET, SOCK_STREAM, 0);
//try to connect... //try to connect...
int status = connect(clientSd, (sockaddr*) &sendSockAddr, sizeof(sendSockAddr)); int status = connect(clientSd, (sockaddr*) &sendSockAddr, sizeof(sendSockAddr));
if(status < 0) if(status < 0) {
{ ERR("Error connecting to socket!")
cout<<"Error connecting to socket!"<<endl; return (char*)"";
return -1;
} }
cout << "Connected to the server!" << endl; INFO("Connected to the server!")
int bytesRead, bytesWritten = 0;
struct timeval start1, end1; memset(msg, 0, strlen(msg));
gettimeofday(&start1, NULL); send(clientSd, cmd, sizeof(cmd), 0);
while(1) INFO("Awaiting server response...");
{ recv(clientSd, msg, msglen, MSG_WAITALL);
cout << ">"; INFO("Server: ", msg)
string data;
getline(cin, data);
memset(&msg, 0, sizeof(msg));//clear the buffer
strcpy(msg, data.c_str());
if(data == "exit")
{
send(clientSd, (char*)&msg, strlen(msg), 0);
break;
}
bytesWritten += send(clientSd, (char*)&msg, strlen(msg), 0);
cout << "Awaiting server response..." << endl;
memset(&msg, 0, sizeof(msg));//clear the buffer
bytesRead += recv(clientSd, (char*)&msg, sizeof(msg), 0);
if(!strcmp(msg, "exit"))
{
cout << "Server has quit the session" << endl;
break;
}
cout << "Server: " << msg << endl;
}
gettimeofday(&end1, NULL);
close(clientSd); close(clientSd);
cout << "********Session********" << endl; INFO("-------------------------")
cout << "Bytes written: " << bytesWritten <<
" Bytes read: " << bytesRead << endl; return msg;
cout << "Elapsed time: " << (end1.tv_sec- start1.tv_sec) }
<< " secs" << endl;
cout << "Connection closed" << endl; char* httpGetURL(char line[], const char symbol[]) {
char *copy = (char*)malloc(strlen(line) + 1);
strcpy(copy, line);
char *message;
char *token = strtok(copy, symbol);
int current = 0;
while(token != nullptr) {
token = strtok(nullptr, " ");
if(current == 0) {
message = token;
if (message == nullptr) {
message = (char *) "";
}
return message;
}
current = current + 1;
}
free(copy);
free(token);
return message;
}
void httpServer(int port) {
char http_header[25] = "HTTP/1.1 200 Ok\r\n";
int server_fd, new_socket, pid;
struct sockaddr_in address;
int addrlen = sizeof(address);
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
CRIT("In sockets")
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
memset(address.sin_zero, '\0', sizeof address.sin_zero);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
CRIT("In bind")
close(server_fd);
exit(EXIT_FAILURE);
}
if (listen(server_fd, 10) < 0) {
CRIT("In listen")
exit(EXIT_FAILURE);
}
INFO("HTTP server started on: http://127.0.0.1:", port)
while(1) {
printf("\n+++++++ Waiting for new connection ++++++++\n\n");
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
CRIT("In accept")
exit(EXIT_FAILURE);
}
pid = fork();
if(pid < 0) {
CRIT("Error on fork")
exit(EXIT_FAILURE);
}
if(pid == 0) {
char buffer[30000] = {0};
read(new_socket , buffer, 30000);
char *url = httpGetURL(buffer, " ");
INFO(url)
char *copy_head = new char[strlen(http_header) + 200];
strcpy(copy_head, http_header);
if(strstr(url, "/api/"))
strcat(copy_head, "Content-Type: application/json\r\n\r\n");
else if(strstr(url, ".js"))
strcat(copy_head, "Content-Type: text/javascript\r\n\r\n");
else
strcat(copy_head, "Content-Type: text/html\r\n\r\n");
write(new_socket, copy_head, strlen(copy_head));
if(strstr(url, ".js")) {
char file_path[512] = ".";
strcat(file_path, url);
int file = open(file_path, O_RDONLY);
if(file < 0){
WARN("Cannot Open file path : ", file_path, " with error ", file)
send(new_socket, R"({"error":"FILE_NOT_EXISTS"})", 27, MSG_DONTWAIT);
}
struct stat stat_buf;
fstat(file, &stat_buf);
sendfile(new_socket, file, nullptr, stat_buf.st_blksize);
}
else if(strcmp(url, "/") == 0) {
char* msg = (char*)R"(<meta charset="UTF-8"><script defer src="/index.js"></script>)";
send(new_socket, msg, strlen(msg), MSG_DONTWAIT);
}
else {
char* msg = getFrom1066((char*)"128.128.128.56", (char*)"estats");
send(new_socket, msg, strlen(msg), MSG_DONTWAIT);
}
close(new_socket);
free(copy_head);
}
else{
printf(">>>>>>>>>>Parent create child with pid: %d <<<<<<<<<", pid);
close(new_socket);
}
}
close(server_fd);
}
int main(int argc, char **argv) {
INFO("Bit.ASICmon started!")
InputParser input(argc, argv);
if(input.cmdOptionExists("-h")) {
INFO("HELP")
exit(0);
}
if(input.cmdOptionExists("-p")) {
const char* aport = input.getCmdOption("-p").c_str();
if (strcmp(aport, "") == 0){
port = atoi(aport);
INFO("Set port: ", port)
}
else {
WARN("Port invalid using default: ", port)
}
}
getFrom1066((char*)"128.128.128.56", (char*)"version");
char* msg = getFrom1066((char*)"128.128.128.56", (char*)"estats");
regex re(R"(BOOTBY\[([\d\s\w.]+)\])");
cmatch m;
regex_search(msg, m, re);
INFO(m[1])
httpServer(port);
return 0; return 0;
} }