├── .gitignore ├── README.md ├── Setup.hs ├── copying.md ├── etc └── openage │ └── masterserver.yaml ├── legal └── AGPLv3 ├── openage-masterserver.cabal ├── src ├── Masterserver │ ├── Config.hs │ ├── Database.hs │ ├── Protocol.hs │ └── Server.hs └── main │ └── Main.hs ├── stack.yaml ├── stack.yaml.lock └── test └── TestCli.hs /.gitignore: -------------------------------------------------------------------------------- 1 | # editor-specific files 2 | \#* 3 | .#* 4 | *~ 5 | .*.swp 6 | 7 | # ELF files 8 | *.o 9 | *.a 10 | *.so 11 | *.s 12 | 13 | # python bytecode 14 | *.pyc 15 | *.pyo 16 | __pycache__ 17 | 18 | # workflow 19 | *.orig 20 | 21 | # build system 22 | /bin 23 | /.bin 24 | 25 | # debugging 26 | callgrind.out.* 27 | perf.data* 28 | .gdb_history 29 | 30 | # haskell stuff 31 | *.o 32 | *.hi 33 | *.chi 34 | *.chs.h 35 | *.prof 36 | *.hp 37 | .hpc 38 | .hsenv 39 | 40 | # cabal packaging 41 | dist/ 42 | cabal-dev/ 43 | .cabal-sandbox/ 44 | cabal.sandbox.config 45 | cabal.config 46 | .stack-work/ 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | openage matchmaking and lobbies 2 | =============================== 3 | 4 | What's this? 5 | ------------ 6 | 7 | This is the "master server" for [openage](http://openage.sft.mx). 8 | 9 | Features: 10 | 11 | * [ ] Dedicated server registry for public lobbies 12 | * [ ] Player accounts 13 | * [ ] Match results signed with [GPG](https://www.gnupg.org/) 14 | * [ ] Player and match statistics 15 | * [ ] [Elo](https://en.wikipedia.org/wiki/Elo_rating_system) rankings and match making 16 | 17 | 18 | When you want to play **with friends** via LAN, VPN or Internet, 19 | this server is not required for you. 20 | 21 | This server provides available public lobbies and can generate 22 | balanced battles through Elo matchmaking. 23 | 24 | 25 | How do I run this thing? 26 | ------------------------ 27 | 28 | You probably don't want to run it except for development: 29 | To have one "official" community, this server is provided by sft. 30 | 31 | The openage masterserver uses the haskell tool stack to build and 32 | install. 33 | Executables can be built using `stack build`. 34 | 35 | The server can be started by running `stack exec openage-masterserver`. 36 | The port it is listening on and the database login credentials are 37 | specified in the config file /etc/openage/masterserver.cfg. 38 | 39 | To start a testclient use 40 | `stack exec openage-masterserver-test HOST PORT` 41 | You will be promted to enter login credentials which need to be stored 42 | in the postgres database. 43 | To view all available commands type `help`. 44 | 45 | 46 | Can I help? 47 | ----------- 48 | 49 | Yay! You can just start hacking on whatever you like to improve. 50 | Fix bugs, implement features, submit pull requests! 51 | 52 | If you got any question, join our IRC: `#sfttech` on `irc.freenode.net`. 53 | 54 | 55 | License 56 | ------- 57 | 58 | **GNU AGPLv3** or later; see [copying.md](copying.md) and [legal/AGPLv3](legal/AGPLv3). 59 | 60 | I know that probably nobody is ever gonna look at the `copying.md` file, 61 | but if you want to contribute code to openage, please take the time to 62 | skim through it and add yourself to the authors list. 63 | -------------------------------------------------------------------------------- /Setup.hs: -------------------------------------------------------------------------------- 1 | -- Copyright 2015-2015 the openage authors. See copying.md for legal info. 2 | 3 | import Distribution.Simple 4 | main = defaultMain 5 | -------------------------------------------------------------------------------- /copying.md: -------------------------------------------------------------------------------- 1 | Any file in this project that doesn't state otherwise, and isn't listed as an 2 | exception below, is Copyright 2015-2015 The openage authors, and licensed 3 | under the terms of the GNU Affero General Public License Version 3, or 4 | (at your option) any later version ("AGPL3+"). 5 | A copy of the license can be found in [legal/AGPLv3](legal/AGPLv3). 6 | 7 | _the openage authors_ are: 8 | 9 | | Full name | aliases | E-Mail | 10 | |-----------------------------|-----------------------------|----------------------------------| 11 | | Jonas Jelten | TheJJ | jj@sft.mx | 12 | | Michael Enßlin | mic_e | michael@ensslin.cc | 13 | | Markus Otto | zuntrax | otto@fs.tum.de | 14 | | Janosch Kindl | kindl | janoschkindl+openage@gmail.com | 15 | | Tobias Heider | tobhe | tobias.heider@stud.ifi.lmu.de | 16 | 17 | If you're a first-time commiter, add yourself to the above list. This is not 18 | just for legal reasons, but also to keep an overview of all those nicknames. 19 | 20 | For some authors, the full names and/or e-mail addresses are unknown. They have 21 | been marked by "?". Luckily, those author's contributions are only small typo 22 | fixes, so no copyright concerns should arise from this. 23 | If your info is missing, wrong, or you want it to be removed for whatever 24 | reason, please contact us. 25 | 26 | A full list of all openage authors ("contributors") can also be determined 27 | from the VCS, e.g. via `git shortlog -sne`, or conveniently looked up on 28 | [the GitHub web interface](https://github.com/SFTtech/openage-masterserver/graphs/contributors). 29 | 30 | Details on individual authorships of files can be obtained via the VCS, 31 | e.g. via `git blame`, or the GitHub web interface. 32 | 33 | This program is distributed in the hope that it will be useful, 34 | but WITHOUT ANY WARRANTY; without even the implied warranty of 35 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 36 | GNU General Public License Version 3 for more details. 37 | 38 | If you wish to include a file from openage in your project, make sure to 39 | include all required legal info. The easiest way to do this would probably 40 | be to include a copy of this file (`copying.md`), and to leave the file's 41 | copyright header untouched. 42 | 43 | Per-file license header guidelines: 44 | 45 | In addition to this file, to prevent legal caveats, every source file *must* 46 | include a header. 47 | 48 | **openage-native** source files, that is, files that were created by 49 | _the openage authors_, require the following one-line header, preferrably in 50 | the first line, as a comment: 51 | 52 | Copyright 20XX-20YY the openage authors. See copying.md for legal info. 53 | 54 | `XXXX` is the year when the file was created, and `YYYY` is the year when the 55 | file was last edited. When editing a file, make sure the last-modification year 56 | is still correct. 57 | 58 | **3rd-party** source files, that is, files that were taken from other open- 59 | source projects, require the following, longer header: 60 | 61 | This file was ((taken|adapted)|contains (data|code)) from $PROJECT, 62 | Copyright 1337-2013 Your Mom. 63 | It's licensed under the terms of the 3-clause BSD license. 64 | < any amount of lines of further legal information required by $PROJECT, 65 | such as a reference to a copy of the $PROJECT's README or AUTHORS file > 66 | < if third-party files from more than the one project were used in this 67 | file, copy the above any number of times > 68 | (Modifications|Other (data|code)|Everything else) Copyright 2014-2014 the openage authors. 69 | See copying.md for further legal info. 70 | 71 | In addition to the openage legal header, the file's original license header should 72 | be retained if in doubt. 73 | 74 | The "license" line is required only if the file is not licensed as 75 | "AGPLv3 or higher". 76 | 77 | Authors of 3rd-party files should generally not be entered in the 78 | "openage authors" list. 79 | 80 | All 3rd-party files **must** be included in the following list: 81 | 82 | List of all 3rd-party files in openage: 83 | 84 | - none (currently) 85 | 86 | Notes about this file: 87 | 88 | I (mic_e) am not a lawyer. This is an open-source project, we're doing this for 89 | fun. People convinced me that this legal shit must be done, so I did it, even 90 | though I'd rather have spent the time on useful parts of the project. 91 | If you see any legal issues, feel free to contact me. 92 | I, personally, despise in-sourcefile legal text blocks. They're a pest, 93 | and unlike many others, I don't simply accept them because 94 | "that is what everybody does". Thus, I worked out the minimal 1-line text above, 95 | which should be free of legal caveats, and a reasonable compromise. 96 | I'd be happy to see it used in other projects; you're free to use this file 97 | (`copying.md`) as a template for your project's legal documentation. 98 | -------------------------------------------------------------------------------- /etc/openage/masterserver.yaml: -------------------------------------------------------------------------------- 1 | # Client version accepted by server where [1,0,0] stands for 2 | # version 1.0.0 3 | acceptedVersion: [1,0,0] 4 | # Port server is running on 5 | port: 1234 6 | # Database connection information 7 | database: 8 | host: 9 | database: 10 | password: 11 | user: 12 | port: 5432 13 | poolsize: 10 14 | -------------------------------------------------------------------------------- /legal/AGPLv3: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /openage-masterserver.cabal: -------------------------------------------------------------------------------- 1 | -- openage masterserver cabal config 2 | 3 | name: openage-masterserver 4 | version: 0.1.0.0 5 | synopsis: master server for openage 6 | description: 7 | Lobby and matchmaking server for openage. 8 | 9 | Imparts public servers to game clients, keeps track of game statistics, 10 | creates signed match results and achievements, performs player rankings. 11 | homepage: http://openage.sft.mx 12 | license: AGPL-3 13 | license-file: legal/AGPLv3 14 | author: Jonas Jelten 15 | maintainer: jj@sft.mx 16 | copyright: 2016, openage team 17 | category: Network, Game 18 | build-type: Simple 19 | extra-source-files: README.md 20 | cabal-version: >=1.10 21 | 22 | library 23 | ghc-options: -O2 -Wall -fwarn-tabs -fwarn-incomplete-uni-patterns -fwarn-incomplete-record-updates 24 | hs-source-dirs: src 25 | exposed-modules: Masterserver.Protocol 26 | , Masterserver.Config 27 | , Masterserver.Database 28 | , Masterserver.Server 29 | build-depends: base >= 4.7 && < 5 30 | , async >= 2.1 31 | , aeson >= 0.11 32 | , containers >= 0.5 33 | , text 34 | , bytestring >= 0.10 35 | , persistent 36 | , persistent-postgresql >= 2.2 37 | , persistent-template >= 2.1 38 | , transformers >= 0.4 39 | , configurator 40 | , mtl 41 | , stm >= 2.4 42 | , monad-logger >= 0.3 43 | , network >= 2.6 44 | , yaml >= 0.8 45 | default-language: Haskell2010 46 | 47 | executable openage-masterserver 48 | ghc-options: -O2 -Wall -threaded -fwarn-tabs -fwarn-incomplete-uni-patterns -fwarn-incomplete-record-updates 49 | hs-source-dirs: src/main/ 50 | main-is: Main.hs 51 | build-depends: base >= 4.7 52 | , aeson >= 0.11 53 | , async >= 2.1 54 | , bcrypt 55 | , bytestring >= 0.10 56 | , containers >= 0.5 57 | , network >= 2.6 58 | , persistent 59 | , stm >= 2.4 60 | , text 61 | , openage-masterserver 62 | default-language: Haskell2010 63 | 64 | executable openage-masterserver-test 65 | hs-source-dirs: test/ 66 | main-is: TestCli.hs 67 | ghc-options: -O2 -Wall -threaded -rtsopts -with-rtsopts=-N -fwarn-tabs -fwarn-incomplete-uni-patterns -fwarn-incomplete-record-updates 68 | build-depends: base 69 | , openage-masterserver 70 | , async >= 2.1 71 | , aeson >= 0.11 72 | , containers >= 0.5 73 | , text 74 | , bytestring >= 0.10 75 | , persistent 76 | , persistent-postgresql >= 2.2 77 | , persistent-template >= 2.1 78 | , transformers >= 0.4 79 | , configurator 80 | , mtl 81 | , keys 82 | , stm >= 2.4 83 | , monad-logger >= 0.3 84 | , network >= 2.6 85 | default-language: Haskell2010 86 | 87 | source-repository head 88 | type: git 89 | location: https://github.com/SFTtech/openage-masterserver.git 90 | -------------------------------------------------------------------------------- /src/Masterserver/Config.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | {-# LANGUAGE TemplateHaskell #-} 3 | ------------------------------------------------------------------------------ 4 | -- | 5 | -- Copyright 2016-2016 the openage authors. See copying.md for legal info. 6 | -- Module: Masterserver.Config 7 | -- 8 | -- This Module defines the masterservers config parser. 9 | 10 | ------------------------------------------------------------------------------ 11 | module Masterserver.Config 12 | ( getPostgresConf 13 | , getPort 14 | , getVersion 15 | ) where 16 | 17 | import Data.Aeson.TH 18 | import Data.Yaml 19 | import Database.Persist.Postgresql 20 | 21 | -- | Config datatype used for parsing. 22 | data Config = Config 23 | { acceptedVersion :: ![Int] -- ^ Client version accepted by server 24 | , port :: !Int -- ^ Port to run server on 25 | , database :: !Value -- ^ Database connection info 26 | } deriving Show 27 | 28 | -- | Derives aeson toJSON and fromJSON instances for Config. 29 | $(deriveJSON defaultOptions ''Config) 30 | 31 | -- | Get PostgresConf from yaml file. 32 | getPostgresConf :: IO PostgresConf 33 | getPostgresConf = do 34 | Just yaml <- decodeFile "etc/openage/masterserver.yaml" 35 | conf <- parseMonad loadConfig $ database yaml 36 | applyEnv (conf :: PostgresConf) 37 | 38 | -- | Get port from yaml file. 39 | getPort :: IO Int 40 | getPort = do 41 | Just yaml <- decodeFile "etc/openage/masterserver.yaml" 42 | return $ port yaml 43 | 44 | -- | Get accepted version from yaml file. 45 | getVersion :: IO [Int] 46 | getVersion = do 47 | Just yaml <- decodeFile "etc/openage/masterserver.yaml" 48 | return $ acceptedVersion yaml 49 | 50 | -------------------------------------------------------------------------------- /src/Masterserver/Database.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DerivingStrategies #-} 2 | {-# LANGUAGE StandaloneDeriving #-} 3 | {-# LANGUAGE UndecidableInstances #-} 4 | {-# LANGUAGE OverloadedStrings #-} 5 | {-# LANGUAGE MultiParamTypeClasses #-} 6 | {-# LANGUAGE TemplateHaskell #-} 7 | {-# LANGUAGE FlexibleContexts #-} 8 | {-# LANGUAGE GADTs #-} 9 | {-# LANGUAGE GeneralizedNewtypeDeriving #-} 10 | {-# LANGUAGE QuasiQuotes #-} 11 | {-# LANGUAGE TypeFamilies #-} 12 | 13 | ------------------------------------------------------------------------------ 14 | -- | 15 | -- Copyright 2016-2016 the openage authors. See copying.md for legal info. 16 | -- Module: Masterserver: Masterserver.Database 17 | -- 18 | -- This Module defines the database scheme used by the masterserver and 19 | -- provides database access functions 20 | 21 | ------------------------------------------------------------------------------ 22 | module Masterserver.Database where 23 | 24 | import Data.ByteString.Char8 as BC 25 | import Database.Persist 26 | import Database.Persist.Sql 27 | import Database.Persist.Postgresql as PO 28 | import Database.Persist.TH 29 | import Data.Text 30 | 31 | import Masterserver.Config 32 | 33 | share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| 34 | Player 35 | username Text 36 | UniqueUsername username 37 | password ByteString 38 | deriving Show 39 | |] 40 | 41 | -- | Add Player to table player 42 | addPlayer :: Text -- ^ Players unique account-name 43 | -> BC.ByteString -- ^ Players salted password hash 44 | -> IO (Maybe (PO.Key Player)) -- ^ Resulting Player 45 | addPlayer name pw = 46 | runPost $ PO.insertUnique $ Player name pw 47 | 48 | -- | Get Player by name 49 | getPlayer :: Text -- ^ Players unique name 50 | -> IO(Maybe (PO.Entity Player)) -- ^ Persist Entity for Player 51 | getPlayer pName = 52 | runPost $ PO.getBy $ UniqueUsername pName 53 | 54 | -- | Run the migrations, creating the database if required. 55 | createDB :: IO () 56 | createDB = 57 | runPost $ runMigration migrateAll 58 | 59 | -- | Run a persist transaction with config credentials 60 | runPost :: SqlPersistT IO a -- ^ Database access action 61 | -> IO a -- ^ actions result 62 | runPost action = do 63 | conf <- getPostgresConf 64 | pool <- createPoolConfig conf 65 | PO.runPool conf action pool 66 | -------------------------------------------------------------------------------- /src/Masterserver/Protocol.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | {-# LANGUAGE TemplateHaskell #-} 3 | {-# LANGUAGE RecordWildCards #-} 4 | -- | Better performance for strict records 5 | {-# OPTIONS_GHC -funbox-strict-fields #-} 6 | 7 | ------------------------------------------------------------------------------ 8 | -- | 9 | -- Copyright 2016-2016 the openage authors. See copying.md for legal info. 10 | -- Module: Masterserver.Protocol 11 | -- 12 | -- This Module defines the JSON protocol used in client-server 13 | -- communicaton. 14 | -- 15 | -- Messages sent to serverthreads are of type InMessage, messages sent 16 | -- to the client are of type OutMessage. 17 | 18 | ------------------------------------------------------------------------------ 19 | 20 | module Masterserver.Protocol 21 | ( InMessage(..) 22 | , OutMessage(..) 23 | , Game(..) 24 | , newGame 25 | , AuthPlayerName 26 | , GameName 27 | , Participant(..) 28 | , newParticipant 29 | ) 30 | where 31 | 32 | import Control.Concurrent.STM 33 | import Data.Aeson.TH 34 | import Data.Map.Strict as Map 35 | import Data.Text(Text) 36 | import Data.Version 37 | import Network.Socket 38 | 39 | -- | Messages received by server 40 | data InMessage 41 | = AddPlayer {name :: !Text, pw :: !Text} 42 | | Broadcast {content :: !Text} 43 | | ChatFromClient {chatFromCContent :: !Text} 44 | | ChatFromThread 45 | { chatFromTOrign :: !AuthPlayerName 46 | , chatFromTContent :: !Text 47 | } 48 | | Login 49 | { loginName :: !AuthPlayerName 50 | , loginPassword :: !Text 51 | } 52 | | Logout 53 | | GameClosedByHost 54 | | GameConfig 55 | { gameConfMap :: !Text 56 | , gameConfMode :: !Text 57 | , gameConfPlayerNum :: !Int 58 | } 59 | | GameInfo 60 | | GameInit 61 | { gameInitName :: !GameName 62 | , gameInitMap :: !Text 63 | , maxPlayers :: !Int 64 | } 65 | | GameJoin {gameId :: !GameName} 66 | | GameLeave 67 | | GameQuery 68 | | GameOver 69 | | GameStart 70 | | GameStartedByHost 71 | | PlayerConfig 72 | { playerCiv :: !Text 73 | , playerTeam :: !Int 74 | , playerReady :: !Bool 75 | } 76 | | VersionMessage {peerProtocolVersion :: !Version} 77 | deriving (Show, Read, Eq) 78 | 79 | -- | Messages sent by Server 80 | data OutMessage 81 | = ChatOut 82 | { chatOutOrigin :: !AuthPlayerName 83 | , chatOutContent :: !Text 84 | } 85 | | GameStartAnswer {playerMap :: Map AuthPlayerName HostName} 86 | | GameQueryAnswer {gameList :: ![Game]} 87 | | GameInfoAnswer {game :: !Game} 88 | | Error {errorString :: !Text} 89 | | Message {messageString :: !Text} 90 | deriving Show 91 | 92 | -- | Game datatype 93 | -- It stores information about an open game 94 | data Game = Game 95 | { gameHost :: !AuthPlayerName 96 | , gameName:: !GameName 97 | , gameMap :: !Text 98 | , gameMode :: !Text 99 | , numPlayers :: !Int 100 | , gamePlayers :: Map AuthPlayerName Participant 101 | } deriving Show 102 | 103 | -- | Unique player account name 104 | type AuthPlayerName = Text 105 | 106 | -- | Unique game name 107 | type GameName = Text 108 | 109 | newGame :: GameName -> AuthPlayerName -> Text -> Int -> STM Game 110 | newGame gameName gameHost gameMap numPlayers = 111 | return Game { gamePlayers=Map.empty 112 | , gameMode="None", ..} 113 | 114 | -- | Game participant, players ingame settings 115 | data Participant = Participant 116 | { parName :: !AuthPlayerName 117 | , parCiv :: !Text 118 | , parTeam :: !Int 119 | , parReady :: !Bool 120 | } deriving Show 121 | 122 | newParticipant :: AuthPlayerName -> Bool -> Participant 123 | newParticipant parName parReady = Participant{ parCiv="None" 124 | , parTeam=0, ..} 125 | 126 | -- | Create automatically derived json protocol instances 127 | Prelude.concat <$> mapM (deriveJSON defaultOptions) [''InMessage, 128 | ''Participant, 129 | ''Game, 130 | ''OutMessage] 131 | -------------------------------------------------------------------------------- /src/Masterserver/Server.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | {-# LANGUAGE RecordWildCards #-} 3 | -- | Better performance for strict records 4 | {-# OPTIONS_GHC -funbox-strict-fields #-} 5 | 6 | ------------------------------------------------------------------------------ 7 | -- | 8 | -- Copyright 2016-2016 the openage authors. See copying.md for legal info. 9 | -- Module: Masterserver.Server 10 | -- 11 | -- This module defines the server datatype and several helperfunctions 12 | -- for the masterservers server logic. 13 | 14 | ------------------------------------------------------------------------------ 15 | 16 | module Masterserver.Server where 17 | 18 | import Control.Concurrent.STM 19 | import Control.Monad 20 | import Data.Aeson 21 | import Data.ByteString.Char8 as BC 22 | import Data.ByteString.Lazy as BL 23 | import Data.List as L 24 | import Data.Map.Strict as Map 25 | import Data.Text 26 | import Network.Socket 27 | import System.IO as S 28 | 29 | import Masterserver.Protocol as P 30 | 31 | -- | Server Datatype 32 | -- Stores Map of running games and Map of logged in clients. 33 | data Server = Server 34 | { -- | Map of open games on the server 35 | games :: TVar (Map GameName Game) 36 | -- | Map of connected clients 37 | , clients :: TVar (Map AuthPlayerName Client) 38 | } 39 | 40 | -- | Returns a Server with empty games and clients Maps. 41 | newServer :: IO Server 42 | newServer = do 43 | games <- newTVarIO Map.empty 44 | clients <- newTVarIO Map.empty 45 | return Server{..} 46 | 47 | -- | Client datatype 48 | -- It stores players name, handle and a channel to address it. 49 | data Client = Client { 50 | clientName :: !AuthPlayerName, -- ^ Name of logged in account 51 | clientAddr :: !HostName, -- ^ Clients ip 52 | clientHandle :: !Handle, -- ^ Clients Socket 53 | clientChan :: TChan InMessage, -- ^ Channel client listens on 54 | clientInGame :: Maybe Text -- ^ Game client has joined 55 | } 56 | 57 | -- |Client constructor 58 | newClient :: AuthPlayerName -> HostName -> Handle -> IO Client 59 | newClient clientName clientAddr clientHandle = do 60 | clientChan <- newTChanIO 61 | return Client{clientInGame=Nothing,..} 62 | 63 | -- | Sends InMessage to the clients channel 64 | sendChannel :: Client -> InMessage -> IO () 65 | sendChannel Client{..} msg = 66 | atomically $ writeTChan clientChan msg 67 | 68 | -- | Send OutMessage over handle to client 69 | sendEncoded :: ToJSON a => Handle -> a -> IO() 70 | sendEncoded handle = BC.hPutStrLn handle . BL.toStrict . encode 71 | 72 | -- | Send encoded GameQueryAnswer 73 | sendGameQueryAnswer :: Handle -> [Game] -> IO () 74 | sendGameQueryAnswer handle list = 75 | sendEncoded handle $ GameQueryAnswer list 76 | 77 | -- | Send encoded Message 78 | sendMessage :: Handle -> Text -> IO() 79 | sendMessage handle text = 80 | sendEncoded handle $ Message text 81 | 82 | -- | Send encoded Error message 83 | sendError :: Handle -> Text -> IO() 84 | sendError handle text = 85 | sendEncoded handle $ P.Error text 86 | 87 | -- | Get List of Games in servers game map 88 | getGameList :: Server -> STM [Game] 89 | getGameList Server{..} = do 90 | gameList <- readTVar games 91 | return $ Map.elems gameList 92 | 93 | -- | Add game to servers game map 94 | checkAddGame :: Server -- ^ Global server containing Maps 95 | -> AuthPlayerName -- ^ This Clients name 96 | -> InMessage -- ^ GameInit message 97 | -> STM (Maybe Game) -- ^ resulting Game if name is not taken 98 | checkAddGame Server{..} pName GameInit{..} = do 99 | gamesMap <- readTVar games 100 | if Map.member gameInitName gamesMap 101 | then return Nothing 102 | else do 103 | game <- newGame gameInitName pName gameInitMap maxPlayers 104 | writeTVar games $ Map.insert gameInitName game gamesMap 105 | return $ Just game 106 | checkAddGame _ _ _ = return Nothing 107 | 108 | -- | Remove Game from servers game map 109 | removeGame :: Server -> GameName -> STM () 110 | removeGame Server{..} game = 111 | modifyTVar' games $ Map.delete game 112 | 113 | -- | Add client to servers clients map 114 | addClient :: Server -> Client -> STM () 115 | addClient Server{..} client@Client{..} = do 116 | clientsMap <- readTVar clients 117 | if member clientName clientsMap 118 | then retry 119 | else writeTVar clients $ Map.insert clientName client clientsMap 120 | 121 | -- | Removes client from servers clientmap and leaves game 122 | removeClientLeave :: Server -> AuthPlayerName -> IO () 123 | removeClientLeave server@Server{..} cliName = do 124 | clientsMap <- readTVarIO clients 125 | let client@Client{..} = clientsMap!cliName 126 | maybe (return ()) (gameLeaveHandler server client) clientInGame 127 | atomically $ modifyTVar' clients $ Map.delete clientName 128 | 129 | -- | Add game to Host and Participant to games map of players 130 | joinGame :: Server -- ^ Global server containing Maps 131 | -> AuthPlayerName -- ^ This Clients name 132 | -> GameName -- ^ Name of game to join 133 | -> Bool -- ^ True if ready 134 | -> STM () 135 | joinGame Server{..} clientName gameName rdy= do 136 | gamesMap <- readTVar games 137 | clientsMap <- readTVar clients 138 | writeTVar clients 139 | $ Map.adjust (addClientInGame gameName) clientName clientsMap 140 | writeTVar games 141 | $ Map.adjust (addParticipant clientName 142 | rdy) gameName gamesMap 143 | 144 | -- | Delete clientName from game and gameName from client in Maps 145 | leaveGame :: Server -- ^ Global server containing Maps 146 | -> AuthPlayerName -- ^ This Clients name 147 | -> GameName -- ^ Name of game to leave 148 | -> STM () 149 | leaveGame Server{..} clientName game = do 150 | let leavePlayer gameOld@Game{..} = 151 | gameOld {gamePlayers = Map.delete clientName gamePlayers} 152 | clientsMap <- readTVar clients 153 | gamesMap <- readTVar games 154 | writeTVar clients $ Map.adjust removeClientInGame clientName clientsMap 155 | when (member game gamesMap) $ 156 | writeTVar games $ Map.adjust leavePlayer game gamesMap 157 | 158 | -- | Leave Game if normal player, close if host 159 | gameLeaveHandler :: Server -> Client -> GameName -> IO() 160 | gameLeaveHandler server@Server{..} Client{..} game = do 161 | gameLis <- readTVarIO games 162 | if clientName == gameHost (gameLis!game) 163 | then do 164 | broadcastGame server game GameClosedByHost 165 | atomically $ removeGame server game 166 | else do 167 | atomically $ leaveGame server clientName game 168 | sendMessage clientHandle "Left Game." 169 | 170 | -- | Add Game to Clients clientInGame field 171 | addClientInGame :: GameName -> Client -> Client 172 | addClientInGame game client@Client{..} = 173 | client {clientInGame = Just game} 174 | 175 | -- | Remove Game from clientsInGame field 176 | removeClientInGame :: Client -> Client 177 | removeClientInGame cli = cli {clientInGame = Nothing} 178 | 179 | -- | Add participant to game 180 | addParticipant :: AuthPlayerName -- ^ Players name 181 | -> Bool -- ^ True if player is host 182 | -> Game -- ^ Game to update 183 | -> Game -- ^ Resulting game 184 | addParticipant name host game@Game{..} = 185 | game {gamePlayers = Map.insert name 186 | (newParticipant name host) gamePlayers} 187 | 188 | -- | Update game with given map, mode and player number 189 | updateGame :: Text -- ^ Games map name 190 | -> Text -- ^ Game mode 191 | -> Int -- ^ Maximal number of Players 192 | -> Game -- ^ Game to update 193 | -> Game -- ^ Resulting game 194 | updateGame gMap mode num game = 195 | game {gameMap=gMap, gameMode=mode, numPlayers=num} 196 | 197 | -- | Updates player configuration 198 | updatePlayer :: AuthPlayerName -- ^ Players name 199 | -> Text -- ^ Players civilization 200 | -> Int -- ^ Team number 201 | -> Bool -- ^ True if player is ready 202 | -> Game -- ^ Game to update 203 | -> Game -- ^ Resulting game 204 | updatePlayer name civ team rdy game@Game{..} = 205 | game {gamePlayers = Map.adjust updateP name gamePlayers} 206 | where 207 | updateP par = par { parName = name 208 | , parCiv = civ 209 | , parTeam=team 210 | , parReady=rdy} 211 | 212 | -- | Broadcast message to all Clients in a Game 213 | broadcastGame :: Server -> GameName -> InMessage -> IO () 214 | broadcastGame Server{..} gameName msg = do 215 | clientLis <- readTVarIO clients 216 | gameLis <- readTVarIO games 217 | mapM_ (flip sendChannel msg . (!) clientLis . parName) 218 | $ gamePlayers $ gameLis!gameName 219 | 220 | -- | Convert the clientmap with filter to the map format used in 221 | -- GameStartAnswer 222 | convMap :: Map.Map AuthPlayerName Client -- ^ Servers clients map 223 | -> [AuthPlayerName] -- ^ List of clients to convert 224 | -> Map.Map AuthPlayerName HostName -- ^ Resulting GameStart map 225 | convMap inMap lis = 226 | Map.map clientAddr (Map.filterWithKey (\k _ -> k `L.elem` lis) inMap) 227 | -------------------------------------------------------------------------------- /src/main/Main.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | {-# LANGUAGE RecordWildCards #-} 3 | 4 | ----------------------------------------------------------------------------- 5 | -- | 6 | -- Copyright 2016-2016 the openage authors. See copying.md for legal info. 7 | -- Module: Main 8 | -- 9 | -- Main entry file for the openage masterserver 10 | -- this server will listen on a tcp socket 11 | -- and provide a funny API for gameservers and clients 12 | -- to start communicating with each other. 13 | 14 | ----------------------------------------------------------------------------- 15 | module Main where 16 | 17 | import Control.Concurrent 18 | import Control.Concurrent.STM 19 | import Control.Concurrent.Async 20 | import Control.Exception.Base (finally) 21 | import Control.Monad 22 | import Crypto.BCrypt 23 | import Data.Aeson 24 | import Data.ByteString as B 25 | import Data.ByteString.Lazy as BL 26 | import Data.ByteString.Char8 as BC 27 | import Data.List as L 28 | import Data.Map.Strict as Map 29 | import Data.Maybe 30 | import Data.Text as T 31 | import Data.Version (makeVersion) 32 | import Database.Persist 33 | import Network.Socket hiding (Broadcast) 34 | import Text.Printf 35 | import System.IO as S 36 | 37 | import Masterserver.Config 38 | import Masterserver.Database 39 | import Masterserver.Protocol as P 40 | import Masterserver.Server 41 | 42 | extractIP :: SockAddr -> String 43 | extractIP (SockAddrInet _ host) = 44 | let (a, b, c, d) = hostAddressToTuple host 45 | in show a <> "." <> show b <> "." <> show c <> "." <> show d 46 | extractIP (SockAddrInet6 _ _ host _) = show host 47 | extractIP x = show x 48 | 49 | main :: IO () 50 | main = createDB *> go 51 | where 52 | go = withSocketsDo $ do 53 | port <- getPort 54 | server <- newServer 55 | let hints = defaultHints { addrSocketType = Stream } 56 | addr:_ <- getAddrInfo (Just hints) (Just "0.0.0.0") (Just $ show port) 57 | sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr) 58 | setSocketOption sock ReuseAddr 1 59 | bind sock (addrAddress addr) 60 | listen sock 1024 61 | printf "Listening on port %d\n" port 62 | forever $ do 63 | (clientSock, host) <- accept sock 64 | handle <- socketToHandle clientSock ReadWriteMode 65 | let clientIP = extractIP host 66 | printf "Accepted connection from %s\n" clientIP 67 | forkFinally (talk handle server clientIP) (\e -> do 68 | print e 69 | printf "Connection from %s closed\n" clientIP >> hClose handle) 70 | 71 | talk :: Handle -> Server -> HostName -> IO() 72 | talk handle server hostname = do 73 | S.hSetNewlineMode handle universalNewlineMode 74 | S.hSetBuffering handle LineBuffering 75 | checkVersion handle 76 | mayClient <- checkAddClient handle server hostname 77 | case mayClient of 78 | Just client@Client{..} -> do 79 | sendMessage handle "Login success." 80 | runClient server client 81 | `finally` removeClientLeave server clientName 82 | Nothing -> 83 | sendError handle "Login failed." 84 | 85 | -- | Compare Version to own 86 | checkVersion :: S.Handle -> IO () 87 | checkVersion handle = do 88 | verJson <- B.hGetLine handle 89 | myVersion <- getVersion 90 | if ( peerProtocolVersion 91 | . fromJust 92 | . decode 93 | . BL.fromStrict) verJson == makeVersion myVersion 94 | then 95 | sendMessage handle "Version accepted." 96 | else do 97 | sendError handle "Incompatible Version." 98 | thread <- myThreadId 99 | killThread thread 100 | 101 | -- | Get login credentials from handle, add client to servers 102 | -- clientmap and return Client 103 | checkAddClient :: Handle -> Server -> HostName -> IO(Maybe Client) 104 | checkAddClient handle server@Server{..} hostname = do 105 | loginJson <- B.hGetLine handle 106 | case (decode . BL.fromStrict) loginJson of 107 | Just Login{..} -> do 108 | let toBs = BC.pack . T.unpack 109 | Just (Entity _ Player{..}) <- getPlayer loginName 110 | if validatePassword playerPassword (toBs loginPassword) 111 | then do 112 | clientMap <- readTVarIO clients 113 | client <- newClient playerUsername hostname handle 114 | if member playerUsername clientMap 115 | then do 116 | sendChannel (clientMap!playerUsername) Logout 117 | atomically $ addClient server client 118 | return $ Just client 119 | else do 120 | atomically $ addClient server client 121 | return $ Just client 122 | else return Nothing 123 | Just AddPlayer{..} -> do 124 | hash <- hashPw pw 125 | res <- addPlayer name hash 126 | maybe (sendError handle "Name taken." 127 | >> checkAddClient handle server hostname) 128 | (\_ -> sendMessage handle "Player successfully added." 129 | >> checkAddClient handle server hostname) res 130 | _ -> do 131 | sendError handle "Unknown Format." 132 | return Nothing 133 | 134 | -- | Uses BCrypt to hash pw before writing it to db 135 | hashPw :: Text -- ^ Password sent by client 136 | -> IO BC.ByteString -- ^ salted password hash 137 | hashPw pw = do 138 | let toBs = BC.pack . T.unpack 139 | mayHash <- hashPasswordUsingPolicy slowerBcryptHashingPolicy $ toBs pw 140 | maybe (error "Hashing failed") return mayHash 141 | 142 | -- | Runs individual Client 143 | runClient :: Server -> Client -> IO () 144 | runClient server@Server{..} client@Client{..} = do 145 | _ <- race internalReceive $ mainLoop server client 146 | return () 147 | where 148 | internalReceive = forever $ do 149 | msg <- B.hGetLine clientHandle 150 | maybe (sendError clientHandle "Could not read message.") 151 | (sendChannel client) $ (decode . BL.fromStrict) msg 152 | 153 | -- | Main Lobby loop with ClientMessage Handler functions 154 | mainLoop :: Server -> Client -> IO () 155 | mainLoop server@Server{..} client@Client{..} = do 156 | msg <- atomically $ readTChan clientChan 157 | case msg of 158 | GameQuery -> do 159 | gameLis <- atomically $ getGameList server 160 | sendGameQueryAnswer clientHandle gameLis 161 | mainLoop server client 162 | GameInit{..} -> do 163 | -- | check if name not taken, return game if successful 164 | maybeGame <- atomically $ checkAddGame server clientName msg 165 | maybe 166 | -- | send Error and return to mainLoop if failed 167 | (sendError clientHandle "Failed adding game." 168 | >> mainLoop server client) 169 | -- | Add game to client, client to game and go to gameLoop 170 | (\ Game{..} -> 171 | atomically (joinGame server clientName gameName True) 172 | >> sendMessage clientHandle "Added game." 173 | >> gameLoop server client gameInitName) maybeGame 174 | GameJoin{..} -> do 175 | gameLis <- readTVarIO games 176 | case member gameId gameLis of 177 | True 178 | | Game{..} <- gameLis!gameId 179 | , Map.size gamePlayers < numPlayers -> do 180 | atomically $ joinGame server clientName gameId False 181 | sendMessage clientHandle "Joined Game." 182 | gameLoop server client gameName 183 | | otherwise -> do 184 | sendError clientHandle "Game is full." 185 | mainLoop server client 186 | _ -> do 187 | sendError clientHandle "Game does not exist." 188 | mainLoop server client 189 | Logout -> 190 | sendMessage clientHandle "You have been logged out." 191 | _ -> do 192 | sendError clientHandle "Unknown Message." 193 | mainLoop server client 194 | 195 | -- | Gamestate loop 196 | gameLoop :: Server -> Client -> GameName -> IO () 197 | gameLoop server@Server{..} client@Client{..} game= do 198 | msg <- atomically $ readTChan clientChan 199 | gameLis <- readTVarIO games 200 | let isHost = clientName == gameHost (gameLis!game) 201 | thisPlayers = gamePlayers $ gameLis!game 202 | case msg of 203 | ChatFromClient{..} -> do 204 | broadcastGame server game 205 | $ ChatFromThread clientName chatFromCContent 206 | gameLoop server client game 207 | ChatFromThread{..} -> do 208 | sendEncoded clientHandle 209 | $ ChatOut chatFromTOrign chatFromTContent 210 | gameLoop server client game 211 | GameStart 212 | | isHost && L.all parReady thisPlayers -> do 213 | clientLis <- readTVarIO clients 214 | broadcastGame server game GameStartedByHost 215 | sendEncoded clientHandle 216 | $ GameStartAnswer $ convMap clientLis (keys thisPlayers) 217 | gameLoop server client game 218 | | isHost -> do 219 | sendError clientHandle "Players not ready." 220 | gameLoop server client game 221 | | otherwise -> do 222 | sendError clientHandle "Only the host can start the game." 223 | gameLoop server client game 224 | GameInfo -> do 225 | sendEncoded clientHandle $ GameInfoAnswer (gameLis!game) 226 | gameLoop server client game 227 | GameConfig{..} 228 | | isHost && 229 | gameConfPlayerNum >= (Map.size . gamePlayers) (gameLis!game)-> do 230 | atomically $ do 231 | gamesMap <- readTVar games 232 | writeTVar games 233 | $ Map.adjust (updateGame gameConfMap gameConfMode 234 | gameConfPlayerNum) game gamesMap 235 | gameLoop server client game 236 | | isHost -> do 237 | sendError clientHandle "Can't choose less Players." 238 | gameLoop server client game 239 | | otherwise -> do 240 | sendError clientHandle "Unknown Message." 241 | inGameLoop server client game 242 | GameClosedByHost -> do 243 | atomically $ leaveGame server clientName game 244 | sendMessage clientHandle "Game was closed by Host." 245 | mainLoop server client 246 | GameLeave -> do 247 | gameLeaveHandler server client game 248 | gameLoop server client game 249 | GameStartedByHost -> do 250 | sendMessage clientHandle "Game started..." 251 | inGameLoop server client game 252 | PlayerConfig{..} -> do 253 | atomically $ do 254 | gamesMap <- readTVar games 255 | writeTVar games 256 | $ Map.adjust (updatePlayer clientName playerCiv playerTeam 257 | playerReady) game gamesMap 258 | gameLoop server client game 259 | Logout -> 260 | sendMessage clientHandle "You have been logged out." 261 | _ -> do 262 | sendError clientHandle "Unknown Message." 263 | gameLoop server client game 264 | 265 | -- | Loop for Host in running Game 266 | inGameLoop :: Server -> Client -> GameName -> IO () 267 | inGameLoop server@Server{..} client@Client{..} game = do 268 | msg <- atomically $ readTChan clientChan 269 | gameLis <- readTVarIO games 270 | let isHost = clientName == gameHost (gameLis!game) 271 | case msg of 272 | Broadcast{..} -> do 273 | sendMessage clientHandle content 274 | inGameLoop server client game 275 | ChatFromClient{..} -> do 276 | broadcastGame server game 277 | $ ChatFromThread clientName chatFromCContent 278 | inGameLoop server client game 279 | ChatFromThread{..} -> do 280 | sendEncoded clientHandle 281 | $ ChatOut chatFromTOrign chatFromTContent 282 | inGameLoop server client game 283 | GameClosedByHost -> do 284 | atomically $ leaveGame server clientName game 285 | sendMessage clientHandle "Game was closed by Host." 286 | mainLoop server client 287 | GameLeave -> do 288 | gameLeaveHandler server client game 289 | gameLoop server client game 290 | GameOver 291 | | isHost -> do 292 | broadcastGame server game $ Broadcast "Game Over." 293 | gameLeaveHandler server client game 294 | inGameLoop server client game 295 | | otherwise -> do 296 | sendError clientHandle "Unknown Message." 297 | inGameLoop server client game 298 | Logout -> 299 | sendMessage clientHandle "You have been logged out." 300 | _ -> do 301 | sendError clientHandle "Unknown Message." 302 | inGameLoop server client game 303 | 304 | -------------------------------------------------------------------------------- /stack.yaml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by stack init 2 | # For more information, see: http://docs.haskellstack.org/en/stable/yaml_configuration.html 3 | 4 | # Specifies the GHC version and set of packages available (e.g., lts-3.5, nightly-2015-09-21, ghc-7.10.2) 5 | resolver: lts-16.13 6 | 7 | # Local packages, usually specified by relative directory name 8 | packages: 9 | - '.' 10 | # Packages to be pulled from upstream that are not in the resolver (e.g., acme-missiles-0.3) 11 | extra-deps: [] 12 | 13 | # Override default flag values for local packages and extra-deps 14 | flags: {} 15 | 16 | # Extra package databases containing global packages 17 | extra-package-dbs: [] 18 | 19 | # Control whether we use the GHC we find on the path 20 | # system-ghc: true 21 | 22 | # Require a specific version of stack, using version ranges 23 | # require-stack-version: -any # Default 24 | # require-stack-version: >= 1.0.0 25 | 26 | # Override the architecture used by stack, especially useful on Windows 27 | # arch: i386 28 | # arch: x86_64 29 | 30 | # Extra directories used by stack for building 31 | # extra-include-dirs: [/path/to/dir] 32 | # extra-lib-dirs: [/path/to/dir] 33 | 34 | # Allow a newer minor version of GHC than the snapshot specifies 35 | # compiler-check: newer-minor 36 | -------------------------------------------------------------------------------- /stack.yaml.lock: -------------------------------------------------------------------------------- 1 | # This file was autogenerated by Stack. 2 | # You should not edit this file by hand. 3 | # For more information, please see the documentation at: 4 | # https://docs.haskellstack.org/en/stable/lock_files 5 | 6 | packages: [] 7 | snapshots: 8 | - completed: 9 | size: 532381 10 | url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/16/13.yaml 11 | sha256: 6ee17f7996e5bc75ae4406250841f1362ad4196418a4d90a0615ff4f26ac98df 12 | original: lts-16.13 13 | -------------------------------------------------------------------------------- /test/TestCli.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedStrings #-} 2 | {-# LANGUAGE RecordWildCards #-} 3 | {-# LANGUAGE TypeApplications #-} 4 | ------------------------------------------------------------------------------ 5 | -- | 6 | -- Copyright 2016-2016 the openage authors. See copying.md for legal info. 7 | -- 8 | -- Main entry file for a test-client 9 | -- this client takes a host and a port as argument 10 | -- and can send Messages defined in Protocol to the server 11 | 12 | ------------------------------------------------------------------------------ 13 | module Main where 14 | 15 | import Data.Key 16 | import Control.Concurrent.Async 17 | import System.Environment 18 | import Text.Printf 19 | import Data.Version 20 | import Data.Aeson 21 | import Data.Map as Map 22 | import Data.ByteString.Lazy as BL 23 | import Data.ByteString.Char8 as B 24 | import System.IO 25 | import Data.Text as TE 26 | import Data.Text.IO as T 27 | import Network.Socket 28 | 29 | import Masterserver.Server 30 | import Masterserver.Protocol as P 31 | 32 | type Continue = Bool 33 | 34 | main :: IO () 35 | main = withSocketsDo $ do 36 | args <- getArgs 37 | printInit 38 | case args of 39 | [host, port] -> do 40 | let hints = defaultHints { addrSocketType = Stream } 41 | addr:_ <- getAddrInfo (Just hints) (Just host) (Just port) 42 | sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr) 43 | connect sock (addrAddress addr) 44 | printf "Connected\n" 45 | handle <- socketToHandle sock ReadWriteMode 46 | hSetBuffering handle NoBuffering 47 | handleVersion handle 48 | getSendCredentials handle 49 | mainLoop handle 50 | _ -> do 51 | printf "Please provide host and port" 52 | return () 53 | 54 | handleVersion :: Handle -> IO () 55 | handleVersion handle = do 56 | let myVer = makeVersion [1,0,0] 57 | printf "Sending version: %s\n" $ showVersion myVer 58 | sendEncoded handle $ VersionMessage myVer 59 | handleAnswer handle 60 | 61 | getSendCredentials :: Handle -> IO () 62 | getSendCredentials handle = do 63 | input <- T.getLine 64 | case TE.words input of 65 | ["addplayer",name,pass] -> do 66 | sendEncoded handle $ AddPlayer name pass 67 | handleAnswer handle 68 | getSendCredentials handle 69 | ["login" ,name ,pass] -> do 70 | sendEncoded handle $ Login name pass 71 | handleAnswer handle 72 | ["help"] -> do 73 | printCommands 74 | getSendCredentials handle 75 | _ -> do 76 | printf "Command not found.\n" 77 | getSendCredentials handle 78 | 79 | handleAnswer :: Handle -> IO () 80 | handleAnswer handle = do 81 | logAns <- B.hGetLine handle 82 | case (decode . BL.fromStrict) logAns of 83 | Just P.Message{..} -> printf "Message: %s\n" messageString 84 | Just P.Error{..} -> printf "Error: %s\n" errorString 85 | Just GameInfoAnswer{..} -> printFormattedGame game 86 | Just GameQueryAnswer{..} -> printFormattedGames gameList 87 | Just GameStartAnswer{..} -> printFormattedGameStart playerMap 88 | Just ChatOut{..} -> 89 | printf "%s: %s\n" chatOutOrigin chatOutContent 90 | _ -> printf "Error: Decoding error." 91 | 92 | mainLoop :: Handle -> IO () 93 | mainLoop handle = do 94 | ans <- async $ handleAnswer handle 95 | inp <- async $ handleLobbyInput handle 96 | -- Weird behavior, seems like it stuck (deadlocking?) when using 97 | -- waitEitherCancel or the equivalent 'race' function. 98 | result <- waitEither ans inp 99 | case result of 100 | Right True -> 101 | printf "Exit requested, proceeding...\n" 102 | _ -> 103 | mainLoop handle 104 | 105 | handleLobbyInput :: Handle -> IO Continue 106 | handleLobbyInput handle = go =<< TE.words <$> T.getLine 107 | where 108 | go ["exit"] = 109 | pure True 110 | go command = do 111 | handleGeneric command 112 | pure False 113 | 114 | handleGeneric ("chat":content) = 115 | sendEncoded handle $ ChatFromClient $ TE.unwords content 116 | handleGeneric ["playerconfig", civ, team, rdy] = 117 | sendEncoded handle (PlayerConfig civ ((read . TE.unpack) team) 118 | ((read . TE.unpack) rdy)) 119 | handleGeneric ["gameconfig", gMap, mode, num] = 120 | sendEncoded handle (GameConfig gMap mode ((read . TE.unpack) num)) 121 | handleGeneric ["gameover"] = sendEncoded handle GameOver 122 | handleGeneric ["join", name] = sendEncoded handle $ GameJoin name 123 | handleGeneric ["info"] = sendEncoded handle GameInfo 124 | handleGeneric ["init", name, gameMap, players] = 125 | sendGameInit handle name gameMap $ (read. TE.unpack) players 126 | handleGeneric ["query"] = sendGameQuery handle 127 | handleGeneric ["leave"] = sendEncoded handle GameLeave 128 | handleGeneric ["start"] = sendEncoded handle GameStart 129 | handleGeneric ["help"] = printCommands 130 | handleGeneric _ = printf "Command not found.\n" 131 | 132 | printInit :: IO () 133 | printInit = do 134 | printf "---------------------------------------------------------\n" 135 | printf "- openage masterserver Testclient\n" 136 | printf "- Type \"help\" for more information and \"exit\" to exit the client\n" 137 | printf "---------------------------------------------------------\n" 138 | 139 | printCommands :: IO () 140 | printCommands = do 141 | printf "Available Commands: \n" 142 | printf "Login:\n" 143 | printf "\taddplayer NAME PASS - add player to server\n" 144 | printf "\tlogin NAME PASS - Login to server\n" 145 | printf "Lobby:\n" 146 | printf "\tquery - Show existing games\n" 147 | printf "\tinit NAME MAP NUMBERPLAYERS - Add new Game \n" 148 | printf "\tjoin NAME - join Gamelobby \n" 149 | printf "Gamelobby:\n" 150 | printf "\tinfo - show info about current game \n" 151 | printf "\tleave - leave Game, close if Host \n" 152 | printf "\tstart - Only Host: start the game, all Players need to be ready.\n" 153 | printf "\tplayerConfig Text:CIV Int:TEAM Bool:READY-\ 154 | \ change Players settings.\n" 155 | printf "Ingame:\n" 156 | printf "\tleave - leave Game, close if Host \n" 157 | printf "\tgameover - Only Host: send gameover, terminates game.\n" 158 | printf "General:\n" 159 | printf "\texit - Close testclient \n" 160 | 161 | printFormattedGameStart :: Map.Map AuthPlayerName HostName -> IO () 162 | printFormattedGameStart pMap = do 163 | printf "Gameinfo to start p2p:\n" 164 | mapWithKeyM_ (printf "\t%s: %s\n") pMap 165 | 166 | printFormattedGame :: Game -> IO () 167 | printFormattedGame Game{..} = do 168 | printf "Name: %s\n" gameName 169 | printf "Map: %s\n" gameMap 170 | printf "MaxPlayers: %d\n" numPlayers 171 | printf "Gamehost: %s\n" gameHost 172 | printf "Team:\tName:\tCivilization:\tReady:\n" 173 | mapM_ printFormattedPart gamePlayers 174 | 175 | printFormattedPart :: Participant -> IO () 176 | printFormattedPart Participant{..} = 177 | printf "%d\t%s\t%s\t\t%s\n" parTeam parName parCiv $ show parReady 178 | 179 | printFormattedGames :: [Game] -> IO () 180 | printFormattedGames games = do 181 | printf "Title\tMap\tPlayers\tHost\n" 182 | mapM_ printGame games 183 | where 184 | printGame Game{..} = 185 | printf "%s\t%s\t%d\t%s\n" gameName gameMap numPlayers gameHost 186 | 187 | sendGameQuery :: Handle -> IO () 188 | sendGameQuery handle = 189 | sendEncoded handle GameQuery 190 | 191 | sendGameInit :: Handle -> GameName -> Text -> Int -> IO () 192 | sendGameInit handle name gameMap players = 193 | sendEncoded handle $ GameInit name gameMap players 194 | --------------------------------------------------------------------------------