Make streams and vfs and http shared_ptr

This commit is contained in:
2025-09-29 02:22:27 -05:00
parent 71d0e36a5c
commit d785508571
61 changed files with 541 additions and 951 deletions

View File

@@ -52,7 +52,6 @@ src/Crypto/ClientTLSStream.cpp
src/Crypto/MbedHelpers.cpp src/Crypto/MbedHelpers.cpp
src/Args.cpp src/Args.cpp
src/TF_Init.cpp src/TF_Init.cpp
src/wrapper.cpp
src/HiddenField.cpp src/HiddenField.cpp
) )
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)

View File

@@ -5,16 +5,16 @@ using namespace Tesses::Framework::Streams;
using namespace Tesses::Framework::Http; using namespace Tesses::Framework::Http;
using namespace Tesses::Framework::Filesystem; using namespace Tesses::Framework::Filesystem;
VFS* vfs; std::shared_ptr<VFS> vfs;
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
TF_InitWithConsole(); TF_InitWithConsole();
vfs = new SubdirFilesystem(&LocalFS,Tesses::Framework::Filesystem::VFSPath::GetAbsoluteCurrentDirectory(),false); vfs = std::make_shared<SubdirFilesystem>(LocalFS,Tesses::Framework::Filesystem::VFSPath::GetAbsoluteCurrentDirectory());
CallbackServer cb([](ServerContext& ctx)->bool{ std::shared_ptr<CallbackServer> cb = std::make_shared<CallbackServer>([](ServerContext& ctx)->bool{
if(ctx.path == "/") if(ctx.path == "/")
{ {
ctx.WithMimeType("text/html") ctx.WithMimeType("text/html")
@@ -39,7 +39,7 @@ int main(int argc, char** argv)
{ {
if(ctx.NeedToParseFormData()) if(ctx.NeedToParseFormData())
{ {
ctx.ParseFormData([](std::string mime, std::string filename,std::string name)->Stream* { ctx.ParseFormData([](std::string mime, std::string filename,std::string name)->std::shared_ptr<Stream> {
if(name != "file") return nullptr; if(name != "file") return nullptr;
VFSPath path("/"+filename); VFSPath path("/"+filename);
auto strm = vfs->OpenFile(path,"wb"); auto strm = vfs->OpenFile(path,"wb");
@@ -81,8 +81,8 @@ int main(int argc, char** argv)
return false; return false;
}); });
Tesses::Framework::Http::MountableServer mountable(cb); auto mountable = std::make_shared<Tesses::Framework::Http::MountableServer>(cb);
mountable.Mount("/files/",new FileServer(vfs,true,true,false),true); mountable->Mount("/files/",std::make_shared<FileServer>(vfs,true,false));
HttpServer srv(4985,mountable); HttpServer srv(4985,mountable);
srv.StartAccepting(); srv.StartAccepting();

View File

@@ -7,9 +7,9 @@ int main(int argc, char** argv)
std::cout << "USAGE: " << argv[0] << " BINARYFILE VARNAME HEADERFILE" << std::endl; std::cout << "USAGE: " << argv[0] << " BINARYFILE VARNAME HEADERFILE" << std::endl;
return 0; return 0;
} }
Tesses::Framework::Streams::FileStream fs(argv[1],"rb"); auto fs=std::make_shared<Tesses::Framework::Streams::FileStream>(argv[1],"rb");
if(!fs.CanRead()) return 1; if(!fs->CanRead()) return 1;
Tesses::Framework::TextStreams::StreamWriter writer(argv[3]); auto writer = std::make_shared<Tesses::Framework::TextStreams::StreamWriter>(argv[3]);
Tesses::Framework::Text::GenerateCHeaderFile(&fs, argv[2], &writer); Tesses::Framework::Text::GenerateCHeaderFile(fs, argv[2], writer);
return 0; return 0;
} }

View File

@@ -59,7 +59,7 @@ int main(int argc, char** argv)
std::cout << "In folder: " << std::filesystem::absolute(directory).string() << std::endl; std::cout << "In folder: " << std::filesystem::absolute(directory).string() << std::endl;
FileServer fs(directory,allowListing, spa); auto fs = std::make_shared<FileServer>(directory,allowListing, spa);
HttpServer server(port,fs); HttpServer server(port,fs);
server.StartAccepting(); server.StartAccepting();
TF_RunEventLoop(); TF_RunEventLoop();

View File

@@ -2,35 +2,33 @@
using namespace Tesses::Framework::Streams; using namespace Tesses::Framework::Streams;
using namespace Tesses::Framework::Serialization::Json; using namespace Tesses::Framework::Serialization::Json;
using namespace Tesses::Framework::TextStreams; using namespace Tesses::Framework::TextStreams;
FileStream* OpenWrite(std::string dest) std::shared_ptr<FileStream> OpenWrite(std::string dest)
{ {
if(dest == "-") if(dest == "-")
{ {
return new FileStream(stdout,false,"w"); return std::make_shared<FileStream>(stdout,false,"w");
} }
else else
{ {
FileStream* strm = new FileStream(dest,"w"); auto strm = std::make_shared<FileStream>(dest,"w");
if(!strm->CanWrite()) if(!strm->CanWrite())
{ {
delete strm;
return nullptr; return nullptr;
} }
return strm; return strm;
} }
} }
FileStream* OpenRead(std::string src) std::shared_ptr<FileStream> OpenRead(std::string src)
{ {
if(src == "-") if(src == "-")
{ {
return new FileStream(stdin,false,"r"); return std::make_shared<FileStream>(stdin,false,"r");
} }
else else
{ {
FileStream* strm = new FileStream(src,"r"); auto strm = std::make_shared<FileStream>(src,"r");
if(!strm->CanRead()) if(!strm->CanRead())
{ {
delete strm;
return nullptr; return nullptr;
} }
return strm; return strm;
@@ -45,25 +43,24 @@ int main(int argc, char** argv)
std::cout << "DEST: prettied file or - for stdout" << std::endl; std::cout << "DEST: prettied file or - for stdout" << std::endl;
return 0; return 0;
} }
FileStream* src = OpenRead(argv[1]); auto src = OpenRead(argv[1]);
FileStream* dest = OpenWrite(argv[2]); auto dest = OpenWrite(argv[2]);
if(src == nullptr) if(src == nullptr)
{ {
if(dest != nullptr) delete dest;
std::cerr << "ERROR: Input could not be read" << std::endl; std::cerr << "ERROR: Input could not be read" << std::endl;
return 1; return 1;
} }
if(dest == nullptr) if(dest == nullptr)
{ {
delete src;
std::cerr << "ERROR: Output could not be read" << std::endl; std::cerr << "ERROR: Output could not be read" << std::endl;
return 1; return 1;
} }
StreamReader reader(src,true); StreamReader reader(src);
StreamWriter writer(dest,true); StreamWriter writer(dest);
auto str = reader.ReadToEnd(); auto str = reader.ReadToEnd();
writer.WriteLine(Json::Encode(Json::Decode(str))); writer.WriteLine(Json::Encode(Json::Decode(str)));

View File

@@ -2,35 +2,33 @@
using namespace Tesses::Framework::Streams; using namespace Tesses::Framework::Streams;
using namespace Tesses::Framework::Serialization::Json; using namespace Tesses::Framework::Serialization::Json;
using namespace Tesses::Framework::TextStreams; using namespace Tesses::Framework::TextStreams;
FileStream* OpenWrite(std::string dest) std::shared_ptr<FileStream> OpenWrite(std::string dest)
{ {
if(dest == "-") if(dest == "-")
{ {
return new FileStream(stdout,false,"w"); return std::make_shared<FileStream>(stdout,false,"w");
} }
else else
{ {
FileStream* strm = new FileStream(dest,"w"); auto strm = std::make_shared<FileStream>(dest,"w");
if(!strm->CanWrite()) if(!strm->CanWrite())
{ {
delete strm;
return nullptr; return nullptr;
} }
return strm; return strm;
} }
} }
FileStream* OpenRead(std::string src) std::shared_ptr<FileStream> OpenRead(std::string src)
{ {
if(src == "-") if(src == "-")
{ {
return new FileStream(stdin,false,"r"); return std::make_shared<FileStream>(stdin,false,"r");
} }
else else
{ {
FileStream* strm = new FileStream(src,"r"); auto strm = std::make_shared<FileStream>(src,"r");
if(!strm->CanRead()) if(!strm->CanRead())
{ {
delete strm;
return nullptr; return nullptr;
} }
return strm; return strm;
@@ -45,25 +43,24 @@ int main(int argc, char** argv)
std::cout << "DEST: unprettied file or - for stdout" << std::endl; std::cout << "DEST: unprettied file or - for stdout" << std::endl;
return 0; return 0;
} }
FileStream* src = OpenRead(argv[1]); auto src = OpenRead(argv[1]);
FileStream* dest = OpenWrite(argv[2]); auto dest = OpenWrite(argv[2]);
if(src == nullptr) if(src == nullptr)
{ {
if(dest != nullptr) delete dest;
std::cerr << "ERROR: Input could not be read" << std::endl; std::cerr << "ERROR: Input could not be read" << std::endl;
return 1; return 1;
} }
if(dest == nullptr) if(dest == nullptr)
{ {
delete src;
std::cerr << "ERROR: Output could not be read" << std::endl; std::cerr << "ERROR: Output could not be read" << std::endl;
return 1; return 1;
} }
StreamReader reader(src,true); StreamReader reader(src);
StreamWriter writer(dest,true); StreamWriter writer(dest);
auto str = reader.ReadToEnd(); auto str = reader.ReadToEnd();
writer.WriteLine(Json::Encode(Json::Decode(str),false)); writer.WriteLine(Json::Encode(Json::Decode(str),false));

View File

@@ -96,7 +96,7 @@ int main(int argc,char** argv)
{ {
if(args.size()<3) continue; if(args.size()<3) continue;
std::vector<std::string> args2(args.begin()+2,args.end()); std::vector<std::string> args2(args.begin()+2,args.end());
auto f = LocalFS.OpenFile(args[1],"rb"); auto f = LocalFS->OpenFile(args[1],"rb");
if(f != nullptr) if(f != nullptr)
{ {
auto path = Environment::GetRealExecutablePath(args2[0]); auto path = Environment::GetRealExecutablePath(args2[0]);
@@ -106,11 +106,10 @@ int main(int argc,char** argv)
{ {
auto strm = p.GetStdinStream(); auto strm = p.GetStdinStream();
f->CopyTo(strm); f->CopyTo(strm);
delete strm;
p.CloseStdInNow(); p.CloseStdInNow();
p.WaitForExit(); p.WaitForExit();
} }
delete f;
} }
} }
else { else {

View File

@@ -9,8 +9,6 @@ int main(int argc, char** argv)
VFSPath dest = fs.SystemToVFSPath(argv[2]); VFSPath dest = fs.SystemToVFSPath(argv[2]);
auto srcs = fs.OpenFile(src,"rb"); auto srcs = fs.OpenFile(src,"rb");
auto dests = fs.OpenFile(dest,"wb"); auto dests = fs.OpenFile(dest,"wb");
srcs->CopyTo(*dests); srcs->CopyTo(dests);
delete srcs;
delete dests;
} }

View File

@@ -13,23 +13,22 @@ int main(int argc, char** argv)
return 1; return 1;
} }
LocalFilesystem lfs;
std::string root = "./root"; std::string root = "./root";
std::string mountDemi = "./demi"; std::string mountDemi = "./demi";
std::string mountJoelSlashJim = "./joelslashjim"; std::string mountJoelSlashJim = "./joelslashjim";
SubdirFilesystem rootdir(&lfs,root,false); std::shared_ptr<SubdirFilesystem> rootdir = std::make_shared<SubdirFilesystem>(LocalFS,root);
SubdirFilesystem mountDemidir(&lfs,mountDemi,false); std::shared_ptr<SubdirFilesystem> mountDemidir = std::make_shared<SubdirFilesystem>(LocalFS,mountDemi);
SubdirFilesystem mountjohnslashjim(&lfs,mountJoelSlashJim,false); std::shared_ptr<SubdirFilesystem> mountjohnslashjim = std::make_shared<SubdirFilesystem>(LocalFS,mountJoelSlashJim);
MountableFilesystem fs(&rootdir,false); std::shared_ptr<MountableFilesystem> fs = std::make_shared<MountableFilesystem>(rootdir);
fs.Mount(std::string("/demi"), &mountDemidir,false); fs->Mount(std::string("/demi"), mountDemidir);
fs.Mount(std::string("/joel/jim"), &mountjohnslashjim,false); fs->Mount(std::string("/joel/jim"), mountjohnslashjim);
std::string command = argv[1]; std::string command = argv[1];
@@ -39,22 +38,22 @@ int main(int argc, char** argv)
std::string dir = "/"; std::string dir = "/";
if(argc > 2) dir = argv[2]; if(argc > 2) dir = argv[2];
for(auto item : fs.EnumeratePaths(dir)) for(auto item : fs->EnumeratePaths(dir))
{ {
std::cout << item.GetFileName() << std::endl; std::cout << item.GetFileName() << std::endl;
} }
} }
else if(command == "cat") else if(command == "cat")
{ {
FileStream strm(stdout, false,"wb",false); std::shared_ptr<FileStream> strm = std::make_shared<FileStream>(stdout, false,"wb",false);
for(int a = 2; a < argc; a++) for(int a = 2; a < argc; a++)
{ {
std::string path = argv[a]; std::string path = argv[a];
auto f = fs.OpenFile(path,"rb"); auto f = fs->OpenFile(path,"rb");
if(f != nullptr) if(f != nullptr)
{ {
f->CopyTo(strm); f->CopyTo(strm);
delete f;
} }
} }
} }

View File

@@ -25,7 +25,7 @@ class MyWebServer : public IHttpServer {
std::cout << ctx.path << std::endl; std::cout << ctx.path << std::endl;
if(ctx.path == "/") if(ctx.path == "/")
{ {
FileStream fs("index.html","rb"); std::shared_ptr<FileStream> fs = std::make_shared<FileStream>("index.html","rb");
ctx ctx
.WithMimeType("text/html") .WithMimeType("text/html")
@@ -34,7 +34,7 @@ class MyWebServer : public IHttpServer {
} }
else if(ctx.path == "/streaming.html") else if(ctx.path == "/streaming.html")
{ {
StreamWriter writer(ctx.OpenResponseStream(),true); StreamWriter writer(ctx.OpenResponseStream());
writer.WriteLine("<html>"); writer.WriteLine("<html>");
writer.WriteLine("<head><title>Streaming</title></head>"); writer.WriteLine("<head><title>Streaming</title></head>");
writer.WriteLine("<body>"); writer.WriteLine("<body>");
@@ -58,7 +58,7 @@ class MyWebServer : public IHttpServer {
else if(ctx.path == "/main.js") else if(ctx.path == "/main.js")
{ {
FileStream fs("main.js","rb"); std::shared_ptr<FileStream> fs = std::make_shared<FileStream>("main.js","rb");
ctx ctx
.WithMimeType("text/js") .WithMimeType("text/js")
@@ -67,8 +67,8 @@ class MyWebServer : public IHttpServer {
} }
else if(ctx.path == "/upload") else if(ctx.path == "/upload")
{ {
ctx.ParseFormData([](std::string mime, std::string filename, std::string name)->Tesses::Framework::Streams::Stream*{ ctx.ParseFormData([](std::string mime, std::string filename, std::string name)->std::shared_ptr<Tesses::Framework::Streams::Stream>{
return new FileStream(filename,"wb"); return std::make_shared<FileStream>(filename,"wb");
}); });
} }
else if(ctx.path == "/steve") else if(ctx.path == "/steve")
@@ -117,11 +117,11 @@ class MyOtherWebServer : public IHttpServer
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
TF_InitWithConsole(); TF_InitWithConsole();
MyOtherWebServer myo; std::shared_ptr<MyOtherWebServer> myo = std::make_shared<MyOtherWebServer>();
MyWebServer mws; std::shared_ptr<MyWebServer> mws = std::make_shared<MyWebServer>();
MountableServer mountable(myo); std::shared_ptr<MountableServer> mountable = std::make_shared<MountableServer>(myo);
mountable.Mount("/mymount/",mws); mountable->Mount("/mymount/",mws);
HttpServer server(10001,mountable); HttpServer server(10001,mountable);
server.StartAccepting(); server.StartAccepting();
TF_RunEventLoop(); TF_RunEventLoop();

View File

@@ -39,7 +39,7 @@ int main(int argc, char** argv)
{ {
Tesses::Framework::TF_Init(); Tesses::Framework::TF_Init();
HttpDictionary reqHeaders; HttpDictionary reqHeaders;
WebSocketConn conn; std::shared_ptr<WebSocketConn> conn = std::make_shared<WebSocketConn>();
WebSocketClient("ws://echo.websocket.org/",reqHeaders,conn); WebSocketClient("ws://echo.websocket.org/",reqHeaders,conn);
return 0; return 0;

View File

@@ -11,8 +11,8 @@ namespace Tesses::Framework::Crypto
public: public:
static std::string GetCertChain(); static std::string GetCertChain();
ClientTLSStream(Tesses::Framework::Streams::Stream* innerStream, bool owns, bool verify, std::string domain); ClientTLSStream(std::shared_ptr<Tesses::Framework::Streams::Stream> innerStream, bool verify, std::string domain);
ClientTLSStream(Tesses::Framework::Streams::Stream* innerStream, bool owns, bool verify, std::string domain, std::string cert); ClientTLSStream(std::shared_ptr<Tesses::Framework::Streams::Stream> innerStream, bool verify, std::string domain, std::string cert);
size_t Read(uint8_t* buff, size_t sz); size_t Read(uint8_t* buff, size_t sz);
size_t Write(const uint8_t* buff, size_t sz); size_t Write(const uint8_t* buff, size_t sz);
bool CanRead(); bool CanRead();

View File

@@ -11,13 +11,11 @@ namespace Tesses::Framework::Crypto
Sha1(); Sha1();
bool Start(); bool Start();
bool Update(const uint8_t* buffer, size_t sz); bool Update(const uint8_t* buffer, size_t sz);
bool Update(Tesses::Framework::Streams::Stream* strm); bool Update(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
bool Update(Tesses::Framework::Streams::Stream& strm); std::vector<uint8_t> Finish();
std::vector<uint8_t> Finish();
~Sha1(); ~Sha1();
static std::vector<uint8_t> ComputeHash(const uint8_t* buffer, size_t len); static std::vector<uint8_t> ComputeHash(const uint8_t* buffer, size_t len);
static std::vector<uint8_t> ComputeHash(Tesses::Framework::Streams::Stream* strm); static std::vector<uint8_t> ComputeHash(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
static std::vector<uint8_t> ComputeHash(Tesses::Framework::Streams::Stream& strm);
}; };
class Sha256 { class Sha256 {
void* inner; void* inner;
@@ -27,13 +25,11 @@ namespace Tesses::Framework::Crypto
bool Start(bool is224=false); bool Start(bool is224=false);
bool Is224(); bool Is224();
bool Update(const uint8_t* buffer, size_t sz); bool Update(const uint8_t* buffer, size_t sz);
bool Update(Tesses::Framework::Streams::Stream* strm); bool Update(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
bool Update(Tesses::Framework::Streams::Stream& strm);
std::vector<uint8_t> Finish(); std::vector<uint8_t> Finish();
~Sha256(); ~Sha256();
static std::vector<uint8_t> ComputeHash(const uint8_t* buffer, size_t len,bool is224=false); static std::vector<uint8_t> ComputeHash(const uint8_t* buffer, size_t len,bool is224=false);
static std::vector<uint8_t> ComputeHash(Tesses::Framework::Streams::Stream* strm,bool is224=false); static std::vector<uint8_t> ComputeHash(std::shared_ptr<Tesses::Framework::Streams::Stream> strm,bool is224=false);
static std::vector<uint8_t> ComputeHash(Tesses::Framework::Streams::Stream& strm,bool is224=false);
}; };
class Sha512 { class Sha512 {
@@ -44,14 +40,12 @@ namespace Tesses::Framework::Crypto
bool Start(bool is384=false); bool Start(bool is384=false);
bool Is384(); bool Is384();
bool Update(const uint8_t* buffer, size_t sz); bool Update(const uint8_t* buffer, size_t sz);
bool Update(Tesses::Framework::Streams::Stream* strm); bool Update(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
bool Update(Tesses::Framework::Streams::Stream& strm); std::vector<uint8_t> Finish();
std::vector<uint8_t> Finish();
~Sha512(); ~Sha512();
static std::vector<uint8_t> ComputeHash(const uint8_t* buffer, size_t len,bool is384=false); static std::vector<uint8_t> ComputeHash(const uint8_t* buffer, size_t len,bool is384=false);
static std::vector<uint8_t> ComputeHash(Tesses::Framework::Streams::Stream* strm,bool is384=false); static std::vector<uint8_t> ComputeHash(std::shared_ptr<Tesses::Framework::Streams::Stream> strm,bool is384=false);
static std::vector<uint8_t> ComputeHash(Tesses::Framework::Streams::Stream& strm,bool is384=false);
}; };
typedef enum { typedef enum {
VERSION_SHA1=1, VERSION_SHA1=1,

View File

@@ -8,7 +8,7 @@ namespace Tesses::Framework::Filesystem
{ {
public: public:
Tesses::Framework::Streams::Stream* OpenFile(VFSPath path, std::string mode); std::shared_ptr<Tesses::Framework::Streams::Stream> OpenFile(VFSPath path, std::string mode);
void CreateDirectory(VFSPath path); void CreateDirectory(VFSPath path);
void DeleteDirectory(VFSPath path); void DeleteDirectory(VFSPath path);
@@ -35,6 +35,11 @@ namespace Tesses::Framework::Filesystem
void GetDate(VFSPath path, Date::DateTime& lastWrite, Date::DateTime& lastAccess); void GetDate(VFSPath path, Date::DateTime& lastWrite, Date::DateTime& lastAccess);
void SetDate(VFSPath path, Date::DateTime lastWrite, Date::DateTime lastAccess); void SetDate(VFSPath path, Date::DateTime lastWrite, Date::DateTime lastAccess);
bool StatVFS(VFSPath path, StatVFSData& vfsData);
void Chmod(VFSPath path, uint32_t mode);
}; };
extern LocalFilesystem LocalFS; extern std::shared_ptr<LocalFilesystem> LocalFS;
} }

View File

@@ -73,7 +73,7 @@ namespace Tesses::Framework::Filesystem
MemoryEntry* GetEntry(VFSPath path,bool followSymlink); MemoryEntry* GetEntry(VFSPath path,bool followSymlink);
public: public:
MemoryFilesystem(); MemoryFilesystem();
Tesses::Framework::Streams::Stream* OpenFile(VFSPath path, std::string mode); std::shared_ptr<Tesses::Framework::Streams::Stream> OpenFile(VFSPath path, std::string mode);
void CreateDirectory(VFSPath path); void CreateDirectory(VFSPath path);
void DeleteDirectory(VFSPath path); void DeleteDirectory(VFSPath path);

View File

@@ -7,29 +7,28 @@ namespace Tesses::Framework::Filesystem
class MountableDirectory { class MountableDirectory {
public: public:
std::string name; std::string name;
VFS* vfs; std::shared_ptr<VFS> vfs;
bool owns; bool owns;
std::vector<MountableDirectory*> dirs; std::vector<MountableDirectory*> dirs;
void GetFS(VFSPath srcPath, VFSPath curDir, VFSPath& destRoot, VFSPath& destPath, VFS*& vfs); void GetFS(VFSPath srcPath, VFSPath curDir, VFSPath& destRoot, VFSPath& destPath, std::shared_ptr<VFS>& vfs);
~MountableDirectory(); ~MountableDirectory();
}; };
class MountableFilesystem : public VFS class MountableFilesystem : public VFS
{ {
bool owns; std::shared_ptr<VFS> root;
VFS* root;
std::vector<MountableDirectory*> directories; std::vector<MountableDirectory*> directories;
void GetFS(VFSPath srcPath, VFSPath& destRoot, VFSPath& destPath, VFS*& vfs); void GetFS(VFSPath srcPath, VFSPath& destRoot, VFSPath& destPath, std::shared_ptr<VFS>& vfs);
public: public:
MountableFilesystem(); MountableFilesystem();
MountableFilesystem(VFS* root, bool owns); MountableFilesystem(std::shared_ptr<VFS> root);
void Mount(VFSPath path, VFS* fs, bool owns); void Mount(VFSPath path, std::shared_ptr<VFS> vfs);
void Unmount(VFSPath path); void Unmount(VFSPath path);
Tesses::Framework::Streams::Stream* OpenFile(VFSPath path, std::string mode); std::shared_ptr<Tesses::Framework::Streams::Stream> OpenFile(VFSPath path, std::string mode);
void CreateDirectory(VFSPath path); void CreateDirectory(VFSPath path);
void DeleteDirectory(VFSPath path); void DeleteDirectory(VFSPath path);
bool SpecialFileExists(VFSPath path); bool SpecialFileExists(VFSPath path);
@@ -53,5 +52,10 @@ namespace Tesses::Framework::Filesystem
~MountableFilesystem(); ~MountableFilesystem();
void GetDate(VFSPath path, Date::DateTime& lastWrite, Date::DateTime& lastAccess); void GetDate(VFSPath path, Date::DateTime& lastWrite, Date::DateTime& lastAccess);
void SetDate(VFSPath path, Date::DateTime lastWrite, Date::DateTime lastAccess); void SetDate(VFSPath path, Date::DateTime lastWrite, Date::DateTime lastAccess);
bool StatVFS(VFSPath path, StatVFSData& vfsData);
void Chmod(VFSPath path, uint32_t mode);
}; };
} }

View File

@@ -7,7 +7,7 @@ namespace Tesses::Framework::Filesystem
class NullFilesystem : public VFS class NullFilesystem : public VFS
{ {
public: public:
Tesses::Framework::Streams::Stream* OpenFile(VFSPath path, std::string mode); std::shared_ptr<Tesses::Framework::Streams::Stream> OpenFile(VFSPath path, std::string mode);
void CreateDirectory(VFSPath path); void CreateDirectory(VFSPath path);
void DeleteDirectory(VFSPath path); void DeleteDirectory(VFSPath path);
bool RegularFileExists(VFSPath path); bool RegularFileExists(VFSPath path);

View File

@@ -6,14 +6,13 @@ namespace Tesses::Framework::Filesystem
{ {
class SubdirFilesystem : public VFS class SubdirFilesystem : public VFS
{ {
bool owns; std::shared_ptr<VFS> parent;
VFS* parent;
VFSPath path; VFSPath path;
VFSPath ToParent(VFSPath path); VFSPath ToParent(VFSPath path);
VFSPath FromParent(VFSPath path); VFSPath FromParent(VFSPath path);
public: public:
SubdirFilesystem(VFS* parent, VFSPath path, bool owns); SubdirFilesystem(std::shared_ptr<VFS> parent, VFSPath path);
Tesses::Framework::Streams::Stream* OpenFile(VFSPath path, std::string mode); std::shared_ptr<Tesses::Framework::Streams::Stream> OpenFile(VFSPath path, std::string mode);
void CreateDirectory(VFSPath path); void CreateDirectory(VFSPath path);
void DeleteDirectory(VFSPath path); void DeleteDirectory(VFSPath path);
bool SpecialFileExists(VFSPath path); bool SpecialFileExists(VFSPath path);
@@ -38,6 +37,9 @@ namespace Tesses::Framework::Filesystem
~SubdirFilesystem(); ~SubdirFilesystem();
void GetDate(VFSPath path, Date::DateTime& lastWrite, Date::DateTime& lastAccess); void GetDate(VFSPath path, Date::DateTime& lastWrite, Date::DateTime& lastAccess);
void SetDate(VFSPath path, Date::DateTime lastWrite, Date::DateTime lastAccess); void SetDate(VFSPath path, Date::DateTime lastWrite, Date::DateTime lastAccess);
bool StatVFS(VFSPath path, StatVFSData& vfsData);
void Chmod(VFSPath path, uint32_t mode);
}; };
} }

View File

@@ -8,6 +8,20 @@
namespace Tesses::Framework::Filesystem namespace Tesses::Framework::Filesystem
{ {
class StatVFSData {
public:
uint64_t BlockSize;
uint64_t FragmentSize;
uint64_t Blocks;
uint64_t BlocksFree;
uint64_t BlocksAvailable;
uint64_t TotalInodes;
uint64_t FreeInodes;
uint64_t AvailableInodes;
uint64_t Id;
uint64_t Flags;
uint64_t MaxNameLength;
};
class VFSPath { class VFSPath {
public: public:
static VFSPath CurrentDirectoryAsRelative(); static VFSPath CurrentDirectoryAsRelative();
@@ -107,7 +121,7 @@ namespace Tesses::Framework::Filesystem
class VFS { class VFS {
public: public:
virtual Tesses::Framework::Streams::Stream* OpenFile(VFSPath path, std::string mode)=0; virtual std::shared_ptr<Tesses::Framework::Streams::Stream> OpenFile(VFSPath path, std::string mode)=0;
virtual void CreateDirectory(VFSPath path)=0; virtual void CreateDirectory(VFSPath path)=0;
virtual void DeleteDirectory(VFSPath path)=0; virtual void DeleteDirectory(VFSPath path)=0;
virtual bool RegularFileExists(VFSPath path)=0; virtual bool RegularFileExists(VFSPath path)=0;
@@ -134,6 +148,10 @@ namespace Tesses::Framework::Filesystem
virtual void GetDate(VFSPath path, Date::DateTime& lastWrite, Date::DateTime& lastAccess); virtual void GetDate(VFSPath path, Date::DateTime& lastWrite, Date::DateTime& lastAccess);
virtual void SetDate(VFSPath path, Date::DateTime lastWrite, Date::DateTime lastAccess); virtual void SetDate(VFSPath path, Date::DateTime lastWrite, Date::DateTime lastAccess);
virtual bool StatVFS(VFSPath path, StatVFSData& data);
virtual void Chmod(VFSPath path, uint32_t mode);
virtual ~VFS(); virtual ~VFS();
}; };
} }

View File

@@ -6,8 +6,8 @@ namespace Tesses::Framework::Http
{ {
class FileServer : public IHttpServer class FileServer : public IHttpServer
{ {
Tesses::Framework::Filesystem::VFS* vfs; std::shared_ptr<Tesses::Framework::Filesystem::VFS> vfs;
bool ownsVFS;
bool SendFile(ServerContext& ctx,Tesses::Framework::Filesystem::VFSPath path); bool SendFile(ServerContext& ctx,Tesses::Framework::Filesystem::VFSPath path);
@@ -17,8 +17,8 @@ namespace Tesses::Framework::Http
std::vector<std::string> defaultNames; std::vector<std::string> defaultNames;
FileServer(std::filesystem::path path,bool allowListing,bool spa); FileServer(std::filesystem::path path,bool allowListing,bool spa);
FileServer(std::filesystem::path path,bool allowListing, bool spa, std::vector<std::string> defaultNames); FileServer(std::filesystem::path path,bool allowListing, bool spa, std::vector<std::string> defaultNames);
FileServer(Tesses::Framework::Filesystem::VFS* fs, bool owns, bool allowListing, bool spa); FileServer(std::shared_ptr<Tesses::Framework::Filesystem::VFS> fs, bool allowListing, bool spa);
FileServer(Tesses::Framework::Filesystem::VFS* fs, bool owns, bool allowListing, bool spa, std::vector<std::string> defaultNames); FileServer(std::shared_ptr<Tesses::Framework::Filesystem::VFS> fs, bool allowListing, bool spa, std::vector<std::string> defaultNames);
bool Handle(ServerContext& ctx); bool Handle(ServerContext& ctx);
~FileServer(); ~FileServer();
}; };

View File

@@ -10,18 +10,18 @@ namespace Tesses::Framework::Http
class HttpRequestBody { class HttpRequestBody {
public: public:
virtual void HandleHeaders(HttpDictionary& dict); virtual void HandleHeaders(HttpDictionary& dict);
virtual void Write(Tesses::Framework::Streams::Stream* strm)=0; virtual void Write(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)=0;
virtual ~HttpRequestBody(); virtual ~HttpRequestBody();
}; };
class StreamHttpRequestBody : public HttpRequestBody { class StreamHttpRequestBody : public HttpRequestBody {
Tesses::Framework::Streams::Stream* strm; std::shared_ptr<Tesses::Framework::Streams::Stream> strm;
bool owns;
std::string mimeType; std::string mimeType;
public: public:
StreamHttpRequestBody(Tesses::Framework::Streams::Stream* strm, bool owns, std::string mimeType); StreamHttpRequestBody(std::shared_ptr<Tesses::Framework::Streams::Stream> strm, std::string mimeType);
void HandleHeaders(HttpDictionary& dict); void HandleHeaders(HttpDictionary& dict);
void Write(Tesses::Framework::Streams::Stream* strm); void Write(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
~StreamHttpRequestBody(); ~StreamHttpRequestBody();
}; };
@@ -31,7 +31,7 @@ namespace Tesses::Framework::Http
public: public:
TextHttpRequestBody(std::string text, std::string mimeType); TextHttpRequestBody(std::string text, std::string mimeType);
void HandleHeaders(HttpDictionary& dict); void HandleHeaders(HttpDictionary& dict);
void Write(Tesses::Framework::Streams::Stream* strm); void Write(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
~TextHttpRequestBody(); ~TextHttpRequestBody();
}; };
@@ -49,52 +49,47 @@ namespace Tesses::Framework::Http
HttpDictionary requestHeaders; HttpDictionary requestHeaders;
HttpRequestBody* body; HttpRequestBody* body;
static Tesses::Framework::Streams::Stream* EstablishConnection(Uri uri,bool ignoreSSLErrors,std::string trusted_root_cert_bundle); static std::shared_ptr<Tesses::Framework::Streams::Stream> EstablishConnection(Uri uri,bool ignoreSSLErrors,std::string trusted_root_cert_bundle);
static Tesses::Framework::Streams::Stream* EstablishUnixPathConnection(std::string unixPath, Uri uri, bool ignoreSSLErrors, std::string trusted_root_cert_bundle); static std::shared_ptr<Tesses::Framework::Streams::Stream> EstablishUnixPathConnection(std::string unixPath, Uri uri, bool ignoreSSLErrors, std::string trusted_root_cert_bundle);
void SendRequest(Tesses::Framework::Streams::Stream* strm); void SendRequest(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
}; };
class HttpResponse { class HttpResponse {
private: private:
bool owns; bool owns;
Tesses::Framework::Streams::Stream* handleStrm; std::shared_ptr<Tesses::Framework::Streams::Stream> handleStrm;
public: public:
HttpResponse(Tesses::Framework::Streams::Stream* strm, bool owns); HttpResponse(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
HttpResponse(HttpRequest& request); HttpResponse(HttpRequest& request);
std::string version; std::string version;
StatusCode statusCode; StatusCode statusCode;
HttpDictionary responseHeaders; HttpDictionary responseHeaders;
std::string ReadAsString(); std::string ReadAsString();
Tesses::Framework::Streams::Stream* ReadAsStream(); std::shared_ptr<Tesses::Framework::Streams::Stream> ReadAsStream();
void CopyToStream(Tesses::Framework::Streams::Stream* strm); void CopyToStream(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
Tesses::Framework::Streams::Stream* GetInternalStream(); std::shared_ptr<Tesses::Framework::Streams::Stream> GetInternalStream();
~HttpResponse(); ~HttpResponse();
}; };
void DownloadToStreamSimple(std::string url, Tesses::Framework::Streams::Stream* strm); void DownloadToStreamSimple(std::string url, std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
void DownloadToStreamSimple(std::string url, Tesses::Framework::Streams::Stream& strm);
void DownloadToFileSimple(std::string url, std::shared_ptr<Tesses::Framework::Filesystem::VFS> vfs, Tesses::Framework::Filesystem::VFSPath path);
void DownloadToFileSimple(std::string url, Tesses::Framework::Filesystem::VFS* vfs, Tesses::Framework::Filesystem::VFSPath path);
void DownloadToFileSimple(std::string url, Tesses::Framework::Filesystem::VFS& vfs, Tesses::Framework::Filesystem::VFSPath path);
void DownloadToFileSimple(std::string url, Tesses::Framework::Filesystem::VFSPath path); void DownloadToFileSimple(std::string url, Tesses::Framework::Filesystem::VFSPath path);
std::string DownloadToStringSimple(std::string url); std::string DownloadToStringSimple(std::string url);
bool WebSocketClientSuccessDefault(HttpDictionary& dict,bool v); bool WebSocketClientSuccessDefault(HttpDictionary& dict,bool v);
void WebSocketClient(std::string url, HttpDictionary& requestHeaders, WebSocketConnection& wsc, std::function<bool(HttpDictionary&,bool)> cb=WebSocketClientSuccessDefault); void WebSocketClient(std::string url, HttpDictionary& requestHeaders, std::shared_ptr<WebSocketConnection> wsc, std::function<bool(HttpDictionary&,bool)> cb=WebSocketClientSuccessDefault);
void WebSocketClient(std::string url, HttpDictionary& requestHeaders, WebSocketConnection* wsc, std::function<bool(HttpDictionary&,bool)> cb=WebSocketClientSuccessDefault);
void DownloadUnixSocketToStreamSimple(std::string unixSocket,std::string url, Tesses::Framework::Streams::Stream* strm); void DownloadUnixSocketToStreamSimple(std::string unixSocket,std::string url, std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
void DownloadUnixSocketToStreamSimple(std::string unixSocket,std::string url, Tesses::Framework::Streams::Stream& strm);
void DownloadUnixSocketToFileSimple(std::string unixSocket,std::string url, Tesses::Framework::Filesystem::VFS* vfs, Tesses::Framework::Filesystem::VFSPath path); void DownloadUnixSocketToFileSimple(std::string unixSocket,std::string url, std::shared_ptr<Tesses::Framework::Filesystem::VFS> vfs, Tesses::Framework::Filesystem::VFSPath path);
void DownloadUnixSocketToFileSimple(std::string unixSocket,std::string url, Tesses::Framework::Filesystem::VFS& vfs, Tesses::Framework::Filesystem::VFSPath path);
void DownloadUnixSocketToFileSimple(std::string unixSocket,std::string url, Tesses::Framework::Filesystem::VFSPath path); void DownloadUnixSocketToFileSimple(std::string unixSocket,std::string url, Tesses::Framework::Filesystem::VFSPath path);
std::string DownloadUnixSocketToStringSimple(std::string unixSocket,std::string url); std::string DownloadUnixSocketToStringSimple(std::string unixSocket,std::string url);
void WebSocketUnixSocketClient(std::string unixSocket,std::string url, HttpDictionary& requestHeaders, WebSocketConnection& wsc, std::function<bool(HttpDictionary&,bool)> cb=WebSocketClientSuccessDefault); void WebSocketUnixSocketClient(std::string unixSocket,std::string url, HttpDictionary& requestHeaders, std::shared_ptr<WebSocketConnection> wsc, std::function<bool(HttpDictionary&,bool)> cb=WebSocketClientSuccessDefault);
void WebSocketUnixSocketClient(std::string unixSocket,std::string url,HttpDictionary& requestHeaders, WebSocketConnection* wsc, std::function<bool(HttpDictionary&,bool)> cb=WebSocketClientSuccessDefault);
} }

View File

@@ -17,7 +17,7 @@ namespace Tesses::Framework::Http
class ServerContext { class ServerContext {
bool sent; bool sent;
Tesses::Framework::Streams::Stream* strm; std::shared_ptr<Tesses::Framework::Streams::Stream> strm;
std::map<std::string,ServerContextData*> data; std::map<std::string,ServerContextData*> data;
public: public:
HttpDictionary requestHeaders; HttpDictionary requestHeaders;
@@ -31,27 +31,25 @@ namespace Tesses::Framework::Http
uint16_t port; uint16_t port;
std::string version; std::string version;
bool encrypted; bool encrypted;
ServerContext(Tesses::Framework::Streams::Stream* strm); ServerContext(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
~ServerContext(); ~ServerContext();
Tesses::Framework::Streams::Stream& GetStream(); std::shared_ptr<Tesses::Framework::Streams::Stream> GetStream();
std::string GetOriginalPathWithQuery(); std::string GetOriginalPathWithQuery();
std::string GetUrlWithQuery(); std::string GetUrlWithQuery();
bool Sent(); bool Sent();
bool NeedToParseFormData(); bool NeedToParseFormData();
void ParseFormData(std::function<Tesses::Framework::Streams::Stream*(std::string mime, std::string filename, std::string name)> cb); void ParseFormData(std::function<std::shared_ptr<Tesses::Framework::Streams::Stream>(std::string mime, std::string filename, std::string name)> cb);
void ReadStream(Tesses::Framework::Streams::Stream& strm); void ReadStream(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
void ReadStream(Tesses::Framework::Streams::Stream* strm);
std::string ReadString(); std::string ReadString();
void SendBytes(std::vector<uint8_t> buffer); void SendBytes(std::vector<uint8_t> buffer);
void SendText(std::string text); void SendText(std::string text);
void SendStream(Tesses::Framework::Streams::Stream& strm); void SendStream(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
void SendStream(Tesses::Framework::Streams::Stream* strm);
void SendErrorPage(bool showPath); void SendErrorPage(bool showPath);
void SendNotFound(); void SendNotFound();
void SendBadRequest(); void SendBadRequest();
void SendException(std::exception& ex); void SendException(std::exception& ex);
Tesses::Framework::Streams::Stream* OpenResponseStream(); std::shared_ptr<Tesses::Framework::Streams::Stream> OpenResponseStream();
Tesses::Framework::Streams::Stream* OpenRequestStream(); std::shared_ptr<Tesses::Framework::Streams::Stream> OpenRequestStream();
ServerContext& WithLastModified(Date::DateTime time); ServerContext& WithLastModified(Date::DateTime time);
ServerContext& WithHeader(std::string key, std::string value); ServerContext& WithHeader(std::string key, std::string value);
ServerContext& WithSingleHeader(std::string key, std::string value); ServerContext& WithSingleHeader(std::string key, std::string value);
@@ -59,7 +57,7 @@ namespace Tesses::Framework::Http
ServerContext& WithContentDisposition(std::string filename, bool isInline); ServerContext& WithContentDisposition(std::string filename, bool isInline);
ServerContext& WriteHeaders(); ServerContext& WriteHeaders();
void StartWebSocketSession(std::function<void(std::function<void(WebSocketMessage&)>,std::function<void()>,std::function<void()>)> onOpen, std::function<void(WebSocketMessage&)> onReceive, std::function<void(bool)> onClose); void StartWebSocketSession(std::function<void(std::function<void(WebSocketMessage&)>,std::function<void()>,std::function<void()>)> onOpen, std::function<void(WebSocketMessage&)> onReceive, std::function<void(bool)> onClose);
void StartWebSocketSession(WebSocketConnection& connection); void StartWebSocketSession(std::shared_ptr<WebSocketConnection> connection);
template<class T> template<class T>
T* GetServerContentData(std::string tag) T* GetServerContentData(std::string tag)
@@ -81,27 +79,20 @@ namespace Tesses::Framework::Http
}; };
class HttpServer { class HttpServer {
Tesses::Framework::Streams::TcpServer* server; std::shared_ptr<Tesses::Framework::Streams::TcpServer> server;
IHttpServer* http; std::shared_ptr<IHttpServer> http;
Tesses::Framework::Threading::Thread* thrd; Tesses::Framework::Threading::Thread* thrd;
bool ownsTCP;
bool ownsHttp;
bool showIPs; bool showIPs;
bool showARTL; bool showARTL;
public: public:
HttpServer(Tesses::Framework::Streams::TcpServer& tcpServer, IHttpServer& http, bool showIPs=true); HttpServer(std::shared_ptr<Tesses::Framework::Streams::TcpServer> tcpServer, std::shared_ptr<IHttpServer> http, bool showIPs=true);
HttpServer(Tesses::Framework::Streams::TcpServer* tcpServer, bool ownsTCP, IHttpServer& http, bool showIPs=true); HttpServer(uint16_t port, std::shared_ptr<IHttpServer> http, bool showIPs=true);
HttpServer(Tesses::Framework::Streams::TcpServer& tcpServer, IHttpServer* http, bool ownsHttpServer, bool showIPs=true); HttpServer(std::string unixPath, std::shared_ptr<IHttpServer> http);
HttpServer(Tesses::Framework::Streams::TcpServer* tcpServer, bool ownsTCP, IHttpServer* http, bool ownsHttpServer, bool showIPs=true);
HttpServer(uint16_t port, IHttpServer& http, bool showIPs=true);
HttpServer(uint16_t port, IHttpServer* http, bool owns, bool showIPs=true);
HttpServer(std::string unixPath, IHttpServer& http);
HttpServer(std::string unixPath, IHttpServer* http, bool owns);
uint16_t GetPort(); uint16_t GetPort();
void StartAccepting(); void StartAccepting();
static void Process(Tesses::Framework::Streams::Stream& strm, IHttpServer& server, std::string ip, uint16_t port, bool encrypted); static void Process(std::shared_ptr<Tesses::Framework::Streams::Stream> strm, std::shared_ptr<IHttpServer> server, std::string ip, uint16_t port, bool encrypted);
~HttpServer(); ~HttpServer();
}; };
} }

View File

@@ -4,22 +4,20 @@
namespace Tesses::Framework::Http namespace Tesses::Framework::Http
{ {
class HttpStream : public Tesses::Framework::Streams::Stream { class HttpStream : public Tesses::Framework::Streams::Stream {
Tesses::Framework::Streams::Stream* strm; std::shared_ptr<Tesses::Framework::Streams::Stream> strm;
size_t offset; size_t offset;
size_t read; size_t read;
int64_t length; int64_t length;
int64_t position; int64_t position;
bool owns;
bool recv; bool recv;
bool http1_1; bool http1_1;
bool done; bool done;
public: public:
HttpStream(Tesses::Framework::Streams::Stream* strm, bool owns, int64_t length, bool recv, bool http1_1); HttpStream(std::shared_ptr<Tesses::Framework::Streams::Stream> strm, int64_t length, bool recv, bool http1_1);
HttpStream(Tesses::Framework::Streams::Stream& strm, int64_t length, bool recv,bool http1_1);
bool CanRead(); bool CanRead();
bool CanWrite(); bool CanWrite();
bool EndOfStream(); bool EndOfStream();

View File

@@ -7,17 +7,14 @@ namespace Tesses::Framework::Http
{ {
class MountableServer : public IHttpServer class MountableServer : public IHttpServer
{ {
IHttpServer* root; std::shared_ptr<IHttpServer> root;
bool owns; std::vector<std::pair<std::string,std::shared_ptr<IHttpServer>>> servers;
std::vector<std::pair<std::string,std::pair<bool,IHttpServer*>>> servers;
std::string Subpath(Filesystem::VFSPath fullPath, Filesystem::VFSPath offsetPath); std::string Subpath(Filesystem::VFSPath fullPath, Filesystem::VFSPath offsetPath);
bool StartsWith(Filesystem::VFSPath fullPath, Filesystem::VFSPath offsetPath); bool StartsWith(Filesystem::VFSPath fullPath, Filesystem::VFSPath offsetPath);
public: public:
MountableServer(); MountableServer();
MountableServer(IHttpServer* root, bool owns); MountableServer(std::shared_ptr<IHttpServer> root);
MountableServer(IHttpServer& root); void Mount(std::string path, std::shared_ptr<IHttpServer> server);
void Mount(std::string path, IHttpServer* server, bool owns);
void Mount(std::string path, IHttpServer& server);
void Unmount(std::string path); void Unmount(std::string path);
bool Handle(ServerContext& ctx); bool Handle(ServerContext& ctx);
~MountableServer(); ~MountableServer();

View File

@@ -6,7 +6,7 @@ class SMTPBody
{ {
public: public:
std::string mimeType; std::string mimeType;
virtual void Write(Tesses::Framework::Streams::Stream* strm)=0; virtual void Write(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)=0;
virtual ~SMTPBody(); virtual ~SMTPBody();
}; };
@@ -16,27 +16,25 @@ class SMTPStringBody : public SMTPBody
SMTPStringBody(); SMTPStringBody();
SMTPStringBody(std::string text, std::string mimeType); SMTPStringBody(std::string text, std::string mimeType);
std::string text; std::string text;
void Write(Tesses::Framework::Streams::Stream* strm); void Write(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
}; };
class SMTPStreamBody : public SMTPBody class SMTPStreamBody : public SMTPBody
{ {
Tesses::Framework::Streams::Stream* stream; std::shared_ptr<Tesses::Framework::Streams::Stream> stream;
bool owns;
public: public:
SMTPStreamBody(std::string mimeType,Tesses::Framework::Streams::Stream& stream); SMTPStreamBody(std::string mimeType,std::shared_ptr<Tesses::Framework::Streams::Stream> stream);
SMTPStreamBody(std::string mimeType,Tesses::Framework::Streams::Stream* stream, bool owns); void Write(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
void Write(Tesses::Framework::Streams::Stream* strm);
~SMTPStreamBody(); ~SMTPStreamBody();
}; };
class SMTPClient { class SMTPClient {
Tesses::Framework::Streams::Stream* strm; std::shared_ptr<Tesses::Framework::Streams::Stream> strm;
bool owns;
public: public:
SMTPClient(Tesses::Framework::Streams::Stream* stream,bool owns=true); SMTPClient(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
SMTPClient(Tesses::Framework::Streams::Stream& strm);
std::string domain; std::string domain;
std::string username; std::string username;
std::string password; std::string password;
@@ -44,8 +42,8 @@ class SMTPClient {
std::string from_name; std::string from_name;
std::string to; std::string to;
std::string subject; std::string subject;
SMTPBody* body; std::shared_ptr<SMTPBody> body;
std::vector<std::pair<std::string,SMTPBody*>> attachments; std::vector<std::pair<std::string,std::shared_ptr<SMTPBody>>> attachments;
void Send(); void Send();
~SMTPClient(); ~SMTPClient();
}; };

View File

@@ -27,14 +27,11 @@ class Process {
void CloseStdInNow(); void CloseStdInNow();
//YOU ARE RESPONSABLE FOR FREEING THIS STREAM OBJECT
std::shared_ptr<Tesses::Framework::Streams::Stream> GetStdinStream();
Tesses::Framework::Streams::Stream* GetStdinStream(); std::shared_ptr<Tesses::Framework::Streams::Stream> GetStdoutStream();
std::shared_ptr<Tesses::Framework::Streams::Stream> GetStderrStream();
//YOU ARE RESPONSABLE FOR FREEING THIS STREAM OBJECT
Tesses::Framework::Streams::Stream* GetStdoutStream();
//YOU ARE RESPONSABLE FOR FREEING THIS STREAM OBJECT
Tesses::Framework::Streams::Stream* GetStderrStream();
Process(); Process();
Process(std::string name, std::vector<std::string> args,bool includeThisEnv=true); Process(std::string name, std::vector<std::string> args,bool includeThisEnv=true);

View File

@@ -6,15 +6,13 @@ namespace Tesses::Framework::Streams
class BufferedStream : public Stream class BufferedStream : public Stream
{ {
private: private:
Stream* strm; std::shared_ptr<Stream> strm;
bool owns;
uint8_t* buffer; uint8_t* buffer;
size_t bufferSize; size_t bufferSize;
size_t offset; size_t offset;
size_t read; size_t read;
public: public:
BufferedStream(Stream* strm, bool owns, size_t bufferSize=1024); BufferedStream(std::shared_ptr<Stream> strm, size_t bufferSize=1024);
BufferedStream(Stream& strm, size_t bufferSize=1024);
bool EndOfStream(); bool EndOfStream();
bool CanRead(); bool CanRead();
bool CanWrite(); bool CanWrite();

View File

@@ -4,12 +4,10 @@
namespace Tesses::Framework::Streams namespace Tesses::Framework::Streams
{ {
class ByteReader { class ByteReader {
Stream* strm; std::shared_ptr<Stream> strm;
bool owns;
public: public:
Stream* GetStream(); std::shared_ptr<Stream> GetStream();
ByteReader(Stream* strm, bool owns); ByteReader(std::shared_ptr<Stream> strm);
ByteReader(Stream& strm);
uint8_t ReadU8(); uint8_t ReadU8();
uint16_t ReadU16BE(); uint16_t ReadU16BE();
uint16_t ReadU16LE(); uint16_t ReadU16LE();
@@ -28,6 +26,5 @@ namespace Tesses::Framework::Streams
float ReadF32LE(); float ReadF32LE();
double ReadF64BE(); double ReadF64BE();
double ReadF64LE(); double ReadF64LE();
~ByteReader();
}; };
} }

View File

@@ -4,12 +4,11 @@
namespace Tesses::Framework::Streams namespace Tesses::Framework::Streams
{ {
class ByteWriter { class ByteWriter {
Stream* strm; std::shared_ptr<Stream> strm;
bool owns;
public: public:
Stream* GetStream(); std::shared_ptr<Stream> GetStream();
ByteWriter(Stream* strm, bool owns); ByteWriter(std::shared_ptr<Stream> strm);
ByteWriter(Stream& strm);
void WriteU8(uint8_t v); void WriteU8(uint8_t v);
void WriteU16BE(uint16_t v); void WriteU16BE(uint16_t v);
void WriteU16LE(uint16_t v); void WriteU16LE(uint16_t v);
@@ -28,6 +27,5 @@ namespace Tesses::Framework::Streams
void WriteF32LE(float v); void WriteF32LE(float v);
void WriteF64BE(double v); void WriteF64BE(double v);
void WriteF64LE(double v); void WriteF64LE(double v);
~ByteWriter();
}; };
} }

View File

@@ -15,7 +15,7 @@ namespace Tesses::Framework::Streams
TcpServer(uint16_t port, int32_t backlog); TcpServer(uint16_t port, int32_t backlog);
TcpServer(std::string ip, uint16_t port, int32_t backlog); TcpServer(std::string ip, uint16_t port, int32_t backlog);
TcpServer(std::string unixPath,int32_t backlog); TcpServer(std::string unixPath,int32_t backlog);
NetworkStream* GetStream(std::string& ip, uint16_t& port); std::shared_ptr<NetworkStream> GetStream(std::string& ip, uint16_t& port);
uint16_t GetPort(); uint16_t GetPort();
~TcpServer(); ~TcpServer();
bool IsValid(); bool IsValid();
@@ -45,7 +45,7 @@ namespace Tesses::Framework::Streams
void Listen(int32_t backlog); void Listen(int32_t backlog);
void Bind(std::string ip, uint16_t port); void Bind(std::string ip, uint16_t port);
void SetBroadcast(bool bC); void SetBroadcast(bool bC);
NetworkStream* Accept(std::string& ip, uint16_t& port); std::shared_ptr<NetworkStream> Accept(std::string& ip, uint16_t& port);
size_t Read(uint8_t* buff, size_t sz); size_t Read(uint8_t* buff, size_t sz);
size_t Write(const uint8_t* buff, size_t sz); size_t Write(const uint8_t* buff, size_t sz);
size_t ReadFrom(uint8_t* buff, size_t sz, std::string& ip, uint16_t& port); size_t ReadFrom(uint8_t* buff, size_t sz, std::string& ip, uint16_t& port);

View File

@@ -23,8 +23,7 @@ namespace Tesses::Framework::Streams
virtual int64_t GetLength(); virtual int64_t GetLength();
virtual void Flush(); virtual void Flush();
virtual void Seek(int64_t pos, SeekOrigin whence); virtual void Seek(int64_t pos, SeekOrigin whence);
void CopyTo(Stream* strm, size_t buffSize=1024); void CopyTo(std::shared_ptr<Stream> strm, size_t buffSize=1024);
void CopyTo(Stream& strm, size_t buffSize=1024);
virtual ~Stream(); virtual ~Stream();
}; };
} }

View File

@@ -1,77 +0,0 @@
#pragma once
#if defined(__cplusplus)
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
typedef void string_t;
typedef void tf_vfs_t;
typedef void tf_stream_t;
typedef void tf_thread_t;
typedef void tf_mutex_t;
typedef void tf_vfs_dir_t;
typedef void (*tf_action_user_data_t)(void* ptr);
typedef enum {
TF_SEEK_BEGIN,
TF_SEEK_CURRENT,
TF_SEEK_END
} TF_WHENCE;
string_t* string_create();
string_t* string_create_from_buff(const void* text, size_t len);
string_t* string_create_from_charpointer(const char* text);
string_t* string_resize(string_t* str, size_t len);
string_t* string_set_char(string_t* str, size_t index, char c);
char string_get_char(string_t* str,size_t index);
string_t* string_append_char(string_t* str, char c);
string_t* string_append_from_buff(string_t* str,const void* text, size_t len);
string_t* string_append_from_charpointer(string_t* str,const char* text);
string_t* string_append(string_t* str, string_t* toAppend);
string_t* string_append_signed(string_t* str, int64_t num);
string_t* string_append_unsigned(string_t* str, uint64_t num);
string_t* string_append_double(string_t* str, double num);
void string_print(string_t* str);
void string_println(string_t* str);
size_t string_size(string_t* str);
const char* string_c_str(string_t* str);
void string_free(string_t* str);
void tf_init();
tf_thread_t* tf_create_thread(void* userData, tf_action_user_data_t cb);
void tf_join_thread(tf_thread_t* thrd);
void tf_detach_thread(tf_thread_t* thrd);
tf_mutex_t* tf_mutex_create();
void tf_mutex_lock(tf_mutex_t* mtx);
bool tf_mutex_trylock(tf_mutex_t* mtx);
void tf_mutex_unlock(tf_mutex_t* mtx);
void tf_mutex_free(tf_mutex_t* mtx);
bool tf_stream_canread(tf_stream_t* strm);
bool tf_stream_canwrite(tf_stream_t* strm);
bool tf_stream_canseek(tf_stream_t* strm);
bool tf_stream_eof(tf_stream_t* strm);
int64_t tf_stream_getlen(tf_stream_t* strm);
int64_t tf_stream_getpos(tf_stream_t* strm);
void tf_stream_seek(tf_stream_t* strm, int64_t pos, TF_WHENCE whence);
size_t tf_stream_read(tf_stream_t* strm, uint8_t* buffer, size_t length);
size_t tf_stream_write(tf_stream_t* strm, const uint8_t* buffer, size_t length);
size_t tf_stream_readblock(tf_stream_t* strm, uint8_t* buffer, size_t length);
void tf_stream_writeblock(tf_stream_t* strm, const uint8_t* buffer, size_t length);
void tf_stream_copyto(tf_stream_t* src, tf_stream_t* dest, size_t blockSize);
void tf_stream_close(tf_stream_t* strm);
void tf_stream_flush(tf_stream_t* strm);
int32_t tf_stream_readbyte(tf_stream_t* strm);
void tf_stream_writebyte(tf_stream_t* strm, uint8_t val);
tf_stream_t* tf_stream_fopen(const char* file, const char* mode);
#if defined(__cplusplus)
}
#endif

View File

@@ -3,9 +3,9 @@
#include "../TextStreams/StringWriter.hpp" #include "../TextStreams/StringWriter.hpp"
namespace Tesses::Framework::Text { namespace Tesses::Framework::Text {
void GenerateCHeaderFile(Streams::Stream* strm,std::string name, TextStreams::TextWriter* writer); void GenerateCHeaderFile(std::shared_ptr<Streams::Stream> strm,std::string name, std::shared_ptr<TextStreams::TextWriter> writer);
std::string GenerateCHeaderFile(Streams::Stream* strm,std::string name); std::string GenerateCHeaderFile(std::shared_ptr<Streams::Stream> strm,std::string name);
void GenerateCHeaderFile(const std::vector<uint8_t>& data,std::string name, TextStreams::TextWriter* writer); void GenerateCHeaderFile(const std::vector<uint8_t>& data,std::string name, std::shared_ptr<TextStreams::TextWriter> writer);
std::string GenerateCHeaderFile(const std::vector<uint8_t>& data,std::string name); std::string GenerateCHeaderFile(const std::vector<uint8_t>& data,std::string name);
} }

View File

@@ -6,12 +6,11 @@ namespace Tesses::Framework::TextStreams
class StreamReader : public TextReader class StreamReader : public TextReader
{ {
private: private:
Tesses::Framework::Streams::Stream* strm; std::shared_ptr<Tesses::Framework::Streams::Stream> strm;
bool owns; bool owns;
public: public:
Tesses::Framework::Streams::Stream& GetStream(); std::shared_ptr<Tesses::Framework::Streams::Stream> GetStream();
StreamReader(Tesses::Framework::Streams::Stream& strm); StreamReader(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
StreamReader(Tesses::Framework::Streams::Stream* strm, bool owns);
StreamReader(std::filesystem::path filename); StreamReader(std::filesystem::path filename);
bool ReadBlock(std::string& str,size_t sz); bool ReadBlock(std::string& str,size_t sz);
bool Rewind(); bool Rewind();

View File

@@ -6,12 +6,10 @@ namespace Tesses::Framework::TextStreams
{ {
class StreamWriter : public TextWriter { class StreamWriter : public TextWriter {
private: private:
Tesses::Framework::Streams::Stream* strm; std::shared_ptr<Tesses::Framework::Streams::Stream> strm;
bool owns;
public: public:
Tesses::Framework::Streams::Stream& GetStream(); std::shared_ptr<Tesses::Framework::Streams::Stream> GetStream();
StreamWriter(Tesses::Framework::Streams::Stream& strm); StreamWriter(std::shared_ptr<Tesses::Framework::Streams::Stream> strm);
StreamWriter(Tesses::Framework::Streams::Stream* strm, bool owns);
StreamWriter(std::filesystem::path filename, bool append=false); StreamWriter(std::filesystem::path filename, bool append=false);
void WriteData(const char* text, size_t len); void WriteData(const char* text, size_t len);
~StreamWriter(); ~StreamWriter();

View File

@@ -25,9 +25,8 @@ namespace Tesses::Framework::Crypto
class ClientTLSPrivateData { class ClientTLSPrivateData {
public: public:
bool eos; bool eos;
bool owns;
bool success; bool success;
Stream* strm; std::shared_ptr<Stream> strm;
mbedtls_entropy_context entropy; mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg; mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_ssl_context ssl; mbedtls_ssl_context ssl;
@@ -40,7 +39,6 @@ namespace Tesses::Framework::Crypto
mbedtls_entropy_free(&entropy); mbedtls_entropy_free(&entropy);
mbedtls_ssl_config_free(&conf); mbedtls_ssl_config_free(&conf);
mbedtls_ssl_free(&ssl); mbedtls_ssl_free(&ssl);
if(this->owns) delete strm;
} }
}; };
#endif #endif
@@ -59,12 +57,12 @@ namespace Tesses::Framework::Crypto
return ""; return "";
} }
ClientTLSStream::ClientTLSStream(Tesses::Framework::Streams::Stream* innerStream, bool owns, bool verify, std::string domain) : ClientTLSStream(innerStream,owns,verify,domain,"") ClientTLSStream::ClientTLSStream(std::shared_ptr<Tesses::Framework::Streams::Stream> innerStream, bool verify, std::string domain) : ClientTLSStream(innerStream,verify,domain,"")
{ {
} }
ClientTLSStream::ClientTLSStream(Tesses::Framework::Streams::Stream* innerStream, bool owns, bool verify, std::string domain, std::string cert) ClientTLSStream::ClientTLSStream(std::shared_ptr<Tesses::Framework::Streams::Stream> innerStream, bool verify, std::string domain, std::string cert)
{ {
#if defined(TESSESFRAMEWORK_ENABLE_MBED) #if defined(TESSESFRAMEWORK_ENABLE_MBED)
if(cert.empty()) if(cert.empty())
@@ -77,7 +75,7 @@ namespace Tesses::Framework::Crypto
data->eos=false; data->eos=false;
data->success=false; data->success=false;
data->strm = innerStream; data->strm = innerStream;
data->owns = owns;
mbedtls_ssl_init(&data->ssl); mbedtls_ssl_init(&data->ssl);
mbedtls_ssl_config_init(&data->conf); mbedtls_ssl_config_init(&data->conf);

View File

@@ -83,7 +83,7 @@ namespace Tesses::Framework::Crypto
#endif #endif
return false; return false;
} }
bool Sha1::Update(Tesses::Framework::Streams::Stream* strm) bool Sha1::Update(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{ {
#if defined(TESSESFRAMEWORK_ENABLE_MBED) #if defined(TESSESFRAMEWORK_ENABLE_MBED)
if(strm == nullptr) return false; if(strm == nullptr) return false;
@@ -97,10 +97,7 @@ namespace Tesses::Framework::Crypto
#endif #endif
return false; return false;
} }
bool Sha1::Update(Tesses::Framework::Streams::Stream& strm)
{
return Update(&strm);
}
std::vector<uint8_t> Sha1::Finish() std::vector<uint8_t> Sha1::Finish()
{ {
#if defined(TESSESFRAMEWORK_ENABLE_MBED) #if defined(TESSESFRAMEWORK_ENABLE_MBED)
@@ -127,20 +124,14 @@ namespace Tesses::Framework::Crypto
if(!sha1.Update(buffer,len)) return {}; if(!sha1.Update(buffer,len)) return {};
return sha1.Finish(); return sha1.Finish();
} }
std::vector<uint8_t> Sha1::ComputeHash(Tesses::Framework::Streams::Stream* strm) std::vector<uint8_t> Sha1::ComputeHash(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{
Sha1 sha1;
if(!sha1.Start()) return {};
if(!sha1.Update(strm)) return {};
return sha1.Finish();
}
std::vector<uint8_t> Sha1::ComputeHash(Tesses::Framework::Streams::Stream& strm)
{ {
Sha1 sha1; Sha1 sha1;
if(!sha1.Start()) return {}; if(!sha1.Start()) return {};
if(!sha1.Update(strm)) return {}; if(!sha1.Update(strm)) return {};
return sha1.Finish(); return sha1.Finish();
} }
Sha256::Sha256() Sha256::Sha256()
{ {
@@ -175,7 +166,7 @@ namespace Tesses::Framework::Crypto
#endif #endif
return false; return false;
} }
bool Sha256::Update(Tesses::Framework::Streams::Stream* strm) bool Sha256::Update(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{ {
#if defined(TESSESFRAMEWORK_ENABLE_MBED) #if defined(TESSESFRAMEWORK_ENABLE_MBED)
if(strm == nullptr) return false; if(strm == nullptr) return false;
@@ -189,10 +180,7 @@ namespace Tesses::Framework::Crypto
#endif #endif
return false; return false;
} }
bool Sha256::Update(Tesses::Framework::Streams::Stream& strm)
{
return Update(&strm);
}
std::vector<uint8_t> Sha256::Finish() std::vector<uint8_t> Sha256::Finish()
{ {
#if defined(TESSESFRAMEWORK_ENABLE_MBED) #if defined(TESSESFRAMEWORK_ENABLE_MBED)
@@ -219,14 +207,7 @@ namespace Tesses::Framework::Crypto
if(!sha256.Update(buffer,len)) return {}; if(!sha256.Update(buffer,len)) return {};
return sha256.Finish(); return sha256.Finish();
} }
std::vector<uint8_t> Sha256::ComputeHash(Tesses::Framework::Streams::Stream* strm,bool is224) std::vector<uint8_t> Sha256::ComputeHash(std::shared_ptr<Tesses::Framework::Streams::Stream> strm,bool is224)
{
Sha256 sha256;
if(!sha256.Start(is224)) return {};
if(!sha256.Update(strm)) return {};
return sha256.Finish();
}
std::vector<uint8_t> Sha256::ComputeHash(Tesses::Framework::Streams::Stream& strm,bool is224)
{ {
Sha256 sha256; Sha256 sha256;
if(!sha256.Start(is224)) return {}; if(!sha256.Start(is224)) return {};
@@ -234,6 +215,7 @@ namespace Tesses::Framework::Crypto
return sha256.Finish(); return sha256.Finish();
} }
Sha512::Sha512() Sha512::Sha512()
{ {
#if defined(TESSESFRAMEWORK_ENABLE_MBED) #if defined(TESSESFRAMEWORK_ENABLE_MBED)
@@ -265,7 +247,7 @@ namespace Tesses::Framework::Crypto
#endif #endif
return false; return false;
} }
bool Sha512::Update(Tesses::Framework::Streams::Stream* strm) bool Sha512::Update(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{ {
#if defined(TESSESFRAMEWORK_ENABLE_MBED) #if defined(TESSESFRAMEWORK_ENABLE_MBED)
if(strm == nullptr) return false; if(strm == nullptr) return false;
@@ -279,10 +261,7 @@ namespace Tesses::Framework::Crypto
#endif #endif
return false; return false;
} }
bool Sha512::Update(Tesses::Framework::Streams::Stream& strm)
{
return Update(&strm);
}
std::vector<uint8_t> Sha512::Finish() std::vector<uint8_t> Sha512::Finish()
{ {
#if defined(TESSESFRAMEWORK_ENABLE_MBED) #if defined(TESSESFRAMEWORK_ENABLE_MBED)
@@ -310,20 +289,14 @@ namespace Tesses::Framework::Crypto
if(!sha512.Update(buffer,len)) return {}; if(!sha512.Update(buffer,len)) return {};
return sha512.Finish(); return sha512.Finish();
} }
std::vector<uint8_t> Sha512::ComputeHash(Tesses::Framework::Streams::Stream* strm,bool is384) std::vector<uint8_t> Sha512::ComputeHash(std::shared_ptr<Tesses::Framework::Streams::Stream> strm,bool is384)
{
Sha512 sha512;
if(!sha512.Start(is384)) return {};
if(!sha512.Update(strm)) return {};
return sha512.Finish();
}
std::vector<uint8_t> Sha512::ComputeHash(Tesses::Framework::Streams::Stream& strm,bool is384)
{ {
Sha512 sha512; Sha512 sha512;
if(!sha512.Start(is384)) return {}; if(!sha512.Start(is384)) return {};
if(!sha512.Update(strm)) return {}; if(!sha512.Update(strm)) return {};
return sha512.Finish(); return sha512.Finish();
} }
bool PBKDF2(std::vector<uint8_t>& output,std::string pass, std::vector<uint8_t>& salt, long itterations, ShaVersion version) bool PBKDF2(std::vector<uint8_t>& output,std::string pass, std::vector<uint8_t>& salt, long itterations, ShaVersion version)

View File

@@ -8,6 +8,7 @@
#undef min #undef min
#else #else
#include <utime.h> #include <utime.h>
#include <sys/statvfs.h>
#endif #endif
namespace Tesses::Framework::Filesystem namespace Tesses::Framework::Filesystem
{ {
@@ -71,9 +72,9 @@ namespace Tesses::Framework::Filesystem
auto res = std::filesystem::read_symlink(this->VFSPathToSystem(path)).string(); auto res = std::filesystem::read_symlink(this->VFSPathToSystem(path)).string();
return this->SystemToVFSPath(res.c_str()); return this->SystemToVFSPath(res.c_str());
} }
Tesses::Framework::Streams::Stream* LocalFilesystem::OpenFile(VFSPath path, std::string mode) std::shared_ptr<Tesses::Framework::Streams::Stream> LocalFilesystem::OpenFile(VFSPath path, std::string mode)
{ {
return new Tesses::Framework::Streams::FileStream(VFSPathToSystem(path), mode); return std::make_shared<Tesses::Framework::Streams::FileStream>(VFSPathToSystem(path), mode);
} }
void LocalFilesystem::DeleteDirectory(VFSPath path) void LocalFilesystem::DeleteDirectory(VFSPath path)
@@ -191,7 +192,45 @@ namespace Tesses::Framework::Filesystem
delete dir; delete dir;
}); });
} }
LocalFilesystem LocalFS; bool LocalFilesystem::StatVFS(VFSPath path, StatVFSData& data)
{
auto pathStr = this->VFSPathToSystem(path);
#if defined(_WIN32)
//not supporting windows yet
VFS::StatVFS(path, data);
return true;
#else
struct statvfs vfs;
if(statvfs(pathStr.c_str(), &vfs) == 0)
{
data.BlockSize = vfs.f_bsize;
data.FragmentSize = vfs.f_frsize;
data.Blocks = vfs.f_blocks;
data.BlocksFree = vfs.f_bfree;
data.BlocksAvailable = vfs.f_bavail;
data.TotalInodes = vfs.f_files;
data.FreeInodes = vfs.f_ffree;
data.AvailableInodes = vfs.f_favail;
data.Id = vfs.f_fsid;
data.Flags = vfs.f_flag;
data.MaxNameLength = vfs.f_namemax;
return true;
}
return false;
#endif
}
void LocalFilesystem::Chmod(VFSPath path, uint32_t mode)
{
auto pathStr = this->VFSPathToSystem(path);
#if defined(_WIN32)
#else
chmod(pathStr.c_str(), (mode_t)mode);
#endif
}
std::shared_ptr<LocalFilesystem> LocalFS;
} }
// C:/Users/Jim/Joel // C:/Users/Jim/Joel

View File

@@ -116,7 +116,7 @@ namespace Tesses::Framework::Filesystem
return nullptr; return nullptr;
} }
Streams::Stream* MemoryFilesystem::OpenFile(VFSPath path, std::string mode) std::shared_ptr<Streams::Stream> MemoryFilesystem::OpenFile(VFSPath path, std::string mode)
{ {
bool canRead=false; bool canRead=false;
bool canWrite=false; bool canWrite=false;
@@ -181,7 +181,7 @@ namespace Tesses::Framework::Filesystem
if(canWrite) f->data->canAccess=false; if(canWrite) f->data->canAccess=false;
mtx->Unlock(); mtx->Unlock();
return new MemoryFilesystemStream(mtx,f->data,canRead,canWrite,canSeek); return std::make_shared<MemoryFilesystemStream>(mtx,f->data,canRead,canWrite,canSeek);
} }
else else
{ {
@@ -204,7 +204,7 @@ namespace Tesses::Framework::Filesystem
file->data->readers++; file->data->readers++;
if(truncate) {file->data->file.clear(); file->data->lastWrite=Date::DateTime::NowUTC();} if(truncate) {file->data->file.clear(); file->data->lastWrite=Date::DateTime::NowUTC();}
mtx->Unlock(); mtx->Unlock();
return new MemoryFilesystemStream(mtx,file->data,canRead,canWrite,canSeek); return std::make_shared<MemoryFilesystemStream>(mtx,file->data,canRead,canWrite,canSeek);
} }
@@ -287,7 +287,7 @@ namespace Tesses::Framework::Filesystem
myDir->entries.push_back(f); myDir->entries.push_back(f);
mtx->Unlock(); mtx->Unlock();
return new MemoryFilesystemStream(mtx,f->data,canRead,canWrite,canSeek); return std::make_shared<MemoryFilesystemStream>(mtx,f->data,canRead,canWrite,canSeek);
} }
if(thefile != nullptr) if(thefile != nullptr)
{ {
@@ -305,7 +305,7 @@ namespace Tesses::Framework::Filesystem
thefile->data->readers++; thefile->data->readers++;
if(truncate) {thefile->data->file.clear(); thefile->data->lastWrite=Date::DateTime::NowUTC();} if(truncate) {thefile->data->file.clear(); thefile->data->lastWrite=Date::DateTime::NowUTC();}
mtx->Unlock(); mtx->Unlock();
return new MemoryFilesystemStream(mtx,thefile->data,canRead,canWrite,canSeek); return std::make_shared<MemoryFilesystemStream>(mtx,thefile->data,canRead,canWrite,canSeek);
} }
} }

View File

@@ -3,29 +3,26 @@
#include <iostream> #include <iostream>
namespace Tesses::Framework::Filesystem namespace Tesses::Framework::Filesystem
{ {
MountableFilesystem::MountableFilesystem() : MountableFilesystem(new NullFilesystem(),true) MountableFilesystem::MountableFilesystem() : MountableFilesystem(std::make_shared<NullFilesystem>())
{ {
} }
MountableFilesystem::MountableFilesystem(VFS* root, bool owns) MountableFilesystem::MountableFilesystem(std::shared_ptr<VFS> root)
{ {
this->root = root; this->root = root;
this->owns = owns;
} }
MountableDirectory::~MountableDirectory() MountableDirectory::~MountableDirectory()
{ {
if(this->owns && this->vfs) delete this->vfs;
for(auto dir : this->dirs) delete dir; for(auto dir : this->dirs) delete dir;
} }
MountableFilesystem::~MountableFilesystem() MountableFilesystem::~MountableFilesystem()
{ {
if(this->owns && this->root) delete root;
for(auto item : this->directories) delete item; for(auto item : this->directories) delete item;
} }
void MountableFilesystem::GetFS(VFSPath srcPath, VFSPath& destRoot, VFSPath& destPath, VFS*& vfs) void MountableFilesystem::GetFS(VFSPath srcPath, VFSPath& destRoot, VFSPath& destPath, std::shared_ptr<VFS>& vfs)
{ {
if(srcPath.path.empty()) return; if(srcPath.path.empty()) return;
for(auto item : this->directories) for(auto item : this->directories)
@@ -52,7 +49,7 @@ namespace Tesses::Framework::Filesystem
void MountableDirectory::GetFS(VFSPath srcPath, VFSPath curDir, VFSPath& destRoot, VFSPath& destPath, VFS*& vfs) void MountableDirectory::GetFS(VFSPath srcPath, VFSPath curDir, VFSPath& destRoot, VFSPath& destPath, std::shared_ptr<VFS>& vfs)
{ {
if(srcPath.path.empty()) return; if(srcPath.path.empty()) return;
for(auto item : this->dirs) for(auto item : this->dirs)
@@ -83,7 +80,7 @@ namespace Tesses::Framework::Filesystem
path = path.CollapseRelativeParents(); path = path.CollapseRelativeParents();
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
if(vfs != nullptr) if(vfs != nullptr)
@@ -91,12 +88,37 @@ namespace Tesses::Framework::Filesystem
return VFSPath(); return VFSPath();
} }
Tesses::Framework::Streams::Stream* MountableFilesystem::OpenFile(VFSPath path, std::string mode) bool MountableFilesystem::StatVFS(VFSPath path, StatVFSData& data)
{ {
path = path.CollapseRelativeParents(); path = path.CollapseRelativeParents();
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs);
if(vfs != nullptr)
return vfs->StatVFS(destPath,data);
return false;
}
void MountableFilesystem::Chmod(VFSPath path, uint32_t mode)
{
path = path.CollapseRelativeParents();
VFSPath destRoot;
VFSPath destPath = path;
std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs);
if(vfs != nullptr)
vfs->Chmod(destPath,mode);
}
std::shared_ptr<Tesses::Framework::Streams::Stream> MountableFilesystem::OpenFile(VFSPath path, std::string mode)
{
path = path.CollapseRelativeParents();
VFSPath destRoot;
VFSPath destPath = path;
std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -110,7 +132,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -128,7 +150,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -145,7 +167,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -160,7 +182,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -174,7 +196,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -189,7 +211,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -203,7 +225,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -217,7 +239,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -232,7 +254,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -248,7 +270,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -265,7 +287,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
if(destPath.path.empty()) return true; if(destPath.path.empty()) return true;
@@ -280,7 +302,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -295,7 +317,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -309,7 +331,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -323,10 +345,10 @@ namespace Tesses::Framework::Filesystem
VFSPath existingDestRoot; VFSPath existingDestRoot;
VFSPath existingDestPath = existingFile; VFSPath existingDestPath = existingFile;
VFS* existingVFS = root; std::shared_ptr<VFS> existingVFS = root;
VFSPath symlinkDestRoot; VFSPath symlinkDestRoot;
VFSPath symlinkDestPath = symlinkFile; VFSPath symlinkDestPath = symlinkFile;
VFS* symlinkVFS = root; std::shared_ptr<VFS> symlinkVFS = root;
GetFS(existingFile, existingDestRoot, existingDestPath, existingVFS); GetFS(existingFile, existingDestRoot, existingDestPath, existingVFS);
GetFS(symlinkFile, symlinkDestRoot, symlinkDestPath, symlinkVFS); GetFS(symlinkFile, symlinkDestRoot, symlinkDestPath, symlinkVFS);
@@ -342,10 +364,10 @@ namespace Tesses::Framework::Filesystem
VFSPath srcDestRoot; VFSPath srcDestRoot;
VFSPath srcDestPath = src; VFSPath srcDestPath = src;
VFS* srcVFS = root; std::shared_ptr<VFS> srcVFS = root;
VFSPath destDestRoot; VFSPath destDestRoot;
VFSPath destDestPath = dest; VFSPath destDestPath = dest;
VFS* destVFS = root; std::shared_ptr<VFS> destVFS = root;
GetFS(src, srcDestRoot, srcDestPath, srcVFS); GetFS(src, srcDestRoot, srcDestPath, srcVFS);
GetFS(dest, destDestRoot, destDestPath, destVFS); GetFS(dest, destDestRoot, destDestPath, destVFS);
@@ -360,10 +382,10 @@ namespace Tesses::Framework::Filesystem
VFSPath srcDestRoot; VFSPath srcDestRoot;
VFSPath srcDestPath = src; VFSPath srcDestPath = src;
VFS* srcVFS = root; std::shared_ptr<VFS> srcVFS = root;
VFSPath destDestRoot; VFSPath destDestRoot;
VFSPath destDestPath = dest; VFSPath destDestPath = dest;
VFS* destVFS = root; std::shared_ptr<VFS> destVFS = root;
GetFS(src, srcDestRoot, srcDestPath, srcVFS); GetFS(src, srcDestRoot, srcDestPath, srcVFS);
GetFS(dest, destDestRoot, destDestPath, destVFS); GetFS(dest, destDestRoot, destDestPath, destVFS);
@@ -378,10 +400,10 @@ namespace Tesses::Framework::Filesystem
VFSPath existingDestRoot; VFSPath existingDestRoot;
VFSPath existingDestPath = existingFile; VFSPath existingDestPath = existingFile;
VFS* existingVFS = root; std::shared_ptr<VFS> existingVFS = root;
VFSPath newNameRoot; VFSPath newNameRoot;
VFSPath newNamePath = newName; VFSPath newNamePath = newName;
VFS* newNameVFS = root; std::shared_ptr<VFS> newNameVFS = root;
GetFS(existingFile, existingDestRoot, existingDestPath, existingVFS); GetFS(existingFile, existingDestRoot, existingDestPath, existingVFS);
GetFS(newName, newNameRoot, newNamePath, newNameVFS); GetFS(newName, newNameRoot, newNamePath, newNameVFS);
@@ -427,7 +449,7 @@ namespace Tesses::Framework::Filesystem
VFSPath destRoot; VFSPath destRoot;
VFSPath destPath = path; VFSPath destPath = path;
VFS* vfs = root; std::shared_ptr<VFS> vfs = root;
GetFS(path, destRoot, destPath, vfs); GetFS(path, destRoot, destPath, vfs);
@@ -476,13 +498,12 @@ namespace Tesses::Framework::Filesystem
}); });
} }
void MountableFilesystem::Mount(VFSPath path, VFS* fs, bool owns) void MountableFilesystem::Mount(VFSPath path, std::shared_ptr<VFS> fs)
{ {
path = path.CollapseRelativeParents(); path = path.CollapseRelativeParents();
if(path.path.empty()) if(path.path.empty())
{ {
if(owns) delete fs;
return; return;
} }
@@ -520,7 +541,7 @@ namespace Tesses::Framework::Filesystem
if(item->name == lastDir) if(item->name == lastDir)
{ {
needToCreate=false; needToCreate=false;
if(item->owns && item->vfs) delete item->vfs;
item->vfs = fs; item->vfs = fs;
break; break;
} }
@@ -530,7 +551,7 @@ namespace Tesses::Framework::Filesystem
{ {
MountableDirectory* dir = new MountableDirectory(); MountableDirectory* dir = new MountableDirectory();
dir->name = lastDir; dir->name = lastDir;
dir->owns=owns;
dir->vfs=fs; dir->vfs=fs;
fsLs->push_back(dir); fsLs->push_back(dir);
} }
@@ -541,7 +562,6 @@ namespace Tesses::Framework::Filesystem
{ {
if(path.path.empty()) if(path.path.empty())
{ {
if(dir->owns && dir->vfs) delete dir->vfs;
dir->vfs = nullptr; dir->vfs = nullptr;
} }

View File

@@ -2,7 +2,7 @@
namespace Tesses::Framework::Filesystem namespace Tesses::Framework::Filesystem
{ {
Tesses::Framework::Streams::Stream* NullFilesystem::OpenFile(VFSPath path, std::string mode) std::shared_ptr<Tesses::Framework::Streams::Stream> NullFilesystem::OpenFile(VFSPath path, std::string mode)
{ {
return nullptr; return nullptr;
} }

View File

@@ -29,10 +29,10 @@ namespace Tesses::Framework::Filesystem
{ {
return this->path / path.CollapseRelativeParents(); return this->path / path.CollapseRelativeParents();
} }
SubdirFilesystem::SubdirFilesystem(VFS* parent, VFSPath path, bool owns) SubdirFilesystem::SubdirFilesystem(std::shared_ptr<VFS> parent, VFSPath path)
{ {
this->parent = parent; this->parent = parent;
if(path.relative && dynamic_cast<LocalFilesystem*>(parent) != nullptr) if(path.relative && std::dynamic_pointer_cast<LocalFilesystem>(parent) != nullptr)
{ {
Tesses::Framework::Filesystem::LocalFilesystem lfs; Tesses::Framework::Filesystem::LocalFilesystem lfs;
auto curDir = std::filesystem::current_path(); auto curDir = std::filesystem::current_path();
@@ -41,9 +41,9 @@ namespace Tesses::Framework::Filesystem
} }
else else
this->path = path; this->path = path;
this->owns=owns;
} }
Tesses::Framework::Streams::Stream* SubdirFilesystem::OpenFile(VFSPath path, std::string mode) std::shared_ptr<Tesses::Framework::Streams::Stream> SubdirFilesystem::OpenFile(VFSPath path, std::string mode)
{ {
return this->parent->OpenFile(ToParent(path),mode); return this->parent->OpenFile(ToParent(path),mode);
} }
@@ -151,7 +151,16 @@ namespace Tesses::Framework::Filesystem
SubdirFilesystem::~SubdirFilesystem() SubdirFilesystem::~SubdirFilesystem()
{ {
if(this->owns)
delete this->parent;
} }
bool SubdirFilesystem::StatVFS(VFSPath path, StatVFSData& vfsData)
{
return this->parent->StatVFS(path, vfsData);
}
void SubdirFilesystem::Chmod(VFSPath path, uint32_t mode)
{
return this->parent->Chmod(path, mode);
}
} }

View File

@@ -194,11 +194,11 @@ namespace Tesses::Framework::Filesystem
VFSPath VFSPath::GetAbsoluteCurrentDirectory() VFSPath VFSPath::GetAbsoluteCurrentDirectory()
{ {
auto p = std::filesystem::current_path(); auto p = std::filesystem::current_path();
return LocalFS.SystemToVFSPath(p.string()); return LocalFS->SystemToVFSPath(p.string());
} }
void VFSPath::SetAbsoluteCurrentDirectory(VFSPath path) void VFSPath::SetAbsoluteCurrentDirectory(VFSPath path)
{ {
auto res = LocalFS.VFSPathToSystem(path); auto res = LocalFS->VFSPathToSystem(path);
std::filesystem::path mpath=res; std::filesystem::path mpath=res;
std::filesystem::current_path(mpath); std::filesystem::current_path(mpath);
} }
@@ -499,5 +499,23 @@ namespace Tesses::Framework::Filesystem
{ {
} }
bool VFS::StatVFS(VFSPath path, StatVFSData& data)
{
data.BlockSize = 512;
data.Blocks=10000000000000;
data.BlocksFree=10000000000000;
data.BlocksAvailable=10000000000000;
data.AvailableInodes=10000000000000;
data.TotalInodes=10000000000000;
data.FreeInodes=10000000000000;
data.FragmentSize=512;
data.Id = 85138;
data.Flags = 0;
data.MaxNameLength=255;
return true;
}
void VFS::Chmod(VFSPath path, uint32_t mode) {
}
} }

View File

@@ -15,23 +15,20 @@ namespace Tesses::Framework::Http
} }
FileServer::FileServer(std::filesystem::path path,bool allowListing, bool spa, std::vector<std::string> defaultNames) FileServer::FileServer(std::filesystem::path path,bool allowListing, bool spa, std::vector<std::string> defaultNames)
{ {
LocalFilesystem* lfs=new LocalFilesystem(); std::shared_ptr<SubdirFilesystem> sdfs=std::make_shared<SubdirFilesystem>(Tesses::Framework::Filesystem::LocalFS,Tesses::Framework::Filesystem::LocalFS->SystemToVFSPath(path.string()));
SubdirFilesystem* sdfs=new SubdirFilesystem(lfs,lfs->SystemToVFSPath(path.string()),true);
this->vfs = sdfs; this->vfs = sdfs;
this->spa = spa; this->spa = spa;
this->ownsVFS=true;
this->allowListing = allowListing; this->allowListing = allowListing;
this->defaultNames = defaultNames; this->defaultNames = defaultNames;
} }
FileServer::FileServer(Tesses::Framework::Filesystem::VFS* fs, bool owns, bool allowListing,bool spa) : FileServer(fs,owns,allowListing,spa,{"index.html","default.html","index.htm","default.htm"}) FileServer::FileServer(std::shared_ptr<Tesses::Framework::Filesystem::VFS> fs, bool allowListing,bool spa) : FileServer(fs,allowListing,spa,{"index.html","default.html","index.htm","default.htm"})
{ {
} }
FileServer::FileServer(Tesses::Framework::Filesystem::VFS* fs, bool owns, bool allowListing, bool spa, std::vector<std::string> defaultNames) FileServer::FileServer(std::shared_ptr<Tesses::Framework::Filesystem::VFS> fs, bool allowListing, bool spa, std::vector<std::string> defaultNames)
{ {
this->vfs = fs; this->vfs = fs;
this->ownsVFS = owns;
this->allowListing = allowListing; this->allowListing = allowListing;
this->defaultNames = defaultNames; this->defaultNames = defaultNames;
this->spa = spa; this->spa = spa;
@@ -49,8 +46,6 @@ namespace Tesses::Framework::Http
retVal = true; retVal = true;
} }
delete strm;
return retVal; return retVal;
} }
@@ -130,7 +125,6 @@ namespace Tesses::Framework::Http
} }
FileServer::~FileServer() FileServer::~FileServer()
{ {
if(this->ownsVFS)
delete this->vfs;
} }
} }

View File

@@ -41,7 +41,7 @@ namespace Tesses::Framework::Http
dict.SetValue("Content-Type",this->mimeType); dict.SetValue("Content-Type",this->mimeType);
dict.SetValue("Content-Length",std::to_string(this->text.size())); dict.SetValue("Content-Length",std::to_string(this->text.size()));
} }
void TextHttpRequestBody::Write(Tesses::Framework::Streams::Stream* strm) void TextHttpRequestBody::Write(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{ {
strm->WriteBlock((const uint8_t*)this->text.c_str(),this->text.size()); strm->WriteBlock((const uint8_t*)this->text.c_str(),this->text.size());
} }
@@ -50,10 +50,9 @@ namespace Tesses::Framework::Http
} }
StreamHttpRequestBody::StreamHttpRequestBody(Stream* strm, bool owns, std::string mimeType) StreamHttpRequestBody::StreamHttpRequestBody(std::shared_ptr<Stream> strm, std::string mimeType)
{ {
this->strm = strm; this->strm = strm;
this->owns = owns;
this->mimeType = mimeType; this->mimeType = mimeType;
} }
void StreamHttpRequestBody::HandleHeaders(HttpDictionary& dict) void StreamHttpRequestBody::HandleHeaders(HttpDictionary& dict)
@@ -63,14 +62,12 @@ namespace Tesses::Framework::Http
if(len > -1) dict.AddValue("Content-Length",std::to_string(len)); if(len > -1) dict.AddValue("Content-Length",std::to_string(len));
} }
void StreamHttpRequestBody::Write(Tesses::Framework::Streams::Stream* strm) void StreamHttpRequestBody::Write(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{ {
this->strm->CopyTo(strm); this->strm->CopyTo(strm);
} }
StreamHttpRequestBody::~StreamHttpRequestBody() StreamHttpRequestBody::~StreamHttpRequestBody()
{ {
if(this->owns)
delete this->strm;
} }
HttpRequest::HttpRequest() HttpRequest::HttpRequest()
{ {
@@ -82,7 +79,7 @@ namespace Tesses::Framework::Http
this->requestHeaders.SetValue("Connection","close"); this->requestHeaders.SetValue("Connection","close");
} }
void HttpRequest::SendRequest(Tesses::Framework::Streams::Stream* strm) void HttpRequest::SendRequest(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{ {
Uri uri; Uri uri;
if(!Uri::TryParse(this->url, uri)) return; if(!Uri::TryParse(this->url, uri)) return;
@@ -109,7 +106,7 @@ namespace Tesses::Framework::Http
request.append("\r\n"); request.append("\r\n");
StreamWriter writer(strm, false); StreamWriter writer(strm);
writer.Write(request); writer.Write(request);
if(body != nullptr) if(body != nullptr)
@@ -117,52 +114,51 @@ namespace Tesses::Framework::Http
body->Write(strm); body->Write(strm);
} }
} }
Stream* HttpRequest::EstablishConnection(Uri uri, bool ignoreSSLErrors, std::string trusted_root_cert_bundle) std::shared_ptr<Stream> HttpRequest::EstablishConnection(Uri uri, bool ignoreSSLErrors, std::string trusted_root_cert_bundle)
{ {
if(uri.scheme == "http:" || uri.scheme == "ws:") if(uri.scheme == "http:" || uri.scheme == "ws:")
{ {
return new NetworkStream(uri.host,uri.GetPort(),false,false,false); return std::make_shared<NetworkStream>(uri.host,uri.GetPort(),false,false,false);
} }
else if(uri.scheme == "https:" || uri.scheme == "wss:") else if(uri.scheme == "https:" || uri.scheme == "wss:")
{ {
auto netStrm = new NetworkStream(uri.host,uri.GetPort(),false,false,false); auto netStrm = std::make_shared<NetworkStream>(uri.host,uri.GetPort(),false,false,false);
if(netStrm == nullptr) return nullptr; if(netStrm == nullptr) return nullptr;
return new ClientTLSStream(netStrm, true, !ignoreSSLErrors,uri.host, trusted_root_cert_bundle); return std::make_shared<ClientTLSStream>(netStrm, !ignoreSSLErrors,uri.host, trusted_root_cert_bundle);
} }
return nullptr; return nullptr;
} }
Stream* HttpRequest::EstablishUnixPathConnection(std::string unixPath,Uri uri, bool ignoreSSLErrors, std::string trusted_root_cert_bundle) std::shared_ptr<Stream> HttpRequest::EstablishUnixPathConnection(std::string unixPath,Uri uri, bool ignoreSSLErrors, std::string trusted_root_cert_bundle)
{ {
if(uri.scheme == "http:" || uri.scheme == "ws:") if(uri.scheme == "http:" || uri.scheme == "ws:")
{ {
return new NetworkStream(unixPath,false); return std::make_shared<NetworkStream>(unixPath,false);
} }
else if(uri.scheme == "https:" || uri.scheme == "wss:") else if(uri.scheme == "https:" || uri.scheme == "wss:")
{ {
auto netStrm = new NetworkStream(unixPath,false); auto netStrm = std::make_shared <NetworkStream>(unixPath,false);
if(netStrm == nullptr) return nullptr; if(netStrm == nullptr) return nullptr;
return new ClientTLSStream(netStrm, true, !ignoreSSLErrors,uri.host, trusted_root_cert_bundle); return std::make_shared<ClientTLSStream>(netStrm, !ignoreSSLErrors,uri.host, trusted_root_cert_bundle);
} }
return nullptr; return nullptr;
} }
Tesses::Framework::Streams::Stream* HttpResponse::GetInternalStream() std::shared_ptr<Tesses::Framework::Streams::Stream> HttpResponse::GetInternalStream()
{ {
return this->handleStrm; return this->handleStrm;
} }
HttpResponse::~HttpResponse() HttpResponse::~HttpResponse()
{ {
if(this->owns)
delete this->handleStrm;
} }
HttpResponse::HttpResponse(Stream* strm, bool owns) HttpResponse::HttpResponse(std::shared_ptr<Stream> strm)
{ {
this->handleStrm=nullptr; this->handleStrm=nullptr;
this->owns=owns; this->owns=owns;
StreamReader reader(strm, false); StreamReader reader(strm);
std::string statusLine; std::string statusLine;
if(!reader.ReadLine(statusLine)) return; if(!reader.ReadLine(statusLine)) return;
auto statusLinesPart = HttpUtils::SplitString(statusLine," ",3); auto statusLinesPart = HttpUtils::SplitString(statusLine," ",3);
@@ -178,7 +174,6 @@ namespace Tesses::Framework::Http
auto v = HttpUtils::SplitString(line,": ", 2); auto v = HttpUtils::SplitString(line,": ", 2);
if(v.size() != 2) if(v.size() != 2)
{ {
delete strm;
return; return;
} }
this->responseHeaders.AddValue(v[0],v[1]); this->responseHeaders.AddValue(v[0],v[1]);
@@ -222,7 +217,7 @@ namespace Tesses::Framework::Http
request.append("\r\n"); request.append("\r\n");
StreamWriter writer(strm, false); StreamWriter writer(strm);
writer.Write(request); writer.Write(request);
if(req.body != nullptr) if(req.body != nullptr)
@@ -230,7 +225,7 @@ namespace Tesses::Framework::Http
req.body->Write(strm); req.body->Write(strm);
} }
StreamReader reader(strm, false); StreamReader reader(strm);
std::string statusLine; std::string statusLine;
if(!reader.ReadLine(statusLine)) break; if(!reader.ReadLine(statusLine)) break;
auto statusLinesPart = HttpUtils::SplitString(statusLine," ",3); auto statusLinesPart = HttpUtils::SplitString(statusLine," ",3);
@@ -246,7 +241,6 @@ namespace Tesses::Framework::Http
auto v = HttpUtils::SplitString(line,": ", 2); auto v = HttpUtils::SplitString(line,": ", 2);
if(v.size() != 2) if(v.size() != 2)
{ {
delete strm;
return; return;
} }
this->responseHeaders.AddValue(v[0],v[1]); this->responseHeaders.AddValue(v[0],v[1]);
@@ -264,7 +258,6 @@ namespace Tesses::Framework::Http
url = uri2.ToString(); url = uri2.ToString();
delete strm;
continue; continue;
} }
this->handleStrm = strm; this->handleStrm = strm;
@@ -275,18 +268,18 @@ namespace Tesses::Framework::Http
{ {
auto strm = ReadAsStream(); auto strm = ReadAsStream();
if(strm == nullptr) return {}; if(strm == nullptr) return {};
StreamReader r(strm, true); StreamReader r(strm);
return r.ReadToEnd(); return r.ReadToEnd();
} }
void HttpResponse::CopyToStream(Stream* strm) void HttpResponse::CopyToStream(std::shared_ptr<Stream> strm)
{ {
if(strm == nullptr) return; if(strm == nullptr) return;
auto src = ReadAsStream(); auto src = ReadAsStream();
if(src == nullptr) return; if(src == nullptr) return;
src->CopyTo(*strm); src->CopyTo(strm);
delete src;
} }
Stream* HttpResponse::ReadAsStream() std::shared_ptr<Stream> HttpResponse::ReadAsStream()
{ {
if(this->handleStrm == nullptr) return nullptr; if(this->handleStrm == nullptr) return nullptr;
int64_t length = -1; int64_t length = -1;
@@ -295,10 +288,10 @@ namespace Tesses::Framework::Http
length = -1; length = -1;
} }
return new HttpStream(this->handleStrm,false,length,true,version=="HTTP/1.1"); return std::make_shared<HttpStream>(this->handleStrm,length,true,version=="HTTP/1.1");
} }
void DownloadUnixSocketToStreamSimple(std::string unixSocket,std::string url, Tesses::Framework::Streams::Stream* strm) void DownloadUnixSocketToStreamSimple(std::string unixSocket,std::string url, std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{ {
if(strm == nullptr) throw std::runtime_error("strm is null"); if(strm == nullptr) throw std::runtime_error("strm is null");
HttpRequest request; HttpRequest request;
@@ -310,26 +303,17 @@ namespace Tesses::Framework::Http
if(response.statusCode < 200 || response.statusCode > 299) throw std::runtime_error("Status code does not indicate success: " + std::to_string(response.statusCode) + " " + HttpUtils::StatusCodeString(response.statusCode)); if(response.statusCode < 200 || response.statusCode > 299) throw std::runtime_error("Status code does not indicate success: " + std::to_string(response.statusCode) + " " + HttpUtils::StatusCodeString(response.statusCode));
response.CopyToStream(strm); response.CopyToStream(strm);
} }
void DownloadUnixSocketToStreamSimple(std::string unixSocket,std::string url, Tesses::Framework::Streams::Stream& strm)
{
DownloadUnixSocketToStreamSimple(unixSocket,url,&strm);
}
void DownloadUnixSocketToFileSimple(std::string unixSocket,std::string url, Tesses::Framework::Filesystem::VFS* vfs, Tesses::Framework::Filesystem::VFSPath path) void DownloadUnixSocketToFileSimple(std::string unixSocket,std::string url, std::shared_ptr<Tesses::Framework::Filesystem::VFS> vfs, Tesses::Framework::Filesystem::VFSPath path)
{ {
if(vfs == nullptr) throw std::runtime_error("vfs is null"); if(vfs == nullptr) throw std::runtime_error("vfs is null");
auto strm = vfs->OpenFile(path,"wb"); auto strm = vfs->OpenFile(path,"wb");
if(strm == nullptr) throw std::runtime_error("strm is null"); if(strm == nullptr) throw std::runtime_error("strm is null");
DownloadUnixSocketToStreamSimple(unixSocket,url,strm); DownloadUnixSocketToStreamSimple(unixSocket,url,strm);
delete strm;
}
void DownloadUnixSocketToFileSimple(std::string unixSocket,std::string url, Tesses::Framework::Filesystem::VFS& vfs, Tesses::Framework::Filesystem::VFSPath path)
{
auto strm = vfs.OpenFile(path,"wb");
if(strm == nullptr) throw std::runtime_error("strm is null");
DownloadUnixSocketToStreamSimple(unixSocket,url,strm);
delete strm;
} }
void DownloadUnixSocketToFileSimple(std::string unixSocket,std::string url, Tesses::Framework::Filesystem::VFSPath path) void DownloadUnixSocketToFileSimple(std::string unixSocket,std::string url, Tesses::Framework::Filesystem::VFSPath path)
{ {
DownloadUnixSocketToFileSimple(unixSocket,url,Tesses::Framework::Filesystem::LocalFS,path); DownloadUnixSocketToFileSimple(unixSocket,url,Tesses::Framework::Filesystem::LocalFS,path);
@@ -345,23 +329,17 @@ namespace Tesses::Framework::Http
if(response.statusCode < 200 || response.statusCode > 299) throw std::runtime_error("Status code does not indicate success: " + std::to_string(response.statusCode) + " " + HttpUtils::StatusCodeString(response.statusCode)); if(response.statusCode < 200 || response.statusCode > 299) throw std::runtime_error("Status code does not indicate success: " + std::to_string(response.statusCode) + " " + HttpUtils::StatusCodeString(response.statusCode));
return response.ReadAsString(); return response.ReadAsString();
} }
void DownloadToStreamSimple(std::string url, Tesses::Framework::Streams::Stream* strm) void DownloadToStreamSimple(std::string url, std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{
DownloadUnixSocketToStreamSimple("",url,strm);
}
void DownloadToStreamSimple(std::string url, Tesses::Framework::Streams::Stream& strm)
{ {
DownloadUnixSocketToStreamSimple("",url,strm); DownloadUnixSocketToStreamSimple("",url,strm);
} }
void DownloadToFileSimple(std::string url, Tesses::Framework::Filesystem::VFS* vfs, Tesses::Framework::Filesystem::VFSPath path) void DownloadToFileSimple(std::string url, std::shared_ptr<Tesses::Framework::Filesystem::VFS> vfs, Tesses::Framework::Filesystem::VFSPath path)
{
DownloadUnixSocketToFileSimple("",url,vfs,path);
}
void DownloadToFileSimple(std::string url, Tesses::Framework::Filesystem::VFS& vfs, Tesses::Framework::Filesystem::VFSPath path)
{ {
DownloadUnixSocketToFileSimple("",url,vfs,path); DownloadUnixSocketToFileSimple("",url,vfs,path);
} }
void DownloadToFileSimple(std::string url, Tesses::Framework::Filesystem::VFSPath path) void DownloadToFileSimple(std::string url, Tesses::Framework::Filesystem::VFSPath path)
{ {
DownloadUnixSocketToFileSimple("",url,path); DownloadUnixSocketToFileSimple("",url,path);
@@ -381,22 +359,15 @@ namespace Tesses::Framework::Http
{ {
return true; return true;
} }
void WebSocketClient(std::string url, HttpDictionary& requestHeaders, WebSocketConnection& wsc, std::function<bool(HttpDictionary&,bool)> cb)
{
WebSocketUnixSocketClient("",url,requestHeaders,wsc,cb);
}
void WebSocketUnixSocketClient(std::string unixSocket,std::string url, HttpDictionary& requestHeaders, WebSocketConnection& wsc, std::function<bool(HttpDictionary&,bool)> cb)
{
WebSocketUnixSocketClient(unixSocket,url,requestHeaders, &wsc,cb);
}
class WSClient { class WSClient {
public: public:
std::atomic<bool> closed; std::atomic<bool> closed;
Threading::Mutex mtx; Threading::Mutex mtx;
WebSocketConnection* conn; std::shared_ptr<WebSocketConnection> conn;
Stream* strm; std::shared_ptr<Stream> strm;
void close() void close()
{ {
mtx.Lock(); mtx.Lock();
@@ -557,7 +528,7 @@ namespace Tesses::Framework::Http
return true; return true;
} }
WSClient(Tesses::Framework::Streams::Stream* strm,WebSocketConnection* conn) WSClient(std::shared_ptr<Tesses::Framework::Streams::Stream> strm,std::shared_ptr<WebSocketConnection> conn)
{ {
this->strm = strm; this->strm = strm;
this->conn = conn; this->conn = conn;
@@ -626,12 +597,12 @@ namespace Tesses::Framework::Http
}; };
void WebSocketClient(std::string url, HttpDictionary& requestHeaders, WebSocketConnection* wsc, std::function<bool(HttpDictionary&,bool)> cb) void WebSocketClient(std::string url, HttpDictionary& requestHeaders, std::shared_ptr<WebSocketConnection> wsc, std::function<bool(HttpDictionary&,bool)> cb)
{ {
WebSocketUnixSocketClient("",url,requestHeaders,wsc,cb); WebSocketUnixSocketClient("",url,requestHeaders,wsc,cb);
} }
void WebSocketUnixSocketClient(std::string unixSocket,std::string url, HttpDictionary& requestHeaders, WebSocketConnection* wsc, std::function<bool(HttpDictionary&,bool)> cb) void WebSocketUnixSocketClient(std::string unixSocket,std::string url, HttpDictionary& requestHeaders, std::shared_ptr<WebSocketConnection> wsc, std::function<bool(HttpDictionary&,bool)> cb)
{ {
HttpRequest req; HttpRequest req;
req.url = url; req.url = url;

View File

@@ -29,8 +29,8 @@ namespace Tesses::Framework::Http
public: public:
Threading::Mutex mtx; Threading::Mutex mtx;
ServerContext* ctx; ServerContext* ctx;
WebSocketConnection* conn; std::shared_ptr<WebSocketConnection> conn;
Stream* strm; std::shared_ptr<Stream> strm;
std::atomic_bool hasInit; std::atomic_bool hasInit;
std::atomic<bool> closed; std::atomic<bool> closed;
void close() void close()
@@ -42,7 +42,6 @@ namespace Tesses::Framework::Http
strm->WriteByte(firstByte); strm->WriteByte(firstByte);
strm->WriteByte(0); strm->WriteByte(0);
delete strm;
this->strm = nullptr; this->strm = nullptr;
mtx.Unlock(); mtx.Unlock();
this->conn->OnClose(true); this->conn->OnClose(true);
@@ -180,11 +179,11 @@ namespace Tesses::Framework::Http
return true; return true;
} }
WSServer(ServerContext* ctx,WebSocketConnection* conn) WSServer(ServerContext* ctx,std::shared_ptr<WebSocketConnection> conn)
{ {
this->ctx = ctx; this->ctx = ctx;
this->conn = conn; this->conn = conn;
this->strm = &this->ctx->GetStream(); this->strm = this->ctx->GetStream();
this->hasInit=false; this->hasInit=false;
@@ -352,27 +351,23 @@ namespace Tesses::Framework::Http
if(this->queryParams.kvp.empty()) return this->originalPath; if(this->queryParams.kvp.empty()) return this->originalPath;
return this->originalPath + "?" + HttpUtils::QueryParamsEncode(this->queryParams); return this->originalPath + "?" + HttpUtils::QueryParamsEncode(this->queryParams);
} }
void ServerContext::ReadStream(Stream* strm) void ServerContext::ReadStream(std::shared_ptr<Stream> strm)
{ {
if(strm == nullptr) return; if(strm == nullptr) return;
auto strm2 = this->OpenRequestStream(); auto strm2 = this->OpenRequestStream();
if(strm2 != nullptr) if(strm2 != nullptr)
{ {
strm2->CopyTo(strm); strm2->CopyTo(strm);
delete strm2;
} }
} }
void ServerContext::ReadStream(Stream& strm)
{
ReadStream(&strm);
}
std::string ServerContext::ReadString() std::string ServerContext::ReadString()
{ {
if(strm == nullptr) return {}; if(strm == nullptr) return {};
auto strm2 = this->OpenRequestStream(); auto strm2 = this->OpenRequestStream();
if(strm2 != nullptr) if(strm2 != nullptr)
{ {
TextStreams::StreamReader reader(strm2,true); TextStreams::StreamReader reader(strm2);
return reader.ReadToEnd(); return reader.ReadToEnd();
} }
return {}; return {};
@@ -389,7 +384,7 @@ namespace Tesses::Framework::Http
} }
return false; return false;
} }
static bool parseUntillBoundaryEnd(Tesses::Framework::Streams::Stream* src, Tesses::Framework::Streams::Stream* dest, std::string boundary) static bool parseUntillBoundaryEnd(std::shared_ptr<Tesses::Framework::Streams::Stream> src, std::shared_ptr<Tesses::Framework::Streams::Stream> dest, std::string boundary)
{ {
bool hasMore=true; bool hasMore=true;
#if defined(_WIN32) #if defined(_WIN32)
@@ -466,7 +461,7 @@ namespace Tesses::Framework::Http
return hasMore; return hasMore;
} }
static bool parseSection(ServerContext* ctx, std::string boundary, std::function<Tesses::Framework::Streams::Stream*(std::string mime, std::string filename, std::string name)> cb) static bool parseSection(ServerContext* ctx, std::string boundary, std::function<std::shared_ptr<Tesses::Framework::Streams::Stream>(std::string mime, std::string filename, std::string name)> cb)
{ {
HttpDictionary req; HttpDictionary req;
StreamReader reader(ctx->GetStream()); StreamReader reader(ctx->GetStream());
@@ -489,10 +484,10 @@ namespace Tesses::Framework::Http
{ {
if(cd1.filename.empty()) if(cd1.filename.empty())
{ {
MemoryStream ms(true); std::shared_ptr<MemoryStream> ms=std::make_shared<MemoryStream>(true);
bool retVal = parseUntillBoundaryEnd(&ctx->GetStream(),&ms,boundary); bool retVal = parseUntillBoundaryEnd(ctx->GetStream(),ms,boundary);
auto& buff = ms.GetBuffer(); auto& buff = ms->GetBuffer();
ctx->queryParams.AddValue(cd1.fieldName, std::string(buff.begin(),buff.end())); ctx->queryParams.AddValue(cd1.fieldName, std::string(buff.begin(),buff.end()));
@@ -502,16 +497,16 @@ namespace Tesses::Framework::Http
else else
{ {
auto strm = cb(ct, cd1.filename, cd1.fieldName); auto strm = cb(ct, cd1.filename, cd1.fieldName);
if(strm == nullptr) strm = new Stream(); if(strm == nullptr) strm = std::make_shared<Stream>();
bool retVal = parseUntillBoundaryEnd(&ctx->GetStream(),strm,boundary); bool retVal = parseUntillBoundaryEnd(ctx->GetStream(),strm,boundary);
delete strm;
return retVal; return retVal;
} }
} }
return false; return false;
} }
void ServerContext::ParseFormData(std::function<Tesses::Framework::Streams::Stream*(std::string mime, std::string filename, std::string name)> cb) void ServerContext::ParseFormData(std::function<std::shared_ptr<Tesses::Framework::Streams::Stream>(std::string mime, std::string filename, std::string name)> cb)
{ {
std::string ct; std::string ct;
if(this->requestHeaders.TryGetFirst("Content-Type",ct)) if(this->requestHeaders.TryGetFirst("Content-Type",ct))
@@ -525,51 +520,33 @@ namespace Tesses::Framework::Http
if(res == std::string::npos) return; if(res == std::string::npos) return;
ct = "--" + ct.substr(res+9); ct = "--" + ct.substr(res+9);
} }
Stream nullStrm; std::shared_ptr<Stream> nullStrm=std::make_shared<Stream>();
parseUntillBoundaryEnd(this->strm,&nullStrm, ct); parseUntillBoundaryEnd(this->strm,nullStrm, ct);
while(parseSection(this, ct, cb)); while(parseSection(this, ct, cb));
} }
HttpServer::HttpServer(Tesses::Framework::Streams::TcpServer& tcpServer, IHttpServer& http, bool showIPs) : HttpServer(&tcpServer,false,&http,false,showIPs)
{
} HttpServer::HttpServer(std::shared_ptr<Tesses::Framework::Streams::TcpServer> tcpServer, std::shared_ptr<IHttpServer> http, bool showIPs)
HttpServer::HttpServer(Tesses::Framework::Streams::TcpServer* tcpServer, bool ownsTCP, IHttpServer& http, bool showIPs) : HttpServer(tcpServer,ownsTCP,&http,false,showIPs)
{
}
HttpServer::HttpServer(Tesses::Framework::Streams::TcpServer& tcpServer, IHttpServer* http, bool ownsHttpServer, bool showIPs) : HttpServer(&tcpServer,false,http,ownsHttpServer,showIPs)
{
}
HttpServer::HttpServer(Tesses::Framework::Streams::TcpServer* tcpServer, bool ownsTCP, IHttpServer* http, bool ownsHttpServer, bool showIPs)
{ {
this->server = tcpServer; this->server = tcpServer;
this->ownsTCP = ownsTCP;
this->http = http; this->http = http;
this->ownsHttp = ownsHttpServer;
this->showIPs = showIPs; this->showIPs = showIPs;
this->thrd=nullptr; this->thrd=nullptr;
this->showARTL = showIPs; this->showARTL = showIPs;
} }
HttpServer::HttpServer(uint16_t port, IHttpServer* http, bool owns, bool showIPs) : HttpServer(new TcpServer(port,10),true,http,owns,showIPs) HttpServer::HttpServer(uint16_t port, std::shared_ptr<IHttpServer> http, bool showIPs) : HttpServer(std::make_shared<TcpServer>(port,10),http,showIPs)
{ {
} }
HttpServer::HttpServer(uint16_t port, IHttpServer& http,bool showIPs) : HttpServer(port,&http,false,showIPs)
{ HttpServer::HttpServer(std::string unixPath, std::shared_ptr<IHttpServer> http) : HttpServer(std::make_shared<TcpServer>(unixPath,10),http,false)
}
HttpServer::HttpServer(std::string unixPath, IHttpServer* http, bool owns) : HttpServer(new TcpServer(unixPath,10),true,http,owns,false)
{ {
this->showARTL=true; this->showARTL=true;
} }
HttpServer::HttpServer(std::string unixPath, IHttpServer& http) : HttpServer(unixPath,&http,false)
{
}
uint16_t HttpServer::GetPort() uint16_t HttpServer::GetPort()
{ {
@@ -577,7 +554,7 @@ namespace Tesses::Framework::Http
return server->GetPort(); return server->GetPort();
return 0; return 0;
} }
Stream* ServerContext::OpenResponseStream() std::shared_ptr<Stream> ServerContext::OpenResponseStream()
{ {
if(sent) return nullptr; if(sent) return nullptr;
int64_t length = -1; int64_t length = -1;
@@ -588,14 +565,14 @@ namespace Tesses::Framework::Http
this->responseHeaders.SetValue("Transfer-Encoding","chunked"); this->responseHeaders.SetValue("Transfer-Encoding","chunked");
this->WriteHeaders(); this->WriteHeaders();
return new HttpStream(this->strm,false,length,false,version == "HTTP/1.1"); return std::make_shared<HttpStream>(this->strm,length,false,version == "HTTP/1.1");
} }
Stream* ServerContext::OpenRequestStream() std::shared_ptr<Stream> ServerContext::OpenRequestStream()
{ {
int64_t length = -1; int64_t length = -1;
if(!this->requestHeaders.TryGetFirstInt("Content-Length",length)) if(!this->requestHeaders.TryGetFirstInt("Content-Length",length))
length = -1; length = -1;
return new HttpStream(this->strm,false,length,true,version == "HTTP/1.1"); return std::make_shared<HttpStream>(this->strm,length,true,version == "HTTP/1.1");
} }
void HttpServer::StartAccepting() void HttpServer::StartAccepting()
{ {
@@ -622,9 +599,9 @@ namespace Tesses::Framework::Http
TF_LOG("Before entering socket thread"); TF_LOG("Before entering socket thread");
Threading::Thread thrd2([sock,http,ip,port]()->void { Threading::Thread thrd2([sock,http,ip,port]()->void {
TF_LOG("In thread to process"); TF_LOG("In thread to process");
HttpServer::Process(*sock,*http,ip,port,false); HttpServer::Process(sock,http,ip,port,false);
TF_LOG("In thread after process"); TF_LOG("In thread after process");
delete sock;
}); });
TF_LOG("Before attach"); TF_LOG("Before attach");
thrd2.Detach(); thrd2.Detach();
@@ -664,16 +641,13 @@ namespace Tesses::Framework::Http
this->thrd->Join(); this->thrd->Join();
delete this->thrd; delete this->thrd;
} }
if(this->ownsHttp)
delete http;
if(this->ownsTCP)
delete this->server;
} }
IHttpServer::~IHttpServer() IHttpServer::~IHttpServer()
{ {
} }
ServerContext::ServerContext(Stream* strm) ServerContext::ServerContext(std::shared_ptr<Stream> strm)
{ {
this->statusCode = OK; this->statusCode = OK;
this->strm = strm; this->strm = strm;
@@ -681,14 +655,14 @@ namespace Tesses::Framework::Http
this->queryParams.SetCaseSensitive(true); this->queryParams.SetCaseSensitive(true);
this->responseHeaders.AddValue("Server","TessesFrameworkWebServer"); this->responseHeaders.AddValue("Server","TessesFrameworkWebServer");
} }
Stream& ServerContext::GetStream() std::shared_ptr<Stream> ServerContext::GetStream()
{ {
return *this->strm; return this->strm;
} }
void ServerContext::SendBytes(std::vector<uint8_t> buff) void ServerContext::SendBytes(std::vector<uint8_t> buff)
{ {
MemoryStream strm(false); std::shared_ptr<MemoryStream> strm=std::make_shared<MemoryStream>(false);
strm.GetBuffer() = buff; strm->GetBuffer() = buff;
SendStream(strm); SendStream(strm);
} }
ServerContext& ServerContext::WithLastModified(Date::DateTime dt) ServerContext& ServerContext::WithLastModified(Date::DateTime dt)
@@ -699,8 +673,9 @@ namespace Tesses::Framework::Http
void ServerContext::SendText(std::string text) void ServerContext::SendText(std::string text)
{ {
MemoryStream strm(false); std::shared_ptr<MemoryStream> strm=std::make_shared<MemoryStream>(false);
auto& buff= strm.GetBuffer();
auto& buff= strm->GetBuffer();
buff.insert(buff.end(),text.begin(),text.end()); buff.insert(buff.end(),text.begin(),text.end());
SendStream(strm); SendStream(strm);
} }
@@ -711,11 +686,7 @@ namespace Tesses::Framework::Http
WithMimeType("text/html").SendText(errorHtml); WithMimeType("text/html").SendText(errorHtml);
} }
void ServerContext::SendStream(Stream* strm)
{
if(strm == nullptr) return;
SendStream(*strm);
}
ServerContext::~ServerContext() ServerContext::~ServerContext()
{ {
for(auto item : this->data) for(auto item : this->data)
@@ -727,14 +698,14 @@ namespace Tesses::Framework::Http
{ {
} }
void ServerContext::SendStream(Stream& strm) void ServerContext::SendStream(std::shared_ptr<Stream> strm)
{ {
if(sent) return; if(sent) return;
if(!strm.CanRead()) throw std::runtime_error("Cannot read from stream"); if(!strm->CanRead()) throw std::runtime_error("Cannot read from stream");
if(strm.EndOfStream()) throw std::runtime_error("End of stream"); if(strm->EndOfStream()) throw std::runtime_error("End of stream");
if(strm.CanSeek()) if(strm->CanSeek())
{ {
int64_t len=strm.GetLength(); int64_t len=strm->GetLength();
std::string range={}; std::string range={};
if(this->requestHeaders.TryGetFirst("Range",range)) if(this->requestHeaders.TryGetFirst("Range",range))
{ {
@@ -815,7 +786,7 @@ namespace Tesses::Framework::Http
this->WithSingleHeader("Content-Range","bytes " + std::to_string(begin) + "-" + std::to_string(end) + "/" + std::to_string(len)); this->WithSingleHeader("Content-Range","bytes " + std::to_string(begin) + "-" + std::to_string(end) + "/" + std::to_string(len));
this->statusCode = PartialContent; this->statusCode = PartialContent;
this->WriteHeaders(); this->WriteHeaders();
strm.Seek(begin,SeekOrigin::Begin); strm->Seek(begin,SeekOrigin::Begin);
uint8_t buffer[1024]; uint8_t buffer[1024];
@@ -825,7 +796,7 @@ namespace Tesses::Framework::Http
myLen = (end - begin)+1; myLen = (end - begin)+1;
if(myLen < read) read = (size_t)myLen; if(myLen < read) read = (size_t)myLen;
if(read == 0) break; if(read == 0) break;
read = strm.Read(buffer,read); read = strm->Read(buffer,read);
if(read == 0) break; if(read == 0) break;
this->strm->WriteBlock(buffer,read); this->strm->WriteBlock(buffer,read);
@@ -848,7 +819,7 @@ namespace Tesses::Framework::Http
this->WithSingleHeader("Accept-Range","bytes"); this->WithSingleHeader("Accept-Range","bytes");
this->WithSingleHeader("Content-Length",std::to_string(len)); this->WithSingleHeader("Content-Length",std::to_string(len));
this->WriteHeaders(); this->WriteHeaders();
strm.CopyTo(*this->strm); strm->CopyTo(this->strm);
} }
} }
@@ -857,7 +828,7 @@ namespace Tesses::Framework::Http
{ {
auto chunkedStream = this->OpenResponseStream(); auto chunkedStream = this->OpenResponseStream();
this->strm->CopyTo(chunkedStream); this->strm->CopyTo(chunkedStream);
delete chunkedStream;
} }
} }
@@ -920,7 +891,7 @@ namespace Tesses::Framework::Http
if(this->sent) return *this; if(this->sent) return *this;
this->sent = true; this->sent = true;
StreamWriter writer(this->strm,false); StreamWriter writer(this->strm);
writer.newline = "\r\n"; writer.newline = "\r\n";
writer.WriteLine("HTTP/1.1 " + std::to_string((int)statusCode) + " " + HttpUtils::StatusCodeString(statusCode)); writer.WriteLine("HTTP/1.1 " + std::to_string((int)statusCode) + " " + HttpUtils::StatusCodeString(statusCode));
for(auto& hdr : responseHeaders.kvp) for(auto& hdr : responseHeaders.kvp)
@@ -935,14 +906,14 @@ namespace Tesses::Framework::Http
return *this; return *this;
} }
void HttpServer::Process(Stream& strm, IHttpServer& server, std::string ip, uint16_t port, bool encrypted) void HttpServer::Process(std::shared_ptr<Stream> strm, std::shared_ptr<IHttpServer> server, std::string ip, uint16_t port, bool encrypted)
{ {
TF_LOG("In process"); TF_LOG("In process");
while(true) while(true)
{ {
BufferedStream bStrm(strm); std::shared_ptr<BufferedStream> bStrm = std::make_shared<BufferedStream>(strm);
StreamReader reader(bStrm); StreamReader reader(bStrm);
ServerContext ctx(&bStrm); ServerContext ctx(bStrm);
ctx.ip = ip; ctx.ip = ip;
ctx.port = port; ctx.port = port;
ctx.encrypted = encrypted; ctx.encrypted = encrypted;
@@ -1002,13 +973,13 @@ namespace Tesses::Framework::Http
{ {
size_t len = (size_t)length; size_t len = (size_t)length;
uint8_t* buffer = new uint8_t[len]; uint8_t* buffer = new uint8_t[len];
len = bStrm.ReadBlock(buffer,len); len = bStrm->ReadBlock(buffer,len);
std::string query((const char*)buffer,len); std::string query((const char*)buffer,len);
delete[] buffer; delete[] buffer;
HttpUtils::QueryParamsDecode(ctx.queryParams, query); HttpUtils::QueryParamsDecode(ctx.queryParams, query);
} }
if(!server.Handle(ctx)) if(!server->Handle(ctx))
{ {
ctx.SendNotFound(); ctx.SendNotFound();
} }
@@ -1047,7 +1018,7 @@ namespace Tesses::Framework::Http
if(HttpUtils::ToLower(connection) != "keep-alive") return; if(HttpUtils::ToLower(connection) != "keep-alive") return;
} }
if(bStrm.EndOfStream()) { if(bStrm->EndOfStream()) {
return; return;
} }
} }
@@ -1059,16 +1030,16 @@ namespace Tesses::Framework::Http
} }
void ServerContext::StartWebSocketSession(std::function<void(std::function<void(WebSocketMessage&)>,std::function<void()>,std::function<void()>)> onOpen, std::function<void(WebSocketMessage&)> onReceive, std::function<void(bool)> onClose) void ServerContext::StartWebSocketSession(std::function<void(std::function<void(WebSocketMessage&)>,std::function<void()>,std::function<void()>)> onOpen, std::function<void(WebSocketMessage&)> onReceive, std::function<void(bool)> onClose)
{ {
CallbackWebSocketConnection wsc(onOpen,onReceive,onClose); std::shared_ptr<CallbackWebSocketConnection> wsc = std::make_shared<CallbackWebSocketConnection>(onOpen,onReceive,onClose);
StartWebSocketSession(wsc); StartWebSocketSession(wsc);
} }
void ServerContext::StartWebSocketSession(WebSocketConnection& connection) void ServerContext::StartWebSocketSession(std::shared_ptr<WebSocketConnection> connection)
{ {
WSServer svr(this,&connection); WSServer svr(this,connection);
Threading::Thread thrd([&svr,&connection]()->void{ Threading::Thread thrd([&svr,&connection]()->void{
try { try {
connection.OnOpen([&svr](WebSocketMessage& msg)->void { connection->OnOpen([&svr](WebSocketMessage& msg)->void {
svr.send_msg(&msg); svr.send_msg(&msg);
},[&svr]()->void { },[&svr]()->void {
std::vector<uint8_t> p = {(uint8_t)'p',(uint8_t)'i',(uint8_t)'n',(uint8_t)'g'}; std::vector<uint8_t> p = {(uint8_t)'p',(uint8_t)'i',(uint8_t)'n',(uint8_t)'g'};

View File

@@ -7,10 +7,9 @@ using StreamWriter = Tesses::Framework::TextStreams::StreamWriter;
using StreamReader = Tesses::Framework::TextStreams::StreamReader; using StreamReader = Tesses::Framework::TextStreams::StreamReader;
namespace Tesses::Framework::Http namespace Tesses::Framework::Http
{ {
HttpStream::HttpStream(Tesses::Framework::Streams::Stream* strm, bool owns, int64_t length, bool recv, bool http1_1) HttpStream::HttpStream(std::shared_ptr<Tesses::Framework::Streams::Stream> strm, int64_t length, bool recv, bool http1_1)
{ {
this->strm = strm; this->strm = strm;
this->owns = owns;
this->length = length; this->length = length;
this->recv = recv; this->recv = recv;
this->http1_1 = http1_1; this->http1_1 = http1_1;
@@ -18,10 +17,6 @@ namespace Tesses::Framework::Http
this->read = 0; this->read = 0;
this->position = 0; this->position = 0;
this->done=false; this->done=false;
}
HttpStream::HttpStream(Tesses::Framework::Streams::Stream& strm, int64_t length, bool recv,bool http1_1) : HttpStream(&strm,false,length,recv,http1_1)
{
} }
bool HttpStream::CanRead() bool HttpStream::CanRead()
{ {
@@ -79,14 +74,14 @@ namespace Tesses::Framework::Http
this->position += len; this->position += len;
if(this->offset >= this->read) if(this->offset >= this->read)
{ {
StreamReader reader(this->strm, false); StreamReader reader(this->strm);
reader.ReadLine(); reader.ReadLine();
} }
return len; return len;
} }
else else
{ {
StreamReader reader(this->strm, false); StreamReader reader(this->strm);
std::string line = reader.ReadLine(); std::string line = reader.ReadLine();
if(!line.empty()) if(!line.empty())
{ {
@@ -141,7 +136,7 @@ namespace Tesses::Framework::Http
std::stringstream strm; std::stringstream strm;
strm << std::hex << len; strm << std::hex << len;
StreamWriter writer(this->strm,false); StreamWriter writer(this->strm);
writer.newline = "\r\n"; writer.newline = "\r\n";
writer.WriteLine(strm.str()); writer.WriteLine(strm.str());
@@ -160,11 +155,10 @@ namespace Tesses::Framework::Http
{ {
if(this->length == -1 && this->http1_1) if(this->length == -1 && this->http1_1)
{ {
StreamWriter writer(this->strm,false); StreamWriter writer(this->strm);
writer.newline = "\r\n"; writer.newline = "\r\n";
writer.WriteLine("0"); writer.WriteLine("0");
writer.WriteLine(); writer.WriteLine();
} }
if(this->owns) delete this->strm;
} }
} }

View File

@@ -22,26 +22,18 @@ bool MountableServer::StartsWith(Filesystem::VFSPath fullPath, Filesystem::VFSPa
} }
return true; return true;
} }
MountableServer::MountableServer() : MountableServer(nullptr,false) MountableServer::MountableServer() : MountableServer(nullptr)
{ {
} }
MountableServer::MountableServer(IHttpServer* root, bool owns) MountableServer::MountableServer(std::shared_ptr<IHttpServer> root)
{ {
this->root = root; this->root = root;
this->owns = owns;
} }
MountableServer::MountableServer(IHttpServer& root) : MountableServer(&root,false)
void MountableServer::Mount(std::string path, std::shared_ptr<IHttpServer> server)
{ {
this->servers.insert(this->servers.begin(), std::pair<std::string,std::shared_ptr<IHttpServer>>(path, server));
}
void MountableServer::Mount(std::string path, IHttpServer* server, bool owns)
{
this->servers.insert(this->servers.begin(), std::pair<std::string,std::pair<bool,IHttpServer*>>(path, std::pair<bool,IHttpServer*>(owns,server)));
}
void MountableServer::Mount(std::string path, IHttpServer& server)
{
Mount(path,&server,false);
} }
void MountableServer::Unmount(std::string path) void MountableServer::Unmount(std::string path)
{ {
@@ -50,7 +42,6 @@ void MountableServer::Unmount(std::string path)
auto& item = *i; auto& item = *i;
if(item.first == path) if(item.first == path)
{ {
if(item.second.first) delete item.second.second;
this->servers.erase(i); this->servers.erase(i);
return; return;
} }
@@ -64,7 +55,7 @@ bool MountableServer::Handle(ServerContext& ctx)
if(StartsWith(oldPath, item.first)) if(StartsWith(oldPath, item.first))
{ {
ctx.path = Subpath(oldPath, item.first); ctx.path = Subpath(oldPath, item.first);
if(item.second.second->Handle(ctx)) if(item.second->Handle(ctx))
{ {
ctx.path = oldPath; ctx.path = oldPath;
return true; return true;
@@ -79,7 +70,5 @@ bool MountableServer::Handle(ServerContext& ctx)
} }
MountableServer::~MountableServer() MountableServer::~MountableServer()
{ {
if(this->owns) delete this->root;
for(auto svr : this->servers) if(svr.second.first) delete svr.second.second;
} }
} }

View File

@@ -5,9 +5,9 @@
#include "TessesFramework/Http/HttpUtils.hpp" #include "TessesFramework/Http/HttpUtils.hpp"
namespace Tesses::Framework::Mail namespace Tesses::Framework::Mail
{ {
static void SMTP_ATTACHMENT_WRITE(std::string& myStr, Tesses::Framework::Streams::MemoryStream& strm) static void SMTP_ATTACHMENT_WRITE(std::string& myStr, std::shared_ptr<Tesses::Framework::Streams::MemoryStream> strm)
{ {
std::string txt = Tesses::Framework::Crypto::Base64_Encode(strm.GetBuffer()); std::string txt = Tesses::Framework::Crypto::Base64_Encode(strm->GetBuffer());
bool first=true; bool first=true;
size_t read; size_t read;
size_t offset = 0; size_t offset = 0;
@@ -39,40 +39,30 @@ namespace Tesses::Framework::Mail
this->text = text; this->text = text;
this->mimeType=mimeType; this->mimeType=mimeType;
} }
void SMTPStringBody::Write(Tesses::Framework::Streams::Stream* strm) void SMTPStringBody::Write(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{ {
strm->WriteBlock((const uint8_t*)this->text.c_str(),this->text.size()); strm->WriteBlock((const uint8_t*)this->text.c_str(),this->text.size());
} }
SMTPStreamBody::SMTPStreamBody(std::string mimeType,Tesses::Framework::Streams::Stream* strm, bool owns) SMTPStreamBody::SMTPStreamBody(std::string mimeType,std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
{ {
this->mimeType = mimeType; this->mimeType = mimeType;
this->stream = strm; this->stream = strm;
this->owns=owns;
} }
SMTPStreamBody::SMTPStreamBody(std::string mimeType,Tesses::Framework::Streams::Stream& strm) : SMTPStreamBody(mimeType,&strm,false)
{ void SMTPStreamBody::Write(std::shared_ptr<Tesses::Framework::Streams::Stream> strm)
}
void SMTPStreamBody::Write(Tesses::Framework::Streams::Stream* strm)
{ {
this->stream->Seek(0L,Tesses::Framework::Streams::SeekOrigin::Begin); this->stream->Seek(0L,Tesses::Framework::Streams::SeekOrigin::Begin);
this->stream->CopyTo(strm); this->stream->CopyTo(strm);
} }
SMTPStreamBody::~SMTPStreamBody() SMTPStreamBody::~SMTPStreamBody()
{ {
if(this->owns)
delete this->stream;
} }
SMTPClient::SMTPClient(Tesses::Framework::Streams::Stream* stream,bool owns) SMTPClient::SMTPClient(std::shared_ptr<Tesses::Framework::Streams::Stream> stream)
{ {
this->strm = stream; this->strm = stream;
this->owns = owns;
this->body = nullptr; this->body = nullptr;
} }
SMTPClient::SMTPClient(Tesses::Framework::Streams::Stream& strm) : SMTPClient(&strm,false)
{
}
void SMTPClient::Send() void SMTPClient::Send()
{ {
std::string emailHeaders = "EHLO "; std::string emailHeaders = "EHLO ";
@@ -112,7 +102,7 @@ namespace Tesses::Framework::Mail
emailHeaders.append("\r\nContent-Type: "); emailHeaders.append("\r\nContent-Type: ");
emailHeaders.append(this->body->mimeType); emailHeaders.append(this->body->mimeType);
emailHeaders.append("; charset=utf-8\r\n\r\n"); emailHeaders.append("; charset=utf-8\r\n\r\n");
Tesses::Framework::TextStreams::StreamWriter writer(this->strm,false); Tesses::Framework::TextStreams::StreamWriter writer(this->strm);
writer.Write(emailHeaders); writer.Write(emailHeaders);
this->body->Write(this->strm); this->body->Write(this->strm);
@@ -138,8 +128,8 @@ namespace Tesses::Framework::Mail
emailHeaders.append("\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\""); emailHeaders.append("\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"");
emailHeaders.append(name); emailHeaders.append(name);
emailHeaders.append("\"\r\n\r\n"); emailHeaders.append("\"\r\n\r\n");
Tesses::Framework::Streams::MemoryStream ms(true); std::shared_ptr<Tesses::Framework::Streams::MemoryStream> ms = std::make_shared<Tesses::Framework::Streams::MemoryStream>(true);
item.second->Write(&ms); item.second->Write(ms);
SMTP_ATTACHMENT_WRITE(emailHeaders,ms); SMTP_ATTACHMENT_WRITE(emailHeaders,ms);
//emailHeaders.append(Tesses::Framework::Crypto::Base64_Encode(ms.GetBuffer())); //emailHeaders.append(Tesses::Framework::Crypto::Base64_Encode(ms.GetBuffer()));
writer.Write(emailHeaders); writer.Write(emailHeaders);
@@ -154,10 +144,6 @@ namespace Tesses::Framework::Mail
SMTPClient::~SMTPClient() SMTPClient::~SMTPClient()
{ {
delete this->body;
for(auto& item : this->attachments)
{
delete item.second;
}
} }
} }

View File

@@ -124,7 +124,7 @@ namespace Tesses::Framework::Platform::Environment
if(!realPath.relative) return realPath; if(!realPath.relative) return realPath;
if(LocalFS.FileExists(realPath)) return realPath.MakeAbsolute(); if(LocalFS->FileExists(realPath)) return realPath.MakeAbsolute();
const char* path = std::getenv("PATH"); const char* path = std::getenv("PATH");
#if defined(_WIN32) #if defined(_WIN32)
const char* pathext = std::getenv("PATHEXT"); const char* pathext = std::getenv("PATHEXT");
@@ -134,13 +134,13 @@ namespace Tesses::Framework::Platform::Environment
for(auto item : pathParts) for(auto item : pathParts)
{ {
auto newPath = LocalFS.SystemToVFSPath(item) / realPath; auto newPath = LocalFS->SystemToVFSPath(item) / realPath;
for(auto item2 : pext) for(auto item2 : pext)
{ {
auto newPathExt = newPath + item2; auto newPathExt = newPath + item2;
if(LocalFS.FileExists(newPathExt)) return newPathExt; if(LocalFS->FileExists(newPathExt)) return newPathExt;
} }
if(LocalFS.FileExists(newPath)) return newPath; if(LocalFS->FileExists(newPath)) return newPath;
} }
return realPath; return realPath;
#else #else
@@ -148,8 +148,8 @@ namespace Tesses::Framework::Platform::Environment
auto pathParts = HttpUtils::SplitString(path,":"); auto pathParts = HttpUtils::SplitString(path,":");
for(auto item : pathParts) for(auto item : pathParts)
{ {
auto newPath = LocalFS.SystemToVFSPath(item) / realPath; auto newPath = LocalFS->SystemToVFSPath(item) / realPath;
if(LocalFS.FileExists(newPath)) return newPath; if(LocalFS->FileExists(newPath)) return newPath;
} }
return realPath.MakeAbsolute(); return realPath.MakeAbsolute();
#endif #endif

View File

@@ -685,34 +685,34 @@ CreateProcessW(
#endif #endif
} }
Tesses::Framework::Streams::Stream* Process::GetStdinStream() std::shared_ptr<Tesses::Framework::Streams::Stream> Process::GetStdinStream()
{ {
if (this->exited) return nullptr; if (this->exited) return nullptr;
#if defined(GEKKO) || defined(__PS2__) || defined(__SWITCH__) || !defined(TESSESFRAMEWORK_ENABLE_PROCESS) #if defined(GEKKO) || defined(__PS2__) || defined(__SWITCH__) || !defined(TESSESFRAMEWORK_ENABLE_PROCESS)
return nullptr; return nullptr;
#else #else
return new ProcessStream(this->hidden.GetField<ProcessData*>()->stdin_strm,true); return std::make_shared<ProcessStream>(this->hidden.GetField<ProcessData*>()->stdin_strm,true);
#endif #endif
} }
Tesses::Framework::Streams::Stream* Process::GetStdoutStream() std::shared_ptr<Tesses::Framework::Streams::Stream> Process::GetStdoutStream()
{ {
if (this->exited) return nullptr; if (this->exited) return nullptr;
#if defined(GEKKO) || defined(__PS2__) || defined(__SWITCH__) || !defined(TESSESFRAMEWORK_ENABLE_PROCESS) #if defined(GEKKO) || defined(__PS2__) || defined(__SWITCH__) || !defined(TESSESFRAMEWORK_ENABLE_PROCESS)
return nullptr; return nullptr;
#else #else
return new ProcessStream(this->hidden.GetField<ProcessData*>()->stdout_strm,false); return std::make_shared<ProcessStream>(this->hidden.GetField<ProcessData*>()->stdout_strm,false);
#endif #endif
} }
Tesses::Framework::Streams::Stream* Process::GetStderrStream() std::shared_ptr<Tesses::Framework::Streams::Stream> Process::GetStderrStream()
{ {
if (this->exited) return nullptr; if (this->exited) return nullptr;
#if defined(GEKKO) || defined(__PS2__) || defined(__SWITCH__) || !defined(TESSESFRAMEWORK_ENABLE_PROCESS) #if defined(GEKKO) || defined(__PS2__) || defined(__SWITCH__) || !defined(TESSESFRAMEWORK_ENABLE_PROCESS)
return nullptr; return nullptr;
#else #else
return new ProcessStream(this->hidden.GetField<ProcessData*>()->stderr_strm,false); return std::make_shared<ProcessStream>(this->hidden.GetField<ProcessData*>()->stderr_strm,false);
#endif #endif
} }

View File

@@ -1,18 +1,14 @@
#include "TessesFramework/Streams/BufferedStream.hpp" #include "TessesFramework/Streams/BufferedStream.hpp"
namespace Tesses::Framework::Streams { namespace Tesses::Framework::Streams {
BufferedStream::BufferedStream(Stream* strm, bool owns, size_t bufferSize) BufferedStream::BufferedStream(std::shared_ptr<Stream> strm, size_t bufferSize)
{ {
this->strm = strm; this->strm = strm;
this->owns = owns;
this->bufferSize = bufferSize; this->bufferSize = bufferSize;
this->buffer = new uint8_t[bufferSize]; this->buffer = new uint8_t[bufferSize];
this->read = 0; this->read = 0;
this->offset = 0; this->offset = 0;
} }
BufferedStream::BufferedStream(Stream& strm, size_t bufferSize) : BufferedStream(&strm,false, bufferSize)
{
}
bool BufferedStream::EndOfStream() bool BufferedStream::EndOfStream()
{ {
if(this->offset < this->read) return false; if(this->offset < this->read) return false;
@@ -60,8 +56,6 @@ namespace Tesses::Framework::Streams {
BufferedStream::~BufferedStream() BufferedStream::~BufferedStream()
{ {
if(this->owns)
delete this->strm;
delete buffer; delete buffer;
} }
} }

View File

@@ -1,19 +1,15 @@
#include "TessesFramework/Streams/ByteReader.hpp" #include "TessesFramework/Streams/ByteReader.hpp"
namespace Tesses::Framework::Streams namespace Tesses::Framework::Streams
{ {
Stream* ByteReader::GetStream() std::shared_ptr<Stream> ByteReader::GetStream()
{ {
return this->strm; return this->strm;
} }
ByteReader::ByteReader(Stream* strm, bool owns) ByteReader::ByteReader(std::shared_ptr<Stream> strm)
{ {
this->strm = strm; this->strm = strm;
this->owns = owns;
}
ByteReader::ByteReader(Stream& strm) : ByteReader(&strm,false)
{
} }
uint8_t ByteReader::ReadU8() uint8_t ByteReader::ReadU8()
{ {
auto r = this->strm->ReadByte(); auto r = this->strm->ReadByte();
@@ -153,8 +149,5 @@ namespace Tesses::Framework::Streams
auto v=ReadU64LE(); auto v=ReadU64LE();
return *(double*)&v; return *(double*)&v;
} }
ByteReader::~ByteReader()
{
if(this->owns) delete this->strm;
}
} }

View File

@@ -1,19 +1,15 @@
#include "TessesFramework/Streams/ByteWriter.hpp" #include "TessesFramework/Streams/ByteWriter.hpp"
namespace Tesses::Framework::Streams namespace Tesses::Framework::Streams
{ {
Stream* ByteWriter::GetStream() std::shared_ptr<Stream> ByteWriter::GetStream()
{ {
return this->strm; return this->strm;
} }
ByteWriter::ByteWriter(Stream* strm, bool owns) ByteWriter::ByteWriter(std::shared_ptr<Stream> strm)
{ {
this->strm = strm; this->strm = strm;
this->owns = owns;
}
ByteWriter::ByteWriter(Stream& strm) : ByteWriter(&strm,false)
{
} }
void ByteWriter::WriteU8(uint8_t v) void ByteWriter::WriteU8(uint8_t v)
{ {
strm->WriteByte(v); strm->WriteByte(v);
@@ -133,8 +129,5 @@ namespace Tesses::Framework::Streams
uint64_t data = *(uint64_t*)&v; uint64_t data = *(uint64_t*)&v;
WriteU64LE(data); WriteU64LE(data);
} }
ByteWriter::~ByteWriter()
{
if(this->owns) delete this->strm;
}
} }

View File

@@ -507,7 +507,7 @@ namespace Tesses::Framework::Streams {
NETWORK_CLOSE(this->sock); NETWORK_CLOSE(this->sock);
this->valid=false; this->valid=false;
} }
NetworkStream* TcpServer::GetStream(std::string& ip, uint16_t& port) std::shared_ptr<NetworkStream> TcpServer::GetStream(std::string& ip, uint16_t& port)
{ {
struct sockaddr_storage storage; struct sockaddr_storage storage;
memset(&storage,0, sizeof(storage)); memset(&storage,0, sizeof(storage));
@@ -522,7 +522,7 @@ namespace Tesses::Framework::Streams {
ip = StringifyIP((struct sockaddr*)&storage); ip = StringifyIP((struct sockaddr*)&storage);
port = getPort((struct sockaddr*)&storage); port = getPort((struct sockaddr*)&storage);
return new NetworkStream(s,true); return std::make_shared<NetworkStream>(s,true);
} }
bool NetworkStream::CanRead() bool NetworkStream::CanRead()
{ {
@@ -690,7 +690,7 @@ namespace Tesses::Framework::Streams {
} }
} }
NetworkStream* NetworkStream::Accept(std::string& ip, uint16_t& port) std::shared_ptr<NetworkStream> NetworkStream::Accept(std::string& ip, uint16_t& port)
{ {
if(!this->success) return nullptr; if(!this->success) return nullptr;
struct sockaddr_storage storage; struct sockaddr_storage storage;
@@ -704,7 +704,7 @@ namespace Tesses::Framework::Streams {
ip = StringifyIP((struct sockaddr*)&storage); ip = StringifyIP((struct sockaddr*)&storage);
port = getPort((struct sockaddr*)&storage); port = getPort((struct sockaddr*)&storage);
return new NetworkStream((int32_t)s,(bool)true); return std::make_shared<NetworkStream>((int32_t)s,(bool)true);
} }
size_t NetworkStream::Read(uint8_t* buff, size_t sz) size_t NetworkStream::Read(uint8_t* buff, size_t sz)
{ {
@@ -803,7 +803,7 @@ TcpServer::TcpServer(std::string unixPath,int32_t backlog)
{ {
} }
NetworkStream* TcpServer::GetStream(std::string& ip, uint16_t& port) std::shared_ptr<NetworkStream> TcpServer::GetStream(std::string& ip, uint16_t& port)
{ {
return nullptr; return nullptr;
} }
@@ -857,7 +857,7 @@ void NetworkStream::SetBroadcast(bool bC)
{ {
} }
NetworkStream* NetworkStream::Accept(std::string& ip, uint16_t& port) std::shared_ptr<NetworkStream> NetworkStream::Accept(std::string& ip, uint16_t& port)
{ {
return nullptr; return nullptr;
} }

View File

@@ -92,30 +92,22 @@ namespace Tesses::Framework::Streams {
{ {
} }
void Stream::CopyTo(Stream* strm, size_t buffSize)
{ void Stream::CopyTo(std::shared_ptr<Stream> strm, size_t buffSize)
if(strm != nullptr)
this->CopyTo(*strm, buffSize);
}
void Stream::CopyTo(Stream& strm, size_t buffSize)
{ {
size_t read; size_t read;
#if defined(_WIN32)
uint8_t* buffer = new uint8_t[buffSize]; uint8_t* buffer = new uint8_t[buffSize];
#else
uint8_t buffer[buffSize];
#endif
do { do {
read = this->Read(buffer,buffSize); read = this->Read(buffer,buffSize);
strm.WriteBlock(buffer, read); strm->WriteBlock(buffer, read);
} while(read > 0); } while(read > 0);
strm.Flush(); strm->Flush();
#if defined(_WIN32)
delete[] buffer; delete[] buffer;
#endif
} }
Stream::~Stream() Stream::~Stream()
{ {

View File

@@ -1,6 +1,7 @@
#include "TessesFramework/Common.hpp" #include "TessesFramework/Common.hpp"
#include "TessesFramework/Streams/NetworkStream.hpp" #include "TessesFramework/Streams/NetworkStream.hpp"
#include "TessesFramework/Lazy.hpp" #include "TessesFramework/Lazy.hpp"
#include "TessesFramework/Filesystem/LocalFS.hpp"
#include <atomic> #include <atomic>
#include <csignal> #include <csignal>
#include <iostream> #include <iostream>
@@ -181,7 +182,7 @@ namespace Tesses::Framework
} }
void TF_Init() void TF_Init()
{ {
Tesses::Framework::Filesystem::LocalFS = std::make_shared<Tesses::Framework::Filesystem::LocalFilesystem>();
#if defined(TESSESFRAMEWORK_ENABLE_SQLITE) #if defined(TESSESFRAMEWORK_ENABLE_SQLITE)
sqlite3_initialize(); sqlite3_initialize();
#if defined(GEKKO) || defined(__SWITCH__) || defined(__PS2__) #if defined(GEKKO) || defined(__SWITCH__) || defined(__PS2__)

View File

@@ -1,7 +1,7 @@
#include "TessesFramework/Text/HeaderGenerator.hpp" #include "TessesFramework/Text/HeaderGenerator.hpp"
namespace Tesses::Framework::Text { namespace Tesses::Framework::Text {
void GenerateCHeaderFile(Streams::Stream* strm,std::string name, TextStreams::TextWriter* writer) void GenerateCHeaderFile(std::shared_ptr<Streams::Stream> strm,std::string name, std::shared_ptr<TextStreams::TextWriter> writer)
{ {
const size_t BLK_SZ=1024; const size_t BLK_SZ=1024;
writer->WriteLine("#pragma once"); writer->WriteLine("#pragma once");
@@ -48,22 +48,22 @@ namespace Tesses::Framework::Text {
} }
std::string GenerateCHeaderFile(Streams::Stream* strm,std::string name) std::string GenerateCHeaderFile(std::shared_ptr<Streams::Stream> strm,std::string name)
{ {
TextStreams::StringWriter writer; auto writer=std::make_shared<TextStreams::StringWriter>();
GenerateCHeaderFile(strm,name,&writer); GenerateCHeaderFile(strm,name,writer);
return writer.GetString(); return writer->GetString();
} }
void GenerateCHeaderFile(const std::vector<uint8_t>& data,std::string name, TextStreams::TextWriter* writer) void GenerateCHeaderFile(const std::vector<uint8_t>& data,std::string name, std::shared_ptr<TextStreams::TextWriter> writer)
{ {
Tesses::Framework::Streams::MemoryStream ms(false); auto ms = std::make_shared<Tesses::Framework::Streams::MemoryStream>(false);
ms.GetBuffer() = data; ms->GetBuffer() = data;
GenerateCHeaderFile(&ms,name,writer); GenerateCHeaderFile(ms,name,writer);
} }
std::string GenerateCHeaderFile(const std::vector<uint8_t>& data,std::string name) std::string GenerateCHeaderFile(const std::vector<uint8_t>& data,std::string name)
{ {
TextStreams::StringWriter writer; auto writer = std::make_shared<TextStreams::StringWriter>();
GenerateCHeaderFile(data,name,&writer); GenerateCHeaderFile(data,name,writer);
return writer.GetString(); return writer->GetString();
} }
}; };

View File

@@ -4,11 +4,8 @@ using Stream = Tesses::Framework::Streams::Stream;
using FileStream = Tesses::Framework::Streams::FileStream; using FileStream = Tesses::Framework::Streams::FileStream;
namespace Tesses::Framework::TextStreams { namespace Tesses::Framework::TextStreams {
StreamReader::StreamReader(Stream& strm) : StreamReader(&strm, false)
{ StreamReader::StreamReader(std::filesystem::path path) : StreamReader(std::make_shared<FileStream>(path,"rb"))
}
StreamReader::StreamReader(std::filesystem::path path) : StreamReader(new FileStream(path,"rb"),true)
{ {
} }
@@ -21,35 +18,30 @@ namespace Tesses::Framework::TextStreams {
} }
return false; return false;
} }
StreamReader::StreamReader(Stream* strm, bool owns) : TextReader() StreamReader::StreamReader(std::shared_ptr<Stream> strm) : TextReader()
{ {
this->strm = strm; this->strm = strm;
this->owns = owns;
} }
Stream& StreamReader::GetStream() std::shared_ptr<Stream> StreamReader::GetStream()
{ {
return *(this->strm); return (this->strm);
} }
bool StreamReader::ReadBlock(std::string& str, size_t len) bool StreamReader::ReadBlock(std::string& str, size_t len)
{ {
#if defined(_WIN32)
uint8_t* buff = new uint8_t[len]; uint8_t* buff = new uint8_t[len];
#else
uint8_t buff[len];
#endif
len = strm->ReadBlock(buff,len); len = strm->ReadBlock(buff,len);
if(len == 0) return false; if(len == 0) {delete buff; return false;}
str.append((const char*)buff, len); str.append((const char*)buff, len);
#if defined(_WIN32)
delete buff; delete buff;
#endif
return true; return true;
} }
StreamReader::~StreamReader() StreamReader::~StreamReader()
{ {
if(this->owns)
delete this->strm;
} }
}; };

View File

@@ -5,20 +5,16 @@ using FileStream = Tesses::Framework::Streams::FileStream;
namespace Tesses::Framework::TextStreams namespace Tesses::Framework::TextStreams
{ {
Stream& StreamWriter::GetStream() std::shared_ptr<Stream> StreamWriter::GetStream()
{ {
return *(this->strm); return this->strm;
} }
StreamWriter::StreamWriter(Stream& strm) : StreamWriter(&strm, false) StreamWriter::StreamWriter(std::shared_ptr<Stream> strm) : TextWriter()
{ {
}
StreamWriter::StreamWriter(Stream* strm, bool owns) : TextWriter()
{
this->strm = strm; this->strm = strm;
this->owns = owns;
} }
StreamWriter::StreamWriter(std::filesystem::path filename, bool append) : StreamWriter(new FileStream(filename, append ? "ab" : "wb"),true) StreamWriter::StreamWriter(std::filesystem::path filename, bool append) : StreamWriter(std::make_shared<FileStream>(filename, append ? "ab" : "wb"))
{ {
} }
@@ -28,7 +24,5 @@ namespace Tesses::Framework::TextStreams
} }
StreamWriter::~StreamWriter() StreamWriter::~StreamWriter()
{ {
if(this->owns)
delete this->strm;
} }
} }

View File

@@ -1,231 +0,0 @@
#include "TessesFramework/TessesFramework.hpp"
#include "TessesFramework/TessesFramework.h"
#include <iostream>
using namespace Tesses::Framework;
using namespace Tesses::Framework::Streams;
using namespace Tesses::Framework::Filesystem;
using namespace Tesses::Framework::Threading;
#if defined(__cplusplus)
extern "C" {
#endif
string_t* string_create()
{
return static_cast<string_t*>(new std::string());
}
string_t* string_create_from_buff(const void* text, size_t len)
{
return static_cast<string_t*>(new std::string((const char*)text,len));
}
string_t* string_create_from_charpointer(const char* text)
{
return static_cast<string_t*>(new std::string(text));
}
string_t* string_resize(string_t* str, size_t len)
{
static_cast<std::string*>(str)->resize(len);
return str;
}
string_t* string_set_char(string_t* str, size_t index, char c)
{
static_cast<std::string*>(str)->at(index) = c;
return str;
}
char string_get_char(string_t* str,size_t index)
{
return static_cast<std::string*>(str)->at(index);
}
string_t* string_append_char(string_t* str, char c)
{
static_cast<std::string*>(str)->push_back(c);
return str;
}
string_t* string_append_from_buff(string_t* str,const void* text, size_t len)
{
static_cast<std::string*>(str)->append((const char*)text,len);
return str;
}
string_t* string_append_from_charpointer(string_t* str,const char* text)
{
static_cast<std::string*>(str)->append(text);
return str;
}
string_t* string_append(string_t* str, string_t* toAppend)
{
if(str == NULL) return NULL;
static_cast<std::string*>(str)->append(*static_cast<std::string*>(str));
return str;
}
string_t* string_append_signed(string_t* str, int64_t num)
{
static_cast<std::string*>(str)->append(std::to_string(num));
return str;
}
string_t* string_append_unsigned(string_t* str, uint64_t num)
{
static_cast<std::string*>(str)->append(std::to_string(num));
return str;
}
string_t* string_append_double(string_t* str, double num)
{
static_cast<std::string*>(str)->append(std::to_string(num));
return str;
}
void string_print(string_t* str)
{
std::cout << *static_cast<std::string*>(str);
}
void string_println(string_t* str)
{
std::cout << *static_cast<std::string*>(str) << std::endl;
}
size_t string_size(string_t* str)
{
return static_cast<std::string*>(str)->size();
}
const char* string_c_str(string_t* str)
{
return static_cast<std::string*>(str)->c_str();
}
void string_free(string_t* str)
{
delete static_cast<std::string*>(str);
}
void tf_init()
{
TF_Init();
}
tf_thread_t* tf_create_thread(void* userData, tf_action_user_data_t cb)
{
Thread* thrd = new Thread([userData,cb]()->void{
cb(userData);
});
return static_cast<tf_thread_t*>(thrd);
}
void tf_join_thread(tf_thread_t* thrd)
{
auto thrd2 = static_cast<Thread*>(thrd);
if(thrd2 != nullptr)
{
thrd2->Join();
delete thrd2;
}
}
void tf_detach_thread(tf_thread_t* thrd)
{
auto thrd2 = static_cast<Thread*>(thrd);
if(thrd2 != nullptr)
{
thrd2->Detach();
delete thrd2;
}
}
tf_mutex_t* tf_mutex_create()
{
return static_cast<tf_mutex_t*>(new Mutex());
}
void tf_mutex_lock(tf_mutex_t* mtx)
{
static_cast<Mutex*>(mtx)->Lock();
}
bool tf_mutex_trylock(tf_mutex_t* mtx)
{
return static_cast<Mutex*>(mtx)->TryLock();
}
void tf_mutex_unlock(tf_mutex_t* mtx)
{
static_cast<Mutex*>(mtx)->Unlock();
}
void tf_mutex_free(tf_mutex_t* mtx)
{
delete static_cast<Mutex*>(mtx);
}
bool tf_stream_canread(tf_stream_t* strm)
{
return static_cast<Stream*>(strm)->CanRead();
}
bool tf_stream_canwrite(tf_stream_t* strm)
{
return static_cast<Stream*>(strm)->CanWrite();
}
bool tf_stream_canseek(tf_stream_t* strm)
{
return static_cast<Stream*>(strm)->CanSeek();
}
bool tf_stream_eof(tf_stream_t* strm)
{
return static_cast<Stream*>(strm)->EndOfStream();
}
int64_t tf_stream_getlen(tf_stream_t* strm)
{
return static_cast<Stream*>(strm)->GetLength();
}
int64_t tf_stream_getpos(tf_stream_t* strm)
{
return static_cast<Stream*>(strm)->GetPosition();
}
void tf_stream_seek(tf_stream_t* strm, int64_t pos, TF_WHENCE whence)
{
static_cast<Stream*>(strm)->Seek(pos,whence == TF_SEEK_BEGIN ? SeekOrigin::Begin : whence == TF_SEEK_CURRENT ? SeekOrigin::Current : SeekOrigin::End);
}
size_t tf_stream_read(tf_stream_t* strm, uint8_t* buffer, size_t length)
{
return static_cast<Stream*>(strm)->Read(buffer,length);
}
size_t tf_stream_write(tf_stream_t* strm, const uint8_t* buffer, size_t length)
{
return static_cast<Stream*>(strm)->Write(buffer,length);
}
size_t tf_stream_readblock(tf_stream_t* strm, uint8_t* buffer, size_t length)
{
return static_cast<Stream*>(strm)->ReadBlock(buffer,length);
}
void tf_stream_writeblock(tf_stream_t* strm, const uint8_t* buffer, size_t length)
{
static_cast<Stream*>(strm)->WriteBlock(buffer,length);
}
void tf_stream_copyto(tf_stream_t* src, tf_stream_t* dest, size_t blockSize)
{
static_cast<Stream*>(src)->CopyTo(static_cast<Stream*>(dest),blockSize);
}
void tf_stream_close(tf_stream_t* strm)
{
delete static_cast<Stream*>(strm);
}
void tf_stream_flush(tf_stream_t* strm)
{
static_cast<Stream*>(strm)->Flush();
}
int32_t tf_stream_readbyte(tf_stream_t* strm)
{
return static_cast<Stream*>(strm)->ReadByte();
}
void tf_stream_writebyte(tf_stream_t* strm, uint8_t val)
{
static_cast<Stream*>(strm)->WriteByte(val);
}
tf_stream_t* tf_stream_fopen(const char* file, const char* mode)
{
FILE* f = fopen(file,mode);
if(f == NULL) return NULL;
return static_cast<tf_stream_t*>(new FileStream(f,true,std::string(mode)));
}
#if defined(__cplusplus)
}
#endif