initial commit, 4.5 stable
Some checks failed
🔗 GHA / 📊 Static checks (push) Has been cancelled
🔗 GHA / 🤖 Android (push) Has been cancelled
🔗 GHA / 🍏 iOS (push) Has been cancelled
🔗 GHA / 🐧 Linux (push) Has been cancelled
🔗 GHA / 🍎 macOS (push) Has been cancelled
🔗 GHA / 🏁 Windows (push) Has been cancelled
🔗 GHA / 🌐 Web (push) Has been cancelled

This commit is contained in:
2025-09-16 20:46:46 -04:00
commit 9d30169a8d
13378 changed files with 7050105 additions and 0 deletions

6
drivers/unix/SCsub Normal file
View File

@@ -0,0 +1,6 @@
#!/usr/bin/env python
from misc.utility.scons_hints import *
Import("env")
env.add_source_files(env.drivers_sources, "*.cpp")

View File

@@ -0,0 +1,750 @@
/**************************************************************************/
/* dir_access_unix.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "dir_access_unix.h"
#if defined(UNIX_ENABLED)
#include "core/os/memory.h"
#include "core/os/os.h"
#include "core/string/print_string.h"
#include "core/templates/list.h"
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#ifdef __linux__
#include <sys/statfs.h>
#endif
#include <sys/statvfs.h>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#if __has_include(<mntent.h>)
#include <mntent.h>
#endif
Error DirAccessUnix::list_dir_begin() {
list_dir_end(); //close any previous dir opening!
//char real_current_dir_name[2048]; //is this enough?!
//getcwd(real_current_dir_name,2048);
//chdir(current_path.utf8().get_data());
dir_stream = opendir(current_dir.utf8().get_data());
//chdir(real_current_dir_name);
if (!dir_stream) {
return ERR_CANT_OPEN; //error!
}
return OK;
}
bool DirAccessUnix::file_exists(String p_file) {
GLOBAL_LOCK_FUNCTION
if (p_file.is_relative_path()) {
p_file = current_dir.path_join(p_file);
}
p_file = fix_path(p_file);
struct stat flags = {};
bool success = (stat(p_file.utf8().get_data(), &flags) == 0);
if (success && S_ISDIR(flags.st_mode)) {
success = false;
}
return success;
}
bool DirAccessUnix::dir_exists(String p_dir) {
GLOBAL_LOCK_FUNCTION
if (p_dir.is_relative_path()) {
p_dir = get_current_dir().path_join(p_dir);
}
p_dir = fix_path(p_dir);
struct stat flags = {};
bool success = (stat(p_dir.utf8().get_data(), &flags) == 0);
return (success && S_ISDIR(flags.st_mode));
}
bool DirAccessUnix::is_readable(String p_dir) {
GLOBAL_LOCK_FUNCTION
if (p_dir.is_relative_path()) {
p_dir = get_current_dir().path_join(p_dir);
}
p_dir = fix_path(p_dir);
return (access(p_dir.utf8().get_data(), R_OK) == 0);
}
bool DirAccessUnix::is_writable(String p_dir) {
GLOBAL_LOCK_FUNCTION
if (p_dir.is_relative_path()) {
p_dir = get_current_dir().path_join(p_dir);
}
p_dir = fix_path(p_dir);
return (access(p_dir.utf8().get_data(), W_OK) == 0);
}
uint64_t DirAccessUnix::get_modified_time(String p_file) {
if (p_file.is_relative_path()) {
p_file = current_dir.path_join(p_file);
}
p_file = fix_path(p_file);
struct stat flags = {};
bool success = (stat(p_file.utf8().get_data(), &flags) == 0);
if (success) {
return flags.st_mtime;
} else {
ERR_FAIL_V(0);
}
return 0;
}
String DirAccessUnix::get_next() {
if (!dir_stream) {
return "";
}
dirent *entry = readdir(dir_stream);
if (entry == nullptr) {
list_dir_end();
return "";
}
String fname = fix_unicode_name(entry->d_name);
// Look at d_type to determine if the entry is a directory, unless
// its type is unknown (the file system does not support it) or if
// the type is a link, in that case we want to resolve the link to
// known if it points to a directory. stat() will resolve the link
// for us.
if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK) {
String f = current_dir.path_join(fname);
struct stat flags = {};
if (stat(f.utf8().get_data(), &flags) == 0) {
_cisdir = S_ISDIR(flags.st_mode);
} else {
_cisdir = false;
}
} else {
_cisdir = (entry->d_type == DT_DIR);
}
_cishidden = is_hidden(fname);
return fname;
}
bool DirAccessUnix::current_is_dir() const {
return _cisdir;
}
bool DirAccessUnix::current_is_hidden() const {
return _cishidden;
}
void DirAccessUnix::list_dir_end() {
if (dir_stream) {
closedir(dir_stream);
}
dir_stream = nullptr;
_cisdir = false;
}
#if __has_include(<mntent.h>) && defined(LINUXBSD_ENABLED)
static bool _filter_drive(struct mntent *mnt) {
// Ignore devices that don't point to /dev
if (strncmp(mnt->mnt_fsname, "/dev", 4) != 0) {
return false;
}
// Accept devices mounted at common locations
if (strncmp(mnt->mnt_dir, "/media", 6) == 0 ||
strncmp(mnt->mnt_dir, "/mnt", 4) == 0 ||
strncmp(mnt->mnt_dir, "/home", 5) == 0 ||
strncmp(mnt->mnt_dir, "/run/media", 10) == 0) {
return true;
}
// Ignore everything else
return false;
}
#endif
static void _get_drives(List<String> *list) {
// Add root.
list->push_back("/");
#if __has_include(<mntent.h>) && defined(LINUXBSD_ENABLED)
// Check /etc/mtab for the list of mounted partitions.
FILE *mtab = setmntent("/etc/mtab", "r");
if (mtab) {
struct mntent mnt;
char strings[4096];
while (getmntent_r(mtab, &mnt, strings, sizeof(strings))) {
if (mnt.mnt_dir != nullptr && _filter_drive(&mnt)) {
// Avoid duplicates
String name = String::utf8(mnt.mnt_dir);
if (!list->find(name)) {
list->push_back(name);
}
}
}
endmntent(mtab);
}
#endif
// Add $HOME.
const char *home = getenv("HOME");
if (home) {
// Only add if it's not a duplicate
String home_name = String::utf8(home);
if (!list->find(home_name)) {
list->push_back(home_name);
}
// Check GTK+3 bookmarks for both XDG locations (Documents, Downloads, etc.)
// and potential user-defined bookmarks.
char path[1024];
snprintf(path, 1024, "%s/.config/gtk-3.0/bookmarks", home);
FILE *fd = fopen(path, "r");
if (fd) {
char string[1024];
while (fgets(string, 1024, fd)) {
// Parse only file:// links
if (strncmp(string, "file://", 7) == 0) {
// Strip any unwanted edges on the strings and push_back if it's not a duplicate.
String fpath = String::utf8(string + 7).strip_edges().split_spaces()[0].uri_file_decode();
if (!list->find(fpath)) {
list->push_back(fpath);
}
}
}
fclose(fd);
}
// Add Desktop dir.
String dpath = OS::get_singleton()->get_system_dir(OS::SystemDir::SYSTEM_DIR_DESKTOP);
if (dpath.length() > 0 && !list->find(dpath)) {
list->push_back(dpath);
}
}
list->sort();
}
int DirAccessUnix::get_drive_count() {
List<String> list;
_get_drives(&list);
return list.size();
}
String DirAccessUnix::get_drive(int p_drive) {
List<String> list;
_get_drives(&list);
ERR_FAIL_INDEX_V(p_drive, list.size(), "");
return list.get(p_drive);
}
int DirAccessUnix::get_current_drive() {
int drive = 0;
int max_length = -1;
const String path = get_current_dir().to_lower();
for (int i = 0; i < get_drive_count(); i++) {
const String d = get_drive(i).to_lower();
if (max_length < d.length() && path.begins_with(d)) {
max_length = d.length();
drive = i;
}
}
return drive;
}
bool DirAccessUnix::drives_are_shortcuts() {
return true;
}
Error DirAccessUnix::make_dir(String p_dir) {
GLOBAL_LOCK_FUNCTION
if (p_dir.is_relative_path()) {
p_dir = get_current_dir().path_join(p_dir);
}
p_dir = fix_path(p_dir);
bool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
int err = errno;
if (success) {
return OK;
}
if (err == EEXIST) {
return ERR_ALREADY_EXISTS;
}
return ERR_CANT_CREATE;
}
Error DirAccessUnix::change_dir(String p_dir) {
GLOBAL_LOCK_FUNCTION
p_dir = fix_path(p_dir);
// prev_dir is the directory we are changing out of
String prev_dir;
char real_current_dir_name[2048];
ERR_FAIL_NULL_V(getcwd(real_current_dir_name, 2048), ERR_BUG);
if (prev_dir.append_utf8(real_current_dir_name) != OK) {
prev_dir = real_current_dir_name; //no utf8, maybe latin?
}
// try_dir is the directory we are trying to change into
String try_dir = "";
if (p_dir.is_relative_path()) {
String next_dir = current_dir.path_join(p_dir);
next_dir = next_dir.simplify_path();
try_dir = next_dir;
} else {
try_dir = p_dir;
}
bool worked = (chdir(try_dir.utf8().get_data()) == 0); // we can only give this utf8
if (!worked) {
return ERR_INVALID_PARAMETER;
}
String base = _get_root_path();
if (!base.is_empty() && !try_dir.begins_with(base)) {
ERR_FAIL_NULL_V(getcwd(real_current_dir_name, 2048), ERR_BUG);
String new_dir;
new_dir.append_utf8(real_current_dir_name);
if (!new_dir.begins_with(base)) {
try_dir = current_dir; //revert
}
}
// the directory exists, so set current_dir to try_dir
current_dir = try_dir;
ERR_FAIL_COND_V(chdir(prev_dir.utf8().get_data()) != 0, ERR_BUG);
return OK;
}
String DirAccessUnix::get_current_dir(bool p_include_drive) const {
String base = _get_root_path();
if (!base.is_empty()) {
String bd = current_dir.replace_first(base, "");
if (bd.begins_with("/")) {
return _get_root_string() + bd.substr(1);
} else {
return _get_root_string() + bd;
}
}
return current_dir;
}
Error DirAccessUnix::rename(String p_path, String p_new_path) {
if (p_path.is_relative_path()) {
p_path = get_current_dir().path_join(p_path);
}
p_path = fix_path(p_path);
if (p_path.ends_with("/")) {
p_path = p_path.left(-1);
}
if (p_new_path.is_relative_path()) {
p_new_path = get_current_dir().path_join(p_new_path);
}
p_new_path = fix_path(p_new_path);
if (p_new_path.ends_with("/")) {
p_new_path = p_new_path.left(-1);
}
int res = ::rename(p_path.utf8().get_data(), p_new_path.utf8().get_data());
if (res != 0 && errno == EXDEV) { // Cross-device move, use copy and remove.
Error err = OK;
err = copy(p_path, p_new_path);
if (err != OK) {
return err;
}
return remove(p_path);
} else {
return (res == 0) ? OK : FAILED;
}
}
Error DirAccessUnix::remove(String p_path) {
if (p_path.is_relative_path()) {
p_path = get_current_dir().path_join(p_path);
}
p_path = fix_path(p_path);
if (p_path.ends_with("/")) {
p_path = p_path.left(-1);
}
struct stat flags = {};
if (lstat(p_path.utf8().get_data(), &flags) != 0) {
return FAILED;
}
int err;
if (S_ISDIR(flags.st_mode) && !is_link(p_path)) {
err = ::rmdir(p_path.utf8().get_data());
} else {
err = ::unlink(p_path.utf8().get_data());
}
if (err != 0) {
return FAILED;
}
if (remove_notification_func != nullptr) {
remove_notification_func(p_path);
}
return OK;
}
bool DirAccessUnix::is_link(String p_file) {
if (p_file.is_relative_path()) {
p_file = get_current_dir().path_join(p_file);
}
p_file = fix_path(p_file);
if (p_file.ends_with("/")) {
p_file = p_file.left(-1);
}
struct stat flags = {};
if (lstat(p_file.utf8().get_data(), &flags) != 0) {
return false;
}
return S_ISLNK(flags.st_mode);
}
String DirAccessUnix::read_link(String p_file) {
if (p_file.is_relative_path()) {
p_file = get_current_dir().path_join(p_file);
}
p_file = fix_path(p_file);
if (p_file.ends_with("/")) {
p_file = p_file.left(-1);
}
char buf[PATH_MAX];
memset(buf, 0, PATH_MAX);
ssize_t len = readlink(p_file.utf8().get_data(), buf, sizeof(buf));
String link;
if (len > 0) {
link.append_utf8(buf, len);
}
return link;
}
Error DirAccessUnix::create_link(String p_source, String p_target) {
if (p_target.is_relative_path()) {
p_target = get_current_dir().path_join(p_target);
}
p_source = fix_path(p_source);
p_target = fix_path(p_target);
if (symlink(p_source.utf8().get_data(), p_target.utf8().get_data()) == 0) {
return OK;
} else {
return FAILED;
}
}
uint64_t DirAccessUnix::get_space_left() {
struct statvfs vfs;
if (statvfs(current_dir.utf8().get_data(), &vfs) != 0) {
return 0;
}
return (uint64_t)vfs.f_bavail * (uint64_t)vfs.f_frsize;
}
String DirAccessUnix::get_filesystem_type() const {
#ifdef __linux__
struct statfs fs;
if (statfs(current_dir.utf8().get_data(), &fs) != 0) {
return "";
}
switch (static_cast<unsigned int>(fs.f_type)) {
case 0x0000adf5:
return "ADFS";
case 0x0000adff:
return "AFFS";
case 0x5346414f:
return "AFS";
case 0x00000187:
return "AUTOFS";
case 0x00c36400:
return "CEPH";
case 0x73757245:
return "CODA";
case 0x28cd3d45:
return "CRAMFS";
case 0x453dcd28:
return "CRAMFS";
case 0x64626720:
return "DEBUGFS";
case 0x73636673:
return "SECURITYFS";
case 0xf97cff8c:
return "SELINUX";
case 0x43415d53:
return "SMACK";
case 0x858458f6:
return "RAMFS";
case 0x01021994:
return "TMPFS";
case 0x958458f6:
return "HUGETLBFS";
case 0x73717368:
return "SQUASHFS";
case 0x0000f15f:
return "ECRYPTFS";
case 0x00414a53:
return "EFS";
case 0xe0f5e1e2:
return "EROFS";
case 0x0000ef53:
return "EXTFS";
case 0xabba1974:
return "XENFS";
case 0x9123683e:
return "BTRFS";
case 0x00003434:
return "NILFS";
case 0xf2f52010:
return "F2FS";
case 0xf995e849:
return "HPFS";
case 0x00009660:
return "ISOFS";
case 0x000072b6:
return "JFFS2";
case 0x58465342:
return "XFS";
case 0x6165676c:
return "PSTOREFS";
case 0xde5e81e4:
return "EFIVARFS";
case 0x00c0ffee:
return "HOSTFS";
case 0x794c7630:
return "OVERLAYFS";
case 0x65735546:
return "FUSE";
case 0xca451a4e:
return "BCACHEFS";
case 0x00004d44:
return "FAT32";
case 0x2011bab0:
return "EXFAT";
case 0x0000564c:
return "NCP";
case 0x00006969:
return "NFS";
case 0x7461636f:
return "OCFS2";
case 0x00009fa1:
return "OPENPROM";
case 0x0000002f:
return "QNX4";
case 0x68191122:
return "QNX6";
case 0x6b414653:
return "AFS";
case 0x52654973:
return "REISERFS";
case 0x0000517b:
return "SMB";
case 0xff534d42:
return "CIFS";
case 0x0027e0eb:
return "CGROUP";
case 0x63677270:
return "CGROUP2";
case 0x07655821:
return "RDTGROUP";
case 0x74726163:
return "TRACEFS";
case 0x01021997:
return "V9FS";
case 0x62646576:
return "BDEVFS";
case 0x64646178:
return "DAXFS";
case 0x42494e4d:
return "BINFMTFS";
case 0x00001cd1:
return "DEVPTS";
case 0x6c6f6f70:
return "BINDERFS";
case 0x0bad1dea:
return "FUTEXFS";
case 0x50495045:
return "PIPEFS";
case 0x00009fa0:
return "PROC";
case 0x534f434b:
return "SOCKFS";
case 0x62656572:
return "SYSFS";
case 0x00009fa2:
return "USBDEVICE";
case 0x11307854:
return "MTD_INODE";
case 0x09041934:
return "ANON_INODE";
case 0x73727279:
return "BTRFS";
case 0x6e736673:
return "NSFS";
case 0xcafe4a11:
return "BPF_FS";
case 0x5a3c69f0:
return "AAFS";
case 0x5a4f4653:
return "ZONEFS";
case 0x15013346:
return "UDF";
case 0x444d4142:
return "DMA_BUF";
case 0x454d444d:
return "DEVMEM";
case 0x5345434d:
return "SECRETMEM";
case 0x50494446:
return "PID_FS";
default:
return "";
}
#else
return ""; //TODO this should be implemented
#endif
}
bool DirAccessUnix::is_hidden(const String &p_name) {
return p_name != "." && p_name != ".." && p_name.begins_with(".");
}
bool DirAccessUnix::is_case_sensitive(const String &p_path) const {
#if defined(LINUXBSD_ENABLED)
String f = p_path;
if (!f.is_absolute_path()) {
f = get_current_dir().path_join(f);
}
f = fix_path(f);
int fd = ::open(f.utf8().get_data(), O_RDONLY | O_NONBLOCK);
if (fd) {
long flags = 0;
if (ioctl(fd, _IOR('f', 1, long), &flags) >= 0) {
::close(fd);
return !(flags & 0x40000000 /* FS_CASEFOLD_FL */);
}
::close(fd);
}
#endif
return true;
}
bool DirAccessUnix::is_equivalent(const String &p_path_a, const String &p_path_b) const {
String f1 = fix_path(p_path_a);
struct stat st1 = {};
int err = stat(f1.utf8().get_data(), &st1);
if (err) {
return DirAccess::is_equivalent(p_path_a, p_path_b);
}
String f2 = fix_path(p_path_b);
struct stat st2 = {};
err = stat(f2.utf8().get_data(), &st2);
if (err) {
return DirAccess::is_equivalent(p_path_a, p_path_b);
}
return (st1.st_dev == st2.st_dev) && (st1.st_ino == st2.st_ino);
}
DirAccessUnix::DirAccessUnix() {
dir_stream = nullptr;
_cisdir = false;
/* determine drive count */
// set current directory to an absolute path of the current directory
char real_current_dir_name[2048];
ERR_FAIL_NULL(getcwd(real_current_dir_name, 2048));
current_dir.clear();
if (current_dir.append_utf8(real_current_dir_name) != OK) {
current_dir = real_current_dir_name;
}
change_dir(current_dir);
}
DirAccessUnix::RemoveNotificationFunc DirAccessUnix::remove_notification_func = nullptr;
DirAccessUnix::~DirAccessUnix() {
list_dir_end();
}
#endif // UNIX_ENABLED

