commit be2dac2b6058e041a05aca3e2c0da6de4b1bd74e Author: rjindael Date: Sat Oct 22 16:43:41 2022 -0700 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..301d88c --- /dev/null +++ b/.gitignore @@ -0,0 +1,401 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates +*.svcmap +*.datainfo +*.svcinfo + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + 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 +them 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey 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; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If 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 convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + 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. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +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. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + 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 +state 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 Affero General Public License as published + by the Free Software Foundation, either version 3 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c6c03f3 --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# Tadah.Arbiter +Manages Tadah game servers + +Fork of [ProjectPolygon/PolygonGSArbiter](https://github.com/ProjectPolygon/PolygonGSArbiter). + +## CI/CD +Tadah.Arbiter is available on the Tadah CI. All builds are compiled as release, and a build occurs per push. + +- [win-x86](https://ci.tadah.sipr/buildConfiguration/Tadah_Arbiter_WinX86) +- [win-x64](https://ci.tadah.sipr/buildConfiguration/Tadah_Arbiter_WinX64) +- [linux-x64](https://ci.tadah.sipr/buildConfiguration/Tadah_Arbiter_LinuxX64) + +## Operations +- `OpenJob (string jobId, int placeId, ClientVersion version)` +- `CloseJob (string jobId)` +- `ExecuteScript (string jobId, string script)` +- `RenewTampaJobLease (string jobId, int expirationInSeconds)` +- `CloseAllJobs (int)` +- `CloseAllTampaProcesses (int)` +- `Thumbnail (AssetType type, int assetId, string? accessKey)` + +## License +~~Copyright (c) Tadah and Project Polygon 2022. All rights reserved. Forked with permission. Not for public use.~~ + +Licensed under the GNU Affero General Public License v3.0. A copy of it [has been included](https://github.com/tadah-foss/arbiter/blob/trunk/LICENSE). \ No newline at end of file diff --git a/Tadah.Arbiter.sln b/Tadah.Arbiter.sln new file mode 100644 index 0000000..857e773 --- /dev/null +++ b/Tadah.Arbiter.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.1.32421.90 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tadah.Arbiter", "Tadah.Arbiter\Tadah.Arbiter.csproj", "{21310A44-340D-4712-BF1A-74AE20806961}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {21310A44-340D-4712-BF1A-74AE20806961}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {21310A44-340D-4712-BF1A-74AE20806961}.Debug|Any CPU.Build.0 = Debug|Any CPU + {21310A44-340D-4712-BF1A-74AE20806961}.Release|Any CPU.ActiveCfg = Release|Any CPU + {21310A44-340D-4712-BF1A-74AE20806961}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {93A0B010-BFC3-4FDE-AC74-4918DBE63B82} + EndGlobalSection +EndGlobal diff --git a/Tadah.Arbiter/Configuration.cs b/Tadah.Arbiter/Configuration.cs new file mode 100644 index 0000000..57b1220 --- /dev/null +++ b/Tadah.Arbiter/Configuration.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using Microsoft.Extensions.Configuration; + +namespace Tadah.Arbiter +{ + public static class Configuration + { + public static Guid Uuid { get; set; } + public static int ServicePort { get; set; } + public static int BasePlaceJobPort { get; set; } + public static int BaseTampaSoapPort { get; set; } + public static int MaximumTampaProcesses { get; set; } + public static int MaximumJobsPerTampaProcess { get; set; } + public static int MaximumPlaceJobs { get; set; } + public static int MaximumThumbnailJobs { get; set; } + public static int MaximumThumbnailJobsPerThumbnailer { get; set; } + public static int Thumbnailers { get; set; } + + public static readonly IConfiguration AppSettings = GetAppSettings(); + + public static IConfiguration GetAppSettings() + { + var builder = new ConfigurationBuilder() + .SetBasePath(AppContext.BaseDirectory) + .AddJsonFile("AppSettings.json", + optional: true, + reloadOnChange: true); + + return builder.Build(); + } + + public static void Load() + { + Dictionary identification = Http.Identify(); + + Uuid = Guid.Parse((string)identification["uuid"]); + BasePlaceJobPort = (int)identification["base_place_job_port"]; + BaseTampaSoapPort = (int)identification["base_tampa_soap_port"]; + MaximumTampaProcesses = (int)identification["maximum_tampa_processes"]; + MaximumJobsPerTampaProcess = (int)identification["maximum_jobs_per_tampa_process"]; + MaximumPlaceJobs = (int)identification["maximum_place_jobs"]; + MaximumThumbnailJobs = (int)identification["maximum_thumbnail_jobs"]; + MaximumThumbnailJobsPerThumbnailer = (int)identification["maximum_thumbnail_jobs_per_thumbnailer"]; + Thumbnailers = (int)identification["thumbnailers"]; + } + } +} diff --git a/Tadah.Arbiter/Connected Services/Tadah.Tampa.Server/ConnectedService.json b/Tadah.Arbiter/Connected Services/Tadah.Tampa.Server/ConnectedService.json new file mode 100644 index 0000000..627d0c0 --- /dev/null +++ b/Tadah.Arbiter/Connected Services/Tadah.Tampa.Server/ConnectedService.json @@ -0,0 +1,17 @@ +{ + "ExtendedData": { + "inputs": [ + "../../Resources/TampaServerSoap.wsdl" + ], + "collectionTypes": [ + "System.Array", + "System.Collections.Generic.Dictionary`2" + ], + "namespaceMappings": [ + "*, Tadah.Tampa.Server" + ], + "sync": true, + "targetFramework": "net6.0", + "typeReuseMode": "None" + } +} \ No newline at end of file diff --git a/Tadah.Arbiter/Http.cs b/Tadah.Arbiter/Http.cs new file mode 100644 index 0000000..853c1e5 --- /dev/null +++ b/Tadah.Arbiter/Http.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Net.NetworkInformation; +using System.Runtime.InteropServices; +using Newtonsoft.Json; + +namespace Tadah.Arbiter +{ + public class Http + { + private static readonly HttpClient WebClient = new(); + private static readonly List> LogsToSend = new(); + + public static int GetAvailableMemory() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + PerformanceCounter performance = new("Memory", "Available MBytes"); + + return (int)performance.NextValue(); + } + + return (int)(GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 1048576.0); + } + + public static int GetCpuUsage() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + PerformanceCounter performance = new("Processor", "% Processor Time", "_Total"); + performance.NextValue(); // this is always gonna be zero + + Thread.Sleep(500); + + return (int)Math.Round(performance.NextValue()); + } + + var startTime = DateTime.UtcNow; + var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime; + + Thread.Sleep(500); + + var endTime = DateTime.UtcNow; + var endCpuUsage = Process.GetCurrentProcess().TotalProcessorTime; var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds; + var totalMsPassed = (endTime - startTime).TotalMilliseconds; var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed); + + return (int)(cpuUsageTotal * 100); + } + + public static Tuple GetNetworkTraffic() + { + if (!NetworkInterface.GetIsNetworkAvailable()) + { + return new Tuple(0, 0); + } + + NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); + + int sent = 0; + int received = 0; + + foreach (NetworkInterface ni in interfaces) + { + sent += (int)ni.GetIPStatistics().BytesSent; + received += (int)ni.GetIPStatistics().BytesReceived; + } + + return new Tuple(sent, received); + } + + public static string ConstructUrl(string path, bool https = true) + { + string scheme = "http"; + +#if (!DEBUG) + if (https) scheme += "s"; +#endif + + return $"{scheme}://{Configuration.AppSettings["BaseUrl"]}{path}"; + } + + public static string GetGameserverScript(string jobId, uint placeId, int port, bool returnData = false) + { + string url = $"/{jobId}/script?placeId={placeId}&port={port}&maxPlayers=10"; + + if (!returnData) + { + // Since this is called on Roblox, we must pass our key + return ConstructUrl(url + $"&{Configuration.AppSettings["AccessKey"]}", false); + } + + return Request(ConstructUrl(url), HttpMethod.Get); + } + + public static string Request(string uri, HttpMethod method, HttpContent content = null) + { + using (var message = new HttpRequestMessage(method, ConstructUrl(uri))) + { + message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Configuration.AppSettings["AccessKey"]); + + if (content != null && method == HttpMethod.Post) + { + message.Content = content; + } + + using HttpResponseMessage response = WebClient.SendAsync(message).Result; + using HttpContent httpContent = response.Content; + + return httpContent.ReadAsStringAsync().Result; + } + } + + public static void Log(LogSeverity severity, int timestamp, string output) + { + Dictionary data = new() + { + { "severity", ((int)severity).ToString() }, + { "timestamp", timestamp.ToString() }, + { "output", output }, + { "blur", (output.Contains(Configuration.AppSettings["AccessKey"]) ? Configuration.AppSettings["AccessKey"] : "") } + }; + + if (Configuration.Uuid == Guid.Empty) + { + LogsToSend.Add(data); + return; + } + + if (LogsToSend.Count > 0) + { + foreach (Dictionary log in LogsToSend) + { + Request($"/{Configuration.Uuid}/log", HttpMethod.Post, new FormUrlEncodedContent(log)); + } + + LogsToSend.Clear(); + } + + Request($"/{Configuration.Uuid}/log", HttpMethod.Post, new FormUrlEncodedContent(data)); + } + + public static void UpdateState(GameServerState state) + { + Request($"/{Configuration.Uuid}/status?state={(int)state}", HttpMethod.Get); + } + + public static void Fatal(string exception) + { + Dictionary data = new() + { + { "exception", exception } + }; + + Request($"/{Configuration.Uuid}/fatal", HttpMethod.Post, new FormUrlEncodedContent(data)); + } + + public static void StartResourceReporter() + { + while (true) + { + string ram = GetAvailableMemory().ToString(); + string cpu = GetCpuUsage().ToString(); + Tuple traffic = GetNetworkTraffic(); + + Dictionary data = new() + { + { "cpu", cpu }, + { "ram", ram }, + { "inbound", traffic.Item1.ToString() }, + { "outbound", traffic.Item2.ToString() } + }; + + FormUrlEncodedContent content = new(data); + + Request($"/{Configuration.Uuid}/resources", HttpMethod.Post, content); + + Thread.Sleep(15000); + } + } + + public static void UpdateJob(string jobId, JobStatus status, int port = 0) + { + string parameters = $"status={(int)status}"; + + if (port != 0) + { + parameters += $"&machine_address={Configuration.AppSettings["MachineAddress"]}"; + } + + Request($"/{jobId}/update?{parameters}", HttpMethod.Get); + } + + public static Dictionary Identify() + { + string offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow).ToString(); + offset = offset[0 .. ^3]; // "-07:00:00" -> "-07:00" + + Dictionary data = new() + { + { "machine_name", Environment.MachineName }, + { "utc_offset", offset } + }; + + return JsonConvert.DeserializeObject>(Request($"/identify", HttpMethod.Post, new FormUrlEncodedContent(data))); + } + } +} diff --git a/Tadah.Arbiter/Job.cs b/Tadah.Arbiter/Job.cs new file mode 100644 index 0000000..3aa57e2 --- /dev/null +++ b/Tadah.Arbiter/Job.cs @@ -0,0 +1,88 @@ +using System; +using System.Diagnostics; + +namespace Tadah.Arbiter +{ + [Flags] + public enum JobStatus + { + Pending = 0, + Started = 1, + Monitored = 2, + Closed = 3, + Crashed = 4 + } + + public abstract class Job + { + public string Id { get; set; } + public uint PlaceId { get; set; } + public Proto.ClientVersion Version { get; set; } + public int Port { get; set; } + public bool IsRunning { get; set; } + public JobStatus Status { get; set; } + public DateTime TimeCreated { get; set; } + public DateTime TimeStarted { get; set; } + public DateTime TimeClosed { get; set; } + public Process Process; + + protected abstract void InternalStart(); + protected abstract JobStatus InternalClose(bool forceClose = false); + public abstract void ExecuteScript(string script); + + protected void Log(string message, LogSeverity severity = LogSeverity.Information) + { + if (this is Tampa.Job) + { + Arbiter.Log.Write($"[TampaJob-{this.Id}] {message}", severity); + } + else if (this is Taipei.Job) + { + Arbiter.Log.Write($"[TaipeiJob-{this.Id}] {message}", severity); + } + } + + public void Start() + { + this.Log($"Starting {Version} on port {Port} ...", LogSeverity.Event); + Http.UpdateJob(Id, JobStatus.Pending, Port); + + this.InternalStart(); + + this.IsRunning = true; + this.Status = JobStatus.Started; + this.TimeStarted = DateTime.UtcNow; + Http.UpdateJob(Id, JobStatus.Started); + + this.Log($"Started!", LogSeverity.Event); + } + + public void Close(bool forceClose = false) + { + JobStatus state = this.InternalClose(forceClose); + + this.Status = state; + this.TimeClosed = DateTime.UtcNow; + + Http.UpdateJob(Id, state); + + if (this.Status == JobStatus.Crashed) + { + this.Log($"Crashed!", LogSeverity.Error); + } + + this.Log($"Closed with result '{Enum.GetName(state)}'", LogSeverity.Information); + } + + public Job(string Id, uint PlaceId, Proto.ClientVersion Version, int Port) + { + this.Id = Id; + this.PlaceId = PlaceId; + this.Version = Version; + this.Port = Port; + + this.Status = JobStatus.Pending; + this.TimeCreated = DateTime.UtcNow; + } + } +} diff --git a/Tadah.Arbiter/JobManager.cs b/Tadah.Arbiter/JobManager.cs new file mode 100644 index 0000000..2e7df7c --- /dev/null +++ b/Tadah.Arbiter/JobManager.cs @@ -0,0 +1,242 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Tadah.Arbiter +{ + public class JobManager + { + public static List OpenJobs = new(); + + [DllImport("User32.dll", CharSet = CharSet.Unicode)] + static extern IntPtr FindWindow(string lpClassName, string lpWindowName); + + [DllImport("User32.dll", CharSet = CharSet.Unicode)] + static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId); + + [DllImport("User32.dll", CharSet = CharSet.Unicode)] + static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); + + [DllImport("User32.dll", CharSet = CharSet.Unicode)] + static extern int GetWindowTextLength(IntPtr hWnd); + + public static string GetWindowTitle(IntPtr hWnd) + { + var length = GetWindowTextLength(hWnd) + 1; + var title = new StringBuilder(length); + GetWindowText(hWnd, title, length); + + return title.ToString(); + } + + public static string[] GetCommandLine(Proto.ClientVersion version, string scriptUrl, string jobId) + { + switch (version) + { + case Proto.ClientVersion.Taipei: + return new string[] { "Versions\\Taipei\\TadahServer.exe", $"-a https://tadah.rocks/Login/Negotiate.ashx -t 0 -j {scriptUrl} -jobId {jobId}" }; + + case Proto.ClientVersion.Tampa: + throw new Exception("Attempt to get command line for TampaJob"); + + default: + throw new Exception("Attempt to get command line for invalid version"); + } + } + + public static int GetAvailablePort() + { + int port = int.Parse(Configuration.AppSettings["BasePort"]); + + for (int i = 0; i < Configuration.BasePlaceJobPort; i++) + { + if (OpenJobs.Find(job => job.Port == port) == null) + { + break; + } + else + { + port++; + } + } + + return port; + } + + public static Job OpenJob(string jobId, uint placeId, Proto.ClientVersion version) + { + Job job; + int port = GetAvailablePort(); + + if (version == Proto.ClientVersion.Tampa) + { + job = new Tampa.Job(jobId, placeId, version, port); + } + else if (version == Proto.ClientVersion.Taipei) + { + job = new Taipei.Job(jobId, placeId, version, port); + } + else + { + throw new Exception("Invalid ClientVersion"); + } + + OpenJobs.Add(job); + job.Start(); + + return job; + } + + public static void CloseJob(string jobId, bool forceClose = false) + { + Job job = GetJobFromId(jobId); + if (job == null) + { + return; + } + + job.Close(forceClose); + OpenJobs.Remove(job); + } + + public static Job GetJobFromId(string jobId) + { + return OpenJobs.Find(job => job.Id == jobId); + } + + public static bool JobExists(string jobId) + { + return GetJobFromId(jobId) != null; + } + + public static bool IsValidVersion(object version) + { + if (!int.TryParse(version.ToString(), out int result)) + { + return false; + } + + return Enum.IsDefined(typeof(Proto.ClientVersion), result); + } + + public static void MonitorCrashedJobs() + { + while (true) + { + IntPtr hWnd = FindWindow(null, "Tadah Crash"); + GetWindowThreadProcessId(hWnd, out uint processId); + + if (processId != 0) + { + Job crashedJob = OpenJobs.Find(Job => Job.Process.Id == processId); + if (crashedJob != null) + { + Log.Write($"[JobManager] '{crashedJob.Id}' has crashed! Closing Job...", LogSeverity.Warning); + crashedJob.Status = JobStatus.Crashed; + crashedJob.Close(); + + OpenJobs.Remove(crashedJob); + } + } + + Thread.Sleep(5000); + } + } + + public static void MonitorUnresponsiveJobs() + { + while (true) + { + try + { + foreach (Job job in OpenJobs) + { + if (job is Tampa.Job) + { + continue; + } + + if (job.Status == JobStatus.Pending || job.Status == JobStatus.Monitored) + { + continue; + } + + if (job.Version == Proto.ClientVersion.Taipei && (Unix.From(job.TimeStarted) + 5 < Unix.Now()) && !GetWindowTitle(job.Process.MainWindowHandle).Contains("Place1")) + { + job.IsRunning = false; + } + + if (!job.IsRunning || job.Process.HasExited) + { + job.Close(); + OpenJobs.Remove(job); + + continue; + } + + if (job.Process.Responding) + { + continue; + } + + Task.Run(() => MonitorUnresponsiveJob(job)); + } + } + catch (InvalidOperationException ex) + { + Log.Write($"[JobManager::MonitorUnresponsiveJobs] InvalidOperationException - {ex.Message}", LogSeverity.Debug); + } + + Thread.Sleep(5000); + } + } + + public static void CloseAllJobs() + { + foreach (Job OpenJob in OpenJobs) + { + OpenJob.Close(); + } + + OpenJobs.Clear(); + Tampa.ProcessManager.CloseAllProcesses(); + } + + public static void MonitorUnresponsiveJob(Job job) + { + if (job is Job) + { + return; + } + + Log.Write($"[JobManager] '{job.Id}' is not responding! Monitoring...", LogSeverity.Warning); + job.Status = JobStatus.Monitored; + + for (int i = 0; i <= 30; i++) + { + Thread.Sleep(1000); + + if (job.Process.Responding) + { + Log.Write($"[JobManager] '{job.Id}' has recovered from its unresponsive status!", LogSeverity.Information); + job.Status = JobStatus.Started; + break; + } + else if (i == 30) + { + Log.Write($"[JobManager] '{job.Id}' has been unresponsive for over 30 seconds. Closing Job...", LogSeverity.Warning); + job.Status = JobStatus.Crashed; + job.Close(); + + OpenJobs.Remove(job); + break; + } + } + + return; + } + } +} diff --git a/Tadah.Arbiter/Log.cs b/Tadah.Arbiter/Log.cs new file mode 100644 index 0000000..c042fac --- /dev/null +++ b/Tadah.Arbiter/Log.cs @@ -0,0 +1,163 @@ +using System; +using System.IO; + +namespace Tadah.Arbiter +{ + public enum LogSeverity + { + Error = 0, // Red + Warning = 1, // Yellow + Event = 2, // Blue + Information = 3, // Grey + Debug = 4, // Dark Blue + Boot = 5 // Green + }; + + internal static class Log + { + static readonly StreamWriter Writer; + static readonly string LogFile = Path.Combine(Directory.GetCurrentDirectory(), "latest.log"); + + static Log() + { + if (File.Exists(LogFile)) + { + if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "Logs"))) + { + Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "Logs")); + } + + File.Move(LogFile, Path.Combine(Directory.GetCurrentDirectory(), "Logs", $"{DateTime.UtcNow:s}.log")); + } + else + { + File.Create(LogFile); + } + + Writer = new StreamWriter(LogFile); + } + + static ConsoleColor SeverityToColor(LogSeverity severity) + { + if (severity == LogSeverity.Error) + { + return ConsoleColor.Red; + } + + if (severity == LogSeverity.Warning) + { + return ConsoleColor.Yellow; + } + + if (severity == LogSeverity.Event) + { + return ConsoleColor.Blue; + } + + if (severity == LogSeverity.Information) + { + return ConsoleColor.DarkGray; + } + + if (severity == LogSeverity.Debug) + { + return ConsoleColor.DarkBlue; + } + + if (severity == LogSeverity.Boot) + { + return ConsoleColor.Green; + } + + return ConsoleColor.Gray; + } + + static string SeverityToEvent(LogSeverity severity) + { + if (severity == LogSeverity.Error) + { + return "error"; + } + + if (severity == LogSeverity.Warning) + { + return "warn"; + } + + if (severity == LogSeverity.Event) + { + return "event"; + } + + if (severity == LogSeverity.Information) + { + return "info"; + } + + if (severity == LogSeverity.Debug) + { + return "debug"; + } + + if (severity == LogSeverity.Boot) + { + return "boot"; + } + + return "info"; + } + + static internal void Write(string message, LogSeverity severity = LogSeverity.Information) + { +#if RELEASE + if (severity == LogSeverity.Debug) + { + return; + } +#endif + + if (Writer != null) + { + lock (Writer) + { + ConsoleColor color = SeverityToColor(severity); + string _event = SeverityToEvent(severity); + int time = Unix.Now(); + + Console.ForegroundColor = ConsoleColor.DarkGray; + Console.Write($"[{time:G}] "); + + Console.ForegroundColor = color; + Console.Write($"[{_event}]"); + Console.ForegroundColor = ConsoleColor.Gray; + + Console.WriteLine($" {message.Replace(Configuration.AppSettings["AccessKey"], "")}"); + + Writer.WriteLine($"[{time}] [{_event}] {message.Replace(Configuration.AppSettings["AccessKey"], "*********")}"); + + Http.Log(severity, time, message); + + Writer.Flush(); + } + } + } + + public static void Error(string message) + { + if (Writer != null) + { + Http.Fatal(message); + + lock (Writer) + { + Writer.WriteLine($"[{DateTime.Now:G}] [FATAL] {message}"); + Writer.Flush(); + } + + Console.WriteLine(message, ConsoleColor.Red); + Console.ReadLine(); + Environment.Exit(0); + } + } + } +} diff --git a/Tadah.Arbiter/Message.cs b/Tadah.Arbiter/Message.cs new file mode 100644 index 0000000..bb3a1ec --- /dev/null +++ b/Tadah.Arbiter/Message.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tadah +{ + public class Message + { + public byte[] Data { get; set; } + public Proto.Signal Signal { get; set; } + public byte[] Signature { get; set; } + + public Message(byte[] data, Proto.Signal signal, byte[] signature) + { + this.Data = data; + this.Signal = signal; + this.Signature = signature; + } + + public static bool TryParse(byte[] buffer, out Message message) + { + message = new Message(null, null, null); + + /* + * 0x02 0x00 0x00 0x00 0x00 0x02 0x00 0x00 .. .. 0x02 0x00 0x00 .. .. + * (STX) (UINT16) (UINT16) (STX) (UINT16) (DATA) (STX) (UINT16) (DATA) + * (MSGREAD) (MSGSIZE) (CHKSUM) (SIGREAD) (SIGSIZE) (SIGDATA) (BUFREAD) (BUFSIZE) (BUFDATA) + */ + + ushort msgSize; + ushort chkSum; + ushort sigSize; + byte[] sigData; + ushort bufSize; + byte[] bufData; + + // Extract MSG* and CHKSUM + if (buffer[0] != 0x02 || buffer.Length < 11) + return false; + + msgSize = BitConverter.ToUInt16(buffer, 1); + chkSum = BitConverter.ToUInt16(buffer, 3); + + if (buffer.Length != msgSize || msgSize == 0) + return false; + + ushort sum = 0; + for (int i = 5; i < msgSize; i++) + sum = unchecked((ushort)(sum + buffer[i])); + + if (sum != chkSum) + return false; + + // Extract SIG* + if (buffer[5] != 0x02) + return false; + + sigSize = BitConverter.ToUInt16(buffer, 6); + + if (buffer.Length < 8 + sigSize || sigSize == 0) + return false; + + sigData = new byte[sigSize]; + Buffer.BlockCopy(buffer, 8, sigData, 0, sigSize - 1); + + // Extract BUF* + if (buffer.Length < 8 + sigSize + 3 || buffer[8 + sigSize + 1] != 0x02) + return false; + + bufSize = BitConverter.ToUInt16(buffer, 8 + sigSize + 1); + + if (buffer.Length < 8 + sigSize + 3 + bufSize || bufSize == 0) + return false; + + bufData = new byte[bufSize]; + Buffer.BlockCopy(buffer, 8 + sigSize + 3, bufData, 0, bufSize - 1); + + // Check signature length (should be 256 bytes; is SHA256) + if (sigSize != 256) + return false; + + // Convert signal + Proto.Signal signal; + + try + { + signal = Proto.Signal.Parser.ParseFrom(bufData); + } + catch + { + return false; + } + + // Return message + message = new Message(bufData, signal, sigData); + + return true; + } + } +} diff --git a/Tadah.Arbiter/Program.cs b/Tadah.Arbiter/Program.cs new file mode 100644 index 0000000..743127f --- /dev/null +++ b/Tadah.Arbiter/Program.cs @@ -0,0 +1,66 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Runtime.InteropServices; + +namespace Tadah.Arbiter +{ + public enum GameServerState + { + Online = 0, + Offline = 1, + Crashed = 2, + Paused = 3 + }; + + public class Program + { + internal static void Main(string[] args) + { +#if DEBUG + Log.Write($"Access Key read: {Configuration.AppSettings["AccessKey"]}", LogSeverity.Boot); + Log.Write($"Current Access key: {Configuration.AppSettings["AccessKey"]}", LogSeverity.Boot); +#else + Log.Write("Access Key read", LogSeverity.Information); +#endif + Log.Write("Service starting...", LogSeverity.Boot); + + Configuration.Load(); + + Log.Write($"Assigned GameserverId: {Configuration.Uuid}", LogSeverity.Boot); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + Task.Run(() => JobManager.MonitorCrashedJobs()); + Task.Run(() => JobManager.MonitorUnresponsiveJobs()); + Task.Run(() => Tampa.ProcessManager.MonitorUnresponsiveProcesses()); + } + + Task.Run(() => Http.StartResourceReporter()); + + Http.UpdateState(GameServerState.Online); + + Log.Write("Initializing Tadah Arbiter Service", LogSeverity.Boot); + int ServicePort = Service.Start(); + Log.Write($"Service Started on port {ServicePort}", LogSeverity.Boot); + + Console.CancelKeyPress += delegate + { + Log.Write("Service shutting down...", LogSeverity.Event); + + Service.Stop(); + JobManager.CloseAllJobs(); + + Http.UpdateState(GameServerState.Offline); + + // wait for web requests to finish + Thread.Sleep(10000); + }; + + while (true) + { + Thread.Sleep(1000); + } + } + } +} diff --git a/Tadah.Arbiter/Proto.cs b/Tadah.Arbiter/Proto.cs new file mode 100644 index 0000000..e6a535e --- /dev/null +++ b/Tadah.Arbiter/Proto.cs @@ -0,0 +1,941 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: Resources/Tadah.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Tadah.Proto { + + /// Holder for reflection information generated from Resources/Tadah.proto + public static partial class TadahReflection { + + #region Descriptor + /// File descriptor for Resources/Tadah.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static TadahReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChVSZXNvdXJjZXMvVGFkYWgucHJvdG8SBVRhZGFoGh9nb29nbGUvcHJvdG9i", + "dWYvdGltZXN0YW1wLnByb3RvIvYCCgZTaWduYWwSKQoFbm9uY2UYASABKAsy", + "Gi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEg0KBWpvYklkGAIgASgJEiMK", + "CW9wZXJhdGlvbhgDIAEoDjIQLlRhZGFoLk9wZXJhdGlvbhIlCgd2ZXJzaW9u", + "GAQgASgOMhQuVGFkYWguQ2xpZW50VmVyc2lvbhIiCgVwbGFjZRgFIAMoCzIT", + "LlRhZGFoLlNpZ25hbC5QbGFjZRIqCgl0aHVtYm5haWwYBiADKAsyFy5UYWRh", + "aC5TaWduYWwuVGh1bWJuYWlsGkUKBVBsYWNlEg8KB3BsYWNlSWQYASABKA0S", + "DgoGc2NyaXB0GAIgASgJEhsKE2V4cGlyYXRpb25JblNlY29uZHMYAyABKA0a", + "TwoJVGh1bWJuYWlsEh4KBHR5cGUYASABKA4yEC5UYWRhaC5Bc3NldFR5cGUS", + "DwoHYXNzZXRJZBgCIAEoDRIRCglhY2Nlc3NLZXkYAyABKAkiXwoIUmVzcG9u", + "c2USIwoJb3BlcmF0aW9uGAEgASgOMhAuVGFkYWguT3BlcmF0aW9uEg8KB3N1", + "Y2Nlc3MYAiABKAgSDwoHbWVzc2FnZRgDIAEoCRIMCgRkYXRhGAQgASgJKpkB", + "CglPcGVyYXRpb24SDAoIT1BFTl9KT0IQABINCglDTE9TRV9KT0IQARISCg5F", + "WEVDVVRFX1NDUklQVBACEhkKFVJFTkVXX1RBTVBBX0pPQl9MRUFTRRADEhIK", + "DkNMT1NFX0FMTF9KT0JTEAQSHQoZQ0xPU0VfQUxMX1RBTVBBX1BST0NFU1NF", + "UxAFEg0KCVRIVU1CTkFJTBAGKjIKDUNsaWVudFZlcnNpb24SCAoETk9ORRAA", + "EgsKBlRBSVBFSRDbDxIKCgVUQU1QQRDgDypZCglBc3NldFR5cGUSDAoIQ0xP", + "VEhJTkcQABIICgRIRUFEEAESCAoETUVTSBACEgkKBVBMQUNFEAMSCAoEVVNF", + "UhAEEgwKCEhFQURTSE9UEAUSBwoDWE1MEAZCDqoCC1RhZGFoLlByb3RvYgZw", + "cm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Tadah.Proto.Operation), typeof(global::Tadah.Proto.ClientVersion), typeof(global::Tadah.Proto.AssetType), }, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Tadah.Proto.Signal), global::Tadah.Proto.Signal.Parser, new[]{ "Nonce", "JobId", "Operation", "Version", "Place", "Thumbnail" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Tadah.Proto.Signal.Types.Place), global::Tadah.Proto.Signal.Types.Place.Parser, new[]{ "PlaceId", "Script", "ExpirationInSeconds" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Tadah.Proto.Signal.Types.Thumbnail), global::Tadah.Proto.Signal.Types.Thumbnail.Parser, new[]{ "Type", "AssetId", "AccessKey" }, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Tadah.Proto.Response), global::Tadah.Proto.Response.Parser, new[]{ "Operation", "Success", "Message", "Data" }, null, null, null) + })); + } + #endregion + + } + #region Enums + public enum Operation { + [pbr::OriginalName("OPEN_JOB")] OpenJob = 0, + [pbr::OriginalName("CLOSE_JOB")] CloseJob = 1, + [pbr::OriginalName("EXECUTE_SCRIPT")] ExecuteScript = 2, + [pbr::OriginalName("RENEW_TAMPA_JOB_LEASE")] RenewTampaJobLease = 3, + [pbr::OriginalName("CLOSE_ALL_JOBS")] CloseAllJobs = 4, + [pbr::OriginalName("CLOSE_ALL_TAMPA_PROCESSES")] CloseAllTampaProcesses = 5, + [pbr::OriginalName("THUMBNAIL")] Thumbnail = 6, + } + + public enum ClientVersion { + [pbr::OriginalName("NONE")] None = 0, + [pbr::OriginalName("TAIPEI")] Taipei = 2011, + [pbr::OriginalName("TAMPA")] Tampa = 2016, + } + + public enum AssetType { + [pbr::OriginalName("CLOTHING")] Clothing = 0, + [pbr::OriginalName("HEAD")] Head = 1, + [pbr::OriginalName("MESH")] Mesh = 2, + [pbr::OriginalName("PLACE")] Place = 3, + [pbr::OriginalName("USER")] User = 4, + [pbr::OriginalName("HEADSHOT")] Headshot = 5, + [pbr::OriginalName("XML")] Xml = 6, + } + + #endregion + + #region Messages + public sealed partial class Signal : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Signal()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Tadah.Proto.TadahReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Signal() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Signal(Signal other) : this() { + nonce_ = other.nonce_ != null ? other.nonce_.Clone() : null; + jobId_ = other.jobId_; + operation_ = other.operation_; + version_ = other.version_; + place_ = other.place_.Clone(); + thumbnail_ = other.thumbnail_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Signal Clone() { + return new Signal(this); + } + + /// Field number for the "nonce" field. + public const int NonceFieldNumber = 1; + private global::Google.Protobuf.WellKnownTypes.Timestamp nonce_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::Google.Protobuf.WellKnownTypes.Timestamp Nonce { + get { return nonce_; } + set { + nonce_ = value; + } + } + + /// Field number for the "jobId" field. + public const int JobIdFieldNumber = 2; + private string jobId_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string JobId { + get { return jobId_; } + set { + jobId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "operation" field. + public const int OperationFieldNumber = 3; + private global::Tadah.Proto.Operation operation_ = 0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::Tadah.Proto.Operation Operation { + get { return operation_; } + set { + operation_ = value; + } + } + + /// Field number for the "version" field. + public const int VersionFieldNumber = 4; + private global::Tadah.Proto.ClientVersion version_ = 0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::Tadah.Proto.ClientVersion Version { + get { return version_; } + set { + version_ = value; + } + } + + /// Field number for the "place" field. + public const int PlaceFieldNumber = 5; + private static readonly pb::FieldCodec _repeated_place_codec + = pb::FieldCodec.ForMessage(42, global::Tadah.Proto.Signal.Types.Place.Parser); + private readonly pbc::RepeatedField place_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::RepeatedField Place { + get { return place_; } + } + + /// Field number for the "thumbnail" field. + public const int ThumbnailFieldNumber = 6; + private static readonly pb::FieldCodec _repeated_thumbnail_codec + = pb::FieldCodec.ForMessage(50, global::Tadah.Proto.Signal.Types.Thumbnail.Parser); + private readonly pbc::RepeatedField thumbnail_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::RepeatedField Thumbnail { + get { return thumbnail_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Signal); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Signal other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(Nonce, other.Nonce)) return false; + if (JobId != other.JobId) return false; + if (Operation != other.Operation) return false; + if (Version != other.Version) return false; + if(!place_.Equals(other.place_)) return false; + if(!thumbnail_.Equals(other.thumbnail_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (nonce_ != null) hash ^= Nonce.GetHashCode(); + if (JobId.Length != 0) hash ^= JobId.GetHashCode(); + if (Operation != 0) hash ^= Operation.GetHashCode(); + if (Version != 0) hash ^= Version.GetHashCode(); + hash ^= place_.GetHashCode(); + hash ^= thumbnail_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (nonce_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Nonce); + } + if (JobId.Length != 0) { + output.WriteRawTag(18); + output.WriteString(JobId); + } + if (Operation != 0) { + output.WriteRawTag(24); + output.WriteEnum((int) Operation); + } + if (Version != 0) { + output.WriteRawTag(32); + output.WriteEnum((int) Version); + } + place_.WriteTo(output, _repeated_place_codec); + thumbnail_.WriteTo(output, _repeated_thumbnail_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (nonce_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Nonce); + } + if (JobId.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(JobId); + } + if (Operation != 0) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Operation); + } + if (Version != 0) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Version); + } + size += place_.CalculateSize(_repeated_place_codec); + size += thumbnail_.CalculateSize(_repeated_thumbnail_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Signal other) { + if (other == null) { + return; + } + if (other.nonce_ != null) { + if (nonce_ == null) { + nonce_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); + } + Nonce.MergeFrom(other.Nonce); + } + if (other.JobId.Length != 0) { + JobId = other.JobId; + } + if (other.Operation != 0) { + Operation = other.Operation; + } + if (other.Version != 0) { + Version = other.Version; + } + place_.Add(other.place_); + thumbnail_.Add(other.thumbnail_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (nonce_ == null) { + nonce_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); + } + input.ReadMessage(nonce_); + break; + } + case 18: { + JobId = input.ReadString(); + break; + } + case 24: { + operation_ = (global::Tadah.Proto.Operation) input.ReadEnum(); + break; + } + case 32: { + version_ = (global::Tadah.Proto.ClientVersion) input.ReadEnum(); + break; + } + case 42: { + place_.AddEntriesFrom(input, _repeated_place_codec); + break; + } + case 50: { + thumbnail_.AddEntriesFrom(input, _repeated_thumbnail_codec); + break; + } + } + } + } + + #region Nested types + /// Container for nested types declared in the Signal message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static partial class Types { + public sealed partial class Place : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Place()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Tadah.Proto.Signal.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Place() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Place(Place other) : this() { + placeId_ = other.placeId_; + script_ = other.script_; + expirationInSeconds_ = other.expirationInSeconds_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Place Clone() { + return new Place(this); + } + + /// Field number for the "placeId" field. + public const int PlaceIdFieldNumber = 1; + private uint placeId_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public uint PlaceId { + get { return placeId_; } + set { + placeId_ = value; + } + } + + /// Field number for the "script" field. + public const int ScriptFieldNumber = 2; + private string script_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Script { + get { return script_; } + set { + script_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "expirationInSeconds" field. + public const int ExpirationInSecondsFieldNumber = 3; + private uint expirationInSeconds_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public uint ExpirationInSeconds { + get { return expirationInSeconds_; } + set { + expirationInSeconds_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Place); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Place other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (PlaceId != other.PlaceId) return false; + if (Script != other.Script) return false; + if (ExpirationInSeconds != other.ExpirationInSeconds) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (PlaceId != 0) hash ^= PlaceId.GetHashCode(); + if (Script.Length != 0) hash ^= Script.GetHashCode(); + if (ExpirationInSeconds != 0) hash ^= ExpirationInSeconds.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (PlaceId != 0) { + output.WriteRawTag(8); + output.WriteUInt32(PlaceId); + } + if (Script.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Script); + } + if (ExpirationInSeconds != 0) { + output.WriteRawTag(24); + output.WriteUInt32(ExpirationInSeconds); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (PlaceId != 0) { + size += 1 + pb::CodedOutputStream.ComputeUInt32Size(PlaceId); + } + if (Script.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Script); + } + if (ExpirationInSeconds != 0) { + size += 1 + pb::CodedOutputStream.ComputeUInt32Size(ExpirationInSeconds); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Place other) { + if (other == null) { + return; + } + if (other.PlaceId != 0) { + PlaceId = other.PlaceId; + } + if (other.Script.Length != 0) { + Script = other.Script; + } + if (other.ExpirationInSeconds != 0) { + ExpirationInSeconds = other.ExpirationInSeconds; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + PlaceId = input.ReadUInt32(); + break; + } + case 18: { + Script = input.ReadString(); + break; + } + case 24: { + ExpirationInSeconds = input.ReadUInt32(); + break; + } + } + } + } + + } + + public sealed partial class Thumbnail : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Thumbnail()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Tadah.Proto.Signal.Descriptor.NestedTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Thumbnail() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Thumbnail(Thumbnail other) : this() { + type_ = other.type_; + assetId_ = other.assetId_; + accessKey_ = other.accessKey_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Thumbnail Clone() { + return new Thumbnail(this); + } + + /// Field number for the "type" field. + public const int TypeFieldNumber = 1; + private global::Tadah.Proto.AssetType type_ = 0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::Tadah.Proto.AssetType Type { + get { return type_; } + set { + type_ = value; + } + } + + /// Field number for the "assetId" field. + public const int AssetIdFieldNumber = 2; + private uint assetId_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public uint AssetId { + get { return assetId_; } + set { + assetId_ = value; + } + } + + /// Field number for the "accessKey" field. + public const int AccessKeyFieldNumber = 3; + private string accessKey_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string AccessKey { + get { return accessKey_; } + set { + accessKey_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Thumbnail); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Thumbnail other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Type != other.Type) return false; + if (AssetId != other.AssetId) return false; + if (AccessKey != other.AccessKey) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Type != 0) hash ^= Type.GetHashCode(); + if (AssetId != 0) hash ^= AssetId.GetHashCode(); + if (AccessKey.Length != 0) hash ^= AccessKey.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (Type != 0) { + output.WriteRawTag(8); + output.WriteEnum((int) Type); + } + if (AssetId != 0) { + output.WriteRawTag(16); + output.WriteUInt32(AssetId); + } + if (AccessKey.Length != 0) { + output.WriteRawTag(26); + output.WriteString(AccessKey); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Type != 0) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); + } + if (AssetId != 0) { + size += 1 + pb::CodedOutputStream.ComputeUInt32Size(AssetId); + } + if (AccessKey.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(AccessKey); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Thumbnail other) { + if (other == null) { + return; + } + if (other.Type != 0) { + Type = other.Type; + } + if (other.AssetId != 0) { + AssetId = other.AssetId; + } + if (other.AccessKey.Length != 0) { + AccessKey = other.AccessKey; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + type_ = (global::Tadah.Proto.AssetType) input.ReadEnum(); + break; + } + case 16: { + AssetId = input.ReadUInt32(); + break; + } + case 26: { + AccessKey = input.ReadString(); + break; + } + } + } + } + + } + + } + #endregion + + } + + public sealed partial class Response : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Response()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Tadah.Proto.TadahReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Response() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Response(Response other) : this() { + operation_ = other.operation_; + success_ = other.success_; + message_ = other.message_; + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Response Clone() { + return new Response(this); + } + + /// Field number for the "operation" field. + public const int OperationFieldNumber = 1; + private global::Tadah.Proto.Operation operation_ = 0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::Tadah.Proto.Operation Operation { + get { return operation_; } + set { + operation_ = value; + } + } + + /// Field number for the "success" field. + public const int SuccessFieldNumber = 2; + private bool success_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Success { + get { return success_; } + set { + success_ = value; + } + } + + /// Field number for the "message" field. + public const int MessageFieldNumber = 3; + private string message_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Message { + get { return message_; } + set { + message_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 4; + private string data_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Data { + get { return data_; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Response); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Response other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Operation != other.Operation) return false; + if (Success != other.Success) return false; + if (Message != other.Message) return false; + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Operation != 0) hash ^= Operation.GetHashCode(); + if (Success != false) hash ^= Success.GetHashCode(); + if (Message.Length != 0) hash ^= Message.GetHashCode(); + if (Data.Length != 0) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (Operation != 0) { + output.WriteRawTag(8); + output.WriteEnum((int) Operation); + } + if (Success != false) { + output.WriteRawTag(16); + output.WriteBool(Success); + } + if (Message.Length != 0) { + output.WriteRawTag(26); + output.WriteString(Message); + } + if (Data.Length != 0) { + output.WriteRawTag(34); + output.WriteString(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Operation != 0) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Operation); + } + if (Success != false) { + size += 1 + 1; + } + if (Message.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Message); + } + if (Data.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Response other) { + if (other == null) { + return; + } + if (other.Operation != 0) { + Operation = other.Operation; + } + if (other.Success != false) { + Success = other.Success; + } + if (other.Message.Length != 0) { + Message = other.Message; + } + if (other.Data.Length != 0) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + operation_ = (global::Tadah.Proto.Operation) input.ReadEnum(); + break; + } + case 16: { + Success = input.ReadBool(); + break; + } + case 26: { + Message = input.ReadString(); + break; + } + case 34: { + Data = input.ReadString(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/Tadah.Arbiter/Resources/AppSettings.json b/Tadah.Arbiter/Resources/AppSettings.json new file mode 100644 index 0000000..ecec553 --- /dev/null +++ b/Tadah.Arbiter/Resources/AppSettings.json @@ -0,0 +1,4 @@ +{ + "AccessKey": "", + "BaseUrl": "tadah.rocks/arbiter" +} \ No newline at end of file diff --git a/Tadah.Arbiter/Resources/Tadah.proto b/Tadah.Arbiter/Resources/Tadah.proto new file mode 100644 index 0000000..ef10e97 --- /dev/null +++ b/Tadah.Arbiter/Resources/Tadah.proto @@ -0,0 +1,62 @@ +syntax = "proto3"; +package Tadah; + +option csharp_namespace = "Tadah.Proto"; +option php_namespace = "App/Proto"; + +import "google/protobuf/timestamp.proto"; + +enum Operation { + OPEN_JOB = 0; + CLOSE_JOB = 1; + EXECUTE_SCRIPT = 2; + RENEW_TAMPA_JOB_LEASE = 3; + CLOSE_ALL_JOBS = 4; + CLOSE_ALL_TAMPA_PROCESSES = 5; + THUMBNAIL = 6; +} + +enum ClientVersion { + NONE = 0; + TAIPEI = 2011; + TAMPA = 2016; +} + +enum AssetType { + CLOTHING = 0; + HEAD = 1; + MESH = 2; + PLACE = 3; + USER = 4; + HEADSHOT = 5; + XML = 6; +} + +message Signal { + google.protobuf.Timestamp nonce = 1; + string jobId = 2; + Operation operation = 3; + ClientVersion version = 4; + + message Place { + uint32 placeId = 1; + string script = 2; + uint32 expirationInSeconds = 3; + } + + message Thumbnail { + AssetType type = 1; + uint32 assetId = 2; + string accessKey = 3; + } + + repeated Place place = 5; + repeated Thumbnail thumbnail = 6; +} + +message Response { + Operation operation = 1; + bool success = 2; + string message = 3; + string data = 4; +} diff --git a/Tadah.Arbiter/Resources/TampaServerSoap.wsdl b/Tadah.Arbiter/Resources/TampaServerSoap.wsdl new file mode 100644 index 0000000..51b85cc --- /dev/null +++ b/Tadah.Arbiter/Resources/TampaServerSoap.wsdl @@ -0,0 +1,795 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Tadah.Arbiter/Scripts/Clothing.lua b/Tadah.Arbiter/Scripts/Clothing.lua new file mode 100644 index 0000000..5822030 --- /dev/null +++ b/Tadah.Arbiter/Scripts/Clothing.lua @@ -0,0 +1,24 @@ +local jobId, type, format, x, y, baseUrl, assetId = ... + +print(("[%s] Started RenderJob for type '%s' with assetId %d"):format(jobId, type, assetId)) + +game:GetService("ScriptInformationProvider"):SetAssetUrl(baseUrl .. "/asset/") +game:GetService("InsertService"):SetAssetUrl(baseUrl .. "/asset/?id=%d") +game:GetService("InsertService"):SetAssetVersionUrl(baseUrl .. "/Asset/?assetversionid=%d") +game:GetService("ContentProvider"):SetBaseUrl(baseUrl) +game:GetService("ScriptContext").ScriptsDisabled = true + +local Player = game.Players:CreateLocalPlayer(0) +Player.CharacterAppearance = ("%s/thumbnail/clothingcharapp/%d"):format(baseUrl, assetId) +Player:LoadCharacter(false) + +game:GetService("RunService"):Run() + +Player.Character.Animate.Disabled = true +Player.Character.Torso.Anchored = true + +print(("[%s] Rendering ..."):format(jobId)) +local result = game:GetService("ThumbnailGenerator"):Click(format, x, y, true) +print(("[%s] Done!"):format(jobId)) + +return result \ No newline at end of file diff --git a/Tadah.Arbiter/Scripts/Head.lua b/Tadah.Arbiter/Scripts/Head.lua new file mode 100644 index 0000000..a6656a1 --- /dev/null +++ b/Tadah.Arbiter/Scripts/Head.lua @@ -0,0 +1,25 @@ +local jobId, type, format, x, y, baseUrl, assetId = ... + +print(("[%s] Started RenderJob for type '%s' with assetId %d"):format(jobId, type, assetId)) + +game:GetService("ScriptInformationProvider"):SetAssetUrl(baseUrl .. "/asset/") +game:GetService("InsertService"):SetAssetUrl(baseUrl .. "/asset/?id=%d") +game:GetService("InsertService"):SetAssetVersionUrl(baseUrl .. "/Asset/?assetversionid=%d") +game:GetService("ContentProvider"):SetBaseUrl(baseUrl) +game:GetService("ScriptContext").ScriptsDisabled = true + +local Player = game.Players:CreateLocalPlayer(0) +Player.CharacterAppearance = ("%s/thumbnail/clothingcharapp/%d"):format(baseUrl, assetId) +Player:LoadCharacter(false) + +for i, v in ipairs(Player.Character:GetChildren()) do + if v.Name ~= "Head" then + v:Destroy() + end +end + +print(("[%s] Rendering ..."):format(jobId)) +local result = game:GetService("ThumbnailGenerator"):Click(format, x, y, true) +print(("[%s] Done!"):format(jobId)) + +return result \ No newline at end of file diff --git a/Tadah.Arbiter/Scripts/Headshot.lua b/Tadah.Arbiter/Scripts/Headshot.lua new file mode 100644 index 0000000..14916d0 --- /dev/null +++ b/Tadah.Arbiter/Scripts/Headshot.lua @@ -0,0 +1,41 @@ +local jobId, type, format, x, y, baseUrl, assetId = ... + +print(("[%s] Started RenderJob for type '%s' with assetId %d ..."):format(jobId, type, assetId)) + +game:GetService("ScriptInformationProvider"):SetAssetUrl(baseUrl .. "/asset/") +game:GetService("InsertService"):SetAssetUrl(baseUrl .. "/asset/?id=%d") +game:GetService("InsertService"):SetAssetVersionUrl(baseUrl .. "/Asset/?assetversionid=%d") +game:GetService("ContentProvider"):SetBaseUrl(baseUrl) +game:GetService("ScriptContext").ScriptsDisabled = true + +local Player = game.Players:CreateLocalPlayer(0) +Player.CharacterAppearance = ("%s/users/%d/character"):format(baseUrl, assetId) +Player:LoadCharacter(false) + +game:GetService("RunService"):Run() + +Player.Character.Animate.Disabled = true +Player.Character.Torso.Anchored = true + +-- Headshot Camera +local FOV = 52.5 +local AngleOffsetX = 0 +local AngleOffsetY = 0 +local AngleOffsetZ = 0 + +local CameraAngle = Player.Character.Head.CFrame * CFrame.new(AngleOffsetX, AngleOffsetY, AngleOffsetZ) +local CameraPosition = Player.Character.Head.CFrame + Vector3.new(0, 0, 0) + (CFrame.Angles(0, 0, 0).lookVector.unit * 3) + +local Camera = Instance.new("Camera", Player.Character) +Camera.Name = "ThumbnailCamera" +Camera.CameraType = Enum.CameraType.Scriptable + +Camera.CoordinateFrame = CFrame.new(CameraPosition.p, CameraAngle.p) +Camera.FieldOfView = FOV +workspace.CurrentCamera = Camera + +print(("[%s] Rendering ..."):format(jobId)) +local result = game:GetService("ThumbnailGenerator"):Click(format, x, y, true) +print(("[%s] Done!"):format(jobId)) + +return result \ No newline at end of file diff --git a/Tadah.Arbiter/Scripts/Mesh.lua b/Tadah.Arbiter/Scripts/Mesh.lua new file mode 100644 index 0000000..d7bf58c --- /dev/null +++ b/Tadah.Arbiter/Scripts/Mesh.lua @@ -0,0 +1,23 @@ +local jobId, type, format, x, y, baseUrl, assetId = ... + +print(("[%s] Started RenderJob for type '%s' with assetId %d ..."):format(jobId, type, assetId)) + +game:GetService("ScriptInformationProvider"):SetAssetUrl(baseUrl .. "/asset/") +game:GetService("InsertService"):SetAssetUrl(baseUrl .. "/asset/?id=%d") +game:GetService("InsertService"):SetAssetVersionUrl(baseUrl .. "/Asset/?assetversionid=%d") +game:GetService("ContentProvider"):SetBaseUrl(baseUrl) +game:GetService("ScriptContext").ScriptsDisabled = true + +local meshPart = Instance.new("Part", workspace) +meshPart.Anchored = true +meshPart.Size = Vector3.new(10, 10, 10) + +local mesh = Instance.new("SpecialMesh", meshPart) +mesh.MeshType = "FileMesh" +mesh.MeshId = ("%s/asset?id=%d"):format(baseUrl, assetId) + +print(("[%s] Rendering ..."):format(jobId)) +local result = game:GetService("ThumbnailGenerator"):Click(format, x, y, true) +print(("[%s] Done!"):format(jobId)) + +return result \ No newline at end of file diff --git a/Tadah.Arbiter/Scripts/Place.lua b/Tadah.Arbiter/Scripts/Place.lua new file mode 100644 index 0000000..22a6dac --- /dev/null +++ b/Tadah.Arbiter/Scripts/Place.lua @@ -0,0 +1,23 @@ +local jobId, type, format, x, y, baseUrl, assetId, key = ... + +print(("[%s] Started RenderJob for type '%s' with assetId %d ..."):format(jobId, type, assetId)) + +game:GetService("ScriptInformationProvider"):SetAssetUrl(baseUrl .. "/asset/") +game:GetService("InsertService"):SetAssetUrl(baseUrl .. "/asset/?id=%d") +game:GetService("InsertService"):SetAssetVersionUrl(baseUrl .. "/Asset/?assetversionid=%d") +game:GetService("ContentProvider"):SetBaseUrl(baseUrl) + +-- do this twice for security +game:GetService("ScriptContext").ScriptsDisabled = true +game:GetService("StarterGui").ShowDevelopmentGui = false + +game:Load(("%s/server/%d/place?key=%s"):format(baseUrl, assetId, key)) + +game:GetService("ScriptContext").ScriptsDisabled = true +game:GetService("StarterGui").ShowDevelopmentGui = false + +print(("[%s] Rendering ..."):format(jobId)) +local result = game:GetService("ThumbnailGenerator"):Click(format, x, y, false) +print(("[%s] Done!"):format(jobId)) + +return result \ No newline at end of file diff --git a/Tadah.Arbiter/Scripts/User.lua b/Tadah.Arbiter/Scripts/User.lua new file mode 100644 index 0000000..b36e7c3 --- /dev/null +++ b/Tadah.Arbiter/Scripts/User.lua @@ -0,0 +1,29 @@ +local jobId, type, format, x, y, baseUrl, assetId = ... +print(("[%s] Started RenderJob for type '%s' with assetId %d ..."):format(jobId, type, assetId)) + +game:GetService("ScriptInformationProvider"):SetAssetUrl(baseUrl .. "/asset/") +game:GetService("InsertService"):SetAssetUrl(baseUrl .. "/asset/?id=%d") +game:GetService("InsertService"):SetAssetVersionUrl(baseUrl .. "/Asset/?assetversionid=%d") +game:GetService("ContentProvider"):SetBaseUrl(baseUrl) +game:GetService("ScriptContext").ScriptsDisabled = true + +local Player = game.Players:CreateLocalPlayer(0) +Player.CharacterAppearance = ("%s/users/%d/character"):format(baseUrl, assetId) +Player:LoadCharacter(false) + +game:GetService("RunService"):Run() + +Player.Character.Animate.Disabled = true +Player.Character.Torso.Anchored = true + +local gear = Player.Backpack:GetChildren()[1] +if gear then + gear.Parent = Player.Character + Player.Character.Torso["Right Shoulder"].CurrentAngle = math.rad(90) +end + +print(("[%s] Rendering ..."):format(jobId)) +local result = game:GetService("ThumbnailGenerator"):Click(format, x, y, true) +print(("[%s] Done!"):format(jobId)) + +return result diff --git a/Tadah.Arbiter/Scripts/XML.lua b/Tadah.Arbiter/Scripts/XML.lua new file mode 100644 index 0000000..855b6b5 --- /dev/null +++ b/Tadah.Arbiter/Scripts/XML.lua @@ -0,0 +1,23 @@ +local jobId, type, format, x, y, baseUrl, assetId = ... + +print(("[%s] Started RenderJob for type '%s' with assetId %d ..."):format(jobId, type, assetId)) + +game:GetService("ScriptInformationProvider"):SetAssetUrl(baseUrl .. "/asset/") +game:GetService("InsertService"):SetAssetUrl(baseUrl .. "/asset/?id=%d") +game:GetService("InsertService"):SetAssetVersionUrl(baseUrl .. "/Asset/?assetversionid=%d") +game:GetService("ContentProvider"):SetBaseUrl(baseUrl) +game:GetService("ScriptContext").ScriptsDisabled = true + +local asset = game:GetObjects(("%s/asset?id=%d"):format(baseUrl, assetId))[1] +asset.Parent = workspace + +local thumbnailCamera = asset:FindFirstChild("ThumbnailCamera") +if thumbnailCamera ~= nil and thumbnailCamera.ClassName == "Camera" then + workspace.CurrentCamera = ModelCamera +end + +print(("[%s] Rendering ..."):format(jobId)) +local result = game:GetService("ThumbnailGenerator"):Click(format, x, y, true) +print(("[%s] Done!"):format(jobId)) + +return result \ No newline at end of file diff --git a/Tadah.Arbiter/Service.cs b/Tadah.Arbiter/Service.cs new file mode 100644 index 0000000..6fdc9fb --- /dev/null +++ b/Tadah.Arbiter/Service.cs @@ -0,0 +1,452 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Google.Protobuf; + +namespace Tadah.Arbiter +{ + internal class Client + { + public string IpAddress { get; private set; } + public int Port { get; private set; } + public Socket Socket { get; set; } + + public Client(Socket socket) + { + this.IpAddress = null; + this.Port = 0; + this.Socket = socket; + + IPEndPoint remote = socket.RemoteEndPoint as IPEndPoint; + IPEndPoint local = socket.LocalEndPoint as IPEndPoint; + + if (remote != null) + { + this.IpAddress = remote.Address.ToString(); + this.Port = remote.Port; + } + + if (local != null) + { + this.IpAddress = local.Address.ToString(); + this.Port = local.Port; + } + + if (local == null && remote == null) + { + throw new("Failed to resolve information from socket"); + } + } + } + + internal class StateObject + { + public byte[] Buffer = new byte[1024]; + public ushort Size = 0; + public Socket WorkSocket = null; + public Client Client; + } + + public class Service + { + private static readonly ManualResetEvent Finished = new(false); + private static Socket Listener; + + public static int Start() + { + IPEndPoint localEndPoint = new(IPAddress.Any, Configuration.ServicePort); + + Listener = new(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + + try + { + Listener.Bind(localEndPoint); + Listener.Listen(100); + } + finally + { + try + { + Task.Run(() => ListenForConnections()); + } + catch (Exception exception) + { + Log.Error($"ListenForConnections failed: {exception}"); + } + } + + return Configuration.ServicePort; + } + + public static void Stop() + { + Listener.Close(); + } + + private static void ListenForConnections() + { + while (true) + { + Finished.Reset(); + Listener.BeginAccept(new(AcceptCallback), Listener); + Finished.WaitOne(); + } + } + + private static void AcceptCallback(IAsyncResult result) + { + Client client = null; + Socket handler = null; + + try + { + Finished.Set(); + + Socket listener = (Socket)result.AsyncState; + handler = listener.EndAccept(result); + client = new(handler); + + Log.Write($"[ArbiterService] '{client.IpAddress}' Connected on port {client.Port}", LogSeverity.Event); + } + finally + { + StateObject state = new(); + state.WorkSocket = handler; + state.Client = client; + + handler.BeginReceive(state.Buffer, 0, 1024, 0, new(ReadCallback), state); + } + } + + private static void ReadCallback(IAsyncResult result) + { + StateObject state = (StateObject)result.AsyncState; + Socket handler = state.WorkSocket; + + try + { + int read = handler.EndReceive(result); + + if (read > 0) + { + /* + * TadahMessage format: + * + * 0x02 0x00 0x00 0x00 0x00 0x02 0x00 0x00 .. .. 0x02 0x00 0x00 .. .. + * (STX) (UINT16) (UINT16) (STX) (UINT16) (DATA) (STX) (UINT16) (DATA) + * (MSGREAD) (MSGSIZE) (CHKSUM) (SIGREAD) (SIGSIZE) (SIGDATA) (BUFREAD) (BUFSIZE) (BUFDATA) + * + * From this, we can do some sanity checks while getting a complete read *and* fending off potential attackers; + * - See if the message begins with our MSGREAD + * - If it does, then recieve next 2 bytes; try parsing as a uint8 and use that as message size + * - Read message up to the specified message size + * - Try parsing the entire message + * - Verify buffer with given signature + * - Send buffer to ProcessData + */ + + if (state.Buffer[0] != 0x02) + { + Log.Write($"[ArbiterService::ReadCallback] '{state.Client.IpAddress}' - Not a TadahMessage", LogSeverity.Warning); + handler.Close(); + } + + if (read == 3) + { + if (state.Size == 0) + { + ushort parsed = 0; + + try + { + parsed = BitConverter.ToUInt16(state.Buffer, 1); // Offset by 1 (MSGREAD[STX]) + } + catch + { + Log.Write($"[ArbiterService::ReadCallback] '{state.Client.IpAddress}' - Not a TadahMessage", LogSeverity.Warning); + handler.Close(); + } + finally + { + if (parsed == 0) + { + Log.Write($"[ArbiterService::ReadCallback] '{state.Client.IpAddress}' - Not a TadahMessage", LogSeverity.Warning); + handler.Close(); + } + + state.Size = parsed; + } + } + + handler.BeginReceive(state.Buffer, 0, state.Size - 3, 0, new AsyncCallback(ReadCallback), state); // state.Size - 3 for 3 bytes already read (MSGREAD[STX], MSGSIZE[UINT8]) + } + + // Parse given data + if (!Message.TryParse(state.Buffer, out Message message)) + { + Log.Write($"[ArbiterService::ReadCallback] '{state.Client.IpAddress}' - Not a TadahMessage", LogSeverity.Warning); + handler.Close(); + } + + // Verify signature + if (!Signature.Verify(message.Data, message.Signature)) + { + Log.Write($"[ArbiterService::ReadCallback] '{state.Client.IpAddress}' - Bad or invalid signature", LogSeverity.Warning); + handler.Close(); + } + + // See if signal is older than ten seconds (so that people can't re-send signed destructive commands, such as "CloseAllJobs") + if (Unix.Now() + 10 > Unix.From(message.Signal.Nonce.ToDateTime())) + { + Log.Write($"[ArbiterService::ReadCallback] '{state.Client.IpAddress}' - Too old message received", LogSeverity.Warning); + handler.Close(); + } + + // Process data + byte[] response = ProcessSignal(message.Signal, state.Client); + SendData(handler, response); + } + } + catch (Exception exception) + { + Log.Write($"[ArbiterService::ReadCallback] - {exception}", LogSeverity.Error); + } + } + + private static void SendCallback(IAsyncResult result) + { + try + { + Socket handler = (Socket)result.AsyncState; + + int bytesSent = handler.EndSend(result); + handler.Shutdown(SocketShutdown.Both); + handler.Close(); + } + catch (Exception ex) + { + Log.Write($"[ArbiterService::SendCallback] {ex.Message}", LogSeverity.Error); + } + } + + private static void SendData(Socket handler, byte[] data) + { + try + { + handler.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), handler); + } + catch (Exception ex) + { + Log.Write($"[ArbiterService::SendData] {ex.Message}", LogSeverity.Error); + } + } + + private static byte[] SignalError(Proto.Signal signal, Client client, string reason) + { + byte[] stream = new byte[1024]; + + try + { + Log.Write($"[ArbiterService::{client.IpAddress}] Tried '{Enum.GetName(signal.Operation)}' with '{signal.JobId}' - {reason}", LogSeverity.Warning); + } + finally + { + new Proto.Response + { + Operation = signal.Operation, + Success = false, + Message = reason + }.WriteTo(stream); + } + + return stream; + } + + private static byte[] ProcessSignal(Proto.Signal signal, Client client) + { + byte[] stream = new byte[1024]; + bool success = false; + object responseData = null; + + try + { + switch (signal.Operation) + { + case Proto.Operation.OpenJob: + { + if (signal.Place.Count == 0) + { + return SignalError(signal, client, "No place specified"); + } + + Proto.Signal.Types.Place place = signal.Place[0]; + + if (JobManager.JobExists(signal.JobId)) + { + return SignalError(signal, client, "Job already exists"); + } + + if (!JobManager.IsValidVersion(signal.Version)) + { + return SignalError(signal, client, "Invalid ClientVersion"); + } + + if (JobManager.OpenJobs.Count >= Configuration.MaximumPlaceJobs) + { + return SignalError(signal, client, "Maximum amount of jobs reached on this arbiter -- please try another"); + } + + Task.Run(() => JobManager.OpenJob(signal.JobId, place.PlaceId, signal.Version)); + success = true; + + break; + } + + case Proto.Operation.CloseJob: + { + if (JobManager.JobExists(signal.JobId)) + { + return SignalError(signal, client, "Job doesn't exist"); + } + + Task.Run(() => JobManager.CloseJob(signal.JobId)); + success = true; + + break; + } + + case Proto.Operation.ExecuteScript: + { + Job job = JobManager.GetJobFromId(signal.JobId); + + if (job == null) + { + return SignalError(signal, client, "Job does not exist"); + } + + if (job is Taipei.Job) + { + return SignalError(signal, client, "Job does not support such functionality (is TaipeiJob)"); + } + + if (signal.Place.Count == 0) + { + return SignalError(signal, client, "No place specified"); + } + + Proto.Signal.Types.Place place = signal.Place[0]; + Task.Run(() => { job.ExecuteScript(place.Script); }); + + success = true; + + break; + } + + case Proto.Operation.RenewTampaJobLease: + { + Job job = JobManager.GetJobFromId(signal.JobId); + + if (job == null) + { + return SignalError(signal, client, "Job doesn't exist"); + } + + if (job is not Tampa.Job) + { + return SignalError(signal, client, "Job does not support such functionality (is TampaJob)"); + } + + if (signal.Place.Count == 0) + { + return SignalError(signal, client, "No place specified"); + } + + Tampa.Job taJob = (Tampa.Job)job; + Task.Run(() => { taJob.RenewLease(signal.Place[0].ExpirationInSeconds); }); + + success = true; + + break; + } + + case Proto.Operation.CloseAllJobs: + { + int jobs = JobManager.OpenJobs.Count; + + Task.Run(() => { JobManager.CloseAllJobs(); }); + + success = true; + responseData = jobs; + + break; + } + + case Proto.Operation.CloseAllTampaProcesses: + { + int processes = Tampa.ProcessManager.OpenProcesses.Count; + + Task.Run(() => { Tampa.ProcessManager.CloseAllProcesses(); }); + + success = true; + responseData = processes; + + break; + } + + default: + { + new Proto.Response + { + Success = false, + Message = "No such operation exists" + }.WriteTo(stream); + + break; + } + } + } + catch (Exception exception) + { + Log.Write($"[ArbiterService::ProcessData] '{client.IpAddress}' - {exception.Message}", LogSeverity.Error); + +#if DEBUG + new Proto.Response + { + Operation = signal.Operation, + Success = false, + Message = exception.Message, + }.WriteTo(stream); +#else + // Will just give a blank error +#endif + } + + if (success) + { + Proto.Response response = new() + { + Operation = signal.Operation, + Success = true + }; + + if (responseData != null) + { + response.Data = (string)responseData; + } + + response.WriteTo(stream); + } + else + { + // If it wasn't successful, the stream has already been written to + // In the case of an exception or the "default" fallthrough in the switch statement. + } + + return stream; + } + } +} diff --git a/Tadah.Arbiter/Signature.cs b/Tadah.Arbiter/Signature.cs new file mode 100644 index 0000000..5ceafcc --- /dev/null +++ b/Tadah.Arbiter/Signature.cs @@ -0,0 +1,70 @@ +using System; +using System.Text; +using System.IO; +using System.Security.Cryptography; +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.OpenSsl; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Security; + +namespace Tadah +{ + public static class Signature + { + private static readonly RSACryptoServiceProvider rsa = ReadPublicKey(Arbiter.Configuration.AppSettings["PublicKeyPath"]); + + private static RSACryptoServiceProvider ReadPublicKey(string path) + { + using TextReader reader = new StringReader(File.ReadAllText(path)); + + PemReader pem = new(reader); + AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter)pem.ReadObject(); + RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaKeyParameters)publicKey); + + RSACryptoServiceProvider csp = new(); + csp.ImportParameters(rsaParams); + return csp; + } + + public static bool Verify(byte[] data, byte[] signature) + { + try + { + return rsa.VerifyData(data, CryptoConfig.MapNameToOID("SHA256"), signature); + } + catch + { + return false; + } + } + + // This is for rudimentary signed data in the format of "%signature%nonce;message" + // Currently just used for TampaJob::ExecuteScript + public static bool VerifyData(string data, out string message) + { + if (!data.StartsWith("%")) + { + message = ""; + return false; + } + + try + { + string signature = data.Substring(1, data[1..].IndexOf("%")); + string nonce = data[(signature.Length + 2)..data.IndexOf(":")]; + + message = data[(signature.Length + nonce.Length + 3)..]; + + bool signatureOK = Verify(Encoding.UTF8.GetBytes(message), Encoding.UTF8.GetBytes(signature)); + bool nonceOK = (Unix.Now() - int.Parse(nonce)) <= 5; + + return nonceOK && signatureOK; + } + catch + { + message = ""; + return false; + } + } + } +} diff --git a/Tadah.Arbiter/Tadah.Arbiter.csproj b/Tadah.Arbiter/Tadah.Arbiter.csproj new file mode 100644 index 0000000..130eaad --- /dev/null +++ b/Tadah.Arbiter/Tadah.Arbiter.csproj @@ -0,0 +1,50 @@ + + + + Exe + net6.0 + False + Tadah + true + Tadah.Arbiter.Program + Resources\Tadah.Arbiter.ico + $(SolutionDir)bin\ + + + + none + + + + + + + + + + + + + + + + + + + + Always + AppSettings.json + + + + + + + + + + True + \ + + + diff --git a/Tadah.Arbiter/Taipei/Job.cs b/Tadah.Arbiter/Taipei/Job.cs new file mode 100644 index 0000000..85a18eb --- /dev/null +++ b/Tadah.Arbiter/Taipei/Job.cs @@ -0,0 +1,95 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; + +namespace Tadah.Taipei +{ + public class Job : Arbiter.Job + { + public Job(string Id, uint PlaceId, Proto.ClientVersion Version, int Port) : base(Id, PlaceId, Version, Port) + { + // + } + + protected override Arbiter.JobStatus InternalClose(bool forceClose = false) + { + if (forceClose) + { + return Arbiter.JobStatus.Crashed; + } + + try + { + if (!this.IsRunning || this.Process.HasExited) + { + if (!this.IsRunning) + { + this.Log("Process has shutdown"); + } + else if (this.Process.HasExited) + { + this.Log("Process has exited"); + } + + if (!this.IsRunning) + { + this.Process.CloseMainWindow(); + } + + this.Process.CloseMainWindow(); + this.Process.Close(); + + return Arbiter.JobStatus.Closed; + } + else if (Status == Arbiter.JobStatus.Crashed || !this.Process.Responding) + { + this.Process.Kill(); + this.Process.Close(); + + return Arbiter.JobStatus.Crashed; + } + else + { + this.Process.CloseMainWindow(); + this.Process.Close(); + + return Arbiter.JobStatus.Crashed; + } + } + catch (InvalidOperationException) + { + return Arbiter.JobStatus.Crashed; + } + } + + protected override void InternalStart() + { + string GameserverScript = Arbiter.Http.GetGameserverScript(Id, PlaceId, Port); + string[] CommandLine = Arbiter.JobManager.GetCommandLine(Version, GameserverScript, this.Id); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + this.Process = new Process(); + this.Process.StartInfo.FileName = CommandLine[0]; + this.Process.StartInfo.Arguments = CommandLine[1]; + this.Process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; + this.Process.Start(); + this.Process.WaitForInputIdle(); + } + else + { + this.Process = new Process(); + this.Process.StartInfo.FileName = "wine"; + this.Process.StartInfo.Arguments = Directory.GetCurrentDirectory() + "/" + CommandLine[0].Replace(@"\", "/") + " " + CommandLine[1]; + this.Process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; + this.Process.Start(); + } + } + + public override void ExecuteScript(string script) + { + return; + } + } +} diff --git a/Tadah.Arbiter/Tampa/Job.cs b/Tadah.Arbiter/Tampa/Job.cs new file mode 100644 index 0000000..13ffdb5 --- /dev/null +++ b/Tadah.Arbiter/Tampa/Job.cs @@ -0,0 +1,78 @@ +using System; +using Tadah.Tampa.Server; + +namespace Tadah.Tampa +{ + public class Job : Arbiter.Job + { + public int ExpirationInSeconds { get; private set; } + public int Cores { get; private set; } + public new System.Diagnostics.Process Process + { + get + { + return _process.Handle; + } + } + + private readonly Process _process; + + public Job(string Id, uint PlaceId, Proto.ClientVersion Version, int Port) : base(Id, PlaceId, Version, Port) + { + this.ExpirationInSeconds = 86400; + _process = ProcessManager.Best(); + } + + protected override void InternalStart() + { + Tampa.Server.Job job = new() + { + id = Id, + expirationInSeconds = ExpirationInSeconds, + category = 1, + cores = 1 + }; + + ScriptExecution script = new() + { + name = "Start Server", + script = Arbiter.Http.GetGameserverScript(Id, PlaceId, Port, true) + }; + + _process.Client.OpenJob(job, script); + this.IsRunning = true; + } + + protected override Arbiter.JobStatus InternalClose(bool forceClose) + { + if (!forceClose) + { + _process.Client.CloseJob(Id); + } + + this.IsRunning = false; + return Arbiter.JobStatus.Closed; + } + + public override void ExecuteScript(string script) + { + if (!Signature.VerifyData(script, out string lua)) + { + return; + } + + ScriptExecution execution = new() + { + name = "Tadah.Arbiter." + Guid.NewGuid(), + script = lua + }; + + _process.Client.ExecuteEx(Id, execution); + } + + public void RenewLease(uint seconds) + { + _process.Client.RenewLease(Id, seconds); + } + } +} diff --git a/Tadah.Arbiter/Tampa/Process.cs b/Tadah.Arbiter/Tampa/Process.cs new file mode 100644 index 0000000..f885f15 --- /dev/null +++ b/Tadah.Arbiter/Tampa/Process.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.IO; +using Tadah; + +namespace Tadah.Tampa +{ + public class Process + { + public int SoapPort { get; } + public Tampa.Server.Client Client { get; private set; } + public bool Monitored { get; set; } + public System.Diagnostics.Process Handle { get; set; } + public List Jobs { get; set; } + + public Process(int SoapPort) + { + this.SoapPort = SoapPort; + } + + internal void Start() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + this.Handle = new System.Diagnostics.Process(); + this.Handle.StartInfo.FileName = "Versions\\Tampa\\TadahServer.exe"; + this.Handle.StartInfo.Arguments = $"-Start ${this.SoapPort}"; + this.Handle.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; + this.Handle.Start(); + } + else + { + this.Handle = new System.Diagnostics.Process(); + this.Handle.StartInfo.FileName = "wine"; + this.Handle.StartInfo.Arguments = $"{Directory.GetCurrentDirectory()}/Versions/2016/TadahServer.exe -Start ${this.SoapPort}"; + this.Handle.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; + this.Handle.Start(); + } + + this.Client = new Tampa.Server.Client("http://tadah.rocks/", $"http://127.0.0.1:${this.SoapPort}"); + } + + internal void Close(bool forceKill = false) + { + if (forceKill) + { + Handle.Kill(); + } + else + { + foreach (Job job in Jobs) + { + if (!job.IsRunning) + { + continue; + } + + job.Close(); + } + + Handle.Close(); + } + } + } +} diff --git a/Tadah.Arbiter/Tampa/ProcessManager.cs b/Tadah.Arbiter/Tampa/ProcessManager.cs new file mode 100644 index 0000000..2224ff8 --- /dev/null +++ b/Tadah.Arbiter/Tampa/ProcessManager.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace Tadah.Tampa +{ + public class ProcessManager + { + public static List OpenProcesses = new(); + + private static int GetAvailableRccSoapPort() + { + int port = Arbiter.Configuration.BaseTampaSoapPort; + + for (int i = 0; i < Arbiter.Configuration.MaximumTampaProcesses; i++) + { + if (OpenProcesses.Find(process => process.SoapPort == port) == null) + { + break; + } + else + { + port++; + } + } + + return port; + } + + public static Process New() + { + if (OpenProcesses.Count >= Arbiter.Configuration.MaximumTampaProcesses) + { + throw new Exception("Maximum amount of Tampa processes reached"); + } + + Process process = new(GetAvailableRccSoapPort()); + process.Start(); + + OpenProcesses.Add(process); + return process; + } + + public static Process Best() + { + if (!OpenProcesses.Any()) + { + return New(); + } + + Process best = OpenProcesses.OrderBy(Process => Process.Jobs.Count).Last(); + if (best.Jobs.Count >= Arbiter.Configuration.MaximumJobsPerTampaProcess) + { + return New(); + } + + return best; + } + + public static void CloseAllProcesses() + { + foreach (Process process in OpenProcesses) + { + process.Close(); + } + + OpenProcesses.Clear(); + } + + public static void MonitorUnresponsiveProcesses() + { + while (true) + { + try + { + foreach (Process process in OpenProcesses) + { + if (process.Monitored) + { + continue; + } + + if (process.Handle.HasExited) + { + process.Close(true); + OpenProcesses.Remove(process); + + // remove all jobs associated + foreach (Job job in process.Jobs) + { + Arbiter.JobManager.CloseJob(job.Id, true); + } + + continue; + } + + if (process.Handle.Responding) + { + continue; + } + + Task.Run(() => MonitorUnresponsiveProcess(process)); + } + } + catch (InvalidOperationException ex) + { + Arbiter.Log.Write($"[Tampa.ProcessManager::MonitorUnresponsiveProcesses] InvalidOperationException - {ex.Message}", Arbiter.LogSeverity.Debug); + } + + Thread.Sleep(5000); + } + } + + private static void MonitorUnresponsiveProcess(Process process) + { + Arbiter.Log.Write($"[TampaProcessManager] TampaProcess with PID '{process.Handle.Id}' is not responding! Monitoring...", Arbiter.LogSeverity.Warning); + process.Monitored = true; + + for (int i = 0; i <= 30; i++) + { + Thread.Sleep(1000); + + if (process.Handle.Responding) + { + Arbiter.Log.Write($"[TampaProcessManager] TampaProcess with PID '{process.Handle.Id}' has recovered from its unresponsive status!", Arbiter.LogSeverity.Information); + process.Monitored = false; + + break; + } + else if (i == 30) + { + Arbiter.Log.Write($"[TampaProcessManager] TampaProcess with PID '{process.Handle.Id}' has been unresponsive for over 30 seconds. Closing Process...", Arbiter.LogSeverity.Warning); + process.Close(true); + OpenProcesses.Remove(process); + + // remove all jobs associated + foreach (Job job in process.Jobs) + { + Arbiter.JobManager.CloseJob(job.Id, true); + } + + break; + } + } + + return; + } + } +} diff --git a/Tadah.Arbiter/Tampa/Server/Soap.cs b/Tadah.Arbiter/Tampa/Server/Soap.cs new file mode 100644 index 0000000..c688acf --- /dev/null +++ b/Tadah.Arbiter/Tampa/Server/Soap.cs @@ -0,0 +1,910 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Tadah.Tampa.Server +{ + + + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ServiceModel.ServiceContractAttribute(Namespace="http://tadah.rocks/", ConfigurationName="Tadah.Tampa.Server.Soap")] + public interface Soap + { + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/HelloWorld", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + string HelloWorld(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/HelloWorld", ReplyAction="*")] + System.Threading.Tasks.Task HelloWorldAsync(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/GetVersion", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + string GetVersion(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/GetVersion", ReplyAction="*")] + System.Threading.Tasks.Task GetVersionAsync(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/GetStatus", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.Status GetStatus(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/GetStatus", ReplyAction="*")] + System.Threading.Tasks.Task GetStatusAsync(); + + // CODEGEN: Parameter 'OpenJobResult' requires additional schema information that cannot be captured using the parameter mode. The specific attribute is 'Microsoft.Xml.Serialization.XmlElementAttribute'. + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/OpenJob", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.OpenJobResponse OpenJob(Tadah.Tampa.Server.OpenJobRequest request); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/OpenJob", ReplyAction="*")] + System.Threading.Tasks.Task OpenJobAsync(Tadah.Tampa.Server.OpenJobRequest request); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/OpenJobEx", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.LuaValue[] OpenJobEx(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/OpenJobEx", ReplyAction="*")] + System.Threading.Tasks.Task OpenJobExAsync(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/RenewLease", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + double RenewLease(string jobID, double expirationInSeconds); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/RenewLease", ReplyAction="*")] + System.Threading.Tasks.Task RenewLeaseAsync(string jobID, double expirationInSeconds); + + // CODEGEN: Parameter 'ExecuteResult' requires additional schema information that cannot be captured using the parameter mode. The specific attribute is 'Microsoft.Xml.Serialization.XmlElementAttribute'. + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/Execute", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.ExecuteResponse Execute(Tadah.Tampa.Server.ExecuteRequest request); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/Execute", ReplyAction="*")] + System.Threading.Tasks.Task ExecuteAsync(Tadah.Tampa.Server.ExecuteRequest request); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/ExecuteEx", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.LuaValue[] ExecuteEx(string jobID, Tadah.Tampa.Server.ScriptExecution script); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/ExecuteEx", ReplyAction="*")] + System.Threading.Tasks.Task ExecuteExAsync(string jobID, Tadah.Tampa.Server.ScriptExecution script); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/CloseJob", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + void CloseJob(string jobID); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/CloseJob", ReplyAction="*")] + System.Threading.Tasks.Task CloseJobAsync(string jobID); + + // CODEGEN: Parameter 'BatchJobResult' requires additional schema information that cannot be captured using the parameter mode. The specific attribute is 'Microsoft.Xml.Serialization.XmlElementAttribute'. + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/BatchJob", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.BatchJobResponse BatchJob(Tadah.Tampa.Server.BatchJobRequest request); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/BatchJob", ReplyAction="*")] + System.Threading.Tasks.Task BatchJobAsync(Tadah.Tampa.Server.BatchJobRequest request); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/BatchJobEx", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.LuaValue[] BatchJobEx(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/BatchJobEx", ReplyAction="*")] + System.Threading.Tasks.Task BatchJobExAsync(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/GetExpiration", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + double GetExpiration(string jobID); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/GetExpiration", ReplyAction="*")] + System.Threading.Tasks.Task GetExpirationAsync(string jobID); + + // CODEGEN: Parameter 'GetAllJobsResult' requires additional schema information that cannot be captured using the parameter mode. The specific attribute is 'Microsoft.Xml.Serialization.XmlElementAttribute'. + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/GetAllJobs", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.GetAllJobsResponse GetAllJobs(Tadah.Tampa.Server.GetAllJobsRequest request); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/GetAllJobs", ReplyAction="*")] + System.Threading.Tasks.Task GetAllJobsAsync(Tadah.Tampa.Server.GetAllJobsRequest request); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/GetAllJobsEx", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.Job[] GetAllJobsEx(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/GetAllJobsEx", ReplyAction="*")] + System.Threading.Tasks.Task GetAllJobsExAsync(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/CloseExpiredJobs", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + int CloseExpiredJobs(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/CloseExpiredJobs", ReplyAction="*")] + System.Threading.Tasks.Task CloseExpiredJobsAsync(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/CloseAllJobs", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + int CloseAllJobs(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/CloseAllJobs", ReplyAction="*")] + System.Threading.Tasks.Task CloseAllJobsAsync(); + + // CODEGEN: Parameter 'DiagResult' requires additional schema information that cannot be captured using the parameter mode. The specific attribute is 'Microsoft.Xml.Serialization.XmlElementAttribute'. + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/Diag", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.DiagResponse Diag(Tadah.Tampa.Server.DiagRequest request); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/Diag", ReplyAction="*")] + System.Threading.Tasks.Task DiagAsync(Tadah.Tampa.Server.DiagRequest request); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/DiagEx", ReplyAction="*")] + [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] + Tadah.Tampa.Server.LuaValue[] DiagEx(int type, string jobID); + + [System.ServiceModel.OperationContractAttribute(Action="http://tadah.rocks/DiagEx", ReplyAction="*")] + System.Threading.Tasks.Task DiagExAsync(int type, string jobID); + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tadah.rocks/")] + public partial class Status + { + + private string versionField; + + private int environmentCountField; + + /// + [System.Xml.Serialization.XmlElementAttribute(Order=0)] + public string version + { + get + { + return this.versionField; + } + set + { + this.versionField = value; + } + } + + /// + [System.Xml.Serialization.XmlElementAttribute(Order=1)] + public int environmentCount + { + get + { + return this.environmentCountField; + } + set + { + this.environmentCountField = value; + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tadah.rocks/")] + public partial class LuaValue + { + + private LuaType typeField; + + private string valueField; + + private LuaValue[] tableField; + + /// + [System.Xml.Serialization.XmlElementAttribute(Order=0)] + public LuaType type + { + get + { + return this.typeField; + } + set + { + this.typeField = value; + } + } + + /// + [System.Xml.Serialization.XmlElementAttribute(Order=1)] + public string value + { + get + { + return this.valueField; + } + set + { + this.valueField = value; + } + } + + /// + [System.Xml.Serialization.XmlArrayAttribute(Order=2)] + public LuaValue[] table + { + get + { + return this.tableField; + } + set + { + this.tableField = value; + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tadah.rocks/")] + public enum LuaType + { + + /// + LUA_TNIL, + + /// + LUA_TBOOLEAN, + + /// + LUA_TNUMBER, + + /// + LUA_TSTRING, + + /// + LUA_TTABLE, + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tadah.rocks/")] + public partial class ScriptExecution + { + + private string nameField; + + private string scriptField; + + private LuaValue[] argumentsField; + + /// + [System.Xml.Serialization.XmlElementAttribute(Order=0)] + public string name + { + get + { + return this.nameField; + } + set + { + this.nameField = value; + } + } + + /// + [System.Xml.Serialization.XmlElementAttribute(Order=1)] + public string script + { + get + { + return this.scriptField; + } + set + { + this.scriptField = value; + } + } + + /// + [System.Xml.Serialization.XmlArrayAttribute(Order=2)] + public LuaValue[] arguments + { + get + { + return this.argumentsField; + } + set + { + this.argumentsField = value; + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tadah.rocks/")] + public partial class Job + { + + private string idField; + + private double expirationInSecondsField; + + private int categoryField; + + private double coresField; + + /// + [System.Xml.Serialization.XmlElementAttribute(Order=0)] + public string id + { + get + { + return this.idField; + } + set + { + this.idField = value; + } + } + + /// + [System.Xml.Serialization.XmlElementAttribute(Order=1)] + public double expirationInSeconds + { + get + { + return this.expirationInSecondsField; + } + set + { + this.expirationInSecondsField = value; + } + } + + /// + [System.Xml.Serialization.XmlElementAttribute(Order=2)] + public int category + { + get + { + return this.categoryField; + } + set + { + this.categoryField = value; + } + } + + /// + [System.Xml.Serialization.XmlElementAttribute(Order=3)] + public double cores + { + get + { + return this.coresField; + } + set + { + this.coresField = value; + } + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + [System.ServiceModel.MessageContractAttribute(WrapperName="OpenJob", WrapperNamespace="http://tadah.rocks/", IsWrapped=true)] + public partial class OpenJobRequest + { + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=0)] + public Tadah.Tampa.Server.Job job; + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=1)] + public Tadah.Tampa.Server.ScriptExecution script; + + public OpenJobRequest() + { + } + + public OpenJobRequest(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script) + { + this.job = job; + this.script = script; + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + [System.ServiceModel.MessageContractAttribute(WrapperName="OpenJobResponse", WrapperNamespace="http://tadah.rocks/", IsWrapped=true)] + public partial class OpenJobResponse + { + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=0)] + [System.Xml.Serialization.XmlElementAttribute("OpenJobResult")] + public Tadah.Tampa.Server.LuaValue[] OpenJobResult; + + public OpenJobResponse() + { + } + + public OpenJobResponse(Tadah.Tampa.Server.LuaValue[] OpenJobResult) + { + this.OpenJobResult = OpenJobResult; + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + [System.ServiceModel.MessageContractAttribute(WrapperName="Execute", WrapperNamespace="http://tadah.rocks/", IsWrapped=true)] + public partial class ExecuteRequest + { + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=0)] + public string jobID; + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=1)] + public Tadah.Tampa.Server.ScriptExecution script; + + public ExecuteRequest() + { + } + + public ExecuteRequest(string jobID, Tadah.Tampa.Server.ScriptExecution script) + { + this.jobID = jobID; + this.script = script; + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + [System.ServiceModel.MessageContractAttribute(WrapperName="ExecuteResponse", WrapperNamespace="http://tadah.rocks/", IsWrapped=true)] + public partial class ExecuteResponse + { + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=0)] + [System.Xml.Serialization.XmlElementAttribute("ExecuteResult", IsNullable=true)] + public Tadah.Tampa.Server.LuaValue[] ExecuteResult; + + public ExecuteResponse() + { + } + + public ExecuteResponse(Tadah.Tampa.Server.LuaValue[] ExecuteResult) + { + this.ExecuteResult = ExecuteResult; + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + [System.ServiceModel.MessageContractAttribute(WrapperName="BatchJob", WrapperNamespace="http://tadah.rocks/", IsWrapped=true)] + public partial class BatchJobRequest + { + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=0)] + public Tadah.Tampa.Server.Job job; + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=1)] + public Tadah.Tampa.Server.ScriptExecution script; + + public BatchJobRequest() + { + } + + public BatchJobRequest(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script) + { + this.job = job; + this.script = script; + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + [System.ServiceModel.MessageContractAttribute(WrapperName="BatchJobResponse", WrapperNamespace="http://tadah.rocks/", IsWrapped=true)] + public partial class BatchJobResponse + { + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=0)] + [System.Xml.Serialization.XmlElementAttribute("BatchJobResult", IsNullable=true)] + public Tadah.Tampa.Server.LuaValue[] BatchJobResult; + + public BatchJobResponse() + { + } + + public BatchJobResponse(Tadah.Tampa.Server.LuaValue[] BatchJobResult) + { + this.BatchJobResult = BatchJobResult; + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + [System.ServiceModel.MessageContractAttribute(WrapperName="GetAllJobs", WrapperNamespace="http://tadah.rocks/", IsWrapped=true)] + public partial class GetAllJobsRequest + { + + public GetAllJobsRequest() + { + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + [System.ServiceModel.MessageContractAttribute(WrapperName="GetAllJobsResponse", WrapperNamespace="http://tadah.rocks/", IsWrapped=true)] + public partial class GetAllJobsResponse + { + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=0)] + [System.Xml.Serialization.XmlElementAttribute("GetAllJobsResult", IsNullable=true)] + public Tadah.Tampa.Server.Job[] GetAllJobsResult; + + public GetAllJobsResponse() + { + } + + public GetAllJobsResponse(Tadah.Tampa.Server.Job[] GetAllJobsResult) + { + this.GetAllJobsResult = GetAllJobsResult; + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + [System.ServiceModel.MessageContractAttribute(WrapperName="Diag", WrapperNamespace="http://tadah.rocks/", IsWrapped=true)] + public partial class DiagRequest + { + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=0)] + public int type; + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=1)] + public string jobID; + + public DiagRequest() + { + } + + public DiagRequest(int type, string jobID) + { + this.type = type; + this.jobID = jobID; + } + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + [System.ServiceModel.MessageContractAttribute(WrapperName="DiagResponse", WrapperNamespace="http://tadah.rocks/", IsWrapped=true)] + public partial class DiagResponse + { + + [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tadah.rocks/", Order=0)] + [System.Xml.Serialization.XmlElementAttribute("DiagResult", IsNullable=true)] + public Tadah.Tampa.Server.LuaValue[] DiagResult; + + public DiagResponse() + { + } + + public DiagResponse(Tadah.Tampa.Server.LuaValue[] DiagResult) + { + this.DiagResult = DiagResult; + } + } + + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + public interface Channel : Tadah.Tampa.Server.Soap, System.ServiceModel.IClientChannel + { + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.3")] + public partial class Client : System.ServiceModel.ClientBase, Tadah.Tampa.Server.Soap + { + + public Client(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : + base(binding, remoteAddress) + { + } + + public Client(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) + { + } + + public string HelloWorld() + { + return base.Channel.HelloWorld(); + } + + public System.Threading.Tasks.Task HelloWorldAsync() + { + return base.Channel.HelloWorldAsync(); + } + + public string GetVersion() + { + return base.Channel.GetVersion(); + } + + public System.Threading.Tasks.Task GetVersionAsync() + { + return base.Channel.GetVersionAsync(); + } + + public Tadah.Tampa.Server.Status GetStatus() + { + return base.Channel.GetStatus(); + } + + public System.Threading.Tasks.Task GetStatusAsync() + { + return base.Channel.GetStatusAsync(); + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + Tadah.Tampa.Server.OpenJobResponse Tadah.Tampa.Server.Soap.OpenJob(Tadah.Tampa.Server.OpenJobRequest request) + { + return base.Channel.OpenJob(request); + } + + public Tadah.Tampa.Server.LuaValue[] OpenJob(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script) + { + Tadah.Tampa.Server.OpenJobRequest inValue = new Tadah.Tampa.Server.OpenJobRequest(); + inValue.job = job; + inValue.script = script; + Tadah.Tampa.Server.OpenJobResponse retVal = ((Tadah.Tampa.Server.Soap)(this)).OpenJob(inValue); + return retVal.OpenJobResult; + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + System.Threading.Tasks.Task Tadah.Tampa.Server.Soap.OpenJobAsync(Tadah.Tampa.Server.OpenJobRequest request) + { + return base.Channel.OpenJobAsync(request); + } + + public System.Threading.Tasks.Task OpenJobAsync(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script) + { + Tadah.Tampa.Server.OpenJobRequest inValue = new Tadah.Tampa.Server.OpenJobRequest(); + inValue.job = job; + inValue.script = script; + return ((Tadah.Tampa.Server.Soap)(this)).OpenJobAsync(inValue); + } + + public Tadah.Tampa.Server.LuaValue[] OpenJobEx(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script) + { + return base.Channel.OpenJobEx(job, script); + } + + public System.Threading.Tasks.Task OpenJobExAsync(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script) + { + return base.Channel.OpenJobExAsync(job, script); + } + + public double RenewLease(string jobID, double expirationInSeconds) + { + return base.Channel.RenewLease(jobID, expirationInSeconds); + } + + public System.Threading.Tasks.Task RenewLeaseAsync(string jobID, double expirationInSeconds) + { + return base.Channel.RenewLeaseAsync(jobID, expirationInSeconds); + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + Tadah.Tampa.Server.ExecuteResponse Tadah.Tampa.Server.Soap.Execute(Tadah.Tampa.Server.ExecuteRequest request) + { + return base.Channel.Execute(request); + } + + public Tadah.Tampa.Server.LuaValue[] Execute(string jobID, Tadah.Tampa.Server.ScriptExecution script) + { + Tadah.Tampa.Server.ExecuteRequest inValue = new Tadah.Tampa.Server.ExecuteRequest(); + inValue.jobID = jobID; + inValue.script = script; + Tadah.Tampa.Server.ExecuteResponse retVal = ((Tadah.Tampa.Server.Soap)(this)).Execute(inValue); + return retVal.ExecuteResult; + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + System.Threading.Tasks.Task Tadah.Tampa.Server.Soap.ExecuteAsync(Tadah.Tampa.Server.ExecuteRequest request) + { + return base.Channel.ExecuteAsync(request); + } + + public System.Threading.Tasks.Task ExecuteAsync(string jobID, Tadah.Tampa.Server.ScriptExecution script) + { + Tadah.Tampa.Server.ExecuteRequest inValue = new Tadah.Tampa.Server.ExecuteRequest(); + inValue.jobID = jobID; + inValue.script = script; + return ((Tadah.Tampa.Server.Soap)(this)).ExecuteAsync(inValue); + } + + public Tadah.Tampa.Server.LuaValue[] ExecuteEx(string jobID, Tadah.Tampa.Server.ScriptExecution script) + { + return base.Channel.ExecuteEx(jobID, script); + } + + public System.Threading.Tasks.Task ExecuteExAsync(string jobID, Tadah.Tampa.Server.ScriptExecution script) + { + return base.Channel.ExecuteExAsync(jobID, script); + } + + public void CloseJob(string jobID) + { + base.Channel.CloseJob(jobID); + } + + public System.Threading.Tasks.Task CloseJobAsync(string jobID) + { + return base.Channel.CloseJobAsync(jobID); + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + Tadah.Tampa.Server.BatchJobResponse Tadah.Tampa.Server.Soap.BatchJob(Tadah.Tampa.Server.BatchJobRequest request) + { + return base.Channel.BatchJob(request); + } + + public Tadah.Tampa.Server.LuaValue[] BatchJob(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script) + { + Tadah.Tampa.Server.BatchJobRequest inValue = new Tadah.Tampa.Server.BatchJobRequest(); + inValue.job = job; + inValue.script = script; + Tadah.Tampa.Server.BatchJobResponse retVal = ((Tadah.Tampa.Server.Soap)(this)).BatchJob(inValue); + return retVal.BatchJobResult; + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + System.Threading.Tasks.Task Tadah.Tampa.Server.Soap.BatchJobAsync(Tadah.Tampa.Server.BatchJobRequest request) + { + return base.Channel.BatchJobAsync(request); + } + + public System.Threading.Tasks.Task BatchJobAsync(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script) + { + Tadah.Tampa.Server.BatchJobRequest inValue = new Tadah.Tampa.Server.BatchJobRequest(); + inValue.job = job; + inValue.script = script; + return ((Tadah.Tampa.Server.Soap)(this)).BatchJobAsync(inValue); + } + + public Tadah.Tampa.Server.LuaValue[] BatchJobEx(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script) + { + return base.Channel.BatchJobEx(job, script); + } + + public System.Threading.Tasks.Task BatchJobExAsync(Tadah.Tampa.Server.Job job, Tadah.Tampa.Server.ScriptExecution script) + { + return base.Channel.BatchJobExAsync(job, script); + } + + public double GetExpiration(string jobID) + { + return base.Channel.GetExpiration(jobID); + } + + public System.Threading.Tasks.Task GetExpirationAsync(string jobID) + { + return base.Channel.GetExpirationAsync(jobID); + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + Tadah.Tampa.Server.GetAllJobsResponse Tadah.Tampa.Server.Soap.GetAllJobs(Tadah.Tampa.Server.GetAllJobsRequest request) + { + return base.Channel.GetAllJobs(request); + } + + public Tadah.Tampa.Server.Job[] GetAllJobs() + { + Tadah.Tampa.Server.GetAllJobsRequest inValue = new Tadah.Tampa.Server.GetAllJobsRequest(); + Tadah.Tampa.Server.GetAllJobsResponse retVal = ((Tadah.Tampa.Server.Soap)(this)).GetAllJobs(inValue); + return retVal.GetAllJobsResult; + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + System.Threading.Tasks.Task Tadah.Tampa.Server.Soap.GetAllJobsAsync(Tadah.Tampa.Server.GetAllJobsRequest request) + { + return base.Channel.GetAllJobsAsync(request); + } + + public System.Threading.Tasks.Task GetAllJobsAsync() + { + Tadah.Tampa.Server.GetAllJobsRequest inValue = new Tadah.Tampa.Server.GetAllJobsRequest(); + return ((Tadah.Tampa.Server.Soap)(this)).GetAllJobsAsync(inValue); + } + + public Tadah.Tampa.Server.Job[] GetAllJobsEx() + { + return base.Channel.GetAllJobsEx(); + } + + public System.Threading.Tasks.Task GetAllJobsExAsync() + { + return base.Channel.GetAllJobsExAsync(); + } + + public int CloseExpiredJobs() + { + return base.Channel.CloseExpiredJobs(); + } + + public System.Threading.Tasks.Task CloseExpiredJobsAsync() + { + return base.Channel.CloseExpiredJobsAsync(); + } + + public int CloseAllJobs() + { + return base.Channel.CloseAllJobs(); + } + + public System.Threading.Tasks.Task CloseAllJobsAsync() + { + return base.Channel.CloseAllJobsAsync(); + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + Tadah.Tampa.Server.DiagResponse Tadah.Tampa.Server.Soap.Diag(Tadah.Tampa.Server.DiagRequest request) + { + return base.Channel.Diag(request); + } + + public Tadah.Tampa.Server.LuaValue[] Diag(int type, string jobID) + { + Tadah.Tampa.Server.DiagRequest inValue = new Tadah.Tampa.Server.DiagRequest(); + inValue.type = type; + inValue.jobID = jobID; + Tadah.Tampa.Server.DiagResponse retVal = ((Tadah.Tampa.Server.Soap)(this)).Diag(inValue); + return retVal.DiagResult; + } + + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + System.Threading.Tasks.Task Tadah.Tampa.Server.Soap.DiagAsync(Tadah.Tampa.Server.DiagRequest request) + { + return base.Channel.DiagAsync(request); + } + + public System.Threading.Tasks.Task DiagAsync(int type, string jobID) + { + Tadah.Tampa.Server.DiagRequest inValue = new Tadah.Tampa.Server.DiagRequest(); + inValue.type = type; + inValue.jobID = jobID; + return ((Tadah.Tampa.Server.Soap)(this)).DiagAsync(inValue); + } + + public Tadah.Tampa.Server.LuaValue[] DiagEx(int type, string jobID) + { + return base.Channel.DiagEx(type, jobID); + } + + public System.Threading.Tasks.Task DiagExAsync(int type, string jobID) + { + return base.Channel.DiagExAsync(type, jobID); + } + + public virtual System.Threading.Tasks.Task OpenAsync() + { + return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action(((System.ServiceModel.ICommunicationObject)(this)).EndOpen)); + } + + public virtual System.Threading.Tasks.Task CloseAsync() + { + return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginClose(null, null), new System.Action(((System.ServiceModel.ICommunicationObject)(this)).EndClose)); + } + } +} diff --git a/Tadah.Arbiter/Unix.cs b/Tadah.Arbiter/Unix.cs new file mode 100644 index 0000000..83c6122 --- /dev/null +++ b/Tadah.Arbiter/Unix.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tadah +{ + public class Unix + { + public static int Now() + { + return (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds; + } + + public static int From(DateTime time) + { + return (int)(time - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds; + } + } +}