├── .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 | 
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 | 
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 | 
156 |
157 | In the server's console, you should see that the handshake completed successfully and the Login Start packet was received.
158 | 
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 | 
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