mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-13 18:24:16 +00:00
Compare commits
619 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f9b9d4642a | |||
| b4d6f90012 | |||
| d5000aea87 | |||
| 810788a3e4 | |||
| e724a2e467 | |||
| 54ba295fce | |||
| f419550061 | |||
| 8cccbe8542 | |||
| 6787843b37 | |||
| 16d3c6f796 | |||
| 21e5101560 | |||
| 1adf19d416 | |||
| c7e228fbae | |||
| 6e04b2d93a | |||
| 57a4c47cb0 | |||
| 416e0399af | |||
| 050b574cc0 | |||
| d65f3cf75b | |||
| 329d2eb268 | |||
| 221f491019 | |||
| 89db370e12 | |||
| aa84a65546 | |||
| b28c69a515 | |||
| ac41547123 | |||
| 2fc610f6bc | |||
| ddd3883aa9 | |||
| defadf094f | |||
| 81299db946 | |||
| c3895ec1ca | |||
| c741fe5310 | |||
| e1dfb1085e | |||
| 142b6fa47a | |||
| a6cbffc774 | |||
| dc4ead532d | |||
| f28d9bc7dc | |||
| 8c73eb8aea | |||
| 43b1b050e2 | |||
| 9f87edc6e9 | |||
| c6f78c5522 | |||
| 9f01268538 | |||
| 5523a4fe4b | |||
| 7f11d0f002 | |||
| 6b31ba35fd | |||
| d2329f0723 | |||
| ef45efeb86 | |||
| edcca75637 | |||
| c1bacf1f3a | |||
| 795b651744 | |||
| be108bb8b3 | |||
| d8b8812026 | |||
| 872c2d410d | |||
| f98704e0f3 | |||
| dea203c108 | |||
| e245c9e9e2 | |||
| 11fe5ad200 | |||
| 667da22b0e | |||
| a6eb2f7bfe | |||
| 103d2dc030 | |||
| 7f206fd0d4 | |||
| 22805af716 | |||
| 2c29a195f9 | |||
| 222d2492ff | |||
| 879b9772f5 | |||
| c51cf090ef | |||
| d677d8d58d | |||
| 4b30918659 | |||
| 688e46f524 | |||
| 9f59c27b1f | |||
| 6a11bcd20b | |||
| b7b578bf3e | |||
| 6c145a6dbf | |||
| 67d792e0e0 | |||
| eaeef0c7d0 | |||
| 47e64a7343 | |||
| 7f5b3919f4 | |||
| 896e777e23 | |||
| aa58c1e211 | |||
| 49a9226dca | |||
| b10d5d0f4e | |||
| 5581fd1692 | |||
| d36bb7962c | |||
| 4e8bd993d5 | |||
| abff9bfbdb | |||
| b024533f90 | |||
| f9251ff92c | |||
| 99f41c28cb | |||
| bbd27c9cba | |||
| 4682922467 | |||
| 83fb387dfe | |||
| 2b61f11a86 | |||
| a8b1a205f7 | |||
| dd9376447a | |||
| aa185afabf | |||
| e8caeb9126 | |||
| fa1944dbef | |||
| 093f905fd8 | |||
| 2a45d2282d | |||
| aeb024953a | |||
| 12a0ab7fdd | |||
| 917c501faf | |||
| 340933bbb3 | |||
| a63359479e | |||
| bdf2da758c | |||
| 88c0ed56e4 | |||
| 4256977400 | |||
| 309a9d1fa9 | |||
| ad860835ca | |||
| c6c2efb0b1 | |||
| c4c3b03b7a | |||
| fd51336a91 | |||
| 466845b314 | |||
| 92632b53b5 | |||
| 331a597ec7 | |||
| 87965433c2 | |||
| 75ff9f7571 | |||
| 94c0547a35 | |||
| 98f77e157f | |||
| 54730d2baf | |||
| 064e71e59f | |||
| 2678234d67 | |||
| 4320a91e5c | |||
| 7d1318653c | |||
| 67d02d4cf2 | |||
| 93b2559120 | |||
| ed872f730d | |||
| b25f4a875c | |||
| cc6b7846b2 | |||
| 88f5db514f | |||
| e595192829 | |||
| c69418ea5e | |||
| 917e3f98ab | |||
| c42a523532 | |||
| 95ae0f5d03 | |||
| fc0a509bd9 | |||
| 6249397fb5 | |||
| 231b13a0e7 | |||
| 7d2e4d4581 | |||
| 7446526a19 | |||
| 6e97a3cd6e | |||
| 30482d290a | |||
| 5f1d003077 | |||
| 5d3dff3c88 | |||
| cb0cb30797 | |||
| 1f14de2e71 | |||
| 658b37acac | |||
| d63c84286e | |||
| 9c6127a105 | |||
| a1d99c0203 | |||
| 10dff185e0 | |||
| dd17b95427 | |||
| 1a9872db00 | |||
| dbb01998ea | |||
| 3c4737a145 | |||
| 36e8ba1614 | |||
| 988f19fd00 | |||
| fdf24815bb | |||
| b145c8159e | |||
| ae517b30c0 | |||
| e638c25f70 | |||
| 24c98eb2b2 | |||
| 501fddadc6 | |||
| 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 | |||
| 35a3dab1ce | |||
| 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 |
@@ -1,7 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: Bug report
|
name: Bug report
|
||||||
about: Create a report to help us improve
|
about: Create a report to help us improve
|
||||||
title: "[Bug] Enter issue title here"
|
|
||||||
labels: bug
|
labels: bug
|
||||||
assignees: ''
|
assignees: ''
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
---
|
---
|
||||||
name: Feature request
|
name: Feature request
|
||||||
about: Suggest an idea for this project
|
about: Suggest an idea for this project
|
||||||
title: "[Feature Request]"
|
labels: feature
|
||||||
labels: enhancement
|
|
||||||
assignees: ''
|
assignees: ''
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
name: CMake Linux Build
|
|
||||||
|
|
||||||
on: [push]
|
|
||||||
|
|
||||||
env:
|
|
||||||
BUILD_TYPE: Release
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
linux-build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
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
|
|
||||||
sudo add-apt-repository ppa:mhier/libboost-latest
|
|
||||||
sudo apt-get install -y libboost1.70-dev libboost1.70
|
|
||||||
|
|
||||||
- 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: Archive artifacts
|
|
||||||
uses: actions/upload-artifact@v2
|
|
||||||
with:
|
|
||||||
name: BeamMP-Server-linux
|
|
||||||
path: ${{github.workspace}}/build-linux/BeamMP-Server
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
name: CMake Windows Build
|
|
||||||
|
|
||||||
on: [push]
|
|
||||||
|
|
||||||
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@main
|
|
||||||
id: runvcpkg
|
|
||||||
with:
|
|
||||||
vcpkgArguments: 'lua zlib rapidjson boost-beast boost-asio openssl websocketpp curl'
|
|
||||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
|
||||||
vcpkgGitCommitId: '8dddc6c899ce6fdbeab38b525a31e7f23cb2d5bb'
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
name: Linux
|
||||||
|
|
||||||
|
on: [push]
|
||||||
|
|
||||||
|
env:
|
||||||
|
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||||
|
CMAKE_BUILD_TYPE: "Release"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
debian-11-build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: debian:11
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/debian-11/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/debian-11/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/debian-11/3-build.sh
|
||||||
|
|
||||||
|
- name: Archive server artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-debian
|
||||||
|
path: ./bin/BeamMP-Server
|
||||||
|
|
||||||
|
- name: Archive server debug info artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-debian.debug
|
||||||
|
path: ./bin/BeamMP-Server.debug
|
||||||
|
|
||||||
|
- name: Build Tests
|
||||||
|
run: bash ./scripts/debian-11/3-build-tests.sh
|
||||||
|
|
||||||
|
- name: Install Runtime Dependencies
|
||||||
|
run: bash ./scripts/debian-11/4-install-runtime-deps.sh
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: ./bin/BeamMP-Server-tests
|
||||||
|
|
||||||
|
ubuntu-22-04-build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: ubuntu:22.04
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Setup vcpkg
|
||||||
|
uses: lukka/run-vcpkg@v11
|
||||||
|
with:
|
||||||
|
runVcpkgInstall: true
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/ubuntu-22.04/3-build.sh
|
||||||
|
|
||||||
|
- name: Archive server artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-ubuntu
|
||||||
|
path: ./bin/BeamMP-Server
|
||||||
|
|
||||||
|
- name: Archive server debug info artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-ubuntu.debug
|
||||||
|
path: ./bin/BeamMP-Server.debug
|
||||||
|
|
||||||
|
- name: Build Tests
|
||||||
|
run: bash ./scripts/ubuntu-22.04/3-build-tests.sh
|
||||||
|
|
||||||
|
- name: Install Runtime Dependencies
|
||||||
|
run: bash ./scripts/ubuntu-22.04/4-install-runtime-deps.sh
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: ./bin/BeamMP-Server-tests
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
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: false
|
|
||||||
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
|
|
||||||
sudo add-apt-repository ppa:mhier/libboost-latest
|
|
||||||
sudo apt-get install -y libboost1.70-dev libboost1.70
|
|
||||||
|
|
||||||
- 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@main
|
|
||||||
id: runvcpkg
|
|
||||||
with:
|
|
||||||
vcpkgArguments: 'lua zlib rapidjson boost-beast boost-asio openssl websocketpp curl'
|
|
||||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
|
||||||
vcpkgGitCommitId: '8dddc6c899ce6fdbeab38b525a31e7f23cb2d5bb'
|
|
||||||
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
|
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
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:
|
||||||
|
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||||
|
CMAKE_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. You need to install the [Visual C++ Redistributables](https://aka.ms/vs/17/release/vc_redist.x64.exe) to run this.
|
||||||
|
- `BeamMP-Server-debian` is a Debian 11 build, requires `liblua5.3-0`.
|
||||||
|
- `BeamMP-Server-ubuntu` is a Ubuntu 22.04 build, requires `liblua5.3-0`.
|
||||||
|
|
||||||
|
upload-release-files-debian-11:
|
||||||
|
name: Build and upload Debian 11 Release Files
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
needs: create-release
|
||||||
|
container:
|
||||||
|
image: debian:11
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/debian-11/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/debian-11/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Setup vcpkg
|
||||||
|
uses: lukka/run-vcpkg@v11
|
||||||
|
with:
|
||||||
|
runVcpkgInstall: true
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/debian-11/3-build.sh
|
||||||
|
|
||||||
|
- 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 }}
|
||||||
|
asset_path: ./bin/BeamMP-Server
|
||||||
|
asset_name: BeamMP-Server-debian
|
||||||
|
asset_content_type: application/x-elf
|
||||||
|
|
||||||
|
- name: Upload Debug Info
|
||||||
|
id: upload-debug-info
|
||||||
|
uses: actions/upload-release-asset@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||||
|
asset_path: ./bin/BeamMP-Server.debug
|
||||||
|
asset_name: debuginfo-debian.debug
|
||||||
|
asset_content_type: application/x-elf
|
||||||
|
|
||||||
|
upload-release-files-ubuntu-22-04:
|
||||||
|
name: Build and upload Ubuntu 22.04 Release Files
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
needs: create-release
|
||||||
|
container:
|
||||||
|
image: ubuntu:22.04
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/ubuntu-22.04/3-build.sh
|
||||||
|
|
||||||
|
- 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 }}
|
||||||
|
asset_path: ./bin/BeamMP-Server
|
||||||
|
asset_name: BeamMP-Server-ubuntu
|
||||||
|
asset_content_type: application/x-elf
|
||||||
|
|
||||||
|
- name: Upload Debug Info
|
||||||
|
id: upload-debug-info
|
||||||
|
uses: actions/upload-release-asset@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||||
|
asset_path: ./bin/BeamMP-Server.debug
|
||||||
|
asset_name: debuginfo-ubuntu.debug
|
||||||
|
asset_content_type: application/x-elf
|
||||||
|
|
||||||
|
upload-release-files-windows:
|
||||||
|
name: Build and upload Windows Release Files
|
||||||
|
runs-on: windows-latest
|
||||||
|
needs: create-release
|
||||||
|
env:
|
||||||
|
VCPKG_DEFAULT_TRIPLET: x64-windows-static
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
shell: bash
|
||||||
|
run: ./scripts/windows/1-configure.sh
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/windows/2-build.sh
|
||||||
|
|
||||||
|
- 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 }}
|
||||||
|
asset_path: ./bin/Release/BeamMP-Server.exe
|
||||||
|
asset_name: BeamMP-Server.exe
|
||||||
|
asset_content_type: application/vnd.microsoft.portable-executable
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
name: Windows
|
||||||
|
|
||||||
|
on: [push]
|
||||||
|
|
||||||
|
env:
|
||||||
|
VCPKG_DEFAULT_TRIPLET: x64-windows-static
|
||||||
|
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||||
|
CMAKE_BUILD_TYPE: "Release"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
windows-build:
|
||||||
|
runs-on: windows-latest
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Setup vcpkg
|
||||||
|
uses: lukka/run-vcpkg@v11
|
||||||
|
with:
|
||||||
|
runVcpkgInstall: true
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
shell: bash
|
||||||
|
run: ./scripts/windows/1-configure.sh
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/windows/2-build.sh
|
||||||
|
|
||||||
|
- name: Archive server artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-windows
|
||||||
|
path: ./bin/Release/BeamMP-Server.exe
|
||||||
|
|
||||||
+5
-14
@@ -1,15 +1,6 @@
|
|||||||
[submodule "include/commandline"]
|
[submodule "deps/commandline"]
|
||||||
path = include/commandline
|
path = deps/commandline
|
||||||
url = https://github.com/lionkor/commandline
|
url = https://github.com/lionkor/commandline
|
||||||
[submodule "asio"]
|
[submodule "vcpkg"]
|
||||||
path = asio
|
path = vcpkg
|
||||||
url = https://github.com/chriskohlhoff/asio
|
url = https://github.com/Microsoft/vcpkg.git
|
||||||
[submodule "rapidjson"]
|
|
||||||
path = rapidjson
|
|
||||||
url = https://github.com/Tencent/rapidjson
|
|
||||||
[submodule "include/toml11"]
|
|
||||||
path = include/toml11
|
|
||||||
url = https://github.com/ToruNiina/toml11
|
|
||||||
[submodule "include/sentry-native"]
|
|
||||||
path = include/sentry-native
|
|
||||||
url = https://github.com/getsentry/sentry-native
|
|
||||||
|
|||||||
+195
-123
@@ -1,141 +1,213 @@
|
|||||||
cmake_minimum_required(VERSION 3.0)
|
cmake_minimum_required(VERSION 3.16 FATAL_ERROR)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
message(STATUS "You can find build instructions and a list of dependencies in the README at \
|
|
||||||
https://github.com/BeamMP/BeamMP-Server")
|
|
||||||
|
|
||||||
project(BeamMP-Server
|
|
||||||
DESCRIPTION "Server for BeamMP - The Multiplayer Mod for BeamNG.drive"
|
|
||||||
HOMEPAGE_URL https://beammp.com
|
|
||||||
LANGUAGES CXX C)
|
|
||||||
|
|
||||||
if (WIN32)
|
if (WIN32)
|
||||||
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
set(VCPKG_TARGET_TRIPLET x64-windows-static)
|
||||||
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})
|
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
include_directories("include/sentry-native/include")
|
include(cmake/Vcpkg.cmake) # needs to happen before project()
|
||||||
set(SENTRY_BUILD_SHARED_LIBS OFF)
|
|
||||||
if (MSVC)
|
|
||||||
set(SENTRY_BUILD_RUNTIMESTATIC ON)
|
|
||||||
endif()
|
|
||||||
set(SENTRY_BACKEND breakpad)
|
|
||||||
add_subdirectory("include/sentry-native")
|
|
||||||
|
|
||||||
message(STATUS "Setting compiler flags")
|
project(
|
||||||
if (WIN32)
|
"BeamMP-Server" # replace this
|
||||||
|
VERSION 3.3.0
|
||||||
|
)
|
||||||
|
|
||||||
#-DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
include(cmake/StandardSettings.cmake)
|
||||||
set(VcpkgRoot ${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET})
|
include(cmake/StaticAnalyzers.cmake)
|
||||||
include_directories(${VcpkgRoot}/include)
|
include(cmake/Git.cmake)
|
||||||
link_directories(${VcpkgRoot}/lib)
|
|
||||||
elseif (UNIX)
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic -static-libstdc++")
|
|
||||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
|
||||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -s -fno-builtin")
|
|
||||||
if (SANITIZE)
|
|
||||||
message(STATUS "sanitize is ON")
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLanAGS} -fsanitize=undefined,thread")
|
|
||||||
endif (SANITIZE)
|
|
||||||
endif ()
|
|
||||||
|
|
||||||
message(STATUS "Checking for Sentry URL")
|
# below are options which should be changed
|
||||||
# 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 "")
|
|
||||||
else()
|
|
||||||
string(LENGTH ${BEAMMP_SECRET_SENTRY_URL} URL_LEN)
|
|
||||||
message(STATUS "Sentry URL is length ${URL_LEN}")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
message(STATUS "Adding local source dependencies")
|
### SETTINGS ###
|
||||||
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
|
|
||||||
include_directories("asio/asio/include")
|
|
||||||
include_directories("rapidjson/include")
|
|
||||||
include_directories("websocketpp")
|
|
||||||
add_subdirectory("include/commandline")
|
|
||||||
|
|
||||||
|
# add all headers (.h, .hpp) to this
|
||||||
|
set(PRJ_HEADERS
|
||||||
|
include/ArgsParser.h
|
||||||
|
include/BoostAliases.h
|
||||||
|
include/Client.h
|
||||||
|
include/Common.h
|
||||||
|
include/Compat.h
|
||||||
|
include/Cryptography.h
|
||||||
|
include/CustomAssert.h
|
||||||
|
include/Defer.h
|
||||||
|
include/Environment.h
|
||||||
|
include/Http.h
|
||||||
|
include/IThreaded.h
|
||||||
|
include/Json.h
|
||||||
|
include/LuaAPI.h
|
||||||
|
include/RWMutex.h
|
||||||
|
include/SignalHandling.h
|
||||||
|
include/TConfig.h
|
||||||
|
include/TConsole.h
|
||||||
|
include/THeartbeatThread.h
|
||||||
|
include/TLuaEngine.h
|
||||||
|
include/TLuaPlugin.h
|
||||||
|
include/TNetwork.h
|
||||||
|
include/TPluginMonitor.h
|
||||||
|
include/TPPSMonitor.h
|
||||||
|
include/TResourceManager.h
|
||||||
|
include/TScopedTimer.h
|
||||||
|
include/TServer.h
|
||||||
|
include/VehicleData.h
|
||||||
|
)
|
||||||
|
# add all source files (.cpp) to this, except the one with main()
|
||||||
|
set(PRJ_SOURCES
|
||||||
|
src/ArgsParser.cpp
|
||||||
|
src/Client.cpp
|
||||||
|
src/Common.cpp
|
||||||
|
src/Compat.cpp
|
||||||
|
src/Http.cpp
|
||||||
|
src/LuaAPI.cpp
|
||||||
|
src/SignalHandling.cpp
|
||||||
|
src/TConfig.cpp
|
||||||
|
src/TConsole.cpp
|
||||||
|
src/THeartbeatThread.cpp
|
||||||
|
src/TLuaEngine.cpp
|
||||||
|
src/TLuaPlugin.cpp
|
||||||
|
src/TNetwork.cpp
|
||||||
|
src/TPluginMonitor.cpp
|
||||||
|
src/TPPSMonitor.cpp
|
||||||
|
src/TResourceManager.cpp
|
||||||
|
src/TScopedTimer.cpp
|
||||||
|
src/TServer.cpp
|
||||||
|
src/VehicleData.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 17)
|
|
||||||
|
|
||||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
|
|
||||||
|
|
||||||
message(STATUS "Looking for Boost")
|
|
||||||
find_package(Boost REQUIRED COMPONENTS system thread)
|
|
||||||
|
|
||||||
add_executable(BeamMP-Server
|
|
||||||
src/main.cpp
|
|
||||||
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/TLuaFile.h src/TLuaFile.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)
|
|
||||||
|
|
||||||
target_compile_definitions(BeamMP-Server PRIVATE SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}")
|
|
||||||
|
|
||||||
target_include_directories(BeamMP-Server PUBLIC
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/commandline")
|
|
||||||
|
|
||||||
message(STATUS "Looking for Lua")
|
|
||||||
find_package(Lua REQUIRED)
|
find_package(Lua REQUIRED)
|
||||||
target_include_directories(BeamMP-Server PUBLIC
|
|
||||||
${Boost_INCLUDE_DIRS}
|
|
||||||
${LUA_INCLUDE_DIR}
|
|
||||||
${CURL_INCLUDE_DIRS}
|
|
||||||
"include/tomlplusplus"
|
|
||||||
"include/sentry-native/include"
|
|
||||||
"include/curl/include")
|
|
||||||
|
|
||||||
message(STATUS "Looking for SSL")
|
|
||||||
|
|
||||||
|
# set the source file containing main()
|
||||||
|
set(PRJ_MAIN src/main.cpp)
|
||||||
|
# set the source file containing the test's main
|
||||||
|
set(PRJ_TEST_MAIN test/test_main.cpp)
|
||||||
|
# set include paths not part of libraries
|
||||||
|
set(PRJ_INCLUDE_DIRS ${LUA_INCLUDE_DIR})
|
||||||
|
# set compile features (e.g. standard version)
|
||||||
|
set(PRJ_COMPILE_FEATURES cxx_std_20)
|
||||||
|
# set #defines (test enable/disable not included here)
|
||||||
|
set(PRJ_DEFINITIONS CPPHTTPLIB_OPENSSL_SUPPORT)
|
||||||
|
# add all libraries used by the project (WARNING: also set them in vcpkg.json!)
|
||||||
|
set(PRJ_LIBRARIES
|
||||||
|
fmt::fmt
|
||||||
|
doctest::doctest
|
||||||
|
Threads::Threads
|
||||||
|
commandline_static
|
||||||
|
toml11::toml11
|
||||||
|
rapidjson
|
||||||
|
sol2
|
||||||
|
httplib::httplib
|
||||||
|
libzip::zip
|
||||||
|
OpenSSL::SSL OpenSSL::Crypto
|
||||||
|
${LUA_LIBRARIES}
|
||||||
|
)
|
||||||
|
|
||||||
|
# add dependency find_package calls and similar here
|
||||||
|
find_package(fmt CONFIG REQUIRED)
|
||||||
find_package(OpenSSL REQUIRED)
|
find_package(OpenSSL REQUIRED)
|
||||||
|
find_package(doctest CONFIG REQUIRED)
|
||||||
|
find_package(Boost REQUIRED)
|
||||||
|
find_package(httplib CONFIG REQUIRED)
|
||||||
|
find_package(libzip CONFIG REQUIRED)
|
||||||
|
find_package(RapidJSON CONFIG REQUIRED)
|
||||||
|
find_package(sol2 CONFIG REQUIRED)
|
||||||
|
find_package(toml11 CONFIG REQUIRED)
|
||||||
|
|
||||||
message(STATUS "CURL IS ${CURL_LIBRARIES}")
|
include_directories(include)
|
||||||
|
|
||||||
|
# to enable multithreading and the Threads::Threads dependency
|
||||||
|
include(FindThreads)
|
||||||
|
|
||||||
|
### END SETTINGS ###
|
||||||
|
|
||||||
|
# DONT change anything beyond this point unless you've read the cmake bible and
|
||||||
|
# swore on it not to bonk up the ci/cd pipelines with your changes.
|
||||||
|
|
||||||
|
####################
|
||||||
|
|
||||||
|
|
||||||
|
# enables compile_commands.json for clang-related tools (such as the clang LS)
|
||||||
|
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||||
|
|
||||||
|
# build release builds by default (if not specified otherwise)
|
||||||
|
if(NOT DEFINED CMAKE_BUILD_TYPE)
|
||||||
|
message(NOTICE "No build type specified, defaulting to 'Release'")
|
||||||
|
set(CMAKE_BUILD_TYPE "Release")
|
||||||
|
endif()
|
||||||
|
|
||||||
if(UNIX)
|
if(UNIX)
|
||||||
target_link_libraries(BeamMP-Server
|
# this will allow to use same _DEBUG macro available in both Linux as well as Windows - MSCV environment. Easy to put Debug specific code.
|
||||||
z
|
add_compile_options("$<$<CONFIG:DEBUG>:-D_DEBUG>")
|
||||||
pthread
|
endif(UNIX)
|
||||||
stdc++fs
|
|
||||||
${LUA_LIBRARIES}
|
if (WIN32)
|
||||||
crypto
|
add_compile_options("-D_WIN32_WINNT=0x0601")
|
||||||
${OPENSSL_LIBRARIES}
|
endif(WIN32)
|
||||||
commandline
|
|
||||||
sentry)
|
|
||||||
elseif (WIN32)
|
include(cmake/CompilerWarnings.cmake)
|
||||||
include(FindLua)
|
|
||||||
message(STATUS "Looking for libz")
|
# set MT library for msvc - this is required (says documentation)
|
||||||
find_package(ZLIB REQUIRED)
|
# linux/mac/etc should simply ignore this by default.
|
||||||
message(STATUS "Looking for RapidJSON")
|
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||||
find_package(RapidJSON CONFIG REQUIRED)
|
|
||||||
target_include_directories(BeamMP-Server PRIVATE ${RAPIDJSON_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS})
|
set(PRJ_DEFINITIONS ${PRJ_DEFINITIONS}
|
||||||
target_link_libraries(BeamMP-Server PRIVATE
|
PRJ_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
|
||||||
ws2_32
|
PRJ_VERSION_MINOR=${PROJECT_VERSION_MINOR}
|
||||||
ZLIB::ZLIB
|
PRJ_VERSION_PATCH=${PROJECT_VERSION_PATCH}
|
||||||
${LUA_LIBRARIES}
|
)
|
||||||
${OPENSSL_LIBRARIES}
|
|
||||||
commandline
|
# build commandline manually for funky windows flags to carry over without a custom toolchain file
|
||||||
sentry)
|
add_library(commandline_static
|
||||||
|
deps/commandline/src/impls.h
|
||||||
|
deps/commandline/src/windows_impl.cpp
|
||||||
|
deps/commandline/src/linux_impl.cpp
|
||||||
|
deps/commandline/src/backends/InteractiveBackend.cpp
|
||||||
|
deps/commandline/src/backends/InteractiveBackend.h
|
||||||
|
deps/commandline/src/backends/Backend.cpp
|
||||||
|
deps/commandline/src/backends/Backend.h
|
||||||
|
deps/commandline/src/commandline.h
|
||||||
|
deps/commandline/src/commandline.cpp
|
||||||
|
deps/commandline/src/backends/BufferedBackend.cpp
|
||||||
|
deps/commandline/src/backends/BufferedBackend.h
|
||||||
|
)
|
||||||
|
if (WIN32)
|
||||||
|
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_WINDOWS=1)
|
||||||
|
else ()
|
||||||
|
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_LINUX=1)
|
||||||
endif ()
|
endif ()
|
||||||
|
target_include_directories(commandline_static PUBLIC "deps/commandline/src")
|
||||||
|
target_link_libraries(commandline_static Threads::Threads)
|
||||||
|
# end of commandline custom build
|
||||||
|
|
||||||
|
add_executable(${PROJECT_NAME} ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_MAIN})
|
||||||
|
set_target_properties(${PROJECT_NAME} PROPERTIES
|
||||||
|
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
|
||||||
|
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
|
||||||
|
MACOSX_BUNDLE TRUE
|
||||||
|
WIN32_EXECUTABLE TRUE
|
||||||
|
)
|
||||||
|
target_include_directories(${PROJECT_NAME} PRIVATE ${PRJ_INCLUDE_DIRS})
|
||||||
|
target_link_libraries(${PROJECT_NAME} ${PRJ_LIBRARIES})
|
||||||
|
target_compile_features(${PROJECT_NAME} PRIVATE ${PRJ_COMPILE_FEATURES})
|
||||||
|
target_compile_definitions(${PROJECT_NAME} PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS}
|
||||||
|
DOCTEST_CONFIG_DISABLE # disables all test code in the final executable
|
||||||
|
)
|
||||||
|
|
||||||
|
if(MSVC)
|
||||||
|
target_link_options(${PROJECT_NAME} PRIVATE "/SUBSYSTEM:CONSOLE")
|
||||||
|
endif(MSVC)
|
||||||
|
|
||||||
|
# setup all warnings (from cmake/CompilerWarnings.cmake)
|
||||||
|
set_project_warnings(${PROJECT_NAME})
|
||||||
|
|
||||||
|
if(${PROJECT_NAME}_ENABLE_UNIT_TESTING)
|
||||||
|
message(STATUS "Unit tests are enabled and will be built as '${PROJECT_NAME}-tests'")
|
||||||
|
add_executable(${PROJECT_NAME}-tests ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_TEST_MAIN})
|
||||||
|
target_include_directories(${PROJECT_NAME}-tests PRIVATE ${PRJ_INCLUDE_DIRS})
|
||||||
|
target_link_libraries(${PROJECT_NAME}-tests ${PRJ_LIBRARIES})
|
||||||
|
target_compile_features(${PROJECT_NAME}-tests PRIVATE ${PRJ_COMPILE_FEATURES})
|
||||||
|
target_compile_definitions(${PROJECT_NAME}-tests PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS})
|
||||||
|
set_project_warnings(${PROJECT_NAME}-tests)
|
||||||
|
if(MSVC)
|
||||||
|
target_link_options(${PROJECT_NAME}-tests PRIVATE "/SUBSYSTEM:CONSOLE")
|
||||||
|
endif(MSVC)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
|||||||
+111
@@ -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.
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
# 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
|
|
||||||
@@ -4,7 +4,16 @@
|
|||||||
[](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Linux+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/).
|
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 throug which all clients communicate. You can write lua mods for the server, detailed instructions on the [BeamMP Wiki](https://wiki.beammp.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, which are listed below under [Runtime Dependencies](#runtime-dependencies)**
|
||||||
|
|
||||||
|
## Support + Contact
|
||||||
|
|
||||||
|
Feel free to ask any questions via the following channels:
|
||||||
|
|
||||||
|
- **Discord**: [click for invite](https://discord.gg/beammp)
|
||||||
|
- **BeamMP Forum**: [BeamMP Forum Support](https://forum.beammp.com/c/support/33)
|
||||||
|
|
||||||
## Minimum Requirements
|
## Minimum Requirements
|
||||||
|
|
||||||
@@ -19,21 +28,21 @@ These values are guesstimated and are subject to change with each release.
|
|||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" label or with nobody assigned, any [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer) cards in the "To-Do" column.
|
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" or "good first issue" label or with nobody assigned.
|
||||||
|
|
||||||
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues) and at the [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer). Any issues that have the "help wanted" label or don't have anyone assigned and any trello cards that aren't assigned or in the "In-Progress" section are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
|
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.
|
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++.
|
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
|
## 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`.
|
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 `v3.1.0`.
|
||||||
|
|
||||||
## Supported Operating Systems
|
## Supported Operating Systems
|
||||||
|
|
||||||
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.
|
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute Windows binaries and Linux. For any other distro or OS, you just have to find the same libraries listed in [Runtime Dependencies](#runtime-dependencies) further down the page, and it should build fine.
|
||||||
|
|
||||||
Recommended compilers: MSVC, GCC, CLANG.
|
Recommended compilers: MSVC, GCC, CLANG.
|
||||||
|
|
||||||
@@ -41,59 +50,38 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
|
|||||||
|
|
||||||
## Build Instructions
|
## Build Instructions
|
||||||
|
|
||||||
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.0`!__**
|
On Linux, you need some dependencies to **build** the server (on Windows, you don't):
|
||||||
|
|
||||||
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)).
|
For Debian, Ubuntu and others you can find scripts that do this in `scripts/`.
|
||||||
|
|
||||||
### Prerequisites
|
```
|
||||||
|
liblua5.3-dev curl zip unzip tar cmake make git g++
|
||||||
#### Windows
|
|
||||||
|
|
||||||
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
|
||||||
|
|
||||||
Dependencies for windows can be installed with `vcpkg`, in which case the current dependencies are the `x64-windows-static` versions of `lua`, `zlib`, `rapidjson`, `boost-beast`, `boost-asio` and `openssl`.
|
|
||||||
|
|
||||||
#### Linux / \*nix
|
|
||||||
|
|
||||||
These package names are in the debian / ubuntu style. Feel free to PR your own guide for a different distro.
|
|
||||||
|
|
||||||
- `git`
|
|
||||||
- `make`
|
|
||||||
- `cmake`
|
|
||||||
- `g++`
|
|
||||||
- `libcurl4-openssl-dev` or similar (search for `libcurl` and look for one with `-dev`)
|
|
||||||
|
|
||||||
Must support ISO C++17. If your distro's `g++` doesn't support C++17, chances are that it has a `g++-8` or `g++-10` package that does. If this is the case. you just need to run CMake with `-DCMAKE_CXX_COMPILER=g++-10` (replace `g++-10` with your compiler's name).
|
|
||||||
- `liblua5.3-dev`
|
|
||||||
|
|
||||||
Any 5.x version should work, but 5.3 is what we officially use. Any other version might break in the future.
|
|
||||||
You can also use any version of `libluajit`, but the same applies regarding the version.
|
|
||||||
- `libz-dev`
|
|
||||||
- `rapidjson-dev`
|
|
||||||
- `libopenssl-dev` or `libssl-dev`
|
|
||||||
|
|
||||||
**If** you're building it from source, you'll need `libboost1.70-all-dev` or `libboost1.71-all-dev` or higher as well.
|
|
||||||
If you can't find this version of boost (only 1.6x, for example), you can either update to a newer version of your distro, build boost yourself, or use an unstable rolling release (like Debian `sid` aka `unstable`).
|
|
||||||
|
|
||||||
In the end you should end up with a command something like this:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
sudo apt install git make cmake g++-10 liblua5.3 libz-dev rapidjson-dev libopenssl-dev libboost1.71-all-dev
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### How to build
|
The names of each package may change depending on your platform. See in `scripts/` or use a search engine to find out what they're called for you.
|
||||||
|
|
||||||
On windows, use git-bash for these commands. On Linux, these should work in your shell.
|
You can build on **Windows, Linux** or other platforms by following these steps:
|
||||||
|
|
||||||
1. Make sure you have all [prerequisites](#prerequisites) installed
|
1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`.
|
||||||
2. Clone the repository in a location of your choice with `git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`.
|
2. Go into the directory `cd BeamMP-Server`.
|
||||||
3. Ensure that all submodules are initialized by running `git submodule update --init --recursive`. Then change into the cloned directory by running `cd BeamMP-Server`.
|
3. Run CMake `cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release` - this can take a few minutes and may take a lot of disk space and bandwidth.
|
||||||
4. Checkout the branch of the release you want to compile (`master` is often unstable), for example `git checkout tags/v1.20` for version 1.20. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
4. Build via `cmake --build bin --parallel -t BeamMP-Server`.
|
||||||
5. Run `cmake .` (with `.`)
|
5. Your executable can be found in `bin/`.
|
||||||
6. Run `make`
|
|
||||||
7. 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_Mod) 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 &`*.*
|
When you make changes to the code, you only have to run step 4 again.
|
||||||
|
|
||||||
|
### Runtime Dependencies
|
||||||
|
|
||||||
|
These are needed to *run* the server.
|
||||||
|
|
||||||
|
Debian, Ubuntu and friends: `liblua5.3-0`
|
||||||
|
|
||||||
|
Other Linux distros: `liblua` of *some kind*.
|
||||||
|
|
||||||
|
Windows: No libraries.
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
|
|||||||
-1
Submodule asio deleted from 230c0d2ae0
@@ -0,0 +1,115 @@
|
|||||||
|
# from here:
|
||||||
|
#
|
||||||
|
# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md
|
||||||
|
# Courtesy of Jason Turner
|
||||||
|
# License here: https://github.com/cpp-best-practices/cppbestpractices/blob/master/LICENSE
|
||||||
|
#
|
||||||
|
# This version has been modified by the owners of the current respository.
|
||||||
|
# Modifications have mostly been marked with "modified" or similar, though this is not
|
||||||
|
# strictly required.
|
||||||
|
|
||||||
|
function(set_project_warnings project_name)
|
||||||
|
set(MSVC_WARNINGS
|
||||||
|
/W4 # Baseline reasonable warnings
|
||||||
|
/w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss
|
||||||
|
# of data
|
||||||
|
/w14254 # 'operator': conversion from 'type1:field_bits' to
|
||||||
|
# 'type2:field_bits', possible loss of data
|
||||||
|
/w14263 # 'function': member function does not override any base class
|
||||||
|
# virtual member function
|
||||||
|
/w14265 # 'classname': class has virtual functions, but destructor is not
|
||||||
|
# virtual instances of this class may not be destructed correctly
|
||||||
|
/w14287 # 'operator': unsigned/negative constant mismatch
|
||||||
|
/we4289 # nonstandard extension used: 'variable': loop control variable
|
||||||
|
# declared in the for-loop is used outside the for-loop scope
|
||||||
|
/w14296 # 'operator': expression is always 'boolean_value'
|
||||||
|
/w14311 # 'variable': pointer truncation from 'type1' to 'type2'
|
||||||
|
/w14545 # expression before comma evaluates to a function which is missing
|
||||||
|
# an argument list
|
||||||
|
/w14546 # function call before comma missing argument list
|
||||||
|
/w14547 # 'operator': operator before comma has no effect; expected
|
||||||
|
# operator with side-effect
|
||||||
|
/w14549 # 'operator': operator before comma has no effect; did you intend
|
||||||
|
# 'operator'?
|
||||||
|
/w14555 # expression has no effect; expected expression with side- effect
|
||||||
|
/w14619 # pragma warning: there is no warning number 'number'
|
||||||
|
/w14640 # Enable warning on thread un-safe static member initialization
|
||||||
|
/w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may
|
||||||
|
# cause unexpected runtime behavior.
|
||||||
|
/w14905 # wide string literal cast to 'LPSTR'
|
||||||
|
/w14906 # string literal cast to 'LPWSTR'
|
||||||
|
/w14928 # illegal copy-initialization; more than one user-defined
|
||||||
|
# conversion has been implicitly applied
|
||||||
|
/permissive- # standards conformance mode for MSVC compiler.
|
||||||
|
)
|
||||||
|
|
||||||
|
set(CLANG_WARNINGS
|
||||||
|
-Wall
|
||||||
|
-Wextra # reasonable and standard
|
||||||
|
-Wshadow # warn the user if a variable declaration shadows one from a
|
||||||
|
# parent context
|
||||||
|
-Wnon-virtual-dtor # warn the user if a class with virtual functions has a
|
||||||
|
# non-virtual destructor. This helps catch hard to
|
||||||
|
# track down memory errors
|
||||||
|
-Wold-style-cast # warn for c-style casts
|
||||||
|
-Wcast-align # warn for potential performance problem casts
|
||||||
|
-Wunused # warn on anything being unused
|
||||||
|
-Woverloaded-virtual # warn if you overload (not override) a virtual
|
||||||
|
# function
|
||||||
|
-Wpedantic # warn if non-standard C++ is used
|
||||||
|
-Wconversion # warn on type conversions that may lose data
|
||||||
|
-Wsign-conversion # warn on sign conversions
|
||||||
|
-Wnull-dereference # warn if a null dereference is detected
|
||||||
|
-Wdouble-promotion # warn if float is implicit promoted to double
|
||||||
|
-Wformat=2 # warn on security issues around functions that format output
|
||||||
|
# (ie printf)
|
||||||
|
# modified; added more errors / warnings
|
||||||
|
# some have been set to be errors, but the option _WARNINGS_AS_ERRORS
|
||||||
|
# (see below) should still be used in strict pipelines.
|
||||||
|
-Werror=uninitialized
|
||||||
|
-Werror=float-equal
|
||||||
|
-Werror=write-strings
|
||||||
|
-Werror=strict-aliasing -fstrict-aliasing
|
||||||
|
-Werror=missing-declarations
|
||||||
|
-Werror=missing-field-initializers
|
||||||
|
-Werror=ctor-dtor-privacy
|
||||||
|
-Werror=switch-enum
|
||||||
|
-Wswitch-default
|
||||||
|
-Werror=unused-result
|
||||||
|
-Werror=implicit-fallthrough
|
||||||
|
-Werror=return-type
|
||||||
|
-Wmissing-include-dirs
|
||||||
|
)
|
||||||
|
|
||||||
|
if (${PROJECT_NAME}_WARNINGS_AS_ERRORS)
|
||||||
|
set(CLANG_WARNINGS ${CLANG_WARNINGS} -Werror)
|
||||||
|
set(MSVC_WARNINGS ${MSVC_WARNINGS} /WX)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(GCC_WARNINGS
|
||||||
|
${CLANG_WARNINGS}
|
||||||
|
-Wmisleading-indentation # warn if indentation implies blocks where blocks
|
||||||
|
# do not exist
|
||||||
|
-Wduplicated-cond # warn if if / else chain has duplicated conditions
|
||||||
|
-Wduplicated-branches # warn if if / else branches have duplicated code
|
||||||
|
-Wlogical-op # warn about logical operations being used where bitwise were
|
||||||
|
# probably wanted
|
||||||
|
# -Wuseless-cast # warn if you perform a cast to the same type (modified: removed)
|
||||||
|
)
|
||||||
|
|
||||||
|
if(MSVC)
|
||||||
|
set(PRJ_WARNINGS ${MSVC_WARNINGS})
|
||||||
|
elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
|
||||||
|
set(PRJ_WARNINGS ${CLANG_WARNINGS})
|
||||||
|
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||||
|
set(PRJ_WARNINGS ${GCC_WARNINGS})
|
||||||
|
else()
|
||||||
|
message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
target_compile_options(${project_name} PUBLIC ${PRJ_WARNINGS})
|
||||||
|
|
||||||
|
if(NOT TARGET ${project_name})
|
||||||
|
message(AUTHOR_WARNING "${project_name} is not a target, thus no compiler warning were added.")
|
||||||
|
endif()
|
||||||
|
endfunction()
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
find_package(Git)
|
||||||
|
if(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES)
|
||||||
|
if(Git_FOUND)
|
||||||
|
message(STATUS "Git found, submodule update and init")
|
||||||
|
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(SEND_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules. This may result in missing dependencies.")
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
message(SEND_ERROR "git required for checking out submodules, but not found. Submodules will not be checked out - this may result in missing dependencies.")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(Git_FOUND)
|
||||||
|
|
||||||
|
else()
|
||||||
|
message(STATUS "Git not found - the version will not include a git hash.")
|
||||||
|
set(PRJ_GIT_HASH "unknown")
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Modified, original version from https://github.com/filipdutescu/modern-cpp-template (Unlicense)
|
||||||
|
|
||||||
|
option(${PROJECT_NAME}_WARNINGS_AS_ERRORS "Treat compiler warnings as errors." OFF)
|
||||||
|
option(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES "If git is found, initialize all submodules." ON)
|
||||||
|
option(${PROJECT_NAME}_ENABLE_UNIT_TESTING "Enable unit tests for the projects (from the `test` subfolder)." ON)
|
||||||
|
option(${PROJECT_NAME}_ENABLE_CLANG_TIDY "Enable static analysis with Clang-Tidy." OFF)
|
||||||
|
option(${PROJECT_NAME}_ENABLE_CPPCHECK "Enable static analysis with Cppcheck." OFF)
|
||||||
|
# TODO Implement code coverage
|
||||||
|
# option(${PROJECT_NAME}_ENABLE_CODE_COVERAGE "Enable code coverage through GCC." OFF)
|
||||||
|
option(${PROJECT_NAME}_ENABLE_DOXYGEN "Enable Doxygen documentation builds of source." OFF)
|
||||||
|
|
||||||
|
# Generate compile_commands.json for clang based tools
|
||||||
|
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||||
|
|
||||||
|
# Export all symbols when building a shared library
|
||||||
|
if(BUILD_SHARED_LIBS)
|
||||||
|
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS OFF)
|
||||||
|
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
|
||||||
|
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(${PROJECT_NAME}_ENABLE_LTO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)." OFF)
|
||||||
|
if(${PROJECT_NAME}_ENABLE_LTO)
|
||||||
|
include(CheckIPOSupported)
|
||||||
|
check_ipo_supported(RESULT result OUTPUT output)
|
||||||
|
if(result)
|
||||||
|
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||||
|
else()
|
||||||
|
message(SEND_ERROR "IPO is not supported: ${output}.")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(${PROJECT_NAME}_ENABLE_CCACHE "Enable the usage of Ccache, in order to speed up rebuild times." ON)
|
||||||
|
find_program(CCACHE_FOUND ccache)
|
||||||
|
if(CCACHE_FOUND)
|
||||||
|
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache)
|
||||||
|
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(${PROJECT_NAME}_ENABLE_SANITIZER "Enable sanitizer to detect memory errors, undefined behavior, etc. (slows down the executable)." OFF)
|
||||||
|
if(${PROJECT_NAME}_ENABLE_SANITIZER)
|
||||||
|
add_compile_options(-fsanitize=address,undefined)
|
||||||
|
add_link_options(-fsanitize=address,undefined)
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
if(${PROJECT_NAME}_ENABLE_CLANG_TIDY)
|
||||||
|
find_program(CLANGTIDY clang-tidy)
|
||||||
|
if(CLANGTIDY)
|
||||||
|
set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option)
|
||||||
|
message("Clang-Tidy finished setting up.")
|
||||||
|
else()
|
||||||
|
message(SEND_ERROR "Clang-Tidy requested but executable not found.")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(${PROJECT_NAME}_ENABLE_CPPCHECK)
|
||||||
|
find_program(CPPCHECK cppcheck)
|
||||||
|
if(CPPCHECK)
|
||||||
|
set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all
|
||||||
|
--inline-suppr --inconclusive)
|
||||||
|
message("Cppcheck finished setting up.")
|
||||||
|
else()
|
||||||
|
message(SEND_ERROR "Cppcheck requested but executable not found.")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
if(NOT DEFINED CMAKE_TOOLCHAIN_FILE)
|
||||||
|
if(NOT EXISTS ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
|
||||||
|
find_package(Git)
|
||||||
|
if(Git_FOUND)
|
||||||
|
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive vcpkg
|
||||||
|
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||||
|
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||||
|
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||||
|
message(SEND_ERROR "Checking out vcpkg in source tree failed with ${GIT_SUBMOD_RESULT}.")
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
message(FATAL_ERROR "Could not find git or vcpkg.cmake. Please either, install git and re-run cmake (or run `git submodule update --init --recursive`), or install vcpkg and add `-DCMAKE_TOOLCHAIN_FILE=<path-to-vcpkg>/scripts/buildsystems/vcpkg.cmake` to your cmake invocation. Please try again after making those changes.")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
|
||||||
|
endif()
|
||||||
|
|
||||||
+1
Submodule deps/commandline added at b2a29733f9
@@ -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;
|
||||||
|
};
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <boost/asio.hpp>
|
||||||
|
#include <boost/system/error_code.hpp>
|
||||||
|
|
||||||
|
using namespace boost::asio;
|
||||||
+33
-22
@@ -2,25 +2,26 @@
|
|||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
#include <queue>
|
#include <queue>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_set>
|
#include <unordered_set>
|
||||||
|
|
||||||
|
#include "BoostAliases.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
#include "VehicleData.h"
|
#include "VehicleData.h"
|
||||||
|
|
||||||
class TServer;
|
class TServer;
|
||||||
|
|
||||||
#ifdef WIN32
|
#ifdef BEAMMP_WINDOWS
|
||||||
// for socklen_t
|
// for socklen_t
|
||||||
#include <WS2tcpip.h>
|
#include <WS2tcpip.h>
|
||||||
#endif // WIN32
|
#endif // WINDOWS
|
||||||
|
|
||||||
struct TConnection final {
|
struct TConnection final {
|
||||||
SOCKET Socket;
|
ip::tcp::socket Socket;
|
||||||
struct sockaddr SockAddr;
|
ip::tcp::endpoint SockAddr;
|
||||||
socklen_t SockAddrLen;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
class TClient final {
|
class TClient final {
|
||||||
@@ -32,27 +33,34 @@ public:
|
|||||||
std::unique_lock<std::mutex> Lock;
|
std::unique_lock<std::mutex> Lock;
|
||||||
};
|
};
|
||||||
|
|
||||||
explicit TClient(TServer& Server);
|
TClient(TServer& Server, ip::tcp::socket&& Socket);
|
||||||
TClient(const TClient&) = delete;
|
TClient(const TClient&) = delete;
|
||||||
|
~TClient();
|
||||||
TClient& operator=(const TClient&) = delete;
|
TClient& operator=(const TClient&) = delete;
|
||||||
|
|
||||||
void AddNewCar(int Ident, const std::string& Data);
|
void AddNewCar(int Ident, const std::string& Data);
|
||||||
void SetCarData(int Ident, const std::string& Data);
|
void SetCarData(int Ident, const std::string& Data);
|
||||||
|
void SetCarPosition(int Ident, const std::string& Data);
|
||||||
TVehicleDataLockPair GetAllCars();
|
TVehicleDataLockPair GetAllCars();
|
||||||
void SetName(const std::string& Name) { mName = Name; }
|
void SetName(const std::string& Name) { mName = Name; }
|
||||||
void SetRoles(const std::string& Role) { mRole = Role; }
|
void SetRoles(const std::string& Role) { mRole = Role; }
|
||||||
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
||||||
std::string GetCarData(int Ident);
|
std::string GetCarData(int Ident);
|
||||||
void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
|
std::string GetCarPositionRaw(int Ident);
|
||||||
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
|
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; }
|
||||||
void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; }
|
void SetDownSock(ip::tcp::socket&& CSock) { mDownSocket = std::move(CSock); }
|
||||||
void SetStatus(int Status) { mStatus = Status; }
|
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); }
|
||||||
|
void Disconnect(std::string_view Reason);
|
||||||
|
bool IsDisconnected() const { return !mSocket.is_open(); }
|
||||||
// locks
|
// locks
|
||||||
void DeleteCar(int Ident);
|
void DeleteCar(int Ident);
|
||||||
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
||||||
[[nodiscard]] sockaddr_in GetUDPAddr() const { return mUDPAddress; }
|
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; }
|
||||||
[[nodiscard]] SOCKET GetDownSock() const { return mSocket[1]; }
|
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; }
|
||||||
[[nodiscard]] SOCKET GetTCPSock() const { return mSocket[0]; }
|
[[nodiscard]] ip::tcp::socket& GetDownSock() { return mDownSocket; }
|
||||||
|
[[nodiscard]] const ip::tcp::socket& GetDownSock() const { return mDownSocket; }
|
||||||
|
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
|
||||||
|
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
|
||||||
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
||||||
[[nodiscard]] std::string GetName() const { return mName; }
|
[[nodiscard]] std::string GetName() const { return mName; }
|
||||||
void SetUnicycleID(int ID) { mUnicycleID = ID; }
|
void SetUnicycleID(int ID) { mUnicycleID = ID; }
|
||||||
@@ -60,7 +68,6 @@ public:
|
|||||||
[[nodiscard]] int GetOpenCarID() const;
|
[[nodiscard]] int GetOpenCarID() const;
|
||||||
[[nodiscard]] int GetCarCount() const;
|
[[nodiscard]] int GetCarCount() const;
|
||||||
void ClearCars();
|
void ClearCars();
|
||||||
[[nodiscard]] int GetStatus() const { return mStatus; }
|
|
||||||
[[nodiscard]] int GetID() const { return mID; }
|
[[nodiscard]] int GetID() const { return mID; }
|
||||||
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
||||||
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
|
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
|
||||||
@@ -70,9 +77,9 @@ public:
|
|||||||
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
|
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
|
||||||
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
|
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
|
||||||
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
|
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
|
||||||
void EnqueuePacket(const std::string& Packet);
|
void EnqueuePacket(const std::vector<uint8_t>& Packet);
|
||||||
[[nodiscard]] std::queue<std::string>& MissedPacketQueue() { return mPacketsSync; }
|
[[nodiscard]] std::queue<std::vector<uint8_t>>& MissedPacketQueue() { return mPacketsSync; }
|
||||||
[[nodiscard]] const std::queue<std::string>& MissedPacketQueue() const { return mPacketsSync; }
|
[[nodiscard]] const std::queue<std::vector<uint8_t>>& MissedPacketQueue() const { return mPacketsSync; }
|
||||||
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
||||||
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
||||||
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
|
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
|
||||||
@@ -88,18 +95,22 @@ private:
|
|||||||
bool mIsSynced = false;
|
bool mIsSynced = false;
|
||||||
bool mIsSyncing = false;
|
bool mIsSyncing = false;
|
||||||
mutable std::mutex mMissedPacketsMutex;
|
mutable std::mutex mMissedPacketsMutex;
|
||||||
std::queue<std::string> mPacketsSync;
|
std::queue<std::vector<uint8_t>> mPacketsSync;
|
||||||
std::unordered_map<std::string, std::string> mIdentifiers;
|
std::unordered_map<std::string, std::string> mIdentifiers;
|
||||||
bool mIsGuest = false;
|
bool mIsGuest = false;
|
||||||
std::mutex mVehicleDataMutex;
|
mutable std::mutex mVehicleDataMutex;
|
||||||
|
mutable std::mutex mVehiclePositionMutex;
|
||||||
TSetOfVehicleData mVehicleData;
|
TSetOfVehicleData mVehicleData;
|
||||||
|
SparseArray<std::string> mVehiclePosition;
|
||||||
std::string mName = "Unknown Client";
|
std::string mName = "Unknown Client";
|
||||||
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
|
ip::tcp::socket mSocket;
|
||||||
sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is
|
ip::tcp::socket mDownSocket;
|
||||||
|
ip::udp::endpoint mUDPAddress {};
|
||||||
int mUnicycleID = -1;
|
int mUnicycleID = -1;
|
||||||
std::string mRole;
|
std::string mRole;
|
||||||
std::string mDID;
|
std::string mDID;
|
||||||
int mStatus = 0;
|
|
||||||
int mID = -1;
|
int mID = -1;
|
||||||
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
|
||||||
|
|||||||
+202
-48
@@ -1,18 +1,22 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "TSentry.h"
|
|
||||||
extern TSentry Sentry;
|
|
||||||
|
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
#include <deque>
|
#include <deque>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <fmt/format.h>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
|
#include <shared_mutex>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <zlib.h>
|
||||||
|
|
||||||
#include "Compat.h"
|
#include <doctest/doctest.h>
|
||||||
|
#include <filesystem>
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
#include "TConsole.h"
|
#include "TConsole.h"
|
||||||
|
|
||||||
@@ -25,6 +29,9 @@ struct Version {
|
|||||||
std::string AsString();
|
std::string AsString();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
using SparseArray = std::unordered_map<size_t, T>;
|
||||||
|
|
||||||
// static class handling application start, shutdown, etc.
|
// static class handling application start, shutdown, etc.
|
||||||
// yes, static classes, singletons, globals are all pretty
|
// yes, static classes, singletons, globals are all pretty
|
||||||
// bad idioms. In this case we need a central way to access
|
// bad idioms. In this case we need a central way to access
|
||||||
@@ -34,27 +41,29 @@ class Application final {
|
|||||||
public:
|
public:
|
||||||
// types
|
// types
|
||||||
struct TSettings {
|
struct TSettings {
|
||||||
TSettings() noexcept
|
std::string ServerName { "BeamMP Server" };
|
||||||
: ServerName("BeamMP Server")
|
std::string ServerDesc { "BeamMP Default Description" };
|
||||||
, ServerDesc("BeamMP Default Description")
|
std::string ServerTags { "Freeroam" };
|
||||||
, Resource("Resources")
|
std::string Resource { "Resources" };
|
||||||
, MapName("/levels/gridmap_v2/info.json")
|
std::string MapName { "/levels/gridmap_v2/info.json" };
|
||||||
, MaxPlayers(10)
|
std::string Key {};
|
||||||
, Private(false)
|
std::string Password{};
|
||||||
, MaxCars(1)
|
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
||||||
, DebugModeEnabled(false)
|
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
||||||
, Port(30814) { }
|
bool HTTPServerEnabled { false };
|
||||||
std::string ServerName;
|
int MaxPlayers { 8 };
|
||||||
std::string ServerDesc;
|
bool Private { true };
|
||||||
std::string Resource;
|
int MaxCars { 1 };
|
||||||
std::string MapName;
|
bool DebugModeEnabled { false };
|
||||||
std::string Key;
|
int Port { 30814 };
|
||||||
int MaxPlayers;
|
std::string CustomIP {};
|
||||||
bool Private;
|
bool LogChat { true };
|
||||||
int MaxCars;
|
bool SendErrors { true };
|
||||||
bool DebugModeEnabled;
|
bool SendErrorsMessageEnabled { true };
|
||||||
int Port;
|
int HTTPServerPort { 8080 };
|
||||||
std::string CustomIP;
|
std::string HTTPServerIP { "127.0.0.1" };
|
||||||
|
bool HTTPServerUseSSL { false };
|
||||||
|
bool HideUpdateMessages { false };
|
||||||
[[nodiscard]] bool HasCustomIP() const { return !CustomIP.empty(); }
|
[[nodiscard]] bool HasCustomIP() const { return !CustomIP.empty(); }
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -67,44 +76,89 @@ public:
|
|||||||
static void RegisterShutdownHandler(const TShutdownHandler& Handler);
|
static void RegisterShutdownHandler(const TShutdownHandler& Handler);
|
||||||
// Causes all threads to finish up and exit gracefull gracefully
|
// Causes all threads to finish up and exit gracefull gracefully
|
||||||
static void GracefullyShutdown();
|
static void GracefullyShutdown();
|
||||||
static TConsole& Console() { return *mConsole; }
|
static TConsole& Console() { return mConsole; }
|
||||||
static std::string ServerVersionString();
|
static std::string ServerVersionString();
|
||||||
static const Version& ServerVersion() { return mVersion; }
|
static const Version& ServerVersion() { return mVersion; }
|
||||||
static std::string ClientVersionString() { return "2.0"; }
|
static uint8_t ClientMajorVersion() { return 2; }
|
||||||
static std::string PPS() { return mPPS; }
|
static std::string PPS() { return mPPS; }
|
||||||
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
||||||
|
|
||||||
static inline TSettings Settings {};
|
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 GetBackendUrlForAuth() { return "auth.beammp.com"; }
|
||||||
static std::string GetBackendHostname() { return "backend.beammp.com"; }
|
|
||||||
static std::string GetBackup1Hostname() { return "backup1.beammp.com"; }
|
|
||||||
static std::string GetBackup2Hostname() { return "backup2.beammp.com"; }
|
|
||||||
static std::string GetBackendUrlForSocketIO() { return "https://backend.beammp.com"; }
|
static std::string GetBackendUrlForSocketIO() { return "https://backend.beammp.com"; }
|
||||||
static void CheckForUpdates();
|
static void CheckForUpdates();
|
||||||
static std::array<uint8_t, 3> VersionStrToInts(const std::string& str);
|
static std::array<uint8_t, 3> VersionStrToInts(const std::string& str);
|
||||||
static bool IsOutdated(const Version& Current, const Version& Newest);
|
static bool IsOutdated(const Version& Current, const Version& Newest);
|
||||||
|
static bool IsShuttingDown();
|
||||||
|
static void SleepSafeSeconds(size_t Seconds);
|
||||||
|
|
||||||
|
static void InitializeConsole() {
|
||||||
|
mConsole.InitializeCommandline();
|
||||||
|
}
|
||||||
|
|
||||||
|
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:
|
private:
|
||||||
|
static void SetShutdown(bool Val);
|
||||||
|
|
||||||
|
static inline SystemStatusMap mSystemStatusMap {};
|
||||||
|
static inline std::mutex mSystemStatusMapMutex {};
|
||||||
static inline std::string mPPS;
|
static inline std::string mPPS;
|
||||||
static std::unique_ptr<TConsole> mConsole;
|
static inline TConsole mConsole;
|
||||||
|
static inline std::shared_mutex mShutdownMtx {};
|
||||||
|
static inline bool mShutdown { false };
|
||||||
static inline std::mutex mShutdownHandlersMutex {};
|
static inline std::mutex mShutdownHandlersMutex {};
|
||||||
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
|
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
|
||||||
|
|
||||||
static inline Version mVersion { 2, 4, 0 };
|
static inline Version mVersion { 3, 2, 0 };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
void SplitString(std::string const& str, const char delim, std::vector<std::string>& out);
|
||||||
|
|
||||||
std::string ThreadName(bool DebugModeOverride = false);
|
std::string ThreadName(bool DebugModeOverride = false);
|
||||||
void RegisterThread(const std::string& str);
|
void RegisterThread(const std::string& str);
|
||||||
#define RegisterThreadAuto() RegisterThread(__func__)
|
#define RegisterThreadAuto() RegisterThread(__func__)
|
||||||
|
|
||||||
#define KB 1024
|
#define KB 1024llu
|
||||||
#define MB (KB * 1024)
|
#define MB (KB * 1024llu)
|
||||||
|
#define GB (MB * 1024llu)
|
||||||
|
#define SSU_UNRAW SECRET_SENTRY_URL
|
||||||
|
|
||||||
#define _file_basename std::filesystem::path(__FILE__).filename().string()
|
#define _file_basename std::filesystem::path(__FILE__).filename().string()
|
||||||
#define _line std::to_string(__LINE__)
|
#define _line std::to_string(__LINE__)
|
||||||
#define _in_lambda (std::string(__func__) == "operator()")
|
#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'
|
// we would like the full function signature 'void a::foo() const'
|
||||||
// on windows this is __FUNCSIG__, on GCC it's __PRETTY_FUNCTION__,
|
// on windows this is __FUNCSIG__, on GCC it's __PRETTY_FUNCTION__,
|
||||||
// feel free to add more
|
// feel free to add more
|
||||||
@@ -116,6 +170,10 @@ void RegisterThread(const std::string& str);
|
|||||||
#define _function_name std::string(__func__)
|
#define _function_name std::string(__func__)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#ifndef NDEBUG
|
||||||
|
#define DEBUG
|
||||||
|
#endif
|
||||||
|
|
||||||
#if defined(DEBUG)
|
#if defined(DEBUG)
|
||||||
|
|
||||||
// if this is defined, we will show the full function signature infront of
|
// if this is defined, we will show the full function signature infront of
|
||||||
@@ -126,42 +184,138 @@ void RegisterThread(const std::string& str);
|
|||||||
#define _this_location (ThreadName() + _file_basename + ":" + _line + " ")
|
#define _this_location (ThreadName() + _file_basename + ":" + _line + " ")
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#else // !defined(DEBUG)
|
|
||||||
|
|
||||||
#define _this_location (ThreadName())
|
|
||||||
|
|
||||||
#endif // defined(DEBUG)
|
#endif // defined(DEBUG)
|
||||||
|
|
||||||
#define warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
|
#define beammp_warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
|
||||||
#define info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
|
#define beammp_info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
|
||||||
#define error(x) \
|
#define beammp_error(x) \
|
||||||
do { \
|
do { \
|
||||||
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
|
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)
|
} while (false)
|
||||||
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
|
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
|
||||||
#define debug(x) \
|
#define beammp_debug(x) \
|
||||||
do { \
|
do { \
|
||||||
if (Application::Settings.DebugModeEnabled) { \
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} 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()
|
// trace() is a debug-build debug()
|
||||||
#if defined(DEBUG)
|
#if defined(DEBUG)
|
||||||
#define trace(x) \
|
#define beammp_trace(x) \
|
||||||
do { \
|
do { \
|
||||||
if (Application::Settings.DebugModeEnabled) { \
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
#else
|
#else
|
||||||
#define trace(x)
|
#define beammp_trace(x)
|
||||||
#endif // defined(DEBUG)
|
#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);
|
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||||
|
|
||||||
#define Biggest 30000
|
#define Biggest 30000
|
||||||
std::string Comp(std::string Data);
|
|
||||||
std::string DeComp(std::string Compressed);
|
template <typename T>
|
||||||
|
inline T Comp(const T& Data) {
|
||||||
|
std::array<char, Biggest> C {};
|
||||||
|
// obsolete
|
||||||
|
C.fill(0);
|
||||||
|
z_stream defstream;
|
||||||
|
defstream.zalloc = nullptr;
|
||||||
|
defstream.zfree = nullptr;
|
||||||
|
defstream.opaque = nullptr;
|
||||||
|
defstream.avail_in = uInt(Data.size());
|
||||||
|
defstream.next_in = const_cast<Bytef*>(reinterpret_cast<const 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 = nullptr;
|
||||||
|
infstream.zfree = nullptr;
|
||||||
|
infstream.opaque = nullptr;
|
||||||
|
infstream.avail_in = Biggest;
|
||||||
|
infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
|
||||||
|
infstream.avail_out = Biggest;
|
||||||
|
infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const 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();
|
std::string GetPlatformAgnosticErrorString();
|
||||||
|
#define S_DSN SU_RAW
|
||||||
|
|||||||
+15
-26
@@ -1,38 +1,27 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include "Environment.h"
|
||||||
|
|
||||||
// ======================= UNIX ========================
|
// ======================= UNIX ========================
|
||||||
|
|
||||||
#ifdef __unix
|
#ifdef BEAMMP_LINUX
|
||||||
#include <arpa/inet.h>
|
#include <errno.h>
|
||||||
#include <sys/socket.h>
|
|
||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
#include <errno.h>
|
|
||||||
using SOCKET = int;
|
|
||||||
using DWORD = unsigned long;
|
|
||||||
using PDWORD = unsigned long*;
|
|
||||||
using LPDWORD = unsigned long*;
|
|
||||||
char _getch();
|
char _getch();
|
||||||
inline void CloseSocketProper(int TheSocket) {
|
|
||||||
shutdown(TheSocket, SHUT_RDWR);
|
|
||||||
close(TheSocket);
|
|
||||||
}
|
|
||||||
#endif // unix
|
#endif // unix
|
||||||
|
|
||||||
// ======================= WIN32 =======================
|
// ======================= APPLE ========================
|
||||||
|
|
||||||
#ifdef WIN32
|
#ifdef BEAMMP_APPLE
|
||||||
|
#include <errno.h>
|
||||||
|
#include <termios.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
char _getch();
|
||||||
|
#endif // unix
|
||||||
|
|
||||||
|
// ======================= WINDOWS =======================
|
||||||
|
|
||||||
|
#ifdef BEAMMP_WINDOWS
|
||||||
#include <conio.h>
|
#include <conio.h>
|
||||||
#include <winsock2.h>
|
|
||||||
inline void CloseSocketProper(SOCKET TheSocket) {
|
|
||||||
shutdown(TheSocket, 2); // 2 == SD_BOTH
|
|
||||||
closesocket(TheSocket);
|
|
||||||
|
|
||||||
}
|
|
||||||
#endif // WIN32
|
#endif // WIN32
|
||||||
|
|
||||||
// ======================= OTHER =======================
|
|
||||||
|
|
||||||
#if !defined(WIN32) && !defined(__unix)
|
|
||||||
#error "OS not supported"
|
|
||||||
#endif
|
|
||||||
@@ -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)
|
||||||
|
|
||||||
|
}
|
||||||
@@ -55,19 +55,18 @@ inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const ch
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#define Assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
#define beammp_assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
||||||
#define AssertNotReachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
#define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
||||||
#else
|
#else
|
||||||
// In release build, these macros turn into NOPs. The compiler will optimize these out.
|
#define beammp_assert(cond) \
|
||||||
#define Assert(cond) \
|
|
||||||
do { \
|
do { \
|
||||||
bool result = (cond); \
|
bool result = (cond); \
|
||||||
if (!result) { \
|
if (!result) { \
|
||||||
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
|
beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
#define AssertNotReachable() \
|
#define beammp_assert_not_reachable() \
|
||||||
do { \
|
do { \
|
||||||
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
|
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
|
||||||
} while (false)
|
} while (false)
|
||||||
#endif // DEBUG
|
#endif // DEBUG
|
||||||
|
|||||||
@@ -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
|
||||||
+30
-1
@@ -1,13 +1,42 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <Common.h>
|
||||||
|
#include <IThreaded.h>
|
||||||
|
#include <filesystem>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
|
||||||
|
#if defined(BEAMMP_LINUX)
|
||||||
|
#pragma GCC diagnostic push
|
||||||
|
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
|
||||||
|
#pragma GCC diagnostic ignored "-Wcast-qual"
|
||||||
|
#pragma GCC diagnostic ignored "-Wold-style-cast"
|
||||||
|
#endif
|
||||||
|
#include <httplib.h>
|
||||||
|
#if defined(BEAMMP_LINUX)
|
||||||
|
#pragma GCC diagnostic pop
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
namespace Http {
|
namespace Http {
|
||||||
std::string GET(const std::string& host, int port, const std::string& target, unsigned int* status = nullptr);
|
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::unordered_map<std::string, std::string>& fields, const std::string& body, const std::string& ContentType, 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 {
|
namespace Status {
|
||||||
std::string ToString(int code);
|
std::string ToString(int code);
|
||||||
}
|
}
|
||||||
const std::string ErrorString = "-1";
|
const std::string ErrorString = "-1";
|
||||||
|
|
||||||
|
namespace Server {
|
||||||
|
class THttpServerInstance {
|
||||||
|
public:
|
||||||
|
THttpServerInstance();
|
||||||
|
|
||||||
|
protected:
|
||||||
|
void operator()();
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::thread mThread;
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,11 @@ public:
|
|||||||
IThreaded()
|
IThreaded()
|
||||||
// invokes operator() on this object
|
// invokes operator() on this object
|
||||||
: mThread() { }
|
: mThread() { }
|
||||||
|
virtual ~IThreaded() noexcept {
|
||||||
|
if (mThread.joinable()) {
|
||||||
|
mThread.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
virtual void Start() final {
|
virtual void Start() final {
|
||||||
mThread = std::thread([this] { (*this)(); });
|
mThread = std::thread([this] { (*this)(); });
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
void SetupSignalHandlers();
|
||||||
+14
-3
@@ -3,21 +3,32 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
|
#include <filesystem>
|
||||||
|
|
||||||
|
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
|
||||||
|
#include <toml.hpp> // header-only version of TOML++
|
||||||
|
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
class TConfig {
|
class TConfig {
|
||||||
public:
|
public:
|
||||||
explicit TConfig();
|
explicit TConfig(const std::string& ConfigFileName);
|
||||||
|
|
||||||
[[nodiscard]] bool Failed() const { return mFailed; }
|
[[nodiscard]] bool Failed() const { return mFailed; }
|
||||||
|
|
||||||
void FlushToFile();
|
void FlushToFile();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void CreateConfigFile(std::string_view name);
|
void CreateConfigFile();
|
||||||
void ParseFromFile(std::string_view name);
|
void ParseFromFile(std::string_view name);
|
||||||
void PrintDebug();
|
void PrintDebug();
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue);
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue);
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue);
|
||||||
|
|
||||||
void ParseOldFormat();
|
void ParseOldFormat();
|
||||||
|
std::string TagsAsPrettyArray() const;
|
||||||
|
bool IsDefault();
|
||||||
bool mFailed { false };
|
bool mFailed { false };
|
||||||
|
std::string mConfigFileName;
|
||||||
};
|
};
|
||||||
|
|||||||
+57
-4
@@ -1,19 +1,72 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "commandline/commandline.h"
|
#include "Cryptography.h"
|
||||||
#include "TLuaFile.h"
|
#include "commandline.h"
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
|
#include <functional>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
#include <tuple>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class TLuaEngine;
|
||||||
|
|
||||||
class TConsole {
|
class TConsole {
|
||||||
public:
|
public:
|
||||||
TConsole();
|
TConsole();
|
||||||
|
|
||||||
|
// Initializes the commandline app to take over I/O
|
||||||
|
void InitializeCommandline();
|
||||||
|
|
||||||
void Write(const std::string& str);
|
void Write(const std::string& str);
|
||||||
void WriteRaw(const std::string& str);
|
void WriteRaw(const std::string& str);
|
||||||
void InitializeLuaConsole(TLuaEngine& Engine);
|
void InitializeLuaConsole(TLuaEngine& Engine);
|
||||||
|
void BackupOldLog();
|
||||||
|
void StartLoggingToFile();
|
||||||
|
Commandline& Internal() { return *mCommandline; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
std::unique_ptr<TLuaFile> mLuaConsole { nullptr };
|
void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false);
|
||||||
Commandline mCommandline;
|
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
|
||||||
|
};
|
||||||
|
|
||||||
|
std::unique_ptr<Commandline> mCommandline { nullptr };
|
||||||
|
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;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ private:
|
|||||||
std::string GenerateCall();
|
std::string GenerateCall();
|
||||||
std::string GetPlayers();
|
std::string GetPlayers();
|
||||||
|
|
||||||
bool mShutdown = false;
|
|
||||||
TResourceManager& mResourceManager;
|
TResourceManager& mResourceManager;
|
||||||
TServer& mServer;
|
TServer& mServer;
|
||||||
};
|
};
|
||||||
|
|||||||
+262
-23
@@ -1,41 +1,280 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Common.h"
|
#include "TNetwork.h"
|
||||||
#include "IThreaded.h"
|
|
||||||
#include "TLuaFile.h"
|
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
#include <optional>
|
#include <any>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <initializer_list>
|
||||||
|
#include <list>
|
||||||
#include <lua.hpp>
|
#include <lua.hpp>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <queue>
|
||||||
|
#include <random>
|
||||||
#include <set>
|
#include <set>
|
||||||
|
#include <toml.hpp>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
class TLuaEngine : public IThreaded {
|
#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, std::unordered_map<std::string, std::string>>;
|
||||||
|
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;
|
||||||
|
static constexpr size_t TLuaArgTypes_StringStringMap = 4;
|
||||||
|
|
||||||
|
class TLuaPlugin;
|
||||||
|
|
||||||
|
struct TLuaResult {
|
||||||
|
bool Ready;
|
||||||
|
bool Error;
|
||||||
|
std::string ErrorMessage;
|
||||||
|
sol::object Result { sol::lua_nil };
|
||||||
|
TLuaStateId StateId;
|
||||||
|
std::string Function;
|
||||||
|
std::shared_ptr<std::mutex> ReadyMutex {
|
||||||
|
std::make_shared<std::mutex>()
|
||||||
|
};
|
||||||
|
std::shared_ptr<std::condition_variable> ReadyCondition {
|
||||||
|
std::make_shared<std::condition_variable>()
|
||||||
|
};
|
||||||
|
|
||||||
|
void MarkAsReady();
|
||||||
|
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:
|
public:
|
||||||
explicit TLuaEngine(TServer& Server, TNetwork& Network);
|
enum CallStrategy : int {
|
||||||
|
BestEffort,
|
||||||
|
Precise,
|
||||||
|
};
|
||||||
|
|
||||||
using TSetOfLuaFile = std::set<std::unique_ptr<TLuaFile>>;
|
struct QueuedFunction {
|
||||||
|
std::string FunctionName;
|
||||||
|
std::shared_ptr<TLuaResult> Result;
|
||||||
|
std::vector<TLuaArgTypes> Args;
|
||||||
|
std::string EventName; // optional, may be empty
|
||||||
|
};
|
||||||
|
|
||||||
|
TLuaEngine();
|
||||||
|
virtual ~TLuaEngine() noexcept {
|
||||||
|
beammp_debug("Lua Engine terminated");
|
||||||
|
}
|
||||||
|
|
||||||
void operator()() override;
|
void operator()() override;
|
||||||
|
|
||||||
[[nodiscard]] const TSetOfLuaFile& LuaFiles() const { return mLuaFiles; }
|
TNetwork& Network() { return *mNetwork; }
|
||||||
[[nodiscard]] TServer& Server() { return mServer; }
|
TServer& Server() { return *mServer; }
|
||||||
[[nodiscard]] const TServer& Server() const { return mServer; }
|
|
||||||
[[nodiscard]] TNetwork& Network() { return mNetwork; }
|
|
||||||
[[nodiscard]] const TNetwork& Network() const { return mNetwork; }
|
|
||||||
|
|
||||||
std::optional<std::reference_wrapper<TLuaFile>> GetScript(lua_State* L);
|
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);
|
||||||
|
|
||||||
static std::unordered_map<std::string, lua_State*> mGlobals;
|
|
||||||
private:
|
private:
|
||||||
void FolderList(const std::string& Path, bool HotSwap);
|
void CollectAndInitPlugins();
|
||||||
void RegisterFiles(const fs::path& Path, bool HotSwap);
|
void InitializePlugin(const fs::path& Folder, const TLuaPluginConfig& Config);
|
||||||
bool IsNewFile(const std::string& Path);
|
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
|
||||||
|
size_t CalculateMemoryUsage();
|
||||||
|
|
||||||
TNetwork& mNetwork;
|
class StateThreadData : IThreaded {
|
||||||
TServer& mServer;
|
public:
|
||||||
std::string mPath;
|
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
||||||
bool mShutdown { false };
|
StateThreadData(const StateThreadData&) = delete;
|
||||||
TSetOfLuaFile mLuaFiles;
|
virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
||||||
std::mutex mListMutex;
|
[[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);
|
||||||
|
|||||||
@@ -1,63 +0,0 @@
|
|||||||
#ifndef TLUAFILE_H
|
|
||||||
#define TLUAFILE_H
|
|
||||||
|
|
||||||
#include <any>
|
|
||||||
#include <filesystem>
|
|
||||||
#include <lua.hpp>
|
|
||||||
#include <mutex>
|
|
||||||
#include <set>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace fs = std::filesystem;
|
|
||||||
|
|
||||||
struct TLuaArg {
|
|
||||||
std::vector<std::any> args;
|
|
||||||
void PushArgs(lua_State* State);
|
|
||||||
};
|
|
||||||
|
|
||||||
class TLuaEngine;
|
|
||||||
|
|
||||||
class TLuaFile {
|
|
||||||
public:
|
|
||||||
void RegisterEvent(const std::string& Event, const std::string& FunctionName);
|
|
||||||
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();
|
|
||||||
lua_State* GetState();
|
|
||||||
std::string GetOrigin();
|
|
||||||
std::mutex Lock;
|
|
||||||
void Reload();
|
|
||||||
void Init(const std::string& PluginName, const std::string& FileName, fs::file_time_type LastWrote);
|
|
||||||
explicit TLuaFile(TLuaEngine& Engine, bool Console = false);
|
|
||||||
~TLuaFile();
|
|
||||||
void SetStopThread(bool StopThread) { mStopThread = StopThread; }
|
|
||||||
TLuaEngine& Engine() { return mEngine; }
|
|
||||||
std::string GetPluginPath() const;
|
|
||||||
std::string GetPluginName() const;
|
|
||||||
std::string GetFileName() const;
|
|
||||||
const lua_State* GetState() const;
|
|
||||||
bool GetStopThread() const { return mStopThread; }
|
|
||||||
const TLuaEngine& Engine() const { return mEngine; }
|
|
||||||
std::string GetRegistered(const std::string& Event) const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
TLuaEngine& mEngine;
|
|
||||||
std::set<std::pair<std::string, std::string>> mRegisteredEvents;
|
|
||||||
lua_State* mLuaState { nullptr };
|
|
||||||
fs::file_time_type mLastWrote;
|
|
||||||
std::string mPluginName {};
|
|
||||||
std::string mFileName {};
|
|
||||||
bool mStopThread = false;
|
|
||||||
bool mConsole = false;
|
|
||||||
void Load();
|
|
||||||
std::mutex mInitMutex;
|
|
||||||
};
|
|
||||||
|
|
||||||
std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaFile* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
|
|
||||||
|
|
||||||
#endif // TLUAFILE_H
|
|
||||||
@@ -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;
|
||||||
|
};
|
||||||
+22
-17
@@ -1,8 +1,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include "BoostAliases.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
#include "TResourceManager.h"
|
#include "TResourceManager.h"
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
|
#include <boost/asio/io_context.hpp>
|
||||||
|
#include <boost/asio/ip/udp.hpp>
|
||||||
|
|
||||||
struct TConnection;
|
struct TConnection;
|
||||||
|
|
||||||
@@ -10,19 +13,18 @@ class TNetwork {
|
|||||||
public:
|
public:
|
||||||
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
||||||
|
|
||||||
[[nodiscard]] bool TCPSend(TClient& c, const std::string& Data, bool IsSync = false);
|
[[nodiscard]] bool TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync = false);
|
||||||
[[nodiscard]] bool SendLarge(TClient& c, std::string Data, bool isSync = false);
|
[[nodiscard]] bool SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync = false);
|
||||||
[[nodiscard]] bool Respond(TClient& c, const std::string& MSG, bool Rel, bool isSync = false);
|
[[nodiscard]] bool Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync = false);
|
||||||
std::shared_ptr<TClient> CreateClient(SOCKET TCPSock);
|
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
|
||||||
std::string TCPRcv(TClient& c);
|
std::vector<uint8_t> TCPRcv(TClient& c);
|
||||||
void ClientKick(TClient& c, const std::string& R);
|
void ClientKick(TClient& c, const std::string& R);
|
||||||
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
||||||
void Identify(const TConnection& client);
|
void Identify(TConnection&& client);
|
||||||
void Authentication(const TConnection& ClientConnection);
|
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
|
||||||
[[nodiscard]] bool CheckBytes(TClient& c, int32_t BytesRcv);
|
|
||||||
void SyncResources(TClient& c);
|
void SyncResources(TClient& c);
|
||||||
[[nodiscard]] bool UDPSend(TClient& Client, std::string Data) const;
|
[[nodiscard]] bool UDPSend(TClient& Client, std::vector<uint8_t> Data);
|
||||||
void SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel);
|
void SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel);
|
||||||
void UpdatePlayer(TClient& Client);
|
void UpdatePlayer(TClient& Client);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -31,21 +33,24 @@ private:
|
|||||||
|
|
||||||
TServer& mServer;
|
TServer& mServer;
|
||||||
TPPSMonitor& mPPSMonitor;
|
TPPSMonitor& mPPSMonitor;
|
||||||
SOCKET mUDPSock {};
|
ip::udp::socket mUDPSock;
|
||||||
bool mShutdown { false };
|
|
||||||
TResourceManager& mResourceManager;
|
TResourceManager& mResourceManager;
|
||||||
std::thread mUDPThread;
|
std::thread mUDPThread;
|
||||||
std::thread mTCPThread;
|
std::thread mTCPThread;
|
||||||
|
|
||||||
std::string UDPRcvFromClient(sockaddr_in& client) const;
|
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
|
||||||
void HandleDownload(SOCKET TCPSock);
|
void HandleDownload(TConnection&& TCPSock);
|
||||||
void OnConnect(const std::weak_ptr<TClient>& c);
|
void OnConnect(const std::weak_ptr<TClient>& c);
|
||||||
void TCPClient(const std::weak_ptr<TClient>& c);
|
void TCPClient(const std::weak_ptr<TClient>& c);
|
||||||
void Looper(const std::weak_ptr<TClient>& c);
|
void Looper(const std::weak_ptr<TClient>& c);
|
||||||
int OpenID();
|
int OpenID();
|
||||||
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked);
|
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
|
||||||
void Parse(TClient& c, const std::string& Packet);
|
void Parse(TClient& c, const std::vector<uint8_t>& Packet);
|
||||||
void SendFile(TClient& c, const std::string& Name);
|
void SendFile(TClient& c, const std::string& Name);
|
||||||
static bool TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size);
|
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
|
||||||
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
||||||
|
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
std::string HashPassword(const std::string& str);
|
||||||
|
std::vector<uint8_t> StringToVector(const std::string& Str);
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ class TNetwork;
|
|||||||
class TPPSMonitor : public IThreaded {
|
class TPPSMonitor : public IThreaded {
|
||||||
public:
|
public:
|
||||||
explicit TPPSMonitor(TServer& Server);
|
explicit TPPSMonitor(TServer& Server);
|
||||||
|
virtual ~TPPSMonitor() {}
|
||||||
|
|
||||||
void operator()() override;
|
void operator()() override;
|
||||||
|
|
||||||
@@ -22,6 +23,5 @@ private:
|
|||||||
|
|
||||||
TServer& mServer;
|
TServer& mServer;
|
||||||
std::optional<std::reference_wrapper<TNetwork>> mNetwork { std::nullopt };
|
std::optional<std::reference_wrapper<TNetwork>> mNetwork { std::nullopt };
|
||||||
bool mShutdown { false };
|
|
||||||
int mInternalPPS { 0 };
|
int mInternalPPS { 0 };
|
||||||
};
|
};
|
||||||
@@ -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;
|
||||||
|
};
|
||||||
@@ -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;
|
||||||
|
};
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
#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
|
|
||||||
+21
-3
@@ -2,11 +2,14 @@
|
|||||||
|
|
||||||
#include "IThreaded.h"
|
#include "IThreaded.h"
|
||||||
#include "RWMutex.h"
|
#include "RWMutex.h"
|
||||||
|
#include "TScopedTimer.h"
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <unordered_set>
|
#include <unordered_set>
|
||||||
|
|
||||||
|
#include "BoostAliases.h"
|
||||||
|
|
||||||
class TClient;
|
class TClient;
|
||||||
class TNetwork;
|
class TNetwork;
|
||||||
class TPPSMonitor;
|
class TPPSMonitor;
|
||||||
@@ -15,23 +18,38 @@ class TServer final {
|
|||||||
public:
|
public:
|
||||||
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
|
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
|
||||||
|
|
||||||
TServer(int argc, char** argv);
|
TServer(const std::vector<std::string_view>& Arguments);
|
||||||
|
|
||||||
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
||||||
std::weak_ptr<TClient> InsertNewClient();
|
|
||||||
void RemoveClient(const std::weak_ptr<TClient>&);
|
void RemoveClient(const std::weak_ptr<TClient>&);
|
||||||
// in Fn, return true to continue, return false to break
|
// in Fn, return true to continue, return false to break
|
||||||
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
||||||
size_t ClientCount() const;
|
size_t ClientCount() const;
|
||||||
|
|
||||||
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
||||||
static void HandleEvent(TClient& c, const std::string& Data);
|
static void HandleEvent(TClient& c, const std::string& Data);
|
||||||
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
||||||
|
|
||||||
|
const TScopedTimer UptimeTimer;
|
||||||
|
|
||||||
|
// asio io context
|
||||||
|
io_context& IoCtx() { return mIoCtx; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
io_context mIoCtx {};
|
||||||
TClientSet mClients;
|
TClientSet mClients;
|
||||||
mutable RWMutex mClientsMutex;
|
mutable RWMutex mClientsMutex;
|
||||||
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
||||||
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
|
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
|
||||||
static bool IsUnicycle(TClient& c, const std::string& CarJson);
|
static bool IsUnicycle(TClient& c, const std::string& CarJson);
|
||||||
static void Apply(TClient& c, int VID, const std::string& pckt);
|
static void Apply(TClient& c, int VID, const std::string& pckt);
|
||||||
|
static void HandlePosition(TClient& c, const std::string& Packet);
|
||||||
|
};
|
||||||
|
|
||||||
|
struct BufferView {
|
||||||
|
uint8_t* Data { nullptr };
|
||||||
|
size_t Size { 0 };
|
||||||
|
const uint8_t* data() const { return Data; }
|
||||||
|
uint8_t* data() { return Data; }
|
||||||
|
size_t size() const { return Size; }
|
||||||
};
|
};
|
||||||
|
|||||||
Submodule include/commandline deleted from c34703df11
Submodule include/sentry-native deleted from 521860373d
Submodule include/toml11 deleted from 647381020e
-1
Submodule rapidjson deleted from 13dfc96c9c
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
git config --global --add safe.directory $(pwd)
|
||||||
|
git config --global --add safe.directory $(pwd)/vcpkg
|
||||||
|
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server-tests
|
||||||
Executable
+10
@@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server
|
||||||
|
|
||||||
|
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
|
||||||
|
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
|
||||||
|
|
||||||
|
strip -s bin/BeamMP-Server
|
||||||
Executable
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 curl
|
||||||
|
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
git config --global --add safe.directory $(pwd)
|
||||||
|
git config --global --add safe.directory $(pwd)/vcpkg
|
||||||
|
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server-tests
|
||||||
Executable
+10
@@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server
|
||||||
|
|
||||||
|
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
|
||||||
|
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
|
||||||
|
|
||||||
|
strip -s bin/BeamMP-Server
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 curl
|
||||||
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server-tests
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server --config Release
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
-5
@@ -1,11 +1,12 @@
|
|||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
|
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
|
#include "TServer.h"
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
// FIXME: add debug prints
|
|
||||||
|
|
||||||
void TClient::DeleteCar(int Ident) {
|
void TClient::DeleteCar(int Ident) {
|
||||||
|
// TODO: Send delete packets
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
std::unique_lock lock(mVehicleDataMutex);
|
||||||
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
|
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
|
||||||
return Ident == elem.ID();
|
return Ident == elem.ID();
|
||||||
@@ -13,7 +14,7 @@ void TClient::DeleteCar(int Ident) {
|
|||||||
if (iter != mVehicleData.end()) {
|
if (iter != mVehicleData.end()) {
|
||||||
mVehicleData.erase(iter);
|
mVehicleData.erase(iter);
|
||||||
} else {
|
} else {
|
||||||
debug("tried to erase a vehicle that doesn't exist (not an error)");
|
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,6 +26,7 @@ void TClient::ClearCars() {
|
|||||||
int TClient::GetOpenCarID() const {
|
int TClient::GetOpenCarID() const {
|
||||||
int OpenID = 0;
|
int OpenID = 0;
|
||||||
bool found;
|
bool found;
|
||||||
|
std::unique_lock lock(mVehicleDataMutex);
|
||||||
do {
|
do {
|
||||||
found = true;
|
found = true;
|
||||||
for (auto& v : mVehicleData) {
|
for (auto& v : mVehicleData) {
|
||||||
@@ -46,6 +48,34 @@ TClient::TVehicleDataLockPair TClient::GetAllCars() {
|
|||||||
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
|
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::string TClient::GetCarPositionRaw(int Ident) {
|
||||||
|
std::unique_lock lock(mVehiclePositionMutex);
|
||||||
|
try {
|
||||||
|
return mVehiclePosition.at(size_t(Ident));
|
||||||
|
} catch (const std::out_of_range& oor) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
void TClient::Disconnect(std::string_view Reason) {
|
||||||
|
beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason);
|
||||||
|
boost::system::error_code ec;
|
||||||
|
mSocket.shutdown(socket_base::shutdown_both, ec);
|
||||||
|
if (ec) {
|
||||||
|
beammp_debugf("Failed to shutdown client socket: {}", ec.message());
|
||||||
|
}
|
||||||
|
mSocket.close(ec);
|
||||||
|
if (ec) {
|
||||||
|
beammp_debugf("Failed to close client socket: {}", ec.message());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
||||||
|
std::unique_lock lock(mVehiclePositionMutex);
|
||||||
|
mVehiclePosition[size_t(Ident)] = Data;
|
||||||
|
}
|
||||||
|
|
||||||
std::string TClient::GetCarData(int Ident) {
|
std::string TClient::GetCarData(int Ident) {
|
||||||
{ // lock
|
{ // lock
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
std::unique_lock lock(mVehicleDataMutex);
|
||||||
@@ -80,16 +110,22 @@ TServer& TClient::Server() const {
|
|||||||
return mServer;
|
return mServer;
|
||||||
}
|
}
|
||||||
|
|
||||||
void TClient::EnqueuePacket(const std::string& Packet) {
|
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
|
||||||
std::unique_lock Lock(mMissedPacketsMutex);
|
std::unique_lock Lock(mMissedPacketsMutex);
|
||||||
mPacketsSync.push(Packet);
|
mPacketsSync.push(Packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
TClient::TClient(TServer& Server)
|
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
|
||||||
: mServer(Server)
|
: mServer(Server)
|
||||||
|
, mSocket(std::move(Socket))
|
||||||
|
, mDownSocket(ip::tcp::socket(Server.IoCtx()))
|
||||||
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TClient::~TClient() {
|
||||||
|
beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName());
|
||||||
|
}
|
||||||
|
|
||||||
void TClient::UpdatePingTime() {
|
void TClient::UpdatePingTime() {
|
||||||
mLastPingTime = std::chrono::high_resolution_clock::now();
|
mLastPingTime = std::chrono::high_resolution_clock::now();
|
||||||
}
|
}
|
||||||
@@ -99,3 +135,19 @@ int TClient::SecondsSinceLastPing() {
|
|||||||
.count();
|
.count();
|
||||||
return int(seconds);
|
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;
|
||||||
|
}
|
||||||
|
|||||||
+222
-62
@@ -8,12 +8,12 @@
|
|||||||
#include <regex>
|
#include <regex>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
#include <zlib.h>
|
|
||||||
|
|
||||||
|
#include "Compat.h"
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
|
||||||
std::unique_ptr<TConsole> Application::mConsole = std::make_unique<TConsole>();
|
Application::TSettings Application::Settings = {};
|
||||||
|
|
||||||
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
||||||
std::unique_lock Lock(mShutdownHandlersMutex);
|
std::unique_lock Lock(mShutdownHandlersMutex);
|
||||||
@@ -23,11 +23,29 @@ void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Application::GracefullyShutdown() {
|
void Application::GracefullyShutdown() {
|
||||||
info("please wait while all subsystems are shutting down...");
|
SetShutdown(true);
|
||||||
std::unique_lock Lock(mShutdownHandlersMutex);
|
static bool AlreadyShuttingDown = false;
|
||||||
for (auto& Handler : mShutdownHandlers) {
|
static uint8_t ShutdownAttempts = 0;
|
||||||
Handler();
|
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() {
|
std::string Application::ServerVersionString() {
|
||||||
@@ -45,7 +63,23 @@ std::array<uint8_t, 3> Application::VersionStrToInts(const std::string& str) {
|
|||||||
return Version;
|
return Version;
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXME: This should be used by operator< on 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) {
|
bool Application::IsOutdated(const Version& Current, const Version& Newest) {
|
||||||
if (Newest.major > Current.major) {
|
if (Newest.major > Current.major) {
|
||||||
return true;
|
return true;
|
||||||
@@ -58,71 +92,138 @@ bool Application::IsOutdated(const Version& Current, const Version& Newest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
|
}
|
||||||
|
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() {
|
void Application::CheckForUpdates() {
|
||||||
|
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Starting);
|
||||||
|
static bool FirstTime = true;
|
||||||
// checks current version against latest version
|
// checks current version against latest version
|
||||||
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
||||||
auto Response = Http::GET(GetBackendHostname(), 443, "/v/s");
|
for (const auto& url : GetBackendUrlsInOrder()) {
|
||||||
|
auto Response = Http::GET(url, 443, "/v/s");
|
||||||
bool Matches = std::regex_match(Response, VersionRegex);
|
bool Matches = std::regex_match(Response, VersionRegex);
|
||||||
if (Matches) {
|
if (Matches) {
|
||||||
auto MyVersion = ServerVersion();
|
auto MyVersion = ServerVersion();
|
||||||
auto RemoteVersion = Version(VersionStrToInts(Response));
|
auto RemoteVersion = Version(VersionStrToInts(Response));
|
||||||
if (IsOutdated(MyVersion, RemoteVersion)) {
|
if (IsOutdated(MyVersion, RemoteVersion)) {
|
||||||
std::string RealVersionString = RemoteVersion.AsString();
|
std::string RealVersionString = RemoteVersion.AsString();
|
||||||
warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION OUT! There's a new version (v" + RealVersionString + ") of the BeamMP-Server available! For info on how to update your server, visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server." + std::string(ANSI_RESET));
|
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 {
|
} else {
|
||||||
info("Server up-to-date!");
|
if (FirstTime) {
|
||||||
|
beammp_info("Server up-to-date!");
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Good);
|
||||||
|
break;
|
||||||
} else {
|
} else {
|
||||||
warn("Unable to fetch version from backend.");
|
if (FirstTime) {
|
||||||
trace("got " + Response);
|
beammp_debug("Failed to fetch version from: " + url);
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
beammp_trace("got " + Response);
|
||||||
Sentry.SetContext("get-response", { { "response", Response } });
|
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad);
|
||||||
Sentry.LogError("failed to get server version", _file_basename, _line);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
if (Application::GetSubsystemStatuses().at("UpdateCheck") == Application::Status::Bad) {
|
||||||
std::string DeComp(std::string Compressed) {
|
if (FirstTime) {
|
||||||
std::array<char, Biggest> C {};
|
beammp_warn("Unable to fetch version info from backend.");
|
||||||
// not needed
|
}
|
||||||
C.fill(0);
|
}
|
||||||
z_stream infstream;
|
FirstTime = false;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// thread name stuff
|
// thread name stuff
|
||||||
@@ -142,11 +243,47 @@ std::string ThreadName(bool DebugModeOverride) {
|
|||||||
return "";
|
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) {
|
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);
|
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
||||||
threadNameMap[std::this_thread::get_id()] = str;
|
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)
|
Version::Version(uint8_t major, uint8_t minor, uint8_t patch)
|
||||||
: major(major)
|
: major(major)
|
||||||
, minor(minor)
|
, minor(minor)
|
||||||
@@ -157,13 +294,19 @@ Version::Version(const std::array<uint8_t, 3>& v)
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::string Version::AsString() {
|
std::string Version::AsString() {
|
||||||
std::stringstream ss {};
|
return fmt::format("{:d}.{:d}.{:d}", major, minor, patch);
|
||||||
ss << int(major) << "." << int(minor) << "." << int(patch);
|
}
|
||||||
return ss.str();
|
|
||||||
|
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) {
|
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
||||||
|
if (Application::Settings.LogChat) {
|
||||||
std::stringstream ss;
|
std::stringstream ss;
|
||||||
|
ss << ThreadName();
|
||||||
ss << "[CHAT] ";
|
ss << "[CHAT] ";
|
||||||
if (id != -1) {
|
if (id != -1) {
|
||||||
ss << "(" << id << ") <" << name << "> ";
|
ss << "(" << id << ") <" << name << "> ";
|
||||||
@@ -171,10 +314,14 @@ void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
|||||||
ss << name << "";
|
ss << name << "";
|
||||||
}
|
}
|
||||||
ss << msg;
|
ss << msg;
|
||||||
|
#ifdef DOCTEST_CONFIG_DISABLE
|
||||||
|
Application::Console().Write(ss.str());
|
||||||
|
#endif
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string GetPlatformAgnosticErrorString() {
|
std::string GetPlatformAgnosticErrorString() {
|
||||||
#ifdef WIN32
|
#ifdef BEAMMP_WINDOWS
|
||||||
// This will provide us with the error code and an error message, all in one.
|
// This will provide us with the error code and an error message, all in one.
|
||||||
int err;
|
int err;
|
||||||
char msgbuf[256];
|
char msgbuf[256];
|
||||||
@@ -195,7 +342,20 @@ std::string GetPlatformAgnosticErrorString() {
|
|||||||
} else {
|
} else {
|
||||||
return std::to_string(GetLastError());
|
return std::to_string(GetLastError());
|
||||||
}
|
}
|
||||||
#else // posix
|
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
return std::strerror(errno);
|
return std::strerror(errno);
|
||||||
|
#else
|
||||||
|
return "(no human-readable errors on this platform)";
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: add unit tests to SplitString
|
||||||
|
void SplitString(const std::string& 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+33
-4
@@ -1,10 +1,13 @@
|
|||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
#include <doctest/doctest.h>
|
||||||
|
|
||||||
#ifndef WIN32
|
#ifndef WIN32
|
||||||
|
|
||||||
static struct termios old, current;
|
static struct termios old, current;
|
||||||
|
|
||||||
void initTermios(int echo) {
|
static void initTermios(int echo) {
|
||||||
tcgetattr(0, &old); /* grab old terminal i/o settings */
|
tcgetattr(0, &old); /* grab old terminal i/o settings */
|
||||||
current = old; /* make new settings same as old settings */
|
current = old; /* make new settings same as old settings */
|
||||||
current.c_lflag &= ~ICANON; /* disable buffered i/o */
|
current.c_lflag &= ~ICANON; /* disable buffered i/o */
|
||||||
@@ -16,14 +19,40 @@ void initTermios(int echo) {
|
|||||||
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
|
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
|
||||||
}
|
}
|
||||||
|
|
||||||
void resetTermios(void) {
|
static void resetTermios(void) {
|
||||||
tcsetattr(0, TCSANOW, &old);
|
tcsetattr(0, TCSANOW, &old);
|
||||||
}
|
}
|
||||||
|
|
||||||
char getch_(int echo) {
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static char getch_(int echo) {
|
||||||
char ch;
|
char ch;
|
||||||
initTermios(echo);
|
initTermios(echo);
|
||||||
read(STDIN_FILENO, &ch, 1);
|
if (read(STDIN_FILENO, &ch, 1) < 0) {
|
||||||
|
// ignore, not much we can do
|
||||||
|
}
|
||||||
resetTermios();
|
resetTermios();
|
||||||
return ch;
|
return ch;
|
||||||
}
|
}
|
||||||
|
|||||||
+119
-128
@@ -1,146 +1,55 @@
|
|||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
|
||||||
|
#include "Client.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#undef error
|
#include "CustomAssert.h"
|
||||||
|
#include "LuaAPI.h"
|
||||||
|
|
||||||
#include <boost/asio/connect.hpp>
|
|
||||||
#include <boost/asio/ip/tcp.hpp>
|
|
||||||
#include <boost/beast.hpp>
|
|
||||||
#include <boost/beast/ssl.hpp>
|
|
||||||
#include <map>
|
#include <map>
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
#include <random>
|
||||||
|
#include <stdexcept>
|
||||||
|
|
||||||
namespace beast = boost::beast; // from <boost/beast.hpp>
|
// TODO: Add sentry error handling back
|
||||||
namespace http = beast::http; // from <boost/beast/http.hpp>
|
|
||||||
namespace net = boost::asio; // from <boost/asio.hpp>
|
|
||||||
namespace ssl = net::ssl; // from <boost/asio/ssl.hpp>
|
|
||||||
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
|
|
||||||
|
|
||||||
std::string GenericRequest(http::verb verb, const std::string& host, int port, const std::string& target, const std::unordered_map<std::string, std::string>& fields, const std::string& body, const std::string& ContentType, unsigned int* status) {
|
using json = nlohmann::json;
|
||||||
try {
|
|
||||||
net::io_context io;
|
|
||||||
|
|
||||||
// The SSL context is required, and holds certificates
|
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
||||||
ssl::context ctx(ssl::context::tlsv13);
|
httplib::SSLClient client(host, port);
|
||||||
|
client.enable_server_certificate_verification(false);
|
||||||
ctx.set_verify_mode(ssl::verify_none);
|
client.set_address_family(AF_INET);
|
||||||
|
auto res = client.Get(target.c_str());
|
||||||
tcp::resolver resolver(io);
|
if (res) {
|
||||||
beast::ssl_stream<beast::tcp_stream> stream(io, ctx);
|
|
||||||
decltype(resolver)::results_type results;
|
|
||||||
auto try_connect_with_protocol = [&](tcp protocol) {
|
|
||||||
try {
|
|
||||||
results = resolver.resolve(protocol, host, std::to_string(port));
|
|
||||||
if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str())) {
|
|
||||||
boost::system::error_code ec { static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() };
|
|
||||||
// FIXME: we could throw and crash, if we like
|
|
||||||
// throw boost::system::system_error { ec };
|
|
||||||
//debug("POST " + host + target + " failed.");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
beast::get_lowest_layer(stream).connect(results);
|
|
||||||
} catch (const boost::system::system_error&) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
//bool ok = try_connect_with_protocol(tcp::v6());
|
|
||||||
//if (!ok) {
|
|
||||||
//debug("IPv6 connect failed, trying IPv4");
|
|
||||||
bool ok = try_connect_with_protocol(tcp::v4());
|
|
||||||
if (!ok) {
|
|
||||||
Application::Console().Write("[ERROR] failed to resolve or connect in POST " + host + target);
|
|
||||||
return "-1";
|
|
||||||
}
|
|
||||||
//}
|
|
||||||
stream.handshake(ssl::stream_base::client);
|
|
||||||
http::request<http::string_body> req { verb, target, 11 /* http 1.1 */ };
|
|
||||||
|
|
||||||
req.set(http::field::host, host);
|
|
||||||
if (!body.empty()) {
|
|
||||||
req.set(http::field::content_type, ContentType); // "application/json"
|
|
||||||
// "application/x-www-form-urlencoded"
|
|
||||||
|
|
||||||
req.set(http::field::content_length, std::to_string(body.size()));
|
|
||||||
req.body() = body;
|
|
||||||
// info("body is " + body + " (" + req.body() + ")");
|
|
||||||
// info("content size is " + std::to_string(body.size()) + " (" + boost::lexical_cast<std::string>(body.size()) + ")");
|
|
||||||
}
|
|
||||||
for (const auto& pair : fields) {
|
|
||||||
// info("setting " + pair.first + " to " + pair.second);
|
|
||||||
req.set(pair.first, pair.second);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::unordered_map<std::string, std::string> request_data;
|
|
||||||
for (const auto& header : req.base()) {
|
|
||||||
// need to do explicit casts to convert string_view to string
|
|
||||||
// since string_view may not be null-terminated (and in fact isn't, here)
|
|
||||||
std::string KeyString(header.name_string());
|
|
||||||
std::string ValueString(header.value());
|
|
||||||
request_data[KeyString] = ValueString;
|
|
||||||
}
|
|
||||||
Sentry.SetContext("https-post-request-data", request_data);
|
|
||||||
|
|
||||||
std::stringstream oss;
|
|
||||||
oss << req;
|
|
||||||
|
|
||||||
beast::get_lowest_layer(stream).expires_after(std::chrono::seconds(5));
|
|
||||||
|
|
||||||
http::write(stream, req);
|
|
||||||
|
|
||||||
// used for reading
|
|
||||||
beast::flat_buffer buffer;
|
|
||||||
http::response<http::string_body> response;
|
|
||||||
|
|
||||||
http::read(stream, buffer, response);
|
|
||||||
|
|
||||||
std::unordered_map<std::string, std::string> response_data;
|
|
||||||
response_data["reponse-code"] = std::to_string(response.result_int());
|
|
||||||
if (status) {
|
if (status) {
|
||||||
*status = response.result_int();
|
*status = res->status;
|
||||||
}
|
}
|
||||||
for (const auto& header : response.base()) {
|
return res->body;
|
||||||
// need to do explicit casts to convert string_view to string
|
} else {
|
||||||
// since string_view may not be null-terminated (and in fact isn't, here)
|
|
||||||
std::string KeyString(header.name_string());
|
|
||||||
std::string ValueString(header.value());
|
|
||||||
response_data[KeyString] = ValueString;
|
|
||||||
}
|
|
||||||
Sentry.SetContext("https-post-response-data", response_data);
|
|
||||||
|
|
||||||
if (status) {
|
|
||||||
*status = response.base().result_int();
|
|
||||||
}
|
|
||||||
|
|
||||||
std::stringstream result;
|
|
||||||
result << response;
|
|
||||||
|
|
||||||
beast::error_code ec;
|
|
||||||
stream.shutdown(ec);
|
|
||||||
// IGNORING ec
|
|
||||||
|
|
||||||
// info(result.str());
|
|
||||||
std::string debug_response_str;
|
|
||||||
std::getline(result, debug_response_str);
|
|
||||||
|
|
||||||
//debug("POST " + host + target + ": " + debug_response_str);
|
|
||||||
return std::string(response.body());
|
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
Application::Console().Write(__func__ + std::string(": ") + e.what());
|
|
||||||
return Http::ErrorString;
|
return Http::ErrorString;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
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) {
|
||||||
return GenericRequest(http::verb::get, host, port, target, {}, {}, {}, status);
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Http::POST(const std::string& host, int port, const std::string& target, const std::unordered_map<std::string, std::string>& fields, const std::string& body, const std::string& ContentType, unsigned int* status) {
|
|
||||||
return GenericRequest(http::verb::post, host, port, target, fields, body, ContentType, status);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// RFC 2616, RFC 7231
|
// RFC 2616, RFC 7231
|
||||||
static std::map<size_t, const char*> Map = {
|
static std::map<size_t, const char*> Map = {
|
||||||
|
{ -1, "Invalid Response Code" },
|
||||||
{ 100, "Continue" },
|
{ 100, "Continue" },
|
||||||
{ 101, "Switching Protocols" },
|
{ 101, "Switching Protocols" },
|
||||||
{ 102, "Processing" },
|
{ 102, "Processing" },
|
||||||
@@ -203,12 +112,94 @@ static std::map<size_t, const char*> Map = {
|
|||||||
{ 508, "Loop Detected" },
|
{ 508, "Loop Detected" },
|
||||||
{ 510, "Not Extended" },
|
{ 510, "Not Extended" },
|
||||||
{ 511, "Network Authentication Required" },
|
{ 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" },
|
||||||
};
|
};
|
||||||
|
|
||||||
std::string Http::Status::ToString(int code) {
|
static const char Magic[] = {
|
||||||
if (Map.find(code) != Map.end()) {
|
0x20, 0x2f, 0x5c, 0x5f,
|
||||||
return Map.at(code);
|
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 {
|
} else {
|
||||||
return "Unassigned";
|
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;
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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()));
|
||||||
|
}
|
||||||
|
|||||||
+680
@@ -0,0 +1,680 @@
|
|||||||
|
#include "LuaAPI.h"
|
||||||
|
#include "Client.h"
|
||||||
|
#include "Common.h"
|
||||||
|
#include "CustomAssert.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();
|
||||||
|
}
|
||||||
|
case sol::type::poly:
|
||||||
|
return "<poly>";
|
||||||
|
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, StringToVector(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, StringToVector(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, StringToVector(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);
|
||||||
|
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||||
|
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
|
||||||
|
// TODO: should we return an error here?
|
||||||
|
}
|
||||||
|
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, StringToVector(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;
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
|
}
|
||||||
|
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));
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
+194
-66
@@ -1,57 +1,147 @@
|
|||||||
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
|
#include "Common.h"
|
||||||
|
|
||||||
#include <toml11/toml.hpp> // header-only version of TOML++
|
|
||||||
|
|
||||||
#include "TConfig.h"
|
#include "TConfig.h"
|
||||||
|
#include <cstdlib>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <istream>
|
#include <istream>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
static const char* ConfigFileName = static_cast<const char*>("ServerConfig.toml");
|
// General
|
||||||
|
|
||||||
static constexpr std::string_view StrDebug = "Debug";
|
static constexpr std::string_view StrDebug = "Debug";
|
||||||
|
static constexpr std::string_view EnvStrDebug = "BEAMMP_DEBUG";
|
||||||
static constexpr std::string_view StrPrivate = "Private";
|
static constexpr std::string_view StrPrivate = "Private";
|
||||||
|
static constexpr std::string_view EnvStrPrivate = "BEAMMP_PRIVATE";
|
||||||
static constexpr std::string_view StrPort = "Port";
|
static constexpr std::string_view StrPort = "Port";
|
||||||
|
static constexpr std::string_view EnvStrPort = "BEAMMP_PORT";
|
||||||
static constexpr std::string_view StrMaxCars = "MaxCars";
|
static constexpr std::string_view StrMaxCars = "MaxCars";
|
||||||
|
static constexpr std::string_view EnvStrMaxCars = "BEAMMP_MAX_CARS";
|
||||||
static constexpr std::string_view StrMaxPlayers = "MaxPlayers";
|
static constexpr std::string_view StrMaxPlayers = "MaxPlayers";
|
||||||
|
static constexpr std::string_view EnvStrMaxPlayers = "BEAMMP_MAX_PLAYERS";
|
||||||
static constexpr std::string_view StrMap = "Map";
|
static constexpr std::string_view StrMap = "Map";
|
||||||
|
static constexpr std::string_view EnvStrMap = "BEAMMP_MAP";
|
||||||
static constexpr std::string_view StrName = "Name";
|
static constexpr std::string_view StrName = "Name";
|
||||||
|
static constexpr std::string_view EnvStrName = "BEAMMP_NAME";
|
||||||
static constexpr std::string_view StrDescription = "Description";
|
static constexpr std::string_view StrDescription = "Description";
|
||||||
|
static constexpr std::string_view EnvStrDescription = "BEAMMP_DESCRIPTION";
|
||||||
|
static constexpr std::string_view StrTags = "Tags";
|
||||||
|
static constexpr std::string_view EnvStrTags = "BEAMMP_TAGS";
|
||||||
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
||||||
|
static constexpr std::string_view EnvStrResourceFolder = "BEAMMP_RESOURCE_FOLDER";
|
||||||
static constexpr std::string_view StrAuthKey = "AuthKey";
|
static constexpr std::string_view StrAuthKey = "AuthKey";
|
||||||
|
static constexpr std::string_view EnvStrAuthKey = "BEAMMP_AUTH_KEY";
|
||||||
|
static constexpr std::string_view StrLogChat = "LogChat";
|
||||||
|
static constexpr std::string_view EnvStrLogChat = "BEAMMP_LOG_CHAT";
|
||||||
|
static constexpr std::string_view StrPassword = "Password";
|
||||||
|
|
||||||
TConfig::TConfig() {
|
// Misc
|
||||||
if (!fs::exists(ConfigFileName) || !fs::is_regular_file(ConfigFileName)) {
|
static constexpr std::string_view StrSendErrors = "SendErrors";
|
||||||
info("No config file found! Generating one...");
|
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
||||||
CreateConfigFile(ConfigFileName);
|
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
||||||
|
|
||||||
|
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");
|
||||||
|
auto res = std::fread(buf.data(), 1, buf.size(), fp);
|
||||||
|
if (res != buf.size()) {
|
||||||
|
// IGNORE?
|
||||||
|
}
|
||||||
|
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());
|
||||||
|
|
||||||
|
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 (!mFailed) {
|
||||||
if (fs::exists("Server.cfg")) {
|
if (fs::exists("Server.cfg")) {
|
||||||
warn("An old \"Server.cfg\" file still exists. Please note that this is no longer used. Instead, \"" + std::string(ConfigFileName) + "\" is used. You can safely delete the \"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(ConfigFileName);
|
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() {
|
void TConfig::FlushToFile() {
|
||||||
auto data = toml::parse(ConfigFileName);
|
// auto data = toml::parse<toml::preserve_comments>(mConfigFileName);
|
||||||
data["General"] = toml::table();
|
auto data = toml::value {};
|
||||||
data["General"][StrAuthKey.data()] = Application::Settings.Key;
|
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"][StrDebug.data()] = Application::Settings.DebugModeEnabled;
|
||||||
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
||||||
data["General"][StrPort.data()] = Application::Settings.Port;
|
data["General"][StrPort.data()] = Application::Settings.Port;
|
||||||
data["General"][StrName.data()] = Application::Settings.ServerName;
|
data["General"][StrName.data()] = Application::Settings.ServerName;
|
||||||
|
SetComment(data["General"][StrTags.data()].comments(), " Add custom identifying tags to your server to make it easier to find. Format should be TagA,TagB,TagC. Note the comma seperation.");
|
||||||
|
data["General"][StrTags.data()] = Application::Settings.ServerTags;
|
||||||
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
|
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
|
||||||
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
|
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
|
||||||
data["General"][StrMap.data()] = Application::Settings.MapName;
|
data["General"][StrMap.data()] = Application::Settings.MapName;
|
||||||
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
|
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
|
||||||
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
|
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
|
||||||
std::ofstream Stream(ConfigFileName);
|
// data["General"][StrPassword.data()] = Application::Settings.Password;
|
||||||
Stream << data << std::flush;
|
// SetComment(data["General"][StrPassword.data()].comments(), " Sets a password on this server, which restricts people from joining. To join, a player must enter this exact password. Leave empty ("") to disable the password.");
|
||||||
|
// 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`");
|
||||||
|
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://keymaster.beammp.com/` 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(std::string_view name) {
|
void TConfig::CreateConfigFile() {
|
||||||
// build from old config Server.cfg
|
// build from old config Server.cfg
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -60,80 +150,108 @@ void TConfig::CreateConfigFile(std::string_view name) {
|
|||||||
ParseOldFormat();
|
ParseOldFormat();
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
|
beammp_error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
|
||||||
}
|
}
|
||||||
|
|
||||||
{ // create file context
|
FlushToFile();
|
||||||
std::ofstream ofs(name.data());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
auto data = toml::parse<toml::preserve_comments>(name.data());
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue) {
|
||||||
|
if (!Env.empty()) {
|
||||||
|
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||||
|
OutValue = std::string(envp);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Table[Category.c_str()][Key.data()].is_string()) {
|
||||||
|
OutValue = Table[Category.c_str()][Key.data()].as_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
data["General"] = toml::table();
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue) {
|
||||||
data["General"][StrAuthKey.data()] = Application::Settings.Key;
|
if (!Env.empty()) {
|
||||||
data["General"][StrDebug.data()] = Application::Settings.DebugModeEnabled;
|
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||||
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
auto Str = std::string(envp);
|
||||||
data["General"][StrPort.data()] = Application::Settings.Port;
|
OutValue = Str == "1" || Str == "true";
|
||||||
data["General"][StrName.data()] = Application::Settings.ServerName;
|
return;
|
||||||
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
|
}
|
||||||
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
|
}
|
||||||
data["General"][StrMap.data()] = Application::Settings.MapName;
|
if (Table[Category.c_str()][Key.data()].is_boolean()) {
|
||||||
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
|
OutValue = Table[Category.c_str()][Key.data()].as_boolean();
|
||||||
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::ofstream ofs { std::string(name) };
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue) {
|
||||||
if (ofs.good()) {
|
if (!Env.empty()) {
|
||||||
ofs << "# This is the BeamMP-Server config file.\n"
|
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||||
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
|
OutValue = int(std::strtol(envp, nullptr, 10));
|
||||||
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under \"Keys\"\n"
|
return;
|
||||||
<< '\n';
|
}
|
||||||
ofs << data << '\n';
|
}
|
||||||
error("There was no \"" + std::string(ConfigFileName) + "\" file (this is normal for the first time running the server), so one was generated for you. It was automatically filled with the settings from your Server.cfg, if you have one. Please open ServerConfig.toml and ensure your AuthKey and other settings are filled in and correct, then restart the server. The old Server.cfg file will no longer be used and causes a warning if it exists from now on.");
|
if (Table[Category.c_str()][Key.data()].is_integer()) {
|
||||||
mFailed = true;
|
OutValue = int(Table[Category.c_str()][Key.data()].as_integer());
|
||||||
} else {
|
|
||||||
error("Couldn't create " + std::string(name) + ". Check permissions, try again, and contact support if it continues not to work.");
|
|
||||||
mFailed = true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::ParseFromFile(std::string_view name) {
|
void TConfig::ParseFromFile(std::string_view name) {
|
||||||
try {
|
try {
|
||||||
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
||||||
Application::Settings.DebugModeEnabled = data["General"][StrDebug.data()].as_boolean();
|
// GENERAL
|
||||||
Application::Settings.Private = data["General"][StrPrivate.data()].as_boolean();
|
TryReadValue(data, "General", StrDebug, EnvStrDebug, Application::Settings.DebugModeEnabled);
|
||||||
Application::Settings.Port = data["General"][StrPort.data()].as_integer();
|
TryReadValue(data, "General", StrPrivate, EnvStrPrivate, Application::Settings.Private);
|
||||||
Application::Settings.MaxCars = data["General"][StrMaxCars.data()].as_integer();
|
TryReadValue(data, "General", StrPort, EnvStrPort, Application::Settings.Port);
|
||||||
Application::Settings.MaxPlayers = data["General"][StrMaxPlayers.data()].as_integer();
|
TryReadValue(data, "General", StrMaxCars, EnvStrMaxCars, Application::Settings.MaxCars);
|
||||||
Application::Settings.MapName = data["General"][StrMap.data()].as_string();
|
TryReadValue(data, "General", StrMaxPlayers, EnvStrMaxPlayers, Application::Settings.MaxPlayers);
|
||||||
Application::Settings.ServerName = data["General"][StrName.data()].as_string();
|
TryReadValue(data, "General", StrMap, EnvStrMap, Application::Settings.MapName);
|
||||||
Application::Settings.ServerDesc = data["General"][StrDescription.data()].as_string();
|
TryReadValue(data, "General", StrName, EnvStrName, Application::Settings.ServerName);
|
||||||
Application::Settings.Resource = data["General"][StrResourceFolder.data()].as_string();
|
TryReadValue(data, "General", StrDescription, EnvStrDescription, Application::Settings.ServerDesc);
|
||||||
Application::Settings.Key = data["General"][StrAuthKey.data()].as_string();
|
TryReadValue(data, "General", StrTags, EnvStrTags, Application::Settings.ServerTags);
|
||||||
|
TryReadValue(data, "General", StrResourceFolder, EnvStrResourceFolder, Application::Settings.Resource);
|
||||||
|
TryReadValue(data, "General", StrAuthKey, EnvStrAuthKey, Application::Settings.Key);
|
||||||
|
TryReadValue(data, "General", StrLogChat, EnvStrLogChat, Application::Settings.LogChat);
|
||||||
|
TryReadValue(data, "General", StrPassword, "", Application::Settings.Password);
|
||||||
|
// Misc
|
||||||
|
TryReadValue(data, "Misc", StrSendErrors, "", Application::Settings.SendErrors);
|
||||||
|
TryReadValue(data, "Misc", StrHideUpdateMessages, "", Application::Settings.HideUpdateMessages);
|
||||||
|
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, "", Application::Settings.SendErrorsMessageEnabled);
|
||||||
} catch (const std::exception& err) {
|
} catch (const std::exception& err) {
|
||||||
error("Error parsing config file value: " + std::string(err.what()));
|
beammp_error("Error parsing config file value: " + std::string(err.what()));
|
||||||
mFailed = true;
|
mFailed = true;
|
||||||
|
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
PrintDebug();
|
PrintDebug();
|
||||||
|
|
||||||
|
// Update in any case
|
||||||
|
FlushToFile();
|
||||||
// all good so far, let's check if there's a key
|
// all good so far, let's check if there's a key
|
||||||
if (Application::Settings.Key.empty()) {
|
if (Application::Settings.Key.empty()) {
|
||||||
error("No AuthKey specified in the \"" + std::string(ConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
|
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;
|
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() {
|
void TConfig::PrintDebug() {
|
||||||
debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
|
beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||||
debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
|
beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
|
||||||
debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
|
beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
|
||||||
debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
|
beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
|
||||||
debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
|
beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
|
||||||
debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
||||||
debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
||||||
debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
||||||
debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
|
beammp_debug(std::string(StrTags) + ": " + TagsAsPrettyArray());
|
||||||
|
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
|
||||||
|
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
|
||||||
// special!
|
// special!
|
||||||
debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
|
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
|
||||||
|
beammp_debug("Password Protected: " + std::string(Application::Settings.Password.empty() ? "false" : "true"));
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::ParseOldFormat() {
|
void TConfig::ParseOldFormat() {
|
||||||
@@ -183,8 +301,18 @@ void TConfig::ParseOldFormat() {
|
|||||||
} else if (Key == "AuthKey") {
|
} else if (Key == "AuthKey") {
|
||||||
Application::Settings.Key = Value.substr(1, Value.size() - 3);
|
Application::Settings.Key = Value.substr(1, Value.size() - 3);
|
||||||
} else {
|
} else {
|
||||||
warn("unknown key in old auth file (ignored): " + Key);
|
beammp_warn("unknown key in old auth file (ignored): " + Key);
|
||||||
}
|
}
|
||||||
Str >> std::ws;
|
Str >> std::ws;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
std::string TConfig::TagsAsPrettyArray() const {
|
||||||
|
std::vector<std::string> TagsArray = {};
|
||||||
|
SplitString(Application::Settings.ServerTags, ',', TagsArray);
|
||||||
|
std::string Pretty = {};
|
||||||
|
for (size_t i = 0; i < TagsArray.size() - 1; ++i) {
|
||||||
|
Pretty += '\"' + TagsArray[i] + "\", ";
|
||||||
|
}
|
||||||
|
Pretty += '\"' + TagsArray.at(TagsArray.size()-1) + "\"";
|
||||||
|
return Pretty;
|
||||||
|
}
|
||||||
|
|||||||
+689
-49
@@ -2,77 +2,717 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
|
|
||||||
|
#include "Client.h"
|
||||||
|
#include "CustomAssert.h"
|
||||||
|
#include "LuaAPI.h"
|
||||||
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
#include <ctime>
|
#include <ctime>
|
||||||
|
#include <mutex>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
std::string GetDate() {
|
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("") == "");
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string GetDate() {
|
||||||
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
||||||
time_t tt = std::chrono::system_clock::to_time_t(now);
|
time_t tt = std::chrono::system_clock::to_time_t(now);
|
||||||
tm local_tm {};
|
auto local_tm = std::localtime(&tt);
|
||||||
#ifdef WIN32
|
char buf[30];
|
||||||
localtime_s(&local_tm, &tt);
|
std::string date;
|
||||||
#else // unix
|
if (Application::Settings.DebugModeEnabled) {
|
||||||
localtime_r(&tt, &local_tm);
|
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T.", local_tm);
|
||||||
#endif // WIN32
|
date += buf;
|
||||||
std::stringstream date;
|
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
|
||||||
int S = local_tm.tm_sec;
|
auto fraction = now - seconds;
|
||||||
int M = local_tm.tm_min;
|
size_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(fraction).count();
|
||||||
int H = local_tm.tm_hour;
|
char fracstr[5];
|
||||||
std::string Secs = (S > 9 ? std::to_string(S) : "0" + std::to_string(S));
|
std::sprintf(fracstr, "%03lu", ms);
|
||||||
std::string Min = (M > 9 ? std::to_string(M) : "0" + std::to_string(M));
|
date += fracstr;
|
||||||
std::string Hour = (H > 9 ? std::to_string(H) : "0" + std::to_string(H));
|
date += "] ";
|
||||||
date
|
} else {
|
||||||
<< "["
|
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T] ", local_tm);
|
||||||
<< local_tm.tm_mday << "/"
|
date += buf;
|
||||||
<< local_tm.tm_mon + 1 << "/"
|
|
||||||
<< local_tm.tm_year + 1900 << " "
|
|
||||||
<< Hour << ":"
|
|
||||||
<< Min << ":"
|
|
||||||
<< Secs
|
|
||||||
<< "] ";
|
|
||||||
/* TODO
|
|
||||||
if (Debug) {
|
|
||||||
date << ThreadName()
|
|
||||||
<< " ";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
*/
|
*/
|
||||||
return date.str();
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 `:exit`");
|
||||||
|
mCommandline->set_prompt("lua @" + LuaStateId + "> ");
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:exit`");
|
||||||
|
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) + " argument(s) 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(min) + " argument(s) 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;
|
||||||
|
// TODO: this sucks, tolower is locale-dependent.
|
||||||
|
auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
|
||||||
|
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = char(std::tolower(char(c))); });
|
||||||
|
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(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;
|
||||||
|
}
|
||||||
|
// this is required, otherwise we get negative int to unsigned cast in the next operations
|
||||||
|
beammp_assert(PrevPtr <= Ptr);
|
||||||
|
Arg = std::string(PrevPtr, std::string::size_type(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, 1, 2)) {
|
||||||
|
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;
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 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(double(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() {
|
TConsole::TConsole() {
|
||||||
mCommandline.enable_history();
|
|
||||||
mCommandline.set_history_limit(20);
|
|
||||||
mCommandline.set_prompt("> ");
|
|
||||||
bool success = mCommandline.enable_write_to_file("Server.log");
|
|
||||||
if (!success) {
|
|
||||||
error("unable to open file for writing: \"Server.log\"");
|
|
||||||
}
|
}
|
||||||
mCommandline.on_command = [this](Commandline& c) {
|
|
||||||
auto cmd = c.get_command();
|
void TConsole::InitializeCommandline() {
|
||||||
mCommandline.write("> " + cmd);
|
mCommandline = std::make_unique<Commandline>();
|
||||||
if (cmd == "exit") {
|
mCommandline->enable_history();
|
||||||
info("gracefully shutting down");
|
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), "", "" });
|
||||||
|
Future->WaitUntilReady();
|
||||||
|
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();
|
Application::GracefullyShutdown();
|
||||||
} else if (cmd == "clear" || cmd == "cls") {
|
} else if (cmd == "say") {
|
||||||
// TODO: clear screen
|
RunAsCommand(TrimmedCmd, true);
|
||||||
|
Command_Say(TrimmedCmd);
|
||||||
} else {
|
} else {
|
||||||
if (mLuaConsole) {
|
if (mCommandMap.find(cmd) != mCommandMap.end()) {
|
||||||
mLuaConsole->Execute(cmd);
|
mCommandMap.at(cmd)(cmd, args);
|
||||||
|
RunAsCommand(TrimmedCmd, true);
|
||||||
} else {
|
} else {
|
||||||
error("Lua subsystem not yet initialized, please wait a few seconds and try again");
|
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&, std::string stub, int) {
|
||||||
|
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) {
|
void TConsole::Write(const std::string& str) {
|
||||||
auto ToWrite = GetDate() + str;
|
auto ToWrite = GetDate() + str;
|
||||||
mCommandline.write(ToWrite);
|
// allows writing to stdout without an initialized console
|
||||||
// TODO write to logfile, too
|
if (mCommandline) {
|
||||||
|
mCommandline->write(ToWrite);
|
||||||
|
} else {
|
||||||
|
std::cout << ToWrite << std::endl;
|
||||||
}
|
}
|
||||||
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
|
|
||||||
mLuaConsole = std::make_unique<TLuaFile>(Engine, true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::WriteRaw(const std::string& str) {
|
void TConsole::WriteRaw(const std::string& str) {
|
||||||
mCommandline.write(str);
|
// allows writing to stdout without an initialized console
|
||||||
|
if (mCommandline) {
|
||||||
|
mCommandline->write(str);
|
||||||
|
} else {
|
||||||
|
std::cout << str << std::endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
|
||||||
|
mLuaEngine = &Engine;
|
||||||
}
|
}
|
||||||
|
|||||||
+78
-44
@@ -3,8 +3,12 @@
|
|||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
//#include "SocketIO.h"
|
//#include "SocketIO.h"
|
||||||
|
#include <rapidjson/document.h>
|
||||||
|
#include <rapidjson/rapidjson.h>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
namespace json = rapidjson;
|
||||||
|
|
||||||
void THeartbeatThread::operator()() {
|
void THeartbeatThread::operator()() {
|
||||||
RegisterThread("Heartbeat");
|
RegisterThread("Heartbeat");
|
||||||
std::string Body;
|
std::string Body;
|
||||||
@@ -15,7 +19,9 @@ void THeartbeatThread::operator()() {
|
|||||||
|
|
||||||
static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
|
static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
|
||||||
bool isAuth = false;
|
bool isAuth = false;
|
||||||
while (!mShutdown) {
|
size_t UpdateReminderCounter = 0;
|
||||||
|
while (!Application::IsShuttingDown()) {
|
||||||
|
++UpdateReminderCounter;
|
||||||
Body = GenerateCall();
|
Body = GenerateCall();
|
||||||
// a hot-change occurs when a setting has changed, to update the backend of that change.
|
// a hot-change occurs when a setting has changed, to update the backend of that change.
|
||||||
auto Now = std::chrono::high_resolution_clock::now();
|
auto Now = std::chrono::high_resolution_clock::now();
|
||||||
@@ -26,62 +32,88 @@ void THeartbeatThread::operator()() {
|
|||||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
debug("heartbeat (after " + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(TimePassed).count()) + "s)");
|
beammp_debug("heartbeat (after " + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(TimePassed).count()) + "s)");
|
||||||
|
|
||||||
Last = Body;
|
Last = Body;
|
||||||
LastNormalUpdateTime = Now;
|
LastNormalUpdateTime = Now;
|
||||||
if (!Application::Settings.CustomIP.empty())
|
if (!Application::Settings.CustomIP.empty()) {
|
||||||
Body += "&ip=" + Application::Settings.CustomIP;
|
Body += "&ip=" + Application::Settings.CustomIP;
|
||||||
|
|
||||||
Body += "&pps=" + Application::PPS();
|
|
||||||
|
|
||||||
auto SentryReportError = [&](const std::string& transaction, int status) {
|
|
||||||
if (status < 0) {
|
|
||||||
status = 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
|
||||||
Sentry.SetContext("heartbeat",
|
|
||||||
{ { "response-body", T },
|
|
||||||
{ "request-body", Body } });
|
|
||||||
Sentry.SetTransaction(transaction);
|
|
||||||
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";
|
auto Target = "/heartbeat";
|
||||||
unsigned int ResponseCode = 0;
|
unsigned int ResponseCode = 0;
|
||||||
T = Http::POST(Application::GetBackendHostname(), 443, Target, {}, Body, "application/x-www-form-urlencoded", &ResponseCode);
|
|
||||||
|
|
||||||
if (T.substr(0, 2) != "20" || ResponseCode != 200) {
|
json::Document Doc;
|
||||||
trace("got " + T + " from backend");
|
bool Ok = false;
|
||||||
SentryReportError(Application::GetBackendHostname() + Target, ResponseCode);
|
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
||||||
|
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
||||||
|
Doc.Parse(T.data(), T.size());
|
||||||
|
if (Doc.HasParseError() || !Doc.IsObject()) {
|
||||||
|
if (!Application::Settings.Private) {
|
||||||
|
beammp_trace("Backend response failed to parse as valid json");
|
||||||
|
beammp_trace("Response was: `" + T + "`");
|
||||||
|
}
|
||||||
|
} else if (ResponseCode != 200) {
|
||||||
|
beammp_errorf("Response code from the heartbeat: {}", ResponseCode);
|
||||||
|
} else {
|
||||||
|
// all ok
|
||||||
|
Ok = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||||
T = Http::POST(Application::GetBackup1Hostname(), 443, Target, {}, Body, "application/x-www-form-urlencoded", &ResponseCode);
|
|
||||||
if (T.substr(0, 2) != "20" || ResponseCode != 200) {
|
|
||||||
SentryReportError(Application::GetBackup1Hostname() + Target, ResponseCode);
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
|
||||||
T = Http::POST(Application::GetBackup2Hostname(), 443, Target, {}, Body, "application/x-www-form-urlencoded", &ResponseCode);
|
|
||||||
if (T.substr(0, 2) != "20" || ResponseCode != 200) {
|
|
||||||
warn("Backend system refused server! Server will not show in the public server list.");
|
|
||||||
|
|
||||||
isAuth = false;
|
|
||||||
SentryReportError(Application::GetBackup2Hostname() + Target, ResponseCode);
|
|
||||||
}
|
}
|
||||||
|
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 {
|
||||||
|
Ok = false;
|
||||||
|
}
|
||||||
|
if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) {
|
||||||
|
Code = Doc[CodeKey].GetString();
|
||||||
|
} else {
|
||||||
|
Ok = false;
|
||||||
|
}
|
||||||
|
if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) {
|
||||||
|
Message = Doc[MessageKey].GetString();
|
||||||
|
} else {
|
||||||
|
Ok = false;
|
||||||
|
}
|
||||||
|
if (!Ok) {
|
||||||
|
beammp_error("Missing/invalid json members in backend response");
|
||||||
|
}
|
||||||
|
} 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 (!isAuth) {
|
if (Ok && !isAuth && !Application::Settings.Private) {
|
||||||
if (T == "2000") {
|
if (Status == "2000") {
|
||||||
info(("Authenticated!"));
|
beammp_info(("Authenticated! " + Message));
|
||||||
isAuth = true;
|
isAuth = true;
|
||||||
} else if (T == "200") {
|
} else if (Status == "200") {
|
||||||
info(("Resumed authenticated session!"));
|
beammp_info(("Resumed authenticated session! " + Message));
|
||||||
isAuth = true;
|
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) {
|
||||||
//SocketIO::Get().SetAuthenticated(isAuth);
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
||||||
|
}
|
||||||
|
if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
|
||||||
|
Application::CheckForUpdates();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,25 +127,27 @@ std::string THeartbeatThread::GenerateCall() {
|
|||||||
<< "&map=" << Application::Settings.MapName
|
<< "&map=" << Application::Settings.MapName
|
||||||
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
||||||
<< "&version=" << Application::ServerVersionString()
|
<< "&version=" << Application::ServerVersionString()
|
||||||
<< "&clientversion=" << Application::ClientVersionString()
|
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
|
||||||
<< "&name=" << Application::Settings.ServerName
|
<< "&name=" << Application::Settings.ServerName
|
||||||
|
<< "&tags=" << Application::Settings.ServerTags
|
||||||
<< "&modlist=" << mResourceManager.TrimmedList()
|
<< "&modlist=" << mResourceManager.TrimmedList()
|
||||||
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
||||||
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
||||||
<< "&playerslist=" << GetPlayers()
|
<< "&playerslist=" << GetPlayers()
|
||||||
<< "&desc=" << Application::Settings.ServerDesc;
|
<< "&desc=" << Application::Settings.ServerDesc
|
||||||
|
<< "&pass=" << (Application::Settings.Password.empty() ? "false" : "true");
|
||||||
return Ret.str();
|
return Ret.str();
|
||||||
}
|
}
|
||||||
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
||||||
: mResourceManager(ResourceManager)
|
: mResourceManager(ResourceManager)
|
||||||
, mServer(Server) {
|
, mServer(Server) {
|
||||||
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
|
||||||
Application::RegisterShutdownHandler([&] {
|
Application::RegisterShutdownHandler([&] {
|
||||||
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
|
||||||
if (mThread.joinable()) {
|
if (mThread.joinable()) {
|
||||||
debug("shutting down Heartbeat");
|
|
||||||
mShutdown = true;
|
|
||||||
mThread.join();
|
mThread.join();
|
||||||
debug("shut down Heartbeat");
|
|
||||||
}
|
}
|
||||||
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Shutdown);
|
||||||
});
|
});
|
||||||
Start();
|
Start();
|
||||||
}
|
}
|
||||||
|
|||||||
+1083
-95
File diff suppressed because it is too large
Load Diff
-1107
File diff suppressed because it is too large
Load Diff
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+470
-404
File diff suppressed because it is too large
Load Diff
+11
-8
@@ -4,26 +4,29 @@
|
|||||||
|
|
||||||
TPPSMonitor::TPPSMonitor(TServer& Server)
|
TPPSMonitor::TPPSMonitor(TServer& Server)
|
||||||
: mServer(Server) {
|
: mServer(Server) {
|
||||||
|
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Starting);
|
||||||
Application::SetPPS("-");
|
Application::SetPPS("-");
|
||||||
Application::RegisterShutdownHandler([&] {
|
Application::RegisterShutdownHandler([&] {
|
||||||
|
Application::SetSubsystemStatus("PPSMonitor", Application::Status::ShuttingDown);
|
||||||
if (mThread.joinable()) {
|
if (mThread.joinable()) {
|
||||||
debug("shutting down PPSMonitor");
|
beammp_debug("shutting down PPSMonitor");
|
||||||
mShutdown = true;
|
|
||||||
mThread.join();
|
mThread.join();
|
||||||
debug("shut down PPSMonitor");
|
beammp_debug("shut down PPSMonitor");
|
||||||
}
|
}
|
||||||
|
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Shutdown);
|
||||||
});
|
});
|
||||||
Start();
|
Start();
|
||||||
}
|
}
|
||||||
void TPPSMonitor::operator()() {
|
void TPPSMonitor::operator()() {
|
||||||
RegisterThread("PPSMonitor");
|
RegisterThread("PPSMonitor");
|
||||||
while (!mNetwork) {
|
while (!mNetwork) {
|
||||||
// hard spi
|
// hard(-ish) spin
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
std::this_thread::yield();
|
||||||
}
|
}
|
||||||
info("PPSMonitor starting");
|
beammp_debug("PPSMonitor starting");
|
||||||
|
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Good);
|
||||||
std::vector<std::shared_ptr<TClient>> TimedOutClients;
|
std::vector<std::shared_ptr<TClient>> TimedOutClients;
|
||||||
while (!mShutdown) {
|
while (!Application::IsShuttingDown()) {
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||||
int C = 0, V = 0;
|
int C = 0, V = 0;
|
||||||
if (mServer.ClientCount() == 0) {
|
if (mServer.ClientCount() == 0) {
|
||||||
@@ -45,7 +48,7 @@ void TPPSMonitor::operator()() {
|
|||||||
}
|
}
|
||||||
// kick on "no ping"
|
// kick on "no ping"
|
||||||
if (c->SecondsSinceLastPing() > (20 * 60)) {
|
if (c->SecondsSinceLastPing() > (20 * 60)) {
|
||||||
debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
|
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);
|
TimedOutClients.push_back(c);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
#include "TPluginMonitor.h"
|
||||||
|
|
||||||
|
#include "TLuaEngine.h"
|
||||||
|
#include <filesystem>
|
||||||
|
|
||||||
|
TPluginMonitor::TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine)
|
||||||
|
: mEngine(Engine)
|
||||||
|
, mPath(Path) {
|
||||||
|
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Starting);
|
||||||
|
if (!fs::exists(mPath)) {
|
||||||
|
fs::create_directories(mPath);
|
||||||
|
}
|
||||||
|
for (const auto& Entry : fs::recursive_directory_iterator(mPath, fs::directory_options::follow_directory_symlink)) {
|
||||||
|
// TODO: trigger an event when a subfolder file changes
|
||||||
|
if (Entry.is_regular_file()) {
|
||||||
|
mFileTimes[Entry.path().string()] = fs::last_write_time(Entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Application::RegisterShutdownHandler([this] {
|
||||||
|
if (mThread.joinable()) {
|
||||||
|
mThread.join();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
void TPluginMonitor::operator()() {
|
||||||
|
RegisterThread("PluginMonitor");
|
||||||
|
beammp_info("PluginMonitor started");
|
||||||
|
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Good);
|
||||||
|
while (!Application::IsShuttingDown()) {
|
||||||
|
std::vector<std::string> ToRemove;
|
||||||
|
for (const auto& Pair : mFileTimes) {
|
||||||
|
try {
|
||||||
|
auto CurrentTime = fs::last_write_time(Pair.first);
|
||||||
|
if (CurrentTime > Pair.second) {
|
||||||
|
mFileTimes[Pair.first] = CurrentTime;
|
||||||
|
// grandparent of the path should be Resources/Server
|
||||||
|
if (fs::equivalent(fs::path(Pair.first).parent_path().parent_path(), mPath)) {
|
||||||
|
beammp_infof("File \"{}\" changed, reloading", Pair.first);
|
||||||
|
// is in root folder, so reload
|
||||||
|
std::ifstream FileStream(Pair.first, std::ios::in | std::ios::binary);
|
||||||
|
auto Size = std::filesystem::file_size(Pair.first);
|
||||||
|
auto Contents = std::make_shared<std::string>();
|
||||||
|
Contents->resize(Size);
|
||||||
|
FileStream.read(Contents->data(), Contents->size());
|
||||||
|
TLuaChunk Chunk(Contents, Pair.first, fs::path(Pair.first).parent_path().string());
|
||||||
|
auto StateID = mEngine->GetStateIDForPlugin(fs::path(Pair.first).parent_path());
|
||||||
|
auto Res = mEngine->EnqueueScript(StateID, Chunk);
|
||||||
|
Res->WaitUntilReady();
|
||||||
|
if (Res->Error) {
|
||||||
|
beammp_lua_errorf("Error while hot-reloading \"{}\": {}", Pair.first, Res->ErrorMessage);
|
||||||
|
} else {
|
||||||
|
mEngine->ReportErrors(mEngine->TriggerLocalEvent(StateID, "onInit"));
|
||||||
|
mEngine->ReportErrors(mEngine->TriggerEvent("onFileChanged", "", Pair.first));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// is in subfolder, dont reload, just trigger an event
|
||||||
|
beammp_debugf("File \"{}\" changed, not reloading because it's in a subdirectory. Triggering 'onFileChanged' event instead", Pair.first);
|
||||||
|
mEngine->ReportErrors(mEngine->TriggerEvent("onFileChanged", "", Pair.first));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ToRemove.push_back(Pair.first);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Application::SleepSafeSeconds(3);
|
||||||
|
for (const auto& File : ToRemove) {
|
||||||
|
mFileTimes.erase(File);
|
||||||
|
beammp_warnf("File \"{}\" couldn't be accessed, so it was removed from plugin hot reload monitor (probably got deleted)", File);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Shutdown);
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
TResourceManager::TResourceManager() {
|
TResourceManager::TResourceManager() {
|
||||||
|
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
|
||||||
std::string Path = Application::Settings.Resource + "/Client";
|
std::string Path = Application::Settings.Resource + "/Client";
|
||||||
if (!fs::exists(Path))
|
if (!fs::exists(Path))
|
||||||
fs::create_directories(Path);
|
fs::create_directories(Path);
|
||||||
@@ -27,6 +28,9 @@ TResourceManager::TResourceManager() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mModsLoaded)
|
if (mModsLoaded) {
|
||||||
info("Loaded " + std::to_string(mModsLoaded) + " Mods");
|
beammp_info("Loaded " + std::to_string(mModsLoaded) + " Mods");
|
||||||
|
}
|
||||||
|
|
||||||
|
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
#include "TScopedTimer.h"
|
||||||
|
#include "Common.h"
|
||||||
|
|
||||||
|
TScopedTimer::TScopedTimer()
|
||||||
|
: mStartTime(std::chrono::high_resolution_clock::now()) {
|
||||||
|
}
|
||||||
|
|
||||||
|
TScopedTimer::TScopedTimer(const std::string& mName)
|
||||||
|
: mStartTime(std::chrono::high_resolution_clock::now())
|
||||||
|
, Name(mName) {
|
||||||
|
}
|
||||||
|
|
||||||
|
TScopedTimer::TScopedTimer(std::function<void(size_t)> OnDestroy)
|
||||||
|
: OnDestroy(OnDestroy)
|
||||||
|
, mStartTime(std::chrono::high_resolution_clock::now()) {
|
||||||
|
}
|
||||||
|
|
||||||
|
TScopedTimer::~TScopedTimer() {
|
||||||
|
auto EndTime = std::chrono::high_resolution_clock::now();
|
||||||
|
auto Delta = EndTime - mStartTime;
|
||||||
|
size_t TimeDelta = Delta / std::chrono::milliseconds(1);
|
||||||
|
if (OnDestroy) {
|
||||||
|
OnDestroy(TimeDelta);
|
||||||
|
} else {
|
||||||
|
beammp_info("Scoped timer: \"" + Name + "\" took " + std::to_string(TimeDelta) + "ms ");
|
||||||
|
}
|
||||||
|
}
|
||||||
-125
@@ -1,125 +0,0 @@
|
|||||||
#include "TSentry.h"
|
|
||||||
#include "Common.h"
|
|
||||||
|
|
||||||
#include <sentry.h>
|
|
||||||
#include <sstream>
|
|
||||||
|
|
||||||
// compile-time length of a string/array
|
|
||||||
template <size_t N>
|
|
||||||
constexpr size_t ConstexprLength(char const (&)[N]) {
|
|
||||||
return N - 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
TSentry::TSentry() {
|
|
||||||
if constexpr (ConstexprLength(SECRET_SENTRY_URL) == 0) {
|
|
||||||
mValid = false;
|
|
||||||
} else {
|
|
||||||
mValid = true;
|
|
||||||
sentry_options_t* options = sentry_options_new();
|
|
||||||
sentry_options_set_dsn(options, SECRET_SENTRY_URL);
|
|
||||||
auto ReleaseString = "BeamMP-Server@" + Application::ServerVersionString();
|
|
||||||
sentry_options_set_symbolize_stacktraces(options, true);
|
|
||||||
sentry_options_set_release(options, ReleaseString.c_str());
|
|
||||||
sentry_options_set_max_breadcrumbs(options, 10);
|
|
||||||
sentry_init(options);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
TSentry::~TSentry() {
|
|
||||||
if (mValid) {
|
|
||||||
sentry_close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::PrintWelcome() {
|
|
||||||
if (mValid) {
|
|
||||||
info("Sentry started");
|
|
||||||
} else {
|
|
||||||
info("Sentry disabled in unofficial build");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::SetupUser() {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sentry_value_t user = sentry_value_new_object();
|
|
||||||
if (Application::Settings.Key.size() == 36) {
|
|
||||||
sentry_value_set_by_key(user, "id", sentry_value_new_string(Application::Settings.Key.c_str()));
|
|
||||||
} else {
|
|
||||||
sentry_value_set_by_key(user, "id", sentry_value_new_string("unauthenticated"));
|
|
||||||
}
|
|
||||||
sentry_set_user(user);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::Log(SentryLevel level, const std::string& logger, const std::string& text) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
SetContext("threads", { { "thread-name", ThreadName(true) } });
|
|
||||||
auto Msg = sentry_value_new_message_event(sentry_level_t(level), logger.c_str(), text.c_str());
|
|
||||||
sentry_capture_event(Msg);
|
|
||||||
sentry_remove_transaction();
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::LogError(const std::string& text, const std::string& file, const std::string& line) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
SetTransaction(file + ":" + line);
|
|
||||||
Log(SentryLevel::Error, "default", file + ": " + text);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::SetContext(const std::string& context_name, const std::unordered_map<std::string, std::string>& map) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto ctx = sentry_value_new_object();
|
|
||||||
for (const auto& pair : map) {
|
|
||||||
std::string key = pair.first;
|
|
||||||
if (key == "type") {
|
|
||||||
// `type` is reserved
|
|
||||||
key = "_type";
|
|
||||||
}
|
|
||||||
sentry_value_set_by_key(ctx, key.c_str(), sentry_value_new_string(pair.second.c_str()));
|
|
||||||
}
|
|
||||||
sentry_set_context(context_name.c_str(), ctx);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::LogException(const std::exception& e, const std::string& file, const std::string& line) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
SetTransaction(file + ":" + line);
|
|
||||||
Log(SentryLevel::Fatal, "exceptions", std::string(e.what()) + " @ " + file + ":" + line);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::LogAssert(const std::string& condition_string, const std::string& file, const std::string& line, const std::string& function) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
SetTransaction(file + ":" + line + ":" + function);
|
|
||||||
std::stringstream ss;
|
|
||||||
ss << "\"" << condition_string << "\" failed @ " << file << ":" << line;
|
|
||||||
Log(SentryLevel::Fatal, "asserts", ss.str());
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::AddErrorBreadcrumb(const std::string& msg, const std::string& file, const std::string& line) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto crumb = sentry_value_new_breadcrumb("default", (msg + " @ " + file + ":" + line).c_str());
|
|
||||||
sentry_value_set_by_key(crumb, "level", sentry_value_new_string("error"));
|
|
||||||
sentry_add_breadcrumb(crumb);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::SetTransaction(const std::string& id) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sentry_set_transaction(id.c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
std::unique_lock<std::mutex> TSentry::CreateExclusiveContext() {
|
|
||||||
return std::unique_lock<std::mutex>(mMutex);
|
|
||||||
}
|
|
||||||
+241
-153
@@ -1,49 +1,104 @@
|
|||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
#include "CustomAssert.h"
|
||||||
#include "TNetwork.h"
|
#include "TNetwork.h"
|
||||||
#include "TPPSMonitor.h"
|
#include "TPPSMonitor.h"
|
||||||
#include <TLuaFile.h>
|
#include <TLuaPlugin.h>
|
||||||
|
#include <algorithm>
|
||||||
#include <any>
|
#include <any>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
|
||||||
|
#include "LuaAPI.h"
|
||||||
|
|
||||||
#undef GetObject // Fixes Windows
|
#undef GetObject // Fixes Windows
|
||||||
|
|
||||||
#include "Json.h"
|
#include "Json.h"
|
||||||
|
|
||||||
namespace json = rapidjson;
|
static std::optional<std::pair<int, int>> GetPidVid(const std::string& str) {
|
||||||
|
auto IDSep = str.find('-');
|
||||||
|
std::string pid = str.substr(0, IDSep);
|
||||||
|
std::string vid = str.substr(IDSep + 1);
|
||||||
|
|
||||||
TServer::TServer(int argc, char** argv) {
|
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||||
info("BeamMP Server v" + Application::ServerVersionString());
|
try {
|
||||||
if (argc > 1) {
|
int PID = stoi(pid);
|
||||||
Application::Settings.CustomIP = argv[1];
|
int VID = stoi(vid);
|
||||||
size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
|
return { { PID, VID } };
|
||||||
auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
|
} catch (const std::exception&) {
|
||||||
if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
|
return std::nullopt;
|
||||||
Application::Settings.CustomIP.clear();
|
|
||||||
warn("IP Specified is invalid! Ignoring");
|
|
||||||
} else {
|
|
||||||
info("server started with custom IP");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("GetPidVid") {
|
||||||
|
SUBCASE("Valid singledigit") {
|
||||||
|
const auto MaybePidVid = GetPidVid("0-1");
|
||||||
|
CHECK(MaybePidVid);
|
||||||
|
auto [pid, vid] = MaybePidVid.value();
|
||||||
|
|
||||||
|
CHECK_EQ(pid, 0);
|
||||||
|
CHECK_EQ(vid, 1);
|
||||||
|
}
|
||||||
|
SUBCASE("Valid doubledigit") {
|
||||||
|
const auto MaybePidVid = GetPidVid("10-12");
|
||||||
|
CHECK(MaybePidVid);
|
||||||
|
auto [pid, vid] = MaybePidVid.value();
|
||||||
|
|
||||||
|
CHECK_EQ(pid, 10);
|
||||||
|
CHECK_EQ(vid, 12);
|
||||||
|
}
|
||||||
|
SUBCASE("Empty string") {
|
||||||
|
const auto MaybePidVid = GetPidVid("");
|
||||||
|
CHECK(!MaybePidVid);
|
||||||
|
}
|
||||||
|
SUBCASE("Invalid separator") {
|
||||||
|
const auto MaybePidVid = GetPidVid("0x0");
|
||||||
|
CHECK(!MaybePidVid);
|
||||||
|
}
|
||||||
|
SUBCASE("Missing pid") {
|
||||||
|
const auto MaybePidVid = GetPidVid("-0");
|
||||||
|
CHECK(!MaybePidVid);
|
||||||
|
}
|
||||||
|
SUBCASE("Missing vid") {
|
||||||
|
const auto MaybePidVid = GetPidVid("0-");
|
||||||
|
CHECK(!MaybePidVid);
|
||||||
|
}
|
||||||
|
SUBCASE("Invalid pid") {
|
||||||
|
const auto MaybePidVid = GetPidVid("x-0");
|
||||||
|
CHECK(!MaybePidVid);
|
||||||
|
}
|
||||||
|
SUBCASE("Invalid vid") {
|
||||||
|
const auto MaybePidVid = GetPidVid("0-x");
|
||||||
|
CHECK(!MaybePidVid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
||||||
|
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
||||||
|
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
||||||
|
Application::SetSubsystemStatus("Server", Application::Status::Good);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
||||||
if (!WeakClientPtr.expired()) {
|
std::shared_ptr<TClient> LockedClientPtr { nullptr };
|
||||||
TClient& Client = *WeakClientPtr.lock();
|
try {
|
||||||
debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
LockedClientPtr = WeakClientPtr.lock();
|
||||||
|
} catch (const std::exception&) {
|
||||||
|
// silently fail, as there's nothing to do
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
beammp_assert(LockedClientPtr != nullptr);
|
||||||
|
TClient& Client = *LockedClientPtr;
|
||||||
|
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
||||||
|
// TODO: Send delete packets for all cars
|
||||||
Client.ClearCars();
|
Client.ClearCars();
|
||||||
WriteLock Lock(mClientsMutex);
|
WriteLock Lock(mClientsMutex);
|
||||||
mClients.erase(WeakClientPtr.lock());
|
mClients.erase(WeakClientPtr.lock());
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
std::weak_ptr<TClient> TServer::InsertNewClient() {
|
|
||||||
debug("inserting new client (" + std::to_string(ClientCount()) + ")");
|
|
||||||
WriteLock Lock(mClientsMutex);
|
|
||||||
auto [Iter, Replaced] = mClients.insert(std::make_shared<TClient>(*this));
|
|
||||||
return *Iter;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
||||||
decltype(mClients) Clients;
|
decltype(mClients) Clients;
|
||||||
@@ -63,12 +118,11 @@ size_t TServer::ClientCount() const {
|
|||||||
return mClients.size();
|
return mClients.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
||||||
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
|
constexpr std::string_view ABG = "ABG:";
|
||||||
//abort();
|
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) {
|
||||||
}
|
Packet.erase(Packet.begin(), Packet.begin() + ABG.size());
|
||||||
if (Packet.substr(0, 4) == "ABG:") {
|
Packet = DeComp(Packet);
|
||||||
Packet = DeComp(Packet.substr(4));
|
|
||||||
}
|
}
|
||||||
if (Packet.empty()) {
|
if (Packet.empty()) {
|
||||||
return;
|
return;
|
||||||
@@ -82,215 +136,227 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
std::any Res;
|
std::any Res;
|
||||||
char Code = Packet.at(0);
|
char Code = Packet.at(0);
|
||||||
|
|
||||||
//V to Z
|
std::string StringPacket(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
||||||
if (Code <= 90 && Code >= 86) {
|
|
||||||
|
// V to Y
|
||||||
|
if (Code <= 89 && Code >= 86) {
|
||||||
PPSMonitor.IncrementInternalPPS();
|
PPSMonitor.IncrementInternalPPS();
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (Code) {
|
switch (Code) {
|
||||||
case 'H': // initial connection
|
case 'H': // initial connection
|
||||||
trace(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
|
|
||||||
if (!Network.SyncClient(Client)) {
|
if (!Network.SyncClient(Client)) {
|
||||||
// TODO handle
|
// TODO handle
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'p':
|
case 'p':
|
||||||
if (!Network.Respond(*LockedClient, ("p"), false)) {
|
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) {
|
||||||
// failed to send
|
// failed to send
|
||||||
if (LockedClient->GetStatus() > -1) {
|
LockedClient->Disconnect("Failed to send ping");
|
||||||
LockedClient->SetStatus(-1);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
Network.UpdatePlayer(*LockedClient);
|
Network.UpdatePlayer(*LockedClient);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'O':
|
case 'O':
|
||||||
if (Packet.length() > 1000) {
|
if (Packet.size() > 1000) {
|
||||||
debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.length()));
|
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size()));
|
||||||
}
|
}
|
||||||
ParseVehicle(*LockedClient, Packet, Network);
|
ParseVehicle(*LockedClient, StringPacket, Network);
|
||||||
return;
|
return;
|
||||||
case 'J':
|
case 'C': {
|
||||||
trace(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
|
||||||
return;
|
|
||||||
case 'C':
|
|
||||||
trace(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
|
|
||||||
break;
|
break;
|
||||||
Res = TriggerLuaEvent("onChatMessage", false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 1) } }), true);
|
const auto PacketAsString = std::string(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
||||||
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), Packet.substr(Packet.find(':', 3) + 1)); // FIXME: this needs to be adjusted once lua is merged
|
std::string Message = "";
|
||||||
if (std::any_cast<int>(Res))
|
const auto ColonPos = PacketAsString.find(':', 3);
|
||||||
break;
|
if (ColonPos != std::string::npos && ColonPos + 2 < PacketAsString.size()) {
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
Message = PacketAsString.substr(ColonPos + 2);
|
||||||
|
}
|
||||||
|
if (Message.empty()) {
|
||||||
|
beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Message);
|
||||||
|
TLuaEngine::WaitForAll(Futures);
|
||||||
|
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
|
||||||
|
if (std::any_of(Futures.begin(), Futures.end(),
|
||||||
|
[](const std::shared_ptr<TLuaResult>& Elem) {
|
||||||
|
return !Elem->Error
|
||||||
|
&& Elem->Result.is<int>()
|
||||||
|
&& bool(Elem->Result.as<int>());
|
||||||
|
})) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message);
|
||||||
|
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
case 'E':
|
case 'E':
|
||||||
trace(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
HandleEvent(*LockedClient, StringPacket);
|
||||||
HandleEvent(*LockedClient, Packet);
|
|
||||||
return;
|
return;
|
||||||
case 'N':
|
case 'N':
|
||||||
trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
||||||
return;
|
return;
|
||||||
|
case 'Z': // position packet
|
||||||
|
PPSMonitor.IncrementInternalPPS();
|
||||||
|
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||||
|
HandlePosition(*LockedClient, StringPacket);
|
||||||
default:
|
default:
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::HandleEvent(TClient& c, const std::string& Data) {
|
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
||||||
std::stringstream ss(Data);
|
// E:Name:Data
|
||||||
std::string t, Name;
|
// Data is allowed to have ':'
|
||||||
int a = 0;
|
if (RawData.size() < 2) {
|
||||||
while (std::getline(ss, t, ':')) {
|
beammp_debugf("Client '{}' ({}) tried to send an empty event, ignoring", c.GetName(), c.GetID());
|
||||||
switch (a) {
|
return;
|
||||||
case 1:
|
|
||||||
Name = t;
|
|
||||||
break;
|
|
||||||
case 2:
|
|
||||||
TriggerLuaEvent(Name, false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), t } }), false);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
if (a == 2)
|
auto NameDataSep = RawData.find(':', 2);
|
||||||
break;
|
if (NameDataSep == std::string::npos) {
|
||||||
a++;
|
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
|
||||||
}
|
}
|
||||||
|
std::string Name = RawData.substr(2, NameDataSep - 2);
|
||||||
|
std::string Data = RawData.substr(NameDataSep + 1);
|
||||||
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), Data));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
||||||
rapidjson::Document Car;
|
try {
|
||||||
Car.Parse(CarJson.c_str(), CarJson.size());
|
auto Car = nlohmann::json::parse(CarJson);
|
||||||
if (Car.HasParseError()) {
|
const std::string jbm = "jbm";
|
||||||
error("Failed to parse vehicle data -> " + CarJson);
|
if (Car.contains(jbm) && Car[jbm].is_string() && Car[jbm] == "unicycle") {
|
||||||
} else if (Car["jbm"].IsString() && std::string(Car["jbm"].GetString()) == "unicycle") {
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'.");
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
||||||
|
if (IsUnicycle(c, CarJson) && c.GetUnicycleID() < 0) {
|
||||||
if (c.GetUnicycleID() > -1 && (c.GetCarCount() - 1) < Application::Settings.MaxCars) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (IsUnicycle(c, CarJson)) {
|
|
||||||
c.SetUnicycleID(ID);
|
c.SetUnicycleID(ID);
|
||||||
return true;
|
return true;
|
||||||
|
} else {
|
||||||
|
return c.GetCarCount() < Application::Settings.MaxCars;
|
||||||
}
|
}
|
||||||
|
|
||||||
return Application::Settings.MaxCars > c.GetCarCount();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
||||||
if (Pckt.length() < 4)
|
if (Pckt.length() < 6)
|
||||||
return;
|
return;
|
||||||
std::string Packet = Pckt;
|
std::string Packet = Pckt;
|
||||||
char Code = Packet.at(1);
|
char Code = Packet.at(1);
|
||||||
int PID = -1;
|
int PID = -1;
|
||||||
int VID = -1, Pos;
|
int VID = -1;
|
||||||
std::string Data = Packet.substr(3), pid, vid;
|
std::string Data = Packet.substr(3), pid, vid;
|
||||||
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
||||||
case 's':
|
case 's':
|
||||||
trace(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size());
|
||||||
if (Data.at(0) == '0') {
|
if (Data.at(0) == '0') {
|
||||||
int CarID = c.GetOpenCarID();
|
int CarID = c.GetOpenCarID();
|
||||||
debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID));
|
beammp_debugf("'{}' created a car with ID {}", c.GetName(), CarID);
|
||||||
|
|
||||||
std::string CarJson = Packet.substr(5);
|
std::string CarJson = Packet.substr(5);
|
||||||
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
||||||
auto Res = TriggerLuaEvent(("onVehicleSpawn"), false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), CarID, Packet.substr(3) } }), true);
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.GetID(), CarID, Packet.substr(3));
|
||||||
|
TLuaEngine::WaitForAll(Futures);
|
||||||
|
bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(),
|
||||||
|
[](const std::shared_ptr<TLuaResult>& Result) {
|
||||||
|
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
||||||
|
});
|
||||||
|
|
||||||
if (ShouldSpawn(c, CarJson, CarID) && std::any_cast<int>(Res) == 0) {
|
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
||||||
c.AddNewCar(CarID, Packet);
|
c.AddNewCar(CarID, Packet);
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
} else {
|
} else {
|
||||||
if (!Network.Respond(c, Packet, true)) {
|
if (!Network.Respond(c, StringToVector(Packet), true)) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
||||||
if (!Network.Respond(c, Destroy, true)) {
|
if (!Network.Respond(c, StringToVector(Destroy), true)) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
debug(c.GetName() + (" (force : car limit/lua) removed ID ") + std::to_string(CarID));
|
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'c':
|
case 'c': {
|
||||||
trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
pid = Data.substr(0, Data.find('-'));
|
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||||
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
|
if (MaybePidVid) {
|
||||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
std::tie(PID, VID) = MaybePidVid.value();
|
||||||
PID = stoi(pid);
|
|
||||||
VID = stoi(vid);
|
|
||||||
}
|
}
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
auto Res = TriggerLuaEvent(("onVehicleEdited"), false, nullptr,
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
|
||||||
std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), VID, Packet.substr(3) } }),
|
TLuaEngine::WaitForAll(Futures);
|
||||||
true);
|
bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(),
|
||||||
|
[](const std::shared_ptr<TLuaResult>& Result) {
|
||||||
|
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
||||||
|
});
|
||||||
|
|
||||||
auto FoundPos = Packet.find('{');
|
auto FoundPos = Packet.find('{');
|
||||||
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
||||||
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
||||||
&& std::any_cast<int>(Res) == 0) {
|
&& !ShouldntAllow) {
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||||
Apply(c, VID, Packet);
|
Apply(c, VID, Packet);
|
||||||
} else {
|
} else {
|
||||||
if (c.GetUnicycleID() == VID) {
|
if (c.GetUnicycleID() == VID) {
|
||||||
c.SetUnicycleID(-1);
|
c.SetUnicycleID(-1);
|
||||||
}
|
}
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
||||||
if (!Network.Respond(c, Destroy, true)) {
|
Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
c.DeleteCar(VID);
|
c.DeleteCar(VID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'd':
|
}
|
||||||
trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
case 'd': {
|
||||||
pid = Data.substr(0, Data.find('-'));
|
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
vid = Data.substr(Data.find('-') + 1);
|
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
if (MaybePidVid) {
|
||||||
PID = stoi(pid);
|
std::tie(PID, VID) = MaybePidVid.value();
|
||||||
VID = stoi(vid);
|
|
||||||
}
|
}
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
if (c.GetUnicycleID() == VID) {
|
if (c.GetUnicycleID() == VID) {
|
||||||
c.SetUnicycleID(-1);
|
c.SetUnicycleID(-1);
|
||||||
}
|
}
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
TriggerLuaEvent(("onVehicleDeleted"), false, nullptr,
|
// TODO: should this trigger on all vehicle deletions?
|
||||||
std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), VID } }), false);
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
||||||
c.DeleteCar(VID);
|
c.DeleteCar(VID);
|
||||||
debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'r':
|
}
|
||||||
trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
case 'r': {
|
||||||
Pos = int(Data.find('-'));
|
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
pid = Data.substr(0, Pos++);
|
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||||
vid = Data.substr(Pos, Data.find(':') - Pos);
|
if (MaybePidVid) {
|
||||||
|
std::tie(PID, VID) = MaybePidVid.value();
|
||||||
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()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
Data = Data.substr(Data.find('{'));
|
Data = Data.substr(Data.find('{'));
|
||||||
TriggerLuaEvent("onVehicleReset", false, nullptr,
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
||||||
std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), VID, Data } }),
|
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||||
false);
|
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
case 't':
|
case 't':
|
||||||
trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||||
|
return;
|
||||||
|
case 'm':
|
||||||
|
Network.SendToAll(&c, StringToVector(Packet), true, true);
|
||||||
return;
|
return;
|
||||||
default:
|
default:
|
||||||
trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -298,42 +364,31 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
||||||
auto FoundPos = pckt.find('{');
|
auto FoundPos = pckt.find('{');
|
||||||
if (FoundPos == std::string::npos) {
|
if (FoundPos == std::string::npos) {
|
||||||
error("Malformed packet received, no '{' found");
|
beammp_error("Malformed packet received, no '{' found");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::string Packet = pckt.substr(FoundPos);
|
std::string Packet = pckt.substr(FoundPos);
|
||||||
std::string VD = c.GetCarData(VID);
|
std::string VD = c.GetCarData(VID);
|
||||||
if (VD.empty()) {
|
if (VD.empty()) {
|
||||||
error("Tried to apply change to vehicle that does not exist");
|
beammp_error("Tried to apply change to vehicle that does not exist");
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
|
||||||
Sentry.SetContext("vehicle-change",
|
|
||||||
{ { "packet", Packet },
|
|
||||||
{ "vehicle-id", std::to_string(VID) },
|
|
||||||
{ "client-car-count", std::to_string(c.GetCarCount()) } });
|
|
||||||
Sentry.LogError("attempt to apply change to nonexistent vehicle", _file_basename, _line);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::string Header = VD.substr(0, VD.find('{'));
|
std::string Header = VD.substr(0, VD.find('{'));
|
||||||
|
|
||||||
FoundPos = VD.find('{');
|
FoundPos = VD.find('{');
|
||||||
if (FoundPos == std::string::npos) {
|
if (FoundPos == std::string::npos) {
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
|
||||||
Sentry.SetContext("vehicle-change-packet",
|
|
||||||
{ { "packet", VD } });
|
|
||||||
Sentry.LogError("malformed packet", _file_basename, _line);
|
|
||||||
error("Malformed packet received, no '{' found");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
VD = VD.substr(FoundPos);
|
VD = VD.substr(FoundPos);
|
||||||
rapidjson::Document Veh, Pack;
|
rapidjson::Document Veh, Pack;
|
||||||
Veh.Parse(VD.c_str());
|
Veh.Parse(VD.c_str());
|
||||||
if (Veh.HasParseError()) {
|
if (Veh.HasParseError()) {
|
||||||
error("Could not get vehicle config!");
|
beammp_error("Could not get vehicle config!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Pack.Parse(Packet.c_str());
|
Pack.Parse(Packet.c_str());
|
||||||
if (Pack.HasParseError() || Pack.IsNull()) {
|
if (Pack.HasParseError() || Pack.IsNull()) {
|
||||||
error("Could not get active vehicle config!");
|
beammp_error("Could not get active vehicle config!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -351,7 +406,40 @@ void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
||||||
debug("inserting client (" + std::to_string(ClientCount()) + ")");
|
beammp_debug("inserting client (" + std::to_string(ClientCount()) + ")");
|
||||||
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
||||||
(void)mClients.insert(NewClient);
|
(void)mClients.insert(NewClient);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void TServer::HandlePosition(TClient& c, const std::string& Packet) {
|
||||||
|
if (Packet.size() < 3) {
|
||||||
|
// invalid packet
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Zp:serverVehicleID:data
|
||||||
|
// Zp:0:data
|
||||||
|
std::string withoutCode = Packet.substr(3);
|
||||||
|
auto NameDataSep = withoutCode.find(':', 2);
|
||||||
|
if (NameDataSep == std::string::npos || NameDataSep < 2) {
|
||||||
|
// invalid packet
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// FIXME: ensure that -2 does what it should... it seems weird.
|
||||||
|
std::string ServerVehicleID = withoutCode.substr(2, NameDataSep - 2);
|
||||||
|
if (NameDataSep + 1 > withoutCode.size()) {
|
||||||
|
// invalid packet
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::string Data = withoutCode.substr(NameDataSep + 1);
|
||||||
|
|
||||||
|
// parse veh ID
|
||||||
|
auto MaybePidVid = GetPidVid(ServerVehicleID);
|
||||||
|
if (MaybePidVid) {
|
||||||
|
int PID = -1;
|
||||||
|
int VID = -1;
|
||||||
|
// FIXME: check that the VID and PID are valid, so that we don't waste memory
|
||||||
|
std::tie(PID, VID) = MaybePidVid.value();
|
||||||
|
|
||||||
|
c.SetCarPosition(VID, Data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+2
-2
@@ -6,9 +6,9 @@
|
|||||||
TVehicleData::TVehicleData(int ID, std::string Data)
|
TVehicleData::TVehicleData(int ID, std::string Data)
|
||||||
: mID(ID)
|
: mID(ID)
|
||||||
, mData(std::move(Data)) {
|
, mData(std::move(Data)) {
|
||||||
trace("vehicle " + std::to_string(mID) + " constructed");
|
beammp_trace("vehicle " + std::to_string(mID) + " constructed");
|
||||||
}
|
}
|
||||||
|
|
||||||
TVehicleData::~TVehicleData() {
|
TVehicleData::~TVehicleData() {
|
||||||
trace("vehicle " + std::to_string(mID) + " destroyed");
|
beammp_trace("vehicle " + std::to_string(mID) + " destroyed");
|
||||||
}
|
}
|
||||||
|
|||||||
+169
-59
@@ -1,91 +1,201 @@
|
|||||||
#include "TSentry.h"
|
#include "ArgsParser.h"
|
||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
#include "LuaAPI.h"
|
||||||
|
#include "SignalHandling.h"
|
||||||
#include "TConfig.h"
|
#include "TConfig.h"
|
||||||
#include "THeartbeatThread.h"
|
#include "THeartbeatThread.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
#include "TNetwork.h"
|
#include "TNetwork.h"
|
||||||
#include "TPPSMonitor.h"
|
#include "TPPSMonitor.h"
|
||||||
|
#include "TPluginMonitor.h"
|
||||||
#include "TResourceManager.h"
|
#include "TResourceManager.h"
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
#ifdef __unix
|
static const std::string sCommandlineArguments = R"(
|
||||||
#include <csignal>
|
USAGE:
|
||||||
|
BeamMP-Server [arguments]
|
||||||
|
|
||||||
void UnixSignalHandler(int sig) {
|
ARGUMENTS:
|
||||||
switch (sig) {
|
--help
|
||||||
case SIGPIPE:
|
Displays this help and exits.
|
||||||
warn("ignoring SIGPIPE");
|
--config=/path/to/ServerConfig.toml
|
||||||
break;
|
Absolute or relative path to the
|
||||||
case SIGTERM:
|
Server Config file, including the
|
||||||
info("gracefully shutting down via SIGTERM");
|
filename. For paths and filenames with
|
||||||
Application::GracefullyShutdown();
|
spaces, put quotes around the path.
|
||||||
break;
|
--working-directory=/path/to/folder
|
||||||
case SIGINT:
|
Sets the working directory of the Server.
|
||||||
info("gracefully shutting down via SIGINT");
|
All paths are considered relative to this,
|
||||||
Application::GracefullyShutdown();
|
including the path given in --config.
|
||||||
break;
|
--version
|
||||||
default:
|
Prints version info and exits.
|
||||||
debug("unhandled signal: " + std::to_string(sig));
|
|
||||||
break;
|
EXAMPLES:
|
||||||
|
BeamMP-Server --config=../MyWestCoastServerConfig.toml
|
||||||
|
Runs the BeamMP-Server and uses the server config file
|
||||||
|
which is one directory above it and is named
|
||||||
|
'MyWestCoastServerConfig.toml'.
|
||||||
|
)";
|
||||||
|
|
||||||
|
struct MainArguments {
|
||||||
|
int argc {};
|
||||||
|
char** argv {};
|
||||||
|
std::vector<std::string_view> List;
|
||||||
|
std::string InvokedAs;
|
||||||
|
};
|
||||||
|
|
||||||
|
int BeamMPServerMain(MainArguments Arguments);
|
||||||
|
|
||||||
|
int main(int argc, char** argv) {
|
||||||
|
MainArguments Args { argc, argv, {}, argv[0] };
|
||||||
|
Args.List.reserve(size_t(argc));
|
||||||
|
for (int i = 1; i < argc; ++i) {
|
||||||
|
Args.List.push_back(argv[i]);
|
||||||
}
|
}
|
||||||
|
int MainRet = 0;
|
||||||
|
try {
|
||||||
|
MainRet = BeamMPServerMain(std::move(Args));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_error("A fatal exception has occurred and the server is forcefully shutting down.");
|
||||||
|
beammp_error(e.what());
|
||||||
|
MainRet = -1;
|
||||||
|
}
|
||||||
|
std::exit(MainRet);
|
||||||
}
|
}
|
||||||
#endif // __unix
|
|
||||||
|
|
||||||
// this is provided by the build system, leave empty for source builds
|
int BeamMPServerMain(MainArguments Arguments) {
|
||||||
// global, yes, this is ugly, no, it cant be done another way
|
|
||||||
TSentry Sentry {};
|
|
||||||
|
|
||||||
#include <iostream>
|
|
||||||
|
|
||||||
int main(int argc, char** argv) try {
|
|
||||||
#ifdef __unix
|
|
||||||
trace("registering handlers for SIGINT, SIGTERM, SIGPIPE");
|
|
||||||
signal(SIGPIPE, UnixSignalHandler);
|
|
||||||
signal(SIGTERM, UnixSignalHandler);
|
|
||||||
#ifndef DEBUG
|
|
||||||
signal(SIGINT, UnixSignalHandler);
|
|
||||||
#endif // DEBUG
|
|
||||||
#endif // __unix
|
|
||||||
setlocale(LC_ALL, "C");
|
setlocale(LC_ALL, "C");
|
||||||
|
ArgsParser Parser;
|
||||||
bool Shutdown = false;
|
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
|
||||||
Application::RegisterShutdownHandler([&Shutdown] { Shutdown = true; });
|
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
|
||||||
Application::RegisterShutdownHandler([] { TriggerLuaEvent("onShutdown", false, nullptr, {}, true); });
|
Parser.RegisterArgument({ "config" }, ArgsParser::HAS_VALUE);
|
||||||
|
Parser.RegisterArgument({ "working-directory" }, ArgsParser::HAS_VALUE);
|
||||||
TServer Server(argc, argv);
|
Parser.Parse(Arguments.List);
|
||||||
TConfig Config;
|
if (!Parser.Verify()) {
|
||||||
|
|
||||||
if (Config.Failed()) {
|
|
||||||
info("Closing in 10 seconds");
|
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(10));
|
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
if (Parser.FoundArgument({ "help" })) {
|
||||||
|
Application::Console().WriteRaw(sCommandlineArguments);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (Parser.FoundArgument({ "version" })) {
|
||||||
|
Application::Console().WriteRaw("BeamMP-Server v" + Application::ServerVersionString());
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string ConfigPath = "ServerConfig.toml";
|
||||||
|
if (Parser.FoundArgument({ "config" })) {
|
||||||
|
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
|
||||||
|
if (MaybeConfigPath.has_value()) {
|
||||||
|
ConfigPath = MaybeConfigPath.value();
|
||||||
|
beammp_info("Custom config requested via commandline arguments: '" + ConfigPath + "'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Parser.FoundArgument({ "working-directory" })) {
|
||||||
|
auto MaybeWorkingDirectory = Parser.GetValueOfArgument({ "working-directory" });
|
||||||
|
if (MaybeWorkingDirectory.has_value()) {
|
||||||
|
beammp_info("Custom working directory requested via commandline arguments: '" + MaybeWorkingDirectory.value() + "'");
|
||||||
|
try {
|
||||||
|
fs::current_path(fs::path(MaybeWorkingDirectory.value()));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_errorf("Could not set working directory to '{}': {}", MaybeWorkingDirectory.value(), e.what());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TConfig Config(ConfigPath);
|
||||||
|
|
||||||
|
if (Config.Failed()) {
|
||||||
|
beammp_info("Closing in 10 seconds");
|
||||||
|
// loop to make it possible to ctrl+c instead
|
||||||
|
for (size_t i = 0; i < 20; ++i) {
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
Application::InitializeConsole();
|
||||||
|
Application::Console().StartLoggingToFile();
|
||||||
|
|
||||||
|
Application::SetSubsystemStatus("Main", Application::Status::Starting);
|
||||||
|
|
||||||
|
SetupSignalHandlers();
|
||||||
|
|
||||||
|
bool Shutdown = false;
|
||||||
|
Application::RegisterShutdownHandler([&Shutdown] {
|
||||||
|
beammp_info("If this takes too long, you can press Ctrl+C repeatedly to force a shutdown.");
|
||||||
|
Application::SetSubsystemStatus("Main", Application::Status::ShuttingDown);
|
||||||
|
Shutdown = true;
|
||||||
|
});
|
||||||
|
Application::RegisterShutdownHandler([] {
|
||||||
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onShutdown", "");
|
||||||
|
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
||||||
|
});
|
||||||
|
|
||||||
|
TServer Server(Arguments.List);
|
||||||
|
|
||||||
|
auto LuaEngine = std::make_shared<TLuaEngine>();
|
||||||
|
LuaEngine->SetServer(&Server);
|
||||||
|
Application::Console().InitializeLuaConsole(*LuaEngine);
|
||||||
|
|
||||||
RegisterThread("Main");
|
RegisterThread("Main");
|
||||||
|
|
||||||
trace("Running in debug mode on a debug build");
|
beammp_trace("Running in debug mode on a debug build");
|
||||||
|
|
||||||
Sentry.SetupUser();
|
|
||||||
Sentry.PrintWelcome();
|
|
||||||
Application::CheckForUpdates();
|
|
||||||
TResourceManager ResourceManager;
|
TResourceManager ResourceManager;
|
||||||
TPPSMonitor PPSMonitor(Server);
|
TPPSMonitor PPSMonitor(Server);
|
||||||
THeartbeatThread Heartbeat(ResourceManager, Server);
|
THeartbeatThread Heartbeat(ResourceManager, Server);
|
||||||
TNetwork Network(Server, PPSMonitor, ResourceManager);
|
TNetwork Network(Server, PPSMonitor, ResourceManager);
|
||||||
TLuaEngine LuaEngine(Server, Network);
|
LuaEngine->SetNetwork(&Network);
|
||||||
PPSMonitor.SetNetwork(Network);
|
PPSMonitor.SetNetwork(Network);
|
||||||
Application::Console().InitializeLuaConsole(LuaEngine);
|
Application::CheckForUpdates();
|
||||||
|
|
||||||
// TODO: replace
|
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
|
||||||
|
|
||||||
|
if (Application::Settings.HTTPServerEnabled) {
|
||||||
|
Http::Server::THttpServerInstance HttpServerInstance {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Application::SetSubsystemStatus("Main", Application::Status::Good);
|
||||||
|
RegisterThread("Main(Waiting)");
|
||||||
|
|
||||||
|
std::set<std::string> IgnoreSubsystems {
|
||||||
|
"UpdateCheck" // Ignore as not to confuse users (non-vital system)
|
||||||
|
};
|
||||||
|
|
||||||
|
bool FullyStarted = false;
|
||||||
while (!Shutdown) {
|
while (!Shutdown) {
|
||||||
|
if (!FullyStarted) {
|
||||||
|
FullyStarted = true;
|
||||||
|
bool WithErrors = false;
|
||||||
|
std::string SystemsBadList {};
|
||||||
|
auto Statuses = Application::GetSubsystemStatuses();
|
||||||
|
for (const auto& NameStatusPair : Statuses) {
|
||||||
|
if (IgnoreSubsystems.count(NameStatusPair.first) > 0) {
|
||||||
|
continue; // ignore
|
||||||
|
}
|
||||||
|
if (NameStatusPair.second == Application::Status::Starting) {
|
||||||
|
FullyStarted = false;
|
||||||
|
} else if (NameStatusPair.second == Application::Status::Bad) {
|
||||||
|
SystemsBadList += NameStatusPair.first + ", ";
|
||||||
|
WithErrors = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// remove ", "
|
||||||
|
SystemsBadList = SystemsBadList.substr(0, SystemsBadList.size() - 2);
|
||||||
|
if (FullyStarted) {
|
||||||
|
if (!WithErrors) {
|
||||||
|
beammp_info("ALL SYSTEMS STARTED SUCCESSFULLY, EVERYTHING IS OKAY");
|
||||||
|
} else {
|
||||||
|
beammp_error("STARTUP NOT SUCCESSFUL, SYSTEMS " + SystemsBadList + " HAD ERRORS. THIS MAY OR MAY NOT CAUSE ISSUES.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
Application::SetSubsystemStatus("Main", Application::Status::Shutdown);
|
||||||
error(e.what());
|
beammp_info("Shutdown.");
|
||||||
Sentry.LogException(e, _file_basename, _line);
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#define DOCTEST_CONFIG_IMPLEMENT
|
||||||
|
#include <doctest/doctest.h>
|
||||||
|
|
||||||
|
#include <Common.h>
|
||||||
|
|
||||||
|
int main(int argc, char** argv) {
|
||||||
|
doctest::Context context;
|
||||||
|
|
||||||
|
// Application::InitializeConsole();
|
||||||
|
|
||||||
|
context.applyCommandLine(argc, argv);
|
||||||
|
|
||||||
|
int res = context.run(); // run
|
||||||
|
|
||||||
|
if (context.shouldExit()) // important - query flags (and --exit) rely on the user doing this
|
||||||
|
return res; // propagate the result of the tests
|
||||||
|
|
||||||
|
int client_stuff_return_code = 0;
|
||||||
|
// your program - if the testing framework is integrated in your production code
|
||||||
|
|
||||||
|
return res + client_stuff_return_code; // the result from doctest is propagated here as well
|
||||||
|
}
|
||||||
Submodule
+1
Submodule vcpkg added at 72010900b7
+19
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "server",
|
||||||
|
"version-string": "0.1.0",
|
||||||
|
"dependencies": [
|
||||||
|
"fmt",
|
||||||
|
"doctest",
|
||||||
|
"boost-asio",
|
||||||
|
"boost-variant",
|
||||||
|
"boost-spirit",
|
||||||
|
"boost-uuid",
|
||||||
|
"cpp-httplib",
|
||||||
|
"toml11",
|
||||||
|
"libzip",
|
||||||
|
"rapidjson",
|
||||||
|
"nlohmann-json",
|
||||||
|
"openssl",
|
||||||
|
"sol2"
|
||||||
|
]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user