### start_link Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_dc_pool.md Example of starting a datacenter connection pool. ```erlang {ok, PoolPid} = mtp_dc_pool:start_link(1),\n% Pool for DC 1 is now ready ``` -------------------------------- ### Install and start front server Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Commands to install and start the front server after the back server is up. ```bash make ROLE=front && sudo make install && systemctl start mtproto-proxy ``` -------------------------------- ### start_link() Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_config.md Example of starting the mtp_config worker process. ```erlang start_link() -> {ok, Pid} ``` ```erlang {ok, Pid} = mtp_config:start_link(), % Pid is the worker process ``` -------------------------------- ### Starting a Listener Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/README.md Example of starting a new MTProto proxy listener with a given configuration. ```erlang Config = #{ name => handler_new, port => 2443, secret => <<"aaaaaabbbbbbccccccddddddeeeeeeee">>, tag => <<"11111122222233333344444455555555"> }, {ok, _Pid} = mtproto_proxy_app:start_proxy(Config). ``` -------------------------------- ### Split-Mode Configuration Setup Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_config.md Example sys.config settings for back and front nodes in a split-mode setup. ```erlang %% Back node sys.config {mtproto_proxy, [{node_role, back}]}. %% Front node sys.config {mtproto_proxy, [{node_role, front}, {back_node, 'back@host.example.com'}]}. ``` -------------------------------- ### ports example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Example configuration for the 'ports' setting. ```erlang {ports, [ #{name => mtp_handler_1, port => 443, secret => <<"d0d6e111bada5511fcce9584deadbeef">>, tag => <<"dcbe8f1493fa4cd9ab300891c0b5b326">>}, #{name => mtp_handler_2, port => 2443, secret => <<"aaaaaabbbbbbccccccddddddeeeeeeee">>, tag => <<"11111122222233333344444455555555">>} ]} ``` -------------------------------- ### start/2 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtproto_proxy_app.md Example of how the start/2 function is called automatically. ```erlang %% Called automatically when application:start(mtproto_proxy) is invoked %% or when the release starts the application application:start(mtproto_proxy). ``` -------------------------------- ### Start Back Server Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Commands to build, install, and start the MTProto proxy service on the back server. ```bash # On back server: make ROLE=back && sudo make install && systemctl start mtproto-proxy ``` -------------------------------- ### Policy Rule Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md An example of how to define connection policy rules. ```erlang {policy, [ {max_connections, [port_name], 10000}, {max_connections, [client_ipv4], 100}, {not_in_table, client_ipv4, banned_ips} ]} ``` -------------------------------- ### domain_fronting configuration examples Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Examples demonstrating different modes for domain fronting. ```erlang {domain_fronting, off} ``` ```erlang {domain_fronting, sni} ``` ```erlang {domain_fronting, "cdn.example.com:443"} ``` -------------------------------- ### get Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_dc_pool.md Example of getting a downstream connection from the pool. ```erlang Opts = #{addr => {{192, 0, 2, 1}, 5000}},\ncase mtp_dc_pool:get(PoolPid, UpstreamPid, Opts) of\n DownPid when is_pid(DownPid) ->\n % Now UpstreamPid -> DownPid mapping is set up\n ok;\n {error, empty} ->\n error(no_downstreams)\nend. ``` -------------------------------- ### running_ports/0 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtproto_proxy_app.md Example of iterating through running proxy ports. ```erlang Ports = mtproto_proxy_app:running_ports(), lists:foreach(fun(#{name := N, port := P, secret := S}) -> io:format("~w: port ~w, secret ~s~n", [N, P, S]) end, Ports). ``` -------------------------------- ### update() Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_config.md Example of triggering an asynchronous configuration update. ```erlang -spec update() -> ok. ``` ```erlang mtp_config:update(), % Configuration will be refreshed in the background ``` -------------------------------- ### config_change/3 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtproto_proxy_app.md Example of triggering a configuration change. ```erlang rpc:call(Node, application, set_env, [mtproto_proxy, max_connections, 50000]), % Triggers config_change/3 on all running nodes ``` -------------------------------- ### status() Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_config.md Example of retrieving status information for all configured datacenters. ```erlang -spec status() -> [mtp_dc_pool:status()]. ``` ```erlang Status = mtp_config:status(), lists:foreach(fun(#{dc_id := DC, n_downstreams := N}) -> io:format("DC ~w has ~w connections~n", [DC, N]) end, Status). ``` -------------------------------- ### High-Performance Production Configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md An example configuration for a high-performance production MTProto Proxy setup. ```erlang {mtproto_proxy, [ {listen_ip, "0.0.0.0"}, {ports, [ #{name => handler_443, port => 443, secret => <<"d0d6e111bada5511fcce9584deadbeef">>, tag => <<"dcbe8f1493fa4cd9ab300891c0b5b326">>} ]}, {num_acceptors, 100}, {max_connections, 50000}, {allowed_protocols, [mtp_secure, mtp_fake_tls]}, {init_timeout_sec, 60}, {hibernate_timeout_sec, 60}, {ready_timeout_sec, 1200}, {replay_check_session_storage, on}, {upstream_send_timeout_ms, 15000}, {downstream_socket_buffer_size, 512000}, {init_dc_connections, 4}, {clients_per_dc_connection, 300}, {reset_close_socket, handshake_error}, {domain_fronting, sni}, {external_ip, "203.0.113.42"}, {metric_backend, prometheus_backend} ]} ``` -------------------------------- ### Build and install Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Building the proxy and installing it to the system. ```bash make && sudo make install ``` -------------------------------- ### Configuration File Format Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_config.md Example of the configuration file format returned by the getProxyConfig API. ```text default 2; proxy_for 1 149.154.175.50:8888; proxy_for 2 149.154.162.39:80; proxy_for -1 149.154.175.50:8888; ``` -------------------------------- ### from_client_hello Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_fake_tls.md Example of processing a fake TLS ClientHello from the client and generating a server reply. ```erlang -spec from_client_hello(binary(), binary()) -> {ok, iodata(), meta(), codec()}. | | Parameter | Type | Description | |-----------|------|-------------| | ClientHello | binary() | Raw ClientHello packet | | Secret | binary() | 16-byte proxy secret | **Return:** - `{ok, Response, Metadata, Codec}` where: - `Response` — ServerHello + ChangeCipherSpec + ApplicationData (iodata) - `Metadata` — Extracted session data - `Codec` — Initialized codec for subsequent encode/decode **Throws:** - `{protocol_error, tls_invalid_digest, ...}` if ClientHello digest mismatch - `{protocol_error, tls_invalid_sni, ...}` if SNI parsing fails **Behavior:** - Validates ClientHello structure - Extracts session ID and digest - Parses SNI domain from extensions (if present) - XORs client and server digests to verify timestamp - Returns ApplicationData with extracted secrets **Example:** ```erlang case mtp_fake_tls:from_client_hello(ClientHelloData, ProxySecret) of {ok, ServerReply, Meta, TlsCodec} -> % Send ServerReply to client, store TlsCodec gen_tcp:send(Socket, ServerReply), handle_tunnel(Socket, TlsCodec, Meta); {error, Reason} -> % Protocol error - close connection error(Reason) end. ``` ``` -------------------------------- ### Minimal Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/README.md A minimal configuration example for the MTProto proxy. ```erlang {mtproto_proxy, [ {ports, [#{ name => handler_1, port => 443, secret => <<"d0d6e111bada5511fcce9584deadbeef">>, tag => <<"dcbe8f1493fa4cd9ab300891c0b5b326">> }]} ]} ``` -------------------------------- ### mtp_listeners/0 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtproto_proxy_app.md Example of retrieving MTProto proxy listeners. ```erlang Listeners = mtproto_proxy_app:mtp_listeners(), % [{handler_1, #{protocol => mtp_handler, ...}}, ...] ``` -------------------------------- ### status Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_dc_pool.md Example of retrieving and inspecting the pool status. ```erlang #{n_downstreams := 2, n_upstreams := 450, min := 220, max := 230, dc_id := 1} = mtp_dc_pool:status(PoolPid). ``` -------------------------------- ### info/2 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_codec.md Example of retrieving the current module and state for a specific layer. ```erlang {Module, State} = mtp_codec:info(crypto, Codec), % {mtp_aes_cbc, #crypto_state{...}} ``` -------------------------------- ### Getting Proxy URLs Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/README.md Example of generating proxy URLs for a given configuration. ```erlang Urls = mtproto_proxy_app:build_urls( "example.com", 443, <<"d0d6e111bada5511fcce9584deadbeef">>, [mtp_secure, mtp_fake_tls]), lists:foreach(fun(Url) -> io:format("~s~n", [Url]) end, Urls). ``` -------------------------------- ### Censorship-Resistant Configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md An example configuration for a censorship-resistant MTProto Proxy setup. ```erlang {mtproto_proxy, [ {allowed_protocols, [mtp_fake_tls]}, {replay_check_server_error_filter, first}, {replay_check_session_storage, on}, {per_sni_secrets, on}, {per_sni_secret_salt, <<"your-unique-salt">>}, {domain_fronting, sni}, {reset_close_socket, handshake_error} ]} ``` -------------------------------- ### protocol_flag Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_rpc.md Example of getting the MTProto protocol flag for a packet layer. ```erlang Flag = mtp_rpc:protocol_flag(mtp_secure), % 1073741824 (0x40000000) ``` -------------------------------- ### Installer with Arguments Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md This command installs and configures the proxy with specified arguments. ```bash curl -L -o mtp_install.sh https://git.io/fj5ru && bash mtp_install.sh -p 443 -s d0d6e111bada5511fcce9584deadbeef -t dcbe8f1493fa4cd9ab300891c0b5b326 -a dd -a tls -d s3.amazonaws.com ``` -------------------------------- ### Configuration Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_codec.md Example of MTProto Proxy configuration, specifically enabling CRC32 validation. ```erlang {mtproto_proxy, [ {mtp_full_check_crc32, true} % Validate CRC32 in mtp_full ]} ``` -------------------------------- ### Example configuration for prod-sys.config Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md An example snippet from the `prod-sys.config` file showing how to configure ports, secrets, and tags. ```erlang {mtproto_proxy, %% see src/mtproto_proxy.app.src for examples. [ #{name => mtp_handler_1, listen_ip => "0.0.0.0", port => 1443, secret => <<"d0d6e111bada5511fcce9584deadbeef">>, tag => <<"dcbe8f1493fa4cd9ab300891c0b5b326">>} ]}, {kernel, [{logger_level, info}, {logger, [{handler, default, logger_std_h, #{config => #{file => "/var/log/mtproto-proxy/application.log"}}} ]}]}, <...> ``` -------------------------------- ### Example for set_config Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_down_conn.md Example of updating the downstream socket buffer size. ```erlang {ok, OldSize} = mtp_down_conn:set_config(DownPid, downstream_socket_buffer_size, 512000). ``` -------------------------------- ### get_netloc Example Usage Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_config.md Example of how to use the get_netloc function and the expected output format. ```erlang {ok, {IpAddr, Port}} = mtp_config:get_netloc(1), % {ok, {{149, 154, 175, 50}, 8888}} ``` -------------------------------- ### replace/4 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_codec.md Example of switching from no encryption to AES-CBC encryption at runtime. ```erlang %% Switch from no encryption to AES-CBC encryption AesSt = mtp_aes_cbc:new(Key, IV), Codec1 = mtp_codec:replace(crypto, mtp_aes_cbc, AesSt, Codec). ``` -------------------------------- ### new/7 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_codec.md Example of creating a codec with an explicit TLS layer and a buffer size limit. ```erlang %% With fake-TLS layer TlsCodec = mtp_fake_tls:new(), Codec = mtp_codec:new( mtp_noop_codec, mtp_noop_codec:new(), mtp_abridged, mtp_abridged:new(), true, TlsCodec, 2 * 1024 * 1024). ``` -------------------------------- ### Interactive Installer Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md This command installs and configures the proxy interactively. ```bash curl -L -o mtp_install.sh https://git.io/fj5ru && bash mtp_install.sh ``` -------------------------------- ### Example for upstream_new Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_down_conn.md Example usage of registering a new upstream connection. ```erlang {_DcId, PoolPid, DownPid} = mtp_config:get_downstream_safe(1, Opts), mtp_down_conn:upstream_new(DownPid, UpstreamPid, Opts). ``` -------------------------------- ### unhex Function Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_handler.md Example of converting a hex string to binary data. ```erlang unhex("00ff80") => <<0, 255, 128>> ``` -------------------------------- ### Application Environment Configuration Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_handler.md Example of the MTProto proxy configuration within the application environment. ```erlang {mtproto_proxy, [ {allowed_protocols, [mtp_secure, mtp_fake_tls, mtp_abridged, mtp_intermediate]}, {init_timeout_sec, 60}, {hibernate_timeout_sec, 60}, {ready_timeout_sec, 1200}, {reset_close_socket, off}, % Send RST on errors? {replay_check_server_error_filter, first}, {upstream_send_timeout_ms, 15000}, {domain_fronting, off} ]} ``` -------------------------------- ### Listen on multiple ports / IPs Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Example configuration for starting the proxy on multiple IP addresses or ports with different secrets and ad tags. ```erlang {mtproto_proxy, %% see src/mtproto_proxy.app.src for examples. [ {ports, [#{name => mtp_handler_1, listen_ip => "0.0.0.0", port => 1443, secret => <<"d0d6e111bada5511fcce9584deadbeef">>, tag => <<"dcbe8f1493fa4cd9ab300891c0b5b326">>}, #{name => mtp_handler_2, listen_ip => "0.0.0.0", port => 2443, secret => <<"100000000000000000000000000000001">>, tag => <<"cf8e6baff125ed5f661a761e69567711">>} ]} ]}, {kernel, <...> } ``` -------------------------------- ### start_link() Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_session_storage.md Starts the session storage worker. Called by supervisor. ```erlang start_link() -> {ok, Pid} ``` ```erlang {ok, Pid} = mtp_session_storage:start_link(), % Session storage is ready ``` -------------------------------- ### new/4 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_codec.md Example of creating a codec with no encryption and abridged packet framing. ```erlang %% No encryption, abridged packet framing Codec = mtp_codec:new( mtp_noop_codec, mtp_noop_codec:new(), mtp_abridged, mtp_abridged:new()). ``` -------------------------------- ### get_default_dc() Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_config.md Example of retrieving the default datacenter ID. ```erlang -spec get_default_dc() -> dc_id() | undefined. ``` ```erlang DefaultDc = mtp_config:get_default_dc(), case DefaultDc of undefined -> error(no_default_dc); DC -> mtp_config:get_downstream_safe(DC, Opts) end. ``` -------------------------------- ### Start in background and enable on system startup Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Enabling and starting the MTProto proxy service to run in the background and on system boot. ```bash sudo systemctl enable mtproto-proxy sudo systemctl start mtproto-proxy ``` -------------------------------- ### metric_backend configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Example of setting a custom metrics backend module. ```erlang {metric_backend, my_prometheus_backend} ``` -------------------------------- ### get_secret() Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_config.md Example of retrieving the current proxy secret. ```erlang -spec get_secret() -> binary(). ``` ```erlang Secret = mtp_config:get_secret(), % Used in encryption/decryption of MTProto packets ``` -------------------------------- ### get_port_secret/1 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtproto_proxy_app.md Example of retrieving a port's secret. ```erlang {ok, Secret} = mtproto_proxy_app:get_port_secret(mtp_handler_1), % {ok, <"d0d6e111bada5511fcce9584deadbeef">} ``` -------------------------------- ### Start Proxy Listener Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtproto_proxy_app.md Starts a single MTProto proxy listener with the given port configuration. ```erlang -spec start_proxy(proxy_port()) -> {ok, pid()}. ``` ```erlang Config = #{name => mtp_handler_2, port => 2443, secret => <<"d0d6e111bada5511fcce9584deadbeef">>, tag => <<"dcbe8f1493fa4cd9ab300891c0b5b326">>}, {ok, _Pid} = mtproto_proxy_app:start_proxy(Config). ``` -------------------------------- ### backend_node() Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_config.md Example of determining if datacenter pools run locally or on a remote back node. ```erlang -spec backend_node() -> local | {remote, node()}. ``` ```erlang case mtp_config:backend_node() of local -> ok; {remote, BackNode} -> io:format("Using backend at ~w~n", [BackNode]) end. ``` -------------------------------- ### keys_str Function Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_handler.md Example of retrieving and using the list of configured port secrets. ```erlang Keys = mtp_handler:keys_str(), % [{"mtp_handler_1", 1443, "d0d6e111bada5511fcce9584deadbeef"}, ...] ``` -------------------------------- ### decode_nonce Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_rpc.md Example of decoding a client nonce packet. ```erlang {nonce, KeySel, _Schema, _Ts, ClientNonce} = mtp_rpc:decode_nonce(RawData). ``` -------------------------------- ### Example Policy Configuration in prod-sys.config Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md A comprehensive example of policy configuration for a production system, including various rule types. ```erlang %% config/prod-sys.config {mtproto_proxy, [ {policy, [ %% 10,000 total connections per port {max_connections, [port_name], 10000}, %% 100 connections per IPv4 address {max_connections, [client_ipv4], 100}, %% 50 connections per /24 subnet {max_connections, [{client_ipv4_subnet, 24}], 50}, %% Reject IPs in the banned list {not_in_table, client_ipv4, banned_ips}, %% Only allow specific TLS domains {in_table, tls_domain, allowed_tls_domains} ]} ]} ``` -------------------------------- ### hex Function Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_handler.md Example of converting binary data to its hex string representation. ```erlang hex(<<0, 255, 128>>) => "00ff80" ``` -------------------------------- ### Convert Policy Key/Value Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md Examples demonstrating the 'convert' function for normalizing policy keys and values into database representations. ```erlang V1 = mtp_policy:convert(client_ipv4, {192, 0, 2, 1}), % Returns: 16909313 (0x01000200 as 32-bit little-endian) V2 = mtp_policy:convert(tls_domain, "Example.COM"), % Returns: << ``` -------------------------------- ### try_decode_packet/2 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_codec.md Example demonstrating how to handle packet decoding, including incomplete data scenarios. ```erlang case mtp_codec:try_decode_packet(RawData, Codec) of {ok, Packet, Rest, Codec1} -> handle_packet(Packet), mtp_codec:try_decode_packet(Rest, Codec1); {incomplete, Codec1} -> {ok, wait_for_more_data, Codec1} end. ``` -------------------------------- ### mtp_ping example Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Example of using mtp_ping to test connectivity and latency. ```bash $ ./_build/default/bin/mtp_ping --proto fake-tls --dc 1,2,3 --repeat 3 \ "https://t.me/proxy?server=tg.example.com&port=443&secret=ee..." Proxy : tg.example.com:443 Testing : 1 protocol(s) x 3 DC(s), timeout=5000ms, showing avg over 3 repeats fake-tls DC +1 : tcp=45ms handshake=52ms ping=140ms [total=237ms] OK fake-tls DC +2 : tcp=48ms handshake=54ms ping=155ms [total=257ms] OK fake-tls DC +3 : tcp=46ms handshake=51ms ping=148ms [total=245ms] OK === Summary === Protocols: fake-tls OK (3/3 DCs) Avg timings per DC (across 1 working protocol(s)): DC TCP(ms) Handshake(ms) Ping(ms) Total(ms) -------------------------------------------------- +1 45 52 140 237 +2 48 54 155 257 +3 46 51 148 245 ``` -------------------------------- ### Application Environment Configuration Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md An example of how MTProto Proxy policy rules are typically configured within the application environment. ```erlang {mtproto_proxy, [ {policy, [ {max_connections, [port_name], 10000}, {max_connections, [client_ipv4], 100}, {not_in_table, client_ipv4, banned_ips}, {in_table, tls_domain, allowed_domains} ]} ]} ``` -------------------------------- ### Check Function Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md Example demonstrating how to use the `check/4` function to evaluate policy rules and decide whether to accept or reject a connection. ```erlang Rules = [ {max_connections, [port_name], 10000}, {max_connections, [client_ipv4], 100}, {not_in_table, client_ipv4, banned_ips}, {in_table, tls_domain, allowed_domains} ], case mtp_policy:check(Rules, mtp_handler_1, {192, 0, 2, 1}, <<"example.com">>) of [] -> accept_connection(); [FailedRule | _] -> reject_connection(FailedRule) end. ``` -------------------------------- ### Install dependencies for Ubuntu/Debian Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Commands to install necessary dependencies for Ubuntu 18.xx, 19.xx, or Debian 10. ```bash sudo apt install erlang-nox erlang-dev make sed diffutils tar ``` -------------------------------- ### start/2 Function Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtproto_proxy_app.md Starts the MTProto proxy application. Called automatically by the OTP application controller. ```erlang start(StartType, StartArgs) -> {ok, Pid} ``` -------------------------------- ### Start in foreground mode (optional) Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Starting the proxy in foreground mode for testing purposes. ```bash ./start.sh ``` -------------------------------- ### IPv6 Configuration Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Example Erlang configuration for setting up MTProto proxy to listen on both IPv4 and IPv6. ```erlang {mtproto_proxy, %% see src/mtproto_proxy.app.src for examples. [ {ports, [#{name => mtp_handler_all_ipv4, listen_ip => "0.0.0.0", % IPv4 address, eg 203.0.113.1 port => 1443, secret => <<"d0d6e111bada5511fcce9584deadbeef">>, tag => <<"dcbe8f1493fa4cd9ab300891c0b5b326">>}, #{name => mtp_handler_all_ipv6, listen_ip => "::", % IPv6 address, eg "2001:db8:85a3::8a2e:370:7334" port => 1443, secret => <<"d0d6e111bada5511fcce9584deadbeef">>, tag => <<"dcbe8f1493fa4cd9ab300891c0b5b326">>} ]} ]}, {kernel, <...> } ``` -------------------------------- ### Install dependencies for CentOS 7 Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Commands to install necessary dependencies and Erlang for CentOS 7. ```bash # Enable "epel" and "Erlang solutions" repositories sudo yum install wget \ https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm \ https://packages.erlang-solutions.com/erlang-solutions-1.0-1.noarch.rpm # Install Erlang sudo yum install erlang-compiler erlang-erts erlang-kernel erlang-stdlib erlang-syntax_tools \ erlang-crypto erlang-inets erlang-sasl erlang-ssl ``` -------------------------------- ### migrate Function Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_handler.md Example usage of the migrate function, called when a downstream connection restarts. ```erlang %% Called by DC pool when a downstream restarts mtp_handler:migrate(UpStreamPid, OldDownstream). ``` -------------------------------- ### node_role configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Example of setting the node role to 'both' for a standard configuration. ```erlang {node_role, both} ``` -------------------------------- ### get_downstream_safe() Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_config.md Example of getting a downstream connection for a specific datacenter. ```erlang -spec get_downstream_safe(dc_id(), mtp_down_conn:upstream_opts()) -> {dc_id(), pid(), mtp_down_conn:handle()}. ``` ```erlang Opts = #{addr => {{10, 0, 0, 1}, 5000}, ad_tag => undefined}, {UsedDcId, PoolPid, DownPid} = mtp_config:get_downstream_safe(1, Opts), % Now DownPid can be used to proxy traffic to that DC ``` -------------------------------- ### Max Connections Rule Example 1 Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md Example of a max_connections rule limiting concurrent connections per listener. ```erlang {max_connections, [port_name], 1000} ``` -------------------------------- ### per_sni_secret_salt configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Example of setting a custom salt for deriving per-SNI secrets. ```erlang {per_sni_secret_salt, <<"your-unique-random-salt-here">>} ``` -------------------------------- ### MTP Policy Table Example Usage Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md Example usage of the 'mtp_policy_table' service for managing whitelist/blacklist tables. ```erlang %% Add IP to banned list mtp_policy_table:add(banned_ips, client_ipv4, {10, 0, 0, 1}), %% Check if IP is banned IsBanned = mtp_policy_table:exists(banned_ips, {10, 0, 0, 1}). ``` -------------------------------- ### send Function Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_handler.md Example usage of the send function to send Telegram responses to a client. ```erlang % Called by mtp_down_conn to send Telegram responses to client mtp_handler:send(UpstreamPid, {proxy_ans, DownPid, TgResponse}). ``` -------------------------------- ### domain_fronting_timeout_sec configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Example of setting the timeout for TCP connection to the fronted host. ```erlang {domain_fronting_timeout_sec, 10} ``` -------------------------------- ### conf_refresh_interval configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Example of setting the interval for automatic configuration refreshes. ```erlang {conf_refresh_interval, 3600} ``` -------------------------------- ### Max Connections Rule Example 2 Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md Example of a max_connections rule limiting concurrent connections per IP address. ```erlang {max_connections, [client_ipv4], 50} ``` -------------------------------- ### In Table Rule Example 2 Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md Example of an in_table rule whitelisting connections based on client IP address. ```erlang {in_table, client_ipv4, trusted_ips} ``` -------------------------------- ### Build Script Source: https://github.com/seriyps/mtproto_proxy/blob/master/AGENTS.md Bash script for building the MTProto Proxy project, including dependency installation and production release compilation. ```bash # Install dependencies and compile ./rebar3 compile # Build a production release (requires config/prod-sys.config and config/prod-vm.args) cp config/sys.config.example config/prod-sys.config cp config/vm.args.example config/prod-vm.args make ``` -------------------------------- ### Dec Function Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md Example demonstrating the usage of the `dec/4` function for cleaning up connection counters when a connection closes. ```erlang %% At connection acceptance: case mtp_policy:check(Rules, Name, Ip, Domain) of [] -> store_rules_for_cleanup(Rules); _ -> close_connection() end. %% At connection close: mtp_policy:dec(StoredRules, Name, Ip, Domain). ``` -------------------------------- ### start_link Function Signature Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_dc_pool.md Function signature for starting a datacenter connection pool. ```erlang start_link(DcId) -> {ok, Pid} ``` -------------------------------- ### proxy_config_url configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Example of setting the URL to fetch datacenter configuration from Telegram. ```erlang {proxy_config_url, "https://core.telegram.org/getProxyConfig"} ``` -------------------------------- ### Get the code Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Cloning the repository and navigating into the project directory. ```bash git clone https://github.com/seriyps/mtproto_proxy.git cd mtproto_proxy/ ``` -------------------------------- ### mtp_full_check_crc32 configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Example of enabling CRC32 checksum validation in mtp_full codec. ```erlang {mtp_full_check_crc32, true} ``` -------------------------------- ### back_node configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Example of setting the remote Erlang node name for datacenter pools. ```erlang {back_node, 'back@example.com'} ``` -------------------------------- ### encode_packet Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_rpc.md Example of encoding a packet to send to Telegram. ```erlang Packet = {proxy_req, 12345, ClientAddr, AdTag, mtp_abridged, ClientData}, Encoded = mtp_rpc:encode_packet(Packet, []). ``` -------------------------------- ### Max Connections Rule Example 3 Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md Example of a max_connections rule limiting concurrent connections per IP address and TLS domain. ```erlang {max_connections, [client_ipv4, tls_domain], 500} ``` -------------------------------- ### inet_pton function examples Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_rpc.md Converts IPv4 or IPv6 address tuple to network binary format. ```erlang inet_pton({A, B, C, D}) -> <<...>> % IPv4: 4 bytes inet_pton({A, B, C, D, E, F, G, H}) -> <<...>> % IPv6: 16 bytes ``` ```erlang <<127, 0, 0, 1>> = mtp_rpc:inet_pton({127, 0, 0, 1}). ``` -------------------------------- ### Application Environment Configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_down_conn.md Example configuration for the MTProto Proxy application environment. ```erlang {mtproto_proxy, [ {init_dc_connections, 2}, % Connections per pool {clients_per_dc_connection, 300}, % Upstreams per downstream {downstream_backpressure, #{ bytes_total => 10485760, packets_total => 600, bytes_per_upstream => 51200, packets_per_upstream => 3 }}, {downstream_socket_buffer_size, 512000}, {upstream_healthchecks, [ {qlen, 300}, {gc, 409600}, {total_mem, 3145728} ]} ]} ``` -------------------------------- ### per_sni_secrets configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Example of enabling unique secrets per TLS SNI domain. ```erlang {per_sni_secrets, on} ``` -------------------------------- ### Initialize Front Server Configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Command to initialize the configuration files for the front server. ```bash make init-config ROLE=front ``` -------------------------------- ### encode_packet Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_codec.md Example of encoding a packet and sending it over a TCP socket. ```erlang -spec encode_packet(iodata(), codec()) -> {iodata(), codec()}. ``` ```erlang {Encoded, Codec1} = mtp_codec:encode_packet(Packet, Codec), gen_tcp:send(Socket, Encoded). ``` -------------------------------- ### Initialize Back Server Configuration Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Command to initialize the configuration files for the back server. ```bash make init-config ROLE=back ``` -------------------------------- ### get Function Signature Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_dc_pool.md Function signature for getting a downstream connection from the pool. ```erlang -spec get(pid(), upstream(), #{addr := mtp_config:netloc_v4v6(), ...}) ->\n downstream() | {error, empty}. ``` -------------------------------- ### Derive SNI Secret Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_fake_tls.md Provides an example of how to use the derive_sni_secret function in Erlang. ```erlang BaseSecret = mtp_config:get_secret(), Salt = application:get_env(mtproto_proxy, per_sni_secret_salt), DerivedSecret = mtp_fake_tls:derive_sni_secret( BaseSecret, << ``` -------------------------------- ### decode_packet Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_rpc.md Example of decoding a received RPC packet from downstream (Telegram server). ```erlang case mtp_rpc:decode_packet(RawData) of {proxy_ans, ConnId, Payload} -> handle_answer(ConnId, Payload); {close_ext, ConnId} -> close_connection(ConnId); {unknown, _Magic, _Rest} -> error(invalid_packet) end. ``` -------------------------------- ### Setting Up Connection Policies Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/README.md Configuration snippet for setting up connection policies, including maximum connections per port and client IP, and a list of banned IPs. ```erlang {mtproto_proxy, [ {policy, [ {max_connections, [port_name], 10000}, {max_connections, [client_ipv4], 100}, {not_in_table, client_ipv4, banned_ips} ]} ]} ``` -------------------------------- ### parse_sni Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_fake_tls.md Example of extracting the SNI (Server Name Indication) domain from a ClientHello packet. ```erlang -spec parse_sni(binary()) -> {ok, binary()} | {error, no_sni | bad_hello}. | | Parameter | Type | Description | |-----------|------|-------------| | ClientHello | binary() | Raw TLS ClientHello packet | **Return:** - `{ok, Domain}` — SNI domain as binary - `{error, no_sni}` — ClientHello has no SNI extension - `{error, bad_hello}` — Invalid ClientHello structure **Example:** ```erlang case mtp_fake_tls:parse_sni(Data) of {ok, Domain} -> io:format("SNI: ~s~n", [Domain]); {error, no_sni} -> ok; {error, bad_hello} -> error(invalid_tls) end. ``` ``` -------------------------------- ### format_secret_hex Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_fake_tls.md Example of formatting a TLS secret as a hex string for Telegram share URLs. ```erlang format_secret_hex(binary(), binary()) -> binary() **Format:** ``` hex([0xee | Secret | Domain]) ``` **Example:** ```erlang HexSecret = mtp_fake_tls:format_secret_hex(Secret, Domain), % Returns: <<"ee" || hex(Secret) || hex(Domain)>> ``` ``` -------------------------------- ### Run the full test suite Source: https://github.com/seriyps/mtproto_proxy/blob/master/AGENTS.md Executes all tests including xref, eunit, common test, property-based tests, dialyzer, and coverage. ```bash make test ``` -------------------------------- ### Configuration Reload Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/errors.md Handles configuration changes, applying valid ones and logging errors for invalid ones. ```erlang config_change(_, Key, Value, _) -> case validate_config(Key, Value) of ok -> apply_config(Key, Value); {error, Why} -> ?LOG_ERROR("Config ~p invalid: ~p, ignoring", [Key, Why]) end ``` -------------------------------- ### allowed_protocols recommended Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Recommended setting for 'allowed_protocols' to prevent DPI detection. ```erlang {allowed_protocols, [mtp_secure, mtp_fake_tls]} ``` -------------------------------- ### fold_packets_if Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_codec.md Example of using fold_packets_if to process packets and stop folding when a count limit is reached. ```erlang -spec fold_packets_if( fun((binary(), Acc, Codec) -> {next | stop, Acc, Codec}), Acc, binary(), Codec) -> {Acc, Codec}. ``` ```erlang ProcessUntilLimit = fun (_, Count, C) when Count >= 100 -> {stop, Count, C}; (_, Count, C) -> {next, Count + 1, C} end, {Processed, Codec1} = mtp_codec:fold_packets_if( ProcessUntilLimit, 0, Data, Codec). ``` -------------------------------- ### fold_packets Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_codec.md Example of decoding all complete packets in data and processing them with a fold function to count packets. ```erlang -spec fold_packets( fun((Packet :: binary(), Acc, Codec) -> {Acc, Codec}), Acc, binary(), Codec) -> {Acc, Codec}. ``` ```erlang ProcessPacket = fun(P, Count, C) -> {Count + 1, C} end, {PacketCount, Codec1} = mtp_codec:fold_packets( ProcessPacket, 0, RawData, Codec). ``` -------------------------------- ### replay_check_session_storage Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Enable session-based replay attack detection. ```erlang {replay_check_session_storage, on} ``` -------------------------------- ### In Table Rule Example 1 Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_policy.md Example of an in_table rule whitelisting connections based on TLS domain. ```erlang {in_table, tls_domain, allowed_domains} ``` -------------------------------- ### Build Release Command Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/README.md Command to build a production release using rebar3. ```bash rebar3 as prod release ``` -------------------------------- ### Automatic Retry Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/errors.md Example of handling an `unknown_upstream` error by migrating to a new downstream connection. ```erlang case mtp_down_conn:send(DownPid, Data) of ok -> ok; {error, unknown_upstream} -> % Upstream must find new downstream mtp_handler:migrate(UpstreamPid, OldDownstream) end ``` -------------------------------- ### ready_timeout_sec Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/configuration.md Timeout for established connections (closes if no activity). ```erlang {ready_timeout_sec, 1200} ``` -------------------------------- ### format_secret_base64 Example Source: https://github.com/seriyps/mtproto_proxy/blob/master/_autodocs/api-reference/mtp_fake_tls.md Example of formatting a TLS secret for use in Telegram share URLs using base64 encoding. ```erlang -spec format_secret_base64(binary(), binary()) -> binary(). | | Parameter | Type | Description | |-----------|------|-------------| | Secret | binary() | 16-byte binary secret or 32-char hex | | Domain | binary() | TLS SNI domain (e.g., <<"s3.amazonaws.com">>) | **Return:** - URL-safe base64-encoded secret with domain **Format:** ``` Base64([0xee | Secret | Domain]) (URL-safe: no padding, + → -, / → _) ``` **Example:** ```erlang Secret = mtp_config:get_secret(), Domain = <<"s3.amazonaws.com">>, B64Secret = mtp_fake_tls:format_secret_base64(Secret, Domain), % Returns: <<"7u3t7e7h4v...">> (usable in t.me/proxy URLs) ``` ``` -------------------------------- ### Run with custom config-file (Docker) Source: https://github.com/seriyps/mtproto_proxy/blob/master/README.md Steps to build and run the MTProto proxy using Docker with a custom configuration. ```bash git clone https://github.com/seriyps/mtproto_proxy.git && cd mtproto_proxy/ make init-config # copies templates and auto-detects your server's IP # configure your port, secret, ad_tag. See [Settings](#settings) below. nano config/prod-sys.config make && sudo make install sudo systemctl enable mtproto-proxy sudo systemctl start mtproto-proxy ```