View File

@@ -0,0 +1,99 @@
/**************************************************************************/
/* dir_access_unix.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#if defined(UNIX_ENABLED)
#include "core/io/dir_access.h"
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
class DirAccessUnix : public DirAccess {
GDSOFTCLASS(DirAccessUnix, DirAccess);
DIR *dir_stream = nullptr;
bool _cisdir = false;
bool _cishidden = false;
protected:
String current_dir;
virtual String fix_unicode_name(const char *p_name) const { return String::utf8(p_name); }
virtual bool is_hidden(const String &p_name);
public:
typedef void (*RemoveNotificationFunc)(const String &p_file);
static RemoveNotificationFunc remove_notification_func;
virtual Error list_dir_begin() override; ///< This starts dir listing
virtual String get_next() override;
virtual bool current_is_dir() const override;
virtual bool current_is_hidden() const override;
virtual void list_dir_end() override; ///<
virtual int get_drive_count() override;
virtual String get_drive(int p_drive) override;
virtual int get_current_drive() override;
virtual bool drives_are_shortcuts() override;
virtual Error change_dir(String p_dir) override; ///< can be relative or absolute, return false on success
virtual String get_current_dir(bool p_include_drive = true) const override; ///< return current dir location
virtual Error make_dir(String p_dir) override;
virtual bool file_exists(String p_file) override;
virtual bool dir_exists(String p_dir) override;
virtual bool is_readable(String p_dir) override;
virtual bool is_writable(String p_dir) override;
virtual uint64_t get_modified_time(String p_file);
virtual Error rename(String p_path, String p_new_path) override;
virtual Error remove(String p_path) override;
virtual bool is_link(String p_file) override;
virtual String read_link(String p_file) override;
virtual Error create_link(String p_source, String p_target) override;
virtual bool is_case_sensitive(const String &p_path) const override;
virtual bool is_equivalent(const String &p_path_a, const String &p_path_b) const override;
virtual uint64_t get_space_left() override;
virtual String get_filesystem_type() const override;
DirAccessUnix();
~DirAccessUnix();
};
#endif // UNIX_ENABLED

View File

@@ -0,0 +1,511 @@
/**************************************************************************/
/* file_access_unix.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "file_access_unix.h"
#if defined(UNIX_ENABLED)
#include "core/os/os.h"
#include "core/string/print_string.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#if defined(TOOLS_ENABLED)
#include <climits>
#include <cstdlib>
#endif
void FileAccessUnix::check_errors(bool p_write) const {
ERR_FAIL_NULL_MSG(f, "File must be opened before use.");
last_error = OK;
if (ferror(f)) {
if (p_write) {
last_error = ERR_FILE_CANT_WRITE;
} else {
last_error = ERR_FILE_CANT_READ;
}
}
if (!p_write && feof(f)) {
last_error = ERR_FILE_EOF;
}
}
Error FileAccessUnix::open_internal(const String &p_path, int p_mode_flags) {
_close();
path_src = p_path;
path = fix_path(p_path);
//printf("opening %s, %i\n", path.utf8().get_data(), Memory::get_static_mem_usage());
ERR_FAIL_COND_V_MSG(f, ERR_ALREADY_IN_USE, "File is already in use.");
const char *mode_string;
if (p_mode_flags == READ) {
mode_string = "rb";
} else if (p_mode_flags == WRITE) {
mode_string = "wb";
} else if (p_mode_flags == READ_WRITE) {
mode_string = "rb+";
} else if (p_mode_flags == WRITE_READ) {
mode_string = "wb+";
} else {
return ERR_INVALID_PARAMETER;
}
/* pretty much every implementation that uses fopen as primary
backend (unix-compatible mostly) supports utf8 encoding */
//printf("opening %s as %s\n", p_path.utf8().get_data(), path.utf8().get_data());
struct stat st = {};
int err = stat(path.utf8().get_data(), &st);
if (!err) {
switch (st.st_mode & S_IFMT) {
case S_IFLNK:
case S_IFREG:
break;
default:
return ERR_FILE_CANT_OPEN;
}
}
#if defined(TOOLS_ENABLED)
if (p_mode_flags & READ) {
String real_path = get_real_path();
if (real_path != path) {
// Don't warn on symlinks, since they can be used to simply share addons on multiple projects.
if (real_path.to_lower() == path.to_lower()) {
// The File system is case insensitive, but other platforms can be sensitive to it
// To ease cross-platform development, we issue a warning if users try to access
// a file using the wrong case (which *works* on Windows and macOS, but won't on other
// platforms).
WARN_PRINT(vformat("Case mismatch opening requested file '%s', stored as '%s' in the filesystem. This file will not open when exported to other case-sensitive platforms.", path, real_path));
}
}
}
#endif
if (is_backup_save_enabled() && (p_mode_flags == WRITE)) {
// Set save path to the symlink target, not the link itself.
String link;
bool is_link = false;
{
CharString cs = path.utf8();
struct stat lst = {};
if (lstat(cs.get_data(), &lst) == 0) {
is_link = S_ISLNK(lst.st_mode);
}
if (is_link) {
char buf[PATH_MAX];
memset(buf, 0, PATH_MAX);
ssize_t len = readlink(cs.get_data(), buf, sizeof(buf));
if (len > 0) {
link.append_utf8(buf, len);
}
if (!link.is_absolute_path()) {
link = path.get_base_dir().path_join(link);
}
}
}
save_path = is_link ? link : path;
// Create a temporary file in the same directory as the target file.
path = path + "-XXXXXX";
CharString cs = path.utf8();
int fd = mkstemp(cs.ptrw());
if (fd == -1) {
last_error = ERR_FILE_CANT_OPEN;
return last_error;
}
fchmod(fd, 0644);
path = String::utf8(cs.ptr());
f = fdopen(fd, mode_string);
if (f == nullptr) {
// Delete temp file and close descriptor if open failed.
::unlink(cs.ptr());
::close(fd);
last_error = ERR_FILE_CANT_OPEN;
return last_error;
}
} else {
f = fopen(path.utf8().get_data(), mode_string);
}
if (f == nullptr) {
switch (errno) {
case ENOENT: {
last_error = ERR_FILE_NOT_FOUND;
} break;
default: {
last_error = ERR_FILE_CANT_OPEN;
} break;
}
return last_error;
}
// Set close on exec to avoid leaking it to subprocesses.
int fd = fileno(f);
if (fd != -1) {
int opts = fcntl(fd, F_GETFD);
fcntl(fd, F_SETFD, opts | FD_CLOEXEC);
}
last_error = OK;
flags = p_mode_flags;
return OK;
}
void FileAccessUnix::_close() {
if (!f) {
return;
}
fclose(f);
f = nullptr;
if (close_notification_func) {
close_notification_func(path, flags);
}
if (!save_path.is_empty()) {
int rename_error = rename(path.utf8().get_data(), save_path.utf8().get_data());
if (rename_error && close_fail_notify) {
close_fail_notify(save_path);
}
save_path = "";
ERR_FAIL_COND(rename_error != 0);
}
}
bool FileAccessUnix::is_open() const {
return (f != nullptr);
}
String FileAccessUnix::get_path() const {
return path_src;
}
String FileAccessUnix::get_path_absolute() const {
return path;
}
#if defined(TOOLS_ENABLED)
String FileAccessUnix::get_real_path() const {
char *resolved_path = ::realpath(path.utf8().get_data(), nullptr);
if (!resolved_path) {
return path;
}
String result;
Error parse_ok = result.append_utf8(resolved_path);
::free(resolved_path);
if (parse_ok != OK) {
return path;
}
return result.simplify_path();
}
#endif
void FileAccessUnix::seek(uint64_t p_position) {
ERR_FAIL_NULL_MSG(f, "File must be opened before use.");
if (fseeko(f, p_position, SEEK_SET)) {
check_errors();
}
}
void FileAccessUnix::seek_end(int64_t p_position) {
ERR_FAIL_NULL_MSG(f, "File must be opened before use.");
if (fseeko(f, p_position, SEEK_END)) {
check_errors();
}
}
uint64_t FileAccessUnix::get_position() const {
ERR_FAIL_NULL_V_MSG(f, 0, "File must be opened before use.");
int64_t pos = ftello(f);
if (pos < 0) {
check_errors();
ERR_FAIL_V(0);
}
return pos;
}
uint64_t FileAccessUnix::get_length() const {
ERR_FAIL_NULL_V_MSG(f, 0, "File must be opened before use.");
int64_t pos = ftello(f);
ERR_FAIL_COND_V(pos < 0, 0);
ERR_FAIL_COND_V(fseeko(f, 0, SEEK_END), 0);
int64_t size = ftello(f);
ERR_FAIL_COND_V(size < 0, 0);
ERR_FAIL_COND_V(fseeko(f, pos, SEEK_SET), 0);
return size;
}
bool FileAccessUnix::eof_reached() const {
return feof(f);
}
uint64_t FileAccessUnix::get_buffer(uint8_t *p_dst, uint64_t p_length) const {
ERR_FAIL_NULL_V_MSG(f, -1, "File must be opened before use.");
ERR_FAIL_COND_V(!p_dst && p_length > 0, -1);
uint64_t read = fread(p_dst, 1, p_length, f);
check_errors();
return read;
}
Error FileAccessUnix::get_error() const {
return last_error;
}
Error FileAccessUnix::resize(int64_t p_length) {
ERR_FAIL_NULL_V_MSG(f, FAILED, "File must be opened before use.");
int res = ::ftruncate(fileno(f), p_length);
switch (res) {
case 0:
return OK;
case EBADF:
return ERR_FILE_CANT_OPEN;
case EFBIG:
return ERR_OUT_OF_MEMORY;
case EINVAL:
return ERR_INVALID_PARAMETER;
default:
return FAILED;
}
}
void FileAccessUnix::flush() {
ERR_FAIL_NULL_MSG(f, "File must be opened before use.");
fflush(f);
}
bool FileAccessUnix::store_buffer(const uint8_t *p_src, uint64_t p_length) {
ERR_FAIL_NULL_V_MSG(f, false, "File must be opened before use.");
ERR_FAIL_COND_V(!p_src && p_length > 0, false);
bool res = fwrite(p_src, 1, p_length, f) == p_length;
check_errors(true);
return res;
}
bool FileAccessUnix::file_exists(const String &p_path) {
struct stat st = {};
const CharString filename_utf8 = fix_path(p_path).utf8();
// Does the name exist at all?
if (stat(filename_utf8.get_data(), &st)) {
return false;
}
// See if we have access to the file
if (access(filename_utf8.get_data(), F_OK)) {
return false;
}
// See if this is a regular file
switch (st.st_mode & S_IFMT) {
case S_IFLNK:
case S_IFREG:
return true;
default:
return false;
}
}
uint64_t FileAccessUnix::_get_modified_time(const String &p_file) {
String file = fix_path(p_file);
struct stat st = {};
int err = stat(file.utf8().get_data(), &st);
if (!err) {
uint64_t modified_time = 0;
if ((st.st_mode & S_IFMT) == S_IFLNK || (st.st_mode & S_IFMT) == S_IFREG || (st.st_mode & S_IFDIR) == S_IFDIR) {
modified_time = st.st_mtime;
}
#ifdef ANDROID_ENABLED
// Workaround for GH-101007
//FIXME: After saving, all timestamps (st_mtime, st_ctime, st_atime) are set to the same value.
// After exporting or after some time, only 'modified_time' resets to a past timestamp.
uint64_t created_time = st.st_ctime;
if (modified_time < created_time) {
modified_time = created_time;
}
#endif
return modified_time;
} else {
return 0;
}
}
uint64_t FileAccessUnix::_get_access_time(const String &p_file) {
String file = fix_path(p_file);
struct stat st = {};
int err = stat(file.utf8().get_data(), &st);
if (!err) {
if ((st.st_mode & S_IFMT) == S_IFLNK || (st.st_mode & S_IFMT) == S_IFREG || (st.st_mode & S_IFDIR) == S_IFDIR) {
return st.st_atime;
}
}
ERR_FAIL_V_MSG(0, "Failed to get access time for: " + p_file + "");
}
int64_t FileAccessUnix::_get_size(const String &p_file) {
String file = fix_path(p_file);
struct stat st = {};
int err = stat(file.utf8().get_data(), &st);
if (!err) {
if ((st.st_mode & S_IFMT) == S_IFLNK || (st.st_mode & S_IFMT) == S_IFREG) {
return st.st_size;
}
}
ERR_FAIL_V_MSG(-1, "Failed to get size for: " + p_file + "");
}
BitField<FileAccess::UnixPermissionFlags> FileAccessUnix::_get_unix_permissions(const String &p_file) {
String file = fix_path(p_file);
struct stat status = {};
int err = stat(file.utf8().get_data(), &status);
if (!err) {
return status.st_mode & 0xFFF; //only permissions
} else {
ERR_FAIL_V_MSG(0, "Failed to get unix permissions for: " + p_file + ".");
}
}
Error FileAccessUnix::_set_unix_permissions(const String &p_file, BitField<FileAccess::UnixPermissionFlags> p_permissions) {
String file = fix_path(p_file);
int err = chmod(file.utf8().get_data(), p_permissions);
if (!err) {
return OK;
}
return FAILED;
}
bool FileAccessUnix::_get_hidden_attribute(const String &p_file) {
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__APPLE__)
String file = fix_path(p_file);
struct stat st = {};
int err = stat(file.utf8().get_data(), &st);
ERR_FAIL_COND_V_MSG(err, false, "Failed to get attributes for: " + p_file);
return (st.st_flags & UF_HIDDEN);
#else
return false;
#endif
}
Error FileAccessUnix::_set_hidden_attribute(const String &p_file, bool p_hidden) {
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__APPLE__)
String file = fix_path(p_file);
struct stat st = {};
int err = stat(file.utf8().get_data(), &st);
ERR_FAIL_COND_V_MSG(err, FAILED, "Failed to get attributes for: " + p_file);
if (p_hidden) {
err = chflags(file.utf8().get_data(), st.st_flags | UF_HIDDEN);
} else {
err = chflags(file.utf8().get_data(), st.st_flags & ~UF_HIDDEN);
}
ERR_FAIL_COND_V_MSG(err, FAILED, "Failed to set attributes for: " + p_file);
return OK;
#else
return ERR_UNAVAILABLE;
#endif
}
bool FileAccessUnix::_get_read_only_attribute(const String &p_file) {
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
String file = fix_path(p_file);
struct stat st = {};
int err = stat(file.utf8().get_data(), &st);
ERR_FAIL_COND_V_MSG(err, false, "Failed to get attributes for: " + p_file);
return st.st_flags & UF_IMMUTABLE;
#else
return false;
#endif
}
Error FileAccessUnix::_set_read_only_attribute(const String &p_file, bool p_ro) {
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
String file = fix_path(p_file);
struct stat st = {};
int err = stat(file.utf8().get_data(), &st);
ERR_FAIL_COND_V_MSG(err, FAILED, "Failed to get attributes for: " + p_file);
if (p_ro) {
err = chflags(file.utf8().get_data(), st.st_flags | UF_IMMUTABLE);
} else {
err = chflags(file.utf8().get_data(), st.st_flags & ~UF_IMMUTABLE);
}
ERR_FAIL_COND_V_MSG(err, FAILED, "Failed to set attributes for: " + p_file);
return OK;
#else
return ERR_UNAVAILABLE;
#endif
}
void FileAccessUnix::close() {
_close();
}
FileAccessUnix::CloseNotificationFunc FileAccessUnix::close_notification_func = nullptr;
FileAccessUnix::~FileAccessUnix() {
_close();
}
#endif // UNIX_ENABLED

