├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE ├── README.md ├── config ├── db_config.toml └── login_server_config.toml ├── crypt ├── Cargo.toml └── src │ ├── aes.rs │ ├── constants.rs │ ├── lib.rs │ ├── login.rs │ └── maple_crypt.rs ├── db ├── .env ├── Cargo.toml ├── migrations │ ├── .gitkeep │ ├── 00000000000000_diesel_initial_setup │ │ ├── down.sql │ │ └── up.sql │ ├── 2020-08-16-181134_create_accounts │ │ ├── down.sql │ │ └── up.sql │ ├── 2020-08-19-201848_create_characters │ │ ├── down.sql │ │ └── up.sql │ ├── 2020-09-01-153708_create_sessions │ │ ├── down.sql │ │ └── up.sql │ ├── 2020-09-02-163632_create_keybindings │ │ ├── down.sql │ │ └── up.sql │ └── 2020-09-12-213326_add_map_to_character │ │ ├── down.sql │ │ └── up.sql └── src │ ├── account │ ├── mod.rs │ └── repository.rs │ ├── character │ ├── mod.rs │ └── repository.rs │ ├── keybinding │ ├── mod.rs │ └── repository.rs │ ├── lib.rs │ ├── schema.rs │ ├── session │ ├── mod.rs │ └── repository.rs │ ├── settings.rs │ └── sql_types.rs ├── diesel.toml ├── docker-compose.yaml ├── img ├── handshake_start.png ├── login.png ├── run.png ├── run_client.png └── sp_ship.png ├── net ├── Cargo.toml └── src │ ├── helpers.rs │ ├── io │ ├── accept.rs │ ├── client.rs │ ├── error.rs │ ├── listener.rs │ └── mod.rs │ ├── lib.rs │ ├── packet │ ├── build │ │ ├── handshake.rs │ │ ├── login │ │ │ ├── char.rs │ │ │ ├── mod.rs │ │ │ ├── status.rs │ │ │ └── world.rs │ │ ├── mod.rs │ │ └── world │ │ │ ├── char.rs │ │ │ ├── keymap.rs │ │ │ ├── map.rs │ │ │ └── mod.rs │ ├── handle │ │ ├── login │ │ │ ├── char │ │ │ │ ├── char_list.rs │ │ │ │ ├── check_name.rs │ │ │ │ ├── create.rs │ │ │ │ ├── delete.rs │ │ │ │ ├── mod.rs │ │ │ │ └── select.rs │ │ │ ├── main │ │ │ │ ├── accept_tos.rs │ │ │ │ ├── guest_login.rs │ │ │ │ ├── login.rs │ │ │ │ ├── login_start.rs │ │ │ │ ├── mod.rs │ │ │ │ └── set_gender.rs │ │ │ ├── mod.rs │ │ │ └── world │ │ │ │ ├── mod.rs │ │ │ │ ├── server_status.rs │ │ │ │ └── world_list.rs │ │ ├── mod.rs │ │ └── world │ │ │ ├── change_map.rs │ │ │ ├── chat.rs │ │ │ ├── keybinds.rs │ │ │ ├── logged_in.rs │ │ │ ├── map_transfer.rs │ │ │ ├── mod.rs │ │ │ ├── move_player.rs │ │ │ └── party_search.rs │ ├── mod.rs │ └── op │ │ ├── mod.rs │ │ ├── recv.rs │ │ └── send.rs │ └── settings.rs ├── packet ├── Cargo.toml └── src │ ├── io.rs │ ├── io │ ├── read.rs │ └── write.rs │ ├── lib.rs │ ├── model.rs │ └── model │ └── packet.rs └── rust-ms ├── Cargo.toml └── src └── bin ├── login.rs └── world.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Cargo compilation/executables 2 | debug/ 3 | target/ 4 | 5 | # Keep this only for binaries 6 | Cargo.lock 7 | 8 | # Rust backup files 9 | **/*.rs.bk 10 | 11 | # VSCode files 12 | *.code-workspace 13 | */.vscode 14 | 15 | # Vim files 16 | .vim 17 | *.vim 18 | 19 | .env 20 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | jobs: 7 | allow_failures: 8 | - rust: nightly 9 | fast_finish: true 10 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | 3 | members = [ 4 | "rust-ms", 5 | "packet", 6 | "crypt", 7 | "net", 8 | "db" 9 | ] 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RustMS 🍁 2 | 3 | RustMS is an attempt at implementing the Maplestory server end from scratch in Rust. 4 | 5 | It's very work-in-progress and really only barely off the ground at this point, but it's been a fun evening/weekend side project so far! 6 | 7 | ![Getting places](img/sp_ship.png) 8 | ## Motivation 9 | The motivation behind this project is two-fold: 10 | 11 | When I started this project, I knew next to no Rust, however I was quite interested in learning it due to a general interest that I've always had in lower level languages. I've previously learned a bit of C, however I've only really used it in an academic setting (as well as to make this relatively bland [shell](https://github.com/neeerp/myShell) I made for fun). I thought Rust sounded interesting so I decided to start a fun project as a means of learning it. I'd also been trying to learn Vim for a while and thought caging myself in with it for this project (initially via the VS Code plugin and later neovim alone) would be fun. 12 | 13 | The second motivation behind this project comes from the fact that Maplestory has a special place in my heart as the game that probably defined my childhood. I knew people had written and ran their own servers before but for the longest time it hadn't hit me that a lot of these servers had their source up on Github. Having looked at a few servers such as [HeavenMS](https://github.com/ronancpl/HeavenMS) and [Valhalla](https://github.com/Hucaru/Valhalla), I realized that I could probably try my hand at writing my own server too and that I could probably have quite a bit of fun with it. 14 | 15 | ## Overview 16 | As of 23/08/2020, RustMS is still in a very early stage. 17 | 18 | ** Currently on hold while school's been very unforgiving; have plans for what to do next here that I will hopefully write down soon though! ** 19 | 20 | ### Crates 21 | The `crypt` crate provides the means for encrypting and decrypting packets using 22 | Maplestory's custom AES algorithm as well as its secondary encryption algorithm 23 | that's applied prior to AES. In particular, this library defines the `MapleAES` 24 | object that is used to encrypt/decrypt and keep track of the encryption nonce for 25 | a unidirectional stream of communication between the client and server. There is 26 | also a module here that provides an interface for encrypting and decrypting 27 | account passwords with bcrypt. 28 | 29 | The `packet` crate provides a simple wrapper for our network packets, as well as an 30 | extension of the `Read` and `Write` IO traits that allow us to read and write various 31 | data types to our packets, including little endian integers of different sizes and 32 | length-headered strings. 33 | 34 | The `db` crate provides connections to RustMS' PostgreSQL database, a representation 35 | of the database's schema, models and projections of the database entities, and 36 | the entities' respective data repositories. The models and data repositories live in 37 | domain specific modules, so, for instance, everything pertaining to user accounts 38 | can be found under the `account` module. The ORM we're using for RustMS is `diesel`. 39 | 40 | The `net` crate is currently the largest crate and consists of two primary modules: 41 | `io` and `packet`. The `io` module has methods and models that define our current 42 | server infrastructure. Things like the entry point to a connection's main IO loop, 43 | as well as the methods and models for reading, decrypting, delegating, and sending 44 | packets are defined here. We also model the client connection and its state here. 45 | The `packet` module defines our packet handlers and builders for dealing with incoming 46 | packets from the client and building responses. There are two major submodules here, 47 | `build` and `handle` that perform the aforementioned duties. Currently, most of our 48 | server's actual logic resides here, however ideally we'd like to create a separate 49 | module (or perhaps add to the `db` crate's domain modules) to keep things organized and 50 | DRY... 51 | 52 | The current entry point of the project is the `rust-ms-login` crate. It listens for 53 | incoming connections on `localhost:8484` and delegates these connections to threads 54 | that instantiate a `Session` (performing an AES handshake in the process) and listen for 55 | IO until some kind of `NetworkError` (defined in the `net` crate) is returned and the 56 | client connection is closed. 57 | 58 | ### Functionality 59 | Currently, RustMS consists solely of a reasonably functional Login Server. 60 | 61 | #### Encryption 62 | Once a new client initiates a connection, the server responds with a handshake to 63 | exchange AES initialization vectors as well as some metadata about the server such 64 | as the client version that it expects. Any subsequent communication between the 65 | client and the server is encrypted with Maplestory's custom encryption (for lack of 66 | a better name) followed by Maplestory's custom AES encryption. Send and Receive data 67 | is encrypted using separate nonces (i.e. the initialization vectors and their 68 | subsequent mutations) that are both kept in sync between the client and server. 69 | 70 | #### Account Creation/Login 71 | Currently, one can create an account by attempting to log into an account that 72 | does not yet exist. The provided password is encrypted and the user/encrypted pw 73 | combination is saved in the database. The first login will prompt the user to 74 | accept a TOS as well as select their gender before forwarding them to the world 75 | select... these two features are currently hardcoded to trigger however in the 76 | future they'll be controlled by a configuration property. 77 | 78 | Existing accounts can be logged into as expected, and a successful login will 79 | forward you to the world select screen as expected. 80 | 81 | Currently, the account PIN prompt is bypassed and PINs are not yet supported. In 82 | the future we'll implement this too (likely whenever we establish our architecture 83 | for handling multiple servers and moving sessions between them... this will likely 84 | require changes in how the client session is modeled, which will have a direct impact 85 | on pin logins). We'll be putting this behind a configuration property as well. 86 | 87 | #### World Select 88 | Currently, one may select a world from the world selection screen once they are 89 | logged in... Currently, there is only one world with one channel (though 3 appear 90 | in the world select, the port of the one world with its one channel is hardcoded). 91 | 92 | #### Character Selection/Creation/Deletion 93 | Currently, character creation is supported to an extent. One may create persistent, 94 | account linked characters that may be viewed on the character selection screen. 95 | These characters inherit some of the features that are selected during character 96 | creation such as gender, hair, and skin color, however equipment is ignored since 97 | this would require us to establish our model for character inventories as well as 98 | character equiped items. This will most likely happen after we actually get a 99 | functioning game server. 100 | 101 | Created characters also enforce uniqueness in their names, hence the check done 102 | at the end of the character creation flow is actually working. Currently this check 103 | is case sensitive, and that'll likely need to be fixed some time in the future. 104 | 105 | Character deletion works and is instantaneous, so be careful (not as though your 106 | characters really matter at this stage of development anyway though). 107 | 108 | PICs are currently disabled and will be implemented alongside PINs as mentioned 109 | previously. They too will be toggleable via configuration. 110 | 111 | #### Game World 112 | Currently, one is able to log into the game world with their selected character. 113 | At this point, the client is rerouted to the world server (one of the two binaries 114 | built) and loads in with the selected character. 115 | 116 | There's not really a whole lot to do in game currently, as very little is actually 117 | implemented, however you can still walk around! 118 | 119 | ##### Maps 120 | New characters initially spawn in the town of Amherst. From here, one may walk 121 | around and enter portals to adjacent maps. If the player logs out, they will reappear 122 | in the map they logged out from. 123 | 124 | Note that currently, the default spawn point is selected for a given map, hence 125 | the portal the player came out from probably won't line up with where the character 126 | actually appears once they've loaded the map. This'll likely get addressed when 127 | we develop a more concrete model for dealing with maps on the server side. 128 | 129 | ##### Keybinds 130 | One may re-assign their keybinds as they normally would with the client. The selected 131 | keybinds actually get saved and will be available if the player logs out and back 132 | in later. 133 | 134 | 135 | #### Database 136 | RustMS is currently being backed by a standalone PostgreSQL server that can be seamlessly 137 | set up using the `docker-compose` file in the root of the project. The database's schema 138 | can be generated by running the `diesel` (our ORM of choice) migrations in the `db` crate. 139 | 140 | ## Demonstration 141 | *This demonstration is out-dated and needs to be updated! For now, see the above 142 | overview for an idea of the implemented features!* 143 | 144 | ### Running the server 145 | If you would like to run RustMS, clone the repository and run the project from the root with `cargo run` (make sure you have Rust and Cargo installed). You should see something akin to the following: 146 | 147 | ![Run the server](img/run.png) 148 | 149 | On the first run of the server, you will likely have more output as dependencies will need to be downloaded and the project itself will build. 150 | 151 | ### Running the client 152 | The server on its own is not particularly interesting without a client to communicate with it. At this point in time, this server is being developed with the [Heaven Client](https://github.com/HeavenClient/HeavenClient) in mind, however in theory any V83 Maplestory client that's pointed at `localhost` should work (no promises). Clone HeavenClient and follow the README's instructions on the branch corresponding to your operating system. Note that RustMS supports encryption and hence you shouldn't disable it when building the client. 153 | 154 | Once you've built the client, run it: 155 | ![Run the client](img/run_client.png) 156 | 157 | In the server's console, you should see that the handshake completed successfully and the Login Start packet was received. 158 | ![Handshake Success](img/handshake_start.png) 159 | 160 | ### Logging in 161 | At the time of writing this, you can type in a username and password in the client's login window and submit. The server will parse the packet and echo it in the console. 162 | ![Credentials Echoed](img/login.png) 163 | 164 | 165 | ## Roadmap 166 | - [X] Develop a library for encrypting and decrypting packets in the form that the client expects 167 | - [X] Develop a model for packets and packet IO 168 | - [X] Develop basic infrastructure for sending and receiving packets to/from the client 169 | - [X] Hook up a containerized database 170 | - [X] Implement proper login and account creation flow 171 | - [X] Implement character creation 172 | - [X] Implement a parallel World Server 173 | - [X] Login Sessions to transfer from Login to World Server 174 | - [X] Save character keybinds from in game 175 | - [X] In game portals to move between maps handled 176 | - [ ] Revise and update roadmap (in progress) 177 | -------------------------------------------------------------------------------- /config/db_config.toml: -------------------------------------------------------------------------------- 1 | [database] 2 | url = "postgres://maplestory:pass@localhost:5432/maplestory" 3 | -------------------------------------------------------------------------------- /config/login_server_config.toml: -------------------------------------------------------------------------------- 1 | [login] 2 | pin_required = false 3 | gender_required = true 4 | -------------------------------------------------------------------------------- /crypt/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crypt" 3 | version = "0.1.0" 4 | authors = ["David Goldstein "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | aes = "0.4.0" 11 | hex-literal = "0.3.0" 12 | rand = "0.7.3" 13 | byteorder = "1.3.4" 14 | bcrypt = "0.8.2" 15 | -------------------------------------------------------------------------------- /crypt/src/aes.rs: -------------------------------------------------------------------------------- 1 | use aes::block_cipher::generic_array::GenericArray; 2 | use aes::block_cipher::{BlockCipher, NewBlockCipher}; 3 | use aes::Aes256; 4 | 5 | use crate::constants; 6 | 7 | pub struct MapleAES { 8 | iv: Vec, 9 | maple_version: i16, 10 | } 11 | 12 | impl MapleAES { 13 | /// Instantiate a new Maple AES Cipher 14 | pub fn new(iv: &Vec, maple_version: i16) -> MapleAES { 15 | let maple_version: i16 = 16 | ((maple_version >> 8) & 0xFF) | ((((maple_version as u32) << 8) & 0xFF00) as i16); 17 | 18 | let iv = iv.clone(); 19 | 20 | MapleAES { iv, maple_version } 21 | } 22 | 23 | /// Encrypt data using Maplestory's custom AES encryption 24 | pub fn crypt(&mut self, data: &mut [u8]) { 25 | let mut remaining = data.len(); 26 | let mut llength = 0x5B0; 27 | let mut start = 0; 28 | 29 | let mut key = self.get_trimmed_user_key(); 30 | let key = GenericArray::from_mut_slice(&mut key); 31 | let cipher = Aes256::new(&key); 32 | 33 | while remaining > 0 { 34 | let mut iv = self.repeat_bytes(&self.iv, 4); 35 | let mut iv = GenericArray::from_mut_slice(&mut iv); 36 | 37 | if remaining < llength { 38 | llength = remaining; 39 | } 40 | for i in start..(start + llength) { 41 | if (i - start) % iv.len() == 0 { 42 | cipher.encrypt_block(&mut iv); 43 | } 44 | data[i] ^= iv[(i - start) % iv.len()]; 45 | } 46 | start += llength; 47 | remaining -= llength; 48 | llength = 0x5B4; 49 | } 50 | 51 | self.update_iv(); 52 | } 53 | 54 | /// Check if header is for a valid maplestory packet 55 | pub fn check_header(&self, packet: &[u8]) -> bool { 56 | ((packet[0] ^ self.iv[2]) & 0xFF) == ((self.maple_version >> 8) as u8 & 0xFF) 57 | && ((packet[1] ^ self.iv[3]) & 0xFF) == (self.maple_version & 0xFF) as u8 58 | } 59 | 60 | /// Check if header is for a valid maplestory packet, taking the header as a u32 61 | pub fn check_header_u32(&self, packet_header: u32) -> bool { 62 | let header_buf: Vec = vec![ 63 | (packet_header >> 24) as u8 & 0xFF, 64 | (packet_header >> 16) as u8 & 0xFF, 65 | ]; 66 | self.check_header(&header_buf) 67 | } 68 | 69 | /// Generate a packet header for a packet of a given length using the 70 | /// stored Maplestory version and nonce. 71 | pub fn gen_packet_header(&self, length: i16) -> Vec { 72 | let mut iiv: u32 = self.iv[3] as u32 & 0xFF; 73 | iiv |= ((self.iv[2] as u32) << 8) & 0xFF00; 74 | iiv ^= self.maple_version as u32; 75 | let mlength = (((length as u32) << 8) & 0xFF00) | ((length as u32) >> 8); 76 | let xored_iv = iiv ^ mlength; 77 | 78 | vec![ 79 | (iiv >> 8) as u8 & 0xFF, 80 | iiv as u8 & 0xFF, 81 | (xored_iv >> 8) as u8 & 0xFF, 82 | xored_iv as u8 & 0xFF, 83 | ] 84 | } 85 | 86 | /// Get packet length from header 87 | pub fn get_packet_length(&self, header: &[u8]) -> i16 { 88 | if header.len() < 4 { 89 | return -1; 90 | } 91 | 92 | (header[0] as i16 + ((header[1] as i16) << 8)) 93 | ^ (header[2] as i16 + ((header[3] as i16) << 8)) 94 | } 95 | 96 | // Get packet length from header, treating header as a u32 97 | pub fn get_packet_length_from_u32(&self, packet_header: u32) -> i32 { 98 | let mut packet_length = (packet_header >> 16) ^ (packet_header & 0xFFFF); 99 | packet_length = ((packet_length << 8) & 0xFF00) | ((packet_length >> 8) & 0xFF); 100 | 101 | packet_length as i32 102 | } 103 | 104 | fn get_trimmed_user_key(&self) -> [u8; 32] { 105 | let mut key = [0u8; 32]; 106 | for i in (0..128).step_by(16) { 107 | key[i / 4] = constants::USER_KEY[i]; 108 | } 109 | key 110 | } 111 | 112 | fn update_iv(&mut self) { 113 | self.iv = self.get_new_iv(&self.iv); 114 | } 115 | 116 | /// Shuffle algorithm to generate a new Initialization Vector based off 117 | /// of the old one. Based directly off of HeavenClient's implementation. 118 | fn get_new_iv(&self, iv: &Vec) -> Vec { 119 | let mut new_iv: Vec = constants::DEFAULT_AES_KEY_VALUE.to_vec(); 120 | let shuffle_bytes = constants::SHUFFLE_BYTES; 121 | 122 | for i in 0..4 { 123 | let byte = iv[i]; 124 | new_iv[0] = new_iv[0] 125 | .wrapping_add(shuffle_bytes[(new_iv[1] & 0xFF) as usize].wrapping_sub(byte)); 126 | new_iv[1] = 127 | new_iv[1].wrapping_sub(new_iv[2] ^ shuffle_bytes[(byte & 0xFF) as usize] & 0xFF); 128 | new_iv[2] = new_iv[2] ^ (shuffle_bytes[(new_iv[3] & 0xFF) as usize].wrapping_add(byte)); 129 | new_iv[3] = new_iv[3].wrapping_add( 130 | (shuffle_bytes[(byte & 0xFF) as usize] & 0xFF).wrapping_sub(new_iv[0] & 0xFF), 131 | ); 132 | 133 | let mut mask = 0usize; 134 | mask |= (new_iv[0] as usize) & 0xFF; 135 | mask |= ((new_iv[1] as usize) << 8) & 0xFF00; 136 | mask |= ((new_iv[2] as usize) << 16) & 0xFF0000; 137 | mask |= ((new_iv[3] as usize) << 24) & 0xFF000000; 138 | mask = (mask >> 0x1D) | (mask << 3); 139 | 140 | for j in 0..4 { 141 | new_iv[j] = ((mask >> (8 * j)) & 0xFF) as u8; 142 | } 143 | } 144 | 145 | new_iv 146 | } 147 | 148 | /// Repeat the bytes in the given vector `mul` times. 149 | fn repeat_bytes(&self, input: &[u8], mul: usize) -> Vec { 150 | let mut result: Vec = Vec::new(); 151 | let iv_len = input.len(); 152 | 153 | for i in 0..(iv_len * mul) { 154 | result.push(input[(i % iv_len) as usize]); 155 | } 156 | 157 | result 158 | } 159 | } 160 | 161 | #[cfg(test)] 162 | mod tests { 163 | use byteorder::{BigEndian, ReadBytesExt}; 164 | use rand::{random, thread_rng, Rng}; 165 | 166 | #[test] 167 | fn test_aes_round_trip() { 168 | for _ in 0..25 { 169 | // Generate an IV 170 | let mut iv: Vec = Vec::new(); 171 | for _ in 0..4 { 172 | iv.push(random()); 173 | } 174 | 175 | // Create an encryption and decryption cipher instance 176 | let mut encrypt_cipher = super::MapleAES::new(&iv, 27); 177 | let mut decrypt_cipher = super::MapleAES::new(&iv, 27); 178 | 179 | let length: u16 = random(); 180 | 181 | let mut to_crypt: Vec = Vec::new(); 182 | let mut expected: Vec = Vec::new(); 183 | 184 | for _ in 0..length { 185 | let byte: u8 = random(); 186 | to_crypt.push(byte); 187 | expected.push(byte); 188 | } 189 | 190 | // Encrypt the bytes 191 | encrypt_cipher.crypt(to_crypt.as_mut_slice()); 192 | assert_ne!(to_crypt, expected); 193 | 194 | // Decrypt them and verify they match 195 | decrypt_cipher.crypt(to_crypt.as_mut_slice()); 196 | assert_eq!(to_crypt, expected); 197 | } 198 | } 199 | 200 | #[test] 201 | fn packet_header_round_trip() { 202 | let mut rng = thread_rng(); 203 | 204 | for _ in 0..100 { 205 | let mut iv: Vec = Vec::new(); 206 | for _ in 0..4 { 207 | iv.push(random()); 208 | } 209 | let cipher = super::MapleAES::new(&iv, 27); 210 | 211 | let initial_length: i16 = rng.gen_range(0, 16000); 212 | 213 | let header = cipher.gen_packet_header(initial_length); 214 | let header_int: u32 = header.as_slice().read_u32::().unwrap(); 215 | 216 | assert!(cipher.check_header_u32(header_int)); 217 | 218 | let length: i16 = cipher.get_packet_length(&header); 219 | assert_eq!(length, initial_length); 220 | } 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /crypt/src/constants.rs: -------------------------------------------------------------------------------- 1 | pub const USER_KEY: [u8; 128] = [ 2 | 0x13, 0x00, 0x00, 0x00, 0x52, 0x00, 0x00, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x5B, 0x00, 0x00, 0x00, 3 | 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 4 | 0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 5 | 0xB4, 0x00, 0x00, 0x00, 0x4B, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 6 | 0x1B, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x5F, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 7 | 0x0F, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 8 | 0x33, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 9 | 0x52, 0x00, 0x00, 0x00, 0xDE, 0x00, 0x00, 0x00, 0xC7, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 10 | ]; 11 | 12 | pub const SHUFFLE_BYTES: [u8; 256] = [ 13 | 0xEC, 0x3F, 0x77, 0xA4, 0x45, 0xD0, 0x71, 0xBF, 0xB7, 0x98, 0x20, 0xFC, 0x4B, 0xE9, 0xB3, 0xE1, 14 | 0x5C, 0x22, 0xF7, 0x0C, 0x44, 0x1B, 0x81, 0xBD, 0x63, 0x8D, 0xD4, 0xC3, 0xF2, 0x10, 0x19, 0xE0, 15 | 0xFB, 0xA1, 0x6E, 0x66, 0xEA, 0xAE, 0xD6, 0xCE, 0x06, 0x18, 0x4E, 0xEB, 0x78, 0x95, 0xDB, 0xBA, 16 | 0xB6, 0x42, 0x7A, 0x2A, 0x83, 0x0B, 0x54, 0x67, 0x6D, 0xE8, 0x65, 0xE7, 0x2F, 0x07, 0xF3, 0xAA, 17 | 0x27, 0x7B, 0x85, 0xB0, 0x26, 0xFD, 0x8B, 0xA9, 0xFA, 0xBE, 0xA8, 0xD7, 0xCB, 0xCC, 0x92, 0xDA, 18 | 0xF9, 0x93, 0x60, 0x2D, 0xDD, 0xD2, 0xA2, 0x9B, 0x39, 0x5F, 0x82, 0x21, 0x4C, 0x69, 0xF8, 0x31, 19 | 0x87, 0xEE, 0x8E, 0xAD, 0x8C, 0x6A, 0xBC, 0xB5, 0x6B, 0x59, 0x13, 0xF1, 0x04, 0x00, 0xF6, 0x5A, 20 | 0x35, 0x79, 0x48, 0x8F, 0x15, 0xCD, 0x97, 0x57, 0x12, 0x3E, 0x37, 0xFF, 0x9D, 0x4F, 0x51, 0xF5, 21 | 0xA3, 0x70, 0xBB, 0x14, 0x75, 0xC2, 0xB8, 0x72, 0xC0, 0xED, 0x7D, 0x68, 0xC9, 0x2E, 0x0D, 0x62, 22 | 0x46, 0x17, 0x11, 0x4D, 0x6C, 0xC4, 0x7E, 0x53, 0xC1, 0x25, 0xC7, 0x9A, 0x1C, 0x88, 0x58, 0x2C, 23 | 0x89, 0xDC, 0x02, 0x64, 0x40, 0x01, 0x5D, 0x38, 0xA5, 0xE2, 0xAF, 0x55, 0xD5, 0xEF, 0x1A, 0x7C, 24 | 0xA7, 0x5B, 0xA6, 0x6F, 0x86, 0x9F, 0x73, 0xE6, 0x0A, 0xDE, 0x2B, 0x99, 0x4A, 0x47, 0x9C, 0xDF, 25 | 0x09, 0x76, 0x9E, 0x30, 0x0E, 0xE4, 0xB2, 0x94, 0xA0, 0x3B, 0x34, 0x1D, 0x28, 0x0F, 0x36, 0xE3, 26 | 0x23, 0xB4, 0x03, 0xD8, 0x90, 0xC8, 0x3C, 0xFE, 0x5E, 0x32, 0x24, 0x50, 0x1F, 0x3A, 0x43, 0x8A, 27 | 0x96, 0x41, 0x74, 0xAC, 0x52, 0x33, 0xF0, 0xD9, 0x29, 0x80, 0xB1, 0x16, 0xD3, 0xAB, 0x91, 0xB9, 28 | 0x84, 0x7F, 0x61, 0x1E, 0xCF, 0xC5, 0xD1, 0x56, 0x3D, 0xCA, 0xF4, 0x05, 0xC6, 0xE5, 0x08, 0x49, 29 | ]; 30 | 31 | pub const DEFAULT_AES_KEY_VALUE: [u8; 4] = [0xF2, 0x53, 0x50, 0xC6]; 32 | -------------------------------------------------------------------------------- /crypt/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod login; 2 | pub mod maple_crypt; 3 | pub use crate::aes::MapleAES; 4 | 5 | mod aes; 6 | mod constants; 7 | 8 | pub use bcrypt::BcryptError; 9 | -------------------------------------------------------------------------------- /crypt/src/login.rs: -------------------------------------------------------------------------------- 1 | use bcrypt::{hash, verify, BcryptResult, DEFAULT_COST}; 2 | 3 | pub fn hash_password(pw: &str) -> BcryptResult { 4 | hash(pw, DEFAULT_COST) 5 | } 6 | 7 | pub fn validate_against_hash(plain: &str, hashed: &str) -> BcryptResult { 8 | verify(plain, hashed) 9 | } 10 | -------------------------------------------------------------------------------- /crypt/src/maple_crypt.rs: -------------------------------------------------------------------------------- 1 | /// Functions to encrypt and decrypt data using Maplestory's custom 2 | /// encryption algorithm. 3 | /// 4 | /// Encrypt bytes using Maplestory's custom encryption algorithm. 5 | pub fn encrypt(data: &mut [u8]) { 6 | let size: usize = data.len(); 7 | let mut c: u8; 8 | let mut a: u8; 9 | for _ in 0..3 { 10 | a = 0; 11 | for j in (1..(size + 1)).rev() { 12 | c = data[size - j]; 13 | c = rotl(c, 3); 14 | c = (c as usize).overflowing_add(j).0 as u8; 15 | c ^= a; 16 | a = c; 17 | c = rotr(a, j as u32); 18 | c ^= 0xFF; 19 | c = c.overflowing_add(0x48).0; 20 | data[size - j] = c; 21 | } 22 | a = 0; 23 | for j in (1..(size + 1)).rev() { 24 | c = data[j - 1]; 25 | c = rotl(c, 4); 26 | c = (c as usize).overflowing_add(j).0 as u8; 27 | c ^= a; 28 | a = c; 29 | c ^= 0x13; 30 | c = rotr(c, 3); 31 | data[j - 1] = c; 32 | } 33 | } 34 | } 35 | 36 | /// Decrypt bytes encrypted with Maplestory's custom encryption algorithm. 37 | pub fn decrypt(data: &mut [u8]) { 38 | let size: usize = data.len(); 39 | let mut a: u8; 40 | let mut b: u8; 41 | let mut c: u8; 42 | for _ in 0..3 { 43 | b = 0; 44 | for j in (1..(size + 1)).rev() { 45 | c = data[j - 1]; 46 | c = rotl(c, 3); 47 | c ^= 0x13; 48 | a = c; 49 | c ^= b; 50 | c = (c as usize).overflowing_sub(j).0 as u8; 51 | c = rotr(c, 4); 52 | b = a; 53 | data[j - 1] = c; 54 | } 55 | b = 0; 56 | for j in (1..(size + 1)).rev() { 57 | c = data[size - j]; 58 | c = c.overflowing_sub(0x48).0; 59 | c ^= 0xFF; 60 | c = rotl(c, j as u32); 61 | a = c; 62 | c ^= b; 63 | c = (c as usize).overflowing_sub(j).0 as u8; 64 | c = rotr(c, 3); 65 | b = a; 66 | data[size - j] = c; 67 | } 68 | } 69 | } 70 | 71 | /// Roll a byte left count times 72 | fn rotl(byte: u8, count: u32) -> u8 { 73 | let count = count % 8; 74 | if count > 0 { 75 | (byte << count) | (byte >> (8 - count)) 76 | } else { 77 | byte 78 | } 79 | } 80 | 81 | /// Roll a byte right count times 82 | fn rotr(byte: u8, count: u32) -> u8 { 83 | let count = count % 8; 84 | if count > 0 { 85 | (byte >> count) | (byte << (8 - count)) 86 | } else { 87 | byte 88 | } 89 | } 90 | 91 | #[cfg(test)] 92 | mod tests { 93 | use rand::{random, thread_rng, Rng}; 94 | 95 | #[test] 96 | fn test_rot_nop_on_max_and_zero() { 97 | let max: u8 = u8::MAX; 98 | let zero: u8 = 0; 99 | 100 | for i in 0..9 { 101 | assert_eq!(super::rotl(max, i), max); 102 | assert_eq!(super::rotr(max, i), max); 103 | assert_eq!(super::rotl(zero, i), zero); 104 | assert_eq!(super::rotr(zero, i), zero); 105 | } 106 | } 107 | 108 | #[test] 109 | fn test_rot_zero_nop() { 110 | for _ in 0..100 { 111 | let byte: u8 = random(); 112 | assert_eq!(super::rotl(byte, 0), byte); 113 | assert_eq!(super::rotr(byte, 0), byte); 114 | } 115 | } 116 | 117 | #[test] 118 | fn test_rot_eight_nop() { 119 | for _ in 0..100 { 120 | let byte: u8 = random(); 121 | assert_eq!(super::rotl(byte, 8), byte); 122 | assert_eq!(super::rotr(byte, 8), byte); 123 | } 124 | } 125 | 126 | #[test] 127 | fn test_rotl_rotr_equivalence() { 128 | for _ in 0..100 { 129 | let byte: u8 = random(); 130 | for i in 0..9 { 131 | assert_eq!(super::rotl(byte, i), super::rotr(byte, 8 - i)); 132 | } 133 | } 134 | } 135 | 136 | #[test] 137 | fn test_rotl_powers_of_two() { 138 | let num: u8 = 1; 139 | for i in 0..17 { 140 | assert_eq!(super::rotl(num, i), 2u8.pow(i % 8)) 141 | } 142 | } 143 | 144 | #[test] 145 | fn test_rotr_powers_of_two() { 146 | let num: u8 = 1; 147 | for i in 0..17 { 148 | assert_eq!(super::rotr(num, i), 2u8.pow((8 - (i % 8)) % 8)) 149 | } 150 | } 151 | 152 | #[test] 153 | fn test_encrypt_decrypt_original() { 154 | let mut rng = thread_rng(); 155 | for _ in 0..100 { 156 | let length = rng.gen_range(1, 255); 157 | let mut bytes: Vec = Vec::new(); 158 | let mut expected: Vec = Vec::new(); 159 | 160 | for _ in 0..length { 161 | let byte: u8 = random(); 162 | bytes.push(byte); 163 | expected.push(byte); 164 | } 165 | 166 | super::encrypt(&mut bytes); 167 | assert_ne!(expected, bytes); 168 | super::decrypt(&mut bytes); 169 | assert_eq!(expected, bytes); 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /db/.env: -------------------------------------------------------------------------------- 1 | DATABASE_URL=postgres://maplestory:pass@localhost:5432/maplestory 2 | -------------------------------------------------------------------------------- /db/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "db" 3 | version = "0.1.0" 4 | authors = ["David Goldstein "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | diesel = { version = "1.4.5", features = ["postgres", "network-address"] } 11 | diesel-derive-enum = { version = "1", features = ["postgres"] } 12 | config = "0.10.1" 13 | serde_derive = "^1.0.8" 14 | serde = "^1.0.8" 15 | ipnetwork = "0.16.0" 16 | eui48 = "1.1.0" 17 | itertools = "0.9.0" 18 | -------------------------------------------------------------------------------- /db/migrations/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/neeerp/RustMS/33083a7f6acee50572c2c042cafa5b0add60ae16/db/migrations/.gitkeep -------------------------------------------------------------------------------- /db/migrations/00000000000000_diesel_initial_setup/down.sql: -------------------------------------------------------------------------------- 1 | -- This file was automatically created by Diesel to setup helper functions 2 | -- and other internal bookkeeping. This file is safe to edit, any future 3 | -- changes will be added to existing projects as new migrations. 4 | 5 | DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); 6 | DROP FUNCTION IF EXISTS diesel_set_updated_at(); 7 | -------------------------------------------------------------------------------- /db/migrations/00000000000000_diesel_initial_setup/up.sql: -------------------------------------------------------------------------------- 1 | -- This file was automatically created by Diesel to setup helper functions 2 | -- and other internal bookkeeping. This file is safe to edit, any future 3 | -- changes will be added to existing projects as new migrations. 4 | 5 | 6 | 7 | 8 | -- Sets up a trigger for the given table to automatically set a column called 9 | -- `updated_at` whenever the row is modified (unless `updated_at` was included 10 | -- in the modified columns) 11 | -- 12 | -- # Example 13 | -- 14 | -- ```sql 15 | -- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); 16 | -- 17 | -- SELECT diesel_manage_updated_at('users'); 18 | -- ``` 19 | CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ 20 | BEGIN 21 | EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s 22 | FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); 23 | END; 24 | $$ LANGUAGE plpgsql; 25 | 26 | CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ 27 | BEGIN 28 | IF ( 29 | NEW IS DISTINCT FROM OLD AND 30 | NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at 31 | ) THEN 32 | NEW.updated_at := current_timestamp; 33 | END IF; 34 | RETURN NEW; 35 | END; 36 | $$ LANGUAGE plpgsql; 37 | -------------------------------------------------------------------------------- /db/migrations/2020-08-16-181134_create_accounts/down.sql: -------------------------------------------------------------------------------- 1 | -- This file should undo anything in `up.sql` 2 | DROP TABLE accounts; 3 | -------------------------------------------------------------------------------- /db/migrations/2020-08-16-181134_create_accounts/up.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE accounts ( 2 | id serial PRIMARY KEY, 3 | user_name varchar(13) NOT NULL, 4 | password varchar(128) NOT NULL, 5 | pin varchar(4) NOT NULL DEFAULT '', 6 | pic varchar(26) NOT NULL DEFAULT '', 7 | 8 | logged_in BOOLEAN NOT NULL DEFAULT FALSE, 9 | last_login_at timestamp NULL DEFAULT NULL, 10 | created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 11 | 12 | character_slots SMALLINT NOT NULL DEFAULT 3, 13 | 14 | gender SMALLINT NOT NULL DEFAULT 10, 15 | accepted_tos BOOLEAN NOT NULL DEFAULT FALSE, 16 | 17 | banned BOOLEAN NOT NULL DEFAULT FALSE, 18 | ban_msg text, 19 | 20 | CONSTRAINT user_is_unique UNIQUE (user_name) 21 | ); 22 | -------------------------------------------------------------------------------- /db/migrations/2020-08-19-201848_create_characters/down.sql: -------------------------------------------------------------------------------- 1 | -- This file should undo anything in `up.sql` 2 | DROP TABLE characters; 3 | -------------------------------------------------------------------------------- /db/migrations/2020-08-19-201848_create_characters/up.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE characters ( 2 | id serial PRIMARY KEY, 3 | accountid INTEGER NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, 4 | world SMALLINT NOT NULL, 5 | name varchar(13) NOT NULL, 6 | 7 | level SMALLINT NOT NULL DEFAULT 1, 8 | exp INTEGER NOT NULL DEFAULT 0, 9 | 10 | stre SMALLINT NOT NULL DEFAULT 12, 11 | dex SMALLINT NOT NULL DEFAULT 5, 12 | luk SMALLINT NOT NULL DEFAULT 4, 13 | int SMALLINT NOT NULL DEFAULT 4, 14 | hp SMALLINT NOT NULL DEFAULT 50, 15 | mp SMALLINT NOT NULL DEFAULT 5, 16 | maxhp SMALLINT NOT NULL DEFAULT 50, 17 | maxmp SMALLINT NOT NULL DEFAULT 5, 18 | ap SMALLINT NOT NULL DEFAULT 0, 19 | fame SMALLINT NOT NULL DEFAULT 0, 20 | 21 | meso INTEGER NOT NULL DEFAULT 0, 22 | 23 | job SMALLINT NOT NULL DEFAULT 0, 24 | 25 | face INTEGER NOT NULL, 26 | hair INTEGER NOT NULL, 27 | hair_color INTEGER NOT NULL, 28 | skin INTEGER NOT NULL, 29 | gender SMALLINT NOT NULL, 30 | 31 | created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 32 | 33 | CONSTRAINT name_is_unique UNIQUE(name) 34 | ); 35 | -------------------------------------------------------------------------------- /db/migrations/2020-09-01-153708_create_sessions/down.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE IF EXISTS sessions; 2 | DROP TYPE IF EXISTS session_state; 3 | -------------------------------------------------------------------------------- /db/migrations/2020-09-01-153708_create_sessions/up.sql: -------------------------------------------------------------------------------- 1 | CREATE TYPE session_state AS ENUM ( 2 | 'before_login', 3 | 'after_login', 4 | 'transition', 5 | 'in_game' 6 | ); 7 | 8 | CREATE TABLE sessions ( 9 | id SERIAL PRIMARY KEY, 10 | account_id INTEGER NOT NULL, 11 | character_id INTEGER, 12 | ip INET NOT NULL, 13 | hwid VARCHAR(12) NOT NULL, 14 | state SESSION_STATE NOT NULL DEFAULT 'before_login', 15 | updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 16 | created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 17 | 18 | CONSTRAINT fk_account 19 | FOREIGN KEY(account_id) 20 | REFERENCES accounts(id) ON DELETE CASCADE, 21 | 22 | CONSTRAINT fk_character 23 | FOREIGN KEY(character_id) 24 | REFERENCES characters(id) ON DELETE SET NULL 25 | ); 26 | -------------------------------------------------------------------------------- /db/migrations/2020-09-02-163632_create_keybindings/down.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE IF EXISTS keybindings; 2 | DROP TYPE IF EXISTS keybind_type; 3 | -------------------------------------------------------------------------------- /db/migrations/2020-09-02-163632_create_keybindings/up.sql: -------------------------------------------------------------------------------- 1 | CREATE TYPE keybind_type AS ENUM ( 2 | 'nil', 3 | 'skill', 4 | 'item', 5 | 'cash', 6 | 'menu', 7 | 'action', 8 | 'face', 9 | 'macro', 10 | 'text' 11 | ); 12 | 13 | -- TODO: action and bind_type could be enums but they aren't really consistent in 14 | -- TODO: numbering... we'd either need filler or another mapping... 15 | 16 | 17 | -- TODO: Action constraint is not needed! Only key constraint! 18 | CREATE TABLE keybindings ( 19 | id SERIAL PRIMARY KEY, 20 | character_id INTEGER NOT NULL, 21 | key SMALLINT NOT NULL DEFAULT 0, 22 | bind_type KEYBIND_TYPE NOT NULL DEFAULT 'nil', 23 | action SMALLINT NOT NULL DEFAULT 0, 24 | 25 | CONSTRAINT fk_character 26 | FOREIGN KEY(character_id) 27 | REFERENCES characters(id) ON DELETE CASCADE, 28 | 29 | CONSTRAINT key_is_unique_per_character UNIQUE(character_id, key) 30 | ); 31 | -------------------------------------------------------------------------------- /db/migrations/2020-09-12-213326_add_map_to_character/down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE characters 2 | DROP COLUMN map_id; 3 | -------------------------------------------------------------------------------- /db/migrations/2020-09-12-213326_add_map_to_character/up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE characters 2 | ADD COLUMN map_id INTEGER NOT NULL DEFAULT 1000000; 3 | -------------------------------------------------------------------------------- /db/src/account/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::schema::accounts; 2 | use std::{fmt::Debug, time::SystemTime}; 3 | 4 | mod repository; 5 | pub use repository::*; 6 | 7 | #[derive(Identifiable, Queryable, AsChangeset)] 8 | pub struct Account { 9 | pub id: i32, 10 | pub user_name: String, 11 | pub password: String, 12 | pub pin: String, 13 | pub pic: String, 14 | pub logged_in: bool, 15 | pub last_login_at: Option, 16 | pub created_at: SystemTime, 17 | pub character_slots: i16, 18 | pub gender: i16, 19 | pub accepted_tos: bool, 20 | pub banned: bool, 21 | pub ban_msg: Option, 22 | } 23 | 24 | impl Debug for Account { 25 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 26 | write!( 27 | f, 28 | "id: {}, user_name: {}, logged_in: {}", 29 | self.id, self.user_name, self.logged_in 30 | ) 31 | } 32 | } 33 | 34 | #[derive(Insertable)] 35 | #[table_name = "accounts"] 36 | pub struct NewAccount<'a> { 37 | pub user_name: &'a str, 38 | pub password: &'a str, 39 | } 40 | -------------------------------------------------------------------------------- /db/src/account/repository.rs: -------------------------------------------------------------------------------- 1 | use super::{Account, NewAccount}; 2 | use crate::establish_connection; 3 | use crate::schema; 4 | use diesel::expression_methods::*; 5 | use diesel::{QueryDsl, QueryResult, RunQueryDsl, SaveChangesDsl}; 6 | use schema::accounts; 7 | use schema::accounts::dsl::*; 8 | 9 | pub fn get_account(user: &str) -> QueryResult { 10 | let connection = establish_connection(); 11 | 12 | accounts 13 | .filter(user_name.eq(user)) 14 | .first::(&connection) 15 | } 16 | 17 | pub fn get_account_by_id(a_id: i32) -> QueryResult { 18 | let connection = establish_connection(); 19 | 20 | accounts.filter(id.eq(a_id)).first::(&connection) 21 | } 22 | 23 | pub fn create_account<'a>(user: &'a str, pw: &'a str) -> QueryResult { 24 | let connection = establish_connection(); 25 | 26 | let new_account = NewAccount { 27 | user_name: user, 28 | password: pw, 29 | }; 30 | 31 | diesel::insert_into(accounts::table) 32 | .values(&new_account) 33 | .get_result::(&connection) 34 | } 35 | 36 | pub fn update_account(acc: &Account) -> QueryResult { 37 | let connection = establish_connection(); 38 | acc.save_changes(&connection) 39 | } 40 | -------------------------------------------------------------------------------- /db/src/character/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::{keybinding::KeybindSet, schema::characters}; 2 | use diesel::QueryResult; 3 | use std::time::SystemTime; 4 | 5 | pub mod repository; 6 | 7 | pub use repository::*; 8 | 9 | /// Character database entity. 10 | #[derive(Identifiable, Queryable, AsChangeset)] 11 | pub struct Character { 12 | pub id: i32, 13 | pub accountid: i32, 14 | pub world: i16, 15 | pub name: String, 16 | 17 | pub level: i16, 18 | pub exp: i32, 19 | 20 | pub stre: i16, 21 | pub dex: i16, 22 | pub luk: i16, 23 | pub int: i16, 24 | pub hp: i16, 25 | pub mp: i16, 26 | pub maxhp: i16, 27 | pub maxmp: i16, 28 | pub ap: i16, 29 | pub fame: i16, 30 | 31 | pub meso: i32, 32 | 33 | pub job: i16, 34 | 35 | pub face: i32, 36 | pub hair: i32, 37 | pub hair_color: i32, 38 | pub skin: i32, 39 | pub gender: i16, 40 | 41 | pub created_at: SystemTime, 42 | 43 | pub map_id: i32, 44 | } 45 | 46 | impl Character { 47 | pub fn save(&self) -> QueryResult { 48 | repository::update_character(self) 49 | } 50 | } 51 | 52 | /// Character creation projection. 53 | #[derive(Insertable)] 54 | #[table_name = "characters"] 55 | pub struct NewCharacter<'a> { 56 | pub accountid: i32, 57 | pub world: i16, 58 | pub name: &'a str, 59 | pub job: i16, 60 | pub face: i32, 61 | pub hair: i32, 62 | pub hair_color: i32, 63 | pub skin: i32, 64 | pub gender: i16, 65 | } 66 | 67 | impl NewCharacter<'_> { 68 | /// Save the new character and return the saved Character's 69 | /// wrapper. 70 | pub fn create(self) -> QueryResult { 71 | let character = repository::create_character(self)?; 72 | let key_binds = KeybindSet::set_defaults(&character)?; 73 | 74 | Ok(CharacterWrapper { 75 | character, 76 | key_binds, 77 | }) 78 | } 79 | } 80 | 81 | /// This struct is meant to hold data pertaining to a character 82 | /// beyond simply the character itself. 83 | pub struct CharacterWrapper { 84 | pub character: Character, 85 | pub key_binds: KeybindSet, 86 | } 87 | 88 | impl CharacterWrapper { 89 | /// Load an existing character given their ID. 90 | pub fn from_character_id(character_id: i32) -> QueryResult { 91 | let character = repository::get_character_by_id(character_id)?; 92 | Self::from_character(character) 93 | } 94 | 95 | /// Wrap a character entity struct along with any additional information. 96 | pub fn from_character(character: Character) -> QueryResult { 97 | let key_binds = KeybindSet::from_character(&character)?; 98 | 99 | let dto = Self { 100 | character, 101 | key_binds, 102 | }; 103 | Ok(dto) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /db/src/character/repository.rs: -------------------------------------------------------------------------------- 1 | use super::{Character, NewCharacter}; 2 | use crate::establish_connection; 3 | use crate::schema; 4 | use crate::schema::characters; 5 | use diesel::expression_methods::*; 6 | use diesel::{QueryDsl, QueryResult, RunQueryDsl, SaveChangesDsl}; 7 | use schema::characters::dsl::*; 8 | 9 | pub fn get_characters_by_accountid(account_id: i32) -> QueryResult> { 10 | let connection = establish_connection(); 11 | 12 | characters 13 | .filter(accountid.eq(account_id)) 14 | .load::(&connection) 15 | } 16 | 17 | pub fn get_character_by_name(cname: &str) -> QueryResult { 18 | let connection = establish_connection(); 19 | 20 | characters 21 | .filter(name.eq(cname)) 22 | .first::(&connection) 23 | } 24 | 25 | pub fn get_character_by_id(cid: i32) -> QueryResult { 26 | let connection = establish_connection(); 27 | 28 | characters 29 | .filter(id.eq(cid)) 30 | .first::(&connection) 31 | } 32 | 33 | pub fn create_character<'a>(char: NewCharacter) -> QueryResult { 34 | let connection = establish_connection(); 35 | 36 | diesel::insert_into(characters::table) 37 | .values(&char) 38 | .get_result::(&connection) 39 | } 40 | 41 | pub fn update_character(character: &Character) -> QueryResult { 42 | let connection = establish_connection(); 43 | 44 | character.save_changes(&connection) 45 | } 46 | 47 | pub fn delete_character(character_id: i32, account_id: i32) -> QueryResult { 48 | let connection = establish_connection(); 49 | 50 | diesel::delete( 51 | characters 52 | .filter(id.eq(character_id)) 53 | .filter(accountid.eq(account_id)), 54 | ) 55 | .execute(&connection) 56 | } 57 | -------------------------------------------------------------------------------- /db/src/keybinding/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::{character::Character, schema::keybindings}; 2 | use diesel::QueryResult; 3 | use itertools::izip; 4 | use std::collections::HashMap; 5 | 6 | mod repository; 7 | pub use repository::*; 8 | 9 | // Values to build default bindings from 10 | // TODO: These aren't a complete default set. 11 | // TODO: Perhaps we should externalize these. 12 | const DEFAULT_KEY: [i16; 23] = [ 13 | 59, 60, 61, 62, 63, 64, 65, 56, 87, 18, 23, 31, 37, 19, 17, 46, 50, 16, 43, 40, 21, 4, 84, 14 | ]; 15 | const DEFAULT_TYPE: [u8; 23] = [ 16 | 6, 6, 6, 6, 6, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 17 | ]; 18 | const DEFAULT_ACTION: [i16; 23] = [ 19 | 100, 101, 102, 103, 104, 105, 106, 54, 54, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 20 | ]; 21 | 22 | #[derive(Debug, Clone, Copy, DbEnum)] 23 | #[DieselType = "Keybind_type"] 24 | #[PgType = "keybind_type"] 25 | pub enum KeybindType { 26 | Nil, 27 | Skill, 28 | Item, 29 | Cash, 30 | Menu, 31 | Action, 32 | Face, 33 | Macro, 34 | Text, 35 | } 36 | 37 | impl From for u8 { 38 | fn from(kind: KeybindType) -> Self { 39 | match kind { 40 | KeybindType::Nil => 0, 41 | KeybindType::Skill => 1, 42 | KeybindType::Item => 2, 43 | KeybindType::Cash => 3, 44 | KeybindType::Menu => 4, 45 | KeybindType::Action => 5, 46 | KeybindType::Face => 6, 47 | KeybindType::Macro => 7, 48 | KeybindType::Text => 8, 49 | } 50 | } 51 | } 52 | 53 | impl From for KeybindType { 54 | fn from(kind: u8) -> Self { 55 | match kind { 56 | 1 => KeybindType::Skill, 57 | 2 => KeybindType::Item, 58 | 3 => KeybindType::Cash, 59 | 4 => KeybindType::Menu, 60 | 5 => KeybindType::Action, 61 | 6 => KeybindType::Face, 62 | 7 => KeybindType::Macro, 63 | 8 => KeybindType::Text, 64 | _ => KeybindType::Nil, 65 | } 66 | } 67 | } 68 | 69 | /// Keybinding database entity. 70 | #[derive(Identifiable, Queryable, Insertable, AsChangeset)] 71 | #[table_name = "keybindings"] 72 | pub struct Keybinding { 73 | pub id: i32, 74 | pub character_id: i32, 75 | pub key: i16, 76 | pub bind_type: KeybindType, 77 | pub action: i16, 78 | } 79 | 80 | /// A projection of the Keybinding entity for less cumbersome manipulation. 81 | #[derive(Clone, Insertable, AsChangeset)] 82 | #[table_name = "keybindings"] 83 | pub struct KeybindDTO { 84 | pub character_id: i32, 85 | pub key: i16, 86 | pub bind_type: KeybindType, 87 | pub action: i16, 88 | } 89 | 90 | impl KeybindDTO { 91 | /// Convert a Keybinding entity struct into its DTO projection. 92 | pub fn from(character_id: i32, key: i16, bind_type: KeybindType, action: i16) -> Self { 93 | KeybindDTO { 94 | character_id, 95 | key, 96 | bind_type, 97 | action, 98 | } 99 | } 100 | 101 | /// Create an empty default keybind for the given key, for the given character. 102 | pub fn default(key: i16, character_id: i32) -> Self { 103 | KeybindDTO { 104 | character_id, 105 | key, 106 | bind_type: KeybindType::Nil, 107 | action: 0, 108 | } 109 | } 110 | } 111 | 112 | impl From<&Keybinding> for KeybindDTO { 113 | fn from(k: &Keybinding) -> Self { 114 | KeybindDTO { 115 | character_id: k.character_id, 116 | key: k.key, 117 | bind_type: k.bind_type, 118 | action: k.action, 119 | } 120 | } 121 | } 122 | 123 | /// A set of keybinds for a given character. 124 | pub struct KeybindSet { 125 | binds: HashMap, 126 | character_id: i32, 127 | } 128 | 129 | impl KeybindSet { 130 | /// Get the keybind set for the given character. 131 | pub fn from_character(character: &Character) -> QueryResult { 132 | let character_id = character.id; 133 | 134 | Ok(Self::from_bind_vec( 135 | character_id, 136 | repository::get_keybindings_by_characterid(character_id)?, 137 | )) 138 | } 139 | 140 | /// Create, set, and return a default keybind set for the given character. 141 | pub fn set_defaults(character: &Character) -> QueryResult { 142 | let character_id = character.id; 143 | let mut bind_set = Self { 144 | character_id, 145 | binds: HashMap::new(), 146 | }; 147 | 148 | izip!( 149 | DEFAULT_KEY.to_vec(), 150 | DEFAULT_TYPE.to_vec(), 151 | DEFAULT_ACTION.to_vec() 152 | ) 153 | .for_each(|(key, btype_ord, action)| { 154 | bind_set.set(KeybindDTO::from( 155 | character_id, 156 | key, 157 | btype_ord.into(), 158 | action, 159 | )) 160 | }); 161 | 162 | bind_set.save()?; 163 | 164 | Ok(bind_set) 165 | } 166 | 167 | /// Convert a vector of keybindings to a keybind set for a given character. 168 | pub fn from_bind_vec(character_id: i32, bind_vec: Vec) -> Self { 169 | let mut bind_set = Self { 170 | character_id, 171 | binds: HashMap::new(), 172 | }; 173 | 174 | bind_vec 175 | .iter() 176 | .for_each(|bind: &Keybinding| bind_set.set(bind.into())); 177 | 178 | bind_set 179 | } 180 | 181 | /// Get the specified key, or a default if it is not present in the keybind set. 182 | pub fn get(&mut self, key: i16) -> KeybindDTO { 183 | self.binds 184 | .get(&key) 185 | .map_or(KeybindDTO::default(key, self.character_id), |bind_ref| { 186 | bind_ref.clone() 187 | }) 188 | } 189 | 190 | /// Set/replace the given key in the keybind set. 191 | pub fn set(&mut self, bind: KeybindDTO) { 192 | self.binds.insert(bind.key, bind); 193 | } 194 | 195 | /// Save the current state of the keybind set. 196 | pub fn save(&self) -> QueryResult<()> { 197 | repository::upsert_keybindings(self.binds.values().map(|x| x.clone()).collect())?; 198 | Ok(()) 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /db/src/keybinding/repository.rs: -------------------------------------------------------------------------------- 1 | use super::{KeybindDTO, Keybinding}; 2 | use crate::establish_connection; 3 | use crate::schema::keybindings::dsl::*; 4 | use diesel::expression_methods::*; 5 | use diesel::pg::upsert::*; 6 | use diesel::{QueryDsl, QueryResult, RunQueryDsl}; 7 | 8 | pub fn get_keybindings_by_characterid(c_id: i32) -> QueryResult> { 9 | let connection = establish_connection(); 10 | 11 | keybindings 12 | .filter(character_id.eq(c_id)) 13 | .load::(&connection) 14 | } 15 | 16 | pub fn upsert_keybindings(bindings: Vec) -> QueryResult> { 17 | let connection = establish_connection(); 18 | 19 | diesel::insert_into(keybindings) 20 | .values(bindings) 21 | .on_conflict(on_constraint("key_is_unique_per_character")) 22 | .do_update() 23 | .set(key.eq(excluded(key))) 24 | .get_results(&connection) 25 | } 26 | -------------------------------------------------------------------------------- /db/src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate serde; 2 | #[macro_use] 3 | extern crate diesel; 4 | #[macro_use] 5 | extern crate serde_derive; 6 | #[macro_use] 7 | extern crate diesel_derive_enum; 8 | 9 | use diesel::pg::PgConnection; 10 | use diesel::prelude::*; 11 | use settings::Settings; 12 | 13 | pub mod schema; 14 | mod settings; 15 | mod sql_types; 16 | 17 | pub mod account; 18 | pub mod character; 19 | pub mod keybinding; 20 | pub mod session; 21 | 22 | pub use diesel::result::Error; 23 | 24 | pub fn establish_connection() -> PgConnection { 25 | // TODO: This needs proper error handling... 26 | let database_url = Settings::new().unwrap().database.url; 27 | PgConnection::establish(&database_url).expect(&format!("Error connecting to {}", database_url)) 28 | } 29 | -------------------------------------------------------------------------------- /db/src/schema.rs: -------------------------------------------------------------------------------- 1 | table! { 2 | use crate::sql_types::*; 3 | 4 | accounts (id) { 5 | id -> Int4, 6 | user_name -> Varchar, 7 | password -> Varchar, 8 | pin -> Varchar, 9 | pic -> Varchar, 10 | logged_in -> Bool, 11 | last_login_at -> Nullable, 12 | created_at -> Timestamp, 13 | character_slots -> Int2, 14 | gender -> Int2, 15 | accepted_tos -> Bool, 16 | banned -> Bool, 17 | ban_msg -> Nullable, 18 | } 19 | } 20 | 21 | table! { 22 | use crate::sql_types::*; 23 | 24 | characters (id) { 25 | id -> Int4, 26 | accountid -> Int4, 27 | world -> Int2, 28 | name -> Varchar, 29 | level -> Int2, 30 | exp -> Int4, 31 | stre -> Int2, 32 | dex -> Int2, 33 | luk -> Int2, 34 | int -> Int2, 35 | hp -> Int2, 36 | mp -> Int2, 37 | maxhp -> Int2, 38 | maxmp -> Int2, 39 | ap -> Int2, 40 | fame -> Int2, 41 | meso -> Int4, 42 | job -> Int2, 43 | face -> Int4, 44 | hair -> Int4, 45 | hair_color -> Int4, 46 | skin -> Int4, 47 | gender -> Int2, 48 | created_at -> Timestamp, 49 | map_id -> Int4, 50 | } 51 | } 52 | 53 | table! { 54 | use crate::sql_types::*; 55 | 56 | keybindings (id) { 57 | id -> Int4, 58 | character_id -> Int4, 59 | key -> Int2, 60 | bind_type -> Keybind_type, 61 | action -> Int2, 62 | } 63 | } 64 | 65 | table! { 66 | use crate::sql_types::*; 67 | 68 | sessions (id) { 69 | id -> Int4, 70 | account_id -> Int4, 71 | character_id -> Nullable, 72 | ip -> Inet, 73 | hwid -> Varchar, 74 | state -> Session_state, 75 | updated_at -> Timestamp, 76 | created_at -> Timestamp, 77 | } 78 | } 79 | 80 | joinable!(sessions -> accounts (account_id)); 81 | 82 | allow_tables_to_appear_in_same_query!( 83 | accounts, 84 | characters, 85 | keybindings, 86 | sessions, 87 | ); 88 | -------------------------------------------------------------------------------- /db/src/session/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::{character, schema::sessions}; 2 | 3 | extern crate ipnetwork; 4 | use character::CharacterWrapper; 5 | use diesel::QueryResult; 6 | use ipnetwork::IpNetwork; 7 | 8 | use std::{cell::RefCell, rc::Rc, time::SystemTime}; 9 | 10 | pub mod repository; 11 | pub use repository::*; 12 | 13 | #[derive(Debug, DbEnum)] 14 | #[DieselType = "Session_state"] 15 | #[PgType = "session_state"] 16 | pub enum SessionState { 17 | BeforeLogin, 18 | AfterLogin, 19 | Transition, 20 | InGame, 21 | } 22 | 23 | #[derive(Identifiable, Queryable, AsChangeset)] 24 | #[table_name = "sessions"] 25 | pub struct Session { 26 | pub id: i32, 27 | pub account_id: i32, 28 | pub character_id: Option, 29 | pub ip: IpNetwork, 30 | pub hwid: String, 31 | pub state: SessionState, 32 | pub updated_at: SystemTime, 33 | pub created_at: SystemTime, 34 | } 35 | 36 | /// Session creation projection. 37 | #[derive(Insertable)] 38 | #[table_name = "sessions"] 39 | pub struct NewSession<'a> { 40 | pub account_id: i32, 41 | pub ip: IpNetwork, 42 | pub hwid: &'a str, 43 | pub state: SessionState, 44 | } 45 | 46 | impl<'a> NewSession<'a> { 47 | /// Create and save a new session. 48 | pub fn create(self) -> QueryResult { 49 | SessionWrapper::from(repository::create_session(self)?) 50 | } 51 | } 52 | 53 | /// A wrapper that holds a session as well as any additional 54 | /// information pertaining to the session. 55 | pub struct SessionWrapper { 56 | pub session: Option, 57 | character: Option>>, 58 | } 59 | 60 | impl SessionWrapper { 61 | /// Create a new wrapper with no associated session. 62 | pub fn new_empty() -> Self { 63 | Self { 64 | session: None, 65 | character: None, 66 | } 67 | } 68 | 69 | /// Create a wrapper from an existing session, loading in the associated 70 | /// character if it exists. 71 | pub fn from(session: Session) -> QueryResult { 72 | let c_id = session.character_id; 73 | 74 | let mut wrapper = Self { 75 | session: Some(session), 76 | character: None, 77 | }; 78 | 79 | if let Some(c_id) = c_id { 80 | wrapper.load_character(c_id)?; 81 | }; 82 | 83 | Ok(wrapper) 84 | } 85 | 86 | /// Retrieve the character that the session is associated with, or a NotFound 87 | /// error if there is no character associated. 88 | pub fn get_character(&mut self) -> QueryResult>> { 89 | self.session 90 | .as_ref() 91 | .and_then(|ses| ses.character_id) 92 | .and_then(|c_id| { 93 | self.character 94 | .as_ref() 95 | .and_then(|chr| Some(chr.clone())) 96 | .or(self.load_character(c_id).ok()) 97 | }) 98 | .ok_or(diesel::result::Error::NotFound) 99 | } 100 | 101 | /// Attach a character to the session wrapper and return a counted refcell. 102 | fn load_character(&mut self, c_id: i32) -> QueryResult>> { 103 | let chr = Rc::new(RefCell::new(CharacterWrapper::from_character_id(c_id)?)); 104 | 105 | self.character = Some(chr.clone()); 106 | 107 | Ok(chr.clone()) 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /db/src/session/repository.rs: -------------------------------------------------------------------------------- 1 | use super::{NewSession, Session, SessionState}; 2 | use crate::establish_connection; 3 | use crate::schema::sessions::dsl::*; 4 | use diesel::expression_methods::*; 5 | use diesel::{QueryDsl, QueryResult, RunQueryDsl, SaveChangesDsl}; 6 | use ipnetwork::IpNetwork; 7 | 8 | pub fn get_session_by_accountid(a_id: i32) -> QueryResult { 9 | let connection = establish_connection(); 10 | 11 | sessions 12 | .filter(account_id.eq(a_id)) 13 | .first::(&connection) 14 | } 15 | 16 | pub fn get_session_by_characterid(c_id: i32) -> QueryResult { 17 | let connection = establish_connection(); 18 | 19 | sessions 20 | .filter(character_id.eq(c_id)) 21 | .first::(&connection) 22 | } 23 | 24 | pub fn get_session_to_reattach(c_id: i32, ip_addr: IpNetwork) -> QueryResult { 25 | let connection = establish_connection(); 26 | 27 | sessions 28 | .filter(character_id.eq(c_id)) 29 | .filter(ip.eq(ip_addr)) 30 | .filter(state.eq(SessionState::Transition)) 31 | .first::(&connection) 32 | } 33 | 34 | pub fn create_session(new_session: NewSession) -> QueryResult { 35 | let connection = establish_connection(); 36 | 37 | diesel::insert_into(sessions) 38 | .values(&new_session) 39 | .get_result::(&connection) 40 | } 41 | 42 | pub fn update_session(ses: &Session) -> QueryResult { 43 | let connection = establish_connection(); 44 | 45 | ses.save_changes(&connection) 46 | } 47 | 48 | pub fn delete_session_by_id(s_id: i32) -> QueryResult { 49 | let connection = establish_connection(); 50 | 51 | diesel::delete(sessions.filter(id.eq(s_id))).execute(&connection) 52 | } 53 | -------------------------------------------------------------------------------- /db/src/settings.rs: -------------------------------------------------------------------------------- 1 | use config::{Config, ConfigError, File}; 2 | 3 | #[derive(Debug, Deserialize)] 4 | pub struct Database { 5 | pub url: String, 6 | } 7 | 8 | #[derive(Debug, Deserialize)] 9 | pub struct Settings { 10 | pub database: Database, 11 | } 12 | 13 | impl Settings { 14 | pub fn new() -> Result { 15 | let mut s = Config::new(); 16 | 17 | s.merge(File::with_name("config/db_config"))?; 18 | 19 | s.try_into() 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /db/src/sql_types.rs: -------------------------------------------------------------------------------- 1 | //! The purpose of this module is to put all relevant types in one place 2 | //! for the schema to make use of. 3 | 4 | pub use crate::keybinding::Keybind_type; 5 | pub use crate::session::Session_state; 6 | pub use diesel::sql_types::*; 7 | -------------------------------------------------------------------------------- /diesel.toml: -------------------------------------------------------------------------------- 1 | # For documentation on how to configure this file, 2 | # see diesel.rs/guides/configuring-diesel-cli 3 | 4 | # TODO: Next major release of Diesel will allow this; 5 | # For now you need to supply --migration-dir to diesel-cli 6 | # [migrations_directory] 7 | # file = "db/migrations/" 8 | 9 | [print_schema] 10 | file = "db/src/schema.rs" 11 | import_types = ["crate::sql_types::*"] 12 | 13 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3.1' 2 | 3 | services: 4 | db: 5 | image: postgres 6 | restart: always 7 | environment: 8 | POSTGRES_USER: maplestory 9 | POSTGRES_PASSWORD: pass 10 | POSTGRES_DATABASE: "RustMS" 11 | ports: 12 | - 5432:5432 13 | -------------------------------------------------------------------------------- /img/handshake_start.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/neeerp/RustMS/33083a7f6acee50572c2c042cafa5b0add60ae16/img/handshake_start.png -------------------------------------------------------------------------------- /img/login.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/neeerp/RustMS/33083a7f6acee50572c2c042cafa5b0add60ae16/img/login.png -------------------------------------------------------------------------------- /img/run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/neeerp/RustMS/33083a7f6acee50572c2c042cafa5b0add60ae16/img/run.png -------------------------------------------------------------------------------- /img/run_client.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/neeerp/RustMS/33083a7f6acee50572c2c042cafa5b0add60ae16/img/run_client.png -------------------------------------------------------------------------------- /img/sp_ship.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/neeerp/RustMS/33083a7f6acee50572c2c042cafa5b0add60ae16/img/sp_ship.png -------------------------------------------------------------------------------- /net/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "net" 3 | version = "0.1.0" 4 | authors = ["David Goldstein "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | packet = { path = "../packet" } 11 | crypt = { path = "../crypt" } 12 | db = { path = "../db" } 13 | bufstream = "0.1.4" 14 | rand = "0.7.3" 15 | num = "0.2" 16 | num-derive = "0.3" 17 | num-traits = "0.2" 18 | serde_derive = "^1.0.8" 19 | serde = "^1.0.8" 20 | config = "0.10.1" 21 | -------------------------------------------------------------------------------- /net/src/helpers.rs: -------------------------------------------------------------------------------- 1 | use std::time::{SystemTime, UNIX_EPOCH}; 2 | 3 | use crate::error::NetworkError; 4 | 5 | /// Convert bytes to a hex String. 6 | pub fn to_hex_string(bytes: &Vec) -> String { 7 | let strs: Vec = bytes.iter().map(|b| format!("{:02X}", b)).collect(); 8 | strs.join(" ") 9 | } 10 | 11 | pub fn current_time_i64() -> Result { 12 | Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as i64) 13 | } 14 | -------------------------------------------------------------------------------- /net/src/io/accept.rs: -------------------------------------------------------------------------------- 1 | //! # Packet Acceptor module 2 | //! 3 | //! This module contains the logic used to accept an incoming packet from a 4 | //! client session's `TcpStream`. 5 | //! 6 | 7 | use crate::{error::NetworkError, io::client::MapleClient}; 8 | use crypt::{maple_crypt, MapleAES}; 9 | use packet::{Packet, MAX_PACKET_LENGTH}; 10 | 11 | use bufstream::BufStream; 12 | use std::io::Read; 13 | use std::net::TcpStream; 14 | 15 | /// Read, decrypt, and wrap a new incoming packet from a stream. 16 | pub fn read_packet(client: &mut MapleClient) -> Result { 17 | let crypt = &mut client.recv_crypt; 18 | let stream = &mut client.stream; 19 | 20 | let data_length = read_header(stream, crypt)?; 21 | read_data(data_length, stream, crypt) 22 | } 23 | 24 | /// Read a new packet header from the session stream and use it to return the 25 | /// length of the incoming packet. 26 | fn read_header( 27 | stream: &mut BufStream, 28 | crypt: &mut MapleAES, 29 | ) -> Result { 30 | let mut header_buf: [u8; 4] = [0u8; 4]; 31 | 32 | stream.read_exact(&mut header_buf)?; 33 | parse_header(&header_buf, crypt) 34 | } 35 | 36 | /// Read the data of a packet given its length from the session stream and 37 | /// decrypt and wrap the data into a `Packet` struct. 38 | fn read_data( 39 | data_length: i16, 40 | stream: &mut BufStream, 41 | crypt: &mut MapleAES, 42 | ) -> Result { 43 | let mut buf = vec![0u8; data_length as usize]; 44 | 45 | stream.read_exact(&mut buf)?; 46 | 47 | // Decrypt incoming packet 48 | crypt.crypt(&mut buf[..]); 49 | maple_crypt::decrypt(&mut buf[..]); 50 | 51 | Ok(Packet::new(&buf[..])) 52 | } 53 | 54 | /// Parse the packet header and return the length of the incoming packet. 55 | fn parse_header(header_buf: &[u8; 4], crypt: &mut MapleAES) -> Result { 56 | if crypt.check_header(&header_buf[..]) { 57 | let length = crypt.get_packet_length(&header_buf[..]); 58 | 59 | validate_packet_length(length) 60 | } else { 61 | Err(NetworkError::InvalidHeader) 62 | } 63 | } 64 | 65 | /// Check that the given length value neither exceeds the maximum packet 66 | /// length nor is too short to contain an opcode. 67 | fn validate_packet_length(length: i16) -> Result { 68 | if length < 2 || length > MAX_PACKET_LENGTH { 69 | Err(NetworkError::InvalidPacketLength(length)) 70 | } else { 71 | Ok(length) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /net/src/io/client.rs: -------------------------------------------------------------------------------- 1 | use crate::error::NetworkError; 2 | use bufstream::BufStream; 3 | use crypt::{maple_crypt, MapleAES}; 4 | use db::{ 5 | account::{self, Account}, 6 | session::{self, SessionState}, 7 | }; 8 | use packet::Packet; 9 | use session::{NewSession, SessionWrapper}; 10 | use std::{io::Write, net::TcpStream, time::SystemTime}; 11 | 12 | /// A container for various pieces of information pertaining to a Session's 13 | /// client. 14 | pub struct MapleClient { 15 | pub stream: BufStream, 16 | pub recv_crypt: MapleAES, 17 | pub send_crypt: MapleAES, 18 | pub session: SessionWrapper, 19 | } 20 | 21 | impl MapleClient { 22 | pub fn new(stream: BufStream, recv_iv: &Vec, send_iv: &Vec) -> Self { 23 | let recv_crypt = MapleAES::new(recv_iv, 83); 24 | let send_crypt = MapleAES::new(send_iv, 83); 25 | 26 | MapleClient { 27 | stream, 28 | recv_crypt, 29 | send_crypt, 30 | session: SessionWrapper::new_empty(), 31 | } 32 | } 33 | 34 | /// Encrypt a packet with the custom Maplestory encryption followed by AES, 35 | /// and then send the packet to the client. 36 | pub fn send(&mut self, packet: &mut Packet) -> Result<(), NetworkError> { 37 | let header = self.send_crypt.gen_packet_header(packet.len() + 2); 38 | 39 | maple_crypt::encrypt(packet); 40 | self.send_crypt.crypt(packet); 41 | 42 | self.send_without_encryption(&header)?; 43 | self.send_without_encryption(packet) 44 | } 45 | 46 | /// Send data to the client. 47 | pub fn send_without_encryption(&mut self, data: &[u8]) -> Result<(), NetworkError> { 48 | match self.stream.write(data) { 49 | Ok(_) => match self.stream.flush() { 50 | Ok(_) => Ok(()), 51 | Err(e) => Err(NetworkError::CouldNotSend(e)), 52 | }, 53 | Err(e) => Err(NetworkError::CouldNotSend(e)), 54 | } 55 | } 56 | 57 | /// Retrieve the account associated with the client session. 58 | pub fn get_account(&self) -> Option { 59 | match &self.session.session { 60 | Some(session) => account::get_account_by_id(session.account_id).ok(), 61 | None => None, 62 | } 63 | } 64 | 65 | // TODO: Move session logic into Session/Session Wrapper objects. 66 | 67 | pub fn login( 68 | &mut self, 69 | account_id: i32, 70 | hwid: &str, 71 | state: SessionState, 72 | ) -> Result<(), NetworkError> { 73 | let ip = self.stream.get_ref().peer_addr()?.ip().into(); 74 | let new_session = NewSession { 75 | account_id, 76 | hwid, 77 | ip, 78 | state, 79 | }; 80 | 81 | self.session = new_session.create()?; 82 | Ok(()) 83 | } 84 | 85 | pub fn complete_login(&mut self) -> Result<(), NetworkError> { 86 | match self.session.session.take() { 87 | Some(mut ses) => { 88 | ses.state = SessionState::AfterLogin; 89 | ses.updated_at = SystemTime::now(); 90 | 91 | self.session.session = Some(session::update_session(&ses)?); 92 | Ok(()) 93 | } 94 | None => Err(NetworkError::NotLoggedIn), 95 | } 96 | } 97 | 98 | pub fn transition(&mut self, character_id: i32) -> Result<(), NetworkError> { 99 | match self.session.session.take() { 100 | Some(mut ses) => { 101 | ses.state = SessionState::Transition; 102 | ses.character_id = Some(character_id); 103 | ses.updated_at = SystemTime::now(); 104 | 105 | session::update_session(&ses)?; 106 | Ok(()) 107 | } 108 | None => Err(NetworkError::NotLoggedIn), 109 | } 110 | } 111 | 112 | pub fn reattach(&mut self, character_id: i32) -> Result<(), NetworkError> { 113 | let ip = self.stream.get_ref().peer_addr()?.ip(); 114 | 115 | let mut ses = session::get_session_to_reattach(character_id, ip.into())?; 116 | ses.state = SessionState::InGame; 117 | ses.updated_at = SystemTime::now(); 118 | 119 | self.session.session = Some(session::update_session(&ses)?); 120 | 121 | Ok(()) 122 | } 123 | 124 | pub fn logout(&mut self) -> Result<(), NetworkError> { 125 | match self.session.session.take() { 126 | Some(session) => { 127 | session::delete_session_by_id(session.id)?; 128 | Ok(()) 129 | } 130 | None => Ok(()), 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /net/src/io/error.rs: -------------------------------------------------------------------------------- 1 | use config::ConfigError; 2 | use std::fmt; 3 | use std::{io, time::SystemTimeError}; 4 | 5 | #[derive(Debug)] 6 | pub enum NetworkError { 7 | InvalidHeader, 8 | InvalidPacketLength(i16), 9 | NoData, 10 | PacketLengthDiscrepancy(i16, i16), 11 | InvalidPacket, 12 | CouldNotReadHeader(io::Error), 13 | CouldNotReadPacket(io::Error), 14 | PacketHandlerError(&'static str), // TODO: Ideally we make a separate error enum 15 | UnsupportedOpcodeError(i16), 16 | CouldNotSend(io::Error), 17 | IoError(io::Error), 18 | CouldNotEstablishConnection(io::Error), 19 | SystemTimeError(SystemTimeError), 20 | ConfigLoadError(ConfigError), 21 | DbError(db::Error), 22 | CryptError(crypt::BcryptError), 23 | LogoutError(Box), 24 | NotLoggedIn, 25 | ClientDisconnected, 26 | } 27 | 28 | impl fmt::Display for NetworkError { 29 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 30 | match self { 31 | NetworkError::InvalidPacketLength(length) => { 32 | write!(f, "Packet length {} according to header is invalid", length) 33 | } 34 | NetworkError::PacketLengthDiscrepancy(actual, expected) => write!( 35 | f, 36 | "Actual length {} does not match reported length {}", 37 | actual, expected 38 | ), 39 | NetworkError::CouldNotReadPacket(e) => write!(f, "Error reading packet: {}", e), 40 | NetworkError::CouldNotReadHeader(e) => write!(f, "Error reading header: {}", e), 41 | NetworkError::PacketHandlerError(msg) => write!(f, "Error handling packet: {}", msg), 42 | NetworkError::UnsupportedOpcodeError(op) => write!(f, "Unsupported Opcode: {}", op), 43 | NetworkError::CouldNotSend(e) => write!(f, "Error Sending Packet: {}", e), 44 | NetworkError::ClientDisconnected => write!(f, "Client Disconnected."), 45 | NetworkError::CouldNotEstablishConnection(e) => { 46 | write!(f, "Could not establish connection: {}", e) 47 | } 48 | NetworkError::SystemTimeError(e) => write!(f, "System Time Conversion Error: {}", e), 49 | NetworkError::ConfigLoadError(e) => { 50 | write!(f, "Error loading configuration from file: {}", e) 51 | } 52 | NetworkError::DbError(e) => write!(f, "Database Error: {}", e), 53 | NetworkError::CryptError(e) => write!(f, "Error applying encryption: {}", e), 54 | NetworkError::LogoutError(e) => write!( 55 | f, 56 | "An error occured while performing a session logout: {}", 57 | *e 58 | ), 59 | NetworkError::NotLoggedIn => write!(f, "User not logged in."), 60 | e => write!(f, "{:?}", e), 61 | } 62 | } 63 | } 64 | 65 | impl From for NetworkError { 66 | fn from(error: io::Error) -> Self { 67 | match error { 68 | ref e if e.kind() == io::ErrorKind::UnexpectedEof => NetworkError::ClientDisconnected, 69 | _ => NetworkError::IoError(error), 70 | } 71 | } 72 | } 73 | 74 | impl From for NetworkError { 75 | fn from(e: SystemTimeError) -> Self { 76 | NetworkError::SystemTimeError(e) 77 | } 78 | } 79 | 80 | impl From for NetworkError { 81 | fn from(e: ConfigError) -> Self { 82 | NetworkError::ConfigLoadError(e) 83 | } 84 | } 85 | 86 | impl From for NetworkError { 87 | fn from(e: db::Error) -> Self { 88 | NetworkError::DbError(e) 89 | } 90 | } 91 | 92 | impl From for NetworkError { 93 | fn from(e: crypt::BcryptError) -> Self { 94 | NetworkError::CryptError(e) 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /net/src/io/listener.rs: -------------------------------------------------------------------------------- 1 | use crate::io::{accept, client::MapleClient}; 2 | use crate::{error::NetworkError, packet::build, packet::handle}; 3 | 4 | use packet::Packet; 5 | 6 | use bufstream::BufStream; 7 | use rand::{thread_rng, Rng}; 8 | use std::net::TcpStream; 9 | 10 | pub struct ClientConnectionListener { 11 | pub client: MapleClient, 12 | server_type: ServerType, 13 | } 14 | 15 | impl ClientConnectionListener { 16 | /// Instantiate a new Login Server Connection Listener 17 | pub fn login_server(stream: TcpStream) -> Result { 18 | Self::new(stream, ServerType::Login) 19 | } 20 | 21 | /// Instantiate a new World server Connection Listener 22 | pub fn world_server(stream: TcpStream) -> Result { 23 | Self::new(stream, ServerType::World) 24 | } 25 | 26 | /// Instantiate a new maplestory client listener, generating encryption 27 | /// IVs in the process. 28 | fn new( 29 | stream: TcpStream, 30 | server_type: ServerType, 31 | ) -> Result { 32 | let stream = BufStream::new(stream); 33 | 34 | let (recv_iv, send_iv) = ClientConnectionListener::generate_ivs(); 35 | let mut client = MapleClient::new(stream, &recv_iv, &send_iv); 36 | 37 | let handshake_packet = build::build_handshake_packet(&recv_iv, &send_iv)?; 38 | 39 | match client.send_without_encryption(&handshake_packet) { 40 | Ok(_) => Ok(ClientConnectionListener { 41 | client, 42 | server_type, 43 | }), 44 | Err(NetworkError::IoError(e)) => Err(NetworkError::CouldNotEstablishConnection(e)), 45 | Err(e) => Err(e), 46 | } 47 | } 48 | 49 | /// Generate a pair of encryption IVs. 50 | fn generate_ivs() -> (Vec, Vec) { 51 | let mut recv_iv: Vec = vec![0u8; 4]; 52 | let mut send_iv: Vec = vec![0u8; 4]; 53 | 54 | let mut rng = thread_rng(); 55 | rng.fill(&mut recv_iv[..]); 56 | rng.fill(&mut send_iv[..]); 57 | 58 | (recv_iv, send_iv) 59 | } 60 | 61 | /// Listen for packets being sent from the client via the session stream. 62 | pub fn listen(&mut self) -> Result<(), NetworkError> { 63 | loop { 64 | if let Err(e) = self.read_from_stream() { 65 | return Err(self.close_gracefully(e)); 66 | } 67 | } 68 | } 69 | 70 | fn close_gracefully(&mut self, e: NetworkError) -> NetworkError { 71 | match self.client.logout() { 72 | Ok(_) => e, 73 | Err(logout_err) => NetworkError::LogoutError(Box::new(logout_err)), // TODO: Need error type that encapsualtes error 74 | } 75 | } 76 | 77 | /// Read packets from the session stream. 78 | fn read_from_stream(&mut self) -> Result<(), NetworkError> { 79 | accept::read_packet(&mut self.client).map(|packet| self.handle_packet(packet))? 80 | } 81 | 82 | /// Deal with the packet data by printing it out. 83 | fn handle_packet(&mut self, mut packet: Packet) -> Result<(), NetworkError> { 84 | let handler = handle::get_handler(packet.opcode(), &self.server_type); 85 | 86 | handler.handle(&mut packet, &mut self.client) 87 | } 88 | } 89 | 90 | pub enum ServerType { 91 | Login, 92 | World, 93 | } 94 | -------------------------------------------------------------------------------- /net/src/io/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod accept; 2 | pub mod client; 3 | pub mod error; 4 | pub mod listener; 5 | -------------------------------------------------------------------------------- /net/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate num_derive; 3 | #[macro_use] 4 | extern crate serde_derive; 5 | extern crate serde; 6 | 7 | mod helpers; 8 | mod io; 9 | mod packet; 10 | pub mod settings; 11 | 12 | pub use self::io::error; 13 | pub use self::io::listener; 14 | -------------------------------------------------------------------------------- /net/src/packet/build/handshake.rs: -------------------------------------------------------------------------------- 1 | use crate::error::NetworkError; 2 | use packet::{io::write::PktWrite, Packet}; 3 | 4 | /// Build the handshake_packet which shares the encryption IVs with the client. 5 | pub fn build_handshake_packet( 6 | recv_iv: &Vec, 7 | send_iv: &Vec, 8 | ) -> Result { 9 | let mut packet = Packet::new_empty(); 10 | 11 | packet.write_short(0x0E)?; // Packet length header 12 | packet.write_short(83)?; // Version 13 | 14 | // Not sure what this part is meant to represent... 15 | // HeavenClient doesn't seem to care for these values but the 16 | // official clients do... 17 | packet.write_short(0)?; 18 | packet.write_byte(0)?; 19 | 20 | packet.write_bytes(&recv_iv)?; 21 | packet.write_bytes(&send_iv)?; 22 | packet.write_byte(8)?; // Locale byte 23 | 24 | Ok(packet) 25 | } 26 | -------------------------------------------------------------------------------- /net/src/packet/build/login/char.rs: -------------------------------------------------------------------------------- 1 | use crate::{error::NetworkError, packet::op::SendOpcode}; 2 | use db::character::Character; 3 | use packet::{io::write::PktWrite, Packet}; 4 | 5 | pub fn build_char_list(chars: Vec) -> Result { 6 | let mut packet = Packet::new_empty(); 7 | let op = SendOpcode::CharList as i16; 8 | 9 | packet.write_short(op)?; 10 | packet.write_byte(0)?; // account status? 11 | 12 | packet.write_byte(chars.len() as u8)?; // number of chars 13 | for character in chars { 14 | write_char(&mut packet, &character)?; 15 | } 16 | 17 | packet.write_byte(2)?; // use pic? 18 | packet.write_int(3)?; // Number of character slots 19 | 20 | Ok(packet) 21 | } 22 | 23 | pub fn build_char_name_response(name: &str, valid: bool) -> Result { 24 | let mut packet = Packet::new_empty(); 25 | let op = SendOpcode::CharNameResponse as i16; 26 | 27 | packet.write_short(op)?; 28 | packet.write_str_with_length(name)?; 29 | packet.write_byte(!valid as u8)?; 30 | 31 | Ok(packet) 32 | } 33 | 34 | pub fn build_char_delete(character_id: i32, status: u8) -> Result { 35 | let mut packet = Packet::new_empty(); 36 | let op = SendOpcode::DeleteCharacter as i16; 37 | 38 | packet.write_short(op)?; 39 | 40 | packet.write_int(character_id)?; 41 | packet.write_byte(status)?; 42 | 43 | Ok(packet) 44 | } 45 | 46 | pub fn build_char_packet(character: Character) -> Result { 47 | let mut packet = Packet::new_empty(); 48 | let op = SendOpcode::NewCharacter as i16; 49 | 50 | packet.write_short(op)?; 51 | packet.write_byte(0)?; 52 | 53 | write_char(&mut packet, &character)?; 54 | 55 | Ok(packet) 56 | } 57 | 58 | fn write_char(packet: &mut Packet, character: &Character) -> Result<(), NetworkError> { 59 | write_char_meta(packet, &character)?; 60 | write_char_look(packet, &character)?; 61 | 62 | packet.write_byte(0)?; 63 | 64 | // Disable rank. 65 | packet.write_byte(0)?; 66 | 67 | Ok(()) 68 | } 69 | 70 | fn write_char_meta(packet: &mut Packet, character: &Character) -> Result<(), NetworkError> { 71 | packet.write_int(character.id)?; 72 | packet.write_str(&character.name)?; 73 | packet.write_bytes(&vec![0u8; 13 - character.name.len()])?; 74 | packet.write_byte(character.gender as u8)?; 75 | packet.write_byte(character.skin as u8)?; 76 | packet.write_int(character.face)?; 77 | packet.write_int(character.hair)?; 78 | 79 | // Pets... Not implemented yet 80 | packet.write_long(0)?; 81 | packet.write_long(0)?; 82 | packet.write_long(0)?; 83 | 84 | packet.write_byte(character.level as u8)?; 85 | packet.write_short(character.job)?; 86 | 87 | packet.write_short(character.stre)?; 88 | packet.write_short(character.dex)?; 89 | packet.write_short(character.int)?; 90 | packet.write_short(character.luk)?; 91 | packet.write_short(character.hp)?; 92 | packet.write_short(character.maxhp)?; 93 | packet.write_short(character.mp)?; 94 | packet.write_short(character.maxmp)?; 95 | packet.write_short(character.ap)?; 96 | 97 | // SP 98 | packet.write_short(0)?; 99 | 100 | packet.write_int(character.exp)?; 101 | packet.write_short(character.fame)?; 102 | 103 | // Gach xp? 104 | packet.write_int(0)?; 105 | 106 | packet.write_int(character.map_id)?; 107 | packet.write_byte(0)?; 108 | 109 | packet.write_int(0)?; 110 | 111 | Ok(()) 112 | } 113 | 114 | fn write_char_look(packet: &mut Packet, character: &Character) -> Result<(), NetworkError> { 115 | packet.write_byte(character.gender as u8)?; 116 | packet.write_byte(character.skin as u8)?; 117 | packet.write_int(character.face)?; 118 | packet.write_byte(0)?; 119 | packet.write_int(character.hair)?; 120 | 121 | write_char_equips(packet, character)?; 122 | 123 | Ok(()) 124 | } 125 | 126 | fn write_char_equips(packet: &mut Packet, _character: &Character) -> Result<(), NetworkError> { 127 | // Regular equips 128 | 129 | // Overall (Top slot) 130 | packet.write_byte(5)?; 131 | packet.write_int(1052122)?; 132 | 133 | // Shoes 134 | packet.write_byte(7)?; 135 | packet.write_int(1072318)?; 136 | 137 | packet.write_byte(0xFF)?; 138 | 139 | // Cash shop equips 140 | 141 | packet.write_byte(0xFF)?; 142 | 143 | // Weapon 144 | packet.write_int(1302000)?; 145 | 146 | // Pet stuff... 147 | packet.write_int(0)?; 148 | packet.write_int(0)?; 149 | packet.write_int(0)?; 150 | 151 | Ok(()) 152 | } 153 | -------------------------------------------------------------------------------- /net/src/packet/build/login/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod char; 2 | pub mod status; 3 | pub mod world; 4 | -------------------------------------------------------------------------------- /net/src/packet/build/login/status.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, 3 | packet::op::SendOpcode::{GuestIdLogin, LoginStatus}, 4 | settings::Settings, 5 | }; 6 | use db::account::Account; 7 | use packet::{io::write::PktWrite, Packet}; 8 | use std::time::{SystemTime, UNIX_EPOCH}; 9 | 10 | /// Build a login status packet that gets sent upon login failure, relaying the 11 | /// reason. 12 | pub fn build_login_status_packet(status: u8) -> Result { 13 | // TODO: Need to create an enum for the status... 14 | let mut packet = Packet::new_empty(); 15 | let opcode = LoginStatus as i16; 16 | 17 | packet.write_short(opcode)?; 18 | packet.write_byte(status)?; 19 | packet.write_byte(0)?; 20 | packet.write_int(0)?; 21 | 22 | Ok(packet) 23 | } 24 | 25 | pub fn build_successful_login_packet(acc: &Account) -> Result { 26 | let mut packet = Packet::new_empty(); 27 | let opcode = LoginStatus as i16; 28 | 29 | let settings = Settings::new()?; 30 | 31 | let account_id = acc.id; 32 | let gender = acc.gender; 33 | let account_name = &acc.user_name; 34 | let created_at: i64 = acc.created_at.duration_since(UNIX_EPOCH)?.as_secs() as i64; 35 | 36 | packet.write_short(opcode)?; 37 | packet.write_int(0)?; 38 | packet.write_short(0)?; 39 | packet.write_int(account_id)?; 40 | packet.write_byte(gender as u8)?; 41 | 42 | packet.write_byte(0)?; 43 | packet.write_byte(0)?; 44 | packet.write_byte(0)?; 45 | 46 | packet.write_str_with_length(account_name)?; 47 | packet.write_byte(0)?; 48 | 49 | packet.write_byte(0)?; 50 | packet.write_long(0)?; 51 | packet.write_long(created_at)?; 52 | 53 | packet.write_int(1)?; 54 | 55 | // PIN/PIC? 56 | packet.write_byte(settings.login.pin_required as u8)?; 57 | packet.write_byte(1)?; 58 | 59 | Ok(packet) 60 | } 61 | 62 | pub fn build_guest_login_packet() -> Result { 63 | let mut packet = Packet::new_empty(); 64 | let opcode = GuestIdLogin as i16; 65 | 66 | let now: i64 = SystemTime::now() 67 | .duration_since(SystemTime::UNIX_EPOCH)? 68 | .as_secs() as i64; 69 | 70 | packet.write_short(opcode)?; 71 | packet.write_short(0x100)?; 72 | packet.write_int(0)?; // TODO: Should be random 73 | packet.write_long(0)?; 74 | packet.write_long(0)?; 75 | packet.write_long(now)?; 76 | packet.write_int(0)?; 77 | packet.write_str_with_length("https://github.com/neeerp")?; 78 | 79 | Ok(packet) 80 | } 81 | -------------------------------------------------------------------------------- /net/src/packet/build/login/world.rs: -------------------------------------------------------------------------------- 1 | use crate::{error::NetworkError, packet::op::SendOpcode}; 2 | use packet::{io::write::PktWrite, Packet}; 3 | 4 | pub fn build_end_of_world_list() -> Result { 5 | let mut packet = Packet::new_empty(); 6 | let op = SendOpcode::ServerList as i16; 7 | 8 | packet.write_short(op)?; 9 | packet.write_byte(0xFF)?; 10 | 11 | Ok(packet) 12 | } 13 | 14 | pub fn build_world_details() -> Result { 15 | let mut packet = Packet::new_empty(); 16 | let op = SendOpcode::ServerList as i16; 17 | 18 | let world_name = "Scania"; 19 | let server_id = 0; 20 | let flag = 0; 21 | let event_msg = "Test!"; 22 | 23 | packet.write_short(op)?; 24 | packet.write_byte(server_id)?; 25 | packet.write_str_with_length(world_name)?; 26 | packet.write_byte(flag)?; 27 | packet.write_str_with_length(event_msg)?; 28 | packet.write_byte(100)?; 29 | packet.write_byte(0)?; 30 | packet.write_byte(100)?; 31 | packet.write_byte(0)?; 32 | packet.write_byte(0)?; 33 | packet.write_byte(3)?; 34 | 35 | // Channel 1 info 36 | packet.write_str_with_length("Scania-1")?; 37 | packet.write_int(700)?; 38 | packet.write_byte(1)?; 39 | packet.write_byte(0)?; 40 | packet.write_byte(0)?; 41 | 42 | packet.write_str_with_length("Scania-2")?; 43 | packet.write_int(700)?; 44 | packet.write_byte(1)?; 45 | packet.write_byte(1)?; 46 | packet.write_byte(0)?; 47 | 48 | packet.write_str_with_length("Scania-3")?; 49 | packet.write_int(700)?; 50 | packet.write_byte(1)?; 51 | packet.write_byte(2)?; 52 | packet.write_byte(0)?; 53 | 54 | packet.write_short(0)?; 55 | 56 | Ok(packet) 57 | } 58 | 59 | pub fn build_select_world() -> Result { 60 | let mut packet = Packet::new_empty(); 61 | let op = SendOpcode::LastConnectedWorld as i16; 62 | 63 | packet.write_short(op)?; 64 | packet.write_int(0)?; 65 | 66 | Ok(packet) 67 | } 68 | 69 | pub fn build_send_recommended_worlds() -> Result { 70 | let mut packet = Packet::new_empty(); 71 | let op = SendOpcode::RecommendedWorlds as i16; 72 | 73 | packet.write_short(op)?; 74 | packet.write_byte(1)?; // No worlds recommended 75 | packet.write_int(0)?; 76 | packet.write_int(0)?; 77 | 78 | Ok(packet) 79 | } 80 | 81 | pub fn build_server_status(status: i16) -> Result { 82 | let mut packet = Packet::new_empty(); 83 | let op = SendOpcode::ServerStatus as i16; 84 | 85 | packet.write_short(op)?; 86 | packet.write_short(status)?; // Highly populated status! 87 | 88 | Ok(packet) 89 | } 90 | 91 | pub fn build_server_redirect(cid: i32) -> Result { 92 | let mut packet = Packet::new_empty(); 93 | let op = SendOpcode::ServerIp as i16; 94 | 95 | let server_ip = vec![127, 0, 0, 1]; 96 | let server_port = 8485; 97 | 98 | packet.write_short(op)?; 99 | packet.write_short(0)?; 100 | 101 | packet.write_bytes(&server_ip)?; 102 | packet.write_short(server_port)?; 103 | packet.write_int(cid)?; 104 | 105 | packet.write_bytes(&vec![0u8; 5])?; 106 | 107 | Ok(packet) 108 | } 109 | -------------------------------------------------------------------------------- /net/src/packet/build/mod.rs: -------------------------------------------------------------------------------- 1 | mod handshake; 2 | pub mod login; 3 | pub mod world; 4 | 5 | pub use self::handshake::build_handshake_packet; 6 | -------------------------------------------------------------------------------- /net/src/packet/build/world/char.rs: -------------------------------------------------------------------------------- 1 | use crate::{error::NetworkError, packet::op::SendOpcode}; 2 | use db::character::Character; 3 | use packet::{io::write::PktWrite, Packet}; 4 | 5 | use std::time::{SystemTime, UNIX_EPOCH}; 6 | 7 | // TODO: This is just a barebones implementation. 8 | pub fn _build_update_buddy_list() -> Result { 9 | let mut packet = Packet::new_empty(); 10 | 11 | let op = SendOpcode::SetField as i16; 12 | packet.write_short(op)?; 13 | 14 | packet.write_byte(7)?; 15 | packet.write_byte(0)?; 16 | 17 | Ok(packet) 18 | } 19 | 20 | // TODO: This is just a barebones implementation. 21 | pub fn _build_load_family(_character: &Character) -> Result { 22 | let mut packet = Packet::new_empty(); 23 | 24 | let op = SendOpcode::SetField as i16; 25 | packet.write_short(op)?; 26 | 27 | packet.write_int(0)?; 28 | 29 | Ok(packet) 30 | } 31 | 32 | pub fn _build_family_info() -> Result { 33 | let mut packet = Packet::new_empty(); 34 | 35 | let op = SendOpcode::FamilyInfo as i16; 36 | packet.write_short(op)?; 37 | 38 | packet.write_int(0)?; 39 | packet.write_int(0)?; 40 | packet.write_int(0)?; 41 | packet.write_short(0)?; 42 | packet.write_short(2)?; 43 | packet.write_short(0)?; 44 | packet.write_int(0)?; 45 | packet.write_str_with_length("")?; 46 | packet.write_str_with_length("")?; 47 | packet.write_int(0)?; 48 | 49 | Ok(packet) 50 | } 51 | 52 | pub fn build_char_info(character: &Character) -> Result { 53 | let mut packet = Packet::new_empty(); 54 | 55 | let op = SendOpcode::SetField as i16; 56 | packet.write_short(op)?; 57 | 58 | let channel = 0; 59 | packet.write_int(channel)?; 60 | 61 | packet.write_byte(1)?; 62 | packet.write_byte(1)?; 63 | packet.write_short(0)?; 64 | 65 | // These are random... No idea what they are though. 66 | packet.write_int(1)?; 67 | packet.write_int(2)?; 68 | packet.write_int(3)?; 69 | 70 | write_char(&mut packet, &character)?; 71 | 72 | let time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as i64; 73 | packet.write_long(time)?; 74 | 75 | Ok(packet) 76 | } 77 | 78 | fn write_char(packet: &mut Packet, character: &Character) -> Result<(), NetworkError> { 79 | packet.write_long(-1)?; 80 | packet.write_byte(0)?; 81 | 82 | write_char_meta(packet, character)?; 83 | 84 | let bl_capacity = 25; 85 | packet.write_byte(bl_capacity)?; 86 | 87 | packet.write_byte(0)?; 88 | 89 | packet.write_int(character.meso)?; 90 | 91 | write_inventory(packet, character)?; 92 | write_skills(packet, character)?; 93 | write_quests(packet, character)?; 94 | write_minigames(packet, character)?; 95 | write_rings(packet, character)?; 96 | write_teleport(packet, character)?; 97 | write_codex(packet, character)?; 98 | write_new_year_cards(packet, character)?; 99 | write_area_info(packet, character)?; 100 | 101 | packet.write_byte(0)?; 102 | 103 | Ok(()) 104 | } 105 | 106 | /// Write the equiped items and the inventory of the player 107 | fn write_inventory(packet: &mut Packet, _character: &Character) -> Result<(), NetworkError> { 108 | // Inventory slot Capacities 109 | packet.write_bytes(&vec![0u8; 5])?; 110 | 111 | // Time? 112 | packet.write_long(0)?; 113 | 114 | // Equiped items go here 115 | 116 | // Start of equiped cash items 117 | packet.write_short(0)?; 118 | 119 | // Start of equiped inventory 120 | packet.write_short(0)?; 121 | 122 | // Start of USE 123 | packet.write_int(0)?; 124 | 125 | // Start of SETUP 126 | packet.write_byte(0)?; 127 | 128 | // Start of ETC 129 | packet.write_byte(0)?; 130 | 131 | // Start of CASH 132 | packet.write_byte(0)?; 133 | 134 | Ok(()) 135 | } 136 | 137 | fn write_skills(packet: &mut Packet, _character: &Character) -> Result<(), NetworkError> { 138 | // Start of skills 139 | packet.write_byte(0)?; 140 | 141 | // No skills! 142 | packet.write_short(0)?; 143 | 144 | // No no cooldowns! 145 | packet.write_short(0)?; 146 | 147 | Ok(()) 148 | } 149 | 150 | fn write_quests(packet: &mut Packet, _character: &Character) -> Result<(), NetworkError> { 151 | let started_quests = 0; 152 | packet.write_short(started_quests)?; 153 | 154 | let completed_quests = 0; 155 | packet.write_short(completed_quests)?; 156 | 157 | Ok(()) 158 | } 159 | 160 | fn write_minigames(packet: &mut Packet, _character: &Character) -> Result<(), NetworkError> { 161 | // This ones required but kinda useless... 162 | packet.write_short(0)?; 163 | Ok(()) 164 | } 165 | 166 | fn write_rings(packet: &mut Packet, _character: &Character) -> Result<(), NetworkError> { 167 | let num_crush_rings = 0; 168 | let num_friendship_rings = 0; 169 | packet.write_short(num_crush_rings)?; 170 | packet.write_short(num_friendship_rings)?; 171 | 172 | // Not married 173 | packet.write_short(0)?; 174 | 175 | Ok(()) 176 | } 177 | 178 | fn write_teleport(packet: &mut Packet, _character: &Character) -> Result<(), NetworkError> { 179 | // Regular tele rock locations 180 | for _ in 0..5 { 181 | packet.write_int(0)?; 182 | } 183 | 184 | // VIP tele rock locations 185 | for _ in 0..10 { 186 | packet.write_int(0)?; 187 | } 188 | 189 | Ok(()) 190 | } 191 | 192 | fn write_codex(packet: &mut Packet, _character: &Character) -> Result<(), NetworkError> { 193 | let codex_cover = 1; 194 | let num_cards = 0; 195 | 196 | packet.write_int(codex_cover)?; 197 | packet.write_byte(0)?; 198 | packet.write_short(num_cards)?; 199 | 200 | Ok(()) 201 | } 202 | 203 | // I have literally no idea what these are... 204 | fn write_new_year_cards(packet: &mut Packet, _character: &Character) -> Result<(), NetworkError> { 205 | let num_cards = 0; 206 | packet.write_short(num_cards)?; 207 | Ok(()) 208 | } 209 | 210 | fn write_area_info(packet: &mut Packet, _character: &Character) -> Result<(), NetworkError> { 211 | let num_areas = 0; 212 | packet.write_short(num_areas)?; 213 | Ok(()) 214 | } 215 | 216 | fn write_char_meta(packet: &mut Packet, character: &Character) -> Result<(), NetworkError> { 217 | packet.write_int(character.id)?; 218 | packet.write_str(&character.name)?; 219 | packet.write_bytes(&vec![0u8; 13 - character.name.len()])?; 220 | packet.write_byte(character.gender as u8)?; 221 | packet.write_byte(character.skin as u8)?; 222 | packet.write_int(character.face)?; 223 | packet.write_int(character.hair)?; 224 | 225 | // Pets... Not implemented yet 226 | packet.write_long(0)?; 227 | packet.write_long(0)?; 228 | packet.write_long(0)?; 229 | 230 | packet.write_byte(character.level as u8)?; 231 | packet.write_short(character.job)?; 232 | 233 | packet.write_short(character.stre)?; 234 | packet.write_short(character.dex)?; 235 | packet.write_short(character.int)?; 236 | packet.write_short(character.luk)?; 237 | packet.write_short(character.hp)?; 238 | packet.write_short(character.maxhp)?; 239 | packet.write_short(character.mp)?; 240 | packet.write_short(character.maxmp)?; 241 | packet.write_short(character.ap)?; 242 | 243 | // SP 244 | packet.write_short(0)?; 245 | 246 | packet.write_int(character.exp)?; 247 | packet.write_short(character.fame)?; 248 | 249 | // Gach xp? 250 | packet.write_int(0)?; 251 | 252 | packet.write_int(character.map_id)?; 253 | packet.write_byte(0)?; 254 | 255 | packet.write_int(0)?; 256 | 257 | Ok(()) 258 | } 259 | -------------------------------------------------------------------------------- /net/src/packet/build/world/keymap.rs: -------------------------------------------------------------------------------- 1 | use crate::{error::NetworkError, packet::op::SendOpcode}; 2 | use db::keybinding::KeybindSet; 3 | use packet::{io::write::PktWrite, Packet}; 4 | 5 | pub fn build_keymap(binds: &mut KeybindSet) -> Result { 6 | let mut packet = Packet::new_empty(); 7 | 8 | let op = SendOpcode::KeyMap as i16; 9 | packet.write_short(op)?; 10 | packet.write_byte(0)?; 11 | 12 | for i in 0..90 { 13 | let bind = binds.get(i); 14 | packet.write_byte(bind.bind_type.into())?; 15 | packet.write_int(bind.action as i32)?; 16 | } 17 | 18 | Ok(packet) 19 | } 20 | -------------------------------------------------------------------------------- /net/src/packet/build/world/map.rs: -------------------------------------------------------------------------------- 1 | use db::character::Character; 2 | use packet::{io::write::PktWrite, Packet}; 3 | 4 | use crate::{error::NetworkError, helpers, packet::op::SendOpcode}; 5 | 6 | pub fn build_warp_to_map(character: &Character, map_id: i32) -> Result { 7 | let mut packet = Packet::new_empty(); 8 | let op = SendOpcode::SetField as i16; 9 | packet.write_short(op)?; 10 | 11 | let channel = 0; 12 | let spawn_point = 0; 13 | let hp = character.hp; 14 | let use_spawn_pos = 0; // If this was non 0, we'd need to provide an x,y 15 | 16 | packet.write_int(channel)?; 17 | 18 | // padding? 19 | packet.write_int(0)?; 20 | packet.write_byte(0)?; 21 | 22 | packet.write_int(map_id)?; 23 | packet.write_byte(spawn_point)?; 24 | packet.write_short(hp)?; 25 | packet.write_byte(use_spawn_pos)?; 26 | packet.write_long(helpers::current_time_i64()?)?; 27 | 28 | Ok(packet) 29 | } 30 | 31 | pub fn build_empty_stat_update() -> Result { 32 | let mut packet = Packet::new_empty(); 33 | let op = SendOpcode::StatChange as i16; 34 | packet.write_short(op)?; 35 | packet.write_byte(1)?; 36 | packet.write_int(0)?; 37 | 38 | Ok(packet) 39 | } 40 | -------------------------------------------------------------------------------- /net/src/packet/build/world/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod char; 2 | pub mod keymap; 3 | pub mod map; 4 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/char/char_list.rs: -------------------------------------------------------------------------------- 1 | use crate::packet::build::login::char; 2 | use crate::{error::NetworkError, io::client::MapleClient, packet::handle::PacketHandler}; 3 | use db::character; 4 | use packet::io::read::PktRead; 5 | use packet::Packet; 6 | use std::io::BufReader; 7 | 8 | pub struct CharListHandler {} 9 | 10 | impl CharListHandler { 11 | pub fn new() -> Self { 12 | CharListHandler {} 13 | } 14 | } 15 | 16 | impl PacketHandler for CharListHandler { 17 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 18 | let mut reader = BufReader::new(&**packet); 19 | reader.read_short()?; 20 | 21 | let _world = reader.read_byte()?; 22 | let _channel = reader.read_byte()? + 1; 23 | 24 | let user = client.get_account(); 25 | let id = match user { 26 | Some(user) => user.id, 27 | None => return Err(NetworkError::PacketHandlerError("User not logged in.")), 28 | }; 29 | 30 | let chars = character::get_characters_by_accountid(id)?; 31 | client.send(&mut char::build_char_list(chars)?) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/char/check_name.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, 3 | io::client::MapleClient, 4 | packet::{build, handle::PacketHandler}, 5 | }; 6 | use build::login; 7 | use packet::{io::read::PktRead, Packet}; 8 | use std::io::BufReader; 9 | 10 | pub struct CheckCharNameHandler {} 11 | 12 | impl CheckCharNameHandler { 13 | pub fn new() -> Self { 14 | CheckCharNameHandler {} 15 | } 16 | 17 | fn check_name(&self, name: &str) -> Result { 18 | match db::character::get_character_by_name(&name) { 19 | Ok(_) => Ok(false), 20 | Err(db::Error::NotFound) => Ok(true), 21 | Err(e) => Err(NetworkError::DbError(e)), 22 | } 23 | } 24 | } 25 | 26 | impl PacketHandler for CheckCharNameHandler { 27 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 28 | let mut reader = BufReader::new(&**packet); 29 | reader.read_short()?; 30 | 31 | let name = reader.read_str_with_length()?; 32 | 33 | client.send(&mut login::char::build_char_name_response( 34 | &name, 35 | self.check_name(&name)?, 36 | )?) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/char/create.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, 3 | io::client::MapleClient, 4 | packet::{build, handle::PacketHandler}, 5 | }; 6 | use build::login; 7 | use db::character::NewCharacter; 8 | use packet::{io::read::PktRead, Packet}; 9 | use std::io::BufReader; 10 | 11 | pub struct CreateCharacterHandler {} 12 | 13 | impl CreateCharacterHandler { 14 | pub fn new() -> Self { 15 | CreateCharacterHandler {} 16 | } 17 | } 18 | 19 | impl PacketHandler for CreateCharacterHandler { 20 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 21 | let mut reader = BufReader::new(&**packet); 22 | reader.read_short()?; 23 | 24 | let user = client.get_account(); 25 | let accountid: i32; 26 | 27 | if let Some(acc) = user { 28 | accountid = acc.id; 29 | } else { 30 | return Err(NetworkError::NotLoggedIn); 31 | } 32 | 33 | let name = &reader.read_str_with_length()?; 34 | let job = reader.read_int()? as i16; 35 | let face = reader.read_int()?; 36 | let hair = reader.read_int()?; 37 | let hair_color = reader.read_int()?; 38 | let skin = reader.read_int()?; 39 | let _top = reader.read_int()?; // Slot 5 40 | let _bot = reader.read_int()?; // Slot 6 41 | let _shoes = reader.read_int()?; // Slot 7 42 | let _weapon = reader.read_int()?; // Special 43 | let gender = reader.read_byte()? as i16; 44 | 45 | let world = 0; 46 | 47 | let character = NewCharacter { 48 | accountid, 49 | world, 50 | name, 51 | job, 52 | face, 53 | hair, 54 | hair_color, 55 | skin, 56 | gender, 57 | }; 58 | 59 | client.send(&mut login::char::build_char_packet( 60 | character.create()?.character, 61 | )?) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/char/delete.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, 3 | io::client::MapleClient, 4 | packet::{build, handle::PacketHandler}, 5 | }; 6 | use build::login; 7 | use db::character; 8 | use packet::{io::read::PktRead, Packet}; 9 | use std::io::BufReader; 10 | 11 | pub struct DeleteCharHandler {} 12 | 13 | impl DeleteCharHandler { 14 | pub fn new() -> Self { 15 | DeleteCharHandler {} 16 | } 17 | } 18 | 19 | impl PacketHandler for DeleteCharHandler { 20 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 21 | let mut reader = BufReader::new(&**packet); 22 | reader.read_short()?; 23 | 24 | let _pic = reader.read_str_with_length()?; 25 | let character_id = reader.read_int()?; 26 | 27 | let user = client.get_account(); 28 | let accountid: i32; 29 | 30 | if let Some(acc) = user { 31 | accountid = acc.id; 32 | } else { 33 | return Err(NetworkError::NotLoggedIn); 34 | } 35 | 36 | match character::delete_character(character_id, accountid) { 37 | Ok(_) => client.send(&mut login::char::build_char_delete(character_id, 0x00)?), 38 | Err(_) => Err(NetworkError::PacketHandlerError( 39 | "Could not delete character", 40 | )), 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/char/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod char_list; 2 | pub mod check_name; 3 | pub mod create; 4 | pub mod delete; 5 | pub mod select; 6 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/char/select.rs: -------------------------------------------------------------------------------- 1 | use crate::packet::{build, handle::PacketHandler}; 2 | use packet::io::read::PktRead; 3 | use std::io::BufReader; 4 | 5 | pub struct CharacterSelectHandler {} 6 | 7 | impl CharacterSelectHandler { 8 | pub fn new() -> Self { 9 | Self {} 10 | } 11 | } 12 | 13 | impl PacketHandler for CharacterSelectHandler { 14 | fn handle( 15 | &self, 16 | packet: &mut packet::Packet, 17 | client: &mut crate::io::client::MapleClient, 18 | ) -> Result<(), crate::error::NetworkError> { 19 | let mut reader = BufReader::new(&**packet); 20 | 21 | let _op = reader.read_short()?; 22 | let cid = reader.read_int()?; 23 | let _mac = reader.read_str_with_length(); 24 | let _hwid = reader.read_str_with_length(); 25 | 26 | client.transition(cid)?; 27 | 28 | println!("Redirecting to port 8485!"); 29 | client.send(&mut build::login::world::build_server_redirect(cid)?) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/main/accept_tos.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, 3 | io::client::MapleClient, 4 | packet::{build, handle::PacketHandler}, 5 | }; 6 | use account::Account; 7 | use db::account; 8 | use packet::{io::read::PktRead, Packet}; 9 | use std::io::BufReader; 10 | 11 | pub struct AcceptTOSHandler {} 12 | 13 | impl AcceptTOSHandler { 14 | pub fn new() -> Self { 15 | AcceptTOSHandler {} 16 | } 17 | 18 | fn accept_logon(&self, client: &mut MapleClient, acc: Account) -> Result<(), NetworkError> { 19 | client.complete_login()?; 20 | 21 | let mut packet = build::login::status::build_successful_login_packet(&acc)?; 22 | Ok(client.send(&mut packet)?) 23 | } 24 | } 25 | 26 | impl PacketHandler for AcceptTOSHandler { 27 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 28 | let mut reader = BufReader::new(&**packet); 29 | reader.read_short()?; 30 | 31 | let confirmed = reader.read_byte()?; 32 | let user = client.get_account(); 33 | 34 | match (confirmed, user) { 35 | (0x01, Some(mut user)) => { 36 | user.accepted_tos = true; 37 | 38 | let user = account::update_account(&user)?; 39 | 40 | self.accept_logon(client, user) 41 | } 42 | _ => Err(NetworkError::PacketHandlerError( 43 | "Accept TOS packet is invalid.", 44 | )), 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/main/guest_login.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, 3 | io::client::MapleClient, 4 | listener::ServerType, 5 | packet::{ 6 | build, 7 | handle::{get_handler, PacketHandler}, 8 | op::RecvOpcode, 9 | }, 10 | }; 11 | use packet::Packet; 12 | 13 | pub struct GuestLoginHandler {} 14 | 15 | /// A handler for guest logins...? 16 | impl GuestLoginHandler { 17 | pub fn new() -> Self { 18 | GuestLoginHandler {} 19 | } 20 | } 21 | 22 | impl PacketHandler for GuestLoginHandler { 23 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 24 | client.send(&mut build::login::status::build_guest_login_packet()?)?; 25 | 26 | get_handler(RecvOpcode::LoginCredentials as i16, &ServerType::Login).handle(packet, client) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/main/login.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, 3 | helpers::to_hex_string, 4 | io::client::MapleClient, 5 | packet::{build, handle::PacketHandler}, 6 | }; 7 | use crypt::login; 8 | use db::{ 9 | account::{self, Account}, 10 | session::SessionState, 11 | }; 12 | use packet::{io::read::PktRead, Packet}; 13 | use std::io::BufReader; 14 | 15 | pub struct LoginCredentialsHandler {} 16 | 17 | // TODO: These methods could use some better error handling. 18 | 19 | /// A handler for login attempt packets. 20 | impl LoginCredentialsHandler { 21 | pub fn new() -> Self { 22 | LoginCredentialsHandler {} 23 | } 24 | 25 | /////// IO /////// 26 | 27 | /// Read the username, password, and HWID from the packet. 28 | fn read_credentials( 29 | &self, 30 | packet: &mut Packet, 31 | ) -> Result<(String, String, String), NetworkError> { 32 | let mut reader = BufReader::new(&**packet); 33 | 34 | reader.read_short()?; // prune opcode 35 | 36 | let user = reader.read_str_with_length()?; 37 | let pw = reader.read_str_with_length()?; 38 | 39 | reader.read_bytes(6)?; // prune padding 40 | 41 | let hwid = to_hex_string(&reader.read_bytes(4)?); 42 | 43 | Ok((user, pw, hwid)) 44 | } 45 | 46 | /////// Get Account /////// 47 | 48 | /// Attempt to get an account, either by logging into the one corresponding 49 | /// to the credentials, or creating one if the user name given is not taken. 50 | fn verify_and_get_account( 51 | &self, 52 | user: &str, 53 | pw: &str, 54 | ) -> Result, NetworkError> { 55 | match account::get_account(&user) { 56 | Ok(acc) => Ok(self.verify_password(acc, pw)), 57 | Err(db::Error::NotFound) => self.create_account(user, pw), 58 | Err(e) => Err(e.into()), 59 | } 60 | } 61 | 62 | /// Return the given account iff the given password matches. 63 | fn verify_password(&self, acc: Account, pw: &str) -> Option { 64 | match login::validate_against_hash(pw, &acc.password) { 65 | Ok(true) => { 66 | println!("Verified account with user '{}'", &acc.user_name); 67 | Some(acc) 68 | } 69 | _ => None, 70 | } 71 | } 72 | 73 | /// Create and save new account with the given username and password. 74 | fn create_account(&self, user: &str, pw: &str) -> Result, NetworkError> { 75 | let pw = crypt::login::hash_password(pw)?; 76 | let acc = account::create_account(user, &pw)?; 77 | 78 | println!("Created user '{}'", user); 79 | 80 | Ok(Some(acc)) 81 | } 82 | 83 | /// Attempt to log the user in. 84 | fn attempt_logon( 85 | &self, 86 | client: &mut MapleClient, 87 | acc: Account, 88 | hwid: &str, 89 | ) -> Result<(), NetworkError> { 90 | match self.check_account_status(&acc) { 91 | 0 => self.accept_logon(client, acc, hwid), 92 | 23 => self.send_tos(client, acc, hwid), 93 | status => self.reject_logon(client, status), 94 | } 95 | } 96 | 97 | fn check_account_status(&self, acc: &Account) -> u8 { 98 | if acc.banned { 99 | 2 100 | } else if acc.logged_in { 101 | 7 102 | } else if !acc.accepted_tos { 103 | 23 104 | } else { 105 | 0 106 | } 107 | } 108 | 109 | /// Log the user in. 110 | fn accept_logon( 111 | &self, 112 | client: &mut MapleClient, 113 | acc: Account, 114 | hwid: &str, 115 | ) -> Result<(), NetworkError> { 116 | let mut packet = &mut build::login::status::build_successful_login_packet(&acc)?; 117 | 118 | client.login(acc.id, hwid, SessionState::AfterLogin)?; 119 | 120 | client.send(&mut packet) 121 | } 122 | 123 | /// Have the user accept the TOS. 124 | fn send_tos( 125 | &self, 126 | client: &mut MapleClient, 127 | acc: Account, 128 | hwid: &str, 129 | ) -> Result<(), NetworkError> { 130 | client.login(acc.id, hwid, SessionState::BeforeLogin)?; 131 | 132 | client.send(&mut build::login::status::build_login_status_packet(23)?) 133 | } 134 | 135 | /// Return a reason for why the user could not log in. 136 | fn reject_logon(&self, client: &mut MapleClient, status: u8) -> Result<(), NetworkError> { 137 | client.send(&mut build::login::status::build_login_status_packet( 138 | status, 139 | )?) 140 | } 141 | } 142 | 143 | impl PacketHandler for LoginCredentialsHandler { 144 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 145 | println!("Login attempted..."); 146 | let (user, pw, hwid) = self.read_credentials(packet)?; 147 | match self.verify_and_get_account(&user, &pw)? { 148 | Some(acc) => self.attempt_logon(client, acc, &hwid), 149 | None => self.reject_logon(client, 4), 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/main/login_start.rs: -------------------------------------------------------------------------------- 1 | use crate::{error::NetworkError, io::client::MapleClient, packet::handle::PacketHandler}; 2 | use packet::Packet; 3 | 4 | pub struct LoginStartHandler {} 5 | 6 | /// A handler for the empty 'login started' packet. 7 | impl LoginStartHandler { 8 | pub fn new() -> Self { 9 | LoginStartHandler {} 10 | } 11 | 12 | fn check_length(&self, packet: &Packet) -> Result<(), NetworkError> { 13 | if packet.len() != 0 { 14 | Err(NetworkError::PacketHandlerError( 15 | "Start login packet has invalid length.", 16 | )) 17 | } else { 18 | println!("Login started."); 19 | Ok(()) 20 | } 21 | } 22 | } 23 | 24 | impl PacketHandler for LoginStartHandler { 25 | fn handle(&self, packet: &mut Packet, _client: &mut MapleClient) -> Result<(), NetworkError> { 26 | self.check_length(packet) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/main/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod accept_tos; 2 | pub mod guest_login; 3 | pub mod login; 4 | pub mod login_start; 5 | pub mod set_gender; 6 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/main/set_gender.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, 3 | io::client::MapleClient, 4 | packet::{build, handle::PacketHandler}, 5 | }; 6 | use account::Account; 7 | use db::account; 8 | use packet::{io::read::PktRead, Packet}; 9 | use std::io::BufReader; 10 | 11 | pub struct SetGenderHandler {} 12 | 13 | impl SetGenderHandler { 14 | pub fn new() -> Self { 15 | SetGenderHandler {} 16 | } 17 | 18 | fn accept_logon(&self, client: &mut MapleClient, acc: Account) -> Result<(), NetworkError> { 19 | client.complete_login()?; 20 | let mut packet = &mut build::login::status::build_successful_login_packet(&acc)?; 21 | 22 | client.send(&mut packet) 23 | } 24 | } 25 | 26 | impl PacketHandler for SetGenderHandler { 27 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 28 | let mut reader = BufReader::new(&**packet); 29 | reader.read_short()?; 30 | 31 | let confirmed = reader.read_byte()?; 32 | let user = client.get_account(); 33 | 34 | match (confirmed, user) { 35 | (0x01, Some(mut user)) => { 36 | let gender = reader.read_byte()?; 37 | user.gender = gender as i16; 38 | 39 | let user = account::update_account(&user)?; 40 | 41 | self.accept_logon(client, user) 42 | } 43 | _ => Err(NetworkError::PacketHandlerError( 44 | "Set Gender packet is invalid.", 45 | )), 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/mod.rs: -------------------------------------------------------------------------------- 1 | mod char; 2 | mod main; 3 | mod world; 4 | 5 | pub use self::char::char_list::CharListHandler; 6 | pub use self::char::check_name::CheckCharNameHandler; 7 | pub use self::char::create::CreateCharacterHandler; 8 | pub use self::char::delete::DeleteCharHandler; 9 | pub use self::char::select::CharacterSelectHandler; 10 | pub use self::main::accept_tos::AcceptTOSHandler; 11 | pub use self::main::guest_login::GuestLoginHandler; 12 | pub use self::main::login::LoginCredentialsHandler; 13 | pub use self::main::login_start::LoginStartHandler; 14 | pub use self::main::set_gender::SetGenderHandler; 15 | pub use self::world::server_status::ServerStatusHandler; 16 | pub use self::world::world_list::WorldListHandler; 17 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/world/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod server_status; 2 | pub mod world_list; 3 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/world/server_status.rs: -------------------------------------------------------------------------------- 1 | use crate::error::NetworkError; 2 | use crate::helpers::to_hex_string; 3 | use crate::io::client::MapleClient; 4 | use crate::packet::build::login::world; 5 | use crate::packet::handle::PacketHandler; 6 | use packet::Packet; 7 | 8 | pub struct ServerStatusHandler {} 9 | 10 | impl ServerStatusHandler { 11 | pub fn new() -> ServerStatusHandler { 12 | ServerStatusHandler {} 13 | } 14 | } 15 | 16 | impl PacketHandler for ServerStatusHandler { 17 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 18 | to_hex_string(&packet.bytes); 19 | 20 | client.send(&mut world::build_server_status(1)?) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /net/src/packet/handle/login/world/world_list.rs: -------------------------------------------------------------------------------- 1 | use crate::packet::build::login::world; 2 | use crate::{ 3 | error::NetworkError, helpers::to_hex_string, io::client::MapleClient, 4 | packet::handle::PacketHandler, 5 | }; 6 | use packet::Packet; 7 | 8 | pub struct WorldListHandler {} 9 | 10 | impl WorldListHandler { 11 | pub fn new() -> Self { 12 | WorldListHandler {} 13 | } 14 | } 15 | 16 | impl PacketHandler for WorldListHandler { 17 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 18 | to_hex_string(&packet.bytes); 19 | 20 | client.send(&mut world::build_world_details()?)?; 21 | client.send(&mut world::build_end_of_world_list()?)?; 22 | client.send(&mut world::build_select_world()?)?; // HeavenClient ignores this... 23 | client.send(&mut world::build_send_recommended_worlds()?) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /net/src/packet/handle/mod.rs: -------------------------------------------------------------------------------- 1 | use super::op::RecvOpcode; 2 | use crate::{ 3 | error::NetworkError, helpers::to_hex_string, io::client::MapleClient, listener::ServerType, 4 | }; 5 | use packet::Packet; 6 | 7 | mod login; 8 | mod world; 9 | 10 | pub trait PacketHandler { 11 | fn handle(&self, packet: &mut Packet, _client: &mut MapleClient) -> Result<(), NetworkError> { 12 | let op = packet.opcode(); 13 | println!("Opcode: {}", op); 14 | println!("Received packet: {}", to_hex_string(&packet.bytes)); 15 | Err(NetworkError::UnsupportedOpcodeError(op)) 16 | } 17 | } 18 | 19 | pub struct DefaultHandler {} 20 | 21 | impl PacketHandler for DefaultHandler {} 22 | 23 | /// A default handler that echoes the packet in the console and throws an error. 24 | impl DefaultHandler { 25 | pub fn new() -> Self { 26 | DefaultHandler {} 27 | } 28 | } 29 | 30 | // TODO: A lot of the login related handlers are very similar and can maybe be 31 | // consolidated, making a check on the opcode to decide how to proceed... These 32 | // handlers include the LoginCredentials handler, AcceptTOS handler, 33 | // SetGenderHandler 34 | // 35 | 36 | pub fn get_handler(op: i16, server_type: &ServerType) -> Box { 37 | match server_type { 38 | ServerType::Login => get_login_handler(op), 39 | ServerType::World => get_world_handler(op), 40 | } 41 | } 42 | 43 | /// Get the packet handler corresponding to the given opcode. 44 | fn get_login_handler(op: i16) -> Box { 45 | match num::FromPrimitive::from_i16(op) { 46 | Some(RecvOpcode::LoginCredentials) => Box::new(login::LoginCredentialsHandler::new()), 47 | Some(RecvOpcode::GuestLogin) => Box::new(login::GuestLoginHandler::new()), 48 | 49 | Some(RecvOpcode::ServerListReRequest) => Box::new(login::WorldListHandler::new()), 50 | Some(RecvOpcode::CharListRequest) => Box::new(login::CharListHandler::new()), 51 | Some(RecvOpcode::ServerStatusRequest) => Box::new(login::ServerStatusHandler::new()), 52 | 53 | Some(RecvOpcode::AcceptTOS) => Box::new(login::AcceptTOSHandler::new()), 54 | Some(RecvOpcode::SetGender) => Box::new(login::SetGenderHandler::new()), 55 | 56 | // TODO: HeavenClient doesn't seem to support PINs... 57 | Some(RecvOpcode::AfterLogin) => Box::new(DefaultHandler::new()), 58 | Some(RecvOpcode::RegisterPin) => Box::new(DefaultHandler::new()), 59 | 60 | Some(RecvOpcode::ServerListRequest) => Box::new(login::WorldListHandler::new()), 61 | 62 | Some(RecvOpcode::ViewAllChar) => Box::new(DefaultHandler::new()), 63 | Some(RecvOpcode::PickAllChar) => Box::new(DefaultHandler::new()), 64 | Some(RecvOpcode::CharSelect) => Box::new(login::CharacterSelectHandler::new()), 65 | 66 | Some(RecvOpcode::CheckCharName) => Box::new(login::CheckCharNameHandler::new()), 67 | Some(RecvOpcode::CreateChar) => Box::new(login::CreateCharacterHandler::new()), 68 | 69 | Some(RecvOpcode::DeleteChar) => Box::new(login::DeleteCharHandler::new()), 70 | 71 | Some(RecvOpcode::RegisterPic) => Box::new(DefaultHandler::new()), 72 | Some(RecvOpcode::CharSelectWithPic) => Box::new(DefaultHandler::new()), 73 | Some(RecvOpcode::ViewAllPicRegister) => Box::new(DefaultHandler::new()), 74 | Some(RecvOpcode::ViewAllWithPic) => Box::new(DefaultHandler::new()), 75 | 76 | Some(RecvOpcode::LoginStarted) => Box::new(login::LoginStartHandler::new()), 77 | 78 | None | Some(_) => Box::new(DefaultHandler::new()), 79 | } 80 | } 81 | 82 | fn get_world_handler(op: i16) -> Box { 83 | match num::FromPrimitive::from_i16(op) { 84 | Some(RecvOpcode::PlayerMove) => Box::new(world::PlayerMoveHandler::new()), 85 | Some(RecvOpcode::PlayerLoggedIn) => Box::new(world::PlayerLoggedInHandler::new()), 86 | Some(RecvOpcode::PlayerMapTransfer) => Box::new(world::PlayerMapTransferHandler::new()), 87 | Some(RecvOpcode::ChangeMap) => Box::new(world::ChangeMapHandler::new()), 88 | Some(RecvOpcode::PartySearch) => Box::new(world::PartySearchHandler::new()), 89 | Some(RecvOpcode::ChangeKeybinds) => Box::new(world::ChangeKeybindsHandler::new()), 90 | Some(RecvOpcode::AllChat) => Box::new(world::AllChatHandler::new()), 91 | 92 | None | Some(_) => Box::new(DefaultHandler::new()), 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /net/src/packet/handle/world/change_map.rs: -------------------------------------------------------------------------------- 1 | use std::io::BufReader; 2 | 3 | use packet::{io::read::PktRead, Packet}; 4 | 5 | use crate::{ 6 | error::NetworkError, io::client::MapleClient, packet::build, packet::handle::PacketHandler, 7 | }; 8 | 9 | pub struct ChangeMapHandler {} 10 | 11 | impl ChangeMapHandler { 12 | pub fn new() -> Self { 13 | Self {} 14 | } 15 | } 16 | 17 | impl PacketHandler for ChangeMapHandler { 18 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 19 | let mut reader = BufReader::new(&**packet); 20 | let _op = reader.read_short()?; 21 | 22 | reader.read_byte()?; 23 | let target = reader.read_int()?; 24 | let _x = reader.read_str_with_length()?; 25 | 26 | reader.read_byte()?; // Padding 27 | 28 | let _wheel_of_destiny = reader.read_short()? > 0; 29 | 30 | let character = client.session.get_character()?; 31 | let mut character = &mut character.borrow_mut().character; 32 | 33 | if target != -1 { 34 | character.map_id = target; 35 | character.save()?; 36 | 37 | client.send(&mut build::world::map::build_warp_to_map( 38 | &character, target, 39 | )?)?; 40 | } 41 | 42 | client.send(&mut build::world::map::build_empty_stat_update()?) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /net/src/packet/handle/world/chat.rs: -------------------------------------------------------------------------------- 1 | use crate::{error::NetworkError, io::client::MapleClient, packet::handle::PacketHandler}; 2 | use packet::{io::read::PktRead, Packet}; 3 | use std::io::BufReader; 4 | 5 | pub struct AllChatHandler {} 6 | 7 | impl AllChatHandler { 8 | pub fn new() -> Self { 9 | Self {} 10 | } 11 | } 12 | 13 | // TODO: Serious implementation later... 14 | impl PacketHandler for AllChatHandler { 15 | fn handle(&self, packet: &mut Packet, _client: &mut MapleClient) -> Result<(), NetworkError> { 16 | let mut reader = BufReader::new(&**packet); 17 | let _op = reader.read_short()?; 18 | 19 | // TODO: We have yet to actually save the character with the session! 20 | let msg = reader.read_str_with_length()?; 21 | println!("Somebody said: {}", msg); 22 | 23 | let _hidden = reader.read_byte()?; 24 | 25 | // TODO: One of the first "Server actions" we can try to implement is 26 | // TODO: perhaps sending chat messages to every player on a given map? 27 | 28 | Ok(()) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /net/src/packet/handle/world/keybinds.rs: -------------------------------------------------------------------------------- 1 | use crate::{error::NetworkError, io::client::MapleClient, packet::handle::PacketHandler}; 2 | use db::keybinding::KeybindType; 3 | use packet::{io::read::PktRead, Packet}; 4 | use std::io::BufReader; 5 | 6 | pub struct ChangeKeybindsHandler {} 7 | 8 | impl ChangeKeybindsHandler { 9 | pub fn new() -> Self { 10 | Self {} 11 | } 12 | } 13 | 14 | // TODO: Serious implementation later... 15 | impl PacketHandler for ChangeKeybindsHandler { 16 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 17 | let mut reader = BufReader::new(&**packet); 18 | reader.read_short()?; // prune op 19 | 20 | if packet.len() < 2 { 21 | return Ok(()); 22 | } 23 | 24 | let character = client.session.get_character()?; 25 | let mut character = character.borrow_mut(); 26 | if reader.read_int()? == 0 { 27 | for _ in 0..reader.read_int()? { 28 | let key = reader.read_int()? as i16; 29 | let bind_type: KeybindType = reader.read_byte()?.into(); 30 | let action = reader.read_int()? as i16; 31 | 32 | let mut bind = character.key_binds.get(key); 33 | bind.bind_type = bind_type; 34 | bind.action = action; 35 | character.key_binds.set(bind); 36 | } 37 | } 38 | 39 | Ok(character.key_binds.save()?) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /net/src/packet/handle/world/logged_in.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, 3 | io::client::MapleClient, 4 | packet::{build, handle::PacketHandler}, 5 | }; 6 | use db::character::CharacterWrapper; 7 | use packet::{io::read::PktRead, Packet}; 8 | use std::io::BufReader; 9 | 10 | pub struct PlayerLoggedInHandler {} 11 | 12 | impl PlayerLoggedInHandler { 13 | pub fn new() -> PlayerLoggedInHandler { 14 | PlayerLoggedInHandler {} 15 | } 16 | 17 | pub fn send_keybinds( 18 | &self, 19 | client: &mut MapleClient, 20 | chr: &mut CharacterWrapper, 21 | ) -> Result<(), NetworkError> { 22 | client.send(&mut build::world::keymap::build_keymap(&mut chr.key_binds)?) 23 | } 24 | 25 | pub fn send_character_data( 26 | &self, 27 | client: &mut MapleClient, 28 | chr: &CharacterWrapper, 29 | ) -> Result<(), NetworkError> { 30 | client.send(&mut build::world::char::build_char_info(&chr.character)?) 31 | } 32 | 33 | pub fn send_loaded_data( 34 | &self, 35 | client: &mut MapleClient, 36 | chr: &mut CharacterWrapper, 37 | ) -> Result<(), NetworkError> { 38 | self.send_keybinds(client, chr)?; 39 | self.send_character_data(client, chr) 40 | } 41 | } 42 | 43 | impl PacketHandler for PlayerLoggedInHandler { 44 | fn handle(&self, packet: &mut Packet, client: &mut MapleClient) -> Result<(), NetworkError> { 45 | let mut reader = BufReader::new(&**packet); 46 | reader.read_short()?; // prune opcode 47 | 48 | let character_id = reader.read_int()?; 49 | client.reattach(character_id)?; 50 | 51 | match client.session.get_character() { 52 | Ok(character) => self.send_loaded_data(client, &mut character.borrow_mut()), 53 | Err(_) => Err(NetworkError::NotLoggedIn), 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /net/src/packet/handle/world/map_transfer.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, helpers::to_hex_string, io::client::MapleClient, 3 | packet::handle::PacketHandler, 4 | }; 5 | use packet::Packet; 6 | use std::io::BufReader; 7 | 8 | pub struct PlayerMapTransferHandler {} 9 | 10 | impl PlayerMapTransferHandler { 11 | pub fn new() -> Self { 12 | Self {} 13 | } 14 | } 15 | 16 | // TODO: Serious implementation later... 17 | impl PacketHandler for PlayerMapTransferHandler { 18 | fn handle(&self, packet: &mut Packet, _client: &mut MapleClient) -> Result<(), NetworkError> { 19 | let mut _reader = BufReader::new(&**packet); 20 | println!("Received packet: {}", to_hex_string(&packet.bytes)); 21 | 22 | Ok(()) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /net/src/packet/handle/world/mod.rs: -------------------------------------------------------------------------------- 1 | mod change_map; 2 | mod chat; 3 | mod keybinds; 4 | mod logged_in; 5 | mod map_transfer; 6 | mod move_player; 7 | mod party_search; 8 | 9 | pub use self::change_map::ChangeMapHandler; 10 | pub use self::chat::AllChatHandler; 11 | pub use self::keybinds::ChangeKeybindsHandler; 12 | pub use self::logged_in::PlayerLoggedInHandler; 13 | pub use self::map_transfer::PlayerMapTransferHandler; 14 | pub use self::move_player::PlayerMoveHandler; 15 | pub use self::party_search::PartySearchHandler; 16 | -------------------------------------------------------------------------------- /net/src/packet/handle/world/move_player.rs: -------------------------------------------------------------------------------- 1 | use crate::{error::NetworkError, io::client::MapleClient, packet::handle::PacketHandler}; 2 | use packet::Packet; 3 | use std::io::BufReader; 4 | 5 | pub struct PlayerMoveHandler {} 6 | 7 | impl PlayerMoveHandler { 8 | pub fn new() -> Self { 9 | Self {} 10 | } 11 | } 12 | 13 | // TODO: Serious implementation later... 14 | impl PacketHandler for PlayerMoveHandler { 15 | fn handle(&self, packet: &mut Packet, _client: &mut MapleClient) -> Result<(), NetworkError> { 16 | let mut _reader = BufReader::new(&**packet); 17 | // This gets annoying fast... 18 | // println!("Received packet: {}", to_hex_string(&packet.bytes)); 19 | 20 | Ok(()) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /net/src/packet/handle/world/party_search.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | error::NetworkError, helpers::to_hex_string, io::client::MapleClient, 3 | packet::handle::PacketHandler, 4 | }; 5 | use packet::Packet; 6 | use std::io::BufReader; 7 | 8 | pub struct PartySearchHandler {} 9 | 10 | impl PartySearchHandler { 11 | pub fn new() -> Self { 12 | Self {} 13 | } 14 | } 15 | 16 | // TODO: Serious implementation later... 17 | impl PacketHandler for PartySearchHandler { 18 | fn handle(&self, packet: &mut Packet, _client: &mut MapleClient) -> Result<(), NetworkError> { 19 | let mut _reader = BufReader::new(&**packet); 20 | println!("Received packet: {}", to_hex_string(&packet.bytes)); 21 | 22 | Ok(()) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /net/src/packet/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod build; 2 | pub mod handle; 3 | pub mod op; 4 | -------------------------------------------------------------------------------- /net/src/packet/op/mod.rs: -------------------------------------------------------------------------------- 1 | mod recv; 2 | mod send; 3 | 4 | pub use self::recv::RecvOpcode; 5 | pub use self::send::SendOpcode; 6 | -------------------------------------------------------------------------------- /net/src/packet/op/recv.rs: -------------------------------------------------------------------------------- 1 | #[derive(FromPrimitive)] 2 | pub enum RecvOpcode { 3 | // Login Server Opcodes 4 | LoginCredentials = 0x01, 5 | GuestLogin = 0x02, 6 | ServerListReRequest = 0x04, 7 | CharListRequest = 0x05, 8 | ServerStatusRequest = 0x06, 9 | AcceptTOS = 0x07, 10 | SetGender = 0x08, 11 | AfterLogin = 0x09, 12 | RegisterPin = 0x0A, 13 | ServerListRequest = 0x0B, 14 | ViewAllChar = 0x0D, 15 | PickAllChar = 0x0E, 16 | CharSelect = 0x13, 17 | CheckCharName = 0x15, 18 | CreateChar = 0x16, 19 | DeleteChar = 0x17, 20 | RegisterPic = 0x1D, 21 | CharSelectWithPic = 0x1E, 22 | ViewAllPicRegister = 0x1F, 23 | ViewAllWithPic = 0x20, 24 | LoginStarted = 0x23, 25 | 26 | // World Server Opcodes 27 | PlayerLoggedIn = 0x14, 28 | 29 | ChangeMap = 0x26, 30 | 31 | PlayerMove = 0x29, 32 | AllChat = 0x31, 33 | 34 | ChangeKeybinds = 0x87, 35 | 36 | PlayerMapTransfer = 0xCF, 37 | PartySearch = 0xDF, 38 | 39 | UnusedOpcode = 0xFF, 40 | } 41 | -------------------------------------------------------------------------------- /net/src/packet/op/send.rs: -------------------------------------------------------------------------------- 1 | #[derive(FromPrimitive)] 2 | pub enum SendOpcode { 3 | LoginStatus = 0x00, 4 | GuestIdLogin = 0x01, 5 | ServerStatus = 0x03, 6 | CheckPin = 0x06, 7 | UpdatePin = 0x07, 8 | ServerList = 0x0A, 9 | NewCharacter = 0x0E, 10 | DeleteCharacter = 0x0F, 11 | CharList = 0x0B, 12 | ServerIp = 0x0C, 13 | CharNameResponse = 0x0D, 14 | LastConnectedWorld = 0x1A, 15 | RecommendedWorlds = 0x1B, 16 | 17 | StatChange = 0x1F, 18 | 19 | BuddyList = 0x3F, 20 | FamilyInfo = 0x5F, 21 | FamilyList = 0x64, 22 | SetField = 0x7D, 23 | 24 | KeyMap = 0x14F, 25 | } 26 | -------------------------------------------------------------------------------- /net/src/settings.rs: -------------------------------------------------------------------------------- 1 | use config::{Config, ConfigError, File}; 2 | 3 | #[derive(Debug, Deserialize)] 4 | pub struct Login { 5 | pub pin_required: bool, 6 | pub gender_required: bool, 7 | } 8 | 9 | #[derive(Debug, Deserialize)] 10 | pub struct Settings { 11 | pub login: Login, 12 | } 13 | 14 | impl Settings { 15 | pub fn new() -> Result { 16 | let mut s = Config::new(); 17 | 18 | s.merge(File::with_name("config/login_server_config"))?; 19 | 20 | s.try_into() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packet/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "packet" 3 | version = "0.1.0" 4 | authors = ["David Goldstein "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | byteorder = "1.3.4" 11 | rand = "0.7.3" 12 | -------------------------------------------------------------------------------- /packet/src/io.rs: -------------------------------------------------------------------------------- 1 | pub mod read; 2 | pub mod write; 3 | -------------------------------------------------------------------------------- /packet/src/io/read.rs: -------------------------------------------------------------------------------- 1 | use byteorder::{LittleEndian, ReadBytesExt}; 2 | use std::io::{Read, Result}; 3 | 4 | pub trait PktRead: ReadBytesExt { 5 | /// Read a byte. 6 | fn read_byte(&mut self) -> Result { 7 | self.read_u8() 8 | } 9 | 10 | /// Read a byte array of a given `length`. 11 | fn read_bytes(&mut self, length: usize) -> Result> { 12 | let mut buf = vec![0u8; length]; 13 | match self.read_exact(&mut buf) { 14 | Ok(_) => Ok(buf), 15 | Err(e) => Err(e), 16 | } 17 | } 18 | 19 | /// Read a short integer. 20 | fn read_short(&mut self) -> Result { 21 | self.read_i16::() 22 | } 23 | 24 | /// Read an integer. 25 | fn read_int(&mut self) -> Result { 26 | self.read_i32::() 27 | } 28 | 29 | /// Read a long integer. 30 | fn read_long(&mut self) -> Result { 31 | self.read_i64::() 32 | } 33 | 34 | /// Read a string of a given `length` starting at the `pos`th byte of the packet. 35 | fn read_str(&mut self, length: usize) -> Result { 36 | let mut buf = vec![0u8; length]; 37 | match self.read_exact(&mut buf) { 38 | Ok(_) => match String::from_utf8(buf) { 39 | Ok(string) => Ok(string), 40 | Err(e) => Err(std::io::Error::new( 41 | std::io::ErrorKind::InvalidData, 42 | e.to_string(), 43 | )), 44 | }, 45 | Err(e) => Err(e), 46 | } 47 | } 48 | 49 | /// Read a length-headered string starting at the `pos`th byte of the packet. 50 | fn read_str_with_length(&mut self) -> Result { 51 | match self.read_short() { 52 | Ok(length) => self.read_str(length as usize), 53 | Err(e) => Err(e), 54 | } 55 | } 56 | } 57 | 58 | impl PktRead for R {} 59 | 60 | #[cfg(test)] 61 | mod read_tests { 62 | use super::PktRead; 63 | use std::io::BufReader; 64 | 65 | use std::io::Write; 66 | 67 | use crate::model::packet::Packet; 68 | use byteorder::{LittleEndian, WriteBytesExt}; 69 | use rand::distributions::Alphanumeric; 70 | use rand::{random, thread_rng, Rng}; 71 | 72 | #[test] 73 | fn read_byte() { 74 | for _ in 0..100 { 75 | let byte: u8 = random(); 76 | 77 | let packet = Packet::new(&[byte]); 78 | let mut reader = BufReader::new(&*packet); 79 | 80 | assert_eq!(reader.read_byte().unwrap(), byte); 81 | } 82 | } 83 | 84 | #[test] 85 | fn read_bytes() { 86 | let mut rng = thread_rng(); 87 | for _ in 0..100 { 88 | let length = rng.gen_range(1, 10); 89 | let mut bytes: Vec = Vec::new(); 90 | 91 | for _ in 0..length { 92 | bytes.push(random()) 93 | } 94 | 95 | let packet = Packet::new(&bytes); 96 | let mut reader = BufReader::new(&*packet); 97 | 98 | assert_eq!(reader.read_bytes(length).unwrap(), bytes.as_slice()); 99 | } 100 | } 101 | 102 | #[test] 103 | fn read_bytes_one_at_a_time() { 104 | let mut rng = thread_rng(); 105 | for _ in 0..100 { 106 | let length = rng.gen_range(1, 10); 107 | let mut bytes: Vec = Vec::new(); 108 | 109 | for _ in 0..length { 110 | bytes.push(random()) 111 | } 112 | 113 | let packet = Packet::new(&bytes); 114 | let mut reader = BufReader::new(&*packet); 115 | 116 | for i in 0..length { 117 | assert_eq!(reader.read_byte().unwrap(), bytes[i]); 118 | } 119 | } 120 | } 121 | 122 | #[test] 123 | fn read_short() { 124 | for _ in 0..100 { 125 | let short: i16 = random(); 126 | 127 | let mut buf = Vec::new(); 128 | buf.write_i16::(short).unwrap(); 129 | 130 | let packet = Packet::new(&buf); 131 | let mut reader = BufReader::new(&*packet); 132 | 133 | assert_eq!(reader.read_short().unwrap(), short); 134 | } 135 | } 136 | 137 | #[test] 138 | fn read_int() { 139 | for _ in 0..100 { 140 | let integer: i32 = random(); 141 | 142 | let mut buf = Vec::new(); 143 | buf.write_i32::(integer).unwrap(); 144 | 145 | let packet = Packet::new(&buf.as_slice()); 146 | let mut reader = BufReader::new(&*packet); 147 | 148 | assert_eq!(reader.read_int().unwrap(), integer); 149 | } 150 | } 151 | 152 | #[test] 153 | fn read_long() { 154 | for _ in 0..100 { 155 | let long: i64 = random(); 156 | 157 | let mut buf = Vec::new(); 158 | buf.write_i64::(long).unwrap(); 159 | 160 | let packet = Packet::new(&buf); 161 | let mut reader = BufReader::new(&*packet); 162 | 163 | assert_eq!(reader.read_long().unwrap(), long); 164 | } 165 | } 166 | 167 | #[test] 168 | fn read_numbers() { 169 | for _ in 0..100 { 170 | let short: i16 = random(); 171 | let integer: i32 = random(); 172 | let long: i64 = random(); 173 | let integer2: i32 = random(); 174 | let short2: i16 = random(); 175 | 176 | let mut buf = Vec::new(); 177 | buf.write_i16::(short).unwrap(); 178 | buf.write_i32::(integer).unwrap(); 179 | buf.write_i64::(long).unwrap(); 180 | buf.write_i32::(integer2).unwrap(); 181 | buf.write_i16::(short2).unwrap(); 182 | 183 | let packet = Packet::new(&buf); 184 | let mut reader = BufReader::new(&*packet); 185 | 186 | assert_eq!(reader.read_short().unwrap(), short); 187 | assert_eq!(reader.read_int().unwrap(), integer); 188 | assert_eq!(reader.read_long().unwrap(), long); 189 | assert_eq!(reader.read_int().unwrap(), integer2); 190 | assert_eq!(reader.read_short().unwrap(), short2); 191 | } 192 | } 193 | 194 | #[test] 195 | fn read_string() { 196 | for _ in 0..100 { 197 | let length = rand::thread_rng().gen_range(0, 255); 198 | let test_string = rand::thread_rng() 199 | .sample_iter(&Alphanumeric) 200 | .take(length) 201 | .collect::(); 202 | 203 | let mut buf = Vec::new(); 204 | buf.write(test_string.as_bytes()).unwrap(); 205 | 206 | let packet = Packet::new(&buf); 207 | let mut reader = BufReader::new(&*packet); 208 | 209 | assert_eq!(reader.read_str(test_string.len()).unwrap(), test_string); 210 | } 211 | } 212 | 213 | #[test] 214 | fn read_str_with_length() { 215 | for _ in 0..100 { 216 | let length = rand::thread_rng().gen_range(0, 255); 217 | let test_string = rand::thread_rng() 218 | .sample_iter(&Alphanumeric) 219 | .take(length) 220 | .collect::(); 221 | 222 | let mut buf = Vec::new(); 223 | buf.write_u16::(length as u16).unwrap(); 224 | buf.write(test_string.as_bytes()).unwrap(); 225 | 226 | let packet = Packet::new(&buf); 227 | let mut reader = BufReader::new(&*packet); 228 | 229 | assert_eq!(reader.read_str_with_length().unwrap(), test_string); 230 | } 231 | } 232 | 233 | #[test] 234 | fn read_str_with_length_between_two_fixed_strs() { 235 | for _ in 0..100 { 236 | let length = rand::thread_rng().gen_range(0, 255); 237 | let test_string = rand::thread_rng() 238 | .sample_iter(&Alphanumeric) 239 | .take(length) 240 | .collect::(); 241 | 242 | let hello = "Hello world!"; 243 | let test = "Test!"; 244 | 245 | let mut buf = Vec::new(); 246 | buf.write_u16::(hello.len() as u16).unwrap(); 247 | buf.write(hello.as_bytes()).unwrap(); 248 | 249 | buf.write_u16::(length as u16).unwrap(); 250 | buf.write(test_string.as_bytes()).unwrap(); 251 | 252 | buf.write(test.as_bytes()).unwrap(); 253 | 254 | let packet = Packet::new(&buf); 255 | let mut reader = BufReader::new(&*packet); 256 | 257 | assert_eq!(reader.read_str_with_length().unwrap(), hello); 258 | assert_eq!(reader.read_str_with_length().unwrap(), test_string); 259 | assert_eq!(reader.read_str(test.len() as usize).unwrap(), test); 260 | } 261 | } 262 | } 263 | -------------------------------------------------------------------------------- /packet/src/io/write.rs: -------------------------------------------------------------------------------- 1 | use byteorder::{LittleEndian, WriteBytesExt}; 2 | use std::io::{Result, Write}; 3 | 4 | pub trait PktWrite: WriteBytesExt { 5 | /// Write a byte to the end of a packet. 6 | fn write_byte(&mut self, byte: u8) -> Result { 7 | self.write(&[byte]) 8 | } 9 | 10 | /// Write a byte array to the end of a packet. 11 | fn write_bytes(&mut self, bytes: &[u8]) -> Result { 12 | self.write(bytes) 13 | } 14 | 15 | /// Write a short integer to the end of a packet in Little Endian format. 16 | fn write_short(&mut self, short: i16) -> Result<()> { 17 | self.write_u16::(short as u16) 18 | } 19 | 20 | /// Write an integer to the end of a packet in Little Endian format. 21 | fn write_int(&mut self, int: i32) -> Result<()> { 22 | self.write_u32::(int as u32) 23 | } 24 | 25 | /// Write a long integer to the end of a packet in Little Endian format. 26 | fn write_long(&mut self, long: i64) -> Result<()> { 27 | self.write_u64::(long as u64) 28 | } 29 | 30 | /// Write a string to the end of a packet. 31 | fn write_str(&mut self, string: &str) -> Result { 32 | self.write(string.as_bytes()) 33 | } 34 | 35 | /// Write a string's length followed by the string itself to the end of a packet. 36 | fn write_str_with_length(&mut self, string: &str) -> Result { 37 | match self.write_short(string.len() as i16) { 38 | Ok(_) => self.write_str(string), 39 | Err(e) => Err(e), 40 | } 41 | } 42 | } 43 | 44 | impl PktWrite for W {} 45 | 46 | #[cfg(test)] 47 | mod write_tests { 48 | use super::PktWrite; 49 | 50 | use crate::Packet; 51 | use rand::distributions::Alphanumeric; 52 | use rand::{random, thread_rng, Rng}; 53 | 54 | use byteorder::{LittleEndian, ReadBytesExt}; 55 | 56 | #[test] 57 | fn write_byte() { 58 | for _ in 0..100 { 59 | let mut packet = Packet::new_empty(); 60 | let byte: u8 = random(); 61 | packet.write_byte(byte).unwrap(); 62 | 63 | assert_eq!(packet.bytes, [byte]); 64 | } 65 | } 66 | 67 | #[test] 68 | fn write_bytes() { 69 | let mut rng = thread_rng(); 70 | for _ in 0..100 { 71 | let mut packet = Packet::new_empty(); 72 | let length = rng.gen_range(1, 10); 73 | let mut bytes: Vec = Vec::new(); 74 | 75 | for _ in 0..length { 76 | bytes.push(random()) 77 | } 78 | 79 | packet.write_bytes(&bytes).unwrap(); 80 | 81 | // TODO: Might need to make sure this checks by element 82 | assert_eq!(packet.bytes, bytes.as_slice()); 83 | } 84 | } 85 | 86 | #[test] 87 | fn write_short() { 88 | for _ in 0..100 { 89 | let mut packet = Packet::new_empty(); 90 | let short: i16 = random(); 91 | 92 | packet.write_short(short).unwrap(); 93 | 94 | assert_eq!(packet.bytes[0], (short & 0xFF) as u8); 95 | assert_eq!(packet.bytes[1], ((short >> 8) & 0xFF) as u8); 96 | } 97 | } 98 | 99 | #[test] 100 | fn write_int() { 101 | for _ in 0..100 { 102 | let mut packet = Packet::new_empty(); 103 | let integer: i32 = random(); 104 | 105 | packet.write_int(integer).unwrap(); 106 | 107 | assert_eq!(packet.bytes[0], (integer & 0xFF) as u8); 108 | assert_eq!(packet.bytes[1], ((integer >> 8) & 0xFF) as u8); 109 | assert_eq!(packet.bytes[2], ((integer >> 16) & 0xFF) as u8); 110 | assert_eq!(packet.bytes[3], ((integer >> 24) & 0xFF) as u8); 111 | } 112 | } 113 | 114 | #[test] 115 | fn write_long() { 116 | for _ in 0..100 { 117 | let mut packet = Packet::new_empty(); 118 | let long: i64 = random(); 119 | 120 | packet.write_long(long).unwrap(); 121 | 122 | assert_eq!(packet.bytes[0], (long & 0xFF) as u8); 123 | assert_eq!(packet.bytes[1], ((long >> 8) & 0xFF) as u8); 124 | assert_eq!(packet.bytes[2], ((long >> 16) & 0xFF) as u8); 125 | assert_eq!(packet.bytes[3], ((long >> 24) & 0xFF) as u8); 126 | assert_eq!(packet.bytes[4], ((long >> 32) & 0xFF) as u8); 127 | assert_eq!(packet.bytes[5], ((long >> 40) & 0xFF) as u8); 128 | assert_eq!(packet.bytes[6], ((long >> 48) & 0xFF) as u8); 129 | assert_eq!(packet.bytes[7], ((long >> 56) & 0xFF) as u8); 130 | } 131 | } 132 | 133 | #[test] 134 | fn write_str() { 135 | for _ in 0..100 { 136 | let mut packet = Packet::new_empty(); 137 | 138 | let length = rand::thread_rng().gen_range(0, 255); 139 | let test_string = rand::thread_rng() 140 | .sample_iter(&Alphanumeric) 141 | .take(length) 142 | .collect::(); 143 | 144 | packet.write_str(&test_string).unwrap(); 145 | 146 | assert_eq!( 147 | String::from_utf8(packet.bytes.to_vec()).unwrap(), 148 | test_string 149 | ); 150 | } 151 | } 152 | 153 | #[test] 154 | fn write_str_with_length() { 155 | for _ in 0..100 { 156 | let mut packet = Packet::new_empty(); 157 | 158 | let length = rand::thread_rng().gen_range(0, 255); 159 | let test_string = rand::thread_rng() 160 | .sample_iter(&Alphanumeric) 161 | .take(length) 162 | .collect::(); 163 | 164 | packet.write_str_with_length(&test_string).unwrap(); 165 | 166 | assert_eq!( 167 | packet.bytes.as_slice().read_u16::().unwrap(), 168 | length as u16 169 | ); 170 | 171 | assert_eq!( 172 | String::from_utf8(packet.bytes[2..].to_vec()).unwrap(), 173 | test_string 174 | ); 175 | } 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /packet/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod io; 2 | mod model; 3 | 4 | pub use self::model::packet::{Packet, INVALID_OPCODE, MAX_PACKET_LENGTH}; 5 | -------------------------------------------------------------------------------- /packet/src/model.rs: -------------------------------------------------------------------------------- 1 | pub mod packet; 2 | -------------------------------------------------------------------------------- /packet/src/model/packet.rs: -------------------------------------------------------------------------------- 1 | use std::io::{Result, Write}; 2 | use std::ops::{Deref, DerefMut}; 3 | 4 | /// A sentinel for an invalid packet opcode. 5 | pub const INVALID_OPCODE: i16 = 1; 6 | 7 | /// The maximum length a network packet may take on. 8 | pub const MAX_PACKET_LENGTH: i16 = i16::MAX; 9 | 10 | /// A data model for a network packet. 11 | pub struct Packet { 12 | pub bytes: Vec, 13 | } 14 | 15 | impl Packet { 16 | /// Instantiate a new packet wrapper. 17 | pub fn new(buffer: &[u8]) -> Packet { 18 | if buffer.len() > MAX_PACKET_LENGTH as usize { 19 | // We should not be reading a buffer so large in the first place! 20 | panic!( 21 | "Packet with length {} exceeded max packet length {}", 22 | buffer.len(), 23 | MAX_PACKET_LENGTH 24 | ); 25 | } 26 | 27 | let bytes = buffer.to_vec(); 28 | Packet { bytes } 29 | } 30 | 31 | pub fn new_empty() -> Packet { 32 | let bytes = vec![]; 33 | 34 | Packet { bytes } 35 | } 36 | 37 | /// Return the opcode of packet. 38 | /// 39 | /// If the packet has no opcode because it is too short or if the 40 | /// opcode is negative, returns the `INVALID_OPCODE` sentinel. 41 | pub fn opcode(&self) -> i16 { 42 | if self.bytes.len() > 1 { 43 | let opcode: i16 = ((self.bytes[0] as u16) | ((self.bytes[1] as u16) << 8)) as i16; 44 | 45 | if opcode >= 0 { 46 | opcode 47 | } else { 48 | INVALID_OPCODE 49 | } 50 | } else { 51 | INVALID_OPCODE 52 | } 53 | } 54 | 55 | /// Return the length of the packet. 56 | pub fn len(&self) -> i16 { 57 | (self.bytes.len() - 2) as i16 58 | } 59 | } 60 | 61 | impl Write for Packet { 62 | fn write(&mut self, buf: &[u8]) -> Result { 63 | self.bytes.write(buf) 64 | } 65 | fn flush(&mut self) -> Result<()> { 66 | self.bytes.flush() 67 | } 68 | } 69 | 70 | impl Deref for Packet { 71 | type Target = [u8]; 72 | 73 | fn deref(&self) -> &Self::Target { 74 | &self.bytes 75 | } 76 | } 77 | 78 | impl DerefMut for Packet { 79 | fn deref_mut(&mut self) -> &mut Self::Target { 80 | &mut self.bytes 81 | } 82 | } 83 | 84 | #[cfg(test)] 85 | mod test_packet { 86 | use super::{Packet, INVALID_OPCODE, MAX_PACKET_LENGTH}; 87 | use byteorder::{LittleEndian, WriteBytesExt}; 88 | use rand::{thread_rng, Rng}; 89 | use std::iter; 90 | 91 | #[test] 92 | fn empty_packet_is_empty() { 93 | let packet = Packet::new_empty(); 94 | 95 | assert_eq!(packet.bytes.len(), 0); 96 | } 97 | 98 | #[test] 99 | fn read_correct_opcodes() { 100 | let mut rng = thread_rng(); 101 | for _ in 0..100 { 102 | let opcode: i16 = rng.gen_range(0, (i16::MAX as usize) + 1) as i16; 103 | 104 | let mut buf = Vec::new(); 105 | buf.write_i16::(opcode).unwrap(); 106 | 107 | let packet = Packet::new(&buf); 108 | 109 | assert_eq!(packet.opcode(), opcode); 110 | } 111 | } 112 | 113 | #[test] 114 | fn read_negative_opcodes() { 115 | let mut rng = thread_rng(); 116 | for _ in 0..100 { 117 | let opcode: i16 = rng.gen_range(i16::MIN, 0); 118 | 119 | let mut buf = Vec::new(); 120 | buf.write_i16::(opcode).unwrap(); 121 | 122 | let packet = Packet::new(&buf); 123 | 124 | assert_eq!(packet.opcode(), INVALID_OPCODE); 125 | } 126 | } 127 | 128 | #[test] 129 | fn empty_buffer_opcode() { 130 | let packet = Packet::new(&[]); 131 | 132 | assert_eq!(packet.opcode(), INVALID_OPCODE); 133 | } 134 | 135 | #[test] 136 | fn short_buffer_opcode() { 137 | let mut rng = thread_rng(); 138 | for _ in 0..100 { 139 | let packet = Packet::new(&vec![rng.gen()]); 140 | 141 | assert_eq!(packet.opcode(), INVALID_OPCODE); 142 | } 143 | } 144 | 145 | #[test] 146 | fn packet_length_constant() { 147 | let mut rng = thread_rng(); 148 | for _ in 0..100 { 149 | let length = rng.gen_range(2, (MAX_PACKET_LENGTH as usize) + 1); 150 | 151 | let mut buf: Vec = iter::repeat(0).take(length).collect(); 152 | rng.fill(&mut buf[..]); 153 | 154 | let packet = Packet::new(&buf); 155 | 156 | assert_eq!(packet.len(), (length - 2) as i16); 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /rust-ms/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust-ms" 3 | version = "0.1.0" 4 | authors = ["David Goldstein "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | ctrlc = "3.1.4" 11 | crypt = { path = "../crypt"} 12 | packet = { path = "../packet" } 13 | net = { path = "../net" } 14 | -------------------------------------------------------------------------------- /rust-ms/src/bin/login.rs: -------------------------------------------------------------------------------- 1 | use std::net::{TcpListener, TcpStream}; 2 | use std::process::exit; 3 | use std::thread; 4 | 5 | use net::listener::ClientConnectionListener; 6 | 7 | fn main() { 8 | println!("Starting up..."); 9 | 10 | // Shut down the server somewhat gracefuly; not a fan of seeing an error on ctrl+c 11 | ctrlc::set_handler(move || { 12 | println!("Shutting down..."); 13 | exit(0); 14 | }) 15 | .expect("Error setting ctrl+c handler!"); 16 | 17 | let listener = TcpListener::bind("0.0.0.0:8484").unwrap(); 18 | 19 | for stream in listener.incoming() { 20 | println!("Incoming connection..."); 21 | let stream = stream.unwrap(); 22 | 23 | thread::spawn(move || { 24 | handle_connection(stream); 25 | }); 26 | } 27 | } 28 | 29 | fn handle_connection(stream: TcpStream) { 30 | println!( 31 | "Connection Terminated: {}", 32 | ClientConnectionListener::login_server(stream) 33 | .and_then(|mut session| session.listen()) 34 | .expect_err("Thread disconnects should result in error...") 35 | ) 36 | } 37 | -------------------------------------------------------------------------------- /rust-ms/src/bin/world.rs: -------------------------------------------------------------------------------- 1 | use std::net::{TcpListener, TcpStream}; 2 | use std::process::exit; 3 | use std::thread; 4 | 5 | use net::listener::ClientConnectionListener; 6 | 7 | fn main() { 8 | println!("Starting World Server..."); 9 | 10 | // Shut down the server somewhat gracefuly; not a fan of seeing an error on ctrl+c 11 | ctrlc::set_handler(move || { 12 | println!("Shutting down..."); 13 | exit(0); 14 | }) 15 | .expect("Error setting ctrl+c handler!"); 16 | 17 | let listener = TcpListener::bind("0.0.0.0:8485").unwrap(); 18 | 19 | for stream in listener.incoming() { 20 | println!("Incoming connection..."); 21 | let stream = stream.unwrap(); 22 | 23 | thread::spawn(move || { 24 | handle_connection(stream); 25 | }); 26 | } 27 | } 28 | 29 | fn handle_connection(stream: TcpStream) { 30 | println!( 31 | "Connection Terminated: {}", 32 | ClientConnectionListener::world_server(stream) 33 | .and_then(|mut session| session.listen()) 34 | .expect_err("Thread disconnects should result in error...") 35 | ) 36 | } 37 | --------------------------------------------------------------------------------