Compare commits

...

2743 Commits

Author SHA1 Message Date
31936f6025 [make] change daemon sources list, add unix/win32 depending on system
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-08 23:03:52 +03:00
f3dcc5364f [make] update Unix daemon source name
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-08 22:57:37 +03:00
fbe2e734c2 [daemon] WIP: rework accessing from webconsole and App
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-08 22:51:09 +03:00
78193fc8f8 [daemon] WIP: use callbacks to work with daemon
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-08 19:35:23 +03:00
463d43b0bb [cmake] remove HTTPServer.cpp from daemon sources
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-08 00:40:50 +03:00
7197fce349 [webconsole] add base templates from current code
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-08 00:37:20 +03:00
5ba387ba2b [cmake] add webconsole library
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-07 22:50:44 +03:00
a843be75f3 start work on webconsole with templates
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-07 22:45:53 +03:00
47460d86b2 verify signature and send peer test msg 5 2022-06-07 12:55:58 -04:00
3cd74f0d4f send PeerTest message 2022-06-06 17:28:39 -04:00
690c9f7c6f [FS] add support for windows ProgramData path when running as service
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-06 18:25:22 +03:00
e2718e5a12 [config] change descriptions for deprecated options
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-06 17:44:36 +03:00
d9fefe757e SSU2/SSU2Session split 2022-06-05 19:33:36 -04:00
55e4bf6b65 set correct statuc code for peer test 2022-06-05 14:59:33 -04:00
0176e5cf18 Do not show 'Address registration' line if leaseset is encrypted 2022-06-04 19:28:01 +00:00
4670b12d49 correct buffer size for token request 2022-06-04 08:18:45 -04:00
321ec8ae4d correct size for Ack block with ranges 2022-06-03 19:16:52 -04:00
1ccbb8d10b correct offset for nonce in peer test message 2022-06-03 14:02:31 -04:00
86c0accdce check nonce for peer test msg 5 2022-06-03 13:18:37 -04:00
38d6c29ce9 correct timestamp size for peer test message 2022-06-03 08:39:54 -04:00
0cf9478cd4 create SSU2 session for peer test msgs 5-7 2022-06-02 20:12:25 -04:00
a04abd304a don't send own hash for peer test msg 1 2022-06-02 18:23:51 -04:00
84aec9fe31 correct msg for first peer test message 2022-06-02 15:40:51 -04:00
593b9bb6c5 start SSU2 server before peer test 2022-06-02 15:08:38 -04:00
d3a9cc8fde check if session is established before sending peer test 2022-06-02 15:04:35 -04:00
87a434c377 start peer test for SSU2 2022-06-01 21:51:02 -04:00
56022c9442 handle garlic messages from tunnels without pool 2022-05-31 21:43:31 -04:00
593d6bf466 create initial peer test 2022-05-31 18:31:05 -04:00
29a4366dcf fix mingw build script
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-06-01 00:12:51 +03:00
0a42f414bf [makefile] update support for WSL, remove gcc version detect
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-31 21:59:28 +03:00
9b2ac4349e [cmake] use Threads::Threads (closes #1735)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-31 21:59:28 +03:00
2d4c7729ad case-insensitive headers 2022-05-29 16:59:15 -04:00
6ecab66b0e always send Connection: close, strip out Keep-Alive for server HTTP tunnel 2022-05-28 21:54:58 -04:00
1dded57a1c fix typo in Referer 2022-05-27 13:29:59 -04:00
1d6104ecf3 addressbook.enabled config param 2022-05-27 13:17:06 -04:00
14da941ff4 Fixed #1761. Correct section for SSU2 2022-05-25 08:37:36 -04:00
06b87311ea 2.42.1
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-24 15:09:26 +03:00
3b31773117 [deb] remove O3 optimization flag
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-24 15:07:16 +03:00
9c87fe79ea [openssl] suppress deprecation messages
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-24 15:06:01 +03:00
bd00112562 update windows build script
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-24 14:39:11 +03:00
1c9160c37d correct jump link 2022-05-24 07:09:24 -04:00
e2ef88229f fixed warning 2022-05-22 12:22:24 -04:00
fd7b889a0f 2.42.0 2022-05-22 08:26:14 -04:00
a7aa056ec1 [gha] fix typo
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-20 21:30:14 +03:00
4f74acb2d3 [gha] build docker containers on tags
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-20 21:26:20 +03:00
22ef1be82b [gha] build docker containers only when pushing to openssl branch
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-20 21:11:19 +03:00
9ddbf255ba fix const std::map usage
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-20 21:04:41 +03:00
dfb171d32a [httpproxy] ordered jumps list
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-20 20:49:26 +03:00
6b4ffcff5a cleanup code (spaces, tabs)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-20 17:44:29 +00:00
d31cd2e5d6 fix incorrect boolean value parsing
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-17 19:02:12 +03:00
396c74e6c6 Revert "Simple refactor of nested if-statements" 2022-05-17 04:55:46 +00:00
609c658a9b [gha] publish releases with latest-release tag
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-15 14:12:26 +03:00
ee6bb40736 remove obsolete msvc define
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-15 11:47:10 +03:00
f8c5ea2b42 [i18n] add french translation
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-15 11:47:10 +03:00
923eb9fdb3 fix udp tunnels reload
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-15 11:47:10 +03:00
2cd3ebbdb3 copy peer test block 2022-05-14 19:18:58 -04:00
5e25e30330 check if there is only one unacked packet 2022-05-14 16:36:16 -04:00
5aa2a8f60f handle peer tests 2022-05-13 20:38:18 -04:00
0a1e302e8a libi2pd: Fix the build with LibreSSL 3.5.2 2022-05-12 19:11:17 +00:00
bb705a77cf handle PeerTest message 2022-05-11 17:48:25 -04:00
cb6155b946 fixed warning 2022-05-11 11:44:27 -04:00
714d1cc993 close stream if delete requested 2022-05-08 11:49:11 -04:00
bc8e4494c4 random new profiles cleanup interval 2022-05-07 09:56:58 -04:00
c3a064f980 change int type
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-07 03:40:59 +03:00
eb3feb7dbd [profiles] add daily cleanup
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-07 03:19:32 +03:00
da3f3ccac9 connect to reachable introducers only 2022-05-06 19:38:48 -04:00
1a1871e8cd add RouterInfo block before RelayIntro 2022-05-06 15:02:09 -04:00
c22ab7e1fc use openssl's siphash for 3.0.1 and higher 2022-05-04 18:58:08 -04:00
436992b069 send and process HolePunch message 2022-05-04 13:58:06 -04:00
18cb3912e5 fixed imccorect termination 2022-05-02 15:05:44 -04:00
a818b0ba02 Merge pull request #1748 from voltamperoff/Refactor-I2CP-CreateSessionMessageHandler
Simple refactor of nested if-statements
2022-05-01 17:13:13 -04:00
3716b6f988 move TunnelHopVisitor inside Tunnel class
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-01 23:40:00 +03:00
c9e4e78f41 [webconsole] remove version from title, move tunnel chain print from Tunnel class
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-01 23:25:08 +03:00
9b4e8bf64b [webconsole] do not show registration block when token is not provided
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-05-01 18:12:43 +03:00
5aebefe73f connect through introducer 2022-05-01 10:33:25 -04:00
8f2124beab update reseeds
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-30 19:33:30 +03:00
8b8b43df28 [rpm] support rhel 9
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-30 17:54:52 +03:00
c42b991bc9 [rpm] pre-support rhel 9
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-30 17:04:08 +03:00
ec08333bf9 [rpm] fix build on fedora 37
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-30 16:45:53 +03:00
9e5b4e14c9 [rpm] fix build on fedora 37
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-30 16:39:36 +03:00
1f5ed89a88 set blinded signature type to RedDSA for EdDSA 2022-04-29 12:48:45 -04:00
2304a2bc2e remove android contrib files (moved to android repo)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-29 12:48:40 +03:00
dc82105226 check status code and verify RelayResponse signature 2022-04-28 20:41:06 -04:00
5221f3ddc9 one SSU2 session per remote router 2022-04-28 13:11:51 -04:00
e970deb92b check presense of introducers in SSU2 address 2022-04-28 11:43:33 -04:00
9db7ec6bb0 create and send RelayRequest 2022-04-27 18:52:44 -04:00
2e691b6655 check if next manage time is too long 2022-04-26 21:02:39 -04:00
f22e10537b fixed typo 2022-04-26 20:45:10 -04:00
6e532c494c create new published SSU2 addresses 2022-04-26 20:30:39 -04:00
f9ed0d4aa2 fixed crash 2022-04-26 20:01:32 -04:00
78b1afcc8c publish introducer cap for SSU2 address 2022-04-26 15:20:57 -04:00
40340cf9c2 handle RelayResponse 2022-04-26 13:59:59 -04:00
eb6437050f SSU2 introducers 2022-04-25 19:57:46 -04:00
45ebfe378b correct Ack range 2022-04-23 11:11:49 -04:00
1326597226 use ipv6 preference only when netinet headers not used (entware with musl workaround)'
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-23 13:50:34 +03:00
751da92c13 send relay response 2022-04-22 20:34:19 -04:00
e10ca637da handle RelayIntro 2022-04-22 15:03:49 -04:00
c5d9d71a8a create relay tag and relay request block 2022-04-21 15:47:36 -04:00
3e0f5d231d send queue after batch of packets 2022-04-18 15:47:35 -04:00
6990f177ba window size 2022-04-18 13:14:09 -04:00
98e713166b show port for non-published SSU addresses 2022-04-18 12:27:57 -04:00
4c91ae0085 check if end of list 2022-04-16 17:01:06 -04:00
43f74d4d5a resend packet with new packet number 2022-04-16 15:42:11 -04:00
8c3e716c3f ranges in ack block 2022-04-15 16:26:44 -04:00
05946125b5 handle single packet 2022-04-13 12:33:59 -04:00
1e2a0a4549 handle incoming packets in batch 2022-04-12 11:42:51 -04:00
f9f5084dd7 typo
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-11 11:26:10 +03:00
b7e7c6db7b UDP Client: ignore incomming traffic and error when stopping (prevent socket restarting)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-10 23:10:41 +03:00
f9d67b28ec handle fragmented SessionConfirmed 2022-04-09 19:56:57 -04:00
46b77cc280 increase RouterInfo buffer size 2022-04-09 14:40:38 -04:00
2f10decf56 daemon: make possible to set datadir before init
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-09 19:57:32 +03:00
678a1ae0fb send fragmented messages 2022-04-09 11:42:34 -04:00
51cbffd097 don't lookup session for every sinle packet 2022-04-07 10:57:57 -04:00
207b13dcab send correct acnt if gaps 2022-04-05 18:23:52 -04:00
3052dbd1e8 single receive thread for both ipv4 and ipv6 2022-04-05 16:27:52 -04:00
5891b1ceb2 separate receive thread 2022-04-05 16:14:13 -04:00
07e14ddda8 check if SSU2 enabled 2022-04-04 20:37:29 -04:00
db5e90787c update I2NP header after all fragments received 2022-04-04 13:25:08 -04:00
67e501f5c7 correct nonce for SessionCorfirmed part 2 2022-04-04 11:52:14 -04:00
2160001167 correct non for token request and retry encryption 2022-04-04 09:58:17 -04:00
f5f4150d17 fixed typo 2022-04-03 13:43:33 -04:00
887f292612 update install target to use correct share directory, skip dh_auto_install in debian
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-04-02 23:16:39 +03:00
f5f282af97 cost for published SSU2 address 2022-04-02 14:32:26 -04:00
82f9585b7a handle fragments 2022-04-02 13:05:11 -04:00
eb561bb0c2 handle Ack ranges 2022-04-01 15:09:35 -04:00
81207999eb check token in SessionRequest 2022-03-31 21:07:51 -04:00
2fef595b83 resend packets 2022-03-31 15:35:55 -04:00
2024e790ca send I2NP messages 2022-03-30 18:04:12 -04:00
f9925c7374 hanlde Ack block 2022-03-30 15:03:45 -04:00
dd774b8dfd store out of sequence packet numbers 2022-03-30 12:31:24 -04:00
064b8042a5 ssu2.published and update SSU2 ipv4 2022-03-29 14:56:57 -04:00
7923ed9567 publish SSU2 address 2022-03-29 13:56:56 -04:00
30b83414ef find SSU2 address by address type 2022-03-28 18:03:22 -04:00
990906c57f insert garlic tag in destination's thread 2022-03-28 12:15:40 -04:00
4c323a666a show SSU2 transports in web console 2022-03-27 19:29:50 -04:00
a3f165d374 handle and send termination 2022-03-27 16:39:58 -04:00
4977f9e6b4 If-statements are simplified. Checks are rearranged for faster errors detection without unnecessary actions. 2022-03-27 18:05:37 +03:00
7d5f51e357 don't send instant Ack for out-of-sequence message 2022-03-27 09:26:45 -04:00
371a339b18 encrypt Data header 2022-03-27 07:47:25 -04:00
7e7aee27b6 handle I2NP message block 2022-03-26 21:59:21 -04:00
53148fe58f send Ack packet 2022-03-26 16:35:07 -04:00
56b6de6962 correct header decryption for Data message 2022-03-25 17:57:59 -04:00
44735681af KDF and process Data message 2022-03-25 15:34:43 -04:00
ee1c4f4fdc internal numeric id for families 2022-03-24 15:50:20 -04:00
fb6ecdde1e handle TokenRequest 2022-03-23 21:48:41 -04:00
861166d8a9 send TokenRequest message: 2022-03-23 19:13:44 -04:00
70dca81c40 dropped MESHNET build option
Dropping MESHNET build option due to lack of usage. That change won't
affect on usage with currently supported Yggdrasil network.

Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-03-24 01:36:12 +03:00
2774d72888 [makefile] add install target for linux
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-03-24 01:36:12 +03:00
2440ffbfc9 handle SSU2 SessionConfirmed 2022-03-23 14:06:55 -04:00
77c5dde320 send SessionConfirmed 2022-03-21 21:06:14 -04:00
aa49cad279 correct encrypted payload size for MixHash 2022-03-21 13:21:08 -04:00
f56ae240ab don't delete peding endpoint if Retry received 2022-03-21 12:56:02 -04:00
e871a30a78 initialize connid in constructor 2022-03-20 16:53:32 -04:00
30e6984889 handle Retry message 2022-03-20 15:10:18 -04:00
324932c758 separate i and key fields for shared SSU address 2022-03-20 10:28:08 -04:00
421800bc8f recognize SSU address supporting SSU2 2022-03-19 17:34:07 -04:00
86fb47b2b4 Merge pull request #1744 from WaxySteelWorm/openssl
Added StormyCloud Inc family cert
2022-03-19 12:34:24 -04:00
715f83bf84 Create stormycloud.crt 2022-03-19 10:59:54 -05:00
87bf5c2418 cleanup pending sessions 2022-03-18 20:21:31 -04:00
5c9af1c613 MixHash with encrypted payload after decryption 2022-03-18 15:32:32 -04:00
765e0e5c6b correct 'i' size for SSU2 2022-03-18 13:33:33 -04:00
cc296e16dc don't make SSU2 address published is 'i' is presented 2022-03-18 13:02:59 -04:00
ab9901525b separated sockets for ipv4 and ipv6 2022-03-17 18:45:14 -04:00
3643a46a0c don't update SSU2 port 2022-03-17 14:47:00 -04:00
d467e6869d don't update address for SSU2 2022-03-17 13:21:51 -04:00
db36018849 Fix typo 2022-03-17 10:41:39 +00:00
3c5c375f71 connect to SSU2 address 2022-03-16 21:11:48 -04:00
7473d8c9aa create and handle Address block 2022-03-16 13:13:31 -04:00
33645d7f09 [gha] XP: use make option for XP
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-03-16 04:29:02 +03:00
9f1106b14a [gha] XP: noconfirm for pacman
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-03-16 04:09:23 +03:00
3dd952b49b [gha] XP: noconfirm for pacman
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-03-16 04:03:26 +03:00
6b85bd2cb8 [gha] XP: fix MinGW repo url
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-03-16 03:54:32 +03:00
60b164c853 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2022-03-15 20:50:24 -04:00
40c8a1bc1d handle payload blocks 2022-03-15 20:49:41 -04:00
22de695f12 [gha] install git to XP builder
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-03-16 03:45:55 +03:00
e91f588cd7 [gha] build for winxp
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-03-16 03:42:10 +03:00
7b72d91549 receive incoming SSU2 packets 2022-03-14 19:25:59 -04:00
b3c2e86436 skip unknown address 2022-03-14 15:54:55 -04:00
908bdc7624 always publish intro key for SSU2 address 2022-03-13 21:55:03 -04:00
21c1ec9c8c enable SSU2 server 2022-03-13 21:34:11 -04:00
6d7d71bb16 don't show address:port for non-published addresses 2022-03-13 11:58:19 -04:00
6eba061c2a show local SSU2 address 2022-03-13 11:04:37 -04:00
f184f550b9 SSU2 address in config and RouterInfo 2022-03-12 21:51:17 -05:00
bb7c0fef20 SSU2 address in config and RouterInfo 2022-03-12 21:40:12 -05:00
5c15a12116 don't allocate buffer from netdb for LocalRouterInfo 2022-03-11 19:03:00 -05:00
68d015763e recognize SSU2 addresses 2022-03-11 16:17:44 -05:00
7faa732f38 send SessionCreated 2022-03-08 21:33:21 -05:00
11f9eeabf1 inbound.lengthVariance and outbound.lengthVariance 2022-03-07 22:20:11 -05:00
a152f36894 MixHash for SSU2 long header 2022-03-07 18:20:06 -05:00
d4ede6ff01 process SessionRequest 2022-03-05 18:39:27 -05:00
35542d803c KDF for session request 2022-03-04 21:51:40 -05:00
f6ba776c12 SSU2 keys 2022-03-01 21:23:08 -05:00
1511dcb309 store endpoint and send packet 2022-02-28 21:46:00 -05:00
35afa98112 [reseed] add new reseed
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-03-01 00:23:52 +03:00
df62b40ca7 [win32] return back service control code (#1733)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-28 23:02:19 +03:00
9f1a125ed9 decrypt connID for incoming packet 2022-02-27 20:15:14 -05:00
b7e20b9b86 2.41.0
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-20 16:57:58 +03:00
a5d6972913 [win] update build script license year
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-20 12:54:48 +03:00
e4cb42c599 [win] add binary signing support
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-20 12:53:31 +03:00
0a34f1f3ad 2.41.0 2022-02-19 17:21:11 -05:00
7bdeaa9611 don't pick own router for peer test 2022-02-19 08:15:49 -05:00
ab2577ce0a [daemon] print errors to stdout
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-18 21:00:16 +03:00
34544be423 Merge pull request #1732 from PurpleI2P/patch-1
Set of updates
2022-02-18 10:13:33 -05:00
6bf0fdd344 [webserver] use cancel instead shutdown for acceptor
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-18 09:45:35 +03:00
6a177cdd1c fix incorrect change in year
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-18 09:29:28 +03:00
a51ef0cfc6 set of updates:
* [webconsole] change error handling code to restart acceptor after any
error
* [webconsole] call shutdown vefore stopping acceptor on exit
* update license headers for modified files, change year to file
  creation year, not 2013 (when project started)

Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-18 09:20:06 +03:00
48374d97df always use TCP/IP sockets for I2CP 2022-02-16 15:32:13 -05:00
bf3d7e74f5 [i2cp] use tcp/ip socket on android
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-16 16:27:59 +03:00
ab3f3890e4 [i2cp] use tcp/ip socket on android
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-16 16:13:15 +03:00
dceb0fb8c5 [cmake] add warning about MESHNET option
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-16 11:39:09 +03:00
05c1856389 [cmake] do not use CMAKE_OSX_ARCHITECTURES for check
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-14 23:53:55 +03:00
dc5cba60d1 [cmake] add MAC_OSX define for Mac
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-14 22:58:56 +03:00
70409dcdcc Merge pull request #1728 from eyedeekay/swig-binding-cleanup
Removes workaround for passing string arguments from Go
2022-02-14 14:32:23 -05:00
a92c29e04c drop routers older than 6 months on start 2022-02-13 15:42:06 -05:00
idk
c4b4dc79cf Remove janky workaround for argument passing from Go. This should allow other languages to use the binding more easily, and go-i2pd doesn't need the workaround anymore 2022-02-13 13:21:18 -05:00
510fe43ec4 create and encrypt SessionRequest 2022-02-11 19:21:04 -05:00
73e572b66b disable thread naming for PowerPC (#1726)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-11 22:17:38 +03:00
a272a2cb7e [cmake] update min version, drop PCH
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-11 07:23:33 +03:00
43b990afe6 [cmake] disable deprecation warning when OpenSSL 3 is used
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-11 07:00:30 +03:00
90130b5492 fix exception printing
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-11 00:38:29 +03:00
f22faaefeb remove duplicate definition
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-11 00:27:19 +03:00
ac25649425 cast pthread name to char* for apple sdk
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-11 00:05:07 +03:00
04388325a8 KDF and encryption for SessionRequest 2022-02-10 14:03:09 -05:00
61ec873842 fixed incorrect ret code 2022-02-10 13:07:29 -05:00
ea1f2d4e26 use i for intro key for SSU 2022-02-06 10:17:35 -05:00
4211c733a2 s and i keys for all addresses 2022-02-05 17:14:25 -05:00
450266818a Noise XK for SSU2 2022-02-05 15:58:39 -05:00
1e019157bb SSU2 initial commit 2022-02-04 15:01:18 -05:00
c9a1066f02 send SessionCreated before connection close if slock skew 2022-02-03 14:49:36 -05:00
0062f7d764 [reseed] dont do yggdrasill address check if option disabled
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-03 14:49:24 +03:00
95e994e171 pass incomplete I2NP message by move 2022-02-02 17:33:33 -05:00
31242401e5 [cmake] update TargetArch.cmake (#1724)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-02 06:07:01 +03:00
19cc1c3b3f adjust clock from SSU SessionCreated is time difference exceeds 15 seconds 2022-02-01 18:43:11 -05:00
03bcdceb9b [gha] add ucrt windows build
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-01 15:42:57 +03:00
33ca836ad0 [gha] add ucrt windows build
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-02-01 15:36:35 +03:00
53f19e4050 Use builtin bitswap for endian on windows
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-01-29 22:09:27 +03:00
54b7d46f5a reseeds update
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-01-28 18:39:21 +03:00
40e6d675c5 I2NP messages pool for I2CP 2022-01-25 13:02:27 -05:00
73b77c83b8 select compatible outbound tunnel 2022-01-24 13:25:47 -05:00
632d41e50c [rpm] try to fix fedora copr build [3]
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-01-24 03:20:43 +03:00
17acadbfb9 [rpm] try to fix fedora copr build [2]
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-01-24 03:14:50 +03:00
2ab5924ec9 [rpm] try to fix fedora copr build
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-01-24 02:56:41 +03:00
ac09a4cf0f [i18n] update german translation
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-01-23 03:18:11 +03:00
c10ee59de3 cleanup memrory pools if no more streams 2022-01-21 21:34:50 -05:00
afad405ed9 check for duplicate destination 2022-01-19 12:08:56 -05:00
5a35de8dc9 [i18n] update uzbek translation
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-01-19 00:38:33 +03:00
58cf26c304 cleanup properties before update 2022-01-15 19:26:11 -05:00
a2de5564ac moved m_Properties to LocalRouterInfo 2022-01-15 18:54:02 -05:00
338b17ccf1 LocalRouterInfo for own router 2022-01-15 12:48:49 -05:00
843a968959 integer uptime 2022-01-09 19:07:10 -05:00
dc45c13eef [i18n] added german translation (thanks to mark22k@crowdin)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-01-09 23:42:13 +03:00
0d6e801595 [webconsole] change dark style colors
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2022-01-09 20:54:18 +03:00
2cd50ebaee fixed race condition 2022-01-07 13:39:12 -05:00
cb6f6a6596 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2022-01-03 16:28:17 -05:00
e4ab0acc92 create RouterInfo from shared pointer to Buffer 2022-01-03 16:27:28 -05:00
10237c41d3 Merge pull request #1717 from rex4539/typos
Fix typo
2022-01-03 20:23:09 +03:00
ac2c6c6010 Fix typo 2022-01-02 12:14:12 +02:00
c6b2ce93c4 Memory pool for RouterInfo address 2022-01-01 15:12:59 -05:00
401b7fe883 send error message in quotes 2021-12-31 08:48:21 -05:00
f567417bb3 memory pool for RouterInfo buffer 2021-12-30 15:16:13 -05:00
ae5cb3bbe7 rollback 2021-12-28 08:00:03 -05:00
0eb8e15796 allocated actual buffer size for RouterInfo 2021-12-27 13:02:06 -05:00
1c95c7856f avoid duplicated addresses. Check presence of netId and version 2021-12-24 18:58:20 -05:00
daf7551e59 try another fllodfill if no compatible tunnels 2021-12-18 17:55:26 -05:00
5b63d3692e HidUser0's yggdrasil reseed added 2021-12-13 13:47:59 -05:00
5f9972af78 [addressbook] fix loading subscriptions from config
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-12-07 23:00:52 +03:00
1be4cce074 [addressbook] fix loading subscriptions from config
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-12-07 22:59:11 +03:00
935e93eb36 minimal send ack interval 2021-12-05 17:54:34 -05:00
5d924cd35a don't copy received datagram 2021-12-04 19:32:18 -05:00
27116b9f30 2.40.0
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-28 04:26:44 +03:00
8ac2ee49a8 [gha] fix build without pushing tag for pre-release debian packages
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-28 04:00:03 +03:00
8a8e328fcf [build] include contrib/webconsole to windows packages
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-28 03:50:05 +03:00
c4207e7672 [webconsole] update css
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-28 03:49:08 +03:00
73642703bd 2.40.0
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-28 03:46:53 +03:00
b3bd175e64 2.40.0 2021-11-27 18:01:13 -05:00
742032907a [gha] update freebsd action
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-27 23:46:03 +03:00
edc0162163 clean line trailing spaces and tabs
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-27 23:30:35 +03:00
94661f697b [log] update log messages (closes #1693)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-27 22:53:53 +03:00
4ecf36fab6 update bandwidth option description (closes #1704)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-27 21:08:05 +03:00
96cdb3bca3 reseeds update
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-21 20:20:23 +03:00
6c57ba36f7 lazy initialization or tunnel gateway's random buffer 2021-11-20 18:31:18 -05:00
cb61897236 Merge pull request #1708 from acetoneRu/openssl
--help small correction
2021-11-20 08:39:43 -05:00
8b931dd40b Transit traffic bandwidth limit 2021-11-20 08:37:36 -05:00
6b81478bd2 Merge branch 'PurpleI2P:openssl' into openssl 2021-11-20 05:47:32 -05:00
9d94eb83c1 --help
Traffic bandwidth -> Transit traffic bandwidth
2021-11-20 05:46:44 -05:00
13374f8b7b [gha] publish windows artifacts separately (#1707) 2021-11-18 16:17:28 +03:00
7bf7aae3d1 [i18n] fix type in translation
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-18 15:23:09 +03:00
e5f39d0caf [i18n] add armenian translation
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-18 15:15:34 +03:00
174983548d Merge pull request #1705 from rex4539/typos
Fix typos
2021-11-14 20:37:33 +03:00
a9ec4d916b Merge pull request #1706 from acetoneRu/openssl
Transit traffic bandwidth configuration
2021-11-14 08:21:16 -05:00
a55c346af5 Bandwidth configuration
Changed to 'Transit traffic bandwidth configuration'
2021-11-14 08:17:53 -05:00
8e0d8c96bb Merge branch 'PurpleI2P:openssl' into openssl 2021-11-14 08:16:36 -05:00
9abd383014 eliminate extra pointers for tunnel hops 2021-11-13 15:11:59 -05:00
8ee9c437e1 Fix typos 2021-11-13 19:07:50 +02:00
4052b1ea6d pick compatible outbound tunnel for datagrams 2021-11-08 18:23:26 -05:00
fdde197c58 [webconsole] update stylesheet
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-08 07:40:39 +03:00
49883dc3ac [webconsole] update stylesheet (closes #1699)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-08 07:02:11 +03:00
d798faa1ca pick compatible ooutbound tunnel 2021-11-07 17:18:31 -05:00
3f63f15b16 copy compatible transports to new tunnel 2021-11-06 19:16:45 -04:00
f8c390cdd3 pick compatible tunnels 2021-11-06 15:44:56 -04:00
8f0978cfd6 all transports by default 2021-11-06 10:49:18 -04:00
1a8a32a773 select next tunnel with compatible transports 2021-11-05 14:51:24 -04:00
c0400bfd07 virtual destructor for TunnelConfig 2021-10-31 22:14:59 -04:00
c6e4758187 Revert "Merge pull request #1703 from simonvetter/simon/memory-and-multithreading-fixes"
This reverts commit 67863cfcf9, reversing
changes made to 4c5ec68ff1.

That change completly bloking transports thread on windows.

Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-01 05:03:34 +03:00
56ec8fe95b eliminate local destination mutex 2021-10-31 21:20:16 -04:00
67863cfcf9 Merge pull request #1703 from simonvetter/simon/memory-and-multithreading-fixes
memory leak and concurrency fixes
2021-10-31 21:08:11 -04:00
4c5ec68ff1 [win] add menu item for opening datadir
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-11-01 02:47:53 +03:00
58b7b7d731 libi2pd: add missing locks to i2p::tunnel::TunnelPool 2021-10-31 23:26:52 +01:00
1de1c79d4f libi2pd: add missing locks to i2p::tunnel::Tunnels
m_InboundTunnelsMutex, m_OutboundTunnelsMutex and m_PoolsMutex
have been changed to recursive_mutexes since they can be
acquired multiple times by the same thread.
2021-10-31 23:14:28 +01:00
7073a6bf38 libi2pd: make Tunnel and TunnelConfig destructors virtual 2021-10-31 14:02:25 +01:00
26db88d89b check if sip key is available 2021-10-27 22:33:37 -04:00
876e98d91e check if sip key is available 2021-10-27 22:23:32 -04:00
8566f6c127 don't store EVP_PKEY sip keys 2021-10-27 21:18:21 -04:00
bb8dc67942 don't use openssl's SipHash from 3.0.0 due regression 2021-10-27 19:05:16 -04:00
9965d72990 don't store EVP_PKEY with EdDSA signer and verifier 2021-10-26 21:36:34 -04:00
921ec9ec12 fix build with openssl 3.0.0 2021-10-23 18:10:02 -04:00
f1990bc2ab use tunnel endpoint memroy pool to split to tunnel messages at gateway 2021-10-22 21:08:20 -04:00
cdc8e463b7 use memory pool for outgoing tunnel gateway messages 2021-10-22 19:18:45 -04:00
0a62a962d7 [debian] update upnp patch
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-10-22 05:57:04 +03:00
b0f043ec86 [make] USE_GIT_VERSION option to use commit info in version (closes #1702)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-10-22 05:35:01 +03:00
ae0cf2e831 use memory pool for tunnel messages 2021-10-20 21:05:22 -04:00
4ce7e192d6 Merge pull request #1701 from simonvetter/openssl
fix a few undefined behaviour/out of bounds issues
2021-10-19 18:25:06 -04:00
04ca916aac Merge pull request #1700 from xanoni/set-default-make-target
Makefile: set default target ("all")
2021-10-19 23:56:41 +03:00
a348e10620 libi2pd: fix undefined behaviour and memory overruns
This fixes the following issues (flagged by cppcheck):
[libi2pd/ECIESX25519AEADRatchetSession.cpp:537]: (error) Buffer is accessed out of bounds: m_NSREncodedKey
[libi2pd/Identity.cpp:22]: (error) Buffer is accessed out of bounds: keys.publicKey
[libi2pd/Identity.cpp:22]: (error) Buffer is accessed out of bounds: publicKey
[libi2pd/NetDb.cpp:70] -> [libi2pd/NetDb.cpp:69]: (error) Iterator 'it' used after element has been erased
[libi2pd/SSUData.cpp:186] -> [libi2pd/SSUData.cpp:187]: (warning) Shifting 32-bit value by 63 bits is undefined behaviour.
2021-10-19 22:27:12 +02:00
af794f901f libi2pd: minor logging fixes 2021-10-19 22:27:06 +02:00
8a58572b34 [webconsole] upload example dark style
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-10-19 18:24:49 +03:00
0c25e8f1eb [build] changes in windows build script
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-10-19 18:24:18 +03:00
ff3d2db85e Darwin: allow calling make install more than once
This commit ensures that `gzip` does not overwrite any of the repo
files, because that prevents `make install` from executing more than
once.
2021-10-18 22:33:32 -04:00
efd84a2404 Makefile: set default target ("all")
Fixes compilation on Darwin, see:
https://github.com/PurpleI2P/i2pd/pull/1698#issuecomment-946304938
2021-10-18 22:11:27 -04:00
278fd2d8d5 create tunnel I2NP message for tunnel data 2021-10-18 19:03:08 -04:00
197882a4c9 create I2NP depending on type in I2NP block 2021-10-17 15:30:24 -04:00
d310efcb5c pass I2NPMessage by move 2021-10-17 11:31:37 -04:00
1af9117b80 don't create new tunnel message for encryption/decryption 2021-10-15 14:01:41 -04:00
44e01b41f8 reserve address for 3 introducers 2021-10-12 13:28:16 -04:00
7def2fa6a3 use std::vector for address list 2021-10-10 09:53:21 -04:00
48131f4597 don't store full path with RouterInfo 2021-10-07 15:08:33 -04:00
49e8cf89d8 don't send short tunnel build messages for ElGamal only destinations 2021-10-06 12:42:32 -04:00
e6bcd04a36 short build message for re-created tunnels and far end transports 2021-10-05 19:38:33 -04:00
af133f4968 fixed crash if incorrect blinded signature type 2021-09-29 12:38:38 -04:00
d723faaaa3 [UDPTunnel] restart local listener on error
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-09-28 14:27:35 +03:00
cc75efcbca fixed build for C++11 2021-09-27 18:25:15 -04:00
2eded7cdd7 send ping every keealive interval for client tunnels 2021-09-26 16:25:12 -04:00
b10e5ce358 send ping 2021-09-26 11:20:20 -04:00
1bb1d89fab change back to map and unodered_map 2021-09-25 18:30:17 -04:00
b9dd4aee8d use flat_map for incompete messages 2021-09-24 19:12:12 -04:00
518e53a61c use flat_map for smaller tables 2021-09-24 14:23:39 -04:00
18b6ba80f2 cleanup RelayRequests 2021-09-22 19:09:56 -04:00
8debdc264c use common cleanup timer for all SSU sessions 2021-09-21 22:13:34 -04:00
31bdce1f1f cleanup received messages list by timestamp 2021-09-21 19:01:22 -04:00
317d8cdc48 don't allocate separate buffers for SessionRequest and SessionCreated 2021-09-18 15:44:43 -04:00
5b2b9e00a2 reuse receive buffer 2021-09-17 21:52:39 -04:00
3dd9e81296 [addressbook] check domain ending when processing subscriptions
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-09-17 02:53:30 +03:00
d2faec70be [gzip] do not initialize deflator if gzip is not enabled for tunnel
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-09-14 14:48:21 +03:00
e5c773a3eb [webconsole] move resources to separate header file
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-09-13 23:16:18 +03:00
ec86c4611d disable reload checks for UDP tunnels (TODO)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-09-13 23:16:18 +03:00
247b6a0ed2 memory pool for SSU packets 2021-09-13 13:13:27 -04:00
f7f36568ef set gzip compression to false by default 2021-09-12 14:29:43 -04:00
e054c6e82c memory pool for SSU messages and fragments 2021-09-11 18:58:27 -04:00
5e2e1a1e3d don't include old tunnel to LeaseSet if recreated 2021-09-10 19:57:38 -04:00
ad036de69d eliminate allocation of m_ExtendedBuffer 2021-09-09 21:19:52 -04:00
20652f7995 resseed if too few floodfills 2021-09-09 15:12:53 -04:00
2f88a75325 Merge pull request #1688 from yangfl/openssl
disable pthread_setname_np on GNU/Hurd
2021-09-05 21:00:19 +00:00
292fe94352 RouterContext is always ECIES 2021-09-05 11:16:41 -04:00
76dca1b46b don't handle ElGamal build record 2021-09-05 09:10:13 -04:00
a54b5c18c6 fixed crash 2021-09-05 09:08:29 -04:00
c763472914 select ECIES routers only for peer tests and introducers 2021-09-05 08:41:32 -04:00
3a77e7ba2d remove dependancy from localization 2021-09-04 18:55:51 -04:00
41d6c117ee make sure server tunnel is published 2021-09-04 18:45:32 -04:00
e8f4c42bfb moved current language from RouterContext to ClientContext 2021-09-04 14:01:57 -04:00
bce8469e59 eliminate extra error message 2021-09-04 08:53:39 -04:00
3f46ca41ca disable pthread_setname_np on GNU/Hurd
which does not exist on GNU/Hurd
2021-09-04 15:07:09 +08:00
6b1ef6e1b9 tunnels reload changes: fix tcp tunnels reload
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-09-04 04:02:27 +03:00
349022ae42 don't select ElGamal routers for tunnels 2021-09-03 13:30:01 -04:00
bb518d3d51 don't pass BN_CTX to encrypt/decrypt functions 2021-08-31 18:51:40 -04:00
c45e202fab removed ElGamal encryption support for own router 2021-08-29 14:22:01 -04:00
541464b705 don't delete floodfill if number of remaining floodfills is less than minimal 2021-08-26 15:13:58 -04:00
c762acd780 Merge pull request #1687 from dbermond/fix-test-blinding
[tests] fix compilation of test-blinding
2021-08-24 10:24:31 +00:00
ec98ff297c Make blinding test runnable 2021-08-24 13:23:10 +03:00
af2c6c5575 [rpm] change if statement to cover fedora 35
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-24 03:16:28 +03:00
7d220fb2eb [tests] fix compilation of test-blinding
test-blinding currently fails to build with the following error:

In file included from ../libi2pd/Timestamp.cpp:19:
../libi2pd/RouterContext.h:21:10: fatal error:
I18N_langs.h: No such file or directory
   21 | #include "I18N_langs.h"
      |          ^~~~~~~~~~~~~~
compilation terminated.
2021-08-23 17:22:28 -03:00
f0c49b58fb suppress inconsistent-missing-override warning message
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-23 19:29:55 +03:00
24eeadea76 [rpm] add changelog note
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-23 17:03:26 +03:00
455c71ff25 fix warning about ifr_name size
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-23 17:00:57 +03:00
96850da31e 2.39.0 2021-08-23 06:58:36 -04:00
6ba992dabd [rpm] try fix build on fedora rawhide [try 3]
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-22 23:41:36 +03:00
2bdfcedd0e [docs] add comma to description
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-22 23:38:04 +03:00
c93ab8f829 update changelog, i2pd.conf
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-22 23:36:08 +03:00
8abd08bd1b change log for 2.39.0 2021-08-22 15:58:46 -04:00
33355c0abe [rpm] try fix build on fedora rawhide
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-22 22:44:04 +03:00
b830babcf4 [rpm] try fix build on fedora rawhide
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-22 22:32:03 +03:00
97765ef895 [i18n] add namespace
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-18 23:04:52 +03:00
8943d212ee [i18n] add Uzbek translation (partial)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-18 22:55:14 +03:00
86e118f2b7 [i18n] change string in HTTPProxy
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-18 22:23:39 +03:00
8c3823fc92 [gha] build docker containers for arm/arm64
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-15 16:53:10 +03:00
b0874410f1 take first avalable resolved address if local address is not specified 2021-08-13 13:54:23 -04:00
797f5eb714 select compatible resolved address for server tunnel 2021-08-13 13:31:04 -04:00
fc29911ffd rollback 2021-08-13 11:36:04 -04:00
1e17ef2f21 [webconsole] show v4 status only ipv4 is enabled
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-13 09:17:27 +03:00
b3e7b1b5ac Squashed commit of the following:
commit 40ec4e8b59e91efe2ef7654c8c0938facfddef1b
Author: Simon Vetter <simon.vetter@runbox.com>
Date:   Fri Jul 30 21:23:27 2021 +0200

    libi2pd: mark additional ipv6 addresses/nets as reserved

    This adds :: (undefined address), ::1 (loopback address) as well as
    ff00::/8 (multicast prefix) to reservedIPv6Ranges.

    A bunch of nodes seem to be publishing bogus addresses (mostly ::1)
    in the netDB, resulting in unnecessary tunnel build failures.

Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-13 09:11:56 +03:00
38a2d45a3c close all existing streams when command SAM socket got closed 2021-08-11 12:31:46 -04:00
49b3ac7f77 don't reschedule resend timer for terminated streams 2021-08-11 12:23:43 -04:00
d124d4cace allow ipv6 adresses for UDP server tunnels 2021-08-10 11:36:12 -04:00
ba369d9b30 [webconsole] fix style in css
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-07 17:31:26 +03:00
bef8587d8f [makefile] create object dirs on windres (race condition)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-07 01:38:35 +03:00
fcbc16f2fd [webconsole] fix style issues, clean external style in file was not found on reload
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-07 01:37:45 +03:00
a3b172bbcb [makefile] change back directories creation, create them before compiling object files 2021-08-06 21:19:05 +00:00
2f945a4fce [makefile] dont build .so and .dll on default target
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-06 21:19:05 +00:00
dc9e5dc2f1 [makefile] suffix, not prefix
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-06 21:19:05 +00:00
9396827379 [makefile] build libraries on default target
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-06 21:19:05 +00:00
28a055bd78 [webconsole] add external CSS support (#1682)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-06 20:42:08 +03:00
37f1a55147 encryption type 0,4 by default for server tunnel 2021-08-06 12:32:21 -04:00
64ec7dd559 narrow down random range 2021-08-03 19:26:09 -04:00
367df4d0db RAND_bytes from random router selection 2021-08-03 15:43:58 -04:00
da7e41c188 use Tag<64> for ratechet tags 2021-08-01 18:42:13 -04:00
d88fe203e1 [tunnels] count outbound traffic for zero-hop tunnels
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-08-01 09:25:02 +03:00
1e01c30e63 set pool for zero-hops tunnels 2021-07-30 14:12:50 -04:00
b16b753ed2 Change default irc server to IRC ILITA (#1677) 2021-07-30 17:49:19 +03:00
7a55d1fc38 don't insert garlic tag for short tunnel build reply if the same router 2021-07-28 21:14:03 -04:00
f8623b6121 consistent path for explicit peers 2021-07-28 19:08:55 -04:00
9a3c22f47d don't encrypt ShortTunnelBuild and ShortTunnelBuildReply if on the same router 2021-07-28 15:06:24 -04:00
e68cff8bba try routers before random router 2021-07-27 18:35:30 -04:00
513493fa78 fixed typo 2021-07-26 18:46:29 -04:00
a6937c792f more precise router selection 2021-07-26 17:51:32 -04:00
99c7d5c23a don't create enryptor for ECIES record encryption 2021-07-25 22:30:54 -04:00
cd8e8970de NTP request through compatible address 2021-07-24 16:01:11 -04:00
26d5ced2ef optimal padding for one-time messages 2021-07-23 20:28:55 -04:00
c7234f705a let NTCP sync through ipv6 2021-07-23 18:34:51 -04:00
c153471c49 use short tunnel build if possible 2021-07-22 20:58:35 -04:00
28369faa00 [debian] fix tabulation in patch 2021-07-22 13:35:58 +00:00
445c5f47ae [debian] update patch for upnp 2021-07-22 13:24:42 +00:00
7078ca53c3 [debian] update patch for upnp 2021-07-22 13:23:05 +00:00
d6ce5f9fa1 Merge pull request #1669 from eyedeekay/c-wrapper-libi2pd-api
C wrapper for part of the libi2pd api
2021-07-22 08:54:59 -04:00
f28024cfe8 decline transit tunnels from short tunnel build message 2021-07-21 18:12:37 -04:00
911ab9813e handle encrypteed I2NPShortTunnelBuildReply in destination 2021-07-21 14:55:38 -04:00
cfbf5862f9 set pool for tunnel before build 2021-07-21 13:08:12 -04:00
5cb1f5986d use msgID from ECIESx25519 block 2021-07-20 22:00:06 -04:00
0b14c810fb handle ShortTunnelBuildReply 2021-07-20 19:38:36 -04:00
c2334db8f8 correct reply key for short tunnel build record 2021-07-20 18:02:48 -04:00
4807092df6 fixed typo 2021-07-20 15:17:58 -04:00
bdc1107c96 correct message type for ShortTunnelBuild 2021-07-20 14:35:02 -04:00
db9223b0d5 set minimal version for floodfill to 0.9.38 2021-07-19 17:50:55 -04:00
6ecfe0789f don't allocate payload buffer for every single ECIESx25519 message 2021-07-18 18:45:08 -04:00
a37cf058cd router with expired introducer is still valid 2021-07-16 20:12:41 -04:00
f4902e6642 eligble floodfill must be reachable by ipv4 2021-07-16 13:53:12 -04:00
5d022c25ba don't send datetime for one time key message 2021-07-16 09:44:22 -04:00
0cd9f1b002 precalculate padding sizes 2021-07-15 19:01:43 -04:00
cd0751d3f1 padding block for message for router 2021-07-15 18:30:32 -04:00
a1d1a5df74 datetime block for message for router 2021-07-15 18:18:55 -04:00
197f13f9c0 rollback 2021-07-15 14:02:20 -04:00
41bfc7899d keep own RouterInfo in netdb 2021-07-14 14:46:56 -04:00
2c129b6d39 create and handle short tunnel build reply 2021-07-12 19:40:40 -04:00
dbe427d5eb set reply code for short tunnel build messages 2021-07-11 19:29:16 -04:00
3e281d4790 Update README.md 2021-07-11 23:10:53 +03:00
15c3d46492 encrypt inbound tunnel build message for short tunnel build only 2021-07-10 17:28:18 -04:00
6a467a09bd fixed build error 2021-07-10 16:47:28 -04:00
ba1b8c7c2b WrapECIESX25519MessageForRouter wihout session 2021-07-10 16:15:15 -04:00
1e9eb30aa3 garlic encryption of inbound tunnel build message 2021-07-10 14:33:23 -04:00
d47bf1bada different tunnel build record size 2021-07-09 19:26:14 -04:00
59dd60f5cb genarate keys in CreateBuildRequestRecord 2021-07-09 19:24:28 -04:00
c02a0c4da9 process DELAY_REQUESTED option 2021-07-08 22:22:00 -04:00
84f6024cc9 locate record to build inside CreateBuildRequestRecord 2021-07-08 19:00:25 -04:00
d73b42b726 extract ret code per hop 2021-07-08 16:39:38 -04:00
ed0c2e68a5 DecryptRecord per tunnel hop 2021-07-07 21:16:30 -04:00
847225c6bf more yggdrasil reseeds added 2021-07-07 08:24:01 -04:00
a6294df9e8 decrypt one-time message encrypted with tag on router 2021-07-06 20:15:55 -04:00
431265a86a update orignal's certificate 2021-07-06 18:22:08 -04:00
4255c4901d orignal's reseed ceritifcate 2021-07-06 17:44:39 -04:00
9000b3df4e KDF for short tunnel build messages 2021-07-05 14:31:07 -04:00
a717542733 update yggdrasil reseed to 0.4 2021-07-04 07:33:28 -04:00
aace644815 added ShortECIESTunnelHopConfig 2021-07-02 22:06:24 -04:00
0ae170531e different ElGamal and ECIES hops configs 2021-07-02 15:41:33 -04:00
idk
5d01ee9581 Also add the languages to the linker flags in the api.go file 2021-07-02 13:20:28 -04:00
8b35ce3320 separate decryption between own record and other records 2021-07-02 13:20:24 -04:00
ff0e23d2c4 [cmake] use GNUInstallDirs for libraries destination path (#1672)
Signed-off-by: r4sas <r4sas@i2pmail.org>
2021-07-02 16:43:41 +00:00
idk
d62d2ed269 resolve merge conflicts 2021-07-02 11:02:31 -04:00
idk
abee29719d fix go linking 2021-07-02 10:47:55 -04:00
5781335814 save and check last stream 2021-06-29 19:08:11 -04:00
f036b8df2d [i18n] update translatable strings (remove douplicates)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-28 12:45:28 +03:00
25f63ac22a create different I2NP tunnel messages for endpoint and non-endpoint 2021-06-27 15:49:57 -04:00
12d6f03dc9 [i18n] add language changing at runtime in webconsole
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-27 17:14:45 +03:00
6d2c9e367b remove unused CI and docker files
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-27 12:24:41 +03:00
66422d6d83 double size tunnel message 2021-06-26 21:44:51 -04:00
b9476791f4 eliminated extra I2NP messages for fragments 2021-06-26 17:40:25 -04:00
9fb8e8a582 [cmake] build translations as library
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-26 23:59:34 +03:00
377a50fa13 [make] build translations as library
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-26 23:45:55 +03:00
da20cae25c [webconsole] urldecode domain for registration string generator
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-26 18:59:48 +03:00
d0c5732e16 eliminate extra lookups for sequential fragments 2021-06-26 07:18:42 -04:00
idk
f9d9aa0306 move wrapper code to own directory 2021-06-24 09:35:42 -04:00
idk
f5db34b98b C_InitI2P is compatible with more things if it passes argv by reference, it would appear. So to pass arguments to InitI2P you need to turn them back into char* argv[] by tokenizing them and copying them into an array which you then pass to InitI2P from C_InitI2P. The Streaming and Destination Creation parts need to have wrappers for over Identity.h, Streaming.h to be useful so remove them. 2021-06-23 11:18:53 -04:00
3c07665479 use unordered_map for incomplete messages 2021-06-22 15:35:44 -04:00
f7f50d049b reduce short tunnel build record length 2021-06-22 13:11:02 -04:00
7d51b4c6ed [i18n] pull ukrainian translation from crowdin (closes #1666)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-21 21:16:46 +03:00
35ba16ff3b fixed #1665. cast to int64_t 2021-06-20 17:20:29 -04:00
6971b1e9da fix typo in config option description
Kudos @iBicha
https://github.com/PurpleI2P/i2pd/pull/1662#pullrequestreview-687850246

Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-20 20:03:33 +03:00
84d987810f add afrikaans in config example 2021-06-20 09:36:14 +03:00
fed04c1a19 requsted router to send to if not in netdb 2021-06-19 14:44:33 -04:00
f5e7d87f5b don't disable floodfill if still reachable by ipv6 2021-06-19 14:25:50 -04:00
6ca28adcbb set address caps and available transports for new address 2021-06-18 18:19:05 -04:00
8e5d2e1b73 [readme] add gha container build badge 2021-06-18 17:26:18 +03:00
e8ad7b4f79 rework of storing certificates path (#1642)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-18 10:04:48 +03:00
d3a49e513c remove repeatable type definition, add include (#1642)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-18 06:45:12 +03:00
5bfab0a796 add certsdir option (#1642)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-18 06:38:10 +03:00
idk
739d1aa9e9 Merge branch 'c-wrapper-libi2pd-api' of github.com:eyedeekay/i2pd into c-wrapper-libi2pd-api 2021-06-17 23:32:47 -04:00
idk
e575c6e94d Merge branch 'PurpleI2P:openssl' into c-wrapper-libi2pd-api 2021-06-17 20:20:26 -07:00
idk
7bc2e74683 Get it to build from go build 2021-06-17 23:12:22 -04:00
2185019b59 check if router is reachable by transport before obtaining address 2021-06-17 19:46:05 -04:00
5d097651c1 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2021-06-17 19:11:28 -04:00
81c83f0d54 pick ECIES routers only for non-x64 2021-06-17 19:10:57 -04:00
idk
5013ce5649 Try and figure out why the C Compiler thinks it needs to find iostream when the C++ library has already been compiled. Make the makefile aware of variables in the environment 2021-06-17 18:25:55 -04:00
5e11a03f0a [docker] fallback to alpine 3.13
https://wiki.alpinelinux.org/wiki/Draft_Release_Notes_for_Alpine_3.14.0#faccessat2
2021-06-17 22:41:37 +03:00
e14d358420 [docker] add debug commands
Adding `g++ -dumpmachine` command on build stage to figure out why docker hub is unable to build container.
2021-06-17 22:11:46 +03:00
82bb3a9b25 [i18n] remove comment line in afrikaans
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-17 21:49:39 +03:00
669720d8f5 [gha] build and publish release containers 2021-06-17 21:37:48 +03:00
idk
45ef6cba9d Un-mangle Destination in case we need to somehow pass one to DestroyLocalDestination,RequestLeaseSet, etc 2021-06-17 13:46:57 -04:00
idk
3330d2bb0c Also Extern Identity, Destination, Streaming headers 2021-06-17 13:24:19 -04:00
a97d2bbb63 [gha] publish containers to docker hub 2021-06-17 20:07:10 +03:00
f56f75bb3f [gha] add docker building (#1664) 2021-06-17 19:37:47 +03:00
08a82a0bcd don't try to connect to a router not reachable from us 2021-06-17 12:12:06 -04:00
3dc19bfd31 [gha] docker - disable cache (test) 2021-06-17 11:07:56 +03:00
970f47ce33 [gha] remove context 2021-06-17 11:03:30 +03:00
2ee7ed8dda [gha] temporary build only amd64 container 2021-06-17 10:59:47 +03:00
d058b9a595 [gha] fix repository name to lowercase 2021-06-17 10:38:38 +03:00
1dda832e39 [gha] build docker containers
Build docker containers and publish them to GitHub Container Registry
2021-06-17 10:35:10 +03:00
a6af4908d5 use m_ReachableTransports bitmask 2021-06-16 18:14:33 -04:00
2c7fff077b [gha] add dist name in package changelog
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-16 22:06:48 +00:00
71df1fc4d6 [gha] do not check source archive for deb build
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-16 21:45:14 +00:00
064ecdb5ec [gha] do no check source archive for deb build
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-16 21:40:45 +00:00
8ec4783249 [gha] fetch all history of git repo for packages (needs for describe)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-16 21:34:59 +00:00
f9d378f1ce [gha] add deb building
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-16 21:19:19 +00:00
f07241bff7 add deb building
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-16 21:14:22 +00:00
a6be32392d update debian packaging files
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-16 20:41:41 +00:00
ac594dbd26 Update status badges in README 2021-06-16 19:12:05 +03:00
954711e980 [i18n] pull afrikaans translation from crowdin
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-16 17:57:20 +03:00
2ba3f4758a [i18n] move gettext translation template to contrib
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-16 17:57:20 +03:00
6be4d508f3 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2021-06-15 19:10:23 -04:00
dc75868bd3 check Alice's IP address in PeerTest 2021-06-15 19:09:36 -04:00
c06a560946 [i18n] use xgettext compatible function format for plural
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-16 00:13:26 +03:00
0bacd4df5f [i18n] update gettext description
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-15 23:44:23 +03:00
b91eaf5487 [i18n] update gettext description
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-15 23:30:28 +03:00
eebea7b342 [i18n] Add translation source in gettext format
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-15 23:22:59 +03:00
29c1173e14 [i18n] fixes in translations
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-15 23:22:11 +03:00
idk
b962a330ad Allow passing raw pointers to C wrapper functions, I think 2021-06-15 12:02:57 -04:00
1d973bc3ac [webconsole] remove extra line break
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-15 17:55:22 +03:00
631c8c9870 use correct address type for NTCP2 acceptors 2021-06-14 21:19:44 -04:00
bce6685d0c correct check of ipv4/ipv6 address 2021-06-14 12:36:54 -04:00
e412b17f70 don't publish slow tunnel in LeaseSet if possible 2021-06-11 08:34:56 -04:00
a92b93192d reg.i2p for subscriptions 2021-06-10 13:24:04 -04:00
8708a0076f fix build with boost < 1.55.0 (closes #1661)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-06-09 22:23:33 +03:00
83fd289e46 don't re-create noise state for every message 2021-06-09 12:49:50 -04:00
idk
ed53cbb7b7 OK that's my first working C wrapper, but I don't yet know how to do anything other than initialize, start, and stop a router 2021-06-08 16:25:45 -04:00
3b051dbba3 send OutboundTunnelBuildReply 2021-06-08 15:36:27 -04:00
8e4781b0f7 tbytes in WinApp (#1660) 2021-06-08 16:39:28 +03:00
d599502b1a 1000Gb+ display 2021-06-07 23:49:56 -04:00
8571830485 create transit tunnel and reply for short tunnel build 2021-06-07 18:28:36 -04:00
48d9a03aa8 tbytes in WinApp 2021-06-07 12:58:57 -04:00
5fb426b336 decrypt and encrypt reply for short tunnel build message 2021-06-06 13:55:38 -04:00
d752a83eb5 handle i2cp.dontPublishLeaseSet for all destinations 2021-06-04 18:28:30 -04:00
e740d5fc4f try to pick non-slow tunnel 2021-06-04 12:16:50 -04:00
8e3e35a36d decrypt short request record 2021-06-02 19:50:29 -04:00
5ce9c0f1e2 build new tunnels instead slow 2021-06-02 14:45:21 -04:00
ef8c4389e1 reachable transports added 2021-06-02 12:55:08 -04:00
0547d590e1 fix typo
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-31 00:24:54 +03:00
be31640010 fix ipv6 preference on linux
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-31 00:23:50 +03:00
39319853ab [i18n] add Turkmen translation
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-30 21:38:14 +03:00
ed42948051 prefer public ipv6 instead rfc4941 (closes #1251)
Wokrs only on linux-based systems. Not tested on other *nix systems, and
not works on windows.

Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-30 03:25:13 +03:00
a0e545a6f1 always create new tunnel from exploratory pool 2021-05-28 12:11:24 -04:00
e77e383efa [docker] add UPnP at compile time (closes #1649) 2021-05-28 18:59:59 +03:00
8ce5ceef59 Correct transaltion for "Firewalled" 2021-05-27 17:47:59 -04:00
3a53e049bd [gha] switch ubuntu to 18.04
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-26 13:43:24 +03:00
5011ecaaa6 [i18n] fix language selection
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-26 13:27:13 +03:00
35b1842a72 [gha] add cmake build on ubuntu
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-26 13:21:15 +03:00
0292227a6b [cmake] switch to glob instead filling sources list
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-26 13:15:17 +03:00
ebce1e34d8 [i18n] enable Ukrainian in source
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-26 12:56:47 +03:00
cc1244126c [i18n] enable Ukrainian in source
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-26 10:50:02 +03:00
bdf63cf82c [i18n] add Ukrainian (#1658) 2021-05-26 10:38:58 +03:00
0275f7f574 [i18n] fix two typos in the russian translation (#1659) 2021-05-26 10:05:10 +03:00
779f2fa451 [i18n] rework localization system
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-25 22:03:29 +03:00
1a4250d8cc [i18n] update russian translation
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-25 00:22:35 +03:00
08fafe267a rekey all routers to ECIES 2021-05-23 17:27:14 -04:00
d06924b339 LeaseSet type 3 by default 2021-05-23 14:28:10 -04:00
585116a51f XMR added 2021-05-23 14:20:23 -04:00
b676d7034f [i18n] update translation
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-23 16:30:42 +03:00
69a0fe3040 pass arg as reference 2021-05-23 08:52:27 -04:00
5207dd4c9e [gha] update freebsd action 2021-05-23 15:43:04 +03:00
919bf4e144 [i18n] add cmake build
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-23 15:39:29 +03:00
7ed440ba75 Merge pull request #1657 from PurpleI2P/i18n
I18n
2021-05-23 08:26:11 -04:00
2db035d23c [i18n] fix addresshelper
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-23 13:16:52 +03:00
a4b84517dc [i18n] rename Russian translation, fix typo
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-23 10:56:20 +03:00
e687773b41 [18n] translate webconsole
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-23 10:50:26 +03:00
df66c2d2dc [i18n] translate HTTP proxy
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-23 06:06:04 +03:00
f321eb66c0 rename DatabaseLookupTageSet to SymmetricKeyTagset 2021-05-22 18:41:25 -04:00
80b44fc9a9 Support multilang, update code
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-22 18:29:05 +03:00
0e68fe4a57 [i18n] start multilang support for webconsole
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-22 08:39:29 +03:00
59b471b9a2 i2cp.leaseSetPrivKey for HTTP and SOCKS proxy 2021-05-20 14:10:31 -04:00
f22eaa6db5 2.38.0 2021-05-16 14:26:00 -04:00
e37244fa0d remove deprecated options from config file example
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-15 16:35:38 +03:00
c359c6e634 update config file example, add v6 status to windows daemon window, code cleanup
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-05-15 16:31:53 +03:00
d299cbaabd Add/Remove subsession 2021-05-13 19:30:54 -04:00
2b22bfadbc show version in hidden content 2021-05-12 11:48:27 -04:00
baec22610e always set expiration time for NSR tagset 2021-05-12 07:57:37 -04:00
43b587636b delete tags of termiated session right away 2021-05-11 18:49:17 -04:00
c6cdb26f47 reduce range for extra tags 2021-05-10 20:20:25 -04:00
1285e30b3e more pre-calculated x25519 2021-05-10 18:55:39 -04:00
a8e1cd9a13 don't throw exception if local bind fails 2021-05-10 11:04:08 -04:00
d6f5640685 attach updated LeaseSet to ECIESx25519 incoming sessions 2021-05-09 07:33:26 -04:00
79dbf2a43e request encrypted LeaseSet if expired 2021-05-07 22:15:12 -04:00
5ad4c2a65e run ipv6 peer test again if still testing 2021-05-04 14:59:25 -04:00
fffa550bb0 SAM subsessions 2021-05-04 14:27:06 -04:00
0b9cb4e75b check identity and signature length for SessionConfirmed 2021-05-03 19:05:25 -04:00
7f143a7f23 support EdDSA for blinding 2021-05-02 15:02:52 -04:00
d8d8a68814 rekey all routers but floodfills 2021-04-30 15:19:31 -04:00
4018cf9d76 SAM single and master sessions 2021-04-26 21:11:36 -04:00
bd33ac202f handle hostname for STREAM CREATE 2021-04-26 18:21:00 -04:00
e091eba831 don't cleanup ipv6 introducers list twice 2021-04-25 17:55:13 -04:00
4a0dbec4fb recognize non-published NTCP2 address 2021-04-25 16:42:09 -04:00
90dee900f0 fixed crash 2021-04-25 10:57:31 -04:00
94555b9c43 don't select next introducers from existing sessions 2021-04-24 14:56:34 -04:00
db93a7315f find new introducers to connect 2021-04-24 11:11:12 -04:00
7a19533380 reuse current introducers if no more available 2021-04-23 12:17:48 -04:00
9d79b26506 check if port if specified 2021-04-22 19:32:47 -04:00
b43a9cc80d handle master session creation 2021-04-21 19:30:20 -04:00
b5618af308 find all introducers at the time 2021-04-21 15:41:04 -04:00
9c8c3b9174 select few introducers at the time 2021-04-21 10:56:39 -04:00
01e591b261 find ipv6 intrioducer session 2021-04-21 09:55:36 -04:00
060e30d283 select ipv6 random introducer 2021-04-21 08:16:13 -04:00
ad019da553 publish ipv6 introducers 2021-04-20 20:02:30 -04:00
69afd3a1da Merge pull request #1651 from acetoneRu/openssl
Уточнение про логирование в Windows
2021-04-19 07:29:33 -04:00
7978adc577 Уточнение про логирование в Windows 2021-04-19 06:43:51 -04:00
ca77ca6ef0 reseed from compatible address 2021-04-18 17:27:50 -04:00
d5b61ed544 select different routers for peer test 2021-04-17 14:33:53 -04:00
5edb256990 check if our external IP is valid 2021-04-16 19:31:49 -04:00
74d0c04314 ipv6 address for relay reponse and relay intro 2021-04-15 16:06:02 -04:00
39d4464be0 make sure that introducer or peer test router is reachable by SSU 2021-04-15 11:43:43 -04:00
be48dc6e87 pick correct local address for intro key 2021-04-13 15:11:37 -04:00
2783337284 require ipv4 for IBGW 2021-04-13 09:16:52 -04:00
727743979c Merge pull request #1648 from acetoneRu/openssl
SAM section fixed
2021-04-13 07:33:07 -04:00
4543e14c57 SAM section fixed 2021-04-13 02:43:42 -04:00
83fc1b0b8e support b32 and b33 addresses in STREAM CONNECT 2021-04-11 17:26:45 -04:00
df858d9143 publish iexp 2021-04-09 13:29:07 -04:00
ac47c9c673 don't check U cap 2021-04-09 10:56:46 -04:00
b9a2d5df02 send HolePunch back based on actual address type 2021-04-08 21:07:14 -04:00
3e873f88c9 don't drop introducers without iExp 2021-04-07 15:55:38 -04:00
277cef5ec4 eliminate cost field 2021-04-07 13:05:38 -04:00
5c9b478e46 published field for SSU addresses 2021-04-05 21:45:48 -04:00
ff89edf127 pick random introducer 2021-04-05 18:22:48 -04:00
2cc9791bf2 exclude already expired introducers 2021-04-04 10:36:22 -04:00
67b32005f6 check if host if unspecified 2021-04-03 22:18:09 -04:00
0f166973ca check ureachable cap and actual introducers separately 2021-04-03 20:03:19 -04:00
4f3333c841 don't check range ffor unspecified address 2021-04-03 19:24:07 -04:00
bea384abea recongnize v4 and v6 SSU addresses without host 2021-04-03 18:56:50 -04:00
43033695f6 select apropriate address for peer test 2021-04-02 21:31:14 -04:00
51ef7ef61c don't publish LeaseSet without tunnels 2021-04-01 13:37:21 -04:00
823b499a02 remove already expired LeaseSets 2021-04-01 11:45:50 -04:00
bb5ed0b40c assign correct 6 or 4 cap to unpublished address 2021-04-01 11:02:29 -04:00
94ca2514af set zero expiration timeout if no tunnels 2021-04-01 10:29:03 -04:00
5412352dec publish ipv6 introducers for ipv6 addresses 2021-03-31 13:42:57 -04:00
c94e8c7df4 Merge pull request #1646 from acetoneRu/openssl
reg.i2p to subscriptions
2021-03-31 12:28:59 -04:00
094541caa6 reg.i2p to subscriptions 2021-03-31 12:16:06 -04:00
8c59977e34 Merge pull request #1645 from acetoneRu/openssl
Configuration file example updated
2021-03-31 12:13:17 -04:00
881bca6ae3 Depricated "nat" deleted 2021-03-31 12:09:06 -04:00
22865f8ee4 reseed.yggurl and persist.addressbook added 2021-03-31 12:05:23 -04:00
f3b728d828 Yggdrasil configuration added
[meshnets] section
2021-03-31 08:45:56 -04:00
bd7328345f Don't change Yddrasil address if router becomes unreachable through ipv6 2021-03-30 19:27:40 -04:00
25eae3c116 return relay tag for ipv6 introducer 2021-03-30 11:31:11 -04:00
5cca5472e6 don't handle unsilicited HolePunch 2021-03-29 15:50:33 -04:00
8462d382f4 don't create SSU session for HolePunch 2021-03-29 15:16:39 -04:00
2b0d18a6d7 don't change router status from ipv6 2021-03-29 14:44:50 -04:00
edf3b7e2fc set X bandiwth for floodfill by default 2021-03-28 13:13:00 -04:00
167d3a0e3c don't create BN_CTX for ECIES tunnel build record decryption 2021-03-28 12:14:02 -04:00
86415bc61f publish introducer cap for ipv6 address 2021-03-27 18:49:35 -04:00
a6ea37a21e set ipv6 address caps depending on peer test 2021-03-27 15:16:56 -04:00
3695aa924b doesn't send peer test to a reserved address 2021-03-24 10:32:15 -04:00
9e050d1a23 peer test for ipv6 2021-03-23 15:36:57 -04:00
34eee2fc26 fixed #1644. check leaseset buffer size 2021-03-22 20:12:58 -04:00
ac10f3055d pick correct local SSU address for sending peer test 2021-03-19 21:51:45 -04:00
991b74f036 bind ipv6 or yggdrasil acceptor to specified address 2021-03-19 13:10:24 -04:00
589049ef0f connect to ipv6 address through introducer 2021-03-19 10:20:02 -04:00
6b0c7c2313 handle ipv6 address in RelayResponse 2021-03-18 21:29:39 -04:00
a9c7d0d598 common ExtractIPAddressAndPort 2021-03-18 20:11:24 -04:00
ef1dfb153c handle ipv6 address for RelayIntro 2021-03-18 18:37:02 -04:00
ff9ee5873f post LeaseSet creation to I2CP destnation's thread 2021-03-17 15:10:14 -04:00
a7b56bbbb7 publish Yggdrasil address when enabled 2021-03-17 11:26:52 -04:00
820a365474 select random peer for first hop for outbound tunnel if number of connections < 100 2021-03-16 18:45:51 -04:00
1d5d06f731 find actual router for peer 2021-03-16 15:23:00 -04:00
43d458cf72 publish and upublish NTCP2 and yggdrasil addresses separatly 2021-03-16 13:08:10 -04:00
436a3e7f54 2.37.0 2021-03-15 09:00:25 -04:00
7015bad905 2.37.0 2021-03-15 08:30:04 -04:00
cf8665748b network sattus Mesh added 2021-03-13 10:28:03 -05:00
1b8da90cbb more precise compatibility check 2021-03-12 20:51:12 -05:00
6012585067 eliminate false positive symmetric NAT 2021-03-12 17:41:41 -05:00
f162876600 insert ipv4 address if enabled back 2021-03-12 16:13:01 -05:00
6555ae5b0a support authorization for reseed proxy 2021-03-11 17:02:56 -05:00
f5af059ef4 [webconsole] add submission of address registration line to reg.i2p
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-03-11 15:20:40 +03:00
cb8651ec68 [win32] drop service code, fix start with daemon option. Throw notification when unable to parse config
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-03-11 14:40:06 +03:00
7c0b0a4e3e common HTTP basic authorization string 2021-03-10 22:47:31 -05:00
880d1a7ccd NTCP2 proxy with authorization 2021-03-10 20:00:21 -05:00
744b25190a don't set proxy if ntcp2 is disabled 2021-03-10 15:36:10 -05:00
3792bb4928 delete sig buffer 2021-03-09 22:10:51 -05:00
9049902ced [webconsole] add address registration line generator
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-03-10 01:48:54 +03:00
5f93dc72fd convert ifname* params to address* 2021-03-09 15:28:07 -05:00
09dadd7e01 Merge pull request #1640 from brain5lug/openssl
logging opimization
2021-03-09 07:46:28 -05:00
60b92f98db OBEP must be ipv4 compatible 2021-03-08 18:54:17 -05:00
97f315d488 set correct 4 and 6 caps for unreachable addresses 2021-03-08 15:57:05 -05:00
f3676d7f18 logging opimization 2021-03-08 11:31:00 +03:00
742dbdb68a rekey low badwidth routers to ECIES 2021-03-07 10:07:51 -05:00
2d59c968ca don't publish NTCP2 address connected through proxy 2021-03-06 18:43:50 -05:00
ad22247c9e start other acceptors if connected through a proxy 2021-03-06 15:35:31 -05:00
f38920c338 Status: Proxy 2021-03-06 08:50:47 -05:00
8f90b21a5d fixed typo 2021-03-05 22:40:27 -05:00
ff0e6813c6 fixed typo 2021-03-05 21:53:19 -05:00
fa5e4d57fd correct caps for SSU address without host 2021-03-05 19:40:37 -05:00
876973f071 remove coreVersion 2021-03-05 09:29:28 -05:00
b994af9209 check reachability of floodfill to request from 2021-03-05 08:41:44 -05:00
1f6cde652e check caps for SSU address 2021-03-04 22:47:56 -05:00
3bf6db1c08 enable yggdrasil address finding for android
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-03-05 03:20:12 +03:00
e70ffc9d7c re-shedule introducers updates if router becomes firewalled 2021-03-04 15:55:51 -05:00
065cfe3b9d separate ratchet session for ECIES router 2021-03-03 15:30:13 -05:00
def9873a70 request multiple introducers at the time 2021-03-02 21:10:19 -05:00
618aa26454 allow some unreachable floodfills 2021-03-02 14:13:28 -05:00
924a7bc533 use connected peers if others not available 2021-03-02 12:29:51 -05:00
ef85277a1b select reachable routers for one hop tunnels 2021-03-02 08:46:13 -05:00
876375f2c3 precise bandwidth limit 2021-03-01 22:13:17 -05:00
f70ee480ba check connectivity between peers for tunnel 2021-03-01 19:02:27 -05:00
6d88c3ab05 Symmetric NAT error 2021-03-01 12:20:53 -05:00
57c969b0ed constants for cost 2021-03-01 11:09:25 -05:00
ae58a7007b different cost for direct or with introducers SSU address 2021-02-28 19:19:09 -05:00
11c924bbe7 publish and handle SSU addreses without host 2021-02-28 18:58:25 -05:00
8bab4f60ef open socket before bing 2021-02-28 09:04:34 -05:00
bef9a54f4a bind SSU socket to specified address 2021-02-27 16:13:12 -05:00
288b19c3f7 bind NTCP2 ipv4 acceptor to specified local address 2021-02-27 10:35:50 -05:00
40f7e9d33e separate decryptor for tunnel builds and floodfill requests 2021-02-26 21:02:51 -05:00
fab53dda66 fixed typo 2021-02-26 20:38:16 -05:00
a4e8bf9857 bind NTCP2 connections to specified address 2021-02-26 19:31:38 -05:00
2cdf84cdab [actions] upload windows artifacts 2021-02-26 21:09:01 +00:00
fbe83f729d don't try to send to unreachable router 2021-02-25 19:55:46 -05:00
4371a084ec check for pubkey in X25519Keys::Agree
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-26 03:20:06 +03:00
d13f58088a Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2021-02-24 18:41:31 -05:00
f75bef7c03 don't set local address if not specified 2021-02-24 18:40:24 -05:00
3d7e93a688 systemd: use SIGTERM instead SIGQUIT, indent UPNP code, make client target
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-25 00:37:41 +03:00
a4dda304d2 cancel connect timer upon SessionConfirmed 2021-02-24 10:03:23 -05:00
124c3ef2d7 always publish SSU port 2021-02-23 21:15:17 -05:00
c3a2fca76a 4 or 6 caps for non-published addresses 2021-02-23 19:59:35 -05:00
b60ebfe1c6 parse '4' and '6' address caps 2021-02-22 22:53:25 -05:00
1d7639b3f4 caps per address 2021-02-22 21:04:26 -05:00
2d972752ff lookuplocal 2021-02-21 16:20:57 -05:00
616f0b2a21 address parameter for server tunnels 2021-02-19 15:15:58 -05:00
94659ba890 create ipv4 and ipv6 NTCP2 addresses separately 2021-02-17 21:51:35 -05:00
d65bc068de create ipv4 and ipv6 NTCP2 addresses separately 2021-02-17 21:12:17 -05:00
1ca0354cf2 find NTCP2 address by static key. Don't make router unreachable if can't connect by NTCP2 2021-02-17 18:46:41 -05:00
b1fcd4d27b show actual IP addresses for proxy connections 2021-02-17 14:26:48 -05:00
74aa07eba8 [actions] update freebsd action 2021-02-15 16:21:30 +03:00
d1a98212ee 2.36.0 2021-02-15 07:57:17 -05:00
75a31c79ae don't process SSU messages after termination 2021-02-13 18:36:23 -05:00
da0b36cb91 enable miniupnpc support by default in debian/ubuntu
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-12 15:06:29 +00:00
aa206d034d fixed #1373. Limit number of tunnels by 16 2021-02-11 18:32:03 -05:00
765ab60753 try to reseed if no compatible routers in netdb 2021-02-10 15:27:13 -05:00
44e4ec573d enable NTCP2 transport for newly created routers 2021-02-10 14:59:08 -05:00
0ed793d6d0 [readme] add links to new android and qt repos
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-10 18:09:51 +03:00
272e25ff07 [actions] remove qt build
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-10 17:59:15 +03:00
63127ab181 add yggdrasil address search for windows
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-10 17:58:14 +03:00
004f3532a0 move android binary build files to contrib
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-10 17:57:31 +03:00
abe1af7b4f moved qt and android sources inn separate repositories
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-10 17:00:35 +03:00
01df1647bc [httpproxy] add viewport and update styles on error
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-09 08:32:35 +03:00
9d8eaf0ccb [win32] dont create notification when taskbar (explorer) restarted
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-08 19:41:46 +03:00
7e4c33d27e resend RouterInfo after some interval 2021-02-07 10:39:26 -05:00
c164601acf reseed from clearnet only if ipv4 or ipv6 is enabled 2021-02-06 21:25:16 -05:00
3b32da4f5c don't disable NTCP2 address if Yggdrasil address is presented 2021-02-06 19:07:39 -05:00
1bc3de8df4 add Yggdrasil address without NTCP2 2021-02-06 18:23:50 -05:00
374e0cbbc3 enable NTCP2 server for Yggdrasil 2021-02-06 18:11:34 -05:00
313921da56 publish and request through exploratory tunnel if floodfill is not reachable 2021-02-06 14:49:42 -05:00
2d0e219197 add Yggdrasil adddress even if NTCP2 is not published. Correct reachable capacity 2021-02-05 17:24:11 -05:00
dc64d1738a try both ipv4 and ipv6 SSU addresses if presented 2021-02-04 21:48:13 -05:00
89e8d99294 check availability of particular address 2021-02-03 20:09:43 -05:00
66a238045f Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2021-02-03 14:25:14 -05:00
33b82b5669 check transport compatibility with peer before connecting 2021-02-03 14:24:43 -05:00
f59d509b15 fix rebase result build issue
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-03 15:12:27 +03:00
6966539b86 reindent Datagram, Daemon, update default subscription in config example
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-02-03 14:57:43 +03:00
0e5dc15005 create Yggdrasil address for new router 2021-02-02 21:39:16 -05:00
a74f685a5d check local address 2021-02-02 19:29:13 -05:00
05c7aacfa5 check for NTCP for yggdrasil address 2021-02-01 22:24:51 -05:00
ace80c29e7 meshnets.yggaddress added 2021-02-01 18:00:03 -05:00
bfb1380dd2 don't update Yggdrasil address from SSU 2021-02-01 13:18:48 -05:00
ea19802d3f update right ipv6 only 2021-02-01 12:47:41 -05:00
fef4f13b8f don't insert Yggdrasil address twice 2021-01-31 19:09:38 -05:00
c4fc0f4ecf add Yggdrasil address 2021-01-31 18:30:53 -05:00
ba3acdac75 NTCP2 transports through the Yggdrasil 2021-01-31 17:50:10 -05:00
aad2d68edb NTCP2 transports through the Yggdrasil 2021-01-31 17:25:07 -05:00
9e5935aea5 NTCP2Mesh added 2021-01-30 18:32:17 -05:00
129b4a2135 don't support NTCP1 address in RouterInfo 2021-01-30 16:50:53 -05:00
82649ab2a7 IsYggdrasilAddress added 2021-01-29 13:27:49 -05:00
1ba5d25819 correct detection of chunked response 2021-01-29 12:12:40 -05:00
daa3f8699b don't detect Yggdrasil for android 2021-01-29 09:32:33 -05:00
df7fda9e0c support ratchets for shared local destination 2021-01-29 07:46:20 -05:00
484f69f16b try to select reachable router of inbound tunnel gateway 2021-01-28 13:33:12 -05:00
7c8280934a update addressbook subscriptions
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-01-27 06:48:35 +03:00
85902b358a remove [] from yggdrasil reseed address 2021-01-26 13:43:20 -05:00
5931cb59ab fix thread setname on NetBSD
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-01-26 18:54:41 +03:00
fd73aab7d0 acetone's certificate 2021-01-25 19:53:00 -05:00
d13fbe5549 support reseed throught the Yggdrasil 2021-01-25 19:48:33 -05:00
ed4c00e4f4 check yggdrasil ipv6 range 2021-01-24 21:21:35 -05:00
07282ec39f get local yggdrasil ipv6 address 2021-01-24 19:42:44 -05:00
2d998aba43 fixed typo 2021-01-24 15:44:54 -05:00
2e0019c8c8 check if NTCP2 address is valid before connection attempt 2021-01-24 11:34:11 -05:00
96e9608036 Merge pull request #1623 from rex4539/fix-warnings2
Fix clang warning
2021-01-24 11:23:12 -05:00
9d5bb1b2b6 drop routing path for LeaseSet resend 2021-01-23 21:25:52 -05:00
67dab9b6d2 Fix clang warning 2021-01-21 11:07:01 +02:00
6fc5f88a3b dump addressbook in hosts.txt format 2021-01-20 19:19:34 -05:00
e0cec79ad6 try both ipv4 and ipv6 NTCP2 addresses if presented 2021-01-18 18:58:16 -05:00
1a9e11d86d don't send updated LeaseSet through a terminated session 2021-01-18 12:58:27 -05:00
1235d18d67 pass address to NTCP2 session 2021-01-17 17:15:41 -05:00
8f25b66760 limit tunnel length to 8 hops 2021-01-14 11:24:03 -05:00
2bc0850b0f [android] add refresh on swipe in webconsole
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2021-01-13 21:07:13 +03:00
29176dd9bf count last send time for expiration 2021-01-09 18:59:09 -05:00
aedcd1bcc0 remove tag after tagset expiration 2021-01-07 14:51:23 -05:00
b1262d54de don't detach ECIESx25519 session from destination 2021-01-05 15:56:48 -05:00
bc4a97774f strong pointer to session for receive tagset 2021-01-04 20:15:48 -05:00
ee3cd44f97 ReceiveRatchetTagSet 2021-01-04 18:20:16 -05:00
726bd0d63b check if x25519 key is valid 2021-01-01 15:03:11 -05:00
ce9640773c Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-12-27 11:19:46 -05:00
7ce92118e4 handle follow-on NSR messages 2020-12-27 11:18:53 -05:00
e12c5fe007 Merge pull request #1601 from gxcreator/openssl
Docker: Move DEFAULT_ARGS to Dockerfile .
2020-12-27 14:51:58 +03:00
86ff0d86db check if new tag was created 2020-12-26 17:18:29 -05:00
b4236b04c6 leaset creation timeout 2020-12-25 09:01:55 -05:00
d34dc397e8 changed to 320 tags max 2020-12-24 14:06:34 -05:00
f2e4d5f06c trim behind not affter max generated tags 2020-12-20 19:52:06 -05:00
da7e2f2580 don't send message through non-established session 2020-12-19 15:07:12 -05:00
e07a20a771 Merge pull request #1608 from nonlinear-chaos-order-etc-etal/openssl-custom
qt: log level ui control now synced with core and log pane ui at runtime
2020-12-19 08:45:00 -05:00
ae1b1da342 qt: log level ui control now synced with core and log pane ui at runtime 2020-12-19 21:16:40 +08:00
a61d7fe115 set correct NAME for NAMING REPLY 2020-12-18 20:48:08 -05:00
b4d1e89696 Merge pull request #1606 from nonlinear-chaos-order-etc-etal/openssl-custom
fixes many i2pd_qt issues
2020-12-17 22:02:06 -05:00
a0d90717c3 qt: i2cp server page is now shown, work towards #914 2020-12-18 10:06:57 +08:00
5c2f1f36e8 qt: sam session is now shown at qt->sam sessions, work towards #914 2020-12-18 09:40:58 +08:00
0b084956e6 qt: stream.kill hrefs done - step to completion of #914 2020-12-18 09:04:40 +08:00
8c61e7d227 replace LeaseSet completely if store type changes 2020-12-17 18:58:30 -05:00
d7342586a6 qt: fixes #1593 2020-12-18 07:44:37 +08:00
242e3d007c qt: fixes #1529 2020-12-18 07:17:01 +08:00
d4b6485102 qt: small improv 2020-12-18 06:57:49 +08:00
370ab6307a qt: fixes #1581 2020-12-18 06:34:22 +08:00
83b10fba62 qt: added assert.h - it is needed for ci circumstances 2020-12-18 05:45:11 +08:00
1921bce4c7 Merge remote-tracking branch 'upstream/openssl' into openssl-custom 2020-12-18 05:37:17 +08:00
669fb62a54 qt: fixed great ui pains with tunnels editing 2020-12-18 05:37:01 +08:00
1a5920ee47 Merge pull request #1605 from nonlinear-chaos-order-etc-etal/openssl-custom
qt: visual fixes + fix for #1582
2020-12-17 15:10:57 -05:00
9c6e3ff1d7 qt: fixes #1582 2020-12-18 03:39:08 +08:00
ca78601ada qt: visual fixes 2020-12-18 02:00:57 +08:00
2edce12759 Merge pull request #1604 from nonlinear-chaos-order-etc-etal/openssl-custom
qt: fixes #1180
2020-12-17 12:42:43 -05:00
ccc604c0f4 qt: fixes #1180 2020-12-18 01:13:50 +08:00
d3bf8c2417 data: ignored *.tmp.xml 2020-12-17 23:15:56 +08:00
dc774f0f94 Merge remote-tracking branch 'upstream/openssl' into openssl-custom 2020-12-17 22:58:35 +08:00
f2059947bf Merge pull request #1603 from nonlinear-chaos-order-etc-etal/openssl-custom
qt: added about box
2020-12-17 09:55:37 -05:00
eccd5b6ff0 qt: removed a few debug log lines 2020-12-17 22:45:10 +08:00
776dc7ec52 qt: about box fixed for older qt5 2020-12-17 22:30:14 +08:00
082c4f1104 qt: added about box 2020-12-17 22:17:05 +08:00
06a7e181cd ECIES for new routers 2020-12-15 16:06:32 -05:00
bf91e16b5d gererate specified number of tags if misssing tag 2020-12-15 15:04:20 -05:00
65945b3462 correct offline signature size for close packet 2020-12-13 21:55:51 -05:00
31f0c35077 Docker: Move DEFAULT_ARGS to Dockerfile . 2020-12-13 17:31:53 +00:00
fc2dc9a019 cumulative ACK bitfields 2020-12-12 21:40:07 -05:00
04645aacc4 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-12-12 17:15:34 -05:00
c91a8711e3 encrypted requests to ECIES floodfills 2020-12-12 17:14:58 -05:00
7373dae026 [avx] check if c++ target supports AVX (closes #1600)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-12-12 09:54:07 +03:00
ca3b819151 [avx] check ig c++ target supports AVX
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-12-10 18:32:41 +03:00
ba79b94e06 try to generate missing ECIESx25519 tag in last tagset 2020-12-08 15:16:40 -05:00
bfc3acb834 use correct function for thread naming on OpenBSD
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-12-07 19:47:50 +03:00
ac67cd7f9a add FreeBSD builder for GHA (#1595) 2020-12-07 08:36:06 +03:00
9a2c6a7619 move thread naming to util
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-12-07 06:31:46 +03:00
3100d4f902 move thread naming to util
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-12-07 06:22:30 +03:00
aace200899 don't create paired zero hops tunnel 2020-12-05 08:26:21 -05:00
a843165cb4 try ratchets tag first 2020-12-04 19:15:06 -05:00
36473e3889 add naming to threads
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-12-04 18:37:17 +03:00
e2fcab34b7 deccrypt and handle garlic message for ECIES router 2020-12-03 22:01:58 -05:00
abdf92c084 encrypt message for ECIES router 2020-12-03 19:43:43 -05:00
32fc6482cc moved Noise initializations to Crypto.cpp 2020-12-03 17:58:37 -05:00
ce14ea6fe5 [windows] add file version to installer
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-12-03 09:35:43 +03:00
2f57013e02 [qt] update project file
Some build systems didn't create required folders for object files, so create them manually with additional call of `mk_obj_dir` target.
2020-12-01 05:07:41 +03:00
ad84944d20 [make] change AES support check 2020-12-01 03:55:41 +03:00
0ab95b1b87 2.35.0 2020-11-30 12:50:15 -05:00
58153c3579 [webconsole] fix content block width
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-11-30 04:10:13 +03:00
746f53ba07 use SendBufferQueue for queued messages from I2P 2020-11-29 14:59:34 -05:00
ff971563db cleanup queue after buffers deletion 2020-11-28 22:25:06 -05:00
242fb7db14 terminate I2CP session if destroyed explicitly 2020-11-28 10:09:38 -05:00
ad36738f57 detach session from destination upon termination 2020-11-27 13:37:03 -05:00
c833b16544 check if session expired before generating more tags 2020-11-26 09:15:45 -05:00
1c5b350c2b TCP_QUICKACK 2020-11-23 18:55:48 -05:00
9301e39af7 minimal version for floodfill 0.9.28 2020-11-23 12:49:18 -05:00
86e3b977e4 check I2CP message size 2020-11-22 21:41:27 -05:00
bc330ff0ea update makefiles, license year
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-11-23 01:46:08 +03:00
771480e368 send queue for incoming I2CP messages 2020-11-22 17:36:00 -05:00
c875ff923a random intro key 2020-11-21 18:44:40 -05:00
3dfb44de31 exclude DSA floodfills 2020-11-21 14:27:08 -05:00
2266c3877c update reseeds
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-11-21 19:45:06 +03:00
f4486bc075 take intro key from right address 2020-11-20 21:48:33 -05:00
0436a65baa upddate DSA router keys 2020-11-20 20:31:50 -05:00
30d6bd144b don't replace an adddress by one with DSA signature 2020-11-19 15:41:00 -05:00
d8381e9486 disable encryption to ECIES routers 2020-11-18 18:11:29 -05:00
feaecbe177 own local destination for each 'transient' 2020-11-18 15:02:06 -05:00
85d796f906 [actions] obj directories before make on windows 2020-11-17 21:39:46 +03:00
0a3af12ee9 [make] track changes in includes
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-11-17 17:59:40 +03:00
3925540517 don't update expired tunnels 2020-11-16 12:56:22 -05:00
3b630fe546 fixed race condition 2020-11-16 10:04:38 -05:00
c69c4ae8a0 don't publish too fast 2020-11-15 21:46:49 -05:00
b4369470cb publish updated RouterInfo 2020-11-15 20:05:27 -05:00
4a44b18b97 fixed typo 2020-11-15 19:56:16 -05:00
2bd6daeb8d disable aes/avx for winxp by default 2020-11-16 03:43:54 +03:00
1ae98b7fe1 [webconsole] graceful timer for windows 2020-11-16 03:43:54 +03:00
44ca315c75 don't build tunnels for all pools at the time 2020-11-15 19:38:34 -05:00
af20b13c7a create paired inbound tunnels if no inbound tunnels yet 2020-11-15 17:02:01 -05:00
1f6be38145 wait for publish confirmation or publish to another floodfill 2020-11-15 13:06:02 -05:00
8b3a7486c7 rename CRYPTO_KEY_TYPE_ECIES_X25519_AEAD_RATCHET to CRYPTO_KEY_TYPE_ECIES_X25519_AEAD 2020-11-14 18:28:50 -05:00
62cd9fffa3 Automate AES-NI and AVX detection on runtime, make it default on x86-based systems (#1578)
Rework CPU extensions detection code and build with AES-NI and AVX support by default
2020-11-15 01:31:20 +03:00
7e874eaa7c pre-calculated h 2020-11-12 15:15:02 -05:00
1c7780a423 garlic clove block for router 2020-11-09 15:35:50 -05:00
07b77443dd don't handle TunnelBuild message for ECIES router 2020-11-07 18:28:38 -05:00
4ba1be2dc0 one time garlic encryption for ECIES routers 2020-11-05 21:21:46 -05:00
6362a7bba5 decrypt garlic on ECIES router 2020-11-05 15:27:37 -05:00
1740715c00 correct reply key and IV for ECIES record 2020-11-04 21:04:28 -05:00
21501cbf81 correct MixHash after decryption 2020-11-04 13:31:28 -05:00
d5f3d6111e correct tunnel build record size to decrept 2020-11-04 11:52:33 -05:00
bd04f92087 correct public key for ECIES address 2020-11-03 18:41:27 -05:00
942b2b05e7 correct key for AEAD decryption 2020-11-03 15:53:47 -05:00
b8064b9b4b copy noise state 2020-11-03 15:42:53 -05:00
f94d03465a don't create transit tunnel if decyrption failed 2020-11-03 15:38:25 -05:00
4e7aafeec1 send transit tunnel reply for ECIES router 2020-11-03 15:23:13 -05:00
d820b8036e correct transient signature length 2020-11-03 09:20:14 -05:00
3907c17cf5 handle TunnelBuildMessage for ECIES router 2020-11-02 18:49:07 -05:00
b12fa97a38 32 bytes private key for ECIESx25519 2020-10-29 18:41:21 -04:00
b9b431e82d Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-10-28 21:53:41 -04:00
9f2a2e44a3 common MixHash and MixKey 2020-10-28 21:53:11 -04:00
aaf6c1ea8b [RPM] fix build on fedora >= 33
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-29 01:17:07 +03:00
b2f0278180 [RPM] fix build on fedora >= 33
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-29 01:03:36 +03:00
530eba1b91 [RPM] fix build on fedora >= 33
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-29 00:51:01 +03:00
812d312a9e [RPM] fix build on fedora >= 33
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-29 00:38:47 +03:00
5d256e1d80 don't allow STREAM CONNECT and STREAM ACCEPT in command session 2020-10-28 15:35:39 -04:00
d02a0c9b3a [QT] don't build i2pd with aesni/avx for compatability with arm64
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-28 21:18:02 +03:00
bdbd060229 [QT] create obj dirs before building i2pd
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-28 21:02:41 +03:00
bf04962994 [QT] change i2pd make command
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-28 20:47:16 +03:00
33f2ddb696 [QT] fix build with prebuild i2pd libs
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-28 20:07:28 +03:00
e444519889 excluded appcompat 2020-10-27 16:46:39 -04:00
a47aa8c282 [actions] build i2pd library before building gui 2020-10-27 19:55:48 +00:00
0c29aeb9be [actions] add qt gui builder 2020-10-27 19:40:22 +00:00
2b4a91cc80 [actions] Rename worker and jobs 2020-10-27 19:34:38 +00:00
9ffc4155dd Merge pull request #1567 from nonlinear-chaos-order-etc-etal/branch2
qt .pro now uses libi2pd.a and libi2pclient.a instead of sources
2020-10-27 15:17:33 -04:00
979282a0d4 qt .pro now uses libi2pd.a and libi2pclient.a instead of sources 2020-10-28 03:11:14 +08:00
c63818f355 2.34.0 2020-10-27 12:27:08 -04:00
c400372a79 create new ratchets session if previous was not replied 2020-10-27 08:32:38 -04:00
56f3bdd746 [win32] handle WinAPI errors in SSU
Windows can throw WinAPI errors which are not handled by boost asio

Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-27 11:52:02 +03:00
cc0367b079 always send STREAM STATUS reply to STREAM FORWARD 2020-10-26 16:06:19 -04:00
e41bbcb2bb handle SILENT for STREAM FORWARD 2020-10-26 11:19:37 -04:00
b35f43d79e initial implementation of STREAM FORWARD 2020-10-25 17:20:15 -04:00
e9f11e204e check if session is terminated before send 2020-10-24 21:22:48 -04:00
1b63c9f6ad Merge pull request #1564 from nonlinear-chaos-order-etc-etal/openssl
android fixes
2020-10-24 19:12:43 -04:00
21d99e355c MixHash(sepk) added 2020-10-24 15:48:56 -04:00
f0adbcd5e1 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-10-24 12:40:40 +08:00
bfcf3cfbf1 Fixes #1563 2020-10-24 12:40:22 +08:00
ef5495bfb2 padding for x25519 crypto key 2020-10-23 22:14:00 -04:00
c93ee0d65d tunnels through ECIES routers 2020-10-23 15:53:22 -04:00
db3e48a81a android: more logical daemon state changes 2020-10-24 03:52:53 +08:00
d9b87e877d Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-10-23 21:41:58 +08:00
b6175132eb android: fix for pre-init jni calls; processAssets moved to a logical place 2020-10-23 21:41:42 +08:00
57d6c7a3b3 Added TunnelConfig.cpp. Removed CryptoWroker.h 2020-10-22 21:06:23 -04:00
d65a282e9d check routers with non ElGamal encryptions for lookup, publish and tunnel build 2020-10-22 18:34:15 -04:00
801ecaa41c temporary exclude routers with non ElGamal crypto types 2020-10-21 19:03:51 -04:00
49bf735c22 don't set destination to routers 2020-10-21 18:59:16 -04:00
cb55944ff6 Merge pull request #1562 from nonlinear-chaos-order-etc-etal/openssl
qt: socks outproxy enabled checkbox added; visual fixes; socks defaults fixes
2020-10-21 13:03:14 -04:00
9c225f8d77 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-10-22 00:36:18 +08:00
365fce922c qt: socks defaults fixes, socks outproxy enabled checkbox added; visual fixes 2020-10-22 00:35:59 +08:00
fbfc5ecda3 Merge pull request #1560 from nonlinear-chaos-order-etc-etal/openssl
qt: newer options added from docs + visual fixes
2020-10-21 07:42:25 -04:00
4001f48a28 qt: visual fixes & more 2020-10-21 18:12:39 +08:00
22124c25d1 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-10-21 14:46:55 +08:00
17f5bcbd1c qt: newer options added; not tested 2020-10-21 14:46:31 +08:00
b7ebb3ea3d [android] support NetworkCallback for network state changes
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-20 19:38:49 +03:00
387830e07a encyption type 0,4 by default for client tunnels 2020-10-19 18:26:01 -04:00
da94d40738 check if session is terminated before receive 2020-10-18 14:39:58 -04:00
417b5ed6cc handle SSU v4 and v6 messages in one thread 2020-10-14 21:06:51 -04:00
005581ef62 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-10-14 23:30:44 +08:00
050390c5c4 qt: all new general options added from docs 2020-10-14 21:37:39 +08:00
2648f1ba89 [workflow] install required packages 2020-10-14 08:14:33 +03:00
d9d31521f9 [workflow] add windows build 2020-10-14 08:06:22 +03:00
8e24d1b909 [workflow] change options order
Apply name for job, not for step.
2020-10-14 07:44:22 +03:00
36fc0daa12 [workflow] use latest boost from PPA 2020-10-14 07:36:16 +03:00
44d3854a13 [workflow] use sudo when installing packages 2020-10-14 07:24:02 +03:00
1dbc35f13d fix workflow 2020-10-14 07:22:00 +03:00
11691fb44a create GH workflow
Add workflow to build on ubuntu with make
2020-10-14 07:20:26 +03:00
acc5592f59 create DH keys for SSU session directly 2020-10-13 21:12:52 -04:00
614921276e [appveyor] update configuration to support cache (#1559) 2020-10-13 15:33:27 +03:00
3f45a11f12 [SSU] handle ICMP responses
Windows network stack can forward ICMP to socket and simple deleting of
packet can cause socket death. Same thing can happen on other systems
but without socket death.

Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-13 15:22:39 +03:00
e3464add50 don't create new tunnels if offline 2020-10-12 17:15:17 -04:00
18bb4a71c2 fix incorrect chars in variable
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-12 18:27:25 +03:00
85e9da82b0 [transports] validate IP when trying connect to remote peer for being in reserved IP range
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-12 14:56:17 +00:00
99d046ca11 [http] handle WebDAV methods
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-12 07:31:57 +03:00
0b372a344c [webconsole] change error status print format
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-10-12 07:29:46 +03:00
ffa0f0afd9 check network status 2020-10-11 17:51:40 -04:00
e21dac21c8 fixed #1557. don't try to send empty message 2020-10-11 14:02:12 -04:00
0108745065 qt: bool optionValuePresent removed 2020-10-08 15:11:55 +08:00
e2a1cd12c3 don't delete unreachable routers if too few 2020-10-07 21:13:26 -04:00
f6ff232106 qt: crypto type added 2020-10-07 23:16:06 +08:00
b0c690d836 qt: build* added to .gitignore 2020-10-07 19:25:02 +08:00
7246624983 list of headers to remove 2020-10-06 19:24:03 -04:00
471c46ad8e remove some HTTP headers from response 2020-10-06 16:22:40 -04:00
59032d515b i2p.streaming.answerPings=false by default for client tunnels 2020-10-04 19:52:12 -04:00
d218c9a983 disable ntcpproxy 2020-10-04 10:12:33 -04:00
243f6e755b restore copyright header 2020-10-04 09:34:15 -04:00
67b76809ea [appveyor] rewrite mirrorlist after updating runtime
If pacman was updated on runtime update, changes which we domne earlier will be rewrited by config from package
2020-10-04 09:57:45 +03:00
77231bfc6c [appeveyor] rewrite mirrorlist (testing)
https://github.com/msys2/MINGW-packages/issues/7084#issuecomment-703211308
2020-10-04 09:53:31 +03:00
e614226926 [appveyor] change repository disabling way (testing) 2020-10-04 09:39:40 +03:00
65e15d74fc [appveyor] print mirrorlist (testing) 2020-10-04 09:32:21 +03:00
7ceb81cc83 [appveyor] clean packages cache after disabling mirrors 2020-10-04 09:16:43 +03:00
d3f7eea0a3 [appveyor] Disable unavailable repository
Ref: https://github.com/msys2/MINGW-packages/issues/7084
2020-10-04 09:05:57 +03:00
c2f13a1496 some cleanup 2020-10-03 22:29:52 -04:00
faae2709d9 removed NTCP 2020-10-03 21:58:20 -04:00
d595006d1f Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-10-03 18:46:40 -04:00
a8d23b5439 disable NTCP for good 2020-10-03 18:46:12 -04:00
cfda807057 [appveyor] use different mirror for keyring
Default repo mirror is not available, changed to other one.
2020-10-04 00:45:30 +03:00
c601a2986f [appveyor] test without manual keyring installation 2020-10-04 00:35:12 +03:00
8483464aab don't attach our RouterInfo to router's request 2020-10-03 17:20:04 -04:00
dca69e9b6e Merge pull request #1555 from zamabuvaraeu/patch-1
Update Win32NetState.h
2020-10-03 17:15:50 -04:00
9450dc84da Update Win32NetState.h
QueryInterface должна увеличивать счётчик ссылок.
2020-10-04 03:32:02 +07:00
3a2724ec58 single thread for I2CP 2020-10-02 13:13:27 -04:00
ee84291997 handle i2p.streaming.answerPings properly 2020-09-30 19:06:13 -04:00
fd9229c467 ping/pong for streaming 2020-09-30 17:12:28 -04:00
ac5a4fe70f [appveyor] remove tasklist print 2020-09-28 04:51:13 +03:00
873b4f3178 [appveyor] suppress error code 2020-09-28 04:48:57 +03:00
beb5d26e6d [appveyor] kill gpg 2020-09-28 04:44:18 +03:00
221b7cbf76 [appveyor] kill bash before second try
Ok, just waiting for bash termination doesn't works, so lets kill it.
2020-09-28 04:29:43 +03:00
7d34f1e883 [appveyor] add delay before second try 2020-09-28 04:20:18 +03:00
208707c00b [appveyor] install keyring package without question 2020-09-28 04:11:40 +03:00
cb41c04551 [appveyor] install keyring package without question 2020-09-28 04:10:11 +03:00
730c6aff11 Update appveyor.yml 2020-09-28 04:08:39 +03:00
3d40c7603d Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-09-27 20:51:34 -04:00
dec7a9a01c shared transient destination between proxies 2020-09-27 20:50:57 -04:00
5f42888b61 [appveyor] disable fix introdued in 7864053 2020-09-28 03:43:47 +03:00
489c38ec5b read Last-Modified 2020-09-27 19:19:48 -04:00
949fc47f31 two tunnels for shared local destination 2020-09-27 19:07:58 -04:00
4d85079372 correct addressbook request 2020-09-27 17:46:15 -04:00
335f9394a5 drop gcc 4.7 support 2020-09-26 19:32:19 -04:00
f939a7b349 reduce variable tunnel build length to 4 2020-09-21 19:22:53 -04:00
09fdb068d2 Database lookups from ECIES destinations 2020-09-19 21:15:42 -04:00
024c29b180 eliminate boost/bind 2020-09-17 21:11:46 -04:00
2b0d1a2190 implement DatabaseLookupTagSet 2020-09-15 19:39:18 -04:00
d0d71c93af set LeaseSet type to 3 for ratchets if not specified 2020-09-10 19:27:29 -04:00
da1e52357f delete symmkey on cleanup 2020-09-08 07:46:55 -04:00
a05a54b38e trim behind ECIESx25519 tags 2020-09-07 18:45:05 -04:00
a0685d804d 2.33.0 2020-08-24 12:48:09 -04:00
954781262c 2.33.0 2020-08-24 12:27:39 -04:00
0777bad2c3 [webconsole] fix warning, mobile page width
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-08-23 22:26:26 +03:00
3159b06988 reseeds update 2020-08-15 13:53:49 -04:00
e7ff6fbffc don't save invalid addreses 2020-08-14 09:54:31 -04:00
6fec92c012 shared transient addresses 2020-08-10 17:49:46 -04:00
e50abbb250 avoid replay upon SSU packet resend 2020-08-08 19:01:55 -04:00
8e25226574 use unordered_map for incomplete and sent messages 2020-08-08 13:34:27 -04:00
9636d82b37 MixHash for SessionConfirmed processing 2020-08-03 18:31:03 -04:00
c3aa6b9cda use delivery type local if destination is not secified 2020-07-29 17:47:46 -04:00
3ef8b3dcbb don't send repliable datagram after less then 100 milliseconds 2020-07-24 20:44:01 -04:00
c41554109b change datagram routing path if nothing comes back in 10 seconds 2020-07-15 16:20:35 -04:00
67b94d3533 unordered_map for RouterInfos and LeaseSets 2020-07-07 15:38:20 -04:00
d52c0633c8 Merge pull request #1544 from wipedlifepotato/openssl
whitelist synonim for accesslist
2020-07-06 19:04:21 -04:00
4e4c117023 whitelist synonim for accesslist 2020-07-07 02:01:56 +03:00
cb0d30cf42 Merge pull request #1 from PurpleI2P/openssl
pull
2020-07-07 01:47:28 +03:00
2d65402ced [webconsole] update styles
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-07-05 10:05:11 +00:00
e15b2cc5d6 [webconsole] rework lists with tunnels, transit, etc
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-07-05 10:05:11 +00:00
c024905d56 Merge pull request #1542 from nonlinear-chaos-order-etc-etal/openssl
Android.mk : openssl-1.1.1d-clang instead of openssl-1.1.1a-clang
2020-07-05 09:48:43 +00:00
6f17624742 Android.mk : openssl-1.1.1d-clang instead of openssl-1.1.1a-clang 2020-07-05 12:59:31 +08:00
6f2e6ed887 key for next send ratchet 2020-06-30 15:05:17 -04:00
5f1e66d64b use pre-calculated x25519 ephemeral keys for ratchets 2020-06-30 13:00:41 -04:00
1f31fdc257 pre-calculate ephemeral keys for x25519 2020-06-29 20:02:09 -04:00
df9965e129 use unordered_map for peers 2020-06-29 18:19:31 -04:00
61e9c31f0d don't hold RouterInfo after successive connect 2020-06-24 11:29:54 -04:00
a0b35ebd3e mark NTCP2 unreachable routers 2020-06-22 22:32:18 -04:00
951ec567c7 don't try to connect though teminated local destination 2020-06-17 21:06:35 -04:00
31494267e5 fixed datagram idle crash 2020-06-17 14:24:25 -04:00
70e4cbc023 differentiate UDP server sessions by port 2020-06-15 20:10:47 -04:00
8d903a09e2 [Docker] drop boost-python2 2020-06-14 22:18:41 +03:00
63451fb781 Merge pull request #1535 from komachi/apparmor-fixes
Improve AppArmor profile
2020-06-14 16:30:08 +00:00
1e609acb03 keep sending through first successive routing path 2020-06-14 11:16:08 -04:00
69194118df generate random padding length in bulk 2020-06-13 21:24:16 -04:00
0f309377ec Improve AppArmor profile
- give it a name
- import needed abstractions
- allow local additions
- cleanup
2020-06-13 20:46:17 +00:00
49a19a52c8 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-06-13 16:18:41 -04:00
1a39f7e5c6 GarlicRoutingPath per session 2020-06-13 16:18:12 -04:00
a5fed64f38 [webconsole] update sliders html and css
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-06-13 18:33:39 +03:00
79858d4372 [webconsole] adaptive styling
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-06-13 18:19:24 +03:00
61897ae16c crypto.ratchet.inboundTags 2020-06-12 20:42:54 -04:00
5e0a8ed232 set UDP receive buffer size 2020-06-12 16:06:07 -04:00
5993cc857a start new tunnel message if remining is too small 2020-06-12 16:03:12 -04:00
6a0174293e send raw datagrams in opposite direction 2020-06-11 22:04:32 -04:00
44bb8f6f16 allocated datagram I2NP from memory pool 2020-06-10 21:19:37 -04:00
a33cad4b70 eliminate datagram send timer 2020-06-10 11:57:40 -04:00
0639cce784 [SAM] fix ECDSA signatures names
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-06-10 05:11:26 +03:00
a8f227f759 send raw follow-on datagrams 2020-06-09 21:48:47 -04:00
f077836bf5 store DatagramSession for bulk 2020-06-09 19:20:24 -04:00
6d7847f2df send bulk datagrams 2020-06-09 16:26:45 -04:00
221c14cf0e don't lookup UDP session if port was not changed 2020-06-07 16:24:11 -04:00
6735b2686b set LeaseSet2 for ECIESx25519 2020-06-05 15:41:30 -04:00
55ff6beb7d don't create ECIESx25519 again if key was not changed 2020-06-05 09:23:50 -04:00
4ae41513ac save new session with NSR tagset 2020-06-04 18:19:38 -04:00
438a225487 pass calculatePublic 2020-06-03 19:58:36 -04:00
e135696530 support multiple encryption keys through the I2CP 2020-06-03 16:05:19 -04:00
9135772f89 2.32.1
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-06-02 19:26:36 +03:00
0dc212d97c fixed non-updating LeaseSet1 2020-05-28 13:46:02 -04:00
45e8d5c50e Return deprecated websocket config options for compatibility
Closes #1523

Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-27 21:29:00 +03:00
37ec90c436 don't gererate more tags for detached session 2020-05-26 16:47:45 -04:00
010541197c Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-05-25 21:41:17 -04:00
bdb918cdb3 honour explicitPeer param in tunnels 2020-05-25 21:40:46 -04:00
64c986ebbb [RPM] update spec files
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-25 23:01:02 +03:00
a4c4bf4b58 [RPM] update spec files
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-25 22:30:18 +03:00
60b1b2ca4a [RPM] update spec files
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-25 21:23:02 +03:00
8e0f1de25a 2.32.0 - [RPM] fix build in fedora copr
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-25 20:30:48 +03:00
dba6d68108 update debian patch
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-25 13:45:46 +00:00
d226834eef update debian patch
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-25 13:33:02 +00:00
2facf14443 fix symbolic link
Signed-off-by: r4sas <r4sas@i2pmail.org>
2020-05-25 13:09:02 +00:00
6bd44f0e4b 2.32.0
Signed-off-by: r4sas <r4sas@i2pmail.org>
2020-05-25 13:06:11 +00:00
1dcb878796 update debian and rpm stuff to 2.32.0
Signed-off-by: r4sas <r4sas@i2pmail.org>
2020-05-25 12:44:34 +00:00
0e0169d22b 2.32.0 2020-05-25 08:37:47 -04:00
50c8a84037 [SOCKS] overwrite connection info after establishing connection to i2p host (closes #1336)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-25 03:53:54 +03:00
1975adc48f print remote peer for queues 2020-05-24 14:14:16 -04:00
71564f0d10 set default i2cp.leaseSetEncType=0,4 for http and socks proxy for android 2020-05-24 10:30:00 -04:00
5a32082624 recreate session after 90 seconds incativity 2020-05-23 15:58:11 -04:00
45aa78d953 revert 7133a07 - it broke usage in some SOCKS implementations
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-23 20:40:27 +03:00
86e8614934 allow session restart after 2 minutes from creation 2020-05-23 10:20:22 -04:00
ead89c767a compress longer RouterInfo 2020-05-22 18:32:44 -04:00
8bae4975fb add copyright headers
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-22 18:14:53 +00:00
7a5146ea74 fix code syle(spaces->tabs, tabulations)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-22 18:14:53 +00:00
9633c247f0 [readme] update docker badges 2020-05-22 19:34:42 +03:00
78640532e1 [appveyor] add build fix (#1520)
Add fix due to msys2/MSYS2-packages#1967
2020-05-22 16:01:25 +03:00
46ee427ee3 common header for repliable datagrams 2020-05-21 21:54:00 -04:00
0c2b0081b5 rollback 2020-05-21 19:38:25 -04:00
f133a7f9fd resend outstading packets again 2020-05-21 18:58:28 -04:00
a6c9ee446a LeaseSet and encryption type for http and socks proxy 2020-05-21 15:36:16 -04:00
153aaa6d21 no compression for RouterInfo gzip 2020-05-21 15:33:12 -04:00
e5901dad91 resend not more than half of window 2020-05-21 14:52:44 -04:00
9318388007 [apparmor] add one more resolv.conf path (reported by user with ubuntu 18.04)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-20 22:30:02 +03:00
bdd75e1171 build client tunnels through router with version >= 0.9.36 2020-05-20 14:59:18 -04:00
7d22ddd710 Merge pull request #1453 from donarrock/patch-1
Update Dockerfile
2020-05-20 12:24:29 +00:00
7e82c8e279 Merge pull request #1394 from zetok/service 2020-05-20 09:57:51 +00:00
db6a0e6ad9 [cmake] remove windows build support (#1517)
Removes support for MSVC, MSYS, MinGW and included NSIS installer in cmake
2020-05-20 12:17:54 +03:00
648d035a0f GzipNoCompression for datagrams 2020-05-19 21:02:32 -04:00
7ebf2f010c shorter padding for optimal packet length 2020-05-19 19:03:12 -04:00
3db4421aa7 don't invoke gzip for decompression if no compression 2020-05-19 10:48:23 -04:00
9fb59e128b resubmit updated LeaseSet if not confirmed 2020-05-18 22:31:36 -04:00
c7c6e5917a Streaming MTU size 1812 for ECIESX25519AEADRatchet 2020-05-18 20:45:25 -04:00
7b418b3adf insert whole message to queue 2020-05-18 17:51:45 -04:00
1c8d662e30 don't add padding for optimal packet size 2020-05-18 16:42:06 -04:00
d4bfeab36c pass gzip parameter to UDP tunnels 2020-05-18 12:01:13 -04:00
e1b1032df9 reseeds update 2020-05-18 08:29:09 -04:00
329439d0ae don't copy datagram payload 2020-05-17 16:49:31 -04:00
0b1cfb2102 send response to recived datagram from ECIESX25519AEADRatchet session 2020-05-16 19:10:17 -04:00
1e4d2fd053 fixed for g++10 2020-05-14 15:45:25 -04:00
716378bd6b [makefile] fix build with g++ 10
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-14 21:53:40 +03:00
de48d3aaec Merge pull request #1515 from BOPOHA/logrotate_config
added logrotate config
2020-05-14 18:04:51 +00:00
b5b195e628 [windows] fix msys build
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-14 20:59:52 +03:00
23be4c01df CreateLeaseSetClove 2020-05-13 18:09:26 -04:00
86782f3479 eliminate extra buffer allocation for incoming packets 2020-05-12 18:30:04 -04:00
a96c205830 allow encryption type param for encrypted LeaseSet 2020-05-08 14:20:13 -04:00
9274881c18 update logrotate config for reusing in debian 2020-05-08 18:45:28 +02:00
24c5f07153 added logrotate config 2020-05-07 12:11:30 +02:00
789ff702ac fixed sudden webconsole hangs 2020-05-06 14:54:41 -04:00
9b6facf3b0 fixed crash of encrypted leaseset without authentication 2020-05-06 14:08:54 -04:00
d503190647 fixed crash of encrypted leaseset without authentication 2020-05-06 10:08:01 -04:00
c4d9c03930 handle termination block 2020-05-05 13:01:23 -04:00
d7d70b707f configurable throw function 2020-05-05 11:13:59 -04:00
dbe1e3f577 ThrowFatal function 2020-05-05 10:16:16 -04:00
bb7f03857c ThrowFatal function 2020-05-05 09:35:41 -04:00
53b43353eb fixed formatting 2020-05-05 08:27:56 -04:00
b197556447 remove dependency from Win32App 2020-05-05 08:11:01 -04:00
42d4781a96 [windows] add binding exceptions messagebox notifications, update exceptions handling code
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-05 02:45:25 +03:00
d991cc3b96 [services] handle binding errors in tunnels, webconsole
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-04 18:19:38 +03:00
4d48d35ad7 [SSU] handle socket binding errors
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-05-04 18:12:23 +03:00
b7ba8f8e93 precalculate initial h and ck 2020-05-03 13:23:08 -04:00
dff510c181 set best compression for RouterInfo 2020-05-03 09:27:17 -04:00
1eead0e885 GzipNoCompression witout zlib calls 2020-05-02 21:18:44 -04:00
e301387896 don't calculate checsum for Data message send through ECIESX25519AEADRatchet session 2020-05-02 11:13:40 -04:00
c49e544781 allow longer families 2020-05-01 14:30:56 -04:00
d48db501e0 max payload is always 1730 2020-05-01 07:33:05 -04:00
ec4e17f75c cleanup previous tagsets 2020-04-30 21:27:35 -04:00
17e69e67b1 create additional tags for NSR tagset 2020-04-30 15:38:15 -04:00
c4f9f7da06 fixed warning 2020-04-30 13:45:26 -04:00
c367476036 [webconsole] fix printing information about ECIESx25519 tags/sessions
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-30 16:21:49 +03:00
f5712c4198 remove not needed initialization for pointer
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-30 04:59:05 +03:00
1aa0da3382 [NTCP2] fix socks proxy support
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-30 04:47:32 +03:00
27d69894d4 show ECIESx25519 session and tag on the web console 2020-04-29 20:50:31 -04:00
7133a07f38 [SOCKS] wrap DNS type requests response as IPv4 (fixes netcat usage, closes #1336)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-30 01:53:07 +03:00
627d8cfe69 correct timestamp check for LeaseSet2 2020-04-29 17:11:48 -04:00
16b992d705 update info about pidfile defaults (closes #1136)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-29 16:55:25 +03:00
3d9c844dca handle out of order NSR 2020-04-28 22:03:13 -04:00
c0de9455bb [android] stop immediatly if no transit tunnels available while graceful shutdown
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-29 02:16:31 +03:00
65e1871cd7 new tag for each NSR 2020-04-28 18:23:13 -04:00
0a431594f8 [Log] Change default loglevel (closes #1230)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-29 00:56:43 +03:00
7b22ef4270 create incoming NSR tagset 2020-04-28 14:47:53 -04:00
f77a58b2dc set some ECIESx25519 params 2020-04-27 18:53:02 -04:00
142a138cfc store previous reverse key 2020-04-27 09:35:02 -04:00
e6fdf5ad8d [Log] create logfile even if loglevel is "none"
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-27 13:59:00 +03:00
5700e18257 [FS] read tunnels configs which ends with .conf only
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-27 13:23:29 +03:00
50a77fedca removed trivial check 2020-04-26 19:37:00 -04:00
51e3d5f7bc create next tagset 2020-04-26 19:27:31 -04:00
7f859978dd [webconsole] Add runtime transit limit changer, fix button CSS
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-26 23:45:30 +03:00
d8134e8a21 handle and send next key message without public key 2020-04-25 21:09:03 -04:00
614d91e0b1 send same next key reponse 2020-04-25 14:45:53 -04:00
30067fc7d7 handle next key forward 2020-04-24 21:36:08 -04:00
ec29597dbd associate tagset for ECIESx25519 tags 2020-04-24 15:46:02 -04:00
ad211a63f3 check if number of peers to exclude doesn't exceed 512 2020-04-23 15:22:07 -04:00
6b596bd05f check ECIES flag for encrypted response 2020-04-21 15:14:03 -04:00
510b85fd23 try ECIESx25519 tag first 2020-04-20 19:37:46 -04:00
e3c8f3fd6f use ack request instead DeliveryStatus for LeaseSet confirmation 2020-04-19 15:00:51 -04:00
f9175db28e store intermediate symmetric keys 2020-04-16 21:30:18 -04:00
f4798d05e7 persist multi encryption keys 2020-04-15 22:04:18 -04:00
a2a0f62135 multi crypto keys in i2cp.leaseSetEncType 2020-04-15 18:01:01 -04:00
d923f0e01b support two encryption keys 2020-04-14 19:12:44 -04:00
2fc16ee13d indetification of incoming garlic messages 2020-04-13 20:00:19 -04:00
152e579f7e [windows] update flag on connectivity state changes, CRLF > LF
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-12 06:02:26 +03:00
90914bb2de [windows] init internet connectivity events checker functional (vista+ supported only)
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-12 05:25:22 +03:00
95fa835191 [android] update strings, menus, add reloading tunnels item
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-11 23:28:45 +03:00
4e37df26a3 2.31.0
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-10 20:33:54 +03:00
5e606573b1 2.31.0 2020-04-10 12:57:47 -04:00
b3974cb52a [webconsole] security hardening headers (closes #1464)
Signed-off-by: r4sas <r4sas@i2pmail.org>
2020-04-10 02:34:47 +00:00
b7c206c44b replace by new incoming session 2020-04-09 15:00:38 -04:00
49c1e47736 correct termination if session already exists 2020-04-08 18:02:12 -04:00
4e1319d874 handle ECIESFlag in DatabaseLookup at floodfill 2020-04-07 11:40:18 -04:00
a9436aa9af drop i2lua
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-03 14:31:38 +03:00
d503f07564 suppress GCC 7 (bug 77728) psabi note
Suppresses messages like that:
    note: parameter passing for argument of type <...> will change in GCC 7.1

Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-04-03 14:31:38 +03:00
aa7750bfd3 keep sending new session reply until first established session message received 2020-04-02 21:48:39 -04:00
8872d1f389 mutex for m_RemoteIdentity 2020-04-01 09:54:10 -04:00
f21af4068f preferred crypto type for Decrypt 2020-03-31 17:35:51 -04:00
f4ca6bbb52 fixed race with identity verifier 2020-03-30 19:27:10 -04:00
869d0156ce handle Ack request 2020-03-26 19:03:38 -04:00
744e893dce check message length 2020-03-23 18:09:57 -04:00
fe9ac10f02 generate new tags based on last received index 2020-03-22 21:21:12 -04:00
6fb80f226a reopen socked and restart receiver on exception 2020-03-22 08:14:20 -04:00
ff19bab800 set only key correctly 2020-03-21 16:21:51 -04:00
962c2160c7 set actual LeaseSet2 buffer size 2020-03-20 17:43:37 -04:00
168da33d8b add comma
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-03-20 18:43:54 +03:00
b6b25dc9f3 update log messages
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-03-20 17:51:55 +03:00
3ca17fdc03 support multiple encryption keys 2020-03-19 18:33:42 -04:00
2249708097 [webconsole] remove excess tag
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-03-19 02:34:45 +03:00
2fcaa7d260 [webconsole] rework spoilers; print tags, leases, router info in table
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-03-19 02:27:07 +03:00
f3b0e57a54 publish multiple encryption keys 2020-03-18 18:03:03 -04:00
5da92437a1 set msg type for deliverystatus 2020-03-16 16:41:07 -04:00
b5bc05ac2b delete unconfirmed LeaseSet and DeliveryStatus 2020-03-14 16:35:34 -04:00
45145fa50a add ECIESX25519AEADRatchet session to delivery status 2020-03-14 09:33:48 -04:00
dd8200e8b0 cleanup websocks
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-03-12 03:50:21 +03:00
2f56547d5f Merge pull request #1477 from PurpleI2P/drop-websockets
drop websockets support
2020-03-11 12:37:38 +00:00
82bdcfbbcb Merge pull request #1491 from nonlinear-chaos-order-etc-etal/openssl
qt: delayed save in background. should be better ui experience
2020-03-10 11:39:07 -04:00
0e38e43315 some qt work. fixed on slow computers; now faster as delayed save is implemented 2020-03-10 23:22:49 +08:00
63746be4d5 resolve i2pd_qt.pro conflict 2020-03-10 21:50:57 +08:00
ee73ee365f some work on qt 2020-03-10 21:49:04 +08:00
3c53479864 update LeaseSet for ECIESX25519AEADRatchet sessions 2020-03-08 20:58:59 -04:00
4adc741de3 send DeliveryStatusMsg for LeaseSet 2020-03-08 18:13:41 -04:00
64da62dbe6 alsways store latest symmkey 2020-03-07 18:46:40 -05:00
dd9b5faa5c fixed crash on termination 2020-03-05 18:44:15 -05:00
51d018acc6 webconsole: add stream closing
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-03-05 04:14:39 +03:00
5eec580727 delete strem from destination upon termination 2020-03-04 18:31:22 -05:00
1e9a53da3f delete stream by id for HTTP interface 2020-03-04 15:54:09 -05:00
8dae044600 Merge pull request #1441 from noraj/patch-1
README: explicit linux distro supported
2020-03-03 18:07:01 +00:00
2d3fad2cdb correct proxy buffers 2020-03-02 16:24:00 -05:00
a59a8f62ca Merge pull request #1479 from wipedlifepotato/openssl
Pre init webview button. (android)
2020-03-01 21:17:14 -05:00
35cfa7d9fb Merge branch 'openssl' of github.com:wipedlifepotato/i2pd into openssl 2020-03-02 05:06:06 +03:00
c6ccb373a2 del geti2pdpath 2020-03-02 05:04:37 +03:00
b6368170ed Update README.md 2020-03-02 04:00:28 +03:00
35e8424293 preinit webview+configparser+README.md
tabulation fixes

configparser to comments

dont need

pre init webview

readme changes

delete submodules

webview in main menu

webview pre init

delete modules

delete submodules
2020-03-02 03:58:50 +03:00
e969d58689 handle ntcp2.proxy parameter 2020-03-01 15:11:54 -05:00
ae20e3aa95 NTCP2 proxy 2020-03-01 11:24:18 -05:00
de4cb74173 Merge pull request #1478 from unlnown542a/openssl
add ntcp2proxy support
2020-03-01 10:04:27 -05:00
4f0da87a7a add ntcp2proxy support 2020-03-01 14:35:24 +00:00
97f0347715 Update android stuff:
* switch to c++17
* use boost 1.72.0
* disable minify in release
* enable apk splitting (separate apk for every ABI)
* add version to output apk name

Signed-off-by: r4sas <r4sas@i2pmail.org>
2020-02-29 23:14:35 +00:00
2ffe62ba41 [[fallthrough]] if C++17 only 2020-02-29 09:21:50 -05:00
fe1724e7e6 switch travis-ci to xenial 2020-02-28 23:41:42 +03:00
2ac2da41cf cmake: fix else statement 2020-02-28 23:28:41 +03:00
ed574f9d79 use C++17 if available when configuring with cmake 2020-02-28 23:05:26 +03:00
e0cb26bd9e fixed fallthough warning for C++17 2020-02-28 14:15:41 -05:00
1893127e84 use fold expression if C++17 2020-02-28 14:05:51 -05:00
b02c9fb118 enable C++17 for gcc 2020-02-28 14:03:08 -05:00
bca0809918 cleanup removed websockets funtions
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-02-28 18:48:43 +03:00
00db527377 drop websockets support
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-02-27 14:58:06 +03:00
2c6e041ae2 rpm: make package buildable on mageia cauldron (#1476) 2020-02-26 13:41:35 +00:00
a0d6c654cc 2.30.0
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2020-02-25 20:08:50 +03:00
5115c27e72 2.30.0 2020-02-25 11:15:30 -05:00
d09c3ccb2d Merge pull request #1474 from rex4539/dead-strip
Pass -dead_strip -dead_strip_dylibs -bind_at_load on macOS
2020-02-24 18:16:20 +00:00
5c308026ac Pass -dead_strip -dead_strip_dylibs -bind_at_load on macOS 2020-02-21 11:12:00 +02:00
91919c6d64 check if both sides are ECIESx25519 2020-02-20 21:07:45 -05:00
7168738835 check ctx for null 2020-02-20 21:05:07 -05:00
9c9b723cf5 delete expired ECIESX25519AEADRatchet sessions and tags 2020-02-20 15:44:09 -05:00
50450923df don't add extra , to result string 2020-02-19 20:51:32 -05:00
f392edd66c single thread SAM by default 2020-02-19 13:27:28 -05:00
24b48e5d50 reseeds update 2020-02-18 17:45:04 -05:00
47f384a0e0 postpone SAM destination termination 2020-02-17 15:14:35 -05:00
88594887f9 fixed qt build 2020-02-16 17:44:36 -05:00
32e2f0b1fa correct termination of streaming destination 2020-02-15 16:30:10 -05:00
09ed57ad42 select preferred crypto from LeaseSet2 2020-02-12 11:09:20 -05:00
53a6162b0c generate more receive tags when needed 2020-02-09 17:19:42 -05:00
694d851cdb Symmetric Key Ratchet 2020-02-08 21:51:02 -05:00
8e53c30a00 correct calls sequence for tag and index 2020-02-07 22:08:55 -05:00
63e807b0b4 fixed crash on stop 2020-02-06 10:53:45 -05:00
012f22cc47 create session tags for ECIESX25519 2020-02-05 15:48:51 -05:00
9d891ab5dd single thread mode for SAM 2020-02-04 15:31:04 -05:00
d0e78be867 moved io_service away from ClientDestination 2020-02-04 14:17:23 -05:00
cbedebc9dd change minimal MTU size 2020-02-04 13:32:16 -05:00
969f9aa436 common RuunableBase with private inheritance 2020-02-04 11:48:56 -05:00
b982be5ff5 handle existing session message 2020-02-03 16:21:07 -05:00
2d154ee640 move RunnableService away from LeaseSetDestination 2020-02-02 18:58:58 -05:00
49810eb153 common RunnableService 2020-02-02 17:05:30 -05:00
85b88b8749 second x25519 for new session reply 2020-01-30 19:30:30 -05:00
239c8b5172 destination delivery instructions 2020-01-30 11:48:32 -05:00
8c800dc178 save aepk from new session message 2020-01-29 21:57:10 -05:00
cdd068d99a correct message size 2020-01-29 19:27:38 -05:00
48fa10b080 incoming ECIESX25519AEADRatchet messages hanler 2020-01-29 15:54:11 -05:00
a1dbec0fcb handle new session reply 2020-01-29 12:54:26 -05:00
abe668f1c3 fixed build error 2020-01-28 10:31:35 -05:00
77440c235d replaced map by unordered_map 2020-01-28 10:03:51 -05:00
fd1ee48dbe datetime and padding blocks 2020-01-23 14:26:40 -05:00
205e807b66 reset keys 2020-01-22 21:42:30 -05:00
34295adb05 attach LeaseSet clove 2020-01-22 14:26:47 -05:00
7c212bef63 add new session to the list after reply received 2020-01-22 11:27:47 -05:00
76f95644b7 fixed #1461. Use openssl's HKDF for 1.1.1 anf higher 2020-01-22 09:59:08 -05:00
928b90d5bc fixed #1461. Use openssl's HKDF for 1.1.1 anf higher 2020-01-22 09:50:50 -05:00
09c6c2a4f3 decode aepk and bepk back 2020-01-21 21:09:19 -05:00
2b2bd733e9 correct sharedkey for new outgoing session 2020-01-21 19:13:23 -05:00
0d2d7e5e71 fixed Elligator tests 2020-01-21 17:53:48 -05:00
6142e93252 session tag for ECIESx25519 sessions 2020-01-21 14:40:23 -05:00
ccec3376ba try another ephemeral keys if elligator encoding failes 2020-01-21 12:19:20 -05:00
f497a74ec4 set random two highest bits 2020-01-21 12:18:31 -05:00
0e666e7d6a encoding fail test 2020-01-21 10:53:11 -05:00
f498fabd27 fix for openssl 1.1 2020-01-21 10:52:51 -05:00
8b49a55442 ratchet tagsets 2020-01-20 15:17:38 -05:00
a26eb942a9 Merge pull request #1458 from neheb/jjjjj
replace random_shuffle with shuffle
2020-01-20 07:16:00 -05:00
eabcafa516 replace random_shuffle with shuffle
random_shuffle is gone with C++17.

Found and fixed with clang-tidy.
2020-01-19 18:09:04 -08:00
6cc388c1bc use HKDF for MixKey 2020-01-18 14:43:36 -05:00
62e39ddfbd new session reply 2020-01-17 14:11:15 -05:00
80373623cd create payload 2020-01-17 11:21:41 -05:00
451c3945f0 create new ECIESX25519AEADRatchet session if not found 2020-01-16 19:33:00 -05:00
00cb15d9b4 fixed tyypo 2020-01-16 18:03:51 -05:00
67dd59125e new outgoing ECIESX25519AEADRatchet session 2020-01-16 16:34:13 -05:00
b6800dd125 lookup ECIESX25519AEADRatchet session by static key 2020-01-16 15:45:22 -05:00
dc9da69509 derive ECIESX25519AEADRatchetSession from GarlicRoutingSession 2020-01-16 14:59:19 -05:00
d7d964bf57 GarlicRoutingSession/ElGamalAESSession split 2020-01-16 14:31:01 -05:00
bcfe44db54 handle tunnel delivery instructioin for ECIESx25519 2020-01-16 12:47:08 -05:00
376bf6ba72 correct message size for ECIESx25519 2020-01-15 19:22:42 -05:00
f651baab25 ECIESX25519AEADRatchetSession added 2020-01-15 15:13:43 -05:00
61752e2aab correct ciphertext length 2020-01-13 22:37:31 -05:00
b7d3fd959e Merge pull request #1454 from rex4539/dead-strip
Pass -dead_strip -dead_strip_dylibs -bind_at_load on macOS
2020-01-13 09:17:05 -05:00
7ac05f8487 Pass -dead_strip -dead_strip_dylibs -bind_at_load on macOS 2020-01-13 14:47:15 +02:00
5cfc574f9a Update Dockerfile
Fixes dependencies, re-adds `boost-python` as `boost-python2` which was removed in #1408 .
2020-01-12 16:24:21 +01:00
4f70822b13 always persist crypto keys for public destinations 2020-01-12 10:03:30 -05:00
0007f304d0 don't pass from to HandleI2NPMessage 2020-01-07 15:20:55 -05:00
4afef91359 invoke HandleCloveI2NPMessage 2020-01-06 16:14:41 -05:00
815b6db0bf HandleCloveI2NPMessage 2020-01-06 15:31:20 -05:00
433d3bf582 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2020-01-06 14:38:13 -05:00
a335841509 pass msgID to HandleDeliveryStatus 2020-01-06 14:37:40 -05:00
26ad793d82 use unscoped storage (fixes usage on android 10)
Signed-off-by: r4sas <r4sas@i2pmail.org>
2020-01-05 23:04:08 +00:00
5337aa10f7 check AES tag first 2020-01-02 13:30:54 -05:00
9f79bdae9b encryptor for ECIES-X25519-AEAD-Ratchet 2019-12-19 15:59:15 -05:00
db84be2488 use HKDF for NTCP2 key derivation data phase 2019-12-18 20:48:30 -05:00
599ec62bb0 use HKDF for NTCP2 key derivation data phase 2019-12-18 20:45:47 -05:00
19a88300c6 decrypt payload section 2019-12-18 14:44:02 -05:00
b5d55e1ffb decrypt flags/static section 2019-12-17 16:34:47 -05:00
521fb83e38 initial code for ECIES-X25519-AEAD-Ratchet KDF 2019-12-17 16:18:40 -05:00
553d59c32b decryptor for ECIES-X25519-AEAD-Ratchet 2019-12-11 13:38:36 -05:00
9ed58e5186 encode with highY 2019-12-10 14:10:12 -05:00
36eaaa748c handle case when encoded key is (p-1)/2 2019-12-10 13:40:04 -05:00
4d7b86ca26 elligator test added 2019-12-10 13:20:23 -05:00
5faf84c732 correct conversion from Little Endian 2019-12-10 12:51:39 -05:00
d7b819267f check a for 0 in Legendre 2019-12-10 10:53:39 -05:00
7417867d0f implemented Legendre 2019-12-10 10:45:08 -05:00
8d74905257 0.9.44 2019-12-10 10:44:19 -05:00
c38298c06e Elligator decode 2019-12-09 16:11:46 -05:00
3100d587d1 use d%q 2019-12-09 13:23:17 -05:00
ba849d0300 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2019-12-06 20:29:29 -05:00
95df3e4b39 encode key 2019-12-06 20:29:03 -05:00
72492e33a0 appveyor: drop msys2 overwrite 2019-12-07 01:02:23 +00:00
934f1269f5 appveyor: replace deprecated --force in msys2 2019-12-07 00:59:33 +00:00
e6956d9bb0 calculate constants 2019-12-06 14:54:15 -05:00
2877900233 use 486662 for A 2019-12-05 16:13:59 -05:00
df1aa52e08 Elligator's encode 2019-12-05 16:03:11 -05:00
5fa2485a7d removed reseed.i2p.net.in 2019-12-04 17:27:16 -05:00
29f0e10411 Elligator added 2019-12-04 15:37:24 -05:00
39300a5bbf removed reseed.i2p.net.in 2019-11-28 17:49:36 -05:00
35d6268675 README: explicit linux distro supported
close #1440
2019-11-23 22:52:31 +01:00
0abb871f3f close socket after if accept failed 2019-11-20 13:00:50 -05:00
704fca969f handle accept errors 2019-11-20 12:05:32 -05:00
95debf8c80 update mingw build script
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2019-11-19 14:29:55 +03:00
dd94b77b2a use GetTickCount dll pointer, add USE_WINXP to makefile
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2019-11-19 13:51:14 +03:00
6cfe4fa580 handle sending errors 2019-11-18 14:13:31 -05:00
515c086099 Use GetProcAddress for inet_pton. Fixed build error 2019-11-12 15:06:04 -05:00
34ce06ac17 some cleanup 2019-11-12 14:19:14 -05:00
a104c9881e some cleanup 2019-11-12 11:57:34 -05:00
c3e3c091cc correct implementation of GetMTUWindows for WindowsXP 2019-11-12 11:35:59 -05:00
651240113c mark RI as unreachable if all connections failed 2019-11-12 10:03:33 -05:00
77189bf8e9 start over if an active session got disconnected 2019-11-12 09:38:22 -05:00
60fd3a4542 fixed #1434 use memset inster bzero 2019-11-12 07:17:57 -05:00
c66f9c8d6d reset connection attempts before reconnect 2019-11-12 06:46:08 -05:00
569088eaca 2.29.0 2019-10-21 12:02:43 -04:00
a7e8dd04fe 2.29.0 2019-10-21 11:50:59 -04:00
dfdd76a1bb fixed #1429. Don't use monotonic timer for Win32 2019-10-15 10:32:29 -04:00
28aac6f93b fix bogus date in changelogs
Signed-off-by: R4SAS <r4sas@i2pmail.org>
2019-10-07 21:18:46 +03:00
c2f47119ce fixed #1424. Check if .b32.i2p address string is valid 2019-09-23 13:42:15 -04:00
d6b1d0d4fb remove incoming session from pending list when established 2019-09-22 21:01:34 -04:00
03a861745b removed CloseSession 2019-09-20 20:09:25 -04:00
9a7aed20e9 handle error for SessionConfrimed send 2019-09-19 16:54:23 -04:00
b7f17d4cb1 client auth flag for B33 address 2019-09-06 11:02:19 -04:00
2497c3d187 Merge pull request #1421 from nonlinear-chaos-order-etc/openssl
Fixes three upnp issues, probably including: probably fixed #1419
2019-09-05 15:51:11 -04:00
f7a084969a fixed #1387 2019-09-06 03:21:26 +08:00
2900bc26a5 fixed #1388 : took code from 736c95a870 and fixed it as https://github.com/PurpleI2P/i2pd/issues/1388#issuecomment-528495918 tells 2019-09-06 02:58:28 +08:00
2334c56a96 Merge pull request #1414 from nonlinear-chaos-order-etc/openssl
qt: fixed logging to window in release builds
2019-08-27 12:40:19 -04:00
90a5d02bf6 2.28.0 2019-08-27 10:17:32 -04:00
81d9626da9 qt: fixed logging to window in release builds 2019-08-27 21:56:36 +08:00
44a2549b81 2.28.0 2019-08-27 09:46:54 -04:00
a2b8d468bc Merge pull request #1412 from nonlinear-chaos-order-etc/openssl
qt: disabled broken UPnP + small qt debugging tweaks
2019-08-27 08:53:44 -04:00
d523f0cadd gitignored autosave files by qtcreator 2019-08-27 19:31:57 +08:00
99116ff097 qt: disabled upnp for now - until upnp fixed 2019-08-27 19:31:28 +08:00
3939ca9eb4 enabled default logging debug option for qt debug builds 2019-08-27 17:51:55 +08:00
b5aa67b491 tweaked debug logging in i2pd_qt 2019-08-27 17:10:53 +08:00
e42efec220 correct outet plain text length in case of authKeys 2019-08-26 07:35:11 -04:00
9d06aa2f6a pass authSalt or epk 2019-08-25 20:51:15 -04:00
80765a797b correct outer cipher text len 2019-08-25 19:14:53 -04:00
0b5509a1ed correct authClients offset 2019-08-25 14:54:43 -04:00
478d7b4a83 Merge pull request #1410 from nonlinear-chaos-order-etc/openssl
android various fixes and improvements
2019-08-24 07:31:12 -04:00
9d3b38141a android various fixes and improv 2019-08-24 19:13:10 +08:00
ab3a4d902e Merge pull request #1409 from nonlinear-chaos-order-etc/openssl
android - show battery optimiz. os dialog menu item added; translated all battery stuff into Russian
2019-08-24 07:03:15 -04:00
5eab5f2437 show battery optimiz. menu item now hidden if not supported by os 2019-08-24 18:00:11 +08:00
80f632c19a show battery optimiz. menu item added; translated all battery stuff into Russian 2019-08-24 17:50:30 +08:00
6e4f18543d added *.local to android/.gitignore 2019-08-24 17:04:04 +08:00
54586c9076 Merge pull request #1408 from docker-and-co/fix-dockerfile-non-existend-deps
fix dockerfile: remove unmet dependencies
2019-08-23 11:02:00 -04:00
351c899807 cleanup incoming streams on stop 2019-08-23 10:00:49 -04:00
fe45d431d7 fix dockerfile: remove unmet dependencies 2019-08-23 16:20:09 +03:00
488c2f6d05 bump SDK version 2019-08-22 09:45:49 -04:00
75ab0909b3 Merge pull request #1405 from nonlinear-chaos-order-etc/openssl
various Android stuff. Fixed #1400
2019-08-22 07:15:36 -04:00
8f82d563c1 various Android stuff. Fixed #1400 2019-08-22 10:00:50 +08:00
9bbce5dba6 fixed typo 2019-08-21 20:26:19 -04:00
099adab9ed Update README.md
update head badges links, add snapcraft badge
2019-08-16 21:45:44 +03:00
c8cbf425ac check and send netid for NTCP2 and SSU 2019-08-13 14:55:18 -04:00
ad9c11cd92 correct parsing of addreses containing # 2019-08-10 22:16:26 -04:00
3872c2a3f5 use published encrypted instead orig type 2019-08-07 16:18:00 -04:00
e6a09b49c9 published encrypted flag 2019-08-07 15:43:03 -04:00
db107602bd handle messages with \r\n 2019-08-02 13:48:39 -04:00
a6558a61a7 Recognize RedDSA_SHA512_Ed25519 signature type 2019-08-02 12:54:24 -04:00
254d2b82b3 fixed #1393. store streams by recvStreamID 2019-07-26 14:23:21 -04:00
2c9fa2f738 Fix and update i2pd.service
- /var/run on distros with systemd is a symlink to /run , hence the
path changes.

- Remove unnecessary runtime dependency on `/bin/kill` which is
provided by `procps` and might not be available on minimal installs
(e.g. containers). Instead use `/bin/sh` which has a built-in `kill`.

- `PrivateDevices=yes` causes i2pd to fail to start on latest Debian
unstable. Service exits with the following:

```
i2pd.service: Failed to execute command: Operation not permitted
i2pd.service: Failed at step EXEC spawning /usr/sbin/i2pd: Operation not permitted
i2pd.service: Control process exited, code=exited, status=203/EXEC
i2pd.service: Failed with result 'exit-code'.
Failed to start I2P Router written in C++.
```

According to `man systemd.exec` exit code 203 corresponds to the
`execve(2)` system call failing. So it looks like i2pd tries to do
something it shouldn't be doing. The proper fix would be in i2pd, but
who knows how long that would actually take, so to allow people to
actually launch i2pd in meanwhile the line has been removed from the
service file.

Also, surprisingly, right after installing i2pd it started without any
problems, and only after restarting the box i2pd started to fail for no
apparent reason.
2019-07-24 11:48:18 +01:00
97d9795fc9 pass encrepted LeaseSet auth keys 2019-07-16 16:31:17 -04:00
54071b0e5d set and handle unpublished LeaseSet flag 2019-07-16 11:48:30 -04:00
925e8316c7 read i2cp.leaseSetAuthType, i2cp.leaseSetClient.dh.nnn and i2cp.leaseSetClient.psk.nnn from tunnel config 2019-07-12 20:58:17 -04:00
99e1b74023 create encrypted LeaseSet2 with authentication 2019-07-12 15:40:59 -04:00
7d68ccca53 create encrypted LeaseSet2 with authentication 2019-07-12 15:37:32 -04:00
a090114066 send data message wih raw type fpr raw datagrams 2019-07-10 13:31:49 -04:00
a204841abb handle RAW SEND 2019-07-10 13:30:31 -04:00
cc451809cc send/receive raw datagrams through the SAM 2019-07-10 11:32:56 -04:00
a605e4bab6 send and recieve raw datagrams 2019-07-09 21:33:55 -04:00
3f0534134d check for malformed b33 2019-07-04 13:05:39 -04:00
3acfb129cd 2.27.0 2019-07-03 12:38:55 -04:00
6ccef66920 call shutdown before close 2019-06-26 10:47:16 -04:00
e9fa4e94a6 Merge pull request #1374 from rszibele/openssl
BOB: fix status command.
2019-06-25 18:28:43 -04:00
fecc0c4640 don't call destructor twice 2019-06-25 16:37:06 -04:00
b759294975 BOB: fix status command. 2019-06-25 19:18:40 +02:00
a23e845c03 BOB: improve comment and remove error log in list command 2019-06-25 19:04:27 +02:00
cb8373e487 BOB: status response now correctly starts with "OK DATA". 2019-06-25 17:59:44 +02:00
8e919ddc8e use monotonic clock for uptime 2019-06-19 11:43:04 -04:00
832a9ab6b5 don't set random NTCP2 port if already set 2019-06-18 15:47:58 -04:00
13732ac333 fix #1363 try connect in SSU's thread 2019-06-14 15:43:03 -04:00
3e932a55f4 fixed typo 2019-06-11 15:09:10 -04:00
74e8610ec9 DH auth for encrypted LeaseSet2 2019-06-11 10:40:53 -04:00
089a60ded6 Merge pull request #1367 from rszibele/openssl
fix build on BSDs, as "isset" is a defined macro.
2019-06-10 19:10:34 -04:00
c8eeefe194 fix build on BSDs, as "isset" is a defined macro. 2019-06-10 23:04:59 +02:00
85eeba14c1 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2019-06-08 21:24:16 -04:00
f6f45eab39 flood encrypted LeaseSet2 with store hash 2019-06-08 21:23:25 -04:00
a74065f775 [qt] dont build UnixDaemon.cpp 2019-06-09 01:04:43 +03:00
48d02f7e09 [qt] update headers, fix ChaCha source name, remove duplicates 2019-06-08 22:24:11 +03:00
e60549f8df [qt] fix build 2019-06-08 21:16:20 +03:00
41f4f4713e handle i2cp.leaseSetPrivKey 2019-06-07 14:51:08 -04:00
213a292fd5 correct offsets for auth data 2019-06-07 11:59:48 -04:00
79630e844b 2.26.0 2019-06-07 17:25:55 +03:00
1c9e46dbb3 2.26.0 2019-06-07 10:04:57 -04:00
0a299284f8 correct check for PSK auth 2019-06-06 13:58:31 -04:00
347a5f7346 pass secret to encrypted LeaseSet2 2019-06-06 12:33:33 -04:00
c6a903572c [HTTP] add PROFIND support 2019-06-06 18:07:17 +03:00
14f0d6d26b extract client auth data 2019-06-05 15:57:20 -04:00
485f105555 fixed typo 2019-06-04 15:12:19 -04:00
686c0b776f common blinding code for public and private keys 2019-06-04 14:47:40 -04:00
828862ea49 store hash for ECDSA blidning 2019-06-03 12:51:57 -04:00
c4dffa4dc8 remove obsolete reseeds 2019-06-01 09:37:02 -04:00
3c1906e3d4 Merge pull request #1360 from khumarahn/openssl
link libi2pd to boost and zlib
2019-06-01 09:28:54 -04:00
7147a3694c link libi2pd to boost and zlib 2019-06-01 12:57:09 +01:00
64707dbb22 key blinding test 2019-05-31 11:57:16 -04:00
554e8eeef3 [appveyor] remove gcc-ada and gcc-objc packages
https://github.com/msys2/MINGW-packages/issues/5434#issuecomment-496706950
2019-05-31 16:32:32 +03:00
5e10549543 disable NTCP by default 2019-05-30 19:18:56 -04:00
685f45bd76 publish/unpublish NTCP2 address depending on network status 2019-05-30 17:52:44 -04:00
61d84dd4c1 publish/unpublish NTCP2 address depending on network status 2019-05-30 17:48:49 -04:00
4d10593bb1 publish/unpublish NTCP2 address depending on network status 2019-05-30 16:11:35 -04:00
fbb8903774 correct buffer size for ECDSA blinding 2019-05-30 13:57:43 -04:00
e8cac91bb7 blind ECDSA public key 2019-05-29 15:48:35 -04:00
7328ffa036 Merge pull request #1359 from rszibele/openssl
BOB modifications.
2019-05-29 14:07:30 -04:00
a03e828317 BOB: status: forgot to pass destination for current tunnel. 2019-05-29 18:47:35 +02:00
93d4dc70cf BOB fixes. 2019-05-29 18:05:03 +02:00
8e3d16e9fb update ipv6 addresses from SSU rather than NTCP or NTCP2 2019-05-29 11:36:58 -04:00
07405e57b9 fixed typo 2019-05-25 14:58:10 -04:00
354c9187db detect our ipv6 address 2019-05-23 15:59:44 -04:00
af33df3004 common buffer size 2019-05-23 11:49:54 -04:00
78bfde237f allocate actual RouterInfo's buffer size 2019-05-23 09:34:04 -04:00
7b9033d678 allocate actual RouterInfo's buffer size 2019-05-23 09:32:07 -04:00
f784cfad46 correct RouterInfo buffer size 2019-05-23 06:56:41 -04:00
e40c139ff1 blind ECDSA private key 2019-05-22 16:15:11 -04:00
edf4f7695d fix #1352. correct response for 'list' command 2019-05-22 12:45:50 -04:00
60ec03237e blidning for ECDSA 2019-05-16 15:49:07 -04:00
a91641e427 fix #823, reindent code 2019-05-16 09:39:22 +03:00
5c3992018f fixed #1350 use GetAddress insted GetIdentHash 2019-05-15 14:22:19 -04:00
f5b682619f [webconsole] move b33 to spoiler, fix typo 2019-05-15 14:15:10 +03:00
743fa745b7 show b33 address for encrypted LeaseSet2 2019-05-14 14:42:10 -04:00
39400fd381 move key blinding code from LeaseSet.cpp to Blinding.cpp 2019-05-14 11:42:25 -04:00
5299ac35a6 create NTCP2 ipv6 address 2019-05-13 11:40:08 -04:00
ef76ed394c publish SSU ipv6 address if NTCP if disabled 2019-05-12 13:36:26 -04:00
1472637de7 skip introducers for non-SSU address 2019-05-11 07:27:34 -04:00
3b8baa85a3 2.25.0 2019-05-09 10:21:11 -04:00
73921b1024 fix ipv6 fallback address 2019-05-08 00:45:52 +03:00
ece140f18c [httpproxy] make addresshelper support configurable for every httpproxy 2019-04-25 23:06:14 +03:00
5e42947fbd always lookup SSU session if peer's endpoint doesn't match 2019-04-25 12:54:44 -04:00
1bfb9b02f5 make sure remote endpoint matches stored with 2019-04-24 11:40:58 -04:00
16a14c2b76 [android] set datadir path from system environment 2019-04-20 19:47:06 +00:00
f6199c6c17 print store hash for encrypted LeaseSet 2019-04-20 09:44:16 -04:00
d7e7f06e88 re-request encrypted LeaseSet 2019-04-17 15:53:07 -04:00
4c4e856a1a ntcp2.addressv6 parameter 2019-04-17 14:40:00 -04:00
07bbbbaf61 fixed gcc 4.7 build 2019-04-17 12:42:43 -04:00
3236827781 add/removed NTCP addresses 2019-04-16 21:04:04 -04:00
0be664cc3d publish NTCP2 address instead NTCP if NTCP is disabled 2019-04-15 16:32:16 -04:00
6cc6849ccc use published timestamp for blinding 2019-04-12 14:05:07 -04:00
5d5cd71714 limit expiration by next midnight for encrypted LS2 2019-04-12 11:13:46 -04:00
d248343517 Handle CreateLeaseSet2 I2CP message for encrypted leasesets 2019-04-11 14:06:53 -04:00
64d800427f allow HTTP headers without value 2019-04-10 15:25:09 -04:00
c4c896a833 publish encrypted LS2 2019-04-10 12:04:19 -04:00
b6b5bb3f75 publish LeaseSet with store hash 2019-04-09 15:36:10 -04:00
5d69bb7383 correct ecrypted LS2 layout 2019-04-09 10:34:05 -04:00
76e222079a Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2019-04-09 09:21:47 -04:00
73abb9278d correct ecrypted LS2 size 2019-04-09 09:21:38 -04:00
8fd843e7ce Merge pull request #1334 from rex4539/fix-typos
Fix typos
2019-04-08 17:36:55 -04:00
6a497a23d9 Fix typos 2019-04-08 22:22:42 +03:00
3ac74e1091 create encrypted LS2 2019-04-08 13:27:21 -04:00
ef0fb48f1f blind private keys 2019-04-05 16:03:58 -04:00
414ef2bc3d fixed gcc 4.7 build 2019-04-04 16:18:52 -04:00
ea791309ad moved credential and blinding to BlindedPublicKey 2019-04-02 16:32:18 -04:00
706da6e431 allow .b32.i2p in jump links 2019-04-02 13:11:49 -04:00
ed116e7cea add gcc 9 support 2019-03-30 13:05:32 +03:00
5b56f4007b counter is always in Little Endian 2019-03-29 18:45:31 -04:00
e2071542bf use 16 bytes iv for chacha20 2019-03-29 16:18:51 -04:00
cdb217b774 always initialize m_Pkey 2019-03-29 13:15:32 -04:00
079798940b lookup for b33 address 2019-03-29 11:59:59 -04:00
f1c24689bf fixed #1319. send correct response 2019-03-29 09:29:28 -04:00
1f9cf6ed7c show lookup keys 2019-03-28 19:00:56 -04:00
43f218410f correct b33 address length threshold 2019-03-28 18:48:38 -04:00
3fd9d5f641 save b33 addresses 2019-03-28 16:06:53 -04:00
f5ab8f2062 replaced GetIdentHash by GetAddress 2019-03-28 12:19:19 -04:00
8774a8fbc2 handle b33 addresses in I2P tunnels 2019-03-28 10:17:03 -04:00
6f4f0f03d2 handle b33 addresses in I2P tunnels 2019-03-28 09:57:34 -04:00
00b5fdce03 create stream to blinded dest 2019-03-27 16:04:46 -04:00
baee6a0d91 generic address for AdressBook 2019-03-27 15:19:10 -04:00
ff44bcc489 complete implementation of RedDSA 2019-03-24 18:42:52 -04:00
c797ac4268 Update README.md 2019-03-23 03:25:10 +03:00
d22a76d4d1 remove incorrect line 2019-03-22 23:40:59 +00:00
a6642e0ebc add script for packaging archive with android binaries 2019-03-22 23:37:20 +00:00
3d4d260a34 extract b33 address 2019-03-22 16:04:47 -04:00
8e4b9da97d pass blinded key instead identity for encrypted LS2 2019-03-22 15:32:13 -04:00
2be80ba30f Fix Docker build 2019-03-22 13:14:02 -04:00
2e44c88d6c [2.24.0][android] update addressbook 2019-03-21 18:34:39 +03:00
21eb1ce6c9 2.24.0 2019-03-21 11:30:12 -04:00
cdfd411df7 2.24.0 2019-03-21 10:58:59 -04:00
a6149ca90c [android] upload gradlew script 2019-03-21 00:09:49 +03:00
642435486c [android] add gradle wrapper, update buildtools version, fixes in code. 2019-03-20 23:49:54 +03:00
fc84d6c4b7 remove unused timer 2019-03-17 21:37:42 -04:00
aa4bddd6ec common HKDF 2019-03-15 12:25:20 -04:00
8ec12a1b65 fixed race condition for publishing 2019-03-10 09:22:42 -04:00
0fbf552e95 lookup and handle encrypted LeaseSet2 2019-03-07 14:52:59 -05:00
09b1b120d7 update LeaseSet2 if store type changed 2019-03-07 14:51:05 -05:00
557244bc3f verify blinding key for encrypted LS2 2019-03-07 11:55:47 -05:00
24c5ed1cff calculate store hash for encrypted LeaseSet2 2019-03-06 16:08:04 -05:00
32e55ebd0c blind public key for encrypted LeaseSet2 2019-03-05 15:51:24 -05:00
ea3070d02b derivation of subcredentials for LeaseSet2 2019-03-05 12:41:01 -05:00
9aaba49a9f decrypt and handle Layer 2 of encrypted LeaseSet 2 2019-03-04 15:47:35 -05:00
9b64be07a9 set chacha20 counter to 1 2019-03-04 15:08:03 -05:00
42c3c28ea7 [addressbook] reset eTags if addressbook can't be loaded 2019-03-04 18:29:29 +00:00
9e9236badb don't check TRANSIENT destination 2019-03-04 07:35:48 -05:00
560ebcec8d persist.addressbook parameter added 2019-03-01 14:42:20 -05:00
9b1fe4338b reuse_address for ipv6 acceptor 2019-02-28 16:00:26 -05:00
9188e3ad3f ChaCha20 decrypt 2019-02-28 13:31:51 -05:00
af65af5be9 H and HKDF for encrypted LeaseSet2 2019-02-27 15:52:47 -05:00
2f0115c300 handle RedDSA as EdDSA 2019-02-27 13:18:09 -05:00
0646461342 check published timestamp for LeaseSet2 2019-02-26 16:20:24 -05:00
ec30ec0996 Merge pull request #1304 from lifecoder-phoenix/openssl
Fix #1257
2019-02-25 07:01:33 -05:00
cdecb7a43c Fix #1257 2019-02-25 10:10:09 +01:00
aa9c1b66a0 Fix #1257 2019-02-25 09:57:18 +01:00
846eac29dc filter out unspecified addresses. Check floodfill status change 2019-02-24 18:26:58 -05:00
0f9e3c5b33 fix crash if public key is null 2019-02-22 13:17:43 -05:00
aa27746982 remove address string 2019-02-22 11:03:31 -05:00
d8a4954bf1 [NetDb] check PersistProfiles on load
* tabulation fixes
2019-02-22 18:37:32 +03:00
d40a029dae eliminate extra copy 2019-02-20 12:36:05 -05:00
96d961c393 correct public key for EdDSA trasient key 2019-02-15 15:03:58 -05:00
7b6814e32d correct flags 2019-02-14 21:22:49 -05:00
6fee2d3536 correct options szie 2019-02-14 17:49:23 -05:00
636fc633d4 send offline signature in streaming 2019-02-14 12:11:25 -05:00
72a239838e publish offline signature 2019-02-12 14:56:39 -05:00
a463dbc5fb Merge pull request #1295 from l-n-s/websocket_support
Support websocket connections over HTTP proxy
2019-02-12 12:30:44 -05:00
016ae3b9e9 rewrite for efficiency 2019-02-12 11:20:54 -05:00
7d0d421724 [windows] handle unexpected conditions (#1185) 2019-02-12 04:27:09 +03:00
83b5856a19 fix overflow warning, fix little typos 2019-02-12 03:09:29 +03:00
f617b27110 Support websocket connections over HTTP proxy 2019-02-11 17:18:01 -05:00
a91a0263cf update outproxy user-agent header rewrite 2019-02-12 00:51:47 +03:00
80ffe13f3e correct offline signature layout 2019-02-08 15:12:51 -05:00
1eb726c9bb create offline keys 2019-02-08 12:19:51 -05:00
1fa3ba8b42 read offline info 2019-02-07 16:04:31 -05:00
b6bfd66a49 use identity from LeaseSet 2019-02-06 21:19:44 -05:00
1be0e7ddaa [windows] add functional
* check tunnels count on graceful shutdown
* add tray menu item for accept/decline transit tunnels
2019-02-07 02:02:28 +03:00
2cac9b03ff common code for offline signatures 2019-02-06 13:36:03 -05:00
f5f4190803 catch error 10045 on stopping SAM acceptor (#1233), fix warning in util 2019-02-06 03:03:37 +03:00
a14d554947 fix tray icon disappearing, var type warning, code tabulation 2019-02-06 00:24:01 +03:00
6d9e5147b5 handle offline signature 2019-02-05 15:32:18 -05:00
841452cb9e Merge pull request #1292 from PurpleI2P/inet_pton_xp
inet_pton for winxp
2019-02-05 17:36:36 +03:00
9c76368dbc inet_pton for winxp 2019-02-05 14:13:23 +03:00
bd5122c6ea fixed build error 2019-02-01 17:41:12 -05:00
6643258618 implement Update for LeaseSet2 2019-02-01 12:55:13 -05:00
bc3f02cb6b fix #1290. copy correct size if message didn't fit previous 2019-01-31 16:03:10 -05:00
d848ae332a encryption keys priority 2019-01-30 14:10:40 -05:00
08ddc98303 initial LeaseSet2 support in I2CP 2019-01-29 11:30:31 -05:00
a3344c4290 resolve SIGNATURE_TYPE string values 2019-01-23 10:52:17 -05:00
22c1ce3ea5 don't pick port 9150 (Tor browser) 2019-01-23 09:53:30 -05:00
afb14e6782 [fedora] fix build in release on fc30+
fixes #1284
2019-01-22 04:57:53 +03:00
e177363377 [fedora] specify srcdir only if building at 30+ 2019-01-22 04:08:52 +03:00
ce213934c9 try fix build in fedora rawhide 2019-01-22 02:33:44 +03:00
af286ec52e try fix build in fedora rawhide 2019-01-22 02:32:51 +03:00
f7f2b7607b 2.23.0 2019-01-21 18:51:04 +03:00
60a282826c 2.23.0 2019-01-21 10:33:22 -05:00
3eba599aec [android] add addressbook in assets
Sources:
http://inr.i2p/export/alive-hosts.txt
http://stats.i2p/cgi-bin/newhosts.txt
http://i2p-projekt.i2p/hosts.txt
http://identiguy.i2p/hosts.txt

Updated: January ‎18, ‎2019, ‏‎12:00:01 PM
2019-01-18 23:59:22 +03:00
74d876f145 [android] update russian strings, add tunnels.d to assets list 2019-01-18 18:43:48 +03:00
d7609f119c [android] build libi2pd staticly, add update strings, fix messages 2019-01-18 15:44:30 +03:00
65c2c7d80b re-create LeaseSet if store type has changed 2019-01-16 19:00:17 -05:00
468a32a819 check LS2 transient key expires time 2019-01-15 18:56:26 -05:00
b89cf73ae2 correct encryption key type for LS2 2019-01-15 18:41:00 -05:00
9cf43dea1a handle i2cp.leaseSetEncType 2019-01-15 15:43:21 -05:00
670ffe2078 show LS2 in Leasets' list 2019-01-14 18:39:02 -05:00
884cf756ed remove invalid leasesets 2019-01-14 18:37:17 -05:00
e44ba54857 show correct LeaseSet's store type 2019-01-14 16:34:43 -05:00
3712749a94 extract timestamp for LS2 2019-01-14 13:49:27 -05:00
6569c4aa03 actual key size for LS2 2019-01-13 19:17:02 -05:00
d6b2b3c996 take key type for LS2 from identity 2019-01-13 08:34:34 -05:00
06c7900ece show LeaseSet type in destination 2019-01-12 18:26:31 -05:00
52a6a12a9a correct LS2 creation 2019-01-12 18:25:10 -05:00
e647603dce handle i2cp.leaseSetType parameter 2019-01-11 13:58:02 -05:00
dadf6174ba create standard LS2 2019-01-10 11:52:34 -05:00
84de7675c4 don't copy LS2 for signature verification 2019-01-10 10:57:57 -05:00
6311a80d0e use clang for android binary build 2019-01-10 09:47:11 -05:00
9504e69598 LocalLeaseSet2 added 2019-01-09 14:51:47 -05:00
5398b651f7 handle LS2 in destinations 2019-01-09 12:47:47 -05:00
b5596c4596 handle encrypted LS2 2019-01-08 11:26:50 -05:00
fdcea5537c show LeaseSet's store type 2019-01-08 09:35:15 -05:00
8ca8bc810d take elgamal percomputation from config 2019-01-08 09:23:14 -05:00
8f909b051f Merge pull request #1281 from neheb/b
Fix compilation without deprecated OpenSSL APIs
2019-01-06 20:12:51 -05:00
90f2b2d249 Fix compilation without deprecated OpenSSL APIs 2019-01-06 15:39:24 -08:00
f74b27c58c check if chacha20 and poly1305 is presented in openssl build 2019-01-06 17:43:05 -05:00
3f091f4748 remove i2pd-qt android project (closes #1279) 2019-01-06 19:46:17 +03:00
d84c9ad611 Merge pull request #1277 from l-n-s/update_zlib_version
CMake: bump version of ZLib
2019-01-04 23:48:44 +03:00
e55e15693d update LS2 leases 2019-01-02 15:40:48 -05:00
c54e6bafdb process meta LS2 2019-01-02 14:19:10 -05:00
2e56c4895d transient key signature verification 2019-01-02 09:43:18 -05:00
bce4224d6e extract and verify LS2 transient key 2019-01-01 17:00:37 -05:00
812e2814bc read flags from LS2 header 2018-12-31 14:23:48 -05:00
7cd17f8e1f build android app with llvm 2018-12-27 03:16:38 +03:00
6193b06708 LS2 signature verification and store type 2018-12-26 15:27:32 -05:00
12af68bdb5 initial support of LeaseSet2 2018-12-21 15:00:03 -05:00
881f7e9062 correct Authorization header 2018-12-21 10:50:23 -05:00
1db4076bbd CMake: bump version of ZLib 2018-12-19 12:19:30 -05:00
1933e44719 reseeds update 2018-12-17 20:14:12 -05:00
25441cb650 revert mingw makefile
ref: https://github.com/Alexpux/MINGW-packages/issues/4773
2018-12-14 21:44:38 +03:00
bc755ac32f [MSYS2] add boost version detection via pacman 2018-12-14 15:43:52 +03:00
1fa34be52a update mingw makefile 2018-12-14 09:29:41 +03:00
f7a6d57855 fixed bug with loval destination shared between http and socks proxy 2018-12-13 09:53:16 -05:00
8a987af244 initialize m_Pkey 2018-12-11 15:14:51 -05:00
65cbb06080 create ephemeral keys after getting connected 2018-12-07 19:24:46 -05:00
979ea9c252 removed address resolvers as discontinued 2018-12-07 12:27:06 -05:00
aa1f4ee72a fixed possible race condition 2018-12-07 12:25:26 -05:00
74ce485b73 EdDSA signatures by default 2018-12-06 13:13:20 -05:00
165e6508f8 EdDSA signatures by default 2018-12-05 14:58:50 -05:00
c7af2889fa removed dummy initializer 2018-12-05 14:56:40 -05:00
5ab3390434 don't create dummy initializer for android 2018-12-05 11:39:48 -05:00
67f60f1889 set openssl no_config before boost::asio:ssl 2018-12-04 21:20:12 -05:00
985a468d0f don't read openssl config file 2018-12-04 18:39:49 -05:00
34dc6fbdc1 check if session is terminated before sending 2018-12-04 16:10:52 -05:00
b57152cc25 common code for padding and sending termination and RouterInfo messages 2018-12-04 15:56:55 -05:00
dc9562e430 padding for termination message 2018-12-04 15:23:43 -05:00
05689fe183 padding for short messages 2018-12-04 15:00:10 -05:00
8f6f95211e eliminate extra copy of RouterInfo 2018-12-04 12:56:49 -05:00
f30b6c9e6e const reference to vector of buffers 2018-12-04 12:54:48 -05:00
12ac7d6a00 enable sending I2NP messages 2018-12-03 18:47:20 -05:00
10251a6447 fixed typo 2018-12-03 15:54:35 -05:00
089cbbc20a rollback 2018-12-03 14:51:27 -05:00
95ab68acd1 don't copy I2NP messages to NTCP2 frame 2018-12-03 14:14:36 -05:00
abc4f6c70b fixed bug with chacha20 encryption of short messages 2018-12-03 13:36:17 -05:00
8fc3a1f9c9 correct frame size for I2NP msgs 2018-12-03 12:29:24 -05:00
5c3d0fc02c create I2NP blocks 2018-12-02 17:24:31 -05:00
7efb47fed4 send NTCP2 frame from I2NP messages 2018-12-02 14:24:39 -05:00
7692332f0e don't inialize Chacha20 state twice 2018-11-30 21:31:06 -05:00
ef6db64e9f correct chacha20 for multiple messages 2018-11-30 16:21:11 -05:00
e68f1dbc99 AEAD/Chacha20/Poly1305 encrypt multiple buffers 2018-11-30 14:41:14 -05:00
0c9ebc36d4 remove AVX and SSE for CipherBlock XOR 2018-11-27 14:33:31 -05:00
fcd6eb7801 overwrite user-agent for outproxy requests 2018-11-27 19:57:40 +03:00
328c2182c2 alignment for tunnel message AES decryption 2018-11-27 10:35:17 -05:00
08706f5dfb fixed typo 2018-11-25 18:49:59 -05:00
d49f165f0d fixed build warning 2018-11-25 15:59:00 -05:00
cf0fc3a4a9 some performance improvements 2018-11-25 10:33:48 -05:00
72c8fd257c eliminate extra buffer for Poly1305 2018-11-24 15:39:37 -05:00
fa620e41a4 correct alignment for polyKey 2018-11-24 14:41:17 -05:00
b07f851ce7 Merge pull request #1272 from majestrate/openssl
expose poly1305 digest struct in poly1305.h
2018-11-24 14:24:09 -05:00
16b3108719 Merge remote-tracking branch 'purple/openssl' into openssl 2018-11-24 10:08:12 -05:00
f385c624c7 expose poly1305 digester 2018-11-24 10:07:17 -05:00
f7e9975192 restore BlockCipher XOR using SSE 2018-11-24 09:43:30 -05:00
cde989b59d don't compile compatibility code if openssl 1.1.1 2018-11-22 12:13:16 -05:00
c0e263abd3 default value for m_PersistProfiles 2018-11-22 11:30:44 -05:00
79c0c11e80 configure persist of peer profiles
* If persist.profiles = false, peer profiles not stored on disk
* remove inet_pton for windows
* update configs
2018-11-22 00:13:23 +03:00
ca671551c8 flood NTCP2 RouterInfo if requested 2018-11-21 13:24:54 -05:00
42ed312384 handle NTCP2 RouterInfo flag 2018-11-21 11:23:48 -05:00
0e9074aaba reduce start and stop time 2018-11-20 13:57:51 -05:00
7c1961d4ef Cancel Graceful Stop 2018-11-20 12:36:10 -05:00
71e57717c2 request memory permisssion for android >= 6 2018-11-19 15:53:16 -05:00
8a549b83a2 NTP sync in separate thread 2018-11-16 12:49:04 -05:00
d7081c5f23 handle RouterInfo from NTCP2 in netdb's thread 2018-11-14 20:52:54 -05:00
588d64a30b more NTP logging 2018-11-14 12:27:11 -05:00
8335bdf3d4 correct ntp servers 2018-11-14 11:47:50 -05:00
85394f2438 NTP time sync 2018-11-14 11:06:53 -05:00
42b556574f add fedora copr mageia support 2018-11-11 22:28:34 +03:00
f34e65ad9e Merge pull request #1268 from sokolas/webroot
Added configurable web console URL path
2018-11-10 15:08:40 -05:00
51352a6819 update debian/rpm tunnels.d storing
+ testing rpm changes: manpage and configs store
2018-11-10 03:28:24 +00:00
d9887ec370 bump i2pd version in appdata manifest 2018-11-09 14:05:10 -05:00
c994950aaf default webroot in config, webroot in automatic redirect instead of request path 2018-11-09 17:42:04 +03:00
a26ed6fe6c Merge remote-tracking branch 'upstream/openssl' into webroot 2018-11-09 16:30:54 +03:00
a12a7e73f9 redirect with webroot 2018-11-09 16:13:56 +03:00
779228857e 2.22.0 2018-11-09 02:22:55 +00:00
8d0b696d33 packages - tunnels.conf.d fix configs place, links 2018-11-07 18:41:04 +03:00
23ae220aa7 add webroot setting 2018-11-07 18:07:05 +03:00
b7940e0002 add tunnels.d to packages 2018-11-06 20:04:26 +03:00
b3fd8bd0ae check if keys are available before sending termination message 2018-11-04 18:51:25 -05:00
bffeb237de termination might be send for non-established session 2018-11-04 15:32:31 -05:00
23e3602ea1 common MixHash 2018-11-01 16:06:39 -04:00
34cfd205f6 create new static keys by X25519Keys 2018-11-01 10:43:31 -04:00
df3da8be7a Merge pull request #1264 from l-n-s/desktop
fix appdata manifest
2018-10-31 17:24:39 +00:00
940243f45e fix appdata manifest 2018-10-31 13:23:13 -04:00
75d6599143 Update desktop files (#1263)
* Rename files to freedesktop standarts

* Add application icons
2018-10-31 12:23:16 +00:00
929a27a5ac Add Desktop files (#1261)
* Add appstream and desktop files

* More metadata in appstream file
2018-10-30 07:48:02 +00:00
82ddee2104 Merge pull request #1260 from l-n-s/version_display
Add --version flag to display i2pd and system libraries versions
2018-10-28 11:01:46 -04:00
a141678119 Add --version flag to display i2pd and system libraries versions 2018-10-28 10:52:22 -04:00
96d109af81 fixed typo 2018-10-27 19:55:23 -04:00
a309eb9f3c faster CipherBlock XOR implementation for non-AVX 2018-10-27 18:41:05 -04:00
d034dab265 fill m3p2 with SessionRequest 2018-10-26 09:58:18 -04:00
883a035e5c Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2018-10-22 12:26:49 -04:00
08603091c5 2.21.1 2018-10-22 14:21:52 +00:00
a2e84e5a1e 2.21.1 2018-10-22 09:19:39 -04:00
d148898ad7 Merge remote-tracking branch 'purple/openssl' into openssl 2018-10-22 07:35:34 -04:00
9439621849 fixed #1259. read extra tunnels from tunnels.d 2018-10-19 15:23:46 -04:00
36cf622979 Merge pull request #1258 from PurpleI2P/openssl
long I2NP messages
2018-10-15 09:30:56 -04:00
15ded89618 set cost=14 for unpublished NTCP2 addresses 2018-10-11 13:00:37 -04:00
b84f74c167 limit SSU message size to 32K 2018-10-11 11:17:14 -04:00
a97300f8be fixed #1256 I2NP messages up to 64K 2018-10-10 11:31:55 -04:00
9e12cff317 fix #1253 handle incorrect values of SIGNATURE_TYPE and CRYPTO_TYPE 2018-10-08 15:03:41 -04:00
ecdf1f4ddc updated debian patches, add patch disabling few settings in service file, fix name in control file 2018-10-05 13:44:18 +00:00
2fa7a48163 2.21.0 2018-10-04 10:17:33 -04:00
5e31e533e2 Merge pull request #1249 from PurpleI2P/openssl
2.21.0
2018-10-04 09:47:29 -04:00
8adf76dcc9 2.21.0 2018-10-04 09:46:10 -04:00
15899c10b2 2.21.0 2018-10-04 09:38:04 -04:00
05ff05ea4b Merge pull request #1246 from 3pdotsif/openssl
added NTCP2 to qt.pro ; fix for #1111
2018-10-02 11:33:07 -04:00
bd62df48c2 added NTCP2 to qt.pro ; made tunnel conf param keys be optional (fixes #1111) 2018-10-02 23:09:01 +08:00
2366cbc833 count outgoing tags 2018-10-01 18:11:44 +03:00
25fb609544 [appveyor] make it work again
Temporary fix. Read: https://github.com/Alexpux/MSYS2-packages/issues/1428
Waiting for https://github.com/Alexpux/MSYS2-packages/pull/1430
2018-09-30 23:24:48 +03:00
af793395f0 don't publish O with X or P 2018-09-30 16:08:26 -04:00
8f41776858 check send queue size 2018-09-28 09:54:42 -04:00
139b13b8d1 openssl 1.1.1/boost 1.64 for andoroid binary only 2018-09-27 10:31:32 -04:00
4c611a5be1 Merge pull request #1243 from PurpleI2P/android-26up-service
try to fix working of service on api 26+
2018-09-25 11:42:34 -04:00
5e7a21e177 try to fix working of service on api 26+ 2018-09-25 03:37:34 +03:00
5f7dda5ba8 treat extra bandwidth as high bandwidth 2018-09-22 14:12:46 -04:00
2dfa1ca0f2 check RouterInfo's timestamp in SessionConfirmed 2018-09-21 11:45:04 -04:00
358cdcf4c4 removed RSA signatures completly 2018-09-21 11:16:38 -04:00
c8f4ace5c4 update timestamp before publishing 2018-09-21 10:13:18 -04:00
5cac6ca8bb read message body immediatly after length 2018-09-17 13:08:49 -04:00
fccad71df1 temporary buffer for EdDSA signature for openssl 1.1.1 2018-09-16 18:08:59 -04:00
97ae2674dc always use EdDsa signer fallback 2018-09-14 21:54:45 -04:00
7c70affd7f eddsa signer fallback 2018-09-14 21:23:16 -04:00
52ff568d86 fixed incorrect second signature 2018-09-14 18:58:40 -04:00
b917aeaa0b openssl 1.1.1/boost 1.64 for android 2018-09-13 09:43:10 -04:00
8de443ec4c siphash from openssl 1.1.1 2018-09-11 13:26:29 -04:00
7d9893c614 fixed build error 2018-09-09 17:27:53 -04:00
3540712517 some cleanup 2018-09-09 08:38:12 -04:00
a8b1a86bd7 X25519Keys for static key 2018-09-08 22:08:08 -04:00
1babd3a5a2 separate X25519Keys 2018-09-08 16:52:42 -04:00
5ecd04dd4f Merge pull request #1240 from PurpleI2P/openssl
eddsa from 1.1.1
2018-09-08 16:22:12 -04:00
50399e5194 fix #1238 (#1239) 2018-09-06 21:27:28 +00:00
b734acf1b1 -latomic for gcc >= 5 only 2018-09-06 11:19:10 -04:00
33aa8e2471 use x25519 from openssl 1.1.1 for ephemeral keys 2018-09-05 11:19:58 -04:00
2c58fe736b fixed build error with openssl 1.1.1 2018-09-05 09:51:03 -04:00
6fe1de5d86 fix make target dependecy 2018-09-04 10:51:44 +03:00
064460b95f osx makefile changes
Move install target from osx to homebrew
use openssl 1.1.0 when building with brew
2018-09-04 10:39:46 +03:00
2c3b19a539 use EdDSA from openssl 1.1.1 2018-09-03 17:39:49 -04:00
dc30a4c1ae Merge pull request #1234 from l-n-s/fix_typo
Fix typo
2018-09-02 15:50:22 -04:00
86e9901bf2 Fix typo 2018-09-02 15:39:23 -04:00
6519e0835a fixed typo 2018-09-02 07:51:58 -04:00
a52344fc01 Merge pull request #1226 from radfish/PR--make-latomic
makefile: linux: add -latomic
2018-09-01 13:31:17 -04:00
b67424643d done insert NTCP2 ipv6 address twice 2018-08-27 18:56:57 -04:00
575a4c01c9 publish NTCP2 adress if port is specified 2018-08-27 18:35:35 -04:00
f0d4ee6618 pass NTCP2 ipv6 address 2018-08-27 16:01:47 -04:00
8753186a0d publish NTCP2 ipv6 address if applicable 2018-08-27 15:01:43 -04:00
ff8fb8000d Merge pull request #1231 from majestrate/fix-socks-outproxy
enable outproxy on socks
2018-08-26 10:20:39 -04:00
9dd38b99d6 check NTCP2 for addreses comparison 2018-08-26 09:40:27 -04:00
dfe08c1ec9 enable outproxy on socks 2018-08-26 09:24:11 -04:00
fb26e78ecc Merge branch 'openssl' of https://github.com/purplei2p/i2pd into openssl 2018-08-25 14:03:21 -04:00
4c687036c4 enable socks outproxy 2018-08-25 14:01:57 -04:00
062d8d0f4f fixed potential race condition 2018-08-25 13:27:03 -04:00
73b6338f62 Merge pull request #1229 from PurpleI2P/openssl
2.20
2018-08-23 11:21:49 -04:00
c0d1e2c07a 2.20 2018-08-23 18:10:05 +03:00
e70feceafe add install target in OSX Makefile for homebrew formula 2018-08-23 18:06:37 +03:00
71ac0286b1 2.20.0 2018-08-23 10:24:44 -04:00
022f4d2c11 don't send message to not established session 2018-08-23 07:23:50 -04:00
a83a839cff Build docker image from openssl branch 2018-08-22 18:22:54 -04:00
b259ee89aa send RouterInfo from NTCP2Server's thread 2018-08-22 12:33:43 -04:00
65cf14bfce update android miniupnpc to 2.1 2018-08-20 01:01:27 +03:00
d9476fb5ca set correct IV when NTCP2 address gets published 2018-08-19 16:17:57 -04:00
9882365ab4 fix NTCP IPv6 category name in transports, add conversion for leasesets expiring time 2018-08-18 22:56:31 +00:00
2d758ce963 change cost for NTCP and NTCP2 2018-08-18 13:52:35 -04:00
1dd003d26a check m2p3len 2018-08-18 08:27:36 -04:00
0df5b77595 makefile: linux: add -latomic
Tested on Arch Linux and Debian unstable with gcc 8.2.0. On Arch Linux
on x86_64 it built without this, but also builds with this. Without this
patch On Debian unstable on PPC linking fail with undefined symbols:
/usr/include/c++/8/bits/atomic_base.h:396: undefined reference to `__atomic_load_8'
2018-08-17 23:24:37 -04:00
e190a005db make sure assets are ready before proceed 2018-08-17 11:17:17 -04:00
45596a0342 android - holder-based updater for certificate
If holder exsists, check string (version) of assets creation.
If it differs from current app version or null, try delete certificates forder contents
for unpacking new certificates.
2018-08-17 01:41:26 +03:00
405429a300 android - add file for notify about successful unpacking assets 2018-08-16 23:34:05 +03:00
d009a29426 android - dont rewrite files from assets if they exist 2018-08-16 23:34:04 +03:00
f1fb42460a rename ipv6 transports 2018-08-16 23:34:04 +03:00
5e110e9f7b enable NTCP2 by default 2018-08-16 13:48:47 -04:00
77a409935d license added 2018-08-16 13:46:59 -04:00
863baeb68b ignore unpublished addresses 2018-08-16 11:02:53 -04:00
11142690a0 show correct value of time drift 2018-08-16 10:13:32 -04:00
02e8c5faca fixed typo 2018-08-15 13:23:10 -04:00
c41081d35c check timestamps 2018-08-15 11:42:56 -04:00
db4c26a400 copy assets before daemon start 2018-08-15 09:52:13 -04:00
331a23fc20 build JNI for arm v7a and x86 both 2018-08-14 22:44:08 +03:00
db5a40d743 enable NTCP2 for android, use L flag for bandwidth,
additional change for multiarch build
2018-08-14 22:41:12 +03:00
e4ab51329d move handshake messages processing to NTCP2Establisher 2018-08-14 14:01:04 -04:00
8490e7ca7c Merge pull request #1223 from PurpleI2P/openssl
recent changes
2018-08-14 13:50:44 -04:00
86782aeb1b don't send RouterInfo twice 2018-08-14 11:27:27 -04:00
49a44fc92e assume siphash IV in Litte Endian 2018-08-13 14:07:57 -04:00
cd39a52c25 correct endianness for siphash length 2018-08-13 13:43:51 -04:00
634101ceb5 Update HTTPServer.cpp
Fix transport sections in web interface 2
2018-08-13 22:29:58 +05:00
55555c8787 Merge pull request #1222 from PurpleI2P/show-transports
Update HTTPServer.cpp
2018-08-13 12:43:31 -04:00
d36d825ac1 Update HTTPServer.cpp
Fix transport sections in web interface
2018-08-13 21:41:43 +05:00
9bb01cd67c Merge pull request #1221 from l-n-s/issue_1220
Don't add SSU/NTCP addresses to RI if they are disabled in config
2018-08-12 13:19:56 -04:00
29b91075d2 Don't add SSU/NTCP addresses to RI if they are disabled in config (#1220) 2018-08-12 02:36:00 -04:00
6d46fc9f9f check send frame error code 2018-08-11 16:08:21 -04:00
a2c41c9e36 allow NTCP2 only transports 2018-08-10 15:35:43 -04:00
ee700ac861 fixed incorrect iv for published NTCP2 addresses 2018-08-10 15:14:07 -04:00
9884a4336f don't connect to NTCP2 only address using NTCP 2018-08-10 13:42:59 -04:00
5b83d4bef8 move handshake messages creation to NTCP2Establisher 2018-08-10 10:53:34 -04:00
d320a89590 don't copy buffer to ifself 2018-08-09 16:32:43 -04:00
f7e4afc282 use same buffer for input and output for AEAD/Chacha20/Poly1305 2018-08-09 15:47:02 -04:00
88e87d589b add incoming NTCP2 session to the sessions list 2018-08-09 14:20:10 -04:00
d8c6dede7e moved NTCP2 handshake buffers to establisher 2018-08-09 12:53:36 -04:00
5cc84133e3 fixed incorrect lenght 2018-08-08 17:38:21 -04:00
f7728aa1f6 reuse NTCP2 frame buffers 2018-08-08 16:23:44 -04:00
2b61f9a731 fixed #1217. verify decryption result 2018-08-07 10:35:25 -04:00
f407022fe6 connect to NTCP2 address if presented 2018-08-04 13:48:09 -04:00
41b9f19b01 get unpublished NTCP2 address 2018-08-04 08:47:58 -04:00
09c6faf923 don't overwrite NTCP2 keys 2018-08-03 21:16:35 -04:00
26d0177c01 always make NTCP address first 2018-08-03 20:28:29 -04:00
f7415c8a8f enable/disable NTCP2 address 2018-08-03 14:49:28 -04:00
4cf79088f9 NTCP2 idle timeout 2018-08-03 13:19:35 -04:00
50cd321818 NTCP2 idle timeout 2018-08-03 13:10:32 -04:00
83bbe6a9d9 show NTCP2 address 2018-08-03 12:07:09 -04:00
0a33c18e36 send termination message 2018-08-02 15:31:15 -04:00
6cf158ac63 check RouterInfo from SessionConfirmed 2018-08-02 13:58:47 -04:00
f96bfa6afa send RouterInfo 2018-08-02 12:42:39 -04:00
2b64cf9126 publish i in correct place for NTCP2 2018-08-01 12:28:34 -04:00
a8dcfc44f5 handle termination message 2018-08-01 09:43:48 -04:00
0ff9c9da27 complete Bob side of NTCP2 2018-07-31 15:41:13 -04:00
07e7c2d852 ntcp2.published and ntcp2.port parameters 2018-07-31 12:59:38 -04:00
10e4b5b2a3 ignore NTCP2 addresses 2018-07-23 15:44:36 -04:00
998653ea9d NTCP2 acceptors 2018-07-23 15:30:51 -04:00
1a38e925bf publish NTCP2 address 2018-07-23 13:51:29 -04:00
c8f51380e6 publish NTCP2 for new routers 2018-07-21 16:59:58 -04:00
2406d57d51 update android target API to 28, use gradle and ndk parallel building 2018-07-21 00:02:54 +03:00
cb1e47eb71 use preconfigured configs for android package 2018-07-20 23:15:22 +03:00
c0a650f28b update gitignore 2018-07-20 23:04:29 +03:00
460cf6fd20 update windows build script, change makefile.mingw line ending 2018-07-20 22:57:47 +03:00
5bedfc1c84 post I2NP messages to NTCP2 thread 2018-07-19 12:46:19 -04:00
5001592fb4 replace ntcp2 by ntcp2.enabled 2018-07-19 09:45:24 -04:00
f6495e59c5 better MixHash 2018-07-19 09:27:59 -04:00
66bf431481 correct KDF1 calculation 2018-07-18 16:27:43 -04:00
d9685e991e handle RouterInfo block 2018-07-18 15:57:18 -04:00
e0790700cd don't connect to unpublished NTCP2 addresses 2018-07-18 14:19:12 -04:00
910a9600bd display NTCP2 session in web console 2018-07-18 12:58:29 -04:00
fc52b2b940 fixed typo 2018-07-18 12:56:46 -04:00
b99f828583 send I2NP messages through NTCP2 2018-07-18 11:16:40 -04:00
f38891cace fixed build for gcc < 4.8 2018-07-18 11:15:27 -04:00
8c5111e11a handle NTCP2 I2NP messages 2018-07-17 15:17:05 -04:00
5575b981c8 enable NTCP2 as transport 2018-07-13 15:59:28 -04:00
0b36732911 Merge pull request #1212 from yangfl/upstream
fix typo
2018-07-10 06:59:35 -04:00
52f3081a40 fix typo 2018-07-10 17:39:21 +08:00
00c71dc26a handle SessionConfirmed 2018-07-09 15:56:23 -04:00
5218c8584f some refactoring of NTCP2 code 2018-07-04 14:15:40 -04:00
6054bd6621 NTCP2 session establisher 2018-07-03 16:26:02 -04:00
55af4ed385 delete old AESNI definition 2018-06-29 02:30:03 +03:00
64aee9c8ae add DEBUG option for make
By default, binary will be built without stripping debug symbols
2018-06-29 02:27:19 +03:00
5233e72205 add assets symlinks 2018-06-27 23:56:52 +03:00
db5b45222a store and install assets on android 2018-06-27 23:56:52 +03:00
fc4787da4e Merge pull request #1207 from AMDmi3/defined-in-macro
Fix "macro expansion producing 'defined' has undefined behavior" clang warning
2018-06-27 15:36:34 -04:00
4ffbb46cf9 Fix "macro expansion producing 'defined' has undefined behavior" clang warning 2018-06-27 22:31:01 +03:00
c3c2550f17 Merge pull request #1205 from AMDmi3/fix-cpp-lib
Limit tampering with standard C++ library to Linux
2018-06-27 11:01:22 -04:00
41e8ab5383 Limit tampering with standard C++ library to Linux
Otherwise it breaks e.g. FreeBSD build where it is not needed at all
2018-06-27 17:47:22 +03:00
a802940616 Merge pull request #1204 from yangfl/upstream
use builtin __AVX__ and __AES__ macros and reduce code duplication
2018-06-27 07:08:26 -04:00
dec848f072 use builtin __AVX__ and __AES__ macros and reduce code duplication 2018-06-27 17:32:38 +08:00
fb229d4064 Merge pull request #1203 from PurpleI2P/openssl
2.19
2018-06-26 13:58:07 -04:00
fc16e76af1 2.19.0 2018-06-26 17:46:01 +00:00
0dff636dbe 2.19.0 2018-06-26 13:38:02 -04:00
00df3f8d4e 2.19.0 2018-06-26 13:36:30 -04:00
34c45f2694 update debian changelog 2018-06-26 20:05:33 +03:00
a188de2e5c increase limits by default, fix symbolic links, change rules 2018-06-26 20:05:33 +03:00
27fbf67352 add systemd configs, change build info, update changelog 2018-06-26 20:05:33 +03:00
b226e22d2f fixed QT build 2018-06-26 07:25:16 -04:00
5bc157eb19 send data frame for NTCP2 2018-06-25 12:28:07 -04:00
f4122abbad Merge pull request #1201 from PurpleI2P/revert-1200-use-explicitpeer-settings
Revert "Read explicitPeer config settings into params"
2018-06-24 06:46:41 -04:00
f0b32e3f54 Revert "Read explicitPeer config settings into params" 2018-06-24 06:46:22 -04:00
fe00999b2c Merge pull request #1200 from shakamd/use-explicitpeer-settings
Read explicitPeer config settings into params
2018-06-24 06:26:21 -04:00
39eed0f6fb Read explicitPeer config settings into params 2018-06-23 23:52:16 +00:00
510d29b381 gcc 8 arch support 2018-06-23 06:56:05 -04:00
0aa618b938 process AEAD/Chacha20/Poly1305 frame for data phase of NTCP2 2018-06-22 15:02:49 -04:00
5884852612 correct usage of sipkeys 2018-06-22 12:20:35 -04:00
5b29592174 generate sipkeys for data pahse of NTCP2 2018-06-21 16:24:19 -04:00
96411cc93e derive keys for siphash 2018-06-21 12:39:24 -04:00
7d862d8eba service and daemon works as bool without values, other requires true/false 2018-06-21 09:40:53 +03:00
dd392941d0 update Config.cpp, links to examples, manpage 2018-06-21 09:40:53 +03:00
3cec5235c9 NTCP2 according to new specs 2018-06-20 16:09:22 -04:00
b5682012d3 process SessionRequest and send SessionCreated for NTCP2 2018-06-19 15:43:47 -04:00
4351a2736c Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2018-06-19 11:17:14 -04:00
9c7cadb191 better implementation of x25519 2018-06-19 11:14:22 -04:00
4d9143734f store standart configs as docs in deb packages 2018-06-19 15:11:48 +03:00
3cec923294 Update tunnels.conf 2018-06-19 15:08:16 +03:00
58c92b8405 aead/chacha20/poly1305 from openssl 1.1 2018-06-18 12:56:47 -04:00
985b618932 addng forgotten bracket 2018-06-16 23:07:03 +03:00
a027a42c46 fix links to online documentation in manpage 2018-06-16 22:57:18 +03:00
bdc7acffbe remove zero_tokens(), update manpage 2018-06-16 22:38:59 +03:00
6bd73cdea2 Update help message, debian manpage. Prepare changelog message 2018-06-16 18:11:46 +03:00
59954c1d7c Merge pull request #1194 from l-n-s/doc_update
Update contrib/i2pd.conf file with more options
2018-06-16 12:28:42 +00:00
a59cdcc9e0 Update contrib/i2pd.conf file with more options 2018-06-16 08:05:43 -04:00
e1bfa786fc fix #1192 2018-06-16 11:59:54 +03:00
d5214099c5 move out android binary build info from README
little change in MSYS build script
2018-06-16 10:55:59 +03:00
e05110ff44 send RouterInfo in SessionConfirmed 2018-06-15 14:56:03 -04:00
706b976a28 handle and publish NTCP2 address 2018-06-15 12:52:43 -04:00
2bd7a92d20 send SessionConfirmed 2018-06-14 15:29:36 -04:00
6b37a41e00 correct ad calculation for SessionCreated 2018-06-14 10:45:25 -04:00
5447259e1a AEAD/ChaCha20/Poly1305 decryption and SessionCreate prcessing 2018-06-13 16:16:23 -04:00
ee0ae0b74b decrypt Y for NTCP2 2018-06-13 14:56:51 -04:00
966256ac32 correct Poly1305 calculation 2018-06-13 12:58:32 -04:00
6b9061515f AEAD/ChaCha20/Poly1305 test added 2018-06-13 12:25:32 -04:00
df60e78766 AEAD/Chacha20/Poly1305 encryption 2018-06-13 11:41:46 -04:00
bf1e1ad457 eliminate extra dependencies 2018-06-13 10:49:14 -04:00
7fa5b06359 x25519 unti test 2018-06-12 18:29:06 -04:00
3b46e9f351 fixed typo 2018-06-12 14:55:40 -04:00
046a80cfe4 scalar multiplication for x25519 2018-06-12 12:42:20 -04:00
a8278fc78b router's NTCP2 private keys 2018-06-11 15:33:48 -04:00
7f3127ac89 pass unencrypted X to KDF 2018-06-11 14:32:15 -04:00
7cdb021a1f pass correct nonce to chacha20 2018-06-11 14:05:30 -04:00
74c0b729c2 connect to NTCP2 2018-06-11 12:29:30 -04:00
5cb81f8532 send SessionRequest message 2018-06-06 15:38:18 -04:00
4f23d7b7df recognize routers with NTCP2 2018-06-06 11:51:34 -04:00
a70d0edf2e encrypt SessionRequest options block 2018-06-05 16:15:33 -04:00
8c9eaccc11 KeyDerivationFunction for NTCP2 2018-06-05 15:37:08 -04:00
86c1984982 NTCP2 added 2018-06-05 12:53:13 -04:00
cd0f75106a moved Ed25519 away from signature 2018-06-04 16:06:38 -04:00
b5291b5151 Merge pull request #1190 from vmon/resolve--tunnel-get-ready-timout-bug
fixes #1124 and calls the ready callbacks if the tunnel gets ready an…
2018-05-29 09:10:02 -04:00
46283dc0ea fixes #1124 and calls the ready callbacks if the tunnel gets ready and no timeout is set 2018-05-28 17:14:17 -04:00
56e76ec59f fix using debug library compilation in release mode 2018-05-28 19:41:23 +03:00
4cedaa9e80 fixed android build 2018-05-28 09:49:59 -04:00
516f140bef ntcp2 crypto added 2018-05-24 14:32:14 -04:00
5d86c1c9a6 ntcp2 crypto added 2018-05-24 14:27:26 -04:00
d289aa71eb Merge pull request #1184 from mewmew-i2p/openssl
closes #1164 (i.e. added a log viewer to qt), + misc cosmetic
2018-05-19 14:44:39 -04:00
ed2818eaa2 qt log viewer now works 2018-05-19 23:06:06 +08:00
f8fe124428 improved comment at qt.pro file 2018-05-19 23:06:06 +08:00
5ec11c53e9 differentiation between windows release and debug build into i2pd_qt.pro 2018-05-19 23:06:05 +08:00
42d118d9a2 Merge pull request #1182 from l-n-s/issue_1178
Add /etc/resolv.conf to apparmor profile and k flag for pidfile
2018-05-18 19:56:29 +00:00
d8b4765f23 Add /etc/resolv.conf to apparmor profile and k flag for pidfile 2018-05-18 15:54:39 -04:00
be69280d0d Merge pull request #1181 from l-n-s/issue_1177
Restore reseed certificate hottuna_at_mail.i2p.crt
2018-05-18 19:47:32 +00:00
53a1a097a6 Restore reseed certificate hottuna_at_mail.i2p.crt 2018-05-18 15:45:35 -04:00
a22e9a2ca7 don't start shared local destination twice 2018-04-30 13:34:16 -04:00
db03595473 correct message size 2018-04-29 18:05:28 -04:00
8fadac0fdc Merge pull request #1172 from majestrate/check-boundary-04-2018
Check boundary
2018-04-29 18:04:15 -04:00
a63bc1cdca correct sizes 2018-04-29 11:41:03 -04:00
6265d452e9 more bounds checking 2018-04-29 11:34:23 -04:00
b095399770 Merge pull request #1170 from unlnown542a/openssl
Separated buld directory for Android i2pd only binary
2018-04-26 17:19:39 -04:00
Al
db8a546b8f android i2pd executable build instructions 2018-04-26 20:07:51 +00:00
6e95318cba I2PD_LIBS_PATH = /path/to/libraries to be same as in android normal build 2018-04-26 22:44:32 +03:00
08a8ab9892 format 2018-04-26 22:42:12 +03:00
c7b796ff31 separate Android binary build based on DaemonLinux 2018-04-26 22:40:13 +03:00
ad23ccb219 separating android binary build 2018-04-26 22:28:30 +03:00
Al
be7a84fdf3 Merge pull request #2 from PurpleI2P/openssl
sync with main repo
2018-04-26 16:53:56 +00:00
2fbbbf298b use shared pointers for tunnel reload 2018-04-25 16:18:07 -04:00
0df68872ab Merge pull request #1169 from majestrate/master
SAM fixes
2018-04-25 12:02:51 -04:00
0ced38cdcb tabify 2018-04-25 11:27:56 -04:00
b046c45a9e tabify 2018-04-25 11:25:49 -04:00
2ce1ab1634 Merge pull request #1168 from mewmew-i2p/openssl
perfecting qt status page
2018-04-25 10:21:17 -04:00
7225231814 perfecting qt status page 2018-04-25 16:36:42 +08:00
11dca2b352 Merge pull request #1167 from borned-mind/openssl
Delete some for correct compilation
2018-04-24 15:04:12 -04:00
97127e86dc Delete some for correct compilation 2018-04-25 01:59:11 +07:00
cb81195959 Merge pull request #1166 from borned-mind/openssl
Disable aesenc for arm64
2018-04-24 14:51:57 -04:00
adaff9f354 Merge branch 'openssl' of https://github.com/borned-mind/i2pd into openssl 2018-04-25 01:34:40 +07:00
66de7ad049 for first time disable aesenc for arm64 2018-04-24 18:23:40 +00:00
1e1e4da144 delete buffer 2018-04-24 14:02:48 -04:00
623433099b don't use reset 2018-04-24 11:50:51 -04:00
73b3fbc2da wrap m_OpenSockets with mutex 2018-04-24 11:42:37 -04:00
5f525d0e43 fix previous commit 2018-04-24 11:16:15 -04:00
60463fdafa shut down socket and don't allocate buffer for each write in WriteI2PData 2018-04-24 11:11:48 -04:00
b7a67b4b03 use refernce not copy 2018-04-24 09:56:24 -04:00
4643c92d33 Initial SAM cleanup 2018-04-24 09:45:16 -04:00
396cba7339 fix static building on windows, add resource files (closes #1163) 2018-04-24 03:25:25 +03:00
a2b3ee53e0 fixed build error 2018-04-23 14:39:46 -04:00
2c67d2055c Merge pull request #1161 from mewmew-i2p/openssl
qt now statically compiles for win32
2018-04-23 13:45:55 -04:00
c8de7aa23c qt now statically compiles for win32 2018-04-24 01:40:12 +08:00
fa154cc4d6 Merge remote-tracking branch 'purple/openssl' 2018-04-22 07:52:49 -04:00
d9b8731ddc Merge pull request #1160 from unlnown542a/openssl
A small pach into main trunk to build cponsole Android i2pd binary
2018-04-21 16:06:27 -04:00
Al
6cebc1a2a2 Merge pull request #1 from PurpleI2P/openssl
merge "mainline"
2018-04-21 19:10:05 +00:00
faac35cd1e Revert "Change jni to build executable. Clone with minimal changes DaemonUnix into DaemonAndroid"
This reverts commit f11266972e.
2018-04-21 21:55:45 +03:00
6916147dda Few cents to get fullly console i2pd under Android 2018-04-21 21:48:42 +03:00
e2da16e9c3 moved reseed out 2018-04-19 19:46:00 +03:00
0c661e7373 save new local destination for failed insert 2018-04-18 15:08:06 -04:00
413f8e8462 Merge pull request #1159 from majestrate/gut-streaming-limits
remove streaming bans
2018-04-16 10:06:27 -04:00
eefbbd4efe remove all related streaming limit members 2018-04-16 09:47:35 -04:00
83932a6f02 remove streaming bans 2018-04-16 09:38:32 -04:00
c175dc30f8 correct uri for outproxy 2018-04-13 16:29:49 -04:00
17aa91803a update outproxy header in right place 2018-04-13 15:40:25 -04:00
48099a367e send correct buffer to outproxy 2018-04-13 15:13:50 -04:00
a9b64893d8 replace Proxy-Authorization 2018-04-13 12:47:53 -04:00
387e030d83 correct cleanup for CONNECT 2018-04-12 21:25:20 -04:00
855cc9ed83 correct Proxy-Authroization 2018-04-12 19:10:21 -04:00
82534eef12 try fix appveyor build 2018-04-11 20:58:21 +03:00
ff4e254618 0.9.34 2018-04-11 10:30:13 -04:00
571a13f0a7 Merge remote-tracking branch 'purple/master' 2018-04-08 19:56:48 -04:00
2cb6283d00 outproxy authorization 2018-04-06 15:23:56 -04:00
f4056e57bb rollback 2018-04-05 07:16:41 -04:00
e80da3cbeb fixes for i2pd_qt MSYS2 mingw32 2018-04-05 15:40:44 +08:00
c0436297c2 fix typo in systemd service type 2018-04-01 23:37:36 +03:00
0d05b4f095 Merge pull request #1154 from yangfl/upstream
fix systemd service type
2018-03-31 16:53:58 +03:00
f06c8710be fix systemd service type 2018-03-31 14:56:45 +08:00
f11266972e Change jni to build executable. Clone with minimal changes DaemonUnix into DaemonAndroid 2018-03-30 15:50:30 +03:00
479edaf80d Merge pull request #1149 from majestrate/fix-ntcp-threading-race
Fix ntcp threading race
2018-03-24 08:29:04 -04:00
ff5c26adf2 Merge remote-tracking branch 'purple/openssl' into fix-ntcp-threading-race 2018-03-24 07:56:49 -04:00
5361e11395 fix race 2018-03-24 07:53:06 -04:00
b041bcdc65 publish updated LeaseSet in destination's thread 2018-03-23 11:41:36 -04:00
b7c350202d always create EdDSA RouterInfo 2018-03-20 20:43:47 -04:00
b1a6c5ddf7 fixed build for gcc 4.7 2018-03-16 11:12:18 -04:00
ac943b5712 Merge pull request #1147 from PurpleI2P/cmake-libs
WITH_LIBRARY usage
2018-03-12 12:35:34 +03:00
ce8d701ecb WITH_LIBRARY usage
closes #1146. Need to be checked before.
2018-03-11 19:20:47 +03:00
182ffe4495 use croorect encryption type for tunnel build 2018-03-09 14:56:06 -05:00
c13983d395 Merge pull request #1145 from PurpleI2P/openssl
recent changes
2018-03-09 14:47:56 -05:00
066f8863fd pass zero padding parameter to ECEIS encryption 2018-03-07 16:08:44 -05:00
e58aaa3f32 make sure tunnelID is non-zero 2018-03-07 12:36:38 -05:00
ca1fa11cb1 Merge pull request #1143 from l-n-s/i2pcontrol_updates
I2pcontrol updates
2018-03-05 14:34:31 -05:00
64ed485cdf Merge pull request #1142 from ffontaine/openssl
Create LogsDirectory in i2pd.service
2018-03-05 21:30:09 +03:00
b0781668e2 Create LogsDirectory in i2pd.service
Create /var/log/i2pd through LogsDirectory parameter of systemd and set
its permission to 0700 through LogsDirectoryMode. Indeed, this directory
must be created with the correct permission as it is used in ExecStart
command

Signed-off-by: Fabrice Fontaine <fontaine.fabrice@gmail.com>
2018-03-05 19:06:14 +01:00
f9fc744949 Merge remote-tracking branch 'upstream/openssl' into i2pcontrol_updates 2018-03-05 12:35:10 -05:00
2661db23f6 I2PControl: fix indentation 2018-03-05 12:34:41 -05:00
7d78f60d29 Merge pull request #1140 from ffontaine/openssl
Install libi2pdclient
2018-03-05 10:58:07 -05:00
1d934bd543 Install libi2pdclient
When building with -DBUILD_SHARED_LIBS=ON, libi2pdclient is not
installed on target so install it by calling install. Moreover, rename
i2pdclient to libi2pdclient so library is installed with correct name.

Signed-off-by: Fabrice Fontaine <fontaine.fabrice@gmail.com>
2018-03-05 15:17:23 +01:00
190435acd9 Merge pull request #1138 from ffontaine/openssl
Fix cmake error when -DBUILD_SHARED_LIBS=ON
2018-03-04 15:35:28 -05:00
656236cb4d Merge pull request #1137 from yangfl/upstream
Makefile: add detection for GNU userspace
2018-03-04 14:48:45 -05:00
6d15be9a32 Fix cmake error when -DBUILD_SHARED_LIBS=ON
Fixes "CMake Error: TARGETS given no LIBRARY DESTINATION for shared
library target" by adding LIBRARY parameter to INSTALL call

Signed-off-by: Fabrice Fontaine <fontaine.fabrice@gmail.com>
2018-03-04 18:31:02 +01:00
18d3c81018 Makefile: add detection for GNU userspace 2018-03-05 00:51:53 +08:00
12292afdec I2PControl: s/remote_endpoint/peer 2018-03-04 11:28:09 -05:00
aef0f4d7b8 Merge pull request #1135 from l-n-s/issue_954
I2PControl: add new method ClientServicesInfo
2018-03-03 07:48:46 -05:00
21545ab7da I2PControl: add new method ClientServicesInfo 2018-03-03 05:52:11 -05:00
5a2b795440 fixed crash 2018-02-26 19:41:24 -05:00
1303dd478c Merge pull request #1130 from majestrate/i2cp-session-reconfig
implement i2cp session reconfigure
2018-02-26 09:33:25 -05:00
7b4fc19fca be concise 2018-02-26 08:18:01 -05:00
008a064764 revert 2018-02-26 08:12:15 -05:00
82a4630061 use correct function 2018-02-26 08:09:26 -05:00
0f77b4810d revert 2018-02-26 08:00:07 -05:00
2f7cfddfc4 Merge remote-tracking branch 'purple/openssl' into i2cp-session-reconfig 2018-02-26 07:58:03 -05:00
84608c16b3 Merge pull request #1128 from majestrate/fix-issue-1126
Fix issue 1126
2018-02-25 09:34:58 -05:00
157411dcc6 Revert "fix issue #1124"
This reverts commit 29e861d1e6.
2018-02-25 08:51:07 -05:00
59672d23cc Merge branch 'fix-issue-1124' into fix-issue-1126 2018-02-25 08:50:27 -05:00
ce30f89c60 make it compile :D 2018-02-25 08:49:39 -05:00
ce9c9411b1 fix issue #1126 2018-02-25 08:47:39 -05:00
cf0d5b616d Merge pull request #1125 from majestrate/fix-issue-1124
fix issue #1124
2018-02-22 16:18:37 -05:00
29e861d1e6 fix issue #1124 2018-02-22 06:54:33 -05:00
c7accd4a5c Merge pull request #1122 from majestrate/ntcp-threadpool
NTCP threadpool
2018-02-20 14:49:01 -05:00
b469080cd7 make ntcp worker threads configurable in number 2018-02-20 13:18:57 -05:00
547a0057e6 whitespace cleanup 2018-02-20 13:04:39 -05:00
b980ca4a9e whitespace cleanup 2018-02-20 13:03:34 -05:00
098b2e968e whitespace cleanup 2018-02-20 13:03:01 -05:00
cd59ca8376 whitespace cleanup 2018-02-20 12:59:39 -05:00
f2e6fad104 make it work 2018-02-20 12:40:28 -05:00
8d7fde0287 more 2018-02-20 11:43:13 -05:00
91fdb038d9 add threadpool for ntcp dh 2018-02-20 11:38:48 -05:00
a0188765c5 Merge pull request #1121 from majestrate/aesni-osx
More OSX fixes
2018-02-19 12:29:34 -05:00
b970a005de don't log AESNI/AVX here 2018-02-19 10:45:13 -05:00
b64878f4fa use std::move 2018-02-19 10:45:02 -05:00
c8936c79bf Merge pull request #1120 from majestrate/aesni-osx
FIX AESNI build on osx with homebrew
2018-02-19 10:19:45 -05:00
f876cc9079 update makefile 2018-02-19 10:16:48 -05:00
a5cc2f3b5d define bit_* if not already defined 2018-02-19 10:15:39 -05:00
9c93d6f931 Revert "define cpu_* if not set"
This reverts commit a077d7671f.
2018-02-19 10:15:26 -05:00
a077d7671f define cpu_* if not set 2018-02-19 10:15:03 -05:00
6485ebe9a7 Merge pull request #1119 from PurpleI2P/docker_build_badge
Added docker build badge
2018-02-18 20:24:32 +01:00
ecb6bb220a Added docker build badge 2018-02-18 20:21:19 +01:00
e3dc400d74 Merge pull request #1117 from hypnosis-i2p/openssl
fixed #1104
2018-02-17 14:49:18 -05:00
3bb4151074 fixed #1104 - android 2018-02-18 01:01:48 +08:00
1de4c2e8c6 perms prompt now doesn't show the back button - android 2018-02-18 00:25:58 +08:00
fbcc4f28e7 removed design lib from deps - android 2018-02-17 23:55:30 +08:00
30fb0f5a94 Merge pull request #1116 from majestrate/netbsd
NetBSD support
2018-02-17 07:22:51 -05:00
b02464990b work around netbsd quarkyness 2018-02-16 18:54:34 -05:00
4988a32d33 make endian work with netbsd 2018-02-16 18:27:30 -05:00
b3e5874631 fixed android build error 2018-02-16 13:56:44 -05:00
f5349dcef9 Merge pull request #1115 from majestrate/aesni-avx-runtime-detect
AESNI/AVX runtime detection [WIP]
2018-02-16 12:40:28 -05:00
486a4cfdd6 add to qt 2018-02-16 12:36:51 -05:00
2277dcb069 add cpu.cpp to cmake 2018-02-16 12:34:17 -05:00
a618a01b1e don 2018-02-16 11:26:07 -05:00
7e60069968 add uncommitted files 2018-02-16 11:01:04 -05:00
91e45d9a4a initial code for runtime detection of aesni/avx 2018-02-16 11:00:33 -05:00
dea6fbf285 Merge pull request #1114 from majestrate/websocks-datagram
Add datagrams to websocks tunnel
2018-02-16 09:18:24 -05:00
48cc0f4289 use write 2018-02-16 08:33:19 -05:00
cdc5fce583 check port 2018-02-16 08:31:20 -05:00
b41a17d548 add datagrams to websocks 2018-02-16 08:26:46 -05:00
606cbaa519 Merge pull request #1113 from majestrate/sam-xss-fix
fix xss in webui from SAM session name
2018-02-16 07:02:55 -05:00
aaf8f527ef fix xss in webui from SAM session name 2018-02-16 06:28:22 -05:00
b7596b7f70 Merge pull request #1112 from majestrate/dns-rebind
mitigate dns rebinding in webui
2018-02-15 09:57:16 -05:00
0309b574e8 mitigate dns rebinding in webui 2018-02-15 09:52:20 -05:00
ca057177c7 Merge pull request #1110 from radfish/PR--remove-openssl-1.1-warning
cmake: remove warning for OpenSSL 1.1
2018-02-11 14:36:03 -05:00
5d9bf18267 Merge pull request #1109 from radfish/PR--clang-stdlib-fix
cmake: add stdlib args for clang build on Linux
2018-02-11 14:35:32 -05:00
f1b8742782 cmake: remove warning for OpenSSL 1.1
Works fine.
2018-02-11 13:14:12 -05:00
7786c97330 cmake: add stdlib args for clang build on Linux
Otherwise linking fails with undefined symbol ... basic_string ... and
libstdc++: DSO not on included in link command.

or with
Host compiler must support std::atomic!
which is due to
undefined reference to `__gxx_personality_v0' and __cxa_begin_catch and
std::terminate()

This was already patched in 7b537a4e94
PR #972 but it got lost, and also needed some tweaking.

Thested with Clan 5.0.1 on Arch Linux (on armv7h).
2018-02-11 13:11:12 -05:00
f2a14047eb Merge pull request #1108 from majestrate/fix-issue-1107
Fix issue 1107
2018-02-11 06:48:01 -05:00
124a9cb030 correction 2018-02-11 06:07:43 -05:00
3ec000d0f8 fix issue #1107 2018-02-11 06:06:14 -05:00
aac1141ca6 fix issue #1107 2018-02-11 06:05:41 -05:00
33cb96126a appveyor: remove catgets before try update 2018-02-10 19:23:07 +03:00
441db9ad7f fix appveyor build 2018-02-10 19:20:44 +03:00
5225e1d7d1 * HTTP.cpp : use bare snprintf() instead locale-dependent strftime() 2018-02-10 12:40:01 +00:00
de849b3f6a fix date in webconsole page header on windows 2018-02-10 03:10:32 +03:00
fb4387c41f Merge pull request #1103 from hypnosis-i2p/openssl
build.gradle auto-indented; ndk-build is now called by gradle build
2018-02-08 07:18:39 -05:00
a9061a8f58 ndk-build is now called by gradle build 2018-02-08 12:55:09 +08:00
0c099dc52b Merge pull request #1102 from PurpleI2P/revert-1097-revert-1096-openssl
Revert "Revert "fixed #1088""
2018-02-07 14:50:30 -05:00
713e92c28f Revert "Revert "fixed #1088"" 2018-02-07 14:50:15 -05:00
d111025012 Merge pull request #1101 from PurpleI2P/revert-1098-revert-1095-openssl
Revert "Revert "reworked the app, fixed #1094, fixed grace stop""
2018-02-07 14:49:50 -05:00
5f2e6b1262 Revert "Revert "reworked the app, fixed #1094, fixed grace stop"" 2018-02-07 14:49:37 -05:00
b6d838731f Merge pull request #1100 from PurpleI2P/revert-1099-revert-1090-openssl
Revert "Revert "quit features replaced by stop; gradle upgraded; i2pd version name updated at build.gradle""
2018-02-07 14:49:05 -05:00
56db8b40b2 Revert "Revert "quit features replaced by stop; gradle upgraded; i2pd version name updated at build.gradle"" 2018-02-07 14:48:51 -05:00
f488c97a09 Merge pull request #1099 from PurpleI2P/revert-1090-openssl
Revert "quit features replaced by stop; gradle upgraded; i2pd version name updated at build.gradle"
2018-02-07 14:08:34 -05:00
31df49a884 Revert "quit features replaced by stop; gradle upgraded; i2pd version name updated at build.gradle" 2018-02-07 14:08:22 -05:00
e5fdced4ac Merge pull request #1098 from PurpleI2P/revert-1095-openssl
Revert "reworked the app, fixed #1094, fixed grace stop"
2018-02-07 14:07:40 -05:00
71546367cf Revert "reworked the app, fixed #1094, fixed grace stop" 2018-02-07 14:07:26 -05:00
857817dae8 Merge pull request #1097 from PurpleI2P/revert-1096-openssl
Revert "fixed #1088"
2018-02-07 14:07:00 -05:00
ae3fca15c7 Revert "fixed #1088" 2018-02-07 14:06:39 -05:00
6bb7382dbd Merge pull request #1096 from hypnosis-i2p/openssl
fixed #1088
2018-02-07 10:47:51 -05:00
badb837b46 fixed #1088 2018-02-07 23:22:31 +08:00
74f5b70a5d Merge pull request #1095 from hypnosis-i2p/openssl
reworked the app, fixed #1094, fixed grace stop
2018-02-07 07:25:33 -05:00
ac495da5fe fixes grac stop 2018-02-07 19:56:44 +08:00
56f6e57118 fixes grac stop 2018-02-07 19:54:19 +08:00
33735b343d fixes 1094; fixes grac stop 2018-02-07 19:24:43 +08:00
1b56d66fc8 android gitignore 2018-02-07 18:25:45 +08:00
0994211a48 android gitignore 2018-02-07 18:25:45 +08:00
62d9a47c3d android work 1 2018-02-07 18:25:45 +08:00
e77037c2b8 fixed warning 2018-02-05 11:13:25 -05:00
030a6ebb71 Merge pull request #1093 from l-n-s/rm_root_docker
Remove broken Dockerfile and it's entrypoint
2018-02-05 04:51:29 +00:00
5a657cff89 Remove broken Dockerfile and it's entrypoint 2018-02-04 23:44:49 -05:00
f3488be7af update rpm, increase release version for Fedora and CentOS 2018-02-05 05:52:12 +03:00
4af0caa506 fix build on GCC 8.0.1
https://bugzilla.redhat.com/show_bug.cgi?id=1541688
2018-02-05 05:07:26 +03:00
0728991821 Merge pull request #1092 from majestrate/master
fix federoa rawhide build with gcc 8
2018-02-03 15:18:15 -05:00
21c35f770b fix federoa rawhide build with gcc 8 2018-02-03 13:46:22 -05:00
f039af6eda Merge pull request #1090 from hypnosis-i2p/openssl
quit features replaced by stop; gradle upgraded; i2pd version name updated at build.gradle
2018-02-03 07:14:14 -05:00
eb3f703b46 gradle upgraded; i2pd version name updated 2018-02-03 19:58:09 +08:00
b88b82a85c quit features replaced by stop - more 2 2018-02-03 19:57:21 +08:00
1d0791dbf5 quit features replaced by stop - more 2018-02-03 19:56:17 +08:00
87f2eefd35 quit features replaced by stop 2018-02-03 19:55:32 +08:00
b8a2c9f955 Merge pull request #1089 from yangfl/upstream
i2pd.service: do not block system shutdown for 10 min
2018-02-02 22:26:06 +03:00
319d748639 i2pd.service: do not block system shutdown for 10 min 2018-02-03 02:29:28 +08:00
4f84d687e4 add endian detection for glibc 2018-02-03 02:27:22 +08:00
fbb9991128 remove obsoletes tag for rpm git package 2018-02-02 10:35:07 +03:00
62bac24246 Merge pull request #1086 from BOPOHA/patch-3
i2pd.spec delete obsoletes tag
2018-02-01 17:43:42 -05:00
4aa8461bea Merge pull request #1087 from BOPOHA/patch-4
systemd issue in centos 7
2018-02-01 17:43:17 -05:00
ce57a130fc systemd issue in centos 7
Not working pre-create pid-file dir (/run/i2pd).
It fixed with one of this ways:

> PermissionsStartOnly=True
or 
> ExecStartPre=/bin/mkdir -p -m 0700 /var/run/i2pd
> ExecStartPre=/bin/chown i2pd: /var/run/i2pd

First way is prefer because RuntimeDirectory's options already used.
2018-02-01 23:21:20 +01:00
80567312ed i2pd.spec delete obsoletes tag
https://github.com/PurpleI2P/i2pd/pull/1084#issuecomment-362215861

```
Resolving Dependencies
--> Running transaction check
---> Package i2pd.x86_64 0:2.17.0-20171206git.el7.centos will be updated
---> Package i2pd.x86_64 0:2.18.0-1.el7.centos will be obsoleting
---> Package i2pd-systemd.x86_64 0:2.17.0-20171206git.el7.centos will be obsoleted
--> Finished Dependency Resolution

Dependencies Resolved

==========================================================================
 Package   Arch        Version                     Repository        Size
==========================================================================
Installing:
 i2pd      x86_64      2.18.0-1.el7.centos         vorona-i2pd      915 k
     replacing  i2pd-systemd.x86_64 2.17.0-20171206git.el7.centos

Transaction Summary
==========================================================================
Install  1 Package

Total download size: 915 k
Is this ok [y/d/N]:
```
@l-n-s  thx, obsoletes tag is unneeded in next release)
2018-02-01 22:11:14 +01:00
180730f9cf fix rpm spec's (#1084)
* added spec for git package
* fixed double slashes
* changed versioning for stable builds
2018-02-01 19:37:38 +03:00
fca2693488 add centos/fedora build status 2018-02-01 01:12:06 +03:00
b6e75e9c5a Update changelog 2018-01-30 11:14:29 -05:00
4901434209 2.18.0 2018-01-30 10:41:35 -05:00
13d174c09c add tunconf in systemctl service file 2018-01-30 18:14:54 +03:00
5363c063d1 Merge pull request #1067 from l-n-s/rpm_updates
Update rpm spec and systemd unit
2018-01-30 15:12:54 +00:00
32d300248e update building stuff 2018-01-30 18:09:26 +03:00
3426906a4f [rpm] Fix changelogs to comply with guidelines, add tunconf key to systemd package 2018-01-30 10:03:53 -05:00
3aaa942c94 Merge pull request #1082 from PurpleI2P/apparmor-homedir
add users homedir to apparmor profile
2018-01-30 17:31:22 +03:00
95d8887ab0 update profile 2018-01-30 17:30:01 +03:00
6272e15b47 add users homedir to profile 2018-01-29 04:13:33 +03:00
20b4f6b24d update apparmor profile 2018-01-29 03:47:43 +03:00
6ee279d83e [rpm] Merge i2pd-systemd with i2pd package + changelog 2018-01-27 10:54:03 -05:00
b00ff43be7 Update README.md 2018-01-26 19:52:11 -05:00
dfbefee477 graceful shutdown complete if no transit tunnels anymore 2018-01-26 14:34:05 -05:00
8c2de4973c rollback 2018-01-26 14:33:06 -05:00
e1527dc137 update LeaseSet if a tunnel was deleted 2018-01-26 14:07:51 -05:00
0957f6b143 Merge pull request #1055 from yangfl/upstream
replace non-working CheckLibcxxAtomic
2018-01-26 15:33:39 +03:00
7db2e9dc4a don't verify signature twice 2018-01-25 10:32:08 -05:00
b1c701085b don't verify signature twice 2018-01-25 10:09:34 -05:00
e8d6c803cd Merge pull request #1076 from majestrate/fix-streaming-race-2018-01-25
try streaming race condition fix
2018-01-25 09:35:58 -05:00
f4a2dda94e try streaming race condition fix 2018-01-25 09:00:00 -05:00
c4216379ed Merge pull request #1074 from l-n-s/fix_docker_2
Fix docker 2
2018-01-24 19:46:38 +00:00
52195bf296 Merge remote-tracking branch 'upstream/openssl' into fix_docker_2 2018-01-24 14:42:55 -05:00
10fe75ed87 Merge pull request #1073 from majestrate/fix-netdb-ls-publish-2018-01-24
check for valid LS before updating
2018-01-24 13:00:30 -05:00
1c659d6ef6 Merge remote-tracking branch 'upstream/openssl' into fix_docker_2 2018-01-24 12:48:57 -05:00
3ac86db038 Fix Docker image error 2018-01-24 12:48:05 -05:00
4a77a03033 * Add LeaseSetBufferValidate which checks lease validity and extracts timestamp
* check for leases with LeaseSetBufferValidate before update in floodfill code as to prevent malicous nodes removing good LS
2018-01-24 10:16:51 -05:00
3820b51960 Revert "check for valid LS before updating"
This reverts commit e070ce4e34.
2018-01-24 09:44:55 -05:00
e070ce4e34 check for valid LS before updating 2018-01-24 09:36:09 -05:00
0bb0adbf3e fix addressbook fetch timeout 2018-01-24 15:34:32 +03:00
ddd25f0945 limit number of retries for subscriptions 2018-01-23 15:50:28 -05:00
162bd592f8 recreate http and socks proxy upon reload 2018-01-23 15:13:43 -05:00
85fa728d41 change shared local destination upon reload 2018-01-23 14:40:05 -05:00
c7db9010ad fixed #1047. Return EXIT_FAILURE 2018-01-23 11:01:50 -05:00
be16545063 Merge pull request #1070 from vmon/f--port-0-for-TCPAcceptor
the change allows when an TCPIPAcceptor is constructed by setting por…
2018-01-23 06:48:18 -05:00
c730839989 the change allows when an TCPIPAcceptor is constructed by setting port = 0, the random port chosen by asio can be retrieved using TCPIPAcceptor::GetLocalEndpoint().port() 2018-01-22 20:47:31 -05:00
4ee364640d Update rpm spec and systemd unit 2018-01-22 13:55:12 -05:00
56dd0db001 Merge pull request #1066 from PurpleI2P/revert-1065-openssl
Revert " Fixes for #1024 , #1018 #1064 "
2018-01-22 13:00:15 -05:00
626ed720a6 Revert " Fixes for #1024 , #1018 #1064 " 2018-01-22 12:59:34 -05:00
b8fd9ba83f Merge pull request #1065 from unlnown542a/openssl
Fixes for #1024 , #1018 #1064
2018-01-22 07:08:34 -05:00
316a4457af Merge github.com:unlnown542a/i2pd into openssl 2018-01-22 01:39:51 +03:00
347a2c2150 fixing conflicts 2018-01-22 01:30:21 +03:00
42d3770b14 fixed layout 2018-01-21 11:28:16 -05:00
39ca07bcc6 Merge pull request #1058 from majestrate/streaming_race_fix_2018_01_15
Streaming race fix 2018 01 15
2018-01-21 11:15:44 -05:00
df304fb38b Merge pull request #1063 from PurpleI2P/openssl
recent changes
2018-01-21 10:29:31 -05:00
914566ece0 removed unused Java router certificates 2018-01-21 10:27:41 -05:00
f537e7b2c6 removed unused cert 2018-01-21 08:09:01 -05:00
06020b8f54 re-enable packet pool 2018-01-20 13:06:08 -05:00
b486d1cd27 rollback
non buildable under x64
2018-01-20 12:07:57 -05:00
b3b38015c2 check max buffer size in Stream::Send 2018-01-20 07:31:58 -05:00
4c6988e3bc code cleanup 2018-01-18 19:35:37 +03:00
0bd4db4cc7 less lines 2018-01-18 16:41:02 +03:00
bc72800fef moved hard code into java side and successfully passed back to native 2018-01-17 20:58:56 +03:00
951f8972c7 replace non-working CheckLibcxxAtomic 2018-01-17 16:12:46 +08:00
38b694a055 Merge pull request #1060 from inetic/openssl
Inherit _publicly_ from shared_from_this in I2PService
2018-01-15 11:58:27 -05:00
44a9c3ca0c Merge pull request #1059 from K1773R/fix-headers-rn
removed redundant \r\n in HTTP header builder
2018-01-15 10:36:42 -05:00
6bf823fb15 removed \r\n in header builder which was redundant and caused the further headers to be ignored 2018-01-15 16:30:01 +01:00
43a751ee0b Merge remote-tracking branch 'purple/openssl' into streaming_race_fix_2018_01_15 2018-01-15 08:25:58 -05:00
207212557e fix sam race conditions 2018-01-15 08:19:57 -05:00
fd1aeeac92 Merge pull request #1045 from yangfl/upstream
code cleanup
2018-01-13 18:11:19 +03:00
50ba52756f fix mixing tabs and spaces 2018-01-13 22:51:02 +08:00
e630b8f8a8 Inherit _publicly_ from shared_from_this in I2PService 2018-01-12 11:04:26 +01:00
cf5081d300 fixed creating certificates.zip when target zip did not include the directory certificates, so they were bein unpacked into datadir. Added entryCompression ZipEntryCompression.STORED since final APK is being compressed as well. Put all custom tasks under android plugin definitions 2018-01-07 19:30:32 +03:00
8864cbf80a return to strdup() when filling argv[] for i2p::android::start(argc,argv).c_str() 2018-01-07 00:40:17 +03:00
81d7a832c0 netDB and certificates in internal storage 2018-01-07 00:08:07 +03:00
d41fabbc9f netDB and certificates in internal storage 2018-01-06 23:59:22 +03:00
46f62e1af9 remove trailing whitespaces 2018-01-06 22:24:03 +08:00
b91efaa973 Merge pull request #1044 from yangfl/upstream
update Makefile and CMakeLists
2018-01-06 09:22:11 -05:00
e3238ff75c CMakeLists: autodetect libatomic 2018-01-06 22:06:44 +08:00
9cc4e8d03a Makefile: get target platform from compiler 2018-01-06 22:06:28 +08:00
68b1afa2df Merge remote-tracking branch 'purple/openssl' into i2cp-session-reconfig 2018-01-04 08:33:06 -05:00
34c98e03c1 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2018-01-03 12:53:05 -05:00
41e40bbc0d fixed typo 2018-01-03 12:52:29 -05:00
80149342f2 proper bounds check 2018-01-03 10:02:11 -05:00
1967dee50c don't recreate tunnels of different size 2018-01-02 12:59:16 -05:00
ab80def94b use reference instead of copy 2018-01-02 12:06:10 -05:00
254bf313a2 fix previous commit 2018-01-02 11:48:38 -05:00
938d5d901a implement i2cp session reconfigure 2018-01-02 11:34:58 -05:00
7b00d828b2 fix lambda capture, don't capture copy 2018-01-01 09:35:32 -05:00
ca49944c85 Merge pull request #1041 from majestrate/fix-streaming-race
fix race condition
2018-01-01 09:26:21 -05:00
d5e9fc7677 fix race condition 2018-01-01 08:28:42 -05:00
6db7c5733d use outbound.nickname as tunnel name if inbound.nickname is not set 2017-12-20 11:38:35 -05:00
418f86ecbd Merge pull request #1039 from majestrate/fix-arm-compile-latomic
Fix arm compile latomic
2017-12-20 10:48:45 -05:00
c68c5af856 fix lib name 2017-12-20 08:56:39 -05:00
950dffbe06 update gitignore 2017-12-20 08:54:41 -05:00
5d557003b6 include cmake stuff 2017-12-20 08:54:02 -05:00
3b8c3c1346 try fixing issue #897 2017-12-20 08:49:47 -05:00
1853263f6c Merge pull request #1038 from PurpleI2P/master
Master
2017-12-18 08:59:19 -05:00
b0f6d81f57 Merge pull request #1037 from PurpleI2P/openssl
recent changes
2017-12-15 22:00:09 -05:00
9ba0329432 Merge pull request #1036 from KenanSulayman/patch-1
Fix typo (confrimed -> confirmed)
2017-12-15 21:56:09 -05:00
614101c4b8 Fix typo (confrimed -> confirmed) 2017-12-16 02:36:01 +01:00
50e4fb138a close #1032 (#1034) 2017-12-13 15:17:45 +03:00
6dba0c6e0e Merge pull request #1031 from AMDmi3/boost-asio-fix
Don't use deprecated boost::asio::ssl::context ctor
2017-12-11 15:30:39 -05:00
0f2d2156e6 Don't use deprecated boost::asio::ssl::context ctor
This was removed in boost 1.66, in prior versions the service
argument was not used
2017-12-11 22:34:48 +03:00
13b17c5a93 Merge pull request #1030 from AMDmi3/freebsd_kernel
Reorder preprocessor conditions in libi2pd/I2PEndian.h
2017-12-11 12:37:08 -05:00
511499d950 Reorder preprocessor conditions in libi2pd/I2PEndian.h
The problem is that __FreeBSD_kernel__ may be defined on FreeBSD as
well, while it always needs <sys/endian.h>
2017-12-11 19:59:06 +03:00
6632b71273 gradle relese build 2017-12-10 09:01:13 -05:00
60ef70cee4 gradle build added 2017-12-10 08:46:13 -05:00
b3ba0a7241 Merge pull request #1027 from majestrate/transient-by-default
Use transient destinations
2017-12-09 07:49:43 -05:00
fc73dabc0b Use transient destinations by default instead of shared local destination 2017-12-09 07:42:32 -05:00
1121d45eb6 Merge pull request #1025 from yangfl/pr
fix typo
2017-12-07 09:09:42 -05:00
18b6353803 fix typo 2017-12-07 21:26:28 +08:00
c0c0642bd1 temporary disable osx build due to of big waiting time of VM 2017-12-06 02:16:01 +03:00
3cf26a84dc Merge pull request #1022 from AMDmi3/patch-1
Don't meddle with stdlib
2017-12-05 10:14:31 -05:00
44d6d4405e Don't meddle with stdlib
Forgotten part of #1014: -stdlib should not be changed. It breaks build on e.g. FreeBSD where libc++ is used.
2017-12-05 13:45:22 +03:00
cafa027f0b Merge pull request #1021 from PurpleI2P/openssl
2.17.0
2017-12-04 13:42:04 -05:00
1c970b0714 2.17.0 2017-12-04 21:40:32 +03:00
6636e432d7 2.17.0 2017-12-04 13:05:04 -05:00
158889b85c check for invalid params 2017-12-01 16:25:32 -05:00
92bebb7ecc webconsole update (#1017)
* webconsole exploratory tunnel mark
* loglevel on commands page
* fix line break on destination page
2017-12-01 22:18:04 +03:00
fff34e77f5 pass signature and crypto type to newkeys 2017-12-01 13:43:00 -05:00
df18692af9 check I2NP messsage buffer size 2017-12-01 12:57:05 -05:00
276a78cb2e Merge pull request #1019 from PurpleI2P/openssl
recent changes
2017-12-01 12:55:45 -05:00
a1e820182c CRYPTO_TYPE for DEST GENERATE 2017-11-28 13:24:07 -05:00
272090fc8f don't accept streams from RSA detinations 2017-11-28 11:33:51 -05:00
ab6bc52a0f don't create destination with RSA signature 2017-11-28 10:59:11 -05:00
c69c369502 close div, update qt gitignore 2017-11-26 12:30:18 +03:00
a5b1b24fee implement i2p.streaming.connectDelay option 2017-11-24 15:37:17 -05:00
40cfbc5d61 Merge pull request #1016 from majestrate/fix-streaming-overflow
fix overflow
2017-11-23 13:54:34 -05:00
ffad1ecd6d reduce buffer size 2017-11-23 13:46:04 -05:00
e1b5803902 fix overflow 2017-11-23 12:27:28 -05:00
492d71a924 transient keys 2017-11-22 14:49:45 -05:00
6d01a3a7d1 fix (quote) 2017-11-21 21:33:24 +03:00
b71e20dfa3 changed back 2017-11-21 13:25:40 -05:00
474158dd18 rollback. build error 2017-11-21 11:04:32 -05:00
914db816c2 Merge pull request #1014 from AMDmi3/patch-1
Fix flags
2017-11-21 07:17:49 -05:00
4485d6fdf4 Fix flags
-stdlib should not be changed. It breaks build on e.g. FreeBSD where libc++ is used.
2017-11-21 14:35:39 +03:00
2c394661a6 Merge pull request #1011 from hypnosis-i2p/openssl
updated qt to build and to reflect some core changes like log dest
2017-11-19 07:14:50 -05:00
611c1a7502 updated qt to build and to reflect some core changes like log dest 2017-11-19 19:26:36 +08:00
4e8858a764 Merge pull request #1009 from majestrate/reseed-proxy
reseed proxy
2017-11-18 16:15:37 -05:00
fb46de5ca6 Delete old R4SAS's reseed cert 2017-11-18 23:56:52 +03:00
65db96e663 reseed proxy 2017-11-18 09:50:30 -05:00
5109d40d8e don't publish unknown crypto type to Java floodfill again 2017-11-17 14:28:48 -05:00
1ba1fa37f9 update travis-ci stuff (#1006)
* enable osx in travis config
* fix brew commands, change comiler
* disable clang build with make on linux
* update README
* tabulation fix in Crypto.cpp
2017-11-17 20:43:00 +03:00
9c97ee6407 check for existing addressbook record 2017-11-16 01:13:42 +03:00
7477d2c219 fix forgotten log colors 2017-11-15 21:51:03 +03:00
a6fb3b602e add loglevel none (closing #998) 2017-11-15 21:46:20 +03:00
d9b9457b56 update webconsole 2017-11-15 00:49:32 +03:00
cfb6ddbfc6 CRYPTO_TYPE for SAM destinations 2017-11-14 15:05:07 -05:00
7de21c1f93 show proxy tunnel name 2017-11-14 13:20:54 -05:00
100f3380c4 fix upnp definitions and make cmake silent (#999) 2017-11-14 08:38:45 +03:00
20e484bb8b travis-ci cmake fix 2017-11-14 06:34:57 +03:00
94fc1a1cee debian wheezy upnp fix 2017-11-14 03:41:01 +03:00
ae28df5276 2.16.0 2017-11-13 22:20:41 +03:00
3a4f1382f3 2.16.0 2017-11-13 14:09:55 -05:00
01a7e08585 0.2.16 2017-11-13 14:01:04 -05:00
847fd15af2 0.2.16 2017-11-13 13:59:41 -05:00
a21fb17d73 renamed ECIES-P256 2017-11-13 11:50:17 -05:00
0c34bd440b reject routers with RSA signatures 2017-11-13 11:25:42 -05:00
1008510750 Merge pull request #997 from PurpleI2P/openssl
recent changes
2017-11-13 11:23:32 -05:00
34d6eb52d0 Merge pull request #996 from majestrate/stream-limits
Stream limits
2017-11-13 07:46:06 -05:00
5820425b6c Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into stream-limits 2017-11-13 07:26:32 -05:00
a4b39a3648 disable connection limiting by default 2017-11-13 07:26:27 -05:00
3dc5542a28 update mingw makefile 2017-11-13 04:46:19 +03:00
dde4643e77 fix shutdown from webconsole in windows 2017-11-13 03:30:52 +03:00
7a857e08c1 update windows build batch 2017-11-13 03:30:52 +03:00
80a3bd6a3b correct new key pair 2017-11-12 17:31:00 -05:00
7fb8ee60b4 correct random padding for ICIES public key 2017-11-11 22:10:54 -05:00
dca4cf2edb fixed #993. bind inbound tunnel to inhost 2017-11-10 11:27:20 -05:00
2bc33f22df fixed #994. check if keys are set 2017-11-10 09:49:50 -05:00
d14c6e2829 cryptotype for server tunnels 2017-11-09 16:18:59 -05:00
a4ce224cd1 pass correct crypto type to identity 2017-11-09 15:49:27 -05:00
ab1cd3f5cf ECIES for GOST R 34.10 2017-11-09 15:01:07 -05:00
1e75de9bb8 514 bytes ECIES block 2017-11-08 21:06:58 -05:00
19a03c42a5 use generic Decrypt instead ElGamalDecrypt 2017-11-08 20:45:53 -05:00
9e5d1bf0fc cryptotype tunnel configuration parameter added 2017-11-08 15:59:41 -05:00
c5f784719d implement Decrypt for all local destination 2017-11-08 13:49:48 -05:00
60aa459dfc 0.9.32 2017-11-08 11:01:00 -05:00
53d71d29ff call RoutingDestination::Encrypt instead ElGamalEncrypt 2017-11-07 20:30:05 -05:00
81658d2ff9 generic encryption for RoutingDestination 2017-11-07 15:05:22 -05:00
9fa67b0e0a crypto key encryptor and decryptor 2017-11-06 15:54:18 -05:00
88ba494701 fixed build error 2017-11-06 15:12:51 -05:00
efacfced45 CryptoKey added 2017-11-06 13:40:58 -05:00
b3c836f298 Merge pull request #987 from majestrate/gcc-7-ubuntu-artsy-fix
fix gcc 7 on ubuntu
2017-11-05 06:22:49 -05:00
3330bf4f2f fix gcc 7 on ubuntu 2017-11-04 07:53:24 -04:00
e634c89995 generate non-ElGamal encryption keys pair 2017-11-02 16:13:10 -04:00
5aa53eee43 GetIdentity for RoutingDestination 2017-11-02 14:50:57 -04:00
42483b6f32 Merge pull request #986 from PurpleI2P/openssl
recent changes
2017-11-02 14:45:47 -04:00
00bbb81375 ECICS gerenarate keys 2017-11-01 14:06:55 -04:00
5271cdacf2 ECICSDecrypt 2017-11-01 10:59:36 -04:00
6d01726961 use AES-CBC for ECICS 2017-11-01 10:20:11 -04:00
12feac1f50 fixed build error for wheezy 2017-10-31 21:25:52 -04:00
39c1c3567b ECICSEncrypt added 2017-10-30 16:16:21 -04:00
63ae6850d3 Fix #979. Router without host but with introducers is considered as SSU v4 2017-10-30 12:58:20 -04:00
bec24e052c Merge pull request #983 from majestrate/i2np-transport-limits
fix limits when not specififed
2017-10-30 09:54:28 -04:00
91eb2b2c4a fix limits when not specififed 2017-10-30 09:53:41 -04:00
0bae2a3397 Merge pull request #982 from majestrate/i2np-transport-limits
I2np transport limits
2017-10-30 09:23:47 -04:00
42ec6db746 Merge remote-tracking branch 'purple/openssl' into i2np-transport-limits 2017-10-30 08:39:58 -04:00
7a9dc0eec0 use terminate 2017-10-30 08:37:54 -04:00
6441c9d5d8 initial ntcp soft/hard limits 2017-10-30 08:27:55 -04:00
2930d39ce7 Merge pull request #978 from majestrate/http-i2p-outproxy
support i2p outproxy in httpproxy
2017-10-29 10:30:03 -04:00
1500e805dd add is_i2p 2017-10-29 09:56:51 -04:00
b14d1801f0 support i2p outproxy 2017-10-27 08:43:54 -04:00
bc11181d5e tables for GOST R 34.11 2017-10-23 14:25:26 -04:00
9739e677aa Merge pull request #975 from chris-barry/974-apparmor-debian
Add apparmor profile to debian. #974
2017-10-16 01:19:35 +03:00
056f076ae8 Add apparmor profile to debian. #974 2017-10-15 13:40:59 -04:00
7dfb6f4a13 update makefiles 2017-10-13 21:46:10 +03:00
b347b719f3 fixed race condition 2017-10-13 14:38:32 -04:00
7b537a4e94 Merge pull request #972 from radfish/PR--cmake-stdlib-args-for-clang
cmake: add stdlib args for clang build on Linux
2017-10-08 21:46:32 -04:00
291f28fcce cmake: add stdlib args for clang build on Linux
Otherwise linking fails with undefined symbol ... basic_string ... and
libstdc++: DSO not on included in link command.
2017-10-08 19:11:12 -04:00
fa9c39732d change max bandwidth limit 2017-10-05 10:37:28 -04:00
bfdf006bd2 add SAM session in webconsole 2017-10-05 05:29:07 +03:00
057d6ca05b windows warnings, tabulation workaround 2017-10-04 20:16:34 +03:00
7d7f5ff4e2 set default nickname after initialization 2017-10-04 12:40:43 -04:00
6e32f4bc85 set nickname for destination 2017-10-04 12:27:08 -04:00
8460a8f4ef update local destination if changed 2017-09-29 15:34:26 -04:00
8c09a7429c Merge pull request #967 from brain5lug/openssl
missed self assigment check for EDDSAPoint
2017-09-29 06:40:19 -04:00
346bf14b7b added missed invariant for MemoryPool 2017-09-29 10:17:23 +03:00
8e3c9410dc missed self assigment check for EDDSAPoint 2017-09-29 00:48:14 +03:00
cb0552e20d Merge pull request #966 from brain5lug/openssl
fixed perfect forwarding for the memory pool
2017-09-28 17:38:58 -04:00
8c8127dda6 fixed perfect forwarding for the memory pool 2017-09-29 00:03:07 +03:00
1d8a481d59 fix tabulation 2017-09-27 23:41:34 +03:00
dd4f066e95 add graceful shutdown in webconsole for windows
add stop graceful shutdown menu item
add reload menu item
2017-09-27 23:30:30 +03:00
5e0d4163a2 Merge pull request #965 from majestrate/fix-leak-2017-09-27
try fixing leak
2017-09-27 10:34:34 -04:00
7fb2d13a8b use BN_CTX_start and BN_CTX_end instead of removing BN_CTX_start 2017-09-27 09:49:43 -04:00
acde10b46e Merge remote-tracking branch 'purple/openssl' into fix-leak-2017-09-27 2017-09-27 09:48:19 -04:00
c0bcab8bc5 try fixing leak 2017-09-27 09:05:52 -04:00
fd6d0922ab Merge pull request #964 from radfish/PR--cmake-openssl-warn
cmake: issue a non-fatal warning for openssl >=1.1
2017-09-26 21:16:20 -04:00
8179e7dbf8 cmake: issue a non-fatal warning for openssl >=1.1 2017-09-26 20:46:06 -04:00
eabeeaccfe Merge pull request #963 from radfish/PR--cmake-check-openssl-ver
cmake: check openssl version
2017-09-26 12:34:31 -04:00
94bba69dee cmake: check openssl version
See #835 for memory leak issues with OpenSSL >= 1.1
2017-09-26 10:56:02 -04:00
4d23de96d5 Merge pull request #961 from l-n-s/small_patches
fixed typo + added optional full date in logs `logclftime=true`
2017-09-19 22:02:30 -04:00
681810ea38 Use setter method for m_TimeFormat, set time format in Daemon.cpp instead of Log.cpp 2017-09-19 19:46:28 -04:00
d500fe66fd Add option logclftime=true for writing full date and time to logs 2017-09-18 18:49:03 -04:00
05c2adeefd fix typo 2017-09-18 15:24:53 -04:00
d46e0fb474 Merge pull request #958 from majestrate/macos-static
fix up homebrew makefile to allow static linking
2017-09-11 10:00:39 -04:00
330fab2efa update macos i2pd qt build to statically compile in libraries for portability 2017-09-11 08:57:43 -04:00
d59d36f93c fix up homebrew makefile 2017-09-11 07:48:10 -04:00
fd6827fdca add space 2017-09-09 20:13:45 +03:00
dca94f17d7 Merge pull request #952 from hypnosis-i2p/openssl
ui beautifying + fixed tunnels invalid ui data handling
2017-09-08 15:07:25 -04:00
d4e16881ff fixed tunnels invalid ui data handling 3 2017-09-09 01:13:42 +08:00
cd3f274763 fixed tunnels invalid ui data handling 2 2017-09-09 01:09:31 +08:00
1947be4957 fixed tunnels invalid ui data handling 2017-09-08 23:25:25 +08:00
21de4709ea ui beautifying more 2017-09-08 23:16:54 +08:00
ec76381a0b ui beautifying 2017-09-08 23:07:37 +08:00
66661417d7 Merge pull request #950 from hypnosis-i2p/openssl
ui critical fixes
2017-09-08 08:54:38 -04:00
81b79e6e53 ui critical fixes 2017-09-08 19:43:27 +08:00
5ae93d852e Merge pull request #948 from hypnosis-i2p/openssl
fixes #945 and #935
2017-09-08 07:00:30 -04:00
96cb663fa8 some work + fixed red errors on malformed input 2017-09-08 18:58:04 +08:00
1efc2a9b5d little ui fixes 2017-09-08 18:02:12 +08:00
9441c1cffe fixed #935 2017-09-08 17:57:15 +08:00
ef30d2d3b6 fixes #945 2017-09-08 15:59:19 +08:00
1673966e36 Merge pull request #942 from Markovskij/openssl
Make tunnels.conf more readable with QT GUI
2017-09-07 09:37:07 -04:00
1d8f913364 Merge branch 'openssl' of github.com:Markovskij/i2pd into openssl 2017-09-04 07:25:06 +03:00
a549ebc25f Add constants 2017-09-04 07:23:59 +03:00
ce853786b5 Merge pull request #2 from PurpleI2P/openssl
Update
2017-09-04 06:52:57 +03:00
7e0ab6d0b1 Merge pull request #943 from majestrate/connect-proxy
HTTP CONNECT in http proxy
2017-09-03 15:28:28 -04:00
d6f907a05b make it work 2017-09-03 11:13:43 -04:00
b2d1962b81 add http connect to http proxy (untested) 2017-09-03 09:46:55 -04:00
b0a6c9fa53 Make tunnels.conf more readable 2017-09-03 15:55:51 +03:00
7a0337f3db Merge pull request #1 from PurpleI2P/openssl
Update
2017-09-03 14:10:25 +03:00
c1dbd3ffd0 Merge pull request #940 from majestrate/defer-connect
Defer connect
2017-09-01 11:40:26 -04:00
1ea6d2016d add initial connection timeout for i2ptunnel 2017-08-31 12:08:22 -04:00
416589cc93 Revert "add deferred ready checking for destination"
This reverts commit 3f409d0e28.
2017-08-31 10:38:26 -04:00
41ce9d47e5 Revert "re trigger timer"
This reverts commit f87a51034e.
2017-08-31 10:37:58 -04:00
d7e4deab4e Revert "tabify"
This reverts commit 897cfad399.
2017-08-31 10:37:57 -04:00
27782ceddd Revert "clarify"
This reverts commit 7af3b751d4.
2017-08-31 10:37:56 -04:00
a6f62a99b9 Revert "use shared from this"
This reverts commit 4e4def4fb9.
2017-08-31 10:37:53 -04:00
4e4def4fb9 use shared from this 2017-08-31 10:24:07 -04:00
7af3b751d4 clarify 2017-08-31 10:14:06 -04:00
897cfad399 tabify 2017-08-31 10:12:59 -04:00
f87a51034e re trigger timer 2017-08-31 10:07:09 -04:00
3f409d0e28 add deferred ready checking for destination 2017-08-31 09:59:04 -04:00
543566840c Merge pull request #936 from hypnosis-i2p/openssl
ReloadConfig + --log fix
2017-08-27 13:43:09 -04:00
1c3174a277 fixed #841 2017-08-27 21:16:52 +08:00
fc2ae6f887 fixed ReloadConfig(); fixed --log 2017-08-27 20:52:55 +08:00
63e175d389 fixed #913 2017-08-27 20:39:10 +08:00
9bfbba6fea Merge pull request #934 from hypnosis-i2p/openssl
various small qt gui fixes
2017-08-27 07:28:15 -04:00
69d245c4bd Merge pull request #933 from myfingerhurt/openssl
Fix deformed json result with an extra comma
2017-08-27 06:44:02 -04:00
7738eae4b0 general settings widget ui revolution for convenience + widget locks: fixed #927 2017-08-27 16:10:09 +08:00
3d5fb07ca8 various small qt gui fixes 2017-08-27 12:41:10 +08:00
0f0fb266c7 Fix deformed json result with an extra comma
{"id":1,"result":{"i2p.router.net.bw.in":48,"i2p.router.net.bw.out":48,},"jsonrpc":"2.0"}
You can see there is an extra comma behind the number 48.
2017-08-27 12:57:06 +09:00
5c3d6298b0 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2017-08-25 14:46:24 -04:00
028f0bdb8d Fixed #931. don't insert null pointer into DHkeys list 2017-08-25 14:45:58 -04:00
44bcdc6866 Merge pull request #932 from Markovskij/openssl
Web interface fix
2017-08-24 20:46:21 -04:00
b9f6f92bad Web interface fix 2017-08-25 02:37:01 +03:00
1607535416 strip out Accept and From headers 2017-08-24 15:13:15 -04:00
f6ced9279b new reseed added 2017-08-20 17:34:53 -04:00
95af716a96 Merge pull request #925 from hypnosis-i2p/openssl
Qt GUI now shows buttons under Status and their corresponding info panes
2017-08-20 06:56:39 -04:00
07fe51fa25 some qt gui changes 2017-08-20 13:40:14 +08:00
822995cbaf ignored android/libs/ 2017-08-20 13:40:14 +08:00
db0e02c05d qt ui - status commands are now pushbuttons with no handlers 2017-08-20 13:40:14 +08:00
856dda68db qt ui - now all buttons have handlers 2017-08-20 13:40:14 +08:00
163cbcb89d qt ui - status main page now works 2017-08-20 13:40:14 +08:00
a79f614e12 qt ui - now pixel perfect buttons 2017-08-20 13:40:14 +08:00
7d3a818565 qt ui - laid out better 2017-08-20 13:40:14 +08:00
978bb47b92 qt ui - settings buttons renamed to *Settings 2017-08-20 13:40:14 +08:00
b791a6a348 qt ui - status buttons done 2017-08-20 13:40:14 +08:00
c21c1f5225 Merge pull request #920 from PurpleI2P/openssl
2.15.0
2017-08-17 14:20:41 -04:00
d6253b1dee remove dupe lines 2017-08-17 21:17:25 +03:00
390bb07cca 2.15.0 2017-08-17 14:09:16 -04:00
309822d933 teminate hadlers upon cleanup 2017-08-10 20:29:35 -04:00
8cb612c10c Merge pull request #919 from l-n-s/peertest_fix2
Don't do peertest if nat=false. FIX #915
2017-08-09 11:09:32 -04:00
7e244455c4 Don't do peertest if nat=false. FIX #915 2017-08-09 10:52:52 -04:00
907fe3d8d9 Merge pull request #918 from majestrate/readme_fixups
explicitly link to build instructions in readme
2017-08-09 08:51:02 -04:00
6420e33fb8 link to build instructions in readme 2017-08-09 08:50:00 -04:00
0b560fdd27 0.9.31 2017-08-08 09:29:30 -04:00
04297eda80 Merge pull request #916 from majestrate/vanity
add stuff for address generator tool
2017-08-07 15:05:19 -04:00
c13fd2261e add stuff for address generator tool 2017-08-07 14:00:50 -04:00
034bff5b2f added gostcoin family certificate 2017-08-02 21:19:12 -04:00
987ad214ff avoid bind exeptions during reload 2017-08-02 21:00:04 -04:00
d11ac64b95 stop I2P tunnel upon deletion 2017-07-28 15:40:07 -04:00
4c8c3b6947 add and remove tunnels without stopping others 2017-07-28 15:12:15 -04:00
d47d8d22a3 removed all Accept-* headers but Accept-Encoding 2017-07-28 11:16:42 -04:00
0ec9defc6e Merge pull request #911 from hypnosis-i2p/openssl
qt ui fixes
2017-07-28 06:27:12 -04:00
4776f11b6a http proxy and socks - initialized comboboxes correctly 2017-07-28 12:57:19 +08:00
3118d7bede restart button now has a handler 2017-07-28 11:59:45 +08:00
a83be187f3 ui fixes 2017-07-28 10:43:20 +08:00
deb5e435e5 fixed i2pd qt gui a bit 2017-07-28 09:21:41 +08:00
9f824f3aa9 remove Accept-Language 2017-07-27 18:45:53 -04:00
032e68da05 Merge pull request #908 from r4sas/openssl
add socks.outproxy.enabled and workout with Config.cpp tabulation
2017-07-19 07:12:19 -04:00
486661d6c6 implement != 2017-07-18 18:27:07 -04:00
aa86ab97f0 update i2pd.conf example, update socks proxy tunnel 2017-07-19 00:36:56 +03:00
a17f07495a add socks.outproxy.enable option 2017-07-19 00:21:02 +03:00
16d3440a4c tabulation workout on Config.cpp 2017-07-18 23:55:53 +03:00
d7b412c1eb overwrite existing address 2017-07-18 15:58:32 -04:00
e5751334d6 update doxygen config 2017-07-15 10:02:15 +03:00
1fb1d7e4e9 don't create SSU session if endpoint is not specified. Wait from RelayResponse 2017-07-13 14:13:58 -04:00
adc20e78da Merge pull request #906 from l-n-s/fix_docker
Docker: fix permissions issue
2017-07-11 21:07:25 +00:00
d499e250e0 Docker: fix permissions issue 2017-07-11 17:00:50 -04:00
68166c22b3 Merge pull request #904 from l-n-s/fix_netdb_thread
NetDb: If NetDb is empty, throw exception instead of killing NetDb thread
2017-07-11 06:28:33 -04:00
06b2b26e39 NetDb: If NetDb is empty, throw exception instead of killing NetDb thread 2017-07-11 02:55:38 -04:00
641ca3d49d install windows service with daemon argument 2017-07-10 01:14:55 +03:00
6d259e00a3 add additional break row 2017-07-08 16:59:10 +03:00
2bc5b97662 separate transports output for IPv4 and IPv6 2017-07-08 16:54:12 +03:00
676c61aa99 fix typo 2017-07-08 16:53:33 +03:00
eade8003ef Merge pull request #902 from l-n-s/fix_options
Fix options: make useless boolean flags configurable in command line
2017-07-07 22:13:01 -04:00
817bbefac6 Fix options: make useless boolean flags configurable in command line 2017-07-07 18:23:27 -04:00
cded6206dc cleanup unused destinations 2017-07-07 15:12:34 -04:00
c287fb58bd reference counter for destinations 2017-07-06 16:12:06 -04:00
1b97f9b6c9 Merge pull request #894 from kayrus/kayrus/run_systemd
Create run dir for i2pd process in systemd unit file
2017-06-23 14:52:14 +03:00
14ca3fc2f3 Merge pull request #896 from PurpleI2P/openssl
recent changes
2017-06-23 07:41:31 -04:00
4bc1143418 update makefile to use gcc 7 on archlinux 2017-06-23 13:02:31 +03:00
4267063dba Create run dir for i2pd process in systemd unit file 2017-06-23 10:25:13 +02:00
8f8b4536b6 add future R4SAS reseed cert replacement
warn: will use after 2.16.0 release
2017-06-22 15:45:23 +03:00
8121ab5163 added including of configs and certificates in mingw batch build 2017-06-22 15:37:02 +03:00
76fab1fea8 reseeds update 2017-06-18 16:41:09 -04:00
143b235a22 Merge pull request #892 from hypnosis-i2p/openssl
Qt GUI + more of SAM debug logging
2017-06-17 08:38:18 -04:00
3a89f2c32f now starting the i2pd daemon - uncommented emit start line 2017-06-17 20:31:00 +08:00
7bab92042a removed some obsolete files 2017-06-17 20:23:33 +08:00
7379b4ddd2 merged with upstream 2017-06-17 20:23:33 +08:00
298181999d qtui first draft completed 2017-06-17 20:23:33 +08:00
61e1e7fe8f added one missing sigtype to Identity.h. Some work on qt gui. 2017-06-17 20:23:33 +08:00
b3050af1a7 some work on desktop qt gui 2017-06-17 20:23:33 +08:00
275da075e0 various qt work 2017-06-17 20:23:33 +08:00
9925e2732a rework + now restarts after app kill event 2017-06-17 20:23:33 +08:00
59b3daabc5 qt gui preliminary results 2017-06-17 20:23:33 +08:00
f2b0f64138 tmp 2017-06-17 20:23:33 +08:00
5df77eb474 qt forms now work even better! 2017-06-17 20:23:33 +08:00
f202fb9af6 qt forms now work! 2017-06-17 20:23:33 +08:00
5b769869d0 fixed qt .pro file 2017-06-17 20:23:33 +08:00
8e266058ae more of SAM debug logging 2017-06-17 20:23:33 +08:00
7c21712e80 Merge pull request #891 from r4sas/win_patch
remove msvc project and fix some warnings
2017-06-11 15:13:37 +03:00
193fc343fe reupload mistakenly deleted iss project 2017-06-11 09:38:07 +03:00
a1e9c3d270 remove NSIS template 2017-06-11 09:34:19 +03:00
629261c4be remove msvc and NSIS project files
fix some windows build warnings
2017-06-11 09:29:31 +03:00
f6d3a6239c Merge pull request #884 from l-n-s/dockerfile_updates
Add updated Dockerfile
2017-06-08 16:21:45 +02:00
83c5131b67 skip expired introducer 2017-06-07 10:53:50 -04:00
36afef3498 Merge pull request #889 from PurpleI2P/openssl
recent changes
2017-06-05 09:02:42 -04:00
52c0485b0c Merge pull request #887 from BOPOHA/patch-2
bogus date in contrib/rpm/i2pd.spec
2017-06-04 18:43:03 -04:00
8c23a091da bogus date in contrib/rpm/i2pd.spec
fixed bad date and  bogus date in %changelog
2017-06-05 00:41:14 +02:00
ca121f80ee Merge pull request #885 from ryzhovau/spaces
Cosmetic changes for "Host XXX.YY not inside I2P network" message
2017-06-04 19:57:55 +03:00
b48846506f Cosmetic changes for "Host XXX.YY not inside I2P network" message
Signed-off-by: Alexander Ryzhov <github@ryzhov-al.ru>
2017-06-04 19:39:15 +03:00
a1c72be2a9 Add updated Dockerfile 2017-06-04 02:47:27 -04:00
2098368417 Merge pull request #883 from BOPOHA/patch-1
base version updated to 2.14.0
2017-06-04 05:51:33 +00:00
4014d86a57 base version updated to 2.14.0 2017-06-04 00:23:22 +02:00
e84e8748bd fixed android build 2017-06-01 10:41:15 -04:00
bd8166e630 2.14.0 2017-06-01 10:05:20 -04:00
03d1519b39 2.14.0 2017-06-01 10:04:02 -04:00
36c4719570 Merge pull request #881 from majestrate/ntcp-socks
NTCP SOCKS/HTTP Proxy support
2017-05-29 10:36:46 -04:00
7c970771c5 fix 2017-05-29 10:09:24 -04:00
3f64c042bd Fixed #880. Print if AESNI or AVX enabled 2017-05-29 10:08:49 -04:00
e336cbfb2d add http proxy, change socks4a to socks5 2017-05-29 09:57:30 -04:00
24eec76428 more 2017-05-29 02:16:57 -04:00
71c9b15ff1 more 2017-05-29 02:12:16 -04:00
2940f0d67c capture by value not reference 2017-05-29 01:53:34 -04:00
cbb1d2d3b5 more whitespace bullshit 2017-05-29 01:44:06 -04:00
36dd11a899 more whitespace bullshit 2017-05-29 01:39:11 -04:00
be88969b79 more whitespace bullshit 2017-05-29 01:38:32 -04:00
d91ad54ed9 more whitespace bullshit 2017-05-29 01:37:19 -04:00
1330228080 fix whitespace bullshit 2017-05-29 01:35:11 -04:00
3ea1eca350 ntcp socks proxy (initial) 2017-05-29 01:28:16 -04:00
a4e6d8120b handle iexp 2017-05-24 12:49:36 -04:00
3219de235c Merge pull request #875 from majestrate/cmake-avx
add AVX option to cmake build system
2017-05-22 14:37:42 -04:00
4e5c2ff620 add AVX option to cmake build system 2017-05-22 11:12:08 -04:00
63e25f0ff9 Merge pull request #873 from majestrate/fix-addressbook
try fixing issue #871
2017-05-22 10:51:48 -04:00
840225b580 try fixing issue #871 2017-05-22 10:34:29 -04:00
bd221d60d6 Merge pull request #872 from majestrate/fix-websocket-cmake
fix cmake compile error with websockets
2017-05-21 08:38:07 -04:00
8a3bb50143 fix cmake compile error with websockets 2017-05-21 08:18:16 -04:00
e4cd1a465c ignore comments 2017-05-10 09:36:58 -04:00
2173a9f246 Merge pull request #869 from bit/patch-1
Build depends on zlib.h (zlib1g-dev)
2017-05-08 14:58:33 -04:00
bit
973a838e2a Build depends on zlib.h (zlib1g-dev) 2017-05-08 12:54:08 +02:00
d95ee55497 skip comment address line 2017-05-05 13:54:21 -04:00
124e2e759c fix #846. ability to limit transit bandwidth 2017-05-04 14:58:12 -04:00
ac918e3618 0.9.30 2017-05-04 09:40:00 -04:00
009a720c32 disabled dead reseed 2017-05-02 21:08:51 -04:00
0dbfa43dad moveable to SD card 2017-05-02 19:25:34 -04:00
e0b4d36a74 changed target sdk back to 25 2017-05-02 18:06:06 -04:00
a441474d75 show transit bandwidth 2017-05-02 14:20:00 -04:00
cfd3c3628e count and show transit traffic 2017-04-27 16:11:37 -04:00
474d52f805 minor performance improvements 2017-04-27 10:12:22 -04:00
7ee8bdf2f3 Merge branch 'master' of https://github.com/PurpleI2P/i2pd into openssl 2017-04-27 10:11:45 -04:00
8a9757111f enable SAM by default 2017-04-24 12:20:15 -04:00
65dda4a70b Merge pull request #865 from l-n-s/update_config
Sample config: enable SAM by default + update description for notransit
2017-04-24 15:10:57 +00:00
1ed39dbbed Sample config: enable SAM by default + update description for notransit 2017-04-24 11:07:54 -04:00
8162c2e4e4 GST added 2017-04-23 06:52:37 -04:00
a7d74f3f98 update debian stuff 2017-04-23 07:09:12 +03:00
ad83ae1e7a removed stdafx 2017-04-22 14:52:19 -04:00
066374906e Merge pull request #862 from r4sas/makefile
update Makefile, tunnels.conf, android platform
2017-04-22 05:35:53 +04:00
ec79a4a6f6 Merge pull request #861 from majestrate/fix-case-insensative-include
remove uneeded lines in qt build file
2017-04-21 21:34:02 -04:00
9fae215db4 update android platform to 14 2017-04-22 04:20:22 +03:00
92b40c9485 update tunnels.conf 2017-04-22 04:19:32 +03:00
19fc59739f update makefile-s 2017-04-22 04:17:01 +03:00
7e0ae4c601 remove uneeded lines in qt build file 2017-04-21 21:01:48 -04:00
81c2f4b30b Merge pull request #860 from majestrate/fix-case-insensative-include
NetDb.h -> NetDb.hpp
2017-04-21 20:46:56 -04:00
e238f7ed37 NetDb.h -> NetDb.hpp for case insensative file systems clashing with libc's netdb.h 2017-04-21 20:04:16 -04:00
2756f3332c changed android target sdk to 25 2017-04-21 12:05:58 -04:00
14b3eefbaf change minimal requirement to android 4.0 2017-04-21 11:54:08 -04:00
dc946582a4 generic path to sdk 2017-04-21 09:54:35 -04:00
dfa14a73a8 Merge pull request #858 from majestrate/restructure
Restructure
2017-04-21 08:52:59 -04:00
112aa845f4 use correct #include in Win32 2017-04-21 07:20:50 -04:00
150a309175 include daemon directory for Win32 mingw 2017-04-21 07:08:31 -04:00
55c14819a3 Merge pull request #859 from PurpleI2P/openssl
recent changes
2017-04-21 06:53:56 -04:00
598897caa6 fix mingw build 2017-04-21 06:48:57 -04:00
cf3f8a796a fix path 2017-04-21 06:36:49 -04:00
bffc294b13 fix path 2017-04-21 06:35:39 -04:00
4cc3b7f9fb restructure build to separate the 3 main components into 3 subdirectories
libi2pd for core libs

libi2pd_client for i2pd client libs

daemon for i2pd daemon libs
2017-04-21 06:33:45 -04:00
b3161dde93 Merge pull request #855 from v2e/patch-2
kbps --> KBps
2017-04-19 07:05:29 -04:00
v2e
5550eabac1 kbs -- KBs in i2pd.conf 2017-04-19 11:39:01 +03:00
v2e
b2b320174b kbps -- KBps in Config.cpp 2017-04-19 11:36:19 +03:00
dd79348b35 delete used tag before update 2017-04-14 22:08:43 -04:00
bd6ce7d4da reduced memory usage 2017-04-14 10:19:26 -04:00
7a67670e1a Fixed #846. httpproxy.addresshelper config parameter added 2017-04-11 14:36:28 -04:00
539bf482b9 Merge pull request #844 from majestrate/datagram-fixes
Datagram fixes
2017-04-09 09:16:37 -04:00
ed67ce7f33 tabifty 2017-04-09 08:53:47 -04:00
d91c7e5e79 fix datagram bugs 2017-04-09 08:52:42 -04:00
4f1dfe2ef7 fixed android build 2017-04-08 17:21:56 -04:00
36ea6c13df Merge pull request #843 from majestrate/obep-ibgw
Allow point to point client tunnels to use OB tunnels that share OBEP and IBGW of remote destination
2017-04-08 15:32:26 -04:00
3acb0aac98 tabify 2017-04-08 15:16:51 -04:00
fdf4b3878f tabify 2017-04-08 15:15:59 -04:00
2fe71782a7 tabify 2017-04-08 15:14:47 -04:00
89dfe2b763 delay request 2017-04-08 15:10:16 -04:00
9b62f238ed add option for client tunnels to build tunnels such that OBEP==IBGW 2017-04-08 15:10:06 -04:00
987688f196 GOST hash of a Little Endian stream 2017-04-07 11:17:40 -04:00
46cb95f16c Merge pull request #842 from PurpleI2P/openssl
2.13.0
2017-04-06 10:02:54 -04:00
4e1fcbb706 update appveyor tag to 2.13 2017-04-06 17:01:39 +03:00
e4c038762b 2.13.0 2017-04-06 09:48:47 -04:00
86dfa200a6 update changelog to 2.13 2017-04-06 16:32:00 +03:00
165cf980d2 fixed memory leak 2017-04-05 18:26:56 -04:00
13ccb16a4a fixed memory leak 2017-04-05 17:44:23 -04:00
f4b5426865 update debian/control 2017-04-04 18:47:50 +03:00
c2f62ba52a persist incoming tags 2017-04-03 15:05:10 -04:00
b2d2c56a09 Merge pull request #839 from PurpleI2P/openssl
recent changes
2017-04-03 11:47:31 -04:00
abf0f5ac87 fixed typo 2017-03-31 12:26:20 -04:00
fa1965deb4 assign signature types 8 and 9 to GOST R 34.10 2017-03-31 10:04:39 -04:00
1f76dc78d8 cleanup acceptor for AcceptOnce 2017-03-30 20:27:31 -04:00
4448884a3e handle SIGNATURE_TYPE for DEST GENERATE 2017-03-30 15:43:02 -04:00
e3fc23bae8 restore previous acceptor later 2017-03-30 13:40:29 -04:00
29ceed74a2 don't drop destination's acceptor if inactive acceptor gets closed 2017-03-30 11:59:39 -04:00
382308c3fd change acceptor back to previous before processing 2017-03-30 11:22:38 -04:00
3d1b6e29c6 Merge pull request #838 from majestrate/sam-crash-fix-2017-03-29
try fixing sam crashyness
2017-03-29 15:01:22 -04:00
3a9a5ec669 try fixing sam crashyness 2017-03-29 14:38:55 -04:00
8c37c491a9 send STREAM CONNECT follow on data 2017-03-29 13:59:48 -04:00
fdf11e6038 allow unknown options for api 2017-03-29 10:51:32 -04:00
8e558f0826 recover public key from GOST R 34.10 signature 2017-03-26 08:55:15 -04:00
69804c23f1 check if destination keys are correct 2017-03-25 16:53:20 -04:00
9aa9a62ed4 AESNI for x86 2017-03-25 08:16:56 -04:00
d9b79f47c8 GetGroup () for GOST curve 2017-03-23 19:26:39 -04:00
249bc42667 merge S,P,L for GOST R 34.11-2012 2017-03-22 10:26:11 -04:00
644c184f7c Merge branch 'openssl' into openssl 2017-03-22 17:49:44 +04:00
66cfae7b3b more memory allocation optimization 2017-03-21 20:51:13 -04:00
bd2c2acd5f use CryptoProA params for GOST R 34.10-2012 256 bits 2017-03-21 11:48:34 -04:00
13aab750dd GOST signature unit test added 2017-03-21 10:45:57 -04:00
7a51abc2f9 GOST unit tests added 2017-03-21 09:44:09 -04:00
44a3e08095 GOST unit tests added 2017-03-21 09:43:36 -04:00
2aa8cf7104 update gitignore 2017-03-21 15:24:27 +03:00
1b1cfe1b92 rewrote win build script and moved it to build folder 2017-03-21 15:03:31 +03:00
199c2cdb66 some improvement of GOST R 34.11 2017-03-20 14:25:38 -04:00
726828a487 use GOST 34.11-2012 with GOST 34.10 2017-03-20 11:57:39 -04:00
fcbf81a3d4 correct implementation of L for GOST R 34.11-2012 2017-03-20 11:33:45 -04:00
7637b51ba5 fix #833. Handle SIGPIPE 2017-03-20 09:52:43 -04:00
3afed3b316 Merge pull request #832 from PurpleI2P/openssl
recent changes
2017-03-19 11:02:36 -04:00
3d6e334007 Appveyor merge (#1) 2017-03-18 05:22:02 +04:00
6c848a57b6 recreated appveyor config 2017-03-18 02:40:39 +03:00
eb12d43800 update windows build scripts 2017-03-17 20:59:10 +03:00
465366e644 new ressed 2017-03-16 20:55:05 -04:00
289e9c809f correct padding for GOST 34.11 2017-03-16 16:30:32 -04:00
8b40354786 GOST R 34.11-2012 implementation 2017-03-16 13:31:25 -04:00
8de8de1b1e GOST 34.11-2012 functions 2017-03-15 20:46:27 -04:00
4b76c76712 correct x for tc26 paramSetA 256 2017-03-15 14:59:17 -04:00
6b9a270506 enable TC26 paramSet A 512 for GOST 34.10-2012 2017-03-15 12:41:02 -04:00
da2c49ab66 tc26 paramSetA 512 for GOST 34.1002012 2017-03-14 21:15:17 -04:00
af2a3f3a65 Gost.cpp added 2017-03-14 21:14:23 -04:00
6369a900da added TC26 param sets for GOST R 34.10-2012 2017-03-14 20:03:44 -04:00
e877247032 support of GOST 34.10-2012 512 bits 2017-03-14 16:41:06 -04:00
5bcc5ff873 initial support of GOST R 34.10-2012 2017-03-14 16:02:16 -04:00
a52064463e fixed race condition 2017-03-14 12:03:51 -04:00
6ed7f19673 moved GOST to separate file 2017-03-13 20:28:36 -04:00
9aba0ba5a8 Merge branch 'openssl' of https://github.com/PurpleI2P/i2pd into openssl 2017-03-12 14:48:47 -04:00
5803a84bd7 change establish timeout to 10 seconds 2017-03-12 14:48:11 -04:00
ce0bf0f4b4 re-fix year 2017-03-12 18:29:57 +03:00
65ed57aff4 fix year 2017-03-12 18:28:25 +03:00
1317b80fca terminate incoming connection by timeout 2017-03-11 21:32:35 -05:00
f0d6145fa6 terminate incoming connection by timeout 2017-03-11 21:17:19 -05:00
c0c157ecef use common context for ElGamal encrypt/decrypt 2017-03-11 16:48:54 -05:00
4bb607f180 Merge pull request #824 from BOPOHA/openssl
i2pd.spec: changed Release format, upgrade Version
2017-03-10 19:25:28 -05:00
2eec205e31 i2pd.spec: changed Release format, upgrade Version 2017-03-11 00:31:00 +01:00
bd8cdd345a A,B,B param sets for GOST R 34.10 2017-03-10 16:57:56 -05:00
7caf3ea7d0 eliminate dependancy from GOST engine for GOST R 34.10 2017-03-10 13:21:22 -05:00
ba89c60b6d correct param set for GOST R 34.10 verification 2017-03-10 11:55:30 -05:00
084e48d6dd ZEC added 2017-03-10 11:53:49 -05:00
1bed3f3936 ZEC added 2017-03-10 11:53:05 -05:00
cd860bfbf8 correct param set for GOST R 34.10 signing 2017-03-09 21:46:34 -05:00
439c2d445c GOST R 34.10 sign 2017-03-09 20:13:21 -05:00
7f71d5dbd8 generate GOST R 34.10 keys with param set 2017-03-09 18:46:28 -05:00
831c835106 GOST R 34.10 param sets 2017-03-08 19:35:51 -05:00
5dfb7cb938 GOST R 34.10 curve added 2017-03-07 16:36:17 -05:00
044d6a2207 eliminate some BIGNUM allocation overhead 2017-03-07 15:02:01 -05:00
955b46534d eliminate some BIGNUM allocation overhead 2017-03-07 14:51:05 -05:00
0e8d80e055 eliminate some BIGNUM allocation overhead 2017-03-07 14:24:19 -05:00
92fc736cfa recreate SSU session again if session key is invalid 2017-03-05 17:08:20 -05:00
60ed43c11b #818. Exploratory config 2017-02-28 15:58:53 -05:00
319f72ae2a 0.9.29 2017-02-28 15:19:49 -05:00
04dc34260f replaced stringstream by a list of buffers 2017-02-26 15:05:14 -05:00
a8196d1f33 Merge pull request #816 from PurpleI2P/openssl
recent changes
2017-02-26 09:29:14 -05:00
1ce6ad5ccc cleanup send buffer 2017-02-24 11:04:40 -05:00
145e36925f check certificate size 2017-02-23 22:08:25 -05:00
c07928144c GOST support for Android openssl 1.1 2017-02-21 15:43:03 -05:00
d8c30f6cbb fixed typo 2017-02-21 11:38:11 -05:00
e968c6a2a4 fixed typo 2017-02-21 11:36:53 -05:00
ffc3a31d09 fixed andorid build 2017-02-21 11:23:14 -05:00
d6e037dd28 fixed build error 2017-02-19 19:31:37 -05:00
83b9b3bf4a enable GOST R 34.10 signatures from netid!=2 2017-02-19 18:08:10 -05:00
1cb89ce20d set correct curve parameters for GOST R 34.10 2017-02-19 14:45:10 -05:00
d75b916153 correct GOST engine initialization 2017-02-18 18:45:21 -05:00
192b484a8c fixed typo 2017-02-18 07:00:14 -05:00
85e2137d0e disable incorrect check 2017-02-18 09:14:23 +03:00
c1042c8f20 GOST R 34.11 hash 2017-02-17 22:26:24 -05:00
c91b05bd4b set correct curve from GOST R 34.10 signer and verifier 2017-02-17 13:37:53 -05:00
f8a09df5c0 generate GOST R 34.10 keys pair 2017-02-16 21:45:12 -05:00
9363db816c GOST R 34.10 signer and verifier 2017-02-16 21:18:18 -05:00
22af4da4d4 initial support of GOST crypto 2017-02-16 16:27:24 -05:00
16fa10b056 fix incorrect traffic counting 2017-02-16 17:45:38 +03:00
f044851abb fix typo 2017-02-16 16:29:08 +03:00
217e99a0e2 updated InnoSetup script
deleted old unused icon
added doxygen "docs/generated" folder to gitignore
2017-02-16 16:16:19 +03:00
1bc4aea217 Merge pull request #808 from l-n-s/update_docs
Update docs
2017-02-16 11:52:32 +00:00
4997934bfe Fix paths for moved contrib files 2017-02-16 06:48:06 -05:00
4905dded87 Moved files from docs/ to contrib/ 2017-02-16 06:36:01 -05:00
ff6447ae2b Merge pull request #806 from l-n-s/update_docs
Update docs
2017-02-16 06:37:55 +00:00
7f51857fa5 Update README.md 2017-02-16 01:20:59 -05:00
78c3babc37 Move docs to new repo 2017-02-16 01:14:07 -05:00
83300044dd fix osx upnp support
fix tabulation in UPnP.cpp
2017-02-15 09:04:40 +03:00
55f891e2aa fixed build error for gcc 4.7 2017-02-14 14:20:37 -05:00
29cc1cf390 Merge pull request #805 from PurpleI2P/openssl
2.12.0
2017-02-14 12:38:32 -05:00
040585bf3d Merge pull request #791 from PurpleI2P/openssl
recent changes
2017-02-01 14:18:41 -05:00
26e7821aaa Merge pull request #781 from PurpleI2P/openssl
recent changes
2017-01-19 21:57:08 -05:00
e0879fbccb Merge pull request #779 from PurpleI2P/openssl
recent changes
2017-01-16 22:06:32 -05:00
b3ab85f3b5 Merge pull request #768 from PurpleI2P/openssl
recent changes
2017-01-05 15:47:04 -05:00
d4f5871e74 Merge pull request #764 from PurpleI2P/openssl
recent changes
2017-01-02 16:16:51 -05:00
fc08d15a79 Merge pull request #743 from PurpleI2P/openssl
2.11.0
2016-12-18 18:11:22 -05:00
0ea5fbfe0a Merge pull request #731 from PurpleI2P/openssl
recent changes
2016-12-03 09:38:28 -05:00
2756cb8b8f Merge pull request #729 from PurpleI2P/openssl
recent changes
2016-11-29 13:39:26 -05:00
c166bc9b18 Merge pull request #719 from PurpleI2P/openssl
recent changes
2016-11-23 11:31:58 -05:00
fb59d80897 Merge pull request #712 from PurpleI2P/openssl
recent changes
2016-11-16 14:40:50 -05:00
7419f992e7 Merge pull request #703 from PurpleI2P/openssl
recent changes
2016-11-09 14:49:12 -05:00
4a4292a0dc Merge pull request #700 from PurpleI2P/openssl
recent changes
2016-11-06 14:40:43 -05:00
bc92586323 Merge pull request #684 from PurpleI2P/openssl
recent changes
2016-10-22 20:05:28 -04:00
40456ebaae Merge pull request #669 from PurpleI2P/openssl
recent changes
2016-10-12 11:54:51 -04:00
7c34c45983 Merge pull request #646 from PurpleI2P/openssl
recent changes
2016-09-27 16:19:01 -04:00
31f6d13cd8 Merge pull request #639 from PurpleI2P/openssl
recent changes
2016-09-18 07:43:21 -04:00
502e6b0ce5 Merge pull request #631 from rabits/patch-1
Fixed upstart i2pd forking
2016-09-10 19:35:02 -04:00
516380f979 Fixed upstart forking
Upstart can't track daemonize fork without expect fork
2016-09-11 01:15:22 +04:00
63edc60753 Merge pull request #618 from PurpleI2P/openssl
recent changes
2016-08-24 11:12:04 -04:00
492 changed files with 79267 additions and 36298 deletions

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
/build/build_mingw.cmd eol=crlf

21
.github/workflows/build-freebsd.yml vendored Normal file
View File

@ -0,0 +1,21 @@
name: Build on FreeBSD
on: [push, pull_request]
jobs:
build:
runs-on: macos-10.15
name: with UPnP
steps:
- uses: actions/checkout@v2
- name: Test in FreeBSD
id: test
uses: vmactions/freebsd-vm@v0.1.5
with:
usesh: true
mem: 2048
prepare: pkg install -y devel/cmake devel/gmake devel/boost-libs security/openssl net/miniupnpc
run: |
cd build
cmake -DWITH_UPNP=ON -DCMAKE_BUILD_TYPE=Release .
gmake -j2

20
.github/workflows/build-osx.yml vendored Normal file
View File

@ -0,0 +1,20 @@
name: Build on OSX
on: [push, pull_request]
jobs:
build:
name: With USE_UPNP=${{ matrix.with_upnp }}
runs-on: macOS-latest
strategy:
fail-fast: true
matrix:
with_upnp: ['yes', 'no']
steps:
- uses: actions/checkout@v2
- name: install packages
run: |
brew update
brew install boost miniupnpc openssl@1.1
- name: build application
run: make HOMEBREW=1 USE_UPNP=${{ matrix.with_upnp }} PREFIX=$GITHUB_WORKSPACE/output -j3

75
.github/workflows/build-windows.yml vendored Normal file
View File

@ -0,0 +1,75 @@
name: Build on Windows
on: [push, pull_request]
defaults:
run:
shell: msys2 {0}
jobs:
build:
name: Building using ${{ matrix.arch }} toolchain
runs-on: windows-latest
strategy:
fail-fast: true
matrix:
include: [
{ msystem: UCRT64, arch: ucrt-x86_64, arch_short: x64-ucrt },
{ msystem: MINGW64, arch: x86_64, arch_short: x64 },
{ msystem: MINGW32, arch: i686, arch_short: x86 }
]
steps:
- uses: actions/checkout@v2
- name: Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: ${{ matrix.msystem }}
install: base-devel mingw-w64-${{ matrix.arch }}-gcc mingw-w64-${{ matrix.arch }}-boost mingw-w64-${{ matrix.arch }}-openssl mingw-w64-${{ matrix.arch }}-miniupnpc
update: true
- name: Build application
run: |
mkdir -p obj/Win32 obj/libi2pd obj/libi2pd_client obj/daemon
make USE_UPNP=yes DEBUG=no USE_GIT_VERSION=yes -j3
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: i2pd-${{ matrix.arch_short }}.exe
path: i2pd.exe
build-xp:
name: Building for Windows XP
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: MINGW32
install: base-devel git mingw-w64-i686-gcc mingw-w64-i686-boost mingw-w64-i686-openssl mingw-w64-i686-miniupnpc
update: true
- name: Build WinXP-capable CRT packages
run: |
git clone https://github.com/msys2/MINGW-packages
pushd MINGW-packages
pushd mingw-w64-headers-git
sed -i 's/0x601/0x501/' PKGBUILD
MINGW_ARCH=mingw32 makepkg-mingw -sCLf --noconfirm
pacman --noconfirm -U mingw-w64-i686-headers-git-*-any.pkg.tar.zst
popd
pushd mingw-w64-crt-git
MINGW_ARCH=mingw32 makepkg-mingw -sCLf --noconfirm
pacman --noconfirm -U mingw-w64-i686-crt-git-*-any.pkg.tar.zst
popd
pushd mingw-w64-winpthreads-git
MINGW_ARCH=mingw32 makepkg-mingw -sCLf --noconfirm
pacman --noconfirm -U mingw-w64-i686-libwinpthread-git-*-any.pkg.tar.zst mingw-w64-i686-winpthreads-git-*-any.pkg.tar.zst
popd
popd
- name: Build application
run: |
mkdir -p obj/Win32 obj/libi2pd obj/libi2pd_client obj/daemon
make USE_UPNP=yes DEBUG=no USE_GIT_VERSION=yes USE_WINXP_FLAGS=yes -j3
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: i2pd-xp.exe
path: i2pd.exe

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

@ -0,0 +1,88 @@
name: Build on Ubuntu
on: [push, pull_request]
jobs:
build-make:
name: Make with USE_UPNP=${{ matrix.with_upnp }}
runs-on: ubuntu-18.04
strategy:
fail-fast: true
matrix:
with_upnp: ['yes', 'no']
steps:
- uses: actions/checkout@v2
- name: install packages
run: |
sudo add-apt-repository ppa:mhier/libboost-latest
sudo apt-get update
sudo apt-get install build-essential libboost1.74-dev libminiupnpc-dev libssl-dev zlib1g-dev
- name: build application
run: make USE_UPNP=${{ matrix.with_upnp }} -j3
build-cmake:
name: CMake with -DWITH_UPNP=${{ matrix.with_upnp }}
runs-on: ubuntu-18.04
strategy:
fail-fast: true
matrix:
with_upnp: ['ON', 'OFF']
steps:
- uses: actions/checkout@v2
- name: install packages
run: |
sudo add-apt-repository ppa:mhier/libboost-latest
sudo apt-get update
sudo apt-get install build-essential cmake libboost1.74-dev libminiupnpc-dev libssl-dev zlib1g-dev
- name: build application
run: |
cd build
cmake -DWITH_UPNP=${{ matrix.with_upnp }} .
make -j3
build-deb-stretch:
name: Build package for stretch
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: change debian changelog
run: |
sudo apt-get update
sudo apt-get install devscripts
debchange -v "`git describe --tags`-stretch" -b -M --distribution stretch "trunk build"
- uses: singingwolfboy/build-dpkg-stretch@v1
id: build
with:
args: --unsigned-source --unsigned-changes -b
- uses: actions/upload-artifact@v1
with:
name: ${{ steps.build.outputs.filename }}
path: ${{ steps.build.outputs.filename }}
- uses: actions/upload-artifact@v1
with:
name: ${{ steps.build.outputs.filename-dbgsym }}
path: ${{ steps.build.outputs.filename-dbgsym }}
build-deb-buster:
name: Build package for buster
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: change debian changelog
run: |
sudo apt-get update
sudo apt-get install devscripts
debchange -v "`git describe --tags`-buster" -b -M --distribution buster "trunk build"
- uses: singingwolfboy/build-dpkg-buster@v1
id: build
with:
args: --unsigned-source --unsigned-changes -b
- uses: actions/upload-artifact@v1
with:
name: ${{ steps.build.outputs.filename }}
path: ${{ steps.build.outputs.filename }}
- uses: actions/upload-artifact@v1
with:
name: ${{ steps.build.outputs.filename-dbgsym }}
path: ${{ steps.build.outputs.filename-dbgsym }}

70
.github/workflows/docker.yml vendored Normal file
View File

@ -0,0 +1,70 @@
name: Build containers
on:
push:
branches:
- openssl
tags:
- '*'
jobs:
docker:
runs-on: ubuntu-latest
permissions:
packages: write
contents: read
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container registry
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push trunk container
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
uses: docker/build-push-action@v2
with:
context: ./contrib/docker
file: ./contrib/docker/Dockerfile
platforms: linux/amd64,linux/386,linux/arm64,linux/arm/v7
push: true
tags: |
purplei2p/i2pd:latest
ghcr.io/purplei2p/i2pd:latest
- name: Set env
if: ${{ startsWith(github.ref, 'refs/tags/') }}
run: echo "RELEASE_VERSION=${GITHUB_REF:10}" >> $GITHUB_ENV
- name: Build and push release container
if: ${{ startsWith(github.ref, 'refs/tags/') }}
uses: docker/build-push-action@v2
with:
context: ./contrib/docker
file: ./contrib/docker/Dockerfile
platforms: linux/amd64,linux/386,linux/arm64,linux/arm/v7
push: true
tags: |
purplei2p/i2pd:latest
purplei2p/i2pd:latest-release
purplei2p/i2pd:release-${{ env.RELEASE_VERSION }}
ghcr.io/purplei2p/i2pd:latest
ghcr.io/purplei2p/i2pd:latest-release
ghcr.io/purplei2p/i2pd:release-${{ env.RELEASE_VERSION }}

41
.gitignore vendored
View File

@ -1,14 +1,23 @@
# i2pd
obj/*.o
*.o
router.info
router.keys
i2p
libi2pd.so
netDb
/i2pd
/libi2pd.a
/libi2pdclient.a
i2pd.exe
/libi2pdlang.a
/libi2pdwebconsole.a
/libi2pd.so
/libi2pdclient.so
/libi2pdlang.so
/libi2pdwebconsole.so
/libi2pd.dll
/libi2pdclient.dll
/libi2pdlang.dll
/libi2pdwebconsole.dll
*.exe
# Autotools
@ -240,10 +249,34 @@ pip-log.txt
docs/_build
/androidIdea/
# Doxygen
docs/generated
# emacs files
*~
*\#*
# gdb files
.gdb_history
.gdb_history
# cmake makefile
build/Makefile
# debian stuff
debian/i2pd.1.gz
.pc/
# qt
qt/i2pd_qt/*.autosave
qt/i2pd_qt/*.ui.bk*
qt/i2pd_qt/*.ui_*
#unknown android stuff
android/libs/
#various logs
*LOGS/
qt/build-*.sh*

View File

@ -1,35 +0,0 @@
language: cpp
cache:
apt: true
os:
- linux
sudo: required
dist: trusty
addons:
apt:
packages:
- build-essential
- cmake
- g++
- clang
- libboost-chrono-dev
- libboost-date-time-dev
- libboost-filesystem-dev
- libboost-program-options-dev
- libboost-system-dev
- libboost-thread-dev
- libminiupnpc-dev
- libssl-dev
compiler:
- gcc
- clang
before_install:
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew update ; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew install openssl miniupnpc ; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew unlink boost openssl && brew link boost openssl -f ; fi
env:
matrix:
- BUILD_TYPE=Release UPNP=ON
- BUILD_TYPE=Release UPNP=OFF
script:
- cd build && cmake -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DWITH_UPNP=${UPNP} && make

290
Base.cpp
View File

@ -1,290 +0,0 @@
#include <stdlib.h>
#include <string.h>
#include "Base.h"
namespace i2p
{
namespace data
{
static const char T32[32] = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '2', '3', '4', '5', '6', '7',
};
const char * GetBase32SubstitutionTable ()
{
return T32;
}
static void iT64Build(void);
/*
*
* BASE64 Substitution Table
* -------------------------
*
* Direct Substitution Table
*/
static const char T64[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '-', '~'
};
const char * GetBase64SubstitutionTable ()
{
return T64;
}
/*
* Reverse Substitution Table (built in run time)
*/
static char iT64[256];
static int isFirstTime = 1;
/*
* Padding
*/
static char P64 = '=';
/*
*
* ByteStreamToBase64
* ------------------
*
* Converts binary encoded data to BASE64 format.
*
*/
size_t /* Number of bytes in the encoded buffer */
ByteStreamToBase64 (
const uint8_t * InBuffer, /* Input buffer, binary data */
size_t InCount, /* Number of bytes in the input buffer */
char * OutBuffer, /* output buffer */
size_t len /* length of output buffer */
)
{
unsigned char * ps;
unsigned char * pd;
unsigned char acc_1;
unsigned char acc_2;
int i;
int n;
int m;
size_t outCount;
ps = (unsigned char *)InBuffer;
n = InCount/3;
m = InCount%3;
if (!m)
outCount = 4*n;
else
outCount = 4*(n+1);
if (outCount > len) return 0;
pd = (unsigned char *)OutBuffer;
for ( i = 0; i<n; i++ ){
acc_1 = *ps++;
acc_2 = (acc_1<<4)&0x30;
acc_1 >>= 2; /* base64 digit #1 */
*pd++ = T64[acc_1];
acc_1 = *ps++;
acc_2 |= acc_1 >> 4; /* base64 digit #2 */
*pd++ = T64[acc_2];
acc_1 &= 0x0f;
acc_1 <<=2;
acc_2 = *ps++;
acc_1 |= acc_2>>6; /* base64 digit #3 */
*pd++ = T64[acc_1];
acc_2 &= 0x3f; /* base64 digit #4 */
*pd++ = T64[acc_2];
}
if ( m == 1 ){
acc_1 = *ps++;
acc_2 = (acc_1<<4)&0x3f; /* base64 digit #2 */
acc_1 >>= 2; /* base64 digit #1 */
*pd++ = T64[acc_1];
*pd++ = T64[acc_2];
*pd++ = P64;
*pd++ = P64;
}
else if ( m == 2 ){
acc_1 = *ps++;
acc_2 = (acc_1<<4)&0x3f;
acc_1 >>= 2; /* base64 digit #1 */
*pd++ = T64[acc_1];
acc_1 = *ps++;
acc_2 |= acc_1 >> 4; /* base64 digit #2 */
*pd++ = T64[acc_2];
acc_1 &= 0x0f;
acc_1 <<=2; /* base64 digit #3 */
*pd++ = T64[acc_1];
*pd++ = P64;
}
return outCount;
}
/*
*
* Base64ToByteStream
* ------------------
*
* Converts BASE64 encoded data to binary format. If input buffer is
* not properly padded, buffer of negative length is returned
*
*/
size_t /* Number of output bytes */
Base64ToByteStream (
const char * InBuffer, /* BASE64 encoded buffer */
size_t InCount, /* Number of input bytes */
uint8_t * OutBuffer, /* output buffer length */
size_t len /* length of output buffer */
)
{
unsigned char * ps;
unsigned char * pd;
unsigned char acc_1;
unsigned char acc_2;
int i;
int n;
int m;
size_t outCount;
if (isFirstTime) iT64Build();
n = InCount/4;
m = InCount%4;
if (InCount && !m)
outCount = 3*n;
else {
outCount = 0;
return 0;
}
ps = (unsigned char *)(InBuffer + InCount - 1);
while ( *ps-- == P64 ) outCount--;
ps = (unsigned char *)InBuffer;
if (outCount > len) return -1;
pd = OutBuffer;
auto endOfOutBuffer = OutBuffer + outCount;
for ( i = 0; i < n; i++ ){
acc_1 = iT64[*ps++];
acc_2 = iT64[*ps++];
acc_1 <<= 2;
acc_1 |= acc_2>>4;
*pd++ = acc_1;
if (pd >= endOfOutBuffer) break;
acc_2 <<= 4;
acc_1 = iT64[*ps++];
acc_2 |= acc_1 >> 2;
*pd++ = acc_2;
if (pd >= endOfOutBuffer) break;
acc_2 = iT64[*ps++];
acc_2 |= acc_1 << 6;
*pd++ = acc_2;
}
return outCount;
}
size_t Base64EncodingBufferSize (const size_t input_size)
{
auto d = div (input_size, 3);
if (d.rem) d.quot++;
return 4*d.quot;
}
/*
*
* iT64
* ----
* Reverse table builder. P64 character is replaced with 0
*
*
*/
static void iT64Build()
{
int i;
isFirstTime = 0;
for ( i=0; i<256; i++ ) iT64[i] = -1;
for ( i=0; i<64; i++ ) iT64[(int)T64[i]] = i;
iT64[(int)P64] = 0;
}
size_t Base32ToByteStream (const char * inBuf, size_t len, uint8_t * outBuf, size_t outLen)
{
int tmp = 0, bits = 0;
size_t ret = 0;
for (size_t i = 0; i < len; i++)
{
char ch = inBuf[i];
if (ch >= '2' && ch <= '7') // digit
ch = (ch - '2') + 26; // 26 means a-z
else if (ch >= 'a' && ch <= 'z')
ch = ch - 'a'; // a = 0
else
return 0; // unexpected character
tmp |= ch;
bits += 5;
if (bits >= 8)
{
if (ret >= outLen) return ret;
outBuf[ret] = tmp >> (bits - 8);
bits -= 8;
ret++;
}
tmp <<= 5;
}
return ret;
}
size_t ByteStreamToBase32 (const uint8_t * inBuf, size_t len, char * outBuf, size_t outLen)
{
size_t ret = 0, pos = 1;
int bits = 8, tmp = inBuf[0];
while (ret < outLen && (bits > 0 || pos < len))
{
if (bits < 5)
{
if (pos < len)
{
tmp <<= 8;
tmp |= inBuf[pos] & 0xFF;
pos++;
bits += 8;
}
else // last byte
{
tmp <<= (5 - bits);
bits = 5;
}
}
bits -= 5;
int ind = (tmp >> bits) & 0x1F;
outBuf[ret] = (ind < 26) ? (ind + 'a') : ((ind - 26) + '2');
ret++;
}
return ret;
}
}
}

647
ChangeLog
View File

@ -1,6 +1,643 @@
# for this file format description,
# see https://github.com/olivierlacan/keep-a-changelog
## [2.42.1] - 2022-05-24
### Fixed
- Incorrect jump link in HTTP Proxy
## [2.42.0] - 2022-05-22
### Added
- Preliminary SSU2 implementation
- Tunnel length variance
- Localization to French
- Daily cleanup of obsolete peer profiles
- Ordered jump services list in HTTP proxy
- Win32 service
- Show port for local non-published SSU addresses in web console
### Changed
- Maximum RouterInfo length increased to 3K
- Skip unknown addresses in RouterInfo
- Don't pick own router for peer test
- Reseeds list
- Internal numeric id for families
- Use ipv6 preference only when netinet headers not used
- Close stream if delete requested
- Remove version from title in web console
- Drop MESHNET build option
- Set data path before initialization
- Don't show registration block in web console if token is not provided
### Fixed
- Encrypted LeaseSet for EdDSA signature
- Clients tunnels are not built if clock is not synced on start
- Incorrect processing of i2cp.dontPublishLeaseSet param
- UDP tunnels reload
- Build for LibreSSL 3.5.2
- Race condition in short tunnel build message
- Race condition in local RouterInfo buffer allocation
## [2.41.0] - 2022-02-20
### Added
- Clock syncronization through SSU
- Drop routers older than 6 months on start
- Localization to German
- Don't send streaming ack too frequently
- Select compatible outbound tunnel for I2CP messages
- Restart webconsole's acceptor in case of exception
### Changed
- Use builtin bitswap for endian on windows
- Send SessionCreated before connection close if clock skew
- Try another floodfill for publishing if no compatible tunnels found
- Reduce memory usage for RouterInfo structures
- Avoid duplicated addresses in RouterInfo. Check presence of netId and version
- Use TCP/IP sockets for I2CP on Android instead local sockets
- Return uptime as integer in I2PControl
- Reseed servers list/cerificates
- Webconsole's dark style colors
### Fixed
- Attempt to use Yggdrasil on start on Android
- Attempts to send peer tests to itself
- Severe packets drop in SSU
- Crash on tunnel tests
- Loading addressbook subscriptions from config
- Multiple I2CP session to the same destination
- Build on Apple Silicon
## [2.40.0] - 2021-11-29
### Added
- Keep alive parameter for client tunnels
- Support openssl 3.0.0
- Localization to Armenian
- Show git commit info in version
- Windows menu item for opening datadir
- Reseed if too few floodfills
- Don't publish old and replacing tunnel in LeaseSet
- Webconsole light/dark theme depending on system settings (via CSS)
### Changed
- Set gzip compression to false by default
- Build tunnel through ECIES routers only
- Removed ElGamal support for tunnels
- Moved webconsole resources to separate file
- Pick tunnels with compatible transport with another tunnel of floodfill
- Use common cleanup timer for all SSU sessions
- Reduced memory usage
- Reseed servers list
- i18n code called from ClientContext
### Fixed
- Tunnels reload
- Some typos in log messages
- Cleanup relay requests table
- Server tunnel is not published
- Build on GNU/Hurd. Disable pthread_setname_np
- Crash when incorrect sigtype used with blinding
## [2.39.0] - 2021-08-23
### Added
- Short tunnel build messages
- Localization. To: Russian, Ukrainian, Turkmen, Uzbek and Afrikaans
- Custom CSS styles for webconsole
- Avoid slow tunnels with more than 250 ms per hop
- Process DELAY_REQUESTED streaming option
- "certsdir" options for certificates location
- Keep own RouterInfo in NetBb
- Pick ECIES routers only for tunnels on non-x64
- NTP sync through ipv6
- Allow ipv6 addresses for UDP server tunnels
### Changed
- Rekey of all routers to ECIES
- Better distribution for random tunnel's peer selection
- Yggdrasil reseed for v0.4, added two more
- Encryption type 0,4 by default for server tunnels
- Handle i2cp.dontPublishLeaseSet param for all destinations
- reg.i2p for subscriptions
- LeaseSet type 3 by default
- Don't allocate payload buffer for every single ECIESx25519 message
- Prefer public ipv6 instead rfc4941
- Optimal padding for one-time ECIESx25519 message
- Don't send datetime block for one-time ECIESx25519 message with one-time key
- Router with expired introducer is still valid
- Don't disable floodfill if still reachable by ipv6
- Set minimal version for floodfill to 0.9.38
- Eliminate extra lookups for sequential fragments on tunnel endpoint
- Consistent path for explicit peers
- Always create new tunnel from exploratory pool
- Don't try to connect to a router not reachable from us
- Mark additional ipv6 addresses/nets as reserved (#1679)
### Fixed
- Zero-hop tunnels
- Crash upon SAM session termination
- Build with boost < 1.55.0
- Address type for NTCP2 acceptors
- Check of ipv4/ipv6 address
- Request router to send to if not in NetDb
- Count outbound traffic for zero-hop tunnels
- URLdecode domain for registration string generator in webconsole
## [2.38.0] - 2021-05-17
### Added
- Publish ipv6 introducers
- Bind ipv6 or yggdrasil NTCP2 acceptor to specified address
- Support .b32.i2p addresses and hostnames for SAM STREAM CREATE
- ipv6 peer tests
- Publish iexp param for introducers
- Show ipv6 network status on the webconsole
- EdDSA signing keys can also be blinded
- Show router version on the webconsole
### Changed
- Rekey of all routers but floodfills to ECIES
- Increased number of precalculated x25519 keys to 15
- Don't publish LeaseSet without inbound tunnels
- Reseed from compatible address(ipv4 or ipv6)
- Recongnize v4 and v6 SSU addresses without host
- Inbound tunnel gateway must be ipv4 compatible
- Don't select next introducers from existing sessions
- Set X bandwidth for floodfill by default
### Fixed
- Incoming ECIES-x25519 session doesn't send updated LeaseSet
- Unique local address for server tunnels
- Race condition for LeaseSet creation in I2CP
- Relay tag for ipv6 introducer
- Already expired introducers
- Find connected router for first peer in tunnel
- Failed outgoing ECIES-x25519 session's tagset stays forever
- Yggdrasil address disappears if router becomes unreachable through ipv6
- Ignore SSU address/introducers if port is not specified
- Check identity and signature length for SSU SessionConfirmed
## [2.37.0] - 2021-03-15
### Added
- Address registration line for reg.i2p and stats.i2p through the web console
- "4" and "6" caps for addresses without published IP address
- Mesh and Proxy network statuses
- Symmetric NAT network status error
- Bind server tunnel connection to specified address
- lookuplocal BOB extended command
- address4 and address6 parameters to bind outgoing connections to
- Rekey of low-bandwidth routers to ECIES
- Popup notification windows when unable to parse config for Windows
### Changed
- Floodfills with "U" cap are not ignored anymore
- Check transports reachability between tunnel peers and between router and floodfill
- NTCP2 and reseed HTTP proxy support authorization now
- Show actual IP addresses for proxy connections
- Publish and handle SSU addreses without host
- Outbound tunnel endpoint must be ipv4 compatible
- Logging optimization
- Removed Windows service
### Fixed
- Incoming SSU session terminates after 5 seconds
- Outgoing NTCP2 ipv4 session even if ipv4 is disabled
- No incoming Yggdrasil connection if connected through NTCP2 proxy
- Race condition between tunnel build and floodfill requests decryption for ECIES routers
- Numeric bandwidth limitation
- Yggdrasil for Android
## [2.36.0] - 2021-02-15
### Added
- Encrypted lookup and publications to ECIES-x25519 floodfiils
- Yggdrasil transports and reseeds
- Dump addressbook in hosts.txt format
- Request RouterInfo through exploratory tunnels if direct connection to fllodfill is not possible
- Threads naming
- Check if public x25519 key is valid
- ECIES-X25519-AEAD-Ratchet for shared local destination
- LeaseSet creation timeout for I2CP session
- Resend RouterInfo after some interval for longer NTCP2 sessions
- Select reachable router of inbound tunnel gateway
- Reseed if no compatible routers in netdb
- Refresh on swipe in Android webconsole
### Changed
- reg.i2p for default addressbook instead inr.i2p
- ECIES-x25519 (crypto type 4) for new routers
- Try to connect to all compatible addresses from peer's RouterInfo
- Replace LeaseSet completely if store type changes
- Try ECIES-X25519-AEAD-Ratchet tag before ElGamal
- Don't detach ECIES-X25519-AEAD-Ratchet session from destination immediately
- Viewport and styles on error in HTTP proxy
- Don't create notification when Windows taskbar restarted
- Cumulative SSU ACK bitfields
- limit tunnel length to 8 hops
- Limit tunnels quantity to 16
### Fixed
- Handling chunked HTTP response in addressbook
- Missing ECIES-X25519-AEAD-Ratchet tags for multiple streams with the same destination
- Correct NAME for NAMING REPLY in SAM
- SSU crash on termination
- Offline signature length for stream close packet
- Don't send updated LeaseSet through a terminated session
- Decryption of follow-on ECIES-X25519-AEAD-Ratchet NSR messages
- Non-confirmed LeaseSet is resent too late for ECIES-X25519-AEAD-Ratchet session
## [2.35.0] - 2020-11-30
### Added
- ECIES-x25519 routers
- Random intro keys for SSU
- Graceful shutdown timer for windows
- Send queue for I2CP messages
- Update DSA router keys to EdDSA
- TCP_QUICKACK for NTCP2 sockets on Linux
### Changed
- Exclude floodfills with DSA signatures and < 0.9.28
- Random intervals between tunnel tests and manage for tunnel pools
- Don't replace an addressbook record by one with DSA signature
- Publish RouterInfo after update
- Create paired inbound tunnels if no inbound tunnels yet
- Reseed servers list
### Fixed
- Transient signature length, if different from identity
- Terminate I2CP session if destroyed
- RouterInfo publishing confirmation
- Check if ECIES-X25519-AEAD-Ratchet session expired before generating more tags
- Correct block size for delivery type local for ECIES-X25519-AEAD-Ratchet
## [2.34.0] - 2020-10-27
### Added
- Ping responses for streaming
- STREAM FORWARD for SAM
- Tunnels through ECIES-x25519 routers
- Single thread for I2CP
- Shared transient destination between proxies
- Database lookups from ECIES destinations with ratchets response
- Handle WebDAV HTTP methods
- Don't try to connect or build tunnels if offline
- Validate IP when trying connect to remote peer
- Handle ICMP responses and WinAPI errors for SSU
### Changed
- Removed NTCP
- Dropped gcc 4.7 support
- Encyption type 0,4 by default for client tunnels
- Stripped out some HTTP header for HTTP server response
- HTTP 1.1 addressbook requests
- Set LeaseSet type to 3 for ratchets if not specified
- Handle SSU v4 and v6 messages in one thread
- Eliminate DH keys thread
### Fixed
- Random crashes on I2CP session disconnect
- Stream through racthets hangs if first SYN was not acked
- Check "Last-Modified" instead "If-Modified-Since" for addressbook reponse
- Trim behind ECIESx25519 tags
- Few bugs with Android main activity
- QT visual and layout issues
## [2.33.0] - 2020-08-24
### Added
- Shared transient addresses
- crypto.ratchet.inboundTags paramater
- Multiple encryption keys through I2CP
- Pre-calculated x25519 ephemeral keys
- Change datagram routing path if nothing comes back in 10 seconds
- Shared routing path for datagram session
### Changed
- UDP tunnels send mix of repliable and raw datagrams in bulk
- Encrypt SSU packet again upon resend
- Start new tunnel message if remaining buffer is too small
- Use LeaseSet2 for ECIES-X25519-AEAD-Ratchet automatically
- Save new ECIES-X25519-AEAD-Ratchet session with NSR tagset
- Generate random padding lengths for ECIES-X25519-AEAD-Ratchet in bulk
- Webconsole layout
- Reseed servers list
### Fixed
- Don't connect through terminated SAM destination
- Differentiate UDP server sessions by port
- ECIES-X25519-AEAD-Ratchet through I2CP
- Don't save invalid address to AddressBook
- ECDSA signatures names in SAM
- AppArmor profile
## [2.32.1] - 2020-06-02
### Added
- Read explicit peers in tunnels config
### Fixed
- Generation of tags for detached sessions
- Non-updating LeaseSet1
- Start when deprecated websocket options present in i2pd.conf
## [2.32.0] - 2020-05-25
### Added
- Multiple encryption types for local destinations
- Next key and tagset for ECIES-X25519-AEAD-Ratchet
- NTCP2 through SOCKS proxy
- Throw error message if any port to bind is occupied
- gzip parameter for UDP tunnels
- Show ECIES-X25519-AEAD-Ratchet sessions and tags on the web console
- Simplified implementation of gzip for no compression mode
- Allow ECIES-X25519-AEAD-Ratchet session restart after 2 minutes
- Added logrotate config for rpm package
### Changed
- Select peers for client tunnels among routers >= 0.9.36
- Check ECIES flag for encrypted lookup reply
- Streaming MTU size 1812 for ECIES-X25519-AEAD-Ratchet
- Don't calculate checksum for Data message send through ECIES-X25519-AEAD-Ratchet
- Catch network connectivity status for Windows
- Stop as soon as no more transit tunnels during graceful shutdown for Android
- RouterInfo gzip compression level depends on size
- Send response to received datagram from ECIES-X25519-AEAD-Ratchet session
- Update webconsole functional
- Increased max transit tunnels limit
- Reseeds list
- Dropped windows support in cmake
### Fixed
- Correct timestamp check for LeaseSet2
- Encrypted leaseset without authentication
- Change SOCKS proxy connection response for clients without socks5h support (#1336)
## [2.31.0] - 2020-04-10
### Added
- NTCP2 through HTTP proxy
- Publish LeaseSet2 for I2CP destinations
- Show status page on main activity for android
- Handle ECIESFlag in DatabaseLookup at floodfill
- C++17 features for eligible compilers
### Changed
- Droped Websockets and Lua support
- Send DeliveryStatusMsg for LeaseSet for ECIES-X25519-AEAD-Ratchet
- Keep sending new session reply until established for ECIES-X25519-AEAD-Ratchet
- Updated SSU log messages
- Reopen SSU socket on exception
- Security hardening headers in web console
- Various web console changes
- Various QT changes
### Fixed
- NTCP2 socket descriptors leak
- Race condition with router's identity in transport sessions
- Not terminated streams remain forever
## [2.30.0] - 2020-02-25
### Added
- Single threaded SAM
- Experimental support of ECIES-X25519-AEAD-Ratchet crypto type
### Changed
- Minimal MTU size is 1280 for ipv6
- Use unordered_map instead map for destination's sessions and tags list
- Use std::shuffle instead std::random_shuffle
- SAM is single threaded by default
- Reseeds list
### Fixed
- Correct termination of streaming destination
- Extra ',' in RouterInfo response in I2PControl
- SAM crash on session termination
- Storage for Android 10
## [2.29.0] - 2019-10-21
### Added
- Client auth flag for b33 address
### Changed
- Remove incoming NTCP2 session from pending list when established
- Handle errors for NTCP2 SessionConfrimed send
### Fixed
- Failure to start on Windows XP
- SAM crash if invalid lookup address
- Possible crash when UPnP enabled on shutdown
## [2.28.0] - 2019-08-27
### Added
- RAW datagrams in SAM
- Publishing encrypted LeaseSet2 with DH or PSH authentication
- Ability to disable battery optimization for Android
- Transport Network ID Check
### Changed
- Set and handle published encrypted flag for LeaseSet2
### Fixed
- ReceiveID changes in the same stream
- "\r\n" command terminator in SAM
- Addressbook lines with signatures
## [2.27.0] - 2019-07-03
### Added
- Support of PSK and DH authentication for encrypted LeaseSet2
### Changed
- Uptime is based on monotonic timer
### Fixed
- BOB status command response
- Correct NTCP2 port if NTCP is disabled
- Flood encrypted LeaseSet2 with store hash
## [2.26.0] - 2019-06-07
### Added
- HTTP method "PROPFIND"
- Detection of external ipv6 address through the SSU
- NTCP2 publishing depends on network status
### Changed
- ntcp is disabled by default, ntcp2 is published by default
- Response to BOB's "list" command
- ipv6 address is not longer NTCP's local endpoint's address
- Reseeds list
- HTTP_REFERER stripping in httpproxy (#823)
### Fixed
- Check and handle incorrect BOB input
- Ignore introducers for NTCP or NTCP2 addresses
- RouterInfo check from NTCP2
## [2.25.0] - 2019-05-09
### Added
- Create, publish and handle encrypted LeaseSet2
- Support of b33 addresses
- RedDSA key blinding
- .b32.i2p addresses in jump links
- ntcp2.addressv6 parameter
### Changed
- Allow HTTP headers without value
- Set data directory from external storage path for Android
- addresshelper support is configurable per tunnel
- gradlew script for android build
### Fixed
- Deletion of expired encrypted LeaseSet2 on floodfills
- ipv6 fallback address
- SSU incoming packets routing
## [2.24.0] - 2019-03-21
### Added
- Support of transient keys for LeaseSet2
- Support of encrypted LeaseSet2
- Recognize signature type 11 (RedDSA)
- Support websocket connections over HTTP proxy
- Ability to disable full addressbook persist
### Changed
- Don't load peer profiles if non-persistant
- REUSE_ADDR for ipv6 acceptors
- Reset eTags if addressbook can't be loaded
### Fixed
- Build with boost 1.70
- Filter out unspecified addresses from RouterInfo
- Check floodfill status change
- Correct SAM response for invalid key
- SAM crash on termination for Windows
- Race condition for publishing
## [2.23.0] - 2019-01-21
### Added
- Standard LeaseSet2 support
- Ability to adjust timestamps through the NTP
- Ability to disable peer profile persist
- Request permission for android >= 6
- Initial addressbook to android assets
- Cancel graceful shutdown for android
- Russian translation for android
### Changed
- Chacha20 and Poly1305 implementation
- Eliminate extra copy of NTCP2 send buffers
- Extract content of tunnel.d from assets on android
- Removed name resolvers from transports
- Update reseed certificates
### Fixed
- LeaseSet published content verification
- Exclude invalid LeaseSets from the list on a floodfill
- Build for OpenWrt with openssl 1.1.1
## [2.22.0] - 2018-11-09
### Added
- Multiple tunnel config files from tunnels.d folder
### Changed
- Fetch own RouterInfo upon SessionRequest for NTCP2
- Faster XOR between AES blocks for non AVX capable CPUs
### Fixed
- Fixed NTCP2 termination send
## [2.21.1] - 2018-10-22
### Changed
- cost=13 for unpublished NTCP2 address
### Fixed
- Handle I2NP messages longer than 32K
## [2.21.0] - 2018-10-04
### Added
- EdDSA, x25519 and SipHash from openssl 1.1.1
- NTCP2 ipv6 incoming connections
- Show total number of destination's outgoing tags in the web console
### Changed
- Android build with openssl 1.1.1/boost 1.64
- Bandwidth classes 'P' and 'X' don't add 'O' anymore
### Fixed
- Update own RouterInfo if no SSU
- Recognize 'P' and 'X' routers as high bandwidth without 'O'
- NTCP address doesn't disappear if NTCP2 enabled
- Android with api 26+
## [2.20.0] - 2018-08-23
### Added
- Full implementation of NTCP2
- Assets for android
### Changed
- armeabi-v7a and x86 in one apk for android
- NTCP2 is enabled by default
- Show lease's expiration time in readable format in the web console
### Fixed
- Correct names for transports in the web console
## [2.19.0] - 2018-06-26
### Added
- ECIES support for RouterInfo
- HTTP outproxy authorization
- AVX/AESNI runtime detection
- Initial implementation of NTCP2
- I2CP session reconfigure
- I2CP method ClientServicesInfo
- Datagrams to websocks
### Changed
- RouterInfo uses EdDSA signature by default
- Remove stream bans
- Android build system changed to gradle
- Multiple changes in QT GUI
- Dockerfile
### Fixed
- zero tunnelID issue
- tunnels reload
- headers in webconsole
- XSS in webconsole from SAM session name
- build for gcc 8
- cmake build scripts
- systemd service files
- some netbsd issues
## [2.18.0] - 2018-01-30
### Added
- Show tunnel nicknames for I2CP destination in WebUI
- Re-create HTTP and SOCKS proxy by tunnel reload
- Graceful shutdown as soon as no more transit tunnels
### Changed
- Regenerate shared local destination by tunnel reload
- Use transient local destination by default if not specified
- Return correct code if pid file can't be created
- Timing and number of attempts for adressbook requests
- Certificates list
### Fixed
- Malformed addressbook subsctiption request
- Build with boost 1.66
- Few race conditions for SAM
- Check LeaseSet's signature before update
## [2.17.0] - 2017-12-04
### Added
- Reseed through HTTP and SOCKS proxy
- Show status of client services through web console
- Change log level through web connsole
- transient keys for tunnels
- i2p.streaming.initialAckDelay parameter
- CRYPTO_TYPE for SAM destination
- signature and crypto type for newkeys BOB command
### Changed
- Correct publication of ECIES destinations
- Disable RSA signatures completely
### Fixed
- CVE-2017-17066
- Possible buffer overflow for RSA-4096
- Shutdown from web console for Windows
- Web console page layout
## [2.16.0] - 2017-11-13
### Added
- https and "Connect" method for HTTP proxy
- outproxy for HTTP proxy
- initial support of ECIES crypto
- NTCP soft and hard descriptors limits
- Support full timestamps in logs
### Changed
- Faster implementation of GOST R 34.11 hash
- Reject routers with RSA signtures
- Reload config and shudown from Windows GUI
- Update tunnels address(destination) without restart
### Fixed
- BOB crashes if destination is not set
- Correct SAM tunnel name
- QT GUI issues
## [2.15.0] - 2017-08-17
### Added
- QT GUI
- Ability to add and remove I2P tunnels without restart
- Ability to disable SOCKS outproxy option
### Changed
- Strip-out Accept-* hedaers in HTTP proxy
- Don't run peer test if nat=false
- Separate output of NTCP and SSU sessions in Transports tab
### Fixed
- Handle lines with comments in hosts.txt file for address book
- Run router with empty netdb for testnet
- Skip expired introducers by iexp
## [2.14.0] - 2017-06-01
### Added
- Transit traffic bandwidth limitation
- NTCP connections through HTTP and SOCKS proxies
- Ability to disable address helper for HTTP proxy
### Changed
- Reseed servers list
- Minimal required version is 4.0 for Android
### Fixed
- Ignore comments in addressbook feed
## [2.13.0] - 2017-04-06
### Added
- Persist local destination's tags
- GOST signature types 9 and 10
- Exploratory tunnels configuration
### Changed
- Reseed servers list
- Inactive NTCP sockets get closed faster
- Some EdDSA speed up
### Fixed
- Multiple acceptors for SAM
- Follow on data after STREAM CREATE for SAM
- Memory leaks
## [2.12.0] - 2017-02-14
### Added
- Additional HTTP and SOCKS proxy tunnels
@ -8,7 +645,7 @@
- Some stats in a main window for Windows version
### Changed
- Reseed servers list
- MTU of 1488 for ipv6
- MTU of 1488 for ipv6
- Android and Mac OS X versions use OpenSSL 1.1
- New logo for Android
### Fixed
@ -38,7 +675,7 @@
## [2.10.2] - 2016-12-04
### Fixed
- Fixes UPnP discovery bug, producing excessive CPU usage
- Fixes sudden SSU thread stop for Windows.
- Fixes sudden SSU thread stop for Windows.
## [2.10.1] - 2016-11-07
### Fixed
@ -53,7 +690,7 @@
- Initial iOS support
### Changed
- Reduced file descriptiors usage
- Reduced file descriptors usage
- Strict reseed checks enabled by default
## Fixed
@ -89,12 +726,12 @@
- Configurable limit of transit tunnels
### Changed
- Speed-up of assymetric crypto for non-x64 platforms
- Speed-up of asymmetric crypto for non-x64 platforms
- Refactoring of web-console
## [2.6.0] - 2016-03-31
### Added
- Gracefull shutdown on SIGINT
- Graceful shutdown on SIGINT
- Numeric bandwidth limits (was: by router class)
- Jumpservices in web-console
- Logging to syslog

View File

@ -1,648 +0,0 @@
#include <fstream>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include "Config.h"
#include "FS.h"
#include "Log.h"
#include "Identity.h"
#include "util.h"
#include "ClientContext.h"
#include "SOCKS.h"
#include "WebSocks.h"
namespace i2p
{
namespace client
{
ClientContext context;
ClientContext::ClientContext (): m_SharedLocalDestination (nullptr),
m_HttpProxy (nullptr), m_SocksProxy (nullptr), m_SamBridge (nullptr),
m_BOBCommandChannel (nullptr), m_I2CPServer (nullptr)
{
}
ClientContext::~ClientContext ()
{
delete m_HttpProxy;
delete m_SocksProxy;
delete m_SamBridge;
delete m_BOBCommandChannel;
delete m_I2CPServer;
}
void ClientContext::Start ()
{
if (!m_SharedLocalDestination)
{
m_SharedLocalDestination = CreateNewLocalDestination (); // non-public, DSA
m_Destinations[m_SharedLocalDestination->GetIdentity ()->GetIdentHash ()] = m_SharedLocalDestination;
m_SharedLocalDestination->Start ();
}
m_AddressBook.Start ();
std::shared_ptr<ClientDestination> localDestination;
bool httproxy; i2p::config::GetOption("httpproxy.enabled", httproxy);
if (httproxy) {
std::string httpProxyKeys; i2p::config::GetOption("httpproxy.keys", httpProxyKeys);
std::string httpProxyAddr; i2p::config::GetOption("httpproxy.address", httpProxyAddr);
uint16_t httpProxyPort; i2p::config::GetOption("httpproxy.port", httpProxyPort);
i2p::data::SigningKeyType sigType; i2p::config::GetOption("httpproxy.signaturetype", sigType);
LogPrint(eLogInfo, "Clients: starting HTTP Proxy at ", httpProxyAddr, ":", httpProxyPort);
if (httpProxyKeys.length () > 0)
{
i2p::data::PrivateKeys keys;
if(LoadPrivateKeys (keys, httpProxyKeys, sigType))
{
std::map<std::string, std::string> params;
ReadI2CPOptionsFromConfig ("httpproxy.", params);
localDestination = CreateNewLocalDestination (keys, false, &params);
}
else
LogPrint(eLogError, "Clients: failed to load HTTP Proxy key");
}
try {
m_HttpProxy = new i2p::proxy::HTTPProxy(httpProxyAddr, httpProxyPort, localDestination);
m_HttpProxy->Start();
} catch (std::exception& e) {
LogPrint(eLogError, "Clients: Exception in HTTP Proxy: ", e.what());
}
}
localDestination = nullptr;
bool socksproxy; i2p::config::GetOption("socksproxy.enabled", socksproxy);
if (socksproxy)
{
std::string socksProxyKeys; i2p::config::GetOption("socksproxy.keys", socksProxyKeys);
std::string socksProxyAddr; i2p::config::GetOption("socksproxy.address", socksProxyAddr);
uint16_t socksProxyPort; i2p::config::GetOption("socksproxy.port", socksProxyPort);
std::string socksOutProxyAddr; i2p::config::GetOption("socksproxy.outproxy", socksOutProxyAddr);
uint16_t socksOutProxyPort; i2p::config::GetOption("socksproxy.outproxyport", socksOutProxyPort);
i2p::data::SigningKeyType sigType; i2p::config::GetOption("socksproxy.signaturetype", sigType);
LogPrint(eLogInfo, "Clients: starting SOCKS Proxy at ", socksProxyAddr, ":", socksProxyPort);
if (socksProxyKeys.length () > 0)
{
i2p::data::PrivateKeys keys;
if (LoadPrivateKeys (keys, socksProxyKeys, sigType))
{
std::map<std::string, std::string> params;
ReadI2CPOptionsFromConfig ("socksproxy.", params);
localDestination = CreateNewLocalDestination (keys, false, &params);
}
else
LogPrint(eLogError, "Clients: failed to load SOCKS Proxy key");
}
try {
m_SocksProxy = new i2p::proxy::SOCKSProxy(socksProxyAddr, socksProxyPort, socksOutProxyAddr, socksOutProxyPort, localDestination);
m_SocksProxy->Start();
} catch (std::exception& e) {
LogPrint(eLogError, "Clients: Exception in SOCKS Proxy: ", e.what());
}
}
// I2P tunnels
ReadTunnels ();
// SAM
bool sam; i2p::config::GetOption("sam.enabled", sam);
if (sam) {
std::string samAddr; i2p::config::GetOption("sam.address", samAddr);
uint16_t samPort; i2p::config::GetOption("sam.port", samPort);
LogPrint(eLogInfo, "Clients: starting SAM bridge at ", samAddr, ":", samPort);
try {
m_SamBridge = new SAMBridge (samAddr, samPort);
m_SamBridge->Start ();
} catch (std::exception& e) {
LogPrint(eLogError, "Clients: Exception in SAM bridge: ", e.what());
}
}
// BOB
bool bob; i2p::config::GetOption("bob.enabled", bob);
if (bob) {
std::string bobAddr; i2p::config::GetOption("bob.address", bobAddr);
uint16_t bobPort; i2p::config::GetOption("bob.port", bobPort);
LogPrint(eLogInfo, "Clients: starting BOB command channel at ", bobAddr, ":", bobPort);
try {
m_BOBCommandChannel = new BOBCommandChannel (bobAddr, bobPort);
m_BOBCommandChannel->Start ();
} catch (std::exception& e) {
LogPrint(eLogError, "Clients: Exception in BOB bridge: ", e.what());
}
}
// I2CP
bool i2cp; i2p::config::GetOption("i2cp.enabled", i2cp);
if (i2cp)
{
std::string i2cpAddr; i2p::config::GetOption("i2cp.address", i2cpAddr);
uint16_t i2cpPort; i2p::config::GetOption("i2cp.port", i2cpPort);
LogPrint(eLogInfo, "Clients: starting I2CP at ", i2cpAddr, ":", i2cpPort);
try
{
m_I2CPServer = new I2CPServer (i2cpAddr, i2cpPort);
m_I2CPServer->Start ();
}
catch (std::exception& e)
{
LogPrint(eLogError, "Clients: Exception in I2CP: ", e.what());
}
}
m_AddressBook.StartResolvers ();
// start UDP cleanup
if (!m_ServerForwards.empty ())
{
m_CleanupUDPTimer.reset (new boost::asio::deadline_timer(m_SharedLocalDestination->GetService ()));
ScheduleCleanupUDP();
}
}
void ClientContext::Stop ()
{
if (m_HttpProxy)
{
LogPrint(eLogInfo, "Clients: stopping HTTP Proxy");
m_HttpProxy->Stop();
delete m_HttpProxy;
m_HttpProxy = nullptr;
}
if (m_SocksProxy)
{
LogPrint(eLogInfo, "Clients: stopping SOCKS Proxy");
m_SocksProxy->Stop();
delete m_SocksProxy;
m_SocksProxy = nullptr;
}
for (auto& it: m_ClientTunnels)
{
LogPrint(eLogInfo, "Clients: stopping I2P client tunnel on port ", it.first);
it.second->Stop ();
}
m_ClientTunnels.clear ();
for (auto& it: m_ServerTunnels)
{
LogPrint(eLogInfo, "Clients: stopping I2P server tunnel");
it.second->Stop ();
}
m_ServerTunnels.clear ();
if (m_SamBridge)
{
LogPrint(eLogInfo, "Clients: stopping SAM bridge");
m_SamBridge->Stop ();
delete m_SamBridge;
m_SamBridge = nullptr;
}
if (m_BOBCommandChannel)
{
LogPrint(eLogInfo, "Clients: stopping BOB command channel");
m_BOBCommandChannel->Stop ();
delete m_BOBCommandChannel;
m_BOBCommandChannel = nullptr;
}
if (m_I2CPServer)
{
LogPrint(eLogInfo, "Clients: stopping I2CP");
m_I2CPServer->Stop ();
delete m_I2CPServer;
m_I2CPServer = nullptr;
}
LogPrint(eLogInfo, "Clients: stopping AddressBook");
m_AddressBook.Stop ();
{
std::lock_guard<std::mutex> lock(m_ForwardsMutex);
m_ServerForwards.clear();
m_ClientForwards.clear();
}
if (m_CleanupUDPTimer)
{
m_CleanupUDPTimer->cancel ();
m_CleanupUDPTimer = nullptr;
}
for (auto& it: m_Destinations)
it.second->Stop ();
m_Destinations.clear ();
m_SharedLocalDestination = nullptr;
}
void ClientContext::ReloadConfig ()
{
std::string config; i2p::config::GetOption("conf", config);
i2p::config::ParseConfig(config);
Stop();
Start();
}
bool ClientContext::LoadPrivateKeys (i2p::data::PrivateKeys& keys, const std::string& filename, i2p::data::SigningKeyType sigType)
{
bool success = true;
std::string fullPath = i2p::fs::DataDirPath (filename);
std::ifstream s(fullPath, std::ifstream::binary);
if (s.is_open ())
{
s.seekg (0, std::ios::end);
size_t len = s.tellg();
s.seekg (0, std::ios::beg);
uint8_t * buf = new uint8_t[len];
s.read ((char *)buf, len);
if(!keys.FromBuffer (buf, len))
{
LogPrint (eLogError, "Clients: failed to load keyfile ", filename);
success = false;
}
else
LogPrint (eLogInfo, "Clients: Local address ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " loaded");
delete[] buf;
}
else
{
LogPrint (eLogError, "Clients: can't open file ", fullPath, " Creating new one with signature type ", sigType);
keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType);
std::ofstream f (fullPath, std::ofstream::binary | std::ofstream::out);
size_t len = keys.GetFullLen ();
uint8_t * buf = new uint8_t[len];
len = keys.ToBuffer (buf, len);
f.write ((char *)buf, len);
delete[] buf;
LogPrint (eLogInfo, "Clients: New private keys file ", fullPath, " for ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " created");
}
return success;
}
std::vector<std::shared_ptr<DatagramSessionInfo> > ClientContext::GetForwardInfosFor(const i2p::data::IdentHash & destination)
{
std::vector<std::shared_ptr<DatagramSessionInfo> > infos;
std::lock_guard<std::mutex> lock(m_ForwardsMutex);
for(const auto & c : m_ClientForwards)
{
if (c.second->IsLocalDestination(destination))
{
for (auto & i : c.second->GetSessions()) infos.push_back(i);
break;
}
}
for(const auto & s : m_ServerForwards)
{
if(std::get<0>(s.first) == destination)
{
for( auto & i : s.second->GetSessions()) infos.push_back(i);
break;
}
}
return infos;
}
std::shared_ptr<ClientDestination> ClientContext::CreateNewLocalDestination (bool isPublic, i2p::data::SigningKeyType sigType,
const std::map<std::string, std::string> * params)
{
i2p::data::PrivateKeys keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType);
auto localDestination = std::make_shared<ClientDestination> (keys, isPublic, params);
std::unique_lock<std::mutex> l(m_DestinationsMutex);
m_Destinations[localDestination->GetIdentHash ()] = localDestination;
localDestination->Start ();
return localDestination;
}
void ClientContext::DeleteLocalDestination (std::shared_ptr<ClientDestination> destination)
{
if (!destination) return;
auto it = m_Destinations.find (destination->GetIdentHash ());
if (it != m_Destinations.end ())
{
auto d = it->second;
{
std::unique_lock<std::mutex> l(m_DestinationsMutex);
m_Destinations.erase (it);
}
d->Stop ();
}
}
std::shared_ptr<ClientDestination> ClientContext::CreateNewLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic,
const std::map<std::string, std::string> * params)
{
auto it = m_Destinations.find (keys.GetPublic ()->GetIdentHash ());
if (it != m_Destinations.end ())
{
LogPrint (eLogWarning, "Clients: Local destination ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " exists");
if (!it->second->IsRunning ())
{
it->second->Start ();
return it->second;
}
return nullptr;
}
auto localDestination = std::make_shared<ClientDestination> (keys, isPublic, params);
std::unique_lock<std::mutex> l(m_DestinationsMutex);
m_Destinations[keys.GetPublic ()->GetIdentHash ()] = localDestination;
localDestination->Start ();
return localDestination;
}
std::shared_ptr<ClientDestination> ClientContext::FindLocalDestination (const i2p::data::IdentHash& destination) const
{
auto it = m_Destinations.find (destination);
if (it != m_Destinations.end ())
return it->second;
return nullptr;
}
template<typename Section, typename Type>
std::string ClientContext::GetI2CPOption (const Section& section, const std::string& name, const Type& value) const
{
return section.second.get (boost::property_tree::ptree::path_type (name, '/'), std::to_string (value));
}
template<typename Section>
void ClientContext::ReadI2CPOptions (const Section& section, std::map<std::string, std::string>& options) const
{
options[I2CP_PARAM_INBOUND_TUNNEL_LENGTH] = GetI2CPOption (section, I2CP_PARAM_INBOUND_TUNNEL_LENGTH, DEFAULT_INBOUND_TUNNEL_LENGTH);
options[I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH] = GetI2CPOption (section, I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH, DEFAULT_OUTBOUND_TUNNEL_LENGTH);
options[I2CP_PARAM_INBOUND_TUNNELS_QUANTITY] = GetI2CPOption (section, I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, DEFAULT_INBOUND_TUNNELS_QUANTITY);
options[I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY] = GetI2CPOption (section, I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, DEFAULT_OUTBOUND_TUNNELS_QUANTITY);
options[I2CP_PARAM_TAGS_TO_SEND] = GetI2CPOption (section, I2CP_PARAM_TAGS_TO_SEND, DEFAULT_TAGS_TO_SEND);
options[I2CP_PARAM_MIN_TUNNEL_LATENCY] = GetI2CPOption(section, I2CP_PARAM_MIN_TUNNEL_LATENCY, DEFAULT_MIN_TUNNEL_LATENCY);
options[I2CP_PARAM_MAX_TUNNEL_LATENCY] = GetI2CPOption(section, I2CP_PARAM_MAX_TUNNEL_LATENCY, DEFAULT_MAX_TUNNEL_LATENCY);
}
void ClientContext::ReadI2CPOptionsFromConfig (const std::string& prefix, std::map<std::string, std::string>& options) const
{
std::string value;
if (i2p::config::GetOption(prefix + I2CP_PARAM_INBOUND_TUNNEL_LENGTH, value))
options[I2CP_PARAM_INBOUND_TUNNEL_LENGTH] = value;
if (i2p::config::GetOption(prefix + I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, value))
options[I2CP_PARAM_INBOUND_TUNNELS_QUANTITY] = value;
if (i2p::config::GetOption(prefix + I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH, value))
options[I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH] = value;
if (i2p::config::GetOption(prefix + I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, value))
options[I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY] = value;
if (i2p::config::GetOption(prefix + I2CP_PARAM_MIN_TUNNEL_LATENCY, value))
options[I2CP_PARAM_MIN_TUNNEL_LATENCY] = value;
if (i2p::config::GetOption(prefix + I2CP_PARAM_MAX_TUNNEL_LATENCY, value))
options[I2CP_PARAM_MAX_TUNNEL_LATENCY] = value;
}
void ClientContext::ReadTunnels ()
{
boost::property_tree::ptree pt;
std::string tunConf; i2p::config::GetOption("tunconf", tunConf);
if (tunConf == "") {
// TODO: cleanup this in 2.8.0
tunConf = i2p::fs::DataDirPath ("tunnels.cfg");
if (i2p::fs::Exists(tunConf)) {
LogPrint(eLogWarning, "FS: please rename tunnels.cfg -> tunnels.conf here: ", tunConf);
} else {
tunConf = i2p::fs::DataDirPath ("tunnels.conf");
}
}
LogPrint(eLogDebug, "FS: tunnels config file: ", tunConf);
try
{
boost::property_tree::read_ini (tunConf, pt);
}
catch (std::exception& ex)
{
LogPrint (eLogWarning, "Clients: Can't read ", tunConf, ": ", ex.what ());
return;
}
int numClientTunnels = 0, numServerTunnels = 0;
for (auto& section: pt)
{
std::string name = section.first;
try
{
std::string type = section.second.get<std::string> (I2P_TUNNELS_SECTION_TYPE);
if (type == I2P_TUNNELS_SECTION_TYPE_CLIENT
|| type == I2P_TUNNELS_SECTION_TYPE_SOCKS
|| type == I2P_TUNNELS_SECTION_TYPE_WEBSOCKS
|| type == I2P_TUNNELS_SECTION_TYPE_HTTPPROXY
|| type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT)
{
// mandatory params
std::string dest;
if (type == I2P_TUNNELS_SECTION_TYPE_CLIENT || type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT)
dest = section.second.get<std::string> (I2P_CLIENT_TUNNEL_DESTINATION);
int port = section.second.get<int> (I2P_CLIENT_TUNNEL_PORT);
// optional params
std::string keys = section.second.get (I2P_CLIENT_TUNNEL_KEYS, "");
std::string address = section.second.get (I2P_CLIENT_TUNNEL_ADDRESS, "127.0.0.1");
int destinationPort = section.second.get (I2P_CLIENT_TUNNEL_DESTINATION_PORT, 0);
i2p::data::SigningKeyType sigType = section.second.get (I2P_CLIENT_TUNNEL_SIGNATURE_TYPE, i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256);
// I2CP
std::map<std::string, std::string> options;
ReadI2CPOptions (section, options);
std::shared_ptr<ClientDestination> localDestination = nullptr;
if (keys.length () > 0)
{
i2p::data::PrivateKeys k;
if(LoadPrivateKeys (k, keys, sigType))
{
localDestination = FindLocalDestination (k.GetPublic ()->GetIdentHash ());
if (!localDestination)
localDestination = CreateNewLocalDestination (k, type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT, &options);
}
}
if (type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT) {
// udp client
// TODO: hostnames
boost::asio::ip::udp::endpoint end(boost::asio::ip::address::from_string(address), port);
if (!localDestination)
{
localDestination = m_SharedLocalDestination;
}
auto clientTunnel = new I2PUDPClientTunnel(name, dest, end, localDestination, destinationPort);
if(m_ClientForwards.insert(std::make_pair(end, std::unique_ptr<I2PUDPClientTunnel>(clientTunnel))).second)
{
clientTunnel->Start();
}
else
LogPrint(eLogError, "Clients: I2P Client forward for endpoint ", end, " already exists");
} else {
boost::asio::ip::tcp::endpoint clientEndpoint;
I2PService * clientTunnel = nullptr;
if (type == I2P_TUNNELS_SECTION_TYPE_SOCKS)
{
// socks proxy
clientTunnel = new i2p::proxy::SOCKSProxy(address, port, "", destinationPort, localDestination);
clientEndpoint = ((i2p::proxy::SOCKSProxy*)clientTunnel)->GetAcceptor().local_endpoint();
}
else if (type == I2P_TUNNELS_SECTION_TYPE_HTTPPROXY)
{
// http proxy
clientTunnel = new i2p::proxy::HTTPProxy(address, port, localDestination);
clientEndpoint = ((i2p::proxy::HTTPProxy*)clientTunnel)->GetAcceptor().local_endpoint();
}
else if (type == I2P_TUNNELS_SECTION_TYPE_WEBSOCKS)
{
// websocks proxy
clientTunnel = new WebSocks(address, port, localDestination);;
clientEndpoint = ((WebSocks*)clientTunnel)->GetLocalEndpoint();
}
else
{
// tcp client
clientTunnel = new I2PClientTunnel (name, dest, address, port, localDestination, destinationPort);
clientEndpoint = ((I2PClientTunnel*)clientTunnel)->GetAcceptor().local_endpoint();
}
if (m_ClientTunnels.insert (std::make_pair (clientEndpoint, std::unique_ptr<I2PService>(clientTunnel))).second)
{
clientTunnel->Start ();
numClientTunnels++;
}
else
LogPrint (eLogError, "Clients: I2P client tunnel for endpoint ", clientEndpoint, "already exists");
}
}
else if (type == I2P_TUNNELS_SECTION_TYPE_SERVER
|| type == I2P_TUNNELS_SECTION_TYPE_HTTP
|| type == I2P_TUNNELS_SECTION_TYPE_IRC
|| type == I2P_TUNNELS_SECTION_TYPE_UDPSERVER)
{
// mandatory params
std::string host = section.second.get<std::string> (I2P_SERVER_TUNNEL_HOST);
int port = section.second.get<int> (I2P_SERVER_TUNNEL_PORT);
std::string keys = section.second.get<std::string> (I2P_SERVER_TUNNEL_KEYS);
// optional params
int inPort = section.second.get (I2P_SERVER_TUNNEL_INPORT, 0);
std::string accessList = section.second.get (I2P_SERVER_TUNNEL_ACCESS_LIST, "");
std::string hostOverride = section.second.get (I2P_SERVER_TUNNEL_HOST_OVERRIDE, "");
std::string webircpass = section.second.get<std::string> (I2P_SERVER_TUNNEL_WEBIRC_PASSWORD, "");
bool gzip = section.second.get (I2P_SERVER_TUNNEL_GZIP, true);
i2p::data::SigningKeyType sigType = section.second.get (I2P_SERVER_TUNNEL_SIGNATURE_TYPE, i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256);
uint32_t maxConns = section.second.get(i2p::stream::I2CP_PARAM_STREAMING_MAX_CONNS_PER_MIN, i2p::stream::DEFAULT_MAX_CONNS_PER_MIN);
std::string address = section.second.get<std::string> (I2P_SERVER_TUNNEL_ADDRESS, "127.0.0.1");
bool isUniqueLocal = section.second.get(I2P_SERVER_TUNNEL_ENABLE_UNIQUE_LOCAL, true);
// I2CP
std::map<std::string, std::string> options;
ReadI2CPOptions (section, options);
std::shared_ptr<ClientDestination> localDestination = nullptr;
i2p::data::PrivateKeys k;
if(!LoadPrivateKeys (k, keys, sigType))
continue;
localDestination = FindLocalDestination (k.GetPublic ()->GetIdentHash ());
if (!localDestination)
localDestination = CreateNewLocalDestination (k, true, &options);
if (type == I2P_TUNNELS_SECTION_TYPE_UDPSERVER)
{
// udp server tunnel
// TODO: hostnames
auto localAddress = boost::asio::ip::address::from_string(address);
boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address::from_string(host), port);
I2PUDPServerTunnel * serverTunnel = new I2PUDPServerTunnel(name, localDestination, localAddress, endpoint, port);
if(!isUniqueLocal)
{
LogPrint(eLogInfo, "Clients: disabling loopback address mapping");
serverTunnel->SetUniqueLocal(isUniqueLocal);
}
std::lock_guard<std::mutex> lock(m_ForwardsMutex);
if(m_ServerForwards.insert(
std::make_pair(
std::make_pair(
localDestination->GetIdentHash(), port),
std::unique_ptr<I2PUDPServerTunnel>(serverTunnel))).second)
{
serverTunnel->Start();
LogPrint(eLogInfo, "Clients: I2P Server Forward created for UDP Endpoint ", host, ":", port, " bound on ", address, " for ",localDestination->GetIdentHash().ToBase32());
}
else
LogPrint(eLogError, "Clients: I2P Server Forward for destination/port ", m_AddressBook.ToAddress(localDestination->GetIdentHash()), "/", port, "already exists");
continue;
}
I2PServerTunnel * serverTunnel;
if (type == I2P_TUNNELS_SECTION_TYPE_HTTP)
serverTunnel = new I2PServerTunnelHTTP (name, host, port, localDestination, hostOverride, inPort, gzip);
else if (type == I2P_TUNNELS_SECTION_TYPE_IRC)
serverTunnel = new I2PServerTunnelIRC (name, host, port, localDestination, webircpass, inPort, gzip);
else // regular server tunnel by default
serverTunnel = new I2PServerTunnel (name, host, port, localDestination, inPort, gzip);
LogPrint(eLogInfo, "Clients: Set Max Conns To ", maxConns);
serverTunnel->SetMaxConnsPerMinute(maxConns);
if(!isUniqueLocal)
{
LogPrint(eLogInfo, "Clients: disabling loopback address mapping");
serverTunnel->SetUniqueLocal(isUniqueLocal);
}
if (accessList.length () > 0)
{
std::set<i2p::data::IdentHash> idents;
size_t pos = 0, comma;
do
{
comma = accessList.find (',', pos);
i2p::data::IdentHash ident;
ident.FromBase32 (accessList.substr (pos, comma != std::string::npos ? comma - pos : std::string::npos));
idents.insert (ident);
pos = comma + 1;
}
while (comma != std::string::npos);
serverTunnel->SetAccessList (idents);
}
if (m_ServerTunnels.insert (std::make_pair (
std::make_pair (localDestination->GetIdentHash (), inPort),
std::unique_ptr<I2PServerTunnel>(serverTunnel))).second)
{
serverTunnel->Start ();
numServerTunnels++;
}
else
LogPrint (eLogError, "Clients: I2P server tunnel for destination/port ", m_AddressBook.ToAddress(localDestination->GetIdentHash ()), "/", inPort, " already exists");
}
else
LogPrint (eLogWarning, "Clients: Unknown section type=", type, " of ", name, " in ", tunConf);
}
catch (std::exception& ex)
{
LogPrint (eLogError, "Clients: Can't read tunnel ", name, " params: ", ex.what ());
}
}
LogPrint (eLogInfo, "Clients: ", numClientTunnels, " I2P client tunnels created");
LogPrint (eLogInfo, "Clients: ", numServerTunnels, " I2P server tunnels created");
}
void ClientContext::ScheduleCleanupUDP()
{
if (m_CleanupUDPTimer)
{
// schedule cleanup in 17 seconds
m_CleanupUDPTimer->expires_from_now (boost::posix_time::seconds (17));
m_CleanupUDPTimer->async_wait(std::bind(&ClientContext::CleanupUDP, this, std::placeholders::_1));
}
}
void ClientContext::CleanupUDP(const boost::system::error_code & ecode)
{
if(!ecode)
{
std::lock_guard<std::mutex> lock(m_ForwardsMutex);
for (auto & s : m_ServerForwards ) s.second->ExpireStale();
ScheduleCleanupUDP();
}
}
}
}

View File

@ -1,285 +0,0 @@
/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "Identity.h"
#include "Config.h"
#include "version.h"
using namespace boost::program_options;
namespace i2p {
namespace config {
options_description m_OptionsDesc;
variables_map m_Options;
void Init() {
options_description general("General options");
general.add_options()
("help", "Show this message")
("conf", value<std::string>()->default_value(""), "Path to main i2pd config file (default: try ~/.i2pd/i2pd.conf or /var/lib/i2pd/i2pd.conf)")
("tunconf", value<std::string>()->default_value(""), "Path to config with tunnels list and options (default: try ~/.i2pd/tunnels.conf or /var/lib/i2pd/tunnels.conf)")
("pidfile", value<std::string>()->default_value(""), "Path to pidfile (default: ~/i2pd/i2pd.pid or /var/lib/i2pd/i2pd.pid)")
("log", value<std::string>()->default_value(""), "Logs destination: stdout, file, syslog (stdout if not set)")
("logfile", value<std::string>()->default_value(""), "Path to logfile (stdout if not set, autodetect if daemon)")
("loglevel", value<std::string>()->default_value("info"), "Set the minimal level of log messages (debug, info, warn, error)")
("family", value<std::string>()->default_value(""), "Specify a family, router belongs to")
("datadir", value<std::string>()->default_value(""), "Path to storage of i2pd data (RI, keys, peer profiles, ...)")
("host", value<std::string>()->default_value("0.0.0.0"), "External IP")
("ifname", value<std::string>()->default_value(""), "Network interface to bind to")
("ifname4", value<std::string>()->default_value(""), "Network interface to bind to for ipv4")
("ifname6", value<std::string>()->default_value(""), "Network interface to bind to for ipv6")
("nat", value<bool>()->zero_tokens()->default_value(true), "Should we assume we are behind NAT?")
("port", value<uint16_t>()->default_value(0), "Port to listen for incoming connections (default: auto)")
("ipv4", value<bool>()->zero_tokens()->default_value(true), "Enable communication through ipv4")
("ipv6", value<bool>()->zero_tokens()->default_value(false), "Enable communication through ipv6")
("netid", value<int>()->default_value(I2PD_NET_ID), "Specify NetID. Main I2P is 2")
("daemon", value<bool>()->zero_tokens()->default_value(false), "Router will go to background after start")
("service", value<bool>()->zero_tokens()->default_value(false), "Router will use system folders like '/var/lib/i2pd'")
("notransit", value<bool>()->zero_tokens()->default_value(false), "Router will not accept transit tunnels at startup")
("floodfill", value<bool>()->zero_tokens()->default_value(false), "Router will be floodfill")
("bandwidth", value<std::string>()->default_value(""), "Bandwidth limit: integer in kbps or letters: L (32), O (256), P (2048), X (>9000)")
("ntcp", value<bool>()->zero_tokens()->default_value(true), "Enable NTCP transport")
("ssu", value<bool>()->zero_tokens()->default_value(true), "Enable SSU transport")
#ifdef _WIN32
("svcctl", value<std::string>()->default_value(""), "Windows service management ('install' or 'remove')")
("insomnia", value<bool>()->zero_tokens()->default_value(false), "Prevent system from sleeping")
("close", value<std::string>()->default_value("ask"), "Action on close: minimize, exit, ask") // TODO: add custom validator or something
#endif
;
options_description limits("Limits options");
limits.add_options()
("limits.coresize", value<uint32_t>()->default_value(0), "Maximum size of corefile in Kb (0 - use system limit)")
("limits.openfiles", value<uint16_t>()->default_value(0), "Maximum number of open files (0 - use system default)")
("limits.transittunnels", value<uint16_t>()->default_value(2500), "Maximum active transit sessions (default:2500)")
;
options_description httpserver("HTTP Server options");
httpserver.add_options()
("http.enabled", value<bool>()->default_value(true), "Enable or disable webconsole")
("http.address", value<std::string>()->default_value("127.0.0.1"), "Webconsole listen address")
("http.port", value<uint16_t>()->default_value(7070), "Webconsole listen port")
("http.auth", value<bool>()->default_value(false), "Enable Basic HTTP auth for webconsole")
("http.user", value<std::string>()->default_value("i2pd"), "Username for basic auth")
("http.pass", value<std::string>()->default_value(""), "Password for basic auth (default: random, see logs)")
;
options_description httpproxy("HTTP Proxy options");
httpproxy.add_options()
("httpproxy.enabled", value<bool>()->default_value(true), "Enable or disable HTTP Proxy")
("httpproxy.address", value<std::string>()->default_value("127.0.0.1"), "HTTP Proxy listen address")
("httpproxy.port", value<uint16_t>()->default_value(4444), "HTTP Proxy listen port")
("httpproxy.keys", value<std::string>()->default_value(""), "File to persist HTTP Proxy keys")
("httpproxy.signaturetype", value<i2p::data::SigningKeyType>()->default_value(i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519), "Signature type for new keys. 7 (EdDSA) by default")
("httpproxy.inbound.length", value<std::string>()->default_value("3"), "HTTP proxy inbound tunnel length")
("httpproxy.outbound.length", value<std::string>()->default_value("3"), "HTTP proxy outbound tunnel length")
("httpproxy.inbound.quantity", value<std::string>()->default_value("5"), "HTTP proxy inbound tunnels quantity")
("httpproxy.outbound.quantity", value<std::string>()->default_value("5"), "HTTP proxy outbound tunnels quantity")
("httpproxy.latency.min", value<std::string>()->default_value("0"), "HTTP proxy min latency for tunnels")
("httpproxy.latency.max", value<std::string>()->default_value("0"), "HTTP proxy max latency for tunnels")
("httpproxy.outproxy", value<std::string>()->default_value(""), "HTTP proxy upstream out proxy url")
;
options_description socksproxy("SOCKS Proxy options");
socksproxy.add_options()
("socksproxy.enabled", value<bool>()->default_value(true), "Enable or disable SOCKS Proxy")
("socksproxy.address", value<std::string>()->default_value("127.0.0.1"), "SOCKS Proxy listen address")
("socksproxy.port", value<uint16_t>()->default_value(4447), "SOCKS Proxy listen port")
("socksproxy.keys", value<std::string>()->default_value(""), "File to persist SOCKS Proxy keys")
("socksproxy.signaturetype", value<i2p::data::SigningKeyType>()->default_value(i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519), "Signature type for new keys. 7 (EdDSA) by default")
("socksproxy.inbound.length", value<std::string>()->default_value("3"), "SOCKS proxy inbound tunnel length")
("socksproxy.outbound.length", value<std::string>()->default_value("3"), "SOCKS proxy outbound tunnel length")
("socksproxy.inbound.quantity", value<std::string>()->default_value("5"), "SOCKS proxy inbound tunnels quantity")
("socksproxy.outbound.quantity", value<std::string>()->default_value("5"), "SOCKS proxy outbound tunnels quantity")
("socksproxy.latency.min", value<std::string>()->default_value("0"), "SOCKS proxy min latency for tunnels")
("socksproxy.latency.max", value<std::string>()->default_value("0"), "SOCKS proxy max latency for tunnels")
("socksproxy.outproxy", value<std::string>()->default_value("127.0.0.1"), "Upstream outproxy address for SOCKS Proxy")
("socksproxy.outproxyport", value<uint16_t>()->default_value(9050), "Upstream outproxy port for SOCKS Proxy")
;
options_description sam("SAM bridge options");
sam.add_options()
("sam.enabled", value<bool>()->default_value(false), "Enable or disable SAM Application bridge")
("sam.address", value<std::string>()->default_value("127.0.0.1"), "SAM listen address")
("sam.port", value<uint16_t>()->default_value(7656), "SAM listen port")
;
options_description bob("BOB options");
bob.add_options()
("bob.enabled", value<bool>()->default_value(false), "Enable or disable BOB command channel")
("bob.address", value<std::string>()->default_value("127.0.0.1"), "BOB listen address")
("bob.port", value<uint16_t>()->default_value(2827), "BOB listen port")
;
options_description i2cp("I2CP options");
i2cp.add_options()
("i2cp.enabled", value<bool>()->default_value(false), "Enable or disable I2CP")
("i2cp.address", value<std::string>()->default_value("127.0.0.1"), "I2CP listen address")
("i2cp.port", value<uint16_t>()->default_value(7654), "I2CP listen port")
;
options_description i2pcontrol("I2PControl options");
i2pcontrol.add_options()
("i2pcontrol.enabled", value<bool>()->default_value(false), "Enable or disable I2P Control Protocol")
("i2pcontrol.address", value<std::string>()->default_value("127.0.0.1"), "I2PCP listen address")
("i2pcontrol.port", value<uint16_t>()->default_value(7650), "I2PCP listen port")
("i2pcontrol.password", value<std::string>()->default_value("itoopie"), "I2PCP access password")
("i2pcontrol.cert", value<std::string>()->default_value("i2pcontrol.crt.pem"), "I2PCP connection cerificate")
("i2pcontrol.key", value<std::string>()->default_value("i2pcontrol.key.pem"), "I2PCP connection cerificate key")
;
bool upnp_default = false;
#if (defined(USE_UPNP) && (defined(WIN32_APP) || defined(ANDROID)))
upnp_default = true; // enable UPNP for windows GUI and android by default
#endif
options_description upnp("UPnP options");
upnp.add_options()
("upnp.enabled", value<bool>()->default_value(upnp_default), "Enable or disable UPnP: automatic port forwarding")
("upnp.name", value<std::string>()->default_value("I2Pd"), "Name i2pd appears in UPnP forwardings list")
;
options_description precomputation("Precomputation options");
precomputation.add_options()
("precomputation.elgamal",
#if defined(__x86_64__)
value<bool>()->default_value(false),
#else
value<bool>()->default_value(true),
#endif
"Enable or disable elgamal precomputation table")
;
options_description reseed("Reseed options");
reseed.add_options()
("reseed.verify", value<bool>()->default_value(false), "Verify .su3 signature")
("reseed.threshold", value<uint16_t>()->default_value(25), "Minimum number of known routers before requesting reseed")
("reseed.floodfill", value<std::string>()->default_value(""), "Path to router info of floodfill to reseed from")
("reseed.file", value<std::string>()->default_value(""), "Path to local .su3 file or HTTPS URL to reseed from")
("reseed.zipfile", value<std::string>()->default_value(""), "Path to local .zip file to reseed from")
("reseed.urls", value<std::string>()->default_value(
"https://reseed.i2p-projekt.de/,"
"https://i2p.mooo.com/netDb/,"
"https://netdb.i2p2.no/,"
// "https://us.reseed.i2p2.no:444/," // mamoth's shit
// "https://uk.reseed.i2p2.no:444/," // mamoth's shit
"https://i2p-0.manas.ca:8443/,"
"https://reseed.i2p.vzaws.com:8443/,"
"https://download.xxlspeed.com/,"
"https://reseed-ru.lngserv.ru/,"
"https://reseed.atomike.ninja/,"
"https://reseed.memcpy.io/,"
"https://reseed.onion.im/,"
"https://itoopie.atomike.ninja/"
), "Reseed URLs, separated by comma")
;
options_description addressbook("AddressBook options");
addressbook.add_options()
("addressbook.defaulturl", value<std::string>()->default_value(
"http://joajgazyztfssty4w2on5oaqksz6tqoxbduy553y34mf4byv6gpq.b32.i2p/export/alive-hosts.txt"
), "AddressBook subscription URL for initial setup")
("addressbook.subscriptions", value<std::string>()->default_value(""),
"AddressBook subscriptions URLs, separated by comma");
options_description trust("Trust options");
trust.add_options()
("trust.enabled", value<bool>()->default_value(false), "Enable explicit trust options")
("trust.family", value<std::string>()->default_value(""), "Router Familiy to trust for first hops")
("trust.routers", value<std::string>()->default_value(""), "Only Connect to these routers")
("trust.hidden", value<bool>()->default_value(false), "Should we hide our router from other routers?");
options_description websocket("Websocket Options");
websocket.add_options()
("websockets.enabled", value<bool>()->default_value(false), "enable websocket server")
("websockets.address", value<std::string>()->default_value("127.0.0.1"), "address to bind websocket server on")
("websockets.port", value<uint16_t>()->default_value(7666), "port to bind websocket server on");
m_OptionsDesc
.add(general)
.add(limits)
.add(httpserver)
.add(httpproxy)
.add(socksproxy)
.add(sam)
.add(bob)
.add(i2cp)
.add(i2pcontrol)
.add(upnp)
.add(precomputation)
.add(reseed)
.add(addressbook)
.add(trust)
.add(websocket)
;
}
void ParseCmdline(int argc, char* argv[]) {
try {
auto style = boost::program_options::command_line_style::unix_style
| boost::program_options::command_line_style::allow_long_disguise;
style &= ~ boost::program_options::command_line_style::allow_guessing;
store(parse_command_line(argc, argv, m_OptionsDesc, style), m_Options);
} catch (boost::program_options::error& e) {
std::cerr << "args: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
if (m_Options.count("help") || m_Options.count("h")) {
std::cout << "i2pd version " << I2PD_VERSION << " (" << I2P_VERSION << ")" << std::endl;
std::cout << m_OptionsDesc;
exit(EXIT_SUCCESS);
}
}
void ParseConfig(const std::string& path) {
if (path == "") return;
std::ifstream config(path, std::ios::in);
if (!config.is_open())
{
std::cerr << "missing/unreadable config file: " << path << std::endl;
exit(EXIT_FAILURE);
}
try
{
store(boost::program_options::parse_config_file(config, m_OptionsDesc), m_Options);
}
catch (boost::program_options::error& e)
{
std::cerr << e.what() << std::endl;
exit(EXIT_FAILURE);
};
}
void Finalize() {
notify(m_Options);
}
bool IsDefault(const char *name) {
if (!m_Options.count(name))
throw "try to check non-existent option";
if (m_Options[name].defaulted())
return true;
return false;
}
} // namespace config
} // namespace i2p

113
Config.h
View File

@ -1,113 +0,0 @@
#ifndef CONFIG_H
#define CONFIG_H
#include <string>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
/**
* Functions to parse and store i2pd parameters
*
* General usage flow:
* Init() -- early as possible
* ParseCmdline() -- somewhere close to main()
* ParseConfig() -- after detecting path to config
* Finalize() -- right after all Parse*() functions called
* GetOption() -- may be called after Finalize()
*/
namespace i2p {
namespace config {
extern boost::program_options::variables_map m_Options;
/**
* @brief Initialize list of acceptable parameters
*
* Should be called before any Parse* functions.
*/
void Init();
/**
* @brief Parse cmdline parameters, and show help if requested
* @param argc Cmdline arguments count, should be passed from main().
* @param argv Cmdline parameters array, should be passed from main()
*
* If --help is given in parameters, shows it's list with description
* terminates the program with exitcode 0.
*
* In case of parameter misuse boost throws an exception.
* We internally handle type boost::program_options::unknown_option,
* and then terminate program with exitcode 1.
*
* Other exceptions will be passed to higher level.
*/
void ParseCmdline(int argc, char* argv[]);
/**
* @brief Load and parse given config file
* @param path Path to config file
*
* If error occured when opening file path is points to,
* we show the error message and terminate program.
*
* In case of parameter misuse boost throws an exception.
* We internally handle type boost::program_options::unknown_option,
* and then terminate program with exitcode 1.
*
* Other exceptions will be passed to higher level.
*/
void ParseConfig(const std::string& path);
/**
* @brief Used to combine options from cmdline, config and default values
*/
void Finalize();
/* @brief Accessor to parameters by name
* @param name Name of the requested parameter
* @param value Variable where to store option
* @return this function returns false if parameter not found
*
* Example: uint16_t port; GetOption("sam.port", port);
*/
template<typename T>
bool GetOption(const char *name, T& value) {
if (!m_Options.count(name))
return false;
value = m_Options[name].as<T>();
return true;
}
template<typename T>
bool GetOption(const std::string& name, T& value)
{
return GetOption (name.c_str (), value);
}
/**
* @brief Set value of given parameter
* @param name Name of settable parameter
* @param value New parameter value
* @return true if value set up successful, false otherwise
*
* Example: uint16_t port = 2827; SetOption("bob.port", port);
*/
template<typename T>
bool SetOption(const char *name, const T& value) {
if (!m_Options.count(name))
return false;
m_Options.at(name).value() = value;
notify(m_Options);
return true;
}
/**
* @brief Check is value explicitly given or default
* @param name Name of checked parameter
* @return true if value set to default, false othervise
*/
bool IsDefault(const char *name);
}
}
#endif // CONFIG_H

View File

@ -1,841 +0,0 @@
#include <string.h>
#include <string>
#include <vector>
#include <mutex>
#include <memory>
#include <openssl/dh.h>
#include <openssl/md5.h>
#include <openssl/crypto.h>
#include "TunnelBase.h"
#include <openssl/ssl.h>
#include "Log.h"
#include "Crypto.h"
namespace i2p
{
namespace crypto
{
const uint8_t elgp_[256]=
{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
const int elgg_ = 2;
const uint8_t dsap_[128]=
{
0x9c, 0x05, 0xb2, 0xaa, 0x96, 0x0d, 0x9b, 0x97, 0xb8, 0x93, 0x19, 0x63, 0xc9, 0xcc, 0x9e, 0x8c,
0x30, 0x26, 0xe9, 0xb8, 0xed, 0x92, 0xfa, 0xd0, 0xa6, 0x9c, 0xc8, 0x86, 0xd5, 0xbf, 0x80, 0x15,
0xfc, 0xad, 0xae, 0x31, 0xa0, 0xad, 0x18, 0xfa, 0xb3, 0xf0, 0x1b, 0x00, 0xa3, 0x58, 0xde, 0x23,
0x76, 0x55, 0xc4, 0x96, 0x4a, 0xfa, 0xa2, 0xb3, 0x37, 0xe9, 0x6a, 0xd3, 0x16, 0xb9, 0xfb, 0x1c,
0xc5, 0x64, 0xb5, 0xae, 0xc5, 0xb6, 0x9a, 0x9f, 0xf6, 0xc3, 0xe4, 0x54, 0x87, 0x07, 0xfe, 0xf8,
0x50, 0x3d, 0x91, 0xdd, 0x86, 0x02, 0xe8, 0x67, 0xe6, 0xd3, 0x5d, 0x22, 0x35, 0xc1, 0x86, 0x9c,
0xe2, 0x47, 0x9c, 0x3b, 0x9d, 0x54, 0x01, 0xde, 0x04, 0xe0, 0x72, 0x7f, 0xb3, 0x3d, 0x65, 0x11,
0x28, 0x5d, 0x4c, 0xf2, 0x95, 0x38, 0xd9, 0xe3, 0xb6, 0x05, 0x1f, 0x5b, 0x22, 0xcc, 0x1c, 0x93
};
const uint8_t dsaq_[20]=
{
0xa5, 0xdf, 0xc2, 0x8f, 0xef, 0x4c, 0xa1, 0xe2, 0x86, 0x74, 0x4c, 0xd8, 0xee, 0xd9, 0xd2, 0x9d,
0x68, 0x40, 0x46, 0xb7
};
const uint8_t dsag_[128]=
{
0x0c, 0x1f, 0x4d, 0x27, 0xd4, 0x00, 0x93, 0xb4, 0x29, 0xe9, 0x62, 0xd7, 0x22, 0x38, 0x24, 0xe0,
0xbb, 0xc4, 0x7e, 0x7c, 0x83, 0x2a, 0x39, 0x23, 0x6f, 0xc6, 0x83, 0xaf, 0x84, 0x88, 0x95, 0x81,
0x07, 0x5f, 0xf9, 0x08, 0x2e, 0xd3, 0x23, 0x53, 0xd4, 0x37, 0x4d, 0x73, 0x01, 0xcd, 0xa1, 0xd2,
0x3c, 0x43, 0x1f, 0x46, 0x98, 0x59, 0x9d, 0xda, 0x02, 0x45, 0x18, 0x24, 0xff, 0x36, 0x97, 0x52,
0x59, 0x36, 0x47, 0xcc, 0x3d, 0xdc, 0x19, 0x7d, 0xe9, 0x85, 0xe4, 0x3d, 0x13, 0x6c, 0xdc, 0xfc,
0x6b, 0xd5, 0x40, 0x9c, 0xd2, 0xf4, 0x50, 0x82, 0x11, 0x42, 0xa5, 0xe6, 0xf8, 0xeb, 0x1c, 0x3a,
0xb5, 0xd0, 0x48, 0x4b, 0x81, 0x29, 0xfc, 0xf1, 0x7b, 0xce, 0x4f, 0x7f, 0x33, 0x32, 0x1c, 0x3c,
0xb3, 0xdb, 0xb1, 0x4a, 0x90, 0x5e, 0x7b, 0x2b, 0x3e, 0x93, 0xbe, 0x47, 0x08, 0xcb, 0xcc, 0x82
};
const int rsae_ = 65537;
struct CryptoConstants
{
// DH/ElGamal
BIGNUM * elgp;
BIGNUM * elgg;
// DSA
BIGNUM * dsap;
BIGNUM * dsaq;
BIGNUM * dsag;
// RSA
BIGNUM * rsae;
CryptoConstants (const uint8_t * elgp_, int elgg_, const uint8_t * dsap_,
const uint8_t * dsaq_, const uint8_t * dsag_, int rsae_)
{
elgp = BN_new ();
BN_bin2bn (elgp_, 256, elgp);
elgg = BN_new ();
BN_set_word (elgg, elgg_);
dsap = BN_new ();
BN_bin2bn (dsap_, 128, dsap);
dsaq = BN_new ();
BN_bin2bn (dsaq_, 20, dsaq);
dsag = BN_new ();
BN_bin2bn (dsag_, 128, dsag);
rsae = BN_new ();
BN_set_word (rsae, rsae_);
}
~CryptoConstants ()
{
BN_free (elgp); BN_free (elgg); BN_free (dsap); BN_free (dsaq); BN_free (dsag); BN_free (rsae);
}
};
static const CryptoConstants& GetCryptoConstants ()
{
static CryptoConstants cryptoConstants (elgp_, elgg_, dsap_, dsaq_, dsag_, rsae_);
return cryptoConstants;
}
bool bn2buf (const BIGNUM * bn, uint8_t * buf, size_t len)
{
int offset = len - BN_num_bytes (bn);
if (offset < 0) return false;
BN_bn2bin (bn, buf + offset);
memset (buf, 0, offset);
return true;
}
// RSA
#define rsae GetCryptoConstants ().rsae
const BIGNUM * GetRSAE ()
{
return rsae;
}
// DSA
#define dsap GetCryptoConstants ().dsap
#define dsaq GetCryptoConstants ().dsaq
#define dsag GetCryptoConstants ().dsag
DSA * CreateDSA ()
{
DSA * dsa = DSA_new ();
DSA_set0_pqg (dsa, BN_dup (dsap), BN_dup (dsaq), BN_dup (dsag));
DSA_set0_key (dsa, NULL, NULL);
return dsa;
}
// DH/ElGamal
const int ELGAMAL_SHORT_EXPONENT_NUM_BITS = 226;
const int ELGAMAL_SHORT_EXPONENT_NUM_BYTES = ELGAMAL_SHORT_EXPONENT_NUM_BITS/8+1;
const int ELGAMAL_FULL_EXPONENT_NUM_BITS = 2048;
const int ELGAMAL_FULL_EXPONENT_NUM_BYTES = ELGAMAL_FULL_EXPONENT_NUM_BITS/8;
#define elgp GetCryptoConstants ().elgp
#define elgg GetCryptoConstants ().elgg
static BN_MONT_CTX * g_MontCtx = nullptr;
static void PrecalculateElggTable (BIGNUM * table[][255], int len) // table is len's array of array of 255 bignums
{
if (len <= 0) return;
BN_CTX * ctx = BN_CTX_new ();
g_MontCtx = BN_MONT_CTX_new ();
BN_MONT_CTX_set (g_MontCtx, elgp, ctx);
auto montCtx = BN_MONT_CTX_new ();
BN_MONT_CTX_copy (montCtx, g_MontCtx);
for (int i = 0; i < len; i++)
{
table[i][0] = BN_new ();
if (!i)
BN_to_montgomery (table[0][0], elgg, montCtx, ctx);
else
BN_mod_mul_montgomery (table[i][0], table[i-1][254], table[i-1][0], montCtx, ctx);
for (int j = 1; j < 255; j++)
{
table[i][j] = BN_new ();
BN_mod_mul_montgomery (table[i][j], table[i][j-1], table[i][0], montCtx, ctx);
}
}
BN_MONT_CTX_free (montCtx);
BN_CTX_free (ctx);
}
static void DestroyElggTable (BIGNUM * table[][255], int len)
{
for (int i = 0; i < len; i++)
for (int j = 0; j < 255; j++)
{
BN_free (table[i][j]);
table[i][j] = nullptr;
}
BN_MONT_CTX_free (g_MontCtx);
}
static BIGNUM * ElggPow (const uint8_t * exp, int len, BIGNUM * table[][255], BN_CTX * ctx)
// exp is in Big Endian
{
if (len <= 0) return nullptr;
auto montCtx = BN_MONT_CTX_new ();
BN_MONT_CTX_copy (montCtx, g_MontCtx);
BIGNUM * res = nullptr;
for (int i = 0; i < len; i++)
{
if (res)
{
if (exp[i])
BN_mod_mul_montgomery (res, res, table[len-1-i][exp[i]-1], montCtx, ctx);
}
else if (exp[i])
res = BN_dup (table[len-i-1][exp[i]-1]);
}
if (res)
BN_from_montgomery (res, res, montCtx, ctx);
BN_MONT_CTX_free (montCtx);
return res;
}
static BIGNUM * ElggPow (const BIGNUM * exp, BIGNUM * table[][255], BN_CTX * ctx)
{
auto len = BN_num_bytes (exp);
uint8_t * buf = new uint8_t[len];
BN_bn2bin (exp, buf);
auto ret = ElggPow (buf, len, table, ctx);
delete[] buf;
return ret;
}
static BIGNUM * (* g_ElggTable)[255] = nullptr;
// DH
DHKeys::DHKeys ()
{
m_DH = DH_new ();
DH_set0_pqg (m_DH, BN_dup (elgp), NULL, BN_dup (elgg));
DH_set0_key (m_DH, NULL, NULL);
}
DHKeys::~DHKeys ()
{
DH_free (m_DH);
}
void DHKeys::GenerateKeys ()
{
BIGNUM * priv_key = NULL, * pub_key = NULL;
#if !defined(__x86_64__) // use short exponent for non x64
priv_key = BN_new ();
BN_rand (priv_key, ELGAMAL_SHORT_EXPONENT_NUM_BITS, 0, 1);
#endif
if (g_ElggTable)
{
#if defined(__x86_64__)
priv_key = BN_new ();
BN_rand (priv_key, ELGAMAL_FULL_EXPONENT_NUM_BITS, 0, 1);
#endif
auto ctx = BN_CTX_new ();
pub_key = ElggPow (priv_key, g_ElggTable, ctx);
DH_set0_key (m_DH, pub_key, priv_key);
BN_CTX_free (ctx);
}
else
{
DH_set0_key (m_DH, NULL, priv_key);
DH_generate_key (m_DH);
DH_get0_key (m_DH, (const BIGNUM **)&pub_key, (const BIGNUM **)&priv_key);
}
bn2buf (pub_key, m_PublicKey, 256);
}
void DHKeys::Agree (const uint8_t * pub, uint8_t * shared)
{
BIGNUM * pk = BN_bin2bn (pub, 256, NULL);
DH_compute_key (shared, pk, m_DH);
BN_free (pk);
}
// ElGamal
void ElGamalEncrypt (const uint8_t * key, const uint8_t * data, uint8_t * encrypted, bool zeroPadding)
{
BN_CTX * ctx = BN_CTX_new ();
// select random k
BIGNUM * k = BN_new ();
#if defined(__x86_64__)
BN_rand (k, ELGAMAL_FULL_EXPONENT_NUM_BITS, -1, 1); // full exponent for x64
#else
BN_rand (k, ELGAMAL_SHORT_EXPONENT_NUM_BITS, -1, 1); // short exponent of 226 bits
#endif
// calculate a
BIGNUM * a;
if (g_ElggTable)
a = ElggPow (k, g_ElggTable, ctx);
else
{
a = BN_new ();
BN_mod_exp (a, elgg, k, elgp, ctx);
}
BIGNUM * y = BN_new ();
BN_bin2bn (key, 256, y);
// calculate b1
BIGNUM * b1 = BN_new ();
BN_mod_exp (b1, y, k, elgp, ctx);
BN_free (y);
BN_free (k);
// create m
uint8_t m[255];
m[0] = 0xFF;
memcpy (m+33, data, 222);
SHA256 (m+33, 222, m+1);
// calculate b = b1*m mod p
BIGNUM * b = BN_new ();
BN_bin2bn (m, 255, b);
BN_mod_mul (b, b1, b, elgp, ctx);
BN_free (b1);
// copy a and b
if (zeroPadding)
{
encrypted[0] = 0;
bn2buf (a, encrypted + 1, 256);
encrypted[257] = 0;
bn2buf (b, encrypted + 258, 256);
}
else
{
bn2buf (a, encrypted, 256);
bn2buf (b, encrypted + 256, 256);
}
BN_free (b);
BN_free (a);
BN_CTX_free (ctx);
}
bool ElGamalDecrypt (const uint8_t * key, const uint8_t * encrypted,
uint8_t * data, bool zeroPadding)
{
BN_CTX * ctx = BN_CTX_new ();
BIGNUM * x = BN_new (), * a = BN_new (), * b = BN_new ();
BN_bin2bn (key, 256, x);
BN_sub (x, elgp, x); BN_sub_word (x, 1); // x = elgp - x- 1
BN_bin2bn (zeroPadding ? encrypted + 1 : encrypted, 256, a);
BN_bin2bn (zeroPadding ? encrypted + 258 : encrypted + 256, 256, b);
// m = b*(a^x mod p) mod p
BN_mod_exp (x, a, x, elgp, ctx);
BN_mod_mul (b, b, x, elgp, ctx);
uint8_t m[255];
bn2buf (b, m, 255);
BN_free (x); BN_free (a); BN_free (b);
BN_CTX_free (ctx);
uint8_t hash[32];
SHA256 (m + 33, 222, hash);
if (memcmp (m + 1, hash, 32))
{
LogPrint (eLogError, "ElGamal decrypt hash doesn't match");
return false;
}
memcpy (data, m + 33, 222);
return true;
}
void GenerateElGamalKeyPair (uint8_t * priv, uint8_t * pub)
{
#if defined(__x86_64__) || defined(__i386__) || defined(_MSC_VER)
RAND_bytes (priv, 256);
#else
// lower 226 bits (28 bytes and 2 bits) only. short exponent
auto numBytes = (ELGAMAL_SHORT_EXPONENT_NUM_BITS)/8 + 1; // 29
auto numZeroBytes = 256 - numBytes;
RAND_bytes (priv + numZeroBytes, numBytes);
memset (priv, 0, numZeroBytes);
priv[numZeroBytes] &= 0x03;
#endif
BN_CTX * ctx = BN_CTX_new ();
BIGNUM * p = BN_new ();
BN_bin2bn (priv, 256, p);
BN_mod_exp (p, elgg, p, elgp, ctx);
bn2buf (p, pub, 256);
BN_free (p);
BN_CTX_free (ctx);
}
// HMAC
const uint64_t IPAD = 0x3636363636363636;
const uint64_t OPAD = 0x5C5C5C5C5C5C5C5C;
#if defined(__AVX__)
static const uint64_t ipads[] = { IPAD, IPAD, IPAD, IPAD };
static const uint64_t opads[] = { OPAD, OPAD, OPAD, OPAD };
#endif
void HMACMD5Digest (uint8_t * msg, size_t len, const MACKey& key, uint8_t * digest)
// key is 32 bytes
// digest is 16 bytes
// block size is 64 bytes
{
uint64_t buf[256];
uint64_t hash[12]; // 96 bytes
#if defined(__AVX__) // for AVX
__asm__
(
"vmovups %[key], %%ymm0 \n"
"vmovups %[ipad], %%ymm1 \n"
"vmovups %%ymm1, 32(%[buf]) \n"
"vxorps %%ymm0, %%ymm1, %%ymm1 \n"
"vmovups %%ymm1, (%[buf]) \n"
"vmovups %[opad], %%ymm1 \n"
"vmovups %%ymm1, 32(%[hash]) \n"
"vxorps %%ymm0, %%ymm1, %%ymm1 \n"
"vmovups %%ymm1, (%[hash]) \n"
"vzeroall \n" // end of AVX
"movups %%xmm0, 80(%[hash]) \n" // zero last 16 bytes
:
: [key]"m"(*(const uint8_t *)key), [ipad]"m"(*ipads), [opad]"m"(*opads),
[buf]"r"(buf), [hash]"r"(hash)
: "memory", "%xmm0" // TODO: change to %ymm0 later
);
#else
// ikeypad
buf[0] = key.GetLL ()[0] ^ IPAD;
buf[1] = key.GetLL ()[1] ^ IPAD;
buf[2] = key.GetLL ()[2] ^ IPAD;
buf[3] = key.GetLL ()[3] ^ IPAD;
buf[4] = IPAD;
buf[5] = IPAD;
buf[6] = IPAD;
buf[7] = IPAD;
// okeypad
hash[0] = key.GetLL ()[0] ^ OPAD;
hash[1] = key.GetLL ()[1] ^ OPAD;
hash[2] = key.GetLL ()[2] ^ OPAD;
hash[3] = key.GetLL ()[3] ^ OPAD;
hash[4] = OPAD;
hash[5] = OPAD;
hash[6] = OPAD;
hash[7] = OPAD;
// fill last 16 bytes with zeros (first hash size assumed 32 bytes in I2P)
memset (hash + 10, 0, 16);
#endif
// concatenate with msg
memcpy (buf + 8, msg, len);
// calculate first hash
MD5((uint8_t *)buf, len + 64, (uint8_t *)(hash + 8)); // 16 bytes
// calculate digest
MD5((uint8_t *)hash, 96, digest);
}
// AES
#ifdef AESNI
#define KeyExpansion256(round0,round1) \
"pshufd $0xff, %%xmm2, %%xmm2 \n" \
"movaps %%xmm1, %%xmm4 \n" \
"pslldq $4, %%xmm4 \n" \
"pxor %%xmm4, %%xmm1 \n" \
"pslldq $4, %%xmm4 \n" \
"pxor %%xmm4, %%xmm1 \n" \
"pslldq $4, %%xmm4 \n" \
"pxor %%xmm4, %%xmm1 \n" \
"pxor %%xmm2, %%xmm1 \n" \
"movaps %%xmm1, "#round0"(%[sched]) \n" \
"aeskeygenassist $0, %%xmm1, %%xmm4 \n" \
"pshufd $0xaa, %%xmm4, %%xmm2 \n" \
"movaps %%xmm3, %%xmm4 \n" \
"pslldq $4, %%xmm4 \n" \
"pxor %%xmm4, %%xmm3 \n" \
"pslldq $4, %%xmm4 \n" \
"pxor %%xmm4, %%xmm3 \n" \
"pslldq $4, %%xmm4 \n" \
"pxor %%xmm4, %%xmm3 \n" \
"pxor %%xmm2, %%xmm3 \n" \
"movaps %%xmm3, "#round1"(%[sched]) \n"
void ECBCryptoAESNI::ExpandKey (const AESKey& key)
{
__asm__
(
"movups (%[key]), %%xmm1 \n"
"movups 16(%[key]), %%xmm3 \n"
"movaps %%xmm1, (%[sched]) \n"
"movaps %%xmm3, 16(%[sched]) \n"
"aeskeygenassist $1, %%xmm3, %%xmm2 \n"
KeyExpansion256(32,48)
"aeskeygenassist $2, %%xmm3, %%xmm2 \n"
KeyExpansion256(64,80)
"aeskeygenassist $4, %%xmm3, %%xmm2 \n"
KeyExpansion256(96,112)
"aeskeygenassist $8, %%xmm3, %%xmm2 \n"
KeyExpansion256(128,144)
"aeskeygenassist $16, %%xmm3, %%xmm2 \n"
KeyExpansion256(160,176)
"aeskeygenassist $32, %%xmm3, %%xmm2 \n"
KeyExpansion256(192,208)
"aeskeygenassist $64, %%xmm3, %%xmm2 \n"
// key expansion final
"pshufd $0xff, %%xmm2, %%xmm2 \n"
"movaps %%xmm1, %%xmm4 \n"
"pslldq $4, %%xmm4 \n"
"pxor %%xmm4, %%xmm1 \n"
"pslldq $4, %%xmm4 \n"
"pxor %%xmm4, %%xmm1 \n"
"pslldq $4, %%xmm4 \n"
"pxor %%xmm4, %%xmm1 \n"
"pxor %%xmm2, %%xmm1 \n"
"movups %%xmm1, 224(%[sched]) \n"
: // output
: [key]"r"((const uint8_t *)key), [sched]"r"(GetKeySchedule ()) // input
: "%xmm1", "%xmm2", "%xmm3", "%xmm4", "memory" // clogged
);
}
#define EncryptAES256(sched) \
"pxor (%["#sched"]), %%xmm0 \n" \
"aesenc 16(%["#sched"]), %%xmm0 \n" \
"aesenc 32(%["#sched"]), %%xmm0 \n" \
"aesenc 48(%["#sched"]), %%xmm0 \n" \
"aesenc 64(%["#sched"]), %%xmm0 \n" \
"aesenc 80(%["#sched"]), %%xmm0 \n" \
"aesenc 96(%["#sched"]), %%xmm0 \n" \
"aesenc 112(%["#sched"]), %%xmm0 \n" \
"aesenc 128(%["#sched"]), %%xmm0 \n" \
"aesenc 144(%["#sched"]), %%xmm0 \n" \
"aesenc 160(%["#sched"]), %%xmm0 \n" \
"aesenc 176(%["#sched"]), %%xmm0 \n" \
"aesenc 192(%["#sched"]), %%xmm0 \n" \
"aesenc 208(%["#sched"]), %%xmm0 \n" \
"aesenclast 224(%["#sched"]), %%xmm0 \n"
void ECBEncryptionAESNI::Encrypt (const ChipherBlock * in, ChipherBlock * out)
{
__asm__
(
"movups (%[in]), %%xmm0 \n"
EncryptAES256(sched)
"movups %%xmm0, (%[out]) \n"
: : [sched]"r"(GetKeySchedule ()), [in]"r"(in), [out]"r"(out) : "%xmm0", "memory"
);
}
#define DecryptAES256(sched) \
"pxor 224(%["#sched"]), %%xmm0 \n" \
"aesdec 208(%["#sched"]), %%xmm0 \n" \
"aesdec 192(%["#sched"]), %%xmm0 \n" \
"aesdec 176(%["#sched"]), %%xmm0 \n" \
"aesdec 160(%["#sched"]), %%xmm0 \n" \
"aesdec 144(%["#sched"]), %%xmm0 \n" \
"aesdec 128(%["#sched"]), %%xmm0 \n" \
"aesdec 112(%["#sched"]), %%xmm0 \n" \
"aesdec 96(%["#sched"]), %%xmm0 \n" \
"aesdec 80(%["#sched"]), %%xmm0 \n" \
"aesdec 64(%["#sched"]), %%xmm0 \n" \
"aesdec 48(%["#sched"]), %%xmm0 \n" \
"aesdec 32(%["#sched"]), %%xmm0 \n" \
"aesdec 16(%["#sched"]), %%xmm0 \n" \
"aesdeclast (%["#sched"]), %%xmm0 \n"
void ECBDecryptionAESNI::Decrypt (const ChipherBlock * in, ChipherBlock * out)
{
__asm__
(
"movups (%[in]), %%xmm0 \n"
DecryptAES256(sched)
"movups %%xmm0, (%[out]) \n"
: : [sched]"r"(GetKeySchedule ()), [in]"r"(in), [out]"r"(out) : "%xmm0", "memory"
);
}
#define CallAESIMC(offset) \
"movaps "#offset"(%[shed]), %%xmm0 \n" \
"aesimc %%xmm0, %%xmm0 \n" \
"movaps %%xmm0, "#offset"(%[shed]) \n"
void ECBDecryptionAESNI::SetKey (const AESKey& key)
{
ExpandKey (key); // expand encryption key first
// then invert it using aesimc
__asm__
(
CallAESIMC(16)
CallAESIMC(32)
CallAESIMC(48)
CallAESIMC(64)
CallAESIMC(80)
CallAESIMC(96)
CallAESIMC(112)
CallAESIMC(128)
CallAESIMC(144)
CallAESIMC(160)
CallAESIMC(176)
CallAESIMC(192)
CallAESIMC(208)
: : [shed]"r"(GetKeySchedule ()) : "%xmm0", "memory"
);
}
#endif
void CBCEncryption::Encrypt (int numBlocks, const ChipherBlock * in, ChipherBlock * out)
{
#ifdef AESNI
__asm__
(
"movups (%[iv]), %%xmm1 \n"
"1: \n"
"movups (%[in]), %%xmm0 \n"
"pxor %%xmm1, %%xmm0 \n"
EncryptAES256(sched)
"movaps %%xmm0, %%xmm1 \n"
"movups %%xmm0, (%[out]) \n"
"add $16, %[in] \n"
"add $16, %[out] \n"
"dec %[num] \n"
"jnz 1b \n"
"movups %%xmm1, (%[iv]) \n"
:
: [iv]"r"((uint8_t *)m_LastBlock), [sched]"r"(m_ECBEncryption.GetKeySchedule ()),
[in]"r"(in), [out]"r"(out), [num]"r"(numBlocks)
: "%xmm0", "%xmm1", "cc", "memory"
);
#else
for (int i = 0; i < numBlocks; i++)
{
*m_LastBlock.GetChipherBlock () ^= in[i];
m_ECBEncryption.Encrypt (m_LastBlock.GetChipherBlock (), m_LastBlock.GetChipherBlock ());
out[i] = *m_LastBlock.GetChipherBlock ();
}
#endif
}
void CBCEncryption::Encrypt (const uint8_t * in, std::size_t len, uint8_t * out)
{
// len/16
int numBlocks = len >> 4;
if (numBlocks > 0)
Encrypt (numBlocks, (const ChipherBlock *)in, (ChipherBlock *)out);
}
void CBCEncryption::Encrypt (const uint8_t * in, uint8_t * out)
{
#ifdef AESNI
__asm__
(
"movups (%[iv]), %%xmm1 \n"
"movups (%[in]), %%xmm0 \n"
"pxor %%xmm1, %%xmm0 \n"
EncryptAES256(sched)
"movups %%xmm0, (%[out]) \n"
"movups %%xmm0, (%[iv]) \n"
:
: [iv]"r"((uint8_t *)m_LastBlock), [sched]"r"(m_ECBEncryption.GetKeySchedule ()),
[in]"r"(in), [out]"r"(out)
: "%xmm0", "%xmm1", "memory"
);
#else
Encrypt (1, (const ChipherBlock *)in, (ChipherBlock *)out);
#endif
}
void CBCDecryption::Decrypt (int numBlocks, const ChipherBlock * in, ChipherBlock * out)
{
#ifdef AESNI
__asm__
(
"movups (%[iv]), %%xmm1 \n"
"1: \n"
"movups (%[in]), %%xmm0 \n"
"movaps %%xmm0, %%xmm2 \n"
DecryptAES256(sched)
"pxor %%xmm1, %%xmm0 \n"
"movups %%xmm0, (%[out]) \n"
"movaps %%xmm2, %%xmm1 \n"
"add $16, %[in] \n"
"add $16, %[out] \n"
"dec %[num] \n"
"jnz 1b \n"
"movups %%xmm1, (%[iv]) \n"
:
: [iv]"r"((uint8_t *)m_IV), [sched]"r"(m_ECBDecryption.GetKeySchedule ()),
[in]"r"(in), [out]"r"(out), [num]"r"(numBlocks)
: "%xmm0", "%xmm1", "%xmm2", "cc", "memory"
);
#else
for (int i = 0; i < numBlocks; i++)
{
ChipherBlock tmp = in[i];
m_ECBDecryption.Decrypt (in + i, out + i);
out[i] ^= *m_IV.GetChipherBlock ();
*m_IV.GetChipherBlock () = tmp;
}
#endif
}
void CBCDecryption::Decrypt (const uint8_t * in, std::size_t len, uint8_t * out)
{
int numBlocks = len >> 4;
if (numBlocks > 0)
Decrypt (numBlocks, (const ChipherBlock *)in, (ChipherBlock *)out);
}
void CBCDecryption::Decrypt (const uint8_t * in, uint8_t * out)
{
#ifdef AESNI
__asm__
(
"movups (%[iv]), %%xmm1 \n"
"movups (%[in]), %%xmm0 \n"
"movups %%xmm0, (%[iv]) \n"
DecryptAES256(sched)
"pxor %%xmm1, %%xmm0 \n"
"movups %%xmm0, (%[out]) \n"
:
: [iv]"r"((uint8_t *)m_IV), [sched]"r"(m_ECBDecryption.GetKeySchedule ()),
[in]"r"(in), [out]"r"(out)
: "%xmm0", "%xmm1", "memory"
);
#else
Decrypt (1, (const ChipherBlock *)in, (ChipherBlock *)out);
#endif
}
void TunnelEncryption::Encrypt (const uint8_t * in, uint8_t * out)
{
#ifdef AESNI
__asm__
(
// encrypt IV
"movups (%[in]), %%xmm0 \n"
EncryptAES256(sched_iv)
"movaps %%xmm0, %%xmm1 \n"
// double IV encryption
EncryptAES256(sched_iv)
"movups %%xmm0, (%[out]) \n"
// encrypt data, IV is xmm1
"1: \n"
"add $16, %[in] \n"
"add $16, %[out] \n"
"movups (%[in]), %%xmm0 \n"
"pxor %%xmm1, %%xmm0 \n"
EncryptAES256(sched_l)
"movaps %%xmm0, %%xmm1 \n"
"movups %%xmm0, (%[out]) \n"
"dec %[num] \n"
"jnz 1b \n"
:
: [sched_iv]"r"(m_IVEncryption.GetKeySchedule ()), [sched_l]"r"(m_LayerEncryption.GetKeySchedule ()),
[in]"r"(in), [out]"r"(out), [num]"r"(63) // 63 blocks = 1008 bytes
: "%xmm0", "%xmm1", "cc", "memory"
);
#else
m_IVEncryption.Encrypt ((const ChipherBlock *)in, (ChipherBlock *)out); // iv
m_LayerEncryption.SetIV (out);
m_LayerEncryption.Encrypt (in + 16, i2p::tunnel::TUNNEL_DATA_ENCRYPTED_SIZE, out + 16); // data
m_IVEncryption.Encrypt ((ChipherBlock *)out, (ChipherBlock *)out); // double iv
#endif
}
void TunnelDecryption::Decrypt (const uint8_t * in, uint8_t * out)
{
#ifdef AESNI
__asm__
(
// decrypt IV
"movups (%[in]), %%xmm0 \n"
DecryptAES256(sched_iv)
"movaps %%xmm0, %%xmm1 \n"
// double IV encryption
DecryptAES256(sched_iv)
"movups %%xmm0, (%[out]) \n"
// decrypt data, IV is xmm1
"1: \n"
"add $16, %[in] \n"
"add $16, %[out] \n"
"movups (%[in]), %%xmm0 \n"
"movaps %%xmm0, %%xmm2 \n"
DecryptAES256(sched_l)
"pxor %%xmm1, %%xmm0 \n"
"movups %%xmm0, (%[out]) \n"
"movaps %%xmm2, %%xmm1 \n"
"dec %[num] \n"
"jnz 1b \n"
:
: [sched_iv]"r"(m_IVDecryption.GetKeySchedule ()), [sched_l]"r"(m_LayerDecryption.GetKeySchedule ()),
[in]"r"(in), [out]"r"(out), [num]"r"(63) // 63 blocks = 1008 bytes
: "%xmm0", "%xmm1", "%xmm2", "cc", "memory"
);
#else
m_IVDecryption.Decrypt ((const ChipherBlock *)in, (ChipherBlock *)out); // iv
m_LayerDecryption.SetIV (out);
m_LayerDecryption.Decrypt (in + 16, i2p::tunnel::TUNNEL_DATA_ENCRYPTED_SIZE, out + 16); // data
m_IVDecryption.Decrypt ((ChipherBlock *)out, (ChipherBlock *)out); // double iv
#endif
}
/* std::vector <std::unique_ptr<std::mutex> > m_OpenSSLMutexes;
static void OpensslLockingCallback(int mode, int type, const char * file, int line)
{
if (type > 0 && (size_t)type < m_OpenSSLMutexes.size ())
{
if (mode & CRYPTO_LOCK)
m_OpenSSLMutexes[type]->lock ();
else
m_OpenSSLMutexes[type]->unlock ();
}
}*/
void InitCrypto (bool precomputation)
{
SSL_library_init ();
/* auto numLocks = CRYPTO_num_locks();
for (int i = 0; i < numLocks; i++)
m_OpenSSLMutexes.emplace_back (new std::mutex);
CRYPTO_set_locking_callback (OpensslLockingCallback);*/
if (precomputation)
{
#if defined(__x86_64__)
g_ElggTable = new BIGNUM * [ELGAMAL_FULL_EXPONENT_NUM_BYTES][255];
PrecalculateElggTable (g_ElggTable, ELGAMAL_FULL_EXPONENT_NUM_BYTES);
#else
g_ElggTable = new BIGNUM * [ELGAMAL_SHORT_EXPONENT_NUM_BYTES][255];
PrecalculateElggTable (g_ElggTable, ELGAMAL_SHORT_EXPONENT_NUM_BYTES);
#endif
}
}
void TerminateCrypto ()
{
if (g_ElggTable)
{
DestroyElggTable (g_ElggTable,
#if defined(__x86_64__)
ELGAMAL_FULL_EXPONENT_NUM_BYTES
#else
ELGAMAL_SHORT_EXPONENT_NUM_BYTES
#endif
);
delete[] g_ElggTable; g_ElggTable = nullptr;
}
/* CRYPTO_set_locking_callback (nullptr);
m_OpenSSLMutexes.clear ();*/
}
}
}

334
Crypto.h
View File

@ -1,334 +0,0 @@
#ifndef CRYPTO_H__
#define CRYPTO_H__
#include <inttypes.h>
#include <string>
#include <openssl/bn.h>
#include <openssl/dh.h>
#include <openssl/aes.h>
#include <openssl/dsa.h>
#include <openssl/ecdsa.h>
#include <openssl/rsa.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include "Base.h"
#include "Tag.h"
namespace i2p
{
namespace crypto
{
bool bn2buf (const BIGNUM * bn, uint8_t * buf, size_t len);
// DSA
DSA * CreateDSA ();
// RSA
const BIGNUM * GetRSAE ();
// DH
class DHKeys
{
public:
DHKeys ();
~DHKeys ();
void GenerateKeys ();
const uint8_t * GetPublicKey () const { return m_PublicKey; };
void Agree (const uint8_t * pub, uint8_t * shared);
private:
DH * m_DH;
uint8_t m_PublicKey[256];
};
// ElGamal
void ElGamalEncrypt (const uint8_t * key, const uint8_t * data, uint8_t * encrypted, bool zeroPadding = false);
bool ElGamalDecrypt (const uint8_t * key, const uint8_t * encrypted, uint8_t * data, bool zeroPadding = false);
void GenerateElGamalKeyPair (uint8_t * priv, uint8_t * pub);
// HMAC
typedef i2p::data::Tag<32> MACKey;
void HMACMD5Digest (uint8_t * msg, size_t len, const MACKey& key, uint8_t * digest);
// AES
struct ChipherBlock
{
uint8_t buf[16];
void operator^=(const ChipherBlock& other) // XOR
{
#if defined(__AVX__) // AVX
__asm__
(
"vmovups (%[buf]), %%xmm0 \n"
"vmovups (%[other]), %%xmm1 \n"
"vxorps %%xmm0, %%xmm1, %%xmm0 \n"
"vmovups %%xmm0, (%[buf]) \n"
:
: [buf]"r"(buf), [other]"r"(other.buf)
: "%xmm0", "%xmm1", "memory"
);
#elif defined(__SSE__) // SSE
__asm__
(
"movups (%[buf]), %%xmm0 \n"
"movups (%[other]), %%xmm1 \n"
"pxor %%xmm1, %%xmm0 \n"
"movups %%xmm0, (%[buf]) \n"
:
: [buf]"r"(buf), [other]"r"(other.buf)
: "%xmm0", "%xmm1", "memory"
);
#else
// TODO: implement it better
for (int i = 0; i < 16; i++)
buf[i] ^= other.buf[i];
#endif
}
};
typedef i2p::data::Tag<32> AESKey;
template<size_t sz>
class AESAlignedBuffer // 16 bytes alignment
{
public:
AESAlignedBuffer ()
{
m_Buf = m_UnalignedBuffer;
uint8_t rem = ((size_t)m_Buf) & 0x0f;
if (rem)
m_Buf += (16 - rem);
}
operator uint8_t * () { return m_Buf; };
operator const uint8_t * () const { return m_Buf; };
ChipherBlock * GetChipherBlock () { return (ChipherBlock *)m_Buf; };
const ChipherBlock * GetChipherBlock () const { return (const ChipherBlock *)m_Buf; };
private:
uint8_t m_UnalignedBuffer[sz + 15]; // up to 15 bytes alignment
uint8_t * m_Buf;
};
#ifdef AESNI
class ECBCryptoAESNI
{
public:
uint8_t * GetKeySchedule () { return m_KeySchedule; };
protected:
void ExpandKey (const AESKey& key);
private:
AESAlignedBuffer<240> m_KeySchedule; // 14 rounds for AES-256, 240 bytes
};
class ECBEncryptionAESNI: public ECBCryptoAESNI
{
public:
void SetKey (const AESKey& key) { ExpandKey (key); };
void Encrypt (const ChipherBlock * in, ChipherBlock * out);
};
class ECBDecryptionAESNI: public ECBCryptoAESNI
{
public:
void SetKey (const AESKey& key);
void Decrypt (const ChipherBlock * in, ChipherBlock * out);
};
typedef ECBEncryptionAESNI ECBEncryption;
typedef ECBDecryptionAESNI ECBDecryption;
#else // use openssl
class ECBEncryption
{
public:
void SetKey (const AESKey& key)
{
AES_set_encrypt_key (key, 256, &m_Key);
}
void Encrypt (const ChipherBlock * in, ChipherBlock * out)
{
AES_encrypt (in->buf, out->buf, &m_Key);
}
private:
AES_KEY m_Key;
};
class ECBDecryption
{
public:
void SetKey (const AESKey& key)
{
AES_set_decrypt_key (key, 256, &m_Key);
}
void Decrypt (const ChipherBlock * in, ChipherBlock * out)
{
AES_decrypt (in->buf, out->buf, &m_Key);
}
private:
AES_KEY m_Key;
};
#endif
class CBCEncryption
{
public:
CBCEncryption () { memset ((uint8_t *)m_LastBlock, 0, 16); };
void SetKey (const AESKey& key) { m_ECBEncryption.SetKey (key); }; // 32 bytes
void SetIV (const uint8_t * iv) { memcpy ((uint8_t *)m_LastBlock, iv, 16); }; // 16 bytes
void Encrypt (int numBlocks, const ChipherBlock * in, ChipherBlock * out);
void Encrypt (const uint8_t * in, std::size_t len, uint8_t * out);
void Encrypt (const uint8_t * in, uint8_t * out); // one block
private:
AESAlignedBuffer<16> m_LastBlock;
ECBEncryption m_ECBEncryption;
};
class CBCDecryption
{
public:
CBCDecryption () { memset ((uint8_t *)m_IV, 0, 16); };
void SetKey (const AESKey& key) { m_ECBDecryption.SetKey (key); }; // 32 bytes
void SetIV (const uint8_t * iv) { memcpy ((uint8_t *)m_IV, iv, 16); }; // 16 bytes
void Decrypt (int numBlocks, const ChipherBlock * in, ChipherBlock * out);
void Decrypt (const uint8_t * in, std::size_t len, uint8_t * out);
void Decrypt (const uint8_t * in, uint8_t * out); // one block
private:
AESAlignedBuffer<16> m_IV;
ECBDecryption m_ECBDecryption;
};
class TunnelEncryption // with double IV encryption
{
public:
void SetKeys (const AESKey& layerKey, const AESKey& ivKey)
{
m_LayerEncryption.SetKey (layerKey);
m_IVEncryption.SetKey (ivKey);
}
void Encrypt (const uint8_t * in, uint8_t * out); // 1024 bytes (16 IV + 1008 data)
private:
ECBEncryption m_IVEncryption;
#ifdef AESNI
ECBEncryption m_LayerEncryption;
#else
CBCEncryption m_LayerEncryption;
#endif
};
class TunnelDecryption // with double IV encryption
{
public:
void SetKeys (const AESKey& layerKey, const AESKey& ivKey)
{
m_LayerDecryption.SetKey (layerKey);
m_IVDecryption.SetKey (ivKey);
}
void Decrypt (const uint8_t * in, uint8_t * out); // 1024 bytes (16 IV + 1008 data)
private:
ECBDecryption m_IVDecryption;
#ifdef AESNI
ECBDecryption m_LayerDecryption;
#else
CBCDecryption m_LayerDecryption;
#endif
};
void InitCrypto (bool precomputation);
void TerminateCrypto ();
}
}
// take care about openssl version
#include <openssl/opensslv.h>
#if (OPENSSL_VERSION_NUMBER < 0x010100000) || defined(LIBRESSL_VERSION_NUMBER) // 1.1.0 or LibreSSL
// define getters and setters introduced in 1.1.0
inline int DSA_set0_pqg(DSA *d, BIGNUM *p, BIGNUM *q, BIGNUM *g)
{ d->p = p; d->q = q; d->g = g; return 1; }
inline int DSA_set0_key(DSA *d, BIGNUM *pub_key, BIGNUM *priv_key)
{ d->pub_key = pub_key; d->priv_key = priv_key; return 1; }
inline void DSA_get0_key(const DSA *d, const BIGNUM **pub_key, const BIGNUM **priv_key)
{ *pub_key = d->pub_key; *priv_key = d->priv_key; }
inline int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s)
{ sig->r = r; sig->s = s; return 1; }
inline void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps)
{ *pr = sig->r; *ps = sig->s; }
inline int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s)
{
if (sig->r) BN_free (sig->r);
if (sig->s) BN_free (sig->s);
sig->r = r; sig->s = s; return 1;
}
inline void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps)
{ *pr = sig->r; *ps = sig->s; }
inline int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d)
{ r->n = n; r->e = e; r->d = d; return 1; }
inline void RSA_get0_key(const RSA *r, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
{ *n = r->n; *e = r->e; *d = r->d; }
inline int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
{ dh->p = p; dh->q = q; dh->g = g; return 1; }
inline int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key)
{
if (dh->pub_key) BN_free (dh->pub_key);
if (dh->priv_key) BN_free (dh->priv_key);
dh->pub_key = pub_key; dh->priv_key = priv_key; return 1;
}
inline void DH_get0_key(const DH *dh, const BIGNUM **pub_key, const BIGNUM **priv_key)
{ *pub_key = dh->pub_key; *priv_key = dh->priv_key; }
inline RSA *EVP_PKEY_get0_RSA(EVP_PKEY *pkey)
{ return pkey->pkey.rsa; }
// ssl
#define TLS_method TLSv1_method
#endif
#endif

View File

@ -1,358 +0,0 @@
#include <thread>
#include <memory>
#include "Daemon.h"
#include "Config.h"
#include "Log.h"
#include "FS.h"
#include "Base.h"
#include "version.h"
#include "Transports.h"
#include "NTCPSession.h"
#include "RouterInfo.h"
#include "RouterContext.h"
#include "Tunnel.h"
#include "HTTP.h"
#include "NetDb.h"
#include "Garlic.h"
#include "Streaming.h"
#include "Destination.h"
#include "HTTPServer.h"
#include "I2PControl.h"
#include "ClientContext.h"
#include "Crypto.h"
#include "UPnP.h"
#include "util.h"
#include "Event.h"
#include "Websocket.h"
namespace i2p
{
namespace util
{
class Daemon_Singleton::Daemon_Singleton_Private
{
public:
Daemon_Singleton_Private() {};
~Daemon_Singleton_Private() {};
std::unique_ptr<i2p::http::HTTPServer> httpServer;
std::unique_ptr<i2p::client::I2PControlService> m_I2PControlService;
std::unique_ptr<i2p::transport::UPnP> UPnP;
#ifdef WITH_EVENTS
std::unique_ptr<i2p::event::WebsocketServer> m_WebsocketServer;
#endif
};
Daemon_Singleton::Daemon_Singleton() : isDaemon(false), running(true), d(*new Daemon_Singleton_Private()) {}
Daemon_Singleton::~Daemon_Singleton() {
delete &d;
}
bool Daemon_Singleton::IsService () const
{
bool service = false;
#ifndef _WIN32
i2p::config::GetOption("service", service);
#endif
return service;
}
bool Daemon_Singleton::init(int argc, char* argv[])
{
i2p::config::Init();
i2p::config::ParseCmdline(argc, argv);
std::string config; i2p::config::GetOption("conf", config);
std::string datadir; i2p::config::GetOption("datadir", datadir);
i2p::fs::DetectDataDir(datadir, IsService());
i2p::fs::Init();
datadir = i2p::fs::GetDataDir();
// TODO: drop old name detection in v2.8.0
if (config == "")
{
config = i2p::fs::DataDirPath("i2p.conf");
if (i2p::fs::Exists (config)) {
LogPrint(eLogWarning, "Daemon: please rename i2p.conf to i2pd.conf here: ", config);
} else {
config = i2p::fs::DataDirPath("i2pd.conf");
if (!i2p::fs::Exists (config)) {
// use i2pd.conf only if exists
config = ""; /* reset */
}
}
}
i2p::config::ParseConfig(config);
i2p::config::Finalize();
i2p::config::GetOption("daemon", isDaemon);
std::string logs = ""; i2p::config::GetOption("log", logs);
std::string logfile = ""; i2p::config::GetOption("logfile", logfile);
std::string loglevel = ""; i2p::config::GetOption("loglevel", loglevel);
/* setup logging */
if (isDaemon && (logs == "" || logs == "stdout"))
logs = "file";
i2p::log::Logger().SetLogLevel(loglevel);
if (logs == "file") {
if (logfile == "")
logfile = i2p::fs::DataDirPath("i2pd.log");
LogPrint(eLogInfo, "Log: will send messages to ", logfile);
i2p::log::Logger().SendTo (logfile);
#ifndef _WIN32
} else if (logs == "syslog") {
LogPrint(eLogInfo, "Log: will send messages to syslog");
i2p::log::Logger().SendTo("i2pd", LOG_DAEMON);
#endif
} else {
// use stdout -- default
}
LogPrint(eLogInfo, "i2pd v", VERSION, " starting");
LogPrint(eLogDebug, "FS: main config file: ", config);
LogPrint(eLogDebug, "FS: data directory: ", datadir);
bool precomputation; i2p::config::GetOption("precomputation.elgamal", precomputation);
i2p::crypto::InitCrypto (precomputation);
int netID; i2p::config::GetOption("netid", netID);
i2p::context.SetNetID (netID);
i2p::context.Init ();
bool ipv6; i2p::config::GetOption("ipv6", ipv6);
bool ipv4; i2p::config::GetOption("ipv4", ipv4);
#ifdef MESHNET
// manual override for meshnet
ipv4 = false;
ipv6 = true;
#endif
uint16_t port; i2p::config::GetOption("port", port);
if (!i2p::config::IsDefault("port"))
{
LogPrint(eLogInfo, "Daemon: accepting incoming connections at port ", port);
i2p::context.UpdatePort (port);
}
i2p::context.SetSupportsV6 (ipv6);
i2p::context.SetSupportsV4 (ipv4);
bool transit; i2p::config::GetOption("notransit", transit);
i2p::context.SetAcceptsTunnels (!transit);
uint16_t transitTunnels; i2p::config::GetOption("limits.transittunnels", transitTunnels);
SetMaxNumTransitTunnels (transitTunnels);
bool isFloodfill; i2p::config::GetOption("floodfill", isFloodfill);
if (isFloodfill) {
LogPrint(eLogInfo, "Daemon: router will be floodfill");
i2p::context.SetFloodfill (true);
} else {
i2p::context.SetFloodfill (false);
}
/* this section also honors 'floodfill' flag, if set above */
std::string bandwidth; i2p::config::GetOption("bandwidth", bandwidth);
if (bandwidth.length () > 0)
{
if (bandwidth[0] >= 'K' && bandwidth[0] <= 'X')
{
i2p::context.SetBandwidth (bandwidth[0]);
LogPrint(eLogInfo, "Daemon: bandwidth set to ", i2p::context.GetBandwidthLimit (), "KBps");
}
else
{
auto value = std::atoi(bandwidth.c_str());
if (value > 0)
{
i2p::context.SetBandwidth (value);
LogPrint(eLogInfo, "Daemon: bandwidth set to ", i2p::context.GetBandwidthLimit (), " KBps");
}
else
{
LogPrint(eLogInfo, "Daemon: unexpected bandwidth ", bandwidth, ". Set to 'low'");
i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_LOW_BANDWIDTH2);
}
}
}
else if (isFloodfill)
{
LogPrint(eLogInfo, "Daemon: floodfill bandwidth set to 'extra'");
i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_EXTRA_BANDWIDTH1);
}
else
{
LogPrint(eLogInfo, "Daemon: bandwidth set to 'low'");
i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_LOW_BANDWIDTH2);
}
std::string family; i2p::config::GetOption("family", family);
i2p::context.SetFamily (family);
if (family.length () > 0)
LogPrint(eLogInfo, "Daemon: family set to ", family);
bool trust; i2p::config::GetOption("trust.enabled", trust);
if (trust)
{
LogPrint(eLogInfo, "Daemon: explicit trust enabled");
std::string fam; i2p::config::GetOption("trust.family", fam);
std::string routers; i2p::config::GetOption("trust.routers", routers);
bool restricted = false;
if (fam.length() > 0)
{
std::set<std::string> fams;
size_t pos = 0, comma;
do
{
comma = fam.find (',', pos);
fams.insert (fam.substr (pos, comma != std::string::npos ? comma - pos : std::string::npos));
pos = comma + 1;
}
while (comma != std::string::npos);
i2p::transport::transports.RestrictRoutesToFamilies(fams);
restricted = fams.size() > 0;
}
if (routers.length() > 0) {
std::set<i2p::data::IdentHash> idents;
size_t pos = 0, comma;
do
{
comma = routers.find (',', pos);
i2p::data::IdentHash ident;
ident.FromBase64 (routers.substr (pos, comma != std::string::npos ? comma - pos : std::string::npos));
idents.insert (ident);
pos = comma + 1;
}
while (comma != std::string::npos);
LogPrint(eLogInfo, "Daemon: setting restricted routes to use ", idents.size(), " trusted routesrs");
i2p::transport::transports.RestrictRoutesToRouters(idents);
restricted = idents.size() > 0;
}
if(!restricted)
LogPrint(eLogError, "Daemon: no trusted routers of families specififed");
}
bool hidden; i2p::config::GetOption("trust.hidden", hidden);
if (hidden)
{
LogPrint(eLogInfo, "Daemon: using hidden mode");
i2p::data::netdb.SetHidden(true);
}
return true;
}
bool Daemon_Singleton::start()
{
i2p::log::Logger().Start();
LogPrint(eLogInfo, "Daemon: starting NetDB");
i2p::data::netdb.Start();
bool upnp; i2p::config::GetOption("upnp.enabled", upnp);
if (upnp) {
d.UPnP = std::unique_ptr<i2p::transport::UPnP>(new i2p::transport::UPnP);
d.UPnP->Start ();
}
bool ntcp; i2p::config::GetOption("ntcp", ntcp);
bool ssu; i2p::config::GetOption("ssu", ssu);
LogPrint(eLogInfo, "Daemon: starting Transports");
if(!ssu) LogPrint(eLogInfo, "Daemon: ssu disabled");
if(!ntcp) LogPrint(eLogInfo, "Daemon: ntcp disabled");
i2p::transport::transports.Start(ntcp, ssu);
if (i2p::transport::transports.IsBoundNTCP() || i2p::transport::transports.IsBoundSSU()) {
LogPrint(eLogInfo, "Daemon: Transports started");
} else {
LogPrint(eLogError, "Daemon: failed to start Transports");
/** shut down netdb right away */
i2p::transport::transports.Stop();
i2p::data::netdb.Stop();
return false;
}
bool http; i2p::config::GetOption("http.enabled", http);
if (http) {
std::string httpAddr; i2p::config::GetOption("http.address", httpAddr);
uint16_t httpPort; i2p::config::GetOption("http.port", httpPort);
LogPrint(eLogInfo, "Daemon: starting HTTP Server at ", httpAddr, ":", httpPort);
d.httpServer = std::unique_ptr<i2p::http::HTTPServer>(new i2p::http::HTTPServer(httpAddr, httpPort));
d.httpServer->Start();
}
LogPrint(eLogInfo, "Daemon: starting Tunnels");
i2p::tunnel::tunnels.Start();
LogPrint(eLogInfo, "Daemon: starting Client");
i2p::client::context.Start ();
// I2P Control Protocol
bool i2pcontrol; i2p::config::GetOption("i2pcontrol.enabled", i2pcontrol);
if (i2pcontrol) {
std::string i2pcpAddr; i2p::config::GetOption("i2pcontrol.address", i2pcpAddr);
uint16_t i2pcpPort; i2p::config::GetOption("i2pcontrol.port", i2pcpPort);
LogPrint(eLogInfo, "Daemon: starting I2PControl at ", i2pcpAddr, ":", i2pcpPort);
d.m_I2PControlService = std::unique_ptr<i2p::client::I2PControlService>(new i2p::client::I2PControlService (i2pcpAddr, i2pcpPort));
d.m_I2PControlService->Start ();
}
#ifdef WITH_EVENTS
bool websocket; i2p::config::GetOption("websockets.enabled", websocket);
if(websocket) {
std::string websocketAddr; i2p::config::GetOption("websockets.address", websocketAddr);
uint16_t websocketPort; i2p::config::GetOption("websockets.port", websocketPort);
LogPrint(eLogInfo, "Daemon: starting Websocket server at ", websocketAddr, ":", websocketPort);
d.m_WebsocketServer = std::unique_ptr<i2p::event::WebsocketServer>(new i2p::event::WebsocketServer (websocketAddr, websocketPort));
d.m_WebsocketServer->Start();
i2p::event::core.SetListener(d.m_WebsocketServer->ToListener());
}
#endif
return true;
}
bool Daemon_Singleton::stop()
{
#ifdef WITH_EVENTS
i2p::event::core.SetListener(nullptr);
#endif
LogPrint(eLogInfo, "Daemon: shutting down");
LogPrint(eLogInfo, "Daemon: stopping Client");
i2p::client::context.Stop();
LogPrint(eLogInfo, "Daemon: stopping Tunnels");
i2p::tunnel::tunnels.Stop();
if (d.UPnP) {
d.UPnP->Stop ();
d.UPnP = nullptr;
}
LogPrint(eLogInfo, "Daemon: stopping Transports");
i2p::transport::transports.Stop();
LogPrint(eLogInfo, "Daemon: stopping NetDB");
i2p::data::netdb.Stop();
if (d.httpServer) {
LogPrint(eLogInfo, "Daemon: stopping HTTP Server");
d.httpServer->Stop();
d.httpServer = nullptr;
}
if (d.m_I2PControlService)
{
LogPrint(eLogInfo, "Daemon: stopping I2PControl");
d.m_I2PControlService->Stop ();
d.m_I2PControlService = nullptr;
}
#ifdef WITH_EVENTS
if (d.m_WebsocketServer) {
LogPrint(eLogInfo, "Daemon: stopping Websocket server");
d.m_WebsocketServer->Stop();
d.m_WebsocketServer = nullptr;
}
#endif
i2p::crypto::TerminateCrypto ();
i2p::log::Logger().Stop();
return true;
}
}
}

107
Daemon.h
View File

@ -1,107 +0,0 @@
#ifndef DAEMON_H__
#define DAEMON_H__
#include <memory>
#include <string>
namespace i2p
{
namespace util
{
class Daemon_Singleton_Private;
class Daemon_Singleton
{
public:
virtual bool init(int argc, char* argv[]);
virtual bool start();
virtual bool stop();
virtual void run () {};
bool isDaemon;
bool running;
protected:
Daemon_Singleton();
virtual ~Daemon_Singleton();
bool IsService () const;
// d-pointer for httpServer, httpProxy, etc.
class Daemon_Singleton_Private;
Daemon_Singleton_Private &d;
};
#if defined(QT_GUI_LIB) // check if QT
#define Daemon i2p::util::DaemonQT::Instance()
// dummy, invoked from RunQT
class DaemonQT: public i2p::util::Daemon_Singleton
{
public:
static DaemonQT& Instance()
{
static DaemonQT instance;
return instance;
}
};
#elif defined(ANDROID)
#define Daemon i2p::util::DaemonAndroid::Instance()
// dummy, invoked from android/jni/DaemonAndroid.*
class DaemonAndroid: public i2p::util::Daemon_Singleton
{
public:
static DaemonAndroid& Instance()
{
static DaemonAndroid instance;
return instance;
}
};
#elif defined(_WIN32)
#define Daemon i2p::util::DaemonWin32::Instance()
class DaemonWin32 : public Daemon_Singleton
{
public:
static DaemonWin32& Instance()
{
static DaemonWin32 instance;
return instance;
}
bool init(int argc, char* argv[]);
bool start();
bool stop();
void run ();
};
#else
#define Daemon i2p::util::DaemonLinux::Instance()
class DaemonLinux : public Daemon_Singleton
{
public:
static DaemonLinux& Instance()
{
static DaemonLinux instance;
return instance;
}
bool start();
bool stop();
void run ();
private:
std::string pidfile;
int pidFH;
public:
int gracefulShutdownInterval; // in seconds
};
#endif
}
}
#endif // DAEMON_H__

View File

@ -1,115 +0,0 @@
#include <thread>
#include <clocale>
#include "Config.h"
#include "Daemon.h"
#include "util.h"
#include "Log.h"
#ifdef _WIN32
#include "Win32/Win32Service.h"
#ifdef WIN32_APP
#include "Win32/Win32App.h"
#endif
namespace i2p
{
namespace util
{
bool DaemonWin32::init(int argc, char* argv[])
{
setlocale(LC_CTYPE, "");
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(LC_ALL, "Russian");
if (!Daemon_Singleton::init(argc, argv))
return false;
std::string serviceControl; i2p::config::GetOption("svcctl", serviceControl);
if (serviceControl == "install")
{
LogPrint(eLogInfo, "WinSVC: installing ", SERVICE_NAME, " as service");
InstallService(
SERVICE_NAME, // Name of service
SERVICE_DISPLAY_NAME, // Name to display
SERVICE_START_TYPE, // Service start type
SERVICE_DEPENDENCIES, // Dependencies
SERVICE_ACCOUNT, // Service running account
SERVICE_PASSWORD // Password of the account
);
return false;
}
else if (serviceControl == "remove")
{
LogPrint(eLogInfo, "WinSVC: uninstalling ", SERVICE_NAME, " service");
UninstallService(SERVICE_NAME);
return false;
}
if (isDaemon)
{
LogPrint(eLogDebug, "Daemon: running as service");
I2PService service(SERVICE_NAME);
if (!I2PService::Run(service))
{
LogPrint(eLogError, "Daemon: Service failed to run w/err 0x%08lx\n", GetLastError());
return false;
}
return false;
}
else
LogPrint(eLogDebug, "Daemon: running as user");
return true;
}
bool DaemonWin32::start()
{
setlocale(LC_CTYPE, "");
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(LC_ALL, "Russian");
#ifdef WIN32_APP
if (!i2p::win32::StartWin32App ()) return false;
// override log
i2p::config::SetOption("log", std::string ("file"));
#endif
bool ret = Daemon_Singleton::start();
if (ret && i2p::log::Logger().GetLogType() == eLogFile)
{
// TODO: find out where this garbage to console comes from
SetStdHandle(STD_OUTPUT_HANDLE, INVALID_HANDLE_VALUE);
SetStdHandle(STD_ERROR_HANDLE, INVALID_HANDLE_VALUE);
}
bool insomnia; i2p::config::GetOption("insomnia", insomnia);
if (insomnia)
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
return ret;
}
bool DaemonWin32::stop()
{
#ifdef WIN32_APP
i2p::win32::StopWin32App ();
#endif
return Daemon_Singleton::stop();
}
void DaemonWin32::run ()
{
#ifdef WIN32_APP
i2p::win32::RunWin32App ();
#else
while (running)
{
std::this_thread::sleep_for (std::chrono::seconds(1));
}
#endif
}
}
}
#endif

View File

@ -1,150 +0,0 @@
#ifndef DATAGRAM_H__
#define DATAGRAM_H__
#include <inttypes.h>
#include <memory>
#include <functional>
#include <map>
#include "Base.h"
#include "Identity.h"
#include "LeaseSet.h"
#include "I2NPProtocol.h"
#include "Garlic.h"
namespace i2p
{
namespace client
{
class ClientDestination;
}
namespace datagram
{
// milliseconds for max session idle time
const uint64_t DATAGRAM_SESSION_MAX_IDLE = 10 * 60 * 1000;
// milliseconds for how long we try sticking to a dead routing path before trying to switch
const uint64_t DATAGRAM_SESSION_PATH_TIMEOUT = 10 * 1000;
// milliseconds interval a routing path is used before switching
const uint64_t DATAGRAM_SESSION_PATH_SWITCH_INTERVAL = 20 * 60 * 1000;
// milliseconds before lease expire should we try switching leases
const uint64_t DATAGRAM_SESSION_LEASE_HANDOVER_WINDOW = 10 * 1000;
// milliseconds fudge factor for leases handover
const uint64_t DATAGRAM_SESSION_LEASE_HANDOVER_FUDGE = 1000;
// milliseconds minimum time between path switches
const uint64_t DATAGRAM_SESSION_PATH_MIN_LIFETIME = 5 * 1000;
// max 64 messages buffered in send queue for each datagram session
const size_t DATAGRAM_SEND_QUEUE_MAX_SIZE = 64;
class DatagramSession : public std::enable_shared_from_this<DatagramSession>
{
public:
DatagramSession(i2p::client::ClientDestination * localDestination, const i2p::data::IdentHash & remoteIdent);
void Start ();
void Stop ();
/** @brief ack the garlic routing path */
void Ack();
/** send an i2np message to remote endpoint for this session */
void SendMsg(std::shared_ptr<I2NPMessage> msg);
/** get the last time in milliseconds for when we used this datagram session */
uint64_t LastActivity() const { return m_LastUse; }
struct Info
{
std::shared_ptr<const i2p::data::IdentHash> IBGW;
std::shared_ptr<const i2p::data::IdentHash> OBEP;
const uint64_t activity;
Info() : IBGW(nullptr), OBEP(nullptr), activity(0) {}
Info(const uint8_t * ibgw, const uint8_t * obep, const uint64_t a) :
activity(a) {
if(ibgw) IBGW = std::make_shared<i2p::data::IdentHash>(ibgw);
else IBGW = nullptr;
if(obep) OBEP = std::make_shared<i2p::data::IdentHash>(obep);
else OBEP = nullptr;
}
};
Info GetSessionInfo() const;
private:
void FlushSendQueue();
void ScheduleFlushSendQueue();
void HandleSend(std::shared_ptr<I2NPMessage> msg);
std::shared_ptr<i2p::garlic::GarlicRoutingPath> GetSharedRoutingPath();
void HandleLeaseSetUpdated(std::shared_ptr<i2p::data::LeaseSet> ls);
private:
i2p::client::ClientDestination * m_LocalDestination;
i2p::data::IdentHash m_RemoteIdent;
std::shared_ptr<const i2p::data::LeaseSet> m_RemoteLeaseSet;
std::shared_ptr<i2p::garlic::GarlicRoutingSession> m_RoutingSession;
std::shared_ptr<const i2p::data::Lease> m_CurrentRemoteLease;
std::shared_ptr<i2p::tunnel::OutboundTunnel> m_CurrentOutboundTunnel;
boost::asio::deadline_timer m_SendQueueTimer;
std::vector<std::shared_ptr<I2NPMessage> > m_SendQueue;
uint64_t m_LastUse;
bool m_RequestingLS;
};
typedef std::shared_ptr<DatagramSession> DatagramSession_ptr;
const size_t MAX_DATAGRAM_SIZE = 32768;
class DatagramDestination
{
typedef std::function<void (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)> Receiver;
public:
DatagramDestination (std::shared_ptr<i2p::client::ClientDestination> owner);
~DatagramDestination ();
void SendDatagramTo (const uint8_t * payload, size_t len, const i2p::data::IdentHash & ident, uint16_t fromPort = 0, uint16_t toPort = 0);
void HandleDataMessagePayload (uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len);
void SetReceiver (const Receiver& receiver) { m_Receiver = receiver; };
void ResetReceiver () { m_Receiver = nullptr; };
void SetReceiver (const Receiver& receiver, uint16_t port) { std::lock_guard<std::mutex> lock(m_ReceiversMutex); m_ReceiversByPorts[port] = receiver; };
void ResetReceiver (uint16_t port) { std::lock_guard<std::mutex> lock(m_ReceiversMutex); m_ReceiversByPorts.erase (port); };
std::shared_ptr<DatagramSession::Info> GetInfoForRemote(const i2p::data::IdentHash & remote);
// clean up stale sessions
void CleanUp ();
private:
std::shared_ptr<DatagramSession> ObtainSession(const i2p::data::IdentHash & ident);
std::shared_ptr<I2NPMessage> CreateDataMessage (const uint8_t * payload, size_t len, uint16_t fromPort, uint16_t toPort);
void HandleDatagram (uint16_t fromPort, uint16_t toPort, uint8_t *const& buf, size_t len);
/** find a receiver by port, if none by port is found try default receiever, otherwise returns nullptr */
Receiver FindReceiver(uint16_t port);
private:
i2p::client::ClientDestination * m_Owner;
i2p::data::IdentityEx m_Identity;
Receiver m_Receiver; // default
std::mutex m_SessionsMutex;
std::map<i2p::data::IdentHash, DatagramSession_ptr > m_Sessions;
std::mutex m_ReceiversMutex;
std::map<uint16_t, Receiver> m_ReceiversByPorts;
i2p::data::GzipInflator m_Inflator;
i2p::data::GzipDeflator m_Deflator;
};
}
}
#endif

View File

@ -1,944 +0,0 @@
#include <algorithm>
#include <cassert>
#include "Crypto.h"
#include "Log.h"
#include "FS.h"
#include "Timestamp.h"
#include "NetDb.h"
#include "Destination.h"
#include "util.h"
namespace i2p
{
namespace client
{
LeaseSetDestination::LeaseSetDestination (bool isPublic, const std::map<std::string, std::string> * params):
m_IsRunning (false), m_Thread (nullptr), m_IsPublic (isPublic),
m_PublishReplyToken (0), m_LastSubmissionTime (0), m_PublishConfirmationTimer (m_Service),
m_PublishVerificationTimer (m_Service), m_PublishDelayTimer (m_Service), m_CleanupTimer (m_Service)
{
int inLen = DEFAULT_INBOUND_TUNNEL_LENGTH;
int inQty = DEFAULT_INBOUND_TUNNELS_QUANTITY;
int outLen = DEFAULT_OUTBOUND_TUNNEL_LENGTH;
int outQty = DEFAULT_OUTBOUND_TUNNELS_QUANTITY;
int numTags = DEFAULT_TAGS_TO_SEND;
std::shared_ptr<std::vector<i2p::data::IdentHash> > explicitPeers;
try {
if (params) {
auto it = params->find (I2CP_PARAM_INBOUND_TUNNEL_LENGTH);
if (it != params->end ())
inLen = std::stoi(it->second);
it = params->find (I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH);
if (it != params->end ())
outLen = std::stoi(it->second);
it = params->find (I2CP_PARAM_INBOUND_TUNNELS_QUANTITY);
if (it != params->end ())
inQty = std::stoi(it->second);
it = params->find (I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY);
if (it != params->end ())
outQty = std::stoi(it->second);
it = params->find (I2CP_PARAM_TAGS_TO_SEND);
if (it != params->end ())
numTags = std::stoi(it->second);
LogPrint (eLogInfo, "Destination: parameters for tunnel set to: ", inQty, " inbound (", inLen, " hops), ", outQty, " outbound (", outLen, " hops), ", numTags, " tags");
it = params->find (I2CP_PARAM_EXPLICIT_PEERS);
if (it != params->end ())
{
explicitPeers = std::make_shared<std::vector<i2p::data::IdentHash> >();
std::stringstream ss(it->second);
std::string b64;
while (std::getline (ss, b64, ','))
{
i2p::data::IdentHash ident;
ident.FromBase64 (b64);
explicitPeers->push_back (ident);
LogPrint (eLogInfo, "Destination: Added to explicit peers list: ", b64);
}
}
}
} catch (std::exception & ex) {
LogPrint(eLogError, "Destination: unable to parse parameters for destination: ", ex.what());
}
SetNumTags (numTags);
m_Pool = i2p::tunnel::tunnels.CreateTunnelPool (inLen, outLen, inQty, outQty);
if (explicitPeers)
m_Pool->SetExplicitPeers (explicitPeers);
if(params)
{
auto itr = params->find(I2CP_PARAM_MAX_TUNNEL_LATENCY);
if (itr != params->end()) {
auto maxlatency = std::stoi(itr->second);
itr = params->find(I2CP_PARAM_MIN_TUNNEL_LATENCY);
if (itr != params->end()) {
auto minlatency = std::stoi(itr->second);
if ( minlatency > 0 && maxlatency > 0 ) {
// set tunnel pool latency
LogPrint(eLogInfo, "Destination: requiring tunnel latency [", minlatency, "ms, ", maxlatency, "ms]");
m_Pool->RequireLatency(minlatency, maxlatency);
}
}
}
}
}
LeaseSetDestination::~LeaseSetDestination ()
{
if (m_IsRunning)
Stop ();
if (m_Pool)
i2p::tunnel::tunnels.DeleteTunnelPool (m_Pool);
for (auto& it: m_LeaseSetRequests)
it.second->Complete (nullptr);
}
void LeaseSetDestination::Run ()
{
while (m_IsRunning)
{
try
{
m_Service.run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "Destination: runtime exception: ", ex.what ());
}
}
}
bool LeaseSetDestination::Start ()
{
if (!m_IsRunning)
{
m_IsRunning = true;
m_Pool->SetLocalDestination (shared_from_this ());
m_Pool->SetActive (true);
m_CleanupTimer.expires_from_now (boost::posix_time::minutes (DESTINATION_CLEANUP_TIMEOUT));
m_CleanupTimer.async_wait (std::bind (&LeaseSetDestination::HandleCleanupTimer,
shared_from_this (), std::placeholders::_1));
m_Thread = new std::thread (std::bind (&LeaseSetDestination::Run, shared_from_this ()));
return true;
}
else
return false;
}
bool LeaseSetDestination::Stop ()
{
if (m_IsRunning)
{
m_CleanupTimer.cancel ();
m_PublishConfirmationTimer.cancel ();
m_PublishVerificationTimer.cancel ();
m_IsRunning = false;
if (m_Pool)
{
m_Pool->SetLocalDestination (nullptr);
i2p::tunnel::tunnels.StopTunnelPool (m_Pool);
}
m_Service.stop ();
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = 0;
}
CleanUp (); // GarlicDestination
return true;
}
else
return false;
}
std::shared_ptr<const i2p::data::LeaseSet> LeaseSetDestination::FindLeaseSet (const i2p::data::IdentHash& ident)
{
std::shared_ptr<i2p::data::LeaseSet> remoteLS;
{
std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex);
auto it = m_RemoteLeaseSets.find (ident);
if (it != m_RemoteLeaseSets.end ())
remoteLS = it->second;
}
if (remoteLS)
{
if (!remoteLS->IsExpired ())
{
if (remoteLS->ExpiresSoon())
{
LogPrint(eLogDebug, "Destination: Lease Set expires soon, updating before expire");
// update now before expiration for smooth handover
auto s = shared_from_this ();
RequestDestination(ident, [s, ident] (std::shared_ptr<i2p::data::LeaseSet> ls) {
if(ls && !ls->IsExpired())
{
ls->PopulateLeases();
{
std::lock_guard<std::mutex> _lock(s->m_RemoteLeaseSetsMutex);
s->m_RemoteLeaseSets[ident] = ls;
}
}
});
}
return remoteLS;
}
else
{
LogPrint (eLogWarning, "Destination: remote LeaseSet expired");
std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex);
m_RemoteLeaseSets.erase (ident);
return nullptr;
}
}
else
{
auto ls = i2p::data::netdb.FindLeaseSet (ident);
if (ls && !ls->IsExpired ())
{
ls->PopulateLeases (); // since we don't store them in netdb
std::lock_guard<std::mutex> _lock(m_RemoteLeaseSetsMutex);
m_RemoteLeaseSets[ident] = ls;
return ls;
}
}
return nullptr;
}
std::shared_ptr<const i2p::data::LocalLeaseSet> LeaseSetDestination::GetLeaseSet ()
{
if (!m_Pool) return nullptr;
if (!m_LeaseSet)
UpdateLeaseSet ();
std::lock_guard<std::mutex> l(m_LeaseSetMutex);
return m_LeaseSet;
}
void LeaseSetDestination::SetLeaseSet (i2p::data::LocalLeaseSet * newLeaseSet)
{
{
std::lock_guard<std::mutex> l(m_LeaseSetMutex);
m_LeaseSet.reset (newLeaseSet);
}
i2p::garlic::GarlicDestination::SetLeaseSetUpdated ();
if (m_IsPublic)
{
m_PublishVerificationTimer.cancel ();
Publish ();
}
}
void LeaseSetDestination::UpdateLeaseSet ()
{
int numTunnels = m_Pool->GetNumInboundTunnels () + 2; // 2 backup tunnels
if (numTunnels > i2p::data::MAX_NUM_LEASES) numTunnels = i2p::data::MAX_NUM_LEASES; // 16 tunnels maximum
CreateNewLeaseSet (m_Pool->GetInboundTunnels (numTunnels));
}
bool LeaseSetDestination::SubmitSessionKey (const uint8_t * key, const uint8_t * tag)
{
struct
{
uint8_t k[32], t[32];
} data;
memcpy (data.k, key, 32);
memcpy (data.t, tag, 32);
auto s = shared_from_this ();
m_Service.post ([s,data](void)
{
s->AddSessionKey (data.k, data.t);
});
return true;
}
void LeaseSetDestination::ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg)
{
m_Service.post (std::bind (&LeaseSetDestination::HandleGarlicMessage, shared_from_this (), msg));
}
void LeaseSetDestination::ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg)
{
m_Service.post (std::bind (&LeaseSetDestination::HandleDeliveryStatusMessage, shared_from_this (), msg));
}
void LeaseSetDestination::HandleI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from)
{
uint8_t typeID = buf[I2NP_HEADER_TYPEID_OFFSET];
switch (typeID)
{
case eI2NPData:
HandleDataMessage (buf + I2NP_HEADER_SIZE, bufbe16toh (buf + I2NP_HEADER_SIZE_OFFSET));
break;
case eI2NPDeliveryStatus:
// we assume tunnel tests non-encrypted
HandleDeliveryStatusMessage (CreateI2NPMessage (buf, GetI2NPMessageLength (buf), from));
break;
case eI2NPDatabaseStore:
HandleDatabaseStoreMessage (buf + I2NP_HEADER_SIZE, bufbe16toh (buf + I2NP_HEADER_SIZE_OFFSET));
break;
case eI2NPDatabaseSearchReply:
HandleDatabaseSearchReplyMessage (buf + I2NP_HEADER_SIZE, bufbe16toh (buf + I2NP_HEADER_SIZE_OFFSET));
break;
default:
i2p::HandleI2NPMessage (CreateI2NPMessage (buf, GetI2NPMessageLength (buf), from));
}
}
void LeaseSetDestination::HandleDatabaseStoreMessage (const uint8_t * buf, size_t len)
{
uint32_t replyToken = bufbe32toh (buf + DATABASE_STORE_REPLY_TOKEN_OFFSET);
size_t offset = DATABASE_STORE_HEADER_SIZE;
if (replyToken)
{
LogPrint (eLogInfo, "Destination: Reply token is ignored for DatabaseStore");
offset += 36;
}
i2p::data::IdentHash key (buf + DATABASE_STORE_KEY_OFFSET);
std::shared_ptr<i2p::data::LeaseSet> leaseSet;
if (buf[DATABASE_STORE_TYPE_OFFSET] == 1) // LeaseSet
{
LogPrint (eLogDebug, "Destination: Remote LeaseSet");
std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex);
auto it = m_RemoteLeaseSets.find (key);
if (it != m_RemoteLeaseSets.end ())
{
leaseSet = it->second;
if (leaseSet->IsNewer (buf + offset, len - offset))
{
leaseSet->Update (buf + offset, len - offset);
if (leaseSet->IsValid () && leaseSet->GetIdentHash () == key)
LogPrint (eLogDebug, "Destination: Remote LeaseSet updated");
else
{
LogPrint (eLogDebug, "Destination: Remote LeaseSet update failed");
m_RemoteLeaseSets.erase (it);
leaseSet = nullptr;
}
}
else
LogPrint (eLogDebug, "Destination: Remote LeaseSet is older. Not updated");
}
else
{
leaseSet = std::make_shared<i2p::data::LeaseSet> (buf + offset, len - offset);
if (leaseSet->IsValid () && leaseSet->GetIdentHash () == key)
{
if (leaseSet->GetIdentHash () != GetIdentHash ())
{
LogPrint (eLogDebug, "Destination: New remote LeaseSet added");
m_RemoteLeaseSets[key] = leaseSet;
}
else
LogPrint (eLogDebug, "Destination: Own remote LeaseSet dropped");
}
else
{
LogPrint (eLogError, "Destination: New remote LeaseSet failed");
leaseSet = nullptr;
}
}
}
else
LogPrint (eLogError, "Destination: Unexpected client's DatabaseStore type ", buf[DATABASE_STORE_TYPE_OFFSET], ", dropped");
auto it1 = m_LeaseSetRequests.find (key);
if (it1 != m_LeaseSetRequests.end ())
{
it1->second->requestTimeoutTimer.cancel ();
if (it1->second) it1->second->Complete (leaseSet);
m_LeaseSetRequests.erase (it1);
}
}
void LeaseSetDestination::HandleDatabaseSearchReplyMessage (const uint8_t * buf, size_t len)
{
i2p::data::IdentHash key (buf);
int num = buf[32]; // num
LogPrint (eLogDebug, "Destination: DatabaseSearchReply for ", key.ToBase64 (), " num=", num);
auto it = m_LeaseSetRequests.find (key);
if (it != m_LeaseSetRequests.end ())
{
auto request = it->second;
bool found = false;
if (request->excluded.size () < MAX_NUM_FLOODFILLS_PER_REQUEST)
{
for (int i = 0; i < num; i++)
{
i2p::data::IdentHash peerHash (buf + 33 + i*32);
if (!request->excluded.count (peerHash) && !i2p::data::netdb.FindRouter (peerHash))
{
LogPrint (eLogInfo, "Destination: Found new floodfill, request it"); // TODO: recheck this message
i2p::data::netdb.RequestDestination (peerHash);
}
}
auto floodfill = i2p::data::netdb.GetClosestFloodfill (key, request->excluded);
if (floodfill)
{
LogPrint (eLogInfo, "Destination: Requesting ", key.ToBase64 (), " at ", floodfill->GetIdentHash ().ToBase64 ());
if (SendLeaseSetRequest (key, floodfill, request))
found = true;
}
}
if (!found)
{
LogPrint (eLogInfo, "Destination: ", key.ToBase64 (), " was not found on ", MAX_NUM_FLOODFILLS_PER_REQUEST, " floodfills");
request->Complete (nullptr);
m_LeaseSetRequests.erase (key);
}
}
else
LogPrint (eLogWarning, "Destination: Request for ", key.ToBase64 (), " not found");
}
void LeaseSetDestination::HandleDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg)
{
uint32_t msgID = bufbe32toh (msg->GetPayload () + DELIVERY_STATUS_MSGID_OFFSET);
if (msgID == m_PublishReplyToken)
{
LogPrint (eLogDebug, "Destination: Publishing LeaseSet confirmed for ", GetIdentHash().ToBase32());
m_ExcludedFloodfills.clear ();
m_PublishReplyToken = 0;
// schedule verification
m_PublishVerificationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_VERIFICATION_TIMEOUT));
m_PublishVerificationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishVerificationTimer,
shared_from_this (), std::placeholders::_1));
}
else
i2p::garlic::GarlicDestination::HandleDeliveryStatusMessage (msg);
}
void LeaseSetDestination::SetLeaseSetUpdated ()
{
UpdateLeaseSet ();
}
void LeaseSetDestination::Publish ()
{
if (!m_LeaseSet || !m_Pool)
{
LogPrint (eLogError, "Destination: Can't publish non-existing LeaseSet");
return;
}
if (m_PublishReplyToken)
{
LogPrint (eLogDebug, "Destination: Publishing LeaseSet is pending");
return;
}
auto ts = i2p::util::GetSecondsSinceEpoch ();
if (ts < m_LastSubmissionTime + PUBLISH_MIN_INTERVAL)
{
LogPrint (eLogDebug, "Destination: Publishing LeaseSet is too fast. Wait for ", PUBLISH_MIN_INTERVAL, " seconds");
m_PublishDelayTimer.cancel ();
m_PublishDelayTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_MIN_INTERVAL));
m_PublishDelayTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishDelayTimer,
shared_from_this (), std::placeholders::_1));
return;
}
auto outbound = m_Pool->GetNextOutboundTunnel ();
if (!outbound)
{
LogPrint (eLogError, "Destination: Can't publish LeaseSet. No outbound tunnels");
return;
}
auto inbound = m_Pool->GetNextInboundTunnel ();
if (!inbound)
{
LogPrint (eLogError, "Destination: Can't publish LeaseSet. No inbound tunnels");
return;
}
auto floodfill = i2p::data::netdb.GetClosestFloodfill (m_LeaseSet->GetIdentHash (), m_ExcludedFloodfills);
if (!floodfill)
{
LogPrint (eLogError, "Destination: Can't publish LeaseSet, no more floodfills found");
m_ExcludedFloodfills.clear ();
return;
}
m_ExcludedFloodfills.insert (floodfill->GetIdentHash ());
LogPrint (eLogDebug, "Destination: Publish LeaseSet of ", GetIdentHash ().ToBase32 ());
RAND_bytes ((uint8_t *)&m_PublishReplyToken, 4);
auto msg = WrapMessage (floodfill, i2p::CreateDatabaseStoreMsg (m_LeaseSet, m_PublishReplyToken, inbound));
m_PublishConfirmationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_CONFIRMATION_TIMEOUT));
m_PublishConfirmationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishConfirmationTimer,
shared_from_this (), std::placeholders::_1));
outbound->SendTunnelDataMsg (floodfill->GetIdentHash (), 0, msg);
m_LastSubmissionTime = ts;
}
void LeaseSetDestination::HandlePublishConfirmationTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
if (m_PublishReplyToken)
{
LogPrint (eLogWarning, "Destination: Publish confirmation was not received in ", PUBLISH_CONFIRMATION_TIMEOUT, " seconds, will try again");
m_PublishReplyToken = 0;
Publish ();
}
}
}
void LeaseSetDestination::HandlePublishVerificationTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
auto s = shared_from_this ();
RequestLeaseSet (GetIdentHash (),
// "this" added due to bug in gcc 4.7-4.8
[s,this](std::shared_ptr<i2p::data::LeaseSet> leaseSet)
{
if (leaseSet)
{
if (s->m_LeaseSet && *s->m_LeaseSet == *leaseSet)
{
// we got latest LeasetSet
LogPrint (eLogDebug, "Destination: published LeaseSet verified for ", GetIdentHash().ToBase32());
s->m_PublishVerificationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_REGULAR_VERIFICATION_INTERNAL));
s->m_PublishVerificationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishVerificationTimer, s, std::placeholders::_1));
return;
}
else
LogPrint (eLogDebug, "Destination: LeaseSet is different than just published for ", GetIdentHash().ToBase32());
}
else
LogPrint (eLogWarning, "Destination: couldn't find published LeaseSet for ", GetIdentHash().ToBase32());
// we have to publish again
s->Publish ();
});
}
}
void LeaseSetDestination::HandlePublishDelayTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
Publish ();
}
bool LeaseSetDestination::RequestDestination (const i2p::data::IdentHash& dest, RequestComplete requestComplete)
{
if (!m_Pool || !IsReady ())
{
if (requestComplete)
m_Service.post ([requestComplete](void){requestComplete (nullptr);});
return false;
}
m_Service.post (std::bind (&LeaseSetDestination::RequestLeaseSet, shared_from_this (), dest, requestComplete));
return true;
}
void LeaseSetDestination::CancelDestinationRequest (const i2p::data::IdentHash& dest, bool notify)
{
auto s = shared_from_this ();
m_Service.post ([dest, notify, s](void)
{
auto it = s->m_LeaseSetRequests.find (dest);
if (it != s->m_LeaseSetRequests.end ())
{
auto requestComplete = it->second;
s->m_LeaseSetRequests.erase (it);
if (notify && requestComplete) requestComplete->Complete (nullptr);
}
});
}
void LeaseSetDestination::RequestLeaseSet (const i2p::data::IdentHash& dest, RequestComplete requestComplete)
{
std::set<i2p::data::IdentHash> excluded;
auto floodfill = i2p::data::netdb.GetClosestFloodfill (dest, excluded);
if (floodfill)
{
auto request = std::make_shared<LeaseSetRequest> (m_Service);
if (requestComplete)
request->requestComplete.push_back (requestComplete);
auto ts = i2p::util::GetSecondsSinceEpoch ();
auto ret = m_LeaseSetRequests.insert (std::pair<i2p::data::IdentHash, std::shared_ptr<LeaseSetRequest> >(dest,request));
if (ret.second) // inserted
{
request->requestTime = ts;
if (!SendLeaseSetRequest (dest, floodfill, request))
{
// request failed
m_LeaseSetRequests.erase (ret.first);
if (requestComplete) requestComplete (nullptr);
}
}
else // duplicate
{
LogPrint (eLogInfo, "Destination: Request of LeaseSet ", dest.ToBase64 (), " is pending already");
if (ts > ret.first->second->requestTime + MAX_LEASESET_REQUEST_TIMEOUT)
{
// something went wrong
m_LeaseSetRequests.erase (ret.first);
if (requestComplete) requestComplete (nullptr);
}
else if (requestComplete)
ret.first->second->requestComplete.push_back (requestComplete);
}
}
else
{
LogPrint (eLogError, "Destination: Can't request LeaseSet, no floodfills found");
if (requestComplete) requestComplete (nullptr);
}
}
bool LeaseSetDestination::SendLeaseSetRequest (const i2p::data::IdentHash& dest,
std::shared_ptr<const i2p::data::RouterInfo> nextFloodfill, std::shared_ptr<LeaseSetRequest> request)
{
if (!request->replyTunnel || !request->replyTunnel->IsEstablished ())
request->replyTunnel = m_Pool->GetNextInboundTunnel ();
if (!request->replyTunnel) LogPrint (eLogError, "Destination: Can't send LeaseSet request, no inbound tunnels found");
if (!request->outboundTunnel || !request->outboundTunnel->IsEstablished ())
request->outboundTunnel = m_Pool->GetNextOutboundTunnel ();
if (!request->outboundTunnel) LogPrint (eLogError, "Destination: Can't send LeaseSet request, no outbound tunnels found");
if (request->replyTunnel && request->outboundTunnel)
{
request->excluded.insert (nextFloodfill->GetIdentHash ());
request->requestTimeoutTimer.cancel ();
uint8_t replyKey[32], replyTag[32];
RAND_bytes (replyKey, 32); // random session key
RAND_bytes (replyTag, 32); // random session tag
AddSessionKey (replyKey, replyTag);
auto msg = WrapMessage (nextFloodfill,
CreateLeaseSetDatabaseLookupMsg (dest, request->excluded,
request->replyTunnel, replyKey, replyTag));
request->outboundTunnel->SendTunnelDataMsg (
{
i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeRouter,
nextFloodfill->GetIdentHash (), 0, msg
}
});
request->requestTimeoutTimer.expires_from_now (boost::posix_time::seconds(LEASESET_REQUEST_TIMEOUT));
request->requestTimeoutTimer.async_wait (std::bind (&LeaseSetDestination::HandleRequestTimoutTimer,
shared_from_this (), std::placeholders::_1, dest));
}
else
return false;
return true;
}
void LeaseSetDestination::HandleRequestTimoutTimer (const boost::system::error_code& ecode, const i2p::data::IdentHash& dest)
{
if (ecode != boost::asio::error::operation_aborted)
{
auto it = m_LeaseSetRequests.find (dest);
if (it != m_LeaseSetRequests.end ())
{
bool done = false;
uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
if (ts < it->second->requestTime + MAX_LEASESET_REQUEST_TIMEOUT)
{
auto floodfill = i2p::data::netdb.GetClosestFloodfill (dest, it->second->excluded);
if (floodfill)
{
// reset tunnels, because one them might fail
it->second->outboundTunnel = nullptr;
it->second->replyTunnel = nullptr;
done = !SendLeaseSetRequest (dest, floodfill, it->second);
}
else
done = true;
}
else
{
LogPrint (eLogWarning, "Destination: ", dest.ToBase64 (), " was not found within ", MAX_LEASESET_REQUEST_TIMEOUT, " seconds");
done = true;
}
if (done)
{
auto requestComplete = it->second;
m_LeaseSetRequests.erase (it);
if (requestComplete) requestComplete->Complete (nullptr);
}
}
}
}
void LeaseSetDestination::HandleCleanupTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
CleanupExpiredTags ();
CleanupRemoteLeaseSets ();
CleanupDestination ();
m_CleanupTimer.expires_from_now (boost::posix_time::minutes (DESTINATION_CLEANUP_TIMEOUT));
m_CleanupTimer.async_wait (std::bind (&LeaseSetDestination::HandleCleanupTimer,
shared_from_this (), std::placeholders::_1));
}
}
void LeaseSetDestination::CleanupRemoteLeaseSets ()
{
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex);
for (auto it = m_RemoteLeaseSets.begin (); it != m_RemoteLeaseSets.end ();)
{
if (it->second->IsEmpty () || ts > it->second->GetExpirationTime ()) // leaseset expired
{
LogPrint (eLogWarning, "Destination: Remote LeaseSet ", it->second->GetIdentHash ().ToBase64 (), " expired");
it = m_RemoteLeaseSets.erase (it);
}
else
++it;
}
}
ClientDestination::ClientDestination (const i2p::data::PrivateKeys& keys, bool isPublic, const std::map<std::string, std::string> * params):
LeaseSetDestination (isPublic, params),
m_Keys (keys), m_DatagramDestination (nullptr),
m_ReadyChecker(GetService())
{
if (isPublic)
PersistTemporaryKeys ();
else
i2p::crypto::GenerateElGamalKeyPair(m_EncryptionPrivateKey, m_EncryptionPublicKey);
if (isPublic)
LogPrint (eLogInfo, "Destination: Local address ", GetIdentHash().ToBase32 (), " created");
}
ClientDestination::~ClientDestination ()
{
}
bool ClientDestination::Start ()
{
if (LeaseSetDestination::Start ())
{
m_StreamingDestination = std::make_shared<i2p::stream::StreamingDestination> (GetSharedFromThis ()); // TODO:
m_StreamingDestination->Start ();
for (auto& it: m_StreamingDestinationsByPorts)
it.second->Start ();
return true;
}
else
return false;
}
bool ClientDestination::Stop ()
{
if (LeaseSetDestination::Stop ())
{
m_ReadyChecker.cancel();
m_StreamingDestination->Stop ();
//m_StreamingDestination->SetOwner (nullptr);
m_StreamingDestination = nullptr;
for (auto& it: m_StreamingDestinationsByPorts)
{
it.second->Stop ();
//it.second->SetOwner (nullptr);
}
m_StreamingDestinationsByPorts.clear ();
if (m_DatagramDestination)
{
delete m_DatagramDestination;
m_DatagramDestination = nullptr;
}
return true;
}
else
return false;
}
#ifdef I2LUA
void ClientDestination::Ready(ReadyPromise & p)
{
ScheduleCheckForReady(&p);
}
void ClientDestination::ScheduleCheckForReady(ReadyPromise * p)
{
// tick every 100ms
m_ReadyChecker.expires_from_now(boost::posix_time::milliseconds(100));
m_ReadyChecker.async_wait([&, p] (const boost::system::error_code & ecode) {
HandleCheckForReady(ecode, p);
});
}
void ClientDestination::HandleCheckForReady(const boost::system::error_code & ecode, ReadyPromise * p)
{
if(ecode) // error happened
p->set_value(nullptr);
else if(IsReady()) // we are ready
p->set_value(std::shared_ptr<ClientDestination>(this));
else // we are not ready
ScheduleCheckForReady(p);
}
#endif
void ClientDestination::HandleDataMessage (const uint8_t * buf, size_t len)
{
uint32_t length = bufbe32toh (buf);
buf += 4;
// we assume I2CP payload
uint16_t fromPort = bufbe16toh (buf + 4), // source
toPort = bufbe16toh (buf + 6); // destination
switch (buf[9])
{
case PROTOCOL_TYPE_STREAMING:
{
// streaming protocol
auto dest = GetStreamingDestination (toPort);
if (dest)
dest->HandleDataMessagePayload (buf, length);
else
LogPrint (eLogError, "Destination: Missing streaming destination");
}
break;
case PROTOCOL_TYPE_DATAGRAM:
// datagram protocol
if (m_DatagramDestination)
m_DatagramDestination->HandleDataMessagePayload (fromPort, toPort, buf, length);
else
LogPrint (eLogError, "Destination: Missing datagram destination");
break;
default:
LogPrint (eLogError, "Destination: Data: unexpected protocol ", buf[9]);
}
}
void ClientDestination::CreateStream (StreamRequestComplete streamRequestComplete, const i2p::data::IdentHash& dest, int port)
{
if (!streamRequestComplete)
{
LogPrint (eLogError, "Destination: request callback is not specified in CreateStream");
return;
}
auto leaseSet = FindLeaseSet (dest);
if (leaseSet)
streamRequestComplete(CreateStream (leaseSet, port));
else
{
auto s = GetSharedFromThis ();
RequestDestination (dest,
[s, streamRequestComplete, port](std::shared_ptr<i2p::data::LeaseSet> ls)
{
if (ls)
streamRequestComplete(s->CreateStream (ls, port));
else
streamRequestComplete (nullptr);
});
}
}
std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (std::shared_ptr<const i2p::data::LeaseSet> remote, int port)
{
if (m_StreamingDestination)
return m_StreamingDestination->CreateNewOutgoingStream (remote, port);
else
return nullptr;
}
std::shared_ptr<i2p::stream::StreamingDestination> ClientDestination::GetStreamingDestination (int port) const
{
if (port)
{
auto it = m_StreamingDestinationsByPorts.find (port);
if (it != m_StreamingDestinationsByPorts.end ())
return it->second;
}
// if port is zero or not found, use default destination
return m_StreamingDestination;
}
void ClientDestination::AcceptStreams (const i2p::stream::StreamingDestination::Acceptor& acceptor)
{
if (m_StreamingDestination)
m_StreamingDestination->SetAcceptor (acceptor);
}
void ClientDestination::StopAcceptingStreams ()
{
if (m_StreamingDestination)
m_StreamingDestination->ResetAcceptor ();
}
bool ClientDestination::IsAcceptingStreams () const
{
if (m_StreamingDestination)
return m_StreamingDestination->IsAcceptorSet ();
return false;
}
void ClientDestination::AcceptOnce (const i2p::stream::StreamingDestination::Acceptor& acceptor)
{
if (m_StreamingDestination)
m_StreamingDestination->AcceptOnce (acceptor);
}
std::shared_ptr<i2p::stream::StreamingDestination> ClientDestination::CreateStreamingDestination (int port, bool gzip)
{
auto dest = std::make_shared<i2p::stream::StreamingDestination> (GetSharedFromThis (), port, gzip);
if (port)
m_StreamingDestinationsByPorts[port] = dest;
else // update default
m_StreamingDestination = dest;
return dest;
}
i2p::datagram::DatagramDestination * ClientDestination::CreateDatagramDestination ()
{
if (m_DatagramDestination == nullptr)
m_DatagramDestination = new i2p::datagram::DatagramDestination (GetSharedFromThis ());
return m_DatagramDestination;
}
std::vector<std::shared_ptr<const i2p::stream::Stream> > ClientDestination::GetAllStreams () const
{
std::vector<std::shared_ptr<const i2p::stream::Stream> > ret;
if (m_StreamingDestination)
{
for (auto& it: m_StreamingDestination->GetStreams ())
ret.push_back (it.second);
}
for (auto& it: m_StreamingDestinationsByPorts)
for (auto& it1: it.second->GetStreams ())
ret.push_back (it1.second);
return ret;
}
void ClientDestination::PersistTemporaryKeys ()
{
std::string ident = GetIdentHash().ToBase32();
std::string path = i2p::fs::DataDirPath("destinations", (ident + ".dat"));
std::ifstream f(path, std::ifstream::binary);
if (f) {
f.read ((char *)m_EncryptionPublicKey, 256);
f.read ((char *)m_EncryptionPrivateKey, 256);
return;
}
LogPrint (eLogInfo, "Destination: Creating new temporary keys for address ", ident, ".b32.i2p");
i2p::crypto::GenerateElGamalKeyPair(m_EncryptionPrivateKey, m_EncryptionPublicKey);
std::ofstream f1 (path, std::ofstream::binary | std::ofstream::out);
if (f1) {
f1.write ((char *)m_EncryptionPublicKey, 256);
f1.write ((char *)m_EncryptionPrivateKey, 256);
return;
}
LogPrint(eLogError, "Destinations: Can't save keys to ", path);
}
void ClientDestination::CreateNewLeaseSet (std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels)
{
auto leaseSet = new i2p::data::LocalLeaseSet (GetIdentity (), m_EncryptionPublicKey, tunnels);
// sign
Sign (leaseSet->GetBuffer (), leaseSet->GetBufferLen () - leaseSet->GetSignatureLen (), leaseSet->GetSignature ()); // TODO
SetLeaseSet (leaseSet);
}
void ClientDestination::CleanupDestination ()
{
if (m_DatagramDestination) m_DatagramDestination->CleanUp ();
}
}
}

View File

@ -1,238 +0,0 @@
#ifndef DESTINATION_H__
#define DESTINATION_H__
#include <thread>
#include <mutex>
#include <memory>
#include <map>
#include <set>
#include <string>
#include <functional>
#ifdef I2LUA
#include <future>
#endif
#include <boost/asio.hpp>
#include "Identity.h"
#include "TunnelPool.h"
#include "Crypto.h"
#include "LeaseSet.h"
#include "Garlic.h"
#include "NetDb.h"
#include "Streaming.h"
#include "Datagram.h"
namespace i2p
{
namespace client
{
const uint8_t PROTOCOL_TYPE_STREAMING = 6;
const uint8_t PROTOCOL_TYPE_DATAGRAM = 17;
const uint8_t PROTOCOL_TYPE_RAW = 18;
const int PUBLISH_CONFIRMATION_TIMEOUT = 5; // in seconds
const int PUBLISH_VERIFICATION_TIMEOUT = 10; // in seconds after successfull publish
const int PUBLISH_MIN_INTERVAL = 20; // in seconds
const int PUBLISH_REGULAR_VERIFICATION_INTERNAL = 100; // in seconds periodically
const int LEASESET_REQUEST_TIMEOUT = 5; // in seconds
const int MAX_LEASESET_REQUEST_TIMEOUT = 40; // in seconds
const int DESTINATION_CLEANUP_TIMEOUT = 3; // in minutes
const unsigned int MAX_NUM_FLOODFILLS_PER_REQUEST = 7;
// I2CP
const char I2CP_PARAM_INBOUND_TUNNEL_LENGTH[] = "inbound.length";
const int DEFAULT_INBOUND_TUNNEL_LENGTH = 3;
const char I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH[] = "outbound.length";
const int DEFAULT_OUTBOUND_TUNNEL_LENGTH = 3;
const char I2CP_PARAM_INBOUND_TUNNELS_QUANTITY[] = "inbound.quantity";
const int DEFAULT_INBOUND_TUNNELS_QUANTITY = 5;
const char I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY[] = "outbound.quantity";
const int DEFAULT_OUTBOUND_TUNNELS_QUANTITY = 5;
const char I2CP_PARAM_EXPLICIT_PEERS[] = "explicitPeers";
const int STREAM_REQUEST_TIMEOUT = 60; //in seconds
const char I2CP_PARAM_TAGS_TO_SEND[] = "crypto.tagsToSend";
const int DEFAULT_TAGS_TO_SEND = 40;
// latency
const char I2CP_PARAM_MIN_TUNNEL_LATENCY[] = "latency.min";
const int DEFAULT_MIN_TUNNEL_LATENCY = 0;
const char I2CP_PARAM_MAX_TUNNEL_LATENCY[] = "latency.max";
const int DEFAULT_MAX_TUNNEL_LATENCY = 0;
typedef std::function<void (std::shared_ptr<i2p::stream::Stream> stream)> StreamRequestComplete;
class LeaseSetDestination: public i2p::garlic::GarlicDestination,
public std::enable_shared_from_this<LeaseSetDestination>
{
typedef std::function<void (std::shared_ptr<i2p::data::LeaseSet> leaseSet)> RequestComplete;
// leaseSet = nullptr means not found
struct LeaseSetRequest
{
LeaseSetRequest (boost::asio::io_service& service): requestTime (0), requestTimeoutTimer (service) {};
std::set<i2p::data::IdentHash> excluded;
uint64_t requestTime;
boost::asio::deadline_timer requestTimeoutTimer;
std::list<RequestComplete> requestComplete;
std::shared_ptr<i2p::tunnel::OutboundTunnel> outboundTunnel;
std::shared_ptr<i2p::tunnel::InboundTunnel> replyTunnel;
void Complete (std::shared_ptr<i2p::data::LeaseSet> ls)
{
for (auto& it: requestComplete) it (ls);
requestComplete.clear ();
}
};
public:
LeaseSetDestination (bool isPublic, const std::map<std::string, std::string> * params = nullptr);
~LeaseSetDestination ();
virtual bool Start ();
virtual bool Stop ();
bool IsRunning () const { return m_IsRunning; };
boost::asio::io_service& GetService () { return m_Service; };
std::shared_ptr<i2p::tunnel::TunnelPool> GetTunnelPool () { return m_Pool; };
bool IsReady () const { return m_LeaseSet && !m_LeaseSet->IsExpired () && m_Pool->GetOutboundTunnels ().size () > 0; };
std::shared_ptr<const i2p::data::LeaseSet> FindLeaseSet (const i2p::data::IdentHash& ident);
bool RequestDestination (const i2p::data::IdentHash& dest, RequestComplete requestComplete = nullptr);
void CancelDestinationRequest (const i2p::data::IdentHash& dest, bool notify = true);
// implements GarlicDestination
std::shared_ptr<const i2p::data::LocalLeaseSet> GetLeaseSet ();
std::shared_ptr<i2p::tunnel::TunnelPool> GetTunnelPool () const { return m_Pool; }
void HandleI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from);
// override GarlicDestination
bool SubmitSessionKey (const uint8_t * key, const uint8_t * tag);
void ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg);
void ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg);
void SetLeaseSetUpdated ();
protected:
void SetLeaseSet (i2p::data::LocalLeaseSet * newLeaseSet);
virtual void CleanupDestination () {}; // additional clean up in derived classes
// I2CP
virtual void HandleDataMessage (const uint8_t * buf, size_t len) = 0;
virtual void CreateNewLeaseSet (std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels) = 0;
private:
void Run ();
void UpdateLeaseSet ();
void Publish ();
void HandlePublishConfirmationTimer (const boost::system::error_code& ecode);
void HandlePublishVerificationTimer (const boost::system::error_code& ecode);
void HandlePublishDelayTimer (const boost::system::error_code& ecode);
void HandleDatabaseStoreMessage (const uint8_t * buf, size_t len);
void HandleDatabaseSearchReplyMessage (const uint8_t * buf, size_t len);
void HandleDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg);
void RequestLeaseSet (const i2p::data::IdentHash& dest, RequestComplete requestComplete);
bool SendLeaseSetRequest (const i2p::data::IdentHash& dest, std::shared_ptr<const i2p::data::RouterInfo> nextFloodfill, std::shared_ptr<LeaseSetRequest> request);
void HandleRequestTimoutTimer (const boost::system::error_code& ecode, const i2p::data::IdentHash& dest);
void HandleCleanupTimer (const boost::system::error_code& ecode);
void CleanupRemoteLeaseSets ();
private:
volatile bool m_IsRunning;
std::thread * m_Thread;
boost::asio::io_service m_Service;
mutable std::mutex m_RemoteLeaseSetsMutex;
std::map<i2p::data::IdentHash, std::shared_ptr<i2p::data::LeaseSet> > m_RemoteLeaseSets;
std::map<i2p::data::IdentHash, std::shared_ptr<LeaseSetRequest> > m_LeaseSetRequests;
std::shared_ptr<i2p::tunnel::TunnelPool> m_Pool;
std::mutex m_LeaseSetMutex;
std::shared_ptr<i2p::data::LocalLeaseSet> m_LeaseSet;
bool m_IsPublic;
uint32_t m_PublishReplyToken;
uint64_t m_LastSubmissionTime; // in seconds
std::set<i2p::data::IdentHash> m_ExcludedFloodfills; // for publishing
boost::asio::deadline_timer m_PublishConfirmationTimer, m_PublishVerificationTimer,
m_PublishDelayTimer, m_CleanupTimer;
public:
// for HTTP only
int GetNumRemoteLeaseSets () const { return m_RemoteLeaseSets.size (); };
const decltype(m_RemoteLeaseSets)& GetLeaseSets () const { return m_RemoteLeaseSets; };
};
class ClientDestination: public LeaseSetDestination
{
public:
#ifdef I2LUA
// type for informing that a client destination is ready
typedef std::promise<std::shared_ptr<ClientDestination> > ReadyPromise;
// informs promise with shared_from_this() when this destination is ready to use
// if cancelled before ready, informs promise with nullptr
void Ready(ReadyPromise & p);
#endif
ClientDestination (const i2p::data::PrivateKeys& keys, bool isPublic, const std::map<std::string, std::string> * params = nullptr);
~ClientDestination ();
bool Start ();
bool Stop ();
const i2p::data::PrivateKeys& GetPrivateKeys () const { return m_Keys; };
void Sign (const uint8_t * buf, int len, uint8_t * signature) const { m_Keys.Sign (buf, len, signature); };
// streaming
std::shared_ptr<i2p::stream::StreamingDestination> CreateStreamingDestination (int port, bool gzip = true); // additional
std::shared_ptr<i2p::stream::StreamingDestination> GetStreamingDestination (int port = 0) const;
// following methods operate with default streaming destination
void CreateStream (StreamRequestComplete streamRequestComplete, const i2p::data::IdentHash& dest, int port = 0);
std::shared_ptr<i2p::stream::Stream> CreateStream (std::shared_ptr<const i2p::data::LeaseSet> remote, int port = 0);
void AcceptStreams (const i2p::stream::StreamingDestination::Acceptor& acceptor);
void StopAcceptingStreams ();
bool IsAcceptingStreams () const;
void AcceptOnce (const i2p::stream::StreamingDestination::Acceptor& acceptor);
// datagram
i2p::datagram::DatagramDestination * GetDatagramDestination () const { return m_DatagramDestination; };
i2p::datagram::DatagramDestination * CreateDatagramDestination ();
// implements LocalDestination
const uint8_t * GetEncryptionPrivateKey () const { return m_EncryptionPrivateKey; };
std::shared_ptr<const i2p::data::IdentityEx> GetIdentity () const { return m_Keys.GetPublic (); };
protected:
void CleanupDestination ();
// I2CP
void HandleDataMessage (const uint8_t * buf, size_t len);
void CreateNewLeaseSet (std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels);
private:
std::shared_ptr<ClientDestination> GetSharedFromThis ()
{ return std::static_pointer_cast<ClientDestination>(shared_from_this ()); }
void PersistTemporaryKeys ();
#ifdef I2LUA
void ScheduleCheckForReady(ReadyPromise * p);
void HandleCheckForReady(const boost::system::error_code & ecode, ReadyPromise * p);
#endif
private:
i2p::data::PrivateKeys m_Keys;
uint8_t m_EncryptionPublicKey[256], m_EncryptionPrivateKey[256];
std::shared_ptr<i2p::stream::StreamingDestination> m_StreamingDestination; // default
std::map<uint16_t, std::shared_ptr<i2p::stream::StreamingDestination> > m_StreamingDestinationsByPorts;
i2p::datagram::DatagramDestination * m_DatagramDestination;
boost::asio::deadline_timer m_ReadyChecker;
public:
// for HTTP only
std::vector<std::shared_ptr<const i2p::stream::Stream> > GetAllStreams () const;
};
}
}
#endif

View File

@ -1,54 +0,0 @@
FROM alpine:latest
MAINTAINER Mikal Villa <mikal@sigterm.no>
ENV GIT_BRANCH="master"
ENV I2PD_PREFIX="/opt/i2pd-${GIT_BRANCH}"
ENV PATH=${I2PD_PREFIX}/bin:$PATH
ENV GOSU_VERSION=1.7
ENV GOSU_SHASUM="34049cfc713e8b74b90d6de49690fa601dc040021980812b2f1f691534be8a50 /usr/local/bin/gosu"
RUN mkdir /user && adduser -S -h /user i2pd && chown -R i2pd:nobody /user
#
# Each RUN is a layer, adding the dependencies and building i2pd in one layer takes around 8-900Mb, so to keep the
# image under 20mb we need to remove all the build dependencies in the same "RUN" / layer.
#
# 1. install deps, clone and build.
# 2. strip binaries.
# 3. Purge all dependencies and other unrelated packages, including build directory.
RUN apk --no-cache --virtual build-dependendencies add make gcc g++ libtool boost-dev build-base openssl-dev openssl git \
&& mkdir -p /tmp/build \
&& cd /tmp/build && git clone -b ${GIT_BRANCH} https://github.com/PurpleI2P/i2pd.git \
&& cd i2pd \
&& make -j4 \
&& mkdir -p ${I2PD_PREFIX}/bin \
&& mv i2pd ${I2PD_PREFIX}/bin/ \
&& cd ${I2PD_PREFIX}/bin \
&& strip i2pd \
&& rm -fr /tmp/build && apk --purge del build-dependendencies build-base fortify-headers boost-dev zlib-dev openssl-dev \
boost-python3 python3 gdbm boost-unit_test_framework boost-python linux-headers boost-prg_exec_monitor \
boost-serialization boost-signals boost-wave boost-wserialization boost-math boost-graph boost-regex git pcre \
libtool g++ gcc pkgconfig
# 2. Adding required libraries to run i2pd to ensure it will run.
RUN apk --no-cache add boost-filesystem boost-system boost-program_options boost-date_time boost-thread boost-iostreams openssl musl-utils libstdc++
# Gosu is a replacement for su/sudo in docker and not a backdoor :) See https://github.com/tianon/gosu
RUN wget -O /usr/local/bin/gosu https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64 \
&& echo "${GOSU_SHASUM}" | sha256sum -c && chmod +x /usr/local/bin/gosu
COPY entrypoint.sh /entrypoint.sh
RUN chmod a+x /entrypoint.sh
RUN echo "export PATH=${PATH}" >> /etc/profile
VOLUME [ "/var/lib/i2pd" ]
EXPOSE 7070 4444 4447 7656 2827 7654 7650
ENTRYPOINT [ "/entrypoint.sh" ]

View File

@ -1,61 +0,0 @@
#include "Event.h"
#include "Log.h"
namespace i2p
{
namespace event
{
#ifdef WITH_EVENTS
EventCore core;
#endif
void EventCore::SetListener(EventListener * l)
{
m_listener = l;
LogPrint(eLogInfo, "Event: listener set");
}
void EventCore::QueueEvent(const EventType & ev)
{
if(m_listener) m_listener->HandleEvent(ev);
}
void EventCore::CollectEvent(const std::string & type, const std::string & ident, uint64_t val)
{
std::unique_lock<std::mutex> lock(m_collect_mutex);
std::string key = type + "." + ident;
if (m_collected.find(key) == m_collected.end())
{
m_collected[key] = {type, key, 0};
}
m_collected[key].Val += val;
}
void EventCore::PumpCollected(EventListener * listener)
{
std::unique_lock<std::mutex> lock(m_collect_mutex);
if(listener)
{
for(const auto & ev : m_collected) {
listener->HandlePumpEvent({{"type", ev.second.Key}, {"ident", ev.second.Ident}}, ev.second.Val);
}
}
m_collected.clear();
}
}
}
void QueueIntEvent(const std::string & type, const std::string & ident, uint64_t val)
{
#ifdef WITH_EVENTS
i2p::event::core.CollectEvent(type, ident, val);
#endif
}
void EmitEvent(const EventType & e)
{
#if WITH_EVENTS
i2p::event::core.QueueEvent(e);
#endif
}

53
Event.h
View File

@ -1,53 +0,0 @@
#ifndef EVENT_H__
#define EVENT_H__
#include <map>
#include <string>
#include <memory>
#include <mutex>
#include <tuple>
#include <boost/asio.hpp>
typedef std::map<std::string, std::string> EventType;
namespace i2p
{
namespace event
{
class EventListener {
public:
virtual ~EventListener() {};
virtual void HandleEvent(const EventType & ev) = 0;
/** @brief handle collected event when pumped */
virtual void HandlePumpEvent(const EventType & ev, const uint64_t & val) = 0;
};
class EventCore
{
public:
void QueueEvent(const EventType & ev);
void CollectEvent(const std::string & type, const std::string & ident, uint64_t val);
void SetListener(EventListener * l);
void PumpCollected(EventListener * l);
private:
std::mutex m_collect_mutex;
struct CollectedEvent
{
std::string Key;
std::string Ident;
uint64_t Val;
};
std::map<std::string, CollectedEvent> m_collected;
EventListener * m_listener = nullptr;
};
#ifdef WITH_EVENTS
extern EventCore core;
#endif
}
}
void QueueIntEvent(const std::string & type, const std::string & ident, uint64_t val);
void EmitEvent(const EventType & ev);
#endif

192
FS.cpp
View File

@ -1,192 +0,0 @@
/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <algorithm>
#include <boost/filesystem.hpp>
#ifdef _WIN32
#include <shlobj.h>
#endif
#include "Base.h"
#include "FS.h"
#include "Log.h"
namespace i2p {
namespace fs {
std::string appName = "i2pd";
std::string dataDir = "";
#ifdef _WIN32
std::string dirSep = "\\";
#else
std::string dirSep = "/";
#endif
const std::string & GetAppName () {
return appName;
}
void SetAppName (const std::string& name) {
appName = name;
}
const std::string & GetDataDir () {
return dataDir;
}
void DetectDataDir(const std::string & cmdline_param, bool isService) {
if (cmdline_param != "") {
dataDir = cmdline_param;
return;
}
#if defined(WIN32) || defined(_WIN32)
char localAppData[MAX_PATH];
// check executable directory first
GetModuleFileName (NULL, localAppData, MAX_PATH);
auto execPath = boost::filesystem::path(localAppData).parent_path();
// if config file exists in .exe's folder use it
if(boost::filesystem::exists(execPath/"i2pd.conf")) // TODO: magic string
dataDir = execPath.string ();
else
{
// otherwise %appdata%
SHGetFolderPath(NULL, CSIDL_APPDATA, 0, NULL, localAppData);
dataDir = std::string(localAppData) + "\\" + appName;
}
return;
#elif defined(MAC_OSX)
char *home = getenv("HOME");
dataDir = (home != NULL && strlen(home) > 0) ? home : "";
dataDir += "/Library/Application Support/" + appName;
return;
#else /* other unix */
#if defined(ANDROID)
const char * ext = getenv("EXTERNAL_STORAGE");
if (!ext) ext = "/sdcard";
if (boost::filesystem::exists(ext))
{
dataDir = std::string (ext) + "/" + appName;
return;
}
// otherwise use /data/files
#endif
char *home = getenv("HOME");
if (isService) {
dataDir = "/var/lib/" + appName;
} else if (home != NULL && strlen(home) > 0) {
dataDir = std::string(home) + "/." + appName;
} else {
dataDir = "/tmp/" + appName;
}
return;
#endif
}
bool Init() {
if (!boost::filesystem::exists(dataDir))
boost::filesystem::create_directory(dataDir);
std::string destinations = DataDirPath("destinations");
if (!boost::filesystem::exists(destinations))
boost::filesystem::create_directory(destinations);
return true;
}
bool ReadDir(const std::string & path, std::vector<std::string> & files) {
if (!boost::filesystem::exists(path))
return false;
boost::filesystem::directory_iterator it(path);
boost::filesystem::directory_iterator end;
for ( ; it != end; it++) {
if (!boost::filesystem::is_regular_file(it->status()))
continue;
files.push_back(it->path().string());
}
return true;
}
bool Exists(const std::string & path) {
return boost::filesystem::exists(path);
}
bool Remove(const std::string & path) {
if (!boost::filesystem::exists(path))
return false;
return boost::filesystem::remove(path);
}
bool CreateDirectory (const std::string& path)
{
if (boost::filesystem::exists(path) &&
boost::filesystem::is_directory (boost::filesystem::status (path))) return true;
return boost::filesystem::create_directory(path);
}
void HashedStorage::SetPlace(const std::string &path) {
root = path + i2p::fs::dirSep + name;
}
bool HashedStorage::Init(const char * chars, size_t count) {
if (!boost::filesystem::exists(root)) {
boost::filesystem::create_directories(root);
}
for (size_t i = 0; i < count; i++) {
auto p = root + i2p::fs::dirSep + prefix1 + chars[i];
if (boost::filesystem::exists(p))
continue;
if (boost::filesystem::create_directory(p))
continue; /* ^ throws exception on failure */
return false;
}
return true;
}
std::string HashedStorage::Path(const std::string & ident) const {
std::string safe_ident = ident;
std::replace(safe_ident.begin(), safe_ident.end(), '/', '-');
std::replace(safe_ident.begin(), safe_ident.end(), '\\', '-');
std::stringstream t("");
t << this->root << i2p::fs::dirSep;
t << prefix1 << safe_ident[0] << i2p::fs::dirSep;
t << prefix2 << safe_ident << "." << suffix;
return t.str();
}
void HashedStorage::Remove(const std::string & ident) {
std::string path = Path(ident);
if (!boost::filesystem::exists(path))
return;
boost::filesystem::remove(path);
}
void HashedStorage::Traverse(std::vector<std::string> & files) {
Iterate([&files] (const std::string & fname) {
files.push_back(fname);
});
}
void HashedStorage::Iterate(FilenameVisitor v)
{
boost::filesystem::path p(root);
boost::filesystem::recursive_directory_iterator it(p);
boost::filesystem::recursive_directory_iterator end;
for ( ; it != end; it++) {
if (!boost::filesystem::is_regular_file( it->status() ))
continue;
const std::string & t = it->path().string();
v(t);
}
}
} // fs
} // i2p

159
FS.h
View File

@ -1,159 +0,0 @@
/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#ifndef FS_H__
#define FS_H__
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <functional>
namespace i2p {
namespace fs {
extern std::string dirSep;
/**
* @brief Class to work with NetDb & Router profiles
*
* Usage:
*
* const char alphabet[8] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
* auto h = HashedStorage("name", "y", "z-", ".txt");
* h.SetPlace("/tmp/hs-test");
* h.GetName() -> gives "name"
* h.GetRoot() -> gives "/tmp/hs-test/name"
* h.Init(alphabet, 8); <- creates needed dirs, 8 is size of alphabet
* h.Path("abcd"); <- returns /tmp/hs-test/name/ya/z-abcd.txt
* h.Remove("abcd"); <- removes /tmp/hs-test/name/ya/z-abcd.txt, if it exists
* std::vector<std::string> files;
* h.Traverse(files); <- finds all files in storage and saves in given vector
*/
class HashedStorage {
protected:
std::string root; /**< path to storage with it's name included */
std::string name; /**< name of the storage */
std::string prefix1; /**< hashed directory prefix */
std::string prefix2; /**< prefix of file in storage */
std::string suffix; /**< suffix of file in storage (extension) */
public:
typedef std::function<void(const std::string &)> FilenameVisitor;
HashedStorage(const char *n, const char *p1, const char *p2, const char *s):
name(n), prefix1(p1), prefix2(p2), suffix(s) {};
/** create subdirs in storage */
bool Init(const char* chars, size_t cnt);
const std::string & GetRoot() const { return root; }
const std::string & GetName() const { return name; }
/** set directory where to place storage directory */
void SetPlace(const std::string & path);
/** path to file with given ident */
std::string Path(const std::string & ident) const;
/** remove file by ident */
void Remove(const std::string & ident);
/** find all files in storage and store list in provided vector */
void Traverse(std::vector<std::string> & files);
/** visit every file in this storage with a visitor */
void Iterate(FilenameVisitor v);
};
/** @brief Returns current application name, default 'i2pd' */
const std::string & GetAppName ();
/** @brief Set applicaton name, affects autodetection of datadir */
void SetAppName (const std::string& name);
/** @brief Returns datadir path */
const std::string & GetDataDir();
/**
* @brief Set datadir either from cmdline option or using autodetection
* @param cmdline_param Value of cmdline parameter --datadir=<something>
* @param isService Value of cmdline parameter --service
*
* Examples of autodetected paths:
*
* Windows < Vista: C:\Documents and Settings\Username\Application Data\i2pd\
* Windows >= Vista: C:\Users\Username\AppData\Roaming\i2pd\
* Mac: /Library/Application Support/i2pd/ or ~/Library/Application Support/i2pd/
* Unix: /var/lib/i2pd/ (system=1) >> ~/.i2pd/ or /tmp/i2pd/
*/
void DetectDataDir(const std::string & cmdline_datadir, bool isService = false);
/**
* @brief Create subdirectories inside datadir
*/
bool Init();
/**
* @brief Get list of files in directory
* @param path Path to directory
* @param files Vector to store found files
* @return true on success and false if directory not exists
*/
bool ReadDir(const std::string & path, std::vector<std::string> & files);
/**
* @brief Remove file with given path
* @param path Absolute path to file
* @return true on success, false if file not exists, throws exception on error
*/
bool Remove(const std::string & path);
/**
* @brief Check existence of file
* @param path Absolute path to file
* @return true if file exists, false otherwise
*/
bool Exists(const std::string & path);
bool CreateDirectory (const std::string& path);
template<typename T>
void _ExpandPath(std::stringstream & path, T c) {
path << i2p::fs::dirSep << c;
}
template<typename T, typename ... Other>
void _ExpandPath(std::stringstream & path, T c, Other ... other) {
_ExpandPath(path, c);
_ExpandPath(path, other ...);
}
/**
* @brief Get path relative to datadir
*
* Examples (with datadir = "/tmp/i2pd"):
*
* i2p::fs::Path("test") -> '/tmp/i2pd/test'
* i2p::fs::Path("test", "file.txt") -> '/tmp/i2pd/test/file.txt'
*/
template<typename ... Other>
std::string DataDirPath(Other ... components) {
std::stringstream s("");
s << i2p::fs::GetDataDir();
_ExpandPath(s, components ...);
return s.str();
}
template<typename Storage, typename... Filename>
std::string StorageRootPath (const Storage& storage, Filename... filenames)
{
std::stringstream s("");
s << storage.GetRoot ();
_ExpandPath(s, filenames...);
return s.str();
}
} // fs
} // i2p
#endif // /* FS_H__ */

View File

@ -1,710 +0,0 @@
#include <inttypes.h>
#include "I2PEndian.h"
#include <map>
#include <string>
#include "Crypto.h"
#include "RouterContext.h"
#include "I2NPProtocol.h"
#include "Tunnel.h"
#include "TunnelPool.h"
#include "Transports.h"
#include "Timestamp.h"
#include "Log.h"
#include "Garlic.h"
namespace i2p
{
namespace garlic
{
GarlicRoutingSession::GarlicRoutingSession (GarlicDestination * owner,
std::shared_ptr<const i2p::data::RoutingDestination> destination, int numTags, bool attachLeaseSet):
m_Owner (owner), m_Destination (destination), m_NumTags (numTags),
m_LeaseSetUpdateStatus (attachLeaseSet ? eLeaseSetUpdated : eLeaseSetDoNotSend),
m_LeaseSetUpdateMsgID (0)
{
// create new session tags and session key
RAND_bytes (m_SessionKey, 32);
m_Encryption.SetKey (m_SessionKey);
}
GarlicRoutingSession::GarlicRoutingSession (const uint8_t * sessionKey, const SessionTag& sessionTag):
m_Owner (nullptr), m_NumTags (1), m_LeaseSetUpdateStatus (eLeaseSetDoNotSend), m_LeaseSetUpdateMsgID (0)
{
memcpy (m_SessionKey, sessionKey, 32);
m_Encryption.SetKey (m_SessionKey);
m_SessionTags.push_back (sessionTag);
m_SessionTags.back ().creationTime = i2p::util::GetSecondsSinceEpoch ();
}
GarlicRoutingSession::~GarlicRoutingSession ()
{
}
std::shared_ptr<GarlicRoutingPath> GarlicRoutingSession::GetSharedRoutingPath ()
{
if (!m_SharedRoutingPath) return nullptr;
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
if (m_SharedRoutingPath->numTimesUsed >= ROUTING_PATH_MAX_NUM_TIMES_USED ||
!m_SharedRoutingPath->outboundTunnel->IsEstablished () ||
ts*1000LL > m_SharedRoutingPath->remoteLease->endDate ||
ts > m_SharedRoutingPath->updateTime + ROUTING_PATH_EXPIRATION_TIMEOUT)
m_SharedRoutingPath = nullptr;
if (m_SharedRoutingPath) m_SharedRoutingPath->numTimesUsed++;
return m_SharedRoutingPath;
}
void GarlicRoutingSession::SetSharedRoutingPath (std::shared_ptr<GarlicRoutingPath> path)
{
if (path && path->outboundTunnel && path->remoteLease)
{
path->updateTime = i2p::util::GetSecondsSinceEpoch ();
path->numTimesUsed = 0;
}
else
path = nullptr;
m_SharedRoutingPath = path;
}
GarlicRoutingSession::UnconfirmedTags * GarlicRoutingSession::GenerateSessionTags ()
{
auto tags = new UnconfirmedTags (m_NumTags);
tags->tagsCreationTime = i2p::util::GetSecondsSinceEpoch ();
for (int i = 0; i < m_NumTags; i++)
{
RAND_bytes (tags->sessionTags[i], 32);
tags->sessionTags[i].creationTime = tags->tagsCreationTime;
}
return tags;
}
void GarlicRoutingSession::MessageConfirmed (uint32_t msgID)
{
TagsConfirmed (msgID);
if (msgID == m_LeaseSetUpdateMsgID)
{
m_LeaseSetUpdateStatus = eLeaseSetUpToDate;
m_LeaseSetUpdateMsgID = 0;
LogPrint (eLogInfo, "Garlic: LeaseSet update confirmed");
}
else
CleanupExpiredTags ();
}
void GarlicRoutingSession::TagsConfirmed (uint32_t msgID)
{
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
auto it = m_UnconfirmedTagsMsgs.find (msgID);
if (it != m_UnconfirmedTagsMsgs.end ())
{
auto& tags = it->second;
if (ts < tags->tagsCreationTime + OUTGOING_TAGS_EXPIRATION_TIMEOUT)
{
for (int i = 0; i < tags->numTags; i++)
m_SessionTags.push_back (tags->sessionTags[i]);
}
m_UnconfirmedTagsMsgs.erase (it);
}
}
bool GarlicRoutingSession::CleanupExpiredTags ()
{
auto ts = i2p::util::GetSecondsSinceEpoch ();
for (auto it = m_SessionTags.begin (); it != m_SessionTags.end ();)
{
if (ts >= it->creationTime + OUTGOING_TAGS_EXPIRATION_TIMEOUT)
it = m_SessionTags.erase (it);
else
++it;
}
CleanupUnconfirmedTags ();
if (m_LeaseSetUpdateMsgID && ts*1000LL > m_LeaseSetSubmissionTime + LEASET_CONFIRMATION_TIMEOUT)
{
if (m_Owner)
m_Owner->RemoveDeliveryStatusSession (m_LeaseSetUpdateMsgID);
m_LeaseSetUpdateMsgID = 0;
}
return !m_SessionTags.empty () || !m_UnconfirmedTagsMsgs.empty ();
}
bool GarlicRoutingSession::CleanupUnconfirmedTags ()
{
bool ret = false;
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
// delete expired unconfirmed tags
for (auto it = m_UnconfirmedTagsMsgs.begin (); it != m_UnconfirmedTagsMsgs.end ();)
{
if (ts >= it->second->tagsCreationTime + OUTGOING_TAGS_CONFIRMATION_TIMEOUT)
{
if (m_Owner)
m_Owner->RemoveDeliveryStatusSession (it->first);
it = m_UnconfirmedTagsMsgs.erase (it);
ret = true;
}
else
++it;
}
return ret;
}
std::shared_ptr<I2NPMessage> GarlicRoutingSession::WrapSingleMessage (std::shared_ptr<const I2NPMessage> msg)
{
auto m = NewI2NPMessage ();
m->Align (12); // in order to get buf aligned to 16 (12 + 4)
size_t len = 0;
uint8_t * buf = m->GetPayload () + 4; // 4 bytes for length
// find non-expired tag
bool tagFound = false;
SessionTag tag;
if (m_NumTags > 0)
{
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
while (!m_SessionTags.empty ())
{
if (ts < m_SessionTags.front ().creationTime + OUTGOING_TAGS_EXPIRATION_TIMEOUT)
{
tag = m_SessionTags.front ();
m_SessionTags.pop_front (); // use same tag only once
tagFound = true;
break;
}
else
m_SessionTags.pop_front (); // remove expired tag
}
}
// create message
if (!tagFound) // new session
{
LogPrint (eLogInfo, "Garlic: No tags available, will use ElGamal");
if (!m_Destination)
{
LogPrint (eLogError, "Garlic: Can't use ElGamal for unknown destination");
return nullptr;
}
// create ElGamal block
ElGamalBlock elGamal;
memcpy (elGamal.sessionKey, m_SessionKey, 32);
RAND_bytes (elGamal.preIV, 32); // Pre-IV
uint8_t iv[32]; // IV is first 16 bytes
SHA256(elGamal.preIV, 32, iv);
i2p::crypto::ElGamalEncrypt (m_Destination->GetEncryptionPublicKey (), (uint8_t *)&elGamal, buf, true);
m_Encryption.SetIV (iv);
buf += 514;
len += 514;
}
else // existing session
{
// session tag
memcpy (buf, tag, 32);
uint8_t iv[32]; // IV is first 16 bytes
SHA256(tag, 32, iv);
m_Encryption.SetIV (iv);
buf += 32;
len += 32;
}
// AES block
len += CreateAESBlock (buf, msg);
htobe32buf (m->GetPayload (), len);
m->len += len + 4;
m->FillI2NPMessageHeader (eI2NPGarlic);
return m;
}
size_t GarlicRoutingSession::CreateAESBlock (uint8_t * buf, std::shared_ptr<const I2NPMessage> msg)
{
size_t blockSize = 0;
bool createNewTags = m_Owner && m_NumTags && ((int)m_SessionTags.size () <= m_NumTags*2/3);
UnconfirmedTags * newTags = createNewTags ? GenerateSessionTags () : nullptr;
htobuf16 (buf, newTags ? htobe16 (newTags->numTags) : 0); // tag count
blockSize += 2;
if (newTags) // session tags recreated
{
for (int i = 0; i < newTags->numTags; i++)
{
memcpy (buf + blockSize, newTags->sessionTags[i], 32); // tags
blockSize += 32;
}
}
uint32_t * payloadSize = (uint32_t *)(buf + blockSize);
blockSize += 4;
uint8_t * payloadHash = buf + blockSize;
blockSize += 32;
buf[blockSize] = 0; // flag
blockSize++;
size_t len = CreateGarlicPayload (buf + blockSize, msg, newTags);
htobe32buf (payloadSize, len);
SHA256(buf + blockSize, len, payloadHash);
blockSize += len;
size_t rem = blockSize % 16;
if (rem)
blockSize += (16-rem); //padding
m_Encryption.Encrypt(buf, blockSize, buf);
return blockSize;
}
size_t GarlicRoutingSession::CreateGarlicPayload (uint8_t * payload, std::shared_ptr<const I2NPMessage> msg, UnconfirmedTags * newTags)
{
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
uint32_t msgID;
RAND_bytes ((uint8_t *)&msgID, 4);
size_t size = 0;
uint8_t * numCloves = payload + size;
*numCloves = 0;
size++;
if (m_Owner)
{
// resubmit non-confirmed LeaseSet
if (m_LeaseSetUpdateStatus == eLeaseSetSubmitted && ts > m_LeaseSetSubmissionTime + LEASET_CONFIRMATION_TIMEOUT)
{
m_LeaseSetUpdateStatus = eLeaseSetUpdated;
SetSharedRoutingPath (nullptr); // invalidate path since leaseset was not confirmed
}
// attach DeviveryStatus if necessary
if (newTags || m_LeaseSetUpdateStatus == eLeaseSetUpdated) // new tags created or leaseset updated
{
// clove is DeliveryStatus
auto cloveSize = CreateDeliveryStatusClove (payload + size, msgID);
if (cloveSize > 0) // successive?
{
size += cloveSize;
(*numCloves)++;
if (newTags) // new tags created
{
newTags->msgID = msgID;
m_UnconfirmedTagsMsgs.insert (std::make_pair(msgID, std::unique_ptr<UnconfirmedTags>(newTags)));
newTags = nullptr; // got acquired
}
m_Owner->DeliveryStatusSent (shared_from_this (), msgID);
}
else
LogPrint (eLogWarning, "Garlic: DeliveryStatus clove was not created");
}
// attach LeaseSet
if (m_LeaseSetUpdateStatus == eLeaseSetUpdated)
{
if (m_LeaseSetUpdateMsgID) m_Owner->RemoveDeliveryStatusSession (m_LeaseSetUpdateMsgID); // remove previous
m_LeaseSetUpdateStatus = eLeaseSetSubmitted;
m_LeaseSetUpdateMsgID = msgID;
m_LeaseSetSubmissionTime = ts;
// clove if our leaseSet must be attached
auto leaseSet = CreateDatabaseStoreMsg (m_Owner->GetLeaseSet ());
size += CreateGarlicClove (payload + size, leaseSet, false);
(*numCloves)++;
}
}
if (msg) // clove message ifself if presented
{
size += CreateGarlicClove (payload + size, msg, m_Destination ? m_Destination->IsDestination () : false);
(*numCloves)++;
}
memset (payload + size, 0, 3); // certificate of message
size += 3;
htobe32buf (payload + size, msgID); // MessageID
size += 4;
htobe64buf (payload + size, ts + 8000); // Expiration of message, 8 sec
size += 8;
if (newTags) delete newTags; // not acquired, delete
return size;
}
size_t GarlicRoutingSession::CreateGarlicClove (uint8_t * buf, std::shared_ptr<const I2NPMessage> msg, bool isDestination)
{
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch () + 8000; // 8 sec
size_t size = 0;
if (isDestination)
{
buf[size] = eGarlicDeliveryTypeDestination << 5;// delivery instructions flag destination
size++;
memcpy (buf + size, m_Destination->GetIdentHash (), 32);
size += 32;
}
else
{
buf[size] = 0;// delivery instructions flag local
size++;
}
memcpy (buf + size, msg->GetBuffer (), msg->GetLength ());
size += msg->GetLength ();
uint32_t cloveID;
RAND_bytes ((uint8_t *)&cloveID, 4);
htobe32buf (buf + size, cloveID); // CloveID
size += 4;
htobe64buf (buf + size, ts); // Expiration of clove
size += 8;
memset (buf + size, 0, 3); // certificate of clove
size += 3;
return size;
}
size_t GarlicRoutingSession::CreateDeliveryStatusClove (uint8_t * buf, uint32_t msgID)
{
size_t size = 0;
if (m_Owner)
{
auto inboundTunnel = m_Owner->GetTunnelPool ()->GetNextInboundTunnel ();
if (inboundTunnel)
{
buf[size] = eGarlicDeliveryTypeTunnel << 5; // delivery instructions flag tunnel
size++;
// hash and tunnelID sequence is reversed for Garlic
memcpy (buf + size, inboundTunnel->GetNextIdentHash (), 32); // To Hash
size += 32;
htobe32buf (buf + size, inboundTunnel->GetNextTunnelID ()); // tunnelID
size += 4;
// create msg
auto msg = CreateDeliveryStatusMsg (msgID);
if (m_Owner)
{
//encrypt
uint8_t key[32], tag[32];
RAND_bytes (key, 32); // random session key
RAND_bytes (tag, 32); // random session tag
m_Owner->SubmitSessionKey (key, tag);
GarlicRoutingSession garlic (key, tag);
msg = garlic.WrapSingleMessage (msg);
}
memcpy (buf + size, msg->GetBuffer (), msg->GetLength ());
size += msg->GetLength ();
// fill clove
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch () + 8000; // 8 sec
uint32_t cloveID;
RAND_bytes ((uint8_t *)&cloveID, 4);
htobe32buf (buf + size, cloveID); // CloveID
size += 4;
htobe64buf (buf + size, ts); // Expiration of clove
size += 8;
memset (buf + size, 0, 3); // certificate of clove
size += 3;
}
else
LogPrint (eLogError, "Garlic: No inbound tunnels in the pool for DeliveryStatus");
}
else
LogPrint (eLogWarning, "Garlic: Missing local LeaseSet");
return size;
}
GarlicDestination::~GarlicDestination ()
{
}
void GarlicDestination::CleanUp ()
{
m_Sessions.clear ();
m_DeliveryStatusSessions.clear ();
m_Tags.clear ();
}
void GarlicDestination::AddSessionKey (const uint8_t * key, const uint8_t * tag)
{
if (key)
{
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
auto decryption = std::make_shared<i2p::crypto::CBCDecryption>();
decryption->SetKey (key);
m_Tags[SessionTag(tag, ts)] = decryption;
}
}
bool GarlicDestination::SubmitSessionKey (const uint8_t * key, const uint8_t * tag)
{
AddSessionKey (key, tag);
return true;
}
void GarlicDestination::HandleGarlicMessage (std::shared_ptr<I2NPMessage> msg)
{
uint8_t * buf = msg->GetPayload ();
uint32_t length = bufbe32toh (buf);
if (length > msg->GetLength ())
{
LogPrint (eLogWarning, "Garlic: message length ", length, " exceeds I2NP message length ", msg->GetLength ());
return;
}
buf += 4; // length
auto it = m_Tags.find (SessionTag(buf));
if (it != m_Tags.end ())
{
// tag found. Use AES
if (length >= 32)
{
uint8_t iv[32]; // IV is first 16 bytes
SHA256(buf, 32, iv);
it->second->SetIV (iv);
it->second->Decrypt (buf + 32, length - 32, buf + 32);
HandleAESBlock (buf + 32, length - 32, it->second, msg->from);
}
else
LogPrint (eLogWarning, "Garlic: message length ", length, " is less than 32 bytes");
m_Tags.erase (it); // tag might be used only once
}
else
{
// tag not found. Use ElGamal
ElGamalBlock elGamal;
if (length >= 514 && i2p::crypto::ElGamalDecrypt (GetEncryptionPrivateKey (), buf, (uint8_t *)&elGamal, true))
{
auto decryption = std::make_shared<i2p::crypto::CBCDecryption>();
decryption->SetKey (elGamal.sessionKey);
uint8_t iv[32]; // IV is first 16 bytes
SHA256(elGamal.preIV, 32, iv);
decryption->SetIV (iv);
decryption->Decrypt(buf + 514, length - 514, buf + 514);
HandleAESBlock (buf + 514, length - 514, decryption, msg->from);
}
else
LogPrint (eLogError, "Garlic: Failed to decrypt message");
}
}
void GarlicDestination::HandleAESBlock (uint8_t * buf, size_t len, std::shared_ptr<i2p::crypto::CBCDecryption> decryption,
std::shared_ptr<i2p::tunnel::InboundTunnel> from)
{
uint16_t tagCount = bufbe16toh (buf);
buf += 2; len -= 2;
if (tagCount > 0)
{
if (tagCount*32 > len)
{
LogPrint (eLogError, "Garlic: Tag count ", tagCount, " exceeds length ", len);
return ;
}
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
for (int i = 0; i < tagCount; i++)
m_Tags[SessionTag(buf + i*32, ts)] = decryption;
}
buf += tagCount*32;
len -= tagCount*32;
uint32_t payloadSize = bufbe32toh (buf);
if (payloadSize > len)
{
LogPrint (eLogError, "Garlic: Unexpected payload size ", payloadSize);
return;
}
buf += 4;
uint8_t * payloadHash = buf;
buf += 32;// payload hash.
if (*buf) // session key?
buf += 32; // new session key
buf++; // flag
// payload
uint8_t digest[32];
SHA256 (buf, payloadSize, digest);
if (memcmp (payloadHash, digest, 32)) // payload hash doesn't match
{
LogPrint (eLogError, "Garlic: wrong payload hash");
return;
}
HandleGarlicPayload (buf, payloadSize, from);
}
void GarlicDestination::HandleGarlicPayload (uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from)
{
const uint8_t * buf1 = buf;
int numCloves = buf[0];
LogPrint (eLogDebug, "Garlic: ", numCloves," cloves");
buf++;
for (int i = 0; i < numCloves; i++)
{
// delivery instructions
uint8_t flag = buf[0];
buf++; // flag
if (flag & 0x80) // encrypted?
{
// TODO: implement
LogPrint (eLogWarning, "Garlic: clove encrypted");
buf += 32;
}
GarlicDeliveryType deliveryType = (GarlicDeliveryType)((flag >> 5) & 0x03);
switch (deliveryType)
{
case eGarlicDeliveryTypeLocal:
LogPrint (eLogDebug, "Garlic: type local");
HandleI2NPMessage (buf, len, from);
break;
case eGarlicDeliveryTypeDestination:
LogPrint (eLogDebug, "Garlic: type destination");
buf += 32; // destination. check it later or for multiple destinations
HandleI2NPMessage (buf, len, from);
break;
case eGarlicDeliveryTypeTunnel:
{
LogPrint (eLogDebug, "Garlic: type tunnel");
// gwHash and gwTunnel sequence is reverted
uint8_t * gwHash = buf;
buf += 32;
uint32_t gwTunnel = bufbe32toh (buf);
buf += 4;
auto msg = CreateI2NPMessage (buf, GetI2NPMessageLength (buf), from);
if (from) // received through an inbound tunnel
{
std::shared_ptr<i2p::tunnel::OutboundTunnel> tunnel;
if (from->GetTunnelPool ())
tunnel = from->GetTunnelPool ()->GetNextOutboundTunnel ();
else
LogPrint (eLogError, "Garlic: Tunnel pool is not set for inbound tunnel");
if (tunnel) // we have send it through an outbound tunnel
tunnel->SendTunnelDataMsg (gwHash, gwTunnel, msg);
else
LogPrint (eLogWarning, "Garlic: No outbound tunnels available for garlic clove");
}
else // received directly
i2p::transport::transports.SendMessage (gwHash, i2p::CreateTunnelGatewayMsg (gwTunnel, msg)); // send directly
break;
}
case eGarlicDeliveryTypeRouter:
{
uint8_t * ident = buf;
buf += 32;
if (!from) // received directly
i2p::transport::transports.SendMessage (ident,
CreateI2NPMessage (buf, GetI2NPMessageLength (buf)));
else
LogPrint (eLogWarning, "Garlic: type router for inbound tunnels not supported");
break;
}
default:
LogPrint (eLogWarning, "Garlic: unknown delivery type ", (int)deliveryType);
}
buf += GetI2NPMessageLength (buf); // I2NP
buf += 4; // CloveID
buf += 8; // Date
buf += 3; // Certificate
if (buf - buf1 > (int)len)
{
LogPrint (eLogError, "Garlic: clove is too long");
break;
}
}
}
std::shared_ptr<I2NPMessage> GarlicDestination::WrapMessage (std::shared_ptr<const i2p::data::RoutingDestination> destination,
std::shared_ptr<I2NPMessage> msg, bool attachLeaseSet)
{
auto session = GetRoutingSession (destination, attachLeaseSet);
return session->WrapSingleMessage (msg);
}
std::shared_ptr<GarlicRoutingSession> GarlicDestination::GetRoutingSession (
std::shared_ptr<const i2p::data::RoutingDestination> destination, bool attachLeaseSet)
{
GarlicRoutingSessionPtr session;
{
std::unique_lock<std::mutex> l(m_SessionsMutex);
auto it = m_Sessions.find (destination->GetIdentHash ());
if (it != m_Sessions.end ())
session = it->second;
}
if (!session)
{
session = std::make_shared<GarlicRoutingSession> (this, destination,
attachLeaseSet ? m_NumTags : 4, attachLeaseSet); // specified num tags for connections and 4 for LS requests
std::unique_lock<std::mutex> l(m_SessionsMutex);
m_Sessions[destination->GetIdentHash ()] = session;
}
return session;
}
void GarlicDestination::CleanupExpiredTags ()
{
// incoming
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
int numExpiredTags = 0;
for (auto it = m_Tags.begin (); it != m_Tags.end ();)
{
if (ts > it->first.creationTime + INCOMING_TAGS_EXPIRATION_TIMEOUT)
{
numExpiredTags++;
it = m_Tags.erase (it);
}
else
++it;
}
if (numExpiredTags > 0)
LogPrint (eLogDebug, "Garlic: ", numExpiredTags, " tags expired for ", GetIdentHash().ToBase64 ());
// outgoing
{
std::unique_lock<std::mutex> l(m_SessionsMutex);
for (auto it = m_Sessions.begin (); it != m_Sessions.end ();)
{
it->second->GetSharedRoutingPath (); // delete shared path if necessary
if (!it->second->CleanupExpiredTags ())
{
LogPrint (eLogInfo, "Routing session to ", it->first.ToBase32 (), " deleted");
it->second->SetOwner (nullptr);
it = m_Sessions.erase (it);
}
else
++it;
}
}
// delivery status sessions
{
std::unique_lock<std::mutex> l(m_DeliveryStatusSessionsMutex);
for (auto it = m_DeliveryStatusSessions.begin (); it != m_DeliveryStatusSessions.end (); )
{
if (it->second->GetOwner () != this)
it = m_DeliveryStatusSessions.erase (it);
else
++it;
}
}
}
void GarlicDestination::RemoveDeliveryStatusSession (uint32_t msgID)
{
std::unique_lock<std::mutex> l(m_DeliveryStatusSessionsMutex);
m_DeliveryStatusSessions.erase (msgID);
}
void GarlicDestination::DeliveryStatusSent (GarlicRoutingSessionPtr session, uint32_t msgID)
{
std::unique_lock<std::mutex> l(m_DeliveryStatusSessionsMutex);
m_DeliveryStatusSessions[msgID] = session;
}
void GarlicDestination::HandleDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg)
{
uint32_t msgID = bufbe32toh (msg->GetPayload ());
GarlicRoutingSessionPtr session;
{
std::unique_lock<std::mutex> l(m_DeliveryStatusSessionsMutex);
auto it = m_DeliveryStatusSessions.find (msgID);
if (it != m_DeliveryStatusSessions.end ())
{
session = it->second;
m_DeliveryStatusSessions.erase (it);
}
}
if (session)
{
session->MessageConfirmed (msgID);
LogPrint (eLogDebug, "Garlic: message ", msgID, " acknowledged");
}
}
void GarlicDestination::SetLeaseSetUpdated ()
{
std::unique_lock<std::mutex> l(m_SessionsMutex);
for (auto& it: m_Sessions)
it.second->SetLeaseSetUpdated ();
}
void GarlicDestination::ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg)
{
HandleGarlicMessage (msg);
}
void GarlicDestination::ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg)
{
HandleDeliveryStatusMessage (msg);
}
}
}

211
Garlic.h
View File

@ -1,211 +0,0 @@
#ifndef GARLIC_H__
#define GARLIC_H__
#include <inttypes.h>
#include <map>
#include <list>
#include <string>
#include <thread>
#include <mutex>
#include <memory>
#include "Crypto.h"
#include "I2NPProtocol.h"
#include "LeaseSet.h"
#include "Queue.h"
#include "Identity.h"
namespace i2p
{
namespace tunnel
{
class OutboundTunnel;
}
namespace garlic
{
enum GarlicDeliveryType
{
eGarlicDeliveryTypeLocal = 0,
eGarlicDeliveryTypeDestination = 1,
eGarlicDeliveryTypeRouter = 2,
eGarlicDeliveryTypeTunnel = 3
};
struct ElGamalBlock
{
uint8_t sessionKey[32];
uint8_t preIV[32];
uint8_t padding[158];
};
const int INCOMING_TAGS_EXPIRATION_TIMEOUT = 960; // 16 minutes
const int OUTGOING_TAGS_EXPIRATION_TIMEOUT = 720; // 12 minutes
const int OUTGOING_TAGS_CONFIRMATION_TIMEOUT = 10; // 10 seconds
const int LEASET_CONFIRMATION_TIMEOUT = 4000; // in milliseconds
const int ROUTING_PATH_EXPIRATION_TIMEOUT = 30; // 30 seconds
const int ROUTING_PATH_MAX_NUM_TIMES_USED = 100; // how many times might be used
struct SessionTag: public i2p::data::Tag<32>
{
SessionTag (const uint8_t * buf, uint32_t ts = 0): Tag<32>(buf), creationTime (ts) {};
SessionTag () = default;
SessionTag (const SessionTag& ) = default;
SessionTag& operator= (const SessionTag& ) = default;
#ifndef _WIN32
SessionTag (SessionTag&& ) = default;
SessionTag& operator= (SessionTag&& ) = default;
#endif
uint32_t creationTime; // seconds since epoch
};
struct GarlicRoutingPath
{
std::shared_ptr<i2p::tunnel::OutboundTunnel> outboundTunnel;
std::shared_ptr<const i2p::data::Lease> remoteLease;
int rtt; // RTT
uint32_t updateTime; // seconds since epoch
int numTimesUsed;
};
class GarlicDestination;
class GarlicRoutingSession: public std::enable_shared_from_this<GarlicRoutingSession>
{
enum LeaseSetUpdateStatus
{
eLeaseSetUpToDate = 0,
eLeaseSetUpdated,
eLeaseSetSubmitted,
eLeaseSetDoNotSend
};
struct UnconfirmedTags
{
UnconfirmedTags (int n): numTags (n), tagsCreationTime (0) { sessionTags = new SessionTag[numTags]; };
~UnconfirmedTags () { delete[] sessionTags; };
uint32_t msgID;
int numTags;
SessionTag * sessionTags;
uint32_t tagsCreationTime;
};
public:
GarlicRoutingSession (GarlicDestination * owner, std::shared_ptr<const i2p::data::RoutingDestination> destination,
int numTags, bool attachLeaseSet);
GarlicRoutingSession (const uint8_t * sessionKey, const SessionTag& sessionTag); // one time encryption
~GarlicRoutingSession ();
std::shared_ptr<I2NPMessage> WrapSingleMessage (std::shared_ptr<const I2NPMessage> msg);
void MessageConfirmed (uint32_t msgID);
bool CleanupExpiredTags (); // returns true if something left
bool CleanupUnconfirmedTags (); // returns true if something has been deleted
void SetLeaseSetUpdated ()
{
if (m_LeaseSetUpdateStatus != eLeaseSetDoNotSend) m_LeaseSetUpdateStatus = eLeaseSetUpdated;
};
bool IsLeaseSetNonConfirmed () const { return m_LeaseSetUpdateStatus == eLeaseSetSubmitted; };
bool IsLeaseSetUpdated () const { return m_LeaseSetUpdateStatus == eLeaseSetUpdated; };
uint64_t GetLeaseSetSubmissionTime () const { return m_LeaseSetSubmissionTime; }
std::shared_ptr<GarlicRoutingPath> GetSharedRoutingPath ();
void SetSharedRoutingPath (std::shared_ptr<GarlicRoutingPath> path);
const GarlicDestination * GetOwner () const { return m_Owner; }
void SetOwner (GarlicDestination * owner) { m_Owner = owner; }
private:
size_t CreateAESBlock (uint8_t * buf, std::shared_ptr<const I2NPMessage> msg);
size_t CreateGarlicPayload (uint8_t * payload, std::shared_ptr<const I2NPMessage> msg, UnconfirmedTags * newTags);
size_t CreateGarlicClove (uint8_t * buf, std::shared_ptr<const I2NPMessage> msg, bool isDestination);
size_t CreateDeliveryStatusClove (uint8_t * buf, uint32_t msgID);
void TagsConfirmed (uint32_t msgID);
UnconfirmedTags * GenerateSessionTags ();
private:
GarlicDestination * m_Owner;
std::shared_ptr<const i2p::data::RoutingDestination> m_Destination;
i2p::crypto::AESKey m_SessionKey;
std::list<SessionTag> m_SessionTags;
int m_NumTags;
std::map<uint32_t, std::unique_ptr<UnconfirmedTags> > m_UnconfirmedTagsMsgs; // msgID->tags
LeaseSetUpdateStatus m_LeaseSetUpdateStatus;
uint32_t m_LeaseSetUpdateMsgID;
uint64_t m_LeaseSetSubmissionTime; // in milliseconds
i2p::crypto::CBCEncryption m_Encryption;
std::shared_ptr<GarlicRoutingPath> m_SharedRoutingPath;
public:
// for HTTP only
size_t GetNumOutgoingTags () const { return m_SessionTags.size (); };
};
//using GarlicRoutingSessionPtr = std::shared_ptr<GarlicRoutingSession>;
typedef std::shared_ptr<GarlicRoutingSession> GarlicRoutingSessionPtr; // TODO: replace to using after switch to 4.8
class GarlicDestination: public i2p::data::LocalDestination
{
public:
GarlicDestination (): m_NumTags (32) {}; // 32 tags by default
~GarlicDestination ();
void CleanUp ();
void SetNumTags (int numTags) { m_NumTags = numTags; };
std::shared_ptr<GarlicRoutingSession> GetRoutingSession (std::shared_ptr<const i2p::data::RoutingDestination> destination, bool attachLeaseSet);
void CleanupExpiredTags ();
void RemoveDeliveryStatusSession (uint32_t msgID);
std::shared_ptr<I2NPMessage> WrapMessage (std::shared_ptr<const i2p::data::RoutingDestination> destination,
std::shared_ptr<I2NPMessage> msg, bool attachLeaseSet = false);
void AddSessionKey (const uint8_t * key, const uint8_t * tag); // one tag
virtual bool SubmitSessionKey (const uint8_t * key, const uint8_t * tag); // from different thread
void DeliveryStatusSent (GarlicRoutingSessionPtr session, uint32_t msgID);
virtual void ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg);
virtual void ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg);
virtual void SetLeaseSetUpdated ();
virtual std::shared_ptr<const i2p::data::LocalLeaseSet> GetLeaseSet () = 0; // TODO
virtual std::shared_ptr<i2p::tunnel::TunnelPool> GetTunnelPool () const = 0;
virtual void HandleI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from) = 0;
protected:
void HandleGarlicMessage (std::shared_ptr<I2NPMessage> msg);
void HandleDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg);
private:
void HandleAESBlock (uint8_t * buf, size_t len, std::shared_ptr<i2p::crypto::CBCDecryption> decryption,
std::shared_ptr<i2p::tunnel::InboundTunnel> from);
void HandleGarlicPayload (uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from);
private:
// outgoing sessions
int m_NumTags;
std::mutex m_SessionsMutex;
std::map<i2p::data::IdentHash, GarlicRoutingSessionPtr> m_Sessions;
// incoming
std::map<SessionTag, std::shared_ptr<i2p::crypto::CBCDecryption>> m_Tags;
// DeliveryStatus
std::mutex m_DeliveryStatusSessionsMutex;
std::map<uint32_t, GarlicRoutingSessionPtr> m_DeliveryStatusSessions; // msgID -> session
public:
// for HTTP only
size_t GetNumIncomingTags () const { return m_Tags.size (); }
const decltype(m_Sessions)& GetSessions () const { return m_Sessions; };
};
}
}
#endif

115
Gzip.cpp
View File

@ -1,115 +0,0 @@
/*
* Copyright (c) 2013-2017, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <inttypes.h>
#include <string.h> /* memset */
#include <iostream>
#include "Log.h"
#include "Gzip.h"
namespace i2p
{
namespace data
{
const size_t GZIP_CHUNK_SIZE = 16384;
GzipInflator::GzipInflator (): m_IsDirty (false)
{
memset (&m_Inflator, 0, sizeof (m_Inflator));
inflateInit2 (&m_Inflator, MAX_WBITS + 16); // gzip
}
GzipInflator::~GzipInflator ()
{
inflateEnd (&m_Inflator);
}
size_t GzipInflator::Inflate (const uint8_t * in, size_t inLen, uint8_t * out, size_t outLen)
{
if (m_IsDirty) inflateReset (&m_Inflator);
m_IsDirty = true;
m_Inflator.next_in = const_cast<uint8_t *>(in);
m_Inflator.avail_in = inLen;
m_Inflator.next_out = out;
m_Inflator.avail_out = outLen;
int err;
if ((err = inflate (&m_Inflator, Z_NO_FLUSH)) == Z_STREAM_END)
return outLen - m_Inflator.avail_out;
// else
LogPrint (eLogError, "Gzip: Inflate error ", err);
return 0;
}
void GzipInflator::Inflate (const uint8_t * in, size_t inLen, std::ostream& os)
{
m_IsDirty = true;
uint8_t * out = new uint8_t[GZIP_CHUNK_SIZE];
m_Inflator.next_in = const_cast<uint8_t *>(in);
m_Inflator.avail_in = inLen;
int ret;
do
{
m_Inflator.next_out = out;
m_Inflator.avail_out = GZIP_CHUNK_SIZE;
ret = inflate (&m_Inflator, Z_NO_FLUSH);
if (ret < 0)
{
inflateEnd (&m_Inflator);
os.setstate(std::ios_base::failbit);
break;
}
os.write ((char *)out, GZIP_CHUNK_SIZE - m_Inflator.avail_out);
}
while (!m_Inflator.avail_out); // more data to read
delete[] out;
}
void GzipInflator::Inflate (std::istream& in, std::ostream& out)
{
uint8_t * buf = new uint8_t[GZIP_CHUNK_SIZE];
while (!in.eof ())
{
in.read ((char *) buf, GZIP_CHUNK_SIZE);
Inflate (buf, in.gcount (), out);
}
delete[] buf;
}
GzipDeflator::GzipDeflator (): m_IsDirty (false)
{
memset (&m_Deflator, 0, sizeof (m_Deflator));
deflateInit2 (&m_Deflator, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY); // 15 + 16 sets gzip
}
GzipDeflator::~GzipDeflator ()
{
deflateEnd (&m_Deflator);
}
void GzipDeflator::SetCompressionLevel (int level)
{
deflateParams (&m_Deflator, level, Z_DEFAULT_STRATEGY);
}
size_t GzipDeflator::Deflate (const uint8_t * in, size_t inLen, uint8_t * out, size_t outLen)
{
if (m_IsDirty) deflateReset (&m_Deflator);
m_IsDirty = true;
m_Deflator.next_in = const_cast<uint8_t *>(in);
m_Deflator.avail_in = inLen;
m_Deflator.next_out = out;
m_Deflator.avail_out = outLen;
int err;
if ((err = deflate (&m_Deflator, Z_FINISH)) == Z_STREAM_END)
return outLen - m_Deflator.avail_out;
// else
LogPrint (eLogError, "Gzip: Deflate error ", err);
return 0;
}
} // data
} // i2p

482
HTTP.cpp
View File

@ -1,482 +0,0 @@
/*
* Copyright (c) 2013-2017, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <algorithm>
#include <utility>
#include "util.h"
#include "HTTP.h"
#include <ctime>
namespace i2p {
namespace http {
const std::vector<std::string> HTTP_METHODS = {
"GET", "HEAD", "POST", "PUT", "PATCH",
"DELETE", "OPTIONS", "CONNECT"
};
const std::vector<std::string> HTTP_VERSIONS = {
"HTTP/1.0", "HTTP/1.1"
};
inline bool is_http_version(const std::string & str) {
return std::find(HTTP_VERSIONS.begin(), HTTP_VERSIONS.end(), str) != std::end(HTTP_VERSIONS);
}
inline bool is_http_method(const std::string & str) {
return std::find(HTTP_METHODS.begin(), HTTP_METHODS.end(), str) != std::end(HTTP_METHODS);
}
void strsplit(const std::string & line, std::vector<std::string> &tokens, char delim, std::size_t limit = 0) {
std::size_t count = 0;
std::stringstream ss(line);
std::string token;
while (1) {
count++;
if (limit > 0 && count >= limit)
delim = '\n'; /* reset delimiter */
if (!std::getline(ss, token, delim))
break;
tokens.push_back(token);
}
}
static std::pair<std::string, std::string> parse_header_line(const std::string& line)
{
std::size_t pos = 0;
std::size_t len = 2; /* strlen(": ") */
std::size_t max = line.length();
if ((pos = line.find(": ", pos)) == std::string::npos)
return std::make_pair("", "");
while ((pos + len) < max && isspace(line.at(pos + len)))
len++;
return std::make_pair(line.substr(0, pos), line.substr(pos + len));
}
void gen_rfc1123_date(std::string & out) {
std::time_t now = std::time(nullptr);
char buf[128];
std::strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", std::gmtime(&now));
out = buf;
}
bool URL::parse(const char *str, std::size_t len) {
std::string url(str, len ? len : strlen(str));
return parse(url);
}
bool URL::parse(const std::string& url) {
std::size_t pos_p = 0; /* < current parse position */
std::size_t pos_c = 0; /* < work position */
if(url.at(0) != '/' || pos_p > 0) {
std::size_t pos_s = 0;
/* schema */
pos_c = url.find("://");
if (pos_c != std::string::npos) {
schema = url.substr(0, pos_c);
pos_p = pos_c + 3;
}
/* user[:pass] */
pos_s = url.find('/', pos_p); /* find first slash */
pos_c = url.find('@', pos_p); /* find end of 'user' or 'user:pass' part */
if (pos_c != std::string::npos && (pos_s == std::string::npos || pos_s > pos_c)) {
std::size_t delim = url.find(':', pos_p);
if (delim != std::string::npos && delim < pos_c) {
user = url.substr(pos_p, delim - pos_p);
delim += 1;
pass = url.substr(delim, pos_c - delim);
} else {
user = url.substr(pos_p, pos_c - pos_p);
}
pos_p = pos_c + 1;
}
/* hostname[:port][/path] */
pos_c = url.find_first_of(":/", pos_p);
if (pos_c == std::string::npos) {
/* only hostname, without post and path */
host = url.substr(pos_p, std::string::npos);
return true;
} else if (url.at(pos_c) == ':') {
host = url.substr(pos_p, pos_c - pos_p);
/* port[/path] */
pos_p = pos_c + 1;
pos_c = url.find('/', pos_p);
std::string port_str = (pos_c == std::string::npos)
? url.substr(pos_p, std::string::npos)
: url.substr(pos_p, pos_c - pos_p);
/* stoi throws exception on failure, we don't need it */
for (char c : port_str) {
if (c < '0' || c > '9')
return false;
port *= 10;
port += c - '0';
}
if (pos_c == std::string::npos)
return true; /* no path part */
pos_p = pos_c;
} else {
/* start of path part found */
host = url.substr(pos_p, pos_c - pos_p);
pos_p = pos_c;
}
}
/* pos_p now at start of path part */
pos_c = url.find_first_of("?#", pos_p);
if (pos_c == std::string::npos) {
/* only path, without fragment and query */
path = url.substr(pos_p, std::string::npos);
return true;
} else if (url.at(pos_c) == '?') {
/* found query part */
path = url.substr(pos_p, pos_c - pos_p);
pos_p = pos_c + 1;
pos_c = url.find('#', pos_p);
if (pos_c == std::string::npos) {
/* no fragment */
query = url.substr(pos_p, std::string::npos);
return true;
} else {
query = url.substr(pos_p, pos_c - pos_p);
pos_p = pos_c + 1;
}
} else {
/* found fragment part */
path = url.substr(pos_p, pos_c - pos_p);
pos_p = pos_c + 1;
}
/* pos_p now at start of fragment part */
frag = url.substr(pos_p, std::string::npos);
return true;
}
bool URL::parse_query(std::map<std::string, std::string> & params) {
std::vector<std::string> tokens;
strsplit(query, tokens, '&');
params.clear();
for (const auto& it : tokens) {
std::size_t eq = it.find ('=');
if (eq != std::string::npos) {
auto e = std::pair<std::string, std::string>(it.substr(0, eq), it.substr(eq + 1));
params.insert(e);
} else {
auto e = std::pair<std::string, std::string>(it, "");
params.insert(e);
}
}
return true;
}
std::string URL::to_string() {
std::string out = "";
if (schema != "") {
out = schema + "://";
if (user != "" && pass != "") {
out += user + ":" + pass + "@";
} else if (user != "") {
out += user + "@";
}
if (port) {
out += host + ":" + std::to_string(port);
} else {
out += host;
}
}
out += path;
if (query != "")
out += "?" + query;
if (frag != "")
out += "#" + frag;
return out;
}
void HTTPMsg::add_header(const char *name, std::string & value, bool replace) {
add_header(name, value.c_str(), replace);
}
void HTTPMsg::add_header(const char *name, const char *value, bool replace) {
std::size_t count = headers.count(name);
if (count && !replace)
return;
if (count) {
headers[name] = value;
return;
}
headers.insert(std::pair<std::string, std::string>(name, value));
}
void HTTPMsg::del_header(const char *name) {
headers.erase(name);
}
int HTTPReq::parse(const char *buf, size_t len) {
std::string str(buf, len);
return parse(str);
}
int HTTPReq::parse(const std::string& str) {
enum { REQ_LINE, HEADER_LINE } expect = REQ_LINE;
std::size_t eoh = str.find(HTTP_EOH); /* request head size */
std::size_t eol = 0, pos = 0;
URL url;
if (eoh == std::string::npos)
return 0; /* str not contains complete request */
while ((eol = str.find(CRLF, pos)) != std::string::npos) {
if (expect == REQ_LINE) {
std::string line = str.substr(pos, eol - pos);
std::vector<std::string> tokens;
strsplit(line, tokens, ' ');
if (tokens.size() != 3)
return -1;
if (!is_http_method(tokens[0]))
return -1;
if (!is_http_version(tokens[2]))
return -1;
if (!url.parse(tokens[1]))
return -1;
/* all ok */
method = tokens[0];
uri = tokens[1];
version = tokens[2];
expect = HEADER_LINE;
}
else
{
std::string line = str.substr(pos, eol - pos);
auto p = parse_header_line(line);
if (p.first.length () > 0)
headers.push_back (p);
else
return -1;
}
pos = eol + strlen(CRLF);
if (pos >= eoh)
break;
}
return eoh + strlen(HTTP_EOH);
}
void HTTPReq::write(std::ostream & o)
{
o << method << " " << uri << " " << version << CRLF;
for (auto & h : headers)
o << h.first << ": " << h.second << CRLF;
o << CRLF;
}
std::string HTTPReq::to_string()
{
std::stringstream ss;
write(ss);
return ss.str();
}
void HTTPReq::AddHeader (const std::string& name, const std::string& value)
{
headers.push_back (std::make_pair(name, value));
}
void HTTPReq::UpdateHeader (const std::string& name, const std::string& value)
{
for (auto& it : headers)
if (it.first == name)
{
it.second = value;
break;
}
}
void HTTPReq::RemoveHeader (const std::string& name)
{
for (auto it = headers.begin (); it != headers.end ();)
{
if (!it->first.compare(0, name.length (), name))
it = headers.erase (it);
else
it++;
}
}
std::string HTTPReq::GetHeader (const std::string& name) const
{
for (auto& it : headers)
if (it.first == name)
return it.second;
return "";
}
bool HTTPRes::is_chunked() const
{
auto it = headers.find("Transfer-Encoding");
if (it == headers.end())
return false;
if (it->second.find("chunked") == std::string::npos)
return true;
return false;
}
bool HTTPRes::is_gzipped(bool includingI2PGzip) const
{
auto it = headers.find("Content-Encoding");
if (it == headers.end())
return false; /* no header */
if (it->second.find("gzip") != std::string::npos)
return true; /* gotcha! */
if (includingI2PGzip && it->second.find("x-i2p-gzip") != std::string::npos)
return true;
return false;
}
long int HTTPMsg::content_length() const
{
unsigned long int length = 0;
auto it = headers.find("Content-Length");
if (it == headers.end())
return -1;
errno = 0;
length = std::strtoul(it->second.c_str(), (char **) NULL, 10);
if (errno != 0)
return -1;
return length;
}
int HTTPRes::parse(const char *buf, size_t len) {
std::string str(buf, len);
return parse(str);
}
int HTTPRes::parse(const std::string& str) {
enum { RES_LINE, HEADER_LINE } expect = RES_LINE;
std::size_t eoh = str.find(HTTP_EOH); /* request head size */
std::size_t eol = 0, pos = 0;
if (eoh == std::string::npos)
return 0; /* str not contains complete request */
while ((eol = str.find(CRLF, pos)) != std::string::npos) {
if (expect == RES_LINE) {
std::string line = str.substr(pos, eol - pos);
std::vector<std::string> tokens;
strsplit(line, tokens, ' ', 3);
if (tokens.size() != 3)
return -1;
if (!is_http_version(tokens[0]))
return -1;
code = atoi(tokens[1].c_str());
if (code < 100 || code >= 600)
return -1;
/* all ok */
version = tokens[0];
status = tokens[2];
expect = HEADER_LINE;
} else {
std::string line = str.substr(pos, eol - pos);
auto p = parse_header_line(line);
if (p.first.length () > 0)
headers.insert (p);
else
return -1;
}
pos = eol + strlen(CRLF);
if (pos >= eoh)
break;
}
return eoh + strlen(HTTP_EOH);
}
std::string HTTPRes::to_string() {
if (version == "HTTP/1.1" && headers.count("Date") == 0) {
std::string date;
gen_rfc1123_date(date);
add_header("Date", date.c_str());
}
if (status == "OK" && code != 200)
status = HTTPCodeToStatus(code); // update
if (body.length() > 0 && headers.count("Content-Length") == 0)
add_header("Content-Length", std::to_string(body.length()).c_str());
/* build response */
std::stringstream ss;
ss << version << " " << code << " " << status << CRLF;
for (auto & h : headers) {
ss << h.first << ": " << h.second << CRLF;
}
ss << CRLF;
if (body.length() > 0)
ss << body;
return ss.str();
}
const char * HTTPCodeToStatus(int code) {
const char *ptr;
switch (code) {
case 105: ptr = "Name Not Resolved"; break;
/* success */
case 200: ptr = "OK"; break;
case 206: ptr = "Partial Content"; break;
/* redirect */
case 301: ptr = "Moved Permanently"; break;
case 302: ptr = "Found"; break;
case 304: ptr = "Not Modified"; break;
case 307: ptr = "Temporary Redirect"; break;
/* client error */
case 400: ptr = "Bad Request"; break;
case 401: ptr = "Unauthorized"; break;
case 403: ptr = "Forbidden"; break;
case 404: ptr = "Not Found"; break;
case 407: ptr = "Proxy Authentication Required"; break;
case 408: ptr = "Request Timeout"; break;
/* server error */
case 500: ptr = "Internal Server Error"; break;
case 502: ptr = "Bad Gateway"; break;
case 503: ptr = "Not Implemented"; break;
case 504: ptr = "Gateway Timeout"; break;
default: ptr = "Unknown Status"; break;
}
return ptr;
}
std::string UrlDecode(const std::string& data, bool allow_null) {
std::string decoded(data);
size_t pos = 0;
while ((pos = decoded.find('%', pos)) != std::string::npos) {
char c = strtol(decoded.substr(pos + 1, 2).c_str(), NULL, 16);
if (c == '\0' && !allow_null) {
pos += 3;
continue;
}
decoded.replace(pos, 3, 1, c);
pos++;
}
return decoded;
}
bool MergeChunkedResponse (std::istream& in, std::ostream& out) {
std::string hexLen;
while (!in.eof ()) {
std::getline (in, hexLen);
errno = 0;
long int len = strtoul(hexLen.c_str(), (char **) NULL, 16);
if (errno != 0)
return false; /* conversion error */
if (len == 0)
return true; /* end of stream */
if (len < 0 || len > 10 * 1024 * 1024) /* < 10Mb */
return false; /* too large chunk */
char * buf = new char[len];
in.read (buf, len);
out.write (buf, len);
delete[] buf;
std::getline (in, hexLen); // read \r\n after chunk
}
return true;
}
} // http
} // i2p

163
HTTP.h
View File

@ -1,163 +0,0 @@
/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#ifndef HTTP_H__
#define HTTP_H__
#include <cstring>
#include <map>
#include <list>
#include <sstream>
#include <string>
#include <vector>
namespace i2p {
namespace http {
const char CRLF[] = "\r\n"; /**< HTTP line terminator */
const char HTTP_EOH[] = "\r\n\r\n"; /**< HTTP end-of-headers mark */
extern const std::vector<std::string> HTTP_METHODS; /**< list of valid HTTP methods */
extern const std::vector<std::string> HTTP_VERSIONS; /**< list of valid HTTP versions */
struct URL {
std::string schema;
std::string user;
std::string pass;
std::string host;
unsigned short int port;
std::string path;
std::string query;
std::string frag;
URL(): schema(""), user(""), pass(""), host(""), port(0), path(""), query(""), frag("") {};
/**
* @brief Tries to parse url from string
* @return true on success, false on invalid url
*/
bool parse (const char *str, std::size_t len = 0);
bool parse (const std::string& url);
/**
* @brief Parse query part of url to key/value map
* @note Honestly, this should be implemented with std::multimap
*/
bool parse_query(std::map<std::string, std::string> & params);
/**
* @brief Serialize URL structure to url
* @note Returns relative url if schema if empty, absolute url otherwise
*/
std::string to_string ();
};
struct HTTPMsg
{
std::map<std::string, std::string> headers;
void add_header(const char *name, std::string & value, bool replace = false);
void add_header(const char *name, const char *value, bool replace = false);
void del_header(const char *name);
/** @brief Returns declared message length or -1 if unknown */
long int content_length() const;
};
struct HTTPReq
{
std::list<std::pair<std::string, std::string> > headers;
std::string version;
std::string method;
std::string uri;
HTTPReq (): version("HTTP/1.0"), method("GET"), uri("/") {};
/**
* @brief Tries to parse HTTP request from string
* @return -1 on error, 0 on incomplete query, >0 on success
* @note Positive return value is a size of header
*/
int parse(const char *buf, size_t len);
int parse(const std::string& buf);
/** @brief Serialize HTTP request to string */
std::string to_string();
void write(std::ostream & o);
void AddHeader (const std::string& name, const std::string& value);
void UpdateHeader (const std::string& name, const std::string& value);
void RemoveHeader (const std::string& name);
std::string GetHeader (const std::string& name) const;
};
struct HTTPRes : HTTPMsg {
std::string version;
std::string status;
unsigned short int code;
/**
* @brief Simplifies response generation
*
* If this variable is set, on @a to_string() call:
* * Content-Length header will be added if missing,
* * contents of @a body will be included in generated response
*/
std::string body;
HTTPRes (): version("HTTP/1.1"), status("OK"), code(200) {}
/**
* @brief Tries to parse HTTP response from string
* @return -1 on error, 0 on incomplete query, >0 on success
* @note Positive return value is a size of header
*/
int parse(const char *buf, size_t len);
int parse(const std::string& buf);
/**
* @brief Serialize HTTP response to string
* @note If @a version is set to HTTP/1.1, and Date header is missing,
* it will be generated based on current time and added to headers
* @note If @a body is set and Content-Length header is missing,
* this header will be added, based on body's length
*/
std::string to_string();
void write(std::ostream & o);
/** @brief Checks that response declared as chunked data */
bool is_chunked() const ;
/** @brief Checks that response contains compressed data */
bool is_gzipped(bool includingI2PGzip = true) const;
};
/**
* @brief returns HTTP status string by integer code
* @param code HTTP code [100, 599]
* @return Immutable string with status
*/
const char * HTTPCodeToStatus(int code);
/**
* @brief Replaces %-encoded characters in string with their values
* @param data Source string
* @param null If set to true - decode also %00 sequence, otherwise - skip
* @return Decoded string
*/
std::string UrlDecode(const std::string& data, bool null = false);
/**
* @brief Merge HTTP response content with Transfer-Encoding: chunked
* @param in Input stream
* @param out Output stream
* @return true on success, false otherwise
*/
bool MergeChunkedResponse (std::istream& in, std::ostream& out);
} // http
} // i2p
#endif /* HTTP_H__ */

View File

@ -1,517 +0,0 @@
#include <cstring>
#include <cassert>
#include <string>
#include <atomic>
#include <memory>
#include <set>
#include <boost/asio.hpp>
#include <mutex>
#include "I2PService.h"
#include "Destination.h"
#include "HTTPProxy.h"
#include "util.h"
#include "Identity.h"
#include "Streaming.h"
#include "Destination.h"
#include "ClientContext.h"
#include "I2PEndian.h"
#include "I2PTunnel.h"
#include "Config.h"
#include "HTTP.h"
namespace i2p {
namespace proxy {
std::map<std::string, std::string> jumpservices = {
{ "inr.i2p", "http://joajgazyztfssty4w2on5oaqksz6tqoxbduy553y34mf4byv6gpq.b32.i2p/search/?q=" },
{ "stats.i2p", "http://7tbay5p4kzeekxvyvbf6v7eauazemsnnl2aoyqhg5jzpr5eke7tq.b32.i2p/cgi-bin/jump.cgi?a=" },
};
static const char *pageHead =
"<head>\r\n"
" <title>I2Pd HTTP proxy</title>\r\n"
" <style type=\"text/css\">\r\n"
" body { font: 100%/1.5em sans-serif; margin: 0; padding: 1.5em; background: #FAFAFA; color: #103456; }\r\n"
" .header { font-size: 2.5em; text-align: center; margin: 1.5em 0; color: #894C84; }\r\n"
" </style>\r\n"
"</head>\r\n"
;
bool str_rmatch(std::string & str, const char *suffix) {
auto pos = str.rfind (suffix);
if (pos == std::string::npos)
return false; /* not found */
if (str.length() == (pos + std::strlen(suffix)))
return true; /* match */
return false;
}
class HTTPReqHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPReqHandler>
{
private:
bool HandleRequest();
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
void Terminate();
void AsyncSockRead();
bool ExtractAddressHelper(i2p::http::URL & url, std::string & b64);
void SanitizeHTTPRequest(i2p::http::HTTPReq & req);
void SentHTTPFailed(const boost::system::error_code & ecode);
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
/* error helpers */
void GenericProxyError(const char *title, const char *description);
void GenericProxyInfo(const char *title, const char *description);
void HostNotFound(std::string & host);
void SendProxyError(std::string & content);
void ForwardToUpstreamProxy();
void HandleUpstreamHTTPProxyConnect(const boost::system::error_code & ec);
void HandleUpstreamSocksProxyConnect(const boost::system::error_code & ec);
void HandleSocksProxySendHandshake(const boost::system::error_code & ec, std::size_t bytes_transfered);
void HandleSocksProxyReply(const boost::system::error_code & ec, std::size_t bytes_transfered);
typedef std::function<void(boost::asio::ip::tcp::endpoint)> ProxyResolvedHandler;
void HandleUpstreamProxyResolved(const boost::system::error_code & ecode, boost::asio::ip::tcp::resolver::iterator itr, ProxyResolvedHandler handler);
void SocksProxySuccess();
void HandoverToUpstreamProxy();
uint8_t m_recv_chunk[8192];
std::string m_recv_buf; // from client
std::string m_send_buf; // to upstream
std::shared_ptr<boost::asio::ip::tcp::socket> m_sock;
std::shared_ptr<boost::asio::ip::tcp::socket> m_proxysock;
boost::asio::ip::tcp::resolver m_proxy_resolver;
i2p::http::URL m_ProxyURL;
i2p::http::URL m_RequestURL;
uint8_t m_socks_buf[255+8]; // for socks request/response
ssize_t m_req_len;
i2p::http::URL m_ClientRequestURL;
i2p::http::HTTPReq m_ClientRequest;
i2p::http::HTTPRes m_ClientResponse;
std::stringstream m_ClientRequestBuffer;
public:
HTTPReqHandler(HTTPProxy * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) :
I2PServiceHandler(parent), m_sock(sock),
m_proxysock(std::make_shared<boost::asio::ip::tcp::socket>(parent->GetService())),
m_proxy_resolver(parent->GetService()) {}
~HTTPReqHandler() { Terminate(); }
void Handle () { AsyncSockRead(); } /* overload */
};
void HTTPReqHandler::AsyncSockRead()
{
LogPrint(eLogDebug, "HTTPProxy: async sock read");
if (!m_sock) {
LogPrint(eLogError, "HTTPProxy: no socket for read");
return;
}
m_sock->async_read_some(boost::asio::buffer(m_recv_chunk, sizeof(m_recv_chunk)),
std::bind(&HTTPReqHandler::HandleSockRecv, shared_from_this(),
std::placeholders::_1, std::placeholders::_2));
}
void HTTPReqHandler::Terminate() {
if (Kill()) return;
if (m_sock)
{
LogPrint(eLogDebug, "HTTPProxy: close sock");
m_sock->close();
m_sock = nullptr;
}
if(m_proxysock)
{
LogPrint(eLogDebug, "HTTPProxy: close proxysock");
if(m_proxysock->is_open())
m_proxysock->close();
m_proxysock = nullptr;
}
Done(shared_from_this());
}
void HTTPReqHandler::GenericProxyError(const char *title, const char *description) {
std::stringstream ss;
ss << "<h1>Proxy error: " << title << "</h1>\r\n";
ss << "<p>" << description << "</p>\r\n";
std::string content = ss.str();
SendProxyError(content);
}
void HTTPReqHandler::GenericProxyInfo(const char *title, const char *description) {
std::stringstream ss;
ss << "<h1>Proxy info: " << title << "</h1>\r\n";
ss << "<p>" << description << "</p>\r\n";
std::string content = ss.str();
SendProxyError(content);
}
void HTTPReqHandler::HostNotFound(std::string & host) {
std::stringstream ss;
ss << "<h1>Proxy error: Host not found</h1>\r\n"
<< "<p>Remote host not found in router's addressbook</p>\r\n"
<< "<p>You may try to find this host on jumpservices below:</p>\r\n"
<< "<ul>\r\n";
for (const auto& js : jumpservices) {
ss << " <li><a href=\"" << js.second << host << "\">" << js.first << "</a></li>\r\n";
}
ss << "</ul>\r\n";
std::string content = ss.str();
SendProxyError(content);
}
void HTTPReqHandler::SendProxyError(std::string & content)
{
i2p::http::HTTPRes res;
res.code = 500;
res.add_header("Content-Type", "text/html; charset=UTF-8");
res.add_header("Connection", "close");
std::stringstream ss;
ss << "<html>\r\n" << pageHead
<< "<body>" << content << "</body>\r\n"
<< "</html>\r\n";
res.body = ss.str();
std::string response = res.to_string();
boost::asio::async_write(*m_sock, boost::asio::buffer(response), boost::asio::transfer_all(),
std::bind(&HTTPReqHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
}
bool HTTPReqHandler::ExtractAddressHelper(i2p::http::URL & url, std::string & b64)
{
const char *param = "i2paddresshelper=";
std::size_t pos = url.query.find(param);
std::size_t len = std::strlen(param);
std::map<std::string, std::string> params;
if (pos == std::string::npos)
return false; /* not found */
if (!url.parse_query(params))
return false;
std::string value = params["i2paddresshelper"];
len += value.length();
b64 = i2p::http::UrlDecode(value);
url.query.replace(pos, len, "");
return true;
}
void HTTPReqHandler::SanitizeHTTPRequest(i2p::http::HTTPReq & req)
{
/* drop common headers */
req.RemoveHeader ("Referer");
req.RemoveHeader("Via");
req.RemoveHeader("Forwarded");
/* drop proxy-disclosing headers */
req.RemoveHeader("X-Forwarded");
req.RemoveHeader("Proxy-");
/* replace headers */
req.UpdateHeader("User-Agent", "MYOB/6.66 (AN/ON)");
/* add headers */
req.AddHeader("Connection", "close"); /* keep-alive conns not supported yet */
}
/**
* @brief Try to parse request from @a m_recv_buf
* If parsing success, rebuild request and store to @a m_send_buf
* with remaining data tail
* @return true on processed request or false if more data needed
*/
bool HTTPReqHandler::HandleRequest()
{
std::string b64;
m_req_len = m_ClientRequest.parse(m_recv_buf);
if (m_req_len == 0)
return false; /* need more data */
if (m_req_len < 0) {
LogPrint(eLogError, "HTTPProxy: unable to parse request");
GenericProxyError("Invalid request", "Proxy unable to parse your request");
return true; /* parse error */
}
/* parsing success, now let's look inside request */
LogPrint(eLogDebug, "HTTPProxy: requested: ", m_ClientRequest.uri);
m_RequestURL.parse(m_ClientRequest.uri);
if (ExtractAddressHelper(m_RequestURL, b64)) {
i2p::client::context.GetAddressBook ().InsertAddress (m_RequestURL.host, b64);
LogPrint (eLogInfo, "HTTPProxy: added b64 from addresshelper for ", m_RequestURL.host);
std::string full_url = m_RequestURL.to_string();
std::stringstream ss;
ss << "Host " << m_RequestURL.host << " added to router's addressbook from helper. "
<< "Click <a href=\"" << full_url << "\">here</a> to proceed.";
GenericProxyInfo("Addresshelper found", ss.str().c_str());
return true; /* request processed */
}
SanitizeHTTPRequest(m_ClientRequest);
std::string dest_host = m_RequestURL.host;
uint16_t dest_port = m_RequestURL.port;
/* always set port, even if missing in request */
if (!dest_port)
dest_port = (m_RequestURL.schema == "https") ? 443 : 80;
/* detect dest_host, set proper 'Host' header in upstream request */
if (dest_host != "")
{
/* absolute url, replace 'Host' header */
std::string h = dest_host;
if (dest_port != 0 && dest_port != 80)
h += ":" + std::to_string(dest_port);
m_ClientRequest.UpdateHeader("Host", h);
}
else
{
auto h = m_ClientRequest.GetHeader ("Host");
if (h.length () > 0)
{
/* relative url and 'Host' header provided. transparent proxy mode? */
i2p::http::URL u;
std::string t = "http://" + h;
u.parse(t);
dest_host = u.host;
dest_port = u.port;
}
else
{
/* relative url and missing 'Host' header */
GenericProxyError("Invalid request", "Can't detect destination host from request");
return true;
}
}
/* check dest_host really exists and inside I2P network */
i2p::data::IdentHash identHash;
if (str_rmatch(dest_host, ".i2p")) {
if (!i2p::client::context.GetAddressBook ().GetIdentHash (dest_host, identHash)) {
HostNotFound(dest_host);
return true; /* request processed */
}
} else {
std::string outproxyUrl; i2p::config::GetOption("httpproxy.outproxy", outproxyUrl);
if(outproxyUrl.size()) {
LogPrint (eLogDebug, "HTTPProxy: use outproxy ", outproxyUrl);
if(m_ProxyURL.parse(outproxyUrl))
ForwardToUpstreamProxy();
else
GenericProxyError("Outproxy failure", "bad outproxy settings");
} else {
LogPrint (eLogWarning, "HTTPProxy: outproxy failure for ", dest_host, ": no outprxy enabled");
std::string message = "Host" + dest_host + "not inside I2P network, but outproxy is not enabled";
GenericProxyError("Outproxy failure", message.c_str());
}
return true;
}
/* make relative url */
m_RequestURL.schema = "";
m_RequestURL.host = "";
m_ClientRequest.uri = m_RequestURL.to_string();
/* drop original request from recv buffer */
m_recv_buf.erase(0, m_req_len);
/* build new buffer from modified request and data from original request */
m_send_buf = m_ClientRequest.to_string();
m_send_buf.append(m_recv_buf);
/* connect to destination */
LogPrint(eLogDebug, "HTTPProxy: connecting to host ", dest_host, ":", dest_port);
GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleStreamRequestComplete,
shared_from_this(), std::placeholders::_1), dest_host, dest_port);
return true;
}
void HTTPReqHandler::ForwardToUpstreamProxy()
{
LogPrint(eLogDebug, "HTTPProxy: forward to upstream");
// build http requset
m_ClientRequestURL = m_RequestURL;
LogPrint(eLogDebug, "HTTPProxy: ", m_ClientRequestURL.host);
m_ClientRequestURL.schema = "";
m_ClientRequestURL.host = "";
m_ClientRequest.uri = m_ClientRequestURL.to_string();
m_ClientRequest.write(m_ClientRequestBuffer);
m_ClientRequestBuffer << m_recv_buf.substr(m_req_len);
// assume http if empty schema
if (m_ProxyURL.schema == "" || m_ProxyURL.schema == "http") {
// handle upstream http proxy
if (!m_ProxyURL.port) m_ProxyURL.port = 80;
boost::asio::ip::tcp::resolver::query q(m_ProxyURL.host, std::to_string(m_ProxyURL.port));
m_proxy_resolver.async_resolve(q, std::bind(&HTTPReqHandler::HandleUpstreamProxyResolved, this, std::placeholders::_1, std::placeholders::_2, [&](boost::asio::ip::tcp::endpoint ep) {
m_proxysock->async_connect(ep, std::bind(&HTTPReqHandler::HandleUpstreamHTTPProxyConnect, this, std::placeholders::_1));
}));
} else if (m_ProxyURL.schema == "socks") {
// handle upstream socks proxy
if (!m_ProxyURL.port) m_ProxyURL.port = 9050; // default to tor default if not specified
boost::asio::ip::tcp::resolver::query q(m_ProxyURL.host, std::to_string(m_ProxyURL.port));
m_proxy_resolver.async_resolve(q, std::bind(&HTTPReqHandler::HandleUpstreamProxyResolved, this, std::placeholders::_1, std::placeholders::_2, [&](boost::asio::ip::tcp::endpoint ep) {
m_proxysock->async_connect(ep, std::bind(&HTTPReqHandler::HandleUpstreamSocksProxyConnect, this, std::placeholders::_1));
}));
} else {
// unknown type, complain
GenericProxyError("unknown outproxy url", m_ProxyURL.to_string().c_str());
}
}
void HTTPReqHandler::HandleUpstreamProxyResolved(const boost::system::error_code & ec, boost::asio::ip::tcp::resolver::iterator it, ProxyResolvedHandler handler)
{
if(ec) GenericProxyError("cannot resolve upstream proxy", ec.message().c_str());
else handler(*it);
}
void HTTPReqHandler::HandleUpstreamSocksProxyConnect(const boost::system::error_code & ec)
{
if(!ec) {
if(m_RequestURL.host.size() > 255) {
GenericProxyError("hostname too long", m_RequestURL.host.c_str());
return;
}
uint16_t port = m_RequestURL.port;
if(!port) port = 80;
LogPrint(eLogDebug, "HTTPProxy: connected to socks upstream");
std::string host = m_RequestURL.host;
std::size_t reqsize = 0;
m_socks_buf[0] = '\x04';
m_socks_buf[1] = 1;
htobe16buf(m_socks_buf+2, port);
m_socks_buf[4] = 0;
m_socks_buf[5] = 0;
m_socks_buf[6] = 0;
m_socks_buf[7] = 1;
// user id
m_socks_buf[8] = 'i';
m_socks_buf[9] = '2';
m_socks_buf[10] = 'p';
m_socks_buf[11] = 'd';
m_socks_buf[12] = 0;
reqsize += 13;
memcpy(m_socks_buf+ reqsize, host.c_str(), host.size());
reqsize += host.size();
m_socks_buf[++reqsize] = 0;
boost::asio::async_write(*m_proxysock, boost::asio::buffer(m_socks_buf, reqsize), boost::asio::transfer_all(), std::bind(&HTTPReqHandler::HandleSocksProxySendHandshake, this, std::placeholders::_1, std::placeholders::_2));
} else GenericProxyError("cannot connect to upstream socks proxy", ec.message().c_str());
}
void HTTPReqHandler::HandleSocksProxySendHandshake(const boost::system::error_code & ec, std::size_t bytes_transferred)
{
LogPrint(eLogDebug, "HTTPProxy: upstream socks handshake sent");
if(ec) GenericProxyError("Cannot negotiate with socks proxy", ec.message().c_str());
else m_proxysock->async_read_some(boost::asio::buffer(m_socks_buf, 8), std::bind(&HTTPReqHandler::HandleSocksProxyReply, this, std::placeholders::_1, std::placeholders::_2));
}
void HTTPReqHandler::HandoverToUpstreamProxy()
{
LogPrint(eLogDebug, "HTTPProxy: handover to socks proxy");
auto connection = std::make_shared<i2p::client::TCPIPPipe>(GetOwner(), m_proxysock, m_sock);
m_sock = nullptr;
m_proxysock = nullptr;
GetOwner()->AddHandler(connection);
connection->Start();
Terminate();
}
void HTTPReqHandler::SocksProxySuccess()
{
if(m_ClientRequest.method == "CONNECT") {
m_ClientResponse.code = 200;
m_send_buf = m_ClientResponse.to_string();
boost::asio::async_write(*m_sock, boost::asio::buffer(m_send_buf), boost::asio::transfer_all(), [&] (const boost::system::error_code & ec, std::size_t transferred) {
if(ec) GenericProxyError("socks proxy error", ec.message().c_str());
else HandoverToUpstreamProxy();
});
} else {
m_send_buf = m_ClientRequestBuffer.str();
LogPrint(eLogDebug, "HTTPProxy: send ", m_send_buf.size(), " bytes");
boost::asio::async_write(*m_proxysock, boost::asio::buffer(m_send_buf), boost::asio::transfer_all(), [&](const boost::system::error_code & ec, std::size_t transferred) {
if(ec) GenericProxyError("failed to send request to upstream", ec.message().c_str());
else HandoverToUpstreamProxy();
});
}
}
void HTTPReqHandler::HandleSocksProxyReply(const boost::system::error_code & ec, std::size_t bytes_transferred)
{
if(!ec)
{
if(m_socks_buf[1] == 90) {
// success
SocksProxySuccess();
} else {
std::stringstream ss;
ss << "error code: ";
ss << (int) m_socks_buf[1];
std::string msg = ss.str();
GenericProxyError("Socks Proxy error", msg.c_str());
}
}
else GenericProxyError("No Reply From socks proxy", ec.message().c_str());
}
void HTTPReqHandler::HandleUpstreamHTTPProxyConnect(const boost::system::error_code & ec)
{
if(!ec) {
LogPrint(eLogDebug, "HTTPProxy: connected to http upstream");
GenericProxyError("cannot connect", "http out proxy not implemented");
} else GenericProxyError("cannot connect to upstream http proxy", ec.message().c_str());
}
/* will be called after some data received from client */
void HTTPReqHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
{
LogPrint(eLogDebug, "HTTPProxy: sock recv: ", len, " bytes, recv buf: ", m_recv_buf.length(), ", send buf: ", m_send_buf.length());
if(ecode)
{
LogPrint(eLogWarning, "HTTPProxy: sock recv got error: ", ecode);
Terminate();
return;
}
m_recv_buf.append(reinterpret_cast<const char *>(m_recv_chunk), len);
if (HandleRequest()) {
m_recv_buf.clear();
return;
}
AsyncSockRead();
}
void HTTPReqHandler::SentHTTPFailed(const boost::system::error_code & ecode)
{
if (ecode)
LogPrint (eLogError, "HTTPProxy: Closing socket after sending failure because: ", ecode.message ());
Terminate();
}
void HTTPReqHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
{
if (!stream) {
LogPrint (eLogError, "HTTPProxy: error when creating the stream, check the previous warnings for more info");
GenericProxyError("Host is down", "Can't create connection to requested host, it may be down");
return;
}
if (Kill())
return;
LogPrint (eLogDebug, "HTTPProxy: Created new I2PTunnel stream, sSID=", stream->GetSendStreamID(), ", rSID=", stream->GetRecvStreamID());
auto connection = std::make_shared<i2p::client::I2PClientTunnelConnectionHTTP>(GetOwner(), m_sock, stream);
GetOwner()->AddHandler (connection);
connection->I2PConnect (reinterpret_cast<const uint8_t*>(m_send_buf.data()), m_send_buf.length());
Done (shared_from_this());
}
HTTPProxy::HTTPProxy(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination):
TCPIPAcceptor(address, port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ())
{
}
std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxy::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
{
return std::make_shared<HTTPReqHandler> (this, socket);
}
} // http
} // i2p

View File

@ -1,21 +0,0 @@
#ifndef HTTP_PROXY_H__
#define HTTP_PROXY_H__
namespace i2p {
namespace proxy {
class HTTPProxy: public i2p::client::TCPIPAcceptor
{
public:
HTTPProxy(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination = nullptr);
~HTTPProxy() {};
protected:
// Implements TCPIPAcceptor
std::shared_ptr<i2p::client::I2PServiceHandler> CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket);
const char* GetName() { return "HTTP Proxy"; }
};
} // http
} // i2p
#endif

View File

@ -1,980 +0,0 @@
#include <iomanip>
#include <sstream>
#include <thread>
#include <memory>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include "Base.h"
#include "FS.h"
#include "Log.h"
#include "Config.h"
#include "Tunnel.h"
#include "TransitTunnel.h"
#include "Transports.h"
#include "NetDb.h"
#include "HTTP.h"
#include "LeaseSet.h"
#include "Destination.h"
#include "RouterContext.h"
#include "ClientContext.h"
#include "HTTPServer.h"
#include "Daemon.h"
#include "util.h"
#ifdef WIN32_APP
#include "Win32/Win32App.h"
#endif
// For image and info
#include "version.h"
namespace i2p {
namespace http {
const char *itoopieFavicon =
"data:image/png;base64,"
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACx"
"jwv8YQUAAAAJcEhZcwAALiIAAC4iAari3ZIAAAAHdElNRQfgCQsUNSZrkhi1AAAAGXRFWHRTb2Z0"
"d2FyZQBwYWludC5uZXQgNC4wLjEyQwRr7AAAAoJJREFUOE9jwAUqi4Q1oEwwcDTV1+5sETaBclGB"
"vb09C5QJB6kWpvFQJoOCeLC5kmjEHCgXE2SlyETLi3h6QrkM4VL+ssWSCZUgtopITLKqaOotRTEn"
"cbAkLqAkGtOqLBLVAWLXyWSVFkkmRiqLxuaqiWb/VBYJMAYrwgckJY25VEUzniqKhjU2y+RtCRSP"
"6lUXy/1jIBV5tlYxZUaFVMq2NInwIi9hO8fSfOEAqDZUoCwal6MulvOvyS7gi69K4j9zxZT/m0ps"
"/28ptvvvquXXryIa7QYMMdTwqi0WNtVi0GIDseXl7TnUxFKfnGlxAGp0+D8j2eH/8Ub7/9e7nf7X"
"+Af/B7rwt6pI0h0l0WhQADOC9DBkhSirpImHNVZKp24ukkyoshGLnN8d5fA/y13t/44Kq/8hlnL/"
"z7fZ/58f6vcxSNpbVUVFhV1RLNBVTsQzVYZPSwhsCAhkiIfpNMrkbO6TLf071Sfk/5ZSi/+7q6z/"
"P5ns+v9mj/P/CpuI/20y+aeNGYxZoVoYGmsF3aFMBAAZlCwftnF9ke3//bU2//fXWP8/UGv731Am"
"+V+DdNblSqnUYqhSTKAiYSOqJBrVqiaa+S3UNPr/gmyH/xuKXf63hnn/B8bIP0UxHfEyyeSNQKVM"
"EB1AEB2twhcTLp+gIBJUoyKasEpVJHmqskh8qryovUG/ffCHHRU2q/Tk/YuB6eGPsbExa7ZkpLu1"
"oLEcVDtuUCgV1w60rQzElpRUE1EVSX0BYidHiInXF4nagNhYQW60EF+ApH1ktni0A1SIITSUgVlZ"
"JHYnlIsfzJjIp9xZKswL5YKBHL+coKJoRDaUSzoozxHVrygQU4JykQADAwAT5b1NHtwZugAAAABJ"
"RU5ErkJggg==";
const char *cssStyles =
"<style>\r\n"
" body { font: 100%/1.5em sans-serif; margin: 0; padding: 1.5em; background: #FAFAFA; color: #103456; }\r\n"
" a { text-decoration: none; color: #894C84; }\r\n"
" a:hover { color: #FAFAFA; background: #894C84; }\r\n"
" .header { font-size: 2.5em; text-align: center; margin: 1.5em 0; color: #894C84; }\r\n"
" .wrapper { margin: 0 auto; padding: 1em; max-width: 60em; }\r\n"
" .left { float: left; position: absolute; }\r\n"
" .right { float: left; font-size: 1em; margin-left: 13em; max-width: 46em; overflow: auto; }\r\n"
" .tunnel.established { color: #56B734; }\r\n"
" .tunnel.expiring { color: #D3AE3F; }\r\n"
" .tunnel.failed { color: #D33F3F; }\r\n"
" .tunnel.another { color: #434343; }\r\n"
" caption { font-size: 1.5em; text-align: center; color: #894C84; }\r\n"
" table { width: 100%; border-collapse: collapse; text-align: center; }\r\n"
" .private { background: black; color: black; } .private:hover { background: black; color: white } \r\n"
" .slide p, .slide [type='checkbox']{ display:none; } \r\n"
" .slide [type='checkbox']:checked ~ p { display:block; } \r\n"
"</style>\r\n";
const char HTTP_PAGE_TUNNELS[] = "tunnels";
const char HTTP_PAGE_TRANSIT_TUNNELS[] = "transit_tunnels";
const char HTTP_PAGE_TRANSPORTS[] = "transports";
const char HTTP_PAGE_LOCAL_DESTINATIONS[] = "local_destinations";
const char HTTP_PAGE_LOCAL_DESTINATION[] = "local_destination";
const char HTTP_PAGE_I2CP_LOCAL_DESTINATION[] = "i2cp_local_destination";
const char HTTP_PAGE_SAM_SESSIONS[] = "sam_sessions";
const char HTTP_PAGE_SAM_SESSION[] = "sam_session";
const char HTTP_PAGE_I2P_TUNNELS[] = "i2p_tunnels";
const char HTTP_PAGE_COMMANDS[] = "commands";
const char HTTP_PAGE_LEASESETS[] = "leasesets";
const char HTTP_COMMAND_ENABLE_TRANSIT[] = "enable_transit";
const char HTTP_COMMAND_DISABLE_TRANSIT[] = "disable_transit";
const char HTTP_COMMAND_SHUTDOWN_START[] = "shutdown_start";
const char HTTP_COMMAND_SHUTDOWN_CANCEL[] = "shutdown_cancel";
const char HTTP_COMMAND_SHUTDOWN_NOW[] = "terminate";
const char HTTP_COMMAND_RUN_PEER_TEST[] = "run_peer_test";
const char HTTP_COMMAND_RELOAD_CONFIG[] = "reload_config";
const char HTTP_PARAM_SAM_SESSION_ID[] = "id";
const char HTTP_PARAM_ADDRESS[] = "address";
static void ShowUptime (std::stringstream& s, int seconds)
{
int num;
if ((num = seconds / 86400) > 0) {
s << num << " days, ";
seconds -= num * 86400;
}
if ((num = seconds / 3600) > 0) {
s << num << " hours, ";
seconds -= num * 3600;
}
if ((num = seconds / 60) > 0) {
s << num << " min, ";
seconds -= num * 60;
}
s << seconds << " seconds";
}
static void ShowTunnelDetails (std::stringstream& s, enum i2p::tunnel::TunnelState eState, int bytes)
{
std::string state;
switch (eState) {
case i2p::tunnel::eTunnelStateBuildReplyReceived :
case i2p::tunnel::eTunnelStatePending : state = "building"; break;
case i2p::tunnel::eTunnelStateBuildFailed :
case i2p::tunnel::eTunnelStateTestFailed :
case i2p::tunnel::eTunnelStateFailed : state = "failed"; break;
case i2p::tunnel::eTunnelStateExpiring : state = "expiring"; break;
case i2p::tunnel::eTunnelStateEstablished : state = "established"; break;
default: state = "unknown"; break;
}
s << "<span class=\"tunnel " << state << "\"> " << state << "</span>, ";
s << " " << (int) (bytes / 1024) << "&nbsp;KiB<br>\r\n";
}
static void ShowPageHead (std::stringstream& s)
{
s <<
"<!DOCTYPE html>\r\n"
"<html lang=\"en\">\r\n" /* TODO: Add support for locale */
" <head>\r\n" /* TODO: Find something to parse html/template system. This is horrible. */
#if (!defined(WIN32))
" <meta charset=\"UTF-8\">\r\n"
#else
" <meta charset=\"windows-1251\">\r\n"
#endif
" <link rel=\"shortcut icon\" href=\"" << itoopieFavicon << "\">\r\n"
" <title>Purple I2P " VERSION " Webconsole</title>\r\n"
<< cssStyles <<
"</head>\r\n";
s <<
"<body>\r\n"
"<div class=header><b>i2pd</b> webconsole</div>\r\n"
"<div class=wrapper>\r\n"
"<div class=left>\r\n"
" <a href=\"/\">Main page</a><br>\r\n<br>\r\n"
" <a href=\"/?page=" << HTTP_PAGE_COMMANDS << "\">Router commands</a><br>\r\n"
" <a href=\"/?page=" << HTTP_PAGE_LOCAL_DESTINATIONS << "\">Local destinations</a><br>\r\n"
" <a href=\"/?page=" << HTTP_PAGE_LEASESETS << "\">LeaseSets</a><br>\r\n"
" <a href=\"/?page=" << HTTP_PAGE_TUNNELS << "\">Tunnels</a><br>\r\n"
" <a href=\"/?page=" << HTTP_PAGE_TRANSIT_TUNNELS << "\">Transit tunnels</a><br>\r\n"
" <a href=\"/?page=" << HTTP_PAGE_TRANSPORTS << "\">Transports</a><br>\r\n"
" <a href=\"/?page=" << HTTP_PAGE_I2P_TUNNELS << "\">I2P tunnels</a><br>\r\n";
if (i2p::client::context.GetSAMBridge ())
s << " <a href=\"/?page=" << HTTP_PAGE_SAM_SESSIONS << "\">SAM sessions</a><br>\r\n";
s <<
"</div>\r\n"
"<div class=right>";
}
static void ShowPageTail (std::stringstream& s)
{
s <<
"</div></div>\r\n"
"</body>\r\n"
"</html>\r\n";
}
static void ShowError(std::stringstream& s, const std::string& string)
{
s << "<b>ERROR:</b>&nbsp;" << string << "<br>\r\n";
}
static void ShowStatus (std::stringstream& s)
{
s << "<b>Uptime:</b> ";
ShowUptime(s, i2p::context.GetUptime ());
s << "<br>\r\n";
s << "<b>Network status:</b> ";
switch (i2p::context.GetStatus ())
{
case eRouterStatusOK: s << "OK"; break;
case eRouterStatusTesting: s << "Testing"; break;
case eRouterStatusFirewalled: s << "Firewalled"; break;
case eRouterStatusError:
{
s << "Error";
switch (i2p::context.GetError ())
{
case eRouterErrorClockSkew:
s << "<br>Clock skew";
break;
default: ;
}
break;
}
default: s << "Unknown";
}
s << "<br>\r\n";
#if (!defined(WIN32) && !defined(QT_GUI_LIB) && !defined(ANDROID))
if (auto remains = Daemon.gracefulShutdownInterval) {
s << "<b>Stopping in:</b> ";
s << remains << " seconds";
s << "<br>\r\n";
}
#endif
auto family = i2p::context.GetFamily ();
if (family.length () > 0)
s << "<b>Family:</b> " << family << "<br>\r\n";
s << "<b>Tunnel creation success rate:</b> " << i2p::tunnel::tunnels.GetTunnelCreationSuccessRate () << "%<br>\r\n";
s << "<b>Received:</b> ";
s << std::fixed << std::setprecision(2);
auto numKBytesReceived = (double) i2p::transport::transports.GetTotalReceivedBytes () / 1024;
if (numKBytesReceived < 1024)
s << numKBytesReceived << " KiB";
else if (numKBytesReceived < 1024 * 1024)
s << numKBytesReceived / 1024 << " MiB";
else
s << numKBytesReceived / 1024 / 1024 << " GiB";
s << " (" << (double) i2p::transport::transports.GetInBandwidth () / 1024 << " KiB/s)<br>\r\n";
s << "<b>Sent:</b> ";
auto numKBytesSent = (double) i2p::transport::transports.GetTotalSentBytes () / 1024;
if (numKBytesSent < 1024)
s << numKBytesSent << " KiB";
else if (numKBytesSent < 1024 * 1024)
s << numKBytesSent / 1024 << " MiB";
else
s << numKBytesSent / 1024 / 1024 << " GiB";
s << " (" << (double) i2p::transport::transports.GetOutBandwidth () / 1024 << " KiB/s)<br>\r\n";
s << "<b>Data path:</b> " << i2p::fs::GetDataDir() << "<br>\r\n";
s << "<div class='slide'\r\n><label for='slide1'>Hidden content. Press on text to see.</label>\r\n<input type='checkbox' id='slide1'/>\r\n<p class='content'>\r\n";
s << "<b>Router Ident:</b> " << i2p::context.GetRouterInfo().GetIdentHashBase64() << "<br>\r\n";
s << "<b>Router Family:</b> " << i2p::context.GetRouterInfo().GetProperty("family") << "<br>\r\n";
s << "<b>Router Caps:</b> " << i2p::context.GetRouterInfo().GetProperty("caps") << "<br>\r\n";
s << "<b>Our external address:</b>" << "<br>\r\n" ;
for (const auto& address : i2p::context.GetRouterInfo().GetAddresses())
{
switch (address->transportStyle)
{
case i2p::data::RouterInfo::eTransportNTCP:
if (address->host.is_v6 ())
s << "NTCP6&nbsp;&nbsp;";
else
s << "NTCP&nbsp;&nbsp;";
break;
case i2p::data::RouterInfo::eTransportSSU:
if (address->host.is_v6 ())
s << "SSU6&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
else
s << "SSU&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
break;
default:
s << "Unknown&nbsp;&nbsp;";
}
s << address->host.to_string() << ":" << address->port << "<br>\r\n";
}
s << "</p>\r\n</div>\r\n";
s << "<b>Routers:</b> " << i2p::data::netdb.GetNumRouters () << " ";
s << "<b>Floodfills:</b> " << i2p::data::netdb.GetNumFloodfills () << " ";
s << "<b>LeaseSets:</b> " << i2p::data::netdb.GetNumLeaseSets () << "<br>\r\n";
size_t clientTunnelCount = i2p::tunnel::tunnels.CountOutboundTunnels();
clientTunnelCount += i2p::tunnel::tunnels.CountInboundTunnels();
size_t transitTunnelCount = i2p::tunnel::tunnels.CountTransitTunnels();
s << "<b>Client Tunnels:</b> " << std::to_string(clientTunnelCount) << " ";
s << "<b>Transit Tunnels:</b> " << std::to_string(transitTunnelCount) << "<br>\r\n";
}
static void ShowLocalDestinations (std::stringstream& s)
{
s << "<b>Local Destinations:</b><br>\r\n<br>\r\n";
for (auto& it: i2p::client::context.GetDestinations ())
{
auto ident = it.second->GetIdentHash ();
s << "<a href=\"/?page=" << HTTP_PAGE_LOCAL_DESTINATION << "&b32=" << ident.ToBase32 () << "\">";
s << i2p::client::context.GetAddressBook ().ToAddress(ident) << "</a><br>\r\n" << std::endl;
}
auto i2cpServer = i2p::client::context.GetI2CPServer ();
if (i2cpServer)
{
s << "<br><b>I2CP Local Destinations:</b><br>\r\n<br>\r\n";
for (auto& it: i2cpServer->GetSessions ())
{
auto dest = it.second->GetDestination ();
if (dest)
{
auto ident = dest->GetIdentHash ();
s << "<a href=\"/?page=" << HTTP_PAGE_I2CP_LOCAL_DESTINATION << "&i2cp_id=" << it.first << "\">";
s << i2p::client::context.GetAddressBook ().ToAddress(ident) << "</a><br>\r\n" << std::endl;
}
}
}
}
static void ShowLeaseSetDestination (std::stringstream& s, std::shared_ptr<const i2p::client::LeaseSetDestination> dest)
{
s << "<b>Base64:</b><br>\r\n<textarea readonly=\"readonly\" cols=\"64\" rows=\"11\" wrap=\"on\">";
s << dest->GetIdentity ()->ToBase64 () << "</textarea><br>\r\n<br>\r\n";
s << "<b>LeaseSets:</b> <i>" << dest->GetNumRemoteLeaseSets () << "</i><br>\r\n";
if(dest->GetNumRemoteLeaseSets())
{
s << "<div class='slide'\r\n><label for='slide1'>Hidden content. Press on text to see.</label>\r\n<input type='checkbox' id='slide1'/>\r\n<p class='content'>\r\n";
for(auto& it: dest->GetLeaseSets ())
s << it.second->GetIdentHash ().ToBase32 () << "<br>\r\n";
s << "</p>\r\n</div>\r\n";
}
auto pool = dest->GetTunnelPool ();
if (pool)
{
s << "<b>Inbound tunnels:</b><br>\r\n";
for (auto & it : pool->GetInboundTunnels ()) {
it->Print(s);
if(it->LatencyIsKnown())
s << " ( " << it->GetMeanLatency() << "ms )";
ShowTunnelDetails(s, it->GetState (), it->GetNumReceivedBytes ());
}
s << "<br>\r\n";
s << "<b>Outbound tunnels:</b><br>\r\n";
for (auto & it : pool->GetOutboundTunnels ()) {
it->Print(s);
if(it->LatencyIsKnown())
s << " ( " << it->GetMeanLatency() << "ms )";
ShowTunnelDetails(s, it->GetState (), it->GetNumSentBytes ());
}
}
s << "<br>\r\n";
s << "<b>Tags</b><br>Incoming: " << dest->GetNumIncomingTags () << "<br>Outgoing:<br>" << std::endl;
for (const auto& it: dest->GetSessions ())
{
s << i2p::client::context.GetAddressBook ().ToAddress(it.first) << " ";
s << it.second->GetNumOutgoingTags () << "<br>" << std::endl;
}
s << "<br>" << std::endl;
}
static void ShowLocalDestination (std::stringstream& s, const std::string& b32)
{
s << "<b>Local Destination:</b><br>\r\n<br>\r\n";
i2p::data::IdentHash ident;
ident.FromBase32 (b32);
auto dest = i2p::client::context.FindLocalDestination (ident);
if (dest)
{
ShowLeaseSetDestination (s, dest);
// show streams
s << "<br>\r\n<table><caption>Streams</caption><tr>";
s << "<th>StreamID</th>";
s << "<th>Destination</th>";
s << "<th>Sent</th>";
s << "<th>Received</th>";
s << "<th>Out</th>";
s << "<th>In</th>";
s << "<th>Buf</th>";
s << "<th>RTT</th>";
s << "<th>Window</th>";
s << "<th>Status</th>";
s << "</tr>";
for (const auto& it: dest->GetAllStreams ())
{
s << "<tr>";
s << "<td>" << it->GetSendStreamID () << "</td>";
s << "<td>" << i2p::client::context.GetAddressBook ().ToAddress(it->GetRemoteIdentity ()) << "</td>";
s << "<td>" << it->GetNumSentBytes () << "</td>";
s << "<td>" << it->GetNumReceivedBytes () << "</td>";
s << "<td>" << it->GetSendQueueSize () << "</td>";
s << "<td>" << it->GetReceiveQueueSize () << "</td>";
s << "<td>" << it->GetSendBufferSize () << "</td>";
s << "<td>" << it->GetRTT () << "</td>";
s << "<td>" << it->GetWindowSize () << "</td>";
s << "<td>" << (int)it->GetStatus () << "</td>";
s << "</tr><br>\r\n" << std::endl;
}
s << "</table>";
}
}
static void ShowI2CPLocalDestination (std::stringstream& s, const std::string& id)
{
auto i2cpServer = i2p::client::context.GetI2CPServer ();
if (i2cpServer)
{
s << "<b>I2CP Local Destination:</b><br>\r\n<br>\r\n";
auto it = i2cpServer->GetSessions ().find (std::stoi (id));
if (it != i2cpServer->GetSessions ().end ())
ShowLeaseSetDestination (s, it->second->GetDestination ());
else
ShowError(s, "I2CP session not found");
}
else
ShowError(s, "I2CP is not enabled");
}
static void ShowLeasesSets(std::stringstream& s)
{
s << "<div id='leasesets'><b>LeaseSets (click on to show info):</b></div><br>\r\n";
int counter = 1;
// for each lease set
i2p::data::netdb.VisitLeaseSets(
[&s, &counter](const i2p::data::IdentHash dest, std::shared_ptr<i2p::data::LeaseSet> leaseSet)
{
// create copy of lease set so we extract leases
i2p::data::LeaseSet ls(leaseSet->GetBuffer(), leaseSet->GetBufferLen());
s << "<div class='leaseset";
if (ls.IsExpired())
s << " expired"; // additional css class for expired
s << "'>\r\n";
if (!ls.IsValid())
s << "<div class='invalid'>!! Invalid !! </div>\r\n";
s << "<div class='slide'><label for='slide" << counter << "'>" << dest.ToBase32() << "</label>\r\n";
s << "<input type='checkbox' id='slide" << (counter++) << "'/>\r\n<p class='content'>\r\n";
s << "<b>Expires:</b> " << ls.GetExpirationTime() << "<br>\r\n";
auto leases = ls.GetNonExpiredLeases();
s << "<b>Non Expired Leases: " << leases.size() << "</b><br>\r\n";
for ( auto & l : leases )
{
s << "<b>Gateway:</b> " << l->tunnelGateway.ToBase64() << "<br>\r\n";
s << "<b>TunnelID:</b> " << l->tunnelID << "<br>\r\n";
s << "<b>EndDate:</b> " << l->endDate << "<br>\r\n";
}
s << "</p>\r\n</div>\r\n</div>\r\n";
}
);
// end for each lease set
}
static void ShowTunnels (std::stringstream& s)
{
s << "<b>Queue size:</b> " << i2p::tunnel::tunnels.GetQueueSize () << "<br>\r\n";
s << "<b>Inbound tunnels:</b><br>\r\n";
for (auto & it : i2p::tunnel::tunnels.GetInboundTunnels ()) {
it->Print(s);
if(it->LatencyIsKnown())
s << " ( " << it->GetMeanLatency() << "ms )";
ShowTunnelDetails(s, it->GetState (), it->GetNumReceivedBytes ());
}
s << "<br>\r\n";
s << "<b>Outbound tunnels:</b><br>\r\n";
for (auto & it : i2p::tunnel::tunnels.GetOutboundTunnels ()) {
it->Print(s);
if(it->LatencyIsKnown())
s << " ( " << it->GetMeanLatency() << "ms )";
ShowTunnelDetails(s, it->GetState (), it->GetNumSentBytes ());
}
s << "<br>\r\n";
}
static void ShowCommands (std::stringstream& s, uint32_t token)
{
/* commands */
s << "<b>Router Commands</b><br>\r\n";
s << " <a href=\"/?cmd=" << HTTP_COMMAND_RUN_PEER_TEST << "&token=" << token << "\">Run peer test</a><br>\r\n";
//s << " <a href=\"/?cmd=" << HTTP_COMMAND_RELOAD_CONFIG << "\">Reload config</a><br>\r\n";
if (i2p::context.AcceptsTunnels ())
s << " <a href=\"/?cmd=" << HTTP_COMMAND_DISABLE_TRANSIT << "&token=" << token << "\">Decline transit tunnels</a><br>\r\n";
else
s << " <a href=\"/?cmd=" << HTTP_COMMAND_ENABLE_TRANSIT << "&token=" << token << "\">Accept transit tunnels</a><br>\r\n";
#if (!defined(WIN32) && !defined(QT_GUI_LIB) && !defined(ANDROID))
if (Daemon.gracefulShutdownInterval)
s << " <a href=\"/?cmd=" << HTTP_COMMAND_SHUTDOWN_CANCEL << "&token=" << token << "\">Cancel graceful shutdown</a><br>";
else
s << " <a href=\"/?cmd=" << HTTP_COMMAND_SHUTDOWN_START << "&token=" << token << "\">Start graceful shutdown</a><br>\r\n";
#endif
#ifdef WIN32_APP
s << " <a href=\"/?cmd=" << HTTP_COMMAND_SHUTDOWN_START << "&token=" << token << "\">Graceful shutdown</a><br>\r\n";
#endif
s << " <a href=\"/?cmd=" << HTTP_COMMAND_SHUTDOWN_NOW << "&token=" << token << "\">Force shutdown</a><br>\r\n";
}
static void ShowTransitTunnels (std::stringstream& s)
{
s << "<b>Transit tunnels:</b><br>\r\n<br>\r\n";
for (const auto& it: i2p::tunnel::tunnels.GetTransitTunnels ())
{
if (std::dynamic_pointer_cast<i2p::tunnel::TransitTunnelGateway>(it))
s << it->GetTunnelID () << " &#8658; ";
else if (std::dynamic_pointer_cast<i2p::tunnel::TransitTunnelEndpoint>(it))
s << " &#8658; " << it->GetTunnelID ();
else
s << " &#8658; " << it->GetTunnelID () << " &#8658; ";
s << " " << it->GetNumTransmittedBytes () << "<br>\r\n";
}
}
static void ShowTransports (std::stringstream& s)
{
s << "<b>Transports:</b><br>\r\n<br>\r\n";
auto ntcpServer = i2p::transport::transports.GetNTCPServer ();
if (ntcpServer)
{
auto sessions = ntcpServer->GetNTCPSessions ();
s << "<b>NTCP</b> ( " << (int) sessions.size() << " )<br>\r\n";
for (const auto& it: sessions )
{
if (it.second && it.second->IsEstablished ())
{
// incoming connection doesn't have remote RI
if (it.second->IsOutgoing ()) s << " &#8658; ";
s << i2p::data::GetIdentHashAbbreviation (it.second->GetRemoteIdentity ()->GetIdentHash ()) << ": "
<< it.second->GetSocket ().remote_endpoint().address ().to_string ();
if (!it.second->IsOutgoing ()) s << " &#8658; ";
s << " [" << it.second->GetNumSentBytes () << ":" << it.second->GetNumReceivedBytes () << "]";
s << "<br>\r\n" << std::endl;
}
}
}
auto ssuServer = i2p::transport::transports.GetSSUServer ();
if (ssuServer)
{
auto sessions = ssuServer->GetSessions ();
s << "<br>\r\n<b>SSU</b> ( " << (int) sessions.size() << " )<br>\r\n";
for (const auto& it: sessions)
{
auto endpoint = it.second->GetRemoteEndpoint ();
if (it.second->IsOutgoing ()) s << " &#8658; ";
s << endpoint.address ().to_string () << ":" << endpoint.port ();
if (!it.second->IsOutgoing ()) s << " &#8658; ";
s << " [" << it.second->GetNumSentBytes () << ":" << it.second->GetNumReceivedBytes () << "]";
if (it.second->GetRelayTag ())
s << " [itag:" << it.second->GetRelayTag () << "]";
s << "<br>\r\n" << std::endl;
}
s << "<br>\r\n<b>SSU6</b><br>\r\n";
for (const auto& it: ssuServer->GetSessionsV6 ())
{
auto endpoint = it.second->GetRemoteEndpoint ();
if (it.second->IsOutgoing ()) s << " &#8658; ";
s << endpoint.address ().to_string () << ":" << endpoint.port ();
if (!it.second->IsOutgoing ()) s << " &#8658; ";
s << " [" << it.second->GetNumSentBytes () << ":" << it.second->GetNumReceivedBytes () << "]";
s << "<br>\r\n" << std::endl;
}
}
}
static void ShowSAMSessions (std::stringstream& s)
{
auto sam = i2p::client::context.GetSAMBridge ();
if (!sam) {
ShowError(s, "SAM disabled");
return;
}
s << "<b>SAM Sessions:</b><br>\r\n<br>\r\n";
for (auto& it: sam->GetSessions ())
{
s << "<a href=\"/?page=" << HTTP_PAGE_SAM_SESSION << "&sam_id=" << it.first << "\">";
s << it.first << "</a><br>\r\n" << std::endl;
}
}
static void ShowSAMSession (std::stringstream& s, const std::string& id)
{
s << "<b>SAM Session:</b><br>\r\n<br>\r\n";
auto sam = i2p::client::context.GetSAMBridge ();
if (!sam) {
ShowError(s, "SAM disabled");
return;
}
auto session = sam->FindSession (id);
if (!session) {
ShowError(s, "SAM session not found");
return;
}
auto& ident = session->localDestination->GetIdentHash();
s << "<a href=\"/?page=" << HTTP_PAGE_LOCAL_DESTINATION << "&b32=" << ident.ToBase32 () << "\">";
s << i2p::client::context.GetAddressBook ().ToAddress(ident) << "</a><br>\r\n";
s << "<br>\r\n";
s << "<b>Streams:</b><br>\r\n";
for (const auto& it: session->ListSockets())
{
switch (it->GetSocketType ())
{
case i2p::client::eSAMSocketTypeSession : s << "session"; break;
case i2p::client::eSAMSocketTypeStream : s << "stream"; break;
case i2p::client::eSAMSocketTypeAcceptor : s << "acceptor"; break;
default: s << "unknown"; break;
}
s << " [" << it->GetSocket ().remote_endpoint() << "]";
s << "<br>\r\n";
}
}
static void ShowI2PTunnels (std::stringstream& s)
{
s << "<b>Client Tunnels:</b><br>\r\n<br>\r\n";
for (auto& it: i2p::client::context.GetClientTunnels ())
{
auto& ident = it.second->GetLocalDestination ()->GetIdentHash();
s << "<a href=\"/?page=" << HTTP_PAGE_LOCAL_DESTINATION << "&b32=" << ident.ToBase32 () << "\">";
s << it.second->GetName () << "</a> &#8656; ";
s << i2p::client::context.GetAddressBook ().ToAddress(ident);
s << "<br>\r\n"<< std::endl;
}
auto httpProxy = i2p::client::context.GetHttpProxy ();
if (httpProxy)
{
auto& ident = httpProxy->GetLocalDestination ()->GetIdentHash();
s << "<a href=\"/?page=" << HTTP_PAGE_LOCAL_DESTINATION << "&b32=" << ident.ToBase32 () << "\">";
s << "HTTP Proxy" << "</a> &#8656; ";
s << i2p::client::context.GetAddressBook ().ToAddress(ident);
s << "<br>\r\n"<< std::endl;
}
auto socksProxy = i2p::client::context.GetSocksProxy ();
if (socksProxy)
{
auto& ident = socksProxy->GetLocalDestination ()->GetIdentHash();
s << "<a href=\"/?page=" << HTTP_PAGE_LOCAL_DESTINATION << "&b32=" << ident.ToBase32 () << "\">";
s << "SOCKS Proxy" << "</a> &#8656; ";
s << i2p::client::context.GetAddressBook ().ToAddress(ident);
s << "<br>\r\n"<< std::endl;
}
s << "<br>\r\n<b>Server Tunnels:</b><br>\r\n<br>\r\n";
for (auto& it: i2p::client::context.GetServerTunnels ())
{
auto& ident = it.second->GetLocalDestination ()->GetIdentHash();
s << "<a href=\"/?page=" << HTTP_PAGE_LOCAL_DESTINATION << "&b32=" << ident.ToBase32 () << "\">";
s << it.second->GetName () << "</a> &#8658; ";
s << i2p::client::context.GetAddressBook ().ToAddress(ident);
s << ":" << it.second->GetLocalPort ();
s << "</a><br>\r\n"<< std::endl;
}
auto& clientForwards = i2p::client::context.GetClientForwards ();
if (!clientForwards.empty ())
{
s << "<br>\r\n<b>Client Forwards:</b><br>\r\n<br>\r\n";
for (auto& it: clientForwards)
{
auto& ident = it.second->GetLocalDestination ()->GetIdentHash();
s << "<a href=\"/?page=" << HTTP_PAGE_LOCAL_DESTINATION << "&b32=" << ident.ToBase32 () << "\">";
s << it.second->GetName () << "</a> &#8656; ";
s << i2p::client::context.GetAddressBook ().ToAddress(ident);
s << "<br>\r\n"<< std::endl;
}
}
auto& serverForwards = i2p::client::context.GetServerForwards ();
if (!serverForwards.empty ())
{
s << "<br>\r\n<b>Server Forwards:</b><br>\r\n<br>\r\n";
for (auto& it: serverForwards)
{
auto& ident = it.second->GetLocalDestination ()->GetIdentHash();
s << "<a href=\"/?page=" << HTTP_PAGE_LOCAL_DESTINATION << "&b32=" << ident.ToBase32 () << "\">";
s << it.second->GetName () << "</a> &#8656; ";
s << i2p::client::context.GetAddressBook ().ToAddress(ident);
s << "<br>\r\n"<< std::endl;
}
}
}
HTTPConnection::HTTPConnection (std::shared_ptr<boost::asio::ip::tcp::socket> socket):
m_Socket (socket), m_Timer (socket->get_io_service ()), m_BufferLen (0)
{
/* cache options */
i2p::config::GetOption("http.auth", needAuth);
i2p::config::GetOption("http.user", user);
i2p::config::GetOption("http.pass", pass);
}
void HTTPConnection::Receive ()
{
m_Socket->async_read_some (boost::asio::buffer (m_Buffer, HTTP_CONNECTION_BUFFER_SIZE),
std::bind(&HTTPConnection::HandleReceive, shared_from_this (),
std::placeholders::_1, std::placeholders::_2));
}
void HTTPConnection::HandleReceive (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode) {
if (ecode != boost::asio::error::operation_aborted)
Terminate (ecode);
return;
}
m_Buffer[bytes_transferred] = '\0';
m_BufferLen = bytes_transferred;
RunRequest();
Receive ();
}
void HTTPConnection::RunRequest ()
{
HTTPReq request;
int ret = request.parse(m_Buffer);
if (ret < 0) {
m_Buffer[0] = '\0';
m_BufferLen = 0;
return; /* error */
}
if (ret == 0)
return; /* need more data */
HandleRequest (request);
}
void HTTPConnection::Terminate (const boost::system::error_code& ecode)
{
if (ecode == boost::asio::error::operation_aborted)
return;
boost::system::error_code ignored_ec;
m_Socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
m_Socket->close ();
}
bool HTTPConnection::CheckAuth (const HTTPReq & req) {
/* method #1: http://user:pass@127.0.0.1:7070/ */
if (req.uri.find('@') != std::string::npos) {
URL url;
if (url.parse(req.uri) && url.user == user && url.pass == pass)
return true;
}
/* method #2: 'Authorization' header sent */
auto provided = req.GetHeader ("Authorization");
if (provided.length () > 0)
{
bool result = false;
std::string expected = user + ":" + pass;
size_t b64_sz = i2p::data::Base64EncodingBufferSize(expected.length()) + 1;
char * b64_creds = new char[b64_sz];
std::size_t len = 0;
len = i2p::data::ByteStreamToBase64((unsigned char *)expected.c_str(), expected.length(), b64_creds, b64_sz);
/* if we decoded properly then check credentials */
if(len) {
b64_creds[len] = '\0';
expected = "Basic ";
expected += b64_creds;
result = expected == provided;
}
delete [] b64_creds;
return result;
}
LogPrint(eLogWarning, "HTTPServer: auth failure from ", m_Socket->remote_endpoint().address ());
return false;
}
void HTTPConnection::HandleRequest (const HTTPReq & req)
{
std::stringstream s;
std::string content;
HTTPRes res;
LogPrint(eLogDebug, "HTTPServer: request: ", req.uri);
if (needAuth && !CheckAuth(req)) {
res.code = 401;
res.add_header("WWW-Authenticate", "Basic realm=\"WebAdmin\"");
SendReply(res, content);
return;
}
// Html5 head start
ShowPageHead (s);
if (req.uri.find("page=") != std::string::npos) {
HandlePage (req, res, s);
} else if (req.uri.find("cmd=") != std::string::npos) {
HandleCommand (req, res, s);
} else {
ShowStatus (s);
res.add_header("Refresh", "10");
}
ShowPageTail (s);
res.code = 200;
content = s.str ();
SendReply (res, content);
}
std::map<uint32_t, uint32_t> HTTPConnection::m_Tokens;
void HTTPConnection::HandlePage (const HTTPReq& req, HTTPRes& res, std::stringstream& s)
{
std::map<std::string, std::string> params;
std::string page("");
URL url;
url.parse(req.uri);
url.parse_query(params);
page = params["page"];
if (page == HTTP_PAGE_TRANSPORTS)
ShowTransports (s);
else if (page == HTTP_PAGE_TUNNELS)
ShowTunnels (s);
else if (page == HTTP_PAGE_COMMANDS)
{
uint32_t token;
RAND_bytes ((uint8_t *)&token, 4);
token &= 0x7FFFFFFF; // clear first bit
auto ts = i2p::util::GetSecondsSinceEpoch ();
for (auto it = m_Tokens.begin (); it != m_Tokens.end (); )
{
if (ts > it->second + TOKEN_EXPIRATION_TIMEOUT)
it = m_Tokens.erase (it);
else
++it;
}
m_Tokens[token] = ts;
ShowCommands (s, token);
}
else if (page == HTTP_PAGE_TRANSIT_TUNNELS)
ShowTransitTunnels (s);
else if (page == HTTP_PAGE_LOCAL_DESTINATIONS)
ShowLocalDestinations (s);
else if (page == HTTP_PAGE_LOCAL_DESTINATION)
ShowLocalDestination (s, params["b32"]);
else if (page == HTTP_PAGE_I2CP_LOCAL_DESTINATION)
ShowI2CPLocalDestination (s, params["i2cp_id"]);
else if (page == HTTP_PAGE_SAM_SESSIONS)
ShowSAMSessions (s);
else if (page == HTTP_PAGE_SAM_SESSION)
ShowSAMSession (s, params["sam_id"]);
else if (page == HTTP_PAGE_I2P_TUNNELS)
ShowI2PTunnels (s);
else if (page == HTTP_PAGE_LEASESETS)
ShowLeasesSets(s);
else {
res.code = 400;
ShowError(s, "Unknown page: " + page);
return;
}
}
void HTTPConnection::HandleCommand (const HTTPReq& req, HTTPRes& res, std::stringstream& s)
{
std::map<std::string, std::string> params;
URL url;
url.parse(req.uri);
url.parse_query(params);
std::string token = params["token"];
if (token.empty () || m_Tokens.find (std::stoi (token)) == m_Tokens.end ())
{
ShowError(s, "Invalid token");
return;
}
std::string cmd = params["cmd"];
if (cmd == HTTP_COMMAND_RUN_PEER_TEST)
i2p::transport::transports.PeerTest ();
else if (cmd == HTTP_COMMAND_RELOAD_CONFIG)
i2p::client::context.ReloadConfig ();
else if (cmd == HTTP_COMMAND_ENABLE_TRANSIT)
i2p::context.SetAcceptsTunnels (true);
else if (cmd == HTTP_COMMAND_DISABLE_TRANSIT)
i2p::context.SetAcceptsTunnels (false);
else if (cmd == HTTP_COMMAND_SHUTDOWN_START) {
i2p::context.SetAcceptsTunnels (false);
#if (!defined(WIN32) && !defined(QT_GUI_LIB) && !defined(ANDROID))
Daemon.gracefulShutdownInterval = 10*60;
#endif
#ifdef WIN32_APP
i2p::win32::GracefulShutdown ();
#endif
} else if (cmd == HTTP_COMMAND_SHUTDOWN_CANCEL) {
i2p::context.SetAcceptsTunnels (true);
#if (!defined(WIN32) && !defined(QT_GUI_LIB) && !defined(ANDROID))
Daemon.gracefulShutdownInterval = 0;
#endif
} else if (cmd == HTTP_COMMAND_SHUTDOWN_NOW) {
Daemon.running = false;
} else {
res.code = 400;
ShowError(s, "Unknown command: " + cmd);
return;
}
s << "<b>SUCCESS</b>:&nbsp;Command accepted<br><br>\r\n";
s << "<a href=\"/?page=commands\">Back to commands list</a><br>\r\n";
s << "<p>You will be redirected in 5 seconds</b>";
res.add_header("Refresh", "5; url=/?page=commands");
}
void HTTPConnection::SendReply (HTTPRes& reply, std::string& content)
{
reply.add_header("X-Frame-Options", "SAMEORIGIN");
reply.add_header("Content-Type", "text/html");
reply.body = content;
m_SendBuffer = reply.to_string();
boost::asio::async_write (*m_Socket, boost::asio::buffer(m_SendBuffer),
std::bind (&HTTPConnection::Terminate, shared_from_this (), std::placeholders::_1));
}
HTTPServer::HTTPServer (const std::string& address, int port):
m_IsRunning (false), m_Thread (nullptr), m_Work (m_Service),
m_Acceptor (m_Service, boost::asio::ip::tcp::endpoint (boost::asio::ip::address::from_string(address), port))
{
}
HTTPServer::~HTTPServer ()
{
Stop ();
}
void HTTPServer::Start ()
{
bool needAuth; i2p::config::GetOption("http.auth", needAuth);
std::string user; i2p::config::GetOption("http.user", user);
std::string pass; i2p::config::GetOption("http.pass", pass);
/* generate pass if needed */
if (needAuth && pass == "") {
uint8_t random[16];
char alnum[] = "0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
pass.resize(sizeof(random));
RAND_bytes(random, sizeof(random));
for (size_t i = 0; i < sizeof(random); i++) {
pass[i] = alnum[random[i] % (sizeof(alnum) - 1)];
}
i2p::config::SetOption("http.pass", pass);
LogPrint(eLogInfo, "HTTPServer: password set to ", pass);
}
m_IsRunning = true;
m_Thread = std::unique_ptr<std::thread>(new std::thread (std::bind (&HTTPServer::Run, this)));
m_Acceptor.listen ();
Accept ();
}
void HTTPServer::Stop ()
{
m_IsRunning = false;
m_Acceptor.close();
m_Service.stop ();
if (m_Thread)
{
m_Thread->join ();
m_Thread = nullptr;
}
}
void HTTPServer::Run ()
{
while (m_IsRunning)
{
try
{
m_Service.run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "HTTPServer: runtime exception: ", ex.what ());
}
}
}
void HTTPServer::Accept ()
{
auto newSocket = std::make_shared<boost::asio::ip::tcp::socket> (m_Service);
m_Acceptor.async_accept (*newSocket, boost::bind (&HTTPServer::HandleAccept, this,
boost::asio::placeholders::error, newSocket));
}
void HTTPServer::HandleAccept(const boost::system::error_code& ecode,
std::shared_ptr<boost::asio::ip::tcp::socket> newSocket)
{
if (ecode)
{
if(newSocket) newSocket->close();
LogPrint(eLogError, "HTTP Server: error handling accept ", ecode.message());
if(ecode != boost::asio::error::operation_aborted)
Accept();
return;
}
CreateConnection(newSocket);
Accept ();
}
void HTTPServer::CreateConnection(std::shared_ptr<boost::asio::ip::tcp::socket> newSocket)
{
auto conn = std::make_shared<HTTPConnection> (newSocket);
conn->Receive ();
}
} // http
} // i2p

View File

@ -1,81 +0,0 @@
#ifndef HTTP_SERVER_H__
#define HTTP_SERVER_H__
#include <inttypes.h>
#include <string>
#include <memory>
#include <map>
#include <thread>
#include <boost/asio.hpp>
#include "HTTP.h"
namespace i2p
{
namespace http
{
const size_t HTTP_CONNECTION_BUFFER_SIZE = 8192;
const int TOKEN_EXPIRATION_TIMEOUT = 30; // in seconds
class HTTPConnection: public std::enable_shared_from_this<HTTPConnection>
{
public:
HTTPConnection (std::shared_ptr<boost::asio::ip::tcp::socket> socket);
void Receive ();
private:
void HandleReceive (const boost::system::error_code& ecode, std::size_t bytes_transferred);
void Terminate (const boost::system::error_code& ecode);
void RunRequest ();
bool CheckAuth (const HTTPReq & req);
void HandleRequest (const HTTPReq & req);
void HandlePage (const HTTPReq & req, HTTPRes & res, std::stringstream& data);
void HandleCommand (const HTTPReq & req, HTTPRes & res, std::stringstream& data);
void SendReply (HTTPRes & res, std::string & content);
private:
std::shared_ptr<boost::asio::ip::tcp::socket> m_Socket;
boost::asio::deadline_timer m_Timer;
char m_Buffer[HTTP_CONNECTION_BUFFER_SIZE + 1];
size_t m_BufferLen;
std::string m_SendBuffer;
bool needAuth;
std::string user;
std::string pass;
static std::map<uint32_t, uint32_t> m_Tokens; // token->timestamp in seconds
};
class HTTPServer
{
public:
HTTPServer (const std::string& address, int port);
~HTTPServer ();
void Start ();
void Stop ();
private:
void Run ();
void Accept ();
void HandleAccept(const boost::system::error_code& ecode,
std::shared_ptr<boost::asio::ip::tcp::socket> newSocket);
void CreateConnection(std::shared_ptr<boost::asio::ip::tcp::socket> newSocket);
private:
bool m_IsRunning;
std::unique_ptr<std::thread> m_Thread;
boost::asio::io_service m_Service;
boost::asio::io_service::work m_Work;
boost::asio::ip::tcp::acceptor m_Acceptor;
};
} // http
} // i2p
#endif /* HTTP_SERVER_H__ */

744
I2CP.cpp
View File

@ -1,744 +0,0 @@
/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <string.h>
#include <stdlib.h>
#include <openssl/rand.h>
#include "I2PEndian.h"
#include "Log.h"
#include "Timestamp.h"
#include "LeaseSet.h"
#include "ClientContext.h"
#include "Transports.h"
#include "Signature.h"
#include "I2CP.h"
namespace i2p
{
namespace client
{
I2CPDestination::I2CPDestination (std::shared_ptr<I2CPSession> owner, std::shared_ptr<const i2p::data::IdentityEx> identity, bool isPublic, const std::map<std::string, std::string>& params):
LeaseSetDestination (isPublic, &params), m_Owner (owner), m_Identity (identity)
{
}
void I2CPDestination::SetEncryptionPrivateKey (const uint8_t * key)
{
memcpy (m_EncryptionPrivateKey, key, 256);
}
void I2CPDestination::HandleDataMessage (const uint8_t * buf, size_t len)
{
uint32_t length = bufbe32toh (buf);
if (length > len - 4) length = len - 4;
m_Owner->SendMessagePayloadMessage (buf + 4, length);
}
void I2CPDestination::CreateNewLeaseSet (std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels)
{
i2p::data::LocalLeaseSet ls (m_Identity, m_EncryptionPrivateKey, tunnels); // we don't care about encryption key
m_LeaseSetExpirationTime = ls.GetExpirationTime ();
uint8_t * leases = ls.GetLeases ();
leases[-1] = tunnels.size ();
htobe16buf (leases - 3, m_Owner->GetSessionID ());
size_t l = 2/*sessionID*/ + 1/*num leases*/ + i2p::data::LEASE_SIZE*tunnels.size ();
m_Owner->SendI2CPMessage (I2CP_REQUEST_VARIABLE_LEASESET_MESSAGE, leases - 3, l);
}
void I2CPDestination::LeaseSetCreated (const uint8_t * buf, size_t len)
{
auto ls = new i2p::data::LocalLeaseSet (m_Identity, buf, len);
ls->SetExpirationTime (m_LeaseSetExpirationTime);
SetLeaseSet (ls);
}
void I2CPDestination::SendMsgTo (const uint8_t * payload, size_t len, const i2p::data::IdentHash& ident, uint32_t nonce)
{
auto msg = NewI2NPMessage ();
uint8_t * buf = msg->GetPayload ();
htobe32buf (buf, len);
memcpy (buf + 4, payload, len);
msg->len += len + 4;
msg->FillI2NPMessageHeader (eI2NPData);
auto s = GetSharedFromThis ();
auto remote = FindLeaseSet (ident);
if (remote)
{
GetService ().post (
[s, msg, remote, nonce]()
{
bool sent = s->SendMsg (msg, remote);
s->m_Owner->SendMessageStatusMessage (nonce, sent ? eI2CPMessageStatusGuaranteedSuccess : eI2CPMessageStatusGuaranteedFailure);
});
}
else
{
RequestDestination (ident,
[s, msg, nonce](std::shared_ptr<i2p::data::LeaseSet> ls)
{
if (ls)
{
bool sent = s->SendMsg (msg, ls);
s->m_Owner->SendMessageStatusMessage (nonce, sent ? eI2CPMessageStatusGuaranteedSuccess : eI2CPMessageStatusGuaranteedFailure);
}
else
s->m_Owner->SendMessageStatusMessage (nonce, eI2CPMessageStatusNoLeaseSet);
});
}
}
bool I2CPDestination::SendMsg (std::shared_ptr<I2NPMessage> msg, std::shared_ptr<const i2p::data::LeaseSet> remote)
{
auto remoteSession = GetRoutingSession (remote, true);
if (!remoteSession)
{
LogPrint (eLogError, "I2CP: Failed to create remote session");
return false;
}
auto path = remoteSession->GetSharedRoutingPath ();
std::shared_ptr<i2p::tunnel::OutboundTunnel> outboundTunnel;
std::shared_ptr<const i2p::data::Lease> remoteLease;
if (path)
{
if (!remoteSession->CleanupUnconfirmedTags ()) // no stuck tags
{
outboundTunnel = path->outboundTunnel;
remoteLease = path->remoteLease;
}
else
remoteSession->SetSharedRoutingPath (nullptr);
}
else
{
outboundTunnel = GetTunnelPool ()->GetNextOutboundTunnel ();
auto leases = remote->GetNonExpiredLeases ();
if (!leases.empty ())
remoteLease = leases[rand () % leases.size ()];
if (remoteLease && outboundTunnel)
remoteSession->SetSharedRoutingPath (std::make_shared<i2p::garlic::GarlicRoutingPath> (
i2p::garlic::GarlicRoutingPath{outboundTunnel, remoteLease, 10000, 0, 0})); // 10 secs RTT
else
remoteSession->SetSharedRoutingPath (nullptr);
}
if (remoteLease && outboundTunnel)
{
std::vector<i2p::tunnel::TunnelMessageBlock> msgs;
auto garlic = remoteSession->WrapSingleMessage (msg);
msgs.push_back (i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeTunnel,
remoteLease->tunnelGateway, remoteLease->tunnelID,
garlic
});
outboundTunnel->SendTunnelDataMsg (msgs);
return true;
}
else
{
if (outboundTunnel)
LogPrint (eLogWarning, "I2CP: Failed to send message. All leases expired");
else
LogPrint (eLogWarning, "I2CP: Failed to send message. No outbound tunnels");
return false;
}
}
I2CPSession::I2CPSession (I2CPServer& owner, std::shared_ptr<proto::socket> socket):
m_Owner (owner), m_Socket (socket), m_Payload (nullptr),
m_SessionID (0xFFFF), m_MessageID (0), m_IsSendAccepted (true)
{
}
I2CPSession::~I2CPSession ()
{
delete[] m_Payload;
}
void I2CPSession::Start ()
{
ReadProtocolByte ();
}
void I2CPSession::Stop ()
{
Terminate ();
}
void I2CPSession::ReadProtocolByte ()
{
if (m_Socket)
{
auto s = shared_from_this ();
m_Socket->async_read_some (boost::asio::buffer (m_Header, 1),
[s](const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (!ecode && bytes_transferred > 0 && s->m_Header[0] == I2CP_PROTOCOL_BYTE)
s->ReceiveHeader ();
else
s->Terminate ();
});
}
}
void I2CPSession::ReceiveHeader ()
{
boost::asio::async_read (*m_Socket, boost::asio::buffer (m_Header, I2CP_HEADER_SIZE),
boost::asio::transfer_all (),
std::bind (&I2CPSession::HandleReceivedHeader, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
}
void I2CPSession::HandleReceivedHeader (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
Terminate ();
else
{
m_PayloadLen = bufbe32toh (m_Header + I2CP_HEADER_LENGTH_OFFSET);
if (m_PayloadLen > 0)
{
m_Payload = new uint8_t[m_PayloadLen];
ReceivePayload ();
}
else // no following payload
{
HandleMessage ();
ReceiveHeader (); // next message
}
}
}
void I2CPSession::ReceivePayload ()
{
boost::asio::async_read (*m_Socket, boost::asio::buffer (m_Payload, m_PayloadLen),
boost::asio::transfer_all (),
std::bind (&I2CPSession::HandleReceivedPayload, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
}
void I2CPSession::HandleReceivedPayload (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
Terminate ();
else
{
HandleMessage ();
delete[] m_Payload;
m_Payload = nullptr;
m_PayloadLen = 0;
ReceiveHeader (); // next message
}
}
void I2CPSession::HandleMessage ()
{
auto handler = m_Owner.GetMessagesHandlers ()[m_Header[I2CP_HEADER_TYPE_OFFSET]];
if (handler)
(this->*handler)(m_Payload, m_PayloadLen);
else
LogPrint (eLogError, "I2CP: Unknown I2CP messsage ", (int)m_Header[I2CP_HEADER_TYPE_OFFSET]);
}
void I2CPSession::Terminate ()
{
if (m_Destination)
{
m_Destination->Stop ();
m_Destination = nullptr;
}
if (m_Socket)
{
m_Socket->close ();
m_Socket = nullptr;
}
m_Owner.RemoveSession (GetSessionID ());
LogPrint (eLogDebug, "I2CP: session ", m_SessionID, " terminated");
}
void I2CPSession::SendI2CPMessage (uint8_t type, const uint8_t * payload, size_t len)
{
auto socket = m_Socket;
if (socket)
{
auto l = len + I2CP_HEADER_SIZE;
uint8_t * buf = new uint8_t[l];
htobe32buf (buf + I2CP_HEADER_LENGTH_OFFSET, len);
buf[I2CP_HEADER_TYPE_OFFSET] = type;
memcpy (buf + I2CP_HEADER_SIZE, payload, len);
boost::asio::async_write (*socket, boost::asio::buffer (buf, l), boost::asio::transfer_all (),
std::bind(&I2CPSession::HandleI2CPMessageSent, shared_from_this (),
std::placeholders::_1, std::placeholders::_2, buf));
}
else
LogPrint (eLogError, "I2CP: Can't write to the socket");
}
void I2CPSession::HandleI2CPMessageSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, const uint8_t * buf)
{
delete[] buf;
if (ecode && ecode != boost::asio::error::operation_aborted)
Terminate ();
}
std::string I2CPSession::ExtractString (const uint8_t * buf, size_t len)
{
uint8_t l = buf[0];
if (l > len) l = len;
return std::string ((const char *)(buf + 1), l);
}
size_t I2CPSession::PutString (uint8_t * buf, size_t len, const std::string& str)
{
auto l = str.length ();
if (l + 1 >= len) l = len - 1;
if (l > 255) l = 255; // 1 byte max
buf[0] = l;
memcpy (buf + 1, str.c_str (), l);
return l + 1;
}
void I2CPSession::ExtractMapping (const uint8_t * buf, size_t len, std::map<std::string, std::string>& mapping)
// TODO: move to Base.cpp
{
size_t offset = 0;
while (offset < len)
{
std::string param = ExtractString (buf + offset, len - offset);
offset += param.length () + 1;
if (buf[offset] != '=')
{
LogPrint (eLogWarning, "I2CP: Unexpected character ", buf[offset], " instead '=' after ", param);
break;
}
offset++;
std::string value = ExtractString (buf + offset, len - offset);
offset += value.length () + 1;
if (buf[offset] != ';')
{
LogPrint (eLogWarning, "I2CP: Unexpected character ", buf[offset], " instead ';' after ", value);
break;
}
offset++;
mapping.insert (std::make_pair (param, value));
}
}
void I2CPSession::GetDateMessageHandler (const uint8_t * buf, size_t len)
{
// get version
auto version = ExtractString (buf, len);
auto l = version.length () + 1 + 8;
uint8_t * payload = new uint8_t[l];
// set date
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
htobe64buf (payload, ts);
// echo vesrion back
PutString (payload + 8, l - 8, version);
SendI2CPMessage (I2CP_SET_DATE_MESSAGE, payload, l);
delete[] payload;
}
void I2CPSession::CreateSessionMessageHandler (const uint8_t * buf, size_t len)
{
RAND_bytes ((uint8_t *)&m_SessionID, 2);
m_Owner.InsertSession (shared_from_this ());
auto identity = std::make_shared<i2p::data::IdentityEx>();
size_t offset = identity->FromBuffer (buf, len);
if (!offset)
{
LogPrint (eLogError, "I2CP: create session maformed identity");
SendSessionStatusMessage (3); // invalid
return;
}
uint16_t optionsSize = bufbe16toh (buf + offset);
offset += 2;
if (optionsSize > len - offset)
{
LogPrint (eLogError, "I2CP: options size ", optionsSize, "exceeds message size");
SendSessionStatusMessage (3); // invalid
return;
}
std::map<std::string, std::string> params;
ExtractMapping (buf + offset, optionsSize, params);
offset += optionsSize; // options
if (params[I2CP_PARAM_MESSAGE_RELIABILITY] == "none") m_IsSendAccepted = false;
offset += 8; // date
if (identity->Verify (buf, offset, buf + offset)) // signature
{
bool isPublic = true;
if (params[I2CP_PARAM_DONT_PUBLISH_LEASESET] == "true") isPublic = false;
if (!m_Destination)
{
m_Destination = std::make_shared<I2CPDestination>(shared_from_this (), identity, isPublic, params);
SendSessionStatusMessage (1); // created
LogPrint (eLogDebug, "I2CP: session ", m_SessionID, " created");
m_Destination->Start ();
}
else
{
LogPrint (eLogError, "I2CP: session already exists");
SendSessionStatusMessage (4); // refused
}
}
else
{
LogPrint (eLogError, "I2CP: create session signature verification falied");
SendSessionStatusMessage (3); // invalid
}
}
void I2CPSession::DestroySessionMessageHandler (const uint8_t * buf, size_t len)
{
SendSessionStatusMessage (0); // destroy
LogPrint (eLogDebug, "I2CP: session ", m_SessionID, " destroyed");
if (m_Destination)
{
m_Destination->Stop ();
m_Destination = 0;
}
}
void I2CPSession::ReconfigureSessionMessageHandler (const uint8_t * buf, size_t len)
{
// TODO: implement actual reconfiguration
SendSessionStatusMessage (2); // updated
}
void I2CPSession::SendSessionStatusMessage (uint8_t status)
{
uint8_t buf[3];
htobe16buf (buf, m_SessionID);
buf[2] = status;
SendI2CPMessage (I2CP_SESSION_STATUS_MESSAGE, buf, 3);
}
void I2CPSession::SendMessageStatusMessage (uint32_t nonce, I2CPMessageStatus status)
{
if (!nonce) return; // don't send status with zero nonce
uint8_t buf[15];
htobe16buf (buf, m_SessionID);
htobe32buf (buf + 2, m_MessageID++);
buf[6] = (uint8_t)status;
memset (buf + 7, 0, 4); // size
htobe32buf (buf + 11, nonce);
SendI2CPMessage (I2CP_MESSAGE_STATUS_MESSAGE, buf, 15);
}
void I2CPSession::CreateLeaseSetMessageHandler (const uint8_t * buf, size_t len)
{
uint16_t sessionID = bufbe16toh (buf);
if (sessionID == m_SessionID)
{
size_t offset = 2;
if (m_Destination)
{
offset += i2p::crypto::DSA_PRIVATE_KEY_LENGTH; // skip signing private key
// we always assume this field as 20 bytes (DSA) regardless actual size
// instead of
//offset += m_Destination->GetIdentity ()->GetSigningPrivateKeyLen ();
m_Destination->SetEncryptionPrivateKey (buf + offset);
offset += 256;
m_Destination->LeaseSetCreated (buf + offset, len - offset);
}
}
else
LogPrint (eLogError, "I2CP: unexpected sessionID ", sessionID);
}
void I2CPSession::SendMessageMessageHandler (const uint8_t * buf, size_t len)
{
uint16_t sessionID = bufbe16toh (buf);
if (sessionID == m_SessionID)
{
size_t offset = 2;
if (m_Destination)
{
i2p::data::IdentityEx identity;
size_t identsize = identity.FromBuffer (buf + offset, len - offset);
if (identsize)
{
offset += identsize;
uint32_t payloadLen = bufbe32toh (buf + offset);
if (payloadLen + offset <= len)
{
offset += 4;
uint32_t nonce = bufbe32toh (buf + offset + payloadLen);
if (m_IsSendAccepted)
SendMessageStatusMessage (nonce, eI2CPMessageStatusAccepted); // accepted
m_Destination->SendMsgTo (buf + offset, payloadLen, identity.GetIdentHash (), nonce);
}
else
LogPrint(eLogError, "I2CP: cannot send message, too big");
}
else
LogPrint(eLogError, "I2CP: invalid identity");
}
}
else
LogPrint (eLogError, "I2CP: unexpected sessionID ", sessionID);
}
void I2CPSession::SendMessageExpiresMessageHandler (const uint8_t * buf, size_t len)
{
SendMessageMessageHandler (buf, len - 8); // ignore flags(2) and expiration(6)
}
void I2CPSession::HostLookupMessageHandler (const uint8_t * buf, size_t len)
{
uint16_t sessionID = bufbe16toh (buf);
if (sessionID == m_SessionID || sessionID == 0xFFFF) // -1 means without session
{
uint32_t requestID = bufbe32toh (buf + 2);
//uint32_t timeout = bufbe32toh (buf + 6);
i2p::data::IdentHash ident;
switch (buf[10])
{
case 0: // hash
ident = i2p::data::IdentHash (buf + 11);
break;
case 1: // address
{
auto name = ExtractString (buf + 11, len - 11);
if (!i2p::client::context.GetAddressBook ().GetIdentHash (name, ident))
{
LogPrint (eLogError, "I2CP: address ", name, " not found");
SendHostReplyMessage (requestID, nullptr);
return;
}
break;
}
default:
LogPrint (eLogError, "I2CP: request type ", (int)buf[10], " is not supported");
SendHostReplyMessage (requestID, nullptr);
return;
}
std::shared_ptr<LeaseSetDestination> destination = m_Destination;
if(!destination) destination = i2p::client::context.GetSharedLocalDestination ();
if (destination)
{
auto ls = destination->FindLeaseSet (ident);
if (ls)
SendHostReplyMessage (requestID, ls->GetIdentity ());
else
{
auto s = shared_from_this ();
destination->RequestDestination (ident,
[s, requestID](std::shared_ptr<i2p::data::LeaseSet> leaseSet)
{
s->SendHostReplyMessage (requestID, leaseSet ? leaseSet->GetIdentity () : nullptr);
});
}
}
else
SendHostReplyMessage (requestID, nullptr);
}
else
LogPrint (eLogError, "I2CP: unexpected sessionID ", sessionID);
}
void I2CPSession::SendHostReplyMessage (uint32_t requestID, std::shared_ptr<const i2p::data::IdentityEx> identity)
{
if (identity)
{
size_t l = identity->GetFullLen () + 7;
uint8_t * buf = new uint8_t[l];
htobe16buf (buf, m_SessionID);
htobe32buf (buf + 2, requestID);
buf[6] = 0; // result code
identity->ToBuffer (buf + 7, l - 7);
SendI2CPMessage (I2CP_HOST_REPLY_MESSAGE, buf, l);
delete[] buf;
}
else
{
uint8_t buf[7];
htobe16buf (buf, m_SessionID);
htobe32buf (buf + 2, requestID);
buf[6] = 1; // result code
SendI2CPMessage (I2CP_HOST_REPLY_MESSAGE, buf, 7);
}
}
void I2CPSession::DestLookupMessageHandler (const uint8_t * buf, size_t len)
{
if (m_Destination)
{
auto ls = m_Destination->FindLeaseSet (buf);
if (ls)
{
auto l = ls->GetIdentity ()->GetFullLen ();
uint8_t * identBuf = new uint8_t[l];
ls->GetIdentity ()->ToBuffer (identBuf, l);
SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, identBuf, l);
delete[] identBuf;
}
else
{
auto s = shared_from_this ();
i2p::data::IdentHash ident (buf);
m_Destination->RequestDestination (ident,
[s, ident](std::shared_ptr<i2p::data::LeaseSet> leaseSet)
{
if (leaseSet) // found
{
auto l = leaseSet->GetIdentity ()->GetFullLen ();
uint8_t * identBuf = new uint8_t[l];
leaseSet->GetIdentity ()->ToBuffer (identBuf, l);
s->SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, identBuf, l);
delete[] identBuf;
}
else
s->SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, ident, 32); // not found
});
}
}
else
SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, buf, 32);
}
void I2CPSession::GetBandwidthLimitsMessageHandler (const uint8_t * buf, size_t len)
{
uint8_t limits[64];
memset (limits, 0, 64);
htobe32buf (limits, i2p::transport::transports.GetInBandwidth ()); // inbound
htobe32buf (limits + 4, i2p::transport::transports.GetOutBandwidth ()); // outbound
SendI2CPMessage (I2CP_BANDWIDTH_LIMITS_MESSAGE, limits, 64);
}
void I2CPSession::SendMessagePayloadMessage (const uint8_t * payload, size_t len)
{
// we don't use SendI2CPMessage to eliminate additional copy
auto l = len + 10 + I2CP_HEADER_SIZE;
uint8_t * buf = new uint8_t[l];
htobe32buf (buf + I2CP_HEADER_LENGTH_OFFSET, len + 10);
buf[I2CP_HEADER_TYPE_OFFSET] = I2CP_MESSAGE_PAYLOAD_MESSAGE;
htobe16buf (buf + I2CP_HEADER_SIZE, m_SessionID);
htobe32buf (buf + I2CP_HEADER_SIZE + 2, m_MessageID++);
htobe32buf (buf + I2CP_HEADER_SIZE + 6, len);
memcpy (buf + I2CP_HEADER_SIZE + 10, payload, len);
boost::asio::async_write (*m_Socket, boost::asio::buffer (buf, l), boost::asio::transfer_all (),
std::bind(&I2CPSession::HandleI2CPMessageSent, shared_from_this (),
std::placeholders::_1, std::placeholders::_2, buf));
}
I2CPServer::I2CPServer (const std::string& interface, int port):
m_IsRunning (false), m_Thread (nullptr),
m_Acceptor (m_Service,
#ifdef ANDROID
I2CPSession::proto::endpoint(std::string (1, '\0') + interface)) // leading 0 for abstract address
#else
I2CPSession::proto::endpoint(boost::asio::ip::address::from_string(interface), port))
#endif
{
memset (m_MessagesHandlers, 0, sizeof (m_MessagesHandlers));
m_MessagesHandlers[I2CP_GET_DATE_MESSAGE] = &I2CPSession::GetDateMessageHandler;
m_MessagesHandlers[I2CP_CREATE_SESSION_MESSAGE] = &I2CPSession::CreateSessionMessageHandler;
m_MessagesHandlers[I2CP_DESTROY_SESSION_MESSAGE] = &I2CPSession::DestroySessionMessageHandler;
m_MessagesHandlers[I2CP_RECONFIGURE_SESSION_MESSAGE] = &I2CPSession::ReconfigureSessionMessageHandler;
m_MessagesHandlers[I2CP_CREATE_LEASESET_MESSAGE] = &I2CPSession::CreateLeaseSetMessageHandler;
m_MessagesHandlers[I2CP_SEND_MESSAGE_MESSAGE] = &I2CPSession::SendMessageMessageHandler;
m_MessagesHandlers[I2CP_SEND_MESSAGE_EXPIRES_MESSAGE] = &I2CPSession::SendMessageExpiresMessageHandler;
m_MessagesHandlers[I2CP_HOST_LOOKUP_MESSAGE] = &I2CPSession::HostLookupMessageHandler;
m_MessagesHandlers[I2CP_DEST_LOOKUP_MESSAGE] = &I2CPSession::DestLookupMessageHandler;
m_MessagesHandlers[I2CP_GET_BANDWIDTH_LIMITS_MESSAGE] = &I2CPSession::GetBandwidthLimitsMessageHandler;
}
I2CPServer::~I2CPServer ()
{
if (m_IsRunning)
Stop ();
}
void I2CPServer::Start ()
{
Accept ();
m_IsRunning = true;
m_Thread = new std::thread (std::bind (&I2CPServer::Run, this));
}
void I2CPServer::Stop ()
{
m_IsRunning = false;
m_Acceptor.cancel ();
for (auto& it: m_Sessions)
it.second->Stop ();
m_Sessions.clear ();
m_Service.stop ();
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = nullptr;
}
}
void I2CPServer::Run ()
{
while (m_IsRunning)
{
try
{
m_Service.run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "I2CP: runtime exception: ", ex.what ());
}
}
}
void I2CPServer::Accept ()
{
auto newSocket = std::make_shared<I2CPSession::proto::socket> (m_Service);
m_Acceptor.async_accept (*newSocket, std::bind (&I2CPServer::HandleAccept, this,
std::placeholders::_1, newSocket));
}
void I2CPServer::HandleAccept(const boost::system::error_code& ecode,
std::shared_ptr<I2CPSession::proto::socket> socket)
{
if (!ecode && socket)
{
boost::system::error_code ec;
auto ep = socket->remote_endpoint (ec);
if (!ec)
{
LogPrint (eLogDebug, "I2CP: new connection from ", ep);
auto session = std::make_shared<I2CPSession>(*this, socket);
session->Start ();
}
else
LogPrint (eLogError, "I2CP: incoming connection error ", ec.message ());
}
else
LogPrint (eLogError, "I2CP: accept error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted)
Accept ();
}
bool I2CPServer::InsertSession (std::shared_ptr<I2CPSession> session)
{
if (!session) return false;
if (!m_Sessions.insert({session->GetSessionID (), session}).second)
{
LogPrint (eLogError, "I2CP: duplicate session id ", session->GetSessionID ());
return false;
}
return true;
}
void I2CPServer::RemoveSession (uint16_t sessionID)
{
m_Sessions.erase (sessionID);
}
}
}

View File

@ -1,668 +0,0 @@
#include <string.h>
#include <atomic>
#include "Base.h"
#include "Log.h"
#include "Crypto.h"
#include "I2PEndian.h"
#include "Timestamp.h"
#include "RouterContext.h"
#include "NetDb.h"
#include "Tunnel.h"
#include "Transports.h"
#include "Garlic.h"
#include "I2NPProtocol.h"
#include "version.h"
using namespace i2p::transport;
namespace i2p
{
std::shared_ptr<I2NPMessage> NewI2NPMessage ()
{
return std::make_shared<I2NPMessageBuffer<I2NP_MAX_MESSAGE_SIZE> >();
}
std::shared_ptr<I2NPMessage> NewI2NPShortMessage ()
{
return std::make_shared<I2NPMessageBuffer<I2NP_MAX_SHORT_MESSAGE_SIZE> >();
}
std::shared_ptr<I2NPMessage> NewI2NPTunnelMessage ()
{
auto msg = new I2NPMessageBuffer<i2p::tunnel::TUNNEL_DATA_MSG_SIZE + I2NP_HEADER_SIZE + 34>(); // reserved for alignment and NTCP 16 + 6 + 12
msg->Align (12);
return std::shared_ptr<I2NPMessage>(msg);
}
std::shared_ptr<I2NPMessage> NewI2NPMessage (size_t len)
{
return (len < I2NP_MAX_SHORT_MESSAGE_SIZE/2) ? NewI2NPShortMessage () : NewI2NPMessage ();
}
void I2NPMessage::FillI2NPMessageHeader (I2NPMessageType msgType, uint32_t replyMsgID)
{
SetTypeID (msgType);
if (!replyMsgID) RAND_bytes ((uint8_t *)&replyMsgID, 4);
SetMsgID (replyMsgID);
SetExpiration (i2p::util::GetMillisecondsSinceEpoch () + I2NP_MESSAGE_EXPIRATION_TIMEOUT);
UpdateSize ();
UpdateChks ();
}
void I2NPMessage::RenewI2NPMessageHeader ()
{
uint32_t msgID;
RAND_bytes ((uint8_t *)&msgID, 4);
SetMsgID (msgID);
SetExpiration (i2p::util::GetMillisecondsSinceEpoch () + I2NP_MESSAGE_EXPIRATION_TIMEOUT);
}
bool I2NPMessage::IsExpired () const
{
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
auto exp = GetExpiration ();
return (ts > exp + I2NP_MESSAGE_CLOCK_SKEW) || (ts < exp - 3*I2NP_MESSAGE_CLOCK_SKEW); // check if expired or too far in future
}
std::shared_ptr<I2NPMessage> CreateI2NPMessage (I2NPMessageType msgType, const uint8_t * buf, size_t len, uint32_t replyMsgID)
{
auto msg = NewI2NPMessage (len);
if (msg->Concat (buf, len) < len)
LogPrint (eLogError, "I2NP: message length ", len, " exceeds max length ", msg->maxLen);
msg->FillI2NPMessageHeader (msgType, replyMsgID);
return msg;
}
std::shared_ptr<I2NPMessage> CreateI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from)
{
auto msg = NewI2NPMessage ();
if (msg->offset + len < msg->maxLen)
{
memcpy (msg->GetBuffer (), buf, len);
msg->len = msg->offset + len;
msg->from = from;
}
else
LogPrint (eLogError, "I2NP: message length ", len, " exceeds max length");
return msg;
}
std::shared_ptr<I2NPMessage> CopyI2NPMessage (std::shared_ptr<I2NPMessage> msg)
{
if (!msg) return nullptr;
auto newMsg = NewI2NPMessage (msg->len);
newMsg->offset = msg->offset;
*newMsg = *msg;
return newMsg;
}
std::shared_ptr<I2NPMessage> CreateDeliveryStatusMsg (uint32_t msgID)
{
auto m = NewI2NPShortMessage ();
uint8_t * buf = m->GetPayload ();
if (msgID)
{
htobe32buf (buf + DELIVERY_STATUS_MSGID_OFFSET, msgID);
htobe64buf (buf + DELIVERY_STATUS_TIMESTAMP_OFFSET, i2p::util::GetMillisecondsSinceEpoch ());
}
else // for SSU establishment
{
RAND_bytes ((uint8_t *)&msgID, 4);
htobe32buf (buf + DELIVERY_STATUS_MSGID_OFFSET, msgID);
htobe64buf (buf + DELIVERY_STATUS_TIMESTAMP_OFFSET, i2p::context.GetNetID ());
}
m->len += DELIVERY_STATUS_SIZE;
m->FillI2NPMessageHeader (eI2NPDeliveryStatus);
return m;
}
std::shared_ptr<I2NPMessage> CreateRouterInfoDatabaseLookupMsg (const uint8_t * key, const uint8_t * from,
uint32_t replyTunnelID, bool exploratory, std::set<i2p::data::IdentHash> * excludedPeers)
{
auto m = excludedPeers ? NewI2NPMessage () : NewI2NPShortMessage ();
uint8_t * buf = m->GetPayload ();
memcpy (buf, key, 32); // key
buf += 32;
memcpy (buf, from, 32); // from
buf += 32;
uint8_t flag = exploratory ? DATABASE_LOOKUP_TYPE_EXPLORATORY_LOOKUP : DATABASE_LOOKUP_TYPE_ROUTERINFO_LOOKUP;
if (replyTunnelID)
{
*buf = flag | DATABASE_LOOKUP_DELIVERY_FLAG; // set delivery flag
htobe32buf (buf+1, replyTunnelID);
buf += 5;
}
else
{
*buf = flag; // flag
buf++;
}
if (excludedPeers)
{
int cnt = excludedPeers->size ();
htobe16buf (buf, cnt);
buf += 2;
for (auto& it: *excludedPeers)
{
memcpy (buf, it, 32);
buf += 32;
}
}
else
{
// nothing to exclude
htobuf16 (buf, 0);
buf += 2;
}
m->len += (buf - m->GetPayload ());
m->FillI2NPMessageHeader (eI2NPDatabaseLookup);
return m;
}
std::shared_ptr<I2NPMessage> CreateLeaseSetDatabaseLookupMsg (const i2p::data::IdentHash& dest,
const std::set<i2p::data::IdentHash>& excludedFloodfills,
std::shared_ptr<const i2p::tunnel::InboundTunnel> replyTunnel, const uint8_t * replyKey, const uint8_t * replyTag)
{
int cnt = excludedFloodfills.size ();
auto m = cnt > 0 ? NewI2NPMessage () : NewI2NPShortMessage ();
uint8_t * buf = m->GetPayload ();
memcpy (buf, dest, 32); // key
buf += 32;
memcpy (buf, replyTunnel->GetNextIdentHash (), 32); // reply tunnel GW
buf += 32;
*buf = DATABASE_LOOKUP_DELIVERY_FLAG | DATABASE_LOOKUP_ENCRYPTION_FLAG | DATABASE_LOOKUP_TYPE_LEASESET_LOOKUP; // flags
buf ++;
htobe32buf (buf, replyTunnel->GetNextTunnelID ()); // reply tunnel ID
buf += 4;
// excluded
htobe16buf (buf, cnt);
buf += 2;
if (cnt > 0)
{
for (auto& it: excludedFloodfills)
{
memcpy (buf, it, 32);
buf += 32;
}
}
// encryption
memcpy (buf, replyKey, 32);
buf[32] = uint8_t( 1 ); // 1 tag
memcpy (buf + 33, replyTag, 32);
buf += 65;
m->len += (buf - m->GetPayload ());
m->FillI2NPMessageHeader (eI2NPDatabaseLookup);
return m;
}
std::shared_ptr<I2NPMessage> CreateDatabaseSearchReply (const i2p::data::IdentHash& ident,
std::vector<i2p::data::IdentHash> routers)
{
auto m = NewI2NPShortMessage ();
uint8_t * buf = m->GetPayload ();
size_t len = 0;
memcpy (buf, ident, 32);
len += 32;
buf[len] = routers.size ();
len++;
for (const auto& it: routers)
{
memcpy (buf + len, it, 32);
len += 32;
}
memcpy (buf + len, i2p::context.GetRouterInfo ().GetIdentHash (), 32);
len += 32;
m->len += len;
m->FillI2NPMessageHeader (eI2NPDatabaseSearchReply);
return m;
}
std::shared_ptr<I2NPMessage> CreateDatabaseStoreMsg (std::shared_ptr<const i2p::data::RouterInfo> router, uint32_t replyToken)
{
if (!router) // we send own RouterInfo
router = context.GetSharedRouterInfo ();
auto m = NewI2NPShortMessage ();
uint8_t * payload = m->GetPayload ();
memcpy (payload + DATABASE_STORE_KEY_OFFSET, router->GetIdentHash (), 32);
payload[DATABASE_STORE_TYPE_OFFSET] = 0; // RouterInfo
htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, replyToken);
uint8_t * buf = payload + DATABASE_STORE_HEADER_SIZE;
if (replyToken)
{
memset (buf, 0, 4); // zero tunnelID means direct reply
buf += 4;
memcpy (buf, router->GetIdentHash (), 32);
buf += 32;
}
uint8_t * sizePtr = buf;
buf += 2;
m->len += (buf - payload); // payload size
i2p::data::GzipDeflator deflator;
size_t size = deflator.Deflate (router->GetBuffer (), router->GetBufferLen (), buf, m->maxLen -m->len);
if (size)
{
htobe16buf (sizePtr, size); // size
m->len += size;
}
else
m = nullptr;
if (m)
m->FillI2NPMessageHeader (eI2NPDatabaseStore);
return m;
}
std::shared_ptr<I2NPMessage> CreateDatabaseStoreMsg (std::shared_ptr<const i2p::data::LeaseSet> leaseSet)
{
if (!leaseSet) return nullptr;
auto m = NewI2NPShortMessage ();
uint8_t * payload = m->GetPayload ();
memcpy (payload + DATABASE_STORE_KEY_OFFSET, leaseSet->GetIdentHash (), 32);
payload[DATABASE_STORE_TYPE_OFFSET] = 1; // LeaseSet
htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, 0);
size_t size = DATABASE_STORE_HEADER_SIZE;
memcpy (payload + size, leaseSet->GetBuffer (), leaseSet->GetBufferLen ());
size += leaseSet->GetBufferLen ();
m->len += size;
m->FillI2NPMessageHeader (eI2NPDatabaseStore);
return m;
}
std::shared_ptr<I2NPMessage> CreateDatabaseStoreMsg (std::shared_ptr<const i2p::data::LocalLeaseSet> leaseSet, uint32_t replyToken, std::shared_ptr<const i2p::tunnel::InboundTunnel> replyTunnel)
{
if (!leaseSet) return nullptr;
auto m = NewI2NPShortMessage ();
uint8_t * payload = m->GetPayload ();
memcpy (payload + DATABASE_STORE_KEY_OFFSET, leaseSet->GetIdentHash (), 32);
payload[DATABASE_STORE_TYPE_OFFSET] = 1; // LeaseSet
htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, replyToken);
size_t size = DATABASE_STORE_HEADER_SIZE;
if (replyToken && replyTunnel)
{
if (replyTunnel)
{
htobe32buf (payload + size, replyTunnel->GetNextTunnelID ());
size += 4; // reply tunnelID
memcpy (payload + size, replyTunnel->GetNextIdentHash (), 32);
size += 32; // reply tunnel gateway
}
else
htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, 0);
}
memcpy (payload + size, leaseSet->GetBuffer (), leaseSet->GetBufferLen ());
size += leaseSet->GetBufferLen ();
m->len += size;
m->FillI2NPMessageHeader (eI2NPDatabaseStore);
return m;
}
bool IsRouterInfoMsg (std::shared_ptr<I2NPMessage> msg)
{
if (!msg || msg->GetTypeID () != eI2NPDatabaseStore) return false;
return !msg->GetPayload ()[DATABASE_STORE_TYPE_OFFSET]; // 0- RouterInfo
}
static uint16_t g_MaxNumTransitTunnels = DEFAULT_MAX_NUM_TRANSIT_TUNNELS; // TODO:
void SetMaxNumTransitTunnels (uint16_t maxNumTransitTunnels)
{
if (maxNumTransitTunnels > 0 && maxNumTransitTunnels <= 10000 && g_MaxNumTransitTunnels != maxNumTransitTunnels)
{
LogPrint (eLogDebug, "I2NP: Max number of transit tunnels set to ", maxNumTransitTunnels);
g_MaxNumTransitTunnels = maxNumTransitTunnels;
}
}
bool HandleBuildRequestRecords (int num, uint8_t * records, uint8_t * clearText)
{
for (int i = 0; i < num; i++)
{
uint8_t * record = records + i*TUNNEL_BUILD_RECORD_SIZE;
if (!memcmp (record + BUILD_REQUEST_RECORD_TO_PEER_OFFSET, (const uint8_t *)i2p::context.GetRouterInfo ().GetIdentHash (), 16))
{
LogPrint (eLogDebug, "I2NP: Build request record ", i, " is ours");
i2p::crypto::ElGamalDecrypt (i2p::context.GetEncryptionPrivateKey (), record + BUILD_REQUEST_RECORD_ENCRYPTED_OFFSET, clearText);
// replace record to reply
if (i2p::context.AcceptsTunnels () &&
i2p::tunnel::tunnels.GetTransitTunnels ().size () <= g_MaxNumTransitTunnels &&
!i2p::transport::transports.IsBandwidthExceeded ())
{
auto transitTunnel = i2p::tunnel::CreateTransitTunnel (
bufbe32toh (clearText + BUILD_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET),
clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
bufbe32toh (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
clearText + BUILD_REQUEST_RECORD_LAYER_KEY_OFFSET,
clearText + BUILD_REQUEST_RECORD_IV_KEY_OFFSET,
clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] & 0x80,
clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET ] & 0x40);
i2p::tunnel::tunnels.AddTransitTunnel (transitTunnel);
record[BUILD_RESPONSE_RECORD_RET_OFFSET] = 0;
}
else
record[BUILD_RESPONSE_RECORD_RET_OFFSET] = 30; // always reject with bandwidth reason (30)
//TODO: fill filler
SHA256 (record + BUILD_RESPONSE_RECORD_PADDING_OFFSET, BUILD_RESPONSE_RECORD_PADDING_SIZE + 1, // + 1 byte of ret
record + BUILD_RESPONSE_RECORD_HASH_OFFSET);
// encrypt reply
i2p::crypto::CBCEncryption encryption;
for (int j = 0; j < num; j++)
{
encryption.SetKey (clearText + BUILD_REQUEST_RECORD_REPLY_KEY_OFFSET);
encryption.SetIV (clearText + BUILD_REQUEST_RECORD_REPLY_IV_OFFSET);
uint8_t * reply = records + j*TUNNEL_BUILD_RECORD_SIZE;
encryption.Encrypt(reply, TUNNEL_BUILD_RECORD_SIZE, reply);
}
return true;
}
}
return false;
}
void HandleVariableTunnelBuildMsg (uint32_t replyMsgID, uint8_t * buf, size_t len)
{
int num = buf[0];
LogPrint (eLogDebug, "I2NP: VariableTunnelBuild ", num, " records");
if (len < num*BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE + 1)
{
LogPrint (eLogError, "VaribleTunnelBuild message of ", num, " records is too short ", len);
return;
}
auto tunnel = i2p::tunnel::tunnels.GetPendingInboundTunnel (replyMsgID);
if (tunnel)
{
// endpoint of inbound tunnel
LogPrint (eLogDebug, "I2NP: VariableTunnelBuild reply for tunnel ", tunnel->GetTunnelID ());
if (tunnel->HandleTunnelBuildResponse (buf, len))
{
LogPrint (eLogInfo, "I2NP: Inbound tunnel ", tunnel->GetTunnelID (), " has been created");
tunnel->SetState (i2p::tunnel::eTunnelStateEstablished);
i2p::tunnel::tunnels.AddInboundTunnel (tunnel);
}
else
{
LogPrint (eLogInfo, "I2NP: Inbound tunnel ", tunnel->GetTunnelID (), " has been declined");
tunnel->SetState (i2p::tunnel::eTunnelStateBuildFailed);
}
}
else
{
uint8_t clearText[BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE];
if (HandleBuildRequestRecords (num, buf + 1, clearText))
{
if (clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] & 0x40) // we are endpoint of outboud tunnel
{
// so we send it to reply tunnel
transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
CreateTunnelGatewayMsg (bufbe32toh (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
eI2NPVariableTunnelBuildReply, buf, len,
bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
}
else
transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
CreateI2NPMessage (eI2NPVariableTunnelBuild, buf, len,
bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
}
}
}
void HandleTunnelBuildMsg (uint8_t * buf, size_t len)
{
if (len < NUM_TUNNEL_BUILD_RECORDS*BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE)
{
LogPrint (eLogError, "TunnelBuild message is too short ", len);
return;
}
uint8_t clearText[BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE];
if (HandleBuildRequestRecords (NUM_TUNNEL_BUILD_RECORDS, buf, clearText))
{
if (clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] & 0x40) // we are endpoint of outbound tunnel
{
// so we send it to reply tunnel
transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
CreateTunnelGatewayMsg (bufbe32toh (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
eI2NPTunnelBuildReply, buf, len,
bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
}
else
transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
CreateI2NPMessage (eI2NPTunnelBuild, buf, len,
bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
}
}
void HandleVariableTunnelBuildReplyMsg (uint32_t replyMsgID, uint8_t * buf, size_t len)
{
int num = buf[0];
LogPrint (eLogDebug, "I2NP: VariableTunnelBuildReplyMsg of ", num, " records replyMsgID=", replyMsgID);
if (len < num*BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE + 1)
{
LogPrint (eLogError, "VaribleTunnelBuildReply message of ", num, " records is too short ", len);
return;
}
auto tunnel = i2p::tunnel::tunnels.GetPendingOutboundTunnel (replyMsgID);
if (tunnel)
{
// reply for outbound tunnel
if (tunnel->HandleTunnelBuildResponse (buf, len))
{
LogPrint (eLogInfo, "I2NP: Outbound tunnel ", tunnel->GetTunnelID (), " has been created");
tunnel->SetState (i2p::tunnel::eTunnelStateEstablished);
i2p::tunnel::tunnels.AddOutboundTunnel (tunnel);
}
else
{
LogPrint (eLogInfo, "I2NP: Outbound tunnel ", tunnel->GetTunnelID (), " has been declined");
tunnel->SetState (i2p::tunnel::eTunnelStateBuildFailed);
}
}
else
LogPrint (eLogWarning, "I2NP: Pending tunnel for message ", replyMsgID, " not found");
}
std::shared_ptr<I2NPMessage> CreateTunnelDataMsg (const uint8_t * buf)
{
auto msg = NewI2NPTunnelMessage ();
msg->Concat (buf, i2p::tunnel::TUNNEL_DATA_MSG_SIZE);
msg->FillI2NPMessageHeader (eI2NPTunnelData);
return msg;
}
std::shared_ptr<I2NPMessage> CreateTunnelDataMsg (uint32_t tunnelID, const uint8_t * payload)
{
auto msg = NewI2NPTunnelMessage ();
htobe32buf (msg->GetPayload (), tunnelID);
msg->len += 4; // tunnelID
msg->Concat (payload, i2p::tunnel::TUNNEL_DATA_MSG_SIZE - 4);
msg->FillI2NPMessageHeader (eI2NPTunnelData);
return msg;
}
std::shared_ptr<I2NPMessage> CreateEmptyTunnelDataMsg ()
{
auto msg = NewI2NPTunnelMessage ();
msg->len += i2p::tunnel::TUNNEL_DATA_MSG_SIZE;
return msg;
}
std::shared_ptr<I2NPMessage> CreateTunnelGatewayMsg (uint32_t tunnelID, const uint8_t * buf, size_t len)
{
auto msg = NewI2NPMessage (len);
uint8_t * payload = msg->GetPayload ();
htobe32buf (payload + TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET, tunnelID);
htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len);
msg->len += TUNNEL_GATEWAY_HEADER_SIZE;
if (msg->Concat (buf, len) < len)
LogPrint (eLogError, "I2NP: tunnel gateway buffer overflow ", msg->maxLen);
msg->FillI2NPMessageHeader (eI2NPTunnelGateway);
return msg;
}
std::shared_ptr<I2NPMessage> CreateTunnelGatewayMsg (uint32_t tunnelID, std::shared_ptr<I2NPMessage> msg)
{
if (msg->offset >= I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE)
{
// message is capable to be used without copying
uint8_t * payload = msg->GetBuffer () - TUNNEL_GATEWAY_HEADER_SIZE;
htobe32buf (payload + TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET, tunnelID);
int len = msg->GetLength ();
htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len);
msg->offset -= (I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE);
msg->len = msg->offset + I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE +len;
msg->FillI2NPMessageHeader (eI2NPTunnelGateway);
return msg;
}
else
return CreateTunnelGatewayMsg (tunnelID, msg->GetBuffer (), msg->GetLength ());
}
std::shared_ptr<I2NPMessage> CreateTunnelGatewayMsg (uint32_t tunnelID, I2NPMessageType msgType,
const uint8_t * buf, size_t len, uint32_t replyMsgID)
{
auto msg = NewI2NPMessage (len);
size_t gatewayMsgOffset = I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE;
msg->offset += gatewayMsgOffset;
msg->len += gatewayMsgOffset;
if (msg->Concat (buf, len) < len)
LogPrint (eLogError, "I2NP: tunnel gateway buffer overflow ", msg->maxLen);
msg->FillI2NPMessageHeader (msgType, replyMsgID); // create content message
len = msg->GetLength ();
msg->offset -= gatewayMsgOffset;
uint8_t * payload = msg->GetPayload ();
htobe32buf (payload + TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET, tunnelID);
htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len);
msg->FillI2NPMessageHeader (eI2NPTunnelGateway); // gateway message
return msg;
}
size_t GetI2NPMessageLength (const uint8_t * msg)
{
return bufbe16toh (msg + I2NP_HEADER_SIZE_OFFSET) + I2NP_HEADER_SIZE;
}
void HandleI2NPMessage (uint8_t * msg, size_t len)
{
uint8_t typeID = msg[I2NP_HEADER_TYPEID_OFFSET];
uint32_t msgID = bufbe32toh (msg + I2NP_HEADER_MSGID_OFFSET);
LogPrint (eLogDebug, "I2NP: msg received len=", len,", type=", (int)typeID, ", msgID=", (unsigned int)msgID);
uint8_t * buf = msg + I2NP_HEADER_SIZE;
int size = bufbe16toh (msg + I2NP_HEADER_SIZE_OFFSET);
switch (typeID)
{
case eI2NPVariableTunnelBuild:
HandleVariableTunnelBuildMsg (msgID, buf, size);
break;
case eI2NPVariableTunnelBuildReply:
HandleVariableTunnelBuildReplyMsg (msgID, buf, size);
break;
case eI2NPTunnelBuild:
HandleTunnelBuildMsg (buf, size);
break;
case eI2NPTunnelBuildReply:
// TODO:
break;
default:
LogPrint (eLogWarning, "I2NP: Unexpected message ", (int)typeID);
}
}
void HandleI2NPMessage (std::shared_ptr<I2NPMessage> msg)
{
if (msg)
{
uint8_t typeID = msg->GetTypeID ();
LogPrint (eLogDebug, "I2NP: Handling message with type ", (int)typeID);
switch (typeID)
{
case eI2NPTunnelData:
i2p::tunnel::tunnels.PostTunnelData (msg);
break;
case eI2NPTunnelGateway:
i2p::tunnel::tunnels.PostTunnelData (msg);
break;
case eI2NPGarlic:
{
if (msg->from)
{
if (msg->from->GetTunnelPool ())
msg->from->GetTunnelPool ()->ProcessGarlicMessage (msg);
else
LogPrint (eLogInfo, "I2NP: Local destination for garlic doesn't exist anymore");
}
else
i2p::context.ProcessGarlicMessage (msg);
break;
}
case eI2NPDatabaseStore:
case eI2NPDatabaseSearchReply:
case eI2NPDatabaseLookup:
// forward to netDb
i2p::data::netdb.PostI2NPMsg (msg);
break;
case eI2NPDeliveryStatus:
{
if (msg->from && msg->from->GetTunnelPool ())
msg->from->GetTunnelPool ()->ProcessDeliveryStatus (msg);
else
i2p::context.ProcessDeliveryStatusMessage (msg);
break;
}
case eI2NPVariableTunnelBuild:
case eI2NPVariableTunnelBuildReply:
case eI2NPTunnelBuild:
case eI2NPTunnelBuildReply:
// forward to tunnel thread
i2p::tunnel::tunnels.PostTunnelData (msg);
break;
default:
HandleI2NPMessage (msg->GetBuffer (), msg->GetLength ());
}
}
}
I2NPMessagesHandler::~I2NPMessagesHandler ()
{
Flush ();
}
void I2NPMessagesHandler::PutNextMessage (std::shared_ptr<I2NPMessage> msg)
{
if (msg)
{
switch (msg->GetTypeID ())
{
case eI2NPTunnelData:
m_TunnelMsgs.push_back (msg);
break;
case eI2NPTunnelGateway:
m_TunnelGatewayMsgs.push_back (msg);
break;
default:
HandleI2NPMessage (msg);
}
}
}
void I2NPMessagesHandler::Flush ()
{
if (!m_TunnelMsgs.empty ())
{
i2p::tunnel::tunnels.PostTunnelData (m_TunnelMsgs);
m_TunnelMsgs.clear ();
}
if (!m_TunnelGatewayMsgs.empty ())
{
i2p::tunnel::tunnels.PostTunnelData (m_TunnelGatewayMsgs);
m_TunnelGatewayMsgs.clear ();
}
}
}

View File

@ -1,216 +0,0 @@
#include "Destination.h"
#include "Identity.h"
#include "ClientContext.h"
#include "I2PService.h"
namespace i2p
{
namespace client
{
static const i2p::data::SigningKeyType I2P_SERVICE_DEFAULT_KEY_TYPE = i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256;
I2PService::I2PService (std::shared_ptr<ClientDestination> localDestination):
m_LocalDestination (localDestination ? localDestination :
i2p::client::context.CreateNewLocalDestination (false, I2P_SERVICE_DEFAULT_KEY_TYPE))
{
}
I2PService::I2PService (i2p::data::SigningKeyType kt):
m_LocalDestination (i2p::client::context.CreateNewLocalDestination (false, kt))
{
}
void I2PService::CreateStream (StreamRequestComplete streamRequestComplete, const std::string& dest, int port) {
assert(streamRequestComplete);
i2p::data::IdentHash identHash;
if (i2p::client::context.GetAddressBook ().GetIdentHash (dest, identHash))
m_LocalDestination->CreateStream (streamRequestComplete, identHash, port);
else
{
LogPrint (eLogWarning, "I2PService: Remote destination not found: ", dest);
streamRequestComplete (nullptr);
}
}
TCPIPPipe::TCPIPPipe(I2PService * owner, std::shared_ptr<boost::asio::ip::tcp::socket> upstream, std::shared_ptr<boost::asio::ip::tcp::socket> downstream) : I2PServiceHandler(owner), m_up(upstream), m_down(downstream)
{
boost::asio::socket_base::receive_buffer_size option(TCP_IP_PIPE_BUFFER_SIZE);
upstream->set_option(option);
downstream->set_option(option);
}
TCPIPPipe::~TCPIPPipe()
{
Terminate();
}
void TCPIPPipe::Start()
{
AsyncReceiveUpstream();
AsyncReceiveDownstream();
}
void TCPIPPipe::Terminate()
{
if(Kill()) return;
if (m_up) {
if (m_up->is_open()) {
m_up->close();
}
m_up = nullptr;
}
if (m_down) {
if (m_down->is_open()) {
m_down->close();
}
m_down = nullptr;
}
Done(shared_from_this());
}
void TCPIPPipe::AsyncReceiveUpstream()
{
if (m_up) {
m_up->async_read_some(boost::asio::buffer(m_upstream_to_down_buf, TCP_IP_PIPE_BUFFER_SIZE),
std::bind(&TCPIPPipe::HandleUpstreamReceived, shared_from_this(),
std::placeholders::_1, std::placeholders::_2));
} else {
LogPrint(eLogError, "TCPIPPipe: upstream receive: no socket");
}
}
void TCPIPPipe::AsyncReceiveDownstream()
{
if (m_down) {
m_down->async_read_some(boost::asio::buffer(m_downstream_to_up_buf, TCP_IP_PIPE_BUFFER_SIZE),
std::bind(&TCPIPPipe::HandleDownstreamReceived, shared_from_this(),
std::placeholders::_1, std::placeholders::_2));
} else {
LogPrint(eLogError, "TCPIPPipe: downstream receive: no socket");
}
}
void TCPIPPipe::UpstreamWrite(size_t len)
{
if (m_up) {
LogPrint(eLogDebug, "TCPIPPipe: upstream: ", (int) len, " bytes written");
boost::asio::async_write(*m_up, boost::asio::buffer(m_upstream_buf, len),
boost::asio::transfer_all(),
std::bind(&TCPIPPipe::HandleUpstreamWrite,
shared_from_this(),
std::placeholders::_1)
);
} else {
LogPrint(eLogError, "TCPIPPipe: upstream write: no socket");
}
}
void TCPIPPipe::DownstreamWrite(size_t len)
{
if (m_down) {
LogPrint(eLogDebug, "TCPIPPipe: downstream: ", (int) len, " bytes written");
boost::asio::async_write(*m_down, boost::asio::buffer(m_downstream_buf, len),
boost::asio::transfer_all(),
std::bind(&TCPIPPipe::HandleDownstreamWrite,
shared_from_this(),
std::placeholders::_1)
);
} else {
LogPrint(eLogError, "TCPIPPipe: downstream write: no socket");
}
}
void TCPIPPipe::HandleDownstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered)
{
LogPrint(eLogDebug, "TCPIPPipe: downstream: ", (int) bytes_transfered, " bytes received");
if (ecode) {
LogPrint(eLogError, "TCPIPPipe: downstream read error:" , ecode.message());
if (ecode != boost::asio::error::operation_aborted)
Terminate();
} else {
if (bytes_transfered > 0 ) {
memcpy(m_upstream_buf, m_downstream_to_up_buf, bytes_transfered);
}
UpstreamWrite(bytes_transfered);
}
}
void TCPIPPipe::HandleDownstreamWrite(const boost::system::error_code & ecode) {
if (ecode) {
LogPrint(eLogError, "TCPIPPipe: downstream write error:" , ecode.message());
if (ecode != boost::asio::error::operation_aborted)
Terminate();
} else {
AsyncReceiveUpstream();
}
}
void TCPIPPipe::HandleUpstreamWrite(const boost::system::error_code & ecode) {
if (ecode) {
LogPrint(eLogError, "TCPIPPipe: upstream write error:" , ecode.message());
if (ecode != boost::asio::error::operation_aborted)
Terminate();
} else {
AsyncReceiveDownstream();
}
}
void TCPIPPipe::HandleUpstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered)
{
LogPrint(eLogDebug, "TCPIPPipe: upstream ", (int)bytes_transfered, " bytes received");
if (ecode) {
LogPrint(eLogError, "TCPIPPipe: upstream read error:" , ecode.message());
if (ecode != boost::asio::error::operation_aborted)
Terminate();
} else {
if (bytes_transfered > 0 ) {
memcpy(m_downstream_buf, m_upstream_to_down_buf, bytes_transfered);
}
DownstreamWrite(bytes_transfered);
}
}
void TCPIPAcceptor::Start ()
{
m_Acceptor.listen ();
Accept ();
}
void TCPIPAcceptor::Stop ()
{
m_Acceptor.close();
m_Timer.cancel ();
ClearHandlers();
}
void TCPIPAcceptor::Accept ()
{
auto newSocket = std::make_shared<boost::asio::ip::tcp::socket> (GetService ());
m_Acceptor.async_accept (*newSocket, std::bind (&TCPIPAcceptor::HandleAccept, this,
std::placeholders::_1, newSocket));
}
void TCPIPAcceptor::HandleAccept (const boost::system::error_code& ecode, std::shared_ptr<boost::asio::ip::tcp::socket> socket)
{
if (!ecode)
{
LogPrint(eLogDebug, "I2PService: ", GetName(), " accepted");
auto handler = CreateHandler(socket);
if (handler)
{
AddHandler(handler);
handler->Handle();
}
else
socket->close();
Accept();
}
else
{
if (ecode != boost::asio::error::operation_aborted)
LogPrint (eLogError, "I2PService: ", GetName(), " closing socket on accept because: ", ecode.message ());
}
}
}
}

View File

@ -1,876 +0,0 @@
#include <cassert>
#include "Base.h"
#include "Log.h"
#include "Destination.h"
#include "ClientContext.h"
#include "I2PTunnel.h"
namespace i2p
{
namespace client
{
/** set standard socket options */
static void I2PTunnelSetSocketOptions(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
{
if (socket && socket->is_open())
{
boost::asio::socket_base::receive_buffer_size option(I2P_TUNNEL_CONNECTION_BUFFER_SIZE);
socket->set_option(option);
}
}
I2PTunnelConnection::I2PTunnelConnection (I2PService * owner, std::shared_ptr<boost::asio::ip::tcp::socket> socket,
std::shared_ptr<const i2p::data::LeaseSet> leaseSet, int port):
I2PServiceHandler(owner), m_Socket (socket), m_RemoteEndpoint (socket->remote_endpoint ()),
m_IsQuiet (true)
{
m_Stream = GetOwner()->GetLocalDestination ()->CreateStream (leaseSet, port);
}
I2PTunnelConnection::I2PTunnelConnection (I2PService * owner,
std::shared_ptr<boost::asio::ip::tcp::socket> socket, std::shared_ptr<i2p::stream::Stream> stream):
I2PServiceHandler(owner), m_Socket (socket), m_Stream (stream),
m_RemoteEndpoint (socket->remote_endpoint ()), m_IsQuiet (true)
{
}
I2PTunnelConnection::I2PTunnelConnection (I2PService * owner, std::shared_ptr<i2p::stream::Stream> stream,
std::shared_ptr<boost::asio::ip::tcp::socket> socket, const boost::asio::ip::tcp::endpoint& target, bool quiet):
I2PServiceHandler(owner), m_Socket (socket), m_Stream (stream),
m_RemoteEndpoint (target), m_IsQuiet (quiet)
{
}
I2PTunnelConnection::~I2PTunnelConnection ()
{
}
void I2PTunnelConnection::I2PConnect (const uint8_t * msg, size_t len)
{
if (m_Stream)
{
if (msg)
m_Stream->Send (msg, len); // connect and send
else
m_Stream->Send (m_Buffer, 0); // connect
}
StreamReceive ();
Receive ();
}
static boost::asio::ip::address GetLoopbackAddressFor(const i2p::data::IdentHash & addr)
{
boost::asio::ip::address_v4::bytes_type bytes;
const uint8_t * ident = addr;
bytes[0] = 127;
memcpy (bytes.data ()+1, ident, 3);
boost::asio::ip::address ourIP = boost::asio::ip::address_v4 (bytes);
return ourIP;
}
static void MapToLoopback(const std::shared_ptr<boost::asio::ip::tcp::socket> & sock, const i2p::data::IdentHash & addr)
{
// bind to 127.x.x.x address
// where x.x.x are first three bytes from ident
auto ourIP = GetLoopbackAddressFor(addr);
sock->bind (boost::asio::ip::tcp::endpoint (ourIP, 0));
}
void I2PTunnelConnection::Connect (bool isUniqueLocal)
{
I2PTunnelSetSocketOptions(m_Socket);
if (m_Socket)
{
#ifdef __linux__
if (isUniqueLocal && m_RemoteEndpoint.address ().is_v4 () &&
m_RemoteEndpoint.address ().to_v4 ().to_bytes ()[0] == 127)
{
m_Socket->open (boost::asio::ip::tcp::v4 ());
auto ident = m_Stream->GetRemoteIdentity()->GetIdentHash();
MapToLoopback(m_Socket, ident);
}
#endif
m_Socket->async_connect (m_RemoteEndpoint, std::bind (&I2PTunnelConnection::HandleConnect,
shared_from_this (), std::placeholders::_1));
}
}
void I2PTunnelConnection::Terminate ()
{
if (Kill()) return;
if (m_Stream)
{
m_Stream->Close ();
m_Stream.reset ();
}
boost::system::error_code ec;
m_Socket->shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec); // avoid RST
m_Socket->close ();
Done(shared_from_this ());
}
void I2PTunnelConnection::Receive ()
{
m_Socket->async_read_some (boost::asio::buffer(m_Buffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE),
std::bind(&I2PTunnelConnection::HandleReceived, shared_from_this (),
std::placeholders::_1, std::placeholders::_2));
}
void I2PTunnelConnection::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
LogPrint (eLogError, "I2PTunnel: read error: ", ecode.message ());
Terminate ();
}
}
else
{
if (m_Stream)
{
auto s = shared_from_this ();
m_Stream->AsyncSend (m_Buffer, bytes_transferred,
[s](const boost::system::error_code& ecode)
{
if (!ecode)
s->Receive ();
else
s->Terminate ();
});
}
}
}
void I2PTunnelConnection::HandleWrite (const boost::system::error_code& ecode)
{
if (ecode)
{
LogPrint (eLogError, "I2PTunnel: write error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted)
Terminate ();
}
else
StreamReceive ();
}
void I2PTunnelConnection::StreamReceive ()
{
if (m_Stream)
{
if (m_Stream->GetStatus () == i2p::stream::eStreamStatusNew ||
m_Stream->GetStatus () == i2p::stream::eStreamStatusOpen) // regular
{
m_Stream->AsyncReceive (boost::asio::buffer (m_StreamBuffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE),
std::bind (&I2PTunnelConnection::HandleStreamReceive, shared_from_this (),
std::placeholders::_1, std::placeholders::_2),
I2P_TUNNEL_CONNECTION_MAX_IDLE);
}
else // closed by peer
{
// get remaning data
auto len = m_Stream->ReadSome (m_StreamBuffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE);
if (len > 0) // still some data
Write (m_StreamBuffer, len);
else // no more data
Terminate ();
}
}
}
void I2PTunnelConnection::HandleStreamReceive (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
LogPrint (eLogError, "I2PTunnel: stream read error: ", ecode.message ());
if (bytes_transferred > 0)
Write (m_StreamBuffer, bytes_transferred); // postpone termination
else if (ecode == boost::asio::error::timed_out && m_Stream && m_Stream->IsOpen ())
StreamReceive ();
else
Terminate ();
}
else
Terminate ();
}
else
Write (m_StreamBuffer, bytes_transferred);
}
void I2PTunnelConnection::Write (const uint8_t * buf, size_t len)
{
boost::asio::async_write (*m_Socket, boost::asio::buffer (buf, len), boost::asio::transfer_all (),
std::bind (&I2PTunnelConnection::HandleWrite, shared_from_this (), std::placeholders::_1));
}
void I2PTunnelConnection::HandleConnect (const boost::system::error_code& ecode)
{
if (ecode)
{
LogPrint (eLogError, "I2PTunnel: connect error: ", ecode.message ());
Terminate ();
}
else
{
LogPrint (eLogDebug, "I2PTunnel: connected");
if (m_IsQuiet)
StreamReceive ();
else
{
// send destination first like received from I2P
std::string dest = m_Stream->GetRemoteIdentity ()->ToBase64 ();
dest += "\n";
if(sizeof(m_StreamBuffer) >= dest.size()) {
memcpy (m_StreamBuffer, dest.c_str (), dest.size ());
}
HandleStreamReceive (boost::system::error_code (), dest.size ());
}
Receive ();
}
}
void I2PClientTunnelConnectionHTTP::Write (const uint8_t * buf, size_t len)
{
if (m_HeaderSent)
I2PTunnelConnection::Write (buf, len);
else
{
m_InHeader.clear ();
m_InHeader.write ((const char *)buf, len);
std::string line;
bool endOfHeader = false;
while (!endOfHeader)
{
std::getline(m_InHeader, line);
if (!m_InHeader.fail ())
{
if (line == "\r") endOfHeader = true;
else
{
if (!m_ConnectionSent && !line.compare(0, 10, "Connection"))
{
m_OutHeader << "Connection: close\r\n";
m_ConnectionSent = true;
}
else if (!m_ProxyConnectionSent && !line.compare(0, 16, "Proxy-Connection"))
{
m_OutHeader << "Proxy-Connection: close\r\n";
m_ProxyConnectionSent = true;
}
else
m_OutHeader << line << "\n";
}
}
else
break;
}
if (endOfHeader)
{
if (!m_ConnectionSent) m_OutHeader << "Connection: close\r\n";
if (!m_ProxyConnectionSent) m_OutHeader << "Proxy-Connection: close\r\n";
m_OutHeader << "\r\n"; // end of header
m_OutHeader << m_InHeader.str ().substr (m_InHeader.tellg ()); // data right after header
m_InHeader.str ("");
m_HeaderSent = true;
I2PTunnelConnection::Write ((uint8_t *)m_OutHeader.str ().c_str (), m_OutHeader.str ().length ());
}
}
}
I2PServerTunnelConnectionHTTP::I2PServerTunnelConnectionHTTP (I2PService * owner, std::shared_ptr<i2p::stream::Stream> stream,
std::shared_ptr<boost::asio::ip::tcp::socket> socket,
const boost::asio::ip::tcp::endpoint& target, const std::string& host):
I2PTunnelConnection (owner, stream, socket, target), m_Host (host), m_HeaderSent (false), m_From (stream->GetRemoteIdentity ())
{
}
void I2PServerTunnelConnectionHTTP::Write (const uint8_t * buf, size_t len)
{
if (m_HeaderSent)
I2PTunnelConnection::Write (buf, len);
else
{
m_InHeader.clear ();
m_InHeader.write ((const char *)buf, len);
std::string line;
bool endOfHeader = false;
while (!endOfHeader)
{
std::getline(m_InHeader, line);
if (!m_InHeader.fail ())
{
if (line == "\r") endOfHeader = true;
else
{
if (m_Host.length () > 0 && line.find ("Host:") != std::string::npos)
m_OutHeader << "Host: " << m_Host << "\r\n"; // override host
else
m_OutHeader << line << "\n";
}
}
else
break;
}
// add X-I2P fields
if (m_From)
{
m_OutHeader << X_I2P_DEST_B32 << ": " << context.GetAddressBook ().ToAddress(m_From->GetIdentHash ()) << "\r\n";
m_OutHeader << X_I2P_DEST_HASH << ": " << m_From->GetIdentHash ().ToBase64 () << "\r\n";
m_OutHeader << X_I2P_DEST_B64 << ": " << m_From->ToBase64 () << "\r\n";
}
if (endOfHeader)
{
m_OutHeader << "\r\n"; // end of header
m_OutHeader << m_InHeader.str ().substr (m_InHeader.tellg ()); // data right after header
m_InHeader.str ("");
m_HeaderSent = true;
I2PTunnelConnection::Write ((uint8_t *)m_OutHeader.str ().c_str (), m_OutHeader.str ().length ());
}
}
}
I2PTunnelConnectionIRC::I2PTunnelConnectionIRC (I2PService * owner, std::shared_ptr<i2p::stream::Stream> stream,
std::shared_ptr<boost::asio::ip::tcp::socket> socket,
const boost::asio::ip::tcp::endpoint& target, const std::string& webircpass):
I2PTunnelConnection (owner, stream, socket, target), m_From (stream->GetRemoteIdentity ()),
m_NeedsWebIrc (webircpass.length() ? true : false), m_WebircPass (webircpass)
{
}
void I2PTunnelConnectionIRC::Write (const uint8_t * buf, size_t len)
{
m_OutPacket.str ("");
if (m_NeedsWebIrc)
{
m_NeedsWebIrc = false;
m_OutPacket << "WEBIRC " << m_WebircPass << " cgiirc " << context.GetAddressBook ().ToAddress (m_From->GetIdentHash ()) << " " << GetSocket ()->local_endpoint ().address () << std::endl;
}
m_InPacket.clear ();
m_InPacket.write ((const char *)buf, len);
while (!m_InPacket.eof () && !m_InPacket.fail ())
{
std::string line;
std::getline (m_InPacket, line);
if (line.length () == 0 && m_InPacket.eof ())
m_InPacket.str ("");
auto pos = line.find ("USER");
if (!pos) // start of line
{
pos = line.find (" ");
pos++;
pos = line.find (" ", pos);
pos++;
auto nextpos = line.find (" ", pos);
m_OutPacket << line.substr (0, pos);
m_OutPacket << context.GetAddressBook ().ToAddress (m_From->GetIdentHash ());
m_OutPacket << line.substr (nextpos) << '\n';
}
else
m_OutPacket << line << '\n';
}
I2PTunnelConnection::Write ((uint8_t *)m_OutPacket.str ().c_str (), m_OutPacket.str ().length ());
}
/* This handler tries to stablish a connection with the desired server and dies if it fails to do so */
class I2PClientTunnelHandler: public I2PServiceHandler, public std::enable_shared_from_this<I2PClientTunnelHandler>
{
public:
I2PClientTunnelHandler (I2PClientTunnel * parent, i2p::data::IdentHash destination,
int destinationPort, std::shared_ptr<boost::asio::ip::tcp::socket> socket):
I2PServiceHandler(parent), m_DestinationIdentHash(destination),
m_DestinationPort (destinationPort), m_Socket(socket) {};
void Handle();
void Terminate();
private:
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
i2p::data::IdentHash m_DestinationIdentHash;
int m_DestinationPort;
std::shared_ptr<boost::asio::ip::tcp::socket> m_Socket;
};
void I2PClientTunnelHandler::Handle()
{
GetOwner()->GetLocalDestination ()->CreateStream (
std::bind (&I2PClientTunnelHandler::HandleStreamRequestComplete, shared_from_this(), std::placeholders::_1),
m_DestinationIdentHash, m_DestinationPort);
}
void I2PClientTunnelHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
{
if (stream)
{
if (Kill()) return;
LogPrint (eLogDebug, "I2PTunnel: new connection");
auto connection = std::make_shared<I2PTunnelConnection>(GetOwner(), m_Socket, stream);
GetOwner()->AddHandler (connection);
connection->I2PConnect ();
Done(shared_from_this());
}
else
{
LogPrint (eLogError, "I2PTunnel: Client Tunnel Issue when creating the stream, check the previous warnings for more info.");
Terminate();
}
}
void I2PClientTunnelHandler::Terminate()
{
if (Kill()) return;
if (m_Socket)
{
m_Socket->close();
m_Socket = nullptr;
}
Done(shared_from_this());
}
I2PClientTunnel::I2PClientTunnel (const std::string& name, const std::string& destination,
const std::string& address, int port, std::shared_ptr<ClientDestination> localDestination, int destinationPort):
TCPIPAcceptor (address, port, localDestination), m_Name (name), m_Destination (destination),
m_DestinationIdentHash (nullptr), m_DestinationPort (destinationPort)
{
}
void I2PClientTunnel::Start ()
{
TCPIPAcceptor::Start ();
GetIdentHash();
}
void I2PClientTunnel::Stop ()
{
TCPIPAcceptor::Stop();
auto *originalIdentHash = m_DestinationIdentHash;
m_DestinationIdentHash = nullptr;
delete originalIdentHash;
}
/* HACK: maybe we should create a caching IdentHash provider in AddressBook */
const i2p::data::IdentHash * I2PClientTunnel::GetIdentHash ()
{
if (!m_DestinationIdentHash)
{
i2p::data::IdentHash identHash;
if (i2p::client::context.GetAddressBook ().GetIdentHash (m_Destination, identHash))
m_DestinationIdentHash = new i2p::data::IdentHash (identHash);
else
LogPrint (eLogWarning, "I2PTunnel: Remote destination ", m_Destination, " not found");
}
return m_DestinationIdentHash;
}
std::shared_ptr<I2PServiceHandler> I2PClientTunnel::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
{
const i2p::data::IdentHash *identHash = GetIdentHash();
if (identHash)
return std::make_shared<I2PClientTunnelHandler>(this, *identHash, m_DestinationPort, socket);
else
return nullptr;
}
I2PServerTunnel::I2PServerTunnel (const std::string& name, const std::string& address,
int port, std::shared_ptr<ClientDestination> localDestination, int inport, bool gzip):
I2PService (localDestination), m_IsUniqueLocal(true), m_Name (name), m_Address (address), m_Port (port), m_IsAccessList (false)
{
m_PortDestination = localDestination->CreateStreamingDestination (inport > 0 ? inport : port, gzip);
}
void I2PServerTunnel::Start ()
{
m_Endpoint.port (m_Port);
boost::system::error_code ec;
auto addr = boost::asio::ip::address::from_string (m_Address, ec);
if (!ec)
{
m_Endpoint.address (addr);
Accept ();
}
else
{
auto resolver = std::make_shared<boost::asio::ip::tcp::resolver>(GetService ());
resolver->async_resolve (boost::asio::ip::tcp::resolver::query (m_Address, ""),
std::bind (&I2PServerTunnel::HandleResolve, this,
std::placeholders::_1, std::placeholders::_2, resolver));
}
}
void I2PServerTunnel::Stop ()
{
ClearHandlers ();
}
void I2PServerTunnel::HandleResolve (const boost::system::error_code& ecode, boost::asio::ip::tcp::resolver::iterator it,
std::shared_ptr<boost::asio::ip::tcp::resolver> resolver)
{
if (!ecode)
{
auto addr = (*it).endpoint ().address ();
LogPrint (eLogInfo, "I2PTunnel: server tunnel ", (*it).host_name (), " has been resolved to ", addr);
m_Endpoint.address (addr);
Accept ();
}
else
LogPrint (eLogError, "I2PTunnel: Unable to resolve server tunnel address: ", ecode.message ());
}
void I2PServerTunnel::SetAccessList (const std::set<i2p::data::IdentHash>& accessList)
{
m_AccessList = accessList;
m_IsAccessList = true;
}
void I2PServerTunnel::Accept ()
{
if (m_PortDestination)
m_PortDestination->SetAcceptor (std::bind (&I2PServerTunnel::HandleAccept, this, std::placeholders::_1));
auto localDestination = GetLocalDestination ();
if (localDestination)
{
if (!localDestination->IsAcceptingStreams ()) // set it as default if not set yet
localDestination->AcceptStreams (std::bind (&I2PServerTunnel::HandleAccept, this, std::placeholders::_1));
}
else
LogPrint (eLogError, "I2PTunnel: Local destination not set for server tunnel");
}
void I2PServerTunnel::HandleAccept (std::shared_ptr<i2p::stream::Stream> stream)
{
if (stream)
{
if (m_IsAccessList)
{
if (!m_AccessList.count (stream->GetRemoteIdentity ()->GetIdentHash ()))
{
LogPrint (eLogWarning, "I2PTunnel: Address ", stream->GetRemoteIdentity ()->GetIdentHash ().ToBase32 (), " is not in white list. Incoming connection dropped");
stream->Close ();
return;
}
}
// new connection
auto conn = CreateI2PConnection (stream);
AddHandler (conn);
conn->Connect (m_IsUniqueLocal);
}
}
std::shared_ptr<I2PTunnelConnection> I2PServerTunnel::CreateI2PConnection (std::shared_ptr<i2p::stream::Stream> stream)
{
return std::make_shared<I2PTunnelConnection> (this, stream, std::make_shared<boost::asio::ip::tcp::socket> (GetService ()), GetEndpoint ());
}
I2PServerTunnelHTTP::I2PServerTunnelHTTP (const std::string& name, const std::string& address,
int port, std::shared_ptr<ClientDestination> localDestination,
const std::string& host, int inport, bool gzip):
I2PServerTunnel (name, address, port, localDestination, inport, gzip),
m_Host (host)
{
}
std::shared_ptr<I2PTunnelConnection> I2PServerTunnelHTTP::CreateI2PConnection (std::shared_ptr<i2p::stream::Stream> stream)
{
return std::make_shared<I2PServerTunnelConnectionHTTP> (this, stream,
std::make_shared<boost::asio::ip::tcp::socket> (GetService ()), GetEndpoint (), m_Host);
}
I2PServerTunnelIRC::I2PServerTunnelIRC (const std::string& name, const std::string& address,
int port, std::shared_ptr<ClientDestination> localDestination,
const std::string& webircpass, int inport, bool gzip):
I2PServerTunnel (name, address, port, localDestination, inport, gzip),
m_WebircPass (webircpass)
{
}
std::shared_ptr<I2PTunnelConnection> I2PServerTunnelIRC::CreateI2PConnection (std::shared_ptr<i2p::stream::Stream> stream)
{
return std::make_shared<I2PTunnelConnectionIRC> (this, stream, std::make_shared<boost::asio::ip::tcp::socket> (GetService ()), GetEndpoint (), this->m_WebircPass);
}
void I2PUDPServerTunnel::HandleRecvFromI2P(const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
{
std::lock_guard<std::mutex> lock(m_SessionsMutex);
auto session = ObtainUDPSession(from, toPort, fromPort);
session->IPSocket.send_to(boost::asio::buffer(buf, len), m_RemoteEndpoint);
session->LastActivity = i2p::util::GetMillisecondsSinceEpoch();
}
void I2PUDPServerTunnel::ExpireStale(const uint64_t delta) {
std::lock_guard<std::mutex> lock(m_SessionsMutex);
uint64_t now = i2p::util::GetMillisecondsSinceEpoch();
auto itr = m_Sessions.begin();
while(itr != m_Sessions.end()) {
if(now - (*itr)->LastActivity >= delta )
itr = m_Sessions.erase(itr);
else
++itr;
}
}
void I2PUDPClientTunnel::ExpireStale(const uint64_t delta) {
std::lock_guard<std::mutex> lock(m_SessionsMutex);
uint64_t now = i2p::util::GetMillisecondsSinceEpoch();
std::vector<uint16_t> removePorts;
for (const auto & s : m_Sessions) {
if (now - s.second.second >= delta)
removePorts.push_back(s.first);
}
for(auto port : removePorts) {
m_Sessions.erase(port);
}
}
UDPSessionPtr I2PUDPServerTunnel::ObtainUDPSession(const i2p::data::IdentityEx& from, uint16_t localPort, uint16_t remotePort)
{
auto ih = from.GetIdentHash();
for (auto & s : m_Sessions )
{
if ( s->Identity == ih)
{
/** found existing session */
LogPrint(eLogDebug, "UDPServer: found session ", s->IPSocket.local_endpoint(), " ", ih.ToBase32());
return s;
}
}
boost::asio::ip::address addr;
/** create new udp session */
if(m_IsUniqueLocal && m_LocalAddress.is_loopback())
{
auto ident = from.GetIdentHash();
addr = GetLoopbackAddressFor(ident);
}
else
addr = m_LocalAddress;
boost::asio::ip::udp::endpoint ep(addr, 0);
m_Sessions.push_back(std::make_shared<UDPSession>(ep, m_LocalDest, m_RemoteEndpoint, &ih, localPort, remotePort));
auto & back = m_Sessions.back();
return back;
}
UDPSession::UDPSession(boost::asio::ip::udp::endpoint localEndpoint,
const std::shared_ptr<i2p::client::ClientDestination> & localDestination,
boost::asio::ip::udp::endpoint endpoint, const i2p::data::IdentHash * to,
uint16_t ourPort, uint16_t theirPort) :
m_Destination(localDestination->GetDatagramDestination()),
IPSocket(localDestination->GetService(), localEndpoint),
SendEndpoint(endpoint),
LastActivity(i2p::util::GetMillisecondsSinceEpoch()),
LocalPort(ourPort),
RemotePort(theirPort)
{
memcpy(Identity, to->data(), 32);
Receive();
}
void UDPSession::Receive() {
LogPrint(eLogDebug, "UDPSession: Receive");
IPSocket.async_receive_from(boost::asio::buffer(m_Buffer, I2P_UDP_MAX_MTU),
FromEndpoint, std::bind(&UDPSession::HandleReceived, this, std::placeholders::_1, std::placeholders::_2));
}
void UDPSession::HandleReceived(const boost::system::error_code & ecode, std::size_t len)
{
if(!ecode)
{
LogPrint(eLogDebug, "UDPSession: forward ", len, "B from ", FromEndpoint);
LastActivity = i2p::util::GetMillisecondsSinceEpoch();
m_Destination->SendDatagramTo(m_Buffer, len, Identity, LocalPort, RemotePort);
Receive();
} else {
LogPrint(eLogError, "UDPSession: ", ecode.message());
}
}
I2PUDPServerTunnel::I2PUDPServerTunnel(const std::string & name, std::shared_ptr<i2p::client::ClientDestination> localDestination,
boost::asio::ip::address localAddress, boost::asio::ip::udp::endpoint forwardTo, uint16_t port) :
m_IsUniqueLocal(true),
m_Name(name),
m_LocalAddress(localAddress),
m_RemoteEndpoint(forwardTo)
{
m_LocalDest = localDestination;
m_LocalDest->Start();
auto dgram = m_LocalDest->CreateDatagramDestination();
dgram->SetReceiver(std::bind(&I2PUDPServerTunnel::HandleRecvFromI2P, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5));
}
I2PUDPServerTunnel::~I2PUDPServerTunnel()
{
auto dgram = m_LocalDest->GetDatagramDestination();
if (dgram) dgram->ResetReceiver();
LogPrint(eLogInfo, "UDPServer: done");
}
void I2PUDPServerTunnel::Start() {
m_LocalDest->Start();
}
std::vector<std::shared_ptr<DatagramSessionInfo> > I2PUDPServerTunnel::GetSessions()
{
std::vector<std::shared_ptr<DatagramSessionInfo> > sessions;
std::lock_guard<std::mutex> lock(m_SessionsMutex);
for ( UDPSessionPtr s : m_Sessions )
{
if (!s->m_Destination) continue;
auto info = s->m_Destination->GetInfoForRemote(s->Identity);
if(!info) continue;
auto sinfo = std::make_shared<DatagramSessionInfo>();
sinfo->Name = m_Name;
sinfo->LocalIdent = std::make_shared<i2p::data::IdentHash>(m_LocalDest->GetIdentHash().data());
sinfo->RemoteIdent = std::make_shared<i2p::data::IdentHash>(s->Identity.data());
sinfo->CurrentIBGW = info->IBGW;
sinfo->CurrentOBEP = info->OBEP;
sessions.push_back(sinfo);
}
return sessions;
}
I2PUDPClientTunnel::I2PUDPClientTunnel(const std::string & name, const std::string &remoteDest,
boost::asio::ip::udp::endpoint localEndpoint,
std::shared_ptr<i2p::client::ClientDestination> localDestination,
uint16_t remotePort) :
m_Name(name),
m_RemoteDest(remoteDest),
m_LocalDest(localDestination),
m_LocalEndpoint(localEndpoint),
m_RemoteIdent(nullptr),
m_ResolveThread(nullptr),
m_LocalSocket(localDestination->GetService(), localEndpoint),
RemotePort(remotePort),
m_cancel_resolve(false)
{
auto dgram = m_LocalDest->CreateDatagramDestination();
dgram->SetReceiver(std::bind(&I2PUDPClientTunnel::HandleRecvFromI2P, this,
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4,
std::placeholders::_5));
}
void I2PUDPClientTunnel::Start() {
m_LocalDest->Start();
if (m_ResolveThread == nullptr)
m_ResolveThread = new std::thread(std::bind(&I2PUDPClientTunnel::TryResolving, this));
RecvFromLocal();
}
void I2PUDPClientTunnel::RecvFromLocal()
{
m_LocalSocket.async_receive_from(boost::asio::buffer(m_RecvBuff, I2P_UDP_MAX_MTU),
m_RecvEndpoint, std::bind(&I2PUDPClientTunnel::HandleRecvFromLocal, this, std::placeholders::_1, std::placeholders::_2));
}
void I2PUDPClientTunnel::HandleRecvFromLocal(const boost::system::error_code & ec, std::size_t transferred)
{
if(ec) {
LogPrint(eLogError, "UDP Client: ", ec.message());
return;
}
if(!m_RemoteIdent) {
LogPrint(eLogWarning, "UDP Client: remote endpoint not resolved yet");
RecvFromLocal();
return; // drop, remote not resolved
}
auto remotePort = m_RecvEndpoint.port();
auto itr = m_Sessions.find(remotePort);
if (itr == m_Sessions.end()) {
// track new udp convo
m_Sessions[remotePort] = {boost::asio::ip::udp::endpoint(m_RecvEndpoint), 0};
}
// send off to remote i2p destination
LogPrint(eLogDebug, "UDP Client: send ", transferred, " to ", m_RemoteIdent->ToBase32(), ":", RemotePort);
m_LocalDest->GetDatagramDestination()->SendDatagramTo(m_RecvBuff, transferred, *m_RemoteIdent, remotePort, RemotePort);
// mark convo as active
m_Sessions[remotePort].second = i2p::util::GetMillisecondsSinceEpoch();
RecvFromLocal();
}
std::vector<std::shared_ptr<DatagramSessionInfo> > I2PUDPClientTunnel::GetSessions()
{
// TODO: implement
std::vector<std::shared_ptr<DatagramSessionInfo> > infos;
return infos;
}
void I2PUDPClientTunnel::TryResolving() {
LogPrint(eLogInfo, "UDP Tunnel: Trying to resolve ", m_RemoteDest);
i2p::data::IdentHash * h = new i2p::data::IdentHash;
while(!context.GetAddressBook().GetIdentHash(m_RemoteDest, *h) && !m_cancel_resolve)
{
LogPrint(eLogWarning, "UDP Tunnel: failed to lookup ", m_RemoteDest);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
if(m_cancel_resolve)
{
LogPrint(eLogError, "UDP Tunnel: lookup of ", m_RemoteDest, " was cancelled");
return;
}
m_RemoteIdent = h;
LogPrint(eLogInfo, "UDP Tunnel: resolved ", m_RemoteDest, " to ", m_RemoteIdent->ToBase32());
}
void I2PUDPClientTunnel::HandleRecvFromI2P(const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
{
if(m_RemoteIdent && from.GetIdentHash() == *m_RemoteIdent)
{
auto itr = m_Sessions.find(toPort);
// found convo ?
if(itr != m_Sessions.end())
{
// found convo
if (len > 0) {
LogPrint(eLogDebug, "UDP Client: got ", len, "B from ", from.GetIdentHash().ToBase32());
m_LocalSocket.send_to(boost::asio::buffer(buf, len), itr->second.first);
// mark convo as active
itr->second.second = i2p::util::GetMillisecondsSinceEpoch();
}
}
else
LogPrint(eLogWarning, "UDP Client: not tracking udp session using port ", (int) toPort);
}
else
LogPrint(eLogWarning, "UDP Client: unwarrented traffic from ", from.GetIdentHash().ToBase32());
}
I2PUDPClientTunnel::~I2PUDPClientTunnel() {
auto dgram = m_LocalDest->GetDatagramDestination();
if (dgram) dgram->ResetReceiver();
m_Sessions.clear();
if(m_LocalSocket.is_open())
m_LocalSocket.close();
m_cancel_resolve = true;
if(m_ResolveThread)
{
m_ResolveThread->join();
delete m_ResolveThread;
m_ResolveThread = nullptr;
}
if (m_RemoteIdent) delete m_RemoteIdent;
}
}
}

View File

@ -1,618 +0,0 @@
#include <time.h>
#include <stdio.h>
#include "Crypto.h"
#include "I2PEndian.h"
#include "Log.h"
#include "Identity.h"
namespace i2p
{
namespace data
{
Identity& Identity::operator=(const Keys& keys)
{
// copy public and signing keys together
memcpy (publicKey, keys.publicKey, sizeof (publicKey) + sizeof (signingKey));
memset (certificate, 0, sizeof (certificate));
return *this;
}
size_t Identity::FromBuffer (const uint8_t * buf, size_t len)
{
if ( len < DEFAULT_IDENTITY_SIZE ) {
// buffer too small, don't overflow
return 0;
}
memcpy (publicKey, buf, DEFAULT_IDENTITY_SIZE);
return DEFAULT_IDENTITY_SIZE;
}
IdentHash Identity::Hash () const
{
IdentHash hash;
SHA256(publicKey, DEFAULT_IDENTITY_SIZE, hash);
return hash;
}
IdentityEx::IdentityEx ():
m_IsVerifierCreated (false), m_ExtendedLen (0), m_ExtendedBuffer (nullptr)
{
}
IdentityEx::IdentityEx(const uint8_t * publicKey, const uint8_t * signingKey, SigningKeyType type):
m_IsVerifierCreated (false)
{
memcpy (m_StandardIdentity.publicKey, publicKey, sizeof (m_StandardIdentity.publicKey));
if (type != SIGNING_KEY_TYPE_DSA_SHA1)
{
size_t excessLen = 0;
uint8_t * excessBuf = nullptr;
switch (type)
{
case SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
{
size_t padding = 128 - i2p::crypto::ECDSAP256_KEY_LENGTH; // 64 = 128 - 64
RAND_bytes (m_StandardIdentity.signingKey, padding);
memcpy (m_StandardIdentity.signingKey + padding, signingKey, i2p::crypto::ECDSAP256_KEY_LENGTH);
break;
}
case SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
{
size_t padding = 128 - i2p::crypto::ECDSAP384_KEY_LENGTH; // 32 = 128 - 96
RAND_bytes (m_StandardIdentity.signingKey, padding);
memcpy (m_StandardIdentity.signingKey + padding, signingKey, i2p::crypto::ECDSAP384_KEY_LENGTH);
break;
}
case SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
{
memcpy (m_StandardIdentity.signingKey, signingKey, 128);
excessLen = i2p::crypto::ECDSAP521_KEY_LENGTH - 128; // 4 = 132 - 128
excessBuf = new uint8_t[excessLen];
memcpy (excessBuf, signingKey + 128, excessLen);
break;
}
case SIGNING_KEY_TYPE_RSA_SHA256_2048:
{
memcpy (m_StandardIdentity.signingKey, signingKey, 128);
excessLen = i2p::crypto::RSASHA2562048_KEY_LENGTH - 128; // 128 = 256 - 128
excessBuf = new uint8_t[excessLen];
memcpy (excessBuf, signingKey + 128, excessLen);
break;
}
case SIGNING_KEY_TYPE_RSA_SHA384_3072:
{
memcpy (m_StandardIdentity.signingKey, signingKey, 128);
excessLen = i2p::crypto::RSASHA3843072_KEY_LENGTH - 128; // 256 = 384 - 128
excessBuf = new uint8_t[excessLen];
memcpy (excessBuf, signingKey + 128, excessLen);
break;
}
case SIGNING_KEY_TYPE_RSA_SHA512_4096:
{
memcpy (m_StandardIdentity.signingKey, signingKey, 128);
excessLen = i2p::crypto::RSASHA5124096_KEY_LENGTH - 128; // 384 = 512 - 128
excessBuf = new uint8_t[excessLen];
memcpy (excessBuf, signingKey + 128, excessLen);
break;
}
case SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519:
{
size_t padding = 128 - i2p::crypto::EDDSA25519_PUBLIC_KEY_LENGTH; // 96 = 128 - 32
RAND_bytes (m_StandardIdentity.signingKey, padding);
memcpy (m_StandardIdentity.signingKey + padding, signingKey, i2p::crypto::EDDSA25519_PUBLIC_KEY_LENGTH);
break;
}
default:
LogPrint (eLogError, "Identity: Signing key type ", (int)type, " is not supported");
}
m_ExtendedLen = 4 + excessLen; // 4 bytes extra + excess length
// fill certificate
m_StandardIdentity.certificate[0] = CERTIFICATE_TYPE_KEY;
htobe16buf (m_StandardIdentity.certificate + 1, m_ExtendedLen);
// fill extended buffer
m_ExtendedBuffer = new uint8_t[m_ExtendedLen];
htobe16buf (m_ExtendedBuffer, type);
htobe16buf (m_ExtendedBuffer + 2, CRYPTO_KEY_TYPE_ELGAMAL);
if (excessLen && excessBuf)
{
memcpy (m_ExtendedBuffer + 4, excessBuf, excessLen);
delete[] excessBuf;
}
// calculate ident hash
uint8_t * buf = new uint8_t[GetFullLen ()];
ToBuffer (buf, GetFullLen ());
SHA256(buf, GetFullLen (), m_IdentHash);
delete[] buf;
}
else // DSA-SHA1
{
memcpy (m_StandardIdentity.signingKey, signingKey, sizeof (m_StandardIdentity.signingKey));
memset (m_StandardIdentity.certificate, 0, sizeof (m_StandardIdentity.certificate));
m_IdentHash = m_StandardIdentity.Hash ();
m_ExtendedLen = 0;
m_ExtendedBuffer = nullptr;
}
CreateVerifier ();
}
IdentityEx::IdentityEx (const uint8_t * buf, size_t len):
m_IsVerifierCreated (false), m_ExtendedLen (0), m_ExtendedBuffer (nullptr)
{
FromBuffer (buf, len);
}
IdentityEx::IdentityEx (const IdentityEx& other):
m_IsVerifierCreated (false), m_ExtendedLen (0), m_ExtendedBuffer (nullptr)
{
*this = other;
}
IdentityEx::IdentityEx (const Identity& standard):
m_IsVerifierCreated (false), m_ExtendedLen (0), m_ExtendedBuffer (nullptr)
{
*this = standard;
}
IdentityEx::~IdentityEx ()
{
delete[] m_ExtendedBuffer;
}
IdentityEx& IdentityEx::operator=(const IdentityEx& other)
{
memcpy (&m_StandardIdentity, &other.m_StandardIdentity, DEFAULT_IDENTITY_SIZE);
m_IdentHash = other.m_IdentHash;
delete[] m_ExtendedBuffer;
m_ExtendedLen = other.m_ExtendedLen;
if (m_ExtendedLen > 0)
{
m_ExtendedBuffer = new uint8_t[m_ExtendedLen];
memcpy (m_ExtendedBuffer, other.m_ExtendedBuffer, m_ExtendedLen);
}
else
m_ExtendedBuffer = nullptr;
m_Verifier = nullptr;
m_IsVerifierCreated = false;
return *this;
}
IdentityEx& IdentityEx::operator=(const Identity& standard)
{
m_StandardIdentity = standard;
m_IdentHash = m_StandardIdentity.Hash ();
delete[] m_ExtendedBuffer;
m_ExtendedBuffer = nullptr;
m_ExtendedLen = 0;
m_Verifier = nullptr;
m_IsVerifierCreated = false;
return *this;
}
size_t IdentityEx::FromBuffer (const uint8_t * buf, size_t len)
{
if (len < DEFAULT_IDENTITY_SIZE)
{
LogPrint (eLogError, "Identity: buffer length ", len, " is too small");
return 0;
}
memcpy (&m_StandardIdentity, buf, DEFAULT_IDENTITY_SIZE);
if(m_ExtendedBuffer) delete[] m_ExtendedBuffer;
m_ExtendedBuffer = nullptr;
m_ExtendedLen = bufbe16toh (m_StandardIdentity.certificate + 1);
if (m_ExtendedLen)
{
if (m_ExtendedLen + DEFAULT_IDENTITY_SIZE <= len)
{
m_ExtendedBuffer = new uint8_t[m_ExtendedLen];
memcpy (m_ExtendedBuffer, buf + DEFAULT_IDENTITY_SIZE, m_ExtendedLen);
}
else
{
LogPrint (eLogError, "Identity: Certificate length ", m_ExtendedLen, " exceeds buffer length ", len - DEFAULT_IDENTITY_SIZE);
m_ExtendedLen = 0;
return 0;
}
}
else
{
m_ExtendedLen = 0;
m_ExtendedBuffer = nullptr;
}
SHA256(buf, GetFullLen (), m_IdentHash);
m_Verifier = nullptr;
return GetFullLen ();
}
size_t IdentityEx::ToBuffer (uint8_t * buf, size_t len) const
{
const size_t fullLen = GetFullLen();
if (fullLen > len) return 0; // buffer is too small and may overflow somewhere else
memcpy (buf, &m_StandardIdentity, DEFAULT_IDENTITY_SIZE);
if (m_ExtendedLen > 0 && m_ExtendedBuffer)
memcpy (buf + DEFAULT_IDENTITY_SIZE, m_ExtendedBuffer, m_ExtendedLen);
return fullLen;
}
size_t IdentityEx::FromBase64(const std::string& s)
{
const size_t slen = s.length();
std::vector<uint8_t> buf(slen); // binary data can't exceed base64
const size_t len = Base64ToByteStream (s.c_str(), slen, buf.data(), slen);
return FromBuffer (buf.data(), len);
}
std::string IdentityEx::ToBase64 () const
{
const size_t bufLen = GetFullLen();
const size_t strLen = Base64EncodingBufferSize(bufLen);
std::vector<uint8_t> buf(bufLen);
std::vector<char> str(strLen);
size_t l = ToBuffer (buf.data(), bufLen);
size_t l1 = i2p::data::ByteStreamToBase64 (buf.data(), l, str.data(), strLen);
return std::string (str.data(), l1);
}
size_t IdentityEx::GetSigningPublicKeyLen () const
{
if (!m_Verifier) CreateVerifier ();
if (m_Verifier)
return m_Verifier->GetPublicKeyLen ();
return 128;
}
size_t IdentityEx::GetSigningPrivateKeyLen () const
{
if (!m_Verifier) CreateVerifier ();
if (m_Verifier)
return m_Verifier->GetPrivateKeyLen ();
return GetSignatureLen ()/2;
}
size_t IdentityEx::GetSignatureLen () const
{
if (!m_Verifier) CreateVerifier ();
if (m_Verifier)
return m_Verifier->GetSignatureLen ();
return i2p::crypto::DSA_SIGNATURE_LENGTH;
}
bool IdentityEx::Verify (const uint8_t * buf, size_t len, const uint8_t * signature) const
{
if (!m_Verifier) CreateVerifier ();
if (m_Verifier)
return m_Verifier->Verify (buf, len, signature);
return false;
}
SigningKeyType IdentityEx::GetSigningKeyType () const
{
if (m_StandardIdentity.certificate[0] == CERTIFICATE_TYPE_KEY && m_ExtendedBuffer)
return bufbe16toh (m_ExtendedBuffer); // signing key
return SIGNING_KEY_TYPE_DSA_SHA1;
}
CryptoKeyType IdentityEx::GetCryptoKeyType () const
{
if (m_StandardIdentity.certificate[0] == CERTIFICATE_TYPE_KEY && m_ExtendedBuffer)
return bufbe16toh (m_ExtendedBuffer + 2); // crypto key
return CRYPTO_KEY_TYPE_ELGAMAL;
}
void IdentityEx::CreateVerifier () const
{
if (m_Verifier) return; // don't create again
auto keyType = GetSigningKeyType ();
switch (keyType)
{
case SIGNING_KEY_TYPE_DSA_SHA1:
UpdateVerifier (new i2p::crypto::DSAVerifier (m_StandardIdentity.signingKey));
break;
case SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
{
size_t padding = 128 - i2p::crypto::ECDSAP256_KEY_LENGTH; // 64 = 128 - 64
UpdateVerifier (new i2p::crypto::ECDSAP256Verifier (m_StandardIdentity.signingKey + padding));
break;
}
case SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
{
size_t padding = 128 - i2p::crypto::ECDSAP384_KEY_LENGTH; // 32 = 128 - 96
UpdateVerifier (new i2p::crypto::ECDSAP384Verifier (m_StandardIdentity.signingKey + padding));
break;
}
case SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
{
uint8_t signingKey[i2p::crypto::ECDSAP521_KEY_LENGTH];
memcpy (signingKey, m_StandardIdentity.signingKey, 128);
size_t excessLen = i2p::crypto::ECDSAP521_KEY_LENGTH - 128; // 4 = 132- 128
memcpy (signingKey + 128, m_ExtendedBuffer + 4, excessLen); // right after signing and crypto key types
UpdateVerifier (new i2p::crypto::ECDSAP521Verifier (signingKey));
break;
}
case SIGNING_KEY_TYPE_RSA_SHA256_2048:
{
uint8_t signingKey[i2p::crypto::RSASHA2562048_KEY_LENGTH];
memcpy (signingKey, m_StandardIdentity.signingKey, 128);
size_t excessLen = i2p::crypto::RSASHA2562048_KEY_LENGTH - 128; // 128 = 256- 128
memcpy (signingKey + 128, m_ExtendedBuffer + 4, excessLen); // right after signing and crypto key types
UpdateVerifier (new i2p::crypto:: RSASHA2562048Verifier (signingKey));
break;
}
case SIGNING_KEY_TYPE_RSA_SHA384_3072:
{
uint8_t signingKey[i2p::crypto::RSASHA3843072_KEY_LENGTH];
memcpy (signingKey, m_StandardIdentity.signingKey, 128);
size_t excessLen = i2p::crypto::RSASHA3843072_KEY_LENGTH - 128; // 256 = 384- 128
memcpy (signingKey + 128, m_ExtendedBuffer + 4, excessLen); // right after signing and crypto key types
UpdateVerifier (new i2p::crypto:: RSASHA3843072Verifier (signingKey));
break;
}
case SIGNING_KEY_TYPE_RSA_SHA512_4096:
{
uint8_t signingKey[i2p::crypto::RSASHA5124096_KEY_LENGTH];
memcpy (signingKey, m_StandardIdentity.signingKey, 128);
size_t excessLen = i2p::crypto::RSASHA5124096_KEY_LENGTH - 128; // 384 = 512- 128
memcpy (signingKey + 128, m_ExtendedBuffer + 4, excessLen); // right after signing and crypto key types
UpdateVerifier (new i2p::crypto:: RSASHA5124096Verifier (signingKey));
break;
}
case SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519:
{
size_t padding = 128 - i2p::crypto::EDDSA25519_PUBLIC_KEY_LENGTH; // 96 = 128 - 32
UpdateVerifier (new i2p::crypto::EDDSA25519Verifier (m_StandardIdentity.signingKey + padding));
break;
}
default:
LogPrint (eLogError, "Identity: Signing key type ", (int)keyType, " is not supported");
}
}
void IdentityEx::UpdateVerifier (i2p::crypto::Verifier * verifier) const
{
if (!m_Verifier)
{
auto created = m_IsVerifierCreated.exchange (true);
if (!created)
m_Verifier.reset (verifier);
else
{
delete verifier;
int count = 0;
while (!m_Verifier && count < 500) // 5 seconds
{
std::this_thread::sleep_for (std::chrono::milliseconds(10));
count++;
}
if (!m_Verifier)
LogPrint (eLogError, "Identity: couldn't get verifier in 5 seconds");
}
}
else
delete verifier;
}
void IdentityEx::DropVerifier () const
{
// TODO: potential race condition with Verify
m_IsVerifierCreated = false;
m_Verifier = nullptr;
}
PrivateKeys& PrivateKeys::operator=(const Keys& keys)
{
m_Public = std::make_shared<IdentityEx>(Identity (keys));
memcpy (m_PrivateKey, keys.privateKey, 256); // 256
memcpy (m_SigningPrivateKey, keys.signingPrivateKey, m_Public->GetSigningPrivateKeyLen ());
m_Signer = nullptr;
CreateSigner ();
return *this;
}
PrivateKeys& PrivateKeys::operator=(const PrivateKeys& other)
{
m_Public = std::make_shared<IdentityEx>(*other.m_Public);
memcpy (m_PrivateKey, other.m_PrivateKey, 256); // 256
memcpy (m_SigningPrivateKey, other.m_SigningPrivateKey, m_Public->GetSigningPrivateKeyLen ());
m_Signer = nullptr;
CreateSigner ();
return *this;
}
size_t PrivateKeys::FromBuffer (const uint8_t * buf, size_t len)
{
m_Public = std::make_shared<IdentityEx>(buf, len);
size_t ret = m_Public->GetFullLen ();
memcpy (m_PrivateKey, buf + ret, 256); // private key always 256
ret += 256;
size_t signingPrivateKeySize = m_Public->GetSigningPrivateKeyLen ();
if(signingPrivateKeySize + ret > len) return 0; // overflow
memcpy (m_SigningPrivateKey, buf + ret, signingPrivateKeySize);
ret += signingPrivateKeySize;
m_Signer = nullptr;
CreateSigner ();
return ret;
}
size_t PrivateKeys::ToBuffer (uint8_t * buf, size_t len) const
{
size_t ret = m_Public->ToBuffer (buf, len);
memcpy (buf + ret, m_PrivateKey, 256); // private key always 256
ret += 256;
size_t signingPrivateKeySize = m_Public->GetSigningPrivateKeyLen ();
if(ret + signingPrivateKeySize > len) return 0; // overflow
memcpy (buf + ret, m_SigningPrivateKey, signingPrivateKeySize);
ret += signingPrivateKeySize;
return ret;
}
size_t PrivateKeys::FromBase64(const std::string& s)
{
uint8_t * buf = new uint8_t[s.length ()];
size_t l = i2p::data::Base64ToByteStream (s.c_str (), s.length (), buf, s.length ());
size_t ret = FromBuffer (buf, l);
delete[] buf;
return ret;
}
std::string PrivateKeys::ToBase64 () const
{
uint8_t * buf = new uint8_t[GetFullLen ()];
char * str = new char[GetFullLen ()*2];
size_t l = ToBuffer (buf, GetFullLen ());
size_t l1 = i2p::data::ByteStreamToBase64 (buf, l, str, GetFullLen ()*2);
str[l1] = 0;
delete[] buf;
std::string ret(str);
delete[] str;
return ret;
}
void PrivateKeys::Sign (const uint8_t * buf, int len, uint8_t * signature) const
{
if (!m_Signer)
CreateSigner();
m_Signer->Sign (buf, len, signature);
}
void PrivateKeys::CreateSigner () const
{
if (m_Signer) return;
switch (m_Public->GetSigningKeyType ())
{
case SIGNING_KEY_TYPE_DSA_SHA1:
m_Signer.reset (new i2p::crypto::DSASigner (m_SigningPrivateKey, m_Public->GetStandardIdentity ().signingKey));
break;
case SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
m_Signer.reset (new i2p::crypto::ECDSAP256Signer (m_SigningPrivateKey));
break;
case SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
m_Signer.reset (new i2p::crypto::ECDSAP384Signer (m_SigningPrivateKey));
break;
case SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
m_Signer.reset (new i2p::crypto::ECDSAP521Signer (m_SigningPrivateKey));
break;
case SIGNING_KEY_TYPE_RSA_SHA256_2048:
m_Signer.reset (new i2p::crypto::RSASHA2562048Signer (m_SigningPrivateKey));
break;
case SIGNING_KEY_TYPE_RSA_SHA384_3072:
m_Signer.reset (new i2p::crypto::RSASHA3843072Signer (m_SigningPrivateKey));
break;
case SIGNING_KEY_TYPE_RSA_SHA512_4096:
m_Signer.reset (new i2p::crypto::RSASHA5124096Signer (m_SigningPrivateKey));
break;
case SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519:
m_Signer.reset (new i2p::crypto::EDDSA25519Signer (m_SigningPrivateKey, m_Public->GetStandardIdentity ().certificate - i2p::crypto::EDDSA25519_PUBLIC_KEY_LENGTH));
break;
default:
LogPrint (eLogError, "Identity: Signing key type ", (int)m_Public->GetSigningKeyType (), " is not supported");
}
}
PrivateKeys PrivateKeys::CreateRandomKeys (SigningKeyType type)
{
if (type != SIGNING_KEY_TYPE_DSA_SHA1)
{
PrivateKeys keys;
// signature
uint8_t signingPublicKey[512]; // signing public key is 512 bytes max
switch (type)
{
case SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
i2p::crypto::CreateECDSAP256RandomKeys (keys.m_SigningPrivateKey, signingPublicKey);
break;
case SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
i2p::crypto::CreateECDSAP384RandomKeys (keys.m_SigningPrivateKey, signingPublicKey);
break;
case SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
i2p::crypto::CreateECDSAP521RandomKeys (keys.m_SigningPrivateKey, signingPublicKey);
break;
case SIGNING_KEY_TYPE_RSA_SHA256_2048:
i2p::crypto::CreateRSARandomKeys (i2p::crypto::RSASHA2562048_KEY_LENGTH, keys.m_SigningPrivateKey, signingPublicKey);
break;
case SIGNING_KEY_TYPE_RSA_SHA384_3072:
i2p::crypto::CreateRSARandomKeys (i2p::crypto::RSASHA3843072_KEY_LENGTH, keys.m_SigningPrivateKey, signingPublicKey);
break;
case SIGNING_KEY_TYPE_RSA_SHA512_4096:
i2p::crypto::CreateRSARandomKeys (i2p::crypto::RSASHA5124096_KEY_LENGTH, keys.m_SigningPrivateKey, signingPublicKey);
break;
case SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519:
i2p::crypto::CreateEDDSA25519RandomKeys (keys.m_SigningPrivateKey, signingPublicKey);
break;
default:
LogPrint (eLogError, "Identity: Signing key type ", (int)type, " is not supported. Create DSA-SHA1");
return PrivateKeys (i2p::data::CreateRandomKeys ()); // DSA-SHA1
}
// encryption
uint8_t publicKey[256];
i2p::crypto::GenerateElGamalKeyPair (keys.m_PrivateKey, publicKey);
// identity
keys.m_Public = std::make_shared<IdentityEx> (publicKey, signingPublicKey, type);
keys.CreateSigner ();
return keys;
}
return PrivateKeys (i2p::data::CreateRandomKeys ()); // DSA-SHA1
}
Keys CreateRandomKeys ()
{
Keys keys;
// encryption
i2p::crypto::GenerateElGamalKeyPair(keys.privateKey, keys.publicKey);
// signing
i2p::crypto::CreateDSARandomKeys (keys.signingPrivateKey, keys.signingKey);
return keys;
}
IdentHash CreateRoutingKey (const IdentHash& ident)
{
uint8_t buf[41]; // ident + yyyymmdd
memcpy (buf, (const uint8_t *)ident, 32);
time_t t = time (nullptr);
struct tm tm;
#ifdef _WIN32
gmtime_s(&tm, &t);
sprintf_s((char *)(buf + 32), 9, "%04i%02i%02i", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
#else
gmtime_r(&t, &tm);
sprintf((char *)(buf + 32), "%04i%02i%02i", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
#endif
IdentHash key;
SHA256(buf, 40, key);
return key;
}
XORMetric operator^(const IdentHash& key1, const IdentHash& key2)
{
XORMetric m;
#if defined(__AVX__) // for AVX
__asm__
(
"vmovups %1, %%ymm0 \n"
"vmovups %2, %%ymm1 \n"
"vxorps %%ymm0, %%ymm1, %%ymm1 \n"
"vmovups %%ymm1, %0 \n"
: "=m"(*m.metric)
: "m"(*key1), "m"(*key2)
: "memory", "%xmm0", "%xmm1" // should be replaced by %ymm0/1 once supported by compiler
);
#else
const uint64_t * hash1 = key1.GetLL (), * hash2 = key2.GetLL ();
m.metric_ll[0] = hash1[0] ^ hash2[0];
m.metric_ll[1] = hash1[1] ^ hash2[1];
m.metric_ll[2] = hash1[2] ^ hash2[2];
m.metric_ll[3] = hash1[3] ^ hash2[3];
#endif
return m;
}
}
}

View File

@ -1,4 +1,4 @@
Copyright (c) 2013-2015, The PurpleI2P Project
Copyright (c) 2013-2020, The PurpleI2P Project
All rights reserved.

View File

@ -1,262 +0,0 @@
#include <string.h>
#include "I2PEndian.h"
#include "Crypto.h"
#include "Log.h"
#include "Timestamp.h"
#include "NetDb.h"
#include "Tunnel.h"
#include "LeaseSet.h"
namespace i2p
{
namespace data
{
LeaseSet::LeaseSet (const uint8_t * buf, size_t len, bool storeLeases):
m_IsValid (true), m_StoreLeases (storeLeases), m_ExpirationTime (0)
{
m_Buffer = new uint8_t[len];
memcpy (m_Buffer, buf, len);
m_BufferLen = len;
ReadFromBuffer ();
}
void LeaseSet::Update (const uint8_t * buf, size_t len)
{
if (len > m_BufferLen)
{
auto oldBuffer = m_Buffer;
m_Buffer = new uint8_t[len];
delete[] oldBuffer;
}
memcpy (m_Buffer, buf, len);
m_BufferLen = len;
ReadFromBuffer (false);
}
void LeaseSet::PopulateLeases ()
{
m_StoreLeases = true;
ReadFromBuffer (false);
}
void LeaseSet::ReadFromBuffer (bool readIdentity)
{
if (readIdentity || !m_Identity)
m_Identity = std::make_shared<IdentityEx>(m_Buffer, m_BufferLen);
size_t size = m_Identity->GetFullLen ();
if (size > m_BufferLen)
{
LogPrint (eLogError, "LeaseSet: identity length ", size, " exceeds buffer size ", m_BufferLen);
m_IsValid = false;
return;
}
memcpy (m_EncryptionKey, m_Buffer + size, 256);
size += 256; // encryption key
size += m_Identity->GetSigningPublicKeyLen (); // unused signing key
uint8_t num = m_Buffer[size];
size++; // num
LogPrint (eLogDebug, "LeaseSet: read num=", (int)num);
if (!num || num > MAX_NUM_LEASES)
{
LogPrint (eLogError, "LeaseSet: incorrect number of leases", (int)num);
m_IsValid = false;
return;
}
// reset existing leases
if (m_StoreLeases)
for (auto& it: m_Leases)
it->isUpdated = false;
else
m_Leases.clear ();
// process leases
m_ExpirationTime = 0;
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
const uint8_t * leases = m_Buffer + size;
for (int i = 0; i < num; i++)
{
Lease lease;
lease.tunnelGateway = leases;
leases += 32; // gateway
lease.tunnelID = bufbe32toh (leases);
leases += 4; // tunnel ID
lease.endDate = bufbe64toh (leases);
leases += 8; // end date
if (ts < lease.endDate + LEASE_ENDDATE_THRESHOLD)
{
if (lease.endDate > m_ExpirationTime)
m_ExpirationTime = lease.endDate;
if (m_StoreLeases)
{
auto ret = m_Leases.insert (std::make_shared<Lease>(lease));
if (!ret.second) (*ret.first)->endDate = lease.endDate; // update existing
(*ret.first)->isUpdated = true;
// check if lease's gateway is in our netDb
if (!netdb.FindRouter (lease.tunnelGateway))
{
// if not found request it
LogPrint (eLogInfo, "LeaseSet: Lease's tunnel gateway not found, requesting");
netdb.RequestDestination (lease.tunnelGateway);
}
}
}
else
LogPrint (eLogWarning, "LeaseSet: Lease is expired already ");
}
if (!m_ExpirationTime)
{
LogPrint (eLogWarning, "LeaseSet: all leases are expired. Dropped");
m_IsValid = false;
return;
}
m_ExpirationTime += LEASE_ENDDATE_THRESHOLD;
// delete old leases
if (m_StoreLeases)
{
for (auto it = m_Leases.begin (); it != m_Leases.end ();)
{
if (!(*it)->isUpdated)
{
(*it)->endDate = 0; // somebody might still hold it
m_Leases.erase (it++);
}
else
++it;
}
}
// verify
if (!m_Identity->Verify (m_Buffer, leases - m_Buffer, leases))
{
LogPrint (eLogWarning, "LeaseSet: verification failed");
m_IsValid = false;
}
}
uint64_t LeaseSet::ExtractTimestamp (const uint8_t * buf, size_t len) const
{
if (!m_Identity) return 0;
size_t size = m_Identity->GetFullLen ();
if (size > len) return 0;
size += 256; // encryption key
size += m_Identity->GetSigningPublicKeyLen (); // unused signing key
if (size > len) return 0;
uint8_t num = buf[size];
size++; // num
if (size + num*LEASE_SIZE > len) return 0;
uint64_t timestamp= 0 ;
for (int i = 0; i < num; i++)
{
size += 36; // gateway (32) + tunnelId(4)
auto endDate = bufbe64toh (buf + size);
size += 8; // end date
if (!timestamp || endDate < timestamp)
timestamp = endDate;
}
return timestamp;
}
bool LeaseSet::IsNewer (const uint8_t * buf, size_t len) const
{
return ExtractTimestamp (buf, len) > ExtractTimestamp (m_Buffer, m_BufferLen);
}
bool LeaseSet::ExpiresSoon(const uint64_t dlt, const uint64_t fudge) const
{
auto now = i2p::util::GetMillisecondsSinceEpoch ();
if (fudge) now += rand() % fudge;
if (now >= m_ExpirationTime) return true;
return m_ExpirationTime - now <= dlt;
}
const std::vector<std::shared_ptr<const Lease> > LeaseSet::GetNonExpiredLeases (bool withThreshold) const
{
return GetNonExpiredLeasesExcluding( [] (const Lease & l) -> bool { return false; }, withThreshold);
}
const std::vector<std::shared_ptr<const Lease> > LeaseSet::GetNonExpiredLeasesExcluding (LeaseInspectFunc exclude, bool withThreshold) const
{
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
std::vector<std::shared_ptr<const Lease> > leases;
for (const auto& it: m_Leases)
{
auto endDate = it->endDate;
if (withThreshold)
endDate += LEASE_ENDDATE_THRESHOLD;
else
endDate -= LEASE_ENDDATE_THRESHOLD;
if (ts < endDate && !exclude(*it))
leases.push_back (it);
}
return leases;
}
bool LeaseSet::HasExpiredLeases () const
{
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
for (const auto& it: m_Leases)
if (ts >= it->endDate) return true;
return false;
}
bool LeaseSet::IsExpired () const
{
if (m_StoreLeases && IsEmpty ()) return true;
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
return ts > m_ExpirationTime;
}
LocalLeaseSet::LocalLeaseSet (std::shared_ptr<const IdentityEx> identity, const uint8_t * encryptionPublicKey, std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels):
m_ExpirationTime (0), m_Identity (identity)
{
int num = tunnels.size ();
if (num > MAX_NUM_LEASES) num = MAX_NUM_LEASES;
// identity
auto signingKeyLen = m_Identity->GetSigningPublicKeyLen ();
m_BufferLen = m_Identity->GetFullLen () + 256 + signingKeyLen + 1 + num*LEASE_SIZE + m_Identity->GetSignatureLen ();
m_Buffer = new uint8_t[m_BufferLen];
auto offset = m_Identity->ToBuffer (m_Buffer, m_BufferLen);
memcpy (m_Buffer + offset, encryptionPublicKey, 256);
offset += 256;
memset (m_Buffer + offset, 0, signingKeyLen);
offset += signingKeyLen;
// num leases
m_Buffer[offset] = num;
offset++;
// leases
m_Leases = m_Buffer + offset;
auto currentTime = i2p::util::GetMillisecondsSinceEpoch ();
for (int i = 0; i < num; i++)
{
memcpy (m_Buffer + offset, tunnels[i]->GetNextIdentHash (), 32);
offset += 32; // gateway id
htobe32buf (m_Buffer + offset, tunnels[i]->GetNextTunnelID ());
offset += 4; // tunnel id
uint64_t ts = tunnels[i]->GetCreationTime () + i2p::tunnel::TUNNEL_EXPIRATION_TIMEOUT - i2p::tunnel::TUNNEL_EXPIRATION_THRESHOLD; // 1 minute before expiration
ts *= 1000; // in milliseconds
if (ts > m_ExpirationTime) m_ExpirationTime = ts;
// make sure leaseset is newer than previous, but adding some time to expiration date
ts += (currentTime - tunnels[i]->GetCreationTime ()*1000LL)*2/i2p::tunnel::TUNNEL_EXPIRATION_TIMEOUT; // up to 2 secs
htobe64buf (m_Buffer + offset, ts);
offset += 8; // end date
}
// we don't sign it yet. must be signed later on
}
LocalLeaseSet::LocalLeaseSet (std::shared_ptr<const IdentityEx> identity, const uint8_t * buf, size_t len):
m_ExpirationTime (0), m_Identity (identity)
{
m_BufferLen = len;
m_Buffer = new uint8_t[m_BufferLen];
memcpy (m_Buffer, buf, len);
}
bool LocalLeaseSet::IsExpired () const
{
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
return ts > m_ExpirationTime;
}
}
}

View File

@ -1,130 +0,0 @@
#ifndef LEASE_SET_H__
#define LEASE_SET_H__
#include <inttypes.h>
#include <string.h>
#include <vector>
#include <set>
#include <memory>
#include "Identity.h"
#include "Timestamp.h"
namespace i2p
{
namespace tunnel
{
class InboundTunnel;
}
namespace data
{
const int LEASE_ENDDATE_THRESHOLD = 51000; // in milliseconds
struct Lease
{
IdentHash tunnelGateway;
uint32_t tunnelID;
uint64_t endDate; // 0 means invalid
bool isUpdated; // trasient
/* return true if this lease expires within t millisecond + fudge factor */
bool ExpiresWithin( const uint64_t t, const uint64_t fudge = 1000 ) const {
auto expire = i2p::util::GetMillisecondsSinceEpoch ();
if(fudge) expire += rand() % fudge;
return endDate - expire >= t;
}
};
struct LeaseCmp
{
bool operator() (std::shared_ptr<const Lease> l1, std::shared_ptr<const Lease> l2) const
{
if (l1->tunnelID != l2->tunnelID)
return l1->tunnelID < l2->tunnelID;
else
return l1->tunnelGateway < l2->tunnelGateway;
};
};
typedef std::function<bool(const Lease & l)> LeaseInspectFunc;
const size_t MAX_LS_BUFFER_SIZE = 3072;
const size_t LEASE_SIZE = 44; // 32 + 4 + 8
const uint8_t MAX_NUM_LEASES = 16;
class LeaseSet: public RoutingDestination
{
public:
LeaseSet (const uint8_t * buf, size_t len, bool storeLeases = true);
~LeaseSet () { delete[] m_Buffer; };
void Update (const uint8_t * buf, size_t len);
bool IsNewer (const uint8_t * buf, size_t len) const;
void PopulateLeases (); // from buffer
std::shared_ptr<const IdentityEx> GetIdentity () const { return m_Identity; };
const uint8_t * GetBuffer () const { return m_Buffer; };
size_t GetBufferLen () const { return m_BufferLen; };
bool IsValid () const { return m_IsValid; };
const std::vector<std::shared_ptr<const Lease> > GetNonExpiredLeases (bool withThreshold = true) const;
const std::vector<std::shared_ptr<const Lease> > GetNonExpiredLeasesExcluding (LeaseInspectFunc exclude, bool withThreshold = true) const;
bool HasExpiredLeases () const;
bool IsExpired () const;
bool IsEmpty () const { return m_Leases.empty (); };
uint64_t GetExpirationTime () const { return m_ExpirationTime; };
bool ExpiresSoon(const uint64_t dlt=1000 * 5, const uint64_t fudge = 0) const ;
bool operator== (const LeaseSet& other) const
{ return m_BufferLen == other.m_BufferLen && !memcmp (m_Buffer, other.m_Buffer, m_BufferLen); };
// implements RoutingDestination
const IdentHash& GetIdentHash () const { return m_Identity->GetIdentHash (); };
const uint8_t * GetEncryptionPublicKey () const { return m_EncryptionKey; };
bool IsDestination () const { return true; };
private:
void ReadFromBuffer (bool readIdentity = true);
uint64_t ExtractTimestamp (const uint8_t * buf, size_t len) const; // min expiration time
private:
bool m_IsValid, m_StoreLeases; // we don't need to store leases for floodfill
std::set<std::shared_ptr<Lease>, LeaseCmp> m_Leases;
uint64_t m_ExpirationTime; // in milliseconds
std::shared_ptr<const IdentityEx> m_Identity;
uint8_t m_EncryptionKey[256];
uint8_t * m_Buffer;
size_t m_BufferLen;
};
class LocalLeaseSet
{
public:
LocalLeaseSet (std::shared_ptr<const IdentityEx> identity, const uint8_t * encryptionPublicKey, std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels);
LocalLeaseSet (std::shared_ptr<const IdentityEx> identity, const uint8_t * buf, size_t len);
~LocalLeaseSet () { delete[] m_Buffer; };
const uint8_t * GetBuffer () const { return m_Buffer; };
uint8_t * GetSignature () { return m_Buffer + m_BufferLen - GetSignatureLen (); };
size_t GetBufferLen () const { return m_BufferLen; };
size_t GetSignatureLen () const { return m_Identity->GetSignatureLen (); };
uint8_t * GetLeases () { return m_Leases; };
const IdentHash& GetIdentHash () const { return m_Identity->GetIdentHash (); };
bool IsExpired () const;
uint64_t GetExpirationTime () const { return m_ExpirationTime; };
void SetExpirationTime (uint64_t expirationTime) { m_ExpirationTime = expirationTime; };
bool operator== (const LeaseSet& other) const
{ return m_BufferLen == other.GetBufferLen () && !memcmp (other.GetBuffer (), other.GetBuffer (), m_BufferLen); };
private:
uint64_t m_ExpirationTime; // in milliseconds
std::shared_ptr<const IdentityEx> m_Identity;
uint8_t * m_Buffer, * m_Leases;
size_t m_BufferLen;
};
}
}
#endif

View File

@ -1,242 +0,0 @@
// LittleBigEndian.h fixed for 64-bits added union
//
#ifndef LITTLEBIGENDIAN_H
#define LITTLEBIGENDIAN_H
// Determine Little-Endian or Big-Endian
#define CURRENT_BYTE_ORDER (*(int *)"\x01\x02\x03\x04")
#define LITTLE_ENDIAN_BYTE_ORDER 0x04030201
#define BIG_ENDIAN_BYTE_ORDER 0x01020304
#define PDP_ENDIAN_BYTE_ORDER 0x02010403
#define IS_LITTLE_ENDIAN (CURRENT_BYTE_ORDER == LITTLE_ENDIAN_BYTE_ORDER)
#define IS_BIG_ENDIAN (CURRENT_BYTE_ORDER == BIG_ENDIAN_BYTE_ORDER)
#define IS_PDP_ENDIAN (CURRENT_BYTE_ORDER == PDP_ENDIAN_BYTE_ORDER)
// Forward declaration
template<typename T>
struct LittleEndian;
template<typename T>
struct BigEndian;
// Little-Endian template
#pragma pack(push,1)
template<typename T>
struct LittleEndian
{
union
{
unsigned char bytes[sizeof(T)];
T raw_value;
};
LittleEndian(T t = T())
{
operator =(t);
}
LittleEndian(const LittleEndian<T> & t)
{
raw_value = t.raw_value;
}
LittleEndian(const BigEndian<T> & t)
{
for (unsigned i = 0; i < sizeof(T); i++)
bytes[i] = t.bytes[sizeof(T)-1-i];
}
operator const T() const
{
T t = T();
for (unsigned i = 0; i < sizeof(T); i++)
t |= T(bytes[i]) << (i << 3);
return t;
}
const T operator = (const T t)
{
for (unsigned i = 0; i < sizeof(T); i++)
bytes[sizeof(T)-1 - i] = static_cast<unsigned char>(t >> (i << 3));
return t;
}
// operators
const T operator += (const T t)
{
return (*this = *this + t);
}
const T operator -= (const T t)
{
return (*this = *this - t);
}
const T operator *= (const T t)
{
return (*this = *this * t);
}
const T operator /= (const T t)
{
return (*this = *this / t);
}
const T operator %= (const T t)
{
return (*this = *this % t);
}
LittleEndian<T> operator ++ (int)
{
LittleEndian<T> tmp(*this);
operator ++ ();
return tmp;
}
LittleEndian<T> & operator ++ ()
{
for (unsigned i = 0; i < sizeof(T); i++)
{
++bytes[i];
if (bytes[i] != 0)
break;
}
return (*this);
}
LittleEndian<T> operator -- (int)
{
LittleEndian<T> tmp(*this);
operator -- ();
return tmp;
}
LittleEndian<T> & operator -- ()
{
for (unsigned i = 0; i < sizeof(T); i++)
{
--bytes[i];
if (bytes[i] != (T)(-1))
break;
}
return (*this);
}
};
#pragma pack(pop)
// Big-Endian template
#pragma pack(push,1)
template<typename T>
struct BigEndian
{
union
{
unsigned char bytes[sizeof(T)];
T raw_value;
};
BigEndian(T t = T())
{
operator =(t);
}
BigEndian(const BigEndian<T> & t)
{
raw_value = t.raw_value;
}
BigEndian(const LittleEndian<T> & t)
{
for (unsigned i = 0; i < sizeof(T); i++)
bytes[i] = t.bytes[sizeof(T)-1-i];
}
operator const T() const
{
T t = T();
for (unsigned i = 0; i < sizeof(T); i++)
t |= T(bytes[sizeof(T) - 1 - i]) << (i << 3);
return t;
}
const T operator = (const T t)
{
for (unsigned i = 0; i < sizeof(T); i++)
bytes[sizeof(T) - 1 - i] = t >> (i << 3);
return t;
}
// operators
const T operator += (const T t)
{
return (*this = *this + t);
}
const T operator -= (const T t)
{
return (*this = *this - t);
}
const T operator *= (const T t)
{
return (*this = *this * t);
}
const T operator /= (const T t)
{
return (*this = *this / t);
}
const T operator %= (const T t)
{
return (*this = *this % t);
}
BigEndian<T> operator ++ (int)
{
BigEndian<T> tmp(*this);
operator ++ ();
return tmp;
}
BigEndian<T> & operator ++ ()
{
for (unsigned i = 0; i < sizeof(T); i++)
{
++bytes[sizeof(T) - 1 - i];
if (bytes[sizeof(T) - 1 - i] != 0)
break;
}
return (*this);
}
BigEndian<T> operator -- (int)
{
BigEndian<T> tmp(*this);
operator -- ();
return tmp;
}
BigEndian<T> & operator -- ()
{
for (unsigned i = 0; i < sizeof(T); i++)
{
--bytes[sizeof(T) - 1 - i];
if (bytes[sizeof(T) - 1 - i] != (T)(-1))
break;
}
return (*this);
}
};
#pragma pack(pop)
#endif // LITTLEBIGENDIAN_H

188
Makefile
View File

@ -1,55 +1,108 @@
UNAME := $(shell uname -s)
SHLIB := libi2pd.so
ARLIB := libi2pd.a
SHLIB_CLIENT := libi2pdclient.so
ARLIB_CLIENT := libi2pdclient.a
I2PD := i2pd
GREP := grep
DEPS := obj/make.dep
.DEFAULT_GOAL := all
include filelist.mk
SYS := $(shell $(CXX) -dumpmachine)
USE_AESNI := yes
USE_AVX := yes
USE_STATIC := no
USE_MESHNET := no
USE_UPNP := no
ifeq ($(WEBSOCKETS),1)
NEEDED_CXXFLAGS += -DWITH_EVENTS
DAEMON_SRC += Websocket.cpp
ifneq (, $(findstring darwin, $(SYS)))
SHARED_SUFFIX = dylib
else ifneq (, $(findstring mingw, $(SYS))$(findstring windows-gnu, $(SYS))$(findstring cygwin, $(SYS)))
SHARED_SUFFIX = dll
else
SHARED_SUFFIX = so
endif
ifeq ($(UNAME),Darwin)
DAEMON_SRC += DaemonLinux.cpp
SHLIB := libi2pd.$(SHARED_SUFFIX)
ARLIB := libi2pd.a
SHLIB_CLIENT := libi2pdclient.$(SHARED_SUFFIX)
ARLIB_CLIENT := libi2pdclient.a
SHLIB_LANG := libi2pdlang.$(SHARED_SUFFIX)
ARLIB_LANG := libi2pdlang.a
SHLIB_WEBCONSOLE := libi2pdwebconsole.$(SHARED_SUFFIX)
ARLIB_WEBCONSOLE := libi2pdwebconsole.a
SHLIB_WRAP := libi2pdwrapper.$(SHARED_SUFFIX)
ARLIB_WRAP := libi2pdwrapper.a
I2PD := i2pd
LIB_SRC_DIR := libi2pd
LIB_CLIENT_SRC_DIR := libi2pd_client
WEBCONSOLE_SRC_DIR := libi2pd_webconsole
LANG_SRC_DIR := i18n
DAEMON_SRC_DIR := daemon
WRAP_SRC_DIR := libi2pd_wrapper
# import source files lists
include filelist.mk
USE_AESNI := $(or $(USE_AESNI),yes)
USE_STATIC := $(or $(USE_STATIC),no)
USE_UPNP := $(or $(USE_UPNP),no)
DEBUG := $(or $(DEBUG),yes)
# for debugging purposes only, when commit hash needed in trunk builds in i2pd version string
USE_GIT_VERSION := $(or $(USE_GIT_VERSION),no)
# for MacOS only, waiting for "1", not "yes"
HOMEBREW := $(or $(HOMEBREW),0)
ifeq ($(DEBUG),yes)
CXX_DEBUG = -g
else
CXX_DEBUG = -Os
LD_DEBUG = -s
endif
ifneq (, $(findstring darwin, $(SYS)))
DAEMON_SRC += $(DAEMON_SRC_DIR)/DaemonUnix.cpp
ifeq ($(HOMEBREW),1)
include Makefile.homebrew
else
include Makefile.osx
endif
else ifeq ($(shell echo $(UNAME) | $(GREP) -Ec '(Free|Open)BSD'),1)
DAEMON_SRC += DaemonLinux.cpp
include Makefile.bsd
else ifeq ($(UNAME),Linux)
DAEMON_SRC += DaemonLinux.cpp
else ifneq (, $(findstring linux, $(SYS))$(findstring gnu, $(SYS)))
DAEMON_SRC += $(DAEMON_SRC_DIR)/DaemonUnix.cpp
include Makefile.linux
else # win32 mingw
DAEMON_SRC += DaemonWin32.cpp Win32/Win32Service.cpp Win32/Win32App.cpp
else ifneq (, $(findstring freebsd, $(SYS))$(findstring openbsd, $(SYS)))
DAEMON_SRC += $(DAEMON_SRC_DIR)/DaemonUnix.cpp
include Makefile.bsd
else ifneq (, $(findstring mingw, $(SYS))$(findstring windows-gnu, $(SYS))$(findstring cygwin, $(SYS)))
DAEMON_SRC += $(DAEMON_SRC_DIR)/DaemonWin32.cpp Win32/Win32App.cpp Win32/Win32Service.cpp Win32/Win32NetState.cpp
include Makefile.mingw
else # not supported
$(error Not supported platform)
endif
ifeq ($(USE_MESHNET),yes)
NEEDED_CXXFLAGS += -DMESHNET
ifeq ($(USE_GIT_VERSION),yes)
GIT_VERSION := $(shell git describe --tags)
NEEDED_CXXFLAGS += -DGITVER=\"$(GIT_VERSION)\"
endif
all: mk_obj_dir $(ARLIB) $(ARLIB_CLIENT) $(I2PD)
NEEDED_CXXFLAGS += -MMD -MP -I$(LIB_SRC_DIR) -I$(LIB_CLIENT_SRC_DIR) -I$(LANG_SRC_DIR) -I$(WEBCONSOLE_SRC_DIR) -DOPENSSL_SUPPRESS_DEPRECATED
LIB_OBJS += $(patsubst %.cpp,obj/%.o,$(LIB_SRC))
LIB_CLIENT_OBJS += $(patsubst %.cpp,obj/%.o,$(LIB_CLIENT_SRC))
LANG_OBJS += $(patsubst %.cpp,obj/%.o,$(LANG_SRC))
WEBCONSOLE_OBJS += $(patsubst %.cpp,obj/%.o,$(WEBCONSOLE_SRC))
DAEMON_OBJS += $(patsubst %.cpp,obj/%.o,$(DAEMON_SRC))
WRAP_LIB_OBJS += $(patsubst %.cpp,obj/%.o,$(WRAP_LIB_SRC))
DEPS += $(LIB_OBJS:.o=.d) $(LIB_CLIENT_OBJS:.o=.d) $(LANG_OBJS:.o=.d) $(WEBCONSOLE_OBJS:.o=.d) $(DAEMON_OBJS:.o=.d) $(WRAP_LIB_OBJS:.o=.d)
## Build all code (libi2pd, libi2pdclient, libi2pdlang), link it to .a and build binary
all: $(ARLIB) $(ARLIB_CLIENT) $(ARLIB_LANG) $(ARLIB_WEBCONSOLE) $(I2PD)
mk_obj_dir:
@mkdir -p obj
@mkdir -p obj/$(LIB_SRC_DIR)
@mkdir -p obj/$(LIB_CLIENT_SRC_DIR)
@mkdir -p obj/$(LANG_SRC_DIR)
@mkdir -p obj/$(WEBCONSOLE_SRC_DIR)
@mkdir -p obj/$(DAEMON_SRC_DIR)
@mkdir -p obj/$(WRAP_SRC_DIR)
@mkdir -p obj/Win32
api: mk_obj_dir $(SHLIB) $(ARLIB)
api_client: mk_obj_dir $(SHLIB) $(ARLIB) $(SHLIB_CLIENT) $(ARLIB_CLIENT)
api: $(SHLIB) $(ARLIB)
client: $(SHLIB_CLIENT) $(ARLIB_CLIENT)
lang: $(SHLIB_LANG) $(ARLIB_LANG)
webconsole: $(SHLIB_WEBCONSOLE) $(ARLIB_WEBCONSOLE)
api_client: api client lang webconsole
wrapper: api_client $(SHLIB_WRAP) $(ARLIB_WRAP)
## NOTE: The NEEDED_CXXFLAGS are here so that CXXFLAGS can be specified at build time
## **without** overwriting the CXXFLAGS which we need in order to build.
@ -58,40 +111,61 @@ api_client: mk_obj_dir $(SHLIB) $(ARLIB) $(SHLIB_CLIENT) $(ARLIB_CLIENT)
## -std=c++11. If you want to remove this variable please do so in a way that allows setting
## custom FLAGS to work at build-time.
deps: mk_obj_dir
$(CXX) $(CXXFLAGS) $(NEEDED_CXXFLAGS) -MM *.cpp > $(DEPS)
@sed -i -e '/\.o:/ s/^/obj\//' $(DEPS)
obj/%.o: %.cpp
$(CXX) $(CXXFLAGS) $(NEEDED_CXXFLAGS) $(INCFLAGS) $(CPU_FLAGS) -c -o $@ $<
obj/%.o: %.cpp | mk_obj_dir
$(CXX) $(CXXFLAGS) $(NEEDED_CXXFLAGS) $(INCFLAGS) -c -o $@ $<
# '-' is 'ignore if missing' on first run
-include $(DEPS)
DAEMON_OBJS += $(patsubst %.cpp,obj/%.o,$(DAEMON_SRC))
$(I2PD): $(DAEMON_OBJS) $(ARLIB) $(ARLIB_CLIENT)
$(CXX) -o $@ $^ $(LDLIBS) $(LDFLAGS)
$(I2PD): $(DAEMON_OBJS) $(ARLIB_WEBCONSOLE) $(ARLIB) $(ARLIB_CLIENT) $(ARLIB_LANG)
$(CXX) -o $@ $(LDFLAGS) $^ $(LDLIBS)
$(SHLIB): $(patsubst %.cpp,obj/%.o,$(LIB_SRC))
$(SHLIB): $(LIB_OBJS) $(SHLIB_LANG)
ifneq ($(USE_STATIC),yes)
$(CXX) $(LDFLAGS) $(LDLIBS) -shared -o $@ $^
$(CXX) $(LDFLAGS) -shared -o $@ $^ $(LDLIBS) $(SHLIB_LANG)
endif
$(SHLIB_CLIENT): $(patsubst %.cpp,obj/%.o,$(LIB_CLIENT_SRC))
$(CXX) $(LDFLAGS) $(LDLIBS) -shared -o $@ $^
$(SHLIB_CLIENT): $(LIB_CLIENT_OBJS) $(SHLIB) $(SHLIB_LANG)
ifneq ($(USE_STATIC),yes)
$(CXX) $(LDFLAGS) -shared -o $@ $^ $(LDLIBS) $(SHLIB) $(SHLIB_LANG)
endif
$(ARLIB): $(patsubst %.cpp,obj/%.o,$(LIB_SRC))
ar -r $@ $^
$(SHLIB_LANG): $(LANG_OBJS)
ifneq ($(USE_STATIC),yes)
$(CXX) $(LDFLAGS) -shared -o $@ $^ $(LDLIBS)
endif
$(ARLIB_CLIENT): $(patsubst %.cpp,obj/%.o,$(LIB_CLIENT_SRC))
ar -r $@ $^
$(SHLIB_WEBCONSOLE): $(WEBCONSOLE_OBJS) $(SHLIB) $(SHLIB_CLIENT) $(SHLIB_LANG)
ifneq ($(USE_STATIC),yes)
$(CXX) $(LDFLAGS) -shared -o $@ $^ $(LDLIBS) $(SHLIB) $(SHLIB_CLIENT) $(SHLIB_LANG)
endif
$(SHLIB_WRAP): $(WRAP_LIB_OBJS)
ifneq ($(USE_STATIC),yes)
$(CXX) $(LDFLAGS) -shared -o $@ $^ $(LDLIBS)
endif
$(ARLIB): $(LIB_OBJS)
$(AR) -r $@ $^
$(ARLIB_CLIENT): $(LIB_CLIENT_OBJS)
$(AR) -r $@ $^
$(ARLIB_LANG): $(LANG_OBJS)
$(AR) -r $@ $^
$(ARLIB_WEBCONSOLE): $(WEBCONSOLE_OBJS)
$(AR) -r $@ $^
$(ARLIB_WRAP): $(WRAP_LIB_OBJS)
$(AR) -r $@ $^
clean:
rm -rf obj
rm -rf docs/generated
$(RM) $(I2PD) $(SHLIB) $(ARLIB) $(SHLIB_CLIENT) $(ARLIB_CLIENT)
$(RM) -r obj
$(RM) -r docs/generated
$(RM) $(I2PD) $(SHLIB) $(ARLIB) $(SHLIB_CLIENT) $(ARLIB_CLIENT) $(SHLIB_LANG) $(ARLIB_LANG) $(SHLIB_WEBCONSOLE) $(ARLIB_WEBCONSOLE) $(SHLIB_WRAP) $(ARLIB_WRAP)
strip: $(I2PD) $(SHLIB_CLIENT) $(SHLIB)
strip: $(I2PD) $(SHLIB) $(SHLIB_CLIENT) $(SHLIB_LANG) $(SHLIB_WEBCONSOLE)
strip $^
LATEST_TAG=$(shell git describe --tags --abbrev=0 openssl)
@ -109,9 +183,13 @@ doxygen:
.PHONY: all
.PHONY: clean
.PHONY: deps
.PHONY: doxygen
.PHONY: dist
.PHONY: last-dist
.PHONY: api
.PHONY: api_client
.PHONY: client
.PHONY: lang
.PHONY: mk_obj_dir
.PHONY: install
.PHONY: strip

View File

@ -1,5 +1,5 @@
CXX = clang++
CXXFLAGS = -O2
CXXFLAGS ?= ${CXX_DEBUG} -Wall -Wextra -Wno-unused-parameter -pedantic -Wno-misleading-indentation
## NOTE: NEEDED_CXXFLAGS is here so that custom CXXFLAGS can be specified at build time
## **without** overwriting the CXXFLAGS which we need in order to build.
## For example, when adding 'hardening flags' to the build
@ -8,5 +8,5 @@ CXXFLAGS = -O2
## custom FLAGS to work at build-time.
NEEDED_CXXFLAGS = -std=c++11 -D_GLIBCXX_USE_NANOSLEEP=1
INCFLAGS = -I/usr/include/ -I/usr/local/include/
LDFLAGS = -Wl,-rpath,/usr/local/lib -L/usr/local/lib
LDFLAGS = ${LD_DEBUG} -Wl,-rpath,/usr/local/lib -L/usr/local/lib
LDLIBS = -lcrypto -lssl -lz -lboost_system -lboost_date_time -lboost_filesystem -lboost_program_options -lpthread

View File

@ -1,29 +1,52 @@
# root directory holding homebrew
BREWROOT = /usr/local/
BREWROOT = /usr/local
BOOSTROOT = ${BREWROOT}/opt/boost
SSLROOT = ${BREWROOT}/opt/libressl
CXX = clang++
CXXFLAGS = -g -Wall -std=c++11 -DMAC_OSX
SSLROOT = ${BREWROOT}/opt/openssl@1.1
UPNPROOT = ${BREWROOT}/opt/miniupnpc
CXXFLAGS = ${CXX_DEBUG} -Wall -std=c++11 -DMAC_OSX -Wno-overloaded-virtual
INCFLAGS = -I${SSLROOT}/include -I${BOOSTROOT}/include
LDFLAGS = -L${SSLROOT}/lib -L${BOOSTROOT}/lib
LDLIBS = -lz -lcrypto -lssl -lboost_system -lboost_date_time -lboost_filesystem -lboost_program_options -lpthread
LDFLAGS = ${LD_DEBUG}
ifndef TRAVIS
CXX = clang++
endif
ifeq ($(USE_STATIC),yes)
LDLIBS = -lz ${SSLROOT}/lib/libcrypto.a ${SSLROOT}/lib/libssl.a ${BOOSTROOT}/lib/libboost_system.a ${BOOSTROOT}/lib/libboost_date_time.a ${BOOSTROOT}/lib/libboost_filesystem.a ${BOOSTROOT}/lib/libboost_program_options.a -lpthread
else
LDFLAGS += -L${SSLROOT}/lib -L${BOOSTROOT}/lib
LDLIBS = -lz -lcrypto -lssl -lboost_system -lboost_date_time -lboost_filesystem -lboost_program_options -lpthread
endif
ifeq ($(USE_UPNP),yes)
LDFLAGS += -ldl
CXXFLAGS += -DUSE_UPNP
LDFLAGS += -ldl
CXXFLAGS += -DUSE_UPNP
INCFLAGS += -I${UPNPROOT}/include
ifeq ($(USE_STATIC),yes)
LDLIBS += ${UPNPROOT}/lib/libminiupnpc.a
else
LDFLAGS += -L${UPNPROOT}/lib
LDLIBS += -lminiupnpc
endif
endif
# OSX Notes
# http://www.hutsby.net/2011/08/macs-with-aes-ni.html
# Seems like all recent Mac's have AES-NI, after firmware upgrade 2.2
# Found no good way to detect it from command line. TODO: Might be some osx sysinfo magic
# note from psi: 2009 macbook does not have aesni
#ifeq ($(USE_AESNI),yes)
# CXXFLAGS += -maes -DAESNI
#endif
ifeq ($(USE_AESNI),yes)
CXXFLAGS += -D__AES__ -maes
endif
# Disabled, since it will be the default make rule. I think its better
# to define the default rule in Makefile and not Makefile.<ostype> - torkel
#install: all
# test -d ${PREFIX} || mkdir -p ${PREFIX}/
# cp -r i2p ${PREFIX}/
install: all
install -d ${PREFIX}/bin ${PREFIX}/etc/i2pd ${PREFIX}/etc/i2pd/tunnels.conf.d ${PREFIX}/share/doc/i2pd ${PREFIX}/share/i2pd ${PREFIX}/share/man/man1 ${PREFIX}/var/lib/i2pd
install -m 755 ${I2PD} ${PREFIX}/bin/
install -m 644 contrib/i2pd.conf contrib/subscriptions.txt contrib/tunnels.conf ${PREFIX}/etc/i2pd
@cp -R contrib/certificates ${PREFIX}/share/i2pd/
install -m 644 ChangeLog LICENSE README.md contrib/i2pd.conf contrib/subscriptions.txt contrib/tunnels.conf ${PREFIX}/share/doc/i2pd
@gzip -kf debian/i2pd.1 && install debian/i2pd.1.gz ${PREFIX}/share/man/man1
@ln -sf ${PREFIX}/share/i2pd/certificates ${PREFIX}/var/lib/i2pd/
@ln -sf ${PREFIX}/etc/i2pd/tunnels.conf.d ${PREFIX}/var/lib/i2pd/tunnels.d
@ln -sf ${PREFIX}/etc/i2pd/i2pd.conf ${PREFIX}/var/lib/i2pd/i2pd.conf
@ln -sf ${PREFIX}/etc/i2pd/subscriptions.txt ${PREFIX}/var/lib/i2pd/subscriptions.txt
@ln -sf ${PREFIX}/etc/i2pd/tunnels.conf ${PREFIX}/var/lib/i2pd/tunnels.conf

View File

@ -1,13 +1,13 @@
# set defaults instead redefine
CXXFLAGS ?= -g -Wall -Wextra -Wno-unused-parameter -pedantic -Wno-misleading-indentation
INCFLAGS ?=
CXXFLAGS ?= ${CXX_DEBUG} -Wall -Wextra -Wno-unused-parameter -pedantic -Wno-psabi
LDFLAGS ?= ${LD_DEBUG}
## NOTE: The NEEDED_CXXFLAGS are here so that custom CXXFLAGS can be specified at build time
## **without** overwriting the CXXFLAGS which we need in order to build.
## For example, when adding 'hardening flags' to the build
## (e.g. -fstack-protector-strong -Wformat -Werror=format-security), we do not want to remove
## -std=c++11. If you want to remove this variable please do so in a way that allows setting
## custom FLAGS to work at build-time.
## custom FDLAGS to work at build-time.
# detect proper flag for c++11 support by compilers
CXXVER := $(shell $(CXX) -dumpversion)
@ -15,14 +15,16 @@ ifeq ($(shell expr match $(CXX) 'clang'),5)
NEEDED_CXXFLAGS += -std=c++11
else ifeq ($(shell expr match ${CXXVER} "4\.[0-9][0-9]"),4) # gcc >= 4.10
NEEDED_CXXFLAGS += -std=c++11
else ifeq ($(shell expr match ${CXXVER} "4\.[7-9]"),3) # >= 4.7
else ifeq ($(shell expr match ${CXXVER} "4\.[8-9]"),3) # gcc 4.8 - 4.9
NEEDED_CXXFLAGS += -std=c++11 -D_GLIBCXX_USE_NANOSLEEP=1
else ifeq ($(shell expr match ${CXXVER} "4\.6"),3) # = 4.6
NEEDED_CXXFLAGS += -std=c++0x
else ifeq ($(shell expr match ${CXXVER} "[5-6]\.[0-9]"),3) # gcc >= 5.0
else ifeq ($(shell expr match ${CXXVER} "[5-6]"),1) # gcc 5 - 6
NEEDED_CXXFLAGS += -std=c++11
LDLIBS = -latomic
else ifeq ($(shell expr match ${CXXVER} "[1,7-9]"),1) # gcc >= 7
NEEDED_CXXFLAGS += -std=c++17
LDLIBS = -latomic
else # not supported
$(error Compiler too old)
$(error Compiler too old)
endif
NEEDED_CXXFLAGS += -fPIC
@ -31,43 +33,45 @@ ifeq ($(USE_STATIC),yes)
# NOTE: on glibc you will get this warning:
# Using 'getaddrinfo' in statically linked applications requires at runtime
# the shared libraries from the glibc version used for linking
LIBDIR := /usr/lib
LDLIBS = $(LIBDIR)/libboost_system.a
LDLIBS += $(LIBDIR)/libboost_date_time.a
LDLIBS += $(LIBDIR)/libboost_filesystem.a
LDLIBS += $(LIBDIR)/libboost_program_options.a
LDLIBS += $(LIBDIR)/libssl.a
LDLIBS += $(LIBDIR)/libcrypto.a
LDLIBS += $(LIBDIR)/libz.a
LDLIBS += -lpthread -static-libstdc++ -static-libgcc -lrt -ldl
USE_AESNI := no
LIBDIR := /usr/lib/$(SYS)
LDLIBS += $(LIBDIR)/libboost_system.a
LDLIBS += $(LIBDIR)/libboost_date_time.a
LDLIBS += $(LIBDIR)/libboost_filesystem.a
LDLIBS += $(LIBDIR)/libboost_program_options.a
LDLIBS += $(LIBDIR)/libssl.a
LDLIBS += $(LIBDIR)/libcrypto.a
LDLIBS += $(LIBDIR)/libz.a
ifeq ($(USE_UPNP),yes)
LDLIBS += $(LIBDIR)/libminiupnpc.a
endif
LDLIBS += -lpthread -ldl
else
LDLIBS = -lcrypto -lssl -lz -lboost_system -lboost_date_time -lboost_filesystem -lboost_program_options -lpthread
LDLIBS += -lcrypto -lssl -lz -lboost_system -lboost_date_time -lboost_filesystem -lboost_program_options -lpthread
ifeq ($(USE_UPNP),yes)
LDLIBS += -lminiupnpc
endif
endif
# UPNP Support (miniupnpc 1.5 and higher)
ifeq ($(USE_UPNP),yes)
CXXFLAGS += -DUSE_UPNP
ifeq ($(USE_STATIC),yes)
LDLIBS += $(LIBDIR)/libminiupnpc.a
else
LDLIBS += -lminiupnpc
endif
NEEDED_CXXFLAGS += -DUSE_UPNP
endif
IS_64 := $(shell $(CXX) -dumpmachine 2>&1 | $(GREP) -c "64")
ifeq ($(USE_AESNI),yes)
ifeq ($(IS_64),1)
#check if AES-NI is supported by CPU
ifneq ($(shell $(GREP) -c aes /proc/cpuinfo),0)
CPU_FLAGS += -maes -DAESNI
endif
ifneq (, $(findstring i386, $(SYS))$(findstring i686, $(SYS))$(findstring x86_64, $(SYS))) # only x86-based CPU supports that
NEEDED_CXXFLAGS += -D__AES__ -maes
endif
endif
ifeq ($(USE_AVX),yes)
#check if AVX supported by CPU
ifneq ($(shell $(GREP) -c avx /proc/cpuinfo),0)
CPU_FLAGS += -mavx
endif
endif
install: all
install -d ${PREFIX}/bin ${PREFIX}/etc ${PREFIX}/etc/i2pd ${PREFIX}/etc/i2pd/tunnels.conf.d ${PREFIX}/usr ${PREFIX}/usr/share ${PREFIX}/usr/share/doc/i2pd ${PREFIX}/usr/share/i2pd ${PREFIX}/usr/share/man ${PREFIX}/usr/share/man/man1 ${PREFIX}/var/lib ${PREFIX}/var/lib/i2pd
install -m 755 ${I2PD} ${PREFIX}/bin/
install -m 644 contrib/i2pd.conf contrib/subscriptions.txt contrib/tunnels.conf ${PREFIX}/etc/i2pd
@cp -R contrib/certificates ${PREFIX}/usr/share/i2pd/
install -m 644 ChangeLog LICENSE README.md contrib/i2pd.conf contrib/subscriptions.txt contrib/tunnels.conf ${PREFIX}/usr/share/doc/i2pd
@gzip -kf debian/i2pd.1 && install debian/i2pd.1.gz ${PREFIX}/usr/share/man/man1
@ln -sf ${PREFIX}/usr/share/i2pd/certificates ${PREFIX}/var/lib/i2pd/
@ln -sf ${PREFIX}/etc/i2pd/tunnels.conf.d ${PREFIX}/var/lib/i2pd/tunnels.d
@ln -sf ${PREFIX}/etc/i2pd/i2pd.conf ${PREFIX}/var/lib/i2pd/i2pd.conf
@ln -sf ${PREFIX}/etc/i2pd/subscriptions.txt ${PREFIX}/var/lib/i2pd/subscriptions.txt
@ln -sf ${PREFIX}/etc/i2pd/tunnels.conf ${PREFIX}/var/lib/i2pd/tunnels.conf

View File

@ -1,57 +1,57 @@
USE_WIN32_APP=yes
CXX = g++
WINDRES = windres
CXXFLAGS = -Os -D_MT -DWIN32 -D_WINDOWS -DWIN32_LEAN_AND_MEAN
NEEDED_CXXFLAGS = -std=c++11
BOOST_SUFFIX = -mt
INCFLAGS = -I/usr/include/ -I/usr/local/include/
LDFLAGS = -Wl,-rpath,/usr/local/lib \
-L/usr/local/lib
# UPNP Support
ifeq ($(USE_UPNP),yes)
CXXFLAGS += -DUSE_UPNP -DMINIUPNP_STATICLIB
LDLIBS = -Wl,-Bstatic -lminiupnpc
endif
LDLIBS += \
-Wl,-Bstatic -lboost_system$(BOOST_SUFFIX) \
-Wl,-Bstatic -lboost_date_time$(BOOST_SUFFIX) \
-Wl,-Bstatic -lboost_filesystem$(BOOST_SUFFIX) \
-Wl,-Bstatic -lboost_program_options$(BOOST_SUFFIX) \
-Wl,-Bstatic -lssl \
-Wl,-Bstatic -lcrypto \
-Wl,-Bstatic -lz \
-Wl,-Bstatic -lwsock32 \
-Wl,-Bstatic -lws2_32 \
-Wl,-Bstatic -lgdi32 \
-Wl,-Bstatic -liphlpapi \
-static-libgcc -static-libstdc++ \
-Wl,-Bstatic -lstdc++ \
-Wl,-Bstatic -lpthread
ifeq ($(USE_WIN32_APP), yes)
CXXFLAGS += -DWIN32_APP
LDFLAGS += -mwindows -s
DAEMON_RC += Win32/Resource.rc
DAEMON_OBJS += $(patsubst %.rc,obj/%.o,$(DAEMON_RC))
endif
# don't change following line to ifeq ($(USE_AESNI),yes) !!!
ifeq ($(USE_AESNI),1)
CPU_FLAGS += -maes -DAESNI
else
CPU_FLAGS += -msse
endif
ifeq ($(USE_AVX),1)
CPU_FLAGS += -mavx
endif
ifeq ($(USE_ASLR),yes)
LDFLAGS += -Wl,--nxcompat -Wl,--high-entropy-va \
-Wl,--dynamicbase,--export-all-symbols
endif
obj/%.o : %.rc
$(WINDRES) -i $< -o $@
# Build application with GUI (tray, main window)
USE_WIN32_APP := yes
WINDRES = windres
CXXFLAGS := $(CXX_DEBUG) -fPIC -msse
INCFLAGS = -IWin32
LDFLAGS := ${LD_DEBUG} -static
NEEDED_CXXFLAGS += -std=c++17 -DWIN32_LEAN_AND_MEAN
# Boost libraries suffix
BOOST_SUFFIX = -mt
# UPNP Support
ifeq ($(USE_UPNP),yes)
CXXFLAGS += -DUSE_UPNP -DMINIUPNP_STATICLIB
LDLIBS = -lminiupnpc
endif
LDLIBS += \
-lboost_system$(BOOST_SUFFIX) \
-lboost_date_time$(BOOST_SUFFIX) \
-lboost_filesystem$(BOOST_SUFFIX) \
-lboost_program_options$(BOOST_SUFFIX) \
-lssl \
-lcrypto \
-lz \
-lwsock32 \
-lws2_32 \
-lgdi32 \
-liphlpapi \
-lole32 \
-luuid \
-lpthread
ifeq ($(USE_WIN32_APP), yes)
NEEDED_CXXFLAGS += -DWIN32_APP
LDFLAGS += -mwindows
DAEMON_RC += Win32/Resource.rc
DAEMON_OBJS += $(patsubst %.rc,obj/%.o,$(DAEMON_RC))
endif
ifeq ($(USE_WINXP_FLAGS), yes)
NEEDED_CXXFLAGS += -DWINVER=0x0501 -D_WIN32_WINNT=0x0501
endif
ifeq ($(USE_AESNI),yes)
NEEDED_CXXFLAGS += -D__AES__ -maes
endif
ifeq ($(USE_ASLR),yes)
LDFLAGS += -Wl,--nxcompat -Wl,--high-entropy-va -Wl,--dynamicbase,--export-all-symbols
endif
obj/%.o : %.rc | mk_obj_dir
$(WINDRES) -i $< -o $@

View File

@ -1,32 +1,29 @@
CXX = clang++
CXXFLAGS = -Os -Wall -std=c++11 -DMAC_OSX
#CXXFLAGS = -g -O2 -Wall -std=c++11
INCFLAGS = -I/usr/local/include
LDFLAGS = -Wl,-rpath,/usr/local/lib -L/usr/local/lib
CXXFLAGS := ${CXX_DEBUG} -Wall -std=c++11 -DMAC_OSX
INCFLAGS = -I/usr/local/include
LDFLAGS := -Wl,-rpath,/usr/local/lib -L/usr/local/lib
LDFLAGS += -Wl,-dead_strip
LDFLAGS += -Wl,-dead_strip_dylibs
LDFLAGS += -Wl,-bind_at_load
ifeq ($(USE_STATIC),yes)
LDLIBS = -lz /usr/local/lib/libcrypto.a /usr/local/lib/libssl.a /usr/local/lib/libboost_system.a /usr/local/lib/libboost_date_time.a /usr/local/lib/libboost_filesystem.a /usr/local/lib/libboost_program_options.a -lpthread
LDLIBS = -lz /usr/local/lib/libcrypto.a /usr/local/lib/libssl.a /usr/local/lib/libboost_system.a /usr/local/lib/libboost_date_time.a /usr/local/lib/libboost_filesystem.a /usr/local/lib/libboost_program_options.a -lpthread
else
LDLIBS = -lz -lcrypto -lssl -lboost_system -lboost_date_time -lboost_filesystem -lboost_program_options -lpthread
LDLIBS = -lz -lcrypto -lssl -lboost_system -lboost_date_time -lboost_filesystem -lboost_program_options -lpthread
endif
ifeq ($(USE_UPNP),yes)
LDFLAGS += -ldl
CXXFLAGS += -DUSE_UPNP
LDFLAGS += -ldl
CXXFLAGS += -DUSE_UPNP
ifeq ($(USE_STATIC),yes)
LDLIBS += /usr/local/lib/libminiupnpc.a
else
LDLIBS += -lminiupnpc
endif
endif
ifeq ($(USE_AESNI),1)
CXXFLAGS += -maes -DAESNI
ifeq ($(USE_AESNI),yes)
CXXFLAGS += -D__AES__ -maes
else
CXXFLAGS += -msse
CXXFLAGS += -msse
endif
ifeq ($(USE_AVX),1)
CXXFLAGS += -mavx
endif
# Disabled, since it will be the default make rule. I think its better
# to define the default rule in Makefile and not Makefile.<ostype> - torkel
#install: all
# test -d ${PREFIX} || mkdir -p ${PREFIX}/
# cp -r i2p ${PREFIX}/

File diff suppressed because it is too large Load Diff

View File

@ -1,178 +0,0 @@
#ifndef NTCP_SESSION_H__
#define NTCP_SESSION_H__
#include <inttypes.h>
#include <map>
#include <memory>
#include <thread>
#include <mutex>
#include <boost/asio.hpp>
#include "Crypto.h"
#include "Identity.h"
#include "RouterInfo.h"
#include "I2NPProtocol.h"
#include "TransportSession.h"
namespace i2p
{
namespace transport
{
struct NTCPPhase1
{
uint8_t pubKey[256];
uint8_t HXxorHI[32];
};
struct NTCPPhase2
{
uint8_t pubKey[256];
struct
{
uint8_t hxy[32];
uint8_t timestamp[4];
uint8_t filler[12];
} encrypted;
};
const size_t NTCP_MAX_MESSAGE_SIZE = 16384;
const size_t NTCP_BUFFER_SIZE = 1028; // fits 1 tunnel data message
const int NTCP_CONNECT_TIMEOUT = 5; // 5 seconds
const int NTCP_TERMINATION_TIMEOUT = 120; // 2 minutes
const int NTCP_TERMINATION_CHECK_TIMEOUT = 30; // 30 seconds
const size_t NTCP_DEFAULT_PHASE3_SIZE = 2/*size*/ + i2p::data::DEFAULT_IDENTITY_SIZE/*387*/ + 4/*ts*/ + 15/*padding*/ + 40/*signature*/; // 448
const int NTCP_CLOCK_SKEW = 60; // in seconds
const int NTCP_MAX_OUTGOING_QUEUE_SIZE = 200; // how many messages we can queue up
class NTCPServer;
class NTCPSession: public TransportSession, public std::enable_shared_from_this<NTCPSession>
{
public:
NTCPSession (NTCPServer& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter = nullptr);
~NTCPSession ();
void Terminate ();
void Done ();
boost::asio::ip::tcp::socket& GetSocket () { return m_Socket; };
bool IsEstablished () const { return m_IsEstablished; };
void ClientLogin ();
void ServerLogin ();
void SendI2NPMessages (const std::vector<std::shared_ptr<I2NPMessage> >& msgs);
private:
void PostI2NPMessages (std::vector<std::shared_ptr<I2NPMessage> > msgs);
void Connected ();
void SendTimeSyncMessage ();
void SetIsEstablished (bool isEstablished) { m_IsEstablished = isEstablished; }
void CreateAESKey (uint8_t * pubKey);
// client
void SendPhase3 ();
void HandlePhase1Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
void HandlePhase2Received (const boost::system::error_code& ecode, std::size_t bytes_transferred);
void HandlePhase2 ();
void HandlePhase3Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsA);
void HandlePhase4Received (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsA);
//server
void SendPhase2 ();
void SendPhase4 (uint32_t tsA, uint32_t tsB);
void HandlePhase1Received (const boost::system::error_code& ecode, std::size_t bytes_transferred);
void HandlePhase2Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB);
void HandlePhase3Received (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB);
void HandlePhase3ExtraReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB, size_t paddingLen);
void HandlePhase3 (uint32_t tsB, size_t paddingLen);
void HandlePhase4Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
// common
void Receive ();
void HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
bool DecryptNextBlock (const uint8_t * encrypted);
void Send (std::shared_ptr<i2p::I2NPMessage> msg);
boost::asio::const_buffers_1 CreateMsgBuffer (std::shared_ptr<I2NPMessage> msg);
void Send (const std::vector<std::shared_ptr<I2NPMessage> >& msgs);
void HandleSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, std::vector<std::shared_ptr<I2NPMessage> > msgs);
private:
NTCPServer& m_Server;
boost::asio::ip::tcp::socket m_Socket;
bool m_IsEstablished, m_IsTerminated;
i2p::crypto::CBCDecryption m_Decryption;
i2p::crypto::CBCEncryption m_Encryption;
struct Establisher
{
NTCPPhase1 phase1;
NTCPPhase2 phase2;
} * m_Establisher;
i2p::crypto::AESAlignedBuffer<NTCP_BUFFER_SIZE + 16> m_ReceiveBuffer;
i2p::crypto::AESAlignedBuffer<16> m_TimeSyncBuffer;
int m_ReceiveBufferOffset;
std::shared_ptr<I2NPMessage> m_NextMessage;
size_t m_NextMessageOffset;
i2p::I2NPMessagesHandler m_Handler;
bool m_IsSending;
std::vector<std::shared_ptr<I2NPMessage> > m_SendQueue;
};
// TODO: move to NTCP.h/.cpp
class NTCPServer
{
public:
NTCPServer ();
~NTCPServer ();
void Start ();
void Stop ();
bool AddNTCPSession (std::shared_ptr<NTCPSession> session);
void RemoveNTCPSession (std::shared_ptr<NTCPSession> session);
std::shared_ptr<NTCPSession> FindNTCPSession (const i2p::data::IdentHash& ident);
void Connect (const boost::asio::ip::address& address, int port, std::shared_ptr<NTCPSession> conn);
bool IsBoundV4() const { return m_NTCPAcceptor != nullptr; };
bool IsBoundV6() const { return m_NTCPV6Acceptor != nullptr; };
boost::asio::io_service& GetService () { return m_Service; };
private:
void Run ();
void HandleAccept (std::shared_ptr<NTCPSession> conn, const boost::system::error_code& error);
void HandleAcceptV6 (std::shared_ptr<NTCPSession> conn, const boost::system::error_code& error);
void HandleConnect (const boost::system::error_code& ecode, std::shared_ptr<NTCPSession> conn, std::shared_ptr<boost::asio::deadline_timer> timer);
// timer
void ScheduleTermination ();
void HandleTerminationTimer (const boost::system::error_code& ecode);
private:
bool m_IsRunning;
std::thread * m_Thread;
boost::asio::io_service m_Service;
boost::asio::io_service::work m_Work;
boost::asio::deadline_timer m_TerminationTimer;
boost::asio::ip::tcp::acceptor * m_NTCPAcceptor, * m_NTCPV6Acceptor;
std::map<i2p::data::IdentHash, std::shared_ptr<NTCPSession> > m_NTCPSessions; // access from m_Thread only
public:
// for HTTP/I2PControl
const decltype(m_NTCPSessions)& GetNTCPSessions () const { return m_NTCPSessions; };
};
}
}
#endif

View File

@ -1,21 +1,41 @@
[![GitHub release](https://img.shields.io/github/release/PurpleI2P/i2pd.svg?label=latest%20release)](https://github.com/PurpleI2P/i2pd/releases/latest)
[![Snapcraft release](https://snapcraft.io/i2pd/badge.svg)](https://snapcraft.io/i2pd)
[![License](https://img.shields.io/github/license/PurpleI2P/i2pd.svg)](https://github.com/PurpleI2P/i2pd/blob/openssl/LICENSE)
[![Packaging status](https://repology.org/badge/tiny-repos/i2pd.svg)](https://repology.org/project/i2pd/versions)
[![Docker Pulls](https://img.shields.io/docker/pulls/purplei2p/i2pd)](https://hub.docker.com/r/purplei2p/i2pd)
[![Crowdin](https://badges.crowdin.net/i2pd/localized.svg)](https://crowdin.com/project/i2pd)
*note: i2pd for Android can be found in [i2pd-android](https://github.com/PurpleI2P/i2pd-android) repository and with Qt GUI in [i2pd-qt](https://github.com/PurpleI2P/i2pd-qt) repository*
i2pd
====
[Русская версия](https://github.com/PurpleI2P/i2pd_docs_ru/blob/master/README.md)
i2pd (I2P Daemon) is a full-featured C++ implementation of I2P client.
i2pd (I2P Daemon) is a full-featured C++ implementation of I2P client.
I2P (Invisible Internet Protocol) is a universal anonymous network layer.
I2P (Invisible Internet Protocol) is a universal anonymous network layer.
All communications over I2P are anonymous and end-to-end encrypted, participants
don't reveal their real IP addresses.
don't reveal their real IP addresses.
I2P client is a software used for building and using anonymous I2P
networks. Such networks are commonly used for anonymous peer-to-peer
applications (filesharing, cryptocurrencies) and anonymous client-server
applications (websites, instant messengers, chat-servers).
I2P client is a software used for building and using anonymous I2P
networks. Such networks are commonly used for anonymous peer-to-peer
applications (filesharing, cryptocurrencies) and anonymous client-server
applications (websites, instant messengers, chat-servers).
I2P allows people from all around the world to communicate and share information
without restrictions.
without restrictions.
Features
--------
* Distributed anonymous networking framework
* End-to-end encrypted communications
* Small footprint, simple dependencies, fast performance
* Rich set of APIs for developers of secure applications
Resources
---------
* [Website](http://i2pd.website)
* [Documentation](https://i2pd.readthedocs.io/en/latest/)
@ -27,37 +47,68 @@ without restrictions.
Installing
----------
The easiest way to install i2pd is by using
[precompiled binaries](https://github.com/PurpleI2P/i2pd/releases/latest).
See [documentation](https://i2pd.readthedocs.io/en/latest/) for how to build
i2pd from source on your OS.
The easiest way to install i2pd is by using precompiled packages and binaries.
You can fetch most of them on [release](https://github.com/PurpleI2P/i2pd/releases/latest) page.
Please see [documentation](https://i2pd.readthedocs.io/en/latest/user-guide/install/) for more info.
Building
--------
See [documentation](https://i2pd.readthedocs.io/en/latest/) for how to build
i2pd from source on your OS.
note: i2pd with Qt GUI can be found in [i2pd-qt](https://github.com/PurpleI2P/i2pd-qt) repository and for android in [i2pd-android](https://github.com/PurpleI2P/i2pd-android) repository.
Build instructions:
* [unix](https://i2pd.readthedocs.io/en/latest/devs/building/unix/)
* [windows](https://i2pd.readthedocs.io/en/latest/devs/building/windows/)
* [iOS](https://i2pd.readthedocs.io/en/latest/devs/building/ios/)
* [android](https://i2pd.readthedocs.io/en/latest/devs/building/android/)
**Supported systems:**
* Linux x86/x64 - [![Build Status](https://travis-ci.org/PurpleI2P/i2pd.svg?branch=openssl)](https://travis-ci.org/PurpleI2P/i2pd)
* Windows - [![Build status](https://ci.appveyor.com/api/projects/status/1908qe4p48ff1x23?svg=true)](https://ci.appveyor.com/project/PurpleI2P/i2pd)
* Mac OS X
* FreeBSD
* Android
* GNU/Linux - [![Build on Ubuntu](https://github.com/PurpleI2P/i2pd/actions/workflows/build.yml/badge.svg)](https://github.com/PurpleI2P/i2pd/actions/workflows/build.yml)
* CentOS / Fedora / Mageia - [![Build Status](https://copr.fedorainfracloud.org/coprs/supervillain/i2pd/package/i2pd-git/status_image/last_build.png)](https://copr.fedorainfracloud.org/coprs/supervillain/i2pd/package/i2pd-git/)
* Alpine, ArchLinux, openSUSE, Gentoo, Debian, Ubuntu, etc.
* Windows - [![Build on Windows](https://github.com/PurpleI2P/i2pd/actions/workflows/build-windows.yml/badge.svg)](https://github.com/PurpleI2P/i2pd/actions/workflows/build-windows.yml)
* Mac OS X - [![Build on OSX](https://github.com/PurpleI2P/i2pd/actions/workflows/build-osx.yml/badge.svg)](https://github.com/PurpleI2P/i2pd/actions/workflows/build-osx.yml)
* Docker image - [![Build Status](https://img.shields.io/docker/cloud/build/purplei2p/i2pd)](https://hub.docker.com/r/purplei2p/i2pd/builds/) [![Build containers](https://github.com/PurpleI2P/i2pd/actions/workflows/docker.yml/badge.svg)](https://github.com/PurpleI2P/i2pd/actions/workflows/docker.yml)
* Snap - [![i2pd](https://snapcraft.io/i2pd/badge.svg)](https://snapcraft.io/i2pd) [![i2pd](https://snapcraft.io/i2pd/trending.svg?name=0)](https://snapcraft.io/i2pd)
* FreeBSD - [![Build on FreeBSD](https://github.com/PurpleI2P/i2pd/actions/workflows/build-freebsd.yml/badge.svg)](https://github.com/PurpleI2P/i2pd/actions/workflows/build-freebsd.yml)
* Android - [![Android CI](https://github.com/PurpleI2P/i2pd-android/actions/workflows/android.yml/badge.svg)](https://github.com/PurpleI2P/i2pd-android/actions/workflows/android.yml)
* iOS
Using i2pd
----------
See [documentation](https://i2pd.readthedocs.io/en/latest/usage.html) and
[example config file](https://github.com/PurpleI2P/i2pd/blob/openssl/docs/i2pd.conf).
See [documentation](https://i2pd.readthedocs.io/en/latest/user-guide/run/) and
[example config file](https://github.com/PurpleI2P/i2pd/blob/openssl/contrib/i2pd.conf).
Localization
------------
You can help us with translation i2pd to your language using Crowdin platform!
Translation project can be found [here](https://crowdin.com/project/i2pd).
New languages can be requested on project's [discussion page](https://crowdin.com/project/i2pd/discussions).
Current status: [![Crowdin](https://badges.crowdin.net/i2pd/localized.svg)](https://crowdin.com/project/i2pd)
Donations
---------
BTC: 1K7Ds6KUeR8ya287UC4rYTjvC96vXyZbDY
DASH: Xw8YUrQpYzP9tZBmbjqxS3M97Q7v3vJKUF
BTC: 3MDoGJW9TLMTCDGrR9bLgWXfm6sjmgy86f
LTC: LKQirrYrDeTuAPnpYq5y7LVKtywfkkHi59
ANC: AQJYweYYUqM1nVfLqfoSMpUMfzxvS4Xd7z
DOGE: DNXLQKziRPAsD9H3DFNjk4fLQrdaSX893Y
ETH: 0x9e5bac70d20d1079ceaa111127f4fb3bccce379d
DASH: Xw8YUrQpYzP9tZBmbjqxS3M97Q7v3vJKUF
ZEC: t1cTckLuXsr1dwVrK4NDzfhehss4NvMadAJ
GST: GbD2JSQHBHCKLa9WTHmigJRpyFgmBj4woG
XMR: 497pJc7X4xqKvcLBLpSUtRgWqMMyo24u4btCos3cak6gbMkpobgSU6492ztUcUBghyeHpYeczB55s38NpuHoH5WGNSPDRMH
License
-------
This project is licensed under the BSD 3-clause license, which can be found in the file
LICENSE in the root of the project source code.
LICENSE in the root of the project source code.

View File

@ -1,567 +0,0 @@
#include <string.h>
#include <fstream>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/algorithm/string.hpp>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <zlib.h>
#include "Crypto.h"
#include "I2PEndian.h"
#include "Reseed.h"
#include "FS.h"
#include "Log.h"
#include "Identity.h"
#include "NetDb.h"
#include "HTTP.h"
#include "util.h"
#include "Config.h"
namespace i2p
{
namespace data
{
Reseeder::Reseeder()
{
}
Reseeder::~Reseeder()
{
}
/** @brief tries to bootstrap into I2P network (from local files and servers, with respect of options)
*/
void Reseeder::Bootstrap ()
{
std::string su3FileName; i2p::config::GetOption("reseed.file", su3FileName);
std::string zipFileName; i2p::config::GetOption("reseed.zipfile", zipFileName);
if (su3FileName.length() > 0) // bootstrap from SU3 file or URL
{
int num;
if (su3FileName.length() > 8 && su3FileName.substr(0, 8) == "https://")
{
num = ReseedFromSU3Url (su3FileName); // from https URL
}
else
{
num = ProcessSU3File (su3FileName.c_str ());
}
if (num == 0)
LogPrint (eLogWarning, "Reseed: failed to reseed from ", su3FileName);
}
else if (zipFileName.length() > 0) // bootstrap from ZIP file
{
int num = ProcessZIPFile (zipFileName.c_str ());
if (num == 0)
LogPrint (eLogWarning, "Reseed: failed to reseed from ", zipFileName);
}
else // bootstrap from reseed servers
{
int num = ReseedFromServers ();
if (num == 0)
LogPrint (eLogWarning, "Reseed: failed to reseed from servers");
}
}
/** @brief bootstrap from random server, retry 10 times
* @return number of entries added to netDb
*/
int Reseeder::ReseedFromServers ()
{
std::string reseedURLs; i2p::config::GetOption("reseed.urls", reseedURLs);
std::vector<std::string> httpsReseedHostList;
boost::split(httpsReseedHostList, reseedURLs, boost::is_any_of(","), boost::token_compress_on);
if (reseedURLs.length () == 0)
{
LogPrint (eLogWarning, "Reseed: No reseed servers specified");
return 0;
}
int reseedRetries = 0;
while (reseedRetries < 10)
{
auto ind = rand () % httpsReseedHostList.size ();
std::string reseedUrl = httpsReseedHostList[ind] + "i2pseeds.su3";
auto num = ReseedFromSU3Url (reseedUrl);
if (num > 0) return num; // success
reseedRetries++;
}
LogPrint (eLogWarning, "Reseed: failed to reseed from servers after 10 attempts");
return 0;
}
/** @brief bootstrap from HTTPS URL with SU3 file
* @param url
* @return number of entries added to netDb
*/
int Reseeder::ReseedFromSU3Url (const std::string& url)
{
LogPrint (eLogInfo, "Reseed: Downloading SU3 from ", url);
std::string su3 = HttpsRequest (url);
if (su3.length () > 0)
{
std::stringstream s(su3);
return ProcessSU3Stream (s);
}
else
{
LogPrint (eLogWarning, "Reseed: SU3 download failed");
return 0;
}
}
int Reseeder::ProcessSU3File (const char * filename)
{
std::ifstream s(filename, std::ifstream::binary);
if (s.is_open ())
return ProcessSU3Stream (s);
else
{
LogPrint (eLogError, "Reseed: Can't open file ", filename);
return 0;
}
}
int Reseeder::ProcessZIPFile (const char * filename)
{
std::ifstream s(filename, std::ifstream::binary);
if (s.is_open ())
{
s.seekg (0, std::ios::end);
auto len = s.tellg ();
s.seekg (0, std::ios::beg);
return ProcessZIPStream (s, len);
}
else
{
LogPrint (eLogError, "Reseed: Can't open file ", filename);
return 0;
}
}
const char SU3_MAGIC_NUMBER[]="I2Psu3";
int Reseeder::ProcessSU3Stream (std::istream& s)
{
char magicNumber[7];
s.read (magicNumber, 7); // magic number and zero byte 6
if (strcmp (magicNumber, SU3_MAGIC_NUMBER))
{
LogPrint (eLogError, "Reseed: Unexpected SU3 magic number");
return 0;
}
s.seekg (1, std::ios::cur); // su3 file format version
SigningKeyType signatureType;
s.read ((char *)&signatureType, 2); // signature type
signatureType = be16toh (signatureType);
uint16_t signatureLength;
s.read ((char *)&signatureLength, 2); // signature length
signatureLength = be16toh (signatureLength);
s.seekg (1, std::ios::cur); // unused
uint8_t versionLength;
s.read ((char *)&versionLength, 1); // version length
s.seekg (1, std::ios::cur); // unused
uint8_t signerIDLength;
s.read ((char *)&signerIDLength, 1); // signer ID length
uint64_t contentLength;
s.read ((char *)&contentLength, 8); // content length
contentLength = be64toh (contentLength);
s.seekg (1, std::ios::cur); // unused
uint8_t fileType;
s.read ((char *)&fileType, 1); // file type
if (fileType != 0x00) // zip file
{
LogPrint (eLogError, "Reseed: Can't handle file type ", (int)fileType);
return 0;
}
s.seekg (1, std::ios::cur); // unused
uint8_t contentType;
s.read ((char *)&contentType, 1); // content type
if (contentType != 0x03) // reseed data
{
LogPrint (eLogError, "Reseed: Unexpected content type ", (int)contentType);
return 0;
}
s.seekg (12, std::ios::cur); // unused
s.seekg (versionLength, std::ios::cur); // skip version
char signerID[256];
s.read (signerID, signerIDLength); // signerID
signerID[signerIDLength] = 0;
bool verify; i2p::config::GetOption("reseed.verify", verify);
if (verify)
{
//try to verify signature
auto it = m_SigningKeys.find (signerID);
if (it != m_SigningKeys.end ())
{
// TODO: implement all signature types
if (signatureType == SIGNING_KEY_TYPE_RSA_SHA512_4096)
{
size_t pos = s.tellg ();
size_t tbsLen = pos + contentLength;
uint8_t * tbs = new uint8_t[tbsLen];
s.seekg (0, std::ios::beg);
s.read ((char *)tbs, tbsLen);
uint8_t * signature = new uint8_t[signatureLength];
s.read ((char *)signature, signatureLength);
// RSA-raw
{
// calculate digest
uint8_t digest[64];
SHA512 (tbs, tbsLen, digest);
// encrypt signature
BN_CTX * bnctx = BN_CTX_new ();
BIGNUM * s = BN_new (), * n = BN_new ();
BN_bin2bn (signature, signatureLength, s);
BN_bin2bn (it->second, i2p::crypto::RSASHA5124096_KEY_LENGTH, n);
BN_mod_exp (s, s, i2p::crypto::GetRSAE (), n, bnctx); // s = s^e mod n
uint8_t * enSigBuf = new uint8_t[signatureLength];
i2p::crypto::bn2buf (s, enSigBuf, signatureLength);
// digest is right aligned
// we can't use RSA_verify due wrong padding in SU3
if (memcmp (enSigBuf + (signatureLength - 64), digest, 64))
LogPrint (eLogWarning, "Reseed: SU3 signature verification failed");
else
verify = false; // verified
delete[] enSigBuf;
BN_free (s); BN_free (n);
BN_CTX_free (bnctx);
}
delete[] signature;
delete[] tbs;
s.seekg (pos, std::ios::beg);
}
else
LogPrint (eLogWarning, "Reseed: Signature type ", signatureType, " is not supported");
}
else
LogPrint (eLogWarning, "Reseed: Certificate for ", signerID, " not loaded");
}
if (verify) // not verified
{
LogPrint (eLogError, "Reseed: SU3 verification failed");
return 0;
}
// handle content
return ProcessZIPStream (s, contentLength);
}
const uint32_t ZIP_HEADER_SIGNATURE = 0x04034B50;
const uint32_t ZIP_CENTRAL_DIRECTORY_HEADER_SIGNATURE = 0x02014B50;
const uint16_t ZIP_BIT_FLAG_DATA_DESCRIPTOR = 0x0008;
int Reseeder::ProcessZIPStream (std::istream& s, uint64_t contentLength)
{
int numFiles = 0;
size_t contentPos = s.tellg ();
while (!s.eof ())
{
uint32_t signature;
s.read ((char *)&signature, 4);
signature = le32toh (signature);
if (signature == ZIP_HEADER_SIGNATURE)
{
// next local file
s.seekg (2, std::ios::cur); // version
uint16_t bitFlag;
s.read ((char *)&bitFlag, 2);
bitFlag = le16toh (bitFlag);
uint16_t compressionMethod;
s.read ((char *)&compressionMethod, 2);
compressionMethod = le16toh (compressionMethod);
s.seekg (4, std::ios::cur); // skip fields we don't care about
uint32_t compressedSize, uncompressedSize;
uint32_t crc_32;
s.read ((char *)&crc_32, 4);
crc_32 = le32toh (crc_32);
s.read ((char *)&compressedSize, 4);
compressedSize = le32toh (compressedSize);
s.read ((char *)&uncompressedSize, 4);
uncompressedSize = le32toh (uncompressedSize);
uint16_t fileNameLength, extraFieldLength;
s.read ((char *)&fileNameLength, 2);
fileNameLength = le16toh (fileNameLength);
if ( fileNameLength > 255 ) {
// too big
LogPrint(eLogError, "Reseed: SU3 fileNameLength too large: ", fileNameLength);
return numFiles;
}
s.read ((char *)&extraFieldLength, 2);
extraFieldLength = le16toh (extraFieldLength);
char localFileName[255];
s.read (localFileName, fileNameLength);
localFileName[fileNameLength] = 0;
s.seekg (extraFieldLength, std::ios::cur);
// take care about data desriptor if presented
if (bitFlag & ZIP_BIT_FLAG_DATA_DESCRIPTOR)
{
size_t pos = s.tellg ();
if (!FindZipDataDescriptor (s))
{
LogPrint (eLogError, "Reseed: SU3 archive data descriptor not found");
return numFiles;
}
s.read ((char *)&crc_32, 4);
crc_32 = le32toh (crc_32);
s.read ((char *)&compressedSize, 4);
compressedSize = le32toh (compressedSize) + 4; // ??? we must consider signature as part of compressed data
s.read ((char *)&uncompressedSize, 4);
uncompressedSize = le32toh (uncompressedSize);
// now we know compressed and uncompressed size
s.seekg (pos, std::ios::beg); // back to compressed data
}
LogPrint (eLogDebug, "Reseed: Proccessing file ", localFileName, " ", compressedSize, " bytes");
if (!compressedSize)
{
LogPrint (eLogWarning, "Reseed: Unexpected size 0. Skipped");
continue;
}
uint8_t * compressed = new uint8_t[compressedSize];
s.read ((char *)compressed, compressedSize);
if (compressionMethod) // we assume Deflate
{
z_stream inflator;
memset (&inflator, 0, sizeof (inflator));
inflateInit2 (&inflator, -MAX_WBITS); // no zlib header
uint8_t * uncompressed = new uint8_t[uncompressedSize];
inflator.next_in = compressed;
inflator.avail_in = compressedSize;
inflator.next_out = uncompressed;
inflator.avail_out = uncompressedSize;
int err;
if ((err = inflate (&inflator, Z_SYNC_FLUSH)) >= 0)
{
uncompressedSize -= inflator.avail_out;
if (crc32 (0, uncompressed, uncompressedSize) == crc_32)
{
i2p::data::netdb.AddRouterInfo (uncompressed, uncompressedSize);
numFiles++;
}
else
LogPrint (eLogError, "Reseed: CRC32 verification failed");
}
else
LogPrint (eLogError, "Reseed: SU3 decompression error ", err);
delete[] uncompressed;
inflateEnd (&inflator);
}
else // no compression
{
i2p::data::netdb.AddRouterInfo (compressed, compressedSize);
numFiles++;
}
delete[] compressed;
if (bitFlag & ZIP_BIT_FLAG_DATA_DESCRIPTOR)
s.seekg (12, std::ios::cur); // skip data descriptor section if presented (12 = 16 - 4)
}
else
{
if (signature != ZIP_CENTRAL_DIRECTORY_HEADER_SIGNATURE)
LogPrint (eLogWarning, "Reseed: Missing zip central directory header");
break; // no more files
}
size_t end = s.tellg ();
if (end - contentPos >= contentLength)
break; // we are beyond contentLength
}
if (numFiles) // check if routers are not outdated
{
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
int numOutdated = 0;
i2p::data::netdb.VisitRouterInfos (
[&numOutdated, ts](std::shared_ptr<const RouterInfo> r)
{
if (r && ts > r->GetTimestamp () + 10*i2p::data::NETDB_MAX_EXPIRATION_TIMEOUT*1000LL) // 270 hours
{
LogPrint (eLogError, "Reseed: router ", r->GetIdentHash().ToBase64 (), " is outdated by ", (ts - r->GetTimestamp ())/1000LL/3600LL, " hours");
numOutdated++;
}
});
if (numOutdated > numFiles/2) // more than half
{
LogPrint (eLogError, "Reseed: mammoth's shit\n"
" *_____*\n"
" *_*****_*\n"
" *_(O)_(O)_*\n"
" **____V____**\n"
" **_________**\n"
" **_________**\n"
" *_________*\n"
" ***___***");
i2p::data::netdb.ClearRouterInfos ();
numFiles = 0;
}
}
return numFiles;
}
const uint8_t ZIP_DATA_DESCRIPTOR_SIGNATURE[] = { 0x50, 0x4B, 0x07, 0x08 };
bool Reseeder::FindZipDataDescriptor (std::istream& s)
{
size_t nextInd = 0;
while (!s.eof ())
{
uint8_t nextByte;
s.read ((char *)&nextByte, 1);
if (nextByte == ZIP_DATA_DESCRIPTOR_SIGNATURE[nextInd])
{
nextInd++;
if (nextInd >= sizeof (ZIP_DATA_DESCRIPTOR_SIGNATURE))
return true;
}
else
nextInd = 0;
}
return false;
}
void Reseeder::LoadCertificate (const std::string& filename)
{
SSL_CTX * ctx = SSL_CTX_new (TLS_method ());
int ret = SSL_CTX_use_certificate_file (ctx, filename.c_str (), SSL_FILETYPE_PEM);
if (ret)
{
SSL * ssl = SSL_new (ctx);
X509 * cert = SSL_get_certificate (ssl);
// verify
if (cert)
{
// extract issuer name
char name[100];
X509_NAME_oneline (X509_get_issuer_name(cert), name, 100);
char * cn = strstr (name, "CN=");
if (cn)
{
cn += 3;
char * terminator = strchr (cn, '/');
if (terminator) terminator[0] = 0;
}
// extract RSA key (we need n only, e = 65537)
RSA * key = EVP_PKEY_get0_RSA (X509_get_pubkey (cert));
const BIGNUM * n, * e, * d;
RSA_get0_key(key, &n, &e, &d);
PublicKey value;
i2p::crypto::bn2buf (n, value, 512);
if (cn)
m_SigningKeys[cn] = value;
else
LogPrint (eLogError, "Reseed: Can't find CN field in ", filename);
}
SSL_free (ssl);
}
else
LogPrint (eLogError, "Reseed: Can't open certificate file ", filename);
SSL_CTX_free (ctx);
}
void Reseeder::LoadCertificates ()
{
std::string certDir = i2p::fs::DataDirPath("certificates", "reseed");
std::vector<std::string> files;
int numCertificates = 0;
if (!i2p::fs::ReadDir(certDir, files)) {
LogPrint(eLogWarning, "Reseed: Can't load reseed certificates from ", certDir);
return;
}
for (const std::string & file : files) {
if (file.compare(file.size() - 4, 4, ".crt") != 0) {
LogPrint(eLogWarning, "Reseed: ignoring file ", file);
continue;
}
LoadCertificate (file);
numCertificates++;
}
LogPrint (eLogInfo, "Reseed: ", numCertificates, " certificates loaded");
}
std::string Reseeder::HttpsRequest (const std::string& address)
{
i2p::http::URL url;
if (!url.parse(address)) {
LogPrint(eLogError, "Reseed: failed to parse url: ", address);
return "";
}
url.schema = "https";
if (!url.port)
url.port = 443;
boost::asio::io_service service;
boost::system::error_code ecode;
auto it = boost::asio::ip::tcp::resolver(service).resolve (
boost::asio::ip::tcp::resolver::query (url.host, std::to_string(url.port)), ecode);
if (!ecode)
{
boost::asio::ssl::context ctx(service, boost::asio::ssl::context::sslv23);
ctx.set_verify_mode(boost::asio::ssl::context::verify_none);
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> s(service, ctx);
s.lowest_layer().connect (*it, ecode);
if (!ecode)
{
SSL_set_tlsext_host_name(s.native_handle(), url.host.c_str ());
s.handshake (boost::asio::ssl::stream_base::client, ecode);
if (!ecode)
{
LogPrint (eLogDebug, "Reseed: Connected to ", url.host, ":", url.port);
i2p::http::HTTPReq req;
req.uri = url.to_string();
req.AddHeader("User-Agent", "Wget/1.11.4");
req.AddHeader("Connection", "close");
s.write_some (boost::asio::buffer (req.to_string()));
// read response
std::stringstream rs;
char recv_buf[1024]; size_t l = 0;
do {
l = s.read_some (boost::asio::buffer (recv_buf, sizeof(recv_buf)), ecode);
if (l) rs.write (recv_buf, l);
} while (!ecode && l);
// process response
std::string data = rs.str();
i2p::http::HTTPRes res;
int len = res.parse(data);
if (len <= 0) {
LogPrint(eLogWarning, "Reseed: incomplete/broken response from ", url.host);
return "";
}
if (res.code != 200) {
LogPrint(eLogError, "Reseed: failed to reseed from ", url.host, ", http code ", res.code);
return "";
}
data.erase(0, len); /* drop http headers from response */
LogPrint(eLogDebug, "Reseed: got ", data.length(), " bytes of data from ", url.host);
if (res.is_chunked()) {
std::stringstream in(data), out;
if (!i2p::http::MergeChunkedResponse(in, out)) {
LogPrint(eLogWarning, "Reseed: failed to merge chunked response from ", url.host);
return "";
}
LogPrint(eLogDebug, "Reseed: got ", data.length(), "(", out.tellg(), ") bytes of data from ", url.host);
data = out.str();
}
return data;
}
else
LogPrint (eLogError, "Reseed: SSL handshake failed: ", ecode.message ());
}
else
LogPrint (eLogError, "Reseed: Couldn't connect to ", url.host, ": ", ecode.message ());
}
else
LogPrint (eLogError, "Reseed: Couldn't resolve address ", url.host, ": ", ecode.message ());
return "";
}
}
}

View File

@ -1,473 +0,0 @@
#include <fstream>
#include "Config.h"
#include "Crypto.h"
#include "Timestamp.h"
#include "I2NPProtocol.h"
#include "NetDb.h"
#include "FS.h"
#include "util.h"
#include "version.h"
#include "Log.h"
#include "Family.h"
#include "RouterContext.h"
namespace i2p
{
RouterContext context;
RouterContext::RouterContext ():
m_LastUpdateTime (0), m_AcceptsTunnels (true), m_IsFloodfill (false),
m_StartupTime (0), m_Status (eRouterStatusOK), m_Error (eRouterErrorNone),
m_NetID (I2PD_NET_ID)
{
}
void RouterContext::Init ()
{
srand (i2p::util::GetMillisecondsSinceEpoch () % 1000);
m_StartupTime = i2p::util::GetSecondsSinceEpoch ();
if (!Load ())
CreateNewRouter ();
UpdateRouterInfo ();
}
void RouterContext::CreateNewRouter ()
{
#if defined(__x86_64__) || defined(__i386__) || defined(_MSC_VER)
m_Keys = i2p::data::PrivateKeys::CreateRandomKeys (i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519);
#else
m_Keys = i2p::data::PrivateKeys::CreateRandomKeys (i2p::data::SIGNING_KEY_TYPE_DSA_SHA1);
#endif
SaveKeys ();
NewRouterInfo ();
}
void RouterContext::NewRouterInfo ()
{
i2p::data::RouterInfo routerInfo;
routerInfo.SetRouterIdentity (GetIdentity ());
uint16_t port; i2p::config::GetOption("port", port);
if (!port)
port = rand () % (30777 - 9111) + 9111; // I2P network ports range
bool ipv4; i2p::config::GetOption("ipv4", ipv4);
bool ipv6; i2p::config::GetOption("ipv6", ipv6);
bool nat; i2p::config::GetOption("nat", nat);
std::string ifname; i2p::config::GetOption("ifname", ifname);
std::string ifname4; i2p::config::GetOption("ifname4", ifname4);
std::string ifname6; i2p::config::GetOption("ifname6", ifname6);
if (ipv4)
{
std::string host = "127.0.0.1";
if (!i2p::config::IsDefault("host"))
i2p::config::GetOption("host", host);
else if (!nat && !ifname.empty())
/* bind to interface, we have no NAT so set external address too */
host = i2p::util::net::GetInterfaceAddress(ifname, false).to_string(); // v4
if(ifname4.size())
host = i2p::util::net::GetInterfaceAddress(ifname4, false).to_string();
routerInfo.AddSSUAddress (host.c_str(), port, routerInfo.GetIdentHash ());
routerInfo.AddNTCPAddress (host.c_str(), port);
}
if (ipv6)
{
std::string host = "::";
if (!i2p::config::IsDefault("host") && !ipv4) // override if v6 only
i2p::config::GetOption("host", host);
else if (!ifname.empty())
host = i2p::util::net::GetInterfaceAddress(ifname, true).to_string(); // v6
if(ifname6.size())
host = i2p::util::net::GetInterfaceAddress(ifname6, true).to_string();
routerInfo.AddSSUAddress (host.c_str(), port, routerInfo.GetIdentHash ());
routerInfo.AddNTCPAddress (host.c_str(), port);
}
routerInfo.SetCaps (i2p::data::RouterInfo::eReachable |
i2p::data::RouterInfo::eSSUTesting | i2p::data::RouterInfo::eSSUIntroducer); // LR, BC
routerInfo.SetProperty ("netId", std::to_string (m_NetID));
routerInfo.SetProperty ("router.version", I2P_VERSION);
routerInfo.CreateBuffer (m_Keys);
m_RouterInfo.SetRouterIdentity (GetIdentity ());
m_RouterInfo.Update (routerInfo.GetBuffer (), routerInfo.GetBufferLen ());
}
void RouterContext::UpdateRouterInfo ()
{
m_RouterInfo.CreateBuffer (m_Keys);
m_RouterInfo.SaveToFile (i2p::fs::DataDirPath (ROUTER_INFO));
m_LastUpdateTime = i2p::util::GetSecondsSinceEpoch ();
}
void RouterContext::SetStatus (RouterStatus status)
{
if (status != m_Status)
{
m_Status = status;
m_Error = eRouterErrorNone;
switch (m_Status)
{
case eRouterStatusOK:
SetReachable ();
break;
case eRouterStatusFirewalled:
SetUnreachable ();
break;
default:
;
}
}
}
void RouterContext::UpdatePort (int port)
{
bool updated = false;
for (auto& address : m_RouterInfo.GetAddresses ())
{
if (address->port != port)
{
address->port = port;
updated = true;
}
}
if (updated)
UpdateRouterInfo ();
}
void RouterContext::UpdateAddress (const boost::asio::ip::address& host)
{
bool updated = false;
for (auto& address : m_RouterInfo.GetAddresses ())
{
if (address->host != host && address->IsCompatible (host))
{
address->host = host;
updated = true;
}
}
auto ts = i2p::util::GetSecondsSinceEpoch ();
if (updated || ts > m_LastUpdateTime + ROUTER_INFO_UPDATE_INTERVAL)
UpdateRouterInfo ();
}
bool RouterContext::AddIntroducer (const i2p::data::RouterInfo::Introducer& introducer)
{
bool ret = m_RouterInfo.AddIntroducer (introducer);
if (ret)
UpdateRouterInfo ();
return ret;
}
void RouterContext::RemoveIntroducer (const boost::asio::ip::udp::endpoint& e)
{
if (m_RouterInfo.RemoveIntroducer (e))
UpdateRouterInfo ();
}
void RouterContext::SetFloodfill (bool floodfill)
{
m_IsFloodfill = floodfill;
if (floodfill)
m_RouterInfo.SetCaps (m_RouterInfo.GetCaps () | i2p::data::RouterInfo::eFloodfill);
else
{
m_RouterInfo.SetCaps (m_RouterInfo.GetCaps () & ~i2p::data::RouterInfo::eFloodfill);
// we don't publish number of routers and leaseset for non-floodfill
m_RouterInfo.DeleteProperty (i2p::data::ROUTER_INFO_PROPERTY_LEASESETS);
m_RouterInfo.DeleteProperty (i2p::data::ROUTER_INFO_PROPERTY_ROUTERS);
}
UpdateRouterInfo ();
}
std::string RouterContext::GetFamily () const
{
return m_RouterInfo.GetProperty (i2p::data::ROUTER_INFO_PROPERTY_FAMILY);
}
void RouterContext::SetFamily (const std::string& family)
{
std::string signature;
if (family.length () > 0)
signature = i2p::data::CreateFamilySignature (family, GetIdentHash ());
if (signature.length () > 0)
{
m_RouterInfo.SetProperty (i2p::data::ROUTER_INFO_PROPERTY_FAMILY, family);
m_RouterInfo.SetProperty (i2p::data::ROUTER_INFO_PROPERTY_FAMILY_SIG, signature);
}
else
{
m_RouterInfo.DeleteProperty (i2p::data::ROUTER_INFO_PROPERTY_FAMILY);
m_RouterInfo.DeleteProperty (i2p::data::ROUTER_INFO_PROPERTY_FAMILY_SIG);
}
}
void RouterContext::SetBandwidth (char L) {
uint16_t limit = 0;
enum { low, high, extra, unlim } type = high;
/* detect parameters */
switch (L)
{
case i2p::data::CAPS_FLAG_LOW_BANDWIDTH1 : limit = 12; type = low; break;
case i2p::data::CAPS_FLAG_LOW_BANDWIDTH2 : limit = 48; type = low; break;
case i2p::data::CAPS_FLAG_HIGH_BANDWIDTH1 : limit = 64; type = high; break;
case i2p::data::CAPS_FLAG_HIGH_BANDWIDTH2 : limit = 128; type = high; break;
case i2p::data::CAPS_FLAG_HIGH_BANDWIDTH3 : limit = 256; type = high; break;
case i2p::data::CAPS_FLAG_EXTRA_BANDWIDTH1 : limit = 2048; type = extra; break;
case i2p::data::CAPS_FLAG_EXTRA_BANDWIDTH2 : limit = 9999; type = unlim; break;
default:
limit = 48; type = low;
}
/* update caps & flags in RI */
auto caps = m_RouterInfo.GetCaps ();
caps &= ~i2p::data::RouterInfo::eHighBandwidth;
caps &= ~i2p::data::RouterInfo::eExtraBandwidth;
switch (type)
{
case low : /* not set */; break;
case extra : caps |= i2p::data::RouterInfo::eExtraBandwidth; break; // 'P'
case unlim : caps |= i2p::data::RouterInfo::eExtraBandwidth; // no break here, extra + high means 'X'
case high : caps |= i2p::data::RouterInfo::eHighBandwidth; break;
}
m_RouterInfo.SetCaps (caps);
UpdateRouterInfo ();
m_BandwidthLimit = limit;
}
void RouterContext::SetBandwidth (int limit)
{
if (limit > 2000) { SetBandwidth('X'); }
else if (limit > 256) { SetBandwidth('P'); }
else if (limit > 128) { SetBandwidth('O'); }
else if (limit > 64) { SetBandwidth('N'); }
else if (limit > 48) { SetBandwidth('M'); }
else if (limit > 12) { SetBandwidth('L'); }
else { SetBandwidth('K'); }
}
bool RouterContext::IsUnreachable () const
{
return m_RouterInfo.GetCaps () & i2p::data::RouterInfo::eUnreachable;
}
void RouterContext::SetUnreachable ()
{
// set caps
uint8_t caps = m_RouterInfo.GetCaps ();
caps &= ~i2p::data::RouterInfo::eReachable;
caps |= i2p::data::RouterInfo::eUnreachable;
caps &= ~i2p::data::RouterInfo::eFloodfill; // can't be floodfill
caps &= ~i2p::data::RouterInfo::eSSUIntroducer; // can't be introducer
m_RouterInfo.SetCaps (caps);
// remove NTCP address
auto& addresses = m_RouterInfo.GetAddresses ();
for (auto it = addresses.begin (); it != addresses.end (); ++it)
{
if ((*it)->transportStyle == i2p::data::RouterInfo::eTransportNTCP &&
(*it)->host.is_v4 ())
{
addresses.erase (it);
break;
}
}
// delete previous introducers
for (auto& addr : addresses)
if (addr->ssu)
addr->ssu->introducers.clear ();
// update
UpdateRouterInfo ();
}
void RouterContext::SetReachable ()
{
// update caps
uint8_t caps = m_RouterInfo.GetCaps ();
caps &= ~i2p::data::RouterInfo::eUnreachable;
caps |= i2p::data::RouterInfo::eReachable;
caps |= i2p::data::RouterInfo::eSSUIntroducer;
if (m_IsFloodfill)
caps |= i2p::data::RouterInfo::eFloodfill;
m_RouterInfo.SetCaps (caps);
// insert NTCP back
auto& addresses = m_RouterInfo.GetAddresses ();
for (const auto& addr : addresses)
{
if (addr->transportStyle == i2p::data::RouterInfo::eTransportSSU &&
addr->host.is_v4 ())
{
// insert NTCP address with host/port from SSU
m_RouterInfo.AddNTCPAddress (addr->host.to_string ().c_str (), addr->port);
break;
}
}
// delete previous introducers
for (auto& addr : addresses)
if (addr->ssu)
addr->ssu->introducers.clear ();
// update
UpdateRouterInfo ();
}
void RouterContext::SetSupportsV6 (bool supportsV6)
{
if (supportsV6)
m_RouterInfo.EnableV6 ();
else
m_RouterInfo.DisableV6 ();
UpdateRouterInfo ();
}
void RouterContext::SetSupportsV4 (bool supportsV4)
{
if (supportsV4)
m_RouterInfo.EnableV4 ();
else
m_RouterInfo.DisableV4 ();
UpdateRouterInfo ();
}
void RouterContext::UpdateNTCPV6Address (const boost::asio::ip::address& host)
{
bool updated = false, found = false;
int port = 0;
auto& addresses = m_RouterInfo.GetAddresses ();
for (auto& addr: addresses)
{
if (addr->host.is_v6 () && addr->transportStyle == i2p::data::RouterInfo::eTransportNTCP)
{
if (addr->host != host)
{
addr->host = host;
updated = true;
}
found = true;
}
else
port = addr->port;
}
if (!found)
{
// create new address
m_RouterInfo.AddNTCPAddress (host.to_string ().c_str (), port);
auto mtu = i2p::util::net::GetMTU (host);
if (mtu)
{
LogPrint (eLogDebug, "Router: Our v6 MTU=", mtu);
if (mtu > 1472) { // TODO: magic constant
mtu = 1472;
LogPrint(eLogWarning, "Router: MTU dropped to upper limit of 1472 bytes");
}
}
m_RouterInfo.AddSSUAddress (host.to_string ().c_str (), port, GetIdentHash (), mtu ? mtu : 1472); // TODO
updated = true;
}
if (updated)
UpdateRouterInfo ();
}
void RouterContext::UpdateStats ()
{
if (m_IsFloodfill)
{
// update routers and leasesets
m_RouterInfo.SetProperty (i2p::data::ROUTER_INFO_PROPERTY_LEASESETS, std::to_string(i2p::data::netdb.GetNumLeaseSets ()));
m_RouterInfo.SetProperty (i2p::data::ROUTER_INFO_PROPERTY_ROUTERS, std::to_string(i2p::data::netdb.GetNumRouters ()));
UpdateRouterInfo ();
}
}
bool RouterContext::Load ()
{
std::ifstream fk (i2p::fs::DataDirPath (ROUTER_KEYS), std::ifstream::in | std::ifstream::binary);
if (!fk.is_open ()) return false;
fk.seekg (0, std::ios::end);
size_t len = fk.tellg();
fk.seekg (0, std::ios::beg);
if (len == sizeof (i2p::data::Keys)) // old keys file format
{
i2p::data::Keys keys;
fk.read ((char *)&keys, sizeof (keys));
m_Keys = keys;
}
else // new keys file format
{
uint8_t * buf = new uint8_t[len];
fk.read ((char *)buf, len);
m_Keys.FromBuffer (buf, len);
delete[] buf;
}
m_RouterInfo.SetRouterIdentity (GetIdentity ());
i2p::data::RouterInfo routerInfo(i2p::fs::DataDirPath (ROUTER_INFO));
if (!routerInfo.IsUnreachable ()) // router.info looks good
{
m_RouterInfo.Update (routerInfo.GetBuffer (), routerInfo.GetBufferLen ());
m_RouterInfo.SetProperty ("coreVersion", I2P_VERSION);
m_RouterInfo.SetProperty ("router.version", I2P_VERSION);
// Migration to 0.9.24. TODO: remove later
m_RouterInfo.DeleteProperty ("coreVersion");
m_RouterInfo.DeleteProperty ("stat_uptime");
}
else
{
LogPrint (eLogError, ROUTER_INFO, " is malformed. Creating new");
NewRouterInfo ();
}
if (IsUnreachable ())
SetReachable (); // we assume reachable until we discover firewall through peer tests
return true;
}
void RouterContext::SaveKeys ()
{
// save in the same format as .dat files
std::ofstream fk (i2p::fs::DataDirPath (ROUTER_KEYS), std::ofstream::binary | std::ofstream::out);
size_t len = m_Keys.GetFullLen ();
uint8_t * buf = new uint8_t[len];
m_Keys.ToBuffer (buf, len);
fk.write ((char *)buf, len);
delete[] buf;
}
std::shared_ptr<i2p::tunnel::TunnelPool> RouterContext::GetTunnelPool () const
{
return i2p::tunnel::tunnels.GetExploratoryPool ();
}
void RouterContext::HandleI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from)
{
i2p::HandleI2NPMessage (CreateI2NPMessage (buf, GetI2NPMessageLength (buf), from));
}
void RouterContext::ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg)
{
std::unique_lock<std::mutex> l(m_GarlicMutex);
i2p::garlic::GarlicDestination::ProcessGarlicMessage (msg);
}
void RouterContext::ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg)
{
std::unique_lock<std::mutex> l(m_GarlicMutex);
i2p::garlic::GarlicDestination::ProcessDeliveryStatusMessage (msg);
}
void RouterContext::CleanupDestination ()
{
std::unique_lock<std::mutex> l(m_GarlicMutex);
i2p::garlic::GarlicDestination::CleanupExpiredTags ();
}
uint32_t RouterContext::GetUptime () const
{
return i2p::util::GetSecondsSinceEpoch () - m_StartupTime;
}
}

View File

@ -1,129 +0,0 @@
#ifndef ROUTER_CONTEXT_H__
#define ROUTER_CONTEXT_H__
#include <inttypes.h>
#include <string>
#include <memory>
#include <mutex>
#include <boost/asio.hpp>
#include "Identity.h"
#include "RouterInfo.h"
#include "Garlic.h"
namespace i2p
{
const char ROUTER_INFO[] = "router.info";
const char ROUTER_KEYS[] = "router.keys";
const int ROUTER_INFO_UPDATE_INTERVAL = 1800; // 30 minutes
enum RouterStatus
{
eRouterStatusOK = 0,
eRouterStatusTesting = 1,
eRouterStatusFirewalled = 2,
eRouterStatusError = 3
};
enum RouterError
{
eRouterErrorNone = 0,
eRouterErrorClockSkew = 1
};
class RouterContext: public i2p::garlic::GarlicDestination
{
public:
RouterContext ();
void Init ();
const i2p::data::PrivateKeys& GetPrivateKeys () const { return m_Keys; };
i2p::data::RouterInfo& GetRouterInfo () { return m_RouterInfo; };
std::shared_ptr<const i2p::data::RouterInfo> GetSharedRouterInfo () const
{
return std::shared_ptr<const i2p::data::RouterInfo> (&m_RouterInfo,
[](const i2p::data::RouterInfo *) {});
}
std::shared_ptr<i2p::garlic::GarlicDestination> GetSharedDestination ()
{
return std::shared_ptr<i2p::garlic::GarlicDestination> (this,
[](i2p::garlic::GarlicDestination *) {});
}
uint32_t GetUptime () const;
uint32_t GetStartupTime () const { return m_StartupTime; };
uint64_t GetLastUpdateTime () const { return m_LastUpdateTime; };
uint64_t GetBandwidthLimit () const { return m_BandwidthLimit; };
RouterStatus GetStatus () const { return m_Status; };
void SetStatus (RouterStatus status);
RouterError GetError () const { return m_Error; };
void SetError (RouterError error) { m_Status = eRouterStatusError; m_Error = error; };
int GetNetID () const { return m_NetID; };
void SetNetID (int netID) { m_NetID = netID; };
void UpdatePort (int port); // called from Daemon
void UpdateAddress (const boost::asio::ip::address& host); // called from SSU or Daemon
bool AddIntroducer (const i2p::data::RouterInfo::Introducer& introducer);
void RemoveIntroducer (const boost::asio::ip::udp::endpoint& e);
bool IsUnreachable () const;
void SetUnreachable ();
void SetReachable ();
bool IsFloodfill () const { return m_IsFloodfill; };
void SetFloodfill (bool floodfill);
void SetFamily (const std::string& family);
std::string GetFamily () const;
void SetBandwidth (int limit); /* in kilobytes */
void SetBandwidth (char L); /* by letter */
bool AcceptsTunnels () const { return m_AcceptsTunnels; };
void SetAcceptsTunnels (bool acceptsTunnels) { m_AcceptsTunnels = acceptsTunnels; };
bool SupportsV6 () const { return m_RouterInfo.IsV6 (); };
bool SupportsV4 () const { return m_RouterInfo.IsV4 (); };
void SetSupportsV6 (bool supportsV6);
void SetSupportsV4 (bool supportsV4);
void UpdateNTCPV6Address (const boost::asio::ip::address& host); // called from NTCP session
void UpdateStats ();
void CleanupDestination (); // garlic destination
// implements LocalDestination
std::shared_ptr<const i2p::data::IdentityEx> GetIdentity () const { return m_Keys.GetPublic (); };
const uint8_t * GetEncryptionPrivateKey () const { return m_Keys.GetPrivateKey (); };
const uint8_t * GetEncryptionPublicKey () const { return GetIdentity ()->GetStandardIdentity ().publicKey; };
void Sign (const uint8_t * buf, int len, uint8_t * signature) const { m_Keys.Sign (buf, len, signature); };
void SetLeaseSetUpdated () {};
// implements GarlicDestination
std::shared_ptr<const i2p::data::LocalLeaseSet> GetLeaseSet () { return nullptr; };
std::shared_ptr<i2p::tunnel::TunnelPool> GetTunnelPool () const;
void HandleI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from);
// override GarlicDestination
void ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg);
void ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg);
private:
void CreateNewRouter ();
void NewRouterInfo ();
void UpdateRouterInfo ();
bool Load ();
void SaveKeys ();
private:
i2p::data::RouterInfo m_RouterInfo;
i2p::data::PrivateKeys m_Keys;
uint64_t m_LastUpdateTime;
bool m_AcceptsTunnels, m_IsFloodfill;
uint64_t m_StartupTime; // in seconds since epoch
uint32_t m_BandwidthLimit; // allowed bandwidth
RouterStatus m_Status;
RouterError m_Error;
int m_NetID;
std::mutex m_GarlicMutex;
};
extern RouterContext context;
}
#endif

View File

@ -1,818 +0,0 @@
#include <stdio.h>
#include <string.h>
#include "I2PEndian.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#if (BOOST_VERSION >= 105300)
#include <boost/atomic.hpp>
#endif
#include "version.h"
#include "Crypto.h"
#include "Base.h"
#include "Timestamp.h"
#include "Log.h"
#include "NetDb.h"
#include "RouterContext.h"
#include "RouterInfo.h"
namespace i2p
{
namespace data
{
RouterInfo::RouterInfo (): m_Buffer (nullptr)
{
m_Addresses = boost::make_shared<Addresses>(); // create empty list
}
RouterInfo::RouterInfo (const std::string& fullPath):
m_FullPath (fullPath), m_IsUpdated (false), m_IsUnreachable (false),
m_SupportedTransports (0), m_Caps (0)
{
m_Addresses = boost::make_shared<Addresses>(); // create empty list
m_Buffer = new uint8_t[MAX_RI_BUFFER_SIZE];
ReadFromFile ();
}
RouterInfo::RouterInfo (const uint8_t * buf, int len):
m_IsUpdated (true), m_IsUnreachable (false), m_SupportedTransports (0), m_Caps (0)
{
m_Addresses = boost::make_shared<Addresses>(); // create empty list
m_Buffer = new uint8_t[MAX_RI_BUFFER_SIZE];
memcpy (m_Buffer, buf, len);
m_BufferLen = len;
ReadFromBuffer (true);
}
RouterInfo::~RouterInfo ()
{
delete[] m_Buffer;
}
void RouterInfo::Update (const uint8_t * buf, int len)
{
// verify signature since we have indentity already
int l = len - m_RouterIdentity->GetSignatureLen ();
if (m_RouterIdentity->Verify (buf, l, buf + l))
{
// clean up
m_IsUpdated = true;
m_IsUnreachable = false;
m_SupportedTransports = 0;
m_Caps = 0;
// don't clean up m_Addresses, it will be replaced in ReadFromStream
m_Properties.clear ();
// copy buffer
if (!m_Buffer)
m_Buffer = new uint8_t[MAX_RI_BUFFER_SIZE];
memcpy (m_Buffer, buf, len);
m_BufferLen = len;
// skip identity
size_t identityLen = m_RouterIdentity->GetFullLen ();
// read new RI
std::stringstream str (std::string ((char *)m_Buffer + identityLen, m_BufferLen - identityLen));
ReadFromStream (str);
// don't delete buffer until saved to the file
}
else
{
LogPrint (eLogError, "RouterInfo: signature verification failed");
m_IsUnreachable = true;
}
}
void RouterInfo::SetRouterIdentity (std::shared_ptr<const IdentityEx> identity)
{
m_RouterIdentity = identity;
m_Timestamp = i2p::util::GetMillisecondsSinceEpoch ();
}
bool RouterInfo::LoadFile ()
{
std::ifstream s(m_FullPath, std::ifstream::binary);
if (s.is_open ())
{
s.seekg (0,std::ios::end);
m_BufferLen = s.tellg ();
if (m_BufferLen < 40 || m_BufferLen > MAX_RI_BUFFER_SIZE)
{
LogPrint(eLogError, "RouterInfo: File", m_FullPath, " is malformed");
return false;
}
s.seekg(0, std::ios::beg);
if (!m_Buffer)
m_Buffer = new uint8_t[MAX_RI_BUFFER_SIZE];
s.read((char *)m_Buffer, m_BufferLen);
}
else
{
LogPrint (eLogError, "RouterInfo: Can't open file ", m_FullPath);
return false;
}
return true;
}
void RouterInfo::ReadFromFile ()
{
if (LoadFile ())
ReadFromBuffer (false);
else
m_IsUnreachable = true;
}
void RouterInfo::ReadFromBuffer (bool verifySignature)
{
m_RouterIdentity = std::make_shared<IdentityEx>(m_Buffer, m_BufferLen);
size_t identityLen = m_RouterIdentity->GetFullLen ();
if (identityLen >= m_BufferLen)
{
LogPrint (eLogError, "RouterInfo: identity length ", identityLen, " exceeds buffer size ", m_BufferLen);
m_IsUnreachable = true;
return;
}
if (verifySignature)
{
// verify signature
int l = m_BufferLen - m_RouterIdentity->GetSignatureLen ();
if (l < 0 || !m_RouterIdentity->Verify ((uint8_t *)m_Buffer, l, (uint8_t *)m_Buffer + l))
{
LogPrint (eLogError, "RouterInfo: signature verification failed");
m_IsUnreachable = true;
return;
}
m_RouterIdentity->DropVerifier ();
}
// parse RI
std::stringstream str;
str.write ((const char *)m_Buffer + identityLen, m_BufferLen - identityLen);
ReadFromStream (str);
if (!str)
{
LogPrint (eLogError, "RouterInfo: malformed message");
m_IsUnreachable = true;
}
}
void RouterInfo::ReadFromStream (std::istream& s)
{
s.read ((char *)&m_Timestamp, sizeof (m_Timestamp));
m_Timestamp = be64toh (m_Timestamp);
// read addresses
auto addresses = boost::make_shared<Addresses>();
uint8_t numAddresses;
s.read ((char *)&numAddresses, sizeof (numAddresses)); if (!s) return;
bool introducers = false;
for (int i = 0; i < numAddresses; i++)
{
uint8_t supportedTransports = 0;
bool isValidAddress = true;
auto address = std::make_shared<Address>();
s.read ((char *)&address->cost, sizeof (address->cost));
s.read ((char *)&address->date, sizeof (address->date));
char transportStyle[5];
ReadString (transportStyle, 5, s);
if (!strcmp (transportStyle, "NTCP"))
address->transportStyle = eTransportNTCP;
else if (!strcmp (transportStyle, "SSU"))
{
address->transportStyle = eTransportSSU;
address->ssu.reset (new SSUExt ());
address->ssu->mtu = 0;
}
else
address->transportStyle = eTransportUnknown;
address->port = 0;
uint16_t size, r = 0;
s.read ((char *)&size, sizeof (size)); if (!s) return;
size = be16toh (size);
while (r < size)
{
char key[255], value[255];
r += ReadString (key, 255, s);
s.seekg (1, std::ios_base::cur); r++; // =
r += ReadString (value, 255, s);
s.seekg (1, std::ios_base::cur); r++; // ;
if (!s) return;
if (!strcmp (key, "host"))
{
boost::system::error_code ecode;
address->host = boost::asio::ip::address::from_string (value, ecode);
if (ecode)
{
if (address->transportStyle == eTransportNTCP)
{
supportedTransports |= eNTCPV4; // TODO:
address->addressString = value;
}
else
{
supportedTransports |= eSSUV4; // TODO:
address->addressString = value;
}
}
else
{
// add supported protocol
if (address->host.is_v4 ())
supportedTransports |= (address->transportStyle == eTransportNTCP) ? eNTCPV4 : eSSUV4;
else
supportedTransports |= (address->transportStyle == eTransportNTCP) ? eNTCPV6 : eSSUV6;
}
}
else if (!strcmp (key, "port"))
address->port = boost::lexical_cast<int>(value);
else if (!strcmp (key, "mtu"))
{
if (address->ssu)
address->ssu->mtu = boost::lexical_cast<int>(value);
else
LogPrint (eLogWarning, "RouterInfo: Unexpected field 'mtu' for NTCP");
}
else if (!strcmp (key, "key"))
{
if (address->ssu)
Base64ToByteStream (value, strlen (value), address->ssu->key, 32);
else
LogPrint (eLogWarning, "RouterInfo: Unexpected field 'key' for NTCP");
}
else if (!strcmp (key, "caps"))
ExtractCaps (value);
else if (key[0] == 'i')
{
// introducers
introducers = true;
size_t l = strlen(key);
unsigned char index = key[l-1] - '0'; // TODO:
key[l-1] = 0;
if (index > 9)
{
LogPrint (eLogError, "RouterInfo: Unexpected introducer's index ", index, " skipped");
if (s) continue; else return;
}
if (index >= address->ssu->introducers.size ())
address->ssu->introducers.resize (index + 1);
Introducer& introducer = address->ssu->introducers.at (index);
if (!strcmp (key, "ihost"))
{
boost::system::error_code ecode;
introducer.iHost = boost::asio::ip::address::from_string (value, ecode);
}
else if (!strcmp (key, "iport"))
introducer.iPort = boost::lexical_cast<int>(value);
else if (!strcmp (key, "itag"))
introducer.iTag = boost::lexical_cast<uint32_t>(value);
else if (!strcmp (key, "ikey"))
Base64ToByteStream (value, strlen (value), introducer.iKey, 32);
}
if (!s) return;
}
if (isValidAddress)
{
addresses->push_back(address);
m_SupportedTransports |= supportedTransports;
}
}
#if (BOOST_VERSION >= 105300)
boost::atomic_store (&m_Addresses, addresses);
#else
m_Addresses = addresses; // race condition
#endif
// read peers
uint8_t numPeers;
s.read ((char *)&numPeers, sizeof (numPeers)); if (!s) return;
s.seekg (numPeers*32, std::ios_base::cur); // TODO: read peers
// read properties
uint16_t size, r = 0;
s.read ((char *)&size, sizeof (size)); if (!s) return;
size = be16toh (size);
while (r < size)
{
char key[255], value[255];
r += ReadString (key, 255, s);
s.seekg (1, std::ios_base::cur); r++; // =
r += ReadString (value, 255, s);
s.seekg (1, std::ios_base::cur); r++; // ;
if (!s) return;
m_Properties[key] = value;
// extract caps
if (!strcmp (key, "caps"))
ExtractCaps (value);
// check netId
else if (!strcmp (key, ROUTER_INFO_PROPERTY_NETID) && atoi (value) != i2p::context.GetNetID ())
{
LogPrint (eLogError, "RouterInfo: Unexpected ", ROUTER_INFO_PROPERTY_NETID, "=", value);
m_IsUnreachable = true;
}
// family
else if (!strcmp (key, ROUTER_INFO_PROPERTY_FAMILY))
{
m_Family = value;
boost::to_lower (m_Family);
}
else if (!strcmp (key, ROUTER_INFO_PROPERTY_FAMILY_SIG))
{
if (!netdb.GetFamilies ().VerifyFamily (m_Family, GetIdentHash (), value))
{
LogPrint (eLogWarning, "RouterInfo: family signature verification failed");
m_Family.clear ();
}
}
if (!s) return;
}
if (!m_SupportedTransports || !m_Addresses->size() || (UsesIntroducer () && !introducers))
SetUnreachable (true);
}
bool RouterInfo::IsFamily(const std::string & fam) const {
return m_Family == fam;
}
void RouterInfo::ExtractCaps (const char * value)
{
const char * cap = value;
while (*cap)
{
switch (*cap)
{
case CAPS_FLAG_FLOODFILL:
m_Caps |= Caps::eFloodfill;
break;
case CAPS_FLAG_HIGH_BANDWIDTH1:
case CAPS_FLAG_HIGH_BANDWIDTH2:
case CAPS_FLAG_HIGH_BANDWIDTH3:
m_Caps |= Caps::eHighBandwidth;
break;
case CAPS_FLAG_EXTRA_BANDWIDTH1:
case CAPS_FLAG_EXTRA_BANDWIDTH2:
m_Caps |= Caps::eExtraBandwidth;
break;
case CAPS_FLAG_HIDDEN:
m_Caps |= Caps::eHidden;
break;
case CAPS_FLAG_REACHABLE:
m_Caps |= Caps::eReachable;
break;
case CAPS_FLAG_UNREACHABLE:
m_Caps |= Caps::eUnreachable;
break;
case CAPS_FLAG_SSU_TESTING:
m_Caps |= Caps::eSSUTesting;
break;
case CAPS_FLAG_SSU_INTRODUCER:
m_Caps |= Caps::eSSUIntroducer;
break;
default: ;
}
cap++;
}
}
void RouterInfo::UpdateCapsProperty ()
{
std::string caps;
if (m_Caps & eFloodfill)
{
if (m_Caps & eExtraBandwidth) caps += (m_Caps & eHighBandwidth) ?
CAPS_FLAG_EXTRA_BANDWIDTH2 : // 'X'
CAPS_FLAG_EXTRA_BANDWIDTH1; // 'P'
caps += CAPS_FLAG_HIGH_BANDWIDTH3; // 'O'
caps += CAPS_FLAG_FLOODFILL; // floodfill
}
else
{
if (m_Caps & eExtraBandwidth)
{
caps += (m_Caps & eHighBandwidth) ? CAPS_FLAG_EXTRA_BANDWIDTH2 /* 'X' */ : CAPS_FLAG_EXTRA_BANDWIDTH1; /*'P' */
caps += CAPS_FLAG_HIGH_BANDWIDTH3; // 'O'
}
else
caps += (m_Caps & eHighBandwidth) ? CAPS_FLAG_HIGH_BANDWIDTH3 /* 'O' */: CAPS_FLAG_LOW_BANDWIDTH2 /* 'L' */; // bandwidth
}
if (m_Caps & eHidden) caps += CAPS_FLAG_HIDDEN; // hidden
if (m_Caps & eReachable) caps += CAPS_FLAG_REACHABLE; // reachable
if (m_Caps & eUnreachable) caps += CAPS_FLAG_UNREACHABLE; // unreachable
SetProperty ("caps", caps);
}
void RouterInfo::WriteToStream (std::ostream& s) const
{
uint64_t ts = htobe64 (m_Timestamp);
s.write ((const char *)&ts, sizeof (ts));
// addresses
uint8_t numAddresses = m_Addresses->size ();
s.write ((char *)&numAddresses, sizeof (numAddresses));
for (const auto& addr_ptr : *m_Addresses)
{
const Address& address = *addr_ptr;
s.write ((const char *)&address.cost, sizeof (address.cost));
s.write ((const char *)&address.date, sizeof (address.date));
std::stringstream properties;
if (address.transportStyle == eTransportNTCP)
WriteString ("NTCP", s);
else if (address.transportStyle == eTransportSSU)
{
WriteString ("SSU", s);
// caps
WriteString ("caps", properties);
properties << '=';
std::string caps;
if (IsPeerTesting ()) caps += CAPS_FLAG_SSU_TESTING;
if (IsIntroducer ()) caps += CAPS_FLAG_SSU_INTRODUCER;
WriteString (caps, properties);
properties << ';';
}
else
WriteString ("", s);
WriteString ("host", properties);
properties << '=';
WriteString (address.host.to_string (), properties);
properties << ';';
if (address.transportStyle == eTransportSSU)
{
// write introducers if any
if (address.ssu->introducers.size () > 0)
{
int i = 0;
for (const auto& introducer: address.ssu->introducers)
{
WriteString ("ihost" + boost::lexical_cast<std::string>(i), properties);
properties << '=';
WriteString (introducer.iHost.to_string (), properties);
properties << ';';
i++;
}
i = 0;
for (const auto& introducer: address.ssu->introducers)
{
WriteString ("ikey" + boost::lexical_cast<std::string>(i), properties);
properties << '=';
char value[64];
size_t l = ByteStreamToBase64 (introducer.iKey, 32, value, 64);
value[l] = 0;
WriteString (value, properties);
properties << ';';
i++;
}
i = 0;
for (const auto& introducer: address.ssu->introducers)
{
WriteString ("iport" + boost::lexical_cast<std::string>(i), properties);
properties << '=';
WriteString (boost::lexical_cast<std::string>(introducer.iPort), properties);
properties << ';';
i++;
}
i = 0;
for (const auto& introducer: address.ssu->introducers)
{
WriteString ("itag" + boost::lexical_cast<std::string>(i), properties);
properties << '=';
WriteString (boost::lexical_cast<std::string>(introducer.iTag), properties);
properties << ';';
i++;
}
}
// write intro key
WriteString ("key", properties);
properties << '=';
char value[64];
size_t l = ByteStreamToBase64 (address.ssu->key, 32, value, 64);
value[l] = 0;
WriteString (value, properties);
properties << ';';
// write mtu
if (address.ssu->mtu)
{
WriteString ("mtu", properties);
properties << '=';
WriteString (boost::lexical_cast<std::string>(address.ssu->mtu), properties);
properties << ';';
}
}
WriteString ("port", properties);
properties << '=';
WriteString (boost::lexical_cast<std::string>(address.port), properties);
properties << ';';
uint16_t size = htobe16 (properties.str ().size ());
s.write ((char *)&size, sizeof (size));
s.write (properties.str ().c_str (), properties.str ().size ());
}
// peers
uint8_t numPeers = 0;
s.write ((char *)&numPeers, sizeof (numPeers));
// properties
std::stringstream properties;
for (const auto& p : m_Properties)
{
WriteString (p.first, properties);
properties << '=';
WriteString (p.second, properties);
properties << ';';
}
uint16_t size = htobe16 (properties.str ().size ());
s.write ((char *)&size, sizeof (size));
s.write (properties.str ().c_str (), properties.str ().size ());
}
bool RouterInfo::IsNewer (const uint8_t * buf, size_t len) const
{
if (!m_RouterIdentity) return false;
size_t size = m_RouterIdentity->GetFullLen ();
if (size + 8 > len) return false;
return bufbe64toh (buf + size) > m_Timestamp;
}
const uint8_t * RouterInfo::LoadBuffer ()
{
if (!m_Buffer)
{
if (LoadFile ())
LogPrint (eLogDebug, "RouterInfo: Buffer for ", GetIdentHashAbbreviation (GetIdentHash ()), " loaded from file");
}
return m_Buffer;
}
void RouterInfo::CreateBuffer (const PrivateKeys& privateKeys)
{
m_Timestamp = i2p::util::GetMillisecondsSinceEpoch (); // refresh timstamp
std::stringstream s;
uint8_t ident[1024];
auto identLen = privateKeys.GetPublic ()->ToBuffer (ident, 1024);
s.write ((char *)ident, identLen);
WriteToStream (s);
m_BufferLen = s.str ().size ();
if (!m_Buffer)
m_Buffer = new uint8_t[MAX_RI_BUFFER_SIZE];
memcpy (m_Buffer, s.str ().c_str (), m_BufferLen);
// signature
privateKeys.Sign ((uint8_t *)m_Buffer, m_BufferLen, (uint8_t *)m_Buffer + m_BufferLen);
m_BufferLen += privateKeys.GetPublic ()->GetSignatureLen ();
}
bool RouterInfo::SaveToFile (const std::string& fullPath)
{
m_FullPath = fullPath;
if (!m_Buffer) {
LogPrint (eLogError, "RouterInfo: Can't save, m_Buffer == NULL");
return false;
}
std::ofstream f (fullPath, std::ofstream::binary | std::ofstream::out);
if (!f.is_open ()) {
LogPrint(eLogError, "RouterInfo: Can't save to ", fullPath);
return false;
}
f.write ((char *)m_Buffer, m_BufferLen);
return true;
}
size_t RouterInfo::ReadString (char * str, size_t len, std::istream& s) const
{
uint8_t l;
s.read ((char *)&l, 1);
if (l < len)
{
s.read (str, l);
if (!s) l = 0; // failed, return empty string
str[l] = 0;
}
else
{
LogPrint (eLogWarning, "RouterInfo: string length ", (int)l, " exceeds buffer size ", len);
s.seekg (l, std::ios::cur); // skip
str[0] = 0;
}
return l+1;
}
void RouterInfo::WriteString (const std::string& str, std::ostream& s) const
{
uint8_t len = str.size ();
s.write ((char *)&len, 1);
s.write (str.c_str (), len);
}
void RouterInfo::AddNTCPAddress (const char * host, int port)
{
auto addr = std::make_shared<Address>();
addr->host = boost::asio::ip::address::from_string (host);
addr->port = port;
addr->transportStyle = eTransportNTCP;
addr->cost = 2;
addr->date = 0;
for (const auto& it: *m_Addresses) // don't insert same address twice
if (*it == *addr) return;
m_SupportedTransports |= addr->host.is_v6 () ? eNTCPV6 : eNTCPV4;
m_Addresses->push_back(std::move(addr));
}
void RouterInfo::AddSSUAddress (const char * host, int port, const uint8_t * key, int mtu)
{
auto addr = std::make_shared<Address>();
addr->host = boost::asio::ip::address::from_string (host);
addr->port = port;
addr->transportStyle = eTransportSSU;
addr->cost = 10; // NTCP should have priority over SSU
addr->date = 0;
addr->ssu.reset (new SSUExt ());
addr->ssu->mtu = mtu;
memcpy (addr->ssu->key, key, 32);
for (const auto& it: *m_Addresses) // don't insert same address twice
if (*it == *addr) return;
m_SupportedTransports |= addr->host.is_v6 () ? eSSUV6 : eSSUV4;
m_Addresses->push_back(std::move(addr));
m_Caps |= eSSUTesting;
m_Caps |= eSSUIntroducer;
}
bool RouterInfo::AddIntroducer (const Introducer& introducer)
{
for (auto& addr : *m_Addresses)
{
if (addr->transportStyle == eTransportSSU && addr->host.is_v4 ())
{
for (auto& intro: addr->ssu->introducers)
if (intro.iTag == introducer.iTag) return false; // already presented
addr->ssu->introducers.push_back (introducer);
return true;
}
}
return false;
}
bool RouterInfo::RemoveIntroducer (const boost::asio::ip::udp::endpoint& e)
{
for (auto& addr: *m_Addresses)
{
if (addr->transportStyle == eTransportSSU && addr->host.is_v4 ())
{
for (auto it = addr->ssu->introducers.begin (); it != addr->ssu->introducers.end (); ++it)
if ( boost::asio::ip::udp::endpoint (it->iHost, it->iPort) == e)
{
addr->ssu->introducers.erase (it);
return true;
}
}
}
return false;
}
void RouterInfo::SetCaps (uint8_t caps)
{
m_Caps = caps;
UpdateCapsProperty ();
}
void RouterInfo::SetCaps (const char * caps)
{
SetProperty ("caps", caps);
m_Caps = 0;
ExtractCaps (caps);
}
void RouterInfo::SetProperty (const std::string& key, const std::string& value)
{
m_Properties[key] = value;
}
void RouterInfo::DeleteProperty (const std::string& key)
{
m_Properties.erase (key);
}
std::string RouterInfo::GetProperty (const std::string& key) const
{
auto it = m_Properties.find (key);
if (it != m_Properties.end ())
return it->second;
return "";
}
bool RouterInfo::IsNTCP (bool v4only) const
{
if (v4only)
return m_SupportedTransports & eNTCPV4;
else
return m_SupportedTransports & (eNTCPV4 | eNTCPV6);
}
bool RouterInfo::IsSSU (bool v4only) const
{
if (v4only)
return m_SupportedTransports & eSSUV4;
else
return m_SupportedTransports & (eSSUV4 | eSSUV6);
}
bool RouterInfo::IsV6 () const
{
return m_SupportedTransports & (eNTCPV6 | eSSUV6);
}
bool RouterInfo::IsV4 () const
{
return m_SupportedTransports & (eNTCPV4 | eSSUV4);
}
void RouterInfo::EnableV6 ()
{
if (!IsV6 ())
m_SupportedTransports |= eNTCPV6 | eSSUV6;
}
void RouterInfo::EnableV4 ()
{
if (!IsV4 ())
m_SupportedTransports |= eNTCPV4 | eSSUV4;
}
void RouterInfo::DisableV6 ()
{
if (IsV6 ())
{
m_SupportedTransports &= ~(eNTCPV6 | eSSUV6);
for (auto it = m_Addresses->begin (); it != m_Addresses->end ();)
{
auto addr = *it;
if (addr->host.is_v6 ())
it = m_Addresses->erase (it);
else
++it;
}
}
}
void RouterInfo::DisableV4 ()
{
if (IsV4 ())
{
m_SupportedTransports &= ~(eNTCPV4 | eSSUV4);
for (auto it = m_Addresses->begin (); it != m_Addresses->end ();)
{
auto addr = *it;
if (addr->host.is_v4 ())
it = m_Addresses->erase (it);
else
++it;
}
}
}
bool RouterInfo::UsesIntroducer () const
{
return m_Caps & Caps::eUnreachable; // non-reachable
}
std::shared_ptr<const RouterInfo::Address> RouterInfo::GetNTCPAddress (bool v4only) const
{
return GetAddress (eTransportNTCP, v4only);
}
std::shared_ptr<const RouterInfo::Address> RouterInfo::GetSSUAddress (bool v4only) const
{
return GetAddress (eTransportSSU, v4only);
}
std::shared_ptr<const RouterInfo::Address> RouterInfo::GetSSUV6Address () const
{
return GetAddress (eTransportSSU, false, true);
}
std::shared_ptr<const RouterInfo::Address> RouterInfo::GetAddress (TransportStyle s, bool v4only, bool v6only) const
{
#if (BOOST_VERSION >= 105300)
auto addresses = boost::atomic_load (&m_Addresses);
#else
auto addresses = m_Addresses;
#endif
for (const auto& address : *addresses)
{
if (address->transportStyle == s)
{
if ((!v4only || address->host.is_v4 ()) && (!v6only || address->host.is_v6 ()))
return address;
}
}
return nullptr;
}
std::shared_ptr<RouterProfile> RouterInfo::GetProfile () const
{
if (!m_Profile)
m_Profile = GetRouterProfile (GetIdentHash ());
return m_Profile;
}
}
}

View File

@ -1,219 +0,0 @@
#ifndef ROUTER_INFO_H__
#define ROUTER_INFO_H__
#include <inttypes.h>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include "Identity.h"
#include "Profiling.h"
namespace i2p
{
namespace data
{
const char ROUTER_INFO_PROPERTY_LEASESETS[] = "netdb.knownLeaseSets";
const char ROUTER_INFO_PROPERTY_ROUTERS[] = "netdb.knownRouters";
const char ROUTER_INFO_PROPERTY_NETID[] = "netId";
const char ROUTER_INFO_PROPERTY_FAMILY[] = "family";
const char ROUTER_INFO_PROPERTY_FAMILY_SIG[] = "family.sig";
const char CAPS_FLAG_FLOODFILL = 'f';
const char CAPS_FLAG_HIDDEN = 'H';
const char CAPS_FLAG_REACHABLE = 'R';
const char CAPS_FLAG_UNREACHABLE = 'U';
/* bandwidth flags */
const char CAPS_FLAG_LOW_BANDWIDTH1 = 'K'; /* < 12 KBps */
const char CAPS_FLAG_LOW_BANDWIDTH2 = 'L'; /* 12-48 KBps */
const char CAPS_FLAG_HIGH_BANDWIDTH1 = 'M'; /* 48-64 KBps */
const char CAPS_FLAG_HIGH_BANDWIDTH2 = 'N'; /* 64-128 KBps */
const char CAPS_FLAG_HIGH_BANDWIDTH3 = 'O'; /* 128-256 KBps */
const char CAPS_FLAG_EXTRA_BANDWIDTH1 = 'P'; /* 256-2000 KBps */
const char CAPS_FLAG_EXTRA_BANDWIDTH2 = 'X'; /* > 2000 KBps */
const char CAPS_FLAG_SSU_TESTING = 'B';
const char CAPS_FLAG_SSU_INTRODUCER = 'C';
const int MAX_RI_BUFFER_SIZE = 2048;
class RouterInfo: public RoutingDestination
{
public:
enum SupportedTranports
{
eNTCPV4 = 0x01,
eNTCPV6 = 0x02,
eSSUV4 = 0x04,
eSSUV6 = 0x08
};
enum Caps
{
eFloodfill = 0x01,
eHighBandwidth = 0x02,
eExtraBandwidth = 0x04,
eReachable = 0x08,
eSSUTesting = 0x10,
eSSUIntroducer = 0x20,
eHidden = 0x40,
eUnreachable = 0x80
};
enum TransportStyle
{
eTransportUnknown = 0,
eTransportNTCP,
eTransportSSU
};
typedef Tag<32> IntroKey; // should be castable to MacKey and AESKey
struct Introducer
{
boost::asio::ip::address iHost;
int iPort;
IntroKey iKey;
uint32_t iTag;
};
struct SSUExt
{
int mtu;
IntroKey key; // intro key for SSU
std::vector<Introducer> introducers;
};
struct Address
{
TransportStyle transportStyle;
boost::asio::ip::address host;
std::string addressString;
int port;
uint64_t date;
uint8_t cost;
std::unique_ptr<SSUExt> ssu; // not null for SSU
bool IsCompatible (const boost::asio::ip::address& other) const
{
return (host.is_v4 () && other.is_v4 ()) ||
(host.is_v6 () && other.is_v6 ());
}
bool operator==(const Address& other) const
{
return transportStyle == other.transportStyle && host == other.host && port == other.port;
}
bool operator!=(const Address& other) const
{
return !(*this == other);
}
};
typedef std::list<std::shared_ptr<Address> > Addresses;
RouterInfo ();
RouterInfo (const std::string& fullPath);
RouterInfo (const RouterInfo& ) = default;
RouterInfo& operator=(const RouterInfo& ) = default;
RouterInfo (const uint8_t * buf, int len);
~RouterInfo ();
std::shared_ptr<const IdentityEx> GetRouterIdentity () const { return m_RouterIdentity; };
void SetRouterIdentity (std::shared_ptr<const IdentityEx> identity);
std::string GetIdentHashBase64 () const { return GetIdentHash ().ToBase64 (); };
uint64_t GetTimestamp () const { return m_Timestamp; };
Addresses& GetAddresses () { return *m_Addresses; }; // should be called for local RI only, otherwise must return shared_ptr
std::shared_ptr<const Address> GetNTCPAddress (bool v4only = true) const;
std::shared_ptr<const Address> GetSSUAddress (bool v4only = true) const;
std::shared_ptr<const Address> GetSSUV6Address () const;
void AddNTCPAddress (const char * host, int port);
void AddSSUAddress (const char * host, int port, const uint8_t * key, int mtu = 0);
bool AddIntroducer (const Introducer& introducer);
bool RemoveIntroducer (const boost::asio::ip::udp::endpoint& e);
void SetProperty (const std::string& key, const std::string& value); // called from RouterContext only
void DeleteProperty (const std::string& key); // called from RouterContext only
std::string GetProperty (const std::string& key) const; // called from RouterContext only
void ClearProperties () { m_Properties.clear (); };
bool IsFloodfill () const { return m_Caps & Caps::eFloodfill; };
bool IsReachable () const { return m_Caps & Caps::eReachable; };
bool IsNTCP (bool v4only = true) const;
bool IsSSU (bool v4only = true) const;
bool IsV6 () const;
bool IsV4 () const;
void EnableV6 ();
void DisableV6 ();
void EnableV4 ();
void DisableV4 ();
bool IsCompatible (const RouterInfo& other) const { return m_SupportedTransports & other.m_SupportedTransports; };
bool UsesIntroducer () const;
bool IsIntroducer () const { return m_Caps & eSSUIntroducer; };
bool IsPeerTesting () const { return m_Caps & eSSUTesting; };
bool IsHidden () const { return m_Caps & eHidden; };
bool IsHighBandwidth () const { return m_Caps & RouterInfo::eHighBandwidth; };
bool IsExtraBandwidth () const { return m_Caps & RouterInfo::eExtraBandwidth; };
uint8_t GetCaps () const { return m_Caps; };
void SetCaps (uint8_t caps);
void SetCaps (const char * caps);
void SetUnreachable (bool unreachable) { m_IsUnreachable = unreachable; };
bool IsUnreachable () const { return m_IsUnreachable; };
const uint8_t * GetBuffer () const { return m_Buffer; };
const uint8_t * LoadBuffer (); // load if necessary
int GetBufferLen () const { return m_BufferLen; };
void CreateBuffer (const PrivateKeys& privateKeys);
bool IsUpdated () const { return m_IsUpdated; };
void SetUpdated (bool updated) { m_IsUpdated = updated; };
bool SaveToFile (const std::string& fullPath);
std::shared_ptr<RouterProfile> GetProfile () const;
void SaveProfile () { if (m_Profile) m_Profile->Save (GetIdentHash ()); };
void Update (const uint8_t * buf, int len);
void DeleteBuffer () { delete[] m_Buffer; m_Buffer = nullptr; };
bool IsNewer (const uint8_t * buf, size_t len) const;
/** return true if we are in a router family and the signature is valid */
bool IsFamily(const std::string & fam) const;
// implements RoutingDestination
const IdentHash& GetIdentHash () const { return m_RouterIdentity->GetIdentHash (); };
const uint8_t * GetEncryptionPublicKey () const { return m_RouterIdentity->GetStandardIdentity ().publicKey; };
bool IsDestination () const { return false; };
private:
bool LoadFile ();
void ReadFromFile ();
void ReadFromStream (std::istream& s);
void ReadFromBuffer (bool verifySignature);
void WriteToStream (std::ostream& s) const;
size_t ReadString (char* str, size_t len, std::istream& s) const;
void WriteString (const std::string& str, std::ostream& s) const;
void ExtractCaps (const char * value);
std::shared_ptr<const Address> GetAddress (TransportStyle s, bool v4only, bool v6only = false) const;
void UpdateCapsProperty ();
private:
std::string m_FullPath, m_Family;
std::shared_ptr<const IdentityEx> m_RouterIdentity;
uint8_t * m_Buffer;
size_t m_BufferLen;
uint64_t m_Timestamp;
boost::shared_ptr<Addresses> m_Addresses; // TODO: use std::shared_ptr and std::atomic_store for gcc >= 4.9
std::map<std::string, std::string> m_Properties;
bool m_IsUpdated, m_IsUnreachable;
uint8_t m_SupportedTransports, m_Caps;
mutable std::shared_ptr<RouterProfile> m_Profile;
};
}
}
#endif

989
SAM.cpp
View File

@ -1,989 +0,0 @@
#include <string.h>
#include <stdio.h>
#ifdef _MSC_VER
#include <stdlib.h>
#endif
#include "Base.h"
#include "Identity.h"
#include "Log.h"
#include "Destination.h"
#include "ClientContext.h"
#include "util.h"
#include "SAM.h"
namespace i2p
{
namespace client
{
SAMSocket::SAMSocket (SAMBridge& owner):
m_Owner (owner), m_Socket (m_Owner.GetService ()), m_Timer (m_Owner.GetService ()),
m_BufferOffset (0), m_SocketType (eSAMSocketTypeUnknown), m_IsSilent (false),
m_Stream (nullptr), m_Session (nullptr)
{
}
SAMSocket::~SAMSocket ()
{
Terminate ();
}
void SAMSocket::CloseStream ()
{
if (m_Stream)
{
m_Stream->Close ();
m_Stream.reset ();
}
}
void SAMSocket::Terminate ()
{
CloseStream ();
switch (m_SocketType)
{
case eSAMSocketTypeSession:
m_Owner.CloseSession (m_ID);
break;
case eSAMSocketTypeStream:
{
if (m_Session)
m_Session->DelSocket (shared_from_this ());
break;
}
case eSAMSocketTypeAcceptor:
{
if (m_Session)
{
m_Session->DelSocket (shared_from_this ());
if (m_Session->localDestination)
m_Session->localDestination->StopAcceptingStreams ();
}
break;
}
default:
;
}
m_SocketType = eSAMSocketTypeTerminated;
if (m_Socket.is_open()) m_Socket.close ();
m_Session = nullptr;
}
void SAMSocket::ReceiveHandshake ()
{
m_Socket.async_read_some (boost::asio::buffer(m_Buffer, SAM_SOCKET_BUFFER_SIZE),
std::bind(&SAMSocket::HandleHandshakeReceived, shared_from_this (),
std::placeholders::_1, std::placeholders::_2));
}
void SAMSocket::HandleHandshakeReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
LogPrint (eLogError, "SAM: handshake read error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted)
Terminate ();
}
else
{
m_Buffer[bytes_transferred] = 0;
char * eol = (char *)memchr (m_Buffer, '\n', bytes_transferred);
if (eol)
*eol = 0;
LogPrint (eLogDebug, "SAM: handshake ", m_Buffer);
char * separator = strchr (m_Buffer, ' ');
if (separator)
{
separator = strchr (separator + 1, ' ');
if (separator)
*separator = 0;
}
if (!strcmp (m_Buffer, SAM_HANDSHAKE))
{
std::string version("3.0");
// try to find MIN and MAX, 3.0 if not found
if (separator)
{
separator++;
std::map<std::string, std::string> params;
ExtractParams (separator, params);
//auto it = params.find (SAM_PARAM_MAX);
// TODO: check MIN as well
//if (it != params.end ())
// version = it->second;
}
if (version[0] == '3') // we support v3 (3.0 and 3.1) only
{
#ifdef _MSC_VER
size_t l = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_HANDSHAKE_REPLY, version.c_str ());
#else
size_t l = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_HANDSHAKE_REPLY, version.c_str ());
#endif
boost::asio::async_write (m_Socket, boost::asio::buffer (m_Buffer, l), boost::asio::transfer_all (),
std::bind(&SAMSocket::HandleHandshakeReplySent, shared_from_this (),
std::placeholders::_1, std::placeholders::_2));
}
else
SendMessageReply (SAM_HANDSHAKE_I2P_ERROR, strlen (SAM_HANDSHAKE_I2P_ERROR), true);
}
else
{
LogPrint (eLogError, "SAM: handshake mismatch");
Terminate ();
}
}
}
void SAMSocket::HandleHandshakeReplySent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
LogPrint (eLogError, "SAM: handshake reply send error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted)
Terminate ();
}
else
{
m_Socket.async_read_some (boost::asio::buffer(m_Buffer, SAM_SOCKET_BUFFER_SIZE),
std::bind(&SAMSocket::HandleMessage, shared_from_this (),
std::placeholders::_1, std::placeholders::_2));
}
}
void SAMSocket::SendMessageReply (const char * msg, size_t len, bool close)
{
if (!m_IsSilent)
boost::asio::async_write (m_Socket, boost::asio::buffer (msg, len), boost::asio::transfer_all (),
std::bind(&SAMSocket::HandleMessageReplySent, shared_from_this (),
std::placeholders::_1, std::placeholders::_2, close));
else
{
if (close)
Terminate ();
else
Receive ();
}
}
void SAMSocket::HandleMessageReplySent (const boost::system::error_code& ecode, std::size_t bytes_transferred, bool close)
{
if (ecode)
{
LogPrint (eLogError, "SAM: reply send error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted)
Terminate ();
}
else
{
if (close)
Terminate ();
else
Receive ();
}
}
void SAMSocket::HandleMessage (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
LogPrint (eLogError, "SAM: read error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted)
Terminate ();
}
else if (m_SocketType == eSAMSocketTypeStream)
HandleReceived (ecode, bytes_transferred);
else
{
bytes_transferred += m_BufferOffset;
m_BufferOffset = 0;
m_Buffer[bytes_transferred] = 0;
char * eol = (char *)memchr (m_Buffer, '\n', bytes_transferred);
if (eol)
{
*eol = 0;
char * separator = strchr (m_Buffer, ' ');
if (separator)
{
separator = strchr (separator + 1, ' ');
if (separator)
*separator = 0;
else
separator = eol;
if (!strcmp (m_Buffer, SAM_SESSION_CREATE))
ProcessSessionCreate (separator + 1, bytes_transferred - (separator - m_Buffer) - 1);
else if (!strcmp (m_Buffer, SAM_STREAM_CONNECT))
ProcessStreamConnect (separator + 1, bytes_transferred - (separator - m_Buffer) - 1);
else if (!strcmp (m_Buffer, SAM_STREAM_ACCEPT))
ProcessStreamAccept (separator + 1, bytes_transferred - (separator - m_Buffer) - 1);
else if (!strcmp (m_Buffer, SAM_DEST_GENERATE))
ProcessDestGenerate ();
else if (!strcmp (m_Buffer, SAM_NAMING_LOOKUP))
ProcessNamingLookup (separator + 1, bytes_transferred - (separator - m_Buffer) - 1);
else if (!strcmp (m_Buffer, SAM_DATAGRAM_SEND))
{
size_t len = bytes_transferred - (separator - m_Buffer) - 1;
size_t processed = ProcessDatagramSend (separator + 1, len, eol + 1);
if (processed < len)
{
m_BufferOffset = len - processed;
if (processed > 0)
memmove (m_Buffer, separator + 1 + processed, m_BufferOffset);
else
{
// restore string back
*separator = ' ';
*eol = '\n';
}
}
// since it's SAM v1 reply is not expected
Receive ();
}
else
{
LogPrint (eLogError, "SAM: unexpected message ", m_Buffer);
Terminate ();
}
}
else
{
LogPrint (eLogError, "SAM: malformed message ", m_Buffer);
Terminate ();
}
}
else
{
LogPrint (eLogWarning, "SAM: incomplete message ", bytes_transferred);
m_BufferOffset = bytes_transferred;
// try to receive remaining message
Receive ();
}
}
}
void SAMSocket::ProcessSessionCreate (char * buf, size_t len)
{
LogPrint (eLogDebug, "SAM: session create: ", buf);
std::map<std::string, std::string> params;
ExtractParams (buf, params);
std::string& style = params[SAM_PARAM_STYLE];
std::string& id = params[SAM_PARAM_ID];
std::string& destination = params[SAM_PARAM_DESTINATION];
m_ID = id;
if (m_Owner.FindSession (id))
{
// session exists
SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_ID, strlen(SAM_SESSION_CREATE_DUPLICATED_ID), true);
return;
}
std::shared_ptr<boost::asio::ip::udp::endpoint> forward = nullptr;
if (style == SAM_VALUE_DATAGRAM && params.find(SAM_VALUE_HOST) != params.end() && params.find(SAM_VALUE_PORT) != params.end())
{
// udp forward selected
boost::system::error_code e;
// TODO: support hostnames in udp forward
auto addr = boost::asio::ip::address::from_string(params[SAM_VALUE_HOST], e);
if (e)
{
// not an ip address
SendI2PError("Invalid IP Address in HOST");
return;
}
auto port = std::stoi(params[SAM_VALUE_PORT]);
if (port == -1)
{
SendI2PError("Invalid port");
return;
}
forward = std::make_shared<boost::asio::ip::udp::endpoint>(addr, port);
}
// create destination
m_Session = m_Owner.CreateSession (id, destination == SAM_VALUE_TRANSIENT ? "" : destination, &params);
if (m_Session)
{
m_SocketType = eSAMSocketTypeSession;
if (style == SAM_VALUE_DATAGRAM)
{
m_Session->UDPEndpoint = forward;
auto dest = m_Session->localDestination->CreateDatagramDestination ();
dest->SetReceiver (std::bind (&SAMSocket::HandleI2PDatagramReceive, shared_from_this (),
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5));
}
if (m_Session->localDestination->IsReady ())
SendSessionCreateReplyOk ();
else
{
m_Timer.expires_from_now (boost::posix_time::seconds(SAM_SESSION_READINESS_CHECK_INTERVAL));
m_Timer.async_wait (std::bind (&SAMSocket::HandleSessionReadinessCheckTimer,
shared_from_this (), std::placeholders::_1));
}
}
else
SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_DEST, strlen(SAM_SESSION_CREATE_DUPLICATED_DEST), true);
}
void SAMSocket::HandleSessionReadinessCheckTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
if (m_Session->localDestination->IsReady ())
SendSessionCreateReplyOk ();
else
{
m_Timer.expires_from_now (boost::posix_time::seconds(SAM_SESSION_READINESS_CHECK_INTERVAL));
m_Timer.async_wait (std::bind (&SAMSocket::HandleSessionReadinessCheckTimer,
shared_from_this (), std::placeholders::_1));
}
}
}
void SAMSocket::SendSessionCreateReplyOk ()
{
uint8_t buf[1024];
char priv[1024];
size_t l = m_Session->localDestination->GetPrivateKeys ().ToBuffer (buf, 1024);
size_t l1 = i2p::data::ByteStreamToBase64 (buf, l, priv, 1024);
priv[l1] = 0;
#ifdef _MSC_VER
size_t l2 = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_SESSION_CREATE_REPLY_OK, priv);
#else
size_t l2 = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_SESSION_CREATE_REPLY_OK, priv);
#endif
SendMessageReply (m_Buffer, l2, false);
}
void SAMSocket::ProcessStreamConnect (char * buf, size_t len)
{
LogPrint (eLogDebug, "SAM: stream connect: ", buf);
std::map<std::string, std::string> params;
ExtractParams (buf, params);
std::string& id = params[SAM_PARAM_ID];
std::string& destination = params[SAM_PARAM_DESTINATION];
std::string& silent = params[SAM_PARAM_SILENT];
if (silent == SAM_VALUE_TRUE) m_IsSilent = true;
m_ID = id;
m_Session = m_Owner.FindSession (id);
if (m_Session)
{
auto dest = std::make_shared<i2p::data::IdentityEx> ();
size_t len = dest->FromBase64(destination);
if (len > 0)
{
context.GetAddressBook().InsertAddress(dest);
auto leaseSet = m_Session->localDestination->FindLeaseSet(dest->GetIdentHash());
if (leaseSet)
Connect(leaseSet);
else
{
m_Session->localDestination->RequestDestination(dest->GetIdentHash(),
std::bind(&SAMSocket::HandleConnectLeaseSetRequestComplete,
shared_from_this(), std::placeholders::_1));
}
}
else
SendMessageReply(SAM_SESSION_STATUS_INVALID_KEY, strlen(SAM_SESSION_STATUS_INVALID_KEY), true);
}
else
SendMessageReply (SAM_STREAM_STATUS_INVALID_ID, strlen(SAM_STREAM_STATUS_INVALID_ID), true);
}
void SAMSocket::Connect (std::shared_ptr<const i2p::data::LeaseSet> remote)
{
m_SocketType = eSAMSocketTypeStream;
m_Session->AddSocket (shared_from_this ());
m_Stream = m_Session->localDestination->CreateStream (remote);
m_Stream->Send ((uint8_t *)m_Buffer, 0); // connect
I2PReceive ();
SendMessageReply (SAM_STREAM_STATUS_OK, strlen(SAM_STREAM_STATUS_OK), false);
}
void SAMSocket::HandleConnectLeaseSetRequestComplete (std::shared_ptr<i2p::data::LeaseSet> leaseSet)
{
if (leaseSet)
Connect (leaseSet);
else
{
LogPrint (eLogError, "SAM: destination to connect not found");
SendMessageReply (SAM_STREAM_STATUS_CANT_REACH_PEER, strlen(SAM_STREAM_STATUS_CANT_REACH_PEER), true);
}
}
void SAMSocket::ProcessStreamAccept (char * buf, size_t len)
{
LogPrint (eLogDebug, "SAM: stream accept: ", buf);
std::map<std::string, std::string> params;
ExtractParams (buf, params);
std::string& id = params[SAM_PARAM_ID];
std::string& silent = params[SAM_PARAM_SILENT];
if (silent == SAM_VALUE_TRUE) m_IsSilent = true;
m_ID = id;
m_Session = m_Owner.FindSession (id);
if (m_Session)
{
m_SocketType = eSAMSocketTypeAcceptor;
m_Session->AddSocket (shared_from_this ());
if (!m_Session->localDestination->IsAcceptingStreams ())
m_Session->localDestination->AcceptOnce (std::bind (&SAMSocket::HandleI2PAccept, shared_from_this (), std::placeholders::_1));
SendMessageReply (SAM_STREAM_STATUS_OK, strlen(SAM_STREAM_STATUS_OK), false);
}
else
SendMessageReply (SAM_STREAM_STATUS_INVALID_ID, strlen(SAM_STREAM_STATUS_INVALID_ID), true);
}
size_t SAMSocket::ProcessDatagramSend (char * buf, size_t len, const char * data)
{
LogPrint (eLogDebug, "SAM: datagram send: ", buf, " ", len);
std::map<std::string, std::string> params;
ExtractParams (buf, params);
size_t size = std::stoi(params[SAM_PARAM_SIZE]), offset = data - buf;
if (offset + size <= len)
{
if (m_Session)
{
auto d = m_Session->localDestination->GetDatagramDestination ();
if (d)
{
i2p::data::IdentityEx dest;
dest.FromBase64 (params[SAM_PARAM_DESTINATION]);
d->SendDatagramTo ((const uint8_t *)data, size, dest.GetIdentHash ());
}
else
LogPrint (eLogError, "SAM: missing datagram destination");
}
else
LogPrint (eLogError, "SAM: session is not created from DATAGRAM SEND");
}
else
{
LogPrint (eLogWarning, "SAM: sent datagram size ", size, " exceeds buffer ", len - offset);
return 0; // try to receive more
}
return offset + size;
}
void SAMSocket::ProcessDestGenerate ()
{
LogPrint (eLogDebug, "SAM: dest generate");
auto keys = i2p::data::PrivateKeys::CreateRandomKeys ();
#ifdef _MSC_VER
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_DEST_REPLY,
keys.GetPublic ()->ToBase64 ().c_str (), keys.ToBase64 ().c_str ());
#else
size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_DEST_REPLY,
keys.GetPublic ()->ToBase64 ().c_str (), keys.ToBase64 ().c_str ());
#endif
SendMessageReply (m_Buffer, len, false);
}
void SAMSocket::ProcessNamingLookup (char * buf, size_t len)
{
LogPrint (eLogDebug, "SAM: naming lookup: ", buf);
std::map<std::string, std::string> params;
ExtractParams (buf, params);
std::string& name = params[SAM_PARAM_NAME];
std::shared_ptr<const i2p::data::IdentityEx> identity;
i2p::data::IdentHash ident;
auto dest = m_Session == nullptr ? context.GetSharedLocalDestination() : m_Session->localDestination;
if (name == "ME")
SendNamingLookupReply (dest->GetIdentity ());
else if ((identity = context.GetAddressBook ().GetAddress (name)) != nullptr)
SendNamingLookupReply (identity);
else if (context.GetAddressBook ().GetIdentHash (name, ident))
{
auto leaseSet = dest->FindLeaseSet (ident);
if (leaseSet)
SendNamingLookupReply (leaseSet->GetIdentity ());
else
dest->RequestDestination (ident,
std::bind (&SAMSocket::HandleNamingLookupLeaseSetRequestComplete,
shared_from_this (), std::placeholders::_1, ident));
}
else
{
LogPrint (eLogError, "SAM: naming failed, unknown address ", name);
#ifdef _MSC_VER
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str());
#else
size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str());
#endif
SendMessageReply (m_Buffer, len, false);
}
}
void SAMSocket::SendI2PError(const std::string & msg)
{
LogPrint (eLogError, "SAM: i2p error ", msg);
#ifdef _MSC_VER
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_SESSION_STATUS_I2P_ERROR, msg.c_str());
#else
size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_SESSION_STATUS_I2P_ERROR, msg.c_str());
#endif
SendMessageReply (m_Buffer, len, true);
}
void SAMSocket::HandleNamingLookupLeaseSetRequestComplete (std::shared_ptr<i2p::data::LeaseSet> leaseSet, i2p::data::IdentHash ident)
{
if (leaseSet)
{
context.GetAddressBook ().InsertAddress (leaseSet->GetIdentity ());
SendNamingLookupReply (leaseSet->GetIdentity ());
}
else
{
LogPrint (eLogError, "SAM: naming lookup failed. LeaseSet for ", ident.ToBase32 (), " not found");
#ifdef _MSC_VER
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY,
context.GetAddressBook ().ToAddress (ident).c_str());
#else
size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY,
context.GetAddressBook ().ToAddress (ident).c_str());
#endif
SendMessageReply (m_Buffer, len, false);
}
}
void SAMSocket::SendNamingLookupReply (std::shared_ptr<const i2p::data::IdentityEx> identity)
{
auto base64 = identity->ToBase64 ();
#ifdef _MSC_VER
size_t l = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY, base64.c_str ());
#else
size_t l = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY, base64.c_str ());
#endif
SendMessageReply (m_Buffer, l, false);
}
void SAMSocket::ExtractParams (char * buf, std::map<std::string, std::string>& params)
{
char * separator;
do
{
separator = strchr (buf, ' ');
if (separator) *separator = 0;
char * value = strchr (buf, '=');
if (value)
{
*value = 0;
value++;
params[buf] = value;
}
buf = separator + 1;
}
while (separator);
}
void SAMSocket::Receive ()
{
if (m_BufferOffset >= SAM_SOCKET_BUFFER_SIZE)
{
LogPrint (eLogError, "SAM: Buffer is full, terminate");
Terminate ();
return;
}
m_Socket.async_read_some (boost::asio::buffer(m_Buffer + m_BufferOffset, SAM_SOCKET_BUFFER_SIZE - m_BufferOffset),
std::bind((m_SocketType == eSAMSocketTypeStream) ? &SAMSocket::HandleReceived : &SAMSocket::HandleMessage,
shared_from_this (), std::placeholders::_1, std::placeholders::_2));
}
void SAMSocket::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
LogPrint (eLogError, "SAM: read error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted)
Terminate ();
}
else
{
if (m_Stream)
{
auto s = shared_from_this ();
m_Stream->AsyncSend ((uint8_t *)m_Buffer, bytes_transferred,
[s](const boost::system::error_code& ecode)
{
if (!ecode)
s->Receive ();
else
s->m_Owner.GetService ().post ([s] { s->Terminate (); });
});
}
}
}
void SAMSocket::I2PReceive ()
{
if (m_Stream)
{
if (m_Stream->GetStatus () == i2p::stream::eStreamStatusNew ||
m_Stream->GetStatus () == i2p::stream::eStreamStatusOpen) // regular
{
m_Stream->AsyncReceive (boost::asio::buffer (m_StreamBuffer, SAM_SOCKET_BUFFER_SIZE),
std::bind (&SAMSocket::HandleI2PReceive, shared_from_this (),
std::placeholders::_1, std::placeholders::_2),
SAM_SOCKET_CONNECTION_MAX_IDLE);
}
else // closed by peer
{
// get remaning data
auto len = m_Stream->ReadSome (m_StreamBuffer, SAM_SOCKET_BUFFER_SIZE);
if (len > 0) // still some data
{
boost::asio::async_write (m_Socket, boost::asio::buffer (m_StreamBuffer, len),
std::bind (&SAMSocket::HandleWriteI2PData, shared_from_this (), std::placeholders::_1));
}
else // no more data
Terminate ();
}
}
}
void SAMSocket::HandleI2PReceive (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (ecode)
{
LogPrint (eLogError, "SAM: stream read error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted)
{
if (bytes_transferred > 0)
boost::asio::async_write (m_Socket, boost::asio::buffer (m_StreamBuffer, bytes_transferred),
std::bind (&SAMSocket::HandleWriteI2PData, shared_from_this (), std::placeholders::_1)); // postpone termination
else
{
auto s = shared_from_this ();
m_Owner.GetService ().post ([s] { s->Terminate (); });
}
}
else
{
auto s = shared_from_this ();
m_Owner.GetService ().post ([s] { s->Terminate (); });
}
}
else
{
boost::asio::async_write (m_Socket, boost::asio::buffer (m_StreamBuffer, bytes_transferred),
std::bind (&SAMSocket::HandleWriteI2PData, shared_from_this (), std::placeholders::_1));
}
}
void SAMSocket::HandleWriteI2PData (const boost::system::error_code& ecode)
{
if (ecode)
{
LogPrint (eLogError, "SAM: socket write error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted)
Terminate ();
}
else
I2PReceive ();
}
void SAMSocket::HandleI2PAccept (std::shared_ptr<i2p::stream::Stream> stream)
{
if (stream)
{
LogPrint (eLogDebug, "SAM: incoming I2P connection for session ", m_ID);
m_SocketType = eSAMSocketTypeStream;
m_Stream = stream;
context.GetAddressBook ().InsertAddress (stream->GetRemoteIdentity ());
auto session = m_Owner.FindSession (m_ID);
if (session)
{
// find more pending acceptors
for (auto it: session->ListSockets ())
if (it->m_SocketType == eSAMSocketTypeAcceptor)
{
session->localDestination->AcceptOnce (std::bind (&SAMSocket::HandleI2PAccept, it, std::placeholders::_1));
break;
}
}
if (!m_IsSilent)
{
// get remote peer address
auto ident_ptr = stream->GetRemoteIdentity();
const size_t ident_len = ident_ptr->GetFullLen();
uint8_t* ident = new uint8_t[ident_len];
// send remote peer address as base64
const size_t l = ident_ptr->ToBuffer (ident, ident_len);
const size_t l1 = i2p::data::ByteStreamToBase64 (ident, l, (char *)m_StreamBuffer, SAM_SOCKET_BUFFER_SIZE);
delete[] ident;
m_StreamBuffer[l1] = '\n';
HandleI2PReceive (boost::system::error_code (), l1 +1); // we send identity like it has been received from stream
}
else
I2PReceive ();
}
else
LogPrint (eLogWarning, "SAM: I2P acceptor has been reset");
}
void SAMSocket::HandleI2PDatagramReceive (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
{
LogPrint (eLogDebug, "SAM: datagram received ", len);
auto base64 = from.ToBase64 ();
auto ep = m_Session->UDPEndpoint;
if (ep)
{
// udp forward enabled
size_t bsz = base64.size();
size_t sz = bsz + 1 + len;
// build datagram body
uint8_t * data = new uint8_t[sz];
// Destination
memcpy(data, base64.c_str(), bsz);
// linefeed
data[bsz] = '\n';
// Payload
memcpy(data+bsz+1, buf, len);
// send to remote endpoint
m_Owner.SendTo(data, sz, ep);
delete [] data;
}
else
{
#ifdef _MSC_VER
size_t l = sprintf_s ((char *)m_StreamBuffer, SAM_SOCKET_BUFFER_SIZE, SAM_DATAGRAM_RECEIVED, base64.c_str (), (long unsigned int)len);
#else
size_t l = snprintf ((char *)m_StreamBuffer, SAM_SOCKET_BUFFER_SIZE, SAM_DATAGRAM_RECEIVED, base64.c_str (), (long unsigned int)len);
#endif
if (len < SAM_SOCKET_BUFFER_SIZE - l)
{
memcpy (m_StreamBuffer + l, buf, len);
boost::asio::async_write (m_Socket, boost::asio::buffer (m_StreamBuffer, len + l),
std::bind (&SAMSocket::HandleWriteI2PData, shared_from_this (), std::placeholders::_1));
}
else
LogPrint (eLogWarning, "SAM: received datagram size ", len," exceeds buffer");
}
}
SAMSession::SAMSession (std::shared_ptr<ClientDestination> dest):
localDestination (dest),
UDPEndpoint(nullptr)
{
}
SAMSession::~SAMSession ()
{
CloseStreams();
i2p::client::context.DeleteLocalDestination (localDestination);
}
void SAMSession::CloseStreams ()
{
{
std::lock_guard<std::mutex> lock(m_SocketsMutex);
for (auto& sock : m_Sockets) {
sock->CloseStream();
}
}
// XXX: should this be done inside locked parts?
m_Sockets.clear();
}
SAMBridge::SAMBridge (const std::string& address, int port):
m_IsRunning (false), m_Thread (nullptr),
m_Acceptor (m_Service, boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(address), port)),
m_DatagramEndpoint (boost::asio::ip::address::from_string(address), port-1), m_DatagramSocket (m_Service, m_DatagramEndpoint)
{
}
SAMBridge::~SAMBridge ()
{
if (m_IsRunning)
Stop ();
}
void SAMBridge::Start ()
{
Accept ();
ReceiveDatagram ();
m_IsRunning = true;
m_Thread = new std::thread (std::bind (&SAMBridge::Run, this));
}
void SAMBridge::Stop ()
{
m_IsRunning = false;
m_Acceptor.cancel ();
for (auto& it: m_Sessions)
it.second->CloseStreams ();
m_Sessions.clear ();
m_Service.stop ();
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = nullptr;
}
}
void SAMBridge::Run ()
{
while (m_IsRunning)
{
try
{
m_Service.run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "SAM: runtime exception: ", ex.what ());
}
}
}
void SAMBridge::Accept ()
{
auto newSocket = std::make_shared<SAMSocket> (*this);
m_Acceptor.async_accept (newSocket->GetSocket (), std::bind (&SAMBridge::HandleAccept, this,
std::placeholders::_1, newSocket));
}
void SAMBridge::HandleAccept(const boost::system::error_code& ecode, std::shared_ptr<SAMSocket> socket)
{
if (!ecode)
{
boost::system::error_code ec;
auto ep = socket->GetSocket ().remote_endpoint (ec);
if (!ec)
{
LogPrint (eLogDebug, "SAM: new connection from ", ep);
socket->ReceiveHandshake ();
}
else
LogPrint (eLogError, "SAM: incoming connection error ", ec.message ());
}
else
LogPrint (eLogError, "SAM: accept error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted)
Accept ();
}
std::shared_ptr<SAMSession> SAMBridge::CreateSession (const std::string& id, const std::string& destination,
const std::map<std::string, std::string> * params)
{
std::shared_ptr<ClientDestination> localDestination = nullptr;
if (destination != "")
{
i2p::data::PrivateKeys keys;
keys.FromBase64 (destination);
localDestination = i2p::client::context.CreateNewLocalDestination (keys, true, params);
}
else // transient
{
// extract signature type
i2p::data::SigningKeyType signatureType = i2p::data::SIGNING_KEY_TYPE_DSA_SHA1;
if (params)
{
auto it = params->find (SAM_PARAM_SIGNATURE_TYPE);
if (it != params->end ())
// TODO: extract string values
signatureType = std::stoi(it->second);
}
localDestination = i2p::client::context.CreateNewLocalDestination (true, signatureType, params);
}
if (localDestination)
{
auto session = std::make_shared<SAMSession>(localDestination);
std::unique_lock<std::mutex> l(m_SessionsMutex);
auto ret = m_Sessions.insert (std::make_pair(id, session));
if (!ret.second)
LogPrint (eLogWarning, "SAM: Session ", id, " already exists");
return ret.first->second;
}
return nullptr;
}
void SAMBridge::CloseSession (const std::string& id)
{
std::shared_ptr<SAMSession> session;
{
std::unique_lock<std::mutex> l(m_SessionsMutex);
auto it = m_Sessions.find (id);
if (it != m_Sessions.end ())
{
session = it->second;
m_Sessions.erase (it);
}
}
if (session)
{
session->localDestination->StopAcceptingStreams ();
session->CloseStreams ();
}
}
std::shared_ptr<SAMSession> SAMBridge::FindSession (const std::string& id) const
{
std::unique_lock<std::mutex> l(m_SessionsMutex);
auto it = m_Sessions.find (id);
if (it != m_Sessions.end ())
return it->second;
return nullptr;
}
void SAMBridge::SendTo(const uint8_t * buf, size_t len, std::shared_ptr<boost::asio::ip::udp::endpoint> remote)
{
if(remote)
{
m_DatagramSocket.send_to(boost::asio::buffer(buf, len), *remote);
}
}
void SAMBridge::ReceiveDatagram ()
{
m_DatagramSocket.async_receive_from (
boost::asio::buffer (m_DatagramReceiveBuffer, i2p::datagram::MAX_DATAGRAM_SIZE),
m_SenderEndpoint,
std::bind (&SAMBridge::HandleReceivedDatagram, this, std::placeholders::_1, std::placeholders::_2));
}
void SAMBridge::HandleReceivedDatagram (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (!ecode)
{
m_DatagramReceiveBuffer[bytes_transferred] = 0;
char * eol = strchr ((char *)m_DatagramReceiveBuffer, '\n');
*eol = 0; eol++;
size_t payloadLen = bytes_transferred - ((uint8_t *)eol - m_DatagramReceiveBuffer);
LogPrint (eLogDebug, "SAM: datagram received ", m_DatagramReceiveBuffer," size=", payloadLen);
char * sessionID = strchr ((char *)m_DatagramReceiveBuffer, ' ');
if (sessionID)
{
sessionID++;
char * destination = strchr (sessionID, ' ');
if (destination)
{
*destination = 0; destination++;
auto session = FindSession (sessionID);
if (session)
{
i2p::data::IdentityEx dest;
dest.FromBase64 (destination);
session->localDestination->GetDatagramDestination ()->
SendDatagramTo ((uint8_t *)eol, payloadLen, dest.GetIdentHash ());
}
else
LogPrint (eLogError, "SAM: Session ", sessionID, " not found");
}
else
LogPrint (eLogError, "SAM: Missing destination key");
}
else
LogPrint (eLogError, "SAM: Missing sessionID");
ReceiveDatagram ();
}
else
LogPrint (eLogError, "SAM: datagram receive error: ", ecode.message ());
}
}
}

782
SSU.cpp
View File

@ -1,782 +0,0 @@
#include <string.h>
#include <boost/bind.hpp>
#include "Log.h"
#include "Timestamp.h"
#include "RouterContext.h"
#include "NetDb.h"
#include "SSU.h"
namespace i2p
{
namespace transport
{
SSUServer::SSUServer (const boost::asio::ip::address & addr, int port):
m_OnlyV6(true), m_IsRunning(false),
m_Thread (nullptr), m_ThreadV6 (nullptr), m_ReceiversThread (nullptr),
m_ReceiversThreadV6 (nullptr), m_Work (m_Service), m_WorkV6 (m_ServiceV6),
m_ReceiversWork (m_ReceiversService), m_ReceiversWorkV6 (m_ReceiversServiceV6),
m_EndpointV6 (addr, port), m_Socket (m_ReceiversService, m_Endpoint),
m_SocketV6 (m_ReceiversServiceV6), m_IntroducersUpdateTimer (m_Service),
m_PeerTestsCleanupTimer (m_Service), m_TerminationTimer (m_Service),
m_TerminationTimerV6 (m_ServiceV6)
{
OpenSocketV6 ();
}
SSUServer::SSUServer (int port):
m_OnlyV6(false), m_IsRunning(false),
m_Thread (nullptr), m_ThreadV6 (nullptr), m_ReceiversThread (nullptr),
m_ReceiversThreadV6 (nullptr), m_Work (m_Service), m_WorkV6 (m_ServiceV6),
m_ReceiversWork (m_ReceiversService), m_ReceiversWorkV6 (m_ReceiversServiceV6),
m_Endpoint (boost::asio::ip::udp::v4 (), port), m_EndpointV6 (boost::asio::ip::udp::v6 (), port),
m_Socket (m_ReceiversService), m_SocketV6 (m_ReceiversServiceV6),
m_IntroducersUpdateTimer (m_Service), m_PeerTestsCleanupTimer (m_Service),
m_TerminationTimer (m_Service), m_TerminationTimerV6 (m_ServiceV6)
{
OpenSocket ();
if (context.SupportsV6 ())
OpenSocketV6 ();
}
SSUServer::~SSUServer ()
{
}
void SSUServer::OpenSocket ()
{
m_Socket.open (boost::asio::ip::udp::v4());
m_Socket.set_option (boost::asio::socket_base::receive_buffer_size (SSU_SOCKET_RECEIVE_BUFFER_SIZE));
m_Socket.set_option (boost::asio::socket_base::send_buffer_size (SSU_SOCKET_SEND_BUFFER_SIZE));
m_Socket.bind (m_Endpoint);
}
void SSUServer::OpenSocketV6 ()
{
m_SocketV6.open (boost::asio::ip::udp::v6());
m_SocketV6.set_option (boost::asio::ip::v6_only (true));
m_SocketV6.set_option (boost::asio::socket_base::receive_buffer_size (SSU_SOCKET_RECEIVE_BUFFER_SIZE));
m_SocketV6.set_option (boost::asio::socket_base::send_buffer_size (SSU_SOCKET_SEND_BUFFER_SIZE));
m_SocketV6.bind (m_EndpointV6);
}
void SSUServer::Start ()
{
m_IsRunning = true;
if (!m_OnlyV6)
{
m_ReceiversThread = new std::thread (std::bind (&SSUServer::RunReceivers, this));
m_Thread = new std::thread (std::bind (&SSUServer::Run, this));
m_ReceiversService.post (std::bind (&SSUServer::Receive, this));
ScheduleTermination ();
}
if (context.SupportsV6 ())
{
m_ReceiversThreadV6 = new std::thread (std::bind (&SSUServer::RunReceiversV6, this));
m_ThreadV6 = new std::thread (std::bind (&SSUServer::RunV6, this));
m_ReceiversServiceV6.post (std::bind (&SSUServer::ReceiveV6, this));
ScheduleTerminationV6 ();
}
SchedulePeerTestsCleanupTimer ();
ScheduleIntroducersUpdateTimer (); // wait for 30 seconds and decide if we need introducers
}
void SSUServer::Stop ()
{
DeleteAllSessions ();
m_IsRunning = false;
m_TerminationTimer.cancel ();
m_TerminationTimerV6.cancel ();
m_Service.stop ();
m_Socket.close ();
m_ServiceV6.stop ();
m_SocketV6.close ();
m_ReceiversService.stop ();
m_ReceiversServiceV6.stop ();
if (m_ReceiversThread)
{
m_ReceiversThread->join ();
delete m_ReceiversThread;
m_ReceiversThread = nullptr;
}
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = nullptr;
}
if (m_ReceiversThreadV6)
{
m_ReceiversThreadV6->join ();
delete m_ReceiversThreadV6;
m_ReceiversThreadV6 = nullptr;
}
if (m_ThreadV6)
{
m_ThreadV6->join ();
delete m_ThreadV6;
m_ThreadV6 = nullptr;
}
}
void SSUServer::Run ()
{
while (m_IsRunning)
{
try
{
m_Service.run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "SSU: server runtime exception: ", ex.what ());
}
}
}
void SSUServer::RunV6 ()
{
while (m_IsRunning)
{
try
{
m_ServiceV6.run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "SSU: v6 server runtime exception: ", ex.what ());
}
}
}
void SSUServer::RunReceivers ()
{
while (m_IsRunning)
{
try
{
m_ReceiversService.run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "SSU: receivers runtime exception: ", ex.what ());
}
}
}
void SSUServer::RunReceiversV6 ()
{
while (m_IsRunning)
{
try
{
m_ReceiversServiceV6.run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "SSU: v6 receivers runtime exception: ", ex.what ());
}
}
}
void SSUServer::AddRelay (uint32_t tag, std::shared_ptr<SSUSession> relay)
{
m_Relays[tag] = relay;
}
void SSUServer::RemoveRelay (uint32_t tag)
{
m_Relays.erase (tag);
}
std::shared_ptr<SSUSession> SSUServer::FindRelaySession (uint32_t tag)
{
auto it = m_Relays.find (tag);
if (it != m_Relays.end ())
{
if (it->second->GetState () == eSessionStateEstablished)
return it->second;
else
m_Relays.erase (it);
}
return nullptr;
}
void SSUServer::Send (const uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& to)
{
if (to.protocol () == boost::asio::ip::udp::v4())
m_Socket.send_to (boost::asio::buffer (buf, len), to);
else
m_SocketV6.send_to (boost::asio::buffer (buf, len), to);
}
void SSUServer::Receive ()
{
SSUPacket * packet = new SSUPacket ();
m_Socket.async_receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V4), packet->from,
std::bind (&SSUServer::HandleReceivedFrom, this, std::placeholders::_1, std::placeholders::_2, packet));
}
void SSUServer::ReceiveV6 ()
{
SSUPacket * packet = new SSUPacket ();
m_SocketV6.async_receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V6), packet->from,
std::bind (&SSUServer::HandleReceivedFromV6, this, std::placeholders::_1, std::placeholders::_2, packet));
}
void SSUServer::HandleReceivedFrom (const boost::system::error_code& ecode, std::size_t bytes_transferred, SSUPacket * packet)
{
if (!ecode)
{
packet->len = bytes_transferred;
std::vector<SSUPacket *> packets;
packets.push_back (packet);
boost::system::error_code ec;
size_t moreBytes = m_Socket.available(ec);
if (!ec)
{
while (moreBytes && packets.size () < 25)
{
packet = new SSUPacket ();
packet->len = m_Socket.receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V4), packet->from, 0, ec);
if (!ec)
{
packets.push_back (packet);
moreBytes = m_Socket.available(ec);
if (ec) break;
}
else
{
LogPrint (eLogError, "SSU: receive_from error: ", ec.message ());
delete packet;
break;
}
}
}
m_Service.post (std::bind (&SSUServer::HandleReceivedPackets, this, packets, &m_Sessions));
Receive ();
}
else
{
delete packet;
if (ecode != boost::asio::error::operation_aborted)
{
LogPrint (eLogError, "SSU: receive error: ", ecode.message ());
m_Socket.close ();
OpenSocket ();
Receive ();
}
}
}
void SSUServer::HandleReceivedFromV6 (const boost::system::error_code& ecode, std::size_t bytes_transferred, SSUPacket * packet)
{
if (!ecode)
{
packet->len = bytes_transferred;
std::vector<SSUPacket *> packets;
packets.push_back (packet);
boost::system::error_code ec;
size_t moreBytes = m_SocketV6.available (ec);
if (!ec)
{
while (moreBytes && packets.size () < 25)
{
packet = new SSUPacket ();
packet->len = m_SocketV6.receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V6), packet->from, 0, ec);
if (!ec)
{
packets.push_back (packet);
moreBytes = m_SocketV6.available(ec);
if (ec) break;
}
else
{
LogPrint (eLogError, "SSU: v6 receive_from error: ", ec.message ());
delete packet;
break;
}
}
}
m_ServiceV6.post (std::bind (&SSUServer::HandleReceivedPackets, this, packets, &m_SessionsV6));
ReceiveV6 ();
}
else
{
delete packet;
if (ecode != boost::asio::error::operation_aborted)
{
LogPrint (eLogError, "SSU: v6 receive error: ", ecode.message ());
m_SocketV6.close ();
OpenSocketV6 ();
ReceiveV6 ();
}
}
}
void SSUServer::HandleReceivedPackets (std::vector<SSUPacket *> packets,
std::map<boost::asio::ip::udp::endpoint, std::shared_ptr<SSUSession> > * sessions)
{
std::shared_ptr<SSUSession> session;
for (auto& packet: packets)
{
try
{
if (!session || session->GetRemoteEndpoint () != packet->from) // we received packet for other session than previous
{
if (session) session->FlushData ();
auto it = sessions->find (packet->from);
if (it != sessions->end ())
session = it->second;
if (!session)
{
session = std::make_shared<SSUSession> (*this, packet->from);
session->WaitForConnect ();
(*sessions)[packet->from] = session;
LogPrint (eLogDebug, "SSU: new session from ", packet->from.address ().to_string (), ":", packet->from.port (), " created");
}
}
session->ProcessNextMessage (packet->buf, packet->len, packet->from);
}
catch (std::exception& ex)
{
LogPrint (eLogError, "SSU: HandleReceivedPackets ", ex.what ());
if (session) session->FlushData ();
session = nullptr;
}
delete packet;
}
if (session) session->FlushData ();
}
std::shared_ptr<SSUSession> SSUServer::FindSession (std::shared_ptr<const i2p::data::RouterInfo> router) const
{
if (!router) return nullptr;
auto address = router->GetSSUAddress (true); // v4 only
if (!address) return nullptr;
auto session = FindSession (boost::asio::ip::udp::endpoint (address->host, address->port));
if (session || !context.SupportsV6 ())
return session;
// try v6
address = router->GetSSUV6Address ();
if (!address) return nullptr;
return FindSession (boost::asio::ip::udp::endpoint (address->host, address->port));
}
std::shared_ptr<SSUSession> SSUServer::FindSession (const boost::asio::ip::udp::endpoint& e) const
{
auto& sessions = e.address ().is_v6 () ? m_SessionsV6 : m_Sessions;
auto it = sessions.find (e);
if (it != sessions.end ())
return it->second;
else
return nullptr;
}
void SSUServer::CreateSession (std::shared_ptr<const i2p::data::RouterInfo> router, bool peerTest, bool v4only)
{
auto address = router->GetSSUAddress (v4only || !context.SupportsV6 ());
if (address)
CreateSession (router, address->host, address->port, peerTest);
else
LogPrint (eLogWarning, "SSU: Router ", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()), " doesn't have SSU address");
}
void SSUServer::CreateSession (std::shared_ptr<const i2p::data::RouterInfo> router,
const boost::asio::ip::address& addr, int port, bool peerTest)
{
if (router)
{
if (router->UsesIntroducer ())
m_Service.post (std::bind (&SSUServer::CreateSessionThroughIntroducer, this, router, peerTest)); // always V4 thread
else
{
boost::asio::ip::udp::endpoint remoteEndpoint (addr, port);
auto& s = addr.is_v6 () ? m_ServiceV6 : m_Service;
s.post (std::bind (&SSUServer::CreateDirectSession, this, router, remoteEndpoint, peerTest));
}
}
}
void SSUServer::CreateDirectSession (std::shared_ptr<const i2p::data::RouterInfo> router, boost::asio::ip::udp::endpoint remoteEndpoint, bool peerTest)
{
auto& sessions = remoteEndpoint.address ().is_v6 () ? m_SessionsV6 : m_Sessions;
auto it = sessions.find (remoteEndpoint);
if (it != sessions.end ())
{
auto session = it->second;
if (peerTest && session->GetState () == eSessionStateEstablished)
session->SendPeerTest ();
}
else
{
// otherwise create new session
auto session = std::make_shared<SSUSession> (*this, remoteEndpoint, router, peerTest);
sessions[remoteEndpoint] = session;
// connect
LogPrint (eLogDebug, "SSU: Creating new session to [", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()), "] ",
remoteEndpoint.address ().to_string (), ":", remoteEndpoint.port ());
session->Connect ();
}
}
void SSUServer::CreateSessionThroughIntroducer (std::shared_ptr<const i2p::data::RouterInfo> router, bool peerTest)
{
if (router && router->UsesIntroducer ())
{
auto address = router->GetSSUAddress (true); // v4 only for now
if (address)
{
boost::asio::ip::udp::endpoint remoteEndpoint (address->host, address->port);
auto it = m_Sessions.find (remoteEndpoint);
// check if session if presented alredy
if (it != m_Sessions.end ())
{
auto session = it->second;
if (peerTest && session->GetState () == eSessionStateEstablished)
session->SendPeerTest ();
return;
}
// create new session
int numIntroducers = address->ssu->introducers.size ();
if (numIntroducers > 0)
{
std::shared_ptr<SSUSession> introducerSession;
const i2p::data::RouterInfo::Introducer * introducer = nullptr;
// we might have a session to introducer already
for (int i = 0; i < numIntroducers; i++)
{
auto intr = &(address->ssu->introducers[i]);
boost::asio::ip::udp::endpoint ep (intr->iHost, intr->iPort);
if (ep.address ().is_v4 ()) // ipv4 only
{
if (!introducer) introducer = intr; // we pick first one for now
it = m_Sessions.find (ep);
if (it != m_Sessions.end ())
{
introducerSession = it->second;
break;
}
}
}
if (!introducer)
{
LogPrint (eLogWarning, "SSU: Can't connect to unreachable router and no ipv4 introducers present");
return;
}
if (introducerSession) // session found
LogPrint (eLogWarning, "SSU: Session to introducer already exists");
else // create new
{
LogPrint (eLogDebug, "SSU: Creating new session to introducer ", introducer->iHost);
boost::asio::ip::udp::endpoint introducerEndpoint (introducer->iHost, introducer->iPort);
introducerSession = std::make_shared<SSUSession> (*this, introducerEndpoint, router);
m_Sessions[introducerEndpoint] = introducerSession;
}
// create session
auto session = std::make_shared<SSUSession> (*this, remoteEndpoint, router, peerTest);
m_Sessions[remoteEndpoint] = session;
// introduce
LogPrint (eLogInfo, "SSU: Introduce new session to [", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()),
"] through introducer ", introducer->iHost, ":", introducer->iPort);
session->WaitForIntroduction ();
if (i2p::context.GetRouterInfo ().UsesIntroducer ()) // if we are unreachable
{
uint8_t buf[1];
Send (buf, 0, remoteEndpoint); // send HolePunch
}
introducerSession->Introduce (*introducer, router);
}
else
LogPrint (eLogWarning, "SSU: Can't connect to unreachable router and no introducers present");
}
else
LogPrint (eLogWarning, "SSU: Router ", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()), " doesn't have SSU address");
}
}
void SSUServer::DeleteSession (std::shared_ptr<SSUSession> session)
{
if (session)
{
session->Close ();
auto& ep = session->GetRemoteEndpoint ();
if (ep.address ().is_v6 ())
m_SessionsV6.erase (ep);
else
m_Sessions.erase (ep);
}
}
void SSUServer::DeleteAllSessions ()
{
for (auto& it: m_Sessions)
it.second->Close ();
m_Sessions.clear ();
for (auto& it: m_SessionsV6)
it.second->Close ();
m_SessionsV6.clear ();
}
template<typename Filter>
std::shared_ptr<SSUSession> SSUServer::GetRandomV4Session (Filter filter) // v4 only
{
std::vector<std::shared_ptr<SSUSession> > filteredSessions;
for (const auto& s :m_Sessions)
if (filter (s.second)) filteredSessions.push_back (s.second);
if (filteredSessions.size () > 0)
{
auto ind = rand () % filteredSessions.size ();
return filteredSessions[ind];
}
return nullptr;
}
std::shared_ptr<SSUSession> SSUServer::GetRandomEstablishedV4Session (std::shared_ptr<const SSUSession> excluded) // v4 only
{
return GetRandomV4Session (
[excluded](std::shared_ptr<SSUSession> session)->bool
{
return session->GetState () == eSessionStateEstablished && session != excluded;
}
);
}
template<typename Filter>
std::shared_ptr<SSUSession> SSUServer::GetRandomV6Session (Filter filter) // v6 only
{
std::vector<std::shared_ptr<SSUSession> > filteredSessions;
for (const auto& s :m_SessionsV6)
if (filter (s.second)) filteredSessions.push_back (s.second);
if (filteredSessions.size () > 0)
{
auto ind = rand () % filteredSessions.size ();
return filteredSessions[ind];
}
return nullptr;
}
std::shared_ptr<SSUSession> SSUServer::GetRandomEstablishedV6Session (std::shared_ptr<const SSUSession> excluded) // v6 only
{
return GetRandomV6Session (
[excluded](std::shared_ptr<SSUSession> session)->bool
{
return session->GetState () == eSessionStateEstablished && session != excluded;
}
);
}
std::set<SSUSession *> SSUServer::FindIntroducers (int maxNumIntroducers)
{
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
std::set<SSUSession *> ret;
for (int i = 0; i < maxNumIntroducers; i++)
{
auto session = GetRandomV4Session (
[&ret, ts](std::shared_ptr<SSUSession> session)->bool
{
return session->GetRelayTag () && !ret.count (session.get ()) &&
session->GetState () == eSessionStateEstablished &&
ts < session->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_DURATION;
}
);
if (session)
{
ret.insert (session.get ());
break;
}
}
return ret;
}
void SSUServer::ScheduleIntroducersUpdateTimer ()
{
m_IntroducersUpdateTimer.expires_from_now (boost::posix_time::seconds(SSU_KEEP_ALIVE_INTERVAL));
m_IntroducersUpdateTimer.async_wait (std::bind (&SSUServer::HandleIntroducersUpdateTimer,
this, std::placeholders::_1));
}
void SSUServer::HandleIntroducersUpdateTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
// timeout expired
if (i2p::context.GetStatus () == eRouterStatusTesting)
{
// we still don't know if we need introducers
ScheduleIntroducersUpdateTimer ();
return;
}
if (i2p::context.GetStatus () == eRouterStatusOK) return; // we don't need introducers anymore
// we are firewalled
if (!i2p::context.IsUnreachable ()) i2p::context.SetUnreachable ();
std::list<boost::asio::ip::udp::endpoint> newList;
size_t numIntroducers = 0;
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
for (const auto& it : m_Introducers)
{
auto session = FindSession (it);
if (session && ts < session->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_DURATION)
{
session->SendKeepAlive ();
newList.push_back (it);
numIntroducers++;
}
else
i2p::context.RemoveIntroducer (it);
}
if (numIntroducers < SSU_MAX_NUM_INTRODUCERS)
{
// create new
auto introducers = FindIntroducers (SSU_MAX_NUM_INTRODUCERS);
for (const auto& it1: introducers)
{
const auto& ep = it1->GetRemoteEndpoint ();
i2p::data::RouterInfo::Introducer introducer;
introducer.iHost = ep.address ();
introducer.iPort = ep.port ();
introducer.iTag = it1->GetRelayTag ();
introducer.iKey = it1->GetIntroKey ();
if (i2p::context.AddIntroducer (introducer))
{
newList.push_back (ep);
if (newList.size () >= SSU_MAX_NUM_INTRODUCERS) break;
}
}
}
m_Introducers = newList;
if (m_Introducers.size () < SSU_MAX_NUM_INTRODUCERS)
{
auto introducer = i2p::data::netdb.GetRandomIntroducer ();
if (introducer)
CreateSession (introducer);
}
ScheduleIntroducersUpdateTimer ();
}
}
void SSUServer::NewPeerTest (uint32_t nonce, PeerTestParticipant role, std::shared_ptr<SSUSession> session)
{
m_PeerTests[nonce] = { i2p::util::GetMillisecondsSinceEpoch (), role, session };
}
PeerTestParticipant SSUServer::GetPeerTestParticipant (uint32_t nonce)
{
auto it = m_PeerTests.find (nonce);
if (it != m_PeerTests.end ())
return it->second.role;
else
return ePeerTestParticipantUnknown;
}
std::shared_ptr<SSUSession> SSUServer::GetPeerTestSession (uint32_t nonce)
{
auto it = m_PeerTests.find (nonce);
if (it != m_PeerTests.end ())
return it->second.session;
else
return nullptr;
}
void SSUServer::UpdatePeerTest (uint32_t nonce, PeerTestParticipant role)
{
auto it = m_PeerTests.find (nonce);
if (it != m_PeerTests.end ())
it->second.role = role;
}
void SSUServer::RemovePeerTest (uint32_t nonce)
{
m_PeerTests.erase (nonce);
}
void SSUServer::SchedulePeerTestsCleanupTimer ()
{
m_PeerTestsCleanupTimer.expires_from_now (boost::posix_time::seconds(SSU_PEER_TEST_TIMEOUT));
m_PeerTestsCleanupTimer.async_wait (std::bind (&SSUServer::HandlePeerTestsCleanupTimer,
this, std::placeholders::_1));
}
void SSUServer::HandlePeerTestsCleanupTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
int numDeleted = 0;
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
for (auto it = m_PeerTests.begin (); it != m_PeerTests.end ();)
{
if (ts > it->second.creationTime + SSU_PEER_TEST_TIMEOUT*1000LL)
{
numDeleted++;
it = m_PeerTests.erase (it);
}
else
++it;
}
if (numDeleted > 0)
LogPrint (eLogDebug, "SSU: ", numDeleted, " peer tests have been expired");
SchedulePeerTestsCleanupTimer ();
}
}
void SSUServer::ScheduleTermination ()
{
m_TerminationTimer.expires_from_now (boost::posix_time::seconds(SSU_TERMINATION_CHECK_TIMEOUT));
m_TerminationTimer.async_wait (std::bind (&SSUServer::HandleTerminationTimer,
this, std::placeholders::_1));
}
void SSUServer::HandleTerminationTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
auto ts = i2p::util::GetSecondsSinceEpoch ();
for (auto& it: m_Sessions)
if (it.second->IsTerminationTimeoutExpired (ts))
{
auto session = it.second;
m_Service.post ([session]
{
LogPrint (eLogWarning, "SSU: no activity with ", session->GetRemoteEndpoint (), " for ", session->GetTerminationTimeout (), " seconds");
session->Failed ();
});
}
ScheduleTermination ();
}
}
void SSUServer::ScheduleTerminationV6 ()
{
m_TerminationTimerV6.expires_from_now (boost::posix_time::seconds(SSU_TERMINATION_CHECK_TIMEOUT));
m_TerminationTimerV6.async_wait (std::bind (&SSUServer::HandleTerminationTimerV6,
this, std::placeholders::_1));
}
void SSUServer::HandleTerminationTimerV6 (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
auto ts = i2p::util::GetSecondsSinceEpoch ();
for (auto& it: m_SessionsV6)
if (it.second->IsTerminationTimeoutExpired (ts))
{
auto session = it.second;
m_ServiceV6.post ([session]
{
LogPrint (eLogWarning, "SSU: no activity with ", session->GetRemoteEndpoint (), " for ", session->GetTerminationTimeout (), " seconds");
session->Failed ();
});
}
ScheduleTerminationV6 ();
}
}
}
}

View File

@ -1,501 +0,0 @@
#include <memory>
#include "Log.h"
#include "Signature.h"
namespace i2p
{
namespace crypto
{
class Ed25519
{
public:
Ed25519 ()
{
BN_CTX * ctx = BN_CTX_new ();
BIGNUM * tmp = BN_new ();
q = BN_new ();
// 2^255-19
BN_set_bit (q, 255); // 2^255
BN_sub_word (q, 19);
l = BN_new ();
// 2^252 + 27742317777372353535851937790883648493
BN_set_bit (l, 252);
two_252_2 = BN_dup (l);
BN_dec2bn (&tmp, "27742317777372353535851937790883648493");
BN_add (l, l, tmp);
BN_sub_word (two_252_2, 2); // 2^252 - 2
// -121665*inv(121666)
d = BN_new ();
BN_set_word (tmp, 121666);
BN_mod_inverse (tmp, tmp, q, ctx);
BN_set_word (d, 121665);
BN_set_negative (d, 1);
BN_mul (d, d, tmp, ctx);
// 2^((q-1)/4)
I = BN_new ();
BN_free (tmp);
tmp = BN_dup (q);
BN_sub_word (tmp, 1);
BN_div_word (tmp, 4);
BN_set_word (I, 2);
BN_mod_exp (I, I, tmp, q, ctx);
BN_free (tmp);
// 4*inv(5)
BIGNUM * By = BN_new ();
BN_set_word (By, 5);
BN_mod_inverse (By, By, q, ctx);
BN_mul_word (By, 4);
BIGNUM * Bx = RecoverX (By, ctx);
BN_mod (Bx, Bx, q, ctx); // % q
BN_mod (By, By, q, ctx); // % q
// precalculate Bi256 table
Bi256Carry = { Bx, By }; // B
for (int i = 0; i < 32; i++)
{
Bi256[i][0] = Bi256Carry; // first point
for (int j = 1; j < 128; j++)
Bi256[i][j] = Sum (Bi256[i][j-1], Bi256[i][0], ctx); // (256+j+1)^i*B
Bi256Carry = Bi256[i][127];
for (int j = 0; j < 128; j++) // add first point 128 more times
Bi256Carry = Sum (Bi256Carry, Bi256[i][0], ctx);
}
BN_CTX_free (ctx);
}
Ed25519 (const Ed25519& other): q (BN_dup (other.q)), l (BN_dup (other.l)),
d (BN_dup (other.d)), I (BN_dup (other.I)), two_252_2 (BN_dup (other.two_252_2)),
Bi256Carry (other.Bi256Carry)
{
for (int i = 0; i < 32; i++)
for (int j = 0; j < 128; j++)
Bi256[i][j] = other.Bi256[i][j];
}
~Ed25519 ()
{
BN_free (q);
BN_free (l);
BN_free (d);
BN_free (I);
BN_free (two_252_2);
}
EDDSAPoint GeneratePublicKey (const uint8_t * expandedPrivateKey, BN_CTX * ctx) const
{
return MulB (expandedPrivateKey, ctx); // left half of expanded key, considered as Little Endian
}
EDDSAPoint DecodePublicKey (const uint8_t * buf, BN_CTX * ctx) const
{
return DecodePoint (buf, ctx);
}
void EncodePublicKey (const EDDSAPoint& publicKey, uint8_t * buf, BN_CTX * ctx) const
{
EncodePoint (Normalize (publicKey, ctx), buf);
}
bool Verify (const EDDSAPoint& publicKey, const uint8_t * digest, const uint8_t * signature) const
{
BN_CTX * ctx = BN_CTX_new ();
BIGNUM * h = DecodeBN<64> (digest);
// signature 0..31 - R, 32..63 - S
// B*S = R + PK*h => R = B*S - PK*h
// we don't decode R, but encode (B*S - PK*h)
auto Bs = MulB (signature + EDDSA25519_SIGNATURE_LENGTH/2, ctx); // B*S;
BN_mod (h, h, l, ctx); // public key is multiple of B, but B%l = 0
auto PKh = Mul (publicKey, h, ctx); // PK*h
uint8_t diff[32];
EncodePoint (Normalize (Sum (Bs, -PKh, ctx), ctx), diff); // Bs - PKh encoded
bool passed = !memcmp (signature, diff, 32); // R
BN_free (h);
BN_CTX_free (ctx);
if (!passed)
LogPrint (eLogError, "25519 signature verification failed");
return passed;
}
void Sign (const uint8_t * expandedPrivateKey, const uint8_t * publicKeyEncoded, const uint8_t * buf, size_t len,
uint8_t * signature) const
{
BN_CTX * bnCtx = BN_CTX_new ();
// calculate r
SHA512_CTX ctx;
SHA512_Init (&ctx);
SHA512_Update (&ctx, expandedPrivateKey + EDDSA25519_PRIVATE_KEY_LENGTH, EDDSA25519_PRIVATE_KEY_LENGTH); // right half of expanded key
SHA512_Update (&ctx, buf, len); // data
uint8_t digest[64];
SHA512_Final (digest, &ctx);
BIGNUM * r = DecodeBN<32> (digest); // DecodeBN<64> (digest); // for test vectors
// calculate R
uint8_t R[EDDSA25519_SIGNATURE_LENGTH/2]; // we must use separate buffer because signature might be inside buf
EncodePoint (Normalize (MulB (digest, bnCtx), bnCtx), R); // EncodePoint (Mul (B, r, bnCtx), R); // for test vectors
// calculate S
SHA512_Init (&ctx);
SHA512_Update (&ctx, R, EDDSA25519_SIGNATURE_LENGTH/2); // R
SHA512_Update (&ctx, publicKeyEncoded, EDDSA25519_PUBLIC_KEY_LENGTH); // public key
SHA512_Update (&ctx, buf, len); // data
SHA512_Final (digest, &ctx);
BIGNUM * h = DecodeBN<64> (digest);
// S = (r + h*a) % l
BIGNUM * a = DecodeBN<EDDSA25519_PRIVATE_KEY_LENGTH> (expandedPrivateKey); // left half of expanded key
BN_mod_mul (h, h, a, l, bnCtx); // %l
BN_mod_add (h, h, r, l, bnCtx); // %l
memcpy (signature, R, EDDSA25519_SIGNATURE_LENGTH/2);
EncodeBN (h, signature + EDDSA25519_SIGNATURE_LENGTH/2, EDDSA25519_SIGNATURE_LENGTH/2); // S
BN_free (r); BN_free (h); BN_free (a);
BN_CTX_free (bnCtx);
}
private:
EDDSAPoint Sum (const EDDSAPoint& p1, const EDDSAPoint& p2, BN_CTX * ctx) const
{
// x3 = (x1*y2+y1*x2)*(z1*z2-d*t1*t2)
// y3 = (y1*y2+x1*x2)*(z1*z2+d*t1*t2)
// z3 = (z1*z2-d*t1*t2)*(z1*z2+d*t1*t2)
// t3 = (y1*y2+x1*x2)*(x1*y2+y1*x2)
BIGNUM * x3 = BN_new (), * y3 = BN_new (), * z3 = BN_new (), * t3 = BN_new ();
BN_mul (x3, p1.x, p2.x, ctx); // A = x1*x2
BN_mul (y3, p1.y, p2.y, ctx); // B = y1*y2
BIGNUM * t1 = p1.t, * t2 = p2.t;
if (!t1) { t1 = BN_new (); BN_mul (t1, p1.x, p1.y, ctx); }
if (!t2) { t2 = BN_new (); BN_mul (t2, p2.x, p2.y, ctx); }
BN_mul (t3, t1, t2, ctx);
BN_mul (t3, t3, d, ctx); // C = d*t1*t2
if (!p1.t) BN_free (t1);
if (!p2.t) BN_free (t2);
if (p1.z)
{
if (p2.z)
BN_mul (z3, p1.z, p2.z, ctx); // D = z1*z2
else
BN_copy (z3, p1.z); // D = z1
}
else
{
if (p2.z)
BN_copy (z3, p2.z); // D = z2
else
BN_one (z3); // D = 1
}
BIGNUM * E = BN_new (), * F = BN_new (), * G = BN_new (), * H = BN_new ();
BN_add (E, p1.x, p1.y);
BN_add (F, p2.x, p2.y);
BN_mul (E, E, F, ctx); // (x1 + y1)*(x2 + y2)
BN_sub (E, E, x3);
BN_sub (E, E, y3); // E = (x1 + y1)*(x2 + y2) - A - B
BN_sub (F, z3, t3); // F = D - C
BN_add (G, z3, t3); // G = D + C
BN_add (H, y3, x3); // H = B + A
BN_mod_mul (x3, E, F, q, ctx); // x3 = E*F
BN_mod_mul (y3, G, H, q, ctx); // y3 = G*H
BN_mod_mul (z3, F, G, q, ctx); // z3 = F*G
BN_mod_mul (t3, E, H, q, ctx); // t3 = E*H
BN_free (E); BN_free (F); BN_free (G); BN_free (H);
return EDDSAPoint {x3, y3, z3, t3};
}
EDDSAPoint Double (const EDDSAPoint& p, BN_CTX * ctx) const
{
BIGNUM * x2 = BN_new (), * y2 = BN_new (), * z2 = BN_new (), * t2 = BN_new ();
BN_sqr (x2, p.x, ctx); // x2 = A = x^2
BN_sqr (y2, p.y, ctx); // y2 = B = y^2
if (p.t)
BN_sqr (t2, p.t, ctx); // t2 = t^2
else
{
BN_mul (t2, p.x, p.y, ctx); // t = x*y
BN_sqr (t2, t2, ctx); // t2 = t^2
}
BN_mul (t2, t2, d, ctx); // t2 = C = d*t^2
if (p.z)
BN_sqr (z2, p.z, ctx); // z2 = D = z^2
else
BN_one (z2); // z2 = 1
BIGNUM * E = BN_new (), * F = BN_new (), * G = BN_new (), * H = BN_new ();
// E = (x+y)*(x+y)-A-B = x^2+y^2+2xy-A-B = 2xy
BN_mul (E, p.x, p.y, ctx);
BN_lshift1 (E, E); // E =2*x*y
BN_sub (F, z2, t2); // F = D - C
BN_add (G, z2, t2); // G = D + C
BN_add (H, y2, x2); // H = B + A
BN_mod_mul (x2, E, F, q, ctx); // x2 = E*F
BN_mod_mul (y2, G, H, q, ctx); // y2 = G*H
BN_mod_mul (z2, F, G, q, ctx); // z2 = F*G
BN_mod_mul (t2, E, H, q, ctx); // t2 = E*H
BN_free (E); BN_free (F); BN_free (G); BN_free (H);
return EDDSAPoint {x2, y2, z2, t2};
}
EDDSAPoint Mul (const EDDSAPoint& p, const BIGNUM * e, BN_CTX * ctx) const
{
BIGNUM * zero = BN_new (), * one = BN_new ();
BN_zero (zero); BN_one (one);
EDDSAPoint res {zero, one};
if (!BN_is_zero (e))
{
int bitCount = BN_num_bits (e);
for (int i = bitCount - 1; i >= 0; i--)
{
res = Double (res, ctx);
if (BN_is_bit_set (e, i)) res = Sum (res, p, ctx);
}
}
return res;
}
EDDSAPoint MulB (const uint8_t * e, BN_CTX * ctx) const // B*e, e is 32 bytes Little Endian
{
BIGNUM * zero = BN_new (), * one = BN_new ();
BN_zero (zero); BN_one (one);
EDDSAPoint res {zero, one};
bool carry = false;
for (int i = 0; i < 32; i++)
{
uint8_t x = e[i];
if (carry)
{
if (x < 255)
{
x++;
carry = false;
}
else
x = 0;
}
if (x > 0)
{
if (x <= 128)
res = Sum (res, Bi256[i][x-1], ctx);
else
{
res = Sum (res, -Bi256[i][255-x], ctx); // -Bi[256-x]
carry = true;
}
}
}
if (carry) res = Sum (res, Bi256Carry, ctx);
return res;
}
EDDSAPoint Normalize (const EDDSAPoint& p, BN_CTX * ctx) const
{
if (p.z)
{
BIGNUM * x = BN_new (), * y = BN_new ();
BN_mod_inverse (y, p.z, q, ctx);
BN_mod_mul (x, p.x, y, q, ctx); // x = x/z
BN_mod_mul (y, p.y, y, q, ctx); // y = y/z
return EDDSAPoint{x, y};
}
else
return EDDSAPoint{BN_dup (p.x), BN_dup (p.y)};
}
bool IsOnCurve (const EDDSAPoint& p, BN_CTX * ctx) const
{
BIGNUM * x2 = BN_new ();
BN_sqr (x2, p.x, ctx); // x^2
BIGNUM * y2 = BN_new ();
BN_sqr (y2, p.y, ctx); // y^2
// y^2 - x^2 - 1 - d*x^2*y^2
BIGNUM * tmp = BN_new ();
BN_mul (tmp, d, x2, ctx);
BN_mul (tmp, tmp, y2, ctx);
BN_sub (tmp, y2, tmp);
BN_sub (tmp, tmp, x2);
BN_sub_word (tmp, 1);
BN_mod (tmp, tmp, q, ctx); // % q
bool ret = BN_is_zero (tmp);
BN_free (x2);
BN_free (y2);
BN_free (tmp);
return ret;
}
BIGNUM * RecoverX (const BIGNUM * y, BN_CTX * ctx) const
{
BIGNUM * y2 = BN_new ();
BN_sqr (y2, y, ctx); // y^2
// xx = (y^2 -1)*inv(d*y^2 +1)
BIGNUM * xx = BN_new ();
BN_mul (xx, d, y2, ctx);
BN_add_word (xx, 1);
BN_mod_inverse (xx, xx, q, ctx);
BN_sub_word (y2, 1);
BN_mul (xx, y2, xx, ctx);
// x = srqt(xx) = xx^(2^252-2)
BIGNUM * x = BN_new ();
BN_mod_exp (x, xx, two_252_2, q, ctx);
// check (x^2 -xx) % q
BN_sqr (y2, x, ctx);
BN_mod_sub (y2, y2, xx, q, ctx);
if (!BN_is_zero (y2))
BN_mod_mul (x, x, I, q, ctx);
if (BN_is_odd (x))
BN_sub (x, q, x);
BN_free (y2);
BN_free (xx);
return x;
}
EDDSAPoint DecodePoint (const uint8_t * buf, BN_CTX * ctx) const
{
// buf is 32 bytes Little Endian, convert it to Big Endian
uint8_t buf1[EDDSA25519_PUBLIC_KEY_LENGTH];
for (size_t i = 0; i < EDDSA25519_PUBLIC_KEY_LENGTH/2; i++) // invert bytes
{
buf1[i] = buf[EDDSA25519_PUBLIC_KEY_LENGTH -1 - i];
buf1[EDDSA25519_PUBLIC_KEY_LENGTH -1 - i] = buf[i];
}
bool isHighestBitSet = buf1[0] & 0x80;
if (isHighestBitSet)
buf1[0] &= 0x7f; // clear highest bit
BIGNUM * y = BN_new ();
BN_bin2bn (buf1, EDDSA25519_PUBLIC_KEY_LENGTH, y);
auto x = RecoverX (y, ctx);
if (BN_is_bit_set (x, 0) != isHighestBitSet)
BN_sub (x, q, x); // x = q - x
BIGNUM * z = BN_new (), * t = BN_new ();
BN_one (z); BN_mod_mul (t, x, y, q, ctx); // pre-calculate t
EDDSAPoint p {x, y, z, t};
if (!IsOnCurve (p, ctx))
LogPrint (eLogError, "Decoded point is not on 25519");
return p;
}
void EncodePoint (const EDDSAPoint& p, uint8_t * buf) const
{
EncodeBN (p.y, buf,EDDSA25519_PUBLIC_KEY_LENGTH);
if (BN_is_bit_set (p.x, 0)) // highest bit
buf[EDDSA25519_PUBLIC_KEY_LENGTH - 1] |= 0x80; // set highest bit
}
template<int len>
BIGNUM * DecodeBN (const uint8_t * buf) const
{
// buf is Little Endian convert it to Big Endian
uint8_t buf1[len];
for (size_t i = 0; i < len/2; i++) // invert bytes
{
buf1[i] = buf[len -1 - i];
buf1[len -1 - i] = buf[i];
}
BIGNUM * res = BN_new ();
BN_bin2bn (buf1, len, res);
return res;
}
void EncodeBN (const BIGNUM * bn, uint8_t * buf, size_t len) const
{
bn2buf (bn, buf, len);
// To Little Endian
for (size_t i = 0; i < len/2; i++) // invert bytes
{
uint8_t tmp = buf[i];
buf[i] = buf[len -1 - i];
buf[len -1 - i] = tmp;
}
}
private:
BIGNUM * q, * l, * d, * I;
// transient values
BIGNUM * two_252_2; // 2^252-2
EDDSAPoint Bi256[32][128]; // per byte, Bi256[i][j] = (256+j+1)^i*B, we don't store zeroes
// if j > 128 we use 256 - j and carry 1 to next byte
// Bi256[0][0] = B, base point
EDDSAPoint Bi256Carry; // Bi256[32][0]
};
static std::unique_ptr<Ed25519> g_Ed25519;
std::unique_ptr<Ed25519>& GetEd25519 ()
{
if (!g_Ed25519)
{
auto c = new Ed25519();
if (!g_Ed25519) // make sure it was not created already
g_Ed25519.reset (c);
else
delete c;
}
return g_Ed25519;
}
EDDSA25519Verifier::EDDSA25519Verifier (const uint8_t * signingKey)
{
memcpy (m_PublicKeyEncoded, signingKey, EDDSA25519_PUBLIC_KEY_LENGTH);
BN_CTX * ctx = BN_CTX_new ();
m_PublicKey = GetEd25519 ()->DecodePublicKey (m_PublicKeyEncoded, ctx);
BN_CTX_free (ctx);
}
bool EDDSA25519Verifier::Verify (const uint8_t * buf, size_t len, const uint8_t * signature) const
{
uint8_t digest[64];
SHA512_CTX ctx;
SHA512_Init (&ctx);
SHA512_Update (&ctx, signature, EDDSA25519_SIGNATURE_LENGTH/2); // R
SHA512_Update (&ctx, m_PublicKeyEncoded, EDDSA25519_PUBLIC_KEY_LENGTH); // public key
SHA512_Update (&ctx, buf, len); // data
SHA512_Final (digest, &ctx);
return GetEd25519 ()->Verify (m_PublicKey, digest, signature);
}
EDDSA25519Signer::EDDSA25519Signer (const uint8_t * signingPrivateKey, const uint8_t * signingPublicKey)
{
// expand key
SHA512 (signingPrivateKey, EDDSA25519_PRIVATE_KEY_LENGTH, m_ExpandedPrivateKey);
m_ExpandedPrivateKey[0] &= 0xF8; // drop last 3 bits
m_ExpandedPrivateKey[EDDSA25519_PRIVATE_KEY_LENGTH - 1] &= 0x3F; // drop first 2 bits
m_ExpandedPrivateKey[EDDSA25519_PRIVATE_KEY_LENGTH - 1] |= 0x40; // set second bit
// generate and encode public key
BN_CTX * ctx = BN_CTX_new ();
auto publicKey = GetEd25519 ()->GeneratePublicKey (m_ExpandedPrivateKey, ctx);
GetEd25519 ()->EncodePublicKey (publicKey, m_PublicKeyEncoded, ctx);
if (signingPublicKey && memcmp (m_PublicKeyEncoded, signingPublicKey, EDDSA25519_PUBLIC_KEY_LENGTH))
{
// keys don't match, it means older key with 0x1F
LogPrint (eLogWarning, "Older EdDSA key detected");
m_ExpandedPrivateKey[EDDSA25519_PRIVATE_KEY_LENGTH - 1] &= 0xDF; // drop third bit
publicKey = GetEd25519 ()->GeneratePublicKey (m_ExpandedPrivateKey, ctx);
GetEd25519 ()->EncodePublicKey (publicKey, m_PublicKeyEncoded, ctx);
}
BN_CTX_free (ctx);
}
void EDDSA25519Signer::Sign (const uint8_t * buf, int len, uint8_t * signature) const
{
GetEd25519 ()->Sign (m_ExpandedPrivateKey, m_PublicKeyEncoded, buf, len, signature);
}
}
}

95
Tag.h
View File

@ -1,95 +0,0 @@
#ifndef TAG_H__
#define TAG_H__
/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <boost/static_assert.hpp>
#include <string.h>
#include <openssl/rand.h>
#include "Base.h"
namespace i2p {
namespace data {
template<size_t sz>
class Tag
{
BOOST_STATIC_ASSERT_MSG(sz % 8 == 0, "Tag size must be multiple of 8 bytes");
public:
Tag () = default;
Tag (const uint8_t * buf) { memcpy (m_Buf, buf, sz); }
bool operator== (const Tag& other) const { return !memcmp (m_Buf, other.m_Buf, sz); }
bool operator< (const Tag& other) const { return memcmp (m_Buf, other.m_Buf, sz) < 0; }
uint8_t * operator()() { return m_Buf; }
const uint8_t * operator()() const { return m_Buf; }
operator uint8_t * () { return m_Buf; }
operator const uint8_t * () const { return m_Buf; }
const uint8_t * data() const { return m_Buf; }
const uint64_t * GetLL () const { return ll; }
bool IsZero () const
{
for (size_t i = 0; i < sz/8; ++i)
if (ll[i]) return false;
return true;
}
void Fill(uint8_t c)
{
memset(m_Buf, c, sz);
}
void Randomize()
{
RAND_bytes(m_Buf, sz);
}
std::string ToBase64 () const
{
char str[sz*2];
size_t l = i2p::data::ByteStreamToBase64 (m_Buf, sz, str, sz*2);
return std::string (str, str + l);
}
std::string ToBase32 () const
{
char str[sz*2];
size_t l = i2p::data::ByteStreamToBase32 (m_Buf, sz, str, sz*2);
return std::string (str, str + l);
}
void FromBase32 (const std::string& s)
{
i2p::data::Base32ToByteStream (s.c_str (), s.length (), m_Buf, sz);
}
void FromBase64 (const std::string& s)
{
i2p::data::Base64ToByteStream (s.c_str (), s.length (), m_Buf, sz);
}
private:
union // 8 bytes aligned
{
uint8_t m_Buf[sz];
uint64_t ll[sz/8];
};
};
} // data
} // i2p
#endif /* TAG_H__ */

View File

@ -1,66 +0,0 @@
#include <inttypes.h>
#include <string.h>
#include <boost/asio.hpp>
#include "Log.h"
#include "I2PEndian.h"
#include "Timestamp.h"
#ifdef WIN32
#ifndef _WIN64
#define _USE_32BIT_TIME_T
#endif
#endif
namespace i2p
{
namespace util
{
static int64_t g_TimeOffset = 0; // in seconds
void SyncTimeWithNTP (const std::string& address)
{
boost::asio::io_service service;
boost::asio::ip::udp::resolver::query query (boost::asio::ip::udp::v4 (), address, "ntp");
boost::system::error_code ec;
auto it = boost::asio::ip::udp::resolver (service).resolve (query, ec);
if (!ec && it != boost::asio::ip::udp::resolver::iterator())
{
auto ep = (*it).endpoint (); // take first one
boost::asio::ip::udp::socket socket (service);
socket.open (boost::asio::ip::udp::v4 (), ec);
if (!ec)
{
uint8_t buf[48];// 48 bytes NTP request/response
memset (buf, 0, 48);
htobe32buf (buf, (3 << 27) | (3 << 24)); // RFC 4330
size_t len = 0;
try
{
socket.send_to (boost::asio::buffer (buf, 48), ep);
int i = 0;
while (!socket.available() && i < 10) // 10 seconds max
{
std::this_thread::sleep_for (std::chrono::seconds(1));
i++;
}
if (socket.available ())
len = socket.receive_from (boost::asio::buffer (buf, 48), ep);
}
catch (std::exception& e)
{
LogPrint (eLogError, "NTP error: ", e.what ());
}
if (len >= 8)
{
auto ourTs = GetSecondsSinceEpoch ();
uint32_t ts = bufbe32toh (buf + 32);
if (ts > 2208988800U) ts -= 2208988800U; // 1/1/1970 from 1/1/1900
g_TimeOffset = ts - ourTs;
LogPrint (eLogInfo, address, " time offset from system time is ", g_TimeOffset, " seconds");
}
}
}
}
}
}

View File

@ -1,32 +0,0 @@
#ifndef TIMESTAMP_H__
#define TIMESTAMP_H__
#include <inttypes.h>
#include <chrono>
namespace i2p
{
namespace util
{
inline uint64_t GetMillisecondsSinceEpoch ()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count ();
}
inline uint32_t GetHoursSinceEpoch ()
{
return std::chrono::duration_cast<std::chrono::hours>(
std::chrono::system_clock::now().time_since_epoch()).count ();
}
inline uint64_t GetSecondsSinceEpoch ()
{
return std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch()).count ();
}
}
}
#endif

View File

@ -1,807 +0,0 @@
#include "Log.h"
#include "Crypto.h"
#include "RouterContext.h"
#include "I2NPProtocol.h"
#include "NetDb.h"
#include "Transports.h"
#include "Config.h"
#ifdef WITH_EVENTS
#include "Event.h"
#include "util.h"
#endif
using namespace i2p::data;
namespace i2p
{
namespace transport
{
DHKeysPairSupplier::DHKeysPairSupplier (int size):
m_QueueSize (size), m_IsRunning (false), m_Thread (nullptr)
{
}
DHKeysPairSupplier::~DHKeysPairSupplier ()
{
Stop ();
}
void DHKeysPairSupplier::Start ()
{
m_IsRunning = true;
m_Thread = new std::thread (std::bind (&DHKeysPairSupplier::Run, this));
}
void DHKeysPairSupplier::Stop ()
{
m_IsRunning = false;
m_Acquired.notify_one ();
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = 0;
}
}
void DHKeysPairSupplier::Run ()
{
while (m_IsRunning)
{
int num, total = 0;
while ((num = m_QueueSize - (int)m_Queue.size ()) > 0 && total < 20)
{
CreateDHKeysPairs (num);
total += num;
}
if (total >= 20)
{
LogPrint (eLogWarning, "Transports: ", total, " DH keys generated at the time");
std::this_thread::sleep_for (std::chrono::seconds(1)); // take a break
}
else
{
std::unique_lock<std::mutex> l(m_AcquiredMutex);
m_Acquired.wait (l); // wait for element gets aquired
}
}
}
void DHKeysPairSupplier::CreateDHKeysPairs (int num)
{
if (num > 0)
{
for (int i = 0; i < num; i++)
{
auto pair = std::make_shared<i2p::crypto::DHKeys> ();
pair->GenerateKeys ();
std::unique_lock<std::mutex> l(m_AcquiredMutex);
m_Queue.push (pair);
}
}
}
std::shared_ptr<i2p::crypto::DHKeys> DHKeysPairSupplier::Acquire ()
{
{
std::unique_lock<std::mutex> l(m_AcquiredMutex);
if (!m_Queue.empty ())
{
auto pair = m_Queue.front ();
m_Queue.pop ();
m_Acquired.notify_one ();
return pair;
}
}
// queue is empty, create new
auto pair = std::make_shared<i2p::crypto::DHKeys> ();
pair->GenerateKeys ();
return pair;
}
void DHKeysPairSupplier::Return (std::shared_ptr<i2p::crypto::DHKeys> pair)
{
std::unique_lock<std::mutex>l(m_AcquiredMutex);
if ((int)m_Queue.size () < 2*m_QueueSize)
m_Queue.push (pair);
}
Transports transports;
Transports::Transports ():
m_IsOnline (true), m_IsRunning (false), m_Thread (nullptr), m_Service (nullptr),
m_Work (nullptr), m_PeerCleanupTimer (nullptr), m_PeerTestTimer (nullptr),
m_NTCPServer (nullptr), m_SSUServer (nullptr), m_DHKeysPairSupplier (5), // 5 pre-generated keys
m_TotalSentBytes(0), m_TotalReceivedBytes(0), m_InBandwidth (0), m_OutBandwidth (0),
m_LastInBandwidthUpdateBytes (0), m_LastOutBandwidthUpdateBytes (0), m_LastBandwidthUpdateTime (0)
{
}
Transports::~Transports ()
{
Stop ();
if (m_Service)
{
delete m_PeerCleanupTimer; m_PeerCleanupTimer = nullptr;
delete m_PeerTestTimer; m_PeerTestTimer = nullptr;
delete m_Work; m_Work = nullptr;
delete m_Service; m_Service = nullptr;
}
}
void Transports::Start (bool enableNTCP, bool enableSSU)
{
if (!m_Service)
{
m_Service = new boost::asio::io_service ();
m_Work = new boost::asio::io_service::work (*m_Service);
m_PeerCleanupTimer = new boost::asio::deadline_timer (*m_Service);
m_PeerTestTimer = new boost::asio::deadline_timer (*m_Service);
}
m_DHKeysPairSupplier.Start ();
m_IsRunning = true;
m_Thread = new std::thread (std::bind (&Transports::Run, this));
// create acceptors
auto& addresses = context.GetRouterInfo ().GetAddresses ();
for (const auto& address : addresses)
{
if (!address) continue;
if (m_NTCPServer == nullptr && enableNTCP)
{
m_NTCPServer = new NTCPServer ();
m_NTCPServer->Start ();
if (!(m_NTCPServer->IsBoundV6() || m_NTCPServer->IsBoundV4())) {
/** failed to bind to NTCP */
LogPrint(eLogError, "Transports: failed to bind to TCP");
m_NTCPServer->Stop();
delete m_NTCPServer;
m_NTCPServer = nullptr;
}
}
if (address->transportStyle == RouterInfo::eTransportSSU)
{
if (m_SSUServer == nullptr && enableSSU)
{
if (address->host.is_v4())
m_SSUServer = new SSUServer (address->port);
else
m_SSUServer = new SSUServer (address->host, address->port);
LogPrint (eLogInfo, "Transports: Start listening UDP port ", address->port);
try {
m_SSUServer->Start ();
} catch ( std::exception & ex ) {
LogPrint(eLogError, "Transports: Failed to bind to UDP port", address->port);
delete m_SSUServer;
m_SSUServer = nullptr;
continue;
}
DetectExternalIP ();
}
else
LogPrint (eLogError, "Transports: SSU server already exists");
}
}
m_PeerCleanupTimer->expires_from_now (boost::posix_time::seconds(5*SESSION_CREATION_TIMEOUT));
m_PeerCleanupTimer->async_wait (std::bind (&Transports::HandlePeerCleanupTimer, this, std::placeholders::_1));
m_PeerTestTimer->expires_from_now (boost::posix_time::minutes(PEER_TEST_INTERVAL));
m_PeerTestTimer->async_wait (std::bind (&Transports::HandlePeerTestTimer, this, std::placeholders::_1));
}
void Transports::Stop ()
{
if (m_PeerCleanupTimer) m_PeerCleanupTimer->cancel ();
if (m_PeerTestTimer) m_PeerTestTimer->cancel ();
m_Peers.clear ();
if (m_SSUServer)
{
m_SSUServer->Stop ();
delete m_SSUServer;
m_SSUServer = nullptr;
}
if (m_NTCPServer)
{
m_NTCPServer->Stop ();
delete m_NTCPServer;
m_NTCPServer = nullptr;
}
m_DHKeysPairSupplier.Stop ();
m_IsRunning = false;
if (m_Service) m_Service->stop ();
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = nullptr;
}
}
void Transports::Run ()
{
while (m_IsRunning && m_Service)
{
try
{
m_Service->run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "Transports: runtime exception: ", ex.what ());
}
}
}
void Transports::UpdateBandwidth ()
{
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
if (m_LastBandwidthUpdateTime > 0)
{
auto delta = ts - m_LastBandwidthUpdateTime;
if (delta > 0)
{
m_InBandwidth = (m_TotalReceivedBytes - m_LastInBandwidthUpdateBytes)*1000/delta; // per second
m_OutBandwidth = (m_TotalSentBytes - m_LastOutBandwidthUpdateBytes)*1000/delta; // per second
}
}
m_LastBandwidthUpdateTime = ts;
m_LastInBandwidthUpdateBytes = m_TotalReceivedBytes;
m_LastOutBandwidthUpdateBytes = m_TotalSentBytes;
}
bool Transports::IsBandwidthExceeded () const
{
auto limit = i2p::context.GetBandwidthLimit() * 1024; // convert to bytes
auto bw = std::max (m_InBandwidth, m_OutBandwidth);
return bw > limit;
}
void Transports::SendMessage (const i2p::data::IdentHash& ident, std::shared_ptr<i2p::I2NPMessage> msg)
{
SendMessages (ident, std::vector<std::shared_ptr<i2p::I2NPMessage> > {msg });
}
void Transports::SendMessages (const i2p::data::IdentHash& ident, const std::vector<std::shared_ptr<i2p::I2NPMessage> >& msgs)
{
#ifdef WITH_EVENTS
QueueIntEvent("transport.send", ident.ToBase64(), msgs.size());
#endif
m_Service->post (std::bind (&Transports::PostMessages, this, ident, msgs));
}
void Transports::PostMessages (i2p::data::IdentHash ident, std::vector<std::shared_ptr<i2p::I2NPMessage> > msgs)
{
if (ident == i2p::context.GetRouterInfo ().GetIdentHash ())
{
// we send it to ourself
for (auto& it: msgs)
m_LoopbackHandler.PutNextMessage (it);
m_LoopbackHandler.Flush ();
return;
}
if(RoutesRestricted() && ! IsRestrictedPeer(ident)) return;
auto it = m_Peers.find (ident);
if (it == m_Peers.end ())
{
bool connected = false;
try
{
auto r = netdb.FindRouter (ident);
{
std::unique_lock<std::mutex> l(m_PeersMutex);
it = m_Peers.insert (std::pair<i2p::data::IdentHash, Peer>(ident, { 0, r, {},
i2p::util::GetSecondsSinceEpoch (), {} })).first;
}
connected = ConnectToPeer (ident, it->second);
}
catch (std::exception& ex)
{
LogPrint (eLogError, "Transports: PostMessages exception:", ex.what ());
}
if (!connected) return;
}
if (!it->second.sessions.empty ())
it->second.sessions.front ()->SendI2NPMessages (msgs);
else
{
if (it->second.delayedMessages.size () < MAX_NUM_DELAYED_MESSAGES)
{
for (auto& it1: msgs)
it->second.delayedMessages.push_back (it1);
}
else
{
LogPrint (eLogWarning, "Transports: delayed messages queue size exceeds ", MAX_NUM_DELAYED_MESSAGES);
std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.erase (it);
}
}
}
bool Transports::ConnectToPeer (const i2p::data::IdentHash& ident, Peer& peer)
{
if (peer.router) // we have RI already
{
if (!peer.numAttempts) // NTCP
{
peer.numAttempts++;
auto address = peer.router->GetNTCPAddress (!context.SupportsV6 ());
if (address && m_NTCPServer)
{
#if BOOST_VERSION >= 104900
if (!address->host.is_unspecified ()) // we have address now
#else
boost::system::error_code ecode;
address->host.to_string (ecode);
if (!ecode)
#endif
{
if (!peer.router->UsesIntroducer () && !peer.router->IsUnreachable ())
{
auto s = std::make_shared<NTCPSession> (*m_NTCPServer, peer.router);
m_NTCPServer->Connect (address->host, address->port, s);
return true;
}
}
else // we don't have address
{
if (address->addressString.length () > 0) // trying to resolve
{
LogPrint (eLogDebug, "Transports: Resolving NTCP ", address->addressString);
NTCPResolve (address->addressString, ident);
return true;
}
}
}
else
LogPrint (eLogDebug, "Transports: NTCP address is not present for ", i2p::data::GetIdentHashAbbreviation (ident), ", trying SSU");
}
if (peer.numAttempts == 1)// SSU
{
peer.numAttempts++;
if (m_SSUServer && peer.router->IsSSU (!context.SupportsV6 ()))
{
auto address = peer.router->GetSSUAddress (!context.SupportsV6 ());
#if BOOST_VERSION >= 104900
if (!address->host.is_unspecified ()) // we have address now
#else
boost::system::error_code ecode;
address->host.to_string (ecode);
if (!ecode)
#endif
{
m_SSUServer->CreateSession (peer.router, address->host, address->port);
return true;
}
else // we don't have address
{
if (address->addressString.length () > 0) // trying to resolve
{
LogPrint (eLogDebug, "Transports: Resolving SSU ", address->addressString);
SSUResolve (address->addressString, ident);
return true;
}
}
}
}
LogPrint (eLogInfo, "Transports: No NTCP or SSU addresses available");
peer.Done ();
std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.erase (ident);
return false;
}
else // otherwise request RI
{
LogPrint (eLogInfo, "Transports: RouterInfo for ", ident.ToBase64 (), " not found, requested");
i2p::data::netdb.RequestDestination (ident, std::bind (
&Transports::RequestComplete, this, std::placeholders::_1, ident));
}
return true;
}
void Transports::RequestComplete (std::shared_ptr<const i2p::data::RouterInfo> r, const i2p::data::IdentHash& ident)
{
m_Service->post (std::bind (&Transports::HandleRequestComplete, this, r, ident));
}
void Transports::HandleRequestComplete (std::shared_ptr<const i2p::data::RouterInfo> r, i2p::data::IdentHash ident)
{
auto it = m_Peers.find (ident);
if (it != m_Peers.end ())
{
if (r)
{
LogPrint (eLogDebug, "Transports: RouterInfo for ", ident.ToBase64 (), " found, Trying to connect");
it->second.router = r;
ConnectToPeer (ident, it->second);
}
else
{
LogPrint (eLogWarning, "Transports: RouterInfo not found, Failed to send messages");
std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.erase (it);
}
}
}
void Transports::NTCPResolve (const std::string& addr, const i2p::data::IdentHash& ident)
{
auto resolver = std::make_shared<boost::asio::ip::tcp::resolver>(*m_Service);
resolver->async_resolve (boost::asio::ip::tcp::resolver::query (addr, ""),
std::bind (&Transports::HandleNTCPResolve, this,
std::placeholders::_1, std::placeholders::_2, ident, resolver));
}
void Transports::HandleNTCPResolve (const boost::system::error_code& ecode, boost::asio::ip::tcp::resolver::iterator it,
i2p::data::IdentHash ident, std::shared_ptr<boost::asio::ip::tcp::resolver> resolver)
{
auto it1 = m_Peers.find (ident);
if (it1 != m_Peers.end ())
{
auto& peer = it1->second;
if (!ecode && peer.router)
{
while (it != boost::asio::ip::tcp::resolver::iterator())
{
auto address = (*it).endpoint ().address ();
LogPrint (eLogDebug, "Transports: ", (*it).host_name (), " has been resolved to ", address);
if (address.is_v4 () || context.SupportsV6 ())
{
auto addr = peer.router->GetNTCPAddress (); // TODO: take one we requested
if (addr)
{
auto s = std::make_shared<NTCPSession> (*m_NTCPServer, peer.router);
m_NTCPServer->Connect (address, addr->port, s);
return;
}
break;
}
else
LogPrint (eLogInfo, "Transports: NTCP ", address, " is not supported");
it++;
}
}
LogPrint (eLogError, "Transports: Unable to resolve NTCP address: ", ecode.message ());
std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.erase (it1);
}
}
void Transports::SSUResolve (const std::string& addr, const i2p::data::IdentHash& ident)
{
auto resolver = std::make_shared<boost::asio::ip::tcp::resolver>(*m_Service);
resolver->async_resolve (boost::asio::ip::tcp::resolver::query (addr, ""),
std::bind (&Transports::HandleSSUResolve, this,
std::placeholders::_1, std::placeholders::_2, ident, resolver));
}
void Transports::HandleSSUResolve (const boost::system::error_code& ecode, boost::asio::ip::tcp::resolver::iterator it,
i2p::data::IdentHash ident, std::shared_ptr<boost::asio::ip::tcp::resolver> resolver)
{
auto it1 = m_Peers.find (ident);
if (it1 != m_Peers.end ())
{
auto& peer = it1->second;
if (!ecode && peer.router)
{
while (it != boost::asio::ip::tcp::resolver::iterator())
{
auto address = (*it).endpoint ().address ();
LogPrint (eLogDebug, "Transports: ", (*it).host_name (), " has been resolved to ", address);
if (address.is_v4 () || context.SupportsV6 ())
{
auto addr = peer.router->GetSSUAddress (); // TODO: take one we requested
if (addr)
{
m_SSUServer->CreateSession (peer.router, address, addr->port);
return;
}
break;
}
else
LogPrint (eLogInfo, "Transports: SSU ", address, " is not supported");
it++;
}
}
LogPrint (eLogError, "Transports: Unable to resolve SSU address: ", ecode.message ());
std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.erase (it1);
}
}
void Transports::CloseSession (std::shared_ptr<const i2p::data::RouterInfo> router)
{
if (!router) return;
m_Service->post (std::bind (&Transports::PostCloseSession, this, router));
}
void Transports::PostCloseSession (std::shared_ptr<const i2p::data::RouterInfo> router)
{
auto ssuSession = m_SSUServer ? m_SSUServer->FindSession (router) : nullptr;
if (ssuSession) // try SSU first
{
m_SSUServer->DeleteSession (ssuSession);
LogPrint (eLogDebug, "Transports: SSU session closed");
}
auto ntcpSession = m_NTCPServer ? m_NTCPServer->FindNTCPSession(router->GetIdentHash()) : nullptr;
if (ntcpSession) // try deleting ntcp session too
{
ntcpSession->Terminate ();
LogPrint(eLogDebug, "Transports: NTCP session closed");
}
}
void Transports::DetectExternalIP ()
{
if (RoutesRestricted())
{
LogPrint(eLogInfo, "Transports: restricted routes enabled, not detecting ip");
i2p::context.SetStatus (eRouterStatusOK);
return;
}
if (m_SSUServer)
{
bool nat; i2p::config::GetOption("nat", nat);
bool isv4 = i2p::context.SupportsV4 ();
if (nat && isv4)
i2p::context.SetStatus (eRouterStatusTesting);
for (int i = 0; i < 5; i++)
{
auto router = i2p::data::netdb.GetRandomPeerTestRouter (isv4); // v4 only if v4
if (router)
m_SSUServer->CreateSession (router, true, isv4); // peer test
else
{
// if not peer test capable routers found pick any
router = i2p::data::netdb.GetRandomRouter ();
if (router && router->IsSSU ())
m_SSUServer->CreateSession (router); // no peer test
}
}
}
else
LogPrint (eLogError, "Transports: Can't detect external IP. SSU is not available");
}
void Transports::PeerTest ()
{
if (RoutesRestricted() || !i2p::context.SupportsV4 ()) return;
if (m_SSUServer)
{
bool statusChanged = false;
for (int i = 0; i < 5; i++)
{
auto router = i2p::data::netdb.GetRandomPeerTestRouter (true); // v4 only
if (router)
{
if (!statusChanged)
{
statusChanged = true;
i2p::context.SetStatus (eRouterStatusTesting); // first time only
}
m_SSUServer->CreateSession (router, true, true); // peer test v4
}
}
if (!statusChanged)
LogPrint (eLogWarning, "Can't find routers for peer test");
}
}
std::shared_ptr<i2p::crypto::DHKeys> Transports::GetNextDHKeysPair ()
{
return m_DHKeysPairSupplier.Acquire ();
}
void Transports::ReuseDHKeysPair (std::shared_ptr<i2p::crypto::DHKeys> pair)
{
m_DHKeysPairSupplier.Return (pair);
}
void Transports::PeerConnected (std::shared_ptr<TransportSession> session)
{
m_Service->post([session, this]()
{
auto remoteIdentity = session->GetRemoteIdentity ();
if (!remoteIdentity) return;
auto ident = remoteIdentity->GetIdentHash ();
auto it = m_Peers.find (ident);
if (it != m_Peers.end ())
{
#ifdef WITH_EVENTS
EmitEvent({{"type" , "transport.connected"}, {"ident", ident.ToBase64()}, {"inbound", "false"}});
#endif
bool sendDatabaseStore = true;
if (it->second.delayedMessages.size () > 0)
{
// check if first message is our DatabaseStore (publishing)
auto firstMsg = it->second.delayedMessages[0];
if (firstMsg && firstMsg->GetTypeID () == eI2NPDatabaseStore &&
i2p::data::IdentHash(firstMsg->GetPayload () + DATABASE_STORE_KEY_OFFSET) == i2p::context.GetIdentHash ())
sendDatabaseStore = false; // we have it in the list already
}
if (sendDatabaseStore)
session->SendI2NPMessages ({ CreateDatabaseStoreMsg () });
else
session->SetTerminationTimeout (10); // most likely it's publishing, no follow-up messages expected, set timeout to 10 seconds
it->second.sessions.push_back (session);
session->SendI2NPMessages (it->second.delayedMessages);
it->second.delayedMessages.clear ();
}
else // incoming connection
{
if(RoutesRestricted() && ! IsRestrictedPeer(ident)) {
// not trusted
LogPrint(eLogWarning, "Transports: closing untrusted inbound connection from ", ident.ToBase64());
session->Done();
return;
}
#ifdef WITH_EVENTS
EmitEvent({{"type" , "transport.connected"}, {"ident", ident.ToBase64()}, {"inbound", "true"}});
#endif
session->SendI2NPMessages ({ CreateDatabaseStoreMsg () }); // send DatabaseStore
std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.insert (std::make_pair (ident, Peer{ 0, nullptr, { session }, i2p::util::GetSecondsSinceEpoch (), {} }));
}
});
}
void Transports::PeerDisconnected (std::shared_ptr<TransportSession> session)
{
m_Service->post([session, this]()
{
auto remoteIdentity = session->GetRemoteIdentity ();
if (!remoteIdentity) return;
auto ident = remoteIdentity->GetIdentHash ();
#ifdef WITH_EVENTS
EmitEvent({{"type" , "transport.disconnected"}, {"ident", ident.ToBase64()}});
#endif
auto it = m_Peers.find (ident);
if (it != m_Peers.end ())
{
it->second.sessions.remove (session);
if (it->second.sessions.empty ()) // TODO: why?
{
if (it->second.delayedMessages.size () > 0)
ConnectToPeer (ident, it->second);
else
{
std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.erase (it);
}
}
}
});
}
bool Transports::IsConnected (const i2p::data::IdentHash& ident) const
{
std::unique_lock<std::mutex> l(m_PeersMutex);
auto it = m_Peers.find (ident);
return it != m_Peers.end ();
}
void Transports::HandlePeerCleanupTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
auto ts = i2p::util::GetSecondsSinceEpoch ();
for (auto it = m_Peers.begin (); it != m_Peers.end (); )
{
if (it->second.sessions.empty () && ts > it->second.creationTime + SESSION_CREATION_TIMEOUT)
{
LogPrint (eLogWarning, "Transports: Session to peer ", it->first.ToBase64 (), " has not been created in ", SESSION_CREATION_TIMEOUT, " seconds");
auto profile = i2p::data::GetRouterProfile(it->first);
if (profile)
{
profile->TunnelNonReplied();
profile->Save(it->first);
}
std::unique_lock<std::mutex> l(m_PeersMutex);
it = m_Peers.erase (it);
}
else
++it;
}
UpdateBandwidth (); // TODO: use separate timer(s) for it
if (i2p::context.GetStatus () == eRouterStatusTesting) // if still testing, repeat peer test
DetectExternalIP ();
m_PeerCleanupTimer->expires_from_now (boost::posix_time::seconds(5*SESSION_CREATION_TIMEOUT));
m_PeerCleanupTimer->async_wait (std::bind (&Transports::HandlePeerCleanupTimer, this, std::placeholders::_1));
}
}
void Transports::HandlePeerTestTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
PeerTest ();
m_PeerTestTimer->expires_from_now (boost::posix_time::minutes(PEER_TEST_INTERVAL));
m_PeerTestTimer->async_wait (std::bind (&Transports::HandlePeerTestTimer, this, std::placeholders::_1));
}
}
std::shared_ptr<const i2p::data::RouterInfo> Transports::GetRandomPeer () const
{
if (m_Peers.empty ()) return nullptr;
std::unique_lock<std::mutex> l(m_PeersMutex);
auto it = m_Peers.begin ();
std::advance (it, rand () % m_Peers.size ());
return it != m_Peers.end () ? it->second.router : nullptr;
}
void Transports::RestrictRoutesToFamilies(std::set<std::string> families)
{
std::lock_guard<std::mutex> lock(m_FamilyMutex);
m_TrustedFamilies.clear();
for ( const auto& fam : families )
m_TrustedFamilies.push_back(fam);
}
void Transports::RestrictRoutesToRouters(std::set<i2p::data::IdentHash> routers)
{
std::unique_lock<std::mutex> lock(m_TrustedRoutersMutex);
m_TrustedRouters.clear();
for (const auto & ri : routers )
m_TrustedRouters.push_back(ri);
}
bool Transports::RoutesRestricted() const {
std::unique_lock<std::mutex> famlock(m_FamilyMutex);
std::unique_lock<std::mutex> routerslock(m_TrustedRoutersMutex);
return m_TrustedFamilies.size() > 0 || m_TrustedRouters.size() > 0;
}
/** XXX: if routes are not restricted this dies */
std::shared_ptr<const i2p::data::RouterInfo> Transports::GetRestrictedPeer() const
{
{
std::lock_guard<std::mutex> l(m_FamilyMutex);
std::string fam;
auto sz = m_TrustedFamilies.size();
if(sz > 1)
{
auto it = m_TrustedFamilies.begin ();
std::advance(it, rand() % sz);
fam = *it;
boost::to_lower(fam);
}
else if (sz == 1)
{
fam = m_TrustedFamilies[0];
}
if (fam.size())
return i2p::data::netdb.GetRandomRouterInFamily(fam);
}
{
std::unique_lock<std::mutex> l(m_TrustedRoutersMutex);
auto sz = m_TrustedRouters.size();
if (sz)
{
if(sz == 1)
return i2p::data::netdb.FindRouter(m_TrustedRouters[0]);
auto it = m_TrustedRouters.begin();
std::advance(it, rand() % sz);
return i2p::data::netdb.FindRouter(*it);
}
}
return nullptr;
}
bool Transports::IsRestrictedPeer(const i2p::data::IdentHash & ih) const
{
{
std::unique_lock<std::mutex> l(m_TrustedRoutersMutex);
for (const auto & r : m_TrustedRouters )
if ( r == ih ) return true;
}
{
std::unique_lock<std::mutex> l(m_FamilyMutex);
auto ri = i2p::data::netdb.FindRouter(ih);
for (const auto & fam : m_TrustedFamilies)
if(ri->IsFamily(fam)) return true;
}
return false;
}
}
}

View File

@ -1,252 +0,0 @@
#ifndef TUNNEL_CONFIG_H__
#define TUNNEL_CONFIG_H__
#include <inttypes.h>
#include <sstream>
#include <vector>
#include <memory>
#include "Crypto.h"
#include "Identity.h"
#include "RouterContext.h"
#include "Timestamp.h"
namespace i2p
{
namespace tunnel
{
struct TunnelHopConfig
{
std::shared_ptr<const i2p::data::IdentityEx> ident;
i2p::data::IdentHash nextIdent;
uint32_t tunnelID, nextTunnelID;
uint8_t layerKey[32];
uint8_t ivKey[32];
uint8_t replyKey[32];
uint8_t replyIV[16];
bool isGateway, isEndpoint;
TunnelHopConfig * next, * prev;
int recordIndex; // record # in tunnel build message
TunnelHopConfig (std::shared_ptr<const i2p::data::IdentityEx> r)
{
RAND_bytes (layerKey, 32);
RAND_bytes (ivKey, 32);
RAND_bytes (replyKey, 32);
RAND_bytes (replyIV, 16);
RAND_bytes ((uint8_t *)&tunnelID, 4);
isGateway = true;
isEndpoint = true;
ident = r;
//nextRouter = nullptr;
nextTunnelID = 0;
next = nullptr;
prev = nullptr;
}
void SetNextIdent (const i2p::data::IdentHash& ident)
{
nextIdent = ident;
isEndpoint = false;
RAND_bytes ((uint8_t *)&nextTunnelID, 4);
}
void SetReplyHop (uint32_t replyTunnelID, const i2p::data::IdentHash& replyIdent)
{
nextIdent = replyIdent;
nextTunnelID = replyTunnelID;
isEndpoint = true;
}
void SetNext (TunnelHopConfig * n)
{
next = n;
if (next)
{
next->prev = this;
next->isGateway = false;
isEndpoint = false;
nextIdent = next->ident->GetIdentHash ();
nextTunnelID = next->tunnelID;
}
}
void SetPrev (TunnelHopConfig * p)
{
prev = p;
if (prev)
{
prev->next = this;
prev->isEndpoint = false;
isGateway = false;
}
}
void CreateBuildRequestRecord (uint8_t * record, uint32_t replyMsgID) const
{
uint8_t clearText[BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE];
htobe32buf (clearText + BUILD_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET, tunnelID);
memcpy (clearText + BUILD_REQUEST_RECORD_OUR_IDENT_OFFSET, ident->GetIdentHash (), 32);
htobe32buf (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET, nextTunnelID);
memcpy (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET, nextIdent, 32);
memcpy (clearText + BUILD_REQUEST_RECORD_LAYER_KEY_OFFSET, layerKey, 32);
memcpy (clearText + BUILD_REQUEST_RECORD_IV_KEY_OFFSET, ivKey, 32);
memcpy (clearText + BUILD_REQUEST_RECORD_REPLY_KEY_OFFSET, replyKey, 32);
memcpy (clearText + BUILD_REQUEST_RECORD_REPLY_IV_OFFSET, replyIV, 16);
uint8_t flag = 0;
if (isGateway) flag |= 0x80;
if (isEndpoint) flag |= 0x40;
clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] = flag;
htobe32buf (clearText + BUILD_REQUEST_RECORD_REQUEST_TIME_OFFSET, i2p::util::GetHoursSinceEpoch ());
htobe32buf (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET, replyMsgID);
RAND_bytes (clearText + BUILD_REQUEST_RECORD_PADDING_OFFSET, BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE - BUILD_REQUEST_RECORD_PADDING_OFFSET);
i2p::crypto::ElGamalEncrypt (ident->GetEncryptionPublicKey (), clearText, record + BUILD_REQUEST_RECORD_ENCRYPTED_OFFSET);
memcpy (record + BUILD_REQUEST_RECORD_TO_PEER_OFFSET, (const uint8_t *)ident->GetIdentHash (), 16);
}
};
class TunnelConfig
{
public:
TunnelConfig (std::vector<std::shared_ptr<const i2p::data::IdentityEx> > peers) // inbound
{
CreatePeers (peers);
m_LastHop->SetNextIdent (i2p::context.GetIdentHash ());
}
TunnelConfig (std::vector<std::shared_ptr<const i2p::data::IdentityEx> > peers,
uint32_t replyTunnelID, const i2p::data::IdentHash& replyIdent) // outbound
{
CreatePeers (peers);
m_FirstHop->isGateway = false;
m_LastHop->SetReplyHop (replyTunnelID, replyIdent);
}
~TunnelConfig ()
{
TunnelHopConfig * hop = m_FirstHop;
while (hop)
{
auto tmp = hop;
hop = hop->next;
delete tmp;
}
}
TunnelHopConfig * GetFirstHop () const
{
return m_FirstHop;
}
TunnelHopConfig * GetLastHop () const
{
return m_LastHop;
}
int GetNumHops () const
{
int num = 0;
TunnelHopConfig * hop = m_FirstHop;
while (hop)
{
num++;
hop = hop->next;
}
return num;
}
bool IsEmpty () const
{
return !m_FirstHop;
}
virtual bool IsInbound () const { return m_FirstHop->isGateway; }
virtual uint32_t GetTunnelID () const
{
if (!m_FirstHop) return 0;
return IsInbound () ? m_LastHop->nextTunnelID : m_FirstHop->tunnelID;
}
virtual uint32_t GetNextTunnelID () const
{
if (!m_FirstHop) return 0;
return m_FirstHop->tunnelID;
}
virtual const i2p::data::IdentHash& GetNextIdentHash () const
{
return m_FirstHop->ident->GetIdentHash ();
}
virtual const i2p::data::IdentHash& GetLastIdentHash () const
{
return m_LastHop->ident->GetIdentHash ();
}
std::vector<std::shared_ptr<const i2p::data::IdentityEx> > GetPeers () const
{
std::vector<std::shared_ptr<const i2p::data::IdentityEx> > peers;
TunnelHopConfig * hop = m_FirstHop;
while (hop)
{
peers.push_back (hop->ident);
hop = hop->next;
}
return peers;
}
protected:
// this constructor can't be called from outside
TunnelConfig (): m_FirstHop (nullptr), m_LastHop (nullptr)
{
}
private:
template<class Peers>
void CreatePeers (const Peers& peers)
{
TunnelHopConfig * prev = nullptr;
for (const auto& it: peers)
{
auto hop = new TunnelHopConfig (it);
if (prev)
prev->SetNext (hop);
else
m_FirstHop = hop;
prev = hop;
}
m_LastHop = prev;
}
private:
TunnelHopConfig * m_FirstHop, * m_LastHop;
};
class ZeroHopsTunnelConfig: public TunnelConfig
{
public:
ZeroHopsTunnelConfig () { RAND_bytes ((uint8_t *)&m_TunnelID, 4);};
bool IsInbound () const { return true; }; // TODO:
uint32_t GetTunnelID () const { return m_TunnelID; };
uint32_t GetNextTunnelID () const { return m_TunnelID; };
const i2p::data::IdentHash& GetNextIdentHash () const { return i2p::context.GetIdentHash (); };
const i2p::data::IdentHash& GetLastIdentHash () const { return i2p::context.GetIdentHash (); };
private:
uint32_t m_TunnelID;
};
}
}
#endif

View File

@ -1,298 +0,0 @@
#include "I2PEndian.h"
#include <string.h>
#include "Crypto.h"
#include "Log.h"
#include "NetDb.h"
#include "I2NPProtocol.h"
#include "Transports.h"
#include "RouterContext.h"
#include "Timestamp.h"
#include "TunnelEndpoint.h"
namespace i2p
{
namespace tunnel
{
TunnelEndpoint::~TunnelEndpoint ()
{
}
void TunnelEndpoint::HandleDecryptedTunnelDataMsg (std::shared_ptr<I2NPMessage> msg)
{
m_NumReceivedBytes += TUNNEL_DATA_MSG_SIZE;
uint8_t * decrypted = msg->GetPayload () + 20; // 4 + 16
uint8_t * zero = (uint8_t *)memchr (decrypted + 4, 0, TUNNEL_DATA_ENCRYPTED_SIZE - 4); // witout 4-byte checksum
if (zero)
{
uint8_t * fragment = zero + 1;
// verify checksum
memcpy (msg->GetPayload () + TUNNEL_DATA_MSG_SIZE, msg->GetPayload () + 4, 16); // copy iv to the end
uint8_t hash[32];
SHA256(fragment, TUNNEL_DATA_MSG_SIZE -(fragment - msg->GetPayload ()) + 16, hash); // payload + iv
if (memcmp (hash, decrypted, 4))
{
LogPrint (eLogError, "TunnelMessage: checksum verification failed");
return;
}
// process fragments
while (fragment < decrypted + TUNNEL_DATA_ENCRYPTED_SIZE)
{
uint8_t flag = fragment[0];
fragment++;
bool isFollowOnFragment = flag & 0x80, isLastFragment = true;
uint32_t msgID = 0;
int fragmentNum = 0;
TunnelMessageBlockEx m;
if (!isFollowOnFragment)
{
// first fragment
m.deliveryType = (TunnelDeliveryType)((flag >> 5) & 0x03);
switch (m.deliveryType)
{
case eDeliveryTypeLocal: // 0
break;
case eDeliveryTypeTunnel: // 1
m.tunnelID = bufbe32toh (fragment);
fragment += 4; // tunnelID
m.hash = i2p::data::IdentHash (fragment);
fragment += 32; // hash
break;
case eDeliveryTypeRouter: // 2
m.hash = i2p::data::IdentHash (fragment);
fragment += 32; // to hash
break;
default:
;
}
bool isFragmented = flag & 0x08;
if (isFragmented)
{
// Message ID
msgID = bufbe32toh (fragment);
fragment += 4;
isLastFragment = false;
}
}
else
{
// follow on
msgID = bufbe32toh (fragment); // MessageID
fragment += 4;
fragmentNum = (flag >> 1) & 0x3F; // 6 bits
isLastFragment = flag & 0x01;
}
uint16_t size = bufbe16toh (fragment);
fragment += 2;
msg->offset = fragment - msg->buf;
msg->len = msg->offset + size;
if (msg->len > msg->maxLen)
{
LogPrint (eLogError, "TunnelMessage: fragment is too long ", (int)size);
return;
}
if (fragment + size < decrypted + TUNNEL_DATA_ENCRYPTED_SIZE)
{
// this is not last message. we have to copy it
m.data = NewI2NPShortMessage ();
m.data->offset += TUNNEL_GATEWAY_HEADER_SIZE; // reserve room for TunnelGateway header
m.data->len += TUNNEL_GATEWAY_HEADER_SIZE;
*(m.data) = *msg;
}
else
m.data = msg;
if (!isFollowOnFragment && isLastFragment)
HandleNextMessage (m);
else
{
if (msgID) // msgID is presented, assume message is fragmented
{
if (!isFollowOnFragment) // create new incomlete message
{
m.nextFragmentNum = 1;
m.receiveTime = i2p::util::GetMillisecondsSinceEpoch ();
auto ret = m_IncompleteMessages.insert (std::pair<uint32_t, TunnelMessageBlockEx>(msgID, m));
if (ret.second)
HandleOutOfSequenceFragments (msgID, ret.first->second);
else
LogPrint (eLogError, "TunnelMessage: Incomplete message ", msgID, " already exists");
}
else
{
m.nextFragmentNum = fragmentNum;
HandleFollowOnFragment (msgID, isLastFragment, m);
}
}
else
LogPrint (eLogError, "TunnelMessage: Message is fragmented, but msgID is not presented");
}
fragment += size;
}
}
else
LogPrint (eLogError, "TunnelMessage: zero not found");
}
void TunnelEndpoint::HandleFollowOnFragment (uint32_t msgID, bool isLastFragment, const TunnelMessageBlockEx& m)
{
auto fragment = m.data->GetBuffer ();
auto size = m.data->GetLength ();
auto it = m_IncompleteMessages.find (msgID);
if (it != m_IncompleteMessages.end())
{
auto& msg = it->second;
if (m.nextFragmentNum == msg.nextFragmentNum)
{
if (msg.data->len + size < I2NP_MAX_MESSAGE_SIZE) // check if message is not too long
{
if (msg.data->len + size > msg.data->maxLen)
{
LogPrint (eLogWarning, "TunnelMessage: I2NP message size ", msg.data->maxLen, " is not enough");
auto newMsg = NewI2NPMessage ();
*newMsg = *(msg.data);
msg.data = newMsg;
}
if (msg.data->Concat (fragment, size) < size) // concatenate fragment
LogPrint (eLogError, "TunnelMessage: I2NP buffer overflow ", msg.data->maxLen);
if (isLastFragment)
{
// message complete
HandleNextMessage (msg);
m_IncompleteMessages.erase (it);
}
else
{
msg.nextFragmentNum++;
HandleOutOfSequenceFragments (msgID, msg);
}
}
else
{
LogPrint (eLogError, "TunnelMessage: Fragment ", m.nextFragmentNum, " of message ", msgID, "exceeds max I2NP message size, message dropped");
m_IncompleteMessages.erase (it);
}
}
else
{
LogPrint (eLogWarning, "TunnelMessage: Unexpected fragment ", (int)m.nextFragmentNum, " instead ", (int)msg.nextFragmentNum, " of message ", msgID, ", saved");
AddOutOfSequenceFragment (msgID, m.nextFragmentNum, isLastFragment, m.data);
}
}
else
{
LogPrint (eLogWarning, "TunnelMessage: First fragment of message ", msgID, " not found, saved");
AddOutOfSequenceFragment (msgID, m.nextFragmentNum, isLastFragment, m.data);
}
}
void TunnelEndpoint::AddOutOfSequenceFragment (uint32_t msgID, uint8_t fragmentNum, bool isLastFragment, std::shared_ptr<I2NPMessage> data)
{
if (!m_OutOfSequenceFragments.insert ({{msgID, fragmentNum}, {isLastFragment, data, i2p::util::GetMillisecondsSinceEpoch () }}).second)
LogPrint (eLogInfo, "TunnelMessage: duplicate out-of-sequence fragment ", fragmentNum, " of message ", msgID);
}
void TunnelEndpoint::HandleOutOfSequenceFragments (uint32_t msgID, TunnelMessageBlockEx& msg)
{
while (ConcatNextOutOfSequenceFragment (msgID, msg))
{
if (!msg.nextFragmentNum) // message complete
{
HandleNextMessage (msg);
m_IncompleteMessages.erase (msgID);
break;
}
}
}
bool TunnelEndpoint::ConcatNextOutOfSequenceFragment (uint32_t msgID, TunnelMessageBlockEx& msg)
{
auto it = m_OutOfSequenceFragments.find ({msgID, msg.nextFragmentNum});
if (it != m_OutOfSequenceFragments.end ())
{
LogPrint (eLogDebug, "TunnelMessage: Out-of-sequence fragment ", (int)msg.nextFragmentNum, " of message ", msgID, " found");
size_t size = it->second.data->GetLength ();
if (msg.data->len + size > msg.data->maxLen)
{
LogPrint (eLogWarning, "TunnelMessage: Tunnel endpoint I2NP message size ", msg.data->maxLen, " is not enough");
auto newMsg = NewI2NPMessage ();
*newMsg = *(msg.data);
msg.data = newMsg;
}
if (msg.data->Concat (it->second.data->GetBuffer (), size) < size) // concatenate out-of-sync fragment
LogPrint (eLogError, "TunnelMessage: Tunnel endpoint I2NP buffer overflow ", msg.data->maxLen);
if (it->second.isLastFragment)
// message complete
msg.nextFragmentNum = 0;
else
msg.nextFragmentNum++;
m_OutOfSequenceFragments.erase (it);
return true;
}
return false;
}
void TunnelEndpoint::HandleNextMessage (const TunnelMessageBlock& msg)
{
if (!m_IsInbound && msg.data->IsExpired ())
{
LogPrint (eLogInfo, "TunnelMessage: message expired");
return;
}
uint8_t typeID = msg.data->GetTypeID ();
LogPrint (eLogDebug, "TunnelMessage: handle fragment of ", msg.data->GetLength (), " bytes, msg type ", (int)typeID);
// catch RI or reply with new list of routers
if ((IsRouterInfoMsg (msg.data) || typeID == eI2NPDatabaseSearchReply) &&
!m_IsInbound && msg.deliveryType != eDeliveryTypeLocal)
i2p::data::netdb.PostI2NPMsg (CopyI2NPMessage (msg.data));
switch (msg.deliveryType)
{
case eDeliveryTypeLocal:
i2p::HandleI2NPMessage (msg.data);
break;
case eDeliveryTypeTunnel:
if (!m_IsInbound) // outbound transit tunnel
i2p::transport::transports.SendMessage (msg.hash, i2p::CreateTunnelGatewayMsg (msg.tunnelID, msg.data));
else
LogPrint (eLogError, "TunnelMessage: Delivery type 'tunnel' arrived from an inbound tunnel, dropped");
break;
case eDeliveryTypeRouter:
if (!m_IsInbound) // outbound transit tunnel
i2p::transport::transports.SendMessage (msg.hash, msg.data);
else // we shouldn't send this message. possible leakage
LogPrint (eLogError, "TunnelMessage: Delivery type 'router' arrived from an inbound tunnel, dropped");
break;
default:
LogPrint (eLogError, "TunnelMessage: Unknown delivery type ", (int)msg.deliveryType);
};
}
void TunnelEndpoint::Cleanup ()
{
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
// out-of-sequence fragments
for (auto it = m_OutOfSequenceFragments.begin (); it != m_OutOfSequenceFragments.end ();)
{
if (ts > it->second.receiveTime + i2p::I2NP_MESSAGE_EXPIRATION_TIMEOUT)
it = m_OutOfSequenceFragments.erase (it);
else
++it;
}
// incomplete messages
for (auto it = m_IncompleteMessages.begin (); it != m_IncompleteMessages.end ();)
{
if (ts > it->second.receiveTime + i2p::I2NP_MESSAGE_EXPIRATION_TIMEOUT)
it = m_IncompleteMessages.erase (it);
else
++it;
}
}
}
}

View File

@ -1,57 +0,0 @@
#ifndef TUNNEL_ENDPOINT_H__
#define TUNNEL_ENDPOINT_H__
#include <inttypes.h>
#include <map>
#include <string>
#include "I2NPProtocol.h"
#include "TunnelBase.h"
namespace i2p
{
namespace tunnel
{
class TunnelEndpoint
{
struct TunnelMessageBlockEx: public TunnelMessageBlock
{
uint64_t receiveTime; // milliseconds since epoch
uint8_t nextFragmentNum;
};
struct Fragment
{
bool isLastFragment;
std::shared_ptr<I2NPMessage> data;
uint64_t receiveTime; // milliseconds since epoch
};
public:
TunnelEndpoint (bool isInbound): m_IsInbound (isInbound), m_NumReceivedBytes (0) {};
~TunnelEndpoint ();
size_t GetNumReceivedBytes () const { return m_NumReceivedBytes; };
void Cleanup ();
void HandleDecryptedTunnelDataMsg (std::shared_ptr<I2NPMessage> msg);
private:
void HandleFollowOnFragment (uint32_t msgID, bool isLastFragment, const TunnelMessageBlockEx& m);
void HandleNextMessage (const TunnelMessageBlock& msg);
void AddOutOfSequenceFragment (uint32_t msgID, uint8_t fragmentNum, bool isLastFragment, std::shared_ptr<I2NPMessage> data);
bool ConcatNextOutOfSequenceFragment (uint32_t msgID, TunnelMessageBlockEx& msg); // true if something added
void HandleOutOfSequenceFragments (uint32_t msgID, TunnelMessageBlockEx& msg);
private:
std::map<uint32_t, TunnelMessageBlockEx> m_IncompleteMessages;
std::map<std::pair<uint32_t, uint8_t>, Fragment> m_OutOfSequenceFragments; // (msgID, fragment#)->fragment
bool m_IsInbound;
size_t m_NumReceivedBytes;
};
}
}
#endif

View File

@ -1,593 +0,0 @@
#include <algorithm>
#include "I2PEndian.h"
#include "Crypto.h"
#include "Tunnel.h"
#include "NetDb.h"
#include "Timestamp.h"
#include "Garlic.h"
#include "Transports.h"
#include "Log.h"
#include "Tunnel.h"
#include "TunnelPool.h"
#include "Destination.h"
#ifdef WITH_EVENTS
#include "Event.h"
#endif
namespace i2p
{
namespace tunnel
{
TunnelPool::TunnelPool (int numInboundHops, int numOutboundHops, int numInboundTunnels, int numOutboundTunnels):
m_NumInboundHops (numInboundHops), m_NumOutboundHops (numOutboundHops),
m_NumInboundTunnels (numInboundTunnels), m_NumOutboundTunnels (numOutboundTunnels), m_IsActive (true),
m_CustomPeerSelector(nullptr)
{
}
TunnelPool::~TunnelPool ()
{
DetachTunnels ();
}
void TunnelPool::SetExplicitPeers (std::shared_ptr<std::vector<i2p::data::IdentHash> > explicitPeers)
{
m_ExplicitPeers = explicitPeers;
if (m_ExplicitPeers)
{
int size = m_ExplicitPeers->size ();
if (m_NumInboundHops > size)
{
m_NumInboundHops = size;
LogPrint (eLogInfo, "Tunnels: Inbound tunnel length has beed adjusted to ", size, " for explicit peers");
}
if (m_NumOutboundHops > size)
{
m_NumOutboundHops = size;
LogPrint (eLogInfo, "Tunnels: Outbound tunnel length has beed adjusted to ", size, " for explicit peers");
}
m_NumInboundTunnels = 1;
m_NumOutboundTunnels = 1;
}
}
void TunnelPool::DetachTunnels ()
{
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
for (auto& it: m_InboundTunnels)
it->SetTunnelPool (nullptr);
m_InboundTunnels.clear ();
}
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
for (auto& it: m_OutboundTunnels)
it->SetTunnelPool (nullptr);
m_OutboundTunnels.clear ();
}
m_Tests.clear ();
}
void TunnelPool::TunnelCreated (std::shared_ptr<InboundTunnel> createdTunnel)
{
if (!m_IsActive) return;
{
#ifdef WITH_EVENTS
EmitTunnelEvent("tunnels.created", createdTunnel);
#endif
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
m_InboundTunnels.insert (createdTunnel);
}
if (m_LocalDestination)
m_LocalDestination->SetLeaseSetUpdated ();
OnTunnelBuildResult(createdTunnel, eBuildResultOkay);
}
void TunnelPool::TunnelExpired (std::shared_ptr<InboundTunnel> expiredTunnel)
{
if (expiredTunnel)
{
#ifdef WITH_EVENTS
EmitTunnelEvent("tunnels.expired", expiredTunnel);
#endif
expiredTunnel->SetTunnelPool (nullptr);
for (auto& it: m_Tests)
if (it.second.second == expiredTunnel) it.second.second = nullptr;
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
m_InboundTunnels.erase (expiredTunnel);
}
}
void TunnelPool::TunnelCreated (std::shared_ptr<OutboundTunnel> createdTunnel)
{
if (!m_IsActive) return;
{
#ifdef WITH_EVENTS
EmitTunnelEvent("tunnels.created", createdTunnel);
#endif
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
m_OutboundTunnels.insert (createdTunnel);
}
OnTunnelBuildResult(createdTunnel, eBuildResultOkay);
//CreatePairedInboundTunnel (createdTunnel);
}
void TunnelPool::TunnelExpired (std::shared_ptr<OutboundTunnel> expiredTunnel)
{
if (expiredTunnel)
{
#ifdef WITH_EVENTS
EmitTunnelEvent("tunnels.expired", expiredTunnel);
#endif
expiredTunnel->SetTunnelPool (nullptr);
for (auto& it: m_Tests)
if (it.second.first == expiredTunnel) it.second.first = nullptr;
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
m_OutboundTunnels.erase (expiredTunnel);
}
}
std::vector<std::shared_ptr<InboundTunnel> > TunnelPool::GetInboundTunnels (int num) const
{
std::vector<std::shared_ptr<InboundTunnel> > v;
int i = 0;
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
for (const auto& it : m_InboundTunnels)
{
if (i >= num) break;
if (it->IsEstablished ())
{
v.push_back (it);
i++;
}
}
return v;
}
std::shared_ptr<OutboundTunnel> TunnelPool::GetNextOutboundTunnel (std::shared_ptr<OutboundTunnel> excluded) const
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
return GetNextTunnel (m_OutboundTunnels, excluded);
}
std::shared_ptr<InboundTunnel> TunnelPool::GetNextInboundTunnel (std::shared_ptr<InboundTunnel> excluded) const
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
return GetNextTunnel (m_InboundTunnels, excluded);
}
template<class TTunnels>
typename TTunnels::value_type TunnelPool::GetNextTunnel (TTunnels& tunnels, typename TTunnels::value_type excluded) const
{
if (tunnels.empty ()) return nullptr;
uint32_t ind = rand () % (tunnels.size ()/2 + 1), i = 0;
typename TTunnels::value_type tunnel = nullptr;
for (const auto& it: tunnels)
{
if (it->IsEstablished () && it != excluded)
{
if(HasLatencyRequirement() && it->LatencyIsKnown() && !it->LatencyFitsRange(m_MinLatency, m_MaxLatency)) {
i ++;
continue;
}
tunnel = it;
i++;
}
if (i > ind && tunnel) break;
}
if(HasLatencyRequirement() && !tunnel) {
ind = rand () % (tunnels.size ()/2 + 1), i = 0;
for (const auto& it: tunnels)
{
if (it->IsEstablished () && it != excluded)
{
tunnel = it;
i++;
}
if (i > ind && tunnel) break;
}
}
if (!tunnel && excluded && excluded->IsEstablished ()) tunnel = excluded;
return tunnel;
}
std::shared_ptr<OutboundTunnel> TunnelPool::GetNewOutboundTunnel (std::shared_ptr<OutboundTunnel> old) const
{
if (old && old->IsEstablished ()) return old;
std::shared_ptr<OutboundTunnel> tunnel;
if (old)
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
for (const auto& it: m_OutboundTunnels)
if (it->IsEstablished () && old->GetEndpointIdentHash () == it->GetEndpointIdentHash ())
{
tunnel = it;
break;
}
}
if (!tunnel)
tunnel = GetNextOutboundTunnel ();
return tunnel;
}
void TunnelPool::CreateTunnels ()
{
int num = 0;
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
for (const auto& it : m_OutboundTunnels)
if (it->IsEstablished ()) num++;
}
for (int i = num; i < m_NumOutboundTunnels; i++)
CreateOutboundTunnel ();
num = 0;
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
for (const auto& it : m_InboundTunnels)
if (it->IsEstablished ()) num++;
}
for (int i = num; i < m_NumInboundTunnels; i++)
CreateInboundTunnel ();
if (num < m_NumInboundTunnels && m_NumInboundHops <= 0 && m_LocalDestination) // zero hops IB
m_LocalDestination->SetLeaseSetUpdated (); // update LeaseSet immediately
}
void TunnelPool::TestTunnels ()
{
decltype(m_Tests) tests;
{
std::unique_lock<std::mutex> l(m_TestsMutex);
tests.swap(m_Tests);
}
for (auto& it: tests)
{
LogPrint (eLogWarning, "Tunnels: test of tunnel ", it.first, " failed");
// if test failed again with another tunnel we consider it failed
if (it.second.first)
{
if (it.second.first->GetState () == eTunnelStateTestFailed)
{
it.second.first->SetState (eTunnelStateFailed);
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
m_OutboundTunnels.erase (it.second.first);
}
else
it.second.first->SetState (eTunnelStateTestFailed);
}
if (it.second.second)
{
if (it.second.second->GetState () == eTunnelStateTestFailed)
{
it.second.second->SetState (eTunnelStateFailed);
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
m_InboundTunnels.erase (it.second.second);
}
if (m_LocalDestination)
m_LocalDestination->SetLeaseSetUpdated ();
}
else
it.second.second->SetState (eTunnelStateTestFailed);
}
}
// new tests
auto it1 = m_OutboundTunnels.begin ();
auto it2 = m_InboundTunnels.begin ();
while (it1 != m_OutboundTunnels.end () && it2 != m_InboundTunnels.end ())
{
bool failed = false;
if ((*it1)->IsFailed ())
{
failed = true;
++it1;
}
if ((*it2)->IsFailed ())
{
failed = true;
++it2;
}
if (!failed)
{
uint32_t msgID;
RAND_bytes ((uint8_t *)&msgID, 4);
{
std::unique_lock<std::mutex> l(m_TestsMutex);
m_Tests[msgID] = std::make_pair (*it1, *it2);
}
(*it1)->SendTunnelDataMsg ((*it2)->GetNextIdentHash (), (*it2)->GetNextTunnelID (),
CreateDeliveryStatusMsg (msgID));
++it1; ++it2;
}
}
}
void TunnelPool::ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg)
{
if (m_LocalDestination)
m_LocalDestination->ProcessGarlicMessage (msg);
else
LogPrint (eLogWarning, "Tunnels: local destination doesn't exist, dropped");
}
void TunnelPool::ProcessDeliveryStatus (std::shared_ptr<I2NPMessage> msg)
{
const uint8_t * buf = msg->GetPayload ();
uint32_t msgID = bufbe32toh (buf);
buf += 4;
uint64_t timestamp = bufbe64toh (buf);
decltype(m_Tests)::mapped_type test;
bool found = false;
{
std::unique_lock<std::mutex> l(m_TestsMutex);
auto it = m_Tests.find (msgID);
if (it != m_Tests.end ())
{
found = true;
test = it->second;
m_Tests.erase (it);
}
}
if (found)
{
// restore from test failed state if any
if (test.first->GetState () == eTunnelStateTestFailed)
test.first->SetState (eTunnelStateEstablished);
if (test.second->GetState () == eTunnelStateTestFailed)
test.second->SetState (eTunnelStateEstablished);
uint64_t dlt = i2p::util::GetMillisecondsSinceEpoch () - timestamp;
LogPrint (eLogDebug, "Tunnels: test of ", msgID, " successful. ", dlt, " milliseconds");
// update latency
uint64_t latency = dlt / 2;
test.first->AddLatencySample(latency);
test.second->AddLatencySample(latency);
}
else
{
if (m_LocalDestination)
m_LocalDestination->ProcessDeliveryStatusMessage (msg);
else
LogPrint (eLogWarning, "Tunnels: Local destination doesn't exist, dropped");
}
}
std::shared_ptr<const i2p::data::RouterInfo> TunnelPool::SelectNextHop (std::shared_ptr<const i2p::data::RouterInfo> prevHop) const
{
bool isExploratory = (i2p::tunnel::tunnels.GetExploratoryPool () == shared_from_this ());
auto hop = isExploratory ? i2p::data::netdb.GetRandomRouter (prevHop):
i2p::data::netdb.GetHighBandwidthRandomRouter (prevHop);
if (!hop || hop->GetProfile ()->IsBad ())
hop = i2p::data::netdb.GetRandomRouter (prevHop);
return hop;
}
bool TunnelPool::SelectPeers (std::vector<std::shared_ptr<const i2p::data::IdentityEx> >& peers, bool isInbound)
{
int numHops = isInbound ? m_NumInboundHops : m_NumOutboundHops;
// peers is empty
if (numHops <= 0) return true;
// custom peer selector in use ?
{
std::lock_guard<std::mutex> lock(m_CustomPeerSelectorMutex);
if (m_CustomPeerSelector)
return m_CustomPeerSelector->SelectPeers(peers, numHops, isInbound);
}
// explicit peers in use
if (m_ExplicitPeers) return SelectExplicitPeers (peers, isInbound);
auto prevHop = i2p::context.GetSharedRouterInfo ();
if(i2p::transport::transports.RoutesRestricted())
{
/** if routes are restricted prepend trusted first hop */
auto hop = i2p::transport::transports.GetRestrictedPeer();
if(!hop) return false;
peers.push_back(hop->GetRouterIdentity());
prevHop = hop;
}
else if (i2p::transport::transports.GetNumPeers () > 25)
{
auto r = i2p::transport::transports.GetRandomPeer ();
if (r && !r->GetProfile ()->IsBad ())
{
prevHop = r;
peers.push_back (r->GetRouterIdentity ());
numHops--;
}
}
for(int i = 0; i < numHops; i++ )
{
auto hop = SelectNextHop (prevHop);
if (!hop)
{
LogPrint (eLogError, "Tunnels: Can't select next hop for ", prevHop->GetIdentHashBase64 ());
return false;
}
prevHop = hop;
peers.push_back (hop->GetRouterIdentity ());
}
return true;
}
bool TunnelPool::SelectExplicitPeers (std::vector<std::shared_ptr<const i2p::data::IdentityEx> >& peers, bool isInbound)
{
int size = m_ExplicitPeers->size ();
std::vector<int> peerIndicies;
for (int i = 0; i < size; i++) peerIndicies.push_back(i);
std::random_shuffle (peerIndicies.begin(), peerIndicies.end());
int numHops = isInbound ? m_NumInboundHops : m_NumOutboundHops;
for (int i = 0; i < numHops; i++)
{
auto& ident = (*m_ExplicitPeers)[peerIndicies[i]];
auto r = i2p::data::netdb.FindRouter (ident);
if (r)
peers.push_back (r->GetRouterIdentity ());
else
{
LogPrint (eLogInfo, "Tunnels: Can't find router for ", ident.ToBase64 ());
i2p::data::netdb.RequestDestination (ident);
return false;
}
}
return true;
}
void TunnelPool::CreateInboundTunnel ()
{
auto outboundTunnel = GetNextOutboundTunnel ();
if (!outboundTunnel)
outboundTunnel = tunnels.GetNextOutboundTunnel ();
LogPrint (eLogDebug, "Tunnels: Creating destination inbound tunnel...");
std::vector<std::shared_ptr<const i2p::data::IdentityEx> > peers;
if (SelectPeers (peers, true))
{
std::shared_ptr<TunnelConfig> config;
if (m_NumInboundHops > 0)
{
std::reverse (peers.begin (), peers.end ());
config = std::make_shared<TunnelConfig> (peers);
}
auto tunnel = tunnels.CreateInboundTunnel (config, outboundTunnel);
tunnel->SetTunnelPool (shared_from_this ());
if (tunnel->IsEstablished ()) // zero hops
TunnelCreated (tunnel);
}
else
LogPrint (eLogError, "Tunnels: Can't create inbound tunnel, no peers available");
}
void TunnelPool::RecreateInboundTunnel (std::shared_ptr<InboundTunnel> tunnel)
{
auto outboundTunnel = GetNextOutboundTunnel ();
if (!outboundTunnel)
outboundTunnel = tunnels.GetNextOutboundTunnel ();
LogPrint (eLogDebug, "Tunnels: Re-creating destination inbound tunnel...");
std::shared_ptr<TunnelConfig> config;
if (m_NumInboundHops > 0) config = std::make_shared<TunnelConfig>(tunnel->GetPeers ());
auto newTunnel = tunnels.CreateInboundTunnel (config, outboundTunnel);
newTunnel->SetTunnelPool (shared_from_this());
if (newTunnel->IsEstablished ()) // zero hops
TunnelCreated (newTunnel);
}
void TunnelPool::CreateOutboundTunnel ()
{
auto inboundTunnel = GetNextInboundTunnel ();
if (!inboundTunnel)
inboundTunnel = tunnels.GetNextInboundTunnel ();
if (inboundTunnel)
{
LogPrint (eLogDebug, "Tunnels: Creating destination outbound tunnel...");
std::vector<std::shared_ptr<const i2p::data::IdentityEx> > peers;
if (SelectPeers (peers, false))
{
std::shared_ptr<TunnelConfig> config;
if (m_NumOutboundHops > 0)
config = std::make_shared<TunnelConfig>(peers, inboundTunnel->GetNextTunnelID (), inboundTunnel->GetNextIdentHash ());
auto tunnel = tunnels.CreateOutboundTunnel (config);
tunnel->SetTunnelPool (shared_from_this ());
if (tunnel->IsEstablished ()) // zero hops
TunnelCreated (tunnel);
}
else
LogPrint (eLogError, "Tunnels: Can't create outbound tunnel, no peers available");
}
else
LogPrint (eLogError, "Tunnels: Can't create outbound tunnel, no inbound tunnels found");
}
void TunnelPool::RecreateOutboundTunnel (std::shared_ptr<OutboundTunnel> tunnel)
{
auto inboundTunnel = GetNextInboundTunnel ();
if (!inboundTunnel)
inboundTunnel = tunnels.GetNextInboundTunnel ();
if (inboundTunnel)
{
LogPrint (eLogDebug, "Tunnels: Re-creating destination outbound tunnel...");
std::shared_ptr<TunnelConfig> config;
if (m_NumOutboundHops > 0)
config = std::make_shared<TunnelConfig>(tunnel->GetPeers (), inboundTunnel->GetNextTunnelID (), inboundTunnel->GetNextIdentHash ());
auto newTunnel = tunnels.CreateOutboundTunnel (config);
newTunnel->SetTunnelPool (shared_from_this ());
if (newTunnel->IsEstablished ()) // zero hops
TunnelCreated (newTunnel);
}
else
LogPrint (eLogDebug, "Tunnels: Can't re-create outbound tunnel, no inbound tunnels found");
}
void TunnelPool::CreatePairedInboundTunnel (std::shared_ptr<OutboundTunnel> outboundTunnel)
{
LogPrint (eLogDebug, "Tunnels: Creating paired inbound tunnel...");
auto tunnel = tunnels.CreateInboundTunnel (std::make_shared<TunnelConfig>(outboundTunnel->GetInvertedPeers ()), outboundTunnel);
tunnel->SetTunnelPool (shared_from_this ());
}
void TunnelPool::SetCustomPeerSelector(TunnelPeerSelector selector)
{
std::lock_guard<std::mutex> lock(m_CustomPeerSelectorMutex);
m_CustomPeerSelector = selector;
}
void TunnelPool::UnsetCustomPeerSelector()
{
SetCustomPeerSelector(nullptr);
}
bool TunnelPool::HasCustomPeerSelector()
{
std::lock_guard<std::mutex> lock(m_CustomPeerSelectorMutex);
return m_CustomPeerSelector != nullptr;
}
std::shared_ptr<InboundTunnel> TunnelPool::GetLowestLatencyInboundTunnel(std::shared_ptr<InboundTunnel> exclude) const
{
std::shared_ptr<InboundTunnel> tun = nullptr;
std::unique_lock<std::mutex> lock(m_InboundTunnelsMutex);
uint64_t min = 1000000;
for (const auto & itr : m_InboundTunnels) {
if(!itr->LatencyIsKnown()) continue;
auto l = itr->GetMeanLatency();
if (l >= min) continue;
tun = itr;
if(tun == exclude) continue;
min = l;
}
return tun;
}
std::shared_ptr<OutboundTunnel> TunnelPool::GetLowestLatencyOutboundTunnel(std::shared_ptr<OutboundTunnel> exclude) const
{
std::shared_ptr<OutboundTunnel> tun = nullptr;
std::unique_lock<std::mutex> lock(m_OutboundTunnelsMutex);
uint64_t min = 1000000;
for (const auto & itr : m_OutboundTunnels) {
if(!itr->LatencyIsKnown()) continue;
auto l = itr->GetMeanLatency();
if (l >= min) continue;
tun = itr;
if(tun == exclude) continue;
min = l;
}
return tun;
}
void TunnelPool::OnTunnelBuildResult(std::shared_ptr<Tunnel> tunnel, TunnelBuildResult result)
{
auto peers = tunnel->GetPeers();
if(m_CustomPeerSelector) m_CustomPeerSelector->OnBuildResult(peers, tunnel->IsInbound(), result);
}
}
}

205
UPnP.cpp
View File

@ -1,205 +0,0 @@
#ifdef USE_UPNP
#include <string>
#include <thread>
#include <boost/thread/thread.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include "Log.h"
#include "RouterContext.h"
#include "UPnP.h"
#include "NetDb.h"
#include "util.h"
#include "RouterInfo.h"
#include "Config.h"
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
namespace i2p
{
namespace transport
{
UPnP::UPnP () : m_IsRunning(false), m_Thread (nullptr), m_Timer (m_Service)
{
}
void UPnP::Stop ()
{
if (m_IsRunning)
{
LogPrint(eLogInfo, "UPnP: stopping");
m_IsRunning = false;
m_Timer.cancel ();
m_Service.stop ();
if (m_Thread)
{
m_Thread->join ();
m_Thread.reset (nullptr);
}
CloseMapping ();
Close ();
}
}
void UPnP::Start()
{
m_IsRunning = true;
LogPrint(eLogInfo, "UPnP: starting");
m_Service.post (std::bind (&UPnP::Discover, this));
std::unique_lock<std::mutex> l(m_StartedMutex);
m_Thread.reset (new std::thread (std::bind (&UPnP::Run, this)));
m_Started.wait_for (l, std::chrono::seconds (5)); // 5 seconds maximum
}
UPnP::~UPnP ()
{
Stop ();
}
void UPnP::Run ()
{
while (m_IsRunning)
{
try
{
m_Service.run ();
// Discover failed
break; // terminate the thread
}
catch (std::exception& ex)
{
LogPrint (eLogError, "UPnP: runtime exception: ", ex.what ());
PortMapping ();
}
}
}
void UPnP::Discover ()
{
int nerror = 0;
#if MINIUPNPC_API_VERSION >= 14
m_Devlist = upnpDiscover (2000, m_MulticastIf, m_Minissdpdpath, 0, 0, 2, &nerror);
#else
m_Devlist = upnpDiscover (2000, m_MulticastIf, m_Minissdpdpath, 0, 0, &nerror);
#endif
{
// notify satrting thread
std::unique_lock<std::mutex> l(m_StartedMutex);
m_Started.notify_all ();
}
int r;
r = UPNP_GetValidIGD (m_Devlist, &m_upnpUrls, &m_upnpData, m_NetworkAddr, sizeof (m_NetworkAddr));
if (r == 1)
{
r = UPNP_GetExternalIPAddress (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
{
LogPrint (eLogError, "UPnP: UPNP_GetExternalIPAddress() returned ", r);
return;
}
else
{
if (!m_externalIPAddress[0])
{
LogPrint (eLogError, "UPnP: GetExternalIPAddress() failed.");
return;
}
}
}
else
{
LogPrint (eLogError, "UPnP: GetValidIGD() failed.");
return;
}
// UPnP discovered
LogPrint (eLogDebug, "UPnP: ExternalIPAddress is ", m_externalIPAddress);
i2p::context.UpdateAddress (boost::asio::ip::address::from_string (m_externalIPAddress));
// port mapping
PortMapping ();
}
void UPnP::PortMapping ()
{
const auto& a = context.GetRouterInfo().GetAddresses();
for (const auto& address : a)
{
if (!address->host.is_v6 ())
TryPortMapping (address);
}
m_Timer.expires_from_now (boost::posix_time::minutes(20)); // every 20 minutes
m_Timer.async_wait ([this](const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
PortMapping ();
});
}
void UPnP::CloseMapping ()
{
const auto& a = context.GetRouterInfo().GetAddresses();
for (const auto& address : a)
{
if (!address->host.is_v6 ())
CloseMapping (address);
}
}
void UPnP::TryPortMapping (std::shared_ptr<i2p::data::RouterInfo::Address> address)
{
std::string strType (GetProto (address)), strPort (std::to_string (address->port));
int r;
std::string strDesc; i2p::config::GetOption("upnp.name", strDesc);
r = UPNP_AddPortMapping (m_upnpUrls.controlURL, m_upnpData.first.servicetype, strPort.c_str (), strPort.c_str (), m_NetworkAddr, strDesc.c_str (), strType.c_str (), 0, "0");
if (r!=UPNPCOMMAND_SUCCESS)
{
LogPrint (eLogError, "UPnP: AddPortMapping (", m_NetworkAddr, ":", strPort, ") failed with code ", r);
return;
}
else
{
LogPrint (eLogDebug, "UPnP: Port Mapping successful. (", m_NetworkAddr ,":", strPort, " type ", strType, " -> ", m_externalIPAddress ,":", strPort ,")");
return;
}
}
void UPnP::CloseMapping (std::shared_ptr<i2p::data::RouterInfo::Address> address)
{
std::string strType (GetProto (address)), strPort (std::to_string (address->port));
int r = 0;
r = UPNP_DeletePortMapping (m_upnpUrls.controlURL, m_upnpData.first.servicetype, strPort.c_str (), strType.c_str (), 0);
LogPrint (eLogError, "UPnP: DeletePortMapping() returned : ", r);
}
void UPnP::Close ()
{
freeUPNPDevlist (m_Devlist);
m_Devlist = 0;
FreeUPNPUrls (&m_upnpUrls);
}
std::string UPnP::GetProto (std::shared_ptr<i2p::data::RouterInfo::Address> address)
{
switch (address->transportStyle)
{
case i2p::data::RouterInfo::eTransportNTCP:
return "TCP";
break;
case i2p::data::RouterInfo::eTransportSSU:
default:
return "UDP";
}
}
}
}
#else /* USE_UPNP */
namespace i2p {
namespace transport {
}
}
#endif /* USE_UPNP */

79
UPnP.h
View File

@ -1,79 +0,0 @@
#ifndef __UPNP_H__
#define __UPNP_H__
#ifdef USE_UPNP
#include <string>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <memory>
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#include <boost/asio.hpp>
namespace i2p
{
namespace transport
{
class UPnP
{
public:
UPnP ();
~UPnP ();
void Close ();
void Start ();
void Stop ();
private:
void Discover ();
void PortMapping ();
void TryPortMapping (std::shared_ptr<i2p::data::RouterInfo::Address> address);
void CloseMapping ();
void CloseMapping (std::shared_ptr<i2p::data::RouterInfo::Address> address);
void Run ();
std::string GetProto (std::shared_ptr<i2p::data::RouterInfo::Address> address);
private:
bool m_IsRunning;
std::unique_ptr<std::thread> m_Thread;
std::condition_variable m_Started;
std::mutex m_StartedMutex;
boost::asio::io_service m_Service;
boost::asio::deadline_timer m_Timer;
struct UPNPUrls m_upnpUrls;
struct IGDdatas m_upnpData;
// For miniupnpc
char * m_MulticastIf = 0;
char * m_Minissdpdpath = 0;
struct UPNPDev * m_Devlist = 0;
char m_NetworkAddr[64];
char m_externalIPAddress[40];
};
}
}
#else // USE_UPNP
namespace i2p {
namespace transport {
/* class stub */
class UPnP {
public:
UPnP () {};
~UPnP () {};
void Start () { LogPrint(eLogWarning, "UPnP: this module was disabled at compile-time"); }
void Stop () {};
};
}
}
#endif // USE_UPNP
#endif // __UPNP_H__

View File

@ -1,467 +0,0 @@
#include "WebSocks.h"
#include "Log.h"
#include <string>
#ifdef WITH_EVENTS
#include "ClientContext.h"
#include "Identity.h"
#include "Destination.h"
#include "Streaming.h"
#include <functional>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include <boost/property_tree/ini_parser.hpp>
#define GCC47_BOOST149 ((BOOST_VERSION == 104900) && (__GNUC__ == 4) && (__GNUC_MINOR__ >= 7))
#if !GCC47_BOOST149
#include <boost/property_tree/json_parser.hpp>
#endif
namespace i2p
{
namespace client
{
typedef websocketpp::server<websocketpp::config::asio> WebSocksServerImpl;
typedef std::function<void(std::shared_ptr<i2p::stream::Stream>)> StreamConnectFunc;
struct IWebSocksConn : public I2PServiceHandler
{
IWebSocksConn(I2PService * parent) : I2PServiceHandler(parent) {}
virtual void Close() = 0;
virtual void GotMessage(const websocketpp::connection_hdl & conn, WebSocksServerImpl::message_ptr msg) = 0;
};
typedef std::shared_ptr<IWebSocksConn> WebSocksConn_ptr;
WebSocksConn_ptr CreateWebSocksConn(const websocketpp::connection_hdl & conn, WebSocksImpl * parent);
class WebSocksImpl
{
typedef std::mutex mutex_t;
typedef std::unique_lock<mutex_t> lock_t;
typedef std::shared_ptr<ClientDestination> Destination_t;
public:
typedef WebSocksServerImpl ServerImpl;
typedef ServerImpl::message_ptr MessagePtr;
WebSocksImpl(const std::string & addr, int port) :
Parent(nullptr),
m_Run(false),
m_Addr(addr),
m_Port(port),
m_Thread(nullptr)
{
m_Server.init_asio();
m_Server.set_open_handler(std::bind(&WebSocksImpl::ConnOpened, this, std::placeholders::_1));
}
void InitializeDestination(WebSocks * parent)
{
Parent = parent;
m_Dest = Parent->GetLocalDestination();
}
ServerImpl::connection_ptr GetConn(const websocketpp::connection_hdl & conn)
{
return m_Server.get_con_from_hdl(conn);
}
void CloseConn(const websocketpp::connection_hdl & conn)
{
auto c = GetConn(conn);
if(c) c->close(websocketpp::close::status::normal, "closed");
}
void CreateStreamTo(const std::string & addr, int port, StreamConnectFunc complete)
{
auto & addressbook = i2p::client::context.GetAddressBook();
i2p::data::IdentHash ident;
if(addressbook.GetIdentHash(addr, ident)) {
// address found
m_Dest->CreateStream(complete, ident, port);
} else {
// not found
complete(nullptr);
}
}
void ConnOpened(websocketpp::connection_hdl conn)
{
auto ptr = CreateWebSocksConn(conn, this);
Parent->AddHandler(ptr);
m_Conns.push_back(ptr);
}
void Start()
{
if(m_Run) return; // already started
m_Server.listen(boost::asio::ip::address::from_string(m_Addr), m_Port);
m_Server.start_accept();
m_Run = true;
m_Thread = new std::thread([&] (){
while(m_Run) {
try {
m_Server.run();
} catch( std::exception & ex) {
LogPrint(eLogError, "Websocks runtime exception: ", ex.what());
}
}
});
m_Dest->Start();
}
void Stop()
{
for(const auto & conn : m_Conns)
conn->Close();
m_Dest->Stop();
m_Run = false;
m_Server.stop();
if(m_Thread) {
m_Thread->join();
delete m_Thread;
}
m_Thread = nullptr;
}
boost::asio::ip::tcp::endpoint GetLocalEndpoint()
{
return boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(m_Addr), m_Port);
}
WebSocks * Parent;
private:
std::vector<WebSocksConn_ptr> m_Conns;
bool m_Run;
ServerImpl m_Server;
std::string m_Addr;
int m_Port;
std::thread * m_Thread;
Destination_t m_Dest;
};
struct WebSocksConn : public IWebSocksConn , public std::enable_shared_from_this<WebSocksConn>
{
enum ConnState
{
eWSCInitial,
eWSCTryConnect,
eWSCFailConnect,
eWSCOkayConnect,
eWSCClose,
eWSCEnd
};
typedef WebSocksServerImpl ServerImpl;
typedef ServerImpl::message_ptr Message_t;
typedef websocketpp::connection_hdl ServerConn;
typedef std::shared_ptr<ClientDestination> Destination_t;
typedef std::shared_ptr<i2p::stream::StreamingDestination> StreamDest_t;
typedef std::shared_ptr<i2p::stream::Stream> Stream_t;
ServerConn m_Conn;
Stream_t m_Stream;
ConnState m_State;
WebSocksImpl * m_Parent;
std::string m_RemoteAddr;
int m_RemotePort;
uint8_t m_RecvBuf[2048];
WebSocksConn(const ServerConn & conn, WebSocksImpl * parent) :
IWebSocksConn(parent->Parent),
m_Conn(conn),
m_Stream(nullptr),
m_State(eWSCInitial),
m_Parent(parent)
{
}
~WebSocksConn()
{
Close();
}
void EnterState(ConnState state)
{
LogPrint(eLogDebug, "websocks: state ", m_State, " -> ", state);
switch(m_State)
{
case eWSCInitial:
if (state == eWSCClose) {
m_State = eWSCClose;
// connection was opened but never used
LogPrint(eLogInfo, "websocks: connection closed but never used");
Close();
return;
} else if (state == eWSCTryConnect) {
// we will try to connect
m_State = eWSCTryConnect;
m_Parent->CreateStreamTo(m_RemoteAddr, m_RemotePort, std::bind(&WebSocksConn::ConnectResult, this, std::placeholders::_1));
} else {
LogPrint(eLogWarning, "websocks: invalid state change ", m_State, " -> ", state);
}
return;
case eWSCTryConnect:
if(state == eWSCOkayConnect) {
// we connected okay
LogPrint(eLogDebug, "websocks: connected to ", m_RemoteAddr, ":", m_RemotePort);
SendResponse("");
m_State = eWSCOkayConnect;
} else if(state == eWSCFailConnect) {
// we did not connect okay
LogPrint(eLogDebug, "websocks: failed to connect to ", m_RemoteAddr, ":", m_RemotePort);
SendResponse("failed to connect");
m_State = eWSCFailConnect;
EnterState(eWSCInitial);
} else if(state == eWSCClose) {
// premature close
LogPrint(eLogWarning, "websocks: websocket connection closed prematurely");
m_State = eWSCClose;
} else {
LogPrint(eLogWarning, "websocks: invalid state change ", m_State, " -> ", state);
}
return;
case eWSCFailConnect:
if (state == eWSCInitial) {
// reset to initial state so we can try connecting again
m_RemoteAddr = "";
m_RemotePort = 0;
LogPrint(eLogDebug, "websocks: reset websocket conn to initial state");
m_State = eWSCInitial;
} else if (state == eWSCClose) {
// we are going to close the connection
m_State = eWSCClose;
Close();
} else {
LogPrint(eLogWarning, "websocks: invalid state change ", m_State, " -> ", state);
}
return;
case eWSCOkayConnect:
if(state == eWSCClose) {
// graceful close
m_State = eWSCClose;
Close();
} else {
LogPrint(eLogWarning, "websocks: invalid state change ", m_State, " -> ", state);
}
case eWSCClose:
if(state == eWSCEnd) {
LogPrint(eLogDebug, "websocks: socket ended");
Kill();
auto me = shared_from_this();
Done(me);
} else {
LogPrint(eLogWarning, "websocks: invalid state change ", m_State, " -> ", state);
}
return;
default:
LogPrint(eLogError, "websocks: bad state ", m_State);
}
}
void StartForwarding()
{
LogPrint(eLogDebug, "websocks: begin forwarding data");
uint8_t b[1];
m_Stream->Send(b, 0);
AsyncRecv();
}
void HandleAsyncRecv(const boost::system::error_code &ec, std::size_t n)
{
if(ec) {
// error
LogPrint(eLogWarning, "websocks: connection error ", ec.message());
EnterState(eWSCClose);
} else {
// forward data
LogPrint(eLogDebug, "websocks recv ", n);
std::string str((char*)m_RecvBuf, n);
auto conn = m_Parent->GetConn(m_Conn);
if(!conn) {
LogPrint(eLogWarning, "websocks: connection is gone");
EnterState(eWSCClose);
return;
}
conn->send(str);
AsyncRecv();
}
}
void AsyncRecv()
{
m_Stream->AsyncReceive(
boost::asio::buffer(m_RecvBuf, sizeof(m_RecvBuf)),
std::bind(&WebSocksConn::HandleAsyncRecv, this, std::placeholders::_1, std::placeholders::_2), 60);
}
/** @brief send error message or empty string for success */
void SendResponse(const std::string & errormsg)
{
boost::property_tree::ptree resp;
if(errormsg.size()) {
resp.put("error", errormsg);
resp.put("success", 0);
} else {
resp.put("success", 1);
}
std::ostringstream ss;
write_json(ss, resp);
auto conn = m_Parent->GetConn(m_Conn);
if(conn) conn->send(ss.str());
}
void ConnectResult(Stream_t stream)
{
m_Stream = stream;
if(m_State == eWSCClose) {
// premature close of websocket
Close();
return;
}
if(m_Stream) {
// connect good
EnterState(eWSCOkayConnect);
StartForwarding();
} else {
// connect failed
EnterState(eWSCFailConnect);
}
}
virtual void GotMessage(const websocketpp::connection_hdl & conn, WebSocksServerImpl::message_ptr msg)
{
(void) conn;
std::string payload = msg->get_payload();
if(m_State == eWSCOkayConnect)
{
// forward to server
LogPrint(eLogDebug, "websocks: forward ", payload.size());
m_Stream->Send((uint8_t*)payload.c_str(), payload.size());
} else if (m_State == eWSCInitial) {
// recv connect request
auto itr = payload.find(":");
if(itr == std::string::npos) {
// no port
m_RemotePort = 0;
m_RemoteAddr = payload;
} else {
// includes port
m_RemotePort = std::stoi(payload.substr(itr+1));
m_RemoteAddr = payload.substr(0, itr);
}
EnterState(eWSCTryConnect);
} else {
// wtf?
LogPrint(eLogWarning, "websocks: got message in invalid state ", m_State);
}
}
virtual void Close()
{
if(m_State == eWSCClose) {
LogPrint(eLogDebug, "websocks: closing connection");
if(m_Stream) m_Stream->Close();
m_Parent->CloseConn(m_Conn);
EnterState(eWSCEnd);
} else {
EnterState(eWSCClose);
}
}
};
WebSocksConn_ptr CreateWebSocksConn(const websocketpp::connection_hdl & conn, WebSocksImpl * parent)
{
auto ptr = std::make_shared<WebSocksConn>(conn, parent);
auto c = parent->GetConn(conn);
c->set_message_handler(std::bind(&WebSocksConn::GotMessage, ptr.get(), std::placeholders::_1, std::placeholders::_2));
return ptr;
}
}
}
#else
// no websocket support
namespace i2p
{
namespace client
{
class WebSocksImpl
{
public:
WebSocksImpl(const std::string & addr, int port) : m_Addr(addr), m_Port(port)
{
}
~WebSocksImpl()
{
}
void Start()
{
LogPrint(eLogInfo, "WebSockets not enabled on compile time");
}
void Stop()
{
}
void InitializeDestination(WebSocks * parent)
{
}
boost::asio::ip::tcp::endpoint GetLocalEndpoint()
{
return boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(m_Addr), m_Port);
}
std::string m_Addr;
int m_Port;
};
}
}
#endif
namespace i2p
{
namespace client
{
WebSocks::WebSocks(const std::string & addr, int port, std::shared_ptr<ClientDestination> localDestination) : m_Impl(new WebSocksImpl(addr, port))
{
m_Impl->InitializeDestination(this);
}
WebSocks::~WebSocks() { delete m_Impl; }
void WebSocks::Start()
{
m_Impl->Start();
GetLocalDestination()->Start();
}
boost::asio::ip::tcp::endpoint WebSocks::GetLocalEndpoint() const
{
return m_Impl->GetLocalEndpoint();
}
void WebSocks::Stop()
{
m_Impl->Stop();
GetLocalDestination()->Stop();
}
}
}

View File

@ -1,34 +0,0 @@
#ifndef WEBSOCKS_H_
#define WEBSOCKS_H_
#include <string>
#include <memory>
#include "I2PService.h"
#include "Destination.h"
namespace i2p
{
namespace client
{
class WebSocksImpl;
/** @brief websocket socks proxy server */
class WebSocks : public i2p::client::I2PService
{
public:
WebSocks(const std::string & addr, int port, std::shared_ptr<ClientDestination> localDestination);
~WebSocks();
void Start();
void Stop();
boost::asio::ip::tcp::endpoint GetLocalEndpoint() const;
const char * GetName() { return "WebSOCKS Proxy"; }
private:
WebSocksImpl * m_Impl;
};
}
}
#endif

View File

@ -1,193 +0,0 @@
#include "Websocket.h"
#include "Log.h"
#include <set>
#include <functional>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include <boost/property_tree/ini_parser.hpp>
#define GCC47_BOOST149 ((BOOST_VERSION == 104900) && (__GNUC__ == 4) && (__GNUC_MINOR__ >= 7))
#if !GCC47_BOOST149
#include <boost/property_tree/json_parser.hpp>
#endif
#include <stdexcept>
namespace i2p
{
namespace event
{
typedef websocketpp::server<websocketpp::config::asio> ServerImpl;
typedef websocketpp::connection_hdl ServerConn;
class WebsocketServerImpl : public EventListener
{
private:
typedef ServerImpl::message_ptr MessagePtr;
public:
WebsocketServerImpl(const std::string & addr, int port) :
m_run(false),
m_ws_thread(nullptr),
m_ev_thread(nullptr),
m_WebsocketTicker(m_Service)
{
m_server.init_asio();
m_server.set_open_handler(std::bind(&WebsocketServerImpl::ConnOpened, this, std::placeholders::_1));
m_server.set_close_handler(std::bind(&WebsocketServerImpl::ConnClosed, this, std::placeholders::_1));
m_server.set_message_handler(std::bind(&WebsocketServerImpl::OnConnMessage, this, std::placeholders::_1, std::placeholders::_2));
m_server.listen(boost::asio::ip::address::from_string(addr), port);
}
~WebsocketServerImpl()
{
}
void Start() {
m_run = true;
m_server.start_accept();
m_ws_thread = new std::thread([&] () {
while(m_run) {
try {
m_server.run();
} catch (std::exception & e ) {
LogPrint(eLogError, "Websocket server: ", e.what());
}
}
});
m_ev_thread = new std::thread([&] () {
while(m_run) {
try {
m_Service.run();
break;
} catch (std::exception & e ) {
LogPrint(eLogError, "Websocket service: ", e.what());
}
}
});
ScheduleTick();
}
void Stop() {
m_run = false;
m_Service.stop();
m_server.stop();
if(m_ev_thread) {
m_ev_thread->join();
delete m_ev_thread;
}
m_ev_thread = nullptr;
if(m_ws_thread) {
m_ws_thread->join();
delete m_ws_thread;
}
m_ws_thread = nullptr;
}
void ConnOpened(ServerConn c)
{
std::lock_guard<std::mutex> lock(m_connsMutex);
m_conns.insert(c);
}
void ConnClosed(ServerConn c)
{
std::lock_guard<std::mutex> lock(m_connsMutex);
m_conns.erase(c);
}
void OnConnMessage(ServerConn conn, ServerImpl::message_ptr msg)
{
(void) conn;
(void) msg;
}
void HandleTick(const boost::system::error_code & ec)
{
if(ec != boost::asio::error::operation_aborted)
LogPrint(eLogError, "Websocket ticker: ", ec.message());
// pump collected events to us
i2p::event::core.PumpCollected(this);
ScheduleTick();
}
void ScheduleTick()
{
LogPrint(eLogDebug, "Websocket schedule tick");
boost::posix_time::seconds dlt(1);
m_WebsocketTicker.expires_from_now(dlt);
m_WebsocketTicker.async_wait(std::bind(&WebsocketServerImpl::HandleTick, this, std::placeholders::_1));
}
/** @brief called from m_ev_thread */
void HandlePumpEvent(const EventType & ev, const uint64_t & val)
{
EventType e;
for (const auto & i : ev)
e[i.first] = i.second;
e["number"] = std::to_string(val);
HandleEvent(e);
}
/** @brief called from m_ws_thread */
void HandleEvent(const EventType & ev)
{
std::lock_guard<std::mutex> lock(m_connsMutex);
boost::property_tree::ptree event;
for (const auto & item : ev) {
event.put(item.first, item.second);
}
std::ostringstream ss;
write_json(ss, event);
std::string s = ss.str();
ConnList::iterator it;
for (it = m_conns.begin(); it != m_conns.end(); ++it) {
ServerImpl::connection_ptr con = m_server.get_con_from_hdl(*it);
con->send(s);
}
}
private:
typedef std::set<ServerConn, std::owner_less<ServerConn> > ConnList;
bool m_run;
std::thread * m_ws_thread;
std::thread * m_ev_thread;
std::mutex m_connsMutex;
ConnList m_conns;
ServerImpl m_server;
boost::asio::io_service m_Service;
boost::asio::deadline_timer m_WebsocketTicker;
};
WebsocketServer::WebsocketServer(const std::string & addr, int port) : m_impl(new WebsocketServerImpl(addr, port)) {}
WebsocketServer::~WebsocketServer()
{
delete m_impl;
}
void WebsocketServer::Start()
{
m_impl->Start();
}
void WebsocketServer::Stop()
{
m_impl->Stop();
}
EventListener * WebsocketServer::ToListener()
{
return m_impl;
}
}
}

View File

@ -1,28 +0,0 @@
#ifndef WEBSOCKET_H__
#define WEBSOCKET_H__
#include "Event.h"
namespace i2p
{
namespace event
{
class WebsocketServerImpl;
class WebsocketServer
{
public:
WebsocketServer(const std::string & addr, int port);
~WebsocketServer();
void Start();
void Stop();
EventListener * ToListener();
private:
WebsocketServerImpl * m_impl;
};
}
}
#endif

14
Win32/.gitignore vendored
View File

@ -1,14 +0,0 @@
*
!*/
!*.h
!*.cpp
!*.bat
!*.sln
!*.vcproj
!*.vcxproj
!*.vcxproj.filters
!*.iss
!.gitignore

View File

@ -1,14 +0,0 @@
@echo off
convert Itoopie.svg ^
-fuzz 90%% -fill transparent -floodfill 2x2 white -fuzz 20%% -fill #AE0E99 -opaque red ^
-fill #FBBC11 -opaque yellow ^
( -clone 0 -resize 256x256 ) ^
( -clone 0 -resize 128x128 ) ^
( -clone 0 -resize 64x64 ) ^
( -clone 0 -resize 48x48 ) ^
( -clone 0 -resize 32x32 ) ^
( -clone 0 -resize 24x24 ) ^
( -clone 0 -resize 16x16 ) ^
( -size 150x57 xc:white -clone 0 -geometry 57x57+46+0 -composite -gravity center -write BMP3:ictoopie.bmp +delete ) ^
( -clone 0 -write Itoopie_purple.png +delete ) ^
-delete 0 ictoopie.ico

View File

@ -1,282 +0,0 @@
# NSIS Installer script. (Tested with NSIS 2.64 on Windows 7)
# Author: Mikal Villa (Meeh)
# Version: 1.1
Name PurpleI2P
RequestExecutionLevel highest
SetCompressor /SOLID lzma
ShowInstDetails show
# General Symbol Definitions
!define REGKEY "SOFTWARE\$(^Name)"
!define VERSION 0.3.0.0
!define COMPANY "The Privacy Solutions Project"
!define URL "https://i2p.io"
# MUI Symbol Definitions
!define MUI_ICON "mask.ico"
#!define MUI_WELCOMEFINISHPAGE_BITMAP "../share/pixmaps/nsis-wizard.bmp"
!define MUI_HEADERIMAGE
!define MUI_HEADERIMAGE_RIGHT
#!define MUI_HEADERIMAGE_BITMAP "../share/pixmaps/nsis-header.bmp"
!define MUI_FINISHPAGE_NOAUTOCLOSE
!define MUI_STARTMENUPAGE_REGISTRY_ROOT HKLM
!define MUI_STARTMENUPAGE_REGISTRY_KEY ${REGKEY}
!define MUI_STARTMENUPAGE_REGISTRY_VALUENAME StartMenuGroup
!define MUI_STARTMENUPAGE_DEFAULTFOLDER PurpleI2P
!define MUI_FINISHPAGE_RUN $INSTDIR\i2pd.exe
!define MUI_FINISHPAGE_SHOWREADME $INSTDIR\Readme.txt
!define MUI_UNICON "${NSISDIR}\Contrib\Graphics\Icons\modern-uninstall.ico"
!define MUI_UNWELCOMEFINISHPAGE_BITMAP "../share/pixmaps/nsis-wizard.bmp"
!define MUI_UNFINISHPAGE_NOAUTOCLOSE
# Included files
!include Sections.nsh
!include MUI2.nsh
!include nsDialogs.nsh
!include winmessages.nsh
!include logiclib.nsh
# Local included files
!include nsi\helper_readme.nsh
;!include nsi\servicelib.nsh
# Variables
Var StartMenuGroup
# Installer pages
# Execution flow of installer windows
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_README "../Readme.md"
!insertmacro MUI_PAGE_DIRECTORY
# Disabled for now. Use the bat
;Page custom mode_selection # Meeh's hack for installing and starting service.
!insertmacro MUI_PAGE_STARTMENU Application $StartMenuGroup
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
# Uninstall pages
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
# Installer languages
!insertmacro MUI_LANGUAGE English
# Installer attributes
OutFile PurpleI2P-0.3.0.0-win32-setup.exe
InstallDir $PROGRAMFILES\PurpleI2P
CRCCheck on
XPStyle on
BrandingText " "
ShowInstDetails show
VIProductVersion 0.3.0.0
VIAddVersionKey ProductName PurpleI2P
VIAddVersionKey ProductVersion "${VERSION}"
VIAddVersionKey CompanyName "${COMPANY}"
VIAddVersionKey CompanyWebsite "${URL}"
VIAddVersionKey FileVersion "${VERSION}"
VIAddVersionKey FileDescription ""
VIAddVersionKey LegalCopyright ""
InstallDirRegKey HKCU "${REGKEY}" Path
ShowUninstDetails show
# Readme definitions
;--------------------------------
;Languages
;Set up install lang strings for 1st lang
${ReadmeLanguage} "${LANG_ENGLISH}" \
"Read Me" \
"Please review the following important information." \
"About $(^name):" \
"$\n Click on scrollbar arrows or press Page Down to review the entire text."
;Add 2nd language
!insertmacro MUI_LANGUAGE "Norwegian"
;set up install lang strings for second lang
${ReadmeLanguage} "${LANG_NORWEGIAN}" \
"Les meg!" \
"Vennligst les informasjonen om hvordan du skal bruke PurpleI2P." \
"Om $(^name):" \
"$\n Klikk på scrollbaren til høyre for å se hele innholdet."
;--------------------------------
# Installer sections
Section -Main SEC0000
SetOutPath $INSTDIR
SetOverwrite on
File /oname=i2pd.exe Release\i2pd.exe
File /oname=install_service.bat install_service.bat
File /oname=uninstall_service.bat uninstall_service.bat
File /oname=LICENSE.txt ..\LICENSE
File /oname=Readme.txt ..\README.md
SetOutPath $INSTDIR\src
File /r /x *.nsi /x *.rc /x *.exe /x *.obj /x *.nsh /x *.sln /x *.vcxproj /x *.tlog /x *.log /x *.res /x *.pdb /x *.suo /x *.opensdf /x *.filters /x *.sdf /x *.iss /x *.aps /x .gitignore /x *.o ../\*.*
SetOutPath $INSTDIR
RMDir /r /REBOOTOK $INSTDIR\src\.git # Remove git directory
RMDir /r /REBOOTOK $INSTDIR\src\Win32\Release # Removing release directory
RMDir /r /REBOOTOK $INSTDIR\src\Win32\nsi
WriteRegStr HKCU "${REGKEY}\Components" Main 1
SectionEnd
Section -post SEC0001
WriteRegStr HKCU "${REGKEY}" Path $INSTDIR
SetOutPath $INSTDIR
WriteUninstaller $INSTDIR\uninstall.exe
!insertmacro MUI_STARTMENU_WRITE_BEGIN Application
CreateDirectory $SMPROGRAMS\$StartMenuGroup
CreateShortcut "$SMPROGRAMS\$StartMenuGroup\PurpleI2P.lnk" $INSTDIR\i2pd.exe
CreateShortcut "$SMPROGRAMS\$StartMenuGroup\Install PurpleI2P Service.lnk" $INSTDIR\install_service.bat
CreateShortcut "$SMPROGRAMS\$StartMenuGroup\Uninstall PurpleI2P Service.lnk" $INSTDIR\uninstall_service.bat
CreateShortcut "$SMPROGRAMS\$StartMenuGroup\Uninstall PurpleI2P.lnk" $INSTDIR\uninstall.exe
!insertmacro MUI_STARTMENU_WRITE_END
WriteRegStr HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayName "$(^Name)"
WriteRegStr HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayVersion "${VERSION}"
WriteRegStr HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" Publisher "${COMPANY}"
WriteRegStr HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" URLInfoAbout "${URL}"
WriteRegStr HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayIcon $INSTDIR\uninstall.exe
WriteRegStr HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" UninstallString $INSTDIR\uninstall.exe
WriteRegDWORD HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" NoModify 1
WriteRegDWORD HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" NoRepair 1
WriteRegStr HKCR "i2pd" "URL Protocol" ""
WriteRegStr HKCR "i2pd" "" "URL:i2pd" # TODO: if a instance of own is found, relaunch with a proxyfied browser to open webage. (e.g i2pd://meeh.i2p)
WriteRegStr HKCR "i2pd\DefaultIcon" "" $INSTDIR\i2pd.exe
WriteRegStr HKCR "i2pd\shell\open\command" "" '"$INSTDIR\i2pd.exe" "%1"'
SectionEnd
# Macro for selecting uninstaller sections
!macro SELECT_UNSECTION SECTION_NAME UNSECTION_ID
Push $R0
ReadRegStr $R0 HKCU "${REGKEY}\Components" "${SECTION_NAME}"
StrCmp $R0 1 0 next${UNSECTION_ID}
!insertmacro SelectSection "${UNSECTION_ID}"
GoTo done${UNSECTION_ID}
next${UNSECTION_ID}:
!insertmacro UnselectSection "${UNSECTION_ID}"
done${UNSECTION_ID}:
Pop $R0
!macroend
# Uninstaller sections
Section /o -un.Main UNSEC0000
Delete /REBOOTOK $INSTDIR\i2pd.exe
Delete /REBOOTOK $INSTDIR\LICENSE.txt
Delete /REBOOTOK $INSTDIR\Readme.txt
Delete /REBOOTOK $INSTDIR\install_service.bat
Delete /REBOOTOK $INSTDIR\uninstall_service.bat
RMDir /r /REBOOTOK $INSTDIR\src
DeleteRegValue HKCU "${REGKEY}\Components" Main
SectionEnd
Section -un.post UNSEC0001
DeleteRegKey HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)"
Delete /REBOOTOK "$SMPROGRAMS\$StartMenuGroup\Uninstall PurpleI2P.lnk"
Delete /REBOOTOK "$SMPROGRAMS\$StartMenuGroup\PurpleI2P.lnk"
Delete /REBOOTOK "$SMPROGRAMS\$StartMenuGroup\Install PurpleI2P Service.lnk"
Delete /REBOOTOK "$SMPROGRAMS\$StartMenuGroup\UnInstall PurpleI2P Service.lnk"
Delete /REBOOTOK "$SMSTARTUP\PurpleI2P.lnk"
Delete /REBOOTOK $INSTDIR\uninstall.exe
Delete /REBOOTOK $INSTDIR\debug.log
DeleteRegValue HKCU "${REGKEY}" StartMenuGroup
DeleteRegValue HKCU "${REGKEY}" Path
DeleteRegKey /IfEmpty HKCU "${REGKEY}\Components"
DeleteRegKey /IfEmpty HKCU "${REGKEY}"
DeleteRegKey HKCR "i2pd"
RmDir /REBOOTOK $SMPROGRAMS\$StartMenuGroup
RmDir /REBOOTOK $INSTDIR
Push $R0
StrCpy $R0 $StartMenuGroup 1
StrCmp $R0 ">" no_smgroup
no_smgroup:
Pop $R0
SectionEnd
; var hwndExecModeRadio
; var hwndRunServiceNowRadio
; Function mode_selection
; nsDialogs::Create 1018
; Pop $0
; ${NSD_CreateLabel} 0 10 75% 20u "How would you like PurpleI2P (i2pd) to run?"
; Pop $0
; ${NSD_CreateRadioButton} 20 60 80% 25u "Service Mode"
; Pop $hwndExecModeRadio
; ${NSD_AddStyle} $hwndExecModeRadio ${WS_GROUP}
; ${NSD_CreateRadioButton} 20 90 80% 25u "Command line Mode"
; Pop $0
; ${NSD_CreateButton} 20 150 -40 14u "Do it!"
; Pop $0
; ${NSD_OnClick} $0 perform_mode
; nsDialogs::Show
; FunctionEnd
; Function start_now_selection
; nsDialogs::Create 1018
; Pop $0
; ${NSD_CreateLabel} 0 10 75% 20u "Enable the service now?"
; Pop $0
; ${NSD_CreateRadioButton} 20 60 80% 25u "Yes"
; Pop $hwndRunServiceNowRadio
; ${NSD_AddStyle} $hwndRunServiceNowRadio ${WS_GROUP}
; ${NSD_CreateRadioButton} 20 90 80% 25u "No"
; Pop $0
; ${NSD_CreateButton} 20 150 -40 14u "Do it!"
; Pop $0
; ${NSD_OnClick} $0 perform_mode
; nsDialogs::Show
; FunctionEnd
; Function perform_mode
; ${NSD_GetState} $hwndExecModeRadio $0
; ${If} $0 = ${BST_CHECKED}
; Call service_mode
; ${EndIF}
; FunctionEnd
; Function start_now
; ${NSD_GetState} $hwndRunServiceNowRadio $0
; ${If} $0 = ${BST_CHECKED}
; Call start_now_selection
; ${EndIF}
; FunctionEnd
; Function service_mode
; Push "create"
; Push "PurpleI2P Service"
; Push "$INSTDIR\i2pd.exe;autostart=1;display=PurpleI2P"
; Call Service
; Pop $0 ; Actually more to write than !insertmacro, but much more fun :D
; Push "start"
; Push "PurpleI2P Service"
; Call Service
; Pop $0
; Call start_now
; !define MUI_FINISHPAGE_RUN_NOTCHECKED
; !define MUI_FINISHPAGE_RUN_TEXT "No need to run now since we already installed and launched it as a Windows service!"
; FunctionEnd
# Installer functions
Function .onInit
InitPluginsDir
!insertmacro MUI_LANGDLL_DISPLAY
FunctionEnd
# Uninstaller functions
Function un.onInit
ReadRegStr $INSTDIR HKCU "${REGKEY}" Path
!insertmacro MUI_STARTMENU_GETFOLDER Application $StartMenuGroup
!insertmacro SELECT_UNSECTION Main ${UNSEC0000}
!insertmacro MUI_UNGETLANGUAGE
FunctionEnd

View File

@ -1,73 +1,36 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
MAINICON ICON "mask.ico"
//MAINICON ICON "anke.ico"
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
MAINICON ICON "mask.ico"
#endif // English (United States) resources
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
#include "Resource.rc2"
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
#endif // not APSTUDIO_INVOKED

View File

@ -1,17 +1,8 @@
//
// Resource.RC2 - resources Microsoft Visual C++ does not edit directly
//
#ifdef APSTUDIO_INVOKED
#error this file is not editable by Microsoft Visual C++
#endif //APSTUDIO_INVOKED
#include "../version.h"
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
#include "../libi2pd/version.h"
VS_VERSION_INFO VERSIONINFO
FILEVERSION I2PD_VERSION_MAJOR,I2PD_VERSION_MINOR,I2PD_VERSION_MICRO,I2PD_VERSION_PATCH
@ -34,7 +25,7 @@ BEGIN
VALUE "FileDescription", "C++ I2P daemon"
VALUE "FileVersion", I2PD_VERSION
VALUE "InternalName", CODENAME
VALUE "LegalCopyright", "Copyright (C) 2013-2015, The PurpleI2P Project"
VALUE "LegalCopyright", "Copyright (C) 2013-2022, The PurpleI2P Project"
VALUE "OriginalFilename", "i2pd"
VALUE "ProductName", "Purple I2P"
VALUE "ProductVersion", I2P_VERSION

View File

@ -1,357 +1,493 @@
#include <string.h>
#include <windows.h>
#include <shellapi.h>
#include "../ClientContext.h"
#include "../Config.h"
#include "../NetDb.h"
#include "../RouterContext.h"
#include "../Transports.h"
#include "../Tunnel.h"
#include "../version.h"
#include "resource.h"
#include "Win32App.h"
#include <stdio.h>
#if defined(_MSC_VER) && _MSC_VER < 1900
#define snprintf _snprintf
#endif
#define ID_ABOUT 2000
#define ID_EXIT 2001
#define ID_CONSOLE 2002
#define ID_APP 2003
#define ID_GRACEFUL_SHUTDOWN 2004
#define ID_TRAY_ICON 2050
#define WM_TRAYICON (WM_USER + 1)
#define IDT_GRACEFUL_SHUTDOWN_TIMER 2100
#define FRAME_UPDATE_TIMER 2101
namespace i2p
{
namespace win32
{
static void ShowPopupMenu (HWND hWnd, POINT *curpos, int wDefaultItem)
{
HMENU hPopup = CreatePopupMenu();
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_CONSOLE, "Open &console");
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_APP, "Show app");
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_ABOUT, "&About...");
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_SEPARATOR, NULL, NULL);
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_GRACEFUL_SHUTDOWN, "&Graceful shutdown");
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_EXIT, "E&xit");
SetMenuDefaultItem (hPopup, ID_CONSOLE, FALSE);
SendMessage (hWnd, WM_INITMENUPOPUP, (WPARAM)hPopup, 0);
POINT p;
if (!curpos)
{
GetCursorPos (&p);
curpos = &p;
}
WORD cmd = TrackPopupMenu (hPopup, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_NONOTIFY, curpos->x, curpos->y, 0, hWnd, NULL);
SendMessage (hWnd, WM_COMMAND, cmd, 0);
DestroyMenu(hPopup);
}
static void AddTrayIcon (HWND hWnd)
{
NOTIFYICONDATA nid;
memset(&nid, 0, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = ID_TRAY_ICON;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO;
nid.uCallbackMessage = WM_TRAYICON;
nid.hIcon = LoadIcon (GetModuleHandle(NULL), MAKEINTRESOURCE (MAINICON));
strcpy (nid.szTip, "i2pd");
strcpy (nid.szInfo, "i2pd is running");
Shell_NotifyIcon(NIM_ADD, &nid );
}
static void RemoveTrayIcon (HWND hWnd)
{
NOTIFYICONDATA nid;
nid.hWnd = hWnd;
nid.uID = ID_TRAY_ICON;
Shell_NotifyIcon (NIM_DELETE, &nid);
}
static void ShowUptime (std::stringstream& s, int seconds)
{
int num;
if ((num = seconds / 86400) > 0) {
s << num << " days, ";
seconds -= num * 86400;
}
if ((num = seconds / 3600) > 0) {
s << num << " hours, ";
seconds -= num * 3600;
}
if ((num = seconds / 60) > 0) {
s << num << " min, ";
seconds -= num * 60;
}
s << seconds << " seconds\n";
}
static void ShowTransfered (std::stringstream& s, int transfer)
{
auto bytes = transfer & 0x03ff;
transfer >>= 10;
auto kbytes = transfer & 0x03ff;
transfer >>= 10;
auto mbytes = transfer & 0x03ff;
transfer >>= 10;
auto gbytes = transfer & 0x03ff;
if (gbytes)
s << gbytes << " GB, ";
if (mbytes)
s << mbytes << " MB, ";
if (kbytes)
s << kbytes << " KB, ";
s << bytes << " Bytes\n";
}
static void PrintMainWindowText (std::stringstream& s)
{
s << "Status: ";
switch (i2p::context.GetStatus())
{
case eRouterStatusOK: s << "OK"; break;
case eRouterStatusTesting: s << "Testing"; break;
case eRouterStatusFirewalled: s << "Firewalled"; break;
case eRouterStatusError:
{
switch (i2p::context.GetError())
{
case eRouterErrorClockSkew: s << "Clock skew"; break;
default: s << "Error";
}
break;
}
default: s << "Unknown";
}
s << "; ";
s << "Success Rate: " << i2p::tunnel::tunnels.GetTunnelCreationSuccessRate() << "%\n";
s << "Uptime: "; ShowUptime(s, i2p::context.GetUptime ());
s << "\n";
s << "Inbound: " << i2p::transport::transports.GetInBandwidth() / 1024 << " KiB/s; ";
s << "Outbound: " << i2p::transport::transports.GetOutBandwidth() / 1024 << " KiB/s\n";
s << "Recvieved: "; ShowTransfered (s, i2p::transport::transports.GetTotalReceivedBytes());
s << "Sent: "; ShowTransfered (s, i2p::transport::transports.GetTotalSentBytes());
s << "\n";
s << "Routers: " << i2p::data::netdb.GetNumRouters () << "; ";
s << "Floodfills: " << i2p::data::netdb.GetNumFloodfills () << "; ";
s << "LeaseSets: " << i2p::data::netdb.GetNumLeaseSets () << "\n";
s << "Tunnels: ";
s << "In: " << i2p::tunnel::tunnels.CountInboundTunnels() << "; ";
s << "Out: " << i2p::tunnel::tunnels.CountOutboundTunnels() << "; ";
s << "Transit: " << i2p::tunnel::tunnels.CountTransitTunnels() << "\n";
}
static LRESULT CALLBACK WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CREATE:
{
AddTrayIcon (hWnd);
break;
}
case WM_CLOSE:
{
RemoveTrayIcon (hWnd);
KillTimer (hWnd, FRAME_UPDATE_TIMER);
KillTimer (hWnd, IDT_GRACEFUL_SHUTDOWN_TIMER);
PostQuitMessage (0);
break;
}
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case ID_ABOUT:
{
std::stringstream text;
text << "Version: " << I2PD_VERSION << " " << CODENAME;
MessageBox( hWnd, TEXT(text.str ().c_str ()), TEXT("i2pd"), MB_ICONINFORMATION | MB_OK );
return 0;
}
case ID_EXIT:
{
PostMessage (hWnd, WM_CLOSE, 0, 0);
return 0;
}
case ID_GRACEFUL_SHUTDOWN:
{
i2p::context.SetAcceptsTunnels (false);
SetTimer (hWnd, IDT_GRACEFUL_SHUTDOWN_TIMER, 10*60*1000, nullptr); // 10 minutes
return 0;
}
case ID_CONSOLE:
{
char buf[30];
std::string httpAddr; i2p::config::GetOption("http.address", httpAddr);
uint16_t httpPort; i2p::config::GetOption("http.port", httpPort);
snprintf(buf, 30, "http://%s:%d", httpAddr.c_str(), httpPort);
ShellExecute(NULL, "open", buf, NULL, NULL, SW_SHOWNORMAL);
return 0;
}
case ID_APP:
{
ShowWindow(hWnd, SW_SHOW);
SetTimer(hWnd, FRAME_UPDATE_TIMER, 3000, NULL);
return 0;
}
}
break;
}
case WM_SYSCOMMAND:
{
switch (wParam)
{
case SC_MINIMIZE:
{
ShowWindow(hWnd, SW_HIDE);
KillTimer (hWnd, FRAME_UPDATE_TIMER);
return 0;
}
case SC_CLOSE:
{
std::string close; i2p::config::GetOption("close", close);
if (0 == close.compare("ask"))
switch(::MessageBox(hWnd, "Would you like to minimize instead of exiting?"
" You can add 'close' configuration option. Valid values are: ask, minimize, exit.",
"Minimize instead of exiting?", MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON1))
{
case IDYES: close = "minimize"; break;
case IDNO: close = "exit"; break;
default: return 0;
}
if (0 == close.compare("minimize"))
{
ShowWindow(hWnd, SW_HIDE);
KillTimer (hWnd, FRAME_UPDATE_TIMER);
return 0;
}
if (0 != close.compare("exit"))
{
::MessageBox(hWnd, close.c_str(), "Unknown close action in config", MB_OK | MB_ICONWARNING);
return 0;
}
}
}
}
case WM_TRAYICON:
{
switch (lParam)
{
case WM_LBUTTONUP:
case WM_RBUTTONUP:
{
SetForegroundWindow (hWnd);
ShowPopupMenu(hWnd, NULL, -1);
PostMessage (hWnd, WM_APP + 1, 0, 0);
break;
}
}
break;
}
case WM_TIMER:
{
if (wParam == IDT_GRACEFUL_SHUTDOWN_TIMER)
{
PostMessage (hWnd, WM_CLOSE, 0, 0); // exit
return 0;
}
if (wParam == FRAME_UPDATE_TIMER)
{
InvalidateRect(hWnd, NULL, TRUE);
}
break;
}
case WM_PAINT:
{
HDC hDC;
PAINTSTRUCT ps;
RECT rp;
HFONT hFont;
std::stringstream s; PrintMainWindowText (s);
hDC = BeginPaint (hWnd, &ps);
GetClientRect(hWnd, &rp);
SetTextColor(hDC, 0x00D43B69);
hFont = CreateFont(18,0,0,0,0,0,0,0,DEFAULT_CHARSET,0,0,0,0,TEXT("Times New Roman"));
SelectObject(hDC,hFont);
DrawText(hDC, TEXT(s.str().c_str()), s.str().length(), &rp, DT_CENTER|DT_VCENTER);
DeleteObject(hFont);
EndPaint(hWnd, &ps);
break;
}
}
return DefWindowProc( hWnd, uMsg, wParam, lParam);
}
bool StartWin32App ()
{
if (FindWindow (I2PD_WIN32_CLASSNAME, TEXT("i2pd")))
{
MessageBox(NULL, TEXT("I2Pd is running already"), TEXT("Warning"), MB_OK);
return false;
}
// register main window
auto hInst = GetModuleHandle(NULL);
WNDCLASSEX wclx;
memset (&wclx, 0, sizeof(wclx));
wclx.cbSize = sizeof(wclx);
wclx.style = 0;
wclx.lpfnWndProc = WndProc;
//wclx.cbClsExtra = 0;
//wclx.cbWndExtra = 0;
wclx.hInstance = hInst;
wclx.hIcon = LoadIcon (hInst, MAKEINTRESOURCE(MAINICON));
wclx.hCursor = LoadCursor (NULL, IDC_ARROW);
//wclx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
wclx.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wclx.lpszMenuName = NULL;
wclx.lpszClassName = I2PD_WIN32_CLASSNAME;
RegisterClassEx (&wclx);
// create new window
if (!CreateWindow(I2PD_WIN32_CLASSNAME, TEXT("i2pd"), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 100, 100, 350, 180, NULL, NULL, hInst, NULL))
{
MessageBox(NULL, "Failed to create main window", TEXT("Warning!"), MB_ICONERROR | MB_OK | MB_TOPMOST);
return false;
}
return true;
}
int RunWin32App ()
{
MSG msg;
while (GetMessage (&msg, NULL, 0, 0 ))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
return msg.wParam;
}
void StopWin32App ()
{
UnregisterClass (I2PD_WIN32_CLASSNAME, GetModuleHandle(NULL));
}
bool GracefulShutdown ()
{
HWND hWnd = FindWindow (I2PD_WIN32_CLASSNAME, TEXT("i2pd"));
if (hWnd)
PostMessage (hWnd, WM_COMMAND, MAKEWPARAM(ID_GRACEFUL_SHUTDOWN, 0), 0);
return hWnd;
}
}
}
/*
* Copyright (c) 2013-2022, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <shellapi.h>
#include "ClientContext.h"
#include "Config.h"
#include "NetDb.hpp"
#include "RouterContext.h"
#include "Transports.h"
#include "Tunnel.h"
#include "version.h"
#include "resource.h"
#include "Win32App.h"
#include "Win32NetState.h"
#define ID_ABOUT 2000
#define ID_EXIT 2001
#define ID_CONSOLE 2002
#define ID_APP 2003
#define ID_GRACEFUL_SHUTDOWN 2004
#define ID_STOP_GRACEFUL_SHUTDOWN 2005
#define ID_RELOAD 2006
#define ID_ACCEPT_TRANSIT 2007
#define ID_DECLINE_TRANSIT 2008
#define ID_DATADIR 2009
#define ID_TRAY_ICON 2050
#define WM_TRAYICON (WM_USER + 1)
#define IDT_GRACEFUL_SHUTDOWN_TIMER 2100
#define FRAME_UPDATE_TIMER 2101
#define IDT_GRACEFUL_TUNNELCHECK_TIMER 2102
namespace i2p
{
namespace win32
{
DWORD g_GracefulShutdownEndtime = 0;
static void ShowPopupMenu (HWND hWnd, POINT *curpos, int wDefaultItem)
{
HMENU hPopup = CreatePopupMenu();
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_CONSOLE, "Open &console");
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_DATADIR, "Open &datadir");
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_APP, "&Show app");
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_ABOUT, "&About...");
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_SEPARATOR, 0, NULL);
if(!i2p::context.AcceptsTunnels())
if(m_getIsGraceful)
if(m_getIsGraceful())
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING | MF_GRAYED, ID_ACCEPT_TRANSIT, "Accept &transit");
else
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_ACCEPT_TRANSIT, "Accept &transit");
else
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_DECLINE_TRANSIT, "Decline &transit");
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_RELOAD, "&Reload tunnels config");
if (!m_getIsGraceful)
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_GRACEFUL_SHUTDOWN, "&Graceful shutdown");
else
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_STOP_GRACEFUL_SHUTDOWN, "Stop &graceful shutdown");
InsertMenu (hPopup, -1, MF_BYPOSITION | MF_STRING, ID_EXIT, "E&xit");
SetMenuDefaultItem (hPopup, ID_CONSOLE, FALSE);
SendMessage (hWnd, WM_INITMENUPOPUP, (WPARAM)hPopup, 0);
POINT p;
if (!curpos)
{
GetCursorPos (&p);
curpos = &p;
}
WORD cmd = TrackPopupMenu (hPopup, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_NONOTIFY, curpos->x, curpos->y, 0, hWnd, NULL);
SendMessage (hWnd, WM_COMMAND, cmd, 0);
DestroyMenu(hPopup);
}
static void AddTrayIcon (HWND hWnd, bool notify = false)
{
NOTIFYICONDATA nid;
memset(&nid, 0, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = ID_TRAY_ICON;
nid.uFlags = notify ? NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO : NIF_ICON | NIF_MESSAGE | NIF_TIP;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO;
nid.uCallbackMessage = WM_TRAYICON;
nid.hIcon = LoadIcon (GetModuleHandle(NULL), MAKEINTRESOURCE (MAINICON));
strcpy (nid.szTip, "i2pd");
if (notify) strcpy (nid.szInfo, "i2pd is starting");
Shell_NotifyIcon(NIM_ADD, &nid );
}
static void RemoveTrayIcon (HWND hWnd)
{
NOTIFYICONDATA nid;
nid.hWnd = hWnd;
nid.uID = ID_TRAY_ICON;
Shell_NotifyIcon (NIM_DELETE, &nid);
}
static void ShowUptime (std::stringstream& s, int seconds)
{
int num;
if ((num = seconds / 86400) > 0) {
s << num << " days, ";
seconds -= num * 86400;
}
if ((num = seconds / 3600) > 0) {
s << num << " hours, ";
seconds -= num * 3600;
}
if ((num = seconds / 60) > 0) {
s << num << " min, ";
seconds -= num * 60;
}
s << seconds << " seconds\n";
}
template <typename size> static void ShowTransfered (std::stringstream& s, size transfer)
{
auto bytes = transfer & 0x03ff;
transfer >>= 10;
auto kbytes = transfer & 0x03ff;
transfer >>= 10;
auto mbytes = transfer & 0x03ff;
transfer >>= 10;
auto gbytes = transfer;
if (gbytes)
s << gbytes << " GB, ";
if (mbytes)
s << mbytes << " MB, ";
if (kbytes)
s << kbytes << " KB, ";
s << bytes << " Bytes\n";
}
static void ShowNetworkStatus (std::stringstream& s, RouterStatus status)
{
switch (status)
{
case eRouterStatusOK: s << "OK"; break;
case eRouterStatusTesting: s << "Test"; break;
case eRouterStatusFirewalled: s << "FW"; break;
case eRouterStatusUnknown: s << "Unk"; break;
case eRouterStatusProxy: s << "Proxy"; break;
case eRouterStatusMesh: s << "Mesh"; break;
case eRouterStatusError:
{
s << "Err";
switch (i2p::context.GetError ())
{
case eRouterErrorClockSkew:
s << " - Clock skew";
break;
case eRouterErrorOffline:
s << " - Offline";
break;
case eRouterErrorSymmetricNAT:
s << " - Symmetric NAT";
break;
default: ;
}
break;
}
default: s << "Unk";
}
}
static void PrintMainWindowText (std::stringstream& s)
{
s << "\n";
s << "Status: ";
ShowNetworkStatus (s, i2p::context.GetStatus ());
if (i2p::context.SupportsV6 ())
{
s << " / ";
ShowNetworkStatus (s, i2p::context.GetStatusV6 ());
}
s << "; ";
s << "Success Rate: " << i2p::tunnel::tunnels.GetTunnelCreationSuccessRate() << "%\n";
s << "Uptime: "; ShowUptime(s, i2p::context.GetUptime ());
if (g_GracefulShutdownEndtime != 0)
{
DWORD GracefulTimeLeft = (g_GracefulShutdownEndtime - GetTickCount()) / 1000;
s << "Graceful shutdown, time left: "; ShowUptime(s, GracefulTimeLeft);
}
else
s << "\n";
s << "Inbound: " << i2p::transport::transports.GetInBandwidth() / 1024 << " KiB/s; ";
s << "Outbound: " << i2p::transport::transports.GetOutBandwidth() / 1024 << " KiB/s\n";
s << "Received: "; ShowTransfered (s, i2p::transport::transports.GetTotalReceivedBytes());
s << "Sent: "; ShowTransfered (s, i2p::transport::transports.GetTotalSentBytes());
s << "\n";
s << "Routers: " << i2p::data::netdb.GetNumRouters () << "; ";
s << "Floodfills: " << i2p::data::netdb.GetNumFloodfills () << "; ";
s << "LeaseSets: " << i2p::data::netdb.GetNumLeaseSets () << "\n";
s << "Tunnels: ";
s << "In: " << i2p::tunnel::tunnels.CountInboundTunnels() << "; ";
s << "Out: " << i2p::tunnel::tunnels.CountOutboundTunnels() << "; ";
s << "Transit: " << i2p::tunnel::tunnels.CountTransitTunnels() << "\n";
s << "\n";
}
static LRESULT CALLBACK WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static UINT s_uTaskbarRestart;
switch (uMsg)
{
case WM_CREATE:
{
s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
AddTrayIcon (hWnd, true);
break;
}
case WM_CLOSE:
{
RemoveTrayIcon (hWnd);
KillTimer (hWnd, FRAME_UPDATE_TIMER);
KillTimer (hWnd, IDT_GRACEFUL_SHUTDOWN_TIMER);
KillTimer (hWnd, IDT_GRACEFUL_TUNNELCHECK_TIMER);
PostQuitMessage (0);
break;
}
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case ID_ABOUT:
{
std::stringstream text;
text << "Version: " << I2PD_VERSION << " " << CODENAME;
MessageBox( hWnd, TEXT(text.str ().c_str ()), TEXT("i2pd"), MB_ICONINFORMATION | MB_OK );
return 0;
}
case ID_EXIT:
{
PostMessage (hWnd, WM_CLOSE, 0, 0);
return 0;
}
case ID_ACCEPT_TRANSIT:
{
i2p::context.SetAcceptsTunnels (true);
std::stringstream text;
text << "I2Pd now accept transit tunnels";
MessageBox( hWnd, TEXT(text.str ().c_str ()), TEXT("i2pd"), MB_ICONINFORMATION | MB_OK );
return 0;
}
case ID_DECLINE_TRANSIT:
{
i2p::context.SetAcceptsTunnels (false);
std::stringstream text;
text << "I2Pd now decline new transit tunnels";
MessageBox( hWnd, TEXT(text.str ().c_str ()), TEXT("i2pd"), MB_ICONINFORMATION | MB_OK );
return 0;
}
case ID_GRACEFUL_SHUTDOWN:
{
i2p::context.SetAcceptsTunnels (false);
SetTimer (hWnd, IDT_GRACEFUL_SHUTDOWN_TIMER, 10*60*1000, nullptr); // 10 minutes
SetTimer (hWnd, IDT_GRACEFUL_TUNNELCHECK_TIMER, 1000, nullptr); // check tunnels every second
g_GracefulShutdownEndtime = GetTickCount() + 10*60*1000;
if (m_setIsGraceful) m_setIsGraceful(true);
return 0;
}
case ID_STOP_GRACEFUL_SHUTDOWN:
{
i2p::context.SetAcceptsTunnels (true);
KillTimer (hWnd, IDT_GRACEFUL_SHUTDOWN_TIMER);
KillTimer (hWnd, IDT_GRACEFUL_TUNNELCHECK_TIMER);
g_GracefulShutdownEndtime = 0;
if (m_setIsGraceful) m_setIsGraceful(false);
return 0;
}
case ID_RELOAD:
{
i2p::client::context.ReloadConfig();
std::stringstream text;
text << "I2Pd reloading configs...";
MessageBox( hWnd, TEXT(text.str ().c_str ()), TEXT("i2pd"), MB_ICONINFORMATION | MB_OK );
return 0;
}
case ID_CONSOLE:
{
char buf[30];
std::string httpAddr; i2p::config::GetOption("http.address", httpAddr);
uint16_t httpPort; i2p::config::GetOption("http.port", httpPort);
snprintf(buf, 30, "http://%s:%d", httpAddr.c_str(), httpPort);
ShellExecute(NULL, "open", buf, NULL, NULL, SW_SHOWNORMAL);
return 0;
}
case ID_APP:
{
ShowWindow(hWnd, SW_SHOW);
SetTimer(hWnd, FRAME_UPDATE_TIMER, 3000, NULL);
return 0;
}
case ID_DATADIR:
{
std::string datadir(i2p::fs::GetUTF8DataDir());
ShellExecute(NULL, "explore", datadir.c_str(), NULL, NULL, SW_SHOWNORMAL);
return 0;
}
}
break;
}
case WM_SYSCOMMAND:
{
switch (wParam)
{
case SC_MINIMIZE:
{
ShowWindow(hWnd, SW_HIDE);
KillTimer (hWnd, FRAME_UPDATE_TIMER);
return 0;
}
case SC_CLOSE:
{
std::string close; i2p::config::GetOption("close", close);
if (0 == close.compare("ask"))
switch(::MessageBox(hWnd, "Would you like to minimize instead of exiting?"
" You can add 'close' configuration option. Valid values are: ask, minimize, exit.",
"Minimize instead of exiting?", MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON1))
{
case IDYES: close = "minimize"; break;
case IDNO: close = "exit"; break;
default: return 0;
}
if (0 == close.compare("minimize"))
{
ShowWindow(hWnd, SW_HIDE);
KillTimer (hWnd, FRAME_UPDATE_TIMER);
return 0;
}
if (0 != close.compare("exit"))
{
::MessageBox(hWnd, close.c_str(), "Unknown close action in config", MB_OK | MB_ICONWARNING);
return 0;
}
}
}
}
case WM_TRAYICON:
{
switch (lParam)
{
case WM_LBUTTONUP:
case WM_RBUTTONUP:
{
SetForegroundWindow (hWnd);
ShowPopupMenu(hWnd, NULL, -1);
PostMessage (hWnd, WM_APP + 1, 0, 0);
break;
}
}
break;
}
case WM_TIMER:
{
switch(wParam)
{
case IDT_GRACEFUL_SHUTDOWN_TIMER:
{
g_GracefulShutdownEndtime = 0;
PostMessage (hWnd, WM_CLOSE, 0, 0); // exit
return 0;
}
case IDT_GRACEFUL_TUNNELCHECK_TIMER:
{
if (i2p::tunnel::tunnels.CountTransitTunnels() == 0)
PostMessage (hWnd, WM_CLOSE, 0, 0);
else
SetTimer (hWnd, IDT_GRACEFUL_TUNNELCHECK_TIMER, 1000, nullptr);
return 0;
}
case FRAME_UPDATE_TIMER:
{
InvalidateRect(hWnd, NULL, TRUE);
return 0;
}
}
break;
}
case WM_PAINT:
{
HDC hDC;
PAINTSTRUCT ps;
RECT rp;
HFONT hFont;
std::stringstream s; PrintMainWindowText (s);
hDC = BeginPaint (hWnd, &ps);
GetClientRect(hWnd, &rp);
SetTextColor(hDC, 0x00D43B69);
hFont = CreateFont(18,0,0,0,0,0,0,0,DEFAULT_CHARSET,0,0,0,0,TEXT("Times New Roman"));
SelectObject(hDC,hFont);
DrawText(hDC, TEXT(s.str().c_str()), s.str().length(), &rp, DT_CENTER|DT_VCENTER);
DeleteObject(hFont);
EndPaint(hWnd, &ps);
break;
}
default:
{
if (uMsg == s_uTaskbarRestart)
AddTrayIcon (hWnd, false);
break;
}
}
return DefWindowProc( hWnd, uMsg, wParam, lParam);
}
bool StartWin32App ()
{
if (FindWindow (I2PD_WIN32_CLASSNAME, TEXT("i2pd")))
{
MessageBox(NULL, TEXT("I2Pd is running already"), TEXT("Warning"), MB_OK);
return false;
}
// register main window
auto hInst = GetModuleHandle(NULL);
WNDCLASSEX wclx;
memset (&wclx, 0, sizeof(wclx));
wclx.cbSize = sizeof(wclx);
wclx.style = 0;
wclx.lpfnWndProc = WndProc;
//wclx.cbClsExtra = 0;
//wclx.cbWndExtra = 0;
wclx.hInstance = hInst;
wclx.hIcon = LoadIcon (hInst, MAKEINTRESOURCE(MAINICON));
wclx.hCursor = LoadCursor (NULL, IDC_ARROW);
//wclx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
wclx.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wclx.lpszMenuName = NULL;
wclx.lpszClassName = I2PD_WIN32_CLASSNAME;
RegisterClassEx (&wclx);
// create new window
if (!CreateWindow(I2PD_WIN32_CLASSNAME, TEXT("i2pd"), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 100, 100, 350, 210, NULL, NULL, hInst, NULL))
{
MessageBox(NULL, "Failed to create main window", TEXT("Warning!"), MB_ICONERROR | MB_OK | MB_TOPMOST);
return false;
}
SubscribeToEvents();
return true;
}
int RunWin32App ()
{
MSG msg;
while (GetMessage (&msg, NULL, 0, 0 ))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
return msg.wParam;
}
void StopWin32App ()
{
HWND hWnd = FindWindow (I2PD_WIN32_CLASSNAME, TEXT("i2pd"));
if (hWnd)
PostMessage (hWnd, WM_COMMAND, MAKEWPARAM(ID_EXIT, 0), 0);
// UnSubscribeFromEvents(); // TODO: understand why unsubscribing crashes app
UnregisterClass (I2PD_WIN32_CLASSNAME, GetModuleHandle(NULL));
}
bool GracefulShutdown ()
{
HWND hWnd = FindWindow (I2PD_WIN32_CLASSNAME, TEXT("i2pd"));
if (hWnd)
PostMessage (hWnd, WM_COMMAND, MAKEWPARAM(ID_GRACEFUL_SHUTDOWN, 0), 0);
return hWnd;
}
bool StopGracefulShutdown ()
{
HWND hWnd = FindWindow (I2PD_WIN32_CLASSNAME, TEXT("i2pd"));
if (hWnd)
PostMessage (hWnd, WM_COMMAND, MAKEWPARAM(ID_STOP_GRACEFUL_SHUTDOWN, 0), 0);
return hWnd;
}
}
}

View File

@ -1,16 +1,36 @@
#ifndef WIN32APP_H__
#define WIN32APP_H__
#define I2PD_WIN32_CLASSNAME "i2pd main window"
namespace i2p
{
namespace win32
{
bool StartWin32App ();
void StopWin32App ();
int RunWin32App ();
bool GracefulShutdown ();
}
}
#endif // WIN32APP_H__
/*
* Copyright (c) 2013-2022, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#ifndef WIN32APP_H__
#define WIN32APP_H__
#define I2PD_WIN32_CLASSNAME "i2pd main window"
namespace i2p
{
namespace win32
{
extern DWORD g_GracefulShutdownEndtime;
bool StartWin32App ();
void StopWin32App ();
int RunWin32App ();
bool GracefulShutdown ();
bool StopGracefulShutdown ();
inline typedef std::function<void (bool)> DaemonSetIsGraceful;
inline DaemonSetIsGraceful m_setIsGraceful;
inline void SetIsGraceful (const DaemonSetIsGraceful& f) { m_setIsGraceful = f; };
inline typedef std::function<bool ()> DaemonGetIsGraceful;
inline DaemonGetIsGraceful m_getIsGraceful;
inline void GetIsGraceful (const DaemonGetIsGraceful& f) { m_getIsGraceful = f; };
}
}
#endif // WIN32APP_H__

86
Win32/Win32NetState.cpp Normal file
View File

@ -0,0 +1,86 @@
/*
* Copyright (c) 2013-2020, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#if WINVER != 0x0501 // supported since Vista
#include "Win32NetState.h"
#include <windows.h>
#include "Log.h"
IUnknown *pUnknown = nullptr;
INetworkListManager *pNetworkListManager = nullptr;
IConnectionPointContainer *pCPContainer = nullptr;
IConnectionPoint *pConnectPoint = nullptr;
DWORD Cookie = 0;
void SubscribeToEvents()
{
LogPrint(eLogInfo, "NetState: Trying to subscribe to NetworkListManagerEvents");
CoInitialize(NULL);
HRESULT Result = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL, IID_IUnknown, (void **)&pUnknown);
if (SUCCEEDED(Result))
{
Result = pUnknown->QueryInterface(IID_INetworkListManager, (void **)&pNetworkListManager);
if (SUCCEEDED(Result))
{
VARIANT_BOOL IsConnect = VARIANT_FALSE;
Result = pNetworkListManager->IsConnectedToInternet(&IsConnect);
if (SUCCEEDED(Result)) {
i2p::transport::transports.SetOnline (true);
LogPrint(eLogInfo, "NetState: Current state: ", IsConnect == VARIANT_TRUE ? "connected" : "disconnected");
}
Result = pNetworkListManager->QueryInterface(IID_IConnectionPointContainer, (void **)&pCPContainer);
if (SUCCEEDED(Result))
{
Result = pCPContainer->FindConnectionPoint(IID_INetworkListManagerEvents, &pConnectPoint);
if(SUCCEEDED(Result))
{
CNetworkListManagerEvent *NetEvent = new CNetworkListManagerEvent;
Result = pConnectPoint->Advise((IUnknown *)NetEvent, &Cookie);
if (SUCCEEDED(Result))
LogPrint(eLogInfo, "NetState: Successfully subscribed to NetworkListManagerEvent messages");
else
LogPrint(eLogError, "NetState: Unable to subscribe to NetworkListManagerEvent messages");
} else
LogPrint(eLogError, "NetState: Unable to find interface connection point");
} else
LogPrint(eLogError, "NetState: Unable to query NetworkListManager interface");
} else
LogPrint(eLogError, "NetState: Unable to query global interface");
} else
LogPrint(eLogError, "NetState: Unable to create INetworkListManager interface");
}
void UnSubscribeFromEvents()
{
try
{
if (pConnectPoint) {
pConnectPoint->Unadvise(Cookie);
pConnectPoint->Release();
}
if (pCPContainer)
pCPContainer->Release();
if (pNetworkListManager)
pNetworkListManager->Release();
if (pUnknown)
pUnknown->Release();
CoUninitialize();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "NetState: Received exception: ", ex.what ());
}
}
#endif // WINVER

94
Win32/Win32NetState.h Normal file
View File

@ -0,0 +1,94 @@
/*
* Copyright (c) 2013-2020, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#ifndef WIN_32_NETSTATE_H__
#define WIN_32_NETSTATE_H__
#if WINVER != 0x0501 // supported since Vista
#include <netlistmgr.h>
#include <ocidl.h>
#include "Log.h"
#include "Transports.h"
class CNetworkListManagerEvent : public INetworkListManagerEvents
{
public:
CNetworkListManagerEvent() : m_ref(1) { }
~CNetworkListManagerEvent() { }
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject)
{
HRESULT Result = S_OK;
if (IsEqualIID(riid, IID_IUnknown)) {
*ppvObject = (IUnknown *)this;
} else if (IsEqualIID(riid ,IID_INetworkListManagerEvents)) {
*ppvObject = (INetworkListManagerEvents *)this;
} else {
Result = E_NOINTERFACE;
}
AddRef();
return Result;
}
ULONG STDMETHODCALLTYPE AddRef()
{
return (ULONG)InterlockedIncrement(&m_ref);
}
ULONG STDMETHODCALLTYPE Release()
{
LONG Result = InterlockedDecrement(&m_ref);
if (Result == 0)
delete this;
return (ULONG)Result;
}
virtual HRESULT STDMETHODCALLTYPE ConnectivityChanged(NLM_CONNECTIVITY newConnectivity)
{
if (newConnectivity == NLM_CONNECTIVITY_DISCONNECTED) {
i2p::transport::transports.SetOnline (false);
LogPrint(eLogInfo, "NetState: disconnected from network");
}
if (((int)newConnectivity & (int)NLM_CONNECTIVITY_IPV4_INTERNET) != 0) {
i2p::transport::transports.SetOnline (true);
LogPrint(eLogInfo, "NetState: connected to internet with IPv4 capability");
}
if (((int)newConnectivity & (int)NLM_CONNECTIVITY_IPV6_INTERNET) != 0) {
i2p::transport::transports.SetOnline (true);
LogPrint(eLogInfo, "NetState: connected to internet with IPv6 capability");
}
if (
(((int)newConnectivity & (int)NLM_CONNECTIVITY_IPV4_INTERNET) == 0) &&
(((int)newConnectivity & (int)NLM_CONNECTIVITY_IPV6_INTERNET) == 0)
) {
i2p::transport::transports.SetOnline (false);
LogPrint(eLogInfo, "NetState: connected without internet access");
}
return S_OK;
}
private:
LONG m_ref;
};
void SubscribeToEvents();
void UnSubscribeFromEvents();
#else // WINVER == 0x0501
void SubscribeToEvents() { }
void UnSubscribeFromEvents() { }
#endif // WINVER
#endif

View File

@ -1,21 +1,22 @@
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS // to use freopen
#endif
/*
* Copyright (c) 2013-2022, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include "Win32Service.h"
#include <assert.h>
#include <strsafe.h>
#include <windows.h>
#include "../Daemon.h"
#include "../Log.h"
#include "Log.h"
I2PService *I2PService::s_service = NULL;
BOOL I2PService::isService()
{
BOOL bIsService = FALSE;
HWINSTA hWinStation = GetProcessWindowStation();
if (hWinStation != NULL)
{
@ -31,28 +32,23 @@ BOOL I2PService::isService()
BOOL I2PService::Run(I2PService &service)
{
s_service = &service;
SERVICE_TABLE_ENTRY serviceTable[] =
{
{ service.m_name, ServiceMain },
{ NULL, NULL }
};
return StartServiceCtrlDispatcher(serviceTable);
}
void WINAPI I2PService::ServiceMain(DWORD dwArgc, PSTR *pszArgv)
{
assert(s_service != NULL);
s_service->m_statusHandle = RegisterServiceCtrlHandler(
s_service->m_name, ServiceCtrlHandler);
if (s_service->m_statusHandle == NULL)
{
throw GetLastError();
}
s_service->Start(dwArgc, pszArgv);
}
@ -61,27 +57,23 @@ void WINAPI I2PService::ServiceCtrlHandler(DWORD dwCtrl)
{
switch (dwCtrl)
{
case SERVICE_CONTROL_STOP: s_service->Stop(); break;
case SERVICE_CONTROL_PAUSE: s_service->Pause(); break;
case SERVICE_CONTROL_CONTINUE: s_service->Continue(); break;
case SERVICE_CONTROL_SHUTDOWN: s_service->Shutdown(); break;
case SERVICE_CONTROL_INTERROGATE: break;
default: break;
case SERVICE_CONTROL_STOP: s_service->Stop(); break;
case SERVICE_CONTROL_PAUSE: s_service->Pause(); break;
case SERVICE_CONTROL_CONTINUE: s_service->Continue(); break;
case SERVICE_CONTROL_SHUTDOWN: s_service->Shutdown(); break;
case SERVICE_CONTROL_INTERROGATE: break;
default: break;
}
}
I2PService::I2PService(PSTR pszServiceName,
BOOL fCanStop,
BOOL fCanShutdown,
BOOL fCanPauseContinue)
{
m_name = (pszServiceName == NULL) ? (PSTR)"" : pszServiceName;
m_statusHandle = NULL;
m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
m_status.dwCurrentState = SERVICE_START_PENDING;
DWORD dwControlsAccepted = 0;
@ -91,16 +83,14 @@ I2PService::I2PService(PSTR pszServiceName,
dwControlsAccepted |= SERVICE_ACCEPT_SHUTDOWN;
if (fCanPauseContinue)
dwControlsAccepted |= SERVICE_ACCEPT_PAUSE_CONTINUE;
m_status.dwControlsAccepted = dwControlsAccepted;
m_status.dwControlsAccepted = dwControlsAccepted;
m_status.dwWin32ExitCode = NO_ERROR;
m_status.dwServiceSpecificExitCode = 0;
m_status.dwCheckPoint = 0;
m_status.dwWaitHint = 0;
m_fStopping = FALSE;
// Create a manual-reset event that is not signaled at first to indicate
// Create a manual-reset event that is not signaled at first to indicate
// the stopped signal of the service.
m_hStoppedEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (m_hStoppedEvent == NULL)
@ -109,7 +99,6 @@ I2PService::I2PService(PSTR pszServiceName,
}
}
I2PService::~I2PService(void)
{
if (m_hStoppedEvent)
@ -119,92 +108,78 @@ I2PService::~I2PService(void)
}
}
void I2PService::Start(DWORD dwArgc, PSTR *pszArgv)
{
try
{
SetServiceStatus(SERVICE_START_PENDING);
OnStart(dwArgc, pszArgv);
SetServiceStatus(SERVICE_RUNNING);
}
catch (DWORD dwError)
{
LogPrint(eLogError, "Win32Service Start", dwError);
LogPrint(eLogError, "Win32Service: Start error: ", dwError);
SetServiceStatus(SERVICE_STOPPED, dwError);
}
catch (...)
{
LogPrint(eLogError, "Win32Service failed to start.", EVENTLOG_ERROR_TYPE);
LogPrint(eLogError, "Win32Service: failed to start: ", EVENTLOG_ERROR_TYPE);
SetServiceStatus(SERVICE_STOPPED);
}
}
void I2PService::OnStart(DWORD dwArgc, PSTR *pszArgv)
{
LogPrint(eLogInfo, "Win32Service in OnStart",
EVENTLOG_INFORMATION_TYPE);
Daemon.start();
//i2p::util::config::OptionParser(dwArgc, pszArgv);
//i2p::util::filesystem::ReadConfigFile(i2p::util::config::mapArgs, i2p::util::config::mapMultiArgs);
//i2p::context.OverrideNTCPAddress(i2p::util::config::GetCharArg("-host", "127.0.0.1"),
// i2p::util::config::GetArg("-port", 17070));
LogPrint(eLogInfo, "Win32Service: in OnStart (", EVENTLOG_INFORMATION_TYPE, ")");
if(m_daemonStart)
m_daemonStart();
else
{
LogPrint(eLogError, "Win32Service: failed to start: Unable to call callback");
SetServiceStatus(SERVICE_STOPPED);
}
_worker = new std::thread(std::bind(&I2PService::WorkerThread, this));
}
void I2PService::WorkerThread()
{
while (!m_fStopping)
{
::Sleep(1000); // Simulate some lengthy operations.
::Sleep(1000); // Simulate some lengthy operations.
}
// Signal the stopped event.
SetEvent(m_hStoppedEvent);
}
void I2PService::Stop()
{
DWORD dwOriginalState = m_status.dwCurrentState;
try
{
SetServiceStatus(SERVICE_STOP_PENDING);
OnStop();
SetServiceStatus(SERVICE_STOPPED);
}
catch (DWORD dwError)
{
LogPrint(eLogInfo, "Win32Service Stop", dwError);
LogPrint(eLogInfo, "Win32Service: Stop error: ", dwError);
SetServiceStatus(dwOriginalState);
}
catch (...)
{
LogPrint(eLogError, "Win32Service failed to stop.", EVENTLOG_ERROR_TYPE);
LogPrint(eLogError, "Win32Service: Failed to stop: ", EVENTLOG_ERROR_TYPE);
SetServiceStatus(dwOriginalState);
}
}
void I2PService::OnStop()
{
// Log a service stop message to the Application log.
LogPrint(eLogInfo, "Win32Service in OnStop", EVENTLOG_INFORMATION_TYPE);
Daemon.stop();
LogPrint(eLogInfo, "Win32Service: in OnStop (", EVENTLOG_INFORMATION_TYPE, ")");
if(m_daemonStop)
m_daemonStop();
else
LogPrint(eLogError, "Win32Service: failed to stop: Unable to call callback");
m_fStopping = TRUE;
if (WaitForSingleObject(m_hStoppedEvent, INFINITE) != WAIT_OBJECT_0)
@ -215,102 +190,83 @@ void I2PService::OnStop()
delete _worker;
}
void I2PService::Pause()
{
try
{
SetServiceStatus(SERVICE_PAUSE_PENDING);
OnPause();
SetServiceStatus(SERVICE_PAUSED);
}
catch (DWORD dwError)
{
LogPrint(eLogError, "Win32Service Pause", dwError);
LogPrint(eLogError, "Win32Service: Pause error: ", dwError);
SetServiceStatus(SERVICE_RUNNING);
}
catch (...)
{
LogPrint(eLogError, "Win32Service failed to pause.", EVENTLOG_ERROR_TYPE);
LogPrint(eLogError, "Win32Service: Failed to pause: ", EVENTLOG_ERROR_TYPE);
SetServiceStatus(SERVICE_RUNNING);
}
}
void I2PService::OnPause()
{
}
void I2PService::Continue()
{
try
{
SetServiceStatus(SERVICE_CONTINUE_PENDING);
OnContinue();
SetServiceStatus(SERVICE_RUNNING);
}
catch (DWORD dwError)
{
LogPrint(eLogError, "Win32Service Continue", dwError);
LogPrint(eLogError, "Win32Service: Continue error: ", dwError);
SetServiceStatus(SERVICE_PAUSED);
}
catch (...)
{
LogPrint(eLogError, "Win32Service failed to resume.", EVENTLOG_ERROR_TYPE);
LogPrint(eLogError, "Win32Service: Failed to resume: ", EVENTLOG_ERROR_TYPE);
SetServiceStatus(SERVICE_PAUSED);
}
}
void I2PService::OnContinue()
{
}
void I2PService::Shutdown()
{
try
{
OnShutdown();
SetServiceStatus(SERVICE_STOPPED);
}
catch (DWORD dwError)
{
LogPrint(eLogError, "Win32Service Shutdown", dwError);
LogPrint(eLogError, "Win32Service: Shutdown error: ", dwError);
}
catch (...)
{
LogPrint(eLogError, "Win32Service failed to shut down.", EVENTLOG_ERROR_TYPE);
LogPrint(eLogError, "Win32Service: Failed to shut down: ", EVENTLOG_ERROR_TYPE);
}
}
void I2PService::OnShutdown()
{
}
void I2PService::SetServiceStatus(DWORD dwCurrentState,
DWORD dwWin32ExitCode,
DWORD dwWaitHint)
{
static DWORD dwCheckPoint = 1;
m_status.dwCurrentState = dwCurrentState;
m_status.dwWin32ExitCode = dwWin32ExitCode;
m_status.dwWaitHint = dwWaitHint;
m_status.dwCheckPoint =
((dwCurrentState == SERVICE_RUNNING) ||
(dwCurrentState == SERVICE_STOPPED)) ?
@ -334,129 +290,3 @@ void FreeHandles(SC_HANDLE schSCManager, SC_HANDLE schService)
schService = NULL;
}
}
void InstallService(PSTR pszServiceName,
PSTR pszDisplayName,
DWORD dwStartType,
PSTR pszDependencies,
PSTR pszAccount,
PSTR pszPassword)
{
printf("Try to install Win32Service (%s).\n", pszServiceName);
char szPath[MAX_PATH];
SC_HANDLE schSCManager = NULL;
SC_HANDLE schService = NULL;
if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)) == 0)
{
printf("GetModuleFileName failed w/err 0x%08lx\n", GetLastError());
FreeHandles(schSCManager, schService);
return;
}
// Open the local default service control manager database
schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT |
SC_MANAGER_CREATE_SERVICE);
if (schSCManager == NULL)
{
printf("OpenSCManager failed w/err 0x%08lx\n", GetLastError());
FreeHandles(schSCManager, schService);
return;
}
// Install the service into SCM by calling CreateService
schService = CreateService(
schSCManager, // SCManager database
pszServiceName, // Name of service
pszDisplayName, // Name to display
SERVICE_QUERY_STATUS, // Desired access
SERVICE_WIN32_OWN_PROCESS, // Service type
dwStartType, // Service start type
SERVICE_ERROR_NORMAL, // Error control type
szPath, // Service's binary
NULL, // No load ordering group
NULL, // No tag identifier
pszDependencies, // Dependencies
pszAccount, // Service running account
pszPassword // Password of the account
);
if (schService == NULL)
{
printf("CreateService failed w/err 0x%08lx\n", GetLastError());
FreeHandles(schSCManager, schService);
return;
}
printf("Win32Service is installed as %s.\n", pszServiceName);
// Centralized cleanup for all allocated resources.
FreeHandles(schSCManager, schService);
}
void UninstallService(PSTR pszServiceName)
{
printf("Try to uninstall Win32Service (%s).\n", pszServiceName);
SC_HANDLE schSCManager = NULL;
SC_HANDLE schService = NULL;
SERVICE_STATUS ssSvcStatus = {};
// Open the local default service control manager database
schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if (schSCManager == NULL)
{
printf("OpenSCManager failed w/err 0x%08lx\n", GetLastError());
FreeHandles(schSCManager, schService);
return;
}
// Open the service with delete, stop, and query status permissions
schService = OpenService(schSCManager, pszServiceName, SERVICE_STOP |
SERVICE_QUERY_STATUS | DELETE);
if (schService == NULL)
{
printf("OpenService failed w/err 0x%08lx\n", GetLastError());
FreeHandles(schSCManager, schService);
return;
}
// Try to stop the service
if (ControlService(schService, SERVICE_CONTROL_STOP, &ssSvcStatus))
{
printf("Stopping %s.\n", pszServiceName);
Sleep(1000);
while (QueryServiceStatus(schService, &ssSvcStatus))
{
if (ssSvcStatus.dwCurrentState == SERVICE_STOP_PENDING)
{
printf(".");
Sleep(1000);
}
else break;
}
if (ssSvcStatus.dwCurrentState == SERVICE_STOPPED)
{
printf("\n%s is stopped.\n", pszServiceName);
}
else
{
printf("\n%s failed to stop.\n", pszServiceName);
}
}
// Now remove the service by calling DeleteService.
if (!DeleteService(schService))
{
printf("DeleteService failed w/err 0x%08lx\n", GetLastError());
FreeHandles(schSCManager, schService);
return;
}
printf("%s is removed.\n", pszServiceName);
// Centralized cleanup for all allocated resources.
FreeHandles(schSCManager, schService);
}

View File

@ -1,84 +1,76 @@
#ifndef WIN_32_SERVICE_H__
#define WIN_32_SERVICE_H__
/*
* Copyright (c) 2013-2022, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#ifndef WIN32SERVICE_H__
#define WIN32SERVICE_H__
#include <functional>
#include <thread>
#include <windows.h>
#ifdef _WIN32
// Internal name of the service
#define SERVICE_NAME "i2pService"
// Displayed name of the service
#define SERVICE_DISPLAY_NAME "i2p router service"
// Service start options.
#define SERVICE_START_TYPE SERVICE_DEMAND_START
// List of service dependencies - "dep1\0dep2\0\0"
#define SERVICE_DEPENDENCIES ""
// The name of the account under which the service should run
#define SERVICE_ACCOUNT "NT AUTHORITY\\LocalService"
// The password to the service account name
#define SERVICE_PASSWORD NULL
#endif
#define SERVICE_NAME "i2pdService"
class I2PService
{
public:
public:
I2PService(PSTR pszServiceName,
BOOL fCanStop = TRUE,
BOOL fCanShutdown = TRUE,
BOOL fCanPauseContinue = FALSE);
I2PService(PSTR pszServiceName,
BOOL fCanStop = TRUE,
BOOL fCanShutdown = TRUE,
BOOL fCanPauseContinue = FALSE);
virtual ~I2PService(void);
virtual ~I2PService(void);
static BOOL isService();
static BOOL Run(I2PService &service);
void Stop();
static BOOL isService();
static BOOL Run(I2PService &service);
void Stop();
protected:
typedef std::function<bool ()> DaemonStart;
void SetDaemonStart (const DaemonStart& f) { m_daemonStart = f; };
virtual void OnStart(DWORD dwArgc, PSTR *pszArgv);
virtual void OnStop();
virtual void OnPause();
virtual void OnContinue();
virtual void OnShutdown();
void SetServiceStatus(DWORD dwCurrentState,
DWORD dwWin32ExitCode = NO_ERROR,
DWORD dwWaitHint = 0);
typedef std::function<bool ()> DaemonStop;
void SetDaemonStop (const DaemonStop& f) { m_daemonStop = f; };
private:
static void WINAPI ServiceMain(DWORD dwArgc, LPSTR *lpszArgv);
static void WINAPI ServiceCtrlHandler(DWORD dwCtrl);
void WorkerThread();
void Start(DWORD dwArgc, PSTR *pszArgv);
void Pause();
void Continue();
void Shutdown();
static I2PService* s_service;
PSTR m_name;
SERVICE_STATUS m_status;
SERVICE_STATUS_HANDLE m_statusHandle;
protected:
BOOL m_fStopping;
HANDLE m_hStoppedEvent;
virtual void OnStart(DWORD dwArgc, PSTR *pszArgv);
virtual void OnStop();
virtual void OnPause();
virtual void OnContinue();
virtual void OnShutdown();
void SetServiceStatus(DWORD dwCurrentState,
DWORD dwWin32ExitCode = NO_ERROR,
DWORD dwWaitHint = 0);
std::thread* _worker;
private:
static void WINAPI ServiceMain(DWORD dwArgc, LPSTR *lpszArgv);
static void WINAPI ServiceCtrlHandler(DWORD dwCtrl);
void WorkerThread();
void Start(DWORD dwArgc, PSTR *pszArgv);
void Pause();
void Continue();
void Shutdown();
static I2PService* s_service;
PSTR m_name;
SERVICE_STATUS m_status;
SERVICE_STATUS_HANDLE m_statusHandle;
BOOL m_fStopping;
HANDLE m_hStoppedEvent;
std::thread* _worker;
private:
DaemonStart m_daemonStart;
DaemonStop m_daemonStop;
};
void InstallService(PSTR pszServiceName,
PSTR pszDisplayName,
DWORD dwStartType,
PSTR pszDependencies,
PSTR pszAccount,
PSTR pszPassword);
void UninstallService(PSTR pszServiceName);
#endif // WIN_32_SERVICE_H__
#endif // WIN32SERVICE_H__

View File

@ -1,30 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30723.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "i2pd", "i2pd.vcxproj", "{930568EC-31C9-406A-AD1C-9636DF5D8FAA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{930568EC-31C9-406A-AD1C-9636DF5D8FAA}.Debug|Win32.ActiveCfg = Debug|Win32
{930568EC-31C9-406A-AD1C-9636DF5D8FAA}.Debug|Win32.Build.0 = Debug|Win32
{930568EC-31C9-406A-AD1C-9636DF5D8FAA}.Debug|Win32.Deploy.0 = Debug|Win32
{930568EC-31C9-406A-AD1C-9636DF5D8FAA}.Debug|x64.ActiveCfg = Debug|x64
{930568EC-31C9-406A-AD1C-9636DF5D8FAA}.Debug|x64.Build.0 = Debug|x64
{930568EC-31C9-406A-AD1C-9636DF5D8FAA}.Release|Win32.ActiveCfg = Release|Win32
{930568EC-31C9-406A-AD1C-9636DF5D8FAA}.Release|Win32.Build.0 = Release|Win32
{930568EC-31C9-406A-AD1C-9636DF5D8FAA}.Release|Win32.Deploy.0 = Release|Win32
{930568EC-31C9-406A-AD1C-9636DF5D8FAA}.Release|x64.ActiveCfg = Release|x64
{930568EC-31C9-406A-AD1C-9636DF5D8FAA}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -1,292 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\AddressBook.cpp" />
<ClCompile Include="..\aes.cpp" />
<ClCompile Include="..\base64.cpp" />
<ClCompile Include="..\BOB.cpp" />
<ClCompile Include="..\CryptoConst.cpp" />
<ClCompile Include="..\Daemon.cpp" />
<ClCompile Include="..\DaemonWin32.cpp" />
<ClCompile Include="..\Garlic.cpp" />
<ClCompile Include="..\HTTPProxy.cpp" />
<ClCompile Include="..\HTTPServer.cpp" />
<ClCompile Include="..\I2NPProtocol.cpp" />
<ClCompile Include="..\i2p.cpp" />
<ClCompile Include="..\I2PEndian.cpp" />
<ClCompile Include="..\I2PService.cpp" />
<ClCompile Include="..\Identity.cpp" />
<ClCompile Include="..\LeaseSet.cpp" />
<ClCompile Include="..\Log.cpp" />
<ClCompile Include="..\NetDb.cpp" />
<ClCompile Include="..\NetDbRequests.cpp" />
<ClCompile Include="..\NTCPSession.cpp" />
<ClCompile Include="..\Profiling.cpp" />
<ClCompile Include="..\Reseed.cpp" />
<ClCompile Include="..\RouterContext.cpp" />
<ClCompile Include="..\RouterInfo.cpp" />
<ClCompile Include="..\Signature.cpp" />
<ClCompile Include="..\SAM.cpp" />
<ClCompile Include="..\SSU.cpp" />
<ClCompile Include="..\SSUData.cpp" />
<ClCompile Include="..\SSUSession.cpp" />
<ClCompile Include="..\Streaming.cpp" />
<ClCompile Include="..\Datagram.cpp" />
<ClCompile Include="..\Destination.cpp" />
<ClCompile Include="..\TransitTunnel.cpp" />
<ClCompile Include="..\Transports.cpp" />
<ClCompile Include="..\Tunnel.cpp" />
<ClCompile Include="..\TunnelEndpoint.cpp" />
<ClCompile Include="..\TunnelGateway.cpp" />
<ClCompile Include="..\TunnelPool.cpp" />
<ClCompile Include="..\UPnP.cpp" />
<ClCompile Include="..\util.cpp" />
<ClCompile Include="..\SOCKS.cpp" />
<ClCompile Include="..\I2PTunnel.cpp" />
<ClCompile Include="..\I2PControl.cpp" />
<ClCompile Include="..\ClientContext.cpp" />
<ClCompile Include="Win32Service.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\AddressBook.h" />
<ClInclude Include="..\base64.h" />
<ClInclude Include="..\BOB.h" />
<ClInclude Include="..\CryptoConst.h" />
<ClInclude Include="..\Daemon.h" />
<ClInclude Include="..\ElGamal.h" />
<ClInclude Include="..\Garlic.h" />
<ClInclude Include="..\HTTPProxy.h" />
<ClInclude Include="..\HTTPServer.h" />
<ClInclude Include="..\I2NPProtocol.h" />
<ClInclude Include="..\I2PEndian.h" />
<ClInclude Include="..\I2PService.h" />
<ClInclude Include="..\Identity.h" />
<ClInclude Include="..\LeaseSet.h" />
<ClInclude Include="..\LittleBigEndian.h" />
<ClInclude Include="..\Log.h" />
<ClInclude Include="..\NetDbRequests.h" />
<ClInclude Include="..\NetDb.h" />
<ClInclude Include="..\NTCPSession.h" />
<ClInclude Include="..\Queue.h" />
<ClInclude Include="..\Profiling.h" />
<ClInclude Include="..\Reseed.h" />
<ClInclude Include="..\RouterContext.h" />
<ClInclude Include="..\RouterInfo.h" />
<ClInclude Include="..\SAM.h" />
<ClInclude Include="..\SSU.h" />
<ClInclude Include="..\SSUData.h" />
<ClInclude Include="..\SSUSession.h" />
<ClInclude Include="..\Streaming.h" />
<ClInclude Include="..\Datagram.h" />
<ClInclude Include="..\Destination.h" />
<ClInclude Include="..\Timestamp.h" />
<ClInclude Include="..\TransitTunnel.h" />
<ClInclude Include="..\Transports.h" />
<ClInclude Include="..\Tunnel.h" />
<ClInclude Include="..\TunnelBase.h" />
<ClInclude Include="..\TunnelConfig.h" />
<ClInclude Include="..\TunnelEndpoint.h" />
<ClInclude Include="..\TunnelGateway.h" />
<ClInclude Include="..\TunnelPool.h" />
<ClInclude Include="..\UPnP.h" />
<ClInclude Include="..\util.h" />
<ClInclude Include="..\SOCKS.h" />
<ClInclude Include="..\I2PTunnel.h" />
<ClInclude Include="..\I2PControl.h" />
<ClInclude Include="..\version.h" />
<ClInclude Include="..\Signature.h" />
<ClInclude Include="..\ClientContext.h" />
<ClInclude Include="..\TransportSession.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="Win32Service.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Resource.rc" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{930568EC-31C9-406A-AD1C-9636DF5D8FAA}</ProjectGuid>
<RootNamespace>i2pd</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120_xp</PlatformToolset>
<CharacterSet>NotSet</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120_xp</PlatformToolset>
<CharacterSet>NotSet</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120_xp</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>NotSet</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120_xp</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>NotSet</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<IncludePath>./..;$(IncludePath);$(BOOST);$(CRYPTOPP);C:\build-lib\cryptopp;C:\build-lib\boost_1_57_0\</IncludePath>
<LibraryPath>$(BOOST)\stage\lib;C:\build-lib\cryptopp;C:\build-lib\boost_1_57_0\stage\lib;$(CRYPTOPP)\cryptopp\$(Platform)\Output\$(Configuration);$(LibraryPath)</LibraryPath>
<SourcePath>./..;$(VC_SourcePath);</SourcePath>
<TargetName>$(ProjectName)_d</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<IncludePath>./..;$(IncludePath);$(BOOST);$(CRYPTOPP)</IncludePath>
<LibraryPath>$(BOOST)\stage\lib;$(CRYPTOPP)\cryptopp\$(Platform)\Output\$(Configuration);$(LibraryPath)</LibraryPath>
<SourcePath>./..;$(VC_SourcePath);</SourcePath>
<TargetName>$(ProjectName)_d</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<IncludePath>./..;$(IncludePath);$(BOOST);C:\build-lib\boost_1_57_0\;C:\build-lib</IncludePath>
<LibraryPath>C:\build-lib\boost_1_57_0\stage\lib;C:\build-lib\cryptopp\$(Platform)\Output\$(Configuration);$(LibraryPath)</LibraryPath>
<SourcePath>./..;$(VC_SourcePath);</SourcePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<IncludePath>./..;$(IncludePath);$(BOOST);$(CRYPTOPP)</IncludePath>
<LibraryPath>$(BOOST)\stage\lib;$(CRYPTOPP)\cryptopp\$(Platform)\Output\$(Configuration);$(LibraryPath)</LibraryPath>
<SourcePath>./..;$(VC_SourcePath);</SourcePath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PreprocessorDefinitions>_MBCS;_WIN32_WINNT=0x0501;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>cryptlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
<UACExecutionLevel>AsInvoker</UACExecutionLevel>
<Version>0.2</Version>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PreprocessorDefinitions>_MBCS;_WIN32_WINNT=0x0502;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>cryptlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
<UACExecutionLevel>AsInvoker</UACExecutionLevel>
<Version>0.2</Version>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level2</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PreprocessorDefinitions>_WIN32_WINNT=0x0501;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>false</OptimizeReferences>
<AdditionalDependencies>cryptlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
<UACExecutionLevel>AsInvoker</UACExecutionLevel>
<Version>
</Version>
<SubSystem>Console</SubSystem>
<MinimumRequiredVersion>5.01</MinimumRequiredVersion>
<LinkErrorReporting>NoErrorReport</LinkErrorReporting>
</Link>
<Manifest>
<AssemblyIdentity>
</AssemblyIdentity>
<ComponentFileName>
</ComponentFileName>
</Manifest>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PreprocessorDefinitions>_WIN32_WINNT=0x0502;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>false</OptimizeReferences>
<AdditionalDependencies>cryptlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
<UACExecutionLevel>AsInvoker</UACExecutionLevel>
<Version>
</Version>
<SubSystem>Console</SubSystem>
<MinimumRequiredVersion>5.02</MinimumRequiredVersion>
<LinkErrorReporting>NoErrorReport</LinkErrorReporting>
</Link>
<Manifest>
<AssemblyIdentity>
</AssemblyIdentity>
<ComponentFileName>
</ComponentFileName>
</Manifest>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,302 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="Win32">
<UniqueIdentifier>{a880a08c-16b8-4243-82ea-6bfc63bb7dab}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\Identity.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\LeaseSet.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Log.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\NetDb.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\NTCPSession.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\RouterContext.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\RouterInfo.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Streaming.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\TransitTunnel.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Transports.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Tunnel.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\TunnelEndpoint.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\TunnelGateway.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\base64.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Garlic.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\HTTPServer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\I2NPProtocol.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\i2p.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\I2PEndian.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\SOCKS.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\SSU.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\util.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Reseed.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\UPnP.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\HTTPProxy.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\TunnelPool.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\AddressBook.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Win32Service.cpp">
<Filter>Win32</Filter>
</ClCompile>
<ClCompile Include="..\Daemon.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\DaemonWin32.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\SSUData.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\CryptoConst.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\aes.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\I2PTunnel.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\SAM.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\SSUSession.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Datagram.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\Destination.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\ClientContext.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\BOB.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\I2PControl.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\I2PService.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Identity.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\LeaseSet.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\LittleBigEndian.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Log.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\NetDb.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\NTCPSession.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Queue.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\RouterContext.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\RouterInfo.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Streaming.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Timestamp.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\TransitTunnel.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Transports.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Tunnel.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\TunnelBase.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\TunnelConfig.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\TunnelEndpoint.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\TunnelGateway.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\base64.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\CryptoConst.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\ElGamal.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Garlic.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\HTTPServer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\I2NPProtocol.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\I2PEndian.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\SOCKS.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\SSU.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\util.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Reseed.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\UPnP.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\HTTPProxy.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\TunnelPool.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\AddressBook.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Win32Service.h">
<Filter>Win32</Filter>
</ClInclude>
<ClInclude Include="..\Daemon.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\SSUData.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\I2PTunnel.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\version.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Signature.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\SAM.h">
<Filter>Source Files</Filter>
</ClInclude>
<ClInclude Include="..\SSUSession.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Datagram.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\Destination.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\ClientContext.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\TransportSession.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="resource.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\BOB.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\I2PControl.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\I2PService.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Resource.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
</Project>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

View File

@ -1,149 +0,0 @@
#define I2Pd_AppName "i2pd"
#define I2Pd_ver "0.2"
[Setup]
AppName={#I2Pd_AppName}
AppVersion={#I2Pd_ver}
DefaultDirName={pf}\I2Pd
DefaultGroupName=I2Pd
UninstallDisplayIcon={app}\I2Pd.exe
Compression=lzma2
SolidCompression=yes
OutputDir=.
LicenseFile=.\..\LICENSE
OutputBaseFilename=setup_{#I2Pd_AppName}_v{#I2Pd_ver}
ArchitecturesInstallIn64BitMode=x64
[Files]
Source: "x64\Release\i2pd.exe"; DestDir: "{app}"; DestName: "i2pd.exe"; Check: Is64BitInstallMode
Source: "Release\i2pd.exe"; DestDir: "{app}"; Check: not Is64BitInstallMode
Source: "..\README.md"; DestDir: "{app}"; DestName: "Readme.txt"; AfterInstall: ConvertLineEndings
[Icons]
Name: "{group}\I2Pd"; Filename: "{app}\i2pd.exe"
Name: "{group}\Readme"; Filename: "{app}\Readme.txt"
[Registry]
Root: HKCU; Subkey: "Environment"; ValueName: "Path"; ValueType: "string"; ValueData: "{app};{olddata}"; Check: NotOnPathAlready(); Flags: preservestringtype;
[Code]
var
DefaultTop,
DefaultLeft,
DefaultHeight,
DefaultBackTop,
DefaultNextTop,
DefaultCancelTop,
DefaultBevelTop,
DefaultOuterHeight: Integer;
const
LicenseHeight = 400;
LF = #10;
CR = #13;
CRLF = CR + LF;
procedure ConvertLineEndings();
var
FilePath : String;
FileContents : String;
begin
FilePath := ExpandConstant(CurrentFileName)
LoadStringFromFile(FilePath, FileContents);
StringChangeEx(FileContents, LF, CRLF, False);
SaveStringToFile(FilePath, FileContents, False);
end;
procedure InitializeWizard();
begin
DefaultTop := WizardForm.Top;
DefaultLeft := WizardForm.Left;
DefaultHeight := WizardForm.Height;
DefaultBackTop := WizardForm.BackButton.Top;
DefaultNextTop := WizardForm.NextButton.Top;
DefaultCancelTop := WizardForm.CancelButton.Top;
DefaultBevelTop := WizardForm.Bevel.Top;
DefaultOuterHeight := WizardForm.OuterNotebook.Height;
WizardForm.InnerPage.Height := WizardForm.InnerPage.Height + (LicenseHeight - DefaultHeight);
WizardForm.InnerNotebook.Height := WizardForm.InnerNotebook.Height + (LicenseHeight - DefaultHeight);
WizardForm.LicensePage.Height := WizardForm.LicensePage.Height + (LicenseHeight - DefaultHeight);
WizardForm.LicenseMemo.Height := WizardForm.LicenseMemo.Height + (LicenseHeight - DefaultHeight);
WizardForm.LicenseNotAcceptedRadio.Top := WizardForm.LicenseNotAcceptedRadio.Top + (LicenseHeight - DefaultHeight);
WizardForm.LicenseAcceptedRadio.Top := WizardForm.LicenseAcceptedRadio.Top + (LicenseHeight - DefaultHeight);
end;
procedure CurPageChanged(CurPageID: Integer);
begin
if CurPageID = wpLicense then
begin
WizardForm.Top := DefaultTop - (LicenseHeight - DefaultHeight) div 2;
WizardForm.Height := LicenseHeight;
WizardForm.OuterNotebook.Height := WizardForm.OuterNotebook.Height + (LicenseHeight - DefaultHeight);
WizardForm.CancelButton.Top := DefaultCancelTop + (LicenseHeight - DefaultHeight);
WizardForm.NextButton.Top := DefaultNextTop + (LicenseHeight - DefaultHeight);
WizardForm.BackButton.Top := DefaultBackTop + (LicenseHeight - DefaultHeight);
WizardForm.Bevel.Top := DefaultBevelTop + (LicenseHeight - DefaultHeight);
end
else
begin
WizardForm.Top := DefaultTop;
WizardForm.Left := DefaultLeft;
WizardForm.Height := DefaultHeight;
WizardForm.OuterNotebook.Height := DefaultOuterHeight;
WizardForm.CancelButton.Top := DefaultCancelTop;
WizardForm.NextButton.Top := DefaultNextTop;
WizardForm.BackButton.Top := DefaultBackTop;
WizardForm.Bevel.Top := DefaultBevelTop;
end;
end;
function NotOnPathAlready(): Boolean;
var
BinDir, Path: String;
begin
Log('Checking if i2pd dir is already in the %PATH%');
if RegQueryStringValue(HKEY_CURRENT_USER, 'Environment', 'Path', Path) then
begin // Successfully read the value
Log('HKCUEnvironmentPATH = ' + Path);
BinDir := ExpandConstant('{app}');
Log('Looking for i2pd dir in %PATH%: ' + BinDir + ' in ' + Path);
if Pos(LowerCase(BinDir), Lowercase(Path)) = 0 then
begin
Log('Did not find i2pd dir in %PATH% so I will add it');
Result := True;
end
else
begin
Log('Found i2pd dir in %PATH% so will not add it again');
Result := False;
end
end
else // The key probably doesn't exist
begin
Log('Could not access HKCUEnvironmentPATH so I assume that it is OK to add it');
Result := True;
end;
end;
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
var
BinDir, Path: String;
begin
if (CurUninstallStep = usPostUninstall)
and (RegQueryStringValue(HKEY_CURRENT_USER, 'Environment', 'PATH', Path)) then
begin
BinDir := ExpandConstant('{app}');
if Pos(LowerCase(BinDir) + ';', Lowercase(Path)) <> 0 then
begin
StringChange(Path, BinDir + ';', '');
RegWriteStringValue(HKEY_CURRENT_USER, 'Environment', 'PATH', Path);
end;
end;
end;

View File

@ -1 +0,0 @@
i2pd --service=install

View File

@ -1,41 +0,0 @@
#define I2Pd_AppName "i2pd"
#define I2Pd_ver "2.12.0"
#define I2Pd_Publisher "PurpleI2P"
[Setup]
AppName={#I2Pd_AppName}
AppVersion={#I2Pd_ver}
AppPublisher={#I2Pd_Publisher}
DefaultDirName={pf}\I2Pd
DefaultGroupName=I2Pd
UninstallDisplayIcon={app}\I2Pd.exe
OutputDir=.
LicenseFile=../LICENSE
OutputBaseFilename=setup_{#I2Pd_AppName}_v{#I2Pd_ver}
SetupIconFile=mask.ico
InternalCompressLevel=ultra64
Compression=lzma/ultra64
SolidCompression=true
ArchitecturesInstallIn64BitMode=x64
AppVerName={#I2Pd_AppName}
ExtraDiskSpaceRequired=15
AppID={{621A23E0-3CF4-4BD6-97BC-4835EA5206A2}
AppPublisherURL=http://i2pd.website/
AppSupportURL=https://github.com/PurpleI2P/i2pd/issues
AppUpdatesURL=https://github.com/PurpleI2P/i2pd/releases
[Files]
Source: ..\i2pd_x86.exe; DestDir: {app}; DestName: i2pd.exe; Flags: ignoreversion; Check: not IsWin64
Source: ..\i2pd_x64.exe; DestDir: {app}; DestName: i2pd.exe; Flags: ignoreversion; Check: IsWin64
Source: ..\README.md; DestDir: {app}; DestName: Readme.txt; Flags: onlyifdoesntexist
Source: ..\docs\i2pd.conf; DestDir: {userappdata}\i2pd; Flags: onlyifdoesntexist
Source: ..\docs\subscriptions.txt; DestDir: {userappdata}\i2pd; Flags: onlyifdoesntexist
Source: ..\docs\tunnels.conf; DestDir: {userappdata}\i2pd; Flags: onlyifdoesntexist
Source: ..\contrib\certificates\*; DestDir: {userappdata}\i2pd\certificates; Flags: onlyifdoesntexist recursesubdirs createallsubdirs
[Icons]
Name: {group}\I2Pd; Filename: {app}\i2pd.exe
Name: {group}\Readme; Filename: {app}\Readme.txt
[UninstallDelete]
Type: filesandordirs; Name: {app}

View File

@ -1,57 +0,0 @@
!verbose push
!verbose 3
!ifndef _MUI_EXTRAPAGES_NSH
!define _MUI_EXTRAPAGES_NSH
!ifmacrondef MUI_EXTRAPAGE_README & MUI_PAGE_README & MUI_UNPAGE_README & ReadmeLangStrings
!macro MUI_EXTRAPAGE_README UN ReadmeFile
!verbose push
!verbose 3
!define MUI_PAGE_HEADER_TEXT "$(${UN}ReadmeHeader)"
!define MUI_PAGE_HEADER_SUBTEXT "$(${UN}ReadmeSubHeader)"
!define MUI_LICENSEPAGE_TEXT_TOP "$(${UN}ReadmeTextTop)"
!define MUI_LICENSEPAGE_TEXT_BOTTOM "$(${UN}ReadmeTextBottom)"
!define MUI_LICENSEPAGE_BUTTON "$(^NextBtn)"
!insertmacro MUI_${UN}PAGE_LICENSE "${ReadmeFile}"
!verbose pop
!macroend
!define ReadmeRun "!insertmacro MUI_EXTRAPAGE_README"
!macro MUI_PAGE_README ReadmeFile
!verbose push
!verbose 3
${ReadmeRun} "" "${ReadmeFile}"
!verbose pop
!macroend
!macro MUI_UNPAGE_README ReadmeFile
!verbose push
!verbose 3
${ReadmeRun} "UN" "${ReadmeFile}"
!verbose pop
!macroend
!macro ReadmeLangStrings UN MUI_LANG ReadmeHeader ReadmeSubHeader ReadmeTextTop ReadmeTextBottom
!verbose push
!verbose 3
LangString ${UN}ReadmeHeader ${MUI_LANG} "${ReadmeHeader}"
LangString ${UN}ReadmeSubHeader ${MUI_LANG} "${ReadmeSubHeader}"
LangString ${UN}ReadmeTextTop ${MUI_LANG} "${ReadmeTextTop}"
LangString ${UN}ReadmeTextBottom ${MUI_LANG} "${ReadmeTextBottom}"
!verbose pop
!macroend
!define ReadmeLanguage `!insertmacro ReadmeLangStrings ""`
!define Un.ReadmeLanguage `!insertmacro ReadmeLangStrings "UN"`
!endif
!endif
!verbose pop

View File

@ -1,419 +0,0 @@
; NSIS SERVICE LIBRARY - servicelib.nsh
; Version 1.8.1 - Jun 21th, 2013
; Questions/Comments - dselkirk@hotmail.com
;
; Description:
; Provides an interface to window services
;
; Inputs:
; action - systemlib action ie. create, delete, start, stop, pause,
; continue, installed, running, status
; name - name of service to manipulate
; param - action parameters; usage: var1=value1;var2=value2;...etc.
; (don't forget to add a ';' after the last value!)
;
; Actions:
; create - creates a new windows service
; Parameters:
; path - path to service executable
; autostart - automatically start with system ie. 1|0
; interact - interact with the desktop ie. 1|0
; depend - service dependencies
; user - user that runs the service
; password - password of the above user
; display - display name in service's console
; description - Description of service
; starttype - start type (supersedes autostart)
; servicetype - service type (supersedes interact)
;
; delete - deletes a windows service
; start - start a stopped windows service
; stop - stops a running windows service
; pause - pauses a running windows service
; continue - continues a paused windows service
; installed - is the provided service installed
; Parameters:
; action - if true then invokes the specified action
; running - is the provided service running
; Parameters:
; action - if true then invokes the specified action
; status - check the status of the provided service
;
; Usage:
; Method 1:
; Push "action"
; Push "name"
; Push "param"
; Call Service
; Pop $0 ;response
;
; Method 2:
; !insertmacro SERVICE "action" "name" "param"
;
; History:
; 1.0 - 09/15/2003 - Initial release
; 1.1 - 09/16/2003 - Changed &l to i, thx brainsucker
; 1.2 - 02/29/2004 - Fixed documentation.
; 1.3 - 01/05/2006 - Fixed interactive flag and pop order (Kichik)
; 1.4 - 12/07/2006 - Added display and depend, fixed datatypes (Vitoco)
; 1.5 - 06/25/2008 - Added description of service.(DeSafe.com/liuqixing#gmail.com)
; 1.5.1 - 06/12/2009 - Added use of __UNINSTALL__
; 1.6 - 08/02/2010 - Fixed description implementation (Anders)
; 1.7 - 04/11/2010 - Added get running service process id (Nico)
; 1.8 - 24/03/2011 - Added starttype and servicetype (Sergius)
; 1.8.1 - 21/06/2013 - Added dynamic ASCII & Unicode support (Zinthose)
!ifndef SERVICELIB
!define SERVICELIB
!define SC_MANAGER_ALL_ACCESS 0x3F
!define SC_STATUS_PROCESS_INFO 0x0
!define SERVICE_ALL_ACCESS 0xF01FF
!define SERVICE_CONTROL_STOP 1
!define SERVICE_CONTROL_PAUSE 2
!define SERVICE_CONTROL_CONTINUE 3
!define SERVICE_STOPPED 0x1
!define SERVICE_START_PENDING 0x2
!define SERVICE_STOP_PENDING 0x3
!define SERVICE_RUNNING 0x4
!define SERVICE_CONTINUE_PENDING 0x5
!define SERVICE_PAUSE_PENDING 0x6
!define SERVICE_PAUSED 0x7
!define SERVICE_KERNEL_DRIVER 0x00000001
!define SERVICE_FILE_SYSTEM_DRIVER 0x00000002
!define SERVICE_WIN32_OWN_PROCESS 0x00000010
!define SERVICE_WIN32_SHARE_PROCESS 0x00000020
!define SERVICE_INTERACTIVE_PROCESS 0x00000100
!define SERVICE_BOOT_START 0x00000000
!define SERVICE_SYSTEM_START 0x00000001
!define SERVICE_AUTO_START 0x00000002
!define SERVICE_DEMAND_START 0x00000003
!define SERVICE_DISABLED 0x00000004
## Added by Zinthose for Native Unicode Support
!ifdef NSIS_UNICODE
!define APITAG "W"
!else
!define APITAG "A"
!endif
!macro SERVICE ACTION NAME PARAM
Push '${ACTION}'
Push '${NAME}'
Push '${PARAM}'
!ifdef __UNINSTALL__
Call un.Service
!else
Call Service
!endif
!macroend
!macro FUNC_GETPARAM
Push $0
Push $1
Push $2
Push $3
Push $4
Push $5
Push $6
Push $7
Exch 8
Pop $1 ;name
Exch 8
Pop $2 ;source
StrCpy $0 ""
StrLen $7 $2
StrCpy $3 0
lbl_loop:
IntCmp $3 $7 0 0 lbl_done
StrLen $4 "$1="
StrCpy $5 $2 $4 $3
StrCmp $5 "$1=" 0 lbl_next
IntOp $5 $3 + $4
StrCpy $3 $5
lbl_loop2:
IntCmp $3 $7 0 0 lbl_done
StrCpy $6 $2 1 $3
StrCmp $6 ";" 0 lbl_next2
IntOp $6 $3 - $5
StrCpy $0 $2 $6 $5
Goto lbl_done
lbl_next2:
IntOp $3 $3 + 1
Goto lbl_loop2
lbl_next:
IntOp $3 $3 + 1
Goto lbl_loop
lbl_done:
Pop $5
Pop $4
Pop $3
Pop $2
Pop $1
Exch 2
Pop $6
Pop $7
Exch $0
!macroend
!macro CALL_GETPARAM VAR NAME DEFAULT LABEL
Push $1
Push ${NAME}
Call ${UN}GETPARAM
Pop $6
StrCpy ${VAR} "${DEFAULT}"
StrCmp $6 "" "${LABEL}" 0
StrCpy ${VAR} $6
!macroend
!macro FUNC_SERVICE UN
Push $0
Push $1
Push $2
Push $3
Push $4
Push $5
Push $6
Push $7
Exch 8
Pop $1 ;param
Exch 8
Pop $2 ;name
Exch 8
Pop $3 ;action
;$0 return
;$4 OpenSCManager
;$5 OpenService
StrCpy $0 "false"
System::Call 'advapi32::OpenSCManager${APITAG}(n, n, i ${SC_MANAGER_ALL_ACCESS}) i.r4'
IntCmp $4 0 lbl_done
StrCmp $3 "create" lbl_create
System::Call 'advapi32::OpenService${APITAG}(i r4, t r2, i ${SERVICE_ALL_ACCESS}) i.r5'
IntCmp $5 0 lbl_done
lbl_select:
StrCmp $3 "delete" lbl_delete
StrCmp $3 "start" lbl_start
StrCmp $3 "stop" lbl_stop
StrCmp $3 "pause" lbl_pause
StrCmp $3 "continue" lbl_continue
StrCmp $3 "installed" lbl_installed
StrCmp $3 "running" lbl_running
StrCmp $3 "status" lbl_status
StrCmp $3 "processid" lbl_processid
Goto lbl_done
; create service
lbl_create:
Push $R1 ;depend
Push $R2 ;user
Push $R3 ;password
Push $R4 ;servicetype/interact
Push $R5 ;starttype/autostart
Push $R6 ;path
Push $R7 ;display
Push $R8 ;description
!insertmacro CALL_GETPARAM $R1 "depend" "n" "lbl_depend"
StrCpy $R1 't "$R1"'
lbl_depend:
StrCmp $R1 "n" 0 lbl_machine ;old name of depend param
!insertmacro CALL_GETPARAM $R1 "machine" "n" "lbl_machine"
StrCpy $R1 't "$R1"'
lbl_machine:
!insertmacro CALL_GETPARAM $R2 "user" "n" "lbl_user"
StrCpy $R2 't "$R2"'
lbl_user:
!insertmacro CALL_GETPARAM $R3 "password" "n" "lbl_password"
StrCpy $R3 't "$R3"'
lbl_password:
!insertmacro CALL_GETPARAM $R4 "interact" "${SERVICE_WIN32_OWN_PROCESS}" "lbl_interact"
StrCpy $6 ${SERVICE_WIN32_OWN_PROCESS}
IntCmp $R4 0 +2
IntOp $6 $6 | ${SERVICE_INTERACTIVE_PROCESS}
StrCpy $R4 $6
lbl_interact:
!insertmacro CALL_GETPARAM $R4 "servicetype" "$R4" "lbl_servicetype"
lbl_servicetype:
!insertmacro CALL_GETPARAM $R5 "autostart" "${SERVICE_DEMAND_START}" "lbl_autostart"
StrCpy $6 ${SERVICE_DEMAND_START}
IntCmp $R5 0 +2
StrCpy $6 ${SERVICE_AUTO_START}
StrCpy $R5 $6
lbl_autostart:
!insertmacro CALL_GETPARAM $R5 "starttype" "$R5" "lbl_starttype"
lbl_starttype:
!insertmacro CALL_GETPARAM $R6 "path" "n" "lbl_path"
lbl_path:
!insertmacro CALL_GETPARAM $R7 "display" "$2" "lbl_display"
lbl_display:
!insertmacro CALL_GETPARAM $R8 "description" "$2" "lbl_description"
lbl_description:
System::Call 'advapi32::CreateService${APITAG}(i r4, t r2, t R7, i ${SERVICE_ALL_ACCESS}, \
i R4, i R5, i 0, t R6, n, n, $R1, $R2, $R3) i.r6'
; write description of service (SERVICE_CONFIG_DESCRIPTION)
System::Call 'advapi32::ChangeServiceConfig2${APITAG}(ir6,i1,*t "$R8")i.R7'
strcmp $R7 "error" 0 lbl_descriptioncomplete
WriteRegStr HKLM "SYSTEM\CurrentControlSet\Services\$2" "Description" $R8
lbl_descriptioncomplete:
Pop $R8
Pop $R7
Pop $R6
Pop $R5
Pop $R4
Pop $R3
Pop $R2
Pop $R1
StrCmp $6 0 lbl_done lbl_good
; delete service
lbl_delete:
System::Call 'advapi32::DeleteService(i r5) i.r6'
StrCmp $6 0 lbl_done lbl_good
; start service
lbl_start:
System::Call 'advapi32::StartService${APITAG}(i r5, i 0, i 0) i.r6'
StrCmp $6 0 lbl_done lbl_good
; stop service
lbl_stop:
Push $R1
System::Call '*(i,i,i,i,i,i,i) i.R1'
System::Call 'advapi32::ControlService(i r5, i ${SERVICE_CONTROL_STOP}, i $R1) i'
System::Free $R1
Pop $R1
StrCmp $6 0 lbl_done lbl_good
; pause service
lbl_pause:
Push $R1
System::Call '*(i,i,i,i,i,i,i) i.R1'
System::Call 'advapi32::ControlService(i r5, i ${SERVICE_CONTROL_PAUSE}, i $R1) i'
System::Free $R1
Pop $R1
StrCmp $6 0 lbl_done lbl_good
; continue service
lbl_continue:
Push $R1
System::Call '*(i,i,i,i,i,i,i) i.R1'
System::Call 'advapi32::ControlService(i r5, i ${SERVICE_CONTROL_CONTINUE}, i $R1) i'
System::Free $R1
Pop $R1
StrCmp $6 0 lbl_done lbl_good
; is installed
lbl_installed:
!insertmacro CALL_GETPARAM $7 "action" "" "lbl_good"
StrCpy $3 $7
Goto lbl_select
; is service running
lbl_running:
Push $R1
System::Call '*(i,i,i,i,i,i,i) i.R1'
System::Call 'advapi32::QueryServiceStatus(i r5, i $R1) i'
System::Call '*$R1(i, i.r6)'
System::Free $R1
Pop $R1
IntFmt $6 "0x%X" $6
StrCmp $6 ${SERVICE_RUNNING} 0 lbl_done
!insertmacro CALL_GETPARAM $7 "action" "" "lbl_good"
StrCpy $3 $7
Goto lbl_select
lbl_status:
Push $R1
System::Call '*(i,i,i,i,i,i,i) i.R1'
System::Call 'advapi32::QueryServiceStatus(i r5, i $R1) i'
System::Call '*$R1(i, i .r6)'
System::Free $R1
Pop $R1
IntFmt $6 "0x%X" $6
StrCpy $0 "running"
IntCmp $6 ${SERVICE_RUNNING} lbl_done
StrCpy $0 "stopped"
IntCmp $6 ${SERVICE_STOPPED} lbl_done
StrCpy $0 "start_pending"
IntCmp $6 ${SERVICE_START_PENDING} lbl_done
StrCpy $0 "stop_pending"
IntCmp $6 ${SERVICE_STOP_PENDING} lbl_done
StrCpy $0 "running"
IntCmp $6 ${SERVICE_RUNNING} lbl_done
StrCpy $0 "continue_pending"
IntCmp $6 ${SERVICE_CONTINUE_PENDING} lbl_done
StrCpy $0 "pause_pending"
IntCmp $6 ${SERVICE_PAUSE_PENDING} lbl_done
StrCpy $0 "paused"
IntCmp $6 ${SERVICE_PAUSED} lbl_done
StrCpy $0 "unknown"
Goto lbl_done
lbl_processid:
Push $R1
Push $R2
System::Call '*(i,i,i,i,i,i,i,i,i) i.R1'
System::Call '*(i 0) i.R2'
System::Call "advapi32::QueryServiceStatusEx(i r5, i ${SC_STATUS_PROCESS_INFO}, i $R1, i 36, i $R2) i"
System::Call "*$R1(i,i,i,i,i,i,i, i .r0)"
System::Free $R2
System::Free $R1
Pop $R2
Pop $R1
Goto lbl_done
lbl_good:
StrCpy $0 "true"
lbl_done:
IntCmp $5 0 +2
System::Call 'advapi32::CloseServiceHandle(i r5) n'
IntCmp $4 0 +2
System::Call 'advapi32::CloseServiceHandle(i r4) n'
Pop $4
Pop $3
Pop $2
Pop $1
Exch 3
Pop $5
Pop $7
Pop $6
Exch $0
!macroend
Function Service
!insertmacro FUNC_SERVICE ""
FunctionEnd
Function un.Service
!insertmacro FUNC_SERVICE "un."
FunctionEnd
Function GetParam
!insertmacro FUNC_GETPARAM
FunctionEnd
Function un.GetParam
!insertmacro FUNC_GETPARAM
FunctionEnd
!undef APITAG
!endif

View File

@ -1,16 +1,11 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Resource.rc
//
#define MAINICON 101
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
//{{NO_DEPENDENCIES}}
#define MAINICON 101
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

View File

@ -1 +0,0 @@
i2pd --service=remove

7
android/.gitignore vendored
View File

@ -1,7 +0,0 @@
gen
tests
.idea
local.properties
build.sh
bin
log*

View File

@ -1,25 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.purplei2p.i2pd"
android:versionCode="1"
android:versionName="2.12.0">
<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="24"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application android:label="@string/app_name" android:allowBackup="true" android:icon="@drawable/icon">
<receiver android:name=".NetworkStateChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
<activity android:name=".I2PD"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".ForegroundService"/>
</application>
</manifest>

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