View File

@@ -0,0 +1,100 @@
/**************************************************************************/
/* file_access_unix.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#include "core/io/file_access.h"
#include "core/os/memory.h"
#include <cstdio>
#if defined(UNIX_ENABLED)
class FileAccessUnix : public FileAccess {
GDSOFTCLASS(FileAccessUnix, FileAccess);
FILE *f = nullptr;
int flags = 0;
void check_errors(bool p_write = false) const;
mutable Error last_error = OK;
String save_path;
String path;
String path_src;
void _close();
#if defined(TOOLS_ENABLED)
String get_real_path() const; // Returns the resolved real path for the current open file.
#endif
public:
typedef void (*CloseNotificationFunc)(const String &p_file, int p_flags);
static CloseNotificationFunc close_notification_func;
virtual Error open_internal(const String &p_path, int p_mode_flags) override; ///< open a file
virtual bool is_open() const override; ///< true when file is open
virtual String get_path() const override; /// returns the path for the current open file
virtual String get_path_absolute() const override; /// returns the absolute path for the current open file
virtual void seek(uint64_t p_position) override; ///< seek to a given position
virtual void seek_end(int64_t p_position = 0) override; ///< seek from the end of file
virtual uint64_t get_position() const override; ///< get position in the file
virtual uint64_t get_length() const override; ///< get size of the file
virtual bool eof_reached() const override; ///< reading passed EOF
virtual uint64_t get_buffer(uint8_t *p_dst, uint64_t p_length) const override;
virtual Error get_error() const override; ///< get last error
virtual Error resize(int64_t p_length) override;
virtual void flush() override;
virtual bool store_buffer(const uint8_t *p_src, uint64_t p_length) override; ///< store an array of bytes
virtual bool file_exists(const String &p_path) override; ///< return true if a file exists
virtual uint64_t _get_modified_time(const String &p_file) override;
virtual uint64_t _get_access_time(const String &p_file) override;
virtual int64_t _get_size(const String &p_file) override;
virtual BitField<FileAccess::UnixPermissionFlags> _get_unix_permissions(const String &p_file) override;
virtual Error _set_unix_permissions(const String &p_file, BitField<FileAccess::UnixPermissionFlags> p_permissions) override;
virtual bool _get_hidden_attribute(const String &p_file) override;
virtual Error _set_hidden_attribute(const String &p_file, bool p_hidden) override;
virtual bool _get_read_only_attribute(const String &p_file) override;
virtual Error _set_read_only_attribute(const String &p_file, bool p_ro) override;
virtual void close() override;
FileAccessUnix() {}
virtual ~FileAccessUnix();
};
#endif // UNIX_ENABLED

View File

@@ -0,0 +1,185 @@
/**************************************************************************/
/* file_access_unix_pipe.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "file_access_unix_pipe.h"
#if defined(UNIX_ENABLED)
#include "core/os/os.h"
#include "core/string/print_string.h"
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
Error FileAccessUnixPipe::open_existing(int p_rfd, int p_wfd, bool p_blocking) {
// Open pipe using handles created by pipe(fd) call in the OS.execute_with_pipe.
_close();
path_src = String();
unlink_on_close = false;
ERR_FAIL_COND_V_MSG(fd[0] >= 0 || fd[1] >= 0, ERR_ALREADY_IN_USE, "Pipe is already in use.");
fd[0] = p_rfd;
fd[1] = p_wfd;
if (!p_blocking) {
fcntl(fd[0], F_SETFL, fcntl(fd[0], F_GETFL) | O_NONBLOCK);
fcntl(fd[1], F_SETFL, fcntl(fd[1], F_GETFL) | O_NONBLOCK);
}
last_error = OK;
return OK;
}
Error FileAccessUnixPipe::open_internal(const String &p_path, int p_mode_flags) {
_close();
path_src = p_path;
ERR_FAIL_COND_V_MSG(fd[0] >= 0 || fd[1] >= 0, ERR_ALREADY_IN_USE, "Pipe is already in use.");
path = String("/tmp/") + p_path.replace("pipe://", "").replace_char('/', '_');
const CharString path_utf8 = path.utf8();
struct stat st = {};
int err = stat(path_utf8.get_data(), &st);
if (err) {
if (mkfifo(path_utf8.get_data(), 0600) != 0) {
last_error = ERR_FILE_CANT_OPEN;
return last_error;
}
unlink_on_close = true;
} else {
ERR_FAIL_COND_V_MSG(!S_ISFIFO(st.st_mode), ERR_ALREADY_IN_USE, "Pipe name is already used by file.");
}
int f = ::open(path_utf8.get_data(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
if (f < 0) {
switch (errno) {
case ENOENT: {
last_error = ERR_FILE_NOT_FOUND;
} break;
default: {
last_error = ERR_FILE_CANT_OPEN;
} break;
}
return last_error;
}
// Set close on exec to avoid leaking it to subprocesses.
fd[0] = f;
fd[1] = f;
last_error = OK;
return OK;
}
void FileAccessUnixPipe::_close() {
if (fd[0] < 0) {
return;
}
if (fd[1] != fd[0]) {
::close(fd[1]);
}
::close(fd[0]);
fd[0] = -1;
fd[1] = -1;
if (unlink_on_close) {
::unlink(path.utf8().ptr());
}
unlink_on_close = false;
}
bool FileAccessUnixPipe::is_open() const {
return (fd[0] >= 0 || fd[1] >= 0);
}
String FileAccessUnixPipe::get_path() const {
return path_src;
}
String FileAccessUnixPipe::get_path_absolute() const {
return path_src;
}
uint64_t FileAccessUnixPipe::get_length() const {
ERR_FAIL_COND_V_MSG(fd[0] < 0, 0, "Pipe must be opened before use.");
int buf_rem = 0;
ERR_FAIL_COND_V(ioctl(fd[0], FIONREAD, &buf_rem) != 0, 0);
return buf_rem;
}
uint64_t FileAccessUnixPipe::get_buffer(uint8_t *p_dst, uint64_t p_length) const {
ERR_FAIL_COND_V_MSG(fd[0] < 0, -1, "Pipe must be opened before use.");
ERR_FAIL_COND_V(!p_dst && p_length > 0, -1);
ssize_t read = ::read(fd[0], p_dst, p_length);
if (read == -1) {
last_error = ERR_FILE_CANT_READ;
read = 0;
} else if (read != (ssize_t)p_length) {
last_error = ERR_FILE_CANT_READ;
} else {
last_error = OK;
}
return read;
}
Error FileAccessUnixPipe::get_error() const {
return last_error;
}
bool FileAccessUnixPipe::store_buffer(const uint8_t *p_src, uint64_t p_length) {
ERR_FAIL_COND_V_MSG(fd[1] < 0, false, "Pipe must be opened before use.");
ERR_FAIL_COND_V(!p_src && p_length > 0, false);
if (::write(fd[1], p_src, p_length) != (ssize_t)p_length) {
last_error = ERR_FILE_CANT_WRITE;
return false;
} else {
last_error = OK;
return true;
}
}
void FileAccessUnixPipe::close() {
_close();
}
FileAccessUnixPipe::~FileAccessUnixPipe() {
_close();
}
#endif // UNIX_ENABLED

View File

@@ -0,0 +1,95 @@
/**************************************************************************/
/* file_access_unix_pipe.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#include "core/io/file_access.h"
#include "core/os/memory.h"
#include <cstdio>
#if defined(UNIX_ENABLED)
class FileAccessUnixPipe : public FileAccess {
GDSOFTCLASS(FileAccessUnixPipe, FileAccess);
bool unlink_on_close = false;
int fd[2] = { -1, -1 };
mutable Error last_error = OK;
String path;
String path_src;
void _close();
public:
Error open_existing(int p_rfd, int p_wfd, bool p_blocking);
virtual Error open_internal(const String &p_path, int p_mode_flags) override; ///< open a file
virtual bool is_open() const override; ///< true when file is open
virtual String get_path() const override; /// returns the path for the current open file
virtual String get_path_absolute() const override; /// returns the absolute path for the current open file
virtual void seek(uint64_t p_position) override {}
virtual void seek_end(int64_t p_position = 0) override {}
virtual uint64_t get_position() const override { return 0; }
virtual uint64_t get_length() const override;
virtual bool eof_reached() const override { return false; }
virtual uint64_t get_buffer(uint8_t *p_dst, uint64_t p_length) const override;
virtual Error get_error() const override; ///< get last error
virtual Error resize(int64_t p_length) override { return ERR_UNAVAILABLE; }
virtual void flush() override {}
virtual bool store_buffer(const uint8_t *p_src, uint64_t p_length) override; ///< store an array of bytes
virtual bool file_exists(const String &p_path) override { return false; }
virtual uint64_t _get_modified_time(const String &p_file) override { return 0; }
virtual uint64_t _get_access_time(const String &p_file) override { return 0; }
virtual int64_t _get_size(const String &p_file) override { return -1; }
virtual BitField<FileAccess::UnixPermissionFlags> _get_unix_permissions(const String &p_file) override { return 0; }
virtual Error _set_unix_permissions(const String &p_file, BitField<FileAccess::UnixPermissionFlags> p_permissions) override { return ERR_UNAVAILABLE; }
virtual bool _get_hidden_attribute(const String &p_file) override { return false; }
virtual Error _set_hidden_attribute(const String &p_file, bool p_hidden) override { return ERR_UNAVAILABLE; }
virtual bool _get_read_only_attribute(const String &p_file) override { return false; }
virtual Error _set_read_only_attribute(const String &p_file, bool p_ro) override { return ERR_UNAVAILABLE; }
virtual void close() override;
FileAccessUnixPipe() {}
virtual ~FileAccessUnixPipe();
};
#endif // UNIX_ENABLED

166
drivers/unix/ip_unix.cpp Normal file
View File

@@ -0,0 +1,166 @@
/**************************************************************************/
/* ip_unix.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#if defined(UNIX_ENABLED) && !defined(UNIX_SOCKET_UNAVAILABLE)
#include "ip_unix.h"
#include <netdb.h>
#ifdef ANDROID_ENABLED
// We could drop this file once we up our API level to 24,
// where the NDK's ifaddrs.h supports to needed getifaddrs.
#include "thirdparty/misc/ifaddrs-android.h"
#else
#ifdef __FreeBSD__
#include <sys/types.h>
#endif
#include <ifaddrs.h>
#endif
#include <arpa/inet.h>
#include <sys/socket.h>
#ifdef __FreeBSD__
#include <netinet/in.h>
#endif
#include <net/if.h> // Order is important on OpenBSD, leave as last.
static IPAddress _sockaddr2ip(struct sockaddr *p_addr) {
IPAddress ip;
if (p_addr->sa_family == AF_INET) {
struct sockaddr_in *addr = (struct sockaddr_in *)p_addr;
ip.set_ipv4((uint8_t *)&(addr->sin_addr));
} else if (p_addr->sa_family == AF_INET6) {
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
ip.set_ipv6(addr6->sin6_addr.s6_addr);
}
return ip;
}
void IPUnix::_resolve_hostname(List<IPAddress> &r_addresses, const String &p_hostname, Type p_type) const {
struct addrinfo hints;
struct addrinfo *result = nullptr;
memset(&hints, 0, sizeof(struct addrinfo));
if (p_type == TYPE_IPV4) {
hints.ai_family = AF_INET;
} else if (p_type == TYPE_IPV6) {
hints.ai_family = AF_INET6;
hints.ai_flags = 0;
} else {
hints.ai_family = AF_UNSPEC;
hints.ai_flags = AI_ADDRCONFIG;
}
hints.ai_flags &= ~AI_NUMERICHOST;
int s = getaddrinfo(p_hostname.utf8().get_data(), nullptr, &hints, &result);
if (s != 0) {
print_verbose("getaddrinfo failed! Cannot resolve hostname.");
return;
}
if (result == nullptr || result->ai_addr == nullptr) {
print_verbose("Invalid response from getaddrinfo.");
if (result) {
freeaddrinfo(result);
}
return;
}
struct addrinfo *next = result;
do {
if (next->ai_addr == nullptr) {
next = next->ai_next;
continue;
}
IPAddress ip = _sockaddr2ip(next->ai_addr);
if (ip.is_valid() && !r_addresses.find(ip)) {
r_addresses.push_back(ip);
}
next = next->ai_next;
} while (next);
freeaddrinfo(result);
}
void IPUnix::get_local_interfaces(HashMap<String, Interface_Info> *r_interfaces) const {
struct ifaddrs *ifAddrStruct = nullptr;
struct ifaddrs *ifa = nullptr;
int family;
getifaddrs(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != nullptr; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr) {
continue;
}
family = ifa->ifa_addr->sa_family;
if (family != AF_INET && family != AF_INET6) {
continue;
}
HashMap<String, Interface_Info>::Iterator E = r_interfaces->find(ifa->ifa_name);
if (!E) {
Interface_Info info;
info.name = ifa->ifa_name;
info.name_friendly = ifa->ifa_name;
info.index = String::num_uint64(if_nametoindex(ifa->ifa_name));
E = r_interfaces->insert(ifa->ifa_name, info);
ERR_CONTINUE(!E);
}
Interface_Info &info = E->value;
info.ip_addresses.push_front(_sockaddr2ip(ifa->ifa_addr));
}
if (ifAddrStruct != nullptr) {
freeifaddrs(ifAddrStruct);
}
}
void IPUnix::make_default() {
_create = _create_unix;
}
IP *IPUnix::_create_unix() {
return memnew(IPUnix);
}
IPUnix::IPUnix() {
}
#endif // UNIX_ENABLED

51
drivers/unix/ip_unix.h Normal file
View File

@@ -0,0 +1,51 @@
/**************************************************************************/
/* ip_unix.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#if defined(UNIX_ENABLED) && !defined(UNIX_SOCKET_UNAVAILABLE)
#include "core/io/ip.h"
class IPUnix : public IP {
GDCLASS(IPUnix, IP);
virtual void _resolve_hostname(List<IPAddress> &r_addresses, const String &p_hostname, Type p_type = TYPE_ANY) const override;
static IP *_create_unix();
public:
virtual void get_local_interfaces(HashMap<String, Interface_Info> *r_interfaces) const override;
static void make_default();
IPUnix();
};
#endif // UNIX_ENABLED

View File

@@ -0,0 +1,626 @@
/**************************************************************************/
/* net_socket_unix.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
// Some proprietary Unix-derived platforms don't expose Unix sockets
// so this allows skipping this file to reimplement this API differently.
#if defined(UNIX_ENABLED) && !defined(UNIX_SOCKET_UNAVAILABLE)
#include "net_socket_unix.h"
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#ifdef WEB_ENABLED
#include <arpa/inet.h>
#endif
// BSD calls this flag IPV6_JOIN_GROUP
#if !defined(IPV6_ADD_MEMBERSHIP) && defined(IPV6_JOIN_GROUP)
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#endif
#if !defined(IPV6_DROP_MEMBERSHIP) && defined(IPV6_LEAVE_GROUP)
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#endif
size_t NetSocketUnix::_set_addr_storage(struct sockaddr_storage *p_addr, const IPAddress &p_ip, uint16_t p_port, IP::Type p_ip_type) {
memset(p_addr, 0, sizeof(struct sockaddr_storage));
if (p_ip_type == IP::TYPE_IPV6 || p_ip_type == IP::TYPE_ANY) { // IPv6 socket.
// IPv6 only socket with IPv4 address.
ERR_FAIL_COND_V(!p_ip.is_wildcard() && p_ip_type == IP::TYPE_IPV6 && p_ip.is_ipv4(), 0);
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
addr6->sin6_family = AF_INET6;
addr6->sin6_port = htons(p_port);
if (p_ip.is_valid()) {
memcpy(&addr6->sin6_addr.s6_addr, p_ip.get_ipv6(), 16);
} else {
addr6->sin6_addr = in6addr_any;
}
return sizeof(sockaddr_in6);
} else { // IPv4 socket.
// IPv4 socket with IPv6 address.
ERR_FAIL_COND_V(!p_ip.is_wildcard() && !p_ip.is_ipv4(), 0);
struct sockaddr_in *addr4 = (struct sockaddr_in *)p_addr;
addr4->sin_family = AF_INET;
addr4->sin_port = htons(p_port); // Short, network byte order.
if (p_ip.is_valid()) {
memcpy(&addr4->sin_addr.s_addr, p_ip.get_ipv4(), 4);
} else {
addr4->sin_addr.s_addr = INADDR_ANY;
}
return sizeof(sockaddr_in);
}
}
void NetSocketUnix::_set_ip_port(struct sockaddr_storage *p_addr, IPAddress *r_ip, uint16_t *r_port) {
if (p_addr->ss_family == AF_INET) {
struct sockaddr_in *addr4 = (struct sockaddr_in *)p_addr;
if (r_ip) {
r_ip->set_ipv4((uint8_t *)&(addr4->sin_addr.s_addr));
}
if (r_port) {
*r_port = ntohs(addr4->sin_port);
}
} else if (p_addr->ss_family == AF_INET6) {
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
if (r_ip) {
r_ip->set_ipv6(addr6->sin6_addr.s6_addr);
}
if (r_port) {
*r_port = ntohs(addr6->sin6_port);
}
}
}
NetSocket *NetSocketUnix::_create_func() {
return memnew(NetSocketUnix);
}
void NetSocketUnix::make_default() {
_create = _create_func;
}
void NetSocketUnix::cleanup() {
}
NetSocketUnix::NetSocketUnix() {
}
NetSocketUnix::~NetSocketUnix() {
close();
}
// Silence a warning reported in GH-27594.
// EAGAIN and EWOULDBLOCK have the same value on most platforms, but it's not guaranteed.
GODOT_GCC_WARNING_PUSH_AND_IGNORE("-Wlogical-op")
NetSocketUnix::NetError NetSocketUnix::_get_socket_error() const {
if (errno == EISCONN) {
return ERR_NET_IS_CONNECTED;
}
if (errno == EINPROGRESS || errno == EALREADY) {
return ERR_NET_IN_PROGRESS;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return ERR_NET_WOULD_BLOCK;
}
if (errno == EADDRINUSE || errno == EINVAL || errno == EADDRNOTAVAIL) {
return ERR_NET_ADDRESS_INVALID_OR_UNAVAILABLE;
}
if (errno == EACCES) {
return ERR_NET_UNAUTHORIZED;
}
if (errno == ENOBUFS) {
return ERR_NET_BUFFER_TOO_SMALL;
}
print_verbose("Socket error: " + itos(errno) + ".");
return ERR_NET_OTHER;
}
GODOT_GCC_WARNING_POP
bool NetSocketUnix::_can_use_ip(const IPAddress &p_ip, const bool p_for_bind) const {
if (p_for_bind && !(p_ip.is_valid() || p_ip.is_wildcard())) {
return false;
} else if (!p_for_bind && !p_ip.is_valid()) {
return false;
}
// Check if socket support this IP type.
IP::Type type = p_ip.is_ipv4() ? IP::TYPE_IPV4 : IP::TYPE_IPV6;
return !(_ip_type != IP::TYPE_ANY && !p_ip.is_wildcard() && _ip_type != type);
}
_FORCE_INLINE_ Error NetSocketUnix::_change_multicast_group(IPAddress p_ip, String p_if_name, bool p_add) {
ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
ERR_FAIL_COND_V(!_can_use_ip(p_ip, false), ERR_INVALID_PARAMETER);
// Need to force level and af_family to IP(v4) when using dual stacking and provided multicast group is IPv4.
IP::Type type = _ip_type == IP::TYPE_ANY && p_ip.is_ipv4() ? IP::TYPE_IPV4 : _ip_type;
// This needs to be the proper level for the multicast group, no matter if the socket is dual stacking.
int level = type == IP::TYPE_IPV4 ? IPPROTO_IP : IPPROTO_IPV6;
int ret = -1;
IPAddress if_ip;
uint32_t if_v6id = 0;
HashMap<String, IP::Interface_Info> if_info;
IP::get_singleton()->get_local_interfaces(&if_info);
for (KeyValue<String, IP::Interface_Info> &E : if_info) {
IP::Interface_Info &c = E.value;
if (c.name != p_if_name) {
continue;
}
if_v6id = (uint32_t)c.index.to_int();
if (type == IP::TYPE_IPV6) {
break; // IPv6 uses index.
}
for (const IPAddress &F : c.ip_addresses) {
if (!F.is_ipv4()) {
continue; // Wrong IP type.
}
if_ip = F;
break;
}
break;
}
if (level == IPPROTO_IP) {
ERR_FAIL_COND_V(!if_ip.is_valid(), ERR_INVALID_PARAMETER);
struct ip_mreq greq;
int sock_opt = p_add ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
memcpy(&greq.imr_multiaddr, p_ip.get_ipv4(), 4);
memcpy(&greq.imr_interface, if_ip.get_ipv4(), 4);
ret = setsockopt(_sock, level, sock_opt, (const char *)&greq, sizeof(greq));
} else {
struct ipv6_mreq greq;
int sock_opt = p_add ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP;
memcpy(&greq.ipv6mr_multiaddr, p_ip.get_ipv6(), 16);
greq.ipv6mr_interface = if_v6id;
ret = setsockopt(_sock, level, sock_opt, (const char *)&greq, sizeof(greq));
}
ERR_FAIL_COND_V(ret != 0, FAILED);
return OK;
}
void NetSocketUnix::_set_socket(int p_sock, IP::Type p_ip_type, bool p_is_stream) {
_sock = p_sock;
_ip_type = p_ip_type;
_is_stream = p_is_stream;
// Disable descriptor sharing with subprocesses.
_set_close_exec_enabled(true);
}
void NetSocketUnix::_set_close_exec_enabled(bool p_enabled) {
// Enable close on exec to avoid sharing with subprocesses. Off by default on Windows.
int opts = fcntl(_sock, F_GETFD);
fcntl(_sock, F_SETFD, opts | FD_CLOEXEC);
}
Error NetSocketUnix::open(Type p_sock_type, IP::Type &ip_type) {
ERR_FAIL_COND_V(is_open(), ERR_ALREADY_IN_USE);
ERR_FAIL_COND_V(ip_type > IP::TYPE_ANY || ip_type < IP::TYPE_NONE, ERR_INVALID_PARAMETER);
#if defined(__OpenBSD__)
// OpenBSD does not support dual stacking, fallback to IPv4 only.
if (ip_type == IP::TYPE_ANY) {
ip_type = IP::TYPE_IPV4;
}
#endif
int family = ip_type == IP::TYPE_IPV4 ? AF_INET : AF_INET6;
int protocol = p_sock_type == TYPE_TCP ? IPPROTO_TCP : IPPROTO_UDP;
int type = p_sock_type == TYPE_TCP ? SOCK_STREAM : SOCK_DGRAM;
_sock = socket(family, type, protocol);
if (_sock == -1 && ip_type == IP::TYPE_ANY) {
// Careful here, changing the referenced parameter so the caller knows that we are using an IPv4 socket
// in place of a dual stack one, and further calls to _set_sock_addr will work as expected.
ip_type = IP::TYPE_IPV4;
family = AF_INET;
_sock = socket(family, type, protocol);
}
ERR_FAIL_COND_V(_sock == -1, FAILED);
_ip_type = ip_type;
if (family == AF_INET6) {
// Select IPv4 over IPv6 mapping.
set_ipv6_only_enabled(ip_type != IP::TYPE_ANY);
}
if (protocol == IPPROTO_UDP) {
// Make sure to disable broadcasting for UDP sockets.
// Depending on the OS, this option might or might not be enabled by default. Let's normalize it.
set_broadcasting_enabled(false);
}
_is_stream = p_sock_type == TYPE_TCP;
// Disable descriptor sharing with subprocesses.
_set_close_exec_enabled(true);
#if defined(SO_NOSIGPIPE)
// Disable SIGPIPE (should only be relevant to stream sockets, but seems to affect UDP too on iOS).
int par = 1;
if (setsockopt(_sock, SOL_SOCKET, SO_NOSIGPIPE, &par, sizeof(int)) != 0) {
print_verbose("Unable to turn off SIGPIPE on socket.");
}
#endif
return OK;
}
void NetSocketUnix::close() {
if (_sock != -1) {
::close(_sock);
}
_sock = -1;
_ip_type = IP::TYPE_NONE;
_is_stream = false;
}
Error NetSocketUnix::bind(IPAddress p_addr, uint16_t p_port) {
ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
ERR_FAIL_COND_V(!_can_use_ip(p_addr, true), ERR_INVALID_PARAMETER);
sockaddr_storage addr;
size_t addr_size = _set_addr_storage(&addr, p_addr, p_port, _ip_type);
if (::bind(_sock, (struct sockaddr *)&addr, addr_size) != 0) {
NetError err = _get_socket_error();
print_verbose("Failed to bind socket. Error: " + itos(err) + ".");
close();
return ERR_UNAVAILABLE;
}
return OK;
}
Error NetSocketUnix::listen(int p_max_pending) {
ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
if (::listen(_sock, p_max_pending) != 0) {
_get_socket_error();
print_verbose("Failed to listen from socket.");
close();
return FAILED;
}
return OK;
}
Error NetSocketUnix::connect_to_host(IPAddress p_host, uint16_t p_port) {
ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
ERR_FAIL_COND_V(!_can_use_ip(p_host, false), ERR_INVALID_PARAMETER);
struct sockaddr_storage addr;
size_t addr_size = _set_addr_storage(&addr, p_host, p_port, _ip_type);
if (::connect(_sock, (struct sockaddr *)&addr, addr_size) != 0) {
NetError err = _get_socket_error();
switch (err) {
// We are already connected.
case ERR_NET_IS_CONNECTED:
return OK;
// Still waiting to connect, try again in a while.
case ERR_NET_WOULD_BLOCK:
case ERR_NET_IN_PROGRESS:
return ERR_BUSY;
default:
print_verbose("Connection to remote host failed.");
close();
return FAILED;
}
}
return OK;
}
Error NetSocketUnix::poll(PollType p_type, int p_timeout) const {
ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
struct pollfd pfd;
pfd.fd = _sock;
pfd.events = POLLIN;
pfd.revents = 0;
switch (p_type) {
case POLL_TYPE_IN:
pfd.events = POLLIN;
break;
case POLL_TYPE_OUT:
pfd.events = POLLOUT;
break;
case POLL_TYPE_IN_OUT:
pfd.events = POLLOUT | POLLIN;
}
int ret = ::poll(&pfd, 1, p_timeout);
if (ret < 0 || pfd.revents & POLLERR) {
_get_socket_error();
print_verbose("Error when polling socket.");
return FAILED;
}
if (ret == 0) {
return ERR_BUSY;
}
return OK;
}
Error NetSocketUnix::recv(uint8_t *p_buffer, int p_len, int &r_read) {
ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
r_read = ::recv(_sock, p_buffer, p_len, 0);
if (r_read < 0) {
NetError err = _get_socket_error();
if (err == ERR_NET_WOULD_BLOCK) {
return ERR_BUSY;
}
if (err == ERR_NET_BUFFER_TOO_SMALL) {
return ERR_OUT_OF_MEMORY;
}
return FAILED;
}
return OK;
}
Error NetSocketUnix::recvfrom(uint8_t *p_buffer, int p_len, int &r_read, IPAddress &r_ip, uint16_t &r_port, bool p_peek) {
ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
struct sockaddr_storage from;
socklen_t len = sizeof(struct sockaddr_storage);
memset(&from, 0, len);
r_read = ::recvfrom(_sock, p_buffer, p_len, p_peek ? MSG_PEEK : 0, (struct sockaddr *)&from, &len);
if (r_read < 0) {
NetError err = _get_socket_error();
if (err == ERR_NET_WOULD_BLOCK) {
return ERR_BUSY;
}
if (err == ERR_NET_BUFFER_TOO_SMALL) {
return ERR_OUT_OF_MEMORY;
}
return FAILED;
}
if (from.ss_family == AF_INET) {
struct sockaddr_in *sin_from = (struct sockaddr_in *)&from;
r_ip.set_ipv4((uint8_t *)&sin_from->sin_addr);
r_port = ntohs(sin_from->sin_port);
} else if (from.ss_family == AF_INET6) {
struct sockaddr_in6 *s6_from = (struct sockaddr_in6 *)&from;
r_ip.set_ipv6((uint8_t *)&s6_from->sin6_addr);
r_port = ntohs(s6_from->sin6_port);
} else {
// Unsupported socket family, should never happen.
ERR_FAIL_V(FAILED);
}
return OK;
}
Error NetSocketUnix::send(const uint8_t *p_buffer, int p_len, int &r_sent) {
ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
int flags = 0;
#ifdef MSG_NOSIGNAL
if (_is_stream) {
flags = MSG_NOSIGNAL;
}
#endif
r_sent = ::send(_sock, p_buffer, p_len, flags);
if (r_sent < 0) {
NetError err = _get_socket_error();
if (err == ERR_NET_WOULD_BLOCK) {
return ERR_BUSY;
}
if (err == ERR_NET_BUFFER_TOO_SMALL) {
return ERR_OUT_OF_MEMORY;
}
return FAILED;
}
return OK;
}
Error NetSocketUnix::sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) {
ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
struct sockaddr_storage addr;
size_t addr_size = _set_addr_storage(&addr, p_ip, p_port, _ip_type);
r_sent = ::sendto(_sock, p_buffer, p_len, 0, (struct sockaddr *)&addr, addr_size);
if (r_sent < 0) {
NetError err = _get_socket_error();
if (err == ERR_NET_WOULD_BLOCK) {
return ERR_BUSY;
}
if (err == ERR_NET_BUFFER_TOO_SMALL) {
return ERR_OUT_OF_MEMORY;
}
return FAILED;
}
return OK;
}
Error NetSocketUnix::set_broadcasting_enabled(bool p_enabled) {
ERR_FAIL_COND_V(!is_open(), ERR_UNCONFIGURED);
// IPv6 has no broadcast support.
if (_ip_type == IP::TYPE_IPV6) {
return ERR_UNAVAILABLE;
}
int par = p_enabled ? 1 : 0;
if (setsockopt(_sock, SOL_SOCKET, SO_BROADCAST, &par, sizeof(int)) != 0) {
WARN_PRINT("Unable to change broadcast setting.");
return FAILED;
}
return OK;
}
void NetSocketUnix::set_blocking_enabled(bool p_enabled) {
ERR_FAIL_COND(!is_open());
int ret = 0;
int opts = fcntl(_sock, F_GETFL);
if (p_enabled) {
ret = fcntl(_sock, F_SETFL, opts & ~O_NONBLOCK);
} else {
ret = fcntl(_sock, F_SETFL, opts | O_NONBLOCK);
}
if (ret != 0) {
WARN_PRINT("Unable to change non-block mode.");
}
}
void NetSocketUnix::set_ipv6_only_enabled(bool p_enabled) {
ERR_FAIL_COND(!is_open());
// This option is only available in IPv6 sockets.
ERR_FAIL_COND(_ip_type == IP::TYPE_IPV4);
int par = p_enabled ? 1 : 0;
if (setsockopt(_sock, IPPROTO_IPV6, IPV6_V6ONLY, &par, sizeof(int)) != 0) {
WARN_PRINT("Unable to change IPv4 address mapping over IPv6 option.");
}
}
void NetSocketUnix::set_tcp_no_delay_enabled(bool p_enabled) {
ERR_FAIL_COND(!is_open());
ERR_FAIL_COND(!_is_stream); // Not TCP.
int par = p_enabled ? 1 : 0;
if (setsockopt(_sock, IPPROTO_TCP, TCP_NODELAY, &par, sizeof(int)) < 0) {
WARN_PRINT("Unable to set TCP no delay option.");
}
}
void NetSocketUnix::set_reuse_address_enabled(bool p_enabled) {
ERR_FAIL_COND(!is_open());
int par = p_enabled ? 1 : 0;
if (setsockopt(_sock, SOL_SOCKET, SO_REUSEADDR, &par, sizeof(int)) < 0) {
WARN_PRINT("Unable to set socket REUSEADDR option.");
}
}
bool NetSocketUnix::is_open() const {
return _sock != -1;
}
int NetSocketUnix::get_available_bytes() const {
ERR_FAIL_COND_V(!is_open(), -1);
int len;
int ret = ioctl(_sock, FIONREAD, &len);
if (ret == -1) {
_get_socket_error();
print_verbose("Error when checking available bytes on socket.");
return -1;
}
return len;
}
Error NetSocketUnix::get_socket_address(IPAddress *r_ip, uint16_t *r_port) const {
ERR_FAIL_COND_V(!is_open(), FAILED);
struct sockaddr_storage saddr;
socklen_t len = sizeof(saddr);
if (getsockname(_sock, (struct sockaddr *)&saddr, &len) != 0) {
_get_socket_error();
print_verbose("Error when reading local socket address.");
return FAILED;
}
_set_ip_port(&saddr, r_ip, r_port);
return OK;
}
Ref<NetSocket> NetSocketUnix::accept(IPAddress &r_ip, uint16_t &r_port) {
Ref<NetSocket> out;
ERR_FAIL_COND_V(!is_open(), out);
struct sockaddr_storage their_addr;
socklen_t size = sizeof(their_addr);
int fd = ::accept(_sock, (struct sockaddr *)&their_addr, &size);
if (fd == -1) {
_get_socket_error();
print_verbose("Error when accepting socket connection.");
return out;
}
_set_ip_port(&their_addr, &r_ip, &r_port);
NetSocketUnix *ns = memnew(NetSocketUnix);
ns->_set_socket(fd, _ip_type, _is_stream);
ns->set_blocking_enabled(false);
return Ref<NetSocket>(ns);
}
Error NetSocketUnix::join_multicast_group(const IPAddress &p_multi_address, const String &p_if_name) {
return _change_multicast_group(p_multi_address, p_if_name, true);
}
Error NetSocketUnix::leave_multicast_group(const IPAddress &p_multi_address, const String &p_if_name) {
return _change_multicast_group(p_multi_address, p_if_name, false);
}
#endif // UNIX_ENABLED && !UNIX_SOCKET_UNAVAILABLE

View File

@@ -0,0 +1,99 @@
/**************************************************************************/
/* net_socket_unix.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#if defined(UNIX_ENABLED) && !defined(UNIX_SOCKET_UNAVAILABLE)
#include "core/io/net_socket.h"
#include <sys/socket.h>
class NetSocketUnix : public NetSocket {
private:
int _sock = -1;
IP::Type _ip_type = IP::TYPE_NONE;
bool _is_stream = false;
enum NetError {
ERR_NET_WOULD_BLOCK,
ERR_NET_IS_CONNECTED,
ERR_NET_IN_PROGRESS,
ERR_NET_ADDRESS_INVALID_OR_UNAVAILABLE,
ERR_NET_UNAUTHORIZED,
ERR_NET_BUFFER_TOO_SMALL,
ERR_NET_OTHER,
};
NetError _get_socket_error() const;
void _set_socket(int p_sock, IP::Type p_ip_type, bool p_is_stream);
_FORCE_INLINE_ Error _change_multicast_group(IPAddress p_ip, String p_if_name, bool p_add);
_FORCE_INLINE_ void _set_close_exec_enabled(bool p_enabled);
protected:
static NetSocket *_create_func();
bool _can_use_ip(const IPAddress &p_ip, const bool p_for_bind) const;
public:
static void make_default();
static void cleanup();
static void _set_ip_port(struct sockaddr_storage *p_addr, IPAddress *r_ip, uint16_t *r_port);
static size_t _set_addr_storage(struct sockaddr_storage *p_addr, const IPAddress &p_ip, uint16_t p_port, IP::Type p_ip_type);
virtual Error open(Type p_sock_type, IP::Type &ip_type) override;
virtual void close() override;
virtual Error bind(IPAddress p_addr, uint16_t p_port) override;
virtual Error listen(int p_max_pending) override;
virtual Error connect_to_host(IPAddress p_host, uint16_t p_port) override;
virtual Error poll(PollType p_type, int timeout) const override;
virtual Error recv(uint8_t *p_buffer, int p_len, int &r_read) override;
virtual Error recvfrom(uint8_t *p_buffer, int p_len, int &r_read, IPAddress &r_ip, uint16_t &r_port, bool p_peek = false) override;
virtual Error send(const uint8_t *p_buffer, int p_len, int &r_sent) override;
virtual Error sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) override;
virtual Ref<NetSocket> accept(IPAddress &r_ip, uint16_t &r_port) override;
virtual bool is_open() const override;
virtual int get_available_bytes() const override;
virtual Error get_socket_address(IPAddress *r_ip, uint16_t *r_port) const override;
virtual Error set_broadcasting_enabled(bool p_enabled) override;
virtual void set_blocking_enabled(bool p_enabled) override;
virtual void set_ipv6_only_enabled(bool p_enabled) override;
virtual void set_tcp_no_delay_enabled(bool p_enabled) override;
virtual void set_reuse_address_enabled(bool p_enabled) override;
virtual Error join_multicast_group(const IPAddress &p_multi_address, const String &p_if_name) override;
virtual Error leave_multicast_group(const IPAddress &p_multi_address, const String &p_if_name) override;
NetSocketUnix();
~NetSocketUnix() override;
};
#endif // UNIX_ENABLED && !UNIX_SOCKET_UNAVAILABLE

1268
drivers/unix/os_unix.cpp Normal file

File diff suppressed because it is too large Load Diff

151
drivers/unix/os_unix.h Normal file
View File

@@ -0,0 +1,151 @@
/**************************************************************************/
/* os_unix.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#ifdef UNIX_ENABLED
#include "core/os/os.h"
#include "drivers/unix/ip_unix.h"
#if defined(__GLIBC__) || defined(WEB_ENABLED)
#include <iconv.h>
#include <langinfo.h>
#define gd_iconv_t iconv_t
#define gd_iconv_open iconv_open
#define gd_iconv iconv
#define gd_iconv_close iconv_close
#else
typedef void *gd_iconv_t;
typedef gd_iconv_t (*PIConvOpen)(const char *, const char *);
typedef size_t (*PIConv)(gd_iconv_t, char **, size_t *, char **, size_t *);
typedef int (*PIConvClose)(gd_iconv_t);
typedef const char *(*PIConvLocaleCharset)(void);
#endif
class OS_Unix : public OS {
struct ProcessInfo {
mutable bool is_running = true;
mutable int exit_code = -1;
};
HashMap<ProcessID, ProcessInfo> *process_map = nullptr;
Mutex process_map_mutex;
#if defined(__GLIBC__) || defined(WEB_ENABLED)
bool _iconv_ok = true;
#else
bool _iconv_ok = false;
PIConvOpen gd_iconv_open = nullptr;
PIConv gd_iconv = nullptr;
PIConvClose gd_iconv_close = nullptr;
PIConvLocaleCharset gd_locale_charset = nullptr;
void _load_iconv();
#endif
static int _wait_for_pid_completion(const pid_t p_pid, int *r_status, int p_options, pid_t *r_pid = nullptr);
bool _check_pid_is_running(const pid_t p_pid, int *r_status) const;
protected:
// UNIX only handles the core functions.
// inheriting platforms under unix (eg. X11) should handle the rest
virtual void initialize_core();
virtual int unix_initialize_audio(int p_audio_driver);
virtual void finalize_core() override;
public:
OS_Unix();
virtual Vector<String> get_video_adapter_driver_info() const override;
virtual String get_stdin_string(int64_t p_buffer_size = 1024) override;
virtual PackedByteArray get_stdin_buffer(int64_t p_buffer_size = 1024) override;
virtual StdHandleType get_stdin_type() const override;
virtual StdHandleType get_stdout_type() const override;
virtual StdHandleType get_stderr_type() const override;
virtual Error get_entropy(uint8_t *r_buffer, int p_bytes) override;
virtual Error open_dynamic_library(const String &p_path, void *&p_library_handle, GDExtensionData *p_data = nullptr) override;
virtual Error close_dynamic_library(void *p_library_handle) override;
virtual Error get_dynamic_library_symbol_handle(void *p_library_handle, const String &p_name, void *&p_symbol_handle, bool p_optional = false) override;
virtual Error set_cwd(const String &p_cwd) override;
virtual String get_name() const override;
virtual String get_distribution_name() const override;
virtual String get_version() const override;
virtual String get_temp_path() const override;
virtual DateTime get_datetime(bool p_utc) const override;
virtual TimeZoneInfo get_time_zone_info() const override;
virtual double get_unix_time() const override;
virtual void delay_usec(uint32_t p_usec) const override;
virtual uint64_t get_ticks_usec() const override;
virtual Dictionary get_memory_info() const override;
virtual String multibyte_to_string(const String &p_encoding, const PackedByteArray &p_array) const override;
virtual PackedByteArray string_to_multibyte(const String &p_encoding, const String &p_string) const override;
virtual Error execute(const String &p_path, const List<String> &p_arguments, String *r_pipe = nullptr, int *r_exitcode = nullptr, bool read_stderr = false, Mutex *p_pipe_mutex = nullptr, bool p_open_console = false) override;
virtual Dictionary execute_with_pipe(const String &p_path, const List<String> &p_arguments, bool p_blocking = true) override;
virtual Error create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id = nullptr, bool p_open_console = false) override;
virtual Error kill(const ProcessID &p_pid) override;
virtual int get_process_id() const override;
virtual bool is_process_running(const ProcessID &p_pid) const override;
virtual int get_process_exit_code(const ProcessID &p_pid) const override;
virtual bool has_environment(const String &p_var) const override;
virtual String get_environment(const String &p_var) const override;
virtual void set_environment(const String &p_var, const String &p_value) const override;
virtual void unset_environment(const String &p_var) const override;
virtual String get_locale() const override;
virtual void initialize_debugging() override;
virtual String get_executable_path() const override;
virtual String get_user_data_dir(const String &p_user_dir) const override;
};
class UnixTerminalLogger : public StdLogger {
public:
virtual void log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify = false, ErrorType p_type = ERR_ERROR, const Vector<Ref<ScriptBacktrace>> &p_script_backtraces = {}) override;
virtual ~UnixTerminalLogger();
};
#endif // UNIX_ENABLED

View File

@@ -0,0 +1,67 @@
/**************************************************************************/
/* syslog_logger.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#ifdef UNIX_ENABLED
#include "syslog_logger.h"
#include "core/string/print_string.h"
#include <syslog.h>
void SyslogLogger::logv(const char *p_format, va_list p_list, bool p_err) {
if (!should_log(p_err)) {
return;
}
vsyslog(p_err ? LOG_ERR : LOG_INFO, p_format, p_list);
}
void SyslogLogger::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
if (!should_log(true)) {
return;
}
const char *err_type = error_type_string(p_type);
const char *err_details;
if (p_rationale && *p_rationale) {
err_details = p_rationale;
} else {
err_details = p_code;
}
syslog(p_type == ERR_WARNING ? LOG_WARNING : LOG_ERR, "**%s**: %s\n At: %s:%i:%s() - %s", err_type, err_details, p_file, p_line, p_function, p_code);
}
SyslogLogger::~SyslogLogger() {
}
#endif

View File

@@ -0,0 +1,45 @@
/**************************************************************************/
/* syslog_logger.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#ifdef UNIX_ENABLED
#include "core/io/logger.h"
class SyslogLogger : public Logger {
public:
virtual void logv(const char *p_format, va_list p_list, bool p_err) _PRINTF_FORMAT_ATTRIBUTE_2_0;
virtual void print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type);
virtual ~SyslogLogger();
};
#endif // UNIX_ENABLED

View File

@@ -0,0 +1,83 @@
/**************************************************************************/
/* thread_posix.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#if defined(UNIX_ENABLED)
#include "thread_posix.h"
#include "core/os/thread.h"
#include "core/string/ustring.h"
#if defined(PLATFORM_THREAD_OVERRIDE) && defined(__APPLE__)
void init_thread_posix() {
}
#else
#ifdef PTHREAD_BSD_SET_NAME
#include <pthread_np.h>
#endif
static Error set_name(const String &p_name) {
#ifdef PTHREAD_NO_RENAME
return ERR_UNAVAILABLE;
#else
#ifdef PTHREAD_RENAME_SELF
// check if thread is the same as caller
int err = pthread_setname_np(p_name.utf8().get_data());
#else
pthread_t running_thread = pthread_self();
#ifdef PTHREAD_BSD_SET_NAME
pthread_set_name_np(running_thread, p_name.utf8().get_data());
int err = 0; // Open/FreeBSD ignore errors in this function
#elif defined(PTHREAD_NETBSD_SET_NAME)
int err = pthread_setname_np(running_thread, "%s", const_cast<char *>(p_name.utf8().get_data()));
#else
int err = pthread_setname_np(running_thread, p_name.utf8().get_data());
#endif // PTHREAD_BSD_SET_NAME
#endif // PTHREAD_RENAME_SELF
return err == 0 ? OK : ERR_INVALID_PARAMETER;
#endif // PTHREAD_NO_RENAME
}
void init_thread_posix() {
Thread::_set_platform_functions({ .set_name = set_name });
}
#endif // PLATFORM_THREAD_OVERRIDE && __APPLE__
#endif // UNIX_ENABLED

View File

@@ -0,0 +1,33 @@
/**************************************************************************/
/* thread_posix.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
void init_thread_posix();