From ef8776b6b1c9e86101410aafd30129c20510ce81 Mon Sep 17 00:00:00 2001 From: Marc Date: Sun, 11 Sep 2022 12:19:46 +0200 Subject: [PATCH] proof of concept --- .gitignore | 5 + CMakeLists.txt | 23 ++ LICENSE | 339 ++++++++++++++++++++++++ README.md | 55 ++++ note for future developments.txt | 4 + src/file.c | 84 ++++++ src/file.h | 15 ++ src/getHome.c | 9 + src/getHome.h | 1 + src/install.c | 105 ++++++++ src/install.h | 6 + src/macro.h | 7 + src/main.c | 425 +++++++++++++++++++++++++++++++ src/main.h | 8 + src/overlayfs.c | 44 ++++ src/overlayfs.h | 6 + src/steam.c | 211 +++++++++++++++ src/steam.h | 49 ++++ 18 files changed, 1396 insertions(+) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 LICENSE create mode 100644 README.md create mode 100644 note for future developments.txt create mode 100644 src/file.c create mode 100644 src/file.h create mode 100644 src/getHome.c create mode 100644 src/getHome.h create mode 100644 src/install.c create mode 100644 src/install.h create mode 100644 src/macro.h create mode 100644 src/main.c create mode 100644 src/main.h create mode 100644 src/overlayfs.c create mode 100644 src/overlayfs.h create mode 100644 src/steam.c create mode 100644 src/steam.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a896241 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.vscode +.cache +build +build/* +compile_commands.json diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..109ff99 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,23 @@ +cmake_minimum_required(VERSION 3.10) + + +# generate the compile_commands for vscode / clang +set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE INTERNAL "") + +# set the project name +project(ModManager) + +# add the executable +add_executable(ModManager src/main.c src/steam.c src/install.c src/overlayfs.c src/getHome.c src/file.c) +add_compile_options(-Wall -Wextra -pedantic -Werror) + +find_package(PkgConfig REQUIRED) +pkg_search_module(GLIB REQUIRED glib-2.0) +pkg_search_module(audit REQUIRED libaudit) +target_include_directories(ModManager PRIVATE ${GLIB_INCLUDE_DIRS}) +target_link_libraries(ModManager ${AUDIT_LIBRARIES}) + +add_compile_options(-fsanitize=address) +add_link_options(-fsanitize=address) + +target_link_libraries(ModManager ${GLIB_LDFLAGS}) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d511905 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fdd97c2 --- /dev/null +++ b/README.md @@ -0,0 +1,55 @@ + +# A Bethesda game mod manager for Linux + +This mod manager is made a protect the game files & mods files at all costs. +if an operation or a mod tries to modify the files they will be stocked in and overlay folder (~/.local/share/modmanager/UPPER_DIRS/appid) + +this mod manager will try to enable casefold inside the mods folder as a way of ensuring that there will not be two file with the same name. + +mods conflicts are solved by priority, currently we still have to implements +a way to change the priority. + + +``` +Use --list-games or -l to list compatible games +Use --add or -a to add a mod to a game +Use --list-mods or -m to list all mods for a game +Use --install or -i to add a mod to a game +Use --remove or -r to remove a mod from a game +Use --deploy or -d to deploy the mods for the game +Use --unbind or -u to rollback a deployment +``` + +## Requirements: +* glib2 + +### Optional requirements: +* Fuse (2 or 3) +* Fuse-overlayfs + +## instructions and warnings about casefold: +Casefold is and options in some linux filesystems that will make a folder (not the whole filesystem) case insensitive, this is really good for proton since it gives a small lookup performance boost and allow us to install mods without fearing having two file with the same name. + +sadly i don't think overlayfs support it, but it might still be worth a try + + + +## TODO: + +1. we need a name for this. +2. add more game to the code, currently i only have Skyrim se. +3. replace the copy of the games files by hard links if available. +4. fomod support + +## Compilation and install instructions: +download a version from the releases(please avoir a simple clone of the git). + +then run this inside the folder: +```bash +mkdir build +cd build +cmake .. +make +``` + +then copy the "ModManager" file to wherever you want. (i recommend ~/.local/bin/) diff --git a/note for future developments.txt b/note for future developments.txt new file mode 100644 index 0000000..d4993f8 --- /dev/null +++ b/note for future developments.txt @@ -0,0 +1,4 @@ +1. +only support betheshda game for now, i spent enough time codding this. +2. +try alternatives to overlayfs diff --git a/src/file.c b/src/file.c new file mode 100644 index 0000000..e9c1130 --- /dev/null +++ b/src/file.c @@ -0,0 +1,84 @@ +#include +#include +#include +#include +#include "file.h" +#include + +u_int32_t countSetBits(u_int32_t n) { + // base case + if (n == 0) + return 0; + else + // if last bit set add 1 else add 0 + return (n & 1) + countSetBits(n >> 1); +} + +//simplest way to copy a file in c(linux) +int copy(const char * path, const char * dest, u_int32_t flags) { + int flagCount = countSetBits(flags); + if(flagCount > 3) { + printf("Invalid flags for cp command\n"); + return -1; + } + //flags + cp + path + dest + const char * args[flagCount + 4]; + memset(args, 0, (flagCount + 4) * sizeof(char *)); + args[0] = "/bin/cp"; + args[1] = path; + args[2] = dest; + int argIndex = 3; + + if(flags & CP_LINK) { + args[argIndex] = "--link"; + argIndex += 1; + } + if(flags & CP_RECURSIVE) { + args[argIndex] = "-r"; + argIndex += 1; + } + if(flags & CP_NO_TARGET_DIR) { + args[argIndex] = "-T"; + argIndex += 1; + } + + + int pid = fork(); + if(pid == 0) { + //discard the const. since we are in a fork we don't care. + execv("/bin/cp", (char **)args); + return 0; + } else { + int returnValue; + waitpid(pid, &returnValue, 0); + return returnValue; + } +} + +int delete(const char * path, bool recursive) { + int pid = fork(); + if(pid == 0) { + if(recursive) { + execl("/bin/rm", "/bin/rm", "-r", path, NULL); + } else { + execl("/bin/rm", "/bin/rm", path, NULL); + } + return 0; + } else { + int returnValue; + waitpid(pid, &returnValue, 0); + return returnValue; + } +} + +int move(const char * source, const char * destination) { + int pid = fork(); + if(pid == 0) { + execl("/bin/mv", "/bin/mv", source, destination, NULL); + return 0; + } else { + int returnValue; + waitpid(pid, &returnValue, 0); + return returnValue; + } +} diff --git a/src/file.h b/src/file.h new file mode 100644 index 0000000..02e1a65 --- /dev/null +++ b/src/file.h @@ -0,0 +1,15 @@ +#include +#include + +#ifndef __FILE_H__ +#define __FILE_H__ + +#define CP_LINK 1 +#define CP_RECURSIVE 2 +#define CP_NO_TARGET_DIR 4 + +int copy(const char * path, const char * dest, u_int32_t flags); +int delete(const char * path, bool recursive); +int move(const char * source, const char * destination); + +#endif diff --git a/src/getHome.c b/src/getHome.c new file mode 100644 index 0000000..e294d51 --- /dev/null +++ b/src/getHome.c @@ -0,0 +1,9 @@ +#include +#include +#include + +char * getHome() { + //not getting home from the env enable us to use sudo + struct passwd *pw = getpwuid(audit_getloginuid()); + return strdup(pw->pw_dir); +} diff --git a/src/getHome.h b/src/getHome.h new file mode 100644 index 0000000..d242b54 --- /dev/null +++ b/src/getHome.h @@ -0,0 +1 @@ +char * getHome(); diff --git a/src/install.c b/src/install.c new file mode 100644 index 0000000..a820672 --- /dev/null +++ b/src/install.c @@ -0,0 +1,105 @@ + +#include +#include +#include +#include +#include +#include "install.h" +#include "main.h" + +//TODO: replace ALL system call by execv / execl since it make my code into swiss cheese + +void unzip(const char * path, const char * outdir) { + char * unzipCommand = g_strconcat("/bin/sh -c 'yes | unzip \"", path, "\" -d \"" , outdir, "\" > /dev/null'", NULL); + if(system(unzipCommand) != 0) { + printf("\nFailed to unzip archive\n"); + exit(EXIT_FAILURE); + } + free(unzipCommand); + +} + +void unrar(const char * path, const char * outdir) { + char * unrarCommand = g_strconcat("/bin/sh -c 'unrar -y x \"", path, "\" \"", outdir, "\" > /dev/null'", NULL); + if(system(unrarCommand) != 0) { + printf("Failed to unzip archive\n"); + exit(EXIT_FAILURE); + } + free(unrarCommand); +} + +void un7z(const char * path, const char * outdir) { + char * un7zCommand = g_strconcat("/bin/sh -c 'yes | 7z x \"", path, "\" \"-o", outdir, "\" > /dev/null'", NULL); + if(system(un7zCommand) != 0) { + printf("Failed to unzip archive\n"); + exit(EXIT_FAILURE); + } + free(un7zCommand); +} + +char * extractLastPart(const char * filePath, const char delimeter) { +int length = strlen(filePath); + int index = -1; + for(int i= length -1; i >= 0; i--) { + if(filePath[i] == delimeter) { + index = i + 1; + break; + } + } + + if(index <= 0) return NULL; + char * extension = malloc((length - index) * sizeof(char)); + memcpy(extension, &filePath[index], (length - index)); + return extension; +} + +char * extractExtension(const char * filePath) { + return extractLastPart(filePath, '.'); +} + +char * extractFileName(const char * filePath) { + return extractLastPart(filePath, '/'); +} + + +void addMod(const char * filePath, int appId) { + if (access(filePath, F_OK) != 0) { + printf("File not found\n"); + exit(EXIT_FAILURE); + } + + char * configFolder = g_build_filename(getenv("HOME"), MANAGER_FILES, NULL); + if(g_mkdir_with_parents(configFolder, 0755) < 0) { + printf("Could not create mod folder"); + exit(EXIT_FAILURE); + } + + char * filename = extractFileName(filePath); + char * extension = extractExtension(filename); + char * lowercaseExtension = g_ascii_strdown(extension, -1); + free(extension); + + char appIdStr[20]; + sprintf(appIdStr, "%d", appId); + + char * outdir = g_build_filename(configFolder, MOD_FOLDER_NAME, appIdStr, filename, NULL); + + g_mkdir_with_parents(outdir, 0755); + printf("Adding mod, this process can be slow depending on your hardware\n"); + if(strcmp(lowercaseExtension, "rar") == 0) { + unrar(filePath, outdir); + } else if (strcmp(lowercaseExtension, "zip") == 0) { + unzip(filePath, outdir); + } else if (strcmp(lowercaseExtension, "7z") == 0) { + un7z(filePath, outdir); + } else { + printf("Unsupported format only zip/7z/rar are supported\n"); + exit(EXIT_FAILURE); + } + + printf("Done\n"); + + free(lowercaseExtension); + free(filename); + free(outdir); +} diff --git a/src/install.h b/src/install.h new file mode 100644 index 0000000..5ec6138 --- /dev/null +++ b/src/install.h @@ -0,0 +1,6 @@ +#ifndef __INSTALL_H__ +#define __INSTALL_H__ +#define INSTALLED_FLAG_FILE "__DO_NOT_REMOVE__" +void addMod(const char * filePath, int appId); + +#endif diff --git a/src/macro.h b/src/macro.h new file mode 100644 index 0000000..82803a9 --- /dev/null +++ b/src/macro.h @@ -0,0 +1,7 @@ +#ifndef __MACRO_H__ +#define __MACRO_H__ + +//cannot be empty it's made for fixed size array +#define LEN(array) sizeof(array) / sizeof(array[0]) + +#endif diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..e71c012 --- /dev/null +++ b/src/main.c @@ -0,0 +1,425 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "overlayfs.h" +#include "install.h" +#include "getHome.h" +#include "steam.h" +#include "main.h" +#include "file.h" + +GHashTable * gamePaths; + +bool isRoot() { + return getuid() == 0; +} + +GList * listFilesInFolder(const char * path) { + GList * list = NULL; + DIR *d; + struct dirent *dir; + d = opendir(path); + if (d) { + while ((dir = readdir(d)) != NULL) { + //removes .. & . from the list + if(strcmp(dir->d_name, "..") != 0 && strcmp(dir->d_name, ".") != 0) { + list = g_list_append(list, strdup(dir->d_name)); + } + } + closedir(d); + } + + return list; +} + +int noRoot() { + printf("Don't run this argument as root\n"); + return EXIT_FAILURE; +} + +int needRoot() { + printf("Root is needed to bind with the game files\n"); + return EXIT_FAILURE; +} + +int usage() { + printf("Use --list-games or -l to list compatible games\n"); + printf("Use --add or -a to add a mod to a game\n"); + printf("Use --list-mods or -m to list all mods for a game\n"); + printf("Use --install or -i to add a mod to a game\n"); + printf("Use --remove or -r to remove a mod from a game\n"); + printf("Use --deploy or -d to deploy the mods for the game\n"); + printf("Use --unbind or -u to rollback a deployment\n"); + //TODO: as bonus + //printf("Use --start-game to deploy the mods and launch the game through steam\n"); + //printf("Use --steam in team cmdline options to deploy directly on game startup\n"); + return EXIT_FAILURE; +} + +int validateAppId(const char * appIdStr) { + //strtoul set EINVAL(after C99) if the string is invalid + u_int32_t appid = strtoul(appIdStr, NULL, 10); + if(errno == EINVAL) { + printf("Appid has to be a valid number\n"); + return -1; + } + + int gameId = getGameIdFromAppId(appid); + if(gameId < 0) { + printf("Game is not compatible\n"); + return -1; + } + + if(!g_hash_table_contains(gamePaths, &gameId)) { + printf("Game not found\n"); + return -1; + } + + return appid; +} + +int listGames(int argc, char ** argv) { + if(argc != 2) return usage(); + GList * gamesIds = g_hash_table_get_keys(gamePaths); + if(g_list_length(gamesIds) == 0) { + printf("No game found\n"); + } else { + while(gamesIds != NULL) { + int * gameIndex = (int*)gamesIds->data; + printf("%d: %s\n", GAMES_APPIDS[*gameIndex], GAMES_NAMES[*gameIndex]); + gamesIds = g_list_next(gamesIds); + } + } + return EXIT_SUCCESS; +} + +int add(int argc, char ** argv) { + if(argc != 4) return usage(); + char * appIdStr = argv[2]; + + u_int32_t appid = validateAppId(appIdStr); + if(appid < 0) { + return EXIT_FAILURE; + } + + addMod(argv[3], appid); + return EXIT_SUCCESS; +} + +int listMods(int argc, char ** argv) { + if(argc != 3) return usage(); + char * appIdStr = argv[2]; + if(validateAppId(appIdStr) < 0) { + return EXIT_FAILURE; + } + + //might crash if no mods were installed + char * modFolder = g_build_filename(getenv("HOME"), MANAGER_FILES, MOD_FOLDER_NAME, appIdStr, NULL); + GList * mods = listFilesInFolder(modFolder); + unsigned short index = 0; + + printf("Id | Installed | Name\n"); + while(mods != NULL) { + char * modName = (char*)mods->data; + char * modPath = g_build_filename(modFolder, modName, INSTALLED_FLAG_FILE, NULL); + + if(access(modPath, F_OK) == 0) { + printf("\033[0;32m %d | ✓ | %s\n", index, modName); + } else { + printf("\033[0;31m %d | ✕ | %s\n", index, modName); + } + + index++; + mods = g_list_next(mods); + } + + + free(modFolder); + free(mods); + return EXIT_SUCCESS; +} + + +/* + * THIS WILL NOT INSTALL THE MOD + * this will just flag the mod as needed to be deployed + * it's the deploying process that handle the rest +*/ +int installAndRemoveMod(int argc, char ** argv, bool install) { + if(argc != 4) return usage(); + char * appIdStr = argv[2]; + u_int32_t appid = validateAppId(appIdStr); + if(appid < 0) { + return EXIT_FAILURE; + } + + //strtoul set EINVAL(after C99) if the string is invalid + u_int32_t modId = strtoul(argv[3], NULL, 10); + if(errno == EINVAL) { + printf("Appid has to be a valid number\n"); + return -1; + } + + //might crash if no mods were installed + char * modFolder = g_build_filename(getenv("HOME"), MANAGER_FILES, MOD_FOLDER_NAME, appIdStr, NULL); + GList * mods = listFilesInFolder(modFolder); + GList * modsFirstPointer = mods; + + for(int i = 0; i < modId; i++) { + mods = g_list_next(mods); + } + + if(mods == NULL) { + printf("Mod not found\n"); + return EXIT_FAILURE; + } + + char * modName = (char*)mods->data; + char * modFlag = g_build_filename(modFolder, modName, INSTALLED_FLAG_FILE, NULL); + + if(install) { + if(access(modFlag, F_OK) == 0) { + printf("The mod is already activated \n"); + return EXIT_SUCCESS; + } + + //Create activated file + FILE * fd = fopen(modFlag, "w"); + fwrite("", 1, 1, fd); + fclose(fd); + } else { + if(access(modFlag, F_OK) != 0) { + printf("The mod is not activated \n"); + return EXIT_SUCCESS; + } + + if(unlink(modFlag) != 0) { + printf("Error could not disable the mod.\n"); + printf("please remove this file '%s' as root\n", modFlag); + return EXIT_FAILURE; + } + } + + free(modFolder); + g_list_free(modsFirstPointer); + return EXIT_SUCCESS; +} + +int deploy(int argc, char ** argv) { + if(argc != 3) return usage(); + + char * appIdStr = argv[2]; + int appid = validateAppId(appIdStr); + if(appid < 0) { + return EXIT_FAILURE; + } + + char * home = getHome(); + char * gameFolder = g_build_filename(home, MANAGER_FILES, GAME_FOLDER_NAME, appIdStr, NULL); + + if(access(gameFolder, F_OK) != 0) { + printf("Please run '%s --setup %d' first", APP_NAME, appid); + } + + //unmount everything beforhand + //might crash if no mods were installed + char * modFolder = g_build_filename(home, MANAGER_FILES, MOD_FOLDER_NAME, appIdStr, NULL); + + GList * mods = listFilesInFolder(modFolder); + //since the priority is by alphabetical order + //and we need to bind the least important first + //and the most important last + //we have to reverse the list + mods = g_list_reverse(mods); + + //probably over allocating but this doesn't matter that much + char * modsToInstall[g_list_length(mods) + 2]; + int modCount = 0; + + while(true) { + if(mods == NULL)break; + char * modName = (char *)mods->data; + char * modPath = g_build_path("/", modFolder, modName, NULL); + char * modFlag = g_build_filename(modPath, INSTALLED_FLAG_FILE, NULL); + + //if the mod is not marked to be deployed then don't + if(access(modFlag, F_OK) != 0) { + printf("ignoring mod %s\n", modName); + mods = g_list_next(mods); + continue; + } + + //this is made to leave the first case empty so i can put lowerdir in it before feeding it to g_strjoinv + printf("Installing %s\n", modName); + modsToInstall[modCount] = modPath; + modCount += 1; + + mods = g_list_next(mods); + free(modFlag); + } + + //const char * data = "lowerdir=gameFolder,gameFolder2,gameFolder3..." + modsToInstall[modCount] = gameFolder; + modsToInstall[modCount + 1] = NULL; + printf("Mounting the overlay\n"); + int gameId = getGameIdFromAppId(appid); + const char * path = g_hash_table_lookup(gamePaths, &gameId); + char * steamGameFolder = g_build_path("/", path, "steamapps/common", GAMES_NAMES[gameId], "Data", NULL); + printf("%s\n", steamGameFolder); + + char * gameUpperDir = g_build_filename(home, MANAGER_FILES, GAME_UPPER_DIR_NAME, appIdStr, NULL); + char * gameWorkDir = g_build_filename(home, MANAGER_FILES, GAME_WORK_DIR_NAME, appIdStr, NULL); + + //unmount the game folder + //DETACH + FORCE allow us to be sure it will be unload. + //it might crash / corrupt game file if the user do it while the game is running + //but it's still very unlikely + while(umount2(steamGameFolder, MNT_FORCE | MNT_DETACH) == 0); + int status = overlayMount(modsToInstall, steamGameFolder, gameUpperDir, gameWorkDir); + if(status == 0) { + printf("Everything is ready, just launch the game\n"); + } else if(status == -1) { + printf("Could not mount the mods overlay, try to install fuse-overlay\n"); + return EXIT_FAILURE; + } else if(status == -2) { + printf("Could not mount the mods overlay\n"); + return EXIT_FAILURE; + } else { + printf("%d take a screenshot and go insult the dev that let this passthrough\n", __LINE__); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} + +int setup(int argc, char ** argv) { + if(argc != 3 ) return usage(); + char * appIdStr = argv[2]; + int appid = validateAppId(appIdStr); + if(appid < 0) { + return EXIT_FAILURE; + } + int gameId = getGameIdFromAppId(appid); + char * home = getHome(); + + char * gameUpperDir = g_build_filename(home, MANAGER_FILES, GAME_UPPER_DIR_NAME, appIdStr, NULL); + char * gameWorkDir = g_build_filename(home, MANAGER_FILES, GAME_WORK_DIR_NAME, appIdStr, NULL); + g_mkdir_with_parents(gameUpperDir, 0755); + g_mkdir_with_parents(gameWorkDir, 0755); + free(gameUpperDir); + free(gameWorkDir); + + const char * path = g_hash_table_lookup(gamePaths, &gameId); + char * steamGameFolder = g_build_path("/", path, "steamapps/common", GAMES_NAMES[gameId], "Data", NULL); + + char * gameFolder = g_build_filename(home, MANAGER_FILES, GAME_FOLDER_NAME, appIdStr, NULL); + if(access(gameFolder, F_OK) == 0) { + //if the game folder alredy exists just delete it + //this will allow the removal of dlcs and language change + delete(gameFolder, true); + } + g_mkdir_with_parents(gameFolder, 0755); + + //links don't conflict with overlayfs and avoid coping 17Gb of files. + //but links require the files to be on the same filesystem + const int returnValue = copy(steamGameFolder, gameFolder, CP_RECURSIVE | CP_NO_TARGET_DIR | CP_LINK); + if(returnValue < 0) copy(steamGameFolder, gameFolder, CP_RECURSIVE | CP_NO_TARGET_DIR); + + free(steamGameFolder); + free(gameFolder); + printf("Done\n"); + return EXIT_SUCCESS; +} + +int unbind(int argc, char ** argv) { + if(argc != 3 ) return usage(); + char * appIdStr = argv[2]; + int appid = validateAppId(appIdStr); + if(appid < 0) { + return EXIT_FAILURE; + } + int gameId = getGameIdFromAppId(appid); + const char * path = g_hash_table_lookup(gamePaths, &gameId); + char * steamGameFolder = g_build_path("/", path, "steamapps/common", GAMES_NAMES[gameId], "Data", NULL); + while(umount2(steamGameFolder, MNT_FORCE | MNT_DETACH)); + + free(steamGameFolder); + return EXIT_SUCCESS; +} + +int main(int argc, char ** argv) { + if(argc < 2 ) return usage(); + + + if(audit_getloginuid() == 0) { + printf("Root user should not be using this\n"); + return EXIT_FAILURE; + } + + gamePaths = search_games(); + + + + + char * configFolder = g_build_filename(getHome(), MANAGER_FILES, NULL); + if(access(configFolder, F_OK) != 0) { + //check to NOT run this as root + //creating folder as root will causes lots of headache + if(getuid() == 0) { + printf("For the first please run without sudo\n"); + return EXIT_FAILURE; + } else { + //leading 0 == octal + int i = g_mkdir_with_parents(configFolder, 0755); + if(i < 0) { + printf("Could not create configs, check access rights for this path: %s", configFolder); + } + //try to enable casefold + //failure would have no impact + char * chattrcommand = g_strjoin("", "chattr +F ",configFolder, " 2> /dev/null", NULL); + system(chattrcommand); + free(chattrcommand); + } + } + free(configFolder); + + + if(strcmp(argv[1], "--list-games") == 0 || strcmp(argv[1], "-l") == 0) { + if(isRoot()) return noRoot(); + return listGames(argc, argv); + } else if(strcmp(argv[1], "--add") == 0 || strcmp(argv[1], "-a") == 0) { + if(isRoot()) return noRoot(); + return add(argc, argv); + } else if(strcmp(argv[1], "--list-mods") == 0 || strcmp(argv[1], "-m") == 0) { + if(isRoot()) return noRoot(); + return listMods(argc, argv); + } else if(strcmp(argv[1], "--install") == 0 || strcmp(argv[1], "-i") == 0) { + if(isRoot()) return noRoot(); + return installAndRemoveMod(argc, argv, true); + } else if(strcmp(argv[1], "--remove") == 0 || strcmp(argv[1], "-r") == 0) { + if(isRoot()) return noRoot(); + return installAndRemoveMod(argc, argv, false); + } else if(strcmp(argv[1], "--deploy") == 0 || strcmp(argv[1], "-d") == 0) { + if(!isRoot()) return needRoot(); + return deploy(argc, argv); + } else if(strcmp(argv[1], "--unbind") == 0 || strcmp(argv[1], "-u") == 0){ + if(!isRoot()) return needRoot(); + return unbind(argc, argv); + } else if(strcmp(argv[1], "--setup") == 0) { + if(isRoot()) return noRoot(); + return setup(argc, argv); + } else { + return usage(); + } + + + return 0; +} diff --git a/src/main.h b/src/main.h new file mode 100644 index 0000000..9474864 --- /dev/null +++ b/src/main.h @@ -0,0 +1,8 @@ +#define APP_NAME "modmanager" +//relative to home the url is not preprocessed so ../ might prose some issues +// in c "A" "B" is the same as "AB" +#define MANAGER_FILES ".local/share/" APP_NAME +#define MOD_FOLDER_NAME "MOD_FOLDER" +#define GAME_FOLDER_NAME "GAME_FOLDER" +#define GAME_UPPER_DIR_NAME "UPPER_DIRS" +#define GAME_WORK_DIR_NAME "WORK_DIRS" diff --git a/src/overlayfs.c b/src/overlayfs.c new file mode 100644 index 0000000..43a6b49 --- /dev/null +++ b/src/overlayfs.c @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include +#include "overlayfs.h" +#include + +int overlayMount(char ** sources, const char * dest, const char * upperdir, const char * workdir) { + char * lowerdir = g_strjoinv(":", sources); + char * mountData = g_strjoin("", "lowerdir=", lowerdir, ",workdir=", workdir, ",upperdir=", upperdir, NULL); + int result = mount("overlay", "none", "overlay", MS_RDONLY, mountData); + if(result < 0) { + //this is very important for a lot of filesystems + //even ext4 can be incompatible with the kernel's implementation + //with some flags such as casefold + if(access("/usr/bin/fuse-overlayfs", F_OK) == 0) { + + int pid = fork(); + if(pid == 0) { + //exit is used to get the return value when using waitpid + exit(execl("/usr/bin/fuse-overlayfs", "/usr/bin/fuse-overlayfs", "-r", "-o", mountData, dest, NULL)); + } else { + + int returnValue = 0; + waitpid(pid, &returnValue, 0); + free(lowerdir); + free(mountData); + if(returnValue != 0) { + return -2; + } + return 0; + } + + } else { + free(lowerdir); + free(mountData); + return -1; + } + } + free(lowerdir); + free(mountData); + return 0; +} diff --git a/src/overlayfs.h b/src/overlayfs.h new file mode 100644 index 0000000..438335e --- /dev/null +++ b/src/overlayfs.h @@ -0,0 +1,6 @@ +#ifndef __OVERLAY_H__ +#define __OVERLAY_H__ + +int overlayMount(char ** sources, const char * dest, const char * upperdir, const char * workdir); + +#endif diff --git a/src/steam.c b/src/steam.c new file mode 100644 index 0000000..3a908a1 --- /dev/null +++ b/src/steam.c @@ -0,0 +1,211 @@ +#include "steam.h" +#include "macro.h" +#include "getHome.h" +#include +#include +#include +#include +#include +#include +#include +#include + +//TODO: optimise and replace reallocs + +enum FieldIds { FIELD_PATH, FIELD_LABEL, FIELD_CONTENT_ID, FIELD_TOTAL_SIZE, FIELD_CLEAN_BYTES, FIELD_CORRUPTION, FIELD_APPS }; + +int getFiledId(const char * field) { + //replace with a hash + switch + if(strcmp(field, "path") == 0) { + return FIELD_PATH; + } else if(strcmp(field, "label") == 0) { + return FIELD_LABEL; + } else if(strcmp(field, "contentid") == 0) { + return FIELD_CONTENT_ID; + } else if(strcmp(field, "totalsize") == 0) { + return FIELD_TOTAL_SIZE; + } else if(strcmp(field, "update_clean_bytes_tally") == 0) { + return FIELD_CLEAN_BYTES; + } else if(strcmp(field, "time_last_update_corruption") == 0) { + return FIELD_CORRUPTION; + } else if(strcmp(field, "apps") == 0) { + return FIELD_APPS; + } else { + printf("unknown field"); + exit(EXIT_FAILURE); + } +} + +ValveLibraries_t * parseVDF(const char * path, size_t * size) { + FILE * fd = fopen(path, "r"); + char * line = NULL; + size_t len = 0; + ssize_t read; + + + + bool inQuotes = false; + + ValveLibraries_t * libraries = NULL; + *size = 0; + + //skip the "libraryfolders" label & the first opening brace + getline(&line, &len, fd); + getline(&line, &len, fd); + + int braceDepth = 0; + + //can support up to 1024 car in quotes; + char buffer[1024]; + bool isAppId = TRUE; + int bufferIndex = 0; + int nextFieldToFill = -1; + + while (getline(&line, &len, fd) != -1) { + for(int i = 0; line[i] != '\0'; i++) { + switch (line[i]) { + case '"': + if(braceDepth == 0) { + //this is a library id so we don't care. + bufferIndex = 0; + } else { + //actual data + if(inQuotes) { + inQuotes = FALSE; + buffer[bufferIndex] = '\0'; + if(nextFieldToFill == -1) { + nextFieldToFill = getFiledId(buffer); + + } else { + char * value = strndup(buffer, bufferIndex); + ValveLibraries_t * library = &libraries[*size - 1]; + switch (nextFieldToFill) { + case FIELD_PATH: + library->path = value; + break; + + case FIELD_LABEL: + library->label = value; + break; + + case FIELD_CONTENT_ID: + library->contentId = value; + break; + + case FIELD_TOTAL_SIZE: + library->totalSize = strtoul(value, NULL, 0); + break; + + case FIELD_CLEAN_BYTES: + library->update_clean_bytes_tally = value; + break; + + case FIELD_CORRUPTION: + library->time_last_update_corruption = value; + break; + + case FIELD_APPS: + if(isAppId) { + library->appsCount++; + library->apps = realloc(library->apps, library->appsCount * sizeof(ValveApp_t)); + unsigned int appid = strtoul(value, NULL, 10); + library->apps[library->appsCount - 1].appid = appid; + } else { + library->apps[library->appsCount - 1].update = strtoul(value, NULL, 10); + } + isAppId = !isAppId; + break; + } + //field apps is using braces so the syntax is different + if(nextFieldToFill != FIELD_APPS)nextFieldToFill = -1; + } + } else { + inQuotes = TRUE; + } + bufferIndex = 0; + + } + break; + case '{': + braceDepth++; + if(braceDepth == 1) { + *size += 1; + libraries = realloc(libraries, sizeof(ValveLibraries_t) * (*size)); + memset(&libraries[*size - 1], 0, sizeof(ValveLibraries_t)); + } + break; + case '}': + if(inQuotes) { + printf("Syntax error in VDF\n"); + exit(EXIT_FAILURE); + } + if(nextFieldToFill == FIELD_APPS) { + nextFieldToFill = -1; + } + braceDepth--; + break; + + default: + if(inQuotes) { + buffer[bufferIndex++] = line[i]; + } + } + } + } + + fclose(fd); + return libraries; +} + +GHashTable* search_games() { + ValveLibraries_t * libraries = NULL; + size_t size = 0; + const char * HOME = getHome(); + + for(int i = 0; i < LEN(steamLibraries); i++) { + char * path = g_build_filename(HOME, steamLibraries[i], "steamapps/libraryfolders.vdf", NULL); + if (access(path, F_OK) == 0) { + libraries = parseVDF(path, &size); + break; + } + + g_free(path); + } + + GHashTable* table = g_hash_table_new(g_int_hash, g_int_equal); + + //fill the table + for(int i = 0; i < size; i++) { + for(int j = 0; j < libraries[i].appsCount; j++) { + int gameId = getGameIdFromAppId(libraries[i].apps[j].appid); + if(gameId >= 0) { + int * key = malloc(sizeof(int)); + *key = gameId; + g_hash_table_insert(table, key, strdup(libraries[i].path)); + } + } + } + + //free used up memory + for(int i = 0; i < size; i++) { + free(libraries[i].path); + free(libraries[i].label); + free(libraries[i].contentId); + free(libraries[i].update_clean_bytes_tally); + free(libraries[i].time_last_update_corruption); + free(libraries[i].apps); + } + + if(libraries != NULL) free(libraries); + return table; +} + + +int getGameIdFromAppId(u_int32_t id) { + for(int k = 0; k < LEN(GAMES_APPIDS); k++) { + if(id == GAMES_APPIDS[k]) { + return k; + } + } + return -1; +} diff --git a/src/steam.h b/src/steam.h new file mode 100644 index 0000000..c96cfe9 --- /dev/null +++ b/src/steam.h @@ -0,0 +1,49 @@ +#ifndef __STEAM_H__ +#define __STEAM_H__ + +#include +#include +#include +#include +#include + +typedef struct ValveApp { + unsigned int appid; + unsigned int update; +} ValveApp_t; + +typedef struct ValveLibraries { + char * path; + char * label; + char * contentId; + unsigned long totalSize; + char * update_clean_bytes_tally; + char * time_last_update_corruption; + ValveApp_t * apps; + size_t appsCount; +} ValveLibraries_t; + +// relative to the home directory +const static char * steamLibraries[] = { + "/.steam/root/", + "/.steam/steam/", + "/.local/share/steam", + //flatpack steam. + "/.var/app/com.valvesoftware.Steam/.local/share/Steam" +}; + +//todo add the older games +// order has to be the same as in GAMES_NAMES +const static u_int32_t GAMES_APPIDS[] = { + 489830, +}; + +//the name of the game in the steamapps/common folder +const static char * GAMES_NAMES[] = { + "Skyrim Special Edition", +}; + +GHashTable * search_games(); +int getGameIdFromAppId(u_int32_t id); + +#endif