2
0
mirror of https://github.com/rehlds/rehlds.git synced 2025-07-25 14:41:44 +03:00

Compare commits

...

179 Commits

Author SHA1 Message Date
b3f2d7d6cc
[chore] improved ci build and signing only at release publish 2025-07-22 20:59:14 +03:00
14f7665e54
[chore] improved ci build and signing at release publish 2025-07-22 20:47:35 +03:00
89f17f5b7f
Merge branch 'bugfix/ci-fixes' 2025-07-21 12:20:03 +03:00
c69fd54580
ci-build updated
+ added signing
 + migrated to windows-2025 runner
+ wmic deprecated and migrated to ps
2025-07-21 12:19:53 +03:00
ec4cef7937
CHANGELOG.md update 2025-07-19 23:54:27 +03:00
09368ebd7e
[chore] License transition from GPLv3 to MIT
[chore] License transition from GPLv3 to MIT
2025-07-19 22:45:54 +03:00
cbeb08abd3
[chore] License transition from GPLv3 to MIT 2025-07-19 22:42:53 +03:00
s1lentq
ae2639d3df filesystem: fix reversing mistake closed #1101
fix crash related #972
2025-07-15 22:50:33 +07:00
jonatan1024
1571474af7
message manager fix (#1089) 2025-04-25 22:27:10 +07:00
Eason
97dd83d626
Add API function SetServerPause (#1086) 2025-04-08 17:47:13 +07:00
5cac7a97ab
also disable sign at linux builds from PRs 2025-04-06 14:16:04 +03:00
s1lentq
44e510a25c SV_EmitSound2: Add new flag SND_EMIT2_USE_ORIGIN for using custom origin instead of entity origin 2025-04-05 02:20:58 +07:00
Faruk
7bc5d86add
cmake dependecy (#1080) 2025-04-04 05:09:13 +07:00
Splatt581
98b4103b86
Added check for invalid utf8 chars in userinfo (#1074) 2025-04-04 05:08:30 +07:00
s1lentq
2f87ace7fc Fix dumb bug where skip logos without advancing to next iter, causing an endless loop when sv_send_logos is disabled Fixes #1085 2025-04-02 21:16:17 +07:00
s1lentq
a2953ea374 API game message manager: fix typo 2025-04-01 22:26:38 +07:00
s1lentq
45fe816fdd API game message manager: add support signed/unsigned value for char,short types 2025-03-29 02:46:36 +07:00
s1lentq
89958d348e Update build.yml 2025-03-28 02:41:18 +07:00
e9991716fc
Added codesign and resources (#1069)
* Added codesign and resources

- for Windows: https://github.com/rehlds/.github/issues/30 and https://github.com/rehlds/.github/issues/29

- for Linux:  https://github.com/rehlds/.github/issues/28
2024-12-26 11:29:08 +03:00
Sergey Shorokhov
20c16bfad3
IP and IPX allocation warnings move under -dev arg (#1071) 2024-12-18 20:07:52 +03:00
Sergey Shorokhov
28c205de11 CI: add workflow_dispatch event trigger
[skip ci]
2024-12-14 18:07:53 +03:00
s1lentq
1a68407710 Netchan_CopyFileFragments: fix typo 2024-12-12 04:35:38 +07:00
Francisco Muñoz
4afb6e3be9
Move SV_CheckMovingGround into SV_Physics (#1045) 2024-12-09 19:20:17 +07:00
s1lentq
e83b324301 Fix build 2024-12-09 01:21:00 +07:00
s1lentq
64c684af4a Added new CVARs for improved handling of decompression failures:
- `sv_net_incoming_decompression_min_failures`: Min failures required to flag a player
- `sv_net_incoming_decompression_max_failures`: max failures allowed before punishment
- `sv_net_incoming_decompression_min_failuretime`: Time window for failure tracking
2024-12-09 00:02:33 +07:00
s1lentq
e54adb089c fix crash due fakeclient 2024-12-08 08:57:51 +07:00
s1lentq
18b173d5c6 Fix potential crash 2024-12-08 05:15:11 +07:00
s1lentq
6e6368da30 CalcSurfaceExtents: more info in extents error message 2024-12-08 00:36:04 +07:00
s1lentq
df862d9bb6 Improved movevars sync logic for clients, allowing independent sync of movement props for each client, regardless of global movevars 2024-12-08 00:18:36 +07:00
12b35dbe8c
deleted local GitHub Action 2024-11-20 00:25:27 +03:00
c17dacd152
reHLDS -> ReHLDS 2024-11-16 00:56:23 +03:00
85d55d15db
Merge pull request #1058 from rehlds/feature/improvements
added changelog
2024-11-06 13:39:04 +03:00
df704585aa
meta improvemetns
* added changelog
2024-11-03 14:46:08 +03:00
Sergey Shorokhov
5a1f66a6b4
CI Workflow Improvements and Fixes (#1056)
chore(ci): standardize and update CI workflows for compatibility and consistency

- Updated action versions (`checkout@v4`, `upload-artifact@v4`, `download-artifact@v4`) for enhanced compatibility and security
- Removed unsecure Node.js version allowance to align with *-latest OS requirements
- Downgraded MSBuild to version 16 to resolve CI compatibility issues
- Migrated test demos to `rehldsorg/testdemos:latest` container with a streamlined testing approach via matrix strategy and `runTest.sh`
- Standardized Linux dependency installation for consistent build environment across jobs
- Unified CI workflow structure with `rehlds` and `regamedll` repositories for better consistency
- Optimized artifact deployment steps and removed unnecessary cleanup operations

Co-authored-by: s1lentq <s1lentsk@yandex.ru>
2024-10-29 09:20:39 +03:00
s1lentq
fe184a82e0 SV_ProcessFile: Ignore customization file uploads if upload is disabled 2024-10-24 02:28:47 +07:00
s1lentq
b29740c19e CalcSurfaceExtents: MAX_SURFACE_TEXTURE_SIZE limit increased from 256 to 512 2024-09-25 02:02:44 +07:00
肯定龙
7073363c88
Small fix in sv_user.cpp (#1042) 2024-08-07 07:24:29 +07:00
s1lentq
2834fb8494 Minor refactoring and improve readability 2024-08-01 03:34:00 +07:00
s1lentq
c8308a2c60 [HLTV] Fix reverse-engineering mistake in World::WritePacketEntities 2024-08-01 00:12:34 +07:00
s1lentq
ed954a710f [HLTV] Fix reverse-engineering mistake in ObjectDictionary::RemoveIndex 2024-08-01 00:09:32 +07:00
Eason
9935f8bc75
Workflows: fix linux build(Action Checkout) (#1040)
* Update build.yml
2024-07-31 01:37:36 +07:00
s1lentq
9c1e84328e Fixed GCC compilation warnings/errors
Fixes #1032
2024-05-30 19:15:39 +07:00
s1lentq
c1ccc5009a Fix warning compiler in linux build 2024-05-27 05:08:02 +07:00
s1lentq
0f45ec09fa Enhanced API interface game message manager
Bump major API version
Minor refactoring
2024-05-27 05:01:37 +07:00
s1lentq
c9f9bbfff9 Implement API interface game message manager 2024-05-13 19:20:19 +07:00
s1lentq
a761efa75d Minor cleanup 2024-05-13 18:48:35 +07:00
Adrian Cirstea
82a3d1d084
Add SV_SendResources hook (#1024)
* Implement `SV_AddResources` hook
2024-05-10 18:15:22 +07:00
s1lentq
693b51c883 Improved behavior of sv_filterban 0. Fixes #1027 2024-05-10 18:05:41 +07:00
s1lentq
47ffe4b257 Fix rehlsdk 2024-05-10 17:43:24 +07:00
s1lentq
3c4acbb046 Fix warning 2024-05-10 17:42:05 +07:00
s1lentq
5b72d06bfb Fix default value for sv_net_incoming_decompression_max_ratio 2024-05-10 17:38:09 +07:00
Dmitry Novikov
0d1bdbab67
Implemented reduction of impact caused by zip-bomb exploit (#994)
* Implemented reduction of impact caused by zip-bomb exploit
Added network security CVars:
- sv_net_incoming_decompression (0-1) Enables or disables incoming data decompression
- sv_net_incoming_decompression_max_ratio (0.0 - 100.0) Sets max allowed ratio between compressed and decompressed data. (A ratio close to 90 indicates large uncompressed data with low entropy)
- sv_net_incoming_decompression_max_size (16-65536) Adjusts max size of output data after decompression.
Added CVar sv_net_incoming_decompression_punish for ban
* Fix missing reg CVar sv_net_incoming_decompression_punish
2024-04-14 01:04:03 +07:00
s1lentq
61ee4f9269 Netchan_CreateFileFragments: Fixed a hang connection on verifying resource stage, when precached file exists but is absolutely empty 2024-04-10 12:30:59 +07:00
Sergey Shorokhov
b870de768b
fix: README badges
[skip ci]
2024-04-06 22:09:47 +03:00
s1lentq
3c282b435c Draw_ValidateCustomLogo: Fixed incorrect offset to palette size 2024-03-26 20:41:53 +07:00
s1lentq
ec47e4d978 Do not propagate custom logos according to sv_send_logos cvar 2024-03-18 22:17:23 +07:00
s1lentq
462fe55fb8 SV_CreateCustomizationList: spew logs in only dev mode 2024-03-18 22:12:01 +07:00
s1lentq
f26ad71aba Do not send customizations list on duplicate or missing resource 2024-03-18 22:09:18 +07:00
s1lentq
59ed3f6867 SV_ParseResourceList: Do not uploading according to sv_allowupload cvar 2024-03-18 22:04:02 +07:00
s1lentq
516bb93627 HPAK_ResourceForHash: Remove message with missing custom.hpk 2024-03-18 21:59:18 +07:00
s1lentq
174414db81 Draw_ValidateCustomLogo: Minor refactoring & cleanup 2024-03-18 21:57:57 +07:00
anzz1
05f4a279f9
Add steamcmd instructions to readme (#1021) 2024-03-02 22:24:04 +07:00
s1lentq
58391b6ee5 SV_WriteEntitiesToClient: Reset movetype if the aiment index is invalid 2024-02-20 03:18:36 +07:00
s1lentq
498d7e0d18 Fix crash when the entity with aiment doesn't have a model 2024-02-14 19:23:16 +07:00
s1lentq
a7b60451f3 TEX_InitFromWad: Fix reversing mistake (Don't add file handle before check) 2024-01-31 15:41:00 +07:00
s1lentq
63fde229c9 MSG_WriteBitAngle: Cap the precision check from 32 to 22 to avoid overflow issues when representing angles with more than 22 bits because the multiply by 'shift' may result in overflow 2024-01-26 07:50:09 +07:00
s1lentq
9b0dbe8dd2 Host_Status_f: Fixed incorrect player index to output 2024-01-25 18:36:03 +07:00
s1lentq
41c5186b2c RCON: Fixes redirect print and minor refactoring 2024-01-22 05:48:34 +07:00
s1lentq
90cb97ddae Update README.md 2024-01-18 21:50:33 +07:00
s1lentq
76cbd2c140 Implemented optional CVar sv_tags for sets a string defining the "gametags" for this server to allows users/scripts to filter in the matchmaking/server-browser interfaces based on the value 2024-01-18 21:46:25 +07:00
s1lentq
f29d6c5769 Update README.md 2024-01-18 00:56:32 +07:00
s1lentq
355172d6db Fix unit-test 2024-01-18 00:46:45 +07:00
s1lentq
62407e0dd6 Implement commands rcon_adduser,rcon_deluser,rcon_users to allow use RCON only by known user IPs (Resolves #796)
SV_Rcon: Minor refactoring
2024-01-18 00:40:16 +07:00
s1lentq
1d6c6826db fix build 2024-01-14 00:24:33 +07:00
s1lentq
5002ff9abe Prevent crash "Cache_UnlinkLRU: NULL link" on client-side if aiment with sprite model will be to render as a studio model 2024-01-14 00:18:08 +07:00
s1lentq
32857e7785 Fix no exec config file when exceed limit text buffer 2024-01-12 22:32:15 +07:00
s1lentq
93f5775ac2 Reworked AlertMessage 2023-12-14 07:40:45 +07:00
s1lentq
0af97d98bb Add reg cvar r_cachestudio 2023-11-28 18:21:53 +07:00
s1lentq
ffb65795dd Update workflows/build.yml
Fixes #1004
2023-11-22 23:41:21 +07:00
Alibek Omarov
3f19bc1d3e
engine: add sv_allow_autoaim cvar for HL25 DLL compatibility (#1000)
add sv_allow_autoaim cvar for HL25 DLL compatibility
2023-11-21 08:35:36 +07:00
s1lentq
7fcec97af4 Add support cheats command god,notarget,noclip 2023-10-09 01:57:11 +07:00
Hamdi
b7f6eb8023
Minor refactor ( add BoundsIntersect function ) (#986) 2023-09-28 00:41:37 +07:00
Francisco Muñoz
5ec8c29185
Update world.cpp (#985) 2023-09-25 03:40:50 +07:00
s1lentq
6f031901cf Added cvarhook from latest HLDS build
Making mapcyclefile/sv_cheats work in realtime
Resolve #868
2023-09-25 02:08:04 +07:00
s1lentq
de3679f039 Host_Motd_f: Fixed viewing motd when motdfile is not specified 2023-09-20 21:00:44 +07:00
s1lentq
2ba27d409c Fixed reversing mistake, missing checking string for null 2023-09-03 15:08:30 +07:00
Sergey Shorokhov
f955b07b69
Revert "change destinition folder for linux build (#842)" (#977)
This reverts commit 9508c8376bd14fbcd92beaa93b191ee4fb1c90a3.
2023-07-03 22:02:28 +03:00
s1lentq
918612fa23 GetBonePosition: Added bone index bounds check 2023-07-04 01:39:26 +07:00
s1lentq
8841ba4aec GetAttachment: Added attachment index bounds check 2023-07-04 01:33:41 +07:00
s1lentq
0c5ce53666 Allow the clients to connect on the server of different game Fixed #975
Client should be use "setinfo _gd <game>"
2023-07-02 03:47:05 +07:00
Sergey Shorokhov
a680f18ee1 SV_BuildSoundMsg: fix '\n' in args check
- fix #965
2023-05-08 12:24:16 +03:00
Hamdi
1796459953
Add SV_AllowPhysent hook (#951)
* Add SV_AllowPhysent hook
2023-02-11 07:03:53 +07:00
s1lentq
5e8b0ba616 Increased limit leafs MAX_MAP_LEAFS up to 32767 2022-12-07 19:17:09 +07:00
s1lentq
14b56e0514 Added more check for possible numleaf overflow
Minor refactoring
2022-12-07 19:15:08 +07:00
Adrian Cirstea
d6ebe82833
API: Implement *_Precache_*, ClientPrintf, CheckUserInfo and AddResource hooks (#903)
* Added SV_CheckUserInfo hook

* Implemented PF_precache_*  hooks

- PF_precache_sound_I
- PF_precache_model_I
- PF_precache_generic_I

* Added EV_Precache and SV_AddResource hooks

and update API minor version

* Added SV_AddResource_internal and fixed pointers

* Added SV_AddResource_hook, fixed chain EV_Precache

* Reworked SV_AddResource for Rehlds API

* Reverted RehldsFuncs_t's SV_AddResource API

* Updated chains

* Update rehlds_api_impl.h

* Implement `SV_ClientPrintf` hook

* Changed `SV_ClientPrintf` chain type to void

* Revert `SV_ClientPrintf` code refactor

* Removed `const` string type

in order to resize the string.

* Changes according to var type

* Fixing function's functionality

* Moved vars declaration after `host_client` check

* revert variable naming in SV_ClientPrintf

* `SV_ClientPrintf_internal`: more safe string copy

Co-authored-by: wopox1337 <wopox1337@ya.ru>
2022-09-19 14:20:33 +03:00
s1lentq
d76b06dcc2 Netchan_CreateFileFragments: Fixed a very old and rare bug with dlfile while downloading direct from server, when content of resource size is less than header size first fragment 2022-08-25 00:01:33 +07:00
s1lentq
e9045e3b63 Fixed: StripUnprintableWorker did not count the null terminator 2022-07-10 15:47:56 +07:00
s1lentq
be0e1c843b Fix null or empty input string in COM_LoadFile (FS_Open with input empty string "" will succeed on some POSIX systems)
Resolved #919
2022-05-25 18:39:14 +07:00
s1lentq
3dc9f8c92d Fixed typo ZONE_DYNAMIC_SIZE 2022-04-17 00:45:13 +07:00
s1lentq
815da982a0 Update workflows/build.yml Set windows job container as windows-2019 instead of windows-latest which now run on windows-2022
https://github.com/actions/virtual-environments/issues/4856
Fixes windows build
2022-04-10 03:46:52 +07:00
s1lentq
4e0a3f312a Fixed case when model name is too long
COM_LoadFile: Increase buffer room size
Mod_LoadModel: Use safe version COM_FileBase_s
Agree on the size of loadname[] and model_t::name[] buffers
2022-04-10 03:35:08 +07:00
Dmitry Novikov
2f0a402f9d
Netchan_FlushIncoming: Don't clear global buffer of incoming network messages (#896)
* Netchan_FlushIncoming: Fixed #888
Co-authored-by: Artem Golubikhin <WPMGPRoSToTeMa@users.noreply.github.com>
2022-02-14 05:14:19 +07:00
RauliTop
6d169b0119
Fix incorrect cvar description (#897) 2022-02-09 13:07:56 +07:00
Dmitry Novikov
f319f50068
Fixed wrong length buffer with "StripUnprintableWorker" and also after stripping (#893)
Remove non-printable unicode char 0xFFA0 from table g_isPrintTable
Resolves #887
2022-02-05 20:07:35 +07:00
Nord1cWarr1or
77b4cd3d32
Added missing CVar sv_rehlds_local_gametime to readme (#882)
* Added missing CVar `sv_rehlds_local_gametime` to readme

Co-authored-by: Sergey Shorokhov <wopox1337@ya.ru>
2021-12-07 08:20:49 +03:00
Sergey Shorokhov
745f8b3735
Revert "Add GitHub Action for Remove old artifacts (#873)" (#874)
This reverts commit 5bc2d83b084362d162bd4e05f875d8c4f0bea83a.

[skip ci]
2021-11-03 17:20:14 +03:00
Sergey Shorokhov
5bc2d83b08
Add GitHub Action for Remove old artifacts (#873) 2021-11-01 15:07:11 +03:00
Franco Romaniello
471158b1d9
Implement Con_Printf() hook (#861)
* Implement Con_Printf hook

* update REHLDS_API_VERSION_MINOR

* Update rehlds_api.h

* Update version.h

* Apply suggestions from code review

Co-authored-by: Sergey Shorokhov <wopox1337@ya.ru>
2021-10-24 14:28:40 +03:00
mlgpero
c86849ef63
Update on grammar/spelling (#865)
* Update on grammar/spelling

Co-authored-by: Artem Golubikhin <WPMGPRoSToTeMa@users.noreply.github.com>
2021-10-23 11:56:02 +03:00
Sergey Shorokhov
22a00eff89 fix pointer symbols 2021-10-22 22:02:14 +03:00
Franco Romaniello
ed83cb6c50
Implement SV_EmitPings() hook (#858)
* Implement SV_EmitPings hook

* Change REHLDS_API_VERSION_MINOR

Co-authored-by: Sergey Shorokhov <wopox1337@ya.ru>
2021-10-20 21:06:29 +03:00
Sergey Shorokhov
2118e8f052
SV_HullForEntity: better log in Sys_Error (#843) 2021-10-20 19:39:07 +03:00
StevenKal
04ddafe637
API: Add hooks "ED_<Alloc|Free>" (#867)
* Update pr_edict.h

* Update pr_edict.cpp

* Update rehlds_api_impl.cpp

* Update rehlds_api_impl.h

* Update rehlds_api.h

* Update pr_edict.h

* Update pr_edict.cpp

* Update rehlds_api_impl.cpp

* Update rehlds_api_impl.h

* Update rehlds_api.h

* Update pr_edict.cpp
2021-10-20 17:39:19 +03:00
s1lentq
aaffe43e3e Reset m_bSentNewResponse to allow new connection when the client goes through the full stage of connection (cl:connect -> sv:S2C_CONNECTION -> cl:new -> SV_New_f) Related 3a9bfb9 2021-06-24 19:09:10 +07:00
Sergey Shorokhov
9508c8376b
change destinition folder for linux build (#842) 2021-06-23 16:04:53 +03:00
Very Strange Karaulov
ad6f6ad396
sv_main.cpp: SV_New_f() uses Q_snprintf() unsafe format. (#807) 2021-06-19 22:39:40 +03:00
Very Strange Karaulov
527d0819b9
static_map.h: fix lowercase convert (#806)
* More readability in convert lowercase

Co-authored-by: Sergey Shorokhov <wopox1337@ya.ru>
Co-authored-by: Artem Golubikhin
2021-06-19 22:30:12 +03:00
Very Strange Karaulov
f23498bef7
sv_user.cpp: Small code refactoring (#810)
* Small code style fix in sv_user.cpp

* SV_EstablishTimeBase_internal: code refactoring

Co-authored-by: Sergey Shorokhov <wopox1337@ya.ru>
2021-06-19 21:44:18 +03:00
s1lentq
478f338e37 PF_sound_I: fix formatting 2021-06-19 20:30:05 +07:00
Artem Golubikhin
0fed5b8038
Fixed volume checking in emit sound (#341)
Co-authored-by: Dmitry Novikov <s1lentsk@yandex.ru>
Co-authored-by: Sergey Shorokhov <wopox1337@ya.ru>
2021-06-19 13:12:24 +03:00
s1lentq
3a9bfb9ca1 SV_New_f: Deny new connection twice at a time if user messages are received
SV_ReadClientMessage: Fix empty names on bad read
2021-06-16 04:23:27 +07:00
s1lentq
f3d60248fa Enhanced IGameClient/IRehldsServerData/IRehldsServerStatic interfaces
Added client_t:m_bSentNewResponse
Bump API minor
2021-06-16 04:23:25 +07:00
Sergey Shorokhov
39b441099c
Implement CVar sv_usercmd_custom_random_seed (#837) 2021-06-14 06:19:51 +07:00
Karol Szuster
81fe334545
Add GetEntityInit hook (#832)
* Add GetEntityInit hook
2021-06-14 05:43:27 +07:00
s1lentq
d9613d2093 SV_ParseMove: Fixed wrong check length 2021-06-13 00:06:02 +07:00
s1lentq
801be3ee5b SV_ParseMove, SV_ParseConsistencyResponse: check length 2021-06-12 00:53:30 +07:00
Juice
05c7601f1e
Fix crash in ProcessStringCmd (#838) 2021-06-12 00:01:01 +07:00
s1lentq
0c47c1c28b CMakeLists.txt: Fix build with cmake 3.7.2 [skip ci] 2021-06-05 08:21:48 +07:00
s1lentq
b0488cf081 Outdated maps compatibility 'Q1BSP_VERSION' for dedicated server 2021-05-03 00:50:25 +07:00
s1lentq
8dd3013813 SV_CheckBottom: Fix bug NPC movement (mistake reversing engineering) 2021-05-03 00:41:05 +07:00
s1lentq
2f70b6cba5 SV_FatPVS/SV_FatPAS: Sanity checks, gPVSRowBytes is not used for singleplayer 2021-05-03 00:39:06 +07:00
s1lentq
80c40ce0c0 Cmd_Alias_f: fix 2021-05-03 00:35:51 +07:00
s1lentq
ee986f7c62 version.vcxproj reworked [skip ci] 2021-04-24 01:13:18 +07:00
s1lentq
9a171db348 SV_ExecuteClientMessage: Don't handle packets when client has already dropped 2021-04-22 17:23:56 +07:00
s1lentq
ebefe19023 workflows/build.yml: remove nuget
info_tests.cpp: fix warning
2021-04-22 02:39:42 +07:00
s1lentq
6a916d766b Update README.md build.yml [skip ci] 2021-04-17 18:14:32 +07:00
s1lentq
2cd25fa7f8 Update README.md 2021-04-16 02:33:32 +07:00
s1lentq
a0bdadd679 reworked windows appversion 2021-04-16 02:32:43 +07:00
s1lentq
41f635869a Remove hookers stuff 2021-04-16 02:26:45 +07:00
s1lentq
13e2db3423 build.sh add help [skip ci] 2021-04-13 05:39:29 +07:00
s1lentq
1d15946cff build.sh fix jobs option parsing
glibc_test.sh: reworked pattern
2021-04-13 04:35:26 +07:00
s1lentq
7bd3d73b79 workflows/build.yml: add unittests for linux
CMakeLists.txt minor refactoring
2021-04-12 04:25:40 +07:00
s1lentq
7cfea77b93 workflows/build.yml: add testing HLDS demo 2021-04-11 07:00:11 +07:00
s1lentq
e9a39d73f2 CMakeLists.txt missing libm.so linking 2021-04-08 18:03:30 +07:00
s1lentq
c893651bf0 Remove gradle & cleanup 2021-04-08 05:13:42 +07:00
s1lentq
ccd36e765b CMakeLists.txt configure Intel C++ Compiler
build.yml: use container linux86buildtools
Minor refactoring
2021-04-08 03:34:55 +07:00
s1lentq
2965e0ea7f Added libraries libm/librt built on glibc 2.11.1 (Fixes #827) 2021-04-05 00:04:00 +07:00
s1lentq
80f0f3c7ea glibc_test.sh: bump minor version up to 11 2021-04-05 00:01:21 +07:00
s1lentq
3c63e41533 QuaternionSlerp: Fix wrong values Related #763 2021-03-27 22:50:57 +07:00
s1lentq
f27be28abb CMakeLists.txt: Configure for more compat to older linux distros (Debian 7, Centoc 6 etc) 2021-03-25 08:29:10 +07:00
s1lentq
af4776487b Windows: Set fetch-depth 0 to fetch all history for proper appversion generate 2021-03-24 17:52:21 +07:00
s1lentq
8aca7cfd8f CalcSurfaceExtents: Fixed a fatal error on some maps due loss of floating point 2021-03-23 20:09:54 +07:00
s1lentq
a579f56679 CMakeLists.txt configure for GCC 8.3 2021-03-23 20:07:32 +07:00
s1lentq
91bf77ac9e appversion.sh fix typo day formatting 2021-03-23 17:08:58 +07:00
s1lentq
b7a4f1e18a Fix wrong initialization values Resolves #822, Closes #823 2021-03-23 16:47:06 +07:00
s1lentq
77f004fdfc CMakeLists.txt: force run path for libsteam_api.so 2021-03-23 03:13:18 +07:00
s1lentq
7ea6686659 HLTV:Console: Fix typo
CMakeLists.txt: Fix typo linker flags
2021-03-23 01:29:00 +07:00
s1lentq
80b849f39e HLTV: Downgrade GLIBC version 2021-03-23 01:10:55 +07:00
s1lentq
42fd0fadfa ExecuteString: Fix parser Closes #821 2021-03-22 23:56:12 +07:00
s1lentq
ce0bfa11ab CMakeLists.txt: Configure for compat oldest libstdc++
CMakeLists.txt: Add -fno-stack-protector
ExecuteString: Fix parser
build.yml: Add paths-ignore README.md
2021-03-17 04:16:49 +07:00
s1lentq
2e8bd9e1eb Add workflows/build.yml
Preparing migration to workflows
Fixes warnings
Update badges README.md
2021-03-16 21:22:34 +07:00
s1lentq
3fc9ee2f55 HLDS Lanucher: make sure the timer is high precision (Fixes #799) 2021-03-13 20:36:10 +07:00
Very Strange Karaulov
2f2be916c2
HTLV: RadiusFromBounds is broken (#811)
HTLV: RadiusFromBounds fix mistake
2021-02-08 17:28:07 +07:00
s1lentq
722e19df31 Fix local-buffer overrun, may undefined behavior with hitbox blending or crash (reverse-engineering mistake) 2021-02-06 20:13:38 +07:00
Sergey Shorokhov
169020067b
Add: new chatdelay command. (#777) 2021-01-29 21:12:32 +03:00
theAsmodai
dc75d828ce
Don't generate different challenge on port change (#804) 2021-01-28 01:43:02 +03:00
Dmitry Novikov
aaf56989f9
Cbuf_Execute: Add checks commented out for multi-lines. (#719) 2021-01-28 01:41:57 +03:00
Simeon Nikolov
d6fff73df8
add ReHLDS logo in README (#778) 2021-01-28 01:27:05 +03:00
theAsmodai
6d01b1b3f2
Merge pull request #802 from dreamstalker/challenges_fix
Fix dos attack on connection challenges system
2021-01-26 02:41:46 +03:00
Asmodai
370dddb8b4 Fix dos attack on connection challenges system 2021-01-26 02:27:11 +03:00
Juice
83c0b6ea2b
HLTV: prevent clients from setting userinfo * keys with setinfo command (#792) 2020-12-03 20:14:54 +07:00
Juice
954ec3237c
Fix crash COM_ListMaps (#791)
* Fix crash COM_ListMaps
2020-11-12 05:40:08 +07:00
s1lentq
543728dad2 Fix crash MSG_ReadFloat 2020-11-09 01:22:55 +07:00
s1lentq
f535b5b38f ReHLDS API: Implemented SV_ShouldSendConsistencyList
ReHLDS API: Bump minor
2020-11-09 01:20:53 +07:00
s1lentq
c11fdbe3f8 Fixed typo with null terminated 2020-10-21 20:52:16 +07:00
Karol Szuster
462484a644
Remove unnecessary qualifier (#781)
Signed-off-by: Karol Szuster <karolsz9898@gmail.com>
2020-09-07 22:19:29 +07:00
Sergey Shorokhov
376bc15cee
Graceful shutdown on sigterm (#776)
* Add players kick on SIGINT \ SIGTERM
* Add SIGINT & SIGTERM handling linux console
* change shutdown method
2020-08-19 17:14:22 +07:00
s1lentq
98db4672cf SV_ProcessFile: Wrap Con_Printf in Con_NetPrintf to avoid spam in HLDS console 2020-07-25 03:42:34 +07:00
Artem Golubikhin
987ee51a6b
Implement svc_exec support in the engine and HLTV (#737)
* Added `svc_exec` to the list of svc commands in engine
* Added `svc_exec` support to HLTV code
* Made the engine code forward-compatible with future svc_* additions
* Added reserved svc_* slots in the enumerations
2020-05-19 01:46:47 +07:00
331 changed files with 8287 additions and 13419 deletions

474
.github/workflows/build.yml vendored Normal file
View File

@ -0,0 +1,474 @@
name: C/C++ CI
on:
push:
branches: [master]
paths-ignore:
- '**.md'
- '.github/**'
pull_request:
types: [opened, reopened, synchronize]
release:
types: [published]
workflow_dispatch:
jobs:
windows:
name: 'Windows'
runs-on: windows-2025
env:
solution: 'msvc/ReHLDS.sln'
buildPlatform: 'Win32'
buildRelease: 'Release'
buildReleasePlay: 'Release Play'
buildTest: 'Test Fixes'
steps:
- name: Configure
run: git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup MSBuild
uses: microsoft/setup-msbuild@v2
# TODO: add support of 141_xp toolchain at VS2022+
# - name: Install v140, v141 and v142 toolsets
# shell: cmd
# run: |
# "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vs_installer.exe" modify ^
# --installPath "C:\Program Files\Microsoft Visual Studio\2022\Enterprise" ^
# --add Microsoft.VisualStudio.Component.WindowsXP ^
# --add Microsoft.VisualStudio.Component.VC.v140 ^
# --add Microsoft.VisualStudio.Component.VC.v140.x86.x64 ^
# --add Microsoft.VisualStudio.Component.VC.v140.xp ^
# --add Microsoft.VisualStudio.Component.VC.140.CRT ^
# --add Microsoft.VisualStudio.Component.VC.v141 ^
# --add Microsoft.VisualStudio.Component.VC.v141.x86.x64 ^
# --add Microsoft.VisualStudio.Component.VC.v141.xp ^
# --add Microsoft.VisualStudio.Component.VC.v142 ^
# --add Microsoft.VisualStudio.Component.VC.v142.x86.x64 ^
# --quiet --norestart
- name: Select PlatformToolset
id: select_toolset
shell: pwsh
run: |
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$vs2019 = & $vswhere -products * -version "[16.0,17.0)" -property installationPath -latest
$vs2022 = & $vswhere -products * -version "[17.0,)" -property installationPath -latest
if ($vs2019) {
"toolset=v140_xp" >> $env:GITHUB_OUTPUT
Write-Host "Selected v140_xp toolset"
} elseif ($vs2022) {
"toolset=v143" >> $env:GITHUB_OUTPUT
Write-Host "Selected v143 toolset"
} else {
Write-Error "No suitable Visual Studio installation found"
exit 1
}
- name: Build and Run unittests
shell: pwsh
run: |
$toolset = '${{ steps.select_toolset.outputs.toolset }}'
msbuild ${{ env.solution }} -p:Configuration="${{ env.buildTest }}" /t:Clean,Build /p:Platform=${{ env.buildPlatform }} /p:PlatformToolset=$toolset /p:XPDeprecationWarning=false
.\"msvc\Test Fixes\swds.exe"
If ($LASTEXITCODE -ne 0 -And
$LASTEXITCODE -ne 3)
{[Environment]::Exit(1)}
- name: Build
shell: pwsh
run: |
$toolset = '${{ steps.select_toolset.outputs.toolset }}'
msbuild ${{ env.solution }} -p:Configuration="${{ env.buildRelease }}" /t:Clean,Build /p:Platform=${{ env.buildPlatform }} /p:PlatformToolset=$toolset /p:XPDeprecationWarning=false
msbuild ${{ env.solution }} -p:Configuration="${{ env.buildReleasePlay }}" /t:Clean,Build /p:Platform=${{ env.buildPlatform }} /p:PlatformToolset=$toolset /p:XPDeprecationWarning=false
- name: Get rcedit from chocolatey
shell: pwsh
run: |
choco install rcedit -y
- name: Move files
run: |
mkdir publish\debug
mkdir publish\tests
mkdir publish\bin\win32\valve\dlls
move "msvc\${{ env.buildReleasePlay }}\swds.dll" publish\tests\swds.dll
move msvc\${{ env.buildRelease }}\hlds.exe publish\bin\win32\hlds.exe
move msvc\${{ env.buildRelease }}\hltv.exe publish\bin\win32\hltv.exe
move msvc\${{ env.buildRelease }}\swds.dll publish\bin\win32\swds.dll
move msvc\${{ env.buildRelease }}\core.dll publish\bin\win32\core.dll
move msvc\${{ env.buildRelease }}\proxy.dll publish\bin\win32\proxy.dll
move msvc\${{ env.buildRelease }}\demoplayer.dll publish\bin\win32\demoplayer.dll
move msvc\${{ env.buildRelease }}\filesystem_stdio.dll publish\bin\win32\filesystem_stdio.dll
move msvc\${{ env.buildRelease }}\director.dll publish\bin\win32\valve\dlls\director.dll
move msvc\${{ env.buildRelease }}\hlds.pdb publish\debug\hlds.pdb
move msvc\${{ env.buildRelease }}\hltv.pdb publish\debug\hltv.pdb
move msvc\${{ env.buildRelease }}\swds.pdb publish\debug\swds.pdb
move msvc\${{ env.buildRelease }}\core.pdb publish\debug\core.pdb
move msvc\${{ env.buildRelease }}\proxy.pdb publish\debug\proxy.pdb
move msvc\${{ env.buildRelease }}\demoplayer.pdb publish\debug\demoplayer.pdb
move msvc\${{ env.buildRelease }}\filesystem_stdio.pdb publish\debug\filesystem_stdio.pdb
move msvc\${{ env.buildRelease }}\director.pdb publish\debug\director.pdb
- name: Get app version
id: get_version
shell: pwsh
run: |
$versionFile = "rehlds/version/appversion.h"
if (-not (Test-Path $versionFile)) {
Write-Error "Version file not found: $versionFile"
exit 1
}
$content = Get-Content $versionFile
foreach ($line in $content) {
if ($line -match '^\s*#define\s+APP_VERSION\s+"([^"]+)"') {
$version = $matches[1]
"version=$version" >> $env:GITHUB_OUTPUT
Write-Host "Found version: $version"
exit 0
}
}
Write-Error "APP_VERSION not found in file"
exit 1
- name: Show version
run: echo "Version is ${{ steps.get_version.outputs.version }}"
- name: Edit resources at windows binaries
run: |
rcedit ${{ github.workspace }}\publish\bin\win32\hlds.exe --set-version-string ProductName "ReHLDS" --set-file-version "${{ steps.get_version.outputs.version }}" --set-product-version "${{ steps.get_version.outputs.version }}" --set-version-string FileDescription "The Half-Life Dedicated Server, Commit: $env:GITHUB_SHA" --set-version-string "Comments" "Commit: $env:GITHUB_SHA" --set-version-string CompanyName "ReHLDS Dev Team" --set-version-string LegalCopyright "Copyright 2025 Valve, ReHLDS DevTeam"
rcedit ${{ github.workspace }}\publish\bin\win32\hltv.exe --set-version-string ProductName "ReHLTV" --set-file-version "${{ steps.get_version.outputs.version }}" --set-product-version "${{ steps.get_version.outputs.version }}" --set-version-string FileDescription "The Half-Life TV, Commit: $env:GITHUB_SHA" --set-version-string "Comments" "Commit: $env:GITHUB_SHA" --set-version-string CompanyName "ReHLDS Dev Team" --set-version-string LegalCopyright "Copyright 2025 Valve, ReHLDS DevTeam"
rcedit ${{ github.workspace }}\publish\tests\swds.dll --set-version-string ProductName "swds.dll" --set-file-version "${{ steps.get_version.outputs.version }}" --set-product-version "${{ steps.get_version.outputs.version }}" --set-version-string FileDescription "A dll used by Steamworks Dedicated Servers, Commit: $env:GITHUB_SHA" --set-version-string "Comments" "Commit: $env:GITHUB_SHA" --set-version-string CompanyName "ReHLDS Dev Team" --set-version-string LegalCopyright "Copyright 2025 Valve, ReHLDS DevTeam" --set-icon rehlds/dedicated/msvc/icon.ico
rcedit ${{ github.workspace }}\publish\bin\win32\swds.dll --set-version-string ProductName "swds.dll" --set-file-version "${{ steps.get_version.outputs.version }}" --set-product-version "${{ steps.get_version.outputs.version }}" --set-version-string FileDescription "A ddll used by Steamworks Dedicated Servers, Commit: $env:GITHUB_SHA" --set-version-string "Comments" "Commit: $env:GITHUB_SHA" --set-version-string CompanyName "ReHLDS Dev Team" --set-version-string LegalCopyright "Copyright 2025 Valve, ReHLDS DevTeam" --set-icon rehlds/dedicated/msvc/icon.ico
rcedit ${{ github.workspace }}\publish\bin\win32\core.dll --set-version-string ProductName "core.dll" --set-file-version "${{ steps.get_version.outputs.version }}" --set-product-version "${{ steps.get_version.outputs.version }}" --set-version-string FileDescription " A dll, it is a core of game engine, Commit: $env:GITHUB_SHA" --set-version-string "Comments" "Commit: $env:GITHUB_SHA" --set-version-string CompanyName "ReHLDS Dev Team" --set-version-string LegalCopyright "Copyright 2025 Valve, ReHLDS DevTeam" --set-icon rehlds/dedicated/msvc/icon.ico
rcedit ${{ github.workspace }}\publish\bin\win32\proxy.dll --set-version-string ProductName "proxy.dll" --set-file-version "${{ steps.get_version.outputs.version }}" --set-product-version "${{ steps.get_version.outputs.version }}" --set-version-string FileDescription "A dll for proxying network connections, Commit: $env:GITHUB_SHA" --set-version-string "Comments" "Commit: $env:GITHUB_SHA" --set-version-string CompanyName "ReHLDS Dev Team" --set-version-string LegalCopyright "Copyright 2025 Valve, ReHLDS DevTeam" --set-icon rehlds/dedicated/msvc/icon.ico
rcedit ${{ github.workspace }}\publish\bin\win32\demoplayer.dll --set-version-string ProductName "demoplayer.dll" --set-file-version "${{ steps.get_version.outputs.version }}" --set-product-version "${{ steps.get_version.outputs.version }}" --set-version-string FileDescription "A dll for demoplayer functionality, Commit: $env:GITHUB_SHA" --set-version-string "Comments" "Commit: $env:GITHUB_SHA" --set-version-string CompanyName "ReHLDS Dev Team" --set-version-string LegalCopyright "Copyright 2025 Valve, ReHLDS DevTeam" --set-icon rehlds/dedicated/msvc/icon.ico
rcedit ${{ github.workspace }}\publish\bin\win32\filesystem_stdio.dll --set-version-string ProductName "filesystem_stdio.dll" --set-file-version "${{ steps.get_version.outputs.version }}" --set-product-version "${{ steps.get_version.outputs.version }}" --set-version-string FileDescription "A dll that manages file input/output operations, Commit: $env:GITHUB_SHA" --set-version-string "Comments" "Commit: $env:GITHUB_SHA" --set-version-string CompanyName "ReHLDS Dev Team" --set-version-string LegalCopyright "Copyright 2025 Valve, ReHLDS DevTeam" --set-icon rehlds/dedicated/msvc/icon.ico
rcedit ${{ github.workspace }}\publish\bin\win32\valve\dlls\director.dll --set-version-string ProductName "director.dll" --set-file-version "${{ steps.get_version.outputs.version }}" --set-product-version "${{ steps.get_version.outputs.version }}" --set-version-string FileDescription "A dll used for Director functionality in Half-Life 1, Commit: $env:GITHUB_SHA" --set-version-string "Comments" "Commit: $env:GITHUB_SHA" --set-version-string CompanyName "ReHLDS Dev Team" --set-version-string LegalCopyright "Copyright 2025 Valve, ReHLDS DevTeam" --set-icon rehlds/dedicated/msvc/icon.ico
shell: "pwsh"
- name: Import PFX and sign
if: github.event_name != 'pull_request'
env:
KEY_PFX_PASS: ${{ secrets.KEY_PFX_PASS }}
# https://github.com/actions/runner-images/blob/main/images/windows/Windows2025-Readme.md
run: |
$pfxBase64 = "${{ secrets.KEY_PFX_B64 }}"
[IO.File]::WriteAllBytes("${{ github.workspace }}\signing-cert.pfx", [Convert]::FromBase64String($pfxBase64))
certutil -f -p "${{ secrets.KEY_PFX_PASS }}" -importPFX "${{ github.workspace }}\signing-cert.pfx"
& 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x86\signtool.exe' sign /a /f "${{ github.workspace }}\signing-cert.pfx" /p $env:KEY_PFX_PASS /d "ReHLDS" /du "https://rehlds.dev/" /tr "http://timestamp.digicert.com" /td sha256 /fd sha256 /v ${{ github.workspace }}\publish\bin\win32\hlds.exe
& 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x86\signtool.exe' sign /a /f "${{ github.workspace }}\signing-cert.pfx" /p $env:KEY_PFX_PASS /d "reHLTV" /du "https://rehlds.dev/" /tr "http://timestamp.digicert.com" /td sha256 /fd sha256 /v ${{ github.workspace }}\publish\bin\win32\hltv.exe
& 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x86\signtool.exe' sign /a /f "${{ github.workspace }}\signing-cert.pfx" /p $env:KEY_PFX_PASS /d "ReHLDS - swds.dll" /du "https://rehlds.dev/" /tr "http://timestamp.digicert.com" /td sha256 /fd sha256 /v ${{ github.workspace }}\publish\tests\swds.dll
& 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x86\signtool.exe' sign /a /f "${{ github.workspace }}\signing-cert.pfx" /p $env:KEY_PFX_PASS /d "ReHLDS - swds.dll" /du "https://rehlds.dev/" /tr "http://timestamp.digicert.com" /td sha256 /fd sha256 /v ${{ github.workspace }}\publish\bin\win32\swds.dll
& 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x86\signtool.exe' sign /a /f "${{ github.workspace }}\signing-cert.pfx" /p $env:KEY_PFX_PASS /d "ReHLDS - core.dll" /du "https://rehlds.dev/" /tr "http://timestamp.digicert.com" /td sha256 /fd sha256 /v ${{ github.workspace }}\publish\bin\win32\core.dll
& 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x86\signtool.exe' sign /a /f "${{ github.workspace }}\signing-cert.pfx" /p $env:KEY_PFX_PASS /d "ReHLDS - proxy.dll" /du "https://rehlds.dev/" /tr "http://timestamp.digicert.com" /td sha256 /fd sha256 /v ${{ github.workspace }}\publish\bin\win32\proxy.dll
& 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x86\signtool.exe' sign /a /f "${{ github.workspace }}\signing-cert.pfx" /p $env:KEY_PFX_PASS /d "ReHLDS - demoplayer.dll" /du "https://rehlds.dev/" /tr "http://timestamp.digicert.com" /td sha256 /fd sha256 /v ${{ github.workspace }}\publish\bin\win32\demoplayer.dll
& 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x86\signtool.exe' sign /a /f "${{ github.workspace }}\signing-cert.pfx" /p $env:KEY_PFX_PASS /d "ReHLDS - filesystem_stdio.dll" /du "https://rehlds.dev/" /tr "http://timestamp.digicert.com" /td sha256 /fd sha256 /v ${{ github.workspace }}\publish\bin\win32\filesystem_stdio.dll
& 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x86\signtool.exe' sign /a /f "${{ github.workspace }}\signing-cert.pfx" /p $env:KEY_PFX_PASS /d "ReHLDS - director.dll" /du "https://rehlds.dev/" /tr "http://timestamp.digicert.com" /td sha256 /fd sha256 /v ${{ github.workspace }}\publish\bin\win32\valve\dlls\director.dll
Remove-Item -Recurse -Force "${{ github.workspace }}\signing-cert.pfx"
shell: "pwsh"
- name: Deploy artifacts
uses: actions/upload-artifact@v4
with:
name: win32
path: publish/*
testdemos:
name: 'Test demos'
runs-on: ubuntu-24.04
container: rehldsorg/testdemos:latest
needs: [windows]
defaults:
run:
shell: bash
working-directory: /opt/HLDS
strategy:
fail-fast: false
matrix:
test: [
{ file: 'cstrike-muliplayer-1', desc: 'CS: Multiplayer' },
{ file: 'rehlds-phys-single1', desc: 'Half-Life: Physics singleplayer' },
{ file: 'crossfire-1-multiplayer-1', desc: 'Half-Life: Multiplayer on crossfire map' },
{ file: 'shooting-hl-1', desc: 'Half-Life: Shooting with several weapons' },
]
steps:
- name: Deploying windows artifacts
uses: actions/download-artifact@v4
with:
name: win32
- name: Setup dependencies
run: |
chown root ~
rsync -a deps/rehlds/* .
mv $GITHUB_WORKSPACE/tests/swds.dll .
- name: Play test
env:
demo: ${{ matrix.test.file }}
desc: ${{ matrix.test.desc }}
run: ./runTest.sh
linux:
name: 'Linux'
runs-on: ubuntu-24.04
container: debian:11-slim
steps:
- name: Install dependencies
run: |
dpkg --add-architecture i386
apt-get update
apt-get install -y \
gcc-multilib g++-multilib \
build-essential \
libc6-dev libc6-dev-i386 \
git cmake rsync \
g++ gcc
- name: Configure
run: git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: GPG Import
run: |
echo "${{ secrets.PUB_ASC }}" > "${{ secrets.PUB_ASC_FILE }}"
echo "${{ secrets.KEY_ASC }}" > "${{ secrets.KEY_ASC_FILE }}"
# Import the public key
gpg --batch --yes --import "${{ secrets.PUB_ASC_FILE }}"
if [[ $? -ne 0 ]]; then
echo "Error: Failed to import the public key"
exit 1
fi
# Import the private key
gpg --batch --yes --import "${{ secrets.KEY_ASC_FILE }}"
if [[ $? -ne 0 ]]; then
echo "Error: Failed to import the private key"
exit 2
fi
# Extract the fingerprint of the imported public key
GPG_LINUX_FINGERPRINT=$(gpg --list-keys --with-colons | grep '^fpr' | head -n 1 | cut -d: -f10)
# Check if the fingerprint was extracted
if [[ -z "$GPG_LINUX_FINGERPRINT" ]]; then
echo "Error: Failed to extract the fingerprint of the key"
exit 3
fi
# Set the trust level for the key
echo "$GPG_LINUX_FINGERPRINT:6:" | gpg --batch --import-ownertrust
if [ $? -ne 0 ]; then
echo "Error: Failed to set trust for the key $GPG_LINUX_FINGERPRINT"
exit 4
fi
echo "Key $GPG_LINUX_FINGERPRINT successfully imported and trusted"
gpg --list-keys
#export for global use
echo "GPG_LINUX_FINGERPRINT=$GPG_LINUX_FINGERPRINT" >> $GITHUB_ENV
shell: bash
if: github.event_name != 'pull_request'
- name: Build and Run unittests
run: |
rm -rf build && cmake -DCMAKE_BUILD_TYPE=Unittests -B build && cmake --build build -j8
retVal=0
export LD_LIBRARY_PATH="rehlds/lib/linux32:$LD_LIBRARY_PATH"
./build/rehlds/engine_i486 2> /dev/null > result.log || retVal=$?
while read line; do
if [[ ${line} == *"Warning in test"* ]] ; then
echo -e "\e[2;38m$line"
elif [[ ${line} == *"Failure in test"* ]] ; then
echo -e "\e[1;31m$line"
else
echo -e "\e[0;33m$line"
fi
done <<< $(cat result.log)
if [ $retVal -ne 0 ] && [ $retVal -ne 3 ]; then
echo -e "\e[30;41mExit code: $retVal\e[0m"
exit 1 # Unittest failed
else
echo -e "\e[30;43mExit code: $retVal\e[0m"
fi
shell: bash
- name: Build using GCC Compiler
run: |
rm -rf build && cmake -B build && cmake --build build -j8
- name: Prepare HLSDK
run: |
mkdir -p publish/hlsdk
rsync -a rehlds/common/ publish/hlsdk/common/
rsync -a rehlds/dlls/ publish/hlsdk/dlls/
rsync -a rehlds/pm_shared/ publish/hlsdk/pm_shared/
rsync -a rehlds/public/ publish/hlsdk/public/ --exclude rehlds/
rsync -a rehlds/public/rehlds/ publish/hlsdk/engine
- name: Move files
run: |
mkdir -p publish/bin/linux32/valve/dlls
mv build/rehlds/engine_i486.so publish/bin/linux32/engine_i486.so
mv rehlds/version/appversion.h publish/appversion.h
mv build/rehlds/dedicated/hlds_linux publish/bin/linux32/hlds_linux
mv build/rehlds/HLTV/Console/hltv publish/bin/linux32/hltv
mv build/rehlds/HLTV/Core/core.so publish/bin/linux32/core.so
mv build/rehlds/HLTV/Proxy/proxy.so publish/bin/linux32/proxy.so
mv build/rehlds/HLTV/DemoPlayer/demoplayer.so publish/bin/linux32/demoplayer.so
mv build/rehlds/HLTV/Director/director.so publish/bin/linux32/valve/dlls/director.so
mv build/rehlds/filesystem/FileSystem_Stdio/filesystem_stdio.so publish/bin/linux32/filesystem_stdio.so
- name: Run GLIBC/ABI version compat test
run: |
binaries=(
"publish/bin/linux32/engine_i486.so"
"publish/bin/linux32/hlds_linux"
"publish/bin/linux32/hltv"
"publish/bin/linux32/core.so"
"publish/bin/linux32/proxy.so"
"publish/bin/linux32/demoplayer.so"
"publish/bin/linux32/valve/dlls/director.so"
"publish/bin/linux32/filesystem_stdio.so"
)
bash ./rehlds/version/glibc_test.sh ${binaries[@]}
if [[ $? -ne 0 ]]; then
exit 1 # Assertion failed
fi
shell: bash
- name: Deploy artifacts
uses: actions/upload-artifact@v4
id: upload-job
with:
name: linux32
path: publish/*
publish:
name: 'Publish'
runs-on: ubuntu-24.04
needs: [windows, testdemos, linux]
steps:
- name: Deploying linux artifacts
uses: actions/download-artifact@v4
with:
name: linux32
- name: Deploying windows artifacts
uses: actions/download-artifact@v4
with:
name: win32
- name: Reading appversion.h
run: |
if [ -e appversion.h ]; then
APP_VERSION=$(cat appversion.h | grep -wi '#define APP_VERSION_STRD' | sed -e 's/#define APP_VERSION_STRD[ \t\r\n\v\f]\+\(.*\)/\1/i' -e 's/\r//g')
if [ $? -ne 0 ]; then
APP_VERSION=""
else
# Remove quotes
APP_VERSION=$(echo $APP_VERSION | xargs)
echo "APP_VERSION=${APP_VERSION}" >> $GITHUB_ENV
fi
fi
rm -f appversion.h
- name: Set SIGN_READY env
run: |
if [[ "${{ github.event_name }}" == "release" && \
"${{ github.event.action }}" == "published" && \
"${{ github.ref }}" == refs/tags/* ]]; then
echo "SIGN_READY=true" >> $GITHUB_ENV
else
echo "SIGN_READY=false" >> $GITHUB_ENV
fi
- name: Final signing and Packaging bin/dbg
id: packaging-job
run: |
if [[ "$SIGN_READY" == "true" ]]; then
echo "Signing avalible."
echo "${{ secrets.PUB_ASC }}" > "${{ secrets.PUB_ASC_FILE }}"
echo "${{ secrets.KEY_ASC }}" > "${{ secrets.KEY_ASC_FILE }}"
gpg --batch --yes --import "${{ secrets.PUB_ASC_FILE }}"
gpg --batch --yes --import "${{ secrets.KEY_ASC_FILE }}"
GPG_LINUX_FINGERPRINT=$(gpg --list-keys --with-colons | grep '^fpr' | head -n 1 | cut -d: -f10)
echo "$GPG_LINUX_FINGERPRINT:6:" | gpg --batch --import-ownertrust
echo "GPG_LINUX_FINGERPRINT=$GPG_LINUX_FINGERPRINT" >> $GITHUB_ENV
else
echo "Signing skipped."
fi
sign_file() {
if [[ "$SIGN_READY" == "true" ]]; then
local file=$1
gpg --batch --yes --detach-sign --armor -u "$GPG_LINUX_FINGERPRINT" "$file"
if [ $? -ne 0 ]; then
echo "Error: Failed to sign $file"
exit 2
fi
echo "$file signed successfully."
else
echo "$file not signed (SIGN_READY=$SIGN_READY)"
fi
}
# Pack and try sign final archive
7z a -tzip rehlds-bin-${{ env.APP_VERSION }}.zip bin/ hlsdk/
sign_file "rehlds-bin-${{ env.APP_VERSION }}.zip"
# Pack and try sign final archive
7z a -t7z -m0=lzma2 -mx=9 -mfb=64 -aoa rehlds-dbg-${{ env.APP_VERSION }}.7z debug/
sign_file "rehlds-dbg-${{ env.APP_VERSION }}.7z"
shell: bash
- name: Publish artifacts
uses: actions/upload-artifact@v4
with:
name: rehlds-ci-${{ env.APP_VERSION }}
path: |
*.zip
*.7z
*.asc
- name: Release artifacts
uses: softprops/action-gh-release@v2
id: publish-job
if: |
startsWith(github.ref, 'refs/tags/') &&
steps.packaging-job.outcome == 'success'
with:
files: |
*.zip
*.7z
*.asc
env:
GITHUB_TOKEN: ${{ secrets.API_TOKEN }}

6
.gitignore vendored
View File

@ -1,10 +1,9 @@
**/build
**/.gradle
.idea
*.iml
*.bat
*.log
*.lnk
*.aps
**/msvc/Debug*
**/msvc/Release*
**/msvc/Tests
@ -21,6 +20,3 @@
**/msvc/ipch
rehlds/version/appversion.h
rehlds/_rehldsTestImg
rehlds/_dev
publish

307
CHANGELOG.md Normal file
View File

@ -0,0 +1,307 @@
# [ReHLDS](https://github.com/ReHLDS/ReHLDS) Changelog
**ReHLDS** is a result of reverse engineering of original `HLDS` (build `6152`/`6153`) using `DWARF` debug info embedded into linux version of `HLDS`, `engine_i486.so`.
Along with reverse engineering, a lot of defects and (potential) bugs were found and fixed.
---
## [`3.14.0.857`](https://github.com/rehlds/rehlds/releases/tag/3.14.0.857) - 2025-03-27
### Added
- Added cvarhook from latest HLDS build. Making `mapcyclefile`/`sv_cheats` work in realtime (resolve #868) by @s1lentq in https://github.com/rehlds/ReHLDS/commit/6f031901cfa85d86c6028086bc9335db1e867a03
- Added forgotten CVar `sys_timescale` by @s1lentq
- Add support cheats commands: `god`, `notarget`, `noclip` by @s1lentq (https://github.com/rehlds/ReHLDS/commit/7fcec97af4c6598ab6a65d60cf424b7775a11729);
- engine: add `sv_allow_autoaim` cvar for `HL25` DLL compatibility by @a1batross in #1000;
- Added new CVar: `r_cachestudio` by @s1lentq in https://github.com/rehlds/ReHLDS/commit/0af97d98bbe31af26395ba616d4be6a089f691b6;
- Implement commands `rcon_adduser`, `rcon_deluser`, `rcon_users` to allow use RCON only by known user IPs (Resolves https://github.com/rehlds/ReHLDS/pull/796)
SV_Rcon: Minor refactoring by @s1lentq in https://github.com/rehlds/ReHLDS/commit/62407e0dd63542f0da8438ebb22b33d3bcab3b9d;
- Implemented optional CVar `sv_tags` for sets a string defining the "gametags" for this server to allows users/scripts to filter in the matchmaking/server-browser interfaces based on the value by @s1lentq in https://github.com/rehlds/ReHLDS/commit/76cbd2c14025b3e54bc14b8fcfe17ce5fa273195;
- Add `SV_SendResources` hook by @ShadowsAdi in #1024;
- Implement API interface game message manager by @s1lentq in https://github.com/rehlds/ReHLDS/commit/c9f9bbfff98cdb6e8ca45b9ab626f40d0c7bb22b;
- CalcSurfaceExtents: MAX_SURFACE_TEXTURE_SIZE limit increased from 256 to 512 by @s1lentq in https://github.com/rehlds/ReHLDS/commit/b29740c19e8cfe7a1ee0605cadccd05b35e8678e;
- Added new CVars for improved handling of decompression failures by @s1lentq in https://github.com/rehlds/ReHLDS/commit/64c684af4a8e6030b9e06a59a774d6efd92db352;
- Added codesign and resources by @stamepicmorg in https://github.com/rehlds/ReHLDS/pull/1069;
### Fixed
- Fixed reversing mistake, missing checking string for null by @s1lentq in https://github.com/rehlds/ReHLDS/commit/2ba27d409c364d12c01b6b72813ac4b991a6e224;
- Host_Motd_f: Fixed viewing motd when motdfile is not specified by @s1lentq in https://github.com/rehlds/ReHLDS/commit/de3679f0391f1452532c820f07a8c4042b1c4281;
- FIX: Don't exec config file when exceed limit text buffer by @s1lentq in https://github.com/rehlds/ReHLDS/commit/32857e77859789275daeb353a278cd6632c2b6bf;
- Prevent crash `Cache_UnlinkLRU: NULL link` on client-side if aiment with sprite model will be to render as a studio model by @s1lentq in https://github.com/rehlds/ReHLDS/commit/5002ff9abe86e9573952e2dc45ec9229d0044a3b;
- RCON: Fixes redirect print and minor refactoring by @s1lentq in https://github.com/rehlds/ReHLDS/commit/41c5186b2c8c00f49101ed2c5d81a47cf79449c4;
- Host_Status_f: Fixed incorrect player index to output by @s1lentq in https://github.com/rehlds/ReHLDS/commit/9b0dbe8dd2ced5f0ead251116f5b9ebd61f6d6a4;
- MSG_WriteBitAngle: Cap the precision check from 32 to 22 to avoid overflow issues when representing angles with more than 22 bits because the multiply by 'shift' may result in overflow by @s1lentq in https://github.com/rehlds/ReHLDS/commit/63fde229c98f7e1bb8f7ea9b8358027414ed26ac;
- Fix reversing mistake in `TEX_InitFromWad` (Don't add file handle before check) by @s1lentq in https://github.com/rehlds/ReHLDS/commit/a7b60451f33e076ba04e4ae38312c2f691540a2d
- Fix crash when the entity with aiment doesn't have a model by @s1lentq in https://github.com/rehlds/ReHLDS/commit/498d7e0d18060f53a65286fcbf91e772f42c5611;
- SV_WriteEntitiesToClient: Reset movetype if the aiment index is invalid by @s1lentq in https://github.com/rehlds/ReHLDS/commit/58391b6ee5e5faefcf84349443a2a36066ed8246;
- SV_ParseResourceList: Do not uploading according to `sv_allowupload` CVar by @s1lentq in https://github.com/rehlds/ReHLDS/commit/59ed3f6867b1b3cba69cd7650887841da8e76d42;
- Do not send customizations list on duplicate or missing resource by @s1lentq in https://github.com/rehlds/ReHLDS/commit/f26ad71aba6a596602245c64af71cd196196859f;
- Do not propagate custom logos according to sv_send_logos cvar by @s1lentq in https://github.com/rehlds/ReHLDS/commit/ec47e4d97834c35f8667684f15a372c85505ce55;
- Draw_ValidateCustomLogo: Fixed incorrect offset to palette size by @s1lentq in https://github.com/rehlds/ReHLDS/commit/3c282b435c7d0508d72104d26a0c9171f7feea71;
- Netchan_CreateFileFragments: Fixed a hang connection on verifying resource stage, when precached file exists but is absolutely empty by @s1lentq in https://github.com/rehlds/ReHLDS/commit/61ee4f926938b1894bedfd9f139d45db48d89903;
- Implemented reduction of impact caused by zip-bomb exploit by @s1lentq in https://github.com/rehlds/ReHLDS/pull/994;
- Improved behavior of `sv_filterban 0`. Fixes https://github.com/rehlds/ReHLDS/issues/1027 by @s1lentq in https://github.com/rehlds/ReHLDS/commit/693b51c8839847270048be40b62fb1d37f9954ae;
- Fixed GCC compilation warnings/errors. Fixes https://github.com/rehlds/ReHLDS/issues/1032 by @s1lentq in https://github.com/rehlds/ReHLDS/commit/9c1e84328ebcdb47ea83c157dd8c7e493dda28a6;
- [HLTV]: Fix reverse-engineering mistake in `ObjectDictionary::RemoveIndex` by @s1lentq in https://github.com/rehlds/ReHLDS/commit/ed954a710fb0888328db1bd9b2c916cf9fc63062;
- [HLTV]: Fix reverse-engineering mistake in `World::WritePacketEntities` by @s1lentq in https://github.com/rehlds/ReHLDS/commit/c8308a2c60d34e4f735b3404f86701109e85f73b;
- fix setting ucmd in `sv_user.cpp` related to https://github.com/rehlds/ReHLDS/issues/1041 by @overl4y in https://github.com/rehlds/ReHLDS/pull/1042;
- SV_ProcessFile: Ignore customization file uploads if upload is disabled by @s1lentq in https://github.com/rehlds/ReHLDS/commit/fe184a82e0a361b9e8bd1625ca93fac948467be1;
- CI Workflow Improvements and Fixes by @SergeyShorokhov in #1056;
- Improved movevars sync logic for clients, allowing independent sync of movement props for each client, regardless of global movevars by @s1lentq in https://github.com/rehlds/ReHLDS/commit/df862d9bb6069084ee17b23135152c57b748e40e;
- FIX: potential crash in `PrecacheModelSounds` by @s1lentq in https://github.com/rehlds/ReHLDS/commit/18b173d5c6715eaf052a979984622f867661cd7b;
- FIX: crash due fakeclient by @s1lentq in https://github.com/rehlds/ReHLDS/commit/e54adb089c816425bac43c7eaf6fc5b898401fb4;
- Netchan_CopyFileFragments: fix typo by @s1lentq in https://github.com/rehlds/ReHLDS/commit/1a684077109023f86cfe9b70d6a1bba92a35c5f6;
### Changed
- Improve `pfnShouldCollide` condition on `SV_ClipToLinks` by @dystopm in #985
- Minor refactor (add `BoundsIntersect` function) by @Hamdi #986
- Reworked AlertMessage by @s1lentq in https://github.com/rehlds/ReHLDS/commit/93f5775ac26240782981f47ee8e052fb53d30877
- CI/CD update:
- Draw_ValidateCustomLogo: Minor refactoring & cleanup by @s1lentq in https://github.com/rehlds/ReHLDS/commit/174414db81116b3647e7bb1b906417d6a38ed3a3;
- HPAK_ResourceForHash: Remove message with missing custom.hpk by @s1lentq in https://github.com/rehlds/ReHLDS/commit/516bb936271b1cf8523d6f97a421370128a7c964;
- SV_CreateCustomizationList: spew logs in only dev mode by @s1lentq in https://github.com/rehlds/ReHLDS/commit/462fe55fb832209270118b6def6034f8eec6efbf;
- CalcSurfaceExtents: more info in extents error message by @s1lentq in https://github.com/rehlds/ReHLDS/commit/6e6368da300f7d024076e6272faa135280cf3bda;
- Move SV_CheckMovingGround into SV_Physics by @dystopm in #1045;
- `IP` and `IPX` allocation warnings move under `-dev` arg by @SergeyShorokhov in #1071;
## New Contributors
* @dystopm made their first contribution in https://github.com/rehlds/ReHLDS/pull/985
* @anzz1 made their first contribution in https://github.com/rehlds/ReHLDS/pull/1021
* @jonathan-up made their first contribution in https://github.com/rehlds/ReHLDS/pull/1040
* @overl4y made their first contribution in https://github.com/rehlds/ReHLDS/pull/1042
* @stamepicmorg made their first contribution in https://github.com/rehlds/ReHLDS/pull/1058
**Full Changelog**: [3.13.0.788...3.14.0.857](https://github.com/rehlds/rehlds/compare/3.13.0.788...3.14.0.857)
## [`3.13.0.788`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.13.0.788) - 2023-07-12
### Added
- Added `SV_AllowPhysent` hook by @justgo97 in [(#951)](ttps://github.com/dreamstalker/ReHLDS/pull/951)
- `GetBonePosition`: Added bone index bounds check
- `GetAttachment`: Added attachment index bounds check
- Added more checks for possible `numleaf` overflow
### Fixed
- `SV_BuildSoundMsg`: fix '`\n`' in args check
### Changed
- Revert "change destinition folder for linux build" by @wopox1337 in [(#977)](https://github.com/dreamstalker/ReHLDS/pull/977)
- Allowed the clients to connect on the server of different game: Client should be use `setinfo _gd <game>`
- Increased limit leafs `MAX_MAP_LEAFS` up to `32767`
## New Contributors
- @justgo97 made their first contribution in [(#951)](https://github.com/dreamstalker/ReHLDS/pull/951)
**Full Changelog**: [3.12.0.780...3.13.0.788](https://github.com/ReHLDS/ReHLDS/compare/3.12.0.780...3.13.0.788)
## [`3.12.0.780`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.12.0.780) - 2022-09-19
### Fixed
- `Netchan_CreateFileFragments`: Fixed a very old and rare bug with dlfile while downloading direct from server, when content of resource size is less than header size first fragment.
### Changed
- `API`: Implement `*_Precache_*`, `ClientPrintf`, `CheckUserInfo` and `AddResource` hooks by @ShadowsAdi in [(#903)](https://github.com/dreamstalker/ReHLDS/pull/903)
## New Contributors
* @ShadowsAdi made their first contribution in [(#903)](https://github.com/dreamstalker/ReHLDS/pull/903)
**Full Changelog**: [3.11.0.779...3.12.0.780](https://github.com/ReHLDS/ReHLDS/compare/3.11.0.779...3.12.0.780)
## [`3.11.0.779`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.11.0.779) - 2022-08-24
### Fixed
- `StripUnprintableWorker` did not count the null terminator [e9045e3](https://github.com/dreamstalker/ReHLDS/commit/e9045e3)
- Very old and rare bug in function `Netchan_CreateFileFragments` with dlfile hang while downloading direct from server, when content of resource size is less than header size first fragment [d76b06d](https://github.com/dreamstalker/ReHLDS/commit/d76b06d)
**Full Changelog**: [3.11.0.777...3.11.0.779](https://github.com/ReHLDS/ReHLDS/compare/3.11.0.777...3.11.0.779)
## [`3.11.0.777`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.11.0.777) - 2022-06-20
### Fixed
* Fixed `null or empty` input string in `COM_LoadFile` (`FS_Open` with input empty string `""` will succeed on some POSIX systems)
- Resolved [(#919)](https://github.com/dreamstalker/ReHLDS/issues/919)
**Full Changelog**: [3.11.0.776...3.11.0.777](https://github.com/ReHLDS/ReHLDS/compare/3.11.0.776...3.11.0.777)
## [`3.11.0.776`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.11.0.776) - 2022-04-20
### Fixed
* Fixed typo `ZONE_DYNAMIC_SIZE`
**Full Changelog**: [3.11.0.767...3.11.0.776](https://github.com/ReHLDS/ReHLDS/compare/3.11.0.767...3.11.0.776)
## [`3.11.0.767`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.11.0.767) - 2021-10-25
### Added
* Implement `SV_EmitPings()` hook by @francoromaniello in [(#858)](https://github.com/ReHLDS/ReHLDS/pull/858)
* Implement `Con_Printf()` hook by @francoromaniello in [(#861)](https://github.com/ReHLDS/ReHLDS/pull/861)
### Changed
* `API`: Add hooks `ED_Alloc()` & `ED_Free()`. by @StevenKal in [(#867)](https://github.com/ReHLDS/ReHLDS/pull/867)
* `SV_HullForEntity`: better log in `Sys_Error` by @wopox1337 in [(#843)](https://github.com/ReHLDS/ReHLDS/pull/843)
* Update on grammar/spelling by @mlgpero in [(#865)](https://github.com/ReHLDS/ReHLDS/pull/865)
## New Contributors
* @StevenKal made their first contribution in [(#867)](https://github.com/ReHLDS/ReHLDS/pull/867)
* @francoromaniello made their first contribution in [(#858)](https://github.com/ReHLDS/ReHLDS/pull/858)
* @Urufusan made their first contribution in [(#865)](https://github.com/ReHLDS/ReHLDS/pull/865)
**Full Changelog**: [v3.10.0.761...3.11.0.767](https://github.com/ReHLDS/ReHLDS/compare/v3.10.0.761...3.11.0.767)
## [`3.10.0.760`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.10.0.760) - 2021-06-23
### Changed
- Changed the destination folder for `Linux build` [(#842)](https://github.com/ReHLDS/ReHLDS/pull/842).
- Temporary removed `Windows build`. :warning:
**Full Changelog**: [3.10.0.759...3.10.0.760](https://github.com/ReHLDS/ReHLDS/compare/3.10.0.759...3.10.0.760)
## [`3.10.0.761`](https://github.com/ReHLDS/ReHLDS/releases/tag/v3.10.0.761) - 2021-06-23
### Changed
- Reset `m_bSentNewResponse` to allow new connection when the client goes through the full stage of connection (`cl:connect` -> `sv:S2C_CONNECTION` -> `cl:new` -> `SV_New_f`)
- Related [3a9bfb9](https://github.com/ReHLDS/ReHLDS/commit/3a9bfb9)
**Full Changelog**: [3.10.0.760...v3.10.0.761](https://github.com/ReHLDS/ReHLDS/compare/3.10.0.760...v3.10.0.761)
## [`3.10.0.760`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.10.0.760) - 2021-06-23
### Changed
- Changed the destination folder for `Linux build` [(#842)](https://github.com/ReHLDS/ReHLDS/pull/842).
- Temporary removed `Windows build`. :warning:
**Full Changelog**: [3.10.0.759...3.10.0.760](https://github.com/ReHLDS/ReHLDS/compare/3.10.0.759...3.10.0.760)
## [`3.10.0.759`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.10.0.759) - 2021-06-22
### Fixed
- Fixed volume checking in emit sound [(#341)](https://github.com/ReHLDS/ReHLDS/pull/341)
- `static_map.h`: fix lowercase convert [(#806)](https://github.com/ReHLDS/ReHLDS/pull/806)
- `SV_New_f`: Deny new connection twice at a time if user messages are received;
- `SV_ReadClientMessage`: Fixed empty names on bad read.
### Changed
- `sv_user.cpp`: Small code refactoring [(#810)](https://github.com/ReHLDS/ReHLDS/pull/810)
- `ReHLDS API`: Enhanced IGameClient/IRehldsServerData/IRehldsServerStatic interfaces
- `sv_main.cpp`: SV_New_f() uses Q_snprintf() unsafe format. #807 [()](https://github.com/ReHLDS/ReHLDS/pull/807)
**Full Changelog**: [3.9.0.752...3.10.0.759](https://github.com/ReHLDS/ReHLDS/compare/3.9.0.752...3.10.0.759)
## [`3.9.0.752`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.9.0.752) - 2021-06-14
### Added
- `ReHLDS API`: Add GetEntityInit hook [(#832)](https://github.com/ReHLDS/ReHLDS/pull/832)
- Implement CVar `sv_usercmd_custom_random_seed` [(#837)](https://github.com/ReHLDS/ReHLDS/pull/837)
### Fixed
- `HLTV`: Fix crash in ProcessStringCmd [(#838)](https://github.com/ReHLDS/ReHLDS/pull/838)
### Changed
- `SV_ParseMove`, `SV_ParseConsistencyResponse`: check length
**Full Changelog**: [3.8.0.739...3.9.0.752](https://github.com/ReHLDS/ReHLDS/compare/3.8.0.739...3.9.0.752)
## [`3.8.0.739`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.8.0.739) - 2021-04-21
### Added
* Added libraries libm/librt built on `GLIBC` `2.11.1` [(#827)](https://github.com/ReHLDS/ReHLDS/pull/827)
### Fixed
* `QuaternionSlerp`: Fixed wrong values [(#763)](https://github.com/ReHLDS/ReHLDS/pull/763)
### Changed
* Updated `Intel C++ Compiler` version `17.0` up to `19.0`
**Full Changelog**: [3.8.0.723...3.8.0.739](https://github.com/ReHLDS/ReHLDS/compare/3.8.0.723...3.8.0.739)
## [`3.8.0.723`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.8.0.723) - 2021-03-23
### Fixed
* `CalcSurfaceExtents:` Fixed a fatal error on some maps due loss of floating point
* `HLTV:` ExecuteString Fix parser [(#821)](https://github.com/ReHLDS/ReHLDS/pull/821)
### Changed
* `HLTV:` Downgrade GLIBC version
**Full Changelog**: [3.8.0.715...3.8.0.723](https://github.com/ReHLDS/ReHLDS/compare/3.8.0.715...3.8.0.723)
## [`3.8.0.715`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.8.0.715) - 2021-03-18
### Fixed
* Make sure the `timer` is high precision [(#799)](https://github.com/ReHLDS/ReHLDS/pull/799)
**Full Changelog**: [3.8.0.711...3.8.0.715](https://github.com/ReHLDS/ReHLDS/compare/3.8.0.711...3.8.0.715)
## [`3.8.0.711`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.8.0.711) - 2021-02-06
### Added
* `HLTV`: Added new chatdelay command [(#777)](https://github.com/ReHLDS/ReHLDS/pull/777)
* `HLTV`: prevent clients from setting userinfo * keys with setinfo command [(#792)](https://github.com/ReHLDS/ReHLDS/pull/792)
* `Cbuf_Execute`: Add checks commented out for multi-lines [(#719)](https://github.com/ReHLDS/ReHLDS/pull/719)
### Fixed
* Fixed local-buffer overrun, may undefined behavior with hitboxes blending or crash (reverse-engineering mistake) [722e19d](https://github.com/ReHLDS/ReHLDS/commit/722e19d)
* Fixed dos attack on connection challenges system [(#802)](https://github.com/ReHLDS/ReHLDS/pull/802)
* Fixed crash `COM_ListMaps` [(#791)](https://github.com/ReHLDS/ReHLDS/pull/791)
**Full Changelog**: [3.8.0.702...3.8.0.711](https://github.com/ReHLDS/ReHLDS/compare/3.8.0.702...3.8.0.711)
## [`3.8.0.702`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.8.0.702) - 2020-11-09
### Fixed
* Fixed crash `MSG_ReadFloat`
### Changed
* **ReHLDS API:** Implemented `SV_ShouldSendConsistencyList`
* **ReHLDS API:** Bump minor
**Full Changelog**: [3.7.0.698...3.8.0.702](https://github.com/ReHLDS/ReHLDS/compare/3.7.0.698...3.8.0.702)
## [`3.7.0.698`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.7.0.698) - 2020-08-19
### Added
* Graceful shutdown on sigterm [(#776)](https://github.com/ReHLDS/ReHLDS/pull/776)
- Add players kick on `SIGINT \ SIGTERM`
- Add SIGINT & SIGTERM handling linux console
### Changed
* Changed shutdown method
**Full Changelog**: [3.7.0.697...3.7.0.698](https://github.com/ReHLDS/ReHLDS/compare/3.7.0.697...3.7.0.698)
## [`3.7.0.697`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.7.0.697) - 2020-08-10
### Fixed
* **SV_ProcessFile:** Wrap `Con_Printf` in `Con_NetPrintf` to avoid spam in HLDS console
**Full Changelog**: [3.7.0.696...3.7.0.697](https://github.com/ReHLDS/ReHLDS/compare/3.7.0.696...3.7.0.697)
## [`3.7.0.696`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.7.0.696) - 2020-05-18
### Added
* Implement `svc_exec` support in the engine and HLTV [(#737)](https://github.com/ReHLDS/ReHLDS/pull/737)
- Added `svc_exec` to the list of svc commands in engine
- Added `svc_exec` support to HLTV code
- Made the engine code forward-compatible with future svc_* additions
- Added reserved svc_* slots in the enumerations
**Full Changelog**: [3.7.0.695...3.7.0.696](https://github.com/ReHLDS/ReHLDS/compare/3.7.0.695...3.7.0.696)
## [`3.7.0.695`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.7.0.695) - 2020-04-06
### Fixed
* Vulnerability fix WAD part 2
- Client-side: Fixed a potential vulnerability from bogus `tempdecal.wad`
**Full Changelog**: [3.7.0.694...3.7.0.695](https://github.com/ReHLDS/ReHLDS/compare/3.7.0.694...3.7.0.695)
## [`3.7.0.694`](https://github.com/ReHLDS/ReHLDS/releases/tag/3.7.0.694) - 2020-03-20
### Fixed
* Vulnerability fix WAD part 1
- Server-side: Fixed a potential vulnerability from bogus `tempdecal.wad`
**Full Changelog**: [3.7.0.694](https://github.com/ReHLDS/ReHLDS/commits/3.7.0.694)

18
CMakeLists.txt Normal file
View File

@ -0,0 +1,18 @@
cmake_minimum_required(VERSION 3.1)
project(rehlds CXX)
if (WIN32)
message(FATAL_ERROR "CMakeLists.txt Windows platform isn't supported yet. Use msvc/ReHLDS.sln instead it!")
endif()
add_custom_target(appversion DEPENDS
COMMAND "${PROJECT_SOURCE_DIR}/rehlds/version/appversion.sh" "${PROJECT_SOURCE_DIR}"
)
add_subdirectory(rehlds)
if (NOT CMAKE_BUILD_TYPE MATCHES Unittests)
add_subdirectory(rehlds/dedicated)
add_subdirectory(rehlds/filesystem)
add_subdirectory(rehlds/HLTV)
endif()

696
LICENSE
View File

@ -1,675 +1,21 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
MIT License
Copyright (c) 20142025 ReHLDS Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

16
LICENSE-TRANSITION.md Normal file
View File

@ -0,0 +1,16 @@
# License Transition Notice
ReHLDS was originally licensed under the GNU General Public License v3.0 (GPLv3).
As of July 2025, the project has transitioned to the MIT License with the explicit agreement of the major contributors, including:
- dreamstalker
- s1lent
- WPMGPRoSToTeMa
- Lev
- wopox
All significant contributors have agreed to this license transition.
All previous contributions are now considered to be licensed under the MIT License unless otherwise noted.
For questions, contact us via GitHub or the ReHLDS dev chat.

189
README.md
View File

@ -1,5 +1,4 @@
# Rehlds [![Build Status](http://teamcity.rehlds.org/app/rest/builds/buildType:(id:Rehlds_Publish)/statusIcon)](http://teamcity.rehlds.org/viewType.html?buildTypeId=Rehlds_Publish&guest=1) [![Download](https://camo.githubusercontent.com/65c70643ec7b40eea50971003624c2fb04d8d375/687474703a2f2f7265686c64732e6f72672f76657273696f6e2f7265686c64732e737667)](http://teamcity.rehlds.org/guestAuth/downloadArtifacts.html?buildTypeId=Rehlds_Publish&buildId=lastSuccessful)
# ReHLDS [![C/C++ CI](https://github.com/rehlds/ReHLDS/actions/workflows/build.yml/badge.svg)](https://github.com/rehlds/ReHLDS/actions/workflows/build.yml) [![GitHub release (by tag)](https://img.shields.io/github/downloads/rehlds/ReHLDS/latest/total)](https://github.com/rehlds/ReHLDS/releases/latest) ![GitHub all releases](https://img.shields.io/github/downloads/rehlds/ReHLDS/total) [![Percentage of issues still open](http://isitmaintained.com/badge/open/rehlds/ReHLDS.svg)](http://isitmaintained.com/project/rehlds/ReHLDS "Percentage of issues still open") [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://www.gnu.org/licenses/gpl-3.0) [![CII Best Practices](https://bestpractices.dev/projects/10929/badge)](https://www.bestpractices.dev/en/projects/10929) <img align="right" src="https://user-images.githubusercontent.com/5860435/111066129-040e5e00-84f0-11eb-9e1f-7a7e8611da2b.png" alt="ReHLDS" />
Reverse-engineered (and bugfixed) HLDS
## What is this?
@ -7,7 +6,16 @@ ReHLDS is a result of reverse engineering of original HLDS (build 6152/6153) usi
Along with reverse engineering, a lot of defects and (potential) bugs were found and fixed
You can try play on one of the servers that using rehlds: http://www.gametracker.com/search/?search_by=server_variable&search_by2=sv_version
You can try playing on one of many servers that are using ReHLDS: [Game Tracker](http://www.gametracker.com/search/?search_by=server_variable&search_by2=sv_version)
> [!TIP]
> ReHLDS linux-releases now is signed via `GPG`, pubkey is: `63547829004f07716f7be4856c32c4282e60fb67` and could be found at [https://keyserver.ubuntu.com/](https://keyserver.ubuntu.com/pks/lookup?search=63547829004f07716f7be4856c32c4282e60fb67+&fingerprint=on&op=index).
>
> How to:
> 1. [Download](https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x63547829004f07716f7be4856c32c4282e60fb67) `63547829004f07716f7be4856c32c4282e60fb67.asc` key
> 2. Import: `gpg --import 63547829004f07716f7be4856c32c4282e60fb67.asc`
> 3. Download release `archive` and `.asc` file.
> 4. Verify: `gpg --verify some-rehlds.zip.asc some-rehlds.zip`.
## Goals of the project
<ul>
@ -15,107 +23,152 @@ You can try play on one of the servers that using rehlds: http://www.gametracker
<li>Performance optimizations (use of SSE for vector math for example) is another goal for the future</li>
</ul>
## 🛠 License
ReHLDS is licensed under the [MIT License](./LICENSE).
### License Transition
> [!NOTE]
> Originally released under [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html), ReHLDS transitioned to the MIT License in July 2025 with the agreement of the core contributors.
> See [LICENSE-TRANSITION.md](./LICENSE-TRANSITION.md) for details.
## How can use it?
Rehlds is fully compatible with latest official HLDS downloaded by steamcmd. All you have to do is to download rehlds binaries and replace original swds.dll/engine_i486.so. For windows you can also copy a swds.pdb file with a debug information.
<br /><b>Warning!</b> Rehlds is not compatible with an old 5xxx or below platforms downloaded by hldsupdatetool.
ReHLDS is fully compatible with the official pre-anniversary edition of HLDS (engine version <= 8684) downloaded by steamcmd. All you have to do is to download ReHLDS binaries and replace original swds.dll/engine_i486.so. For windows you can also copy a swds.pdb file with a debug information.
Compiled binaries are available here: http://nexus.rehlds.org/nexus/content/repositories/rehlds-dev/rehlds/rehlds/
> [!CAUTION]
> ReHLDS is not compatible with an old 5xxx or below platforms downloaded by hldsupdatetool.
Rehlds binaries require SSE, SSE2 and SSE3 instruction sets to run and can benefit from SSE4.1 and SSE4.2.
#### Downloading HLDS via steamcmd
Archive's bin directory contains 2 subdirectories, 'bugfixed' and 'pure'
<ul>
<li>'pure' version is designed to work exactly as official hlds engine</li>
<li>'bugfixed' version contains some fixes and improvements</li>
</ul>
```
app_set_config 90 mod cstrike
app_update 90 -beta steam_legacy validate
```
<b>Warning!</b> Rehlds is not binary compatible with original hlds since it's compiled with compilers other than ones used for original hlds. This means that plugins that do binary code analysis (Orpheu for example) probably will not work with rehlds.
## Downloads
* [Release builds](https://github.com/rehlds/ReHLDS/releases)
* [Dev builds](https://github.com/rehlds/ReHLDS/actions/workflows/build.yml)
ReHLDS binaries require `SSE`, `SSE2` and `SSE3` instruction sets to run and can benefit from `SSE4.1` and `SSE4.2`
<b>Warning!</b> ReHLDS is not binary compatible with original hlds since it's compiled with compilers other than ones used for original hlds.
This means that plugins that do binary code analysis (Orpheu for example) probably will not work with ReHLDS.
## Configuring
Bugfixed version of rehlds contains an additional cvars:
<details>
<summary>Click to expand</summary>
<ul>
<li>listipcfgfile <filename> // File for permanent ip bans. Default: listip.cfg
<li>syserror_logfile <filename> // File for the system error log. Default: sys_error.log
<li>sv_auto_precache_sounds_in_models <1|0> // Automatically precache sounds attached to models. Deault: 0
<li>sv_delayed_spray_upload <1|0> // Upload custom sprays after entering the game instead of when connecting. It increases upload speed. Default: 0
<li>sv_echo_unknown_cmd <1|0> // Echo in the console when trying execute an unknown command. Default: 0
<li>sv_rcon_condebug <1|0> // Print rcon debug in the console. Default: 1
<li>sv_force_ent_intersection <1|0> // In a 3-rd party plugins used to force colliding of SOLID_SLIDEBOX entities. Default: 0
<li>sv_rehlds_force_dlmax <1|0> // Force a client's cl_dlmax cvar to 1024. It avoids an excessive packets fragmentation. Default: 0
<li>sv_rehlds_hull_centering <1|0> // Use center of hull instead of corner. Default: 0
<li>listipcfgfile &lt;filename&gt; // File for permanent ip bans. Default: listip.cfg
<li>syserror_logfile &lt;filename&gt; // File for the system error log. Default: sys_error.log
<li>sv_auto_precache_sounds_in_models &lt;1|0&gt; // Automatically precache sounds attached to models. Deault: 0
<li>sv_delayed_spray_upload &lt;1|0&gt; // Upload custom sprays after entering the game instead of when connecting. It increases upload speed. Default: 0
<li>sv_echo_unknown_cmd &lt;1|0&gt; // Echo in the console when trying execute an unknown command. Default: 0
<li>sv_rcon_condebug &lt;1|0&gt; // Print rcon debug in the console. Default: 1
<li>sv_force_ent_intersection &lt;1|0&gt; // In a 3-rd party plugins used to force colliding of SOLID_SLIDEBOX entities. Default: 0
<li>sv_rehlds_force_dlmax &lt;1|0&gt; // Force a client's cl_dlmax cvar to 1024. It avoids an excessive packets fragmentation. Default: 0
<li>sv_rehlds_hull_centering &lt;1|0&gt; // Use center of hull instead of corner. Default: 0
<li>sv_rehlds_movecmdrate_max_avg // Max average level of 'move' cmds for ban. Default: 400
<li>sv_rehlds_movecmdrate_avg_punish // Time in minutes for which the player will be banned (0 - Permanent, use a negative number for a kick). Default: 5
<li>sv_rehlds_movecmdrate_max_burst // Max burst level of 'move' cmds for ban. Default: 2500
<li>sv_rehlds_movecmdrate_burst_punish // Time in minutes for which the player will be banned (0 - Permanent, use a negative number for a kick). Default: 5
<li>sv_rehlds_send_mapcycle <1|0> // Send mapcycle.txt in serverinfo message (HLDS behavior, but it is unused on the client). Default: 0
<li>sv_rehlds_send_mapcycle &lt;1|0&gt; // Send mapcycle.txt in serverinfo message (HLDS behavior, but it is unused on the client). Default: 0
<li>sv_rehlds_stringcmdrate_max_avg // Max average level of 'string' cmds for ban. Default: 80
<li>sv_rehlds_stringcmdrate_avg_punish // Time in minutes for which the player will be banned (0 - Permanent, use a negative number for a kick). Default: 5
<li>sv_rehlds_stringcmdrate_max_burst // Max burst level of 'string' cmds for ban. Default: 400
<li>sv_rehlds_stringcmdrate_burst_punish // Time in minutes for which the player will be banned (0 - Permanent, use a negative number for a kick). Default: 5
<li>sv_rehlds_userinfo_transmitted_fields // Userinfo fields only with these keys will be transmitted to clients via network. If not set then all fields will be transmitted (except prefixed with underscore). Each key must be prefixed by backslash, for example "\name\model\*sid\*hltv\bottomcolor\topcolor". See [wiki](https://github.com/dreamstalker/rehlds/wiki/Userinfo-keys) to collect sufficient set of keys for your server. Default: ""
<li>sv_rehlds_userinfo_transmitted_fields // Userinfo fields only with these keys will be transmitted to clients via network. If not set then all fields will be transmitted (except prefixed with underscore). Each key must be prefixed by backslash, for example "\name\model\*sid\*hltv\bottomcolor\topcolor". See [wiki](https://github.com/rehlds/ReHLDS/wiki/Userinfo-keys) to collect sufficient set of keys for your server. Default: ""
<li>sv_rehlds_attachedentities_playeranimationspeed_fix // Fixes bug with gait animation speed increase when player has some attached entities (aiments). Can cause animation lags when cl_updaterate is low. Default: 0
<li>sv_rehlds_maxclients_from_single_ip // Limit number of connections from the single ip address. Default: 5
<li>sv_rehlds_maxclients_from_single_ip // Limit number of connections at the same time from single IP address, not confuse to already connected players. Default: 5
<li>sv_rehlds_local_gametime &lt;1|0&gt; // A feature of local gametime which decrease "lags" if you run same map for a long time. Default: 0
<li>sv_use_entity_file // Use custom entity file for a map. Path to an entity file will be "maps/[map name].ent". 0 - use original entities. 1 - use .ent files from maps directory. 2 - use .ent files from maps directory and create new .ent file if not exist.
<li>sv_usercmd_custom_random_seed // When enabled server will populate an additional random seed independent of the client. Default: 0
<li>sv_net_incoming_decompression &lt;1|0&gt; // When enabled server will decompress of incoming compressed file transfer payloads. Default: 1
<li>sv_net_incoming_decompression_max_ratio &lt;0|100&gt; // Sets the max allowed ratio between compressed and uncompressed data for file transfer. (A ratio close to 90 indicates large uncompressed data with low entropy) Default: 80.0
<li>sv_net_incoming_decompression_max_size &lt;16|65536&gt; // Sets the max allowed size for decompressed file transfer data. Default: 65536 bytes
<li>sv_net_incoming_decompression_min_failures &lt;0|10&gt; // Sets the min number of decompression failures required before a player's connection is flagged for potential punishment. Default: 4
<li>sv_net_incoming_decompression_max_failures &lt;0|10&gt; // Sets the max number of decompression failures allowed within a specified time window before action is taken against the player. Default: 10
<li>sv_net_incoming_decompression_min_failuretime: &lt;0.1|10.0&gt; // Sets the min time in secs within which decompression failures are tracked to determine if the player exceeds the failure thresholds. Default: 0.1
<li>sv_net_incoming_decompression_punish // Time in minutes for which the player will be banned for malformed/abnormal bzip2 fragments (0 - Permanent, use a negative number for a kick). Default: -1
<li>sv_tags &lt;comma-delimited string list of tags&gt; // Sets a string defining the "gametags" for this server, this is optional, but if it is set it allows users/scripts to filter in the matchmaking/server-browser interfaces based on the value. Default: ""
<li>sv_filterban &lt;-1|0|1&gt;// Set packet filtering by IP mode. -1 - All players will be rejected without any exceptions. 0 - No checks will happen. 1 - All incoming players will be checked if they're IP banned (if they have an IP filter entry), if they are, they will be kicked. Default: 1
</ul>
</details>
## Commands
Bugfixed version of rehlds contains an additional commands:
<ul>
<li>rescount // Prints the total count of precached resources in the server console
<li>reslist &lt;sound | model | decal | generic | event&gt; // Separately prints the details of the precached resources for sounds, models, decals, generic and events in server console. Useful for managing resources and dealing with the goldsource precache limits.
<li>rcon_adduser &lt;ipaddress/CIDR&gt; // Add a new IP address or CIDR range to RCON user list (This command adds a new IP address to the RCON user list. The specified IP or CIDR range is granted privileged access to server console. Without any Rcon users, access is allowed to anyone with a valid password)</li>
<li>rcon_deluser &lt;ipaddress&gt; {removeAll} // Remove an IP address or CIDR range from RCON user list</li>
<li>rcon_users // List all IP addresses and CIDR ranges in RCON user list</li>
</ul>
## Build instructions
There are several software requirements for building rehlds:
<ol>
<li>Java Development Kit (JDK) 7+ (http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)</li>
<li>For Windows: Visual Studio 2013 and later</li>
<li>For Linux: Intel C++ Compiler 13 and later or GCC 4.9.2 or later (some earlier versions might work too)</li>
</ol>
### Checking requirements
#### JDK version
Windows<pre>&gt; %JAVA_HOME%\bin\javac -version
javac 1.8.0_25
There are several software requirements for building ReHLDS:
#### Windows
<pre>
Visual Studio 2015 (C++14 standard) and later
</pre>
Linux
<pre>$ javac -version
javac 1.7.0_65
</pre>
#### Visual Studio
Help -> About
#### ICC
<pre>$ icc --version
icc (ICC) 15.0.1 20141023
</pre>
#### GCC
<pre>$ gcc --version
gcc (Debian 4.9.2-10) 4.9.2
#### Linux
<pre>
cmake >= 3.10
GCC >= 4.9.2 (Optional)
ICC >= 15.0.1 20141023 (Optional)
LLVM (Clang) >= 6.0 (Optional)
</pre>
### Building
On Windows:
<pre>gradlew --max-workers=1 clean buildRelease</pre>
* For faster building without unit tests use this:exclamation:
<pre>gradlew --max-workers=1 clean buildFixes</pre>
<b>NOTE:</b> You can also use `Visual Studio` to build, just select from the solution configurations list `Release Swds` or `Debug Swds`<br />
On Linux (ICC):
<pre>./gradlew --max-workers=1 clean buildRelease</pre>
* For faster building without unit tests use this:exclamation:
<pre>./gradlew --max-workers=1 clean buildFixes</pre>
#### Windows
Use `Visual Studio` to build, open `msvc/ReHLDS.sln` and just select from the solution configurations list `Release Swds` or `Debug Swds`
On Linux (GCC):
<pre>./gradlew --max-workers=1 -PuseGcc clean buildRelease</pre>
* For faster building without unit tests use this:exclamation:
<pre>./gradlew --max-workers=1 -PuseGcc clean buildFixes</pre>
#### Linux
Also there is a task `buildEngine`, it builds only engine, without other parts of the project.<br />
Compiled binaries will be placed in the rehlds/build/binaries/ directory
* Optional options using `build.sh --compiler=[gcc] --jobs=[N] -D[option]=[ON or OFF]` (without square brackets)
<pre>
-c=|--compiler=[icc|gcc|clang] - Select preferred C/C++ compiler to build
-j=|--jobs=[N] - Specifies the number of jobs (commands) to run simultaneously (For faster building)
<sub>Definitions (-D)</sub>
DEBUG - Enables debugging mode
USE_STATIC_LIBSTDC - Enables static linking library libstdc++
</pre>
* ICC <pre>./build.sh --compiler=intel</pre>
* LLVM (Clang) <pre>./build.sh --compiler=clang</pre>
* GCC <pre>./build.sh --compiler=gcc</pre>
##### Checking build environment (Debian / Ubuntu)
<details>
<summary>Click to expand</summary>
<ul>
<li>
Installing required packages
<pre>
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install -y gcc-multilib g++-multilib
sudo apt-get install -y build-essential
sudo apt-get install -y libc6-dev libc6-dev-i386
sudo apt-get install -y cmake
</pre>
</li>
<li>
Select the preferred C/C++ Compiler installation
<pre>
1) sudo apt-get install -y gcc g++
2) sudo apt-get install -y clang
</pre>
</li>
</ul>
</details>
## How can I help the project?
Just install it on your game server and report problems you faced.

View File

@ -1,55 +0,0 @@
import versioning.GitVersioner
import versioning.RehldsVersionInfo
import org.joda.time.DateTime
apply plugin: 'maven-publish'
apply from: 'shared.gradle'
group = 'rehlds'
apply plugin: 'idea'
idea {
project {
languageLevel = 'JDK_1_7'
}
}
def gitInfo = GitVersioner.versionForDir(project.rootDir)
RehldsVersionInfo versionInfo
if (gitInfo && gitInfo.tag && gitInfo.tag[0] == 'v') {
def m = gitInfo.tag =~ /^v(\d+)\.(\d+)(\.(\d+))?$/
if (!m.find()) {
throw new RuntimeException("Invalid git version tag name ${gitInfo.tag}")
}
versionInfo = new RehldsVersionInfo(
majorVersion: m.group(1) as int,
minorVersion: m.group(2) as int,
maintenanceVersion: m.group(4) ? (m.group(4) as int) : null,
localChanges: gitInfo.localChanges,
commitDate: gitInfo.commitDate,
commitSHA: gitInfo.commitSHA,
commitURL: gitInfo.commitURL
)
} else {
versionInfo = new RehldsVersionInfo(
majorVersion: project.majorVersion as int,
minorVersion: project.minorVersion as int,
maintenanceVersion: project.maintenanceVersion as int,
suffix: 'dev',
localChanges: gitInfo ? gitInfo.localChanges : true,
commitDate: gitInfo ? gitInfo.commitDate : new DateTime(),
commitSHA: gitInfo ? gitInfo.commitSHA : "",
commitURL: gitInfo ? gitInfo.commitURL : "",
commitCount: gitInfo ? (gitInfo.commitCount as int) : null
)
}
project.ext.rehldsVersionInfo = versionInfo
project.version = versionInfo.asMavenVersion()
apply from: 'publish.gradle'
task wrapper(type: Wrapper) {
gradleVersion = '2.4'
}

60
build.sh Executable file
View File

@ -0,0 +1,60 @@
#!/bin/bash
main()
{
CC=gcc
CXX=g++
if [[ "$*" =~ "--help" ]]; then
help
exit 0;
fi
n=0
args=()
for i in "$@"
do
case $i in
-j=*|--jobs=*)
jobs="-j${i#*=}"
shift
;;
-c=*|--compiler=*)
C="${i#*=}"
shift
;;
*)
args[$n]="$i"
((++n))
;;
esac
done
case "$C" in
("intel"|"icc") CC=icc CXX=icpc ;;
("gcc"|"g++") CC=gcc CXX=g++ ;;
("clang|llvm") CC=clang CXX=clang++ ;;
*)
;;
esac
rm -rf build
mkdir build
pushd build &> /dev/null
CC=$CC CXX=$CXX cmake ${args[@]} ..
make ${jobs}
popd > /dev/null
}
help()
{
printf "Usage: ./build.sh <options>\n\n"
printf " -c= | --compiler=<icc|gcc|clang> - Select preferred C/C++ compiler to build\n"
printf " -j= | --jobs=<N> - Specifies the number of jobs (commands) to run simultaneously (For faster building)\n\n"
}
# Initialize
main $*
# Exit normally
exit 0

View File

@ -1,27 +0,0 @@
apply plugin: 'groovy'
repositories {
//mavenLocal()
mavenCentral()
maven {
url 'http://nexus.rehlds.org/nexus/content/repositories/rehlds-releases/'
}
maven {
url 'http://nexus.rehlds.org/nexus/content/repositories/rehlds-snapshots/'
}
maven {
url 'http://nexus.rehlds.org/nexus/content/repositories/rehlds-dev/'
}
}
dependencies {
compile gradleApi()
compile localGroovy()
compile 'commons-io:commons-io:2.4'
compile 'commons-lang:commons-lang:2.6'
compile 'joda-time:joda-time:2.7'
compile 'org.doomedsociety.gradlecpp:gradle-cpp-plugin:1.2'
compile 'org.eclipse.jgit:org.eclipse.jgit:3.7.0.201502260915-r'
compile 'org.apache.velocity:velocity:1.7'
}

View File

@ -1,58 +0,0 @@
package dirsync.builder
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
import groovy.transform.CompileStatic
class FileSystemTreeBuilder {
@CompileStatic
private static FileNode<File> buildNodeForFile(File file, DirectoryNode<File> parent) {
if (parent.getChildren(file.name)) {
throw new RuntimeException("Parent dir ${parent.name} already contains child node ${file.name}");
}
return new FileNode(
name: file.name,
lastModifiedDate: file.lastModified(),
data: file,
parent: parent,
size: file.size()
);
}
@CompileStatic
private static DirectoryNode<File> buildNodeForDirectoryRecursive(File dir, DirectoryNode<File> parent) {
if (!dir.isDirectory()) {
throw new RuntimeException("File ${dir.absolutePath} is not a directory")
}
if (parent != null && parent.getChildren(dir.name)) {
throw new RuntimeException("Parent dir ${parent.name} already contains child node ${dir.name}");
}
DirectoryNode<File> thisNode = new DirectoryNode(
name: dir.name,
lastModifiedDate: dir.lastModified(),
data: dir,
parent: parent
);
dir.eachFile { File f ->
if (f.isDirectory()) {
thisNode.childNodes[f.name] = buildNodeForDirectoryRecursive(f, thisNode)
} else {
thisNode.childNodes[f.name] = buildNodeForFile(f, thisNode)
}
}
return thisNode;
}
static DirectoryNode<File> buildFileSystemTree(File rootDir) {
def root = buildNodeForDirectoryRecursive(rootDir, null);
PostBuildPass.doPostBuild(root)
return root
}
}

View File

@ -1,60 +0,0 @@
package dirsync.builder
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
class FileTreeMerger {
private static <T> void mergeContentsRecursive(DirectoryNode<T> newParent, DirectoryNode<T> toMerge) {
toMerge.childNodes.each { cn ->
def node = cn.value
def existingNode = newParent.childNodes[node.name]
if (existingNode) {
if (!(existingNode instanceof DirectoryNode) || !(node instanceof DirectoryNode))
throw new RuntimeException("Failed to merge non-directory nodes ${node.fullPath}")
def existingDirNode = existingNode as DirectoryNode<T>
def dirNode = node as DirectoryNode<T>
existingDirNode.lastModifiedDate = Math.max(existingDirNode.lastModifiedDate, dirNode.lastModifiedDate)
mergeContentsRecursive(existingDirNode, dirNode)
} else {
if (node instanceof DirectoryNode) {
def dirNode = node as DirectoryNode<T>
def newNode = new DirectoryNode<T>(
name: dirNode.name,
data: dirNode.data,
parent: newParent,
lastModifiedDate: dirNode.lastModifiedDate
)
newParent.childNodes[node.name] = newNode
mergeContentsRecursive(newNode, dirNode)
} else {
FileNode<T> fileNode = node as FileNode<T>
FileNode<T> newNode = new FileNode<T>(
name: fileNode.name,
data: fileNode.data,
parent: newParent,
lastModifiedDate: fileNode.lastModifiedDate,
size: fileNode.size
)
newParent.childNodes[node.name] = newNode
}
}
}
}
public static <T> DirectoryNode<T> mergeTrees(DirectoryNode<T> tree1, DirectoryNode<T> tree2) {
DirectoryNode<T> newRoot = new DirectoryNode<T>(
name: tree1.name ?: tree2.name
)
mergeContentsRecursive(newRoot, tree1)
mergeContentsRecursive(newRoot, tree2)
PostBuildPass.doPostBuild(newRoot)
return newRoot
}
}

View File

@ -1,22 +0,0 @@
package dirsync.builder
import dirsync.model.tree.DirectoryNode
class PostBuildPass {
private static <T> void postProcessRecursive(DirectoryNode<T> dir) {
dir.childNodes.each { cne ->
def childNode = cne.value
childNode.fullPath = dir.fullPath ? dir.fullPath + '/' + childNode.name : childNode.name
if (childNode instanceof DirectoryNode) {
def childDirNode = childNode as DirectoryNode<T>
postProcessRecursive(childDirNode)
}
}
}
static <T> void doPostBuild(DirectoryNode<T> root) {
root.fullPath = ''
postProcessRecursive(root)
}
}

View File

@ -1,53 +0,0 @@
package dirsync.builder
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
import dirsync.model.tree.ZipData
import java.util.zip.ZipFile
class ZipTreeBuilder {
static DirectoryNode<ZipData> buildForZipArchive(String zipArchive, ZipFile zf) {
DirectoryNode<ZipData> root = new DirectoryNode<>()
zf.entries().each { ze ->
def path = ze.name.replace('\\', '/')
if (path.endsWith('/'))
path = path.substring(0, path.length() - 1)
def parentPath = path.contains('/') ? path.substring(0, path.lastIndexOf('/')) : ''
def childPath = path.contains('/') ? path.substring(path.lastIndexOf('/') + 1) : path
def parentNode = (DirectoryNode<ZipData>) root.getByPath(parentPath)
if (parentNode == null)
throw new RuntimeException("Error reading ${zipArchive}: could not find parent path ${parentPath} for path ${path}")
def childNode = parentNode.getChildren(childPath)
if (childNode)
throw new RuntimeException("Error reading ${zipArchive}: duplicate path ${path}")
if (ze.directory) {
childNode = new DirectoryNode<ZipData>(
name: childPath,
lastModifiedDate: ze.time,
data: new ZipData(zipEntryName: ze.name, zipArchiveName: zipArchive),
parent: parentNode
);
} else {
childNode = new FileNode<ZipData>(
name: childPath,
lastModifiedDate: ze.time,
data: new ZipData(zipEntryName: ze.name, zipArchiveName: zipArchive),
parent: parentNode,
size: ze.size
);
}
parentNode.childNodes[childPath] = childNode
//println '' + ze.directory + ' ' + ze.name + ' ' + parentPath + ' ' + childPath
}
PostBuildPass.doPostBuild(root)
return root
}
}

View File

@ -1,97 +0,0 @@
package dirsync.merger
import dirsync.model.synccmd.AbstractSyncCmd
import dirsync.model.synccmd.CopyDirCmd
import dirsync.model.synccmd.CopyFileCmd
import dirsync.model.synccmd.DeleteDirCmd
import dirsync.model.synccmd.DeleteFileCmd
import dirsync.model.synccmd.ReplaceFileCmd
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
import groovy.transform.TypeChecked
@TypeChecked
class FileTreeComparator {
private static <T, U> void mergeDirsRecursive(DirectoryNode<T> left, DirectoryNode<U> right, List<AbstractSyncCmd<T, U>> diffs) {
// left => right
left.childNodes.each { le ->
def leftNode = le.value
def rightNode = right.childNodes[leftNode.name]
if (rightNode == null) {
switch (leftNode) {
case DirectoryNode:
def leftDirNode = leftNode as DirectoryNode<T>
diffs << new CopyDirCmd<>(src: leftDirNode, dstParentDir: right)
break
case FileNode:
def leftFileNode = leftNode as FileNode<T>
diffs << new CopyFileCmd<>(src: leftFileNode, dstDir: right)
break
default:
throw new RuntimeException("Invalid node class ${leftNode.class.name}")
}
return
}
if (rightNode.class != leftNode.class) {
throw new RuntimeException("node classes mismatch: ${leftNode.class.name} != ${rightNode.class.name}")
}
switch (rightNode) {
case DirectoryNode:
def leftDirNode = leftNode as DirectoryNode<T>
def rightDirNode = rightNode as DirectoryNode<U>
mergeDirsRecursive(leftDirNode, rightDirNode, diffs)
break
case FileNode:
def leftFileNode = leftNode as FileNode<T>
def rightFileNode = rightNode as FileNode<T>
if (leftFileNode.size != rightFileNode.size || leftFileNode.lastModifiedDate != rightFileNode.lastModifiedDate) {
diffs << new ReplaceFileCmd<>(src: leftFileNode, dst: rightFileNode)
}
break
default:
throw new RuntimeException("Invalid node class ${rightNode.class.name}")
}
} // ~left => right
//right => left
right.childNodes.each { re ->
def rightNode = re.value
def leftNode = left.childNodes[rightNode.name]
if (leftNode != null) {
return //already processed in left => right
}
switch (rightNode) {
case DirectoryNode:
def rightDirNode = rightNode as DirectoryNode<U>
diffs << new DeleteDirCmd<>(dirNode: rightDirNode)
break
case FileNode:
def rightFileNode = rightNode as FileNode<T>
diffs << new DeleteFileCmd<>(node: rightFileNode)
break
default:
throw new RuntimeException("Invalid node class ${rightNode.class.name}")
}
} // ~right => left
}
static <T, U> List<AbstractSyncCmd<T, U>> mergeTrees(DirectoryNode<T> leftRoot, DirectoryNode<U> rightRoot) {
List<AbstractSyncCmd<T, U>> res = []
mergeDirsRecursive(leftRoot, rightRoot, res)
return res
}
}

View File

@ -1,103 +0,0 @@
package dirsync.merger
import dirsync.model.synccmd.AbstractSyncCmd
import dirsync.model.synccmd.CopyDirCmd
import dirsync.model.synccmd.CopyFileCmd
import dirsync.model.synccmd.DeleteDirCmd
import dirsync.model.synccmd.DeleteFileCmd
import dirsync.model.synccmd.ReplaceFileCmd
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
import dirsync.model.tree.TreePhysMapper
import groovy.transform.TypeChecked
import org.apache.commons.io.IOUtils
@TypeChecked
public class FileTreeDiffApplier {
static <T, U> void copyDirRecursive(DirectoryNode<T> src, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
dstMapper.createDirectory(src.fullPath)
src.childNodes.each { ce ->
def childNode = ce.value
def childPath = childNode.fullPath
switch (childNode) {
case FileNode:
srcMapper.fileContent(childNode.data).withStream { InputStream inStream ->
dstMapper.createFile(childPath).withStream { OutputStream outStream ->
IOUtils.copy(inStream, outStream)
}
dstMapper.setFileLastUpdatedDate(childPath, childNode.lastModifiedDate)
}
break;
case DirectoryNode:
copyDirRecursive(childNode as DirectoryNode<T>, srcMapper, dstMapper)
break;
default:
throw new RuntimeException("Invalid node class: ${childNode.class.name}")
}
}
}
static <T, U> void handleCopyFile(CopyFileCmd<T, U> fileCopy, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
def dstPath = fileCopy.dstDir.fullPath ? fileCopy.dstDir.fullPath + '/' + fileCopy.src.name : fileCopy.src.name
srcMapper.fileContent(fileCopy.src.data).withStream { InputStream inStream ->
dstMapper.createFile(dstPath).withStream { OutputStream outStream ->
IOUtils.copy(inStream, outStream)
}
dstMapper.setFileLastUpdatedDate(dstPath, fileCopy.src.lastModifiedDate)
}
}
static <T, U> void handleDeleteDir(DeleteDirCmd<T, U> delDir, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
dstMapper.removeDirectory(delDir.dirNode.fullPath)
}
static <T, U> void handleDeleteFile(DeleteFileCmd<T, U> delFile, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
dstMapper.removeFile(delFile.node.fullPath)
}
static <T, U> void handleReplaceFile(ReplaceFileCmd<T, U> replaceFile, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
dstMapper.removeFile(replaceFile.dst.fullPath)
srcMapper.fileContent(replaceFile.src.data).withStream { InputStream inStream ->
dstMapper.createFile(replaceFile.dst.fullPath).withStream { OutputStream outStream ->
IOUtils.copy(inStream, outStream)
}
dstMapper.setFileLastUpdatedDate(replaceFile.dst.fullPath, replaceFile.src.lastModifiedDate)
}
}
static <T, U> void applyDiffs(List<AbstractSyncCmd<T, U>> diffs, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
diffs.each { diff ->
switch (diff) {
case CopyDirCmd:
def copyDir = diff as CopyDirCmd<T, U>
copyDirRecursive(copyDir.src, srcMapper, dstMapper)
break
case CopyFileCmd:
handleCopyFile(diff as CopyFileCmd<T, U>, srcMapper, dstMapper)
break
case DeleteDirCmd:
handleDeleteDir(diff as DeleteDirCmd<T, U>, srcMapper, dstMapper)
break
case DeleteFileCmd:
handleDeleteFile(diff as DeleteFileCmd<T, U>, srcMapper, dstMapper)
break
case ReplaceFileCmd:
handleReplaceFile(diff as ReplaceFileCmd<T, U>, srcMapper, dstMapper)
break
default:
throw new RuntimeException("Invalid diff command ${diff.class.name}")
}
}
}
}

View File

@ -1,4 +0,0 @@
package dirsync.model.synccmd
class AbstractSyncCmd<T, U> {
}

View File

@ -1,8 +0,0 @@
package dirsync.model.synccmd
import dirsync.model.tree.DirectoryNode
class CopyDirCmd<T, U> extends AbstractSyncCmd<T, U> {
DirectoryNode<T> src
DirectoryNode<U> dstParentDir
}

View File

@ -1,9 +0,0 @@
package dirsync.model.synccmd
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
class CopyFileCmd<T, U> extends AbstractSyncCmd<T, U> {
FileNode<T> src
DirectoryNode<U> dstDir
}

View File

@ -1,7 +0,0 @@
package dirsync.model.synccmd
import dirsync.model.tree.DirectoryNode
class DeleteDirCmd<T, U> extends AbstractSyncCmd<T, U> {
DirectoryNode<U> dirNode
}

View File

@ -1,7 +0,0 @@
package dirsync.model.synccmd
import dirsync.model.tree.FileNode
class DeleteFileCmd<T, U> extends AbstractSyncCmd<T, U> {
FileNode<U> node
}

View File

@ -1,8 +0,0 @@
package dirsync.model.synccmd
import dirsync.model.tree.FileNode
class ReplaceFileCmd<T, U> extends AbstractSyncCmd<T, U> {
FileNode<T> src
FileNode<U> dst
}

View File

@ -1,27 +0,0 @@
package dirsync.model.tree
import groovy.transform.CompileStatic
@CompileStatic
abstract class AbstractFileTreeNode<T> {
DirectoryNode<T> parent
String name
String fullPath
long lastModifiedDate
T data
boolean equals(o) {
if (this.is(o)) return true
if (getClass() != o.class) return false
AbstractFileTreeNode that = (AbstractFileTreeNode) o
if (name != that.name) return false
return true
}
int hashCode() {
return (name != null ? name.hashCode() : 0)
}
}

View File

@ -1,42 +0,0 @@
package dirsync.model.tree
import groovy.transform.CompileStatic
@CompileStatic
class DirectoryNode<T> extends AbstractFileTreeNode<T> {
Map<String, AbstractFileTreeNode<T>> childNodes = new HashMap<>()
AbstractFileTreeNode<T> getChildren(String name) {
return childNodes[name];
}
AbstractFileTreeNode<T> getChildren(String[] names, int idx) {
if (idx == names.length)
return this
AbstractFileTreeNode<T> c = childNodes[names[idx]]
if (c == null)
return null
if (c instanceof DirectoryNode) {
def d = (DirectoryNode<T>) c;
return d.getChildren(names, idx + 1)
}
return null;
}
AbstractFileTreeNode<T> getByPath(String path) {
path = path.replace('\\', '/')
if (path.endsWith('/'))
path = path.substring(0, path.length() - 1)
if (path.empty) {
return this
}
String[] components = path.split('/')
return getChildren(components, 0)
}
}

View File

@ -1,50 +0,0 @@
package dirsync.model.tree
class FSMapper extends TreePhysMapper<File> {
final File root
FSMapper(File root) {
this.root = root
}
@Override
InputStream fileContent(File file) {
return file.newDataInputStream()
}
@Override
void createDirectory(String dir) {
def target = new File(root, dir)
if (!target.mkdirs()) {
throw new RuntimeException("Failed to create directory ${target.absolutePath}")
}
}
@Override
void removeDirectory(String dir) {
def target = new File(root, dir)
if (!target.deleteDir()) {
throw new RuntimeException("Failed to delete directory ${target.absolutePath}")
}
}
@Override
void removeFile(String path) {
def target = new File(root, path)
if (!target.delete()) {
throw new RuntimeException("Failed to delete file ${target.absolutePath}")
}
}
@Override
OutputStream createFile(String path) {
def target = new File(root, path)
return target.newOutputStream()
}
@Override
void setFileLastUpdatedDate(String path, long date) {
def target = new File(root, path)
target.setLastModified(date)
}
}

View File

@ -1,8 +0,0 @@
package dirsync.model.tree
import groovy.transform.CompileStatic
@CompileStatic
class FileNode<T> extends AbstractFileTreeNode<T> {
long size
}

View File

@ -1,11 +0,0 @@
package dirsync.model.tree
abstract class TreePhysMapper<T> {
abstract InputStream fileContent(T file)
abstract void createDirectory(String dir)
abstract void removeDirectory(String dir)
abstract void removeFile(String path)
abstract OutputStream createFile(String path)
abstract void setFileLastUpdatedDate(String path, long date)
}

View File

@ -1,9 +0,0 @@
package dirsync.model.tree
import groovy.transform.CompileStatic
@CompileStatic
class ZipData {
String zipEntryName
String zipArchiveName
}

View File

@ -1,72 +0,0 @@
package dirsync.model.tree
import dirsync.builder.FileTreeMerger
import dirsync.builder.ZipTreeBuilder
import sun.reflect.generics.reflectiveObjects.NotImplementedException
import java.util.zip.ZipFile
public class ZipTreeMapper extends TreePhysMapper<ZipData> implements Closeable {
Map<String, ZipFile> zipArchives = [:]
void addZipArchive(String zipArchive) {
zipArchives[zipArchive] = new ZipFile(zipArchive)
}
DirectoryNode<ZipData> buildFileTree() {
def root = new DirectoryNode<ZipData>()
zipArchives.each { ze ->
def zipTree = ZipTreeBuilder.buildForZipArchive(ze.key, ze.value)
root = FileTreeMerger.mergeTrees(root, zipTree)
}
return root
}
@Override
void close() throws IOException {
zipArchives.each { ze ->
try { ze.value.close() } catch (Exception ignored) { }
}
}
@Override
InputStream fileContent(ZipData file) {
def archive = zipArchives[file.zipArchiveName]
if (!archive) {
throw new RuntimeException("Archive ${file.zipArchiveName} is not loaded");
}
def zipEntry = archive.getEntry(file.zipEntryName)
if (!zipEntry) {
throw new RuntimeException("File ${file.zipEntryName} not found in archive ${file.zipArchiveName}");
}
return archive.getInputStream(zipEntry)
}
@Override
void createDirectory(String dir) {
throw new NotImplementedException()
}
@Override
void removeDirectory(String dir) {
throw new NotImplementedException()
}
@Override
void removeFile(String path) {
throw new NotImplementedException()
}
@Override
OutputStream createFile(String path) {
throw new NotImplementedException()
}
@Override
void setFileLastUpdatedDate(String path, long date) {
throw new NotImplementedException()
}
}

View File

@ -1,19 +0,0 @@
package gradlecpp
import org.gradle.api.Project
import org.gradle.nativeplatform.NativeBinarySpec
class CppUnitTestExtension {
Project _project
CppUnitTestExtension(Project p) {
_project = p
}
void eachTestExecutable(Closure action) {
_project.binaries.each { NativeBinarySpec bin ->
if (!bin.hasProperty('cppUnitTestsExecutable')) return
action(bin)
}
}
}

View File

@ -1,256 +0,0 @@
package gradlecpp
import gradlecpp.teamcity.TeamCityIntegration
import org.gradle.api.Action
import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.internal.project.AbstractProject
import org.gradle.model.internal.core.DirectNodeModelAction
import org.gradle.model.internal.core.ModelActionRole
import org.gradle.model.internal.core.ModelPath
import org.gradle.model.internal.core.ModelReference
import org.gradle.model.internal.core.MutableModelNode
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor
import org.gradle.model.internal.core.rule.describe.SimpleModelRuleDescriptor
import org.gradle.model.internal.registry.ModelRegistry
import org.gradle.nativeplatform.NativeBinarySpec
import org.gradle.nativeplatform.NativeLibrarySpec
import org.gradle.nativeplatform.internal.AbstractNativeBinarySpec
import org.doomedsociety.gradlecpp.GradleCppUtils
class CppUnitTestPlugin implements Plugin<Project> {
private static class TestExecStatus {
boolean successful
boolean warning
int exitCode
String output
long durationMsec
String cmdLine
String execDir
}
static void onBinariesCreated(Project p, String desc, Closure action) {
ModelRegistry mr = (p as AbstractProject).getModelRegistry()
def modelPath = ModelPath.path("binaries")
ModelRuleDescriptor ruleDescriptor = new SimpleModelRuleDescriptor(desc);
mr.configure(ModelActionRole.Finalize, DirectNodeModelAction.of(ModelReference.of(modelPath), ruleDescriptor, new Action<MutableModelNode>() {
@Override
void execute(MutableModelNode node) {
action()
}
}))
}
@Override
void apply(Project project) {
project.extensions.create('cppUnitTest', CppUnitTestExtension, project)
onBinariesCreated(project, 'CppUnitTestPlugin::AttachUnitTest', {
processCppUnitTests(project)
})
}
/**
* Attaches test tasks to C/C++ libraries build tasks
*/
static void processCppUnitTests(Project p) {
//println "processCppUnitTests::afterEvaluate on ${p.name}: project type is ${p.projectType}"
p.binaries.all { NativeBinarySpec bin ->
if (!(bin.component instanceof NativeLibrarySpec)) {
return
}
def testComponentName = bin.component.name + '_tests'
Collection<NativeBinarySpec> testCandidates = p.binaries.matching { it.component.name == testComponentName && bin.buildType == it.buildType && bin.flavor == it.flavor }
if (testCandidates.size() > 1) {
throw new GradleException("Found >1 test candidates for library ${bin.component.name} in project ${p}: ${testCandidates}")
} else if (!testCandidates.empty) {
def testBinary = testCandidates.first()
GradleCppUtils.onTasksCreated(p, 'CppUnitTestPlugin::AttachUnitTestTask', {
attachTestTaskToCppLibrary(bin, testBinary)
})
String testTaskName = bin.namingScheme.getTaskName('unitTest')
bin.ext.cppUnitTestTask = testTaskName
} else {
throw new GradleException("No tests found for library ${bin.component.name} in project ${p}")
}
}
}
static TestExecStatus runTestExecutable(NativeBinarySpec testSubject, String executable, List<String> params, String phase, int timeout) {
def execFile = new File(executable)
def outDir = new File(testSubject.buildTask.project.buildDir, "tests/${testSubject.name}/run")
outDir.mkdirs()
def outPath = new File(outDir, "${phase}.log")
def cmdParams = [];
cmdParams << execFile.absolutePath
cmdParams.addAll(params)
def execDir = execFile.parentFile
def pb = new ProcessBuilder(cmdParams).redirectErrorStream(true).directory(execDir)
if (!GradleCppUtils.windows) {
pb.environment().put('LD_LIBRARY_PATH', '.')
}
def sout = new StringBuffer()
long startTime = System.currentTimeMillis()
def p = pb.start()
p.consumeProcessOutput(sout, sout)
p.waitForOrKill(timeout * 1000)
long endTime = System.currentTimeMillis()
int exitVal = p.exitValue()
outPath.withWriter('UTF-8') { writer ->
writer.write(sout.toString())
}
return new TestExecStatus(
exitCode: exitVal,
successful: (exitVal == 0 || exitVal == 3),
warning: (exitVal == 3),
output: sout.toString(),
durationMsec: endTime - startTime,
cmdLine: cmdParams.join(' '),
execDir: execDir.absolutePath
)
}
static void dumpTestExecStatus(TestExecStatus stat) {
if (!stat) {
println "Execution of test executable failed"
}
println "Test executable command: ${stat.cmdLine}"
println "Test executable run directury: ${stat.execDir}"
println "Test executable exit code: ${stat.exitCode}"
println "Test executable output BEGIN"
println stat.output
println "Test executable output END"
}
static void attachTestTaskToCppLibrary(NativeBinarySpec libBin, NativeBinarySpec testExecBin) {
Project p = libBin.buildTask.project
def libBinImpl = libBin as AbstractNativeBinarySpec
def libLinkTask = GradleCppUtils.getLinkTask(libBin)
def testExecLinkTask = GradleCppUtils.getLinkTask(testExecBin)
// collect all output files from library and test executable
def depFiles = []
depFiles.addAll(libLinkTask.outputs.files.files)
depFiles.addAll(testExecLinkTask.outputs.files.files)
//create 'tests' task
def testTaskName = libBinImpl.namingScheme.getTaskName('unitTest')
def testTask = p.task(testTaskName, { Task testTask ->
//output dir
def testResDir = new File(p.buildDir, "tests/${libBin.name}")
//inputs/outputs for up-to-date check
testTask.outputs.dir testResDir
testTask.inputs.files depFiles
//dependencies on library and test executable
testTask.dependsOn libLinkTask
testTask.dependsOn testExecLinkTask
// binary build depends on unit test
libBin.buildTask.dependsOn testTask
// extra project-specific dependencies
def testDepsTask = p.tasks.findByName('testDeps')
if (testDepsTask != null) {
testTask.dependsOn testDepsTask
}
// task actions
testTask.doLast {
//temporary file that store info about all tests (XML)
File allTests = File.createTempFile('j4s-testinfo', 'data')
allTests.deleteOnExit()
//fill file with test info
print "Fetching test info..."
def getTestsStatus = runTestExecutable(libBin, testExecBin.executableFile.absolutePath, ['-writeTestInfo', allTests.absolutePath], '__getTests', 5000)
if (!getTestsStatus.successful) {
println " Failed"
dumpTestExecStatus(getTestsStatus)
throw new GradleException("Unable to fetch test names")
}
println " OK"
getTestsStatus = null // allow GC to collect it
// parse the test info file
def root = new XmlSlurper().parse(allTests)
// run all tests
println "Running ${root.test.size()} tests..."
TeamCityIntegration.suiteStarted("unitTests.${libBin.name}")
int failCount = 0;
int warnCount = 0;
root.test.list().each { testInfo ->
def testName = '' + testInfo.@name.text()
def testGroup = '' + testInfo.@group.text()
def testTimeout = ('' + testInfo.@timeout.text()) as int
if (!TeamCityIntegration.writeOutput) {
print " ${testGroup}-${testName}..."
System.out.flush()
}
TeamCityIntegration.testStarted("${testGroup}-${testName}")
def testExecStatus = runTestExecutable(libBin, testExecBin.executableFile.absolutePath, ['-runTest', testGroup, testName], "${testGroup}-${testName}", testTimeout)
if (!testExecStatus.successful) {
if (!TeamCityIntegration.writeOutput) {
println " Failed"
}
TeamCityIntegration.testFailed("${testGroup}-${testName}", "test executable return code is ${testExecStatus.exitCode}", "test executable return code is ${testExecStatus.exitCode}")
dumpTestExecStatus(testExecStatus)
failCount++
} else {
if (!TeamCityIntegration.writeOutput) {
if (testExecStatus.warning) {
println " WARNING"
dumpTestExecStatus(testExecStatus)
warnCount++
}
else
println " OK"
}
}
TeamCityIntegration.testStdOut("${testGroup}-${testName}", testExecStatus.output)
TeamCityIntegration.testFinished("${testGroup}-${testName}", testExecStatus.durationMsec)
}
TeamCityIntegration.suiteFinished("unitTests.${libBin.name}")
if (failCount) {
throw new GradleException("CPP unit tests: ${failCount} tests failed");
}
else if (warnCount) {
println "CPP unit tests: ${warnCount} tests warnings";
}
}
})
}
}

View File

@ -1,17 +0,0 @@
package gradlecpp
import org.gradle.api.Plugin
import org.gradle.api.Project
class RehldsPlayTestPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
project.configurations {
rehlds_playtest_image
}
project.dependencies {
rehlds_playtest_image 'rehlds.testimg:testimg:0.2'
}
}
}

View File

@ -1,80 +0,0 @@
package gradlecpp
import gradlecpp.teamcity.TeamCityIntegration
import org.apache.commons.lang.SystemUtils
import org.gradle.api.DefaultTask
import org.gradle.api.file.FileCollection
import org.gradle.api.tasks.TaskAction
import org.gradle.nativeplatform.NativeBinarySpec
import rehlds.testdemo.RehldsDemoRunner
import rehlds.testdemo.RehldsTestParser
class RehldsPlayTestTask extends DefaultTask {
def FileCollection testDemos
def Closure postExtractAction
def File rehldsImageRoot
def File rehldsTestLogs
def NativeBinarySpec testFor
@TaskAction
def doPlay() {
if (!SystemUtils.IS_OS_WINDOWS) {
return
}
if (!testDemos) {
println 'RehldsPlayTestTask: no demos attached to the testDemos property'
}
rehldsImageRoot.mkdirs()
rehldsTestLogs.mkdirs()
def demoRunner = new RehldsDemoRunner(this.project.configurations.rehlds_playtest_image.getFiles(), rehldsImageRoot, postExtractAction)
println "Preparing engine..."
demoRunner.prepareEngine()
println "Running ${testDemos.getFiles().size()} ReHLDS test demos..."
TeamCityIntegration.suiteStarted("rehldsDemo.${testFor.name}")
int failCount = 0;
testDemos.getFiles().each { f ->
def testInfo = RehldsTestParser.parseTestInfo(f)
TeamCityIntegration.testStarted(testInfo.testName)
if (!TeamCityIntegration.writeOutput) {
print "Running ReHLDS test demo ${testInfo.testName} "
System.out.flush()
}
def testRes = demoRunner.runTest(testInfo, rehldsTestLogs)
if (testRes.success) {
if (!TeamCityIntegration.writeOutput) {
println ' OK'
}
} else {
TeamCityIntegration.testFailed(testInfo.testName, "Exit code: ${testRes.returnCode}", "Exit code: ${testRes.returnCode}")
if (!TeamCityIntegration.writeOutput) {
println ' Failed'
println "ReHLDS testdemo ${testInfo.testName} playback failed. Exit status is ${testRes.returnCode}."
println "Dumping console output:"
println testRes.hldsConsoleOutput
}
failCount++
}
TeamCityIntegration.testStdOut(testInfo.testName, testRes.hldsConsoleOutput)
TeamCityIntegration.testFinished(testInfo.testName, testRes.duration)
}
TeamCityIntegration.suiteFinished("rehldsDemo.${testFor.name}")
if (failCount) {
throw new RuntimeException("Rehlds testdemos: failed ${failCount} tests")
}
}
}

View File

@ -1,34 +0,0 @@
package gradlecpp
import org.apache.velocity.Template
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.Velocity
class VelocityUtils {
static {
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
p.setProperty("class.resource.loader.path", "");
p.setProperty("input.encoding", "UTF-8");
p.setProperty("output.encoding", "UTF-8");
Velocity.init(p);
}
static String renderTemplate(File tplFile, Map<String, ? extends Object> ctx) {
Template tpl = Velocity.getTemplate(tplFile.absolutePath)
if (!tpl) {
throw new RuntimeException("Failed to load velocity template ${tplFile.absolutePath}: not found")
}
def velocityContext = new VelocityContext(ctx)
def sw = new StringWriter()
tpl.merge(velocityContext, sw)
return sw.toString()
}
}

View File

@ -1,84 +0,0 @@
package gradlecpp.teamcity
import groovy.transform.CompileStatic
class TeamCityIntegration {
static final String flowId = System.getenv('TEAMCITY_PROCESS_FLOW_ID')
static final boolean underTeamcity = System.getenv('TEAMCITY_PROJECT_NAME')
static boolean writeOutput = underTeamcity
@CompileStatic
private static String escape(String s) {
StringBuilder sb = new StringBuilder((int)(s.length() * 1.2));
for (char c in s.chars) {
switch (c) {
case '\n': sb.append('|n'); break;
case '\r': sb.append('|r'); break;
case '\'': sb.append('|\''); break;
case '|': sb.append('||'); break;
case ']': sb.append('|]'); break;
default: sb.append(c);
}
}
return sb.toString()
}
@CompileStatic
static void writeMessage(String name, Map params) {
if (!writeOutput) return
StringBuilder sb = new StringBuilder()
sb.append('##teamcity[').append(name)
params.each { e ->
if (e.value != null) {
sb.append(' ').append('' + e.key).append('=\'').append(escape('' + e.value)).append('\'')
}
}
sb.append(']')
println sb.toString()
}
static void suiteStarted(String suiteName) {
writeMessage('testSuiteStarted', [name: suiteName, flowId: flowId ?: null])
}
static void suiteFinished(String suiteName) {
writeMessage('testSuiteFinished', [name: suiteName, flowId: flowId ?: null])
}
static void testStarted(String testName) {
writeMessage('testStarted', [name: testName, flowId: flowId ?: null])
}
static void testStdOut(String testName, String output) {
writeMessage('testStdOut', [name: testName, out: output, flowId: flowId ?: null])
}
static void testFinished(String testName, long durationMs) {
writeMessage('testFinished', [
name: testName,
flowId: flowId ?: null,
duration: (durationMs >= 0) ? durationMs : null
])
}
static void testFailed(String testName, String message, String details) {
writeMessage('testFailed', [
name: testName,
flowId: flowId ?: null,
message: message,
details: details
])
}
static void testIgnored(String testName, String message) {
writeMessage('testIgnored', [
name: testName,
flowId: flowId ?: null,
message: message,
])
}
}

View File

@ -1,81 +0,0 @@
package rehlds.testdemo
import dirsync.builder.FileSystemTreeBuilder
import dirsync.merger.FileTreeComparator
import dirsync.merger.FileTreeDiffApplier
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FSMapper
import dirsync.model.tree.ZipData
import dirsync.model.tree.ZipTreeMapper
class RehldsDemoRunner {
ZipTreeMapper rehldsImage = new ZipTreeMapper()
File rootDir
DirectoryNode<ZipData> engineImageTree
Closure postExtract
static class TestResult {
boolean success
int returnCode
String hldsConsoleOutput
long duration
}
RehldsDemoRunner(Collection<File> engineImageZips, File rootDir, Closure postExtract) {
this.rootDir = rootDir
engineImageZips.each { f ->
rehldsImage.addZipArchive(f.absolutePath)
}
engineImageTree = rehldsImage.buildFileTree()
this.postExtract = postExtract
}
void prepareEngine() {
def existingTree = FileSystemTreeBuilder.buildFileSystemTree(rootDir)
def cmds = FileTreeComparator.mergeTrees(engineImageTree, existingTree)
FSMapper fsMapper = new FSMapper(rootDir)
FileTreeDiffApplier.applyDiffs(cmds, rehldsImage, fsMapper)
if (postExtract != null) {
postExtract.run()
}
}
TestResult runTest(RehldsTestInfo info, File testLogDir) {
long startTime = System.currentTimeMillis()
prepareEngine()
def outPath = new File(testLogDir, "${info.testName}_run.log")
def cmdParams = []
cmdParams << new File(rootDir, 'hlds.exe').absolutePath
cmdParams.addAll(info.hldsArgs)
if (info.rehldsExtraArgs) {
cmdParams.addAll(info.rehldsExtraArgs)
}
cmdParams << '--rehlds-test-play' << info.testBinFile.absolutePath
def pb = new ProcessBuilder(cmdParams).redirectErrorStream(true).directory(rootDir)
def sout = new StringBuffer()
def p = pb.start()
p.consumeProcessOutput(sout, sout)
p.waitForOrKill(info.timeoutSeconds * 1000)
int exitVal = p.exitValue()
outPath.withWriter('UTF-8') { writer ->
writer.write(sout.toString())
}
long endTime = System.currentTimeMillis()
return new TestResult(
success: (exitVal == 777),
returnCode: exitVal,
hldsConsoleOutput: sout.toString(),
duration: endTime - startTime
)
}
}

View File

@ -1,9 +0,0 @@
package rehlds.testdemo
class RehldsTestInfo {
String testName
List<String> hldsArgs
String rehldsExtraArgs
int timeoutSeconds
File testBinFile
}

View File

@ -1,63 +0,0 @@
package rehlds.testdemo
import groovy.util.slurpersupport.GPathResult
import org.apache.commons.io.IOUtils
import java.util.zip.ZipFile
class RehldsTestParser {
static final String REHLDS_TEST_METAINFO_FILE = 'rehlds_test_metainfo.xml'
static RehldsTestInfo parseTestInfo(File testArchive) {
def zf = new ZipFile(testArchive);
try {
def metaInfoEntry = zf.getEntry(REHLDS_TEST_METAINFO_FILE)
if (metaInfoEntry == null) {
throw new RuntimeException("Unable to open ${REHLDS_TEST_METAINFO_FILE} in ${testArchive.absolutePath}")
}
GPathResult metaInfo = null
zf.getInputStream(metaInfoEntry).withStream { InputStream ins ->
metaInfo = new XmlSlurper().parse(ins)
}
RehldsTestInfo testInfo = new RehldsTestInfo(
testName: metaInfo.name.text(),
hldsArgs: metaInfo.runArgs.arg.list().collect { it.text().trim() },
timeoutSeconds: metaInfo.timeout.text() as int
)
//validate testInfo
if (!testInfo.testName) {
throw new RuntimeException("Error parsing ${testArchive.absolutePath}: test name is not specified")
}
if (!testInfo.hldsArgs) {
throw new RuntimeException("Error parsing ${testArchive.absolutePath}: run arguments are not specified")
}
if (testInfo.timeoutSeconds <= 0) {
throw new RuntimeException("Error parsing ${testArchive.absolutePath}: bad timeout")
}
def testBinName = testInfo.testName + '.bin'
def testBinEntry = zf.getEntry(testBinName)
if (testBinEntry == null) {
throw new RuntimeException("Error parsing ${testArchive.absolutePath}: test binary ${testBinName} not found inside archive")
}
testInfo.testBinFile = File.createTempFile(testBinName, 'rehlds')
testInfo.testBinFile.deleteOnExit()
zf.getInputStream(testBinEntry).withStream { InputStream ins ->
testInfo.testBinFile.withOutputStream { OutputStream os ->
IOUtils.copy(ins, os)
}
}
return testInfo
} finally {
try { zf.close() } catch (Exception ignored) { }
}
}
}

View File

@ -1,16 +0,0 @@
package versioning
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.joda.time.DateTime
@CompileStatic @TypeChecked
class GitInfo {
boolean localChanges
DateTime commitDate
String branch
String tag
String commitSHA
String commitURL
Integer commitCount
}

View File

@ -1,126 +0,0 @@
package versioning
import java.util.Set;
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.lib.ObjectId
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.lib.StoredConfig
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
@CompileStatic @TypeChecked
class GitVersioner {
static GitInfo versionForDir(String dir) {
versionForDir(new File(dir))
}
static int getCountCommit(Repository repo) {
Iterable<RevCommit> commits = Git.wrap(repo).log().call()
int count = 0;
commits.each {
count++;
}
return count;
}
static String prepareUrlToCommits(String url) {
if (url == null) {
// default remote url
return "https://github.com/dreamstalker/rehlds/commit/";
}
StringBuilder sb = new StringBuilder();
String childPath;
int pos = url.indexOf('@');
if (pos != -1) {
childPath = url.substring(pos + 1, url.lastIndexOf('.git')).replace(':', '/');
sb.append('https://');
} else {
pos = url.lastIndexOf('.git');
childPath = (pos == -1) ? url : url.substring(0, pos);
}
// support for different links to history of commits
if (url.indexOf('bitbucket.org') != -1) {
sb.append(childPath).append('/commits/');
} else {
sb.append(childPath).append('/commit/');
}
return sb.toString();
}
// check uncommited changes
static boolean getUncommittedChanges(Repository repo) {
Git git = new Git(repo);
Status status = git.status().call();
Set<String> uncommittedChanges = status.getUncommittedChanges();
for(String uncommitted : uncommittedChanges) {
return true;
}
return false;
}
static GitInfo versionForDir(File dir) {
FileRepositoryBuilder builder = new FileRepositoryBuilder()
Repository repo = builder.setWorkTree(dir)
.findGitDir()
.build()
ObjectId head = repo.resolve('HEAD')
if (!head) {
return null
}
final StoredConfig cfg = repo.getConfig();
def commit = new RevWalk(repo).parseCommit(head)
if (!commit) {
throw new RuntimeException("Can't find last commit.")
}
def localChanges = getUncommittedChanges(repo);
def commitDate = new DateTime(1000L * commit.commitTime, DateTimeZone.UTC);
if (localChanges) {
commitDate = new DateTime();
}
def branch = repo.getBranch()
String url = null;
String remote_name = cfg.getString("branch", branch, "remote");
if (remote_name == null) {
for (String remotes : cfg.getSubsections("remote")) {
if (url != null) {
println 'Found a second remote: (' + remotes + '), url: (' + cfg.getString("remote", remotes, "url") + ')'
continue;
}
url = cfg.getString("remote", remotes, "url");
}
} else {
url = cfg.getString("remote", remote_name, "url");
}
String commitURL = prepareUrlToCommits(url);
String tag = repo.tags.find { kv -> kv.value.objectId == commit.id }?.key
String commitSHA = commit.getId().abbreviate(7).name();
return new GitInfo(
localChanges: localChanges,
commitDate: commitDate,
branch: branch,
tag: tag,
commitSHA: commitSHA,
commitURL: commitURL,
commitCount: getCountCommit(repo)
)
}
}

View File

@ -1,56 +0,0 @@
package versioning
import groovy.transform.CompileStatic
import groovy.transform.ToString
import groovy.transform.TypeChecked
import org.joda.time.format.DateTimeFormat
import org.joda.time.DateTime
@CompileStatic @TypeChecked
@ToString(includeNames = true)
class RehldsVersionInfo {
int majorVersion
int minorVersion
Integer maintenanceVersion
String suffix
boolean localChanges
DateTime commitDate
String commitSHA
String commitURL
Integer commitCount
String asMavenVersion(boolean extra = true) {
StringBuilder sb = new StringBuilder()
sb.append(majorVersion).append('.' + minorVersion);
if (maintenanceVersion != null) {
sb.append('.' + maintenanceVersion);
}
if (commitCount != null) {
sb.append('.' + commitCount)
}
if (extra && suffix) {
sb.append('-' + suffix)
}
// do mark for this build like a modified version
if (extra && localChanges) {
sb.append('+m');
}
return sb.toString()
}
String asCommitDate() {
String pattern = "MMM d yyyy";
if (commitDate.getDayOfMonth() >= 10) {
pattern = "MMM d yyyy";
}
return DateTimeFormat.forPattern(pattern).withLocale(Locale.ENGLISH).print(commitDate);
}
String asCommitTime() {
return DateTimeFormat.forPattern('HH:mm:ss').withLocale(Locale.ENGLISH).print(commitDate);
}
}

View File

@ -1,44 +0,0 @@
package dirsync.builder
import org.junit.Test
import java.io.File
import dirsync.builder.ZipTreeBuilder
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream;
import static org.junit.Assert.*;
class ZipTreeBuilderTest {
@Test
void test1() {
File zipFile = File.createTempFile('ZipTreeBuilderTest', 'zip')
zipFile.deleteOnExit()
new ZipOutputStream(zipFile.newDataOutputStream()).withStream { ZipOutputStream zos ->
zos.putNextEntry(new ZipEntry('aRootFile1.txt'))
zos.write(65) //'A'
zos.putNextEntry(new ZipEntry('dir1/'))
zos.putNextEntry(new ZipEntry('dir1/dir2/'))
zos.putNextEntry(new ZipEntry('dir1/dir2/d1d2f1.txt'))
zos.write(65); zos.write(66) //'AB'
zos.putNextEntry(new ZipEntry('dir1/d1f1.txt'))
zos.write(65); zos.write(66); zos.write(67) //'ABC'
zos.putNextEntry(new ZipEntry('zRootFile2.txt'))
zos.write(65); zos.write(66); zos.write(67); zos.write(68) //'ABCD'
}
ZipFile zf = new ZipFile(zipFile.absolutePath)
def tree = ZipTreeBuilder.buildForZipArchive(zipFile.absolutePath, zf)
assert tree.childNodes.size() == 3
}
}

25
dep/bzip2/CMakeLists.txt Normal file
View File

@ -0,0 +1,25 @@
cmake_minimum_required(VERSION 3.1)
project(bzip2 C)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g0 -O1 -fno-stack-protector")
set(BZIP2_SRCS
"src/blocksort.c"
"src/bzlib.c"
"src/compress.c"
"src/crctable.c"
"src/decompress.c"
"src/huffman.c"
"src/precompiled.c"
"src/randtable.c"
"src/bzlib_private.h"
)
include_directories(
"include"
)
add_library(bzip2 STATIC ${BZIP2_SRCS})
set_target_properties(bzip2 PROPERTIES
COMPILE_FLAGS "-m32"
)

View File

@ -1,79 +0,0 @@
import org.doomedsociety.gradlecpp.cfg.ToolchainConfigUtils
import org.doomedsociety.gradlecpp.msvc.MsvcToolchainConfig
import org.doomedsociety.gradlecpp.toolchain.icc.Icc
import org.doomedsociety.gradlecpp.toolchain.icc.IccCompilerPlugin
import org.doomedsociety.gradlecpp.gcc.GccToolchainConfig
import org.gradle.nativeplatform.NativeBinarySpec
import org.gradle.nativeplatform.NativeLibrarySpec
import org.gradle.nativeplatform.toolchain.VisualCpp
apply plugin: 'c'
apply plugin: IccCompilerPlugin
apply plugin: GccCompilerPlugin
void setupToolchain(NativeBinarySpec b) {
def cfg = rootProject.createToolchainConfig(b)
if (cfg instanceof MsvcToolchainConfig) {
cfg.compilerOptions.pchConfig = new MsvcToolchainConfig.PrecompiledHeadersConfig(
enabled: true,
pchHeader: 'bzlib_private.h',
pchSourceSet: 'bz2_pch'
)
}
ToolchainConfigUtils.apply(project, cfg, b)
}
model {
buildTypes {
debug
release
}
platforms {
x86 {
architecture "x86"
}
}
toolChains {
visualCpp(VisualCpp)
if (project.hasProperty("useGcc")) {
gcc(Gcc)
} else {
icc(Icc)
}
}
components {
bzip2(NativeLibrarySpec) {
targetPlatform 'x86'
sources {
bz2_main(CSourceSet) {
source {
srcDir "src"
include "**/*.c"
exclude "precompiled.c"
}
exportedHeaders {
srcDir "include"
}
}
bz2_pch(CSourceSet) {
source {
srcDir "src"
include "precompiled.c"
}
exportedHeaders {
srcDir "include"
}
}
}
binaries.all { NativeBinarySpec b -> project.setupToolchain(b) }
}
}
}

View File

@ -5,10 +5,6 @@
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release Swds|Win32">
<Configuration>Release Swds</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
@ -39,16 +35,6 @@
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Swds|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '12.0'">v120</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '14.0'">v140</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '15.0'">v141</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '16.0'">v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
@ -58,9 +44,6 @@
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Swds|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
@ -97,25 +80,6 @@
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Swds|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(ProjectDir)..\include\</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeaderFile>bzlib_private.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
@ -129,7 +93,6 @@
<ClCompile Include="..\src\precompiled.c">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release Swds|Win32'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="..\src\randtable.c" />
</ItemGroup>

View File

@ -0,0 +1,25 @@
cmake_minimum_required(VERSION 3.1)
project(cppunitlite CXX)
add_library(cppunitlite STATIC)
target_sources(cppunitlite PRIVATE
src/Test.cpp
src/TestResult.cpp
src/TestRegistry.cpp
src/Assertions.cpp
src/MainAdapter.cpp
)
target_include_directories(cppunitlite PRIVATE
"${PROJECT_SOURCE_DIR}/src"
"${PROJECT_SOURCE_DIR}/include"
)
target_compile_definitions(cppunitlite PRIVATE
_GLIBCXX_USE_CXX11_ABI=0
)
target_compile_options(cppunitlite PRIVATE
-m32
)

View File

@ -1,64 +0,0 @@
import org.doomedsociety.gradlecpp.cfg.ToolchainConfigUtils
import org.doomedsociety.gradlecpp.msvc.MsvcToolchainConfig
import org.doomedsociety.gradlecpp.toolchain.icc.Icc
import org.doomedsociety.gradlecpp.toolchain.icc.IccCompilerPlugin
import org.doomedsociety.gradlecpp.gcc.GccToolchainConfig
import org.gradle.nativeplatform.NativeBinarySpec
import org.gradle.nativeplatform.NativeLibrarySpec
apply plugin: 'cpp'
apply plugin: IccCompilerPlugin
apply plugin: GccCompilerPlugin
void setupToolchain(NativeBinarySpec b) {
def cfg = rootProject.createToolchainConfig(b)
ToolchainConfigUtils.apply(project, cfg, b)
}
model {
buildTypes {
debug
release
}
platforms {
x86 {
architecture "x86"
}
}
toolChains {
visualCpp(VisualCpp)
if (project.hasProperty("useGcc")) {
gcc(Gcc)
} else {
icc(Icc)
}
}
components {
cppunitlite(NativeLibrarySpec) {
targetPlatform 'x86'
sources {
cppul_main(CppSourceSet) {
source {
srcDir "src"
include "**/*.cpp"
}
exportedHeaders {
srcDir "include"
}
}
}
binaries.all { NativeBinarySpec b ->
project.setupToolchain(b)
}
}
}
}

View File

@ -1,6 +1,6 @@
#pragma once
class GradleAdapter {
class MainAdapter {
public:
int writeAllTestsInfoToFile(const char* fname);
int runTest(const char* groupName, const char* testName);

View File

@ -20,7 +20,7 @@ public:
void setNext(Test *test);
Test *getNext () const;
void run(TestResult& result);
const char* getName() {
return name_.c_str();
}
@ -28,7 +28,7 @@ public:
const char* getGroup() {
return group_.c_str();
}
int getTimeout() {
return timeout_;
}
@ -47,7 +47,7 @@ protected:
{ public: testGroup##testName##Test () : Test (#testName , #testGroup , testTimeout) {} \
void runInternal (); } \
testGroup##testName##Instance; \
void testGroup##testName##Test::runInternal()
void testGroup##testName##Test::runInternal()

View File

@ -5,10 +5,6 @@
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release Swds|Win32">
<Configuration>Release Swds</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
@ -17,7 +13,7 @@
<ItemGroup>
<ClInclude Include="..\include\cppunitlite\Assertions.h" />
<ClInclude Include="..\include\cppunitlite\Failure.h" />
<ClInclude Include="..\include\cppunitlite\GradleAdapter.h" />
<ClInclude Include="..\include\cppunitlite\MainAdapter.h" />
<ClInclude Include="..\include\cppunitlite\Test.h" />
<ClInclude Include="..\include\cppunitlite\TestHarness.h" />
<ClInclude Include="..\include\cppunitlite\TestRegistry.h" />
@ -25,7 +21,7 @@
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\Assertions.cpp" />
<ClCompile Include="..\src\GradleAdapter.cpp" />
<ClCompile Include="..\src\MainAdapter.cpp" />
<ClCompile Include="..\src\Test.cpp" />
<ClCompile Include="..\src\TestRegistry.cpp" />
<ClCompile Include="..\src\TestResult.cpp" />
@ -55,16 +51,6 @@
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Swds|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '12.0'">v120</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '14.0'">v140</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '15.0'">v141</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '16.0'">v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
@ -74,9 +60,6 @@
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Swds|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
@ -115,26 +98,6 @@
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Swds|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalIncludeDirectories>$(ProjectDir)..\include\</AdditionalIncludeDirectories>
<TreatWarningAsError>false</TreatWarningAsError>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>

View File

@ -27,7 +27,7 @@
<ClInclude Include="..\include\cppunitlite\TestResult.h">
<Filter>include</Filter>
</ClInclude>
<ClInclude Include="..\include\cppunitlite\GradleAdapter.h">
<ClInclude Include="..\include\cppunitlite\MainAdapter.h">
<Filter>include</Filter>
</ClInclude>
</ItemGroup>
@ -44,7 +44,7 @@
<ClCompile Include="..\src\TestResult.cpp">
<Filter>src</Filter>
</ClCompile>
<ClCompile Include="..\src\GradleAdapter.cpp">
<ClCompile Include="..\src\MainAdapter.cpp">
<Filter>src</Filter>
</ClCompile>
</ItemGroup>

View File

@ -2,11 +2,11 @@
#include <stdlib.h>
#include <string.h>
#include "cppunitlite/GradleAdapter.h"
#include "cppunitlite/MainAdapter.h"
#include "cppunitlite/Test.h"
#include "cppunitlite/TestRegistry.h"
int GradleAdapter::writeAllTestsInfoToFile(const char* fname) {
int MainAdapter::writeAllTestsInfoToFile(const char* fname) {
FILE* outFile = fopen(fname, "w");
if (outFile == NULL) {
return 1;
@ -33,7 +33,7 @@ int GradleAdapter::writeAllTestsInfoToFile(const char* fname) {
return 0;
}
int GradleAdapter::runTest(const char* groupName, const char* testName) {
int MainAdapter::runTest(const char* groupName, const char* testName) {
Test* curTest = TestRegistry::getFirstTest();
while (curTest != NULL) {
if (!strcmp(groupName, curTest->getGroup()) && !strcmp(testName, curTest->getName())) {
@ -61,7 +61,7 @@ int GradleAdapter::runTest(const char* groupName, const char* testName) {
}
}
int GradleAdapter::runGroup(const char* groupName) {
int MainAdapter::runGroup(const char* groupName) {
Test* curTest = TestRegistry::getFirstTest();
int ranTests = 0;
int warnTest = 0;
@ -101,7 +101,7 @@ int GradleAdapter::runGroup(const char* groupName) {
return 0;
}
int GradleAdapter::runAllTests() {
int MainAdapter::runAllTests() {
Test* curTest = TestRegistry::getFirstTest();
int ranTests = 0;
int warnTest = 0;
@ -131,7 +131,7 @@ int GradleAdapter::runAllTests() {
return 0;
}
int GradleAdapter::testsEntryPoint(int argc, char* argv[]) {
int MainAdapter::testsEntryPoint(int argc, char* argv[]) {
if (argc < 2 || !strcmp(argv[1], "-all")) {
return runAllTests();
}

View File

@ -5,10 +5,11 @@
#include "cppunitlite/Failure.h"
#include <exception>
#include <iostream>
#include <sstream>
Test::Test (const char* testName, const char* testGroup, int timeout)
Test::Test (const char* testName, const char* testGroup, int timeout)
: name_ (testName), group_ (testGroup), timeout_(timeout)
{
next_ = NULL;
@ -23,13 +24,14 @@ Test *Test::getNext() const
void Test::setNext(Test *test)
{
{
next_ = test;
}
void Test::run(TestResult &result) {
try {
runInternal();
std::cout << "Test::run() > " << group_ << "::" << name_ << " Passed" << std::endl;
} catch (TestFailException &e) {
result.addFailure(Failure(e, name_));
} catch (std::exception &e) {

View File

@ -1,35 +0,0 @@
apply plugin: 'java'
apply plugin: 'groovy'
group = 'org.rehlds.flightrec'
version = rootProject.version
sourceCompatibility = '1.7'
targetCompatibility = '1.7'
repositories {
mavenCentral()
}
dependencies {
testCompile 'org.codehaus.groovy:groovy-all:2.4.5'
testCompile "junit:junit:4.12"
compile project(':flightrec/decoder_api')
}
task uberjar(type: Jar, dependsOn: ['check', ':flightrec/decoder_api:build']) {
from files(sourceSets.main.output.classesDir)
from { configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } }
exclude('META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.SF', 'META-INF/*.LIST') //exclude all signing stuff
manifest {
attributes 'Main-Class': 'org.rehlds.flightrec.main.FlightRecorder'
attributes 'Implementation-Vendor': 'Sun Microsystems, Inc'
attributes 'Implementation-Title': 'Java Runtime Environment'
attributes 'Implementation-Version': '1.7.0'
}
}
tasks.withType(AbstractCompile) {
options.encoding = 'UTF-8'
}

View File

@ -1,47 +0,0 @@
@if "%DEBUG%" == "" @echo off
setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
set CMD_LINE_ARGS=%*
"%JAVA_EXE%" -jar "%DIRNAME%/decoder.jar" %CMD_LINE_ARGS%
:end
goto mainEnd
:fail
exit /b 1
:mainEnd
endlocal

View File

@ -1,156 +0,0 @@
// Copyright 2011 Google Inc. All rights reserved.
package com.google.cloud;
import java.util.zip.Checksum;
/**
* This class generates a CRC32C checksum, defined by rfc3720 section B.4.
*
*
*/
public final class Crc32c implements Checksum {
private static final long[] CRC_TABLE = {
0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4,
0xc79a971f, 0x35f1141c, 0x26a1e7e8, 0xd4ca64eb,
0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b,
0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24,
0x105ec76f, 0xe235446c, 0xf165b798, 0x030e349b,
0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384,
0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54,
0x5d1d08bf, 0xaf768bbc, 0xbc267848, 0x4e4dfb4b,
0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a,
0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35,
0xaa64d611, 0x580f5512, 0x4b5fa6e6, 0xb93425e5,
0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa,
0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45,
0xf779deae, 0x05125dad, 0x1642ae59, 0xe4292d5a,
0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a,
0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595,
0x417b1dbc, 0xb3109ebf, 0xa0406d4b, 0x522bee48,
0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957,
0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687,
0x0c38d26c, 0xfe53516f, 0xed03a29b, 0x1f682198,
0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927,
0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38,
0xdbfc821c, 0x2997011f, 0x3ac7f2eb, 0xc8ac71e8,
0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7,
0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096,
0xa65c047d, 0x5437877e, 0x4767748a, 0xb50cf789,
0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859,
0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46,
0x7198540d, 0x83f3d70e, 0x90a324fa, 0x62c8a7f9,
0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6,
0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36,
0x3cdb9bdd, 0xceb018de, 0xdde0eb2a, 0x2f8b6829,
0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c,
0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93,
0x082f63b7, 0xfa44e0b4, 0xe9141340, 0x1b7f9043,
0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c,
0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3,
0x55326b08, 0xa759e80b, 0xb4091bff, 0x466298fc,
0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c,
0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033,
0xa24bb5a6, 0x502036a5, 0x4370c551, 0xb11b4652,
0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d,
0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d,
0xef087a76, 0x1d63f975, 0x0e330a81, 0xfc588982,
0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d,
0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622,
0x38cc2a06, 0xcaa7a905, 0xd9f75af1, 0x2b9cd9f2,
0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed,
0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530,
0x0417b1db, 0xf67c32d8, 0xe52cc12c, 0x1747422f,
0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff,
0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0,
0xd3d3e1ab, 0x21b862a8, 0x32e8915c, 0xc083125f,
0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540,
0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90,
0x9e902e7b, 0x6cfbad78, 0x7fab5e8c, 0x8dc0dd8f,
0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee,
0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1,
0x69e9f0d5, 0x9b8273d6, 0x88d28022, 0x7ab90321,
0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e,
0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81,
0x34f4f86a, 0xc69f7b69, 0xd5cf889d, 0x27a40b9e,
0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e,
0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351
};
private static final long LONG_MASK = 0xffffffffL;
private static final long BYTE_MASK = 0xff;
private long crc;
public Crc32c() {
crc = 0;
}
/**
* Updates the checksum with a new byte.
* @param b the new byte.
*/
@Override
public void update(int b) {
long newCrc = crc;
newCrc = updateByte((byte) b, newCrc);
crc = newCrc;
}
/**
* Updates the checksum with an array of bytes.
* @param bArray the array of bytes.
* @param off the offset into the array where the update should begin.
* @param len the length of data to examine.
*/
@Override
public void update(byte[] bArray, int off, int len) {
long newCrc = crc;
for (int i = off; i < off + len; i++) {
newCrc = updateByte(bArray[i], newCrc);
}
crc = newCrc;
}
public void update(byte[] bArray) {
update(bArray, 0, bArray.length);
}
/**
* Returns the value of the checksum.
* @return the long representation of the checksum (high bits set to zero).
*/
@Override
public long getValue() {
return crc;
}
/**
* Returns the value of the checksum.
* @return the 4-byte array representation of the checksum in network byte order (big endian).
*/
public byte[] getValueAsBytes() {
long value = crc;
byte[] result = new byte[4];
for (int i = 3; i >= 0; i--) {
result[i] = (byte) (value & 0xffL);
value >>= 8;
}
return result;
}
/**
* Resets the crc.
*/
@Override
public void reset() {
crc = 0;
}
private long updateByte(byte newByte, long crc) {
byte b = (byte) (newByte & BYTE_MASK);
int index = (int) ((crc ^ b) & BYTE_MASK);
return (CRC_TABLE[index] ^ (crc >> 8)) & LONG_MASK;
}
}

View File

@ -1,14 +0,0 @@
package org.rehlds.flightrec;
public class Consts {
public final static String META_HEADER_SIG_STR = "REHLDS_FLIGHTREC_META";
public final static String DATA_HEADER_SIG_STR = "REHLDS_FLIGHTREC_DATA";
public static byte[] META_HEADER_SIG_BYTES = (META_HEADER_SIG_STR + META_HEADER_SIG_STR + META_HEADER_SIG_STR + ":").getBytes();
public static byte[] DATA_HEADER_SIG_BYTES = (DATA_HEADER_SIG_STR + DATA_HEADER_SIG_STR + DATA_HEADER_SIG_STR + ":").getBytes();
public static int META_HEADER_SIZE = 128;
public static int DATA_HEADER_SIZE = 128;
public static int MAX_HEADER_SIZE = Math.max(META_HEADER_SIZE, DATA_HEADER_SIZE);
}

View File

@ -1,22 +0,0 @@
package org.rehlds.flightrec.decoders.rehlds;
import org.rehlds.flightrec.api.DecodedExtraData;
import org.rehlds.flightrec.api.FlightrecMessage;
import org.rehlds.flightrec.api.FlightrecMessageType;
import org.rehlds.flightrec.api.MessageDecoder;
import org.rehlds.flightrec.api.util.UtilSizeBuf;
public class AllocEntPrivateDataV1Decoder implements MessageDecoder {
@Override
public FlightrecMessageType getMessageType() {
return new FlightrecMessageType("rehlds", "AllocEntPrivateData", 1, false);
}
@Override
public DecodedExtraData decode(FlightrecMessage msg) {
UtilSizeBuf sb = msg.getDataSizebuf();
long ptr = sb.readUInt32();
return DecodedExtraData.create("pPrivData", "0x" + Long.toHexString(ptr));
}
}

View File

@ -1,22 +0,0 @@
package org.rehlds.flightrec.decoders.rehlds;
import org.rehlds.flightrec.api.DecodedExtraData;
import org.rehlds.flightrec.api.FlightrecMessage;
import org.rehlds.flightrec.api.FlightrecMessageType;
import org.rehlds.flightrec.api.MessageDecoder;
import org.rehlds.flightrec.api.util.UtilSizeBuf;
public class AllocEntPrivateDataV2Decoder implements MessageDecoder {
@Override
public FlightrecMessageType getMessageType() {
return new FlightrecMessageType("rehlds", "AllocEntPrivateData", 2, false);
}
@Override
public DecodedExtraData decode(FlightrecMessage msg) {
UtilSizeBuf sb = msg.getDataSizebuf();
long ptr = sb.readUInt32();
long size = sb.readUInt32();
return DecodedExtraData.create("pPrivData", "0x" + Long.toHexString(ptr), "size", "" + size);
}
}

View File

@ -1,30 +0,0 @@
package org.rehlds.flightrec.decoders.rehlds;
import org.rehlds.flightrec.api.DecodedExtraData;
import org.rehlds.flightrec.api.FlightrecMessage;
import org.rehlds.flightrec.api.FlightrecMessageType;
import org.rehlds.flightrec.api.MessageDecoder;
import org.rehlds.flightrec.api.util.UtilSizeBuf;
public class FrameV1Decoder implements MessageDecoder {
@Override
public FlightrecMessageType getMessageType() {
return new FlightrecMessageType("rehlds", "Frame", 1, true);
}
DecodedExtraData decodeStart(UtilSizeBuf sb) {
double startTime = sb.readDouble();
return DecodedExtraData.create("startTime", "" + startTime);
}
DecodedExtraData decodeEnd(UtilSizeBuf sb) {
return DecodedExtraData.EMPTY;
}
@Override
public DecodedExtraData decode(FlightrecMessage msg) {
UtilSizeBuf sb = msg.getDataSizebuf();
return msg.isEnterMessage() ? decodeStart(sb) : decodeEnd(sb);
}
}

View File

@ -1,32 +0,0 @@
package org.rehlds.flightrec.decoders.rehlds;
import org.rehlds.flightrec.api.DecodedExtraData;
import org.rehlds.flightrec.api.FlightrecMessage;
import org.rehlds.flightrec.api.FlightrecMessageType;
import org.rehlds.flightrec.api.MessageDecoder;
import org.rehlds.flightrec.api.util.UtilSizeBuf;
public class FrameV2Decoder implements MessageDecoder {
@Override
public FlightrecMessageType getMessageType() {
return new FlightrecMessageType("rehlds", "Frame", 2, true);
}
DecodedExtraData decodeStart(UtilSizeBuf sb) {
long frameId = sb.readInt64();
double startTime = sb.readDouble();
return DecodedExtraData.create("frameId", "" + frameId, "startTime", "" + startTime);
}
DecodedExtraData decodeEnd(UtilSizeBuf sb) {
long frameId = sb.readInt64();
return DecodedExtraData.create("frameId", "" + frameId);
}
@Override
public DecodedExtraData decode(FlightrecMessage msg) {
UtilSizeBuf sb = msg.getDataSizebuf();
return msg.isEnterMessage() ? decodeStart(sb) : decodeEnd(sb);
}
}

View File

@ -1,21 +0,0 @@
package org.rehlds.flightrec.decoders.rehlds;
import org.rehlds.flightrec.api.DecodedExtraData;
import org.rehlds.flightrec.api.FlightrecMessage;
import org.rehlds.flightrec.api.FlightrecMessageType;
import org.rehlds.flightrec.api.MessageDecoder;
import org.rehlds.flightrec.api.util.UtilSizeBuf;
public class FreeEntPrivateDataV1Decoder implements MessageDecoder {
@Override
public FlightrecMessageType getMessageType() {
return new FlightrecMessageType("rehlds", "FreeEntPrivateData", 1, false);
}
@Override
public DecodedExtraData decode(FlightrecMessage msg) {
UtilSizeBuf sb = msg.getDataSizebuf();
long ptr = sb.readUInt32();
return DecodedExtraData.create("pPrivData", "0x" + Long.toHexString(ptr));
}
}

View File

@ -1,22 +0,0 @@
package org.rehlds.flightrec.decoders.rehlds;
import org.rehlds.flightrec.api.DecodedExtraData;
import org.rehlds.flightrec.api.FlightrecMessage;
import org.rehlds.flightrec.api.FlightrecMessageType;
import org.rehlds.flightrec.api.MessageDecoder;
import org.rehlds.flightrec.api.util.UtilSizeBuf;
public class LogV1Decoder implements MessageDecoder {
@Override
public FlightrecMessageType getMessageType() {
return new FlightrecMessageType("rehlds", "Log", 1, false);
}
@Override
public DecodedExtraData decode(FlightrecMessage msg) {
UtilSizeBuf sb = msg.getDataSizebuf();
String prefix = sb.readString();
String message = sb.readString();
return DecodedExtraData.create("prefix", prefix, "message", message);
}
}

View File

@ -1,18 +0,0 @@
package org.rehlds.flightrec.decoders.rehlds;
import org.rehlds.flightrec.api.SimpleDecoderModule;
public class RehldsDecodersModule extends SimpleDecoderModule {
public RehldsDecodersModule() {
super("Rehlds decoders (built-in)", "0.2");
registerDecoder(new FrameV1Decoder());
registerDecoder(new FreeEntPrivateDataV1Decoder());
registerDecoder(new AllocEntPrivateDataV1Decoder());
registerDecoder(new FrameV2Decoder());
registerDecoder(new LogV1Decoder());
registerDecoder(new AllocEntPrivateDataV2Decoder());
}
}

View File

@ -1,9 +0,0 @@
package org.rehlds.flightrec.filescan;
import java.util.ArrayList;
import java.util.List;
public class FileScanResult {
public List<HeaderScanResult> metaHeaders = new ArrayList<>();
public List<HeaderScanResult> dataHeaders = new ArrayList<>();
}

View File

@ -1,100 +0,0 @@
package org.rehlds.flightrec.filescan;
import com.google.cloud.Crc32c;
import org.rehlds.flightrec.api.util.UtilByteBuffer;
import org.rehlds.flightrec.api.util.UtilSizeBuf;
import static org.rehlds.flightrec.Consts.*;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.List;
public class FlightRecFileScanner {
RandomAccessFile file;
long fileLen;
FileScanResult scanRes = new FileScanResult();
private byte readBuf[] = new byte[65536];
private byte header[] = new byte[MAX_HEADER_SIZE];
private UtilSizeBuf headerSBuf = new UtilSizeBuf("header", new UtilByteBuffer(header), 0, header.length);
private FlightRecFileScanner(RandomAccessFile file) throws IOException {
this.file = file;
this.fileLen = file.length();
}
private void examineHeader(byte[] data, int size, int pos) throws IOException {
if (pos + MAX_HEADER_SIZE < size) {
System.arraycopy(data, pos, header, 0, MAX_HEADER_SIZE);
} else {
return; //will be read in next iteration
}
headerSBuf.reset();
String matchedType = null;
if (Arrays.equals(META_HEADER_SIG_BYTES, Arrays.copyOfRange(header, 0, META_HEADER_SIG_BYTES.length))) {
matchedType = META_HEADER_SIG_STR;
headerSBuf.skip(META_HEADER_SIG_BYTES.length);
} else if (Arrays.equals(DATA_HEADER_SIG_BYTES, Arrays.copyOfRange(header, 0, DATA_HEADER_SIG_BYTES.length))) {
matchedType = DATA_HEADER_SIG_STR;
headerSBuf.skip(DATA_HEADER_SIG_BYTES.length);
}
if (matchedType == null) {
return;
}
List<HeaderScanResult> resList = (matchedType.equals(META_HEADER_SIG_STR)) ? scanRes.metaHeaders : scanRes.dataHeaders;
int version = headerSBuf.readInt32();
int allocSize = headerSBuf.readInt32();
Crc32c crc32 = new Crc32c();
crc32.update(header, 0, headerSBuf.tell());
long calculatedChecksum = crc32.getValue();
long bufChecksum = headerSBuf.readUInt32();
if (calculatedChecksum != bufChecksum) {
resList.add(new HeaderScanResult(file.getFilePointer() - size + pos, allocSize, false, "Checksum mismatch", version));
return;
}
long endPos = file.getFilePointer() - size + pos + allocSize;
if (endPos > file.length()) {
resList.add(new HeaderScanResult(file.getFilePointer() - size + pos, allocSize, false, "Regions partially lays outside the file", version));
return;
}
resList.add(new HeaderScanResult(file.getFilePointer() - size + pos, allocSize, true, null, version));
}
private void scanForHeaders(byte[] data, int size) throws IOException {
int maxHeaderSize = Math.max(META_HEADER_SIG_STR.length(), DATA_HEADER_SIG_STR.length());
for (int i = 0; i < size - maxHeaderSize; i++) {
if (data[i + 15] == META_HEADER_SIG_BYTES[15] && data[i + 16] == META_HEADER_SIG_BYTES[16] && data[i + 17] == META_HEADER_SIG_BYTES[17] && data[i + 18] == META_HEADER_SIG_BYTES[18]) {
examineHeader(data, size, i);
} else if (data[i + 15] == DATA_HEADER_SIG_BYTES[15] && data[i + 16] == DATA_HEADER_SIG_BYTES[16] && data[i + 17] == DATA_HEADER_SIG_BYTES[17] && data[i + 18] == DATA_HEADER_SIG_BYTES[18]) {
examineHeader(data, size, i);
}
}
}
private void doScan() throws IOException {
file.seek(0);
int read;
while (-1 != (read = file.read(readBuf))) {
scanForHeaders(readBuf, read);
if (read == readBuf.length) {
file.seek(file.getFilePointer() - MAX_HEADER_SIZE * 2);
}
}
}
public static FileScanResult scan(RandomAccessFile file) throws IOException {
FlightRecFileScanner scanner = new FlightRecFileScanner(file);
scanner.doScan();
return scanner.scanRes;
}
}

View File

@ -1,17 +0,0 @@
package org.rehlds.flightrec.filescan;
public class HeaderScanResult {
public long pos;
public int len;
public boolean valid;
public String error;
public int version;
public HeaderScanResult(long pos, int len, boolean valid, String error, int version) {
this.pos = pos;
this.len = len;
this.valid = valid;
this.error = error;
this.version = version;
}
}

View File

@ -1,12 +0,0 @@
package org.rehlds.flightrec.logparser;
public class DataHeader {
public int prevItrLastPos;
public DataHeader(int prevItrLastPos) {
this.prevItrLastPos = prevItrLastPos;
}
public DataHeader() {
}
}

View File

@ -1,179 +0,0 @@
package org.rehlds.flightrec.logparser;
import org.rehlds.flightrec.api.EntranceKind;
import org.rehlds.flightrec.api.FlightrecMessage;
import org.rehlds.flightrec.api.FlightrecMessageDef;
import org.rehlds.flightrec.api.FlightrecMessageType;
import org.rehlds.flightrec.filescan.HeaderScanResult;
import org.rehlds.flightrec.api.util.UtilByteBuffer;
import org.rehlds.flightrec.api.util.UtilSizeBuf;
import static org.rehlds.flightrec.Consts.*;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;
public class FlightLogParser {
UtilByteBuffer metaRegion;
UtilByteBuffer dataRegion;
MetaHeader metaHeader;
RecorderState recorderState;
DataHeader dataHeader;
Map<Integer, FlightrecMessageType> msgTypes = new HashMap<>();
List<FlightrecMessage> messages = new ArrayList<>();
void parseMessageDefinition(UtilSizeBuf sbuf) {
int msgId = sbuf.readUInt16();
String module = sbuf.readString();
String messageName = sbuf.readString();
long msgVersion = sbuf.readUInt32();
boolean inOut = sbuf.readBool();
FlightrecMessageDef msgDef = new FlightrecMessageDef(module, messageName, msgVersion, inOut, msgId);
if (msgTypes.containsKey(msgId)) {
System.out.println("Duplicate message id: " + msgTypes.get(msgId) + " and " + msgDef);
}
msgTypes.put(msgId, msgDef.msgType);
}
void parseMetaRegion() {
metaHeader = new MetaHeader();
UtilSizeBuf metaSBuf = new UtilSizeBuf("meta region", metaRegion);
metaSBuf.skip(META_HEADER_SIG_BYTES.length); //skip signature
metaSBuf.readInt32(); //version
metaSBuf.readInt32(); //allocSize
metaSBuf.readInt32(); //checksum
metaHeader.numDefinitions = metaSBuf.readInt32();
metaHeader.metaRegionPos = metaSBuf.readInt32();
recorderState = new RecorderState();
recorderState.wpos = metaSBuf.readInt32();
recorderState.lastMsgBeginPos = metaSBuf.readInt32();
recorderState.curMessage = metaSBuf.readUInt16();
metaSBuf = new UtilSizeBuf("meta region defs", metaRegion, META_HEADER_SIZE, metaHeader.metaRegionPos);
for (int i = 0; i < metaHeader.numDefinitions; i++) {
int defKind = metaSBuf.readUInt8();
switch (defKind) {
case 1: //MRT_MESSAGE_DEF
parseMessageDefinition(metaSBuf);
break;
default:
throw new RuntimeException("Invalid meta definition type" + defKind);
}
}
dataHeader = new DataHeader();
dataHeader.prevItrLastPos = dataRegion.readInt32(DATA_HEADER_SIG_BYTES.length + 12);
}
public FlightLogParser(UtilByteBuffer metaRegion, UtilByteBuffer dataRegion) {
this.metaRegion = metaRegion;
this.dataRegion = dataRegion;
}
void doParseMessage(UtilSizeBuf msg) {
int opc = msg.readUInt16();
boolean entrance = (0 != (opc & 0x8000));
opc &= 0x7FFF;
FlightrecMessageType msgType = msgTypes.get(opc);
if (msgType == null) {
throw new RuntimeException("Invalid message opcode @" + Long.toHexString(msg.getAbsoluteCurrentPos() - 2) + ": " + opc);
}
EntranceKind entranceKind;
if (msgType.inout) {
entranceKind = entrance ? EntranceKind.ENTRANCE_ENTER : EntranceKind.ENTRANCE_LEAVE;
} else {
entranceKind = EntranceKind.ENTRANCE_UNUSED;
}
FlightrecMessage flMsg = new FlightrecMessage(msgType, entranceKind, msg.getBuffer(), msg.getAbsoluteCurrentPos(), msg.getMaxSize() - 2);
messages.add(flMsg);
}
void parseMessage(UtilSizeBuf msg) {
int startPos = msg.getStartPos();
try {
doParseMessage(msg);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error while parsing message @" + startPos);
}
}
List<FlightrecMessage> parse() {
parseMetaRegion();
UtilByteBuffer flightData = dataRegion.cutLeft(DATA_HEADER_SIZE);
boolean flippedToEnd = false;
/*
Each message has following layout:
Opcode [2 bytes]
Data [0+ bytes]
Length of opcode + data [2 bytes]
*/
int curMsgPos = (recorderState.curMessage == 0) ? recorderState.wpos : recorderState.lastMsgBeginPos;
curMsgPos -= 2; //position of the Length field of the message
UtilSizeBuf msg = new UtilSizeBuf("flightrec_message", flightData, 0, 0);
while (true) {
if (flippedToEnd && curMsgPos <= recorderState.wpos)
break;
if (curMsgPos <= 0) { //move read pointer to the end of the data region
if (dataHeader.prevItrLastPos == -1) //wpos never reached end of the region
break;
curMsgPos = dataHeader.prevItrLastPos - 2;
flippedToEnd = true;
continue;
}
int msgLen = flightData.readUInt16(curMsgPos);
int msgStartPos = curMsgPos - msgLen;
if (msgStartPos < 0) {
throw new RuntimeException("Corrupted data region; read msgLen=" + msgLen + " at " + curMsgPos + ", but it is too large (startPos < 0)");
}
if (flippedToEnd && msgStartPos < recorderState.wpos) {
break;
}
msg.init(msgStartPos, msgLen);
parseMessage(msg);
curMsgPos = msgStartPos - 2;
}
return messages;
}
public static List<FlightrecMessage> doParse(RandomAccessFile f, HeaderScanResult metaHeader, HeaderScanResult dataHeader) throws IOException {
//read regions to byte buffers
f.seek(metaHeader.pos);
byte[] metaRegionData = new byte[metaHeader.len];
f.readFully(metaRegionData);
f.seek(dataHeader.pos);
byte[] dataRegionData = new byte[dataHeader.len];
f.readFully(dataRegionData);
UtilByteBuffer metaRegion = new UtilByteBuffer(metaRegionData);
UtilByteBuffer dataRegion = new UtilByteBuffer(dataRegionData);
List<FlightrecMessage> res = new FlightLogParser(metaRegion, dataRegion).parse();
Collections.reverse(res);
return res;
}
}

View File

@ -1,12 +0,0 @@
package org.rehlds.flightrec.logparser;
public class LogParsingException extends RuntimeException {
public LogParsingException(String message) {
super(message);
}
public LogParsingException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -1,14 +0,0 @@
package org.rehlds.flightrec.logparser;
public class MetaHeader {
public int numDefinitions;
public int metaRegionPos;
public MetaHeader(int numMessages, int metaRegionPos) {
this.numDefinitions = numMessages;
this.metaRegionPos = metaRegionPos;
}
public MetaHeader() {
}
}

View File

@ -1,16 +0,0 @@
package org.rehlds.flightrec.logparser;
public class RecorderState {
public int wpos;
public int lastMsgBeginPos;
public int curMessage;
public RecorderState(int wpos, int lastMsgBeginPos, int curMessage) {
this.wpos = wpos;
this.lastMsgBeginPos = lastMsgBeginPos;
this.curMessage = curMessage;
}
public RecorderState() {
}
}

View File

@ -1,72 +0,0 @@
package org.rehlds.flightrec.logtree;
import org.rehlds.flightrec.api.FlightrecMessage;
import org.rehlds.flightrec.api.FlightrecMessageType;
import java.util.List;
public class FlightLogTreeBuilder {
LogTreeNodeComplex rootNode = new LogTreeNodeComplex(null, null, null);
LogTreeNodeComplex currentNode = rootNode;
void handleEnterMessage(FlightrecMessage msg) {
LogTreeNodeComplex n = new LogTreeNodeComplex(currentNode, msg, null);
currentNode.addChild(n);
currentNode = n;
}
void handleLeaveMessage(FlightrecMessage msg) {
if (currentNode == rootNode) {
currentNode.leaveMsg = msg;
rootNode = new LogTreeNodeComplex(null, null, null);
rootNode.addChild(currentNode);
currentNode.setParent(rootNode);
currentNode = rootNode;
return;
}
if (currentNode.enterMsg != null) {
FlightrecMessageType startType = currentNode.enterMsg.messageType;
FlightrecMessageType endType = msg.messageType;
if (!startType.equals(endType)) {
throw new RuntimeException("Closing message @" + Long.toHexString(msg.rawDataPos) + " has invalid type " + endType + "; expected " + startType);
}
}
currentNode.leaveMsg = msg;
currentNode = currentNode.parent;
}
void handleSimpleMessage(FlightrecMessage msg) {
LogTreeNodeLeaf leafNode = new LogTreeNodeLeaf(currentNode, msg);
currentNode.addChild(leafNode);
}
void doBuildLogTree(List<FlightrecMessage> messages) {
for (FlightrecMessage msg : messages) {
switch (msg.entranceKind) {
case ENTRANCE_ENTER:
handleEnterMessage(msg);
break;
case ENTRANCE_LEAVE:
handleLeaveMessage(msg);
break;
case ENTRANCE_UNUSED:
handleSimpleMessage(msg);
break;
default:
throw new RuntimeException("Invalid exntrance kind");
}
}
}
public static LogTreeNodeComplex buildTree(List<FlightrecMessage> messages) {
FlightLogTreeBuilder builder = new FlightLogTreeBuilder();
builder.doBuildLogTree(messages);
return builder.rootNode;
}
}

View File

@ -1,21 +0,0 @@
package org.rehlds.flightrec.logtree;
import java.util.List;
public abstract class LogTreeNode {
LogTreeNodeComplex parent;
protected LogTreeNode(LogTreeNodeComplex parent) {
this.parent = parent;
}
abstract List<? extends LogTreeNode> getChildren();
LogTreeNodeComplex getParent() {
return parent;
}
public void setParent(LogTreeNodeComplex parent) {
this.parent = parent;
}
}

View File

@ -1,36 +0,0 @@
package org.rehlds.flightrec.logtree;
import org.rehlds.flightrec.api.FlightrecMessage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LogTreeNodeComplex extends LogTreeNode {
public FlightrecMessage enterMsg;
public FlightrecMessage leaveMsg;
public LogTreeNodeComplex(LogTreeNodeComplex parent, FlightrecMessage enterMsg, FlightrecMessage leaveMsg) {
super(parent);
this.enterMsg = enterMsg;
this.leaveMsg = leaveMsg;
}
List<LogTreeNode> children = Collections.emptyList();
@Override
public List<LogTreeNode> getChildren() {
return children;
}
public void addChild(LogTreeNode node) {
if (children.isEmpty()) {
children = new ArrayList<>();
}
children.add(node);
}
}

View File

@ -1,20 +0,0 @@
package org.rehlds.flightrec.logtree;
import org.rehlds.flightrec.api.FlightrecMessage;
import java.util.Collections;
import java.util.List;
public class LogTreeNodeLeaf extends LogTreeNode {
public FlightrecMessage msg;
public LogTreeNodeLeaf(LogTreeNodeComplex parent, FlightrecMessage msg) {
super(parent);
this.msg = msg;
}
@Override
List<? extends LogTreeNode> getChildren() {
return Collections.emptyList();
}
}

View File

@ -1,230 +0,0 @@
package org.rehlds.flightrec.main;
import org.rehlds.flightrec.api.DecoderModule;
import org.rehlds.flightrec.api.FlightrecMessage;
import org.rehlds.flightrec.decoders.rehlds.RehldsDecodersModule;
import org.rehlds.flightrec.filescan.FileScanResult;
import org.rehlds.flightrec.filescan.FlightRecFileScanner;
import org.rehlds.flightrec.filescan.HeaderScanResult;
import org.rehlds.flightrec.logtree.FlightLogTreeBuilder;
import org.rehlds.flightrec.logtree.LogTreeNodeComplex;
import org.rehlds.flightrec.logparser.FlightLogParser;
import org.rehlds.flightrec.textlogwriter.TextLogWriter;
import org.rehlds.flightrec.util.JarUtils;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
public class FlightRecorder {
RunConfig cfg;
List<DecoderModule> decoderModules = new ArrayList<>();
public FlightRecorder(RunConfig cfg) {
this.cfg = cfg;
}
private boolean checkConfig() {
if (cfg.dumpFile == null) {
System.out.println("Dump file is not selected, please use --dump-file <filename> parameter to specify it");
return false;
}
if (cfg.outFile == null) {
cfg.outFile = new File(cfg.dumpFile.getAbsolutePath() + ".flog");
}
return true;
}
private List<FlightrecMessage> scanFile(RandomAccessFile f) throws IOException {
FileScanResult scanResult = FlightRecFileScanner.scan(f);
System.out.println("Dump file scan results: ");
for (HeaderScanResult hdr : scanResult.metaHeaders) {
System.out.print(String.format("\tMeta header @ 0x%08X; len=%d; version=%d; valid=%s", hdr.pos, hdr.len, hdr.version, "" + (hdr.error == null)));
if (hdr.error != null) {
System.out.print("; error: " + hdr.error);
}
System.out.println();
}
for (HeaderScanResult hdr : scanResult.dataHeaders) {
System.out.print(String.format("\tData header @ 0x%08X; len=%d; version=%d; valid=%s", hdr.pos, hdr.len, hdr.version, "" + (hdr.error == null)));
if (hdr.error != null) {
System.out.print("; error: " + hdr.error);
}
System.out.println();
}
HeaderScanResult validMetaHeader = null;
HeaderScanResult validDataHeader = null;
for (HeaderScanResult metaHeader : scanResult.metaHeaders) {
if (metaHeader.error != null) {
continue;
}
if (validMetaHeader != null) {
System.out.println("Multiple meta headers found, exiting");
return null;
}
validMetaHeader = metaHeader;
}
for (HeaderScanResult dataHeader : scanResult.dataHeaders) {
if (dataHeader.error != null) {
continue;
}
if (validDataHeader != null) {
System.out.println("Multiple data headers found, exiting");
return null;
}
validDataHeader = dataHeader;
}
if (validMetaHeader == null) {
System.out.println("Meta header not found, exiting");
return null;
}
if (validDataHeader == null) {
System.out.println("Data header not found, exiting");
return null;
}
return FlightLogParser.doParse(f, validMetaHeader, validDataHeader);
}
private LogTreeNodeComplex buildTree(List<FlightrecMessage> messages) {
return FlightLogTreeBuilder.buildTree(messages);
}
private boolean writeOutputFile(LogTreeNodeComplex logTreeRoot) {
TextLogWriter.decodeAndWrite(logTreeRoot, cfg.outFile, decoderModules);
System.out.println("Written decoded log to '" + cfg.outFile.getAbsolutePath() + ";");
return true;
}
public boolean run() {
registerBuiltinDecoders();
loadExternalDecoders();
if (!checkConfig()) {
return false;
}
List<FlightrecMessage> messages;
try(RandomAccessFile f = new RandomAccessFile(cfg.dumpFile, "r")) {
messages = scanFile(f);
} catch (IOException e) {
e.printStackTrace();
return false;
}
if (messages == null) {
return false;
}
System.out.println("Read " + messages.size() + " messages from '" + cfg.dumpFile.getAbsolutePath() + "'");
LogTreeNodeComplex treeRootNode = buildTree(messages);
if (treeRootNode == null) {
return false;
}
if (!writeOutputFile(treeRootNode)) {
return false;
}
return true;
}
private void loadExternalDecoders() {
File f = JarUtils.getJarFileOfClass(FlightRecorder.class);
if (f == null) {
System.out.println("Could not locate main JAR, external decoders will not be loaded");
return;
}
File extDir = new File(f.getParentFile(), "extDecoders");
if (!extDir.exists() || !extDir.isDirectory()) {
System.out.println("Directory '" + extDir.getAbsolutePath() + "' doesn't exist");
}
File[] jarFiles = extDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".jar");
}
});
ArrayList<URL> jarUrls = new ArrayList<>();
for (File jf : jarFiles) {
try {
jarUrls.add(jf.toURI().toURL());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
URLClassLoader extDecodersClassloader = new URLClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), this.getClass().getClassLoader());
ServiceLoader<DecoderModule> srvLoader = ServiceLoader.load(DecoderModule.class, extDecodersClassloader);
for (DecoderModule decoderModule : srvLoader) {
System.out.println("Loaded external decoder module " + decoderModule.getDescription() + " version " + decoderModule.getVersion());
decoderModules.add(decoderModule);
}
}
private void registerBuiltinDecoders() {
decoderModules.add(new RehldsDecodersModule());
}
public static void main(String args[]) {
RunConfig cfg;
try {
cfg = parseArgs(args);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
return;
}
new FlightRecorder(cfg).run();
}
private static RunConfig parseArgs(String args[]) {
RunConfig cfg = new RunConfig();
for (int i = 0; i < args.length; i++) {
String a = args[i];
if ("--dump-file".equals(a)) {
if (i + 1 >= args.length) {
throw new IllegalArgumentException("--dump-file should be followed by file name");
}
i++;
cfg.dumpFile = new File(args[i]);
continue;
}
if ("--out-file".equals(a)) {
if (i + 1 >= args.length) {
throw new IllegalArgumentException("--out-file should be followed by file name");
}
i++;
cfg.outFile = new File(args[i]);
continue;
}
throw new IllegalArgumentException("Invalid command line parameter: '" + a + "'");
}
return cfg;
}
}

View File

@ -1,8 +0,0 @@
package org.rehlds.flightrec.main;
import java.io.File;
public class RunConfig {
public File dumpFile;
public File outFile;
}

View File

@ -1,185 +0,0 @@
package org.rehlds.flightrec.textlogwriter;
import org.rehlds.flightrec.api.*;
import org.rehlds.flightrec.logtree.LogTreeNode;
import org.rehlds.flightrec.logtree.LogTreeNodeComplex;
import org.rehlds.flightrec.logtree.LogTreeNodeLeaf;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TextLogWriter {
Writer writer;
List<DecoderModule> decoderModules;
int indent;
HashMap<Integer, String> indents = new HashMap<>();
Map<FlightrecMessageType, MessageDecoder> decodersByMsgType = new HashMap<>();
public TextLogWriter(Writer writer, List<DecoderModule> decoderModules) {
this.writer = writer;
this.decoderModules = decoderModules;
}
MessageDecoder lookupDecoder(FlightrecMessageType msgType) {
for (DecoderModule dm : decoderModules) {
MessageDecoder d = dm.lookupDecoder(msgType);
if (d != null) {
return d;
}
}
return null;
}
MessageDecoder getDecoder(FlightrecMessage message) {
FlightrecMessageType msgType = message.messageType;
if (!decodersByMsgType.containsKey(msgType)) {
decodersByMsgType.put(msgType, lookupDecoder(msgType));
}
return decodersByMsgType.get(msgType);
}
DecodedExtraData tryDecode(FlightrecMessage message) {
MessageDecoder decoder = getDecoder(message);
if (decoder == null) {
return null;
}
return decoder.decode(message);
}
String escapeString(String s) {
return s.replace("\"", "\\\"")
.replace("'", "\\'")
.replace("\n", "\\n")
.replace("\r", "\\r");
}
String generateIndent() {
String res = indents.get(indent);
if (res != null) {
return res;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indent; i++) {
sb.append(" ");
}
res = sb.toString();
indents.put(indent, res);
return res;
}
void writeExtraData(StringBuilder sb, DecodedExtraData extraData) {
boolean first = true;
for (ImmutablePair<String, String> kv : extraData.data) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(kv.first).append(": '").append(escapeString(kv.second)).append("'");
}
}
String prepareMessageText(FlightrecMessage msg) {
StringBuilder sb = new StringBuilder();
sb.append(generateIndent());
switch (msg.entranceKind) {
case ENTRANCE_ENTER:
sb.append(">>");
break;
case ENTRANCE_LEAVE:
sb.append("<<");
break;
case ENTRANCE_UNUSED:
sb.append("--");
break;
default:
throw new RuntimeException("Invalid entrance kind " + msg.entranceKind);
}
FlightrecMessageType msgType = msg.messageType;
sb.append(" ").append(msgType.module).append(".").append(msgType.message).append(":").append(msgType.version).append(" ");
DecodedExtraData extraData = tryDecode(msg);
if (extraData != null) {
writeExtraData(sb, extraData);
} else {
sb.append("undecoded[");
boolean firstByte = true;
for (int i = msg.rawDataPos; i < msg.rawDataLen + msg.rawDataPos; i++) {
if (firstByte) {
firstByte = false;
} else {
sb.append(" ");
}
sb.append(String.format("%02X", msg.rawData[i] & 0xFF));
}
sb.append("]");
}
sb.append("\n");
return sb.toString();
}
void writeMessage(FlightrecMessage msg) throws IOException {
String text = prepareMessageText(msg);
writer.write(text);
}
void writeLeafNode(LogTreeNodeLeaf node) throws IOException {
writeMessage(node.msg);
}
void writeComplexNode(LogTreeNodeComplex node) throws IOException {
if (node.enterMsg != null) {
writeMessage(node.enterMsg);
} else {
writer.write(generateIndent() + ">> [Unknown]\n");
}
indent++;
writeNodes(node.getChildren());
indent--;
if (node.leaveMsg != null) {
writeMessage(node.leaveMsg);
} else {
writer.write(generateIndent() + "<< [Unknown]\n");
}
}
void writeNodes(List<LogTreeNode> nodes) throws IOException {
for (LogTreeNode node : nodes) {
if (node instanceof LogTreeNodeComplex) {
writeComplexNode((LogTreeNodeComplex) node);
} else if (node instanceof LogTreeNodeLeaf) {
writeLeafNode((LogTreeNodeLeaf) node);
} else {
throw new RuntimeException("Invalid node class " + node.getClass().getName());
}
}
}
public static void decodeAndWrite(LogTreeNodeComplex rootNode, File outFile, List<DecoderModule> decoderModules) {
try (FileWriter fw = new FileWriter(outFile)) {
TextLogWriter logWriter = new TextLogWriter(fw, decoderModules);
logWriter.writeNodes(rootNode.getChildren());
} catch (IOException e) {
throw new RuntimeException("Failed to open/write file '" + outFile + "': " + e.getMessage(), e);
}
}
}

View File

@ -1,31 +0,0 @@
package org.rehlds.flightrec.util;
import java.io.File;
import java.net.URL;
public class JarUtils {
public static File getJarFileOfClass(Class c) {
String classFileName = c.getName().replace('.', '/') + ".class";
ClassLoader classLoader = c.getClassLoader();
if (classLoader == null) {
classLoader = JarUtils.class.getClassLoader();
}
URL url = classLoader.getResource(classFileName);
if (url == null) {
return null;
}
String strUrl = url.toString();
if (!strUrl.startsWith("jar:file:/")) {
return null;
}
int jarSeparator = strUrl.indexOf('!');
if (jarSeparator == -1) {
return null;
}
String jarFilePath = strUrl.substring("jar:file:/".length(), jarSeparator);
return new File(jarFilePath);
}
}

View File

@ -1,181 +0,0 @@
package org.rehlds.flightrec.logtree
import org.junit.Test
import org.rehlds.flightrec.api.EntranceKind
import org.rehlds.flightrec.api.FlightrecMessage
import org.rehlds.flightrec.api.FlightrecMessageType
class FlightLogTreeBuilderTest {
static final FlightrecMessageType hierarchyMsgType1 = new FlightrecMessageType('test', 'hmsg1', 1, true);
static final FlightrecMessageType hierarchyMsgType2 = new FlightrecMessageType('test', 'hmsg1', 1, true);
static final FlightrecMessageType flatMsgType1 = new FlightrecMessageType('test', 'flatmsg1', 1, true);
static final FlightrecMessageType flatMsgType2 = new FlightrecMessageType('test', 'flatmsg2', 1, true);
static FlightrecMessage enterMsg(FlightrecMessageType type) {
return new FlightrecMessage(type, EntranceKind.ENTRANCE_ENTER, null, 0, 0);
}
static FlightrecMessage leaveMsg(FlightrecMessageType type) {
return new FlightrecMessage(type, EntranceKind.ENTRANCE_LEAVE, null, 0, 0);
}
static FlightrecMessage flatMsg(FlightrecMessageType type) {
return new FlightrecMessage(type, EntranceKind.ENTRANCE_UNUSED, null, 0, 0);
}
@Test
void 'decode 2 flat messages'() {
def messages = [flatMsg(flatMsgType1), flatMsg(flatMsgType2)]
def rootNode = FlightLogTreeBuilder.buildTree(messages)
assert rootNode.children.size() == 2
assert rootNode.children[0].msg == messages[0];
assert rootNode.children[1].msg == messages[1];
assert rootNode.enterMsg == null
assert rootNode.leaveMsg == null
}
@Test
void 'decode 2 empty hierarchy msgs'() {
def messages = [
enterMsg(hierarchyMsgType1), leaveMsg(hierarchyMsgType1),
enterMsg(hierarchyMsgType2), leaveMsg(hierarchyMsgType2)
]
def rootNode = FlightLogTreeBuilder.buildTree(messages)
assert rootNode.children.size() == 2
rootNode.children[0].enterMsg == messages[0]
rootNode.children[0].leaveMsg == messages[1]
assert rootNode.children[0].children.empty
rootNode.children[1].enterMsg == messages[2]
rootNode.children[1].leaveMsg == messages[3]
assert rootNode.children[1].children.empty
assert rootNode.enterMsg == null
assert rootNode.leaveMsg == null
}
@Test
void 'decode 2 hierarchy messages with flat payload'() {
def messages = [
enterMsg(hierarchyMsgType1), flatMsg(flatMsgType1), leaveMsg(hierarchyMsgType1),
enterMsg(hierarchyMsgType2), flatMsg(flatMsgType2), leaveMsg(hierarchyMsgType2)
]
def rootNode = FlightLogTreeBuilder.buildTree(messages)
assert rootNode.children.size() == 2
rootNode.children[0].enterMsg == messages[0]
rootNode.children[0].leaveMsg == messages[2]
assert rootNode.children[0].children.size() == 1
assert rootNode.children[0].children[0].msg == messages[1]
rootNode.children[1].enterMsg == messages[3]
rootNode.children[1].leaveMsg == messages[5]
assert rootNode.children[1].children.size() == 1
assert rootNode.children[1].children[0].msg == messages[4]
assert rootNode.enterMsg == null
assert rootNode.leaveMsg == null
}
@Test
void 'decode hierarchical message with mixed payload'() {
def messages = [
flatMsg(flatMsgType2),
enterMsg(hierarchyMsgType1),
flatMsg(flatMsgType1),
enterMsg(hierarchyMsgType2),
flatMsg(flatMsgType2),
leaveMsg(hierarchyMsgType2),
flatMsg(flatMsgType2),
leaveMsg(hierarchyMsgType1),
flatMsg(flatMsgType1)
]
def rootNode = FlightLogTreeBuilder.buildTree(messages)
assert rootNode.children.size() == 3
assert rootNode.enterMsg == null
assert rootNode.leaveMsg == null
assert rootNode.children[0].msg == messages[0]
assert rootNode.children[2].msg == messages[8]
assert rootNode.children[1].enterMsg == messages[1]
assert rootNode.children[1].leaveMsg == messages[7]
assert rootNode.children[1].children.size() == 3
assert rootNode.children[1].children[0].msg == messages[2]
assert rootNode.children[1].children[2].msg == messages[6]
assert rootNode.children[1].children[1].enterMsg == messages[3]
assert rootNode.children[1].children[1].leaveMsg == messages[5]
assert rootNode.children[1].children[1].children.size() == 1
assert rootNode.children[1].children[1].children[0].msg == messages[4]
}
@Test
void 'decode hierarchical msg with flat payload and missing start'() {
def messages = [
flatMsg(flatMsgType1),
leaveMsg(hierarchyMsgType1),
flatMsg(flatMsgType2)
]
def rootNode = FlightLogTreeBuilder.buildTree(messages)
assert rootNode.children.size() == 2
assert rootNode.enterMsg == null
assert rootNode.leaveMsg == null
assert rootNode.children[0].enterMsg == null
assert rootNode.children[0].leaveMsg == messages[1]
assert rootNode.children[0].children.size() == 1
assert rootNode.children[0].children[0].msg == messages[0]
assert rootNode.children[1].msg == messages[2]
}
@Test
void 'decode empty hierarchical msg with missing start'() {
def messages = [
leaveMsg(hierarchyMsgType1),
flatMsg(flatMsgType2)
]
def rootNode = FlightLogTreeBuilder.buildTree(messages)
assert rootNode.children.size() == 2
assert rootNode.enterMsg == null
assert rootNode.leaveMsg == null
assert rootNode.children[0].enterMsg == null
assert rootNode.children[0].leaveMsg == messages[0]
assert rootNode.children[0].children.empty
assert rootNode.children[1].msg == messages[1]
}
@Test
void 'decode hierarchical msg with flat payload and missing end'() {
def messages = [
flatMsg(flatMsgType1),
enterMsg(hierarchyMsgType1),
flatMsg(flatMsgType2)
]
def rootNode = FlightLogTreeBuilder.buildTree(messages)
assert rootNode.children.size() == 2
assert rootNode.enterMsg == null
assert rootNode.leaveMsg == null
assert rootNode.children[0].msg == messages[0]
assert rootNode.children[1].enterMsg == messages[1]
assert rootNode.children[1].leaveMsg == null
assert rootNode.children[1].children.size() == 1
assert rootNode.children[1].children[0].msg == messages[2]
}
}

View File

@ -1,43 +0,0 @@
package com.google.cloud;
import org.junit.Test;
import static org.junit.Assert.*;
public class Crc32cTest {
static class TestData {
public String src;
public long hash;
TestData(String src, long hash) {
this.src = src;
this.hash = hash;
}
}
@Test
public void testCrc32c() {
TestData testData[] = {
new TestData("a", 0x93AD1061L),
new TestData("ab", 0x13C35EE4L),
new TestData("abc", 0x562F9CCDL),
new TestData("abcd", 0xDAAF41F6L),
new TestData("abcde", 0x8122A0A2L),
new TestData("abcdef", 0x0496937BL),
new TestData("abcdefg", 0x5D199E2CL),
new TestData("abcdefgh", 0x86BC933DL),
new TestData("abcdefghi", 0x9639F15FL),
new TestData("abcdefghij", 0x0584645CL),
};
for (TestData t : testData) {
Crc32c crc32c = new Crc32c();
crc32c.update(t.src.getBytes());
long cksum = crc32c.getValue();
assertEquals(t.hash, cksum);
}
}
}

View File

@ -1,74 +0,0 @@
apply plugin: 'java'
apply plugin: 'maven-publish'
group = 'org.rehlds.flightrec'
version = rootProject.version
sourceCompatibility = '1.7'
targetCompatibility = '1.7'
repositories {
mavenCentral()
}
dependencies {
testCompile "junit:junit:4.12"
}
publishing {
publications {
maven(MavenPublication) {
version project.version
artifactId 'decoder-api'
artifact jar
pom.withXml {
asNode().children().last() + {
resolveStrategy = DELEGATE_FIRST
name 'decoder-api'
description project.description
//url github
//scm {
// url "${github}.git"
// connection "scm:git:${github}.git"
//}
/*
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
distribution 'repo'
}
}
developers {
developer {
id 'dreamstalker'
name 'dreamstalker'
}
}
*/
}
}
}
}
}
publishing {
repositories {
maven {
if (project.version.contains('dev')) {
url "http://nexus.rehlds.org/nexus/content/repositories/rehlds-dev/"
} else {
url "http://nexus.rehlds.org/nexus/content/repositories/rehlds-releases/"
}
credentials {
username rootProject.repoCreds.getProperty('username')
password rootProject.repoCreds.getProperty('password')
}
}
}
}
tasks.withType(AbstractCompile) {
options.encoding = 'UTF-8'
}

View File

@ -1,28 +0,0 @@
package org.rehlds.flightrec.api;
public class DecodedExtraData {
public ImmutablePair<String, String>[] data;
public DecodedExtraData(ImmutablePair<String, String>[] data) {
this.data = data;
}
public static final DecodedExtraData EMPTY = new DecodedExtraData(new ImmutablePair[0]);
public static DecodedExtraData create(String... args) {
if ((args.length % 2) == 1) {
throw new RuntimeException("DecodedExtraData.create: number of arguments must be even");
}
int numPairs = args.length / 2;
DecodedExtraData res = new DecodedExtraData(new ImmutablePair[numPairs]);
for (int i = 0; i < numPairs; i++) {
res.data[i] = new ImmutablePair<>(args[i * 2], args[i * 2 + 1]);
}
return res;
}
}

View File

@ -1,7 +0,0 @@
package org.rehlds.flightrec.api;
public interface DecoderModule {
public MessageDecoder lookupDecoder(FlightrecMessageType msgType);
public String getDescription();
public String getVersion();
}

View File

@ -1,7 +0,0 @@
package org.rehlds.flightrec.api;
public enum EntranceKind {
ENTRANCE_ENTER,
ENTRANCE_LEAVE,
ENTRANCE_UNUSED,
}

View File

@ -1,35 +0,0 @@
package org.rehlds.flightrec.api;
import org.rehlds.flightrec.api.util.UtilByteBuffer;
import org.rehlds.flightrec.api.util.UtilSizeBuf;
public class FlightrecMessage {
public final FlightrecMessageType messageType;
public final EntranceKind entranceKind;
public final byte[] rawData;
public final int rawDataPos;
public final int rawDataLen;
DecodedExtraData decodedData;
public FlightrecMessage(FlightrecMessageType messageType, EntranceKind entranceKind, byte[] rawData, int rawDataOffset, int rawDataLen) {
this.messageType = messageType;
this.entranceKind = entranceKind;
this.rawData = rawData;
this.rawDataPos = rawDataOffset;
this.rawDataLen = rawDataLen;
}
public UtilSizeBuf getDataSizebuf() {
return new UtilSizeBuf("msg: '" + messageType + "' @" + rawDataPos, new UtilByteBuffer(rawData), rawDataPos, rawDataLen);
}
public boolean isEnterMessage() {
return (entranceKind == EntranceKind.ENTRANCE_ENTER);
}
public boolean isLeaveMessage() {
return (entranceKind == EntranceKind.ENTRANCE_LEAVE);
}
}

View File

@ -1,22 +0,0 @@
package org.rehlds.flightrec.api;
public class FlightrecMessageDef {
public final FlightrecMessageType msgType;
public final int opcode;
public FlightrecMessageDef(String module, String message, long version, boolean inout, int opcode) {
msgType = new FlightrecMessageType(module, message, version, inout);
this.opcode = opcode;
}
@Override
public String toString() {
return "FlightrecMessageDef{" +
"module='" + msgType.module + '\'' +
", message='" + msgType.message + '\'' +
", version=" + msgType.version +
", inout=" + msgType.inout +
", opcode=" + opcode +
'}';
}
}

View File

@ -1,49 +0,0 @@
package org.rehlds.flightrec.api;
public class FlightrecMessageType {
public final String module;
public final String message;
public final long version;
public final boolean inout;
public FlightrecMessageType(String module, String message, long version, boolean inout) {
this.module = module;
this.message = message;
this.version = version;
this.inout = inout;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FlightrecMessageType that = (FlightrecMessageType) o;
if (inout != that.inout) return false;
if (version != that.version) return false;
if (!message.equals(that.message)) return false;
if (!module.equals(that.module)) return false;
return true;
}
@Override
public int hashCode() {
int result = module.hashCode();
result = 31 * result + message.hashCode();
result = 31 * result + (int) (version ^ (version >>> 32));
result = 31 * result + (inout ? 1 : 0);
return result;
}
@Override
public String toString() {
return "FlightrecMessageType{" +
"module='" + module + '\'' +
", message='" + message + '\'' +
", version=" + version +
", inout=" + inout +
'}';
}
}

View File

@ -1,11 +0,0 @@
package org.rehlds.flightrec.api;
public class ImmutablePair<T, U> {
public final T first;
public final U second;
public ImmutablePair(T first, U second) {
this.first = first;
this.second = second;
}
}

View File

@ -1,6 +0,0 @@
package org.rehlds.flightrec.api;
public interface MessageDecoder {
FlightrecMessageType getMessageType();
DecodedExtraData decode(FlightrecMessage msg);
}

View File

@ -1,35 +0,0 @@
package org.rehlds.flightrec.api;
import java.util.HashMap;
import java.util.Map;
public class SimpleDecoderModule implements DecoderModule {
Map<FlightrecMessageType, MessageDecoder> decoders = new HashMap<>();
public final String description;
public final String version;
public SimpleDecoderModule(String description, String version) {
this.description = description;
this.version = version;
}
@Override
public MessageDecoder lookupDecoder(FlightrecMessageType msgType) {
return decoders.get(msgType);
}
@Override
public String getDescription() {
return description;
}
@Override
public String getVersion() {
return version;
}
public void registerDecoder(MessageDecoder msgDecoder) {
decoders.put(msgDecoder.getMessageType(), msgDecoder);
}
}

View File

@ -1,8 +0,0 @@
package org.rehlds.flightrec.api.util;
import java.nio.charset.Charset;
public class Globals {
public static final Charset UTF8 = Charset.forName("UTF-8");
}

View File

@ -1,10 +0,0 @@
package org.rehlds.flightrec.api.util;
public class SizebufOverflowException extends RuntimeException {
public final String sizebufName;
public SizebufOverflowException(String sizebufName) {
super(sizebufName + " overflowed");
this.sizebufName = sizebufName;
}
}

View File

@ -1,79 +0,0 @@
package org.rehlds.flightrec.api.util;
public class UtilByteBuffer {
byte data[];
public UtilByteBuffer(byte[] data) {
this.data = data;
}
public byte[] getData() {
return data;
}
public UtilByteBuffer cutLeft(int newStart) {
byte[] newData = new byte[data.length - newStart];
System.arraycopy(data, newStart, newData, 0, data.length - newStart);
return new UtilByteBuffer(newData);
}
public int getDataLength() {
return data.length;
}
public int readUInt8(int pos) {
return data[pos] & 0xFF;
}
public boolean readBool(int pos) {
return data[pos] != 0;
}
public int readUInt16(int pos) {
return (data[pos] & 0xFF) | ((data[pos + 1] & 0xFF) << 8);
}
public long readUInt32(int pos) {
return (data[pos] & 0xFF) | ((data[pos + 1] & 0xFF) << 8) | ((data[pos + 2] & 0xFF) << 16) | ((long)(data[pos + 3] & 0xFF) << 24);
}
public int readInt32(int pos) {
return (data[pos] & 0xFF) | ((data[pos + 1] & 0xFF) << 8) | ((data[pos + 2] & 0xFF) << 16) | ((data[pos + 3] & 0xFF) << 24);
}
public long readInt64(int pos) {
long lowBits = readUInt32(pos);
long highBits = readUInt32(pos + 4);
return lowBits | (highBits << 32);
}
public double readDouble(int pos) {
long bits = readInt64(pos);
return Double.longBitsToDouble(bits);
}
public float readFloat(int pos) {
int bits = readInt32(pos);
return Float.intBitsToFloat(bits);
}
public String readString(int pos) {
return readString(pos, data.length - pos, true);
}
public String readString(int pos, int maxSize, boolean errorOnMaxSizeHit) {
int iMax = Math.min(data.length, pos + maxSize);
for (int i = pos; i < iMax; i++) {
if (data[i] == 0) {
return new String(data, pos, i - pos, Globals.UTF8);
}
}
if (errorOnMaxSizeHit) {
return null;
}
return new String(data, pos, iMax - pos, Globals.UTF8);
}
}

View File

@ -1,159 +0,0 @@
package org.rehlds.flightrec.api.util;
public class UtilSizeBuf {
String name;
UtilByteBuffer buf;
int startPos;
int maxSize;
int curPos;
public UtilSizeBuf(String name, UtilByteBuffer buf, int startPos, int maxSize) {
this.name = name;
this.buf = buf;
this.startPos = startPos;
this.maxSize = maxSize;
curPos = 0;
}
public UtilSizeBuf(String name, UtilByteBuffer buf) {
this(name, buf, 0, buf.getDataLength());
}
public void init(int startPos, int maxSize) {
this.startPos = startPos;
this.maxSize = maxSize;
curPos = 0;
}
public void reset() {
this.curPos = 0;
}
public int tell() {
return curPos;
}
public int getAbsoluteCurrentPos() {
return curPos + startPos;
}
public void skip(int count) {
if (curPos + count > maxSize) {
curPos = maxSize;
throw new SizebufOverflowException(name);
}
curPos += count;
}
public int readUInt8() {
if (curPos + 1 > maxSize) {
curPos = maxSize;
throw new SizebufOverflowException(name);
}
int pos = curPos;
curPos++;
return buf.readUInt8(pos + this.startPos);
}
public boolean readBool() {
if (curPos + 1 > maxSize) {
curPos = maxSize;
throw new SizebufOverflowException(name);
}
int pos = curPos;
curPos++;
return buf.readBool(pos + this.startPos);
}
public int readUInt16() {
if (curPos + 2 > maxSize) {
curPos = maxSize;
throw new SizebufOverflowException(name);
}
int pos = curPos;
curPos += 2;
return buf.readUInt16(pos + this.startPos);
}
public long readUInt32() {
if (curPos + 4 > maxSize) {
curPos = maxSize;
throw new SizebufOverflowException(name);
}
int pos = curPos;
curPos += 4;
return buf.readUInt32(pos + this.startPos);
}
public int readInt32() {
if (curPos + 4 > maxSize) {
curPos = maxSize;
throw new SizebufOverflowException(name);
}
int pos = curPos;
curPos += 4;
return buf.readInt32(pos + this.startPos);
}
public long readInt64() {
if (curPos + 8 > maxSize) {
curPos = maxSize;
throw new SizebufOverflowException(name);
}
int pos = curPos;
curPos += 8;
return buf.readInt64(pos + this.startPos);
}
public double readDouble() {
if (curPos + 8 > maxSize) {
curPos = maxSize;
throw new SizebufOverflowException(name);
}
int pos = curPos;
curPos += 8;
return buf.readDouble(pos + this.startPos);
}
public float readFloat() {
if (curPos + 4 > maxSize) {
curPos = maxSize;
throw new SizebufOverflowException(name);
}
int pos = curPos;
curPos += 4;
return buf.readFloat(pos + this.startPos);
}
public String readString() {
String s = buf.readString(curPos + this.startPos);
if (s == null) {
curPos = maxSize;
throw new SizebufOverflowException(name);
}
curPos += s.getBytes(Globals.UTF8).length + 1;
return s;
}
public int getStartPos() {
return startPos;
}
public int getMaxSize() {
return maxSize;
}
public byte[] getBuffer() {
return buf.getData();
}
}

View File

@ -1,127 +0,0 @@
package org.rehlds.flightrec.util;
import org.junit.Test;
import org.rehlds.flightrec.api.util.UtilByteBuffer;
import static org.junit.Assert.*;
public class UtilByteBufferTest {
@Test
public void testReadUInt8() throws Exception {
byte data[] = { 0x10, 0x00, 0x7F, (byte)0x80, (byte)0xFF };
UtilByteBuffer bb = new UtilByteBuffer(data);
assertEquals(0x10, bb.readUInt8(0));
assertEquals(0x00, bb.readUInt8(1));
assertEquals(0x7F, bb.readUInt8(2));
assertEquals(0x80, bb.readUInt8(3));
assertEquals(0xFF, bb.readUInt8(4));
}
@Test
public void testReadUInt16() throws Exception {
byte data[] = { 0x10, 0x00, 0x7F, (byte)0x80, (byte)0xFF, 0x00 };
UtilByteBuffer bb = new UtilByteBuffer(data);
assertEquals(0x10, bb.readUInt16(0));
assertEquals(0x7F00, bb.readUInt16(1));
assertEquals(0x807F, bb.readUInt16(2));
assertEquals(0xFF80, bb.readUInt16(3));
assertEquals(0x00FF, bb.readUInt16(4));
}
@Test
public void testReadUInt32() throws Exception {
byte data[] = { 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x00, 0x00, 0x00, (byte)0xFF, 0x00, 0x00, 0x00 };
UtilByteBuffer bb = new UtilByteBuffer(data);
assertEquals(0x10000000, bb.readUInt32(0));
assertEquals(0x100000, bb.readUInt32(1));
assertEquals(0x1000, bb.readUInt32(2));
assertEquals(0x10, bb.readUInt32(3));
assertEquals(0x0, bb.readUInt32(4));
assertEquals(0x7F000000, bb.readUInt32(5));
assertEquals(0x7F0000, bb.readUInt32(6));
assertEquals(0x7F00, bb.readUInt32(7));
assertEquals(0x7F, bb.readUInt32(8));
assertEquals(0xFF000000L, bb.readUInt32(9));
assertEquals(0xFF0000, bb.readUInt32(10));
assertEquals(0xFF00, bb.readUInt32(11));
assertEquals(0xFF, bb.readUInt32(12));
}
@Test
public void testReadInt32() throws Exception {
byte data[] = { 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x00, 0x00, 0x00, (byte)0xFF, 0x00, 0x00, 0x00 };
UtilByteBuffer bb = new UtilByteBuffer(data);
assertEquals(0x10000000, bb.readInt32(0));
assertEquals(0x100000, bb.readInt32(1));
assertEquals(0x1000, bb.readInt32(2));
assertEquals(0x10, bb.readInt32(3));
assertEquals(0x0, bb.readInt32(4));
assertEquals(0x7F000000, bb.readInt32(5));
assertEquals(0x7F0000, bb.readInt32(6));
assertEquals(0x7F00, bb.readInt32(7));
assertEquals(0x7F, bb.readInt32(8));
assertEquals((int)0xFF000000, bb.readInt32(9));
assertEquals(0xFF0000, bb.readInt32(10));
assertEquals(0xFF00, bb.readInt32(11));
assertEquals(0xFF, bb.readInt32(12));
}
@Test
public void testReadInt64() throws Exception {
byte data[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
UtilByteBuffer bb = new UtilByteBuffer(data);
assertEquals(0x1000000000000000L, bb.readInt64(0));
assertEquals(0x10000000000000L, bb.readInt64(1));
assertEquals(0x100000000000L, bb.readInt64(2));
assertEquals(0x1000000000L, bb.readInt64(3));
assertEquals(0x10000000L, bb.readInt64(4));
assertEquals(0x100000L, bb.readInt64(5));
assertEquals(0x1000L, bb.readInt64(6));
assertEquals(0x10L, bb.readInt64(7));
assertEquals(0x00L, bb.readInt64(8));
assertEquals(0x7F00000000000000L, bb.readInt64(9));
assertEquals(0x7F000000000000L, bb.readInt64(10));
assertEquals(0x7F0000000000L, bb.readInt64(11));
assertEquals(0x7F00000000L, bb.readInt64(12));
assertEquals(0x7F000000L, bb.readInt64(13));
assertEquals(0x7F0000L, bb.readInt64(14));
assertEquals(0x7F00L, bb.readInt64(15));
assertEquals(0x7FL, bb.readInt64(16));
assertEquals(0xFF00000000000000L, bb.readInt64(17));
assertEquals(0xFF000000000000L, bb.readInt64(18));
assertEquals(0xFF0000000000L, bb.readInt64(19));
assertEquals(0xFF00000000L, bb.readInt64(20));
assertEquals(0xFF000000L, bb.readInt64(21));
assertEquals(0xFF0000L, bb.readInt64(22));
assertEquals(0xFF00L, bb.readInt64(23));
assertEquals(0xFFL, bb.readInt64(24));
}
@Test
public void testReadString() throws Exception {
byte data[] = { 0x00, 0x41, 0x00, 0x41, 0x42, 0x00, 0x50, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x69, 0x74, (byte)0xC3, (byte)0xA9, 0x00, 0x41, 0x42 };
UtilByteBuffer bb = new UtilByteBuffer(data);
assertEquals("", bb.readString(0));
assertEquals("A", bb.readString(1));
assertEquals("", bb.readString(2));
assertEquals("AB", bb.readString(3));
assertEquals("Publicité", bb.readString(6));
assertNull(bb.readString(17));
assertEquals("Public", bb.readString(6, 6, false));
assertNull(bb.readString(6, 6, true));
assertEquals("AB", bb.readString(17, 2, false));
assertNull(bb.readString(17, 2, true));
}
}

View File

@ -1,4 +0,0 @@
@echo off
call "%VS140COMNTOOLS%vcvarsqueryregistry.bat"
echo %UniversalCRTSdkDir%
echo %UCRTVersion%

View File

@ -1,3 +0,0 @@
majorVersion=3
minorVersion=7
maintenanceVersion=0

Some files were not shown because too many files have changed in this diff Show More