mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-02-16 18:50:44 +00:00
Compare commits
858 Commits
v1.20-linu
...
feature-be
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6da9a921d0 | ||
|
|
a8333359ce | ||
|
|
b71aa2db04 | ||
|
|
78f7cdc17a | ||
|
|
36a1da3218 | ||
|
|
23e9941704 | ||
|
|
469eb78c80 | ||
|
|
af5658d0e1 | ||
|
|
1062e29582 | ||
|
|
ec9a280d30 | ||
|
|
784bbd4f6b | ||
|
|
bc6b4e40e1 | ||
|
|
071ba08dfe | ||
|
|
023738c41b | ||
|
|
6a166110f6 | ||
|
|
71fbf7b7cc | ||
|
|
4b242c26fc | ||
|
|
a84d042a8a | ||
|
|
44b94c9e58 | ||
|
|
660f94b691 | ||
|
|
a7c4103f7c | ||
|
|
0932078e4b | ||
|
|
54e02abad1 | ||
|
|
e4cbba59ef | ||
|
|
e4db66782e | ||
|
|
b443bec72e | ||
|
|
76a8f231ac | ||
|
|
398f8d3fa4 | ||
|
|
60dd1e2472 | ||
|
|
e634b4b6b7 | ||
|
|
1caa5e3517 | ||
|
|
b009a37f35 | ||
|
|
054016a099 | ||
|
|
8b57f6e35a | ||
|
|
f21d3d0389 | ||
|
|
2ed92c4aa1 | ||
|
|
fd7b11f436 | ||
|
|
6a94060970 | ||
|
|
51ccf31373 | ||
|
|
a2cc629153 | ||
|
|
ad414ec5c9 | ||
|
|
0a8e7d8e50 | ||
|
|
bbd026e399 | ||
|
|
04bbdff6b7 | ||
|
|
a28b3e1532 | ||
|
|
b01bed2996 | ||
|
|
7bdc2b304b | ||
|
|
b19bca4c82 | ||
|
|
708848f275 | ||
|
|
2d8ce09b2c | ||
|
|
05251efc06 | ||
|
|
f8d622352f | ||
|
|
6c1d02a425 | ||
|
|
38eeec39b4 | ||
|
|
696e080e1c | ||
|
|
98681254e6 | ||
|
|
420e6c3533 | ||
|
|
06f8ba5a0e | ||
|
|
9420d8a7a0 | ||
|
|
dfa90da8af | ||
|
|
d6625187d1 | ||
|
|
6e46d5aca9 | ||
|
|
817bd4b588 | ||
|
|
25391fa0c7 | ||
|
|
28270072d4 | ||
|
|
758d5b2c96 | ||
|
|
1970d97ea4 | ||
|
|
d8526f0649 | ||
|
|
0621c0bf82 | ||
|
|
36547d1e9e | ||
|
|
f06f31c2a0 | ||
|
|
46b92b4992 | ||
|
|
70e53c2a70 | ||
|
|
cc35d83834 | ||
|
|
b4f97a6da0 | ||
|
|
3d7db6d0bc | ||
|
|
1c3b1ecc76 | ||
|
|
303da19f48 | ||
|
|
c455d4855c | ||
|
|
8df61fe44c | ||
|
|
7224e90c68 | ||
|
|
fde5bc7fb6 | ||
|
|
22b63220c7 | ||
|
|
811ace1999 | ||
|
|
2cf083a7e4 | ||
|
|
28c43a51ee | ||
|
|
00f156cb86 | ||
|
|
67b8565a4d | ||
|
|
ed8d8a6419 | ||
|
|
895058f85f | ||
|
|
a0876ed58c | ||
|
|
4f69ca1ad0 | ||
|
|
bc1628afeb | ||
|
|
019c5202ea | ||
|
|
2dd181d492 | ||
|
|
a5153e4bc1 | ||
|
|
8d7505956d | ||
|
|
3b2016d09f | ||
|
|
ed03096cf5 | ||
|
|
88f1976668 | ||
|
|
ca52d233c0 | ||
|
|
34b39aad4d | ||
|
|
f4eb492d91 | ||
|
|
7f41a2a574 | ||
|
|
11c53e0b3a | ||
|
|
974dda9f8b | ||
|
|
0979c8b1e4 | ||
|
|
0761036c8c | ||
|
|
5ded713b4b | ||
|
|
668cc496b6 | ||
|
|
056d20292a | ||
|
|
58e2383b2e | ||
|
|
d8c33c03ee | ||
|
|
1bab3276e9 | ||
|
|
4ff69528bd | ||
|
|
5e4c7eac51 | ||
|
|
952631bb80 | ||
|
|
23af76dba1 | ||
|
|
5755ead9be | ||
|
|
450f0a6875 | ||
|
|
104737571c | ||
|
|
d01d79a49a | ||
|
|
d4b30a2583 | ||
|
|
81dbf747d5 | ||
|
|
b97397132d | ||
|
|
d86efabb1a | ||
|
|
de82caef33 | ||
|
|
f8c58f363a | ||
|
|
71c2d4b859 | ||
|
|
b2f27c21be | ||
|
|
b780a08f73 | ||
|
|
cd4332b790 | ||
|
|
7a814ed35e | ||
|
|
9e0d02c6db | ||
|
|
d0bb32ec63 | ||
|
|
5180c96e2b | ||
|
|
dbfe4a4d11 | ||
|
|
4cb299061e | ||
|
|
ef902a03f3 | ||
|
|
c1e216957b | ||
|
|
39db1a5e42 | ||
|
|
be498be661 | ||
|
|
0466ae55a4 | ||
|
|
6a43694c0f | ||
|
|
fe06726d75 | ||
|
|
3c08e54471 | ||
|
|
a97763a94f | ||
|
|
daa674f448 | ||
|
|
710b15535e | ||
|
|
a85fef15c2 | ||
|
|
359faee696 | ||
|
|
299004b14e | ||
|
|
b09f5a401d | ||
|
|
2caa74d913 | ||
|
|
e3d9d11bbd | ||
|
|
09c9b24cbf | ||
|
|
a450531b8a | ||
|
|
ace7aaada7 | ||
|
|
ca3314b416 | ||
|
|
7d97c3b560 | ||
|
|
dd5cf1a4af | ||
|
|
9a0cdc6517 | ||
|
|
965935a0e6 | ||
|
|
96a0e4b6fb | ||
|
|
b52677e585 | ||
|
|
95b417bb36 | ||
|
|
8ce3be03a3 | ||
|
|
687b4e4235 | ||
|
|
86ad28abdc | ||
|
|
a982d54202 | ||
|
|
588c68ebe1 | ||
|
|
548b2512cc | ||
|
|
8ff94a57d7 | ||
|
|
a44684f6e7 | ||
|
|
944b68c6d5 | ||
|
|
01268821dc | ||
|
|
5553aca0bb | ||
|
|
beaea4f624 | ||
|
|
a4f07c9a4d | ||
|
|
dada8fe6bf | ||
|
|
36853ca683 | ||
|
|
d969c4a2c2 | ||
|
|
f26ca6b40d | ||
|
|
17c571811a | ||
|
|
b72de4bd0a | ||
|
|
fdb7c9ce71 | ||
|
|
c391abcc93 | ||
|
|
144ccf14ec | ||
|
|
40b23cbbe6 | ||
|
|
7b458e3e27 | ||
|
|
69656f95db | ||
|
|
0f5c476d09 | ||
|
|
86b6aed350 | ||
|
|
81780294f8 | ||
|
|
7c1fb12625 | ||
|
|
9f892af997 | ||
|
|
9494bc70fb | ||
|
|
5c44a307bc | ||
|
|
754053e73f | ||
|
|
29f8d29e33 | ||
|
|
e043361abb | ||
|
|
fd12ee672d | ||
|
|
fca5bbcec9 | ||
|
|
2a588954be | ||
|
|
cd4129e05d | ||
|
|
c42c748b37 | ||
|
|
179b33a7ab | ||
|
|
1b14206a3c | ||
|
|
0cf81cf3f4 | ||
|
|
801780bcb1 | ||
|
|
84d52578e0 | ||
|
|
3555cec5fe | ||
|
|
71efe30345 | ||
|
|
5df8aedf08 | ||
|
|
c3ab4b729a | ||
|
|
464aa3b59f | ||
|
|
cfe63198c7 | ||
|
|
435d73f0c1 | ||
|
|
a5c23f8dde | ||
|
|
6c5b2cbeb5 | ||
|
|
ca5b3956a1 | ||
|
|
924e18c163 | ||
|
|
bbe92dfa0f | ||
|
|
a19943c96d | ||
|
|
cd19ae0836 | ||
|
|
3ee83904a1 | ||
|
|
fe652cbf42 | ||
|
|
2c115a2b2c | ||
|
|
1172420b77 | ||
|
|
92d9857902 | ||
|
|
816d3d5df8 | ||
|
|
817a146699 | ||
|
|
3cce875fbb | ||
|
|
a1335e8c7d | ||
|
|
0f74eca2ee | ||
|
|
279c93179c | ||
|
|
62cc1e9ce4 | ||
|
|
bd41382233 | ||
|
|
9d283738aa | ||
|
|
b33d50361c | ||
|
|
479bb9f931 | ||
|
|
672c7d02d1 | ||
|
|
a289d0e872 | ||
|
|
86169ad0fa | ||
|
|
f477570a1c | ||
|
|
7b99ccb08e | ||
|
|
265dd710cf | ||
|
|
eb67f483b2 | ||
|
|
98c7fea139 | ||
|
|
ccdc5dae17 | ||
|
|
1bc9a5293e | ||
|
|
c3151093e2 | ||
|
|
8f77f1c8c0 | ||
|
|
19d67dee95 | ||
|
|
fc440bea2a | ||
|
|
c91f3ee33c | ||
|
|
297b646d33 | ||
|
|
768d0466f4 | ||
|
|
1e0ab6bbb3 | ||
|
|
472ec3390c | ||
|
|
a4123d7d7c | ||
|
|
6fd54f7907 | ||
|
|
fd7bea0f36 | ||
|
|
9d2d4bb221 | ||
|
|
e1756298af | ||
|
|
eae27633db | ||
|
|
938774618c | ||
|
|
1a2a123d87 | ||
|
|
6247061d09 | ||
|
|
08a62261e7 | ||
|
|
a7db41ebaa | ||
|
|
66d4e34a75 | ||
|
|
7169e65305 | ||
|
|
097e52674b | ||
|
|
1ec47252f2 | ||
|
|
2ddac7f138 | ||
|
|
cf08dee84f | ||
|
|
f1148ed1c4 | ||
|
|
b6fa3574fd | ||
|
|
7079e80b71 | ||
|
|
48b9aa72dc | ||
|
|
c36ea52f60 | ||
|
|
87f23427a1 | ||
|
|
7197c23632 | ||
|
|
b5ea084c9b | ||
|
|
f8af134dc9 | ||
|
|
3e7aa763ed | ||
|
|
5fdd7beac8 | ||
|
|
701a7feee3 | ||
|
|
1e305c3c90 | ||
|
|
9f5fa8fb9b | ||
|
|
fdc205f521 | ||
|
|
a18abd6c8b | ||
|
|
1b2ea88a71 | ||
|
|
50589fbe3d | ||
|
|
7287fce341 | ||
|
|
6de625682d | ||
|
|
6189aed6e7 | ||
|
|
c4d6aab08b | ||
|
|
577d4c429d | ||
|
|
d027f7f29f | ||
|
|
af14188ec0 | ||
|
|
1ee45c9d1a | ||
|
|
d1f890752a | ||
|
|
9eabd19e17 | ||
|
|
ae7a63669f | ||
|
|
243e96d503 | ||
|
|
932fbe2b2f | ||
|
|
26ec50b199 | ||
|
|
87ecc3f9f6 | ||
|
|
7f1d37a0e6 | ||
|
|
255feb4f8e | ||
|
|
013ca14ab8 | ||
|
|
e7f29ce04f | ||
|
|
e948edca8d | ||
|
|
d0431c0b9d | ||
|
|
0961f86662 | ||
|
|
7f2ca025f8 | ||
|
|
33ebfa82f0 | ||
|
|
9d0caf2c7d | ||
|
|
fe3ccafc1d | ||
|
|
23ffa25d78 | ||
|
|
908f67a799 | ||
|
|
27b5c6d850 | ||
|
|
32756ccc4a | ||
|
|
3626f4108e | ||
|
|
d7a4322313 | ||
|
|
d84051bdd3 | ||
|
|
238577a4f7 | ||
|
|
041db23a69 | ||
|
|
a3a18a3b56 | ||
|
|
9efe352e7a | ||
|
|
3edb9322d4 | ||
|
|
4bf89706b4 | ||
|
|
a97791d4ee | ||
|
|
323184911d | ||
|
|
6f9f790c5b | ||
|
|
4de80e0c7a | ||
|
|
366a7dc9a6 | ||
|
|
785b858651 | ||
|
|
a4ff9488c5 | ||
|
|
60b86e2be6 | ||
|
|
701e613990 | ||
|
|
7dbf859529 | ||
|
|
8419ca2234 | ||
|
|
7f63dd8d7d | ||
|
|
da78d77e6c | ||
|
|
1ff5107707 | ||
|
|
dd70e88e4c | ||
|
|
38dffc5462 | ||
|
|
f98ef7d41c | ||
|
|
29a858e74a | ||
|
|
e53f2d9877 | ||
|
|
be3ac45abb | ||
|
|
246f8289b6 | ||
|
|
3c7109b23f | ||
|
|
82a5fc3999 | ||
|
|
11d4d9ff91 | ||
|
|
48caae25fd | ||
|
|
9dfe9f659a | ||
|
|
a07b5062de | ||
|
|
fcbb188ee0 | ||
|
|
883d69ba27 | ||
|
|
7459779363 | ||
|
|
a0c47d9947 | ||
|
|
7db345cfbc | ||
|
|
1d3958817f | ||
|
|
fd3088c78f | ||
|
|
c2b73d93b5 | ||
|
|
9a37ed4341 | ||
|
|
e64114e4fa | ||
|
|
79531334dd | ||
|
|
ed6f5282d9 | ||
|
|
62fd369625 | ||
|
|
1880536276 | ||
|
|
bac476ec34 | ||
|
|
e75e65815c | ||
|
|
b0c467f971 | ||
|
|
6b17990d4d | ||
|
|
c73d56c143 | ||
|
|
a44050f0f1 | ||
|
|
cb1eb40def | ||
|
|
4c03a90157 | ||
|
|
be61511bdf | ||
|
|
968d9ff999 | ||
|
|
1c80a4deb7 | ||
|
|
e602decb96 | ||
|
|
dca573b15c | ||
|
|
26231c6272 | ||
|
|
ebe3630ec8 | ||
|
|
d7f7a81cb0 | ||
|
|
9ef6c32864 | ||
|
|
9b9c18a4c1 | ||
|
|
5978665ad6 | ||
|
|
2cf368c2b0 | ||
|
|
ba0678dade | ||
|
|
c309fa28c6 | ||
|
|
f5b2be0a03 | ||
|
|
dd4e4c4467 | ||
|
|
d082620525 | ||
|
|
be90a8a2c0 | ||
|
|
8b69127cdd | ||
|
|
bb34378b8e | ||
|
|
2355327c21 | ||
|
|
3837e101e2 | ||
|
|
fa19ba08e3 | ||
|
|
57d0eb735e | ||
|
|
15704abf6c | ||
|
|
6883c96d33 | ||
|
|
f632606d76 | ||
|
|
c70ada2926 | ||
|
|
80aebcb9a7 | ||
|
|
3fc397814c | ||
|
|
6542be09ee | ||
|
|
38b934bc0f | ||
|
|
a2f92b5791 | ||
|
|
30624c77a2 | ||
|
|
b1664bb184 | ||
|
|
ffac000cd2 | ||
|
|
3cd94380e2 | ||
|
|
b055fd8bda | ||
|
|
d43ee4b7b6 | ||
|
|
a514591650 | ||
|
|
0f9f81e9fa | ||
|
|
11e94e91a7 | ||
|
|
588242822c | ||
|
|
58da200901 | ||
|
|
f4ccf6c177 | ||
|
|
27103a73a9 | ||
|
|
2727f90430 | ||
|
|
2a96546c8c | ||
|
|
6462636b29 | ||
|
|
5742ab0dad | ||
|
|
0087205d55 | ||
|
|
d16843e45d | ||
|
|
24516dbfd7 | ||
|
|
a311d58e11 | ||
|
|
1444d91e7e | ||
|
|
1e2f060107 | ||
|
|
fdb5da2ed6 | ||
|
|
de57613326 | ||
|
|
b49782e8a3 | ||
|
|
ff80b4cf63 | ||
|
|
4c23b78f84 | ||
|
|
aca3c52c20 | ||
|
|
51d6c4fb0a | ||
|
|
2af9491fd6 | ||
|
|
95c036836e | ||
|
|
a7f2f85e45 | ||
|
|
42c5aaad5a | ||
|
|
88684bd9af | ||
|
|
c6457f7df4 | ||
|
|
ba3fd0e144 | ||
|
|
e3b6fd7998 | ||
|
|
943159cd40 | ||
|
|
9423831937 | ||
|
|
95188042c5 | ||
|
|
a0a7b8ecce | ||
|
|
53617abae4 | ||
|
|
853b078124 | ||
|
|
549517c518 | ||
|
|
2be4b8fd91 | ||
|
|
2cfb27820a | ||
|
|
1ff12cb2bf | ||
|
|
518cb0664e | ||
|
|
80432eb718 | ||
|
|
b1caf5c29a | ||
|
|
950cee9fd0 | ||
|
|
046097579e | ||
|
|
cacdc004da | ||
|
|
8250d5876f | ||
|
|
a7b02c459e | ||
|
|
0d5ef404f6 | ||
|
|
07cf7d7c21 | ||
|
|
809a851c71 | ||
|
|
fe36191baf | ||
|
|
7d137eb496 | ||
|
|
fd6234bd21 | ||
|
|
9f0b057c14 | ||
|
|
0143748953 | ||
|
|
8ec90d5186 | ||
|
|
d054214b7f | ||
|
|
003a8269aa | ||
|
|
59b1b45625 | ||
|
|
15e5cee166 | ||
|
|
12123582ad | ||
|
|
3fb227e468 | ||
|
|
31e9004011 | ||
|
|
f98c8dabb0 | ||
|
|
e8665bfb72 | ||
|
|
3d13381abd | ||
|
|
5352e4ff03 | ||
|
|
c571e218c7 | ||
|
|
5725717e29 | ||
|
|
7f5447f25e | ||
|
|
b33b396089 | ||
|
|
ff3cbebac0 | ||
|
|
0f9a994c10 | ||
|
|
c4b72be50a | ||
|
|
5a3140c84a | ||
|
|
bea8006a26 | ||
|
|
a2dc42c5f5 | ||
|
|
4b92532203 | ||
|
|
683e13a4a0 | ||
|
|
9d6dbefb9d | ||
|
|
981b56b846 | ||
|
|
9f52ab2e54 | ||
|
|
8fada3ac04 | ||
|
|
5330013dc3 | ||
|
|
c7e0461a86 | ||
|
|
032c1daf30 | ||
|
|
d1efebe068 | ||
|
|
c77e2b3fd8 | ||
|
|
e92847e628 | ||
|
|
afb18ccff7 | ||
|
|
4659a9362d | ||
|
|
fe6e1e6266 | ||
|
|
c0faff5b05 | ||
|
|
f4ffa2cdda | ||
|
|
1409d4ef80 | ||
|
|
51e662fdda | ||
|
|
72950fdab2 | ||
|
|
b9f594896a | ||
|
|
8551e56e42 | ||
|
|
f4fc182d5e | ||
|
|
ee1e948a65 | ||
|
|
e3081a971e | ||
|
|
7c5bf9473e | ||
|
|
5a44a8e9c5 | ||
|
|
d1a0eaffab | ||
|
|
10322bf24e | ||
|
|
969cd93358 | ||
|
|
b3a8b1a682 | ||
|
|
2774a73d83 | ||
|
|
739eaad199 | ||
|
|
b53b72d604 | ||
|
|
85fd9e9ee3 | ||
|
|
57e6e98423 | ||
|
|
e3c6bdb50d | ||
|
|
1f89b202b4 | ||
|
|
0a31107e56 | ||
|
|
9237f0dd43 | ||
|
|
ce834a634c | ||
|
|
f65607cb00 | ||
|
|
b0475f262f | ||
|
|
cee824ad46 | ||
|
|
530e977d9d | ||
|
|
807cb68f0f | ||
|
|
3850740ded | ||
|
|
cfc7b302fe | ||
|
|
a7c28a8d0d | ||
|
|
9fe1a94d42 | ||
|
|
1eee56a666 | ||
|
|
28fe6e9634 | ||
|
|
4512f44ea1 | ||
|
|
3efd31bc84 | ||
|
|
5684134894 | ||
|
|
e6c97de3c4 | ||
|
|
f550d0bba9 | ||
|
|
2b4fec6d11 | ||
|
|
550c658ac5 | ||
|
|
da41862f49 | ||
|
|
d5769ce9be | ||
|
|
4bf9244005 | ||
|
|
89f63024ab | ||
|
|
f258678751 | ||
|
|
35a3dab1ce | ||
|
|
4d2f68068d | ||
|
|
131ade02cd | ||
|
|
2c2f76b340 | ||
|
|
106d8e5863 | ||
|
|
1fb7cb6bc1 | ||
|
|
9666fff622 | ||
|
|
5d5f155f0c | ||
|
|
cfe348770c | ||
|
|
206120dcef | ||
|
|
2a3bb1bef8 | ||
|
|
0faa46d48c | ||
|
|
dae52a71fd | ||
|
|
c46c36bf09 | ||
|
|
ed3d0834e6 | ||
|
|
9d4c6e880b | ||
|
|
d39b5d7c77 | ||
|
|
b071906db5 | ||
|
|
8420cdb5bf | ||
|
|
e11211f201 | ||
|
|
9595ef164e | ||
|
|
d18afdf84b | ||
|
|
0acbb70d10 | ||
|
|
7a3848e640 | ||
|
|
261aa8f320 | ||
|
|
e994cdd8a2 | ||
|
|
44e0f3aa21 | ||
|
|
8853cef809 | ||
|
|
fb76b8309a | ||
|
|
a23946dddf | ||
|
|
55ee1d3747 | ||
|
|
4cd0093687 | ||
|
|
cc88734279 | ||
|
|
a865c95e2a | ||
|
|
9f636345ef | ||
|
|
3d0d5e9e4c | ||
|
|
a1ca8e0576 | ||
|
|
b22f21a6b2 | ||
|
|
531a901431 | ||
|
|
46f778bd01 | ||
|
|
f3b6eea418 | ||
|
|
bceb3aefe4 | ||
|
|
6c72432992 | ||
|
|
17d3f303ca | ||
|
|
2cbcf96282 | ||
|
|
7d4fd44dbf | ||
|
|
71c2af1224 | ||
|
|
2e112fc5f1 | ||
|
|
96c93a6aa6 | ||
|
|
9dbb91fd84 | ||
|
|
26c33ae2fb | ||
|
|
3eb943309e | ||
|
|
3c8e8399cb | ||
|
|
5b500a3da5 | ||
|
|
ade19123b7 | ||
|
|
5ee18e0576 | ||
|
|
77d23caa63 | ||
|
|
79856cde8e | ||
|
|
7bc230974a | ||
|
|
b1ab7e65da | ||
|
|
c82c53e3d1 | ||
|
|
9e861ab993 | ||
|
|
ae11ba5f0d | ||
|
|
1427966d1a | ||
|
|
db92f2867d | ||
|
|
208a41d45f | ||
|
|
f2915f9c2a | ||
|
|
1abf6d5adf | ||
|
|
f626474b4f | ||
|
|
6f3960d2c2 | ||
|
|
6cb19a7991 | ||
|
|
4fe3c50edd | ||
|
|
fe7335fb0e | ||
|
|
40cd203047 | ||
|
|
1fc03500f0 | ||
|
|
73729746ff | ||
|
|
ffdf4dce60 | ||
|
|
bb5d7fdcf4 | ||
|
|
2df2475b59 | ||
|
|
bb32b9cfea | ||
|
|
3f034264f9 | ||
|
|
c67fffed58 | ||
|
|
f50b821733 | ||
|
|
1e5d19bca4 | ||
|
|
1011de1971 | ||
|
|
7336d63f58 | ||
|
|
c5d7369088 | ||
|
|
c3a463552f | ||
|
|
ae9462898e | ||
|
|
529b7e2ae4 | ||
|
|
1bee72a175 | ||
|
|
f1e1b6cc28 | ||
|
|
573bd77bbd | ||
|
|
770e03e3c6 | ||
|
|
11d4522dc7 | ||
|
|
830bc47987 | ||
|
|
bec698fbdc | ||
|
|
60cc835daf | ||
|
|
a85ce18589 | ||
|
|
1228c2fabe | ||
|
|
3da0af37e4 | ||
|
|
baa41dd65a | ||
|
|
534b457f48 | ||
|
|
029cf94e68 | ||
|
|
15f7a6ba85 | ||
|
|
86b5d91579 | ||
|
|
31486bcb56 | ||
|
|
08660d83dc | ||
|
|
6d8f75a577 | ||
|
|
018246cea5 | ||
|
|
a584e25bf3 | ||
|
|
d4d773b769 | ||
|
|
56a02f0215 | ||
|
|
7231c69e10 | ||
|
|
3c68dfaeaf | ||
|
|
69709968fd | ||
|
|
5b9effad85 | ||
|
|
808ab94c68 | ||
|
|
e7ae71513c | ||
|
|
b825e5685b | ||
|
|
e47821416a | ||
|
|
50549f3d1a | ||
|
|
f323d50e34 | ||
|
|
24994d7dde | ||
|
|
77337204e5 | ||
|
|
dad1acbb91 | ||
|
|
8b755e6b7b | ||
|
|
7ccc5a963a | ||
|
|
ca24339c9a | ||
|
|
fc201efa4b | ||
|
|
533c8c80e1 | ||
|
|
78fb81004e | ||
|
|
942b7baa74 | ||
|
|
aa72b2507e | ||
|
|
9860240e24 | ||
|
|
cda8168c58 | ||
|
|
667bd7f7c8 | ||
|
|
b524aa67de | ||
|
|
e35d1b5457 | ||
|
|
1875c8832d | ||
|
|
61726ea3ab | ||
|
|
e4d6c86919 | ||
|
|
eaa6b5322f | ||
|
|
2c06a98e00 | ||
|
|
e73d578797 | ||
|
|
704e25636d | ||
|
|
c7cf0a733e | ||
|
|
24a34d7a97 | ||
|
|
1c98921127 | ||
|
|
2d898f8665 | ||
|
|
229914ac74 | ||
|
|
3258b04dad | ||
|
|
603663ed2c | ||
|
|
44f2fdfa7c | ||
|
|
19abb5b68c | ||
|
|
dd5b0bdd6d | ||
|
|
9c9f503e5c | ||
|
|
b4850f09a9 | ||
|
|
3094d382ff | ||
|
|
940a39ed4e | ||
|
|
23b39bb6c7 | ||
|
|
2cd6e21f8c | ||
|
|
3c6aa741ef | ||
|
|
e79318e49a | ||
|
|
e8938968f2 | ||
|
|
e6f79a8dd1 | ||
|
|
347e72ce90 | ||
|
|
a90c67f47d | ||
|
|
956b2ef5b5 | ||
|
|
31d68249a8 | ||
|
|
6d3e053c71 | ||
|
|
87a1564c0a | ||
|
|
e6109c98bd | ||
|
|
c372e63bd1 | ||
|
|
709ac1dd58 | ||
|
|
6ead6bbb1e | ||
|
|
50fb023eff | ||
|
|
08d043da8d | ||
|
|
c623bdea91 | ||
|
|
b953bae5da | ||
|
|
e039eeaab8 | ||
|
|
15cad02e13 | ||
|
|
67f22c7d76 | ||
|
|
632a5f2801 | ||
|
|
44fa68e6da | ||
|
|
33e0cac4c1 | ||
|
|
a7f1e93ca2 | ||
|
|
f8a9d01749 | ||
|
|
356354d1eb | ||
|
|
40cae31885 | ||
|
|
05c5fb047c | ||
|
|
83145d7466 | ||
|
|
3c48ac6145 | ||
|
|
3fe8d48ada | ||
|
|
f0abfcc0ef | ||
|
|
7410e31230 | ||
|
|
3bc8744b63 | ||
|
|
c076c83edc | ||
|
|
776ddcbbef | ||
|
|
9a74434bbb | ||
|
|
3e2cb3176a | ||
|
|
7cd420a1a5 | ||
|
|
4edd1ac100 | ||
|
|
8e4006fc38 | ||
|
|
ab44ac8c15 | ||
|
|
266303b09d | ||
|
|
b777781c96 | ||
|
|
714d31fb45 | ||
|
|
d481fcd3a7 | ||
|
|
df3269756c | ||
|
|
aadcd1abe5 | ||
|
|
57fc0ea74d | ||
|
|
fe4a1b28b5 | ||
|
|
30916c41c3 | ||
|
|
fab20276ff | ||
|
|
7e6d5ce359 | ||
|
|
6aed93fbf1 | ||
|
|
9b1bf071a8 | ||
|
|
f52308c439 | ||
|
|
0580ad67fd | ||
|
|
218504e674 | ||
|
|
f13523fbe5 | ||
|
|
b81ac35b37 | ||
|
|
8664522d1d | ||
|
|
c15046f8b1 | ||
|
|
c7f8b2b131 | ||
|
|
84252e892e | ||
|
|
32038046d5 | ||
|
|
e04a569e33 | ||
|
|
13f8be5d39 | ||
|
|
bca4b3f140 | ||
|
|
b3256062f7 | ||
|
|
51dbfe0482 | ||
|
|
92a67c7305 | ||
|
|
cc5a878692 | ||
|
|
5759a6f80f | ||
|
|
3dd2e1c278 | ||
|
|
4826fb5fc2 | ||
|
|
8cd35d64e4 | ||
|
|
aec6ad9c14 | ||
|
|
d360403c56 | ||
|
|
bf74b1ae32 | ||
|
|
f19a012509 | ||
|
|
72607583bf | ||
|
|
ef5db013b3 | ||
|
|
4cda6e8bc3 | ||
|
|
459814a6ec | ||
|
|
e5e447c7af | ||
|
|
6a2ce7faab | ||
|
|
ce8661159b | ||
|
|
f5ecc251e7 | ||
|
|
45b3057ed5 | ||
|
|
0476ffa990 | ||
|
|
43690d0833 | ||
|
|
f9cb9af078 | ||
|
|
e4979bb6e2 | ||
|
|
5266ac418b | ||
|
|
ffca27ae6a | ||
|
|
cd1aba7afb | ||
|
|
50b3a9ea19 | ||
|
|
d8f49edb6b | ||
|
|
ec0987e5c1 | ||
|
|
e4fa9a23fa | ||
|
|
0fe4913928 | ||
|
|
bd349556f0 | ||
|
|
dc9c3255de | ||
|
|
d5541ae154 | ||
|
|
467e5a64c3 | ||
|
|
3bb9b17d47 | ||
|
|
51f0b504b7 | ||
|
|
2e48cef647 | ||
|
|
0fe7050166 | ||
|
|
a25cc00093 | ||
|
|
e2e23635bc | ||
|
|
a20f632e3e | ||
|
|
5f3fecb92c | ||
|
|
710bb939ad | ||
|
|
00b7d1ca96 | ||
|
|
7e8b86cf57 | ||
|
|
d47e721b38 | ||
|
|
33a7d0e1a1 | ||
|
|
480c78c9f2 | ||
|
|
d0a7b56e75 | ||
|
|
f6121704df | ||
|
|
c75acbff76 | ||
|
|
d394d7b5a6 | ||
|
|
4e1d2a7ddd | ||
|
|
2571cb1478 | ||
|
|
c387cc3610 | ||
|
|
769c19b811 | ||
|
|
b62676daf4 | ||
|
|
cd19cd343a |
29
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
29
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: "[Bug] Enter issue title here"
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Fill out general information**
|
||||
OS (windows, linux, ...):
|
||||
BeamMP-Server Version:
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Do x ...
|
||||
2. Do y ...
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Logs**
|
||||
Please attach the `Server.log` from the run in which the issue appeared, preferably with Debug turned on in the `ServerConfig.toml`.
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: "[Feature Request]"
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. For example: "I'm always frustrated when ...".
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen. Also supply OS information if relevant, for example "*On Linux*, I would like to be able to...".
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the feature request here.
|
||||
83
.github/workflows/cmake-linux.yml
vendored
Normal file
83
.github/workflows/cmake-linux.yml
vendored
Normal file
@@ -0,0 +1,83 @@
|
||||
name: CMake Linux Build
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
types: [opened, reopened]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
env:
|
||||
BUILD_TYPE: Release
|
||||
|
||||
jobs:
|
||||
linux-build:
|
||||
runs-on: ubuntu-20.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: "recursive"
|
||||
|
||||
- name: Install Dependencies
|
||||
env:
|
||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
||||
run: |
|
||||
echo ${#beammp_sentry_url}
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10
|
||||
|
||||
- name: Create Build Environment
|
||||
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
||||
|
||||
- name: Configure CMake
|
||||
shell: bash
|
||||
working-directory: ${{github.workspace}}/build-linux
|
||||
env:
|
||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
||||
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10 -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
||||
|
||||
- name: Build Server
|
||||
working-directory: ${{github.workspace}}/build-linux
|
||||
shell: bash
|
||||
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server --parallel
|
||||
|
||||
- name: Build Tests
|
||||
working-directory: ${{github.workspace}}/build-linux
|
||||
shell: bash
|
||||
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server-tests --parallel
|
||||
|
||||
- name: Archive server artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: BeamMP-Server-linux
|
||||
path: ${{github.workspace}}/build-linux/BeamMP-Server
|
||||
|
||||
- name: Archive test artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: BeamMP-Server-linux-tests
|
||||
path: ${{github.workspace}}/build-linux/BeamMP-Server-tests
|
||||
|
||||
run-tests:
|
||||
needs: linux-build
|
||||
runs-on: ubuntu-20.04
|
||||
|
||||
steps:
|
||||
- uses: actions/download-artifact@master
|
||||
with:
|
||||
name: BeamMP-Server-linux-tests
|
||||
path: ${{github.workspace}}
|
||||
|
||||
- name: Install Runtime Dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y liblua5.3 openssl
|
||||
|
||||
- name: Test
|
||||
working-directory: ${{github.workspace}}
|
||||
shell: bash
|
||||
run: |
|
||||
chmod +x ./BeamMP-Server-tests
|
||||
./BeamMP-Server-tests
|
||||
62
.github/workflows/cmake-windows.yml
vendored
Normal file
62
.github/workflows/cmake-windows.yml
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
name: CMake Windows Build
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
types: [opened, reopened]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
env:
|
||||
BUILD_TYPE: Release
|
||||
|
||||
jobs:
|
||||
windows-build:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: "recursive"
|
||||
|
||||
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
||||
uses: lukka/run-vcpkg@v7
|
||||
id: runvcpkg
|
||||
with:
|
||||
vcpkgArguments: "lua zlib rapidjson openssl websocketpp curl"
|
||||
vcpkgDirectory: "${{ runner.workspace }}/b/vcpkg"
|
||||
vcpkgGitCommitId: "a106de33bbee694e3be6243718aa2a549a692832"
|
||||
vcpkgTriplet: "x64-windows-static"
|
||||
|
||||
- name: Create Build Environment
|
||||
run: cmake -E make_directory ${{github.workspace}}/build-windows
|
||||
|
||||
- name: Configure CMake
|
||||
shell: bash
|
||||
working-directory: ${{github.workspace}}/build-windows
|
||||
env:
|
||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
||||
run: cmake $GITHUB_WORKSPACE -DSENTRY_BACKEND=breakpad -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
||||
|
||||
- name: Build
|
||||
working-directory: ${{github.workspace}}/build-windows
|
||||
shell: bash
|
||||
run: cmake --build . --config $BUILD_TYPE
|
||||
|
||||
- name: Archive artifacts
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: BeamMP-Server.exe
|
||||
path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe
|
||||
|
||||
- name: Build debug
|
||||
working-directory: ${{github.workspace}}/build-windows
|
||||
shell: bash
|
||||
run: |
|
||||
cmake --build . --config Debug
|
||||
|
||||
- name: Archive debug artifacts
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: BeamMP-Server-debug.exe
|
||||
path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe
|
||||
115
.github/workflows/release-build.yml
vendored
Normal file
115
.github/workflows/release-build.yml
vendored
Normal file
@@ -0,0 +1,115 @@
|
||||
name: Release Create & Build
|
||||
on:
|
||||
push:
|
||||
# Sequence of patterns matched against refs/tags
|
||||
tags:
|
||||
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
|
||||
|
||||
env:
|
||||
BUILD_TYPE: Release
|
||||
|
||||
jobs:
|
||||
create-release:
|
||||
runs-on: ubuntu-latest
|
||||
name: Create Release
|
||||
outputs:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
steps:
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ github.ref }}
|
||||
release_name: ${{ github.ref }}
|
||||
draft: false
|
||||
prerelease: true
|
||||
body: |
|
||||
Files included in this release:
|
||||
- `BeamMP-Server.exe` is the windows build
|
||||
- `BeamMP-Server-linux` is a ubuntu build, so you need the dependencies listed in README.md to run it. For any other distros please build from source as described in README.md.
|
||||
|
||||
upload-release-files-linux:
|
||||
name: Upload Linux Release Files
|
||||
runs-on: ubuntu-latest
|
||||
needs: create-release
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
|
||||
- name: Install Dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
|
||||
|
||||
- name: Create Build Environment
|
||||
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
||||
|
||||
- name: Configure CMake
|
||||
shell: bash
|
||||
working-directory: ${{github.workspace}}/build-linux
|
||||
env:
|
||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
||||
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10 -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
||||
|
||||
- name: Build
|
||||
working-directory: ${{github.workspace}}/build-linux
|
||||
shell: bash
|
||||
run: cmake --build . --config $BUILD_TYPE
|
||||
|
||||
- name: Upload Release Asset
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
|
||||
asset_path: ${{github.workspace}}/build-linux/BeamMP-Server
|
||||
asset_name: BeamMP-Server-linux
|
||||
asset_content_type: application/x-elf
|
||||
|
||||
upload-release-files-windows:
|
||||
name: Upload Windows Release Files
|
||||
runs-on: windows-latest
|
||||
needs: create-release
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
|
||||
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
||||
uses: lukka/run-vcpkg@v7
|
||||
id: runvcpkg
|
||||
with:
|
||||
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl'
|
||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
||||
vcpkgGitCommitId: 'a106de33bbee694e3be6243718aa2a549a692832'
|
||||
vcpkgTriplet: 'x64-windows-static'
|
||||
|
||||
- name: Create Build Environment
|
||||
run: cmake -E make_directory ${{github.workspace}}/build-windows
|
||||
|
||||
- name: Configure CMake
|
||||
shell: bash
|
||||
working-directory: ${{github.workspace}}/build-windows
|
||||
env:
|
||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
||||
run: cmake $GITHUB_WORKSPACE -DSENTRY_BACKEND=breakpad -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
||||
|
||||
- name: Build
|
||||
working-directory: ${{github.workspace}}/build-windows
|
||||
shell: bash
|
||||
run: cmake --build . --config $BUILD_TYPE
|
||||
|
||||
- name: Upload Release Asset
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
|
||||
asset_path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe
|
||||
asset_name: BeamMP-Server.exe
|
||||
asset_content_type: application/vnd.microsoft.portable-executable
|
||||
39
.gitignore
vendored
39
.gitignore
vendored
@@ -1,5 +1,10 @@
|
||||
.idea/
|
||||
.sentry-native/
|
||||
*.orig
|
||||
*.toml
|
||||
boost_*
|
||||
Resources
|
||||
run-in-env.sh
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
@@ -22,16 +27,9 @@ mono_crash.*
|
||||
out/
|
||||
|
||||
#Clion Files
|
||||
cmake-build-debug/CMakeFiles/
|
||||
cmake-build-release/CMakeFiles/
|
||||
cmake-build-debug/Resources/
|
||||
cmake-build-release/Resources/
|
||||
cmake-build-debug/*.*
|
||||
cmake-build-release/*.*
|
||||
cmake-build-debug/Makefile
|
||||
cmake-build-release/Makefile
|
||||
!cmake-build-debug/*.lib
|
||||
!cmake-build-release/*.lib
|
||||
cmake-build-debug/
|
||||
cmake-build-release/
|
||||
.idea/
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
@@ -51,7 +49,6 @@ bld/
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
@@ -462,3 +459,23 @@ out/build/x86-Debug/.cmake/api/v1/reply/index-2020-01-28T17-35-38-0764.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/codemodel-v2-6a61e390ef8eaf17e9f8.json
|
||||
out/build/x86-Debug/Server.cfg
|
||||
*Server.cfg*
|
||||
*.cmake
|
||||
*.make
|
||||
*.xml
|
||||
*.includecache
|
||||
cmake-build-release/include/commandline/Makefile
|
||||
*.lib
|
||||
*.cbp
|
||||
*.marks
|
||||
*.internal
|
||||
*.xml
|
||||
cmake-build-debug/include/commandline/Makefile
|
||||
*.manifest
|
||||
*.rc
|
||||
*.res
|
||||
BeamMP-Server
|
||||
*.patch
|
||||
callgrind.*
|
||||
notes/*
|
||||
compile_commands.json
|
||||
nohup.out
|
||||
|
||||
33
.gitmodules
vendored
Normal file
33
.gitmodules
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
[submodule "deps/commandline"]
|
||||
path = deps/commandline
|
||||
url = https://github.com/lionkor/commandline
|
||||
[submodule "deps/asio"]
|
||||
path = deps/asio
|
||||
url = https://github.com/chriskohlhoff/asio
|
||||
[submodule "deps/rapidjson"]
|
||||
path = deps/rapidjson
|
||||
url = https://github.com/Tencent/rapidjson
|
||||
[submodule "deps/toml11"]
|
||||
path = deps/toml11
|
||||
url = https://github.com/ToruNiina/toml11
|
||||
[submodule "deps/sentry-native"]
|
||||
path = deps/sentry-native
|
||||
url = https://github.com/getsentry/sentry-native
|
||||
[submodule "deps/sol2"]
|
||||
path = deps/sol2
|
||||
url = https://github.com/ThePhD/sol2
|
||||
[submodule "deps/libzip"]
|
||||
path = deps/libzip
|
||||
url = https://github.com/nih-at/libzip
|
||||
[submodule "deps/cpp-httplib"]
|
||||
path = deps/cpp-httplib
|
||||
url = https://github.com/yhirose/cpp-httplib
|
||||
[submodule "deps/json"]
|
||||
path = deps/json
|
||||
url = https://github.com/nlohmann/json
|
||||
[submodule "deps/fmt"]
|
||||
path = deps/fmt
|
||||
url = https://github.com/fmtlib/fmt
|
||||
[submodule "deps/doctest"]
|
||||
path = deps/doctest
|
||||
url = https://github.com/doctest/doctest
|
||||
2
.idea/.gitignore
generated
vendored
2
.idea/.gitignore
generated
vendored
@@ -1,2 +0,0 @@
|
||||
# Default ignored files
|
||||
/workspace.xml
|
||||
1
.idea/.name
generated
1
.idea/.name
generated
@@ -1 +0,0 @@
|
||||
Server
|
||||
2
.idea/BeamNG-MP-Server.iml
generated
2
.idea/BeamNG-MP-Server.iml
generated
@@ -1,2 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module classpath="CMake" type="CPP_MODULE" version="4" />
|
||||
7
.idea/misc.xml
generated
7
.idea/misc.xml
generated
@@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" />
|
||||
<component name="JavaScriptSettings">
|
||||
<option name="languageLevel" value="ES6" />
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/vcs.xml
generated
6
.idea/vcs.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
231
CMakeLists.txt
231
CMakeLists.txt
@@ -1,43 +1,208 @@
|
||||
cmake_minimum_required(VERSION 3.13)
|
||||
project(Server)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
# 3.4 is required for imported targets.
|
||||
cmake_minimum_required(VERSION 3.4 FATAL_ERROR)
|
||||
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
|
||||
message(STATUS "You can find build instructions and a list of dependencies in the README at \
|
||||
https://github.com/BeamMP/BeamMP-Server")
|
||||
|
||||
if (UNIX)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic -static-libstdc++")
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Og -g")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -s -fno-builtin")
|
||||
project(BeamMP-Server
|
||||
DESCRIPTION "Server for BeamMP - The Multiplayer Mod for BeamNG.drive"
|
||||
HOMEPAGE_URL https://beammp.com
|
||||
LANGUAGES CXX C)
|
||||
|
||||
find_package(Git REQUIRED)
|
||||
# Update submodules as needed
|
||||
option(GIT_SUBMODULE "Check submodules during build" ON)
|
||||
if(GIT_SUBMODULE)
|
||||
message(STATUS "Submodule update")
|
||||
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||
message(FATAL_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
|
||||
set(HTTPLIB_REQUIRE_OPENSSL ON)
|
||||
set(SENTRY_BUILD_SHARED_LIBS OFF)
|
||||
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/asio/asio/include")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/rapidjson/include")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/websocketpp")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/commandline")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/sol2/include")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/cpp-httplib")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/json/single_include")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps")
|
||||
|
||||
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1)
|
||||
|
||||
# ------------------------ APPLE ---------------------------------
|
||||
if(APPLE)
|
||||
if(IS_DIRECTORY /opt/homebrew/Cellar/lua@5.3/5.3.6)
|
||||
set(LUA_INCLUDE_DIR /opt/homebrew/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
||||
link_directories(/opt/homebrew/Cellar/lua@5.3/5.3.6/lib)
|
||||
else()
|
||||
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
||||
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
|
||||
endif()
|
||||
set(LUA_LIBRARIES lua)
|
||||
if(IS_DIRECTORY /opt/homebrew/opt/openssl@1.1)
|
||||
include_directories(/opt/homebrew/opt/openssl@1.1/include)
|
||||
link_directories(/opt/homebrew/opt/openssl@1.1/lib)
|
||||
else()
|
||||
include_directories(/usr/local/opt/openssl@1.1/include)
|
||||
link_directories(/usr/local/opt/openssl@1.1/lib)
|
||||
endif()
|
||||
# ------------------------ WINDOWS ---------------------------------
|
||||
elseif (WIN32)
|
||||
# This might cause issues with old windows headers, but it's worth the trouble to keep the code
|
||||
# completely cross platform. For fixes to common issues arising from /permissive- visit:
|
||||
# https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance
|
||||
|
||||
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /permissive-")
|
||||
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
||||
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
||||
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
|
||||
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
||||
#-DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
||||
# ------------------------ LINUX ---------------------------------
|
||||
elseif (UNIX)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic -static-libstdc++ -static-libgcc")
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -fno-builtin")
|
||||
option(SANITIZE "Turns on thread and UB sanitizers" OFF)
|
||||
if (SANITIZE)
|
||||
message(STATUS "sanitize is ON")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined,thread")
|
||||
endif (SANITIZE)
|
||||
endif ()
|
||||
|
||||
#find_package(Boost 1.70.0 REQUIRED COMPONENTS system thread)
|
||||
include_directories("include/sentry-native/include")
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
# ------------------------ SENTRY ---------------------------------
|
||||
message(STATUS "Checking for Sentry URL")
|
||||
# this is set by the build system.
|
||||
# IMPORTANT: if you're building from source, just leave this empty
|
||||
if (NOT DEFINED BEAMMP_SECRET_SENTRY_URL)
|
||||
message(WARNING "No sentry URL configured. Sentry logging is disabled for this build. \
|
||||
This is not an error, and if you're building the BeamMP-Server yourself, this is expected and can be ignored.")
|
||||
set(BEAMMP_SECRET_SENTRY_URL "")
|
||||
set(SENTRY_BACKEND none)
|
||||
else()
|
||||
set(SENTRY_BACKEND breakpad)
|
||||
endif()
|
||||
add_subdirectory("deps/sentry-native")
|
||||
|
||||
file(GLOB source_files "src/*.cpp" "include/*.h" "include/*/*.h" "include/*/*/*.h" "include/*.hpp" "include/*/*.hpp" "src/*/*.cpp")
|
||||
add_executable(BeamMP-Server ${source_files})
|
||||
|
||||
target_include_directories(BeamMP-Server PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
|
||||
|
||||
find_package(Lua REQUIRED)
|
||||
target_include_directories(BeamMP-Server PUBLIC ${LUA_INCLUDE_DIR})
|
||||
|
||||
if (UNIX)
|
||||
target_link_libraries(BeamMP-Server z pthread stdc++fs ${Boost_LINK_DIRS} ${LUA_LIBRARIES} curl dl)
|
||||
elseif (WIN32)
|
||||
include(FindLua)
|
||||
find_package(ZLIB REQUIRED)
|
||||
find_package(CURL CONFIG REQUIRED)
|
||||
find_package(RapidJSON CONFIG REQUIRED)
|
||||
target_include_directories(BeamMP-Server PRIVATE ${RAPIDJSON_INCLUDE_DIRS})
|
||||
target_link_libraries(BeamMP-Server PRIVATE ws2_32 CURL::libcurl ZLIB::ZLIB ${LUA_LIBRARIES})
|
||||
#${Boost_LINK_DIRS}
|
||||
# ------------------------ C++ SETUP ---------------------------------
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
if (MSVC)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
|
||||
endif ()
|
||||
|
||||
# ------------------------ DEPENDENCIES ------------------------------
|
||||
message(STATUS "Adding local source dependencies")
|
||||
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
|
||||
add_subdirectory(deps)
|
||||
|
||||
# ------------------------ VARIABLES ---------------------------------
|
||||
|
||||
include(FindLua)
|
||||
include(FindOpenSSL)
|
||||
include(FindThreads)
|
||||
include(FindZLIB)
|
||||
|
||||
set(BeamMP_Sources
|
||||
include/TConsole.h src/TConsole.cpp
|
||||
include/TServer.h src/TServer.cpp
|
||||
include/Compat.h src/Compat.cpp
|
||||
include/Common.h src/Common.cpp
|
||||
include/Client.h src/Client.cpp
|
||||
include/VehicleData.h src/VehicleData.cpp
|
||||
include/TConfig.h src/TConfig.cpp
|
||||
include/TLuaEngine.h src/TLuaEngine.cpp
|
||||
include/TLuaPlugin.h src/TLuaPlugin.cpp
|
||||
include/TResourceManager.h src/TResourceManager.cpp
|
||||
include/THeartbeatThread.h src/THeartbeatThread.cpp
|
||||
include/Http.h src/Http.cpp
|
||||
include/TSentry.h src/TSentry.cpp
|
||||
include/TPPSMonitor.h src/TPPSMonitor.cpp
|
||||
include/TNetwork.h src/TNetwork.cpp
|
||||
include/LuaAPI.h src/LuaAPI.cpp
|
||||
include/TScopedTimer.h src/TScopedTimer.cpp
|
||||
include/SignalHandling.h src/SignalHandling.cpp
|
||||
include/ArgsParser.h src/ArgsParser.cpp
|
||||
include/TPluginMonitor.h src/TPluginMonitor.cpp
|
||||
include/Environment.h
|
||||
)
|
||||
|
||||
set(BeamMP_Includes
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/commandline"
|
||||
${LUA_INCLUDE_DIR}
|
||||
${CURL_INCLUDE_DIRS}
|
||||
"include/tomlplusplus"
|
||||
"include/sentry-native/include"
|
||||
"include/curl/include"
|
||||
)
|
||||
|
||||
set(BeamMP_Definitions
|
||||
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
|
||||
)
|
||||
|
||||
set(BeamMP_Libraries
|
||||
doctest::doctest
|
||||
OpenSSL::SSL
|
||||
OpenSSL::Crypto
|
||||
sol2::sol2
|
||||
fmt::fmt
|
||||
Threads::Threads
|
||||
ZLIB::ZLIB
|
||||
${LUA_LIBRARIES}
|
||||
commandline
|
||||
sentry
|
||||
)
|
||||
|
||||
if (WIN32)
|
||||
set(BeamMP_PlatformLibs wsock32 ws2_32)
|
||||
endif ()
|
||||
|
||||
# ------------------------ BEAMMP SERVER -----------------------------
|
||||
|
||||
add_executable(BeamMP-Server
|
||||
src/main.cpp
|
||||
${BeamMP_Sources}
|
||||
)
|
||||
|
||||
target_compile_definitions(BeamMP-Server PRIVATE
|
||||
${BeamMP_Definitions}
|
||||
DOCTEST_CONFIG_DISABLE
|
||||
)
|
||||
|
||||
target_include_directories(BeamMP-Server PUBLIC
|
||||
${BeamMP_Includes}
|
||||
)
|
||||
|
||||
target_link_libraries(BeamMP-Server
|
||||
${BeamMP_Libraries}
|
||||
${BeamMP_PlatformLibs}
|
||||
)
|
||||
|
||||
# ------------------------ BEAMMP SERVER TESTS -----------------------
|
||||
|
||||
option(BUILD_TESTS "Build BeamMP-Server tests" ON)
|
||||
|
||||
if(BUILD_TESTS)
|
||||
add_executable(BeamMP-Server-tests
|
||||
test/test_main.cpp
|
||||
${BeamMP_Sources}
|
||||
)
|
||||
|
||||
target_compile_definitions(BeamMP-Server-tests PRIVATE
|
||||
${BeamMP_Definitions}
|
||||
)
|
||||
|
||||
target_include_directories(BeamMP-Server-tests PUBLIC
|
||||
${BeamMP_Includes}
|
||||
)
|
||||
|
||||
target_link_libraries(BeamMP-Server-tests
|
||||
${BeamMP_Libraries}
|
||||
${BeamMP_PlatformLibs}
|
||||
)
|
||||
endif()
|
||||
|
||||
|
||||
111
CONTRIBUTING.md
Normal file
111
CONTRIBUTING.md
Normal file
@@ -0,0 +1,111 @@
|
||||
# Contributing to BeamMP-Server
|
||||
|
||||
Unlike other parts of BeamMP, the BeamMP-Server does not have any dependency to the BeamNG.drive game.
|
||||
|
||||
To contribute *C++ code*, you'll need a MacOS, Linux or Windows PC, and intermediate to advanced knowledge of C++.
|
||||
For reference, you should know be reasonably comfortable with the STL, the concept of RAII, templates, and generally know how to read & write post-C++17 code. To contribute anything else, you won't need most of this (though it'd be helpful to have some vocabulary about computers).
|
||||
|
||||
# Ways to Contribute
|
||||
|
||||
## Bug Reports
|
||||
|
||||
If you work with BeamMP-Server, either by simply using it, or even writing plugins for it, and you run into any issues, we definitely want to know about it. Please use [GitHub issues](https://github.com/BeamMP/BeamMP-Server/issues) and select the "Bug" template, read it, and fill it out accordingly.
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
If you are interested in fixing bugs, check out the [GitHub issues](https://github.com/BeamMP/BeamMP-Server/issues). There, you can pick any issue that has nobody assigned to it. For example, some bugs which we definitely need some help with are marked with the "help wanted" tag.
|
||||
|
||||
Once you picked a bug, you need to reproduce it. Start by following the instructions in the bug report, and don't be afraid to ask for more information or clarification on the issue itself.
|
||||
|
||||
Refer to [getting started with the codebase](#getting-started-with-the-codebase) for more information on how to build the server. You can also ask on our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`).
|
||||
|
||||
## Features
|
||||
|
||||
If you want to add new features, please make an issue for it first or ask on our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`).
|
||||
|
||||
You need to make sure the feature isn't being worked on by someone else, and aligns with the vision we have for the server.
|
||||
|
||||
# Git Guidelines
|
||||
|
||||
**Read this carefully. Failing to follow these rules results in your changes not being accepted**. This applies for outside contributors, members of the BeamMP development team ("BeamMP Developers"), project owners, maintainers, frequent contributors, and literally everyone else. **It applies to everyone**.
|
||||
|
||||
## How to Commit
|
||||
|
||||
Commit messages **MUST** (mandatory):
|
||||
|
||||
- start with a **lower case action verb in present tense**, for example `add`, `fix`, `implement`, `refactor`, `remove`, `rename`. *Counter examples (these are bad): ~~`Fixed`, `fixing`, `added`, `removing`~~*.
|
||||
- not have a first line much longer than 70 characters.
|
||||
- explain briefly the changes made.
|
||||
- reference the issue by number, if there is an issue the commit addresses, like so: `#<number>`. Example: `#123`.
|
||||
|
||||
If any of these are not followed, **your changes will not be accepted.**
|
||||
|
||||
Commit messages **SHOULD** (optional, "nice to have"):
|
||||
|
||||
- only address one "atomic" change.
|
||||
- have an empty second line, and the subsequent lines explaining the changes in more detail (if more detail is available).
|
||||
|
||||
Commits may be squashed (via a Git "interactive rebase") in order to satisfy these rules, but history that is >1h old should not be rewritten if possible. Force pushes are ugly ;)
|
||||
|
||||
## Pulling, Merging
|
||||
|
||||
Do **NOT** pull with merge. This is the default git behavior for `git pull`, but creates ugly and unnecessary commit messages like `"merge origin/master into master"`. Instead, pull with rebase, for example via `git pull -r`. If you get conflicts, resolve them properly.
|
||||
|
||||
The only acceptable merge commits are those which actually merge functionally different branches into each other, for example for merging one feature branch into another.
|
||||
|
||||
## Branches
|
||||
|
||||
### Which branch should I base my work on?
|
||||
|
||||
Each *feature* or *bug-fix* is implemented on a new Git branch, branched off of the branch it should be based on. The `master` branch is usually stable, so we don't do development on it. It is always a safe bet to branch off of `master`, but it may be more work to merge later. Branches to base your work on are usually branches like `rc-v3.3.0`, when the latest public version is `3.2.0`, for example. These can often be found in Pull-Requests on GitHub which are tagged `Release Candidate`.
|
||||
|
||||
## Unit tests & CI/CD
|
||||
|
||||
We use GitHub Actions, which runs our unit-tests. PR's which fail these tests, or even fail any of our actions (which run automatically), will not be merged and require further changes until they compile, link, and all tests pass properly. If you have issues with this, feel free to ask in our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`)
|
||||
|
||||
### What should I call by branch?
|
||||
|
||||
Keep branch names **unique**, **descriptive**, and **shorter than 30 characters**. Names must be in present-tense, such as `fix-xyz`, **not** ~~`fixing-xyz`~~.
|
||||
|
||||
We generally use *feature branches*, so we keep one branch per feature or fix.
|
||||
|
||||
For example:
|
||||
- You want to fix issue number #123? You could call the branch `fix-123`.
|
||||
- You want to add a feature described in issue #456? You could call the branch `implement-456`.
|
||||
- You want to add a feature or fix a bug that has no issue? You should probably make an issue for it first! Or, if you're not ready for that yet, you could call it by the feature name or bug description, for example for a bug that makes cars disappear: `fix-disappearing-cars`.
|
||||
|
||||
## Pull Requests, Code Review
|
||||
|
||||
Once you are ready to show what you did, and get feedback on it, you open a Pull-Request on GitHub. Please make sure to pick the right branches, and a descriptive title. Mention any related issues with `#<issue number>`, for example `#123`.
|
||||
|
||||
Make sure to explain what the PR does, what it fixes, and what needs to still be done (if anything).
|
||||
|
||||
A BeamMP-Developer must review your code in detail, and leave a review. If this takes too long, feel free to @ a maintainer/developer, or leave another comment on the PR. It helps to say something like "Ready for review", for example.
|
||||
|
||||
# Getting Started with the Codebase
|
||||
|
||||
1. Look at current Pull-Requests, look at the git branches, or ask in our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`), in order to find out which branch you should work on to minimize conflict. See [this section on branches](#branches) for more info.
|
||||
2. Fork the repository (with that branch) on GitHub. GitHub, by default, gives you only the `master` branch when forking, so make sure you fork with other branches enabled when you want to work on a branch that isn't master (it's a checkbox when you fork).
|
||||
3. Clone the fork to your local machine.
|
||||
4. Check out the branch you want to work on (see 1.).
|
||||
5. Run `git submodule update --init --recursive`.
|
||||
6. Make a new branch for your feature or fix from the branch you are on. You can do this via `git checkout -b <branch name>`. See [this section on branches](#branches) for more info on branch naming.
|
||||
7. Install all dependencies. Those are usually listed in the `README.md` in the branch you're in, or, more reliably, in one of the files in `.github/workflows` (if you can read `yaml`).
|
||||
8. Run CMake to configure the project. You can find tutorials on this online. You will want to tell CMake to build with `CMAKE_BUILD_TYPE=Debug`, for example by passing it to CMake via the commandline switch `-DCMAKE_BUILD_TYPE=Debug`. You may also want to turn off sentry by setting `SENTRY_BACKEND=none` (for example via commandline switch `-DSENTRY_BACKEND=none`). An example invocation on Linux with GNU make would be
|
||||
`cmake . -DCMAKE_BUILD_TYPE=Debug -DSENTRY_BACKEND=none` .
|
||||
9. Build the `BeamMP-Server` target to build the BeamMP-Server, or the `BeamMP-Server-tests` target to build the unit-tests (does not include a working server). In the example from 8. (on Linux), you could build with `make BeamMP-Server`, `make -j BeamMP-Server` or `cmake --build . --parallel --target BeamMP-Server` . Or, on Windows, (in Visual Studio), you would just press some big green "run" or "debug" button.
|
||||
10. When making changes, refer to [this section on how to commit properly](#how-to-commit). Not following those guidelines will result in your changes being rejected, so please take a look.
|
||||
11. Make sure to add Unit-tests with `doctest` if you build new stuff. You can find examples all over the latest version of the codebase (search for `TEST_CASE`).
|
||||
|
||||
# Code Guidelines
|
||||
|
||||
## Formatting
|
||||
|
||||
1. Use `clang-format` to format your code before committig. A `.clang-format` file is provided in the root of the repository.
|
||||
2. All identifiers, type names, function names, etc. should be `PascalCase`. Type names may also have the `T` prefix, although this is not enforced (for example `TNetwork`).
|
||||
|
||||
## Modular code
|
||||
|
||||
Write code that is modular and testable. Generally, if you can write a good unit-test for it, it's modular. If you can't, it's not.
|
||||
|
||||
Don't overdo it though - sometimes its okay to just write code, do the job, be done with it. You'll get feedback on this in the code review for your PR.
|
||||
142
Changelog.md
Normal file
142
Changelog.md
Normal file
@@ -0,0 +1,142 @@
|
||||
|
||||
# v3.1.0
|
||||
|
||||
- ADDED Tab autocomplete in console, smart tab autocomplete (understands lua tables and types) in the lua console
|
||||
- ADDED lua debug facilities (type `:help` when attached to lua via `lua`)
|
||||
- ADDED MP.JsonEncode() and MP.JsonDecode(), which turn lua tables into json and vice-versa
|
||||
- ADDED FS.ListFiles and FS.ListDirectories
|
||||
- ADDED onFileChanged event, triggered when a server plugin file changes
|
||||
- ADDED MP.GetPositionRaw(), which can be used to retrieve the latest position packet per player, per vehicle
|
||||
- ADDED error messages to some lua functions
|
||||
- FIXED `ip` in MP.GetIdentifiers
|
||||
- FIXED issue with client->server events which contain ':'
|
||||
- FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink
|
||||
- FIXED onInit not being called on hot-reload
|
||||
- FIXED incorrect timing calculation of Lua EventTimer loop
|
||||
- FIXED bug which caused hot-reload not to report syntax errors
|
||||
- FIXED missing error messages on some event handler calls
|
||||
- FIXED vehicles not deleting for all players if an edit was cancelled by Lua
|
||||
|
||||
# v3.0.2
|
||||
|
||||
- ADDED Periodic update message if a new server is released
|
||||
- ADDED Config setting for the IP the http server listens on
|
||||
- CHANGED Default MaxPlayers to 8
|
||||
- CHANGED Default http server listen IP to localhost
|
||||
- FIXED `MP.CreateEventTimer` filling up the queue (see <https://wiki.beammp.com/en/Scripting/new-lua-scripting#mpcreateeventtimerevent_name-string-interval_ms-number-strategy-number-since-v302>)
|
||||
- FIXED `MP.TriggerClientEvent` not kicking the client if it failed
|
||||
- FIXED Lua result queue handling not checking all results
|
||||
- FIXED bug which caused ServerConfig.toml to generate incorrectly
|
||||
|
||||
# v3.0.1
|
||||
|
||||
- ADDED Backup URLs to UpdateCheck (will fail less often now)
|
||||
- ADDED console cursor left and right movement (with arrow keys) and working HOME and END key (via github.com/lionkor/commandline)
|
||||
- FIXED infinite snowmen / infinite unicycle spawning bug
|
||||
- FIXED a bug where, when run with --working-directory, the Server.log would still be in the original directory
|
||||
- FIXED a bug which could cause the plugin reload thread to spin at 100% if the reloaded plugin's didn't terminate
|
||||
- FIXED an issue which would cause servers to crash on mod download via SIGPIPE on POSIX
|
||||
- FIXED an issue which would cause servers to crash when checking if a vehicle is a unicycle
|
||||
|
||||
# v3.0.0
|
||||
|
||||
- CHANGED entire plugin Lua implementation (rewrite)
|
||||
- CHANGED moved *almost all* Lua functions into MP.\*
|
||||
- CHANGED console to use a custom language (type `help`, `list`, or `status`!)
|
||||
- CHANGED all files of a Lua plugin to share a Lua state (no more state-per-file)
|
||||
- ADDED many new Lua API functions, which can be found at <https://wiki.beammp.com/en/Scripting/functions>
|
||||
- ADDED Commandline options. Run with `--help` to see all options.
|
||||
- ADDED HTTP(S) Server (OpenAPI spec coming soon!)
|
||||
- ADDED plugin directories to `package.path` and `package.cpath` before `onInit`
|
||||
- ADDED ability to add `PluginConfig.toml` to your plugin folder to change some settings
|
||||
- ADDED ability to share a lua state with other plugins via `StateId` setting in `PluginConfig.toml`
|
||||
- ADDED ability to see name-to-thread-ID association in debug mode
|
||||
- ADDED dumping tables with `print()` (try it with `print(MP)`)
|
||||
- ADDED `MP.GetOSName()`, `MP.CreateTimer()`, `MP.GetLuaMemoryUsage()` and many more (see <https://wiki.beammp.com/en/Scripting/functions>)
|
||||
- ADDED `MP.Settings` table to make usage of `MP.Set()` easier
|
||||
- ADDED `FS.*` table with common filesystem operations (do `print(FS)` to see them!)
|
||||
- FIXED i/o thread spin when stdout is /dev/null on linux
|
||||
- FIXED removed extra whitespace infront of onChatMessage message
|
||||
|
||||
# v2.3.3
|
||||
|
||||
- CHANGED servers to be private by default
|
||||
|
||||
# v2.3.2
|
||||
|
||||
- ADDED Ctrl+C causes a graceful shutdown on windows (did already on linux)
|
||||
- ADDED more meaningful shutdown messages
|
||||
- ADDED even better backend connection error reporting
|
||||
- ADDED `SendErrors` config in `ServerConfig.toml` to opt-out of error reporting
|
||||
- ADDED hard-shutdown if Ctrl+C pressed 3 times
|
||||
- FIXED issue with shells like bash being unusable after server exit
|
||||
|
||||
# v2.3.1
|
||||
|
||||
- CHANGED join/sync timeout to 20 minutes, players wont drop if loading takes >5 mins
|
||||
|
||||
# v2.3.0
|
||||
|
||||
- ADDED version check - the server will now let you know when a new release is out
|
||||
- ADDED logging of various errors, crashes and exceptions to the backend
|
||||
- ADDED chat messages are now logged to the server console as [CHAT]
|
||||
- ADDED debug message telling you when the server heartbeats to the backend
|
||||
- REMOVED various [DEBUG] messages which were confusing (such as "breaking client loop")
|
||||
- FIXED various crashes and issues with handling unexpected backend responses
|
||||
- FIXED minor bugs due to code correctness
|
||||
|
||||
# v2.2.0
|
||||
|
||||
- FIXED major security flaw
|
||||
- FIXED minor bugs
|
||||
|
||||
# v2.1.4
|
||||
|
||||
- ADDED debug heartbeat print
|
||||
- ADDED kicking every player before shutdown
|
||||
- FIXED rare bug which led to violent crash
|
||||
- FIXED minor bugs
|
||||
|
||||
# v2.1.3
|
||||
|
||||
- FIXED Lua events not cancelling properly on Linux
|
||||
|
||||
# v2.1.2
|
||||
|
||||
- CHANGED default map to gridmap v2
|
||||
- FIXED version number display
|
||||
|
||||
# v2.1.1
|
||||
# v2.1.0 (pre-v2.1.1)
|
||||
# v2.0.4 (pre-v2.1.0)
|
||||
|
||||
- REMOVED boost as a runtime dependency
|
||||
- FIXED Lua plugins on Linux
|
||||
- FIXED console history on Windows
|
||||
- CHANGED to new config format TOML
|
||||
|
||||
# v2.0.3
|
||||
|
||||
- WORKAROUND for timeout bug / ghost player bug
|
||||
- FIXED 100% CPU spin when stdin is /dev/null.
|
||||
|
||||
# v2.0.2
|
||||
|
||||
- ADDED fully new commandline
|
||||
- ADDED new backend
|
||||
- ADDED automated build system
|
||||
- ADDED lua GetPlayerIdentifiers
|
||||
- ADDED lots of debug info
|
||||
- ADDED better POSTing and GETing
|
||||
- ADDED a license
|
||||
- FIXED ghost players in player list issue
|
||||
- FIXED ghost vehicle after joining issue
|
||||
- FIXED missing vehicle after joining issue
|
||||
- FIXED a lot of desync issues
|
||||
- FIXED some memory leaks
|
||||
- FIXED various crashes
|
||||
- FIXED various data-races
|
||||
- FIXED some linux-specific crashes
|
||||
- FIXED some linux-specific issues
|
||||
- FIXED bug which caused kicking to be logged as leaving
|
||||
- FIXED various internal developer quality-of-life things
|
||||
3
LICENSE
3
LICENSE
@@ -1 +1,2 @@
|
||||
Copyright (c) 2019-present Anonymous275. BeamMP Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries, the only permission that has been granted is to use the software in its compiled form as distributed from the BeamMP.com website. Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
Copyright (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor). BeamMP-Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder(s) in order to modify or distribute any part of the source or binaries. Special permission to modify the source-code is implicitly granted only for the purpose of upstreaming those changes directly to github.com/BeamMP/BeamMP-Server via a GitHub pull-request.
|
||||
Commercial usage is prohibited, unless explicit permission has been granted prior to usage.
|
||||
|
||||
114
README.md
114
README.md
@@ -1,41 +1,115 @@
|
||||
# BeamMP-Server
|
||||
|
||||
The Server is the way we link client to each other and handle authentication, compression, and data management. It also allows lua plugins, that system is always being reviewed and improved with detailed instructions on wiki.beammp.com.
|
||||
[](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Windows+Build%22)
|
||||
[](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Linux+Build%22)
|
||||
|
||||
This is the server for the multiplayer mod **[BeamMP](https://beammp.com/)** for the game [BeamNG.drive](https://www.beamng.com/).
|
||||
The server is the point through which all clients communicate. You can write Lua mods for the server, there are detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com).
|
||||
|
||||
**For Linux, you __need__ the runtime dependencies, listed below under "[prerequisites](#prerequisites)".**
|
||||
|
||||
## Support + Contact
|
||||
|
||||
Feel free to ask any questions via the following channels:
|
||||
|
||||
- **IRC**: `#beammp` on [irc.libera.chat](https://web.libera.chat/)
|
||||
- **Discord**: [click for invite](https://discord.gg/beammp)
|
||||
- **BeamMP Forum**: [BeamMP Forum Support](https://forum.beammp.com/c/support/33)
|
||||
|
||||
## Minimum Requirements
|
||||
|
||||
These values are guesstimated and are subject to change with each release.
|
||||
|
||||
* RAM: 50+ MiB usable (not counting OS overhead)
|
||||
* CPU: >1GHz, preferably multicore
|
||||
* OS: Windows, Linux (theoretically any POSIX)
|
||||
* GPU: None
|
||||
* HDD: 10 MiB + Mods/Plugins
|
||||
* Bandwidth: 5-10 Mb/s upload
|
||||
|
||||
## Contributing
|
||||
|
||||
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" label or with nobody assigned.
|
||||
|
||||
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues). Any issues that have the "help wanted" label or don't have anyone assigned are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
|
||||
|
||||
Fork this repository, make a new branch for your feature, implement your feature or fix, and then create a pull-request here. Even incomplete features and fixes can be pull-requested.
|
||||
|
||||
If you need support with understanding the codebase, please write us in the Discord. You'll need to be proficient in modern C++.
|
||||
|
||||
## About Building from Source
|
||||
|
||||
We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v1.20`.
|
||||
|
||||
## Supported Operating Systems
|
||||
|
||||
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we only distribute windows binaries and instructions to build on Debian 10 (stable). For any other distro or OS, you just have to find the same libraries listed in the Linux Build [Prerequisites](#prerequisites) further down the page, and it should build fine. We don't currently support ARM or any big-endian architectures.
|
||||
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute Windows binaries and sometimes Linux. For any other distro or OS, you just have to find the same libraries listed in the Linux Build [Prerequisites](#prerequisites) further down the page, and it should build fine. We don't currently support any big-endian architectures.
|
||||
|
||||
Recommended compilers: MSVC, GCC.
|
||||
Recommended compilers: MSVC, GCC, CLANG.
|
||||
|
||||
## Linux / POSIX specific build instructions
|
||||
You can find precompiled binaries under [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
||||
|
||||
Currently only linux and windows are supported (generally). On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
|
||||
## Build Instructions
|
||||
|
||||
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.3.3`!__**
|
||||
|
||||
Currently only Linux and Windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
|
||||
|
||||
### Prerequisites
|
||||
|
||||
All package names are ones found in debian's (debian 10 stable) repositories, but will exist under similar names in other distros. Feel free to PR your own guide for a different distro.
|
||||
#### Windows
|
||||
|
||||
- `git`
|
||||
- `make`
|
||||
- `cmake`
|
||||
- `g++` (must support ISO C++17)
|
||||
- `liblua5.3`
|
||||
- `libz-dev`
|
||||
- `rapidjson-dev`
|
||||
- `libcurl4-openssl-dev` (or other `libcurl4-*-dev`)
|
||||
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
||||
|
||||
Dependencies for **Windows** can be installed with `vcpkg`.
|
||||
These are:
|
||||
```
|
||||
lua
|
||||
zlib
|
||||
rapidjson
|
||||
openssl
|
||||
websocketpp
|
||||
curl
|
||||
```
|
||||
|
||||
#### Linux
|
||||
|
||||
Runtime dependencies - you want to find packages for:
|
||||
- libz
|
||||
- rapidjson
|
||||
- lua5.3
|
||||
- ssl / openssl
|
||||
- websocketpp
|
||||
- curl (with ssl support)
|
||||
|
||||
Build-time dependencies are:
|
||||
```
|
||||
git
|
||||
make
|
||||
cmake
|
||||
g++
|
||||
```
|
||||
|
||||
### How to build
|
||||
|
||||
On Windows, use git-bash for these commands. On Linux, these should work in your shell.
|
||||
|
||||
1. Make sure you have all [prerequisites](#prerequisites) installed
|
||||
2. Clone the repository in a location of your choice with `git clone --recursive https://github.com/BeamMP/BeamMP-Server`
|
||||
3. `cd` into it with `cd BeamMP-Server`
|
||||
4. Run `cmake .` (with `.`)
|
||||
5. Run `make`
|
||||
6. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server`. Follow the (windows or linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/Server_Mod) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
|
||||
2. Clone the repository in a location of your choice with `git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`.
|
||||
3. Change into the BeamMP-Server directory by running `cd BeamMP-Server`.
|
||||
4. Checkout the branch of the release you want to compile, for example `git checkout tags/v3.0.2` for version 3.0.2. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
||||
5. Ensure that all submodules are initialized by running `git submodule update --init --recursive`
|
||||
6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
|
||||
7. Run `make`
|
||||
8. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (Windows or Linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/server-installation) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
|
||||
|
||||
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
|
||||
|
||||
## Support
|
||||
The BeamMP project is supported by community donations via our [Patreon](https://www.patreon.com/BeamMP). This brings perks such as Patreon-only channels on our Discord, early access to new updates, and more server keys.
|
||||
|
||||
## Copyright
|
||||
|
||||
Copyright (c) 2019-present Anonymous275. BeamMP Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries, the only permission that has been granted is to use the software in its compiled form as distributed from the BeamMP.com website. Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
Copyright (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor).
|
||||
BeamMP-Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder(s) in order to modify or distribute any part of the source or binaries. Special permission to modify the source-code is implicitly granted only for the purpose of upstreaming those changes directly to github.com/BeamMP/BeamMP-Server via a GitHub pull-request.
|
||||
Commercial usage is prohibited, unless explicit permission has been granted prior to usage.
|
||||
|
||||
7
deps/CMakeLists.txt
vendored
Normal file
7
deps/CMakeLists.txt
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
include_directories("${PROJECT_SOURCE_DIR}/deps")
|
||||
include_directories("${PROJECT_SOURCE_DIR}/deps/commandline")
|
||||
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/commandline")
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/fmt")
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/sol2")
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/doctest")
|
||||
1
deps/asio
vendored
Submodule
1
deps/asio
vendored
Submodule
Submodule deps/asio added at 4915cfd8a1
1
deps/commandline
vendored
Submodule
1
deps/commandline
vendored
Submodule
Submodule deps/commandline added at 7b9f51d6a0
1
deps/cpp-httplib
vendored
Submodule
1
deps/cpp-httplib
vendored
Submodule
Submodule deps/cpp-httplib added at d92c314466
1
deps/doctest
vendored
Submodule
1
deps/doctest
vendored
Submodule
Submodule deps/doctest added at b7c21ec5ce
1
deps/fmt
vendored
Submodule
1
deps/fmt
vendored
Submodule
Submodule deps/fmt added at c4ee726532
1
deps/json
vendored
Submodule
1
deps/json
vendored
Submodule
Submodule deps/json added at 69d744867f
1
deps/libzip
vendored
Submodule
1
deps/libzip
vendored
Submodule
Submodule deps/libzip added at 5532f9baa0
1
deps/rapidjson
vendored
Submodule
1
deps/rapidjson
vendored
Submodule
Submodule deps/rapidjson added at 00dbcf2c6e
1
deps/sentry-native
vendored
Submodule
1
deps/sentry-native
vendored
Submodule
Submodule deps/sentry-native added at 87e67ad783
1
deps/sol2
vendored
Submodule
1
deps/sol2
vendored
Submodule
Submodule deps/sol2 added at eba86625b7
1
deps/toml11
vendored
Submodule
1
deps/toml11
vendored
Submodule
Submodule deps/toml11 added at c7627ff6a1
49
include/ArgsParser.h
Normal file
49
include/ArgsParser.h
Normal file
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include <initializer_list>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
/*
|
||||
* Allows syntax:
|
||||
* --help : long flags
|
||||
* --path=/home/lion : long assignments
|
||||
*/
|
||||
class ArgsParser {
|
||||
public:
|
||||
enum Flags : int {
|
||||
NONE = 0,
|
||||
REQUIRED = 1, // argument is required
|
||||
HAS_VALUE = 2, // argument must have a value
|
||||
};
|
||||
|
||||
ArgsParser() = default;
|
||||
|
||||
void Parse(const std::vector<std::string_view>& ArgList);
|
||||
// prints errors if any errors occurred, in that case also returns false
|
||||
bool Verify();
|
||||
void RegisterArgument(std::vector<std::string>&& ArgumentNames, int Flags);
|
||||
// pass all possible names for this argument (short, long, etc)
|
||||
bool FoundArgument(const std::vector<std::string>& Names);
|
||||
std::optional<std::string> GetValueOfArgument(const std::vector<std::string>& Names);
|
||||
|
||||
private:
|
||||
void ConsumeLongAssignment(const std::string& Arg);
|
||||
void ConsumeLongFlag(const std::string& Arg);
|
||||
bool IsRegistered(const std::string& Name);
|
||||
|
||||
struct Argument {
|
||||
std::string Name;
|
||||
std::optional<std::string> Value;
|
||||
};
|
||||
|
||||
struct RegisteredArgument {
|
||||
std::vector<std::string> Names;
|
||||
int Flags;
|
||||
};
|
||||
|
||||
std::vector<RegisteredArgument> mRegisteredArguments;
|
||||
std::vector<Argument> mFoundArgs;
|
||||
};
|
||||
112
include/Client.h
Normal file
112
include/Client.h
Normal file
@@ -0,0 +1,112 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
|
||||
#include "Common.h"
|
||||
#include "Compat.h"
|
||||
#include "VehicleData.h"
|
||||
|
||||
class TServer;
|
||||
|
||||
#ifdef BEAMMP_WINDOWS
|
||||
// for socklen_t
|
||||
#include <WS2tcpip.h>
|
||||
#endif // WINDOWS
|
||||
|
||||
struct TConnection final {
|
||||
SOCKET Socket;
|
||||
struct sockaddr SockAddr;
|
||||
socklen_t SockAddrLen;
|
||||
};
|
||||
|
||||
class TClient final {
|
||||
public:
|
||||
using TSetOfVehicleData = std::vector<TVehicleData>;
|
||||
|
||||
struct TVehicleDataLockPair {
|
||||
TSetOfVehicleData* VehicleData;
|
||||
std::unique_lock<std::mutex> Lock;
|
||||
};
|
||||
|
||||
explicit TClient(TServer& Server);
|
||||
TClient(const TClient&) = delete;
|
||||
TClient& operator=(const TClient&) = delete;
|
||||
|
||||
void AddNewCar(int Ident, const std::string& Data);
|
||||
void SetCarData(int Ident, const std::string& Data);
|
||||
void SetCarPosition(int Ident, const std::string& Data);
|
||||
TVehicleDataLockPair GetAllCars();
|
||||
void SetName(const std::string& Name) { mName = Name; }
|
||||
void SetRoles(const std::string& Role) { mRole = Role; }
|
||||
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
||||
std::string GetCarData(int Ident);
|
||||
std::string GetCarPositionRaw(int Ident);
|
||||
void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
|
||||
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
|
||||
void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; }
|
||||
void SetStatus(int Status) { mStatus = Status; }
|
||||
// locks
|
||||
void DeleteCar(int Ident);
|
||||
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
||||
[[nodiscard]] sockaddr_in GetUDPAddr() const { return mUDPAddress; }
|
||||
[[nodiscard]] SOCKET GetDownSock() const { return mSocket[1]; }
|
||||
[[nodiscard]] SOCKET GetTCPSock() const { return mSocket[0]; }
|
||||
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
||||
[[nodiscard]] std::string GetName() const { return mName; }
|
||||
void SetUnicycleID(int ID) { mUnicycleID = ID; }
|
||||
void SetID(int ID) { mID = ID; }
|
||||
[[nodiscard]] int GetOpenCarID() const;
|
||||
[[nodiscard]] int GetCarCount() const;
|
||||
void ClearCars();
|
||||
[[nodiscard]] int GetStatus() const { return mStatus; }
|
||||
[[nodiscard]] int GetID() const { return mID; }
|
||||
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
||||
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
|
||||
[[nodiscard]] bool IsSynced() const { return mIsSynced; }
|
||||
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
|
||||
[[nodiscard]] bool IsGuest() const { return mIsGuest; }
|
||||
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
|
||||
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
|
||||
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
|
||||
void EnqueuePacket(const std::string& Packet);
|
||||
[[nodiscard]] std::queue<std::string>& MissedPacketQueue() { return mPacketsSync; }
|
||||
[[nodiscard]] const std::queue<std::string>& MissedPacketQueue() const { return mPacketsSync; }
|
||||
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
||||
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
||||
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
|
||||
[[nodiscard]] TServer& Server() const;
|
||||
void UpdatePingTime();
|
||||
int SecondsSinceLastPing();
|
||||
|
||||
private:
|
||||
void InsertVehicle(int ID, const std::string& Data);
|
||||
|
||||
TServer& mServer;
|
||||
bool mIsConnected = false;
|
||||
bool mIsSynced = false;
|
||||
bool mIsSyncing = false;
|
||||
mutable std::mutex mMissedPacketsMutex;
|
||||
std::queue<std::string> mPacketsSync;
|
||||
std::unordered_map<std::string, std::string> mIdentifiers;
|
||||
bool mIsGuest = false;
|
||||
mutable std::mutex mVehicleDataMutex;
|
||||
mutable std::mutex mVehiclePositionMutex;
|
||||
TSetOfVehicleData mVehicleData;
|
||||
SparseArray<std::string> mVehiclePosition;
|
||||
std::string mName = "Unknown Client";
|
||||
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
|
||||
sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is
|
||||
int mUnicycleID = -1;
|
||||
std::string mRole;
|
||||
std::string mDID;
|
||||
int mStatus = 0;
|
||||
int mID = -1;
|
||||
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
||||
};
|
||||
|
||||
std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
|
||||
@@ -1,91 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
|
||||
#pragma once
|
||||
#ifdef WIN32
|
||||
#include <WS2tcpip.h>
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#define SOCKET int
|
||||
#endif
|
||||
#include "CustomAssert.h"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct VData {
|
||||
int ID = -1;
|
||||
std::string Data;
|
||||
};
|
||||
|
||||
class Client {
|
||||
private:
|
||||
std::set<std::unique_ptr<VData>> VehicleData; //ID and Data;
|
||||
std::string Name = "Unknown Client";
|
||||
SOCKET SOCK[2] { SOCKET(-1) };
|
||||
sockaddr_in UDPADDR;
|
||||
std::string Role;
|
||||
std::string DID;
|
||||
int Status = 0;
|
||||
int ID = -1;
|
||||
|
||||
public:
|
||||
bool isConnected = false;
|
||||
bool isSynced = false;
|
||||
bool isGuest = false;
|
||||
|
||||
void AddNewCar(int ident, const std::string& Data);
|
||||
void SetCarData(int ident, const std::string& Data);
|
||||
std::set<std::unique_ptr<VData>>& GetAllCars();
|
||||
void SetName(const std::string& name) { Name = name; }
|
||||
void SetRoles(const std::string& role) { Role = role; }
|
||||
std::string GetCarData(int ident);
|
||||
void SetUDPAddr(sockaddr_in Addr) { UDPADDR = Addr; }
|
||||
void SetDownSock(SOCKET CSock) { SOCK[1] = CSock; }
|
||||
void SetTCPSock(SOCKET CSock) { SOCK[0] = CSock; }
|
||||
void SetStatus(int status) { Status = status; }
|
||||
void DeleteCar(int ident);
|
||||
sockaddr_in GetUDPAddr() { return UDPADDR; }
|
||||
std::string GetRoles() { return Role; }
|
||||
std::string GetName() { return Name; }
|
||||
SOCKET GetDownSock() { return SOCK[1]; }
|
||||
SOCKET GetTCPSock() { return SOCK[0]; }
|
||||
void SetID(int ID) { this->ID = ID; }
|
||||
int GetOpenCarID();
|
||||
int GetCarCount();
|
||||
void ClearCars();
|
||||
int GetStatus() { return Status; }
|
||||
int GetID() { return ID; }
|
||||
};
|
||||
struct ClientInterface {
|
||||
std::set<std::unique_ptr<Client>> Clients;
|
||||
void RemoveClient(Client*& c) {
|
||||
Assert(c);
|
||||
c->ClearCars();
|
||||
auto Iter = std::find_if(Clients.begin(), Clients.end(), [&](auto& ptr) {
|
||||
return c == ptr.get();
|
||||
});
|
||||
Assert(Iter != Clients.end());
|
||||
if (Iter == Clients.end()) {
|
||||
return;
|
||||
}
|
||||
Clients.erase(Iter);
|
||||
c = nullptr;
|
||||
}
|
||||
void AddClient(Client*&& c) {
|
||||
Assert(c);
|
||||
Clients.insert(std::unique_ptr<Client>(c));
|
||||
}
|
||||
int Size() {
|
||||
return int(Clients.size());
|
||||
}
|
||||
};
|
||||
|
||||
extern std::unique_ptr<ClientInterface> CI;
|
||||
327
include/Common.h
Normal file
327
include/Common.h
Normal file
@@ -0,0 +1,327 @@
|
||||
#pragma once
|
||||
|
||||
#include "TSentry.h"
|
||||
extern TSentry Sentry;
|
||||
|
||||
#include <array>
|
||||
#include <unordered_map>
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <filesystem>
|
||||
#include <fmt/format.h>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <sstream>
|
||||
#include <zlib.h>
|
||||
|
||||
#include <doctest/doctest.h>
|
||||
#include <filesystem>
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
#include "Compat.h"
|
||||
|
||||
#include "TConsole.h"
|
||||
|
||||
struct Version {
|
||||
uint8_t major;
|
||||
uint8_t minor;
|
||||
uint8_t patch;
|
||||
Version(uint8_t major, uint8_t minor, uint8_t patch);
|
||||
Version(const std::array<uint8_t, 3>& v);
|
||||
std::string AsString();
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
using SparseArray = std::unordered_map<size_t, T>;
|
||||
|
||||
// static class handling application start, shutdown, etc.
|
||||
// yes, static classes, singletons, globals are all pretty
|
||||
// bad idioms. In this case we need a central way to access
|
||||
// stuff like graceful shutdown, global settings (its in the name),
|
||||
// etc.
|
||||
class Application final {
|
||||
public:
|
||||
// types
|
||||
struct TSettings {
|
||||
std::string ServerName { "BeamMP Server" };
|
||||
std::string ServerDesc { "BeamMP Default Description" };
|
||||
std::string Resource { "Resources" };
|
||||
std::string MapName { "/levels/gridmap_v2/info.json" };
|
||||
std::string Key {};
|
||||
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
||||
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
||||
bool HTTPServerEnabled { false };
|
||||
int MaxPlayers { 8 };
|
||||
bool Private { true };
|
||||
int MaxCars { 1 };
|
||||
bool DebugModeEnabled { false };
|
||||
int Port { 30814 };
|
||||
std::string CustomIP {};
|
||||
bool LogChat { true };
|
||||
bool SendErrors { true };
|
||||
bool SendErrorsMessageEnabled { true };
|
||||
int HTTPServerPort { 8080 };
|
||||
std::string HTTPServerIP { "127.0.0.1" };
|
||||
bool HTTPServerUseSSL { false };
|
||||
bool HideUpdateMessages { false };
|
||||
[[nodiscard]] bool HasCustomIP() const { return !CustomIP.empty(); }
|
||||
};
|
||||
|
||||
using TShutdownHandler = std::function<void()>;
|
||||
|
||||
// methods
|
||||
Application() = delete;
|
||||
|
||||
// 'Handler' is called when GracefullyShutdown is called
|
||||
static void RegisterShutdownHandler(const TShutdownHandler& Handler);
|
||||
// Causes all threads to finish up and exit gracefull gracefully
|
||||
static void GracefullyShutdown();
|
||||
static TConsole& Console() { return *mConsole; }
|
||||
static std::string ServerVersionString();
|
||||
static const Version& ServerVersion() { return mVersion; }
|
||||
static std::string ClientVersionString() { return "2.0"; }
|
||||
static std::string PPS() { return mPPS; }
|
||||
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
||||
|
||||
static TSettings Settings;
|
||||
|
||||
static std::vector<std::string> GetBackendUrlsInOrder() {
|
||||
return {
|
||||
"backend.beammp.com",
|
||||
"backup1.beammp.com",
|
||||
"backup2.beammp.com"
|
||||
};
|
||||
}
|
||||
|
||||
static std::string GetBackendUrlForAuth() { return "auth.beammp.com"; }
|
||||
static std::string GetBackendUrlForSocketIO() { return "https://backend.beammp.com"; }
|
||||
static void CheckForUpdates();
|
||||
static std::array<uint8_t, 3> VersionStrToInts(const std::string& str);
|
||||
static bool IsOutdated(const Version& Current, const Version& Newest);
|
||||
static bool IsShuttingDown();
|
||||
static void SleepSafeSeconds(size_t Seconds);
|
||||
|
||||
static void InitializeConsole() {
|
||||
if (!mConsole) {
|
||||
mConsole = std::make_unique<TConsole>();
|
||||
}
|
||||
}
|
||||
|
||||
enum class Status {
|
||||
Starting,
|
||||
Good,
|
||||
Bad,
|
||||
ShuttingDown,
|
||||
Shutdown,
|
||||
};
|
||||
|
||||
using SystemStatusMap = std::unordered_map<std::string /* system name */, Status /* status */>;
|
||||
|
||||
static const SystemStatusMap& GetSubsystemStatuses() {
|
||||
std::unique_lock Lock(mSystemStatusMapMutex);
|
||||
return mSystemStatusMap;
|
||||
}
|
||||
|
||||
static void SetSubsystemStatus(const std::string& Subsystem, Status status);
|
||||
|
||||
private:
|
||||
static void SetShutdown(bool Val);
|
||||
|
||||
static inline SystemStatusMap mSystemStatusMap {};
|
||||
static inline std::mutex mSystemStatusMapMutex {};
|
||||
static inline std::string mPPS;
|
||||
static inline std::unique_ptr<TConsole> mConsole;
|
||||
static inline std::shared_mutex mShutdownMtx {};
|
||||
static inline bool mShutdown { false };
|
||||
static inline std::mutex mShutdownHandlersMutex {};
|
||||
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
|
||||
|
||||
static inline Version mVersion { 3, 1, 0 };
|
||||
};
|
||||
|
||||
std::string ThreadName(bool DebugModeOverride = false);
|
||||
void RegisterThread(const std::string& str);
|
||||
#define RegisterThreadAuto() RegisterThread(__func__)
|
||||
|
||||
#define KB 1024llu
|
||||
#define MB (KB * 1024llu)
|
||||
#define GB (MB * 1024llu)
|
||||
#define SSU_UNRAW SECRET_SENTRY_URL
|
||||
|
||||
#define _file_basename std::filesystem::path(__FILE__).filename().string()
|
||||
#define _line std::to_string(__LINE__)
|
||||
#define _in_lambda (std::string(__func__) == "operator()")
|
||||
|
||||
// for those times when you just need to ignore something :^)
|
||||
// explicity disables a [[nodiscard]] warning
|
||||
#define beammp_ignore(x) (void)x
|
||||
|
||||
// clang-format off
|
||||
#ifdef DOCTEST_CONFIG_DISABLE
|
||||
|
||||
// we would like the full function signature 'void a::foo() const'
|
||||
// on windows this is __FUNCSIG__, on GCC it's __PRETTY_FUNCTION__,
|
||||
// feel free to add more
|
||||
#if defined(WIN32)
|
||||
#define _function_name std::string(__FUNCSIG__)
|
||||
#elif defined(__unix) || defined(__unix__)
|
||||
#define _function_name std::string(__PRETTY_FUNCTION__)
|
||||
#else
|
||||
#define _function_name std::string(__func__)
|
||||
#endif
|
||||
|
||||
#ifndef NDEBUG
|
||||
#define DEBUG
|
||||
#endif
|
||||
|
||||
#if defined(DEBUG)
|
||||
|
||||
// if this is defined, we will show the full function signature infront of
|
||||
// each info/debug/warn... call instead of the 'filename:line' format.
|
||||
#if defined(BMP_FULL_FUNCTION_NAMES)
|
||||
#define _this_location (ThreadName() + _function_name + " ")
|
||||
#else
|
||||
#define _this_location (ThreadName() + _file_basename + ":" + _line + " ")
|
||||
#endif
|
||||
|
||||
#endif // defined(DEBUG)
|
||||
|
||||
#define beammp_warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
|
||||
#define beammp_info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
|
||||
#define beammp_error(x) \
|
||||
do { \
|
||||
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
|
||||
Sentry.AddErrorBreadcrumb((x), _file_basename, _line); \
|
||||
} while (false)
|
||||
#define beammp_lua_error(x) \
|
||||
do { \
|
||||
Application::Console().Write(_this_location + std::string("[LUA ERROR] ") + (x)); \
|
||||
} while (false)
|
||||
#define beammp_lua_warn(x) \
|
||||
do { \
|
||||
Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \
|
||||
} while (false)
|
||||
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
|
||||
#define beammp_debug(x) \
|
||||
do { \
|
||||
if (Application::Settings.DebugModeEnabled) { \
|
||||
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
|
||||
} \
|
||||
} while (false)
|
||||
#define beammp_event(x) \
|
||||
do { \
|
||||
if (Application::Settings.DebugModeEnabled) { \
|
||||
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
|
||||
} \
|
||||
} while (false)
|
||||
// trace() is a debug-build debug()
|
||||
#if defined(DEBUG)
|
||||
#define beammp_trace(x) \
|
||||
do { \
|
||||
if (Application::Settings.DebugModeEnabled) { \
|
||||
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
||||
} \
|
||||
} while (false)
|
||||
#else
|
||||
#define beammp_trace(x)
|
||||
#endif // defined(DEBUG)
|
||||
|
||||
#define beammp_errorf(...) beammp_error(fmt::format(__VA_ARGS__))
|
||||
#define beammp_infof(...) beammp_info(fmt::format(__VA_ARGS__))
|
||||
#define beammp_debugf(...) beammp_debug(fmt::format(__VA_ARGS__))
|
||||
#define beammp_warnf(...) beammp_warn(fmt::format(__VA_ARGS__))
|
||||
#define beammp_tracef(...) beammp_trace(fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_errorf(...) beammp_lua_error(fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_warnf(...) beammp_lua_warn(fmt::format(__VA_ARGS__))
|
||||
|
||||
#else // DOCTEST_CONFIG_DISABLE
|
||||
|
||||
#define beammp_error(x) /* x */
|
||||
#define beammp_lua_error(x) /* x */
|
||||
#define beammp_warn(x) /* x */
|
||||
#define beammp_lua_warn(x) /* x */
|
||||
#define beammp_info(x) /* x */
|
||||
#define beammp_event(x) /* x */
|
||||
#define beammp_debug(x) /* x */
|
||||
#define beammp_trace(x) /* x */
|
||||
#define luaprint(x) /* x */
|
||||
#define beammp_errorf(...) beammp_error(fmt::format(__VA_ARGS__))
|
||||
#define beammp_infof(...) beammp_info(fmt::format(__VA_ARGS__))
|
||||
#define beammp_warnf(...) beammp_warn(fmt::format(__VA_ARGS__))
|
||||
#define beammp_debugf(...) beammp_debug(fmt::format(__VA_ARGS__))
|
||||
#define beammp_tracef(...) beammp_trace(fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_errorf(...) beammp_lua_error(fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_warnf(...) beammp_lua_warn(fmt::format(__VA_ARGS__))
|
||||
|
||||
#endif // DOCTEST_CONFIG_DISABLE
|
||||
|
||||
#if defined(DEBUG)
|
||||
#define SU_RAW SSU_UNRAW
|
||||
#else
|
||||
#define SU_RAW RAWIFY(SSU_UNRAW)
|
||||
#define _this_location (ThreadName())
|
||||
#endif
|
||||
|
||||
// clang-format on
|
||||
|
||||
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||
|
||||
#define Biggest 30000
|
||||
|
||||
template <typename T>
|
||||
inline T Comp(const T& Data) {
|
||||
std::array<char, Biggest> C {};
|
||||
// obsolete
|
||||
C.fill(0);
|
||||
z_stream defstream;
|
||||
defstream.zalloc = Z_NULL;
|
||||
defstream.zfree = Z_NULL;
|
||||
defstream.opaque = Z_NULL;
|
||||
defstream.avail_in = (uInt)Data.size();
|
||||
defstream.next_in = (Bytef*)&Data[0];
|
||||
defstream.avail_out = Biggest;
|
||||
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
||||
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
||||
deflate(&defstream, Z_SYNC_FLUSH);
|
||||
deflate(&defstream, Z_FINISH);
|
||||
deflateEnd(&defstream);
|
||||
size_t TotalOut = defstream.total_out;
|
||||
T Ret;
|
||||
Ret.resize(TotalOut);
|
||||
std::fill(Ret.begin(), Ret.end(), 0);
|
||||
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
||||
return Ret;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline T DeComp(const T& Compressed) {
|
||||
std::array<char, Biggest> C {};
|
||||
// not needed
|
||||
C.fill(0);
|
||||
z_stream infstream;
|
||||
infstream.zalloc = Z_NULL;
|
||||
infstream.zfree = Z_NULL;
|
||||
infstream.opaque = Z_NULL;
|
||||
infstream.avail_in = Biggest;
|
||||
infstream.next_in = (Bytef*)(&Compressed[0]);
|
||||
infstream.avail_out = Biggest;
|
||||
infstream.next_out = (Bytef*)(C.data());
|
||||
inflateInit(&infstream);
|
||||
inflate(&infstream, Z_SYNC_FLUSH);
|
||||
inflate(&infstream, Z_FINISH);
|
||||
inflateEnd(&infstream);
|
||||
size_t TotalOut = infstream.total_out;
|
||||
T Ret;
|
||||
Ret.resize(TotalOut);
|
||||
std::fill(Ret.begin(), Ret.end(), 0);
|
||||
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
||||
return Ret;
|
||||
}
|
||||
|
||||
std::string GetPlatformAgnosticErrorString();
|
||||
#define S_DSN SU_RAW
|
||||
|
||||
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||
58
include/Compat.h
Normal file
58
include/Compat.h
Normal file
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include "Environment.h"
|
||||
|
||||
// ======================= UNIX ========================
|
||||
|
||||
#ifdef BEAMMP_LINUX
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
#include <sys/socket.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
using SOCKET = int;
|
||||
using DWORD = unsigned long;
|
||||
using PDWORD = unsigned long*;
|
||||
using LPDWORD = unsigned long*;
|
||||
char _getch();
|
||||
inline void CloseSocketProper(int TheSocket) {
|
||||
shutdown(TheSocket, SHUT_RDWR);
|
||||
close(TheSocket);
|
||||
}
|
||||
#endif // unix
|
||||
|
||||
// ======================= APPLE ========================
|
||||
|
||||
#ifdef BEAMMP_APPLE
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
#include <sys/socket.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
using SOCKET = int;
|
||||
using DWORD = unsigned long;
|
||||
using PDWORD = unsigned long*;
|
||||
using LPDWORD = unsigned long*;
|
||||
char _getch();
|
||||
inline void CloseSocketProper(int TheSocket) {
|
||||
shutdown(TheSocket, SHUT_RDWR);
|
||||
close(TheSocket);
|
||||
}
|
||||
#endif // unix
|
||||
|
||||
// ======================= WINDOWS =======================
|
||||
|
||||
#ifdef BEAMMP_WINDOWS
|
||||
#include <conio.h>
|
||||
#include <winsock2.h>
|
||||
inline void CloseSocketProper(SOCKET TheSocket) {
|
||||
shutdown(TheSocket, 2); // 2 == SD_BOTH
|
||||
closesocket(TheSocket);
|
||||
}
|
||||
#endif // WIN32
|
||||
|
||||
#ifdef INVALID_SOCKET
|
||||
static inline constexpr int BEAMMP_INVALID_SOCKET = INVALID_SOCKET;
|
||||
#else
|
||||
static inline constexpr int BEAMMP_INVALID_SOCKET = -1;
|
||||
#endif
|
||||
@@ -1,11 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/24/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
std::string Comp(std::string Data);
|
||||
std::string DeComp(std::string Compressed);
|
||||
114
include/Cryptography.h
Normal file
114
include/Cryptography.h
Normal file
@@ -0,0 +1,114 @@
|
||||
// Copyright Anonymous275 8/11/2020
|
||||
|
||||
#pragma once
|
||||
#include <array>
|
||||
#include <cstdarg>
|
||||
#include <string>
|
||||
|
||||
namespace Crypto {
|
||||
|
||||
constexpr auto time = __TIME__;
|
||||
constexpr auto seed = static_cast<int>(time[7]) + static_cast<int>(time[6]) * 10 + static_cast<int>(time[4]) * 60 + static_cast<int>(time[3]) * 600 + static_cast<int>(time[1]) * 3600 + static_cast<int>(time[0]) * 36000;
|
||||
|
||||
// 1988, Stephen Park and Keith Miller
|
||||
// "Random Number Generators: Good Ones Are Hard To Find", considered as "minimal standard"
|
||||
// Park-Miller 31 bit pseudo-random number generator, implemented with G. Carta's optimisation:
|
||||
// with 32-bit math and without division
|
||||
|
||||
template <int N>
|
||||
struct RandomGenerator {
|
||||
private:
|
||||
static constexpr unsigned a = 16807; // 7^5
|
||||
static constexpr unsigned m = 2147483647; // 2^31 - 1
|
||||
|
||||
static constexpr unsigned s = RandomGenerator<N - 1>::value;
|
||||
static constexpr unsigned lo = a * (s & 0xFFFFu); // Multiply lower 16 bits by 16807
|
||||
static constexpr unsigned hi = a * (s >> 16u); // Multiply higher 16 bits by 16807
|
||||
static constexpr unsigned lo2 = lo + ((hi & 0x7FFFu) << 16u); // Combine lower 15 bits of hi with lo's upper bits
|
||||
static constexpr unsigned hi2 = hi >> 15u; // Discard lower 15 bits of hi
|
||||
static constexpr unsigned lo3 = lo2 + hi;
|
||||
|
||||
public:
|
||||
static constexpr unsigned max = m;
|
||||
static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct RandomGenerator<0> {
|
||||
static constexpr unsigned value = seed;
|
||||
};
|
||||
|
||||
template <int N, int M>
|
||||
struct RandomInt {
|
||||
static constexpr auto value = RandomGenerator<N + 1>::value % M;
|
||||
};
|
||||
|
||||
template <int N>
|
||||
struct RandomChar {
|
||||
static const char value = static_cast<char>(1 + RandomInt<N, 0x7F - 1>::value);
|
||||
};
|
||||
|
||||
template <size_t N, int K, typename Char>
|
||||
struct MangleString {
|
||||
private:
|
||||
const char _key;
|
||||
std::array<Char, N + 1> _encrypted;
|
||||
|
||||
constexpr Char enc(Char c) const {
|
||||
return c ^ _key;
|
||||
}
|
||||
|
||||
Char dec(Char c) const {
|
||||
return c ^ _key;
|
||||
}
|
||||
|
||||
public:
|
||||
template <size_t... Is>
|
||||
constexpr MangleString(const Char* str, std::index_sequence<Is...>)
|
||||
: _key(RandomChar<K>::value)
|
||||
, _encrypted { enc(str[Is])... } { }
|
||||
|
||||
decltype(auto) decrypt() {
|
||||
for (size_t i = 0; i < N; ++i) {
|
||||
_encrypted[i] = dec(_encrypted[i]);
|
||||
}
|
||||
_encrypted[N] = '\0';
|
||||
return _encrypted.data();
|
||||
}
|
||||
};
|
||||
|
||||
static auto w_printf = [](const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vprintf(fmt, args);
|
||||
va_end(args);
|
||||
};
|
||||
|
||||
static auto w_printf_s = [](const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vprintf(fmt, args);
|
||||
va_end(args);
|
||||
};
|
||||
|
||||
static auto w_sprintf_s = [](char* buf, size_t, const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vsprintf(buf, fmt, args);
|
||||
va_end(args);
|
||||
};
|
||||
|
||||
static auto w_sprintf_s_ret = [](char* buf, size_t, const char* fmt, ...) {
|
||||
int ret;
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
ret = vsprintf(buf, fmt, args);
|
||||
va_end(args);
|
||||
return ret;
|
||||
};
|
||||
|
||||
#define XOR_C(s) [] { constexpr Crypto::MangleString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char > expr( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ); return expr; }().decrypt()
|
||||
#define XOR_W(s) [] { constexpr Crypto::MangleString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t > expr( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ); return expr; }().decrypt()
|
||||
#define RAWIFY(s) XOR_C(s)
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/18/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
std::string HttpRequest(const std::string& IP, int port);
|
||||
std::string PostHTTP(const std::string& IP, const std::string& Fields, bool json);
|
||||
@@ -15,7 +15,7 @@
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
#include "Logger.h"
|
||||
#include "Common.h"
|
||||
|
||||
static const char* const ANSI_RESET = "\u001b[0m";
|
||||
|
||||
@@ -40,7 +40,8 @@ static const char* const ANSI_WHITE_BOLD = "\u001b[37;1m";
|
||||
static const char* const ANSI_BOLD = "\u001b[1m";
|
||||
static const char* const ANSI_UNDERLINE = "\u001b[4m";
|
||||
|
||||
#if DEBUG
|
||||
#ifdef DEBUG
|
||||
#include <iostream>
|
||||
inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const char* function, [[maybe_unused]] unsigned line,
|
||||
[[maybe_unused]] const char* condition_string, [[maybe_unused]] bool result) {
|
||||
if (!result) {
|
||||
@@ -54,14 +55,19 @@ inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const ch
|
||||
}
|
||||
}
|
||||
|
||||
#define Assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
||||
#define AssertNotReachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
||||
#define beammp_assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
||||
#define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
||||
#else
|
||||
// In release build, these macros turn into NOPs. The compiler will optimize these out.
|
||||
#define Assert(x) \
|
||||
do { \
|
||||
#define beammp_assert(cond) \
|
||||
do { \
|
||||
bool result = (cond); \
|
||||
if (!result) { \
|
||||
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
|
||||
} \
|
||||
} while (false)
|
||||
#define AssertNotReachable() \
|
||||
do { \
|
||||
#define beammp_assert_not_reachable() \
|
||||
do { \
|
||||
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
|
||||
} while (false)
|
||||
#endif // DEBUG
|
||||
|
||||
18
include/Defer.h
Normal file
18
include/Defer.h
Normal file
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
|
||||
template <typename FnT>
|
||||
class Defer final {
|
||||
public:
|
||||
Defer(FnT fn)
|
||||
: mFunction([&fn] { (void)fn(); }) { }
|
||||
~Defer() {
|
||||
if (mFunction) {
|
||||
mFunction();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::function<void()> mFunction;
|
||||
};
|
||||
17
include/Environment.h
Normal file
17
include/Environment.h
Normal file
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
// one of BEAMMP_{WINDOWS,LINUX,APPLE} will be set at the end of this
|
||||
|
||||
// clang-format off
|
||||
#if !defined(BEAMMP_WINDOWS) && !defined(BEAMMP_UNIX) && !defined(BEAMMP_APPLE)
|
||||
#if defined(_WIN32) || defined(__CYGWIN__)
|
||||
#define BEAMMP_WINDOWS
|
||||
#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__unix__) || defined(__unix) || defined(unix)
|
||||
#define BEAMMP_LINUX
|
||||
#elif defined(__APPLE__) || defined(__MACH__)
|
||||
#define BEAMMP_APPLE
|
||||
#else
|
||||
#error "This platform is not known. Please define one of the above for your OS."
|
||||
#endif
|
||||
#endif
|
||||
// clang-format on
|
||||
40
include/Http.h
Normal file
40
include/Http.h
Normal file
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
#include <Common.h>
|
||||
#include <IThreaded.h>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#if defined(BEAMMP_LINUX)
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
|
||||
#endif
|
||||
#include <httplib.h>
|
||||
#if defined(BEAMMP_LINUX)
|
||||
#pragma GCC diagnostic pop
|
||||
#endif
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace Http {
|
||||
std::string GET(const std::string& host, int port, const std::string& target, unsigned int* status = nullptr);
|
||||
std::string POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status = nullptr, const httplib::Headers& headers = {});
|
||||
namespace Status {
|
||||
std::string ToString(int code);
|
||||
}
|
||||
const std::string ErrorString = "-1";
|
||||
|
||||
namespace Server {
|
||||
class THttpServerInstance {
|
||||
public:
|
||||
THttpServerInstance();
|
||||
|
||||
protected:
|
||||
void operator()();
|
||||
|
||||
private:
|
||||
std::thread mThread;
|
||||
};
|
||||
}
|
||||
}
|
||||
24
include/IThreaded.h
Normal file
24
include/IThreaded.h
Normal file
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <thread>
|
||||
|
||||
// pure virtual class to be inherited from by classes which intend to be threaded
|
||||
class IThreaded {
|
||||
public:
|
||||
IThreaded()
|
||||
// invokes operator() on this object
|
||||
: mThread() { }
|
||||
~IThreaded() noexcept {
|
||||
if (mThread.joinable()) {
|
||||
mThread.join();
|
||||
}
|
||||
}
|
||||
|
||||
virtual void Start() final {
|
||||
mThread = std::thread([this] { (*this)(); });
|
||||
}
|
||||
virtual void operator()() = 0;
|
||||
|
||||
protected:
|
||||
std::thread mThread;
|
||||
};
|
||||
@@ -1,12 +1,9 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 11/27/2020
|
||||
///
|
||||
//
|
||||
// Created by anon on 4/21/21.
|
||||
//
|
||||
|
||||
#pragma once
|
||||
#include "rapidjson/document.h"
|
||||
#include "rapidjson/stringbuffer.h"
|
||||
#include "rapidjson/prettywriter.h"
|
||||
#include "rapidjson/document.h"
|
||||
#include "rapidjson/writer.h"
|
||||
namespace json = rapidjson;
|
||||
@@ -1,21 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 4/2/2020.
|
||||
///
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
void InitLog();
|
||||
#define DebugPrintTID() DebugPrintTIDInternal(__func__, false)
|
||||
void DebugPrintTIDInternal(const std::string& func, bool overwrite = true); // prints the current thread id in debug mode, to make tracing of crashes and asserts easier
|
||||
void ConsoleOut(const std::string& msg);
|
||||
void except(const std::string& toPrint);
|
||||
void debug(const std::string& toPrint);
|
||||
void error(const std::string& toPrint);
|
||||
void info(const std::string& toPrint);
|
||||
void warn(const std::string& toPrint);
|
||||
@@ -1,81 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 5/20/2020
|
||||
///
|
||||
|
||||
#pragma once
|
||||
#include <any>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <lua.hpp>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
struct LuaArg {
|
||||
std::vector<std::any> args;
|
||||
void PushArgs(lua_State* State) {
|
||||
for (std::any arg : args) {
|
||||
if (!arg.has_value())
|
||||
return;
|
||||
std::string Type = arg.type().name();
|
||||
if (Type.find("bool") != std::string::npos) {
|
||||
lua_pushboolean(State, std::any_cast<bool>(arg));
|
||||
}
|
||||
if (Type.find("basic_string") != std::string::npos || Type.find("char") != std::string::npos) {
|
||||
lua_pushstring(State, std::any_cast<std::string>(arg).c_str());
|
||||
}
|
||||
if (Type.find("int") != std::string::npos) {
|
||||
lua_pushinteger(State, std::any_cast<int>(arg));
|
||||
}
|
||||
if (Type.find("float") != std::string::npos) {
|
||||
lua_pushnumber(State, std::any_cast<float>(arg));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class Lua {
|
||||
private:
|
||||
std::set<std::pair<std::string, std::string>> _RegisteredEvents;
|
||||
lua_State* luaState { nullptr };
|
||||
fs::file_time_type _LastWrote;
|
||||
std::string _PluginName {};
|
||||
std::string _FileName {};
|
||||
bool _StopThread = false;
|
||||
bool _Console = false;
|
||||
|
||||
public:
|
||||
void Init();
|
||||
void RegisterEvent(const std::string& Event, const std::string& FunctionName);
|
||||
std::string GetRegistered(const std::string& Event) const;
|
||||
void UnRegisterEvent(const std::string& Event);
|
||||
void SetLastWrite(fs::file_time_type time);
|
||||
bool IsRegistered(const std::string& Event);
|
||||
void SetPluginName(const std::string& Name);
|
||||
void Execute(const std::string& Command);
|
||||
void SetFileName(const std::string& Name);
|
||||
fs::file_time_type GetLastWrite();
|
||||
std::string GetPluginName() const;
|
||||
std::string GetFileName() const;
|
||||
lua_State* GetState();
|
||||
const lua_State* GetState() const;
|
||||
std::string GetOrigin();
|
||||
std::mutex Lock;
|
||||
void Reload();
|
||||
Lua(const std::string& PluginName, const std::string& FileName, fs::file_time_type LastWrote, bool Console = false);
|
||||
Lua(bool Console = false);
|
||||
~Lua();
|
||||
void SetStopThread(bool StopThread) { _StopThread = StopThread; }
|
||||
bool GetStopThread() const { return _StopThread; }
|
||||
};
|
||||
std::any CallFunction(Lua* lua, const std::string& FuncName, std::shared_ptr<LuaArg> args);
|
||||
std::any TriggerLuaEvent(const std::string& Event, bool local, Lua* Caller, std::shared_ptr<LuaArg> arg, bool Wait);
|
||||
extern std::set<std::unique_ptr<Lua>> PluginEngine;
|
||||
48
include/LuaAPI.h
Normal file
48
include/LuaAPI.h
Normal file
@@ -0,0 +1,48 @@
|
||||
#pragma once
|
||||
|
||||
#include "TLuaEngine.h"
|
||||
#include <tuple>
|
||||
|
||||
namespace LuaAPI {
|
||||
int PanicHandler(lua_State* State);
|
||||
std::string LuaToString(const sol::object Value, size_t Indent = 1, bool QuoteStrings = false);
|
||||
void Print(sol::variadic_args);
|
||||
namespace MP {
|
||||
extern TLuaEngine* Engine;
|
||||
|
||||
std::string GetOSName();
|
||||
std::tuple<int, int, int> GetServerVersion();
|
||||
std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
|
||||
std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
|
||||
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); }
|
||||
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
||||
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
|
||||
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
|
||||
void Set(int ConfigID, sol::object NewValue);
|
||||
bool IsPlayerGuest(int ID);
|
||||
bool IsPlayerConnected(int ID);
|
||||
void Sleep(size_t Ms);
|
||||
void PrintRaw(sol::variadic_args);
|
||||
std::string JsonEncode(const sol::table& object);
|
||||
std::string JsonDiff(const std::string& a, const std::string& b);
|
||||
std::string JsonDiffApply(const std::string& data, const std::string& patch);
|
||||
std::string JsonPrettify(const std::string& json);
|
||||
std::string JsonMinify(const std::string& json);
|
||||
std::string JsonFlatten(const std::string& json);
|
||||
std::string JsonUnflatten(const std::string& json);
|
||||
}
|
||||
|
||||
namespace FS {
|
||||
std::pair<bool, std::string> CreateDirectory(const std::string& Path);
|
||||
std::pair<bool, std::string> Remove(const std::string& Path);
|
||||
std::pair<bool, std::string> Rename(const std::string& Path, const std::string& NewPath);
|
||||
std::pair<bool, std::string> Copy(const std::string& Path, const std::string& NewPath);
|
||||
std::string GetFilename(const std::string& Path);
|
||||
std::string GetExtension(const std::string& Path);
|
||||
std::string GetParentFolder(const std::string& Path);
|
||||
bool Exists(const std::string& Path);
|
||||
bool IsDirectory(const std::string& Path);
|
||||
bool IsFile(const std::string& Path);
|
||||
std::string ConcatPaths(sol::variadic_args Args);
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/31/2020
|
||||
///
|
||||
#pragma once
|
||||
#include "Client.hpp"
|
||||
#include <string>
|
||||
void TCPServerMain();
|
||||
void UpdatePlayers();
|
||||
void OnConnect(Client* c);
|
||||
void TCPClient(Client* c);
|
||||
std::string TCPRcv(Client* c);
|
||||
void SyncResources(Client* c);
|
||||
[[noreturn]] void UDPServerMain();
|
||||
void OnDisconnect(Client* c, bool kicked);
|
||||
void UDPSend(Client* c, std::string Data);
|
||||
void SendLarge(Client* c, std::string Data);
|
||||
bool TCPSend(Client* c, const std::string& Data);
|
||||
void GParser(Client* c, const std::string& Packet);
|
||||
std::string StaticReason(bool Set, const std::string& R);
|
||||
void Respond(Client* c, const std::string& MSG, bool Rel);
|
||||
void SendToAll(Client* c, const std::string& Data, bool Self, bool Rel);
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
#include <shared_mutex>
|
||||
#include <mutex>
|
||||
|
||||
// Use ReadLock(m) and WriteLock(m) to lock it.
|
||||
using RWMutex = std::shared_mutex;
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#pragma once
|
||||
#ifdef __linux
|
||||
#define EXCEPTION_POINTERS void
|
||||
#else
|
||||
#include <WS2tcpip.h>
|
||||
#endif
|
||||
#include <string>
|
||||
int Handle(EXCEPTION_POINTERS* ep, char* Origin);
|
||||
@@ -1,28 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
extern std::string ServerName;
|
||||
extern std::string ServerDesc;
|
||||
extern std::string StatReport;
|
||||
extern std::string FileSizes;
|
||||
extern std::string Resource;
|
||||
extern std::string FileList;
|
||||
extern std::string CustomIP;
|
||||
extern std::string MapName;
|
||||
extern uint64_t MaxModSize;
|
||||
extern std::string Key;
|
||||
std::string GetSVer();
|
||||
std::string GetCVer();
|
||||
extern int MaxPlayers;
|
||||
extern int ModsLoaded;
|
||||
extern bool Private;
|
||||
extern int MaxCars;
|
||||
extern bool Debug;
|
||||
extern int Port;
|
||||
extern int PPS;
|
||||
3
include/SignalHandling.h
Normal file
3
include/SignalHandling.h
Normal file
@@ -0,0 +1,3 @@
|
||||
#pragma once
|
||||
|
||||
void SetupSignalHandlers();
|
||||
@@ -1,16 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#pragma once
|
||||
void InitServer(int argc, char* argv[]);
|
||||
void ConsoleInit();
|
||||
void InitConfig();
|
||||
void InitLua();
|
||||
void InitRes();
|
||||
void HBInit();
|
||||
void StatInit();
|
||||
void NetMain();
|
||||
33
include/TConfig.h
Normal file
33
include/TConfig.h
Normal file
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <filesystem>
|
||||
|
||||
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
|
||||
#include <toml11/toml.hpp> // header-only version of TOML++
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
class TConfig {
|
||||
public:
|
||||
explicit TConfig(const std::string& ConfigFileName);
|
||||
|
||||
[[nodiscard]] bool Failed() const { return mFailed; }
|
||||
|
||||
void FlushToFile();
|
||||
|
||||
private:
|
||||
void CreateConfigFile();
|
||||
void ParseFromFile(std::string_view name);
|
||||
void PrintDebug();
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue);
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue);
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue);
|
||||
|
||||
void ParseOldFormat();
|
||||
bool IsDefault();
|
||||
bool mFailed { false };
|
||||
std::string mConfigFileName;
|
||||
};
|
||||
68
include/TConsole.h
Normal file
68
include/TConsole.h
Normal file
@@ -0,0 +1,68 @@
|
||||
#pragma once
|
||||
|
||||
#include "Cryptography.h"
|
||||
#include "commandline.h"
|
||||
#include <atomic>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
class TLuaEngine;
|
||||
|
||||
class TConsole {
|
||||
public:
|
||||
TConsole();
|
||||
|
||||
void Write(const std::string& str);
|
||||
void WriteRaw(const std::string& str);
|
||||
void InitializeLuaConsole(TLuaEngine& Engine);
|
||||
void BackupOldLog();
|
||||
void StartLoggingToFile();
|
||||
Commandline& Internal() { return mCommandline; }
|
||||
|
||||
private:
|
||||
void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false);
|
||||
void ChangeToLuaConsole(const std::string& LuaStateId);
|
||||
void ChangeToRegularConsole();
|
||||
void HandleLuaInternalCommand(const std::string& cmd);
|
||||
|
||||
void Command_Lua(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_Help(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_Kick(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_List(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_Status(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_Settings(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_Clear(const std::string&, const std::vector<std::string>& args);
|
||||
|
||||
void Command_Say(const std::string& FullCommand);
|
||||
bool EnsureArgsCount(const std::vector<std::string>& args, size_t n);
|
||||
bool EnsureArgsCount(const std::vector<std::string>& args, size_t min, size_t max);
|
||||
|
||||
static std::tuple<std::string, std::vector<std::string>> ParseCommand(const std::string& cmd);
|
||||
static std::string ConcatArgs(const std::vector<std::string>& args, char space = ' ');
|
||||
|
||||
std::unordered_map<std::string, std::function<void(const std::string&, const std::vector<std::string>&)>> mCommandMap = {
|
||||
{ "lua", [this](const auto& a, const auto& b) { Command_Lua(a, b); } },
|
||||
{ "help", [this](const auto& a, const auto& b) { Command_Help(a, b); } },
|
||||
{ "kick", [this](const auto& a, const auto& b) { Command_Kick(a, b); } },
|
||||
{ "list", [this](const auto& a, const auto& b) { Command_List(a, b); } },
|
||||
{ "status", [this](const auto& a, const auto& b) { Command_Status(a, b); } },
|
||||
{ "settings", [this](const auto& a, const auto& b) { Command_Settings(a, b); } },
|
||||
{ "clear", [this](const auto& a, const auto& b) { Command_Clear(a, b); } },
|
||||
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
|
||||
};
|
||||
|
||||
Commandline mCommandline;
|
||||
std::vector<std::string> mCachedLuaHistory;
|
||||
std::vector<std::string> mCachedRegularHistory;
|
||||
TLuaEngine* mLuaEngine { nullptr };
|
||||
bool mIsLuaConsole { false };
|
||||
bool mFirstTime { true };
|
||||
std::string mStateId;
|
||||
const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE";
|
||||
std::ofstream mLogFileStream;
|
||||
std::mutex mLogFileStreamMtx;
|
||||
};
|
||||
20
include/THeartbeatThread.h
Normal file
20
include/THeartbeatThread.h
Normal file
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include "IThreaded.h"
|
||||
#include "TResourceManager.h"
|
||||
#include "TServer.h"
|
||||
|
||||
class THeartbeatThread : public IThreaded {
|
||||
public:
|
||||
THeartbeatThread(TResourceManager& ResourceManager, TServer& Server);
|
||||
//~THeartbeatThread();
|
||||
void operator()() override;
|
||||
|
||||
private:
|
||||
std::string GenerateCall();
|
||||
std::string GetPlayers();
|
||||
|
||||
TResourceManager& mResourceManager;
|
||||
TServer& mServer;
|
||||
};
|
||||
272
include/TLuaEngine.h
Normal file
272
include/TLuaEngine.h
Normal file
@@ -0,0 +1,272 @@
|
||||
#pragma once
|
||||
|
||||
#include "TNetwork.h"
|
||||
#include "TServer.h"
|
||||
#include <any>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <initializer_list>
|
||||
#include <list>
|
||||
#include <lua.hpp>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <random>
|
||||
#include <set>
|
||||
#include <toml11/toml.hpp>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#define SOL_ALL_SAFETIES_ON 1
|
||||
#include <sol/sol.hpp>
|
||||
|
||||
using TLuaStateId = std::string;
|
||||
namespace fs = std::filesystem;
|
||||
/**
|
||||
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args
|
||||
*/
|
||||
using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool>;
|
||||
static constexpr size_t TLuaArgTypes_String = 0;
|
||||
static constexpr size_t TLuaArgTypes_Int = 1;
|
||||
static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
|
||||
static constexpr size_t TLuaArgTypes_Bool = 3;
|
||||
|
||||
class TLuaPlugin;
|
||||
|
||||
struct TLuaResult {
|
||||
bool Ready;
|
||||
bool Error;
|
||||
std::string ErrorMessage;
|
||||
sol::object Result { sol::lua_nil };
|
||||
TLuaStateId StateId;
|
||||
std::string Function;
|
||||
// TODO: Add condition_variable
|
||||
void WaitUntilReady();
|
||||
};
|
||||
|
||||
struct TLuaPluginConfig {
|
||||
static inline const std::string FileName = "PluginConfig.toml";
|
||||
TLuaStateId StateId;
|
||||
// TODO: Add execute list
|
||||
// TODO: Build a better toml serializer, or some way to do this in an easier way
|
||||
};
|
||||
|
||||
struct TLuaChunk {
|
||||
TLuaChunk(std::shared_ptr<std::string> Content,
|
||||
std::string FileName,
|
||||
std::string PluginPath);
|
||||
std::shared_ptr<std::string> Content;
|
||||
std::string FileName;
|
||||
std::string PluginPath;
|
||||
};
|
||||
|
||||
class TLuaEngine : public std::enable_shared_from_this<TLuaEngine>, IThreaded {
|
||||
public:
|
||||
enum CallStrategy : int {
|
||||
BestEffort,
|
||||
Precise,
|
||||
};
|
||||
|
||||
struct QueuedFunction {
|
||||
std::string FunctionName;
|
||||
std::shared_ptr<TLuaResult> Result;
|
||||
std::vector<TLuaArgTypes> Args;
|
||||
std::string EventName; // optional, may be empty
|
||||
};
|
||||
|
||||
TLuaEngine();
|
||||
~TLuaEngine() noexcept {
|
||||
beammp_debug("Lua Engine terminated");
|
||||
}
|
||||
|
||||
void operator()() override;
|
||||
|
||||
TNetwork& Network() { return *mNetwork; }
|
||||
TServer& Server() { return *mServer; }
|
||||
|
||||
void SetNetwork(TNetwork* Network) { mNetwork = Network; }
|
||||
void SetServer(TServer* Server) { mServer = Server; }
|
||||
|
||||
size_t GetResultsToCheckSize() {
|
||||
std::unique_lock Lock(mResultsToCheckMutex);
|
||||
return mResultsToCheck.size();
|
||||
}
|
||||
|
||||
size_t GetLuaStateCount() {
|
||||
std::unique_lock Lock(mLuaStatesMutex);
|
||||
return mLuaStates.size();
|
||||
}
|
||||
std::vector<std::string> GetLuaStateNames() {
|
||||
std::vector<std::string> names{};
|
||||
for(auto const& [stateId, _ ] : mLuaStates) {
|
||||
names.push_back(stateId);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
size_t GetTimedEventsCount() {
|
||||
std::unique_lock Lock(mTimedEventsMutex);
|
||||
return mTimedEvents.size();
|
||||
}
|
||||
size_t GetRegisteredEventHandlerCount() {
|
||||
std::unique_lock Lock(mLuaEventsMutex);
|
||||
size_t LuaEventsCount = 0;
|
||||
for (const auto& State : mLuaEvents) {
|
||||
for (const auto& Events : State.second) {
|
||||
LuaEventsCount += Events.second.size();
|
||||
}
|
||||
}
|
||||
return LuaEventsCount - GetLuaStateCount();
|
||||
}
|
||||
|
||||
static void WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results,
|
||||
const std::optional<std::chrono::high_resolution_clock::duration>& Max = std::nullopt);
|
||||
void ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results);
|
||||
bool HasState(TLuaStateId StateId);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
||||
void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false);
|
||||
void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName);
|
||||
/**
|
||||
*
|
||||
* @tparam ArgsT Template Arguments for the event (Metadata) todo: figure out what this means
|
||||
* @param EventName Name of the event
|
||||
* @param IgnoreId
|
||||
* @param Args
|
||||
* @return
|
||||
*/
|
||||
template <typename... ArgsT>
|
||||
[[nodiscard]] std::vector<std::shared_ptr<TLuaResult>> TriggerEvent(const std::string& EventName, TLuaStateId IgnoreId, ArgsT&&... Args) {
|
||||
std::unique_lock Lock(mLuaEventsMutex);
|
||||
beammp_event(EventName);
|
||||
if (mLuaEvents.find(EventName) == mLuaEvents.end()) { // if no event handler is defined for 'EventName', return immediately
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||
|
||||
for (const auto& Event : mLuaEvents.at(EventName)) {
|
||||
for (const auto& Function : Event.second) {
|
||||
if (Event.first != IgnoreId) {
|
||||
Results.push_back(EnqueueFunctionCall(Event.first, Function, Arguments));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Results; //
|
||||
}
|
||||
template <typename... ArgsT>
|
||||
[[nodiscard]] std::vector<std::shared_ptr<TLuaResult>> TriggerLocalEvent(const TLuaStateId& StateId, const std::string& EventName, ArgsT&&... Args) {
|
||||
std::unique_lock Lock(mLuaEventsMutex);
|
||||
beammp_event(EventName + " in '" + StateId + "'");
|
||||
if (mLuaEvents.find(EventName) == mLuaEvents.end()) { // if no event handler is defined for 'EventName', return immediately
|
||||
return {};
|
||||
}
|
||||
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||
const auto Handlers = GetEventHandlersForState(EventName, StateId);
|
||||
for (const auto& Handler : Handlers) {
|
||||
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments));
|
||||
}
|
||||
return Results;
|
||||
}
|
||||
std::set<std::string> GetEventHandlersForState(const std::string& EventName, TLuaStateId StateId);
|
||||
void CreateEventTimer(const std::string& EventName, TLuaStateId StateId, size_t IntervalMS, CallStrategy Strategy);
|
||||
void CancelEventTimers(const std::string& EventName, TLuaStateId StateId);
|
||||
sol::state_view GetStateForPlugin(const fs::path& PluginPath);
|
||||
TLuaStateId GetStateIDForPlugin(const fs::path& PluginPath);
|
||||
void AddResultToCheck(const std::shared_ptr<TLuaResult>& Result);
|
||||
|
||||
static constexpr const char* BeamMPFnNotFoundError = "BEAMMP_FN_NOT_FOUND";
|
||||
|
||||
std::vector<std::string> GetStateGlobalKeysForState(TLuaStateId StateId);
|
||||
std::vector<std::string> GetStateTableKeysForState(TLuaStateId StateId, std::vector<std::string> keys);
|
||||
|
||||
// Debugging functions (slow)
|
||||
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId);
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueueForState(TLuaStateId StateId);
|
||||
std::vector<QueuedFunction> Debug_GetStateFunctionQueueForState(TLuaStateId StateId);
|
||||
std::vector<TLuaResult> Debug_GetResultsToCheckForState(TLuaStateId StateId);
|
||||
|
||||
private:
|
||||
void CollectAndInitPlugins();
|
||||
void InitializePlugin(const fs::path& Folder, const TLuaPluginConfig& Config);
|
||||
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
|
||||
size_t CalculateMemoryUsage();
|
||||
|
||||
class StateThreadData : IThreaded {
|
||||
public:
|
||||
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
||||
StateThreadData(const StateThreadData&) = delete;
|
||||
~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
|
||||
void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
|
||||
void AddPath(const fs::path& Path); // to be added to path and cpath
|
||||
void operator()() override;
|
||||
sol::state_view State() { return sol::state_view(mState); }
|
||||
|
||||
std::vector<std::string> GetStateGlobalKeys();
|
||||
std::vector<std::string> GetStateTableKeys(const std::vector<std::string>& keys);
|
||||
|
||||
// Debug functions, slow
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
|
||||
std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue();
|
||||
|
||||
private:
|
||||
sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs);
|
||||
sol::table Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs);
|
||||
sol::table Lua_GetPlayerIdentifiers(int ID);
|
||||
sol::table Lua_GetPlayers();
|
||||
std::string Lua_GetPlayerName(int ID);
|
||||
sol::table Lua_GetPlayerVehicles(int ID);
|
||||
std::pair<sol::table, std::string> Lua_GetPositionRaw(int PID, int VID);
|
||||
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
|
||||
sol::table Lua_JsonDecode(const std::string& str);
|
||||
int Lua_GetPlayerIDByName(const std::string& Name);
|
||||
sol::table Lua_FS_ListFiles(const std::string& Path);
|
||||
sol::table Lua_FS_ListDirectories(const std::string& Path);
|
||||
|
||||
std::string mName;
|
||||
TLuaStateId mStateId;
|
||||
lua_State* mState;
|
||||
std::thread mThread;
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
|
||||
std::recursive_mutex mStateExecuteQueueMutex;
|
||||
std::vector<QueuedFunction> mStateFunctionQueue;
|
||||
std::mutex mStateFunctionQueueMutex;
|
||||
std::condition_variable mStateFunctionQueueCond;
|
||||
TLuaEngine* mEngine;
|
||||
sol::state_view mStateView { mState };
|
||||
std::queue<fs::path> mPaths;
|
||||
std::recursive_mutex mPathsMutex;
|
||||
std::mt19937 mMersenneTwister;
|
||||
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
||||
};
|
||||
|
||||
struct TimedEvent {
|
||||
std::chrono::high_resolution_clock::duration Duration {};
|
||||
std::chrono::high_resolution_clock::time_point LastCompletion {};
|
||||
std::string EventName;
|
||||
TLuaStateId StateId;
|
||||
CallStrategy Strategy;
|
||||
bool Expired();
|
||||
void Reset();
|
||||
};
|
||||
|
||||
TNetwork* mNetwork;
|
||||
TServer* mServer;
|
||||
const fs::path mResourceServerPath;
|
||||
std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins;
|
||||
std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates;
|
||||
std::recursive_mutex mLuaStatesMutex;
|
||||
std::unordered_map<std::string /* event name */, std::unordered_map<TLuaStateId, std::set<std::string>>> mLuaEvents;
|
||||
std::recursive_mutex mLuaEventsMutex;
|
||||
std::vector<TimedEvent> mTimedEvents;
|
||||
std::recursive_mutex mTimedEventsMutex;
|
||||
std::list<std::shared_ptr<TLuaResult>> mResultsToCheck;
|
||||
std::mutex mResultsToCheckMutex;
|
||||
std::condition_variable mResultsToCheckCond;
|
||||
};
|
||||
|
||||
// std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
|
||||
19
include/TLuaPlugin.h
Normal file
19
include/TLuaPlugin.h
Normal file
@@ -0,0 +1,19 @@
|
||||
#include "TLuaEngine.h"
|
||||
|
||||
class TLuaPlugin {
|
||||
public:
|
||||
TLuaPlugin(TLuaEngine& Engine, const TLuaPluginConfig& Config, const fs::path& MainFolder);
|
||||
TLuaPlugin(const TLuaPlugin&) = delete;
|
||||
TLuaPlugin& operator=(const TLuaPlugin&) = delete;
|
||||
~TLuaPlugin() noexcept = default;
|
||||
|
||||
const TLuaPluginConfig& GetConfig() const { return mConfig; }
|
||||
fs::path GetFolder() const { return mFolder; }
|
||||
|
||||
private:
|
||||
TLuaPluginConfig mConfig;
|
||||
TLuaEngine& mEngine;
|
||||
fs::path mFolder;
|
||||
std::string mPluginName;
|
||||
std::unordered_map<std::string, std::shared_ptr<std::string>> mFileContents;
|
||||
};
|
||||
51
include/TNetwork.h
Normal file
51
include/TNetwork.h
Normal file
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
|
||||
#include "Compat.h"
|
||||
#include "TResourceManager.h"
|
||||
#include "TServer.h"
|
||||
|
||||
struct TConnection;
|
||||
|
||||
class TNetwork {
|
||||
public:
|
||||
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
||||
|
||||
[[nodiscard]] bool TCPSend(TClient& c, const std::string& Data, bool IsSync = false);
|
||||
[[nodiscard]] bool SendLarge(TClient& c, std::string Data, bool isSync = false);
|
||||
[[nodiscard]] bool Respond(TClient& c, const std::string& MSG, bool Rel, bool isSync = false);
|
||||
std::shared_ptr<TClient> CreateClient(SOCKET TCPSock);
|
||||
std::string TCPRcv(TClient& c);
|
||||
void ClientKick(TClient& c, const std::string& R);
|
||||
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
||||
void Identify(const TConnection& client);
|
||||
void Authentication(const TConnection& ClientConnection);
|
||||
[[nodiscard]] bool CheckBytes(TClient& c, int32_t BytesRcv);
|
||||
void SyncResources(TClient& c);
|
||||
[[nodiscard]] bool UDPSend(TClient& Client, std::string Data) const;
|
||||
void SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel);
|
||||
void UpdatePlayer(TClient& Client);
|
||||
|
||||
private:
|
||||
void UDPServerMain();
|
||||
void TCPServerMain();
|
||||
|
||||
TServer& mServer;
|
||||
TPPSMonitor& mPPSMonitor;
|
||||
SOCKET mUDPSock {};
|
||||
TResourceManager& mResourceManager;
|
||||
std::thread mUDPThread;
|
||||
std::thread mTCPThread;
|
||||
|
||||
std::string UDPRcvFromClient(sockaddr_in& client) const;
|
||||
void HandleDownload(SOCKET TCPSock);
|
||||
void OnConnect(const std::weak_ptr<TClient>& c);
|
||||
void TCPClient(const std::weak_ptr<TClient>& c);
|
||||
void Looper(const std::weak_ptr<TClient>& c);
|
||||
int OpenID();
|
||||
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked);
|
||||
void Parse(TClient& c, const std::string& Packet);
|
||||
void SendFile(TClient& c, const std::string& Name);
|
||||
static bool TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size);
|
||||
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
||||
static uint8_t* SendSplit(TClient& c, SOCKET Socket, uint8_t* DataPtr, size_t Size);
|
||||
};
|
||||
26
include/TPPSMonitor.h
Normal file
26
include/TPPSMonitor.h
Normal file
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include "TServer.h"
|
||||
#include <optional>
|
||||
|
||||
class TNetwork;
|
||||
|
||||
class TPPSMonitor : public IThreaded {
|
||||
public:
|
||||
explicit TPPSMonitor(TServer& Server);
|
||||
|
||||
void operator()() override;
|
||||
|
||||
void SetInternalPPS(int NewPPS) { mInternalPPS = NewPPS; }
|
||||
void IncrementInternalPPS() { ++mInternalPPS; }
|
||||
[[nodiscard]] int InternalPPS() const { return mInternalPPS; }
|
||||
void SetNetwork(TNetwork& Server) { mNetwork = std::ref(Server); }
|
||||
|
||||
private:
|
||||
TNetwork& Network() { return mNetwork->get(); }
|
||||
|
||||
TServer& mServer;
|
||||
std::optional<std::reference_wrapper<TNetwork>> mNetwork { std::nullopt };
|
||||
int mInternalPPS { 0 };
|
||||
};
|
||||
22
include/TPluginMonitor.h
Normal file
22
include/TPluginMonitor.h
Normal file
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include "IThreaded.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
|
||||
class TLuaEngine;
|
||||
|
||||
class TPluginMonitor : IThreaded, public std::enable_shared_from_this<TPluginMonitor> {
|
||||
public:
|
||||
TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine);
|
||||
|
||||
void operator()();
|
||||
|
||||
private:
|
||||
std::shared_ptr<TLuaEngine> mEngine;
|
||||
fs::path mPath;
|
||||
std::unordered_map<std::string, fs::file_time_type> mFileTimes;
|
||||
};
|
||||
21
include/TResourceManager.h
Normal file
21
include/TResourceManager.h
Normal file
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
|
||||
class TResourceManager {
|
||||
public:
|
||||
TResourceManager();
|
||||
|
||||
[[nodiscard]] size_t MaxModSize() const { return mMaxModSize; }
|
||||
[[nodiscard]] std::string FileList() const { return mFileList; }
|
||||
[[nodiscard]] std::string TrimmedList() const { return mTrimmedList; }
|
||||
[[nodiscard]] std::string FileSizes() const { return mFileSizes; }
|
||||
[[nodiscard]] int ModsLoaded() const { return mModsLoaded; }
|
||||
|
||||
private:
|
||||
size_t mMaxModSize = 0;
|
||||
std::string mFileSizes;
|
||||
std::string mFileList;
|
||||
std::string mTrimmedList;
|
||||
int mModsLoaded = 0;
|
||||
};
|
||||
25
include/TScopedTimer.h
Normal file
25
include/TScopedTimer.h
Normal file
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
|
||||
class TScopedTimer {
|
||||
public:
|
||||
TScopedTimer();
|
||||
TScopedTimer(const std::string& Name);
|
||||
TScopedTimer(std::function<void(size_t)> OnDestroy);
|
||||
~TScopedTimer();
|
||||
auto GetElapsedTime() const {
|
||||
auto EndTime = std::chrono::high_resolution_clock::now();
|
||||
auto Delta = EndTime - mStartTime;
|
||||
size_t TimeDelta = Delta / std::chrono::milliseconds(1);
|
||||
return TimeDelta;
|
||||
}
|
||||
|
||||
std::function<void(size_t /* time_ms */)> OnDestroy { nullptr };
|
||||
|
||||
private:
|
||||
std::chrono::high_resolution_clock::time_point mStartTime;
|
||||
std::string Name;
|
||||
};
|
||||
38
include/TSentry.h
Normal file
38
include/TSentry.h
Normal file
@@ -0,0 +1,38 @@
|
||||
#ifndef SENTRY_H
|
||||
#define SENTRY_H
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
enum class SentryLevel {
|
||||
Debug = -1,
|
||||
Info = 0,
|
||||
Warning = 1,
|
||||
Error = 2,
|
||||
Fatal = 3,
|
||||
};
|
||||
|
||||
// singleton, dont make this twice
|
||||
class TSentry final {
|
||||
public:
|
||||
TSentry();
|
||||
~TSentry();
|
||||
|
||||
void PrintWelcome();
|
||||
void SetupUser();
|
||||
void Log(SentryLevel level, const std::string& logger, const std::string& text);
|
||||
void LogError(const std::string& text, const std::string& file, const std::string& line);
|
||||
void SetContext(const std::string& context_name, const std::unordered_map<std::string, std::string>& map);
|
||||
void LogException(const std::exception& e, const std::string& file, const std::string& line);
|
||||
void LogAssert(const std::string& condition_string, const std::string& file, const std::string& line, const std::string& function);
|
||||
void AddErrorBreadcrumb(const std::string& msg, const std::string& file, const std::string& line);
|
||||
// cleared when Logged
|
||||
void SetTransaction(const std::string& id);
|
||||
[[nodiscard]] std::unique_lock<std::mutex> CreateExclusiveContext();
|
||||
|
||||
private:
|
||||
bool mValid { true };
|
||||
std::mutex mMutex;
|
||||
};
|
||||
|
||||
#endif // SENTRY_H
|
||||
42
include/TServer.h
Normal file
42
include/TServer.h
Normal file
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include "IThreaded.h"
|
||||
#include "RWMutex.h"
|
||||
#include "TScopedTimer.h"
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_set>
|
||||
|
||||
class TClient;
|
||||
class TNetwork;
|
||||
class TPPSMonitor;
|
||||
|
||||
class TServer final {
|
||||
public:
|
||||
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
|
||||
|
||||
TServer(const std::vector<std::string_view>& Arguments);
|
||||
|
||||
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
||||
std::weak_ptr<TClient> InsertNewClient();
|
||||
void RemoveClient(const std::weak_ptr<TClient>&);
|
||||
// in Fn, return true to continue, return false to break
|
||||
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
||||
size_t ClientCount() const;
|
||||
|
||||
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
||||
static void HandleEvent(TClient& c, const std::string& Data);
|
||||
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
||||
|
||||
|
||||
const TScopedTimer UptimeTimer;
|
||||
private:
|
||||
TClientSet mClients;
|
||||
mutable RWMutex mClientsMutex;
|
||||
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
||||
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
|
||||
static bool IsUnicycle(TClient& c, const std::string& CarJson);
|
||||
static void Apply(TClient& c, int VID, const std::string& pckt);
|
||||
static void HandlePosition(TClient& c, const std::string& Packet);
|
||||
};
|
||||
@@ -1,38 +0,0 @@
|
||||
// Author: lionkor
|
||||
|
||||
#pragma once
|
||||
|
||||
// This header defines unix equivalents of common win32 functions.
|
||||
|
||||
#ifndef WIN32
|
||||
|
||||
#include "CustomAssert.h"
|
||||
#include <cstring>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// ZeroMemory is just a {0} or a memset(addr, 0, len), and it's a macro on MSVC
|
||||
inline void ZeroMemory([[maybe_unused]] void* dst, [[maybe_unused]] size_t len) {
|
||||
[[maybe_unused]] auto res = std::memset(dst, 0, len);
|
||||
Assert(res != nullptr);
|
||||
}
|
||||
// provides unix equivalent of closesocket call in win32
|
||||
inline void CloseSocketProper(int socket) {
|
||||
shutdown(socket, SHUT_RDWR);
|
||||
close(socket);
|
||||
}
|
||||
|
||||
#ifndef __try
|
||||
#define __try
|
||||
#endif
|
||||
|
||||
#ifndef __except
|
||||
#define __except (x) /**/
|
||||
#endif
|
||||
|
||||
#else // win32
|
||||
inline void CloseSocketProper(uint64_t socket) {
|
||||
shutdown(socket, SD_BOTH);
|
||||
closesocket(socket);
|
||||
}
|
||||
#endif // WIN32
|
||||
35
include/VehicleData.h
Normal file
35
include/VehicleData.h
Normal file
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
class TVehicleData final {
|
||||
public:
|
||||
TVehicleData(int ID, std::string Data);
|
||||
~TVehicleData();
|
||||
// We cannot delete this, since vector needs to be able to copy when it resizes.
|
||||
// Deleting this causes some wacky template errors which are hard to decipher,
|
||||
// and end up making no sense, so let's just leave the copy ctor.
|
||||
// TVehicleData(const TVehicleData&) = delete;
|
||||
|
||||
[[nodiscard]] bool IsInvalid() const { return mID == -1; }
|
||||
[[nodiscard]] int ID() const { return mID; }
|
||||
|
||||
[[nodiscard]] std::string Data() const { return mData; }
|
||||
void SetData(const std::string& Data) { mData = Data; }
|
||||
|
||||
bool operator==(const TVehicleData& v) const { return mID == v.mID; }
|
||||
|
||||
private:
|
||||
int mID { -1 };
|
||||
std::string mData;
|
||||
};
|
||||
|
||||
// TODO: unused now, remove?
|
||||
namespace std {
|
||||
template <>
|
||||
struct hash<TVehicleData> {
|
||||
std::size_t operator()(const TVehicleData& s) const noexcept {
|
||||
return s.ID();
|
||||
}
|
||||
};
|
||||
}
|
||||
170
src/ArgsParser.cpp
Normal file
170
src/ArgsParser.cpp
Normal file
@@ -0,0 +1,170 @@
|
||||
#include "ArgsParser.h"
|
||||
#include "Common.h"
|
||||
#include <algorithm>
|
||||
#include <doctest/doctest.h>
|
||||
|
||||
void ArgsParser::Parse(const std::vector<std::string_view>& ArgList) {
|
||||
for (const auto& Arg : ArgList) {
|
||||
if (Arg.size() > 2 && Arg.substr(0, 2) == "--") {
|
||||
// long arg
|
||||
if (Arg.find("=") != Arg.npos) {
|
||||
ConsumeLongAssignment(std::string(Arg));
|
||||
} else {
|
||||
ConsumeLongFlag(std::string(Arg));
|
||||
}
|
||||
} else {
|
||||
beammp_errorf("Error parsing commandline arguments: Supplied argument '{}' is not a valid argument and was ignored.", Arg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool ArgsParser::Verify() {
|
||||
bool Ok = true;
|
||||
for (const auto& RegisteredArg : mRegisteredArguments) {
|
||||
if (RegisteredArg.Flags & Flags::REQUIRED && !FoundArgument(RegisteredArg.Names)) {
|
||||
beammp_errorf("Error in commandline arguments: Argument '{}' is required but wasn't found.", RegisteredArg.Names.at(0));
|
||||
Ok = false;
|
||||
continue;
|
||||
} else if (FoundArgument(RegisteredArg.Names)) {
|
||||
if (RegisteredArg.Flags & Flags::HAS_VALUE) {
|
||||
if (!GetValueOfArgument(RegisteredArg.Names).has_value()) {
|
||||
beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' expects a value, but no value was given.");
|
||||
Ok = false;
|
||||
}
|
||||
} else if (GetValueOfArgument(RegisteredArg.Names).has_value()) {
|
||||
beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' does not expect a value, but one was given.");
|
||||
Ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok;
|
||||
}
|
||||
|
||||
void ArgsParser::RegisterArgument(std::vector<std::string>&& ArgumentNames, int Flags) {
|
||||
mRegisteredArguments.push_back({ ArgumentNames, Flags });
|
||||
}
|
||||
|
||||
bool ArgsParser::FoundArgument(const std::vector<std::string>& Names) {
|
||||
// if any of the found args match any of the names
|
||||
return std::any_of(mFoundArgs.begin(), mFoundArgs.end(),
|
||||
[&Names](const Argument& Arg) -> bool {
|
||||
// if any of the names match this arg's name
|
||||
return std::any_of(Names.begin(), Names.end(), [&Arg](const std::string& Name) -> bool {
|
||||
return Arg.Name == Name;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
std::optional<std::string> ArgsParser::GetValueOfArgument(const std::vector<std::string>& Names) {
|
||||
// finds an entry which has a name that is any of the names in 'Names'
|
||||
auto Found = std::find_if(mFoundArgs.begin(), mFoundArgs.end(), [&Names](const Argument& Arg) -> bool {
|
||||
return std::any_of(Names.begin(), Names.end(), [&Arg](const std::string_view& Name) -> bool {
|
||||
return Arg.Name == Name;
|
||||
});
|
||||
});
|
||||
if (Found != mFoundArgs.end()) {
|
||||
// found
|
||||
return Found->Value;
|
||||
} else {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
bool ArgsParser::IsRegistered(const std::string& Name) {
|
||||
return std::any_of(mRegisteredArguments.begin(), mRegisteredArguments.end(), [&Name](const RegisteredArgument& Arg) {
|
||||
auto Iter = std::find(Arg.Names.begin(), Arg.Names.end(), Name);
|
||||
return Iter != Arg.Names.end();
|
||||
});
|
||||
}
|
||||
|
||||
void ArgsParser::ConsumeLongAssignment(const std::string& Arg) {
|
||||
auto Value = Arg.substr(Arg.rfind("=") + 1);
|
||||
auto Name = Arg.substr(2, Arg.rfind("=") - 2);
|
||||
if (!IsRegistered(Name)) {
|
||||
beammp_warn("Argument '" + Name + "' was supplied but isn't a known argument, so it is likely being ignored.");
|
||||
}
|
||||
mFoundArgs.push_back({ Name, Value });
|
||||
}
|
||||
|
||||
void ArgsParser::ConsumeLongFlag(const std::string& Arg) {
|
||||
auto Name = Arg.substr(2, Arg.rfind("=") - 2);
|
||||
mFoundArgs.push_back({ Name, std::nullopt });
|
||||
if (!IsRegistered(Name)) {
|
||||
beammp_warn("Argument '" + Name + "' was supplied but isn't a known argument, so it is likely being ignored.");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("ArgsParser") {
|
||||
ArgsParser parser;
|
||||
|
||||
SUBCASE("Simple args") {
|
||||
parser.RegisterArgument({ "a" }, ArgsParser::Flags::NONE);
|
||||
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::NONE);
|
||||
parser.Parse({ "--a", "--hello" });
|
||||
CHECK(parser.Verify());
|
||||
CHECK(parser.FoundArgument({ "a" }));
|
||||
CHECK(parser.FoundArgument({ "hello" }));
|
||||
CHECK(parser.FoundArgument({ "a", "hello" }));
|
||||
CHECK(!parser.FoundArgument({ "b" }));
|
||||
CHECK(!parser.FoundArgument({ "goodbye" }));
|
||||
}
|
||||
|
||||
SUBCASE("No args") {
|
||||
parser.RegisterArgument({ "a" }, ArgsParser::Flags::NONE);
|
||||
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::NONE);
|
||||
parser.Parse({});
|
||||
CHECK(parser.Verify());
|
||||
CHECK(!parser.FoundArgument({ "a" }));
|
||||
CHECK(!parser.FoundArgument({ "hello" }));
|
||||
CHECK(!parser.FoundArgument({ "a", "hello" }));
|
||||
CHECK(!parser.FoundArgument({ "b" }));
|
||||
CHECK(!parser.FoundArgument({ "goodbye" }));
|
||||
CHECK(!parser.FoundArgument({ "" }));
|
||||
}
|
||||
|
||||
SUBCASE("Value args") {
|
||||
parser.RegisterArgument({ "a" }, ArgsParser::Flags::HAS_VALUE);
|
||||
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::HAS_VALUE);
|
||||
parser.Parse({ "--a=5", "--hello=world" });
|
||||
CHECK(parser.Verify());
|
||||
REQUIRE(parser.FoundArgument({ "a" }));
|
||||
REQUIRE(parser.FoundArgument({ "hello" }));
|
||||
CHECK(parser.GetValueOfArgument({ "a" }).has_value());
|
||||
CHECK(parser.GetValueOfArgument({ "a" }).value() == "5");
|
||||
CHECK(parser.GetValueOfArgument({ "hello" }).has_value());
|
||||
CHECK(parser.GetValueOfArgument({ "hello" }).value() == "world");
|
||||
}
|
||||
|
||||
SUBCASE("Mixed value & no-value args") {
|
||||
parser.RegisterArgument({ "a" }, ArgsParser::Flags::HAS_VALUE);
|
||||
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::NONE);
|
||||
parser.Parse({ "--a=5", "--hello" });
|
||||
CHECK(parser.Verify());
|
||||
REQUIRE(parser.FoundArgument({ "a" }));
|
||||
REQUIRE(parser.FoundArgument({ "hello" }));
|
||||
CHECK(parser.GetValueOfArgument({ "a" }).has_value());
|
||||
CHECK(parser.GetValueOfArgument({ "a" }).value() == "5");
|
||||
CHECK(!parser.GetValueOfArgument({ "hello" }).has_value());
|
||||
}
|
||||
|
||||
SUBCASE("Required args") {
|
||||
SUBCASE("Two required, two present") {
|
||||
parser.RegisterArgument({ "a" }, ArgsParser::Flags::REQUIRED);
|
||||
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::REQUIRED);
|
||||
parser.Parse({ "--a", "--hello" });
|
||||
CHECK(parser.Verify());
|
||||
}
|
||||
SUBCASE("Two required, one present") {
|
||||
parser.RegisterArgument({ "a" }, ArgsParser::Flags::REQUIRED);
|
||||
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::REQUIRED);
|
||||
parser.Parse({ "--a" });
|
||||
CHECK(!parser.Verify());
|
||||
}
|
||||
SUBCASE("Two required, none present") {
|
||||
parser.RegisterArgument({ "a" }, ArgsParser::Flags::REQUIRED);
|
||||
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::REQUIRED);
|
||||
parser.Parse({ "--b" });
|
||||
CHECK(!parser.Verify());
|
||||
}
|
||||
}
|
||||
}
|
||||
135
src/Client.cpp
Normal file
135
src/Client.cpp
Normal file
@@ -0,0 +1,135 @@
|
||||
#include "Client.h"
|
||||
|
||||
#include "CustomAssert.h"
|
||||
#include "TServer.h"
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
void TClient::DeleteCar(int Ident) {
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
|
||||
return Ident == elem.ID();
|
||||
});
|
||||
if (iter != mVehicleData.end()) {
|
||||
mVehicleData.erase(iter);
|
||||
} else {
|
||||
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
|
||||
}
|
||||
}
|
||||
|
||||
void TClient::ClearCars() {
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
mVehicleData.clear();
|
||||
}
|
||||
|
||||
int TClient::GetOpenCarID() const {
|
||||
int OpenID = 0;
|
||||
bool found;
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
do {
|
||||
found = true;
|
||||
for (auto& v : mVehicleData) {
|
||||
if (v.ID() == OpenID) {
|
||||
OpenID++;
|
||||
found = false;
|
||||
}
|
||||
}
|
||||
} while (!found);
|
||||
return OpenID;
|
||||
}
|
||||
|
||||
void TClient::AddNewCar(int Ident, const std::string& Data) {
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
mVehicleData.emplace_back(Ident, Data);
|
||||
}
|
||||
|
||||
TClient::TVehicleDataLockPair TClient::GetAllCars() {
|
||||
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
|
||||
}
|
||||
|
||||
std::string TClient::GetCarPositionRaw(int Ident) {
|
||||
std::unique_lock lock(mVehiclePositionMutex);
|
||||
try
|
||||
{
|
||||
return mVehiclePosition.at(Ident);
|
||||
}
|
||||
catch (const std::out_of_range& oor) {
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
||||
std::unique_lock lock(mVehiclePositionMutex);
|
||||
mVehiclePosition[Ident] = Data;
|
||||
}
|
||||
|
||||
std::string TClient::GetCarData(int Ident) {
|
||||
{ // lock
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
for (auto& v : mVehicleData) {
|
||||
if (v.ID() == Ident) {
|
||||
return v.Data();
|
||||
}
|
||||
}
|
||||
} // unlock
|
||||
DeleteCar(Ident);
|
||||
return "";
|
||||
}
|
||||
|
||||
void TClient::SetCarData(int Ident, const std::string& Data) {
|
||||
{ // lock
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
for (auto& v : mVehicleData) {
|
||||
if (v.ID() == Ident) {
|
||||
v.SetData(Data);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} // unlock
|
||||
DeleteCar(Ident);
|
||||
}
|
||||
|
||||
int TClient::GetCarCount() const {
|
||||
return int(mVehicleData.size());
|
||||
}
|
||||
|
||||
TServer& TClient::Server() const {
|
||||
return mServer;
|
||||
}
|
||||
|
||||
void TClient::EnqueuePacket(const std::string& Packet) {
|
||||
std::unique_lock Lock(mMissedPacketsMutex);
|
||||
mPacketsSync.push(Packet);
|
||||
}
|
||||
|
||||
TClient::TClient(TServer& Server)
|
||||
: mServer(Server)
|
||||
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
||||
}
|
||||
|
||||
void TClient::UpdatePingTime() {
|
||||
mLastPingTime = std::chrono::high_resolution_clock::now();
|
||||
}
|
||||
int TClient::SecondsSinceLastPing() {
|
||||
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::high_resolution_clock::now() - mLastPingTime)
|
||||
.count();
|
||||
return int(seconds);
|
||||
}
|
||||
|
||||
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
|
||||
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
|
||||
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
|
||||
ReadLock Lock(Server.GetClientMutex());
|
||||
if (!CPtr.expired()) {
|
||||
auto C = CPtr.lock();
|
||||
if (C->GetID() == ID) {
|
||||
MaybeClient = CPtr;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return MaybeClient;
|
||||
}
|
||||
351
src/Common.cpp
Normal file
351
src/Common.cpp
Normal file
@@ -0,0 +1,351 @@
|
||||
#include "Common.h"
|
||||
|
||||
#include "TConsole.h"
|
||||
#include <array>
|
||||
#include <charconv>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <regex>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
#include "CustomAssert.h"
|
||||
#include "Http.h"
|
||||
|
||||
// global, yes, this is ugly, no, it cant be done another way
|
||||
TSentry Sentry {};
|
||||
|
||||
Application::TSettings Application::Settings = {};
|
||||
|
||||
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
||||
std::unique_lock Lock(mShutdownHandlersMutex);
|
||||
if (Handler) {
|
||||
mShutdownHandlers.push_front(Handler);
|
||||
}
|
||||
}
|
||||
|
||||
void Application::GracefullyShutdown() {
|
||||
SetShutdown(true);
|
||||
static bool AlreadyShuttingDown = false;
|
||||
static uint8_t ShutdownAttempts = 0;
|
||||
if (AlreadyShuttingDown) {
|
||||
++ShutdownAttempts;
|
||||
// hard shutdown at 2 additional tries
|
||||
if (ShutdownAttempts == 2) {
|
||||
beammp_info("hard shutdown forced by multiple shutdown requests");
|
||||
std::exit(0);
|
||||
}
|
||||
beammp_info("already shutting down!");
|
||||
return;
|
||||
} else {
|
||||
AlreadyShuttingDown = true;
|
||||
}
|
||||
beammp_trace("waiting for lock release");
|
||||
std::unique_lock Lock(mShutdownHandlersMutex);
|
||||
beammp_info("please wait while all subsystems are shutting down...");
|
||||
for (size_t i = 0; i < mShutdownHandlers.size(); ++i) {
|
||||
beammp_info("Subsystem " + std::to_string(i + 1) + "/" + std::to_string(mShutdownHandlers.size()) + " shutting down");
|
||||
mShutdownHandlers[i]();
|
||||
}
|
||||
// std::exit(-1);
|
||||
}
|
||||
|
||||
std::string Application::ServerVersionString() {
|
||||
return mVersion.AsString();
|
||||
}
|
||||
|
||||
std::array<uint8_t, 3> Application::VersionStrToInts(const std::string& str) {
|
||||
std::array<uint8_t, 3> Version;
|
||||
std::stringstream ss(str);
|
||||
for (uint8_t& i : Version) {
|
||||
std::string Part;
|
||||
std::getline(ss, Part, '.');
|
||||
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), i);
|
||||
}
|
||||
return Version;
|
||||
}
|
||||
|
||||
TEST_CASE("Application::VersionStrToInts") {
|
||||
auto v = Application::VersionStrToInts("1.2.3");
|
||||
CHECK(v[0] == 1);
|
||||
CHECK(v[1] == 2);
|
||||
CHECK(v[2] == 3);
|
||||
|
||||
v = Application::VersionStrToInts("10.20.30");
|
||||
CHECK(v[0] == 10);
|
||||
CHECK(v[1] == 20);
|
||||
CHECK(v[2] == 30);
|
||||
|
||||
v = Application::VersionStrToInts("100.200.255");
|
||||
CHECK(v[0] == 100);
|
||||
CHECK(v[1] == 200);
|
||||
CHECK(v[2] == 255);
|
||||
}
|
||||
|
||||
bool Application::IsOutdated(const Version& Current, const Version& Newest) {
|
||||
if (Newest.major > Current.major) {
|
||||
return true;
|
||||
} else if (Newest.major == Current.major && Newest.minor > Current.minor) {
|
||||
return true;
|
||||
} else if (Newest.major == Current.major && Newest.minor == Current.minor && Newest.patch > Current.patch) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool Application::IsShuttingDown() {
|
||||
std::shared_lock Lock(mShutdownMtx);
|
||||
return mShutdown;
|
||||
}
|
||||
|
||||
void Application::SleepSafeSeconds(size_t Seconds) {
|
||||
// Sleeps for 500 ms, checks if a shutdown occurred, and so forth
|
||||
for (size_t i = 0; i < Seconds * 2; ++i) {
|
||||
if (Application::IsShuttingDown()) {
|
||||
return;
|
||||
} else {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Application::IsOutdated (version check)") {
|
||||
SUBCASE("Same version") {
|
||||
CHECK(!Application::IsOutdated({ 1, 2, 3 }, { 1, 2, 3 }));
|
||||
}
|
||||
// we need to use over 1-2 digits to test against lexical comparisons
|
||||
SUBCASE("Patch outdated") {
|
||||
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
|
||||
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
|
||||
for (uint8_t Major = 0; Major < 10; ++Major) {
|
||||
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major), uint8_t(Minor), uint8_t(Patch + 1) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SUBCASE("Minor outdated") {
|
||||
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
|
||||
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
|
||||
for (uint8_t Major = 0; Major < 10; ++Major) {
|
||||
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major), uint8_t(Minor + 1), uint8_t(Patch) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SUBCASE("Major outdated") {
|
||||
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
|
||||
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
|
||||
for (uint8_t Major = 0; Major < 10; ++Major) {
|
||||
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major + 1), uint8_t(Minor), uint8_t(Patch) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SUBCASE("All outdated") {
|
||||
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
|
||||
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
|
||||
for (uint8_t Major = 0; Major < 10; ++Major) {
|
||||
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major + 1), uint8_t(Minor + 1), uint8_t(Patch + 1) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Application::SetSubsystemStatus(const std::string& Subsystem, Status status) {
|
||||
switch (status) {
|
||||
case Status::Good:
|
||||
beammp_trace("Subsystem '" + Subsystem + "': Good");
|
||||
break;
|
||||
case Status::Bad:
|
||||
beammp_trace("Subsystem '" + Subsystem + "': Bad");
|
||||
break;
|
||||
case Status::Starting:
|
||||
beammp_trace("Subsystem '" + Subsystem + "': Starting");
|
||||
break;
|
||||
case Status::ShuttingDown:
|
||||
beammp_trace("Subsystem '" + Subsystem + "': Shutting down");
|
||||
break;
|
||||
case Status::Shutdown:
|
||||
beammp_trace("Subsystem '" + Subsystem + "': Shutdown");
|
||||
break;
|
||||
}
|
||||
std::unique_lock Lock(mSystemStatusMapMutex);
|
||||
mSystemStatusMap[Subsystem] = status;
|
||||
}
|
||||
|
||||
void Application::SetShutdown(bool Val) {
|
||||
std::unique_lock Lock(mShutdownMtx);
|
||||
mShutdown = Val;
|
||||
}
|
||||
|
||||
TEST_CASE("Application::SetSubsystemStatus") {
|
||||
Application::SetSubsystemStatus("Test", Application::Status::Good);
|
||||
auto Map = Application::GetSubsystemStatuses();
|
||||
CHECK(Map.at("Test") == Application::Status::Good);
|
||||
Application::SetSubsystemStatus("Test", Application::Status::Bad);
|
||||
Map = Application::GetSubsystemStatuses();
|
||||
CHECK(Map.at("Test") == Application::Status::Bad);
|
||||
}
|
||||
|
||||
void Application::CheckForUpdates() {
|
||||
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Starting);
|
||||
static bool FirstTime = true;
|
||||
// checks current version against latest version
|
||||
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
||||
for (const auto& url : GetBackendUrlsInOrder()) {
|
||||
auto Response = Http::GET(GetBackendUrlsInOrder().at(0), 443, "/v/s");
|
||||
bool Matches = std::regex_match(Response, VersionRegex);
|
||||
if (Matches) {
|
||||
auto MyVersion = ServerVersion();
|
||||
auto RemoteVersion = Version(VersionStrToInts(Response));
|
||||
if (IsOutdated(MyVersion, RemoteVersion)) {
|
||||
std::string RealVersionString = RemoteVersion.AsString();
|
||||
beammp_warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION IS OUT! Please update to the new version (v" + RealVersionString + ") of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server" + std::string(ANSI_RESET));
|
||||
} else {
|
||||
if (FirstTime) {
|
||||
beammp_info("Server up-to-date!");
|
||||
}
|
||||
}
|
||||
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Good);
|
||||
break;
|
||||
} else {
|
||||
if (FirstTime) {
|
||||
beammp_debug("Failed to fetch version from: " + url);
|
||||
beammp_trace("got " + Response);
|
||||
auto Lock = Sentry.CreateExclusiveContext();
|
||||
Sentry.SetContext("get-response", { { "response", Response } });
|
||||
Sentry.LogError("failed to get server version", _file_basename, _line);
|
||||
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Application::GetSubsystemStatuses().at("UpdateCheck") == Application::Status::Bad) {
|
||||
if (FirstTime) {
|
||||
beammp_warn("Unable to fetch version info from backend.");
|
||||
}
|
||||
}
|
||||
FirstTime = false;
|
||||
}
|
||||
|
||||
// thread name stuff
|
||||
|
||||
static std::map<std::thread::id, std::string> threadNameMap {};
|
||||
static std::mutex ThreadNameMapMutex {};
|
||||
|
||||
std::string ThreadName(bool DebugModeOverride) {
|
||||
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
||||
if (DebugModeOverride || Application::Settings.DebugModeEnabled) {
|
||||
auto id = std::this_thread::get_id();
|
||||
if (threadNameMap.find(id) != threadNameMap.end()) {
|
||||
// found
|
||||
return threadNameMap.at(id) + " ";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
TEST_CASE("ThreadName") {
|
||||
RegisterThread("MyThread");
|
||||
auto OrigDebug = Application::Settings.DebugModeEnabled;
|
||||
|
||||
// ThreadName adds a space at the end, legacy but we need it still
|
||||
SUBCASE("Debug mode enabled") {
|
||||
Application::Settings.DebugModeEnabled = true;
|
||||
CHECK(ThreadName(true) == "MyThread ");
|
||||
CHECK(ThreadName(false) == "MyThread ");
|
||||
}
|
||||
SUBCASE("Debug mode disabled") {
|
||||
Application::Settings.DebugModeEnabled = false;
|
||||
CHECK(ThreadName(true) == "MyThread ");
|
||||
CHECK(ThreadName(false) == "");
|
||||
}
|
||||
// cleanup
|
||||
Application::Settings.DebugModeEnabled = OrigDebug;
|
||||
}
|
||||
|
||||
void RegisterThread(const std::string& str) {
|
||||
std::string ThreadId;
|
||||
#ifdef BEAMMP_WINDOWS
|
||||
ThreadId = std::to_string(GetCurrentThreadId());
|
||||
#elif defined(BEAMMP_APPLE)
|
||||
ThreadId = std::to_string(getpid()); // todo: research if 'getpid()' is a valid, posix compliant alternative to 'gettid()'
|
||||
#elif defined(BEAMMP_LINUX)
|
||||
ThreadId = std::to_string(gettid());
|
||||
#endif
|
||||
if (Application::Settings.DebugModeEnabled) {
|
||||
std::ofstream ThreadFile(".Threads.log", std::ios::app);
|
||||
ThreadFile << ("Thread \"" + str + "\" is TID " + ThreadId) << std::endl;
|
||||
}
|
||||
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
||||
threadNameMap[std::this_thread::get_id()] = str;
|
||||
}
|
||||
|
||||
TEST_CASE("RegisterThread") {
|
||||
RegisterThread("MyThread");
|
||||
CHECK(threadNameMap.at(std::this_thread::get_id()) == "MyThread");
|
||||
}
|
||||
|
||||
Version::Version(uint8_t major, uint8_t minor, uint8_t patch)
|
||||
: major(major)
|
||||
, minor(minor)
|
||||
, patch(patch) { }
|
||||
|
||||
Version::Version(const std::array<uint8_t, 3>& v)
|
||||
: Version(v[0], v[1], v[2]) {
|
||||
}
|
||||
|
||||
std::string Version::AsString() {
|
||||
return fmt::format("{:d}.{:d}.{:d}", major, minor, patch);
|
||||
}
|
||||
|
||||
TEST_CASE("Version::AsString") {
|
||||
CHECK(Version { 0, 0, 0 }.AsString() == "0.0.0");
|
||||
CHECK(Version { 1, 2, 3 }.AsString() == "1.2.3");
|
||||
CHECK(Version { 255, 255, 255 }.AsString() == "255.255.255");
|
||||
}
|
||||
|
||||
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
||||
if (Application::Settings.LogChat) {
|
||||
std::stringstream ss;
|
||||
ss << ThreadName();
|
||||
ss << "[CHAT] ";
|
||||
if (id != -1) {
|
||||
ss << "(" << id << ") <" << name << "> ";
|
||||
} else {
|
||||
ss << name << "";
|
||||
}
|
||||
ss << msg;
|
||||
#ifdef DOCTEST_CONFIG_DISABLE
|
||||
Application::Console().Write(ss.str());
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
std::string GetPlatformAgnosticErrorString() {
|
||||
#ifdef BEAMMP_WINDOWS
|
||||
// This will provide us with the error code and an error message, all in one.
|
||||
int err;
|
||||
char msgbuf[256];
|
||||
msgbuf[0] = '\0';
|
||||
|
||||
err = GetLastError();
|
||||
|
||||
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||
nullptr,
|
||||
err,
|
||||
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||
msgbuf,
|
||||
sizeof(msgbuf),
|
||||
nullptr);
|
||||
|
||||
if (*msgbuf) {
|
||||
return std::to_string(GetLastError()) + " - " + std::string(msgbuf);
|
||||
} else {
|
||||
return std::to_string(GetLastError());
|
||||
}
|
||||
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||
return std::strerror(errno);
|
||||
#endif
|
||||
}
|
||||
62
src/Compat.cpp
Normal file
62
src/Compat.cpp
Normal file
@@ -0,0 +1,62 @@
|
||||
#include "Compat.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <doctest/doctest.h>
|
||||
|
||||
#ifndef WIN32
|
||||
|
||||
static struct termios old, current;
|
||||
|
||||
void initTermios(int echo) {
|
||||
tcgetattr(0, &old); /* grab old terminal i/o settings */
|
||||
current = old; /* make new settings same as old settings */
|
||||
current.c_lflag &= ~ICANON; /* disable buffered i/o */
|
||||
if (echo) {
|
||||
current.c_lflag |= ECHO; /* set echo mode */
|
||||
} else {
|
||||
current.c_lflag &= ~ECHO; /* set no echo mode */
|
||||
}
|
||||
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
|
||||
}
|
||||
|
||||
void resetTermios(void) {
|
||||
tcsetattr(0, TCSANOW, &old);
|
||||
}
|
||||
|
||||
TEST_CASE("init and reset termios") {
|
||||
if (isatty(STDIN_FILENO)) {
|
||||
struct termios original;
|
||||
tcgetattr(0, &original);
|
||||
SUBCASE("no echo") {
|
||||
initTermios(false);
|
||||
}
|
||||
SUBCASE("yes echo") {
|
||||
initTermios(true);
|
||||
}
|
||||
resetTermios();
|
||||
struct termios current;
|
||||
tcgetattr(0, ¤t);
|
||||
CHECK_EQ(std::memcmp(¤t.c_cc, &original.c_cc, sizeof(current.c_cc)), 0);
|
||||
CHECK_EQ(current.c_cflag, original.c_cflag);
|
||||
CHECK_EQ(current.c_iflag, original.c_iflag);
|
||||
CHECK_EQ(current.c_ispeed, original.c_ispeed);
|
||||
CHECK_EQ(current.c_lflag, original.c_lflag);
|
||||
CHECK_EQ(current.c_line, original.c_line);
|
||||
CHECK_EQ(current.c_oflag, original.c_oflag);
|
||||
CHECK_EQ(current.c_ospeed, original.c_ospeed);
|
||||
}
|
||||
}
|
||||
|
||||
char getch_(int echo) {
|
||||
char ch;
|
||||
initTermios(echo);
|
||||
read(STDIN_FILENO, &ch, 1);
|
||||
resetTermios();
|
||||
return ch;
|
||||
}
|
||||
|
||||
char _getch(void) {
|
||||
return getch_(0);
|
||||
}
|
||||
|
||||
#endif // !WIN32
|
||||
@@ -1,56 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/15/2020
|
||||
///
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <iostream>
|
||||
#include <zlib.h>
|
||||
|
||||
#define Biggest 30000
|
||||
std::string Comp(std::string Data) {
|
||||
std::array<char, Biggest> C {};
|
||||
// obsolete
|
||||
C.fill(0);
|
||||
z_stream defstream;
|
||||
defstream.zalloc = Z_NULL;
|
||||
defstream.zfree = Z_NULL;
|
||||
defstream.opaque = Z_NULL;
|
||||
defstream.avail_in = (uInt)Data.length();
|
||||
defstream.next_in = (Bytef*)&Data[0];
|
||||
defstream.avail_out = Biggest;
|
||||
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
||||
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
||||
deflate(&defstream, Z_SYNC_FLUSH);
|
||||
deflate(&defstream, Z_FINISH);
|
||||
deflateEnd(&defstream);
|
||||
size_t TO = defstream.total_out;
|
||||
std::string Ret(TO, 0);
|
||||
std::copy_n(C.begin(), TO, Ret.begin());
|
||||
return Ret;
|
||||
}
|
||||
std::string DeComp(std::string Compressed) {
|
||||
std::array<char, Biggest> C {};
|
||||
// not needed
|
||||
C.fill(0);
|
||||
z_stream infstream;
|
||||
infstream.zalloc = Z_NULL;
|
||||
infstream.zfree = Z_NULL;
|
||||
infstream.opaque = Z_NULL;
|
||||
infstream.avail_in = Biggest;
|
||||
infstream.next_in = (Bytef*)(&Compressed[0]);
|
||||
infstream.avail_out = Biggest;
|
||||
infstream.next_out = (Bytef*)(C.data());
|
||||
inflateInit(&infstream);
|
||||
inflate(&infstream, Z_SYNC_FLUSH);
|
||||
inflate(&infstream, Z_FINISH);
|
||||
inflateEnd(&infstream);
|
||||
size_t TO = infstream.total_out;
|
||||
std::string Ret(TO, 0);
|
||||
std::copy_n(C.begin(), TO, Ret.begin());
|
||||
return Ret;
|
||||
}
|
||||
263
src/Console.cpp
263
src/Console.cpp
@@ -1,263 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 10/29/2020
|
||||
///
|
||||
|
||||
#include "Lua/LuaSystem.hpp"
|
||||
#ifdef WIN32
|
||||
#include <conio.h>
|
||||
#include <windows.h>
|
||||
#else // *nix
|
||||
typedef unsigned long DWORD, *PDWORD, *LPDWORD;
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
#endif // WIN32
|
||||
#include "Logger.h"
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
std::vector<std::string> QConsoleOut;
|
||||
std::string CInputBuff;
|
||||
std::mutex MLock;
|
||||
std::unique_ptr<Lua> LuaConsole;
|
||||
void HandleInput(const std::string& cmd) {
|
||||
std::cout << std::endl;
|
||||
if (cmd == ("exit")) {
|
||||
_Exit(0);
|
||||
} else if (cmd == ("clear") || cmd == ("cls")) {
|
||||
// 2J is clearscreen, H is reset position to top-left
|
||||
ConsoleOut(("\x1b[2J\x1b[H"));
|
||||
} else {
|
||||
LuaConsole->Execute(cmd);
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessOut() {
|
||||
printf("%c[2K\r", 27);
|
||||
for (const std::string& msg : QConsoleOut)
|
||||
if (!msg.empty())
|
||||
std::cout << msg;
|
||||
MLock.lock();
|
||||
QConsoleOut.clear();
|
||||
MLock.unlock();
|
||||
std::cout << "> " << CInputBuff << std::flush;
|
||||
}
|
||||
|
||||
void ConsoleOut(const std::string& msg) {
|
||||
MLock.lock();
|
||||
QConsoleOut.emplace_back(msg);
|
||||
MLock.unlock();
|
||||
}
|
||||
|
||||
[[noreturn]] void OutputRefresh() {
|
||||
DebugPrintTID();
|
||||
while (true) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
ProcessOut();
|
||||
}
|
||||
}
|
||||
|
||||
#ifndef WIN32
|
||||
|
||||
static struct termios old, current;
|
||||
|
||||
void initTermios(int echo) {
|
||||
tcgetattr(0, &old); /* grab old terminal i/o settings */
|
||||
current = old; /* make new settings same as old settings */
|
||||
current.c_lflag &= ~ICANON; /* disable buffered i/o */
|
||||
if (echo) {
|
||||
current.c_lflag |= ECHO; /* set echo mode */
|
||||
} else {
|
||||
current.c_lflag &= ~ECHO; /* set no echo mode */
|
||||
}
|
||||
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
|
||||
}
|
||||
|
||||
void resetTermios(void) {
|
||||
tcsetattr(0, TCSANOW, &old);
|
||||
}
|
||||
|
||||
char getch_(int echo) {
|
||||
char ch;
|
||||
initTermios(echo);
|
||||
read(STDIN_FILENO, &ch, 1);
|
||||
resetTermios();
|
||||
return ch;
|
||||
}
|
||||
|
||||
char _getch(void) {
|
||||
return getch_(0);
|
||||
}
|
||||
|
||||
#endif // WIN32
|
||||
|
||||
void SetupConsole() {
|
||||
#if defined(WIN32)
|
||||
DWORD outMode = 0;
|
||||
HANDLE stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
if (stdoutHandle == INVALID_HANDLE_VALUE) {
|
||||
error("Invalid console handle! Inputs will not work properly");
|
||||
return;
|
||||
}
|
||||
if (!GetConsoleMode(stdoutHandle, &outMode)) {
|
||||
error("Invalid console mode! Inputs will not work properly");
|
||||
return;
|
||||
}
|
||||
// Enable ANSI escape codes
|
||||
outMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
|
||||
if (!SetConsoleMode(stdoutHandle, outMode)) {
|
||||
error("failed to set console mode! Inputs will not work properly");
|
||||
return;
|
||||
}
|
||||
#else
|
||||
#endif // WIN32
|
||||
}
|
||||
|
||||
static std::vector<std::string> ConsoleHistory {};
|
||||
// buffer used to revert back to what we were writing when we go all the way forward in history
|
||||
static std::string LastInputBuffer {};
|
||||
static size_t ConsoleHistoryReadIndex { 0 };
|
||||
|
||||
static inline void ConsoleHistoryAdd(const std::string& cmd) {
|
||||
LastInputBuffer.clear();
|
||||
ConsoleHistory.push_back(cmd);
|
||||
ConsoleHistoryReadIndex = ConsoleHistory.size();
|
||||
}
|
||||
|
||||
static inline void ConsoleHistoryEnsureBounds() {
|
||||
if (ConsoleHistoryReadIndex >= ConsoleHistory.size()) {
|
||||
ConsoleHistoryReadIndex = ConsoleHistory.size() - 1;
|
||||
}
|
||||
}
|
||||
|
||||
static inline void ConsoleHistoryGoBack() {
|
||||
if (ConsoleHistoryReadIndex > 0) {
|
||||
--ConsoleHistoryReadIndex;
|
||||
ConsoleHistoryEnsureBounds();
|
||||
}
|
||||
}
|
||||
|
||||
static inline void ConsoleHistoryGoForward() {
|
||||
++ConsoleHistoryReadIndex;
|
||||
ConsoleHistoryEnsureBounds();
|
||||
}
|
||||
|
||||
static std::string CompositeInput;
|
||||
static bool CompositeInputExpected { false };
|
||||
|
||||
static void ProcessCompositeInput() {
|
||||
#ifdef WIN32
|
||||
if (CompositeInput.size() == 1 && memcmp(CompositeInput.data(), std::array<char, 1> { 72 }.data(), 1) == 0) {
|
||||
#else // unix
|
||||
if (CompositeInput.size() == 2 && memcmp(CompositeInput.data(), std::array<char, 2> { 91, 65 }.data(), 2) == 0) {
|
||||
#endif // WIN32
|
||||
|
||||
// UP ARROW
|
||||
if (!ConsoleHistory.empty()) {
|
||||
ConsoleHistoryGoBack();
|
||||
CInputBuff = ConsoleHistory.at(ConsoleHistoryReadIndex);
|
||||
}
|
||||
#ifdef WIN32
|
||||
} else if (CompositeInput.size() == 1 && memcmp(CompositeInput.data(), std::array<char, 1> { 80 }.data(), 1) == 0) {
|
||||
#else // unix
|
||||
} else if (CompositeInput.size() == 2 && memcmp(CompositeInput.data(), std::array<char, 2> { 91, 66 }.data(), 2) == 0) {
|
||||
#endif // WIN32
|
||||
|
||||
// DOWN ARROW
|
||||
if (!ConsoleHistory.empty()) {
|
||||
if (ConsoleHistoryReadIndex == ConsoleHistory.size() - 1) {
|
||||
CInputBuff = LastInputBuffer;
|
||||
} else {
|
||||
ConsoleHistoryGoForward();
|
||||
CInputBuff = ConsoleHistory.at(ConsoleHistoryReadIndex);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// not composite input, we made a mistake, so lets just add it to the buffer like usual
|
||||
CInputBuff += CompositeInput;
|
||||
}
|
||||
// ensure history doesnt grow too far beyond a max
|
||||
static constexpr size_t MaxHistory = 10;
|
||||
if (ConsoleHistory.size() > 2 * MaxHistory) {
|
||||
decltype(ConsoleHistory) NewHistory(ConsoleHistory.begin() + ConsoleHistory.size() - MaxHistory, ConsoleHistory.end());
|
||||
ConsoleHistory = std::move(NewHistory);
|
||||
ConsoleHistoryReadIndex = ConsoleHistory.size();
|
||||
}
|
||||
}
|
||||
|
||||
void ReadCin() {
|
||||
DebugPrintTID();
|
||||
size_t null_byte_counter = 0;
|
||||
while (true) {
|
||||
int In = _getch();
|
||||
//info(std::to_string(In));
|
||||
if (In == 0) {
|
||||
++null_byte_counter;
|
||||
if (null_byte_counter > 50) {
|
||||
info(("too many null bytes in input, this is now assumed to be a background thread - console input is now disabled"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (CompositeInputExpected) {
|
||||
CompositeInput += char(In);
|
||||
#ifdef WIN32
|
||||
if (CompositeInput.size() == 1) {
|
||||
#else // unix
|
||||
if (CompositeInput.size() == 2) {
|
||||
#endif // WIN32
|
||||
CompositeInputExpected = false;
|
||||
ProcessCompositeInput();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (In == 13 || In == '\n') {
|
||||
if (!CInputBuff.empty()) {
|
||||
HandleInput(CInputBuff);
|
||||
ConsoleHistoryAdd(CInputBuff);
|
||||
CInputBuff.clear();
|
||||
}
|
||||
} else if (In == 8 || In == 127) {
|
||||
if (!CInputBuff.empty())
|
||||
CInputBuff.pop_back();
|
||||
} else if (In == 4) {
|
||||
CInputBuff = "exit";
|
||||
HandleInput(CInputBuff);
|
||||
CInputBuff.clear();
|
||||
} else if (In == 12) {
|
||||
CInputBuff = "clear";
|
||||
HandleInput(CInputBuff);
|
||||
CInputBuff.clear();
|
||||
#ifdef WIN32
|
||||
} else if (In == 224) {
|
||||
#else // unix
|
||||
} else if (In == 27) {
|
||||
#endif // WIN32
|
||||
|
||||
// escape char, assume stuff follows
|
||||
CompositeInputExpected = true;
|
||||
CompositeInput.clear();
|
||||
} else if (!isprint(In)) {
|
||||
// ignore
|
||||
} else {
|
||||
CInputBuff += char(In);
|
||||
LastInputBuffer = CInputBuff;
|
||||
}
|
||||
}
|
||||
}
|
||||
void ConsoleInit() {
|
||||
SetupConsole();
|
||||
LuaConsole = std::make_unique<Lua>(true);
|
||||
LuaConsole->Init();
|
||||
printf("> ");
|
||||
std::thread In(ReadCin);
|
||||
In.detach();
|
||||
std::thread Out(OutputRefresh);
|
||||
Out.detach();
|
||||
}
|
||||
27
src/Enc.cpp
27
src/Enc.cpp
@@ -1,27 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#include "Security/Enc.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "Logger.h"
|
||||
#include <sstream>
|
||||
|
||||
#ifdef WIN32
|
||||
#include <WS2tcpip.h>
|
||||
int Handle(EXCEPTION_POINTERS* ep, char* Origin) {
|
||||
Assert(false);
|
||||
std::stringstream R;
|
||||
R << ("Code : ") << std::hex
|
||||
<< ep->ExceptionRecord->ExceptionCode
|
||||
<< std::dec << (" Origin : ") << Origin;
|
||||
except(R.str());
|
||||
return 1;
|
||||
}
|
||||
#else
|
||||
// stub
|
||||
int Handle(EXCEPTION_POINTERS*, char*) { return 1; }
|
||||
#endif // WIN32
|
||||
204
src/Http.cpp
Normal file
204
src/Http.cpp
Normal file
@@ -0,0 +1,204 @@
|
||||
#include "Http.h"
|
||||
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "LuaAPI.h"
|
||||
#include "httplib.h"
|
||||
|
||||
#include <map>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
|
||||
// TODO: Add sentry error handling back
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
||||
httplib::SSLClient client(host, port);
|
||||
client.enable_server_certificate_verification(false);
|
||||
client.set_address_family(AF_INET);
|
||||
auto res = client.Get(target.c_str());
|
||||
if (res) {
|
||||
if (status) {
|
||||
*status = res->status;
|
||||
}
|
||||
return res->body;
|
||||
} else {
|
||||
return Http::ErrorString;
|
||||
}
|
||||
}
|
||||
|
||||
std::string Http::POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status, const httplib::Headers& headers) {
|
||||
httplib::SSLClient client(host, port);
|
||||
client.set_read_timeout(std::chrono::seconds(10));
|
||||
beammp_assert(client.is_valid());
|
||||
client.enable_server_certificate_verification(false);
|
||||
client.set_address_family(AF_INET);
|
||||
auto res = client.Post(target.c_str(), headers, body.c_str(), body.size(), ContentType.c_str());
|
||||
if (res) {
|
||||
if (status) {
|
||||
*status = res->status;
|
||||
}
|
||||
return res->body;
|
||||
} else {
|
||||
beammp_debug("POST failed: " + httplib::to_string(res.error()));
|
||||
return Http::ErrorString;
|
||||
}
|
||||
}
|
||||
|
||||
// RFC 2616, RFC 7231
|
||||
static std::map<size_t, const char*> Map = {
|
||||
{ -1, "Invalid Response Code" },
|
||||
{ 100, "Continue" },
|
||||
{ 101, "Switching Protocols" },
|
||||
{ 102, "Processing" },
|
||||
{ 103, "Early Hints" },
|
||||
{ 200, "OK" },
|
||||
{ 201, "Created" },
|
||||
{ 202, "Accepted" },
|
||||
{ 203, "Non-Authoritative Information" },
|
||||
{ 204, "No Content" },
|
||||
{ 205, "Reset Content" },
|
||||
{ 206, "Partial Content" },
|
||||
{ 207, "Multi-Status" },
|
||||
{ 208, "Already Reported" },
|
||||
{ 226, "IM Used" },
|
||||
{ 300, "Multiple Choices" },
|
||||
{ 301, "Moved Permanently" },
|
||||
{ 302, "Found" },
|
||||
{ 303, "See Other" },
|
||||
{ 304, "Not Modified" },
|
||||
{ 305, "Use Proxy" },
|
||||
{ 306, "(Unused)" },
|
||||
{ 307, "Temporary Redirect" },
|
||||
{ 308, "Permanent Redirect" },
|
||||
{ 400, "Bad Request" },
|
||||
{ 401, "Unauthorized" },
|
||||
{ 402, "Payment Required" },
|
||||
{ 403, "Forbidden" },
|
||||
{ 404, "Not Found" },
|
||||
{ 405, "Method Not Allowed" },
|
||||
{ 406, "Not Acceptable" },
|
||||
{ 407, "Proxy Authentication Required" },
|
||||
{ 408, "Request Timeout" },
|
||||
{ 409, "Conflict" },
|
||||
{ 410, "Gone" },
|
||||
{ 411, "Length Required" },
|
||||
{ 412, "Precondition Failed" },
|
||||
{ 413, "Payload Too Large" },
|
||||
{ 414, "URI Too Long" },
|
||||
{ 415, "Unsupported Media Type" },
|
||||
{ 416, "Range Not Satisfiable" },
|
||||
{ 417, "Expectation Failed" },
|
||||
{ 421, "Misdirected Request" },
|
||||
{ 422, "Unprocessable Entity" },
|
||||
{ 423, "Locked" },
|
||||
{ 424, "Failed Dependency" },
|
||||
{ 425, "Too Early" },
|
||||
{ 426, "Upgrade Required" },
|
||||
{ 428, "Precondition Required" },
|
||||
{ 429, "Too Many Requests" },
|
||||
{ 431, "Request Header Fields Too Large" },
|
||||
{ 451, "Unavailable For Legal Reasons" },
|
||||
{ 500, "Internal Server Error" },
|
||||
{ 501, "Not Implemented" },
|
||||
{ 502, "Bad Gateway" },
|
||||
{ 503, "Service Unavailable" },
|
||||
{ 504, "Gateway Timeout" },
|
||||
{ 505, "HTTP Version Not Supported" },
|
||||
{ 506, "Variant Also Negotiates" },
|
||||
{ 507, "Insufficient Storage" },
|
||||
{ 508, "Loop Detected" },
|
||||
{ 510, "Not Extended" },
|
||||
{ 511, "Network Authentication Required" },
|
||||
// cloudflare status codes
|
||||
{ 520, "(CDN) Web Server Returns An Unknown Error" },
|
||||
{ 521, "(CDN) Web Server Is Down" },
|
||||
{ 522, "(CDN) Connection Timed Out" },
|
||||
{ 523, "(CDN) Origin Is Unreachable" },
|
||||
{ 524, "(CDN) A Timeout Occurred" },
|
||||
{ 525, "(CDN) SSL Handshake Failed" },
|
||||
{ 526, "(CDN) Invalid SSL Certificate" },
|
||||
{ 527, "(CDN) Railgun Listener To Origin Error" },
|
||||
{ 530, "(CDN) 1XXX Internal Error" },
|
||||
};
|
||||
|
||||
static const char Magic[] = {
|
||||
0x20, 0x2f, 0x5c, 0x5f,
|
||||
0x2f, 0x5c, 0x0a, 0x28,
|
||||
0x20, 0x6f, 0x2e, 0x6f,
|
||||
0x20, 0x29, 0x0a, 0x20,
|
||||
0x3e, 0x20, 0x5e, 0x20,
|
||||
0x3c, 0x0a, 0x00
|
||||
};
|
||||
|
||||
std::string Http::Status::ToString(int Code) {
|
||||
if (Map.find(Code) != Map.end()) {
|
||||
return Map.at(Code);
|
||||
} else {
|
||||
return std::to_string(Code);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Http::Status::ToString") {
|
||||
CHECK(Http::Status::ToString(200) == "OK");
|
||||
CHECK(Http::Status::ToString(696969) == "696969");
|
||||
CHECK(Http::Status::ToString(-1) == "Invalid Response Code");
|
||||
}
|
||||
|
||||
Http::Server::THttpServerInstance::THttpServerInstance() {
|
||||
Application::SetSubsystemStatus("HTTPServer", Application::Status::Starting);
|
||||
mThread = std::thread(&Http::Server::THttpServerInstance::operator(), this);
|
||||
mThread.detach();
|
||||
}
|
||||
|
||||
void Http::Server::THttpServerInstance::operator()() try {
|
||||
beammp_info("HTTP(S) Server started on port " + std::to_string(Application::Settings.HTTPServerPort));
|
||||
std::unique_ptr<httplib::Server> HttpLibServerInstance;
|
||||
HttpLibServerInstance = std::make_unique<httplib::Server>();
|
||||
// todo: make this IP agnostic so people can set their own IP
|
||||
HttpLibServerInstance->Get("/", [](const httplib::Request&, httplib::Response& res) {
|
||||
res.set_content("<!DOCTYPE html><article><h1>Hello World!</h1><section><p>BeamMP Server can now serve HTTP requests!</p></section></article></html>", "text/html");
|
||||
});
|
||||
HttpLibServerInstance->Get("/health", [](const httplib::Request&, httplib::Response& res) {
|
||||
size_t SystemsGood = 0;
|
||||
size_t SystemsBad = 0;
|
||||
auto Statuses = Application::GetSubsystemStatuses();
|
||||
for (const auto& NameStatusPair : Statuses) {
|
||||
switch (NameStatusPair.second) {
|
||||
case Application::Status::Starting:
|
||||
case Application::Status::ShuttingDown:
|
||||
case Application::Status::Shutdown:
|
||||
case Application::Status::Good:
|
||||
SystemsGood++;
|
||||
break;
|
||||
case Application::Status::Bad:
|
||||
SystemsBad++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
res.set_content(
|
||||
json {
|
||||
{ "ok", SystemsBad == 0 },
|
||||
}
|
||||
.dump(),
|
||||
"application/json");
|
||||
res.status = 200;
|
||||
});
|
||||
// magic endpoint
|
||||
HttpLibServerInstance->Get({ 0x2f, 0x6b, 0x69, 0x74, 0x74, 0x79 }, [](const httplib::Request&, httplib::Response& res) {
|
||||
res.set_content(std::string(Magic), "text/plain");
|
||||
});
|
||||
HttpLibServerInstance->set_logger([](const httplib::Request& Req, const httplib::Response& Res) {
|
||||
beammp_debug("Http Server: " + Req.method + " " + Req.target + " -> " + std::to_string(Res.status));
|
||||
});
|
||||
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
|
||||
auto ret = HttpLibServerInstance->listen(Application::Settings.HTTPServerIP.c_str(), Application::Settings.HTTPServerPort);
|
||||
if (!ret) {
|
||||
beammp_error("Failed to start http server (failed to listen). Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it.");
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("Failed to start http server. Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it. Error: " + std::string(e.what()));
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#include "CustomAssert.h"
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
std::string ServerName;
|
||||
std::string ServerDesc;
|
||||
std::string Resource;
|
||||
std::string MapName;
|
||||
std::string Key;
|
||||
int MaxPlayers;
|
||||
bool Private;
|
||||
int MaxCars;
|
||||
bool Debug;
|
||||
int Port;
|
||||
|
||||
void SetValues(const std::string& Line, int Index) {
|
||||
int state = 0;
|
||||
std::string Data;
|
||||
bool Switch = false;
|
||||
if (Index > 5)
|
||||
Switch = true;
|
||||
for (char c : Line) {
|
||||
if (Switch) {
|
||||
if (c == '\"')
|
||||
state++;
|
||||
if (state > 0 && state < 2)
|
||||
Data += c;
|
||||
} else {
|
||||
if (c == ' ')
|
||||
state++;
|
||||
if (state > 1)
|
||||
Data += c;
|
||||
}
|
||||
}
|
||||
Data = Data.substr(1);
|
||||
std::string::size_type sz;
|
||||
bool FoundTrue = std::string(Data).find("true") != std::string::npos; //searches for "true"
|
||||
switch (Index) {
|
||||
case 1:
|
||||
Debug = FoundTrue; //checks and sets the Debug Value
|
||||
break;
|
||||
case 2:
|
||||
Private = FoundTrue; //checks and sets the Private Value
|
||||
break;
|
||||
case 3:
|
||||
Port = std::stoi(Data, &sz); //sets the Port
|
||||
break;
|
||||
case 4:
|
||||
MaxCars = std::stoi(Data, &sz); //sets the Max Car amount
|
||||
break;
|
||||
case 5:
|
||||
MaxPlayers = std::stoi(Data, &sz); //sets the Max Amount of player
|
||||
break;
|
||||
case 6:
|
||||
MapName = Data; //Map
|
||||
break;
|
||||
case 7:
|
||||
ServerName = Data; //Name
|
||||
break;
|
||||
case 8:
|
||||
ServerDesc = Data; //desc
|
||||
break;
|
||||
case 9:
|
||||
Resource = Data; //File name
|
||||
break;
|
||||
case 10:
|
||||
Key = Data; //File name
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::string RemoveComments(const std::string& Line) {
|
||||
std::string Return;
|
||||
for (char c : Line) {
|
||||
if (c == '#')
|
||||
break;
|
||||
Return += c;
|
||||
}
|
||||
return Return;
|
||||
}
|
||||
void LoadConfig(std::ifstream& IFS) {
|
||||
Assert(IFS.is_open());
|
||||
std::string line;
|
||||
int index = 1;
|
||||
while (getline(IFS, line)) {
|
||||
index++;
|
||||
}
|
||||
if (index - 1 < 11) {
|
||||
error(("Outdated/Incorrect config please remove it server will close in 5 secs"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
_Exit(0);
|
||||
}
|
||||
IFS.close();
|
||||
IFS.open(("Server.cfg"));
|
||||
info(("Config found updating values"));
|
||||
index = 1;
|
||||
while (getline(IFS, line)) {
|
||||
if (line.rfind('#', 0) != 0 && line.rfind(' ', 0) != 0) { //Checks if it starts as Comment
|
||||
std::string CleanLine = RemoveComments(line); //Cleans it from the Comments
|
||||
SetValues(CleanLine, index); //sets the values
|
||||
index++;
|
||||
}
|
||||
}
|
||||
}
|
||||
void GenerateConfig() {
|
||||
std::ofstream FileStream;
|
||||
FileStream.open(("Server.cfg"));
|
||||
FileStream << ("# This is the BeamMP Server Configuration File v0.60\n"
|
||||
"Debug = false # true or false to enable debug console output\n"
|
||||
"Private = true # Private?\n"
|
||||
"Port = 30814 # Port to run the server on UDP and TCP\n"
|
||||
"Cars = 1 # Max cars for every player\n"
|
||||
"MaxPlayers = 10 # Maximum Amount of Clients\n"
|
||||
"Map = \"/levels/gridmap/info.json\" # Default Map\n"
|
||||
"Name = \"BeamMP New Server\" # Server Name\n"
|
||||
"Desc = \"BeamMP Default Description\" # Server Description\n"
|
||||
"use = \"Resources\" # Resource file name\n"
|
||||
"AuthKey = \"\" # Auth Key");
|
||||
FileStream.close();
|
||||
}
|
||||
void Default() {
|
||||
info(("Config not found generating default"));
|
||||
GenerateConfig();
|
||||
error(("You are required to input the AuthKey"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
_Exit(0);
|
||||
}
|
||||
void DebugData() {
|
||||
debug(std::string("Debug : ") + (Debug ? "true" : "false"));
|
||||
debug(std::string("Private : ") + (Private ? "true" : "false"));
|
||||
debug("Port : " + std::to_string(Port));
|
||||
debug("Max Cars : " + std::to_string(MaxCars));
|
||||
debug("MaxPlayers : " + std::to_string(MaxPlayers));
|
||||
debug("MapName : " + MapName);
|
||||
debug("ServerName : " + ServerName);
|
||||
debug("ServerDesc : " + ServerDesc);
|
||||
debug("File : " + Resource);
|
||||
debug("Key length: " + std::to_string(Key.length()));
|
||||
}
|
||||
void InitConfig() {
|
||||
////TODO: Move to json after update 4
|
||||
|
||||
std::ifstream IFS;
|
||||
IFS.open(("Server.cfg"));
|
||||
if (IFS.good())
|
||||
LoadConfig(IFS);
|
||||
else
|
||||
Default();
|
||||
if (IFS.is_open())
|
||||
IFS.close();
|
||||
if (Key.empty()) {
|
||||
error(("No AuthKey was found"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
_Exit(0);
|
||||
}
|
||||
if (Debug)
|
||||
DebugData();
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
#include "Curl/Http.h"
|
||||
#include "Logger.h"
|
||||
#include "Settings.h"
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
void WebsocketInit();
|
||||
std::string GetPlayers() {
|
||||
std::string Return;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr) {
|
||||
Return += c->GetName() + ";";
|
||||
}
|
||||
}
|
||||
return Return;
|
||||
}
|
||||
std::string GenerateCall() {
|
||||
std::stringstream Ret;
|
||||
Ret << "uuid=" << Key << "&players=" << CI->Size()
|
||||
<< "&maxplayers=" << MaxPlayers << "&port=" << Port
|
||||
<< "&map=" << MapName << "&private=" << (Private ? "true" : "false")
|
||||
<< "&version=" << GetSVer() << "&clientversion=" << GetCVer()
|
||||
<< "&name=" << ServerName << "&pps=" << StatReport
|
||||
<< "&modlist=" << FileList << "&modstotalsize=" << MaxModSize
|
||||
<< "&modstotal=" << ModsLoaded << "&playerslist=" << GetPlayers()
|
||||
<< "&desc=" << ServerDesc;
|
||||
return Ret.str();
|
||||
}
|
||||
std::string RunPromise(const std::string& IP, const std::string& R) {
|
||||
std::packaged_task<std::string()> task([&] { return PostHTTP(IP, R, false); });
|
||||
std::future<std::string> f1 = task.get_future();
|
||||
std::thread t(std::move(task));
|
||||
t.detach();
|
||||
auto status = f1.wait_for(std::chrono::seconds(15));
|
||||
if (status != std::future_status::timeout)
|
||||
return f1.get();
|
||||
error("Backend system Timeout please try again later");
|
||||
return "";
|
||||
}
|
||||
|
||||
[[noreturn]] void Heartbeat() {
|
||||
DebugPrintTID();
|
||||
std::string R, T;
|
||||
bool isAuth = false;
|
||||
while (true) {
|
||||
R = GenerateCall();
|
||||
if (!CustomIP.empty())
|
||||
R += "&ip=" + CustomIP;
|
||||
std::string link = "https://beammp.com/heartbeatv2";
|
||||
T = RunPromise(link, R);
|
||||
|
||||
if (T.substr(0, 2) != "20") {
|
||||
//Backend system refused server startup!
|
||||
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||
std::string Backup = "https://backup1.beammp.com/heartbeatv2";
|
||||
T = RunPromise(Backup, R);
|
||||
if (T.substr(0, 2) != "20") {
|
||||
warn("Backend system refused server! Server might not show in the public list");
|
||||
}
|
||||
}
|
||||
//Server Authenticated
|
||||
if (!isAuth) {
|
||||
WebsocketInit();
|
||||
if (T.length() == 4)info(("Authenticated!"));
|
||||
else info(("Resumed authenticated session!"));
|
||||
isAuth = true;
|
||||
}
|
||||
//std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
}
|
||||
}
|
||||
void HBInit() {
|
||||
std::thread HB(Heartbeat);
|
||||
HB.detach();
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
uint64_t MaxModSize = 0;
|
||||
std::string FileSizes;
|
||||
std::string FileList;
|
||||
int ModsLoaded = 0;
|
||||
|
||||
void InitRes() {
|
||||
std::string Path = Resource + "/Client";
|
||||
if (!fs::exists(Path))
|
||||
fs::create_directory(Path);
|
||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
||||
auto pos = entry.path().string().find(".zip");
|
||||
if (pos != std::string::npos) {
|
||||
if (entry.path().string().length() - pos == 4) {
|
||||
FileList += entry.path().string() + ";";
|
||||
FileSizes += std::to_string(uint64_t(fs::file_size(entry.path()))) + ";";
|
||||
MaxModSize += uint64_t(fs::file_size(entry.path()));
|
||||
ModsLoaded++;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::replace(FileList.begin(), FileList.end(), '\\', '/');
|
||||
if (ModsLoaded)
|
||||
info("Loaded " + std::to_string(ModsLoaded) + " Mods");
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
std::string CustomIP;
|
||||
std::string GetSVer() {
|
||||
return "1.20";
|
||||
}
|
||||
std::string GetCVer() {
|
||||
return "1.80";
|
||||
}
|
||||
void Args(int argc, char* argv[]) {
|
||||
info("BeamMP Server Running version " + GetSVer());
|
||||
if (argc > 1) {
|
||||
CustomIP = argv[1];
|
||||
size_t n = std::count(CustomIP.begin(), CustomIP.end(), '.');
|
||||
auto p = CustomIP.find_first_not_of((".0123456789"));
|
||||
if (p != std::string::npos || n != 3 || CustomIP.substr(0, 3) == ("127")) {
|
||||
CustomIP.clear();
|
||||
warn("IP Specified is invalid! Ignoring");
|
||||
} else
|
||||
info("Server started with custom IP");
|
||||
}
|
||||
}
|
||||
void InitServer(int argc, char* argv[]) {
|
||||
InitLog();
|
||||
Args(argc, argv);
|
||||
CI = std::make_unique<ClientInterface>();
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 5/20/2020
|
||||
///
|
||||
|
||||
#include "Logger.h"
|
||||
#include "Lua/LuaSystem.hpp"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include <thread>
|
||||
|
||||
#ifdef __linux
|
||||
// we need this for `struct stat`
|
||||
#include <sys/stat.h>
|
||||
#endif // __linux
|
||||
|
||||
std::set<std::unique_ptr<Lua>> PluginEngine;
|
||||
bool NewFile(const std::string& Path) {
|
||||
for (auto& Script : PluginEngine) {
|
||||
if (Path == Script->GetFileName())
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
void RegisterFiles(const std::string& Path, bool HotSwap) {
|
||||
std::string Name = Path.substr(Path.find_last_of('\\') + 1);
|
||||
if (!HotSwap)
|
||||
info(("Loading plugin : ") + Name);
|
||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
||||
auto pos = entry.path().string().find((".lua"));
|
||||
if (pos != std::string::npos && entry.path().string().length() - pos == 4) {
|
||||
if (!HotSwap || NewFile(entry.path().string())) {
|
||||
auto FileName = entry.path().string();
|
||||
std::unique_ptr<Lua> ScriptToInsert(new Lua(Name, FileName, fs::last_write_time(FileName)));
|
||||
auto& Script = *ScriptToInsert;
|
||||
PluginEngine.insert(std::move(ScriptToInsert));
|
||||
Script.Init();
|
||||
if (HotSwap)
|
||||
info(("[HOTSWAP] Added : ") + Script.GetFileName().substr(Script.GetFileName().find('\\')));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void FolderList(const std::string& Path, bool HotSwap) {
|
||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
||||
auto pos = entry.path().filename().string().find('.');
|
||||
if (pos == std::string::npos) {
|
||||
RegisterFiles(entry.path().string(), HotSwap);
|
||||
}
|
||||
}
|
||||
}
|
||||
[[noreturn]] void HotSwaps(const std::string& path) {
|
||||
DebugPrintTID();
|
||||
while (true) {
|
||||
if (!PluginEngine.empty()) {
|
||||
for (auto& Script : PluginEngine) {
|
||||
struct stat Info { };
|
||||
if (stat(Script->GetFileName().c_str(), &Info) != 0) {
|
||||
Script->SetStopThread(true);
|
||||
PluginEngine.erase(Script);
|
||||
info(("[HOTSWAP] Removed removed script due to delete"));
|
||||
break;
|
||||
}
|
||||
if (Script->GetLastWrite() != fs::last_write_time(Script->GetFileName())) {
|
||||
Script->SetStopThread(true);
|
||||
info(("[HOTSWAP] Updated Scripts due to edit"));
|
||||
Script->SetLastWrite(fs::last_write_time(Script->GetFileName()));
|
||||
Script->Reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
FolderList(path, true);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(2));
|
||||
}
|
||||
}
|
||||
|
||||
void InitLua() {
|
||||
if (!fs::exists(Resource)) {
|
||||
fs::create_directory(Resource);
|
||||
}
|
||||
std::string Path = Resource + ("/Server");
|
||||
if (!fs::exists(Path)) {
|
||||
fs::create_directory(Path);
|
||||
}
|
||||
FolderList(Path, false);
|
||||
std::thread t1(HotSwaps, Path);
|
||||
t1.detach();
|
||||
info(("Lua system online"));
|
||||
}
|
||||
@@ -1,705 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 5/19/2020
|
||||
///
|
||||
|
||||
#include "Lua/LuaSystem.hpp"
|
||||
#include "Client.hpp"
|
||||
#include "Logger.h"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
std::shared_ptr<LuaArg> CreateArg(lua_State* L, int T, int S) {
|
||||
if (S > T)
|
||||
return nullptr;
|
||||
std::shared_ptr<LuaArg> temp(new LuaArg);
|
||||
for (int C = S; C <= T; C++) {
|
||||
if (lua_isstring(L, C)) {
|
||||
temp->args.emplace_back(std::string(lua_tostring(L, C)));
|
||||
} else if (lua_isinteger(L, C)) {
|
||||
temp->args.emplace_back(int(lua_tointeger(L, C)));
|
||||
} else if (lua_isboolean(L, C)) {
|
||||
temp->args.emplace_back(bool(lua_toboolean(L, C)));
|
||||
} else if (lua_isnumber(L, C)) {
|
||||
temp->args.emplace_back(float(lua_tonumber(L, C)));
|
||||
}
|
||||
}
|
||||
return temp;
|
||||
}
|
||||
void ClearStack(lua_State* L) {
|
||||
lua_settop(L, 0);
|
||||
}
|
||||
std::optional<std::reference_wrapper<Lua>> GetScript(lua_State* L) {
|
||||
for (auto& Script : PluginEngine) {
|
||||
if (Script->GetState() == L)
|
||||
return *Script;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
void SendError(lua_State* L, const std::string& msg) {
|
||||
Assert(L);
|
||||
auto MaybeS = GetScript(L);
|
||||
std::string a;
|
||||
if (!MaybeS.has_value()) {
|
||||
a = ("_Console");
|
||||
} else {
|
||||
Lua& S = MaybeS.value();
|
||||
a = fs::path(S.GetFileName()).filename().string();
|
||||
}
|
||||
warn(a + (" | Incorrect Call of ") + msg);
|
||||
}
|
||||
std::any Trigger(Lua* lua, const std::string& R, std::shared_ptr<LuaArg> arg) {
|
||||
std::lock_guard<std::mutex> lockGuard(lua->Lock);
|
||||
std::packaged_task<std::any(std::shared_ptr<LuaArg>)> task([lua, R](std::shared_ptr<LuaArg> arg) { return CallFunction(lua, R, arg); });
|
||||
std::future<std::any> f1 = task.get_future();
|
||||
std::thread t(std::move(task), arg);
|
||||
t.detach();
|
||||
auto status = f1.wait_for(std::chrono::seconds(5));
|
||||
if (status != std::future_status::timeout)
|
||||
return f1.get();
|
||||
SendError(lua->GetState(), R + " took too long to respond");
|
||||
return 0;
|
||||
}
|
||||
std::any FutureWait(Lua* lua, const std::string& R, std::shared_ptr<LuaArg> arg, bool Wait) {
|
||||
Assert(lua);
|
||||
std::packaged_task<std::any(std::shared_ptr<LuaArg>)> task([lua, R](std::shared_ptr<LuaArg> arg) { return Trigger(lua, R, arg); });
|
||||
std::future<std::any> f1 = task.get_future();
|
||||
std::thread t(std::move(task), arg);
|
||||
t.detach();
|
||||
int T = 0;
|
||||
if (Wait)
|
||||
T = 6;
|
||||
auto status = f1.wait_for(std::chrono::seconds(T));
|
||||
if (status != std::future_status::timeout)
|
||||
return f1.get();
|
||||
return 0;
|
||||
}
|
||||
std::any TriggerLuaEvent(const std::string& Event, bool local, Lua* Caller, std::shared_ptr<LuaArg> arg, bool Wait) {
|
||||
std::any R;
|
||||
std::string Type;
|
||||
int Ret = 0;
|
||||
for (auto& Script : PluginEngine) {
|
||||
if (Script->IsRegistered(Event)) {
|
||||
if (local) {
|
||||
if (Script->GetPluginName() == Caller->GetPluginName()) {
|
||||
R = FutureWait(Script.get(), Script->GetRegistered(Event), arg, Wait);
|
||||
Type = R.type().name();
|
||||
if (Type.find("int") != std::string::npos) {
|
||||
if (std::any_cast<int>(R))
|
||||
Ret++;
|
||||
} else if (Event == "onPlayerAuth")
|
||||
return R;
|
||||
}
|
||||
} else {
|
||||
R = FutureWait(Script.get(), Script->GetRegistered(Event), arg, Wait);
|
||||
Type = R.type().name();
|
||||
if (Type.find("int") != std::string::npos) {
|
||||
if (std::any_cast<int>(R))
|
||||
Ret++;
|
||||
} else if (Event == "onPlayerAuth")
|
||||
return R;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ret;
|
||||
}
|
||||
bool ConsoleCheck(lua_State* L, int r) {
|
||||
if (r != LUA_OK) {
|
||||
std::string msg = lua_tostring(L, -1);
|
||||
warn(("_Console | ") + msg);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool CheckLua(lua_State* L, int r) {
|
||||
if (r != LUA_OK) {
|
||||
std::string msg = lua_tostring(L, -1);
|
||||
auto MaybeS = GetScript(L);
|
||||
if (MaybeS.has_value()) {
|
||||
Lua& S = MaybeS.value();
|
||||
std::string a = fs::path(S.GetFileName()).filename().string();
|
||||
warn(a + " | " + msg);
|
||||
return false;
|
||||
}
|
||||
// What the fuck, what do we do?!
|
||||
AssertNotReachable();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int lua_RegisterEvent(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
auto MaybeScript = GetScript(L);
|
||||
Assert(MaybeScript.has_value());
|
||||
Lua& Script = MaybeScript.value();
|
||||
if (Args == 2 && lua_isstring(L, 1) && lua_isstring(L, 2)) {
|
||||
Script.RegisterEvent(lua_tostring(L, 1), lua_tostring(L, 2));
|
||||
} else
|
||||
SendError(L, ("RegisterEvent invalid argument count expected 2 got ") + std::to_string(Args));
|
||||
return 0;
|
||||
}
|
||||
int lua_TriggerEventL(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
auto MaybeScript = GetScript(L);
|
||||
Assert(MaybeScript.has_value());
|
||||
Lua& Script = MaybeScript.value();
|
||||
if (Args > 0) {
|
||||
if (lua_isstring(L, 1)) {
|
||||
TriggerLuaEvent(lua_tostring(L, 1), true, &Script, CreateArg(L, Args, 2), false);
|
||||
} else
|
||||
SendError(L, ("TriggerLocalEvent wrong argument [1] need string"));
|
||||
} else {
|
||||
SendError(L, ("TriggerLocalEvent not enough arguments expected 1 got 0"));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int lua_TriggerEventG(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
auto MaybeScript = GetScript(L);
|
||||
Assert(MaybeScript.has_value());
|
||||
Lua& Script = MaybeScript.value();
|
||||
if (Args > 0) {
|
||||
if (lua_isstring(L, 1)) {
|
||||
TriggerLuaEvent(lua_tostring(L, 1), false, &Script, CreateArg(L, Args, 2), false);
|
||||
} else
|
||||
SendError(L, ("TriggerGlobalEvent wrong argument [1] need string"));
|
||||
} else
|
||||
SendError(L, ("TriggerGlobalEvent not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
|
||||
char* ThreadOrigin(Lua* lua) {
|
||||
std::string T = "Thread in " + fs::path(lua->GetFileName()).filename().string();
|
||||
char* Data = new char[T.size() + 1];
|
||||
ZeroMemory(Data, T.size() + 1);
|
||||
memcpy(Data, T.c_str(), T.size());
|
||||
return Data;
|
||||
}
|
||||
void SafeExecution(Lua* lua, const std::string& FuncName) {
|
||||
lua_State* luaState = lua->GetState();
|
||||
lua_getglobal(luaState, FuncName.c_str());
|
||||
if (lua_isfunction(luaState, -1)) {
|
||||
char* Origin = ThreadOrigin(lua);
|
||||
#ifdef WIN32
|
||||
__try {
|
||||
int R = lua_pcall(luaState, 0, 0, 0);
|
||||
CheckLua(luaState, R);
|
||||
} __except (Handle(GetExceptionInformation(), Origin)) {
|
||||
}
|
||||
#else // unix
|
||||
int R = lua_pcall(luaState, 0, 0, 0);
|
||||
CheckLua(luaState, R);
|
||||
#endif // WIN32
|
||||
delete[] Origin;
|
||||
}
|
||||
ClearStack(luaState);
|
||||
}
|
||||
|
||||
void ExecuteAsync(Lua* lua, const std::string& FuncName) {
|
||||
std::lock_guard<std::mutex> lockGuard(lua->Lock);
|
||||
SafeExecution(lua, FuncName);
|
||||
}
|
||||
void CallAsync(Lua* lua, const std::string& Func, int U) {
|
||||
DebugPrintTID();
|
||||
lua->SetStopThread(false);
|
||||
int D = 1000 / U;
|
||||
while (!lua->GetStopThread()) {
|
||||
ExecuteAsync(lua, Func);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(D));
|
||||
}
|
||||
}
|
||||
int lua_StopThread(lua_State* L) {
|
||||
auto MaybeScript = GetScript(L);
|
||||
Assert(MaybeScript.has_value());
|
||||
// ugly, but whatever, this is safe as fuck
|
||||
MaybeScript.value().get().SetStopThread(true);
|
||||
return 0;
|
||||
}
|
||||
int lua_CreateThread(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
if (Args > 1) {
|
||||
if (lua_isstring(L, 1)) {
|
||||
std::string STR = lua_tostring(L, 1);
|
||||
if (lua_isinteger(L, 2) || lua_isnumber(L, 2)) {
|
||||
int U = int(lua_tointeger(L, 2));
|
||||
if (U > 0 && U < 501) {
|
||||
auto MaybeScript = GetScript(L);
|
||||
Assert(MaybeScript.has_value());
|
||||
Lua& Script = MaybeScript.value();
|
||||
std::thread t1(CallAsync, &Script, STR, U);
|
||||
t1.detach();
|
||||
} else
|
||||
SendError(L, ("CreateThread wrong argument [2] number must be between 1 and 500"));
|
||||
} else
|
||||
SendError(L, ("CreateThread wrong argument [2] need number"));
|
||||
} else
|
||||
SendError(L, ("CreateThread wrong argument [1] need string"));
|
||||
} else
|
||||
SendError(L, ("CreateThread not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
int lua_Sleep(lua_State* L) {
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int t = int(lua_tonumber(L, 1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(t));
|
||||
} else {
|
||||
SendError(L, ("Sleep not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
Client* GetClient(int ID) {
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr && c->GetID() == ID) {
|
||||
return c.get();
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
int lua_isConnected(lua_State* L) {
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int ID = int(lua_tonumber(L, 1));
|
||||
Client* c = GetClient(ID);
|
||||
if (c != nullptr)
|
||||
lua_pushboolean(L, c->isConnected);
|
||||
else
|
||||
return 0;
|
||||
} else {
|
||||
SendError(L, ("isConnected not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
int lua_GetPlayerName(lua_State* L) {
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int ID = int(lua_tonumber(L, 1));
|
||||
Client* c = GetClient(ID);
|
||||
if (c != nullptr)
|
||||
lua_pushstring(L, c->GetName().c_str());
|
||||
else
|
||||
return 0;
|
||||
} else {
|
||||
SendError(L, ("GetPlayerName not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
int lua_GetPlayerCount(lua_State* L) {
|
||||
lua_pushinteger(L, CI->Size());
|
||||
return 1;
|
||||
}
|
||||
int lua_GetGuest(lua_State* L) {
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int ID = int(lua_tonumber(L, 1));
|
||||
Client* c = GetClient(ID);
|
||||
if (c != nullptr)
|
||||
lua_pushboolean(L, c->isGuest);
|
||||
else
|
||||
return 0;
|
||||
} else {
|
||||
SendError(L, "GetGuest not enough arguments");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
int lua_GetAllPlayers(lua_State* L) {
|
||||
lua_newtable(L);
|
||||
int i = 1;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c == nullptr)
|
||||
continue;
|
||||
lua_pushinteger(L, c->GetID());
|
||||
lua_pushstring(L, c->GetName().c_str());
|
||||
lua_settable(L, -3);
|
||||
i++;
|
||||
}
|
||||
if (CI->Clients.empty())
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
int lua_GetCars(lua_State* L) {
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int ID = int(lua_tonumber(L, 1));
|
||||
Client* c = GetClient(ID);
|
||||
if (c != nullptr) {
|
||||
int i = 1;
|
||||
for (auto& v : c->GetAllCars()) {
|
||||
if (v != nullptr) {
|
||||
lua_pushinteger(L, v->ID);
|
||||
lua_pushstring(L, v->Data.substr(3).c_str());
|
||||
lua_settable(L, -3);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
if (c->GetAllCars().empty())
|
||||
return 0;
|
||||
} else
|
||||
return 0;
|
||||
} else {
|
||||
SendError(L, ("GetPlayerVehicles not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
int lua_dropPlayer(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int ID = int(lua_tonumber(L, 1));
|
||||
Client* c = GetClient(ID);
|
||||
if (c == nullptr)
|
||||
return 0;
|
||||
std::string Reason;
|
||||
if (Args > 1 && lua_isstring(L, 2)) {
|
||||
Reason = std::string((" Reason : ")) + lua_tostring(L, 2);
|
||||
}
|
||||
Respond(c, "C:Server:You have been Kicked from the server! " + Reason, true);
|
||||
c->SetStatus(-2);
|
||||
info(("Closing socket due to kick"));
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
} else
|
||||
SendError(L, ("DropPlayer not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
int lua_sendChat(lua_State* L) {
|
||||
if (lua_isinteger(L, 1) || lua_isnumber(L, 1)) {
|
||||
if (lua_isstring(L, 2)) {
|
||||
int ID = int(lua_tointeger(L, 1));
|
||||
if (ID == -1) {
|
||||
std::string Packet = "C:Server: " + std::string(lua_tostring(L, 2));
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
} else {
|
||||
Client* c = GetClient(ID);
|
||||
if (c != nullptr) {
|
||||
if (!c->isSynced)
|
||||
return 0;
|
||||
std::string Packet = "C:Server: " + std::string(lua_tostring(L, 2));
|
||||
Respond(c, Packet, true);
|
||||
} else
|
||||
SendError(L, ("SendChatMessage invalid argument [1] invalid ID"));
|
||||
}
|
||||
} else
|
||||
SendError(L, ("SendChatMessage invalid argument [2] expected string"));
|
||||
} else
|
||||
SendError(L, ("SendChatMessage invalid argument [1] expected number"));
|
||||
return 0;
|
||||
}
|
||||
int lua_RemoveVehicle(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
if (Args != 2) {
|
||||
SendError(L, ("RemoveVehicle invalid argument count expected 2 got ") + std::to_string(Args));
|
||||
return 0;
|
||||
}
|
||||
if ((lua_isinteger(L, 1) || lua_isnumber(L, 1)) && (lua_isinteger(L, 2) || lua_isnumber(L, 2))) {
|
||||
int PID = int(lua_tointeger(L, 1));
|
||||
int VID = int(lua_tointeger(L, 2));
|
||||
Client* c = GetClient(PID);
|
||||
if (c == nullptr) {
|
||||
SendError(L, ("RemoveVehicle invalid Player ID"));
|
||||
return 0;
|
||||
}
|
||||
if (!c->GetCarData(VID).empty()) {
|
||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||
SendToAll(nullptr, Destroy, true, true);
|
||||
c->DeleteCar(VID);
|
||||
}
|
||||
} else
|
||||
SendError(L, ("RemoveVehicle invalid argument expected number"));
|
||||
return 0;
|
||||
}
|
||||
int lua_HWID(lua_State* L) {
|
||||
lua_pushinteger(L, -1);
|
||||
return 1;
|
||||
}
|
||||
int lua_RemoteEvent(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
if (Args != 3) {
|
||||
SendError(L, ("TriggerClientEvent invalid argument count expected 3 got ") + std::to_string(Args));
|
||||
return 0;
|
||||
}
|
||||
if (!lua_isnumber(L, 1)) {
|
||||
SendError(L, ("TriggerClientEvent invalid argument [1] expected number"));
|
||||
return 0;
|
||||
}
|
||||
if (!lua_isstring(L, 2)) {
|
||||
SendError(L, ("TriggerClientEvent invalid argument [2] expected string"));
|
||||
return 0;
|
||||
}
|
||||
if (!lua_isstring(L, 3)) {
|
||||
SendError(L, ("TriggerClientEvent invalid argument [3] expected string"));
|
||||
return 0;
|
||||
}
|
||||
int ID = int(lua_tointeger(L, 1));
|
||||
std::string Packet = "E:" + std::string(lua_tostring(L, 2)) + ":" + std::string(lua_tostring(L, 3));
|
||||
if (ID == -1)
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
else {
|
||||
Client* c = GetClient(ID);
|
||||
if (c == nullptr) {
|
||||
SendError(L, ("TriggerClientEvent invalid Player ID"));
|
||||
return 0;
|
||||
}
|
||||
Respond(c, Packet, true);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int lua_ServerExit(lua_State* L) {
|
||||
if (lua_gettop(L) > 0) {
|
||||
if (lua_isnumber(L, 1)) {
|
||||
_Exit(int(lua_tointeger(L, 1)));
|
||||
}
|
||||
}
|
||||
_Exit(0);
|
||||
}
|
||||
int lua_Set(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
if (Args != 2) {
|
||||
SendError(L, ("set invalid argument count expected 2 got ") + std::to_string(Args));
|
||||
return 0;
|
||||
}
|
||||
if (!lua_isnumber(L, 1)) {
|
||||
SendError(L, ("set invalid argument [1] expected number"));
|
||||
return 0;
|
||||
}
|
||||
auto MaybeSrc = GetScript(L);
|
||||
std::string Name;
|
||||
if (!MaybeSrc.has_value()) {
|
||||
Name = ("_Console");
|
||||
} else {
|
||||
Name = MaybeSrc.value().get().GetPluginName();
|
||||
}
|
||||
int C = int(lua_tointeger(L, 1));
|
||||
switch (C) {
|
||||
case 0: //debug
|
||||
if (lua_isboolean(L, 2)) {
|
||||
Debug = lua_toboolean(L, 2);
|
||||
info(Name + (" | Debug -> ") + (Debug ? "true" : "false"));
|
||||
} else
|
||||
SendError(L, ("set invalid argument [2] expected boolean for ID : 0"));
|
||||
break;
|
||||
case 1: //private
|
||||
if (lua_isboolean(L, 2)) {
|
||||
Private = lua_toboolean(L, 2);
|
||||
info(Name + (" | Private -> ") + (Private ? "true" : "false"));
|
||||
} else
|
||||
SendError(L, ("set invalid argument [2] expected boolean for ID : 1"));
|
||||
break;
|
||||
case 2: //max cars
|
||||
if (lua_isnumber(L, 2)) {
|
||||
MaxCars = int(lua_tointeger(L, 2));
|
||||
info(Name + (" | MaxCars -> ") + std::to_string(MaxCars));
|
||||
} else
|
||||
SendError(L, ("set invalid argument [2] expected number for ID : 2"));
|
||||
break;
|
||||
case 3: //max players
|
||||
if (lua_isnumber(L, 2)) {
|
||||
MaxPlayers = int(lua_tointeger(L, 2));
|
||||
info(Name + (" | MaxPlayers -> ") + std::to_string(MaxPlayers));
|
||||
} else
|
||||
SendError(L, ("set invalid argument [2] expected number for ID : 3"));
|
||||
break;
|
||||
case 4: //Map
|
||||
if (lua_isstring(L, 2)) {
|
||||
MapName = lua_tostring(L, 2);
|
||||
info(Name + (" | MapName -> ") + MapName);
|
||||
} else
|
||||
SendError(L, ("set invalid argument [2] expected string for ID : 4"));
|
||||
break;
|
||||
case 5: //Name
|
||||
if (lua_isstring(L, 2)) {
|
||||
ServerName = lua_tostring(L, 2);
|
||||
info(Name + (" | ServerName -> ") + ServerName);
|
||||
} else
|
||||
SendError(L, ("set invalid argument [2] expected string for ID : 5"));
|
||||
break;
|
||||
case 6: //Desc
|
||||
if (lua_isstring(L, 2)) {
|
||||
ServerDesc = lua_tostring(L, 2);
|
||||
info(Name + (" | ServerDesc -> ") + ServerDesc);
|
||||
} else
|
||||
SendError(L, ("set invalid argument [2] expected string for ID : 6"));
|
||||
break;
|
||||
default:
|
||||
warn(("Invalid config ID : ") + std::to_string(C));
|
||||
break;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
extern "C" {
|
||||
int lua_Print(lua_State* L) {
|
||||
int Arg = lua_gettop(L);
|
||||
for (int i = 1; i <= Arg; i++) {
|
||||
auto str = lua_tostring(L, i);
|
||||
if (str != nullptr) {
|
||||
ConsoleOut(str + std::string(("\n")));
|
||||
} else {
|
||||
ConsoleOut(("nil\n"));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Lua::Lua(const std::string& PluginName, const std::string& FileName, fs::file_time_type LastWrote, bool Console)
|
||||
: luaState(luaL_newstate()) {
|
||||
Assert(luaState);
|
||||
if (!PluginName.empty()) {
|
||||
SetPluginName(PluginName);
|
||||
}
|
||||
if (!FileName.empty()) {
|
||||
SetFileName(FileName);
|
||||
}
|
||||
SetLastWrite(LastWrote);
|
||||
_Console = Console;
|
||||
}
|
||||
|
||||
Lua::Lua(bool Console)
|
||||
: luaState(luaL_newstate()) {
|
||||
_Console = Console;
|
||||
}
|
||||
|
||||
void Lua::Execute(const std::string& Command) {
|
||||
if (ConsoleCheck(luaState, luaL_dostring(luaState, Command.c_str()))) {
|
||||
lua_settop(luaState, 0);
|
||||
}
|
||||
}
|
||||
void Lua::Reload() {
|
||||
if (CheckLua(luaState, luaL_dofile(luaState, _FileName.c_str()))) {
|
||||
CallFunction(this, ("onInit"), nullptr);
|
||||
}
|
||||
}
|
||||
std::string Lua::GetOrigin() {
|
||||
return fs::path(GetFileName()).filename().string();
|
||||
}
|
||||
|
||||
std::any CallFunction(Lua* lua, const std::string& FuncName, std::shared_ptr<LuaArg> Arg) {
|
||||
lua_State* luaState = lua->GetState();
|
||||
lua_getglobal(luaState, FuncName.c_str());
|
||||
if (lua_isfunction(luaState, -1)) {
|
||||
int Size = 0;
|
||||
if (Arg != nullptr) {
|
||||
Size = int(Arg->args.size());
|
||||
Arg->PushArgs(luaState);
|
||||
}
|
||||
int R = lua_pcall(luaState, Size, 1, 0);
|
||||
if (CheckLua(luaState, R)) {
|
||||
if (lua_isnumber(luaState, -1)) {
|
||||
return int(lua_tointeger(luaState, -1));
|
||||
} else if (lua_isstring(luaState, -1)) {
|
||||
return std::string(lua_tostring(luaState, -1));
|
||||
}
|
||||
}
|
||||
}
|
||||
ClearStack(luaState);
|
||||
return 0;
|
||||
}
|
||||
void Lua::SetPluginName(const std::string& Name) {
|
||||
_PluginName = Name;
|
||||
}
|
||||
void Lua::SetFileName(const std::string& Name) {
|
||||
_FileName = Name;
|
||||
}
|
||||
int lua_TempFix(lua_State* L) {
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int ID = int(lua_tonumber(L, 1));
|
||||
Client* c = GetClient(ID);
|
||||
if (c == nullptr)
|
||||
return 0;
|
||||
std::string Ret;
|
||||
if (c->isGuest) {
|
||||
Ret = "Guest-" + c->GetName();
|
||||
} else
|
||||
Ret = c->GetName();
|
||||
lua_pushstring(L, Ret.c_str());
|
||||
} else
|
||||
SendError(L, "GetDID not enough arguments");
|
||||
return 1;
|
||||
}
|
||||
void Lua::Init() {
|
||||
Assert(luaState);
|
||||
luaL_openlibs(luaState);
|
||||
lua_register(luaState, "TriggerGlobalEvent", lua_TriggerEventG);
|
||||
lua_register(luaState, "TriggerLocalEvent", lua_TriggerEventL);
|
||||
lua_register(luaState, "TriggerClientEvent", lua_RemoteEvent);
|
||||
lua_register(luaState, "GetPlayerCount", lua_GetPlayerCount);
|
||||
lua_register(luaState, "isPlayerConnected", lua_isConnected);
|
||||
lua_register(luaState, "RegisterEvent", lua_RegisterEvent);
|
||||
lua_register(luaState, "GetPlayerName", lua_GetPlayerName);
|
||||
lua_register(luaState, "RemoveVehicle", lua_RemoveVehicle);
|
||||
lua_register(luaState, "GetPlayerDiscordID", lua_TempFix);
|
||||
lua_register(luaState, "CreateThread", lua_CreateThread);
|
||||
lua_register(luaState, "GetPlayerVehicles", lua_GetCars);
|
||||
lua_register(luaState, "SendChatMessage", lua_sendChat);
|
||||
lua_register(luaState, "GetPlayers", lua_GetAllPlayers);
|
||||
lua_register(luaState, "GetPlayerGuest", lua_GetGuest);
|
||||
lua_register(luaState, "StopThread", lua_StopThread);
|
||||
lua_register(luaState, "DropPlayer", lua_dropPlayer);
|
||||
lua_register(luaState, "GetPlayerHWID", lua_HWID);
|
||||
lua_register(luaState, "exit", lua_ServerExit);
|
||||
lua_register(luaState, "Sleep", lua_Sleep);
|
||||
lua_register(luaState, "print", lua_Print);
|
||||
lua_register(luaState, "Set", lua_Set);
|
||||
if (!_Console)
|
||||
Reload();
|
||||
}
|
||||
|
||||
void Lua::RegisterEvent(const std::string& Event, const std::string& FunctionName) {
|
||||
_RegisteredEvents.insert(std::make_pair(Event, FunctionName));
|
||||
}
|
||||
void Lua::UnRegisterEvent(const std::string& Event) {
|
||||
for (const std::pair<std::string, std::string>& a : _RegisteredEvents) {
|
||||
if (a.first == Event) {
|
||||
_RegisteredEvents.erase(a);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
bool Lua::IsRegistered(const std::string& Event) {
|
||||
for (const std::pair<std::string, std::string>& a : _RegisteredEvents) {
|
||||
if (a.first == Event)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
std::string Lua::GetRegistered(const std::string& Event) const {
|
||||
for (const std::pair<std::string, std::string>& a : _RegisteredEvents) {
|
||||
if (a.first == Event)
|
||||
return a.second;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
std::string Lua::GetFileName() const {
|
||||
return _FileName;
|
||||
}
|
||||
std::string Lua::GetPluginName() const {
|
||||
return _PluginName;
|
||||
}
|
||||
lua_State* Lua::GetState() {
|
||||
return luaState;
|
||||
}
|
||||
|
||||
const lua_State* Lua::GetState() const {
|
||||
return luaState;
|
||||
}
|
||||
|
||||
void Lua::SetLastWrite(fs::file_time_type time) {
|
||||
_LastWrote = time;
|
||||
}
|
||||
fs::file_time_type Lua::GetLastWrite() {
|
||||
return _LastWrote;
|
||||
}
|
||||
|
||||
Lua::~Lua() {
|
||||
info("closing lua state");
|
||||
lua_close(luaState);
|
||||
}
|
||||
671
src/LuaAPI.cpp
Normal file
671
src/LuaAPI.cpp
Normal file
@@ -0,0 +1,671 @@
|
||||
#include "LuaAPI.h"
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "TLuaEngine.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#define SOL_ALL_SAFETIES_ON 1
|
||||
#include <sol/sol.hpp>
|
||||
|
||||
std::string LuaAPI::LuaToString(const sol::object Value, size_t Indent, bool QuoteStrings) {
|
||||
if (Indent > 80) {
|
||||
return "[[possible recursion, refusing to keep printing]]";
|
||||
}
|
||||
switch (Value.get_type()) {
|
||||
case sol::type::userdata: {
|
||||
std::stringstream ss;
|
||||
ss << "[[userdata: " << Value.as<sol::userdata>().pointer() << "]]";
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::thread: {
|
||||
std::stringstream ss;
|
||||
ss << "[[thread: " << Value.as<sol::thread>().pointer() << "]] {"
|
||||
<< "\n";
|
||||
for (size_t i = 0; i < Indent; ++i) {
|
||||
ss << "\t";
|
||||
}
|
||||
ss << "status: " << std::to_string(int(Value.as<sol::thread>().status())) << "\n}";
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::lightuserdata: {
|
||||
std::stringstream ss;
|
||||
ss << "[[lightuserdata: " << Value.as<sol::lightuserdata>().pointer() << "]]";
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::string:
|
||||
if (QuoteStrings) {
|
||||
return "\"" + Value.as<std::string>() + "\"";
|
||||
} else {
|
||||
return Value.as<std::string>();
|
||||
}
|
||||
case sol::type::number: {
|
||||
std::stringstream ss;
|
||||
ss << Value.as<float>();
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::lua_nil:
|
||||
case sol::type::none:
|
||||
return "<nil>";
|
||||
case sol::type::boolean:
|
||||
return Value.as<bool>() ? "true" : "false";
|
||||
case sol::type::table: {
|
||||
std::stringstream Result;
|
||||
auto Table = Value.as<sol::table>();
|
||||
Result << "[[table: " << Table.pointer() << "]]: {";
|
||||
if (!Table.empty()) {
|
||||
for (const auto& Entry : Table) {
|
||||
Result << "\n";
|
||||
for (size_t i = 0; i < Indent; ++i) {
|
||||
Result << "\t";
|
||||
}
|
||||
Result << LuaToString(Entry.first, Indent + 1) << ": " << LuaToString(Entry.second, Indent + 1, true) << ",";
|
||||
}
|
||||
Result << "\n";
|
||||
}
|
||||
for (size_t i = 0; i < Indent - 1; ++i) {
|
||||
Result << "\t";
|
||||
}
|
||||
Result << "}";
|
||||
return Result.str();
|
||||
}
|
||||
case sol::type::function: {
|
||||
std::stringstream ss;
|
||||
ss << "[[function: " << Value.as<sol::function>().pointer() << "]]";
|
||||
return ss.str();
|
||||
}
|
||||
default:
|
||||
return "((unprintable type))";
|
||||
}
|
||||
}
|
||||
|
||||
std::string LuaAPI::MP::GetOSName() {
|
||||
#if WIN32
|
||||
return "Windows";
|
||||
#elif __linux
|
||||
return "Linux";
|
||||
#else
|
||||
return "Other";
|
||||
#endif
|
||||
}
|
||||
|
||||
std::tuple<int, int, int> LuaAPI::MP::GetServerVersion() {
|
||||
return { Application::ServerVersion().major, Application::ServerVersion().minor, Application::ServerVersion().patch };
|
||||
}
|
||||
|
||||
void LuaAPI::Print(sol::variadic_args Args) {
|
||||
std::string ToPrint = "";
|
||||
for (const auto& Arg : Args) {
|
||||
ToPrint += LuaToString(static_cast<const sol::object>(Arg));
|
||||
ToPrint += "\t";
|
||||
}
|
||||
luaprint(ToPrint);
|
||||
}
|
||||
|
||||
TEST_CASE("LuaAPI::MP::GetServerVersion") {
|
||||
const auto [ma, mi, pa] = LuaAPI::MP::GetServerVersion();
|
||||
const auto real = Application::ServerVersion();
|
||||
CHECK(ma == real.major);
|
||||
CHECK(mi == real.minor);
|
||||
CHECK(pa == real.patch);
|
||||
}
|
||||
|
||||
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
||||
std::string Packet = "E:" + EventName + ":" + Data;
|
||||
if (PlayerID == -1) {
|
||||
LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true);
|
||||
return {true, ""};
|
||||
} else {
|
||||
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
||||
return {false, "Invalid Player ID"};
|
||||
}
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!LuaAPI::MP::Engine->Network().Respond(*c, Packet, true)) {
|
||||
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
||||
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
||||
return {false, "Respond failed, dropping client"};
|
||||
|
||||
}
|
||||
return {true, ""};
|
||||
}
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
||||
std::string Data = DataObj.as<std::string>();
|
||||
return InternalTriggerClientEvent(PlayerID, EventName, Data);
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
||||
return {false, "Player does not exist"};
|
||||
}
|
||||
auto c = MaybeClient.value().lock();
|
||||
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
||||
return {true, ""};
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
||||
std::pair<bool, std::string> Result;
|
||||
std::string Packet = "C:Server: " + Message;
|
||||
if (ID == -1) {
|
||||
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
||||
Engine->Network().SendToAll(nullptr, Packet, true, true);
|
||||
Result.first = true;
|
||||
} else {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!c->IsSynced()) {
|
||||
Result.first = false;
|
||||
Result.second = "Player still syncing data";
|
||||
return Result;
|
||||
}
|
||||
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
||||
Engine->Network().Respond(*c, Packet, true);
|
||||
Result.first = true;
|
||||
} else {
|
||||
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
||||
std::pair<bool, std::string> Result;
|
||||
auto MaybeClient = GetClient(Engine->Server(), PID);
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
beammp_lua_error("RemoveVehicle invalid Player ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
return Result;
|
||||
}
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!c->GetCarData(VID).empty()) {
|
||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||
Engine->Network().SendToAll(nullptr, Destroy, true, true);
|
||||
c->DeleteCar(VID);
|
||||
Result.first = true;
|
||||
} else {
|
||||
Result.first = false;
|
||||
Result.second = "Vehicle does not exist";
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
switch (ConfigID) {
|
||||
case 0: // debug
|
||||
if (NewValue.is<bool>()) {
|
||||
Application::Settings.DebugModeEnabled = NewValue.as<bool>();
|
||||
beammp_info(std::string("Set `Debug` to ") + (Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||
}
|
||||
break;
|
||||
case 1: // private
|
||||
if (NewValue.is<bool>()) {
|
||||
Application::Settings.Private = NewValue.as<bool>();
|
||||
beammp_info(std::string("Set `Private` to ") + (Application::Settings.Private ? "true" : "false"));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||
}
|
||||
break;
|
||||
case 2: // max cars
|
||||
if (NewValue.is<int>()) {
|
||||
Application::Settings.MaxCars = NewValue.as<int>();
|
||||
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::Settings.MaxCars));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected integer");
|
||||
}
|
||||
break;
|
||||
case 3: // max players
|
||||
if (NewValue.is<int>()) {
|
||||
Application::Settings.MaxPlayers = NewValue.as<int>();
|
||||
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::Settings.MaxPlayers));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected integer");
|
||||
}
|
||||
break;
|
||||
case 4: // Map
|
||||
if (NewValue.is<std::string>()) {
|
||||
Application::Settings.MapName = NewValue.as<std::string>();
|
||||
beammp_info(std::string("Set `Map` to ") + Application::Settings.MapName);
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected string");
|
||||
}
|
||||
break;
|
||||
case 5: // Name
|
||||
if (NewValue.is<std::string>()) {
|
||||
Application::Settings.ServerName = NewValue.as<std::string>();
|
||||
beammp_info(std::string("Set `Name` to ") + Application::Settings.ServerName);
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected string");
|
||||
}
|
||||
break;
|
||||
case 6: // Desc
|
||||
if (NewValue.is<std::string>()) {
|
||||
Application::Settings.ServerDesc = NewValue.as<std::string>();
|
||||
beammp_info(std::string("Set `Description` to ") + Application::Settings.ServerDesc);
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected string");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
beammp_warn("Invalid config ID \"" + std::to_string(ConfigID) + "\". Use `MP.Settings.*` enum for this.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void LuaAPI::MP::Sleep(size_t Ms) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(Ms));
|
||||
}
|
||||
|
||||
bool LuaAPI::MP::IsPlayerConnected(int ID) {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
return MaybeClient.value().lock()->IsConnected();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool LuaAPI::MP::IsPlayerGuest(int ID) {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
return MaybeClient.value().lock()->IsGuest();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
|
||||
std::string ToPrint = "";
|
||||
for (const auto& Arg : Args) {
|
||||
ToPrint += LuaToString(static_cast<const sol::object>(Arg));
|
||||
ToPrint += "\t";
|
||||
}
|
||||
#ifdef DOCTEST_CONFIG_DISABLE
|
||||
Application::Console().WriteRaw(ToPrint);
|
||||
#endif
|
||||
}
|
||||
|
||||
int LuaAPI::PanicHandler(lua_State* State) {
|
||||
beammp_lua_error("PANIC: " + sol::stack::get<std::string>(State, 1));
|
||||
return 0;
|
||||
}
|
||||
|
||||
template <typename FnT, typename... ArgsT>
|
||||
static std::pair<bool, std::string> FSWrapper(FnT Fn, ArgsT&&... Args) {
|
||||
std::error_code errc;
|
||||
std::pair<bool, std::string> Result;
|
||||
Fn(std::forward<ArgsT>(Args)..., errc);
|
||||
Result.first = errc == std::error_code {};
|
||||
if (!Result.first) {
|
||||
Result.second = errc.message();
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::FS::CreateDirectory(const std::string& Path) {
|
||||
std::error_code errc;
|
||||
std::pair<bool, std::string> Result;
|
||||
fs::create_directories(Path, errc);
|
||||
Result.first = errc == std::error_code {};
|
||||
if (!Result.first) {
|
||||
Result.second = errc.message();
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
TEST_CASE("LuaAPI::FS::CreateDirectory") {
|
||||
std::string TestDir = "beammp_test_dir";
|
||||
fs::remove_all(TestDir);
|
||||
SUBCASE("Single level dir") {
|
||||
const auto [Ok, Err] = LuaAPI::FS::CreateDirectory(TestDir);
|
||||
CHECK(Ok);
|
||||
CHECK(Err == "");
|
||||
CHECK(fs::exists(TestDir));
|
||||
}
|
||||
SUBCASE("Multi level dir") {
|
||||
const auto [Ok, Err] = LuaAPI::FS::CreateDirectory(TestDir + "/a/b/c");
|
||||
CHECK(Ok);
|
||||
CHECK(Err == "");
|
||||
CHECK(fs::exists(TestDir + "/a/b/c"));
|
||||
}
|
||||
SUBCASE("Already exists") {
|
||||
const auto [Ok, Err] = LuaAPI::FS::CreateDirectory(TestDir);
|
||||
CHECK(Ok);
|
||||
CHECK(Err == "");
|
||||
CHECK(fs::exists(TestDir));
|
||||
const auto [Ok2, Err2] = LuaAPI::FS::CreateDirectory(TestDir);
|
||||
CHECK(Ok2);
|
||||
CHECK(Err2 == "");
|
||||
}
|
||||
fs::remove_all(TestDir);
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::FS::Remove(const std::string& Path) {
|
||||
std::error_code errc;
|
||||
std::pair<bool, std::string> Result;
|
||||
fs::remove(fs::relative(Path), errc);
|
||||
Result.first = errc == std::error_code {};
|
||||
if (!Result.first) {
|
||||
Result.second = errc.message();
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
TEST_CASE("LuaAPI::FS::Remove") {
|
||||
const std::string TestFileOrDir = "beammp_test_thing";
|
||||
SUBCASE("Remove existing directory") {
|
||||
fs::create_directory(TestFileOrDir);
|
||||
const auto [Ok, Err] = LuaAPI::FS::Remove(TestFileOrDir);
|
||||
CHECK(Ok);
|
||||
CHECK_EQ(Err, "");
|
||||
CHECK(!fs::exists(TestFileOrDir));
|
||||
}
|
||||
SUBCASE("Remove non-existing directory") {
|
||||
fs::remove_all(TestFileOrDir);
|
||||
const auto [Ok, Err] = LuaAPI::FS::Remove(TestFileOrDir);
|
||||
CHECK(Ok);
|
||||
CHECK_EQ(Err, "");
|
||||
CHECK(!fs::exists(TestFileOrDir));
|
||||
}
|
||||
// TODO: add tests for files
|
||||
// TODO: add tests for files and folders without access permissions (failure)
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::FS::Rename(const std::string& Path, const std::string& NewPath) {
|
||||
std::error_code errc;
|
||||
std::pair<bool, std::string> Result;
|
||||
fs::rename(Path, NewPath, errc);
|
||||
Result.first = errc == std::error_code {};
|
||||
if (!Result.first) {
|
||||
Result.second = errc.message();
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
TEST_CASE("LuaAPI::FS::Rename") {
|
||||
const auto TestDir = "beammp_test_dir";
|
||||
const auto OtherTestDir = "beammp_test_dir_2";
|
||||
fs::remove_all(OtherTestDir);
|
||||
fs::create_directory(TestDir);
|
||||
const auto [Ok, Err] = LuaAPI::FS::Rename(TestDir, OtherTestDir);
|
||||
CHECK(Ok);
|
||||
CHECK_EQ(Err, "");
|
||||
CHECK(!fs::exists(TestDir));
|
||||
CHECK(fs::exists(OtherTestDir));
|
||||
|
||||
fs::remove_all(OtherTestDir);
|
||||
fs::remove_all(TestDir);
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::FS::Copy(const std::string& Path, const std::string& NewPath) {
|
||||
std::error_code errc;
|
||||
std::pair<bool, std::string> Result;
|
||||
fs::copy(Path, NewPath, fs::copy_options::recursive, errc);
|
||||
Result.first = errc == std::error_code {};
|
||||
if (!Result.first) {
|
||||
Result.second = errc.message();
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
TEST_CASE("LuaAPI::FS::Copy") {
|
||||
const auto TestDir = "beammp_test_dir";
|
||||
const auto OtherTestDir = "beammp_test_dir_2";
|
||||
fs::remove_all(OtherTestDir);
|
||||
fs::create_directory(TestDir);
|
||||
const auto [Ok, Err] = LuaAPI::FS::Copy(TestDir, OtherTestDir);
|
||||
CHECK(Ok);
|
||||
CHECK_EQ(Err, "");
|
||||
CHECK(fs::exists(TestDir));
|
||||
CHECK(fs::exists(OtherTestDir));
|
||||
|
||||
fs::remove_all(OtherTestDir);
|
||||
fs::remove_all(TestDir);
|
||||
}
|
||||
|
||||
bool LuaAPI::FS::Exists(const std::string& Path) {
|
||||
return fs::exists(Path);
|
||||
}
|
||||
|
||||
TEST_CASE("LuaAPI::FS::Exists") {
|
||||
const auto TestDir = "beammp_test_dir";
|
||||
const auto OtherTestDir = "beammp_test_dir_2";
|
||||
fs::remove_all(OtherTestDir);
|
||||
fs::create_directory(TestDir);
|
||||
|
||||
CHECK(LuaAPI::FS::Exists(TestDir));
|
||||
CHECK(!LuaAPI::FS::Exists(OtherTestDir));
|
||||
|
||||
fs::remove_all(OtherTestDir);
|
||||
fs::remove_all(TestDir);
|
||||
}
|
||||
|
||||
std::string LuaAPI::FS::GetFilename(const std::string& Path) {
|
||||
return fs::path(Path).filename().string();
|
||||
}
|
||||
|
||||
TEST_CASE("LuaAPI::FS::GetFilename") {
|
||||
CHECK(LuaAPI::FS::GetFilename("test.txt") == "test.txt");
|
||||
CHECK(LuaAPI::FS::GetFilename("/test.txt") == "test.txt");
|
||||
CHECK(LuaAPI::FS::GetFilename("place/test.txt") == "test.txt");
|
||||
CHECK(LuaAPI::FS::GetFilename("/some/../place/test.txt") == "test.txt");
|
||||
}
|
||||
|
||||
std::string LuaAPI::FS::GetExtension(const std::string& Path) {
|
||||
return fs::path(Path).extension().string();
|
||||
}
|
||||
|
||||
TEST_CASE("LuaAPI::FS::GetExtension") {
|
||||
CHECK(LuaAPI::FS::GetExtension("test.txt") == ".txt");
|
||||
CHECK(LuaAPI::FS::GetExtension("/test.txt") == ".txt");
|
||||
CHECK(LuaAPI::FS::GetExtension("place/test.txt") == ".txt");
|
||||
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.txt") == ".txt");
|
||||
CHECK(LuaAPI::FS::GetExtension("/some/../place/test") == "");
|
||||
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.a.b.c") == ".c");
|
||||
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.") == ".");
|
||||
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.a.b.") == ".");
|
||||
}
|
||||
|
||||
std::string LuaAPI::FS::GetParentFolder(const std::string& Path) {
|
||||
return fs::path(Path).parent_path().string();
|
||||
}
|
||||
|
||||
TEST_CASE("LuaAPI::FS::GetParentFolder") {
|
||||
CHECK(LuaAPI::FS::GetParentFolder("test.txt") == "");
|
||||
CHECK(LuaAPI::FS::GetParentFolder("/test.txt") == "/");
|
||||
CHECK(LuaAPI::FS::GetParentFolder("place/test.txt") == "place");
|
||||
CHECK(LuaAPI::FS::GetParentFolder("/some/../place/test.txt") == "/some/../place");
|
||||
}
|
||||
|
||||
// TODO: add tests
|
||||
bool LuaAPI::FS::IsDirectory(const std::string& Path) {
|
||||
return fs::is_directory(Path);
|
||||
}
|
||||
|
||||
// TODO: add tests
|
||||
bool LuaAPI::FS::IsFile(const std::string& Path) {
|
||||
return fs::is_regular_file(Path);
|
||||
}
|
||||
|
||||
// TODO: add tests
|
||||
std::string LuaAPI::FS::ConcatPaths(sol::variadic_args Args) {
|
||||
fs::path Path;
|
||||
for (size_t i = 0; i < Args.size(); ++i) {
|
||||
auto Obj = Args[i];
|
||||
if (!Obj.is<std::string>()) {
|
||||
beammp_lua_error("FS.Concat called with non-string argument");
|
||||
return "";
|
||||
}
|
||||
Path += Obj.as<std::string>();
|
||||
if (i < Args.size() - 1 && !Path.empty()) {
|
||||
Path += fs::path::preferred_separator;
|
||||
}
|
||||
}
|
||||
auto Result = Path.lexically_normal().string();
|
||||
return Result;
|
||||
}
|
||||
|
||||
static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, const sol::object& right, bool is_array, size_t depth = 0) {
|
||||
if (depth > 100) {
|
||||
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
|
||||
return;
|
||||
}
|
||||
std::string key;
|
||||
switch (left.get_type()) {
|
||||
case sol::type::lua_nil:
|
||||
case sol::type::none:
|
||||
case sol::type::poly:
|
||||
case sol::type::boolean:
|
||||
case sol::type::lightuserdata:
|
||||
case sol::type::userdata:
|
||||
case sol::type::thread:
|
||||
case sol::type::function:
|
||||
case sol::type::table:
|
||||
beammp_lua_error("JsonEncode: left side of table field is unexpected type");
|
||||
return;
|
||||
case sol::type::string:
|
||||
key = left.as<std::string>();
|
||||
break;
|
||||
case sol::type::number:
|
||||
key = std::to_string(left.as<double>());
|
||||
break;
|
||||
}
|
||||
nlohmann::json value;
|
||||
switch (right.get_type()) {
|
||||
case sol::type::lua_nil:
|
||||
case sol::type::none:
|
||||
return;
|
||||
case sol::type::poly:
|
||||
beammp_lua_warn("unsure what to do with poly type in JsonEncode, ignoring");
|
||||
return;
|
||||
case sol::type::boolean:
|
||||
value = right.as<bool>();
|
||||
break;
|
||||
case sol::type::lightuserdata:
|
||||
beammp_lua_warn("unsure what to do with lightuserdata in JsonEncode, ignoring");
|
||||
return;
|
||||
case sol::type::userdata:
|
||||
beammp_lua_warn("unsure what to do with userdata in JsonEncode, ignoring");
|
||||
return;
|
||||
case sol::type::thread:
|
||||
beammp_lua_warn("unsure what to do with thread in JsonEncode, ignoring");
|
||||
return;
|
||||
case sol::type::string:
|
||||
value = right.as<std::string>();
|
||||
break;
|
||||
case sol::type::number:
|
||||
value = right.as<double>();
|
||||
break;
|
||||
case sol::type::function:
|
||||
beammp_lua_warn("unsure what to do with function in JsonEncode, ignoring");
|
||||
return;
|
||||
case sol::type::table: {
|
||||
bool local_is_array = true;
|
||||
for (const auto& pair : right.as<sol::table>()) {
|
||||
if (pair.first.get_type() != sol::type::number) {
|
||||
local_is_array = false;
|
||||
}
|
||||
}
|
||||
for (const auto& pair : right.as<sol::table>()) {
|
||||
JsonEncodeRecursive(value, pair.first, pair.second, local_is_array, depth + 1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (is_array) {
|
||||
json.push_back(value);
|
||||
} else {
|
||||
json[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
std::string LuaAPI::MP::JsonEncode(const sol::table& object) {
|
||||
nlohmann::json json;
|
||||
// table
|
||||
bool is_array = true;
|
||||
for (const auto& pair : object.as<sol::table>()) {
|
||||
if (pair.first.get_type() != sol::type::number) {
|
||||
is_array = false;
|
||||
}
|
||||
}
|
||||
for (const auto& entry : object) {
|
||||
JsonEncodeRecursive(json, entry.first, entry.second, is_array);
|
||||
}
|
||||
return json.dump();
|
||||
}
|
||||
|
||||
std::string LuaAPI::MP::JsonDiff(const std::string& a, const std::string& b) {
|
||||
if (!nlohmann::json::accept(a)) {
|
||||
beammp_lua_error("JsonDiff first argument is not valid json: `" + a + "`");
|
||||
return "";
|
||||
}
|
||||
if (!nlohmann::json::accept(b)) {
|
||||
beammp_lua_error("JsonDiff second argument is not valid json: `" + b + "`");
|
||||
return "";
|
||||
}
|
||||
auto a_json = nlohmann::json::parse(a);
|
||||
auto b_json = nlohmann::json::parse(b);
|
||||
return nlohmann::json::diff(a_json, b_json).dump();
|
||||
}
|
||||
|
||||
std::string LuaAPI::MP::JsonDiffApply(const std::string& data, const std::string& patch) {
|
||||
if (!nlohmann::json::accept(data)) {
|
||||
beammp_lua_error("JsonDiffApply first argument is not valid json: `" + data + "`");
|
||||
return "";
|
||||
}
|
||||
if (!nlohmann::json::accept(patch)) {
|
||||
beammp_lua_error("JsonDiffApply second argument is not valid json: `" + patch + "`");
|
||||
return "";
|
||||
}
|
||||
auto a_json = nlohmann::json::parse(data);
|
||||
auto b_json = nlohmann::json::parse(patch);
|
||||
a_json.patch(b_json);
|
||||
return a_json.dump();
|
||||
}
|
||||
|
||||
std::string LuaAPI::MP::JsonPrettify(const std::string& json) {
|
||||
if (!nlohmann::json::accept(json)) {
|
||||
beammp_lua_error("JsonPrettify argument is not valid json: `" + json + "`");
|
||||
return "";
|
||||
}
|
||||
return nlohmann::json::parse(json).dump(4);
|
||||
}
|
||||
|
||||
std::string LuaAPI::MP::JsonMinify(const std::string& json) {
|
||||
if (!nlohmann::json::accept(json)) {
|
||||
beammp_lua_error("JsonMinify argument is not valid json: `" + json + "`");
|
||||
return "";
|
||||
}
|
||||
return nlohmann::json::parse(json).dump(-1);
|
||||
}
|
||||
|
||||
std::string LuaAPI::MP::JsonFlatten(const std::string& json) {
|
||||
if (!nlohmann::json::accept(json)) {
|
||||
beammp_lua_error("JsonFlatten argument is not valid json: `" + json + "`");
|
||||
return "";
|
||||
}
|
||||
return nlohmann::json::parse(json).flatten().dump(-1);
|
||||
}
|
||||
|
||||
std::string LuaAPI::MP::JsonUnflatten(const std::string& json) {
|
||||
if (!nlohmann::json::accept(json)) {
|
||||
beammp_lua_error("JsonUnflatten argument is not valid json: `" + json + "`");
|
||||
return "";
|
||||
}
|
||||
return nlohmann::json::parse(json).unflatten().dump(-1);
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
|
||||
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/31/2020
|
||||
///
|
||||
|
||||
#include "Curl/Http.h"
|
||||
#include "Json.h"
|
||||
#include "Logger.h"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <Lua/LuaSystem.hpp>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
std::string GetClientInfo(const std::string& PK) {
|
||||
if (!PK.empty()) {
|
||||
return PostHTTP("https://auth.beammp.com/pkToUser", R"({"key":")" + PK + "\"}", true);
|
||||
;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
Client* CreateClient(SOCKET TCPSock) {
|
||||
auto* c = new Client;
|
||||
c->SetTCPSock(TCPSock);
|
||||
return c;
|
||||
}
|
||||
|
||||
void ClientKick(Client* c, const std::string& R) {
|
||||
info("Client kicked: " + R);
|
||||
TCPSend(c, "E" + R);
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
}
|
||||
|
||||
void Authentication(SOCKET TCPSock) {
|
||||
DebugPrintTID();
|
||||
auto* c = CreateClient(TCPSock);
|
||||
|
||||
info("Identifying new client...");
|
||||
std::string Rc = TCPRcv(c);
|
||||
|
||||
if (Rc.size() > 3 && Rc.substr(0, 2) == "VC") {
|
||||
Rc = Rc.substr(2);
|
||||
if (Rc.length() > 4 || Rc != GetCVer()) {
|
||||
ClientKick(c, "Outdated Version!");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
ClientKick(c, "Invalid version header!");
|
||||
return;
|
||||
}
|
||||
TCPSend(c, "S");
|
||||
|
||||
Rc = TCPRcv(c);
|
||||
|
||||
if (Rc.size() > 50) {
|
||||
ClientKick(c, "Invalid Key!");
|
||||
return;
|
||||
}
|
||||
|
||||
Rc = GetClientInfo(Rc);
|
||||
json::Document d;
|
||||
d.Parse(Rc.c_str());
|
||||
if (Rc == "-1" || d.HasParseError()) {
|
||||
ClientKick(c, "Invalid key! Please restart your game.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (d["username"].IsString() && d["roles"].IsString() && d["guest"].IsBool()) {
|
||||
c->SetName(d["username"].GetString());
|
||||
c->SetRoles(d["roles"].GetString());
|
||||
c->isGuest = d["guest"].GetBool();
|
||||
} else {
|
||||
ClientKick(c, "Invalid authentication data!");
|
||||
return;
|
||||
}
|
||||
|
||||
debug("Name -> " + c->GetName() + ", Guest -> " + std::to_string(c->isGuest) + ", Roles -> " + c->GetRoles());
|
||||
for (auto& Cl : CI->Clients) {
|
||||
if (Cl != nullptr) {
|
||||
if (Cl->GetName() == c->GetName() && Cl->isGuest == c->isGuest) {
|
||||
info("Old client (" + Cl->GetName() + ") kicked: Reconnecting");
|
||||
CloseSocketProper(Cl->GetTCPSock());
|
||||
Cl->SetStatus(-2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto arg = std::make_unique<LuaArg>(LuaArg { { c->GetName(), c->GetRoles(), c->isGuest } });
|
||||
std::any Res = TriggerLuaEvent("onPlayerAuth", false, nullptr, std::move(arg), true);
|
||||
std::string Type = Res.type().name();
|
||||
if (Type.find("int") != std::string::npos && std::any_cast<int>(Res)) {
|
||||
ClientKick(c, "you are not allowed on the server!");
|
||||
return;
|
||||
} else if (Type.find("string") != std::string::npos) {
|
||||
ClientKick(c, std::any_cast<std::string>(Res));
|
||||
return;
|
||||
}
|
||||
if (CI->Size() < MaxPlayers) {
|
||||
info("Identification success");
|
||||
Client& Client = *c;
|
||||
CI->AddClient(std::move(c));
|
||||
TCPClient(&Client);
|
||||
} else
|
||||
ClientKick(c, "Server full!");
|
||||
}
|
||||
|
||||
void HandleDownload(SOCKET TCPSock) {
|
||||
char D;
|
||||
if (recv(TCPSock, &D, 1, 0) != 1) {
|
||||
CloseSocketProper(TCPSock);
|
||||
return;
|
||||
}
|
||||
auto ID = uint8_t(D);
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c->GetID() == ID) {
|
||||
c->SetDownSock(TCPSock);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Identify(SOCKET TCPSock) {
|
||||
char Code;
|
||||
if (recv(TCPSock, &Code, 1, 0) != 1) {
|
||||
CloseSocketProper(TCPSock);
|
||||
return;
|
||||
}
|
||||
if (Code == 'C') {
|
||||
Authentication(TCPSock);
|
||||
} else if (Code == 'D') {
|
||||
HandleDownload(TCPSock);
|
||||
} else
|
||||
CloseSocketProper(TCPSock);
|
||||
}
|
||||
|
||||
void TCPServerMain() {
|
||||
DebugPrintTID();
|
||||
#ifdef WIN32
|
||||
WSADATA wsaData;
|
||||
if (WSAStartup(514, &wsaData)) {
|
||||
error("Can't start Winsock!");
|
||||
return;
|
||||
}
|
||||
SOCKET client, Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
sockaddr_in addr {};
|
||||
addr.sin_addr.S_un.S_addr = ADDR_ANY;
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(Port);
|
||||
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
|
||||
error("Can't bind socket! " + std::to_string(WSAGetLastError()));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
_Exit(-1);
|
||||
}
|
||||
if (Listener == -1) {
|
||||
error("Invalid listening socket");
|
||||
return;
|
||||
}
|
||||
if (listen(Listener, SOMAXCONN)) {
|
||||
error("listener failed " + std::to_string(GetLastError()));
|
||||
return;
|
||||
}
|
||||
info("Vehicle event network online");
|
||||
do {
|
||||
try {
|
||||
client = accept(Listener, nullptr, nullptr);
|
||||
if (client == -1) {
|
||||
warn("Got an invalid client socket on connect! Skipping...");
|
||||
continue;
|
||||
}
|
||||
std::thread ID(Identify, client);
|
||||
ID.detach();
|
||||
} catch (const std::exception& e) {
|
||||
error("fatal: " + std::string(e.what()));
|
||||
}
|
||||
} while (client);
|
||||
|
||||
CloseSocketProper(client);
|
||||
WSACleanup();
|
||||
#else // unix
|
||||
// wondering why we need slightly different implementations of this?
|
||||
// ask ms.
|
||||
SOCKET client = -1, Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
int optval = 1;
|
||||
setsockopt(Listener, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
|
||||
// TODO: check optval or return value idk
|
||||
sockaddr_in addr {};
|
||||
addr.sin_addr.s_addr = INADDR_ANY;
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(uint16_t(Port));
|
||||
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) != 0) {
|
||||
error(("Can't bind socket! ") + std::string(strerror(errno)));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
_Exit(-1);
|
||||
}
|
||||
if (Listener == -1) {
|
||||
error(("Invalid listening socket"));
|
||||
return;
|
||||
}
|
||||
if (listen(Listener, SOMAXCONN)) {
|
||||
error(("listener failed ") + std::string(strerror(errno)));
|
||||
return;
|
||||
}
|
||||
info(("Vehicle event network online"));
|
||||
do {
|
||||
try {
|
||||
client = accept(Listener, nullptr, nullptr);
|
||||
if (client == -1) {
|
||||
warn(("Got an invalid client socket on connect! Skipping..."));
|
||||
continue;
|
||||
}
|
||||
std::thread ID(Identify, client);
|
||||
ID.detach();
|
||||
} catch (const std::exception& e) {
|
||||
error(("fatal: ") + std::string(e.what()));
|
||||
}
|
||||
} while (client);
|
||||
|
||||
debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(client);
|
||||
#endif // WIN32
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
|
||||
#include <memory>
|
||||
|
||||
void Client::DeleteCar(int ident) {
|
||||
for (auto& v : VehicleData) {
|
||||
if (v != nullptr && v->ID == ident) {
|
||||
VehicleData.erase(v);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
void Client::ClearCars() {
|
||||
VehicleData.clear();
|
||||
}
|
||||
int Client::GetOpenCarID() {
|
||||
int OpenID = 0;
|
||||
bool found;
|
||||
do {
|
||||
found = true;
|
||||
for (auto& v : VehicleData) {
|
||||
if (v != nullptr && v->ID == OpenID) {
|
||||
OpenID++;
|
||||
found = false;
|
||||
}
|
||||
}
|
||||
} while (!found);
|
||||
return OpenID;
|
||||
}
|
||||
void Client::AddNewCar(int ident, const std::string& Data) {
|
||||
VehicleData.insert(std::make_unique<VData>(VData { ident, Data }));
|
||||
}
|
||||
|
||||
std::set<std::unique_ptr<VData>>& Client::GetAllCars() {
|
||||
return VehicleData;
|
||||
}
|
||||
|
||||
std::string Client::GetCarData(int ident) {
|
||||
for (auto& v : VehicleData) {
|
||||
if (v != nullptr && v->ID == ident) {
|
||||
return v->Data;
|
||||
}
|
||||
}
|
||||
DeleteCar(ident);
|
||||
return "";
|
||||
}
|
||||
|
||||
void Client::SetCarData(int ident, const std::string& Data) {
|
||||
for (auto& v : VehicleData) {
|
||||
if (v != nullptr && v->ID == ident) {
|
||||
v->Data = Data;
|
||||
return;
|
||||
}
|
||||
}
|
||||
DeleteCar(ident);
|
||||
}
|
||||
int Client::GetCarCount() {
|
||||
return int(VehicleData.size());
|
||||
}
|
||||
@@ -1,268 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 8/1/2020
|
||||
///
|
||||
|
||||
#include "Client.hpp"
|
||||
#include "Logger.h"
|
||||
#include "Lua/LuaSystem.hpp"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#undef GetObject //to fix microsoft bs
|
||||
#include "Json.h"
|
||||
|
||||
void Apply(Client* c, int VID, const std::string& pckt) {
|
||||
Assert(c);
|
||||
std::string Packet = pckt.substr(pckt.find('{')), VD = c->GetCarData(VID);
|
||||
std::string Header = VD.substr(0, VD.find('{'));
|
||||
VD = VD.substr(VD.find('{'));
|
||||
rapidjson::Document Veh, Pack;
|
||||
Veh.Parse(VD.c_str());
|
||||
if (Veh.HasParseError()) {
|
||||
error("Could not get vehicle config!");
|
||||
return;
|
||||
}
|
||||
Pack.Parse(Packet.c_str());
|
||||
if (Pack.HasParseError() || Pack.IsNull()) {
|
||||
error("Could not get active vehicle config!");
|
||||
return;
|
||||
}
|
||||
|
||||
for (auto& M : Pack.GetObject()) {
|
||||
if (Veh[M.name].IsNull()) {
|
||||
Veh.AddMember(M.name, M.value, Veh.GetAllocator());
|
||||
} else {
|
||||
Veh[M.name] = Pack[M.name];
|
||||
}
|
||||
}
|
||||
rapidjson::StringBuffer Buffer;
|
||||
rapidjson::Writer<rapidjson::StringBuffer> writer(Buffer);
|
||||
Veh.Accept(writer);
|
||||
c->SetCarData(VID, Header + Buffer.GetString());
|
||||
}
|
||||
|
||||
void VehicleParser(Client* c, const std::string& Pckt) {
|
||||
Assert(c);
|
||||
if (c == nullptr || Pckt.length() < 4)
|
||||
return;
|
||||
std::string Packet = Pckt;
|
||||
char Code = Packet.at(1);
|
||||
int PID = -1;
|
||||
int VID = -1;
|
||||
std::string Data = Packet.substr(3), pid, vid;
|
||||
switch (Code) { //Spawned Destroyed Switched/Moved NotFound Reset
|
||||
case 's':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
#endif
|
||||
if (Data.at(0) == '0') {
|
||||
int CarID = c->GetOpenCarID();
|
||||
debug(c->GetName() + (" created a car with ID ") + std::to_string(CarID));
|
||||
Packet = "Os:" + c->GetRoles() + ":" + c->GetName() + ":" + std::to_string(c->GetID()) + "-" + std::to_string(CarID) + Packet.substr(4);
|
||||
auto Res = TriggerLuaEvent(("onVehicleSpawn"), false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID(), CarID, Packet.substr(3) } }), true);
|
||||
if (c->GetCarCount() >= MaxCars || std::any_cast<int>(Res)) {
|
||||
Respond(c, Packet, true);
|
||||
std::string Destroy = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(CarID);
|
||||
Respond(c, Destroy, true);
|
||||
debug(c->GetName() + (" (force : car limit/lua) removed ID ") + std::to_string(CarID));
|
||||
} else {
|
||||
c->AddNewCar(CarID, Packet);
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
}
|
||||
}
|
||||
return;
|
||||
case 'c':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
#endif
|
||||
pid = Data.substr(0, Data.find('-'));
|
||||
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
|
||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||
PID = stoi(pid);
|
||||
VID = stoi(vid);
|
||||
}
|
||||
if (PID != -1 && VID != -1 && PID == c->GetID()) {
|
||||
auto Res = TriggerLuaEvent(("onVehicleEdited"), false, nullptr,
|
||||
std::make_unique<LuaArg>(LuaArg { { c->GetID(), VID, Packet.substr(3) } }),
|
||||
true);
|
||||
if (!std::any_cast<int>(Res)) {
|
||||
SendToAll(c, Packet, false, true);
|
||||
Apply(c, VID, Packet);
|
||||
} else {
|
||||
std::string Destroy = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(VID);
|
||||
Respond(c, Destroy, true);
|
||||
c->DeleteCar(VID);
|
||||
}
|
||||
}
|
||||
return;
|
||||
case 'd':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
#endif
|
||||
pid = Data.substr(0, Data.find('-'));
|
||||
vid = Data.substr(Data.find('-') + 1);
|
||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||
PID = stoi(pid);
|
||||
VID = stoi(vid);
|
||||
}
|
||||
if (PID != -1 && VID != -1 && PID == c->GetID()) {
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
TriggerLuaEvent(("onVehicleDeleted"), false, nullptr,
|
||||
std::make_unique<LuaArg>(LuaArg { { c->GetID(), VID } }), false);
|
||||
c->DeleteCar(VID);
|
||||
debug(c->GetName() + (" deleted car with ID ") + std::to_string(VID));
|
||||
}
|
||||
return;
|
||||
case 'r':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
#endif
|
||||
SendToAll(c, Packet, false, true);
|
||||
return;
|
||||
case 't':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
#endif
|
||||
SendToAll(c, Packet, false, true);
|
||||
return;
|
||||
default:
|
||||
#ifdef DEBUG
|
||||
warn(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
||||
#endif // DEBUG
|
||||
return;
|
||||
}
|
||||
}
|
||||
void SyncClient(Client* c) {
|
||||
Assert(c);
|
||||
if (c->isSynced)
|
||||
return;
|
||||
c->isSynced = true;
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
Respond(c, ("Sn") + c->GetName(), true);
|
||||
SendToAll(c, ("JWelcome ") + c->GetName() + "!", false, true);
|
||||
TriggerLuaEvent(("onPlayerJoin"), false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID() } }), false);
|
||||
for (auto& client : CI->Clients) {
|
||||
if (client != nullptr) {
|
||||
if (client.get() != c) {
|
||||
for (auto& v : client->GetAllCars()) {
|
||||
if (v != nullptr) {
|
||||
if (c->GetStatus() < 0)
|
||||
return;
|
||||
Respond(c, v->Data, true);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
info(c->GetName() + (" is now synced!"));
|
||||
}
|
||||
void ParseVeh(Client* c, const std::string& Packet) {
|
||||
Assert(c);
|
||||
#ifdef WIN32
|
||||
__try {
|
||||
VehicleParser(c, Packet);
|
||||
} __except (Handle(GetExceptionInformation(), ("Vehicle Handler"))) { }
|
||||
#else // unix
|
||||
VehicleParser(c, Packet);
|
||||
#endif // WIN32
|
||||
}
|
||||
|
||||
void HandleEvent(Client* c, const std::string& Data) {
|
||||
Assert(c);
|
||||
std::stringstream ss(Data);
|
||||
std::string t, Name;
|
||||
int a = 0;
|
||||
while (std::getline(ss, t, ':')) {
|
||||
switch (a) {
|
||||
case 1:
|
||||
Name = t;
|
||||
break;
|
||||
case 2:
|
||||
TriggerLuaEvent(Name, false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID(), t } }), false);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (a == 2)
|
||||
break;
|
||||
a++;
|
||||
}
|
||||
}
|
||||
|
||||
void GlobalParser(Client* c, const std::string& Packet) {
|
||||
Assert(c);
|
||||
if (Packet.empty() || c == nullptr)
|
||||
return;
|
||||
std::any Res;
|
||||
char Code = Packet.at(0);
|
||||
|
||||
//V to Z
|
||||
if (Code <= 90 && Code >= 86) {
|
||||
PPS++;
|
||||
SendToAll(c, Packet, false, false);
|
||||
return;
|
||||
}
|
||||
switch (Code) {
|
||||
case 'H': // initial connection
|
||||
#ifdef DEBUG
|
||||
debug(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
|
||||
#endif
|
||||
SyncClient(c);
|
||||
return;
|
||||
case 'p':
|
||||
Respond(c, ("p"), false);
|
||||
UpdatePlayers();
|
||||
return;
|
||||
case 'O':
|
||||
if (Packet.length() > 1000) {
|
||||
debug(("Received data from: ") + c->GetName() + (" Size: ") + std::to_string(Packet.length()));
|
||||
}
|
||||
ParseVeh(c, Packet);
|
||||
return;
|
||||
case 'J':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
#endif
|
||||
SendToAll(c, Packet, false, true);
|
||||
return;
|
||||
case 'C':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
#endif
|
||||
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
|
||||
break;
|
||||
Res = TriggerLuaEvent("onChatMessage", false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID(), c->GetName(), Packet.substr(Packet.find(':', 3) + 1) } }), true);
|
||||
if (std::any_cast<int>(Res))
|
||||
break;
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
return;
|
||||
case 'E':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
#endif
|
||||
HandleEvent(c, Packet);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void GParser(Client* c, const std::string& Packet) {
|
||||
Assert(c);
|
||||
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
|
||||
abort();
|
||||
}
|
||||
#ifdef WIN32
|
||||
__try {
|
||||
GlobalParser(c, Packet);
|
||||
} __except (Handle(GetExceptionInformation(), ("Global Handler"))) { }
|
||||
#else
|
||||
GlobalParser(c, Packet);
|
||||
#endif // WIN32
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 4/9/2020
|
||||
///
|
||||
|
||||
#include "CustomAssert.h"
|
||||
#include <curl/curl.h>
|
||||
#include <iostream>
|
||||
|
||||
class CurlManager{
|
||||
public:
|
||||
CurlManager(){
|
||||
curl = curl_easy_init();
|
||||
}
|
||||
~CurlManager(){
|
||||
curl_easy_cleanup(curl);
|
||||
}
|
||||
inline CURL* Get(){
|
||||
return curl;
|
||||
}
|
||||
private:
|
||||
CURL *curl;
|
||||
};
|
||||
|
||||
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
|
||||
((std::string*)userp)->append((char*)contents, size * nmemb);
|
||||
return size * nmemb;
|
||||
}
|
||||
std::string HttpRequest(const std::string& IP, int port) {
|
||||
static thread_local CurlManager M;
|
||||
std::string readBuffer;
|
||||
CURL* curl = M.Get();
|
||||
CURLcode res;
|
||||
Assert(curl);
|
||||
if (curl) {
|
||||
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
|
||||
curl_easy_setopt(curl, CURLOPT_PORT, port);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
|
||||
res = curl_easy_perform(curl);
|
||||
if (res != CURLE_OK)
|
||||
return "-1";
|
||||
}
|
||||
return readBuffer;
|
||||
}
|
||||
|
||||
std::string PostHTTP(const std::string& IP, const std::string& Fields, bool json) {
|
||||
auto header = curl_slist { (char*)"Content-Type: application/json" };
|
||||
static thread_local CurlManager M;
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
CURL* curl = M.Get();
|
||||
CURLcode res;
|
||||
std::string readBuffer;
|
||||
|
||||
Assert(curl);
|
||||
if (curl) {
|
||||
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
|
||||
if (json)
|
||||
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
|
||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, Fields.size());
|
||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, Fields.c_str());
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
|
||||
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
|
||||
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);
|
||||
res = curl_easy_perform(curl);
|
||||
if (res != CURLE_OK)
|
||||
return "-1";
|
||||
}
|
||||
return readBuffer;
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 8/1/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
#include "Logger.h"
|
||||
#include "Lua/LuaSystem.hpp"
|
||||
#include "Network.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <memory>
|
||||
|
||||
int OpenID() {
|
||||
int ID = 0;
|
||||
bool found;
|
||||
do {
|
||||
found = true;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr) {
|
||||
if (c->GetID() == ID) {
|
||||
found = false;
|
||||
ID++;
|
||||
}
|
||||
}
|
||||
}
|
||||
} while (!found);
|
||||
return ID;
|
||||
}
|
||||
void Respond(Client* c, const std::string& MSG, bool Rel) {
|
||||
Assert(c);
|
||||
char C = MSG.at(0);
|
||||
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
|
||||
if (C == 'O' || C == 'T' || MSG.length() > 1000) {
|
||||
SendLarge(c, MSG);
|
||||
} else {
|
||||
TCPSend(c, MSG);
|
||||
}
|
||||
} else {
|
||||
UDPSend(c, MSG);
|
||||
}
|
||||
}
|
||||
void SendToAll(Client* c, const std::string& Data, bool Self, bool Rel) {
|
||||
if (!Self)
|
||||
Assert(c);
|
||||
char C = Data.at(0);
|
||||
for (auto& client : CI->Clients) {
|
||||
if (client != nullptr) {
|
||||
if (Self || client.get() != c) {
|
||||
if (client->isSynced) {
|
||||
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
|
||||
if (C == 'O' || C == 'T' || Data.length() > 1000)
|
||||
SendLarge(client.get(), Data);
|
||||
else
|
||||
TCPSend(client.get(), Data);
|
||||
} else
|
||||
UDPSend(client.get(), Data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void UpdatePlayers() {
|
||||
std::string Packet = ("Ss") + std::to_string(CI->Size()) + "/" + std::to_string(MaxPlayers) + ":";
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr)
|
||||
Packet += c->GetName() + ",";
|
||||
}
|
||||
Packet = Packet.substr(0, Packet.length() - 1);
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
}
|
||||
void OnDisconnect(Client* c, bool kicked) {
|
||||
Assert(c);
|
||||
info(c->GetName() + (" Connection Terminated"));
|
||||
std::string Packet;
|
||||
for (auto& v : c->GetAllCars()) {
|
||||
if (v != nullptr) {
|
||||
Packet = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(v->ID);
|
||||
SendToAll(c, Packet, false, true);
|
||||
}
|
||||
}
|
||||
if (kicked)
|
||||
Packet = ("L") + c->GetName() + (" was kicked!");
|
||||
else
|
||||
Packet = ("L") + c->GetName() + (" left the server!");
|
||||
SendToAll(c, Packet, false, true);
|
||||
Packet.clear();
|
||||
TriggerLuaEvent(("onPlayerDisconnect"), false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID() } }), false);
|
||||
if (c->GetTCPSock())
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
if (c->GetDownSock())
|
||||
CloseSocketProper(c->GetDownSock());
|
||||
CI->RemoveClient(c);
|
||||
}
|
||||
void OnConnect(Client* c) {
|
||||
Assert(c);
|
||||
info("Client connected");
|
||||
c->SetID(OpenID());
|
||||
info("Assigned ID " + std::to_string(c->GetID()) + " to " + c->GetName());
|
||||
TriggerLuaEvent("onPlayerConnecting", false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID() } }), false);
|
||||
SyncResources(c);
|
||||
if (c->GetStatus() < 0)
|
||||
return;
|
||||
Respond(c, "M" + MapName, true); //Send the Map on connect
|
||||
info(c->GetName() + " : Connected");
|
||||
TriggerLuaEvent("onPlayerJoining", false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID() } }), false);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
#include "Network.h"
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
std::unique_ptr<ClientInterface> CI;
|
||||
void NetMain() {
|
||||
std::thread TCP(TCPServerMain);
|
||||
TCP.detach();
|
||||
UDPServerMain();
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 6/18/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
#include "Security/Enc.h"
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
std::string StatReport;
|
||||
int PPS = 0;
|
||||
void Monitor() {
|
||||
int C = 0, V = 0;
|
||||
if (CI->Clients.empty()) {
|
||||
StatReport = "-";
|
||||
return;
|
||||
}
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr && c->GetCarCount() > 0) {
|
||||
C++;
|
||||
V += c->GetCarCount();
|
||||
}
|
||||
}
|
||||
if (C == 0 || PPS == 0) {
|
||||
StatReport = "-";
|
||||
} else {
|
||||
int R = (PPS / C) / V;
|
||||
StatReport = std::to_string(R);
|
||||
}
|
||||
PPS = 0;
|
||||
}
|
||||
|
||||
[[noreturn]] void Stat() {
|
||||
DebugPrintTID();
|
||||
while (true) {
|
||||
Monitor();
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
}
|
||||
|
||||
void StatInit() {
|
||||
StatReport = "-";
|
||||
std::thread Init(Stat);
|
||||
Init.detach();
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 8/1/2020
|
||||
///
|
||||
|
||||
#include "Client.hpp"
|
||||
#include "Logger.h"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
|
||||
bool TCPSendRaw(SOCKET C, char* Data, int32_t Size) {
|
||||
int64_t Sent = 0;
|
||||
do {
|
||||
int64_t Temp = send(C, &Data[Sent], int(Size - Sent), 0);
|
||||
if (Temp < 1) {
|
||||
info("Socket Closed! " + std::to_string(C));
|
||||
CloseSocketProper(C);
|
||||
return false;
|
||||
}
|
||||
Sent += Temp;
|
||||
} while (Sent < Size);
|
||||
return true;
|
||||
}
|
||||
|
||||
void SplitLoad(Client* c, int64_t Sent, int64_t Size, bool D, const std::string& Name) {
|
||||
std::ifstream f(Name.c_str(), std::ios::binary);
|
||||
int32_t Split = 0x7735940; //125MB
|
||||
char* Data;
|
||||
if (Size > Split)
|
||||
Data = new char[Split];
|
||||
else
|
||||
Data = new char[Size];
|
||||
SOCKET TCPSock;
|
||||
if (D)
|
||||
TCPSock = c->GetDownSock();
|
||||
else
|
||||
TCPSock = c->GetTCPSock();
|
||||
info("Split load Socket " + std::to_string(TCPSock));
|
||||
while (c->GetStatus() > -1 && Sent < Size) {
|
||||
int64_t Diff = Size - Sent;
|
||||
if (Diff > Split) {
|
||||
f.seekg(Sent, std::ios_base::beg);
|
||||
f.read(Data, Split);
|
||||
if (!TCPSendRaw(TCPSock, Data, Split)) {
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
break;
|
||||
}
|
||||
Sent += Split;
|
||||
} else {
|
||||
f.seekg(Sent, std::ios_base::beg);
|
||||
f.read(Data, Diff);
|
||||
if (!TCPSendRaw(TCPSock, Data, int32_t(Diff))) {
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
break;
|
||||
}
|
||||
Sent += Diff;
|
||||
}
|
||||
}
|
||||
delete[] Data;
|
||||
f.close();
|
||||
}
|
||||
|
||||
void SendFile(Client* c, const std::string& Name) {
|
||||
Assert(c);
|
||||
info(c->GetName() + " requesting : " + Name.substr(Name.find_last_of('/')));
|
||||
|
||||
if (!std::filesystem::exists(Name)) {
|
||||
TCPSend(c, "CO");
|
||||
warn("File " + Name + " could not be accessed!");
|
||||
return;
|
||||
} else
|
||||
TCPSend(c, "AG");
|
||||
|
||||
///Wait for connections
|
||||
int T = 0;
|
||||
while (c->GetDownSock() < 1 && T < 50) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
T++;
|
||||
}
|
||||
|
||||
if (c->GetDownSock() < 1) {
|
||||
error("Client doesn't have a download socket!");
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
return;
|
||||
}
|
||||
|
||||
int64_t Size = std::filesystem::file_size(Name), MSize = Size / 2;
|
||||
|
||||
std::thread Dt(SplitLoad, c, 0, MSize, false, Name);
|
||||
Dt.detach();
|
||||
|
||||
SplitLoad(c, MSize, Size, true, Name);
|
||||
|
||||
if (Dt.joinable())
|
||||
Dt.join();
|
||||
}
|
||||
|
||||
void Parse(Client* c, const std::string& Packet) {
|
||||
Assert(c);
|
||||
if (c == nullptr || Packet.empty())
|
||||
return;
|
||||
char Code = Packet.at(0), SubCode = 0;
|
||||
if (Packet.length() > 1)
|
||||
SubCode = Packet.at(1);
|
||||
switch (Code) {
|
||||
case 'f':
|
||||
SendFile(c, Packet.substr(1));
|
||||
return;
|
||||
case 'S':
|
||||
if (SubCode == 'R') {
|
||||
debug("Sending Mod Info");
|
||||
std::string ToSend = FileList + FileSizes;
|
||||
if (ToSend.empty())
|
||||
ToSend = "-";
|
||||
TCPSend(c, ToSend);
|
||||
}
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void SyncResources(Client* c) {
|
||||
Assert(c);
|
||||
if (c == nullptr)
|
||||
return;
|
||||
#ifndef DEBUG
|
||||
try {
|
||||
#endif
|
||||
TCPSend(c, "P" + std::to_string(c->GetID()));
|
||||
std::string Data;
|
||||
while (c->GetStatus() > -1) {
|
||||
Data = TCPRcv(c);
|
||||
if (Data == "Done")
|
||||
break;
|
||||
Parse(c, Data);
|
||||
}
|
||||
#ifndef DEBUG
|
||||
} catch (std::exception& e) {
|
||||
except("Exception! : " + std::string(e.what()));
|
||||
c->SetStatus(-1);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 8/1/2020
|
||||
///
|
||||
#include "Compressor.h"
|
||||
#include "Logger.h"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <thread>
|
||||
|
||||
bool TCPSend(Client* c, const std::string& Data) {
|
||||
Assert(c);
|
||||
if (c == nullptr)
|
||||
return false;
|
||||
|
||||
int32_t Size, Sent;
|
||||
std::string Send(4, 0);
|
||||
Size = int32_t(Data.size());
|
||||
memcpy(&Send[0], &Size, sizeof(Size));
|
||||
Send += Data;
|
||||
Sent = 0;
|
||||
Size += 4;
|
||||
do {
|
||||
int32_t Temp = send(c->GetTCPSock(), &Send[Sent], Size - Sent, 0);
|
||||
if (Temp == 0) {
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
return false;
|
||||
} else if (Temp < 0) {
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
return false;
|
||||
}
|
||||
Sent += Temp;
|
||||
} while (Sent < Size);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CheckBytes(Client* c, int32_t BytesRcv) {
|
||||
Assert(c);
|
||||
if (BytesRcv == 0) {
|
||||
debug("(TCP) Connection closing...");
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
return false;
|
||||
} else if (BytesRcv < 0) {
|
||||
#ifdef WIN32
|
||||
debug(("(TCP) recv failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
#else // unix
|
||||
debug(("(TCP) recv failed with error: ") + std::string(strerror(errno)));
|
||||
#endif // WIN32
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
info(("Closing socket in CheckBytes, BytesRcv < 0"));
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string TCPRcv(Client* c) {
|
||||
Assert(c);
|
||||
int32_t Header, BytesRcv = 0, Temp;
|
||||
if (c == nullptr || c->GetStatus() < 0)
|
||||
return "";
|
||||
|
||||
std::vector<char> Data(sizeof(Header));
|
||||
do {
|
||||
Temp = recv(c->GetTCPSock(), &Data[BytesRcv], 4 - BytesRcv, 0);
|
||||
if (!CheckBytes(c, Temp)) {
|
||||
#ifdef DEBUG
|
||||
error(std::string(__func__) + (": failed on CheckBytes in while(BytesRcv < 4)"));
|
||||
#endif // DEBUG
|
||||
return "";
|
||||
}
|
||||
BytesRcv += Temp;
|
||||
} while (size_t(BytesRcv) < sizeof(Header));
|
||||
memcpy(&Header, &Data[0], sizeof(Header));
|
||||
|
||||
#ifdef DEBUG
|
||||
//debug(std::string(__func__) + (": expecting ") + std::to_string(Header) + (" bytes."));
|
||||
#endif // DEBUG
|
||||
if (!CheckBytes(c, BytesRcv)) {
|
||||
#ifdef DEBUG
|
||||
error(std::string(__func__) + (": failed on CheckBytes"));
|
||||
#endif // DEBUG
|
||||
return "";
|
||||
}
|
||||
Data.resize(Header);
|
||||
BytesRcv = 0;
|
||||
do {
|
||||
Temp = recv(c->GetTCPSock(), &Data[BytesRcv], Header - BytesRcv, 0);
|
||||
if (!CheckBytes(c, Temp)) {
|
||||
#ifdef DEBUG
|
||||
error(std::string(__func__) + (": failed on CheckBytes in while(BytesRcv < Header)"));
|
||||
#endif // DEBUG
|
||||
|
||||
return "";
|
||||
}
|
||||
#ifdef DEBUG
|
||||
//debug(std::string(__func__) + (": Temp: ") + std::to_string(Temp) + (", BytesRcv: ") + std::to_string(BytesRcv));
|
||||
#endif // DEBUG
|
||||
BytesRcv += Temp;
|
||||
} while (BytesRcv < Header);
|
||||
#ifdef DEBUG
|
||||
//debug(std::string(__func__) + (": finished recv with Temp: ") + std::to_string(Temp) + (", BytesRcv: ") + std::to_string(BytesRcv));
|
||||
#endif // DEBUG
|
||||
std::string Ret(Data.data(), Header);
|
||||
|
||||
if (Ret.substr(0, 4) == "ABG:") {
|
||||
Ret = DeComp(Ret.substr(4));
|
||||
}
|
||||
#ifdef DEBUG
|
||||
//debug("Parsing from " + c->GetName() + " -> " +std::to_string(Ret.size()));
|
||||
#endif
|
||||
|
||||
return Ret;
|
||||
}
|
||||
|
||||
void TCPClient(Client* c) {
|
||||
DebugPrintTIDInternal("Client(" + c->GetName() + ")", true);
|
||||
Assert(c);
|
||||
if (c->GetTCPSock() == -1) {
|
||||
CI->RemoveClient(c);
|
||||
return;
|
||||
}
|
||||
OnConnect(c);
|
||||
while (c->GetStatus() > -1) {
|
||||
GParser(c, TCPRcv(c));
|
||||
}
|
||||
OnDisconnect(c, c->GetStatus() == -2);
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
|
||||
#include "Client.hpp"
|
||||
#include "Compressor.h"
|
||||
#include "Logger.h"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <array>
|
||||
|
||||
SOCKET UDPSock;
|
||||
void UDPSend(Client* c, std::string Data) {
|
||||
Assert(c);
|
||||
if (c == nullptr || !c->isConnected || c->GetStatus() < 0)
|
||||
return;
|
||||
sockaddr_in Addr = c->GetUDPAddr();
|
||||
socklen_t AddrSize = sizeof(c->GetUDPAddr());
|
||||
if (Data.length() > 400) {
|
||||
std::string CMP(Comp(Data));
|
||||
Data = "ABG:" + CMP;
|
||||
}
|
||||
#ifdef WIN32
|
||||
int sendOk;
|
||||
int len = static_cast<int>(Data.size());
|
||||
#else
|
||||
int64_t sendOk;
|
||||
size_t len = Data.size();
|
||||
#endif // WIN32
|
||||
|
||||
sendOk = sendto(UDPSock, Data.c_str(), len, 0, (sockaddr*)&Addr, AddrSize);
|
||||
#ifdef WIN32
|
||||
if (sendOk == -1) {
|
||||
debug(("(UDP) Send Failed Code : ") + std::to_string(WSAGetLastError()));
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
} else if (sendOk == 0) {
|
||||
debug(("(UDP) sendto returned 0"));
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
}
|
||||
#else // unix
|
||||
if (sendOk == -1) {
|
||||
debug(("(UDP) Send Failed Code : ") + std::string(strerror(errno)));
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
} else if (sendOk == 0) {
|
||||
debug(("(UDP) sendto returned 0"));
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
}
|
||||
#endif // WIN32
|
||||
}
|
||||
|
||||
void SendLarge(Client* c, std::string Data) {
|
||||
Assert(c);
|
||||
if (Data.length() > 400) {
|
||||
std::string CMP(Comp(Data));
|
||||
Data = "ABG:" + CMP;
|
||||
}
|
||||
TCPSend(c, Data);
|
||||
}
|
||||
|
||||
std::string UDPRcvFromClient(sockaddr_in& client) {
|
||||
size_t clientLength = sizeof(client);
|
||||
std::array<char, 1024> Ret{};
|
||||
int64_t Rcv = recvfrom(UDPSock, Ret.data(), Ret.size(), 0, (sockaddr*)&client, (socklen_t*)&clientLength);
|
||||
if (Rcv == -1) {
|
||||
#ifdef WIN32
|
||||
error(("(UDP) Error receiving from Client! Code : ") + std::to_string(WSAGetLastError()));
|
||||
#else // unix
|
||||
error(("(UDP) Error receiving from Client! Code : ") + std::string(strerror(errno)));
|
||||
#endif // WIN32
|
||||
return "";
|
||||
}
|
||||
return std::string(Ret.begin(), Ret.begin() + Rcv);
|
||||
}
|
||||
|
||||
void UDPParser(Client* c, std::string Packet) {
|
||||
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
|
||||
abort();
|
||||
}
|
||||
Assert(c);
|
||||
if (Packet.substr(0, 4) == "ABG:") {
|
||||
Packet = DeComp(Packet.substr(4));
|
||||
}
|
||||
GParser(c, Packet);
|
||||
}
|
||||
|
||||
[[noreturn]] void UDPServerMain() {
|
||||
#ifdef WIN32
|
||||
WSADATA data;
|
||||
if (WSAStartup(514, &data)) {
|
||||
error(("Can't start Winsock!"));
|
||||
//return;
|
||||
}
|
||||
|
||||
UDPSock = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
// Create a server hint structure for the server
|
||||
sockaddr_in serverAddr {};
|
||||
serverAddr.sin_addr.S_un.S_addr = ADDR_ANY; //Any Local
|
||||
serverAddr.sin_family = AF_INET; // Address format is IPv4
|
||||
serverAddr.sin_port = htons(Port); // Convert from little to big endian
|
||||
|
||||
// Try and bind the socket to the IP and port
|
||||
if (bind(UDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
|
||||
error(("Can't bind socket!") + std::to_string(WSAGetLastError()));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
_Exit(-1);
|
||||
//return;
|
||||
}
|
||||
|
||||
info(("Vehicle data network online on port ") + std::to_string(Port) + (" with a Max of ") + std::to_string(MaxPlayers) + (" Clients"));
|
||||
while (true) {
|
||||
try {
|
||||
sockaddr_in client {};
|
||||
std::string Data = UDPRcvFromClient(client); //Receives any data from Socket
|
||||
auto Pos = Data.find(':');
|
||||
if (Data.empty() || Pos == std::string::npos || Pos > 2)
|
||||
continue;
|
||||
/*char clientIp[256];
|
||||
ZeroMemory(clientIp, 256); ///Code to get IP we don't need that yet
|
||||
inet_ntop(AF_INET, &client.sin_addr, clientIp, 256);*/
|
||||
uint8_t ID = Data.at(0) - 1;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr && c->GetID() == ID) {
|
||||
c->SetUDPAddr(client);
|
||||
c->isConnected = true;
|
||||
UDPParser(c.get(), Data.substr(2));
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
error(("fatal: ") + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
/*CloseSocketProper(UDPSock);
|
||||
WSACleanup();
|
||||
return;*/
|
||||
#else // unix
|
||||
UDPSock = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
// Create a server hint structure for the server
|
||||
sockaddr_in serverAddr {};
|
||||
serverAddr.sin_addr.s_addr = INADDR_ANY; //Any Local
|
||||
serverAddr.sin_family = AF_INET; // Address format is IPv4
|
||||
serverAddr.sin_port = htons(uint16_t(Port)); // Convert from little to big endian
|
||||
|
||||
// Try and bind the socket to the IP and port
|
||||
if (bind(UDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
|
||||
error(("Can't bind socket!") + std::string(strerror(errno)));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
_Exit(-1);
|
||||
//return;
|
||||
}
|
||||
|
||||
info(("Vehicle data network online on port ") + std::to_string(Port) + (" with a Max of ") + std::to_string(MaxPlayers) + (" Clients"));
|
||||
while (true) {
|
||||
try {
|
||||
sockaddr_in client {};
|
||||
std::string Data = UDPRcvFromClient(client); //Receives any data from Socket
|
||||
size_t Pos = Data.find(':');
|
||||
if (Data.empty() || Pos > 2)
|
||||
continue;
|
||||
/*char clientIp[256];
|
||||
ZeroMemory(clientIp, 256); ///Code to get IP we don't need that yet
|
||||
inet_ntop(AF_INET, &client.sin_addr, clientIp, 256);*/
|
||||
uint8_t ID = uint8_t(Data.at(0)) - 1;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr && c->GetID() == ID) {
|
||||
c->SetUDPAddr(client);
|
||||
c->isConnected = true;
|
||||
UDPParser(c.get(), Data.substr(2));
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
error(("fatal: ") + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
/*CloseSocketProper(UDPSock); // TODO: Why not this? We did this in TCPServerMain?
|
||||
return;
|
||||
*/
|
||||
#endif // WIN32
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Server code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 11/6/2020
|
||||
///
|
||||
/*#include <boost/beast/core.hpp>
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <boost/asio/connect.hpp>
|
||||
#include <boost/asio/ip/tcp.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <thread>*/
|
||||
|
||||
/*namespace beast = boost::beast;
|
||||
namespace http = beast::http;
|
||||
namespace websocket = beast::websocket;
|
||||
namespace net = boost::asio;
|
||||
using tcp = boost::asio::ip::tcp;
|
||||
|
||||
std::string GetRes(const beast::flat_buffer& buff) {
|
||||
return (char*)buff.data().data();
|
||||
}*/
|
||||
|
||||
void SyncData() {
|
||||
/*DebugPrintTID();
|
||||
try {
|
||||
std::string const host = ("95.216.35.232");
|
||||
|
||||
net::io_context ioc;
|
||||
tcp::resolver r(ioc);
|
||||
|
||||
websocket::stream<tcp::socket> ws(ioc);
|
||||
auto const results = r.resolve(host, ("3600"));
|
||||
net::connect(ws.next_layer(), results.begin(), results.end());
|
||||
|
||||
|
||||
ws.handshake(host, "/");
|
||||
beast::flat_buffer buffer;
|
||||
ws.write(boost::asio::buffer("Hello, world!"));
|
||||
ws.read(buffer);
|
||||
|
||||
std::cout << GetRes(buffer) << std::endl;
|
||||
|
||||
ws.close(websocket::close_code::normal);
|
||||
|
||||
}catch(std::exception const& e){
|
||||
error(e.what());
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
_Exit(0);
|
||||
}*/
|
||||
}
|
||||
|
||||
void WebsocketInit() {
|
||||
/*std::thread t1(SyncData);
|
||||
t1.detach();*/
|
||||
}
|
||||
62
src/SignalHandling.cpp
Normal file
62
src/SignalHandling.cpp
Normal file
@@ -0,0 +1,62 @@
|
||||
#include "SignalHandling.h"
|
||||
#include "Common.h"
|
||||
|
||||
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||
#include <csignal>
|
||||
static void UnixSignalHandler(int sig) {
|
||||
switch (sig) {
|
||||
case SIGPIPE:
|
||||
beammp_warn("ignoring SIGPIPE");
|
||||
break;
|
||||
case SIGTERM:
|
||||
beammp_info("gracefully shutting down via SIGTERM");
|
||||
Application::GracefullyShutdown();
|
||||
break;
|
||||
case SIGINT:
|
||||
beammp_info("gracefully shutting down via SIGINT");
|
||||
Application::GracefullyShutdown();
|
||||
break;
|
||||
default:
|
||||
beammp_debug("unhandled signal: " + std::to_string(sig));
|
||||
break;
|
||||
}
|
||||
}
|
||||
#endif // UNIX
|
||||
|
||||
#ifdef BEAMMP_WINDOWS
|
||||
#include <windows.h>
|
||||
// return TRUE if handled, FALSE if not
|
||||
BOOL WINAPI Win32CtrlC_Handler(DWORD CtrlType) {
|
||||
switch (CtrlType) {
|
||||
case CTRL_C_EVENT:
|
||||
beammp_info("gracefully shutting down via CTRL+C");
|
||||
Application::GracefullyShutdown();
|
||||
return TRUE;
|
||||
case CTRL_BREAK_EVENT:
|
||||
beammp_info("gracefully shutting down via CTRL+BREAK");
|
||||
Application::GracefullyShutdown();
|
||||
return TRUE;
|
||||
case CTRL_CLOSE_EVENT:
|
||||
beammp_info("gracefully shutting down via close");
|
||||
Application::GracefullyShutdown();
|
||||
return TRUE;
|
||||
}
|
||||
// we dont care for any others like CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT
|
||||
return FALSE;
|
||||
}
|
||||
#endif // WINDOWS
|
||||
|
||||
void SetupSignalHandlers() {
|
||||
// signal handlers for unix#include <windows.h>
|
||||
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||
beammp_trace("registering handlers for signals");
|
||||
signal(SIGPIPE, UnixSignalHandler);
|
||||
signal(SIGTERM, UnixSignalHandler);
|
||||
#ifndef DEBUG
|
||||
signal(SIGINT, UnixSignalHandler);
|
||||
#endif // DEBUG
|
||||
#elif defined(BEAMMP_WINDOWS)
|
||||
beammp_trace("registering handlers for CTRL_*_EVENTs");
|
||||
SetConsoleCtrlHandler(Win32CtrlC_Handler, TRUE);
|
||||
#endif
|
||||
}
|
||||
293
src/TConfig.cpp
Normal file
293
src/TConfig.cpp
Normal file
@@ -0,0 +1,293 @@
|
||||
#include "Common.h"
|
||||
|
||||
#include "TConfig.h"
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
#include <sstream>
|
||||
|
||||
// General
|
||||
static constexpr std::string_view StrDebug = "Debug";
|
||||
static constexpr std::string_view StrPrivate = "Private";
|
||||
static constexpr std::string_view StrPort = "Port";
|
||||
static constexpr std::string_view StrMaxCars = "MaxCars";
|
||||
static constexpr std::string_view StrMaxPlayers = "MaxPlayers";
|
||||
static constexpr std::string_view StrMap = "Map";
|
||||
static constexpr std::string_view StrName = "Name";
|
||||
static constexpr std::string_view StrDescription = "Description";
|
||||
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
||||
static constexpr std::string_view StrAuthKey = "AuthKey";
|
||||
static constexpr std::string_view StrLogChat = "LogChat";
|
||||
|
||||
// Misc
|
||||
static constexpr std::string_view StrSendErrors = "SendErrors";
|
||||
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
||||
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
||||
|
||||
// HTTP
|
||||
static constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
|
||||
static constexpr std::string_view StrHTTPServerUseSSL = "UseSSL";
|
||||
static constexpr std::string_view StrSSLKeyPath = "SSLKeyPath";
|
||||
static constexpr std::string_view StrSSLCertPath = "SSLCertPath";
|
||||
static constexpr std::string_view StrHTTPServerPort = "HTTPServerPort";
|
||||
static constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
|
||||
|
||||
TEST_CASE("TConfig::TConfig") {
|
||||
const std::string CfgFile = "beammp_server_testconfig.toml";
|
||||
fs::remove(CfgFile);
|
||||
|
||||
TConfig Cfg(CfgFile);
|
||||
|
||||
CHECK(fs::file_size(CfgFile) != 0);
|
||||
|
||||
std::string buf;
|
||||
{
|
||||
buf.resize(fs::file_size(CfgFile));
|
||||
auto fp = std::fopen(CfgFile.c_str(), "r");
|
||||
std::fread(buf.data(), 1, buf.size(), fp);
|
||||
std::fclose(fp);
|
||||
}
|
||||
INFO("file contents are:", buf);
|
||||
|
||||
const auto table = toml::parse(CfgFile);
|
||||
CHECK(table.at("General").is_table());
|
||||
CHECK(table.at("Misc").is_table());
|
||||
CHECK(table.at("HTTP").is_table());
|
||||
|
||||
fs::remove(CfgFile);
|
||||
}
|
||||
|
||||
TConfig::TConfig(const std::string& ConfigFileName)
|
||||
: mConfigFileName(ConfigFileName) {
|
||||
Application::SetSubsystemStatus("Config", Application::Status::Starting);
|
||||
if (!fs::exists(mConfigFileName) || !fs::is_regular_file(mConfigFileName)) {
|
||||
beammp_info("No config file found! Generating one...");
|
||||
CreateConfigFile();
|
||||
}
|
||||
if (!mFailed) {
|
||||
if (fs::exists("Server.cfg")) {
|
||||
beammp_warn("An old \"Server.cfg\" file still exists. Please note that this is no longer used. Instead, \"" + std::string(mConfigFileName) + "\" is used. You can safely delete the \"Server.cfg\".");
|
||||
}
|
||||
ParseFromFile(mConfigFileName);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename CommentsT>
|
||||
void SetComment(CommentsT& Comments, const std::string& Comment) {
|
||||
Comments.clear();
|
||||
Comments.push_back(Comment);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Writes out the loaded application state into ServerConfig.toml
|
||||
*
|
||||
* This writes out the current state of application settings that are
|
||||
* applied to the server instance (i.e. the current application settings loaded in the server).
|
||||
* If the state of the application settings changes during runtime,
|
||||
* call this function whenever something about the config changes
|
||||
* whether it is in TConfig.cpp or the configuration file.
|
||||
*/
|
||||
void TConfig::FlushToFile() {
|
||||
// auto data = toml::parse<toml::preserve_comments>(mConfigFileName);
|
||||
auto data = toml::value {};
|
||||
data["General"][StrAuthKey.data()] = Application::Settings.Key;
|
||||
SetComment(data["General"][StrAuthKey.data()].comments(), " AuthKey has to be filled out in order to run the server");
|
||||
data["General"][StrLogChat.data()] = Application::Settings.LogChat;
|
||||
SetComment(data["General"][StrLogChat.data()].comments(), " Whether to log chat messages in the console / log");
|
||||
data["General"][StrDebug.data()] = Application::Settings.DebugModeEnabled;
|
||||
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
||||
data["General"][StrPort.data()] = Application::Settings.Port;
|
||||
data["General"][StrName.data()] = Application::Settings.ServerName;
|
||||
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
|
||||
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
|
||||
data["General"][StrMap.data()] = Application::Settings.MapName;
|
||||
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
|
||||
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
|
||||
// Misc
|
||||
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
|
||||
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
||||
data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
|
||||
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
||||
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
||||
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
||||
// HTTP
|
||||
data["HTTP"][StrSSLKeyPath.data()] = Application::Settings.SSLKeyPath;
|
||||
data["HTTP"][StrSSLCertPath.data()] = Application::Settings.SSLCertPath;
|
||||
data["HTTP"][StrHTTPServerPort.data()] = Application::Settings.HTTPServerPort;
|
||||
SetComment(data["HTTP"][StrHTTPServerIP.data()].comments(), " Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.");
|
||||
data["HTTP"][StrHTTPServerIP.data()] = Application::Settings.HTTPServerIP;
|
||||
data["HTTP"][StrHTTPServerUseSSL.data()] = Application::Settings.HTTPServerUseSSL;
|
||||
SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files");
|
||||
data["HTTP"][StrHTTPServerEnabled.data()] = Application::Settings.HTTPServerEnabled;
|
||||
SetComment(data["HTTP"][StrHTTPServerEnabled.data()].comments(), " Enables the internal HTTP server");
|
||||
std::stringstream Ss;
|
||||
Ss << "# This is the BeamMP-Server config file.\n"
|
||||
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
|
||||
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under \"Keys\"\n"
|
||||
<< data;
|
||||
auto File = std::fopen(mConfigFileName.c_str(), "w+");
|
||||
if (!File) {
|
||||
beammp_error("Failed to create/write to config file: " + GetPlatformAgnosticErrorString());
|
||||
throw std::runtime_error("Failed to create/write to config file");
|
||||
}
|
||||
auto Str = Ss.str();
|
||||
auto N = std::fwrite(Str.data(), sizeof(char), Str.size(), File);
|
||||
if (N != Str.size()) {
|
||||
beammp_error("Failed to write to config file properly, config file might be misshapen");
|
||||
}
|
||||
std::fclose(File);
|
||||
}
|
||||
|
||||
void TConfig::CreateConfigFile() {
|
||||
// build from old config Server.cfg
|
||||
|
||||
try {
|
||||
if (fs::exists("Server.cfg")) {
|
||||
// parse it (this is weird and bad and should be removed in some future version)
|
||||
ParseOldFormat();
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
|
||||
}
|
||||
|
||||
FlushToFile();
|
||||
}
|
||||
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) {
|
||||
if (Table[Category.c_str()][Key.data()].is_string()) {
|
||||
OutValue = Table[Category.c_str()][Key.data()].as_string();
|
||||
}
|
||||
}
|
||||
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue) {
|
||||
if (Table[Category.c_str()][Key.data()].is_boolean()) {
|
||||
OutValue = Table[Category.c_str()][Key.data()].as_boolean();
|
||||
}
|
||||
}
|
||||
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue) {
|
||||
if (Table[Category.c_str()][Key.data()].is_integer()) {
|
||||
OutValue = Table[Category.c_str()][Key.data()].as_integer();
|
||||
}
|
||||
}
|
||||
|
||||
void TConfig::ParseFromFile(std::string_view name) {
|
||||
try {
|
||||
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
||||
// GENERAL
|
||||
TryReadValue(data, "General", StrDebug, Application::Settings.DebugModeEnabled);
|
||||
TryReadValue(data, "General", StrPrivate, Application::Settings.Private);
|
||||
TryReadValue(data, "General", StrPort, Application::Settings.Port);
|
||||
TryReadValue(data, "General", StrMaxCars, Application::Settings.MaxCars);
|
||||
TryReadValue(data, "General", StrMaxPlayers, Application::Settings.MaxPlayers);
|
||||
TryReadValue(data, "General", StrMap, Application::Settings.MapName);
|
||||
TryReadValue(data, "General", StrName, Application::Settings.ServerName);
|
||||
TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc);
|
||||
TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
|
||||
TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
|
||||
TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat);
|
||||
// Misc
|
||||
TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors);
|
||||
TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages);
|
||||
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, Application::Settings.SendErrorsMessageEnabled);
|
||||
// HTTP
|
||||
TryReadValue(data, "HTTP", StrSSLKeyPath, Application::Settings.SSLKeyPath);
|
||||
TryReadValue(data, "HTTP", StrSSLCertPath, Application::Settings.SSLCertPath);
|
||||
TryReadValue(data, "HTTP", StrHTTPServerPort, Application::Settings.HTTPServerPort);
|
||||
TryReadValue(data, "HTTP", StrHTTPServerIP, Application::Settings.HTTPServerIP);
|
||||
TryReadValue(data, "HTTP", StrHTTPServerEnabled, Application::Settings.HTTPServerEnabled);
|
||||
TryReadValue(data, "HTTP", StrHTTPServerUseSSL, Application::Settings.HTTPServerUseSSL);
|
||||
} catch (const std::exception& err) {
|
||||
beammp_error("Error parsing config file value: " + std::string(err.what()));
|
||||
mFailed = true;
|
||||
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
||||
return;
|
||||
}
|
||||
PrintDebug();
|
||||
|
||||
// Update in any case
|
||||
FlushToFile();
|
||||
// all good so far, let's check if there's a key
|
||||
if (Application::Settings.Key.empty()) {
|
||||
beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
|
||||
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
||||
mFailed = true;
|
||||
return;
|
||||
}
|
||||
Application::SetSubsystemStatus("Config", Application::Status::Good);
|
||||
if (Application::Settings.Key.size() != 36) {
|
||||
beammp_warn("AuthKey specified is the wrong length and likely isn't valid.");
|
||||
}
|
||||
}
|
||||
|
||||
void TConfig::PrintDebug() {
|
||||
beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||
beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
|
||||
beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
|
||||
beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
|
||||
beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
|
||||
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
||||
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
||||
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
||||
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
|
||||
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
|
||||
beammp_debug(std::string(StrSSLKeyPath) + ": \"" + Application::Settings.SSLKeyPath + "\"");
|
||||
beammp_debug(std::string(StrSSLCertPath) + ": \"" + Application::Settings.SSLCertPath + "\"");
|
||||
beammp_debug(std::string(StrHTTPServerPort) + ": \"" + std::to_string(Application::Settings.HTTPServerPort) + "\"");
|
||||
beammp_debug(std::string(StrHTTPServerIP) + ": \"" + Application::Settings.HTTPServerIP + "\"");
|
||||
// special!
|
||||
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
|
||||
}
|
||||
|
||||
void TConfig::ParseOldFormat() {
|
||||
std::ifstream File("Server.cfg");
|
||||
// read all, strip comments
|
||||
std::string Content;
|
||||
for (;;) {
|
||||
std::string Line;
|
||||
std::getline(File, Line);
|
||||
if (!Line.empty() && Line.at(0) != '#') {
|
||||
Line = Line.substr(0, Line.find_first_of('#'));
|
||||
Content += Line + "\n";
|
||||
}
|
||||
if (!File.good()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::stringstream Str(Content);
|
||||
std::string Key, Ignore, Value;
|
||||
for (;;) {
|
||||
Str >> Key >> std::ws >> Ignore >> std::ws;
|
||||
std::getline(Str, Value);
|
||||
if (Str.eof()) {
|
||||
break;
|
||||
}
|
||||
std::stringstream ValueStream(Value);
|
||||
ValueStream >> std::ws; // strip leading whitespace if any
|
||||
Value = ValueStream.str();
|
||||
if (Key == "Debug") {
|
||||
Application::Settings.DebugModeEnabled = Value.find("true") != std::string::npos;
|
||||
} else if (Key == "Private") {
|
||||
Application::Settings.Private = Value.find("true") != std::string::npos;
|
||||
} else if (Key == "Port") {
|
||||
ValueStream >> Application::Settings.Port;
|
||||
} else if (Key == "Cars") {
|
||||
ValueStream >> Application::Settings.MaxCars;
|
||||
} else if (Key == "MaxPlayers") {
|
||||
ValueStream >> Application::Settings.MaxPlayers;
|
||||
} else if (Key == "Map") {
|
||||
Application::Settings.MapName = Value.substr(1, Value.size() - 3);
|
||||
} else if (Key == "Name") {
|
||||
Application::Settings.ServerName = Value.substr(1, Value.size() - 3);
|
||||
} else if (Key == "Desc") {
|
||||
Application::Settings.ServerDesc = Value.substr(1, Value.size() - 3);
|
||||
} else if (Key == "use") {
|
||||
Application::Settings.Resource = Value.substr(1, Value.size() - 3);
|
||||
} else if (Key == "AuthKey") {
|
||||
Application::Settings.Key = Value.substr(1, Value.size() - 3);
|
||||
} else {
|
||||
beammp_warn("unknown key in old auth file (ignored): " + Key);
|
||||
}
|
||||
Str >> std::ws;
|
||||
}
|
||||
}
|
||||
712
src/TConsole.cpp
Normal file
712
src/TConsole.cpp
Normal file
@@ -0,0 +1,712 @@
|
||||
#include "TConsole.h"
|
||||
#include "Common.h"
|
||||
#include "Compat.h"
|
||||
|
||||
#include "Client.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "LuaAPI.h"
|
||||
#include "TLuaEngine.h"
|
||||
|
||||
#include <ctime>
|
||||
#include <sstream>
|
||||
|
||||
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
||||
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
|
||||
}
|
||||
|
||||
TEST_CASE("StringStartsWith") {
|
||||
CHECK(StringStartsWith("Hello, World", "Hello"));
|
||||
CHECK(StringStartsWith("Hello, World", "H"));
|
||||
CHECK(StringStartsWith("Hello, World", ""));
|
||||
CHECK(!StringStartsWith("Hello, World", "ello"));
|
||||
CHECK(!StringStartsWith("Hello, World", "World"));
|
||||
CHECK(StringStartsWith("", ""));
|
||||
CHECK(!StringStartsWith("", "hello"));
|
||||
}
|
||||
|
||||
// Trims leading and trailing spaces, newlines, tabs, etc.
|
||||
static inline std::string TrimString(std::string S) {
|
||||
S.erase(S.begin(), std::find_if(S.begin(), S.end(), [](unsigned char ch) {
|
||||
return !std::isspace(ch);
|
||||
}));
|
||||
S.erase(std::find_if(S.rbegin(), S.rend(), [](unsigned char ch) {
|
||||
return !std::isspace(ch);
|
||||
}).base(),
|
||||
S.end());
|
||||
return S;
|
||||
}
|
||||
|
||||
TEST_CASE("TrimString") {
|
||||
CHECK(TrimString("hel lo") == "hel lo");
|
||||
CHECK(TrimString(" hel lo") == "hel lo");
|
||||
CHECK(TrimString(" hel lo ") == "hel lo");
|
||||
CHECK(TrimString("hel lo ") == "hel lo");
|
||||
CHECK(TrimString(" hel lo") == "hel lo");
|
||||
CHECK(TrimString("hel lo ") == "hel lo");
|
||||
CHECK(TrimString(" hel lo ") == "hel lo");
|
||||
CHECK(TrimString("\t\thel\nlo\n\n") == "hel\nlo");
|
||||
CHECK(TrimString("\n\thel\tlo\n\t") == "hel\tlo");
|
||||
CHECK(TrimString(" ") == "");
|
||||
CHECK(TrimString(" \t\n\r ") == "");
|
||||
CHECK(TrimString("") == "");
|
||||
}
|
||||
|
||||
// TODO: add unit tests to SplitString
|
||||
static inline void SplitString(std::string const& str, const char delim, std::vector<std::string>& out) {
|
||||
size_t start;
|
||||
size_t end = 0;
|
||||
|
||||
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
|
||||
end = str.find(delim, start);
|
||||
out.push_back(str.substr(start, end - start));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
std::string GetDate() {
|
||||
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
||||
time_t tt = std::chrono::system_clock::to_time_t(now);
|
||||
auto local_tm = std::localtime(&tt);
|
||||
char buf[30];
|
||||
std::string date;
|
||||
if (Application::Settings.DebugModeEnabled) {
|
||||
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T.", local_tm);
|
||||
date += buf;
|
||||
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
|
||||
auto fraction = now - seconds;
|
||||
size_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(fraction).count();
|
||||
char fracstr[5];
|
||||
std::sprintf(fracstr, "%03lu", ms);
|
||||
date += fracstr;
|
||||
date += "] ";
|
||||
} else {
|
||||
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T] ", local_tm);
|
||||
date += buf;
|
||||
}
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
void TConsole::BackupOldLog() {
|
||||
fs::path Path = "Server.log";
|
||||
if (fs::exists(Path)) {
|
||||
auto OldLog = Path.filename().stem().string() + ".old.log";
|
||||
try {
|
||||
fs::rename(Path, OldLog);
|
||||
beammp_debug("renamed old log file to '" + OldLog + "'");
|
||||
} catch (const std::exception& e) {
|
||||
beammp_warn(e.what());
|
||||
}
|
||||
/*
|
||||
int err = 0;
|
||||
zip* z = zip_open("ServerLogs.zip", ZIP_CREATE, &err);
|
||||
if (!z) {
|
||||
std::cerr << GetPlatformAgnosticErrorString() << std::endl;
|
||||
return;
|
||||
}
|
||||
FILE* File = std::fopen(Path.string().c_str(), "r");
|
||||
if (!File) {
|
||||
std::cerr << GetPlatformAgnosticErrorString() << std::endl;
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> Buffer;
|
||||
Buffer.resize(fs::file_size(Path));
|
||||
std::fread(Buffer.data(), 1, Buffer.size(), File);
|
||||
std::fclose(File);
|
||||
|
||||
auto s = zip_source_buffer(z, Buffer.data(), Buffer.size(), 0);
|
||||
|
||||
auto TimePoint = fs::last_write_time(Path);
|
||||
auto Secs = TimePoint.time_since_epoch().count();
|
||||
auto MyTimeT = std::time(&Secs);
|
||||
|
||||
std::string NewName = Path.stem().string();
|
||||
NewName += "_";
|
||||
std::string Time;
|
||||
Time.resize(32);
|
||||
size_t n = strftime(Time.data(), Time.size(), "%F_%H.%M.%S", localtime(&MyTimeT));
|
||||
Time.resize(n);
|
||||
NewName += Time;
|
||||
NewName += ".log";
|
||||
|
||||
zip_file_add(z, NewName.c_str(), s, 0);
|
||||
zip_close(z);
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
void TConsole::StartLoggingToFile() {
|
||||
mLogFileStream.open("Server.log");
|
||||
Application::Console().Internal().on_write = [this](const std::string& ToWrite) {
|
||||
// TODO: Sanitize by removing all ansi escape codes (vt100)
|
||||
std::unique_lock Lock(mLogFileStreamMtx);
|
||||
mLogFileStream.write(ToWrite.c_str(), ToWrite.size());
|
||||
mLogFileStream.write("\n", 1);
|
||||
mLogFileStream.flush();
|
||||
};
|
||||
}
|
||||
|
||||
void TConsole::ChangeToLuaConsole(const std::string& LuaStateId) {
|
||||
if (!mIsLuaConsole) {
|
||||
if (!mLuaEngine) {
|
||||
beammp_error("Lua engine not initialized yet, please wait and try again");
|
||||
return;
|
||||
}
|
||||
mLuaEngine->EnsureStateExists(mDefaultStateId, "Console");
|
||||
mStateId = LuaStateId;
|
||||
mIsLuaConsole = true;
|
||||
if (mStateId != mDefaultStateId) {
|
||||
Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:detach`");
|
||||
mCommandline.set_prompt("lua @" + LuaStateId + "> ");
|
||||
} else {
|
||||
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:detach`");
|
||||
mCommandline.set_prompt("lua> ");
|
||||
}
|
||||
mCachedRegularHistory = mCommandline.history();
|
||||
mCommandline.set_history(mCachedLuaHistory);
|
||||
}
|
||||
}
|
||||
|
||||
void TConsole::ChangeToRegularConsole() {
|
||||
if (mIsLuaConsole) {
|
||||
mIsLuaConsole = false;
|
||||
if (mStateId != mDefaultStateId) {
|
||||
Application::Console().WriteRaw("Detached from Lua state '" + mStateId + "'.");
|
||||
} else {
|
||||
Application::Console().WriteRaw("Detached from Lua.");
|
||||
}
|
||||
mCachedLuaHistory = mCommandline.history();
|
||||
mCommandline.set_history(mCachedRegularHistory);
|
||||
mCommandline.set_prompt("> ");
|
||||
mStateId = mDefaultStateId;
|
||||
}
|
||||
}
|
||||
|
||||
bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t n) {
|
||||
if (n == 0 && args.size() != 0) {
|
||||
Application::Console().WriteRaw("This command expects no arguments.");
|
||||
return false;
|
||||
} else if (args.size() != n) {
|
||||
Application::Console().WriteRaw("Expected " + std::to_string(n) + " argument(s), instead got " + std::to_string(args.size()));
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t min, size_t max) {
|
||||
if (min == max) {
|
||||
return EnsureArgsCount(args, min);
|
||||
} else {
|
||||
if (args.size() > max) {
|
||||
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
||||
return false;
|
||||
} else if (args.size() < min) {
|
||||
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void TConsole::Command_Lua(const std::string&, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 0, 1)) {
|
||||
return;
|
||||
}
|
||||
if (args.size() == 1) {
|
||||
auto NewStateId = args.at(0);
|
||||
beammp_assert(!NewStateId.empty());
|
||||
if (mLuaEngine->HasState(NewStateId)) {
|
||||
ChangeToLuaConsole(NewStateId);
|
||||
} else {
|
||||
Application::Console().WriteRaw("Lua state '" + NewStateId + "' is not a known state. Didn't switch to Lua.");
|
||||
}
|
||||
} else if (args.size() == 0) {
|
||||
ChangeToLuaConsole(mDefaultStateId);
|
||||
}
|
||||
}
|
||||
|
||||
void TConsole::Command_Help(const std::string&, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 0)) {
|
||||
return;
|
||||
}
|
||||
static constexpr const char* sHelpString = R"(
|
||||
Commands:
|
||||
help displays this help
|
||||
exit shuts down the server
|
||||
kick <name> [reason] kicks specified player with an optional reason
|
||||
list lists all players and info about them
|
||||
say <message> sends the message to all players in chat
|
||||
lua [state id] switches to lua, optionally into a specific state id's lua
|
||||
settings [command] sets or gets settings for the server, run `settings help` for more info
|
||||
status how the server is doing and what it's up to
|
||||
clear clears the console window)";
|
||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||
}
|
||||
|
||||
std::string TConsole::ConcatArgs(const std::vector<std::string>& args, char space) {
|
||||
std::string Result;
|
||||
for (const auto& arg : args) {
|
||||
Result += arg + space;
|
||||
}
|
||||
Result = Result.substr(0, Result.size() - 1); // strip trailing space
|
||||
return Result;
|
||||
}
|
||||
|
||||
void TConsole::Command_Clear(const std::string&, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 0, size_t(-1))) {
|
||||
return;
|
||||
}
|
||||
mCommandline.write("\x1b[;H\x1b[2J");
|
||||
}
|
||||
|
||||
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 1, size_t(-1))) {
|
||||
return;
|
||||
}
|
||||
auto Name = args.at(0);
|
||||
std::string Reason = "Kicked by server console";
|
||||
if (args.size() > 1) {
|
||||
Reason = ConcatArgs({ args.begin() + 1, args.end() });
|
||||
}
|
||||
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
|
||||
bool Kicked = false;
|
||||
auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
|
||||
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = tolower(c); });
|
||||
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = tolower(c); });
|
||||
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
||||
};
|
||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||
if (!Client.expired()) {
|
||||
auto locked = Client.lock();
|
||||
if (NameCompare(locked->GetName(), Name)) {
|
||||
mLuaEngine->Network().ClientKick(*locked, Reason);
|
||||
Kicked = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (!Kicked) {
|
||||
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
||||
} else {
|
||||
Application::Console().WriteRaw("Kicked player '" + Name + "' for reason: '" + Reason + "'.");
|
||||
}
|
||||
}
|
||||
|
||||
std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const std::string& CommandWithArgs) {
|
||||
// Algorithm designed and implemented by Lion Kortlepel (c) 2022
|
||||
// It correctly splits arguments, including respecting single and double quotes, as well as backticks
|
||||
auto End_i = CommandWithArgs.find_first_of(' ');
|
||||
std::string Command = CommandWithArgs.substr(0, End_i);
|
||||
std::string ArgsStr {};
|
||||
if (End_i != std::string::npos) {
|
||||
ArgsStr = CommandWithArgs.substr(End_i);
|
||||
}
|
||||
std::vector<std::string> Args;
|
||||
char* PrevPtr = ArgsStr.data();
|
||||
char* Ptr = ArgsStr.data();
|
||||
const char* End = ArgsStr.data() + ArgsStr.size();
|
||||
while (Ptr != End) {
|
||||
std::string Arg = "";
|
||||
// advance while space
|
||||
while (Ptr != End && std::isspace(*Ptr))
|
||||
++Ptr;
|
||||
PrevPtr = Ptr;
|
||||
// advance while NOT space, also handle quotes
|
||||
while (Ptr != End && !std::isspace(*Ptr)) {
|
||||
// TODO: backslash escaping quotes
|
||||
for (char Quote : { '"', '\'', '`' }) {
|
||||
if (*Ptr == Quote) {
|
||||
// seek if there's a closing quote
|
||||
// if there is, go there and continue, otherwise ignore
|
||||
char* Seeker = Ptr + 1;
|
||||
while (Seeker != End && *Seeker != Quote)
|
||||
++Seeker;
|
||||
if (Seeker != End) {
|
||||
// found closing quote
|
||||
Ptr = Seeker;
|
||||
}
|
||||
break; // exit for loop
|
||||
}
|
||||
}
|
||||
++Ptr;
|
||||
}
|
||||
Arg = std::string(PrevPtr, Ptr - PrevPtr);
|
||||
// remove quotes if enclosed in quotes
|
||||
for (char Quote : { '"', '\'', '`' }) {
|
||||
if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) {
|
||||
Arg = Arg.substr(1, Arg.size() - 2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!Arg.empty()) {
|
||||
Args.push_back(Arg);
|
||||
}
|
||||
}
|
||||
return { Command, Args };
|
||||
}
|
||||
|
||||
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 0)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void TConsole::Command_Say(const std::string& FullCmd) {
|
||||
if (FullCmd.size() > 3) {
|
||||
auto Message = FullCmd.substr(4);
|
||||
LuaAPI::MP::SendChatMessage(-1, Message);
|
||||
if (!Application::Settings.LogChat) {
|
||||
Application::Console().WriteRaw("Chat message sent!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TConsole::Command_List(const std::string&, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 0)) {
|
||||
return;
|
||||
}
|
||||
if (mLuaEngine->Server().ClientCount() == 0) {
|
||||
Application::Console().WriteRaw("No players online.");
|
||||
} else {
|
||||
std::stringstream ss;
|
||||
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
|
||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||
if (!Client.expired()) {
|
||||
auto locked = Client.lock();
|
||||
ss << std::left << std::setw(25) << locked->GetName()
|
||||
<< std::setw(6) << locked->GetID()
|
||||
<< std::setw(6) << locked->GetCarCount() << "\n";
|
||||
}
|
||||
return true;
|
||||
});
|
||||
auto Str = ss.str();
|
||||
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
|
||||
}
|
||||
}
|
||||
|
||||
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 0)) {
|
||||
return;
|
||||
}
|
||||
std::stringstream Status;
|
||||
|
||||
size_t CarCount = 0;
|
||||
size_t ConnectedCount = 0;
|
||||
size_t GuestCount = 0;
|
||||
size_t SyncedCount = 0;
|
||||
size_t SyncingCount = 0;
|
||||
size_t MissedPacketQueueSum = 0;
|
||||
int LargestSecondsSinceLastPing = 0;
|
||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||
if (!Client.expired()) {
|
||||
auto Locked = Client.lock();
|
||||
CarCount += Locked->GetCarCount();
|
||||
ConnectedCount += Locked->IsConnected() ? 1 : 0;
|
||||
GuestCount += Locked->IsGuest() ? 1 : 0;
|
||||
SyncedCount += Locked->IsSynced() ? 1 : 0;
|
||||
SyncingCount += Locked->IsSyncing() ? 1 : 0;
|
||||
MissedPacketQueueSum += Locked->MissedPacketQueueSize();
|
||||
if (Locked->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
|
||||
LargestSecondsSinceLastPing = Locked->SecondsSinceLastPing();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
size_t SystemsStarting = 0;
|
||||
size_t SystemsGood = 0;
|
||||
size_t SystemsBad = 0;
|
||||
size_t SystemsShuttingDown = 0;
|
||||
size_t SystemsShutdown = 0;
|
||||
std::string SystemsBadList {};
|
||||
std::string SystemsGoodList {};
|
||||
std::string SystemsStartingList {};
|
||||
std::string SystemsShuttingDownList {};
|
||||
std::string SystemsShutdownList {};
|
||||
auto Statuses = Application::GetSubsystemStatuses();
|
||||
for (const auto& NameStatusPair : Statuses) {
|
||||
switch (NameStatusPair.second) {
|
||||
case Application::Status::Good:
|
||||
SystemsGood++;
|
||||
SystemsGoodList += NameStatusPair.first + ", ";
|
||||
break;
|
||||
case Application::Status::Bad:
|
||||
SystemsBad++;
|
||||
SystemsBadList += NameStatusPair.first + ", ";
|
||||
break;
|
||||
case Application::Status::Starting:
|
||||
SystemsStarting++;
|
||||
SystemsStartingList += NameStatusPair.first + ", ";
|
||||
break;
|
||||
case Application::Status::ShuttingDown:
|
||||
SystemsShuttingDown++;
|
||||
SystemsShuttingDownList += NameStatusPair.first + ", ";
|
||||
break;
|
||||
case Application::Status::Shutdown:
|
||||
SystemsShutdown++;
|
||||
SystemsShutdownList += NameStatusPair.first + ", ";
|
||||
break;
|
||||
}
|
||||
}
|
||||
// remove ", " at the end
|
||||
SystemsBadList = SystemsBadList.substr(0, SystemsBadList.size() - 2);
|
||||
SystemsGoodList = SystemsGoodList.substr(0, SystemsGoodList.size() - 2);
|
||||
SystemsStartingList = SystemsStartingList.substr(0, SystemsStartingList.size() - 2);
|
||||
SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2);
|
||||
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
|
||||
|
||||
auto ElapsedTime = mLuaEngine->Server().UptimeTimer.GetElapsedTime();
|
||||
|
||||
Status << "BeamMP-Server Status:\n"
|
||||
<< "\tTotal Players: " << mLuaEngine->Server().ClientCount() << "\n"
|
||||
<< "\tSyncing Players: " << SyncingCount << "\n"
|
||||
<< "\tSynced Players: " << SyncedCount << "\n"
|
||||
<< "\tConnected Players: " << ConnectedCount << "\n"
|
||||
<< "\tGuests: " << GuestCount << "\n"
|
||||
<< "\tCars: " << CarCount << "\n"
|
||||
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(ElapsedTime / 1000.0 / 60.0 / 60.0) << "h) \n"
|
||||
<< "\tLua:\n"
|
||||
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
|
||||
<< "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n"
|
||||
<< "\t\tEvent timers: " << mLuaEngine->GetTimedEventsCount() << "\n"
|
||||
<< "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n"
|
||||
<< "\tSubsystems:\n"
|
||||
<< "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n"
|
||||
<< "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n"
|
||||
<< "\t\tGood: [ " << SystemsGoodList << " ]\n"
|
||||
<< "\t\tStarting: [ " << SystemsStartingList << " ]\n"
|
||||
<< "\t\tBad: [ " << SystemsBadList << " ]\n"
|
||||
<< "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n"
|
||||
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
|
||||
<< "";
|
||||
|
||||
Application::Console().WriteRaw(Status.str());
|
||||
}
|
||||
|
||||
void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
|
||||
auto FutureIsNonNil =
|
||||
[](const std::shared_ptr<TLuaResult>& Future) {
|
||||
if (!Future->Error && Future->Result.valid()) {
|
||||
auto Type = Future->Result.get_type();
|
||||
return Type != sol::type::lua_nil && Type != sol::type::none;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
std::vector<std::shared_ptr<TLuaResult>> NonNilFutures;
|
||||
{ // Futures scope
|
||||
auto Futures = mLuaEngine->TriggerEvent("onConsoleInput", "", cmd);
|
||||
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
||||
size_t Count = 0;
|
||||
for (auto& Future : Futures) {
|
||||
if (!Future->Error) {
|
||||
++Count;
|
||||
}
|
||||
}
|
||||
for (const auto& Future : Futures) {
|
||||
if (FutureIsNonNil(Future)) {
|
||||
NonNilFutures.push_back(Future);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (NonNilFutures.size() == 0) {
|
||||
if (!IgnoreNotACommand) {
|
||||
Application::Console().WriteRaw("Error: Unknown command: '" + cmd + "'. Type 'help' to see a list of valid commands.");
|
||||
}
|
||||
} else {
|
||||
std::stringstream Reply;
|
||||
if (NonNilFutures.size() > 1) {
|
||||
for (size_t i = 0; i < NonNilFutures.size(); ++i) {
|
||||
Reply << NonNilFutures[i]->StateId << ": \n"
|
||||
<< LuaAPI::LuaToString(NonNilFutures[i]->Result);
|
||||
if (i < NonNilFutures.size() - 1) {
|
||||
Reply << "\n";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Reply << LuaAPI::LuaToString(NonNilFutures[0]->Result);
|
||||
}
|
||||
Application::Console().WriteRaw(Reply.str());
|
||||
}
|
||||
}
|
||||
|
||||
void TConsole::HandleLuaInternalCommand(const std::string& cmd) {
|
||||
if (cmd == "exit") {
|
||||
ChangeToRegularConsole();
|
||||
} else if (cmd == "queued") {
|
||||
auto QueuedFunctions = LuaAPI::MP::Engine->Debug_GetStateFunctionQueueForState(mStateId);
|
||||
Application::Console().WriteRaw("Pending functions in State '" + mStateId + "'");
|
||||
std::unordered_map<std::string, size_t> FunctionsCount;
|
||||
std::vector<std::string> FunctionsInOrder;
|
||||
while (!QueuedFunctions.empty()) {
|
||||
auto Tuple = QueuedFunctions.front();
|
||||
QueuedFunctions.erase(QueuedFunctions.begin());
|
||||
FunctionsInOrder.push_back(Tuple.FunctionName);
|
||||
FunctionsCount[Tuple.FunctionName] += 1;
|
||||
}
|
||||
std::set<std::string> Uniques;
|
||||
for (const auto& Function : FunctionsInOrder) {
|
||||
if (Uniques.count(Function) == 0) {
|
||||
Uniques.insert(Function);
|
||||
if (FunctionsCount.at(Function) > 1) {
|
||||
Application::Console().WriteRaw(" " + Function + " (" + std::to_string(FunctionsCount.at(Function)) + "x)");
|
||||
} else {
|
||||
Application::Console().WriteRaw(" " + Function);
|
||||
}
|
||||
}
|
||||
}
|
||||
Application::Console().WriteRaw("Executed functions waiting to be checked in State '" + mStateId + "'");
|
||||
for (const auto& Function : LuaAPI::MP::Engine->Debug_GetResultsToCheckForState(mStateId)) {
|
||||
Application::Console().WriteRaw(" '" + Function.Function + "' (Ready? " + (Function.Ready ? "Yes" : "No") + ", Error? " + (Function.Error ? "Yes: '" + Function.ErrorMessage + "'" : "No") + ")");
|
||||
}
|
||||
} else if (cmd == "events") {
|
||||
auto Events = LuaAPI::MP::Engine->Debug_GetEventsForState(mStateId);
|
||||
Application::Console().WriteRaw("Registered Events + Handlers for State '" + mStateId + "'");
|
||||
for (const auto& EventHandlerPair : Events) {
|
||||
Application::Console().WriteRaw(" Event '" + EventHandlerPair.first + "'");
|
||||
for (const auto& Handler : EventHandlerPair.second) {
|
||||
Application::Console().WriteRaw(" " + Handler);
|
||||
}
|
||||
}
|
||||
} else if (cmd == "help") {
|
||||
Application::Console().WriteRaw(R"(BeamMP Lua Debugger
|
||||
All commands must be prefixed with a `:`. Non-prefixed commands are interpreted as Lua.
|
||||
|
||||
Commands
|
||||
:exit detaches (exits) from this Lua console
|
||||
:help displays this help
|
||||
:events shows a list of currently registered events
|
||||
:queued shows a list of all pending and queued functions)");
|
||||
} else {
|
||||
beammp_error("internal command '" + cmd + "' is not known");
|
||||
}
|
||||
}
|
||||
|
||||
TConsole::TConsole() {
|
||||
mCommandline.enable_history();
|
||||
mCommandline.set_history_limit(20);
|
||||
mCommandline.set_prompt("> ");
|
||||
BackupOldLog();
|
||||
mCommandline.on_command = [this](Commandline& c) {
|
||||
try {
|
||||
auto TrimmedCmd = c.get_command();
|
||||
TrimmedCmd = TrimString(TrimmedCmd);
|
||||
auto [cmd, args] = ParseCommand(TrimmedCmd);
|
||||
mCommandline.write(mCommandline.prompt() + TrimmedCmd);
|
||||
if (mIsLuaConsole) {
|
||||
if (!mLuaEngine) {
|
||||
beammp_info("Lua not started yet, please try again in a second");
|
||||
} else if (!cmd.empty() && cmd.at(0) == ':') {
|
||||
HandleLuaInternalCommand(cmd.substr(1));
|
||||
} else {
|
||||
auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" });
|
||||
while (!Future->Ready) {
|
||||
std::this_thread::yield(); // TODO: Add a timeout
|
||||
}
|
||||
if (Future->Error) {
|
||||
beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!mLuaEngine) {
|
||||
beammp_error("Attempted to run a command before Lua engine started. Please wait and try again.");
|
||||
} else if (cmd == "exit") {
|
||||
beammp_info("gracefully shutting down");
|
||||
Application::GracefullyShutdown();
|
||||
} else if (cmd == "say") {
|
||||
RunAsCommand(TrimmedCmd, true);
|
||||
Command_Say(TrimmedCmd);
|
||||
} else {
|
||||
if (mCommandMap.find(cmd) != mCommandMap.end()) {
|
||||
mCommandMap.at(cmd)(cmd, args);
|
||||
RunAsCommand(TrimmedCmd, true);
|
||||
} else {
|
||||
RunAsCommand(TrimmedCmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate.");
|
||||
}
|
||||
};
|
||||
mCommandline.on_autocomplete = [this](Commandline& c, std::string stub, int cursorPos) {
|
||||
std::vector<std::string> suggestions;
|
||||
try {
|
||||
if (mIsLuaConsole) { // if lua
|
||||
if (!mLuaEngine) {
|
||||
beammp_info("Lua not started yet, please try again in a second");
|
||||
} else {
|
||||
std::string prefix {}; // stores non-table part of input
|
||||
for (size_t i = stub.length(); i > 0; i--) { //separate table from input
|
||||
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_' && stub[i - 1] != '.') {
|
||||
prefix = stub.substr(0, i);
|
||||
stub = stub.substr(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// turn string into vector of keys
|
||||
std::vector<std::string> tablekeys;
|
||||
|
||||
SplitString(stub, '.', tablekeys);
|
||||
|
||||
// remove last key if incomplete
|
||||
if (stub.rfind('.') != stub.size() - 1 && !tablekeys.empty()) {
|
||||
tablekeys.pop_back();
|
||||
}
|
||||
|
||||
auto keys = mLuaEngine->GetStateTableKeysForState(mStateId, tablekeys);
|
||||
|
||||
for (const auto& key : keys) { // go through each bottom-level key
|
||||
auto last_dot = stub.rfind('.');
|
||||
std::string last_atom;
|
||||
if (last_dot != std::string::npos) {
|
||||
last_atom = stub.substr(last_dot + 1);
|
||||
}
|
||||
std::string before_last_atom = stub.substr(0, last_dot + 1); // get last confirmed key
|
||||
auto last = stub.substr(stub.rfind('.') + 1);
|
||||
std::string::size_type n = key.find(last);
|
||||
if (n == 0) {
|
||||
suggestions.push_back(prefix + before_last_atom + key);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else { // if not lua
|
||||
if (stub.find("lua") == 0) { // starts with "lua" means we should suggest state names
|
||||
std::string after_prefix = TrimString(stub.substr(3));
|
||||
auto stateNames = mLuaEngine->GetLuaStateNames();
|
||||
|
||||
for (const auto& name : stateNames) {
|
||||
if (name.find(after_prefix) == 0) {
|
||||
suggestions.push_back("lua " + name);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const auto& [cmd_name, cmd_fn] : mCommandMap) {
|
||||
if (cmd_name.find(stub) == 0) {
|
||||
suggestions.push_back(cmd_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate.");
|
||||
}
|
||||
std::sort(suggestions.begin(), suggestions.end());
|
||||
return suggestions;
|
||||
};
|
||||
}
|
||||
|
||||
void TConsole::Write(const std::string& str) {
|
||||
auto ToWrite = GetDate() + str;
|
||||
mCommandline.write(ToWrite);
|
||||
}
|
||||
|
||||
void TConsole::WriteRaw(const std::string& str) {
|
||||
mCommandline.write(str);
|
||||
}
|
||||
|
||||
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
|
||||
mLuaEngine = &Engine;
|
||||
}
|
||||
185
src/THeartbeatThread.cpp
Normal file
185
src/THeartbeatThread.cpp
Normal file
@@ -0,0 +1,185 @@
|
||||
#include "THeartbeatThread.h"
|
||||
|
||||
#include "Client.h"
|
||||
#include "Http.h"
|
||||
//#include "SocketIO.h"
|
||||
#include <rapidjson/document.h>
|
||||
#include <rapidjson/rapidjson.h>
|
||||
#include <sstream>
|
||||
|
||||
namespace json = rapidjson;
|
||||
|
||||
void THeartbeatThread::operator()() {
|
||||
RegisterThread("Heartbeat");
|
||||
std::string Body;
|
||||
std::string T;
|
||||
|
||||
// these are "hot-change" related variables
|
||||
static std::string Last;
|
||||
|
||||
static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
|
||||
bool isAuth = false;
|
||||
size_t UpdateReminderCounter = 0;
|
||||
while (!Application::IsShuttingDown()) {
|
||||
++UpdateReminderCounter;
|
||||
Body = GenerateCall();
|
||||
// a hot-change occurs when a setting has changed, to update the backend of that change.
|
||||
auto Now = std::chrono::high_resolution_clock::now();
|
||||
bool Unchanged = Last == Body;
|
||||
auto TimePassed = (Now - LastNormalUpdateTime);
|
||||
auto Threshold = Unchanged ? 30 : 5;
|
||||
if (TimePassed < std::chrono::seconds(Threshold)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
continue;
|
||||
}
|
||||
beammp_debug("heartbeat (after " + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(TimePassed).count()) + "s)");
|
||||
|
||||
Last = Body;
|
||||
LastNormalUpdateTime = Now;
|
||||
if (!Application::Settings.CustomIP.empty()) {
|
||||
Body += "&ip=" + Application::Settings.CustomIP;
|
||||
}
|
||||
|
||||
Body += "&pps=" + Application::PPS();
|
||||
|
||||
beammp_trace("heartbeat body: '" + Body + "'");
|
||||
|
||||
auto SentryReportError = [&](const std::string& transaction, int status) {
|
||||
auto Lock = Sentry.CreateExclusiveContext();
|
||||
Sentry.SetContext("heartbeat",
|
||||
{ { "response-body", T },
|
||||
{ "request-body", Body } });
|
||||
Sentry.SetTransaction(transaction);
|
||||
beammp_trace("sending log to sentry: " + std::to_string(status) + " for " + transaction);
|
||||
Sentry.Log(SentryLevel::Error, "default", Http::Status::ToString(status) + " (" + std::to_string(status) + ")");
|
||||
};
|
||||
|
||||
auto Target = "/heartbeat";
|
||||
unsigned int ResponseCode = 0;
|
||||
|
||||
json::Document Doc;
|
||||
bool Ok = false;
|
||||
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
||||
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
||||
beammp_trace(T);
|
||||
Doc.Parse(T.data(), T.size());
|
||||
if (Doc.HasParseError() || !Doc.IsObject()) {
|
||||
if (!Application::Settings.Private) {
|
||||
beammp_error("Backend response failed to parse as valid json");
|
||||
beammp_trace("Response was: `" + T + "`");
|
||||
}
|
||||
Sentry.SetContext("JSON Response", { { "reponse", T } });
|
||||
SentryReportError(Url + Target, ResponseCode);
|
||||
} else if (ResponseCode != 200) {
|
||||
SentryReportError(Url + Target, ResponseCode);
|
||||
} else {
|
||||
// all ok
|
||||
Ok = true;
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
}
|
||||
std::string Status {};
|
||||
std::string Code {};
|
||||
std::string Message {};
|
||||
const auto StatusKey = "status";
|
||||
const auto CodeKey = "code";
|
||||
const auto MessageKey = "msg";
|
||||
|
||||
if (Ok) {
|
||||
if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) {
|
||||
Status = Doc[StatusKey].GetString();
|
||||
} else {
|
||||
Sentry.SetContext("JSON Response", { { StatusKey, "invalid string / missing" } });
|
||||
Ok = false;
|
||||
}
|
||||
if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) {
|
||||
Code = Doc[CodeKey].GetString();
|
||||
} else {
|
||||
Sentry.SetContext("JSON Response", { { CodeKey, "invalid string / missing" } });
|
||||
Ok = false;
|
||||
}
|
||||
if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) {
|
||||
Message = Doc[MessageKey].GetString();
|
||||
} else {
|
||||
Sentry.SetContext("JSON Response", { { MessageKey, "invalid string / missing" } });
|
||||
Ok = false;
|
||||
}
|
||||
if (!Ok) {
|
||||
beammp_error("Missing/invalid json members in backend response");
|
||||
Sentry.LogError("Missing/invalid json members in backend response", __FILE__, std::to_string(__LINE__));
|
||||
}
|
||||
} else {
|
||||
if (!Application::Settings.Private) {
|
||||
beammp_warn("Backend failed to respond to a heartbeat. Your server may temporarily disappear from the server list. This is not an error, and will likely resolve itself soon. Direct connect will still work.");
|
||||
}
|
||||
}
|
||||
|
||||
if (Ok && !isAuth && !Application::Settings.Private) {
|
||||
if (Status == "2000") {
|
||||
beammp_info(("Authenticated! " + Message));
|
||||
isAuth = true;
|
||||
} else if (Status == "200") {
|
||||
beammp_info(("Resumed authenticated session! " + Message));
|
||||
isAuth = true;
|
||||
} else {
|
||||
if (Message.empty()) {
|
||||
Message = "Backend didn't provide a reason.";
|
||||
}
|
||||
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
|
||||
}
|
||||
}
|
||||
if (isAuth || Application::Settings.Private) {
|
||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
||||
}
|
||||
if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
|
||||
Application::CheckForUpdates();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string THeartbeatThread::GenerateCall() {
|
||||
std::stringstream Ret;
|
||||
|
||||
Ret << "uuid=" << Application::Settings.Key
|
||||
<< "&players=" << mServer.ClientCount()
|
||||
<< "&maxplayers=" << Application::Settings.MaxPlayers
|
||||
<< "&port=" << Application::Settings.Port
|
||||
<< "&map=" << Application::Settings.MapName
|
||||
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
||||
<< "&version=" << Application::ServerVersionString()
|
||||
<< "&clientversion=" << Application::ClientVersionString()
|
||||
<< "&name=" << Application::Settings.ServerName
|
||||
<< "&modlist=" << mResourceManager.TrimmedList()
|
||||
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
||||
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
||||
<< "&playerslist=" << GetPlayers()
|
||||
<< "&desc=" << Application::Settings.ServerDesc;
|
||||
return Ret.str();
|
||||
}
|
||||
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
||||
: mResourceManager(ResourceManager)
|
||||
, mServer(Server) {
|
||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
|
||||
Application::RegisterShutdownHandler([&] {
|
||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
|
||||
if (mThread.joinable()) {
|
||||
mThread.join();
|
||||
}
|
||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Shutdown);
|
||||
});
|
||||
Start();
|
||||
}
|
||||
std::string THeartbeatThread::GetPlayers() {
|
||||
std::string Return;
|
||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
if (!ClientPtr.expired()) {
|
||||
Return += ClientPtr.lock()->GetName() + ";";
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return Return;
|
||||
}
|
||||
/*THeartbeatThread::~THeartbeatThread() {
|
||||
}*/
|
||||
1084
src/TLuaEngine.cpp
Normal file
1084
src/TLuaEngine.cpp
Normal file
File diff suppressed because it is too large
Load Diff
52
src/TLuaPlugin.cpp
Normal file
52
src/TLuaPlugin.cpp
Normal file
@@ -0,0 +1,52 @@
|
||||
#include "TLuaPlugin.h"
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <random>
|
||||
#include <utility>
|
||||
|
||||
TLuaPlugin::TLuaPlugin(TLuaEngine& Engine, const TLuaPluginConfig& Config, const fs::path& MainFolder)
|
||||
: mConfig(Config)
|
||||
, mEngine(Engine)
|
||||
, mFolder(MainFolder)
|
||||
, mPluginName(MainFolder.stem().string())
|
||||
, mFileContents(0) {
|
||||
beammp_debug("Lua plugin \"" + mPluginName + "\" starting in \"" + mFolder.string() + "\"");
|
||||
std::vector<fs::path> Entries;
|
||||
for (const auto& Entry : fs::directory_iterator(mFolder)) {
|
||||
if (Entry.is_regular_file() && Entry.path().extension() == ".lua") {
|
||||
Entries.push_back(Entry);
|
||||
}
|
||||
}
|
||||
// sort alphabetically (not needed if config is used to determine call order)
|
||||
// TODO: Use config to figure out what to run in which order
|
||||
std::sort(Entries.begin(), Entries.end(), [](const fs::path& first, const fs::path& second) {
|
||||
auto firstStr = first.string();
|
||||
auto secondStr = second.string();
|
||||
std::transform(firstStr.begin(), firstStr.end(), firstStr.begin(), ::tolower);
|
||||
std::transform(secondStr.begin(), secondStr.end(), secondStr.begin(), ::tolower);
|
||||
return firstStr < secondStr;
|
||||
});
|
||||
std::vector<std::pair<fs::path, std::shared_ptr<TLuaResult>>> ResultsToCheck;
|
||||
for (const auto& Entry : Entries) {
|
||||
// read in entire file
|
||||
try {
|
||||
std::ifstream FileStream(Entry.string(), std::ios::in | std::ios::binary);
|
||||
auto Size = std::filesystem::file_size(Entry);
|
||||
auto Contents = std::make_shared<std::string>();
|
||||
Contents->resize(Size);
|
||||
FileStream.read(Contents->data(), Contents->size());
|
||||
mFileContents[fs::relative(Entry).string()] = Contents;
|
||||
// Execute first time
|
||||
auto Result = mEngine.EnqueueScript(mConfig.StateId, TLuaChunk(Contents, Entry.string(), MainFolder.string()));
|
||||
ResultsToCheck.emplace_back(Entry.string(), std::move(Result));
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("Error loading file \"" + Entry.string() + "\": " + e.what());
|
||||
}
|
||||
}
|
||||
for (auto& Result : ResultsToCheck) {
|
||||
Result.second->WaitUntilReady();
|
||||
if (Result.second->Error) {
|
||||
beammp_lua_error("Failed: \"" + Result.first.string() + "\": " + Result.second->ErrorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
1050
src/TNetwork.cpp
Normal file
1050
src/TNetwork.cpp
Normal file
File diff suppressed because it is too large
Load Diff
69
src/TPPSMonitor.cpp
Normal file
69
src/TPPSMonitor.cpp
Normal file
@@ -0,0 +1,69 @@
|
||||
#include "TPPSMonitor.h"
|
||||
#include "Client.h"
|
||||
#include "TNetwork.h"
|
||||
|
||||
TPPSMonitor::TPPSMonitor(TServer& Server)
|
||||
: mServer(Server) {
|
||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Starting);
|
||||
Application::SetPPS("-");
|
||||
Application::RegisterShutdownHandler([&] {
|
||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::ShuttingDown);
|
||||
if (mThread.joinable()) {
|
||||
beammp_debug("shutting down PPSMonitor");
|
||||
mThread.join();
|
||||
beammp_debug("shut down PPSMonitor");
|
||||
}
|
||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Shutdown);
|
||||
});
|
||||
Start();
|
||||
}
|
||||
void TPPSMonitor::operator()() {
|
||||
RegisterThread("PPSMonitor");
|
||||
while (!mNetwork) {
|
||||
// hard(-ish) spin
|
||||
std::this_thread::yield();
|
||||
}
|
||||
beammp_debug("PPSMonitor starting");
|
||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Good);
|
||||
std::vector<std::shared_ptr<TClient>> TimedOutClients;
|
||||
while (!Application::IsShuttingDown()) {
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
int C = 0, V = 0;
|
||||
if (mServer.ClientCount() == 0) {
|
||||
Application::SetPPS("-");
|
||||
continue;
|
||||
}
|
||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||
std::shared_ptr<TClient> c;
|
||||
{
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
if (!ClientPtr.expired()) {
|
||||
c = ClientPtr.lock();
|
||||
} else
|
||||
return true;
|
||||
}
|
||||
if (c->GetCarCount() > 0) {
|
||||
C++;
|
||||
V += c->GetCarCount();
|
||||
}
|
||||
// kick on "no ping"
|
||||
if (c->SecondsSinceLastPing() > (20 * 60)) {
|
||||
beammp_debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
|
||||
TimedOutClients.push_back(c);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
for (auto& ClientToKick : TimedOutClients) {
|
||||
Network().ClientKick(*ClientToKick, "Timeout (no ping for way too long)");
|
||||
}
|
||||
TimedOutClients.clear();
|
||||
if (C == 0 || mInternalPPS == 0) {
|
||||
Application::SetPPS("-");
|
||||
} else {
|
||||
int R = (mInternalPPS / C) / V;
|
||||
Application::SetPPS(std::to_string(R));
|
||||
}
|
||||
mInternalPPS = 0;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user