Compare commits

...
Author SHA1 Message Date
ahp 7168914d12 docs: add Arch Linux installation instructions 2026-11-22 13:47:48 +03:30
Morteza Bashsiz 70a99789d8 Merge pull request #265 from MortezaBashsiz/mori/multi_user
Change github test actions
2026-11-22 08:00:02 +01:00
Morteza Bashsiz d77e8deef9 Change github test actions 2026-11-22 07:59:25 +01:00
Morteza Bashsiz d1a24d5e3a Merge pull request #264 from MortezaBashsiz/mori/multi_user
Implement test and fix some bugs
2026-11-22 07:56:18 +01:00
Morteza Bashsiz 6d51a6b716 Implement test and fix some bugs 2026-11-22 07:45:14 +01:00
Morteza Bashsiz 31e649f670 Merge pull request #263 from MortezaBashsiz/mori/multi_user
Implement test and fix some bugs
2026-11-22 07:43:07 +01:00
Morteza Bashsiz c0b7b0b4d4 Implement test and fix some bugs 2026-11-22 07:42:23 +01:00
Morteza Bashsiz 01b2912765 Merge pull request #262 from MortezaBashsiz/mori/multi_user
Change config file
2026-11-22 07:10:42 +01:00
Morteza Bashsiz 13ea230e73 Change config file 2026-11-22 07:09:44 +01:00
Morteza Bashsiz 75638f7e1b Merge pull request #261 from MortezaBashsiz/mori/multi_user
add tag to detect users when aes is off
2026-11-21 21:21:28 +01:00
Morteza Bashsiz bd268c3e82 add tag to detect users when aes is off 2026-11-21 21:20:39 +01:00
Morteza Bashsiz 75d7104670 Merge pull request #260 from MortezaBashsiz/mori/multi_user
change config logic and replace directives
2026-11-21 20:40:04 +01:00
Morteza Bashsiz 933e373247 change config logic and replace directives 2026-11-21 20:38:43 +01:00
Morteza Bashsiz db1bd2e819 Merge pull request #259 from MortezaBashsiz/mori/multi_user
Add users usage control
2026-11-21 19:15:58 +01:00
Morteza Bashsiz 4bacfbfd99 Change version to 2.1.0 2026-11-21 19:15:34 +01:00
Morteza Bashsiz f1ae8d598c Add users usage control 2026-11-21 19:13:14 +01:00
Morteza Bashsiz fd775091b5 Merge pull request #258 from MortezaBashsiz/mori/multi_user
Implement multiuser mode and support SIGHUP for Linux
2026-11-21 16:45:06 +01:00
Morteza Bashsiz 87fc8a3f3c Implement multiuser mode and support SIGHUP for Linux 2026-11-21 16:44:16 +01:00
Morteza Bashsiz 1701f36638 fix systemd service files 2026-11-21 15:34:04 +01:00
Morteza Bashsiz abc8ae9a6b Add new line end of readme 2026-11-11 06:48:08 +01:00
Morteza Bashsiz 0a45ccc315 Add //namespace from tcpclient.cpp 2026-11-11 06:41:22 +01:00
Morteza Bashsiz bd283fbf22 Remove //namespace from tcpclient.cpp 2026-11-11 06:39:14 +01:00
Morteza Bashsiz 29eab9f955 Remove docs 2026-11-11 06:36:20 +01:00
Morteza Bashsiz 1d95451402 Merge pull request #256 from MortezaBashsiz/mori/add_python_config2url_script
Add python2url script
2026-10-30 16:42:50 +01:00
Morteza Bashsiz 230ea19b34 Add python2url script 2026-10-30 16:42:05 +01:00
Morteza Bashsiz 65fd8f1fca Merge pull request #254 from MortezaBashsiz/mori/update_readme
Update Readme
2026-10-29 14:05:11 +01:00
Morteza Bashsiz 4dd09b0d0e Update Readme 2026-10-29 14:03:08 +01:00
Morteza Bashsiz 6bcc946f58 Merge pull request #252 from MortezaBashsiz/mori/refactor
fix termux build issue
2026-10-27 23:17:08 +01:00
Morteza Bashsiz 6770764f2b fix termux build issue 2026-10-27 23:16:40 +01:00
Morteza Bashsiz 9199a0ded9 Merge pull request #251 from MortezaBashsiz/mori/refactor
Mori/refactor
2026-10-27 23:02:59 +01:00
Morteza Bashsiz 92de8a0bce change log level to infor in the config 2026-10-27 23:02:40 +01:00
Morteza Bashsiz 679ab77dc2 Fix CPU utilization issue 2026-10-27 22:52:25 +01:00
Morteza Bashsiz 04768f37de Test commit 2026-10-27 22:29:19 +01:00
Morteza Bashsiz ce61bfd8ad Merge pull request #245 from MortezaBashsiz/mori/add-docker
add docker file
2026-06-22 16:02:39 +02:00
Morteza Bashsiz 78188d8ac3 add docker file 2026-06-22 16:01:44 +02:00
Morteza Bashsiz 5f3594b6d2 Merge pull request #242 from MortezaBashsiz/mori
Mori
2026-06-17 22:56:49 +02:00
Morteza Bashsiz 95e05cf59c Update readme 2026-06-17 22:55:47 +02:00
Morteza Bashsiz a8205a716b Merge pull request #241 from MortezaBashsiz/dev
Dev
2026-06-17 11:08:29 +02:00
Morteza Bashsiz c76b23f93c Merge pull request #240 from MortezaBashsiz/mori
update readme
2026-06-17 11:06:53 +02:00
Morteza Bashsiz 555cad3654 Merge branch 'dev' into mori 2026-06-17 11:06:23 +02:00
Morteza Bashsiz df310303da update readme 2026-06-17 11:04:44 +02:00
Morteza Bashsiz 5056b7b907 Merge pull request #239 from MortezaBashsiz/dev
Add nix support
2026-06-16 14:16:47 +02:00
Morteza Bashsiz 5616828192 Merge pull request #225 from Grphq1/feat/add-flake-nix
feat: add nix flake support
2026-06-16 14:14:17 +02:00
Morteza Bashsiz 5a0c414f63 Version 1.1.59
Version 1.1.59
2026-06-16 11:49:39 +02:00
Morteza Bashsiz 5ddfcf1a0d Merge pull request #238 from MortezaBashsiz/mori
fix readme
2026-06-16 11:47:50 +02:00
Morteza Bashsiz 703595501c fix readme 2026-06-16 11:44:53 +02:00
Morteza Bashsiz 3b195208ff Merge pull request #236 from MortezaBashsiz/mori version 1.1.59
new version 1.1.59
2026-06-16 11:29:25 +02:00
Morteza Bashsiz a63d7ca141 new version 1.1.59 2026-06-16 11:28:42 +02:00
Morteza Bashsiz 882c68179f Merge pull request #235 from MortezaBashsiz/mori
change libyaml-cpp dependencies
2026-06-16 10:54:37 +02:00
Morteza Bashsiz 5e8b76769d change libyaml-cpp dependencies 2026-06-16 10:53:57 +02:00
Morteza Bashsiz c1afc7dab2 Merge pull request #233 from MortezaBashsiz/mori Version 1.1.59
Version 1.1.59
2026-06-16 10:29:57 +02:00
Morteza Bashsiz ef04fb3fb2 Fix config and log overwrite 2026-06-16 10:28:10 +02:00
Morteza Bashsiz ec5eaf824b Make logs better 2026-06-15 11:43:53 +02:00
Morteza Bashsiz de4606d884 Version 1.1.58
Add bufferSize to config
2026-06-14 09:48:11 +02:00
Morteza Bashsiz 4860804ef1 Version 1.1.58 (Dev)
Add bufferSize to config
Implement Buffer size configurable
2026-06-11 22:44:37 +02:00
Morteza Bashsiz d9c3a45074 Add bufferSize to config 2026-06-11 22:40:32 +02:00
lorem10 33adcf9541 chore(nix): bump version to 1.1.57 2026-06-10 17:30:29 +03:30
lorem10 02920acb49 docs: add Nix guide 2026-06-10 17:18:48 +03:30
lorem10 b250ec47a9 feat: add Nix Flake 2026-06-10 17:18:48 +03:30
Morteza Bashsiz 8e677a826d Merge pull request #220 from MortezaBashsiz/dev
Version 1.1.57
2026-06-09 16:07:09 +02:00
Morteza Bashsiz 2e2ef18529 Merge pull request #219 from MortezaBashsiz/mori
Mori
2026-06-09 16:03:12 +02:00
Morteza Bashsiz fdf03a7ec7 Fix windows version 2026-06-09 15:57:37 +02:00
Morteza Bashsiz 14f7f107b7 Version 1.1.57
* fix logging issue while INFO
* Version 1.1.57
2026-06-09 15:41:17 +02:00
Morteza Bashsiz 13aa2cd816 Version 1.1.57 (#216)
* fix logging issue while INFO
* Version 1.1.57
2026-06-09 15:38:22 +02:00
Morteza Bashsiz 042998095e fix logging issue while INFO (#215) 2026-06-09 15:13:40 +02:00
Morteza Bashsiz a006ba4e0c Merge pull request #212 from MortezaBashsiz/dev
Version 1.1.56
2026-06-07 20:36:51 +02:00
Morteza Bashsiz 413bffba44 Version 1.1.56
Version 1.1.56
2026-06-07 20:25:44 +02:00
Morteza Bashsiz 3b2c01b095 Merge branch 'dev' into mori 2026-06-07 20:25:20 +02:00
Morteza Bashsiz 4c6a00e801 Version 1.1.56 2026-06-07 20:23:26 +02:00
Morteza Bashsiz c2dc1487a2 Version 1.1.55
Version 1.1.55
2026-06-07 20:15:34 +02:00
Morteza Bashsiz 4df70ae101 Merge pull request #209 from MortezaBashsiz/mori
fix version
2026-06-07 20:14:06 +02:00
Morteza Bashsiz 49026a2f0d fix version 2026-06-07 20:13:15 +02:00
Morteza Bashsiz 7c82f7f3b5 Versin 1.1.55
Versin 1.1.55
2026-06-07 19:02:48 +02:00
Morteza Bashsiz 3a965c904f Merge branch 'main' into dev 2026-06-07 19:00:57 +02:00
Morteza Bashsiz 1f03931aa4 Merge pull request #207 from MortezaBashsiz/mori
fix ipv6 bug
2026-06-07 18:57:43 +02:00
Morteza Bashsiz aa36749c47 fix ipv6 bug 2026-06-07 18:56:45 +02:00
Morteza Bashsiz 6535cb51b7 Fix IPv6 bug 2026-06-07 13:34:14 +02:00
Morteza Bashsiz 212003760b fix server freezing bug 2026-06-07 11:36:12 +02:00
Morteza Bashsiz 698da19a8c Merge pull request #204 from MortezaBashsiz/revert-202-dev
Revert "Version 1.1.55"
2026-06-07 07:41:46 +02:00
Morteza Bashsiz 451a169756 Revert "Version 1.1.55" 2026-06-07 07:38:50 +02:00
Morteza Bashsiz 277321306b Version 1.1.55
Version 1.1.55
2026-06-06 14:04:46 +02:00
Morteza Bashsiz d6e0161aa5 Merge pull request #201 from MortezaBashsiz/mori
Version 1.1.55
2026-06-06 14:02:13 +02:00
Morteza Bashsiz 14b0947140 Version 1.1.55 2026-06-06 14:01:16 +02:00
Morteza Bashsiz 134251779c Merge pull request #200 from MortezaBashsiz/mori
change tcpconnection handle accept method
2026-06-06 08:32:05 +02:00
Morteza Bashsiz 92d877be31 change tcpconnection handle accept method 2026-06-06 08:17:14 +02:00
Morteza Bashsiz 7e6ae56753 Version 1.1.54
In this version

Socks5 protocol is now supported. So user can choose socks5|http protocol between client and agent

Refactor of code base is done
2026-06-05 17:45:46 +02:00
Morteza Bashsiz deae50f9d4 Merge pull request #197 from MortezaBashsiz/mori
Add socks5 support
2026-06-05 16:59:20 +02:00
Morteza Bashsiz daa21a57db fix main branch support 2026-06-05 16:38:20 +02:00
Morteza Bashsiz d8f09b9fe2 Add socks5 support 2026-06-05 16:21:05 +02:00
Morteza Bashsiz aeeea2a527 Merge pull request #196 from MortezaBashsiz/mori
Refactor code with better style
2026-06-05 10:33:08 +02:00
Morteza Bashsiz 55004368e4 Refactor code with better style 2026-06-05 10:30:06 +02:00
Morteza Bashsiz d0da1c55d8 Version 1.1.53
Fix handshake bug, close connection after handshake failed
2026-06-05 07:53:48 +02:00
Morteza Bashsiz 3363a7a5d2 Fix handshake bug, close connection after handshake failed
Fix handshake bug, close connection after handshake failed
2026-06-04 23:38:55 +02:00
Morteza Bashsiz 4cdc66bdf1 Fix handshake bug, close connection after handshake failed 2026-06-04 23:36:15 +02:00
Morteza Bashsiz 2540b3a504 Add windows build 2026-06-04 18:33:56 +02:00
Morteza Bashsiz cb87555503 Version 1.1.52
Version 1.1.52
2026-06-04 17:17:48 +02:00
Morteza Bashsiz 20bb0d2b9d Version 1.1.52
Version 1.1.52
2026-06-04 17:14:08 +02:00
Morteza Bashsiz 31b7bb96a8 Version 1.1.52 2026-06-04 17:12:52 +02:00
Morteza Bashsiz 9abc319202 Add workflows for all branches & support android in threading
Add workflows for all branches & support android in threading
2026-06-04 16:51:51 +02:00
Morteza Bashsiz 6c21edfc40 Add workflows for all branches & support android in threading 2026-06-04 16:38:43 +02:00
Morteza Bashsiz 6493d88258 create workflows for all branches 2026-06-04 16:37:01 +02:00
Morteza Bashsiz ed10d097f1 fix missing args 2026-06-03 14:52:26 +02:00
Morteza Bashsiz 14ead78ff8 add release step to android dev 2026-06-02 19:25:05 +02:00
Morteza Bashsiz b1a18e243c change jthread to thread for android 2026-06-02 18:43:46 +02:00
Morteza Bashsiz 24390b6562 fix android binary action 2026-06-02 18:26:57 +02:00
Morteza Bashsiz ec4a68fdb6 Merge pull request #187 from MortezaBashsiz/dev
Fix main verion
2026-06-02 16:37:21 +02:00
Morteza Bashsiz bae6afa35b Merge pull request #186 from MortezaBashsiz/mori
Mori
2026-06-02 16:35:16 +02:00
Morteza Bashsiz 36315032d9 fix main version 2026-06-02 16:33:49 +02:00
Morteza Bashsiz 96758b6322 add android 2026-06-02 16:18:21 +02:00
Morteza Bashsiz 9b5b275275 Merge pull request #185 from MortezaBashsiz/dev
add termux version #182
2026-06-02 16:14:35 +02:00
Morteza Bashsiz 76a9e4acb0 Merge pull request #184 from MortezaBashsiz/mori
add aarch64 termux
2026-06-02 15:57:43 +02:00
Morteza Bashsiz 3b3d2f4d88 add aarch64 to the build 2026-06-02 15:55:23 +02:00
Morteza Bashsiz 9af39a5715 Merge pull request #181 from MortezaBashsiz/dev
Release arm64 and amd64
2026-06-02 09:28:44 +02:00
Morteza Bashsiz 2f043a6f83 Merge pull request #180 from MortezaBashsiz/mori
Build debian package for arm64
2026-06-02 07:26:11 +02:00
Morteza Bashsiz d94075e5c3 fix workflow dev and main 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 9f1a7c8637 fix control 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 2add09ea33 fix control 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 8beee5d127 add arm to workflow 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 84bb675b9c add arm to workflow 2026-06-02 07:09:44 +02:00
Morteza Bashsiz 67c43de80d implement pullTimeout
Add configurable
```
  # pullTimeout: unsigned short
  # Defines the timeout for I/O Operation in milliseconds.
  #   Useful to expire serverside read timer.
  pullTimeout: 50
```
Higher number helps when your network is slower
2026-06-01 15:53:38 +02:00
Morteza Bashsiz ab4580920f implement pullTimeout (#178) 2026-06-01 15:47:15 +02:00
Morteza Bashsiz c0942c4015 Implement Random fakeUrl
* implement random fakeUrl
2026-05-31 23:06:14 +02:00
Morteza Bashsiz 228aff5d63 Dev fix #167 (#174)
* Fix #167 package versioning
2026-05-29 10:46:51 +02:00
Morteza Bashsiz 5647fd2f69 Fix #167 (#171)
* Fix #167 package versioning
2026-05-29 10:00:14 +02:00
Morteza Bashsiz 92a290cca7 Merge pull request #169 from MortezaBashsiz/dev
Fix #167
2026-05-29 09:20:47 +02:00
Morteza Bashsiz 108b9729c7 Merge pull request #168 from MortezaBashsiz/mori
Fix #167
2026-05-29 09:17:28 +02:00
Morteza Bashsiz 7baaf6aefb Fix #167 package versioning 2026-05-29 08:40:03 +02:00
Morteza Bashsiz 4793a3f0e3 update workflows action 2026-05-29 01:27:44 +02:00
Morteza Bashsiz c8cd4066d7 Merge pull request #166 from MortezaBashsiz/dev
Fix segmentation fault
Improve performance
Move tls config to general
2026-05-28 18:25:46 +02:00
Morteza Bashsiz 33a4dbd0b8 Merge pull request #165 from MortezaBashsiz/mori
fix segmentation fault issue
2026-05-28 18:21:32 +02:00
Morteza Bashsiz 01d8b36ca0 fix segmentation fault issue 2026-05-28 10:07:23 +02:00
Morteza Bashsiz cd7b985da1 move all tls configs to general 2026-05-28 09:09:09 +02:00
Morteza Bashsiz 80c631f66b Merge pull request #164 from MortezaBashsiz/dev
Merge from dev version v1-1-41
2026-05-26 20:58:56 +02:00
Morteza Bashsiz 8a1fcde280 Merge pull request #163 from MortezaBashsiz/mori
Mori
2026-05-26 16:52:07 +02:00
Morteza Bashsiz 51feb98dc3 fix segmentation fault for server and test connectionReuse 2026-05-26 16:37:48 +02:00
Morteza Bashsiz 560b5d93cc dummy commit 2026-05-26 14:03:01 +02:00
Morteza Bashsiz 97ee705eec dummy commit 2026-05-26 14:00:31 +02:00
Morteza Bashsiz 8d1ecfc2dc dummy commit 2026-05-26 13:55:11 +02:00
Morteza Bashsiz b402144e9e Update config 2026-05-26 13:27:39 +02:00
Morteza Bashsiz e7c8cb51cc See if behind cf fixed or not 2026-05-26 13:07:15 +02:00
Morteza Bashsiz 51fd1d47cc test if it works behind cf 2026-05-26 12:02:39 +02:00
Morteza Bashsiz 251b0202e8 Try to implement connectionReuse 2026-05-26 09:59:48 +02:00
Morteza Bashsiz 10e4481376 Merge pull request #153 from MortezaBashsiz/dev
Random endpoint and method
2026-05-06 13:19:59 +02:00
Morteza Bashsiz 47b56af86e Merge pull request #152 from MortezaBashsiz/mori
Random endpoint and method
2026-05-06 12:34:08 +02:00
Morteza Bashsiz 1c8d2d610b add random endPoint 2026-05-06 10:47:17 +02:00
Morteza Bashsiz 86f2b750a8 add random method 2026-05-06 10:18:48 +02:00
Morteza Bashsiz 0e4c1bf00d Implement tunnel mode
Implement tunnel mode beside http mode, So you can configure if you like to have the connection between agent and data in tunnel or pure HTTP request/response
2026-05-04 12:39:52 +02:00
Morteza Bashsiz 1452c1bd82 Merge pull request #150 from MortezaBashsiz/mori
Implement tunnel mode beside http mode, So you can configure if you like to have the connection between agent and data in tunnel or pure HTTP request/response
2026-05-04 11:59:56 +02:00
Morteza Bashsiz 09d5e25509 rename function from browser to client 2026-05-04 11:33:22 +02:00
Morteza Bashsiz 73f9cb01c1 implement the tunnel mode 2026-05-04 09:35:33 +02:00
Morteza Bashsiz 88bf0953e3 Start to add tunnel mode as configurable 2026-05-02 17:20:36 +02:00
Morteza Bashsiz 83fbb7adf2 fix branch in mori action 2026-05-01 23:20:39 +02:00
Morteza Bashsiz 7ac2fb293f remove anonymous namespaces and use struct instead 2026-05-01 23:18:52 +02:00
Morteza Bashsiz f70ef566d7 Merge pull request #149 from MortezaBashsiz/dev
Update readme
Update actions
2026-05-01 21:00:09 +02:00
Morteza Bashsiz 064fe1614a Merge pull request #148 from MortezaBashsiz/mori
Change readme
2026-05-01 20:58:07 +02:00
Morteza Bashsiz 323380afa5 change readme 2026-05-01 20:56:56 +02:00
Morteza Bashsiz f2b63aacb9 init mori branch 2026-05-01 20:53:50 +02:00
Morteza Bashsiz d968046d8b Merge pull request #146 from MortezaBashsiz/dev
Implement pure HTTP interaction between server and agent
2026-04-30 14:35:12 +02:00
Morteza Bashsiz a9d290c788 Merge pull request #145 from MortezaBashsiz/mori/cf
Mori/cf
2026-04-30 13:34:55 +02:00
Morteza Bashsiz 268dcfb207 remove unused chunkHeader 2026-04-30 12:47:00 +02:00
Morteza Bashsiz f3bd05787b test http mode 2026-04-30 10:03:30 +02:00
Morteza Bashsiz 9f7e6ab713 Merge pull request #144 from MortezaBashsiz/dev
Change read bytes from exactly(1) to at_least(1)
2026-04-28 08:08:39 +02:00
Morteza Bashsiz 62d34bd3e8 Merge pull request #143 from MortezaBashsiz/mori/cf
return encryption
2026-04-23 10:53:19 +02:00
Morteza Bashsiz 97bb609bd6 return encryption 2026-04-23 10:27:46 +02:00
Morteza Bashsiz 7b6a23f508 Merge pull request #142 from MortezaBashsiz/dev
Fix tls enable true and false
2026-04-22 14:43:18 +02:00
Morteza Bashsiz 5473b4b7b1 Merge pull request #141 from MortezaBashsiz/mori/cf
Resolve tlsEnable true and false issue
2026-04-22 14:38:22 +02:00
Morteza Bashsiz 9cfe163ac2 fix tlsEnable true and false 2026-04-22 14:14:58 +02:00
Morteza Bashsiz b6a8954a4b fix tlsEnable true and false 2026-04-22 14:13:25 +02:00
Morteza Bashsiz 61a8b4ddae Remove all comments 2026-04-21 08:10:51 +02:00
Morteza Bashsiz 576bef360d change connect method 2026-04-20 14:20:24 +02:00
Morteza Bashsiz 750ed871c8 remove http2 2026-04-17 15:49:36 +02:00
Morteza Bashsiz cd3c88f90d check the cf 2026-04-17 15:36:39 +02:00
Morteza Bashsiz 78adf29ff2 check the cf 2026-04-17 15:30:03 +02:00
Morteza Bashsiz cf012afa87 Merge pull request #138 from MortezaBashsiz/dev
Dev
2026-04-15 13:04:08 +02:00
Morteza Bashsiz 4c0a3c4df7 Merge pull request #137 from MortezaBashsiz/dev
Dev
2026-04-15 08:36:11 +02:00
Morteza Bashsiz b46529b2c2 Merge pull request #136 from MortezaBashsiz/dev
make compatible with boost 1.89.0
2026-04-14 17:44:08 +02:00
Morteza Bashsiz 21fec88b6e Merge pull request #135 from MortezaBashsiz/dev
upgrade artifact
2025-11-24 14:03:22 +01:00
61 changed files with 7379 additions and 8517 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
.git
.github
build
cmake-build-*
*.deb
*.tar.gz
*.log
+157
View File
@@ -0,0 +1,157 @@
name: Build Android Binary - dev
on:
workflow_dispatch:
push:
branches:
- dev
paths:
- 'core/src/**'
- 'core/**'
- 'CMakeLists.txt'
- 'core/CMakeLists.txt'
- '.github/workflows/android-dev.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 0.1.${{ github.run_number }}
jobs:
build-android:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
ninja-build \
git \
curl \
zip \
unzip \
tar \
pkg-config \
autoconf \
autoconf-archive \
automake \
libtool
- name: Setup Android NDK r29
uses: nttld/setup-ndk@v1
with:
ndk-version: r29
add-to-path: true
- name: Show Android NDK information
run: |
echo "ANDROID_NDK_HOME=$ANDROID_NDK_HOME"
echo "ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT"
ls -lah "$ANDROID_NDK_HOME"
- name: Setup vcpkg
run: |
git clone https://github.com/microsoft/vcpkg.git "$HOME/vcpkg"
"$HOME/vcpkg/bootstrap-vcpkg.sh"
echo "VCPKG_ROOT=$HOME/vcpkg" >> "$GITHUB_ENV"
echo "$HOME/vcpkg" >> "$GITHUB_PATH"
- name: Build Android dependencies
run: |
"$VCPKG_ROOT/vcpkg" install \
boost:arm64-android \
openssl:arm64-android \
yaml-cpp:arm64-android
- name: Configure Android arm64-v8a build
run: |
rm -rf build-android-arm64
cmake -S . -B build-android-arm64 \
-G Ninja \
-DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \
-DVCPKG_TARGET_TRIPLET=arm64-android \
-DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake" \
-DANDROID_ABI=arm64-v8a \
-DANDROID_PLATFORM=android-23 \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_EXE_LINKER_FLAGS="-Wl,-z,max-page-size=16384" \
-DCMAKE_SHARED_LINKER_FLAGS="-Wl,-z,max-page-size=16384"
- name: Build Android arm64-v8a binary
run: |
cmake --build build-android-arm64 -j"$(nproc)"
- name: Collect Android binary and libraries
run: |
mkdir -p out/android/arm64-v8a
if [ ! -f build-android-arm64/core/nipovpn ]; then
echo "Android binary not found:"
find build-android-arm64 -type f || true
exit 1
fi
cp build-android-arm64/core/nipovpn out/android/arm64-v8a/libnipovpn_dev_"${{ env.PACKAGE_VERSION }}".so
chmod 755 out/android/arm64-v8a/libnipovpn_dev_"${{ env.PACKAGE_VERSION }}".so
find "$VCPKG_ROOT/installed/arm64-android" -type f -name "*.so*" -exec cp -v {} out/android/arm64-v8a/ \; || true
ls -lah out/android/arm64-v8a/
- name: Check 16 KB ELF alignment
run: |
READELF="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf"
for file in out/android/arm64-v8a/*.so*; do
echo "Checking $file"
"$READELF" -l "$file" | grep -A3 LOAD || true
if "$READELF" -l "$file" | awk '/LOAD/ && $NF != "0x4000" { bad=1 } END { exit bad }'; then
echo "OK: $file is 16 KB aligned"
else
echo "ERROR: $file is not 16 KB aligned"
exit 1
fi
done
- name: Upload Android artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-dev-android-arm64-v8a
path: out/android/arm64-v8a/
release-android:
needs:
- build-android
runs-on: ubuntu-24.04
steps:
- name: Download Android artifact
uses: actions/download-artifact@v4
with:
name: nipovpn-dev-android-arm64-v8a
path: ./android-artifact
- name: Show downloaded Android artifact
run: |
ls -lah android-artifact
- name: Create Android GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: dev-android-v${{ env.PACKAGE_VERSION }}
name: dev Android Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
android-artifact/*
env:
GITHUB_TOKEN: ${{ github.token }}
+157
View File
@@ -0,0 +1,157 @@
name: Build Android Binary - main
on:
workflow_dispatch:
push:
branches:
- main
paths:
- 'core/src/**'
- 'core/**'
- 'CMakeLists.txt'
- 'core/CMakeLists.txt'
- '.github/workflows/android-main.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 2.1.0
jobs:
build-android:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
ninja-build \
git \
curl \
zip \
unzip \
tar \
pkg-config \
autoconf \
autoconf-archive \
automake \
libtool
- name: Setup Android NDK r29
uses: nttld/setup-ndk@v1
with:
ndk-version: r29
add-to-path: true
- name: Show Android NDK information
run: |
echo "ANDROID_NDK_HOME=$ANDROID_NDK_HOME"
echo "ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT"
ls -lah "$ANDROID_NDK_HOME"
- name: Setup vcpkg
run: |
git clone https://github.com/microsoft/vcpkg.git "$HOME/vcpkg"
"$HOME/vcpkg/bootstrap-vcpkg.sh"
echo "VCPKG_ROOT=$HOME/vcpkg" >> "$GITHUB_ENV"
echo "$HOME/vcpkg" >> "$GITHUB_PATH"
- name: Build Android dependencies
run: |
"$VCPKG_ROOT/vcpkg" install \
boost:arm64-android \
openssl:arm64-android \
yaml-cpp:arm64-android
- name: Configure Android arm64-v8a build
run: |
rm -rf build-android-arm64
cmake -S . -B build-android-arm64 \
-G Ninja \
-DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \
-DVCPKG_TARGET_TRIPLET=arm64-android \
-DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake" \
-DANDROID_ABI=arm64-v8a \
-DANDROID_PLATFORM=android-23 \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_EXE_LINKER_FLAGS="-Wl,-z,max-page-size=16384" \
-DCMAKE_SHARED_LINKER_FLAGS="-Wl,-z,max-page-size=16384"
- name: Build Android arm64-v8a binary
run: |
cmake --build build-android-arm64 -j"$(nproc)"
- name: Collect Android binary and libraries
run: |
mkdir -p out/android/arm64-v8a
if [ ! -f build-android-arm64/core/nipovpn ]; then
echo "Android binary not found:"
find build-android-arm64 -type f || true
exit 1
fi
cp build-android-arm64/core/nipovpn out/android/arm64-v8a/libnipovpn_"${{ env.PACKAGE_VERSION }}".so
chmod 755 out/android/arm64-v8a/libnipovpn_"${{ env.PACKAGE_VERSION }}".so
find "$VCPKG_ROOT/installed/arm64-android" -type f -name "*.so*" -exec cp -v {} out/android/arm64-v8a/ \; || true
ls -lah out/android/arm64-v8a/
- name: Check 16 KB ELF alignment
run: |
READELF="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf"
for file in out/android/arm64-v8a/*.so*; do
echo "Checking $file"
"$READELF" -l "$file" | grep -A3 LOAD || true
if "$READELF" -l "$file" | awk '/LOAD/ && $NF != "0x4000" { bad=1 } END { exit bad }'; then
echo "OK: $file is 16 KB aligned"
else
echo "ERROR: $file is not 16 KB aligned"
exit 1
fi
done
- name: Upload Android artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-main-android-arm64-v8a
path: out/android/arm64-v8a/
release-android:
needs:
- build-android
runs-on: ubuntu-24.04
steps:
- name: Download Android artifact
uses: actions/download-artifact@v4
with:
name: nipovpn-main-android-arm64-v8a
path: ./android-artifact
- name: Show downloaded Android artifact
run: |
ls -lah android-artifact
- name: Create Android GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: android-v${{ env.PACKAGE_VERSION }}
name: Android Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
android-artifact/*
env:
GITHUB_TOKEN: ${{ github.token }}
+301 -40
View File
@@ -1,4 +1,4 @@
name: Build and Release Debian Package
name: Build and Release Package - dev
on:
push:
@@ -6,70 +6,331 @@ on:
- dev
paths:
- 'core/src/**'
- '.github/workflows/**'
- 'core/**'
- 'nipovpn/**'
- '.github/workflows/debian-dev.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 0.1.${{ github.run_number }}
jobs:
build:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
package_arch: amd64
- arch: arm64
package_arch: arm64
steps:
- name: Checkout source code
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Set up dependencies
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
platforms: arm64
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y dpkg-dev build-essential lintian fakeroot devscripts cmake libssl-dev libboost-all-dev libyaml-cpp-dev
sudo apt-get install -y \
dpkg-dev \
build-essential \
lintian \
fakeroot \
devscripts \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
- name: Build the package
- name: Build binary
run: |
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Debug ..
make -j$(nproc)
cd ..
mkdir -p nipovpn/usr/bin/
cp build/core/nipovpn nipovpn/usr/bin/nipovpn
dpkg-deb --build nipovpn/ build/nipovpn_staging_v1-1-${{ github.run_number }}.deb
rm -rf build
- name: Upload the Debian nipovpn as an artifact
if [ "${{ matrix.arch }}" = "arm64" ]; then
docker run --rm --platform linux/arm64 \
-v "$PWD:/src" \
-w /src \
ubuntu:24.04 \
bash -c '
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y \
build-essential \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
'
sudo chown -R $USER:$USER build
else
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
fi
- name: Build Debian package
run: |
PACKAGE_FILE="nipovpn_dev_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
rm -rf package-root
cp -a nipovpn package-root
mkdir -p package-root/usr/bin
cp build/core/nipovpn package-root/usr/bin/nipovpn
chmod 755 package-root/usr/bin/nipovpn
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" package-root/DEBIAN/control
sed -i -E "s/^Architecture[[:space:]]*:.*/Architecture: ${{ matrix.package_arch }}/" package-root/DEBIAN/control
sed -i -e '$a\' package-root/DEBIAN/control
mkdir -p package-root/DEBIAN
cat > package-root/DEBIAN/conffiles <<'EOF'
/etc/nipovpn/config.yaml
EOF
rm -f package-root/var/log/nipovpn/nipovpn.log
mkdir -p package-root/var/log/nipovpn
cat > package-root/DEBIAN/postinst <<'EOF'
#!/bin/sh
set -e
mkdir -p /var/log/nipovpn
if [ ! -f /var/log/nipovpn/nipovpn.log ]; then
touch /var/log/nipovpn/nipovpn.log
chmod 0644 /var/log/nipovpn/nipovpn.log
fi
exit 0
EOF
chmod 755 package-root/DEBIAN/postinst
echo "Final control file:"
cat package-root/DEBIAN/control
grep "^Version: ${PACKAGE_VERSION}$" package-root/DEBIAN/control
grep "^Architecture: ${{ matrix.package_arch }}$" package-root/DEBIAN/control
mkdir -p build
dpkg-deb --build package-root "build/${PACKAGE_FILE}"
ls -lah build/
- name: Show Debian package information
run: |
PACKAGE_FILE="nipovpn_dev_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
dpkg -I "build/${PACKAGE_FILE}"
dpkg -c "build/${PACKAGE_FILE}"
- name: Upload Debian package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn
path: build/nipovpn_staging_v1-1-${{ github.run_number }}.deb
name: nipovpn-dev-deb-${{ matrix.arch }}
path: build/nipovpn_dev_${{ env.PACKAGE_VERSION }}_${{ matrix.arch }}.deb
- name: Show nipovpn information
build-termux:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
with:
path: nipovpn-src
- name: Install host dependencies
run: |
dpkg -I build/nipovpn_staging_v1-1-${{ github.run_number }}.deb
sudo apt-get update
sudo apt-get install -y \
git \
wget \
unzip \
curl \
python3 \
python3-pip \
build-essential \
cmake \
ninja-build \
pkg-config \
autoconf \
automake \
libtool \
autopoint \
bison \
flex \
gettext \
gperf \
help2man \
lzip \
libarchive-tools \
rsync \
texinfo \
jq
- name: Clone termux-packages
run: |
git clone --depth=1 https://github.com/termux/termux-packages.git
- name: Install Android NDK required by termux-packages
run: |
NDK_NUM="$(sed -n 's/^: "${TERMUX_NDK_VERSION_NUM:="\([0-9]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
NDK_REV="$(sed -n 's/^: "${TERMUX_NDK_REVISION:="\([a-z]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
if [ -z "$NDK_NUM" ]; then
echo "Could not read the NDK version from termux-packages/scripts/properties.sh"
grep -n NDK termux-packages/scripts/properties.sh || true
exit 1
fi
NDK_VERSION="r${NDK_NUM}${NDK_REV}"
echo "termux-packages requires Android NDK $NDK_VERSION"
mkdir -p "$HOME/lib"
cd "$HOME/lib"
wget -q "https://dl.google.com/android/repository/android-ndk-${NDK_VERSION}-linux.zip"
unzip -q "android-ndk-${NDK_VERSION}-linux.zip"
EXTRACTED_DIR="$(find "$HOME/lib" -maxdepth 1 -type d -name "android-ndk-${NDK_VERSION}*" | head -n 1)"
if [ -z "$EXTRACTED_DIR" ]; then
echo "Android NDK $NDK_VERSION directory not found"
ls -lah "$HOME/lib"
exit 1
fi
if [ "$EXTRACTED_DIR" != "$HOME/lib/android-ndk-${NDK_VERSION}" ]; then
ln -sfn "$EXTRACTED_DIR" "$HOME/lib/android-ndk-${NDK_VERSION}"
fi
echo "NDK=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
echo "ANDROID_NDK_ROOT=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
ls -ld "$HOME/lib/android-ndk-${NDK_VERSION}"
- name: Create Termux package recipe
run: |
mkdir -p termux-packages/packages/nipovpn
cat > termux-packages/packages/nipovpn/build.sh <<'EOF'
TERMUX_PKG_HOMEPAGE=https://github.com/MortezaBashsiz/nipovpn
TERMUX_PKG_DESCRIPTION="Powerful and secure HTTP/S proxy"
TERMUX_PKG_LICENSE="MIT"
TERMUX_PKG_MAINTAINER="Morteza Bashsiz"
TERMUX_PKG_VERSION=@PACKAGE_VERSION@
TERMUX_PKG_SRCURL=file://@GITHUB_WORKSPACE@/nipovpn-src
TERMUX_PKG_SHA256=SKIP_CHECKSUM
TERMUX_PKG_DEPENDS="openssl, boost, libyaml-cpp"
TERMUX_PKG_BUILD_IN_SRC=false
termux_step_configure() {
cmake -S "$TERMUX_PKG_SRCDIR" \
-B "$TERMUX_PKG_BUILDDIR" \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX="$TERMUX_PREFIX"
}
termux_step_make() {
cmake --build "$TERMUX_PKG_BUILDDIR" -j "$(nproc)"
}
termux_step_make_install() {
install -Dm755 \
"$TERMUX_PKG_BUILDDIR/core/nipovpn" \
"$TERMUX_PREFIX/bin/nipovpn"
if [ -d "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn" ]; then
mkdir -p "$TERMUX_PREFIX/etc/nipovpn"
cp -a "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn/." \
"$TERMUX_PREFIX/etc/nipovpn/"
fi
}
EOF
sed -i "s|@PACKAGE_VERSION@|${PACKAGE_VERSION}|g" termux-packages/packages/nipovpn/build.sh
sed -i "s|@GITHUB_WORKSPACE@|${GITHUB_WORKSPACE}|g" termux-packages/packages/nipovpn/build.sh
cat termux-packages/packages/nipovpn/build.sh
- name: Prepare Termux build data dir
run: |
sudo mkdir -p /data
sudo chown -R $USER:$USER /data
- name: Build Termux aarch64 package
working-directory: termux-packages
run: |
./build-package.sh -I -a aarch64 nipovpn
- name: Collect Termux package
run: |
mkdir -p out
TERMUX_DEB="$(find termux-packages/output -type f -name '*.deb' | head -n 1)"
if [ -z "$TERMUX_DEB" ]; then
echo "No Termux .deb package found"
find termux-packages/output -type f || true
exit 1
fi
cp "$TERMUX_DEB" "out/nipovpn_dev_${PACKAGE_VERSION}_termux_aarch64.deb"
ls -lah out/
- name: Upload Termux package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-dev-termux-aarch64
path: out/nipovpn_dev_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
release:
needs: build
needs:
- build
- build-termux
runs-on: ubuntu-latest
steps:
- name: Download build artifact
- name: Download package artifacts
uses: actions/download-artifact@v4
with:
name: nipovpn
pattern: nipovpn-dev-*
merge-multiple: true
path: ./
- name: Create GitHub Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
with:
tag_name: 'v.0.1.1.${{ github.run_number }}'
release_name: Staging v.0.1.1.${{ github.run_number }}
draft: false
prerelease: true
- name: Show downloaded files
run: |
ls -lah
- name: Upload Debian Package to Release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
- name: Create dev GitHub Release
uses: softprops/action-gh-release@v2
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./nipovpn_staging_v1-1-${{ github.run_number }}.deb
asset_name: nipovpn_staging_v1-1-${{ github.run_number }}.deb
asset_content_type: application/octet-stream
tag_name: dev-v${{ env.PACKAGE_VERSION }}
name: dev Version v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
nipovpn_dev_${{ env.PACKAGE_VERSION }}_amd64.deb
nipovpn_dev_${{ env.PACKAGE_VERSION }}_arm64.deb
nipovpn_dev_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
env:
GITHUB_TOKEN: ${{ github.token }}
+336
View File
@@ -0,0 +1,336 @@
name: Build and Release Package - main
on:
push:
branches:
- main
paths:
- 'core/src/**'
- 'core/**'
- 'nipovpn/**'
- '.github/workflows/debian-main.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 2.1.0
jobs:
build:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
package_arch: amd64
- arch: arm64
package_arch: arm64
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
platforms: arm64
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
dpkg-dev \
build-essential \
lintian \
fakeroot \
devscripts \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
- name: Build binary
run: |
rm -rf build
if [ "${{ matrix.arch }}" = "arm64" ]; then
docker run --rm --platform linux/arm64 \
-v "$PWD:/src" \
-w /src \
ubuntu:24.04 \
bash -c '
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y \
build-essential \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
'
sudo chown -R $USER:$USER build
else
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
fi
- name: Build Debian package
run: |
PACKAGE_FILE="nipovpn_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
rm -rf package-root
cp -a nipovpn package-root
mkdir -p package-root/usr/bin
cp build/core/nipovpn package-root/usr/bin/nipovpn
chmod 755 package-root/usr/bin/nipovpn
sed -i -E "s/^Version[[:space:]]*:.*/Version: ${PACKAGE_VERSION}/" package-root/DEBIAN/control
sed -i -E "s/^Architecture[[:space:]]*:.*/Architecture: ${{ matrix.package_arch }}/" package-root/DEBIAN/control
sed -i -e '$a\' package-root/DEBIAN/control
mkdir -p package-root/DEBIAN
cat > package-root/DEBIAN/conffiles <<'EOF'
/etc/nipovpn/config.yaml
EOF
rm -f package-root/var/log/nipovpn/nipovpn.log
mkdir -p package-root/var/log/nipovpn
cat > package-root/DEBIAN/postinst <<'EOF'
#!/bin/sh
set -e
mkdir -p /var/log/nipovpn
if [ ! -f /var/log/nipovpn/nipovpn.log ]; then
touch /var/log/nipovpn/nipovpn.log
chmod 0644 /var/log/nipovpn/nipovpn.log
fi
exit 0
EOF
chmod 755 package-root/DEBIAN/postinst
echo "Final control file:"
cat package-root/DEBIAN/control
grep "^Version: ${PACKAGE_VERSION}$" package-root/DEBIAN/control
grep "^Architecture: ${{ matrix.package_arch }}$" package-root/DEBIAN/control
mkdir -p build
dpkg-deb --build package-root "build/${PACKAGE_FILE}"
ls -lah build/
- name: Show Debian package information
run: |
PACKAGE_FILE="nipovpn_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
dpkg -I "build/${PACKAGE_FILE}"
dpkg -c "build/${PACKAGE_FILE}"
- name: Upload Debian package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-deb-${{ matrix.arch }}
path: build/nipovpn_${{ env.PACKAGE_VERSION }}_${{ matrix.arch }}.deb
build-termux:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
with:
path: nipovpn-src
- name: Install host dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
git \
wget \
unzip \
curl \
python3 \
python3-pip \
build-essential \
cmake \
ninja-build \
pkg-config \
autoconf \
automake \
libtool \
autopoint \
bison \
flex \
gettext \
gperf \
help2man \
lzip \
libarchive-tools \
rsync \
texinfo \
jq
- name: Clone termux-packages
run: |
git clone --depth=1 https://github.com/termux/termux-packages.git
- name: Install Android NDK required by termux-packages
run: |
NDK_NUM="$(sed -n 's/^: "${TERMUX_NDK_VERSION_NUM:="\([0-9]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
NDK_REV="$(sed -n 's/^: "${TERMUX_NDK_REVISION:="\([a-z]*\)"}"/\1/p' termux-packages/scripts/properties.sh)"
if [ -z "$NDK_NUM" ]; then
echo "Could not read the NDK version from termux-packages/scripts/properties.sh"
grep -n NDK termux-packages/scripts/properties.sh || true
exit 1
fi
NDK_VERSION="r${NDK_NUM}${NDK_REV}"
echo "termux-packages requires Android NDK $NDK_VERSION"
mkdir -p "$HOME/lib"
cd "$HOME/lib"
wget -q "https://dl.google.com/android/repository/android-ndk-${NDK_VERSION}-linux.zip"
unzip -q "android-ndk-${NDK_VERSION}-linux.zip"
EXTRACTED_DIR="$(find "$HOME/lib" -maxdepth 1 -type d -name "android-ndk-${NDK_VERSION}*" | head -n 1)"
if [ -z "$EXTRACTED_DIR" ]; then
echo "Android NDK $NDK_VERSION directory not found"
ls -lah "$HOME/lib"
exit 1
fi
if [ "$EXTRACTED_DIR" != "$HOME/lib/android-ndk-${NDK_VERSION}" ]; then
ln -sfn "$EXTRACTED_DIR" "$HOME/lib/android-ndk-${NDK_VERSION}"
fi
echo "NDK=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
echo "ANDROID_NDK_ROOT=$HOME/lib/android-ndk-${NDK_VERSION}" >> "$GITHUB_ENV"
ls -ld "$HOME/lib/android-ndk-${NDK_VERSION}"
- name: Create Termux package recipe
run: |
mkdir -p termux-packages/packages/nipovpn
cat > termux-packages/packages/nipovpn/build.sh <<'EOF'
TERMUX_PKG_HOMEPAGE=https://github.com/MortezaBashsiz/nipovpn
TERMUX_PKG_DESCRIPTION="Powerful and secure HTTP/S proxy"
TERMUX_PKG_LICENSE="MIT"
TERMUX_PKG_MAINTAINER="Morteza Bashsiz"
TERMUX_PKG_VERSION=@PACKAGE_VERSION@
TERMUX_PKG_SRCURL=file://@GITHUB_WORKSPACE@/nipovpn-src
TERMUX_PKG_SHA256=SKIP_CHECKSUM
TERMUX_PKG_DEPENDS="openssl, boost, libyaml-cpp"
TERMUX_PKG_BUILD_IN_SRC=false
termux_step_configure() {
cmake -S "$TERMUX_PKG_SRCDIR" \
-B "$TERMUX_PKG_BUILDDIR" \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX="$TERMUX_PREFIX"
}
termux_step_make() {
cmake --build "$TERMUX_PKG_BUILDDIR" -j "$(nproc)"
}
termux_step_make_install() {
install -Dm755 \
"$TERMUX_PKG_BUILDDIR/core/nipovpn" \
"$TERMUX_PREFIX/bin/nipovpn"
if [ -d "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn" ]; then
mkdir -p "$TERMUX_PREFIX/etc/nipovpn"
cp -a "$TERMUX_PKG_SRCDIR/nipovpn/etc/nipovpn/." \
"$TERMUX_PREFIX/etc/nipovpn/"
fi
}
EOF
sed -i "s|@PACKAGE_VERSION@|${PACKAGE_VERSION}|g" termux-packages/packages/nipovpn/build.sh
sed -i "s|@GITHUB_WORKSPACE@|${GITHUB_WORKSPACE}|g" termux-packages/packages/nipovpn/build.sh
cat termux-packages/packages/nipovpn/build.sh
- name: Prepare Termux build data dir
run: |
sudo mkdir -p /data
sudo chown -R $USER:$USER /data
- name: Build Termux aarch64 package
working-directory: termux-packages
run: |
./build-package.sh -I -a aarch64 nipovpn
- name: Collect Termux package
run: |
mkdir -p out
TERMUX_DEB="$(find termux-packages/output -type f -name '*.deb' | head -n 1)"
if [ -z "$TERMUX_DEB" ]; then
echo "No Termux .deb package found"
find termux-packages/output -type f || true
exit 1
fi
cp "$TERMUX_DEB" "out/nipovpn_${PACKAGE_VERSION}_termux_aarch64.deb"
ls -lah out/
- name: Upload Termux package artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-termux-aarch64
path: out/nipovpn_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
release:
needs:
- build
- build-termux
runs-on: ubuntu-latest
steps:
- name: Download package artifacts
uses: actions/download-artifact@v4
with:
pattern: nipovpn-*
merge-multiple: true
path: ./
- name: Show downloaded files
run: |
ls -lah
- name: Create main GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: v${{ env.PACKAGE_VERSION }}
name: Version v${{ env.PACKAGE_VERSION }}
prerelease: true
files: |
nipovpn_${{ env.PACKAGE_VERSION }}_amd64.deb
nipovpn_${{ env.PACKAGE_VERSION }}_arm64.deb
nipovpn_${{ env.PACKAGE_VERSION }}_termux_aarch64.deb
env:
GITHUB_TOKEN: ${{ github.token }}
-75
View File
@@ -1,75 +0,0 @@
name: Build and Release Debian Package
on:
push:
branches:
- main
paths:
- 'core/src/**'
jobs:
build:
runs-on: ubuntu-24.04
steps:
- name: Checkout source code
uses: actions/checkout@v3
- name: Set up dependencies
run: |
sudo apt-get update
sudo apt-get install -y dpkg-dev build-essential lintian fakeroot devscripts cmake libssl-dev libboost-all-dev libyaml-cpp-dev
- name: Build the package
run: |
mkdir -p build
cd build
cmake -DCMAKE_BUILD_TYPE=Debug ..
make -j$(nproc)
cd ..
mkdir -p nipovpn/usr/bin/
cp build/core/nipovpn nipovpn/usr/bin/nipovpn
dpkg-deb --build nipovpn/ build/nipovpn_v1-1-${{ github.run_number }}.deb
- name: Upload the Debian nipovpn as an artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn
path: build/nipovpn_v1-1-${{ github.run_number }}.deb
- name: Show nipovpn information
run: |
dpkg -I build/nipovpn_v1-1-${{ github.run_number }}.deb
release:
needs: build
runs-on: ubuntu-latest
steps:
- name: Download build artifact
uses: actions/download-artifact@v4
with:
name: nipovpn
path: ./
- name: Create GitHub Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
with:
tag_name: 'v1.1.${{ github.run_number }}'
release_name: Version v1.1.${{ github.run_number }}
draft: false
prerelease: false
- name: Upload Debian Package to Release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./nipovpn_v1-1-${{ github.run_number }}.deb
asset_name: nipovpn_v1-1-${{ github.run_number }}.deb
asset_content_type: application/octet-stream
+76
View File
@@ -0,0 +1,76 @@
name: Tests
on:
workflow_dispatch:
pull_request:
branches:
- main
- dev
paths:
- 'core/**'
- 'CMakeLists.txt'
- 'nipovpn/etc/nipovpn/config.yaml'
- 'tests/**'
- '.github/workflows/test.yml'
permissions:
contents: read
concurrency:
group: tests-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
e2e:
name: End-to-end (${{ matrix.build }})
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- build: release
build_type: Release
cxx_flags: ""
- build: sanitizers
build_type: RelWithDebInfo
cxx_flags: "-fsanitize=address,undefined -fno-omit-frame-pointer"
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
libssl-dev \
libboost-all-dev \
libyaml-cpp-dev \
python3-yaml \
curl \
openssl
- name: Build
run: |
cmake -S . -B build \
-DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \
-DCMAKE_CXX_FLAGS="${{ matrix.cxx_flags }}"
cmake --build build -j"$(nproc)"
- name: Run end-to-end tests
env:
ASAN_OPTIONS: detect_leaks=0
UBSAN_OPTIONS: print_stacktrace=1
run: python3 tests/e2e.py --binary build/core/nipovpn --artifacts test-artifacts
- name: Upload logs of failed tests
if: failure()
uses: actions/upload-artifact@v4
with:
name: e2e-logs-${{ matrix.build }}
path: test-artifacts
if-no-files-found: ignore
retention-days: 14
+98
View File
@@ -0,0 +1,98 @@
name: Build Windows Binary - dev
on:
push:
branches:
- dev
paths:
- 'core/**'
- 'server/**'
- 'agent/**'
- 'CMakeLists.txt'
- '.github/workflows/windows-dev.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 0.1.${{ github.run_number }}
jobs:
build-windows:
runs-on: windows-latest
defaults:
run:
shell: msys2 {0}
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
update: true
install: >-
git
zip
mingw-w64-x86_64-gcc
mingw-w64-x86_64-cmake
mingw-w64-x86_64-ninja
mingw-w64-x86_64-boost
mingw-w64-x86_64-openssl
mingw-w64-x86_64-yaml-cpp
- name: Build nipovpn.exe
run: |
rm -rf build dist
mkdir -p build dist
cmake -S . -B build \
-G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CXX_FLAGS="-DNOMINMAX -DWIN32_LEAN_AND_MEAN -DNOGDI -DOUT=NIPO_OUT"
cmake --build build -j$(nproc)
cp build/core/nipovpn.exe dist/
- name: Copy required DLL files
run: |
cd dist
for dll in $(ldd nipovpn.exe | grep 'mingw64' | awk '{print $3}'); do
cp "$dll" .
done
ls -lah
- name: Add config files
run: |
mkdir -p dist/etc/nipovpn
if [ -d nipovpn/etc/nipovpn ]; then
cp -a nipovpn/etc/nipovpn/. dist/etc/nipovpn/
fi
- name: Create ZIP package
run: |
cd dist
zip -r ../nipovpn_dev_${PACKAGE_VERSION}_windows_x86_64.zip .
- name: Upload Windows artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-dev-windows-x86_64
path: nipovpn_dev_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
- name: Create dev Windows Release
uses: softprops/action-gh-release@v2
with:
tag_name: dev-windows-v${{ env.PACKAGE_VERSION }}
name: dev Windows Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: nipovpn_dev_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
env:
GITHUB_TOKEN: ${{ github.token }}
+99
View File
@@ -0,0 +1,99 @@
name: Build Windows Binary - main
on:
push:
branches:
- main
paths:
- 'core/**'
- 'server/**'
- 'agent/**'
- 'CMakeLists.txt'
- '.github/workflows/windows-main.yml'
permissions:
contents: write
env:
PACKAGE_VERSION: 2.1.0
jobs:
build-windows:
runs-on: windows-latest
defaults:
run:
shell: msys2 {0}
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
update: true
install: >-
git
zip
mingw-w64-x86_64-gcc
mingw-w64-x86_64-cmake
mingw-w64-x86_64-ninja
mingw-w64-x86_64-boost
mingw-w64-x86_64-openssl
mingw-w64-x86_64-yaml-cpp
- name: Build nipovpn.exe
run: |
rm -rf build dist
mkdir -p build dist
cmake -S . -B build \
-G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CXX_FLAGS="-DNOMINMAX -DWIN32_LEAN_AND_MEAN -DNOGDI -DOUT=NIPO_OUT"
cmake --build build -j$(nproc)
cp build/core/nipovpn.exe dist/
- name: Copy required DLL files
run: |
cd dist
for dll in $(ldd nipovpn.exe | grep 'mingw64' | awk '{print $3}'); do
cp "$dll" .
done
ls -lah
- name: Add config files
run: |
mkdir -p dist/etc/nipovpn
if [ -d nipovpn/etc/nipovpn ]; then
cp -a nipovpn/etc/nipovpn/. dist/etc/nipovpn/
fi
- name: Create ZIP package
run: |
cd dist
zip -r ../nipovpn_${PACKAGE_VERSION}_windows_x86_64.zip .
- name: Upload Windows artifact
uses: actions/upload-artifact@v4
with:
name: nipovpn-windows-x86_64
path: nipovpn_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
- name: Create Windows Release
uses: softprops/action-gh-release@v2
with:
tag_name: windows-v${{ env.PACKAGE_VERSION }}
name: Windows Binary v${{ env.PACKAGE_VERSION }}
prerelease: true
files: nipovpn_${{ env.PACKAGE_VERSION }}_windows_x86_64.zip
env:
GITHUB_TOKEN: ${{ github.token }}
+8
View File
@@ -37,3 +37,11 @@ build
.idea
/cmake-build-debug/
test
.git
*.deb
*.tar.gz
*.log
__pycache__/
*.pyc
+4
View File
@@ -10,6 +10,10 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -ggdb")
# Set the preprocessor flags
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -MMD -MP")
if(POLICY CMP0167)
cmake_policy(SET CMP0167 NEW)
endif()
# https://cmake.org/cmake/help/latest/module/FindBoost.html
find_package(Boost REQUIRED COMPONENTS regex OPTIONAL_COMPONENTS system)
+544 -48
View File
@@ -1,71 +1,567 @@
# NipoVPN (Not ready yet :D)
# NipoVPN
## Overview
NipoVPN is a proxy that hides your traffic inside ordinary-looking HTTP requests.
It runs in two roles: an **agent** on your side and a **server** outside the
censored or monitored network. The agent wraps each request in a decoy HTTP
request (random method, endpoint and `Host`), optionally encrypts it with
AES-256-GCM and sends it over TLS. The server unwraps it, talks to the real
destination and sends the response back the same way.
NipoVPN is a powerful proxy tool designed to conceal your HTTP requests within fake HTTP requests. This program, written in C++, leverages the Boost library to handle networking functionalities efficiently.
It is written in C++20 on top of Boost.Asio, OpenSSL and yaml-cpp.
- [Features](#features)
- [How it works](#how-it-works)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Configuration reference](#configuration-reference)
- [Security notes](#security-notes)
- [Logging](#logging)
- [Troubleshooting](#troubleshooting)
- [Contribution](#contribution)
- [License](#license)
## Features
- HTTP Request Obfuscation: Hide your legitimate HTTP requests inside decoy requests to avoid detection.
- Boost Library Integration: Utilizes Boost for robust and reliable networking operations.
- High Performance: Optimized for speed and efficiency, ensuring minimal impact on request latency.
### Client side (agent)
- **HTTP proxy and SOCKS5 proxy** for local applications (`agent.protocol`).
- HTTP: plain HTTP requests and `CONNECT` tunnels (HTTPS).
- SOCKS5: `CONNECT` command, no authentication, with IPv4, IPv6 and domain
name targets.
- **Multiple agents per server.** Each agent session is identified by a UUID, so
many agents (and many clients behind each agent) can share one server.
- **Multi-threaded.** The number of worker threads is configurable for the agent
and the server separately.
## Usecases
### Traffic obfuscation
### Bypass filtering
This could help you to bypass the filtering in your country.
- **Decoy HTTP requests.** Every request between the agent and server is a
normal HTTP request whose method, path and `Host` header are picked at random
from lists you configure (`methods`, `endPoints`, `fakeUrls`).
- **Configurable `User-Agent` and HTTP version** for the decoy requests.
- **Randomized TLS SNI.** With TLS enabled, the SNI sent to the server is also
picked at random from `fakeUrls`.
- **Hidden control data.** The session ID and action travel inside the
(encrypted) body, not in custom headers, so the outer request carries no
NipoVPN-specific headers.
### Encryption
- **AES-256-GCM payload encryption** (on by default). The key is the SHA-256 of
the user's token; each message gets a random 12-byte nonce and a 16-byte
authentication tag, so tampered or wrongly keyed payloads are rejected.
- **TLS between agent and server** (`tlsEnable`): TLS 1.2 minimum, TLS 1.3
preferred, with AEAD-only cipher suites (AES-GCM, ChaCha20-Poly1305).
- **Optional certificate verification** on the agent (`tlsVerifyPeer`) against
a custom CA (`tlsCaFile`).
AES and TLS are independent: you can use either, both, or (not recommended)
neither.
### Connection handling
- **Two tunnel modes** for `CONNECT`/SOCKS5 traffic:
- **Polling mode** (default, `tunnelEnable: false`): every chunk of tunneled
data is sent as its own decoy HTTP request (`send`), and the agent polls the
server for incoming data (`recv`). Traffic looks like many short HTTP
requests. Polling backs off from `pullTimeout` up to 50 ms while idle and
snaps back as soon as data arrives.
- **Direct tunnel mode** (`tunnelEnable: true`): after the first decoy
request, the agent–server connection becomes a raw byte pipe to the
destination. Faster, but only the opening request is disguised and
encrypted. Use it together with `tlsEnable`.
- **Connection reuse** (`connectionReuse`): keep one keep-alive connection
between agent and server instead of opening a new one per request.
- **Timeouts**: an I/O timeout that closes stalled connections (`timeout`) and
a configurable buffer size per read (`bufferSize`).
### Operations
- **Config validation at startup** with clear error messages.
- **Per-user monthly traffic limits** (e.g. 2 GB), with usage kept in an
editable file. See [Usage limits](#usage-limits).
- **Multiple users** on one server, each with their own token. Users can be
added, disabled or removed without a restart. See [Multiple users](#multiple-users).
- **Reload without restart** on `SIGHUP` (`systemctl reload`). See
[Reloading the configuration](#reloading-the-configuration).
- **Warning when the public sample token is still in use.**
- **Log levels** `INFO`, `TRACE` (per-request source/destination) and `DEBUG`;
logs go to a file and to stdout.
- **Packaging**: `.deb` packages (amd64, arm64) with systemd units, a Docker
image and compose file, a Nix flake with a NixOS module, a Termux package,
Windows (x86_64) builds and an [Android app](https://github.com/MortezaBashsiz/nipovpn-android).
## How it works
### Use cases
**Bypass filtering.** Run the server outside the filtered network and the agent
inside it. Filtering equipment sees only HTTP(S) requests to harmless-looking
hosts.
![Filtering](https://github.com/MortezaBashsiz/nipovpn/blob/main/files/pic/archFilternet.png)
### Hide your requests in the Internet
If you want to hide your HTTP requests in the Internet, this proxy could help you.
**Hide your requests on the Internet.** Even without censorship, NipoVPN hides
which sites you visit from anyone watching your connection.
![Internet](https://github.com/MortezaBashsiz/nipovpn/blob/main/files/pic/archInternet.png)
## Flow
Here you can see the logical flow of a single request from first step to get the response
### Request flow
```
Browser/app ──HTTP or SOCKS5──▶ Agent ──decoy HTTP(S)──▶ Server ──real request──▶ Destination
◀────────────────── ◀──────────────── ◀────────────────
```
1. A local application sends a request to the agent (HTTP proxy or SOCKS5).
SOCKS5 requests are converted to an HTTP `CONNECT` internally.
2. The agent builds an envelope `action + session ID + request bytes`, encrypts
it with AES-256-GCM (if `aesEnable`; otherwise signs it with HMAC-SHA256)
and Base64-encodes it.
3. The envelope is sent as the body of a decoy request such as
`PUT /login` with `Host: cloudflare.com`, over TLS if `tlsEnable`.
4. The server decodes and decrypts the body and performs the action:
- `request` — forward a plain HTTP request and return the response.
- `open` — open a TCP connection to the `CONNECT` target.
- `send` / `recv` — write to / read from that connection (polling mode).
- `close` — close the connection.
5. The server's reply is encrypted and returned as the body of an HTTP
`200 OK` response; the agent decrypts it and hands it to the application.
![Flow](https://github.com/MortezaBashsiz/nipovpn/blob/main/files/pic/flow.png)
## Installation
| Platform | How |
|---|---|
| Debian / Ubuntu (amd64, arm64) | `.deb` from the [releases page](https://github.com/MortezaBashsiz/nipovpn/releases), tested on Ubuntu 24.04 |
| Arch Linux | [AUR package](https://aur.archlinux.org/packages/nipovpn) |
| Build from source on Linux | [Linux build guide](guides/BuildLinux.md) |
| Docker | [Docker guide](guides/Docker.md) |
| Nix / NixOS | [Nix guide](guides/Nix.md) |
| Termux | [Termux guide](guides/InstallTermux.md) |
| Windows (x86_64) | zip from the [releases page](https://github.com/MortezaBashsiz/nipovpn/releases) (`windows-v*` tags) |
| Android | [nipovpn-android](https://github.com/MortezaBashsiz/nipovpn-android) |
### Debian package
```bash
sudo apt install ./nipovpn.deb
```
The package installs:
- `/usr/bin/nipovpn`
- `/etc/nipovpn/config.yaml` (kept on upgrade)
- `nipovpn-server.service` and `nipovpn-agent.service`
```bash
sudo systemctl enable --now nipovpn-server.service # on the server
sudo systemctl enable --now nipovpn-agent.service # on the agent machine
```
### Arch Linux
Install NipoVPN from the AUR using your preferred AUR helper:
```bash
paru -S nipovpn
```
Or build and install it manually:
```bash
git clone https://aur.archlinux.org/nipovpn.git
cd nipovpn
makepkg -si
```
The package installs:
- `/usr/bin/nipovpn`
- `/etc/nipovpn/config.yaml`
- `nipovpn-server.service` and `nipovpn-agent.service`
```bash
sudo systemctl enable --now nipovpn-server.service # on the server
sudo systemctl enable --now nipovpn-agent.service # on the agent machine
```
See the [AUR package page](https://aur.archlinux.org/packages/nipovpn) for package details.
### From source
Requirements: a C++20 compiler, CMake ≥ 3.22, Boost ≥ 1.88, yaml-cpp ≥ 0.8 and
OpenSSL. See the [Linux build guide](guides/BuildLinux.md) for details.
```bash
cmake -DCMAKE_BUILD_TYPE=Release -B build
cmake --build build -j$(nproc)
```
## Quick start
The same binary and the same config file format are used on both sides; the
first argument selects the role:
```bash
nipovpn <server|agent> <config_file_path>
```
### 1. Prepare the log file
```bash
sudo mkdir -p /var/log/nipovpn/
sudo touch /var/log/nipovpn/nipovpn.log
```
### 2. Create a user
Generate a token of at least 32 bytes for each person. Do not use the sample
tokens from the shipped config.
```bash
openssl rand -hex 16 # prints 32 hex characters
```
On the server, list it in `server.users`. On that person's machine, put the
same token in `agent.token`:
```yaml
# server config # agent config
server: agent:
users: token: "<alice's token>"
- name: alice
token: "<alice's token>"
```
### 3. TLS certificate (if `tlsEnable: true`)
The server needs a certificate and key. A self-signed pair is enough when
`tlsVerifyPeer` is `false`:
```bash
sudo openssl req -x509 -newkey rsa:2048 -nodes -days 3650 \
-subj "/CN=example.com" \
-keyout /etc/nipovpn/server.key -out /etc/nipovpn/server.crt
```
### 4. Run the server
On the server, set `server.listenIp`/`server.listenPort`, then:
```bash
sudo nipovpn server /etc/nipovpn/config.yaml
```
### 5. Run the agent
On your machine, set `agent.serverIp`/`agent.serverPort` to the server's
address, set `agent.token` to one of the server's users, and make sure
`aesEnable`, `tlsEnable` and `tunnelEnable` match the server. Then:
```bash
sudo nipovpn agent /etc/nipovpn/config.yaml
```
### 6. Point your applications at the agent
```bash
# agent.protocol: socks5
curl --socks5-hostname 127.0.0.1:8080 https://example.com
# agent.protocol: http
curl -x http://127.0.0.1:8080 https://example.com
```
Or configure the agent's address as the SOCKS5/HTTP proxy in your browser or
operating system.
## Configuration reference
The sample config lives at [nipovpn/etc/nipovpn/config.yaml](nipovpn/etc/nipovpn/config.yaml).
Settings marked **must match** have to be the same on agent and server.
### `general`
Settings both sides use. Old configs that still have one of the settings below
in `general` keep working, with a warning naming the keys to move.
| Key | Type | Default | Description |
|---|---|---|---|
| `aesEnable` | bool | `true` | AES-256-GCM payload encryption. **Must match.** |
| `tunnelEnable` | bool | `false` | `true` = direct tunnel mode, `false` = polling mode. **Must match.** |
| `tlsEnable` | bool | `false` | TLS between agent and server. **Must match.** |
| `timeout` | seconds | `10` | I/O timeout for stalled connections. `0` disables it. Each side uses its own value. |
### `log`
| Key | Default | Description |
|---|---|---|
| `logLevel` | `INFO` | `INFO`, `TRACE` or `DEBUG`. Errors are always logged. |
| `logFile` | — | Log file path. The directory and file must exist. |
### `server`
| Key | Default | Description |
|---|---|---|
| `threads` | `2` | Worker threads. |
| `listenIp` | `127.0.0.1` | IPv4 address to listen on. |
| `listenPort` | `8080` | Port to listen on (443 is a good choice to blend in). |
| `bufferSize` | `65536` | Maximum bytes read from a destination at a time in polling mode, 1–65536. |
| `tlsCertFile` | — | Server certificate (PEM, chain allowed), used when `tlsEnable` is on. |
| `tlsKeyFile` | — | Server private key (PEM). |
### `agent`
| Key | Default | Description |
|---|---|---|
| `threads` | `2` | Worker threads. |
| `listenIp` | `127.0.0.1` | IPv4 address for local applications to connect to. |
| `listenPort` | `8080` | Port for local applications. |
| `protocol` | — | `http` or `socks5`: the protocol local applications use to connect to the agent. |
| `serverIp` | `127.0.0.1` | IPv4 address of the NipoVPN server. |
| `serverPort` | `8080` | Port of the NipoVPN server. |
| `httpVersion` | `1.1` | HTTP version in decoy requests. |
| `userAgent` | `NipoAgent` | `User-Agent` header in decoy requests. |
| `fakeUrls` | — | Hosts used at random for the decoy `Host` header and TLS SNI. |
| `methods` | `GET` | HTTP methods used at random for decoy requests. |
| `endPoints` | `api` | URL paths used at random for decoy requests (`/api`, `/login`, ...). |
| `pullTimeout` | `1` | Base polling interval in milliseconds in polling mode. |
| `connectionReuse` | `false` | Reuse one keep-alive connection to the server. The server follows the agent's choice. |
| `tlsVerifyPeer` | `false` | Verify the server certificate. |
| `tlsCaFile` | — | CA file used when `tlsVerifyPeer` is on. |
| `token` | — | This agent's token, ≥ 32 bytes. Must be the token of an enabled user on the server. The AES key (or, with `aesEnable: false`, the signing key) is derived from it; the token itself is never sent. |
### `server.users`
The users allowed to connect, each with their own token. Agents do not use
this block.
| Key | Default | Description |
|---|---|---|
| `name` | — | 1–64 characters of `A-Z a-z 0-9 . _ - @`. Unique. Shown in the server log. |
| `token` | — | The user's token, ≥ 32 bytes. Unique. The user's agent puts it in `agent.token`. |
| `enabled` | `true` | `false` rejects the user without deleting the entry. |
| `limit` | none | Traffic allowed per month, e.g. `2GB`, `500MB`, `1.5GiB`. See [Usage limits](#usage-limits). |
### `server.usage` (optional)
| Key | Default | Description |
|---|---|---|
| `file` | `/var/lib/nipovpn/usage.yaml` | Where per-user usage is kept. Changing it needs a restart. |
| `resetDay` | `1` | Day of the month (1–28) on which everyone's usage goes back to zero. |
## Multiple users
Every person gets their own token. The **server** lists them all in
`server.users`:
```yaml
server:
users:
- name: alice
token: "4f3c9a...32 or more characters"
- name: bob
token: "b81e07...32 or more characters"
enabled: false # bob is rejected until this is set back to true
```
Each user's agent puts their token in `agent.token`. All other settings that
must match (such as `aesEnable`, `tlsEnable` and `tunnelEnable`) are shared by
everyone.
- The server identifies a request's user by which token decrypts it, or with
`aesEnable: false`, by which token's HMAC-SHA256 signature matches. Nothing on
the wire names the user, so this adds nothing for a censor to fingerprint.
- With `aesEnable: false`, requests are signed but not encrypted: tampered
requests are rejected, but anyone on the path can read them unless
`tlsEnable` is on.
- The server log shows the user on each connection: `[SRC ...] [USER alice]`.
- A tunnel opened by one user cannot be used by another user.
- **Upgrading from `general.token`:** older configs still work. An agent reads
`general.token` when `agent.token` is missing, and a server without a `server.users`
list accepts `general.token` as a single user named `default`. Both log a
deprecation warning at startup. To migrate, move the agent's token to
`agent.token` and add it to the server's `server.users` list. Agents of any version
keep working, since the token on the wire is the same.
- Each new connection costs one decryption attempt per enabled user until a
token matches. A reused connection tries its last user first. This is fine
for dozens of users; with hundreds, prefer `connectionReuse: true`.
To add, disable or remove a user, edit the config and [reload](#reloading-the-configuration).
When a user is removed or disabled, or their token changes, the server closes
their open connections and tunnels on reload.
## Usage limits
A server with a `server.users` list counts each user's traffic: the bytes they send to
websites plus the bytes they receive from them. NipoVPN's own overhead (decoy
HTTP framing, base64, encryption) is not counted. Give a user a monthly
allowance with `limit`:
```yaml
server:
usage:
resetDay: 1 # everyone's usage resets on the 1st of each month
users:
- name: alice
token: "..."
limit: 2GB # KB/MB/GB/TB = powers of 1000; KiB/MiB/GiB/TiB = powers of 1024
- name: bob
token: "..." # no limit
```
When a user reaches their limit, the server closes their open connections and
refuses new ones until the next period, and logs:
```
[Usage] user alice reached their limit of 2.00 GB; blocked until the next period
```
They regain access as soon as their usage drops below the limit: at the next
`resetDay`, when you raise their limit (edit the config and reload), or when you
reset them.
**Seeing and changing usage.** The server writes usage to `server.usage.file`
(default `/var/lib/nipovpn/usage.yaml`) every 30 seconds, on reload and on
shutdown:
```yaml
period: "2026-11-01"
users:
alice: {used: 2000123456} # 2.00 GB of 2.00 GB (100%), blocked
bob: {used: 734003200} # 734.00 MB, no limit
```
To reset or change a user's usage, edit their `used` number (for example set it
to `0`) and save. The server applies the edit within 30 seconds, or right away
on reload. Traffic counted in the meantime is kept on top of your value. Do not
edit `period`.
Notes:
- The file is the only record of usage, so it survives restarts. With Docker,
keep `/var/lib/nipovpn` on a volume (the compose file does).
- If the file cannot be parsed, the server logs an error and stops saving until
you fix it, rather than overwriting your edit.
- A user who is removed and later added back keeps their usage for the period.
- Usage is not tracked on a server without a `server.users` list.
## Reloading the configuration
Send `SIGHUP` to apply config changes without dropping other users' connections:
```bash
sudo systemctl reload nipovpn-server.service # or nipovpn-agent.service
docker kill -s HUP nipovpn # Docker
kill -HUP "$(pidof nipovpn)" # anything else
```
The file is validated first. If it is invalid, the running configuration is
kept and the error is logged at `ERROR` level, so a typo never takes the server
down. A successful reload logs a summary, for example:
```
[Runner reload] config reloaded; 2 of 3 users enabled; access revoked for: bob
[Runner reload] closed 1 connections and 0 tunnel sessions of revoked users
```
New requests use the new settings at once. These settings only change on
restart: `listenIp`, `listenPort`, `threads`, `tlsEnable` and `server.usage.file`. If you change
them, the reload logs `... changed but needs a restart`. Certificate files are
read for every new connection, so a renewed certificate needs no reload at
all. Reload is not available on Windows.
## Security notes
- **Change the token.** The sample token is public; the program logs a warning
if it is still in use.
- **Turn on at least one of `aesEnable` and `tlsEnable`.** Without either,
traffic is only obfuscated, not encrypted.
- **Direct tunnel mode** sends tunneled bytes without the decoy framing or AES,
so pair it with `tlsEnable: true`.
- **`tlsVerifyPeer: false`** protects against passive observers but not against
an active man-in-the-middle. Enable it with a proper `tlsCaFile` if that
matters to you. AES-GCM with a strong token still authenticates the payload.
- **Listening on `0.0.0.0` on the agent** exposes your proxy to the local
network. Use `127.0.0.1` unless you mean to share it.
> **Protocol change:** this version uses AES-256-GCM and carries the session and
> action inside the encrypted body instead of `X-Nipo-*` headers. It is not
> compatible with older agents, servers or the Android app; upgrade all of them
> together.
## Logging
Log lines look like:
```
2026-01-01_12:00:00 [AGENT] [INFO] [<session-uuid>] [CONNECT] [SRC 127.0.0.1:51234] [ORIGIN example.com:443]
2026-01-01_12:00:00 [SERVER] [INFO] [<session-uuid>] [CONNECT] [SRC 203.0.113.7:40112] [USER alice] [ORIGIN example.com:443]
```
On the server, `[USER ...]` is the user from the `server.users` list, or `default`
when the server still uses the deprecated `general.token`.
- `INFO`: startup, effective configuration (token hidden), connections opened.
- `TRACE`: adds the destination of every forwarded request.
- `DEBUG`: adds handshake, encryption and byte-level details. Use only for
troubleshooting.
```bash
tail -f /var/log/nipovpn/nipovpn.log
journalctl -u nipovpn-server.service -f
```
## Troubleshooting
| Symptom | Likely cause |
|---|---|
| `Configuration validation failed: ...` | A required key is missing or invalid; the message names the block. |
| `agent.token must be at least 32 bytes` | Use a longer token (`openssl rand -hex 16`). |
| `Error opening log file` | Create the log directory and file (see Quick start). |
| Server logs `Decryption Failed` / `Invalid Envelope` | `token`, `aesEnable` or NipoVPN versions differ between agent and server. With `server.users`: the agent's token is not an enabled user's token. |
| `agent.token is required` | Set the agent's token in the `agent` block (it used to be `general.token`). |
| `the server needs a server.users list with at least one user` | Add a `users` list under `server` in the server config. |
| `users belongs under the server block` | Configs from before this change had `users`/`usage` at the top level; indent them under `server:`. |
| `[WARNING] general.token is deprecated` | Move the token to `agent.token` (agent) or a `server.users` entry (server). |
| `[WARNING] these settings moved out of general: ...` | Move the listed keys from `general` to the block the warning names (`agent` or `server`). |
| `limit must be a size with a unit` | Write the limit with a unit: `2GB`, `500MB`, `1.5GiB`, or `1024B` for bytes. |
| `[Usage] cannot read .../usage.yaml` | The usage file has a syntax error, probably from a manual edit. Fix it; usage is not saved until then. |
| `[Usage] cannot save usage` | The server cannot write `server.usage.file`; check the directory and permissions. |
| `[Runner reload] config not reloaded: ...` | The edited file is invalid; the old configuration is still running. Fix the file and reload again. |
| Agent logs `[Tunnel closed] recv refused or failed` | The server rejected the agent's token (e.g. the user was disabled) or became unreachable. |
| Agent logs `[TLS] [ERROR]` | `tlsEnable` differs between the two sides, or the certificate/key path is wrong. |
| `[CONNECT] [ERROR] [To Server]` | Agent cannot reach `serverIp:serverPort` (firewall, wrong address, server not running). |
## Tests
[tests/e2e.py](tests/e2e.py) runs end-to-end tests: for each test it starts a real
server and agent on localhost, sends traffic through them with `curl`, and checks
every byte with SHA-256. It covers every combination of `tlsEnable`,
`tunnelEnable`, `connectionReuse`, `aesEnable` and `protocol`, plus multiple users,
unknown and disabled users, reload, usage limits, the 1.1.x config layout and
config validation. Every test config is built from the sample `config.yaml`.
```bash
cmake -S . -B build && cmake --build build -j
python3 tests/e2e.py --binary build/core/nipovpn # all tests
python3 tests/e2e.py --binary build/core/nipovpn -k reload # names containing "reload"
python3 tests/e2e.py --list
```
It needs Python 3 with PyYAML, `curl` and `openssl`. GitHub Actions runs it on every
push and pull request ([.github/workflows/test.yml](.github/workflows/test.yml)),
once on a release build and once with AddressSanitizer and UndefinedBehaviorSanitizer.
## Contribution
To contribute take a look at [contribution page](https://github.com/MortezaBashsiz/nipovpn/blob/main/CONTRIBUTING.md).
## Build
See the [contribution guide](CONTRIBUTING.md). In short: branch from `dev`,
format with `scripts/format.sh`, build and test, and open a pull request against
`dev`.
Build from source for [Linux](guides/BuildLinux.md)
## License
NipoVPN is released under the [GNU General Public License v3.0](LICENSE).
## Run
#### Create directories
Create the log directory and log file
```bash
[~/nipovpn]>$ sudo mkdir /var/log/nipovpn/
[~/nipovpn]>$ sudo touch /var/log/nipovpn/nipovpn.log
```
Run it
```bash
sudo build/core/nipovpn server nipovpn/etc/nipovpn/config.yaml
```
### Package
#### Install
Currently it is only available for debian-based Linuxes and fully tested on ubuntu 24.04
You can simply download and install the package. To download it please visit the [releases page](https://github.com/MortezaBashsiz/nipovpn/tags) and get the latest release.
```bash
[~]>$ sudo apt install ./nipovpn.deb
```
#### Run
There are systemd services to manage the nipovpn process.
`nipovpn-server.service` to manage as server.
`nipovpn-agent.service` to manage as agent.
```bash
[~]>$ sudo systemctl start nipovpn-server.service
[~]>$ cat /var/log/nipovpn/nipovpn.log
```
+6
View File
@@ -12,6 +12,7 @@ set(CORE_TARGET_HEADERS
src/tcpclient.hpp
src/tcpconnection.hpp
src/tcpserver.hpp
src/usage.hpp
)
set(CORE_TARGET_SOURCES
@@ -24,6 +25,7 @@ set(CORE_TARGET_SOURCES
src/tcpclient.cpp
src/tcpconnection.cpp
src/tcpserver.cpp
src/usage.cpp
)
@@ -38,3 +40,7 @@ target_include_directories(${CORE_TARGET} PUBLIC ${OPENSSL_INCLUDE_DIR})
target_link_libraries(${CORE_TARGET} ${Boost_LIBRARIES})
target_link_libraries(${CORE_TARGET} ${YAML_CPP_LIBRARIES})
target_link_libraries(${CORE_TARGET} ${OPENSSL_LIBRARIES})
if(WIN32)
target_link_libraries(${CORE_TARGET} ws2_32 mswsock)
endif()
+104 -169
View File
@@ -1,233 +1,168 @@
#include "agenthandler.hpp"
/**
* @brief Constructs an `AgentHandler` instance with the required buffers, configuration,
* logging, client connection, and session identifier.
*
* @details
* - Initializes internal references to the read and write buffers.
* - Stores shared references to the configuration and logging objects.
* - Stores the associated `TCPClient` instance used for server communication.
* - Creates an `HTTP` helper object for parsing and generating HTTP messages.
* - Saves the client connection string and UUID for logging and tracking purposes.
* - Sets the initial state flags:
* - `end_` is initialized to `false`, indicating processing is not finished.
* - `connect_` is initialized to `false`, indicating that no CONNECT tunnel is active.
*
* @param readBuffer Reference to the stream buffer used for reading incoming client data.
* @param writeBuffer Reference to the stream buffer used for storing outgoing response data.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param client Shared pointer to the `TCPClient` used for communication with the remote server.
* @param clientConnStr String describing the client connection source.
* @param uuid Unique identifier for this handler session, represented as a Boost UUID.
*/
#include <sstream>
#include <utility>
AgentHandler::AgentHandler(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid)
: config_(config),
log_(log),
client_(client),
client_(std::move(client)),
readBuffer_(readBuffer),
writeBuffer_(writeBuffer),
request_(HTTP::create(config, log, readBuffer, uuid)),
clientConnStr_(clientConnStr),
clientConnStr_(std::move(clientConnStr)),
uuid_(uuid) {
end_ = false;
connect_ = false;
}
/**
* @brief Destroys the `AgentHandler` instance.
*
* @details
* - Performs no additional cleanup explicitly.
* - Resource lifetime is managed by referenced objects and smart pointers.
*/
AgentHandler::~AgentHandler() {}
/**
* @brief Handles a client request by encrypting it, forwarding it to the agent server,
* and processing the server response.
*
* @details
* - Ensures thread-safe execution using an internal mutex.
* - Reads the incoming request data from `readBuffer_` and encrypts it using AES-256.
* - Encodes the encrypted payload with Base64 and wraps it into an HTTP POST request.
* - Detects the type of the original HTTP request before forwarding it.
* - Logs connection details when a valid HTTP target is available.
* - Initializes TLS on the client connection when enabled in the configuration.
* - Establishes a TCP connection to the configured server if one is not already open.
* - Performs a TLS handshake when TLS is active on the client connection.
* - Sends the generated HTTP request to the remote server and reads the response.
* - Handles CONNECT requests specially by forwarding the raw response directly.
* - Parses normal HTTP responses, decrypts their body content, and writes the
* decrypted result into `writeBuffer_`.
* - On any failure during encryption, connection, parsing, decryption, or I/O,
* the client socket is shut down and processing stops.
*
* @note
* - For CONNECT requests, the method does not decrypt the response body and instead
* forwards the raw response stream directly to the write buffer.
* - The `connect_` flag is updated when a connection or CONNECT tunnel is established.
*/
void AgentHandler::handle() {
std::lock_guard lock(mutex_);
BoolStr encryption{false, std::string("FAILED")};
/**
* @brief Encrypts the incoming request payload using the configured token.
*/
encryption = aes256Encrypt(hexStreambufToStr(readBuffer_),
config_->general().token);
if (!encryption.ok) {
log_->write("[" + to_string(uuid_) +
"] [AgentHandler handle] [Encryption Failed] : [ " +
encryption.message + "] ",
Log::Level::DEBUG);
client_->socketShutdown();
return;
}
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Done]",
Log::Level::DEBUG);
/**
* @brief Builds a new HTTP POST request containing the encrypted payload.
*/
std::string newReq(
request_->genHttpPostReqString(encode64(encryption.message)));
/**
* @brief Verifies that the incoming request is a valid HTTP request before forwarding.
*/
if (!request_->detectType()) {
log_->write("[" + to_string(uuid_) +
"] [AgentHandler handle] [NOT HTTP Request] [Request] : " +
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Request] [Request] : " +
streambufToString(readBuffer_),
Log::Level::DEBUG);
client_->socketShutdown();
return;
}
/**
* @brief Logs the source and destination information when the request target is available.
*/
if (request_->parsedHttpRequest().target().length() > 0) {
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " + clientConnStr_ +
"] [DST " +
std::string(request_->parsedHttpRequest().target()) +
"]",
Log::Level::INFO);
log_->write("[" + to_string(uuid_) + "] [FORWARD] [SRC " + clientConnStr_ + "] [DST " +
std::string(request_->parsedHttpRequest().target()) + "]",
Log::Level::TRACE);
}
/**
* @brief Enables TLS on the client connection if configured and not already active.
*/
if (config_->agent().tlsEnable && !client_->tlsEnabled()) {
if (config_->general().tlsEnable && !client_->tlsEnabled()) {
if (!client_->enableTlsClient()) {
log_->write("[" + to_string(uuid_) +
"] [TLS] [ERROR] [Init Client Context] [SRC " +
clientConnStr_ + "] [DST " + config_->agent().serverIp +
":" + std::to_string(config_->agent().serverPort) + "]",
log_->write("[" + to_string(uuid_) + "] [TLS] [ERROR] [Init Client Context] [SRC " +
clientConnStr_ + "] [DST " + config_->agent().serverIp + ":" +
std::to_string(config_->agent().serverPort) + "]",
Log::Level::ERROR);
client_->socketShutdown();
return;
}
}
/**
* @brief Establishes the TCP connection and performs the TLS handshake if needed.
*/
if (!client_->isOpen()) {
connect_ = true;
if (!client_->doConnect(config_->agent().serverIp,
config_->agent().serverPort)) {
log_->write("[" + to_string(uuid_) +
"] [CONNECT] [ERROR] [To Server] [SRC " + clientConnStr_ +
"] [DST " + config_->agent().serverIp + ":" +
if (!client_->doConnect(config_->agent().serverIp, config_->agent().serverPort)) {
log_->write("[" + to_string(uuid_) + "] [CONNECT] [ERROR] [To Server] [SRC " +
clientConnStr_ + "] [DST " + config_->agent().serverIp + ":" +
std::to_string(config_->agent().serverPort) + "]",
Log::Level::INFO);
client_->socketShutdown();
return;
} else {
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " +
clientConnStr_ + "] [ORIGIN " + std::string(request_->parsedHttpRequest().target()) + "]",
Log::Level::INFO);
}
if (client_->tlsEnabled()) {
if (!client_->doHandshakeClient()) {
log_->write("[" + to_string(uuid_) +
"] [TLS] [ERROR] [Client Handshake] [SRC " +
clientConnStr_ + "] [DST " + config_->agent().serverIp +
":" + std::to_string(config_->agent().serverPort) + "]",
Log::Level::ERROR);
client_->socketShutdown();
return;
}
if (client_->tlsEnabled() && !client_->doHandshakeClient()) {
log_->write("[" + to_string(uuid_) + "] [TLS] [ERROR] [Client Handshake] [SRC " +
clientConnStr_ + "] [DST " + config_->agent().serverIp + ":" +
std::to_string(config_->agent().serverPort) + "]",
Log::Level::ERROR);
client_->socketShutdown();
return;
}
}
/**
* @brief Sends the generated request to the remote server and waits for the response.
*/
copyStringToStreambuf(newReq, readBuffer_);
client_->doWrite(readBuffer_);
client_->doReadAgent();
const std::string action =
request_->httpType() == HTTP::HttpType::connect ? "open" : "request";
/**
* @brief Stops processing if no response data was received from the server.
*/
if (client_->readBuffer().size() == 0) {
client_->socketShutdown();
return;
}
/**
* @brief Handles CONNECT requests by forwarding the raw response directly.
*/
if (request_->httpType() == HTTP::HttpType::connect) {
connect_ = true;
moveStreambuf(client_->readBuffer(), writeBuffer_);
return;
}
/**
* @brief Creates and parses an HTTP response object from the received server data.
*/
HTTP::pointer response =
HTTP::create(config_, log_, client_->readBuffer(), uuid_);
if (!response->parseHttpResp()) {
log_->write("[AgentHandler handle] [NOT HTTP Response] [Response] : " +
streambufToString(client_->readBuffer()),
BoolStr encryption{false, std::string("FAILED")};
const std::string payload =
makeEnvelope(action, to_string(uuid_), hexStreambufToStr(readBuffer_));
encryption = config_->general().aesEnable
? aes256Encrypt(payload, config_->agent().token)
: BoolStr{true, signWithKey(payload, deriveAesKey(config_->agent().token))};
if (!encryption.ok) {
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Encryption Failed] : [ " +
encryption.message + "] ",
Log::Level::DEBUG);
client_->socketShutdown();
return;
}
const std::string innerRequest = encode64(encryption.message);
std::ostringstream outer;
const bool directTunnelOpen =
config_->general().tunnelEnable &&
request_->httpType() == HTTP::HttpType::connect;
outer << config_->randomMethod() + " /" + config_->randomEndPoint() + " HTTP/" << config_->agent().httpVersion << "\r\n"
<< "Host: " << relayHostHeader(config_) << "\r\n"
<< "User-Agent: " << config_->agent().userAgent << "\r\n"
<< "Accept: */*\r\n"
<< "Content-Type: text/plain; charset=utf-8\r\n"
<< "Content-Length: " << innerRequest.size() << "\r\n"
<< "Connection: "
<< ((config_->agent().connectionReuse || directTunnelOpen) ? "keep-alive" : "close")
<< "\r\n"
<< "\r\n"
<< innerRequest;
copyStringToStreambuf(outer.str(), readBuffer_);
client_->doWrite(readBuffer_);
client_->doReadAgent();
if (client_->readBuffer().size() == 0 && !config_->agent().connectionReuse) {
client_->socketShutdown();
return;
}
const std::string outerResponse = streambufToString(client_->readBuffer());
const auto bodyPos = outerResponse.find("\r\n\r\n");
if (bodyPos == std::string::npos) {
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [NOT HTTP Response] [Response] : " +
outerResponse,
Log::Level::DEBUG);
client_->socketShutdown();
return;
}
const std::string responseBody = outerResponse.substr(bodyPos + 4);
if (responseBody.empty()) {
client_->socketShutdown();
return;
}
BoolStr decryption{false, std::string("FAILED")};
/**
* @brief Decodes and decrypts the HTTP response body using the configured token.
*/
decryption = aes256Decrypt(
decode64(std::string(response->parsedHttpResponse().body())),
config_->general().token);
decryption = config_->general().aesEnable
? aes256Decrypt(responseBody, config_->agent().token)
: BoolStr{true, responseBody};
if (!decryption.ok) {
log_->write("[" + to_string(uuid_) +
"] [AgentHandler handle] [Decryption Failed] : [ " +
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Decryption Failed] : [ " +
decryption.message + "] ",
Log::Level::DEBUG);
client_->socketShutdown();
return;
}
/**
* @brief Writes the decrypted response payload into the output buffer.
*/
copyStringToStreambuf(decryption.message, writeBuffer_);
}
log_->write("[" + to_string(uuid_) + "] [AgentHandler handle] [Payload Decoded]",
Log::Level::DEBUG);
connect_ = request_->httpType() == HTTP::HttpType::connect;
end_ = false;
}
std::string AgentHandler::relayHostHeader(const std::shared_ptr<Config> &config) {
std::string hostHeader = config->randomFakeUrl();
auto pos = hostHeader.find("://");
if (pos != std::string::npos) hostHeader = hostHeader.substr(pos + 3);
pos = hostHeader.find('/');
if (pos != std::string::npos) hostHeader = hostHeader.substr(0, pos);
return hostHeader;
}
+17 -94
View File
@@ -9,126 +9,49 @@
#include "log.hpp"
#include "tcpclient.hpp"
/**
* @brief The `AgentHandler` class manages communication between the client and the agent server.
*
* @details
* - Responsible for processing incoming client requests and forwarding them to the agent server.
* - Handles encryption, HTTP request generation, and response processing.
* - Maintains connection state and supports both normal HTTP and CONNECT tunneling.
* - Uses Boost.Asio stream buffers for efficient I/O operations.
* - Ensures thread safety using an internal mutex.
* - Integrates with external components such as configuration, logging, and TCP client handling.
*
* @note
* - Inherits from `Uncopyable` to prevent accidental copying.
* - Uses shared ownership via `std::shared_ptr` (see `pointer` alias).
* - Instances must be created using the `create` factory method.
*/
class AgentHandler : private Uncopyable {
public:
using pointer = std::shared_ptr<AgentHandler>;
/**
* @brief Factory method to create a new `AgentHandler` instance.
*
* @details
* - Wraps object construction in a `std::shared_ptr`.
* - Ensures consistent creation and ownership semantics.
*
* @param readBuffer Reference to the stream buffer used for reading client data.
* @param writeBuffer Reference to the stream buffer used for writing response data.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param client Shared pointer to the `TCPClient` managing server communication.
* @param clientConnStr String describing the client connection source.
* @param uuid Unique identifier for this handler instance.
* @return A shared pointer to the created `AgentHandler`.
*/
static pointer create(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid) {
return pointer(new AgentHandler(readBuffer, writeBuffer, config, log,
client, clientConnStr, uuid));
}
/**
* @brief Destructor for `AgentHandler`.
*
* @details
* - Default destructor; resource management is handled by smart pointers and references.
*/
~AgentHandler();
/**
* @brief Processes a client request and communicates with the agent server.
*
* @details
* - Encrypts incoming data.
* - Builds and sends an HTTP request to the agent server.
* - Receives, parses, and decrypts the server response.
* - Handles CONNECT tunneling and normal HTTP flows.
*/
void handle();
/**
* @brief Provides access to the associated HTTP request object.
*
* @return A const reference to the HTTP request pointer.
*/
inline const HTTP::pointer &request() & { return request_; }
inline const HTTP::pointer &request() const { return request_; }
/**
* @brief Provides rvalue access to the HTTP request object.
*
* @details
* - Enables move semantics when transferring ownership.
*
* @return An rvalue reference to the HTTP request pointer.
*/
inline const HTTP::pointer &&request() && { return std::move(request_); }
bool end_; ///< Indicates whether processing has completed.
bool connect_;///< Indicates whether a CONNECT tunnel or server connection is active.
bool end_;
bool connect_;
private:
/**
* @brief Constructs an `AgentHandler` instance.
*
* @details
* - Initializes buffers, configuration, logging, and client references.
* - Creates the internal HTTP request handler.
* - Stores connection metadata and unique identifier.
*
* @param readBuffer Reference to the input stream buffer.
* @param writeBuffer Reference to the output stream buffer.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param client Shared pointer to the TCP client.
* @param clientConnStr Client connection description string.
* @param uuid Unique identifier for this handler instance.
*/
AgentHandler(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid);
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
const TCPClient::pointer &client_; ///< Reference to the TCP client.
boost::asio::streambuf &readBuffer_; ///< Buffer for incoming client data.
boost::asio::streambuf &writeBuffer_; ///< Buffer for outgoing response data.
HTTP::pointer request_; ///< HTTP request handler instance.
const std::string &clientConnStr_; ///< Client connection string.
std::string relayHostHeader(const std::shared_ptr<Config> &config);
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
TCPClient::pointer client_;
boost::asio::streambuf &readBuffer_;
boost::asio::streambuf &writeBuffer_;
HTTP::pointer request_;
std::string clientConnStr_;
boost::uuids::uuid uuid_;///< Unique identifier for this handler.
boost::uuids::uuid uuid_;
std::mutex mutex_;///< Mutex used to ensure thread-safe operations.
std::mutex mutex_;
};
+289 -158
View File
@@ -1,139 +1,233 @@
#include "config.hpp"
/**
* @brief Constructs a `Config` instance by loading and parsing a YAML configuration file.
*
* @details
* - Loads the YAML configuration from the provided file path.
* - Initializes all configuration sections (`general_`, `log_`, `server_`, `agent_`)
* directly from the parsed YAML structure.
* - Sets default runtime values for threads, listen IP, and port.
* - Based on the selected `RunMode`, initializes runtime parameters:
* - `threads_`
* - `listenIp_`
* - `listenPort_`
* - Ensures thread-safe initialization using a mutex lock.
*
* @param mode Runtime mode (server or agent).
* @param filePath Path to the YAML configuration file.
*/
Config::Config(const RunMode &mode, const std::string &filePath)
namespace {
std::string trimNewlines(std::string s) {
while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) s.pop_back();
return s;
}
}// namespace
std::unique_ptr<Config::Settings> Config::load(RunMode mode, const std::string &filePath) {
const YAML::Node yaml = YAML::LoadFile(filePath);
auto s = std::make_unique<Settings>();
const std::string legacyToken = yaml["general"]["token"].as<std::string>("");
std::vector<std::string> deprecated;
auto setting = [&](const char *block, const char *key) {
if ((mode == RunMode::agent) == (std::string(block) == "agent") &&
isDeprecatedSetting(yaml, block, key)) {
deprecated.push_back(key);
}
return movedSetting(yaml, block, key);
};
s->general = {yaml["general"]["timeout"].as<unsigned short>(10),
yaml["general"]["tunnelEnable"].as<bool>(false),
yaml["general"]["aesEnable"].as<bool>(true),
yaml["general"]["tlsEnable"].as<bool>(false)};
s->log = {yaml["log"]["logLevel"].as<std::string>("INFO"),
yaml["log"]["logFile"].as<std::string>()};
s->server = {yaml["server"]["threads"].as<unsigned short>(2),
yaml["server"]["listenIp"].as<std::string>("127.0.0.1"),
yaml["server"]["listenPort"].as<unsigned short>(8080),
setting("server", "bufferSize").as<unsigned int>(65536),
setting("server", "tlsCertFile").as<std::string>(""),
setting("server", "tlsKeyFile").as<std::string>("")};
s->agent = {yaml["agent"]["threads"].as<unsigned short>(2),
yaml["agent"]["listenIp"].as<std::string>("127.0.0.1"),
yaml["agent"]["listenPort"].as<unsigned short>(8080),
yaml["agent"]["serverIp"].as<std::string>("127.0.0.1"),
yaml["agent"]["serverPort"].as<unsigned short>(8080),
yaml["agent"]["httpVersion"].as<std::string>("1.1"),
yaml["agent"]["userAgent"].as<std::string>("NipoAgent"),
yaml["agent"]["token"].as<std::string>(""),
setting("agent", "protocol").as<std::string>(""),
setting("agent", "fakeUrls").as<std::vector<std::string>>(std::vector<std::string>{}),
setting("agent", "methods").as<std::vector<std::string>>(std::vector<std::string>{}),
setting("agent", "endPoints").as<std::vector<std::string>>(std::vector<std::string>{}),
setting("agent", "pullTimeout").as<unsigned short>(1),
setting("agent", "connectionReuse").as<bool>(false),
setting("agent", "tlsVerifyPeer").as<bool>(false),
setting("agent", "tlsCaFile").as<std::string>("")};
if (!deprecated.empty()) {
std::string keys;
for (const auto &key: deprecated) keys += (keys.empty() ? "" : ", ") + key;
s->warnings.push_back("these settings moved out of general: " + keys + "; move them to the " +
(mode == RunMode::agent ? "agent" : "server") + " block");
}
if (mode == RunMode::agent && s->agent.token.empty() && !legacyToken.empty()) {
s->agent.token = legacyToken;
s->warnings.push_back("general.token is deprecated; move it to agent.token");
}
if (mode == RunMode::server) {
const YAML::Node usage = yaml["server"]["usage"];
s->usageFile = usage ? usage["file"].as<std::string>("/var/lib/nipovpn/usage.yaml")
: "/var/lib/nipovpn/usage.yaml";
s->usageResetDay = usage ? usage["resetDay"].as<int>(1) : 1;
const YAML::Node users = yaml["server"]["users"];
if (users && users.IsSequence()) {
s->usersFromFile = true;
for (const auto &u: users) {
const std::string token = u["token"].as<std::string>();
std::uint64_t limit = 0;
if (u["limit"]) parseByteSize(u["limit"].as<std::string>(), limit);
s->users.push_back({u["name"].as<std::string>(), token, deriveAesKey(token),
u["enabled"].as<bool>(true), limit});
}
} else {
s->users.push_back({"default", legacyToken, deriveAesKey(legacyToken), true});
if (!legacyToken.empty()) {
s->warnings.push_back(
"general.token is deprecated on the server; "
"put the token in a server.users list instead");
}
}
}
return s;
}
Config::Config(RunMode mode, const std::string &filePath)
: runMode_(mode),
filePath_(filePath),
configYaml_(YAML::LoadFile(filePath)),
threads_(0),
listenIp_("127.0.0.1"),
listenPort_(0),
general_({configYaml_["general"]["token"].as<std::string>(),
configYaml_["general"]["fakeUrl"].as<std::string>(),
configYaml_["general"]["method"].as<std::string>(),
configYaml_["general"]["timeout"].as<unsigned short>(),
configYaml_["general"]["chunkHeader"].as<std::string>()}),
log_({configYaml_["log"]["logLevel"].as<std::string>(),
configYaml_["log"]["logFile"].as<std::string>()}),
server_({configYaml_["server"]["threads"].as<unsigned short>(),
configYaml_["server"]["listenIp"].as<std::string>(),
configYaml_["server"]["listenPort"].as<unsigned short>(),
configYaml_["server"]["tlsEnable"].as<bool>(false),
configYaml_["server"]["tlsVerifyPeer"].as<bool>(false),
configYaml_["server"]["tlsCertFile"].as<std::string>(""),
configYaml_["server"]["tlsKeyFile"].as<std::string>(""),
configYaml_["server"]["tlsCaFile"].as<std::string>("")}),
agent_({configYaml_["agent"]["threads"].as<unsigned short>(),
configYaml_["agent"]["listenIp"].as<std::string>(),
configYaml_["agent"]["listenPort"].as<unsigned short>(),
configYaml_["agent"]["serverIp"].as<std::string>(),
configYaml_["agent"]["serverPort"].as<unsigned short>(),
configYaml_["agent"]["httpVersion"].as<std::string>(),
configYaml_["agent"]["userAgent"].as<std::string>(),
configYaml_["agent"]["tlsEnable"].as<bool>(false),
configYaml_["agent"]["tlsVerifyPeer"].as<bool>(false),
configYaml_["agent"]["tlsCaFile"].as<std::string>("")}) {
listenPort_(0) {
publish(load(mode, filePath));
std::lock_guard<std::mutex> lock(configMutex_);
/**
* @brief Initializes runtime parameters based on the selected run mode.
*/
const Settings &s = current();
switch (runMode_) {
case RunMode::server:
threads_ = server_.threads;
listenIp_ = server_.listenIp;
listenPort_ = server_.listenPort;
threads_ = s.server.threads;
listenIp_ = s.server.listenIp;
listenPort_ = s.server.listenPort;
break;
case RunMode::agent:
threads_ = agent_.threads;
listenIp_ = agent_.listenIp;
listenPort_ = agent_.listenPort;
threads_ = s.agent.threads;
listenIp_ = s.agent.listenIp;
listenPort_ = s.agent.listenPort;
break;
}
}
/**
* @brief Copy constructor that creates a new `Config` instance from an existing one.
*
* @details
* - Copies all configuration sections and runtime parameters.
* - Reloads the YAML configuration from the original file path.
* - Preserves the runtime mode and all derived values.
*
* @param config Shared pointer to the existing configuration.
*/
Config::Config(const Config::pointer &config)
: runMode_(config->runMode()),
filePath_(config->filePath()),
configYaml_(YAML::LoadFile(config->filePath())),
threads_(config->threads()),
listenIp_(config->listenIp()),
listenPort_(config->listenPort()),
general_(config->general()),
log_(config->log()),
server_(config->server()),
agent_(config->agent()) {}
/**
* @brief Destructor for `Config`.
*
* @details
* - Defaulted destructor; no explicit resource cleanup required.
*/
Config::~Config() = default;
/**
* @brief Converts the configuration into a human-readable string.
*
* @details
* - Serializes all configuration sections into a formatted string.
* - Includes General, Log, Server, and Agent sections.
* - Useful for debugging and logging configuration state.
*
* @return A formatted string representation of the configuration.
*/
const Config::Settings &Config::current() const {
return *current_.load(std::memory_order_acquire);
}
void Config::publish(std::unique_ptr<Settings> settings) {
std::lock_guard<std::mutex> lock(configMutex_);
snapshots_.push_back(std::move(settings));
current_.store(snapshots_.back().get(), std::memory_order_release);
}
Config::ReloadResult Config::reload() {
std::lock_guard<std::mutex> lock(reloadMutex_);
const BoolStr valid = validateConfigFile(modeToString(), filePath_);
if (!valid.ok) {
return {false, "config not reloaded: " + trimNewlines(valid.message), {}};
}
std::unique_ptr<Settings> next;
try {
next = load(runMode_, filePath_);
} catch (const std::exception &e) {
return {false, std::string("config not reloaded: ") + e.what(), {}};
}
const Settings &prev = current();
std::vector<std::string> notes;
auto keep = [&notes](auto &field, const auto &old, const char *name) {
if (field != old) {
notes.push_back(std::string(name) + " changed but needs a restart");
field = old;
}
};
if (runMode_ == RunMode::server) {
keep(next->server.listenIp, prev.server.listenIp, "server.listenIp");
keep(next->server.listenPort, prev.server.listenPort, "server.listenPort");
keep(next->server.threads, prev.server.threads, "server.threads");
} else {
keep(next->agent.listenIp, prev.agent.listenIp, "agent.listenIp");
keep(next->agent.listenPort, prev.agent.listenPort, "agent.listenPort");
keep(next->agent.threads, prev.agent.threads, "agent.threads");
}
keep(next->usageFile, prev.usageFile, "server.usage.file");
keep(next->general.tlsEnable, prev.general.tlsEnable, "general.tlsEnable");
std::vector<std::string> revoked;
for (const auto &old: prev.users) {
if (!old.enabled) continue;
bool stillValid = false;
for (const auto &u: next->users) {
if (u.name == old.name) {
stillValid = u.enabled && u.token == old.token;
break;
}
}
if (!stillValid) revoked.push_back(old.name);
}
std::size_t enabled = 0;
for (const auto &u: next->users) {
if (u.enabled) ++enabled;
}
std::string message = "config reloaded";
if (runMode_ == RunMode::server) {
message += "; " + std::to_string(enabled) + " of " +
std::to_string(next->users.size()) + " users enabled";
if (!revoked.empty()) {
message += "; access revoked for:";
for (const auto &name: revoked) message += " " + name;
}
}
for (const auto &note: notes) message += "; " + note;
publish(std::move(next));
return {true, message, revoked};
}
std::string Config::toString() const {
std::lock_guard<std::mutex> lock(configMutex_);
const Settings &cur = current();
const General &general_ = cur.general;
const Log &log_ = cur.log;
const Server &server_ = cur.server;
const Agent &agent_ = cur.agent;
std::stringstream ss;
ss << "\nConfig :\n"
<< " General :\n"
<< " token: " << general_.token << "\n"
<< " fakeUrl: " << general_.fakeUrl << "\n"
<< " method: " << general_.method << "\n"
<< " timeout: " << general_.timeout << "\n"
<< " chunkHeader: " << general_.chunkHeader << "\n"
<< " tunnelEnable: " << std::boolalpha << general_.tunnelEnable << "\n"
<< " aesEnable: " << std::boolalpha << general_.aesEnable << "\n"
<< " tlsEnable: " << std::boolalpha << general_.tlsEnable << "\n"
<< " Log :\n"
<< " logLevel: " << log_.level << "\n"
<< " logFile: " << log_.file << "\n"
<< " server :\n"
<< " Server :\n"
<< " threads: " << server_.threads << "\n"
<< " listenIp: " << server_.listenIp << "\n"
<< " listenPort: " << server_.listenPort << "\n"
<< " tlsEnable: " << server_.tlsEnable << "\n"
<< " tlsVerifyPeer: " << server_.tlsVerifyPeer << "\n"
<< " bufferSize: " << server_.bufferSize << "\n"
<< " tlsCertFile: " << server_.tlsCertFile << "\n"
<< " tlsKeyFile: " << server_.tlsKeyFile << "\n"
<< " tlsCaFile: " << server_.tlsCaFile << "\n"
<< " agent :\n"
<< " Agent :\n"
<< " threads: " << agent_.threads << "\n"
<< " listenIp: " << agent_.listenIp << "\n"
<< " listenPort: " << agent_.listenPort << "\n"
@@ -141,114 +235,103 @@ std::string Config::toString() const {
<< " serverPort: " << agent_.serverPort << "\n"
<< " httpVersion: " << agent_.httpVersion << "\n"
<< " userAgent: " << agent_.userAgent << "\n"
<< " tlsEnable: " << agent_.tlsEnable << "\n"
<< " tlsVerifyPeer: " << agent_.tlsVerifyPeer << "\n"
<< " tlsCaFile: " << agent_.tlsCaFile << "\n";
<< " protocol: " << agent_.protocol << "\n"
<< " fakeUrls: " << boost::algorithm::join(agent_.fakeUrls, ", ") << "\n"
<< " methods: " << boost::algorithm::join(agent_.methods, ", ") << "\n"
<< " endPoints: " << boost::algorithm::join(agent_.endPoints, ", ") << "\n"
<< " pullTimeout: " << agent_.pullTimeout << "\n"
<< " connectionReuse: " << std::boolalpha << agent_.connectionReuse << "\n"
<< " tlsVerifyPeer: " << std::boolalpha << agent_.tlsVerifyPeer << "\n"
<< " tlsCaFile: " << agent_.tlsCaFile << "\n"
<< " token: " << (agent_.token.empty() ? "" : "<hidden>") << "\n";
if (runMode_ == RunMode::server && cur.usersFromFile) {
ss << " Users :\n";
for (const auto &u: cur.users) {
ss << " " << u.name << (u.enabled ? "" : " (disabled)")
<< (u.limit ? " limit " + formatBytes(u.limit) : std::string()) << "\n";
}
}
return ss.str();
}
/**
* @brief Returns the General configuration section.
*/
const Config::General &Config::general() const {
std::lock_guard<std::mutex> lock(configMutex_);
return general_;
return current().general;
}
/**
* @brief Returns the Log configuration section.
*/
const Config::Log &Config::log() const {
std::lock_guard<std::mutex> lock(configMutex_);
return log_;
return current().log;
}
/**
* @brief Returns the Server configuration section.
*/
const Config::Server &Config::server() const {
std::lock_guard<std::mutex> lock(configMutex_);
return server_;
return current().server;
}
/**
* @brief Returns the Agent configuration section.
*/
const Config::Agent &Config::agent() const {
std::lock_guard<std::mutex> lock(configMutex_);
return agent_;
return current().agent;
}
/**
* @brief Gets the current thread count.
*/
const unsigned short &Config::threads() const {
const std::vector<User> &Config::users() const {
return current().users;
}
const std::vector<std::string> &Config::warnings() const {
return current().warnings;
}
bool Config::hasUserList() const {
return current().usersFromFile;
}
const std::string &Config::usageFile() const {
return current().usageFile;
}
int Config::usageResetDay() const {
return current().usageResetDay;
}
unsigned short Config::threads() const {
std::lock_guard<std::mutex> lock(configMutex_);
return threads_;
}
/**
* @brief Sets the thread count at runtime.
*/
void Config::threads(unsigned short threads) {
std::lock_guard<std::mutex> lock(configMutex_);
threads_ = threads;
}
/**
* @brief Gets the listening IP address.
*/
const std::string &Config::listenIp() const {
std::lock_guard<std::mutex> lock(configMutex_);
return listenIp_;
}
/**
* @brief Sets the listening IP address at runtime.
*/
void Config::listenIp(const std::string &ip) {
std::lock_guard<std::mutex> lock(configMutex_);
listenIp_ = ip;
}
/**
* @brief Gets the listening port.
*/
const unsigned short &Config::listenPort() const {
unsigned short Config::listenPort() const {
std::lock_guard<std::mutex> lock(configMutex_);
return listenPort_;
}
/**
* @brief Sets the listening port at runtime.
*/
void Config::listenPort(unsigned short port) {
std::lock_guard<std::mutex> lock(configMutex_);
listenPort_ = port;
}
/**
* @brief Returns the current runtime mode.
*/
const RunMode &Config::runMode() const {
RunMode Config::runMode() const {
std::lock_guard<std::mutex> lock(configMutex_);
return runMode_;
}
/**
* @brief Returns the configuration file path.
*/
const std::string &Config::filePath() const {
std::lock_guard<std::mutex> lock(configMutex_);
return filePath_;
}
/**
* @brief Converts the runtime mode to a string.
*
* @return "server" or "agent" depending on the current mode.
*/
std::string Config::modeToString() const {
std::lock_guard<std::mutex> lock(configMutex_);
@@ -260,4 +343,52 @@ std::string Config::modeToString() const {
default:
return "UNKNOWN MODE";
}
}
std::string Config::randomFakeUrl() const {
const Agent &agent_ = current().agent;
if (agent_.fakeUrls.empty()) {
return "www.google.com";
}
static thread_local std::mt19937 generator{std::random_device{}()};
std::uniform_int_distribution<std::size_t> distribution(
0,
agent_.fakeUrls.size() - 1);
return agent_.fakeUrls[distribution(generator)];
}
std::string Config::randomMethod() const {
const Agent &agent_ = current().agent;
if (agent_.methods.empty()) {
return "GET";
}
static thread_local std::mt19937 generator{std::random_device{}()};
std::uniform_int_distribution<std::size_t> distribution(
0,
agent_.methods.size() - 1);
return agent_.methods[distribution(generator)];
}
std::string Config::randomEndPoint() const {
const Agent &agent_ = current().agent;
if (agent_.endPoints.empty()) {
return "api";
}
static thread_local std::mt19937 generator{std::random_device{}()};
std::uniform_int_distribution<std::size_t> distribution(
0,
agent_.endPoints.size() - 1);
return agent_.endPoints[distribution(generator)];
}
+109 -175
View File
@@ -2,221 +2,155 @@
#include <yaml-cpp/yaml.h>
#include <atomic>
#include <cstdint>
#include <memory>
#include <mutex>
#include <random>
#include <sstream>
#include <string>
#include <vector>
#include "general.hpp"
/**
* @brief Defines the runtime mode of the application.
*
* @details
* - `server`: Runs in server mode, accepting incoming client connections.
* - `agent`: Runs in agent mode, forwarding traffic to a remote server.
*/
enum class RunMode {
server,
agent
};
/**
* @brief The `Config` class manages application configuration loaded from a YAML file.
*
* @details
* - Responsible for parsing and storing configuration values.
* - Provides structured access to configuration sections:
* - General
* - Log
* - Server
* - Agent
* - Ensures thread-safe access to mutable runtime parameters.
* - Supports both server and agent runtime modes.
*
* @note
* - Inherits from `Uncopyable` to prevent unintended copying.
* - Uses shared ownership via `std::shared_ptr` (see `pointer` alias).
* - Configuration values are primarily immutable after initialization,
* except for selected runtime-adjustable parameters.
*/
struct User {
std::string name;
std::string token;
std::string key;
bool enabled;
std::uint64_t limit = 0;
};
class Config : private Uncopyable {
private:
/**
* @brief General configuration section.
*
* @details
* - Contains global settings shared across components.
*/
struct General {
std::string token; ///< Shared secret used for encryption/decryption.
std::string fakeUrl; ///< Fake URL used for obfuscation.
std::string method; ///< HTTP method used for requests.
unsigned short timeout; ///< Network timeout in seconds.
std::string chunkHeader;///< Custom header for chunked communication.
};
/**
* @brief Logging configuration section.
*/
struct Log {
std::string level;///< Log level (e.g., DEBUG, INFO, ERROR).
std::string file; ///< Output file path for logs.
};
/**
* @brief Server configuration section.
*
* @details
* - Defines listening parameters and TLS settings for server mode.
*/
struct Server {
unsigned short threads; ///< Number of worker threads.
std::string listenIp; ///< IP address to bind.
unsigned short listenPort;///< Port to listen on.
bool tlsEnable; ///< Enables TLS for incoming connections.
bool tlsVerifyPeer; ///< Enables peer certificate verification.
std::string tlsCertFile;///< Path to TLS certificate file.
std::string tlsKeyFile; ///< Path to TLS private key file.
std::string tlsCaFile; ///< Path to CA certificate file.
};
/**
* @brief Agent configuration section.
*
* @details
* - Defines client-side behavior and remote server connection settings.
*/
struct Agent {
unsigned short threads; ///< Number of worker threads.
std::string listenIp; ///< Local listening IP address.
unsigned short listenPort;///< Local listening port.
std::string serverIp; ///< Remote server IP address.
unsigned short serverPort;///< Remote server port.
std::string httpVersion; ///< HTTP version used for requests.
std::string userAgent; ///< User-Agent header value.
bool tlsEnable; ///< Enables TLS for outbound connections.
bool tlsVerifyPeer; ///< Enables server certificate verification.
std::string tlsCaFile;///< Path to CA certificate file.
};
const RunMode &runMode_; ///< Current runtime mode.
std::string filePath_; ///< Path to the configuration file.
const YAML::Node configYaml_;///< Parsed YAML configuration root.
unsigned short threads_; ///< Runtime thread count.
std::string listenIp_; ///< Runtime listening IP.
unsigned short listenPort_;///< Runtime listening port.
mutable std::mutex configMutex_;///< Mutex for thread-safe runtime updates.
/**
* @brief Private constructor for initializing configuration from file.
*
* @param mode Runtime mode (server or agent).
* @param filePath Path to the YAML configuration file.
*/
explicit Config(const RunMode &mode, const std::string &filePath);
public:
struct General {
unsigned short timeout;
bool tunnelEnable;
bool aesEnable;
bool tlsEnable;
};
struct Log {
std::string level;
std::string file;
};
struct Server {
unsigned short threads;
std::string listenIp;
unsigned short listenPort;
unsigned int bufferSize;
std::string tlsCertFile;
std::string tlsKeyFile;
};
struct Agent {
unsigned short threads;
std::string listenIp;
unsigned short listenPort;
std::string serverIp;
unsigned short serverPort;
std::string httpVersion;
std::string userAgent;
std::string token;
std::string protocol;
std::vector<std::string> fakeUrls;
std::vector<std::string> methods;
std::vector<std::string> endPoints;
unsigned short pullTimeout;
bool connectionReuse;
bool tlsVerifyPeer;
std::string tlsCaFile;
};
struct Settings {
General general;
Log log;
Server server;
Agent agent;
std::vector<User> users;
bool usersFromFile = false;
std::string usageFile;
int usageResetDay = 1;
std::vector<std::string> warnings;
};
struct ReloadResult {
bool ok;
std::string message;
std::vector<std::string> revokedUsers;
};
using pointer = std::shared_ptr<Config>;
/**
* @brief Factory method to create a new `Config` instance.
*
* @param mode Runtime mode.
* @param filePath Path to the configuration file.
* @return Shared pointer to the created `Config`.
*/
static pointer create(const RunMode &mode, const std::string &filePath) {
static pointer create(RunMode mode, const std::string &filePath) {
return pointer(new Config(mode, filePath));
}
const General general_;///< General configuration section.
const Log log_; ///< Logging configuration section.
const Server server_; ///< Server configuration section.
const Agent agent_; ///< Agent configuration section.
/**
* @brief Copy constructor from shared pointer.
*
* @param config Existing configuration instance.
*/
explicit Config(const Config::pointer &config);
/**
* @brief Destructor for `Config`.
*/
~Config();
/// @name Section Accessors
/// @{
const General &general() const;
const Log &log() const;
const Server &server() const;
const Agent &agent() const;
const std::vector<User> &users() const;
const std::vector<std::string> &warnings() const;
bool hasUserList() const;
const std::string &usageFile() const;
int usageResetDay() const;
/// @}
ReloadResult reload();
/// @name Runtime Configuration Accessors
/// @{
unsigned short threads() const;
/**
* @brief Gets the current thread count.
*/
const unsigned short &threads() const;
/**
* @brief Sets the thread count.
*/
void threads(unsigned short threads);
/**
* @brief Gets the listening IP address.
*/
const std::string &listenIp() const;
/**
* @brief Sets the listening IP address.
*/
void listenIp(const std::string &ip);
/**
* @brief Gets the listening port.
*/
const unsigned short &listenPort() const;
unsigned short listenPort() const;
/**
* @brief Sets the listening port.
*/
void listenPort(unsigned short port);
/// @}
RunMode runMode() const;
/**
* @brief Gets the current runtime mode.
*/
const RunMode &runMode() const;
/**
* @brief Gets the configuration file path.
*/
const std::string &filePath() const;
/**
* @brief Converts the runtime mode to a string representation.
*
* @return String representation of the mode.
*/
std::string modeToString() const;
/**
* @brief Converts the full configuration into a human-readable string.
*
* @return Serialized configuration string.
*/
std::string toString() const;
};
std::string randomFakeUrl() const;
std::string randomMethod() const;
std::string randomEndPoint() const;
private:
explicit Config(RunMode mode, const std::string &filePath);
static std::unique_ptr<Settings> load(RunMode mode, const std::string &filePath);
const Settings &current() const;
void publish(std::unique_ptr<Settings> settings);
RunMode runMode_;
std::string filePath_;
unsigned short threads_;
std::string listenIp_;
unsigned short listenPort_;
mutable std::mutex configMutex_;
std::atomic<const Settings *> current_{nullptr};
std::vector<std::unique_ptr<const Settings>> snapshots_;
std::mutex reloadMutex_;
};
+393 -246
View File
@@ -1,8 +1,10 @@
#pragma once
#include <openssl/conf.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include <yaml-cpp/yaml.h>
@@ -14,23 +16,21 @@
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <cstdint>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
/**
* @brief Base class used to disable copy construction and copy assignment.
*
* @details
* - Intended to be inherited privately by classes that must not be copied.
* - Keeps the default constructor available.
* - Deletes copy constructor and copy assignment operator.
*/
static constexpr std::size_t BufferSize = 65536;
static constexpr std::size_t MinTokenLength = 32;
static constexpr const char *SampleToken = "af445adb-2434-4975-9445-2c1b2231";
class Uncopyable {
public:
Uncopyable() = default;
@@ -40,62 +40,26 @@ private:
Uncopyable &operator=(const Uncopyable &) = delete;
};
/**
* @brief Prints a message to standard output.
*
* @details
* - Intended for quick debugging output.
* - Prefixes the message with a fixed marker.
*
* @param message Value to be written to `std::cout`.
*/
inline void OUT(const auto &message) {
std::cout << "OUT OUT OUT OUT OUT OUT OUT OUT : " << message
<< std::endl;
}
/**
* @brief Simple result structure containing a success flag and message.
*
* @details
* - Commonly used to return operation status along with an explanatory message.
*/
struct BoolStr {
bool ok; ///< Indicates whether the operation succeeded.
std::string message;///< Contains the result or error message.
bool ok;
std::string message;
};
/**
* @brief Checks whether a file exists.
*
* @param name Path to the file.
* @return `true` if the file exists and is accessible, otherwise `false`.
*/
inline bool fileExists(const std::string &name) {
std::ifstream file(name.c_str());
return file.good();
}
/**
* @brief Converts a Boost.Asio stream buffer into a string.
*
* @param buff Reference to the stream buffer.
* @return String containing the current contents of the buffer.
*/
inline std::string streambufToString(const boost::asio::streambuf &buff) {
return {boost::asio::buffers_begin(buff.data()),
boost::asio::buffers_begin(buff.data()) + buff.size()};
}
/**
* @brief Replaces the contents of a stream buffer with a string.
*
* @details
* - Clears the destination buffer before writing the new string.
*
* @param inputStr Source string to copy into the buffer.
* @param buff Destination stream buffer.
*/
inline void copyStringToStreambuf(const std::string &inputStr,
boost::asio::streambuf &buff) {
buff.consume(buff.size());
@@ -103,16 +67,6 @@ inline void copyStringToStreambuf(const std::string &inputStr,
os << inputStr;
}
/**
* @brief Moves all data from one stream buffer to another.
*
* @details
* - Copies the source buffer contents into the target buffer.
* - Consumes all data from the source buffer after copying.
*
* @param source Source stream buffer.
* @param target Target stream buffer.
*/
inline void moveStreambuf(boost::asio::streambuf &source,
boost::asio::streambuf &target) {
auto bytes_copied =
@@ -121,15 +75,6 @@ inline void moveStreambuf(boost::asio::streambuf &source,
source.consume(source.size());
}
/**
* @brief Copies all data from one stream buffer to another.
*
* @details
* - Leaves the source buffer unchanged.
*
* @param source Source stream buffer.
* @param target Target stream buffer.
*/
inline void copyStreambuf(boost::asio::streambuf &source,
boost::asio::streambuf &target) {
auto bytes_copied =
@@ -137,13 +82,6 @@ inline void copyStreambuf(boost::asio::streambuf &source,
target.commit(bytes_copied);
}
/**
* @brief Converts a byte array to its hexadecimal string representation.
*
* @param data Pointer to the input byte array.
* @param size Number of bytes in the array.
* @return Lowercase hexadecimal string representation of the input.
*/
inline std::string hexArrToStr(const unsigned char *data, std::size_t size) {
std::stringstream tempStr;
tempStr << std::hex << std::setfill('0');
@@ -155,29 +93,13 @@ inline std::string hexArrToStr(const unsigned char *data, std::size_t size) {
return tempStr.str();
}
/**
* @brief Converts a hexadecimal string to an integer.
*
* @param hexString Hexadecimal string input.
* @return Parsed value as an unsigned integer.
*/
inline unsigned int hexToInt(const std::string &hexString) {
unsigned short result;
unsigned int result{};
std::stringstream hexStr(hexString);
hexStr >> std::hex >> result;
return result;
}
/**
* @brief Converts a hexadecimal string into its ASCII string representation.
*
* @details
* - Processes the input two characters at a time.
* - Each hexadecimal byte is converted into its character equivalent.
*
* @param hex Hexadecimal string input.
* @return Decoded ASCII string.
*/
inline std::string hexToASCII(const std::string &hex) {
std::string ascii;
@@ -190,12 +112,6 @@ inline std::string hexToASCII(const std::string &hex) {
return ascii;
}
/**
* @brief Converts a hexadecimal character into its numeric value.
*
* @param c Input character.
* @return Numeric value of the hexadecimal character, or `0` if invalid.
*/
inline unsigned char charToHex(char c) {
if ('0' <= c && c <= '9') return c - '0';
if ('A' <= c && c <= 'F') return c - 'A' + 10;
@@ -203,12 +119,6 @@ inline unsigned char charToHex(char c) {
return 0;
}
/**
* @brief Converts a hexadecimal string into a byte array.
*
* @param hexStr Hexadecimal string input.
* @return Vector containing the decoded bytes.
*/
inline std::vector<unsigned char> strToHexArr(const std::string &hexStr) {
std::vector<unsigned char> result(hexStr.size() / 2);
@@ -219,29 +129,12 @@ inline std::vector<unsigned char> strToHexArr(const std::string &hexStr) {
return result;
}
/**
* @brief Converts a stream buffer into a hexadecimal string.
*
* @details
* - First converts the stream buffer into a raw string.
* - Then converts the raw bytes into a hexadecimal representation.
*
* @param buff Source stream buffer.
* @return Hexadecimal string representation of the buffer contents.
*/
inline std::string hexStreambufToStr(const boost::asio::streambuf &buff) {
return hexArrToStr(
reinterpret_cast<const unsigned char *>(streambufToString(buff).c_str()),
buff.size());
}
/**
* @brief Splits a string using a delimiter.
*
* @param str Input string.
* @param delimiter Delimiter string.
* @return Vector containing the split parts.
*/
inline std::vector<std::string> splitString(const std::string &str,
const std::string &delimiter) {
std::vector<std::string> result;
@@ -266,17 +159,6 @@ inline std::vector<std::string> splitString(const std::string &str,
return result;
}
/**
* @brief Decodes a Base64-encoded string.
*
* @details
* - Trims trailing padding characters before decoding.
* - Uses Boost archive iterators for Base64 decoding.
* - Throws `std::runtime_error` if decoding fails.
*
* @param inputStr Base64-encoded input string.
* @return Decoded binary string.
*/
inline std::string decode64(const std::string &inputStr) {
using namespace boost::archive::iterators;
@@ -293,16 +175,6 @@ inline std::string decode64(const std::string &inputStr) {
}
}
/**
* @brief Encodes a string into Base64 format.
*
* @details
* - Uses Boost archive iterators for Base64 encoding.
* - Appends the required padding characters (`=`).
*
* @param inputStr Input string.
* @return Base64-encoded string.
*/
inline std::string encode64(const std::string &inputStr) {
using namespace boost::archive::iterators;
@@ -317,134 +189,127 @@ inline std::string encode64(const std::string &inputStr) {
return encoded;
}
/**
* @brief Encrypts a string using AES-256-CBC.
*
* @details
* - Generates a random IV for each encryption operation.
* - Prepends the IV to the encrypted output.
* - Uses OpenSSL EVP APIs for encryption.
*
* @param plaintext Input plaintext string.
* @param key Encryption key.
* @return A `BoolStr` containing success status and encrypted data or an error message.
*/
inline BoolStr aes256Encrypt(const std::string &plaintext,
const std::string &key) {
static constexpr std::size_t AesGcmNonceLength = 12;
static constexpr std::size_t AesGcmTagLength = 16;
inline std::string deriveAesKey(const std::string &token) {
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digestLen = 0;
EVP_Digest(token.data(), token.size(), digest, &digestLen, EVP_sha256(), NULL);
return std::string(reinterpret_cast<char *>(digest), digestLen);
}
inline BoolStr aes256EncryptWithKey(const std::string &plaintext,
const std::string &key) {
BoolStr result{false, "Encryption failed"};
unsigned char iv[EVP_MAX_IV_LENGTH];
if (!RAND_bytes(iv, sizeof(iv))) {
result.message = "IV generation failed";
unsigned char nonce[AesGcmNonceLength];
if (!RAND_bytes(nonce, sizeof(nonce))) {
result.message = "Nonce generation failed";
return result;
}
int ciphertext_len =
plaintext.size() + EVP_CIPHER_block_size(EVP_aes_256_cbc());
std::vector<unsigned char> ciphertext(ciphertext_len);
std::vector<unsigned char> ciphertext(plaintext.size());
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
using EvpCipherCtxPtr = std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)>;
EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
if (!ctx) {
result.message = "Context initialization failed";
return result;
}
if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
reinterpret_cast<const unsigned char *>(key.c_str()),
iv) != 1) {
EVP_CIPHER_CTX_free(ctx);
if (EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL) != 1 ||
EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, AesGcmNonceLength, NULL) != 1 ||
EVP_EncryptInit_ex(ctx.get(), NULL, NULL,
reinterpret_cast<const unsigned char *>(key.data()),
nonce) != 1) {
result.message = "Encryption initialization failed";
return result;
}
int len;
int len = 0;
if (EVP_EncryptUpdate(
ctx, ciphertext.data(), &len,
reinterpret_cast<const unsigned char *>(plaintext.c_str()),
ctx.get(), ciphertext.data(), &len,
reinterpret_cast<const unsigned char *>(plaintext.data()),
plaintext.size()) != 1) {
EVP_CIPHER_CTX_free(ctx);
result.message = "Encryption update failed";
return result;
}
ciphertext_len = len;
int ciphertext_len = len;
if (EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len) != 1) {
EVP_CIPHER_CTX_free(ctx);
if (EVP_EncryptFinal_ex(ctx.get(), ciphertext.data() + len, &len) != 1) {
result.message = "Encryption finalization failed";
return result;
}
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
unsigned char tag[AesGcmTagLength];
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, AesGcmTagLength, tag) != 1) {
result.message = "Tag generation failed";
return result;
}
std::string final_result(reinterpret_cast<char *>(iv), sizeof(iv));
final_result.append(reinterpret_cast<char *>(ciphertext.data()),
ciphertext_len);
std::string final_result(reinterpret_cast<char *>(nonce), sizeof(nonce));
final_result.append(reinterpret_cast<char *>(ciphertext.data()), ciphertext_len);
final_result.append(reinterpret_cast<char *>(tag), sizeof(tag));
result.ok = true;
result.message = final_result;
return result;
}
/**
* @brief Decrypts an AES-256-CBC encrypted string containing a prepended IV.
*
* @details
* - Extracts the IV from the beginning of the input.
* - Decrypts the remaining ciphertext using OpenSSL EVP APIs.
*
* @param ciphertext_with_iv Encrypted input containing IV + ciphertext.
* @param key Decryption key.
* @return A `BoolStr` containing success status and decrypted plaintext or an error message.
*/
inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
const std::string &key) {
inline BoolStr aes256DecryptWithKey(const std::string &sealed,
const std::string &key) {
BoolStr result{false, "Decryption failed"};
unsigned char iv[EVP_MAX_IV_LENGTH];
std::memcpy(iv, ciphertext_with_iv.c_str(),
EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
if (sealed.size() < AesGcmNonceLength + AesGcmTagLength) {
result.message = "Ciphertext too short";
return result;
}
std::string ciphertext =
ciphertext_with_iv.substr(EVP_CIPHER_iv_length(EVP_aes_256_cbc()));
const auto *nonce = reinterpret_cast<const unsigned char *>(sealed.data());
const auto *ciphertext = nonce + AesGcmNonceLength;
const std::size_t ciphertextLen = sealed.size() - AesGcmNonceLength - AesGcmTagLength;
std::string tag = sealed.substr(sealed.size() - AesGcmTagLength);
int max_plaintext_len = ciphertext.size();
std::vector<unsigned char> plaintext(max_plaintext_len);
std::vector<unsigned char> plaintext(ciphertextLen);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
using EvpCipherCtxPtr = std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)>;
EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
if (!ctx) {
result.message = "Context initialization failed";
return result;
}
if (EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
reinterpret_cast<const unsigned char *>(key.c_str()),
iv) != 1) {
EVP_CIPHER_CTX_free(ctx);
if (EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL) != 1 ||
EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, AesGcmNonceLength, NULL) != 1 ||
EVP_DecryptInit_ex(ctx.get(), NULL, NULL,
reinterpret_cast<const unsigned char *>(key.data()),
nonce) != 1) {
result.message = "Decryption initialization failed";
return result;
}
int len;
if (EVP_DecryptUpdate(
ctx, plaintext.data(), &len,
reinterpret_cast<const unsigned char *>(ciphertext.c_str()),
ciphertext.size()) != 1) {
EVP_CIPHER_CTX_free(ctx);
int len = 0;
if (EVP_DecryptUpdate(ctx.get(), plaintext.data(), &len, ciphertext,
ciphertextLen) != 1) {
result.message = "Decryption update failed";
return result;
}
int plaintext_len = len;
if (EVP_DecryptFinal_ex(ctx, plaintext.data() + len, &len) != 1) {
EVP_CIPHER_CTX_free(ctx);
result.message = "Decryption finalization failed";
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, AesGcmTagLength,
tag.data()) != 1) {
result.message = "Setting tag failed";
return result;
}
if (EVP_DecryptFinal_ex(ctx.get(), plaintext.data() + len, &len) != 1) {
result.message = "Authentication failed (wrong token or tampered payload)";
return result;
}
plaintext_len += len;
EVP_CIPHER_CTX_free(ctx);
result.ok = true;
result.message =
std::string(reinterpret_cast<char *>(plaintext.data()), plaintext_len);
@@ -452,48 +317,164 @@ inline BoolStr aes256Decrypt(const std::string &ciphertext_with_iv,
return result;
}
/**
* @brief Validates command-line arguments and the configuration file.
*
* @details
* - Verifies the expected number of arguments.
* - Ensures the selected mode is either `server` or `agent`.
* - Checks that the configuration file exists.
* - Loads and parses the YAML configuration file.
* - Validates required keys in the following sections:
* - `general`
* - `log`
* - `server`
* - `agent`
*
* @param argc Number of command-line arguments.
* @param argv Array of command-line argument strings.
* @return A `BoolStr` containing validation status and an explanatory message.
*/
inline BoolStr validateConfig(int argc, const char *argv[]) {
constexpr std::size_t HmacTagLength = 32;
inline std::string hmacSha256(const std::string &data, const std::string &key) {
unsigned char tag[EVP_MAX_MD_SIZE];
unsigned int tagLen = 0;
HMAC(EVP_sha256(), key.data(), static_cast<int>(key.size()),
reinterpret_cast<const unsigned char *>(data.data()), data.size(), tag, &tagLen);
return std::string(reinterpret_cast<char *>(tag), tagLen);
}
inline std::string signWithKey(const std::string &payload, const std::string &key) {
return payload + hmacSha256(payload, key);
}
inline BoolStr verifyWithKey(const std::string &signedPayload, const std::string &key) {
if (signedPayload.size() < HmacTagLength) return {false, "payload too short for a signature"};
const std::string payload = signedPayload.substr(0, signedPayload.size() - HmacTagLength);
const std::string tag = hmacSha256(payload, key);
if (CRYPTO_memcmp(tag.data(), signedPayload.data() + payload.size(), HmacTagLength) != 0) {
return {false, "signature does not match"};
}
return {true, payload};
}
inline BoolStr aes256Encrypt(const std::string &plaintext,
const std::string &token) {
return aes256EncryptWithKey(plaintext, deriveAesKey(token));
}
inline BoolStr aes256Decrypt(const std::string &sealed,
const std::string &token) {
return aes256DecryptWithKey(sealed, deriveAesKey(token));
}
inline std::string makeEnvelope(const std::string &action,
const std::string &session,
const std::string &data) {
return action + "\n" + session + "\n" + data;
}
struct Envelope {
std::string action;
std::string session;
std::string data;
};
inline bool parseEnvelope(const std::string &raw, Envelope &out) {
const auto actionEnd = raw.find('\n');
if (actionEnd == std::string::npos) return false;
const auto sessionEnd = raw.find('\n', actionEnd + 1);
if (sessionEnd == std::string::npos) return false;
out.action = raw.substr(0, actionEnd);
out.session = raw.substr(actionEnd + 1, sessionEnd - actionEnd - 1);
out.data = raw.substr(sessionEnd + 1);
return true;
}
inline bool parseByteSize(const std::string &text, std::uint64_t &out) {
std::size_t i = 0;
while (i < text.size() && text[i] == ' ') ++i;
const std::size_t numStart = i;
bool dot = false;
while (i < text.size() && ((text[i] >= '0' && text[i] <= '9') || (text[i] == '.' && !dot))) {
if (text[i] == '.') dot = true;
++i;
}
if (i == numStart) return false;
double value = 0;
try {
value = std::stod(text.substr(numStart, i - numStart));
} catch (const std::exception &) {
return false;
}
while (i < text.size() && text[i] == ' ') ++i;
std::string unit = text.substr(i);
while (!unit.empty() && unit.back() == ' ') unit.pop_back();
for (auto &c: unit) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
double multiplier = 0;
if (unit == "b") multiplier = 1;
else if (unit == "kb")
multiplier = 1e3;
else if (unit == "mb")
multiplier = 1e6;
else if (unit == "gb")
multiplier = 1e9;
else if (unit == "tb")
multiplier = 1e12;
else if (unit == "kib")
multiplier = 1024.0;
else if (unit == "mib")
multiplier = 1024.0 * 1024;
else if (unit == "gib")
multiplier = 1024.0 * 1024 * 1024;
else if (unit == "tib")
multiplier = 1024.0 * 1024 * 1024 * 1024;
else
return false;
const double bytes = value * multiplier;
if (bytes < 1 || bytes > 1.8e19) return false;
out = static_cast<std::uint64_t>(bytes);
return true;
}
inline std::string formatBytes(std::uint64_t bytes) {
const char *units[] = {"B", "KB", "MB", "GB", "TB", "PB"};
double value = static_cast<double>(bytes);
int unit = 0;
while (value >= 1000 && unit < 5) {
value /= 1000;
++unit;
}
std::ostringstream out;
if (unit == 0) out << bytes << " B";
else
out << std::fixed << std::setprecision(2) << value << " " << units[unit];
return out.str();
}
inline bool isValidUserName(const std::string &name) {
if (name.empty() || name.size() > 64) return false;
for (const char c: name) {
const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '.' || c == '_' ||
c == '-' || c == '@';
if (!ok) return false;
}
return true;
}
inline YAML::Node movedSetting(const YAML::Node &yaml, const char *block, const char *key) {
if (yaml[block][key]) return yaml[block][key];
return yaml["general"][key];
}
inline bool isDeprecatedSetting(const YAML::Node &yaml, const char *block, const char *key) {
return !yaml[block][key] && yaml["general"][key];
}
inline BoolStr validateConfigFile(const std::string &mode, const std::string &path) {
BoolStr result{false, "Validation failed"};
if (argc != 3) {
result.message =
"Requires 2 arguments: mode [server|agent] and config file "
"path\nExample: nipovpn server config.yaml\n";
return result;
}
if (std::string(argv[1]) != "server" && std::string(argv[1]) != "agent") {
if (mode != "server" && mode != "agent") {
result.message = "First argument must be one of [server|agent]\n";
return result;
}
if (!fileExists(argv[2])) {
result.message =
std::string("Config file ") + argv[2] + " does not exist\n";
if (!fileExists(path)) {
result.message = "Config file " + path + " does not exist\n";
return result;
}
YAML::Node configYaml;
try {
configYaml = YAML::LoadFile(argv[2]);
configYaml = YAML::LoadFile(path);
} catch (const std::exception &e) {
result.message =
std::string("Error parsing config file: ") + e.what() + "\n";
@@ -501,11 +482,9 @@ inline BoolStr validateConfig(int argc, const char *argv[]) {
}
try {
configYaml["general"]["token"].as<std::string>();
configYaml["general"]["fakeUrl"].as<std::string>();
configYaml["general"]["method"].as<std::string>();
configYaml["general"]["token"].as<std::string>("");
configYaml["general"]["timeout"].as<unsigned short>();
configYaml["general"]["chunkHeader"].as<std::string>();
configYaml["general"]["tunnelEnable"].as<bool>();
} catch (const std::exception &e) {
result.message = std::string("Error in 'general' block: ") + e.what() + "\n";
return result;
@@ -539,7 +518,175 @@ inline BoolStr validateConfig(int argc, const char *argv[]) {
return result;
}
const char *side = mode == "agent" ? "agent" : "server";
std::string key;
try {
auto check = [&](const char *name, auto sample) {
key = name;
const YAML::Node node = movedSetting(configYaml, side, name);
if (node) node.as<decltype(sample)>();
};
if (mode == "agent") {
check("protocol", std::string());
check("fakeUrls", std::vector<std::string>());
check("methods", std::vector<std::string>());
check("endPoints", std::vector<std::string>());
check("pullTimeout", static_cast<unsigned short>(0));
check("connectionReuse", false);
check("tlsVerifyPeer", false);
check("tlsCaFile", std::string());
} else {
check("bufferSize", 0u);
check("tlsCertFile", std::string());
check("tlsKeyFile", std::string());
}
} catch (const std::exception &e) {
result.message = std::string("Error in ") + side + "." + key + ": " + e.what() + "\n";
return result;
}
if (mode == "agent") {
const std::string protocol = movedSetting(configYaml, "agent", "protocol").as<std::string>("");
if (protocol != "http" && protocol != "socks5") {
result.message = "agent.protocol must be one of [http|socks5]\n";
return result;
}
} else {
const unsigned int bufferSize = movedSetting(configYaml, "server", "bufferSize").as<unsigned int>(65536);
if (bufferSize < 1 || bufferSize > 65536) {
result.message = "server.bufferSize must be between 1 and 65536\n";
return result;
}
}
const std::string logLevel = configYaml["log"]["logLevel"].as<std::string>();
if (logLevel != "INFO" && logLevel != "TRACE" && logLevel != "DEBUG") {
result.message = "logLevel must be one of [INFO|TRACE|DEBUG]\n";
return result;
}
const bool aesEnable = configYaml["general"]["aesEnable"].as<bool>(true);
std::string agentToken;
try {
agentToken = configYaml["agent"]["token"].as<std::string>("");
} catch (const std::exception &e) {
result.message = std::string("Error in agent.token: ") + e.what() + "\n";
return result;
}
const std::string legacyToken = configYaml["general"]["token"].as<std::string>("");
for (const char *block: {"users", "usage"}) {
if (configYaml[block]) {
result.message = std::string(block) + " belongs under the server block: move it to server." +
block + "\n";
return result;
}
}
const YAML::Node users = configYaml["server"]["users"];
const bool serverUsers = mode == "server" && users && !users.IsNull();
if (mode == "agent") {
const std::string token = agentToken.empty() ? legacyToken : agentToken;
if (token.empty()) {
result.message = "agent.token is required\n";
return result;
}
if (token.size() < MinTokenLength) {
result.message = "agent.token must be at least 32 bytes\n";
return result;
}
} else if (serverUsers) {
if (!users.IsSequence()) {
result.message = "server.users must be a list\n";
return result;
}
if (users.size() == 0) {
result.message = "server.users must have at least one entry\n";
return result;
}
std::vector<std::string> names;
std::vector<std::string> tokens;
for (std::size_t i = 0; i < users.size(); ++i) {
const YAML::Node user = users[i];
const std::string where = "server.users[" + std::to_string(i) + "]";
std::string name;
std::string userToken;
try {
if (!user.IsMap()) throw std::runtime_error("must be a map with name and token");
name = user["name"].as<std::string>();
userToken = user["token"].as<std::string>();
user["enabled"].as<bool>(true);
if (user["limit"]) {
std::uint64_t limit = 0;
if (!parseByteSize(user["limit"].as<std::string>(), limit)) {
throw std::runtime_error(
"limit must be a size with a unit, such as 2GB, 500MB or 1.5GiB");
}
}
} catch (const std::exception &e) {
result.message = "Error in " + where + ": " + e.what() + "\n";
return result;
}
if (!isValidUserName(name)) {
result.message = where + ".name must be 1-64 characters of [A-Za-z0-9._@-]\n";
return result;
}
if (userToken.size() < MinTokenLength) {
result.message = "token of user " + name + " must be at least " +
std::to_string(MinTokenLength) + " bytes\n";
return result;
}
for (const auto &n: names) {
if (n == name) {
result.message = "user name " + name + " is used more than once\n";
return result;
}
}
for (std::size_t j = 0; j < tokens.size(); ++j) {
if (tokens[j] == userToken) {
result.message = "users " + names[j] + " and " + name + " have the same token\n";
return result;
}
}
names.push_back(name);
tokens.push_back(userToken);
}
if (const YAML::Node usage = configYaml["server"]["usage"]) {
try {
usage["file"].as<std::string>("");
const int resetDay = usage["resetDay"].as<int>(1);
if (resetDay < 1 || resetDay > 28) {
throw std::runtime_error("resetDay must be between 1 and 28");
}
} catch (const std::exception &e) {
result.message = std::string("Error in server.usage: ") + e.what() + "\n";
return result;
}
}
} else if (aesEnable) {
if (legacyToken.empty()) {
result.message = "the server needs a server.users list with at least one user\n";
return result;
}
if (legacyToken.size() < MinTokenLength) {
result.message = "general.token must be at least 32 bytes when aesEnable is true\n";
return result;
}
}
result.ok = true;
result.message = "OK";
return result;
}
inline BoolStr validateConfig(int argc, const char *argv[]) {
if (argc != 3) {
return {false,
"Requires 2 arguments: mode [server|agent] and config file "
"path\nExample: nipovpn server config.yaml\n"};
}
return validateConfigFile(argv[1], argv[2]);
}
+118 -211
View File
@@ -1,22 +1,5 @@
#include "http.hpp"
/**
* @brief Constructs an `HTTP` instance with configuration, logging, input buffer,
* and session identifier.
*
* @details
* - Stores references to the configuration, logging, and stream buffer objects.
* - Initializes the parsed HTTP request object and default HTTP type.
* - Initializes the parsed TLS request state with empty values and a default
* TLS handshake type.
* - Stores the UUID used for logging and tracing this session.
* - Sets the default chunk header state to `"no"`.
*
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param buffer Reference to the stream buffer containing raw request or response data.
* @param uuid Unique identifier for the current session.
*/
HTTP::HTTP(const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
boost::asio::streambuf &buffer,
@@ -28,20 +11,8 @@ HTTP::HTTP(const std::shared_ptr<Config> &config,
httpType_(HTTP::HttpType::https),
parsedTlsRequest_{"", "", TlsTypes::TLSHandshake},
uuid_(uuid) {
chunkHeader_ = "no";
}
/**
* @brief Copy-constructs an `HTTP` instance from another instance.
*
* @details
* - Copies references to the configuration, logging, and stream buffer objects.
* - Copies the parsed HTTP request and parsed TLS request state.
* - Copies the UUID for session identification.
* - Resets the chunk header state to `"no"`.
*
* @param http Existing `HTTP` object to copy.
*/
HTTP::HTTP(const HTTP &http)
: config_(http.config_),
log_(http.log_),
@@ -49,33 +20,10 @@ HTTP::HTTP(const HTTP &http)
parsedHttpRequest_(http.parsedHttpRequest_),
parsedTlsRequest_(http.parsedTlsRequest_),
uuid_(http.uuid_) {
chunkHeader_ = "no";
}
/**
* @brief Destroys the `HTTP` instance.
*
* @details
* - Performs no explicit cleanup.
* - Resource management is handled by referenced objects and standard class members.
*/
HTTP::~HTTP() {}
/**
* @brief Detects whether the current buffer contains TLS-related traffic or HTTP traffic.
*
* @details
* - Reads the input buffer as a hexadecimal string.
* - Inspects the first byte to distinguish TLS record types from plain HTTP data.
* - Treats values `16`, `14`, and `17` as TLS record types:
* - `16`: Handshake
* - `14`: ChangeCipherSpec
* - `17`: ApplicationData
* - For TLS traffic, stores the raw body and invokes `parseTls()`.
* - For non-TLS traffic, invokes `parseHttp()`.
*
* @return `true` if the request type is successfully detected and parsed, otherwise `false`.
*/
bool HTTP::detectType() {
std::string requestStr{hexStreambufToStr(buffer_)};
std::string tmpStr;
@@ -99,19 +47,6 @@ bool HTTP::detectType() {
}
}
/**
* @brief Parses an HTTP request from the current input buffer.
*
* @details
* - Converts the stream buffer contents to a string.
* - Uses Boost.Beast request parsing to parse the HTTP request.
* - Detects whether the request method is `CONNECT` or a normal HTTP method.
* - Sets the internal HTTP type accordingly.
* - Extracts and stores the destination IP address and port.
* - Logs parsing errors when request parsing fails.
*
* @return `true` if parsing succeeds, otherwise `false`.
*/
bool HTTP::parseHttp() {
std::string requestStr(streambufToString(buffer_));
boost::beast::http::request_parser<boost::beast::http::string_body> parser;
@@ -137,17 +72,6 @@ bool HTTP::parseHttp() {
}
}
/**
* @brief Parses an HTTP response from the current input buffer.
*
* @details
* - Converts the stream buffer contents to a string.
* - Uses the internal Boost.Beast parser to parse the HTTP response.
* - Stores the parsed response object on success.
* - Logs parsing errors when response parsing fails.
*
* @return `true` if parsing succeeds, otherwise `false`.
*/
bool HTTP::parseHttpResp() {
std::string requestStr(streambufToString(buffer_));
parser_.eager(true);
@@ -165,21 +89,6 @@ bool HTTP::parseHttpResp() {
}
}
/**
* @brief Parses TLS request data from the stored TLS body.
*
* @details
* - Inspects the TLS record type from the first byte of the hex-encoded body.
* - Supports parsing of:
* - TLS Handshake
* - ChangeCipherSpec
* - ApplicationData
* - For TLS handshake records, attempts to extract the Server Name Indication (SNI)
* from the ClientHello message.
* - Updates destination IP and port after successful parsing.
*
* @return `true` if parsing succeeds, otherwise `false`.
*/
bool HTTP::parseTls() {
std::string tmpStr;
unsigned short pos = 0;
@@ -244,132 +153,149 @@ bool HTTP::parseTls() {
return false;
}
/**
* @brief Generates an HTTP POST request string containing the provided body.
*
* @details
* - Builds an HTTP request using configured method, fake URL, HTTP version,
* and User-Agent.
* - Sets common headers including `Host`, `Accept`, `Connection`,
* `Content-Length`, and `Content-Type`.
* - Appends the payload body followed by the application terminator marker.
*
* @param body Body content to include in the HTTP request.
* @return Serialized HTTP POST request string.
*/
const std::string HTTP::genHttpPostReqString(const std::string &body) const {
return std::string(config_->general().method + " " +
config_->general().fakeUrl + " HTTP/" +
config_->agent().httpVersion + "\r\n") +
"Host: " + config_->general().fakeUrl + "\r\n" +
"User-Agent: " + config_->agent().userAgent + "\r\n" +
"Accept: */*\r\n" + "Connection: keep-alive\r\n" +
"Content-Length: " + std::to_string(body.length()) + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" + "\r\n" + body + "COMP\r\n\r\n";
}
/**
* @brief Generates a REST-style HTTP POST request string.
*
* @details
* - Builds an HTTP request using configured method, fake URL, HTTP version,
* and User-Agent.
* - Adds the custom `Rest: yes` header to mark the request as a REST-style operation.
* - Appends the application terminator marker.
*
* @return Serialized REST-style HTTP POST request string.
*/
const std::string HTTP::genHttpRestPostReqString() const {
return std::string(config_->general().method + " " +
config_->general().fakeUrl + " HTTP/" +
config_->agent().httpVersion + "\r\n") +
"Host: " + config_->general().fakeUrl + "\r\n" +
"User-Agent: " + config_->agent().userAgent + "\r\n" +
"Accept: */*\r\n" + "Connection: keep-alive\r\n" +
"Rest: yes\r\n" + "COMP\r\n\r\n";
}
/**
* @brief Generates an HTTP `200 OK` response string.
*
* @details
* - Builds a successful HTTP response with content type, content length,
* custom chunk header, and cache-related headers.
* - Appends the response body followed by the application terminator marker.
*
* @param body Body content to include in the HTTP response.
* @return Serialized HTTP `200 OK` response string.
*/
const std::string HTTP::genHttpOkResString(const std::string &body) const {
std::string HTTP::genHttpOkResString(const std::string &body) const {
return std::string("HTTP/1.1 200 OK\r\n") +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + std::to_string(body.length()) + "\r\n" +
config_->general().chunkHeader + ": " + chunkHeader_ + "\r\n" +
"Connection: keep-alive\r\n" + "Cache-Control: no-cache\r\n" +
"Pragma: no-cache\r\n" + "\r\n" + body + "COMP\r\n\r\n";
}
/**
* @brief Extracts and stores destination IP address and port from the parsed request data.
*
* @details
* - For TLS traffic, uses the parsed SNI value and defaults to port `443`
* when no explicit port is provided.
* - For HTTP traffic, extracts the host and optional port from the request target
* and defaults to port `80` when no port is present.
* - For CONNECT traffic, splits the target directly into host and port.
* - Logs an error when HTTP request parsing does not provide a usable target.
*/
bool HTTP::parseHostPort(const std::string &input,
std::string &host,
unsigned short &port,
unsigned short defaultPort) {
host.clear();
port = defaultPort;
if (input.empty()) return false;
auto parsePort = [](const std::string &value,
unsigned short &out) -> bool {
try {
int p = std::stoi(value);
if (p < 1 || p > 65535) return false;
out = static_cast<unsigned short>(p);
return true;
} catch (...) {
return false;
}
};
if (input.front() == '[') {
auto close = input.find(']');
if (close == std::string::npos) return false;
host = input.substr(1, close - 1);
if (close + 1 < input.size()) {
if (input[close + 1] != ':') return false;
if (!parsePort(input.substr(close + 2), port)) return false;
}
return !host.empty();
}
auto firstColon = input.find(':');
auto lastColon = input.rfind(':');
if (firstColon != std::string::npos && firstColon != lastColon) {
const std::string maybePort = input.substr(lastColon + 1);
unsigned short parsedPort = defaultPort;
if (parsePort(maybePort, parsedPort)) {
host = input.substr(0, lastColon);
port = parsedPort;
return !host.empty();
}
host = input;
port = defaultPort;
return true;
}
if (lastColon != std::string::npos) {
host = input.substr(0, lastColon);
if (!parsePort(input.substr(lastColon + 1), port)) return false;
} else {
host = input;
port = defaultPort;
}
return !host.empty();
}
void HTTP::setIPPort() {
std::string target{};
std::vector<std::string> splitted;
switch (httpType()) {
case HTTP::HttpType::https:
case HTTP::HttpType::https: {
target = parsedTlsRequest_.sni;
splitted = splitString(target, ":");
if (splitted.size() > 1) {
dstIP_ = splitted[0];
dstPort_ = std::stoi(splitted[1]);
} else {
dstIP_ = target;
if (!parseHostPort(target, dstIp_, dstPort_, 443)) {
dstIp_.clear();
dstPort_ = 443;
}
break;
}
case HTTP::HttpType::http:
case HTTP::HttpType::http: {
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
splitted = splitString(
splitString(splitString(target, "http://")[1], "/")[0], ":");
if (!splitted.empty()) {
dstIP_ = splitted[0];
std::string hostPort;
if (splitted.size() > 1)
dstPort_ = std::stoi(splitted[1]);
else
dstPort_ = 80;
if (target.rfind("http://", 0) == 0) {
std::string withoutScheme = target.substr(std::string("http://").size());
auto slashPos = withoutScheme.find('/');
hostPort = (slashPos == std::string::npos)
? withoutScheme
: withoutScheme.substr(0, slashPos);
} else if (target.rfind("https://", 0) == 0) {
std::string withoutScheme = target.substr(std::string("https://").size());
auto slashPos = withoutScheme.find('/');
hostPort = (slashPos == std::string::npos)
? withoutScheme
: withoutScheme.substr(0, slashPos);
} else {
log_->write("[" + to_string(uuid_) + "] [HTTP setIPPort] wrong request", Log::Level::DEBUG);
auto hostIt = parsedHttpRequest_.find("Host");
if (hostIt != parsedHttpRequest_.end()) {
hostPort = boost::lexical_cast<std::string>(hostIt->value());
} else {
log_->write("[" + to_string(uuid_) +
"] [HTTP setIPPort] missing Host header",
Log::Level::DEBUG);
dstIp_.clear();
dstPort_ = 80;
break;
}
}
if (!parseHostPort(hostPort, dstIp_, dstPort_, 80)) {
log_->write("[" + to_string(uuid_) +
"] [HTTP setIPPort] wrong request",
Log::Level::DEBUG);
dstIp_.clear();
dstPort_ = 80;
}
break;
case HTTP::HttpType::connect:
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
splitted = splitString(target, ":");
dstIP_ = splitted[0];
dstPort_ = std::stoi(splitted[1]);
break;
}
case HTTP::HttpType::connect: {
target = boost::lexical_cast<std::string>(parsedHttpRequest_.target());
if (!parseHostPort(target, dstIp_, dstPort_, 443)) {
dstIp_.clear();
dstPort_ = 443;
}
break;
}
}
}
/**
* @brief Converts the parsed TLS record type to a string.
*
* @return String representation of the current TLS type.
*/
const std::string HTTP::tlsTypeToString() const {
std::string HTTP::tlsTypeToString() const {
switch (parsedTlsRequest_.type) {
case TlsTypes::TLSHandshake:
return "TLSHandshake";
@@ -382,18 +308,7 @@ const std::string HTTP::tlsTypeToString() const {
}
}
/**
* @brief Converts the current parsed request state into a human-readable string.
*
* @details
* - For TLS traffic, returns TLS type, SNI, body size, and body contents.
* - For HTTP traffic, returns method, version, target, User-Agent, body size,
* and body contents.
* - For CONNECT traffic, returns method and target only.
*
* @return Formatted string representation of the current request state.
*/
const std::string HTTP::toString() const {
std::string HTTP::toString() const {
switch (httpType()) {
case HTTP::HttpType::https:
return std::string("\n") + "TLS Type : " + tlsTypeToString() + "\n" +
@@ -429,15 +344,7 @@ const std::string HTTP::toString() const {
}
}
/**
* @brief Converts the parsed HTTP response into a human-readable string.
*
* @details
* - Returns the response base fields, body size, and body contents.
*
* @return Formatted string representation of the parsed HTTP response.
*/
const std::string HTTP::restoString() const {
std::string HTTP::restoString() const {
return std::string("\n") +
boost::lexical_cast<std::string>(parsedHttpResponse_.base()) + "\n" +
"Body Size : " +
+29 -198
View File
@@ -10,38 +10,10 @@
#include "general.hpp"
#include "log.hpp"
/**
* @brief The `HTTP` class provides parsing and generation utilities for HTTP and TLS traffic.
*
* @details
* - Parses HTTP requests and responses from a stream buffer.
* - Detects whether incoming traffic is plain HTTP, HTTPS-related, or CONNECT tunneling.
* - Parses selected TLS request data such as message type and SNI.
* - Generates HTTP request and response strings used by the application.
* - Tracks destination IP address and port derived from parsed request data.
* - Integrates with configuration and logging components for runtime behavior and diagnostics.
*
* @note
* - Instances are managed through shared ownership using `std::shared_ptr`.
* - Objects should be created using the `create` factory method.
*/
class HTTP {
public:
using pointer = std::shared_ptr<HTTP>;
/**
* @brief Factory method to create a new `HTTP` instance.
*
* @details
* - Wraps object creation in a `std::shared_ptr`.
* - Ensures consistent ownership handling across the application.
*
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param buffer Reference to the stream buffer containing raw input data.
* @param uuid Unique session identifier.
* @return A shared pointer to the created `HTTP` instance.
*/
static pointer create(const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
boost::asio::streambuf &buffer,
@@ -49,230 +21,89 @@ public:
return pointer(new HTTP(config, log, buffer, uuid));
}
/**
* @brief Enumeration of supported HTTP traffic types.
*
* @details
* - `https`: HTTPS-style traffic or TLS-related traffic.
* - `http`: Standard HTTP request traffic.
* - `connect`: HTTP CONNECT tunnel request.
*/
enum class HttpType {
https,
http,
connect
};
/**
* @brief Enumeration of supported TLS record types.
*/
enum class TlsTypes {
TLSHandshake, ///< TLS handshake record.
ChangeCipherSpec,///< TLS ChangeCipherSpec record.
ApplicationData ///< TLS application data record.
TLSHandshake,
ChangeCipherSpec,
ApplicationData
};
/**
* @brief Stores parsed TLS request information.
*
* @details
* - Contains the extracted Server Name Indication (SNI), payload body,
* and detected TLS record type.
*/
struct TlsRequest {
std::string sni; ///< Parsed Server Name Indication value.
std::string body;///< Raw or extracted TLS payload body.
TlsTypes type; ///< Detected TLS record type.
std::string sni;
std::string body;
TlsTypes type;
};
/**
* @brief Copy constructor.
*
* @param request Existing `HTTP` object to copy.
*/
explicit HTTP(const HTTP &request);
/**
* @brief Destructor for `HTTP`.
*/
~HTTP();
/**
* @brief Returns the detected HTTP traffic type.
*
* @return Reference to the current `HttpType`.
*/
inline const HTTP::HttpType &httpType() const { return httpType_; }
inline HTTP::HttpType httpType() const { return httpType_; }
/**
* @brief Sets the HTTP traffic type.
*
* @param httpType New HTTP type value.
*/
inline void httpType(const HTTP::HttpType &httpType) { httpType_ = httpType; }
/**
* @brief Detects the type of traffic present in the buffer.
*
* @details
* - Inspects the current buffer contents.
* - Determines whether the input is HTTP, HTTPS-related, or CONNECT traffic.
*
* @return `true` if the type is successfully detected, otherwise `false`.
*/
static bool parseHostPort(const std::string &input,
std::string &host,
unsigned short &port,
unsigned short defaultPort);
bool detectType();
/**
* @brief Parses an HTTP request from the buffer.
*
* @details
* - Populates the internal parsed HTTP request object.
* - May also derive destination information from the parsed request.
*
* @return `true` if parsing succeeds, otherwise `false`.
*/
bool parseHttp();
/**
* @brief Parses an HTTP response from the buffer.
*
* @details
* - Populates the internal parsed HTTP response object.
*
* @return `true` if parsing succeeds, otherwise `false`.
*/
bool parseHttpResp();
/**
* @brief Parses a TLS request from the buffer.
*
* @details
* - Extracts selected TLS metadata such as record type and SNI when available.
*
* @return `true` if parsing succeeds, otherwise `false`.
*/
bool parseTls();
/**
* @brief Generates an HTTP POST request string with the given body.
*
* @param body Body content to include in the request.
* @return Serialized HTTP POST request string.
*/
const std::string genHttpPostReqString(const std::string &body) const;
/**
* @brief Generates a REST-style HTTP POST request string.
*
* @return Serialized REST-style HTTP POST request string.
*/
const std::string genHttpRestPostReqString() const;
std::string genHttpOkResString(const std::string &body) const;
/**
* @brief Generates an HTTP `200 OK` response string.
*
* @param body Body content to include in the response.
* @return Serialized HTTP response string.
*/
const std::string genHttpOkResString(const std::string &body) const;
/**
* @brief Returns the parsed HTTP request object.
*
* @return Const reference to the parsed HTTP request.
*/
inline const boost::beast::http::request<boost::beast::http::string_body> &
parsedHttpRequest() & {
return parsedHttpRequest_;
}
/**
* @brief Returns the parsed HTTP response object.
*
* @return Const reference to the parsed HTTP response.
*/
inline const boost::beast::http::response<boost::beast::http::string_body> &
parsedHttpResponse() & {
return parsedHttpResponse_;
}
/**
* @brief Returns the parsed TLS request information.
*
* @return Const reference to the parsed TLS request structure.
*/
inline const TlsRequest &parsedTlsRequest() & { return parsedTlsRequest_; }
/**
* @brief Converts the parsed TLS type to a string.
*
* @return String representation of the current TLS record type.
*/
const std::string tlsTypeToString() const;
std::string tlsTypeToString() const;
/**
* @brief Returns the destination IP address.
*
* @return Const reference to the destination IP string.
*/
inline const std::string &dstIP() { return dstIP_; }
inline const std::string &dstIp() const { return dstIp_; }
/**
* @brief Returns the destination port.
*
* @return Const reference to the destination port.
*/
inline const unsigned short &dstPort() { return dstPort_; }
inline unsigned short dstPort() const { return dstPort_; }
/**
* @brief Converts the current HTTP object state to a human-readable string.
*
* @return String representation of the parsed or generated HTTP state.
*/
const std::string toString() const;
std::string toString() const;
/**
* @brief Converts REST-related HTTP state to a human-readable string.
*
* @return String representation of REST-specific state information.
*/
const std::string restoString() const;
std::string chunkHeader_;///< Custom chunk-related header value.
std::string restoString() const;
private:
/**
* @brief Private constructor for `HTTP`.
*
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param buffer Reference to the stream buffer used for input parsing.
* @param uuid Unique session identifier.
*/
explicit HTTP(const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
boost::asio::streambuf &buffer,
boost::uuids::uuid uuid);
/**
* @brief Sets destination IP address and port from parsed request data.
*
* @details
* - Extracts and stores destination connection information after parsing.
*/
void setIPPort();
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
boost::asio::streambuf &buffer_; ///< Buffer containing raw HTTP or TLS data.
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::streambuf &buffer_;
boost::beast::http::parser<false, boost::beast::http::string_body> parser_; ///< HTTP request parser.
boost::beast::http::request<boost::beast::http::string_body> parsedHttpRequest_; ///< Parsed HTTP request.
boost::beast::http::response<boost::beast::http::string_body> parsedHttpResponse_;///< Parsed HTTP response.
boost::beast::http::parser<false, boost::beast::http::string_body> parser_;
boost::beast::http::request<boost::beast::http::string_body> parsedHttpRequest_;
boost::beast::http::response<boost::beast::http::string_body> parsedHttpResponse_;
HttpType httpType_; ///< Detected HTTP traffic type.
std::string dstIP_; ///< Parsed destination IP or host.
unsigned short dstPort_; ///< Parsed destination port.
TlsRequest parsedTlsRequest_;///< Parsed TLS request metadata.
boost::uuids::uuid uuid_; ///< Unique session identifier.
HttpType httpType_;
std::string dstIp_;
unsigned short dstPort_;
TlsRequest parsedTlsRequest_;
boost::uuids::uuid uuid_;
};
+126
View File
@@ -0,0 +1,126 @@
#pragma once
#include <algorithm>
#include <cctype>
#include <sstream>
#include <string>
namespace http_utils {
inline std::string makeHostPort(const std::string &host, uint16_t port) {
if (host.find(':') != std::string::npos &&
!(host.size() >= 2 && host.front() == '[' && host.back() == ']')) {
return "[" + host + "]:" + std::to_string(port);
}
return host + ":" + std::to_string(port);
}
inline std::string toLowerCopy(std::string value) {
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return value;
}
inline std::string trimCopy(std::string value) {
while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) {
value.erase(value.begin());
}
while (!value.empty() &&
(value.back() == ' ' ||
value.back() == '\t' ||
value.back() == '\r' ||
value.back() == '\n')) {
value.pop_back();
}
return value;
}
inline std::string extractHeaders(const std::string &message) {
const auto pos = message.find("\r\n\r\n");
if (pos == std::string::npos) {
return {};
}
return message.substr(0, pos + 4);
}
inline std::string extractBody(const std::string &message) {
const auto pos = message.find("\r\n\r\n");
if (pos == std::string::npos) {
return {};
}
return message.substr(pos + 4);
}
inline bool parseContentLength(const std::string &headers, std::size_t &value) {
std::istringstream iss(headers);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
const auto lower = toLowerCopy(line);
if (lower.rfind("content-length:", 0) == 0) {
auto raw = line.substr(std::string("Content-Length:").size());
raw.erase(0, raw.find_first_not_of(" \t"));
try {
value = static_cast<std::size_t>(std::stoull(raw));
return true;
} catch (...) {
return false;
}
}
}
return false;
}
inline bool isChunked(const std::string &headers) {
std::istringstream iss(headers);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
const auto lower = toLowerCopy(line);
if (lower.rfind("transfer-encoding:", 0) == 0 &&
lower.find("chunked") != std::string::npos) {
return true;
}
}
return false;
}
inline std::string getRawHeader(const std::string &headers, const std::string &name) {
std::istringstream iss(headers);
std::string line;
const std::string prefix = toLowerCopy(name) + ":";
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
const std::string lower = toLowerCopy(line);
if (lower.rfind(prefix, 0) == 0) {
return trimCopy(line.substr(name.size() + 1));
}
}
return {};
}
}// namespace http_utils
+22 -85
View File
@@ -1,110 +1,60 @@
#include "log.hpp"
/**
* @brief Constructs a `Log` instance using the provided configuration.
*
* @details
* - Initializes the runtime mode string based on the configured `RunMode`.
* - Attempts to open the configured log file to verify accessibility.
* - Initializes the logging level based on configuration:
* - Supported levels: INFO, TRACE, DEBUG
* - Defaults to INFO if not specified or invalid
* - Prints an error to `std::cerr` if the log file cannot be opened or
* if an invalid log level is provided.
*
* @param config Shared pointer to the configuration object.
*/
Log::Log(const std::shared_ptr<Config> &config)
: config_(config), level_(Level::INFO) {
/**
* @brief Determines the runtime mode string for log entries.
*/
if (config_->runMode() == RunMode::server)
mode_ = std::string("SERVER");
else if (config_->runMode() == RunMode::agent)
mode_ = std::string("AGENT");
/**
* @brief Verifies that the log file can be opened.
*/
std::ofstream logFile(config_->log().file, std::ios::out | std::ios::app);
if (!logFile.is_open()) {
std::cerr << "Error opening log file: " << config_->log().file
<< ". Make sure the directory and file exist.\n";
}
/**
* @brief Sets the logging level based on configuration.
*/
const auto &logLevel = config_->log().level;
applyConfigLevel();
}
if (logLevel == "INFO") {
level_ = Level::INFO;
} else if (logLevel == "TRACE") {
level_ = Level::TRACE;
} else if (logLevel == "DEBUG") {
level_ = Level::DEBUG;
bool Log::parseLevel(const std::string &name, Level &out) {
if (name == "INFO") {
out = Level::INFO;
} else if (name == "TRACE") {
out = Level::TRACE;
} else if (name == "DEBUG") {
out = Level::DEBUG;
} else {
return false;
}
return true;
}
void Log::applyConfigLevel() {
const std::string logLevel = config_->log().level;
Level parsed;
if (parseLevel(logLevel, parsed)) {
level_.store(parsed);
} else {
std::cerr << "Invalid log level: " << logLevel
<< ". It should be one of [INFO|TRACE|DEBUG].\n";
}
}
/**
* @brief Copy-constructs a `Log` instance from another instance.
*
* @details
* - Copies the configuration reference and logging level.
* - Does not duplicate file handles or internal state beyond configuration.
*
* @param log Shared pointer to the source `Log` instance.
*/
Log::Log(const std::shared_ptr<Log> &log)
: config_(log->config_), level_(log->level_) {}
: config_(log->config_), level_(log->level_.load()) {}
/**
* @brief Destroys the `Log` instance.
*
* @details
* - No explicit resource cleanup is required.
* - File streams are opened and closed per write operation.
*/
Log::~Log() {}
/**
* @brief Writes a log message to the configured output.
*
* @details
* - Ensures thread safety using an internal mutex.
* - Writes messages only if:
* - The message level is less than or equal to the configured level, OR
* - The message level is `ERROR`.
* - Each log entry includes:
* - Timestamp (YYYY-MM-DD_HH:MM:SS)
* - Runtime mode (SERVER or AGENT)
* - Log level
* - Message content
* - Outputs the log entry to both:
* - The configured log file
* - Standard output (`std::cout`)
* - Prints an error to `std::cerr` if the log file cannot be opened.
*
* @param message Log message to write.
* @param level Severity level of the message.
*/
void Log::write(const std::string &message, Level level) const {
std::lock_guard<std::mutex> lock(logMutex_);
if (level <= level_ || level == Level::ERROR) {
if (level <= level_.load() || level == Level::ERROR) {
std::ofstream logFile(config_->log().file, std::ios::out | std::ios::app);
if (logFile.is_open()) {
/**
* @brief Generates a formatted timestamp.
*/
auto now = std::time(nullptr);
auto localTime = *std::localtime(&now);
@@ -112,9 +62,6 @@ void Log::write(const std::string &message, Level level) const {
timestampStream << std::put_time(&localTime, "%Y-%m-%d_%H:%M:%S");
std::string timestamp = timestampStream.str();
/**
* @brief Formats the final log line.
*/
std::string line = timestamp + " [" + mode_ + "]" + " [" +
levelToString(level) + "] " + message + "\n";
@@ -128,16 +75,6 @@ void Log::write(const std::string &message, Level level) const {
}
}
/**
* @brief Converts a log level enum value to its string representation.
*
* @details
* - Maps each `Level` enum value to its corresponding string.
* - Returns `"UNKNOWN"` for unsupported values.
*
* @param level Log level to convert.
* @return String representation of the log level.
*/
std::string Log::levelToString(Level level) {
switch (level) {
case Level::INFO:
+15 -84
View File
@@ -1,6 +1,6 @@
#pragma once
// Standard library includes
#include <atomic>
#include <ctime>
#include <fstream>
#include <iomanip>
@@ -8,115 +8,46 @@
#include <mutex>
#include <string>
// Project-specific includes
#include "config.hpp"
#include "general.hpp"
/**
* @brief The `Log` class provides thread-safe logging functionality for the application.
*
* @details
* - Supports multiple log severity levels.
* - Writes log messages using configuration-defined logging behavior.
* - Ensures thread-safe access through an internal mutex.
* - Uses shared ownership via `std::shared_ptr`.
*
* @note
* - Inherits from `Uncopyable` to prevent accidental copying.
* - Instances should be created using the `create` factory method.
*/
class Log : private Uncopyable {
public:
/**
* @brief Enumeration of supported log severity levels.
*/
enum class Level {
INFO, ///< Informational messages.
TRACE,///< Detailed tracing messages.
ERROR,///< Error messages.
DEBUG ///< Debugging messages.
INFO,
TRACE,
ERROR,
DEBUG
};
using pointer = std::shared_ptr<Log>;
/**
* @brief Factory method to create a new `Log` instance.
*
* @details
* - Wraps object creation in a `std::shared_ptr`.
* - Ensures consistent construction and ownership handling.
*
* @param config Shared pointer to the configuration object.
* @return A shared pointer to the created `Log` instance.
*/
static pointer create(const std::shared_ptr<Config> &config) {
return pointer(new Log(config));
}
/**
* @brief Copy constructor that creates a `Log` instance from another `Log` object.
*
* @param log Shared pointer to the existing `Log` object.
*/
explicit Log(const std::shared_ptr<Log> &log);
/**
* @brief Destructor for `Log`.
*
* @details
* - Performs standard object cleanup.
* - Any file handling or output cleanup is managed by implementation details.
*/
~Log();
/**
* @brief Returns the configuration associated with this logger.
*
* @return Const reference to the shared configuration pointer.
*/
const std::shared_ptr<Config> &config() const { return config_; }
std::shared_ptr<Config> config() const { return config_; }
/**
* @brief Returns the currently configured log level.
*
* @return Current log severity level.
*/
Level level() const { return level_; }
Level level() const { return level_.load(); }
void applyConfigLevel();
/**
* @brief Writes a log message using the specified severity level.
*
* @details
* - Thread-safe through internal mutex protection.
* - Uses configuration-defined logging mode and output destination.
*
* @param message Log message to write.
* @param level Severity level of the message.
*/
void write(const std::string &message, Level level) const;
private:
/**
* @brief Private constructor for creating a `Log` instance from configuration.
*
* @details
* - Intended to be used only through the `create` factory method.
*
* @param config Shared pointer to the configuration object.
*/
explicit Log(const std::shared_ptr<Config> &config);
/**
* @brief Converts a log level enum value to its string representation.
*
* @param level Log level to convert.
* @return String representation of the log level.
*/
static std::string levelToString(Level level);
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
Level level_; ///< Active logging level.
std::string mode_; ///< Current runtime mode string.
static bool parseLevel(const std::string &name, Level &out);
mutable std::mutex logMutex_;///< Mutex used to ensure thread-safe logging.
std::shared_ptr<Config> config_;
std::atomic<Level> level_;
std::string mode_;
mutable std::mutex logMutex_;
};
+3 -39
View File
@@ -5,37 +5,16 @@
#include "log.hpp"
#include "runner.hpp"
/**
* @brief Application entry point.
*
* @details
* - Validates command-line arguments.
* - Validates the provided configuration file and runtime mode.
* - Creates the main configuration and logging objects.
* - Constructs the application runner and starts execution.
*
* @param argc Number of command-line arguments.
* @param argv Array of command-line argument strings.
* @return `0` on successful execution, otherwise `1`.
*/
int main(int argc, char const *argv[]) {
/**
* @brief Ensures that the required command-line arguments are provided.
*
* @details
* - Expects two arguments:
* - runtime mode (`server` or `agent`)
* - configuration file path
*/
if (argc < 3) {
std::cerr << "Usage: " << argv[0] << " <mode> <config_file_path>\n";
return 1;
}
/**
* @brief Validates the configuration file and command-line arguments.
*/
std::string mode(argv[1]);
RunMode runMode_ = (mode == "agent") ? RunMode::agent : RunMode::server;
BoolStr configValidation = validateConfig(argc, argv);
if (!configValidation.ok) {
std::cerr << "Configuration validation failed: " << configValidation.message
@@ -43,25 +22,10 @@ int main(int argc, char const *argv[]) {
return 1;
}
/**
* @brief Converts the string mode argument into the internal `RunMode` enum.
*/
std::string mode(argv[1]);
RunMode runMode_ = (mode == "agent") ? RunMode::agent : RunMode::server;
/**
* @brief Creates the configuration object from the provided file.
*/
Config::pointer config_ = Config::create(runMode_, std::string(argv[2]));
/**
* @brief Creates the logging object using the loaded configuration.
*/
Log::pointer log_ = Log::create(config_);
/**
* @brief Creates the main runner instance and starts the application.
*/
Runner runner_(config_, log_);
runner_.run();
+137 -50
View File
@@ -1,18 +1,7 @@
#include "runner.hpp"
/**
* @brief Constructs a `Runner` instance with configuration and logging support.
*
* @details
* - Stores references to the configuration and logging objects.
* - Initializes the internal Boost.Asio `io_context`.
* - Creates a work guard to keep the `io_context` alive.
* - Sets the running state to `true`.
* - Initializes a strand for serialized handler execution.
*
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
*/
#include "usage.hpp"
Runner::Runner(const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log)
: config_(config),
@@ -20,16 +9,11 @@ Runner::Runner(const std::shared_ptr<Config> &config,
io_context_(),
work_guard_(boost::asio::make_work_guard(io_context_)),
running_(true),
strand_(boost::asio::make_strand(io_context_)) {}
strand_(boost::asio::make_strand(io_context_)),
signals_(io_context_),
stopSignals_(io_context_),
usageTimer_(io_context_) {}
/**
* @brief Destroys the `Runner` instance and shuts down all execution resources.
*
* @details
* - Sets the running state to `false`.
* - Stops the Boost.Asio `io_context`.
* - Joins all worker threads in the thread pool if they are still joinable.
*/
Runner::~Runner() {
running_.store(false);
io_context_.stop();
@@ -39,26 +23,23 @@ Runner::~Runner() {
thread.join();
}
}
ServerHandler::closeAllSessions();
}
/**
* @brief Starts the server runtime and launches worker threads.
*
* @details
* - Logs the current runtime mode and full configuration.
* - Creates the `TCPServer` instance bound to the internal `io_context`.
* - Spawns a number of worker threads based on the configured thread count.
* - Each worker thread runs the `workerThread()` loop.
* - Waits for all worker threads to finish before returning.
* - Logs any exception that occurs during startup or runtime coordination.
*/
void Runner::run() {
try {
log_->write("Config initialized in " + config_->modeToString() + " mode", Log::Level::INFO);
log_->write(config_->toString(), Log::Level::INFO);
warnAboutSampleToken();
auto tcpServer = TCPServer::create(io_context_, config_, log_);
waitForReloadSignal();
waitForStopSignal();
startUsage();
for (auto i = 0; i < config_->threads(); ++i) {
threadPool_.emplace_back([this] { workerThread(); });
}
@@ -76,15 +57,6 @@ void Runner::run() {
}
}
/**
* @brief Worker thread entry point for processing asynchronous operations.
*
* @details
* - Repeatedly runs the Boost.Asio `io_context` while the runner is active.
* - Exits the loop when `io_context_.run()` completes normally.
* - Catches and logs exceptions so that a single handler failure does not
* immediately terminate the worker loop.
*/
void Runner::workerThread() {
while (running_.load()) {
try {
@@ -98,14 +70,129 @@ void Runner::workerThread() {
}
}
/**
* @brief Stops the runner and terminates asynchronous processing.
*
* @details
* - Sets the running state to `false`.
* - Stops the internal Boost.Asio `io_context`.
*/
void Runner::stop() {
running_.store(false);
io_context_.stop();
}
}
void Runner::warnAboutSampleToken() {
for (const auto &warning: config_->warnings()) {
log_->write("[WARNING] " + warning, Log::Level::ERROR);
}
if (config_->runMode() == RunMode::agent) {
if (config_->agent().token == SampleToken) {
log_->write(
"[WARNING] agent.token is the public sample token; "
"set a unique random token for each user",
Log::Level::ERROR);
}
return;
}
for (const auto &user: config_->users()) {
if (user.enabled && user.token == SampleToken) {
log_->write("[WARNING] user " + user.name +
" uses the public sample token; "
"set a unique random token for each user",
Log::Level::ERROR);
}
}
}
void Runner::waitForReloadSignal() {
#if defined(SIGHUP)
boost::system::error_code ec;
signals_.add(SIGHUP, ec);
if (ec) {
log_->write("[Runner] cannot handle SIGHUP, reload disabled: " + ec.message(),
Log::Level::ERROR);
return;
}
signals_.async_wait([this](const boost::system::error_code &error, int) {
if (error) return;
reload();
waitForReloadSignal();
});
#endif
}
void Runner::reload() {
log_->write("[Runner reload] reloading " + config_->filePath(), Log::Level::INFO);
const Config::ReloadResult result = config_->reload();
if (!result.ok) {
log_->write("[Runner reload] " + result.message, Log::Level::ERROR);
return;
}
log_->applyConfigLevel();
log_->write("[Runner reload] " + result.message, Log::Level::INFO);
warnAboutSampleToken();
if (config_->runMode() == RunMode::server) {
Usage::instance().configure(*config_, nullptr, *log_);
Usage::instance().flush(*log_);
}
if (!result.revokedUsers.empty()) {
const std::size_t connections = TCPConnection::revokeUsers(result.revokedUsers);
const std::size_t sessions = ServerHandler::revokeSessions(result.revokedUsers);
log_->write("[Runner reload] closed " + std::to_string(connections) +
" connections and " + std::to_string(sessions) +
" tunnel sessions of revoked users",
Log::Level::INFO);
}
}
void Runner::startUsage() {
if (config_->runMode() != RunMode::server) return;
Usage::instance().configure(
*config_, [this](const std::string &user) { onUsageLimit(user); }, *log_);
if (!config_->hasUserList()) return;
Usage::instance().flush(*log_);
log_->write("[Usage] tracking usage in " + config_->usageFile() + ", period from " +
Usage::periodStart(config_->usageResetDay()),
Log::Level::INFO);
scheduleUsageFlush();
}
void Runner::scheduleUsageFlush() {
usageTimer_.expires_after(std::chrono::seconds(30));
usageTimer_.async_wait([this](const boost::system::error_code &error) {
if (error) return;
Usage::instance().flush(*log_);
scheduleUsageFlush();
});
}
void Runner::onUsageLimit(const std::string &user) {
std::string limit;
for (const auto &u: config_->users()) {
if (u.name == user) limit = formatBytes(u.limit);
}
log_->write("[Usage] user " + user + " reached their limit of " + limit +
"; blocked until the next period",
Log::Level::INFO);
TCPConnection::revokeUsers({user});
ServerHandler::revokeSessions({user});
}
void Runner::waitForStopSignal() {
boost::system::error_code ec;
stopSignals_.add(SIGINT, ec);
stopSignals_.add(SIGTERM, ec);
stopSignals_.async_wait([this](const boost::system::error_code &error, int signal) {
if (error) return;
log_->write("[Runner] received signal " + std::to_string(signal) + ", stopping",
Log::Level::INFO);
if (config_->runMode() == RunMode::server) {
Usage::instance().flush(*log_);
}
stop();
});
}
+30 -72
View File
@@ -3,105 +3,63 @@
#include <atomic>
#include <boost/asio/executor_work_guard.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/asio/steady_timer.hpp>
#include <csignal>
#include <iostream>
#include <thread>
#include <vector>
#if defined(__ANDROID__)
using runnerThread = std::thread;
#else
using runnerThread = std::jthread;
#endif
#include "config.hpp"
#include "log.hpp"
#include "tcpserver.hpp"
/**
* @brief The `Runner` class manages the lifecycle and execution of the asynchronous server.
*
* @details
* - Initializes and owns the Boost.Asio `io_context`.
* - Creates and manages a pool of worker threads.
* - Keeps the `io_context` alive using a work guard.
* - Provides mechanisms to start and gracefully stop the server.
* - Ensures thread-safe execution of handlers using a strand.
*
* @note
* - Inherits from `Uncopyable` to prevent copying.
* - Uses `std::jthread` for automatic thread cleanup on destruction.
*/
class Runner : private Uncopyable {
public:
/**
* @brief Constructs a `Runner` instance with configuration and logging support.
*
* @details
* - Initializes the internal `io_context`.
* - Creates a work guard to prevent premature exit of the event loop.
* - Prepares the threading and execution environment.
*
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
*/
explicit Runner(const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log);
/**
* @brief Destructor for `Runner`.
*
* @details
* - Ensures that all worker threads are stopped.
* - Releases the work guard and shuts down the `io_context`.
*/
~Runner();
/**
* @brief Starts the server and worker thread pool.
*
* @details
* - Launches multiple worker threads.
* - Each thread runs the `io_context` event loop.
* - Begins processing asynchronous operations.
*/
void run();
private:
/**
* @brief Worker thread entry point.
*
* @details
* - Executes the `io_context::run()` loop.
* - Processes asynchronous tasks until the context is stopped.
*/
void workerThread();
/**
* @brief Stops the server and shuts down execution.
*
* @details
* - Signals termination via the `running_` flag.
* - Stops the `io_context`.
* - Ensures all threads exit cleanly.
*/
void stop();
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
void reload();
boost::asio::io_context io_context_;///< Core I/O execution context.
void waitForReloadSignal();
void warnAboutSampleToken();
void startUsage();
void scheduleUsageFlush();
void onUsageLimit(const std::string &user);
void waitForStopSignal();
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context io_context_;
/**
* @brief Work guard to keep the `io_context` active.
*
* @details
* - Prevents `io_context::run()` from returning when no tasks are queued.
*/
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work_guard_;
std::atomic<bool> running_;///< Indicates whether the runner is active.
std::atomic<bool> running_;
std::vector<std::jthread> threadPool_;///< Pool of worker threads.
std::vector<runnerThread> threadPool_;
/**
* @brief Strand for serialized handler execution.
*
* @details
* - Ensures that certain handlers do not execute concurrently.
*/
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::asio::signal_set signals_;
boost::asio::signal_set stopSignals_;
boost::asio::steady_timer usageTimer_;
};
+445 -144
View File
@@ -1,206 +1,507 @@
#include "serverhandler.hpp"
/**
* @brief Constructs a `ServerHandler` instance with buffers, configuration,
* logging, client connection, and session identifier.
*
* @details
* - Stores references to the configuration, logging, and client objects.
* - Stores references to the read and write stream buffers.
* - Creates an internal `HTTP` helper object for parsing and generating HTTP data.
* - Stores the client connection string and UUID for logging and tracing.
* - Initializes the internal state flags:
* - `end_` is set to `false`
* - `connect_` is set to `false`
*
* @param readBuffer Reference to the input stream buffer.
* @param writeBuffer Reference to the output stream buffer.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param client Shared pointer to the TCP client used for remote communication.
* @param clientConnStr String describing the client connection source.
* @param uuid Unique identifier for this handler instance.
*/
#include <sstream>
#include <utility>
#include <vector>
#include "http_utils.hpp"
#include "usage.hpp"
std::mutex ServerHandler::sessionsMutex_;
std::unordered_map<std::string, ServerHandler::Session> ServerHandler::sessions_;
std::size_t ServerHandler::revokeSessions(const std::vector<std::string> &users) {
std::lock_guard<std::mutex> lock(sessionsMutex_);
std::size_t closed = 0;
for (auto it = sessions_.begin(); it != sessions_.end();) {
bool revoked = false;
for (const auto &name: users) {
if (it->second.user == name) {
revoked = true;
break;
}
}
if (revoked) {
it->second.client->socketShutdown();
it = sessions_.erase(it);
++closed;
} else {
++it;
}
}
return closed;
}
void ServerHandler::closeAllSessions() {
std::unordered_map<std::string, Session> sessions;
{
std::lock_guard<std::mutex> lock(sessionsMutex_);
sessions.swap(sessions_);
}
for (auto &[key, session]: sessions) session.client->socketShutdown();
}
std::string ServerHandler::HttpUtils::lowerCopy(std::string s) {
return http_utils::toLowerCopy(std::move(s));
}
std::string ServerHandler::HttpUtils::trimCopy(std::string s) {
return http_utils::trimCopy(std::move(s));
}
std::string ServerHandler::HttpUtils::getRawHeader(const std::string &headers,
const std::string &name) {
return http_utils::getRawHeader(headers, name);
}
std::string ServerHandler::HttpUtils::extractHttpBody(const std::string &msg) {
return http_utils::extractBody(msg);
}
ServerHandler::ServerHandler(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
boost::uuids::uuid uuid)
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid,
std::string &userHint)
: config_(config),
log_(log),
client_(client),
client_(std::move(client)),
readBuffer_(readBuffer),
writeBuffer_(writeBuffer),
request_(HTTP::create(config, log, readBuffer, uuid)),
clientConnStr_(clientConnStr),
uuid_(uuid) {
clientConnStr_(std::move(clientConnStr)),
uuid_(uuid),
userHint_(userHint) {
end_ = false;
connect_ = false;
}
/**
* @brief Destroys the `ServerHandler` instance.
*
* @details
* - Performs no explicit cleanup.
* - Resource management is handled by referenced objects and smart pointers.
*/
BoolStr ServerHandler::authenticate(const std::string &payload) {
const std::vector<User> &users = config_->users();
const bool aes = config_->general().aesEnable;
BoolStr result{false, "no enabled user's token authenticates the request"};
auto tryUser = [&](const User &u) {
if (!u.enabled) return false;
BoolStr r = aes ? aes256DecryptWithKey(payload, u.key) : verifyWithKey(payload, u.key);
if (!r.ok) return false;
result = std::move(r);
user_ = &u;
userHint_ = u.name;
return true;
};
if (!userHint_.empty()) {
for (const auto &u: users) {
if (u.name == userHint_) {
if (tryUser(u)) return result;
break;
}
}
}
for (const auto &u: users) {
if (u.name != userHint_ && tryUser(u)) return result;
}
if (!aes && !config_->hasUserList() && !users.empty()) {
user_ = &users.front();
return {true, withoutUnverifiedSignature(payload)};
}
return result;
}
std::string ServerHandler::withoutUnverifiedSignature(const std::string &payload) {
const auto actionEnd = payload.find('\n');
const auto sessionEnd = actionEnd == std::string::npos ? actionEnd : payload.find('\n', actionEnd + 1);
if (sessionEnd == std::string::npos || payload.size() < sessionEnd + 1 + HmacTagLength) return payload;
static const char *hex = "0123456789abcdefABCDEF";
const std::size_t dataStart = sessionEnd + 1;
const std::size_t tagStart = payload.size() - HmacTagLength;
if (payload.find_first_not_of(hex, dataStart) == std::string::npos) return payload;
if (payload.find_first_not_of(hex, dataStart) < tagStart) return payload;
return payload.substr(0, tagStart);
}
std::string ServerHandler::srcTag() const {
return clientConnStr_ + (user_ ? "] [USER " + user_->name : std::string());
}
ServerHandler::~ServerHandler() {}
/**
* @brief Handles an incoming agent request, decrypts it, forwards it to the target,
* and prepares the response.
*
* @details
* - Ensures thread-safe execution using an internal mutex.
* - Parses the incoming request received from the agent.
* - Decrypts the HTTP request body using the configured token.
* - Converts the decrypted hexadecimal payload back into raw request data.
* - Re-parses the decrypted request as HTTP or TLS-related traffic.
* - Handles requests based on detected type:
* - `CONNECT`: Establishes a tunnel and returns a connection status response.
* - `HTTP` / `HTTPS`: Connects to the destination, forwards the request,
* reads the remote response, encrypts it, and wraps it in an HTTP `200 OK` response.
* - On any parsing, decryption, encryption, or connection failure, closes the client socket.
*/
void ServerHandler::handle() {
std::lock_guard lock(mutex_);
std::string ServerHandler::connectionHeader() const {
return requestKeepAlive_ ? "keep-alive" : "close";
}
/**
* @brief Parses the outer request received from the agent.
*/
if (!request_->detectType()) {
log_->write("[" + to_string(uuid_) +
"] [ServerHandler handle] [NOT HTTP Request From Agent] "
"[Request] : " +
streambufToString(readBuffer_),
void ServerHandler::makePlainHttpResponse(const std::string &body,
const std::string &status,
const std::string &connection) {
std::ostringstream outer;
outer << "HTTP/1.1 " << status << "\r\n"
<< "Content-Type: application/octet-stream\r\n"
<< "Content-Length: " << body.size() << "\r\n"
<< "Connection: " << connection << "\r\n"
<< "\r\n"
<< body;
copyStringToStreambuf(outer.str(), writeBuffer_);
keepAlive_ = connection == "keep-alive";
end_ = false;
connect_ = false;
}
void ServerHandler::makePayloadHttpResponse(const std::string &plainBody,
const std::string &status,
const std::string &connection) {
BoolStr encryption{false, "no authenticated user to encrypt for"};
if (!config_->general().aesEnable) {
encryption = {true, plainBody};
} else if (user_) {
encryption = aes256EncryptWithKey(plainBody, user_->key);
}
if (!encryption.ok) {
log_->write("[" + to_string(uuid_) + "] [ServerHandler] [Encryption Failed] " + encryption.message,
Log::Level::DEBUG);
makePlainHttpResponse("", "500 Internal Server Error", "close");
return;
}
makePlainHttpResponse(encryption.message, status, connection);
}
void ServerHandler::handle() {
std::lock_guard<std::mutex> lock(mutex_);
if (!request_->detectType()) {
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [NOT HTTP Request From Agent] [Request] : " +
streambufToString(readBuffer_),
Log::Level::DEBUG);
client_->socket().close();
return;
}
const auto &outerReq = request_->parsedHttpRequest();
requestKeepAlive_ = outerReq.keep_alive();
const std::string outerRaw = streambufToString(readBuffer_);
std::string requestBody = std::string(outerReq.body());
if (requestBody.empty()) {
requestBody = HttpUtils::extractHttpBody(outerRaw);
}
BoolStr decryption{false, std::string("FAILED")};
/**
* @brief Decrypts the received request body using the configured token.
*/
decryption = aes256Decrypt(
decode64(std::string(request_->parsedHttpRequest().body())),
config_->general().token);
try {
decryption = authenticate(decode64(requestBody));
} catch (const std::exception &e) {
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [Base64 Decode Failed] " + e.what(),
Log::Level::DEBUG);
makePlainHttpResponse("", "400 Bad Request", "close");
return;
}
if (!decryption.ok) {
log_->write("[" + to_string(uuid_) +
"] [ServerHandler handle] [Decryption Failed] : [ " +
decryption.message + "] ",
Log::Level::DEBUG);
client_->socket().close();
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [Decryption Failed] : [ " +
decryption.message + "] ",
Log::Level::DEBUG);
makePlainHttpResponse("", "400 Bad Request", "close");
return;
}
/**
* @brief Converts the decrypted hexadecimal payload into raw request bytes
* and replaces the input buffer contents.
*/
auto tempHexArr = strToHexArr(decryption.message);
std::string tempHexArrStr(tempHexArr.begin(), tempHexArr.end());
copyStringToStreambuf(tempHexArrStr, readBuffer_);
/**
* @brief Parses the decrypted inner request.
*/
if (!request_->detectType()) {
log_->write("[" + to_string(uuid_) +
"] [ServerHandler handle] [NOT HTTP Request] [Request] : " +
streambufToString(readBuffer_),
usage_ = user_ ? Usage::instance().counter(user_->name) : nullptr;
if (usage_ && Usage::overLimit(*usage_)) {
log_->write("[" + to_string(uuid_) + "] [ServerHandler handle] [USER " + user_->name +
"] refused: usage limit reached",
Log::Level::DEBUG);
client_->socket().close();
makePlainHttpResponse("", "403 Forbidden", "close");
return;
}
/**
* @brief Processes the request according to its detected type.
*/
switch (request_->httpType()) {
Envelope envelope;
if (!parseEnvelope(decryption.message, envelope)) {
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [Invalid Envelope] (agent and server versions or aesEnable may differ)",
Log::Level::DEBUG);
makePlainHttpResponse("", "400 Bad Request", "close");
return;
}
const std::string &action = envelope.action;
const std::string &session = envelope.session;
decryption.message = std::move(envelope.data);
log_->write(
"[" + to_string(uuid_) + "] [ServerHandler handle] [Payload Decoded]",
Log::Level::DEBUG);
if (action == "send") {
TCPClient::pointer targetClient;
{
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
auto it = sessions_.find(session);
if (it != sessions_.end() && it->second.user == userName()) {
targetClient = it->second.client;
}
}
if (!targetClient || !targetClient->isOpen()) {
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
boost::asio::streambuf tunnelBuf;
copyStringToStreambuf(hexToASCII(decryption.message), tunnelBuf);
Usage::instance().add(usage_, tunnelBuf.size());
targetClient->doWrite(tunnelBuf);
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
if (action == "recv") {
TCPClient::pointer targetClient;
{
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
auto it = sessions_.find(session);
if (it != sessions_.end() && it->second.user == userName()) {
targetClient = it->second.client;
}
}
if (!targetClient || !targetClient->isOpen()) {
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
boost::system::error_code ec;
std::size_t available = targetClient->socket().available(ec);
if (ec || available == 0) {
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
std::vector<char> data(std::min<std::size_t>(available, config_->server().bufferSize));
std::size_t n = targetClient->socket().read_some(
boost::asio::buffer(data),
ec);
if (ec || n == 0) {
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
Usage::instance().add(usage_, n);
makePayloadHttpResponse(
std::string(data.data(), n),
"200 OK",
connectionHeader());
return;
}
if (action == "close") {
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
auto it = sessions_.find(session);
if (it != sessions_.end() && it->second.user == userName()) {
it->second.client->socketShutdown();
sessions_.erase(it);
}
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
const std::string innerRequest = hexToASCII(decryption.message);
const std::size_t headerEnd = innerRequest.find("\r\n\r\n");
if (headerEnd == std::string::npos) {
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [INNER REQUEST MISSING HEADER END]",
Log::Level::DEBUG);
makePayloadHttpResponse("", "400 Bad Request", "close");
return;
}
const std::string innerHeaders = innerRequest.substr(0, headerEnd + 4);
const std::string pendingTunnelData = innerRequest.substr(headerEnd + 4);
copyStringToStreambuf(innerHeaders, readBuffer_);
HTTP::pointer inner = HTTP::create(config_, log_, readBuffer_, uuid_);
if (!inner->detectType()) {
log_->write(
"[" + to_string(uuid_) +
"] [ServerHandler handle] [NOT INNER HTTP Request] [Request] : " +
streambufToString(readBuffer_),
Log::Level::DEBUG);
makePayloadHttpResponse("", "400 Bad Request", "close");
return;
}
switch (inner->httpType()) {
case HTTP::HttpType::connect: {
connect_ = true;
boost::asio::streambuf tempBuff;
std::iostream os(&tempBuff);
/**
* @brief Establishes a CONNECT tunnel to the requested destination.
*/
if (client_->doConnect(request_->dstIP(), request_->dstPort())) {
log_->write("[" + to_string(uuid_) + "] [CONNECT] [SRC " +
clientConnStr_ + "] [DST " + request_->dstIP() + ":" +
std::to_string(request_->dstPort()) + "]",
Log::Level::INFO);
os << "HTTP/1.1 200 Connection established COMP\r\n\r\n";
} else {
log_->write(std::string("[") + to_string(uuid_) +
if (config_->general().tunnelEnable) {
if (!client_->doConnect(inner->dstIp(), inner->dstPort())) {
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
clientConnStr_ + "] [DST " + request_->dstIP() + ":" +
std::to_string(request_->dstPort()) + "]",
srcTag() + "] [DST " +
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
os << "HTTP/1.1 500 Connection failed COMP\r\n\r\n";
makePayloadHttpResponse(
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
"502 Bad Gateway",
"close");
connect_ = false;
end_ = false;
return;
}
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [SRC " +
srcTag() + "] [DST " +
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
makePayloadHttpResponse(
"HTTP/1.1 200 Connection Established\r\n\r\n",
"200 OK",
"keep-alive");
connect_ = true;
end_ = false;
return;
}
moveStreambuf(tempBuff, writeBuffer_);
TCPClient::pointer targetClient = TCPClient::create(
static_cast<boost::asio::io_context &>(
client_->socket().get_executor().context()),
config_,
log_);
targetClient->uuid_ = uuid_;
if (!targetClient->doConnect(inner->dstIp(), inner->dstPort())) {
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [ERROR] [Resolving Host] [SRC " +
srcTag() + "] [DST " +
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
makePayloadHttpResponse(
"HTTP/1.1 502 Bad Gateway\r\n\r\n",
"502 Bad Gateway",
"close");
connect_ = false;
end_ = false;
return;
}
log_->write(
"[" + to_string(uuid_) +
"] [CONNECT] [SRC " +
srcTag() + "] [ORIGIN " +
inner->dstIp() + ":" + std::to_string(inner->dstPort()) + "]",
Log::Level::INFO);
if (!pendingTunnelData.empty()) {
boost::asio::streambuf pendingBuf;
copyStringToStreambuf(pendingTunnelData, pendingBuf);
Usage::instance().add(usage_, pendingBuf.size());
targetClient->doWrite(pendingBuf);
}
{
std::lock_guard<std::mutex> sessionLock(sessionsMutex_);
const std::string key = session.empty() ? to_string(uuid_) : session;
auto it = sessions_.find(key);
if (it != sessions_.end() && it->second.user != userName()) {
targetClient->socketShutdown();
makePayloadHttpResponse("", "403 Forbidden", "close");
return;
}
sessions_[key] = Session{targetClient, userName()};
}
makePayloadHttpResponse(
"HTTP/1.1 200 Connection Established\r\n\r\n",
"200 OK",
connectionHeader());
connect_ = false;
end_ = false;
return;
}
case HTTP::HttpType::http:
case HTTP::HttpType::https: {
/**
* @brief Connects to the target destination if no active socket is open.
*/
copyStringToStreambuf(innerRequest, readBuffer_);
if (!client_->socket().is_open()) {
if (!client_->doConnect(request_->dstIP(), request_->dstPort())) {
if (!client_->doConnect(inner->dstIp(), inner->dstPort())) {
client_->socket().close();
makePayloadHttpResponse("", "502 Bad Gateway", "close");
return;
}
}
/**
* @brief Forwards the request to the destination and reads the response.
*/
Usage::instance().add(usage_, readBuffer_.size());
client_->doWrite(readBuffer_);
client_->doReadServer();
Usage::instance().add(usage_, client_->readBuffer().size());
if (client_->readBuffer().size() == 0) {
client_->socket().close();
makePayloadHttpResponse("", "200 OK", connectionHeader());
return;
}
BoolStr encryption{false, std::string("FAILED")};
makePayloadHttpResponse(
streambufToString(client_->readBuffer()),
"200 OK",
connectionHeader());
/**
* @brief Encrypts the received response payload.
*/
encryption =
aes256Encrypt(streambufToString(client_->readBuffer()),
config_->general().token);
if (!encryption.ok) {
log_->write("[" + to_string(uuid_) +
"] [ServerHandler handle] [Encryption Failed] : [ " +
encryption.message + "] ",
Log::Level::DEBUG);
client_->socket().close();
return;
}
/**
* @brief Wraps the encrypted response in an HTTP `200 OK` response
* and writes it to the output buffer.
*/
std::string newRes(
request_->genHttpOkResString(encode64(encryption.message)));
copyStringToStreambuf(newRes, writeBuffer_);
connect_ = true;
connect_ = false;
end_ = false;
return;
}
+68 -97
View File
@@ -1,131 +1,102 @@
#pragma once
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include "config.hpp"
#include "general.hpp"
#include "http.hpp"
#include "log.hpp"
#include "tcpclient.hpp"
#include "usage.hpp"
/**
* @brief The `ServerHandler` class manages server-side request processing for a single connection.
*
* @details
* - Responsible for handling incoming client data and generating responses.
* - Integrates with the `HTTP` parser for request processing.
* - Uses `TCPClient` to manage the underlying connection.
* - Maintains connection state such as completion and CONNECT tunneling.
* - Ensures thread-safe operations using an internal mutex.
*
* @note
* - Inherits from `Uncopyable` to prevent copying.
* - Uses shared ownership via `std::shared_ptr`.
* - Instances should be created using the `create` factory method.
*/
class ServerHandler : private Uncopyable {
public:
using pointer = std::shared_ptr<ServerHandler>;
/**
* @brief Factory method to create a new `ServerHandler` instance.
*
* @details
* - Wraps construction in a `std::shared_ptr`.
* - Ensures consistent ownership and lifecycle management.
*
* @param readBuffer Reference to the stream buffer for incoming data.
* @param writeBuffer Reference to the stream buffer for outgoing data.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param client Shared pointer to the associated `TCPClient`.
* @param clientConnStr String describing the client connection (e.g., IP:port).
* @param uuid Unique identifier for this connection.
* @return A shared pointer to the created `ServerHandler`.
*/
static pointer create(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
boost::uuids::uuid uuid) {
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log,
client, clientConnStr, uuid));
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid,
std::string &userHint) {
return pointer(new ServerHandler(readBuffer, writeBuffer, config, log, client, clientConnStr, uuid, userHint));
}
/**
* @brief Destructor for `ServerHandler`.
*
* @details
* - Performs no explicit cleanup.
* - Resource management is handled by referenced objects and smart pointers.
*/
static std::size_t revokeSessions(const std::vector<std::string> &users);
static void closeAllSessions();
std::string userName() const { return user_ ? user_->name : std::string(); }
~ServerHandler();
/**
* @brief Processes the incoming request and generates the appropriate response.
*
* @details
* - Parses incoming data using the `HTTP` handler.
* - Handles connection logic, including CONNECT tunneling.
* - Coordinates communication with the client and remote endpoints.
*/
void handle();
/**
* @brief Returns a reference to the associated HTTP request object.
*
* @return Const reference to the HTTP request pointer.
*/
inline const HTTP::pointer &request() & { return request_; }
inline const HTTP::pointer &request() const { return request_; }
/**
* @brief Returns an rvalue reference to the HTTP request object.
*
* @details
* - Enables move semantics when transferring ownership.
*
* @return Rvalue reference to the HTTP request pointer.
*/
inline const HTTP::pointer &&request() && { return std::move(request_); }
bool end_; ///< Indicates whether request processing is complete.
bool connect_;///< Indicates whether a CONNECT tunnel or persistent connection is active.
bool end_;
bool connect_;
bool keepAlive_ = false;
private:
/**
* @brief Constructs a `ServerHandler` instance.
*
* @details
* - Initializes buffers, configuration, logging, and client references.
* - Creates the internal HTTP request handler.
* - Stores connection metadata and unique identifier.
*
* @param readBuffer Reference to the input stream buffer.
* @param writeBuffer Reference to the output stream buffer.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param client Shared pointer to the TCP client.
* @param clientConnStr Client connection description string.
* @param uuid Unique identifier for this handler instance.
*/
struct HttpUtils {
static std::string lowerCopy(std::string s);
static std::string trimCopy(std::string s);
static std::string getRawHeader(const std::string &headers, const std::string &name);
static std::string extractHttpBody(const std::string &msg);
};
explicit ServerHandler(boost::asio::streambuf &readBuffer,
boost::asio::streambuf &writeBuffer,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
const TCPClient::pointer &client,
const std::string &clientConnStr,
boost::uuids::uuid uuid);
TCPClient::pointer client,
std::string clientConnStr,
boost::uuids::uuid uuid,
std::string &userHint);
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
const TCPClient::pointer &client_; ///< Reference to the TCP client.
boost::asio::streambuf &readBuffer_; ///< Buffer for incoming data.
boost::asio::streambuf &writeBuffer_; ///< Buffer for outgoing data.
HTTP::pointer request_; ///< HTTP request handler instance.
const std::string &clientConnStr_; ///< Client connection string.
boost::uuids::uuid uuid_; ///< Unique identifier for this handler.
BoolStr authenticate(const std::string &payload);
std::mutex mutex_;///< Mutex for thread-safe operations.
std::string srcTag() const;
static std::string withoutUnverifiedSignature(const std::string &payload);
void makePayloadHttpResponse(const std::string &plainBody,
const std::string &status = "200 OK",
const std::string &connection = "close");
std::string connectionHeader() const;
bool requestKeepAlive_ = false;
void makePlainHttpResponse(const std::string &body,
const std::string &status = "200 OK",
const std::string &connection = "close");
struct Session {
TCPClient::pointer client;
std::string user;
};
static std::mutex sessionsMutex_;
static std::unordered_map<std::string, Session> sessions_;
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
TCPClient::pointer client_;
boost::asio::streambuf &readBuffer_;
boost::asio::streambuf &writeBuffer_;
HTTP::pointer request_;
std::string clientConnStr_;
boost::uuids::uuid uuid_;
std::mutex mutex_;
std::string &userHint_;
const User *user_ = nullptr;
std::shared_ptr<Usage::Counter> usage_;
};
+496 -282
View File
@@ -2,22 +2,95 @@
#include <openssl/ssl.h>
/**
* @brief Constructs a `TCPClient` instance with I/O context, configuration,
* and logging support.
*
* @details
* - Stores references to the configuration, logging object, and I/O context.
* - Initializes the plain TCP socket.
* - Initializes the TLS context in client mode.
* - Starts with TLS disabled and no SSL stream allocated.
* - Initializes the DNS resolver and timeout timer.
* - Sets the internal connection completion flag `end_` to `false`.
*
* @param io_context Reference to the Boost.Asio I/O context.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
*/
#include <algorithm>
#include <cctype>
#include <chrono>
#include <memory>
#include <sstream>
#include <utility>
#include <vector>
#include "http_utils.hpp"
#ifndef _WIN32
#include <poll.h>
#endif
namespace {
template<typename Socket>
void connectWithTimeout(Socket &socket,
const boost::asio::ip::tcp::resolver::results_type &endpoints,
unsigned short timeoutSeconds,
boost::system::error_code &ec) {
ec = boost::asio::error::host_not_found;
for (const auto &entry: endpoints) {
boost::system::error_code ignored;
socket.close(ignored);
socket.open(entry.endpoint().protocol(), ec);
if (ec) continue;
if (timeoutSeconds == 0) {
socket.connect(entry.endpoint(), ec);
if (!ec) return;
continue;
}
socket.native_non_blocking(true, ec);
if (ec) continue;
const auto endpoint = entry.endpoint();
const bool started =
::connect(socket.native_handle(), endpoint.data(),
static_cast<int>(endpoint.size())) == 0;
#ifdef _WIN32
const int connectErr = started ? 0 : WSAGetLastError();
const bool pending = connectErr == WSAEWOULDBLOCK;
#else
const int connectErr = started ? 0 : errno;
const bool pending = connectErr == EINPROGRESS;
#endif
ec = boost::system::error_code(connectErr, boost::system::system_category());
if (pending) {
#ifdef _WIN32
WSAPOLLFD pfd{socket.native_handle(), POLLWRNORM, 0};
const int ready = WSAPoll(&pfd, 1, timeoutSeconds * 1000);
#else
pollfd pfd{socket.native_handle(), POLLOUT, 0};
const int ready = ::poll(&pfd, 1, timeoutSeconds * 1000);
#endif
if (ready == 0) {
ec = boost::asio::error::timed_out;
} else if (ready < 0) {
#ifdef _WIN32
ec = boost::system::error_code(WSAGetLastError(), boost::system::system_category());
#else
ec = boost::system::error_code(errno, boost::system::system_category());
#endif
} else {
boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_ERROR> soError;
socket.get_option(soError, ec);
if (!ec && soError.value() != 0) {
ec = boost::system::error_code(soError.value(), boost::system::system_category());
}
}
}
if (!ec) {
socket.native_non_blocking(false, ec);
if (!ec) return;
}
}
boost::system::error_code ignored;
socket.close(ignored);
}
}// namespace
TCPClient::TCPClient(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log)
@@ -33,58 +106,18 @@ TCPClient::TCPClient(boost::asio::io_context &io_context,
end_ = false;
}
/**
* @brief Returns the underlying plain TCP socket.
*
* @return Reference to the internal TCP socket.
*/
TCPClient::tcp::socket &TCPClient::socket() { return socket_; }
/**
* @brief Returns the TLS stream socket.
*
* @return Reference to the internal SSL stream.
*/
TCPClient::ssl_stream &TCPClient::sslSocket() { return *sslSocket_; }
/**
* @brief Indicates whether TLS is enabled for this client.
*
* @return `true` if TLS is enabled, otherwise `false`.
*/
bool TCPClient::tlsEnabled() const { return tlsEnabled_; }
/**
* @brief Checks whether the active underlying socket is open.
*
* @details
* - If TLS is enabled and the SSL stream exists, checks the lowest layer socket.
* - Otherwise checks the plain TCP socket.
*
* @return `true` if the active socket is open, otherwise `false`.
*/
bool TCPClient::isOpen() const {
if (tlsEnabled_ && sslSocket_) return sslSocket_->lowest_layer().is_open();
return socket_.is_open();
}
/**
* @brief Enables TLS support for the client connection.
*
* @details
* - Reinitializes the SSL context in TLS client mode.
* - Applies SSL context options to disable legacy SSL versions.
* - Enforces a minimum protocol version of TLS 1.2.
* - Configures peer verification based on the application configuration.
* - Loads the CA file when peer verification is enabled and a CA file is provided.
* - Sets the allowed TLS cipher list and TLS 1.3 cipher suites.
* - Creates the SSL stream object bound to the internal I/O context.
* - Marks the client as TLS-enabled.
*
* @return `true` if TLS initialization succeeds, otherwise `false`.
*/
bool TCPClient::enableTlsClient() {
std::lock_guard lock(mutex_);
try {
if (tlsEnabled_) return true;
@@ -141,30 +174,27 @@ bool TCPClient::enableTlsClient() {
}
}
/**
* @brief Resolves and connects to the specified destination.
*
* @details
* - Resolves the destination host and port using the internal resolver.
* - Connects either the plain TCP socket or the TLS socket's lowest layer,
* depending on whether TLS is enabled.
* - Logs connection attempts and resolution/connect failures.
*
* @param dstIP Destination hostname or IP address.
* @param dstPort Destination port.
* @return `true` if the connection succeeds, otherwise `false`.
*/
bool TCPClient::doConnect(const std::string &dstIP, const unsigned short &dstPort) {
std::lock_guard lock(mutex_);
bool TCPClient::doConnect(const std::string &dstIp, unsigned short dstPort) {
try {
log_->write("[" + to_string(uuid_) + "] [TCPClient doConnect] [DST " + dstIP +
":" + std::to_string(dstPort) + "]",
if (tlsEnabled_ && sslSocket_ && sslSocket_->lowest_layer().is_open()) {
return true;
}
if (!tlsEnabled_ && socket_.is_open()) {
return true;
}
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] [DST " + dstIp + ":" +
std::to_string(dstPort) + "]",
Log::Level::DEBUG);
boost::system::error_code error_code;
auto endpoint =
resolver_.resolve(dstIP.c_str(), std::to_string(dstPort).c_str(), error_code);
auto endpoints = resolver_.resolve(
dstIp,
std::to_string(dstPort),
error_code);
if (error_code) {
log_->write("[" + to_string(uuid_) +
@@ -174,127 +204,179 @@ bool TCPClient::doConnect(const std::string &dstIP, const unsigned short &dstPor
return false;
}
if (tlsEnabled_ && sslSocket_) {
boost::asio::connect(sslSocket_->lowest_layer(), endpoint, error_code);
resetTimeout();
if (tlsEnabled_) {
sslSocket_ = std::make_unique<ssl_stream>(io_context_, sslContext_);
closed_ = false;
connectWithTimeout(sslSocket_->lowest_layer(), endpoints,
config_->general().timeout, error_code);
} else {
boost::asio::connect(socket_, endpoint, error_code);
socket_ = tcp::socket(io_context_);
closed_ = false;
connectWithTimeout(socket_, endpoints,
config_->general().timeout, error_code);
}
cancelTimeout();
if (error_code) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] connect error: " +
error_code.message(),
Log::Level::ERROR);
socketShutdown();
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] connected",
Log::Level::DEBUG);
return true;
} catch (std::exception &error) {
log_->write("[" + to_string(uuid_) + "] [TCPClient doConnect] " +
error.what(),
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doConnect] exception: " + ex.what(),
Log::Level::ERROR);
socketShutdown();
return false;
}
}
/**
* @brief Performs the TLS client handshake.
*
* @details
* - Returns immediately if TLS is not enabled.
* - Extracts the hostname from `config_->general().fakeUrl` for use as SNI.
* - Strips the scheme, path, and port from the configured URL before setting SNI.
* - Sets the TLS SNI extension on the SSL stream.
* - Starts a timeout timer before the handshake and cancels it after completion.
* - Logs SNI usage and handshake failures.
*
* @return `true` if the handshake succeeds or TLS is not enabled, otherwise `false`.
*/
bool TCPClient::doHandshakeClient() {
std::lock_guard lock(mutex_);
try {
if (!tlsEnabled_ || !sslSocket_) return true;
std::string sniHost = config_->general().fakeUrl;
/**
* @brief Extracts the hostname portion of the configured fake URL.
*/
if (!sniHost.empty()) {
auto pos = sniHost.find("://");
if (pos != std::string::npos) {
sniHost = sniHost.substr(pos + 3);
}
pos = sniHost.find('/');
if (pos != std::string::npos) {
sniHost = sniHost.substr(0, pos);
}
pos = sniHost.find(':');
if (pos != std::string::npos) {
sniHost = sniHost.substr(0, pos);
}
if (!sniHost.empty()) {
if (!SSL_set_tlsext_host_name(sslSocket_->native_handle(),
sniHost.c_str())) {
log_->write("[" + to_string(uuid_) +
"] [TLS] Failed to set SNI: " + sniHost,
Log::Level::ERROR);
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TLS] Using SNI: " + sniHost,
Log::Level::DEBUG);
}
if (!tlsEnabled_ || !sslSocket_) {
return true;
}
if (!sslSocket_->lowest_layer().is_open()) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doHandshakeClient] socket is not open",
Log::Level::ERROR);
socketShutdown();
return false;
}
std::string sniHost = config_->randomFakeUrl();
auto pos = sniHost.find("://");
if (pos != std::string::npos) {
sniHost = sniHost.substr(pos + 3);
}
pos = sniHost.find('/');
if (pos != std::string::npos) {
sniHost = sniHost.substr(0, pos);
}
pos = sniHost.find(':');
if (pos != std::string::npos) {
sniHost = sniHost.substr(0, pos);
}
if (!sniHost.empty()) {
if (!SSL_set_tlsext_host_name(
sslSocket_->native_handle(),
sniHost.c_str())) {
log_->write("[" + to_string(uuid_) +
"] [TLS] Failed to set SNI: " + sniHost,
Log::Level::ERROR);
socketShutdown();
return false;
}
static const unsigned char alpn[] = {
0x08, 'h', 't', 't', 'p', '/', '1', '.', '1'};
if (SSL_set_alpn_protos(
sslSocket_->native_handle(),
alpn,
sizeof(alpn)) != 0) {
log_->write("[" + to_string(uuid_) +
"] [TLS] Failed to set ALPN http/1.1",
Log::Level::ERROR);
socketShutdown();
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TLS] Starting client handshake with SNI: " +
sniHost,
Log::Level::DEBUG);
}
boost::system::error_code error;
resetTimeout();
sslSocket_->handshake(boost::asio::ssl::stream_base::client);
sslSocket_->handshake(
boost::asio::ssl::stream_base::client,
error);
cancelTimeout();
if (error) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doHandshakeClient] handshake error: " +
error.message(),
Log::Level::ERROR);
socketShutdown();
return false;
}
log_->write("[" + to_string(uuid_) +
"] [TLS] Client handshake completed",
Log::Level::DEBUG);
const unsigned char *selected = nullptr;
unsigned int selectedLen = 0;
SSL_get0_alpn_selected(
sslSocket_->native_handle(),
&selected,
&selectedLen);
if (selected != nullptr && selectedLen > 0) {
std::string negotiated(
reinterpret_cast<const char *>(selected),
selectedLen);
log_->write("[" + to_string(uuid_) +
"] [TLS] Negotiated ALPN: " + negotiated,
Log::Level::DEBUG);
} else {
log_->write("[" + to_string(uuid_) +
"] [TLS] No ALPN negotiated",
Log::Level::DEBUG);
}
return true;
} catch (std::exception &error) {
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doHandshakeClient] " + error.what(),
"] [TCPClient doHandshakeClient] exception: " +
ex.what(),
Log::Level::ERROR);
socketShutdown();
return false;
}
}
/**
* @brief Replaces the internal write buffer with the contents of the provided buffer.
*
* @param buffer Source buffer whose contents are moved into the internal write buffer.
*/
void TCPClient::writeBuffer(boost::asio::streambuf &buffer) {
std::lock_guard lock(mutex_);
moveStreambuf(buffer, writeBuffer_);
}
/**
* @brief Writes the contents of a buffer to the connected endpoint.
*
* @details
* - Moves the provided input buffer into the internal write buffer.
* - Verifies that the socket is open and that data exists to send.
* - Starts a timeout timer before writing and cancels it afterwards.
* - Writes through the TLS stream when TLS is enabled, otherwise uses the plain socket.
* - Logs destination endpoint information and number of bytes written.
* - Shuts down the socket on error.
*
* @param buffer Source buffer containing data to write.
*/
void TCPClient::doWrite(boost::asio::streambuf &buffer) {
std::lock_guard lock(mutex_);
bool TCPClient::doWrite(boost::asio::streambuf &buffer) {
try {
writeBuffer_.consume(writeBuffer_.size());
moveStreambuf(buffer, writeBuffer_);
if (!isOpen()) {
@@ -302,31 +384,33 @@ void TCPClient::doWrite(boost::asio::streambuf &buffer) {
"] [TCPClient doWrite] socket is not open",
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
if (writeBuffer_.size() == 0) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] empty write buffer",
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
boost::system::error_code error;
resetTimeout();
if (tlsEnabled_ && sslSocket_) {
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [DST " +
sslSocket_->lowest_layer().remote_endpoint().address().to_string() +
":" +
std::to_string(sslSocket_->lowest_layer().remote_endpoint().port()) +
"] [Bytes " + std::to_string(writeBuffer_.size()) + "] ",
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] [SSL] [Bytes " +
std::to_string(writeBuffer_.size()) + "]",
Log::Level::DEBUG);
boost::asio::write(*sslSocket_, writeBuffer_, error);
} else {
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [DST " +
socket_.remote_endpoint().address().to_string() + ":" +
std::to_string(socket_.remote_endpoint().port()) +
"] [Bytes " + std::to_string(writeBuffer_.size()) + "] ",
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] [TCP] [Bytes " +
std::to_string(writeBuffer_.size()) + "]",
Log::Level::DEBUG);
boost::asio::write(socket_, writeBuffer_, error);
}
@@ -337,101 +421,106 @@ void TCPClient::doWrite(boost::asio::streambuf &buffer) {
"] [TCPClient doWrite] [error] " + error.message(),
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
} catch (std::exception &error) {
log_->write("[" + to_string(uuid_) + "] [TCPClient doWrite] [catch] " +
error.what(),
return true;
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doWrite] [catch] " + ex.what(),
Log::Level::DEBUG);
socketShutdown();
return false;
}
}
/**
* @brief Reads agent-side data until the application terminator is encountered.
*
* @details
* - Clears the internal read buffer before reading.
* - Verifies that the socket is open.
* - Starts a timeout timer before reading and cancels it afterwards.
* - Reads until the delimiter `"COMP\r\n\r\n"` is found.
* - Uses the TLS stream when TLS is enabled, otherwise uses the plain socket.
* - Copies the received data into the general-purpose buffer on success.
* - Shuts down the socket on EOF, read error, or exception.
*/
void TCPClient::doReadAgent() {
bool TCPClient::doReadAgent() {
boost::system::error_code error;
std::lock_guard lock(mutex_);
readBuffer_.consume(readBuffer_.size());
try {
if (!isOpen()) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] Socket is not OPEN",
Log::Level::DEBUG);
return;
{
std::lock_guard<std::mutex> lock(mutex_);
readBuffer_.consume(readBuffer_.size());
buffer_.consume(buffer_.size());
if (!isOpen()) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] Socket is not OPEN",
Log::Level::DEBUG);
return false;
}
}
resetTimeout();
if (tlsEnabled_ && sslSocket_) {
boost::asio::read_until(*sslSocket_, readBuffer_, "COMP\r\n\r\n", error);
bool ok = false;
if (tlsEnabled_) {
if (!sslSocket_) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] SSL socket is null",
Log::Level::DEBUG);
socketShutdown();
return false;
}
ok = HttpUtils::readHttpMessage(*sslSocket_, readBuffer_, error);
} else {
boost::asio::read_until(socket_, readBuffer_, "COMP\r\n\r\n", error);
ok = HttpUtils::readHttpMessage(socket_, readBuffer_, error);
}
cancelTimeout();
if (error == boost::asio::error::eof) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [EOF] Connection closed by peer.",
Log::Level::TRACE);
if (!ok) {
if (error == boost::asio::error::operation_aborted) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [aborted]",
Log::Level::DEBUG);
} else if (error == boost::asio::error::eof) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [EOF] Connection closed by peer.",
Log::Level::TRACE);
} else {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [error] " + error.message(),
Log::Level::ERROR);
}
socketShutdown();
return;
} else if (error) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [error] " + error.message(),
Log::Level::ERROR);
socketShutdown();
return;
return false;
}
if (readBuffer_.size() > 0) {
copyStreambuf(readBuffer_, buffer_);
} else {
if (readBuffer_.size() == 0) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] empty read buffer",
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
} catch (std::exception &error) {
copyStreambuf(readBuffer_, buffer_);
return true;
} catch (const std::exception &ex) {
cancelTimeout();
log_->write("[" + to_string(uuid_) +
"] [TCPClient doReadAgent] [catch read] " + error.what(),
"] [TCPClient doReadAgent] [catch read] " + ex.what(),
Log::Level::DEBUG);
socketShutdown();
return;
return false;
}
}
/**
* @brief Reads a chunk of data from the remote server.
*
* @details
* - Clears the internal read buffer before reading.
* - Verifies that the socket is open.
* - Starts a timeout timer before reading and cancels it afterwards.
* - Reads up to 16384 bytes using `read_some`.
* - Uses the TLS stream when TLS is enabled, otherwise uses the plain socket.
* - Writes received bytes into the internal read buffer.
* - Copies the received data into the general-purpose buffer.
* - Updates the `end_` flag when no data is received.
* - Logs source endpoint information and number of bytes read.
* - Shuts down the socket on EOF, read error, or exception.
*/
void TCPClient::doReadServer() {
boost::system::error_code error;
end_ = false;
std::lock_guard lock(mutex_);
readBuffer_.consume(readBuffer_.size());
try {
@@ -500,13 +589,6 @@ void TCPClient::doReadServer() {
}
}
/**
* @brief Starts or resets the operation timeout timer.
*
* @details
* - Does nothing when the configured timeout value is zero.
* - Schedules an asynchronous wait that invokes `onTimeout()`.
*/
void TCPClient::resetTimeout() {
if (!config_->general().timeout) return;
@@ -517,65 +599,197 @@ void TCPClient::resetTimeout() {
});
}
/**
* @brief Cancels the active timeout timer.
*
* @details
* - Does nothing when the configured timeout value is zero.
*/
void TCPClient::cancelTimeout() {
if (config_->general().timeout) timeout_.cancel();
}
/**
* @brief Handles timeout expiration events.
*
* @details
* - Ignores callbacks triggered by cancellation or other non-expiration errors.
* - Logs timeout expiration details.
* - Shuts down the socket when the timeout expires.
*
* @param error Boost system error code for the timer event.
*/
void TCPClient::onTimeout(const boost::system::error_code &error) {
if (error || error == boost::asio::error::operation_aborted) return;
if (error == boost::asio::error::operation_aborted) {
return;
}
log_->write("[" + to_string(uuid_) +
"] [TCPClient onTimeout] [expiration] " +
std::to_string(+config_->general().timeout) +
" seconds has passed, and the timeout has expired",
"] [TCPClient onTimeout] timeout expired",
Log::Level::TRACE);
socketShutdown();
}
/**
* @brief Shuts down and closes the active connection.
*
* @details
* - Gracefully shuts down the TLS stream when present.
* - Shuts down and closes the underlying socket.
* - Ignores shutdown-related error codes.
* - Logs exceptions encountered during shutdown.
*/
void TCPClient::socketShutdown() {
try {
boost::system::error_code ignored;
boost::system::error_code ec;
if (sslSocket_) {
sslSocket_->shutdown(ignored);
sslSocket_->lowest_layer().shutdown(
boost::asio::ip::tcp::socket::shutdown_both, ignored);
sslSocket_->lowest_layer().close(ignored);
}
std::lock_guard<std::mutex> lock(mutex_);
if (socket_.is_open()) {
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored);
socket_.close(ignored);
}
if (closed_) return;
closed_ = true;
} catch (std::exception &error) {
log_->write("[" + to_string(uuid_) +
"] [TCPClient socketShutdown] [catch] " + error.what(),
cancelTimeout();
if (sslSocket_) {
log_->write("[" + to_string(uuid_) + "] [TCPClient socketShutdown] [SSL]",
Log::Level::DEBUG);
auto &lowest = sslSocket_->lowest_layer();
lowest.cancel(ec);
ec.clear();
if (lowest.is_open()) {
lowest.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
ec.clear();
lowest.close(ec);
}
}
}
if (socket_.is_open()) {
log_->write("[" + to_string(uuid_) + "] [TCPClient socketShutdown] [TCP]",
Log::Level::DEBUG);
socket_.cancel(ec);
ec.clear();
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
ec.clear();
socket_.close(ec);
}
tlsEnabled_ = false;
}
std::string TCPClient::HttpUtils::toLowerCopy(std::string s) {
return http_utils::toLowerCopy(std::move(s));
}
std::string TCPClient::HttpUtils::extractHeaders(const std::string &msg) {
return http_utils::extractHeaders(msg);
}
std::string TCPClient::HttpUtils::extractBody(const std::string &msg) {
return http_utils::extractBody(msg);
}
bool TCPClient::HttpUtils::parseContentLength(const std::string &headers, std::size_t &value) {
return http_utils::parseContentLength(headers, value);
}
bool TCPClient::HttpUtils::isChunked(const std::string &headers) {
return http_utils::isChunked(headers);
}
bool TCPClient::HttpUtils::readHttpMessage(
tcp::socket &stream,
boost::asio::streambuf &out,
boost::system::error_code &ec) {
return readHttpMessageImpl(
out,
ec,
[&stream](boost::asio::mutable_buffer buffer,
boost::system::error_code &error) {
return stream.read_some(buffer, error);
},
[&stream](boost::asio::streambuf &buffer,
boost::system::error_code &error) {
boost::asio::read_until(stream, buffer, "\r\n\r\n", error);
return !error;
});
}
bool TCPClient::HttpUtils::readHttpMessage(
ssl_stream &stream,
boost::asio::streambuf &out,
boost::system::error_code &ec) {
return readHttpMessageImpl(
out,
ec,
[&stream](boost::asio::mutable_buffer buffer,
boost::system::error_code &error) {
return stream.read_some(buffer, error);
},
[&stream](boost::asio::streambuf &buffer,
boost::system::error_code &error) {
boost::asio::read_until(stream, buffer, "\r\n\r\n", error);
return !error;
});
}
bool TCPClient::HttpUtils::readHttpMessageImpl(
boost::asio::streambuf &out,
boost::system::error_code &ec,
const std::function<std::size_t(
boost::asio::mutable_buffer,
boost::system::error_code &)> &readSome,
const std::function<bool(
boost::asio::streambuf &,
boost::system::error_code &)> &readHeaders) {
out.consume(out.size());
if (!readHeaders(out, ec)) {
return false;
}
std::string current = streambufToString(out);
std::string headers = extractHeaders(current);
std::string body = extractBody(current);
std::size_t contentLength = 0;
if (parseContentLength(headers, contentLength)) {
while (body.size() < contentLength) {
char tmp[8192];
std::size_t remaining =
contentLength - body.size();
std::size_t toRead =
std::min<std::size_t>(
sizeof(tmp),
remaining);
std::size_t n =
readSome(
boost::asio::buffer(
tmp,
toRead),
ec);
if (ec) {
return false;
}
if (n == 0) {
ec = boost::asio::error::eof;
return false;
}
boost::asio::buffer_copy(
out.prepare(n),
boost::asio::buffer(tmp, n));
out.commit(n);
body.append(tmp, n);
}
return true;
}
if (isChunked(headers)) {
while (
body.find("\r\n0\r\n\r\n") ==
std::string::npos &&
body.find("\r\n0\r\n") ==
std::string::npos) {
char tmp[8192];
std::size_t n =
readSome(
boost::asio::buffer(tmp),
ec);
if (ec) {
return false;
}
if (n == 0) {
ec = boost::asio::error::eof;
return false;
}
boost::asio::buffer_copy(
out.prepare(n),
boost::asio::buffer(tmp, n));
out.commit(n);
body.append(tmp, n);
}
return true;
}
return true;
}
+49 -151
View File
@@ -2,9 +2,8 @@
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/uuid/uuid.hpp>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
@@ -14,195 +13,94 @@
#include "http.hpp"
#include "log.hpp"
/**
* @brief The `TCPClient` class manages TCP and optional TLS communication with remote endpoints.
*
* @details
* - Provides connection management, including DNS resolution and socket handling.
* - Supports both plain TCP and TLS (SSL) communication.
* - Handles reading and writing of data using Boost.Asio stream buffers.
* - Manages connection timeouts and error handling.
* - Designed to be used with shared ownership (`boost::shared_ptr`).
*
* @note
* - Inherits from `boost::enable_shared_from_this` to allow safe shared pointer usage.
* - Thread safety is ensured using an internal mutex where required.
*/
class TCPClient : public boost::enable_shared_from_this<TCPClient> {
class TCPClient : public std::enable_shared_from_this<TCPClient> {
public:
using pointer = boost::shared_ptr<TCPClient>;
using pointer = std::shared_ptr<TCPClient>;
using tcp = boost::asio::ip::tcp;
using ssl_stream = boost::asio::ssl::stream<tcp::socket>;
/**
* @brief Factory method to create a new `TCPClient` instance.
*
* @param io_context Reference to the Boost.Asio I/O context.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @return Shared pointer to the created `TCPClient`.
*/
static pointer create(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log) {
return pointer(new TCPClient(io_context, config, log));
}
/**
* @brief Returns the underlying TCP socket.
*
* @return Reference to the TCP socket.
*/
tcp::socket &socket();
/**
* @brief Returns the TLS (SSL) socket stream.
*
* @return Reference to the SSL stream.
*/
ssl_stream &sslSocket();
/**
* @brief Indicates whether TLS is enabled for this client.
*
* @return `true` if TLS is enabled, otherwise `false`.
*/
bool tlsEnabled() const;
/**
* @brief Checks whether the underlying socket is open.
*
* @return `true` if the socket is open, otherwise `false`.
*/
bool isOpen() const;
/**
* @brief Enables TLS for the client connection.
*
* @details
* - Initializes the SSL context.
* - Prepares the SSL stream for encrypted communication.
*
* @return `true` if initialization succeeds, otherwise `false`.
*/
bool enableTlsClient();
/**
* @brief Performs a TLS handshake with the remote endpoint.
*
* @details
* - Must be called after establishing a TCP connection.
*
* @return `true` if the handshake succeeds, otherwise `false`.
*/
bool doHandshakeClient();
bool doConnect(const std::string &dstIp, unsigned short dstPort);
/**
* @brief Writes data into the internal write buffer.
*
* @param buffer Source buffer to copy into the internal write buffer.
*/
void writeBuffer(boost::asio::streambuf &buffer);
/**
* @brief Returns the internal write buffer (lvalue).
*/
inline boost::asio::streambuf &writeBuffer() & { return writeBuffer_; }
/**
* @brief Returns the internal write buffer (rvalue).
*/
inline boost::asio::streambuf &&writeBuffer() && {
return std::move(writeBuffer_);
}
/**
* @brief Returns the internal read buffer (lvalue).
*/
inline boost::asio::streambuf &readBuffer() & { return readBuffer_; }
/**
* @brief Returns the internal read buffer (rvalue).
*/
inline boost::asio::streambuf &&readBuffer() && { return std::move(readBuffer_); }
/**
* @brief Establishes a connection to the specified destination.
*
* @param dstIP Destination IP address or hostname.
* @param dstPort Destination port.
* @return `true` if the connection succeeds, otherwise `false`.
*/
bool doConnect(const std::string &dstIP, const unsigned short &dstPort);
/**
* @brief Writes data to the remote endpoint.
*
* @param buffer Buffer containing the data to send.
*/
void doWrite(boost::asio::streambuf &buffer);
/**
* @brief Reads data from the agent-side connection.
*/
void doReadAgent();
/**
* @brief Reads data from the server-side connection.
*/
bool doReadAgent();
bool doWrite(boost::asio::streambuf &buffer);
void doReadServer();
/**
* @brief Shuts down and closes the socket connection.
*/
void socketShutdown();
boost::uuids::uuid uuid_;///< Unique identifier for this client session.
bool end_; ///< Indicates whether the connection has completed.
boost::uuids::uuid uuid() const { return uuid_; }
bool ended() const { return end_; }
boost::uuids::uuid uuid_;
bool end_;
private:
/**
* @brief Constructs a `TCPClient` instance.
*
* @param io_context Reference to the Boost.Asio I/O context.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
*/
struct HttpUtils {
static std::string toLowerCopy(std::string s);
static std::string extractHeaders(const std::string &msg);
static std::string extractBody(const std::string &msg);
static bool parseContentLength(const std::string &headers, std::size_t &value);
static bool isChunked(const std::string &headers);
static bool readHttpMessage(tcp::socket &stream,
boost::asio::streambuf &out,
boost::system::error_code &ec);
static bool readHttpMessage(ssl_stream &stream,
boost::asio::streambuf &out,
boost::system::error_code &ec);
static bool readHttpMessageImpl(
boost::asio::streambuf &out,
boost::system::error_code &ec,
const std::function<std::size_t(boost::asio::mutable_buffer,
boost::system::error_code &)> &readSome,
const std::function<bool(boost::asio::streambuf &,
boost::system::error_code &)> &readHeaders);
};
explicit TCPClient(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log);
/**
* @brief Resets the connection timeout timer.
*/
void resetTimeout();
/**
* @brief Cancels the connection timeout timer.
*/
void cancelTimeout();
/**
* @brief Handles timeout events.
*
* @param error Boost system error code.
*/
void onTimeout(const boost::system::error_code &error);
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
boost::asio::io_context &io_context_; ///< Reference to the I/O context.
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context &io_context_;
tcp::socket socket_; ///< Underlying TCP socket.
boost::asio::ssl::context sslContext_; ///< SSL context for TLS connections.
std::unique_ptr<ssl_stream> sslSocket_;///< SSL stream wrapper.
bool tlsEnabled_; ///< Indicates whether TLS is active.
tcp::socket socket_;
boost::asio::ssl::context sslContext_;
std::unique_ptr<ssl_stream> sslSocket_;
bool tlsEnabled_;
boost::asio::streambuf buffer_; ///< General-purpose buffer.
boost::asio::streambuf writeBuffer_;///< Buffer for outgoing data.
boost::asio::streambuf readBuffer_; ///< Buffer for incoming data.
boost::asio::streambuf buffer_;
boost::asio::streambuf writeBuffer_;
boost::asio::streambuf readBuffer_;
tcp::resolver resolver_; ///< DNS resolver.
boost::asio::steady_timer timeout_;///< Timeout timer.
mutable std::mutex mutex_; ///< Mutex for thread-safe operations.
tcp::resolver resolver_;
boost::asio::steady_timer timeout_;
mutable std::mutex mutex_;
bool closed_ = false;
};
+997 -473
View File
File diff suppressed because it is too large. Load diff
+108 -192
View File
@@ -1,57 +1,32 @@
#pragma once
#include <array>
#include <atomic>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <chrono>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
#include "agenthandler.hpp"
#include "general.hpp"
#include "serverhandler.hpp"
#include "usage.hpp"
/**
* @brief The `TCPConnection` class manages a single inbound connection and its forwarding lifecycle.
*
* @details
* - Owns the accepted client-side socket.
* - Optionally supports TLS on the server-facing accepted connection.
* - Coordinates request handling using either `AgentHandler` or `ServerHandler`
* depending on the runtime mode.
* - Manages asynchronous reads, writes, timeout handling, and tunnel relaying.
* - Maintains per-connection state such as connection completion, CONNECT mode,
* and full tunnel mode.
*
* @note
* - Inherits from `boost::enable_shared_from_this` to safely retain itself
* during asynchronous operations.
* - Uses shared ownership via `boost::shared_ptr`.
* - Instances should be created using the `create` factory method.
*/
class TCPConnection : public boost::enable_shared_from_this<TCPConnection> {
class TCPConnection : public std::enable_shared_from_this<TCPConnection> {
public:
using pointer = boost::shared_ptr<TCPConnection>;
using ssl_stream =
boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
using pointer = std::shared_ptr<TCPConnection>;
using ssl_stream = boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
/**
* @brief Factory method to create a new `TCPConnection` instance.
*
* @details
* - Wraps construction in a `boost::shared_ptr`.
* - Ensures consistent ownership and lifetime management for asynchronous use.
*
* @param io_context Reference to the Boost.Asio I/O context.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param client Shared pointer to the associated outbound `TCPClient`.
* @return Shared pointer to the created `TCPConnection`.
*/
static pointer create(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
@@ -59,198 +34,139 @@ public:
return pointer(new TCPConnection(io_context, config, log, client));
}
/**
* @brief Returns the accepted client-side socket.
*
* @return Reference to the underlying TCP socket.
*/
boost::asio::ip::tcp::socket &socket();
/**
* @brief Returns the associated outbound `TCPClient`.
*
* @return Shared pointer to the client object.
*/
inline TCPClient::pointer client() { return client_; }
/**
* @brief Returns the TLS server stream.
*
* @return Reference to the TLS socket stream.
*/
inline TCPClient::pointer client() const { return client_; }
ssl_stream &tlsSocket();
/**
* @brief Initializes the TLS server context for this connection.
*
* @details
* - Loads certificates, private key, and related TLS configuration.
* - Prepares the connection to accept inbound TLS handshakes.
*
* @return `true` if initialization succeeds, otherwise `false`.
*/
bool initTlsServerContext();
/**
* @brief Performs the server-side TLS handshake.
*
* @return `true` if the handshake succeeds, otherwise `false`.
*/
bool doHandshakeServer();
/**
* @brief Replaces the internal write buffer with the provided buffer contents.
*
* @param buffer Source buffer whose contents are moved into the internal write buffer.
*/
inline void writeBuffer(boost::asio::streambuf &buffer) {
moveStreambuf(buffer, writeBuffer_);
}
/**
* @brief Returns the internal read buffer (lvalue).
*
* @return Const reference to the internal read buffer.
*/
inline const boost::asio::streambuf &readBuffer() & { return readBuffer_; }
/**
* @brief Returns the internal read buffer (rvalue).
*
* @return Const rvalue reference to the internal read buffer.
*/
inline const boost::asio::streambuf &&readBuffer() && {
return std::move(readBuffer_);
}
inline boost::uuids::uuid uuid() const { return uuid_; }
/**
* @brief Returns the UUID associated with this connection.
*
* @return Connection UUID.
*/
inline boost::uuids::uuid uuid() { return uuid_; }
/**
* @brief Starts connection processing in agent mode.
*
* @details
* - Uses `AgentHandler` logic to process incoming traffic.
*/
void startAgent();
/**
* @brief Starts connection processing in server mode.
*
* @details
* - Uses `ServerHandler` logic to process incoming traffic.
*/
void startServer();
/**
* @brief Initiates an asynchronous read for agent-side traffic.
*/
void doReadAgent();
/**
* @brief Initiates an asynchronous read for server-side traffic.
*/
void doReadServer();
void handleReadAgent(const boost::system::error_code &error, size_t bytes_transferred);
void handleReadServer(const boost::system::error_code &error, size_t bytes_transferred);
/**
* @brief Handles completion of an agent-side asynchronous read.
*
* @param error Boost system error code.
* @param bytes_transferred Number of bytes received.
*/
void handleReadAgent(const boost::system::error_code &error,
size_t bytes_transferred);
/**
* @brief Handles completion of a server-side asynchronous read.
*
* @param error Boost system error code.
* @param bytes_transferred Number of bytes received.
*/
void handleReadServer(const boost::system::error_code &error,
size_t bytes_transferred);
/**
* @brief Gracefully shuts down and closes the active connection.
*/
void socketShutdown();
/**
* @brief Enables full tunnel relay mode.
*
* @details
* - Used after CONNECT-style negotiation when traffic should be relayed
* transparently in both directions.
*/
void enableTunnelMode();
static std::size_t revokeUsers(const std::vector<std::string> &users);
/**
* @brief Relays traffic from the connected client to the remote endpoint.
*/
void relayClientToRemote();
void enableDirectTunnelMode();
/**
* @brief Relays traffic from the remote endpoint back to the connected client.
*/
void relayRemoteToClient();
void relayClientToServer();
void relayServerToClient();
void relayAgentToTarget();
void relayTargetToAgent();
std::mutex relayMutex_;
inline void asyncWriteToAgentConnection(
const char *data,
std::size_t bytes,
std::function<void(const boost::system::error_code &)> done);
inline void asyncReadFromAgentConnection(
std::array<char, BufferSize> &buffer,
std::function<void(const boost::system::error_code &, std::size_t)> done);
inline void asyncWriteToAgentServerConnection(
const char *data,
std::size_t bytes,
std::function<void(const boost::system::error_code &)> done);
inline void asyncReadFromAgentServerConnection(
std::array<char, BufferSize> &buffer,
std::function<void(const boost::system::error_code &, std::size_t)> done);
private:
/**
* @brief Constructs a `TCPConnection` instance.
*
* @param io_context Reference to the Boost.Asio I/O context.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @param client Shared pointer to the associated outbound `TCPClient`.
*/
struct HttpUtils {
static std::string toLowerCopy(std::string s);
static std::string extractHeaders(const std::string &msg);
static std::string extractBody(const std::string &msg);
static bool parseContentLength(const std::string &headers, std::size_t &value);
static bool isChunked(const std::string &headers);
static bool readRemainingHttpBody(boost::asio::ip::tcp::socket &stream,
boost::asio::streambuf &buf,
boost::system::error_code &ec);
static bool readRemainingHttpBody(ssl_stream &stream,
boost::asio::streambuf &buf,
boost::system::error_code &ec);
static bool readRemainingHttpBodyImpl(
boost::asio::streambuf &buf,
boost::system::error_code &ec,
const std::function<std::size_t(boost::asio::mutable_buffer,
boost::system::error_code &)> &readSome);
};
explicit TCPConnection(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log,
TCPClient::pointer client);
/**
* @brief Starts or resets the timeout timer for the connection.
*/
bool handleSocks5Handshake();
bool readExactFromClient(void *data, std::size_t size);
void resetTimeout();
/**
* @brief Cancels the active timeout timer.
*/
void cancelTimeout();
/**
* @brief Handles timeout expiration events.
*
* @param error Boost system error code for the timer event.
*/
void onTimeout(const boost::system::error_code &error);
boost::asio::ip::tcp::socket socket_; ///< Accepted inbound socket.
boost::asio::ssl::context sslContext_; ///< TLS server context.
std::unique_ptr<ssl_stream> tlsSocket_;///< Optional TLS-wrapped inbound socket.
void startTunnelReadFromClient();
void startTunnelPollServer();
std::optional<std::string> postTunnelAction(const std::string &action, const std::string &rawBody);
void abortTunnel(const std::string &reason);
std::string makeRelayHostHeader() const;
void closeTunnelSession();
const std::shared_ptr<Config> &config_;///< Reference to the configuration object.
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
boost::asio::io_context &io_context_; ///< Reference to the I/O context.
TCPClient::pointer client_; ///< Associated outbound TCP client.
void trackUser(const std::string &user);
boost::asio::streambuf readBuffer_; ///< Buffer for incoming data.
boost::asio::streambuf writeBuffer_;///< Buffer for outgoing data.
boost::asio::ip::tcp::socket socket_;
boost::asio::ssl::context sslContext_;
std::unique_ptr<ssl_stream> tlsSocket_;
boost::asio::steady_timer timeout_; ///< Per-connection timeout timer.
boost::asio::strand<boost::asio::io_context::executor_type> strand_;///< Strand for serialized handlers.
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context &io_context_;
TCPClient::pointer client_;
boost::uuids::uuid uuid_;///< Unique identifier for this connection.
std::mutex mutex_; ///< Mutex for thread-safe state changes.
boost::asio::streambuf readBuffer_;
boost::asio::streambuf writeBuffer_;
bool end_; ///< Indicates whether processing has completed.
bool connect_; ///< Indicates whether a connection or CONNECT tunnel is active.
bool tunnelMode_;///< Indicates whether transparent bidirectional relay mode is enabled.
boost::asio::steady_timer timeout_;
boost::asio::steady_timer pollTimer_;
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
std::array<char, 16384> downstreamBuf_;///< Buffer for traffic flowing to the remote side.
std::array<char, 16384> upstreamBuf_; ///< Buffer for traffic flowing back to the client.
boost::uuids::uuid uuid_;
std::mutex mutex_;
bool end_;
bool connect_;
bool tunnelMode_;
bool tunnelClosed_;
bool pollInProgress_;
unsigned int pollDelayMs_;
std::atomic_bool closed_{false};
std::string userHint_;
std::string trackedUser_;
std::shared_ptr<Usage::Counter> usage_;
static std::mutex registryMutex_;
static std::unordered_map<std::string, std::vector<std::weak_ptr<TCPConnection>>> byUser_;
std::array<char, BufferSize> downstreamBuf_;
std::array<char, BufferSize> upstreamBuf_;
};
+24 -70
View File
@@ -1,17 +1,8 @@
#include "tcpserver.hpp"
/**
* @brief Constructs a `TCPServer` instance and initializes the listening acceptor.
*
* @details
* - Binds the acceptor to the configured IP address and port.
* - Enables `reuse_address` to allow quick restarts without waiting for socket release.
* - Immediately starts accepting incoming connections.
*
* @param io_context Reference to the Boost.Asio I/O context.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
*/
#include <atomic>
#include <chrono>
TCPServer::TCPServer(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log)
@@ -23,18 +14,9 @@ TCPServer::TCPServer(boost::asio::io_context &io_context,
boost::asio::ip::make_address(config->listenIp()),
config->listenPort())) {
acceptor_.set_option(boost::asio::socket_base::reuse_address(true));
startAccept();
}
/**
* @brief Initiates an asynchronous accept operation for incoming connections.
*
* @details
* - Creates a new `TCPClient` and associated `TCPConnection`.
* - Calls `async_accept` to wait for incoming connections.
* - On completion, forwards control to `handleAccept()`.
*/
void TCPServer::startAccept() {
auto client = TCPClient::create(io_context_, config_, log_);
auto connection = TCPConnection::create(io_context_, config_, log_, client);
@@ -46,71 +28,43 @@ void TCPServer::startAccept() {
});
}
/**
* @brief Handles the result of an asynchronous accept operation.
*
* @details
* - On successful accept:
* - In **server mode**:
* - Initializes TLS server context.
* - Transfers the accepted socket to the TLS stream.
* - Performs TLS handshake.
* - Starts server-side processing.
* - In **agent mode**:
* - Starts agent-side processing directly (no TLS termination).
*
* - On failure:
* - Logs the error.
*
* - Always continues accepting new connections regardless of outcome.
*
* @param connection Shared pointer to the accepted `TCPConnection`.
* @param error Error code returned by the accept operation.
*/
void TCPServer::handleAccept(TCPConnection::pointer connection,
const boost::system::error_code &error) {
void TCPServer::handleAccept(
TCPConnection::pointer connection,
const boost::system::error_code &error) {
startAccept();
try {
if (!error) {
if (config_->runMode() == RunMode::server) {
// Initialize TLS context for incoming server connections
if (error) {
log_->write("[TCPServer handleAccept] Error: " + error.message(), Log::Level::ERROR);
return;
}
if (config_->runMode() == RunMode::server) {
if (config_->general().tlsEnable) {
if (!connection->initTlsServerContext()) {
log_->write("[TCPServer handleAccept] TLS server context init failed",
Log::Level::ERROR);
log_->write("[TCPServer handleAccept] TLS server context init failed", Log::Level::ERROR);
connection->socketShutdown();
startAccept();
return;
}
// Move plain socket into TLS layer
connection->tlsSocket().lowest_layer() = std::move(connection->socket());
// Perform TLS handshake
if (!connection->doHandshakeServer()) {
log_->write("[TCPServer handleAccept] TLS server handshake failed",
Log::Level::ERROR);
log_->write("[TCPServer handleAccept] TLS server handshake failed", Log::Level::ERROR);
connection->socketShutdown();
startAccept();
return;
}
// Start server-side handling
connection->startServer();
} else {
// Start agent-side handling (no TLS termination)
connection->startAgent();
}
connection->startServer();
} else {
log_->write("[TCPServer handleAccept] Error: " + error.message(),
Log::Level::ERROR);
connection->startAgent();
}
} catch (const std::exception &ex) {
log_->write("[TCPServer handleAccept] Exception: " + std::string(ex.what()),
Log::Level::ERROR);
log_->write("[TCPServer handleAccept] Exception: " + std::string(ex.what()), Log::Level::ERROR);
connection->socketShutdown();
} catch (...) {
log_->write("[TCPServer handleAccept] Unknown exception",
Log::Level::ERROR);
log_->write("[TCPServer handleAccept] Unknown exception", Log::Level::ERROR);
connection->socketShutdown();
}
// Continue accepting new connections
startAccept();
}
+7 -61
View File
@@ -1,86 +1,32 @@
#pragma once
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <memory>
#include "tcpconnection.hpp"
/**
* @brief The `TCPServer` class accepts incoming TCP connections and dispatches them for handling.
*
* @details
* - Owns the listening acceptor socket.
* - Uses the provided Boost.Asio `io_context` for asynchronous accept operations.
* - Creates `TCPConnection` instances for accepted clients.
* - Integrates with configuration and logging components.
*
* @note
* - Instances are managed through shared ownership using `boost::shared_ptr`.
* - Objects should be created using the `create` factory method.
*/
class TCPServer {
public:
using pointer = boost::shared_ptr<TCPServer>;
using pointer = std::shared_ptr<TCPServer>;
/**
* @brief Factory method to create a new `TCPServer` instance.
*
* @details
* - Wraps object construction in a `boost::shared_ptr`.
* - Ensures consistent ownership and lifetime management.
*
* @param io_context Reference to the Boost.Asio I/O context.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
* @return Shared pointer to the created `TCPServer`.
*/
static pointer create(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log) {
return pointer(new TCPServer(io_context, config, log));
}
/**
* @brief Starts accepting incoming client connections.
*
* @details
* - Begins an asynchronous accept operation on the listening socket.
* - Accepted connections are passed to `handleAccept()`.
*/
void startAccept();
private:
/**
* @brief Constructs a `TCPServer` instance.
*
* @details
* - Stores references to the configuration, logging object, and I/O context.
* - Initializes the listening acceptor socket.
*
* @param io_context Reference to the Boost.Asio I/O context.
* @param config Shared pointer to the configuration object.
* @param log Shared pointer to the logging object.
*/
explicit TCPServer(boost::asio::io_context &io_context,
const std::shared_ptr<Config> &config,
const std::shared_ptr<Log> &log);
/**
* @brief Handles completion of an asynchronous accept operation.
*
* @details
* - Receives the newly accepted `TCPConnection`.
* - Inspects the accept result through the provided error code.
* - Starts connection processing when accept succeeds.
*
* @param connection Shared pointer to the accepted `TCPConnection`.
* @param error Result of the accept operation.
*/
void handleAccept(TCPConnection::pointer connection,
const boost::system::error_code &error);
const std::shared_ptr<Config> &config_; ///< Reference to the configuration object.
const std::shared_ptr<Log> &log_; ///< Reference to the logging object.
boost::asio::io_context &io_context_; ///< Reference to the I/O context.
boost::asio::ip::tcp::acceptor acceptor_;///< Listening TCP acceptor.
};
std::shared_ptr<Config> config_;
std::shared_ptr<Log> log_;
boost::asio::io_context &io_context_;
boost::asio::ip::tcp::acceptor acceptor_;
};
+220
View File
@@ -0,0 +1,220 @@
#include "usage.hpp"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <cstdio>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <sstream>
Usage &Usage::instance() {
static Usage usage;
return usage;
}
std::string Usage::periodStart(int resetDay) {
const std::time_t now = std::time(nullptr);
std::tm local{};
#if defined(_WIN32)
localtime_s(&local, &now);
#else
localtime_r(&now, &local);
#endif
int year = local.tm_year + 1900;
int month = local.tm_mon + 1;
if (local.tm_mday < resetDay) {
if (--month == 0) {
month = 12;
--year;
}
}
char buf[40];
std::snprintf(buf, sizeof(buf), "%04d-%02d-%02d", year, month, resetDay);
return buf;
}
bool Usage::overLimit(const Counter &counter) {
const std::uint64_t limit = counter.limit.load();
return limit != 0 && counter.used.load() >= limit;
}
void Usage::configure(const Config &config, LimitHandler onLimit, Log &log) {
std::vector<std::string> newlyBlocked;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!onLimit_) onLimit_ = std::move(onLimit);
enabled_ = config.runMode() == RunMode::server && config.hasUserList();
if (!enabled_) return;
file_ = config.usageFile();
resetDay_ = config.usageResetDay();
active_.clear();
for (const auto &user: config.users()) {
auto &counter = counters_[user.name];
if (!counter) counter = std::make_shared<Counter>(user.name);
counter->limit.store(user.limit);
active_.insert(user.name);
}
newlyBlocked = refreshBlocked(log);
}
for (const auto &name: newlyBlocked) onLimit_(name);
}
Usage::CounterPtr Usage::counter(const std::string &user) {
std::lock_guard<std::mutex> lock(mutex_);
if (!enabled_) return nullptr;
auto it = counters_.find(user);
return it == counters_.end() ? nullptr : it->second;
}
void Usage::add(const CounterPtr &counter, std::uint64_t bytes) {
if (!counter || bytes == 0) return;
const std::uint64_t after = counter->used.fetch_add(bytes) + bytes;
const std::uint64_t limit = counter->limit.load();
if (limit != 0 && after >= limit && !counter->blocked.exchange(true) && onLimit_) {
onLimit_(counter->name);
}
}
std::vector<std::string> Usage::refreshBlocked(Log &log) {
std::vector<std::string> newlyBlocked;
for (const auto &[name, counter]: counters_) {
const bool over = overLimit(*counter);
if (over && !counter->blocked.exchange(true)) {
newlyBlocked.push_back(name);
} else if (!over && counter->blocked.exchange(false)) {
log.write("[Usage] user " + name + " is below their limit again", Log::Level::INFO);
}
}
return newlyBlocked;
}
void Usage::flush(Log &log) {
std::vector<std::string> newlyBlocked;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!enabled_) return;
YAML::Node doc;
bool haveFile = false;
if (fileExists(file_)) {
try {
doc = YAML::LoadFile(file_);
haveFile = true;
} catch (const std::exception &e) {
log.write("[Usage] cannot read " + file_ + ": " + e.what() +
"; usage is not saved until the file is fixed",
Log::Level::ERROR);
return;
}
}
const std::string filePeriod = haveFile ? doc["period"].as<std::string>("") : "";
const bool firstFlush = !loaded_;
if (firstFlush) {
period_ = filePeriod.empty() ? periodStart(resetDay_) : filePeriod;
loaded_ = true;
}
const YAML::Node fileUsers = haveFile ? doc["users"] : YAML::Node();
if (haveFile && filePeriod == period_ && fileUsers.IsMap()) {
for (auto &[name, counter]: counters_) {
const YAML::Node entry = fileUsers[name];
if (!entry || !entry["used"]) continue;
std::uint64_t value = 0;
try {
value = entry["used"].as<std::uint64_t>();
} catch (const std::exception &) {
log.write("[Usage] used of " + name + " in " + file_ +
" is not a number of bytes; ignored",
Log::Level::ERROR);
continue;
}
if (value == counter->lastWritten) continue;
counter->used.fetch_add(value - counter->lastWritten);
counter->lastWritten = value;
if (!firstFlush) {
log.write("[Usage] usage of " + name + " set to " + formatBytes(value) +
" from " + file_,
Log::Level::INFO);
}
}
}
const std::string current = periodStart(resetDay_);
if (current != period_) {
for (auto &[name, counter]: counters_) counter->used.store(0);
log.write("[Usage] new usage period from " + current + "; usage of all users reset",
Log::Level::INFO);
period_ = current;
}
newlyBlocked = refreshBlocked(log);
std::vector<std::string> names;
for (const auto &[name, counter]: counters_) names.push_back(name);
std::sort(names.begin(), names.end());
std::ostringstream out;
out << "# NipoVPN usage: bytes each user sent and received since " << period_ << ".\n"
<< "# To change a user's usage, edit their \"used\" (for example set it to 0).\n"
<< "# The server applies the change within 30 seconds. Do not edit \"period\".\n"
<< "period: \"" << period_ << "\"\n"
<< "users:\n";
std::vector<std::pair<Counter *, std::uint64_t>> written;
for (const auto &name: names) {
Counter &counter = *counters_[name];
const std::uint64_t used = counter.used.load();
const std::uint64_t limit = counter.limit.load();
out << " " << name << ": {used: " << used << "} # " << formatBytes(used);
if (!active_.count(name)) {
out << ", not in the users list";
} else if (limit != 0) {
out << " of " << formatBytes(limit) << " ("
<< std::min<std::uint64_t>(used * 100 / limit, 999) << "%)"
<< (used >= limit ? ", blocked" : "");
} else {
out << ", no limit";
}
out << "\n";
written.emplace_back(&counter, used);
}
if (haveFile && filePeriod == period_ && fileUsers.IsMap()) {
for (const auto &entry: fileUsers) {
const std::string name = entry.first.as<std::string>("");
if (name.empty() || counters_.count(name) || !isValidUserName(name)) continue;
out << " " << name << ": {used: " << entry.second["used"].as<std::uint64_t>(0)
<< "} # not in the users list\n";
}
}
try {
const std::filesystem::path path(file_);
if (path.has_parent_path()) std::filesystem::create_directories(path.parent_path());
const std::string tmp = file_ + ".tmp";
{
std::ofstream f(tmp, std::ios::out | std::ios::trunc);
if (!f) throw std::runtime_error("cannot open " + tmp + " for writing");
f << out.str();
f.flush();
if (!f) throw std::runtime_error("cannot write " + tmp);
}
std::filesystem::rename(tmp, path);
for (const auto &[counter, used]: written) counter->lastWritten = used;
} catch (const std::exception &e) {
log.write(std::string("[Usage] cannot save usage: ") + e.what(), Log::Level::ERROR);
}
}
for (const auto &name: newlyBlocked) onLimit_(name);
}
+59
View File
@@ -0,0 +1,59 @@
#pragma once
#include <atomic>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "config.hpp"
#include "log.hpp"
class Usage : private Uncopyable {
public:
struct Counter {
explicit Counter(std::string userName) : name(std::move(userName)) {}
const std::string name;
std::atomic<std::uint64_t> used{0};
std::atomic<std::uint64_t> limit{0};
std::atomic<bool> blocked{false};
std::uint64_t lastWritten = 0;
};
using CounterPtr = std::shared_ptr<Counter>;
using LimitHandler = std::function<void(const std::string &user)>;
static Usage &instance();
void configure(const Config &config, LimitHandler onLimit, Log &log);
CounterPtr counter(const std::string &user);
void add(const CounterPtr &counter, std::uint64_t bytes);
static bool overLimit(const Counter &counter);
void flush(Log &log);
static std::string periodStart(int resetDay);
private:
Usage() = default;
std::vector<std::string> refreshBlocked(Log &log);
std::mutex mutex_;
std::unordered_map<std::string, CounterPtr> counters_;
std::unordered_set<std::string> active_;
LimitHandler onLimit_;
bool enabled_ = false;
std::string file_;
int resetDay_ = 1;
std::string period_;
bool loaded_ = false;
};
+40
View File
@@ -0,0 +1,40 @@
FROM ubuntu:24.04 AS builder
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
build-essential \
cmake \
git \
libboost-all-dev \
libssl-dev \
libyaml-cpp-dev \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /src
COPY . .
RUN cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \
&& cmake --build build --target nipovpn -j$(nproc)
FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
libboost-regex1.83.0 \
libssl3t64 \
libyaml-cpp0.8 \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN mkdir -p /etc/nipovpn /var/log/nipovpn
COPY --from=builder /src/build/core/nipovpn /usr/local/bin/nipovpn
COPY nipovpn/etc/nipovpn/config.yaml /etc/nipovpn/config.yaml
ENTRYPOINT ["nipovpn"]
CMD ["server", "/etc/nipovpn/config.yaml"]
+29
View File
@@ -0,0 +1,29 @@
services:
nipovpn:
container_name: nipovpn
build:
context: ..
dockerfile: docker/Dockerfile
image: nipovpn:latest
restart: unless-stopped
ports:
- "443:443"
- "8080:8080"
volumes:
- ../nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro
- nipovpn_logs:/var/log/nipovpn
# Per-user usage (server with a users list); keeps counts across restarts.
- nipovpn_state:/var/lib/nipovpn
command:
- ${NIPOVPN_MODE:-server}
- /etc/nipovpn/config.yaml
volumes:
nipovpn_logs:
nipovpn_state:
-3
View File
@@ -1,3 +0,0 @@
theme: jekyll-theme-minimal
title: NipoVPN's homepage
description: Safe and powerful http proxy
-74
View File
@@ -1,74 +0,0 @@
body {
font-family: 'Karla', sans-serif;
background-image: url("../images/bg.jpg");
background-size: cover;
background-repeat: no-repeat;
background-position: center;
color: #ffffff;
padding-bottom: 75px; }
@media (min-width: 768px) {
body {
padding-bottom: 110px; } }
.navbar-brand {
margin-right: 0; }
.navbar-brand img {
height: 21px; }
.navbar-dark {
padding-top: 35px;
padding-bottom: 35px; }
.navbar-dark .navbar-text {
color: #ffffff;
opacity: 1;
padding: 0 20px;
border-right: 1px solid #ffffff;
font-size: 18px;
font-weight: bold;
text-align: center; }
.navbar-dark .navbar-text:last-child {
border-right: 0; }
@media (max-width: 767px) {
.navbar-dark {
padding-bottom: 0; } }
.page-title {
font-size: 80px;
font-weight: bold;
margin-bottom: 6px; }
@media (max-width: 767px) {
.page-title {
font-size: 35px;
margin-bottom: 14px; } }
.page-description {
max-width: 465px;
font-size: 18px;
margin-bottom: 59px; }
@media (max-width: 767px) {
.page-description {
font-size: 14px; } }
p {
font-size: 14px;
margin-bottom: 21px; }
.footer-social-links .social-link {
display: inline-block;
text-align: center;
line-height: 40px;
width: 40px;
height: 40px;
border-radius: 50%;
background-color: #ffffff;
color: #000000;
margin-right: 16px;
transition: all 0.3s ease-in-out; }
.footer-social-links .social-link:last-child {
margin-right: 0; }
.footer-social-links .social-link:hover {
text-decoration: none;
background-color: #000000;
color: #ffffff; }
/*# sourceMappingURL=bd-coming-soon.css.map */
-1
View File
@@ -1 +0,0 @@
{"version":3,"sources":["bd-coming-soon.scss"],"names":[],"mappings":"AAAA;EACI,gCAAgC;EAChC,yCAAyC;EACzC,sBAAsB;EACtB,4BAA4B;EAC5B,2BAA2B;EAC3B,cAAc;EACd,oBAAoB,EAAA;EAEpB;IATJ;MAUQ,qBAAqB,EAAA,EAE5B;;AACD;EACI,eAAe,EAAA;EADnB;IAIQ,YAAY,EAAA;;AAGpB;EACI,iBAAiB;EACjB,oBAAoB,EAAA;EAFxB;IAIQ,cAAc;IACd,UAAU;IACV,eAAe;IACf,+BAA+B;IAC/B,eAAe;IACf,iBAAiB;IACjB,kBAAkB,EAAA;IAV1B;MAaY,eAAe,EAAA;EAIvB;IAjBJ;MAkBQ,iBAAiB,EAAA,EAExB;;AACD;EACI,eAAe;EACf,iBAAiB;EACjB,kBAAkB,EAAA;EAElB;IALJ;MAMQ,eAAe;MACf,mBAAmB,EAAA,EAE1B;;AACD;EACI,gBAAgB;EAChB,eAAe;EACf,mBAAmB,EAAA;EAEnB;IALJ;MAMQ,eAAe,EAAA,EAEtB;;AAED;EACI,eAAe;EACf,mBAAmB,EAAA;;AAGvB;EAEQ,qBAAqB;EACrB,kBAAkB;EAClB,iBAAiB;EACjB,WAAW;EACX,YAAY;EACZ,kBAAkB;EAClB,yBAAyB;EACzB,cAAc;EACd,kBAAkB;EAClB,gCAAgC,EAAA;EAXxC;IAcY,eAAe,EAAA;EAd3B;IAkBY,qBAAqB;IACrB,yBAAyB;IACzB,cAAc,EAAA","file":"bd-coming-soon.css","sourcesContent":["body {\n font-family: 'Karla', sans-serif;\n background-image: url(\"../images/bg.jpg\");\n background-size: cover;\n background-repeat: no-repeat;\n background-position: center;\n color: #ffffff;\n padding-bottom: 75px;\n\n @media (min-width: 768px) {\n padding-bottom: 110px;\n }\n}\n.navbar-brand {\n margin-right: 0;\n\n img {\n height: 21px;\n }\n}\n.navbar-dark {\n padding-top: 35px;\n padding-bottom: 35px;\n .navbar-text {\n color: #ffffff;\n opacity: 1;\n padding: 0 20px;\n border-right: 1px solid #ffffff;\n font-size: 18px;\n font-weight: bold;\n text-align: center;\n\n &:last-child {\n border-right: 0;\n }\n }\n\n @media (max-width: 767px) {\n padding-bottom: 0;\n }\n}\n.page-title {\n font-size: 80px;\n font-weight: bold;\n margin-bottom: 6px;\n\n @media (max-width: 767px) {\n font-size: 35px;\n margin-bottom: 14px; \n }\n}\n.page-description {\n max-width: 465px;\n font-size: 18px;\n margin-bottom: 59px;\n\n @media (max-width: 767px) {\n font-size: 14px; \n }\n}\n\np {\n font-size: 14px;\n margin-bottom: 21px;\n}\n\n.footer-social-links {\n .social-link {\n display: inline-block;\n text-align: center;\n line-height: 40px;\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background-color: #ffffff;\n color: #000000;\n margin-right: 16px;\n transition: all 0.3s ease-in-out;\n\n &:last-child {\n margin-right: 0;\n }\n\n &:hover {\n text-decoration: none;\n background-color: #000000;\n color: #ffffff;\n }\n }\n}"]}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 215 KiB

-3
View File
@@ -1,3 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="59" height="25" viewBox="0 0 59 25" fill="#FFFFFF">
<path d="M4.125,15.3 L10.05,15.3 L10.05,18 L0.6,18 L0.6,0.35 L4.125,0.35 L4.125,15.3 Z M18.55,3.975 C19.9000067,3.975 21.1124946,4.2583305 22.1875,4.825 C23.2625054,5.3916695 24.1083302,6.21249462 24.725,7.2875 C25.3416697,8.36250537 25.65,9.62499275 25.65,11.075 C25.65,12.5250073 25.3416697,13.783328 24.725,14.85 C24.1083302,15.916672 23.2625054,16.7374971 22.1875,17.3125 C21.1124946,17.8875029 19.9000067,18.175 18.55,18.175 C17.1999933,18.175 15.9875054,17.8875029 14.9125,17.3125 C13.8374946,16.7374971 12.9916697,15.916672 12.375,14.85 C11.7583302,13.783328 11.45,12.5250073 11.45,11.075 C11.45,9.62499275 11.7583302,8.36250537 12.375,7.2875 C12.9916697,6.21249462 13.8374946,5.3916695 14.9125,4.825 C15.9875054,4.2583305 17.1999933,3.975 18.55,3.975 Z M18.55,7.025 C17.5666618,7.025 16.7333368,7.37082987 16.05,8.0625 C15.3666633,8.75417013 15.025,9.75832675 15.025,11.075 C15.025,12.3916733 15.3666633,13.3958299 16.05,14.0875 C16.7333368,14.7791701 17.5666618,15.125 18.55,15.125 C19.5333382,15.125 20.3666633,14.7791701 21.05,14.0875 C21.7333367,13.3958299 22.075,12.3916733 22.075,11.075 C22.075,9.75832675 21.7333367,8.75417013 21.05,8.0625 C20.3666633,7.37082987 19.5333382,7.025 18.55,7.025 Z M33.575,3.975 C34.7416725,3.975 35.7416625,4.24999725 36.575,4.8 C37.4083375,5.35000275 37.9999982,6.091662 38.35,7.025 L38.35,4.15 L41.85,4.15 L41.85,18.05 C41.85,19.3333398 41.5958359,20.4874949 41.0875,21.5125 C40.5791641,22.5375051 39.8208384,23.3416638 38.8125,23.925 C37.8041616,24.5083363 36.5833405,24.8 35.15,24.8 C33.14999,24.8 31.5333395,24.3250048 30.3,23.375 C29.0666605,22.4249953 28.316668,21.1333415 28.05,19.5 L31.525,19.5 C31.725001,20.2000035 32.1124971,20.7458314 32.6875,21.1375 C33.2625029,21.5291686 33.9999955,21.725 34.9,21.725 C35.9333385,21.725 36.7666635,21.4208364 37.4,20.8125 C38.0333365,20.2041636 38.35,19.2833395 38.35,18.05 L38.35,15.1 C37.9999982,16.033338 37.4083375,16.7791639 36.575,17.3375 C35.7416625,17.8958361 34.7416725,18.175 33.575,18.175 C32.4083275,18.175 31.358338,17.8916695 30.425,17.325 C29.491662,16.7583305 28.7625026,15.9375054 28.2375,14.8625 C27.7124974,13.7874946 27.45,12.5250073 27.45,11.075 C27.45,9.62499275 27.7124974,8.36250537 28.2375,7.2875 C28.7625026,6.21249462 29.491662,5.3916695 30.425,4.825 C31.358338,4.2583305 32.4083275,3.975 33.575,3.975 Z M34.675,7.05 C33.5749945,7.05 32.69167,7.40832975 32.025,8.125 C31.35833,8.84167025 31.025,9.82499375 31.025,11.075 C31.025,12.3250063 31.35833,13.3041631 32.025,14.0125 C32.69167,14.7208369 33.5749945,15.075 34.675,15.075 C35.741672,15.075 36.6208299,14.7125036 37.3125,13.9875 C38.0041701,13.2624964 38.35,12.2916728 38.35,11.075 C38.35,9.8416605 38.0041701,8.86250363 37.3125,8.1375 C36.6208299,7.41249637 35.741672,7.05 34.675,7.05 Z M51.45,3.975 C52.8000068,3.975 54.0124946,4.2583305 55.0875,4.825 C56.1625054,5.3916695 57.0083302,6.21249462 57.625,7.2875 C58.2416697,8.36250537 58.55,9.62499275 58.55,11.075 C58.55,12.5250073 58.2416697,13.783328 57.625,14.85 C57.0083302,15.916672 56.1625054,16.7374971 55.0875,17.3125 C54.0124946,17.8875029 52.8000068,18.175 51.45,18.175 C50.0999933,18.175 48.8875054,17.8875029 47.8125,17.3125 C46.7374946,16.7374971 45.8916698,15.916672 45.275,14.85 C44.6583303,13.783328 44.35,12.5250073 44.35,11.075 C44.35,9.62499275 44.6583303,8.36250537 45.275,7.2875 C45.8916698,6.21249462 46.7374946,5.3916695 47.8125,4.825 C48.8875054,4.2583305 50.0999933,3.975 51.45,3.975 Z M51.45,7.025 C50.4666618,7.025 49.6333367,7.37082987 48.95,8.0625 C48.2666633,8.75417013 47.925,9.75832675 47.925,11.075 C47.925,12.3916733 48.2666633,13.3958299 48.95,14.0875 C49.6333367,14.7791701 50.4666618,15.125 51.45,15.125 C52.4333383,15.125 53.2666633,14.7791701 53.95,14.0875 C54.6333367,13.3958299 54.975,12.3916733 54.975,11.075 C54.975,9.75832675 54.6333367,8.75417013 53.95,8.0625 C53.2666633,7.37082987 52.4333383,7.025 51.45,7.025 Z"/>
</svg>

Before

Width:  |  Height:  |  Size: 3.9 KiB

-90
View File
@@ -1,90 +0,0 @@
body {
font-family: 'Karla', sans-serif;
background-image: url("../images/bg.jpg");
background-size: cover;
background-repeat: no-repeat;
background-position: center;
color: #ffffff;
padding-bottom: 75px;
@media (min-width: 768px) {
padding-bottom: 110px;
}
}
.navbar-brand {
margin-right: 0;
img {
height: 21px;
}
}
.navbar-dark {
padding-top: 35px;
padding-bottom: 35px;
.navbar-text {
color: #ffffff;
opacity: 1;
padding: 0 20px;
border-right: 1px solid #ffffff;
font-size: 18px;
font-weight: bold;
text-align: center;
&:last-child {
border-right: 0;
}
}
@media (max-width: 767px) {
padding-bottom: 0;
}
}
.page-title {
font-size: 80px;
font-weight: bold;
margin-bottom: 6px;
@media (max-width: 767px) {
font-size: 35px;
margin-bottom: 14px;
}
}
.page-description {
max-width: 465px;
font-size: 18px;
margin-bottom: 59px;
@media (max-width: 767px) {
font-size: 14px;
}
}
p {
font-size: 14px;
margin-bottom: 21px;
}
.footer-social-links {
.social-link {
display: inline-block;
text-align: center;
line-height: 40px;
width: 40px;
height: 40px;
border-radius: 50%;
background-color: #ffffff;
color: #000000;
margin-right: 16px;
transition: all 0.3s ease-in-out;
&:last-child {
margin-right: 0;
}
&:hover {
text-decoration: none;
background-color: #000000;
color: #ffffff;
}
}
}
-39
View File
@@ -1,39 +0,0 @@
//Import
const gulp = require('gulp');
const sass = require('gulp-sass');
const sourceMaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync');
//SCSS
function style() {
return gulp.src('./assets/scss/*.scss')
.pipe(sourceMaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer())
.pipe(sourceMaps.write('./'))
.pipe(gulp.dest('./assets/css'))
.pipe(browserSync.stream());
}
//Serve and watch
function watch() {
browserSync.init({
server: {
baseDir: './',
},
startPath: './index.html',
ghostMode: false,
notify: false
});
gulp.watch('./assets/scss/*.scss', style);
gulp.watch('./*.html').on('change', browserSync.reload);
gulp.watch('./assets/js/*.js').on('change', browserSync.reload);
}
exports.style = style;
exports.watch = watch;
-45
View File
@@ -1,45 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>NipoVPN documentation</title>
<link href="https://fonts.googleapis.com/css?family=Karla:400,700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.materialdesignicons.com/4.8.95/css/materialdesignicons.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/bd-coming-soon.css">
</head>
<body class="min-vh-100 d-flex flex-column">
<header>
<div class="container">
<nav class="navbar navbar-dark bg-transparenet">
<a class="navbar-brand" href="#">
<img src="assets/images/logo.svg" alt="logo">
</a>
<span class="navbar-text ml-auto d-none d-sm-inline-block">Email</span>
<span class="navbar-text d-none d-sm-inline-block">morteza.bashsiz@gmail.com</span>
</nav>
</div>
</header>
<main class="my-auto">
<div class="container">
<h1 class="page-title">We're coming soon</h1>
<p class="page-description">We are working hard to make it possible
</p>
<p>Stay connected</p>
<!-- <nav class="footer-social-links">
<a href="#!" class="social-link"><i class="mdi mdi-facebook-box"></i></a>
<a href="#!" class="social-link"><i class="mdi mdi-twitter"></i></a>
<a href="#!" class="social-link"><i class="mdi mdi-google"></i></a>
<a href="#!" class="social-link"><i class="mdi mdi-slack"></i></a>
<a href="#!" class="social-link"><i class="mdi mdi-skype"></i></a>
</nav> -->
</div>
</main>
</body>
</html>
-4995
View File
File diff suppressed because it is too large. Load diff
-19
View File
@@ -1,19 +0,0 @@
{
"name": "bd-wizard-free-1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"browser-sync": "^3.0.2",
"gulp": "^5.0.0",
"gulp-autoprefixer": "^7.0.1",
"gulp-sass": "^5.1.0",
"gulp-sourcemaps": "^2.6.5",
"node-sass": "^9.0.0"
}
}
Generated
+61
View File
@@ -0,0 +1,61 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1780243769,
"narHash": "sha256-x5UQuRsH3MqI0U9afaXSNqzTPSeZlRLvFAav2Ux1pNw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "331800de5053fcebacf6813adb5db9c9dca22a0c",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
+72
View File
@@ -0,0 +1,72 @@
{
description = "NipoVPN - Powerful HTTP proxy";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
};
outputs = {
self,
nixpkgs,
flake-utils,
}:
flake-utils.lib.eachSystem ["x86_64-linux" "aarch64-linux"] (system: let
pkgs = nixpkgs.legacyPackages.${system};
nipovpn = pkgs.stdenv.mkDerivation {
pname = "nipovpn";
version = "1.1.57";
src = self;
nativeBuildInputs = with pkgs; [cmake];
buildInputs = with pkgs; [boost yaml-cpp openssl];
cmakeFlags = ["-DCMAKE_BUILD_TYPE=Release"];
installPhase = ''
runHook preInstall
mkdir -p $out/bin $out/etc/nipovpn
cp core/nipovpn $out/bin/nipovpn
cp -r $src/nipovpn/etc/nipovpn/. $out/etc/nipovpn/
runHook postInstall
'';
meta = with pkgs.lib; {
description = "Powerful HTTP proxy with traffic obfuscation";
homepage = "https://github.com/MortezaBashsiz/nipovpn";
license = licenses.gpl3Plus;
platforms = platforms.linux;
mainProgram = "nipovpn";
};
};
in {
packages.default = nipovpn;
packages.nipovpn = nipovpn;
devShells.default = pkgs.mkShell {
buildInputs = with pkgs; [
cmake
ninja
boost
yaml-cpp
openssl
clang-tools
gdb
valgrind
];
shellHook = ''
echo "NipoVPN dev environment ready"
echo ""
echo "You can build using either Make or Ninja:"
echo " Standard (Make):"
echo " cmake -B build -DCMAKE_BUILD_TYPE=Debug"
echo " cmake --build build -j\$(nproc)"
echo ""
echo " Fast (Ninja):"
echo " cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug"
echo " cmake --build build -j\$(nproc)"
'';
};
});
}
+348
View File
@@ -0,0 +1,348 @@
# NipoVPN Docker
This directory contains Docker files for building and running **NipoVPN** in either `server` or `agent` mode.
## Directory Structure
```text
nipovpn/
├── docker/
│ ├── Dockerfile
│ ├── docker-compose.yml
│ └── README.md
├── nipovpn/
│ └── etc/nipovpn/config.yaml
├── core/
├── CMakeLists.txt
└── .dockerignore
```
## Requirements
Install Docker and Docker Compose:
```bash
docker --version
docker compose version
```
For older systems:
```bash
docker-compose --version
```
## Important: `.dockerignore`
Create `.dockerignore` in the repository root:
```text
.git
.github
build
cmake-build-*
*.deb
*.tar.gz
*.log
```
This prevents local build files from being copied into the Docker image.
## Docker Compose File
The compose file is located at:
```bash
docker/docker-compose.yml
```
Example:
```yaml
services:
nipovpn:
container_name: nipovpn
build:
context: ..
dockerfile: docker/Dockerfile
image: nipovpn:latest
restart: unless-stopped
ports:
- "443:443"
- "8080:8080"
volumes:
- ../nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro
- nipovpn_logs:/var/log/nipovpn
command:
- ${NIPOVPN_MODE:-server}
- /etc/nipovpn/config.yaml
volumes:
nipovpn_logs:
```
## Build Image
From the `docker` directory:
```bash
cd docker
docker compose build
```
Or with old Docker Compose:
```bash
cd docker
docker-compose build
```
To rebuild without cache:
```bash
docker compose build --no-cache
```
## Run in Server Mode
Using environment variable:
```bash
cd docker
NIPOVPN_MODE=server docker compose up -d
```
Or create `docker/.env`:
```env
NIPOVPN_MODE=server
```
Then run:
```bash
docker compose up -d
```
The container will run:
```bash
nipovpn server /etc/nipovpn/config.yaml
```
## Run in Agent Mode
Using environment variable:
```bash
cd docker
NIPOVPN_MODE=agent docker compose up -d
```
Or create `docker/.env`:
```env
NIPOVPN_MODE=agent
```
Then run:
```bash
docker compose up -d
```
The container will run:
```bash
nipovpn agent /etc/nipovpn/config.yaml
```
## Specify Config File
By default, this file is mounted into the container:
```bash
../nipovpn/etc/nipovpn/config.yaml
```
Inside the container it becomes:
```bash
/etc/nipovpn/config.yaml
```
To use another config file, change this line in `docker-compose.yml`:
```yaml
volumes:
- ../nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro
```
Example:
```yaml
volumes:
- ./server-config.yaml:/etc/nipovpn/config.yaml:ro
```
Then run:
```bash
docker compose up -d
```
## View Logs
Show live container logs:
```bash
docker compose logs -f
```
Show logs only for NipoVPN service:
```bash
docker compose logs -f nipovpn
```
Read the log file inside the container volume:
```bash
docker exec -it nipovpn cat /var/log/nipovpn/nipovpn.log
```
Follow the log file:
```bash
docker exec -it nipovpn tail -f /var/log/nipovpn/nipovpn.log
```
## Stop Container
```bash
docker compose down
```
## Restart Container
```bash
docker compose restart
```
## Rebuild and Restart
```bash
docker compose down
docker compose build --no-cache
docker compose up -d
```
## Check Container Status
```bash
docker ps
```
Or:
```bash
docker compose ps
```
## Execute Shell Inside Container
```bash
docker exec -it nipovpn bash
```
## Run Manually Without Compose
Build image from repository root:
```bash
docker build -f docker/Dockerfile -t nipovpn:latest .
```
Run server mode:
```bash
docker run --rm \
--name nipovpn \
-p 443:443 \
-p 8080:8080 \
-v ./nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro \
nipovpn:latest server /etc/nipovpn/config.yaml
```
Run agent mode:
```bash
docker run --rm \
--name nipovpn \
-p 8080:8080 \
-v ./nipovpn/etc/nipovpn/config.yaml:/etc/nipovpn/config.yaml:ro \
nipovpn:latest agent /etc/nipovpn/config.yaml
```
## Common Problems
### CMakeCache path error
If you see an error like:
```text
CMakeCache.txt directory is different
```
your local `build/` directory was copied into Docker.
Fix:
```bash
rm -rf build
docker compose build --no-cache
```
Also make sure `.dockerignore` exists in the repository root.
### Port already in use
If port `443` or `8080` is already used, change the port mapping:
```yaml
ports:
- "8443:443"
- "8081:8080"
```
### Config changes are not applied
Restart the container:
```bash
docker compose restart
```
## Recommended Commands
Server:
```bash
cd docker
NIPOVPN_MODE=server docker compose up -d --build
docker compose logs -f
```
Agent:
```bash
cd docker
NIPOVPN_MODE=agent docker compose up -d --build
docker compose logs -f
```
+18
View File
@@ -0,0 +1,18 @@
## Install on Termux
### Requirements
libyaml-cpp >= 0.8
boost >= 1.88.0
### Dependencies
Install the dependencies
```bash
pkg install boost libyaml-cpp
```
### Install
Download the nipovpn_VERSION_termux_aarch64 version from releases pages
```bash
pkg install ./nipovpn_VERSION_termux_aarch64.deb
```
+84
View File
@@ -0,0 +1,84 @@
## Nix Guide
**Note:** Nix Flakes are an experimental feature and must be enabled before using any of the commands in this guide.
### Enable Flakes
* **NixOS:** Follow the instructions in the NixOS & Flakes Book:
[Enabling NixOS with Flakes](https://nixos-and-flakes.thiscute.world/nixos-with-flakes/nixos-with-flakes-enabled?utm_source=chatgpt.com#enable-nix-flakes)
* **Non-NixOS systems:** Add the following to `~/.config/nix/nix.conf` (or `/etc/nix/nix.conf`):
```bash
experimental-features = nix-command flakes
```
## Installation
### Install into your Nix profile
```bash
nix profile install github:MortezaBashsiz/nipovpn
```
### NixOS (system-wide installation)
Add the flake as an input in your system `flake.nix`:
```nix
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
nipovpn.url = "github:MortezaBashsiz/nipovpn";
};
outputs = { self, nixpkgs, nipovpn, ... }: {
nixosConfigurations.yourhostname = nixpkgs.lib.nixosSystem {
system = "x86_64-linux"; # or "aarch64-linux"
modules = [
./configuration.nix
{
environment.systemPackages = [
nipovpn.packages.${pkgs.system}.default
];
}
];
};
};
}
```
## Building
### Manual Build (without Nix)
For traditional builds on Linux, please refer to [`BuildLinux.md`](./BuildLinux.md).
### Build with Nix
From the repository root:
```bash
nix build
```
Or directly from GitHub without cloning:
```bash
nix build github:MortezaBashsiz/nipovpn
```
## Development
Enter the development shell with all dependencies pre-configured:
```bash
git clone https://github.com/MortezaBashsiz/nipovpn.git
cd nipovpn
nix develop
```
If the command completes successfully, the development environment is ready to use.
+1
View File
@@ -0,0 +1 @@
/etc/nipovpn/config.yaml
+7 -7
View File
@@ -1,7 +1,7 @@
Package : nipovpn
Version : 0.1
Maintainer : Morteza Bashsiz
Architecture : amd64
Description : Powerfull and Secure http/s Proxy
Depends : libyaml-cpp0.8
Homepage : https://github.com/MortezaBashsiz/nipovpn
Package: nipovpn
Version: 0.0.0
Maintainer: Morteza Bashsiz
Architecture: amd64
Depends: libyaml-cpp0.8
Homepage: https://github.com/MortezaBashsiz/nipovpn
Description: Powerful and secure proxy
+92 -25
View File
@@ -1,28 +1,29 @@
---
# This block contains general and global configuration which is in both modes
# This block holds settings both the agent and the server use.
# aesEnable, tunnelEnable and tlsEnable must be the same on both.
general:
# token: 32 bytes of string. this will be used on agent and server side to encryption
token: "af445adb-2434-4975-9445-2c1b2231"
# fakeUrl: string
# Defines the fake url and endpoint between agent and server
fakeUrl: "http://www.adas.com"
# method: "HEAD|GET|POST|PUT|DELETE"
# Defines with which method
# you like to send requests from agent to server
method: "POST"
# aesEnable: bool (default: true)
# Enables AES-256-GCM payload encryption (confidentiality and integrity). Must match on the agent and server.
# When false, requests are signed (HMAC-SHA256) instead, so users still work,
# but traffic is readable on the path unless tlsEnable is true.
# Independent of tlsEnable; request encoding remains enabled.
aesEnable: false
# timeout: unsigned short
# Defines the timeout for I/O Operation in seconds. 0 indicates no timeout.
# Useful to automatically close stalled connections.
timeout: 10
# chunkHeader: String
# Defines the chunk header that you want to inform Agent/Server if it is end or not.
chunkHeader: "END"
# tunnelEnable: bool
# Defines the connection mode between agent and server. If enabled then the traffic
# will be TCP/TLS tunnel like.
tunnelEnable: true
# tlsEnable: bool
# It enables or disables tls between agent and server
tlsEnable: true
# This block is to define log directives
log:
# logLevel: "INFO|TRACE|DEBUG"
logLevel: "DEBUG"
logLevel: "INFO"
# logFile: "/var/log/nipo/nipo.log"
# Path of log file
logFile: "/var/log/nipovpn/nipovpn.log"
@@ -30,33 +31,99 @@ log:
# This block is to define server directives
server:
# threads: number of threads in server
threads: 8
threads: 2
# listenIp: which must be IPv4 which is used on server
listenIp: "0.0.0.0"
# listenPort: the port number which will be used on server
listenPort: 443
tlsEnable: true
tlsVerifyPeer: false
# bufferSize: maximum bytes read from a destination at a time in polling mode,
# 1-65536 (default: 65536)
bufferSize: 65536
# tlsCertFile, tlsKeyFile: the server's certificate (PEM, chain allowed) and
# private key, used when tlsEnable is true
tlsCertFile: "/etc/nipovpn/server.crt"
tlsKeyFile: "/etc/nipovpn/server.key"
tlsCaFile: ""
# usage: optional per-user usage tracking.
# Usage (bytes each user sends and receives) is kept in the usage file, which
# you can also edit to change or reset a user's usage (e.g. set "used" to 0).
usage:
# file: where usage is kept (default: /var/lib/nipovpn/usage.yaml)
file: "/var/lib/nipovpn/usage.yaml"
# resetDay: day of the month (1-28) on which everyone's usage resets (default: 1)
resetDay: 1
# users: the users allowed to connect.
# Each user has their own token, and that user's agent puts the same token in
# agent.token. Add, disable or remove users without a
# restart: edit this file and run `systemctl reload nipovpn-server`.
users:
- name: adas
# token: at least 32 bytes, unique per user, e.g. `openssl rand -hex 16`
token: "b354d990-1d1e-4956-94dd-75adfc692668"
# enabled: bool (default: true). false rejects the user and, on reload,
# closes their open connections.
# limit: optional traffic allowance per month (upload + download), e.g. 2GB,
# 500MB or 1.5GiB. When reached, the user is blocked until the next period.
enabled: true
- name: nokhod
token: "4bc22ec2-b29b-4279-acc2-bfa1702e8dec"
enabled: true
limit: 1GB
# This block is to define agent directives
agent:
# threads: number of threads in agent
threads: 8
threads: 16
# listenIp: which must be IPv4 which is used on agent
listenIp: "0.0.0.0"
# listenPort: the port number which will be used on agent
listenPort: 8080
# protocol: the protocol local applications use to connect to the agent
# Choose http or socks5
protocol: socks5
# fakeUrls: hosts used at random for the Host header and TLS SNI of
# the requests the agent sends to the server
fakeUrls:
- nipo.sudoer.net
- sudoer.ir
- sudoer.net
- google.com
- cloudflare.com
# methods: HTTP methods used at random for those requests
methods:
- GET
- POST
- PUT
- DELETE
# endPoints: URL paths used at random for those requests
endPoints:
- api
- login
- user
- update
# pullTimeout: base interval in milliseconds between polls in polling mode
pullTimeout: 1
# connectionReuse: bool
# true: send requests to the server over one kept-alive connection
# false: open a new connection to the server for each request
# The server follows the agent's choice.
connectionReuse: true
# tlsVerifyPeer: bool. Verify the server's certificate when tlsEnable is true
tlsVerifyPeer: false
# tlsCaFile: CA file used to verify the server's certificate
tlsCaFile: ""
# serverIp: IPv4 of the nipoServer
serverIp: "127.0.0.10"
serverIp: "127.0.0.1"
# serverPort: port number of the nipoServer
serverPort: 443
# httpVersion: This version will be used between agent and server
# Supported values are 1.0 or 1.1
httpVersion: "1.1"
# userAgent: This is the http user agent which will be used between agent and server
userAgent : "NipoAgent"
tlsEnable: true
tlsVerifyPeer: false
tlsCaFile: ""
userAgent : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0"
# token: the token this agent sends; it must be the token of an enabled user
# in the server's users list. At least 32 bytes. The AES-256-GCM key is derived from it.
# Generate one with `openssl rand -hex 16`
token: "4bc22ec2-b29b-4279-acc2-bfa1702e8dec"
@@ -8,7 +8,7 @@ ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
Type=simple
LimitNOFILE=1048576
[Install]
WantedBy=multi-user.target
Alias=sshd.service
@@ -8,7 +8,7 @@ ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
Type=simple
LimitNOFILE=1048576
[Install]
WantedBy=multi-user.target
Alias=sshd.service
View File
Whitespace-only changes.
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
import argparse
import base64
import json
import sys
try:
import yaml
except ImportError:
sys.exit("PyYAML is required: pip install pyyaml (or install python-yaml)")
DEFAULT_CONFIG = "/etc/nipovpn/config.yaml"
def to_str(value):
return "" if value is None else str(value)
def to_lines(value):
if isinstance(value, (list, tuple)):
return "\n".join(str(v) for v in value)
return to_str(value)
def build_payload(cfg, name=None, server_ip=None):
general = cfg.get("general", {}) or {}
log = cfg.get("log", {}) or {}
agent = cfg.get("agent", {}) or {}
server = cfg.get("server", {}) or {}
def moved(block, key, default=None):
# Settings used by one side moved out of general; general is the deprecated location.
return block.get(key, general.get(key, default))
server_ip = server_ip or to_str(agent.get("serverIp"))
config = {
# agent.token; general.token is the deprecated location.
"token": to_str(agent.get("token") or general.get("token")),
"protocol": to_str(moved(agent, "protocol")),
"fakeUrls": to_lines(moved(agent, "fakeUrls")),
"methods": to_lines(moved(agent, "methods")),
"endPoints": to_lines(moved(agent, "endPoints")),
"timeout": to_str(general.get("timeout")),
"pullTimeout": to_str(moved(agent, "pullTimeout")),
"tunnelEnable": bool(general.get("tunnelEnable", False)),
"connectionReuse": bool(moved(agent, "connectionReuse", False)),
"tlsEnable": bool(general.get("tlsEnable", False)),
"tlsVerifyPeer": bool(moved(agent, "tlsVerifyPeer", False)),
"tlsCertFile": to_str(moved(server, "tlsCertFile")),
"tlsKeyFile": to_str(moved(server, "tlsKeyFile")),
"tlsCaFile": to_str(moved(agent, "tlsCaFile")),
"logLevel": to_str(log.get("logLevel")),
"listenIp": to_str(agent.get("listenIp")),
"listenPort": to_str(agent.get("listenPort")),
"serverIp": server_ip,
"serverPort": to_str(agent.get("serverPort")),
"httpVersion": to_str(agent.get("httpVersion")),
"userAgent": to_str(agent.get("userAgent")),
}
return {"name": name or server_ip, "config": config}
def encode(payload):
text = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
text = text.replace("/", "\\/")
return "nipovpn://" + base64.b64encode(text.encode("utf-8")).decode("ascii")
def decode(url):
data = url.strip()
if data.startswith("nipovpn://"):
data = data[len("nipovpn://"):]
data += "=" * (-len(data) % 4)
return json.loads(base64.b64decode(data).decode("utf-8"))
def main():
parser = argparse.ArgumentParser(description="Convert nipovpn config.yaml to a nipovpn:// URL")
parser.add_argument("config", nargs="?", default=DEFAULT_CONFIG,
help=f"path to config.yaml (default: {DEFAULT_CONFIG})")
parser.add_argument("--name", help="profile name (default: serverIp)")
parser.add_argument("--server-ip", help="override agent.serverIp (e.g. the public IP of the server)")
parser.add_argument("--decode", metavar="URL", help="decode a nipovpn:// URL and print its JSON")
args = parser.parse_args()
if args.decode:
print(json.dumps(decode(args.decode), indent=2, ensure_ascii=False))
return
try:
with open(args.config, "r", encoding="utf-8") as f:
cfg = yaml.safe_load(f) or {}
except OSError as e:
sys.exit(f"Cannot read {args.config}: {e}")
print(encode(build_payload(cfg, args.name, args.server_ip)))
if __name__ == "__main__":
main()
Executable
+866
View File
@@ -0,0 +1,866 @@
#!/usr/bin/env python3
"""End-to-end tests for NipoVPN.
Starts a real server and agent on localhost for each test, sends traffic
through them with curl and checks that every byte arrives intact.
python3 tests/e2e.py --binary build/core/nipovpn
python3 tests/e2e.py --binary build/core/nipovpn -k matrix # only matching tests
python3 tests/e2e.py --binary build/core/nipovpn --list
Needs: python3 with PyYAML, curl and openssl.
"""
import argparse
import copy
import hashlib
import http.server
import itertools
import os
import re
import secrets
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
import traceback
from urllib.parse import urlsplit
try:
import yaml
except ImportError:
sys.exit("PyYAML is required: pip install pyyaml (or apt install python3-yaml)")
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SAMPLE_CONFIG = os.path.join(ROOT, "nipovpn", "etc", "nipovpn", "config.yaml")
CRASH_MARKERS = (
"terminate called",
"Segmentation fault",
"Aborted",
"AddressSanitizer",
"runtime error:",
)
class TestFailure(Exception):
pass
def check(condition, message):
if not condition:
raise TestFailure(message)
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def sha256(data):
return hashlib.sha256(data).hexdigest()
def new_token():
return secrets.token_hex(20)
# ---------------------------------------------------------------- origin server
class Origin:
"""Local web server the traffic is sent to.
GET /<name> returns a fixed random blob, GET /slow streams the big blob
over about 3 seconds, and POST /upload returns the SHA-256
of the request body. Accepts absolute-form request targets
(GET http://host/path), which an HTTP proxy forwards unchanged.
"""
SIZES = {"small": 64 * 1024, "mid": 512 * 1024, "big": 2 * 1024 * 1024}
def __init__(self):
self.blobs = {name: os.urandom(size) for name, size in self.SIZES.items()}
blobs = self.blobs
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def _send(self, status, body):
self.send_response(status)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
name = urlsplit(self.path).path.strip("/")
if name == "slow":
body = blobs["big"]
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
try:
for i in range(0, len(body), 64 * 1024):
self.wfile.write(body[i:i + 64 * 1024])
self.wfile.flush()
time.sleep(0.1)
except OSError:
pass
elif name in blobs:
self._send(200, blobs[name])
else:
self._send(404, b"not found")
def do_POST(self):
length = int(self.headers.get("Content-Length", "0"))
body = self.rfile.read(length)
self._send(200, sha256(body).encode())
self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.server.daemon_threads = True
self.port = self.server.server_address[1]
threading.Thread(target=self.server.serve_forever, daemon=True).start()
def url(self, name):
return f"http://127.0.0.1:{self.port}/{name}"
def close(self):
self.server.shutdown()
self.server.server_close()
# ---------------------------------------------------------------- processes
class Node:
"""One nipovpn process (server or agent)."""
def __init__(self, env, mode, config, name):
self.env = env
self.mode = mode
self.name = name
self.config = config
self.config_path = os.path.join(env.dir, f"{name}.yaml")
self.log_path = config["log"]["logFile"]
self.out_path = os.path.join(env.dir, f"{name}.out")
self.proc = None
self.write_config(config)
def write_config(self, config):
self.config = config
tmp = self.config_path + ".tmp"
with open(tmp, "w") as f:
yaml.safe_dump(config, f, sort_keys=False)
os.replace(tmp, self.config_path)
@property
def port(self):
return self.config[self.mode]["listenPort"]
def start(self):
open(self.log_path, "a").close()
self.out = open(self.out_path, "w")
self.proc = subprocess.Popen(
[self.env.binary, self.mode, self.config_path],
stdout=self.out,
stderr=subprocess.STDOUT,
start_new_session=True,
)
self.env.nodes.append(self)
deadline = time.time() + 15
while time.time() < deadline:
if self.proc.poll() is not None:
raise TestFailure(f"{self.name} exited at startup:\n{self.output()}")
try:
with socket.create_connection(("127.0.0.1", self.port), timeout=0.5):
return self
except OSError:
time.sleep(0.05)
raise TestFailure(f"{self.name} did not start listening on port {self.port}")
def alive(self):
return self.proc is not None and self.proc.poll() is None
def send_signal(self, sig):
self.proc.send_signal(sig)
def stop(self):
if self.proc is None:
return
if self.alive():
self.proc.send_signal(signal.SIGTERM)
try:
self.proc.wait(timeout=10)
except subprocess.TimeoutExpired:
self.proc.kill()
self.proc.wait()
self.out.close()
def output(self):
try:
with open(self.out_path, errors="replace") as f:
return f.read()
except OSError:
return ""
def log(self):
try:
with open(self.log_path, errors="replace") as f:
return f.read()
except OSError:
return ""
def wait_for_log(self, pattern, count=1, timeout=15):
regex = re.compile(pattern)
deadline = time.time() + timeout
while time.time() < deadline:
if len(regex.findall(self.log())) >= count:
return
time.sleep(0.1)
raise TestFailure(f"{self.name} log never showed /{pattern}/ (x{count})")
def crash_report(self):
text = self.output()
for marker in CRASH_MARKERS:
if marker in text:
start = max(0, text.find("ERROR:") if "ERROR:" in text else text.find(marker))
return f"{self.name} crashed ({marker}):\n{text[start:start + 6000]}"
if self.proc is not None and self.proc.returncode not in (None, 0, -signal.SIGTERM):
return f"{self.name} exited with code {self.proc.returncode}:\n{text[-2000:]}"
return None
class Env:
"""Per-test working directory, configs and processes."""
def __init__(self, runner, name):
self.binary = runner.binary
self.origin = runner.origin
self.cert, self.key = runner.cert, runner.key
self.dir = tempfile.mkdtemp(prefix=re.sub(r"[^A-Za-z0-9]+", "_", name)[:60] + "_",
dir=runner.workdir)
self.nodes = []
with open(SAMPLE_CONFIG) as f:
self.sample = yaml.safe_load(f)
# -- configs
def base(self, tls=True, tunnel=False, aes=True, reuse=True, protocol="socks5",
users=None, agent_token=None):
"""A config derived from the shipped sample config."""
cfg = copy.deepcopy(self.sample)
server_port, agent_port = free_port(), free_port()
if users is None:
users = [{"name": "alice", "token": new_token(), "enabled": True}]
cfg["general"].update(aesEnable=aes, tunnelEnable=tunnel, tlsEnable=tls, timeout=10)
cfg["log"]["logLevel"] = "INFO"
cfg["server"].update(
threads=4,
listenIp="127.0.0.1",
listenPort=server_port,
tlsCertFile=self.cert,
tlsKeyFile=self.key,
usage={"file": os.path.join(self.dir, "usage.yaml"), "resetDay": 1},
users=users,
)
cfg["agent"].update(
threads=8,
listenIp="127.0.0.1",
listenPort=agent_port,
serverIp="127.0.0.1",
serverPort=server_port,
protocol=protocol,
connectionReuse=reuse,
tlsVerifyPeer=False,
tlsCaFile="",
token=agent_token or users[0]["token"],
)
return cfg
def server(self, cfg, name="server"):
cfg = copy.deepcopy(cfg)
cfg["log"]["logFile"] = os.path.join(self.dir, f"{name}.log")
return Node(self, "server", cfg, name).start()
def agent(self, cfg, name="agent", token=None):
cfg = copy.deepcopy(cfg)
cfg["log"]["logFile"] = os.path.join(self.dir, f"{name}.log")
cfg["agent"]["listenPort"] = free_port()
if token:
cfg["agent"]["token"] = token
return Node(self, "agent", cfg, name).start()
# -- traffic
def curl(self, agent, url, protocol=None, connect=True, data_file=None, timeout=60):
protocol = protocol or agent.config["agent"].get("protocol") or agent.config["general"]["protocol"]
cmd = ["curl", "-sS", "--fail", "--max-time", str(timeout), "-o", "-"]
if protocol == "socks5":
cmd += ["--socks5-hostname", f"127.0.0.1:{agent.port}"]
else:
cmd += ["-x", f"http://127.0.0.1:{agent.port}"]
if connect:
cmd.append("-p")
if data_file:
cmd += ["--data-binary", "@" + data_file, "-H", "Content-Type: application/octet-stream"]
cmd.append(url)
result = subprocess.run(cmd, capture_output=True, timeout=timeout + 10)
return result.returncode, result.stdout, result.stderr.decode(errors="replace").strip()
@staticmethod
def how(agent, kw):
protocol = kw.get("protocol") or agent.config["agent"].get("protocol") or agent.config["general"]["protocol"]
if protocol == "socks5":
return "over SOCKS5"
return "over HTTP CONNECT" if kw.get("connect", True) else "as a plain HTTP proxy request"
def download_ok(self, agent, name="big", **kw):
rc, body, err = self.curl(agent, self.origin.url(name), **kw)
what = f"download of /{name} {self.how(agent, kw)}"
check(rc == 0, f"{what} failed (curl exit {rc}: {err})")
check(sha256(body) == sha256(self.origin.blobs[name]),
f"{what} corrupted: got {len(body)} bytes, "
f"expected {len(self.origin.blobs[name])}")
def download_fails(self, agent, name="small", **kw):
rc, body, _ = self.curl(agent, self.origin.url(name), timeout=15, **kw)
check(rc != 0 or sha256(body) != sha256(self.origin.blobs[name]),
f"download of /{name} succeeded but should have been refused")
def upload_ok(self, agent, size=1024 * 1024, **kw):
data = os.urandom(size)
path = os.path.join(self.dir, f"upload_{secrets.token_hex(4)}.bin")
with open(path, "wb") as f:
f.write(data)
rc, body, err = self.curl(agent, self.origin.url("upload"), data_file=path, **kw)
what = f"upload of {size} bytes {self.how(agent, kw)}"
check(rc == 0, f"{what} failed (curl exit {rc}: {err})")
check(body.decode(errors="replace") == sha256(data), f"{what} corrupted on the way")
def parallel_downloads_ok(self, agent, count=4, name="mid", **kw):
errors = []
def one():
try:
self.download_ok(agent, name, **kw)
except Exception as e:
errors.append(str(e))
threads = [threading.Thread(target=one) for _ in range(count)]
for t in threads:
t.start()
for t in threads:
t.join()
check(not errors, f"{len(errors)} of {count} parallel downloads failed: {errors[0] if errors else ''}")
def usage(self):
path = os.path.join(self.dir, "usage.yaml")
check(os.path.exists(path), "usage file was not written")
with open(path) as f:
doc = yaml.safe_load(f) or {}
return {name: entry.get("used", 0) for name, entry in (doc.get("users") or {}).items()}
# -- teardown
def close(self):
crashes = []
for node in reversed(self.nodes):
node.stop()
report = node.crash_report()
if report:
crashes.append(report)
return crashes
# ---------------------------------------------------------------- tests
TESTS = []
def test(name):
def register(fn):
TESTS.append((name, fn))
return fn
return register
def onoff(value):
return "on" if value else "off"
def make_matrix_test(tls, tunnel, reuse, aes, protocol):
def run(env):
cfg = env.base(tls=tls, tunnel=tunnel, reuse=reuse, aes=aes, protocol=protocol)
env.server(cfg)
agent = env.agent(cfg)
if protocol == "socks5":
env.download_ok(agent, "big")
env.download_ok(agent, "small")
env.upload_ok(agent)
env.parallel_downloads_ok(agent)
else:
env.download_ok(agent, "big", connect=True)
env.download_ok(agent, "small", connect=True)
env.upload_ok(agent, connect=True)
env.parallel_downloads_ok(agent, connect=True)
return run
for _tls, _tunnel, _reuse, _aes, _protocol in itertools.product(
(True, False), (False, True), (True, False), (True, False), ("socks5", "http")):
TESTS.append((
f"matrix tls={onoff(_tls)} tunnel={onoff(_tunnel)} reuse={onoff(_reuse)} "
f"aes={onoff(_aes)} protocol={_protocol}",
make_matrix_test(_tls, _tunnel, _reuse, _aes, _protocol),
))
KNOWN_BUG_PLAIN_HTTP = (
"the server returns only its first read (up to 16 KB) from the destination as the "
"response to a plain HTTP proxy request; also in 1.1.60")
for _tunnel, _tls in itertools.product((False, True), (True, False)):
def _plain_http_test(env, tunnel=_tunnel, tls=_tls):
cfg = env.base(tls=tls, tunnel=tunnel, protocol="http")
env.server(cfg)
agent = env.agent(cfg)
env.download_ok(agent, "small", connect=False)
env.download_ok(agent, "big", connect=False)
env.upload_ok(agent, connect=False)
_plain_http_test.known_bug = KNOWN_BUG_PLAIN_HTTP
TESTS.append((f"plain HTTP proxy request tls={onoff(_tls)} tunnel={onoff(_tunnel)}",
_plain_http_test))
@test("http version 1.0 between agent and server")
def _(env):
for tunnel in (False, True):
cfg = env.base(tunnel=tunnel)
cfg["agent"]["httpVersion"] = "1.0"
env.server(cfg, name=f"server_{tunnel}")
agent = env.agent(cfg, name=f"agent_{tunnel}")
env.download_ok(agent)
env.upload_ok(agent)
def two_users(env, **kw):
users = [
{"name": "alice", "token": new_token(), "enabled": True},
{"name": "bob", "token": new_token(), "enabled": True},
]
return env.base(users=users, **kw), users
for _aes, _tunnel in itertools.product((True, False), (False, True)):
def _users_test(env, aes=_aes, tunnel=_tunnel):
cfg, users = two_users(env, aes=aes, tunnel=tunnel)
server = env.server(cfg)
alice = env.agent(cfg, name="agent_alice", token=users[0]["token"])
bob = env.agent(cfg, name="agent_bob", token=users[1]["token"])
errors = []
def traffic(agent, name):
try:
env.download_ok(agent, name)
except Exception as e:
errors.append(str(e))
threads = [threading.Thread(target=traffic, args=(bob, "big")),
threading.Thread(target=traffic, args=(bob, "mid")),
threading.Thread(target=traffic, args=(alice, "small"))]
for t in threads:
t.start()
for t in threads:
t.join()
check(not errors, f"traffic of two users at once failed: {errors}")
server.stop()
log = server.log()
check("[USER alice]" in log and "[USER bob]" in log,
"server log does not name both users")
used = env.usage()
big = len(env.origin.blobs["big"]) + len(env.origin.blobs["mid"])
check(used.get("bob", 0) >= big, f"bob's usage {used.get('bob')} < {big} bytes downloaded")
check(0 < used.get("alice", 0) < big,
f"alice's usage {used.get('alice')} does not match her small download")
TESTS.append((f"users identified and counted aes={onoff(_aes)} tunnel={onoff(_tunnel)}",
_users_test))
for _aes in (True, False):
def _unknown_test(env, aes=_aes):
cfg = env.base(aes=aes)
server = env.server(cfg)
stranger = env.agent(cfg, name="agent_unknown", token=new_token())
env.download_fails(stranger)
check(server.alive(), "server died after an unknown token")
good = env.agent(cfg, name="agent_alice")
env.download_ok(good, "small")
TESTS.append((f"unknown token refused aes={onoff(_aes)}", _unknown_test))
@test("disabled user refused")
def _(env):
cfg, users = two_users(env)
users[1]["enabled"] = False
env.server(cfg)
env.download_fails(env.agent(cfg, name="agent_bob", token=users[1]["token"]))
env.download_ok(env.agent(cfg, name="agent_alice", token=users[0]["token"]), "small")
@test("reload disables and re-enables a user")
def _(env):
cfg, users = two_users(env)
server = env.server(cfg)
bob = env.agent(cfg, name="agent_bob", token=users[1]["token"])
alice = env.agent(cfg, name="agent_alice", token=users[0]["token"])
env.download_ok(bob, "small")
users[1]["enabled"] = False
server.write_config(server.config | {"server": cfg["server"]})
server.send_signal(signal.SIGHUP)
server.wait_for_log(r"config reloaded.*access revoked for: bob")
env.download_fails(bob)
env.download_ok(alice, "small")
users[1]["enabled"] = True
server.write_config(server.config | {"server": cfg["server"]})
server.send_signal(signal.SIGHUP)
server.wait_for_log(r"config reloaded", count=2)
env.download_ok(bob, "small")
@test("reload revokes a user in the middle of a download")
def _(env):
for tunnel in (False, True):
cfg, users = two_users(env, tunnel=tunnel)
server = env.server(cfg, name=f"server_{tunnel}")
bob = env.agent(cfg, name=f"agent_bob_{tunnel}", token=users[1]["token"])
result = {}
def slow_download():
result["rc"], result["body"], _ = env.curl(bob, env.origin.url("slow"), timeout=60)
t = threading.Thread(target=slow_download)
t.start()
time.sleep(0.8)
users[1]["enabled"] = False
server.write_config(server.config | {"server": cfg["server"]})
server.send_signal(signal.SIGHUP)
server.wait_for_log(r"access revoked for: bob")
t.join()
check(result.get("rc") != 0 or len(result.get("body", b"")) < len(env.origin.blobs["big"]),
f"tunnel={onoff(tunnel)}: the download continued after bob was revoked")
env.download_fails(bob)
@test("reload with an invalid config keeps the old one")
def _(env):
cfg = env.base()
server = env.server(cfg)
agent = env.agent(cfg)
with open(server.config_path, "w") as f:
f.write("general: [this is: not valid\n")
server.send_signal(signal.SIGHUP)
server.wait_for_log(r"config not reloaded")
check(server.alive(), "server died on an invalid reload")
env.download_ok(agent, "small")
for _tunnel in (False, True):
def _limit_test(env, tunnel=_tunnel):
cfg, users = two_users(env, tunnel=tunnel)
users[1]["limit"] = "1MB"
server = env.server(cfg)
bob = env.agent(cfg, name="agent_bob", token=users[1]["token"])
alice = env.agent(cfg, name="agent_alice", token=users[0]["token"])
rc, body, _ = env.curl(bob, env.origin.url("big"), timeout=30)
check(rc != 0 or len(body) < len(env.origin.blobs["big"]),
"bob downloaded 2 MB despite a 1MB limit")
server.wait_for_log(r"user bob reached their limit")
env.download_fails(bob)
env.download_ok(alice, "small")
users[1]["limit"] = "100MB"
server.write_config(server.config | {"server": cfg["server"]})
server.send_signal(signal.SIGHUP)
server.wait_for_log(r"user bob is below their limit again")
env.download_ok(bob, "small")
TESTS.append((f"usage limit blocks and reload unblocks tunnel={onoff(_tunnel)}", _limit_test))
@test("usage survives a server restart")
def _(env):
cfg = env.base()
server = env.server(cfg)
agent = env.agent(cfg)
env.download_ok(agent, "big")
server.stop()
first = env.usage().get("alice", 0)
check(first >= len(env.origin.blobs["big"]), f"usage {first} lower than the download")
server = env.server(cfg, name="server2")
env.download_ok(agent, "small")
server.stop()
second = env.usage().get("alice", 0)
check(second >= first + len(env.origin.blobs["small"]),
f"usage went from {first} to {second}; the restart lost it")
def legacy_config(env, aes=True, tunnel=False, token=True):
"""The 1.1.x layout: everything shared in general, one general.token."""
cfg = env.base(aes=aes, tunnel=tunnel)
legacy = copy.deepcopy(cfg)
for key in ("protocol", "fakeUrls", "methods", "endPoints", "pullTimeout",
"connectionReuse", "tlsVerifyPeer", "tlsCaFile"):
if key in legacy["agent"]:
legacy["general"][key] = legacy["agent"].pop(key)
for key in ("bufferSize", "tlsCertFile", "tlsKeyFile"):
if key in legacy["server"]:
legacy["general"][key] = legacy["server"].pop(key)
agent_token = legacy["agent"].pop("token")
legacy["server"].pop("users")
legacy["server"].pop("usage")
if token:
legacy["general"]["token"] = agent_token
return legacy, agent_token
for _aes, _tunnel in itertools.product((True, False), (False, True)):
def _legacy_test(env, aes=_aes, tunnel=_tunnel):
cfg, _ = legacy_config(env, aes=aes, tunnel=tunnel)
server = env.server(cfg)
agent = env.agent(cfg)
env.download_ok(agent, "big")
env.upload_ok(agent)
check("moved out of general" in server.log(), "server did not warn about the old layout")
check("moved out of general" in agent.log(), "agent did not warn about the old layout")
check("general.token is deprecated" in agent.log(), "agent did not warn about general.token")
TESTS.append((f"1.1.x config layout still works aes={onoff(_aes)} tunnel={onoff(_tunnel)}",
_legacy_test))
@test("aes off server without users or token")
def _(env):
cfg, token = legacy_config(env, aes=False, token=False)
env.server(cfg)
agent_cfg = copy.deepcopy(cfg)
agent_cfg["agent"]["token"] = token
agent = env.agent(agent_cfg)
env.download_ok(agent, "big")
env.upload_ok(agent)
# ---------------------------------------------------------------- validation
def mutate(path, value):
def apply(cfg):
node = cfg
for key in path[:-1]:
node = node[key]
if value is DELETE:
node.pop(path[-1], None)
else:
node[path[-1]] = value
return apply
DELETE = object()
VALIDATION_CASES = [
("server", mutate(("server", "bufferSize"), 70000), "server.bufferSize must be between 1 and 65536"),
("server", mutate(("server", "bufferSize"), 0), "server.bufferSize must be between 1 and 65536"),
("agent", mutate(("agent", "protocol"), "ftp"), "agent.protocol must be one of"),
("agent", mutate(("agent", "fakeUrls"), {"a": 1}), "Error in agent.fakeUrls"),
("agent", mutate(("agent", "token"), "short"), "agent.token must be at least 32 bytes"),
("agent", mutate(("agent", "token"), DELETE), "agent.token is required"),
("server", mutate(("log", "logLevel"), "LOUD"), "logLevel must be one of"),
("server", mutate(("server", "users"), []), "server.users must have at least one entry"),
("server", mutate(("server", "users"), "alice"), "server.users must be a list"),
("server", mutate(("server", "users"), [{"name": "bad name!", "token": "x" * 40}]),
"name must be 1-64 characters"),
("server", mutate(("server", "users"), [{"name": "a", "token": "short"}]),
"token of user a must be at least"),
("server", mutate(("server", "users"), [{"name": "a", "token": "x" * 40},
{"name": "a", "token": "y" * 40}]),
"user name a is used more than once"),
("server", mutate(("server", "users"), [{"name": "a", "token": "x" * 40},
{"name": "b", "token": "x" * 40}]),
"have the same token"),
("server", mutate(("server", "users"), [{"name": "a", "token": "x" * 40, "limit": "2048"}]),
"limit must be a size with a unit"),
("server", mutate(("server", "usage"), {"resetDay": 40}), "resetDay must be between 1 and 28"),
]
def _validation_test(env):
failures = []
for mode, apply, expected in VALIDATION_CASES:
cfg = env.base()
cfg["log"]["logFile"] = os.path.join(env.dir, "validation.log")
apply(cfg)
path = os.path.join(env.dir, "invalid.yaml")
with open(path, "w") as f:
yaml.safe_dump(cfg, f, sort_keys=False)
open(cfg["log"]["logFile"], "a").close()
try:
result = subprocess.run([env.binary, mode, path], capture_output=True, timeout=10)
except subprocess.TimeoutExpired:
failures.append(f"{mode}: expected '{expected}' but the program started")
continue
output = (result.stdout + result.stderr).decode(errors="replace")
if result.returncode == 0 or expected not in output:
failures.append(f"{mode}: expected '{expected}', got exit {result.returncode}: "
f"{output.strip()[-300:]}")
for mode, text, expected in [
("server", "users:\n - name: a\n", "users belongs under the server block"),
("server", "general: [broken\n", "Error parsing config file"),
]:
cfg = env.base()
cfg["log"]["logFile"] = os.path.join(env.dir, "validation.log")
path = os.path.join(env.dir, "invalid.yaml")
with open(path, "w") as f:
if text.startswith("users"):
yaml.safe_dump(cfg, f, sort_keys=False)
f.write(text)
result = subprocess.run([env.binary, mode, path], capture_output=True, timeout=10)
output = (result.stdout + result.stderr).decode(errors="replace")
if result.returncode == 0 or expected not in output:
failures.append(f"{mode}: expected '{expected}', got exit {result.returncode}: "
f"{output.strip()[-300:]}")
check(not failures, "\n".join(failures))
TESTS.append(("invalid configs are rejected with a clear message", _validation_test))
@test("sample config passes validation")
def _(env):
for mode in ("server", "agent"):
cfg = copy.deepcopy(env.sample)
cfg["log"]["logFile"] = os.path.join(env.dir, "sample.log")
cfg["server"]["usage"] = {"file": os.path.join(env.dir, "usage.yaml")}
cfg["server"]["listenIp"], cfg["server"]["listenPort"] = "127.0.0.1", free_port()
cfg["agent"]["listenIp"], cfg["agent"]["listenPort"] = "127.0.0.1", free_port()
cfg["server"]["tlsCertFile"], cfg["server"]["tlsKeyFile"] = env.cert, env.key
node = Node(env, mode, cfg, f"sample_{mode}")
node.start()
# ---------------------------------------------------------------- runner
class Runner:
def __init__(self, args):
self.binary = os.path.abspath(args.binary)
if not os.access(self.binary, os.X_OK):
sys.exit(f"{self.binary} is not an executable")
for tool in ("curl", "openssl"):
if not shutil.which(tool):
sys.exit(f"{tool} is required")
self.workdir = tempfile.mkdtemp(prefix="nipovpn-e2e-")
self.artifacts = args.artifacts
self.cert = os.path.join(self.workdir, "server.crt")
self.key = os.path.join(self.workdir, "server.key")
subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
"-keyout", self.key, "-out", self.cert, "-days", "2",
"-subj", "/CN=nipovpn-test"], check=True, capture_output=True)
self.origin = Origin()
def run(self, tests):
passed, failed, known, fixed = [], [], [], []
started = time.time()
for index, (name, fn) in enumerate(tests, 1):
env = Env(self, name)
t0 = time.time()
error = None
try:
fn(env)
except TestFailure as e:
error = str(e)
except Exception:
error = traceback.format_exc()
crashes = env.close()
if crashes:
error = (error + "\n" if error else "") + "\n".join(crashes)
duration = time.time() - t0
known_bug = getattr(fn, "known_bug", None)
if known_bug and error is not None and not crashes:
status = "KNOWN BUG"
elif known_bug and error is None:
status = "FIXED?"
else:
status = "PASS" if error is None else "FAIL"
print(f"[{index:>2}/{len(tests)}] {status} {name} ({duration:.1f}s)", flush=True)
if status == "KNOWN BUG":
known.append(name)
print(f" {known_bug}\n {error.splitlines()[0]}", flush=True)
shutil.rmtree(env.dir, ignore_errors=True)
elif status == "FIXED?":
fixed.append(name)
print(" passes now: remove its known_bug marker", flush=True)
shutil.rmtree(env.dir, ignore_errors=True)
elif error is None:
passed.append(name)
shutil.rmtree(env.dir, ignore_errors=True)
else:
failed.append(name)
print(" " + error.replace("\n", "\n "), flush=True)
if self.artifacts:
dest = os.path.join(self.artifacts, os.path.basename(env.dir))
shutil.copytree(env.dir, dest, dirs_exist_ok=True)
print(f"\n{len(passed)} passed, {len(failed)} failed, {len(known)} known bugs, "
f"{len(fixed)} known bugs passing in {time.time() - started:.0f}s")
for name in failed:
print(f" FAILED: {name}")
self.origin.close()
if not failed:
shutil.rmtree(self.workdir, ignore_errors=True)
return not failed
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--binary", default=os.path.join(ROOT, "build", "core", "nipovpn"),
help="nipovpn binary to test (default: build/core/nipovpn)")
parser.add_argument("-k", dest="filter", action="append", default=[],
help="run only tests whose name contains this text (repeatable)")
parser.add_argument("--list", action="store_true", help="list tests and exit")
parser.add_argument("--artifacts", help="copy logs and configs of failed tests here")
args = parser.parse_args()
tests = [(n, f) for n, f in TESTS if not args.filter or any(k in n for k in args.filter)]
if args.list:
for name, _ in tests:
print(name)
return
if not tests:
sys.exit("no tests match")
sys.exit(0 if Runner(args).run(tests) else 1)
if __name__ == "__main__":
main()