From f28cb1b0a926f1ea98700b7871537ad1793511fd Mon Sep 17 00:00:00 2001 From: Dmitry Kozlov Date: Wed, 5 Jan 2011 15:18:59 +0300 Subject: rename accel-pptp to accel-ppp --- accel-pppd/CMakeLists.txt | 102 ++ accel-pppd/accel-ppp.conf | 121 +++ accel-pppd/accel-ppp.conf.5 | 384 ++++++++ accel-pppd/auth/CMakeLists.txt | 13 + accel-pppd/auth/auth_chap_md5.c | 427 ++++++++ accel-pppd/auth/auth_mschap_v1.c | 517 ++++++++++ accel-pppd/auth/auth_mschap_v2.c | 639 ++++++++++++ accel-pppd/auth/auth_pap.c | 273 ++++++ accel-pppd/cli/CMakeLists.txt | 1 + accel-pppd/cli/cli.c | 227 +++++ accel-pppd/cli/cli.h | 48 + accel-pppd/cli/cli_p.h | 22 + accel-pppd/cli/show_sessions.c | 434 +++++++++ accel-pppd/cli/std_cmd.c | 324 +++++++ accel-pppd/cli/tcp.c | 371 +++++++ accel-pppd/cli/telnet.c | 757 +++++++++++++++ accel-pppd/ctrl/CMakeLists.txt | 3 + accel-pppd/ctrl/l2tp/CMakeLists.txt | 17 + accel-pppd/ctrl/l2tp/attr_defs.h | 73 ++ accel-pppd/ctrl/l2tp/dict.c | 271 ++++++ accel-pppd/ctrl/l2tp/dict/dictionary | 2 + accel-pppd/ctrl/l2tp/dict/dictionary.rfc2661 | 55 ++ accel-pppd/ctrl/l2tp/dict/dictionary.rfc3931 | 15 + accel-pppd/ctrl/l2tp/dict2c.py | 20 + accel-pppd/ctrl/l2tp/l2tp.c | 1141 ++++++++++++++++++++++ accel-pppd/ctrl/l2tp/l2tp.h | 88 ++ accel-pppd/ctrl/l2tp/l2tp_kernel.h | 163 ++++ accel-pppd/ctrl/l2tp/l2tp_prot.h | 55 ++ accel-pppd/ctrl/l2tp/netlink.c | 94 ++ accel-pppd/ctrl/l2tp/packet.c | 494 ++++++++++ accel-pppd/ctrl/pppoe/CMakeLists.txt | 17 + accel-pppd/ctrl/pppoe/cli.c | 205 ++++ accel-pppd/ctrl/pppoe/dpado.c | 162 ++++ accel-pppd/ctrl/pppoe/mac_filter.c | 255 +++++ accel-pppd/ctrl/pppoe/pppoe.c | 1288 +++++++++++++++++++++++++ accel-pppd/ctrl/pppoe/pppoe.h | 117 +++ accel-pppd/ctrl/pppoe/tr101.c | 97 ++ accel-pppd/ctrl/pptp/CMakeLists.txt | 5 + accel-pppd/ctrl/pptp/pptp.c | 775 +++++++++++++++ accel-pppd/ctrl/pptp/pptp_prot.h | 299 ++++++ accel-pppd/extra/CMakeLists.txt | 19 + accel-pppd/extra/chap-secrets.c | 281 ++++++ accel-pppd/extra/ippool.c | 208 ++++ accel-pppd/extra/pppd_compat.c | 523 ++++++++++ accel-pppd/extra/shaper_tbf.c | 1274 ++++++++++++++++++++++++ accel-pppd/extra/sigchld.c | 116 +++ accel-pppd/extra/sigchld.h | 21 + accel-pppd/include/cli.h | 1 + accel-pppd/include/events.h | 49 + accel-pppd/include/if_pppox.h | 234 +++++ accel-pppd/include/ipdb.h | 1 + accel-pppd/include/iprange.h | 1 + accel-pppd/include/linux_ppp.h | 19 + accel-pppd/include/list.h | 1 + accel-pppd/include/log.h | 1 + accel-pppd/include/memdebug.h | 1 + accel-pppd/include/mempool.h | 1 + accel-pppd/include/ppp.h | 1 + accel-pppd/include/ppp_auth.h | 1 + accel-pppd/include/ppp_fsm.h | 1 + accel-pppd/include/ppp_lcp.h | 1 + accel-pppd/include/pwdb.h | 1 + accel-pppd/include/radius.h | 1 + accel-pppd/include/sigchld.h | 1 + accel-pppd/include/spinlock.h | 1 + accel-pppd/include/triton.h | 1 + accel-pppd/include/utils.h | 1 + accel-pppd/ipdb.c | 31 + accel-pppd/ipdb.h | 29 + accel-pppd/iprange.c | 146 +++ accel-pppd/iprange.h | 10 + accel-pppd/log.c | 501 ++++++++++ accel-pppd/log.h | 69 ++ accel-pppd/logs/CMakeLists.txt | 17 + accel-pppd/logs/log_file.c | 614 ++++++++++++ accel-pppd/logs/log_pgsql.c | 321 ++++++ accel-pppd/logs/log_tcp.c | 323 +++++++ accel-pppd/main.c | 201 ++++ accel-pppd/memdebug.c | 184 ++++ accel-pppd/memdebug.h | 28 + accel-pppd/ppp/CMakeLists.txt | 19 + accel-pppd/ppp/ccp_mppe.c | 259 +++++ accel-pppd/ppp/ipcp_opt_dns.c | 155 +++ accel-pppd/ppp/ipcp_opt_ipaddr.c | 227 +++++ accel-pppd/ppp/lcp_opt_accomp.c | 106 ++ accel-pppd/ppp/lcp_opt_magic.c | 91 ++ accel-pppd/ppp/lcp_opt_mru.c | 195 ++++ accel-pppd/ppp/lcp_opt_pcomp.c | 106 ++ accel-pppd/ppp/ppp.c | 681 +++++++++++++ accel-pppd/ppp/ppp.h | 189 ++++ accel-pppd/ppp/ppp_auth.c | 346 +++++++ accel-pppd/ppp/ppp_auth.h | 37 + accel-pppd/ppp/ppp_ccp.c | 759 +++++++++++++++ accel-pppd/ppp/ppp_ccp.h | 96 ++ accel-pppd/ppp/ppp_fsm.c | 544 +++++++++++ accel-pppd/ppp/ppp_fsm.h | 72 ++ accel-pppd/ppp/ppp_ipcp.c | 665 +++++++++++++ accel-pppd/ppp/ppp_ipcp.h | 96 ++ accel-pppd/ppp/ppp_lcp.c | 847 ++++++++++++++++ accel-pppd/ppp/ppp_lcp.h | 136 +++ accel-pppd/ppp/ppp_notify.c | 54 ++ accel-pppd/ppp/ppp_pd.c | 14 + accel-pppd/pwdb.c | 56 ++ accel-pppd/pwdb.h | 27 + accel-pppd/radius/CMakeLists.txt | 19 + accel-pppd/radius/acct.c | 328 +++++++ accel-pppd/radius/attr_defs.h | 287 ++++++ accel-pppd/radius/auth.c | 497 ++++++++++ accel-pppd/radius/dict.c | 356 +++++++ accel-pppd/radius/dict/dictionary | 79 ++ accel-pppd/radius/dict/dictionary.cisco | 156 +++ accel-pppd/radius/dict/dictionary.microsoft | 83 ++ accel-pppd/radius/dict/dictionary.rfc2865 | 137 +++ accel-pppd/radius/dict/dictionary.rfc2866 | 57 ++ accel-pppd/radius/dict/dictionary.rfc2867 | 16 + accel-pppd/radius/dict/dictionary.rfc2868 | 54 ++ accel-pppd/radius/dict/dictionary.rfc2869 | 39 + accel-pppd/radius/dict/dictionary.rfc3576 | 30 + accel-pppd/radius/dict/dictionary.rfc3580 | 16 + accel-pppd/radius/dict/dictionary.rfc4072 | 9 + accel-pppd/radius/dict/dictionary.rfc4372 | 8 + accel-pppd/radius/dict/dictionary.rfc4675 | 28 + accel-pppd/radius/dict/dictionary.rfc4679 | 62 ++ accel-pppd/radius/dict/dictionary.rfc4818 | 11 + accel-pppd/radius/dict/dictionary.rfc4849 | 8 + accel-pppd/radius/dict/dictionary.rfc5176 | 9 + accel-pppd/radius/dict2c.py | 20 + accel-pppd/radius/dm_coa.c | 295 ++++++ accel-pppd/radius/packet.c | 644 +++++++++++++ accel-pppd/radius/radius.c | 529 ++++++++++ accel-pppd/radius/radius.h | 117 +++ accel-pppd/radius/radius_p.h | 122 +++ accel-pppd/radius/req.c | 277 ++++++ accel-pppd/triton/CMakeLists.txt | 40 + accel-pppd/triton/conf_file.c | 248 +++++ accel-pppd/triton/event.c | 105 ++ accel-pppd/triton/list.h | 249 +++++ accel-pppd/triton/loader.c | 62 ++ accel-pppd/triton/log.c | 73 ++ accel-pppd/triton/md.c | 216 +++++ accel-pppd/triton/mempool.c | 338 +++++++ accel-pppd/triton/mempool.h | 26 + accel-pppd/triton/options.c | 48 + accel-pppd/triton/spinlock.h | 42 + accel-pppd/triton/timer.c | 222 +++++ accel-pppd/triton/timerfd.c | 19 + accel-pppd/triton/timerfd.h | 60 ++ accel-pppd/triton/triton.c | 610 ++++++++++++ accel-pppd/triton/triton.h | 138 +++ accel-pppd/triton/triton_p.h | 103 ++ accel-pppd/utils.c | 11 + accel-pppd/utils.h | 8 + accel-pptpd/CMakeLists.txt | 102 -- accel-pptpd/accel-pptp.conf | 121 --- accel-pptpd/accel-pptp.conf.5 | 384 -------- accel-pptpd/auth/CMakeLists.txt | 13 - accel-pptpd/auth/auth_chap_md5.c | 427 -------- accel-pptpd/auth/auth_mschap_v1.c | 517 ---------- accel-pptpd/auth/auth_mschap_v2.c | 639 ------------ accel-pptpd/auth/auth_pap.c | 273 ------ accel-pptpd/cli/CMakeLists.txt | 1 - accel-pptpd/cli/cli.c | 227 ----- accel-pptpd/cli/cli.h | 48 - accel-pptpd/cli/cli_p.h | 22 - accel-pptpd/cli/show_sessions.c | 434 --------- accel-pptpd/cli/std_cmd.c | 324 ------- accel-pptpd/cli/tcp.c | 371 ------- accel-pptpd/cli/telnet.c | 757 --------------- accel-pptpd/ctrl/CMakeLists.txt | 3 - accel-pptpd/ctrl/l2tp/CMakeLists.txt | 17 - accel-pptpd/ctrl/l2tp/attr_defs.h | 73 -- accel-pptpd/ctrl/l2tp/dict.c | 271 ------ accel-pptpd/ctrl/l2tp/dict/dictionary | 2 - accel-pptpd/ctrl/l2tp/dict/dictionary.rfc2661 | 55 -- accel-pptpd/ctrl/l2tp/dict/dictionary.rfc3931 | 15 - accel-pptpd/ctrl/l2tp/dict2c.py | 20 - accel-pptpd/ctrl/l2tp/l2tp.c | 1141 ---------------------- accel-pptpd/ctrl/l2tp/l2tp.h | 88 -- accel-pptpd/ctrl/l2tp/l2tp_kernel.h | 163 ---- accel-pptpd/ctrl/l2tp/l2tp_prot.h | 55 -- accel-pptpd/ctrl/l2tp/netlink.c | 94 -- accel-pptpd/ctrl/l2tp/packet.c | 494 ---------- accel-pptpd/ctrl/pppoe/CMakeLists.txt | 17 - accel-pptpd/ctrl/pppoe/cli.c | 205 ---- accel-pptpd/ctrl/pppoe/dpado.c | 162 ---- accel-pptpd/ctrl/pppoe/mac_filter.c | 255 ----- accel-pptpd/ctrl/pppoe/pppoe.c | 1288 ------------------------- accel-pptpd/ctrl/pppoe/pppoe.h | 117 --- accel-pptpd/ctrl/pppoe/tr101.c | 97 -- accel-pptpd/ctrl/pptp/CMakeLists.txt | 5 - accel-pptpd/ctrl/pptp/pptp.c | 775 --------------- accel-pptpd/ctrl/pptp/pptp_prot.h | 299 ------ accel-pptpd/extra/CMakeLists.txt | 19 - accel-pptpd/extra/chap-secrets.c | 281 ------ accel-pptpd/extra/ippool.c | 208 ---- accel-pptpd/extra/pppd_compat.c | 523 ---------- accel-pptpd/extra/shaper_tbf.c | 1274 ------------------------ accel-pptpd/extra/sigchld.c | 116 --- accel-pptpd/extra/sigchld.h | 21 - accel-pptpd/include/cli.h | 1 - accel-pptpd/include/events.h | 49 - accel-pptpd/include/if_pppox.h | 234 ----- accel-pptpd/include/ipdb.h | 1 - accel-pptpd/include/iprange.h | 1 - accel-pptpd/include/linux_ppp.h | 19 - accel-pptpd/include/list.h | 1 - accel-pptpd/include/log.h | 1 - accel-pptpd/include/memdebug.h | 1 - accel-pptpd/include/mempool.h | 1 - accel-pptpd/include/ppp.h | 1 - accel-pptpd/include/ppp_auth.h | 1 - accel-pptpd/include/ppp_fsm.h | 1 - accel-pptpd/include/ppp_lcp.h | 1 - accel-pptpd/include/pwdb.h | 1 - accel-pptpd/include/radius.h | 1 - accel-pptpd/include/sigchld.h | 1 - accel-pptpd/include/spinlock.h | 1 - accel-pptpd/include/triton.h | 1 - accel-pptpd/include/utils.h | 1 - accel-pptpd/ipdb.c | 31 - accel-pptpd/ipdb.h | 29 - accel-pptpd/iprange.c | 146 --- accel-pptpd/iprange.h | 10 - accel-pptpd/log.c | 501 ---------- accel-pptpd/log.h | 69 -- accel-pptpd/logs/CMakeLists.txt | 17 - accel-pptpd/logs/log_file.c | 614 ------------ accel-pptpd/logs/log_pgsql.c | 321 ------ accel-pptpd/logs/log_tcp.c | 323 ------- accel-pptpd/main.c | 201 ---- accel-pptpd/memdebug.c | 184 ---- accel-pptpd/memdebug.h | 28 - accel-pptpd/ppp/CMakeLists.txt | 19 - accel-pptpd/ppp/ccp_mppe.c | 259 ----- accel-pptpd/ppp/ipcp_opt_dns.c | 155 --- accel-pptpd/ppp/ipcp_opt_ipaddr.c | 227 ----- accel-pptpd/ppp/lcp_opt_accomp.c | 106 -- accel-pptpd/ppp/lcp_opt_magic.c | 91 -- accel-pptpd/ppp/lcp_opt_mru.c | 195 ---- accel-pptpd/ppp/lcp_opt_pcomp.c | 106 -- accel-pptpd/ppp/ppp.c | 681 ------------- accel-pptpd/ppp/ppp.h | 189 ---- accel-pptpd/ppp/ppp_auth.c | 346 ------- accel-pptpd/ppp/ppp_auth.h | 37 - accel-pptpd/ppp/ppp_ccp.c | 759 --------------- accel-pptpd/ppp/ppp_ccp.h | 96 -- accel-pptpd/ppp/ppp_fsm.c | 544 ----------- accel-pptpd/ppp/ppp_fsm.h | 72 -- accel-pptpd/ppp/ppp_ipcp.c | 665 ------------- accel-pptpd/ppp/ppp_ipcp.h | 96 -- accel-pptpd/ppp/ppp_lcp.c | 847 ---------------- accel-pptpd/ppp/ppp_lcp.h | 136 --- accel-pptpd/ppp/ppp_notify.c | 54 -- accel-pptpd/ppp/ppp_pd.c | 14 - accel-pptpd/pwdb.c | 56 -- accel-pptpd/pwdb.h | 27 - accel-pptpd/radius/CMakeLists.txt | 19 - accel-pptpd/radius/acct.c | 328 ------- accel-pptpd/radius/attr_defs.h | 287 ------ accel-pptpd/radius/auth.c | 497 ---------- accel-pptpd/radius/dict.c | 356 ------- accel-pptpd/radius/dict/dictionary | 79 -- accel-pptpd/radius/dict/dictionary.cisco | 156 --- accel-pptpd/radius/dict/dictionary.microsoft | 83 -- accel-pptpd/radius/dict/dictionary.rfc2865 | 137 --- accel-pptpd/radius/dict/dictionary.rfc2866 | 57 -- accel-pptpd/radius/dict/dictionary.rfc2867 | 16 - accel-pptpd/radius/dict/dictionary.rfc2868 | 54 -- accel-pptpd/radius/dict/dictionary.rfc2869 | 39 - accel-pptpd/radius/dict/dictionary.rfc3576 | 30 - accel-pptpd/radius/dict/dictionary.rfc3580 | 16 - accel-pptpd/radius/dict/dictionary.rfc4072 | 9 - accel-pptpd/radius/dict/dictionary.rfc4372 | 8 - accel-pptpd/radius/dict/dictionary.rfc4675 | 28 - accel-pptpd/radius/dict/dictionary.rfc4679 | 62 -- accel-pptpd/radius/dict/dictionary.rfc4818 | 11 - accel-pptpd/radius/dict/dictionary.rfc4849 | 8 - accel-pptpd/radius/dict/dictionary.rfc5176 | 9 - accel-pptpd/radius/dict2c.py | 20 - accel-pptpd/radius/dm_coa.c | 295 ------ accel-pptpd/radius/packet.c | 644 ------------- accel-pptpd/radius/radius.c | 529 ---------- accel-pptpd/radius/radius.h | 117 --- accel-pptpd/radius/radius_p.h | 122 --- accel-pptpd/radius/req.c | 277 ------ accel-pptpd/triton/CMakeLists.txt | 40 - accel-pptpd/triton/conf_file.c | 248 ----- accel-pptpd/triton/event.c | 105 -- accel-pptpd/triton/list.h | 249 ----- accel-pptpd/triton/loader.c | 62 -- accel-pptpd/triton/log.c | 73 -- accel-pptpd/triton/md.c | 216 ----- accel-pptpd/triton/mempool.c | 338 ------- accel-pptpd/triton/mempool.h | 26 - accel-pptpd/triton/options.c | 48 - accel-pptpd/triton/spinlock.h | 42 - accel-pptpd/triton/timer.c | 222 ----- accel-pptpd/triton/timerfd.c | 19 - accel-pptpd/triton/timerfd.h | 60 -- accel-pptpd/triton/triton.c | 610 ------------ accel-pptpd/triton/triton.h | 138 --- accel-pptpd/triton/triton_p.h | 103 -- accel-pptpd/utils.c | 11 - accel-pptpd/utils.h | 8 - 304 files changed, 28294 insertions(+), 28294 deletions(-) create mode 100644 accel-pppd/CMakeLists.txt create mode 100644 accel-pppd/accel-ppp.conf create mode 100644 accel-pppd/accel-ppp.conf.5 create mode 100644 accel-pppd/auth/CMakeLists.txt create mode 100644 accel-pppd/auth/auth_chap_md5.c create mode 100644 accel-pppd/auth/auth_mschap_v1.c create mode 100644 accel-pppd/auth/auth_mschap_v2.c create mode 100644 accel-pppd/auth/auth_pap.c create mode 100644 accel-pppd/cli/CMakeLists.txt create mode 100644 accel-pppd/cli/cli.c create mode 100644 accel-pppd/cli/cli.h create mode 100644 accel-pppd/cli/cli_p.h create mode 100644 accel-pppd/cli/show_sessions.c create mode 100644 accel-pppd/cli/std_cmd.c create mode 100644 accel-pppd/cli/tcp.c create mode 100644 accel-pppd/cli/telnet.c create mode 100644 accel-pppd/ctrl/CMakeLists.txt create mode 100644 accel-pppd/ctrl/l2tp/CMakeLists.txt create mode 100644 accel-pppd/ctrl/l2tp/attr_defs.h create mode 100644 accel-pppd/ctrl/l2tp/dict.c create mode 100644 accel-pppd/ctrl/l2tp/dict/dictionary create mode 100644 accel-pppd/ctrl/l2tp/dict/dictionary.rfc2661 create mode 100644 accel-pppd/ctrl/l2tp/dict/dictionary.rfc3931 create mode 100644 accel-pppd/ctrl/l2tp/dict2c.py create mode 100644 accel-pppd/ctrl/l2tp/l2tp.c create mode 100644 accel-pppd/ctrl/l2tp/l2tp.h create mode 100644 accel-pppd/ctrl/l2tp/l2tp_kernel.h create mode 100644 accel-pppd/ctrl/l2tp/l2tp_prot.h create mode 100644 accel-pppd/ctrl/l2tp/netlink.c create mode 100644 accel-pppd/ctrl/l2tp/packet.c create mode 100644 accel-pppd/ctrl/pppoe/CMakeLists.txt create mode 100644 accel-pppd/ctrl/pppoe/cli.c create mode 100644 accel-pppd/ctrl/pppoe/dpado.c create mode 100644 accel-pppd/ctrl/pppoe/mac_filter.c create mode 100644 accel-pppd/ctrl/pppoe/pppoe.c create mode 100644 accel-pppd/ctrl/pppoe/pppoe.h create mode 100644 accel-pppd/ctrl/pppoe/tr101.c create mode 100644 accel-pppd/ctrl/pptp/CMakeLists.txt create mode 100644 accel-pppd/ctrl/pptp/pptp.c create mode 100644 accel-pppd/ctrl/pptp/pptp_prot.h create mode 100644 accel-pppd/extra/CMakeLists.txt create mode 100644 accel-pppd/extra/chap-secrets.c create mode 100644 accel-pppd/extra/ippool.c create mode 100644 accel-pppd/extra/pppd_compat.c create mode 100644 accel-pppd/extra/shaper_tbf.c create mode 100644 accel-pppd/extra/sigchld.c create mode 100644 accel-pppd/extra/sigchld.h create mode 120000 accel-pppd/include/cli.h create mode 100644 accel-pppd/include/events.h create mode 100644 accel-pppd/include/if_pppox.h create mode 120000 accel-pppd/include/ipdb.h create mode 120000 accel-pppd/include/iprange.h create mode 100644 accel-pppd/include/linux_ppp.h create mode 120000 accel-pppd/include/list.h create mode 120000 accel-pppd/include/log.h create mode 120000 accel-pppd/include/memdebug.h create mode 120000 accel-pppd/include/mempool.h create mode 120000 accel-pppd/include/ppp.h create mode 120000 accel-pppd/include/ppp_auth.h create mode 120000 accel-pppd/include/ppp_fsm.h create mode 120000 accel-pppd/include/ppp_lcp.h create mode 120000 accel-pppd/include/pwdb.h create mode 120000 accel-pppd/include/radius.h create mode 120000 accel-pppd/include/sigchld.h create mode 120000 accel-pppd/include/spinlock.h create mode 120000 accel-pppd/include/triton.h create mode 120000 accel-pppd/include/utils.h create mode 100644 accel-pppd/ipdb.c create mode 100644 accel-pppd/ipdb.h create mode 100644 accel-pppd/iprange.c create mode 100644 accel-pppd/iprange.h create mode 100644 accel-pppd/log.c create mode 100644 accel-pppd/log.h create mode 100644 accel-pppd/logs/CMakeLists.txt create mode 100644 accel-pppd/logs/log_file.c create mode 100644 accel-pppd/logs/log_pgsql.c create mode 100644 accel-pppd/logs/log_tcp.c create mode 100644 accel-pppd/main.c create mode 100644 accel-pppd/memdebug.c create mode 100644 accel-pppd/memdebug.h create mode 100644 accel-pppd/ppp/CMakeLists.txt create mode 100644 accel-pppd/ppp/ccp_mppe.c create mode 100644 accel-pppd/ppp/ipcp_opt_dns.c create mode 100644 accel-pppd/ppp/ipcp_opt_ipaddr.c create mode 100644 accel-pppd/ppp/lcp_opt_accomp.c create mode 100644 accel-pppd/ppp/lcp_opt_magic.c create mode 100644 accel-pppd/ppp/lcp_opt_mru.c create mode 100644 accel-pppd/ppp/lcp_opt_pcomp.c create mode 100644 accel-pppd/ppp/ppp.c create mode 100644 accel-pppd/ppp/ppp.h create mode 100644 accel-pppd/ppp/ppp_auth.c create mode 100644 accel-pppd/ppp/ppp_auth.h create mode 100644 accel-pppd/ppp/ppp_ccp.c create mode 100644 accel-pppd/ppp/ppp_ccp.h create mode 100644 accel-pppd/ppp/ppp_fsm.c create mode 100644 accel-pppd/ppp/ppp_fsm.h create mode 100644 accel-pppd/ppp/ppp_ipcp.c create mode 100644 accel-pppd/ppp/ppp_ipcp.h create mode 100644 accel-pppd/ppp/ppp_lcp.c create mode 100644 accel-pppd/ppp/ppp_lcp.h create mode 100644 accel-pppd/ppp/ppp_notify.c create mode 100644 accel-pppd/ppp/ppp_pd.c create mode 100644 accel-pppd/pwdb.c create mode 100644 accel-pppd/pwdb.h create mode 100644 accel-pppd/radius/CMakeLists.txt create mode 100644 accel-pppd/radius/acct.c create mode 100644 accel-pppd/radius/attr_defs.h create mode 100644 accel-pppd/radius/auth.c create mode 100644 accel-pppd/radius/dict.c create mode 100644 accel-pppd/radius/dict/dictionary create mode 100644 accel-pppd/radius/dict/dictionary.cisco create mode 100644 accel-pppd/radius/dict/dictionary.microsoft create mode 100644 accel-pppd/radius/dict/dictionary.rfc2865 create mode 100644 accel-pppd/radius/dict/dictionary.rfc2866 create mode 100644 accel-pppd/radius/dict/dictionary.rfc2867 create mode 100644 accel-pppd/radius/dict/dictionary.rfc2868 create mode 100644 accel-pppd/radius/dict/dictionary.rfc2869 create mode 100644 accel-pppd/radius/dict/dictionary.rfc3576 create mode 100644 accel-pppd/radius/dict/dictionary.rfc3580 create mode 100644 accel-pppd/radius/dict/dictionary.rfc4072 create mode 100644 accel-pppd/radius/dict/dictionary.rfc4372 create mode 100644 accel-pppd/radius/dict/dictionary.rfc4675 create mode 100644 accel-pppd/radius/dict/dictionary.rfc4679 create mode 100644 accel-pppd/radius/dict/dictionary.rfc4818 create mode 100644 accel-pppd/radius/dict/dictionary.rfc4849 create mode 100644 accel-pppd/radius/dict/dictionary.rfc5176 create mode 100644 accel-pppd/radius/dict2c.py create mode 100644 accel-pppd/radius/dm_coa.c create mode 100644 accel-pppd/radius/packet.c create mode 100644 accel-pppd/radius/radius.c create mode 100644 accel-pppd/radius/radius.h create mode 100644 accel-pppd/radius/radius_p.h create mode 100644 accel-pppd/radius/req.c create mode 100644 accel-pppd/triton/CMakeLists.txt create mode 100644 accel-pppd/triton/conf_file.c create mode 100644 accel-pppd/triton/event.c create mode 100644 accel-pppd/triton/list.h create mode 100644 accel-pppd/triton/loader.c create mode 100644 accel-pppd/triton/log.c create mode 100644 accel-pppd/triton/md.c create mode 100644 accel-pppd/triton/mempool.c create mode 100644 accel-pppd/triton/mempool.h create mode 100644 accel-pppd/triton/options.c create mode 100644 accel-pppd/triton/spinlock.h create mode 100644 accel-pppd/triton/timer.c create mode 100644 accel-pppd/triton/timerfd.c create mode 100644 accel-pppd/triton/timerfd.h create mode 100644 accel-pppd/triton/triton.c create mode 100644 accel-pppd/triton/triton.h create mode 100644 accel-pppd/triton/triton_p.h create mode 100644 accel-pppd/utils.c create mode 100644 accel-pppd/utils.h delete mode 100644 accel-pptpd/CMakeLists.txt delete mode 100644 accel-pptpd/accel-pptp.conf delete mode 100644 accel-pptpd/accel-pptp.conf.5 delete mode 100644 accel-pptpd/auth/CMakeLists.txt delete mode 100644 accel-pptpd/auth/auth_chap_md5.c delete mode 100644 accel-pptpd/auth/auth_mschap_v1.c delete mode 100644 accel-pptpd/auth/auth_mschap_v2.c delete mode 100644 accel-pptpd/auth/auth_pap.c delete mode 100644 accel-pptpd/cli/CMakeLists.txt delete mode 100644 accel-pptpd/cli/cli.c delete mode 100644 accel-pptpd/cli/cli.h delete mode 100644 accel-pptpd/cli/cli_p.h delete mode 100644 accel-pptpd/cli/show_sessions.c delete mode 100644 accel-pptpd/cli/std_cmd.c delete mode 100644 accel-pptpd/cli/tcp.c delete mode 100644 accel-pptpd/cli/telnet.c delete mode 100644 accel-pptpd/ctrl/CMakeLists.txt delete mode 100644 accel-pptpd/ctrl/l2tp/CMakeLists.txt delete mode 100644 accel-pptpd/ctrl/l2tp/attr_defs.h delete mode 100644 accel-pptpd/ctrl/l2tp/dict.c delete mode 100644 accel-pptpd/ctrl/l2tp/dict/dictionary delete mode 100644 accel-pptpd/ctrl/l2tp/dict/dictionary.rfc2661 delete mode 100644 accel-pptpd/ctrl/l2tp/dict/dictionary.rfc3931 delete mode 100644 accel-pptpd/ctrl/l2tp/dict2c.py delete mode 100644 accel-pptpd/ctrl/l2tp/l2tp.c delete mode 100644 accel-pptpd/ctrl/l2tp/l2tp.h delete mode 100644 accel-pptpd/ctrl/l2tp/l2tp_kernel.h delete mode 100644 accel-pptpd/ctrl/l2tp/l2tp_prot.h delete mode 100644 accel-pptpd/ctrl/l2tp/netlink.c delete mode 100644 accel-pptpd/ctrl/l2tp/packet.c delete mode 100644 accel-pptpd/ctrl/pppoe/CMakeLists.txt delete mode 100644 accel-pptpd/ctrl/pppoe/cli.c delete mode 100644 accel-pptpd/ctrl/pppoe/dpado.c delete mode 100644 accel-pptpd/ctrl/pppoe/mac_filter.c delete mode 100644 accel-pptpd/ctrl/pppoe/pppoe.c delete mode 100644 accel-pptpd/ctrl/pppoe/pppoe.h delete mode 100644 accel-pptpd/ctrl/pppoe/tr101.c delete mode 100644 accel-pptpd/ctrl/pptp/CMakeLists.txt delete mode 100644 accel-pptpd/ctrl/pptp/pptp.c delete mode 100644 accel-pptpd/ctrl/pptp/pptp_prot.h delete mode 100644 accel-pptpd/extra/CMakeLists.txt delete mode 100644 accel-pptpd/extra/chap-secrets.c delete mode 100644 accel-pptpd/extra/ippool.c delete mode 100644 accel-pptpd/extra/pppd_compat.c delete mode 100644 accel-pptpd/extra/shaper_tbf.c delete mode 100644 accel-pptpd/extra/sigchld.c delete mode 100644 accel-pptpd/extra/sigchld.h delete mode 120000 accel-pptpd/include/cli.h delete mode 100644 accel-pptpd/include/events.h delete mode 100644 accel-pptpd/include/if_pppox.h delete mode 120000 accel-pptpd/include/ipdb.h delete mode 120000 accel-pptpd/include/iprange.h delete mode 100644 accel-pptpd/include/linux_ppp.h delete mode 120000 accel-pptpd/include/list.h delete mode 120000 accel-pptpd/include/log.h delete mode 120000 accel-pptpd/include/memdebug.h delete mode 120000 accel-pptpd/include/mempool.h delete mode 120000 accel-pptpd/include/ppp.h delete mode 120000 accel-pptpd/include/ppp_auth.h delete mode 120000 accel-pptpd/include/ppp_fsm.h delete mode 120000 accel-pptpd/include/ppp_lcp.h delete mode 120000 accel-pptpd/include/pwdb.h delete mode 120000 accel-pptpd/include/radius.h delete mode 120000 accel-pptpd/include/sigchld.h delete mode 120000 accel-pptpd/include/spinlock.h delete mode 120000 accel-pptpd/include/triton.h delete mode 120000 accel-pptpd/include/utils.h delete mode 100644 accel-pptpd/ipdb.c delete mode 100644 accel-pptpd/ipdb.h delete mode 100644 accel-pptpd/iprange.c delete mode 100644 accel-pptpd/iprange.h delete mode 100644 accel-pptpd/log.c delete mode 100644 accel-pptpd/log.h delete mode 100644 accel-pptpd/logs/CMakeLists.txt delete mode 100644 accel-pptpd/logs/log_file.c delete mode 100644 accel-pptpd/logs/log_pgsql.c delete mode 100644 accel-pptpd/logs/log_tcp.c delete mode 100644 accel-pptpd/main.c delete mode 100644 accel-pptpd/memdebug.c delete mode 100644 accel-pptpd/memdebug.h delete mode 100644 accel-pptpd/ppp/CMakeLists.txt delete mode 100644 accel-pptpd/ppp/ccp_mppe.c delete mode 100644 accel-pptpd/ppp/ipcp_opt_dns.c delete mode 100644 accel-pptpd/ppp/ipcp_opt_ipaddr.c delete mode 100644 accel-pptpd/ppp/lcp_opt_accomp.c delete mode 100644 accel-pptpd/ppp/lcp_opt_magic.c delete mode 100644 accel-pptpd/ppp/lcp_opt_mru.c delete mode 100644 accel-pptpd/ppp/lcp_opt_pcomp.c delete mode 100644 accel-pptpd/ppp/ppp.c delete mode 100644 accel-pptpd/ppp/ppp.h delete mode 100644 accel-pptpd/ppp/ppp_auth.c delete mode 100644 accel-pptpd/ppp/ppp_auth.h delete mode 100644 accel-pptpd/ppp/ppp_ccp.c delete mode 100644 accel-pptpd/ppp/ppp_ccp.h delete mode 100644 accel-pptpd/ppp/ppp_fsm.c delete mode 100644 accel-pptpd/ppp/ppp_fsm.h delete mode 100644 accel-pptpd/ppp/ppp_ipcp.c delete mode 100644 accel-pptpd/ppp/ppp_ipcp.h delete mode 100644 accel-pptpd/ppp/ppp_lcp.c delete mode 100644 accel-pptpd/ppp/ppp_lcp.h delete mode 100644 accel-pptpd/ppp/ppp_notify.c delete mode 100644 accel-pptpd/ppp/ppp_pd.c delete mode 100644 accel-pptpd/pwdb.c delete mode 100644 accel-pptpd/pwdb.h delete mode 100644 accel-pptpd/radius/CMakeLists.txt delete mode 100644 accel-pptpd/radius/acct.c delete mode 100644 accel-pptpd/radius/attr_defs.h delete mode 100644 accel-pptpd/radius/auth.c delete mode 100644 accel-pptpd/radius/dict.c delete mode 100644 accel-pptpd/radius/dict/dictionary delete mode 100644 accel-pptpd/radius/dict/dictionary.cisco delete mode 100644 accel-pptpd/radius/dict/dictionary.microsoft delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc2865 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc2866 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc2867 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc2868 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc2869 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc3576 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc3580 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc4072 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc4372 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc4675 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc4679 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc4818 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc4849 delete mode 100644 accel-pptpd/radius/dict/dictionary.rfc5176 delete mode 100644 accel-pptpd/radius/dict2c.py delete mode 100644 accel-pptpd/radius/dm_coa.c delete mode 100644 accel-pptpd/radius/packet.c delete mode 100644 accel-pptpd/radius/radius.c delete mode 100644 accel-pptpd/radius/radius.h delete mode 100644 accel-pptpd/radius/radius_p.h delete mode 100644 accel-pptpd/radius/req.c delete mode 100644 accel-pptpd/triton/CMakeLists.txt delete mode 100644 accel-pptpd/triton/conf_file.c delete mode 100644 accel-pptpd/triton/event.c delete mode 100644 accel-pptpd/triton/list.h delete mode 100644 accel-pptpd/triton/loader.c delete mode 100644 accel-pptpd/triton/log.c delete mode 100644 accel-pptpd/triton/md.c delete mode 100644 accel-pptpd/triton/mempool.c delete mode 100644 accel-pptpd/triton/mempool.h delete mode 100644 accel-pptpd/triton/options.c delete mode 100644 accel-pptpd/triton/spinlock.h delete mode 100644 accel-pptpd/triton/timer.c delete mode 100644 accel-pptpd/triton/timerfd.c delete mode 100644 accel-pptpd/triton/timerfd.h delete mode 100644 accel-pptpd/triton/triton.c delete mode 100644 accel-pptpd/triton/triton.h delete mode 100644 accel-pptpd/triton/triton_p.h delete mode 100644 accel-pptpd/utils.c delete mode 100644 accel-pptpd/utils.h diff --git a/accel-pppd/CMakeLists.txt b/accel-pppd/CMakeLists.txt new file mode 100644 index 0000000..f65e2e6 --- /dev/null +++ b/accel-pppd/CMakeLists.txt @@ -0,0 +1,102 @@ +INCLUDE(CheckLibraryExists) +INCLUDE(CheckIncludeFiles) + +CHECK_LIBRARY_EXISTS(crypto MD5_Init "" HAVE_SSL) +IF (NOT HAVE_SSL) + MESSAGE(FATAL_ERROR "openssl library not found") +ENDIF (NOT HAVE_SSL) + +SET(CMAKE_REQUIRED_INCLUDES "openssl") +CHECK_INCLUDE_FILES("md5.h" HAVE_SSL) +IF (NOT HAVE_SSL) + MESSAGE(FATAL_ERROR "openssl headers not found") +ENDIF (NOT HAVE_SSL) + +SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -fvisibility=hidden -fno-strict-aliasing -D_GNU_SOURCE -DPTHREAD_SPINLOCK -DMEMDEBUG -fPIC") + +IF (EXISTS ${CMAKE_HOME_DIRECTORY}/.git) + EXECUTE_PROCESS( + COMMAND git log + COMMAND head -n1 + COMMAND awk "{print $2}" + WORKING_DIRECTORY ${CMAKE_HOME_DIRECTORY} + OUTPUT_VARIABLE ACCEL_PPP_VERSION + ) + STRING(STRIP ${ACCEL_PPP_VERSION} ACCEL_PPP_VERSION) +ELSE (EXISTS ${CMAKE_HOME_DIRECTORY}/.git) + SET (ACCEL_PPP_VERSION 1.3.2) +ENDIF (EXISTS ${CMAKE_HOME_DIRECTORY}/.git) + +ADD_DEFINITIONS(-DACCEL_PPP_VERSION="${ACCEL_PPP_VERSION}") + +INCLUDE_DIRECTORIES(include) + +IF (NOT DEFINED RADIUS) + SET(RADIUS TRUE) +ENDIF (NOT DEFINED RADIUS) + +IF (RADIUS) + ADD_DEFINITIONS(-DRADIUS) + ADD_SUBDIRECTORY(radius) +ENDIF (RADIUS) + +IF (VALGRIND) + ADD_DEFINITIONS(-DVALGRIND) +ENDIF (VALGRIND) + +ADD_SUBDIRECTORY(triton) +ADD_SUBDIRECTORY(ctrl) +ADD_SUBDIRECTORY(auth) +ADD_SUBDIRECTORY(logs) +ADD_SUBDIRECTORY(extra) + +ADD_EXECUTABLE(accel-pppd + ppp/ppp.c + ppp/ppp_fsm.c + ppp/ppp_lcp.c + ppp/lcp_opt_mru.c + ppp/lcp_opt_magic.c + ppp/lcp_opt_pcomp.c + ppp/lcp_opt_accomp.c + ppp/ppp_auth.c + ppp/ppp_ipcp.c + ppp/ipcp_opt_ipaddr.c + ppp/ipcp_opt_dns.c + ppp/ppp_ccp.c + ppp/ccp_mppe.c + + cli/std_cmd.c + cli/show_sessions.c + cli/telnet.c + cli/tcp.c + cli/cli.c + + pwdb.c + ipdb.c + + iprange.c + + utils.c + + log.c + main.c + memdebug.c +) + +TARGET_LINK_LIBRARIES(accel-pppd triton rt pthread crypto pcre) +set_property(TARGET accel-pppd PROPERTY CMAKE_SKIP_BUILD_RPATH FALSE) +set_property(TARGET accel-pppd PROPERTY CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) +set_property(TARGET accel-pppd PROPERTY INSTALL_RPATH_USE_LINK_PATH FALSE) +set_property(TARGET accel-pppd PROPERTY INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/lib/accel-ppp) + +INSTALL(TARGETS accel-pppd + RUNTIME DESTINATION sbin +) + +INSTALL(FILES accel-ppp.conf DESTINATION /etc RENAME accel-ppp.conf.dist) +INSTALL(FILES accel-ppp.conf.5 DESTINATION share/man/man5) + +INSTALL(CODE "EXECUTE_PROCESS(COMMAND mkdir -p /var/log/accel-ppp)") +INSTALL(CODE "EXECUTE_PROCESS(COMMAND mkdir -p /var/run/accel-ppp)") +INSTALL(CODE "EXECUTE_PROCESS(COMMAND 'echo 0 > /var/run/accel-ppp/seq')") + diff --git a/accel-pppd/accel-ppp.conf b/accel-pppd/accel-ppp.conf new file mode 100644 index 0000000..ab844dd --- /dev/null +++ b/accel-pppd/accel-ppp.conf @@ -0,0 +1,121 @@ +[modules] +#path=/usr/local/lib/accel-ppp +log_file +#log_tcp +#log_pgsql +pptp +#pppoe +#l2tp +auth_mschap_v2 +auth_mschap_v1 +auth_chap_md5 +auth_pap +radius +ippool +sigchld +pppd_compat +#shaper_tbf +#chap-secrets + +[core] +log-error=/var/log/accel-ppp/core.log +thread-count=4 + +[ppp] +verbose=1 +min-mtu=1000 +mtu=1400 +mru=1400 +#ccp=0 +#sid-case=upper +#check-ip=0 + +[lcp] +echo-interval=30 +echo-failure=3 + +[pptp] +echo-interval=30 +verbose=1 + +[pppoe] +interface=eth0 +#ac-name=xxx +#service-name=yyy +#pado-delay=0 +#pado-delay=0,100:100,200:200,-1:500 +#ifname-in-sid=called-sid +verbose=1 + +[l2tp] +#dictionary=/usr/local/share/accel-ppp/l2tp/dictionary +#hello-interval=60 +#timeout=60 +#rtimeout=5 +#retransmit=5 +#host-name=accel-ppp +verbose=1 + +[dns] +#dns1=172.16.0.1 +#dns2=172.16.1.1 + +[radius] +#dictionary=/usr/local/share/accel-ppp/radius/dictionary +nas-identifier=accel-ppp +nas-ip-address=127.0.0.1 +gw-ip-address=192.168.100.1 +auth-server=127.0.0.1:1812,testing123 +acct-server=127.0.0.1:1813,testing123 +dae-server=127.0.0.1:3799,testing123 +#dm_coa_secret=testing123 (deprecated) +verbose=1 +#timeout=3 +#max-try=3 +#acct-timeout=120 + +[client-ip-range] +10.0.0.0/8 + +[ip-pool] +gw-ip-address=192.168.0.1 +192.168.0.2-255 +192.168.1.1-255 +192.168.2.1-255 +192.168.3.1-255 + +[log] +log-file=/var/log/accel-ppp/accel-ppp.log +log-emerg=/var/log/accel-ppp/emerg.log +#log-debug=/dev/stdout +#log-tcp=127.0.0.1:3000 +copy=1 +#color=1 +#per-user-dir=per_user +#per-session-dir=per_session +#per-session=1 +level=3 +#log-tcp=127.0.0.1:3000 + +[log-pgsql] +conninfo=user=log +log-table=log + +[pppd-compat] +#ip-pre-up=/etc/ppp/ip-pre-up +ip-up=/etc/ppp/ip-up +ip-down=/etc/ppp/ip-down +ip-change=/etc/ppp/ip-change +radattr-prefix=/var/run/radattr +verbose=1 + +[tbf] +#attr=Filter-Id +#down-burst-factor=0.1 +#up-burst-factor=1.0 +#latency=50 + +[cli] +telnet=127.0.0.1:2000 +tcp=127.0.0.1:2001 +#passwd=123 diff --git a/accel-pppd/accel-ppp.conf.5 b/accel-pppd/accel-ppp.conf.5 new file mode 100644 index 0000000..d9aaadb --- /dev/null +++ b/accel-pppd/accel-ppp.conf.5 @@ -0,0 +1,384 @@ +.TH ACCEL-PPP.CONF 5 "6 October 2010" +.SH NAME +.B accel-ppp.conf +- ACCEL-PPP VPN daemon configuration +.SH DESCRIPTION +.BR accel-pppd (8) +reads options from this file, usually +.IR /etc/accel-ppp.conf +.TP +Configuration file consists of sections in form: +.TP +[section1] +.br +name1=val1 +.br +name2=val2 +.br +name3 +.TP +[section2] +.br + .... +.br +.SH SECTIONS +.TP +.SH [modules] +containes list of modules to load +.TP +.BI log_file +This is logging target which logs messages to files. It support per-session/per-user features. +.TP +.BI log_tcp +This is logging target which logs messages over TCP/IP. +.TP +.BI log_pgsql +This is logging target which logs messages to PostgreSQL. +.TP +.BI pptp +.br +PPTP controlling connection handling module. +.TP +.BI pppoe +.br +PPPoE discovery stage handling module. +.TP +.BI auth_pap +PAP authentication module. +.TP +.BI auth_chap +CHAP (md5) authentication module. +.TP +.BI auth_mschap_v1 +Microsoft CHAP (version 1) authentication module. +.TP +.BI auth_mschap_v2 +Microsoft CHAP (version 2) authentication module. +.TP +.BI radius +.br +RADIUS interaction module. +.TP +.BI ippool +.br +IP address assigning module. +.TP +.BI sigchld +Helper module to manage child processes, required by pppd_compat +.TP +.BI pppd_compat +This module starts pppd compatible ip-up/ip-down scripts and ip-change to handle RADIUS CoA request. +.TP +.SH [core] +Configuration of core module +.TP +.BI "log-error=" path +Path to file for core module error logging. +.TP +.BI "thread-count=" n +number of working threads, optimal - number of processors/cores +.TP +.SH [ppp] +.br +PPP module configuration. +.TP +.BI "verbose=" n +If n is not zero ppp module will produce verbose logging. +.TP +.BI "min-mtu=" n +Minimum acceptable MTU. If client will try to negotiate less then specified MTU then it will be NAKed or disconnected if rejects greater MTU. +.TP +.BI "mtu=" n +MTU which will be negotiated if client's MRU will be not acceptable. +.TP +.BI "mru=" n +Prefered MRU. +.TP +.BI "ccp=" n +Disable CCP negotiation if this parameter is zero. +.TP +.TP +.BI "sid-case=" upper|lower +Specifies in which case generate session identifier (default lower). +.TP +.BI "check-ip=" 0|1 +Specifies whether accel-ppp should check if IP already assigned to other ppp interface (default 0). +.TP +.SH [lcp] +.br +PPP LCP module configuration +.TP +.BI "echo-interval=" n +If this option is given and greater then 0 then lcp module will send echo-request every +.B n +seconds. +.TP +.BI "echo-failure=" n +Specifies maximum number of echo-requests may be sent without valid echo-reply, if exceeds connection will be terminated. +.TP +.SH [dns] +.TP +.BI "dns1=" x.x.x.x +Specifies primary DNS to be sent to peer. +.TP +.BI "dns2=" x.x.x.x +Specifies secondary DNS to be sent to peer. +.TP +.SH [client-ip-range] +You have to explicitly specify range of ip address from which clients can connect to server in form: +.br +.B x.x.x.x/mask +(for example 10.0.0.0/8) +.br +.B x.x.x.x-y +(for example 10.0.0.1-254) +.TP +.SH [pptp] +.br +Configuration of PPTP module. +.TP +.BI "bind=" x.x.x.x +If this option is given then pptp server will bind to specified IP address. +.TP +.BI "verbose=" n +If this option is given and +.B n +is greater of zero then pptp module will produce verbose logging. +.TP +.BI "echo-interval=" n +If this option is given and greater then zero then pptp module will send echo-request every +.B n +seconds. +.TP +.BI "echo-failure=" n +Specifies maximum number of echo-requests may be sent without valid echo-reply, if exceeds connection will be terminated. +.TP +.BI "timeout=" n +Timeout waiting reply from client in seconds (default 5). +.TP +.SH [pppoe] +.br +Configuration of PPPoE module. +.TP +.BI "interface=" ethX +Specifies interface name to listen/send discovery packets. You may specify multiple +.B interface +options. +.TP +.BI "ac-name=" ac-name +Specifies AC-Name tag value. If absent tag will not be sent. +.TP +.BI "service-name=" service-name +Specifies Service-Name to respond. If absent any Service-Name is acceptable and client's Service-Name will be sent back. +.TP +.BI "pado-delay=" delay[,delay1:count1[,delay2:count2[,...]]] +Specifies delays (also in condition of connection count) to send PADO (ms). +Last delay in list may be -1 which means don't accept new connections. +List have to be sorted by count key. +.TP +.BI "mac-filter=" filename,type +Specifies mac-filter filename and type, type maybe +.B allow +or +.B deny +.TP +.BI "ifname-in-sid=" called-sid|calling-sid|both +Specifies that interface name should be present in Called-Station-ID or in Calling-Station-ID or in both attributes. +.TP +.BI "verbose=" n +If this option is given and +.B n +is greater of zero then pppoe module will produce verbose logging. +.TP +.SH [l2tp] +.br +Configuration of L2TP module. +.TP +.BI "bind=" x.x.x.x +Specifies IP address to bind. +.TP +.BI "host-name=" string +This name will be sent to clients in Host-Name attribute. +.TP +.BI "hello-interval=" n +Specifies interval (in seconds) to send Hello control message. Its used for keep alive connection. If peer will not respond to Hello connection will be terminated. +.TP +.BI "timeout=" n +Specifies timeout (in seconds) to wait peer completes tunnel and session negotiation. +.TP +.BI "rtimeout=" n +Specifies timeout (in seconds) to wait message acknowledge, if elapsed message retransmition will be performed. +.TP +.BI "retransmit=" n +Specifies maximum number of message retransmission, if exceeds connection will be terminated. +.TP +.BI "verbose=" n +If this option is given and +.B n +is greater of zero then l2tp module will produce verbose logging. +.TP +.SH [radius] +.br +Configuration of RADIUS module. +.TP +.BI "nas-identifier=" identifier +Specifies value to send to RADIUS server in NAS-Identifier attribute and to be matched in DM/CoA requests. +.TP +.BI "nas-ip-address=" x.x.x.x +Specifies value to send to RADIUS server in NAS-IP-Address attribute and to be matched in DM/CoA requests. +Also DM/CoA server will bind to that address. +.TP +.BI "gw-ip-address=" x.x.x.x +Specifies address to use as local address of ppp interfaces if Framed-IP-Address received from RADIUS server. +.TP +.BI "auth-server=" x.x.x.x:port,secret +Specifies IP address, port and secret of authentication RADIUS server. +.TP +.BI "acct-server=" x.x.x.x:port,secret +Specifies IP address, port and secret of accounting RADIUS server. +.TP +.BI "dae-server=" x.x.x.x:port,secret +Specifies IP address, port to bind and secret for Dynamic Authorization Extension server (DM/CoA). +.TP +.BI "dm_coa_secret=" secret (deprecated, use dae-server instead) +Specifies secret to use in DM/CoA communication. +.TP +.BI "acct-interim-interval=" n +Specifies interval in seconds to send accounting information (may be overriden by radius Acct-Interim-Interval attribute) +.TP +.BI "verbose=" n +If this option is given and +.B n +is greater of zero then radius module will produce verbose logging. +.TP +.BI "interim-verbose=" n +If this option is given and +.B n +is greater of zero then radius module will produce verbose logging of interim radius packets. +.TP +.BI "timeout=" n +Timeout to wait response from server (sec) +.TP +.BI "max-try=" n +Specifies number of tries to send Access-Request/Accounting-Request queries. +.TP +.BI "acct-timeout=" n +Specifies timeout of accounting interim update. +.TP +.SH [log] +.br +Configuration of log and log_file modules. +.TP +.BI "log-file=" file +Path to file to write general log. +.TP +.BI "log-emerg=" file +Path to file to write emergency messages. +.TP +.BI "log-tcp=" x.x.x.x:port +Send logs to specified host. +.TP +.BI "copy=" n +If this options is given and greater then zero logging engine will duplicate session log in general log. +(Useful when per-session/per-user logs are not used) +.TP +.BI "per-session-dir=" dir +Directory for session logs. If specified each session will be logged separately to file which name is unique session identifier. +.TP +.BI "per-user-dir=" dir +Directory for user logs. If specified all sessions of same user will be logged to file which name is user name. +.TP +.BI "per-session=" n +If specified and n is greater then zero each session of same user will be logger separately to directory specified by "per-user-dir" +and subdirectory which name is user name and to file which name os unique session identifier. +.TP +.BI "level=" n +Specifies log level which values are: +.br +.B 0 +turn off all logging +.br +.B 1 +log only error messages +.br +.B 2 +log error and warning messages +.br +.B 3 +log error, warning and minimum information messages (use this level in conjuction with verbose option of other modules if you need verbose logging) +.br +.B 4 +log error, warning and full information messages (use this level in conjuction with verbose option of other modules if you need verbose logging) +.br +.B 5 +log all messages including debug messages +.TP +.SH [log-pgsql] +.br +Configuration of log_pgsql module. +.TP +.BI "conninfo=" conninfo +Conninfo to connect to PostgreSQL server. +.TP +.BI "log-table=" table +Table to send log messages. Table must contain following field: +.br +.B timestamp +timestamp +.br +.B username +text +.br +.B sessionid +text +.br +.B msg +text +.TP +.SH [pppd_compat] +.br +Configuration of pppd_compat module. +.TP +.BI "ip-pre-up=" file +Path to ip-pre-up script which is executed before ppp interface comes up, useful to setup firewall rules before any traffic can pass through the interface. +.TP +.BI "ip-up=" file +Path to ip-up script which is executed when ppp interfaces is completly configured and started. +.TP +.BI "ip-down=" file +Path to ip-down script which is executed when session is about to terminate. +.TP +.BI "ip-change=" file +Path to ip-change script which is executed for RADIUS CoA handling. +.TP +.BI "radattr=" prefix +Prefix of radattr files (for example /var/run/radattr, resulting files will be /var/run/radattr.pppX) +.TP +.BI "verbose=" n +If specified and greated then zero pppd_module will produce verbose logging. +.TP +.SH [ip-pool] +.br +Configuration of ippool module. +.TP +.BI "gw-ip-address=" x.x.x.x +Specifies single IP address to be used as local address of ppp interfaces. +.TP +.BI "gw=" range +Specifies range of local address of ppp interfaces if form: +.br +.B x.x.x.x/mask +(for example 10.0.0.0/8) +.br +.B x.x.x.x-y +(for example 10.0.0.1-254) +.TP +.BI "tunnel=" range +Specifies range of remote address of ppp interfaces if form: +.br +.B x.x.x.x/mask +.br +.B x.x.x.x-y +.TP +.BI "x.x.x.x/mask or x.x.x.x-y" +Also specifies range of remote address of ppp interfaces. diff --git a/accel-pppd/auth/CMakeLists.txt b/accel-pppd/auth/CMakeLists.txt new file mode 100644 index 0000000..ef9478a --- /dev/null +++ b/accel-pppd/auth/CMakeLists.txt @@ -0,0 +1,13 @@ +ADD_LIBRARY(auth_pap SHARED auth_pap.c) +ADD_LIBRARY(auth_chap_md5 SHARED auth_chap_md5.c) +ADD_LIBRARY(auth_mschap_v1 SHARED auth_mschap_v1.c) +ADD_LIBRARY(auth_mschap_v2 SHARED auth_mschap_v2.c) + +TARGET_LINK_LIBRARIES(auth_chap_md5 crypto) +TARGET_LINK_LIBRARIES(auth_mschap_v1 crypto) +TARGET_LINK_LIBRARIES(auth_mschap_v2 crypto) + +INSTALL(TARGETS auth_pap auth_chap_md5 auth_mschap_v1 auth_mschap_v2 + LIBRARY DESTINATION lib/accel-ppp +) + diff --git a/accel-pppd/auth/auth_chap_md5.c b/accel-pppd/auth/auth_chap_md5.c new file mode 100644 index 0000000..d19634a --- /dev/null +++ b/accel-pppd/auth/auth_chap_md5.c @@ -0,0 +1,427 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "log.h" +#include "ppp.h" +#include "ppp_auth.h" +#include "ppp_lcp.h" +#include "pwdb.h" + +#include "memdebug.h" + +#define CHAP_CHALLENGE 1 +#define CHAP_RESPONSE 2 +#define CHAP_SUCCESS 3 +#define CHAP_FAILURE 4 + +#define CHAP_MD5 5 + +#define VALUE_SIZE 16 + +#define MSG_FAILURE "Authentication failed" +#define MSG_SUCCESS "Authentication successed" + +#define HDR_LEN (sizeof(struct chap_hdr_t)-2) + +static int conf_timeout = 5; +static int conf_interval = 0; +static int conf_max_failure = 3; +static int conf_any_login = 0; + +static int urandom_fd; + +struct chap_hdr_t +{ + uint16_t proto; + uint8_t code; + uint8_t id; + uint16_t len; +} __attribute__((packed)); + +struct chap_challenge_t +{ + struct chap_hdr_t hdr; + uint8_t val_size; + uint8_t val[VALUE_SIZE]; + char name[0]; +} __attribute__((packed)); + +struct chap_failure_t +{ + struct chap_hdr_t hdr; + char message[sizeof(MSG_FAILURE)]; +} __attribute__((packed)); + +struct chap_success_t +{ + struct chap_hdr_t hdr; + char message[sizeof(MSG_SUCCESS)]; +} __attribute__((packed)); + + +struct chap_auth_data_t +{ + struct auth_data_t auth; + struct ppp_handler_t h; + struct ppp_t *ppp; + int id; + uint8_t val[VALUE_SIZE]; + struct triton_timer_t timeout; + struct triton_timer_t interval; + int failure; + int started:1; +}; + +static void chap_send_challenge(struct chap_auth_data_t *ad); +static void chap_recv(struct ppp_handler_t *h); +static void chap_timeout_timer(struct triton_timer_t *t); +static void chap_restart_timer(struct triton_timer_t *t); + +static void print_buf(const uint8_t *buf, int size) +{ + int i; + for (i=0; i < size; i++) + log_ppp_info2("%x", buf[i]); +} +static void print_str(const char *buf, int size) +{ + int i; + for (i = 0; i < size; i++) + log_ppp_info2("%c", buf[i]); +} + +static struct auth_data_t* auth_data_init(struct ppp_t *ppp) +{ + struct chap_auth_data_t *d = _malloc(sizeof(*d)); + + memset(d, 0, sizeof(*d)); + d->auth.proto = PPP_CHAP; + d->ppp = ppp; + + return &d->auth; +} + +static void auth_data_free(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + if (d->timeout.tpd) + triton_timer_del(&d->timeout); + + if (d->interval.tpd) + triton_timer_del(&d->interval); + + _free(d); +} + +static int chap_start(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + d->h.proto = PPP_CHAP; + d->h.recv = chap_recv; + d->timeout.expire = chap_timeout_timer; + d->timeout.period = conf_timeout * 1000; + d->interval.expire = chap_restart_timer; + d->interval.period = conf_interval * 1000; + + ppp_register_chan_handler(ppp, &d->h); + + chap_send_challenge(d); + + return 0; +} + +static int chap_finish(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + if (d->timeout.tpd) + triton_timer_del(&d->timeout); + + if (d->interval.tpd) + triton_timer_del(&d->interval); + + ppp_unregister_handler(ppp, &d->h); + + return 0; +} + +static void chap_timeout_timer(struct triton_timer_t *t) +{ + struct chap_auth_data_t *d = container_of(t, typeof(*d), timeout); + + if (conf_ppp_verbose) + log_ppp_warn("chap-md5: timeout\n"); + + if (++d->failure == conf_max_failure) { + if (d->started) + ppp_terminate(d->ppp, TERM_USER_ERROR, 0); + else + ppp_auth_failed(d->ppp, NULL); + } else { + --d->id; + chap_send_challenge(d); + } +} + +static void chap_restart_timer(struct triton_timer_t *t) +{ + struct chap_auth_data_t *d = container_of(t, typeof(*d), interval); + + chap_send_challenge(d); +} + +static int lcp_send_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) +{ + *ptr = CHAP_MD5; + return 1; +} + +static int lcp_recv_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) +{ + if (*ptr == CHAP_MD5) + return LCP_OPT_ACK; + return LCP_OPT_NAK; +} + +static void chap_send_failure(struct chap_auth_data_t *ad) +{ + struct chap_failure_t msg = { + .hdr.proto = htons(PPP_CHAP), + .hdr.code = CHAP_FAILURE, + .hdr.id = ad->id, + .hdr.len = htons(sizeof(msg) - 1 - 2), + .message = MSG_FAILURE, + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [CHAP Failure id=%x \"%s\"]\n", msg.hdr.id, MSG_FAILURE); + + ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); +} + +static void chap_send_success(struct chap_auth_data_t *ad) +{ + struct chap_success_t msg = { + .hdr.proto = htons(PPP_CHAP), + .hdr.code = CHAP_SUCCESS, + .hdr.id = ad->id, + .hdr.len = htons(sizeof(msg)-1-2), + .message = MSG_SUCCESS, + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [CHAP Success id=%x \"%s\"]\n", msg.hdr.id, MSG_SUCCESS); + + ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); +} + +static void chap_send_challenge(struct chap_auth_data_t *ad) +{ + struct chap_challenge_t msg = { + .hdr.proto = htons(PPP_CHAP), + .hdr.code = CHAP_CHALLENGE, + .hdr.id = ++ad->id, + .hdr.len = htons(sizeof(msg) - 2), + .val_size = VALUE_SIZE, + }; + + read(urandom_fd, ad->val, VALUE_SIZE); + memcpy(msg.val, ad->val, VALUE_SIZE); + + if (conf_ppp_verbose) { + log_ppp_info2("send [CHAP Challenge id=%x <", msg.hdr.id); + print_buf(msg.val, VALUE_SIZE); + log_ppp_info2(">]\n"); + } + + ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); + + if (conf_timeout && !ad->timeout.tpd) + triton_timer_add(ad->ppp->ctrl->ctx, &ad->timeout, 0); +} + +static void chap_recv_response(struct chap_auth_data_t *ad, struct chap_hdr_t *hdr) +{ + MD5_CTX md5_ctx; + uint8_t md5[MD5_DIGEST_LENGTH]; + char *passwd; + char *name; + int r; + struct chap_challenge_t *msg = (struct chap_challenge_t*)hdr; + + if (ad->timeout.tpd) + triton_timer_del(&ad->timeout); + + if (conf_ppp_verbose) { + log_ppp_info2("recv [CHAP Response id=%x <", msg->hdr.id); + print_buf(msg->val, msg->val_size); + log_ppp_info2(">, name=\""); + print_str(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); + log_ppp_info2("\"]\n"); + } + + if (msg->hdr.id != ad->id) { + if (conf_ppp_verbose) + log_ppp_error("chap-md5: id mismatch\n"); + chap_send_failure(ad); + ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); + } + + if (msg->val_size != VALUE_SIZE) { + log_ppp_error("chap-md5: incorrect value-size (%i)\n", msg->val_size); + chap_send_failure(ad); + ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); + } + + name = _strndup(msg->name,ntohs(msg->hdr.len) - sizeof(*msg) + 2); + + if (conf_any_login) { + chap_send_success(ad); + ad->started = 1; + ppp_auth_successed(ad->ppp, name); + return; + } + + r = pwdb_check(ad->ppp, name, PPP_CHAP, CHAP_MD5, ad->id, ad->val, VALUE_SIZE, msg->val); + + if (r == PWDB_NO_IMPL) { + passwd = pwdb_get_passwd(ad->ppp,name); + if (!passwd) + { + _free(name); + if (conf_ppp_verbose) + log_ppp_warn("chap-md5: user not found\n"); + chap_send_failure(ad); + return; + } + + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx,&msg->hdr.id,1); + MD5_Update(&md5_ctx,passwd,strlen(passwd)); + MD5_Update(&md5_ctx,ad->val,VALUE_SIZE); + MD5_Final(md5,&md5_ctx); + + if (memcmp(md5,msg->val,sizeof(md5))) + { + if (conf_ppp_verbose) + log_ppp_warn("chap-md5: challenge response mismatch\n"); + chap_send_failure(ad); + if (ad->started) + ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); + else + ppp_auth_failed(ad->ppp, name); + _free(name); + } else { + chap_send_success(ad); + if (!ad->started) { + ad->started = 1; + if (conf_interval) + triton_timer_add(ad->ppp->ctrl->ctx, &ad->interval, 0); + ppp_auth_successed(ad->ppp, name); + } else + _free(name); + } + _free(passwd); + } else if (r == PWDB_DENIED) { + chap_send_failure(ad); + if (ad->started) + ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); + else + ppp_auth_failed(ad->ppp, name); + _free(name); + } else { + chap_send_success(ad); + if (!ad->started) { + ad->started = 1; + if (conf_interval) + triton_timer_add(ad->ppp->ctrl->ctx, &ad->interval, 0); + ppp_auth_successed(ad->ppp, name); + } else + _free(name); + } +} + +static int chap_check(uint8_t *ptr) +{ + return *ptr == CHAP_MD5; +} + +static int chap_restart(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + chap_send_challenge(d); + + return 0; +} + +static struct ppp_auth_handler_t chap= +{ + .name = "CHAP-md5", + .init = auth_data_init, + .free = auth_data_free, + .send_conf_req = lcp_send_conf_req, + .recv_conf_req = lcp_recv_conf_req, + .start = chap_start, + .finish = chap_finish, + .check = chap_check, + .restart = chap_restart, +}; + +static void chap_recv(struct ppp_handler_t *h) +{ + struct chap_auth_data_t *d = container_of(h, typeof(*d), h); + struct chap_hdr_t *hdr = (struct chap_hdr_t *)d->ppp->chan_buf; + + if (d->ppp->chan_buf_size < sizeof(*hdr) || ntohs(hdr->len) < HDR_LEN || ntohs(hdr->len) < d->ppp->chan_buf_size - 2) { + log_ppp_warn("chap-md5: short packet received\n"); + return; + } + + if (hdr->code == CHAP_RESPONSE) + chap_recv_response(d, hdr); + else + log_ppp_warn("chap-md5: unknown code received %x\n", hdr->code); +} + +static void __init auth_chap_md5_init() +{ + char *opt; + + opt = conf_get_opt("auth", "timeout"); + if (opt && atoi(opt) > 0) + conf_timeout = atoi(opt); + + opt = conf_get_opt("auth", "interval"); + if (opt && atoi(opt) > 0) + conf_interval = atoi(opt); + + opt = conf_get_opt("auth", "max-failure"); + if (opt && atoi(opt) > 0) + conf_max_failure = atoi(opt); + + opt = conf_get_opt("auth", "any-login"); + if (opt && atoi(opt) > 0) + conf_any_login = 1; + + urandom_fd=open("/dev/urandom", O_RDONLY); + + if (urandom_fd < 0) { + log_emerg("chap-md5: failed to open /dev/urandom: %s\n", strerror(errno)); + return; + } + + if (ppp_auth_register_handler(&chap)) + log_emerg("chap-md5: failed to register handler\n"); +} + diff --git a/accel-pppd/auth/auth_mschap_v1.c b/accel-pppd/auth/auth_mschap_v1.c new file mode 100644 index 0000000..5b38db5 --- /dev/null +++ b/accel-pppd/auth/auth_mschap_v1.c @@ -0,0 +1,517 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "log.h" +#include "ppp.h" +#include "events.h" +#include "ppp_auth.h" +#include "ppp_lcp.h" +#include "pwdb.h" + +#include "memdebug.h" + +#define MSCHAP_V1 0x80 + +#define CHAP_CHALLENGE 1 +#define CHAP_RESPONSE 2 +#define CHAP_SUCCESS 3 +#define CHAP_FAILURE 4 + +#define VALUE_SIZE 8 +#define RESPONSE_VALUE_SIZE (24+24+1) + +#define MSG_FAILURE "E=691 R=0" +#define MSG_SUCCESS "Authentication successed" + +#define HDR_LEN (sizeof(struct chap_hdr_t)-2) + +static int conf_timeout = 5; +static int conf_interval = 0; +static int conf_max_failure = 3; +static int conf_any_login = 0; + +static int urandom_fd; + +struct chap_hdr_t +{ + uint16_t proto; + uint8_t code; + uint8_t id; + uint16_t len; +} __attribute__((packed)); + +struct chap_challenge_t +{ + struct chap_hdr_t hdr; + uint8_t val_size; + uint8_t val[VALUE_SIZE]; + char name[0]; +} __attribute__((packed)); + +struct chap_response_t +{ + struct chap_hdr_t hdr; + uint8_t val_size; + uint8_t lm_hash[24]; + uint8_t nt_hash[24]; + uint8_t flags; + char name[0]; +} __attribute__((packed)); + +struct chap_failure_t +{ + struct chap_hdr_t hdr; + char message[sizeof(MSG_FAILURE)]; +} __attribute__((packed)); + +struct chap_success_t +{ + struct chap_hdr_t hdr; + char message[sizeof(MSG_SUCCESS)]; +} __attribute__((packed)); + + +struct chap_auth_data_t +{ + struct auth_data_t auth; + struct ppp_handler_t h; + struct ppp_t *ppp; + int id; + uint8_t val[VALUE_SIZE]; + struct triton_timer_t timeout; + struct triton_timer_t interval; + int failure; + int started:1; +}; + +static void chap_send_challenge(struct chap_auth_data_t *ad); +static void chap_recv(struct ppp_handler_t *h); +static int chap_check_response(struct chap_auth_data_t *ad, struct chap_response_t *res, const char *name); +static void chap_timeout_timer(struct triton_timer_t *t); +static void chap_restart_timer(struct triton_timer_t *t); +static void set_mppe_keys(struct chap_auth_data_t *ad, uint8_t *z_hash); + +static void print_buf(const uint8_t *buf,int size) +{ + int i; + for (i = 0; i < size; i++) + log_ppp_info2("%x", buf[i]); +} +static void print_str(const char *buf, int size) +{ + int i; + for(i = 0; i < size; i++) + log_ppp_info2("%c", buf[i]); +} + +static struct auth_data_t* auth_data_init(struct ppp_t *ppp) +{ + struct chap_auth_data_t *d = _malloc(sizeof(*d)); + + memset(d, 0, sizeof(*d)); + d->auth.proto = PPP_CHAP; + d->ppp = ppp; + + return &d->auth; +} + +static void auth_data_free(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + if (d->timeout.tpd) + triton_timer_del(&d->timeout); + + if (d->interval.tpd) + triton_timer_del(&d->interval); + + _free(d); +} + +static int chap_start(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + d->h.proto = PPP_CHAP; + d->h.recv = chap_recv; + d->timeout.expire = chap_timeout_timer; + d->timeout.period = conf_timeout * 1000; + d->interval.expire = chap_restart_timer; + d->interval.period = conf_interval * 1000; + + ppp_register_chan_handler(ppp, &d->h); + + chap_send_challenge(d); + + return 0; +} + +static int chap_finish(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + if (d->timeout.tpd) + triton_timer_del(&d->timeout); + + if (d->interval.tpd) + triton_timer_del(&d->interval); + + ppp_unregister_handler(ppp, &d->h); + + return 0; +} + +static void chap_timeout_timer(struct triton_timer_t *t) +{ + struct chap_auth_data_t *d = container_of(t, typeof(*d), timeout); + + if (conf_ppp_verbose) + log_ppp_warn("mschap-v1: timeout\n"); + + if (++d->failure == conf_max_failure) { + if (d->started) + ppp_terminate(d->ppp, TERM_USER_ERROR, 0); + else + ppp_auth_failed(d->ppp, NULL); + } else { + --d->id; + chap_send_challenge(d); + } +} + +static void chap_restart_timer(struct triton_timer_t *t) +{ + struct chap_auth_data_t *d = container_of(t, typeof(*d), interval); + + chap_send_challenge(d); +} + +static int lcp_send_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) +{ + *ptr = MSCHAP_V1; + return 1; +} + +static int lcp_recv_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) +{ + if (*ptr == MSCHAP_V1) + return LCP_OPT_ACK; + return LCP_OPT_NAK; +} + +static void chap_send_failure(struct chap_auth_data_t *ad) +{ + struct chap_failure_t msg = { + .hdr.proto = htons(PPP_CHAP), + .hdr.code = CHAP_FAILURE, + .hdr.id = ad->id, + .hdr.len = htons(sizeof(msg)-1-2), + .message = MSG_FAILURE, + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [MSCHAP-v1 Failure id=%x \"%s\"]\n", msg.hdr.id, MSG_FAILURE); + + ppp_chan_send(ad->ppp,&msg,ntohs(msg.hdr.len)+2); +} + +static void chap_send_success(struct chap_auth_data_t *ad) +{ + struct chap_success_t msg = { + .hdr.proto = htons(PPP_CHAP), + .hdr.code = CHAP_SUCCESS, + .hdr.id = ad->id, + .hdr.len = htons(sizeof(msg)-1-2), + .message = MSG_SUCCESS, + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [MSCHAP-v1 Success id=%x \"%s\"]\n", msg.hdr.id, MSG_SUCCESS); + + ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); +} + +static void chap_send_challenge(struct chap_auth_data_t *ad) +{ + struct chap_challenge_t msg = { + .hdr.proto = htons(PPP_CHAP), + .hdr.code = CHAP_CHALLENGE, + .hdr.id = ++ad->id, + .hdr.len = htons(sizeof(msg) - 2), + .val_size = VALUE_SIZE, + }; + + read(urandom_fd, ad->val, VALUE_SIZE); + memcpy(msg.val, ad->val, VALUE_SIZE); + + if (conf_ppp_verbose) { + log_ppp_info2("send [MSCHAP-v1 Challenge id=%x <", msg.hdr.id); + print_buf(msg.val, VALUE_SIZE); + log_ppp_info2(">]\n"); + } + + ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); + + if (conf_timeout && !ad->timeout.tpd) + triton_timer_add(ad->ppp->ctrl->ctx, &ad->timeout, 0); +} + +static void chap_recv_response(struct chap_auth_data_t *ad, struct chap_hdr_t *hdr) +{ + struct chap_response_t *msg = (struct chap_response_t*)hdr; + char *name; + int r; + + if (ad->timeout.tpd) + triton_timer_del(&ad->timeout); + + if (conf_ppp_verbose) { + log_ppp_info2("recv [MSCHAP-v1 Response id=%x <", msg->hdr.id); + print_buf(msg->lm_hash, 24); + log_ppp_info2(">, <"); + print_buf(msg->nt_hash, 24); + log_ppp_info2(">, F=%i, name=\"", msg->flags); + print_str(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); + log_ppp_info2("\"]\n"); + } + + if (msg->hdr.id != ad->id) { + if (conf_ppp_verbose) + log_ppp_error("mschap-v1: id mismatch\n"); + chap_send_failure(ad); + if (ad->started) + ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); + else + ppp_auth_failed(ad->ppp, NULL); + } + + if (msg->val_size != RESPONSE_VALUE_SIZE) { + log_ppp_error("mschap-v1: incorrect value-size (%i)\n", msg->val_size); + chap_send_failure(ad); + if (ad->started) + ppp_terminate(ad->ppp, TERM_AUTH_ERROR, 0); + else + ppp_auth_failed(ad->ppp, NULL); + } + + name = _strndup(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); + if (!name) { + log_emerg("mschap-v1: out of memory\n"); + if (ad->started) + ppp_terminate(ad->ppp, TERM_NAS_ERROR, 0); + else + ppp_auth_failed(ad->ppp, NULL); + return; + } + + if (conf_any_login) { + chap_send_success(ad); + ad->started = 1; + ppp_auth_successed(ad->ppp, name); + return; + } + + r = pwdb_check(ad->ppp, name, PPP_CHAP, MSCHAP_V1, ad->id, ad->val, VALUE_SIZE, msg->lm_hash, msg->nt_hash, msg->flags); + if (r == PWDB_NO_IMPL) + if (chap_check_response(ad, msg, name)) + r = PWDB_DENIED; + + if (r == PWDB_DENIED) { + chap_send_failure(ad); + if (ad->started) + ppp_terminate(ad->ppp, TERM_AUTH_ERROR, 0); + else + ppp_auth_failed(ad->ppp, name); + _free(name); + } else { + chap_send_success(ad); + if (!ad->started) { + ad->started = 1; + if (conf_interval) + triton_timer_add(ad->ppp->ctrl->ctx, &ad->interval, 0); + ppp_auth_successed(ad->ppp, name); + } else + _free(name); + } +} + +static void des_encrypt(const uint8_t *input, const uint8_t *key, uint8_t *output) +{ + int i, j, parity; + union + { + uint64_t u64; + uint8_t buf[8]; + } p_key; + DES_cblock cb; + DES_cblock res; + DES_key_schedule ks; + + memcpy(p_key.buf, key, 7); + p_key.u64 = bswap_64(p_key.u64); + + for (i = 0; i < 8; i++) { + cb[i] = (((p_key.u64 << (7 * i)) >> 56) & 0xfe); + for( j = 0, parity = 0; j < 7; j++) + if ((cb[i] >> (j + 1)) & 1) + parity++; + cb[i] |= (~parity) & 1; + } + + DES_set_key_checked(&cb, &ks); + memcpy(cb, input, 8); + DES_ecb_encrypt(&cb, &res, &ks, DES_ENCRYPT); + memcpy(output, res, 8); +} + +static int chap_check_response(struct chap_auth_data_t *ad, struct chap_response_t *msg, const char *name) +{ + MD4_CTX md4_ctx; + uint8_t z_hash[21]; + uint8_t nt_hash[24]; + char *passwd; + char *u_passwd; + int i; + + passwd = pwdb_get_passwd(ad->ppp,name); + if (!passwd) { + if (conf_ppp_verbose) + log_ppp_warn("mschap-v1: user not found\n"); + chap_send_failure(ad); + return PWDB_DENIED; + } + + u_passwd = _malloc(strlen(passwd) * 2); + for (i = 0; i< strlen(passwd); i++) { + u_passwd[i * 2] = passwd[i]; + u_passwd[i * 2 + 1] = 0; + } + + memset(z_hash, 0, sizeof(z_hash)); + MD4_Init(&md4_ctx); + MD4_Update(&md4_ctx, u_passwd, strlen(passwd) * 2); + MD4_Final(z_hash, &md4_ctx); + + des_encrypt(ad->val, z_hash, nt_hash); + des_encrypt(ad->val, z_hash + 7, nt_hash + 8); + des_encrypt(ad->val, z_hash + 14, nt_hash + 16); + + set_mppe_keys(ad, z_hash); + + _free(passwd); + _free(u_passwd); + + return memcmp(nt_hash, msg->nt_hash, 24) ? PWDB_DENIED : PWDB_SUCCESS; +} + +static int chap_check(uint8_t *ptr) +{ + return *ptr == MSCHAP_V1; +} + +static void set_mppe_keys(struct chap_auth_data_t *ad, uint8_t *z_hash) +{ + MD4_CTX md4_ctx; + SHA_CTX sha_ctx; + uint8_t digest[20]; + + struct ev_mppe_keys_t ev_mppe = { + .ppp = ad->ppp, + .type = 1 << 2, + .policy = 1, + .recv_key = digest, + .send_key = digest, + }; + + //NtPasswordHashHash + MD4_Init(&md4_ctx); + MD4_Update(&md4_ctx, z_hash, 16); + MD4_Final(digest, &md4_ctx); + + //Get_Start_Key + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, digest, 16); + SHA1_Update(&sha_ctx, digest, 16); + SHA1_Update(&sha_ctx, ad->val, VALUE_SIZE); + SHA1_Final(digest, &sha_ctx); + + triton_event_fire(EV_MPPE_KEYS, &ev_mppe); +} + +static int chap_restart(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + chap_send_challenge(d); + + return 0; +} + +static struct ppp_auth_handler_t chap = { + .name = "MSCHAP-v1", + .init = auth_data_init, + .free = auth_data_free, + .send_conf_req = lcp_send_conf_req, + .recv_conf_req = lcp_recv_conf_req, + .start = chap_start, + .finish = chap_finish, + .check = chap_check, + .restart = chap_restart, +}; + +static void chap_recv(struct ppp_handler_t *h) +{ + struct chap_auth_data_t *d = container_of(h, typeof(*d), h); + struct chap_hdr_t *hdr = (struct chap_hdr_t *)d->ppp->chan_buf; + + if (d->ppp->chan_buf_size < sizeof(*hdr) || ntohs(hdr->len) < HDR_LEN || ntohs(hdr->len) < d->ppp->chan_buf_size - 2) { + log_ppp_warn("mschap-v1: short packet received\n"); + return; + } + + if (hdr->code == CHAP_RESPONSE) + chap_recv_response(d, hdr); + else + log_ppp_warn("mschap-v1: unknown code received %x\n", hdr->code); +} + +static void __init auth_mschap_v1_init() +{ + char *opt; + + opt = conf_get_opt("auth", "timeout"); + if (opt && atoi(opt) > 0) + conf_timeout = atoi(opt); + + opt = conf_get_opt("auth", "interval"); + if (opt && atoi(opt) > 0) + conf_interval = atoi(opt); + + opt = conf_get_opt("auth", "max-failure"); + if (opt && atoi(opt) > 0) + conf_max_failure = atoi(opt); + + opt = conf_get_opt("auth", "any-login"); + if (opt && atoi(opt) > 0) + conf_any_login = 1; + + urandom_fd = open("/dev/urandom", O_RDONLY); + if (urandom_fd < 0) { + log_emerg("mschap-v1: failed to open /dev/urandom: %s\n", strerror(errno)); + return; + } + if (ppp_auth_register_handler(&chap)) + log_emerg("mschap-v1: failed to register handler\n"); +} + diff --git a/accel-pppd/auth/auth_mschap_v2.c b/accel-pppd/auth/auth_mschap_v2.c new file mode 100644 index 0000000..e07c4f7 --- /dev/null +++ b/accel-pppd/auth/auth_mschap_v2.c @@ -0,0 +1,639 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "log.h" +#include "ppp.h" +#include "events.h" +#include "ppp_auth.h" +#include "ppp_lcp.h" +#include "pwdb.h" + +#include "memdebug.h" + +#define MSCHAP_V2 0x81 + +#define CHAP_CHALLENGE 1 +#define CHAP_RESPONSE 2 +#define CHAP_SUCCESS 3 +#define CHAP_FAILURE 4 + +#define VALUE_SIZE 16 +#define RESPONSE_VALUE_SIZE (16+8+24+1) + +#define MSG_FAILURE "E=691 R=0 C=cccccccccccccccccccccccccccccccc V=3 M=Authentication failure" +#define MSG_SUCCESS "S=cccccccccccccccccccccccccccccccccccccccc M=Authentication successed" + +#define HDR_LEN (sizeof(struct chap_hdr_t)-2) + +static int conf_timeout = 5; +static int conf_interval = 0; +static int conf_max_failure = 3; + +static int urandom_fd; + +struct chap_hdr_t +{ + uint16_t proto; + uint8_t code; + uint8_t id; + uint16_t len; +} __attribute__((packed)); + +struct chap_challenge_t +{ + struct chap_hdr_t hdr; + uint8_t val_size; + uint8_t val[VALUE_SIZE]; + char name[0]; +} __attribute__((packed)); + +struct chap_response_t +{ + struct chap_hdr_t hdr; + uint8_t val_size; + uint8_t peer_challenge[16]; + uint8_t reserved[8]; + uint8_t nt_hash[24]; + uint8_t flags; + char name[0]; +} __attribute__((packed)); + +struct chap_failure_t +{ + struct chap_hdr_t hdr; + char message[sizeof(MSG_FAILURE)]; +} __attribute__((packed)); + +struct chap_success_t +{ + struct chap_hdr_t hdr; + char message[sizeof(MSG_SUCCESS)]; +} __attribute__((packed)); + + +struct chap_auth_data_t +{ + struct auth_data_t auth; + struct ppp_handler_t h; + struct ppp_t *ppp; + int id; + uint8_t val[VALUE_SIZE]; + struct triton_timer_t timeout; + struct triton_timer_t interval; + int failure; + int started:1; +}; + +static void chap_send_challenge(struct chap_auth_data_t *ad); +static void chap_recv(struct ppp_handler_t *h); +static int chap_check_response(struct chap_auth_data_t *ad, struct chap_response_t *msg, const char *name); +static void chap_timeout_timer(struct triton_timer_t *t); +static void chap_restart_timer(struct triton_timer_t *t); +static void set_mppe_keys(struct chap_auth_data_t *ad, uint8_t *z_hash, uint8_t *nt_hash); + +static void print_buf(const uint8_t *buf, int size) +{ + int i; + for (i = 0; i < size; i++) + log_ppp_info2("%x", buf[i]); +} + +static void print_str(const char *buf, int size) +{ + int i; + for (i = 0; i < size; i++) + log_ppp_info2("%c", buf[i]); +} + +static struct auth_data_t* auth_data_init(struct ppp_t *ppp) +{ + struct chap_auth_data_t *d = _malloc(sizeof(*d)); + + memset(d, 0, sizeof(*d)); + d->auth.proto = PPP_CHAP; + d->ppp = ppp; + + return &d->auth; +} + +static void auth_data_free(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + if (d->timeout.tpd) + triton_timer_del(&d->timeout); + + if (d->interval.tpd) + triton_timer_del(&d->interval); + + _free(d); +} + +static int chap_start(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + d->h.proto = PPP_CHAP; + d->h.recv = chap_recv; + d->timeout.expire = chap_timeout_timer; + d->timeout.period = conf_timeout * 1000; + d->interval.expire = chap_restart_timer; + d->interval.period = conf_interval * 1000; + + ppp_register_chan_handler(ppp, &d->h); + + chap_send_challenge(d); + + return 0; +} + +static int chap_finish(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + if (d->timeout.tpd) + triton_timer_del(&d->timeout); + + if (d->interval.tpd) + triton_timer_del(&d->interval); + + ppp_unregister_handler(ppp,&d->h); + + return 0; +} + +static void chap_timeout_timer(struct triton_timer_t *t) +{ + struct chap_auth_data_t *d = container_of(t, typeof(*d), timeout); + + if (conf_ppp_verbose) + log_ppp_warn("mschap-v2: timeout\n"); + + if (++d->failure == conf_max_failure) { + if (d->started) + ppp_terminate(d->ppp, TERM_USER_ERROR, 0); + else + ppp_auth_failed(d->ppp, NULL); + } else { + --d->id; + chap_send_challenge(d); + } +} + +static void chap_restart_timer(struct triton_timer_t *t) +{ + struct chap_auth_data_t *d = container_of(t, typeof(*d), interval); + + chap_send_challenge(d); +} + +static int lcp_send_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) +{ + *ptr = MSCHAP_V2; + return 1; +} + +static int lcp_recv_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) +{ + if (*ptr == MSCHAP_V2) + return LCP_OPT_ACK; + return LCP_OPT_NAK; +} + +static void chap_send_failure(struct chap_auth_data_t *ad) +{ + struct chap_failure_t msg = { + .hdr.proto = htons(PPP_CHAP), + .hdr.code = CHAP_FAILURE, + .hdr.id = ad->id, + .hdr.len = htons(sizeof(msg) - 1 - 2), + .message = MSG_FAILURE, + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [MSCHAP-v2 Failure id=%x \"%s\"]\n", msg.hdr.id, MSG_FAILURE); + + ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); +} + +static int generate_response(struct chap_auth_data_t *ad, struct chap_response_t *msg, const char *name, char *authenticator) +{ + MD4_CTX md4_ctx; + SHA_CTX sha_ctx; + char *passwd; + char *u_passwd; + uint8_t pw_hash[MD4_DIGEST_LENGTH]; + uint8_t c_hash[SHA_DIGEST_LENGTH]; + uint8_t response[SHA_DIGEST_LENGTH]; + int i; + + uint8_t magic1[39] = + {0x4D, 0x61, 0x67, 0x69, 0x63, 0x20, 0x73, 0x65, 0x72, 0x76, + 0x65, 0x72, 0x20, 0x74, 0x6F, 0x20, 0x63, 0x6C, 0x69, 0x65, + 0x6E, 0x74, 0x20, 0x73, 0x69, 0x67, 0x6E, 0x69, 0x6E, 0x67, + 0x20, 0x63, 0x6F, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x74}; + uint8_t magic2[41] = + {0x50, 0x61, 0x64, 0x20, 0x74, 0x6F, 0x20, 0x6D, 0x61, 0x6B, + 0x65, 0x20, 0x69, 0x74, 0x20, 0x64, 0x6F, 0x20, 0x6D, 0x6F, + 0x72, 0x65, 0x20, 0x74, 0x68, 0x61, 0x6E, 0x20, 0x6F, 0x6E, + 0x65, 0x20, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6F, + 0x6E}; + + + passwd = pwdb_get_passwd(ad->ppp,name); + if (!passwd) + return -1; + + u_passwd=_malloc(strlen(passwd)*2); + for(i=0; int_hash,24); + SHA1_Update(&sha_ctx,magic1,39); + SHA1_Final(response,&sha_ctx); + + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx,msg->peer_challenge,16); + SHA1_Update(&sha_ctx,ad->val,16); + SHA1_Update(&sha_ctx,name,strlen(name)); + SHA1_Final(c_hash,&sha_ctx); + + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx,response,20); + SHA1_Update(&sha_ctx,c_hash,8); + SHA1_Update(&sha_ctx,magic2,41); + SHA1_Final(response,&sha_ctx); + + for(i=0; i<20; i++) + sprintf(authenticator+i*2,"%02X",response[i]); + + _free(passwd); + _free(u_passwd); + + return 0; +} + +static void chap_send_success(struct chap_auth_data_t *ad, struct chap_response_t *res_msg, const char *authenticator) +{ + struct chap_success_t msg = { + .hdr.proto = htons(PPP_CHAP), + .hdr.code = CHAP_SUCCESS, + .hdr.id = ad->id, + .hdr.len = htons(sizeof(msg) - 1 - 2), + .message = MSG_SUCCESS, + }; + + memcpy(msg.message + 2, authenticator, 40); + + if (conf_ppp_verbose) + log_ppp_info2("send [MSCHAP-v2 Success id=%x \"%s\"]\n", msg.hdr.id, msg.message); + + ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); +} + +static void chap_send_challenge(struct chap_auth_data_t *ad) +{ + struct chap_challenge_t msg = { + .hdr.proto = htons(PPP_CHAP), + .hdr.code = CHAP_CHALLENGE, + .hdr.id = ++ad->id, + .hdr.len = htons(sizeof(msg) - 2), + .val_size = VALUE_SIZE, + }; + + read(urandom_fd, ad->val, VALUE_SIZE); + memcpy(msg.val, ad->val, VALUE_SIZE); + + if (conf_ppp_verbose) { + log_ppp_info2("send [MSCHAP-v2 Challenge id=%x <", msg.hdr.id); + print_buf(msg.val, VALUE_SIZE); + log_ppp_info2(">]\n"); + } + + ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); + + if (conf_timeout && !ad->timeout.tpd) + triton_timer_add(ad->ppp->ctrl->ctx, &ad->timeout, 0); +} + +static void chap_recv_response(struct chap_auth_data_t *ad, struct chap_hdr_t *hdr) +{ + struct chap_response_t *msg = (struct chap_response_t*)hdr; + char *name; + char authenticator[41]; + int r; + + if (ad->timeout.tpd) + triton_timer_del(&ad->timeout); + + if (conf_ppp_verbose) { + log_ppp_info2("recv [MSCHAP-v2 Response id=%x <", msg->hdr.id); + print_buf(msg->peer_challenge,16); + log_ppp_info2(">, <"); + print_buf(msg->nt_hash, 24); + log_ppp_info2(">, F=%i, name=\"", msg->flags); + print_str(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); + log_ppp_info2("\"]\n"); + } + + if (msg->hdr.id != ad->id) { + if (conf_ppp_verbose) + log_ppp_error("mschap-v2: id mismatch\n"); + chap_send_failure(ad); + if (ad->started) + ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); + else + ppp_auth_failed(ad->ppp, NULL); + } + + if (msg->val_size != RESPONSE_VALUE_SIZE) { + log_ppp_error("mschap-v2: incorrect value-size (%i)\n", msg->val_size); + chap_send_failure(ad); + if (ad->started) + ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); + else + ppp_auth_failed(ad->ppp, NULL); + } + + name = _strndup(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); + if (!name) { + log_emerg("mschap-v2: out of memory\n"); + if (ad->started) + ppp_terminate(ad->ppp, TERM_NAS_ERROR, 0); + else + ppp_auth_failed(ad->ppp, NULL); + return; + } + + r = pwdb_check(ad->ppp, name, PPP_CHAP, MSCHAP_V2, ad->id, ad->val, msg->peer_challenge, msg->reserved, msg->nt_hash, msg->flags, authenticator); + + if (r == PWDB_NO_IMPL) { + r = chap_check_response(ad, msg, name); + if (r) + r = PWDB_DENIED; + else if (generate_response(ad, msg, name, authenticator)) + r = PWDB_DENIED; + } + + if (r == PWDB_DENIED) { + chap_send_failure(ad); + if (ad->started) + ppp_terminate(ad->ppp, TERM_AUTH_ERROR, 0); + else + ppp_auth_failed(ad->ppp, name); + _free(name); + } else { + chap_send_success(ad, msg, authenticator); + if (!ad->started) { + ad->started = 1; + if (conf_interval) + triton_timer_add(ad->ppp->ctrl->ctx, &ad->interval, 0); + ppp_auth_successed(ad->ppp, name); + } else + _free(name); + } +} + +static void des_encrypt(const uint8_t *input, const uint8_t *key, uint8_t *output) +{ + int i,j,parity; + union + { + uint64_t u64; + uint8_t buf[8]; + } p_key; + DES_cblock cb; + DES_cblock res; + DES_key_schedule ks; + + memcpy(p_key.buf,key,7); + p_key.u64=bswap_64(p_key.u64); + + for(i=0;i<8;i++) + { + cb[i]=(((p_key.u64<<(7*i))>>56)&0xfe); + for(j=0, parity=0; j<7; j++) + if ((cb[i]>>(j+1))&1) parity++; + cb[i]|=(~parity)&1; + } + + DES_set_key_checked(&cb, &ks); + memcpy(cb,input,8); + DES_ecb_encrypt(&cb,&res,&ks,DES_ENCRYPT); + memcpy(output,res,8); +} + +static int chap_check_response(struct chap_auth_data_t *ad, struct chap_response_t *msg, const char *name) +{ + MD4_CTX md4_ctx; + SHA_CTX sha_ctx; + uint8_t z_hash[21]; + uint8_t c_hash[SHA_DIGEST_LENGTH]; + uint8_t nt_hash[24]; + char *passwd; + char *u_passwd; + int i; + + passwd = pwdb_get_passwd(ad->ppp, name); + if (!passwd) { + if (conf_ppp_verbose) + log_ppp_warn("mschap-v2: user not found\n"); + chap_send_failure(ad); + return -1; + } + + u_passwd=_malloc(strlen(passwd)*2); + for(i=0; ipeer_challenge,16); + SHA1_Update(&sha_ctx,ad->val,16); + SHA1_Update(&sha_ctx,name,strlen(name)); + SHA1_Final(c_hash,&sha_ctx); + + memset(z_hash,0,sizeof(z_hash)); + MD4_Init(&md4_ctx); + MD4_Update(&md4_ctx,u_passwd,strlen(passwd)*2); + MD4_Final(z_hash,&md4_ctx); + + des_encrypt(c_hash,z_hash,nt_hash); + des_encrypt(c_hash,z_hash+7,nt_hash+8); + des_encrypt(c_hash,z_hash+14,nt_hash+16); + + set_mppe_keys(ad, z_hash, msg->nt_hash); + + _free(passwd); + _free(u_passwd); + + return memcmp(nt_hash,msg->nt_hash,24); +} + +static void set_mppe_keys(struct chap_auth_data_t *ad, uint8_t *z_hash, uint8_t *nt_hash) +{ + MD4_CTX md4_ctx; + SHA_CTX sha_ctx; + uint8_t digest[20]; + uint8_t send_key[20]; + uint8_t recv_key[20]; + + uint8_t pad1[40] = + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + + uint8_t pad2[40] = + {0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, + 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, + 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, + 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2}; + + uint8_t magic1[27] = + {0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, + 0x68, 0x65, 0x20, 0x4d, 0x50, 0x50, 0x45, 0x20, 0x4d, + 0x61, 0x73, 0x74, 0x65, 0x72, 0x20, 0x4b, 0x65, 0x79}; + + uint8_t magic2[84] = + {0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69, + 0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, + 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, + 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, 0x6b, 0x65, 0x79, + 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, + 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, 0x69, 0x64, 0x65, + 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, + 0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20, + 0x6b, 0x65, 0x79, 0x2e}; + + uint8_t magic3[84] = + {0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69, + 0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, + 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, + 0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20, + 0x6b, 0x65, 0x79, 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, + 0x65, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, + 0x69, 0x64, 0x65, 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, + 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, + 0x6b, 0x65, 0x79, 0x2e}; + + struct ev_mppe_keys_t ev_mppe = { + .ppp = ad->ppp, + .type = 1 << 2, + .policy = 1, + .recv_key = recv_key, + .send_key = send_key, + }; + + //NtPasswordHashHash + MD4_Init(&md4_ctx); + MD4_Update(&md4_ctx, z_hash, 16); + MD4_Final(digest, &md4_ctx); + + //GetMasterKey + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, digest, 16); + SHA1_Update(&sha_ctx, nt_hash, 24); + SHA1_Update(&sha_ctx, magic1, sizeof(magic1)); + SHA1_Final(digest, &sha_ctx); + + //send key + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, digest, 16); + SHA1_Update(&sha_ctx, pad1, sizeof(pad1)); + SHA1_Update(&sha_ctx, magic3, sizeof(magic2)); + SHA1_Update(&sha_ctx, pad2, sizeof(pad2)); + SHA1_Final(send_key, &sha_ctx); + + //recv key + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, digest, 16); + SHA1_Update(&sha_ctx, pad1, sizeof(pad1)); + SHA1_Update(&sha_ctx, magic2, sizeof(magic3)); + SHA1_Update(&sha_ctx, pad2, sizeof(pad2)); + SHA1_Final(recv_key, &sha_ctx); + + triton_event_fire(EV_MPPE_KEYS, &ev_mppe); +} + +static int chap_check(uint8_t *ptr) +{ + return *ptr == MSCHAP_V2; +} + +static int chap_restart(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + chap_send_challenge(d); + + return 0; +} + +static struct ppp_auth_handler_t chap= +{ + .name = "MSCHAP-v2", + .init = auth_data_init, + .free = auth_data_free, + .send_conf_req = lcp_send_conf_req, + .recv_conf_req = lcp_recv_conf_req, + .start = chap_start, + .finish = chap_finish, + .check = chap_check, + .restart = chap_restart, +}; + +static void chap_recv(struct ppp_handler_t *h) +{ + struct chap_auth_data_t *d = container_of(h, typeof(*d), h); + struct chap_hdr_t *hdr = (struct chap_hdr_t *)d->ppp->chan_buf; + + if (d->ppp->chan_buf_size < sizeof(*hdr) || ntohs(hdr->len) < HDR_LEN || ntohs(hdr->len) < d->ppp->chan_buf_size - 2) { + log_ppp_warn("mschap-v2: short packet received\n"); + return; + } + + if (hdr->code == CHAP_RESPONSE) + chap_recv_response(d, hdr); + else + log_ppp_warn("mschap-v2: unknown code received %x\n",hdr->code); +} + +static void __init auth_mschap_v2_init() +{ + urandom_fd = open("/dev/urandom", O_RDONLY); + if (urandom_fd < 0) { + log_emerg("mschap-v2: failed to open /dev/urandom: %s\n", strerror(errno)); + return; + } + + if (ppp_auth_register_handler(&chap)) + log_emerg("mschap-v2: failed to register handler\n"); +} + diff --git a/accel-pppd/auth/auth_pap.c b/accel-pppd/auth/auth_pap.c new file mode 100644 index 0000000..6909046 --- /dev/null +++ b/accel-pppd/auth/auth_pap.c @@ -0,0 +1,273 @@ +#include +#include +#include +#include + +#include "log.h" +#include "ppp.h" +#include "ppp_auth.h" +#include "ppp_lcp.h" +#include "pwdb.h" + +#include "memdebug.h" + +#define MSG_FAILED "Authentication failed" +#define MSG_SUCCESSED "Authentication successed" + +#define HDR_LEN (sizeof(struct pap_hdr_t)-2) + +#define PAP_REQ 1 +#define PAP_ACK 2 +#define PAP_NAK 3 + +static int conf_timeout = 5; +static int conf_any_login = 0; + +static struct auth_data_t* auth_data_init(struct ppp_t *ppp); +static void auth_data_free(struct ppp_t*, struct auth_data_t*); +static int lcp_send_conf_req(struct ppp_t*, struct auth_data_t*, uint8_t*); +static int lcp_recv_conf_req(struct ppp_t*, struct auth_data_t*, uint8_t*); +static int pap_start(struct ppp_t*, struct auth_data_t*); +static int pap_finish(struct ppp_t*, struct auth_data_t*); +static void pap_recv(struct ppp_handler_t*h); +static void pap_timeout(struct triton_timer_t *t); + +struct pap_auth_data_t +{ + struct auth_data_t auth; + struct ppp_handler_t h; + struct ppp_t *ppp; + int started:1; + struct triton_timer_t timeout; +}; + +struct pap_hdr_t +{ + uint16_t proto; + uint8_t code; + uint8_t id; + uint16_t len; +} __attribute__((packed)); + +struct pap_ack_t +{ + struct pap_hdr_t hdr; + uint8_t msg_len; + char msg[0]; +} __attribute__((packed)); + +static struct ppp_auth_handler_t pap= +{ + .name = "PAP", + .init = auth_data_init, + .free = auth_data_free, + .send_conf_req = lcp_send_conf_req, + .recv_conf_req = lcp_recv_conf_req, + .start = pap_start, + .finish = pap_finish, +}; + +static struct auth_data_t* auth_data_init(struct ppp_t *ppp) +{ + struct pap_auth_data_t *d = _malloc(sizeof(*d)); + + memset(d, 0, sizeof(*d)); + d->auth.proto = PPP_PAP; + d->ppp = ppp; + + return &d->auth; +} + +static void auth_data_free(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct pap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + _free(d); +} + +static int pap_start(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct pap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + d->h.proto = PPP_PAP; + d->h.recv = pap_recv; + d->timeout.expire = pap_timeout; + d->timeout.period = conf_timeout * 1000; + + triton_timer_add(ppp->ctrl->ctx, &d->timeout, 0); + + ppp_register_chan_handler(ppp, &d->h); + + return 0; +} +static int pap_finish(struct ppp_t *ppp, struct auth_data_t *auth) +{ + struct pap_auth_data_t *d = container_of(auth, typeof(*d), auth); + + if (d->timeout.tpd) + triton_timer_del(&d->timeout); + + ppp_unregister_handler(ppp, &d->h); + + return 0; +} + +static void pap_timeout(struct triton_timer_t *t) +{ + struct pap_auth_data_t *d = container_of(t, typeof(*d), timeout); + + if (conf_ppp_verbose) + log_ppp_warn("pap: timeout\n"); + + ppp_auth_failed(d->ppp, NULL); +} + +static int lcp_send_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) +{ + return 0; +} + +static int lcp_recv_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) +{ + return LCP_OPT_ACK; +} + +static void pap_send_ack(struct pap_auth_data_t *p, int id) +{ + uint8_t buf[128]; + struct pap_ack_t *msg = (struct pap_ack_t*)buf; + msg->hdr.proto = htons(PPP_PAP); + msg->hdr.code = PAP_ACK; + msg->hdr.id = id; + msg->hdr.len = htons(HDR_LEN + 1 + sizeof(MSG_SUCCESSED) - 1); + msg->msg_len = sizeof(MSG_SUCCESSED) - 1; + memcpy(msg->msg, MSG_SUCCESSED, sizeof(MSG_SUCCESSED)); + + if (conf_ppp_verbose) + log_ppp_info2("send [PAP AuthAck id=%x \"%s\"]\n", id, MSG_SUCCESSED); + + ppp_chan_send(p->ppp, msg, ntohs(msg->hdr.len) + 2); +} + +static void pap_send_nak(struct pap_auth_data_t *p, int id) +{ + uint8_t buf[128]; + struct pap_ack_t *msg = (struct pap_ack_t*)buf; + msg->hdr.proto = htons(PPP_PAP); + msg->hdr.code = PAP_NAK; + msg->hdr.id = id; + msg->hdr.len = htons(HDR_LEN + 1 + sizeof(MSG_FAILED) - 1); + msg->msg_len = sizeof(MSG_FAILED) - 1; + memcpy(msg->msg, MSG_FAILED, sizeof(MSG_FAILED)); + + if (conf_ppp_verbose) + log_ppp_info2("send [PAP AuthNak id=%x \"%s\"]\n", id, MSG_FAILED); + + ppp_chan_send(p->ppp, msg, ntohs(msg->hdr.len) + 2); +} + +static int pap_recv_req(struct pap_auth_data_t *p, struct pap_hdr_t *hdr) +{ + int ret, r; + char *peer_id; + char *passwd; + char *passwd2; + int peer_id_len; + int passwd_len; + uint8_t *ptr = (uint8_t*)(hdr + 1); + + if (p->timeout.tpd) + triton_timer_del(&p->timeout); + + if (conf_ppp_verbose) + log_ppp_info2("recv [PAP AuthReq id=%x]\n", hdr->id); + + peer_id_len = *(uint8_t*)ptr; ptr++; + if (peer_id_len > ntohs(hdr->len) - sizeof(*hdr) + 2 - 1) { + log_ppp_warn("PAP: short packet received\n"); + return -1; + } + peer_id = (char*)ptr; ptr += peer_id_len; + + passwd_len = *(uint8_t*)ptr; ptr++; + if (passwd_len > ntohs(hdr->len) - sizeof(*hdr ) + 2 - 2 - peer_id_len) { + log_ppp_warn("PAP: short packet received\n"); + return -1; + } + + peer_id = _strndup((const char*)peer_id, peer_id_len); + + if (conf_any_login) { + pap_send_ack(p, hdr->id); + p->started = 1; + ppp_auth_successed(p->ppp, peer_id); + return 0; + } + + passwd = _strndup((const char*)ptr, passwd_len); + + r = pwdb_check(p->ppp, peer_id, PPP_PAP, passwd); + if (r == PWDB_NO_IMPL) { + passwd2 = pwdb_get_passwd(p->ppp, peer_id); + if (!passwd2 || strcmp(passwd2, passwd)) + r = PWDB_DENIED; + else + r = PWDB_SUCCESS; + _free(passwd2); + } + if (r == PWDB_DENIED) { + if (conf_ppp_verbose) + log_ppp_warn("PAP: authentication error\n"); + pap_send_nak(p, hdr->id); + if (p->started) + ppp_terminate(p->ppp, TERM_AUTH_ERROR, 0); + else + ppp_auth_failed(p->ppp, peer_id); + ret=-1; + _free(peer_id); + } else { + pap_send_ack(p, hdr->id); + if (!p->started) { + p->started = 1; + ppp_auth_successed(p->ppp, peer_id); + } + ret = 0; + } + + _free(passwd); + + return ret; +} + +static void pap_recv(struct ppp_handler_t *h) +{ + struct pap_auth_data_t *d = container_of(h, typeof(*d), h); + struct pap_hdr_t *hdr = (struct pap_hdr_t *)d->ppp->chan_buf; + + if (d->ppp->chan_buf_size < sizeof(*hdr) || ntohs(hdr->len) < HDR_LEN || ntohs(hdr->len) < d->ppp->chan_buf_size - 2) { + log_ppp_warn("PAP: short packet received\n"); + return; + } + + if (hdr->code == PAP_REQ) + pap_recv_req(d, hdr); + else { + log_ppp_warn("PAP: unknown code received %x\n",hdr->code); + } +} + +static void __init auth_pap_init() +{ + char *opt; + + opt = conf_get_opt("auth", "timeout"); + if (opt && atoi(opt) > 0) + conf_timeout = atoi(opt); + + opt = conf_get_opt("auth", "any-login"); + if (opt && atoi(opt) > 0) + conf_any_login = 1; + + ppp_auth_register_handler(&pap); +} + diff --git a/accel-pppd/cli/CMakeLists.txt b/accel-pppd/cli/CMakeLists.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/accel-pppd/cli/CMakeLists.txt @@ -0,0 +1 @@ + diff --git a/accel-pppd/cli/cli.c b/accel-pppd/cli/cli.c new file mode 100644 index 0000000..5009a74 --- /dev/null +++ b/accel-pppd/cli/cli.c @@ -0,0 +1,227 @@ +#include +#include +#include +#include + +#include "triton.h" + +#include "cli.h" +#include "cli_p.h" +#include "log.h" +#include "events.h" + +#include "memdebug.h" + +#define MAX_CMD_ITEMS 100 +#define MSG_SYNTAX_ERROR "syntax error\r\n" +#define MSG_INVAL_ERROR "invalid argument\r\n" +#define MSG_UNKNOWN_CMD "command unknown\r\n" + +char *conf_cli_passwd; +static const char *def_cli_prompt = "accel-ppp"; +char *conf_cli_prompt; + +static LIST_HEAD(simple_cmd_list); +static LIST_HEAD(regexp_cmd_list); + +void __export cli_register_simple_cmd(struct cli_simple_cmd_t *cmd) +{ + list_add_tail(&cmd->entry, &simple_cmd_list); +} + +void __export cli_register_simple_cmd2( + int (*exec)(const char *cmd, char * const *fields, int fields_cnt, void *client), + void (*help)(char * const *fields, int fields_cnt, void *client), + int hdr_len, + ... + ) +{ + struct cli_simple_cmd_t *c; + int i; + va_list ap; + + va_start(ap, hdr_len); + + c = malloc(sizeof(*c)); + memset(c, 0, sizeof(*c)); + + c->exec = exec; + c->help = help; + c->hdr_len = hdr_len; + c->hdr = malloc(hdr_len * sizeof(void*)); + + for (i = 0; i < hdr_len; i++) + c->hdr[i] = va_arg(ap, char *); + + list_add_tail(&c->entry, &simple_cmd_list); +} + +void __export cli_register_regexp_cmd(struct cli_regexp_cmd_t *cmd) +{ + int err; + cmd->re = pcre_compile2(cmd->pattern, cmd->options, &err, NULL, NULL, NULL); + if (!cmd->re) { + log_emerg("cli: failed to compile regexp %s: %i\n", cmd->pattern, err); + _exit(EXIT_FAILURE); + } + list_add_tail(&cmd->entry, &simple_cmd_list); +} + +int __export cli_send(void *client, const char *data) +{ + struct cli_client_t *cln = (struct cli_client_t *)client; + + return cln->send(cln, data, strlen(data)); +} + +int __export cli_sendv(void *client, const char *fmt, ...) +{ + struct cli_client_t *cln = (struct cli_client_t *)client; + int r; + + va_list ap; + va_start(ap, fmt); + r = cln->sendv(cln, fmt, ap); + va_end(ap); + + return r; +} + + +static char *skip_word(char *ptr) +{ + for(; *ptr; ptr++) + if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') + break; + return ptr; +} +static char *skip_space(char *ptr) +{ + for(; *ptr; ptr++) + if (*ptr != ' ' && *ptr != '\t') + break; + return ptr; +} +static int split(char *buf, char **ptr) +{ + int i; + + ptr[0] = buf; + + for (i = 1; i <= MAX_CMD_ITEMS; i++) { + buf = skip_word(buf); + if (!*buf) + return i; + + *buf = 0; + + buf = skip_space(buf + 1); + if (!*buf) + return i; + + ptr[i] = buf; + } + + buf = skip_word(buf); + *buf = 0; + + return i; +} + +int cli_process_cmd(struct cli_client_t *cln) +{ + struct cli_simple_cmd_t *cmd1; + struct cli_regexp_cmd_t *cmd2; + char *f[MAX_CMD_ITEMS]; + int r, i, n, found = 0; + + n = split((char *)cln->cmdline, f); + + if (n >= 1 && !strcmp(f[0], "help")) { + list_for_each_entry(cmd1, &simple_cmd_list, entry) + if (cmd1->help) + cmd1->help(f, n, cln); + + list_for_each_entry(cmd2, ®exp_cmd_list, entry) + if (cmd2->help) + cmd1->help(f, n, cln); + + return 0; + } + + list_for_each_entry(cmd1, &simple_cmd_list, entry) { + if (cmd1->hdr_len && n >= cmd1->hdr_len) { + for (i = 0; i < cmd1->hdr_len; i++) { + if (strcmp(cmd1->hdr[i], f[i])) + break; + } + if (i < cmd1->hdr_len) + continue; + r = cmd1->exec((char *)cln->cmdline, f, n, cln); + switch (r) { + case CLI_CMD_EXIT: + cln->disconnect(cln); + case CLI_CMD_FAILED: + return -1; + case CLI_CMD_SYNTAX: + cli_send(cln, MSG_SYNTAX_ERROR); + return 0; + case CLI_CMD_INVAL: + cli_send(cln, MSG_INVAL_ERROR); + return 0; + case CLI_CMD_OK: + found = 1; + } + } + } + + list_for_each_entry(cmd2, ®exp_cmd_list, entry) { + r = cmd2->exec((char *)cln->cmdline, cln); + switch (r) { + case CLI_CMD_EXIT: + cln->disconnect(cln); + case CLI_CMD_FAILED: + return 0; + case CLI_CMD_SYNTAX: + cli_send(cln, MSG_SYNTAX_ERROR); + return 0; + case CLI_CMD_OK: + found = 1; + } + } + + if (!found) { + if (cli_send(cln, MSG_UNKNOWN_CMD)) + return -1; + } + + return 0; +} + +static void load_config(void) +{ + const char *opt; + + if (conf_cli_passwd) + _free(conf_cli_passwd); + opt = conf_get_opt("cli", "password"); + if (opt) + conf_cli_passwd = _strdup(opt); + else + conf_cli_passwd = NULL; + + if (conf_cli_prompt && conf_cli_prompt != def_cli_prompt) + _free(conf_cli_prompt); + opt = conf_get_opt("cli", "prompt"); + if (opt) + conf_cli_prompt = _strdup(opt); + else + conf_cli_prompt = (char *)def_cli_prompt; +} + +static void __init init(void) +{ + load_config(); + + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); +} diff --git a/accel-pppd/cli/cli.h b/accel-pppd/cli/cli.h new file mode 100644 index 0000000..cdceb2f --- /dev/null +++ b/accel-pppd/cli/cli.h @@ -0,0 +1,48 @@ +#ifndef __CLI_H +#define __CLI_H + +#include +#include + +#define CLI_CMD_OK 0 +#define CLI_CMD_FAILED -1 +#define CLI_CMD_EXIT -2 +#define CLI_CMD_SYNTAX 1 +#define CLI_CMD_INVAL 2 + +struct cli_simple_cmd_t +{ + struct list_head entry; + int hdr_len; + const char **hdr; + int (*exec)(const char *cmd, char * const *fields, int fields_cnt, void *client); + void (*help)(char * const *fields, int field_cnt, void *client); +}; + +struct cli_regexp_cmd_t +{ + struct list_head entry; + pcre *re; + const char *pattern; + int options; + int (*exec)(const char *cmd, void *client); + int (*help)(char * const *fields, int field_cnt, void *client); +}; + +struct ppp_t; + +void cli_register_simple_cmd(struct cli_simple_cmd_t *cmd); +void cli_register_simple_cmd2( + int (*exec)(const char *cmd, char * const *fields, int fields_cnt, void *client), + void (*help)(char * const *fields, int fields_cnt, void *client), + int hdr_len, + ... + ); +void cli_register_regexp_cmd(struct cli_regexp_cmd_t *cmd); +void cli_show_ses_register(const char *name, const char *desc, void (*print)(const struct ppp_t *ppp, char *buf)); + +int cli_send(void *client, const char *data); +int cli_sendv(void *client, const char *fmt, ...); + +#endif + diff --git a/accel-pppd/cli/cli_p.h b/accel-pppd/cli/cli_p.h new file mode 100644 index 0000000..0fcba30 --- /dev/null +++ b/accel-pppd/cli/cli_p.h @@ -0,0 +1,22 @@ +#ifndef __CLI_P_H +#define __CLI_P_H + +#include + +#include "triton.h" + +struct cli_client_t +{ + uint8_t *cmdline; + int (*send)(struct cli_client_t *, const void *buf, int size); + int (*sendv)(struct cli_client_t *, const char *fmt, va_list ap); + void (*disconnect)(struct cli_client_t *); +}; + +int cli_process_cmd(struct cli_client_t *cln); + +extern char *conf_cli_passwd; +extern char *conf_cli_prompt; + +#endif + diff --git a/accel-pppd/cli/show_sessions.c b/accel-pppd/cli/show_sessions.c new file mode 100644 index 0000000..90aeb3f --- /dev/null +++ b/accel-pppd/cli/show_sessions.c @@ -0,0 +1,434 @@ +#include +#include +#include +#include +#include +#include + +#include "triton.h" +#include "events.h" +#include "ppp.h" +#include "cli.h" +#include "utils.h" +#include "log.h" +#include "memdebug.h" + +#define CELL_SIZE 128 +#define DEF_COLUMNS "ifname,username,calling-sid,ip,rate-limit,type,state,uptime" + +struct column_t +{ + struct list_head entry; + const char *name; + const char *desc; + void (*print)(const struct ppp_t *ppp, char *buf); +}; + +struct col_t +{ + struct list_head entry; + struct column_t *column; + int width; +}; + +struct row_t +{ + struct list_head entry; + char *match_key; + char *order_key; + struct list_head cell_list; +}; + +struct cell_t +{ + struct list_head entry; + struct col_t *col; + char buf[CELL_SIZE + 1]; +}; + +static LIST_HEAD(col_list); + +void __export cli_show_ses_register(const char *name, const char *desc, void (*print)(const struct ppp_t *ppp, char *buf)) +{ + struct column_t *c = malloc(sizeof(*c)); + c->name = name; + c->desc = desc; + c->print = print; + list_add_tail(&c->entry, &col_list); +} + +static void show_ses_help(char * const *f, int f_cnt, void *cli) +{ + struct column_t *col; + char buf[129]; + + cli_send(cli, "show sessions [columns] [order ] [match ] - shows sessions\r\n"); + cli_send(cli, "\tcolumns:\r\n"); + + list_for_each_entry(col, &col_list, entry) { + snprintf(buf, 128, "\t\t%s - %s\r\n", col->name, col->desc); + cli_send(cli, buf); + } +} + +static struct column_t *find_column(const char *name) +{ + struct column_t *col; + + list_for_each_entry(col, &col_list, entry) { + if (strcmp(col->name, name)) + continue; + return col; + } + + return NULL; +} + +static void free_row(struct row_t *row) +{ + struct cell_t *cell; + + while (!list_empty(&row->cell_list)) { + cell = list_entry(row->cell_list.next, typeof(*cell), entry); + list_del(&cell->entry); + _free(cell); + } + + _free(row); +} + +static void insert_row(struct list_head *list, struct row_t *row) +{ + struct row_t *row2, *row3; + + row3 = NULL; + list_for_each_entry(row2, list, entry) { + if (strcmp(row->order_key, row2->order_key) <= 0) { + row3 = row2; + break; + } + } + if (row3) + list_add_tail(&row->entry, &row3->entry); + else + list_add_tail(&row->entry, list); +} + +static int show_ses_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + char *columns = NULL; + struct column_t *match_key = NULL; + char *match_pattern = NULL; + struct column_t *order_key = NULL; + pcre *re = NULL; + const char *pcre_err; + int pcre_offset; + struct column_t *column; + struct col_t *col; + struct row_t *row; + struct cell_t *cell; + char *ptr1, *ptr2; + int i, n, total_width, def_columns = 0; + struct ppp_t *ppp; + char *buf = NULL; + LIST_HEAD(c_list); + LIST_HEAD(r_list); + LIST_HEAD(t_list); + + for (i = 2; i < f_cnt; i++) { + if (!strcmp(f[i], "order")) { + if (i == f_cnt - 1) + return CLI_CMD_SYNTAX; + order_key = find_column(f[++i]); + if (!order_key) { + cli_sendv(cli, "unknown column %s\r\n", f[i]); + return CLI_CMD_OK; + } + } else if (!strcmp(f[i], "match")) { + if (i == f_cnt - 2) + return CLI_CMD_SYNTAX; + match_key = find_column(f[++i]); + if (!match_key) { + cli_sendv(cli, "unknown column %s\r\n", f[i]); + return CLI_CMD_OK; + } + match_pattern = f[++i]; + } else if (!columns) + columns = f[i]; + else + return CLI_CMD_SYNTAX; + } + + if (match_key) { + re = pcre_compile2(match_pattern, 0, NULL, &pcre_err, &pcre_offset, NULL); + if (!re) { + cli_sendv(cli, "match: %s at %i\r\n", pcre_err, pcre_offset); + return CLI_CMD_OK; + } + } + + if (!columns) { + columns = DEF_COLUMNS; + def_columns = 1; + } + + columns = _strdup(columns); + ptr1 = columns; + while (1) { + ptr2 = strchr(ptr1, ','); + if (ptr2) + *ptr2 = 0; + column = find_column(ptr1); + if (column) { + col = _malloc(sizeof(*col)); + col->column = column; + col->width = strlen(column->name); + list_add_tail(&col->entry, &c_list); + } else { + if (!def_columns) { + cli_sendv(cli, "unknown column %s\r\n", ptr1); + _free(columns); + goto out; + } + } + if (!ptr2) + break; + ptr1 = ptr2 + 1; + } + _free(columns); + + pthread_rwlock_rdlock(&ppp_lock); + list_for_each_entry(ppp, &ppp_list, entry) { + row = _malloc(sizeof(*row)); + if (!row) + goto oom; + memset(row, 0, sizeof(*row)); + INIT_LIST_HEAD(&row->cell_list); + if (match_key || order_key) + list_add_tail(&row->entry, &t_list); + else + list_add_tail(&row->entry, &r_list); + list_for_each_entry(col, &c_list, entry) { + cell = _malloc(sizeof(*cell)); + if (!cell) + goto oom; + cell->col = col; + list_add_tail(&cell->entry, &row->cell_list); + col->column->print(ppp, cell->buf); + n = strlen(cell->buf); + if (n > col->width) + col->width = n; + if (col->column == order_key) + row->order_key = cell->buf; + if (col->column == match_key) + row->match_key = cell->buf; + } + } + pthread_rwlock_unlock(&ppp_lock); + + if (order_key || match_key) { + while(!list_empty(&t_list)) { + row = list_entry(t_list.next, typeof(*row), entry); + list_del(&row->entry); + if (match_key) { + if (pcre_exec(re, NULL, row->match_key, strlen(row->match_key), 0, 0, NULL, 0) < 0) { + free_row(row); + continue; + } + } + if (order_key) + insert_row(&r_list, row); + else + list_add_tail(&row->entry, &r_list); + } + } + + total_width = -1; + list_for_each_entry(col, &c_list, entry) + total_width += col->width + 3; + + buf = _malloc(total_width + 3); + if (!buf) + goto oom; + + ptr1 = buf; + list_for_each_entry(col, &c_list, entry) { + n = strlen(col->column->name); + if (col->width > n + 1) { + ptr2 = ptr1; + memset(ptr1, ' ', col->width/2 - n/2 + 1); + ptr1 += col->width/2 - n/2 + 1; + sprintf(ptr1, "%s", col->column->name); + ptr1 = strchr(ptr1, 0); + memset(ptr1, ' ', col->width + 2 - (ptr1 - ptr2)); + ptr1 += col->width + 2 - (ptr1 - ptr2); + *ptr1 = '|'; + ptr1++; + } else if (col->width > n) { + sprintf(ptr1, " %s |", col->column->name); + ptr1 = strchr(ptr1, 0); + } else { + sprintf(ptr1, " %s |", col->column->name); + ptr1 = strchr(ptr1, 0); + } + } + + strcpy(ptr1 - 1, "\r\n"); + cli_send(cli, buf); + + ptr1 = buf; + list_for_each_entry(col, &c_list, entry) { + memset(ptr1, '-', col->width + 2); + ptr1 += col->width + 2; + *ptr1 = '+'; + ptr1++; + } + + strcpy(ptr1 - 1, "\r\n"); + cli_send(cli, buf); + + while (!list_empty(&r_list)) { + row = list_entry(r_list.next, typeof(*row), entry); + ptr1 = buf; + list_for_each_entry(cell, &row->cell_list, entry) { + ptr2 = ptr1; + sprintf(ptr1, " %s ", cell->buf); + ptr1 = strchr(ptr1, 0); + n = ptr1 - ptr2; + if (n - 2 < cell->col->width) { + memset(ptr1, ' ', cell->col->width + 2 - (ptr1 - ptr2)); + ptr1 += cell->col->width + 2 - (ptr1 - ptr2); + } + *ptr1 = '|'; + ptr1++; + } + strcpy(ptr1 - 1, "\r\n"); + cli_send(cli, buf); + list_del(&row->entry); + free_row(row); + } + + _free(buf); + +out: + while (!list_empty(&c_list)) { + col = list_entry(c_list.next, typeof(*col), entry); + list_del(&col->entry); + _free(col); + } + + if (re) + pcre_free(re); + + return CLI_CMD_OK; + +oom: + if (buf) + _free(buf); + + while (!list_empty(&t_list)) { + row = list_entry(t_list.next, typeof(*row), entry); + list_del(&row->entry); + free_row(row); + } + cli_send(cli, "out of memory"); + goto out; +} + +static void print_ifname(const struct ppp_t *ppp, char *buf) +{ + snprintf(buf, CELL_SIZE, "%s", ppp->ifname); +} + +static void print_username(const struct ppp_t *ppp, char *buf) +{ + if (ppp->username) + snprintf(buf, CELL_SIZE, "%s", ppp->username); +} + +static void print_ip(const struct ppp_t *ppp, char *buf) +{ + char str[17]; + u_inet_ntoa(ppp->peer_ipaddr, str); + sprintf(buf, "%s", str); +} + +static void print_type(const struct ppp_t *ppp, char *buf) +{ + snprintf(buf, CELL_SIZE, "%s", ppp->ctrl->name); +} + +static void print_state(const struct ppp_t *ppp, char *buf) +{ + char *state; + switch (ppp->state) { + case PPP_STATE_STARTING: + state = "start"; + break; + case PPP_STATE_ACTIVE: + state = "active"; + break; + case PPP_STATE_FINISHING: + state = "finish"; + break; + default: + state = "unk"; + } + sprintf(buf, "%s", state); +} + +static void print_uptime(const struct ppp_t *ppp, char *buf) +{ + time_t uptime; + int day,hour,min,sec; + char time_str[14]; + + if (ppp->stop_time) + uptime = ppp->stop_time - ppp->start_time; + else { + time(&uptime); + uptime -= ppp->start_time; + } + + day = uptime/ (24*60*60); uptime %= (24*60*60); + hour = uptime / (60*60); uptime %= (60*60); + min = uptime / 60; + sec = uptime % 60; + if (day) + snprintf(time_str, 13, "%i.%02i:%02i:%02i", day, hour, min, sec); + else + snprintf(time_str, 13, "%02i:%02i:%02i", hour, min, sec); + + sprintf(buf, "%s", time_str); +} + +static void print_calling_sid(const struct ppp_t *ppp, char *buf) +{ + snprintf(buf, CELL_SIZE, "%s", ppp->ctrl->calling_station_id); +} + +static void print_called_sid(const struct ppp_t *ppp, char *buf) +{ + snprintf(buf, CELL_SIZE, "%s", ppp->ctrl->called_station_id); +} + +static void print_sid(const struct ppp_t *ppp, char *buf) +{ + snprintf(buf, CELL_SIZE, "%s", ppp->sessionid); +} + +void __init init(void) +{ + cli_register_simple_cmd2(show_ses_exec, show_ses_help, 2, "show", "sessions"); + + cli_show_ses_register("ifname", "interface name", print_ifname); + cli_show_ses_register("username", "user name", print_username); + cli_show_ses_register("ip", "IP address", print_ip); + cli_show_ses_register("type", "VPN type", print_type); + cli_show_ses_register("state", "state of session", print_state); + cli_show_ses_register("uptime", "uptime", print_uptime); + cli_show_ses_register("calling-sid", "calling station id", print_calling_sid); + cli_show_ses_register("called-sid", "called station id", print_called_sid); + cli_show_ses_register("sid", "session id", print_sid); +} + diff --git a/accel-pppd/cli/std_cmd.c b/accel-pppd/cli/std_cmd.c new file mode 100644 index 0000000..a49bbce --- /dev/null +++ b/accel-pppd/cli/std_cmd.c @@ -0,0 +1,324 @@ +#include +#include +#include +#include +#include +#include + +#include "triton.h" +#include "events.h" +#include "ppp.h" +#include "cli.h" +#include "utils.h" +#include "log.h" +#include "memdebug.h" + +static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) +{ + time_t dt; + int day,hour; + char statm_fname[128]; + FILE *f; + unsigned long vmsize = 0, vmrss = 0; + unsigned long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; + + sprintf(statm_fname, "/proc/%i/statm", getpid()); + f = fopen(statm_fname, "r"); + if (f) { + fscanf(f, "%lu %lu", &vmsize, &vmrss); + fclose(f); + } + + time(&dt); + dt -= triton_stat.start_time; + day = dt / (60 * 60 * 24); + dt %= 60 * 60 * 24; + hour = dt / (60 * 60); + dt %= 60 * 60; + + cli_sendv(client, "uptime: %i.%02i:%02i:%02i\r\n", day, hour, dt / 60, dt % 60); + cli_sendv(client, "cpu: %i%%\r\n", triton_stat.cpu); + cli_sendv(client, "mem(rss/virt): %lu/%lu kB\r\n", vmrss * page_size_kb, vmsize * page_size_kb); + cli_send(client, "core:\r\n"); + cli_sendv(client, " mempool_allocated: %u\r\n", triton_stat.mempool_allocated); + cli_sendv(client, " mempool_available: %u\r\n", triton_stat.mempool_available); + cli_sendv(client, " thread_count: %u\r\n", triton_stat.thread_count); + cli_sendv(client, " thread_active: %u\r\n", triton_stat.thread_active); + cli_sendv(client, " context_count: %u\r\n", triton_stat.context_count); + cli_sendv(client, " context_sleeping: %u\r\n", triton_stat.context_sleeping); + cli_sendv(client, " context_pending: %u\r\n", triton_stat.context_pending); + cli_sendv(client, " md_handler_count: %u\r\n", triton_stat.md_handler_count); + cli_sendv(client, " md_handler_pending: %u\r\n", triton_stat.md_handler_pending); + cli_sendv(client, " timer_count: %u\r\n", triton_stat.timer_count); + cli_sendv(client, " timer_pending: %u\r\n", triton_stat.timer_pending); + +//=========== + cli_send(client, "ppp:\r\n"); + cli_sendv(client, " staring: %u\r\n", ppp_stat.starting); + cli_sendv(client, " active: %u\r\n", ppp_stat.active); + cli_sendv(client, " finishing: %u\r\n", ppp_stat.finishing); + + return CLI_CMD_OK; +} + +static void show_stat_help(char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "show stat - shows various statistics information\r\n"); +} +//============================= + +static int exit_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) +{ + return CLI_CMD_EXIT; +} + +static void exit_help(char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "exit - exit cli\r\n"); +} + +//============================= + +static void ppp_terminate_soft(struct ppp_t *ppp) +{ + ppp_terminate(ppp, TERM_NAS_REQUEST, 0); +} + +static void ppp_terminate_hard(struct ppp_t *ppp) +{ + ppp_terminate(ppp, TERM_NAS_REQUEST, 1); +} + +static int terminate_exec1(char * const *f, int f_cnt, void *cli) +{ + struct ppp_t *ppp; + int hard = 0; + pcre *re; + const char *pcre_err; + int pcre_offset; + + if (f_cnt == 5) { + if (!strcmp(f[4], "hard")) + hard = 1; + else if (strcmp(f[4], "soft")) + return CLI_CMD_SYNTAX; + } else if (f_cnt != 4) + return CLI_CMD_SYNTAX; + + re = pcre_compile2(f[3], 0, NULL, &pcre_err, &pcre_offset, NULL); + if (!re) { + cli_sendv(cli, "match: %s at %i\r\n", pcre_err, pcre_offset); + return CLI_CMD_OK; + } + + pthread_rwlock_rdlock(&ppp_lock); + list_for_each_entry(ppp, &ppp_list, entry) { + if (pcre_exec(re, NULL, ppp->username, strlen(ppp->username), 0, 0, NULL, 0) < 0) + continue; + if (hard) + triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_hard, ppp); + else + triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_soft, ppp); + } + pthread_rwlock_unlock(&ppp_lock); + + pcre_free(re); + + return CLI_CMD_OK; +} + +static int terminate_exec2(int key, char * const *f, int f_cnt, void *cli) +{ + struct ppp_t *ppp; + int hard = 0; + in_addr_t ipaddr = 0; + + if (f_cnt == 4) { + if (!strcmp(f[3], "hard")) + hard = 1; + else if (strcmp(f[3], "soft")) + return CLI_CMD_SYNTAX; + } else if (f_cnt != 3) + return CLI_CMD_SYNTAX; + + if (key == 1) + ipaddr = inet_addr(f[2]); + + pthread_rwlock_rdlock(&ppp_lock); + list_for_each_entry(ppp, &ppp_list, entry) { + switch (key) { + case 0: + if (strcmp(ppp->username, f[2])) + continue; + break; + case 1: + if (ppp->peer_ipaddr != ipaddr) + continue; + break; + case 2: + if (strcmp(ppp->ctrl->calling_station_id, f[2])) + continue; + break; + case 3: + if (strcmp(ppp->sessionid, f[2])) + continue; + break; + case 4: + if (strcmp(ppp->ifname, f[2])) + continue; + break; + } + if (hard) + triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_hard, ppp); + else + triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_soft, ppp); + break; + } + pthread_rwlock_unlock(&ppp_lock); + + return CLI_CMD_OK; +} + +static int terminate_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) +{ + struct ppp_t *ppp; + int hard = 0; + + if (fields_cnt == 1) + return CLI_CMD_SYNTAX; + + if (!strcmp(fields[1], "match") && fields_cnt > 3 && !strcmp(fields[2], "username")) + return terminate_exec1(fields, fields_cnt, client); + else if (!strcmp(fields[1], "username")) + return terminate_exec2(0, fields, fields_cnt, client); + else if (!strcmp(fields[1], "ip")) + return terminate_exec2(1, fields, fields_cnt, client); + else if (!strcmp(fields[1], "csid")) + return terminate_exec2(2, fields, fields_cnt, client); + else if (!strcmp(fields[1], "sid")) + return terminate_exec2(3, fields, fields_cnt, client); + else if (!strcmp(fields[1], "if")) + return terminate_exec2(4, fields, fields_cnt, client); + else if (strcmp(fields[1], "all")) + return CLI_CMD_SYNTAX; + + if (fields_cnt == 3) { + if (!strcmp(fields[2], "hard")) + hard = 1; + else if (strcmp(fields[2], "soft")) + return CLI_CMD_SYNTAX; + } else if (fields_cnt != 2) + return CLI_CMD_SYNTAX; + + pthread_rwlock_rdlock(&ppp_lock); + list_for_each_entry(ppp, &ppp_list, entry) { + if (hard) + triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_hard, ppp); + else + triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_soft, ppp); + } + pthread_rwlock_unlock(&ppp_lock); + + return CLI_CMD_OK; +} + +static void terminate_help(char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "terminate if [soft|hard]- terminate session by interface name\r\n"); + cli_send(client, "\t[match] username [soft|hard]- terminate session by username\r\n"); + cli_send(client, "\tip [soft|hard]- terminate session by ip address\r\n"); + cli_send(client, "\tcsid [soft|hard]- terminate session by calling station id\r\n"); + cli_send(client, "\tsid [soft|hard]- terminate session by session id\r\n"); + cli_send(client, "\tall [soft|hard]- terminate all sessions\r\n"); +} + +//============================= + +static void shutdown_help(char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "shutdown [soft|hard|cancel]- shutdown daemon\r\n"); + cli_send(client, "\t\tdefault action - send termination signals to all clients and wait everybody disconnects\r\n"); + cli_send(client, "\t\tsoft - wait until all clients disconnects, don't accept new connections\r\n"); + cli_send(client, "\t\thard - shutdown now, don't wait anything\r\n"); + cli_send(client, "\t\tcancel - cancel 'shutdown soft' and return to normal operation\r\n"); +} + +static void ppp_terminate_soft2(struct ppp_t *ppp) +{ + ppp_terminate(ppp, TERM_NAS_REBOOT, 0); +} + +static void ppp_terminate_hard2(struct ppp_t *ppp) +{ + ppp_terminate(ppp, TERM_NAS_REBOOT, 1); +} + +static int shutdown_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + int hard = 0; + struct ppp_t *ppp; + + if (f_cnt == 2) { + if (!strcmp(f[1], "soft")) { + ppp_shutdown_soft(); + return CLI_CMD_OK; + } else if (!strcmp(f[1], "hard")) + hard = 1; + else if (!strcmp(f[1], "cancel")) { + ppp_shutdown = 0; + return CLI_CMD_OK; + } else + return CLI_CMD_SYNTAX; + } + + ppp_shutdown_soft(); + + pthread_rwlock_rdlock(&ppp_lock); + list_for_each_entry(ppp, &ppp_list, entry) { + if (hard) + triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_hard2, ppp); + else + triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_soft2, ppp); + } + pthread_rwlock_unlock(&ppp_lock); + + return CLI_CMD_OK; +} + +//========================== +static int conf_reload_res; +static struct triton_context_t *conf_reload_ctx; +static void conf_reload_notify(int r) +{ + if (!r) + triton_event_fire(EV_CONFIG_RELOAD, NULL); + conf_reload_res = r; + triton_context_wakeup(conf_reload_ctx); +} +static int reload_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + if (f_cnt == 1) { + conf_reload_ctx = triton_context_self(); + triton_conf_reload(conf_reload_notify); + triton_context_schedule(); + if (conf_reload_res) + cli_send(cli, "failed\r\n"); + return CLI_CMD_OK; + } else + return CLI_CMD_SYNTAX; +} + +static void reload_help(char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "reload - reload config file\r\n"); +} + +static void __init init(void) +{ + cli_register_simple_cmd2(show_stat_exec, show_stat_help, 2, "show", "stat"); + cli_register_simple_cmd2(terminate_exec, terminate_help, 1, "terminate"); + cli_register_simple_cmd2(reload_exec, reload_help, 1, "reload"); + cli_register_simple_cmd2(shutdown_exec, shutdown_help, 1, "shutdown"); + cli_register_simple_cmd2(exit_exec, exit_help, 1, "exit"); +} + diff --git a/accel-pppd/cli/tcp.c b/accel-pppd/cli/tcp.c new file mode 100644 index 0000000..260225f --- /dev/null +++ b/accel-pppd/cli/tcp.c @@ -0,0 +1,371 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "triton.h" +#include "log.h" +#include "list.h" +#include "memdebug.h" + +#include "cli_p.h" + +#define RECV_BUF_SIZE 1024 + +struct tcp_client_t +{ + struct cli_client_t cli_client; + struct list_head entry; + struct triton_md_handler_t hnd; + struct list_head xmit_queue; + struct buffer_t *xmit_buf; + uint8_t *cmdline; + int xmit_pos; + int recv_pos; + int auth:1; + int disconnect:1; +}; + +struct buffer_t +{ + struct list_head entry; + int size; + uint8_t buf[0]; +}; + +static struct triton_context_t serv_ctx; +static struct triton_md_handler_t serv_hnd; +static LIST_HEAD(clients); + +static uint8_t *temp_buf; + +static void disconnect(struct tcp_client_t *cln) +{ + struct buffer_t *b; + + log_debug("cli: disconnect\n"); + + list_del(&cln->entry); + + triton_md_unregister_handler(&cln->hnd); + close(cln->hnd.fd); + + if (cln->xmit_buf) + _free(cln->xmit_buf); + + while (!list_empty(&cln->xmit_queue)) { + b = list_entry(cln->xmit_queue.next, typeof(*b), entry); + list_del(&b->entry); + _free(b); + } + + _free(cln->cmdline); + _free(cln); +} + +static void cli_client_disconnect(struct cli_client_t *tcln) +{ + struct tcp_client_t *cln = container_of(tcln, typeof(*cln), cli_client); + cln->disconnect = 1; +} + +static void queue_buffer(struct tcp_client_t *cln, struct buffer_t *b) +{ + if (cln->xmit_buf) + list_add_tail(&b->entry, &cln->xmit_queue); + else + cln->xmit_buf = b; +} + +static int cli_client_send(struct cli_client_t *tcln, const void *_buf, int size) +{ + struct tcp_client_t *cln = container_of(tcln, typeof(*cln), cli_client); + int n, k; + struct buffer_t *b; + const uint8_t *buf = (const uint8_t *)_buf; + + if (cln->disconnect) + return -1; + + if (!list_empty(&cln->xmit_queue)) { + b = _malloc(sizeof(*b) + size); + b->size = size; + memcpy(b->buf, buf, size); + queue_buffer(cln, b); + return 0; + } + + for (n = 0; n < size; n += k) { + k = write(cln->hnd.fd, buf + n, size - n); + if (k < 0) { + if (errno == EAGAIN) { + b = _malloc(sizeof(*b) + size - n); + b->size = size - n; + memcpy(b->buf, buf, size - n); + queue_buffer(cln, b); + + triton_md_enable_handler(&cln->hnd, MD_MODE_WRITE); + break; + } + if (errno != EPIPE) + log_error("cli: write: %s\n", strerror(errno)); + //disconnect(cln); + cln->disconnect = 1; + return -1; + } + } + return 0; +} + +static int cli_client_sendv(struct cli_client_t *tcln, const char *fmt, va_list ap) +{ + struct tcp_client_t *cln = container_of(tcln, typeof(*cln), cli_client); + int r = vsnprintf((char *)temp_buf, RECV_BUF_SIZE, fmt, ap); + + if (r >= RECV_BUF_SIZE) { + strcpy((char *)temp_buf + RECV_BUF_SIZE - 5, "...\n"); + r = RECV_BUF_SIZE; + } + + return cli_client_send(tcln, temp_buf, r); +} + +static int cln_read(struct triton_md_handler_t *h) +{ + struct tcp_client_t *cln = container_of(h, typeof(*cln), hnd); + int n; + char *d; + + while (1) { + n = read(h->fd, cln->cmdline + cln->recv_pos, RECV_BUF_SIZE - cln->recv_pos); + if (n == 0) + break; + if (n < 0) { + if (errno != EAGAIN) + log_error("cli: read: %s\n", strerror(errno)); + return 0; + } + + cln->recv_pos += n; + + while (cln->recv_pos) { + d = strchr((char *)cln->cmdline, '\n'); + if (!d) { + if (cln->recv_pos == RECV_BUF_SIZE) { + log_warn("cli: tcp: recv buffer overflow\n"); + goto drop; + } + break; + } + + *d = 0; + + if (!cln->auth) { + if (strcmp((char *)cln->cmdline, conf_cli_passwd)) + goto drop; + cln->auth = 1; + } else + cli_process_cmd(&cln->cli_client); + + if (cln->disconnect) + goto drop; + + cln->recv_pos -= (uint8_t *)d + 1 - cln->cmdline; + memmove(cln->cmdline, d + 1, cln->recv_pos); + } + } + +drop: + disconnect(cln); + return -1; +} + +static int cln_write(struct triton_md_handler_t *h) +{ + struct tcp_client_t *cln = container_of(h, typeof(*cln), hnd); + int k; + + while (1) { + for (; cln->xmit_pos < cln->xmit_buf->size; cln->xmit_pos += k) { + k = write(cln->hnd.fd, cln->xmit_buf->buf + cln->xmit_pos, cln->xmit_buf->size - cln->xmit_pos); + if (k < 0) { + if (errno == EAGAIN) + return 0; + if (errno != EPIPE) + log_error("cli: tcp: write: %s\n", strerror(errno)); + disconnect(cln); + return -1; + } + } + + _free(cln->xmit_buf); + cln->xmit_pos = 0; + + if (list_empty(&cln->xmit_queue)) + break; + + cln->xmit_buf = list_entry(cln->xmit_queue.next, typeof(*cln->xmit_buf), entry); + list_del(&cln->xmit_buf->entry); + } + + triton_md_disable_handler(&cln->hnd, MD_MODE_WRITE); + + return 0; +} + +static int serv_read(struct triton_md_handler_t *h) +{ + struct sockaddr_in addr; + socklen_t size = sizeof(addr); + int sock; + struct tcp_client_t *conn; + + while(1) { + sock = accept(h->fd, (struct sockaddr *)&addr, &size); + if (sock < 0) { + if (errno == EAGAIN) + return 0; + log_error("cli: tcp: accept failed: %s\n", strerror(errno)); + continue; + } + + log_info2("cli: tcp: new connection from %s\n", inet_ntoa(addr.sin_addr)); + + if (fcntl(sock, F_SETFL, O_NONBLOCK)) { + log_error("cli: tcp: failed to set nonblocking mode: %s, closing connection...\n", strerror(errno)); + close(sock); + continue; + } + + conn = _malloc(sizeof(*conn)); + memset(conn, 0, sizeof(*conn)); + conn->hnd.fd = sock; + conn->hnd.read = cln_read; + conn->hnd.write = cln_write; + conn->cmdline = _malloc(RECV_BUF_SIZE); + INIT_LIST_HEAD(&conn->xmit_queue); + + conn->cli_client.cmdline = conn->cmdline; + conn->cli_client.send = cli_client_send; + conn->cli_client.sendv = cli_client_sendv; + conn->cli_client.disconnect = cli_client_disconnect; + + triton_md_register_handler(&serv_ctx, &conn->hnd); + triton_md_enable_handler(&conn->hnd,MD_MODE_READ); + + list_add_tail(&conn->entry, &clients); + + if (!conf_cli_passwd) + conn->auth = 1; + } + return 0; +} + +static void serv_close(struct triton_context_t *ctx) +{ + struct tcp_client_t *cln; + + while (!list_empty(&clients)) { + cln = list_entry(clients.next, typeof(*cln), entry); + disconnect(cln); + } + + triton_md_unregister_handler(&serv_hnd); + close(serv_hnd.fd); + triton_context_unregister(ctx); +} + +static struct triton_context_t serv_ctx = { + .close = serv_close, + .before_switch = log_switch, +}; + +static struct triton_md_handler_t serv_hnd = { + .read = serv_read, +}; + +static void start_server(const char *host, int port) +{ + struct sockaddr_in addr; + + serv_hnd.fd = socket(PF_INET, SOCK_STREAM, 0); + if (serv_hnd.fd < 0) { + log_emerg("cli: tcp: failed to create server socket: %s\n", strerror(errno)); + return; + } + + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + if (host) + addr.sin_addr.s_addr = inet_addr(host); + else + addr.sin_addr.s_addr = htonl(INADDR_ANY); + + setsockopt(serv_hnd.fd, SOL_SOCKET, SO_REUSEADDR, &serv_hnd.fd, 4); + if (bind (serv_hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { + log_emerg("cli: tcp: failed to bind socket: %s\n", strerror(errno)); + close(serv_hnd.fd); + return; + } + + if (listen (serv_hnd.fd, 1) < 0) { + log_emerg("cli: tcp: failed to listen socket: %s\n", strerror(errno)); + close(serv_hnd.fd); + return; + } + + if (fcntl(serv_hnd.fd, F_SETFL, O_NONBLOCK)) { + log_emerg("cli: tcp: failed to set nonblocking mode: %s\n", strerror(errno)); + close(serv_hnd.fd); + return; + } + + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = inet_addr(host); + + triton_context_register(&serv_ctx, NULL); + triton_context_set_priority(&serv_ctx, 1); + triton_md_register_handler(&serv_ctx, &serv_hnd); + triton_md_enable_handler(&serv_hnd, MD_MODE_READ); + triton_context_wakeup(&serv_ctx); +} + +static void __init init(void) +{ + const char *opt; + char *host, *d; + int port; + + opt = conf_get_opt("cli", "tcp"); + if (!opt) + return; + + host = strdup(opt); + d = strstr(host, ":"); + if (!d) + goto err_fmt; + + *d = 0; + port = atoi(d + 1); + if (port <= 0) + goto err_fmt; + + temp_buf = malloc(RECV_BUF_SIZE); + + start_server(host, port); + + return; +err_fmt: + log_emerg("cli: tcp: invalid format\n"); + free(host); +} + diff --git a/accel-pppd/cli/telnet.c b/accel-pppd/cli/telnet.c new file mode 100644 index 0000000..5176df2 --- /dev/null +++ b/accel-pppd/cli/telnet.c @@ -0,0 +1,757 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "triton.h" +#include "log.h" +#include "ppp.h" +#include "list.h" +#include "memdebug.h" + +#include "cli_p.h" + +#define RECV_BUF_SIZE 1024 + +#define MSG_AUTH_FAILED "\r\nAuthentication failed\r\n" +#define MSG_SHUTDOWN_IN_PROGRESS "note: 'shutdown soft' is in progress...\r\n" + +#define ESC_LEFT "[D" +#define ESC_RIGHT "[C" +#define ESC_UP "[A" +#define ESC_DOWN "[B" + +struct telnet_client_t +{ + struct cli_client_t cli_client; + struct list_head entry; + struct triton_md_handler_t hnd; + struct list_head xmit_queue; + struct buffer_t *xmit_buf; + int xmit_pos; + struct list_head history; + struct list_head *history_pos; + uint8_t *cmdline; + int cmdline_pos; + int cmdline_pos2; + int cmdline_len; + int auth:1; + int echo:1; + int telcmd:1; + int esc:1; + int disconnect:1; +}; + +struct buffer_t +{ + struct list_head entry; + int size; + struct buffer_t *p_buf; + uint8_t buf[0]; +}; + +static struct triton_context_t serv_ctx; +static struct triton_md_handler_t serv_hnd; +static LIST_HEAD(clients); + +static uint8_t *recv_buf; +static uint8_t *temp_buf; + +static int conf_history_len = 100; +static const char *conf_history_file = "/var/run/accel-ppp/history"; +static LIST_HEAD(history); +static int history_len; +static pthread_mutex_t history_lock = PTHREAD_MUTEX_INITIALIZER; + +static void disconnect(struct telnet_client_t *cln) +{ + struct buffer_t *b, *b2; + + log_debug("cli: disconnect\n"); + + triton_stop_collect_cpu_usage(); + + list_del(&cln->entry); + + triton_md_unregister_handler(&cln->hnd); + close(cln->hnd.fd); + + if (cln->xmit_buf) + _free(cln->xmit_buf); + + while (!list_empty(&cln->xmit_queue)) { + b = list_entry(cln->xmit_queue.next, typeof(*b), entry); + list_del(&b->entry); + _free(b); + } + + pthread_mutex_lock(&history_lock); + while (!list_empty(&cln->history)) { + b = list_entry(cln->history.prev, typeof(*b), entry); + list_del(&b->entry); + if (!b->p_buf) { + if (history_len == conf_history_len) { + b2 = list_entry(history.next, typeof(*b2), entry); + list_del(&b2->entry); + _free(b2); + } else + history_len++; + list_add_tail(&b->entry, &history); + } else + _free(b); + } + pthread_mutex_unlock(&history_lock); + + _free(cln->cmdline); + _free(cln); +} + +static void cli_client_disconnect(struct cli_client_t *tcln) +{ + struct telnet_client_t *cln = container_of(tcln, typeof(*cln), cli_client); + cln->disconnect = 1; +} + +static void queue_buffer(struct telnet_client_t *cln, struct buffer_t *b) +{ + if (cln->xmit_buf) + list_add_tail(&b->entry, &cln->xmit_queue); + else + cln->xmit_buf = b; +} + +static int telnet_send(struct telnet_client_t *cln, const void *_buf, int size) +{ + int n, k; + struct buffer_t *b; + const uint8_t *buf = (const uint8_t *)_buf; + + if (cln->disconnect) + return -1; + + if (!list_empty(&cln->xmit_queue)) { + b = _malloc(sizeof(*b) + size); + b->size = size; + memcpy(b->buf, buf, size); + queue_buffer(cln, b); + return 0; + } + + for (n = 0; n < size; n += k) { + k = write(cln->hnd.fd, buf + n, size - n); + if (k < 0) { + if (errno == EAGAIN) { + b = _malloc(sizeof(*b) + size - n); + b->size = size - n; + memcpy(b->buf, buf, size - n); + queue_buffer(cln, b); + + triton_md_enable_handler(&cln->hnd, MD_MODE_WRITE); + break; + } + if (errno != EPIPE) + log_error("cli: write: %s\n", strerror(errno)); + //disconnect(cln); + cln->disconnect = 1; + return -1; + } + } + return 0; +} + +static int cli_client_send(struct cli_client_t *tcln, const void *buf, int size) +{ + struct telnet_client_t *cln = container_of(tcln, typeof(*cln), cli_client); + return telnet_send(cln, buf, size); +} + +static int cli_client_sendv(struct cli_client_t *tcln, const char *fmt, va_list ap) +{ + struct telnet_client_t *cln = container_of(tcln, typeof(*cln), cli_client); + int r = vsnprintf((char *)temp_buf, RECV_BUF_SIZE, fmt, ap); + + if (r >= RECV_BUF_SIZE) { + strcpy((char *)temp_buf + RECV_BUF_SIZE - 6, "...\r\n"); + r = RECV_BUF_SIZE; + } + + return telnet_send(cln, temp_buf, r); +} + +static int send_banner(struct telnet_client_t *cln) +{ + if (telnet_send(cln, "accel-ppp version " ACCEL_PPP_VERSION "\r\n", sizeof("accel-ppp version " ACCEL_PPP_VERSION "\r\n"))) + return -1; + return 0; +} + +static int send_config(struct telnet_client_t *cln) +{ + uint8_t buf[] = {IAC, WILL, TELOPT_ECHO, IAC, WILL, TELOPT_SGA, IAC, DONT, TELOPT_LINEMODE}; + return telnet_send(cln, buf, sizeof(buf)); +} + +static int send_password_request(struct telnet_client_t *cln) +{ + uint8_t buf0[] = {IAC, WILL, TELOPT_ECHO}; + uint8_t buf1[] = "Password: "; + + if (telnet_send(cln, buf0, sizeof(buf0))) + return -1; + + if (telnet_send(cln, buf1, sizeof(buf1))) + return -1; + + return 0; +} + +static int send_prompt(struct telnet_client_t *cln) +{ + sprintf((char *)temp_buf, "%s%s# ", conf_cli_prompt, ppp_shutdown ? "(shutdown)" : ""); + return telnet_send(cln, temp_buf, strlen((char *)temp_buf)); +} + +/*static void print_buf(const uint8_t *buf, int size) +{ + int i; + + for (i = 0; i < size; i++) + log_debug("%x ", buf[i]); + log_debug("\n"); +}*/ + +static int send_cmdline_tail(struct telnet_client_t *cln, int corr) +{ + if (telnet_send(cln, cln->cmdline + cln->cmdline_pos, cln->cmdline_len - cln->cmdline_pos)) + return -1; + + memset(temp_buf, '\b', cln->cmdline_len - cln->cmdline_pos - corr); + + if (telnet_send(cln, temp_buf, cln->cmdline_len - cln->cmdline_pos - corr)) + return -1; + + return 0; +} + +static int load_history(struct telnet_client_t *cln) +{ + struct buffer_t *b = list_entry(cln->history_pos, typeof(*b), entry); + if (b->size < cln->cmdline_len) { + memset(temp_buf, '\b', cln->cmdline_len - b->size); + memset(temp_buf + cln->cmdline_len - b->size, ' ', cln->cmdline_len - b->size); + if (telnet_send(cln, temp_buf, (cln->cmdline_len - b->size) * 2)) + return -1; + } + if (telnet_send(cln, "\r", 1)) + return -1; + if (send_prompt(cln)) + return -1; + memcpy(cln->cmdline, b->p_buf ? b->p_buf->buf : b->buf, b->size); + cln->cmdline_pos = b->size; + cln->cmdline_len = b->size; + if (telnet_send(cln, b->p_buf ? b->p_buf->buf : b->buf, b->size)) + return -1; + + return 0; +} + +static int telnet_input_char(struct telnet_client_t *cln, uint8_t c) +{ + uint8_t buf[] = {IAC, DONT, 0}; + struct buffer_t *b; + + if (c == '\n') + return 0; + + if (c == '\r') { + cln->cmdline[cln->cmdline_len] = 0; + + if (cln->echo) { + if (telnet_send(cln, "\r\n", 2)) + return -1; + } + + if (!cln->auth) { + if (strcmp((char *)cln->cmdline, conf_cli_passwd)) { + if (telnet_send(cln, MSG_AUTH_FAILED, sizeof(MSG_AUTH_FAILED))) + return -1; + cln->disconnect = 1; + return -1; + } + cln->auth = 1; + if (ppp_shutdown) { + if (telnet_send(cln, MSG_SHUTDOWN_IN_PROGRESS, sizeof(MSG_SHUTDOWN_IN_PROGRESS))) + return -1; + } + } else if (cln->cmdline_len) { + b = _malloc(sizeof(*b) + cln->cmdline_len); + b->p_buf = NULL; + memcpy(b->buf, cln->cmdline, cln->cmdline_len); + b->size = cln->cmdline_len; + list_add(&b->entry, cln->history.next); + cln->history_pos = cln->history.next; + + if (cli_process_cmd(&cln->cli_client)) + return -1; + } + + cln->cmdline_pos = 0; + cln->cmdline_len = 0; + + return send_prompt(cln); + } + + if (cln->telcmd) { + if (cln->cmdline_pos2 == RECV_BUF_SIZE - 1) { + log_error("cli: buffer overflow, dropping connection ...\n"); + disconnect(cln); + return -1; + } + + cln->cmdline[cln->cmdline_pos2] = c; + cln->cmdline_pos2++; + + if (cln->cmdline[cln->cmdline_len] >= WILL && cln->cmdline[cln->cmdline_len] <= DONT && cln->cmdline_pos2 - cln->cmdline_len != 2) + return 0; + + switch (cln->cmdline[cln->cmdline_len]) { + case WILL: + case WONT: + buf[2] = c; + if (telnet_send(cln, buf, 3)) + return -1; + break; + case DO: + if (c == TELOPT_ECHO) + cln->echo = 1; + break; + case SB: + if (c != SE) + return 0; + } + + cln->telcmd = 0; + } else if (cln->esc) { + if (cln->cmdline_pos2 == RECV_BUF_SIZE - 1) { + log_error("cli: buffer overflow, dropping connection ...\n"); + disconnect(cln); + return -1; + } + + cln->cmdline[cln->cmdline_pos2] = c; + cln->cmdline_pos2++; + + if (cln->cmdline_pos2 - cln->cmdline_len != 2) + return 0; + + cln->esc = 0; + + if (cln->auth) { + if (!memcmp(cln->cmdline + cln->cmdline_len, ESC_LEFT, 2)) { + if (cln->cmdline_pos) { + if (telnet_send(cln, "\b", 1)) + return -1; + cln->cmdline_pos--; + } + } else if (!memcmp(cln->cmdline + cln->cmdline_len, ESC_RIGHT, 2)) { + if (cln->cmdline_pos < cln->cmdline_len) { + if (send_cmdline_tail(cln, 1)) + return -1; + cln->cmdline_pos++; + } + } else if (!memcmp(cln->cmdline + cln->cmdline_len, ESC_UP, 2)) { + if (cln->history_pos == cln->history.next) { + b = list_entry(cln->history_pos, typeof(*b), entry); + memcpy(b->buf, cln->cmdline, cln->cmdline_len); + b->size = cln->cmdline_len; + } + cln->history_pos = cln->history_pos->next; + if (cln->history_pos == &cln->history) { + cln->history_pos = cln->history_pos->prev; + return 0; + } + if (load_history(cln)) + return -1; + } else if (!memcmp(cln->cmdline + cln->cmdline_len, ESC_DOWN, 2)) { + cln->history_pos = cln->history_pos->prev; + if (cln->history_pos == &cln->history) { + cln->history_pos = cln->history_pos->next; + return 0; + } + if (load_history(cln)) + return -1; + } + } + } else { + switch (c) { + case 0xff: + cln->cmdline_pos2 = cln->cmdline_len; + cln->telcmd = 1; + return 0; + case 0x1b: + cln->cmdline_pos2 = cln->cmdline_len; + cln->esc = 1; + return 0; + case 0x7f: + if (cln->cmdline_pos) { + if (cln->cmdline_pos < cln->cmdline_len) { + memmove(cln->cmdline + cln->cmdline_pos - 1, cln->cmdline + cln->cmdline_pos, cln->cmdline_len - cln->cmdline_pos); + + cln->cmdline[cln->cmdline_len - 1] = ' '; + + if (telnet_send(cln, "\b", 1)) + return -1; + + cln->cmdline_pos--; + + if (send_cmdline_tail(cln, 0)) + return -1; + } else { + buf[0] = '\b'; + buf[1] = ' '; + buf[2] = '\b'; + if (telnet_send(cln, buf, 3)) + return -1; + cln->cmdline_pos--; + } + + cln->cmdline_len--; + } + return 0; + case 3: + cln->disconnect = 1; + return -1; + } + + if (isprint(c)) { + if (cln->cmdline_len == RECV_BUF_SIZE - 1) + return 0; + + if (cln->cmdline_pos < cln->cmdline_len) + memmove(cln->cmdline + cln->cmdline_pos + 1, cln->cmdline + cln->cmdline_pos, cln->cmdline_len - cln->cmdline_pos); + cln->cmdline[cln->cmdline_pos] = c; + cln->cmdline_pos++; + cln->cmdline_len++; + + if (cln->echo) { + if (!cln->auth) { + if (telnet_send(cln, "*", 1)) + return -1; + } else { + if (telnet_send(cln, &c, 1)) + return -1; + } + } + + if (cln->cmdline_pos < cln->cmdline_len) { + if (send_cmdline_tail(cln, 0)) + return -1; + } + } + } + + return 0; +} + +static int cln_read(struct triton_md_handler_t *h) +{ + struct telnet_client_t *cln = container_of(h, typeof(*cln), hnd); + int i, n; + + while (1) { + n = read(h->fd, recv_buf, RECV_BUF_SIZE); + if (n == 0) { + disconnect(cln); + return -1; + } + if (n < 0) { + if (errno != EAGAIN) + log_error("cli: telnet: read: %s\n", strerror(errno)); + return 0; + } + /*log_debug("cli: read(%i): ", n); + print_buf(cln->recv_buf + cln->recv_pos, n);*/ + for (i = 0; i < n; i++) { + if (telnet_input_char(cln, recv_buf[i])) + break; + } + if (cln->disconnect) { + disconnect(cln); + return -1; + } + } + + return 0; +} + +static int cln_write(struct triton_md_handler_t *h) +{ + struct telnet_client_t *cln = container_of(h, typeof(*cln), hnd); + int k; + + while (1) { + for (; cln->xmit_pos < cln->xmit_buf->size; cln->xmit_pos += k) { + k = write(cln->hnd.fd, cln->xmit_buf->buf + cln->xmit_pos, cln->xmit_buf->size - cln->xmit_pos); + if (k < 0) { + if (errno == EAGAIN) + return 0; + if (errno != EPIPE) + log_error("cli: telnet: write: %s\n", strerror(errno)); + disconnect(cln); + return -1; + } + } + + _free(cln->xmit_buf); + cln->xmit_pos = 0; + + if (list_empty(&cln->xmit_queue)) + break; + + cln->xmit_buf = list_entry(cln->xmit_queue.next, typeof(*cln->xmit_buf), entry); + list_del(&cln->xmit_buf->entry); + } + + triton_md_disable_handler(&cln->hnd, MD_MODE_WRITE); + + return 0; +} + +static int serv_read(struct triton_md_handler_t *h) +{ + struct sockaddr_in addr; + socklen_t size = sizeof(addr); + int sock; + struct telnet_client_t *conn; + struct buffer_t *b, *b2; + + while(1) { + sock = accept(h->fd, (struct sockaddr *)&addr, &size); + if (sock < 0) { + if (errno == EAGAIN) + return 0; + log_error("cli: telnet: accept failed: %s\n", strerror(errno)); + continue; + } + + log_info2("cli: telnet: new connection from %s\n", inet_ntoa(addr.sin_addr)); + + if (fcntl(sock, F_SETFL, O_NONBLOCK)) { + log_error("cli: telnet: failed to set nonblocking mode: %s, closing connection...\n", strerror(errno)); + close(sock); + continue; + } + + conn = _malloc(sizeof(*conn)); + memset(conn, 0, sizeof(*conn)); + conn->hnd.fd = sock; + conn->hnd.read = cln_read; + conn->hnd.write = cln_write; + conn->cmdline = _malloc(RECV_BUF_SIZE); + INIT_LIST_HEAD(&conn->xmit_queue); + INIT_LIST_HEAD(&conn->history); + + b = _malloc(sizeof(*b) + RECV_BUF_SIZE); + b->p_buf = b; + b->size = 0; + list_add_tail(&b->entry, &conn->history); + + pthread_mutex_lock(&history_lock); + list_for_each_entry(b, &history, entry) { + b2 = _malloc(sizeof(*b)); + b2->p_buf = b; + b2->size = b->size; + list_add(&b2->entry, conn->history.next); + } + pthread_mutex_unlock(&history_lock); + + conn->history_pos = conn->history.next; + + conn->cli_client.cmdline = conn->cmdline; + conn->cli_client.send = cli_client_send; + conn->cli_client.sendv = cli_client_sendv; + conn->cli_client.disconnect = cli_client_disconnect; + + triton_md_register_handler(&serv_ctx, &conn->hnd); + triton_md_enable_handler(&conn->hnd,MD_MODE_READ); + + list_add_tail(&conn->entry, &clients); + + if (send_banner(conn)) + continue; + + if (send_config(conn)) + continue; + + if (conf_cli_passwd) + send_password_request(conn); + else { + conn->auth = 1; + if (ppp_shutdown) { + if (telnet_send(conn, MSG_SHUTDOWN_IN_PROGRESS, sizeof(MSG_SHUTDOWN_IN_PROGRESS))) + continue; + } + send_prompt(conn); + } + triton_collect_cpu_usage(); + } + return 0; +} +static void serv_close(struct triton_context_t *ctx) +{ + struct telnet_client_t *cln; + + while (!list_empty(&clients)) { + cln = list_entry(clients.next, typeof(*cln), entry); + disconnect(cln); + } + + triton_md_unregister_handler(&serv_hnd); + close(serv_hnd.fd); + triton_context_unregister(ctx); +} + +static struct triton_context_t serv_ctx = { + .close = serv_close, + .before_switch = log_switch, +}; + +static struct triton_md_handler_t serv_hnd = { + .read = serv_read, +}; + +static void start_server(const char *host, int port) +{ + struct sockaddr_in addr; + + serv_hnd.fd = socket(PF_INET, SOCK_STREAM, 0); + if (serv_hnd.fd < 0) { + log_emerg("cli: telnet: failed to create server socket: %s\n", strerror(errno)); + return; + } + + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + if (host) + addr.sin_addr.s_addr = inet_addr(host); + else + addr.sin_addr.s_addr = htonl(INADDR_ANY); + + setsockopt(serv_hnd.fd, SOL_SOCKET, SO_REUSEADDR, &serv_hnd.fd, 4); + if (bind (serv_hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { + log_emerg("cli: telnet: failed to bind socket: %s\n", strerror(errno)); + close(serv_hnd.fd); + return; + } + + if (listen (serv_hnd.fd, 1) < 0) { + log_emerg("cli: telnet: failed to listen socket: %s\n", strerror(errno)); + close(serv_hnd.fd); + return; + } + + if (fcntl(serv_hnd.fd, F_SETFL, O_NONBLOCK)) { + log_emerg("cli: telnet: failed to set nonblocking mode: %s\n", strerror(errno)); + close(serv_hnd.fd); + return; + } + + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = inet_addr(host); + + triton_context_register(&serv_ctx, NULL); + triton_context_set_priority(&serv_ctx, 1); + triton_md_register_handler(&serv_ctx, &serv_hnd); + triton_md_enable_handler(&serv_hnd, MD_MODE_READ); + triton_context_wakeup(&serv_ctx); +} + +static void save_history_file(void) +{ + int fd; + struct buffer_t *b; + + fd = open(conf_history_file, O_WRONLY | O_TRUNC | O_CREAT, S_IREAD | S_IWRITE); + if (!fd) + return; + + list_for_each_entry(b, &history, entry) { + b->buf[b->size] = '\n'; + write(fd, b->buf, b->size + 1); + } + + close(fd); +} + +static void load_history_file(void) +{ + struct buffer_t *b; + FILE *f; + + f = fopen(conf_history_file, "r"); + if (!f) + return; + + while (fgets((char *)temp_buf, RECV_BUF_SIZE, f)) { + b = _malloc(sizeof(*b) + strlen((char *)temp_buf)); + b->p_buf = NULL; + b->size = strlen((char *)temp_buf) - 1; + memcpy(b->buf, temp_buf, b->size); + list_add_tail(&b->entry, &history); + } + + fclose(f); +} + +static void __init init(void) +{ + const char *opt; + char *host, *d; + int port; + + opt = conf_get_opt("cli", "telnet"); + if (!opt) + return; + + host = strdup(opt); + d = strstr(host, ":"); + if (!d) + goto err_fmt; + + *d = 0; + port = atoi(d + 1); + if (port <= 0) + goto err_fmt; + + opt = conf_get_opt("cli", "history-file"); + if (opt) + conf_history_file = _strdup(opt); + + recv_buf = malloc(RECV_BUF_SIZE); + temp_buf = malloc(RECV_BUF_SIZE); + + load_history_file(); + + start_server(host, port); + + atexit(save_history_file); + + return; +err_fmt: + log_emerg("cli: telnet: invalid format\n"); + free(host); +} + diff --git a/accel-pppd/ctrl/CMakeLists.txt b/accel-pppd/ctrl/CMakeLists.txt new file mode 100644 index 0000000..6b37bc4 --- /dev/null +++ b/accel-pppd/ctrl/CMakeLists.txt @@ -0,0 +1,3 @@ +ADD_SUBDIRECTORY(pptp) +ADD_SUBDIRECTORY(pppoe) +ADD_SUBDIRECTORY(l2tp) diff --git a/accel-pppd/ctrl/l2tp/CMakeLists.txt b/accel-pppd/ctrl/l2tp/CMakeLists.txt new file mode 100644 index 0000000..b295289 --- /dev/null +++ b/accel-pppd/ctrl/l2tp/CMakeLists.txt @@ -0,0 +1,17 @@ +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +ADD_DEFINITIONS(-DDICTIONARY="${CMAKE_INSTALL_PREFIX}/share/accel-ppp/l2tp/dictionary") + +ADD_LIBRARY(l2tp SHARED + l2tp.c + dict.c + packet.c + # netlink.c +) +#TARGET_LINK_LIBRARIES(l2tp nl nl-genl) + +INSTALL(TARGETS l2tp LIBRARY DESTINATION lib/accel-ppp) + +FILE(GLOB dict "${CMAKE_CURRENT_SOURCE_DIR}/dict/*") +INSTALL(FILES ${dict} DESTINATION share/accel-ppp/l2tp) + diff --git a/accel-pppd/ctrl/l2tp/attr_defs.h b/accel-pppd/ctrl/l2tp/attr_defs.h new file mode 100644 index 0000000..e799157 --- /dev/null +++ b/accel-pppd/ctrl/l2tp/attr_defs.h @@ -0,0 +1,73 @@ +#ifndef __ATTR_DEFS_H +#define __ATTR_DEFS_H + +#define Message_Type 0 +#define Random_Vector 36 +#define Result_Code 1 +#define Protocol_Version 2 +#define Framing_Capabilities 3 +#define Bearer_Capabilities 4 +#define Tie_Breaker 5 +#define Firmware_Revision 6 +#define Host_Name 7 +#define Vendor_Name 8 +#define Assigned_Tunnel_ID 9 +#define Recv_Window_Size 10 +#define Challenge 11 +#define Challenge_Response 13 +#define Cause_Code 12 +#define Assigned_Session_ID 14 +#define Call_Serial_Number 15 +#define Minimum_BPS 16 +#define Maximum_BPS 17 +#define Bearer_Type 18 +#define Framing_Type 19 +#define Called_Number 21 +#define Calling_Number 22 +#define Sub_Address 23 +#define TX_Speed 24 +#define RX_Speed 38 +#define Physical_Channel_ID 25 +#define Private_Group_ID 37 +#define Sequencing_Required 39 +#define Init_Recv_LCP 26 +#define Last_Sent_LCP 27 +#define Last_Recv_LCP 28 +#define Proxy_Authen_Type 29 +#define Proxy_Authen_Name 30 +#define Proxy_Authen_Challenge 31 +#define Proxy_Authen_ID 32 +#define Proxy_Authen_Response 33 +#define Call_Errors 34 +#define ACCM 35 +#define Message_Type_Start_Ctrl_Conn_Request 1 +#define Message_Type_Start_Ctrl_Conn_Reply 2 +#define Message_Type_Start_Ctrl_Conn_Connected 3 +#define Message_Type_Stop_Ctrl_Conn_Notify 4 +#define Message_Type_Hello 6 +#define Message_Type_Outgoing_Call_Request 7 +#define Message_Type_Outgoing_Call_Reply 8 +#define Message_Type_Outgoing_Call_Connected 9 +#define Message_Type_Incoming_Call_Request 10 +#define Message_Type_Incoming_Call_Reply 11 +#define Message_Type_Incoming_Call_Connected 12 +#define Message_Type_Call_Disconnect_Notify 14 +#define Message_Type_WAN_Error_Notify 15 +#define Message_Type_Set_Link_Info 16 +#define Message_Digest 59 +#define Router_ID 60 +#define Assigned_Connection_ID 61 +#define Pseudowire_Capabilities 62 +#define Prefered_Language 72 +#define Local_Session_ID 63 +#define Remote_Session_ID 64 +#define Assigned_Cookie 65 +#define Remote_End_ID 66 +#define Pseudowire_Type 68 +#define L2_Specific_Sublayer 69 +#define Data_Sequencing 70 +#define TX_Connect_Speeed 74 +#define RX_Connect_Speeed 75 +#define Circuit_Status 71 + +#endif diff --git a/accel-pppd/ctrl/l2tp/dict.c b/accel-pppd/ctrl/l2tp/dict.c new file mode 100644 index 0000000..c93ccd4 --- /dev/null +++ b/accel-pppd/ctrl/l2tp/dict.c @@ -0,0 +1,271 @@ +#include +#include +#include +#include +#include +#include + +#include "list.h" +#include "l2tp.h" +#include "log.h" +#include "triton.h" + +#include "memdebug.h" + +struct l2tp_dict_t +{ + struct list_head items; +}; + +static struct l2tp_dict_t *dict; + +#define BUF_SIZE 1024 +static char *path, *fname1, *buf; + +struct l2tp_dict_attr_t *l2tp_dict_find_attr_by_name(const char *name) +{ + struct l2tp_dict_attr_t *attr; + + list_for_each_entry(attr, &dict->items, entry) { + if (!strcmp(attr->name, name)) + return attr; + } + + return NULL; +} + +struct l2tp_dict_attr_t *l2tp_dict_find_attr_by_id(int id) +{ + struct l2tp_dict_attr_t *attr; + + list_for_each_entry(attr, &dict->items, entry) { + if (attr->id == id) + return attr; + } + + return NULL; +} + +struct l2tp_dict_value_t *l2tp_dict_find_value(struct l2tp_dict_attr_t *attr, l2tp_value_t val) +{ + struct l2tp_dict_value_t *v; + + list_for_each_entry(v, &attr->values, entry) { + switch (attr->type) { + case ATTR_TYPE_INT16: + if (v->val.int16 == val.int16) + return v; + break; + case ATTR_TYPE_INT32: + if (v->val.int32 == val.int32) + return v; + break; + } + } + + return NULL; +} + +static char *skip_word(char *ptr) +{ + for(; *ptr; ptr++) + if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') + break; + return ptr; +} + +static char *skip_space(char *ptr) +{ + for(; *ptr; ptr++) + if (*ptr != ' ' && *ptr != '\t') + break; + return ptr; +} + +static int split(char *buf, char **ptr) +{ + int i; + + for (i = 0; i < 6; i++) { + buf = skip_word(buf); + if (!*buf) + return i; + + *buf = 0; + + buf = skip_space(buf + 1); + if (!*buf) + return i; + + ptr[i] = buf; + } + + buf = skip_word(buf); + //if (*buf == '\n') + *buf = 0; + //else if (*buf) + // return -1; + + return i; +} + + +static int dict_load(const char *fname) +{ + FILE *f; + char *ptr[6], *endptr; + struct l2tp_dict_attr_t *attr; + struct l2tp_dict_value_t *value; + struct list_head *items; + int i, r, n = 0; + + f = fopen(fname, "r"); + if (!f) { + log_emerg("l2tp: open '%s': %s\n", fname, strerror(errno)); + return -1; + } + + items = &dict->items; + while (fgets(buf, BUF_SIZE, f)) { + n++; + if (buf[0] == '#' || buf[0] == '\n' || buf[0] == 0) + continue; + + r = split(buf, ptr); + + if (!strcmp(buf, "$INCLUDE")) { + if (r != 1) + goto out_syntax; + + for (i = strlen(path) - 1; i; i--) { + if (path[i] == '/') { + path[i + 1] = 0; + break; + } + } + + strcpy(fname1, path); + strcat(fname1, ptr[0]); + + if (dict_load(fname1)) + goto out_err; + } else if (!strcmp(buf, "ATTRIBUTE")) { + if (r < 3) + goto out_syntax; + + attr = malloc(sizeof(*attr)); + memset(attr, 0, sizeof(*attr)); + list_add_tail(&attr->entry, items); + INIT_LIST_HEAD(&attr->values); + + attr->name = strdup(ptr[0]); + attr->id = strtol(ptr[1], &endptr, 10); + if (*endptr != 0) + goto out_syntax; + + if (!strcmp(ptr[2], "none")) + attr->type = ATTR_TYPE_NONE; + else if (!strcmp(ptr[2], "int16")) + attr->type = ATTR_TYPE_INT16; + else if (!strcmp(ptr[2], "int32")) + attr->type = ATTR_TYPE_INT32; + else if (!strcmp(ptr[2], "int64")) + attr->type = ATTR_TYPE_INT64; + else if (!strcmp(ptr[2], "octets")) + attr->type = ATTR_TYPE_OCTETS; + else if (!strcmp(ptr[2], "string")) + attr->type = ATTR_TYPE_STRING; + else + goto out_syntax; + + attr->M = -1; + attr->H = -1; + + for (i = 3; i < r; i++) { + if (!strcmp(ptr[i], "M=0")) + attr->M = 0; + else if (!strcmp(ptr[i], "M=1")) + attr->M = 1; + else if (!strcmp(ptr[i], "H=0")) + attr->H = 0; + else if (!strcmp(ptr[i], "H=1")) + attr->H = 1; + else + goto out_syntax; + } + } else if (!strcmp(buf, "VALUE")) { + if (r != 3) + goto out_syntax; + + attr = l2tp_dict_find_attr_by_name(ptr[0]); + if (!attr) { + log_emerg("l2tp:%s:%i: attribute not found\n", fname, n); + goto out_err; + } + + value = malloc(sizeof(*value)); + memset(value, 0, sizeof(*value)); + list_add_tail(&value->entry, &attr->values); + + value->name = strdup(ptr[1]); + switch (attr->type) { + case ATTR_TYPE_INT16: + case ATTR_TYPE_INT32: + value->val.int16 = strtol(ptr[2], &endptr, 10); + if (*endptr != 0) + goto out_syntax; + break; + case ATTR_TYPE_STRING: + value->val.string = strdup(ptr[2]); + break; + } + } else + goto out_syntax; + } + + fclose(f); + + return 0; + +out_syntax: + log_emerg("l2tp:%s:%i: syntaxis error\n", fname, n); +out_err: + fclose(f); + return -1; +} + +static int l2tp_dict_load(const char *fname) +{ + int r; + + dict = _malloc(sizeof(*dict)); + memset(dict, 0, sizeof(*dict)); + INIT_LIST_HEAD(&dict->items); + + path = _malloc(PATH_MAX); + fname1 = _malloc(PATH_MAX); + buf = _malloc(BUF_SIZE); + + strcpy(path, fname); + + r = dict_load(fname); + + _free(buf); + _free(fname1); + _free(path); + + return r; +} + +static void __init dict_init(void) +{ + char *opt; + + opt = conf_get_opt("l2tp", "dictionary"); + if (!opt) + opt = DICTIONARY; + + if (l2tp_dict_load(opt)) + _exit(EXIT_FAILURE); +} + diff --git a/accel-pppd/ctrl/l2tp/dict/dictionary b/accel-pppd/ctrl/l2tp/dict/dictionary new file mode 100644 index 0000000..f5d7c42 --- /dev/null +++ b/accel-pppd/ctrl/l2tp/dict/dictionary @@ -0,0 +1,2 @@ +$INCLUDE dictionary.rfc2661 +$INCLUDE dictionary.rfc3931 diff --git a/accel-pppd/ctrl/l2tp/dict/dictionary.rfc2661 b/accel-pppd/ctrl/l2tp/dict/dictionary.rfc2661 new file mode 100644 index 0000000..3fd9614 --- /dev/null +++ b/accel-pppd/ctrl/l2tp/dict/dictionary.rfc2661 @@ -0,0 +1,55 @@ +ATTRIBUTE Message-Type 0 int16 H=0 +ATTRIBUTE Random-Vector 36 octets M=1 H=0 +ATTRIBUTE Result-Code 1 octets M=1 H=0 +ATTRIBUTE Protocol-Version 2 int16 M=1 H=0 +ATTRIBUTE Framing-Capabilities 3 int32 M=1 +ATTRIBUTE Bearer-Capabilities 4 int32 M=1 +ATTRIBUTE Tie-Breaker 5 int64 M=0 +ATTRIBUTE Firmware-Revision 6 int16 M=0 +ATTRIBUTE Host-Name 7 string M=1 +ATTRIBUTE Vendor-Name 8 string M=0 +ATTRIBUTE Assigned-Tunnel-ID 9 int16 M=1 +ATTRIBUTE Recv-Window-Size 10 int16 M=1 +ATTRIBUTE Challenge 11 octets M=1 +ATTRIBUTE Challenge-Response 13 octets M=1 +ATTRIBUTE Cause-Code 12 int32 M=1 H=0 +ATTRIBUTE Assigned-Session-ID 14 int16 M=1 +ATTRIBUTE Call-Serial-Number 15 int32 M=1 +ATTRIBUTE Minimum-BPS 16 int32 M=1 +ATTRIBUTE Maximum-BPS 17 int32 M=1 +ATTRIBUTE Bearer-Type 18 int32 M=1 +ATTRIBUTE Framing-Type 19 int32 M=1 +ATTRIBUTE Called-Number 21 string M=1 +ATTRIBUTE Calling-Number 22 string M=1 +ATTRIBUTE Sub-Address 23 string M=1 +ATTRIBUTE TX-Speed 24 int32 M=1 +ATTRIBUTE RX-Speed 38 int32 M=1 +ATTRIBUTE Physical-Channel-ID 25 int32 M=0 +ATTRIBUTE Private-Group-ID 37 int32 M=0 +ATTRIBUTE Sequencing-Required 39 none M=1 H=0 +ATTRIBUTE Init-Recv-LCP 26 octets M=0 +ATTRIBUTE Last-Sent-LCP 27 octets M=0 +ATTRIBUTE Last-Recv-LCP 28 octets M=0 +ATTRIBUTE Proxy-Authen-Type 29 int16 M=0 +ATTRIBUTE Proxy-Authen-Name 30 string M=0 +ATTRIBUTE Proxy-Authen-Challenge 31 octets M=0 +ATTRIBUTE Proxy-Authen-ID 32 int16 M=0 +ATTRIBUTE Proxy-Authen-Response 33 octets M=0 +ATTRIBUTE Call-Errors 34 octets M=1 +ATTRIBUTE ACCM 35 octets M=1 + +VALUE Message-Type Start-Ctrl-Conn-Request 1 +VALUE Message-Type Start-Ctrl-Conn-Reply 2 +VALUE Message-Type Start-Ctrl-Conn-Connected 3 +VALUE Message-Type Stop-Ctrl-Conn-Notify 4 +VALUE Message-Type Hello 6 +VALUE Message-Type Outgoing-Call-Request 7 +VALUE Message-Type Outgoing-Call-Reply 8 +VALUE Message-Type Outgoing-Call-Connected 9 +VALUE Message-Type Incoming-Call-Request 10 +VALUE Message-Type Incoming-Call-Reply 11 +VALUE Message-Type Incoming-Call-Connected 12 +VALUE Message-Type Call-Disconnect-Notify 14 +VALUE Message-Type WAN-Error-Notify 15 +VALUE Message-Type Set-Link-Info 16 + diff --git a/accel-pppd/ctrl/l2tp/dict/dictionary.rfc3931 b/accel-pppd/ctrl/l2tp/dict/dictionary.rfc3931 new file mode 100644 index 0000000..d6ad410 --- /dev/null +++ b/accel-pppd/ctrl/l2tp/dict/dictionary.rfc3931 @@ -0,0 +1,15 @@ +ATTRIBUTE Message-Digest 59 octets M=1 H=0 +ATTRIBUTE Router-ID 60 int32 H=0 +ATTRIBUTE Assigned-Connection-ID 61 int32 +ATTRIBUTE Pseudowire-Capabilities 62 octets +ATTRIBUTE Prefered-Language 72 octets +ATTRIBUTE Local-Session-ID 63 int32 +ATTRIBUTE Remote-Session-ID 64 int32 +ATTRIBUTE Assigned-Cookie 65 octets +ATTRIBUTE Remote-End-ID 66 octets +ATTRIBUTE Pseudowire-Type 68 int16 +ATTRIBUTE L2-Specific-Sublayer 69 int16 +ATTRIBUTE Data-Sequencing 70 int16 +ATTRIBUTE TX-Connect-Speeed 74 int64 +ATTRIBUTE RX-Connect-Speeed 75 int64 +ATTRIBUTE Circuit-Status 71 int16 diff --git a/accel-pppd/ctrl/l2tp/dict2c.py b/accel-pppd/ctrl/l2tp/dict2c.py new file mode 100644 index 0000000..ff0961e --- /dev/null +++ b/accel-pppd/ctrl/l2tp/dict2c.py @@ -0,0 +1,20 @@ +import sys,re + +hdr = file(sys.argv[2],'w') + +def process(fname, hdr): + for line in file(fname): + if line[:-1].strip() == '': + continue + if line[0] == '#': + continue + f = re.compile('[$.a-zA-Z0-9\-]+').findall(line) + if f[0] == 'ATTRIBUTE' or f[0] == 'VENDOR': + hdr.write('#define {0} {1}\n'.format(f[1].replace('-','_').replace('.','_'), f[2])) + elif f[0] == 'VALUE': + hdr.write('#define {0}_{1} {2}\n'.format(f[1].replace('-','_').replace('.','_'), f[2].replace('-','_'),f[3])) + elif f[0] == '$INCLUDE': + process(f[1], hdr) + +if __name__ == '__main__': + process(sys.argv[1], hdr) diff --git a/accel-pppd/ctrl/l2tp/l2tp.c b/accel-pppd/ctrl/l2tp/l2tp.c new file mode 100644 index 0000000..ca56051 --- /dev/null +++ b/accel-pppd/ctrl/l2tp/l2tp.c @@ -0,0 +1,1141 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "triton.h" +#include "mempool.h" +#include "log.h" +#include "ppp.h" +#include "events.h" +#include "utils.h" +#include "iprange.h" +#include "cli.h" + +#include "memdebug.h" + +#include "l2tp.h" +#include "attr_defs.h" + +#ifndef SOL_PPPOL2TP +#define SOL_PPPOL2TP 273 +#endif + +#define STATE_WAIT_SCCCN 1 +#define STATE_WAIT_ICRQ 2 +#define STATE_WAIT_ICCN 3 +#define STATE_WAIT_OCRP 4 +#define STATE_WAIT_OCCN 5 +#define STATE_ESTB 6 +#define STATE_PPP 7 +#define STATE_FIN 8 +#define STATE_CLOSE 0 + +int conf_verbose = 0; +int conf_timeout = 60; +int conf_rtimeout = 5; +int conf_retransmit = 5; +int conf_hello_interval = 60; +char *conf_host_name = NULL; + +static unsigned int stat_active; +static unsigned int stat_starting; + +struct l2tp_serv_t +{ + struct triton_context_t ctx; + struct triton_md_handler_t hnd; + struct sockaddr_in addr; +}; + +struct l2tp_conn_t +{ + struct triton_context_t ctx; + struct triton_md_handler_t hnd; + struct triton_timer_t timeout_timer; + struct triton_timer_t rtimeout_timer; + struct triton_timer_t hello_timer; + + int tunnel_fd; + + struct sockaddr_in addr; + uint16_t tid; + uint16_t sid; + uint16_t peer_tid; + uint16_t peer_sid; + uint32_t framing_cap; + + int retransmit; + uint16_t Ns, Nr; + struct list_head send_queue; + + int state; + int state1; + int state2; + + struct ppp_ctrl_t ctrl; + struct ppp_t ppp; +}; + +static pthread_mutex_t l2tp_lock = PTHREAD_MUTEX_INITIALIZER; +static struct l2tp_conn_t **l2tp_conn; +static uint16_t l2tp_tid; + +static mempool_t l2tp_conn_pool; + +static void l2tp_timeout(struct triton_timer_t *t); +static void l2tp_rtimeout(struct triton_timer_t *t); +static void l2tp_send_HELLO(struct triton_timer_t *t); +static void l2tp_send_SCCRP(struct l2tp_conn_t *conn); +static int l2tp_send(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack, int log_debug); +static int l2tp_conn_read(struct triton_md_handler_t *); + +static void l2tp_disconnect(struct l2tp_conn_t *conn) +{ + struct l2tp_packet_t *pack; + + triton_md_unregister_handler(&conn->hnd); + close(conn->hnd.fd); + + if (conn->timeout_timer.tpd) + triton_timer_del(&conn->timeout_timer); + + if (conn->rtimeout_timer.tpd) + triton_timer_del(&conn->rtimeout_timer); + + if (conn->hello_timer.tpd) + triton_timer_del(&conn->hello_timer); + + if (conn->state == STATE_PPP) { + __sync_sub_and_fetch(&stat_active, 1); + conn->state = STATE_FIN; + ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); + } else if (conn->state != STATE_FIN) + __sync_sub_and_fetch(&stat_starting, 1); + + pthread_mutex_lock(&l2tp_lock); + l2tp_conn[conn->tid] = NULL; + pthread_mutex_unlock(&l2tp_lock); + + if (conn->ppp.fd != -1) + close(conn->ppp.fd); + + if (conn->tunnel_fd != -1) + close(conn->tunnel_fd); + + triton_event_fire(EV_CTRL_FINISHED, &conn->ppp); + + log_ppp_info1("disconnected\n"); + + triton_context_unregister(&conn->ctx); + + while (!list_empty(&conn->send_queue)) { + pack = list_entry(conn->send_queue.next, typeof(*pack), entry); + list_del(&pack->entry); + l2tp_packet_free(pack); + } + + if (conn->ppp.chan_name) + _free(conn->ppp.chan_name); + + _free(conn->ctrl.calling_station_id); + _free(conn->ctrl.called_station_id); + + mempool_free(conn); +} + +static int l2tp_terminate(struct l2tp_conn_t *conn, int res, int err) +{ + struct l2tp_packet_t *pack; + struct l2tp_avp_result_code rc = {res, err}; + + log_ppp_debug("l2tp: terminate (%i, %i)\n", res, err); + + pack = l2tp_packet_alloc(2, Message_Type_Stop_Ctrl_Conn_Notify, &conn->addr); + if (!pack) + return -1; + + if (l2tp_packet_add_int16(pack, Assigned_Tunnel_ID, conn->tid, 1)) + goto out_err; + if (l2tp_packet_add_octets(pack, Result_Code, (uint8_t *)&rc, sizeof(rc), 0)) + goto out_err; + + l2tp_send(conn, pack, 0); + + conn->state = STATE_FIN; + + return 0; + +out_err: + l2tp_packet_free(pack); + return -1; +} + +static void l2tp_ppp_started(struct ppp_t *ppp) +{ + struct l2tp_conn_t *conn = container_of(ppp, typeof(*conn), ppp); + + log_ppp_debug("l2tp: ppp started\n"); + + if (conf_hello_interval) + triton_timer_add(&conn->ctx, &conn->hello_timer, 0); +} + +static void l2tp_ppp_finished(struct ppp_t *ppp) +{ + struct l2tp_conn_t *conn = container_of(ppp, typeof(*conn), ppp); + + log_ppp_debug("l2tp: ppp finished\n"); + + if (conn->state != STATE_FIN) { + __sync_sub_and_fetch(&stat_active, 1); + if (l2tp_terminate(conn, 0, 0)) + triton_context_call(&conn->ctx, (triton_event_func)l2tp_disconnect, conn); + } +} + +static void l2tp_conn_close(struct triton_context_t *ctx) +{ + struct l2tp_conn_t *conn = container_of(ctx, typeof(*conn), ctx); + + if (conn->state == STATE_PPP) { + __sync_sub_and_fetch(&stat_active, 1); + conn->state = STATE_FIN; + ppp_terminate(&conn->ppp, TERM_ADMIN_RESET, 1); + } + + if (l2tp_terminate(conn, 0, 0)) + l2tp_disconnect(conn); +} + +static int l2tp_tunnel_alloc(struct l2tp_serv_t *serv, struct l2tp_packet_t *pack, struct in_pktinfo *pkt_info, struct l2tp_attr_t *assigned_tid, struct l2tp_attr_t *framing_cap) +{ + struct l2tp_conn_t *conn; + struct sockaddr_in addr; + uint16_t tid; + //char *opt; + int flag = 1; + + conn = mempool_alloc(l2tp_conn_pool); + if (!conn) { + log_emerg("l2tp: out of memory\n"); + return -1; + } + + memset(conn, 0, sizeof(*conn)); + INIT_LIST_HEAD(&conn->send_queue); + + conn->hnd.fd = socket(PF_INET, SOCK_DGRAM, 0); + if (conn->hnd.fd < 0) { + log_error("l2tp: socket: %s\n", strerror(errno)); + mempool_free(conn); + return -1; + } + + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_addr = pkt_info->ipi_addr; + addr.sin_port = htons(L2TP_PORT); + + setsockopt(conn->hnd.fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); + if (bind(conn->hnd.fd, &addr, sizeof(addr))) { + log_error("l2tp: bind: %s\n", strerror(errno)); + goto out_err; + } + + if (connect(conn->hnd.fd, (struct sockaddr *)&pack->addr, sizeof(addr))) { + log_error("l2tp: connect: %s\n", strerror(errno)); + goto out_err; + } + + if (fcntl(conn->hnd.fd, F_SETFL, O_NONBLOCK)) { + log_emerg("l2tp: failed to set nonblocking mode: %s\n", strerror(errno)); + goto out_err; + } + + pthread_mutex_lock(&l2tp_lock); + for (tid = l2tp_tid + 1; tid != l2tp_tid; tid++) { + if (tid == L2TP_MAX_TID) + tid = 1; + if (!l2tp_conn[tid]) { + l2tp_conn[tid] = conn; + conn->tid = tid; + break; + } + } + pthread_mutex_unlock(&l2tp_lock); + + if (!conn->tid) { + if (conf_verbose) + log_warn("l2tp: no free tid available\n"); + mempool_free(conn); + return -1; + } + + conn->sid = 1; + + memcpy(&conn->addr, &pack->addr, sizeof(pack->addr)); + conn->peer_tid = assigned_tid->val.uint16; + conn->framing_cap = framing_cap->val.uint32; + + conn->ctx.before_switch = log_switch; + conn->ctx.close = l2tp_conn_close; + conn->hnd.read = l2tp_conn_read; + conn->timeout_timer.expire = l2tp_timeout; + conn->timeout_timer.period = conf_timeout * 1000; + conn->rtimeout_timer.expire = l2tp_rtimeout; + conn->rtimeout_timer.period = conf_rtimeout * 1000; + conn->hello_timer.expire = l2tp_send_HELLO; + conn->hello_timer.period = conf_hello_interval * 1000; + conn->ctrl.ctx = &conn->ctx; + conn->ctrl.name = "l2tp"; + conn->ctrl.started = l2tp_ppp_started; + conn->ctrl.finished = l2tp_ppp_finished; + conn->ctrl.max_mtu = 1420; + + conn->ctrl.calling_station_id = _malloc(17); + conn->ctrl.called_station_id = _malloc(17); + u_inet_ntoa(conn->addr.sin_addr.s_addr, conn->ctrl.calling_station_id); + u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.called_station_id); + + ppp_init(&conn->ppp); + conn->ppp.ctrl = &conn->ctrl; + conn->ppp.fd = -1; + conn->tunnel_fd = -1; + + triton_context_register(&conn->ctx, &conn->ppp); + triton_md_register_handler(&conn->ctx, &conn->hnd); + triton_md_enable_handler(&conn->hnd, MD_MODE_READ); + triton_context_wakeup(&conn->ctx); + + if (conf_verbose) { + log_switch(&conn->ctx, &conn->ppp); + log_ppp_info2("recv "); + l2tp_packet_print(pack, log_ppp_info2); + } + + triton_context_call(&conn->ctx, (triton_event_func)l2tp_send_SCCRP, conn); + + __sync_add_and_fetch(&stat_starting, 1); + + return 0; + +out_err: + close(conn->hnd.fd); + mempool_free(conn); + return -1; +} + +static int l2tp_connect(struct l2tp_conn_t *conn) +{ + struct sockaddr_pppol2tp pppox_addr; + int arg = 1; + + memset(&pppox_addr, 0, sizeof(pppox_addr)); + pppox_addr.sa_family = AF_PPPOX; + pppox_addr.sa_protocol = PX_PROTO_OL2TP; + pppox_addr.pppol2tp.fd = conn->hnd.fd; + memcpy(&pppox_addr.pppol2tp.addr, &conn->addr, sizeof(conn->addr)); + pppox_addr.pppol2tp.s_tunnel = conn->tid; + pppox_addr.pppol2tp.d_tunnel = conn->peer_tid; + + conn->tunnel_fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP); + if (!conn->ppp.fd) { + log_ppp_error("l2tp: socket(AF_PPPOX): %s\n", strerror(errno)); + return -1; + } + + conn->ppp.fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP); + if (!conn->ppp.fd) { + close(conn->tunnel_fd); + conn->tunnel_fd = -1; + log_ppp_error("l2tp: socket(AF_PPPOX): %s\n", strerror(errno)); + return -1; + } + + if (connect(conn->tunnel_fd, (struct sockaddr *)&pppox_addr, sizeof(pppox_addr)) < 0) { + log_ppp_error("l2tp: connect(tunnel): %s\n", strerror(errno)); + return -1; + } + + pppox_addr.pppol2tp.s_session = conn->sid; + pppox_addr.pppol2tp.d_session = conn->peer_sid; + + if (connect(conn->ppp.fd, (struct sockaddr *)&pppox_addr, sizeof(pppox_addr)) < 0) { + log_ppp_error("l2tp: connect(session): %s\n", strerror(errno)); + return -1; + } + + if (setsockopt(conn->ppp.fd, SOL_PPPOL2TP, PPPOL2TP_SO_LNSMODE, &arg, sizeof(arg))) { + log_ppp_error("l2tp: setsockopt: %s\n", strerror(errno)); + return -1; + } + + conn->ppp.chan_name = _strdup(inet_ntoa(conn->addr.sin_addr)); + + triton_event_fire(EV_CTRL_STARTED, &conn->ppp); + + if (establish_ppp(&conn->ppp)) + return -1; + + __sync_sub_and_fetch(&stat_starting, 1); + __sync_add_and_fetch(&stat_active, 1); + + conn->state = STATE_PPP; + + return 0; +} + +static void l2tp_rtimeout(struct triton_timer_t *t) +{ + struct l2tp_conn_t *conn = container_of(t, typeof(*conn), rtimeout_timer); + struct l2tp_packet_t *pack; + + if (!list_empty(&conn->send_queue)) { + log_ppp_debug("l2tp: retransmit (%i)\n", conn->retransmit); + if (++conn->retransmit <= conf_retransmit) { + pack = list_entry(conn->send_queue.next, typeof(*pack), entry); + pack->hdr.Nr = htons(conn->Nr + 1); + if (conf_verbose) { + log_ppp_debug("send "); + l2tp_packet_print(pack, log_ppp_debug); + } + if (l2tp_packet_send(conn->hnd.fd, pack) == 0) + return; + } else + l2tp_disconnect(conn); + } +} + +static void l2tp_timeout(struct triton_timer_t *t) +{ + struct l2tp_conn_t *conn = container_of(t, typeof(*conn), timeout_timer); + log_ppp_debug("l2tp: timeout\n"); + l2tp_disconnect(conn); +} + +static int l2tp_send(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack, int log_debug) +{ + conn->retransmit = 0; + + pack->hdr.tid = htons(conn->peer_tid); + //pack->hdr.sid = htons(conn->peer_sid); + pack->hdr.Nr = htons(conn->Nr + 1); + pack->hdr.Ns = htons(conn->Ns); + + if (!list_empty(&pack->attrs)) + conn->Ns++; + + if (conf_verbose) { + if (log_debug) { + log_ppp_debug("send "); + l2tp_packet_print(pack, log_ppp_debug); + } else { + log_ppp_info2("send "); + l2tp_packet_print(pack, log_ppp_info2); + } + } + + if (l2tp_packet_send(conn->hnd.fd, pack)) + goto out_err; + + if (!list_empty(&pack->attrs)) { + list_add_tail(&pack->entry, &conn->send_queue); + if (!conn->rtimeout_timer.tpd) + triton_timer_add(&conn->ctx, &conn->rtimeout_timer, 0); + } else + l2tp_packet_free(pack); + + return 0; + +out_err: + l2tp_packet_free(pack); + return -1; +} + +static int l2tp_send_ZLB(struct l2tp_conn_t *conn) +{ + struct l2tp_packet_t *pack; + + pack = l2tp_packet_alloc(2, 0, &conn->addr); + if (!pack) + return -1; + + if (l2tp_send(conn, pack, 1)) + return -1; + + return 0; +} + +static void l2tp_send_HELLO(struct triton_timer_t *t) +{ + struct l2tp_conn_t *conn = container_of(t, typeof(*conn), hello_timer); + struct l2tp_packet_t *pack; + + pack = l2tp_packet_alloc(2, Message_Type_Hello, &conn->addr); + if (!pack) { + l2tp_disconnect(conn); + return; + } + + if (l2tp_send(conn, pack, 1)) + l2tp_disconnect(conn); +} + +static void l2tp_send_SCCRP(struct l2tp_conn_t *conn) +{ + struct l2tp_packet_t *pack; + + pack = l2tp_packet_alloc(2, Message_Type_Start_Ctrl_Conn_Reply, &conn->addr); + if (!pack) + goto out; + + if (l2tp_packet_add_int16(pack, Protocol_Version, L2TP_V2_PROTOCOL_VERSION, 1)) + goto out_err; + if (conf_host_name && l2tp_packet_add_string(pack, Host_Name, conf_host_name, 1)) + goto out_err; + if (l2tp_packet_add_int32(pack, Framing_Capabilities, conn->framing_cap, 1)) + goto out_err; + if (l2tp_packet_add_int16(pack, Assigned_Tunnel_ID, conn->tid, 1)) + goto out_err; + + if (l2tp_send(conn, pack, 0)) + goto out; + + if (!conn->timeout_timer.tpd) + triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); + else + triton_timer_mod(&conn->timeout_timer, 0); + + conn->state = STATE_WAIT_SCCCN; + + return; + +out_err: + l2tp_packet_free(pack); +out: + l2tp_disconnect(conn); +} + +static int l2tp_send_ICRP(struct l2tp_conn_t *conn) +{ + struct l2tp_packet_t *pack; + + pack = l2tp_packet_alloc(2, Message_Type_Incoming_Call_Reply, &conn->addr); + if (!pack) + return -1; + + pack->hdr.sid = htons(conn->peer_sid); + + if (l2tp_packet_add_int16(pack, Assigned_Session_ID, conn->sid, 1)) + goto out_err; + + l2tp_send(conn, pack, 0); + + if (!conn->timeout_timer.tpd) + triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); + else + triton_timer_mod(&conn->timeout_timer, 0); + + conn->state1 = STATE_WAIT_ICCN; + + return 0; + +out_err: + l2tp_packet_free(pack); + return -1; +} + +static int l2tp_send_OCRQ(struct l2tp_conn_t *conn) +{ + struct l2tp_packet_t *pack; + + pack = l2tp_packet_alloc(2, Message_Type_Outgoing_Call_Request, &conn->addr); + if (!pack) + return -1; + + pack->hdr.sid = htons(conn->peer_sid); + + if (l2tp_packet_add_int16(pack, Assigned_Session_ID, conn->sid, 1)) + goto out_err; + if (l2tp_packet_add_int32(pack, Call_Serial_Number, 0, 1)) + goto out_err; + if (l2tp_packet_add_int32(pack, Minimum_BPS, 100, 1)) + goto out_err; + if (l2tp_packet_add_int32(pack, Maximum_BPS, 100000, 1)) + goto out_err; + if (l2tp_packet_add_int32(pack, Bearer_Type, 3, 1)) + goto out_err; + if (l2tp_packet_add_int32(pack, Framing_Type, 3, 1)) + goto out_err; + if (l2tp_packet_add_string(pack, Called_Number, "", 1)) + goto out_err; + + if (l2tp_send(conn, pack, 0)) + return -1; + + if (!conn->timeout_timer.tpd) + triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); + else + triton_timer_mod(&conn->timeout_timer, 0); + + conn->state2 = STATE_WAIT_OCRP; + + return 0; + +out_err: + l2tp_packet_free(pack); + return -1; +} + + +static int l2tp_recv_SCCRQ(struct l2tp_serv_t *serv, struct l2tp_packet_t *pack, struct in_pktinfo *pkt_info) +{ + struct l2tp_attr_t *attr; + struct l2tp_attr_t *protocol_version = NULL; + struct l2tp_attr_t *assigned_tid = NULL; + struct l2tp_attr_t *assigned_cid = NULL; + struct l2tp_attr_t *framing_cap = NULL; + struct l2tp_attr_t *router_id = NULL; + + if (ppp_shutdown) + return 0; + + list_for_each_entry(attr, &pack->attrs, entry) { + switch (attr->attr->id) { + case Protocol_Version: + protocol_version = attr; + break; + case Framing_Capabilities: + framing_cap = attr; + break; + case Assigned_Tunnel_ID: + assigned_tid = attr; + break; + case Challenge: + if (conf_verbose) + log_warn("l2tp: Challenge in SCCRQ is not supported\n"); + return -1; + case Assigned_Connection_ID: + assigned_cid = attr; + break; + case Router_ID: + router_id = attr; + break; + case Message_Digest: + if (conf_verbose) + log_warn("l2tp: Message-Digest is not supported\n"); + return -1; + } + } + + if (assigned_tid) { + if (!protocol_version) { + if (conf_verbose) + log_warn("l2tp: SCCRQ: no Protocol-Version present in message\n"); + return -1; + } + if (protocol_version->val.uint16 != L2TP_V2_PROTOCOL_VERSION) { + if (conf_verbose) + log_warn("l2tp: protocol version %02x is not supported\n", protocol_version->val.uint16); + return -1; + } + if (!framing_cap) { + if (conf_verbose) + log_warn("l2tp: SCCRQ: no Framing-Capabilities present in message\n"); + return -1; + } + + if (l2tp_tunnel_alloc(serv, pack, pkt_info, assigned_tid, framing_cap)) + return -1; + + } else if (assigned_cid) { + // not yet implemented + return 0; + } else { + if (conf_verbose) + log_warn("l2tp: SCCRQ: no Assigned-Tunnel-ID or Assigned-Connection-ID present in message\n"); + return -1; + } + + return 0; +} + +static int l2tp_recv_SCCCN(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) +{ + if (conn->state == STATE_WAIT_SCCCN) { + triton_timer_mod(&conn->timeout_timer, 0); + conn->state = STATE_ESTB; + conn->state1 = STATE_WAIT_ICRQ; + } + else + log_ppp_warn("l2tp: unexpected SCCCN\n"); + + return 0; +} + +static int l2tp_recv_StopCCN(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) +{ + l2tp_send_ZLB(conn); + return -1; +} + +static int l2tp_recv_HELLO(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) +{ + if (l2tp_send_ZLB(conn)) + return -1; + + return 0; +} + +static int l2tp_recv_ICRQ(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) +{ + struct l2tp_attr_t *attr; + struct l2tp_attr_t *assigned_sid = NULL; + + if (conn->state1 != STATE_WAIT_ICRQ) { + log_ppp_warn("l2tp: unexpected ICRQ\n"); + return 0; + } + + list_for_each_entry(attr, &pack->attrs, entry) { + switch(attr->attr->id) { + case Assigned_Session_ID: + assigned_sid = attr; + break; + case Message_Type: + case Call_Serial_Number: + case Bearer_Type: + case Calling_Number: + case Called_Number: + case Sub_Address: + case Physical_Channel_ID: + break; + default: + if (attr->M) { + if (conf_verbose) { + log_ppp_warn("l2tp: ICRQ: unknown attribute %i\n", attr->attr->id); + if (l2tp_terminate(conn, 2, 8)) + return -1; + return 0; + } + } + } + } + + if (!assigned_sid) { + if (conf_verbose) + log_ppp_warn("l2tp: ICRQ: no Assigned-Session-ID attribute present in message\n"); + if (l2tp_terminate(conn, 2, 0)) + return -1; + } + + conn->peer_sid = assigned_sid->val.uint16; + + if (l2tp_send_ICRP(conn)) + return -1; + + if (l2tp_send_OCRQ(conn)) + return -1; + + return 0; +} + +static int l2tp_recv_ICCN(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) +{ + if (conn->state1 != STATE_WAIT_ICCN) { + log_ppp_warn("l2tp: unexpected ICCN\n"); + return 0; + } + + conn->state1 = STATE_ESTB; + + if (l2tp_connect(conn)) { + if (l2tp_terminate(conn, 2, 0)) + return -1; + return 0; + } + + if (l2tp_send_ZLB(conn)) + return -1; + + triton_timer_del(&conn->timeout_timer); + + return 0; +} + +static int l2tp_recv_OCRP(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) +{ + if (conn->state2 != STATE_WAIT_OCRP) { + log_ppp_warn("l2tp: unexpected OCRP\n"); + return 0; + } + + conn->state2 = STATE_WAIT_OCCN; + + return 0; +} + +static int l2tp_recv_OCCN(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) +{ + if (conn->state2 != STATE_WAIT_OCCN) { + log_ppp_warn("l2tp: unexpected OCCN\n"); + return 0; + } + + conn->state2 = STATE_ESTB; + + return 0; +} + +static int l2tp_recv_CDN(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) +{ + if (ntohs(pack->hdr.sid) != conn->sid) { + if (conf_verbose) + log_warn("l2tp: sid %i is incorrect\n", ntohs(pack->hdr.sid)); + return 0; + } + + if (conn->state == STATE_PPP) { + __sync_sub_and_fetch(&stat_active, 1); + conn->state = STATE_FIN; + ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); + } + + if (l2tp_terminate(conn, 0, 0)) + return -1; + + return 0; +} + +static int l2tp_recv_SLI(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) +{ + return 0; +} + +static int l2tp_conn_read(struct triton_md_handler_t *h) +{ + struct l2tp_conn_t *conn = container_of(h, typeof(*conn), hnd); + struct l2tp_packet_t *pack, *p; + struct l2tp_attr_t *msg_type; + + while (1) { + if (l2tp_recv(h->fd, &pack, NULL)) + return 0; + + if (!pack) + continue; + + if (ntohs(pack->hdr.tid) != conn->tid) { + if (conf_verbose) + log_warn("l2tp: incorrect tid %i in tunnel %i\n", ntohs(pack->hdr.tid), conn->tid); + l2tp_packet_free(pack); + continue; + } + + if (ntohs(pack->hdr.Ns) == conn->Nr + 1) { + if (!list_empty(&pack->attrs)) + conn->Nr++; + if (!list_empty(&conn->send_queue)) { + p = list_entry(conn->send_queue.next, typeof(*pack), entry); + list_del(&p->entry); + l2tp_packet_free(p); + conn->retransmit = 0; + } + if (!list_empty(&conn->send_queue)) + triton_timer_mod(&conn->rtimeout_timer, 0); + else { + if (conn->rtimeout_timer.tpd) + triton_timer_del(&conn->rtimeout_timer); + if (conn->state == STATE_FIN) + goto drop; + } + } else { + if (ntohs(pack->hdr.Ns) < conn->Nr + 1 || (ntohs(pack->hdr.Ns > 32767 && conn->Nr + 1 < 32767))) { + log_ppp_debug("duplicate packet\n"); + if (l2tp_send_ZLB(conn)) + goto drop; + } else + log_ppp_debug("reordered packet\n"); + l2tp_packet_free(pack); + continue; + } + + if (list_empty(&pack->attrs)) { + l2tp_packet_free(pack); + continue; + } + + msg_type = list_entry(pack->attrs.next, typeof(*msg_type), entry); + + if (msg_type->attr->id != Message_Type) { + if (conf_verbose) + log_ppp_error("l2tp: first attribute is not Message-Type, dropping connection...\n"); + goto drop; + } + + if (conf_verbose) { + if (msg_type->val.uint16 == Message_Type_Hello) { + log_ppp_debug("recv "); + l2tp_packet_print(pack, log_ppp_debug); + } else { + log_ppp_info2("recv "); + l2tp_packet_print(pack, log_ppp_info2); + } + } + + switch (msg_type->val.uint16) { + case Message_Type_Start_Ctrl_Conn_Connected: + if (l2tp_recv_SCCCN(conn, pack)) + goto drop; + break; + case Message_Type_Stop_Ctrl_Conn_Notify: + if (l2tp_recv_StopCCN(conn, pack)) + goto drop; + break; + case Message_Type_Hello: + if (l2tp_recv_HELLO(conn, pack)) + goto drop; + break; + case Message_Type_Incoming_Call_Request: + if (l2tp_recv_ICRQ(conn, pack)) + goto drop; + break; + case Message_Type_Incoming_Call_Connected: + if (l2tp_recv_ICCN(conn, pack)) + goto drop; + break; + case Message_Type_Outgoing_Call_Reply: + if (l2tp_recv_OCRP(conn, pack)) + goto drop; + break; + case Message_Type_Outgoing_Call_Connected: + if (l2tp_recv_OCCN(conn, pack)) + goto drop; + break; + case Message_Type_Call_Disconnect_Notify: + if (l2tp_recv_CDN(conn, pack)) + goto drop; + break; + case Message_Type_Set_Link_Info: + if (l2tp_recv_SLI(conn, pack)) + goto drop; + break; + case Message_Type_Start_Ctrl_Conn_Request: + case Message_Type_Start_Ctrl_Conn_Reply: + case Message_Type_Outgoing_Call_Request: + case Message_Type_Incoming_Call_Reply: + case Message_Type_WAN_Error_Notify: + if (conf_verbose) + log_warn("l2tp: unexpected Message-Type %i\n", msg_type->val.uint16); + break; + default: + if (conf_verbose) + log_warn("l2tp: unknown Message-Type %i\n", msg_type->val.uint16); + if (msg_type->M) { + if (l2tp_terminate(conn, 2, 8)) + goto drop; + } + } + + l2tp_packet_free(pack); + } + +drop: + l2tp_packet_free(pack); + l2tp_disconnect(conn); + return -1; +} + +static int l2tp_udp_read(struct triton_md_handler_t *h) +{ + struct l2tp_serv_t *serv = container_of(h, typeof(*serv), hnd); + struct l2tp_packet_t *pack; + struct l2tp_attr_t *msg_type; + struct in_pktinfo pkt_info; + + while (1) { + if (l2tp_recv(h->fd, &pack, &pkt_info)) + break; + + if (!pack) + continue; + + if (iprange_client_check(pack->addr.sin_addr.s_addr)) { + log_warn("l2tp: IP is out of client-ip-range, droping connection...\n"); + goto skip; + } + + if (pack->hdr.tid) + goto skip; + + if (list_empty(&pack->attrs)) { + if (conf_verbose) + log_warn("l2tp: to Message-Type attribute present\n"); + goto skip; + } + + msg_type = list_entry(pack->attrs.next, typeof(*msg_type), entry); + if (msg_type->attr->id != Message_Type) { + if (conf_verbose) + log_warn("l2tp: first attribute is not Message-Type\n"); + goto skip; + } + + if (msg_type->val.uint16 == Message_Type_Start_Ctrl_Conn_Request) + l2tp_recv_SCCRQ(serv, pack, &pkt_info); + else { + if (conf_verbose) { + log_warn("recv (unexpected) "); + l2tp_packet_print(pack, log_ppp_warn); + } + } +skip: + l2tp_packet_free(pack); + } + + return 0; +} + +static void l2tp_udp_close(struct triton_context_t *ctx) +{ + struct l2tp_serv_t *serv = container_of(ctx, typeof(*serv), ctx); + triton_md_unregister_handler(&serv->hnd); + close(serv->hnd.fd); + triton_context_unregister(&serv->ctx); +} + +static struct l2tp_serv_t udp_serv = +{ + .hnd.read = l2tp_udp_read, + .ctx.close = l2tp_udp_close, + .ctx.before_switch = log_switch, +}; + +/*static struct l2tp_serv_t ip_serv = +{ + .hnd.read=l2t_ip_read, + .ctx.close=l2tp_ip_close, +};*/ + +static void start_udp_server(void) +{ + struct sockaddr_in addr; + char *opt; + int flag = 1; + + udp_serv.hnd.fd = socket(PF_INET, SOCK_DGRAM, 0); + if (udp_serv.hnd.fd < 0) { + log_emerg("l2tp: socket: %s\n", strerror(errno)); + return; + } + + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_port = htons(L2TP_PORT); + + opt = conf_get_opt("l2tp", "bind"); + if (opt) + addr.sin_addr.s_addr = inet_addr(opt); + else + addr.sin_addr.s_addr = htonl(INADDR_ANY); + + setsockopt(udp_serv.hnd.fd, SOL_SOCKET, SO_REUSEADDR, &udp_serv.hnd.fd, sizeof(udp_serv.hnd.fd)); + setsockopt(udp_serv.hnd.fd, SOL_SOCKET, SO_NO_CHECK, &udp_serv.hnd.fd, sizeof(udp_serv.hnd.fd)); + + if (bind (udp_serv.hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { + log_emerg("l2tp: bind: %s\n", strerror(errno)); + close(udp_serv.hnd.fd); + return; + } + + if (fcntl(udp_serv.hnd.fd, F_SETFL, O_NONBLOCK)) { + log_emerg("l2tp: failed to set nonblocking mode: %s\n", strerror(errno)); + close(udp_serv.hnd.fd); + return; + } + + if (setsockopt(udp_serv.hnd.fd, IPPROTO_IP, IP_PKTINFO, &flag, sizeof(flag))) { + log_emerg("l2tp: setsockopt(IP_PKTINFO): %s\n", strerror(errno)); + close(udp_serv.hnd.fd); + return; + } + + memcpy(&udp_serv.addr, &addr, sizeof(addr)); + + triton_context_register(&udp_serv.ctx, NULL); + triton_md_register_handler(&udp_serv.ctx, &udp_serv.hnd); + triton_md_enable_handler(&udp_serv.hnd, MD_MODE_READ); + triton_context_wakeup(&udp_serv.ctx); +} + +static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "l2tp:\r\n"); + cli_sendv(client, " starting: %u\r\n", stat_starting); + cli_sendv(client, " active: %u\r\n", stat_active); + + return CLI_CMD_OK; +} + +static void load_config(void) +{ + char *opt; + + opt = conf_get_opt("l2tp", "verbose"); + if (opt && atoi(opt) > 0) + conf_verbose = 1; + + opt = conf_get_opt("l2tp", "hello-interval"); + if (opt && atoi(opt) > 0) + conf_hello_interval = atoi(opt); + + opt = conf_get_opt("l2tp", "timeout"); + if (opt && atoi(opt) > 0) + conf_timeout = atoi(opt); + + opt = conf_get_opt("l2tp", "rtimeout"); + if (opt && atoi(opt) > 0) + conf_rtimeout = atoi(opt); + + opt = conf_get_opt("l2tp", "retransmit"); + if (opt && atoi(opt) > 0) + conf_retransmit = atoi(opt); + + if (conf_host_name) + _free(conf_host_name); + opt = conf_get_opt("l2tp", "host-name"); + if (opt) + conf_host_name = _strdup(opt); + else + conf_host_name = NULL; +} + +static void __init l2tp_init(void) +{ + l2tp_conn = malloc(L2TP_MAX_TID * sizeof(void *)); + memset(l2tp_conn, 0, L2TP_MAX_TID * sizeof(void *)); + + l2tp_conn_pool = mempool_create(sizeof(struct l2tp_conn_t)); + + load_config(); + + start_udp_server(); + + cli_register_simple_cmd2(&show_stat_exec, NULL, 2, "show", "stat"); + + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); +} + diff --git a/accel-pppd/ctrl/l2tp/l2tp.h b/accel-pppd/ctrl/l2tp/l2tp.h new file mode 100644 index 0000000..ac9b8e0 --- /dev/null +++ b/accel-pppd/ctrl/l2tp/l2tp.h @@ -0,0 +1,88 @@ +#ifndef __L2TP_H +#define __L2TP_H + +#include + +#include "list.h" +#include "l2tp_prot.h" + +#define ATTR_TYPE_NONE 0 +#define ATTR_TYPE_INT16 1 +#define ATTR_TYPE_INT32 2 +#define ATTR_TYPE_INT64 3 +#define ATTR_TYPE_OCTETS 4 +#define ATTR_TYPE_STRING 5 + +#define L2TP_MAX_PACKET_SIZE 65536 +#define L2TP_MAX_TID 65534 + +#define L2TP_V2_PROTOCOL_VERSION ( 1 << 8 | 0 ) + +typedef union +{ + uint32_t uint32; + int32_t int32; + uint16_t uint16; + int16_t int16; + uint64_t uint64; + uint8_t *octets; + char *string; +} l2tp_value_t; + +struct l2tp_dict_attr_t +{ + struct list_head entry; + const char *name; + int id; + int type; + int M; + int H; + struct list_head values; +}; + +struct l2tp_dict_value_t +{ + struct list_head entry; + const char *name; + l2tp_value_t val; +}; + +struct l2tp_attr_t +{ + struct list_head entry; + struct l2tp_dict_attr_t *attr; + int M:1; + int H:1; + int length; + l2tp_value_t val; +}; + +struct l2tp_packet_t +{ + struct list_head entry; + struct sockaddr_in addr; + struct l2tp_hdr_t hdr; + struct list_head attrs; +}; + +extern int conf_verbose; + +struct l2tp_dict_attr_t *l2tp_dict_find_attr_by_name(const char *name); +struct l2tp_dict_attr_t *l2tp_dict_find_attr_by_id(int id); +struct l2tp_dict_value_t *l2tp_dict_find_value(struct l2tp_dict_attr_t *attr, l2tp_value_t val); + +int l2tp_recv(int fd, struct l2tp_packet_t **, struct in_pktinfo *); +void l2tp_packet_free(struct l2tp_packet_t *); +void l2tp_packet_print(struct l2tp_packet_t *, void (*print)(const char *fmt, ...)); +struct l2tp_packet_t *l2tp_packet_alloc(int ver, int msg_type, struct sockaddr_in *addr); +int l2tp_packet_send(int sock, struct l2tp_packet_t *); +int l2tp_packet_add_int16(struct l2tp_packet_t *pack, int id, int16_t val, int M); +int l2tp_packet_add_int32(struct l2tp_packet_t *pack, int id, int32_t val, int M); +int l2tp_packet_add_string(struct l2tp_packet_t *pack, int id, const char *val, int M); +int l2tp_packet_add_octets(struct l2tp_packet_t *pack, int id, const uint8_t *val, int size, int M); + +void l2tp_nl_create_tunnel(int fd, int tid, int peer_tid); +void l2tp_nl_create_session(int tid, int sid, int peer_sid); +void l2tp_nl_delete_tunnel(int tid); + +#endif diff --git a/accel-pppd/ctrl/l2tp/l2tp_kernel.h b/accel-pppd/ctrl/l2tp/l2tp_kernel.h new file mode 100644 index 0000000..4bdb31d --- /dev/null +++ b/accel-pppd/ctrl/l2tp/l2tp_kernel.h @@ -0,0 +1,163 @@ +/* + * L2TP-over-IP socket for L2TPv3. + * + * Author: James Chapman + */ + +#ifndef _LINUX_L2TP_H_ +#define _LINUX_L2TP_H_ + +#include +#ifdef __KERNEL__ +#include +#include +#else +#include +#endif + +#define IPPROTO_L2TP 115 + +/** + * struct sockaddr_l2tpip - the sockaddr structure for L2TP-over-IP sockets + * @l2tp_family: address family number AF_L2TPIP. + * @l2tp_addr: protocol specific address information + * @l2tp_conn_id: connection id of tunnel + */ +#define __SOCK_SIZE__ 16 /* sizeof(struct sockaddr) */ +struct sockaddr_l2tpip { + /* The first fields must match struct sockaddr_in */ + sa_family_t l2tp_family; /* AF_INET */ + __be16 l2tp_unused; /* INET port number (unused) */ + struct in_addr l2tp_addr; /* Internet address */ + + __u32 l2tp_conn_id; /* Connection ID of tunnel */ + + /* Pad to size of `struct sockaddr'. */ + unsigned char __pad[sizeof(struct sockaddr) - sizeof(sa_family_t) - + sizeof(__be16) - sizeof(struct in_addr) - + sizeof(__u32)]; +}; + +/***************************************************************************** + * NETLINK_GENERIC netlink family. + *****************************************************************************/ + +/* + * Commands. + * Valid TLVs of each command are:- + * TUNNEL_CREATE - CONN_ID, pw_type, netns, ifname, ipinfo, udpinfo, udpcsum, vlanid + * TUNNEL_DELETE - CONN_ID + * TUNNEL_MODIFY - CONN_ID, udpcsum + * TUNNEL_GETSTATS - CONN_ID, (stats) + * TUNNEL_GET - CONN_ID, (...) + * SESSION_CREATE - SESSION_ID, PW_TYPE, offset, data_seq, cookie, peer_cookie, offset, l2spec + * SESSION_DELETE - SESSION_ID + * SESSION_MODIFY - SESSION_ID, data_seq + * SESSION_GET - SESSION_ID, (...) + * SESSION_GETSTATS - SESSION_ID, (stats) + * + */ +enum { + L2TP_CMD_NOOP, + L2TP_CMD_TUNNEL_CREATE, + L2TP_CMD_TUNNEL_DELETE, + L2TP_CMD_TUNNEL_MODIFY, + L2TP_CMD_TUNNEL_GET, + L2TP_CMD_SESSION_CREATE, + L2TP_CMD_SESSION_DELETE, + L2TP_CMD_SESSION_MODIFY, + L2TP_CMD_SESSION_GET, + __L2TP_CMD_MAX, +}; + +#define L2TP_CMD_MAX (__L2TP_CMD_MAX - 1) + +/* + * ATTR types defined for L2TP + */ +enum { + L2TP_ATTR_NONE, /* no data */ + L2TP_ATTR_PW_TYPE, /* u16, enum l2tp_pwtype */ + L2TP_ATTR_ENCAP_TYPE, /* u16, enum l2tp_encap_type */ + L2TP_ATTR_OFFSET, /* u16 */ + L2TP_ATTR_DATA_SEQ, /* u16 */ + L2TP_ATTR_L2SPEC_TYPE, /* u8, enum l2tp_l2spec_type */ + L2TP_ATTR_L2SPEC_LEN, /* u8, enum l2tp_l2spec_type */ + L2TP_ATTR_PROTO_VERSION, /* u8 */ + L2TP_ATTR_IFNAME, /* string */ + L2TP_ATTR_CONN_ID, /* u32 */ + L2TP_ATTR_PEER_CONN_ID, /* u32 */ + L2TP_ATTR_SESSION_ID, /* u32 */ + L2TP_ATTR_PEER_SESSION_ID, /* u32 */ + L2TP_ATTR_UDP_CSUM, /* u8 */ + L2TP_ATTR_VLAN_ID, /* u16 */ + L2TP_ATTR_COOKIE, /* 0, 4 or 8 bytes */ + L2TP_ATTR_PEER_COOKIE, /* 0, 4 or 8 bytes */ + L2TP_ATTR_DEBUG, /* u32 */ + L2TP_ATTR_RECV_SEQ, /* u8 */ + L2TP_ATTR_SEND_SEQ, /* u8 */ + L2TP_ATTR_LNS_MODE, /* u8 */ + L2TP_ATTR_USING_IPSEC, /* u8 */ + L2TP_ATTR_RECV_TIMEOUT, /* msec */ + L2TP_ATTR_FD, /* int */ + L2TP_ATTR_IP_SADDR, /* u32 */ + L2TP_ATTR_IP_DADDR, /* u32 */ + L2TP_ATTR_UDP_SPORT, /* u16 */ + L2TP_ATTR_UDP_DPORT, /* u16 */ + L2TP_ATTR_MTU, /* u16 */ + L2TP_ATTR_MRU, /* u16 */ + L2TP_ATTR_STATS, /* nested */ + __L2TP_ATTR_MAX, +}; + +#define L2TP_ATTR_MAX (__L2TP_ATTR_MAX - 1) + +/* Nested in L2TP_ATTR_STATS */ +enum { + L2TP_ATTR_STATS_NONE, /* no data */ + L2TP_ATTR_TX_PACKETS, /* u64 */ + L2TP_ATTR_TX_BYTES, /* u64 */ + L2TP_ATTR_TX_ERRORS, /* u64 */ + L2TP_ATTR_RX_PACKETS, /* u64 */ + L2TP_ATTR_RX_BYTES, /* u64 */ + L2TP_ATTR_RX_SEQ_DISCARDS, /* u64 */ + L2TP_ATTR_RX_OOS_PACKETS, /* u64 */ + L2TP_ATTR_RX_ERRORS, /* u64 */ + __L2TP_ATTR_STATS_MAX, +}; + +#define L2TP_ATTR_STATS_MAX (__L2TP_ATTR_STATS_MAX - 1) + +enum l2tp_pwtype { + L2TP_PWTYPE_NONE = 0x0000, + L2TP_PWTYPE_ETH_VLAN = 0x0004, + L2TP_PWTYPE_ETH = 0x0005, + L2TP_PWTYPE_PPP = 0x0007, + L2TP_PWTYPE_PPP_AC = 0x0008, + L2TP_PWTYPE_IP = 0x000b, + __L2TP_PWTYPE_MAX +}; + +enum l2tp_l2spec_type { + L2TP_L2SPECTYPE_NONE, + L2TP_L2SPECTYPE_DEFAULT, +}; + +enum l2tp_encap_type { + L2TP_ENCAPTYPE_UDP, + L2TP_ENCAPTYPE_IP, +}; + +enum l2tp_seqmode { + L2TP_SEQ_NONE = 0, + L2TP_SEQ_IP = 1, + L2TP_SEQ_ALL = 2, +}; + +/* + * NETLINK_GENERIC related info + */ +#define L2TP_GENL_NAME "l2tp" +#define L2TP_GENL_VERSION 0x1 + +#endif diff --git a/accel-pppd/ctrl/l2tp/l2tp_prot.h b/accel-pppd/ctrl/l2tp/l2tp_prot.h new file mode 100644 index 0000000..1c1d9da --- /dev/null +++ b/accel-pppd/ctrl/l2tp/l2tp_prot.h @@ -0,0 +1,55 @@ +#ifndef __L2TP_PROT_H +#define __L2TP_PROT_H + +#include + +#define L2TP_PORT 1701 + +struct l2tp_hdr_t +{ + uint8_t P:1; + uint8_t O:1; + uint8_t reserved2:1; + uint8_t S:1; + uint8_t reserved1:2; + uint8_t L:1; + uint8_t T:1; + uint8_t ver:4; + uint8_t reserved3:4; + uint16_t length; + union { + struct { + uint16_t tid; + uint16_t sid; + }; + uint32_t cid; + }; + uint16_t Ns; + uint16_t Nr; +} __attribute__((packed)); + +/*#define L2TP_T(hdr) (hdr->flags >> 15) +#define L2TP_L(hdr) ((hdr->flags >> 14) & 1) +#define L2TP_S(hdr) ((hdr->flags >> 10) & 1) +#define L2TP_O(hdr) ((hdr->flags >> 8) & 1) +#define L2TP_VER(hdr) (hdr->flags & 0xf)*/ + +struct l2tp_avp_t +{ + uint16_t length:10; + uint16_t reserved:4; + uint16_t H:1; + uint16_t M:1; + uint16_t vendor; + uint16_t type; + uint8_t val[0]; +} __attribute__((packed)); + +struct l2tp_avp_result_code +{ + uint16_t result_code; + uint16_t error_code; +} __attribute__((packed)); + +#endif + diff --git a/accel-pppd/ctrl/l2tp/netlink.c b/accel-pppd/ctrl/l2tp/netlink.c new file mode 100644 index 0000000..7c8c79a --- /dev/null +++ b/accel-pppd/ctrl/l2tp/netlink.c @@ -0,0 +1,94 @@ +#include +#include +#include + +#include "l2tp_kernel.h" +#include "triton.h" + +static int family; + +void l2tp_nl_delete_tunnel(int tid) +{ + struct nl_sock *nl_sock; + struct nl_msg *msg; + + nl_sock = nl_socket_alloc(); + msg = nlmsg_alloc(); + + genl_connect(nl_sock); + + genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_REQUEST, L2TP_CMD_TUNNEL_DELETE, L2TP_GENL_VERSION); + nla_put_u32(msg, L2TP_ATTR_CONN_ID, tid); + + nl_send_auto_complete(nl_sock, msg); + nl_recvmsgs_default(nl_sock); + + nlmsg_free(msg); + nl_close(nl_sock); + nl_socket_free(nl_sock); +} + +void l2tp_nl_create_tunnel(int fd, int tid, int peer_tid) +{ + struct nl_sock *nl_sock; + struct nl_msg *msg; + + nl_sock = nl_socket_alloc(); + msg = nlmsg_alloc(); + + genl_connect(nl_sock); + + genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_REQUEST, L2TP_CMD_TUNNEL_CREATE, L2TP_GENL_VERSION); + nla_put_u16(msg, L2TP_ATTR_ENCAP_TYPE, L2TP_ENCAPTYPE_UDP); + nla_put_u8(msg, L2TP_ATTR_PROTO_VERSION, 2); + nla_put_u32(msg, L2TP_ATTR_CONN_ID, tid); + nla_put_u32(msg, L2TP_ATTR_PEER_CONN_ID, peer_tid); + nla_put_u32(msg, L2TP_ATTR_FD, fd); + //nla_put_u32(msg, L2TP_ATTR_DEBUG, 0xffffffff); + + nl_send_auto_complete(nl_sock, msg); + nl_recvmsgs_default(nl_sock); + + nlmsg_free(msg); + nl_close(nl_sock); + nl_socket_free(nl_sock); +} + +void l2tp_nl_create_session(int tid, int sid, int peer_sid) +{ + struct nl_sock *nl_sock; + struct nl_msg *msg; + + nl_sock = nl_socket_alloc(); + msg = nlmsg_alloc(); + + genl_connect(nl_sock); + + genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_REQUEST, L2TP_CMD_SESSION_CREATE, L2TP_GENL_VERSION); + nla_put_u32(msg, L2TP_ATTR_CONN_ID, tid); + nla_put_u32(msg, L2TP_ATTR_SESSION_ID, sid); + nla_put_u32(msg, L2TP_ATTR_PEER_SESSION_ID, peer_sid); + nla_put_u16(msg, L2TP_ATTR_PW_TYPE, L2TP_PWTYPE_PPP); + nla_put_u8(msg, L2TP_ATTR_LNS_MODE, 1); + //nla_put_u32(msg, L2TP_ATTR_DEBUG, 0xffffffff); + + nl_send_auto_complete(nl_sock, msg); + nl_recvmsgs_default(nl_sock); + + nlmsg_free(msg); + nl_close(nl_sock); + nl_socket_free(nl_sock); +} + +static void __init init(void) +{ + struct nl_sock *nl_sock = nl_socket_alloc(); + + genl_connect(nl_sock); + + family = genl_ctrl_resolve(nl_sock, L2TP_GENL_NAME); + + nl_close(nl_sock); + nl_socket_free(nl_sock); +} + diff --git a/accel-pppd/ctrl/l2tp/packet.c b/accel-pppd/ctrl/l2tp/packet.c new file mode 100644 index 0000000..e3f6896 --- /dev/null +++ b/accel-pppd/ctrl/l2tp/packet.c @@ -0,0 +1,494 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "triton.h" +#include "log.h" +#include "mempool.h" +#include "memdebug.h" + +#include "l2tp.h" +#include "attr_defs.h" + +static mempool_t attr_pool; +static mempool_t pack_pool; +static mempool_t buf_pool; + +void l2tp_packet_print(struct l2tp_packet_t *pack, void (*print)(const char *fmt, ...)) +{ + struct l2tp_attr_t *attr; + struct l2tp_dict_value_t *val; + + if (pack->hdr.ver == 2) { + print("[L2TP tid=%i sid=%i", ntohs(pack->hdr.tid), ntohs(pack->hdr.sid)); + log_ppp_debug(" Ns=%i Nr=%i", ntohs(pack->hdr.Ns), ntohs(pack->hdr.Nr)); + } else { + print("[L2TP cid=%u", pack->hdr.cid); + log_ppp_debug(" Ns=%i Nr=%i", ntohs(pack->hdr.Ns), ntohs(pack->hdr.Nr)); + } + + list_for_each_entry(attr, &pack->attrs, entry) { + print(" <%s", attr->attr->name); + val = l2tp_dict_find_value(attr->attr, attr->val); + if (val) + print(" %s", val->name); + else { + switch (attr->attr->type) { + case ATTR_TYPE_INT16: + print(" %i", attr->val.int16); + break; + case ATTR_TYPE_INT32: + print(" %i", attr->val.int32); + break; + case ATTR_TYPE_STRING: + print(" %s", attr->val.string); + break; + } + } + print(">"); + } + + print("]\n"); +} + +struct l2tp_packet_t *l2tp_packet_alloc(int ver, int msg_type, struct sockaddr_in *addr) +{ + struct l2tp_packet_t *pack = mempool_alloc(pack_pool); + if (!pack) + return NULL; + + memset(pack, 0, sizeof(*pack)); + INIT_LIST_HEAD(&pack->attrs); + pack->hdr.ver = ver; + pack->hdr.T = 1; + pack->hdr.L = 1; + pack->hdr.S = 1; + memcpy(&pack->addr, addr, sizeof(*addr)); + + if (msg_type) { + if (l2tp_packet_add_int16(pack, Message_Type, msg_type, 1)) { + mempool_free(pack); + return NULL; + } + } + + return pack; +} + +void l2tp_packet_free(struct l2tp_packet_t *pack) +{ + struct l2tp_attr_t *attr; + + while (!list_empty(&pack->attrs)) { + attr = list_entry(pack->attrs.next, typeof(*attr), entry); + if (attr->attr->type == ATTR_TYPE_OCTETS || attr->attr->type == ATTR_TYPE_STRING) + _free(attr->val.octets); + list_del(&attr->entry); + mempool_free(attr); + } + + mempool_free(pack); +} + +int l2tp_recv(int fd, struct l2tp_packet_t **p, struct in_pktinfo *pkt_info) +{ + int n, length; + uint8_t *buf; + struct l2tp_hdr_t *hdr; + struct l2tp_avp_t *avp; + struct l2tp_dict_attr_t *da; + struct l2tp_attr_t *attr, *RV = NULL; + uint8_t *ptr; + struct l2tp_packet_t *pack; + struct sockaddr_in addr; + socklen_t len = sizeof(addr); + struct msghdr msg; + char msg_control[128]; + struct cmsghdr *cmsg; + + *p = NULL; + + if (pkt_info) { + memset(&msg, 0, sizeof(msg)); + msg.msg_control = msg_control; + msg.msg_controllen = 128; + + n = recvmsg(fd, &msg, MSG_PEEK); + + if (n < 0) { + if (errno == EAGAIN) + return -1; + log_error("l2tp: recvmsg: %s\n", strerror(errno)); + return 0; + } + + for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) { + if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO) { + memcpy(pkt_info, CMSG_DATA(cmsg), sizeof(*pkt_info)); + break; + } + } + } + + buf = mempool_alloc(buf_pool); + if (!buf) { + log_emerg("l2tp: out of memory\n"); + return 0; + } + hdr = (struct l2tp_hdr_t *)buf; + ptr = (uint8_t *)(hdr + 1); + + n = recvfrom(fd, buf, L2TP_MAX_PACKET_SIZE, 0, &addr, &len); + + if (n < 0) { + mempool_free(buf); + if (errno == EAGAIN) + return -1; + log_error("l2tp: recv: %s\n", strerror(errno)); + return 0; + } + + if (n < sizeof(*hdr)) { + if (conf_verbose) + log_warn("l2tp: short packet received (%i/%i)\n", n, sizeof(*hdr)); + goto out_err_hdr; + } + + if (n < ntohs(hdr->length)) { + if (conf_verbose) + log_warn("l2tp: short packet received (%i/%i)\n", n, ntohs(hdr->length)); + goto out_err_hdr; + } + + if (hdr->T == 0) + goto out_err_hdr; + + if (hdr->ver == 2) { + if (hdr->L == 0) { + if (conf_verbose) + log_warn("l2tp: incorrect message received (L=0)\n"); + goto out_err_hdr; + } + + if (hdr->S == 0) { + if (conf_verbose) + log_warn("l2tp: incorrect message received (S=0)\n"); + goto out_err_hdr; + } + + if (hdr->O == 1) { + if (conf_verbose) + log_warn("l2tp: incorrect message received (O=1)\n"); + goto out_err_hdr; + } + } else if (hdr->ver != 3) { + if (conf_verbose) + log_warn("l2tp: protocol version %i is not supported\n", hdr->ver); + goto out_err_hdr; + } + + pack = mempool_alloc(pack_pool); + if (!pack) { + log_emerg("l2tp: out of memory\n"); + goto out_err_hdr; + } + + memset(pack, 0, sizeof(*pack)); + INIT_LIST_HEAD(&pack->attrs); + + memcpy(&pack->addr, &addr, sizeof(addr)); + memcpy(&pack->hdr, hdr, sizeof(*hdr)); + length = ntohs(hdr->length) - sizeof(*hdr); + + while (length) { + *(uint16_t *)ptr = ntohs(*(uint16_t *)ptr); + avp = (struct l2tp_avp_t *)ptr; + + if (avp->length > length) { + if (conf_verbose) + log_warn("l2tp: incorrect avp received (exceeds message length)\n"); + goto out_err; + } + + if (avp->vendor) + goto skip; + + da = l2tp_dict_find_attr_by_id(ntohs(avp->type)); + if (!da) { + if (conf_verbose) + log_warn("l2tp: unknown avp received (type=%i, M=%u)\n", ntohs(avp->type), avp->M); + if (avp->M) + goto out_err; + } else { + if (da->M != -1 && da->M != avp->M) { + if (conf_verbose) + log_warn("l2tp: incorrect avp received (type=%i, M=%i, must be %i)\n", ntohs(avp->type), avp->M, da->M); + goto out_err; + } + + if (da->H != -1 && da->H != avp->H) { + if (conf_verbose) + log_warn("l2tp: incorrect avp received (type=%i, H=%i, must be %i)\n", ntohs(avp->type), avp->H, da->H); + goto out_err; + } + + if (avp->H) { + if (!RV) { + if (conf_verbose) + log_warn("l2tp: incorrect avp received (type=%i, H=1, but Random-Vector is not received)\n", ntohs(avp->type)); + goto out_err; + } else { + if (conf_verbose) + log_warn("l2tp: hidden avp received (type=%i)\n", ntohs(avp->type)); + } + } + + attr = mempool_alloc(attr_pool); + memset(attr, 0, sizeof(*attr)); + list_add_tail(&attr->entry, &pack->attrs); + + attr->attr = da; + attr->M = avp->M; + attr->H = avp->H; + attr->length = avp->length - sizeof(*avp); + + if (attr->attr->id == Random_Vector) + RV = attr; + + switch (da->type) { + case ATTR_TYPE_INT16: + if (avp->length != sizeof(*avp) + 2) + goto out_err_len; + attr->val.uint16 = ntohs(*(uint16_t *)avp->val); + break; + case ATTR_TYPE_INT32: + if (avp->length != sizeof(*avp) + 4) + goto out_err_len; + attr->val.uint32 = ntohl(*(uint32_t *)avp->val); + break; + case ATTR_TYPE_INT64: + if (avp->length != sizeof(*avp) + 8) + goto out_err_len; + attr->val.uint64 = *(uint64_t *)avp->val; + break; + case ATTR_TYPE_OCTETS: + attr->val.octets = _malloc(attr->length); + if (!attr->val.octets) + goto out_err_mem; + memcpy(attr->val.octets, avp->val, attr->length); + break; + case ATTR_TYPE_STRING: + attr->val.string = _malloc(attr->length + 1); + if (!attr->val.string) + goto out_err_mem; + memcpy(attr->val.string, avp->val, attr->length); + attr->val.string[attr->length] = 0; + break; + } + } +skip: + ptr += avp->length; + length -= avp->length; + } + + *p = pack; + + mempool_free(buf); + + return 0; + +out_err: + l2tp_packet_free(pack); +out_err_hdr: + mempool_free(buf); + return 0; +out_err_len: + if (conf_verbose) + log_warn("l2tp: incorrect avp received (type=%i, incorrect length %i)\n", ntohs(avp->type), avp->length); + goto out_err; +out_err_mem: + log_emerg("l2tp: out of memory\n"); + goto out_err; +} + +int l2tp_packet_send(int sock, struct l2tp_packet_t *pack) +{ + uint8_t *buf = mempool_alloc(buf_pool); + struct l2tp_avp_t *avp; + struct l2tp_attr_t *attr; + uint8_t *ptr; + int n; + int len = sizeof(pack->hdr); + + if (!buf) { + log_emerg("l2tp: out of memory\n"); + return -1; + } + + memset(buf, 0, L2TP_MAX_PACKET_SIZE); + + ptr = buf + sizeof(pack->hdr); + + list_for_each_entry(attr, &pack->attrs, entry) { + if (len + sizeof(*avp) + attr->length >= L2TP_MAX_PACKET_SIZE) { + log_error("l2tp: cann't send packet (exceeds maximum size)\n"); + mempool_free(buf); + return -1; + } + avp = (struct l2tp_avp_t *)ptr; + avp->type = htons(attr->attr->id); + avp->M = attr->M; + avp->H = attr->H; + avp->length = sizeof(*avp) + attr->length; + *(uint16_t *)ptr = htons(*(uint16_t *)ptr); + switch (attr->attr->type) { + case ATTR_TYPE_INT16: + *(int16_t *)avp->val = htons(attr->val.int16); + break; + case ATTR_TYPE_INT32: + *(int32_t *)avp->val = htonl(attr->val.int32); + break; + case ATTR_TYPE_STRING: + case ATTR_TYPE_OCTETS: + memcpy(avp->val, attr->val.string, attr->length); + break; + } + + ptr += sizeof(*avp) + attr->length; + len += sizeof(*avp) + attr->length; + } + + pack->hdr.length = htons(len); + memcpy(buf, &pack->hdr, sizeof(pack->hdr)); + + n = write(sock, buf, ntohs(pack->hdr.length)); + + mempool_free(buf); + + if (n < 0) { + if (errno == EAGAIN) { + if (conf_verbose) + log_warn("l2tp: buffer overflow (packet lost)\n"); + } else { + if (conf_verbose) + log_warn("l2tp: sendto: %s\n", strerror(errno)); + return -1; + } + } + + if (n != ntohs(pack->hdr.length)) { + if (conf_verbose) + log_warn("l2tp: short write (%i/%i)\n", n, ntohs(pack->hdr.length)); + } + + return 0; +} + +static struct l2tp_attr_t *attr_alloc(int id, int M) +{ + struct l2tp_attr_t *attr; + struct l2tp_dict_attr_t *da; + + da = l2tp_dict_find_attr_by_id(id); + if (!da) + return NULL; + + attr = mempool_alloc(attr_pool); + if (!attr) { + log_emerg("l2tp: out of memory\n"); + return NULL; + } + + memset(attr, 0, sizeof(*attr)); + + attr->attr = da; + + if (da->M != -1) + attr->M = da->M; + else + attr->M = M; + + //if (da->H != -1) + //attr->H = da->H; + + return attr; +} + +int l2tp_packet_add_int16(struct l2tp_packet_t *pack, int id, int16_t val, int M) +{ + struct l2tp_attr_t *attr = attr_alloc(id, M); + + if (!attr) + return -1; + + attr->length = 2; + attr->val.int16 = val; + list_add_tail(&attr->entry, &pack->attrs); + + return 0; +} +int l2tp_packet_add_int32(struct l2tp_packet_t *pack, int id, int32_t val, int M) +{ + struct l2tp_attr_t *attr = attr_alloc(id, M); + + if (!attr) + return -1; + + attr->length = 4; + attr->val.int32 = val; + list_add_tail(&attr->entry, &pack->attrs); + + return 0; +} +int l2tp_packet_add_string(struct l2tp_packet_t *pack, int id, const char *val, int M) +{ + struct l2tp_attr_t *attr = attr_alloc(id, M); + + if (!attr) + return -1; + + attr->length = strlen(val); + attr->val.string = _strdup(val); + if (!attr->val.string) { + log_emerg("l2tp: out of memory\n"); + mempool_free(attr); + return -1; + } + memcpy(attr->val.string, val, attr->length); + list_add_tail(&attr->entry, &pack->attrs); + + return 0; +} + +int l2tp_packet_add_octets(struct l2tp_packet_t *pack, int id, const uint8_t *val, int size, int M) +{ + struct l2tp_attr_t *attr = attr_alloc(id, M); + + if (!attr) + return -1; + + attr->length = size; + attr->val.octets = _malloc(size); + if (!attr->val.string) { + log_emerg("l2tp: out of memory\n"); + mempool_free(attr); + return -1; + } + memcpy(attr->val.octets, val, attr->length); + list_add_tail(&attr->entry, &pack->attrs); + + return 0; +} + +static void __init init(void) +{ + attr_pool = mempool_create(sizeof(struct l2tp_attr_t)); + pack_pool = mempool_create(sizeof(struct l2tp_packet_t)); + buf_pool = mempool_create(L2TP_MAX_PACKET_SIZE); +} + diff --git a/accel-pppd/ctrl/pppoe/CMakeLists.txt b/accel-pppd/ctrl/pppoe/CMakeLists.txt new file mode 100644 index 0000000..b2c0584 --- /dev/null +++ b/accel-pppd/ctrl/pppoe/CMakeLists.txt @@ -0,0 +1,17 @@ +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +SET(sources + pppoe.c + mac_filter.c + dpado.c + cli.c +) + +IF (RADIUS) +SET(sources ${sources} tr101.c) +ENDIF(RADIUS) + +ADD_LIBRARY(pppoe SHARED ${sources}) +TARGET_LINK_LIBRARIES(pppoe crypto) + +INSTALL(TARGETS pppoe LIBRARY DESTINATION lib/accel-ppp) diff --git a/accel-pppd/ctrl/pppoe/cli.c b/accel-pppd/ctrl/pppoe/cli.c new file mode 100644 index 0000000..9929f66 --- /dev/null +++ b/accel-pppd/ctrl/pppoe/cli.c @@ -0,0 +1,205 @@ +#include +#include +#include +#include + +#include "triton.h" +#include "cli.h" +#include "ppp.h" +#include "memdebug.h" + +#include "pppoe.h" + +static void show_interfaces(void *cli) +{ + struct pppoe_serv_t *serv; + + cli_send(cli, "interface: connections: state:\r\n"); + cli_send(cli, "-----------------------------------\r\n"); + + pthread_rwlock_rdlock(&serv_lock); + list_for_each_entry(serv, &serv_list, entry) { + cli_sendv(cli, "%9s %11u %6s\r\n", serv->ifname, serv->conn_cnt, serv->stopping ? "stop" : "active"); + } + pthread_rwlock_unlock(&serv_lock); +} + +static void intf_help(char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "pppoe interface add - start pppoe server on specified interface\r\n"); + cli_send(client, "pppoe interface del - stop pppoe server on specified interface and drop his connections\r\n"); + cli_send(client, "pppoe interface show - show interfaces on which pppoe server started\r\n"); +} + +static int intf_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) +{ + if (fields_cnt == 2) + goto help; + + if (fields_cnt == 3) { + if (!strcmp(fields[2], "show")) + show_interfaces(client); + else + goto help; + + return CLI_CMD_OK; + } + + if (fields_cnt != 4) + goto help; + + if (!strcmp(fields[2], "add")) + pppoe_server_start(fields[3], client); + else if (!strcmp(fields[2], "del")) + pppoe_server_stop(fields[3]); + else + goto help; + + return CLI_CMD_OK; +help: + intf_help(fields, fields_cnt, client); + return CLI_CMD_OK; +} + +//=================================== + +static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "pppoe:\r\n"); + cli_sendv(client, " active: %u\r\n", stat_active); + cli_sendv(client, " delayed PADO: %u\r\n", stat_delayed_pado); + cli_sendv(client, " recv PADI: %lu\r\n", stat_PADI_recv); + cli_sendv(client, " sent PADO: %lu\r\n", stat_PADO_sent); + cli_sendv(client, " recv PADR(dup): %lu(%lu)\r\n", stat_PADR_recv, stat_PADR_dup_recv); + cli_sendv(client, " sent PADS: %lu\r\n", stat_PADS_sent); + + return CLI_CMD_OK; +} + +//=================================== + +static void set_verbose_help(char * const *f, int f_cnt, void *cli) +{ + cli_send(cli, "pppoe set verbose - set verbosity of pppoe logging\r\n"); + cli_send(cli, "pppoe set PADO-delay - set PADO delays (ms)\r\n"); + cli_send(cli, "pppoe set Service-Name - set Service-Name to respond\r\n"); + cli_send(cli, "pppoe set Service-Name * - respond with client's Service-Name\r\n"); + cli_send(cli, "pppoe set AC-Name - set AC-Name tag value\r\n"); + cli_send(cli, "pppoe show verbose - show current verbose value\r\n"); + cli_send(cli, "pppoe show PADO-delay - show current PADO delay value\r\n"); + cli_send(cli, "pppoe show Service-Name - show current Service-Name value\r\n"); + cli_send(cli, "pppoe show AC-Name - show current AC-Name tag value\r\n"); +} + +static int show_verbose_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + if (f_cnt != 3) + return CLI_CMD_SYNTAX; + + cli_sendv(cli, "%i\r\n", conf_verbose); + + return CLI_CMD_OK; +} + +static int show_pado_delay_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + if (f_cnt != 3) + return CLI_CMD_SYNTAX; + + cli_sendv(cli, "%s\r\n", conf_pado_delay); + + return CLI_CMD_OK; +} + +static int show_service_name_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + if (f_cnt != 3) + return CLI_CMD_SYNTAX; + + if (conf_service_name) + cli_sendv(cli, "%s\r\n", conf_service_name); + else + cli_sendv(cli, "*\r\n", conf_service_name); + + return CLI_CMD_OK; +} + +static int show_ac_name_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + if (f_cnt != 3) + return CLI_CMD_SYNTAX; + + cli_sendv(cli, "%s\r\n", conf_ac_name); + + return CLI_CMD_OK; +} + +static int set_verbose_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + if (f_cnt != 4) + return CLI_CMD_SYNTAX; + + if (!strcmp(f[3], "0")) + conf_verbose = 0; + else if (!strcmp(f[3], "1")) + conf_verbose = 1; + else + return CLI_CMD_INVAL; + + return CLI_CMD_OK; +} + +static int set_pado_delay_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + if (f_cnt != 4) + return CLI_CMD_SYNTAX; + + if (dpado_parse(f[3])) + return CLI_CMD_INVAL; + + return CLI_CMD_OK; +} + +static int set_service_name_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + if (f_cnt != 4) + return CLI_CMD_SYNTAX; + + if (conf_service_name) + _free(conf_service_name); + + if (!strcmp(f[3], "*")) + conf_service_name = NULL; + else + conf_service_name = _strdup(f[3]); + + return CLI_CMD_OK; +} + +static int set_ac_name_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + if (f_cnt != 4) + return CLI_CMD_SYNTAX; + + _free(conf_ac_name); + conf_ac_name = _strdup(f[3]); + + return CLI_CMD_OK; +} +//=================================== + + +static void __init init(void) +{ + cli_register_simple_cmd2(show_stat_exec, NULL, 2, "show", "stat"); + cli_register_simple_cmd2(intf_exec, intf_help, 2, "pppoe", "interface"); + cli_register_simple_cmd2(set_verbose_exec, set_verbose_help, 3, "pppoe", "set", "verbose"); + cli_register_simple_cmd2(set_pado_delay_exec, NULL, 3, "pppoe", "set", "PADO-delay"); + cli_register_simple_cmd2(set_service_name_exec, NULL, 3, "pppoe", "set", "Service-Name"); + cli_register_simple_cmd2(set_ac_name_exec, NULL, 3, "pppoe", "set", "AC-Name"); + cli_register_simple_cmd2(show_verbose_exec, NULL, 3, "pppoe", "show", "verbose"); + cli_register_simple_cmd2(show_pado_delay_exec, NULL, 3, "pppoe", "show", "PADO-delay"); + cli_register_simple_cmd2(show_service_name_exec, NULL, 3, "pppoe", "show", "Service-Name"); + cli_register_simple_cmd2(show_ac_name_exec, NULL, 3, "pppoe", "show", "AC-Name"); +} + diff --git a/accel-pppd/ctrl/pppoe/dpado.c b/accel-pppd/ctrl/pppoe/dpado.c new file mode 100644 index 0000000..3f56519 --- /dev/null +++ b/accel-pppd/ctrl/pppoe/dpado.c @@ -0,0 +1,162 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "list.h" +#include "cli.h" +#include "triton.h" +#include "log.h" +#include "memdebug.h" + +#include "pppoe.h" + +struct dpado_range_t +{ + struct list_head entry; + unsigned int conn_cnt; + int pado_delay; +}; + +static pthread_mutex_t dpado_range_lock = PTHREAD_MUTEX_INITIALIZER; +static LIST_HEAD(dpado_range_list); +static struct dpado_range_t *dpado_range_next; +static struct dpado_range_t *dpado_range_prev; +int pado_delay; + +void dpado_check_next(int conn_cnt) +{ + pthread_mutex_lock(&dpado_range_lock); + if (dpado_range_next && conn_cnt == dpado_range_next->conn_cnt) { + pado_delay = dpado_range_next->pado_delay; + dpado_range_prev = dpado_range_next; + if (dpado_range_next->entry.next != &dpado_range_list) + dpado_range_next = list_entry(dpado_range_next->entry.next, typeof(*dpado_range_next), entry); + else + dpado_range_next = NULL; + /*printf("active=%i, prev=%i:%i, next=%i:%i, pado_delay=%i\n", stat_active, + dpado_range_prev?dpado_range_prev->pado_delay:0,dpado_range_prev?dpado_range_prev->conn_cnt:0, + dpado_range_next?dpado_range_next->pado_delay:0,dpado_range_next?dpado_range_next->conn_cnt:0, + pado_delay);*/ + } + pthread_mutex_unlock(&dpado_range_lock); +} + +void dpado_check_prev(int conn_cnt) +{ + pthread_mutex_lock(&dpado_range_lock); + if (dpado_range_prev && conn_cnt == dpado_range_prev->conn_cnt) { + dpado_range_next = dpado_range_prev; + dpado_range_prev = list_entry(dpado_range_prev->entry.prev, typeof(*dpado_range_prev), entry); + pado_delay = dpado_range_prev->pado_delay; + /*printf("active=%i, prev=%i:%i, next=%i:%i, pado_delay=%i\n", stat_active, + dpado_range_prev?dpado_range_prev->pado_delay:0,dpado_range_prev?dpado_range_prev->conn_cnt:0, + dpado_range_next?dpado_range_next->pado_delay:0,dpado_range_next?dpado_range_next->conn_cnt:0, + pado_delay);*/ + } + pthread_mutex_unlock(&dpado_range_lock); +} + +static void strip(char *str) +{ + char *ptr = str; + char *endptr = strchr(str, 0); + while (1) { + ptr = strchr(ptr, ' '); + if (ptr) + memmove(ptr, ptr + 1, endptr - ptr - 1); + else + break; + } +} + +int dpado_parse(const char *str) +{ + char *str1 = _strdup(str); + char *ptr1, *ptr2, *ptr3, *endptr; + LIST_HEAD(range_list); + struct dpado_range_t *r; + + strip(str1); + + ptr1 = str1; + + while (1) { + ptr2 = strchr(ptr1, ','); + if (ptr2) + *ptr2 = 0; + ptr3 = strchr(ptr1, ':'); + if (ptr3) + *ptr3 = 0; + + r = _malloc(sizeof(*r)); + memset(r, 0, sizeof(*r)); + + r->pado_delay = strtol(ptr1, &endptr, 10); + if (*endptr) + goto out_err; + + if (list_empty(&range_list)) + r->conn_cnt = INT_MAX; + else { + if (!ptr3) + goto out_err; + r->conn_cnt = strtol(ptr3 + 1, &endptr, 10); + if (*endptr) + goto out_err; + } + + list_add_tail(&r->entry, &range_list); + //printf("parsed range: %i:%i\n", r->pado_delay, r->conn_cnt); + + if (!ptr2) + break; + + ptr1 = ptr2 + 1; + } + + pthread_mutex_lock(&dpado_range_lock); + while (!list_empty(&dpado_range_list)) { + r = list_entry(dpado_range_list.next, typeof(*r), entry); + list_del(&r->entry); + _free(r); + } + + dpado_range_next = NULL; + dpado_range_prev = NULL; + + while (!list_empty(&range_list)) { + r = list_entry(range_list.next, typeof(*r), entry); + list_del(&r->entry); + list_add_tail(&r->entry, &dpado_range_list); + + if (!dpado_range_prev || stat_active >= r->conn_cnt) + dpado_range_prev = r; + else if (!dpado_range_next) + dpado_range_next = r; + } + + pado_delay = dpado_range_prev->pado_delay; + + if (conf_pado_delay) + _free(conf_pado_delay); + conf_pado_delay = _strdup(str); + /*printf("active=%i, prev=%i:%i, next=%i:%i, pado_delay=%i\n", stat_active, + dpado_range_prev?dpado_range_prev->pado_delay:0,dpado_range_prev?dpado_range_prev->conn_cnt:0, + dpado_range_next?dpado_range_next->pado_delay:0,dpado_range_next?dpado_range_next->conn_cnt:0, + pado_delay);*/ + + pthread_mutex_unlock(&dpado_range_lock); + + _free(str1); + return 0; + +out_err: + _free(str1); + log_emerg("pppoe: pado_delay: invalid format\n"); + return -1; +} + diff --git a/accel-pppd/ctrl/pppoe/mac_filter.c b/accel-pppd/ctrl/pppoe/mac_filter.c new file mode 100644 index 0000000..9b101c6 --- /dev/null +++ b/accel-pppd/ctrl/pppoe/mac_filter.c @@ -0,0 +1,255 @@ +#include +#include +#include +#include +#include +#include + +#include "list.h" +#include "cli.h" +#include "triton.h" +#include "log.h" +#include "ppp.h" +#include "memdebug.h" + +#include "pppoe.h" + +struct mac_t +{ + struct list_head entry; + uint8_t addr[ETH_ALEN]; +}; + +static LIST_HEAD(mac_list); +static int type; // -1 - disabled, 1 - allow, 0 - denied +static pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER; +static const char *conf_mac_filter; + +int mac_filter_check(const uint8_t *addr) +{ + struct mac_t *mac; + int res = type; + + if (type == -1) + return 0; + + pthread_rwlock_rdlock(&lock); + list_for_each_entry(mac, &mac_list, entry) { + if (memcmp(mac->addr, addr, ETH_ALEN)) + continue; + res = !type; + break; + } + pthread_rwlock_unlock(&lock); + + return res; +} + +static int mac_filter_load(const char *opt) +{ + struct mac_t *mac; + FILE *f; + char *c; + char *name = _strdup(opt); + char *buf = _malloc(1024); + int n[ETH_ALEN]; + int i, line = 0; + + c = strstr(name, ","); + if (!c) + goto err_inval; + + *c = 0; + + if (!strcmp(c + 1, "allow")) + type = 1; + else if (!strcmp(c + 1, "deny")) + type = 0; + else + goto err_inval; + + f = fopen(name, "r"); + if (!f) { + log_emerg("pppoe: open '%s': %s\n", name, strerror(errno)); + goto err; + } + + conf_mac_filter = opt; + + pthread_rwlock_wrlock(&lock); + while (!list_empty(&mac_list)) { + mac = list_entry(mac_list.next, typeof(*mac), entry); + list_del(&mac->entry); + _free(mac); + } + + while (fgets(buf, 1024, f)) { + line++; + if (buf[0] == '#' || buf[0] == ';' || buf[0] == '\n') + continue; + if (sscanf(buf, "%x:%x:%x:%x:%x:%x", + n + 0, n + 1, n + 2, n + 3, n + 4, n + 5) != 6) { + log_warn("pppoe: mac-filter:%s:%i: address is invalid\n", name, line); + continue; + } + mac = _malloc(sizeof(*mac)); + for (i = 0; i < ETH_ALEN; i++) { + if (n[i] > 255) { + log_warn("pppoe: mac-filter:%s:%i: address is invalid\n", name, line); + _free(mac); + continue; + } + mac->addr[i] = n[i]; + } + list_add_tail(&mac->entry, &mac_list); + } + pthread_rwlock_unlock(&lock); + + fclose(f); + + _free(name); + _free(buf); + + return 0; + +err_inval: + log_emerg("pppoe: mac-filter format is invalid\n"); +err: + _free(name); + _free(buf); + return -1; +} + +static void mac_filter_add(const char *addr, void *client) +{ + int n[ETH_ALEN]; + struct mac_t *mac; + int i; + + if (sscanf(addr, "%x:%x:%x:%x:%x:%x", + n + 0, n + 1, n + 2, n + 3, n + 4, n + 5) != 6) { + cli_send(client, "invalid format\r\n"); + return; + } + + mac = _malloc(sizeof(*mac)); + for (i = 0; i < ETH_ALEN; i++) { + if (n[i] > 255) { + _free(mac); + cli_send(client, "invalid format\r\n"); + return; + } + mac->addr[i] = n[i]; + } + + pthread_rwlock_wrlock(&lock); + list_add_tail(&mac->entry, &mac_list); + pthread_rwlock_unlock(&lock); +} + +static void mac_filter_del(const char *addr, void *client) +{ + int n[ETH_ALEN]; + uint8_t a[ETH_ALEN]; + struct mac_t *mac; + int i; + int found = 0; + + if (sscanf(addr, "%x:%x:%x:%x:%x:%x", + n + 0, n + 1, n + 2, n + 3, n + 4, n + 5) != 6) { + cli_send(client, "invalid format\r\n"); + return; + } + + for (i = 0; i < ETH_ALEN; i++) { + if (n[i] > 255) { + cli_send(client, "invalid format\r\n"); + return; + } + a[i] = n[i]; + } + + pthread_rwlock_wrlock(&lock); + list_for_each_entry(mac, &mac_list, entry) { + if (memcmp(a, mac->addr, ETH_ALEN)) + continue; + list_del(&mac->entry); + _free(mac); + found = 1; + break; + } + pthread_rwlock_unlock(&lock); + + if (!found) + cli_send(client, "not found\r\n"); +} + +static void mac_filter_show(void *client) +{ + struct mac_t *mac; + const char *filter_type; + + if (type == 0) + filter_type = "deny"; + else if (type == 1) + filter_type = "allow"; + else + filter_type = "disabled"; + + cli_sendv(client, "filter type: %s\r\n", filter_type); + + pthread_rwlock_rdlock(&lock); + list_for_each_entry(mac, &mac_list, entry) { + cli_sendv(client, "%02x:%02x:%02x:%02x:%02x:%02x\r\n", + mac->addr[0], mac->addr[1], mac->addr[2], + mac->addr[3], mac->addr[4], mac->addr[5]); + } + pthread_rwlock_unlock(&lock); +} + +static void cmd_help(char * const *fields, int fields_cnt, void *client); +static int cmd_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) +{ + if (fields_cnt == 2) + goto help; + + if (!strcmp(fields[2], "reload")) { + if (!conf_mac_filter) + cli_send(client, "error: mac-filter was not specified in the config\r\n"); + else if (mac_filter_load(conf_mac_filter)) + cli_send(client, "error: check logs\r\n"); + } else if (!strcmp(fields[2], "add")) { + if (fields_cnt != 4) + goto help; + mac_filter_add(fields[3], client); + } else if (!strcmp(fields[2], "del")) { + if (fields_cnt != 4) + goto help; + mac_filter_del(fields[3], client); + } else if (!strcmp(fields[2], "show")) { + mac_filter_show(client); + } + + return CLI_CMD_OK; +help: + cmd_help(fields, fields_cnt, client); + return CLI_CMD_OK; +} + +static void cmd_help(char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "pppoe mac-filter reload - reload mac-filter file\r\n"); + cli_send(client, "pppoe mac-filter add
- add address to mac-filter list\r\n"); + cli_send(client, "pppoe mac-filter del
- delete address from mac-filter list\r\n"); + cli_send(client, "pppoe mac-filter show - show current mac-filter list\r\n"); +} + +static void __init init(void) +{ + const char *opt = conf_get_opt("pppoe", "mac-filter"); + if (!opt || mac_filter_load(opt)) + type = -1; + + cli_register_simple_cmd2(cmd_exec, cmd_help, 2, "pppoe", "mac-filter"); +} + diff --git a/accel-pppd/ctrl/pppoe/pppoe.c b/accel-pppd/ctrl/pppoe/pppoe.c new file mode 100644 index 0000000..7860c4e --- /dev/null +++ b/accel-pppd/ctrl/pppoe/pppoe.c @@ -0,0 +1,1288 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "events.h" +#include "triton.h" +#include "log.h" +#include "ppp.h" +#include "mempool.h" +#include "cli.h" + +#ifdef RADIUS +#include "radius.h" +#endif + +#include "pppoe.h" + +#include "memdebug.h" + +struct pppoe_conn_t +{ + struct list_head entry; + struct triton_context_t ctx; + struct pppoe_serv_t *serv; + int disc_sock; + uint16_t sid; + uint8_t addr[ETH_ALEN]; + int ppp_started:1; + + struct pppoe_tag *relay_sid; + struct pppoe_tag *host_uniq; + struct pppoe_tag *service_name; + struct pppoe_tag *tr101; + uint8_t cookie[COOKIE_LENGTH]; + + struct ppp_ctrl_t ctrl; + struct ppp_t ppp; +#ifdef RADIUS + struct rad_plugin_t radius; +#endif +}; + +struct delayed_pado_t +{ + struct list_head entry; + struct triton_timer_t timer; + struct pppoe_serv_t *serv; + uint8_t addr[ETH_ALEN]; + struct pppoe_tag *host_uniq; + struct pppoe_tag *relay_sid; + struct pppoe_tag *service_name; +}; + +int conf_verbose; +char *conf_service_name; +char *conf_ac_name; +int conf_ifname_in_sid; +char *conf_pado_delay; + +static mempool_t conn_pool; +static mempool_t pado_pool; + +unsigned int stat_active; +unsigned int stat_delayed_pado; +unsigned long stat_PADI_recv; +unsigned long stat_PADO_sent; +unsigned long stat_PADR_recv; +unsigned long stat_PADR_dup_recv; +unsigned long stat_PADS_sent; + +pthread_rwlock_t serv_lock = PTHREAD_RWLOCK_INITIALIZER; +LIST_HEAD(serv_list); + +static uint8_t bc_addr[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; + +static void pppoe_send_PADT(struct pppoe_conn_t *conn); +static void _server_stop(struct pppoe_serv_t *serv); +void pppoe_server_free(struct pppoe_serv_t *serv); +static int init_secret(struct pppoe_serv_t *serv); + +static void disconnect(struct pppoe_conn_t *conn) +{ + if (conn->ppp_started) { + dpado_check_prev(__sync_fetch_and_sub(&stat_active, 1)); + conn->ppp_started = 0; + ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); + } + + pppoe_send_PADT(conn); + + close(conn->disc_sock); + + + triton_event_fire(EV_CTRL_FINISHED, &conn->ppp); + + log_ppp_info1("disconnected\n"); + + pthread_mutex_lock(&conn->serv->lock); + conn->serv->conn[conn->sid] = NULL; + list_del(&conn->entry); + conn->serv->conn_cnt--; + if (conn->serv->stopping && conn->serv->conn_cnt == 0) { + pthread_mutex_unlock(&conn->serv->lock); + pppoe_server_free(conn->serv); + } else + pthread_mutex_unlock(&conn->serv->lock); + + _free(conn->ctrl.calling_station_id); + _free(conn->ctrl.called_station_id); + _free(conn->service_name); + if (conn->host_uniq) + _free(conn->host_uniq); + if (conn->relay_sid) + _free(conn->relay_sid); + + triton_context_unregister(&conn->ctx); + + mempool_free(conn); +} + +static void ppp_started(struct ppp_t *ppp) +{ + log_ppp_debug("pppoe: ppp started\n"); +} + +static void ppp_finished(struct ppp_t *ppp) +{ + struct pppoe_conn_t *conn = container_of(ppp, typeof(*conn), ppp); + + log_ppp_debug("pppoe: ppp finished\n"); + + if (conn->ppp_started) { + dpado_check_prev(__sync_fetch_and_sub(&stat_active, 1)); + conn->ppp_started = 0; + triton_context_call(&conn->ctx, (triton_event_func)disconnect, conn); + } +} + +static void pppoe_conn_close(struct triton_context_t *ctx) +{ + struct pppoe_conn_t *conn = container_of(ctx, typeof(*conn), ctx); + + if (conn->ppp_started) + ppp_terminate(&conn->ppp, TERM_ADMIN_RESET, 0); + else + disconnect(conn); +} + +#ifdef RADIUS +static int pppoe_rad_send_access_request(struct rad_plugin_t *rad, struct rad_packet_t *pack) +{ + struct pppoe_conn_t *conn = container_of(rad, typeof(*conn), radius); + + if (conn->tr101) + return tr101_send_access_request(conn->tr101, pack); + + return 0; +} + +static int pppoe_rad_send_accounting_request(struct rad_plugin_t *rad, struct rad_packet_t *pack) +{ + struct pppoe_conn_t *conn = container_of(rad, typeof(*conn), radius); + + if (conn->tr101) + return tr101_send_accounting_request(conn->tr101, pack); + + return 0; +} +#endif + +static struct pppoe_conn_t *allocate_channel(struct pppoe_serv_t *serv, const uint8_t *addr, const struct pppoe_tag *host_uniq, const struct pppoe_tag *relay_sid, const struct pppoe_tag *service_name, const struct pppoe_tag *tr101, const uint8_t *cookie) +{ + struct pppoe_conn_t *conn; + int sid; + + conn = mempool_alloc(conn_pool); + if (!conn) { + log_emerg("pppoe: out of memory\n"); + return NULL; + } + + memset(conn, 0, sizeof(*conn)); + + pthread_mutex_lock(&serv->lock); + for (sid = serv->sid + 1; sid != serv->sid; sid++) { + if (sid == MAX_SID) + sid = 1; + if (!serv->conn[sid]) { + conn->sid = sid; + serv->sid = sid; + serv->conn[sid] = conn; + list_add_tail(&conn->entry, &serv->conn_list); + serv->conn_cnt++; + break; + } + } + pthread_mutex_unlock(&serv->lock); + + if (!conn->sid) { + log_warn("pppoe: no free sid available\n"); + mempool_free(conn); + return NULL; + } + + conn->serv = serv; + memcpy(conn->addr, addr, ETH_ALEN); + + if (host_uniq) { + conn->host_uniq = _malloc(sizeof(*host_uniq) + ntohs(host_uniq->tag_len)); + memcpy(conn->host_uniq, host_uniq, sizeof(*host_uniq) + ntohs(host_uniq->tag_len)); + } + + if (relay_sid) { + conn->relay_sid = _malloc(sizeof(*relay_sid) + ntohs(relay_sid->tag_len)); + memcpy(conn->relay_sid, relay_sid, sizeof(*relay_sid) + ntohs(relay_sid->tag_len)); + } + + if (tr101) { + conn->tr101 = _malloc(sizeof(*tr101) + ntohs(tr101->tag_len)); + memcpy(conn->tr101, tr101, sizeof(*tr101) + ntohs(tr101->tag_len)); + } + + conn->service_name = _malloc(sizeof(*service_name) + ntohs(service_name->tag_len)); + memcpy(conn->service_name, service_name, sizeof(*service_name) + ntohs(service_name->tag_len)); + + memcpy(conn->cookie, cookie, COOKIE_LENGTH); + + conn->ctx.before_switch = log_switch; + conn->ctx.close = pppoe_conn_close; + conn->ctrl.ctx = &conn->ctx; + conn->ctrl.started = ppp_started; + conn->ctrl.finished = ppp_finished; + conn->ctrl.max_mtu = MAX_PPPOE_MTU; + conn->ctrl.name = "pppoe"; + + conn->ctrl.calling_station_id = _malloc(IFNAMSIZ + 19); + conn->ctrl.called_station_id = _malloc(IFNAMSIZ + 19); + + if (conf_ifname_in_sid == 1 || conf_ifname_in_sid == 3) + sprintf(conn->ctrl.calling_station_id, "%s:%02x:%02x:%02x:%02x:%02x:%02x", serv->ifname, + addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); + else + sprintf(conn->ctrl.calling_station_id, "%02x:%02x:%02x:%02x:%02x:%02x", + addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); + + if (conf_ifname_in_sid == 2 || conf_ifname_in_sid == 3) + sprintf(conn->ctrl.called_station_id, "%s:%02x:%02x:%02x:%02x:%02x:%02x", serv->ifname, + serv->hwaddr[0], serv->hwaddr[1], serv->hwaddr[2], serv->hwaddr[3], serv->hwaddr[4], serv->hwaddr[5]); + else + sprintf(conn->ctrl.called_station_id, "%02x:%02x:%02x:%02x:%02x:%02x", + serv->hwaddr[0], serv->hwaddr[1], serv->hwaddr[2], serv->hwaddr[3], serv->hwaddr[4], serv->hwaddr[5]); + + ppp_init(&conn->ppp); + + conn->ppp.ctrl = &conn->ctrl; + conn->ppp.chan_name = conn->ctrl.calling_station_id; + + triton_context_register(&conn->ctx, &conn->ppp); + triton_context_wakeup(&conn->ctx); + + triton_event_fire(EV_CTRL_STARTING, &conn->ppp); + triton_event_fire(EV_CTRL_STARTED, &conn->ppp); + + conn->disc_sock = dup(serv->hnd.fd); + + return conn; +} + +static void connect_channel(struct pppoe_conn_t *conn) +{ + int sock; + struct sockaddr_pppox sp; + + sock = socket(AF_PPPOX, SOCK_STREAM, PX_PROTO_OE); + if (!sock) { + log_error("pppoe: socket(PPPOX): %s\n", strerror(errno)); + goto out_err; + } + + memset(&sp, 0, sizeof(sp)); + + sp.sa_family = AF_PPPOX; + sp.sa_protocol = PX_PROTO_OE; + sp.sa_addr.pppoe.sid = htons(conn->sid); + strcpy(sp.sa_addr.pppoe.dev, conn->serv->ifname); + memcpy(sp.sa_addr.pppoe.remote, conn->addr, ETH_ALEN); + + if (connect(sock, (struct sockaddr *)&sp, sizeof(sp))) { + log_error("pppoe: connect: %s\n", strerror(errno)); + goto out_err_close; + } + + conn->ppp.fd = sock; + + if (establish_ppp(&conn->ppp)) + goto out_err_close; + +#ifdef RADIUS + if (conn->tr101) { + conn->radius.send_access_request = pppoe_rad_send_access_request; + conn->radius.send_accounting_request = pppoe_rad_send_accounting_request; + rad_register_plugin(&conn->ppp, &conn->radius); + } +#endif + + conn->ppp_started = 1; + + dpado_check_next(__sync_add_and_fetch(&stat_active, 1)); + + return; + +out_err_close: + close(sock); +out_err: + disconnect(conn); +} + +static struct pppoe_conn_t *find_channel(struct pppoe_serv_t *serv, const uint8_t *cookie) +{ + struct pppoe_conn_t *conn; + + list_for_each_entry(conn, &serv->conn_list, entry) + if (!memcmp(conn->cookie, cookie, COOKIE_LENGTH)) + return conn; + + return NULL; +} + +static void print_tag_string(struct pppoe_tag *tag) +{ + int i; + + for (i = 0; i < ntohs(tag->tag_len); i++) + log_info2("%c", tag->tag_data[i]); +} + +static void print_tag_octets(struct pppoe_tag *tag) +{ + int i; + + for (i = 0; i < ntohs(tag->tag_len); i++) + log_info2("%02x", (uint8_t)tag->tag_data[i]); +} + +static void print_packet(uint8_t *pack) +{ + struct ethhdr *ethhdr = (struct ethhdr *)pack; + struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); + struct pppoe_tag *tag; + int n; + + log_info2("[PPPoE "); + + switch (hdr->code) { + case CODE_PADI: + log_info2("PADI"); + break; + case CODE_PADO: + log_info2("PADO"); + break; + case CODE_PADR: + log_info2("PADR"); + break; + case CODE_PADS: + log_info2("PADS"); + break; + case CODE_PADT: + log_info2("PADT"); + break; + } + + log_info2(" %02x:%02x:%02x:%02x:%02x:%02x => %02x:%02x:%02x:%02x:%02x:%02x", + ethhdr->h_source[0], ethhdr->h_source[1], ethhdr->h_source[2], ethhdr->h_source[3], ethhdr->h_source[4], ethhdr->h_source[5], + ethhdr->h_dest[0], ethhdr->h_dest[1], ethhdr->h_dest[2], ethhdr->h_dest[3], ethhdr->h_dest[4], ethhdr->h_dest[5]); + + log_info2(" sid=%04x", ntohs(hdr->sid)); + + for (n = 0; n < ntohs(hdr->length); n += sizeof(*tag) + ntohs(tag->tag_len)) { + tag = (struct pppoe_tag *)(pack + ETH_HLEN + sizeof(*hdr) + n); + switch (ntohs(tag->tag_type)) { + case TAG_END_OF_LIST: + log_info2(" "); + break; + case TAG_SERVICE_NAME: + log_info2(" "); + break; + case TAG_AC_NAME: + log_info2(" "); + break; + case TAG_HOST_UNIQ: + log_info2(" "); + break; + case TAG_AC_COOKIE: + log_info2(" "); + break; + case TAG_VENDOR_SPECIFIC: + if (ntohs(tag->tag_len) < 4) + log_info2(" "); + else + log_info2(" ", ntohl(*(uint32_t *)tag->tag_data)); + break; + case TAG_RELAY_SESSION_ID: + log_info2(" "); + break; + case TAG_SERVICE_NAME_ERROR: + log_info2(" "); + break; + case TAG_AC_SYSTEM_ERROR: + log_info2(" "); + break; + case TAG_GENERIC_ERROR: + log_info2(" "); + break; + default: + log_info2(" ", ntohs(tag->tag_type)); + break; + } + } + + log_info2("]\n"); +} + +static void generate_cookie(struct pppoe_serv_t *serv, const uint8_t *src, uint8_t *cookie) +{ + MD5_CTX ctx; + DES_cblock key; + DES_key_schedule ks; + int i; + union { + DES_cblock b[3]; + uint8_t raw[24]; + } u1, u2; + + memset(&key, 0, sizeof(key)); + DES_random_key(&key); + DES_set_key(&key, &ks); + + MD5_Init(&ctx); + MD5_Update(&ctx, serv->secret, SECRET_LENGTH); + MD5_Update(&ctx, serv->hwaddr, ETH_ALEN); + MD5_Update(&ctx, src, ETH_ALEN); + MD5_Update(&ctx, &key, 8); + MD5_Final(u1.raw, &ctx); + + for (i = 0; i < 2; i++) + DES_ecb_encrypt(&u1.b[i], &u2.b[i], &ks, DES_ENCRYPT); + memcpy(u2.b[2], &key, 8); + + for (i = 0; i < 3; i++) + DES_ecb_encrypt(&u2.b[i], &u1.b[i], &serv->des_ks, DES_ENCRYPT); + + memcpy(cookie, u1.raw, 24); +} + +static int check_cookie(struct pppoe_serv_t *serv, const uint8_t *src, const uint8_t *cookie) +{ + MD5_CTX ctx; + DES_key_schedule ks; + int i; + union { + DES_cblock b[3]; + uint8_t raw[24]; + } u1, u2; + + memcpy(u1.raw, cookie, 24); + + for (i = 0; i < 3; i++) + DES_ecb_encrypt(&u1.b[i], &u2.b[i], &serv->des_ks, DES_DECRYPT); + + if (DES_set_key_checked(&u2.b[2], &ks)) + return -1; + + for (i = 0; i < 2; i++) + DES_ecb_encrypt(&u2.b[i], &u1.b[i], &ks, DES_DECRYPT); + + MD5_Init(&ctx); + MD5_Update(&ctx, serv->secret, SECRET_LENGTH); + MD5_Update(&ctx, serv->hwaddr, ETH_ALEN); + MD5_Update(&ctx, src, ETH_ALEN); + MD5_Update(&ctx, u2.b[2], 8); + MD5_Final(u2.raw, &ctx); + + return memcmp(u1.raw, u2.raw, 16); +} + +static void setup_header(uint8_t *pack, const uint8_t *src, const uint8_t *dst, int code, uint16_t sid) +{ + struct ethhdr *ethhdr = (struct ethhdr *)pack; + struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); + + memcpy(ethhdr->h_source, src, ETH_ALEN); + memcpy(ethhdr->h_dest, dst, ETH_ALEN); + ethhdr->h_proto = htons(ETH_P_PPP_DISC); + + hdr->ver = 1; + hdr->type = 1; + hdr->code = code; + hdr->sid = htons(sid); + hdr->length = 0; +} + +static void add_tag(uint8_t *pack, int type, const uint8_t *data, int len) +{ + struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); + struct pppoe_tag *tag = (struct pppoe_tag *)(pack + ETH_HLEN + sizeof(*hdr) + ntohs(hdr->length)); + + tag->tag_type = htons(type); + tag->tag_len = htons(len); + memcpy(tag->tag_data, data, len); + + hdr->length = htons(ntohs(hdr->length) + sizeof(*tag) + len); +} + +static void add_tag2(uint8_t *pack, const struct pppoe_tag *t) +{ + struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); + struct pppoe_tag *tag = (struct pppoe_tag *)(pack + ETH_HLEN + sizeof(*hdr) + ntohs(hdr->length)); + + memcpy(tag, t, sizeof(*t) + ntohs(t->tag_len)); + + hdr->length = htons(ntohs(hdr->length) + sizeof(*tag) + ntohs(t->tag_len)); +} + +static void pppoe_send(int fd, const uint8_t *pack) +{ + struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); + int n, s; + + s = ETH_HLEN + sizeof(*hdr) + ntohs(hdr->length); + n = write(fd, pack, s); + if (n < 0 ) + log_error("pppoe: write: %s\n", strerror(errno)); + else if (n != s) { + log_warn("pppoe: short write %i/%i\n", n,s); + } +} + +static void pppoe_send_PADO(struct pppoe_serv_t *serv, const uint8_t *addr, const struct pppoe_tag *host_uniq, const struct pppoe_tag *relay_sid, const struct pppoe_tag *service_name) +{ + uint8_t pack[ETHER_MAX_LEN]; + uint8_t cookie[COOKIE_LENGTH]; + + setup_header(pack, serv->hwaddr, addr, CODE_PADO, 0); + + add_tag(pack, TAG_AC_NAME, (uint8_t *)conf_ac_name, strlen(conf_ac_name)); + if (conf_service_name) + add_tag(pack, TAG_SERVICE_NAME, (uint8_t *)conf_service_name, strlen(conf_service_name)); + + if (service_name) + add_tag2(pack, service_name); + + generate_cookie(serv, addr, cookie); + add_tag(pack, TAG_AC_COOKIE, cookie, COOKIE_LENGTH); + + if (host_uniq) + add_tag2(pack, host_uniq); + + if (relay_sid) + add_tag2(pack, relay_sid); + + if (conf_verbose) { + log_info2("send "); + print_packet(pack); + } + + __sync_add_and_fetch(&stat_PADO_sent, 1); + pppoe_send(serv->hnd.fd, pack); +} + +static void pppoe_send_err(struct pppoe_serv_t *serv, const uint8_t *addr, const struct pppoe_tag *host_uniq, const struct pppoe_tag *relay_sid, int code, int tag_type) +{ + uint8_t pack[ETHER_MAX_LEN]; + + setup_header(pack, serv->hwaddr, addr, code, 0); + + add_tag(pack, TAG_AC_NAME, (uint8_t *)conf_ac_name, strlen(conf_ac_name)); + add_tag(pack, tag_type, NULL, 0); + + if (host_uniq) + add_tag2(pack, host_uniq); + + if (relay_sid) + add_tag2(pack, relay_sid); + + if (conf_verbose) { + log_info2("send "); + print_packet(pack); + } + + pppoe_send(serv->hnd.fd, pack); +} + +static void pppoe_send_PADS(struct pppoe_conn_t *conn) +{ + uint8_t pack[ETHER_MAX_LEN]; + + setup_header(pack, conn->serv->hwaddr, conn->addr, CODE_PADS, conn->sid); + + add_tag(pack, TAG_AC_NAME, (uint8_t *)conf_ac_name, strlen(conf_ac_name)); + + add_tag2(pack, conn->service_name); + + if (conn->host_uniq) + add_tag2(pack, conn->host_uniq); + + if (conn->relay_sid) + add_tag2(pack, conn->relay_sid); + + if (conf_verbose) { + log_info2("send "); + print_packet(pack); + } + + __sync_add_and_fetch(&stat_PADS_sent, 1); + pppoe_send(conn->disc_sock, pack); +} + +static void pppoe_send_PADT(struct pppoe_conn_t *conn) +{ + uint8_t pack[ETHER_MAX_LEN]; + + setup_header(pack, conn->serv->hwaddr, conn->addr, CODE_PADT, conn->sid); + + add_tag(pack, TAG_AC_NAME, (uint8_t *)conf_ac_name, strlen(conf_ac_name)); + + add_tag2(pack, conn->service_name); + + if (conn->host_uniq) + add_tag2(pack, conn->host_uniq); + + if (conn->relay_sid) + add_tag2(pack, conn->relay_sid); + + if (conf_verbose) { + log_info2("send "); + print_packet(pack); + } + + pppoe_send(conn->disc_sock, pack); +} + +static void free_delayed_pado(struct delayed_pado_t *pado) +{ + triton_timer_del(&pado->timer); + + __sync_sub_and_fetch(&stat_delayed_pado, 1); + list_del(&pado->entry); + + if (pado->host_uniq) + _free(pado->host_uniq); + if (pado->relay_sid) + _free(pado->relay_sid); + if (pado->service_name) + _free(pado->service_name); + + mempool_free(pado); +} + +static void pado_timer(struct triton_timer_t *t) +{ + struct delayed_pado_t *pado = container_of(t, typeof(*pado), timer); + + if (!ppp_shutdown) + pppoe_send_PADO(pado->serv, pado->addr, pado->host_uniq, pado->relay_sid, pado->service_name); + + free_delayed_pado(pado); +} + +static void pppoe_recv_PADI(struct pppoe_serv_t *serv, uint8_t *pack, int size) +{ + struct ethhdr *ethhdr = (struct ethhdr *)pack; + struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); + struct pppoe_tag *tag; + struct pppoe_tag *host_uniq_tag = NULL; + struct pppoe_tag *relay_sid_tag = NULL; + struct pppoe_tag *service_name_tag = NULL; + int n, service_match = 0; + struct delayed_pado_t *pado; + + __sync_add_and_fetch(&stat_PADI_recv, 1); + + if (ppp_shutdown || pado_delay == -1) + return; + + if (hdr->sid) { + log_warn("pppoe: discarding PADI packet (sid is not zero)\n"); + return; + } + + if (conf_verbose) { + log_info2("recv "); + print_packet(pack); + } + + for (n = 0; n < ntohs(hdr->length); n += sizeof(*tag) + ntohs(tag->tag_len)) { + tag = (struct pppoe_tag *)(pack + ETH_HLEN + sizeof(*hdr) + n); + switch (ntohs(tag->tag_type)) { + case TAG_END_OF_LIST: + break; + case TAG_SERVICE_NAME: + if (conf_service_name && tag->tag_len) { + if (ntohs(tag->tag_len) != strlen(conf_service_name)) + break; + if (memcmp(tag->tag_data, conf_service_name, ntohs(tag->tag_len))) + break; + service_match = 1; + } else { + service_name_tag = tag; + service_match = 1; + } + break; + case TAG_HOST_UNIQ: + host_uniq_tag = tag; + break; + case TAG_RELAY_SESSION_ID: + relay_sid_tag = tag; + break; + } + } + + if (!service_match) { + if (conf_verbose) + log_warn("pppoe: discarding PADI packet (Service-Name mismatch)\n"); + return; + } + + if (pado_delay) { + list_for_each_entry(pado, &serv->pado_list, entry) { + if (memcmp(pado->addr, ethhdr->h_source, ETH_ALEN)) + continue; + if (conf_verbose) + log_warn("pppoe: discarding PADI packet (already queued)\n"); + return; + } + pado = mempool_alloc(pado_pool); + memset(pado, 0, sizeof(*pado)); + pado->serv = serv; + memcpy(pado->addr, ethhdr->h_source, ETH_ALEN); + + if (host_uniq_tag) { + pado->host_uniq = _malloc(sizeof(*host_uniq_tag) + ntohs(host_uniq_tag->tag_len)); + memcpy(pado->host_uniq, host_uniq_tag, sizeof(*host_uniq_tag) + ntohs(host_uniq_tag->tag_len)); + } + + if (relay_sid_tag) { + pado->relay_sid = _malloc(sizeof(*relay_sid_tag) + ntohs(relay_sid_tag->tag_len)); + memcpy(pado->relay_sid, relay_sid_tag, sizeof(*relay_sid_tag) + ntohs(relay_sid_tag->tag_len)); + } + + if (service_name_tag) { + pado->service_name = _malloc(sizeof(*service_name_tag) + ntohs(service_name_tag->tag_len)); + memcpy(pado->service_name, service_name_tag, sizeof(*service_name_tag) + ntohs(service_name_tag->tag_len)); + } + + pado->timer.expire = pado_timer; + pado->timer.period = pado_delay; + + triton_timer_add(&serv->ctx, &pado->timer, 0); + + list_add_tail(&pado->entry, &serv->pado_list); + __sync_add_and_fetch(&stat_delayed_pado, 1); + } else + pppoe_send_PADO(serv, ethhdr->h_source, host_uniq_tag, relay_sid_tag, service_name_tag); +} + +static void pppoe_recv_PADR(struct pppoe_serv_t *serv, uint8_t *pack, int size) +{ + struct ethhdr *ethhdr = (struct ethhdr *)pack; + struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); + struct pppoe_tag *tag; + struct pppoe_tag *host_uniq_tag = NULL; + struct pppoe_tag *relay_sid_tag = NULL; + struct pppoe_tag *ac_cookie_tag = NULL; + struct pppoe_tag *service_name_tag = NULL; + struct pppoe_tag *tr101_tag = NULL; + int n, service_match = 0; + struct pppoe_conn_t *conn; + int vendor_id; + + __sync_add_and_fetch(&stat_PADR_recv, 1); + + if (ppp_shutdown) + return; + + if (!memcmp(ethhdr->h_dest, bc_addr, ETH_ALEN)) { + if (conf_verbose) + log_warn("pppoe: discard PADR (destination address is broadcast)\n"); + return; + } + + if (hdr->sid) { + if (conf_verbose) + log_warn("pppoe: discarding PADR packet (sid is not zero)\n"); + return; + } + + if (conf_verbose) { + log_info2("recv "); + print_packet(pack); + } + + for (n = 0; n < ntohs(hdr->length); n += sizeof(*tag) + ntohs(tag->tag_len)) { + tag = (struct pppoe_tag *)(pack + ETH_HLEN + sizeof(*hdr) + n); + switch (ntohs(tag->tag_type)) { + case TAG_END_OF_LIST: + break; + case TAG_SERVICE_NAME: + service_name_tag = tag; + if (tag->tag_len == 0) + service_match = 1; + else if (conf_service_name) { + if (ntohs(tag->tag_len) != strlen(conf_service_name)) + break; + if (memcmp(tag->tag_data, conf_service_name, ntohs(tag->tag_len))) + break; + service_match = 1; + } else { + service_match = 1; + } + break; + case TAG_HOST_UNIQ: + host_uniq_tag = tag; + break; + case TAG_AC_COOKIE: + ac_cookie_tag = tag; + break; + case TAG_RELAY_SESSION_ID: + relay_sid_tag = tag; + break; + case TAG_VENDOR_SPECIFIC: + if (ntohs(tag->tag_len) < 4) + continue; + vendor_id = ntohl(*(uint32_t *)tag->tag_data); + if (vendor_id == VENDOR_ADSL_FORUM) + tr101_tag = tag; + break; + } + } + + if (!ac_cookie_tag) { + if (conf_verbose) + log_warn("pppoe: discard PADR packet (no AC-Cookie tag present)\n"); + return; + } + + if (ntohs(ac_cookie_tag->tag_len) != COOKIE_LENGTH) { + if (conf_verbose) + log_warn("pppoe: discard PADR packet (incorrect AC-Cookie tag length)\n"); + return; + } + + if (check_cookie(serv, ethhdr->h_source, (uint8_t *)ac_cookie_tag->tag_data)) { + if (conf_verbose) + log_warn("pppoe: discard PADR packet (incorrect AC-Cookie)\n"); + return; + } + + if (!service_match) { + if (conf_verbose) + log_warn("pppoe: Service-Name mismatch\n"); + pppoe_send_err(serv, ethhdr->h_source, host_uniq_tag, relay_sid_tag, CODE_PADS, TAG_SERVICE_NAME_ERROR); + return; + } + + pthread_mutex_lock(&serv->lock); + conn = find_channel(serv, (uint8_t *)ac_cookie_tag->tag_data); + if (conn && !conn->ppp.username) { + __sync_add_and_fetch(&stat_PADR_dup_recv, 1); + pppoe_send_PADS(conn); + } + pthread_mutex_unlock(&serv->lock); + + if (conn) + return; + + conn = allocate_channel(serv, ethhdr->h_source, host_uniq_tag, relay_sid_tag, service_name_tag, tr101_tag, (uint8_t *)ac_cookie_tag->tag_data); + if (!conn) + pppoe_send_err(serv, ethhdr->h_source, host_uniq_tag, relay_sid_tag, CODE_PADS, TAG_AC_SYSTEM_ERROR); + else { + pppoe_send_PADS(conn); + triton_context_call(&conn->ctx, (triton_event_func)connect_channel, conn); + } +} + +static void pppoe_recv_PADT(struct pppoe_serv_t *serv, uint8_t *pack) +{ + struct ethhdr *ethhdr = (struct ethhdr *)pack; + struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); + struct pppoe_conn_t *conn; + + if (!memcmp(ethhdr->h_dest, bc_addr, ETH_ALEN)) { + if (conf_verbose) + log_warn("pppoe: discard PADT (destination address is broadcast)\n"); + return; + } + + if (conf_verbose) { + log_info2("recv "); + print_packet(pack); + } + + pthread_mutex_lock(&serv->lock); + conn = serv->conn[ntohs(hdr->sid)]; + if (conn && !memcmp(conn->addr, ethhdr->h_source, ETH_ALEN)) + triton_context_call(&conn->ctx, (void (*)(void *))disconnect, conn); + pthread_mutex_unlock(&serv->lock); +} + +static int pppoe_serv_read(struct triton_md_handler_t *h) +{ + struct pppoe_serv_t *serv = container_of(h, typeof(*serv), hnd); + uint8_t pack[ETHER_MAX_LEN]; + struct ethhdr *ethhdr = (struct ethhdr *)pack; + struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); + int n; + + while (1) { + n = read(h->fd, pack, sizeof(pack)); + if (n < 0) { + if (errno == EAGAIN) + break; + log_error("pppoe: read: %s\n", strerror(errno)); + return 0; + } + + if (n < ETH_HLEN + sizeof(*hdr)) { + if (conf_verbose) + log_warn("pppoe: short packet received (%i)\n", n); + continue; + } + + if (mac_filter_check(ethhdr->h_source)) + continue; + + if (memcmp(ethhdr->h_dest, bc_addr, ETH_ALEN) && memcmp(ethhdr->h_dest, serv->hwaddr, ETH_ALEN)) + continue; + + if (!memcmp(ethhdr->h_source, bc_addr, ETH_ALEN)) { + if (conf_verbose) + log_warn("pppoe: discarding packet (host address is broadcast)\n"); + continue; + } + + if ((ethhdr->h_source[0] & 1) != 0) { + if (conf_verbose) + log_warn("pppoe: discarding packet (host address is not unicast)\n"); + continue; + } + + if (n < ETH_HLEN + sizeof(*hdr) + ntohs(hdr->length)) { + if (conf_verbose) + log_warn("pppoe: short packet received\n"); + continue; + } + + if (hdr->ver != 1) { + if (conf_verbose) + log_warn("pppoe: discarding packet (unsupported version %i)\n", hdr->ver); + continue; + } + + if (hdr->type != 1) { + if (conf_verbose) + log_warn("pppoe: discarding packet (unsupported type %i)\n", hdr->type); + } + + switch (hdr->code) { + case CODE_PADI: + pppoe_recv_PADI(serv, pack, n); + break; + case CODE_PADR: + pppoe_recv_PADR(serv, pack, n); + break; + case CODE_PADT: + pppoe_recv_PADT(serv, pack); + break; + } + } + return 0; +} + +static void pppoe_serv_close(struct triton_context_t *ctx) +{ + struct pppoe_serv_t *serv = container_of(ctx, typeof(*serv), ctx); + + triton_md_disable_handler(&serv->hnd, MD_MODE_READ | MD_MODE_WRITE); + + serv->stopping = 1; + + pthread_mutex_lock(&serv->lock); + if (!serv->conn_cnt) { + pthread_mutex_unlock(&serv->lock); + pppoe_server_free(serv); + return; + } + pthread_mutex_unlock(&serv->lock); +} + +void pppoe_server_start(const char *ifname, void *cli) +{ + struct pppoe_serv_t *serv; + int sock; + int opt = 1; + struct ifreq ifr; + struct sockaddr_ll sa; + + pthread_rwlock_rdlock(&serv_lock); + list_for_each_entry(serv, &serv_list, entry) { + if (!strcmp(serv->ifname, ifname)) { + if (cli) + cli_send(cli, "error: already exists\r\n"); + pthread_rwlock_unlock(&serv_lock); + return; + } + } + pthread_rwlock_unlock(&serv_lock); + + serv = _malloc(sizeof(*serv)); + memset(serv, 0, sizeof(*serv)); + + if (init_secret(serv)) { + if (cli) + cli_sendv(cli, "init secret failed\r\n"); + _free(serv); + return; + } + + sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_PPP_DISC)); + if (sock < 0) { + if (cli) + cli_sendv(cli, "socket: %s\r\n", strerror(errno)); + log_emerg("pppoe: socket: %s\n", strerror(errno)); + _free(serv); + return; + } + + if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt))) { + if (cli) + cli_sendv(cli, "setsockopt(SO_BROADCAST): %s\r\n", strerror(errno)); + log_emerg("pppoe: setsockopt(SO_BROADCAST): %s\n", strerror(errno)); + goto out_err; + } + + strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)); + if (ioctl(sock, SIOCGIFHWADDR, &ifr)) { + if (cli) + cli_sendv(cli, "ioctl(SIOCGIFHWADDR): %s\r\n", strerror(errno)); + log_emerg("pppoe: ioctl(SIOCGIFHWADDR): %s\n", strerror(errno)); + goto out_err; + } + +#ifdef ARPHDR_ETHER + if (ifr.ifr_hwaddr.sa_family != ARPHDR_ETHER) { + log_emerg("pppoe: interface %s is not ethernet\n", ifname); + goto out_err; + } +#endif + + if ((ifr.ifr_hwaddr.sa_data[0] & 1) != 0) { + if (cli) + cli_sendv(cli, "interface %s has not unicast address\r\n", ifname); + log_emerg("pppoe: interface %s has not unicast address\n", ifname); + goto out_err; + } + + memcpy(serv->hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN); + + if (ioctl(sock, SIOCGIFMTU, &ifr)) { + if (cli) + cli_sendv(cli, "ioctl(SIOCGIFMTU): %s\r\n", strerror(errno)); + log_emerg("pppoe: ioctl(SIOCGIFMTU): %s\n", strerror(errno)); + goto out_err; + } + + if (ifr.ifr_mtu < ETH_DATA_LEN) { + if (cli) + cli_sendv(cli, "interface %s has MTU of %i, should be %i\r\n", ifname, ifr.ifr_mtu, ETH_DATA_LEN); + log_emerg("pppoe: interface %s has MTU of %i, should be %i\n", ifname, ifr.ifr_mtu, ETH_DATA_LEN); + } + + if (ioctl(sock, SIOCGIFINDEX, &ifr)) { + if (cli) + cli_sendv(cli, "ioctl(SIOCGIFINDEX): %s\r\n", strerror(errno)); + log_emerg("pppoe: ioctl(SIOCGIFINDEX): %s\n", strerror(errno)); + goto out_err; + } + + memset(&sa, 0, sizeof(sa)); + sa.sll_family = AF_PACKET; + sa.sll_protocol = htons(ETH_P_PPP_DISC); + sa.sll_ifindex = ifr.ifr_ifindex; + + if (bind(sock, (struct sockaddr *)&sa, sizeof(sa))) { + if (cli) + cli_sendv(cli, "bind: %s\n", strerror(errno)); + log_emerg("pppoe: bind: %s\n", strerror(errno)); + goto out_err; + } + + if (fcntl(sock, F_SETFL, O_NONBLOCK)) { + if (cli) + cli_sendv(cli, "failed to set nonblocking mode: %s\n", strerror(errno)); + log_emerg("pppoe: failed to set nonblocking mode: %s\n", strerror(errno)); + goto out_err; + } + + serv->ctx.close = pppoe_serv_close; + serv->ctx.before_switch = log_switch; + serv->hnd.fd = sock; + serv->hnd.read = pppoe_serv_read; + serv->ifname = _strdup(ifname); + pthread_mutex_init(&serv->lock, NULL); + + INIT_LIST_HEAD(&serv->conn_list); + INIT_LIST_HEAD(&serv->pado_list); + + triton_context_register(&serv->ctx, NULL); + triton_md_register_handler(&serv->ctx, &serv->hnd); + triton_md_enable_handler(&serv->hnd, MD_MODE_READ); + triton_context_wakeup(&serv->ctx); + + pthread_rwlock_wrlock(&serv_lock); + list_add_tail(&serv->entry, &serv_list); + pthread_rwlock_unlock(&serv_lock); + + return; + +out_err: + close(sock); + _free(serv); +} + +static void _conn_stop(struct pppoe_conn_t *conn) +{ + ppp_terminate(&conn->ppp, 0, TERM_ADMIN_RESET); +} + +static void _server_stop(struct pppoe_serv_t *serv) +{ + struct pppoe_conn_t *conn; + + if (serv->stopping) + return; + + serv->stopping = 1; + triton_md_disable_handler(&serv->hnd, MD_MODE_READ | MD_MODE_WRITE); + + pthread_mutex_lock(&serv->lock); + if (!serv->conn_cnt) { + pthread_mutex_unlock(&serv->lock); + pppoe_server_free(serv); + return; + } + list_for_each_entry(conn, &serv->conn_list, entry) + triton_context_call(&conn->ctx, (triton_event_func)_conn_stop, conn); + pthread_mutex_unlock(&serv->lock); +} + +void pppoe_server_free(struct pppoe_serv_t *serv) +{ + struct delayed_pado_t *pado; + + pthread_rwlock_wrlock(&serv_lock); + list_del(&serv->entry); + pthread_rwlock_unlock(&serv_lock); + + while (!list_empty(&serv->pado_list)) { + pado = list_entry(serv->pado_list.next, typeof(*pado), entry); + free_delayed_pado(pado); + } + + triton_md_unregister_handler(&serv->hnd); + close(serv->hnd.fd); + triton_context_unregister(&serv->ctx); + _free(serv->ifname); + _free(serv); +} + +void pppoe_server_stop(const char *ifname) +{ + struct pppoe_serv_t *serv; + + pthread_rwlock_rdlock(&serv_lock); + list_for_each_entry(serv, &serv_list, entry) { + if (strcmp(serv->ifname, ifname)) + continue; + triton_context_call(&serv->ctx, (triton_event_func)_server_stop, serv); + break; + } + pthread_rwlock_unlock(&serv_lock); +} + +static int init_secret(struct pppoe_serv_t *serv) +{ + int fd; + DES_cblock key; + + fd = open("/dev/urandom", O_RDONLY); + if (fd < 0) { + log_emerg("pppoe: cann't open /dev/urandom: %s\n", strerror(errno)); + return -1; + } + + if (read(fd, serv->secret, SECRET_LENGTH) < 0) { + log_emerg("pppoe: faild to read /dev/urandom\n", strerror(errno)); + close(fd); + return -1; + } + + close(fd); + + memset(key, 0, sizeof(key)); + DES_random_key(&key); + DES_set_key(&key, &serv->des_ks); + + return 0; +} + +static void __init pppoe_init(void) +{ + struct conf_sect_t *s = conf_get_section("pppoe"); + struct conf_option_t *opt; + + conn_pool = mempool_create(sizeof(struct pppoe_conn_t)); + pado_pool = mempool_create(sizeof(struct delayed_pado_t)); + + if (!s) { + log_emerg("pppoe: no configuration, disabled...\n"); + return; + } + + list_for_each_entry(opt, &s->items, entry) { + if (!strcmp(opt->name, "interface")) { + if (opt->val) + pppoe_server_start(opt->val, NULL); + } else if (!strcmp(opt->name, "verbose")) { + if (atoi(opt->val) > 0) + conf_verbose = 1; + } else if (!strcmp(opt->name, "ac-name") || !strcmp(opt->name, "AC-Name")) { + if (opt->val && strlen(opt->val)) + conf_ac_name = _strdup(opt->val); + } else if (!strcmp(opt->name, "service-name") || !strcmp(opt->name, "Service-Name")) { + if (opt->val && strlen(opt->val)) + conf_service_name = _strdup(opt->val); + } else if (!strcmp(opt->name, "pado-delay") || !strcmp(opt->name, "PADO-delay")) { + if (dpado_parse(opt->val)) + _exit(EXIT_FAILURE); + } else if (!strcmp(opt->name, "ifname-in-sid")) { + if (!opt->val) + continue; + if (!strcmp(opt->val, "called-sid")) + conf_ifname_in_sid = 1; + else if (!strcmp(opt->val, "calling-sid")) + conf_ifname_in_sid = 2; + else if (!strcmp(opt->val, "both")) + conf_ifname_in_sid = 3; + else if (atoi(opt->val) >= 0) + conf_ifname_in_sid = atoi(opt->val); + } + } + + if (!conf_ac_name) + conf_ac_name = _strdup("accel-ppp"); +} + diff --git a/accel-pppd/ctrl/pppoe/pppoe.h b/accel-pppd/ctrl/pppoe/pppoe.h new file mode 100644 index 0000000..2264dd1 --- /dev/null +++ b/accel-pppd/ctrl/pppoe/pppoe.h @@ -0,0 +1,117 @@ +#ifndef __PPPOE_H +#define __PPPOE_H + +#include + +#include + +#include +#include + +/* PPPoE codes */ +#define CODE_PADI 0x09 +#define CODE_PADO 0x07 +#define CODE_PADR 0x19 +#define CODE_PADS 0x65 +#define CODE_PADT 0xA7 +#define CODE_SESS 0x00 + +/* PPPoE Tags */ +#define TAG_END_OF_LIST 0x0000 +#define TAG_SERVICE_NAME 0x0101 +#define TAG_AC_NAME 0x0102 +#define TAG_HOST_UNIQ 0x0103 +#define TAG_AC_COOKIE 0x0104 +#define TAG_VENDOR_SPECIFIC 0x0105 +#define TAG_RELAY_SESSION_ID 0x0110 +#define TAG_SERVICE_NAME_ERROR 0x0201 +#define TAG_AC_SYSTEM_ERROR 0x0202 +#define TAG_GENERIC_ERROR 0x0203 + +/* Discovery phase states */ +#define STATE_SENT_PADI 0 +#define STATE_RECEIVED_PADO 1 +#define STATE_SENT_PADR 2 +#define STATE_SESSION 3 +#define STATE_TERMINATED 4 + +/* Header size of a PPPoE packet */ +#define PPPOE_OVERHEAD 6 /* type, code, session, length */ +#define HDR_SIZE (sizeof(struct ethhdr) + PPPOE_OVERHEAD) +#define MAX_PPPOE_PAYLOAD (ETH_DATA_LEN - PPPOE_OVERHEAD) +#define MAX_PPPOE_MTU (MAX_PPPOE_PAYLOAD - 2) + +#define VENDOR_ADSL_FORUM 0xde9 + +#define MAX_SID 65534 +#define SECRET_LENGTH 16 +#define COOKIE_LENGTH 24 + +struct pppoe_tag_t +{ + struct list_head entry; + int type; + int len; +}; + +struct pppoe_packet_t +{ + uint8_t src[ETH_ALEN]; + uint8_t dst[ETH_ALEN]; + int code; + uint16_t sid; + struct list_head tags; +}; + +struct pppoe_serv_t +{ + struct list_head entry; + struct triton_context_t ctx; + struct triton_md_handler_t hnd; + uint8_t hwaddr[ETH_ALEN]; + char *ifname; + + uint8_t secret[SECRET_LENGTH]; + DES_key_schedule des_ks; + + pthread_mutex_t lock; + struct pppoe_conn_t *conn[MAX_SID]; + uint16_t sid; + int stopping:1; + + unsigned int conn_cnt; + struct list_head conn_list; + struct list_head pado_list; +}; + +extern int conf_verbose; +extern char *conf_service_name; +extern char *conf_ac_name; +extern char *conf_pado_delay; + +extern unsigned int stat_active; +extern unsigned int stat_delayed_pado; +extern unsigned long stat_PADI_recv; +extern unsigned long stat_PADO_sent; +extern unsigned long stat_PADR_recv; +extern unsigned long stat_PADR_dup_recv; +extern unsigned long stat_PADS_sent; + +extern pthread_rwlock_t serv_lock; +extern struct list_head serv_list; + +int mac_filter_check(const uint8_t *addr); +void pppoe_server_start(const char *intf, void *client); +void pppoe_server_stop(const char *intf); + +extern int pado_delay; +void dpado_check_next(int conn_cnt); +void dpado_check_prev(int conn_cnt); +int dpado_parse(const char *str); + +struct rad_packet_t; +int tr101_send_access_request(struct pppoe_tag *tr101, struct rad_packet_t *pack); +int tr101_send_accounting_request(struct pppoe_tag *tr101, struct rad_packet_t *pack); + +#endif + diff --git a/accel-pppd/ctrl/pppoe/tr101.c b/accel-pppd/ctrl/pppoe/tr101.c new file mode 100644 index 0000000..cfb0fbc --- /dev/null +++ b/accel-pppd/ctrl/pppoe/tr101.c @@ -0,0 +1,97 @@ +#include +#include +#include +#include + +#include "triton.h" +#include "ppp.h" +#include "log.h" +#include "radius.h" +#include "memdebug.h" + +#include "pppoe.h" + +#define OPT_CIRCUIT_ID 0x01 +#define OPT_REMOTE_AGENT_ID 0x02 +#define OPT_ACTUAL_DATA_RATE_UP 0x81 +#define OPT_ACTUAL_DATA_RATE_DOWN 0x82 +#define OPT_MIN_DATA_RATE_UP 0x83 +#define OPT_MAX_DATA_RATE_DOWN 0x84 + +static int tr101_send_request(struct pppoe_tag *tr101, struct rad_packet_t *pack, int type) +{ + uint8_t *ptr = (uint8_t *)tr101->tag_data + 4; + uint8_t *endptr = (uint8_t *)tr101->tag_data + ntohs(tr101->tag_len); + int id, len; + char str[64]; + + while (ptr < endptr) { + if (ptr + 2 > endptr) + goto inval; + id = *ptr++; + len = *ptr++; + if (ptr + len - 2 > endptr) + goto inval; + if (type && id > 0x80) + continue; + switch (id) { + case OPT_CIRCUIT_ID: + if (len - 2 > 63) + goto inval; + memcpy(str, ptr, len); + str[len - 2] = 0; + if (rad_packet_add_str(pack, "ADSL-Forum", "ADSL-Agent-Circuit-Id", str)) + return -1; + break; + case OPT_REMOTE_AGENT_ID: + if (len - 2 > 63) + goto inval; + memcpy(str, ptr, len); + str[len - 2] = 0; + if (rad_packet_add_str(pack, "ADSL-Forum", "ADSL-Agent-Remote-Id", str)) + return -1; + break; + case OPT_ACTUAL_DATA_RATE_UP: + if (len != 6) + goto inval; + if (rad_packet_add_int(pack, "ADSL-Forum", "Actual-Data-Rate-Upstream", ntohl(*(uint32_t *)ptr))) + return -1; + break; + case OPT_ACTUAL_DATA_RATE_DOWN: + if (len != 6) + goto inval; + if (rad_packet_add_int(pack, "ADSL-Forum", "Actual-Data-Rate-Downstream", ntohl(*(uint32_t *)ptr))) + return -1; + break; + case OPT_MIN_DATA_RATE_UP: + if (len != 6) + goto inval; + if (rad_packet_add_int(pack, "ADSL-Forum", "Minimum-Data-Rate-Upstream", ntohl(*(uint32_t *)ptr))) + return -1; + break; + case OPT_MAX_DATA_RATE_DOWN: + if (len != 6) + goto inval; + if (rad_packet_add_int(pack, "ADSL-Forum", "Maximum-Data-Rate-Upstream", ntohl(*(uint32_t *)ptr))) + return -1; + break; + } + ptr += len - 2; + } + + return 0; + +inval: + log_ppp_warn("pppoe:tr101: invalid tag received\n"); + return -1; +} + +int tr101_send_access_request(struct pppoe_tag *tr101, struct rad_packet_t *pack) +{ + return tr101_send_request(tr101, pack, 1); +} + +int tr101_send_accounting_request(struct pppoe_tag *tr101, struct rad_packet_t *pack) +{ + return tr101_send_request(tr101, pack, 0); +} diff --git a/accel-pppd/ctrl/pptp/CMakeLists.txt b/accel-pppd/ctrl/pptp/CMakeLists.txt new file mode 100644 index 0000000..3199e7f --- /dev/null +++ b/accel-pppd/ctrl/pptp/CMakeLists.txt @@ -0,0 +1,5 @@ +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +ADD_LIBRARY(pptp SHARED pptp.c) + +INSTALL(TARGETS pptp LIBRARY DESTINATION lib/accel-ppp ) diff --git a/accel-pppd/ctrl/pptp/pptp.c b/accel-pppd/ctrl/pptp/pptp.c new file mode 100644 index 0000000..687aecb --- /dev/null +++ b/accel-pppd/ctrl/pptp/pptp.c @@ -0,0 +1,775 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "if_pppox.h" + +#include "events.h" +#include "list.h" +#include "pptp_prot.h" +#include "triton.h" +#include "log.h" +#include "ppp.h" +#include "mempool.h" +#include "iprange.h" +#include "utils.h" +#include "cli.h" + +#include "memdebug.h" + +#define STATE_IDLE 0 +#define STATE_ESTB 1 +#define STATE_PPP 2 +#define STATE_FIN 3 +#define STATE_CLOSE 4 + +struct pptp_conn_t +{ + struct triton_context_t ctx; + struct triton_md_handler_t hnd; + struct triton_timer_t timeout_timer; + struct triton_timer_t echo_timer; + int call_id; + int peer_call_id; + int state; + int echo_sent; + + uint8_t *in_buf; + int in_size; + uint8_t *out_buf; + int out_size; + int out_pos; + + struct ppp_ctrl_t ctrl; + struct ppp_t ppp; +}; + +static int conf_timeout = 5; +static int conf_echo_interval = 0; +static int conf_echo_failure = 3; +static int conf_verbose = 0; +static mempool_t conn_pool; + +static unsigned int stat_starting; +static unsigned int stat_active; + +static int pptp_read(struct triton_md_handler_t *h); +static int pptp_write(struct triton_md_handler_t *h); +static void pptp_timeout(struct triton_timer_t *); +static void ppp_started(struct ppp_t *); +static void ppp_finished(struct ppp_t *); + +static void disconnect(struct pptp_conn_t *conn) +{ + log_ppp_debug("pptp: disconnect\n"); + + triton_md_unregister_handler(&conn->hnd); + close(conn->hnd.fd); + + if (conn->timeout_timer.tpd) + triton_timer_del(&conn->timeout_timer); + + if (conn->echo_timer.tpd) + triton_timer_del(&conn->echo_timer); + + if (conn->state == STATE_PPP) { + __sync_sub_and_fetch(&stat_active, 1); + conn->state = STATE_CLOSE; + ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); + } else if (conn->state != STATE_CLOSE) + __sync_sub_and_fetch(&stat_starting, 1); + + triton_event_fire(EV_CTRL_FINISHED, &conn->ppp); + + log_ppp_info1("disconnected\n"); + + triton_context_unregister(&conn->ctx); + + if (conn->ppp.chan_name) + _free(conn->ppp.chan_name); + + _free(conn->in_buf); + _free(conn->out_buf); + _free(conn->ctrl.calling_station_id); + _free(conn->ctrl.called_station_id); + mempool_free(conn); +} + +static int post_msg(struct pptp_conn_t *conn, void *buf, int size) +{ + int n; + if (conn->out_size) { + log_error("pptp: buffer is not empty\n"); + return -1; + } + + n=write(conn->hnd.fd, buf, size); + if (n < 0) { + if (errno == EINTR || errno == EAGAIN) + n = 0; + else { + if (errno != EPIPE) { + if (conf_verbose) + log_ppp_info2("pptp: write: %s\n", strerror(errno)); + return -1; + } + } + } + + if ( nout_buf, buf + n, size - n); + triton_md_enable_handler(&conn->hnd, MD_MODE_WRITE); + } + + return 0; +} + +static int send_pptp_stop_ctrl_conn_rqst(struct pptp_conn_t *conn, int reason) +{ + struct pptp_stop_ctrl_conn msg = { + .header = PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RQST), + .reason_result = hton8(reason), + }; + + if (conf_verbose) + log_ppp_info2("send [PPTP Stop-Ctrl-Conn-Request ]\n", reason); + + return post_msg(conn, &msg, sizeof(msg)); +} + +static int send_pptp_stop_ctrl_conn_rply(struct pptp_conn_t *conn, int reason, int err_code) +{ + struct pptp_stop_ctrl_conn msg = { + .header = PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RPLY), + .reason_result = hton8(reason), + .error_code = hton8(err_code), + }; + + if (conf_verbose) + log_ppp_info2("send [PPTP Stop-Ctrl-Conn-Reply ]\n", msg.reason_result, msg.error_code); + + return post_msg(conn, &msg, sizeof(msg)); +} +static int pptp_stop_ctrl_conn_rqst(struct pptp_conn_t *conn) +{ + struct pptp_stop_ctrl_conn *msg = (struct pptp_stop_ctrl_conn *)conn->in_buf; + if (conf_verbose) + log_ppp_info2("recv [PPTP Stop-Ctrl-Conn-Request ]\n", msg->reason_result); + + send_pptp_stop_ctrl_conn_rply(conn, PPTP_CONN_STOP_OK, 0); + + return -1; +} + +static int pptp_stop_ctrl_conn_rply(struct pptp_conn_t *conn) +{ + struct pptp_stop_ctrl_conn *msg = (struct pptp_stop_ctrl_conn*)conn->in_buf; + if (conf_verbose) + log_ppp_info2("recv [PPTP Stop-Ctrl-Conn-Reply ]\n", msg->reason_result, msg->error_code); + return -1; +} + +static int send_pptp_start_ctrl_conn_rply(struct pptp_conn_t *conn, int res_code, int err_code) +{ + struct pptp_start_ctrl_conn msg = { + .header = PPTP_HEADER_CTRL(PPTP_START_CTRL_CONN_RPLY), + .version = htons(PPTP_VERSION), + .result_code = res_code, + .error_code = err_code, + .framing_cap = htonl(3), + .bearer_cap = htonl(3), + .max_channels = htons(1), + .firmware_rev = htons(PPTP_FIRMWARE_VERSION), + }; + + memset(msg.hostname, 0, sizeof(msg.hostname)); + strcpy((char*)msg.hostname, PPTP_HOSTNAME); + + memset(msg.vendor, 0, sizeof(msg.vendor)); + strcpy((char*)msg.vendor, PPTP_VENDOR); + + if (conf_verbose) + log_ppp_info2("send [PPTP Start-Ctrl-Conn-Reply ]\n", msg.version, msg.result_code, msg.error_code, ntohl(msg.framing_cap), ntohl(msg.bearer_cap), ntohs(msg.max_channels)); + + return post_msg(conn, &msg, sizeof(msg)); +} + +static int pptp_start_ctrl_conn_rqst(struct pptp_conn_t *conn) +{ + struct pptp_start_ctrl_conn *msg = (struct pptp_start_ctrl_conn *)conn->in_buf; + + if (conf_verbose) + log_ppp_info2("recv [PPTP Start-Ctrl-Conn-Request ]\n", msg->version, ntohl(msg->framing_cap), ntohl(msg->bearer_cap), ntohs(msg->max_channels)); + + if (conn->state != STATE_IDLE) { + log_ppp_warn("unexpected PPTP_START_CTRL_CONN_RQST\n"); + if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_EXISTS, 0)) + return -1; + return 0; + } + + if (msg->version != htons(PPTP_VERSION)) { + log_ppp_warn("PPTP version mismatch: expecting %x, received %s\n", PPTP_VERSION, msg->version); + if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_PROTOCOL, 0)) + return -1; + return 0; + } + /*if (!(ntohl(msg->framing_cap) & PPTP_FRAME_SYNC)) { + log_ppp_warn("connection does not supports sync mode\n"); + if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_GE, 0)) + return -1; + return 0; + }*/ + if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_SUCCESS, 0)) + return -1; + + triton_timer_mod(&conn->timeout_timer, 0); + + conn->state = STATE_ESTB; + + return 0; +} + +static int send_pptp_out_call_rply(struct pptp_conn_t *conn, struct pptp_out_call_rqst *rqst, int call_id, int res_code, int err_code) +{ + struct pptp_out_call_rply msg = { + .header = PPTP_HEADER_CTRL(PPTP_OUT_CALL_RPLY), + .call_id = htons(call_id), + .call_id_peer = rqst->call_id, + .result_code = res_code, + .error_code = err_code, + .cause_code = 0, + .speed = rqst->bps_max, + .recv_size = rqst->recv_size, + .delay = 0, + .channel = 0, + }; + + if (conf_verbose) + log_ppp_info2("send [PPTP Outgoing-Call-Reply ]\n", ntohs(msg.call_id), ntohs(msg.call_id_peer), msg.result_code, msg.error_code, ntohs(msg.cause_code), ntohl(msg.speed), ntohs(msg.recv_size), ntohs(msg.delay), ntohl(msg.channel)); + + return post_msg(conn, &msg, sizeof(msg)); +} + +static int pptp_out_call_rqst(struct pptp_conn_t *conn) +{ + struct pptp_out_call_rqst *msg = (struct pptp_out_call_rqst *)conn->in_buf; + struct sockaddr_pppox src_addr, dst_addr; + struct sockaddr_in addr; + socklen_t addrlen; + int pptp_sock; + + if (conf_verbose) + log_ppp_info2("recv [PPTP Outgoing-Call-Request ]\n", ntohs(msg->call_id), ntohs(msg->call_sernum), ntohl(msg->bps_min), ntohl(msg->bps_max), ntohl(msg->bearer), ntohl(msg->framing), ntohs(msg->recv_size), ntohs(msg->delay)); + + if (conn->state != STATE_ESTB) { + log_ppp_warn("unexpected PPTP_OUT_CALL_RQST\n"); + if (send_pptp_out_call_rply(conn, msg, 0, PPTP_CALL_RES_GE, PPTP_GE_NOCONN)) + return -1; + return 0; + } + + memset(&src_addr, 0, sizeof(src_addr)); + src_addr.sa_family = AF_PPPOX; + src_addr.sa_protocol = PX_PROTO_PPTP; + src_addr.sa_addr.pptp.call_id = 0; + addrlen = sizeof(addr); + getsockname(conn->hnd.fd, (struct sockaddr*)&addr, &addrlen); + src_addr.sa_addr.pptp.sin_addr = addr.sin_addr; + + memset(&dst_addr, 0, sizeof(dst_addr)); + dst_addr.sa_family = AF_PPPOX; + dst_addr.sa_protocol = PX_PROTO_PPTP; + dst_addr.sa_addr.pptp.call_id = htons(msg->call_id); + addrlen = sizeof(addr); + getpeername(conn->hnd.fd, (struct sockaddr*)&addr, &addrlen); + dst_addr.sa_addr.pptp.sin_addr = addr.sin_addr; + + pptp_sock = socket(AF_PPPOX, SOCK_STREAM, PX_PROTO_PPTP); + if (pptp_sock < 0) { + log_ppp_error("failed to create PPTP socket (%s)\n", strerror(errno)); + return -1; + } + if (bind(pptp_sock, (struct sockaddr*)&src_addr, sizeof(src_addr))) { + log_ppp_error("failed to bind PPTP socket (%s)\n", strerror(errno)); + close(pptp_sock); + return -1; + } + addrlen = sizeof(src_addr); + getsockname(pptp_sock, (struct sockaddr*)&src_addr, &addrlen); + + if (connect(pptp_sock, (struct sockaddr*)&dst_addr, sizeof(dst_addr))) { + log_ppp_error("failed to connect PPTP socket (%s)\n", strerror(errno)); + close(pptp_sock); + return -1; + } + + if (send_pptp_out_call_rply(conn, msg, src_addr.sa_addr.pptp.call_id, PPTP_CALL_RES_OK, 0)) + return -1; + + conn->call_id = src_addr.sa_addr.pptp.call_id; + conn->peer_call_id = msg->call_id; + conn->ppp.fd = pptp_sock; + conn->ppp.chan_name = _strdup(inet_ntoa(dst_addr.sa_addr.pptp.sin_addr)); + + triton_event_fire(EV_CTRL_STARTED, &conn->ppp); + + if (establish_ppp(&conn->ppp)) { + close(pptp_sock); + //if (send_pptp_stop_ctrl_conn_rqst(conn, 0, 0)) + conn->state = STATE_FIN; + return -1; + } + conn->state = STATE_PPP; + __sync_sub_and_fetch(&stat_starting, 1); + __sync_add_and_fetch(&stat_active, 1); + + if (conn->timeout_timer.tpd) + triton_timer_del(&conn->timeout_timer); + + if (conf_echo_interval) { + conn->echo_timer.period = conf_echo_interval * 1000; + triton_timer_add(&conn->ctx, &conn->echo_timer, 0); + } + + return 0; +} + +static int send_pptp_call_disconnect_notify(struct pptp_conn_t *conn, int result) +{ + struct pptp_call_clear_ntfy msg = { + .header = PPTP_HEADER_CTRL(PPTP_CALL_CLEAR_NTFY), + .call_id = htons(conn->peer_call_id), + .result_code = result, + .error_code = 0, + .cause_code = 0, + }; + + if (conf_verbose) + log_ppp_info2("send [PPTP Call-Disconnect-Notify ]\n", ntohs(msg.call_id), msg.result_code, msg.error_code, msg.cause_code); + + return post_msg(conn, &msg, sizeof(msg)); +} + +static int pptp_call_clear_rqst(struct pptp_conn_t *conn) +{ + struct pptp_call_clear_rqst *rqst = (struct pptp_call_clear_rqst *)conn->in_buf; + + if (conf_verbose) + log_ppp_info2("recv [PPTP Call-Clear-Request ]\n", ntohs(rqst->call_id)); + + if (conn->state == STATE_PPP) { + __sync_sub_and_fetch(&stat_active, 1); + conn->state = STATE_CLOSE; + ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); + } + + return send_pptp_call_disconnect_notify(conn, 4); +} + +static int pptp_echo_rqst(struct pptp_conn_t *conn) +{ + struct pptp_echo_rqst *in_msg = (struct pptp_echo_rqst *)conn->in_buf; + struct pptp_echo_rply out_msg = { + .header = PPTP_HEADER_CTRL(PPTP_ECHO_RPLY), + .identifier = in_msg->identifier, + .result_code = 1, + }; + + if (conf_verbose) { + log_ppp_debug("recv [PPTP Echo-Request ]\n", in_msg->identifier); + log_ppp_debug("send [PPTP Echo-Reply ]\n", out_msg.identifier); + } + + return post_msg(conn, &out_msg, sizeof(out_msg)); +} + +static int pptp_echo_rply(struct pptp_conn_t *conn) +{ + struct pptp_echo_rply *msg = (struct pptp_echo_rply *)conn->in_buf; + + if (conf_verbose) + log_ppp_debug("recv [PPTP Echo-Reply ]\n", msg->identifier); + + if (msg->identifier != conn->echo_sent) { + log_ppp_warn("pptp:echo: identifier mismatch\n"); + //return -1; + } + conn->echo_sent = 0; + return 0; +} +static void pptp_send_echo(struct triton_timer_t *t) +{ + struct pptp_conn_t *conn = container_of(t, typeof(*conn), echo_timer); + struct pptp_echo_rqst msg = { + .header = PPTP_HEADER_CTRL(PPTP_ECHO_RQST), + }; + + if (++conn->echo_sent == conf_echo_failure) { + log_ppp_warn("pptp: no echo reply\n"); + disconnect(conn); + return; + } + + conn->echo_sent = random(); + msg.identifier = conn->echo_sent; + + if (conf_verbose) + log_ppp_debug("send [PPTP Echo-Request ]\n", msg.identifier); + + if (post_msg(conn, &msg, sizeof(msg))) + disconnect(conn); +} + +static int process_packet(struct pptp_conn_t *conn) +{ + struct pptp_header *hdr = (struct pptp_header *)conn->in_buf; + switch(ntohs(hdr->ctrl_type)) + { + case PPTP_START_CTRL_CONN_RQST: + return pptp_start_ctrl_conn_rqst(conn); + case PPTP_STOP_CTRL_CONN_RQST: + return pptp_stop_ctrl_conn_rqst(conn); + case PPTP_STOP_CTRL_CONN_RPLY: + return pptp_stop_ctrl_conn_rply(conn); + case PPTP_OUT_CALL_RQST: + return pptp_out_call_rqst(conn); + case PPTP_ECHO_RQST: + return pptp_echo_rqst(conn); + case PPTP_ECHO_RPLY: + return pptp_echo_rply(conn); + case PPTP_CALL_CLEAR_RQST: + return pptp_call_clear_rqst(conn); + case PPTP_SET_LINK_INFO: + if (conf_verbose) + log_ppp_info2("recv [PPTP Set-Link-Info]\n"); + return 0; + default: + log_ppp_warn("recv [PPTP Unknown (%x)]\n", ntohs(hdr->ctrl_type)); + } + return 0; +} + +static int pptp_read(struct triton_md_handler_t *h) +{ + struct pptp_conn_t *conn=container_of(h,typeof(*conn),hnd); + struct pptp_header *hdr=(struct pptp_header *)conn->in_buf; + int n; + + while(1) { + n = read(h->fd, conn->in_buf + conn->in_size, PPTP_CTRL_SIZE_MAX - conn->in_size); + if (n < 0) { + if (errno == EINTR) + continue; + if (errno == EAGAIN) + return 0; + log_ppp_error("pptp: read: %s\n",strerror(errno)); + goto drop; + } + if (n == 0) { + if (conf_verbose) + log_ppp_info2("pptp: disconnect by peer\n"); + goto drop; + } + conn->in_size += n; + if (conn->in_size >= sizeof(*hdr)) { + if (hdr->magic != htonl(PPTP_MAGIC)) { + log_ppp_error("pptp: invalid magic\n"); + goto drop; + } + if (ntohs(hdr->length) >= PPTP_CTRL_SIZE_MAX) { + log_ppp_error("pptp: message is too long\n"); + goto drop; + } + if (ntohs(hdr->length) > conn->in_size) + continue; + if (ntohs(hdr->length) <= conn->in_size) { + if (ntohs(hdr->length) != PPTP_CTRL_SIZE(ntohs(hdr->ctrl_type))) { + log_ppp_error("pptp: invalid message length\n"); + goto drop; + } + if (process_packet(conn)) + goto drop; + conn->in_size -= ntohs(hdr->length); + if (conn->in_size) + memmove(conn->in_buf, conn->in_buf + ntohs(hdr->length), conn->in_size); + } + } + } +drop: + disconnect(conn); + return 1; +} +static int pptp_write(struct triton_md_handler_t *h) +{ + struct pptp_conn_t *conn = container_of(h, typeof(*conn), hnd); + int n; + + while (1) { + n = write(h->fd, conn->out_buf+conn->out_pos, conn->out_size-conn->out_pos); + + if (n < 0) { + if (errno == EINTR) + continue; + if (errno == EAGAIN) + n = 0; + else { + if (errno != EPIPE) { + if (conf_verbose) + log_ppp_info2("pptp: post_msg: %s\n", strerror(errno)); + } + disconnect(conn); + return 1; + } + } + + conn->out_pos += n; + if (conn->out_pos == conn->out_size) { + conn->out_pos = 0; + conn->out_size = 0; + triton_md_disable_handler(h, MD_MODE_WRITE); + return 0; + } + } +} +static void pptp_timeout(struct triton_timer_t *t) +{ + struct pptp_conn_t *conn = container_of(t, typeof(*conn), timeout_timer); + disconnect(conn); +} +static void pptp_close(struct triton_context_t *ctx) +{ + struct pptp_conn_t *conn = container_of(ctx, typeof(*conn), ctx); + if (conn->state == STATE_PPP) { + __sync_sub_and_fetch(&stat_active, 1); + conn->state = STATE_CLOSE; + ppp_terminate(&conn->ppp, TERM_ADMIN_RESET, 1); + if (send_pptp_call_disconnect_notify(conn, 3)) { + triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); + return; + } + } else { + if (send_pptp_stop_ctrl_conn_rqst(conn, 0)) { + triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); + return; + } + } + + if (conn->timeout_timer.tpd) + triton_timer_mod(&conn->timeout_timer, 0); + else + triton_timer_add(ctx, &conn->timeout_timer, 0); +} +static void ppp_started(struct ppp_t *ppp) +{ + log_ppp_debug("pptp: ppp started\n"); +} +static void ppp_finished(struct ppp_t *ppp) +{ + struct pptp_conn_t *conn = container_of(ppp, typeof(*conn), ppp); + + if (conn->state != STATE_CLOSE) { + log_ppp_debug("pptp: ppp finished\n"); + conn->state = STATE_CLOSE; + __sync_sub_and_fetch(&stat_active, 1); + + if (send_pptp_call_disconnect_notify(conn, 3)) + triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); + else if (send_pptp_stop_ctrl_conn_rqst(conn, 0)) + triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); + else { + if (conn->timeout_timer.tpd) + triton_timer_mod(&conn->timeout_timer, 0); + else + triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); + } + } +} + +//================================== + +struct pptp_serv_t +{ + struct triton_context_t ctx; + struct triton_md_handler_t hnd; +}; + +static int pptp_connect(struct triton_md_handler_t *h) +{ + struct sockaddr_in addr; + socklen_t size = sizeof(addr); + int sock; + struct pptp_conn_t *conn; + + while(1) { + sock = accept(h->fd, (struct sockaddr *)&addr, &size); + if (sock < 0) { + if (errno == EAGAIN) + return 0; + log_error("pptp: accept failed: %s\n", strerror(errno)); + continue; + } + + if (ppp_shutdown) { + close(sock); + continue; + } + + log_info2("pptp: new connection from %s\n", inet_ntoa(addr.sin_addr)); + + if (iprange_client_check(addr.sin_addr.s_addr)) { + log_warn("pptp: IP is out of client-ip-range, droping connection...\n"); + close(sock); + continue; + } + + if (fcntl(sock, F_SETFL, O_NONBLOCK)) { + log_error("pptp: failed to set nonblocking mode: %s, closing connection...\n", strerror(errno)); + close(sock); + continue; + } + + conn = mempool_alloc(conn_pool); + memset(conn, 0, sizeof(*conn)); + conn->hnd.fd = sock; + conn->hnd.read = pptp_read; + conn->hnd.write = pptp_write; + conn->ctx.close = pptp_close; + conn->ctx.before_switch = log_switch; + conn->in_buf = _malloc(PPTP_CTRL_SIZE_MAX); + conn->out_buf = _malloc(PPTP_CTRL_SIZE_MAX); + conn->timeout_timer.expire = pptp_timeout; + conn->timeout_timer.period = conf_timeout * 1000; + conn->echo_timer.expire = pptp_send_echo; + conn->ctrl.ctx = &conn->ctx; + conn->ctrl.started = ppp_started; + conn->ctrl.finished = ppp_finished; + conn->ctrl.max_mtu = PPTP_MAX_MTU; + conn->ctrl.name = "pptp"; + + conn->ctrl.calling_station_id = _malloc(17); + conn->ctrl.called_station_id = _malloc(17); + u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.calling_station_id); + getsockname(sock, &addr, &size); + u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.called_station_id); + + ppp_init(&conn->ppp); + conn->ppp.ctrl = &conn->ctrl; + + triton_context_register(&conn->ctx, &conn->ppp); + triton_md_register_handler(&conn->ctx, &conn->hnd); + triton_md_enable_handler(&conn->hnd,MD_MODE_READ); + triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); + triton_context_wakeup(&conn->ctx); + + triton_event_fire(EV_CTRL_STARTING, &conn->ppp); + + __sync_add_and_fetch(&stat_starting, 1); + } + return 0; +} +static void pptp_serv_close(struct triton_context_t *ctx) +{ + struct pptp_serv_t *s=container_of(ctx,typeof(*s),ctx); + triton_md_unregister_handler(&s->hnd); + close(s->hnd.fd); + triton_context_unregister(ctx); +} + +static struct pptp_serv_t serv= +{ + .hnd.read = pptp_connect, + .ctx.close = pptp_serv_close, + .ctx.before_switch = log_switch, +}; + +static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "pptp:\r\n"); + cli_sendv(client," starting: %u\r\n", stat_starting); + cli_sendv(client," active: %u\r\n", stat_active); + + return CLI_CMD_OK; +} + +static void load_config(void) +{ + char *opt; + + opt = conf_get_opt("pptp", "timeout"); + if (opt && atoi(opt) > 0) + conf_timeout = atoi(opt); + + opt = conf_get_opt("pptp", "echo-interval"); + if (opt && atoi(opt) >= 0) + conf_echo_interval = atoi(opt); + + opt = conf_get_opt("pptp", "echo-failure"); + if (opt && atoi(opt) > 0) + conf_echo_failure = atoi(opt); + + opt = conf_get_opt("pptp", "verbose"); + if (opt && atoi(opt) > 0) + conf_verbose = 1; +} + +static void __init pptp_init(void) +{ + struct sockaddr_in addr; + char *opt; + + serv.hnd.fd = socket(PF_INET, SOCK_STREAM, 0); + if (serv.hnd.fd < 0) { + log_emerg("pptp: failed to create server socket: %s\n", strerror(errno)); + return; + } + addr.sin_family = AF_INET; + addr.sin_port = htons(PPTP_PORT); + + opt = conf_get_opt("pptp", "bind"); + if (opt) + addr.sin_addr.s_addr = inet_addr(opt); + else + addr.sin_addr.s_addr = htonl(INADDR_ANY); + + setsockopt(serv.hnd.fd, SOL_SOCKET, SO_REUSEADDR, &serv.hnd.fd, 4); + if (bind (serv.hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { + log_emerg("pptp: failed to bind socket: %s\n", strerror(errno)); + close(serv.hnd.fd); + return; + } + + if (listen (serv.hnd.fd, 100) < 0) { + log_emerg("pptp: failed to listen socket: %s\n", strerror(errno)); + close(serv.hnd.fd); + return; + } + + if (fcntl(serv.hnd.fd, F_SETFL, O_NONBLOCK)) { + log_emerg("pptp: failed to set nonblocking mode: %s\n", strerror(errno)); + close(serv.hnd.fd); + return; + } + + conn_pool = mempool_create(sizeof(struct pptp_conn_t)); + + load_config(); + + triton_context_register(&serv.ctx, NULL); + triton_md_register_handler(&serv.ctx, &serv.hnd); + triton_md_enable_handler(&serv.hnd, MD_MODE_READ); + triton_context_wakeup(&serv.ctx); + + cli_register_simple_cmd2(show_stat_exec, NULL, 2, "show", "stat"); + + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); +} + diff --git a/accel-pppd/ctrl/pptp/pptp_prot.h b/accel-pppd/ctrl/pptp/pptp_prot.h new file mode 100644 index 0000000..ee8cb34 --- /dev/null +++ b/accel-pppd/ctrl/pptp/pptp_prot.h @@ -0,0 +1,299 @@ +#ifndef PPTP_PROT_H +#define PPTP_PROT_H + +#include + +#define PPTP_MAX_MTU 1436 + +#define hton8(x) (x) +#define ntoh8(x) (x) +#define hton16(x) htons(x) +#define ntoh16(x) ntohs(x) +#define hton32(x) htonl(x) +#define ntoh32(x) ntohl(x) + +/* PPTP magic numbers: ----------------------------------------- */ + +#define PPTP_MAGIC 0x1A2B3C4D /* Magic cookie for PPTP datagrams */ +#define PPTP_PORT 1723 /* PPTP TCP port number */ +#define PPTP_PROTO 47 /* PPTP IP protocol number */ + +/* PPTP result codes:---------------------------------------- */ +#define PPTP_CONN_RES_SUCCESS 1 +#define PPTP_CONN_RES_GE 2 +#define PPTP_CONN_RES_EXISTS 3 +#define PPTP_CONN_RES_AUTH 4 +#define PPTP_CONN_RES_PROTOCOL 5 + +#define PPTP_CONN_STOP_OK 1 +#define PPTP_CONN_STOP_GE 2 + +#define PPTP_CALL_RES_OK 1 +#define PPTP_CALL_RES_GE 2 + +#define PPTP_GE_NOCONN 1 + +/* Control Connection Message Types: --------------------------- */ + +#define PPTP_MESSAGE_CONTROL 1 +#define PPTP_MESSAGE_MANAGE 2 + +/* Control Message Types: -------------------------------------- */ + +/* (Control Connection Management) */ +#define PPTP_START_CTRL_CONN_RQST 1 +#define PPTP_START_CTRL_CONN_RPLY 2 +#define PPTP_STOP_CTRL_CONN_RQST 3 +#define PPTP_STOP_CTRL_CONN_RPLY 4 +#define PPTP_ECHO_RQST 5 +#define PPTP_ECHO_RPLY 6 + +/* (Call Management) */ +#define PPTP_OUT_CALL_RQST 7 +#define PPTP_OUT_CALL_RPLY 8 +#define PPTP_IN_CALL_RQST 9 +#define PPTP_IN_CALL_RPLY 10 +#define PPTP_IN_CALL_CONNECT 11 +#define PPTP_CALL_CLEAR_RQST 12 +#define PPTP_CALL_CLEAR_NTFY 13 + +/* (Error Reporting) */ +#define PPTP_WAN_ERR_NTFY 14 + +/* (PPP Session Control) */ +#define PPTP_SET_LINK_INFO 15 + +/* PPTP version information: --------------------------------------*/ +#define PPTP_VERSION_STRING "1.00" +#define PPTP_VERSION 0x100 +#define PPTP_FIRMWARE_STRING "0.01" +#define PPTP_FIRMWARE_VERSION 0x001 + +#define PPTP_HOSTNAME "local" +#define PPTP_VENDOR "cananian" + +/* PPTP capabilities: ---------------------------------------------*/ + +/* (Framing capabilities for msg sender) */ +#define PPTP_FRAME_ASYNC 1 +#define PPTP_FRAME_SYNC 2 +#define PPTP_FRAME_ANY 3 + +/* (Bearer capabilities for msg sender) */ +#define PPTP_BEARER_ANALOG 1 +#define PPTP_BEARER_DIGITAL 2 +#define PPTP_BEARER_ANY 3 + +#define PPTP_RESULT_GENERAL_ERROR 2 + +/* (Reasons to close a connection) */ +#define PPTP_STOP_NONE 1 /* no good reason */ +#define PPTP_STOP_PROTOCOL 2 /* can't support peer's protocol version */ +#define PPTP_STOP_LOCAL_SHUTDOWN 3 /* requester is being shut down */ + +/* PPTP datagram structures (all data in network byte order): ----------*/ + +struct pptp_header +{ + uint16_t length; /* message length in octets, including header */ + uint16_t pptp_type; /* PPTP message type. 1 for control message. */ + uint32_t magic; /* this should be PPTP_MAGIC. */ + uint16_t ctrl_type; /* Control message type (0-15) */ + uint16_t reserved0; /* reserved. MUST BE ZERO. */ +}__attribute__((packed)); + +struct pptp_start_ctrl_conn /* for control message types 1 and 2 */ +{ + struct pptp_header header; + + uint16_t version; /* PPTP protocol version. = PPTP_VERSION */ + uint8_t result_code; /* these two fields should be zero on rqst msg*/ + uint8_t error_code; /* 0 unless result_code==2 (General Error) */ + uint32_t framing_cap; /* Framing capabilities */ + uint32_t bearer_cap; /* Bearer Capabilities */ + uint16_t max_channels; /* Maximum Channels (=0 for PNS, PAC ignores) */ + uint16_t firmware_rev; /* Firmware or Software Revision */ + uint8_t hostname[64]; /* Host Name (64 octets, zero terminated) */ + uint8_t vendor[64]; /* Vendor string (64 octets, zero term.) */ +}__attribute__((packed)); + +struct pptp_stop_ctrl_conn /* for control message types 3 and 4 */ +{ + struct pptp_header header; + + uint8_t reason_result; /* reason for rqst, result for rply */ + uint8_t error_code; /* MUST be 0, unless rply result==2 (general err)*/ + uint16_t reserved1; /* MUST be 0 */ +}__attribute__((packed)); + +struct pptp_echo_rqst /* for control message type 5 */ +{ + struct pptp_header header; + uint32_t identifier; /* arbitrary value set by sender which is used */ + /* to match up reply and request */ +}__attribute__((packed)); + +struct pptp_echo_rply /* for control message type 6 */ +{ + struct pptp_header header; + uint32_t identifier; /* should correspond to id of rqst */ + uint8_t result_code; + uint8_t error_code; /* =0, unless result_code==2 (general error) */ + uint16_t reserved1; /* MUST BE ZERO */ +}__attribute__((packed)); + +struct pptp_out_call_rqst /* for control message type 7 */ +{ + struct pptp_header header; + uint16_t call_id; /* Call ID (unique id used to multiplex data) */ + uint16_t call_sernum; /* Call Serial Number (used for logging) */ + uint32_t bps_min; /* Minimum BPS (lowest acceptable line speed) */ + uint32_t bps_max; /* Maximum BPS (highest acceptable line speed) */ + uint32_t bearer; /* Bearer type */ + uint32_t framing; /* Framing type */ + uint16_t recv_size; /* Recv. Window Size (no. of buffered packets) */ + uint16_t delay; /* Packet Processing Delay (in 1/10 sec) */ + uint16_t phone_len; /* Phone Number Length (num. of valid digits) */ + uint16_t reserved1; /* MUST BE ZERO */ + uint8_t phone_num[64]; /* Phone Number (64 octets, null term.) */ + uint8_t subaddress[64]; /* Subaddress (64 octets, null term.) */ +}__attribute__((packed)); + +struct pptp_out_call_rply /* for control message type 8 */ +{ + struct pptp_header header; + uint16_t call_id; /* Call ID (used to multiplex data over tunnel)*/ + uint16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/ + uint8_t result_code; /* Result Code (1 is no errors) */ + uint8_t error_code; /* Error Code (=0 unless result_code==2) */ + uint16_t cause_code; /* Cause Code (addt'l failure information) */ + uint32_t speed; /* Connect Speed (in BPS) */ + uint16_t recv_size; /* Recv. Window Size (no. of buffered packets) */ + uint16_t delay; /* Packet Processing Delay (in 1/10 sec) */ + uint32_t channel; /* Physical Channel ID (for logging) */ +}__attribute__((packed)); + +struct pptp_in_call_rqst /* for control message type 9 */ +{ + struct pptp_header header; + uint16_t call_id; /* Call ID (unique id used to multiplex data) */ + uint16_t call_sernum; /* Call Serial Number (used for logging) */ + uint32_t bearer; /* Bearer type */ + uint32_t channel; /* Physical Channel ID (for logging) */ + uint16_t dialed_len; /* Dialed Number Length (# of valid digits) */ + uint16_t dialing_len; /* Dialing Number Length (# of valid digits) */ + uint8_t dialed_num[64]; /* Dialed Number (64 octets, zero term.) */ + uint8_t dialing_num[64]; /* Dialing Number (64 octets, zero term.) */ + uint8_t subaddress[64]; /* Subaddress (64 octets, zero term.) */ +}__attribute__((packed)); + +struct pptp_in_call_rply /* for control message type 10 */ +{ + struct pptp_header header; + uint16_t call_id; /* Call ID (used to multiplex data over tunnel)*/ + uint16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/ + uint8_t result_code; /* Result Code (1 is no errors) */ + uint8_t error_code; /* Error Code (=0 unless result_code==2) */ + uint16_t recv_size; /* Recv. Window Size (no. of buffered packets) */ + uint16_t delay; /* Packet Processing Delay (in 1/10 sec) */ + uint16_t reserved1; /* MUST BE ZERO */ +}__attribute__((packed)); + +struct pptp_in_call_connect /* for control message type 11 */ +{ + struct pptp_header header; + uint16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/ + uint16_t reserved1; /* MUST BE ZERO */ + uint32_t speed; /* Connect Speed (in BPS) */ + uint16_t recv_size; /* Recv. Window Size (no. of buffered packets) */ + uint16_t delay; /* Packet Processing Delay (in 1/10 sec) */ + uint32_t framing; /* Framing type */ +}__attribute__((packed)); + +struct pptp_call_clear_rqst /* for control message type 12 */ +{ + struct pptp_header header; + uint16_t call_id; /* Call ID (used to multiplex data over tunnel)*/ + uint16_t reserved1; /* MUST BE ZERO */ +}__attribute__((packed)); + +struct pptp_call_clear_ntfy /* for control message type 13 */ +{ + struct pptp_header header; + uint16_t call_id; /* Call ID (used to multiplex data over tunnel)*/ + uint8_t result_code; /* Result Code */ + uint8_t error_code; /* Error Code (=0 unless result_code==2) */ + uint16_t cause_code; /* Cause Code (for ISDN, is Q.931 cause code) */ + uint16_t reserved1; /* MUST BE ZERO */ + uint8_t call_stats[128]; /* Call Statistics: 128 octets, ascii, 0-term */ +}__attribute__((packed)); + +struct pptp_wan_err_ntfy /* for control message type 14 */ +{ + struct pptp_header header; + uint16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/ + uint16_t reserved1; /* MUST BE ZERO */ + uint32_t crc_errors; /* CRC errors */ + uint32_t frame_errors; /* Framing errors */ + uint32_t hard_errors; /* Hardware overruns */ + uint32_t buff_errors; /* Buffer overruns */ + uint32_t time_errors; /* Time-out errors */ + uint32_t align_errors; /* Alignment errors */ +}__attribute__((packed)); + +struct pptp_set_link_info /* for control message type 15 */ +{ + struct pptp_header header; + uint16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst) */ + uint16_t reserved1; /* MUST BE ZERO */ + uint32_t send_accm; /* Send ACCM (for PPP packets; default 0xFFFFFFFF)*/ + uint32_t recv_accm; /* Receive ACCM (for PPP pack.;default 0xFFFFFFFF)*/ +}__attribute__((packed)); + +/* helpful #defines: -------------------------------------------- */ +#define pptp_isvalid_ctrl(header, type, length) \ + (!( ( ntoh16(((struct pptp_header *)header)->length) < (length) ) || \ + ( ntoh16(((struct pptp_header *)header)->pptp_type) !=(type) ) || \ + ( ntoh32(((struct pptp_header *)header)->magic) !=PPTP_MAGIC) || \ + ( ntoh16(((struct pptp_header *)header)->ctrl_type) > PPTP_SET_LINK_INFO) || \ + ( ntoh16(((struct pptp_header *)header)->reserved0) !=0 ) )) + +#define PPTP_HEADER_CTRL(type) \ +{ hton16(PPTP_CTRL_SIZE(type)), \ + hton16(PPTP_MESSAGE_CONTROL), \ + hton32(PPTP_MAGIC), \ + hton16(type), 0 } + +#define PPTP_CTRL_SIZE(type) ( \ +(type==PPTP_START_CTRL_CONN_RQST)?sizeof(struct pptp_start_ctrl_conn): \ +(type==PPTP_START_CTRL_CONN_RPLY)?sizeof(struct pptp_start_ctrl_conn): \ +(type==PPTP_STOP_CTRL_CONN_RQST )?sizeof(struct pptp_stop_ctrl_conn): \ +(type==PPTP_STOP_CTRL_CONN_RPLY )?sizeof(struct pptp_stop_ctrl_conn): \ +(type==PPTP_ECHO_RQST )?sizeof(struct pptp_echo_rqst): \ +(type==PPTP_ECHO_RPLY )?sizeof(struct pptp_echo_rply): \ +(type==PPTP_OUT_CALL_RQST )?sizeof(struct pptp_out_call_rqst): \ +(type==PPTP_OUT_CALL_RPLY )?sizeof(struct pptp_out_call_rply): \ +(type==PPTP_IN_CALL_RQST )?sizeof(struct pptp_in_call_rqst): \ +(type==PPTP_IN_CALL_RPLY )?sizeof(struct pptp_in_call_rply): \ +(type==PPTP_IN_CALL_CONNECT )?sizeof(struct pptp_in_call_connect): \ +(type==PPTP_CALL_CLEAR_RQST )?sizeof(struct pptp_call_clear_rqst): \ +(type==PPTP_CALL_CLEAR_NTFY )?sizeof(struct pptp_call_clear_ntfy): \ +(type==PPTP_WAN_ERR_NTFY )?sizeof(struct pptp_wan_err_ntfy): \ +(type==PPTP_SET_LINK_INFO )?sizeof(struct pptp_set_link_info): \ +0) +#define max(a,b) (((a)>(b))?(a):(b)) +#define PPTP_CTRL_SIZE_MAX ( \ +max(sizeof(struct pptp_start_ctrl_conn), \ +max(sizeof(struct pptp_echo_rqst), \ +max(sizeof(struct pptp_echo_rply), \ +max(sizeof(struct pptp_out_call_rqst), \ +max(sizeof(struct pptp_out_call_rply), \ +max(sizeof(struct pptp_in_call_rqst), \ +max(sizeof(struct pptp_in_call_rply), \ +max(sizeof(struct pptp_in_call_connect), \ +max(sizeof(struct pptp_call_clear_rqst), \ +max(sizeof(struct pptp_call_clear_ntfy), \ +max(sizeof(struct pptp_wan_err_ntfy), \ +max(sizeof(struct pptp_set_link_info), 0))))))))))))) + +#endif diff --git a/accel-pppd/extra/CMakeLists.txt b/accel-pppd/extra/CMakeLists.txt new file mode 100644 index 0000000..03d857a --- /dev/null +++ b/accel-pppd/extra/CMakeLists.txt @@ -0,0 +1,19 @@ +ADD_LIBRARY(pppd_compat SHARED pppd_compat.c) +ADD_LIBRARY(ippool SHARED ippool.c) +ADD_LIBRARY(sigchld SHARED sigchld.c) +ADD_LIBRARY(chap-secrets SHARED chap-secrets.c) + +INSTALL(TARGETS pppd_compat ippool sigchld chap-secrets + LIBRARY DESTINATION lib/accel-ppp +) + +IF (SHAPER) + ADD_LIBRARY(shaper_tbf SHARED shaper_tbf.c) + IF (LIBNL_PREFIX) + SET_PROPERTY(TARGET shaper_tbf PROPERTY COMPILE_FLAGS "-I${LIBNL_PREFIX}/include") + SET_PROPERTY(TARGET shaper_tbf PROPERTY LINK_FLAGS "-L${LIBNL_PREFIX}/lib") + ENDIF (LIBNL_PREFIX) + TARGET_LINK_LIBRARIES(shaper_tbf nl m) + INSTALL(TARGETS shaper_tbf LIBRARY DESTINATION lib/accel-ppp) +ENDIF (SHAPER) + diff --git a/accel-pppd/extra/chap-secrets.c b/accel-pppd/extra/chap-secrets.c new file mode 100644 index 0000000..3550347 --- /dev/null +++ b/accel-pppd/extra/chap-secrets.c @@ -0,0 +1,281 @@ +#include +#include +#include +#include +#include + +#include "pwdb.h" +#include "ipdb.h" +#include "ppp.h" +#include "events.h" +#include "triton.h" +#include "log.h" + +#include "memdebug.h" + +static char *def_chap_secrets = "/etc/ppp/chap-secrets"; +static char *conf_chap_secrets; +static in_addr_t conf_gw_ip_address = 0; + +static void *pd_key; +static struct ipdb_t ipdb; + +struct cs_pd_t +{ + struct ppp_pd_t pd; + struct ipdb_item_t ip; + char *passwd; + char *rate; +}; + +static char *skip_word(char *ptr) +{ + char quote = 0; + + if (*ptr == '\'' || *ptr == '"') { + quote = *ptr; + ptr++; + } + + for(; *ptr; ptr++) { + if (quote) { + if (*ptr == '\n') + break; + if (*ptr == '\\' && ptr[1] && ptr[1] != '\n') { + memmove(ptr, ptr + 1, strlen(ptr)); + continue; + } + if (*ptr == quote) { + *ptr = ' '; + break; + } + } else if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') + break; + } + return ptr; +} +static char *skip_space(char *ptr) +{ + for(; *ptr; ptr++) + if (*ptr != ' ' && *ptr != '\t') + break; + return ptr; +} +static int split(char *buf, char **ptr) +{ + int i; + + for (i = 0; i < 4; i++) { + buf = skip_word(buf); + if (!*buf) + return i; + + *buf = 0; + + buf = skip_space(buf + 1); + if (!*buf) + return i; + + if (*buf == '"' || *buf == '\'') + ptr[i] = buf + 1; + else + ptr[i] = buf; + } + + buf = skip_word(buf); + //if (*buf == '\n') + *buf = 0; + //else if (*buf) + // return -1; + + return i; +} + + +static struct cs_pd_t *create_pd(struct ppp_t *ppp, const char *username) +{ + FILE *f; + char *buf; + char *ptr[5]; + int n; + struct cs_pd_t *pd; + + if (!conf_chap_secrets) + return NULL; + + f = fopen(conf_chap_secrets, "r"); + if (!f) { + log_error("chap-secrets: open '%s': %s\n", conf_chap_secrets, strerror(errno)); + return NULL; + } + + buf = _malloc(4096); + if (!buf) { + log_emerg("chap-secrets: out of memory\n"); + fclose(f); + return NULL; + } + + while (fgets(buf, 4096, f)) { + if (buf[0] == '#') + continue; + n = split(buf, ptr); + if (n < 3) + continue; + if (*buf == '\'' || *buf == '"') { + if (!strcmp(buf + 1, username)) + goto found; + } else { + if (!strcmp(buf, username)) + goto found; + } + } + +out: + fclose(f); + _free(buf); + return NULL; + +found: + pd = _malloc(sizeof(*pd)); + if (!pd) { + log_emerg("chap-secrets: out of memory\n"); + goto out; + } + + memset(pd, 0, sizeof(*pd)); + pd->pd.key = &pd_key; + pd->passwd = _strdup(ptr[1]); + if (!pd->passwd) { + log_emerg("chap-secrets: out of memory\n"); + _free(pd); + goto out; + } + + pd->ip.addr = conf_gw_ip_address; + if (n >= 3) + pd->ip.peer_addr = inet_addr(ptr[2]); + pd->ip.owner = &ipdb; + + if (n == 4) + pd->rate = _strdup(ptr[3]); + + list_add_tail(&pd->pd.entry, &ppp->pd_list); + + fclose(f); + _free(buf); + + return pd; +} + +static struct cs_pd_t *find_pd(struct ppp_t *ppp) +{ + struct ppp_pd_t *pd; + + list_for_each_entry(pd, &ppp->pd_list, entry) { + if (pd->key == &pd_key) { + return container_of(pd, typeof(struct cs_pd_t), pd); + } + } + + return NULL; +} + +static void ev_ppp_finished(struct ppp_t *ppp) +{ + struct cs_pd_t *pd = find_pd(ppp); + + if (!pd) + return; + + list_del(&pd->pd.entry); + _free(pd->passwd); + if (pd->rate) + _free(pd->rate); + _free(pd); +} + +static void ev_ppp_pre_up(struct ppp_t *ppp) +{ + struct cs_pd_t *pd = find_pd(ppp); + struct ev_shaper_t ev = { + .ppp = ppp, + }; + + if (!pd) + return; + + if (pd->rate) { + ev.val = pd->rate; + triton_event_fire(EV_SHAPER, &ev); + } +} + +static struct ipdb_item_t *get_ip(struct ppp_t *ppp) +{ + struct cs_pd_t *pd; + + if (!conf_gw_ip_address) + return NULL; + + pd = find_pd(ppp); + + if (!pd) + return NULL; + + if (!pd->ip.addr) + return NULL; + + return &pd->ip; +} + +static char* get_passwd(struct pwdb_t *pwdb, struct ppp_t *ppp, const char *username) +{ + struct cs_pd_t *pd = find_pd(ppp); + + if (!pd) + pd = create_pd(ppp, username); + + if (!pd) + return NULL; + + return _strdup(pd->passwd); +} + +static struct ipdb_t ipdb = { + .get = get_ip, +}; + +static struct pwdb_t pwdb = { + .get_passwd = get_passwd, +}; + +static void load_config(void) +{ + const char *opt; + + if (conf_chap_secrets && conf_chap_secrets != def_chap_secrets) + _free(conf_chap_secrets); + opt = conf_get_opt("chap-secrets", "chap-secrets"); + if (opt) + conf_chap_secrets = _strdup(opt); + else + conf_chap_secrets = def_chap_secrets; + + opt = conf_get_opt("chap-secrets", "gw-ip-address"); + if (opt) + conf_gw_ip_address = inet_addr(opt); +} + +static void __init init(void) +{ + load_config(); + + pwdb_register(&pwdb); + ipdb_register(&ipdb); + + triton_event_register_handler(EV_PPP_FINISHED, (triton_event_func)ev_ppp_finished); + triton_event_register_handler(EV_PPP_PRE_UP, (triton_event_func)ev_ppp_pre_up); + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); +} + diff --git a/accel-pppd/extra/ippool.c b/accel-pppd/extra/ippool.c new file mode 100644 index 0000000..6136a14 --- /dev/null +++ b/accel-pppd/extra/ippool.c @@ -0,0 +1,208 @@ +#include +#include +#include +#include +#include +#include + +#include "ipdb.h" +#include "list.h" +#include "spinlock.h" + +#include "memdebug.h" + +struct ippool_item_t +{ + struct list_head entry; + struct ipdb_item_t it; +}; + +struct ipaddr_t +{ + struct list_head entry; + in_addr_t addr; +}; + +static LIST_HEAD(gw_list); +static LIST_HEAD(tunnel_list); +static LIST_HEAD(ippool); +static spinlock_t pool_lock = SPINLOCK_INITIALIZER; +static struct ipdb_t ipdb; + +static in_addr_t conf_gw_ip_address; +static int cnt; + +static void parse_gw_ip_address(const char *val) +{ + if (!val) + return; + + conf_gw_ip_address = inet_addr(val); +} + +//parses ranges like x.x.x.x/mask +static int parse1(const char *str, uint32_t *begin, uint32_t *end) +{ + int n, f1, f2, f3, f4, m, mask = 0; + + n = sscanf(str, "%u.%u.%u.%u/%u",&f1, &f2, &f3, &f4, &m); + if (n != 5) + return -1; + if (f1 > 255) + return -1; + if (f2 > 255) + return -1; + if (f3 > 255) + return -1; + if (f4 > 255) + return -1; + if (m == 0 || m > 32) + return -1; + + for (n = 0; n < m ; n++) + mask |= 1 << n; + + *begin = (f4 << 24) | (f3 << 16) | (f2 << 8) | f1; + *end = *begin | ~mask; + + return 0; +} + +//parses ranges like x.x.x.x-y +static int parse2(const char *str, uint32_t *begin, uint32_t *end) +{ + int n, f1, f2, f3, f4, m; + + n = sscanf(str, "%u.%u.%u.%u-%u",&f1, &f2, &f3, &f4, &m); + if (n != 5) + return -1; + if (f1 > 255) + return -1; + if (f2 > 255) + return -1; + if (f3 > 255) + return -1; + if (f4 > 255) + return -1; + if (m < f4 || m > 255) + return -1; + + *begin = (f4 << 24) | (f3 << 16) | (f2 << 8) | f1; + *end = (m << 24) | (f3 << 16) | (f2 << 8) | f1; + + return 0; +} + +static void add_range(struct list_head *list, const char *name) +{ + uint32_t i,startip, endip; + struct ipaddr_t *ip; + + if (parse1(name, &startip, &endip)) + if (parse2(name, &startip, &endip)) { + fprintf(stderr, "ippool: cann't parse '%s'\n", name); + _exit(EXIT_FAILURE); + } + + for (i = ntohl(startip); i <= ntohl(endip); i++) { + ip = malloc(sizeof(*ip)); + ip->addr = htonl(i); + list_add_tail(&ip->entry, list); + cnt++; + } +} + +static void generate_pool(void) +{ + struct ippool_item_t *it; + struct ipaddr_t *addr = NULL; + struct ipaddr_t *peer_addr; + + while (1) { + if (list_empty(&tunnel_list)) + break; + else { + peer_addr = list_entry(tunnel_list.next, typeof(*peer_addr), entry); + list_del(&peer_addr->entry); + } + + if (!conf_gw_ip_address) { + if (list_empty(&gw_list)) + break; + else { + addr = list_entry(gw_list.next, typeof(*addr), entry); + list_del(&addr->entry); + } + } + + it = malloc(sizeof(*it)); + if (!it) { + fprintf(stderr, "ippool: out of memory\n"); + break; + } + + it->it.owner = &ipdb; + if (conf_gw_ip_address) + it->it.addr = conf_gw_ip_address; + else + it->it.addr = addr->addr; + + it->it.peer_addr = peer_addr->addr; + + list_add_tail(&it->entry, &ippool); + } +} + +static struct ipdb_item_t *get_ip(struct ppp_t *ppp) +{ + struct ippool_item_t *it; + + spin_lock(&pool_lock); + if (!list_empty(&ippool)) { + it = list_entry(ippool.next, typeof(*it), entry); + list_del(&it->entry); + } else + it = NULL; + spin_unlock(&pool_lock); + + return it ? &it->it : NULL; +} + +static void put_ip(struct ppp_t *ppp, struct ipdb_item_t *it) +{ + struct ippool_item_t *pit = container_of(it, typeof(*pit), it); + + spin_lock(&pool_lock); + list_add_tail(&pit->entry, &ippool); + spin_unlock(&pool_lock); +} + +static struct ipdb_t ipdb = { + .get = get_ip, + .put = put_ip, +}; + +static void __init ipool_init(void) +{ + struct conf_sect_t *s = conf_get_section("ip-pool"); + struct conf_option_t *opt; + + if (!s) + return; + + list_for_each_entry(opt, &s->items, entry) { + if (!strcmp(opt->name, "gw-ip-address")) + parse_gw_ip_address(opt->val); + else if (!strcmp(opt->name, "gw")) + add_range(&gw_list, opt->val); + else if (!strcmp(opt->name, "tunnel")) + add_range(&tunnel_list, opt->val); + else if (!opt->val) + add_range(&tunnel_list, opt->name); + } + + generate_pool(); + + ipdb_register(&ipdb); +} + diff --git a/accel-pppd/extra/pppd_compat.c b/accel-pppd/extra/pppd_compat.c new file mode 100644 index 0000000..f897dd6 --- /dev/null +++ b/accel-pppd/extra/pppd_compat.c @@ -0,0 +1,523 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "linux_ppp.h" + +#include "triton.h" + +#include "events.h" +#include "ppp.h" +#include "log.h" +#include "utils.h" +#include "sigchld.h" + +#ifdef RADIUS +#include "radius.h" +#endif + +#include "memdebug.h" + +static char *conf_ip_up = "/etc/ppp/ip-up"; +static char *conf_ip_pre_up; +static char *conf_ip_down = "/etc/ppp/ip-down"; +static char *conf_ip_change; +static char *conf_radattr_prefix = "/var/run/radattr."; +static int conf_verbose = 0; + +static void *pd_key; + +struct pppd_compat_pd_t +{ + struct ppp_pd_t pd; + struct ppp_t *ppp; + struct sigchld_handler_t ip_pre_up_hnd; + struct sigchld_handler_t ip_up_hnd; + struct sigchld_handler_t ip_change_hnd; + struct sigchld_handler_t ip_down_hnd; +#ifdef RADIUS + int radattr_saved:1; +#endif + int started:1; + int res; + int bytes_sent; + int bytes_rcvd; +}; + +static struct pppd_compat_pd_t *find_pd(struct ppp_t *ppp); +static void fill_argv(char **argv, struct ppp_t *ppp, char *path); +static void fill_env(char **env, struct pppd_compat_pd_t *pd); +#ifdef RADIUS +static void remove_radattr(struct ppp_t *ppp); +static void write_radattr(struct ppp_t *ppp, struct rad_packet_t *pack, int save_old); +#endif + +static void ip_pre_up_handler(struct sigchld_handler_t *h, int status) +{ + struct pppd_compat_pd_t *pd = container_of(h, typeof(*pd), ip_pre_up_hnd); + if (conf_verbose) { + log_switch(NULL, pd->ppp); + log_ppp_info2("pppd_compat: ip-pre-up finished (%i)\n", status); + pd->res = status; + } + sched_yield(); + triton_context_wakeup(pd->ppp->ctrl->ctx); +} + +static void ip_up_handler(struct sigchld_handler_t *h, int status) +{ + struct pppd_compat_pd_t *pd = container_of(h, typeof(*pd), ip_up_hnd); + if (conf_verbose) { + log_switch(NULL, pd->ppp); + log_ppp_info2("pppd_compat: ip-up finished (%i)\n", status); + } +} + +static void ip_down_handler(struct sigchld_handler_t *h, int status) +{ + struct pppd_compat_pd_t *pd = container_of(h, typeof(*pd), ip_down_hnd); + if (conf_verbose) { + log_switch(NULL, pd->ppp); + log_ppp_info2("pppd_compat: ip-down finished (%i)\n", status); + } + sched_yield(); + triton_context_wakeup(pd->ppp->ctrl->ctx); +} + +static void ip_change_handler(struct sigchld_handler_t *h, int status) +{ + struct pppd_compat_pd_t *pd = container_of(h, typeof(*pd), ip_change_hnd); + if (conf_verbose) { + log_switch(NULL, pd->ppp); + log_ppp_info2("pppd_compat: ip-change finished (%i)\n", status); + } + sched_yield(); + pd->res = status; + triton_context_wakeup(pd->ppp->ctrl->ctx); +} + +static void ev_ppp_starting(struct ppp_t *ppp) +{ + struct pppd_compat_pd_t *pd = _malloc(sizeof(*pd)); + + if (!pd) { + log_emerg("pppd_compat: out of memory\n"); + return; + } + + memset(pd, 0, sizeof(*pd)); + pd->pd.key = &pd_key; + pd->ppp = ppp; + pd->ip_pre_up_hnd.handler = ip_pre_up_handler; + pd->ip_up_hnd.handler = ip_up_handler; + pd->ip_down_hnd.handler = ip_down_handler; + pd->ip_change_hnd.handler = ip_change_handler; + list_add_tail(&pd->pd.entry, &ppp->pd_list); +} + +static void ev_ppp_pre_up(struct ppp_t *ppp) +{ + pid_t pid; + char *argv[8]; + char *env[2]; + char ipaddr[17]; + char peer_ipaddr[17]; + char peername[64]; + struct pppd_compat_pd_t *pd = find_pd(ppp); + + if (!pd) + return; + + argv[4] = ipaddr; + argv[5] = peer_ipaddr; + fill_argv(argv, ppp, conf_ip_up); + + env[0] = peername; + env[1] = NULL; + fill_env(env, pd); + + if (conf_ip_pre_up) { + sigchld_lock(); + pid = fork(); + if (pid > 0) { + pd->ip_pre_up_hnd.pid = pid; + sigchld_register_handler(&pd->ip_pre_up_hnd); + if (conf_verbose) + log_ppp_info2("pppd_compat: ip-pre-up started (pid %i)\n", pid); + sigchld_unlock(); + triton_context_schedule(); + pthread_mutex_lock(&pd->ip_pre_up_hnd.lock); + pthread_mutex_unlock(&pd->ip_pre_up_hnd.lock); + if (pd->res != 0) { + ppp_terminate(ppp, 0, pd->res < 0 ? TERM_NAS_ERROR : TERM_ADMIN_RESET); + return; + } + } else if (pid == 0) { + execve(conf_ip_pre_up, argv, env); + log_emerg("pppd_compat: exec '%s': %s\n", conf_ip_pre_up, strerror(errno)); + _exit(EXIT_FAILURE); + } else + log_error("pppd_compat: fork: %s\n", strerror(errno)); + } +} + +static void ev_ppp_started(struct ppp_t *ppp) +{ + pid_t pid; + char *argv[8]; + char *env[2]; + char ipaddr[17]; + char peer_ipaddr[17]; + char peername[64]; + struct pppd_compat_pd_t *pd = find_pd(ppp); + + if (!pd) + return; + + argv[4] = ipaddr; + argv[5] = peer_ipaddr; + fill_argv(argv, ppp, conf_ip_up); + + env[0] = peername; + env[1] = NULL; + fill_env(env, pd); + + if (conf_ip_up) { + sigchld_lock(); + pid = fork(); + if (pid > 0) { + pd->ip_up_hnd.pid = pid; + sigchld_register_handler(&pd->ip_up_hnd); + if (conf_verbose) + log_ppp_info2("pppd_compat: ip-up started (pid %i)\n", pid); + sigchld_unlock(); + } else if (pid == 0) { + execve(conf_ip_up, argv, env); + log_emerg("pppd_compat: exec '%s': %s\n", conf_ip_up, strerror(errno)); + _exit(EXIT_FAILURE); + } else + log_error("pppd_compat: fork: %s\n", strerror(errno)); + } + + pd->started = 1; +} + +static void ev_ppp_finishing(struct ppp_t *ppp) +{ + struct ifpppstatsreq ifreq; + struct pppd_compat_pd_t *pd = find_pd(ppp); + + if (!pd) + return; + + memset(&ifreq, 0, sizeof(ifreq)); + ifreq.stats_ptr = (void *)&ifreq.stats; + strcpy(ifreq.ifr__name, ppp->ifname); + + if (ioctl(sock_fd, SIOCGPPPSTATS, &ifreq)) { + log_ppp_error("pppd_compat: failed to get ppp statistics: %s\n", strerror(errno)); + return; + } + + pd->bytes_sent = ifreq.stats.p.ppp_obytes; + pd->bytes_rcvd = ifreq.stats.p.ppp_ibytes; +} + +static void ev_ppp_finished(struct ppp_t *ppp) +{ + pid_t pid; + char *argv[8]; + char *env[5]; + char ipaddr[17]; + char peer_ipaddr[17]; + char peername[64]; + char connect_time[24]; + char bytes_sent[24]; + char bytes_rcvd[24]; + struct pppd_compat_pd_t *pd = find_pd(ppp); + + if (!pd) + return; + + if (!pd->started) + goto skip; + + pthread_mutex_lock(&pd->ip_up_hnd.lock); + if (pd->ip_up_hnd.pid) { + log_ppp_warn("pppd_compat: ip-up is not yet finished, terminating it ...\n"); + kill(pd->ip_up_hnd.pid, SIGTERM); + } + pthread_mutex_unlock(&pd->ip_up_hnd.lock); + + argv[4] = ipaddr; + argv[5] = peer_ipaddr; + fill_argv(argv, pd->ppp, conf_ip_down); + + env[0] = peername; + env[1] = connect_time; + env[2] = bytes_sent; + env[3] = bytes_rcvd; + env[4] = NULL; + fill_env(env, pd); + + sigchld_lock(); + pid = fork(); + if (pid > 0) { + pd->ip_down_hnd.pid = pid; + sigchld_register_handler(&pd->ip_down_hnd); + if (conf_verbose) + log_ppp_info2("pppd_compat: ip-down started (pid %i)\n", pid); + sigchld_unlock(); + triton_context_schedule(); + pthread_mutex_lock(&pd->ip_down_hnd.lock); + pthread_mutex_unlock(&pd->ip_down_hnd.lock); + } else if (pid == 0) { + execve(conf_ip_down, argv, env); + log_emerg("pppd_compat: exec '%s': %s\n", conf_ip_down, strerror(errno)); + _exit(EXIT_FAILURE); + } else + log_error("pppd_compat: fork: %s\n", strerror(errno)); + + pthread_mutex_lock(&pd->ip_up_hnd.lock); + if (pd->ip_up_hnd.pid) { + log_ppp_warn("pppd_compat: ip-up is not yet finished, killing it ...\n"); + kill(pd->ip_up_hnd.pid, SIGKILL); + pthread_mutex_unlock(&pd->ip_up_hnd.lock); + sigchld_unregister_handler(&pd->ip_up_hnd); + } else + pthread_mutex_unlock(&pd->ip_up_hnd.lock); + +skip: +#ifdef RADIUS + if (pd->radattr_saved) + remove_radattr(ppp); +#endif + + list_del(&pd->pd.entry); + _free(pd); +} + +#ifdef RADIUS +static void ev_radius_access_accept(struct ev_radius_t *ev) +{ + struct pppd_compat_pd_t *pd = find_pd(ev->ppp); + + write_radattr(ev->ppp, ev->reply, 0); + + pd->radattr_saved = 1; +} + +static void ev_radius_coa(struct ev_radius_t *ev) +{ + pid_t pid; + char *argv[8]; + char *env[2]; + char ipaddr[17]; + char peer_ipaddr[17]; + char peername[64]; + struct pppd_compat_pd_t *pd = find_pd(ev->ppp); + + if (!pd) + return; + + write_radattr(ev->ppp, ev->request, 1); + + argv[4] = ipaddr; + argv[5] = peer_ipaddr; + fill_argv(argv, pd->ppp, conf_ip_change); + + env[0] = peername; + env[1] = NULL; + fill_env(env, pd); + + sigchld_lock(); + pid = fork(); + if (pid > 0) { + pd->ip_change_hnd.pid = pid; + sigchld_register_handler(&pd->ip_change_hnd); + sigchld_unlock(); + if (conf_verbose) + log_ppp_info2("pppd_compat: ip-change started (pid %i)\n", pid); + triton_context_schedule(); + if (!ev->res) + ev->res = pd->res; + } else if (pid == 0) { + execve(conf_ip_change, argv, env); + log_emerg("pppd_compat: exec '%s': %s\n", conf_ip_change, strerror(errno)); + _exit(EXIT_FAILURE); + } else + log_error("pppd_compat: fork: %s\n", strerror(errno)); +} + +static void remove_radattr(struct ppp_t *ppp) +{ + char *fname; + + fname = _malloc(PATH_MAX); + if (!fname) { + log_emerg("pppd_compat: out of memory\n"); + return; + } + + sprintf(fname, "%s.%s", conf_radattr_prefix, ppp->ifname); + if (unlink(fname)) { + log_ppp_warn("pppd_compat: failed to remove '%s': %s\n", fname, strerror(errno)); + } + sprintf(fname, "%s_old.%s", conf_radattr_prefix, ppp->ifname); + unlink(fname); + + _free(fname); +} + +static void write_radattr(struct ppp_t *ppp, struct rad_packet_t *pack, int save_old) +{ + struct rad_attr_t *attr; + struct rad_dict_value_t *val; + FILE *f; + char *fname1, *fname2 = NULL; + int i; + + fname1 = _malloc(PATH_MAX); + if (!fname1) { + log_emerg("pppd_compat: out of memory\n"); + return; + } + + if (save_old) { + fname2 = _malloc(PATH_MAX); + if (!fname2) { + log_emerg("pppd_compat: out of memory\n"); + _free(fname1); + return; + } + } + + sprintf(fname1, "%s.%s", conf_radattr_prefix, ppp->ifname); + if (save_old) { + sprintf(fname2, "%s_old.%s", conf_radattr_prefix, ppp->ifname); + if (rename(fname1, fname2)) { + log_ppp_warn("pppd_compat: rename: %s\n", strerror(errno)); + } + } + + f = fopen(fname1, "w"); + if (f) { + list_for_each_entry(attr, &pack->attrs, entry) { + fprintf(f, "%s ", attr->attr->name); + switch (attr->attr->type) { + case ATTR_TYPE_INTEGER: + val = rad_dict_find_val(attr->attr, attr->val); + if (val) + fprintf(f, "%s\n", val->name); + else + fprintf(f, "%i\n", attr->val.integer); + break; + case ATTR_TYPE_STRING: + fprintf(f, "%s\n", attr->val.string); + break; + case ATTR_TYPE_OCTETS: + for (i = 0; i < attr->len; i++) + fprintf(f, "%02X", attr->val.octets[i]); + fprintf(f, "\n"); + break; + case ATTR_TYPE_IPADDR: + fprintf(f, "%i.%i.%i.%i\n", attr->val.ipaddr & 0xff, (attr->val.ipaddr >> 8) & 0xff, (attr->val.ipaddr >> 16) & 0xff, (attr->val.ipaddr >> 24) & 0xff); + break; + case ATTR_TYPE_DATE: + fprintf(f, "%lu\n", attr->val.date); + break; + } + } + fclose(f); + } else + log_ppp_warn("pppd_compat: failed to create '%s': %s\n", fname1, strerror(errno)); + + _free(fname1); + if (save_old) + _free(fname2); +} +#endif + +static struct pppd_compat_pd_t *find_pd(struct ppp_t *ppp) +{ + struct ppp_pd_t *pd; + struct pppd_compat_pd_t *cpd; + + list_for_each_entry(pd, &ppp->pd_list, entry) { + if (pd->key == &pd_key) { + cpd = container_of(pd, typeof(*cpd), pd); + return cpd; + } + } + + log_ppp_warn("pppd_compat: pd not found\n"); + return NULL; +} + +static void fill_argv(char **argv, struct ppp_t *ppp, char *path) +{ + argv[0] = path; + argv[1] = ppp->ifname; + argv[2] = "none"; + argv[3] = "0"; + u_inet_ntoa(ppp->ipaddr, argv[4]); + u_inet_ntoa(ppp->peer_ipaddr, argv[5]); + argv[6] = ppp->ctrl->calling_station_id; + argv[7] = NULL; +} + +static void fill_env(char **env, struct pppd_compat_pd_t *pd) +{ + snprintf(env[0], 64, "PEERNAME=%s", pd->ppp->username); + + if (pd->ppp->stop_time && env[1]) { + snprintf(env[1], 24, "CONNECT_TIME=%lu", pd->ppp->stop_time - pd->ppp->start_time); + snprintf(env[2], 24, "BYTES_SENT=%u", pd->bytes_sent); + snprintf(env[3], 24, "BYTES_RCVD=%u", pd->bytes_rcvd); + } +} + +static void __init init(void) +{ + char *opt; + + opt = conf_get_opt("pppd-compat", "ip-pre-up"); + if (opt) + conf_ip_pre_up = _strdup(opt); + + opt = conf_get_opt("pppd-compat", "ip-up"); + if (opt) + conf_ip_up = _strdup(opt); + + opt = conf_get_opt("pppd-compat", "ip-down"); + if (opt) + conf_ip_down = _strdup(opt); + + opt = conf_get_opt("pppd-compat", "ip-change"); + if (opt) + conf_ip_change = _strdup(opt); + + opt = conf_get_opt("pppd-compat", "radattr-prefix"); + if (opt) + conf_radattr_prefix = _strdup(opt); + + opt = conf_get_opt("pppd-compat", "verbose"); + if (opt && atoi(opt) > 0) + conf_verbose = 1; + + triton_event_register_handler(EV_PPP_STARTING, (triton_event_func)ev_ppp_starting); + triton_event_register_handler(EV_PPP_PRE_UP, (triton_event_func)ev_ppp_pre_up); + triton_event_register_handler(EV_PPP_STARTED, (triton_event_func)ev_ppp_started); + triton_event_register_handler(EV_PPP_FINISHING, (triton_event_func)ev_ppp_finishing); + triton_event_register_handler(EV_PPP_FINISHED, (triton_event_func)ev_ppp_finished); +#ifdef RADIUS + triton_event_register_handler(EV_RADIUS_ACCESS_ACCEPT, (triton_event_func)ev_radius_access_accept); + triton_event_register_handler(EV_RADIUS_COA, (triton_event_func)ev_radius_coa); +#endif +} diff --git a/accel-pppd/extra/shaper_tbf.c b/accel-pppd/extra/shaper_tbf.c new file mode 100644 index 0000000..d7e4f0b --- /dev/null +++ b/accel-pppd/extra/shaper_tbf.c @@ -0,0 +1,1274 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "netlink/netlink.h" +#include "netlink/socket.h" +#include "netlink/msg.h" + +#include "triton.h" +#include "events.h" +#include "log.h" +#include "ppp.h" +#include "cli.h" + +#ifdef RADIUS +#include "radius.h" +#endif + +#include "memdebug.h" + +#define RTNL_TC_RTABLE_SIZE 256 +#define TIME_UNITS_PER_SEC 1000000 + +#define ATTR_UP 1 +#define ATTR_DOWN 2 + +static int conf_verbose = 0; +#ifdef RADIUS +static int conf_attr_down = 11; //Filter-Id +static int conf_attr_up = 11; //Filter-Id +static int conf_vendor = 0; +#endif +static double conf_down_burst_factor = 0.1; +static double conf_up_burst_factor = 1; +static int conf_latency = 50; +static int conf_mpu = 0; + +static int temp_down_speed; +static int temp_up_speed; + +static pthread_rwlock_t shaper_lock = PTHREAD_RWLOCK_INITIALIZER; +static LIST_HEAD(shaper_list); + +static double tick_in_usec = 1; +static double clock_factor = 1; + +struct time_range_pd_t; +struct shaper_pd_t +{ + struct list_head entry; + struct ppp_t *ppp; + struct ppp_pd_t pd; + int temp_down_speed; + int temp_up_speed; + int down_speed; + int up_speed; + struct list_head tr_list; + struct time_range_pd_t *cur_tr; +}; + +struct time_range_pd_t +{ + struct list_head entry; + int id; + int down_speed; + int down_burst; + int up_speed; + int up_burst; +}; + +struct time_range_t +{ + struct list_head entry; + int id; + struct triton_timer_t begin; + struct triton_timer_t end; +}; + +static void *pd_key; + +static LIST_HEAD(time_range_list); +static int time_range_id; + +static void shaper_ctx_close(struct triton_context_t *); +static struct triton_context_t shaper_ctx = { + .close = shaper_ctx_close, + .before_switch = log_switch, +}; + +static unsigned tc_time2tick(unsigned time) +{ + return time*tick_in_usec; +} + +/*static unsigned tc_tick2time(unsigned tick) +{ + return tick/tick_in_usec; +}*/ + +static unsigned tc_calc_xmittime(unsigned rate, unsigned size) +{ + return tc_time2tick(TIME_UNITS_PER_SEC*((double)size/rate)); +} + +/*static unsigned tc_calc_xmitsize(unsigned rate, unsigned ticks) +{ + return ((double)rate*tc_tick2time(ticks))/TIME_UNITS_PER_SEC; +}*/ + +static void tc_calc_rtable(struct tc_ratespec *r, uint32_t *rtab, int cell_log, unsigned mtu) +{ + int i; + unsigned sz; + unsigned bps = r->rate; + unsigned mpu = r->mpu; + + if (mtu == 0) + mtu = 2047; + + if (cell_log <= 0) { + cell_log = 0; + while ((mtu >> cell_log) > 255) + cell_log++; + } + + for (i=0; i<256; i++) { + //sz = tc_adjust_size((i + 1) << cell_log, mpu, linklayer); + sz = (i + 1) << cell_log; + if (sz < mpu) + sz = mpu; + rtab[i] = tc_calc_xmittime(bps, sz); + } + + r->cell_align=-1; // Due to the sz calc + r->cell_log=cell_log; +} + +static int install_tbf(struct nl_sock *h, int ifindex, int speed, int burst) +{ + struct tc_tbf_qopt opt; + struct nl_msg *msg; + struct nl_msg *pmsg = NULL; + uint32_t rtab[RTNL_TC_RTABLE_SIZE]; + double rate = speed * 1000 / 8; + double bucket = burst ? burst : rate * conf_down_burst_factor; + + struct tcmsg tchdr = { + .tcm_family = AF_UNSPEC, + .tcm_ifindex = ifindex, + .tcm_handle = 0x00010000, + .tcm_parent = TC_H_ROOT, + }; + + memset(&opt, 0, sizeof(opt)); + + opt.rate.rate = rate; + opt.rate.mpu = conf_mpu; + opt.limit = rate*conf_latency/1000 + bucket; + opt.buffer = tc_calc_xmittime(rate, bucket); + + tc_calc_rtable(&opt.rate, rtab, 0, 0); + + msg = nlmsg_alloc(); + if (!msg) + goto out_err; + + NLA_PUT(msg, TCA_TBF_PARMS, sizeof(opt), &opt); + NLA_PUT(msg, TCA_TBF_RTAB, sizeof(rtab), rtab); + + pmsg = nlmsg_alloc_simple(RTM_NEWQDISC, NLM_F_CREATE | NLM_F_REPLACE); + if (!pmsg) + goto out_err; + + if (nlmsg_append(pmsg, &tchdr, sizeof(tchdr), NLMSG_ALIGNTO) < 0) + goto out_err; + + NLA_PUT_STRING(pmsg, TCA_KIND, "tbf"); + nla_put_nested(pmsg, TCA_OPTIONS, msg); + + if (nl_send_auto_complete(h, pmsg) < 0) + goto out_err; + + if (nl_wait_for_ack(h) < 0) + goto out_err; + + nlmsg_free(msg); + nlmsg_free(pmsg); + + return 0; + +out_err: +nla_put_failure: + + if (msg) + nlmsg_free(msg); + + if (pmsg) + nlmsg_free(pmsg); + + log_ppp_error("tbf: error occured, tbf is not installed\n"); + + return -1; +} + +static int install_ingress(struct nl_sock *h, int ifindex) +{ + struct nl_msg *pmsg; + + struct tcmsg tchdr = { + .tcm_family = AF_UNSPEC, + .tcm_ifindex = ifindex, + .tcm_handle = 0xffff0000, + .tcm_parent = TC_H_INGRESS, + }; + + pmsg = nlmsg_alloc_simple(RTM_NEWQDISC, NLM_F_CREATE | NLM_F_REPLACE); + if (!pmsg) + goto out_err; + + if (nlmsg_append(pmsg, &tchdr, sizeof(tchdr), NLMSG_ALIGNTO) < 0) + goto out_err; + + NLA_PUT_STRING(pmsg, TCA_KIND, "ingress"); + + if (nl_send_auto_complete(h, pmsg) < 0) + goto out_err; + + if (nl_wait_for_ack(h) < 0) + goto out_err; + + nlmsg_free(pmsg); + + return 0; + +out_err: +nla_put_failure: + + if (pmsg) + nlmsg_free(pmsg); + + log_ppp_error("tbf: error occured, ingress is not installed\n"); + + return -1; +} + +static int install_filter(struct nl_sock *h, int ifindex, int speed, int burst) +{ + //double rate = speed*1000/8; + //double bucket = rate*conf_burst_factor; + double rate = speed * 1000 / 8; + double bucket = burst ? burst : rate * conf_up_burst_factor; + struct nl_msg *pmsg = NULL; + struct nl_msg *msg = NULL; + struct nl_msg *msg1 = NULL; + struct nl_msg *msg2 = NULL; + struct nl_msg *msg3 = NULL; + uint32_t rtab[RTNL_TC_RTABLE_SIZE]; + + struct tcmsg tchdr = { + .tcm_family = AF_UNSPEC, + .tcm_ifindex = ifindex, + .tcm_handle = 1, + .tcm_parent = 0xffff0000, + .tcm_info = TC_H_MAKE(10 << 16, ntohs(ETH_P_IP)), + }; + + struct sel_t { + struct tc_u32_sel sel; + struct tc_u32_key key; + } sel = { + .sel.nkeys = 1, + .sel.flags = TC_U32_TERMINAL, + .key.off = 12, + }; + + struct tc_police police = { + .action = TC_POLICE_SHOT, + .rate.rate = rate, + .rate.mpu = conf_mpu, + .limit = rate*conf_latency/1000 + bucket, + .burst = tc_calc_xmittime(rate, bucket), + }; + + tc_calc_rtable(&police.rate, rtab, 0, 0); + + pmsg = nlmsg_alloc_simple(RTM_NEWTFILTER, NLM_F_CREATE | NLM_F_REPLACE); + if (!pmsg) + goto out_err; + + msg = nlmsg_alloc(); + if (!msg) + goto out_err; + + msg1 = nlmsg_alloc(); + if (!msg1) + goto out_err; + + msg2 = nlmsg_alloc(); + if (!msg2) + goto out_err; + + msg3 = nlmsg_alloc(); + if (!msg3) + goto out_err; + + if (nlmsg_append(pmsg, &tchdr, sizeof(tchdr), NLMSG_ALIGNTO) < 0) + goto out_err; + + NLA_PUT_STRING(pmsg, TCA_KIND, "u32"); + + NLA_PUT_U32(msg, TCA_U32_CLASSID, 1); + NLA_PUT(msg, TCA_U32_SEL, sizeof(sel), &sel); + + NLA_PUT_STRING(msg3, TCA_ACT_KIND, "police"); + + NLA_PUT(msg2, TCA_POLICE_TBF, sizeof(police), &police); + NLA_PUT(msg2, TCA_POLICE_RATE, sizeof(rtab), rtab); + + if (nla_put_nested(msg3, TCA_ACT_OPTIONS, msg2) < 0) + goto out_err; + + if (nla_put_nested(msg1, 1, msg3) < 0) + goto out_err; + + if (nla_put_nested(msg, TCA_U32_ACT, msg1)) + goto out_err; + + if (nla_put_nested(pmsg, TCA_OPTIONS, msg)) + goto out_err; + + if (nl_send_auto_complete(h, pmsg) < 0) + goto out_err; + + if (nl_wait_for_ack(h) < 0) + goto out_err; + + nlmsg_free(pmsg); + nlmsg_free(msg); + nlmsg_free(msg1); + nlmsg_free(msg2); + nlmsg_free(msg3); + + return 0; + +out_err: +nla_put_failure: + + if (pmsg) + nlmsg_free(pmsg); + + if (msg) + nlmsg_free(msg); + + if (msg1) + nlmsg_free(msg1); + + if (msg2) + nlmsg_free(msg1); + + if (msg3) + nlmsg_free(msg1); + + log_ppp_error("tbf: error occured, filter is not installed\n"); + + return -1; +} + + +static int install_shaper(const char *ifname, int down_speed, int down_burst, int up_speed, int up_burst) +{ + struct nl_sock *h; + struct ifreq ifr; + int err; + + memset(&ifr, 0, sizeof(ifr)); + strcpy(ifr.ifr_name, ifname); + + if (ioctl(sock_fd, SIOCGIFINDEX, &ifr)) { + log_ppp_error("tbf: ioctl(SIOCGIFINDEX)", strerror(errno)); + return -1; + } + + h = nl_socket_alloc(); + if (!h) { + log_ppp_error("tbf: nl_socket_alloc failed\n"); + return -1; + } + + err = nl_connect(h, NETLINK_ROUTE); + if (err < 0) { + log_ppp_error("tbf: nl_connect: %s", strerror(errno)); + goto out; + } + + if (down_speed) + if (install_tbf(h, ifr.ifr_ifindex, down_speed, down_burst)) + return -1; + + if (up_speed) { + if (install_ingress(h, ifr.ifr_ifindex)) + return -1; + if (install_filter(h, ifr.ifr_ifindex, up_speed, up_burst)) + return -1; + } + + nl_close(h); +out: + nl_socket_free(h); + + return 0; +} + +static struct shaper_pd_t *find_pd(struct ppp_t *ppp, int create) +{ + struct ppp_pd_t *pd; + struct shaper_pd_t *spd; + + list_for_each_entry(pd, &ppp->pd_list, entry) { + if (pd->key == &pd_key) { + spd = container_of(pd, typeof(*spd), pd); + return spd; + } + } + + if (create) { + spd = _malloc(sizeof(*spd)); + if (!spd) { + log_emerg("tbf: out of memory\n"); + return NULL; + } + + memset(spd, 0, sizeof(*spd)); + spd->ppp = ppp; + list_add_tail(&spd->pd.entry, &ppp->pd_list); + spd->pd.key = &pd_key; + INIT_LIST_HEAD(&spd->tr_list); + + pthread_rwlock_wrlock(&shaper_lock); + list_add_tail(&spd->entry, &shaper_list); + pthread_rwlock_unlock(&shaper_lock); + return spd; + } + + return NULL; +} + +static int remove_shaper(const char *ifname) +{ + struct nl_sock *h; + struct ifreq ifr; + struct nl_msg *pmsg; + int err; + + memset(&ifr, 0, sizeof(ifr)); + strcpy(ifr.ifr_name, ifname); + + if (ioctl(sock_fd, SIOCGIFINDEX, &ifr)) { + log_ppp_error("tbf: ioctl(SIOCGIFINDEX)", strerror(errno)); + return -1; + } + + struct tcmsg tchdr1 = { + .tcm_family = AF_UNSPEC, + .tcm_ifindex = ifr.ifr_ifindex, + .tcm_handle = 0x00010000, + .tcm_parent = TC_H_ROOT, + }; + + struct tcmsg tchdr2 = { + .tcm_family = AF_UNSPEC, + .tcm_ifindex = ifr.ifr_ifindex, + .tcm_handle = 0xffff0000, + .tcm_parent = TC_H_INGRESS, + }; + + h = nl_socket_alloc(); + if (!h) { + log_ppp_error("tbf: nl_socket_alloc failed\n"); + return -1; + } + + err = nl_connect(h, NETLINK_ROUTE); + if (err < 0) { + log_ppp_error("tbf: nl_connect: %s", strerror(errno)); + nl_socket_free(h); + return -1; + } + + pmsg = nlmsg_alloc_simple(RTM_DELQDISC, NLM_F_CREATE | NLM_F_REPLACE); + if (!pmsg) + goto out_err; + + if (nlmsg_append(pmsg, &tchdr1, sizeof(tchdr1), NLMSG_ALIGNTO) < 0) + goto out_err; + + if (nl_send_auto_complete(h, pmsg) < 0) + goto out_err; + + if (nl_wait_for_ack(h) < 0) + goto out_err; + + nlmsg_free(pmsg); + + pmsg = nlmsg_alloc_simple(RTM_DELQDISC, NLM_F_CREATE | NLM_F_REPLACE); + if (!pmsg) + goto out_err; + + if (nlmsg_append(pmsg, &tchdr2, sizeof(tchdr2), NLMSG_ALIGNTO) < 0) + goto out_err; + + if (nl_send_auto_complete(h, pmsg) < 0) + goto out_err; + + if (nl_wait_for_ack(h) < 0) + goto out_err; + + nlmsg_free(pmsg); + + nl_close(h); + nl_socket_free(h); + return 0; + +out_err: + log_ppp_error("tbf: failed to remove shaper\n"); + + if (pmsg) + nlmsg_free(pmsg); + + nl_close(h); + nl_socket_free(h); + + return -1; +} + +static void parse_string(const char *str, int dir, int *speed, int *burst, int *tr_id) +{ + char *endptr; + long int val; + unsigned int n1, n2, n3; + + if (strstr(str, "lcp:interface-config#1=rate-limit output access-group") == str) { + if (dir == ATTR_DOWN) { + val = sscanf(str, "lcp:interface-config#1=rate-limit output access-group %i %u %u %u conform-action transmit exceed-action drop", tr_id, &n1, &n2, &n3); + if (val == 4) { + *speed = n1/1000; + *burst = n2; + } + } + return; + } else if (strstr(str, "lcp:interface-config#1=rate-limit input access-group") == str) { + if (dir == ATTR_UP) { + val = sscanf(str, "lcp:interface-config#1=rate-limit input access-group %i %u %u %u conform-action transmit exceed-action drop", tr_id, &n1, &n2, &n3); + if (val == 4) { + *speed = n1/1000; + *burst = n2; + } + } + return; + } else if (strstr(str, "lcp:interface-config#1=rate-limit output") == str) { + if (dir == ATTR_DOWN) { + val = sscanf(str, "lcp:interface-config#1=rate-limit output %u %u %u conform-action transmit exceed-action drop", &n1, &n2, &n3); + if (val == 3) { + *speed = n1/1000; + *burst = n2; + } + } + return; + } else if (strstr(str, "lcp:interface-config#1=rate-limit input") == str) { + if (dir == ATTR_UP) { + val = sscanf(str, "lcp:interface-config#1=rate-limit input %u %u %u conform-action transmit exceed-action drop", &n1, &n2, &n3); + if (val == 3) { + *speed = n1/1000; + *burst = n2; + } + } + return; + } + + val = strtol(str, &endptr, 10); + if (*endptr == 0) { + *speed = val; + return; + } + if (*endptr == ',') { + *tr_id = val; + val = strtol(endptr + 1, &endptr, 10); + } + if (*endptr == 0) { + *speed = val; + return; + } else { + if (*endptr == '/' || *endptr == '\\' || *endptr == ':') { + if (dir == ATTR_DOWN) + *speed = val; + else + *speed = strtol(endptr + 1, &endptr, 10); + } + } +} + +#ifdef RADIUS +static void parse_attr(struct rad_attr_t *attr, int dir, int *speed, int *burst, int *tr_id) +{ + if (attr->attr->type == ATTR_TYPE_STRING) + parse_string(attr->val.string, dir, speed, burst, tr_id); + else if (attr->attr->type == ATTR_TYPE_INTEGER) + *speed = attr->val.integer; +} + +static struct time_range_pd_t *get_tr_pd(struct shaper_pd_t *pd, int id) +{ + struct time_range_pd_t *tr_pd; + + list_for_each_entry(tr_pd, &pd->tr_list, entry) { + if (tr_pd->id == id) + return tr_pd; + } + + tr_pd = _malloc(sizeof(*tr_pd)); + memset(tr_pd, 0, sizeof(*tr_pd)); + tr_pd->id = id; + + if (id == time_range_id) + pd->cur_tr = tr_pd; + + list_add_tail(&tr_pd->entry, &pd->tr_list); + + return tr_pd; +} + +static void clear_tr_pd(struct shaper_pd_t *pd) +{ + struct time_range_pd_t *tr_pd; + + while (!list_empty(&pd->tr_list)) { + tr_pd = list_entry(pd->tr_list.next, typeof(*tr_pd), entry); + list_del(&tr_pd->entry); + _free(tr_pd); + } +} + +static void check_radius_attrs(struct shaper_pd_t *pd, struct rad_packet_t *pack) +{ + struct rad_attr_t *attr; + int down_speed, down_burst; + int up_speed, up_burst; + int tr_id; + struct time_range_pd_t *tr_pd; + + list_for_each_entry(attr, &pack->attrs, entry) { + if (attr->vendor && attr->vendor->id != conf_vendor) + continue; + if (!attr->vendor && conf_vendor) + continue; + if (attr->attr->id != conf_attr_down && attr->attr->id != conf_attr_up) + continue; + tr_id = 0; + down_speed = 0; + down_burst = 0; + up_speed = 0; + up_burst = 0; + if (attr->attr->id == conf_attr_down) + parse_attr(attr, ATTR_DOWN, &down_speed, &down_burst, &tr_id); + if (attr->attr->id == conf_attr_up) + parse_attr(attr, ATTR_UP, &up_speed, &up_burst, &tr_id); + tr_pd = get_tr_pd(pd, tr_id); + if (down_speed) + tr_pd->down_speed = down_speed; + if (down_burst) + tr_pd->down_burst = down_burst; + if (up_speed) + tr_pd->up_speed = up_speed; + if (up_burst) + tr_pd->up_burst = up_burst; + } +} + +static void ev_radius_access_accept(struct ev_radius_t *ev) +{ + int down_speed, down_burst; + int up_speed, up_burst; + struct shaper_pd_t *pd = find_pd(ev->ppp, 1); + + if (!pd) + return; + + check_radius_attrs(pd, ev->reply); + + if (temp_down_speed || temp_up_speed) { + pd->temp_down_speed = temp_down_speed; + pd->temp_up_speed = temp_up_speed; + pd->down_speed = temp_down_speed; + pd->up_speed = temp_up_speed; + down_speed = temp_down_speed; + up_speed = temp_up_speed; + down_burst = 0; + up_burst = 0; + } else { + if (!pd->cur_tr) + return; + pd->down_speed = pd->cur_tr->down_speed; + pd->up_speed = pd->cur_tr->up_speed; + down_speed = pd->cur_tr->down_speed; + up_speed = pd->cur_tr->up_speed; + down_burst = pd->cur_tr->down_burst; + up_burst = pd->cur_tr->up_speed; + } + + if (down_speed > 0 && up_speed > 0) { + if (!install_shaper(ev->ppp->ifname, down_speed, down_burst, up_speed, up_burst)) { + if (conf_verbose) + log_ppp_info2("tbf: installed shaper %i/%i (Kbit)\n", down_speed, up_speed); + } + } +} + +static void ev_radius_coa(struct ev_radius_t *ev) +{ + struct shaper_pd_t *pd = find_pd(ev->ppp, 0); + + if (!pd) { + ev->res = -1; + return; + } + + clear_tr_pd(pd); + check_radius_attrs(pd, ev->request); + + if (pd->temp_down_speed || pd->temp_up_speed) + return; + + if (!pd->cur_tr) { + if (pd->down_speed || pd->up_speed) { + pd->down_speed = 0; + pd->up_speed = 0; + if (conf_verbose) + log_ppp_info2("tbf: removed shaper\n"); + remove_shaper(ev->ppp->ifname); + } + return; + } + + if (pd->down_speed != pd->cur_tr->down_speed || pd->up_speed != pd->cur_tr->up_speed) { + pd->down_speed = pd->cur_tr->down_speed; + pd->up_speed = pd->cur_tr->up_speed; + + if (remove_shaper(ev->ppp->ifname)) { + ev->res = -1; + return; + } + + if (pd->down_speed > 0 || pd->up_speed > 0) { + if (install_shaper(ev->ppp->ifname, pd->cur_tr->down_speed, pd->cur_tr->down_burst, pd->cur_tr->up_speed, pd->cur_tr->up_burst)) { + ev->res= -1; + return; + } else { + if (conf_verbose) + log_ppp_info2("tbf: changed shaper %i/%i (Kbit)\n", pd->down_speed, pd->up_speed); + } + } else { + if (conf_verbose) + log_ppp_info2("tbf: removed shaper\n"); + } + } +} +#endif + +static void ev_shaper(struct ev_shaper_t *ev) +{ + struct shaper_pd_t *pd = find_pd(ev->ppp, 1); + int down_speed = 0, down_burst = 0; + int up_speed = 0, up_burst = 0; + int tr_id; + + if (!pd) + return; + + parse_string(ev->val, ATTR_DOWN, &down_speed, &down_burst, &tr_id); + parse_string(ev->val, ATTR_UP, &up_speed, &up_burst, &tr_id); + + if (down_speed > 0 && up_speed > 0) { + pd->down_speed = down_speed; + pd->up_speed = up_speed; + if (!install_shaper(ev->ppp->ifname, down_speed, down_burst, up_speed, up_burst)) { + if (conf_verbose) + log_ppp_info2("tbf: installed shaper %i/%i (Kbit)\n", down_speed, up_speed); + } + } +} + +static void ev_ctrl_finished(struct ppp_t *ppp) +{ + struct shaper_pd_t *pd = find_pd(ppp, 0); + + if (pd) { + clear_tr_pd(pd); + pthread_rwlock_wrlock(&shaper_lock); + list_del(&pd->entry); + pthread_rwlock_unlock(&shaper_lock); + list_del(&pd->pd.entry); + _free(pd); + } +} + +static void shaper_change_help(char * const *f, int f_cnt, void *cli) +{ + cli_send(cli, "shaper change [temp] - change shaper on specified interface, if temp is set then previous settings may be restored later by 'shaper restore'\r\n"); + cli_send(cli, "shaper change all [temp] - change shaper on all interfaces, if temp is set also new interfaces will have specified shaper value\r\n"); +} + +static void shaper_change(struct shaper_pd_t *pd) +{ + if ((pd->temp_down_speed && pd->temp_up_speed) || (pd->down_speed && pd->up_speed)) + remove_shaper(pd->ppp->ifname); + + if (pd->temp_down_speed && pd->temp_up_speed) + install_shaper(pd->ppp->ifname, pd->temp_down_speed, 0, pd->temp_up_speed, 0); + else if (pd->down_speed && pd->up_speed) + install_shaper(pd->ppp->ifname, pd->cur_tr->down_speed, pd->cur_tr->down_burst, pd->cur_tr->up_speed, pd->cur_tr->up_burst); +} + +static int shaper_change_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + struct shaper_pd_t *pd; + int down_speed = 0, up_speed = 0, down_burst = 0, up_burst = 0; + int all = 0, temp = 0, found = 0; + int tr_id; + + if (f_cnt < 4) + return CLI_CMD_SYNTAX; + + parse_string(f[3], ATTR_DOWN, &down_speed, &down_burst, &tr_id); + parse_string(f[3], ATTR_UP, &up_speed, &up_burst, &tr_id); + + if (down_speed == 0 || up_speed == 0) + return CLI_CMD_INVAL; + + if (!strcmp(f[2], "all")) + all = 1; + + if (f_cnt == 5) { + if (strcmp(f[4], "temp")) + return CLI_CMD_SYNTAX; + else + temp = 1; + } + + if (all && temp) { + temp_down_speed = down_speed; + temp_up_speed = up_speed; + } + + pthread_rwlock_rdlock(&shaper_lock); + list_for_each_entry(pd, &shaper_list, entry) { + if (all || !strcmp(f[2], pd->ppp->ifname)) { + if (temp) { + pd->temp_down_speed = down_speed; + pd->temp_up_speed = up_speed; + } else { + pd->temp_down_speed = 0; + pd->temp_up_speed = 0; + if (!pd->cur_tr) + pd->cur_tr = get_tr_pd(pd, 0); + pd->cur_tr->down_speed = down_speed; + pd->cur_tr->down_burst = down_burst; + pd->cur_tr->up_speed = up_speed; + pd->cur_tr->up_burst = up_burst; + } + triton_context_call(pd->ppp->ctrl->ctx, (triton_event_func)shaper_change, pd); + if (!all) { + found = 1; + break; + } + } + } + pthread_rwlock_unlock(&shaper_lock); + + if (!all && !found) + cli_send(cli, "not found\r\n"); + + return CLI_CMD_OK; +} + +static void shaper_restore_help(char * const *f, int f_cnt, void *cli) +{ + cli_send(cli, "shaper restore - restores shaper settings on specified interface made by 'shaper change' command with 'temp' flag\r\n"); + cli_send(cli, "shaper restore all - restores shaper settings on all interfaces made by 'shaper change' command with 'temp' flag\r\n"); +} + +static void shaper_restore(struct shaper_pd_t *pd) +{ + remove_shaper(pd->ppp->ifname); + + if (pd->cur_tr) + install_shaper(pd->ppp->ifname, pd->cur_tr->down_speed, pd->cur_tr->down_burst, pd->cur_tr->up_speed, pd->cur_tr->up_burst); +} + +static int shaper_restore_exec(const char *cmd, char * const *f, int f_cnt, void *cli) +{ + struct shaper_pd_t *pd; + int all, found = 0;; + + if (f_cnt != 3) + return CLI_CMD_SYNTAX; + + if (strcmp(f[2], "all")) + all = 0; + else + all = 1; + + pthread_rwlock_rdlock(&shaper_lock); + if (all) { + temp_down_speed = 0; + temp_up_speed = 0; + } + list_for_each_entry(pd, &shaper_list, entry) { + if (!pd->temp_down_speed) + continue; + if (all || !strcmp(f[2], pd->ppp->ifname)) { + pd->temp_down_speed = 0; + pd->temp_up_speed = 0; + triton_context_call(pd->ppp->ctrl->ctx, (triton_event_func)shaper_restore, pd); + if (!all) { + found = 1; + break; + } + } + } + pthread_rwlock_unlock(&shaper_lock); + + if (!all && !found) + cli_send(cli, "not found\r\n"); + + return CLI_CMD_OK; +} + +static void print_rate(const struct ppp_t *ppp, char *buf) +{ + struct shaper_pd_t *pd = find_pd((struct ppp_t *)ppp, 0); + + if (pd && (pd->down_speed || pd->up_speed)) + sprintf(buf, "%i/%i", pd->down_speed, pd->up_speed); + else + *buf = 0; +} + +static void shaper_ctx_close(struct triton_context_t *ctx) +{ + struct time_range_t *r; + + while (!list_empty(&time_range_list)) { + r = list_entry(time_range_list.next, typeof(*r), entry); + list_del(&r->entry); + if (r->begin.tpd) + triton_timer_del(&r->begin); + if (r->end.tpd) + triton_timer_del(&r->end); + _free(r); + } + + triton_context_unregister(ctx); +} + +static void update_shaper_tr(struct shaper_pd_t *pd) +{ + struct time_range_pd_t *tr; + + list_for_each_entry(tr, &pd->tr_list, entry) { + if (tr->id != time_range_id) + continue; + pd->cur_tr = tr; + break; + } + + if (pd->temp_down_speed || pd->temp_up_speed) + return; + + if (pd->down_speed || pd->up_speed) { + if (pd->cur_tr && pd->down_speed == pd->cur_tr->down_speed && pd->up_speed == pd->cur_tr->up_speed) + return; + remove_shaper(pd->ppp->ifname); + } + + if (pd->cur_tr && (pd->cur_tr->down_speed || pd->cur_tr->up_speed)) { + pd->down_speed = pd->cur_tr->down_speed; + pd->up_speed = pd->cur_tr->up_speed; + if (!install_shaper(pd->ppp->ifname, pd->cur_tr->down_speed, pd->cur_tr->down_burst, pd->cur_tr->up_speed, pd->cur_tr->up_burst)) { + if (conf_verbose) + log_ppp_info2("tbf: changed shaper %i/%i (Kbit)\n", pd->cur_tr->down_speed, pd->cur_tr->up_speed); + } + } else + if (conf_verbose) + log_ppp_info2("tbf: removed shaper\n"); + +} + +static void time_range_begin_timer(struct triton_timer_t *t) +{ + struct time_range_t *tr = container_of(t, typeof(*tr), begin); + struct shaper_pd_t *pd; + + time_range_id = tr->id; + + log_debug("tbf: time_range_begin_timer: id=%i\n", time_range_id); + + pthread_rwlock_rdlock(&shaper_lock); + list_for_each_entry(pd, &shaper_list, entry) + triton_context_call(pd->ppp->ctrl->ctx, (triton_event_func)update_shaper_tr, pd); + pthread_rwlock_unlock(&shaper_lock); +} + +static void time_range_end_timer(struct triton_timer_t *t) +{ + struct shaper_pd_t *pd; + + time_range_id = 0; + + log_debug("tbf: time_range_end_timer\n"); + + pthread_rwlock_rdlock(&shaper_lock); + list_for_each_entry(pd, &shaper_list, entry) + triton_context_call(pd->ppp->ctrl->ctx, (triton_event_func)update_shaper_tr, pd); + pthread_rwlock_unlock(&shaper_lock); +} + +static struct time_range_t *parse_range(const char *val) +{ + char *endptr; + int id; + time_t t; + struct tm begin_tm, end_tm; + struct time_range_t *r; + + id = strtol(val, &endptr, 10); + if (*endptr != ',') + return NULL; + if (id <= 0) + return NULL; + + time(&t); + localtime_r(&t, &begin_tm); + begin_tm.tm_sec = 1; + end_tm = begin_tm; + end_tm.tm_sec = 0; + + endptr = strptime(endptr + 1, "%H:%M", &begin_tm); + if (*endptr != '-') + return NULL; + + endptr = strptime(endptr + 1, "%H:%M", &end_tm); + if (*endptr) + return NULL; + + r = _malloc(sizeof(*r)); + memset(r, 0, sizeof(*r)); + + r->id = id; + r->begin.expire_tv.tv_sec = mktime(&begin_tm); + r->begin.period = 24 * 60 * 60 * 1000; + r->begin.expire = time_range_begin_timer; + r->end.expire_tv.tv_sec = mktime(&end_tm); + r->end.period = 24 * 60 * 60 * 1000; + r->end.expire = time_range_end_timer; + + return r; +} + +static void load_time_ranges(void) +{ + struct conf_sect_t *s = conf_get_section("tbf"); + struct conf_option_t *opt; + struct time_range_t *r; + time_t ts; + + if (!s) + return; + + time(&ts); + + while (!list_empty(&time_range_list)) { + r = list_entry(time_range_list.next, typeof(*r), entry); + list_del(&r->entry); + if (r->begin.tpd) + triton_timer_del(&r->begin); + if (r->end.tpd) + triton_timer_del(&r->end); + _free(r); + } + + list_for_each_entry(opt, &s->items, entry) { + if (strcmp(opt->name, "time-range")) + continue; + r = parse_range(opt->val); + if (r) { + list_add_tail(&r->entry, &time_range_list); + if (r->begin.expire_tv.tv_sec > r->end.expire_tv.tv_sec) { + if (ts >= r->begin.expire_tv.tv_sec - 24*60*60 && ts <= r->end.expire_tv.tv_sec) + time_range_begin_timer(&r->begin); + } else { + if (ts >= r->begin.expire_tv.tv_sec && ts <= r->end.expire_tv.tv_sec) + time_range_begin_timer(&r->begin); + } + if (r->begin.expire_tv.tv_sec < ts) + r->begin.expire_tv.tv_sec += 24 * 60 * 60; + if (r->end.expire_tv.tv_sec < ts) + r->end.expire_tv.tv_sec += 24 * 60 * 60; + triton_timer_add(&shaper_ctx, &r->begin, 1); + triton_timer_add(&shaper_ctx, &r->end, 1); + } else + log_emerg("tbf: failed to parse time-range '%s'\n", opt->val); + } +} + +#ifdef RADIUS +static int parse_attr_opt(const char *opt) +{ + struct rad_dict_attr_t *attr; + struct rad_dict_vendor_t *vendor; + + if (conf_vendor) + vendor = rad_dict_find_vendor_id(conf_vendor); + else + vendor = NULL; + + if (conf_vendor) { + if (vendor) + attr = rad_dict_find_vendor_attr(vendor, opt); + else + attr = NULL; + }else + attr = rad_dict_find_attr(opt); + + if (attr) + return attr->id; + + return atoi(opt); +} + +static int parse_vendor_opt(const char *opt) +{ + struct rad_dict_vendor_t *vendor; + + vendor = rad_dict_find_vendor_name(opt); + if (vendor) + return vendor->id; + + return atoi(opt); +} +#endif + +static void load_config(void) +{ + const char *opt; + +#ifdef RADIUS + opt = conf_get_opt("tbf", "vendor"); + if (opt) + conf_vendor = parse_vendor_opt(opt); + + opt = conf_get_opt("tbf", "attr"); + if (opt) { + conf_attr_down = parse_attr_opt(opt); + conf_attr_up = parse_attr_opt(opt); + } + + opt = conf_get_opt("tbf", "attr-down"); + if (opt) + conf_attr_down = parse_attr_opt(opt); + + opt = conf_get_opt("tbf", "attr-up"); + if (opt) + conf_attr_up = parse_attr_opt(opt); + + if (conf_attr_up <= 0 || conf_attr_down <= 0) { + log_emerg("tbf: incorrect attribute(s), tbf disabled...\n"); + return; + } +#endif + + opt = conf_get_opt("tbf", "burst-factor"); + if (opt) { + conf_down_burst_factor = strtod(opt, NULL); + conf_up_burst_factor = conf_down_burst_factor * 10; + } + + opt = conf_get_opt("tbf", "down-burst-factor"); + if (opt) + conf_down_burst_factor = strtod(opt, NULL); + + opt = conf_get_opt("tbf", "up-burst-factor"); + if (opt) + conf_up_burst_factor = strtod(opt, NULL); + + opt = conf_get_opt("tbf", "latency"); + if (opt && atoi(opt) > 0) + conf_latency = atoi(opt); + + opt = conf_get_opt("tbf", "mpu"); + if (opt && atoi(opt) >= 0) + conf_mpu = atoi(opt); + + opt = conf_get_opt("tbf", "verbose"); + if (opt && atoi(opt) > 0) + conf_verbose = 1; + + triton_context_call(&shaper_ctx, (triton_event_func)load_time_ranges, NULL); +} + +static int clock_init(void) +{ + FILE *fp; + uint32_t clock_res; + uint32_t t2us; + uint32_t us2t; + + fp = fopen("/proc/net/psched", "r"); + + if (!fp) { + log_emerg("tbf: failed to open /proc/net/psched: %s\n", strerror(errno)); + return -1; + } + + if (fscanf(fp, "%08x%08x%08x", &t2us, &us2t, &clock_res) != 3) { + log_emerg("tbf: failed to parse /proc/net/psched\n"); + fclose(fp); + return -1; + } + + fclose(fp); + + /* compatibility hack: for old iproute binaries (ignoring + * the kernel clock resolution) the kernel advertises a + * tick multiplier of 1000 in case of nano-second resolution, + * which really is 1. */ + if (clock_res == 1000000000) + t2us = us2t; + + clock_factor = (double)clock_res / TIME_UNITS_PER_SEC; + tick_in_usec = (double)t2us / us2t * clock_factor; + + return 0; +} + +static void __init init(void) +{ + if (clock_init()) + return; + + triton_context_register(&shaper_ctx, NULL); + triton_context_wakeup(&shaper_ctx); + + load_config(); + +#ifdef RADIUS + triton_event_register_handler(EV_RADIUS_ACCESS_ACCEPT, (triton_event_func)ev_radius_access_accept); + triton_event_register_handler(EV_RADIUS_COA, (triton_event_func)ev_radius_coa); +#endif + triton_event_register_handler(EV_CTRL_FINISHED, (triton_event_func)ev_ctrl_finished); + triton_event_register_handler(EV_SHAPER, (triton_event_func)ev_shaper); + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); + + cli_register_simple_cmd2(shaper_change_exec, shaper_change_help, 2, "shaper", "change"); + cli_register_simple_cmd2(shaper_restore_exec, shaper_restore_help, 2, "shaper", "restore"); + cli_show_ses_register("rate-limit", "rate limit down-stream/up-stream (Kbit)", print_rate); +} + diff --git a/accel-pppd/extra/sigchld.c b/accel-pppd/extra/sigchld.c new file mode 100644 index 0000000..abfd42f --- /dev/null +++ b/accel-pppd/extra/sigchld.c @@ -0,0 +1,116 @@ +#include +#include +#include +#include +#include + +#include "triton.h" +#include "spinlock.h" +#include "log.h" + +#include "sigchld.h" + +#include "memdebug.h" + +static LIST_HEAD(handlers); +static int lock_refs; +static pthread_mutex_t handlers_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t refs_cond = PTHREAD_COND_INITIALIZER; +static pthread_t sigchld_thr; + +static void* sigchld_thread(void *arg) +{ + sigset_t set; + struct sigchld_handler_t *h, *h0; + pid_t pid; + int status, sig; + + sigfillset(&set); + sigdelset(&set, SIGKILL); + sigdelset(&set, SIGSTOP); + pthread_sigmask(SIG_BLOCK, &set, NULL); + + sigemptyset(&set); + sigaddset(&set, SIGCHLD); + sigaddset(&set, SIGQUIT); + + while (1) { + pid = waitpid(0, &status, 0); + if (pid < 0) { + if (errno == EINTR) + continue; + if (errno == ECHILD) { + sigwait(&set, &sig); + if (sig == SIGQUIT) + break; + continue; + } + log_error("sigchld: waitpid: %s\n", strerror(errno)); + continue; + } + + pthread_mutex_lock(&handlers_lock); + while (lock_refs) + pthread_cond_wait(&refs_cond, &handlers_lock); + + h0 = NULL; + list_for_each_entry(h, &handlers, entry) { + if (h->pid == pid) { + h0 = h; + list_del(&h0->entry); + pthread_mutex_lock(&h0->lock); + break; + } + } + pthread_mutex_unlock(&handlers_lock); + if (h0) { + h0->handler(h0, WEXITSTATUS(status)); + h0->pid = 0; + pthread_mutex_unlock(&h0->lock); + } + } + + return NULL; +} + +void __export sigchld_register_handler(struct sigchld_handler_t *h) +{ + pthread_mutex_init(&h->lock, NULL); + + pthread_mutex_lock(&handlers_lock); + list_add_tail(&h->entry, &handlers); + pthread_mutex_unlock(&handlers_lock); +} + +void __export sigchld_unregister_handler(struct sigchld_handler_t *h) +{ + pthread_mutex_lock(&handlers_lock); + pthread_mutex_lock(&h->lock); + if (h->pid) { + list_del(&h->entry); + h->pid = 0; + } + pthread_mutex_unlock(&h->lock); + pthread_mutex_unlock(&handlers_lock); +} + +void __export sigchld_lock() +{ + pthread_mutex_lock(&handlers_lock); + ++lock_refs; + pthread_mutex_unlock(&handlers_lock); +} + +void __export sigchld_unlock() +{ + pthread_mutex_lock(&handlers_lock); + if (--lock_refs == 0) + pthread_cond_signal(&refs_cond); + pthread_mutex_unlock(&handlers_lock); +} + +static void __init init(void) +{ + if (pthread_create(&sigchld_thr, NULL, sigchld_thread, NULL)) + log_emerg("sigchld: pthread_create: %s\n", strerror(errno)); +} diff --git a/accel-pppd/extra/sigchld.h b/accel-pppd/extra/sigchld.h new file mode 100644 index 0000000..27d1adf --- /dev/null +++ b/accel-pppd/extra/sigchld.h @@ -0,0 +1,21 @@ +#ifndef __SIGCHLD_H +#define __SIGCHLD_H + +#include +#include "list.h" + +struct sigchld_handler_t +{ + struct list_head entry; + pthread_mutex_t lock; + pid_t pid; + void (*handler)(struct sigchld_handler_t *, int status); +}; + +void sigchld_register_handler(struct sigchld_handler_t *); +void sigchld_unregister_handler(struct sigchld_handler_t *); +void sigchld_lock(); +void sigchld_unlock(); + +#endif + diff --git a/accel-pppd/include/cli.h b/accel-pppd/include/cli.h new file mode 120000 index 0000000..b0f4902 --- /dev/null +++ b/accel-pppd/include/cli.h @@ -0,0 +1 @@ +../cli/cli.h \ No newline at end of file diff --git a/accel-pppd/include/events.h b/accel-pppd/include/events.h new file mode 100644 index 0000000..6a8caf0 --- /dev/null +++ b/accel-pppd/include/events.h @@ -0,0 +1,49 @@ +#ifndef __EVENTS_H +#define __EVENTS_H + +#include + +#define EV_PPP_STARTING 1 +#define EV_PPP_STARTED 2 +#define EV_PPP_FINISHING 3 +#define EV_PPP_FINISHED 4 +#define EV_PPP_AUTHORIZED 5 +#define EV_CTRL_STARTING 6 +#define EV_CTRL_STARTED 7 +#define EV_CTRL_FINISHED 8 +#define EV_PPP_PRE_UP 9 +#define EV_PPP_ACCT_START 10 +#define EV_CONFIG_RELOAD 11 +#define EV_IP_CHANGED 100 +#define EV_SHAPER 101 +#define EV_MPPE_KEYS 102 +#define EV_RADIUS_ACCESS_ACCEPT 200 +#define EV_RADIUS_COA 201 + +struct ppp_t; +struct rad_packet_t; +struct ev_radius_t +{ + struct ppp_t *ppp; + struct rad_packet_t *request; + struct rad_packet_t *reply; + int res; +}; + +struct ev_mppe_keys_t +{ + struct ppp_t *ppp; + uint8_t *recv_key; + uint8_t *send_key; + int policy; + int type; +}; + +struct ev_shaper_t +{ + struct ppp_t *ppp; + const char *val; +}; + +#endif + diff --git a/accel-pppd/include/if_pppox.h b/accel-pppd/include/if_pppox.h new file mode 100644 index 0000000..0532d18 --- /dev/null +++ b/accel-pppd/include/if_pppox.h @@ -0,0 +1,234 @@ +/*************************************************************************** + * Linux PPP over X - Generic PPP transport layer sockets + * Linux PPP over Ethernet (PPPoE) Socket Implementation (RFC 2516) + * + * This file supplies definitions required by the PPP over Ethernet driver + * (pppox.c). All version information wrt this file is located in pppox.c + * + * License: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + * + */ + +#ifndef __LINUX_IF_PPPOX_H +#define __LINUX_IF_PPPOX_H + + +#include +#include +#include +#include +#include + +#ifdef __KERNEL__ +#include +#include +#include +#endif /* __KERNEL__ */ + +/* For user-space programs to pick up these definitions + * which they wouldn't get otherwise without defining __KERNEL__ + */ +#ifndef AF_PPPOX +#define AF_PPPOX 24 +#define PF_PPPOX AF_PPPOX +#endif /* !(AF_PPPOX) */ + +struct pppoe_addr { + __be16 sid; + unsigned char remote[ETH_ALEN]; + char dev[IFNAMSIZ]; +}; + +struct pptp_addr { + __u16 call_id; + struct in_addr sin_addr; +}; +/************************************************************************ + * Protocols supported by AF_PPPOX + */ +#define PX_PROTO_OE 0 /* Currently just PPPoE */ +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) +#define PX_PROTO_PPTP 1 +#define PX_MAX_PROTO 2 +#else +#define PX_PROTO_PPTP 2 +#define PX_MAX_PROTO 3 +#endif + +struct sockaddr_pppox { + sa_family_t sa_family; /* address family, AF_PPPOX */ + unsigned int sa_protocol; /* protocol identifier */ + union{ + struct pppoe_addr pppoe; + struct pptp_addr pptp; + }sa_addr; +}__attribute__ ((packed)); + + +/********************************************************************* + * + * ioctl interface for defining forwarding of connections + * + ********************************************************************/ + +#define PPPOEIOCSFWD _IOW(0xB1 ,0, size_t) +#define PPPOEIOCDFWD _IO(0xB1 ,1) +/*#define PPPOEIOCGFWD _IOWR(0xB1,2, size_t)*/ + +/* Codes to identify message types */ +#define PADI_CODE 0x09 +#define PADO_CODE 0x07 +#define PADR_CODE 0x19 +#define PADS_CODE 0x65 +#define PADT_CODE 0xa7 +struct pppoe_tag { + __u16 tag_type; + __u16 tag_len; + char tag_data[0]; +} __attribute ((packed)); + +/* Tag identifiers */ +#define PTT_EOL __constant_htons(0x0000) +#define PTT_SRV_NAME __constant_htons(0x0101) +#define PTT_AC_NAME __constant_htons(0x0102) +#define PTT_HOST_UNIQ __constant_htons(0x0103) +#define PTT_AC_COOKIE __constant_htons(0x0104) +#define PTT_VENDOR __constant_htons(0x0105) +#define PTT_RELAY_SID __constant_htons(0x0110) +#define PTT_SRV_ERR __constant_htons(0x0201) +#define PTT_SYS_ERR __constant_htons(0x0202) +#define PTT_GEN_ERR __constant_htons(0x0203) + +struct pppoe_hdr { +#if defined(__LITTLE_ENDIAN_BITFIELD) + __u8 ver : 4; + __u8 type : 4; +#elif defined(__BIG_ENDIAN_BITFIELD) + __u8 type : 4; + __u8 ver : 4; +#else +#error "Please fix " +#endif + __u8 code; + __u16 sid; + __u16 length; + struct pppoe_tag tag[0]; +} __attribute__ ((packed)); + + +/* Socket options */ +#define PPTP_SO_TIMEOUT 1 + + +#ifdef __KERNEL__ +#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,0) +struct pppoe_opt { + struct net_device *dev; /* device associated with socket*/ + struct pppoe_addr pa; /* what this socket is bound to*/ + struct sockaddr_pppox relay; /* what socket data will be + relayed to (PPPoE relaying) */ +}; +#endif +struct pptp_opt { + struct pptp_addr src_addr; + struct pptp_addr dst_addr; + int timeout; + __u32 ack_sent, ack_recv; + __u32 seq_sent, seq_recv; + int ppp_flags; + int flags; + struct sk_buff_head skb_buf; + #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) + struct tq_struct buf_work; //check bufferd packets work + struct timer_list buf_timer; + #else + #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20) + struct delayed_work buf_work; //check bufferd packets work + #else + struct work_struct buf_work; //check bufferd packets work + #endif + #endif + struct gre_statistics *stat; + spinlock_t xmit_lock; + spinlock_t rcv_lock; +}; +#define PPTP_FLAG_PAUSE 0 +#define PPTP_FLAG_PROC 1 + +#include + +struct pppox_sock { + /* struct sock must be the first member of pppox_sock */ + #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) + struct ppp_channel chan; + struct sock *sk; + #else + struct sock sk; + struct ppp_channel chan; + #endif + struct pppox_sock *next; /* for hash table */ + union { + struct pppoe_opt pppoe; + struct pptp_opt pptp; + } proto; + unsigned short num; +}; +#define pppoe_dev proto.pppoe.dev +#define pppoe_pa proto.pppoe.pa +#define pppoe_relay proto.pppoe.relay + +static inline struct pppox_sock *pppox_sk(struct sock *sk) +{ + #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) + return (struct pppox_sock *)sk->protinfo.pppox; + #else + return (struct pppox_sock *)sk; + #endif +} + +static inline struct sock *sk_pppox(struct pppox_sock *po) +{ + #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) + return po->sk; + #else + return (struct sock *)po; + #endif +} + +struct module; + +struct pppox_proto { + #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24) + int (*create)(struct socket *sock); + #else + int (*create)(struct net *net, struct socket *sock); + #endif + int (*ioctl)(struct socket *sock, unsigned int cmd, + unsigned long arg); + #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,15) + struct module *owner; + #endif +}; + +extern int register_pppox_proto(int proto_num, struct pppox_proto *pp); +extern void unregister_pppox_proto(int proto_num); +extern void pppox_unbind_sock(struct sock *sk);/* delete ppp-channel binding */ +extern int pppox_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg); + +/* PPPoX socket states */ +enum { + PPPOX_NONE = 0, /* initial state */ + PPPOX_CONNECTED = 1, /* connection established ==TCP_ESTABLISHED */ + PPPOX_BOUND = 2, /* bound to ppp device */ + PPPOX_RELAY = 4, /* forwarding is enabled */ + PPPOX_ZOMBIE = 8, /* dead, but still bound to ppp device */ + PPPOX_DEAD = 16 /* dead, useless, please clean me up!*/ +}; + +#endif /* __KERNEL__ */ + +#endif /* !(__LINUX_IF_PPPOX_H) */ diff --git a/accel-pppd/include/ipdb.h b/accel-pppd/include/ipdb.h new file mode 120000 index 0000000..77ab85b --- /dev/null +++ b/accel-pppd/include/ipdb.h @@ -0,0 +1 @@ +../ipdb.h \ No newline at end of file diff --git a/accel-pppd/include/iprange.h b/accel-pppd/include/iprange.h new file mode 120000 index 0000000..b8c2c43 --- /dev/null +++ b/accel-pppd/include/iprange.h @@ -0,0 +1 @@ +../iprange.h \ No newline at end of file diff --git a/accel-pppd/include/linux_ppp.h b/accel-pppd/include/linux_ppp.h new file mode 100644 index 0000000..ebb4c23 --- /dev/null +++ b/accel-pppd/include/linux_ppp.h @@ -0,0 +1,19 @@ +#ifndef __KERNEL_PPP_H +#define __KERNEL_PPP_H + +#include + +#ifndef aligned_u64 +#define aligned_u64 __u64 __attribute__((aligned(8))) +#endif + +#ifndef __aligned_u64 +#define __aligned_u64 __u64 __attribute__((aligned(8))) +#endif + +#include +#include +#include + +#endif + diff --git a/accel-pppd/include/list.h b/accel-pppd/include/list.h new file mode 120000 index 0000000..4b6d9a9 --- /dev/null +++ b/accel-pppd/include/list.h @@ -0,0 +1 @@ +../triton/list.h \ No newline at end of file diff --git a/accel-pppd/include/log.h b/accel-pppd/include/log.h new file mode 120000 index 0000000..49a04dd --- /dev/null +++ b/accel-pppd/include/log.h @@ -0,0 +1 @@ +../log.h \ No newline at end of file diff --git a/accel-pppd/include/memdebug.h b/accel-pppd/include/memdebug.h new file mode 120000 index 0000000..3ee61bc --- /dev/null +++ b/accel-pppd/include/memdebug.h @@ -0,0 +1 @@ +../memdebug.h \ No newline at end of file diff --git a/accel-pppd/include/mempool.h b/accel-pppd/include/mempool.h new file mode 120000 index 0000000..2637ab6 --- /dev/null +++ b/accel-pppd/include/mempool.h @@ -0,0 +1 @@ +../triton/mempool.h \ No newline at end of file diff --git a/accel-pppd/include/ppp.h b/accel-pppd/include/ppp.h new file mode 120000 index 0000000..ae3fa2e --- /dev/null +++ b/accel-pppd/include/ppp.h @@ -0,0 +1 @@ +../ppp/ppp.h \ No newline at end of file diff --git a/accel-pppd/include/ppp_auth.h b/accel-pppd/include/ppp_auth.h new file mode 120000 index 0000000..527c853 --- /dev/null +++ b/accel-pppd/include/ppp_auth.h @@ -0,0 +1 @@ +../ppp/ppp_auth.h \ No newline at end of file diff --git a/accel-pppd/include/ppp_fsm.h b/accel-pppd/include/ppp_fsm.h new file mode 120000 index 0000000..5c6b7f4 --- /dev/null +++ b/accel-pppd/include/ppp_fsm.h @@ -0,0 +1 @@ +../ppp/ppp_fsm.h \ No newline at end of file diff --git a/accel-pppd/include/ppp_lcp.h b/accel-pppd/include/ppp_lcp.h new file mode 120000 index 0000000..4902752 --- /dev/null +++ b/accel-pppd/include/ppp_lcp.h @@ -0,0 +1 @@ +../ppp/ppp_lcp.h \ No newline at end of file diff --git a/accel-pppd/include/pwdb.h b/accel-pppd/include/pwdb.h new file mode 120000 index 0000000..360efe4 --- /dev/null +++ b/accel-pppd/include/pwdb.h @@ -0,0 +1 @@ +../pwdb.h \ No newline at end of file diff --git a/accel-pppd/include/radius.h b/accel-pppd/include/radius.h new file mode 120000 index 0000000..e1465f1 --- /dev/null +++ b/accel-pppd/include/radius.h @@ -0,0 +1 @@ +../radius/radius.h \ No newline at end of file diff --git a/accel-pppd/include/sigchld.h b/accel-pppd/include/sigchld.h new file mode 120000 index 0000000..9b74ebd --- /dev/null +++ b/accel-pppd/include/sigchld.h @@ -0,0 +1 @@ +../extra/sigchld.h \ No newline at end of file diff --git a/accel-pppd/include/spinlock.h b/accel-pppd/include/spinlock.h new file mode 120000 index 0000000..09edcf6 --- /dev/null +++ b/accel-pppd/include/spinlock.h @@ -0,0 +1 @@ +../triton/spinlock.h \ No newline at end of file diff --git a/accel-pppd/include/triton.h b/accel-pppd/include/triton.h new file mode 120000 index 0000000..6f35a2f --- /dev/null +++ b/accel-pppd/include/triton.h @@ -0,0 +1 @@ +../triton/triton.h \ No newline at end of file diff --git a/accel-pppd/include/utils.h b/accel-pppd/include/utils.h new file mode 120000 index 0000000..6cd5d4f --- /dev/null +++ b/accel-pppd/include/utils.h @@ -0,0 +1 @@ +../utils.h \ No newline at end of file diff --git a/accel-pppd/ipdb.c b/accel-pppd/ipdb.c new file mode 100644 index 0000000..a08d3be --- /dev/null +++ b/accel-pppd/ipdb.c @@ -0,0 +1,31 @@ +#include "triton.h" +#include "ipdb.h" + +#include "memdebug.h" + +static LIST_HEAD(ipdb_handlers); + +__export struct ipdb_item_t *ipdb_get(struct ppp_t *ppp) +{ + struct ipdb_t *ipdb; + struct ipdb_item_t *it; + + list_for_each_entry(ipdb, &ipdb_handlers, entry) { + it = ipdb->get(ppp); + if (it) + return it; + } + + return NULL; +} + +void __export ipdb_put(struct ppp_t *ppp, struct ipdb_item_t *it) +{ + if (it->owner->put) + it->owner->put(ppp, it); +} + +void __export ipdb_register(struct ipdb_t *ipdb) +{ + list_add_tail(&ipdb->entry, &ipdb_handlers); +} diff --git a/accel-pppd/ipdb.h b/accel-pppd/ipdb.h new file mode 100644 index 0000000..ebf3885 --- /dev/null +++ b/accel-pppd/ipdb.h @@ -0,0 +1,29 @@ +#ifndef IPDB_H +#define IPDB_H + +#include + +#include "ppp.h" +#include "list.h" + +struct ipdb_item_t +{ + struct ipdb_t *owner; + in_addr_t addr; + in_addr_t peer_addr; +}; + +struct ipdb_t +{ + struct list_head entry; + struct ipdb_item_t *(*get)(struct ppp_t *ppp); + void (*put)(struct ppp_t *ppp, struct ipdb_item_t *); +}; + +struct ipdb_item_t *ipdb_get(struct ppp_t *ppp); +void ipdb_put(struct ppp_t *ppp, struct ipdb_item_t *); + +void ipdb_register(struct ipdb_t *); + +#endif + diff --git a/accel-pppd/iprange.c b/accel-pppd/iprange.c new file mode 100644 index 0000000..411dcb7 --- /dev/null +++ b/accel-pppd/iprange.c @@ -0,0 +1,146 @@ +#include +#include +#include +#include +#include + +#include "triton.h" +#include "list.h" +#include "log.h" + +#include "iprange.h" + +#include "memdebug.h" + +struct iprange_t +{ + struct list_head entry; + uint32_t begin; + uint32_t end; +}; + +static int conf_disable = 0; + +static LIST_HEAD(client_ranges); +//static LIST_HEAD(tunnel_ranges); + +//parses ranges like x.x.x.x/mask +static struct iprange_t *parse1(const char *str) +{ + int n,f1,f2,f3,f4,m; + struct iprange_t *r; + int mask; + + n = sscanf(str, "%u.%u.%u.%u/%u",&f1, &f2, &f3, &f4, &m); + if (n != 5) + return NULL; + if (f1 > 255) + return NULL; + if (f2 > 255) + return NULL; + if (f3 > 255) + return NULL; + if (f4 > 255) + return NULL; + if (m == 0 || m > 32) + return NULL; + + r = _malloc(sizeof(*r)); + r->begin = (f4 << 24) | (f3 << 16) | (f2 << 8) | f1; + + mask = htonl(~((1 << (32 - m)) - 1)); + r->end = ntohl(r->begin | ~mask); + r->begin = ntohl(r->begin); + + return r; +} + +//parses ranges like x.x.x.x-y +static struct iprange_t *parse2(const char *str) +{ + int n,f1,f2,f3,f4,m; + struct iprange_t *r; + + n = sscanf(str, "%u.%u.%u.%u-%u",&f1, &f2, &f3, &f4, &m); + if (n != 5) + return NULL; + if (f1 > 255) + return NULL; + if (f2 > 255) + return NULL; + if (f3 > 255) + return NULL; + if (f4 > 255) + return NULL; + if (m < f4 || m > 255) + return NULL; + + r = _malloc(sizeof(*r)); + r->begin = ntohl((f4 << 24) | (f3 << 16) | (f2 << 8) | f1); + r->end = ntohl((m << 24) | (f3 << 16) | (f2 << 8) | f1); + + return r; +} + +static void load_ranges(struct list_head *list, const char *conf_sect) +{ + struct conf_sect_t *s = conf_get_section(conf_sect); + struct conf_option_t *opt; + struct iprange_t *r; + + if (!s) { + log_emerg("iprange: section '%s' not found in config file, pptp and l2tp probably will not work...\n", conf_sect); + return; + } + + list_for_each_entry(opt, &s->items, entry) { + if (!strcmp(opt->name, "disable")) { + conf_disable = 1; + log_emerg("iprange: iprange module disabled so improper ip address assigning may cause kernel soft lockup!\n"); + continue; + } + r = parse1(opt->name); + if (!r) + r = parse2(opt->name); + if (!r) { + log_emerg("iprange: cann't parse '%s' in '%s'\n", opt->name, conf_sect); + _exit(EXIT_FAILURE); + } + list_add_tail(&r->entry, list); + } +} + +static int check_range(struct list_head *list, in_addr_t ipaddr) +{ + struct iprange_t *r; + uint32_t a = ntohl(ipaddr); + + list_for_each_entry(r, list, entry) { + if (a >= r->begin && a <= r->end) + return 0; + } + + return -1; +} + +int __export iprange_client_check(in_addr_t ipaddr) +{ + if (conf_disable) + return 0; + + return check_range(&client_ranges, ipaddr); +} +int __export iprange_tunnel_check(in_addr_t ipaddr) +{ + if (conf_disable) + return 0; + + return !check_range(&client_ranges, ipaddr); +} + +static void __init iprange_init(void) +{ + load_ranges(&client_ranges, "client-ip-range"); + //load_ranges(&tunnel_ranges, "tunnel-ip-range"); +} + diff --git a/accel-pppd/iprange.h b/accel-pppd/iprange.h new file mode 100644 index 0000000..88a2486 --- /dev/null +++ b/accel-pppd/iprange.h @@ -0,0 +1,10 @@ +#ifndef __IPRANGE_H +#define __IPRANGE_H + +#include + +int iprange_client_check(in_addr_t ipaddr); +int iprange_tunnel_check(in_addr_t ipaddr); + +#endif + diff --git a/accel-pppd/log.c b/accel-pppd/log.c new file mode 100644 index 0000000..428fedd --- /dev/null +++ b/accel-pppd/log.c @@ -0,0 +1,501 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "triton/mempool.h" +#include "events.h" +#include "ppp.h" + +#include "log.h" + +#include "memdebug.h" + +struct log_pd_t +{ + struct ppp_pd_t pd; + struct ppp_t *ppp; + struct list_head msgs; + struct log_msg_t *msg; + int authorized:1; +}; + +struct _log_msg_t +{ + struct list_head entry; + int level; + struct timeval timestamp; + struct list_head chunks; + unsigned int refs; +}; + +static int log_level; + +static LIST_HEAD(targets); +static mempool_t msg_pool; +static mempool_t _msg_pool; +static mempool_t chunk_pool; + +static __thread struct ppp_t *cur_ppp; +static __thread struct _log_msg_t *cur_msg; +static __thread char *stat_buf; + +static FILE *emerg_file; +static FILE *debug_file; + +static void _log_free_msg(struct _log_msg_t *msg); +static struct log_msg_t *clone_msg(struct _log_msg_t *msg); +static int add_msg(struct _log_msg_t *msg, const char *buf); +//static struct log_pd_t *find_pd(struct ppp_t *ppp); +static void write_msg(FILE *f, struct _log_msg_t *msg, struct ppp_t *ppp); + +static void do_log(int level, const char *fmt, va_list ap, struct ppp_t *ppp) +{ + struct log_target_t *t; + struct log_msg_t *m; + + if (!stat_buf) + stat_buf = _malloc(LOG_MAX_SIZE + 1); + + vsnprintf(stat_buf, LOG_MAX_SIZE, fmt, ap); + + if (!cur_msg) { + cur_msg = mempool_alloc(_msg_pool); + if (!cur_msg) + return; + INIT_LIST_HEAD(&cur_msg->chunks); + cur_msg->refs = 1; + cur_msg->level = level; + gettimeofday(&cur_msg->timestamp, NULL); + } + + if (add_msg(cur_msg, stat_buf)) + goto out; + + if (stat_buf[strlen(stat_buf) - 1] != '\n') + return; + + if (debug_file) + write_msg(debug_file, cur_msg, ppp); + + list_for_each_entry(t, &targets, entry) { + m = clone_msg(cur_msg); + if (!m) + break; + t->log(t, m, ppp); + } + +out: + _log_free_msg(cur_msg); + cur_msg = NULL; +} + +void __export log_error(const char *fmt,...) +{ + if (log_level >= LOG_ERROR) { + va_list ap; + va_start(ap,fmt); + do_log(LOG_ERROR, fmt, ap, NULL); + va_end(ap); + } +} + +void __export log_warn(const char *fmt,...) +{ + if (log_level >= LOG_WARN) { + va_list ap; + va_start(ap,fmt); + do_log(LOG_WARN, fmt, ap, NULL); + va_end(ap); + } +} + +void __export log_info1(const char *fmt,...) +{ + if (log_level >= LOG_INFO1) { + va_list ap; + va_start(ap, fmt); + do_log(LOG_INFO1, fmt, ap, NULL); + va_end(ap); + } +} + +void __export log_info2(const char *fmt,...) +{ + if (log_level >= LOG_INFO2) { + va_list ap; + va_start(ap, fmt); + do_log(LOG_INFO2, fmt, ap, NULL); + va_end(ap); + } +} + +void __export log_debug(const char *fmt,...) +{ + if (log_level >= LOG_DEBUG) { + va_list ap; + va_start(ap, fmt); + do_log(LOG_DEBUG, fmt, ap, NULL); + va_end(ap); + } +} + +void __export log_debug2(const char *fmt,...) +{ + va_list ap; + va_start(ap, fmt); + vfprintf(debug_file, fmt, ap); + va_end(ap); + fflush(debug_file); +} +void __export log_msg(const char *fmt,...) +{ + va_list ap; + va_start(ap, fmt); + do_log(LOG_MSG, fmt, ap, NULL); + va_end(ap); +} + +void __export log_ppp_error(const char *fmt,...) +{ + if (log_level >= LOG_ERROR) { + va_list ap; + va_start(ap, fmt); + do_log(LOG_ERROR, fmt, ap, cur_ppp); + va_end(ap); + } +} + +void __export log_ppp_warn(const char *fmt,...) +{ + if (log_level >= LOG_WARN) { + va_list ap; + va_start(ap, fmt); + do_log(LOG_WARN, fmt, ap, cur_ppp); + va_end(ap); + } +} + +void __export log_ppp_info1(const char *fmt,...) +{ + if (log_level >= LOG_INFO1) { + va_list ap; + va_start(ap, fmt); + do_log(LOG_INFO1, fmt, ap, cur_ppp); + va_end(ap); + } +} + +void __export log_ppp_info2(const char *fmt,...) +{ + if (log_level >= LOG_INFO2) { + va_list ap; + va_start(ap, fmt); + do_log(LOG_INFO2, fmt, ap, cur_ppp); + va_end(ap); + } +} + +void __export log_ppp_debug(const char *fmt,...) +{ + if (log_level >= LOG_DEBUG) { + va_list ap; + va_start(ap, fmt); + do_log(LOG_DEBUG, fmt, ap, cur_ppp); + va_end(ap); + } +} + +void __export log_ppp_msg(const char *fmt,...) +{ + va_list ap; + va_start(ap, fmt); + do_log(LOG_MSG, fmt, ap, cur_ppp); + va_end(ap); +} + +void __export log_emerg(const char *fmt, ...) +{ + if (emerg_file) { + va_list ap; + va_start(ap, fmt); + vfprintf(emerg_file, fmt, ap); + va_end(ap); + fflush(emerg_file); + } +} + +void __export log_free_msg(struct log_msg_t *m) +{ + struct _log_msg_t *msg = (struct _log_msg_t *)m->lpd; + + //printf("free msg %p\n", m); + + mempool_free(m->hdr); + _log_free_msg(msg); + + mempool_free(m); +} + + +static void _log_free_msg(struct _log_msg_t *msg) +{ + struct log_chunk_t *chunk; + + if (__sync_sub_and_fetch(&msg->refs, 1)) + return; + + while(!list_empty(&msg->chunks)) { + chunk = list_entry(msg->chunks.next, typeof(*chunk), entry); + list_del(&chunk->entry); + mempool_free(chunk); + } + + mempool_free(msg); +} + +static struct log_msg_t *clone_msg(struct _log_msg_t *msg) +{ + struct log_msg_t *m = mempool_alloc(msg_pool); + if (!m) { + log_emerg("log: out of memory\n"); + return NULL; + } + + m->hdr = mempool_alloc(chunk_pool); + if (!m->hdr) { + log_emerg("log: out of memory\n"); + mempool_free(m); + return NULL; + } + + m->hdr->len = 0; + m->lpd = msg; + m->chunks = &msg->chunks; + m->timestamp = msg->timestamp; + m->level = msg->level; + + __sync_add_and_fetch(&msg->refs, 1); + + //printf("clone msg %p\n", m); + return m; +} + +static int add_msg(struct _log_msg_t *msg, const char *buf) +{ + struct log_chunk_t *chunk; + int i, len, chunk_cnt; + + len = strlen(buf); + chunk_cnt = (len - 1)/LOG_CHUNK_SIZE + 1; + + for (i = 0; i < chunk_cnt; i++) { + chunk = mempool_alloc(chunk_pool); + if (!chunk) + return -1; + + chunk->len = i == chunk_cnt -1 ? len - i * LOG_CHUNK_SIZE : LOG_CHUNK_SIZE; + memcpy(chunk->msg, buf + i * LOG_CHUNK_SIZE, chunk->len); + chunk->msg[chunk->len] = 0; + + list_add_tail(&chunk->entry, &msg->chunks); + } + + return 0; +} + +static void write_msg(FILE *f, struct _log_msg_t *msg, struct ppp_t *ppp) +{ + struct log_chunk_t *chunk; + + if (ppp) + sprintf(stat_buf,"%s: %s: ", ppp->ifname, ppp->sessionid); + else + stat_buf[0] = 0; + + list_for_each_entry(chunk, &msg->chunks, entry) + strcat(stat_buf, chunk->msg); + + fwrite(stat_buf, strlen(stat_buf), 1, f); + fflush(f); +} + +/*static struct log_pd_t *find_pd(struct ppp_t *ppp) +{ + struct ppp_pd_t *pd; + struct log_pd_t *lpd; + + list_for_each_entry(pd, &ppp->pd_list, entry) { + if (pd->key == &pd_key) { + lpd = container_of(pd, typeof(*lpd), pd); + return lpd; + } + } + log_emerg("log:BUG: pd not found\n"); + abort(); +} + +static void ev_ctrl_starting(struct ppp_t *ppp) +{ + struct log_pd_t *lpd = _malloc(sizeof(*lpd)); + if (!lpd) { + log_emerg("log: out of memory\n"); + return; + } + + memset(lpd, 0, sizeof(*lpd)); + lpd->pd.key = &pd_key; + lpd->ppp = ppp; + INIT_LIST_HEAD(&lpd->msgs); + list_add_tail(&lpd->pd.entry, &ppp->pd_list); +} + +static void ev_ctrl_finished(struct ppp_t *ppp) +{ + struct log_pd_t *lpd = find_pd(ppp); + struct _log_msg_t *msg; + struct log_msg_t *m; + struct log_target_t *t; + + if (lpd->msg) { + log_emerg("log:BUG: lpd->msg is not NULL\n"); + abort(); + } + + if (lpd->authorized) { + if (!list_empty(&lpd->msgs)) { + log_emerg("log:BUG: lpd->msgs is not empty\n"); + abort(); + } + list_for_each_entry(t, &targets, entry) + if (t->session_stop) + t->session_stop(ppp); + } + + while (!list_empty(&lpd->msgs)) { + msg = list_entry(lpd->msgs.next, typeof(*msg), entry); + list_del(&msg->entry); + + list_for_each_entry(t, &targets, entry) { + if (!t->log) + continue; + m = clone_msg(msg); + if (!m) + break; + t->log(m); + } + + _log_free_msg(msg); + } + + list_del(&lpd->pd.entry); + _free(lpd); +} + +static void ev_ppp_authorized(struct ppp_t *ppp) +{ + struct log_pd_t *lpd = find_pd(ppp); + struct _log_msg_t *msg; + struct log_msg_t *m; + struct log_target_t *t; + + list_for_each_entry(t, &targets, entry) + if (t->session_start) + t->session_start(ppp); + + while(!list_empty(&lpd->msgs)) { + msg = list_entry(lpd->msgs.next, typeof(*msg), entry); + list_del(&msg->entry); + + list_for_each_entry(t, &targets, entry) { + if (!t->session_log) + continue; + m = clone_msg(msg); + if (!m) + break; + t->session_log(lpd->ppp, m); + } + + _log_free_msg(msg); + } + + lpd->authorized = 1; +}*/ + +void __export log_switch(struct triton_context_t *ctx, void *arg) +{ + cur_ppp = (struct ppp_t *)arg; +} + + +void __export log_register_target(struct log_target_t *t) +{ + list_add_tail(&t->entry, &targets); +} + +static void sighup(int n) +{ + struct log_target_t *t; + + list_for_each_entry(t, &targets, entry) + if (t->reopen) + t->reopen(); +} + +static void load_config(void) +{ + char *opt; + + opt = conf_get_opt("log", "level"); + if (opt && atoi(opt) >= 0) + log_level = atoi(opt); + + opt = conf_get_opt("log", "log-emerg"); + if (opt) { + if (emerg_file) + emerg_file = freopen(opt, "a", emerg_file); + else + emerg_file = fopen(opt, "a"); + if (!emerg_file) + fprintf(stderr, "log:open: %s\n", strerror(errno)); + } else if (emerg_file) { + fclose(emerg_file); + emerg_file = NULL; + } + + opt = conf_get_opt("log", "log-debug"); + if (opt) { + if (debug_file) + debug_file = freopen(opt, "a", debug_file); + else + debug_file = fopen(opt, "a"); + if (!debug_file) + fprintf(stderr, "log:open: %s\n", strerror(errno)); + } else if (debug_file) { + fclose(debug_file); + debug_file = NULL; + } +} + +static void __init log_init(void) +{ + struct sigaction sa = { + .sa_handler = sighup, + }; + + msg_pool = mempool_create(sizeof(struct log_msg_t)); + _msg_pool = mempool_create(sizeof(struct _log_msg_t)); + chunk_pool = mempool_create(sizeof(struct log_chunk_t) + LOG_CHUNK_SIZE + 1); + + load_config(); + + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); + + sigaction(SIGHUP, &sa, NULL); +} + diff --git a/accel-pppd/log.h b/accel-pppd/log.h new file mode 100644 index 0000000..d87c42c --- /dev/null +++ b/accel-pppd/log.h @@ -0,0 +1,69 @@ +#ifndef __LOG_H +#define __LOG_H + +#include +#include +#include "list.h" + +#define LOG_MSG 0 +#define LOG_ERROR 1 +#define LOG_WARN 2 +#define LOG_INFO1 3 +#define LOG_INFO2 4 +#define LOG_DEBUG 5 + +#define LOG_CHUNK_SIZE 128 +#define LOG_MAX_SIZE 4096 + +struct ppp_t; +struct triton_context_t; + +struct log_msg_t +{ + struct list_head entry; + void *lpd; + void *tpd; + struct timeval timestamp; + int level; + struct log_chunk_t *hdr; + struct list_head *chunks; +}; + +struct log_chunk_t +{ + struct list_head entry; + int len; + char msg[0]; +}; + +struct log_target_t +{ + struct list_head entry; + + void (*log)(struct log_target_t *, struct log_msg_t *, struct ppp_t *ppp); + void (*reopen)(void); +}; + +void log_free_msg(struct log_msg_t *msg); + +void log_emerg(const char *fmt, ...); + +void log_error(const char *fmt,...); +void log_warn(const char *fmt,...); +void log_info1(const char *fmt,...); +void log_info2(const char *fmt,...); +void log_debug(const char *fmt,...); +void log_msg(const char *fmt,...); + +void log_ppp_error(const char *fmt,...); +void log_ppp_warn(const char *fmt,...); +void log_ppp_info1(const char *fmt,...); +void log_ppp_info2(const char *fmt,...); +void log_ppp_debug(const char *fmt,...); +void log_ppp_msg(const char *fmt,...); + +void log_switch(struct triton_context_t *ctx, void *arg); + +void log_register_target(struct log_target_t *t); + +#endif diff --git a/accel-pppd/logs/CMakeLists.txt b/accel-pppd/logs/CMakeLists.txt new file mode 100644 index 0000000..ce909b6 --- /dev/null +++ b/accel-pppd/logs/CMakeLists.txt @@ -0,0 +1,17 @@ +ADD_LIBRARY(log_file SHARED log_file.c) +TARGET_LINK_LIBRARIES(log_file rt) + +ADD_LIBRARY(log_tcp SHARED log_tcp.c) + +INSTALL(TARGETS log_file log_tcp + LIBRARY DESTINATION lib/accel-ppp +) + +IF(LOG_PGSQL) + ADD_LIBRARY(log_pgsql SHARED log_pgsql.c) + TARGET_LINK_LIBRARIES(log_pgsql pq) + INSTALL(TARGETS log_pgsql + LIBRARY DESTINATION lib/accel-ppp + ) +ENDIF(LOG_PGSQL) + diff --git a/accel-pppd/logs/log_file.c b/accel-pppd/logs/log_file.c new file mode 100644 index 0000000..e435757 --- /dev/null +++ b/accel-pppd/logs/log_file.c @@ -0,0 +1,614 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "log.h" +#include "events.h" +#include "ppp.h" +#include "spinlock.h" +#include "mempool.h" + +#include "memdebug.h" + +#define LOG_BUF_SIZE 16*1024 + +#define RED_COLOR "\033[1;31m" +#define GREEN_COLOR "\033[1;32m" +#define YELLOW_COLOR "\033[1;33m" +#define BLUE_COLOR "\033[1;34m" +#define NORMAL_COLOR "\033[0;39m" + +struct log_file_t +{ + struct list_head entry; + struct list_head msgs; + spinlock_t lock; + int need_free:1; + int queued:1; + struct log_file_pd_t *lpd; + + int fd; + int new_fd; + off_t offset; + unsigned long magic; +}; + +struct log_file_pd_t +{ + struct ppp_pd_t pd; + struct log_file_t lf; + unsigned long tmp; +}; + +static int conf_color; +static int conf_per_session; +static char *conf_per_user_dir; +static char *conf_per_session_dir; +static int conf_copy; + +static const char* level_name[]={" msg", "error", " warn", " info", " info", "debug"}; +static const char* level_color[]={NORMAL_COLOR, RED_COLOR, YELLOW_COLOR, GREEN_COLOR, GREEN_COLOR, BLUE_COLOR}; + +static void *pd_key1; +static void *pd_key2; +static struct log_file_t *log_file; + +static mempool_t lpd_pool; +static char *log_buf; + +static struct aiocb aiocb = { + .aio_lio_opcode = LIO_WRITE, + .aio_sigevent.sigev_notify = SIGEV_SIGNAL, + .aio_sigevent.sigev_signo = SIGIO, +}; + +static LIST_HEAD(lf_queue); +static spinlock_t lf_queue_lock = SPINLOCK_INITIALIZER; +static int lf_queue_sleeping = 1; + +static unsigned long temp_seq; + +static void send_next_chunk(); + + +static void log_file_init(struct log_file_t *lf) +{ + spinlock_init(&lf->lock); + INIT_LIST_HEAD(&lf->msgs); + lf->fd = -1; + lf->new_fd = -1; +} + +static int log_file_open(struct log_file_t *lf, const char *fname) +{ + lf->fd = open(fname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); + if (lf->fd < 0) { + log_emerg("log_file: open '%s': %s\n", fname, strerror(errno)); + return -1; + } + + lf->offset = lseek(lf->fd, 0, SEEK_END); + + return 0; +} + +static void sigio(int num, siginfo_t *si, void *uc) +{ + struct log_file_t *lf; + int n; + + if (si->si_signo != SIGIO) + return; + + if (si->si_code != SI_ASYNCIO) { + if (aio_write(&aiocb)) + log_emerg("log_file: aio_write: %s\n", strerror(errno)); + return; + } + + lf = (struct log_file_t *)si->si_ptr; + + n = aio_return(&aiocb); + if (n < 0) + log_emerg("log_file: %s\n", strerror(aio_error(&aiocb))); + else if (n != aiocb.aio_nbytes) + log_emerg("log_file: short write %p %i %lu\n", lf, n, aiocb.aio_nbytes); + + spin_lock(&lf->lock); + lf->offset += n; + if (list_empty(&lf->msgs)) { + if (lf->need_free) { + spin_unlock(&lf->lock); + close(lf->fd); + mempool_free(lf->lpd); + } else { + lf->queued = 0; + spin_unlock(&lf->lock); + } + } else { + spin_unlock(&lf->lock); + + spin_lock(&lf_queue_lock); + list_add_tail(&lf->entry, &lf_queue); + spin_unlock(&lf_queue_lock); + } + + send_next_chunk(); +} + +static int dequeue_log(struct log_file_t *lf) +{ + int n, pos = 0; + struct log_msg_t *msg; + struct log_chunk_t *chunk; + + while (1) { + spin_lock(&lf->lock); + if (list_empty(&lf->msgs)) { + spin_unlock(&lf->lock); + return pos; + } + msg = list_entry(lf->msgs.next, typeof(*msg), entry); + list_del(&msg->entry); + spin_unlock(&lf->lock); + + if (pos + msg->hdr->len > LOG_BUF_SIZE) + goto overrun; + memcpy(log_buf + pos, msg->hdr->msg, msg->hdr->len); + n = msg->hdr->len; + + list_for_each_entry(chunk, msg->chunks, entry) { + if (pos + n + chunk->len > LOG_BUF_SIZE) + goto overrun; + memcpy(log_buf + pos + n, chunk->msg, chunk->len); + n += chunk->len; + } + + log_free_msg(msg); + pos += n; + } + +overrun: + spin_lock(&lf->lock); + list_add(&msg->entry, &lf->msgs); + spin_unlock(&lf->lock); + + return pos; +} + +static void send_next_chunk(void) +{ + struct log_file_t *lf; + int n; + + spin_lock(&lf_queue_lock); + if (list_empty(&lf_queue)) { + lf_queue_sleeping = 1; + spin_unlock(&lf_queue_lock); + return; + } + lf = list_entry(lf_queue.next, typeof(*lf), entry); + + n = log_file->entry.next == NULL; + list_del(&lf->entry); + + spin_unlock(&lf_queue_lock); + + if (lf->new_fd != -1) { + close(lf->fd); + lf->fd = lf->new_fd; + lf->new_fd = -1; + lf->offset = 0; + } + + aiocb.aio_fildes = lf->fd; + aiocb.aio_offset = lf->offset; + aiocb.aio_sigevent.sigev_value.sival_ptr = lf; + aiocb.aio_nbytes = dequeue_log(lf); + + if (aio_write(&aiocb)) + log_emerg("log_file: aio_write: %s\n", strerror(errno)); +} + +static void queue_lf(struct log_file_t *lf) +{ + int r; + + spin_lock(&lf_queue_lock); + list_add_tail(&lf->entry, &lf_queue); + r = lf_queue_sleeping; + lf_queue_sleeping = 0; + spin_unlock(&lf_queue_lock); + + if (r) + send_next_chunk(); +} + +static void queue_log(struct log_file_t *lf, struct log_msg_t *msg) +{ + int r; + + spin_lock(&lf->lock); + list_add_tail(&msg->entry, &lf->msgs); + if (lf->fd != -1) { + r = lf->queued; + lf->queued = 1; + } else + r = 1; + spin_unlock(&lf->lock); + + if (!r) + queue_lf(lf); +} + +static void set_hdr(struct log_msg_t *msg, struct ppp_t *ppp) +{ + struct tm tm; + char timestamp[32]; + + localtime_r(&msg->timestamp.tv_sec, &tm); + + strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &tm); + sprintf(msg->hdr->msg, "%s[%s]: %s: %s%s%s", conf_color ? level_color[msg->level] : "", + timestamp, level_name[msg->level], + ppp ? ppp->ifname : "", + ppp ? ": " : "", + conf_color ? NORMAL_COLOR : ""); + msg->hdr->len = strlen(msg->hdr->msg); +} + +static void general_log(struct log_target_t *t, struct log_msg_t *msg, struct ppp_t *ppp) +{ + if (ppp && !conf_copy) { + log_free_msg(msg); + return; + } + + set_hdr(msg, ppp); + queue_log(log_file, msg); +} + +static struct log_file_pd_t *find_pd(struct ppp_t *ppp, void *pd_key) +{ + struct ppp_pd_t *pd; + struct log_file_pd_t *lpd; + + list_for_each_entry(pd, &ppp->pd_list, entry) { + if (pd->key == pd_key) { + lpd = container_of(pd, typeof(*lpd), pd); + return lpd; + } + } + return NULL; +} + +static void per_user_log(struct log_target_t *t, struct log_msg_t *msg, struct ppp_t *ppp) +{ + struct log_file_pd_t *lpd; + + if (!ppp) { + log_free_msg(msg); + return; + } + + lpd = find_pd(ppp, &pd_key1); + + if (!lpd) { + log_free_msg(msg); + return; + } + + set_hdr(msg, ppp); + queue_log(&lpd->lf, msg); +} + +static void per_session_log(struct log_target_t *t, struct log_msg_t *msg, struct ppp_t *ppp) +{ + struct log_file_pd_t *lpd; + + if (!ppp) { + log_free_msg(msg); + return; + } + + lpd = find_pd(ppp, &pd_key2); + + if (!lpd) { + log_free_msg(msg); + return; + } + + set_hdr(msg, ppp); + queue_log(&lpd->lf, msg); +} + +static void general_reopen(void) +{ + char *fname = conf_get_opt("log", "log-file"); + int fd = open(fname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); + if (fd < 0) { + log_emerg("log_file: open '%s': %s\n", fname, strerror(errno)); + return; + } + log_file->new_fd = fd; +} + +static void free_lpd(struct log_file_pd_t *lpd) +{ + struct log_msg_t *msg; + + spin_lock(&lpd->lf.lock); + list_del(&lpd->pd.entry); + lpd->lf.need_free = 1; + if (lpd->lf.queued) + spin_unlock(&lpd->lf.lock); + else { + while (!list_empty(&lpd->lf.msgs)) { + msg = list_entry(lpd->lf.msgs.next, typeof(*msg), entry); + list_del(&msg->entry); + log_free_msg(msg); + } + if (lpd->lf.fd != -1) + close(lpd->lf.fd); + spin_unlock(&lpd->lf.lock); + mempool_free(lpd); + } +} + +static void ev_ctrl_started(struct ppp_t *ppp) +{ + struct log_file_pd_t *lpd; + char *fname; + + if (conf_per_user_dir) { + lpd = mempool_alloc(lpd_pool); + if (!lpd) { + log_emerg("log_file: out of memory\n"); + return; + } + memset(lpd, 0, sizeof(*lpd)); + lpd->pd.key = &pd_key1; + log_file_init(&lpd->lf); + lpd->lf.lpd = lpd; + list_add_tail(&lpd->pd.entry, &ppp->pd_list); + } + + if (conf_per_session_dir) { + lpd = mempool_alloc(lpd_pool); + if (!lpd) { + log_emerg("log_file: out of memory\n"); + return; + } + memset(lpd, 0, sizeof(*lpd)); + lpd->pd.key = &pd_key2; + log_file_init(&lpd->lf); + lpd->lf.lpd = lpd; + + fname = _malloc(PATH_MAX); + if (!fname) { + mempool_free(lpd); + log_emerg("log_file: out of memory\n"); + return; + } + + lpd->tmp = temp_seq++; + strcpy(fname, conf_per_session_dir); + strcat(fname, "/tmp"); + sprintf(fname + strlen(fname), "%lu", lpd->tmp); + + if (log_file_open(&lpd->lf, fname)) { + mempool_free(lpd); + _free(fname); + return; + } + + _free(fname); + + list_add_tail(&lpd->pd.entry, &ppp->pd_list); + } +} + +static void ev_ctrl_finished(struct ppp_t *ppp) +{ + struct log_file_pd_t *lpd; + char *fname; + + lpd = find_pd(ppp, &pd_key1); + if (lpd) + free_lpd(lpd); + + + lpd = find_pd(ppp, &pd_key2); + if (lpd) { + if (lpd->tmp) { + fname = _malloc(PATH_MAX); + if (fname) { + strcpy(fname, conf_per_session_dir); + strcat(fname, "/tmp"); + sprintf(fname + strlen(fname), "%lu", lpd->tmp); + if (unlink(fname)) + log_emerg("log_file: unlink '%s': %s\n", fname, strerror(errno)); + _free(fname); + } else + log_emerg("log_file: out of memory\n"); + } + free_lpd(lpd); + } +} + +static void ev_ppp_starting(struct ppp_t *ppp) +{ + struct log_file_pd_t *lpd; + char *fname1, *fname2; + + lpd = find_pd(ppp, &pd_key2); + if (!lpd) + return; + + fname1 = _malloc(PATH_MAX); + if (!fname1) { + log_emerg("log_file: out of memory\n"); + return; + } + + fname2 = _malloc(PATH_MAX); + if (!fname2) { + log_emerg("log_file: out of memory\n"); + _free(fname1); + return; + } + + strcpy(fname1, conf_per_session_dir); + strcat(fname1, "/tmp"); + sprintf(fname1 + strlen(fname1), "%lu", lpd->tmp); + + strcpy(fname2, conf_per_session_dir); + strcat(fname2, "/"); + strcat(fname2, ppp->sessionid); + strcat(fname2, ".log"); + + if (rename(fname1, fname2)) + log_emerg("log_file: rename '%s' to '%s': %s\n", fname1, fname2, strerror(errno)); + + lpd->tmp = 0; + + _free(fname1); + _free(fname2); +} + +static void ev_ppp_authorized(struct ppp_t *ppp) +{ + struct log_file_pd_t *lpd; + char *fname; + + lpd = find_pd(ppp, &pd_key1); + if (!lpd) + return; + + fname = _malloc(PATH_MAX); + if (!fname) { + log_emerg("log_file: out of memory\n"); + return; + } + + strcpy(fname, conf_per_user_dir); + strcat(fname, "/"); + strcat(fname, ppp->username); + if (conf_per_session) { + if (mkdir(fname, S_IRWXU) && errno != EEXIST) { + log_emerg("log_file: mkdir '%s': %s'\n", fname, strerror(errno)); + goto out_err; + } + strcat(fname, "/"); + strcat(fname, ppp->sessionid); + } + strcat(fname, ".log"); + + if (log_file_open(&lpd->lf, fname)) + goto out_err; + + _free(fname); + + if (!list_empty(&lpd->lf.msgs)) { + lpd->lf.queued = 1; + queue_lf(&lpd->lf); + } + + return; + +out_err: + _free(fname); + list_del(&lpd->pd.entry); + free_lpd(lpd); +} + +static struct log_target_t general_target = +{ + .log = general_log, + .reopen = general_reopen, +}; + +static struct log_target_t per_user_target = +{ + .log = per_user_log, +}; + +static struct log_target_t per_session_target = +{ + .log = per_session_log, +}; + +static void __init init(void) +{ + char *opt; + + sigset_t set; + sigemptyset(&set); + sigaddset(&set, SIGIO); + + struct sigaction sa = { + .sa_sigaction = sigio, + .sa_flags = SA_SIGINFO, + .sa_mask = set, + }; + + lpd_pool = mempool_create(sizeof(struct log_file_pd_t)); + log_buf = malloc(LOG_BUF_SIZE); + aiocb.aio_buf = log_buf; + + if (sigaction(SIGIO, &sa, NULL)) { + log_emerg("log_file: sigaction: %s\n", strerror(errno)); + return; + } + + opt = conf_get_opt("log", "log-file"); + if (opt) { + log_file = malloc(sizeof(*log_file)); + memset(log_file, 0, sizeof(*log_file)); + log_file_init(log_file); + if (log_file_open(log_file, opt)) { + free(log_file); + _exit(EXIT_FAILURE); + } + } + + opt = conf_get_opt("log","color"); + if (opt && atoi(opt) > 0) + conf_color = 1; + + opt = conf_get_opt("log", "per-user-dir"); + if (opt) + conf_per_user_dir = _strdup(opt); + + opt = conf_get_opt("log", "per-session-dir"); + if (opt) + conf_per_session_dir = _strdup(opt); + + opt = conf_get_opt("log", "per-session"); + if (opt && atoi(opt) > 0) + conf_per_session = 1; + + opt = conf_get_opt("log", "copy"); + if (opt && atoi(opt) > 0) + conf_copy = 1; + + log_register_target(&general_target); + + if (conf_per_user_dir) + log_register_target(&per_user_target); + + if (conf_per_session_dir) + log_register_target(&per_session_target); + + triton_event_register_handler(EV_CTRL_STARTED, (triton_event_func)ev_ctrl_started); + triton_event_register_handler(EV_CTRL_FINISHED, (triton_event_func)ev_ctrl_finished); + triton_event_register_handler(EV_PPP_STARTING, (triton_event_func)ev_ppp_starting); + triton_event_register_handler(EV_PPP_AUTHORIZED, (triton_event_func)ev_ppp_authorized); +} diff --git a/accel-pppd/logs/log_pgsql.c b/accel-pppd/logs/log_pgsql.c new file mode 100644 index 0000000..af67e0b --- /dev/null +++ b/accel-pppd/logs/log_pgsql.c @@ -0,0 +1,321 @@ +#include +#include +#include + +#include + +#include "triton.h" +#include "spinlock.h" +#include "log.h" +#include "list.h" +#include "ppp.h" + +#include "memdebug.h" + +static char *conf_conninfo; +static int conf_queue_max = 1000; +static char *conf_query; +#define QUERY_TEMPLATE "insert into %s (timestamp, username, sessionid, msg) values ($1, $2, $3, $4)" + +static void start_connect(void); +static void start_connect_timer(struct triton_timer_t *); +static void pgsql_close(struct triton_context_t *ctx); + +static struct triton_context_t pgsql_ctx = { + .close = pgsql_close, + .before_switch = log_switch, +}; +static struct triton_md_handler_t pgsql_hnd; +static struct triton_timer_t connect_timer = { + .period = 5000, + .expire = start_connect_timer, +}; + +static PGconn *conn; + +static LIST_HEAD(msg_queue); +static int queue_size; +static int sleeping = 0; +static spinlock_t queue_lock = SPINLOCK_INITIALIZER; +static char *log_buf; +static int need_close; + +static void unpack_msg(struct log_msg_t *msg) +{ + struct log_chunk_t *chunk; + int pos = 0; + + list_for_each_entry(chunk, msg->chunks, entry) { + memcpy(log_buf + pos, chunk->msg, chunk->len); + pos += chunk->len; + } + if (pos > 1) + log_buf[pos - 1] = 0; + else + log_buf[0] = 0; +} + +static void set_hdr(struct log_msg_t *msg, struct ppp_t *ppp) +{ + struct tm tm; + + localtime_r(&msg->timestamp.tv_sec, &tm); + + strftime(msg->hdr->msg, LOG_CHUNK_SIZE, "%Y-%m-%d %H:%M:%S", &tm); + msg->hdr->len = strlen(msg->hdr->msg) + 1; + if (ppp && ppp->username) { + strcpy(msg->hdr->msg + msg->hdr->len, ppp->username); + msg->hdr->len += strlen(ppp->username) + 1; + strcpy(msg->hdr->msg + msg->hdr->len, ppp->sessionid); + msg->hdr->len += strlen(ppp->sessionid) + 1; + } else + memset(msg->hdr->msg + msg->hdr->len, 0, 2); + +} + +static void write_next_msg(void) +{ + struct log_msg_t *msg; + const char *paramValues[4]; + int paramFormats[4] = {0, 0, 0, 0}; + char *ptr1, *ptr2; + int r; + + spin_lock(&queue_lock); + if (list_empty(&msg_queue)) { + sleeping = 1; + spin_unlock(&queue_lock); + if (need_close) { + triton_md_unregister_handler(&pgsql_hnd); + PQfinish(conn); + conn = NULL; + triton_context_unregister(&pgsql_ctx); + } + return; + } + + msg = list_entry(msg_queue.next, typeof(*msg), entry); + list_del(&msg->entry); + --queue_size; + spin_unlock(&queue_lock); + + unpack_msg(msg); + + ptr1 = strchr(msg->hdr->msg, 0); + ptr2 = strchr(ptr1 + 1, 0); + + paramValues[1] = ptr1[1] ? ptr1 + 1 : NULL; + paramValues[2] = ptr2[1] ? ptr2 + 1 : NULL; + paramValues[0] = msg->hdr->msg; + paramValues[3] = log_buf; + + if (!PQsendQueryParams(conn, conf_query, 4, NULL, paramValues, NULL, paramFormats, 0)) + log_emerg("log_pgsql: %s\n", PQerrorMessage(conn)); + + log_free_msg(msg); + + r = PQflush(conn); + if (r == -1) + log_emerg("log_pgsql: %s\n", PQerrorMessage(conn)); + if (r == 0) + triton_md_enable_handler(&pgsql_hnd, MD_MODE_WRITE); +} + +static int pgsql_check_ready(struct triton_md_handler_t *h) +{ + PGresult *res; + + if (!PQconsumeInput(conn)) { + log_emerg("log_pgsql: %s\n", PQerrorMessage(conn)); + if (PQstatus(conn) == CONNECTION_BAD) { + PQfinish(conn); + start_connect(); + } + } + + if (PQisBusy(conn)) + return 0; + + while (1) { + res = PQgetResult(conn); + if (!res) + break; + if (PQresultStatus(res) != PGRES_COMMAND_OK) + log_emerg("log_pgsql: %s\n", PQerrorMessage(conn)); + PQclear(res); + } + + write_next_msg(); + + return 0; +} + +static int pgsql_flush(struct triton_md_handler_t *h) +{ + int r; + + r = PQflush(conn); + if (r == -1) + log_emerg("log_pgsql: %s\n", PQerrorMessage(conn)); + if (r == 1) + return 0; + + triton_md_disable_handler(&pgsql_hnd, MD_MODE_WRITE); + return 0; +} + +static void wakeup_log(void) +{ + write_next_msg(); +} + +static void queue_log(struct log_msg_t *msg) +{ + int r = 0, f = 0; + spin_lock(&queue_lock); + if (!conn) { + log_free_msg(msg); + spin_unlock(&queue_lock); + return; + } + if (queue_size < conf_queue_max) { + list_add_tail(&msg->entry, &msg_queue); + ++queue_size; + r = sleeping; + sleeping = 0; + } else + f = 1; + spin_unlock(&queue_lock); + + if (r) + triton_context_call(&pgsql_ctx, (void (*)(void*))wakeup_log, NULL); + else if (f) + log_free_msg(msg); +} + + +static void general_log(struct log_target_t *t, struct log_msg_t *msg, struct ppp_t *ppp) +{ + set_hdr(msg, ppp); + queue_log(msg); +} + +static int wait_connect(struct triton_md_handler_t *h) +{ + PostgresPollingStatusType status = PQconnectPoll(conn); + char *err_msg; + + switch(status) { + case PGRES_POLLING_READING: + triton_md_enable_handler(h, MD_MODE_READ); + triton_md_disable_handler(h, MD_MODE_WRITE); + break; + case PGRES_POLLING_WRITING: + triton_md_enable_handler(h, MD_MODE_WRITE); + triton_md_disable_handler(h, MD_MODE_READ); + break; + case PGRES_POLLING_FAILED: + err_msg = PQerrorMessage(conn); + log_emerg("log_pgsql: %s\n", err_msg); + triton_md_disable_handler(h, MD_MODE_READ | MD_MODE_WRITE); + PQfinish(conn); + h->read = NULL; + h->write = NULL; + if (!connect_timer.tpd) + triton_timer_add(&pgsql_ctx, &connect_timer, 0); + break; + case PGRES_POLLING_OK: + //triton_md_disable_handler(h, MD_MODE_READ | MD_MODE_WRITE); + PQsetnonblocking(conn, 1); + h->write = pgsql_flush; + h->read = pgsql_check_ready; + triton_md_enable_handler(&pgsql_hnd, MD_MODE_READ); + wakeup_log(); + break; + default: + break; + } + return 0; +} + +static void start_connect(void) +{ + conn = PQconnectStart(conf_conninfo); + if (!conn) { + log_emerg("log_pgsql: out of memory\n"); + return; + } + + if (PQstatus(conn) == CONNECTION_BAD) { + log_emerg("log_pgsql: PQconnectStart failed\n"); + } + + pgsql_hnd.fd = PQsocket(conn); + pgsql_hnd.read = wait_connect; + pgsql_hnd.write = wait_connect; + + wait_connect(&pgsql_hnd); +} + +static void start_connect_timer(struct triton_timer_t *t) +{ + triton_timer_del(t); + start_connect(); +} + +static void pgsql_close(struct triton_context_t *ctx) +{ + spin_lock(&queue_lock); + if (sleeping) { + triton_md_unregister_handler(&pgsql_hnd); + PQfinish(conn); + conn = NULL; + triton_context_unregister(&pgsql_ctx); + } else + need_close = 1; + spin_unlock(&queue_lock); +} + +static struct log_target_t target = { + .log = general_log, +}; + +static void __init init(void) +{ + char *opt; + + opt = conf_get_opt("log-pgsql", "conninfo"); + if (!opt) + return; + conf_conninfo = _strdup(opt); + + opt = conf_get_opt("log-pgsql", "connect-inteval"); + if (opt && atoi(opt) > 0) + connect_timer.period = atoi(opt) * 1000; + + opt = conf_get_opt("log-pgsql", "log-query"); + if (opt) + conf_query = _strdup(opt); + else { + opt = conf_get_opt("log-pgsql", "log-table"); + if (!opt || strlen(opt) > 32) + opt = "log"; + conf_query = _malloc(sizeof(QUERY_TEMPLATE) + strlen(opt)); + sprintf(conf_query, QUERY_TEMPLATE, opt); + } + + log_buf = _malloc(LOG_MAX_SIZE + 1); + if (!log_buf) { + log_emerg("log_pgsql: out of memory\n"); + return; + } + + triton_context_register(&pgsql_ctx, NULL); + triton_md_register_handler(&pgsql_ctx, &pgsql_hnd); + triton_md_set_trig(&pgsql_hnd, MD_TRIG_LEVEL); + triton_context_wakeup(&pgsql_ctx); + + start_connect(); + + log_register_target(&target); +} diff --git a/accel-pppd/logs/log_tcp.c b/accel-pppd/logs/log_tcp.c new file mode 100644 index 0000000..306c450 --- /dev/null +++ b/accel-pppd/logs/log_tcp.c @@ -0,0 +1,323 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "log.h" +#include "triton.h" +#include "events.h" +#include "ppp.h" +#include "spinlock.h" +#include "mempool.h" + +#include "memdebug.h" + +struct tcp_target_t +{ + struct log_target_t target; + struct list_head entry; + struct triton_md_handler_t hnd; + struct triton_timer_t conn_timer; + struct sockaddr_in addr; + char *buf; + int buf_size; + int buf_pos; + spinlock_t lock; + struct list_head queue; + int queue_len; + int connected:1; + int wait:1; +}; + +static int conf_connect_interval = 5; +static int conf_queue_len = 1000; + +static struct triton_context_t tcp_ctx; + +static const char* level_name[]={" msg", "error", " warn", " info", " info", "debug"}; + +static void start_connect(struct tcp_target_t *t); + +static LIST_HEAD(targets); + +static void disconnect(struct tcp_target_t *t) +{ + triton_md_unregister_handler(&t->hnd); + close(t->hnd.fd); + + start_connect(t); +} + +static void unpack_msg(struct tcp_target_t *t, struct log_msg_t *msg) +{ + struct log_chunk_t *chunk; + int pos = strlen(msg->hdr->msg); + + strcpy(t->buf, msg->hdr->msg); + + list_for_each_entry(chunk, msg->chunks, entry) { + memcpy(t->buf + pos, chunk->msg, chunk->len); + pos += chunk->len; + } + + t->buf_size = pos; + t->buf_pos = 0; +} + +static int send_log(struct tcp_target_t *t) +{ + struct log_msg_t *msg; + int n; + + while (1) { + spin_lock(&t->lock); + if (!t->queue_len) { + t->wait = 0; + spin_unlock(&t->lock); + return 0; + } + msg = list_entry(t->queue.next, typeof(*msg), entry); + list_del(&msg->entry); + t->queue_len--; + spin_unlock(&t->lock); + + unpack_msg(t, msg); + + log_free_msg(msg); + + while (t->buf_pos != t->buf_size) { + n = write(t->hnd.fd, t->buf + t->buf_pos, t->buf_size - t->buf_pos); + if (n < 0) { + if (errno == EAGAIN) + return 1; + if (errno != EPIPE) + log_emerg("log-tcp: write: %s\n", strerror(errno)); + disconnect(t); + return 0; + } + t->buf_pos += n; + } + } +} + +static void queue_log(struct tcp_target_t *t, struct log_msg_t *msg) +{ + int r; + + spin_lock(&t->lock); + if (t->queue_len == conf_queue_len) { + spin_unlock(&t->lock); + log_free_msg(msg); + return; + } + list_add_tail(&msg->entry, &t->queue); + t->queue_len++; + if (t->connected) { + r = t->wait; + t->wait = 1; + } else + r = 1; + spin_unlock(&t->lock); + + if (!r) { + if (send_log(t)) + triton_md_enable_handler(&t->hnd, MD_MODE_WRITE); + } +} + +static void set_hdr(struct log_msg_t *msg, struct ppp_t *ppp) +{ + struct tm tm; + char timestamp[32]; + + localtime_r(&msg->timestamp.tv_sec, &tm); + + strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &tm); + sprintf(msg->hdr->msg, "[%s]: %s: %s: ", timestamp, level_name[msg->level], ppp ? ppp->ifname : ""); + msg->hdr->len = strlen(msg->hdr->msg); +} + +static void general_log(struct log_target_t *lt, struct log_msg_t *msg, struct ppp_t *ppp) +{ + struct tcp_target_t *t = container_of(lt, typeof(*t), target); + + set_hdr(msg, ppp); + queue_log(t, msg); +} + +static int log_tcp_write(struct triton_md_handler_t *h) +{ + struct tcp_target_t *t = container_of(h, typeof(*t), hnd); + + if (!send_log(t)) + triton_md_disable_handler(h, MD_MODE_WRITE); + + return 0; +} + +static int log_tcp_connect(struct triton_md_handler_t *h) +{ + struct tcp_target_t *t = container_of(h, typeof(*t), hnd); + + if (connect(t->hnd.fd, &t->addr, sizeof(t->addr))) { + if (errno == EAGAIN) + return 0; + if (errno == EINPROGRESS) + return 0; + log_emerg("log-tcp: connect: %s\n", strerror(errno)); + triton_md_unregister_handler(&t->hnd); + close(t->hnd.fd); + triton_timer_add(&tcp_ctx, &t->conn_timer, 0); + return 0; + } + + t->hnd.write = log_tcp_write; + + triton_md_disable_handler(&t->hnd, MD_MODE_WRITE); + + spin_lock(&t->lock); + t->connected = 1; + t->wait = 1; + spin_unlock(&t->lock); + + if (send_log(t)) + triton_md_enable_handler(&t->hnd, MD_MODE_WRITE); + + return 0; +} + +static void connect_timer(struct triton_timer_t *timer) +{ + struct tcp_target_t *t = container_of(timer, typeof(*t), conn_timer); + + triton_timer_del(timer); + + start_connect(t); +} + +static void start_connect(struct tcp_target_t *t) +{ + t->hnd.write = log_tcp_connect; + t->hnd.fd = socket(PF_INET, SOCK_STREAM, 0); + + if (!t->hnd.fd) { + log_emerg("log-tcp: socket: %s\n", strerror(errno)); + return; + } + + if (fcntl(t->hnd.fd, F_SETFL, O_NONBLOCK)) { + log_emerg("log-tcp: failed to set nonblocking mode: %s\n", strerror(errno)); + close(t->hnd.fd); + return; + } + + if (connect(t->hnd.fd, &t->addr, sizeof(t->addr))) { + if (errno != EINPROGRESS) { + log_emerg("log-tcp: connect: %s\n", strerror(errno)); + close(t->hnd.fd); + return; + } + } + + triton_md_register_handler(&tcp_ctx, &t->hnd); + triton_md_enable_handler(&t->hnd, MD_MODE_WRITE); +} + +static void log_tcp_close(struct triton_context_t *ctx) +{ + struct tcp_target_t *t; + + while (!list_empty(&targets)) { + t = list_entry(targets.next, typeof(*t), entry); + list_del(&t->entry); + if (t->conn_timer.tpd) + triton_timer_del(&t->conn_timer); + else { + t->connected = 0; + triton_md_unregister_handler(&t->hnd); + close(t->hnd.fd); + } + } + + triton_context_unregister(&tcp_ctx); +} + +static int start_log(const char *_opt) +{ + struct tcp_target_t *t; + char *opt = strdup(_opt); + int port; + char *d; + + d = strchr(opt, ':'); + if (!d) + goto err; + + *d = 0; + + port = atoi(d + 1); + if (port <= 0) + goto err; + + t = _malloc(sizeof(*t)); + memset(t, 0, sizeof(*t)); + + t->buf = _malloc(LOG_MAX_SIZE + 64); + + t->conn_timer.expire_tv.tv_sec = conf_connect_interval; + t->conn_timer.expire = connect_timer; + + t->target.log = general_log; + + memset(&t->addr, 0, sizeof(t->addr)); + t->addr.sin_family = AF_INET; + t->addr.sin_port = htons(port); + t->addr.sin_addr.s_addr = inet_addr(opt); + + INIT_LIST_HEAD(&t->queue); + + spinlock_init(&t->lock); + + start_connect(t); + + log_register_target(&t->target); + + list_add_tail(&t->entry, &targets); + + return 0; + +err: + free(opt); + return -1; +} + +static struct triton_context_t tcp_ctx ={ + .close = log_tcp_close, + .before_switch = log_switch, +}; + +static void __init init(void) +{ + struct conf_sect_t *s = conf_get_section("log"); + struct conf_option_t *opt; + + if (!s) + return; + + triton_context_register(&tcp_ctx, NULL); + + list_for_each_entry(opt, &s->items, entry) { + if (strcmp(opt->name, "log-tcp")) + continue; + if (!opt->val || start_log(opt->val)) + log_emerg("log: log-tcp: invalid format: '%s'\n", opt->val); + } + + triton_context_wakeup(&tcp_ctx); +} + diff --git a/accel-pppd/main.c b/accel-pppd/main.c new file mode 100644 index 0000000..2e48c45 --- /dev/null +++ b/accel-pppd/main.c @@ -0,0 +1,201 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "triton/triton.h" + +#include "memdebug.h" +#include "log.h" +#include "events.h" + +static int goto_daemon; +static char *pid_file; +static char *conf_file; + +#define ARG_MAX 128 +static int parse_cmdline(char ***argv) +{ + FILE *f; + int i; + size_t len; + + f = fopen("/proc/self/cmdline", "r"); + if (!f) { + perror("open cmdline"); + _exit(EXIT_FAILURE); + } + + *argv = _malloc(ARG_MAX * sizeof(void *)); + memset(*argv, 0, ARG_MAX * sizeof(void *)); + + for(i = 0; i < ARG_MAX; i++) { + len = 0; + if (getdelim(&(*argv)[i], &len, 0, f) < 0) + break; + } + + fclose(f); + + return i; +} +static void __init __main(void) +{ + int i,argc; + char **argv; + + argc=parse_cmdline(&argv); + + if (argc < 2) + goto usage; + + for(i = 1; i < argc; i++) { + if (!strcmp(argv[i], "-d")) + goto_daemon = 1; + else if (!strcmp(argv[i], "-p")) { + if (i == argc - 1) + goto usage; + pid_file = argv[++i]; + } else if (!strcmp(argv[i], "-c")) { + if (i == argc - 1) + goto usage; + conf_file = argv[++i]; + } + } + + if (!conf_file) + goto usage; + + if (triton_init(conf_file)) + _exit(EXIT_FAILURE); + + return; + +usage: + printf("usage: accel-pppd [-d] [-p ] -c \n\ + where:\n\ + -d - daemon mode\n\ + -p - write pid to \n\ + -c - config file\n"); + _exit(EXIT_FAILURE); +} + +static void change_limits(void) +{ + FILE *f; + struct rlimit lim; + unsigned int file_max; + + f = fopen("/proc/sys/fs/file-max", "r"); + if (f) { + fscanf(f, "%d", &file_max); + fclose(f); + + lim.rlim_cur = file_max; + lim.rlim_max = file_max; + if (setrlimit(RLIMIT_NOFILE, &lim)) + log_emerg("main: setrlimit: %s\n", strerror(errno)); + } else + log_emerg("main: failed to open '/proc/sys/fs/file-max': %s\n", strerror(errno)); +} + +static void config_reload_notify(int r) +{ + if (!r) + triton_event_fire(EV_CONFIG_RELOAD, NULL); +} +static void config_reload(int num) +{ + triton_conf_reload(config_reload_notify); +} + +int main(int argc, char **argv) +{ + sigset_t set; + int sig; + + if (goto_daemon) { + /*pid_t pid = fork(); + if (pid > 0) + _exit(EXIT_SUCCESS); + if (pid < 0) { + perror("fork"); + return EXIT_FAILURE; + } + if (setsid() < 0) + _exit(EXIT_FAILURE); + pid = fork(); + if (pid) + _exit(0); + umask(0); + chdir("/"); + close(STDIN_FILENO); + close(STDOUT_FILENO); + close(STDERR_FILENO);*/ + daemon(0, 0); + } + + if (pid_file) { + FILE *f = fopen(pid_file, "w"); + if (f) { + fprintf(f, "%i", getpid()); + fclose(f); + } + } + + //signal(SIGTERM, sigterm); + //signal(SIGPIPE, sigterm); + + change_limits(); + + if (triton_load_modules("modules")) + return EXIT_FAILURE; + + log_msg("accel-ppp version %s\n", ACCEL_PPP_VERSION); + + triton_run(); + + sigfillset(&set); + + struct sigaction sa = { + .sa_handler = config_reload, + .sa_mask = set, + }; + + sigaction(SIGUSR1, &sa, NULL); + + sigdelset(&set, SIGKILL); + sigdelset(&set, SIGSTOP); + sigdelset(&set, SIGSEGV); + sigdelset(&set, SIGFPE); + sigdelset(&set, SIGILL); + sigdelset(&set, SIGBUS); + sigdelset(&set, SIGHUP); + sigdelset(&set, SIGIO); + sigdelset(&set, SIGINT); + sigdelset(&set, SIGUSR1); + sigdelset(&set, 35); + sigdelset(&set, 36); + pthread_sigmask(SIG_SETMASK, &set, NULL); + + sigemptyset(&set); + //sigaddset(&set, SIGINT); + sigaddset(&set, SIGTERM); + sigaddset(&set, SIGSEGV); + sigaddset(&set, SIGILL); + sigaddset(&set, SIGFPE); + sigaddset(&set, SIGBUS); + + sigwait(&set, &sig); + log_info1("terminate, sig = %i\n", sig); + + triton_terminate(); + + return EXIT_SUCCESS; +} + diff --git a/accel-pppd/memdebug.c b/accel-pppd/memdebug.c new file mode 100644 index 0000000..c33e34b --- /dev/null +++ b/accel-pppd/memdebug.c @@ -0,0 +1,184 @@ +#undef MEMDEBUG + +#include +#include +#include +#include +#include +#include + +#include "spinlock.h" +#include "list.h" + +#define __init __attribute__((constructor)) +#define __export __attribute__((visibility("default"))) + +#undef offsetof +#ifdef __compiler_offsetof +#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER) +#else +#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) +#endif + +#define container_of(ptr, type, member) ({ \ + const typeof( ((type *)0)->member ) *__mptr = (ptr); \ + (type *)( (char *)__mptr - offsetof(type,member) );}) + + +#define MAGIC1 0x1122334455667788llu + +struct mem_t +{ + struct list_head entry; + char fname[PATH_MAX]; + int line; + size_t size; + uint64_t magic2; + uint64_t magic1; + char data[0]; +}; + +static LIST_HEAD(mem_list); +static spinlock_t mem_list_lock = SPINLOCK_INITIALIZER; + +struct mem_t *_md_malloc(size_t size, const char *fname, int line) +{ + struct mem_t *mem = malloc(sizeof(*mem) + size + 8); + + if (size > 4096) + line = 0; + + strcpy(mem->fname, fname); + mem->line = line; + mem->size = size; + mem->magic1 = MAGIC1; + mem->magic2 = (uint64_t)random() * (uint64_t)random(); + *(uint64_t*)(mem->data + size) = mem->magic2; + + spin_lock(&mem_list_lock); + list_add_tail(&mem->entry, &mem_list); + spin_unlock(&mem_list_lock); + + return mem; +} + +void __export *md_malloc(size_t size, const char *fname, int line) +{ + struct mem_t *mem = _md_malloc(size, fname, line); + + return mem->data; +} + +void __export md_free(void *ptr, const char *fname, int line) +{ + struct mem_t *mem = container_of(ptr, typeof(*mem), data); + + if (!ptr) { + printf("free null pointer at %s:%i\n", fname, line); + abort(); + } + + if (mem->magic1 != MAGIC1) { + printf("memory corruption:\nfree at %s:%i\n", fname, line); + abort(); + } + + if (mem->magic2 != *(uint64_t*)(mem->data + mem->size)) { + printf("memory corruption:\nmalloc(%lu) at %s:%i\nfree at %s:%i\n", (long unsigned)mem->size, mem->fname, mem->line, fname, line); + abort(); + } + + mem->magic1 = 0; + mem->magic2 = 0; + + spin_lock(&mem_list_lock); + list_del(&mem->entry); + spin_unlock(&mem_list_lock); + + free(mem); + return; +} + +void __export *md_realloc(void *ptr, size_t size, const char *fname, int line) +{ + struct mem_t *mem = container_of(ptr, typeof(*mem), data); + struct mem_t *mem2; + + if (mem->magic1 != MAGIC1) { + printf("memory corruption:\nfree at %s:%i\n", fname, line); + abort(); + } + + if (mem->magic2 != *(uint64_t*)(mem->data + mem->size)) { + printf("memory corruption:\nmalloc(%lu) at %s:%i\nfree at %s:%i\n", (long unsigned)mem->size, mem->fname, mem->line, fname, line); + abort(); + } + + mem2 = _md_malloc(size, fname, line); + memcpy(mem2->data, mem->data, mem->size); + + md_free(mem->data, fname, line); + + return mem2->data; +} + +char __export *md_strdup(const char *ptr, const char *fname, int line) +{ + struct mem_t *mem = _md_malloc(strlen(ptr) + 1, fname, line); + memcpy(mem->data, ptr, strlen(ptr) + 1); + return mem->data; +} + +char __export *md_strndup(const char *ptr, size_t n, const char *fname, int line) +{ + struct mem_t *mem = _md_malloc(n + 1, fname, line); + memcpy(mem->data, ptr, n); + mem->data[n] = 0; + return mem->data; +} + +static void siginfo(int num) +{ + struct mem_t *mem; + size_t total = 0; + + spin_lock(&mem_list_lock); + list_for_each_entry(mem, &mem_list, entry) { + printf("%s:%i %lu\n", mem->fname, mem->line, (long unsigned)mem->size); + total += mem->size; + } + spin_unlock(&mem_list_lock); + printf("total = %lu\n", (long unsigned)total); +} + +static void siginfo2(int num) +{ + struct mem_t *mem; + + spin_lock(&mem_list_lock); + list_for_each_entry(mem, &mem_list, entry) { + if (mem->magic1 != MAGIC1 || mem->magic2 != *(uint64_t*)(mem->data + mem->size)) + printf("%s:%i %lu\n", mem->fname, mem->line, (long unsigned)mem->size); + } + spin_unlock(&mem_list_lock); +} + +void __export md_check(void *ptr) +{ + struct mem_t *mem = container_of(ptr, typeof(*mem), data); + + if (!ptr) + abort(); + + if (mem->magic1 != MAGIC1) + abort(); + + if (mem->magic2 != *(uint64_t*)(mem->data + mem->size)) + abort(); +} + +static void __init init(void) +{ + signal(36, siginfo); + signal(37, siginfo2); +} diff --git a/accel-pppd/memdebug.h b/accel-pppd/memdebug.h new file mode 100644 index 0000000..dc6b9ad --- /dev/null +++ b/accel-pppd/memdebug.h @@ -0,0 +1,28 @@ +#ifndef __MEMDEBUG_H +#define __MEMDEBUG_H + +#ifdef MEMDEBUG + +#include + +#define _malloc(size) md_malloc(size, __FILE__, __LINE__) +#define _realloc(ptr, size) md_realloc(ptr, size, __FILE__, __LINE__) +#define _free(ptr) md_free(ptr, __FILE__, __LINE__) +#define _strdup(str) md_strdup(str, __FILE__, __LINE__) +#define _strndup(str, size) md_strndup(str, size, __FILE__, __LINE__) + +void *md_malloc(size_t size, const char *fname, int line); +void *md_realloc(void *ptr, size_t size, const char *fname, int line); +void md_free(void *ptr, const char *fname, int line); +char* md_strdup(const char *ptr, const char *fname, int line); +char* md_strndup(const char *ptr, size_t size, const char *fname, int line); +void md_check(void *ptr); + +#else +#define _malloc(size) malloc(size) +#define _realloc(ptr, size) realloc(ptr, size) +#define _free(ptr) free(ptr) +#endif + +#endif + diff --git a/accel-pppd/ppp/CMakeLists.txt b/accel-pppd/ppp/CMakeLists.txt new file mode 100644 index 0000000..f4c0f04 --- /dev/null +++ b/accel-pppd/ppp/CMakeLists.txt @@ -0,0 +1,19 @@ +SET(target ppp) +SET(sources_c + ppp.c + ppp_fsm.c + ppp_lcp.c + lcp_opt_mru.c + lcp_opt_magic.c + lcp_opt_pcomp.c + lcp_opt_accomp.c + ppp_auth.c + ppp_ipcp.c + ipcp_opt_ipaddr.c + ipcp_opt_dns.c + ppp_ccp.c +) +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +ADD_LIBRARY(${target} SHARED ${sources_c}) + diff --git a/accel-pppd/ppp/ccp_mppe.c b/accel-pppd/ppp/ccp_mppe.c new file mode 100644 index 0000000..0952aa0 --- /dev/null +++ b/accel-pppd/ppp/ccp_mppe.c @@ -0,0 +1,259 @@ +#include +#include +#include +#include +#include +#include "linux_ppp.h" + +#include "ppp.h" +#include "ppp_ccp.h" +#include "log.h" +#include "events.h" + +#include "memdebug.h" + +#define MPPE_H (1 << 24) +#define MPPE_M (1 << 7) +#define MPPE_S (1 << 6) +#define MPPE_L (1 << 5) +#define MPPE_D (1 << 4) +#define MPPE_C (1 << 0) + +#define MPPE_PAD 4 + +static struct ccp_option_t *mppe_init(struct ppp_ccp_t *ccp); +static void mppe_free(struct ppp_ccp_t *ccp, struct ccp_option_t *opt); +static int mppe_send_conf_req(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr); +static int mppe_recv_conf_req(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr); +static int mppe_recv_conf_nak(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr); +static int mppe_recv_conf_rej(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr); +static void mppe_print(void (*print)(const char *fmt,...),struct ccp_option_t*, uint8_t *ptr); + +struct mppe_option_t +{ + struct ccp_option_t opt; + int mppe; + uint8_t recv_key[16]; + uint8_t send_key[16]; + int policy; // 1 - allowed, 2 - required +}; + +static struct ccp_option_handler_t mppe_opt_hnd = { + .init = mppe_init, + .send_conf_req = mppe_send_conf_req, + .send_conf_nak = mppe_send_conf_req, + .recv_conf_req = mppe_recv_conf_req, + .recv_conf_nak = mppe_recv_conf_nak, + .recv_conf_rej = mppe_recv_conf_rej, + .free = mppe_free, + .print = mppe_print, +}; + +static struct ccp_option_t *mppe_init(struct ppp_ccp_t *ccp) +{ + struct mppe_option_t *mppe_opt = _malloc(sizeof(*mppe_opt)); + memset(mppe_opt, 0, sizeof(*mppe_opt)); + mppe_opt->mppe = -1; + mppe_opt->opt.id = CI_MPPE; + mppe_opt->opt.len = 6; + + return &mppe_opt->opt; +} + +static void mppe_free(struct ppp_ccp_t *ccp, struct ccp_option_t *opt) +{ + struct mppe_option_t *mppe_opt = container_of(opt, typeof(*mppe_opt), opt); + + _free(mppe_opt); +} + +static int setup_mppe_key(int fd, int transmit, uint8_t *key) +{ + struct ppp_option_data data; + uint8_t buf[6 + 16]; + + memset(buf, 0, sizeof(buf)); + buf[0] = CI_MPPE; + buf[1] = 6; + *(uint32_t*)(buf + 2) = htonl(MPPE_S | MPPE_H); + if (key) + memcpy(buf + 6, key, 16); + + memset(&data, 0, sizeof(data)); + data.ptr = buf; + data.length = sizeof(buf); + data.transmit = transmit; + + if (ioctl(fd, PPPIOCSCOMPRESS, &data)) { + log_ppp_warn("mppe: MPPE requested but not supported by kernel\n"); + return -1; + } + + return 0; +} + +static int decrease_mtu(struct ppp_t *ppp) +{ + struct ifreq ifr; + + strcpy(ifr.ifr_name, ppp->ifname); + + if (ioctl(sock_fd, SIOCGIFMTU, &ifr)) { + log_ppp_error("mppe: failed to get MTU: %s\n", strerror(errno)); + return -1; + } + + ifr.ifr_mtu -= MPPE_PAD; + + if (ioctl(sock_fd, SIOCSIFMTU, &ifr)) { + log_ppp_error("mppe: failed to set MTU: %s\n", strerror(errno)); + return -1; + } + + return 0; +} + +static int mppe_send_conf_req(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr) +{ + struct mppe_option_t *mppe_opt = container_of(opt,typeof(*mppe_opt),opt); + struct ccp_opt32_t *opt32 = (struct ccp_opt32_t*)ptr; + + if (mppe_opt->mppe != -1) { + opt32->hdr.id = CI_MPPE; + opt32->hdr.len = 6; + opt32->val = mppe_opt->mppe ? htonl(MPPE_S | MPPE_H) : 0; + + if (mppe_opt->mppe && setup_mppe_key(ccp->ppp->unit_fd, 0, mppe_opt->recv_key)) + return 0; + + return 6; + } + return 0; +} + +static int mppe_recv_conf_req(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr) +{ + struct mppe_option_t *mppe_opt = container_of(opt, typeof(*mppe_opt), opt); + struct ccp_opt32_t *opt32 = (struct ccp_opt32_t *)ptr; + + /*if (!ptr) { + if (mppe_opt->policy == 2) + return CCP_OPT_NAK; + return CCP_OPT_ACK; + }*/ + + if (opt32->hdr.len != 6) + return CCP_OPT_REJ; + + if (mppe_opt->policy == 2) { + if (ntohl(opt32->val) != (MPPE_S | MPPE_H)) + return CCP_OPT_NAK; + } else if (mppe_opt->policy == 1) { + if (ntohl(opt32->val) == (MPPE_S | MPPE_H)) + mppe_opt->mppe = 1; + else if ((ntohl(opt32->val) & (MPPE_S | MPPE_H)) == (MPPE_S | MPPE_H)) { + mppe_opt->mppe = 1; + return CCP_OPT_NAK; + } else if (opt32->val) { + mppe_opt->mppe = 0; + return CCP_OPT_NAK; + } else + mppe_opt->mppe = 0; + } else + return CCP_OPT_REJ; + + if (mppe_opt->mppe) { + if (setup_mppe_key(ccp->ppp->unit_fd, 1, mppe_opt->send_key)) + return CCP_OPT_REJ; + + decrease_mtu(ccp->ppp); + + log_ppp_debug(" (mppe enabled)"); + } + + return CCP_OPT_ACK; +} + +static int mppe_recv_conf_rej(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr) +{ + struct mppe_option_t *mppe_opt = container_of(opt, typeof(*mppe_opt), opt); + + if (mppe_opt->mppe != 2) { + mppe_opt->mppe = -1; + return 0; + } + + return -1; +} + +static int mppe_recv_conf_nak(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr) +{ + struct mppe_option_t *mppe_opt = container_of(opt, typeof(*mppe_opt), opt); + struct ccp_opt32_t *opt32 = (struct ccp_opt32_t *)ptr; + + if (opt32->hdr.len != 6) + return -1; + + if (mppe_opt->policy == 2) { + if (ntohl(opt32->val) == (MPPE_S | MPPE_H)) + return -1; + } else if (mppe_opt->policy == 1) { + if ((ntohl(opt32->val) & (MPPE_S | MPPE_H)) == (MPPE_S | MPPE_H)) + mppe_opt->mppe = 0; + else + mppe_opt->mppe = 1; + } else { + if (opt32->val == 0) + return -1; + } + + return 0; +} + +static void mppe_print(void (*print)(const char *fmt,...),struct ccp_option_t *opt, uint8_t *ptr) +{ + struct mppe_option_t *mppe_opt = container_of(opt, typeof(*mppe_opt), opt); + struct ccp_opt32_t *opt32 = (struct ccp_opt32_t *)ptr; + uint32_t bits; + + if (ptr) + bits = ntohl(opt32->val); + else + if (mppe_opt->mppe) + bits = MPPE_S | MPPE_H; + else + bits = 0; + + print("", + bits & MPPE_H ? "+" : "-", + bits & MPPE_M ? "+" : "-", + bits & MPPE_S ? "+" : "-", + bits & MPPE_L ? "+" : "-", + bits & MPPE_D ? "+" : "-", + bits & MPPE_C ? "+" : "-" + ); +} + +static void ev_mppe_keys(struct ev_mppe_keys_t *ev) +{ + struct mppe_option_t *mppe_opt = container_of(ccp_find_option(ev->ppp, &mppe_opt_hnd), typeof(*mppe_opt), opt); + + if ((ev->type & 0x04) == 0) { + log_ppp_warn("mppe: 128-bit session keys not allowed, disabling mppe ...\n"); + return; + } + + memcpy(mppe_opt->recv_key, ev->recv_key, 16); + memcpy(mppe_opt->send_key, ev->send_key, 16); + mppe_opt->policy = ev->policy; + + if (ev->policy == 2) + mppe_opt->mppe = 1; +} + +static void __init mppe_opt_init() +{ + ccp_option_register(&mppe_opt_hnd); + triton_event_register_handler(EV_MPPE_KEYS, (triton_event_func)ev_mppe_keys); +} + diff --git a/accel-pppd/ppp/ipcp_opt_dns.c b/accel-pppd/ppp/ipcp_opt_dns.c new file mode 100644 index 0000000..c177092 --- /dev/null +++ b/accel-pppd/ppp/ipcp_opt_dns.c @@ -0,0 +1,155 @@ +#include +#include +#include + +#include "ppp.h" +#include "ppp_ipcp.h" +#include "log.h" +#include "ipdb.h" + +#include "memdebug.h" + +static in_addr_t conf_dns1; +static in_addr_t conf_dns2; + +static struct ipcp_option_t *dns1_init(struct ppp_ipcp_t *ipcp); +static struct ipcp_option_t *dns2_init(struct ppp_ipcp_t *ipcp); +static void dns_free(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt); +static int dns_send_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); +static int dns_send_conf_nak(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); +static int dns_recv_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); +static void dns1_print(void (*print)(const char *fmt,...),struct ipcp_option_t*, uint8_t *ptr); +static void dns2_print(void (*print)(const char *fmt,...),struct ipcp_option_t*, uint8_t *ptr); + +struct dns_option_t +{ + struct ipcp_option_t opt; + in_addr_t addr; +}; + +static struct ipcp_option_handler_t dns1_opt_hnd= +{ + .init=dns1_init, + .send_conf_req=dns_send_conf_req, + .send_conf_nak=dns_send_conf_nak, + .recv_conf_req=dns_recv_conf_req, + .free=dns_free, + .print=dns1_print, +}; +static struct ipcp_option_handler_t dns2_opt_hnd= +{ + .init=dns2_init, + .send_conf_req=dns_send_conf_req, + .send_conf_nak=dns_send_conf_nak, + .recv_conf_req=dns_recv_conf_req, + .free=dns_free, + .print=dns2_print, +}; + +static struct ipcp_option_t *dns1_init(struct ppp_ipcp_t *ipcp) +{ + struct dns_option_t *dns_opt=_malloc(sizeof(*dns_opt)); + memset(dns_opt,0,sizeof(*dns_opt)); + dns_opt->opt.id=CI_DNS1; + dns_opt->opt.len=6; + + return &dns_opt->opt; +} + +static struct ipcp_option_t *dns2_init(struct ppp_ipcp_t *ipcp) +{ + struct dns_option_t *dns_opt=_malloc(sizeof(*dns_opt)); + memset(dns_opt,0,sizeof(*dns_opt)); + dns_opt->opt.id=CI_DNS2; + dns_opt->opt.len=6; + + return &dns_opt->opt; +} + +static void dns_free(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt) +{ + struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); + + _free(dns_opt); +} + +static int dns_send_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) +{ + return 0; +} + +static int dns_send_conf_nak(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) +{ + struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); + struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; + opt32->hdr.id=dns_opt->opt.id; + opt32->hdr.len=6; + opt32->val=dns_opt->addr; + return 6; +} + +static int dns_recv_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) +{ + struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); + struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; + + if (opt32->hdr.len != 6) + return IPCP_OPT_REJ; + + if (!dns_opt->addr) + { + if (dns_opt->opt.id == CI_DNS1 && conf_dns1) dns_opt->addr=conf_dns1; + else if (dns_opt->opt.id == CI_DNS2 && conf_dns2) dns_opt->addr=conf_dns2; + + if (!dns_opt->addr) + { + dns_opt->addr=opt32->val; + return IPCP_OPT_ACK; + } + } + + if (dns_opt->addr==opt32->val) + return IPCP_OPT_ACK; + + return IPCP_OPT_NAK; +} + +static void dns1_print(void (*print)(const char *fmt,...),struct ipcp_option_t *opt, uint8_t *ptr) +{ + struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); + struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; + struct in_addr in; + + if (ptr) in.s_addr=opt32->val; + else in.s_addr=dns_opt->addr; + + print("",inet_ntoa(in)); +} + +static void dns2_print(void (*print)(const char *fmt,...),struct ipcp_option_t *opt, uint8_t *ptr) +{ + struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); + struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; + struct in_addr in; + + if (ptr) in.s_addr=opt32->val; + else in.s_addr=dns_opt->addr; + + print("",inet_ntoa(in)); +} + +static void __init dns_opt_init() +{ + char *opt; + + opt = conf_get_opt("dns", "dns1"); + if (opt) + conf_dns1 = inet_addr(opt); + + opt = conf_get_opt("dns", "dns2"); + if (opt) + conf_dns2 = inet_addr(opt); + + ipcp_option_register(&dns1_opt_hnd); + ipcp_option_register(&dns2_opt_hnd); +} diff --git a/accel-pppd/ppp/ipcp_opt_ipaddr.c b/accel-pppd/ppp/ipcp_opt_ipaddr.c new file mode 100644 index 0000000..334f425 --- /dev/null +++ b/accel-pppd/ppp/ipcp_opt_ipaddr.c @@ -0,0 +1,227 @@ +#include +#include +#include +#include +#include +#include +#include +#include "linux_ppp.h" + +#include "ppp.h" +#include "ppp_ipcp.h" +#include "log.h" +#include "ipdb.h" +#include "iprange.h" +#include "events.h" + +#include "memdebug.h" + +static int conf_check_exists; + +static struct ipcp_option_t *ipaddr_init(struct ppp_ipcp_t *ipcp); +static void ipaddr_free(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt); +static int ipaddr_send_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); +static int ipaddr_send_conf_nak(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); +static int ipaddr_recv_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); +//static int ipaddr_recv_conf_ack(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); +static void ipaddr_print(void (*print)(const char *fmt,...),struct ipcp_option_t*, uint8_t *ptr); + +struct ipaddr_option_t +{ + struct ipcp_option_t opt; + struct ipdb_item_t *ip; + int started:1; +}; + +static struct ipcp_option_handler_t ipaddr_opt_hnd= +{ + .init=ipaddr_init, + .send_conf_req=ipaddr_send_conf_req, + .send_conf_nak=ipaddr_send_conf_nak, + .recv_conf_req=ipaddr_recv_conf_req, + .free=ipaddr_free, + .print=ipaddr_print, +}; + +static struct ipcp_option_t *ipaddr_init(struct ppp_ipcp_t *ipcp) +{ + struct ipaddr_option_t *ipaddr_opt=_malloc(sizeof(*ipaddr_opt)); + memset(ipaddr_opt,0,sizeof(*ipaddr_opt)); + ipaddr_opt->opt.id=CI_ADDR; + ipaddr_opt->opt.len=6; + + return &ipaddr_opt->opt; +} + +static void ipaddr_free(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt) +{ + struct ipaddr_option_t *ipaddr_opt=container_of(opt,typeof(*ipaddr_opt),opt); + + if (ipaddr_opt->ip) + ipdb_put(ipcp->ppp, ipaddr_opt->ip); + + _free(ipaddr_opt); +} + +static int check_exists(struct ppp_t *self_ppp, in_addr_t addr) +{ + struct ppp_t *ppp; + int r = 0; + + pthread_rwlock_rdlock(&ppp_lock); + list_for_each_entry(ppp, &ppp_list, entry) { + if (!ppp->terminating && ppp->peer_ipaddr == addr && ppp != self_ppp) { + log_ppp_warn("ppp:ipcp: requested IP already assigned to %s\n", ppp->ifname); + r = 1; + break; + } + } + pthread_rwlock_unlock(&ppp_lock); + + return r; +} + +static int ipaddr_send_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) +{ + struct ipaddr_option_t *ipaddr_opt=container_of(opt,typeof(*ipaddr_opt),opt); + struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; + + if (!ipaddr_opt->ip) { + ipaddr_opt->ip = ipdb_get(ipcp->ppp); + if (!ipaddr_opt->ip) { + log_ppp_warn("ppp:ipcp: no free IP address\n"); + return -1; + } + } + + if (iprange_tunnel_check(ipaddr_opt->ip->peer_addr)) { + log_ppp_warn("ppp:ipcp: to avoid kernel soft lockup requested IP cannot be assigned (%i.%i.%i.%i)\n", + ipaddr_opt->ip->peer_addr&0xff, + (ipaddr_opt->ip->peer_addr >> 8)&0xff, + (ipaddr_opt->ip->peer_addr >> 16)&0xff, + (ipaddr_opt->ip->peer_addr >> 24)&0xff); + return -1; + } + + if (conf_check_exists && check_exists(ipcp->ppp, ipaddr_opt->ip->peer_addr)) + return -1; + + opt32->hdr.id=CI_ADDR; + opt32->hdr.len=6; + opt32->val=ipaddr_opt->ip->addr; + return 6; +} + +static int ipaddr_send_conf_nak(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) +{ + struct ipaddr_option_t *ipaddr_opt=container_of(opt,typeof(*ipaddr_opt),opt); + struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; + opt32->hdr.id=CI_ADDR; + opt32->hdr.len=6; + opt32->val=ipaddr_opt->ip->peer_addr; + return 6; +} + +static int ipaddr_recv_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) +{ + struct ipaddr_option_t *ipaddr_opt = container_of(opt,typeof(*ipaddr_opt), opt); + struct ipcp_opt32_t *opt32 = (struct ipcp_opt32_t*)ptr; + struct ifreq ifr; + struct sockaddr_in addr; + struct npioctl np; + + if (opt32->hdr.len != 6) + return IPCP_OPT_REJ; + + if (ipaddr_opt->ip->peer_addr == opt32->val) + goto ack; + + /*if (!ipaddr_opt->peer_addr) { + ipaddr_opt->peer_addr = opt32->val; + goto ack; + }*/ + + return IPCP_OPT_NAK; + +ack: + if (ipaddr_opt->started) + return IPCP_OPT_ACK; + + ipaddr_opt->started = 1; + + ipcp->ppp->ipaddr = ipaddr_opt->ip->addr; + ipcp->ppp->peer_ipaddr = ipaddr_opt->ip->peer_addr; + + triton_event_fire(EV_PPP_ACCT_START, ipcp->ppp); + if (ipcp->ppp->stop_time) + return IPCP_OPT_ACK; + + triton_event_fire(EV_PPP_PRE_UP, ipcp->ppp); + if (ipcp->ppp->stop_time) + return IPCP_OPT_ACK; + + memset(&ifr, 0, sizeof(ifr)); + memset(&addr, 0, sizeof(addr)); + + strcpy(ifr.ifr_name, ipcp->ppp->ifname); + + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = ipaddr_opt->ip->addr; + memcpy(&ifr.ifr_addr,&addr,sizeof(addr)); + + if (ioctl(sock_fd, SIOCSIFADDR, &ifr)) + log_ppp_error("ipcp: failed to set PA address: %s\n", strerror(errno)); + + addr.sin_addr.s_addr = ipaddr_opt->ip->peer_addr; + memcpy(&ifr.ifr_dstaddr,&addr,sizeof(addr)); + + if (ioctl(sock_fd, SIOCSIFDSTADDR, &ifr)) + log_ppp_error("ipcp: failed to set remote PA address: %s\n", strerror(errno)); + + if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr)) + log_ppp_error("ipcp: failed to get interface flags: %s\n", strerror(errno)); + + ifr.ifr_flags |= IFF_UP | IFF_POINTOPOINT; + + if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr)) + log_ppp_error("ipcp: failed to set interface flags: %s\n", strerror(errno)); + + np.protocol = PPP_IP; + np.mode = NPMODE_PASS; + + if (ioctl(ipcp->ppp->unit_fd, PPPIOCSNPMODE, &np)) + log_ppp_error("ipcp: failed to set NP mode: %s\n", strerror(errno)); + + return IPCP_OPT_ACK; +} + +static void ipaddr_print(void (*print)(const char *fmt,...),struct ipcp_option_t *opt, uint8_t *ptr) +{ + struct ipaddr_option_t *ipaddr_opt=container_of(opt,typeof(*ipaddr_opt),opt); + struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; + struct in_addr in = { .s_addr = 0, }; + + if (ptr) + in.s_addr = opt32->val; + else if (ipaddr_opt->ip) + in.s_addr = ipaddr_opt->ip->addr; + + print("",inet_ntoa(in)); +} + +static void load_config(void) +{ + const char *opt; + + opt = conf_get_opt("ppp", "check-ip"); + if (opt && atoi(opt) > 0) + conf_check_exists = 1; +} + +static void __init ipaddr_opt_init() +{ + ipcp_option_register(&ipaddr_opt_hnd); + load_config(); + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); +} + diff --git a/accel-pppd/ppp/lcp_opt_accomp.c b/accel-pppd/ppp/lcp_opt_accomp.c new file mode 100644 index 0000000..241b0e0 --- /dev/null +++ b/accel-pppd/ppp/lcp_opt_accomp.c @@ -0,0 +1,106 @@ +#include +#include +#include + +#include "ppp.h" +#include "ppp_lcp.h" +#include "log.h" + +#include "memdebug.h" + +static struct lcp_option_t *accomp_init(struct ppp_lcp_t *lcp); +static void accomp_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt); +static int accomp_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int accomp_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int accomp_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static void accomp_print(void (*print)(const char *fmt,...),struct lcp_option_t*, uint8_t *ptr); + +struct accomp_option_t +{ + struct lcp_option_t opt; + int accomp; // 0 - disabled, 1 - enabled, 2 - allow,disabled, 3 - allow,enabled + int require; +}; + +static struct lcp_option_handler_t accomp_opt_hnd= +{ + .init=accomp_init, + .send_conf_req=accomp_send_conf_req, + .send_conf_nak=accomp_send_conf_nak, + .recv_conf_req=accomp_recv_conf_req, + .free=accomp_free, + .print=accomp_print, +}; + +static struct lcp_option_t *accomp_init(struct ppp_lcp_t *lcp) +{ + struct accomp_option_t *accomp_opt=_malloc(sizeof(*accomp_opt)); + memset(accomp_opt,0,sizeof(*accomp_opt)); + accomp_opt->accomp=0; + accomp_opt->opt.id=CI_ACCOMP; + accomp_opt->opt.len=2; + + return &accomp_opt->opt; +} + +static void accomp_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt) +{ + struct accomp_option_t *accomp_opt=container_of(opt,typeof(*accomp_opt),opt); + + _free(accomp_opt); +} + +static int accomp_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct accomp_option_t *accomp_opt=container_of(opt,typeof(*accomp_opt),opt); + struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; + if (accomp_opt->accomp==1 || accomp_opt->accomp==3) + { + opt0->id=CI_ACCOMP; + opt0->len=2; + return 2; + } + return 0; +} + +static int accomp_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct accomp_option_t *accomp_opt=container_of(opt,typeof(*accomp_opt),opt); + struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; + opt0->id=CI_ACCOMP; + opt0->len=2; + return 2; +} + +static int accomp_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct accomp_option_t *accomp_opt=container_of(opt,typeof(*accomp_opt),opt); + struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; + + /*if (!ptr) { + if (accomp_opt->require) + return LCP_OPT_NAK; + accomp_opt->accomp=0; + return LCP_OPT_ACK; + }*/ + + if (opt0->len != 2) + return LCP_OPT_REJ; + + if (accomp_opt->accomp>0) + { + accomp_opt->accomp=1; + return LCP_OPT_ACK; + }else return LCP_OPT_REJ; +} + +static void accomp_print(void (*print)(const char *fmt,...),struct lcp_option_t *opt, uint8_t *ptr) +{ + print(""); +} + +static void __init accomp_opt_init() +{ + lcp_option_register(&accomp_opt_hnd); +} + diff --git a/accel-pppd/ppp/lcp_opt_magic.c b/accel-pppd/ppp/lcp_opt_magic.c new file mode 100644 index 0000000..4a61ef9 --- /dev/null +++ b/accel-pppd/ppp/lcp_opt_magic.c @@ -0,0 +1,91 @@ +#include +#include +#include + +#include "ppp.h" +#include "ppp_lcp.h" +#include "log.h" + +#include "memdebug.h" + +static struct lcp_option_t *magic_init(struct ppp_lcp_t *lcp); +static void magic_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt); +static int magic_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int magic_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static void magic_print(void (*print)(const char *fmt,...),struct lcp_option_t*, uint8_t *ptr); + +struct magic_option_t +{ + struct lcp_option_t opt; + int magic; +}; + +static struct lcp_option_handler_t magic_opt_hnd= +{ + .init=magic_init, + .send_conf_req=magic_send_conf_req, + .recv_conf_req=magic_recv_conf_req, + .free=magic_free, + .print=magic_print, +}; + +static struct lcp_option_t *magic_init(struct ppp_lcp_t *lcp) +{ + struct magic_option_t *magic_opt=_malloc(sizeof(*magic_opt)); + memset(magic_opt,0,sizeof(*magic_opt)); + magic_opt->magic=random(); + magic_opt->opt.id=CI_MAGIC; + magic_opt->opt.len=6; + + lcp->magic = magic_opt->magic; + + return &magic_opt->opt; +} + +static void magic_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt) +{ + struct magic_option_t *magic_opt=container_of(opt,typeof(*magic_opt),opt); + + _free(magic_opt); +} + +static int magic_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct magic_option_t *magic_opt=container_of(opt,typeof(*magic_opt),opt); + struct lcp_opt32_t *opt32=(struct lcp_opt32_t*)ptr; + opt32->hdr.id=CI_MAGIC; + opt32->hdr.len=6; + opt32->val=htonl(magic_opt->magic); + return 6; +} + +static int magic_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct magic_option_t *magic_opt=container_of(opt,typeof(*magic_opt),opt); + struct lcp_opt32_t *opt32=(struct lcp_opt32_t*)ptr; + + /*if (!ptr) + return LCP_OPT_NAK;*/ + + if (opt32->hdr.len != 6) + return LCP_OPT_REJ; + + if (magic_opt->magic==ntohl(opt32->val)) + { + log_ppp_error("loop detected"); + return -1; + } + return LCP_OPT_ACK; +} + +static void magic_print(void (*print)(const char *fmt,...),struct lcp_option_t *opt, uint8_t *ptr) +{ + struct magic_option_t *magic_opt=container_of(opt,typeof(*magic_opt),opt); + + print("",magic_opt->magic); +} + +static void __init magic_opt_init() +{ + lcp_option_register(&magic_opt_hnd); +} diff --git a/accel-pppd/ppp/lcp_opt_mru.c b/accel-pppd/ppp/lcp_opt_mru.c new file mode 100644 index 0000000..78e06b5 --- /dev/null +++ b/accel-pppd/ppp/lcp_opt_mru.c @@ -0,0 +1,195 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "linux_ppp.h" + +#include "ppp.h" +#include "ppp_lcp.h" +#include "log.h" +#include "events.h" + +#include "memdebug.h" + +static int conf_mtu; +static int conf_mru; +static int conf_min_mtu = 100; +static int conf_max_mtu = 1500; + +static struct lcp_option_t *mru_init(struct ppp_lcp_t *lcp); +static void mru_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt); +static int mru_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int mru_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int mru_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int mru_recv_conf_ack(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int mru_recv_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static void mru_print(void (*print)(const char *fmt,...),struct lcp_option_t*, uint8_t *ptr); + +struct mru_option_t +{ + struct lcp_option_t opt; + int mru; + int mtu; + int naked:1; +}; + +static struct lcp_option_handler_t mru_opt_hnd= +{ + .init=mru_init, + .send_conf_req=mru_send_conf_req, + .send_conf_nak=mru_send_conf_nak, + .recv_conf_req=mru_recv_conf_req, + .recv_conf_ack=mru_recv_conf_ack, + .recv_conf_nak=mru_recv_conf_nak, + .free=mru_free, + .print=mru_print, +}; + +static struct lcp_option_t *mru_init(struct ppp_lcp_t *lcp) +{ + struct mru_option_t *mru_opt=_malloc(sizeof(*mru_opt)); + memset(mru_opt, 0, sizeof(*mru_opt)); + mru_opt->mru = (conf_mru && conf_mru <= lcp->ppp->ctrl->max_mtu) ? conf_mru : lcp->ppp->ctrl->max_mtu; + if (mru_opt->mru > conf_max_mtu) + mru_opt->mru = conf_max_mtu; + mru_opt->mtu = (conf_mtu && conf_mtu <= lcp->ppp->ctrl->max_mtu) ? conf_mtu : lcp->ppp->ctrl->max_mtu; + if (mru_opt->mtu > conf_max_mtu) + mru_opt->mtu = conf_max_mtu; + mru_opt->opt.id = CI_MRU; + mru_opt->opt.len = 4; + + return &mru_opt->opt; +} + +static void mru_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt) +{ + struct mru_option_t *mru_opt = container_of(opt, typeof(*mru_opt), opt); + + _free(mru_opt); +} + +static int mru_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct mru_option_t *mru_opt = container_of(opt,typeof(*mru_opt),opt); + struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; + + if (mru_opt->naked) + return 0; + + opt16->hdr.id = CI_MRU; + opt16->hdr.len = 4; + opt16->val = htons(mru_opt->mru); + return 4; +} + +static int mru_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct mru_option_t *mru_opt = container_of(opt,typeof(*mru_opt),opt); + struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; + opt16->hdr.id = CI_MRU; + opt16->hdr.len = 4; + opt16->val = htons(mru_opt->mtu); + return 4; +} + +static int mru_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct mru_option_t *mru_opt = container_of(opt,typeof(*mru_opt),opt); + struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; + + /*if (!ptr) + return LCP_OPT_NAK;*/ + + if (opt16->hdr.len != 4) + return LCP_OPT_REJ; + + if (ntohs(opt16->val) < conf_min_mtu || ntohs(opt16->val) > lcp->ppp->ctrl->max_mtu || ntohs(opt16->val) > conf_max_mtu) + return LCP_OPT_NAK; + + mru_opt->mtu = ntohs(opt16->val); + return LCP_OPT_ACK; +} + +static int mru_recv_conf_ack(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct mru_option_t *mru_opt = container_of(opt,typeof(*mru_opt), opt); + struct ifreq ifr = { + .ifr_mtu = mru_opt->mtu, + }; + + strcpy(ifr.ifr_name, lcp->ppp->ifname); + + if (ioctl(lcp->ppp->unit_fd, PPPIOCSMRU, &mru_opt->mru)) + log_ppp_error("lcp:mru: failed to set MRU: %s\n", strerror(errno)); + + if (ioctl(sock_fd, SIOCSIFMTU, &ifr)) + log_ppp_error("lcp:mru: failed to set MTU: %s\n", strerror(errno)); + + return 0; +} + +static int mru_recv_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct mru_option_t *mru_opt = container_of(opt,typeof(*mru_opt), opt); + mru_opt->naked = 1; + return 0; +} + +static void mru_print(void (*print)(const char *fmt,...), struct lcp_option_t *opt, uint8_t *ptr) +{ + struct mru_option_t *mru_opt = container_of(opt, typeof(*mru_opt), opt); + struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; + + if (ptr) + print("",ntohs(opt16->val)); + else + print("",mru_opt->mru); +} + +static void load_config(void) +{ + char *opt; + + opt = conf_get_opt("ppp", "mtu"); + if (opt && atoi(opt) > 0) + conf_mtu = atoi(opt); + + opt = conf_get_opt("ppp", "mru"); + if (opt && atoi(opt) > 0) + conf_mru = atoi(opt); + + opt = conf_get_opt("ppp", "min-mtu"); + if (opt && atoi(opt) > 0) + conf_min_mtu = atoi(opt); + + opt = conf_get_opt("ppp", "max-mtu"); + if (opt && atoi(opt) > 0) + conf_max_mtu = atoi(opt); + + if (conf_min_mtu > conf_mru) { + log_emerg("min-mtu cann't be greater then mtu/mru\n"); + conf_min_mtu = conf_mru; + } + + if (conf_min_mtu > 1500) { + log_emerg("min-mtu cann't be greater then 1500\n"); + conf_min_mtu = 1500; + } + + if (conf_mru > 1500 || conf_mtu > 1500) { + log_emerg("mtu/mru cann't be greater then 1500\n"); + conf_mru = 1500; + } +} + +static void __init mru_opt_init() +{ + load_config(); + lcp_option_register(&mru_opt_hnd); + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); +} + diff --git a/accel-pppd/ppp/lcp_opt_pcomp.c b/accel-pppd/ppp/lcp_opt_pcomp.c new file mode 100644 index 0000000..1f8532b --- /dev/null +++ b/accel-pppd/ppp/lcp_opt_pcomp.c @@ -0,0 +1,106 @@ +#include +#include +#include + +#include "ppp.h" +#include "ppp_lcp.h" +#include "log.h" + +#include "memdebug.h" + +static struct lcp_option_t *pcomp_init(struct ppp_lcp_t *lcp); +static void pcomp_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt); +static int pcomp_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int pcomp_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int pcomp_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static void pcomp_print(void (*print)(const char *fmt,...),struct lcp_option_t*, uint8_t *ptr); + +struct pcomp_option_t +{ + struct lcp_option_t opt; + int pcomp; // 0 - disabled, 1 - enabled, 2 - allow,disabled, 3 - allow,enabled + int require; +}; + +static struct lcp_option_handler_t pcomp_opt_hnd= +{ + .init=pcomp_init, + .send_conf_req=pcomp_send_conf_req, + .send_conf_nak=pcomp_send_conf_nak, + .recv_conf_req=pcomp_recv_conf_req, + .free=pcomp_free, + .print=pcomp_print, +}; + +static struct lcp_option_t *pcomp_init(struct ppp_lcp_t *lcp) +{ + struct pcomp_option_t *pcomp_opt=_malloc(sizeof(*pcomp_opt)); + memset(pcomp_opt,0,sizeof(*pcomp_opt)); + pcomp_opt->pcomp=0; + pcomp_opt->opt.id=CI_PCOMP; + pcomp_opt->opt.len=2; + + return &pcomp_opt->opt; +} + +static void pcomp_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt) +{ + struct pcomp_option_t *pcomp_opt=container_of(opt,typeof(*pcomp_opt),opt); + + _free(pcomp_opt); +} + +static int pcomp_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct pcomp_option_t *pcomp_opt=container_of(opt,typeof(*pcomp_opt),opt); + struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; + if (pcomp_opt->pcomp==1 || pcomp_opt->pcomp==3) + { + opt0->id=CI_PCOMP; + opt0->len=2; + return 2; + } + return 0; +} + +static int pcomp_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct pcomp_option_t *pcomp_opt=container_of(opt,typeof(*pcomp_opt),opt); + struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; + opt0->id=CI_PCOMP; + opt0->len=2; + return 2; +} + +static int pcomp_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct pcomp_option_t *pcomp_opt=container_of(opt,typeof(*pcomp_opt),opt); + struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; + + /*if (!ptr) { + if (pcomp_opt->require) + return LCP_OPT_NAK; + pcomp_opt->pcomp=0; + return LCP_OPT_ACK; + }*/ + + if (opt0->len != 2) + return LCP_OPT_REJ; + + if (pcomp_opt->pcomp>0) + { + pcomp_opt->pcomp=1; + return LCP_OPT_ACK; + }else return LCP_OPT_REJ; +} + +static void pcomp_print(void (*print)(const char *fmt,...),struct lcp_option_t *opt, uint8_t *ptr) +{ + print(""); +} + +static void __init pcomp_opt_init() +{ + lcp_option_register(&pcomp_opt_hnd); +} + diff --git a/accel-pppd/ppp/ppp.c b/accel-pppd/ppp/ppp.c new file mode 100644 index 0000000..f578e8e --- /dev/null +++ b/accel-pppd/ppp/ppp.c @@ -0,0 +1,681 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "linux_ppp.h" + +#include + +#include "triton.h" + +#include "events.h" +#include "ppp.h" +#include "ppp_fsm.h" +#include "log.h" +#include "spinlock.h" + +#include "memdebug.h" + +int __export conf_ppp_verbose; +static int conf_sid_ucase; + +pthread_rwlock_t __export ppp_lock = PTHREAD_RWLOCK_INITIALIZER; +__export LIST_HEAD(ppp_list); + +static LIST_HEAD(layers); +int __export sock_fd; + +int __export ppp_shutdown; + +static unsigned long long seq; +#if __WORDSIZE == 32 +static spinlock_t seq_lock; +#endif + + +struct ppp_stat_t ppp_stat; + +struct layer_node_t +{ + struct list_head entry; + int order; + struct list_head items; +}; + +static int ppp_chan_read(struct triton_md_handler_t*); +static int ppp_unit_read(struct triton_md_handler_t*); +static void init_layers(struct ppp_t *); +static void _free_layers(struct ppp_t *); +static void start_first_layer(struct ppp_t *); + +void __export ppp_init(struct ppp_t *ppp) +{ + memset(ppp,0,sizeof(*ppp)); + INIT_LIST_HEAD(&ppp->layers); + INIT_LIST_HEAD(&ppp->chan_handlers); + INIT_LIST_HEAD(&ppp->unit_handlers); + INIT_LIST_HEAD(&ppp->pd_list); +} + +static void _free_ppp(struct ppp_t *ppp) +{ + if (ppp->chan_buf) + free(ppp->chan_buf); + if (ppp->unit_buf) + _free(ppp->unit_buf); + if (ppp->username) + _free(ppp->username); +} + +static void generate_sessionid(struct ppp_t *ppp) +{ + unsigned long long sid; + +#if __WORDSIZE == 32 + spin_lock(&seq_lock); + sid = ++seq; + spin_unlock(&seq_lock); +#else + sid = __sync_add_and_fetch(&seq, 1); +#endif + + if (conf_sid_ucase) + sprintf(ppp->sessionid, "%016llX", sid); + else + sprintf(ppp->sessionid, "%016llx", sid); +} + +int __export establish_ppp(struct ppp_t *ppp) +{ + /* Open an instance of /dev/ppp and connect the channel to it */ + if (ioctl(ppp->fd, PPPIOCGCHAN, &ppp->chan_idx) == -1) { + log_ppp_error("ioctl(PPPIOCGCHAN): %s\n", strerror(errno)); + return -1; + } + + ppp->chan_fd = open("/dev/ppp", O_RDWR); + if (ppp->chan_fd < 0) { + log_ppp_error("open(chan) /dev/ppp: %s\n", strerror(errno)); + return -1; + } + + if (ioctl(ppp->chan_fd, PPPIOCATTCHAN, &ppp->chan_idx) < 0) { + log_ppp_error("ioctl(PPPIOCATTCHAN): %s\n", strerror(errno)); + goto exit_close_chan; + } + + ppp->unit_fd = open("/dev/ppp", O_RDWR); + if (ppp->unit_fd < 0) { + log_ppp_error("open(unit) /dev/ppp: %s\n", strerror(errno)); + goto exit_close_chan; + } + + ppp->unit_idx = -1; + if (ioctl(ppp->unit_fd, PPPIOCNEWUNIT, &ppp->unit_idx) < 0) { + log_ppp_error("ioctl(PPPIOCNEWUNIT): %s\n", strerror(errno)); + goto exit_close_unit; + } + + if (ioctl(ppp->chan_fd, PPPIOCCONNECT, &ppp->unit_idx) < 0) { + log_ppp_error("ioctl(PPPIOCCONNECT): %s\n", strerror(errno)); + goto exit_close_unit; + } + + if (fcntl(ppp->chan_fd, F_SETFL, O_NONBLOCK)) { + log_ppp_error("ppp: cann't to set nonblocking mode: %s\n", strerror(errno)); + goto exit_close_unit; + } + + if (fcntl(ppp->unit_fd, F_SETFL, O_NONBLOCK)) { + log_ppp_error("ppp: cann't to set nonblocking mode: %s\n", strerror(errno)); + goto exit_close_unit; + } + + ppp->start_time = time(NULL); + generate_sessionid(ppp); + sprintf(ppp->ifname, "ppp%i", ppp->unit_idx); + + log_ppp_info1("connect: %s <--> %s(%s)\n", ppp->ifname, ppp->ctrl->name, ppp->chan_name); + + init_layers(ppp); + + if (list_empty(&ppp->layers)) { + log_ppp_error("no layers to start\n"); + goto exit_close_unit; + } + + ppp->chan_buf = _malloc(PPP_MRU); + ppp->unit_buf = _malloc(PPP_MRU); + + ppp->chan_hnd.fd = ppp->chan_fd; + ppp->chan_hnd.read = ppp_chan_read; + ppp->unit_hnd.fd = ppp->unit_fd; + ppp->unit_hnd.read = ppp_unit_read; + triton_md_register_handler(ppp->ctrl->ctx, &ppp->chan_hnd); + triton_md_register_handler(ppp->ctrl->ctx, &ppp->unit_hnd); + + triton_md_enable_handler(&ppp->chan_hnd, MD_MODE_READ); + triton_md_enable_handler(&ppp->unit_hnd, MD_MODE_READ); + + ppp->state = PPP_STATE_STARTING; + __sync_add_and_fetch(&ppp_stat.starting, 1); + + pthread_rwlock_wrlock(&ppp_lock); + list_add_tail(&ppp->entry, &ppp_list); + pthread_rwlock_unlock(&ppp_lock); + + log_ppp_debug("ppp established\n"); + + triton_event_fire(EV_PPP_STARTING, ppp); + + start_first_layer(ppp); + + return 0; + +exit_close_unit: + close(ppp->unit_fd); +exit_close_chan: + close(ppp->chan_fd); + + _free_ppp(ppp); + + return -1; +} + +static void destablish_ppp(struct ppp_t *ppp) +{ + pthread_rwlock_wrlock(&ppp_lock); + list_del(&ppp->entry); + pthread_rwlock_unlock(&ppp_lock); + + switch (ppp->state) { + case PPP_STATE_ACTIVE: + __sync_sub_and_fetch(&ppp_stat.active, 1); + break; + case PPP_STATE_STARTING: + __sync_sub_and_fetch(&ppp_stat.starting, 1); + break; + case PPP_STATE_FINISHING: + __sync_sub_and_fetch(&ppp_stat.finishing, 1); + break; + } + + triton_md_unregister_handler(&ppp->chan_hnd); + triton_md_unregister_handler(&ppp->unit_hnd); + + close(ppp->unit_fd); + close(ppp->chan_fd); + close(ppp->fd); + + ppp->unit_fd = -1; + ppp->chan_fd = -1; + ppp->fd = -1; + + _free(ppp->unit_buf); + _free(ppp->chan_buf); + + _free_layers(ppp); + + ppp->terminated = 1; + + log_ppp_debug("ppp destablished\n"); + + triton_event_fire(EV_PPP_FINISHED, ppp); + ppp->ctrl->finished(ppp); + + if (ppp->username) { + _free(ppp->username); + ppp->username = NULL; + } + + if (ppp_shutdown && !ppp_stat.starting && !ppp_stat.active && !ppp_stat.finishing) + kill(getpid(), SIGTERM); +} + +/*void print_buf(uint8_t *buf, int size) +{ + int i; + for(i=0;ichan_fd,data,size); + if (n < size) + log_ppp_error("ppp_chan_send: short write %i, excpected %i\n", n, size); + return n; +} + +int __export ppp_unit_send(struct ppp_t *ppp, void *data, int size) +{ + int n; + + //printf("ppp_unit_send: "); + //print_buf((uint8_t*)data,size); + + n=write(ppp->unit_fd, data, size); + if (n < size) + log_ppp_error("ppp_unit_send: short write %i, excpected %i\n",n,size); + return n; +} + +static int ppp_chan_read(struct triton_md_handler_t *h) +{ + struct ppp_t *ppp = container_of(h, typeof(*ppp), chan_hnd); + struct ppp_handler_t *ppp_h; + uint16_t proto; + + while(1) { +cont: + ppp->chan_buf_size = read(h->fd, ppp->chan_buf, PPP_MRU); + if (ppp->chan_buf_size < 0) { + if (errno == EAGAIN) + return 0; + log_ppp_error("ppp_chan_read: %s\n", strerror(errno)); + return 0; + } + + //printf("ppp_chan_read: "); + //print_buf(ppp->chan_buf,ppp->chan_buf_size); + if (ppp->chan_buf_size == 0) { + ppp_terminate(ppp, 1, TERM_NAS_ERROR); + return 1; + } + + if (ppp->chan_buf_size < 2) { + log_ppp_error("ppp_chan_read: short read %i\n", ppp->chan_buf_size); + continue; + } + + proto = ntohs(*(uint16_t*)ppp->chan_buf); + list_for_each_entry(ppp_h, &ppp->chan_handlers, entry) { + if (ppp_h->proto == proto) { + ppp_h->recv(ppp_h); + if (ppp->chan_fd == -1) { + ppp->ctrl->finished(ppp); + return 1; + } + goto cont; + } + } + + lcp_send_proto_rej(ppp, proto); + //log_ppp_warn("ppp_chan_read: discarding unknown packet %x\n", proto); + } +} + +static int ppp_unit_read(struct triton_md_handler_t *h) +{ + struct ppp_t *ppp = container_of(h, typeof(*ppp), unit_hnd); + struct ppp_handler_t *ppp_h; + uint16_t proto; + + while (1) { +cont: + ppp->unit_buf_size = read(h->fd, ppp->unit_buf, PPP_MRU); + if (ppp->unit_buf_size < 0) { + if (errno == EAGAIN) + return 0; + log_ppp_error("ppp_unit_read: %s\n",strerror(errno)); + return 0; + } + + md_check(ppp->unit_buf); + //printf("ppp_unit_read: "); + //print_buf(ppp->unit_buf,ppp->unit_buf_size); + + if (ppp->unit_buf_size == 0) { + ppp_terminate(ppp, 1, TERM_NAS_ERROR); + return 1; + } + + if (ppp->unit_buf_size < 2) { + log_ppp_error("ppp_unit_read: short read %i\n", ppp->unit_buf_size); + continue; + } + + proto=ntohs(*(uint16_t*)ppp->unit_buf); + list_for_each_entry(ppp_h, &ppp->unit_handlers, entry) { + if (ppp_h->proto == proto) { + ppp_h->recv(ppp_h); + if (ppp->unit_fd == -1) { + ppp->ctrl->finished(ppp); + return 1; + } + goto cont; + } + } + lcp_send_proto_rej(ppp, proto); + //log_ppp_warn("ppp_unit_read: discarding unknown packet %x\n", proto); + } +} + +void ppp_recv_proto_rej(struct ppp_t *ppp, uint16_t proto) +{ + struct ppp_handler_t *ppp_h; + + list_for_each_entry(ppp_h, &ppp->chan_handlers, entry) { + if (ppp_h->proto == proto) { + if (ppp_h->recv_proto_rej) + ppp_h->recv_proto_rej(ppp_h); + return; + } + } + + list_for_each_entry(ppp_h, &ppp->unit_handlers, entry) { + if (ppp_h->proto == proto) { + if (ppp_h->recv_proto_rej) + ppp_h->recv_proto_rej(ppp_h); + return; + } + } +} + +void __export ppp_layer_started(struct ppp_t *ppp, struct ppp_layer_data_t *d) +{ + struct layer_node_t *n = d->node; + + if (d->started) + return; + + d->started = 1; + + list_for_each_entry(d, &n->items, entry) + if (!d->started) return; + + if (n->entry.next == &ppp->layers) { + ppp->state = PPP_STATE_ACTIVE; + __sync_sub_and_fetch(&ppp_stat.starting, 1); + __sync_add_and_fetch(&ppp_stat.active, 1); + ppp->ctrl->started(ppp); + triton_event_fire(EV_PPP_STARTED, ppp); + } else { + n = list_entry(n->entry.next, typeof(*n), entry); + list_for_each_entry(d, &n->items, entry) { + d->starting = 1; + if (d->layer->start(d)) { + ppp_terminate(ppp, TERM_NAS_ERROR, 0); + return; + } + } + } +} + +void __export ppp_layer_finished(struct ppp_t *ppp, struct ppp_layer_data_t *d) +{ + struct layer_node_t *n = d->node; + + d->finished = 1; + d->starting = 0; + + list_for_each_entry(n, &ppp->layers, entry) { + list_for_each_entry(d, &n->items, entry) { + if (d->starting && !d->finished) + return; + } + } + + destablish_ppp(ppp); +} + +void __export ppp_terminate(struct ppp_t *ppp, int cause, int hard) +{ + struct layer_node_t *n; + struct ppp_layer_data_t *d; + int s = 0; + + if (ppp->terminated) + return; + + if (!ppp->stop_time) + time(&ppp->stop_time); + + if (!ppp->terminate_cause) + ppp->terminate_cause = cause; + + if (ppp->terminating) { + if (hard) + destablish_ppp(ppp); + return; + } + + ppp->terminating = 1; + if (ppp->state == PPP_STATE_ACTIVE) + __sync_sub_and_fetch(&ppp_stat.active, 1); + else + __sync_sub_and_fetch(&ppp_stat.starting, 1); + __sync_add_and_fetch(&ppp_stat.finishing, 1); + ppp->state = PPP_STATE_FINISHING; + + log_ppp_debug("ppp_terminate\n"); + + triton_event_fire(EV_PPP_FINISHING, ppp); + + if (hard) { + destablish_ppp(ppp); + return; + } + + list_for_each_entry(n,&ppp->layers,entry) { + list_for_each_entry(d,&n->items,entry) { + if (d->starting) { + s = 1; + d->layer->finish(d); + } + } + } + if (s) + return; + destablish_ppp(ppp); +} + +void __export ppp_register_chan_handler(struct ppp_t *ppp,struct ppp_handler_t *h) +{ + list_add_tail(&h->entry,&ppp->chan_handlers); +} +void __export ppp_register_unit_handler(struct ppp_t *ppp,struct ppp_handler_t *h) +{ + list_add_tail(&h->entry,&ppp->unit_handlers); +} +void __export ppp_unregister_handler(struct ppp_t *ppp,struct ppp_handler_t *h) +{ + list_del(&h->entry); +} + +static int get_layer_order(const char *name) +{ + if (!strcmp(name,"lcp")) return 0; + if (!strcmp(name,"auth")) return 1; + if (!strcmp(name,"ccp")) return 2; + if (!strcmp(name,"ipcp")) return 2; + return -1; +} + +int __export ppp_register_layer(const char *name, struct ppp_layer_t *layer) +{ + int order; + struct layer_node_t *n,*n1; + + order = get_layer_order(name); + + if (order < 0) + return order; + + list_for_each_entry(n, &layers, entry) { + if (order > n->order) + continue; + if (order < n->order) { + n1 = _malloc(sizeof(*n1)); + memset(n1, 0, sizeof(*n1)); + n1->order = order; + INIT_LIST_HEAD(&n1->items); + list_add_tail(&n1->entry, &n->entry); + n = n1; + } + goto insert; + } + n1 = _malloc(sizeof(*n1)); + memset(n1, 0, sizeof(*n1)); + n1->order = order; + INIT_LIST_HEAD(&n1->items); + list_add_tail(&n1->entry, &layers); + n = n1; +insert: + list_add_tail(&layer->entry, &n->items); + + return 0; +} +void __export ppp_unregister_layer(struct ppp_layer_t *layer) +{ + list_del(&layer->entry); +} + +static void init_layers(struct ppp_t *ppp) +{ + struct layer_node_t *n, *n1; + struct ppp_layer_t *l; + struct ppp_layer_data_t *d; + + list_for_each_entry(n,&layers,entry) { + n1 = _malloc(sizeof(*n1)); + memset(n1, 0, sizeof(*n1)); + INIT_LIST_HEAD(&n1->items); + list_add_tail(&n1->entry, &ppp->layers); + list_for_each_entry(l, &n->items, entry) { + d = l->init(ppp); + d->layer = l; + d->started = 0; + d->node = n1; + list_add_tail(&d->entry, &n1->items); + } + } +} + +static void _free_layers(struct ppp_t *ppp) +{ + struct layer_node_t *n; + struct ppp_layer_data_t *d; + + while (!list_empty(&ppp->layers)) { + n = list_entry(ppp->layers.next, typeof(*n), entry); + while (!list_empty(&n->items)) { + d = list_entry(n->items.next, typeof(*d), entry); + list_del(&d->entry); + d->layer->free(d); + } + list_del(&n->entry); + _free(n); + } +} + +static void start_first_layer(struct ppp_t *ppp) +{ + struct layer_node_t *n; + struct ppp_layer_data_t *d; + + n = list_entry(ppp->layers.next, typeof(*n), entry); + list_for_each_entry(d, &n->items, entry) { + d->starting = 1; + if (d->layer->start(d)) { + ppp_terminate(ppp, TERM_NAS_ERROR, 0); + return; + } + } +} + +struct ppp_layer_data_t *ppp_find_layer_data(struct ppp_t *ppp, struct ppp_layer_t *layer) +{ + struct layer_node_t *n; + struct ppp_layer_data_t *d; + + list_for_each_entry(n,&ppp->layers,entry) { + list_for_each_entry(d,&n->items,entry) { + if (d->layer == layer) + return d; + } + } + + return NULL; +} + +void ppp_shutdown_soft(void) +{ + ppp_shutdown = 1; + + if (!ppp_stat.starting && !ppp_stat.active && !ppp_stat.finishing) + kill(getpid(), SIGTERM); +} + +static void save_seq(void) +{ + FILE *f; + char *opt = conf_get_opt("ppp", "seq-file"); + if (!opt) + opt = "/var/run/accel-ppp/seq"; + + f = fopen(opt, "w"); + if (f) { + fprintf(f, "%llu", seq); + fclose(f); + } +} + +static void load_config(void) +{ + char *opt; + + opt = conf_get_opt("ppp", "verbose"); + if (opt && atoi(opt) > 0) + conf_ppp_verbose = 1; + + opt = conf_get_opt("ppp", "sid-case"); + if (opt) { + if (!strcmp(opt, "upper")) + conf_sid_ucase = 1; + else if (strcmp(opt, "lower")) + log_emerg("ppp: sid-case: invalid format\n"); + } +} + +static void __init init(void) +{ + char *opt; + FILE *f; + + sock_fd = socket(AF_INET, SOCK_DGRAM, 0); + if (sock_fd < 0) { + perror("socket"); + _exit(EXIT_FAILURE); + } + + opt = conf_get_opt("ppp", "seq-file"); + if (!opt) + opt = "/var/run/accel-ppp/seq"; + + f = fopen(opt, "r"); + if (f) { + fscanf(f, "%llu", &seq); + fclose(f); + } else + seq = (unsigned long long)random() * (unsigned long long)random(); + + load_config(); + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); + + atexit(save_seq); +} + diff --git a/accel-pppd/ppp/ppp.h b/accel-pppd/ppp/ppp.h new file mode 100644 index 0000000..c633135 --- /dev/null +++ b/accel-pppd/ppp/ppp.h @@ -0,0 +1,189 @@ +#ifndef PPP_H +#define PPP_H + +#include +#include +#include +#include + +#include "triton.h" +#include "list.h" + +/* + * Packet header = Code, id, length. + */ +#define PPP_HEADERLEN 4 +#define PPP_MTU 1500 + + +/* + * Protocol field values. + */ +#define PPP_IP 0x21 /* Internet Protocol */ +#define PPP_AT 0x29 /* AppleTalk Protocol */ +#define PPP_IPX 0x2b /* IPX protocol */ +#define PPP_VJC_COMP 0x2d /* VJ compressed TCP */ +#define PPP_VJC_UNCOMP 0x2f /* VJ uncompressed TCP */ +#define PPP_IPV6 0x57 /* Internet Protocol Version 6 */ +#define PPP_COMP 0xfd /* compressed packet */ +#define PPP_IPCP 0x8021 /* IP Control Protocol */ +#define PPP_ATCP 0x8029 /* AppleTalk Control Protocol */ +#define PPP_IPXCP 0x802b /* IPX Control Protocol */ +#define PPP_IPV6CP 0x8057 /* IPv6 Control Protocol */ +#define PPP_CCP 0x80fd /* Compression Control Protocol */ +#define PPP_ECP 0x8053 /* Encryption Control Protocol */ +#define PPP_LCP 0xc021 /* Link Control Protocol */ +#define PPP_PAP 0xc023 /* Password Authentication Protocol */ +#define PPP_LQR 0xc025 /* Link Quality Report protocol */ +#define PPP_CHAP 0xc223 /* Cryptographic Handshake Auth. Protocol */ +#define PPP_CBCP 0xc029 /* Callback Control Protocol */ +#define PPP_EAP 0xc227 /* Extensible Authentication Protocol */ + +#define PPP_SESSIONID_LEN 16 +#define PPP_IFNAME_LEN 10 + +#define PPP_STATE_STARTING 1 +#define PPP_STATE_ACTIVE 2 +#define PPP_STATE_FINISHING 3 + +#define TERM_USER_REQUEST 1 +#define TERM_SESSION_TIMEOUT 2 +#define TERM_ADMIN_RESET 3 +#define TERM_USER_ERROR 4 +#define TERM_NAS_ERROR 5 +#define TERM_NAS_REQUEST 6 +#define TERM_NAS_REBOOT 7 +#define TERM_AUTH_ERROR 8 + + +struct ppp_t; + +struct ppp_ctrl_t +{ + struct triton_context_t *ctx; + const char *name; + int max_mtu; + char *calling_station_id; + char *called_station_id; + void (*started)(struct ppp_t*); + void (*finished)(struct ppp_t*); +}; + +struct ppp_pd_t +{ + struct list_head entry; + void *key; +}; + +struct ppp_t +{ + struct list_head entry; + struct triton_md_handler_t chan_hnd; + struct triton_md_handler_t unit_hnd; + int fd; + int chan_fd; + int unit_fd; + + int chan_idx; + int unit_idx; + + int state; + char *chan_name; + char ifname[PPP_IFNAME_LEN]; + char sessionid[PPP_SESSIONID_LEN+1]; + time_t start_time; + time_t stop_time; + char *username; + in_addr_t ipaddr; + in_addr_t peer_ipaddr; + + struct ppp_ctrl_t *ctrl; + + int terminating:1; + int terminated:1; + int terminate_cause; + + void *chan_buf; + int chan_buf_size; + void *unit_buf; + int unit_buf_size; + + struct list_head chan_handlers; + struct list_head unit_handlers; + + struct list_head layers; + + struct ppp_lcp_t *lcp; + + struct list_head pd_list; +}; + +struct ppp_layer_t; +struct layer_node_t; +struct ppp_layer_data_t +{ + struct list_head entry; + struct ppp_layer_t *layer; + struct layer_node_t *node; + int starting:1; + int started:1; + int finished:1; +}; + +struct ppp_layer_t +{ + struct list_head entry; + struct ppp_layer_data_t *(*init)(struct ppp_t *); + int (*start)(struct ppp_layer_data_t*); + void (*finish)(struct ppp_layer_data_t*); + void (*free)(struct ppp_layer_data_t *); +}; + +struct ppp_handler_t +{ + struct list_head entry; + int proto; + void (*recv)(struct ppp_handler_t*); + void (*recv_proto_rej)(struct ppp_handler_t *h); +}; + +struct ppp_stat_t +{ + unsigned int active; + unsigned int starting; + unsigned int finishing; +}; + +struct ppp_t *alloc_ppp(void); +void ppp_init(struct ppp_t *ppp); +int establish_ppp(struct ppp_t *ppp); +int ppp_chan_send(struct ppp_t *ppp, void *data, int size); +int ppp_unit_send(struct ppp_t *ppp, void *data, int size); +void lcp_send_proto_rej(struct ppp_t *ppp, uint16_t proto); +void ppp_recv_proto_rej(struct ppp_t *ppp, uint16_t proto); + +struct ppp_fsm_t* ppp_lcp_init(struct ppp_t *ppp); +void ppp_layer_started(struct ppp_t *ppp,struct ppp_layer_data_t*); +void ppp_layer_finished(struct ppp_t *ppp,struct ppp_layer_data_t*); +void ppp_terminate(struct ppp_t *ppp, int hard, int cause); + +void ppp_register_chan_handler(struct ppp_t *, struct ppp_handler_t *); +void ppp_register_unit_handler(struct ppp_t * ,struct ppp_handler_t *); +void ppp_unregister_handler(struct ppp_t *, struct ppp_handler_t *); + +int ppp_register_layer(const char *name, struct ppp_layer_t *); +void ppp_unregister_layer(struct ppp_layer_t *); +struct ppp_layer_data_t *ppp_find_layer_data(struct ppp_t *, struct ppp_layer_t *); + +extern int ppp_shutdown; +void ppp_shutdown_soft(void); + +extern int conf_ppp_verbose; + +extern pthread_rwlock_t ppp_lock; +extern struct list_head ppp_list; + +extern struct ppp_stat_t ppp_stat; + +extern int sock_fd; // internet socket for ioctls +#endif diff --git a/accel-pppd/ppp/ppp_auth.c b/accel-pppd/ppp/ppp_auth.c new file mode 100644 index 0000000..32413c6 --- /dev/null +++ b/accel-pppd/ppp/ppp_auth.c @@ -0,0 +1,346 @@ +#include +#include +#include + +#include "ppp.h" +#include "events.h" +#include "ppp_lcp.h" +#include "log.h" + +#include "ppp_auth.h" + +#include "memdebug.h" + +static LIST_HEAD(auth_handlers); +static int extra_opt_len = 0; + +static struct lcp_option_t *auth_init(struct ppp_lcp_t *lcp); +static void auth_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt); +static int auth_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int auth_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int auth_recv_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int auth_recv_conf_rej(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static int auth_recv_conf_ack(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); +static void auth_print(void (*print)(const char *fmt,...), struct lcp_option_t*, uint8_t *ptr); + +static struct ppp_layer_data_t *auth_layer_init(struct ppp_t*); +static int auth_layer_start(struct ppp_layer_data_t *); +static void auth_layer_finish(struct ppp_layer_data_t *); +static void auth_layer_free(struct ppp_layer_data_t *); + +struct auth_option_t +{ + struct lcp_option_t opt; + struct list_head auth_list; + struct auth_data_t *auth; + struct auth_data_t *peer_auth; + int started:1; +}; + +struct auth_layer_data_t +{ + struct ppp_layer_data_t ld; + struct auth_option_t auth_opt; + struct ppp_t *ppp; +}; + +static struct lcp_option_handler_t auth_opt_hnd = +{ + .init = auth_init, + .send_conf_req = auth_send_conf_req, + .send_conf_nak = auth_send_conf_req, + .recv_conf_req = auth_recv_conf_req, + .recv_conf_nak = auth_recv_conf_nak, + .recv_conf_rej = auth_recv_conf_rej, + .recv_conf_ack = auth_recv_conf_ack, + .free = auth_free, + .print = auth_print, +}; + +static struct ppp_layer_t auth_layer = +{ + .init = auth_layer_init, + .start = auth_layer_start, + .finish = auth_layer_finish, + .free = auth_layer_free, +}; + +static struct lcp_option_t *auth_init(struct ppp_lcp_t *lcp) +{ + struct ppp_auth_handler_t *h; + struct auth_data_t *d; + struct auth_layer_data_t *ad; + + ad = container_of(ppp_find_layer_data(lcp->ppp, &auth_layer), typeof(*ad), ld); + + ad->auth_opt.opt.id = CI_AUTH; + ad->auth_opt.opt.len = 4 + extra_opt_len; + + INIT_LIST_HEAD(&ad->auth_opt.auth_list); + + list_for_each_entry(h, &auth_handlers, entry) { + d = h->init(lcp->ppp); + d->h = h; + list_add_tail(&d->entry, &ad->auth_opt.auth_list); + } + + return &ad->auth_opt.opt; +} + +static void auth_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt) +{ + struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); + struct auth_data_t *d; + + if (auth_opt->started && auth_opt->auth) { + auth_opt->auth->h->finish(lcp->ppp, auth_opt->auth); + auth_opt->started = 0; + } + + while(!list_empty(&auth_opt->auth_list)) { + d = list_entry(auth_opt->auth_list.next, typeof(*d), entry); + list_del(&d->entry); + d->h->free(lcp->ppp, d); + } +} + +static int auth_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); + struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; + struct auth_data_t *d; + int n; + + if (list_empty(&auth_opt->auth_list)) + return 0; + + if (!auth_opt->auth || auth_opt->auth->state == LCP_OPT_NAK) { + list_for_each_entry(d, &auth_opt->auth_list, entry) { + if (d->state == LCP_OPT_NAK || d->state == LCP_OPT_REJ) + continue; + auth_opt->auth = d; + break; + } + } + + opt16->hdr.id = CI_AUTH; + opt16->val = htons(auth_opt->auth->proto); + n = auth_opt->auth->h->send_conf_req(lcp->ppp, auth_opt->auth, (uint8_t*)(opt16 + 1)); + opt16->hdr.len = 4 + n; + + return 4 + n; +} + +static int auth_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct auth_option_t *auth_opt = container_of(opt,typeof(*auth_opt),opt); + struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; + struct auth_data_t *d; + int r; + + if (list_empty(&auth_opt->auth_list)) + return LCP_OPT_REJ; + + if (!ptr) + return LCP_OPT_ACK; + + + list_for_each_entry(d, &auth_opt->auth_list, entry) { + if (d->proto == ntohs(opt16->val)) { + r = d->h->recv_conf_req(lcp->ppp, d, (uint8_t*)(opt16 + 1)); + if (r == LCP_OPT_FAIL) + return LCP_OPT_FAIL; + if (r == LCP_OPT_REJ) + break; + auth_opt->peer_auth = d; + return r; + } + } + + list_for_each_entry(d, &auth_opt->auth_list, entry) { + if (d->state != LCP_OPT_NAK) { + auth_opt->peer_auth = d; + return LCP_OPT_NAK; + } + } + + log_ppp_error("cann't negotiate authentication type\n"); + return LCP_OPT_FAIL; +} + +static int auth_recv_conf_ack(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); + + auth_opt->peer_auth = NULL; + + return 0; +} + +static int auth_recv_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); + struct auth_data_t *d; + + if (!auth_opt->auth) { + log_ppp_error("auth: unexcepcted configure-nak\n"); + return -1; + } + auth_opt->auth->state = LCP_OPT_NAK; + if (auth_opt->peer_auth) + auth_opt->auth = auth_opt->peer_auth; + + list_for_each_entry(d, &auth_opt->auth_list, entry) { + if (d->state != LCP_OPT_NAK) + return 0; + } + + log_ppp_error("cann't negotiate authentication type\n"); + return -1; +} + +static int auth_recv_conf_rej(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) +{ + struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); + struct auth_data_t *d; + + if (!auth_opt->auth) { + log_ppp_error("auth: unexcepcted configure-reject\n"); + return -1; + } + + auth_opt->auth->state = LCP_OPT_NAK; + if (auth_opt->peer_auth) + auth_opt->auth = auth_opt->peer_auth; + + list_for_each_entry(d, &auth_opt->auth_list, entry) { + if (d->state != LCP_OPT_NAK) + return 0; + } + + log_ppp_error("cann't negotiate authentication type\n"); + return -1; +} + +static void auth_print(void (*print)(const char *fmt,...), struct lcp_option_t *opt, uint8_t *ptr) +{ + struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); + struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; + struct auth_data_t *d; + + if (ptr) { + list_for_each_entry(d, &auth_opt->auth_list, entry) { + if (d->proto == ntohs(opt16->val) && (!d->h->check || d->h->check((uint8_t *)(opt16 + 1)))) + goto print_d; + } + + print("", ntohs(opt16->val)); + return; + } else if (auth_opt->auth) + d = auth_opt->auth; + else + return; + +print_d: + print("", d->h->name); +} + +static struct ppp_layer_data_t *auth_layer_init(struct ppp_t *ppp) +{ + struct auth_layer_data_t *ad = _malloc(sizeof(*ad)); + + log_ppp_debug("auth_layer_init\n"); + + memset(ad, 0, sizeof(*ad)); + + ad->ppp = ppp; + + return &ad->ld; +} + +static int auth_layer_start(struct ppp_layer_data_t *ld) +{ + struct auth_layer_data_t *ad = container_of(ld,typeof(*ad),ld); + + log_ppp_debug("auth_layer_start\n"); + + if (ad->auth_opt.auth) { + ad->auth_opt.started = 1; + ad->auth_opt.auth->h->start(ad->ppp, ad->auth_opt.auth); + } else { + log_ppp_debug("auth_layer_started\n"); + ppp_layer_started(ad->ppp, ld); + } + + return 0; +} + +static void auth_layer_finish(struct ppp_layer_data_t *ld) +{ + struct auth_layer_data_t *ad = container_of(ld, typeof(*ad), ld); + + log_ppp_debug("auth_layer_finish\n"); + + if (ad->auth_opt.auth) + ad->auth_opt.auth->h->finish(ad->ppp, ad->auth_opt.auth); + + ad->auth_opt.started = 0; + + log_ppp_debug("auth_layer_finished\n"); + ppp_layer_finished(ad->ppp, ld); +} + +static void auth_layer_free(struct ppp_layer_data_t *ld) +{ + struct auth_layer_data_t *ad = container_of(ld, typeof(*ad), ld); + + log_ppp_debug("auth_layer_free\n"); + + _free(ad); +} + +void __export ppp_auth_successed(struct ppp_t *ppp, char *username) +{ + struct auth_layer_data_t *ad = container_of(ppp_find_layer_data(ppp, &auth_layer), typeof(*ad), ld); + log_ppp_debug("auth_layer_started\n"); + ppp->username = username; + ppp_layer_started(ppp, &ad->ld); + log_ppp_info1("%s: authentication successed\n", username); + triton_event_fire(EV_PPP_AUTHORIZED, ppp); +} + +void __export ppp_auth_failed(struct ppp_t *ppp, const char *username) +{ + if (username) + log_ppp_info1("%s: authentication failed\n", username); + else + log_ppp_info1("authentication failed\n"); + ppp_terminate(ppp, TERM_AUTH_ERROR, 0); +} + +int __export ppp_auth_register_handler(struct ppp_auth_handler_t *h) +{ + list_add_tail(&h->entry, &auth_handlers); + return 0; +} + +int __export ppp_auth_restart(struct ppp_t *ppp) +{ + struct auth_layer_data_t *ad = container_of(ppp_find_layer_data(ppp, &auth_layer), typeof(*ad), ld); + log_ppp_debug("ppp_auth_restart\n"); + + if (!ad->auth_opt.auth->h->restart) + return -1; + + if (ad->auth_opt.auth->h->restart(ppp, ad->auth_opt.auth)) + return -1; + + return 0; +} + +static void __init ppp_auth_init() +{ + ppp_register_layer("auth", &auth_layer); + lcp_option_register(&auth_opt_hnd); +} + diff --git a/accel-pppd/ppp/ppp_auth.h b/accel-pppd/ppp/ppp_auth.h new file mode 100644 index 0000000..87cc742 --- /dev/null +++ b/accel-pppd/ppp/ppp_auth.h @@ -0,0 +1,37 @@ +#ifndef PPP_AUTH_H +#define PPP_AUTH_H + +#include "list.h" + +struct ppp_auth_handler_t; + +struct auth_data_t +{ + struct list_head entry; + int proto; + int state; + struct ppp_auth_handler_t *h; +}; + +struct ppp_auth_handler_t +{ + struct list_head entry; + const char *name; + struct auth_data_t* (*init)(struct ppp_t*); + int (*send_conf_req)(struct ppp_t*, struct auth_data_t*, uint8_t*); + int (*recv_conf_req)(struct ppp_t*, struct auth_data_t*, uint8_t*); + int (*start)(struct ppp_t*, struct auth_data_t*); + int (*finish)(struct ppp_t*, struct auth_data_t*); + void (*free)(struct ppp_t*,struct auth_data_t*); + int (*check)(uint8_t *); + int (*restart)(struct ppp_t*,struct auth_data_t*); +}; + +int ppp_auth_register_handler(struct ppp_auth_handler_t*); + +void ppp_auth_successed(struct ppp_t *ppp, char *username); +void ppp_auth_failed(struct ppp_t *ppp, const char *username); +int ppp_auth_restart(struct ppp_t *ppp); + +#endif + diff --git a/accel-pppd/ppp/ppp_ccp.c b/accel-pppd/ppp/ppp_ccp.c new file mode 100644 index 0000000..721dd9b --- /dev/null +++ b/accel-pppd/ppp/ppp_ccp.c @@ -0,0 +1,759 @@ +#include +#include +#include +#include +#include +#include "linux_ppp.h" + +#include "triton.h" + +#include "log.h" +#include "events.h" + +#include "ppp.h" +#include "ppp_ccp.h" + +#include "memdebug.h" + +struct recv_opt_t +{ + struct list_head entry; + struct ccp_opt_hdr_t *hdr; + int len; + int state; + struct ccp_option_t *lopt; +}; + +static int conf_ccp = 1; + +static struct ppp_layer_t ccp_layer; +static LIST_HEAD(option_handlers); + +static void ccp_layer_up(struct ppp_fsm_t*); +static void ccp_layer_down(struct ppp_fsm_t*); +static int send_conf_req(struct ppp_fsm_t*); +static void send_conf_ack(struct ppp_fsm_t*); +static void send_conf_nak(struct ppp_fsm_t*); +static void send_conf_rej(struct ppp_fsm_t*); +static void send_term_req(struct ppp_fsm_t *fsm); +static void send_term_ack(struct ppp_fsm_t *fsm); +static void ccp_recv(struct ppp_handler_t*); +static void ccp_recv_proto_rej(struct ppp_handler_t*); + +static void ccp_options_init(struct ppp_ccp_t *ccp) +{ + struct ccp_option_t *lopt; + struct ccp_option_handler_t *h; + + ccp->conf_req_len = sizeof(struct ccp_hdr_t); + + list_for_each_entry(h, &option_handlers, entry) { + lopt = h->init(ccp); + if (lopt) { + lopt->h = h; + list_add_tail(&lopt->entry, &ccp->options); + ccp->conf_req_len += lopt->len; + } + } +} + +static void ccp_options_free(struct ppp_ccp_t *ccp) +{ + struct ccp_option_t *lopt; + + while (!list_empty(&ccp->options)) { + lopt = list_entry(ccp->options.next, typeof(*lopt), entry); + list_del(&lopt->entry); + lopt->h->free(ccp, lopt); + } +} + +static int ccp_set_flags(int fd, int isopen, int isup) +{ + int flags; + + if (ioctl(fd, PPPIOCGFLAGS, &flags)) { + log_ppp_error("ccp: failed to get flags: %s\n", strerror(errno)); + return -1; + } + + flags &= ~(SC_CCP_OPEN | SC_CCP_UP); + flags |= (isopen ? SC_CCP_OPEN : 0) | (isup ? SC_CCP_UP : 0); + + if (ioctl(fd, PPPIOCSFLAGS, &flags)) { + log_ppp_error("ccp: failed to set flags: %s\n", strerror(errno)); + return -1; + } + + return 0; +} + +static struct ppp_layer_data_t *ccp_layer_init(struct ppp_t *ppp) +{ + struct ppp_ccp_t *ccp = _malloc(sizeof(*ccp)); + memset(ccp, 0, sizeof(*ccp)); + + log_ppp_debug("ccp_layer_init\n"); + + ccp->ppp = ppp; + ccp->fsm.ppp = ppp; + + ccp->hnd.proto = PPP_CCP; + ccp->hnd.recv = ccp_recv; + ccp->hnd.recv_proto_rej = ccp_recv_proto_rej; + + ppp_register_unit_handler(ppp, &ccp->hnd); + + INIT_LIST_HEAD(&ccp->options); + ccp_options_init(ccp); + + ccp->passive = 0; + + ccp->fsm.proto = PPP_CCP; + ppp_fsm_init(&ccp->fsm); + + ccp->fsm.layer_up = ccp_layer_up; + ccp->fsm.layer_finished = ccp_layer_down; + ccp->fsm.send_conf_req = send_conf_req; + ccp->fsm.send_conf_ack = send_conf_ack; + ccp->fsm.send_conf_nak = send_conf_nak; + ccp->fsm.send_conf_rej = send_conf_rej; + ccp->fsm.send_term_req = send_term_req; + ccp->fsm.send_term_ack = send_term_ack; + + INIT_LIST_HEAD(&ccp->ropt_list); + + return &ccp->ld; +} + +int ccp_layer_start(struct ppp_layer_data_t *ld) +{ + struct ppp_ccp_t *ccp = container_of(ld, typeof(*ccp), ld); + + log_ppp_debug("ccp_layer_start\n"); + + if (list_empty(&ccp->options) || !conf_ccp) { + ppp_layer_started(ccp->ppp, &ccp->ld); + return 0; + } + + ppp_fsm_lower_up(&ccp->fsm); + if (ppp_fsm_open(&ccp->fsm)) + return -1; + + if (ccp_set_flags(ccp->ppp->unit_fd, 1, 0)) { + ppp_fsm_close(&ccp->fsm); + return -1; + } + + return 0; +} + +void ccp_layer_finish(struct ppp_layer_data_t *ld) +{ + struct ppp_ccp_t *ccp = container_of(ld, typeof(*ccp), ld); + + log_ppp_debug("ccp_layer_finish\n"); + + ccp_set_flags(ccp->ppp->unit_fd, 0, 0); + + ccp->fsm.fsm_state = FSM_Closed; + + log_ppp_debug("ccp_layer_finished\n"); + ppp_layer_finished(ccp->ppp, &ccp->ld); +} + +void ccp_layer_free(struct ppp_layer_data_t *ld) +{ + struct ppp_ccp_t *ccp = container_of(ld, typeof(*ccp), ld); + + log_ppp_debug("ccp_layer_free\n"); + + ppp_unregister_handler(ccp->ppp, &ccp->hnd); + ccp_options_free(ccp); + ppp_fsm_free(&ccp->fsm); + + _free(ccp); +} + +static void ccp_layer_up(struct ppp_fsm_t *fsm) +{ + struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); + + log_ppp_debug("ccp_layer_started\n"); + + if (!ccp->started) { + ccp->started = 1; + if (ccp_set_flags(ccp->ppp->unit_fd, 1, 1)) { + ppp_terminate(ccp->ppp, TERM_NAS_ERROR, 0); + return; + } + ppp_layer_started(ccp->ppp, &ccp->ld); + } +} + +static void ccp_layer_down(struct ppp_fsm_t *fsm) +{ + struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); + + log_ppp_debug("ccp_layer_finished\n"); + + if (!ccp->started) + ppp_layer_started(ccp->ppp, &ccp->ld); + ccp->started = 0; + ppp_layer_finished(ccp->ppp, &ccp->ld); +} + +static void print_ropt(struct recv_opt_t *ropt) +{ + int i; + uint8_t *ptr = (uint8_t*)ropt->hdr; + + log_ppp_info2("<"); + for (i = 0; i < ropt->len; i++) { + log_ppp_info2(" %x", ptr[i]); + } + log_ppp_info2(" >"); +} + +static int send_conf_req(struct ppp_fsm_t *fsm) +{ + struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); + uint8_t *buf, *ptr; + struct ccp_hdr_t *ccp_hdr; + struct ccp_option_t *lopt; + int n; + + ccp->need_req = 0; + + if (ccp->passive) { + ccp->passive--; + return 0; + } + + buf = _malloc(ccp->conf_req_len); + ccp_hdr = (struct ccp_hdr_t*)buf; + + ccp_hdr->proto = htons(PPP_CCP); + ccp_hdr->code = CONFREQ; + ccp_hdr->id = ++ccp->fsm.id; + ccp_hdr->len = 0; + + ptr = (uint8_t*)(ccp_hdr + 1); + + if (conf_ppp_verbose) + log_ppp_info2("send [CCP ConfReq id=%x", ccp_hdr->id); + + list_for_each_entry(lopt, &ccp->options, entry) { + n = lopt->h->send_conf_req(ccp, lopt, ptr); + if (n < 0) + return -1; + if (n) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, NULL); + } + } + ptr += n; + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + ccp_hdr->len = htons(ptr - buf - 2); + ppp_unit_send(ccp->ppp, ccp_hdr, ptr - buf); + + _free(buf); + + return 0; +} + +static void send_conf_ack(struct ppp_fsm_t *fsm) +{ + struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); + struct ccp_hdr_t *hdr = (struct ccp_hdr_t*)ccp->ppp->unit_buf; + + hdr->code = CONFACK; + + if (conf_ppp_verbose) + log_ppp_info2("send [CCP ConfAck id=%x]\n", ccp->fsm.recv_id); + + ppp_unit_send(ccp->ppp,hdr,ntohs(hdr->len)+2); +} + +static void send_conf_nak(struct ppp_fsm_t *fsm) +{ + struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); + uint8_t *buf = _malloc(ccp->conf_req_len), *ptr = buf; + struct ccp_hdr_t *ccp_hdr = (struct ccp_hdr_t*)ptr; + struct recv_opt_t *ropt; + + if (conf_ppp_verbose) + log_ppp_info2("send [CCP ConfNak id=%x", ccp->fsm.recv_id); + + ccp_hdr->proto = htons(PPP_CCP); + ccp_hdr->code = CONFNAK; + ccp_hdr->id = ccp->fsm.recv_id; + ccp_hdr->len = 0; + + ptr += sizeof(*ccp_hdr); + + list_for_each_entry(ropt, &ccp->ropt_list, entry) { + if (ropt->state == CCP_OPT_NAK) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + ropt->lopt->h->print(log_ppp_info2, ropt->lopt, NULL); + } + ptr += ropt->lopt->h->send_conf_nak(ccp, ropt->lopt, ptr); + } + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + ccp_hdr->len = htons(ptr - buf - 2); + ppp_unit_send(ccp->ppp, ccp_hdr, ptr - buf); + + _free(buf); +} + +static void send_conf_rej(struct ppp_fsm_t *fsm) +{ + struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); + uint8_t *buf = _malloc(ccp->ropt_len + sizeof(struct ccp_hdr_t)), *ptr = buf; + struct ccp_hdr_t *ccp_hdr = (struct ccp_hdr_t*)ptr; + struct recv_opt_t *ropt; + + if (conf_ppp_verbose) + log_ppp_info2("send [CCP ConfRej id=%x", ccp->fsm.recv_id); + + ccp_hdr->proto = htons(PPP_CCP); + ccp_hdr->code = CONFREJ; + ccp_hdr->id = ccp->fsm.recv_id; + ccp_hdr->len = 0; + + ptr += sizeof(*ccp_hdr); + + list_for_each_entry(ropt, &ccp->ropt_list, entry) { + if (ropt->state == CCP_OPT_REJ) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + if (ropt->lopt) + ropt->lopt->h->print(log_ppp_info2, ropt->lopt, (uint8_t*)ropt->hdr); + else + print_ropt(ropt); + } + memcpy(ptr, ropt->hdr, ropt->len); + ptr += ropt->len; + } + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + ccp_hdr->len = htons(ptr - buf - 2); + ppp_unit_send(ccp->ppp, ccp_hdr, ptr-buf); + + _free(buf); +} + +static int ccp_recv_conf_req(struct ppp_ccp_t *ccp, uint8_t *data, int size) +{ + struct ccp_opt_hdr_t *hdr; + struct recv_opt_t *ropt; + struct ccp_option_t *lopt; + int r, ret = 1, ack = 0; + + ccp->need_req = 0; + ccp->ropt_len = size; + + while (size > 0) { + hdr = (struct ccp_opt_hdr_t *)data; + + ropt = _malloc(sizeof(*ropt)); + memset(ropt, 0, sizeof(*ropt)); + + if (hdr->len > size) + ropt->len = size; + else + ropt->len = hdr->len; + + ropt->hdr = hdr; + ropt->state = CCP_OPT_NONE; + list_add_tail(&ropt->entry, &ccp->ropt_list); + + data += ropt->len; + size -= ropt->len; + } + + if (conf_ppp_verbose) + log_ppp_info2("recv [CCP ConfReq id=%x", ccp->fsm.recv_id); + + list_for_each_entry(ropt, &ccp->ropt_list, entry) { + list_for_each_entry(lopt, &ccp->options, entry) { + if (lopt->id == ropt->hdr->id) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, (uint8_t*)ropt->hdr); + } + r = lopt->h->recv_conf_req(ccp, lopt, (uint8_t*)ropt->hdr); + if (ack) { + lopt->state = CCP_OPT_REJ; + ropt->state = CCP_OPT_REJ; + } else { + /*if (lopt->state == CCP_OPT_NAK && r == CCP_OPT_ACK) + ccp->need_req = 1;*/ + lopt->state = r; + ropt->state = r; + } + ropt->lopt = lopt; + if (r < ret) + ret = r; + break; + } + } + if (ropt->state == CCP_OPT_ACK || ropt->state == CCP_OPT_NAK) + ack = 1; + else if (!ropt->lopt) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + print_ropt(ropt); + } + ropt->state = CCP_OPT_REJ; + ret = CCP_OPT_REJ; + } + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + /*list_for_each_entry(lopt,&ccp->options,entry) + { + if (lopt->state==CCP_OPT_NONE) + { + r=lopt->h->recv_conf_req(ccp,lopt,NULL); + lopt->state=r; + if (rropt_list)) { + ropt = list_entry(ccp->ropt_list.next, typeof(*ropt), entry); + list_del(&ropt->entry); + _free(ropt); + } +} + +static int ccp_recv_conf_rej(struct ppp_ccp_t *ccp, uint8_t *data, int size) +{ + struct ccp_opt_hdr_t *hdr; + struct ccp_option_t *lopt; + int res = 0; + + if (conf_ppp_verbose) + log_ppp_info2("recv [CCP ConfRej id=%x", ccp->fsm.recv_id); + + if (ccp->fsm.recv_id != ccp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info2(": id mismatch ]\n"); + return 0; + } + + while (size > 0) { + hdr = (struct ccp_opt_hdr_t *)data; + + list_for_each_entry(lopt, &ccp->options, entry) { + if (lopt->id == hdr->id) { + if (!lopt->h->recv_conf_rej) + res = -1; + else if (lopt->h->recv_conf_rej(ccp, lopt, data)) + res = -1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + return res; +} + +static int ccp_recv_conf_nak(struct ppp_ccp_t *ccp, uint8_t *data, int size) +{ + struct ccp_opt_hdr_t *hdr; + struct ccp_option_t *lopt; + int res = 0; + + if (conf_ppp_verbose) + log_ppp_info2("recv [CCP ConfNak id=%x", ccp->fsm.recv_id); + + if (ccp->fsm.recv_id != ccp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info2(": id mismatch ]\n"); + return 0; + } + + while (size > 0) { + hdr = (struct ccp_opt_hdr_t *)data; + + list_for_each_entry(lopt, &ccp->options, entry) { + if (lopt->id == hdr->id) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, data); + } + if (lopt->h->recv_conf_nak && lopt->h->recv_conf_nak(ccp, lopt, data)) + res = -1; + //lopt->state = CCP_OPT_NAK; + //ccp->need_req = 1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + return res; +} + +static int ccp_recv_conf_ack(struct ppp_ccp_t *ccp, uint8_t *data, int size) +{ + struct ccp_opt_hdr_t *hdr; + struct ccp_option_t *lopt; + int res = 0; + + if (conf_ppp_verbose) + log_ppp_info2("recv [CCP ConfAck id=%x", ccp->fsm.recv_id); + + if (ccp->fsm.recv_id != ccp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info2(": id mismatch ]\n"); + return 0; + } + + while (size > 0) { + hdr = (struct ccp_opt_hdr_t *)data; + + list_for_each_entry(lopt, &ccp->options, entry) { + if (lopt->id == hdr->id) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2,lopt,data); + } + if (!lopt->h->recv_conf_ack) + break; + if (lopt->h->recv_conf_ack(ccp, lopt, data)) + res = -1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + return res; +} + +static void send_term_req(struct ppp_fsm_t *fsm) +{ + struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); + struct ccp_hdr_t hdr = { + .proto = htons(PPP_CCP), + .code = TERMREQ, + .id = ++ccp->fsm.id, + .len = htons(4), + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [CCP TermReq id=%i]\n", hdr.id); + + ppp_chan_send(ccp->ppp, &hdr, 6); +} + +static void send_term_ack(struct ppp_fsm_t *fsm) +{ + struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); + struct ccp_hdr_t hdr = { + .proto = htons(PPP_CCP), + .code = TERMACK, + .id = ccp->fsm.recv_id, + .len = htons(4), + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [CCP TermAck id=%i]\n", hdr.id); + + ppp_chan_send(ccp->ppp, &hdr, 6); +} + +static void ccp_recv(struct ppp_handler_t*h) +{ + struct ccp_hdr_t *hdr; + struct ppp_ccp_t *ccp = container_of(h, typeof(*ccp), hnd); + int r; + + if (ccp->fsm.fsm_state == FSM_Initial || ccp->fsm.fsm_state == FSM_Closed || ccp->ppp->terminating) { + if (conf_ppp_verbose) + log_ppp_warn("CCP: discarding packet\n"); + if (ccp->fsm.fsm_state == FSM_Closed || !conf_ccp) + lcp_send_proto_rej(ccp->ppp, PPP_CCP); + return; + } + + if (ccp->ppp->unit_buf_size < PPP_HEADERLEN + 2) { + log_ppp_warn("CCP: short packet received\n"); + return; + } + + hdr = (struct ccp_hdr_t *)ccp->ppp->unit_buf; + if (ntohs(hdr->len) < PPP_HEADERLEN) { + log_ppp_warn("CCP: short packet received\n"); + return; + } + + ccp->fsm.recv_id = hdr->id; + switch(hdr->code) { + case CONFREQ: + r = ccp_recv_conf_req(ccp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); + switch(r) { + case CCP_OPT_ACK: + ppp_fsm_recv_conf_req_ack(&ccp->fsm); + break; + case CCP_OPT_NAK: + ppp_fsm_recv_conf_req_nak(&ccp->fsm); + break; + case CCP_OPT_REJ: + ppp_fsm_recv_conf_req_rej(&ccp->fsm); + break; + } + ccp_free_conf_req(ccp); + + if (r == CCP_OPT_ACK && ccp->passive) { + ccp->passive = 0; + send_conf_req(&ccp->fsm); + } + if (r == CCP_OPT_FAIL) + ppp_terminate(ccp->ppp, TERM_USER_ERROR, 0); + break; + case CONFACK: + if (ccp_recv_conf_ack(ccp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) + ppp_terminate(ccp->ppp, TERM_USER_ERROR, 0); + else { + ppp_fsm_recv_conf_ack(&ccp->fsm); + if (ccp->need_req) + send_conf_req(&ccp->fsm); + } + break; + case CONFNAK: + ccp_recv_conf_nak(ccp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); + ppp_fsm_recv_conf_rej(&ccp->fsm); + break; + case CONFREJ: + if (ccp_recv_conf_rej(ccp, (uint8_t*)(hdr + 1),ntohs(hdr->len) - PPP_HDRLEN)) + ppp_terminate(ccp->ppp, TERM_USER_ERROR, 0); + else + ppp_fsm_recv_conf_rej(&ccp->fsm); + break; + case TERMREQ: + if (conf_ppp_verbose) + log_ppp_info2("recv [CCP TermReq id=%x]\n", hdr->id); + ppp_fsm_recv_term_req(&ccp->fsm); + ppp_fsm_close(&ccp->fsm); + break; + case TERMACK: + if (conf_ppp_verbose) + log_ppp_info2("recv [CCP TermAck id=%x]\n", hdr->id); + ppp_fsm_recv_term_ack(&ccp->fsm); + break; + case CODEREJ: + if (conf_ppp_verbose) + log_ppp_info2("recv [CCP CodeRej id=%x]\n", hdr->id); + ppp_fsm_recv_code_rej_bad(&ccp->fsm); + break; + default: + ppp_fsm_recv_unk(&ccp->fsm); + break; + } +} + +static void ccp_recv_proto_rej(struct ppp_handler_t *h) +{ + struct ppp_ccp_t *ccp = container_of(h, typeof(*ccp), hnd); + + if (ccp->fsm.fsm_state == FSM_Initial || ccp->fsm.fsm_state == FSM_Closed) + return; + + ppp_fsm_lower_down(&ccp->fsm); + ppp_fsm_close(&ccp->fsm); +} + +int ccp_option_register(struct ccp_option_handler_t *h) +{ + /*struct ccp_option_drv_t *p; + + list_for_each_entry(p,option_drv_list,entry) + if (p->id==h->id) + return -1;*/ + + list_add_tail(&h->entry,&option_handlers); + + return 0; +} + +struct ccp_option_t *ccp_find_option(struct ppp_t *ppp, struct ccp_option_handler_t *h) +{ + struct ppp_ccp_t *ccp = container_of(ppp_find_layer_data(ppp, &ccp_layer), typeof(*ccp), ld); + struct ccp_option_t *opt; + + list_for_each_entry(opt, &ccp->options, entry) + if (opt->h == h) + return opt; + + log_emerg("ccp: BUG: option not found\n"); + abort(); +} + +static struct ppp_layer_t ccp_layer= +{ + .init = ccp_layer_init, + .start = ccp_layer_start, + .finish = ccp_layer_finish, + .free = ccp_layer_free, +}; + +static void load_config(void) +{ + const char *opt; + + opt = conf_get_opt("ppp", "ccp"); + if (opt && atoi(opt) >= 0) + conf_ccp = atoi(opt); +} + +static void __init ccp_init(void) +{ + ppp_register_layer("ccp", &ccp_layer); + + load_config(); + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); +} + diff --git a/accel-pppd/ppp/ppp_ccp.h b/accel-pppd/ppp/ppp_ccp.h new file mode 100644 index 0000000..2c2dc6d --- /dev/null +++ b/accel-pppd/ppp/ppp_ccp.h @@ -0,0 +1,96 @@ +#ifndef PPP_CCP_H +#define PPP_CCP_H + +#include + +#include "triton.h" +#include "ppp_fsm.h" +/* + * Options. + */ + +#define CI_MPPE 18 /* MPPE */ + +struct ccp_hdr_t +{ + uint16_t proto; + uint8_t code; + uint8_t id; + uint16_t len; +} __attribute__((packed)); +struct ccp_opt_hdr_t +{ + uint8_t id; + uint8_t len; +} __attribute__((packed)); +struct ccp_opt8_t +{ + struct ccp_opt_hdr_t hdr; + uint8_t val; +} __attribute__((packed)); +struct ccp_opt16_t +{ + struct ccp_opt_hdr_t hdr; + uint16_t val; +} __attribute__((packed)); +struct ccp_opt32_t +{ + struct ccp_opt_hdr_t hdr; + uint32_t val; +} __attribute__((packed)); + +#define CCP_OPT_NONE 0 +#define CCP_OPT_ACK 1 +#define CCP_OPT_NAK -1 +#define CCP_OPT_REJ -2 +#define CCP_OPT_FAIL -3 + +struct ppp_ccp_t; +struct ccp_option_handler_t; + +struct ccp_option_t +{ + struct list_head entry; + int id; + int len; + int state; + struct ccp_option_handler_t *h; +}; + +struct ccp_option_handler_t +{ + struct list_head entry; + struct ccp_option_t* (*init)(struct ppp_ccp_t*); + int (*send_conf_req)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); + int (*send_conf_rej)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); + int (*send_conf_nak)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); + int (*recv_conf_req)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); + int (*recv_conf_rej)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); + int (*recv_conf_nak)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); + int (*recv_conf_ack)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); + void (*free)(struct ppp_ccp_t*,struct ccp_option_t*); + void (*print)(void (*print)(const char *fmt,...), struct ccp_option_t*,uint8_t*); +}; + +struct ppp_ccp_t +{ + struct ppp_layer_data_t ld; + struct ppp_handler_t hnd; + struct ppp_fsm_t fsm; + struct ppp_t *ppp; + struct list_head options; + + struct list_head ropt_list; // last received ConfReq + int ropt_len; + + int conf_req_len; + int passive; + int started:1; + int need_req:1; +}; + +int ccp_option_register(struct ccp_option_handler_t *h); +struct ccp_option_t *ccp_find_option(struct ppp_t *ppp, struct ccp_option_handler_t *h); + +#endif + diff --git a/accel-pppd/ppp/ppp_fsm.c b/accel-pppd/ppp/ppp_fsm.c new file mode 100644 index 0000000..c6bc430 --- /dev/null +++ b/accel-pppd/ppp/ppp_fsm.c @@ -0,0 +1,544 @@ +#include +#include + +#include "triton.h" + +#include "ppp.h" +#include "ppp_fsm.h" +#include "ppp_lcp.h" +#include "log.h" +#include "events.h" + +#include "memdebug.h" + +static int conf_max_terminate = 2; +static int conf_max_configure = 10; +static int conf_max_failure = 10; +static int conf_timeout = 5; + +void send_term_req(struct ppp_fsm_t *layer); +void send_term_ack(struct ppp_fsm_t *layer); +void send_echo_reply(struct ppp_fsm_t *layer); + +static void init_req_counter(struct ppp_fsm_t *layer,int timeout); +static void zero_req_counter(struct ppp_fsm_t *layer); +static void restart_timer_func(struct triton_timer_t *t); +static void stop_timer(struct ppp_fsm_t *fsm); + +void ppp_fsm_init(struct ppp_fsm_t *layer) +{ + layer->fsm_state = FSM_Initial; + layer->restart_timer.expire = restart_timer_func; + layer->restart_timer.period = conf_timeout * 1000; + layer->restart_counter = 0; + + layer->max_terminate = conf_max_terminate; + layer->max_configure = conf_max_configure; + layer->max_failure = conf_max_failure; + layer->timeout = conf_timeout; +} +void ppp_fsm_free(struct ppp_fsm_t *layer) +{ + stop_timer(layer); +} + +int ppp_fsm_lower_up(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Initial: + layer->fsm_state=FSM_Closed; + break; + case FSM_Starting: + //if (layer->init_req_cnt) layer->init_req_cnt(layer); + init_req_counter(layer,layer->max_configure); + --layer->restart_counter; + if (layer->send_conf_req) + if (layer->send_conf_req(layer)) + return -1; + layer->fsm_state=FSM_Req_Sent; + break; + default: + break; + } + return 0; +} + +void ppp_fsm_lower_down(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Closed: + case FSM_Closing: + layer->fsm_state=FSM_Initial; + break; + case FSM_Stopped: + if (layer->layer_started) layer->layer_started(layer); + layer->fsm_state=FSM_Starting; + break; + case FSM_Stopping: + case FSM_Req_Sent: + case FSM_Ack_Rcvd: + case FSM_Ack_Sent: + layer->fsm_state=FSM_Starting; + break; + case FSM_Opened: + if (layer->layer_down) layer->layer_down(layer); + layer->fsm_state=FSM_Starting; + break; + default: + break; + } +} + +int ppp_fsm_open(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Initial: + if (layer->layer_started) layer->layer_started(layer); + layer->fsm_state=FSM_Starting; + break; + case FSM_Starting: + break; + case FSM_Closed: + //if (layer->init_req_cnt) layer->init_req_cnt(layer); + init_req_counter(layer,layer->max_configure); + --layer->restart_counter; + if (layer->send_conf_req) + if (layer->send_conf_req(layer)) + return -1; + layer->fsm_state=FSM_Req_Sent; + break; + case FSM_Closing: + case FSM_Stopping: + case FSM_Stopped: + case FSM_Opened: + ppp_fsm_lower_down(layer); + ppp_fsm_lower_up(layer); + break; + default: + break; + } + return 0; +} + +void ppp_fsm_close(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Starting: + stop_timer(layer); + layer->fsm_state=FSM_Initial; + if (layer->layer_finished) layer->layer_finished(layer); + break; + case FSM_Stopped: + layer->fsm_state=FSM_Closed; + stop_timer(layer); + break; + case FSM_Stopping: + layer->fsm_state=FSM_Closing; + break; + case FSM_Opened: + if (layer->layer_down) layer->layer_down(layer); + case FSM_Req_Sent: + case FSM_Ack_Rcvd: + case FSM_Ack_Sent: + //if (layer->init_req_cnt) layer->init_req_cnt(layer); + init_req_counter(layer,layer->max_terminate); + layer->send_term_req(layer); + layer->fsm_state=FSM_Closing; + break; + default: + break; + } +} + +void ppp_fsm_timeout0(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Closing: + case FSM_Stopping: + --layer->restart_counter; + layer->send_term_req(layer); + break; + case FSM_Ack_Rcvd: + layer->fsm_state=FSM_Req_Sent; + case FSM_Req_Sent: + case FSM_Ack_Sent: + --layer->restart_counter; + --layer->id; + if (layer->send_conf_req) layer->send_conf_req(layer); + break; + default: + break; + } +} + +void ppp_fsm_timeout1(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Closing: + stop_timer(layer); + layer->fsm_state=FSM_Closed; + if (layer->layer_finished) layer->layer_finished(layer); + break; + case FSM_Stopping: + stop_timer(layer); + layer->fsm_state=FSM_Stopped; + if (layer->layer_finished) layer->layer_finished(layer); + break; + case FSM_Ack_Rcvd: + case FSM_Req_Sent: + case FSM_Ack_Sent: + stop_timer(layer); + layer->fsm_state=FSM_Stopped; + if (layer->layer_finished) layer->layer_finished(layer); + break; + default: + break; + } +} + +void ppp_fsm_recv_conf_req_ack(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Closed: + layer->send_term_ack(layer); + break; + case FSM_Stopped: + //if (layer->init_req_cnt) layer->init_req_cnt(layer); + init_req_counter(layer,layer->max_configure); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + case FSM_Req_Sent: + case FSM_Ack_Sent: + if (layer->send_conf_ack) layer->send_conf_ack(layer); + layer->fsm_state=FSM_Ack_Sent; + break; + case FSM_Ack_Rcvd: + if (layer->send_conf_ack) layer->send_conf_ack(layer); + stop_timer(layer); + if (layer->layer_up) layer->layer_up(layer); + layer->fsm_state=FSM_Opened; + break; + case FSM_Opened: + if (layer->layer_down) layer->layer_down(layer); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + if (layer->send_conf_ack) layer->send_conf_ack(layer); + layer->fsm_state=FSM_Ack_Sent; + break; + default: + break; + } +} + +void ppp_fsm_recv_conf_req_nak(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Closed: + layer->send_term_ack(layer); + break; + case FSM_Stopped: + //if (layer->init_req_cnt) layer->init_req_cnt(layer); + init_req_counter(layer,layer->max_configure); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + case FSM_Ack_Sent: + if (layer->send_conf_nak) layer->send_conf_nak(layer); + layer->fsm_state=FSM_Req_Sent; + break; + case FSM_Req_Sent: + case FSM_Ack_Rcvd: + if (++layer->conf_failure == layer->max_failure) { + if (layer->layer_finished) layer->layer_finished(layer); + return; + } + if (layer->send_conf_nak) layer->send_conf_nak(layer); + break; + case FSM_Opened: + if (layer->layer_down) layer->layer_down(layer); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + if (layer->send_conf_nak) layer->send_conf_nak(layer); + layer->fsm_state=FSM_Req_Sent; + break; + default: + break; + } +} + +void ppp_fsm_recv_conf_req_rej(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Closed: + layer->send_term_ack(layer); + break; + case FSM_Stopped: + //if (layer->init_req_cnt) layer->init_req_cnt(layer); + init_req_counter(layer,layer->max_configure); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + case FSM_Ack_Sent: + if (++layer->conf_failure == layer->max_failure) { + if (layer->layer_down) layer->layer_down(layer); + return; + } + if (layer->send_conf_rej) layer->send_conf_rej(layer); + layer->fsm_state=FSM_Req_Sent; + break; + case FSM_Req_Sent: + case FSM_Ack_Rcvd: + if (++layer->conf_failure == layer->max_failure) { + if (layer->layer_finished) layer->layer_finished(layer); + return; + } + if (layer->send_conf_rej) layer->send_conf_rej(layer); + break; + case FSM_Opened: + if (layer->layer_down) layer->layer_down(layer); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + if (layer->send_conf_rej) layer->send_conf_rej(layer); + layer->fsm_state=FSM_Req_Sent; + break; + default: + break; + } +} + +void ppp_fsm_recv_conf_ack(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Closed: + case FSM_Stopped: + layer->send_term_ack(layer); + break; + case FSM_Req_Sent: + //if (layer->init_req_cnt) layer->init_req_cnt(layer); + init_req_counter(layer,layer->max_configure); + layer->fsm_state=FSM_Ack_Rcvd; + break; + case FSM_Ack_Rcvd: + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + layer->fsm_state=FSM_Req_Sent; + break; + case FSM_Ack_Sent: + //if (layer->init_req_cnt) layer->init_req_cnt(layer); + //init_req_counter(layer,layer->max_configure); + //tlu + stop_timer(layer); + if (layer->layer_up) layer->layer_up(layer); + layer->fsm_state=FSM_Opened; + break; + case FSM_Opened: + if (layer->layer_down) layer->layer_down(layer); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + layer->fsm_state=FSM_Req_Sent; + default: + break; + } +} + +void ppp_fsm_recv_conf_rej(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Closed: + case FSM_Stopped: + layer->send_term_ack(layer); + break; + case FSM_Req_Sent: + if (++layer->conf_failure == layer->max_failure) { + if (layer->layer_down) layer->layer_down(layer); + return; + } + //if (layer->init_req_cnt) layer->init_req_cnt(layer); + init_req_counter(layer,layer->max_failure); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + break; + case FSM_Ack_Rcvd: + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + layer->fsm_state=FSM_Req_Sent; + break; + case FSM_Ack_Sent: + //if (layer->init_req_cnt) layer->init_req_cnt(layer); + init_req_counter(layer,layer->max_configure); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + break; + case FSM_Opened: + if (layer->layer_down) layer->layer_down(layer); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + layer->fsm_state=FSM_Req_Sent; + break; + default: + break; + } +} + +void ppp_fsm_recv_term_req(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Opened: + if (layer->layer_down) layer->layer_down(layer); + //send_term_req(layer); + layer->send_term_ack(layer); + //if (layer->zero_req_cnt) layer->zero_req_cnt(layer); + zero_req_counter(layer); + layer->fsm_state=FSM_Stopping; + break; + case FSM_Req_Sent: + case FSM_Ack_Rcvd: + case FSM_Ack_Sent: + layer->send_term_ack(layer); + layer->fsm_state=FSM_Req_Sent; + break; + default: + layer->send_term_ack(layer); + break; + } +} + +void ppp_fsm_recv_term_ack(struct ppp_fsm_t *layer) +{ + stop_timer(layer); + switch(layer->fsm_state) + { + case FSM_Closing: + layer->fsm_state=FSM_Closed; + if (layer->layer_finished) layer->layer_finished(layer); + break; + case FSM_Stopping: + layer->fsm_state=FSM_Stopped; + if (layer->layer_finished) layer->layer_finished(layer); + break; + case FSM_Ack_Rcvd: + layer->fsm_state=FSM_Req_Sent; + break; + case FSM_Opened: + if (layer->layer_down) layer->layer_down(layer); + --layer->restart_counter; + if (layer->send_conf_req) layer->send_conf_req(layer); + layer->fsm_state=FSM_Req_Sent; + break; + default: + break; + } +} + +void ppp_fsm_recv_unk(struct ppp_fsm_t *layer) +{ + if (layer->send_code_rej) layer->send_code_rej(layer); +} + +void ppp_fsm_recv_code_rej_perm(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Ack_Rcvd: + layer->fsm_state=FSM_Req_Sent; + break; + default: + break; + } +} + +void ppp_fsm_recv_code_rej_bad(struct ppp_fsm_t *layer) +{ + switch(layer->fsm_state) + { + case FSM_Opened: + if (layer->layer_down) layer->layer_down(layer); + --layer->restart_counter; + layer->send_term_req(layer); + layer->fsm_state=FSM_Stopping; + break; + case FSM_Closing: + layer->fsm_state=FSM_Closed; + if (layer->layer_finished) layer->layer_finished(layer); + break; + case FSM_Stopping: + case FSM_Req_Sent: + case FSM_Ack_Rcvd: + case FSM_Ack_Sent: + layer->fsm_state=FSM_Stopped; + if (layer->layer_finished) layer->layer_finished(layer); + break; + default: + break; + } +} + +static void stop_timer(struct ppp_fsm_t *fsm) +{ + if (fsm->restart_timer.tpd) + triton_timer_del(&fsm->restart_timer); +} +static void init_req_counter(struct ppp_fsm_t *layer,int timeout) +{ + layer->restart_counter = timeout; + + if (!layer->restart_timer.tpd) + triton_timer_add(layer->ppp->ctrl->ctx, &layer->restart_timer, 0); +} +static void zero_req_counter(struct ppp_fsm_t *layer) +{ + layer->restart_counter=0; + + if (!layer->restart_timer.tpd) + triton_timer_add(layer->ppp->ctrl->ctx, &layer->restart_timer, 0); +} + +static void restart_timer_func(struct triton_timer_t *t) +{ + struct ppp_fsm_t *layer = container_of(t, typeof(*layer), restart_timer); + + log_ppp_debug("fsm timeout\n"); + + if (layer->restart_counter>0) + ppp_fsm_timeout0(layer); + else + ppp_fsm_timeout1(layer); +} + +static void load_config(void) +{ + char *opt; + + opt = conf_get_opt("ppp", "max-terminate"); + if (opt && atoi(opt) > 0) + conf_max_terminate = atoi(opt); + + opt = conf_get_opt("ppp", "max-configure"); + if (opt && atoi(opt) > 0) + conf_max_configure = atoi(opt); + + opt = conf_get_opt("ppp", "max-failure"); + if (opt && atoi(opt) > 0) + conf_max_failure = atoi(opt); + + opt = conf_get_opt("ppp", "timeout"); + if (opt && atoi(opt) > 0) + conf_timeout = atoi(opt); +} + +void __init fsm_init(void) +{ + load_config(); + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); +} + diff --git a/accel-pppd/ppp/ppp_fsm.h b/accel-pppd/ppp/ppp_fsm.h new file mode 100644 index 0000000..6010240 --- /dev/null +++ b/accel-pppd/ppp/ppp_fsm.h @@ -0,0 +1,72 @@ +#ifndef PPP_FSM_H +#define PPP_FSM_H + +typedef enum {FSM_Initial=0,FSM_Starting,FSM_Closed,FSM_Stopped,FSM_Closing,FSM_Stopping,FSM_Req_Sent,FSM_Ack_Rcvd,FSM_Ack_Sent,FSM_Opened} FSM_STATE; +/* + * CP (LCP, IPCP, etc.) codes. + */ +#define CONFREQ 1 /* Configuration Request */ +#define CONFACK 2 /* Configuration Ack */ +#define CONFNAK 3 /* Configuration Nak */ +#define CONFREJ 4 /* Configuration Reject */ +#define TERMREQ 5 /* Termination Request */ +#define TERMACK 6 /* Termination Ack */ +#define CODEREJ 7 /* Code Reject */ +#define PROTOREJ 8 /* Code Reject */ +#define ECHOREQ 9 /* Echo Request */ +#define ECHOREP 10 /* Echo Reply */ +#define IDENT 12 /* Identification */ + +struct ppp_t; + +struct ppp_fsm_t +{ + struct ppp_t *ppp; + FSM_STATE fsm_state; + uint16_t proto; + + struct triton_timer_t restart_timer; + int restart_counter; + int max_terminate; + int max_configure; + int max_failure; + int timeout; + int conf_failure; + + int id; + int recv_id; + + //fsm handling + void (*layer_up)(struct ppp_fsm_t*); + void (*layer_down)(struct ppp_fsm_t*); + void (*layer_started)(struct ppp_fsm_t*); + void (*layer_finished)(struct ppp_fsm_t*); + int (*send_conf_req)(struct ppp_fsm_t*); + void (*send_conf_ack)(struct ppp_fsm_t*); + void (*send_conf_nak)(struct ppp_fsm_t*); + void (*send_conf_rej)(struct ppp_fsm_t*); + void (*send_code_rej)(struct ppp_fsm_t*); + void (*send_term_req)(struct ppp_fsm_t*); + void (*send_term_ack)(struct ppp_fsm_t*); +}; + +void ppp_fsm_init(struct ppp_fsm_t*); +void ppp_fsm_free(struct ppp_fsm_t*); + +int ppp_fsm_lower_up(struct ppp_fsm_t*); +void ppp_fsm_lower_down(struct ppp_fsm_t*); +int ppp_fsm_open(struct ppp_fsm_t*); +void ppp_fsm_close(struct ppp_fsm_t*); +void ppp_fsm_timeout0(struct ppp_fsm_t *layer); +void ppp_fsm_timeout1(struct ppp_fsm_t *layer); +void ppp_fsm_recv_conf_req_ack(struct ppp_fsm_t *layer); +void ppp_fsm_recv_conf_req_nak(struct ppp_fsm_t *layer); +void ppp_fsm_recv_conf_req_rej(struct ppp_fsm_t *layer); +void ppp_fsm_recv_conf_ack(struct ppp_fsm_t *layer); +void ppp_fsm_recv_conf_rej(struct ppp_fsm_t *layer); +void ppp_fsm_recv_term_req(struct ppp_fsm_t *layer); +void ppp_fsm_recv_term_ack(struct ppp_fsm_t *layer); +void ppp_fsm_recv_unk(struct ppp_fsm_t *layer); +void ppp_fsm_recv_code_rej_bad(struct ppp_fsm_t *layer); + +#endif diff --git a/accel-pppd/ppp/ppp_ipcp.c b/accel-pppd/ppp/ppp_ipcp.c new file mode 100644 index 0000000..7cdcdbc --- /dev/null +++ b/accel-pppd/ppp/ppp_ipcp.c @@ -0,0 +1,665 @@ +#include +#include +#include +#include +#include "linux_ppp.h" + +#include "triton.h" + +#include "log.h" + +#include "ppp.h" +#include "ppp_ipcp.h" + +#include "memdebug.h" + +struct recv_opt_t +{ + struct list_head entry; + struct ipcp_opt_hdr_t *hdr; + int len; + int state; + struct ipcp_option_t *lopt; +}; + +static LIST_HEAD(option_handlers); + +static void ipcp_layer_up(struct ppp_fsm_t*); +static void ipcp_layer_down(struct ppp_fsm_t*); +static int send_conf_req(struct ppp_fsm_t*); +static void send_conf_ack(struct ppp_fsm_t*); +static void send_conf_nak(struct ppp_fsm_t*); +static void send_conf_rej(struct ppp_fsm_t*); +static void ipcp_recv(struct ppp_handler_t*); +static void send_term_req(struct ppp_fsm_t *fsm); +static void send_term_ack(struct ppp_fsm_t *fsm); + +static void ipcp_options_init(struct ppp_ipcp_t *ipcp) +{ + struct ipcp_option_t *lopt; + struct ipcp_option_handler_t *h; + + ipcp->conf_req_len = sizeof(struct ipcp_hdr_t); + + list_for_each_entry(h,&option_handlers,entry) { + lopt = h->init(ipcp); + if (lopt) { + lopt->h = h; + list_add_tail(&lopt->entry, &ipcp->options); + ipcp->conf_req_len += lopt->len; + } + } +} + +static void ipcp_options_free(struct ppp_ipcp_t *ipcp) +{ + struct ipcp_option_t *lopt; + + while (!list_empty(&ipcp->options)) { + lopt = list_entry(ipcp->options.next, typeof(*lopt), entry); + list_del(&lopt->entry); + lopt->h->free(ipcp, lopt); + } +} + +static struct ppp_layer_data_t *ipcp_layer_init(struct ppp_t *ppp) +{ + struct ppp_ipcp_t *ipcp = _malloc(sizeof(*ipcp)); + memset(ipcp, 0, sizeof(*ipcp)); + + log_ppp_debug("ipcp_layer_init\n"); + + ipcp->ppp = ppp; + ipcp->fsm.ppp = ppp; + + ipcp->hnd.proto = PPP_IPCP; + ipcp->hnd.recv = ipcp_recv; + + ppp_register_unit_handler(ppp, &ipcp->hnd); + + ipcp->fsm.proto = PPP_IPCP; + ppp_fsm_init(&ipcp->fsm); + + ipcp->fsm.layer_up = ipcp_layer_up; + ipcp->fsm.layer_finished = ipcp_layer_down; + ipcp->fsm.send_conf_req = send_conf_req; + ipcp->fsm.send_conf_ack = send_conf_ack; + ipcp->fsm.send_conf_nak = send_conf_nak; + ipcp->fsm.send_conf_rej = send_conf_rej; + ipcp->fsm.send_term_req = send_term_req; + ipcp->fsm.send_term_ack = send_term_ack; + + INIT_LIST_HEAD(&ipcp->options); + INIT_LIST_HEAD(&ipcp->ropt_list); + + return &ipcp->ld; +} + +int ipcp_layer_start(struct ppp_layer_data_t *ld) +{ + struct ppp_ipcp_t *ipcp = container_of(ld, typeof(*ipcp), ld); + + log_ppp_debug("ipcp_layer_start\n"); + + ipcp_options_init(ipcp); + ppp_fsm_lower_up(&ipcp->fsm); + if (ppp_fsm_open(&ipcp->fsm)) + return -1; + + return 0; +} + +void ipcp_layer_finish(struct ppp_layer_data_t *ld) +{ + struct ppp_ipcp_t *ipcp = container_of(ld, typeof(*ipcp), ld); + + log_ppp_debug("ipcp_layer_finish\n"); + + ipcp->fsm.fsm_state = FSM_Closed; + + log_ppp_debug("ipcp_layer_finished\n"); + ppp_layer_finished(ipcp->ppp, &ipcp->ld); +} + +void ipcp_layer_free(struct ppp_layer_data_t *ld) +{ + struct ppp_ipcp_t *ipcp = container_of(ld, typeof(*ipcp), ld); + + log_ppp_debug("ipcp_layer_free\n"); + + ppp_unregister_handler(ipcp->ppp, &ipcp->hnd); + ipcp_options_free(ipcp); + ppp_fsm_free(&ipcp->fsm); + + _free(ipcp); +} + +static void ipcp_layer_up(struct ppp_fsm_t *fsm) +{ + struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); + + log_ppp_debug("ipcp_layer_started\n"); + + if (!ipcp->started) { + ipcp->started = 1; + ppp_layer_started(ipcp->ppp, &ipcp->ld); + } +} + +static void ipcp_layer_down(struct ppp_fsm_t *fsm) +{ + struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); + + log_ppp_debug("ipcp_layer_finished\n"); + + if (ipcp->started) { + ipcp->started = 0; + ppp_layer_finished(ipcp->ppp, &ipcp->ld); + } else + ppp_terminate(ipcp->ppp, TERM_NAS_ERROR, 0); +} + +static void print_ropt(struct recv_opt_t *ropt) +{ + int i; + uint8_t *ptr = (uint8_t*)ropt->hdr; + + log_ppp_info2("<"); + for (i = 0; i < ropt->len; i++) { + log_ppp_info2(" %x", ptr[i]); + } + log_ppp_info2(" >"); +} + +static int send_conf_req(struct ppp_fsm_t *fsm) +{ + struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); + uint8_t *buf = _malloc(ipcp->conf_req_len), *ptr = buf; + struct ipcp_hdr_t *ipcp_hdr = (struct ipcp_hdr_t*)ptr; + struct ipcp_option_t *lopt; + int n; + + ipcp_hdr->proto = htons(PPP_IPCP); + ipcp_hdr->code = CONFREQ; + ipcp_hdr->id = ++ipcp->fsm.id; + ipcp_hdr->len = 0; + + ptr += sizeof(*ipcp_hdr); + + list_for_each_entry(lopt, &ipcp->options, entry) { + n = lopt->h->send_conf_req(ipcp, lopt, ptr); + if (n < 0) + return -1; + if (n) { + ptr += n; + lopt->print = 1; + } else + lopt->print = 0; + } + + if (conf_ppp_verbose) { + log_ppp_info2("send [IPCP ConfReq id=%x", ipcp_hdr->id); + list_for_each_entry(lopt,&ipcp->options,entry) { + if (lopt->print) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, NULL); + } + } + log_ppp_info2("]\n"); + } + + ipcp_hdr->len = htons(ptr - buf - 2); + ppp_unit_send(ipcp->ppp, ipcp_hdr, ptr - buf); + + _free(buf); + + return 0; +} + +static void send_conf_ack(struct ppp_fsm_t *fsm) +{ + struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); + struct ipcp_hdr_t *hdr = (struct ipcp_hdr_t*)ipcp->ppp->unit_buf; + + hdr->code = CONFACK; + + if (conf_ppp_verbose) + log_ppp_info2("send [IPCP ConfAck id=%x]\n", ipcp->fsm.recv_id); + + ppp_unit_send(ipcp->ppp, hdr, ntohs(hdr->len) + 2); +} + +static void send_conf_nak(struct ppp_fsm_t *fsm) +{ + struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); + uint8_t *buf = _malloc(ipcp->conf_req_len), *ptr = buf; + struct ipcp_hdr_t *ipcp_hdr = (struct ipcp_hdr_t*)ptr; + struct recv_opt_t *ropt; + + if (conf_ppp_verbose) + log_ppp_info2("send [IPCP ConfNak id=%x", ipcp->fsm.recv_id); + + ipcp_hdr->proto = htons(PPP_IPCP); + ipcp_hdr->code = CONFNAK; + ipcp_hdr->id = ipcp->fsm.recv_id; + ipcp_hdr->len = 0; + + ptr += sizeof(*ipcp_hdr); + + list_for_each_entry(ropt, &ipcp->ropt_list, entry) { + if (ropt->state == IPCP_OPT_NAK) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + ropt->lopt->h->print(log_ppp_info2, ropt->lopt, NULL); + } + ptr += ropt->lopt->h->send_conf_nak(ipcp, ropt->lopt, ptr); + } + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + ipcp_hdr->len = htons(ptr-buf-2); + ppp_unit_send(ipcp->ppp, ipcp_hdr, ptr - buf); + + _free(buf); +} + +static void send_conf_rej(struct ppp_fsm_t *fsm) +{ + struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); + uint8_t *buf = _malloc(ipcp->ropt_len + sizeof(struct ipcp_hdr_t)), *ptr = buf; + struct ipcp_hdr_t *ipcp_hdr = (struct ipcp_hdr_t*)ptr; + struct recv_opt_t *ropt; + + if (conf_ppp_verbose) + log_ppp_info2("send [IPCP ConfRej id=%x", ipcp->fsm.recv_id); + + ipcp_hdr->proto = htons(PPP_IPCP); + ipcp_hdr->code = CONFREJ; + ipcp_hdr->id = ipcp->fsm.recv_id; + ipcp_hdr->len = 0; + + ptr += sizeof(*ipcp_hdr); + + list_for_each_entry(ropt, &ipcp->ropt_list, entry) { + if (ropt->state == IPCP_OPT_REJ) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + if (ropt->lopt) + ropt->lopt->h->print(log_ppp_info2, ropt->lopt, (uint8_t*)ropt->hdr); + else + print_ropt(ropt); + } + memcpy(ptr, ropt->hdr, ropt->len); + ptr += ropt->len; + } + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + ipcp_hdr->len = htons(ptr - buf - 2); + ppp_unit_send(ipcp->ppp, ipcp_hdr, ptr-buf); + + _free(buf); +} + +static int ipcp_recv_conf_req(struct ppp_ipcp_t *ipcp, uint8_t *data, int size) +{ + struct ipcp_opt_hdr_t *hdr; + struct recv_opt_t *ropt; + struct ipcp_option_t *lopt; + int r,ret = 1; + + ipcp->ropt_len = size; + + while (size > 0) { + hdr = (struct ipcp_opt_hdr_t *)data; + + ropt = _malloc(sizeof(*ropt)); + memset(ropt, 0, sizeof(*ropt)); + + if (hdr->len > size) + ropt->len = size; + else + ropt->len = hdr->len; + ropt->hdr = hdr; + ropt->state = IPCP_OPT_NONE; + list_add_tail(&ropt->entry, &ipcp->ropt_list); + + data += ropt->len; + size -= ropt->len; + } + + list_for_each_entry(lopt, &ipcp->options, entry) + lopt->state=IPCP_OPT_NONE; + + if (conf_ppp_verbose) { + log_ppp_info2("recv [IPCP ConfReq id=%x", ipcp->fsm.recv_id); + + list_for_each_entry(ropt, &ipcp->ropt_list, entry) { + list_for_each_entry(lopt, &ipcp->options, entry) { + if (lopt->id == ropt->hdr->id) { + ropt->lopt = lopt; + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, (uint8_t*)ropt->hdr); + break; + } + } + if (!ropt->lopt) { + log_ppp_info2(" "); + print_ropt(ropt); + } + } + log_ppp_info2("]\n"); + } + + list_for_each_entry(ropt, &ipcp->ropt_list, entry) { + list_for_each_entry(lopt, &ipcp->options, entry) { + if (lopt->id == ropt->hdr->id) { + r = lopt->h->recv_conf_req(ipcp, lopt, (uint8_t*)ropt->hdr); + if (ipcp->ppp->stop_time) + return -1; + lopt->state = r; + ropt->state = r; + ropt->lopt = lopt; + if (r < ret) + ret = r; + break; + } + } + if (!ropt->lopt) { + ropt->state = IPCP_OPT_REJ; + ret = IPCP_OPT_REJ; + } + } + + + /*list_for_each_entry(lopt,&ipcp->options,entry) + { + if (lopt->state==IPCP_OPT_NONE) + { + r=lopt->h->recv_conf_req(ipcp,lopt,NULL); + lopt->state=r; + if (rropt_list)) { + ropt = list_entry(ipcp->ropt_list.next, typeof(*ropt), entry); + list_del(&ropt->entry); + _free(ropt); + } +} + +static int ipcp_recv_conf_rej(struct ppp_ipcp_t *ipcp, uint8_t *data, int size) +{ + struct ipcp_opt_hdr_t *hdr; + struct ipcp_option_t *lopt; + int res = 0; + + if (conf_ppp_verbose) + log_ppp_info2("recv [IPCP ConfRej id=%x", ipcp->fsm.recv_id); + + if (ipcp->fsm.recv_id != ipcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info2(": id mismatch ]\n"); + return 0; + } + + while (size > 0) { + hdr = (struct ipcp_opt_hdr_t *)data; + + list_for_each_entry(lopt, &ipcp->options, entry) { + if (lopt->id == hdr->id) { + if (!lopt->h->recv_conf_rej) + res = -1; + else if (lopt->h->recv_conf_rej(ipcp, lopt, data)) + res = -1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + return res; +} + +static int ipcp_recv_conf_nak(struct ppp_ipcp_t *ipcp, uint8_t *data, int size) +{ + struct ipcp_opt_hdr_t *hdr; + struct ipcp_option_t *lopt; + int res = 0; + + if (conf_ppp_verbose) + log_ppp_info2("recv [IPCP ConfNak id=%x", ipcp->fsm.recv_id); + + if (ipcp->fsm.recv_id != ipcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info2(": id mismatch ]\n"); + return 0; + } + + while (size > 0) { + hdr = (struct ipcp_opt_hdr_t *)data; + + list_for_each_entry(lopt, &ipcp->options, entry) { + if (lopt->id == hdr->id) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2,lopt,data); + } + if (lopt->h->recv_conf_nak && lopt->h->recv_conf_nak(ipcp, lopt, data)) + res =- 1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + return res; +} + +static int ipcp_recv_conf_ack(struct ppp_ipcp_t *ipcp, uint8_t *data, int size) +{ + struct ipcp_opt_hdr_t *hdr; + struct ipcp_option_t *lopt; + int res = 0; + + if (conf_ppp_verbose) + log_ppp_info2("recv [IPCP ConfAck id=%x", ipcp->fsm.recv_id); + + if (ipcp->fsm.recv_id != ipcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info2(": id mismatch ]\n"); + return 0; + } + + while (size > 0) { + hdr = (struct ipcp_opt_hdr_t *)data; + + list_for_each_entry(lopt, &ipcp->options, entry) { + if (lopt->id == hdr->id) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, data); + } + if (!lopt->h->recv_conf_ack) + break; + if (lopt->h->recv_conf_ack(ipcp, lopt, data)) + res = -1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + return res; +} + +static void send_term_req(struct ppp_fsm_t *fsm) +{ + struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); + struct ipcp_hdr_t hdr = { + .proto = htons(PPP_IPCP), + .code = TERMREQ, + .id = ++ipcp->fsm.id, + .len = htons(4), + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [IPCP TermReq id=%i]\n", hdr.id); + + ppp_unit_send(ipcp->ppp, &hdr, 6); +} + +static void send_term_ack(struct ppp_fsm_t *fsm) +{ + struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); + struct ipcp_hdr_t hdr = { + .proto = htons(PPP_IPCP), + .code = TERMACK, + .id = ipcp->fsm.recv_id, + .len = htons(4), + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [IPCP TermAck id=%i]\n", hdr.id); + + ppp_unit_send(ipcp->ppp, &hdr, 6); +} + +static void ipcp_recv(struct ppp_handler_t*h) +{ + struct ipcp_hdr_t *hdr; + struct ppp_ipcp_t *ipcp = container_of(h, typeof(*ipcp), hnd); + int r; + + if (ipcp->fsm.fsm_state == FSM_Initial || ipcp->fsm.fsm_state == FSM_Closed || ipcp->ppp->terminating) { + if (conf_ppp_verbose) + log_ppp_warn("IPCP: discarding packet\n"); + return; + } + + if (ipcp->ppp->unit_buf_size < PPP_HEADERLEN + 2) { + log_ppp_warn("IPCP: short packet received\n"); + return; + } + + hdr = (struct ipcp_hdr_t *)ipcp->ppp->unit_buf; + if (ntohs(hdr->len) < PPP_HEADERLEN) { + log_ppp_warn("IPCP: short packet received\n"); + return; + } + + ipcp->fsm.recv_id = hdr->id; + switch(hdr->code) { + case CONFREQ: + r = ipcp_recv_conf_req(ipcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); + if (ipcp->ppp->stop_time) { + ipcp_free_conf_req(ipcp); + return; + } + switch(r) { + case IPCP_OPT_ACK: + ppp_fsm_recv_conf_req_ack(&ipcp->fsm); + break; + case IPCP_OPT_NAK: + ppp_fsm_recv_conf_req_nak(&ipcp->fsm); + break; + case IPCP_OPT_REJ: + ppp_fsm_recv_conf_req_rej(&ipcp->fsm); + break; + } + ipcp_free_conf_req(ipcp); + if (r == IPCP_OPT_FAIL) + ppp_terminate(ipcp->ppp, TERM_USER_ERROR, 0); + break; + case CONFACK: + if (ipcp_recv_conf_ack(ipcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) + ppp_terminate(ipcp->ppp, TERM_USER_ERROR, 0); + else + ppp_fsm_recv_conf_ack(&ipcp->fsm); + break; + case CONFNAK: + ipcp_recv_conf_nak(ipcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); + ppp_fsm_recv_conf_rej(&ipcp->fsm); + break; + case CONFREJ: + if (ipcp_recv_conf_rej(ipcp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) + ppp_terminate(ipcp->ppp, TERM_USER_ERROR, 0); + else + ppp_fsm_recv_conf_rej(&ipcp->fsm); + break; + case TERMREQ: + if (conf_ppp_verbose) + log_ppp_info2("recv [IPCP TermReq id=%x]\n", hdr->id); + ppp_fsm_recv_term_req(&ipcp->fsm); + ppp_terminate(ipcp->ppp, TERM_USER_REQUEST, 0); + break; + case TERMACK: + if (conf_ppp_verbose) + log_ppp_info2("recv [IPCP TermAck id=%x]\n", hdr->id); + //ppp_fsm_recv_term_ack(&ipcp->fsm); + //ppp_terminate(ipcp->ppp, 0); + break; + case CODEREJ: + if (conf_ppp_verbose) + log_ppp_info2("recv [IPCP CodeRej id=%x]\n", hdr->id); + ppp_fsm_recv_code_rej_bad(&ipcp->fsm); + break; + default: + ppp_fsm_recv_unk(&ipcp->fsm); + break; + } +} + +int ipcp_option_register(struct ipcp_option_handler_t *h) +{ + /*struct ipcp_option_drv_t *p; + + list_for_each_entry(p,option_drv_list,entry) + if (p->id==h->id) + return -1;*/ + + list_add_tail(&h->entry, &option_handlers); + + return 0; +} + +static struct ppp_layer_t ipcp_layer = +{ + .init = ipcp_layer_init, + .start = ipcp_layer_start, + .finish = ipcp_layer_finish, + .free = ipcp_layer_free, +}; + +static void __init ipcp_init(void) +{ + ppp_register_layer("ipcp", &ipcp_layer); +} + diff --git a/accel-pppd/ppp/ppp_ipcp.h b/accel-pppd/ppp/ppp_ipcp.h new file mode 100644 index 0000000..c955987 --- /dev/null +++ b/accel-pppd/ppp/ppp_ipcp.h @@ -0,0 +1,96 @@ +#ifndef PPP_IPCP_H +#define PPP_IPCP_H + +#include + +#include "triton.h" +#include "ppp_fsm.h" +/* + * Options. + */ +#define CI_COMP 2 /* IP-Compress-Protocol */ +#define CI_ADDR 3 /* IP-Address */ +#define CI_DNS1 129 /* Primary-DNS-Address */ +#define CI_DNS2 131 /* Secondary-DNS-Address */ + +struct ipcp_hdr_t +{ + uint16_t proto; + uint8_t code; + uint8_t id; + uint16_t len; +} __attribute__((packed)); +struct ipcp_opt_hdr_t +{ + uint8_t id; + uint8_t len; +} __attribute__((packed)); +struct ipcp_opt8_t +{ + struct ipcp_opt_hdr_t hdr; + uint8_t val; +} __attribute__((packed)); +struct ipcp_opt16_t +{ + struct ipcp_opt_hdr_t hdr; + uint16_t val; +} __attribute__((packed)); +struct ipcp_opt32_t +{ + struct ipcp_opt_hdr_t hdr; + uint32_t val; +} __attribute__((packed)); + +#define IPCP_OPT_NONE 0 +#define IPCP_OPT_ACK 1 +#define IPCP_OPT_NAK -1 +#define IPCP_OPT_REJ -2 +#define IPCP_OPT_FAIL -3 + +struct ppp_ipcp_t; +struct ipcp_option_handler_t; + +struct ipcp_option_t +{ + struct list_head entry; + int id; + int len; + int state; + int print:1; + struct ipcp_option_handler_t *h; +}; + +struct ipcp_option_handler_t +{ + struct list_head entry; + struct ipcp_option_t* (*init)(struct ppp_ipcp_t*); + int (*send_conf_req)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); + int (*send_conf_rej)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); + int (*send_conf_nak)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); + int (*recv_conf_req)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); + int (*recv_conf_rej)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); + int (*recv_conf_nak)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); + int (*recv_conf_ack)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); + void (*free)(struct ppp_ipcp_t*,struct ipcp_option_t*); + void (*print)(void (*print)(const char *fmt,...), struct ipcp_option_t*,uint8_t*); +}; + +struct ppp_ipcp_t +{ + struct ppp_layer_data_t ld; + struct ppp_handler_t hnd; + struct ppp_fsm_t fsm; + struct ppp_t *ppp; + struct list_head options; + + struct list_head ropt_list; // last received ConfReq + int ropt_len; + + int conf_req_len; + int started:1; +}; + +int ipcp_option_register(struct ipcp_option_handler_t *h); + +#endif + diff --git a/accel-pppd/ppp/ppp_lcp.c b/accel-pppd/ppp/ppp_lcp.c new file mode 100644 index 0000000..e40e321 --- /dev/null +++ b/accel-pppd/ppp/ppp_lcp.c @@ -0,0 +1,847 @@ +#include +#include +#include +#include +#include "linux_ppp.h" + +#include "triton.h" + +#include "log.h" + +#include "ppp.h" +#include "ppp_lcp.h" +#include "events.h" + +#include "memdebug.h" + +struct recv_opt_t +{ + struct list_head entry; + struct lcp_opt_hdr_t *hdr; + int len; + int state; + struct lcp_option_t *lopt; +}; + +static int conf_echo_interval = 0; +static int conf_echo_failure = 3; + +static LIST_HEAD(option_handlers); +static struct ppp_layer_t lcp_layer; + +static void lcp_layer_up(struct ppp_fsm_t*); +static void lcp_layer_down(struct ppp_fsm_t*); +static void lcp_layer_finished(struct ppp_fsm_t*); +static int send_conf_req(struct ppp_fsm_t*); +static void send_conf_ack(struct ppp_fsm_t*); +static void send_conf_nak(struct ppp_fsm_t*); +static void send_conf_rej(struct ppp_fsm_t*); +static void send_code_rej(struct ppp_fsm_t*); +static void start_echo(struct ppp_lcp_t *lcp); +static void stop_echo(struct ppp_lcp_t *lcp); +static void send_term_req(struct ppp_fsm_t *fsm); +static void send_term_ack(struct ppp_fsm_t *fsm); +static void lcp_recv(struct ppp_handler_t*); + +static void lcp_options_init(struct ppp_lcp_t *lcp) +{ + struct lcp_option_t *lopt; + struct lcp_option_handler_t *h; + + INIT_LIST_HEAD(&lcp->options); + + lcp->conf_req_len = sizeof(struct lcp_hdr_t); + + list_for_each_entry(h, &option_handlers, entry) { + lopt = h->init(lcp); + if (lopt) { + lopt->h = h; + list_add_tail(&lopt->entry, &lcp->options); + lcp->conf_req_len += lopt->len; + } + } +} + +static void lcp_options_free(struct ppp_lcp_t *lcp) +{ + struct lcp_option_t *lopt; + + while (!list_empty(&lcp->options)) { + lopt = list_entry(lcp->options.next, typeof(*lopt), entry); + list_del(&lopt->entry); + lopt->h->free(lcp, lopt); + } +} + +static struct ppp_layer_data_t *lcp_layer_init(struct ppp_t *ppp) +{ + struct ppp_lcp_t *lcp = _malloc(sizeof(*lcp)); + memset(lcp, 0, sizeof(*lcp)); + + log_ppp_debug("lcp_layer_init\n"); + + lcp->ppp = ppp; + lcp->fsm.ppp = ppp; + + lcp->hnd.proto = PPP_LCP; + lcp->hnd.recv = lcp_recv; + + ppp_register_chan_handler(ppp, &lcp->hnd); + + lcp->fsm.proto = PPP_LCP; + ppp_fsm_init(&lcp->fsm); + + lcp->fsm.layer_up = lcp_layer_up; + lcp->fsm.layer_down = lcp_layer_down; + lcp->fsm.layer_finished = lcp_layer_finished; + lcp->fsm.send_conf_req = send_conf_req; + lcp->fsm.send_conf_ack = send_conf_ack; + lcp->fsm.send_conf_nak = send_conf_nak; + lcp->fsm.send_conf_rej = send_conf_rej; + lcp->fsm.send_code_rej = send_code_rej; + lcp->fsm.send_term_req = send_term_req; + lcp->fsm.send_term_ack = send_term_ack; + + INIT_LIST_HEAD(&lcp->ropt_list); + + return &lcp->ld; +} + +int lcp_layer_start(struct ppp_layer_data_t *ld) +{ + struct ppp_lcp_t *lcp = container_of(ld, typeof(*lcp), ld); + + log_ppp_debug("lcp_layer_start\n"); + + lcp_options_init(lcp); + ppp_fsm_lower_up(&lcp->fsm); + if (ppp_fsm_open(&lcp->fsm)) + return -1; + + return 0; +} + +static void _lcp_layer_finished(struct ppp_lcp_t *lcp) +{ + ppp_layer_finished(lcp->ppp, &lcp->ld); +} + +void lcp_layer_finish(struct ppp_layer_data_t *ld) +{ + struct ppp_lcp_t *lcp = container_of(ld,typeof(*lcp),ld); + + log_ppp_debug("lcp_layer_finish\n"); + + if (lcp->started) { + stop_echo(lcp); + ppp_fsm_close(&lcp->fsm); + } else + triton_context_call(lcp->ppp->ctrl->ctx, (triton_event_func)_lcp_layer_finished, lcp); +} + +void lcp_layer_free(struct ppp_layer_data_t *ld) +{ + struct ppp_lcp_t *lcp = container_of(ld, typeof(*lcp), ld); + + log_ppp_debug("lcp_layer_free\n"); + + stop_echo(lcp); + ppp_unregister_handler(lcp->ppp, &lcp->hnd); + lcp_options_free(lcp); + ppp_fsm_free(&lcp->fsm); + triton_cancel_call(lcp->ppp->ctrl->ctx, (triton_event_func)_lcp_layer_finished); + + _free(lcp); +} + +static void lcp_layer_up(struct ppp_fsm_t *fsm) +{ + struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); + + log_ppp_debug("lcp_layer_started\n"); + + if (!lcp->started) { + lcp->started = 1; + ppp_layer_started(lcp->ppp, &lcp->ld); + } + start_echo(lcp); +} + +static void lcp_layer_down(struct ppp_fsm_t *fsm) +{ + struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); + //ppp_fsm_close(&lcp->fsm); + stop_echo(lcp); + //ppp_layer_finished(lcp->ppp,&lcp->ld); +} + +static void lcp_layer_finished(struct ppp_fsm_t *fsm) +{ + struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); + + log_ppp_debug("lcp_layer_finished\n"); + + stop_echo(lcp); + if (lcp->started) { + lcp->started = 0; + if (lcp->ppp->terminating) + ppp_layer_finished(lcp->ppp, &lcp->ld); + else + ppp_terminate(lcp->ppp, TERM_NAS_ERROR, 0); + } else + ppp_terminate(lcp->ppp, TERM_NAS_ERROR, 0); +} + +static void print_ropt(struct recv_opt_t *ropt) +{ + int i; + uint8_t *ptr = (uint8_t*)ropt->hdr; + + log_ppp_info2("<"); + for (i = 0; i < ropt->len; i++) { + log_ppp_info2(" %x", ptr[i]); + } + log_ppp_info2(" >"); +} + +static int send_conf_req(struct ppp_fsm_t *fsm) +{ + struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); + uint8_t *buf = _malloc(lcp->conf_req_len), *ptr = buf; + struct lcp_hdr_t *lcp_hdr = (struct lcp_hdr_t*)ptr; + struct lcp_option_t *lopt; + int n; + + lcp_hdr->proto = htons(PPP_LCP); + lcp_hdr->code = CONFREQ; + lcp_hdr->id = ++lcp->fsm.id; + lcp_hdr->len = 0; + + ptr += sizeof(*lcp_hdr); + + list_for_each_entry(lopt, &lcp->options, entry) { + n = lopt->h->send_conf_req(lcp, lopt, ptr); + if (n < 0) + return -1; + if (n) { + ptr += n; + lopt->print = 1; + } else + lopt->print = 0; + } + + if (conf_ppp_verbose) { + log_ppp_info2("send [LCP ConfReq id=%x", lcp_hdr->id); + list_for_each_entry(lopt,&lcp->options,entry) { + if (lopt->print) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, NULL); + } + } + log_ppp_info2("]\n"); + } + + lcp_hdr->len = htons(ptr - buf - 2); + ppp_chan_send(lcp->ppp, lcp_hdr, ptr-buf); + + _free(buf); + + return 0; +} + +static void send_conf_ack(struct ppp_fsm_t *fsm) +{ + struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); + struct lcp_hdr_t *hdr = (struct lcp_hdr_t*)lcp->ppp->chan_buf; + + hdr->code = CONFACK; + + if (conf_ppp_verbose) + log_ppp_info2("send [LCP ConfAck id=%x ]\n", lcp->fsm.recv_id); + + ppp_chan_send(lcp->ppp, hdr, ntohs(hdr->len) + 2); +} + +static void send_code_rej(struct ppp_fsm_t *fsm) +{ + struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); + struct lcp_hdr_t *hdr = (struct lcp_hdr_t*)lcp->ppp->chan_buf; + + hdr->code = CONFACK; + + if (conf_ppp_verbose) + log_ppp_info2("send [LCP CodeRej %x id=%x ]\n",hdr->code, lcp->fsm.recv_id); + + ppp_chan_send(lcp->ppp, hdr, ntohs(hdr->len) + 2); +} + +static void send_conf_nak(struct ppp_fsm_t *fsm) +{ + struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); + uint8_t *buf = _malloc(lcp->conf_req_len), *ptr = buf; + struct lcp_hdr_t *lcp_hdr = (struct lcp_hdr_t*)ptr; + struct lcp_option_t *lopt; + + if (conf_ppp_verbose) + log_ppp_info2("send [LCP ConfNak id=%x", lcp->fsm.recv_id); + + lcp_hdr->proto = htons(PPP_LCP); + lcp_hdr->code = CONFNAK; + lcp_hdr->id = lcp->fsm.recv_id; + lcp_hdr->len = 0; + + ptr += sizeof(*lcp_hdr); + + list_for_each_entry(lopt, &lcp->options, entry) { + if (lopt->state == LCP_OPT_NAK) { + ptr+=lopt->h->send_conf_nak(lcp,lopt,ptr); + + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, NULL); + } + } + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + lcp_hdr->len = htons(ptr - buf - 2); + ppp_chan_send(lcp->ppp, lcp_hdr,ptr - buf); + + _free(buf); +} + +static void send_conf_rej(struct ppp_fsm_t *fsm) +{ + struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); + uint8_t *buf = _malloc(lcp->ropt_len + sizeof(struct lcp_hdr_t)), *ptr = buf; + struct lcp_hdr_t *lcp_hdr = (struct lcp_hdr_t*)ptr; + struct recv_opt_t *ropt; + + if (conf_ppp_verbose) + log_ppp_info2("send [LCP ConfRej id=%x ", lcp->fsm.recv_id); + + lcp_hdr->proto = htons(PPP_LCP); + lcp_hdr->code = CONFREJ; + lcp_hdr->id = lcp->fsm.recv_id; + lcp_hdr->len = 0; + + ptr += sizeof(*lcp_hdr); + + list_for_each_entry(ropt, &lcp->ropt_list, entry) { + if (ropt->state == LCP_OPT_REJ) { + memcpy(ptr, ropt->hdr, ropt->len); + ptr += ropt->len; + + if (conf_ppp_verbose) { + log_ppp_info2(" "); + if (ropt->lopt) + ropt->lopt->h->print(log_ppp_info2, ropt->lopt, (uint8_t*)ropt->hdr); + else + print_ropt(ropt); + } + } + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + lcp_hdr->len = htons(ptr - buf - 2); + ppp_chan_send(lcp->ppp, lcp_hdr, ptr - buf); + + _free(buf); +} + +static int lcp_recv_conf_req(struct ppp_lcp_t *lcp, uint8_t *data, int size) +{ + struct lcp_opt_hdr_t *hdr; + struct recv_opt_t *ropt; + struct lcp_option_t *lopt; + int r, ret = 1; + + lcp->ropt_len = size; + + while (size > 0) { + hdr = (struct lcp_opt_hdr_t *)data; + + ropt = _malloc(sizeof(*ropt)); + memset(ropt, 0, sizeof(*ropt)); + + if (hdr->len > size) + ropt->len = size; + else + ropt->len = hdr->len; + + ropt->hdr = hdr; + ropt->state = LCP_OPT_NONE; + list_add_tail(&ropt->entry, &lcp->ropt_list); + + data += ropt->len; + size -= ropt->len; + } + + list_for_each_entry(lopt, &lcp->options, entry) + lopt->state = LCP_OPT_NONE; + + if (conf_ppp_verbose) + log_ppp_info2("recv [LCP ConfReq id=%x", lcp->fsm.recv_id); + + list_for_each_entry(ropt, &lcp->ropt_list, entry) { + list_for_each_entry(lopt, &lcp->options, entry) { + if (lopt->id == ropt->hdr->id) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, (uint8_t*)ropt->hdr); + } + r = lopt->h->recv_conf_req(lcp, lopt, (uint8_t*)ropt->hdr); + lopt->state = r; + ropt->state = r; + ropt->lopt = lopt; + if (rlopt) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + print_ropt(ropt); + } + ropt->state=LCP_OPT_REJ; + ret=LCP_OPT_REJ; + } + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + /*list_for_each_entry(lopt,&lcp->options,entry) + { + if (lopt->state==LCP_OPT_NONE) + { + r=lopt->h->recv_conf_req(lcp,lopt,NULL); + lopt->state=r; + if (rropt_list)) { + ropt = list_entry(lcp->ropt_list.next, typeof(*ropt), entry); + list_del(&ropt->entry); + _free(ropt); + } +} + +static int lcp_recv_conf_rej(struct ppp_lcp_t *lcp, uint8_t *data, int size) +{ + struct lcp_opt_hdr_t *hdr; + struct lcp_option_t *lopt; + int res = 0; + + if (conf_ppp_verbose) + log_ppp_info2("recv [LCP ConfRej id=%x", lcp->fsm.recv_id); + + if (lcp->fsm.recv_id != lcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info2(": id mismatch ]\n"); + return 0; + } + + while (size > 0) { + hdr = (struct lcp_opt_hdr_t *)data; + + list_for_each_entry(lopt, &lcp->options, entry) { + if (lopt->id == hdr->id) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, (uint8_t*)hdr); + } + if (!lopt->h->recv_conf_rej) + res = -1; + else if (lopt->h->recv_conf_rej(lcp, lopt, data)) + res = -1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + return res; +} + +static int lcp_recv_conf_nak(struct ppp_lcp_t *lcp, uint8_t *data, int size) +{ + struct lcp_opt_hdr_t *hdr; + struct lcp_option_t *lopt; + int res = 0; + + if (conf_ppp_verbose) + log_ppp_info2("recv [LCP ConfNak id=%x", lcp->fsm.recv_id); + + if (lcp->fsm.recv_id != lcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info2(": id mismatch ]\n"); + return 0; + } + + while (size > 0) { + hdr = (struct lcp_opt_hdr_t *)data; + + list_for_each_entry(lopt,&lcp->options,entry) { + if (lopt->id == hdr->id) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, data); + } + if (lopt->h->recv_conf_nak && lopt->h->recv_conf_nak(lcp, lopt, data)) + res = -1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + return res; +} + +static int lcp_recv_conf_ack(struct ppp_lcp_t *lcp, uint8_t *data, int size) +{ + struct lcp_opt_hdr_t *hdr; + struct lcp_option_t *lopt; + int res=0; + + if (conf_ppp_verbose) + log_ppp_info2("recv [LCP ConfAck id=%x", lcp->fsm.recv_id); + + if (lcp->fsm.recv_id != lcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info2(": id mismatch ]\n"); + return 0; + } + + while (size > 0) { + hdr = (struct lcp_opt_hdr_t *)data; + + list_for_each_entry(lopt, &lcp->options, entry) { + if (lopt->id == hdr->id) { + if (conf_ppp_verbose) { + log_ppp_info2(" "); + lopt->h->print(log_ppp_info2, lopt, data); + } + if (!lopt->h->recv_conf_ack) + break; + if (lopt->h->recv_conf_ack(lcp, lopt, data)) + res = -1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info2("]\n"); + + return res; +} + +static void lcp_recv_echo_repl(struct ppp_lcp_t *lcp, uint8_t *data, int size) +{ + uint32_t magic = *(uint32_t *)data; + + if (size != 4) { + log_ppp_error("lcp:echo: magic number size mismatch\n"); + ppp_terminate(lcp->ppp, TERM_USER_ERROR, 0); + } + + if (conf_ppp_verbose) + log_ppp_debug("recv [LCP EchoRep id=%x ]\n", lcp->fsm.recv_id, magic); + + if (magic == lcp->magic) { + log_ppp_error("lcp: echo: loop-back detected\n"); + ppp_terminate(lcp->ppp, TERM_NAS_ERROR, 0); + } + + lcp->echo_sent = 0; +} + +static void send_echo_reply(struct ppp_lcp_t *lcp) +{ + struct lcp_hdr_t *hdr = (struct lcp_hdr_t*)lcp->ppp->chan_buf; + uint32_t magic = *(uint32_t *)(hdr + 1); + + hdr->code = ECHOREP; + *(uint32_t *)(hdr + 1) = lcp->magic; + + if (conf_ppp_verbose) + log_ppp_debug("send [LCP EchoRep id=%x ]\n", hdr->id, magic); + + ppp_chan_send(lcp->ppp, hdr, ntohs(hdr->len) + 2); +} + +static void send_echo_request(struct triton_timer_t *t) +{ + struct ppp_lcp_t *lcp = container_of(t, typeof(*lcp), echo_timer); + struct lcp_echo_req_t + { + struct lcp_hdr_t hdr; + uint32_t magic; + } __attribute__((packed)) msg = { + .hdr.proto = htons(PPP_LCP), + .hdr.code = ECHOREQ, + .hdr.id = ++lcp->fsm.id, + .hdr.len = htons(8), + .magic = lcp->magic, + }; + + if (++lcp->echo_sent > lcp->echo_failure) { + log_ppp_warn("lcp: no echo reply\n"); + ppp_terminate(lcp->ppp, TERM_USER_ERROR, 1); + } else { + if (conf_ppp_verbose) + log_ppp_debug("send [LCP EchoReq id=%x ]\n", msg.hdr.id, msg.magic); + ppp_chan_send(lcp->ppp,&msg,ntohs(msg.hdr.len)+2); + } +} + +static void start_echo(struct ppp_lcp_t *lcp) +{ + lcp->echo_interval = conf_echo_interval; + lcp->echo_failure = conf_echo_failure; + + lcp->echo_timer.period = lcp->echo_interval * 1000; + lcp->echo_timer.expire = send_echo_request; + if (lcp->echo_timer.period && !lcp->echo_timer.tpd) + triton_timer_add(lcp->ppp->ctrl->ctx, &lcp->echo_timer, 0); +} +static void stop_echo(struct ppp_lcp_t *lcp) +{ + if (lcp->echo_timer.tpd) + triton_timer_del(&lcp->echo_timer); +} + +static void send_term_req(struct ppp_fsm_t *fsm) +{ + struct ppp_lcp_t *lcp=container_of(fsm,typeof(*lcp),fsm); + struct lcp_hdr_t hdr = { + .proto = htons(PPP_LCP), + .code = TERMREQ, + .id = ++lcp->fsm.id, + .len = htons(4), + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [LCP TermReq id=%i]\n", hdr.id); + + ppp_chan_send(lcp->ppp, &hdr, 6); +} + +static void send_term_ack(struct ppp_fsm_t *fsm) +{ + struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); + struct lcp_hdr_t hdr = { + .proto = htons(PPP_LCP), + .code = TERMACK, + .id = lcp->fsm.recv_id, + .len = htons(4), + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [LCP TermAck id=%i]\n", hdr.id); + + ppp_chan_send(lcp->ppp, &hdr, 6); +} + +void lcp_send_proto_rej(struct ppp_t *ppp, uint16_t proto) +{ + struct ppp_lcp_t *lcp = container_of(ppp_find_layer_data(ppp, &lcp_layer), typeof(*lcp), ld); + struct rej_msg_t + { + struct lcp_hdr_t hdr; + uint16_t proto; + } __attribute__((packed)) msg = { + .hdr.proto = htons(PPP_LCP), + .hdr.code = PROTOREJ, + .hdr.id = ++lcp->fsm.id, + .hdr.len = htons(6), + .proto = ntohs(proto), + }; + + if (conf_ppp_verbose) + log_ppp_info2("send [LCP ProtoRej id=%i <%04x>]\n", msg.hdr.id, proto); + + ppp_chan_send(lcp->ppp, &msg, sizeof(msg)); +} + +static void lcp_recv(struct ppp_handler_t*h) +{ + struct lcp_hdr_t *hdr; + struct ppp_lcp_t *lcp = container_of(h, typeof(*lcp), hnd); + int r; + char *term_msg; + + if (lcp->fsm.fsm_state == FSM_Initial || lcp->fsm.fsm_state == FSM_Closed || lcp->ppp->terminating) { + /*if (conf_ppp_verbose) + log_ppp_warn("LCP: discaring packet\n"); + lcp_send_proto_rej(ccp->ppp, htons(PPP_CCP));*/ + return; + } + + if (lcp->ppp->chan_buf_size < PPP_HEADERLEN + 2) { + log_ppp_warn("LCP: short packet received\n"); + return; + } + + hdr = (struct lcp_hdr_t *)lcp->ppp->chan_buf; + if (ntohs(hdr->len) < PPP_HEADERLEN) { + log_ppp_warn("LCP: short packet received\n"); + return; + } + + lcp->fsm.recv_id = hdr->id; + switch(hdr->code) { + case CONFREQ: + r = lcp_recv_conf_req(lcp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); + switch(r) { + case LCP_OPT_ACK: + ppp_fsm_recv_conf_req_ack(&lcp->fsm); + break; + case LCP_OPT_NAK: + ppp_fsm_recv_conf_req_nak(&lcp->fsm); + break; + case LCP_OPT_REJ: + ppp_fsm_recv_conf_req_rej(&lcp->fsm); + break; + } + lcp_free_conf_req(lcp); + if (r == LCP_OPT_FAIL) + ppp_terminate(lcp->ppp, TERM_USER_ERROR, 0); + break; + case CONFACK: + if (lcp_recv_conf_ack(lcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) + ppp_terminate(lcp->ppp, TERM_USER_ERROR, 0); + else + if (lcp->fsm.recv_id != lcp->fsm.id) + break; + ppp_fsm_recv_conf_ack(&lcp->fsm); + break; + case CONFNAK: + lcp_recv_conf_nak(lcp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); + if (lcp->fsm.recv_id != lcp->fsm.id) + break; + ppp_fsm_recv_conf_rej(&lcp->fsm); + break; + case CONFREJ: + if (lcp_recv_conf_rej(lcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) + ppp_terminate(lcp->ppp, TERM_USER_ERROR, 0); + else + if (lcp->fsm.recv_id != lcp->fsm.id) + break; + ppp_fsm_recv_conf_rej(&lcp->fsm); + break; + case TERMREQ: + if (conf_ppp_verbose) + log_ppp_info2("recv [LCP TermReq id=%x]\n", hdr->id); + ppp_fsm_recv_term_req(&lcp->fsm); + ppp_terminate(lcp->ppp, TERM_USER_REQUEST, 0); + break; + case TERMACK: + if (conf_ppp_verbose) + log_ppp_info2("recv [LCP TermAck id=%x]\n", hdr->id); + ppp_fsm_recv_term_ack(&lcp->fsm); + break; + case CODEREJ: + if (conf_ppp_verbose) + log_ppp_info2("recv [LCP CodeRej id=%x]\n", hdr->id); + ppp_fsm_recv_code_rej_bad(&lcp->fsm); + break; + case ECHOREQ: + if (conf_ppp_verbose) + log_ppp_debug("recv [LCP EchoReq id=%x ]\n", hdr->id, *(uint32_t*)(hdr + 1)); + send_echo_reply(lcp); + break; + case ECHOREP: + lcp_recv_echo_repl(lcp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); + break; + case PROTOREJ: + if (conf_ppp_verbose) + log_ppp_info2("recv [LCP ProtoRej id=%x <%04x>]\n", hdr->code, hdr->id, ntohs(*(uint16_t*)(hdr + 1))); + ppp_recv_proto_rej(lcp->ppp, ntohs(*(uint16_t *)(hdr + 1))); + break; + case IDENT: + if (conf_ppp_verbose) { + term_msg = _strndup((char*)(hdr + 1) + 4, ntohs(hdr->len) - 4 - 4); + log_ppp_info2("recv [LCP Ident id=%x <%s>]\n", hdr->id, term_msg); + _free(term_msg); + } + break; + default: + if (conf_ppp_verbose) + log_ppp_info2("recv [LCP Unknown %x]\n", hdr->code); + ppp_fsm_recv_unk(&lcp->fsm); + break; + } +} + +int lcp_option_register(struct lcp_option_handler_t *h) +{ + /*struct lcp_option_drv_t *p; + + list_for_each_entry(p,option_drv_list,entry) + if (p->id==h->id) + return -1;*/ + + list_add_tail(&h->entry, &option_handlers); + + return 0; +} + +static struct ppp_layer_t lcp_layer= +{ + .init = lcp_layer_init, + .start = lcp_layer_start, + .finish = lcp_layer_finish, + .free = lcp_layer_free, +}; + +static void load_config(void) +{ + char *opt; + + opt = conf_get_opt("lcp", "echo-interval"); + if (opt && atoi(opt) > 0) + conf_echo_interval = atoi(opt); + + opt = conf_get_opt("lcp", "echo-failure"); + if (opt && atoi(opt) > 0) + conf_echo_failure = atoi(opt); +} + +static void __init lcp_init(void) +{ + load_config(); + + ppp_register_layer("lcp", &lcp_layer); + + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); +} + diff --git a/accel-pppd/ppp/ppp_lcp.h b/accel-pppd/ppp/ppp_lcp.h new file mode 100644 index 0000000..6d67b69 --- /dev/null +++ b/accel-pppd/ppp/ppp_lcp.h @@ -0,0 +1,136 @@ +#ifndef PPP_LCP_H +#define PPP_LCP_H + +#include + +#include "triton.h" +#include "ppp_fsm.h" +/* + * Options. + */ +#define CI_VENDOR 0 /* Vendor Specific */ +#define CI_MRU 1 /* Maximum Receive Unit */ +#define CI_ASYNCMAP 2 /* Async Control Character Map */ +#define CI_AUTH 3 /* Authentication Type */ +#define CI_QUALITY 4 /* Quality Protocol */ +#define CI_MAGIC 5 /* Magic Number */ +#define CI_PCOMP 7 /* Protocol Field Compression */ +#define CI_ACCOMP 8 /* Address/Control Field Compression */ +#define CI_FCSALTERN 9 /* FCS-Alternatives */ +#define CI_SDP 10 /* Self-Describing-Pad */ +#define CI_NUMBERED 11 /* Numbered-Mode */ +#define CI_CALLBACK 13 /* callback */ +#define CI_MRRU 17 /* max reconstructed receive unit; multilink */ +#define CI_SSNHF 18 /* short sequence numbers for multilink */ +#define CI_EPDISC 19 /* endpoint discriminator */ +#define CI_MPPLUS 22 /* Multi-Link-Plus-Procedure */ +#define CI_LDISC 23 /* Link-Discriminator */ +#define CI_LCPAUTH 24 /* LCP Authentication */ +#define CI_COBS 25 /* Consistent Overhead Byte Stuffing */ +#define CI_PREFELIS 26 /* Prefix Elision */ +#define CI_MPHDRFMT 27 /* MP Header Format */ +#define CI_I18N 28 /* Internationalization */ +#define CI_SDL 29 /* Simple Data Link */ + +struct lcp_hdr_t +{ + uint16_t proto; + uint8_t code; + uint8_t id; + uint16_t len; +} __attribute__((packed)); +struct lcp_opt_hdr_t +{ + uint8_t id; + uint8_t len; +} __attribute__((packed)); +struct lcp_opt8_t +{ + struct lcp_opt_hdr_t hdr; + uint8_t val; +} __attribute__((packed)); +struct lcp_opt16_t +{ + struct lcp_opt_hdr_t hdr; + uint16_t val; +} __attribute__((packed)); +struct lcp_opt32_t +{ + struct lcp_opt_hdr_t hdr; + uint32_t val; +} __attribute__((packed)); + +/*struct lcp_options_t +{ + int magic; + int mtu; + int mru; + int accomp; // 0 - disabled, 1 - enable, 2 - allow, disabled, 3 - allow,enabled + int pcomp; // 0 - disabled, 1 - enable, 2 - allow, disabled, 3 - allow,enabled + // negotiated options; + int neg_mru; + int neg_mtu; + int neg_accomp; // -1 - rejected + int neg_pcomp; + int neg_auth[AUTH_MAX]; +};*/ + +#define LCP_OPT_NONE 0 +#define LCP_OPT_ACK 1 +#define LCP_OPT_NAK -1 +#define LCP_OPT_REJ -2 +#define LCP_OPT_FAIL -3 + +struct ppp_lcp_t; +struct lcp_option_handler_t; + +struct lcp_option_t +{ + struct list_head entry; + int id; + int len; + int state; + int print:1; + struct lcp_option_handler_t *h; +}; + +struct lcp_option_handler_t +{ + struct list_head entry; + struct lcp_option_t* (*init)(struct ppp_lcp_t*); + int (*send_conf_req)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); + int (*send_conf_rej)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); + int (*send_conf_nak)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); + int (*recv_conf_req)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); + int (*recv_conf_rej)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); + int (*recv_conf_nak)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); + int (*recv_conf_ack)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); + void (*free)(struct ppp_lcp_t*,struct lcp_option_t*); + void (*print)(void (*print)(const char *fmt,...), struct lcp_option_t*,uint8_t*); +}; + +struct ppp_lcp_t +{ + struct ppp_layer_data_t ld; + struct ppp_handler_t hnd; + struct ppp_fsm_t fsm; + struct ppp_t *ppp; + struct list_head options; + + struct triton_timer_t echo_timer; + int echo_interval; + int echo_failure; + int echo_sent; + int magic; + + struct list_head ropt_list; // last received ConfReq + int ropt_len; + + int conf_req_len; + int started:1; +}; + +int lcp_option_register(struct lcp_option_handler_t *h); + +#endif + diff --git a/accel-pppd/ppp/ppp_notify.c b/accel-pppd/ppp/ppp_notify.c new file mode 100644 index 0000000..ad9fd1f --- /dev/null +++ b/accel-pppd/ppp/ppp_notify.c @@ -0,0 +1,54 @@ +#include "ppp.h" + +static LIST_HEAD(notified_list); + +void __export ppp_register_notified(struct ppp_notified_t *n) +{ + list_add_tail(&n->entry, ¬ified_list); +} + +void __export ppp_unregister_notified(struct ppp_notified_t *n) +{ + list_del(&n->entry); +} + +void ppp_notify_starting(struct ppp_t *ppp) +{ + struct ppp_notified_t *n; + + list_for_each_entry(n, ¬ified_list, entry) { + if (n->starting) + n->starting(n, ppp); + } +} + +void ppp_notify_started(struct ppp_t *ppp) +{ + struct ppp_notified_t *n; + + list_for_each_entry(n, ¬ified_list, entry) { + if (n->started) + n->started(n, ppp); + } +} + +void ppp_notify_finished(struct ppp_t *ppp) +{ + struct ppp_notified_t *n; + + list_for_each_entry(n, ¬ified_list, entry) { + if (n->finished) + n->finished(n, ppp); + } +} + +void ppp_notify_finishing(struct ppp_t *ppp) +{ + struct ppp_notified_t *n; + + list_for_each_entry(n, ¬ified_list, entry) { + if (n->finishing) + n->finishing(n, ppp); + } +} + diff --git a/accel-pppd/ppp/ppp_pd.c b/accel-pppd/ppp/ppp_pd.c new file mode 100644 index 0000000..f770208 --- /dev/null +++ b/accel-pppd/ppp/ppp_pd.c @@ -0,0 +1,14 @@ +#include "ppp.h" + +#include "memdebug.h" + +int ppp_store_pd(struct ppp_t *ppp, pd_key_t key, void *data) +{ + struct ppp_pd_t *pd; + + list_for_each_entry(pd, &ppp->pd_list, entry) + if (pd->key == key) + return -1; + + +} diff --git a/accel-pppd/pwdb.c b/accel-pppd/pwdb.c new file mode 100644 index 0000000..4c0ab02 --- /dev/null +++ b/accel-pppd/pwdb.c @@ -0,0 +1,56 @@ +#include + +#include "triton.h" + +#include "pwdb.h" + +#include "memdebug.h" + +static LIST_HEAD(pwdb_handlers); + +int __export pwdb_check(struct ppp_t *ppp, const char *username, int type, ...) +{ + struct pwdb_t *pwdb; + int r, res = PWDB_NO_IMPL; + va_list args; + + va_start(args, type); + + list_for_each_entry(pwdb, &pwdb_handlers, entry) { + if (!pwdb->check) + continue; + r = pwdb->check(pwdb, ppp, username, type, args); + if (r == PWDB_NO_IMPL) + continue; + if (r == PWDB_SUCCESS) + return PWDB_SUCCESS; + res = r; + } + + return res; +} +__export char *pwdb_get_passwd(struct ppp_t *ppp, const char *username) +{ + struct pwdb_t *pwdb; + char *r = NULL; + + list_for_each_entry(pwdb, &pwdb_handlers, entry) { + if (!pwdb->get_passwd) + continue; + r = pwdb->get_passwd(pwdb, ppp, username); + if (r) + break; + } + + return r; +} + +void __export pwdb_register(struct pwdb_t *pwdb) +{ + list_add_tail(&pwdb->entry, &pwdb_handlers); +} +void __export pwdb_unregister(struct pwdb_t *pwdb) +{ + list_del(&pwdb->entry); +} + diff --git a/accel-pppd/pwdb.h b/accel-pppd/pwdb.h new file mode 100644 index 0000000..a1c2ced --- /dev/null +++ b/accel-pppd/pwdb.h @@ -0,0 +1,27 @@ +#ifndef PWDB_H +#define PWDB_H + +#include +#include "list.h" + +struct ppp_t; + +#define PWDB_SUCCESS 0 +#define PWDB_DENIED 1 +#define PWDB_NO_IMPL 2 + +struct pwdb_t +{ + struct list_head entry; + int (*check)(struct pwdb_t *, struct ppp_t *, const char *username, int type, va_list args); + char* (*get_passwd)(struct pwdb_t *, struct ppp_t *, const char *username); +}; + +int pwdb_check(struct ppp_t *, const char *username, int type, ...); +char *pwdb_get_passwd(struct ppp_t *, const char *username); + +void pwdb_register(struct pwdb_t *); +void pwdb_unregister(struct pwdb_t *); + +#endif + diff --git a/accel-pppd/radius/CMakeLists.txt b/accel-pppd/radius/CMakeLists.txt new file mode 100644 index 0000000..322bee5 --- /dev/null +++ b/accel-pppd/radius/CMakeLists.txt @@ -0,0 +1,19 @@ +SET(sources + dict.c + req.c + packet.c + auth.c + acct.c + dm_coa.c + radius.c +) + +ADD_DEFINITIONS(-DDICTIONARY="${CMAKE_INSTALL_PREFIX}/share/accel-ppp/radius/dictionary") + +ADD_LIBRARY(radius SHARED ${sources}) + +INSTALL(TARGETS radius + LIBRARY DESTINATION lib/accel-ppp +) +FILE(GLOB dict "${CMAKE_CURRENT_SOURCE_DIR}/dict/*") +INSTALL(FILES ${dict} DESTINATION share/accel-ppp/radius) diff --git a/accel-pppd/radius/acct.c b/accel-pppd/radius/acct.c new file mode 100644 index 0000000..ddb3e08 --- /dev/null +++ b/accel-pppd/radius/acct.c @@ -0,0 +1,328 @@ +#include +#include +#include +#include +#include +#include +#include +#include "linux_ppp.h" + +#include + +#include "log.h" +#include "radius_p.h" + +#include "memdebug.h" + +#define STAT_UPDATE_INTERVAL (10 * 60 * 1000) + +static int req_set_RA(struct rad_req_t *req, const char *secret) +{ + MD5_CTX ctx; + + if (rad_packet_build(req->pack, req->RA)) + return -1; + + MD5_Init(&ctx); + MD5_Update(&ctx, req->pack->buf, req->pack->len); + MD5_Update(&ctx, secret, strlen(secret)); + MD5_Final(req->pack->buf + 4, &ctx); + + return 0; +} + +static void req_set_stat(struct rad_req_t *req, struct ppp_t *ppp) +{ + struct ifpppstatsreq ifreq; + time_t stop_time; + + if (ppp->stop_time) + stop_time = ppp->stop_time; + else + time(&stop_time); + + memset(&ifreq, 0, sizeof(ifreq)); + ifreq.stats_ptr = (void *)&ifreq.stats; + strcpy(ifreq.ifr__name, ppp->ifname); + + if (ioctl(sock_fd, SIOCGPPPSTATS, &ifreq)) { + log_ppp_error("radius: failed to get ppp statistics: %s\n", strerror(errno)); + return; + } + + if (ifreq.stats.p.ppp_ibytes < req->rpd->acct_input_octets) + req->rpd->acct_input_gigawords++; + req->rpd->acct_input_octets = ifreq.stats.p.ppp_ibytes; + + if (ifreq.stats.p.ppp_obytes < req->rpd->acct_output_octets) + req->rpd->acct_output_gigawords++; + req->rpd->acct_output_octets = ifreq.stats.p.ppp_obytes; + + rad_packet_change_int(req->pack, NULL, "Acct-Input-Octets", ifreq.stats.p.ppp_ibytes); + rad_packet_change_int(req->pack, NULL, "Acct-Output-Octets", ifreq.stats.p.ppp_obytes); + rad_packet_change_int(req->pack, NULL, "Acct-Input-Packets", ifreq.stats.p.ppp_ipackets); + rad_packet_change_int(req->pack, NULL, "Acct-Output-Packets", ifreq.stats.p.ppp_opackets); + rad_packet_change_int(req->pack, NULL, "Acct-Input-Gigawords", req->rpd->acct_input_gigawords); + rad_packet_change_int(req->pack, NULL, "Acct-Output-Gigawords", req->rpd->acct_output_gigawords); + rad_packet_change_int(req->pack, NULL, "Acct-Session-Time", stop_time - ppp->start_time); +} + +static int rad_acct_read(struct triton_md_handler_t *h) +{ + struct rad_req_t *req = container_of(h, typeof(*req), hnd); + struct rad_packet_t *pack; + int r; + + if (req->reply) { + rad_packet_free(req->reply); + req->reply = NULL; + } + + while (1) { + r = rad_packet_recv(h->fd, &pack, NULL); + + if (pack) { + if (req->reply) + rad_packet_free(req->reply); + req->reply = pack; + if (conf_interim_verbose) { + log_ppp_info2("recv "); + rad_packet_print(req->reply, log_ppp_info2); + } + } + + if (r) + break; + } + + if (!req->reply) + return 0; + + if (req->reply->code != CODE_ACCOUNTING_RESPONSE || req->reply->id != req->pack->id) { + rad_packet_free(req->reply); + req->reply = NULL; + } else { + if (req->timeout.tpd) + triton_timer_del(&req->timeout); + } + + return 0; +} + +static void rad_acct_timeout(struct triton_timer_t *t) +{ + struct rad_req_t *req = container_of(t, typeof(*req), timeout); + time_t ts, dt; + + __sync_add_and_fetch(&stat_interim_lost, 1); + + time(&ts); + + dt = ts - req->rpd->acct_timestamp; + + if (dt > conf_acct_timeout) { + log_ppp_warn("radius:acct: no response, terminating session...\n"); + ppp_terminate(req->rpd->ppp, TERM_NAS_ERROR, 0); + return; + } + if (dt > conf_acct_timeout / 2) { + req->timeout.period += 1000; + triton_timer_mod(&req->timeout, 0); + } else if (dt > conf_acct_timeout / 3) { + if (req->timeout.period != conf_timeout * 2000) { + req->timeout.period = conf_timeout * 2000; + triton_timer_mod(&req->timeout, 0); + } + } + + req->pack->id++; + + rad_packet_change_int(req->pack, NULL, "Acct-Delay-Time", dt); + req_set_RA(req, conf_acct_secret); + rad_req_send(req, conf_interim_verbose); + __sync_add_and_fetch(&stat_interim_sent, 1); +} + +static void rad_acct_interim_update(struct triton_timer_t *t) +{ + struct radius_pd_t *rpd = container_of(t, typeof(*rpd), acct_interim_timer); + + if (rpd->acct_req->timeout.tpd) + return; + + req_set_stat(rpd->acct_req, rpd->ppp); + if (!rpd->acct_interim_interval) + return; + + time(&rpd->acct_timestamp); + rpd->acct_req->pack->id++; + + rad_packet_change_val(rpd->acct_req->pack, NULL, "Acct-Status-Type", "Interim-Update"); + rad_packet_change_int(rpd->acct_req->pack, NULL, "Acct-Delay-Time", 0); + req_set_RA(rpd->acct_req, conf_acct_secret); + rad_req_send(rpd->acct_req, conf_interim_verbose); + __sync_add_and_fetch(&stat_interim_sent, 1); + if (conf_acct_timeout) { + rpd->acct_req->timeout.period = conf_timeout * 1000; + triton_timer_add(rpd->ppp->ctrl->ctx, &rpd->acct_req->timeout, 0); + } +} + +int rad_acct_start(struct radius_pd_t *rpd) +{ + int i; + time_t ts; + + rpd->acct_req = rad_req_alloc(rpd, CODE_ACCOUNTING_REQUEST, rpd->ppp->username); + if (!rpd->acct_req) { + log_emerg("radius: out of memory\n"); + return -1; + } + + if (rad_req_acct_fill(rpd->acct_req)) { + log_ppp_error("radius:acct: failed to fill accounting attributes\n"); + goto out_err; + } + + //if (rad_req_add_val(rpd->acct_req, "Acct-Status-Type", "Start", 4)) + // goto out_err; + //if (rad_req_add_str(rpd->acct_req, "Acct-Session-Id", rpd->ppp->sessionid, PPP_SESSIONID_LEN, 1)) + // goto out_err; + + if (rpd->acct_req->reply) { + rad_packet_free(rpd->acct_req->reply); + rpd->acct_req->reply = NULL; + } + + time(&rpd->acct_timestamp); + + for (i = 0; i < conf_max_try; i++) { + time(&ts); + rad_packet_change_int(rpd->acct_req->pack, NULL, "Acct-Delay-Time", ts - rpd->acct_timestamp); + if (req_set_RA(rpd->acct_req, conf_acct_secret)) + goto out_err; + if (rad_req_send(rpd->acct_req, conf_verbose)) + goto out_err; + __sync_add_and_fetch(&stat_acct_sent, 1); + rad_req_wait(rpd->acct_req, conf_timeout); + if (!rpd->acct_req->reply) { + rpd->acct_req->pack->id++; + __sync_add_and_fetch(&stat_acct_lost, 1); + continue; + } + if (rpd->acct_req->reply->id != rpd->acct_req->pack->id || rpd->acct_req->reply->code != CODE_ACCOUNTING_RESPONSE) { + rad_packet_free(rpd->acct_req->reply); + rpd->acct_req->reply = NULL; + rpd->acct_req->pack->id++; + __sync_add_and_fetch(&stat_acct_lost, 1); + } else + break; + } + + if (!rpd->acct_req->reply) { + log_ppp_warn("radius:acct_start: no response\n"); + goto out_err; + } + + rpd->acct_req->hnd.read = rad_acct_read; + + triton_md_register_handler(rpd->ppp->ctrl->ctx, &rpd->acct_req->hnd); + if (triton_md_enable_handler(&rpd->acct_req->hnd, MD_MODE_READ)) + goto out_err; + + rpd->acct_req->timeout.expire = rad_acct_timeout; + rpd->acct_req->timeout.period = conf_timeout * 1000; + + rpd->acct_interim_timer.expire = rad_acct_interim_update; + rpd->acct_interim_timer.period = rpd->acct_interim_interval ? rpd->acct_interim_interval * 1000 : STAT_UPDATE_INTERVAL; + if (rpd->acct_interim_interval && triton_timer_add(rpd->ppp->ctrl->ctx, &rpd->acct_interim_timer, 0)) { + triton_md_unregister_handler(&rpd->acct_req->hnd); + triton_timer_del(&rpd->acct_req->timeout); + goto out_err; + } + return 0; + +out_err: + rad_req_free(rpd->acct_req); + rpd->acct_req = NULL; + return -1; +} + +void rad_acct_stop(struct radius_pd_t *rpd) +{ + int i; + time_t ts; + + if (rpd->acct_interim_timer.tpd) + triton_timer_del(&rpd->acct_interim_timer); + + if (rpd->acct_req) { + triton_md_unregister_handler(&rpd->acct_req->hnd); + if (rpd->acct_req->timeout.tpd) + triton_timer_del(&rpd->acct_req->timeout); + + switch (rpd->ppp->terminate_cause) { + case TERM_USER_REQUEST: + rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "User-Request"); + break; + case TERM_SESSION_TIMEOUT: + rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "Session-Timeout"); + break; + case TERM_ADMIN_RESET: + rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "Admin-Reset"); + break; + case TERM_USER_ERROR: + case TERM_AUTH_ERROR: + rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "User-Error"); + break; + case TERM_NAS_ERROR: + rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "NAS-Error"); + break; + case TERM_NAS_REQUEST: + rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "NAS-Request"); + break; + case TERM_NAS_REBOOT: + rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "NAS-Reboot"); + break; + } + rad_packet_change_val(rpd->acct_req->pack, NULL, "Acct-Status-Type", "Stop"); + req_set_stat(rpd->acct_req, rpd->ppp); + req_set_RA(rpd->acct_req, conf_acct_secret); + /// !!! rad_req_add_val(rpd->acct_req, "Acct-Terminate-Cause", ""); + + if (rpd->acct_req->reply) { + rad_packet_free(rpd->acct_req->reply); + rpd->acct_req->reply = NULL; + } + + time(&rpd->acct_timestamp); + + for(i = 0; i < conf_max_try; i++) { + time(&ts); + rad_packet_change_int(rpd->acct_req->pack, NULL, "Acct-Delay-Time", ts - rpd->acct_timestamp); + rpd->acct_req->pack->id++; + if (req_set_RA(rpd->acct_req, conf_acct_secret)) + break; + if (rad_req_send(rpd->acct_req, conf_verbose)) + break; + __sync_add_and_fetch(&stat_acct_sent, 1); + rad_req_wait(rpd->acct_req, conf_timeout); + if (!rpd->acct_req->reply) { + __sync_add_and_fetch(&stat_acct_lost, 1); + continue; + } + if (rpd->acct_req->reply->id != rpd->acct_req->pack->id || rpd->acct_req->reply->code != CODE_ACCOUNTING_RESPONSE) { + rad_packet_free(rpd->acct_req->reply); + rpd->acct_req->reply = NULL; + __sync_add_and_fetch(&stat_acct_lost, 1); + } else + break; + } + if (!rpd->acct_req->reply) + log_ppp_warn("radius:acct_stop: no response\n"); + + rad_req_free(rpd->acct_req); + rpd->acct_req = NULL; + } +} + diff --git a/accel-pppd/radius/attr_defs.h b/accel-pppd/radius/attr_defs.h new file mode 100644 index 0000000..e9b617e --- /dev/null +++ b/accel-pppd/radius/attr_defs.h @@ -0,0 +1,287 @@ +#define User_Name 1 +#define User_Password 2 +#define CHAP_Password 3 +#define NAS_IP_Address 4 +#define NAS_Port 5 +#define Service_Type 6 +#define Framed_Protocol 7 +#define Framed_IP_Address 8 +#define Framed_IP_Netmask 9 +#define Framed_Routing 10 +#define Filter_Id 11 +#define Framed_MTU 12 +#define Framed_Compression 13 +#define Login_IP_Host 14 +#define Login_Service 15 +#define Login_TCP_Port 16 +#define Reply_Message 18 +#define Callback_Number 19 +#define Callback_Id 20 +#define Framed_Route 22 +#define Framed_IPX_Network 23 +#define State 24 +#define Class 25 +#define Vendor_Specific 26 +#define Session_Timeout 27 +#define Idle_Timeout 28 +#define Termination_Action 29 +#define Called_Station_Id 30 +#define Calling_Station_Id 31 +#define NAS_Identifier 32 +#define Proxy_State 33 +#define Login_LAT_Service 34 +#define Login_LAT_Node 35 +#define Login_LAT_Group 36 +#define Framed_AppleTalk_Link 37 +#define Framed_AppleTalk_Network 38 +#define Framed_AppleTalk_Zone 39 +#define CHAP_Challenge 60 +#define NAS_Port_Type 61 +#define Port_Limit 62 +#define Login_LAT_Port 63 +#define Service_Type_Login_User 1 +#define Service_Type_Framed_User 2 +#define Service_Type_Callback_Login_User 3 +#define Service_Type_Callback_Framed_User 4 +#define Service_Type_Outbound_User 5 +#define Service_Type_Administrative_User 6 +#define Service_Type_NAS_Prompt_User 7 +#define Service_Type_Authenticate_Only 8 +#define Service_Type_Callback_NAS_Prompt 9 +#define Service_Type_Call_Check 10 +#define Service_Type_Callback_Administrative 11 +#define Framed_Protocol_PPP 1 +#define Framed_Protocol_SLIP 2 +#define Framed_Protocol_ARAP 3 +#define Framed_Protocol_Gandalf_SLML 4 +#define Framed_Protocol_Xylogics_IPX_SLIP 5 +#define Framed_Protocol_X_75_Synchronous 6 +#define Framed_Routing_None 0 +#define Framed_Routing_Broadcast 1 +#define Framed_Routing_Listen 2 +#define Framed_Routing_Broadcast_Listen 3 +#define Framed_Compression_None 0 +#define Framed_Compression_Van_Jacobson_TCP_IP 1 +#define Framed_Compression_IPX_Header_Compression 2 +#define Framed_Compression_Stac_LZS 3 +#define Login_Service_Telnet 0 +#define Login_Service_Rlogin 1 +#define Login_Service_TCP_Clear 2 +#define Login_Service_PortMaster 3 +#define Login_Service_LAT 4 +#define Login_Service_X25_PAD 5 +#define Login_Service_X25_T3POS 6 +#define Login_Service_TCP_Clear_Quiet 8 +#define Login_TCP_Port_Telnet 23 +#define Login_TCP_Port_Rlogin 513 +#define Login_TCP_Port_Rsh 514 +#define Termination_Action_Default 0 +#define Termination_Action_RADIUS_Request 1 +#define NAS_Port_Type_Async 0 +#define NAS_Port_Type_Sync 1 +#define NAS_Port_Type_ISDN 2 +#define NAS_Port_Type_ISDN_V120 3 +#define NAS_Port_Type_ISDN_V110 4 +#define NAS_Port_Type_Virtual 5 +#define NAS_Port_Type_PIAFS 6 +#define NAS_Port_Type_HDLC_Clear_Channel 7 +#define NAS_Port_Type_X_25 8 +#define NAS_Port_Type_X_75 9 +#define NAS_Port_Type_G_3_Fax 10 +#define NAS_Port_Type_SDSL 11 +#define NAS_Port_Type_ADSL_CAP 12 +#define NAS_Port_Type_ADSL_DMT 13 +#define NAS_Port_Type_IDSL 14 +#define NAS_Port_Type_Ethernet 15 +#define NAS_Port_Type_xDSL 16 +#define NAS_Port_Type_Cable 17 +#define NAS_Port_Type_Wireless_Other 18 +#define NAS_Port_Type_Wireless_802_11 19 +#define Acct_Status_Type 40 +#define Acct_Delay_Time 41 +#define Acct_Input_Octets 42 +#define Acct_Output_Octets 43 +#define Acct_Session_Id 44 +#define Acct_Authentic 45 +#define Acct_Session_Time 46 +#define Acct_Input_Packets 47 +#define Acct_Output_Packets 48 +#define Acct_Terminate_Cause 49 +#define Acct_Multi_Session_Id 50 +#define Acct_Link_Count 51 +#define Acct_Status_Type_Start 1 +#define Acct_Status_Type_Stop 2 +#define Acct_Status_Type_Alive 3 +#define Acct_Status_Type_Interim_Update 3 +#define Acct_Status_Type_Accounting_On 7 +#define Acct_Status_Type_Accounting_Off 8 +#define Acct_Status_Type_Failed 15 +#define Acct_Authentic_RADIUS 1 +#define Acct_Authentic_Local 2 +#define Acct_Authentic_Remote 3 +#define Acct_Authentic_Diameter 4 +#define Acct_Terminate_Cause_User_Request 1 +#define Acct_Terminate_Cause_Lost_Carrier 2 +#define Acct_Terminate_Cause_Lost_Service 3 +#define Acct_Terminate_Cause_Idle_Timeout 4 +#define Acct_Terminate_Cause_Session_Timeout 5 +#define Acct_Terminate_Cause_Admin_Reset 6 +#define Acct_Terminate_Cause_Admin_Reboot 7 +#define Acct_Terminate_Cause_Port_Error 8 +#define Acct_Terminate_Cause_NAS_Error 9 +#define Acct_Terminate_Cause_NAS_Request 10 +#define Acct_Terminate_Cause_NAS_Reboot 11 +#define Acct_Terminate_Cause_Port_Unneeded 12 +#define Acct_Terminate_Cause_Port_Preempted 13 +#define Acct_Terminate_Cause_Port_Suspended 14 +#define Acct_Terminate_Cause_Service_Unavailable 15 +#define Acct_Terminate_Cause_Callback 16 +#define Acct_Terminate_Cause_User_Error 17 +#define Acct_Terminate_Cause_Host_Request 18 +#define Acct_Tunnel_Connection 68 +#define Acct_Tunnel_Packets_Lost 86 +#define Acct_Status_Type_Tunnel_Start 9 +#define Acct_Status_Type_Tunnel_Stop 10 +#define Acct_Status_Type_Tunnel_Reject 11 +#define Acct_Status_Type_Tunnel_Link_Start 12 +#define Acct_Status_Type_Tunnel_Link_Stop 13 +#define Acct_Status_Type_Tunnel_Link_Reject 14 +#define Tunnel_Type 64 +#define Tunnel_Medium_Type 65 +#define Tunnel_Client_Endpoint 66 +#define Tunnel_Server_Endpoint 67 +#define Tunnel_Password 69 +#define Tunnel_Private_Group_Id 81 +#define Tunnel_Assignment_Id 82 +#define Tunnel_Preference 83 +#define Tunnel_Client_Auth_Id 90 +#define Tunnel_Server_Auth_Id 91 +#define Tunnel_Type_PPTP 1 +#define Tunnel_Type_L2F 2 +#define Tunnel_Type_L2TP 3 +#define Tunnel_Type_ATMP 4 +#define Tunnel_Type_VTP 5 +#define Tunnel_Type_AH 6 +#define Tunnel_Type_IP 7 +#define Tunnel_Type_MIN_IP 8 +#define Tunnel_Type_ESP 9 +#define Tunnel_Type_GRE 10 +#define Tunnel_Type_DVS 11 +#define Tunnel_Type_IP_in_IP 12 +#define Tunnel_Medium_Type_IP 1 +#define Tunnel_Medium_Type_IPv4 1 +#define Tunnel_Medium_Type_IPv6 2 +#define Tunnel_Medium_Type_NSAP 3 +#define Tunnel_Medium_Type_HDLC 4 +#define Tunnel_Medium_Type_BBN_1822 5 +#define Tunnel_Medium_Type_IEEE_802 6 +#define Tunnel_Medium_Type_E_163 7 +#define Tunnel_Medium_Type_E_164 8 +#define Tunnel_Medium_Type_F_69 9 +#define Tunnel_Medium_Type_X_121 10 +#define Tunnel_Medium_Type_IPX 11 +#define Tunnel_Medium_Type_Appletalk 12 +#define Tunnel_Medium_Type_DecNet_IV 13 +#define Tunnel_Medium_Type_Banyan_Vines 14 +#define Tunnel_Medium_Type_E_164_NSAP 15 +#define Acct_Input_Gigawords 52 +#define Acct_Output_Gigawords 53 +#define Event_Timestamp 55 +#define ARAP_Password 70 +#define ARAP_Features 71 +#define ARAP_Zone_Access 72 +#define ARAP_Security 73 +#define ARAP_Security_Data 74 +#define Password_Retry 75 +#define Prompt 76 +#define Connect_Info 77 +#define Configuration_Token 78 +#define EAP_Message 79 +#define Message_Authenticator 80 +#define ARAP_Challenge_Response 84 +#define Acct_Interim_Interval 85 +#define NAS_Port_Id 87 +#define Framed_Pool 88 +#define ARAP_Zone_Access_Default_Zone 1 +#define ARAP_Zone_Access_Zone_Filter_Inclusive 2 +#define ARAP_Zone_Access_Zone_Filter_Exclusive 4 +#define Prompt_No_Echo 0 +#define Prompt_Echo 1 +#define Error_Cause 101 +#define Service_Type_Authorize_Only 17 +#define Error_Cause_Residual_Context_Removed 201 +#define Error_Cause_Invalid_EAP_Packet 202 +#define Error_Cause_Unsupported_Attribute 401 +#define Error_Cause_Missing_Attribute 402 +#define Error_Cause_NAS_Identification_Mismatch 403 +#define Error_Cause_Invalid_Request 404 +#define Error_Cause_Unsupported_Service 405 +#define Error_Cause_Unsupported_Extension 406 +#define Error_Cause_Administratively_Prohibited 501 +#define Error_Cause_Proxy_Request_Not_Routable 502 +#define Error_Cause_Session_Context_Not_Found 503 +#define Error_Cause_Session_Context_Not_Removable 504 +#define Error_Cause_Proxy_Processing_Error 505 +#define Error_Cause_Resources_Unavailable 506 +#define Error_Cause_Request_Initiated 507 +#define Acct_Terminate_Cause_Supplicant_Restart 19 +#define Acct_Terminate_Cause_Reauthentication_Failure 20 +#define Acct_Terminate_Cause_Port_Reinit 21 +#define Acct_Terminate_Cause_Port_Disabled 22 +#define NAS_Port_Type_Token_Ring 20 +#define NAS_Port_Type_FDDI 21 +#define Tunnel_Type_VLAN 13 +#define EAP_Key_Name 102 +#define Chargeable_User_Identity 89 +#define Error_Cause_Invalid_Attribute_Value 407 +#define Error_Cause_Multiple_Session_Selection_Unsupported 508 +#define Vendor_Microsoft 311 +#define MS_CHAP_Response 1 +#define MS_CHAP_Error 2 +#define MS_CHAP_CPW_1 3 +#define MS_CHAP_CPW_2 4 +#define MS_CHAP_LM_Enc_PW 5 +#define MS_CHAP_NT_Enc_PW 6 +#define MS_MPPE_Encryption_Policy 7 +#define MS_MPPE_Encryption_Type 8 +#define MS_MPPE_Encryption_Types 8 +#define MS_RAS_Vendor 9 +#define MS_CHAP_Domain 10 +#define MS_CHAP_Challenge 11 +#define MS_CHAP_MPPE_Keys 12 +#define MS_BAP_Usage 13 +#define MS_Link_Utilization_Threshold 14 +#define MS_Link_Drop_Time_Limit 15 +#define MS_MPPE_Send_Key 16 +#define MS_MPPE_Recv_Key 17 +#define MS_RAS_Version 18 +#define MS_Old_ARAP_Password 19 +#define MS_New_ARAP_Password 20 +#define MS_ARAP_PW_Change_Reason 21 +#define MS_Filter 22 +#define MS_Acct_Auth_Type 23 +#define MS_Acct_EAP_Type 24 +#define MS_CHAP2_Response 25 +#define MS_CHAP2_Success 26 +#define MS_CHAP2_CPW 27 +#define MS_Primary_DNS_Server 28 +#define MS_Secondary_DNS_Server 29 +#define MS_Primary_NBNS_Server 30 +#define MS_Secondary_NBNS_Server 31 +#define MS_BAP_Usage_Not_Allowed 0 +#define MS_BAP_Usage_Allowed 1 +#define MS_BAP_Usage_Required 2 +#define MS_ARAP_PW_Change_Reason_Just_Change_Password 1 +#define MS_ARAP_PW_Change_Reason_Expired_Password 2 +#define MS_ARAP_PW_Change_Reason_Admin_Requires_Password_Change 3 +#define MS_ARAP_PW_Change_Reason_Password_Too_Short 4 +#define MS_Acct_Auth_Type_PAP 1 +#define MS_Acct_Auth_Type_CHAP 2 +#define MS_Acct_Auth_Type_MS_CHAP_1 3 +#define MS_Acct_Auth_Type_MS_CHAP_2 4 +#define MS_Acct_Auth_Type_EAP 5 +#define MS_Acct_EAP_Type_MD5 4 +#define MS_Acct_EAP_Type_OTP 5 +#define MS_Acct_EAP_Type_Generic_Token_Card 6 +#define MS_Acct_EAP_Type_TLS 13 +#define Traffic_Shape_in 231 diff --git a/accel-pppd/radius/auth.c b/accel-pppd/radius/auth.c new file mode 100644 index 0000000..692830e --- /dev/null +++ b/accel-pppd/radius/auth.c @@ -0,0 +1,497 @@ +#include +#include +#include +#include + +#include "triton.h" +#include "events.h" +#include "log.h" +#include "pwdb.h" + +#include "radius_p.h" +#include "attr_defs.h" + +#include "memdebug.h" + +static int decrypt_chap_mppe_keys(struct rad_req_t *req, struct rad_attr_t *attr, const uint8_t *challenge, uint8_t *key) +{ + MD5_CTX md5_ctx; + SHA_CTX sha1_ctx; + uint8_t md5[MD5_DIGEST_LENGTH]; + uint8_t sha1[SHA_DIGEST_LENGTH]; + uint8_t plain[32]; + int i; + + if (attr->len != 32) { + log_ppp_warn("radius: %s: incorrect attribute length (%i)\n", attr->attr->name, attr->len); + return -1; + } + + memcpy(plain, attr->val.octets, 32); + + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx, conf_auth_secret, strlen(conf_auth_secret)); + MD5_Update(&md5_ctx, req->pack->buf + 4, 16); + MD5_Final(md5, &md5_ctx); + + for (i = 0; i < 16; i++) + plain[i] ^= md5[i]; + + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx, conf_auth_secret, strlen(conf_auth_secret)); + MD5_Update(&md5_ctx, attr->val.octets, 16); + MD5_Final(md5, &md5_ctx); + + for (i = 0; i < 16; i++) + plain[i + 16] ^= md5[i]; + + SHA1_Init(&sha1_ctx); + SHA1_Update(&sha1_ctx, plain + 8, 16); + SHA1_Update(&sha1_ctx, plain + 8, 16); + SHA1_Update(&sha1_ctx, challenge, 8); + SHA1_Final(sha1, &sha1_ctx); + + memcpy(key, sha1, 16); + + return 0; +} + +static int decrypt_mppe_key(struct rad_req_t *req, struct rad_attr_t *attr, uint8_t *key) +{ + MD5_CTX md5_ctx; + uint8_t md5[16]; + uint8_t plain[32]; + int i; + + if (attr->len != 34) { + log_ppp_warn("radius: %s: incorrect attribute length (%i)\n", attr->attr->name, attr->len); + return -1; + } + + if ((attr->val.octets[0] & 0x80) == 0) { + log_ppp_warn("radius: %s: incorrect salt value (%x)\n", attr->attr->name, attr->len); + return -1; + } + + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx, conf_auth_secret, strlen(conf_auth_secret)); + MD5_Update(&md5_ctx, req->pack->buf + 4, 16); + MD5_Update(&md5_ctx, attr->val.octets, 2); + MD5_Final(md5, &md5_ctx); + + memcpy(plain, attr->val.octets + 2, 32); + + for (i = 0; i < 16; i++) + plain[i] ^= md5[i]; + + if (plain[0] != 16) { + log_ppp_warn("radius: %s: incorrect key length (%i)\n", attr->attr->name, plain[0]); + return -1; + } + + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx, conf_auth_secret, strlen(conf_auth_secret)); + MD5_Update(&md5_ctx, attr->val.octets + 2, 16); + MD5_Final(md5, &md5_ctx); + + plain[16] ^= md5[0]; + + memcpy(key, plain + 1, 16); + + return 0; +} + + +static uint8_t* encrypt_password(const char *passwd, const char *secret, const uint8_t *RA, int *epasswd_len) +{ + uint8_t *epasswd; + int i, j, chunk_cnt; + uint8_t b[16], c[16]; + MD5_CTX ctx; + + if (strlen(passwd)) + chunk_cnt = (strlen(passwd) - 1) / 16 + 1; + else { + *epasswd_len = 0; + return (uint8_t *)1; + } + + epasswd = _malloc(chunk_cnt * 16); + if (!epasswd) { + log_emerg("radius: out of memory\n"); + return NULL; + } + + memset(epasswd, 0, chunk_cnt * 16); + memcpy(epasswd, passwd, strlen(passwd)); + memcpy(c, RA, 16); + + for (i = 0; i < chunk_cnt; i++) { + MD5_Init(&ctx); + MD5_Update(&ctx, secret, strlen(secret)); + MD5_Update(&ctx, c, 16); + MD5_Final(b, &ctx); + + for(j = 0; j < 16; j++) + epasswd[i * 16 + j] ^= b[j]; + + memcpy(c, epasswd + i * 16, 16); + } + + *epasswd_len = chunk_cnt * 16; + return epasswd; +} + +static int rad_auth_send(struct rad_req_t *req) +{ + int i; + + for(i = 0; i < conf_max_try; i++) { + __sync_add_and_fetch(&stat_auth_sent, 1); + if (rad_req_send(req, conf_verbose)) + goto out; + + rad_req_wait(req, conf_timeout); + + if (req->reply) { + if (req->reply->id != req->pack->id) { + __sync_add_and_fetch(&stat_auth_lost, 1); + rad_packet_free(req->reply); + req->reply = NULL; + } else + break; + } else + __sync_add_and_fetch(&stat_auth_lost, 1); + } + + if (!req->reply) + log_ppp_warn("radius:auth: no response\n"); + else if (req->reply->code == CODE_ACCESS_ACCEPT) { + if (rad_proc_attrs(req)) + return PWDB_DENIED; + return PWDB_SUCCESS; + } + +out: + return PWDB_DENIED; +} + +int rad_auth_pap(struct radius_pd_t *rpd, const char *username, va_list args) +{ + struct rad_req_t *req; + int r = PWDB_DENIED; + //int id = va_arg(args, int); + const char *passwd = va_arg(args, const char *); + uint8_t *epasswd; + int epasswd_len; + + req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); + if (!req) + return PWDB_DENIED; + + epasswd = encrypt_password(passwd, conf_auth_secret, req->RA, &epasswd_len); + if (!epasswd) + goto out; + + if (rad_packet_add_octets(req->pack, NULL, "User-Password", epasswd, epasswd_len)) { + if (epasswd_len) + _free(epasswd); + goto out; + } + + if (epasswd_len) + _free(epasswd); + + if (conf_sid_in_auth) + if (rad_packet_add_str(req->pack, NULL, "Acct-Session-Id", rpd->ppp->sessionid)) + return -1; + + r = rad_auth_send(req); + if (r == PWDB_SUCCESS) { + struct ev_radius_t ev = { + .ppp = rpd->ppp, + .request = req->pack, + .reply = req->reply, + }; + triton_event_fire(EV_RADIUS_ACCESS_ACCEPT, &ev); + } + +out: + rad_req_free(req); + + return r; +} + +int rad_auth_chap_md5(struct radius_pd_t *rpd, const char *username, va_list args) +{ + int r = PWDB_DENIED; + uint8_t chap_password[17]; + + int id = va_arg(args, int); + uint8_t *challenge = va_arg(args, uint8_t *); + int challenge_len = va_arg(args, int); + uint8_t *response = va_arg(args, uint8_t *); + + chap_password[0] = id; + memcpy(chap_password + 1, response, 16); + + if (!rpd->auth_req) { + rpd->auth_req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); + if (!rpd->auth_req) + return PWDB_DENIED; + + if (challenge_len == 16) + memcpy(rpd->auth_req->RA, challenge, 16); + else { + if (rad_packet_add_octets(rpd->auth_req->pack, NULL, "CHAP-Challenge", challenge, challenge_len)) + goto out; + } + + if (rad_packet_add_octets(rpd->auth_req->pack, NULL, "CHAP-Password", chap_password, 17)) + goto out; + } else { + if (challenge_len == 16) + memcpy(rpd->auth_req->RA, challenge, 16); + else { + if (rad_packet_change_octets(rpd->auth_req->pack, NULL, "CHAP-Challenge", challenge, challenge_len)) + goto out; + } + + if (rad_packet_change_octets(rpd->auth_req->pack, NULL, "CHAP-Password", chap_password, 17)) + goto out; + + if (rpd->attr_state) { + if (rad_packet_find_attr(rpd->auth_req->pack, NULL, "State")) { + if (rad_packet_change_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) + goto out; + } else { + if (rad_packet_add_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) + goto out; + } + } + + if (rad_packet_build(rpd->auth_req->pack, rpd->auth_req->RA)) + return -1; + } + + if (conf_sid_in_auth) + if (rad_packet_add_str(rpd->auth_req->pack, NULL, "Acct-Session-Id", rpd->ppp->sessionid)) + goto out; + + r = rad_auth_send(rpd->auth_req); + if (r == PWDB_SUCCESS) { + struct ev_radius_t ev = { + .ppp = rpd->ppp, + .request = rpd->auth_req->pack, + .reply = rpd->auth_req->reply, + }; + triton_event_fire(EV_RADIUS_ACCESS_ACCEPT, &ev); + rpd->auth_req->pack->id++; + } + + return r; +out: + rad_req_free(rpd->auth_req); + rpd->auth_req = NULL; + + return r; +} + +static void setup_mppe(struct rad_req_t *req, const uint8_t *challenge) +{ + struct rad_attr_t *attr; + uint8_t mppe_recv_key[16]; + uint8_t mppe_send_key[16]; + struct ev_mppe_keys_t ev_mppe = { + .ppp = req->rpd->ppp, + }; + + list_for_each_entry(attr, &req->reply->attrs, entry) { + if (attr->vendor && attr->vendor->id == Vendor_Microsoft) { + switch (attr->attr->id) { + case MS_CHAP_MPPE_Keys: + if (decrypt_chap_mppe_keys(req, attr, challenge, mppe_recv_key)) + continue; + ev_mppe.recv_key = mppe_recv_key; + ev_mppe.send_key = mppe_recv_key; + break; + case MS_MPPE_Recv_Key: + if (decrypt_mppe_key(req, attr, mppe_recv_key)) + continue; + ev_mppe.recv_key = mppe_recv_key; + break; + case MS_MPPE_Send_Key: + if (decrypt_mppe_key(req, attr, mppe_send_key)) + continue; + ev_mppe.send_key = mppe_send_key; + break; + case MS_MPPE_Encryption_Policy: + ev_mppe.policy = attr->val.integer; + break; + case MS_MPPE_Encryption_Type: + ev_mppe.type = attr->val.integer; + break; + } + } + } + + if (ev_mppe.recv_key && ev_mppe.send_key) + triton_event_fire(EV_MPPE_KEYS, &ev_mppe); +} + +int rad_auth_mschap_v1(struct radius_pd_t *rpd, const char *username, va_list args) +{ + int r = PWDB_DENIED; + uint8_t response[50]; + + int id = va_arg(args, int); + const uint8_t *challenge = va_arg(args, const uint8_t *); + int challenge_len = va_arg(args, int); + const uint8_t *lm_response = va_arg(args, const uint8_t *); + const uint8_t *nt_response = va_arg(args, const uint8_t *); + int flags = va_arg(args, int); + + response[0] = id; + response[1] = flags; + memcpy(response + 2, lm_response, 24); + memcpy(response + 2 + 24, nt_response, 24); + + if (!rpd->auth_req) { + rpd->auth_req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); + if (!rpd->auth_req) + return PWDB_DENIED; + + if (rad_packet_add_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Challenge", challenge, challenge_len)) + goto out; + + if (rad_packet_add_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Response", response, sizeof(response))) + goto out; + } else { + if (rad_packet_change_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Challenge", challenge, challenge_len)) + goto out; + + if (rad_packet_change_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Response", response, sizeof(response))) + goto out; + + if (rpd->attr_state) { + if (rad_packet_find_attr(rpd->auth_req->pack, NULL, "State")) { + if (rad_packet_change_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) + goto out; + } else { + if (rad_packet_add_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) + goto out; + } + } + + if (rad_packet_build(rpd->auth_req->pack, rpd->auth_req->RA)) + return -1; + } + + if (conf_sid_in_auth) + if (rad_packet_add_str(rpd->auth_req->pack, NULL, "Acct-Session-Id", rpd->ppp->sessionid)) + goto out; + + r = rad_auth_send(rpd->auth_req); + if (r == PWDB_SUCCESS) { + struct ev_radius_t ev = { + .ppp = rpd->ppp, + .request = rpd->auth_req->pack, + .reply = rpd->auth_req->reply, + }; + triton_event_fire(EV_RADIUS_ACCESS_ACCEPT, &ev); + setup_mppe(rpd->auth_req, challenge); + rpd->auth_req->pack->id++; + } + + return r; +out: + rad_req_free(rpd->auth_req); + rpd->auth_req = NULL; + + return r; +} + +int rad_auth_mschap_v2(struct radius_pd_t *rpd, const char *username, va_list args) +{ + int r = PWDB_DENIED; + struct rad_attr_t *ra; + uint8_t mschap_response[50]; + + int id = va_arg(args, int); + const uint8_t *challenge = va_arg(args, const uint8_t *); + const uint8_t *peer_challenge = va_arg(args, const uint8_t *); + const uint8_t *reserved = va_arg(args, const uint8_t *); + const uint8_t *response = va_arg(args, const uint8_t *); + int flags = va_arg(args, int); + uint8_t *authenticator = va_arg(args, uint8_t *); + + mschap_response[0] = id; + mschap_response[1] = flags; + memcpy(mschap_response + 2, peer_challenge, 16); + memcpy(mschap_response + 2 + 16, reserved, 8); + memcpy(mschap_response + 2 + 16 + 8, response, 24); + + if (!rpd->auth_req) { + rpd->auth_req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); + if (!rpd->auth_req) + return PWDB_DENIED; + + if (rad_packet_add_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Challenge", challenge, 16)) + goto out; + + if (rad_packet_add_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP2-Response", mschap_response, sizeof(mschap_response))) + goto out; + } else { + if (rad_packet_change_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Challenge", challenge, 16)) + goto out; + + if (rad_packet_change_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP2-Response", mschap_response, sizeof(mschap_response))) + goto out; + + if (rpd->attr_state) { + if (rad_packet_find_attr(rpd->auth_req->pack, NULL, "State")) { + if (rad_packet_change_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) + goto out; + } else { + if (rad_packet_add_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) + goto out; + } + } + + if (rad_packet_build(rpd->auth_req->pack, rpd->auth_req->RA)) + return -1; + } + + if (conf_sid_in_auth) + if (rad_packet_add_str(rpd->auth_req->pack, NULL, "Acct-Session-Id", rpd->ppp->sessionid)) + goto out; + + r = rad_auth_send(rpd->auth_req); + if (r == PWDB_SUCCESS) { + ra = rad_packet_find_attr(rpd->auth_req->reply, "Microsoft", "MS-CHAP2-Success"); + if (!ra) { + log_error("radius:auth:mschap-v2: 'MS-CHAP-Success' not found in radius response\n"); + r = PWDB_DENIED; + } else + memcpy(authenticator, ra->val.octets + 3, 40); + } + if (r == PWDB_SUCCESS) { + struct ev_radius_t ev = { + .ppp = rpd->ppp, + .request = rpd->auth_req->pack, + .reply = rpd->auth_req->reply, + }; + triton_event_fire(EV_RADIUS_ACCESS_ACCEPT, &ev); + setup_mppe(rpd->auth_req, NULL); + rpd->auth_req->pack->id++; + } + + return r; +out: + rad_req_free(rpd->auth_req); + rpd->auth_req = NULL; + + return r; +} + + diff --git a/accel-pppd/radius/dict.c b/accel-pppd/radius/dict.c new file mode 100644 index 0000000..9704569 --- /dev/null +++ b/accel-pppd/radius/dict.c @@ -0,0 +1,356 @@ +#include +#include +#include +#include +#include + +#include "list.h" +#include "radius_p.h" +#include "log.h" + +#include "memdebug.h" + +static struct rad_dict_t *dict; + +static char *skip_word(char *ptr) +{ + for(; *ptr; ptr++) + if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') + break; + return ptr; +} +static char *skip_space(char *ptr) +{ + for(; *ptr; ptr++) + if (*ptr != ' ' && *ptr != '\t') + break; + return ptr; +} +static int split(char *buf, char **ptr) +{ + int i; + + for (i = 0; i < 3; i++) { + buf = skip_word(buf); + if (!*buf) + return i; + + *buf = 0; + + buf = skip_space(buf + 1); + if (!*buf) + return i; + + ptr[i] = buf; + } + + buf = skip_word(buf); + //if (*buf == '\n') + *buf = 0; + //else if (*buf) + // return -1; + + return i; +} + +struct rad_dict_attr_t *find_attr(struct list_head *items, const char *name) +{ + struct rad_dict_attr_t *attr; + + list_for_each_entry(attr, items, entry) + if (!strcmp(attr->name, name)) + return attr; + + return NULL; +} + +#define BUF_SIZE 1024 + +static char *path, *fname1, *buf; +static int dict_load(const char *fname) +{ + FILE *f; + char *ptr[3], *endptr; + int r, n = 0; + struct rad_dict_attr_t *attr; + struct rad_dict_value_t *val; + struct rad_dict_vendor_t *vendor; + struct list_head *items; + + f = fopen(fname, "r"); + if (!f) { + log_emerg("radius: open dictioanary '%s': %s\n", fname, strerror(errno)); + return -1; + } + + items = &dict->items; + + while (fgets(buf, BUF_SIZE, f)) { + n++; + if (buf[0] == '#' || buf[0] == '\n' || buf[0] == 0) + continue; + r = split(buf, ptr); + if (r == 1) { + if (!strcmp(buf, "BEGIN-VENDOR")) { + vendor = rad_dict_find_vendor_name(ptr[0]); + if (!vendor) { + log_emerg("radius:%s:%i: vendor not found\n", fname, n); + goto out_err; + } + items = &vendor->items; + } else if (!strcmp(buf, "END-VENDOR")) + items = &dict->items; + else if (!strcmp(buf, "$INCLUDE")) { + for (r = strlen(path) - 1; r; r--) + if (path[r] == '/') { + path[r + 1] = 0; + break; + } + strcpy(fname1, path); + strcat(fname1, ptr[0]); + if (dict_load(fname1)) + goto out_err; + } else + goto out_err_syntax; + } else if (r == 2) { + if (!strcmp(buf, "VENDOR")) { + vendor = malloc(sizeof(*vendor)); + if (!vendor) { + log_emerg("radius: out of memory\n"); + goto out_err; + } + vendor->id = strtol(ptr[1], &endptr, 10); + if (*endptr != 0) + goto out_err_syntax; + vendor->name = strdup(ptr[0]); + if (!vendor->name) { + log_emerg("radius: out of memory\n"); + goto out_err; + } + INIT_LIST_HEAD(&vendor->items); + list_add_tail(&vendor->entry, &dict->vendors); + } else + goto out_err_syntax; + } else if (r == 3) { + if (!strcmp(buf, "ATTRIBUTE")) { + attr = malloc(sizeof(*attr)); + if (!attr) { + log_emerg("radius: out of memory\n"); + goto out_err; + } + memset(attr, 0, sizeof(*attr)); + INIT_LIST_HEAD(&attr->values); + list_add_tail(&attr->entry, items); + attr->name = strdup(ptr[0]); + attr->id = strtol(ptr[1], &endptr, 10); + if (*endptr != 0) + goto out_err_syntax; + if (!strcmp(ptr[2], "integer")) + attr->type = ATTR_TYPE_INTEGER; + else if (!strcmp(ptr[2], "string")) + attr->type = ATTR_TYPE_STRING; + else if (!strcmp(ptr[2], "date")) + attr->type = ATTR_TYPE_DATE; + else if (!strcmp(ptr[2], "ipaddr")) + attr->type = ATTR_TYPE_IPADDR; + else if (!strcmp(ptr[2], "octets")) + attr->type = ATTR_TYPE_OCTETS; + else { + log_emerg("radius:%s:%i: unknown attribute type\n", fname, n); + goto out_err; + } + } else if (!strcmp(buf, "VALUE")) { + attr = find_attr(items, ptr[0]); + if (!attr) { + log_emerg("radius:%s:%i: unknown attribute\n", fname, n); + goto out_err; + } + val = malloc(sizeof(*val)); + if (!val) { + log_emerg("radius: out of memory\n"); + goto out_err; + } + memset(val, 0, sizeof(*val)); + list_add_tail(&val->entry, &attr->values); + val->name = strdup(ptr[1]); + switch (attr->type) { + case ATTR_TYPE_INTEGER: + val->val.integer = strtol(ptr[2], &endptr, 10); + if (*endptr != 0) + goto out_err_syntax; + break; + case ATTR_TYPE_STRING: + val->val.string = strdup(ptr[2]); + break; + case ATTR_TYPE_DATE: + log_warn("radius:%s:%i: VALUE of type 'date' is not implemented yet\n", fname, n); + break; + case ATTR_TYPE_IPADDR: + log_warn("radius:%s:%i: VALUE of type 'ipaddr' is not implemented yet\n", fname, n); + break; + } + } else + goto out_err_syntax; + } else + goto out_err_syntax; + } + + fclose(f); + + return 0; + +out_err_syntax: + log_emerg("radius:%s:%i: syntaxis error\n", fname, n); +out_err: + fclose(f); + return -1; +} + +int rad_dict_load(const char *fname) +{ + int r = -1; + + dict = malloc(sizeof(*dict)); + if (!dict) { + log_emerg("radius: out of memory\n"); + return -1; + } + INIT_LIST_HEAD(&dict->items); + INIT_LIST_HEAD(&dict->vendors); + + path = _malloc(PATH_MAX); + if (!path) { + log_emerg("radius: out of memory\n"); + goto out_free_dict; + } + + fname1 = _malloc(PATH_MAX); + if (!fname1) { + log_emerg("radius: out of memory\n"); + goto out_free_path; + } + + buf = _malloc(BUF_SIZE); + if (!buf) { + log_emerg("radius: out of memory\n"); + goto out_free_fname1; + } + + strcpy(path, fname); + + r = dict_load(fname); + +out_free_fname1: + _free(fname1); +out_free_path: + _free(path); +out_free_dict: + if (r) + rad_dict_free(dict); + return r; +} + +void rad_dict_free(struct rad_dict_t *dict) +{ + struct rad_dict_attr_t *attr; + struct rad_dict_value_t *val; + + while (!list_empty(&dict->items)) { + attr = list_entry(dict->items.next, typeof(*attr), entry); + while (!list_empty(&attr->values)) { + val = list_entry(attr->values.next, typeof(*val), entry); + list_del(&val->entry); + _free((char*)val->name); + if (attr->type == ATTR_TYPE_STRING) + _free((char*)val->val.string); + _free(val); + } + list_del(&attr->entry); + _free((char*)attr->name); + _free(attr); + } + free(dict); +} + +static struct rad_dict_attr_t *dict_find_attr(struct list_head *items, const char *name) +{ + struct rad_dict_attr_t *attr; + + list_for_each_entry(attr, items, entry) + if (!strcmp(attr->name, name)) + return attr; + + return NULL; +} + +__export struct rad_dict_attr_t *rad_dict_find_attr(const char *name) +{ + return dict_find_attr(&dict->items, name); +} + +__export struct rad_dict_attr_t *rad_dict_find_attr_id(struct rad_dict_vendor_t *vendor, int id) +{ + struct rad_dict_attr_t *attr; + struct list_head *items = vendor ? &vendor->items : &dict->items; + + list_for_each_entry(attr, items, entry) + if (attr->id == id) + return attr; + + return NULL; +} + +__export struct rad_dict_value_t *rad_dict_find_val_name(struct rad_dict_attr_t *attr, const char *name) +{ + struct rad_dict_value_t *val; + + list_for_each_entry(val, &attr->values, entry) + if (!strcmp(val->name, name)) + return val; + + return NULL; +} + +__export struct rad_dict_value_t *rad_dict_find_val(struct rad_dict_attr_t *attr, rad_value_t v) +{ + struct rad_dict_value_t *val; + + if (attr->type != ATTR_TYPE_INTEGER) + return NULL; + + list_for_each_entry(val, &attr->values, entry) + if (val->val.integer == v.integer) + return val; + + return NULL; +} + +__export struct rad_dict_vendor_t *rad_dict_find_vendor_name(const char *name) +{ + struct rad_dict_vendor_t *vendor; + + list_for_each_entry(vendor, &dict->vendors, entry) { + if (!strcmp(vendor->name, name)) + return vendor; + } + + return NULL; +} + +__export struct rad_dict_vendor_t *rad_dict_find_vendor_id(int id) +{ + struct rad_dict_vendor_t *vendor; + + list_for_each_entry(vendor, &dict->vendors, entry) { + if (vendor->id == id) + return vendor; + } + + return NULL; +} + +__export struct rad_dict_attr_t *rad_dict_find_vendor_attr(struct rad_dict_vendor_t *vendor, const char *name) +{ + return dict_find_attr(&vendor->items, name); +} + diff --git a/accel-pppd/radius/dict/dictionary b/accel-pppd/radius/dict/dictionary new file mode 100644 index 0000000..2797310 --- /dev/null +++ b/accel-pppd/radius/dict/dictionary @@ -0,0 +1,79 @@ +# -*- text -*- +# +# Version $Id: dictionary,v 1.155 2008/04/20 14:47:55 aland Exp $ +# +# DO NOT EDIT THE FILES IN THIS DIRECTORY +# +# The files in this directory are maintained and updated by +# the FreeRADIUS project. Newer releases of software may update +# or change these files. +# +# Use the main dictionary file (usually /etc/raddb/dictionary) +# for local system attributes and $INCLUDEs. +# +# +# +# This file contains dictionary translations for parsing +# requests and generating responses. All transactions are +# composed of Attribute/Value Pairs. The value of each attribute +# is specified as one of 4 data types. Valid data types are: +# +# text - printable, generally UTF-8 encoded (subset of 'string') +# string - 0-253 octets +# ipaddr - 4 octets in network byte order +# integer - 32 bit value in big endian order (high byte first) +# date - 32 bit value in big endian order - seconds since +# 00:00:00 GMT, Jan. 1, 1970 +# ifid - 8 octets in network byte order +# ipv6addr - 16 octets in network byte order +# ipv6prefix - 18 octets in network byte order +# ether - 6 octets of hh:hh:hh:hh:hh:hh +# where 'h' is hex digits, upper or lowercase. +# +# FreeRADIUS includes extended data types which are not defined +# in the RFC's. These data types are: +# +# abinary - Ascend's binary filter format. +# octets - raw octets, printed and input as hex strings. +# e.g.: 0x123456789abcdef +# +# +# Enumerated values are stored in the user file with dictionary +# VALUE translations for easy administration. +# +# Example: +# +# ATTRIBUTE VALUE +# --------------- ----- +# Framed-Protocol = PPP +# 7 = 1 (integer encoding) +# + +# +# Include compatibility dictionary for older users file. Move +# this directive to the end of this file if you want to see the +# old names in the logfiles, INSTEAD OF the new names. +# +# +# Include the RFC dictionaries next. +# +# For a complete list of the standard attributes and values, +# see: +# http://www.iana.org/assignments/radius-types +# +$INCLUDE dictionary.rfc2865 +$INCLUDE dictionary.rfc2866 +$INCLUDE dictionary.rfc2867 +$INCLUDE dictionary.rfc2868 +$INCLUDE dictionary.rfc2869 +$INCLUDE dictionary.rfc3576 +$INCLUDE dictionary.rfc3580 +$INCLUDE dictionary.rfc4072 +$INCLUDE dictionary.rfc4372 +$INCLUDE dictionary.rfc4679 +$INCLUDE dictionary.rfc5176 + +$INCLUDE dictionary.microsoft +$INCLUDE dictionary.cisco + +ATTRIBUTE Traffic-Shape-in 231 integer diff --git a/accel-pppd/radius/dict/dictionary.cisco b/accel-pppd/radius/dict/dictionary.cisco new file mode 100644 index 0000000..6d1efbe --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.cisco @@ -0,0 +1,156 @@ +# -*- text -*- +# +# dictionary.cisco +# +# Accounting VSAs originally by +# "Marcelo M. Sosa Lugones" +# +# Version: $Id: dictionary.cisco,v 1.16 2006/06/05 16:55:21 pnixon Exp $ +# +# For documentation on Cisco RADIUS attributes, see: +# +# http://www.cisco.com/univercd/cc/td/doc/product/access/acs_serv/vapp_dev/vsaig3.htm +# +# For general documentation on Cisco RADIUS configuration, see: +# +# http://www.cisco.com/en/US/partner/tech/tk583/tk547/tsd_technology_support_sub-protocol_home.html +# + +VENDOR Cisco 9 + +# +# Standard attribute +# +BEGIN-VENDOR Cisco + +ATTRIBUTE Cisco-AVPair 1 string +ATTRIBUTE Cisco-NAS-Port 2 string + +# +# T.37 Store-and-Forward attributes. +# +ATTRIBUTE Cisco-Fax-Account-Id-Origin 3 string +ATTRIBUTE Cisco-Fax-Msg-Id 4 string +ATTRIBUTE Cisco-Fax-Pages 5 string +ATTRIBUTE Cisco-Fax-Coverpage-Flag 6 string +ATTRIBUTE Cisco-Fax-Modem-Time 7 string +ATTRIBUTE Cisco-Fax-Connect-Speed 8 string +ATTRIBUTE Cisco-Fax-Recipient-Count 9 string +ATTRIBUTE Cisco-Fax-Process-Abort-Flag 10 string +ATTRIBUTE Cisco-Fax-Dsn-Address 11 string +ATTRIBUTE Cisco-Fax-Dsn-Flag 12 string +ATTRIBUTE Cisco-Fax-Mdn-Address 13 string +ATTRIBUTE Cisco-Fax-Mdn-Flag 14 string +ATTRIBUTE Cisco-Fax-Auth-Status 15 string +ATTRIBUTE Cisco-Email-Server-Address 16 string +ATTRIBUTE Cisco-Email-Server-Ack-Flag 17 string +ATTRIBUTE Cisco-Gateway-Id 18 string +ATTRIBUTE Cisco-Call-Type 19 string +ATTRIBUTE Cisco-Port-Used 20 string +ATTRIBUTE Cisco-Abort-Cause 21 string + +# +# Voice over IP attributes. +# +ATTRIBUTE h323-remote-address 23 string +ATTRIBUTE h323-conf-id 24 string +ATTRIBUTE h323-setup-time 25 string +ATTRIBUTE h323-call-origin 26 string +ATTRIBUTE h323-call-type 27 string +ATTRIBUTE h323-connect-time 28 string +ATTRIBUTE h323-disconnect-time 29 string +ATTRIBUTE h323-disconnect-cause 30 string +ATTRIBUTE h323-voice-quality 31 string +ATTRIBUTE h323-gw-id 33 string +ATTRIBUTE h323-incoming-conf-id 35 string + +ATTRIBUTE h323-credit-amount 101 string +ATTRIBUTE h323-credit-time 102 string +ATTRIBUTE h323-return-code 103 string +ATTRIBUTE h323-prompt-id 104 string +ATTRIBUTE h323-time-and-day 105 string +ATTRIBUTE h323-redirect-number 106 string +ATTRIBUTE h323-preferred-lang 107 string +ATTRIBUTE h323-redirect-ip-address 108 string +ATTRIBUTE h323-billing-model 109 string +ATTRIBUTE h323-currency 110 string +ATTRIBUTE subscriber 111 string +ATTRIBUTE gw-rxd-cdn 112 string +ATTRIBUTE gw-final-xlated-cdn 113 string +ATTRIBUTE remote-media-address 114 string +ATTRIBUTE release-source 115 string +ATTRIBUTE gw-rxd-cgn 116 string +ATTRIBUTE gw-final-xlated-cgn 117 string + +# SIP Attributes +ATTRIBUTE call-id 141 string +ATTRIBUTE session-protocol 142 string +ATTRIBUTE method 143 string +ATTRIBUTE prev-hop-via 144 string +ATTRIBUTE prev-hop-ip 145 string +ATTRIBUTE incoming-req-uri 146 string +ATTRIBUTE outgoing-req-uri 147 string +ATTRIBUTE next-hop-ip 148 string +ATTRIBUTE next-hop-dn 149 string +ATTRIBUTE sip-hdr 150 string + +# +# Extra attributes sent by the Cisco, if you configure +# "radius-server vsa accounting" (requires IOS11.2+). +# +ATTRIBUTE Cisco-Multilink-ID 187 integer +ATTRIBUTE Cisco-Num-In-Multilink 188 integer +ATTRIBUTE Cisco-Pre-Input-Octets 190 integer +ATTRIBUTE Cisco-Pre-Output-Octets 191 integer +ATTRIBUTE Cisco-Pre-Input-Packets 192 integer +ATTRIBUTE Cisco-Pre-Output-Packets 193 integer +ATTRIBUTE Cisco-Maximum-Time 194 integer +ATTRIBUTE Cisco-Disconnect-Cause 195 integer +ATTRIBUTE Cisco-Data-Rate 197 integer +ATTRIBUTE Cisco-PreSession-Time 198 integer +ATTRIBUTE Cisco-PW-Lifetime 208 integer +ATTRIBUTE Cisco-IP-Direct 209 integer +ATTRIBUTE Cisco-PPP-VJ-Slot-Comp 210 integer +ATTRIBUTE Cisco-PPP-Async-Map 212 integer +ATTRIBUTE Cisco-IP-Pool-Definition 217 string +ATTRIBUTE Cisco-Assign-IP-Pool 218 integer +ATTRIBUTE Cisco-Route-IP 228 integer +ATTRIBUTE Cisco-Link-Compression 233 integer +ATTRIBUTE Cisco-Target-Util 234 integer +ATTRIBUTE Cisco-Maximum-Channels 235 integer +ATTRIBUTE Cisco-Data-Filter 242 integer +ATTRIBUTE Cisco-Call-Filter 243 integer +ATTRIBUTE Cisco-Idle-Limit 244 integer +ATTRIBUTE Cisco-Account-Info 250 string +ATTRIBUTE Cisco-Service-Info 251 string +ATTRIBUTE Cisco-Command-Code 252 string +ATTRIBUTE Cisco-Control-Info 253 string +ATTRIBUTE Cisco-Xmit-Rate 255 integer + +VALUE Cisco-Disconnect-Cause Unknown 2 +VALUE Cisco-Disconnect-Cause CLID-Authentication-Failure 4 +VALUE Cisco-Disconnect-Cause No-Carrier 10 +VALUE Cisco-Disconnect-Cause Lost-Carrier 11 +VALUE Cisco-Disconnect-Cause No-Detected-Result-Codes 12 +VALUE Cisco-Disconnect-Cause User-Ends-Session 20 +VALUE Cisco-Disconnect-Cause Idle-Timeout 21 +VALUE Cisco-Disconnect-Cause Exit-Telnet-Session 22 +VALUE Cisco-Disconnect-Cause No-Remote-IP-Addr 23 +VALUE Cisco-Disconnect-Cause Exit-Raw-TCP 24 +VALUE Cisco-Disconnect-Cause Password-Fail 25 +VALUE Cisco-Disconnect-Cause Raw-TCP-Disabled 26 +VALUE Cisco-Disconnect-Cause Control-C-Detected 27 +VALUE Cisco-Disconnect-Cause EXEC-Program-Destroyed 28 +VALUE Cisco-Disconnect-Cause Timeout-PPP-LCP 40 +VALUE Cisco-Disconnect-Cause Failed-PPP-LCP-Negotiation 41 +VALUE Cisco-Disconnect-Cause Failed-PPP-PAP-Auth-Fail 42 +VALUE Cisco-Disconnect-Cause Failed-PPP-CHAP-Auth 43 +VALUE Cisco-Disconnect-Cause Failed-PPP-Remote-Auth 44 +VALUE Cisco-Disconnect-Cause PPP-Remote-Terminate 45 +VALUE Cisco-Disconnect-Cause PPP-Closed-Event 46 +VALUE Cisco-Disconnect-Cause Session-Timeout 100 +VALUE Cisco-Disconnect-Cause Session-Failed-Security 101 +VALUE Cisco-Disconnect-Cause Session-End-Callback 102 +VALUE Cisco-Disconnect-Cause Invalid-Protocol 120 + +END-VENDOR Cisco diff --git a/accel-pppd/radius/dict/dictionary.microsoft b/accel-pppd/radius/dict/dictionary.microsoft new file mode 100644 index 0000000..9ca6b8e --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.microsoft @@ -0,0 +1,83 @@ +# -*- text -*- +# +# Microsoft's VSA's, from RFC 2548 +# +# $Id: dictionary.microsoft,v 1.8 2005/08/08 22:23:37 aland Exp $ +# + +VENDOR Microsoft 311 + +BEGIN-VENDOR Microsoft +ATTRIBUTE MS-CHAP-Response 1 octets +ATTRIBUTE MS-CHAP-Error 2 string +ATTRIBUTE MS-CHAP-CPW-1 3 octets +ATTRIBUTE MS-CHAP-CPW-2 4 octets +ATTRIBUTE MS-CHAP-LM-Enc-PW 5 octets +ATTRIBUTE MS-CHAP-NT-Enc-PW 6 octets +ATTRIBUTE MS-MPPE-Encryption-Policy 7 integer +# This is referred to as both singular and plural in the RFC. +# Plural seems to make more sense. +ATTRIBUTE MS-MPPE-Encryption-Type 8 integer +ATTRIBUTE MS-MPPE-Encryption-Types 8 integer +ATTRIBUTE MS-RAS-Vendor 9 integer # content is Vendor-ID +ATTRIBUTE MS-CHAP-Domain 10 string +ATTRIBUTE MS-CHAP-Challenge 11 octets +ATTRIBUTE MS-CHAP-MPPE-Keys 12 octets encrypt=1 +ATTRIBUTE MS-BAP-Usage 13 integer +ATTRIBUTE MS-Link-Utilization-Threshold 14 integer # values are 1-100 +ATTRIBUTE MS-Link-Drop-Time-Limit 15 integer +ATTRIBUTE MS-MPPE-Send-Key 16 octets encrypt=2 +ATTRIBUTE MS-MPPE-Recv-Key 17 octets encrypt=2 +ATTRIBUTE MS-RAS-Version 18 string +ATTRIBUTE MS-Old-ARAP-Password 19 octets +ATTRIBUTE MS-New-ARAP-Password 20 octets +ATTRIBUTE MS-ARAP-PW-Change-Reason 21 integer + +ATTRIBUTE MS-Filter 22 octets +ATTRIBUTE MS-Acct-Auth-Type 23 integer +ATTRIBUTE MS-Acct-EAP-Type 24 integer + +ATTRIBUTE MS-CHAP2-Response 25 octets +ATTRIBUTE MS-CHAP2-Success 26 octets +ATTRIBUTE MS-CHAP2-CPW 27 octets + +ATTRIBUTE MS-Primary-DNS-Server 28 ipaddr +ATTRIBUTE MS-Secondary-DNS-Server 29 ipaddr +ATTRIBUTE MS-Primary-NBNS-Server 30 ipaddr +ATTRIBUTE MS-Secondary-NBNS-Server 31 ipaddr + +#ATTRIBUTE MS-ARAP-Challenge 33 octets + +# +# Integer Translations +# + +# MS-BAP-Usage Values + +VALUE MS-BAP-Usage Not-Allowed 0 +VALUE MS-BAP-Usage Allowed 1 +VALUE MS-BAP-Usage Required 2 + +# MS-ARAP-Password-Change-Reason Values + +VALUE MS-ARAP-PW-Change-Reason Just-Change-Password 1 +VALUE MS-ARAP-PW-Change-Reason Expired-Password 2 +VALUE MS-ARAP-PW-Change-Reason Admin-Requires-Password-Change 3 +VALUE MS-ARAP-PW-Change-Reason Password-Too-Short 4 + +# MS-Acct-Auth-Type Values + +VALUE MS-Acct-Auth-Type PAP 1 +VALUE MS-Acct-Auth-Type CHAP 2 +VALUE MS-Acct-Auth-Type MS-CHAP-1 3 +VALUE MS-Acct-Auth-Type MS-CHAP-2 4 +VALUE MS-Acct-Auth-Type EAP 5 + +# MS-Acct-EAP-Type Values + +VALUE MS-Acct-EAP-Type MD5 4 +VALUE MS-Acct-EAP-Type OTP 5 +VALUE MS-Acct-EAP-Type Generic-Token-Card 6 +VALUE MS-Acct-EAP-Type TLS 13 + +END-VENDOR Microsoft diff --git a/accel-pppd/radius/dict/dictionary.rfc2865 b/accel-pppd/radius/dict/dictionary.rfc2865 new file mode 100644 index 0000000..7e5bf58 --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc2865 @@ -0,0 +1,137 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 2865. +# http://www.ietf.org/rfc/rfc2865.txt +# +# $Id: dictionary.rfc2865,v 1.3 2005/08/10 20:59:40 aland Exp $ +# +ATTRIBUTE User-Name 1 string +ATTRIBUTE User-Password 2 octets +ATTRIBUTE CHAP-Password 3 octets +ATTRIBUTE NAS-IP-Address 4 ipaddr +ATTRIBUTE NAS-Port 5 integer +ATTRIBUTE Service-Type 6 integer +ATTRIBUTE Framed-Protocol 7 integer +ATTRIBUTE Framed-IP-Address 8 ipaddr +ATTRIBUTE Framed-IP-Netmask 9 ipaddr +ATTRIBUTE Framed-Routing 10 integer +ATTRIBUTE Filter-Id 11 string +ATTRIBUTE Framed-MTU 12 integer +ATTRIBUTE Framed-Compression 13 integer +ATTRIBUTE Login-IP-Host 14 ipaddr +ATTRIBUTE Login-Service 15 integer +ATTRIBUTE Login-TCP-Port 16 integer +# Attribute 17 is undefined +ATTRIBUTE Reply-Message 18 string +ATTRIBUTE Callback-Number 19 string +ATTRIBUTE Callback-Id 20 string +# Attribute 21 is undefined +ATTRIBUTE Framed-Route 22 string +ATTRIBUTE Framed-IPX-Network 23 ipaddr +ATTRIBUTE State 24 octets +ATTRIBUTE Class 25 octets +ATTRIBUTE Vendor-Specific 26 octets +ATTRIBUTE Session-Timeout 27 integer +ATTRIBUTE Idle-Timeout 28 integer +ATTRIBUTE Termination-Action 29 integer +ATTRIBUTE Called-Station-Id 30 string +ATTRIBUTE Calling-Station-Id 31 string +ATTRIBUTE NAS-Identifier 32 string +ATTRIBUTE Proxy-State 33 octets +ATTRIBUTE Login-LAT-Service 34 string +ATTRIBUTE Login-LAT-Node 35 string +ATTRIBUTE Login-LAT-Group 36 octets +ATTRIBUTE Framed-AppleTalk-Link 37 integer +ATTRIBUTE Framed-AppleTalk-Network 38 integer +ATTRIBUTE Framed-AppleTalk-Zone 39 string + +ATTRIBUTE CHAP-Challenge 60 octets +ATTRIBUTE NAS-Port-Type 61 integer +ATTRIBUTE Port-Limit 62 integer +ATTRIBUTE Login-LAT-Port 63 integer + +# +# Integer Translations +# + +# Service types + +VALUE Service-Type Login-User 1 +VALUE Service-Type Framed-User 2 +VALUE Service-Type Callback-Login-User 3 +VALUE Service-Type Callback-Framed-User 4 +VALUE Service-Type Outbound-User 5 +VALUE Service-Type Administrative-User 6 +VALUE Service-Type NAS-Prompt-User 7 +VALUE Service-Type Authenticate-Only 8 +VALUE Service-Type Callback-NAS-Prompt 9 +VALUE Service-Type Call-Check 10 +VALUE Service-Type Callback-Administrative 11 + +# Framed Protocols + +VALUE Framed-Protocol PPP 1 +VALUE Framed-Protocol SLIP 2 +VALUE Framed-Protocol ARAP 3 +VALUE Framed-Protocol Gandalf-SLML 4 +VALUE Framed-Protocol Xylogics-IPX-SLIP 5 +VALUE Framed-Protocol X.75-Synchronous 6 + +# Framed Routing Values + +VALUE Framed-Routing None 0 +VALUE Framed-Routing Broadcast 1 +VALUE Framed-Routing Listen 2 +VALUE Framed-Routing Broadcast-Listen 3 + +# Framed Compression Types + +VALUE Framed-Compression None 0 +VALUE Framed-Compression Van-Jacobson-TCP-IP 1 +VALUE Framed-Compression IPX-Header-Compression 2 +VALUE Framed-Compression Stac-LZS 3 + +# Login Services + +VALUE Login-Service Telnet 0 +VALUE Login-Service Rlogin 1 +VALUE Login-Service TCP-Clear 2 +VALUE Login-Service PortMaster 3 +VALUE Login-Service LAT 4 +VALUE Login-Service X25-PAD 5 +VALUE Login-Service X25-T3POS 6 +VALUE Login-Service TCP-Clear-Quiet 8 + +# Login-TCP-Port (see /etc/services for more examples) + +VALUE Login-TCP-Port Telnet 23 +VALUE Login-TCP-Port Rlogin 513 +VALUE Login-TCP-Port Rsh 514 + +# Termination Options + +VALUE Termination-Action Default 0 +VALUE Termination-Action RADIUS-Request 1 + +# NAS Port Types + +VALUE NAS-Port-Type Async 0 +VALUE NAS-Port-Type Sync 1 +VALUE NAS-Port-Type ISDN 2 +VALUE NAS-Port-Type ISDN-V120 3 +VALUE NAS-Port-Type ISDN-V110 4 +VALUE NAS-Port-Type Virtual 5 +VALUE NAS-Port-Type PIAFS 6 +VALUE NAS-Port-Type HDLC-Clear-Channel 7 +VALUE NAS-Port-Type X.25 8 +VALUE NAS-Port-Type X.75 9 +VALUE NAS-Port-Type G.3-Fax 10 +VALUE NAS-Port-Type SDSL 11 +VALUE NAS-Port-Type ADSL-CAP 12 +VALUE NAS-Port-Type ADSL-DMT 13 +VALUE NAS-Port-Type IDSL 14 +VALUE NAS-Port-Type Ethernet 15 +VALUE NAS-Port-Type xDSL 16 +VALUE NAS-Port-Type Cable 17 +VALUE NAS-Port-Type Wireless-Other 18 +VALUE NAS-Port-Type Wireless-802.11 19 diff --git a/accel-pppd/radius/dict/dictionary.rfc2866 b/accel-pppd/radius/dict/dictionary.rfc2866 new file mode 100644 index 0000000..15472bd --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc2866 @@ -0,0 +1,57 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 2866. +# http://www.ietf.org/rfc/rfc2866.txt +# +# $Id: dictionary.rfc2866,v 1.2 2005/08/08 22:23:38 aland Exp $ +# +ATTRIBUTE Acct-Status-Type 40 integer +ATTRIBUTE Acct-Delay-Time 41 integer +ATTRIBUTE Acct-Input-Octets 42 integer +ATTRIBUTE Acct-Output-Octets 43 integer +ATTRIBUTE Acct-Session-Id 44 string +ATTRIBUTE Acct-Authentic 45 integer +ATTRIBUTE Acct-Session-Time 46 integer +ATTRIBUTE Acct-Input-Packets 47 integer +ATTRIBUTE Acct-Output-Packets 48 integer +ATTRIBUTE Acct-Terminate-Cause 49 integer +ATTRIBUTE Acct-Multi-Session-Id 50 string +ATTRIBUTE Acct-Link-Count 51 integer + +# Accounting Status Types + +VALUE Acct-Status-Type Start 1 +VALUE Acct-Status-Type Stop 2 +VALUE Acct-Status-Type Alive 3 # dup +VALUE Acct-Status-Type Interim-Update 3 +VALUE Acct-Status-Type Accounting-On 7 +VALUE Acct-Status-Type Accounting-Off 8 +VALUE Acct-Status-Type Failed 15 + +# Authentication Types + +VALUE Acct-Authentic RADIUS 1 +VALUE Acct-Authentic Local 2 +VALUE Acct-Authentic Remote 3 +VALUE Acct-Authentic Diameter 4 + +# Acct Terminate Causes + +VALUE Acct-Terminate-Cause User-Request 1 +VALUE Acct-Terminate-Cause Lost-Carrier 2 +VALUE Acct-Terminate-Cause Lost-Service 3 +VALUE Acct-Terminate-Cause Idle-Timeout 4 +VALUE Acct-Terminate-Cause Session-Timeout 5 +VALUE Acct-Terminate-Cause Admin-Reset 6 +VALUE Acct-Terminate-Cause Admin-Reboot 7 +VALUE Acct-Terminate-Cause Port-Error 8 +VALUE Acct-Terminate-Cause NAS-Error 9 +VALUE Acct-Terminate-Cause NAS-Request 10 +VALUE Acct-Terminate-Cause NAS-Reboot 11 +VALUE Acct-Terminate-Cause Port-Unneeded 12 +VALUE Acct-Terminate-Cause Port-Preempted 13 +VALUE Acct-Terminate-Cause Port-Suspended 14 +VALUE Acct-Terminate-Cause Service-Unavailable 15 +VALUE Acct-Terminate-Cause Callback 16 +VALUE Acct-Terminate-Cause User-Error 17 +VALUE Acct-Terminate-Cause Host-Request 18 diff --git a/accel-pppd/radius/dict/dictionary.rfc2867 b/accel-pppd/radius/dict/dictionary.rfc2867 new file mode 100644 index 0000000..b018aba --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc2867 @@ -0,0 +1,16 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 2867. +# http://www.ietf.org/rfc/rfc2867.txt +# +# $Id: dictionary.rfc2867,v 1.2 2005/08/08 22:23:38 aland Exp $ +# +ATTRIBUTE Acct-Tunnel-Connection 68 string +ATTRIBUTE Acct-Tunnel-Packets-Lost 86 integer + +VALUE Acct-Status-Type Tunnel-Start 9 +VALUE Acct-Status-Type Tunnel-Stop 10 +VALUE Acct-Status-Type Tunnel-Reject 11 +VALUE Acct-Status-Type Tunnel-Link-Start 12 +VALUE Acct-Status-Type Tunnel-Link-Stop 13 +VALUE Acct-Status-Type Tunnel-Link-Reject 14 diff --git a/accel-pppd/radius/dict/dictionary.rfc2868 b/accel-pppd/radius/dict/dictionary.rfc2868 new file mode 100644 index 0000000..f6a4047 --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc2868 @@ -0,0 +1,54 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 2868. +# http://www.ietf.org/rfc/rfc2868.txt +# +# $Id: dictionary.rfc2868,v 1.4 2007/02/13 13:28:17 aland Exp $ +# +ATTRIBUTE Tunnel-Type 64 integer has_tag +ATTRIBUTE Tunnel-Medium-Type 65 integer has_tag +ATTRIBUTE Tunnel-Client-Endpoint 66 string has_tag +ATTRIBUTE Tunnel-Server-Endpoint 67 string has_tag + +ATTRIBUTE Tunnel-Password 69 string has_tag,encrypt=2 + +ATTRIBUTE Tunnel-Private-Group-Id 81 string has_tag +ATTRIBUTE Tunnel-Assignment-Id 82 string has_tag +ATTRIBUTE Tunnel-Preference 83 integer has_tag + +ATTRIBUTE Tunnel-Client-Auth-Id 90 string has_tag +ATTRIBUTE Tunnel-Server-Auth-Id 91 string has_tag + +# Tunnel Type + +VALUE Tunnel-Type PPTP 1 +VALUE Tunnel-Type L2F 2 +VALUE Tunnel-Type L2TP 3 +VALUE Tunnel-Type ATMP 4 +VALUE Tunnel-Type VTP 5 +VALUE Tunnel-Type AH 6 +VALUE Tunnel-Type IP 7 +VALUE Tunnel-Type MIN-IP 8 +VALUE Tunnel-Type ESP 9 +VALUE Tunnel-Type GRE 10 +VALUE Tunnel-Type DVS 11 +VALUE Tunnel-Type IP-in-IP 12 + +# Tunnel Medium Type + +VALUE Tunnel-Medium-Type IP 1 +VALUE Tunnel-Medium-Type IPv4 1 +VALUE Tunnel-Medium-Type IPv6 2 +VALUE Tunnel-Medium-Type NSAP 3 +VALUE Tunnel-Medium-Type HDLC 4 +VALUE Tunnel-Medium-Type BBN-1822 5 +VALUE Tunnel-Medium-Type IEEE-802 6 +VALUE Tunnel-Medium-Type E.163 7 +VALUE Tunnel-Medium-Type E.164 8 +VALUE Tunnel-Medium-Type F.69 9 +VALUE Tunnel-Medium-Type X.121 10 +VALUE Tunnel-Medium-Type IPX 11 +VALUE Tunnel-Medium-Type Appletalk 12 +VALUE Tunnel-Medium-Type DecNet-IV 13 +VALUE Tunnel-Medium-Type Banyan-Vines 14 +VALUE Tunnel-Medium-Type E.164-NSAP 15 diff --git a/accel-pppd/radius/dict/dictionary.rfc2869 b/accel-pppd/radius/dict/dictionary.rfc2869 new file mode 100644 index 0000000..1a2631e --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc2869 @@ -0,0 +1,39 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 2869. +# http://www.ietf.org/rfc/rfc2869.txt +# +# $Id: dictionary.rfc2869,v 1.2 2005/08/08 22:23:39 aland Exp $ +# +ATTRIBUTE Acct-Input-Gigawords 52 integer +ATTRIBUTE Acct-Output-Gigawords 53 integer + +ATTRIBUTE Event-Timestamp 55 date + +ATTRIBUTE ARAP-Password 70 octets # 16 octets of data +ATTRIBUTE ARAP-Features 71 octets # 14 octets of data +ATTRIBUTE ARAP-Zone-Access 72 integer +ATTRIBUTE ARAP-Security 73 integer +ATTRIBUTE ARAP-Security-Data 74 string +ATTRIBUTE Password-Retry 75 integer +ATTRIBUTE Prompt 76 integer +ATTRIBUTE Connect-Info 77 string +ATTRIBUTE Configuration-Token 78 string +ATTRIBUTE EAP-Message 79 octets +ATTRIBUTE Message-Authenticator 80 octets + +ATTRIBUTE ARAP-Challenge-Response 84 octets # 8 octets of data +ATTRIBUTE Acct-Interim-Interval 85 integer +# 86: RFC 2867 +ATTRIBUTE NAS-Port-Id 87 string +ATTRIBUTE Framed-Pool 88 string + +# ARAP Zone Access + +VALUE ARAP-Zone-Access Default-Zone 1 +VALUE ARAP-Zone-Access Zone-Filter-Inclusive 2 +VALUE ARAP-Zone-Access Zone-Filter-Exclusive 4 + +# Prompt +VALUE Prompt No-Echo 0 +VALUE Prompt Echo 1 diff --git a/accel-pppd/radius/dict/dictionary.rfc3576 b/accel-pppd/radius/dict/dictionary.rfc3576 new file mode 100644 index 0000000..35aeb32 --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc3576 @@ -0,0 +1,30 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 3576. +# http://www.ietf.org/rfc/rfc3576.txt +# +# $Id: dictionary.rfc3576,v 1.2 2005/08/08 22:23:39 aland Exp $ +# +ATTRIBUTE Error-Cause 101 integer + +# Service Types + +VALUE Service-Type Authorize-Only 17 + +# Error causes + +VALUE Error-Cause Residual-Context-Removed 201 +VALUE Error-Cause Invalid-EAP-Packet 202 +VALUE Error-Cause Unsupported-Attribute 401 +VALUE Error-Cause Missing-Attribute 402 +VALUE Error-Cause NAS-Identification-Mismatch 403 +VALUE Error-Cause Invalid-Request 404 +VALUE Error-Cause Unsupported-Service 405 +VALUE Error-Cause Unsupported-Extension 406 +VALUE Error-Cause Administratively-Prohibited 501 +VALUE Error-Cause Proxy-Request-Not-Routable 502 +VALUE Error-Cause Session-Context-Not-Found 503 +VALUE Error-Cause Session-Context-Not-Removable 504 +VALUE Error-Cause Proxy-Processing-Error 505 +VALUE Error-Cause Resources-Unavailable 506 +VALUE Error-Cause Request-Initiated 507 diff --git a/accel-pppd/radius/dict/dictionary.rfc3580 b/accel-pppd/radius/dict/dictionary.rfc3580 new file mode 100644 index 0000000..1bd4ca3 --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc3580 @@ -0,0 +1,16 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 3580. +# http://www.ietf.org/rfc/rfc3580.txt +# +# $Id: dictionary.rfc3580,v 1.2 2005/08/08 22:23:39 aland Exp $ +# +VALUE Acct-Terminate-Cause Supplicant-Restart 19 +VALUE Acct-Terminate-Cause Reauthentication-Failure 20 +VALUE Acct-Terminate-Cause Port-Reinit 21 +VALUE Acct-Terminate-Cause Port-Disabled 22 + +VALUE NAS-Port-Type Token-Ring 20 +VALUE NAS-Port-Type FDDI 21 + +VALUE Tunnel-Type VLAN 13 diff --git a/accel-pppd/radius/dict/dictionary.rfc4072 b/accel-pppd/radius/dict/dictionary.rfc4072 new file mode 100644 index 0000000..2280d07 --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc4072 @@ -0,0 +1,9 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 4072 +# http://www.ietf.org/rfc/4072.txt +# +# $Id: dictionary.rfc4072,v 1.1 2007/11/14 09:00:25 aland Exp $ +# + +ATTRIBUTE EAP-Key-Name 102 string diff --git a/accel-pppd/radius/dict/dictionary.rfc4372 b/accel-pppd/radius/dict/dictionary.rfc4372 new file mode 100644 index 0000000..b8af44a --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc4372 @@ -0,0 +1,8 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 4372. +# http://www.ietf.org/rfc/4372.txt +# +# $Id: dictionary.rfc4372,v 1.1 2007/04/07 14:47:34 aland Exp $ +# +ATTRIBUTE Chargeable-User-Identity 89 string diff --git a/accel-pppd/radius/dict/dictionary.rfc4675 b/accel-pppd/radius/dict/dictionary.rfc4675 new file mode 100644 index 0000000..8d1187f --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc4675 @@ -0,0 +1,28 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 4675. +# http://www.ietf.org/rfc/4675.txt +# +# $Id: dictionary.rfc4675,v 1.1 2007/04/07 14:54:14 aland Exp $ +# + +# +# High byte = '1' (0x31) means the frames are tagged. +# High byte = '2' (0x32) means the frames are untagged. +# +# Next 12 bits MUST be zero. +# +# Lower 12 bits is the IEEE-802.1Q VLAN VID. +# +ATTRIBUTE Egress-VLANID 56 integer +ATTRIBUTE Ingress-Filters 57 integer + +# +# First byte == '1' (0x31) means that the frames are tagged. +# First byte == '2' (0x32) means that the frames are untagged. +# +ATTRIBUTE Egress-VLAN-Name 58 string +ATTRIBUTE User-Priority-Table 59 octets # 8 + +VALUE Ingress-Filters Enabled 1 +VALUE Ingress-Filters Disabled 2 diff --git a/accel-pppd/radius/dict/dictionary.rfc4679 b/accel-pppd/radius/dict/dictionary.rfc4679 new file mode 100644 index 0000000..39892a5 --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc4679 @@ -0,0 +1,62 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 4679. +# http://www.ietf.org/rfc/4679.txt +# +# $Id: dictionary.rfc4679,v 1.1 2007/04/08 14:18:01 aland Exp $ +# + +VENDOR ADSL-Forum 3561 + +BEGIN-VENDOR ADSL-Forum + +# +# The first two attributes are prefixed with "ADSL-" because of +# conflicting names in dictionary.redback. +# +ATTRIBUTE ADSL-Agent-Circuit-Id 1 string +ATTRIBUTE ADSL-Agent-Remote-Id 2 string +ATTRIBUTE Actual-Data-Rate-Upstream 129 integer +ATTRIBUTE Actual-Data-Rate-Downstream 130 integer +ATTRIBUTE Minimum-Data-Rate-Upstream 131 integer +ATTRIBUTE Minimum-Data-Rate-Downstream 132 integer +ATTRIBUTE Attainable-Data-Rate-Upstream 133 integer +ATTRIBUTE Attainable-Data-Rate-Downstream 134 integer +ATTRIBUTE Maximum-Data-Rate-Upstream 135 integer +ATTRIBUTE Maximum-Data-Rate-Downstream 136 integer +ATTRIBUTE Minimum-Data-Rate-Upstream-Low-Power 137 integer +ATTRIBUTE Minimum-Data-Rate-Downstream-Low-Power 138 integer +ATTRIBUTE Maximum-Interleaving-Delay-Upstream 139 integer +ATTRIBUTE Actual-Interleaving-Delay-Upstream 140 integer +ATTRIBUTE Maximum-Interleaving-Delay-Downstream 141 integer +ATTRIBUTE Actual-Interleaving-Delay-Downstream 142 integer + +# +# This next attribute has a weird encoding. +# +# Octet[0] - 0x01 AAL5 +# Octet[0] - 0x02 Ethernet + +# Octet[1] - 0x00 Not Available +# Octet[1] - 0x01 Untagged Ethernet +# Octet[1] - 0x02 Single-Tagged Ethernet + +# Octet[2] - 0x00 Not available +# Octet[2] - 0x01 PPPoA LLC +# Octet[2] - 0x02 PPPoA Null +# Octet[2] - 0x03 IPoA LLC +# Octet[2] - 0x04 IPoA NULL +# Octet[2] - 0x05 Ethernet over AAL5 LLC with FCS +# Octet[2] - 0x06 Ethernet over AAL5 LLC without FCS +# Octet[2] - 0x07 Ethernet over AAL5 Null with FCS +# Octet[2] - 0x08 Ethernet over AAL5 Null without FCS +# +ATTRIBUTE Access-Loop-Encapsulation 144 octets # 3 + +# +# If this attribute exists, it means that IFW has been performed +# for the subscribers session. +# +ATTRIBUTE IWF-Session 252 octets # 0 + +END-VENDOR ADSL-Forum diff --git a/accel-pppd/radius/dict/dictionary.rfc4818 b/accel-pppd/radius/dict/dictionary.rfc4818 new file mode 100644 index 0000000..4ea5945 --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc4818 @@ -0,0 +1,11 @@ +# -*- text -*- +############################################################################## +# +# Attributes and values defined in RFC 4818. +# http://www.ietf.org/rfc/rfc4818.txt +# +# $Id: dictionary.rfc4818,v 1.1 2007/05/16 10:06:36 aland Exp $ +# +############################################################################## + +ATTRIBUTE Delegated-IPv6-Prefix 123 ipv6prefix diff --git a/accel-pppd/radius/dict/dictionary.rfc4849 b/accel-pppd/radius/dict/dictionary.rfc4849 new file mode 100644 index 0000000..1738eea --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc4849 @@ -0,0 +1,8 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 4849. +# http://www.ietf.org/rfc/rfc4849.txt +# +# $Id: dictionary.rfc4849,v 1.2 2007/06/15 13:08:03 aland Exp $ +# +ATTRIBUTE NAS-Filter-Rule 92 string diff --git a/accel-pppd/radius/dict/dictionary.rfc5176 b/accel-pppd/radius/dict/dictionary.rfc5176 new file mode 100644 index 0000000..9308961 --- /dev/null +++ b/accel-pppd/radius/dict/dictionary.rfc5176 @@ -0,0 +1,9 @@ +# -*- text -*- +# +# Attributes and values defined in RFC 5176. +# http://www.ietf.org/rfc/rfc5176.txt +# +# $Id: dictionary.rfc5176,v 1.1 2008/03/08 16:17:44 aland Exp $ +# +VALUE Error-Cause Invalid-Attribute-Value 407 +VALUE Error-Cause Multiple-Session-Selection-Unsupported 508 diff --git a/accel-pppd/radius/dict2c.py b/accel-pppd/radius/dict2c.py new file mode 100644 index 0000000..ff0961e --- /dev/null +++ b/accel-pppd/radius/dict2c.py @@ -0,0 +1,20 @@ +import sys,re + +hdr = file(sys.argv[2],'w') + +def process(fname, hdr): + for line in file(fname): + if line[:-1].strip() == '': + continue + if line[0] == '#': + continue + f = re.compile('[$.a-zA-Z0-9\-]+').findall(line) + if f[0] == 'ATTRIBUTE' or f[0] == 'VENDOR': + hdr.write('#define {0} {1}\n'.format(f[1].replace('-','_').replace('.','_'), f[2])) + elif f[0] == 'VALUE': + hdr.write('#define {0}_{1} {2}\n'.format(f[1].replace('-','_').replace('.','_'), f[2].replace('-','_'),f[3])) + elif f[0] == '$INCLUDE': + process(f[1], hdr) + +if __name__ == '__main__': + process(sys.argv[1], hdr) diff --git a/accel-pppd/radius/dm_coa.c b/accel-pppd/radius/dm_coa.c new file mode 100644 index 0000000..366bb41 --- /dev/null +++ b/accel-pppd/radius/dm_coa.c @@ -0,0 +1,295 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "triton.h" +#include "events.h" +#include "log.h" + +#include "radius_p.h" + +#include "memdebug.h" + +#define PD_COA_PORT 3799 + +struct dm_coa_serv_t +{ + struct triton_context_t ctx; + struct triton_md_handler_t hnd; +}; + +static struct dm_coa_serv_t serv; + +static int dm_coa_check_RA(struct rad_packet_t *pack, const char *secret) +{ + uint8_t RA[16]; + MD5_CTX ctx; + + memset(RA, 0, 16); + + MD5_Init(&ctx); + MD5_Update(&ctx, pack->buf, 4); + MD5_Update(&ctx, RA, 16); + MD5_Update(&ctx, pack->buf + 20, pack->len - 20); + MD5_Update(&ctx, secret, strlen(secret)); + MD5_Final(RA, &ctx); + + return memcmp(RA, pack->buf + 4, 16); +} + +static void dm_coa_set_RA(struct rad_packet_t *pack, const char *secret) +{ + MD5_CTX ctx; + + MD5_Init(&ctx); + MD5_Update(&ctx, pack->buf, pack->len); + MD5_Update(&ctx, secret, strlen(secret)); + MD5_Final(pack->buf + 4, &ctx); +} + +static int dm_coa_send_ack(int fd, struct rad_packet_t *req, struct sockaddr_in *addr) +{ + struct rad_packet_t *reply; + uint8_t RA[16]; + + memcpy(RA, req->buf + 4, sizeof(RA)); + + reply = rad_packet_alloc(req->code == CODE_COA_REQUEST ? CODE_COA_ACK : CODE_DISCONNECT_ACK); + if (!reply) + return -1; + + reply->id = req->id; + + if (rad_packet_build(reply, RA)) { + rad_packet_free(reply); + return -1; + } + + dm_coa_set_RA(reply, conf_dm_coa_secret); + + if (conf_verbose) { + log_ppp_info2("send "); + rad_packet_print(reply, log_ppp_info2); + } + + rad_packet_send(reply, fd, addr); + + rad_packet_free(reply); + + return 0; +} + +static int dm_coa_send_nak(int fd, struct rad_packet_t *req, struct sockaddr_in *addr, int err_code) +{ + struct rad_packet_t *reply; + uint8_t RA[16]; + + memcpy(RA, req->buf + 4, sizeof(RA)); + + reply = rad_packet_alloc(req->code == CODE_COA_REQUEST ? CODE_COA_NAK : CODE_DISCONNECT_NAK); + if (!reply) + return -1; + + reply->id = req->id; + + if (err_code) + rad_packet_add_int(reply, NULL, "Error-Cause", err_code); + + if (rad_packet_build(reply, RA)) { + rad_packet_free(reply); + return -1; + } + + dm_coa_set_RA(reply, conf_dm_coa_secret); + + if (conf_verbose) { + log_ppp_info2("send "); + rad_packet_print(reply, log_ppp_info2); + } + + rad_packet_send(reply, fd, addr); + + rad_packet_free(reply); + + return 0; +} + + +static void disconnect_request(struct radius_pd_t *rpd) +{ + if (conf_verbose) { + log_ppp_info2("recv "); + rad_packet_print(rpd->dm_coa_req, log_ppp_info2); + } + + dm_coa_send_ack(serv.hnd.fd, rpd->dm_coa_req, &rpd->dm_coa_addr); + + rad_packet_free(rpd->dm_coa_req); + + pthread_mutex_lock(&rpd->lock); + rpd->dm_coa_req = NULL; + pthread_mutex_unlock(&rpd->lock); + + ppp_terminate(rpd->ppp, TERM_ADMIN_RESET, 0); +} + +static void coa_request(struct radius_pd_t *rpd) +{ + struct ev_radius_t ev = { + .ppp = rpd->ppp, + .request = rpd->dm_coa_req, + }; + + if (conf_verbose) { + log_ppp_info2("recv "); + rad_packet_print(rpd->dm_coa_req, log_ppp_info2); + } + + triton_event_fire(EV_RADIUS_COA, &ev); + + if (ev.res) + dm_coa_send_nak(serv.hnd.fd, rpd->dm_coa_req, &rpd->dm_coa_addr, 0); + else + dm_coa_send_ack(serv.hnd.fd, rpd->dm_coa_req, &rpd->dm_coa_addr); + + rad_packet_free(rpd->dm_coa_req); + + pthread_mutex_lock(&rpd->lock); + rpd->dm_coa_req = NULL; + pthread_mutex_unlock(&rpd->lock); +} + +void dm_coa_cancel(struct radius_pd_t *rpd) +{ + triton_cancel_call(rpd->ppp->ctrl->ctx, (triton_event_func)disconnect_request); + triton_cancel_call(rpd->ppp->ctrl->ctx, (triton_event_func)coa_request); + rad_packet_free(rpd->dm_coa_req); +} + +static int dm_coa_read(struct triton_md_handler_t *h) +{ + struct rad_packet_t *pack; + struct radius_pd_t *rpd; + int err_code; + struct sockaddr_in addr; + + while (1) { + if (rad_packet_recv(h->fd, &pack, &addr)) + return 0; + + if (!pack) + continue; + + if (pack->code != CODE_DISCONNECT_REQUEST && pack->code != CODE_COA_REQUEST) { + log_warn("radius:dm_coa: unexpected code (%i) received\n", pack->code); + goto out_err_no_reply; + } + + if (dm_coa_check_RA(pack, conf_dm_coa_secret)) { + log_warn("radius:dm_coa: RA validation failed\n"); + goto out_err_no_reply; + } + + if (conf_verbose) { + log_debug("recv "); + rad_packet_print(pack, log_debug); + } + + if (rad_check_nas_pack(pack)) { + log_warn("radius:dm_coa: NAS identification failed\n"); + err_code = 403; + goto out_err; + } + + rpd = rad_find_session_pack(pack); + if (!rpd) { + log_warn("radius:dm_coa: session not found\n"); + err_code = 503; + goto out_err; + } + + if (rpd->dm_coa_req) { + pthread_mutex_unlock(&rpd->lock); + goto out_err_no_reply; + } + + rpd->dm_coa_req = pack; + memcpy(&rpd->dm_coa_addr, &addr, sizeof(addr)); + + if (pack->code == CODE_DISCONNECT_REQUEST) + triton_context_call(rpd->ppp->ctrl->ctx, (triton_event_func)disconnect_request, rpd); + else + triton_context_call(rpd->ppp->ctrl->ctx, (triton_event_func)coa_request, rpd); + + pthread_mutex_unlock(&rpd->lock); + + continue; + + out_err: + dm_coa_send_nak(h->fd, pack, &addr, err_code); + + out_err_no_reply: + rad_packet_free(pack); + } +} + +static void dm_coa_close(struct triton_context_t *ctx) +{ + struct dm_coa_serv_t *serv = container_of(ctx, typeof(*serv), ctx); + triton_md_unregister_handler(&serv->hnd); + close(serv->hnd.fd); + triton_context_unregister(ctx); +} + +static struct dm_coa_serv_t serv = { + .ctx.close = dm_coa_close, + .ctx.before_switch = log_switch, + .hnd.read = dm_coa_read, +}; + +static void __init init(void) +{ + struct sockaddr_in addr; + + if (!conf_dm_coa_secret) { + log_emerg("radius: no dm_coa_secret specified, DM/CoA disabled...\n"); + return; + } + + serv.hnd.fd = socket (PF_INET, SOCK_DGRAM, 0); + if (serv.hnd.fd < 0) { + log_emerg("radius:dm_coa: socket: %s\n", strerror(errno)); + return; + } + addr.sin_family = AF_INET; + addr.sin_port = htons (conf_dm_coa_port); + if (conf_dm_coa_server) + addr.sin_addr.s_addr = conf_dm_coa_server; + else + addr.sin_addr.s_addr = htonl (INADDR_ANY); + if (bind (serv.hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { + log_emerg("radius:dm_coa: bind: %s\n", strerror(errno)); + close(serv.hnd.fd); + return; + } + + if (fcntl(serv.hnd.fd, F_SETFL, O_NONBLOCK)) { + log_emerg("radius:dm_coa: failed to set nonblocking mode: %s\n", strerror(errno)); + close(serv.hnd.fd); + return; + } + + triton_context_register(&serv.ctx, NULL); + triton_md_register_handler(&serv.ctx, &serv.hnd); + triton_md_enable_handler(&serv.hnd, MD_MODE_READ); + triton_context_wakeup(&serv.ctx); +} diff --git a/accel-pppd/radius/packet.c b/accel-pppd/radius/packet.c new file mode 100644 index 0000000..4e24ded --- /dev/null +++ b/accel-pppd/radius/packet.c @@ -0,0 +1,644 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "log.h" +#include "mempool.h" + +#include "radius_p.h" + +#include "memdebug.h" + +static mempool_t packet_pool; +static mempool_t attr_pool; + +struct rad_packet_t *rad_packet_alloc(int code) +{ + struct rad_packet_t *pack; + + pack = mempool_alloc(packet_pool); + if (!pack) { + log_emerg("radius:packet: out of memory\n"); + return NULL; + } + + memset(pack, 0, sizeof(*pack)); + pack->code = code; + pack->len = 20; + pack->id = 1; + INIT_LIST_HEAD(&pack->attrs); + + return pack; +} + +void print_buf(uint8_t *buf,int size) +{ + int i; + for(i=0;ibuf) + ptr = _realloc(pack->buf, pack->len); + else + ptr = _malloc(pack->len); + + if (!ptr) { + log_emerg("radius:packet: out of memory\n"); + return -1; + } + + pack->buf = ptr; + *ptr = pack->code; ptr++; + *ptr = pack->id; ptr++; + *(uint16_t*)ptr = htons(pack->len); ptr+= 2; + memcpy(ptr, RA, 16); ptr+=16; + + list_for_each_entry(attr, &pack->attrs, entry) { + if (attr->vendor) { + *ptr = 26; ptr++; + *ptr = attr->len + 2 + 6; ptr++; + *(uint32_t *)ptr = htonl(attr->vendor->id); ptr+=4; + } + *ptr = attr->attr->id; ptr++; + *ptr = attr->len + 2; ptr++; + switch(attr->attr->type) { + case ATTR_TYPE_INTEGER: + *(uint32_t*)ptr = htonl(attr->val.integer); + break; + case ATTR_TYPE_OCTETS: + case ATTR_TYPE_STRING: + memcpy(ptr, attr->val.string, attr->len); + break; + case ATTR_TYPE_IPADDR: + *(in_addr_t*)ptr = attr->val.ipaddr; + break; + case ATTR_TYPE_DATE: + *(uint32_t*)ptr = htonl(attr->val.date); + break; + default: + log_emerg("radius:packet:BUG: unknown attribute type\n"); + abort(); + } + ptr += attr->len; + } + + //print_buf(pack->buf, pack->len); + return 0; +} + +int rad_packet_recv(int fd, struct rad_packet_t **p, struct sockaddr_in *addr) +{ + struct rad_packet_t *pack; + struct rad_attr_t *attr; + struct rad_dict_attr_t *da; + struct rad_dict_vendor_t *vendor; + uint8_t *ptr; + int n, id, len, vendor_id; + socklen_t addr_len = sizeof(*addr); + + *p = NULL; + + pack = rad_packet_alloc(0); + if (!pack) + return 0; + + pack->buf = _malloc(REQ_LENGTH_MAX); + if (!pack->buf) { + log_emerg("radius:packet: out of memory\n"); + goto out_err; + } + + while (1) { + if (addr) + n = recvfrom(fd, pack->buf, REQ_LENGTH_MAX, 0, addr, &addr_len); + else + n = read(fd, pack->buf, REQ_LENGTH_MAX); + if (n < 0) { + if (errno == EAGAIN) { + rad_packet_free(pack); + return -1; + } + if (errno != ECONNREFUSED) + log_ppp_error("radius:packet:read: %s\n", strerror(errno)); + goto out_err; + } + break; + } + + if (n < 20) { + log_ppp_warn("radius:packet: short packed received (%i)\n", n); + goto out_err; + } + + ptr = (uint8_t *)pack->buf; + + pack->code = *ptr; ptr++; + pack->id = *ptr; ptr++; + pack->len = ntohs(*(uint16_t*)ptr); ptr += 2; + + if (pack->len > n) { + log_ppp_warn("radius:packet: short packet received %i, expected %i\n", pack->len, n); + goto out_err; + } + + ptr += 16; + n -= 20; + + while (n>0) { + id = *ptr; ptr++; + len = *ptr - 2; ptr++; + if (len < 0) { + log_ppp_warn("radius:packet short attribute len received\n"); + goto out_err; + } + if (2 + len > n) { + log_ppp_warn("radius:packet: too long attribute received (%i, %i)\n", id, len); + goto out_err; + } + if (id == 26) { + vendor_id = ntohl(*(uint32_t *)ptr); + vendor = rad_dict_find_vendor_id(vendor_id); + if (vendor) { + ptr += 4; + id = *ptr; ptr++; + len = *ptr - 2; ptr++; + n -= 2 + 4; + } else + log_ppp_warn("radius:packet: vendor %i not found\n", id); + } else + vendor = NULL; + da = rad_dict_find_attr_id(vendor, id); + if (da) { + attr = mempool_alloc(attr_pool); + if (!attr) { + log_emerg("radius:packet: out of memory\n"); + goto out_err; + } + memset(attr, 0, sizeof(*attr)); + attr->vendor = vendor; + attr->attr = da; + attr->len = len; + switch (da->type) { + case ATTR_TYPE_STRING: + attr->val.string = _malloc(len+1); + if (!attr->val.string) { + log_emerg("radius:packet: out of memory\n"); + _free(attr); + goto out_err; + } + memcpy(attr->val.string, ptr, len); + attr->val.string[len] = 0; + break; + case ATTR_TYPE_OCTETS: + attr->val.octets = _malloc(len); + if (!attr->val.octets) { + log_emerg("radius:packet: out of memory\n"); + _free(attr); + goto out_err; + } + memcpy(attr->val.octets, ptr, len); + break; + case ATTR_TYPE_DATE: + case ATTR_TYPE_INTEGER: + attr->val.integer = ntohl(*(uint32_t*)ptr); + break; + case ATTR_TYPE_IPADDR: + attr->val.integer = *(uint32_t*)ptr; + break; + } + list_add_tail(&attr->entry, &pack->attrs); + } else + log_ppp_warn("radius:packet: unknown attribute received (%i,%i)\n", vendor ? vendor->id : 0, id); + ptr += len; + n -= 2 + len; + } + + *p = pack; + + return 0; + +out_err: + rad_packet_free(pack); + return 0; +} + +void rad_packet_free(struct rad_packet_t *pack) +{ + struct rad_attr_t *attr; + + if (pack->buf) + _free(pack->buf); + + while(!list_empty(&pack->attrs)) { + attr = list_entry(pack->attrs.next, typeof(*attr), entry); + list_del(&attr->entry); + if (attr->attr->type == ATTR_TYPE_STRING || attr->attr->type == ATTR_TYPE_OCTETS) + _free(attr->val.string); + mempool_free(attr); + } + + mempool_free(pack); +} + +void rad_packet_print(struct rad_packet_t *pack, void (*print)(const char *fmt, ...)) +{ + struct rad_attr_t *attr; + struct rad_dict_value_t *val; + + print("[RADIUS "); + switch(pack->code) { + case CODE_ACCESS_REQUEST: + print("Access-Request"); + break; + case CODE_ACCESS_CHALLENGE: + print("Access-Challenge"); + break; + case CODE_ACCESS_ACCEPT: + print("Access-Accept"); + break; + case CODE_ACCESS_REJECT: + print("Access-Reject"); + break; + case CODE_ACCOUNTING_REQUEST: + print("Accounting-Request"); + break; + case CODE_ACCOUNTING_RESPONSE: + print("Accounting-Response"); + break; + case CODE_DISCONNECT_REQUEST: + print("Disconnect-Request"); + break; + case CODE_DISCONNECT_ACK: + print("Disconnect-ACK"); + break; + case CODE_DISCONNECT_NAK: + print("Disconnect-NAK"); + break; + case CODE_COA_REQUEST: + print("CoA-Request"); + break; + case CODE_COA_ACK: + print("CoA-ACK"); + break; + case CODE_COA_NAK: + print("CoA-NAK"); + break; + default: + print("Unknown (%i)", pack->code); + } + print(" id=%x", pack->id); + + list_for_each_entry(attr, &pack->attrs, entry) { + if (attr->vendor) + print("<%s %s ", attr->vendor->name, attr->attr->name); + else + print(" <%s ", attr->attr->name); + switch (attr->attr->type) { + case ATTR_TYPE_INTEGER: + val = rad_dict_find_val(attr->attr, attr->val); + if (val) + print("%s", val->name); + else + print("%u", attr->val.integer); + break; + case ATTR_TYPE_STRING: + print("\"%s\"", attr->val.string); + break; + case ATTR_TYPE_IPADDR: + print("%i.%i.%i.%i", attr->val.ipaddr & 0xff, (attr->val.ipaddr >> 8) & 0xff, (attr->val.ipaddr >> 16) & 0xff, (attr->val.ipaddr >> 24) & 0xff); + break; + } + print(">"); + } + print("]\n"); +} + +int __export rad_packet_add_int(struct rad_packet_t *pack, const char *vendor_name, const char *name, int val) +{ + struct rad_attr_t *ra; + struct rad_dict_attr_t *attr; + struct rad_dict_vendor_t *vendor; + + if (pack->len + (vendor_name ? 8 : 2) + 4 >= REQ_LENGTH_MAX) + return -1; + + if (vendor_name) { + vendor = rad_dict_find_vendor_name(vendor_name); + if (!vendor) + return -1; + attr = rad_dict_find_vendor_attr(vendor, name); + } else { + vendor = NULL; + attr = rad_dict_find_attr(name); + } + + if (!attr) + return -1; + + ra = mempool_alloc(attr_pool); + if (!ra) + return -1; + + memset(ra, 0, sizeof(*ra)); + ra->vendor = vendor; + ra->attr = attr; + ra->len = 4; + ra->val.integer = val; + list_add_tail(&ra->entry, &pack->attrs); + pack->len += (vendor_name ? 8 : 2) + 4; + + return 0; +} + +int __export rad_packet_change_int(struct rad_packet_t *pack, const char *vendor_name, const char *name, int val) +{ + struct rad_attr_t *ra; + + ra = rad_packet_find_attr(pack, vendor_name, name); + if (!ra) + return -1; + + ra->val.integer = val; + + return 0; +} + +int __export rad_packet_add_octets(struct rad_packet_t *pack, const char *vendor_name, const char *name, const uint8_t *val, int len) +{ + struct rad_attr_t *ra; + struct rad_dict_attr_t *attr; + struct rad_dict_vendor_t *vendor; + + if (pack->len + (vendor_name ? 8 : 2) + len >= REQ_LENGTH_MAX) + return -1; + + if (vendor_name) { + vendor = rad_dict_find_vendor_name(vendor_name); + if (!vendor) + return -1; + attr = rad_dict_find_vendor_attr(vendor, name); + } else { + vendor = NULL; + attr = rad_dict_find_attr(name); + } + + if (!attr) + return -1; + + ra = mempool_alloc(attr_pool); + if (!ra) { + log_emerg("radius: out of memory\n"); + return -1; + } + + memset(ra, 0, sizeof(*ra)); + ra->vendor = vendor; + ra->attr = attr; + ra->len = len; + ra->val.octets = _malloc(len); + if (!ra->val.octets) { + log_emerg("radius: out of memory\n"); + _free(ra); + return -1; + } + memcpy(ra->val.octets, val, len); + list_add_tail(&ra->entry, &pack->attrs); + pack->len += (vendor_name ? 8 : 2) + len; + + return 0; +} + +int __export rad_packet_change_octets(struct rad_packet_t *pack, const char *vendor_name, const char *name, const uint8_t *val, int len) +{ + struct rad_attr_t *ra; + + ra = rad_packet_find_attr(pack, vendor_name, name); + if (!ra) + return -1; + + if (ra->len != len) { + if (pack->len - ra->len + len >= REQ_LENGTH_MAX) + return -1; + + ra->val.octets = _realloc(ra->val.octets, len); + if (!ra->val.octets) { + log_emerg("radius: out of memory\n"); + return -1; + } + + pack->len += len - ra->len; + ra->len = len; + } + + memcpy(ra->val.octets, val, len); + + return 0; +} + + +int __export rad_packet_add_str(struct rad_packet_t *pack, const char *vendor_name, const char *name, const char *val) +{ + struct rad_attr_t *ra; + struct rad_dict_attr_t *attr; + struct rad_dict_vendor_t *vendor; + int len = strlen(val); + + if (pack->len + (vendor_name ? 8 : 2) + len >= REQ_LENGTH_MAX) + return -1; + + if (vendor_name) { + vendor = rad_dict_find_vendor_name(vendor_name); + if (!vendor) + return -1; + attr = rad_dict_find_vendor_attr(vendor, name); + } else { + vendor = NULL; + attr = rad_dict_find_attr(name); + } + + if (!attr) + return -1; + + ra = mempool_alloc(attr_pool); + if (!ra) { + log_emerg("radius: out of memory\n"); + return -1; + } + + memset(ra, 0, sizeof(*ra)); + ra->vendor = vendor; + ra->attr = attr; + ra->len = len; + ra->val.string = _malloc(len + 1); + if (!ra->val.string) { + log_emerg("radius: out of memory\n"); + _free(ra); + return -1; + } + memcpy(ra->val.string, val, len); + ra->val.string[len] = 0; + list_add_tail(&ra->entry, &pack->attrs); + pack->len += (vendor_name ? 8 : 2) + len; + + return 0; +} + +int __export rad_packet_change_str(struct rad_packet_t *pack, const char *vendor_name, const char *name, const char *val, int len) +{ + struct rad_attr_t *ra; + + ra = rad_packet_find_attr(pack, vendor_name, name); + if (!ra) + return -1; + + if (ra->len != len) { + if (pack->len - ra->len + len >= REQ_LENGTH_MAX) + return -1; + + ra->val.string = _realloc(ra->val.string, len + 1); + if (!ra->val.string) { + log_emerg("radius: out of memory\n"); + return -1; + } + + pack->len += len - ra->len; + ra->len = len; + } + + memcpy(ra->val.string, val, len); + ra->val.string[len] = 0; + + return 0; +} + +int __export rad_packet_add_val(struct rad_packet_t *pack, const char *vendor_name, const char *name, const char *val) +{ + struct rad_attr_t *ra; + struct rad_dict_attr_t *attr; + struct rad_dict_value_t *v; + struct rad_dict_vendor_t *vendor; + + if (pack->len + (vendor_name ? 8 : 2) + 4 >= REQ_LENGTH_MAX) + return -1; + + if (vendor_name) { + vendor = rad_dict_find_vendor_name(vendor_name); + if (!vendor) + return -1; + attr = rad_dict_find_vendor_attr(vendor, name); + } else { + vendor = NULL; + attr = rad_dict_find_attr(name); + } + + if (!attr) + return -1; + + v = rad_dict_find_val_name(attr, val); + if (!v) + return -1; + + ra = mempool_alloc(attr_pool); + if (!ra) + return -1; + + memset(ra, 0, sizeof(*ra)); + ra->vendor = vendor; + ra->attr = attr; + ra->len = 4; + ra->val = v->val; + list_add_tail(&ra->entry, &pack->attrs); + pack->len += (vendor_name ? 8 : 2) + 4; + + return 0; +} + +int __export rad_packet_change_val(struct rad_packet_t *pack, const char *vendor_name, const char *name, const char *val) +{ + struct rad_attr_t *ra; + struct rad_dict_value_t *v; + + ra = rad_packet_find_attr(pack, vendor_name, name); + if (!ra) + return -1; + + v = rad_dict_find_val_name(ra->attr, val); + if (!v) + return -1; + + ra->val = v->val; + + return 0; +} + +int __export rad_packet_add_ipaddr(struct rad_packet_t *pack, const char *vendor_name, const char *name, in_addr_t ipaddr) +{ + return rad_packet_add_int(pack, vendor_name, name, ipaddr); +} + + +struct rad_attr_t __export *rad_packet_find_attr(struct rad_packet_t *pack, const char *vendor_name, const char *name) +{ + struct rad_attr_t *ra; + struct rad_dict_vendor_t *vendor; + + if (vendor_name) { + vendor = rad_dict_find_vendor_name(vendor_name); + if (!vendor) + return NULL; + } else + vendor = NULL; + + list_for_each_entry(ra, &pack->attrs, entry) { + if (vendor && vendor != ra->vendor) + continue; + + if (strcmp(ra->attr->name, name)) + continue; + + return ra; + } + + return NULL; +} + +int rad_packet_send(struct rad_packet_t *pack, int fd, struct sockaddr_in *addr) +{ + int n; + + while (1) { + if (addr) + n = sendto(fd, pack->buf, pack->len, 0, addr, sizeof(*addr)); + else + n = write(fd, pack->buf, pack->len); + if (n < 0) { + if (errno == EINTR) + continue; + log_ppp_error("radius:write: %s\n", strerror(errno)); + return -1; + } else if (n != pack->len) { + log_ppp_error("radius:write: short write %i, excpected %i\n", n, pack->len); + return -1; + } + break; + } + + return 0; +} + +static void __init init(void) +{ + attr_pool = mempool_create(sizeof(struct rad_attr_t)); + packet_pool = mempool_create(sizeof(struct rad_packet_t)); +} diff --git a/accel-pppd/radius/radius.c b/accel-pppd/radius/radius.c new file mode 100644 index 0000000..8976a33 --- /dev/null +++ b/accel-pppd/radius/radius.c @@ -0,0 +1,529 @@ +#include +#include +#include +#include +#include +#include + +#include "mempool.h" +#include "events.h" +#include "log.h" +#include "ppp.h" +#include "pwdb.h" +#include "ipdb.h" +#include "ppp_auth.h" +#include "cli.h" + +#include "radius_p.h" +#include "attr_defs.h" + +#include "memdebug.h" + +#define CHAP_MD5 5 +#define MSCHAP_V1 0x80 +#define MSCHAP_V2 0x81 + +int conf_max_try = 3; +int conf_timeout = 3; +int conf_acct_timeout = 600; +char *conf_nas_identifier; +in_addr_t conf_nas_ip_address; +in_addr_t conf_gw_ip_address; +in_addr_t conf_bind; +int conf_verbose; +int conf_interim_verbose; + +in_addr_t conf_auth_server; +int conf_auth_server_port = 1812; +char *conf_auth_secret; + +in_addr_t conf_acct_server; +int conf_acct_server_port = 1813; +char *conf_acct_secret; + +in_addr_t conf_dm_coa_server; +int conf_dm_coa_port = 3799; +char *conf_dm_coa_secret; + +int conf_sid_in_auth; +int conf_require_nas_ident; +int conf_acct_interim_interval; + +unsigned long stat_auth_sent; +unsigned long stat_auth_lost; +unsigned long stat_acct_sent; +unsigned long stat_acct_lost; +unsigned long stat_interim_sent; +unsigned long stat_interim_lost; + +static LIST_HEAD(sessions); +static pthread_rwlock_t sessions_lock = PTHREAD_RWLOCK_INITIALIZER; + +static void *pd_key; +static struct ipdb_t ipdb; + +static mempool_t rpd_pool; + +int rad_proc_attrs(struct rad_req_t *req) +{ + struct rad_attr_t *attr; + int res = 0; + + req->rpd->acct_interim_interval = conf_acct_interim_interval; + + list_for_each_entry(attr, &req->reply->attrs, entry) { + if (attr->vendor) + continue; + switch(attr->attr->id) { + case Framed_IP_Address: + if (!conf_gw_ip_address) + log_ppp_warn("radius: gw-ip-address not specified, cann't assign IP address...\n"); + else { + req->rpd->ipaddr.owner = &ipdb; + req->rpd->ipaddr.peer_addr = attr->val.ipaddr; + req->rpd->ipaddr.addr = conf_gw_ip_address; + } + break; + case Acct_Interim_Interval: + req->rpd->acct_interim_interval = attr->val.integer; + break; + case Session_Timeout: + req->rpd->session_timeout.period = attr->val.integer * 1000; + break; + case Class: + if (!req->rpd->attr_class) + req->rpd->attr_class = _malloc(attr->len); + else if (req->rpd->attr_class_len != attr->len) + req->rpd->attr_class = _realloc(req->rpd->attr_class, attr->len); + memcpy(req->rpd->attr_class, attr->val.octets, attr->len); + req->rpd->attr_class_len = attr->len; + break; + case State: + if (!req->rpd->attr_state) + req->rpd->attr_state = _malloc(attr->len); + else if (req->rpd->attr_state_len != attr->len) + req->rpd->attr_state = _realloc(req->rpd->attr_state, attr->len); + memcpy(req->rpd->attr_state, attr->val.octets, attr->len); + req->rpd->attr_state_len = attr->len; + break; + case Termination_Action: + req->rpd->termination_action = attr->val.integer; + break; + } + } + + return res; +} + +static int check(struct pwdb_t *pwdb, struct ppp_t *ppp, const char *username, int type, va_list _args) +{ + int r = PWDB_NO_IMPL; + va_list args; + int chap_type; + struct radius_pd_t *rpd = find_pd(ppp); + + va_copy(args, _args); + + switch(type) { + case PPP_PAP: + r = rad_auth_pap(rpd, username, args); + break; + case PPP_CHAP: + chap_type = va_arg(args, int); + switch(chap_type) { + case CHAP_MD5: + r = rad_auth_chap_md5(rpd, username, args); + break; + case MSCHAP_V1: + r = rad_auth_mschap_v1(rpd, username, args); + break; + case MSCHAP_V2: + r = rad_auth_mschap_v2(rpd, username, args); + break; + } + break; + } + + va_end(args); + + return r; +} + +static struct ipdb_item_t *get_ip(struct ppp_t *ppp) +{ + struct radius_pd_t *rpd = find_pd(ppp); + + if (rpd->ipaddr.peer_addr) + return &rpd->ipaddr; + return NULL; +} + +static void session_timeout(struct triton_timer_t *t) +{ + struct radius_pd_t *rpd = container_of(t, typeof(*rpd), session_timeout); + log_ppp_msg("radius: session timed out\n"); + + if (rpd->ppp->stop_time) + return; + + if (rpd->termination_action == Termination_Action_RADIUS_Request) { + if (ppp_auth_restart(rpd->ppp)) + ppp_terminate(rpd->ppp, TERM_SESSION_TIMEOUT, 0); + } else + ppp_terminate(rpd->ppp, TERM_SESSION_TIMEOUT, 0); +} + +static void ppp_starting(struct ppp_t *ppp) +{ + struct radius_pd_t *rpd = mempool_alloc(rpd_pool); + + memset(rpd, 0, sizeof(*rpd)); + rpd->pd.key = &pd_key; + rpd->ppp = ppp; + pthread_mutex_init(&rpd->lock, NULL); + INIT_LIST_HEAD(&rpd->plugin_list); + list_add_tail(&rpd->pd.entry, &ppp->pd_list); + + pthread_rwlock_wrlock(&sessions_lock); + list_add_tail(&rpd->entry, &sessions); + pthread_rwlock_unlock(&sessions_lock); +} + +static void ppp_acct_start(struct ppp_t *ppp) +{ + struct radius_pd_t *rpd = find_pd(ppp); + + if (rad_acct_start(rpd)) { + ppp_terminate(rpd->ppp, TERM_NAS_ERROR, 0); + return; + } + + if (rpd->session_timeout.period) { + rpd->session_timeout.expire = session_timeout; + triton_timer_add(ppp->ctrl->ctx, &rpd->session_timeout, 0); + } +} +static void ppp_finishing(struct ppp_t *ppp) +{ + struct radius_pd_t *rpd = find_pd(ppp); + + rad_acct_stop(rpd); +} +static void ppp_finished(struct ppp_t *ppp) +{ + struct radius_pd_t *rpd = find_pd(ppp); + + pthread_rwlock_wrlock(&sessions_lock); + pthread_mutex_lock(&rpd->lock); + list_del(&rpd->entry); + pthread_mutex_unlock(&rpd->lock); + pthread_rwlock_unlock(&sessions_lock); + + if (rpd->auth_req) + rad_req_free(rpd->auth_req); + + if (rpd->acct_req) + rad_req_free(rpd->acct_req); + + if (rpd->dm_coa_req) + dm_coa_cancel(rpd); + + if (rpd->session_timeout.tpd) + triton_timer_del(&rpd->session_timeout); + + if (rpd->attr_class) + _free(rpd->attr_class); + + if (rpd->attr_state) + _free(rpd->attr_state); + + list_del(&rpd->pd.entry); + + mempool_free(rpd); +} + +struct radius_pd_t *find_pd(struct ppp_t *ppp) +{ + struct ppp_pd_t *pd; + struct radius_pd_t *rpd; + + list_for_each_entry(pd, &ppp->pd_list, entry) { + if (pd->key == &pd_key) { + rpd = container_of(pd, typeof(*rpd), pd); + return rpd; + } + } + log_emerg("radius:BUG: rpd not found\n"); + abort(); +} + + +struct radius_pd_t *rad_find_session(const char *sessionid, const char *username, int port_id, in_addr_t ipaddr, const char *csid) +{ + struct radius_pd_t *rpd; + + pthread_rwlock_rdlock(&sessions_lock); + list_for_each_entry(rpd, &sessions, entry) { + if (!rpd->ppp->username) + continue; + if (sessionid && strcmp(sessionid, rpd->ppp->sessionid)) + continue; + if (username && strcmp(username, rpd->ppp->username)) + continue; + if (port_id >= 0 && port_id != rpd->ppp->unit_idx) + continue; + if (ipaddr && ipaddr != rpd->ppp->peer_ipaddr) + continue; + if (csid && rpd->ppp->ctrl->calling_station_id && strcmp(csid, rpd->ppp->ctrl->calling_station_id)) + continue; + pthread_mutex_lock(&rpd->lock); + pthread_rwlock_unlock(&sessions_lock); + return rpd; + } + pthread_rwlock_unlock(&sessions_lock); + return NULL; +} + +struct radius_pd_t *rad_find_session_pack(struct rad_packet_t *pack) +{ + struct rad_attr_t *attr; + const char *sessionid = NULL; + const char *username = NULL; + const char *csid = NULL; + int port_id = -1; + in_addr_t ipaddr = 0; + + list_for_each_entry(attr, &pack->attrs, entry) { + switch(attr->attr->id) { + case Acct_Session_Id: + sessionid = attr->val.string; + break; + case User_Name: + username = attr->val.string; + break; + case NAS_Port: + port_id = attr->val.integer; + break; + case Framed_IP_Address: + ipaddr = attr->val.ipaddr; + break; + case Calling_Station_Id: + csid = attr->val.string; + break; + } + } + + if (!sessionid && !username && port_id == -1 && ipaddr == 0 && !csid) + return NULL; + + if (username && !sessionid && port_id == -1 && ipaddr == 0) + return NULL; + + return rad_find_session(sessionid, username, port_id, ipaddr, csid); +} + +int rad_check_nas_pack(struct rad_packet_t *pack) +{ + struct rad_attr_t *attr; + const char *ident = NULL; + in_addr_t ipaddr = 0; + + list_for_each_entry(attr, &pack->attrs, entry) { + if (!strcmp(attr->attr->name, "NAS-Identifier")) + ident = attr->val.string; + else if (!strcmp(attr->attr->name, "NAS-IP-Address")) + ipaddr = attr->val.ipaddr; + } + + if (conf_require_nas_ident && !ident && !ipaddr) + return -1; + + if (conf_nas_identifier && ident && strcmp(conf_nas_identifier, ident)) + return -1; + + if (conf_nas_ip_address && ipaddr && conf_nas_ip_address != ipaddr) + return -1; + + return 0; +} + +static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) +{ + cli_send(client, "radius:\r\n"); + cli_sendv(client, " auth sent: %lu\r\n", stat_auth_sent); + cli_sendv(client, " auth lost: %lu\r\n", stat_auth_lost); + cli_sendv(client, " acct sent: %lu\r\n", stat_acct_sent); + cli_sendv(client, " acct lost: %lu\r\n", stat_acct_lost); + cli_sendv(client, " interim sent: %lu\r\n", stat_interim_sent); + cli_sendv(client, " interim lost: %lu\r\n", stat_interim_lost); + return CLI_CMD_OK; +} + +void __export rad_register_plugin(struct ppp_t *ppp, struct rad_plugin_t *plugin) +{ + struct radius_pd_t *rpd = find_pd(ppp); + + if (!rpd) + return; + + list_add_tail(&plugin->entry, &rpd->plugin_list); +} + +static struct ipdb_t ipdb = { + .get = get_ip, +}; + +static struct pwdb_t pwdb = { + .check = check, +}; + +static int parse_server(const char *opt, in_addr_t *addr, int *port, char **secret) +{ + char *str = _strdup(opt); + char *p1, *p2; + + p1 = strstr(str, ":"); + p2 = strstr(str, ","); + + if (p1) + *p1 = 0; + if (p2) + *p2 = 0; + else + return -1; + + *addr = inet_addr(str); + + if (p1) { + *port = atoi(p1 + 1); + if (*port <=0 ) + return -1; + } + + p1 = _strdup(p2 + 1); + p2 = *secret; + *secret = p1; + if (p2) + _free(p2); + + _free(str); + + return 0; +} + +static int load_config(void) +{ + char *opt; + + opt = conf_get_opt("radius", "max-try"); + if (opt && atoi(opt) > 0) + conf_max_try = atoi(opt); + + opt = conf_get_opt("radius", "timeout"); + if (opt && atoi(opt) > 0) + conf_timeout = atoi(opt); + + opt = conf_get_opt("radius", "acct-timeout"); + if (opt && atoi(opt) > 0) + conf_acct_timeout = atoi(opt); + + opt = conf_get_opt("radius", "verbose"); + if (opt && atoi(opt) > 0) + conf_verbose = 1; + + opt = conf_get_opt("radius", "interim-verbose"); + if (opt && atoi(opt) > 0) + conf_interim_verbose = 1; + + opt = conf_get_opt("radius", "nas-ip-address"); + if (opt) + conf_nas_ip_address = inet_addr(opt); + + if (conf_nas_identifier) + _free(conf_nas_identifier); + opt = conf_get_opt("radius", "nas-identifier"); + if (opt) + conf_nas_identifier = _strdup(opt); + else + conf_nas_identifier = NULL; + + opt = conf_get_opt("radius", "gw-ip-address"); + if (opt) + conf_gw_ip_address = inet_addr(opt); + + opt = conf_get_opt("radius", "bind"); + if (opt) + conf_bind = inet_addr(opt); + else if (conf_nas_ip_address) + conf_bind = conf_nas_ip_address; + + opt = conf_get_opt("radius", "auth-server"); + if (!opt) + opt = conf_get_opt("radius", "auth_server"); + if (!opt) { + log_emerg("radius: auth-server not specified\n"); + return -1; + } else if (parse_server(opt, &conf_auth_server, &conf_auth_server_port, &conf_auth_secret)) { + log_emerg("radius: failed to parse auth_server\n"); + return -1; + } + + opt = conf_get_opt("radius", "acct-server"); + if (!opt) + opt = conf_get_opt("radius", "acct_server"); + if (!opt) + log_emerg("radius: acct-server not specified\n"); + if (opt && parse_server(opt, &conf_acct_server, &conf_acct_server_port, &conf_acct_secret)) { + log_emerg("radius: failed to parse acct_server\n"); + return -1; + } + + opt = conf_get_opt("radius", "dae-server"); + if (opt && parse_server(opt, &conf_dm_coa_server, &conf_dm_coa_port, &conf_dm_coa_secret)) { + log_emerg("radius: failed to parse dae-server\n"); + return -1; + } + + opt = conf_get_opt("radius", "sid_in_auth"); + if (opt && atoi(opt) > 0) + conf_sid_in_auth = 1; + + opt = conf_get_opt("radius", "require-nas-identification"); + if (opt && atoi(opt) > 0) + conf_require_nas_ident = 1; + + opt = conf_get_opt("radius", "acct-interim-interval"); + if (opt && atoi(opt) > 0) + conf_acct_interim_interval = atoi(opt); + + return 0; +} + +static void __init radius_init(void) +{ + char *opt; + char *dict = DICTIONARY; + + rpd_pool = mempool_create(sizeof(struct radius_pd_t)); + + if (load_config()) + _exit(EXIT_FAILURE); + + opt = conf_get_opt("radius", "dictionary"); + if (opt) + dict = opt; + + if (rad_dict_load(dict)) + _exit(EXIT_FAILURE); + + pwdb_register(&pwdb); + ipdb_register(&ipdb); + + triton_event_register_handler(EV_PPP_STARTING, (triton_event_func)ppp_starting); + triton_event_register_handler(EV_PPP_ACCT_START, (triton_event_func)ppp_acct_start); + triton_event_register_handler(EV_PPP_FINISHING, (triton_event_func)ppp_finishing); + triton_event_register_handler(EV_PPP_FINISHED, (triton_event_func)ppp_finished); + triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); + + cli_register_simple_cmd2(show_stat_exec, NULL, 2, "show", "stat"); +} diff --git a/accel-pppd/radius/radius.h b/accel-pppd/radius/radius.h new file mode 100644 index 0000000..ad229d2 --- /dev/null +++ b/accel-pppd/radius/radius.h @@ -0,0 +1,117 @@ +#ifndef __RADIUS_H +#define __RADIUS_H + +#include + +#define REQ_LENGTH_MAX 4096 + +#define ATTR_TYPE_INTEGER 0 +#define ATTR_TYPE_STRING 1 +#define ATTR_TYPE_OCTETS 2 +#define ATTR_TYPE_DATE 3 +#define ATTR_TYPE_IPADDR 4 + +#define CODE_ACCESS_REQUEST 1 +#define CODE_ACCESS_ACCEPT 2 +#define CODE_ACCESS_REJECT 3 +#define CODE_ACCESS_CHALLENGE 11 + +#define CODE_ACCOUNTING_REQUEST 4 +#define CODE_ACCOUNTING_RESPONSE 5 + +#define CODE_DISCONNECT_REQUEST 40 +#define CODE_DISCONNECT_ACK 41 +#define CODE_DISCONNECT_NAK 42 +#define CODE_COA_REQUEST 43 +#define CODE_COA_ACK 44 +#define CODE_COA_NAK 45 + +typedef union +{ + int integer; + char *string; + uint8_t *octets; + time_t date; + in_addr_t ipaddr; +} rad_value_t; + +struct rad_dict_t +{ + struct list_head items; + struct list_head vendors; +}; + +struct rad_dict_vendor_t +{ + struct list_head entry; + int id; + const char *name; + struct list_head items; +}; + +struct rad_dict_value_t +{ + struct list_head entry; + rad_value_t val; + const char *name; +}; + +struct rad_dict_attr_t +{ + struct list_head entry; + const char *name; + int id; + int type; + struct list_head values; +}; + +struct rad_attr_t +{ + struct list_head entry; + struct rad_dict_attr_t *attr; + struct rad_dict_vendor_t *vendor; + //struct rad_dict_value_t *val; + rad_value_t val; + int len; +}; + +struct rad_packet_t +{ + int code; + uint8_t id; + int len; + struct list_head attrs; + void *buf; +}; + +struct rad_plugin_t +{ + struct list_head entry; + int (*send_access_request)(struct rad_plugin_t *, struct rad_packet_t *pack); + int (*send_accounting_request)(struct rad_plugin_t *, struct rad_packet_t *pack); +}; + +struct ppp_t; + +void rad_register_plugin(struct ppp_t *, struct rad_plugin_t *); + +struct rad_dict_attr_t *rad_dict_find_attr(const char *name); +struct rad_dict_attr_t *rad_dict_find_attr_id(struct rad_dict_vendor_t *vendor, int type); +struct rad_dict_value_t *rad_dict_find_val_name(struct rad_dict_attr_t *, const char *name); +struct rad_dict_value_t *rad_dict_find_val(struct rad_dict_attr_t *, rad_value_t val); +struct rad_dict_vendor_t *rad_dict_find_vendor_name(const char *name); +struct rad_dict_vendor_t *rad_dict_find_vendor_id(int id); +struct rad_dict_attr_t *rad_dict_find_vendor_attr(struct rad_dict_vendor_t *vendor, const char *name); + +struct rad_attr_t *rad_packet_find_attr(struct rad_packet_t *pack, const char *vendor, const char *name); +int rad_packet_add_int(struct rad_packet_t *pack, const char *vendor, const char *name, int val); +int rad_packet_add_val(struct rad_packet_t *pack, const char *vendor, const char *name, const char *val); +int rad_packet_add_str(struct rad_packet_t *pack, const char *vendor, const char *name, const char *val); +int rad_packet_add_octets(struct rad_packet_t *pack, const char *vendor, const char *name, const uint8_t *val, int len); +int rad_packet_change_int(struct rad_packet_t *pack, const char *vendor, const char *name, int val); +int rad_packet_change_val(struct rad_packet_t *pack, const char *vendor, const char *name, const char *val); +int rad_packet_change_octets(struct rad_packet_t *pack, const char *vendor, const char *name, const uint8_t *val, int len); +int rad_packet_add_ipaddr(struct rad_packet_t *pack, const char *vendor, const char *name, in_addr_t ipaddr); + +#endif + diff --git a/accel-pppd/radius/radius_p.h b/accel-pppd/radius/radius_p.h new file mode 100644 index 0000000..71c1a63 --- /dev/null +++ b/accel-pppd/radius/radius_p.h @@ -0,0 +1,122 @@ +#ifndef __RADIUS_P_H +#define __RADIUS_P_H + +#include +#include + +#include "triton.h" +#include "radius.h" +#include "ppp.h" +#include "ipdb.h" + +struct radius_pd_t +{ + struct list_head entry; + struct ppp_pd_t pd; + struct ppp_t *ppp; + pthread_mutex_t lock; + + struct rad_req_t *auth_req; + struct rad_req_t *acct_req; + struct triton_timer_t acct_interim_timer; + uint32_t acct_input_octets; + uint32_t acct_output_octets; + uint32_t acct_input_gigawords; + uint32_t acct_output_gigawords; + + struct triton_timer_t session_timeout; + + struct rad_packet_t *dm_coa_req; + struct sockaddr_in dm_coa_addr; + + struct ipdb_item_t ipaddr; + int acct_interim_interval; + time_t acct_timestamp; + + uint8_t *attr_class; + int attr_class_len; + uint8_t *attr_state; + int attr_state_len; + int termination_action; + + struct list_head plugin_list; +}; + +struct rad_req_t +{ + struct triton_context_t ctx; + struct triton_md_handler_t hnd; + struct triton_timer_t timeout; + uint8_t RA[16]; + struct rad_packet_t *pack; + struct rad_packet_t *reply; + in_addr_t server_addr; + int server_port; + + struct radius_pd_t *rpd; +}; + +extern int conf_max_try; +extern int conf_timeout; +extern int conf_acct_timeout; +extern int conf_verbose; +extern int conf_interim_verbose; +extern char *conf_nas_identifier; +extern in_addr_t conf_nas_ip_address; +extern in_addr_t conf_bind; +extern in_addr_t conf_gw_ip_address; +extern in_addr_t conf_auth_server; +extern char *conf_auth_secret; +extern int conf_auth_server_port; +extern in_addr_t conf_acct_server; +extern char *conf_acct_secret; +extern int conf_acct_server_port; +extern char *conf_dm_coa_secret; +extern int conf_sid_in_auth; +extern int conf_require_nas_ident; +extern in_addr_t conf_dm_coa_server; +extern int conf_dm_coa_port; +extern int conf_acct_interim_interval; + +extern unsigned long stat_auth_sent; +extern unsigned long stat_auth_lost; +extern unsigned long stat_acct_sent; +extern unsigned long stat_acct_lost; +extern unsigned long stat_interim_sent; +extern unsigned long stat_interim_lost; + +int rad_check_nas_pack(struct rad_packet_t *pack); +struct radius_pd_t *rad_find_session(const char *sessionid, const char *username, int port_id, in_addr_t ipaddr, const char *csid); +struct radius_pd_t *rad_find_session_pack(struct rad_packet_t *pack); + +int rad_dict_load(const char *fname); +void rad_dict_free(struct rad_dict_t *dict); + +struct rad_req_t *rad_req_alloc(struct radius_pd_t *rpd, int code, const char *username); +int rad_req_acct_fill(struct rad_req_t *); +void rad_req_free(struct rad_req_t *); +int rad_req_send(struct rad_req_t *, int verbose); +int rad_req_wait(struct rad_req_t *, int); + +struct radius_pd_t *find_pd(struct ppp_t *ppp); +int rad_proc_attrs(struct rad_req_t *req); + +int rad_auth_pap(struct radius_pd_t *rpd, const char *username, va_list args); +int rad_auth_chap_md5(struct radius_pd_t *rpd, const char *username, va_list args); +int rad_auth_mschap_v1(struct radius_pd_t *rpd, const char *username, va_list args); +int rad_auth_mschap_v2(struct radius_pd_t *rpd, const char *username, va_list args); + +int rad_acct_start(struct radius_pd_t *rpd); +void rad_acct_stop(struct radius_pd_t *rpd); + +struct rad_packet_t *rad_packet_alloc(int code); +int rad_packet_build(struct rad_packet_t *pack, uint8_t *RA); +int rad_packet_recv(int fd, struct rad_packet_t **, struct sockaddr_in *addr); +void rad_packet_free(struct rad_packet_t *); +void rad_packet_print(struct rad_packet_t *pack, void (*print)(const char *fmt, ...)); +int rad_packet_send(struct rad_packet_t *pck, int fd, struct sockaddr_in *addr); + +void dm_coa_cancel(struct radius_pd_t *pd); + +#endif + diff --git a/accel-pppd/radius/req.c b/accel-pppd/radius/req.c new file mode 100644 index 0000000..a384f23 --- /dev/null +++ b/accel-pppd/radius/req.c @@ -0,0 +1,277 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "log.h" +#include "radius_p.h" + +#include "memdebug.h" + +static int urandom_fd; + +static int rad_req_read(struct triton_md_handler_t *h); +static void rad_req_timeout(struct triton_timer_t *t); + +struct rad_req_t *rad_req_alloc(struct radius_pd_t *rpd, int code, const char *username) +{ + struct rad_plugin_t *plugin; + struct rad_req_t *req = _malloc(sizeof(*req)); + + if (!req) + return NULL; + + memset(req, 0, sizeof(*req)); + req->rpd = rpd; + req->hnd.fd = -1; + req->ctx.before_switch = log_switch; + + req->server_addr = conf_auth_server; + req->server_port = conf_auth_server_port; + + while (1) { + if (read(urandom_fd, req->RA, 16) != 16) { + if (errno == EINTR) + continue; + log_ppp_error("radius:req:read urandom: %s\n", strerror(errno)); + goto out_err; + } + break; + } + + req->pack = rad_packet_alloc(code); + if (!req->pack) + goto out_err; + + if (rad_packet_add_str(req->pack, NULL, "User-Name", username)) + goto out_err; + if (conf_nas_identifier) + if (rad_packet_add_str(req->pack, NULL, "NAS-Identifier", conf_nas_identifier)) + goto out_err; + if (conf_nas_ip_address) + if (rad_packet_add_ipaddr(req->pack, NULL, "NAS-IP-Address", conf_nas_ip_address)) + goto out_err; + if (rad_packet_add_int(req->pack, NULL, "NAS-Port", rpd->ppp->unit_idx)) + goto out_err; + if (rad_packet_add_val(req->pack, NULL, "NAS-Port-Type", "Virtual")) + goto out_err; + if (rad_packet_add_val(req->pack, NULL, "Service-Type", "Framed-User")) + goto out_err; + if (rad_packet_add_val(req->pack, NULL, "Framed-Protocol", "PPP")) + goto out_err; + if (rpd->ppp->ctrl->calling_station_id) + if (rad_packet_add_str(req->pack, NULL, "Calling-Station-Id", rpd->ppp->ctrl->calling_station_id)) + goto out_err; + if (rpd->ppp->ctrl->called_station_id) + if (rad_packet_add_str(req->pack, NULL, "Called-Station-Id", rpd->ppp->ctrl->called_station_id)) + goto out_err; + if (rpd->attr_class) + if (rad_packet_add_octets(req->pack, NULL, "Class", rpd->attr_class, rpd->attr_class_len)) + goto out_err; + + list_for_each_entry(plugin, &req->rpd->plugin_list, entry) { + switch (code) { + case CODE_ACCESS_REQUEST: + if (plugin->send_access_request && plugin->send_access_request(plugin, req->pack)) + goto out_err; + break; + case CODE_ACCOUNTING_REQUEST: + if (plugin->send_accounting_request && plugin->send_accounting_request(plugin, req->pack)) + goto out_err; + break; + } + } + + return req; + +out_err: + rad_req_free(req); + return NULL; +} + +int rad_req_acct_fill(struct rad_req_t *req) +{ + req->server_addr = conf_acct_server; + req->server_port = conf_acct_server_port; + + memset(req->RA, 0, sizeof(req->RA)); + + if (rad_packet_add_val(req->pack, NULL, "Acct-Status-Type", "Start")) + return -1; + if (rad_packet_add_val(req->pack, NULL, "Acct-Authentic", "RADIUS")) + return -1; + if (rad_packet_add_str(req->pack, NULL, "Acct-Session-Id", req->rpd->ppp->sessionid)) + return -1; + if (rad_packet_add_int(req->pack, NULL, "Acct-Session-Time", 0)) + return -1; + if (rad_packet_add_int(req->pack, NULL, "Acct-Input-Octets", 0)) + return -1; + if (rad_packet_add_int(req->pack, NULL, "Acct-Output-Octets", 0)) + return -1; + if (rad_packet_add_int(req->pack, NULL, "Acct-Input-Packets", 0)) + return -1; + if (rad_packet_add_int(req->pack, NULL, "Acct-Output-Packets", 0)) + return -1; + if (rad_packet_add_int(req->pack, NULL, "Acct-Input-Gigawords", 0)) + return -1; + if (rad_packet_add_int(req->pack, NULL, "Acct-Output-Gigawords", 0)) + return -1; + if (rad_packet_add_int(req->pack, NULL, "Acct-Delay-Time", 0)) + return -1; + if (rad_packet_add_ipaddr(req->pack, NULL, "Framed-IP-Address", req->rpd->ppp->peer_ipaddr)) + return -1; + + return 0; +} + +void rad_req_free(struct rad_req_t *req) +{ + if (req->hnd.fd >= 0 ) + close(req->hnd.fd); + if (req->pack) + rad_packet_free(req->pack); + if (req->reply) + rad_packet_free(req->reply); + _free(req); +} + +static int make_socket(struct rad_req_t *req) +{ + struct sockaddr_in addr; + + req->hnd.fd = socket(PF_INET, SOCK_DGRAM, 0); + if (req->hnd.fd < 0) { + log_ppp_error("radius:socket: %s\n", strerror(errno)); + return -1; + } + + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + + if (conf_bind) { + addr.sin_addr.s_addr = conf_bind; + if (bind(req->hnd.fd, (struct sockaddr *) &addr, sizeof(addr))) { + log_ppp_error("radius:bind: %s\n", strerror(errno)); + goto out_err; + } + } + + addr.sin_addr.s_addr = req->server_addr; + addr.sin_port = htons(req->server_port); + + if (connect(req->hnd.fd, (struct sockaddr *) &addr, sizeof(addr))) { + log_ppp_error("radius:connect: %s\n", strerror(errno)); + goto out_err; + } + + if (fcntl(req->hnd.fd, F_SETFL, O_NONBLOCK)) { + log_ppp_error("radius: failed to set nonblocking mode: %s\n", strerror(errno)); + goto out_err; + } + + return 0; + +out_err: + close(req->hnd.fd); + req->hnd.fd = -1; + return -1; +} + +int rad_req_send(struct rad_req_t *req, int verbose) +{ + if (req->hnd.fd == -1 && make_socket(req)) + return -1; + + if (!req->pack->buf && rad_packet_build(req->pack, req->RA)) + goto out_err; + + if (verbose) { + log_ppp_info1("send "); + rad_packet_print(req->pack, log_ppp_info1); + } + + rad_packet_send(req->pack, req->hnd.fd, NULL); + + return 0; + +out_err: + close(req->hnd.fd); + req->hnd.fd = -1; + return -1; +} + +static void req_wakeup(struct rad_req_t *req) +{ + struct triton_context_t *ctx = req->rpd->ppp->ctrl->ctx; + triton_timer_del(&req->timeout); + triton_md_unregister_handler(&req->hnd); + triton_context_unregister(&req->ctx); + triton_context_wakeup(ctx); +} +static int rad_req_read(struct triton_md_handler_t *h) +{ + struct rad_req_t *req = container_of(h, typeof(*req), hnd); + struct rad_packet_t *pack; + int r; + + while (1) { + r = rad_packet_recv(h->fd, &pack, NULL); + + if (pack) { + if (req->reply) + rad_packet_free(req->reply); + req->reply = pack; + } + + if (r) + break; + } + + req_wakeup(req); + + return 1; +} +static void rad_req_timeout(struct triton_timer_t *t) +{ + struct rad_req_t *req = container_of(t, typeof(*req), timeout); + + req_wakeup(req); +} + +int rad_req_wait(struct rad_req_t *req, int timeout) +{ + req->hnd.read = rad_req_read; + req->timeout.expire = rad_req_timeout; + + triton_context_register(&req->ctx, req->rpd->ppp); + triton_md_register_handler(&req->ctx, &req->hnd); + triton_md_enable_handler(&req->hnd, MD_MODE_READ); + + req->timeout.period = timeout * 1000; + triton_timer_add(&req->ctx, &req->timeout, 0); + + triton_context_wakeup(&req->ctx); + + triton_context_schedule(); + + if (conf_verbose && req->reply) { + log_ppp_info1("recv "); + rad_packet_print(req->reply, log_ppp_info1); + } + return 0; +} + +void __init req_init(void) +{ + urandom_fd = open("/dev/urandom", O_RDONLY); + if (!urandom_fd) { + log_emerg("radius:req: open /dev/urandom: %s\n", strerror(errno)); + _exit(EXIT_FAILURE); + } +} diff --git a/accel-pppd/triton/CMakeLists.txt b/accel-pppd/triton/CMakeLists.txt new file mode 100644 index 0000000..105b62a --- /dev/null +++ b/accel-pppd/triton/CMakeLists.txt @@ -0,0 +1,40 @@ +SET(sources_c + md.c + timer.c + triton.c + conf_file.c + loader.c + log.c + mempool.c + event.c +) + +INCLUDE(CheckFunctionExists) +CHECK_FUNCTION_EXISTS(timerfd_create HAVE_TIMERFD) + +IF (HAVE_TIMERFD) + ADD_DEFINITIONS(-DHAVE_TIMERFD) +ELSE (HAVE_TIMERFD) + INCLUDE (CheckCSourceCompiles) + CHECK_C_SOURCE_COMPILES(" + #include + int main() + { + syscall(SYS_timerfd_create); + }" HAVE_SYSCALL) + IF (NOT HAVE_SYSCALL) + MESSAGE(FATAL_ERROR "Your system is too old and is not supported by accel-ppp, sorry...") + ENDIF (NOT HAVE_SYSCALL) + SET(sources_c ${sources_c} timerfd.c) +ENDIF (HAVE_TIMERFD) + +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +ADD_DEFINITIONS(-DMODULE_PATH="${CMAKE_INSTALL_PREFIX}/lib/accel-ppp") + +ADD_LIBRARY(triton SHARED ${sources_c}) +TARGET_LINK_LIBRARIES(triton dl) + +INSTALL(TARGETS triton + LIBRARY DESTINATION lib/accel-ppp +) diff --git a/accel-pppd/triton/conf_file.c b/accel-pppd/triton/conf_file.c new file mode 100644 index 0000000..ce8549c --- /dev/null +++ b/accel-pppd/triton/conf_file.c @@ -0,0 +1,248 @@ +#include +#include +#include +#include +#include + +#include "triton_p.h" + +#include "memdebug.h" + +struct sect_t +{ + struct list_head entry; + + struct conf_sect_t *sect; +}; + +static pthread_mutex_t conf_lock = PTHREAD_MUTEX_INITIALIZER; +static LIST_HEAD(sections); +static char *conf_fname; + +static char* skip_space(char *str); +static char* skip_word(char *str); + +static struct conf_sect_t *find_sect(const char *name); +static struct conf_sect_t *create_sect(const char *name); +static void sect_add_item(struct conf_sect_t *sect, const char *name, const char *val); +static struct conf_option_t *find_item(struct conf_sect_t *, const char *name); + +static char *buf; + +int __conf_load(const char *fname, struct conf_sect_t *cur_sect) +{ + char *str,*str2; + int cur_line = 0; + + FILE *f = fopen(fname, "r"); + if (!f) { + perror("conf_file:open"); + return -1; + } + + while(!feof(f)) { + if (!fgets(buf, 1024, f)) + break; + ++cur_line; + if (buf[strlen(buf) - 1] == '\n') + buf[strlen(buf) - 1] = 0; + + str = skip_space(buf); + if (*str == '#' || *str == 0) + continue; + if (strncmp(str, "$include", 8) == 0) { + str = skip_word(str); + str = skip_space(str); + if (__conf_load(str, cur_sect)); + break; + continue; + } + if (*str == '[') { + for (str2 = ++str; *str2 && *str2 != ']'; str2++); + if (*str2 != ']') { + fprintf(stderr, "conf_file:%s:%i: sintax error\n", fname, cur_line); + return -1; + } + *str2 = 0; + cur_sect = find_sect(str); + if (!cur_sect) + cur_sect = create_sect(str); + continue; + } + if (!cur_sect) { + fprintf(stderr, "conf_file:%s:%i: no section opened\n", fname, cur_line); + return -1; + } + str2 = skip_word(str); + if (*str2 == ' ') { + *str2 = 0; + ++str2; + } + str2 = skip_space(str2); + if (*str2 == '=' || *str2 == ',') { + *str2 = 0; + str2 = skip_space(str2 + 1); + if (*str2 && *(str2 + 1) && *str2 == '$' && *(str2 + 1) == '{') { + char *s; + struct conf_option_t *opt; + for (s = str2+2; *s && *s != '}'; s++); + if (*s == '}') { + *s = 0; + str2 += 2; + } + opt = find_item(cur_sect, str2); + if (!opt) { + fprintf(stderr, "conf_file:%s:%i: parent option not found\n", fname, cur_line); + return -1; + } + str2 = opt->val; + } + } else + str2 = NULL; + sect_add_item(cur_sect, str, str2); + } + + fclose(f); + + return 0; +} + +int conf_load(const char *fname) +{ + int r; + + if (fname) { + if (conf_fname) + _free(conf_fname); + conf_fname = _strdup(fname); + } else + fname = conf_fname; + + buf = _malloc(1024); + + r = __conf_load(fname, NULL); + + _free(buf); + + return r; +} + +int conf_reload(const char *fname) +{ + struct sect_t *sect; + struct conf_option_t *opt; + int r; + LIST_HEAD(sections_bak); + + pthread_mutex_lock(&conf_lock); + + while (!list_empty(§ions)) { + sect = list_entry(sections.next, typeof(*sect), entry); + list_del(§->entry); + list_add_tail(§->entry, §ions_bak); + } + + r = conf_load(fname); + + if (r) { + while (!list_empty(§ions_bak)) { + sect = list_entry(sections_bak.next, typeof(*sect), entry); + list_del(§->entry); + list_add_tail(§->entry, §ions); + } + pthread_mutex_unlock(&conf_lock); + } else { + pthread_mutex_unlock(&conf_lock); + while (!list_empty(§ions_bak)) { + sect = list_entry(sections_bak.next, typeof(*sect), entry); + list_del(§->entry); + while (!list_empty(§->sect->items)) { + opt = list_entry(sect->sect->items.next, typeof(*opt), entry); + list_del(&opt->entry); + if (opt->val) + _free(opt->val); + _free(opt->name); + _free(opt); + } + _free((char *)sect->sect->name); + _free(sect->sect); + _free(sect); + } + } + + return r; +} + +static char* skip_space(char *str) +{ + for (; *str && *str == ' '; str++); + return str; +} +static char* skip_word(char *str) +{ + for (; *str && (*str != ' ' && *str != '='); str++); + return str; +} + +static struct conf_sect_t *find_sect(const char *name) +{ + struct sect_t *s; + list_for_each_entry(s, §ions, entry) + if (strcmp(s->sect->name, name) == 0) return s->sect; + return NULL; +} + +static struct conf_sect_t *create_sect(const char *name) +{ + struct sect_t *s = _malloc(sizeof(struct sect_t)); + + s->sect = _malloc(sizeof(struct conf_sect_t)); + s->sect->name = (char*)_strdup(name); + INIT_LIST_HEAD(&s->sect->items); + + list_add_tail(&s->entry, §ions); + + return s->sect; +} + +static void sect_add_item(struct conf_sect_t *sect, const char *name, const char *val) +{ + struct conf_option_t *opt = _malloc(sizeof(struct conf_option_t)); + + opt->name = _strdup(name); + opt->val = val ? _strdup(val) : NULL; + + list_add_tail(&opt->entry, §->items); +} + +static struct conf_option_t *find_item(struct conf_sect_t *sect, const char *name) +{ + struct conf_option_t *opt; + list_for_each_entry(opt, §->items, entry) { + if (strcmp(opt->name, name) == 0) + return opt; + } + + return NULL; +} + +__export struct conf_sect_t * conf_get_section(const char *name) +{ + return find_sect(name); +} + +__export char * conf_get_opt(const char *sect, const char *name) +{ + struct conf_option_t *opt; + struct conf_sect_t *s = conf_get_section(sect); + + if (!s) + return NULL; + + opt = find_item(s, name); + if (!opt) + return NULL; + + return opt->val; +} + diff --git a/accel-pppd/triton/event.c b/accel-pppd/triton/event.c new file mode 100644 index 0000000..d45eca0 --- /dev/null +++ b/accel-pppd/triton/event.c @@ -0,0 +1,105 @@ +#include +#include +#include + +#include "triton_p.h" + +#include "memdebug.h" + +static int max_events = 1024; +static struct _triton_event_t **events; + +struct event_handler_t +{ + struct list_head entry; + triton_event_func func; +}; + +int event_init(void) +{ + events = malloc(max_events * sizeof(void *)); + if (!events) { + fprintf(stderr,"event:cann't allocate memory\n"); + return -1; + } + + memset(events, 0, max_events * sizeof(void *)); + + return 0; +} + +int __export triton_event_register_handler(int ev_id, triton_event_func func) +{ + struct _triton_event_t *ev; + struct event_handler_t *h; + + if (ev_id >= max_events) + return -1; + + ev = events[ev_id]; + if (!ev) { + ev = malloc(sizeof(*ev)); + if (!ev) { + triton_log_error("event: out of memory\n"); + return -1; + } + INIT_LIST_HEAD(&ev->handlers); + events[ev_id] = ev; + } + + h = malloc(sizeof(*h)); + if (!h) { + triton_log_error("event: out of memory\n"); + return -1; + } + + h->func = func; + list_add_tail(&h->entry, &ev->handlers); + + return 0; +} + +/*int triton_event_unregister_handler(int ev_id, triton_event_func func) +{ + struct _triton_event_t *ev; + struct event_handler_t *h; + + if (ev_id >= max_events) + return -1; + + ev = events[ev_id]; + if (!ev) { + return -1; + } + + list_for_each_entry(h, &ev->handlers, entry) { + if (h->func == func) { + if (ev->in_progress) + h->func = NULL; + else { + list_del(&h->entry); + _free(h); + } + return 0; + } + } + + return -1; +}*/ + +void __export triton_event_fire(int ev_id, void *arg) +{ + struct _triton_event_t *ev; + struct event_handler_t *h; + + if (ev_id >= max_events) + return; + + ev = events[ev_id]; + if (!ev) + return; + + list_for_each_entry(h, &ev->handlers, entry) + h->func(arg); +} + diff --git a/accel-pppd/triton/list.h b/accel-pppd/triton/list.h new file mode 100644 index 0000000..d95dd71 --- /dev/null +++ b/accel-pppd/triton/list.h @@ -0,0 +1,249 @@ +#ifndef _LINUX_LIST_H +#define _LINUX_LIST_H + +//#if defined(__KERNEL__) || defined(_LVM_H_INCLUDE) + +//#include + +/* + * Simple doubly linked list implementation. + * + * Some of the internal functions ("__xxx") are useful when + * manipulating whole lists rather than single entries, as + * sometimes we already know the next/prev entries and we can + * generate better code by using them directly rather than + * using the generic single-entry routines. + */ + +typedef struct list_head { + struct list_head *next, *prev; +} list_t; + +#define LIST_HEAD_INIT(name) { &(name), &(name) } + +#define LIST_HEAD(name) \ + struct list_head name = LIST_HEAD_INIT(name) + +#define INIT_LIST_HEAD(ptr) do { \ + (ptr)->next = (ptr); (ptr)->prev = (ptr); \ +} while (0) + +/* + * Insert a new entry between two known consecutive entries. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ + +static void inline prefetch(void *p){} + +static inline void __list_add(struct list_head *new, + struct list_head *prev, + struct list_head *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} + +/** + * list_add - add a new entry + * @new: new entry to be added + * @head: list head to add it after + * + * Insert a new entry after the specified head. + * This is good for implementing stacks. + */ +static inline void list_add(struct list_head *new, struct list_head *head) +{ + __list_add(new, head, head->next); +} + +/** + * list_add_tail - add a new entry + * @new: new entry to be added + * @head: list head to add it before + * + * Insert a new entry before the specified head. + * This is useful for implementing queues. + */ +static inline void list_add_tail(struct list_head *new, struct list_head *head) +{ + __list_add(new, head->prev, head); +} + +/* + * Delete a list entry by making the prev/next entries + * point to each other. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_del(struct list_head *prev, struct list_head *next) +{ + next->prev = prev; + prev->next = next; +} + +/** + * list_del - deletes entry from list. + * @entry: the element to delete from the list. + * Note: list_empty on entry does not return true after this, the entry is in an undefined state. + */ +static inline void list_del(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + entry->next = (void *) 0; + entry->prev = (void *) 0; +} + +/** + * list_del_init - deletes entry from list and reinitialize it. + * @entry: the element to delete from the list. + */ +static inline void list_del_init(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + INIT_LIST_HEAD(entry); +} + +/** + * list_move - delete from one list and add as another's head + * @list: the entry to move + * @head: the head that will precede our entry + */ +static inline void list_move(struct list_head *list, struct list_head *head) +{ + __list_del(list->prev, list->next); + list_add(list, head); +} + +/** + * list_move_tail - delete from one list and add as another's tail + * @list: the entry to move + * @head: the head that will follow our entry + */ +static inline void list_move_tail(struct list_head *list, + struct list_head *head) +{ + __list_del(list->prev, list->next); + list_add_tail(list, head); +} + +/** + * list_empty - tests whether a list is empty + * @head: the list to test. + */ +static inline int list_empty(struct list_head *head) +{ + return head->next == head; +} + +static inline void __list_splice(struct list_head *list, + struct list_head *head) +{ + struct list_head *first = list->next; + struct list_head *last = list->prev; + struct list_head *at = head->next; + + first->prev = head; + head->next = first; + + last->next = at; + at->prev = last; +} + +/** + * list_splice - join two lists + * @list: the new list to add. + * @head: the place to add it in the first list. + */ +static inline void list_splice(struct list_head *list, struct list_head *head) +{ + if (!list_empty(list)) + __list_splice(list, head); +} + +/** + * list_splice_init - join two lists and reinitialise the emptied list. + * @list: the new list to add. + * @head: the place to add it in the first list. + * + * The list at @list is reinitialised + */ +static inline void list_splice_init(struct list_head *list, + struct list_head *head) +{ + if (!list_empty(list)) { + __list_splice(list, head); + INIT_LIST_HEAD(list); + } +} + +/** + * list_entry - get the struct for this entry + * @ptr: the &struct list_head pointer. + * @type: the type of the struct this is embedded in. + * @member: the name of the list_struct within the struct. + */ +#define list_entry(ptr, type, member) \ + ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) + +/** + * list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + */ +#define list_for_each(pos, head) \ + for (pos = (head)->next, prefetch(pos->next); pos != (head); \ + pos = pos->next, prefetch(pos->next)) + +/** + * __list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + * + * This variant differs from list_for_each() in that it's the + * simplest possible list iteration code, no prefetching is done. + * Use this for code that knows the list to be very short (empty + * or 1 entry) most of the time. + */ +#define __list_for_each(pos, head) \ + for (pos = (head)->next; pos != (head); pos = pos->next) + +/** + * list_for_each_prev - iterate over a list backwards + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + */ +#define list_for_each_prev(pos, head) \ + for (pos = (head)->prev, prefetch(pos->prev); pos != (head); \ + pos = pos->prev, prefetch(pos->prev)) + +/** + * list_for_each_safe - iterate over a list safe against removal of list entry + * @pos: the &struct list_head to use as a loop counter. + * @n: another &struct list_head to use as temporary storage + * @head: the head for your list. + */ +#define list_for_each_safe(pos, n, head) \ + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, n = pos->next) + +/** + * list_for_each_entry - iterate over list of given type + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member), \ + prefetch(pos->member.next); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member), \ + prefetch(pos->member.next)) + +//#endif /* __KERNEL__ || _LVM_H_INCLUDE */ + +#endif diff --git a/accel-pppd/triton/loader.c b/accel-pppd/triton/loader.c new file mode 100644 index 0000000..2a2a2e2 --- /dev/null +++ b/accel-pppd/triton/loader.c @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "triton_p.h" + +#include "memdebug.h" + +int load_modules(const char *name) +{ + struct conf_sect_t *sect; + struct conf_option_t *opt; + char *fname; + char *path = MODULE_PATH; + + sect = conf_get_section(name); + if (!sect) { + fprintf(stderr, "loader: section '%s' not found\n", name); + return -1; + } + + fname = _malloc(PATH_MAX); + + list_for_each_entry(opt, §->items, entry) { + if (!strcmp(opt->name,"path") && opt->val) { + path = opt->val; + continue; + } + + strcpy(fname, path); + strcat(fname, "/"); + strcat(fname, opt->name); + if (access(fname, F_OK)) { + strcpy(fname, path); + strcat(fname, "/lib"); + strcat(fname, opt->name); + strcat(fname, ".so"); + if (access(fname, F_OK)) { + strcpy(fname, opt->name); + if (access(opt->name, F_OK)) { + triton_log_error("loader: '%s' not found\n", opt->name); + continue; + } + } + } + + if (!dlopen(fname, RTLD_LAZY | RTLD_GLOBAL)) { + triton_log_error("loader: failed to load '%s': %s\n", opt->name, dlerror()); + _free(fname); + return -1; + } + } + + _free(fname); + + return 0; +} + diff --git a/accel-pppd/triton/log.c b/accel-pppd/triton/log.c new file mode 100644 index 0000000..c7e6b7f --- /dev/null +++ b/accel-pppd/triton/log.c @@ -0,0 +1,73 @@ +#include +#include + +#include "triton_p.h" + +#include "memdebug.h" + +static FILE *f_error; +static FILE *f_debug; +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + +int log_init(void) +{ + char *log_error = conf_get_opt("core","log-error"); + char *log_debug = conf_get_opt("core","log-debug"); + + if (log_error) { + f_error = fopen(log_error, "a"); + if (!f_error) { + perror("log:log_error:open"); + return -1; + } + } + if (log_debug) { + f_debug = fopen(log_debug, "a"); + if (!f_debug) { + perror("log:log_debug:open"); + return -1; + } + } + + return 0; +} + +static void do_log(FILE *f, const char *fmt, va_list ap) +{ + struct timeval tv; + struct tm tm; + char date[64]; + + gettimeofday(&tv, NULL); + localtime_r(&tv.tv_sec, &tm); + strftime(date, sizeof(date), "%F %H:%M:%S", &tm); + + pthread_mutex_lock(&lock); + fprintf(f, "[%s.%i]", date, (int)tv.tv_usec / 1000); + vfprintf(f, fmt,ap); + pthread_mutex_unlock(&lock); + + fflush(f); +} +void triton_log_error(const char *fmt,...) +{ + va_list ap; + + if (!f_error) + return; + + va_start(ap, fmt); + do_log(f_error, fmt, ap); +} + +void triton_log_debug(const char *fmt,...) +{ + va_list ap; + + if (!f_debug) + return; + + va_start(ap, fmt); + do_log(f_debug, fmt, ap); +} + diff --git a/accel-pppd/triton/md.c b/accel-pppd/triton/md.c new file mode 100644 index 0000000..84073d0 --- /dev/null +++ b/accel-pppd/triton/md.c @@ -0,0 +1,216 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "triton_p.h" + +#include "memdebug.h" + +extern int max_events; + +static int epoll_fd; +static struct epoll_event *epoll_events; + +static pthread_t md_thr; +static void *md_thread(void *arg); + +static mempool_t *md_pool; + +static pthread_mutex_t freed_list_lock = PTHREAD_MUTEX_INITIALIZER; +static LIST_HEAD(freed_list); +static LIST_HEAD(freed_list2); + +int md_init(void) +{ + epoll_fd = epoll_create(1); + if (epoll_fd < 0) { + perror("md:epoll_create"); + return -1; + } + + epoll_events = _malloc(max_events * sizeof(struct epoll_event)); + if (!epoll_events) { + fprintf(stderr,"md:cann't allocate memory\n"); + return -1; + } + + md_pool = mempool_create(sizeof(struct _triton_md_handler_t)); + + return 0; +} +void md_run(void) +{ + if (pthread_create(&md_thr, NULL, md_thread, NULL)) { + triton_log_error("md:pthread_create: %s", strerror(errno)); + _exit(-1); + } +} + +void md_terminate(void) +{ + pthread_cancel(md_thr); + pthread_join(md_thr, NULL); +} + +static void *md_thread(void *arg) +{ + int i,n,r; + struct _triton_md_handler_t *h; + sigset_t set; + + sigfillset(&set); + sigdelset(&set, SIGKILL); + sigdelset(&set, SIGSTOP); + pthread_sigmask(SIG_BLOCK, &set, NULL); + + while(1) { + n = epoll_wait(epoll_fd, epoll_events, max_events, -1); + if (n < 0) { + if (errno == EINTR) + continue; + triton_log_error("md:epoll_wait: %s\n", strerror(errno)); + _exit(-1); + } + + for(i = 0; i < n; i++) { + h = (struct _triton_md_handler_t *)epoll_events[i].data.ptr; + if (!h->ud) + continue; + spin_lock(&h->ctx->lock); + if (h->ud) { + h->trig_epoll_events |= epoll_events[i].events; + if (!h->pending) { + list_add_tail(&h->entry2, &h->ctx->pending_handlers); + h->pending = 1; + __sync_add_and_fetch(&triton_stat.md_handler_pending, 1); + r = triton_queue_ctx(h->ctx); + } else + r = 0; + } else + r = 0; + spin_unlock(&h->ctx->lock); + if (r) + triton_thread_wakeup(h->ctx->thread); + } + + while (!list_empty(&freed_list2)) { + h = list_entry(freed_list2.next, typeof(*h), entry); + list_del(&h->entry); + mempool_free(h); + } + + pthread_mutex_lock(&freed_list_lock); + while (!list_empty(&freed_list)) { + h = list_entry(freed_list.next, typeof(*h), entry); + list_del(&h->entry); + list_add(&h->entry, &freed_list2); + } + pthread_mutex_unlock(&freed_list_lock); + } + + return NULL; +} + +void __export triton_md_register_handler(struct triton_context_t *ctx, struct triton_md_handler_t *ud) +{ + struct _triton_md_handler_t *h = mempool_alloc(md_pool); + memset(h, 0, sizeof(*h)); + h->ud = ud; + h->epoll_event.data.ptr = h; + if (ctx) + h->ctx = (struct _triton_context_t *)ctx->tpd; + else + h->ctx = (struct _triton_context_t *)default_ctx.tpd; + ud->tpd = h; + spin_lock(&h->ctx->lock); + list_add_tail(&h->entry, &h->ctx->handlers); + spin_unlock(&h->ctx->lock); + + triton_stat.md_handler_count++; +} +void __export triton_md_unregister_handler(struct triton_md_handler_t *ud) +{ + struct _triton_md_handler_t *h = (struct _triton_md_handler_t *)ud->tpd; + triton_md_disable_handler(ud, MD_MODE_READ | MD_MODE_WRITE); + + spin_lock(&h->ctx->lock); + h->ud = NULL; + list_del(&h->entry); + if (h->pending) { + list_del(&h->entry2); + __sync_sub_and_fetch(&triton_stat.md_handler_pending, 1); + } + spin_unlock(&h->ctx->lock); + + sched_yield(); + + pthread_mutex_lock(&freed_list_lock); + list_add_tail(&h->entry, &freed_list); + pthread_mutex_unlock(&freed_list_lock); + + triton_stat.md_handler_count--; +} +int __export triton_md_enable_handler(struct triton_md_handler_t *ud, int mode) +{ + struct _triton_md_handler_t *h = (struct _triton_md_handler_t *)ud->tpd; + int r; + int events = h->epoll_event.events; + + if (mode & MD_MODE_READ) + h->epoll_event.events |= EPOLLIN; + if (mode & MD_MODE_WRITE) + h->epoll_event.events |= EPOLLOUT; + + if (!h->trig_level) + h->epoll_event.events |= EPOLLET; + + if (events) + r = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, h->ud->fd, &h->epoll_event); + else + r = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, h->ud->fd, &h->epoll_event); + + if (r) { + triton_log_error("md:epoll_ctl: %s\n",strerror(errno)); + abort(); + } + + return r; +} +int __export triton_md_disable_handler(struct triton_md_handler_t *ud,int mode) +{ + struct _triton_md_handler_t *h = (struct _triton_md_handler_t *)ud->tpd; + int r=0; + + if (!h->epoll_event.events) + return -1; + + if (mode & MD_MODE_READ) + h->epoll_event.events &= ~EPOLLIN; + if (mode & MD_MODE_WRITE) + h->epoll_event.events &= ~EPOLLOUT; + + if (h->epoll_event.events & (EPOLLIN | EPOLLOUT)) + r = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, h->ud->fd, &h->epoll_event); + else { + h->epoll_event.events = 0; + r = epoll_ctl(epoll_fd, EPOLL_CTL_DEL, h->ud->fd, NULL); + } + + if (r) { + triton_log_error("md:epoll_ctl: %s\n",strerror(errno)); + abort(); + } + + return r; +} + +void __export triton_md_set_trig(struct triton_md_handler_t *ud, int mode) +{ + struct _triton_md_handler_t *h = (struct _triton_md_handler_t *)ud->tpd; + h->trig_level = mode; +} + diff --git a/accel-pppd/triton/mempool.c b/accel-pppd/triton/mempool.c new file mode 100644 index 0000000..855e22e --- /dev/null +++ b/accel-pppd/triton/mempool.c @@ -0,0 +1,338 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "triton_p.h" + +#include "memdebug.h" + +#ifdef VALGRIND +#include +#define DELAY 5 +#endif + +//#define MEMPOOL_DISABLE + +#define MAGIC1 0x2233445566778899llu + +struct _mempool_t +{ + struct list_head entry; + int size; + struct list_head items; +#ifdef MEMDEBUG + struct list_head ditems; +#endif + spinlock_t lock; + uint64_t magic; + int mmap:1; +}; + +struct _item_t +{ + struct list_head entry; +#ifdef VALGRIND + time_t timestamp; +#endif + struct _mempool_t *owner; +#ifdef MEMDEBUG + const char *fname; + int line; +#endif + uint64_t magic2; + uint64_t magic1; + char ptr[0]; +}; + +static LIST_HEAD(pools); +static spinlock_t pools_lock = SPINLOCK_INITIALIZER; + +mempool_t __export *mempool_create(int size) +{ + struct _mempool_t *p = _malloc(sizeof(*p)); + + memset(p, 0, sizeof(*p)); + INIT_LIST_HEAD(&p->items); +#ifdef MEMDEBUG + INIT_LIST_HEAD(&p->ditems); +#endif + spinlock_init(&p->lock); + p->size = size; + p->magic = (uint64_t)random() * (uint64_t)random(); + + spin_lock(&pools_lock); + list_add_tail(&p->entry, &pools); + spin_unlock(&pools_lock); + + return (mempool_t *)p; +} + +mempool_t __export *mempool_create2(int size) +{ + struct _mempool_t *p = (struct _mempool_t *)mempool_create(size); + + p->mmap = 1; + + return (mempool_t *)p; +} + +#ifndef MEMDEBUG +void __export *mempool_alloc(mempool_t *pool) +{ + struct _mempool_t *p = (struct _mempool_t *)pool; + struct _item_t *it; + uint32_t size = sizeof(*it) + p->size + 8; + + spin_lock(&p->lock); + if (!list_empty(&p->items)) { + it = list_entry(p->items.next, typeof(*it), entry); + list_del(&it->entry); + spin_unlock(&p->lock); + + __sync_sub_and_fetch(&triton_stat.mempool_available, size); + + it->magic1 = MAGIC1; + + return it->ptr; + } + spin_unlock(&p->lock); + + if (p->mmap) + it = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_32BIT, -1, 0); + else + it = _malloc(size); + + if (!it) { + triton_log_error("mempool: out of memory\n"); + return NULL; + } + it->owner = p; + it->magic1 = MAGIC1; + it->magic2 = p->magic; + *(uint64_t*)(it->data + p->size) = it->magic2; + + __sync_add_and_fetch(&triton_stat.mempool_allocated, size); + + return it->ptr; +} +#endif + +void __export *mempool_alloc_md(mempool_t *pool, const char *fname, int line) +{ + struct _mempool_t *p = (struct _mempool_t *)pool; + struct _item_t *it; + uint32_t size = sizeof(*it) + p->size + 8; + int i, n; + + spin_lock(&p->lock); + if (!list_empty(&p->items)) { + it = list_entry(p->items.next, typeof(*it), entry); +#ifdef VALGRIND + if (it->timestamp + DELAY < time(NULL)) { + VALGRIND_MAKE_MEM_DEFINED(&it->owner, size - sizeof(it->entry) - sizeof(it->timestamp)); + VALGRIND_MAKE_MEM_UNDEFINED(it->ptr, p->size); +#endif + list_del(&it->entry); + list_add(&it->entry, &p->ditems); + spin_unlock(&p->lock); + + it->fname = fname; + it->line = line; + + __sync_sub_and_fetch(&triton_stat.mempool_available, size); + + it->magic1 = MAGIC1; + + return it->ptr; +#ifdef VALGRIND + } +#endif + } + spin_unlock(&p->lock); + + if (p->mmap) { + n = (sysconf(_SC_PAGE_SIZE) - 1) / size + 1; + it = mmap(NULL, n * size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_32BIT, -1, 0); + __sync_add_and_fetch(&triton_stat.mempool_allocated, size * (n - 1)); + __sync_add_and_fetch(&triton_stat.mempool_available, size * (n - 1)); + spin_lock(&p->lock); + for (i = 0; i < n - 1; i++, it) { + it->owner = p; + it->magic2 = p->magic; + it->magic1 = MAGIC1; + *(uint64_t*)(it->ptr + p->size) = it->magic2; + list_add_tail(&it->entry,&p->items); +#ifdef VALGRIND + it->timestamp = 0; + VALGRIND_MAKE_MEM_NOACCESS(&it->owner, size - sizeof(it->entry) - sizeof(it->timestamp)); +#endif + it = (struct _item_t *)((char *)it + size); + } + spin_unlock(&p->lock); +#ifdef VALGRIND + VALGRIND_MAKE_MEM_UNDEFINED(it, size); +#endif + } else + it = md_malloc(size, fname, line); + + if (!it) { + triton_log_error("mempool: out of memory\n"); + return NULL; + } + it->owner = p; + it->magic2 = p->magic; + it->magic1 = MAGIC1; + it->fname = fname; + it->line = line; + *(uint64_t*)(it->ptr + p->size) = it->magic2; + + spin_lock(&p->lock); + list_add(&it->entry, &p->ditems); + spin_unlock(&p->lock); + + __sync_add_and_fetch(&triton_stat.mempool_allocated, size); + + return it->ptr; +} + + +void __export mempool_free(void *ptr) +{ + struct _item_t *it = container_of(ptr, typeof(*it), ptr); + struct _mempool_t *p = it->owner; + uint32_t size = sizeof(*it) + it->owner->size + 8; + +#ifdef MEMDEBUG + if (it->magic1 != MAGIC1) { + triton_log_error("mempool: memory corruption detected"); + abort(); + } + + if (it->magic2 != it->owner->magic) { + triton_log_error("mempool: memory corruption detected"); + abort(); + } + + if (it->magic2 != *(uint64_t*)(it->ptr + it->owner->size)) { + triton_log_error("mempool: memory corruption detected"); + abort(); + } + + it->magic1 = 0; +#endif + + spin_lock(&p->lock); +#ifdef MEMDEBUG + list_del(&it->entry); +#endif +#ifndef MEMPOOL_DISABLE + list_add_tail(&it->entry,&it->owner->items); +#endif +#ifdef VALGRIND + time(&it->timestamp); + VALGRIND_MAKE_MEM_NOACCESS(&it->owner, size - sizeof(it->entry) - sizeof(it->timestamp)); +#endif + spin_unlock(&p->lock); + +#ifdef MEMPOOL_DISABLE + if (it->owner->mmap) + munmap(it, size); + else + _free(it); +#endif + + __sync_add_and_fetch(&triton_stat.mempool_available, size); +} + +void __export mempool_clean(mempool_t *pool) +{ + struct _mempool_t *p = (struct _mempool_t *)pool; + struct _item_t *it; + uint32_t size = sizeof(*it) + p->size + 8; + + spin_lock(&p->lock); + while (!list_empty(&p->items)) { + it = list_entry(p->items.next, typeof(*it), entry); +#ifdef VALGRIND + if (it->timestamp + DELAY < time(NULL)) { + VALGRIND_MAKE_MEM_DEFINED(&it->owner, size - sizeof(it->entry) - sizeof(it->timestamp)); +#endif + list_del(&it->entry); + if (p->mmap) + munmap(it, size); + else + _free(it); + __sync_sub_and_fetch(&triton_stat.mempool_allocated, size); + __sync_sub_and_fetch(&triton_stat.mempool_available, size); +#ifdef VALGRIND + } else + break; +#endif + } + spin_unlock(&p->lock); +} + +#ifdef MEMDEBUG +void __export mempool_show(mempool_t *pool) +{ + struct _mempool_t *p = (struct _mempool_t *)pool; + struct _item_t *it; + + spin_lock(&p->lock); + list_for_each_entry(it, &p->ditems, entry) + triton_log_error("%s:%i %p\n", it->fname, it->line, it->ptr); + spin_unlock(&p->lock); +} +#endif + +void sigclean(int num) +{ + struct _mempool_t *p; + struct _item_t *it; + uint32_t size; + + triton_log_error("mempool: clean\n"); + + spin_lock(&pools_lock); + list_for_each_entry(p, &pools, entry) { + if (p->mmap) + continue; + size = sizeof(*it) + p->size + 8; + spin_lock(&p->lock); + while (!list_empty(&p->items)) { + it = list_entry(p->items.next, typeof(*it), entry); +#ifdef VALGRIND + if (it->timestamp + DELAY < time(NULL)) { + VALGRIND_MAKE_MEM_DEFINED(&it->owner, size - sizeof(it->entry) - sizeof(it->timestamp)); +#endif + list_del(&it->entry); + _free(it); + __sync_sub_and_fetch(&triton_stat.mempool_allocated, size); + __sync_sub_and_fetch(&triton_stat.mempool_available, size); +#ifdef VALGRIND + } else + break; +#endif + } + spin_unlock(&p->lock); + } + spin_unlock(&pools_lock); +} + +static void __init init(void) +{ + sigset_t set; + sigfillset(&set); + + struct sigaction sa = { + .sa_handler = sigclean, + .sa_mask = set, + }; + + sigaction(35, &sa, NULL); +} + diff --git a/accel-pppd/triton/mempool.h b/accel-pppd/triton/mempool.h new file mode 100644 index 0000000..bdb3e71 --- /dev/null +++ b/accel-pppd/triton/mempool.h @@ -0,0 +1,26 @@ +#ifndef __TRITON_MEMPOOL_H +#define __TRITON_MEMPOOL_H + +#include + +struct mempool_stat_t +{ + uint32_t allocated; + uint32_t available; +}; + +typedef void * mempool_t; +mempool_t *mempool_create(int size); +mempool_t *mempool_create2(int size); +void mempool_free(void*); +struct mempool_stat_t mempool_get_stat(void); + +#ifdef MEMDEBUG +void *mempool_alloc_md(mempool_t*, const char *fname, int line); +#define mempool_alloc(pool) mempool_alloc_md(pool, __FILE__, __LINE__) +#else +void *mempool_alloc(mempool_t*); +#endif + +#endif + diff --git a/accel-pppd/triton/options.c b/accel-pppd/triton/options.c new file mode 100644 index 0000000..a5214e2 --- /dev/null +++ b/accel-pppd/triton/options.c @@ -0,0 +1,48 @@ +#include +#include + +#include "triton_p.h" +#include "conf_file.h" + +#include "memdebug.h" + +static struct conf_file_sect_t *sect=NULL; + +static const char* find_option(const char *name) +{ + struct option_t *opt; + + if (!sect) + { + sect=conf_file_get_section("options"); + if (!sect) return 0; + } + + list_for_each_entry(opt,§->items,entry) + { + if (strcmp(opt->name,name)==0) + return opt->val; + } + + return NULL; +} +int triton_get_int_option(const char *str) +{ + const char *val=find_option(str); + if (!val) return 0; + + return atoi(val); +} +const char* triton_get_str_option(const char *str) +{ + const char *val=find_option(str); + + return val; +} +double triton_get_double_option(const char *str) +{ + const char *val=find_option(str); + if (!val) return 0; + + return atof(val); +} diff --git a/accel-pppd/triton/spinlock.h b/accel-pppd/triton/spinlock.h new file mode 100644 index 0000000..bb8dcf4 --- /dev/null +++ b/accel-pppd/triton/spinlock.h @@ -0,0 +1,42 @@ +#ifndef __TRITON_SPINLOCK_H +#define __TRITON_SPINLOCK_H + +#if defined(FUTEX_SPINLOCK) + +/*#include +#include +#include +typedef volatile int __attribute__((aligned)) spinlock_t; +static inline void _spin_lock(spinlock_t *l) +{ + syscall(SYS_futex, l, FUTEX_WAIT, r, NULL, NULL, 0); +} +static inline void _spin_unlock(spinlock_t *l) +{ + syscall(SYS_futex, l, FUTEX_WAKE, 2, NULL, NULL, 0); +} +#define spin_lock(l) _spin_lock(l) +#define spin_unlock(l) _spin_unlock(l) +#define SPINLOCK_INITIALIZER 1 +#define spinlock_init(l) {*(l)=1;}*/ + +#elif defined(GCC_SPINLOCK) + +typedef volatile int __attribute__((aligned)) spinlock_t; +#define spin_lock(l) {while(__sync_lock_test_and_set(l,1));} +#define spin_unlock(l) __sync_lock_release(l) +#define SPINLOCK_INITIALIZER 0 +#define spinlock_init(l) {*(l)=0;} + +#else + +#include +typedef pthread_mutex_t spinlock_t; +#define spin_lock(l) pthread_mutex_lock(l) +#define spin_unlock(l) pthread_mutex_unlock(l) +#define SPINLOCK_INITIALIZER PTHREAD_MUTEX_INITIALIZER +#define spinlock_init(l) pthread_mutex_init(l,NULL) +#endif + +#endif + diff --git a/accel-pppd/triton/timer.c b/accel-pppd/triton/timer.c new file mode 100644 index 0000000..e419e93 --- /dev/null +++ b/accel-pppd/triton/timer.c @@ -0,0 +1,222 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_TIMERFD +#include +#else +#include "timerfd.h" +#endif + +#include "triton_p.h" + +#include "memdebug.h" + +extern int max_events; +static int epoll_fd; +static struct epoll_event *epoll_events; + +static pthread_t timer_thr; +static void *timer_thread(void *arg); + +static mempool_t *timer_pool; + +static pthread_mutex_t freed_list_lock = PTHREAD_MUTEX_INITIALIZER; +static LIST_HEAD(freed_list); +static LIST_HEAD(freed_list2); + +int timer_init(void) +{ + epoll_fd = epoll_create(1); + if (epoll_fd < 0) { + perror("timer:epoll_create"); + return -1; + } + + epoll_events = _malloc(max_events * sizeof(struct epoll_event)); + if (!epoll_events) { + fprintf(stderr,"timer:cann't allocate memory\n"); + return -1; + } + + timer_pool = mempool_create(sizeof(struct _triton_timer_t)); + + return 0; +} + +void timer_run(void) +{ + if (pthread_create(&timer_thr, NULL, timer_thread, NULL)) { + triton_log_error("timer:pthread_create: %s",strerror(errno)); + _exit(-1); + } +} + +void timer_terminate(void) +{ + pthread_cancel(timer_thr); + pthread_join(timer_thr, NULL); +} + +void *timer_thread(void *arg) +{ + int i,n,r; + struct _triton_timer_t *t; + sigset_t set; + + sigfillset(&set); + sigdelset(&set, SIGKILL); + sigdelset(&set, SIGSTOP); + pthread_sigmask(SIG_BLOCK, &set, NULL); + + while(1) { + n = epoll_wait(epoll_fd, epoll_events, max_events, -1); + if (n < 0) { + if (errno == EINTR) + continue; + triton_log_error("timer:epoll_wait: %s", strerror(errno)); + _exit(-1); + } + + for(i = 0; i < n; i++) { + t = (struct _triton_timer_t *)epoll_events[i].data.ptr; + if (!t->ud) + continue; + spin_lock(&t->ctx->lock); + if (t->ud) { + if (!t->pending) { + list_add_tail(&t->entry2, &t->ctx->pending_timers); + t->pending = 1; + __sync_add_and_fetch(&triton_stat.timer_pending, 1); + r = triton_queue_ctx(t->ctx); + } else + r = 0; + } else + r = 0; + spin_unlock(&t->ctx->lock); + if (r) + triton_thread_wakeup(t->ctx->thread); + } + + while (!list_empty(&freed_list2)) { + t = list_entry(freed_list2.next, typeof(*t), entry); + list_del(&t->entry); + mempool_free(t); + } + + pthread_mutex_lock(&freed_list_lock); + while (!list_empty(&freed_list)) { + t = list_entry(freed_list.next, typeof(*t), entry); + list_del(&t->entry); + list_add(&t->entry, &freed_list2); + } + pthread_mutex_unlock(&freed_list_lock); + } + + return NULL; +} + + +int __export triton_timer_add(struct triton_context_t *ctx, struct triton_timer_t *ud, int abs_time) +{ + struct _triton_timer_t *t = mempool_alloc(timer_pool); + + memset(t, 0, sizeof(*t)); + t->ud = ud; + t->epoll_event.data.ptr = t; + t->epoll_event.events = EPOLLIN | EPOLLET; + if (ctx) + t->ctx = (struct _triton_context_t *)ctx->tpd; + else + t->ctx = (struct _triton_context_t *)default_ctx.tpd; + t->fd = timerfd_create(abs_time ? CLOCK_REALTIME : CLOCK_MONOTONIC, 0); + if (t->fd < 0) { + triton_log_error("timer:timerfd_create: %s", strerror(errno)); + mempool_free(t); + return -1; + } + + if (fcntl(t->fd, F_SETFL, O_NONBLOCK)) { + triton_log_error("timer: failed to set nonblocking mode: %s\n", strerror(errno)); + goto out_err; + } + + ud->tpd = t; + + if (triton_timer_mod(ud, abs_time)) + goto out_err; + + spin_lock(&t->ctx->lock); + list_add_tail(&t->entry, &t->ctx->timers); + spin_unlock(&t->ctx->lock); + + if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, t->fd, &t->epoll_event)) { + triton_log_error("timer:epoll_ctl: %s", strerror(errno)); + spin_lock(&t->ctx->lock); + t->ud = NULL; + list_del(&t->entry); + spin_unlock(&t->ctx->lock); + goto out_err; + } + + triton_stat.timer_count++; + + return 0; + +out_err: + ud->tpd = NULL; + close(t->fd); + mempool_free(t); + return -1; +} +int __export triton_timer_mod(struct triton_timer_t *ud,int abs_time) +{ + struct _triton_timer_t *t = (struct _triton_timer_t *)ud->tpd; + struct itimerspec ts = { + .it_value.tv_sec = ud->expire_tv.tv_sec, + .it_value.tv_nsec = ud->expire_tv.tv_usec * 1000, + .it_interval.tv_sec = ud->period / 1000, + .it_interval.tv_nsec = (ud->period % 1000) * 1000, + }; + + if (ud->expire_tv.tv_sec == 0 && ud->expire_tv.tv_usec == 0) + ts.it_value = ts.it_interval; + + if (timerfd_settime(t->fd, abs_time ? TFD_TIMER_ABSTIME : 0, &ts, NULL)) { + triton_log_error("timer:timerfd_settime: %s", strerror(errno)); + return -1; + } + + return 0; +} +void __export triton_timer_del(struct triton_timer_t *ud) +{ + struct _triton_timer_t *t = (struct _triton_timer_t *)ud->tpd; + epoll_ctl(epoll_fd, EPOLL_CTL_DEL, t->fd, &t->epoll_event); + close(t->fd); + spin_lock(&t->ctx->lock); + t->ud = NULL; + list_del(&t->entry); + if (t->pending) { + list_del(&t->entry2); + __sync_sub_and_fetch(&triton_stat.timer_pending, 1); + } + spin_unlock(&t->ctx->lock); + + sched_yield(); + + pthread_mutex_lock(&freed_list_lock); + list_add_tail(&t->entry, &freed_list); + pthread_mutex_unlock(&freed_list_lock); + + ud->tpd = NULL; + + triton_stat.timer_count--; +} + diff --git a/accel-pppd/triton/timerfd.c b/accel-pppd/triton/timerfd.c new file mode 100644 index 0000000..b026258 --- /dev/null +++ b/accel-pppd/triton/timerfd.c @@ -0,0 +1,19 @@ +#include +#include +#include + +#include "timerfd.h" + +int timerfd_create (clockid_t __clock_id, int __flags) +{ + return syscall(SYS_timerfd_create, __clock_id, __flags); +} + + +int timerfd_settime (int __ufd, int __flags, + __const struct itimerspec *__utmr, + struct itimerspec *__otmr) +{ + return syscall(SYS_timerfd_settime, __ufd, __flags, __utmr, __otmr); +} + diff --git a/accel-pppd/triton/timerfd.h b/accel-pppd/triton/timerfd.h new file mode 100644 index 0000000..c1bb06f --- /dev/null +++ b/accel-pppd/triton/timerfd.h @@ -0,0 +1,60 @@ +/* Copyright (C) 2008 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#ifndef _SYS_TIMERFD_H +#define _SYS_TIMERFD_H 1 + +#include + + +/* Bits to be set in the FLAGS parameter of `timerfd_create'. */ +enum + { + TFD_CLOEXEC = 02000000, +#define TFD_CLOEXEC TFD_CLOEXEC + TFD_NONBLOCK = 04000 +#define TFD_NONBLOCK TFD_NONBLOCK + }; + + +/* Bits to be set in the FLAGS parameter of `timerfd_settime'. */ +enum + { + TFD_TIMER_ABSTIME = 1 << 0 +#define TFD_TIMER_ABSTIME TFD_TIMER_ABSTIME + }; + + +__BEGIN_DECLS + +/* Return file descriptor for new interval timer source. */ +extern int timerfd_create (clockid_t __clock_id, int __flags) __THROW; + +/* Set next expiration time of interval timer source UFD to UTMR. If + FLAGS has the TFD_TIMER_ABSTIME flag set the timeout value is + absolute. Optionally return the old expiration time in OTMR. */ +extern int timerfd_settime (int __ufd, int __flags, + __const struct itimerspec *__utmr, + struct itimerspec *__otmr) __THROW; + +/* Return the next expiration time of UFD. */ +extern int timerfd_gettime (int __ufd, struct itimerspec *__otmr) __THROW; + +__END_DECLS + +#endif /* sys/timerfd.h */ diff --git a/accel-pppd/triton/triton.c b/accel-pppd/triton/triton.c new file mode 100644 index 0000000..00dfcf6 --- /dev/null +++ b/accel-pppd/triton/triton.c @@ -0,0 +1,610 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "triton_p.h" +#include "memdebug.h" + +int thread_count = 2; +int max_events = 64; + +static spinlock_t threads_lock = SPINLOCK_INITIALIZER; +static LIST_HEAD(threads); +static LIST_HEAD(sleep_threads); + +static LIST_HEAD(ctx_queue); + +static spinlock_t ctx_list_lock = SPINLOCK_INITIALIZER; +static LIST_HEAD(ctx_list); + +static int terminate; +static int need_terminate; + +static int need_config_reload; +static void (*config_reload_notify)(int); + +static mempool_t *ctx_pool; +static mempool_t *call_pool; + +struct triton_stat_t __export triton_stat; + +static struct timeval ru_utime; +static struct timeval ru_stime; +static struct timespec ru_timestamp; +static int ru_refs; +static void ru_update(struct triton_timer_t *); +static struct triton_timer_t ru_timer = { + .period = 1000, + .expire = ru_update, +}; +struct triton_context_t default_ctx; + +static struct triton_context_t __thread *this_ctx; + +#define log_debug2(fmt, ...) + +void triton_thread_wakeup(struct _triton_thread_t *thread) +{ + log_debug2("wake up thread %p\n", thread); + pthread_kill(thread->thread, SIGUSR1); +} + +static void __config_reload(void (*notify)(int)) +{ + struct _triton_thread_t *t; + int r; + + log_debug2("config_reload: enter\n"); + r = conf_reload(NULL); + notify(r); + + spin_lock(&threads_lock); + need_config_reload = 0; + list_for_each_entry(t, &threads, entry) + triton_thread_wakeup(t); + spin_unlock(&threads_lock); + log_debug2("config_reload: exit\n"); +} + +static void ctx_thread(struct _triton_context_t *ctx); +static void* triton_thread(struct _triton_thread_t *thread) +{ + sigset_t set; + int sig; + + sigfillset(&set); + sigdelset(&set, SIGKILL); + sigdelset(&set, SIGSTOP); + pthread_sigmask(SIG_BLOCK, &set, NULL); + + sigemptyset(&set); + sigaddset(&set, SIGUSR1); + sigaddset(&set, SIGQUIT); + + pthread_mutex_lock(&thread->sleep_lock); + pthread_mutex_unlock(&thread->sleep_lock); + + while (1) { + spin_lock(&threads_lock); + if (!list_empty(&ctx_queue) && !need_config_reload) { + thread->ctx = list_entry(ctx_queue.next, typeof(*thread->ctx), entry2); + log_debug2("thread: %p: dequeued ctx %p\n", thread, thread->ctx); + list_del(&thread->ctx->entry2); + spin_unlock(&threads_lock); + spin_lock(&thread->ctx->lock); + thread->ctx->thread = thread; + thread->ctx->queued = 0; + spin_unlock(&thread->ctx->lock); + __sync_sub_and_fetch(&triton_stat.context_pending, 1); + } else { + if (triton_stat.thread_count > thread_count + triton_stat.context_sleeping) { + __sync_sub_and_fetch(&triton_stat.thread_active, 1); + __sync_sub_and_fetch(&triton_stat.thread_count, 1); + list_del(&thread->entry); + spin_unlock(&threads_lock); + pthread_detach(pthread_self()); + log_debug2("thread: %p: exit\n", thread); + _free(thread); + return NULL; + } + log_debug2("thread: %p: sleeping\n", thread); + if (!terminate) + list_add(&thread->entry2, &sleep_threads); + + if (__sync_sub_and_fetch(&triton_stat.thread_active, 1) == 0 && need_config_reload) { + spin_unlock(&threads_lock); + __config_reload(config_reload_notify); + } else + spin_unlock(&threads_lock); + + if (terminate) + return NULL; + + //printf("thread %p: enter sigwait\n", thread); + sigwait(&set, &sig); + //printf("thread %p: exit sigwait\n", thread); + + spin_lock(&threads_lock); + __sync_add_and_fetch(&triton_stat.thread_active, 1); + if (!thread->ctx) { + list_del(&thread->entry2); + spin_unlock(&threads_lock); + continue; + } + spin_unlock(&threads_lock); + } + +cont: + log_debug2("thread %p: ctx=%p %p\n", thread, thread->ctx, thread->ctx ? thread->ctx->thread : NULL); + this_ctx = thread->ctx->ud; + if (thread->ctx->ud->before_switch) + thread->ctx->ud->before_switch(thread->ctx->ud, thread->ctx->bf_arg); + + log_debug2("thread %p: switch to %p\n", thread, thread->ctx); + ctx_thread(thread->ctx); + log_debug2("thread %p: switch from %p %p\n", thread, thread->ctx, thread->ctx->thread); + + spin_lock(&thread->ctx->lock); + if (thread->ctx->pending) { + spin_unlock(&thread->ctx->lock); + goto cont; + } + thread->ctx->thread = NULL; + spin_unlock(&thread->ctx->lock); + + if (thread->ctx->need_free) { + log_debug2("- context %p removed\n", thread->ctx); + mempool_free(thread->ctx); + } + + thread->ctx = NULL; + } +} + +static void ctx_thread(struct _triton_context_t *ctx) +{ + struct _triton_md_handler_t *h; + struct _triton_timer_t *t; + struct _triton_ctx_call_t *call; + uint64_t tt; + + log_debug2("ctx %p %p: enter\n", ctx, ctx->thread); + if (ctx->need_close) { + if (ctx->ud->close) + ctx->ud->close(ctx->ud); + ctx->need_close = 0; + } + + while (1) { + spin_lock(&ctx->lock); + if (!list_empty(&ctx->pending_timers)) { + t = list_entry(ctx->pending_timers.next, typeof(*t), entry2); + list_del(&t->entry2); + t->pending = 0; + spin_unlock(&ctx->lock); + __sync_sub_and_fetch(&triton_stat.timer_pending, 1); + read(t->fd, &tt, sizeof(tt)); + t->ud->expire(t->ud); + continue; + } + if (!list_empty(&ctx->pending_handlers)) { + h = list_entry(ctx->pending_handlers.next, typeof(*h), entry2); + list_del(&h->entry2); + h->pending = 0; + spin_unlock(&ctx->lock); + __sync_sub_and_fetch(&triton_stat.md_handler_pending, 1); + if (h->trig_epoll_events & (EPOLLIN | EPOLLERR | EPOLLHUP)) + if (h->ud && h->ud->read) + if (h->ud->read(h->ud)) + continue; + if (h->trig_epoll_events & (EPOLLOUT | EPOLLERR | EPOLLHUP)) + if (h->ud && h->ud->write) + if (h->ud->write(h->ud)) + continue; + h->trig_epoll_events = 0; + continue; + } + if (!list_empty(&ctx->pending_calls)) { + call = list_entry(ctx->pending_calls.next, typeof(*call), entry); + list_del(&call->entry); + spin_unlock(&ctx->lock); + call->func(call->arg); + mempool_free(call); + continue; + } + ctx->pending = 0; + spin_unlock(&ctx->lock); + break; + } + + log_debug2("ctx %p %p: exit\n", ctx, ctx->thread); +} + +struct _triton_thread_t *create_thread() +{ + struct _triton_thread_t *thread = _malloc(sizeof(*thread)); + if (!thread) + return NULL; + + memset(thread, 0, sizeof(*thread)); + pthread_mutex_init(&thread->sleep_lock, NULL); + pthread_cond_init(&thread->sleep_cond, NULL); + pthread_mutex_lock(&thread->sleep_lock); + if (pthread_create(&thread->thread, NULL, (void*(*)(void*))triton_thread, thread)) { + triton_log_error("pthread_create: %s", strerror(errno)); + return NULL; + } + + __sync_add_and_fetch(&triton_stat.thread_count, 1); + __sync_add_and_fetch(&triton_stat.thread_active, 1); + + return thread; +} + +int triton_queue_ctx(struct _triton_context_t *ctx) +{ + ctx->pending = 1; + if (ctx->thread || ctx->queued || ctx->init) + return 0; + + spin_lock(&threads_lock); + if (list_empty(&sleep_threads) || need_config_reload) { + if (ctx->priority) + list_add(&ctx->entry2, &ctx_queue); + else + list_add_tail(&ctx->entry2, &ctx_queue); + spin_unlock(&threads_lock); + ctx->queued = 1; + log_debug2("ctx %p: queued\n", ctx); + __sync_add_and_fetch(&triton_stat.context_pending, 1); + return 0; + } + + ctx->thread = list_entry(sleep_threads.next, typeof(*ctx->thread), entry2); + ctx->thread->ctx = ctx; + log_debug2("ctx %p: assigned to thread %p\n", ctx, ctx->thread); + list_del(&ctx->thread->entry2); + spin_unlock(&threads_lock); + + return 1; +} + +int __export triton_context_register(struct triton_context_t *ud, void *bf_arg) +{ + struct _triton_context_t *ctx = mempool_alloc(ctx_pool); + + log_debug2("ctx %p: register\n", ctx); + if (!ctx) + return -1; + + memset(ctx, 0, sizeof(*ctx)); + ctx->ud = ud; + ctx->bf_arg = bf_arg; + ctx->init = 1; + spinlock_init(&ctx->lock); + INIT_LIST_HEAD(&ctx->handlers); + INIT_LIST_HEAD(&ctx->timers); + INIT_LIST_HEAD(&ctx->pending_handlers); + INIT_LIST_HEAD(&ctx->pending_timers); + INIT_LIST_HEAD(&ctx->pending_calls); + + ud->tpd = ctx; + + spin_lock(&ctx_list_lock); + list_add_tail(&ctx->entry, &ctx_list); + spin_unlock(&ctx_list_lock); + + __sync_add_and_fetch(&triton_stat.context_sleeping, 1); + __sync_add_and_fetch(&triton_stat.context_count, 1); + + return 0; +} + +void __export triton_context_unregister(struct triton_context_t *ud) +{ + struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; + struct _triton_ctx_call_t *call; + struct _triton_thread_t *t; + + log_debug2("ctx %p: unregister\n", ctx); + + while (!list_empty(&ctx->pending_calls)) { + call = list_entry(ctx->pending_calls.next, typeof(*call), entry); + list_del(&call->entry); + mempool_free(call); + } + + if (!list_empty(&ctx->handlers)) { + triton_log_error("BUG:ctx:triton_unregister_ctx: handlers is not empty"); + { + struct _triton_md_handler_t *h; + list_for_each_entry(h, &ctx->handlers, entry) + if (h->ud) + printf("%p\n", h->ud); + } + abort(); + } + if (!list_empty(&ctx->pending_handlers)) { + triton_log_error("BUG:ctx:triton_unregister_ctx: pending_handlers is not empty"); + abort(); + } + if (!list_empty(&ctx->timers)) { + triton_log_error("BUG:ctx:triton_unregister_ctx: timers is not empty"); + abort(); + } + if (!list_empty(&ctx->pending_timers)) { + triton_log_error("BUG:ctx:triton_unregister_ctx: pending_timers is not empty"); + abort(); + } + + ctx->need_free = 1; + spin_lock(&ctx_list_lock); + list_del(&ctx->entry); + if (__sync_sub_and_fetch(&triton_stat.context_count, 1) == 1) { + if (need_terminate) + terminate = 1; + } + spin_unlock(&ctx_list_lock); + + if (terminate) { + list_for_each_entry(t, &threads, entry) + triton_thread_wakeup(t); + } +} + +void __export triton_context_set_priority(struct triton_context_t *ud, int prio) +{ + struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; + + ctx->priority = prio > 0; +} + +void __export triton_context_schedule() +{ + struct _triton_context_t *ctx = (struct _triton_context_t *)this_ctx->tpd; + struct _triton_thread_t *t = NULL; + + log_debug2("ctx %p: enter schedule\n", ctx); + __sync_add_and_fetch(&triton_stat.context_sleeping, 1); + __sync_sub_and_fetch(&triton_stat.thread_active, 1); + pthread_mutex_lock(&ctx->thread->sleep_lock); + while (1) { + if (ctx->wakeup) { + ctx->wakeup = 0; + break; + } else { + if (!t && triton_stat.thread_count <= thread_count + triton_stat.context_sleeping) { + t = create_thread(); + spin_lock(&threads_lock); + list_add_tail(&t->entry, &threads); + spin_unlock(&threads_lock); + pthread_mutex_unlock(&t->sleep_lock); + } + pthread_cond_wait(&ctx->thread->sleep_cond, &ctx->thread->sleep_lock); + } + } + pthread_mutex_unlock(&ctx->thread->sleep_lock); + __sync_sub_and_fetch(&triton_stat.context_sleeping, 1); + __sync_add_and_fetch(&triton_stat.thread_active, 1); + log_debug2("ctx %p: exit schedule\n", ctx); +} + +struct triton_context_t __export *triton_context_self(void) +{ + return this_ctx; +} + +void triton_context_print(void) +{ + struct _triton_context_t *ctx; + + list_for_each_entry(ctx, &ctx_list, entry) + printf("%p\n", ctx); +} + +void __export triton_context_wakeup(struct triton_context_t *ud) +{ + struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; + int r = 0; + + log_debug2("ctx %p: wakeup\n", ctx); + + if (ctx->init) { + __sync_sub_and_fetch(&triton_stat.context_sleeping, 1); + spin_lock(&ctx->lock); + ctx->init = 0; + if (ctx->pending) + r = triton_queue_ctx(ctx); + spin_unlock(&ctx->lock); + if (r) + triton_thread_wakeup(ctx->thread); + return; + } + + pthread_mutex_lock(&ctx->thread->sleep_lock); + ctx->wakeup = 1; + pthread_cond_signal(&ctx->thread->sleep_cond); + pthread_mutex_unlock(&ctx->thread->sleep_lock); +} + +int __export triton_context_call(struct triton_context_t *ud, void (*func)(void *), void *arg) +{ + struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; + struct _triton_ctx_call_t *call = mempool_alloc(call_pool); + int r; + + if (!call) + return -1; + + call->func = func; + call->arg = arg; + + spin_lock(&ctx->lock); + list_add_tail(&call->entry, &ctx->pending_calls); + r = triton_queue_ctx(ctx); + spin_unlock(&ctx->lock); + + if (r) + triton_thread_wakeup(ctx->thread); + + return 0; +} + +void __export triton_cancel_call(struct triton_context_t *ud, void (*func)(void *)) +{ + struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; + struct list_head *pos, *n; + struct _triton_ctx_call_t *call; + + list_for_each_safe(pos, n, &ctx->pending_calls) { + call = list_entry(pos, typeof(*call), entry); + if (call->func != func) + continue; + list_del(&call->entry); + mempool_free(call); + } +} + +void __export triton_collect_cpu_usage(void) +{ + struct rusage rusage; + + if (__sync_fetch_and_add(&ru_refs, 1) == 0) { + triton_timer_add(NULL, &ru_timer, 0); + getrusage(RUSAGE_SELF, &rusage); + clock_gettime(CLOCK_MONOTONIC, &ru_timestamp); + ru_utime = rusage.ru_utime; + ru_stime = rusage.ru_stime; + triton_stat.cpu = 0; + } +} + +void __export triton_stop_collect_cpu_usage(void) +{ + if (__sync_sub_and_fetch(&ru_refs, 1) == 0) + triton_timer_del(&ru_timer); +} + +static void ru_update(struct triton_timer_t *t) +{ + struct timespec ts; + struct rusage rusage; + unsigned int dt; + unsigned int val; + + getrusage(RUSAGE_SELF, &rusage); + clock_gettime(CLOCK_MONOTONIC, &ts); + + dt = (ts.tv_sec - ru_timestamp.tv_sec) * 1000000 + (ts.tv_nsec - ru_timestamp.tv_nsec) / 1000000; + val = (double)((rusage.ru_utime.tv_sec - ru_utime.tv_sec) * 1000000 + (rusage.ru_utime.tv_usec - ru_utime.tv_usec) + + (rusage.ru_stime.tv_sec - ru_stime.tv_sec) * 1000000 + (rusage.ru_stime.tv_usec - ru_stime.tv_usec)) / dt * 100; + + if (val <= 100) + triton_stat.cpu = val; + + ru_timestamp = ts; + ru_utime = rusage.ru_utime; + ru_stime = rusage.ru_stime; +} + +int __export triton_init(const char *conf_file) +{ + ctx_pool = mempool_create2(sizeof(struct _triton_context_t)); + call_pool = mempool_create(sizeof(struct _triton_ctx_call_t)); + + if (conf_load(conf_file)) + return -1; + + if (log_init()) + return -1; + + if (md_init()) + return -1; + + if (timer_init()) + return -1; + + if (event_init()) + return -1; + + return 0; +} + +int __export triton_load_modules(const char *mod_sect) +{ + if (load_modules(mod_sect)) + return -1; + + return 0; +} + +void __export triton_conf_reload(void (*notify)(int)) +{ + spin_lock(&threads_lock); + need_config_reload = 1; + config_reload_notify = notify; + if (triton_stat.thread_active == 0) { + spin_unlock(&threads_lock); + __config_reload(notify); + } else + spin_unlock(&threads_lock); +} + +void __export triton_run() +{ + struct _triton_thread_t *t; + int i; + char *opt; + + opt = conf_get_opt("core", "thread-count"); + if (opt && atoi(opt) > 0) + thread_count = atoi(opt); + + for(i = 0; i < thread_count; i++) { + t = create_thread(); + if (!t) + _exit(-1); + + list_add_tail(&t->entry, &threads); + pthread_mutex_unlock(&t->sleep_lock); + } + + time(&triton_stat.start_time); + + md_run(); + timer_run(); + + triton_context_register(&default_ctx, NULL); + triton_context_wakeup(&default_ctx); +} + +void __export triton_terminate() +{ + struct _triton_context_t *ctx; + struct _triton_thread_t *t; + int r; + + need_terminate = 1; + + spin_lock(&ctx_list_lock); + list_for_each_entry(ctx, &ctx_list, entry) { + spin_lock(&ctx->lock); + ctx->need_close = 1; + r = triton_queue_ctx(ctx); + if (r) + triton_thread_wakeup(ctx->thread); + spin_unlock(&ctx->lock); + } + spin_unlock(&ctx_list_lock); + + list_for_each_entry(t, &threads, entry) + pthread_join(t->thread, NULL); + + md_terminate(); + timer_terminate(); +} + diff --git a/accel-pppd/triton/triton.h b/accel-pppd/triton/triton.h new file mode 100644 index 0000000..6866d52 --- /dev/null +++ b/accel-pppd/triton/triton.h @@ -0,0 +1,138 @@ +#ifndef TRITON_H +#define TRITON_H + +#include +#include + +#include "list.h" + +struct triton_context_t +{ + const void *tpd; // triton private data, don't touch + void (*close)(struct triton_context_t*); + void (*free)(struct triton_context_t*); + void (*before_switch)(struct triton_context_t *ctx, void *arg); +}; + +struct triton_md_handler_t +{ + const void *tpd; // triton private data, don't touch! + int fd; + int (*read)(struct triton_md_handler_t *); + int (*write)(struct triton_md_handler_t *); +}; + +struct triton_timer_t +{ + const void *tpd; // triton private data, don't touch! + struct timeval expire_tv; + int period; + void (*expire)(struct triton_timer_t *); +}; + +struct triton_sigchld_handler_t +{ + void *tpd; + int pid; + void (*handler)(struct triton_sigchld_handler_t *h, int status); +}; + +struct conf_option_t +{ + struct list_head entry; + char *name; + char *val; +}; + +struct conf_sect_t +{ + const char *name; + struct list_head items; +}; + +struct triton_stat_t +{ + unsigned int mempool_allocated; + unsigned int mempool_available; + unsigned int thread_count; + unsigned int thread_active; + unsigned int context_count; + unsigned int context_sleeping; + unsigned int context_pending; + unsigned int md_handler_count; + unsigned int md_handler_pending; + unsigned int timer_count; + unsigned int timer_pending; + time_t start_time; + unsigned int cpu; +}; + +extern struct triton_stat_t triton_stat; +int triton_context_register(struct triton_context_t *, void *arg); +void triton_context_unregister(struct triton_context_t *); +void triton_context_set_priority(struct triton_context_t *, int); +void triton_context_schedule(void); +void triton_context_wakeup(struct triton_context_t *); +int triton_context_call(struct triton_context_t *, void (*func)(void *), void *arg); +void triton_cancel_call(struct triton_context_t *, void (*func)(void *)); +struct triton_context_t *triton_context_self(void); + +#define MD_MODE_READ 1 +#define MD_MODE_WRITE 2 + +#define MD_TRIG_EDGE 0 +#define MD_TRIG_LEVEL 1 + +void triton_md_register_handler(struct triton_context_t *, struct triton_md_handler_t *); +void triton_md_unregister_handler(struct triton_md_handler_t *h); +int triton_md_enable_handler(struct triton_md_handler_t *h, int mode); +int triton_md_disable_handler(struct triton_md_handler_t *h,int mode); +void triton_md_set_trig(struct triton_md_handler_t *h, int mode); + +int triton_timer_add(struct triton_context_t *ctx, struct triton_timer_t*,int abs_time); +int triton_timer_mod(struct triton_timer_t *,int abs_time); +void triton_timer_del(struct triton_timer_t *); + +typedef void (*triton_event_func)(void *); +int triton_event_register_handler(int ev_id, triton_event_func func); +void triton_event_fire(int ev_id, void *arg); + +struct conf_sect_t *conf_get_section(const char *name); +char *conf_get_opt(const char *sect, const char *name); +void triton_conf_reload(void (*notify)(int)); + +void triton_collect_cpu_usage(void); +void triton_stop_collect_cpu_usage(void); + + +#define TRITON_OK 0 +#define TRITON_ERR_NOCOMP -1 +#define TRITON_ERR_NOSUPP -2 +#define TRITON_ERR_NOINTF -3 +#define TRITON_ERR_EXISTS -4 +#define TRITON_ERR_NOCHAN -5 +#define TRITON_ERR_NOMSG -6 +#define TRITON_ERR_BUSY -5 + +int triton_init(const char *conf_file); +int triton_load_modules(const char *md_sect); +void triton_run(void); +void triton_terminate(void); + + +#define __init __attribute__((constructor)) +#define __exit __attribute__((destructor)) +#define __export __attribute__((visibility("default"))) + +#undef offsetof +#ifdef __compiler_offsetof +#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER) +#else +#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) +#endif + +#define container_of(ptr, type, member) ({ \ + const typeof( ((type *)0)->member ) *__mptr = (ptr); \ + (type *)( (char *)__mptr - offsetof(type,member) );}) + +#endif diff --git a/accel-pppd/triton/triton_p.h b/accel-pppd/triton/triton_p.h new file mode 100644 index 0000000..235eb70 --- /dev/null +++ b/accel-pppd/triton/triton_p.h @@ -0,0 +1,103 @@ +#ifndef TRITON_P_H +#define TRITON_P_H + +#include +#include + +#include "triton.h" +#include "list.h" +#include "spinlock.h" +#include "mempool.h" + +struct _triton_thread_t +{ + struct list_head entry; + struct list_head entry2; + pthread_t thread; + int terminate; + struct _triton_context_t *ctx; + pthread_mutex_t sleep_lock; + pthread_cond_t sleep_cond; +}; + +struct _triton_context_t +{ + struct list_head entry; + struct list_head entry2; + + spinlock_t lock; + struct _triton_thread_t *thread; + + struct list_head handlers; + struct list_head timers; + struct list_head pending_handlers; + struct list_head pending_timers; + struct list_head pending_calls; + + int init; + int queued; + int wakeup; + int need_close; + int need_free; + int pending; + int priority; + + struct triton_context_t *ud; + void *bf_arg; +}; + +struct _triton_md_handler_t +{ + struct list_head entry; + struct list_head entry2; + struct _triton_context_t *ctx; + struct epoll_event epoll_event; + uint32_t trig_epoll_events; + int pending:1; + int trig_level:1; + struct triton_md_handler_t *ud; +}; + +struct _triton_timer_t +{ + struct list_head entry; + struct list_head entry2; + struct epoll_event epoll_event; + struct _triton_context_t *ctx; + int fd; + int pending:1; + struct triton_timer_t *ud; +}; + +struct _triton_event_t +{ + struct list_head handlers; +}; + +struct _triton_ctx_call_t +{ + struct list_head entry; + + void *arg; + void (*func)(void *); +}; + +int log_init(void); +int md_init(); +int timer_init(); +int event_init(); + +void md_run(); +void md_terminate(); +void timer_run(); +void timer_terminate(); +extern struct triton_context_t default_ctx; +int triton_queue_ctx(struct _triton_context_t*); +void triton_thread_wakeup(struct _triton_thread_t*); +int conf_load(const char *fname); +int conf_reload(const char *fname); +void triton_log_error(const char *fmt,...); +void triton_log_debug(const char *fmt,...); +int load_modules(const char *name); + +#endif diff --git a/accel-pppd/utils.c b/accel-pppd/utils.c new file mode 100644 index 0000000..491e650 --- /dev/null +++ b/accel-pppd/utils.c @@ -0,0 +1,11 @@ +#include + +#include "triton.h" +#include "utils.h" + +#include "memdebug.h" + +void __export u_inet_ntoa(in_addr_t addr, char *str) +{ + sprintf(str, "%i.%i.%i.%i", addr & 0xff, (addr >> 8) & 0xff, (addr >> 16) & 0xff, (addr >> 24) & 0xff); +} diff --git a/accel-pppd/utils.h b/accel-pppd/utils.h new file mode 100644 index 0000000..27d4d05 --- /dev/null +++ b/accel-pppd/utils.h @@ -0,0 +1,8 @@ +#ifndef __UTILS_H +#define __UTILS_H + +#include + +void u_inet_ntoa(in_addr_t, char *str); + +#endif diff --git a/accel-pptpd/CMakeLists.txt b/accel-pptpd/CMakeLists.txt deleted file mode 100644 index e0a8dd4..0000000 --- a/accel-pptpd/CMakeLists.txt +++ /dev/null @@ -1,102 +0,0 @@ -INCLUDE(CheckLibraryExists) -INCLUDE(CheckIncludeFiles) - -CHECK_LIBRARY_EXISTS(crypto MD5_Init "" HAVE_SSL) -IF (NOT HAVE_SSL) - MESSAGE(FATAL_ERROR "openssl library not found") -ENDIF (NOT HAVE_SSL) - -SET(CMAKE_REQUIRED_INCLUDES "openssl") -CHECK_INCLUDE_FILES("md5.h" HAVE_SSL) -IF (NOT HAVE_SSL) - MESSAGE(FATAL_ERROR "openssl headers not found") -ENDIF (NOT HAVE_SSL) - -SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -fvisibility=hidden -fno-strict-aliasing -D_GNU_SOURCE -DPTHREAD_SPINLOCK -DMEMDEBUG -fPIC") - -IF (EXISTS ${CMAKE_HOME_DIRECTORY}/.git) - EXECUTE_PROCESS( - COMMAND git log - COMMAND head -n1 - COMMAND awk "{print $2}" - WORKING_DIRECTORY ${CMAKE_HOME_DIRECTORY} - OUTPUT_VARIABLE ACCEL_PPTP_VERSION - ) - STRING(STRIP ${ACCEL_PPTP_VERSION} ACCEL_PPTP_VERSION) -ELSE (EXISTS ${CMAKE_HOME_DIRECTORY}/.git) - SET (ACCEL_PPTP_VERSION 1.3.2) -ENDIF (EXISTS ${CMAKE_HOME_DIRECTORY}/.git) - -ADD_DEFINITIONS(-DACCEL_PPTP_VERSION="${ACCEL_PPTP_VERSION}") - -INCLUDE_DIRECTORIES(include) - -IF (NOT DEFINED RADIUS) - SET(RADIUS TRUE) -ENDIF (NOT DEFINED RADIUS) - -IF (RADIUS) - ADD_DEFINITIONS(-DRADIUS) - ADD_SUBDIRECTORY(radius) -ENDIF (RADIUS) - -IF (VALGRIND) - ADD_DEFINITIONS(-DVALGRIND) -ENDIF (VALGRIND) - -ADD_SUBDIRECTORY(triton) -ADD_SUBDIRECTORY(ctrl) -ADD_SUBDIRECTORY(auth) -ADD_SUBDIRECTORY(logs) -ADD_SUBDIRECTORY(extra) - -ADD_EXECUTABLE(accel-pptpd - ppp/ppp.c - ppp/ppp_fsm.c - ppp/ppp_lcp.c - ppp/lcp_opt_mru.c - ppp/lcp_opt_magic.c - ppp/lcp_opt_pcomp.c - ppp/lcp_opt_accomp.c - ppp/ppp_auth.c - ppp/ppp_ipcp.c - ppp/ipcp_opt_ipaddr.c - ppp/ipcp_opt_dns.c - ppp/ppp_ccp.c - ppp/ccp_mppe.c - - cli/std_cmd.c - cli/show_sessions.c - cli/telnet.c - cli/tcp.c - cli/cli.c - - pwdb.c - ipdb.c - - iprange.c - - utils.c - - log.c - main.c - memdebug.c -) - -TARGET_LINK_LIBRARIES(accel-pptpd triton rt pthread crypto pcre) -set_property(TARGET accel-pptpd PROPERTY CMAKE_SKIP_BUILD_RPATH FALSE) -set_property(TARGET accel-pptpd PROPERTY CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) -set_property(TARGET accel-pptpd PROPERTY INSTALL_RPATH_USE_LINK_PATH FALSE) -set_property(TARGET accel-pptpd PROPERTY INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/lib/accel-pptp) - -INSTALL(TARGETS accel-pptpd - RUNTIME DESTINATION sbin -) - -INSTALL(FILES accel-pptp.conf DESTINATION /etc RENAME accel-pptp.conf.dist) -INSTALL(FILES accel-pptp.conf.5 DESTINATION share/man/man5) - -INSTALL(CODE "EXECUTE_PROCESS(COMMAND mkdir -p /var/log/accel-pptp)") -INSTALL(CODE "EXECUTE_PROCESS(COMMAND mkdir -p /var/run/accel-pptp)") -INSTALL(CODE "EXECUTE_PROCESS(COMMAND 'echo 0 > /var/run/accel-pptp/seq')") - diff --git a/accel-pptpd/accel-pptp.conf b/accel-pptpd/accel-pptp.conf deleted file mode 100644 index 0050cea..0000000 --- a/accel-pptpd/accel-pptp.conf +++ /dev/null @@ -1,121 +0,0 @@ -[modules] -#path=/usr/local/lib/accel-pptp -log_file -#log_tcp -#log_pgsql -pptp -#pppoe -#l2tp -auth_mschap_v2 -auth_mschap_v1 -auth_chap_md5 -auth_pap -radius -ippool -sigchld -pppd_compat -#shaper_tbf -#chap-secrets - -[core] -log-error=/var/log/accel-pptp/core.log -thread-count=4 - -[ppp] -verbose=1 -min-mtu=1000 -mtu=1400 -mru=1400 -#ccp=0 -#sid-case=upper -#check-ip=0 - -[lcp] -echo-interval=30 -echo-failure=3 - -[pptp] -echo-interval=30 -verbose=1 - -[pppoe] -interface=eth0 -#ac-name=xxx -#service-name=yyy -#pado-delay=0 -#pado-delay=0,100:100,200:200,-1:500 -#ifname-in-sid=called-sid -verbose=1 - -[l2tp] -#dictionary=/usr/local/share/accel-pptp/l2tp/dictionary -#hello-interval=60 -#timeout=60 -#rtimeout=5 -#retransmit=5 -#host-name=accel-pptp -verbose=1 - -[dns] -#dns1=172.16.0.1 -#dns2=172.16.1.1 - -[radius] -#dictionary=/usr/local/share/accel-pptp/radius/dictionary -nas-identifier=accel-pptp -nas-ip-address=127.0.0.1 -gw-ip-address=192.168.100.1 -auth-server=127.0.0.1:1812,testing123 -acct-server=127.0.0.1:1813,testing123 -dae-server=127.0.0.1:3799,testing123 -#dm_coa_secret=testing123 (deprecated) -verbose=1 -#timeout=3 -#max-try=3 -#acct-timeout=120 - -[client-ip-range] -10.0.0.0/8 - -[ip-pool] -gw-ip-address=192.168.0.1 -192.168.0.2-255 -192.168.1.1-255 -192.168.2.1-255 -192.168.3.1-255 - -[log] -log-file=/var/log/accel-pptp/accel-pptp.log -log-emerg=/var/log/accel-pptp/emerg.log -#log-debug=/dev/stdout -#log-tcp=127.0.0.1:3000 -copy=1 -#color=1 -#per-user-dir=per_user -#per-session-dir=per_session -#per-session=1 -level=3 -#log-tcp=127.0.0.1:3000 - -[log-pgsql] -conninfo=user=log -log-table=log - -[pppd-compat] -#ip-pre-up=/etc/ppp/ip-pre-up -ip-up=/etc/ppp/ip-up -ip-down=/etc/ppp/ip-down -ip-change=/etc/ppp/ip-change -radattr-prefix=/var/run/radattr -verbose=1 - -[tbf] -#attr=Filter-Id -#down-burst-factor=0.1 -#up-burst-factor=1.0 -#latency=50 - -[cli] -telnet=127.0.0.1:2000 -tcp=127.0.0.1:2001 -#passwd=123 diff --git a/accel-pptpd/accel-pptp.conf.5 b/accel-pptpd/accel-pptp.conf.5 deleted file mode 100644 index b786bef..0000000 --- a/accel-pptpd/accel-pptp.conf.5 +++ /dev/null @@ -1,384 +0,0 @@ -.TH ACCEL-PPTP.CONF 5 "6 October 2010" -.SH NAME -.B accel-pptp.conf -- ACCEL-PPTP VPN daemon configuration -.SH DESCRIPTION -.BR accel-pptpd (8) -reads options from this file, usually -.IR /etc/accel-pptp.conf -.TP -Configuration file consists of sections in form: -.TP -[section1] -.br -name1=val1 -.br -name2=val2 -.br -name3 -.TP -[section2] -.br - .... -.br -.SH SECTIONS -.TP -.SH [modules] -containes list of modules to load -.TP -.BI log_file -This is logging target which logs messages to files. It support per-session/per-user features. -.TP -.BI log_tcp -This is logging target which logs messages over TCP/IP. -.TP -.BI log_pgsql -This is logging target which logs messages to PostgreSQL. -.TP -.BI pptp -.br -PPTP controlling connection handling module. -.TP -.BI pppoe -.br -PPPoE discovery stage handling module. -.TP -.BI auth_pap -PAP authentication module. -.TP -.BI auth_chap -CHAP (md5) authentication module. -.TP -.BI auth_mschap_v1 -Microsoft CHAP (version 1) authentication module. -.TP -.BI auth_mschap_v2 -Microsoft CHAP (version 2) authentication module. -.TP -.BI radius -.br -RADIUS interaction module. -.TP -.BI ippool -.br -IP address assigning module. -.TP -.BI sigchld -Helper module to manage child processes, required by pppd_compat -.TP -.BI pppd_compat -This module starts pppd compatible ip-up/ip-down scripts and ip-change to handle RADIUS CoA request. -.TP -.SH [core] -Configuration of core module -.TP -.BI "log-error=" path -Path to file for core module error logging. -.TP -.BI "thread-count=" n -number of working threads, optimal - number of processors/cores -.TP -.SH [ppp] -.br -PPP module configuration. -.TP -.BI "verbose=" n -If n is not zero ppp module will produce verbose logging. -.TP -.BI "min-mtu=" n -Minimum acceptable MTU. If client will try to negotiate less then specified MTU then it will be NAKed or disconnected if rejects greater MTU. -.TP -.BI "mtu=" n -MTU which will be negotiated if client's MRU will be not acceptable. -.TP -.BI "mru=" n -Prefered MRU. -.TP -.BI "ccp=" n -Disable CCP negotiation if this parameter is zero. -.TP -.TP -.BI "sid-case=" upper|lower -Specifies in which case generate session identifier (default lower). -.TP -.BI "check-ip=" 0|1 -Specifies whether accel-pptp should check if IP already assigned to other ppp interface (default 0). -.TP -.SH [lcp] -.br -PPP LCP module configuration -.TP -.BI "echo-interval=" n -If this option is given and greater then 0 then lcp module will send echo-request every -.B n -seconds. -.TP -.BI "echo-failure=" n -Specifies maximum number of echo-requests may be sent without valid echo-reply, if exceeds connection will be terminated. -.TP -.SH [dns] -.TP -.BI "dns1=" x.x.x.x -Specifies primary DNS to be sent to peer. -.TP -.BI "dns2=" x.x.x.x -Specifies secondary DNS to be sent to peer. -.TP -.SH [client-ip-range] -You have to explicitly specify range of ip address from which clients can connect to server in form: -.br -.B x.x.x.x/mask -(for example 10.0.0.0/8) -.br -.B x.x.x.x-y -(for example 10.0.0.1-254) -.TP -.SH [pptp] -.br -Configuration of PPTP module. -.TP -.BI "bind=" x.x.x.x -If this option is given then pptp server will bind to specified IP address. -.TP -.BI "verbose=" n -If this option is given and -.B n -is greater of zero then pptp module will produce verbose logging. -.TP -.BI "echo-interval=" n -If this option is given and greater then zero then pptp module will send echo-request every -.B n -seconds. -.TP -.BI "echo-failure=" n -Specifies maximum number of echo-requests may be sent without valid echo-reply, if exceeds connection will be terminated. -.TP -.BI "timeout=" n -Timeout waiting reply from client in seconds (default 5). -.TP -.SH [pppoe] -.br -Configuration of PPPoE module. -.TP -.BI "interface=" ethX -Specifies interface name to listen/send discovery packets. You may specify multiple -.B interface -options. -.TP -.BI "ac-name=" ac-name -Specifies AC-Name tag value. If absent tag will not be sent. -.TP -.BI "service-name=" service-name -Specifies Service-Name to respond. If absent any Service-Name is acceptable and client's Service-Name will be sent back. -.TP -.BI "pado-delay=" delay[,delay1:count1[,delay2:count2[,...]]] -Specifies delays (also in condition of connection count) to send PADO (ms). -Last delay in list may be -1 which means don't accept new connections. -List have to be sorted by count key. -.TP -.BI "mac-filter=" filename,type -Specifies mac-filter filename and type, type maybe -.B allow -or -.B deny -.TP -.BI "ifname-in-sid=" called-sid|calling-sid|both -Specifies that interface name should be present in Called-Station-ID or in Calling-Station-ID or in both attributes. -.TP -.BI "verbose=" n -If this option is given and -.B n -is greater of zero then pppoe module will produce verbose logging. -.TP -.SH [l2tp] -.br -Configuration of L2TP module. -.TP -.BI "bind=" x.x.x.x -Specifies IP address to bind. -.TP -.BI "host-name=" string -This name will be sent to clients in Host-Name attribute. -.TP -.BI "hello-interval=" n -Specifies interval (in seconds) to send Hello control message. Its used for keep alive connection. If peer will not respond to Hello connection will be terminated. -.TP -.BI "timeout=" n -Specifies timeout (in seconds) to wait peer completes tunnel and session negotiation. -.TP -.BI "rtimeout=" n -Specifies timeout (in seconds) to wait message acknowledge, if elapsed message retransmition will be performed. -.TP -.BI "retransmit=" n -Specifies maximum number of message retransmission, if exceeds connection will be terminated. -.TP -.BI "verbose=" n -If this option is given and -.B n -is greater of zero then l2tp module will produce verbose logging. -.TP -.SH [radius] -.br -Configuration of RADIUS module. -.TP -.BI "nas-identifier=" identifier -Specifies value to send to RADIUS server in NAS-Identifier attribute and to be matched in DM/CoA requests. -.TP -.BI "nas-ip-address=" x.x.x.x -Specifies value to send to RADIUS server in NAS-IP-Address attribute and to be matched in DM/CoA requests. -Also DM/CoA server will bind to that address. -.TP -.BI "gw-ip-address=" x.x.x.x -Specifies address to use as local address of ppp interfaces if Framed-IP-Address received from RADIUS server. -.TP -.BI "auth-server=" x.x.x.x:port,secret -Specifies IP address, port and secret of authentication RADIUS server. -.TP -.BI "acct-server=" x.x.x.x:port,secret -Specifies IP address, port and secret of accounting RADIUS server. -.TP -.BI "dae-server=" x.x.x.x:port,secret -Specifies IP address, port to bind and secret for Dynamic Authorization Extension server (DM/CoA). -.TP -.BI "dm_coa_secret=" secret (deprecated, use dae-server instead) -Specifies secret to use in DM/CoA communication. -.TP -.BI "acct-interim-interval=" n -Specifies interval in seconds to send accounting information (may be overriden by radius Acct-Interim-Interval attribute) -.TP -.BI "verbose=" n -If this option is given and -.B n -is greater of zero then radius module will produce verbose logging. -.TP -.BI "interim-verbose=" n -If this option is given and -.B n -is greater of zero then radius module will produce verbose logging of interim radius packets. -.TP -.BI "timeout=" n -Timeout to wait response from server (sec) -.TP -.BI "max-try=" n -Specifies number of tries to send Access-Request/Accounting-Request queries. -.TP -.BI "acct-timeout=" n -Specifies timeout of accounting interim update. -.TP -.SH [log] -.br -Configuration of log and log_file modules. -.TP -.BI "log-file=" file -Path to file to write general log. -.TP -.BI "log-emerg=" file -Path to file to write emergency messages. -.TP -.BI "log-tcp=" x.x.x.x:port -Send logs to specified host. -.TP -.BI "copy=" n -If this options is given and greater then zero logging engine will duplicate session log in general log. -(Useful when per-session/per-user logs are not used) -.TP -.BI "per-session-dir=" dir -Directory for session logs. If specified each session will be logged separately to file which name is unique session identifier. -.TP -.BI "per-user-dir=" dir -Directory for user logs. If specified all sessions of same user will be logged to file which name is user name. -.TP -.BI "per-session=" n -If specified and n is greater then zero each session of same user will be logger separately to directory specified by "per-user-dir" -and subdirectory which name is user name and to file which name os unique session identifier. -.TP -.BI "level=" n -Specifies log level which values are: -.br -.B 0 -turn off all logging -.br -.B 1 -log only error messages -.br -.B 2 -log error and warning messages -.br -.B 3 -log error, warning and minimum information messages (use this level in conjuction with verbose option of other modules if you need verbose logging) -.br -.B 4 -log error, warning and full information messages (use this level in conjuction with verbose option of other modules if you need verbose logging) -.br -.B 5 -log all messages including debug messages -.TP -.SH [log-pgsql] -.br -Configuration of log_pgsql module. -.TP -.BI "conninfo=" conninfo -Conninfo to connect to PostgreSQL server. -.TP -.BI "log-table=" table -Table to send log messages. Table must contain following field: -.br -.B timestamp -timestamp -.br -.B username -text -.br -.B sessionid -text -.br -.B msg -text -.TP -.SH [pppd_compat] -.br -Configuration of pppd_compat module. -.TP -.BI "ip-pre-up=" file -Path to ip-pre-up script which is executed before ppp interface comes up, useful to setup firewall rules before any traffic can pass through the interface. -.TP -.BI "ip-up=" file -Path to ip-up script which is executed when ppp interfaces is completly configured and started. -.TP -.BI "ip-down=" file -Path to ip-down script which is executed when session is about to terminate. -.TP -.BI "ip-change=" file -Path to ip-change script which is executed for RADIUS CoA handling. -.TP -.BI "radattr=" prefix -Prefix of radattr files (for example /var/run/radattr, resulting files will be /var/run/radattr.pppX) -.TP -.BI "verbose=" n -If specified and greated then zero pppd_module will produce verbose logging. -.TP -.SH [ip-pool] -.br -Configuration of ippool module. -.TP -.BI "gw-ip-address=" x.x.x.x -Specifies single IP address to be used as local address of ppp interfaces. -.TP -.BI "gw=" range -Specifies range of local address of ppp interfaces if form: -.br -.B x.x.x.x/mask -(for example 10.0.0.0/8) -.br -.B x.x.x.x-y -(for example 10.0.0.1-254) -.TP -.BI "tunnel=" range -Specifies range of remote address of ppp interfaces if form: -.br -.B x.x.x.x/mask -.br -.B x.x.x.x-y -.TP -.BI "x.x.x.x/mask or x.x.x.x-y" -Also specifies range of remote address of ppp interfaces. diff --git a/accel-pptpd/auth/CMakeLists.txt b/accel-pptpd/auth/CMakeLists.txt deleted file mode 100644 index dbf4d13..0000000 --- a/accel-pptpd/auth/CMakeLists.txt +++ /dev/null @@ -1,13 +0,0 @@ -ADD_LIBRARY(auth_pap SHARED auth_pap.c) -ADD_LIBRARY(auth_chap_md5 SHARED auth_chap_md5.c) -ADD_LIBRARY(auth_mschap_v1 SHARED auth_mschap_v1.c) -ADD_LIBRARY(auth_mschap_v2 SHARED auth_mschap_v2.c) - -TARGET_LINK_LIBRARIES(auth_chap_md5 crypto) -TARGET_LINK_LIBRARIES(auth_mschap_v1 crypto) -TARGET_LINK_LIBRARIES(auth_mschap_v2 crypto) - -INSTALL(TARGETS auth_pap auth_chap_md5 auth_mschap_v1 auth_mschap_v2 - LIBRARY DESTINATION lib/accel-pptp -) - diff --git a/accel-pptpd/auth/auth_chap_md5.c b/accel-pptpd/auth/auth_chap_md5.c deleted file mode 100644 index d19634a..0000000 --- a/accel-pptpd/auth/auth_chap_md5.c +++ /dev/null @@ -1,427 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "log.h" -#include "ppp.h" -#include "ppp_auth.h" -#include "ppp_lcp.h" -#include "pwdb.h" - -#include "memdebug.h" - -#define CHAP_CHALLENGE 1 -#define CHAP_RESPONSE 2 -#define CHAP_SUCCESS 3 -#define CHAP_FAILURE 4 - -#define CHAP_MD5 5 - -#define VALUE_SIZE 16 - -#define MSG_FAILURE "Authentication failed" -#define MSG_SUCCESS "Authentication successed" - -#define HDR_LEN (sizeof(struct chap_hdr_t)-2) - -static int conf_timeout = 5; -static int conf_interval = 0; -static int conf_max_failure = 3; -static int conf_any_login = 0; - -static int urandom_fd; - -struct chap_hdr_t -{ - uint16_t proto; - uint8_t code; - uint8_t id; - uint16_t len; -} __attribute__((packed)); - -struct chap_challenge_t -{ - struct chap_hdr_t hdr; - uint8_t val_size; - uint8_t val[VALUE_SIZE]; - char name[0]; -} __attribute__((packed)); - -struct chap_failure_t -{ - struct chap_hdr_t hdr; - char message[sizeof(MSG_FAILURE)]; -} __attribute__((packed)); - -struct chap_success_t -{ - struct chap_hdr_t hdr; - char message[sizeof(MSG_SUCCESS)]; -} __attribute__((packed)); - - -struct chap_auth_data_t -{ - struct auth_data_t auth; - struct ppp_handler_t h; - struct ppp_t *ppp; - int id; - uint8_t val[VALUE_SIZE]; - struct triton_timer_t timeout; - struct triton_timer_t interval; - int failure; - int started:1; -}; - -static void chap_send_challenge(struct chap_auth_data_t *ad); -static void chap_recv(struct ppp_handler_t *h); -static void chap_timeout_timer(struct triton_timer_t *t); -static void chap_restart_timer(struct triton_timer_t *t); - -static void print_buf(const uint8_t *buf, int size) -{ - int i; - for (i=0; i < size; i++) - log_ppp_info2("%x", buf[i]); -} -static void print_str(const char *buf, int size) -{ - int i; - for (i = 0; i < size; i++) - log_ppp_info2("%c", buf[i]); -} - -static struct auth_data_t* auth_data_init(struct ppp_t *ppp) -{ - struct chap_auth_data_t *d = _malloc(sizeof(*d)); - - memset(d, 0, sizeof(*d)); - d->auth.proto = PPP_CHAP; - d->ppp = ppp; - - return &d->auth; -} - -static void auth_data_free(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - if (d->timeout.tpd) - triton_timer_del(&d->timeout); - - if (d->interval.tpd) - triton_timer_del(&d->interval); - - _free(d); -} - -static int chap_start(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - d->h.proto = PPP_CHAP; - d->h.recv = chap_recv; - d->timeout.expire = chap_timeout_timer; - d->timeout.period = conf_timeout * 1000; - d->interval.expire = chap_restart_timer; - d->interval.period = conf_interval * 1000; - - ppp_register_chan_handler(ppp, &d->h); - - chap_send_challenge(d); - - return 0; -} - -static int chap_finish(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - if (d->timeout.tpd) - triton_timer_del(&d->timeout); - - if (d->interval.tpd) - triton_timer_del(&d->interval); - - ppp_unregister_handler(ppp, &d->h); - - return 0; -} - -static void chap_timeout_timer(struct triton_timer_t *t) -{ - struct chap_auth_data_t *d = container_of(t, typeof(*d), timeout); - - if (conf_ppp_verbose) - log_ppp_warn("chap-md5: timeout\n"); - - if (++d->failure == conf_max_failure) { - if (d->started) - ppp_terminate(d->ppp, TERM_USER_ERROR, 0); - else - ppp_auth_failed(d->ppp, NULL); - } else { - --d->id; - chap_send_challenge(d); - } -} - -static void chap_restart_timer(struct triton_timer_t *t) -{ - struct chap_auth_data_t *d = container_of(t, typeof(*d), interval); - - chap_send_challenge(d); -} - -static int lcp_send_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) -{ - *ptr = CHAP_MD5; - return 1; -} - -static int lcp_recv_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) -{ - if (*ptr == CHAP_MD5) - return LCP_OPT_ACK; - return LCP_OPT_NAK; -} - -static void chap_send_failure(struct chap_auth_data_t *ad) -{ - struct chap_failure_t msg = { - .hdr.proto = htons(PPP_CHAP), - .hdr.code = CHAP_FAILURE, - .hdr.id = ad->id, - .hdr.len = htons(sizeof(msg) - 1 - 2), - .message = MSG_FAILURE, - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [CHAP Failure id=%x \"%s\"]\n", msg.hdr.id, MSG_FAILURE); - - ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); -} - -static void chap_send_success(struct chap_auth_data_t *ad) -{ - struct chap_success_t msg = { - .hdr.proto = htons(PPP_CHAP), - .hdr.code = CHAP_SUCCESS, - .hdr.id = ad->id, - .hdr.len = htons(sizeof(msg)-1-2), - .message = MSG_SUCCESS, - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [CHAP Success id=%x \"%s\"]\n", msg.hdr.id, MSG_SUCCESS); - - ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); -} - -static void chap_send_challenge(struct chap_auth_data_t *ad) -{ - struct chap_challenge_t msg = { - .hdr.proto = htons(PPP_CHAP), - .hdr.code = CHAP_CHALLENGE, - .hdr.id = ++ad->id, - .hdr.len = htons(sizeof(msg) - 2), - .val_size = VALUE_SIZE, - }; - - read(urandom_fd, ad->val, VALUE_SIZE); - memcpy(msg.val, ad->val, VALUE_SIZE); - - if (conf_ppp_verbose) { - log_ppp_info2("send [CHAP Challenge id=%x <", msg.hdr.id); - print_buf(msg.val, VALUE_SIZE); - log_ppp_info2(">]\n"); - } - - ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); - - if (conf_timeout && !ad->timeout.tpd) - triton_timer_add(ad->ppp->ctrl->ctx, &ad->timeout, 0); -} - -static void chap_recv_response(struct chap_auth_data_t *ad, struct chap_hdr_t *hdr) -{ - MD5_CTX md5_ctx; - uint8_t md5[MD5_DIGEST_LENGTH]; - char *passwd; - char *name; - int r; - struct chap_challenge_t *msg = (struct chap_challenge_t*)hdr; - - if (ad->timeout.tpd) - triton_timer_del(&ad->timeout); - - if (conf_ppp_verbose) { - log_ppp_info2("recv [CHAP Response id=%x <", msg->hdr.id); - print_buf(msg->val, msg->val_size); - log_ppp_info2(">, name=\""); - print_str(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); - log_ppp_info2("\"]\n"); - } - - if (msg->hdr.id != ad->id) { - if (conf_ppp_verbose) - log_ppp_error("chap-md5: id mismatch\n"); - chap_send_failure(ad); - ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); - } - - if (msg->val_size != VALUE_SIZE) { - log_ppp_error("chap-md5: incorrect value-size (%i)\n", msg->val_size); - chap_send_failure(ad); - ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); - } - - name = _strndup(msg->name,ntohs(msg->hdr.len) - sizeof(*msg) + 2); - - if (conf_any_login) { - chap_send_success(ad); - ad->started = 1; - ppp_auth_successed(ad->ppp, name); - return; - } - - r = pwdb_check(ad->ppp, name, PPP_CHAP, CHAP_MD5, ad->id, ad->val, VALUE_SIZE, msg->val); - - if (r == PWDB_NO_IMPL) { - passwd = pwdb_get_passwd(ad->ppp,name); - if (!passwd) - { - _free(name); - if (conf_ppp_verbose) - log_ppp_warn("chap-md5: user not found\n"); - chap_send_failure(ad); - return; - } - - MD5_Init(&md5_ctx); - MD5_Update(&md5_ctx,&msg->hdr.id,1); - MD5_Update(&md5_ctx,passwd,strlen(passwd)); - MD5_Update(&md5_ctx,ad->val,VALUE_SIZE); - MD5_Final(md5,&md5_ctx); - - if (memcmp(md5,msg->val,sizeof(md5))) - { - if (conf_ppp_verbose) - log_ppp_warn("chap-md5: challenge response mismatch\n"); - chap_send_failure(ad); - if (ad->started) - ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); - else - ppp_auth_failed(ad->ppp, name); - _free(name); - } else { - chap_send_success(ad); - if (!ad->started) { - ad->started = 1; - if (conf_interval) - triton_timer_add(ad->ppp->ctrl->ctx, &ad->interval, 0); - ppp_auth_successed(ad->ppp, name); - } else - _free(name); - } - _free(passwd); - } else if (r == PWDB_DENIED) { - chap_send_failure(ad); - if (ad->started) - ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); - else - ppp_auth_failed(ad->ppp, name); - _free(name); - } else { - chap_send_success(ad); - if (!ad->started) { - ad->started = 1; - if (conf_interval) - triton_timer_add(ad->ppp->ctrl->ctx, &ad->interval, 0); - ppp_auth_successed(ad->ppp, name); - } else - _free(name); - } -} - -static int chap_check(uint8_t *ptr) -{ - return *ptr == CHAP_MD5; -} - -static int chap_restart(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - chap_send_challenge(d); - - return 0; -} - -static struct ppp_auth_handler_t chap= -{ - .name = "CHAP-md5", - .init = auth_data_init, - .free = auth_data_free, - .send_conf_req = lcp_send_conf_req, - .recv_conf_req = lcp_recv_conf_req, - .start = chap_start, - .finish = chap_finish, - .check = chap_check, - .restart = chap_restart, -}; - -static void chap_recv(struct ppp_handler_t *h) -{ - struct chap_auth_data_t *d = container_of(h, typeof(*d), h); - struct chap_hdr_t *hdr = (struct chap_hdr_t *)d->ppp->chan_buf; - - if (d->ppp->chan_buf_size < sizeof(*hdr) || ntohs(hdr->len) < HDR_LEN || ntohs(hdr->len) < d->ppp->chan_buf_size - 2) { - log_ppp_warn("chap-md5: short packet received\n"); - return; - } - - if (hdr->code == CHAP_RESPONSE) - chap_recv_response(d, hdr); - else - log_ppp_warn("chap-md5: unknown code received %x\n", hdr->code); -} - -static void __init auth_chap_md5_init() -{ - char *opt; - - opt = conf_get_opt("auth", "timeout"); - if (opt && atoi(opt) > 0) - conf_timeout = atoi(opt); - - opt = conf_get_opt("auth", "interval"); - if (opt && atoi(opt) > 0) - conf_interval = atoi(opt); - - opt = conf_get_opt("auth", "max-failure"); - if (opt && atoi(opt) > 0) - conf_max_failure = atoi(opt); - - opt = conf_get_opt("auth", "any-login"); - if (opt && atoi(opt) > 0) - conf_any_login = 1; - - urandom_fd=open("/dev/urandom", O_RDONLY); - - if (urandom_fd < 0) { - log_emerg("chap-md5: failed to open /dev/urandom: %s\n", strerror(errno)); - return; - } - - if (ppp_auth_register_handler(&chap)) - log_emerg("chap-md5: failed to register handler\n"); -} - diff --git a/accel-pptpd/auth/auth_mschap_v1.c b/accel-pptpd/auth/auth_mschap_v1.c deleted file mode 100644 index 5b38db5..0000000 --- a/accel-pptpd/auth/auth_mschap_v1.c +++ /dev/null @@ -1,517 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "log.h" -#include "ppp.h" -#include "events.h" -#include "ppp_auth.h" -#include "ppp_lcp.h" -#include "pwdb.h" - -#include "memdebug.h" - -#define MSCHAP_V1 0x80 - -#define CHAP_CHALLENGE 1 -#define CHAP_RESPONSE 2 -#define CHAP_SUCCESS 3 -#define CHAP_FAILURE 4 - -#define VALUE_SIZE 8 -#define RESPONSE_VALUE_SIZE (24+24+1) - -#define MSG_FAILURE "E=691 R=0" -#define MSG_SUCCESS "Authentication successed" - -#define HDR_LEN (sizeof(struct chap_hdr_t)-2) - -static int conf_timeout = 5; -static int conf_interval = 0; -static int conf_max_failure = 3; -static int conf_any_login = 0; - -static int urandom_fd; - -struct chap_hdr_t -{ - uint16_t proto; - uint8_t code; - uint8_t id; - uint16_t len; -} __attribute__((packed)); - -struct chap_challenge_t -{ - struct chap_hdr_t hdr; - uint8_t val_size; - uint8_t val[VALUE_SIZE]; - char name[0]; -} __attribute__((packed)); - -struct chap_response_t -{ - struct chap_hdr_t hdr; - uint8_t val_size; - uint8_t lm_hash[24]; - uint8_t nt_hash[24]; - uint8_t flags; - char name[0]; -} __attribute__((packed)); - -struct chap_failure_t -{ - struct chap_hdr_t hdr; - char message[sizeof(MSG_FAILURE)]; -} __attribute__((packed)); - -struct chap_success_t -{ - struct chap_hdr_t hdr; - char message[sizeof(MSG_SUCCESS)]; -} __attribute__((packed)); - - -struct chap_auth_data_t -{ - struct auth_data_t auth; - struct ppp_handler_t h; - struct ppp_t *ppp; - int id; - uint8_t val[VALUE_SIZE]; - struct triton_timer_t timeout; - struct triton_timer_t interval; - int failure; - int started:1; -}; - -static void chap_send_challenge(struct chap_auth_data_t *ad); -static void chap_recv(struct ppp_handler_t *h); -static int chap_check_response(struct chap_auth_data_t *ad, struct chap_response_t *res, const char *name); -static void chap_timeout_timer(struct triton_timer_t *t); -static void chap_restart_timer(struct triton_timer_t *t); -static void set_mppe_keys(struct chap_auth_data_t *ad, uint8_t *z_hash); - -static void print_buf(const uint8_t *buf,int size) -{ - int i; - for (i = 0; i < size; i++) - log_ppp_info2("%x", buf[i]); -} -static void print_str(const char *buf, int size) -{ - int i; - for(i = 0; i < size; i++) - log_ppp_info2("%c", buf[i]); -} - -static struct auth_data_t* auth_data_init(struct ppp_t *ppp) -{ - struct chap_auth_data_t *d = _malloc(sizeof(*d)); - - memset(d, 0, sizeof(*d)); - d->auth.proto = PPP_CHAP; - d->ppp = ppp; - - return &d->auth; -} - -static void auth_data_free(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - if (d->timeout.tpd) - triton_timer_del(&d->timeout); - - if (d->interval.tpd) - triton_timer_del(&d->interval); - - _free(d); -} - -static int chap_start(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - d->h.proto = PPP_CHAP; - d->h.recv = chap_recv; - d->timeout.expire = chap_timeout_timer; - d->timeout.period = conf_timeout * 1000; - d->interval.expire = chap_restart_timer; - d->interval.period = conf_interval * 1000; - - ppp_register_chan_handler(ppp, &d->h); - - chap_send_challenge(d); - - return 0; -} - -static int chap_finish(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - if (d->timeout.tpd) - triton_timer_del(&d->timeout); - - if (d->interval.tpd) - triton_timer_del(&d->interval); - - ppp_unregister_handler(ppp, &d->h); - - return 0; -} - -static void chap_timeout_timer(struct triton_timer_t *t) -{ - struct chap_auth_data_t *d = container_of(t, typeof(*d), timeout); - - if (conf_ppp_verbose) - log_ppp_warn("mschap-v1: timeout\n"); - - if (++d->failure == conf_max_failure) { - if (d->started) - ppp_terminate(d->ppp, TERM_USER_ERROR, 0); - else - ppp_auth_failed(d->ppp, NULL); - } else { - --d->id; - chap_send_challenge(d); - } -} - -static void chap_restart_timer(struct triton_timer_t *t) -{ - struct chap_auth_data_t *d = container_of(t, typeof(*d), interval); - - chap_send_challenge(d); -} - -static int lcp_send_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) -{ - *ptr = MSCHAP_V1; - return 1; -} - -static int lcp_recv_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) -{ - if (*ptr == MSCHAP_V1) - return LCP_OPT_ACK; - return LCP_OPT_NAK; -} - -static void chap_send_failure(struct chap_auth_data_t *ad) -{ - struct chap_failure_t msg = { - .hdr.proto = htons(PPP_CHAP), - .hdr.code = CHAP_FAILURE, - .hdr.id = ad->id, - .hdr.len = htons(sizeof(msg)-1-2), - .message = MSG_FAILURE, - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [MSCHAP-v1 Failure id=%x \"%s\"]\n", msg.hdr.id, MSG_FAILURE); - - ppp_chan_send(ad->ppp,&msg,ntohs(msg.hdr.len)+2); -} - -static void chap_send_success(struct chap_auth_data_t *ad) -{ - struct chap_success_t msg = { - .hdr.proto = htons(PPP_CHAP), - .hdr.code = CHAP_SUCCESS, - .hdr.id = ad->id, - .hdr.len = htons(sizeof(msg)-1-2), - .message = MSG_SUCCESS, - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [MSCHAP-v1 Success id=%x \"%s\"]\n", msg.hdr.id, MSG_SUCCESS); - - ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); -} - -static void chap_send_challenge(struct chap_auth_data_t *ad) -{ - struct chap_challenge_t msg = { - .hdr.proto = htons(PPP_CHAP), - .hdr.code = CHAP_CHALLENGE, - .hdr.id = ++ad->id, - .hdr.len = htons(sizeof(msg) - 2), - .val_size = VALUE_SIZE, - }; - - read(urandom_fd, ad->val, VALUE_SIZE); - memcpy(msg.val, ad->val, VALUE_SIZE); - - if (conf_ppp_verbose) { - log_ppp_info2("send [MSCHAP-v1 Challenge id=%x <", msg.hdr.id); - print_buf(msg.val, VALUE_SIZE); - log_ppp_info2(">]\n"); - } - - ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); - - if (conf_timeout && !ad->timeout.tpd) - triton_timer_add(ad->ppp->ctrl->ctx, &ad->timeout, 0); -} - -static void chap_recv_response(struct chap_auth_data_t *ad, struct chap_hdr_t *hdr) -{ - struct chap_response_t *msg = (struct chap_response_t*)hdr; - char *name; - int r; - - if (ad->timeout.tpd) - triton_timer_del(&ad->timeout); - - if (conf_ppp_verbose) { - log_ppp_info2("recv [MSCHAP-v1 Response id=%x <", msg->hdr.id); - print_buf(msg->lm_hash, 24); - log_ppp_info2(">, <"); - print_buf(msg->nt_hash, 24); - log_ppp_info2(">, F=%i, name=\"", msg->flags); - print_str(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); - log_ppp_info2("\"]\n"); - } - - if (msg->hdr.id != ad->id) { - if (conf_ppp_verbose) - log_ppp_error("mschap-v1: id mismatch\n"); - chap_send_failure(ad); - if (ad->started) - ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); - else - ppp_auth_failed(ad->ppp, NULL); - } - - if (msg->val_size != RESPONSE_VALUE_SIZE) { - log_ppp_error("mschap-v1: incorrect value-size (%i)\n", msg->val_size); - chap_send_failure(ad); - if (ad->started) - ppp_terminate(ad->ppp, TERM_AUTH_ERROR, 0); - else - ppp_auth_failed(ad->ppp, NULL); - } - - name = _strndup(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); - if (!name) { - log_emerg("mschap-v1: out of memory\n"); - if (ad->started) - ppp_terminate(ad->ppp, TERM_NAS_ERROR, 0); - else - ppp_auth_failed(ad->ppp, NULL); - return; - } - - if (conf_any_login) { - chap_send_success(ad); - ad->started = 1; - ppp_auth_successed(ad->ppp, name); - return; - } - - r = pwdb_check(ad->ppp, name, PPP_CHAP, MSCHAP_V1, ad->id, ad->val, VALUE_SIZE, msg->lm_hash, msg->nt_hash, msg->flags); - if (r == PWDB_NO_IMPL) - if (chap_check_response(ad, msg, name)) - r = PWDB_DENIED; - - if (r == PWDB_DENIED) { - chap_send_failure(ad); - if (ad->started) - ppp_terminate(ad->ppp, TERM_AUTH_ERROR, 0); - else - ppp_auth_failed(ad->ppp, name); - _free(name); - } else { - chap_send_success(ad); - if (!ad->started) { - ad->started = 1; - if (conf_interval) - triton_timer_add(ad->ppp->ctrl->ctx, &ad->interval, 0); - ppp_auth_successed(ad->ppp, name); - } else - _free(name); - } -} - -static void des_encrypt(const uint8_t *input, const uint8_t *key, uint8_t *output) -{ - int i, j, parity; - union - { - uint64_t u64; - uint8_t buf[8]; - } p_key; - DES_cblock cb; - DES_cblock res; - DES_key_schedule ks; - - memcpy(p_key.buf, key, 7); - p_key.u64 = bswap_64(p_key.u64); - - for (i = 0; i < 8; i++) { - cb[i] = (((p_key.u64 << (7 * i)) >> 56) & 0xfe); - for( j = 0, parity = 0; j < 7; j++) - if ((cb[i] >> (j + 1)) & 1) - parity++; - cb[i] |= (~parity) & 1; - } - - DES_set_key_checked(&cb, &ks); - memcpy(cb, input, 8); - DES_ecb_encrypt(&cb, &res, &ks, DES_ENCRYPT); - memcpy(output, res, 8); -} - -static int chap_check_response(struct chap_auth_data_t *ad, struct chap_response_t *msg, const char *name) -{ - MD4_CTX md4_ctx; - uint8_t z_hash[21]; - uint8_t nt_hash[24]; - char *passwd; - char *u_passwd; - int i; - - passwd = pwdb_get_passwd(ad->ppp,name); - if (!passwd) { - if (conf_ppp_verbose) - log_ppp_warn("mschap-v1: user not found\n"); - chap_send_failure(ad); - return PWDB_DENIED; - } - - u_passwd = _malloc(strlen(passwd) * 2); - for (i = 0; i< strlen(passwd); i++) { - u_passwd[i * 2] = passwd[i]; - u_passwd[i * 2 + 1] = 0; - } - - memset(z_hash, 0, sizeof(z_hash)); - MD4_Init(&md4_ctx); - MD4_Update(&md4_ctx, u_passwd, strlen(passwd) * 2); - MD4_Final(z_hash, &md4_ctx); - - des_encrypt(ad->val, z_hash, nt_hash); - des_encrypt(ad->val, z_hash + 7, nt_hash + 8); - des_encrypt(ad->val, z_hash + 14, nt_hash + 16); - - set_mppe_keys(ad, z_hash); - - _free(passwd); - _free(u_passwd); - - return memcmp(nt_hash, msg->nt_hash, 24) ? PWDB_DENIED : PWDB_SUCCESS; -} - -static int chap_check(uint8_t *ptr) -{ - return *ptr == MSCHAP_V1; -} - -static void set_mppe_keys(struct chap_auth_data_t *ad, uint8_t *z_hash) -{ - MD4_CTX md4_ctx; - SHA_CTX sha_ctx; - uint8_t digest[20]; - - struct ev_mppe_keys_t ev_mppe = { - .ppp = ad->ppp, - .type = 1 << 2, - .policy = 1, - .recv_key = digest, - .send_key = digest, - }; - - //NtPasswordHashHash - MD4_Init(&md4_ctx); - MD4_Update(&md4_ctx, z_hash, 16); - MD4_Final(digest, &md4_ctx); - - //Get_Start_Key - SHA1_Init(&sha_ctx); - SHA1_Update(&sha_ctx, digest, 16); - SHA1_Update(&sha_ctx, digest, 16); - SHA1_Update(&sha_ctx, ad->val, VALUE_SIZE); - SHA1_Final(digest, &sha_ctx); - - triton_event_fire(EV_MPPE_KEYS, &ev_mppe); -} - -static int chap_restart(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - chap_send_challenge(d); - - return 0; -} - -static struct ppp_auth_handler_t chap = { - .name = "MSCHAP-v1", - .init = auth_data_init, - .free = auth_data_free, - .send_conf_req = lcp_send_conf_req, - .recv_conf_req = lcp_recv_conf_req, - .start = chap_start, - .finish = chap_finish, - .check = chap_check, - .restart = chap_restart, -}; - -static void chap_recv(struct ppp_handler_t *h) -{ - struct chap_auth_data_t *d = container_of(h, typeof(*d), h); - struct chap_hdr_t *hdr = (struct chap_hdr_t *)d->ppp->chan_buf; - - if (d->ppp->chan_buf_size < sizeof(*hdr) || ntohs(hdr->len) < HDR_LEN || ntohs(hdr->len) < d->ppp->chan_buf_size - 2) { - log_ppp_warn("mschap-v1: short packet received\n"); - return; - } - - if (hdr->code == CHAP_RESPONSE) - chap_recv_response(d, hdr); - else - log_ppp_warn("mschap-v1: unknown code received %x\n", hdr->code); -} - -static void __init auth_mschap_v1_init() -{ - char *opt; - - opt = conf_get_opt("auth", "timeout"); - if (opt && atoi(opt) > 0) - conf_timeout = atoi(opt); - - opt = conf_get_opt("auth", "interval"); - if (opt && atoi(opt) > 0) - conf_interval = atoi(opt); - - opt = conf_get_opt("auth", "max-failure"); - if (opt && atoi(opt) > 0) - conf_max_failure = atoi(opt); - - opt = conf_get_opt("auth", "any-login"); - if (opt && atoi(opt) > 0) - conf_any_login = 1; - - urandom_fd = open("/dev/urandom", O_RDONLY); - if (urandom_fd < 0) { - log_emerg("mschap-v1: failed to open /dev/urandom: %s\n", strerror(errno)); - return; - } - if (ppp_auth_register_handler(&chap)) - log_emerg("mschap-v1: failed to register handler\n"); -} - diff --git a/accel-pptpd/auth/auth_mschap_v2.c b/accel-pptpd/auth/auth_mschap_v2.c deleted file mode 100644 index e07c4f7..0000000 --- a/accel-pptpd/auth/auth_mschap_v2.c +++ /dev/null @@ -1,639 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "log.h" -#include "ppp.h" -#include "events.h" -#include "ppp_auth.h" -#include "ppp_lcp.h" -#include "pwdb.h" - -#include "memdebug.h" - -#define MSCHAP_V2 0x81 - -#define CHAP_CHALLENGE 1 -#define CHAP_RESPONSE 2 -#define CHAP_SUCCESS 3 -#define CHAP_FAILURE 4 - -#define VALUE_SIZE 16 -#define RESPONSE_VALUE_SIZE (16+8+24+1) - -#define MSG_FAILURE "E=691 R=0 C=cccccccccccccccccccccccccccccccc V=3 M=Authentication failure" -#define MSG_SUCCESS "S=cccccccccccccccccccccccccccccccccccccccc M=Authentication successed" - -#define HDR_LEN (sizeof(struct chap_hdr_t)-2) - -static int conf_timeout = 5; -static int conf_interval = 0; -static int conf_max_failure = 3; - -static int urandom_fd; - -struct chap_hdr_t -{ - uint16_t proto; - uint8_t code; - uint8_t id; - uint16_t len; -} __attribute__((packed)); - -struct chap_challenge_t -{ - struct chap_hdr_t hdr; - uint8_t val_size; - uint8_t val[VALUE_SIZE]; - char name[0]; -} __attribute__((packed)); - -struct chap_response_t -{ - struct chap_hdr_t hdr; - uint8_t val_size; - uint8_t peer_challenge[16]; - uint8_t reserved[8]; - uint8_t nt_hash[24]; - uint8_t flags; - char name[0]; -} __attribute__((packed)); - -struct chap_failure_t -{ - struct chap_hdr_t hdr; - char message[sizeof(MSG_FAILURE)]; -} __attribute__((packed)); - -struct chap_success_t -{ - struct chap_hdr_t hdr; - char message[sizeof(MSG_SUCCESS)]; -} __attribute__((packed)); - - -struct chap_auth_data_t -{ - struct auth_data_t auth; - struct ppp_handler_t h; - struct ppp_t *ppp; - int id; - uint8_t val[VALUE_SIZE]; - struct triton_timer_t timeout; - struct triton_timer_t interval; - int failure; - int started:1; -}; - -static void chap_send_challenge(struct chap_auth_data_t *ad); -static void chap_recv(struct ppp_handler_t *h); -static int chap_check_response(struct chap_auth_data_t *ad, struct chap_response_t *msg, const char *name); -static void chap_timeout_timer(struct triton_timer_t *t); -static void chap_restart_timer(struct triton_timer_t *t); -static void set_mppe_keys(struct chap_auth_data_t *ad, uint8_t *z_hash, uint8_t *nt_hash); - -static void print_buf(const uint8_t *buf, int size) -{ - int i; - for (i = 0; i < size; i++) - log_ppp_info2("%x", buf[i]); -} - -static void print_str(const char *buf, int size) -{ - int i; - for (i = 0; i < size; i++) - log_ppp_info2("%c", buf[i]); -} - -static struct auth_data_t* auth_data_init(struct ppp_t *ppp) -{ - struct chap_auth_data_t *d = _malloc(sizeof(*d)); - - memset(d, 0, sizeof(*d)); - d->auth.proto = PPP_CHAP; - d->ppp = ppp; - - return &d->auth; -} - -static void auth_data_free(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - if (d->timeout.tpd) - triton_timer_del(&d->timeout); - - if (d->interval.tpd) - triton_timer_del(&d->interval); - - _free(d); -} - -static int chap_start(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - d->h.proto = PPP_CHAP; - d->h.recv = chap_recv; - d->timeout.expire = chap_timeout_timer; - d->timeout.period = conf_timeout * 1000; - d->interval.expire = chap_restart_timer; - d->interval.period = conf_interval * 1000; - - ppp_register_chan_handler(ppp, &d->h); - - chap_send_challenge(d); - - return 0; -} - -static int chap_finish(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - if (d->timeout.tpd) - triton_timer_del(&d->timeout); - - if (d->interval.tpd) - triton_timer_del(&d->interval); - - ppp_unregister_handler(ppp,&d->h); - - return 0; -} - -static void chap_timeout_timer(struct triton_timer_t *t) -{ - struct chap_auth_data_t *d = container_of(t, typeof(*d), timeout); - - if (conf_ppp_verbose) - log_ppp_warn("mschap-v2: timeout\n"); - - if (++d->failure == conf_max_failure) { - if (d->started) - ppp_terminate(d->ppp, TERM_USER_ERROR, 0); - else - ppp_auth_failed(d->ppp, NULL); - } else { - --d->id; - chap_send_challenge(d); - } -} - -static void chap_restart_timer(struct triton_timer_t *t) -{ - struct chap_auth_data_t *d = container_of(t, typeof(*d), interval); - - chap_send_challenge(d); -} - -static int lcp_send_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) -{ - *ptr = MSCHAP_V2; - return 1; -} - -static int lcp_recv_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) -{ - if (*ptr == MSCHAP_V2) - return LCP_OPT_ACK; - return LCP_OPT_NAK; -} - -static void chap_send_failure(struct chap_auth_data_t *ad) -{ - struct chap_failure_t msg = { - .hdr.proto = htons(PPP_CHAP), - .hdr.code = CHAP_FAILURE, - .hdr.id = ad->id, - .hdr.len = htons(sizeof(msg) - 1 - 2), - .message = MSG_FAILURE, - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [MSCHAP-v2 Failure id=%x \"%s\"]\n", msg.hdr.id, MSG_FAILURE); - - ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); -} - -static int generate_response(struct chap_auth_data_t *ad, struct chap_response_t *msg, const char *name, char *authenticator) -{ - MD4_CTX md4_ctx; - SHA_CTX sha_ctx; - char *passwd; - char *u_passwd; - uint8_t pw_hash[MD4_DIGEST_LENGTH]; - uint8_t c_hash[SHA_DIGEST_LENGTH]; - uint8_t response[SHA_DIGEST_LENGTH]; - int i; - - uint8_t magic1[39] = - {0x4D, 0x61, 0x67, 0x69, 0x63, 0x20, 0x73, 0x65, 0x72, 0x76, - 0x65, 0x72, 0x20, 0x74, 0x6F, 0x20, 0x63, 0x6C, 0x69, 0x65, - 0x6E, 0x74, 0x20, 0x73, 0x69, 0x67, 0x6E, 0x69, 0x6E, 0x67, - 0x20, 0x63, 0x6F, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x74}; - uint8_t magic2[41] = - {0x50, 0x61, 0x64, 0x20, 0x74, 0x6F, 0x20, 0x6D, 0x61, 0x6B, - 0x65, 0x20, 0x69, 0x74, 0x20, 0x64, 0x6F, 0x20, 0x6D, 0x6F, - 0x72, 0x65, 0x20, 0x74, 0x68, 0x61, 0x6E, 0x20, 0x6F, 0x6E, - 0x65, 0x20, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6F, - 0x6E}; - - - passwd = pwdb_get_passwd(ad->ppp,name); - if (!passwd) - return -1; - - u_passwd=_malloc(strlen(passwd)*2); - for(i=0; int_hash,24); - SHA1_Update(&sha_ctx,magic1,39); - SHA1_Final(response,&sha_ctx); - - SHA1_Init(&sha_ctx); - SHA1_Update(&sha_ctx,msg->peer_challenge,16); - SHA1_Update(&sha_ctx,ad->val,16); - SHA1_Update(&sha_ctx,name,strlen(name)); - SHA1_Final(c_hash,&sha_ctx); - - SHA1_Init(&sha_ctx); - SHA1_Update(&sha_ctx,response,20); - SHA1_Update(&sha_ctx,c_hash,8); - SHA1_Update(&sha_ctx,magic2,41); - SHA1_Final(response,&sha_ctx); - - for(i=0; i<20; i++) - sprintf(authenticator+i*2,"%02X",response[i]); - - _free(passwd); - _free(u_passwd); - - return 0; -} - -static void chap_send_success(struct chap_auth_data_t *ad, struct chap_response_t *res_msg, const char *authenticator) -{ - struct chap_success_t msg = { - .hdr.proto = htons(PPP_CHAP), - .hdr.code = CHAP_SUCCESS, - .hdr.id = ad->id, - .hdr.len = htons(sizeof(msg) - 1 - 2), - .message = MSG_SUCCESS, - }; - - memcpy(msg.message + 2, authenticator, 40); - - if (conf_ppp_verbose) - log_ppp_info2("send [MSCHAP-v2 Success id=%x \"%s\"]\n", msg.hdr.id, msg.message); - - ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); -} - -static void chap_send_challenge(struct chap_auth_data_t *ad) -{ - struct chap_challenge_t msg = { - .hdr.proto = htons(PPP_CHAP), - .hdr.code = CHAP_CHALLENGE, - .hdr.id = ++ad->id, - .hdr.len = htons(sizeof(msg) - 2), - .val_size = VALUE_SIZE, - }; - - read(urandom_fd, ad->val, VALUE_SIZE); - memcpy(msg.val, ad->val, VALUE_SIZE); - - if (conf_ppp_verbose) { - log_ppp_info2("send [MSCHAP-v2 Challenge id=%x <", msg.hdr.id); - print_buf(msg.val, VALUE_SIZE); - log_ppp_info2(">]\n"); - } - - ppp_chan_send(ad->ppp, &msg, ntohs(msg.hdr.len) + 2); - - if (conf_timeout && !ad->timeout.tpd) - triton_timer_add(ad->ppp->ctrl->ctx, &ad->timeout, 0); -} - -static void chap_recv_response(struct chap_auth_data_t *ad, struct chap_hdr_t *hdr) -{ - struct chap_response_t *msg = (struct chap_response_t*)hdr; - char *name; - char authenticator[41]; - int r; - - if (ad->timeout.tpd) - triton_timer_del(&ad->timeout); - - if (conf_ppp_verbose) { - log_ppp_info2("recv [MSCHAP-v2 Response id=%x <", msg->hdr.id); - print_buf(msg->peer_challenge,16); - log_ppp_info2(">, <"); - print_buf(msg->nt_hash, 24); - log_ppp_info2(">, F=%i, name=\"", msg->flags); - print_str(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); - log_ppp_info2("\"]\n"); - } - - if (msg->hdr.id != ad->id) { - if (conf_ppp_verbose) - log_ppp_error("mschap-v2: id mismatch\n"); - chap_send_failure(ad); - if (ad->started) - ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); - else - ppp_auth_failed(ad->ppp, NULL); - } - - if (msg->val_size != RESPONSE_VALUE_SIZE) { - log_ppp_error("mschap-v2: incorrect value-size (%i)\n", msg->val_size); - chap_send_failure(ad); - if (ad->started) - ppp_terminate(ad->ppp, TERM_USER_ERROR, 0); - else - ppp_auth_failed(ad->ppp, NULL); - } - - name = _strndup(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); - if (!name) { - log_emerg("mschap-v2: out of memory\n"); - if (ad->started) - ppp_terminate(ad->ppp, TERM_NAS_ERROR, 0); - else - ppp_auth_failed(ad->ppp, NULL); - return; - } - - r = pwdb_check(ad->ppp, name, PPP_CHAP, MSCHAP_V2, ad->id, ad->val, msg->peer_challenge, msg->reserved, msg->nt_hash, msg->flags, authenticator); - - if (r == PWDB_NO_IMPL) { - r = chap_check_response(ad, msg, name); - if (r) - r = PWDB_DENIED; - else if (generate_response(ad, msg, name, authenticator)) - r = PWDB_DENIED; - } - - if (r == PWDB_DENIED) { - chap_send_failure(ad); - if (ad->started) - ppp_terminate(ad->ppp, TERM_AUTH_ERROR, 0); - else - ppp_auth_failed(ad->ppp, name); - _free(name); - } else { - chap_send_success(ad, msg, authenticator); - if (!ad->started) { - ad->started = 1; - if (conf_interval) - triton_timer_add(ad->ppp->ctrl->ctx, &ad->interval, 0); - ppp_auth_successed(ad->ppp, name); - } else - _free(name); - } -} - -static void des_encrypt(const uint8_t *input, const uint8_t *key, uint8_t *output) -{ - int i,j,parity; - union - { - uint64_t u64; - uint8_t buf[8]; - } p_key; - DES_cblock cb; - DES_cblock res; - DES_key_schedule ks; - - memcpy(p_key.buf,key,7); - p_key.u64=bswap_64(p_key.u64); - - for(i=0;i<8;i++) - { - cb[i]=(((p_key.u64<<(7*i))>>56)&0xfe); - for(j=0, parity=0; j<7; j++) - if ((cb[i]>>(j+1))&1) parity++; - cb[i]|=(~parity)&1; - } - - DES_set_key_checked(&cb, &ks); - memcpy(cb,input,8); - DES_ecb_encrypt(&cb,&res,&ks,DES_ENCRYPT); - memcpy(output,res,8); -} - -static int chap_check_response(struct chap_auth_data_t *ad, struct chap_response_t *msg, const char *name) -{ - MD4_CTX md4_ctx; - SHA_CTX sha_ctx; - uint8_t z_hash[21]; - uint8_t c_hash[SHA_DIGEST_LENGTH]; - uint8_t nt_hash[24]; - char *passwd; - char *u_passwd; - int i; - - passwd = pwdb_get_passwd(ad->ppp, name); - if (!passwd) { - if (conf_ppp_verbose) - log_ppp_warn("mschap-v2: user not found\n"); - chap_send_failure(ad); - return -1; - } - - u_passwd=_malloc(strlen(passwd)*2); - for(i=0; ipeer_challenge,16); - SHA1_Update(&sha_ctx,ad->val,16); - SHA1_Update(&sha_ctx,name,strlen(name)); - SHA1_Final(c_hash,&sha_ctx); - - memset(z_hash,0,sizeof(z_hash)); - MD4_Init(&md4_ctx); - MD4_Update(&md4_ctx,u_passwd,strlen(passwd)*2); - MD4_Final(z_hash,&md4_ctx); - - des_encrypt(c_hash,z_hash,nt_hash); - des_encrypt(c_hash,z_hash+7,nt_hash+8); - des_encrypt(c_hash,z_hash+14,nt_hash+16); - - set_mppe_keys(ad, z_hash, msg->nt_hash); - - _free(passwd); - _free(u_passwd); - - return memcmp(nt_hash,msg->nt_hash,24); -} - -static void set_mppe_keys(struct chap_auth_data_t *ad, uint8_t *z_hash, uint8_t *nt_hash) -{ - MD4_CTX md4_ctx; - SHA_CTX sha_ctx; - uint8_t digest[20]; - uint8_t send_key[20]; - uint8_t recv_key[20]; - - uint8_t pad1[40] = - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - - uint8_t pad2[40] = - {0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, - 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, - 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, - 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2}; - - uint8_t magic1[27] = - {0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, - 0x68, 0x65, 0x20, 0x4d, 0x50, 0x50, 0x45, 0x20, 0x4d, - 0x61, 0x73, 0x74, 0x65, 0x72, 0x20, 0x4b, 0x65, 0x79}; - - uint8_t magic2[84] = - {0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69, - 0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, - 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, - 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, 0x6b, 0x65, 0x79, - 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, - 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, 0x69, 0x64, 0x65, - 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, - 0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20, - 0x6b, 0x65, 0x79, 0x2e}; - - uint8_t magic3[84] = - {0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69, - 0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, - 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, - 0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20, - 0x6b, 0x65, 0x79, 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, - 0x65, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, - 0x69, 0x64, 0x65, 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, - 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, - 0x6b, 0x65, 0x79, 0x2e}; - - struct ev_mppe_keys_t ev_mppe = { - .ppp = ad->ppp, - .type = 1 << 2, - .policy = 1, - .recv_key = recv_key, - .send_key = send_key, - }; - - //NtPasswordHashHash - MD4_Init(&md4_ctx); - MD4_Update(&md4_ctx, z_hash, 16); - MD4_Final(digest, &md4_ctx); - - //GetMasterKey - SHA1_Init(&sha_ctx); - SHA1_Update(&sha_ctx, digest, 16); - SHA1_Update(&sha_ctx, nt_hash, 24); - SHA1_Update(&sha_ctx, magic1, sizeof(magic1)); - SHA1_Final(digest, &sha_ctx); - - //send key - SHA1_Init(&sha_ctx); - SHA1_Update(&sha_ctx, digest, 16); - SHA1_Update(&sha_ctx, pad1, sizeof(pad1)); - SHA1_Update(&sha_ctx, magic3, sizeof(magic2)); - SHA1_Update(&sha_ctx, pad2, sizeof(pad2)); - SHA1_Final(send_key, &sha_ctx); - - //recv key - SHA1_Init(&sha_ctx); - SHA1_Update(&sha_ctx, digest, 16); - SHA1_Update(&sha_ctx, pad1, sizeof(pad1)); - SHA1_Update(&sha_ctx, magic2, sizeof(magic3)); - SHA1_Update(&sha_ctx, pad2, sizeof(pad2)); - SHA1_Final(recv_key, &sha_ctx); - - triton_event_fire(EV_MPPE_KEYS, &ev_mppe); -} - -static int chap_check(uint8_t *ptr) -{ - return *ptr == MSCHAP_V2; -} - -static int chap_restart(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct chap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - chap_send_challenge(d); - - return 0; -} - -static struct ppp_auth_handler_t chap= -{ - .name = "MSCHAP-v2", - .init = auth_data_init, - .free = auth_data_free, - .send_conf_req = lcp_send_conf_req, - .recv_conf_req = lcp_recv_conf_req, - .start = chap_start, - .finish = chap_finish, - .check = chap_check, - .restart = chap_restart, -}; - -static void chap_recv(struct ppp_handler_t *h) -{ - struct chap_auth_data_t *d = container_of(h, typeof(*d), h); - struct chap_hdr_t *hdr = (struct chap_hdr_t *)d->ppp->chan_buf; - - if (d->ppp->chan_buf_size < sizeof(*hdr) || ntohs(hdr->len) < HDR_LEN || ntohs(hdr->len) < d->ppp->chan_buf_size - 2) { - log_ppp_warn("mschap-v2: short packet received\n"); - return; - } - - if (hdr->code == CHAP_RESPONSE) - chap_recv_response(d, hdr); - else - log_ppp_warn("mschap-v2: unknown code received %x\n",hdr->code); -} - -static void __init auth_mschap_v2_init() -{ - urandom_fd = open("/dev/urandom", O_RDONLY); - if (urandom_fd < 0) { - log_emerg("mschap-v2: failed to open /dev/urandom: %s\n", strerror(errno)); - return; - } - - if (ppp_auth_register_handler(&chap)) - log_emerg("mschap-v2: failed to register handler\n"); -} - diff --git a/accel-pptpd/auth/auth_pap.c b/accel-pptpd/auth/auth_pap.c deleted file mode 100644 index 6909046..0000000 --- a/accel-pptpd/auth/auth_pap.c +++ /dev/null @@ -1,273 +0,0 @@ -#include -#include -#include -#include - -#include "log.h" -#include "ppp.h" -#include "ppp_auth.h" -#include "ppp_lcp.h" -#include "pwdb.h" - -#include "memdebug.h" - -#define MSG_FAILED "Authentication failed" -#define MSG_SUCCESSED "Authentication successed" - -#define HDR_LEN (sizeof(struct pap_hdr_t)-2) - -#define PAP_REQ 1 -#define PAP_ACK 2 -#define PAP_NAK 3 - -static int conf_timeout = 5; -static int conf_any_login = 0; - -static struct auth_data_t* auth_data_init(struct ppp_t *ppp); -static void auth_data_free(struct ppp_t*, struct auth_data_t*); -static int lcp_send_conf_req(struct ppp_t*, struct auth_data_t*, uint8_t*); -static int lcp_recv_conf_req(struct ppp_t*, struct auth_data_t*, uint8_t*); -static int pap_start(struct ppp_t*, struct auth_data_t*); -static int pap_finish(struct ppp_t*, struct auth_data_t*); -static void pap_recv(struct ppp_handler_t*h); -static void pap_timeout(struct triton_timer_t *t); - -struct pap_auth_data_t -{ - struct auth_data_t auth; - struct ppp_handler_t h; - struct ppp_t *ppp; - int started:1; - struct triton_timer_t timeout; -}; - -struct pap_hdr_t -{ - uint16_t proto; - uint8_t code; - uint8_t id; - uint16_t len; -} __attribute__((packed)); - -struct pap_ack_t -{ - struct pap_hdr_t hdr; - uint8_t msg_len; - char msg[0]; -} __attribute__((packed)); - -static struct ppp_auth_handler_t pap= -{ - .name = "PAP", - .init = auth_data_init, - .free = auth_data_free, - .send_conf_req = lcp_send_conf_req, - .recv_conf_req = lcp_recv_conf_req, - .start = pap_start, - .finish = pap_finish, -}; - -static struct auth_data_t* auth_data_init(struct ppp_t *ppp) -{ - struct pap_auth_data_t *d = _malloc(sizeof(*d)); - - memset(d, 0, sizeof(*d)); - d->auth.proto = PPP_PAP; - d->ppp = ppp; - - return &d->auth; -} - -static void auth_data_free(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct pap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - _free(d); -} - -static int pap_start(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct pap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - d->h.proto = PPP_PAP; - d->h.recv = pap_recv; - d->timeout.expire = pap_timeout; - d->timeout.period = conf_timeout * 1000; - - triton_timer_add(ppp->ctrl->ctx, &d->timeout, 0); - - ppp_register_chan_handler(ppp, &d->h); - - return 0; -} -static int pap_finish(struct ppp_t *ppp, struct auth_data_t *auth) -{ - struct pap_auth_data_t *d = container_of(auth, typeof(*d), auth); - - if (d->timeout.tpd) - triton_timer_del(&d->timeout); - - ppp_unregister_handler(ppp, &d->h); - - return 0; -} - -static void pap_timeout(struct triton_timer_t *t) -{ - struct pap_auth_data_t *d = container_of(t, typeof(*d), timeout); - - if (conf_ppp_verbose) - log_ppp_warn("pap: timeout\n"); - - ppp_auth_failed(d->ppp, NULL); -} - -static int lcp_send_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) -{ - return 0; -} - -static int lcp_recv_conf_req(struct ppp_t *ppp, struct auth_data_t *d, uint8_t *ptr) -{ - return LCP_OPT_ACK; -} - -static void pap_send_ack(struct pap_auth_data_t *p, int id) -{ - uint8_t buf[128]; - struct pap_ack_t *msg = (struct pap_ack_t*)buf; - msg->hdr.proto = htons(PPP_PAP); - msg->hdr.code = PAP_ACK; - msg->hdr.id = id; - msg->hdr.len = htons(HDR_LEN + 1 + sizeof(MSG_SUCCESSED) - 1); - msg->msg_len = sizeof(MSG_SUCCESSED) - 1; - memcpy(msg->msg, MSG_SUCCESSED, sizeof(MSG_SUCCESSED)); - - if (conf_ppp_verbose) - log_ppp_info2("send [PAP AuthAck id=%x \"%s\"]\n", id, MSG_SUCCESSED); - - ppp_chan_send(p->ppp, msg, ntohs(msg->hdr.len) + 2); -} - -static void pap_send_nak(struct pap_auth_data_t *p, int id) -{ - uint8_t buf[128]; - struct pap_ack_t *msg = (struct pap_ack_t*)buf; - msg->hdr.proto = htons(PPP_PAP); - msg->hdr.code = PAP_NAK; - msg->hdr.id = id; - msg->hdr.len = htons(HDR_LEN + 1 + sizeof(MSG_FAILED) - 1); - msg->msg_len = sizeof(MSG_FAILED) - 1; - memcpy(msg->msg, MSG_FAILED, sizeof(MSG_FAILED)); - - if (conf_ppp_verbose) - log_ppp_info2("send [PAP AuthNak id=%x \"%s\"]\n", id, MSG_FAILED); - - ppp_chan_send(p->ppp, msg, ntohs(msg->hdr.len) + 2); -} - -static int pap_recv_req(struct pap_auth_data_t *p, struct pap_hdr_t *hdr) -{ - int ret, r; - char *peer_id; - char *passwd; - char *passwd2; - int peer_id_len; - int passwd_len; - uint8_t *ptr = (uint8_t*)(hdr + 1); - - if (p->timeout.tpd) - triton_timer_del(&p->timeout); - - if (conf_ppp_verbose) - log_ppp_info2("recv [PAP AuthReq id=%x]\n", hdr->id); - - peer_id_len = *(uint8_t*)ptr; ptr++; - if (peer_id_len > ntohs(hdr->len) - sizeof(*hdr) + 2 - 1) { - log_ppp_warn("PAP: short packet received\n"); - return -1; - } - peer_id = (char*)ptr; ptr += peer_id_len; - - passwd_len = *(uint8_t*)ptr; ptr++; - if (passwd_len > ntohs(hdr->len) - sizeof(*hdr ) + 2 - 2 - peer_id_len) { - log_ppp_warn("PAP: short packet received\n"); - return -1; - } - - peer_id = _strndup((const char*)peer_id, peer_id_len); - - if (conf_any_login) { - pap_send_ack(p, hdr->id); - p->started = 1; - ppp_auth_successed(p->ppp, peer_id); - return 0; - } - - passwd = _strndup((const char*)ptr, passwd_len); - - r = pwdb_check(p->ppp, peer_id, PPP_PAP, passwd); - if (r == PWDB_NO_IMPL) { - passwd2 = pwdb_get_passwd(p->ppp, peer_id); - if (!passwd2 || strcmp(passwd2, passwd)) - r = PWDB_DENIED; - else - r = PWDB_SUCCESS; - _free(passwd2); - } - if (r == PWDB_DENIED) { - if (conf_ppp_verbose) - log_ppp_warn("PAP: authentication error\n"); - pap_send_nak(p, hdr->id); - if (p->started) - ppp_terminate(p->ppp, TERM_AUTH_ERROR, 0); - else - ppp_auth_failed(p->ppp, peer_id); - ret=-1; - _free(peer_id); - } else { - pap_send_ack(p, hdr->id); - if (!p->started) { - p->started = 1; - ppp_auth_successed(p->ppp, peer_id); - } - ret = 0; - } - - _free(passwd); - - return ret; -} - -static void pap_recv(struct ppp_handler_t *h) -{ - struct pap_auth_data_t *d = container_of(h, typeof(*d), h); - struct pap_hdr_t *hdr = (struct pap_hdr_t *)d->ppp->chan_buf; - - if (d->ppp->chan_buf_size < sizeof(*hdr) || ntohs(hdr->len) < HDR_LEN || ntohs(hdr->len) < d->ppp->chan_buf_size - 2) { - log_ppp_warn("PAP: short packet received\n"); - return; - } - - if (hdr->code == PAP_REQ) - pap_recv_req(d, hdr); - else { - log_ppp_warn("PAP: unknown code received %x\n",hdr->code); - } -} - -static void __init auth_pap_init() -{ - char *opt; - - opt = conf_get_opt("auth", "timeout"); - if (opt && atoi(opt) > 0) - conf_timeout = atoi(opt); - - opt = conf_get_opt("auth", "any-login"); - if (opt && atoi(opt) > 0) - conf_any_login = 1; - - ppp_auth_register_handler(&pap); -} - diff --git a/accel-pptpd/cli/CMakeLists.txt b/accel-pptpd/cli/CMakeLists.txt deleted file mode 100644 index 8b13789..0000000 --- a/accel-pptpd/cli/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/accel-pptpd/cli/cli.c b/accel-pptpd/cli/cli.c deleted file mode 100644 index ef168de..0000000 --- a/accel-pptpd/cli/cli.c +++ /dev/null @@ -1,227 +0,0 @@ -#include -#include -#include -#include - -#include "triton.h" - -#include "cli.h" -#include "cli_p.h" -#include "log.h" -#include "events.h" - -#include "memdebug.h" - -#define MAX_CMD_ITEMS 100 -#define MSG_SYNTAX_ERROR "syntax error\r\n" -#define MSG_INVAL_ERROR "invalid argument\r\n" -#define MSG_UNKNOWN_CMD "command unknown\r\n" - -char *conf_cli_passwd; -static const char *def_cli_prompt = "accel-pptp"; -char *conf_cli_prompt; - -static LIST_HEAD(simple_cmd_list); -static LIST_HEAD(regexp_cmd_list); - -void __export cli_register_simple_cmd(struct cli_simple_cmd_t *cmd) -{ - list_add_tail(&cmd->entry, &simple_cmd_list); -} - -void __export cli_register_simple_cmd2( - int (*exec)(const char *cmd, char * const *fields, int fields_cnt, void *client), - void (*help)(char * const *fields, int fields_cnt, void *client), - int hdr_len, - ... - ) -{ - struct cli_simple_cmd_t *c; - int i; - va_list ap; - - va_start(ap, hdr_len); - - c = malloc(sizeof(*c)); - memset(c, 0, sizeof(*c)); - - c->exec = exec; - c->help = help; - c->hdr_len = hdr_len; - c->hdr = malloc(hdr_len * sizeof(void*)); - - for (i = 0; i < hdr_len; i++) - c->hdr[i] = va_arg(ap, char *); - - list_add_tail(&c->entry, &simple_cmd_list); -} - -void __export cli_register_regexp_cmd(struct cli_regexp_cmd_t *cmd) -{ - int err; - cmd->re = pcre_compile2(cmd->pattern, cmd->options, &err, NULL, NULL, NULL); - if (!cmd->re) { - log_emerg("cli: failed to compile regexp %s: %i\n", cmd->pattern, err); - _exit(EXIT_FAILURE); - } - list_add_tail(&cmd->entry, &simple_cmd_list); -} - -int __export cli_send(void *client, const char *data) -{ - struct cli_client_t *cln = (struct cli_client_t *)client; - - return cln->send(cln, data, strlen(data)); -} - -int __export cli_sendv(void *client, const char *fmt, ...) -{ - struct cli_client_t *cln = (struct cli_client_t *)client; - int r; - - va_list ap; - va_start(ap, fmt); - r = cln->sendv(cln, fmt, ap); - va_end(ap); - - return r; -} - - -static char *skip_word(char *ptr) -{ - for(; *ptr; ptr++) - if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') - break; - return ptr; -} -static char *skip_space(char *ptr) -{ - for(; *ptr; ptr++) - if (*ptr != ' ' && *ptr != '\t') - break; - return ptr; -} -static int split(char *buf, char **ptr) -{ - int i; - - ptr[0] = buf; - - for (i = 1; i <= MAX_CMD_ITEMS; i++) { - buf = skip_word(buf); - if (!*buf) - return i; - - *buf = 0; - - buf = skip_space(buf + 1); - if (!*buf) - return i; - - ptr[i] = buf; - } - - buf = skip_word(buf); - *buf = 0; - - return i; -} - -int cli_process_cmd(struct cli_client_t *cln) -{ - struct cli_simple_cmd_t *cmd1; - struct cli_regexp_cmd_t *cmd2; - char *f[MAX_CMD_ITEMS]; - int r, i, n, found = 0; - - n = split((char *)cln->cmdline, f); - - if (n >= 1 && !strcmp(f[0], "help")) { - list_for_each_entry(cmd1, &simple_cmd_list, entry) - if (cmd1->help) - cmd1->help(f, n, cln); - - list_for_each_entry(cmd2, ®exp_cmd_list, entry) - if (cmd2->help) - cmd1->help(f, n, cln); - - return 0; - } - - list_for_each_entry(cmd1, &simple_cmd_list, entry) { - if (cmd1->hdr_len && n >= cmd1->hdr_len) { - for (i = 0; i < cmd1->hdr_len; i++) { - if (strcmp(cmd1->hdr[i], f[i])) - break; - } - if (i < cmd1->hdr_len) - continue; - r = cmd1->exec((char *)cln->cmdline, f, n, cln); - switch (r) { - case CLI_CMD_EXIT: - cln->disconnect(cln); - case CLI_CMD_FAILED: - return -1; - case CLI_CMD_SYNTAX: - cli_send(cln, MSG_SYNTAX_ERROR); - return 0; - case CLI_CMD_INVAL: - cli_send(cln, MSG_INVAL_ERROR); - return 0; - case CLI_CMD_OK: - found = 1; - } - } - } - - list_for_each_entry(cmd2, ®exp_cmd_list, entry) { - r = cmd2->exec((char *)cln->cmdline, cln); - switch (r) { - case CLI_CMD_EXIT: - cln->disconnect(cln); - case CLI_CMD_FAILED: - return 0; - case CLI_CMD_SYNTAX: - cli_send(cln, MSG_SYNTAX_ERROR); - return 0; - case CLI_CMD_OK: - found = 1; - } - } - - if (!found) { - if (cli_send(cln, MSG_UNKNOWN_CMD)) - return -1; - } - - return 0; -} - -static void load_config(void) -{ - const char *opt; - - if (conf_cli_passwd) - _free(conf_cli_passwd); - opt = conf_get_opt("cli", "password"); - if (opt) - conf_cli_passwd = _strdup(opt); - else - conf_cli_passwd = NULL; - - if (conf_cli_prompt && conf_cli_prompt != def_cli_prompt) - _free(conf_cli_prompt); - opt = conf_get_opt("cli", "prompt"); - if (opt) - conf_cli_prompt = _strdup(opt); - else - conf_cli_prompt = (char *)def_cli_prompt; -} - -static void __init init(void) -{ - load_config(); - - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); -} diff --git a/accel-pptpd/cli/cli.h b/accel-pptpd/cli/cli.h deleted file mode 100644 index cdceb2f..0000000 --- a/accel-pptpd/cli/cli.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef __CLI_H -#define __CLI_H - -#include -#include - -#define CLI_CMD_OK 0 -#define CLI_CMD_FAILED -1 -#define CLI_CMD_EXIT -2 -#define CLI_CMD_SYNTAX 1 -#define CLI_CMD_INVAL 2 - -struct cli_simple_cmd_t -{ - struct list_head entry; - int hdr_len; - const char **hdr; - int (*exec)(const char *cmd, char * const *fields, int fields_cnt, void *client); - void (*help)(char * const *fields, int field_cnt, void *client); -}; - -struct cli_regexp_cmd_t -{ - struct list_head entry; - pcre *re; - const char *pattern; - int options; - int (*exec)(const char *cmd, void *client); - int (*help)(char * const *fields, int field_cnt, void *client); -}; - -struct ppp_t; - -void cli_register_simple_cmd(struct cli_simple_cmd_t *cmd); -void cli_register_simple_cmd2( - int (*exec)(const char *cmd, char * const *fields, int fields_cnt, void *client), - void (*help)(char * const *fields, int fields_cnt, void *client), - int hdr_len, - ... - ); -void cli_register_regexp_cmd(struct cli_regexp_cmd_t *cmd); -void cli_show_ses_register(const char *name, const char *desc, void (*print)(const struct ppp_t *ppp, char *buf)); - -int cli_send(void *client, const char *data); -int cli_sendv(void *client, const char *fmt, ...); - -#endif - diff --git a/accel-pptpd/cli/cli_p.h b/accel-pptpd/cli/cli_p.h deleted file mode 100644 index 0fcba30..0000000 --- a/accel-pptpd/cli/cli_p.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef __CLI_P_H -#define __CLI_P_H - -#include - -#include "triton.h" - -struct cli_client_t -{ - uint8_t *cmdline; - int (*send)(struct cli_client_t *, const void *buf, int size); - int (*sendv)(struct cli_client_t *, const char *fmt, va_list ap); - void (*disconnect)(struct cli_client_t *); -}; - -int cli_process_cmd(struct cli_client_t *cln); - -extern char *conf_cli_passwd; -extern char *conf_cli_prompt; - -#endif - diff --git a/accel-pptpd/cli/show_sessions.c b/accel-pptpd/cli/show_sessions.c deleted file mode 100644 index 90aeb3f..0000000 --- a/accel-pptpd/cli/show_sessions.c +++ /dev/null @@ -1,434 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "triton.h" -#include "events.h" -#include "ppp.h" -#include "cli.h" -#include "utils.h" -#include "log.h" -#include "memdebug.h" - -#define CELL_SIZE 128 -#define DEF_COLUMNS "ifname,username,calling-sid,ip,rate-limit,type,state,uptime" - -struct column_t -{ - struct list_head entry; - const char *name; - const char *desc; - void (*print)(const struct ppp_t *ppp, char *buf); -}; - -struct col_t -{ - struct list_head entry; - struct column_t *column; - int width; -}; - -struct row_t -{ - struct list_head entry; - char *match_key; - char *order_key; - struct list_head cell_list; -}; - -struct cell_t -{ - struct list_head entry; - struct col_t *col; - char buf[CELL_SIZE + 1]; -}; - -static LIST_HEAD(col_list); - -void __export cli_show_ses_register(const char *name, const char *desc, void (*print)(const struct ppp_t *ppp, char *buf)) -{ - struct column_t *c = malloc(sizeof(*c)); - c->name = name; - c->desc = desc; - c->print = print; - list_add_tail(&c->entry, &col_list); -} - -static void show_ses_help(char * const *f, int f_cnt, void *cli) -{ - struct column_t *col; - char buf[129]; - - cli_send(cli, "show sessions [columns] [order ] [match ] - shows sessions\r\n"); - cli_send(cli, "\tcolumns:\r\n"); - - list_for_each_entry(col, &col_list, entry) { - snprintf(buf, 128, "\t\t%s - %s\r\n", col->name, col->desc); - cli_send(cli, buf); - } -} - -static struct column_t *find_column(const char *name) -{ - struct column_t *col; - - list_for_each_entry(col, &col_list, entry) { - if (strcmp(col->name, name)) - continue; - return col; - } - - return NULL; -} - -static void free_row(struct row_t *row) -{ - struct cell_t *cell; - - while (!list_empty(&row->cell_list)) { - cell = list_entry(row->cell_list.next, typeof(*cell), entry); - list_del(&cell->entry); - _free(cell); - } - - _free(row); -} - -static void insert_row(struct list_head *list, struct row_t *row) -{ - struct row_t *row2, *row3; - - row3 = NULL; - list_for_each_entry(row2, list, entry) { - if (strcmp(row->order_key, row2->order_key) <= 0) { - row3 = row2; - break; - } - } - if (row3) - list_add_tail(&row->entry, &row3->entry); - else - list_add_tail(&row->entry, list); -} - -static int show_ses_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - char *columns = NULL; - struct column_t *match_key = NULL; - char *match_pattern = NULL; - struct column_t *order_key = NULL; - pcre *re = NULL; - const char *pcre_err; - int pcre_offset; - struct column_t *column; - struct col_t *col; - struct row_t *row; - struct cell_t *cell; - char *ptr1, *ptr2; - int i, n, total_width, def_columns = 0; - struct ppp_t *ppp; - char *buf = NULL; - LIST_HEAD(c_list); - LIST_HEAD(r_list); - LIST_HEAD(t_list); - - for (i = 2; i < f_cnt; i++) { - if (!strcmp(f[i], "order")) { - if (i == f_cnt - 1) - return CLI_CMD_SYNTAX; - order_key = find_column(f[++i]); - if (!order_key) { - cli_sendv(cli, "unknown column %s\r\n", f[i]); - return CLI_CMD_OK; - } - } else if (!strcmp(f[i], "match")) { - if (i == f_cnt - 2) - return CLI_CMD_SYNTAX; - match_key = find_column(f[++i]); - if (!match_key) { - cli_sendv(cli, "unknown column %s\r\n", f[i]); - return CLI_CMD_OK; - } - match_pattern = f[++i]; - } else if (!columns) - columns = f[i]; - else - return CLI_CMD_SYNTAX; - } - - if (match_key) { - re = pcre_compile2(match_pattern, 0, NULL, &pcre_err, &pcre_offset, NULL); - if (!re) { - cli_sendv(cli, "match: %s at %i\r\n", pcre_err, pcre_offset); - return CLI_CMD_OK; - } - } - - if (!columns) { - columns = DEF_COLUMNS; - def_columns = 1; - } - - columns = _strdup(columns); - ptr1 = columns; - while (1) { - ptr2 = strchr(ptr1, ','); - if (ptr2) - *ptr2 = 0; - column = find_column(ptr1); - if (column) { - col = _malloc(sizeof(*col)); - col->column = column; - col->width = strlen(column->name); - list_add_tail(&col->entry, &c_list); - } else { - if (!def_columns) { - cli_sendv(cli, "unknown column %s\r\n", ptr1); - _free(columns); - goto out; - } - } - if (!ptr2) - break; - ptr1 = ptr2 + 1; - } - _free(columns); - - pthread_rwlock_rdlock(&ppp_lock); - list_for_each_entry(ppp, &ppp_list, entry) { - row = _malloc(sizeof(*row)); - if (!row) - goto oom; - memset(row, 0, sizeof(*row)); - INIT_LIST_HEAD(&row->cell_list); - if (match_key || order_key) - list_add_tail(&row->entry, &t_list); - else - list_add_tail(&row->entry, &r_list); - list_for_each_entry(col, &c_list, entry) { - cell = _malloc(sizeof(*cell)); - if (!cell) - goto oom; - cell->col = col; - list_add_tail(&cell->entry, &row->cell_list); - col->column->print(ppp, cell->buf); - n = strlen(cell->buf); - if (n > col->width) - col->width = n; - if (col->column == order_key) - row->order_key = cell->buf; - if (col->column == match_key) - row->match_key = cell->buf; - } - } - pthread_rwlock_unlock(&ppp_lock); - - if (order_key || match_key) { - while(!list_empty(&t_list)) { - row = list_entry(t_list.next, typeof(*row), entry); - list_del(&row->entry); - if (match_key) { - if (pcre_exec(re, NULL, row->match_key, strlen(row->match_key), 0, 0, NULL, 0) < 0) { - free_row(row); - continue; - } - } - if (order_key) - insert_row(&r_list, row); - else - list_add_tail(&row->entry, &r_list); - } - } - - total_width = -1; - list_for_each_entry(col, &c_list, entry) - total_width += col->width + 3; - - buf = _malloc(total_width + 3); - if (!buf) - goto oom; - - ptr1 = buf; - list_for_each_entry(col, &c_list, entry) { - n = strlen(col->column->name); - if (col->width > n + 1) { - ptr2 = ptr1; - memset(ptr1, ' ', col->width/2 - n/2 + 1); - ptr1 += col->width/2 - n/2 + 1; - sprintf(ptr1, "%s", col->column->name); - ptr1 = strchr(ptr1, 0); - memset(ptr1, ' ', col->width + 2 - (ptr1 - ptr2)); - ptr1 += col->width + 2 - (ptr1 - ptr2); - *ptr1 = '|'; - ptr1++; - } else if (col->width > n) { - sprintf(ptr1, " %s |", col->column->name); - ptr1 = strchr(ptr1, 0); - } else { - sprintf(ptr1, " %s |", col->column->name); - ptr1 = strchr(ptr1, 0); - } - } - - strcpy(ptr1 - 1, "\r\n"); - cli_send(cli, buf); - - ptr1 = buf; - list_for_each_entry(col, &c_list, entry) { - memset(ptr1, '-', col->width + 2); - ptr1 += col->width + 2; - *ptr1 = '+'; - ptr1++; - } - - strcpy(ptr1 - 1, "\r\n"); - cli_send(cli, buf); - - while (!list_empty(&r_list)) { - row = list_entry(r_list.next, typeof(*row), entry); - ptr1 = buf; - list_for_each_entry(cell, &row->cell_list, entry) { - ptr2 = ptr1; - sprintf(ptr1, " %s ", cell->buf); - ptr1 = strchr(ptr1, 0); - n = ptr1 - ptr2; - if (n - 2 < cell->col->width) { - memset(ptr1, ' ', cell->col->width + 2 - (ptr1 - ptr2)); - ptr1 += cell->col->width + 2 - (ptr1 - ptr2); - } - *ptr1 = '|'; - ptr1++; - } - strcpy(ptr1 - 1, "\r\n"); - cli_send(cli, buf); - list_del(&row->entry); - free_row(row); - } - - _free(buf); - -out: - while (!list_empty(&c_list)) { - col = list_entry(c_list.next, typeof(*col), entry); - list_del(&col->entry); - _free(col); - } - - if (re) - pcre_free(re); - - return CLI_CMD_OK; - -oom: - if (buf) - _free(buf); - - while (!list_empty(&t_list)) { - row = list_entry(t_list.next, typeof(*row), entry); - list_del(&row->entry); - free_row(row); - } - cli_send(cli, "out of memory"); - goto out; -} - -static void print_ifname(const struct ppp_t *ppp, char *buf) -{ - snprintf(buf, CELL_SIZE, "%s", ppp->ifname); -} - -static void print_username(const struct ppp_t *ppp, char *buf) -{ - if (ppp->username) - snprintf(buf, CELL_SIZE, "%s", ppp->username); -} - -static void print_ip(const struct ppp_t *ppp, char *buf) -{ - char str[17]; - u_inet_ntoa(ppp->peer_ipaddr, str); - sprintf(buf, "%s", str); -} - -static void print_type(const struct ppp_t *ppp, char *buf) -{ - snprintf(buf, CELL_SIZE, "%s", ppp->ctrl->name); -} - -static void print_state(const struct ppp_t *ppp, char *buf) -{ - char *state; - switch (ppp->state) { - case PPP_STATE_STARTING: - state = "start"; - break; - case PPP_STATE_ACTIVE: - state = "active"; - break; - case PPP_STATE_FINISHING: - state = "finish"; - break; - default: - state = "unk"; - } - sprintf(buf, "%s", state); -} - -static void print_uptime(const struct ppp_t *ppp, char *buf) -{ - time_t uptime; - int day,hour,min,sec; - char time_str[14]; - - if (ppp->stop_time) - uptime = ppp->stop_time - ppp->start_time; - else { - time(&uptime); - uptime -= ppp->start_time; - } - - day = uptime/ (24*60*60); uptime %= (24*60*60); - hour = uptime / (60*60); uptime %= (60*60); - min = uptime / 60; - sec = uptime % 60; - if (day) - snprintf(time_str, 13, "%i.%02i:%02i:%02i", day, hour, min, sec); - else - snprintf(time_str, 13, "%02i:%02i:%02i", hour, min, sec); - - sprintf(buf, "%s", time_str); -} - -static void print_calling_sid(const struct ppp_t *ppp, char *buf) -{ - snprintf(buf, CELL_SIZE, "%s", ppp->ctrl->calling_station_id); -} - -static void print_called_sid(const struct ppp_t *ppp, char *buf) -{ - snprintf(buf, CELL_SIZE, "%s", ppp->ctrl->called_station_id); -} - -static void print_sid(const struct ppp_t *ppp, char *buf) -{ - snprintf(buf, CELL_SIZE, "%s", ppp->sessionid); -} - -void __init init(void) -{ - cli_register_simple_cmd2(show_ses_exec, show_ses_help, 2, "show", "sessions"); - - cli_show_ses_register("ifname", "interface name", print_ifname); - cli_show_ses_register("username", "user name", print_username); - cli_show_ses_register("ip", "IP address", print_ip); - cli_show_ses_register("type", "VPN type", print_type); - cli_show_ses_register("state", "state of session", print_state); - cli_show_ses_register("uptime", "uptime", print_uptime); - cli_show_ses_register("calling-sid", "calling station id", print_calling_sid); - cli_show_ses_register("called-sid", "called station id", print_called_sid); - cli_show_ses_register("sid", "session id", print_sid); -} - diff --git a/accel-pptpd/cli/std_cmd.c b/accel-pptpd/cli/std_cmd.c deleted file mode 100644 index a49bbce..0000000 --- a/accel-pptpd/cli/std_cmd.c +++ /dev/null @@ -1,324 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "triton.h" -#include "events.h" -#include "ppp.h" -#include "cli.h" -#include "utils.h" -#include "log.h" -#include "memdebug.h" - -static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) -{ - time_t dt; - int day,hour; - char statm_fname[128]; - FILE *f; - unsigned long vmsize = 0, vmrss = 0; - unsigned long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; - - sprintf(statm_fname, "/proc/%i/statm", getpid()); - f = fopen(statm_fname, "r"); - if (f) { - fscanf(f, "%lu %lu", &vmsize, &vmrss); - fclose(f); - } - - time(&dt); - dt -= triton_stat.start_time; - day = dt / (60 * 60 * 24); - dt %= 60 * 60 * 24; - hour = dt / (60 * 60); - dt %= 60 * 60; - - cli_sendv(client, "uptime: %i.%02i:%02i:%02i\r\n", day, hour, dt / 60, dt % 60); - cli_sendv(client, "cpu: %i%%\r\n", triton_stat.cpu); - cli_sendv(client, "mem(rss/virt): %lu/%lu kB\r\n", vmrss * page_size_kb, vmsize * page_size_kb); - cli_send(client, "core:\r\n"); - cli_sendv(client, " mempool_allocated: %u\r\n", triton_stat.mempool_allocated); - cli_sendv(client, " mempool_available: %u\r\n", triton_stat.mempool_available); - cli_sendv(client, " thread_count: %u\r\n", triton_stat.thread_count); - cli_sendv(client, " thread_active: %u\r\n", triton_stat.thread_active); - cli_sendv(client, " context_count: %u\r\n", triton_stat.context_count); - cli_sendv(client, " context_sleeping: %u\r\n", triton_stat.context_sleeping); - cli_sendv(client, " context_pending: %u\r\n", triton_stat.context_pending); - cli_sendv(client, " md_handler_count: %u\r\n", triton_stat.md_handler_count); - cli_sendv(client, " md_handler_pending: %u\r\n", triton_stat.md_handler_pending); - cli_sendv(client, " timer_count: %u\r\n", triton_stat.timer_count); - cli_sendv(client, " timer_pending: %u\r\n", triton_stat.timer_pending); - -//=========== - cli_send(client, "ppp:\r\n"); - cli_sendv(client, " staring: %u\r\n", ppp_stat.starting); - cli_sendv(client, " active: %u\r\n", ppp_stat.active); - cli_sendv(client, " finishing: %u\r\n", ppp_stat.finishing); - - return CLI_CMD_OK; -} - -static void show_stat_help(char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "show stat - shows various statistics information\r\n"); -} -//============================= - -static int exit_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) -{ - return CLI_CMD_EXIT; -} - -static void exit_help(char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "exit - exit cli\r\n"); -} - -//============================= - -static void ppp_terminate_soft(struct ppp_t *ppp) -{ - ppp_terminate(ppp, TERM_NAS_REQUEST, 0); -} - -static void ppp_terminate_hard(struct ppp_t *ppp) -{ - ppp_terminate(ppp, TERM_NAS_REQUEST, 1); -} - -static int terminate_exec1(char * const *f, int f_cnt, void *cli) -{ - struct ppp_t *ppp; - int hard = 0; - pcre *re; - const char *pcre_err; - int pcre_offset; - - if (f_cnt == 5) { - if (!strcmp(f[4], "hard")) - hard = 1; - else if (strcmp(f[4], "soft")) - return CLI_CMD_SYNTAX; - } else if (f_cnt != 4) - return CLI_CMD_SYNTAX; - - re = pcre_compile2(f[3], 0, NULL, &pcre_err, &pcre_offset, NULL); - if (!re) { - cli_sendv(cli, "match: %s at %i\r\n", pcre_err, pcre_offset); - return CLI_CMD_OK; - } - - pthread_rwlock_rdlock(&ppp_lock); - list_for_each_entry(ppp, &ppp_list, entry) { - if (pcre_exec(re, NULL, ppp->username, strlen(ppp->username), 0, 0, NULL, 0) < 0) - continue; - if (hard) - triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_hard, ppp); - else - triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_soft, ppp); - } - pthread_rwlock_unlock(&ppp_lock); - - pcre_free(re); - - return CLI_CMD_OK; -} - -static int terminate_exec2(int key, char * const *f, int f_cnt, void *cli) -{ - struct ppp_t *ppp; - int hard = 0; - in_addr_t ipaddr = 0; - - if (f_cnt == 4) { - if (!strcmp(f[3], "hard")) - hard = 1; - else if (strcmp(f[3], "soft")) - return CLI_CMD_SYNTAX; - } else if (f_cnt != 3) - return CLI_CMD_SYNTAX; - - if (key == 1) - ipaddr = inet_addr(f[2]); - - pthread_rwlock_rdlock(&ppp_lock); - list_for_each_entry(ppp, &ppp_list, entry) { - switch (key) { - case 0: - if (strcmp(ppp->username, f[2])) - continue; - break; - case 1: - if (ppp->peer_ipaddr != ipaddr) - continue; - break; - case 2: - if (strcmp(ppp->ctrl->calling_station_id, f[2])) - continue; - break; - case 3: - if (strcmp(ppp->sessionid, f[2])) - continue; - break; - case 4: - if (strcmp(ppp->ifname, f[2])) - continue; - break; - } - if (hard) - triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_hard, ppp); - else - triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_soft, ppp); - break; - } - pthread_rwlock_unlock(&ppp_lock); - - return CLI_CMD_OK; -} - -static int terminate_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) -{ - struct ppp_t *ppp; - int hard = 0; - - if (fields_cnt == 1) - return CLI_CMD_SYNTAX; - - if (!strcmp(fields[1], "match") && fields_cnt > 3 && !strcmp(fields[2], "username")) - return terminate_exec1(fields, fields_cnt, client); - else if (!strcmp(fields[1], "username")) - return terminate_exec2(0, fields, fields_cnt, client); - else if (!strcmp(fields[1], "ip")) - return terminate_exec2(1, fields, fields_cnt, client); - else if (!strcmp(fields[1], "csid")) - return terminate_exec2(2, fields, fields_cnt, client); - else if (!strcmp(fields[1], "sid")) - return terminate_exec2(3, fields, fields_cnt, client); - else if (!strcmp(fields[1], "if")) - return terminate_exec2(4, fields, fields_cnt, client); - else if (strcmp(fields[1], "all")) - return CLI_CMD_SYNTAX; - - if (fields_cnt == 3) { - if (!strcmp(fields[2], "hard")) - hard = 1; - else if (strcmp(fields[2], "soft")) - return CLI_CMD_SYNTAX; - } else if (fields_cnt != 2) - return CLI_CMD_SYNTAX; - - pthread_rwlock_rdlock(&ppp_lock); - list_for_each_entry(ppp, &ppp_list, entry) { - if (hard) - triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_hard, ppp); - else - triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_soft, ppp); - } - pthread_rwlock_unlock(&ppp_lock); - - return CLI_CMD_OK; -} - -static void terminate_help(char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "terminate if [soft|hard]- terminate session by interface name\r\n"); - cli_send(client, "\t[match] username [soft|hard]- terminate session by username\r\n"); - cli_send(client, "\tip [soft|hard]- terminate session by ip address\r\n"); - cli_send(client, "\tcsid [soft|hard]- terminate session by calling station id\r\n"); - cli_send(client, "\tsid [soft|hard]- terminate session by session id\r\n"); - cli_send(client, "\tall [soft|hard]- terminate all sessions\r\n"); -} - -//============================= - -static void shutdown_help(char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "shutdown [soft|hard|cancel]- shutdown daemon\r\n"); - cli_send(client, "\t\tdefault action - send termination signals to all clients and wait everybody disconnects\r\n"); - cli_send(client, "\t\tsoft - wait until all clients disconnects, don't accept new connections\r\n"); - cli_send(client, "\t\thard - shutdown now, don't wait anything\r\n"); - cli_send(client, "\t\tcancel - cancel 'shutdown soft' and return to normal operation\r\n"); -} - -static void ppp_terminate_soft2(struct ppp_t *ppp) -{ - ppp_terminate(ppp, TERM_NAS_REBOOT, 0); -} - -static void ppp_terminate_hard2(struct ppp_t *ppp) -{ - ppp_terminate(ppp, TERM_NAS_REBOOT, 1); -} - -static int shutdown_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - int hard = 0; - struct ppp_t *ppp; - - if (f_cnt == 2) { - if (!strcmp(f[1], "soft")) { - ppp_shutdown_soft(); - return CLI_CMD_OK; - } else if (!strcmp(f[1], "hard")) - hard = 1; - else if (!strcmp(f[1], "cancel")) { - ppp_shutdown = 0; - return CLI_CMD_OK; - } else - return CLI_CMD_SYNTAX; - } - - ppp_shutdown_soft(); - - pthread_rwlock_rdlock(&ppp_lock); - list_for_each_entry(ppp, &ppp_list, entry) { - if (hard) - triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_hard2, ppp); - else - triton_context_call(ppp->ctrl->ctx, (triton_event_func)ppp_terminate_soft2, ppp); - } - pthread_rwlock_unlock(&ppp_lock); - - return CLI_CMD_OK; -} - -//========================== -static int conf_reload_res; -static struct triton_context_t *conf_reload_ctx; -static void conf_reload_notify(int r) -{ - if (!r) - triton_event_fire(EV_CONFIG_RELOAD, NULL); - conf_reload_res = r; - triton_context_wakeup(conf_reload_ctx); -} -static int reload_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - if (f_cnt == 1) { - conf_reload_ctx = triton_context_self(); - triton_conf_reload(conf_reload_notify); - triton_context_schedule(); - if (conf_reload_res) - cli_send(cli, "failed\r\n"); - return CLI_CMD_OK; - } else - return CLI_CMD_SYNTAX; -} - -static void reload_help(char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "reload - reload config file\r\n"); -} - -static void __init init(void) -{ - cli_register_simple_cmd2(show_stat_exec, show_stat_help, 2, "show", "stat"); - cli_register_simple_cmd2(terminate_exec, terminate_help, 1, "terminate"); - cli_register_simple_cmd2(reload_exec, reload_help, 1, "reload"); - cli_register_simple_cmd2(shutdown_exec, shutdown_help, 1, "shutdown"); - cli_register_simple_cmd2(exit_exec, exit_help, 1, "exit"); -} - diff --git a/accel-pptpd/cli/tcp.c b/accel-pptpd/cli/tcp.c deleted file mode 100644 index 260225f..0000000 --- a/accel-pptpd/cli/tcp.c +++ /dev/null @@ -1,371 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "triton.h" -#include "log.h" -#include "list.h" -#include "memdebug.h" - -#include "cli_p.h" - -#define RECV_BUF_SIZE 1024 - -struct tcp_client_t -{ - struct cli_client_t cli_client; - struct list_head entry; - struct triton_md_handler_t hnd; - struct list_head xmit_queue; - struct buffer_t *xmit_buf; - uint8_t *cmdline; - int xmit_pos; - int recv_pos; - int auth:1; - int disconnect:1; -}; - -struct buffer_t -{ - struct list_head entry; - int size; - uint8_t buf[0]; -}; - -static struct triton_context_t serv_ctx; -static struct triton_md_handler_t serv_hnd; -static LIST_HEAD(clients); - -static uint8_t *temp_buf; - -static void disconnect(struct tcp_client_t *cln) -{ - struct buffer_t *b; - - log_debug("cli: disconnect\n"); - - list_del(&cln->entry); - - triton_md_unregister_handler(&cln->hnd); - close(cln->hnd.fd); - - if (cln->xmit_buf) - _free(cln->xmit_buf); - - while (!list_empty(&cln->xmit_queue)) { - b = list_entry(cln->xmit_queue.next, typeof(*b), entry); - list_del(&b->entry); - _free(b); - } - - _free(cln->cmdline); - _free(cln); -} - -static void cli_client_disconnect(struct cli_client_t *tcln) -{ - struct tcp_client_t *cln = container_of(tcln, typeof(*cln), cli_client); - cln->disconnect = 1; -} - -static void queue_buffer(struct tcp_client_t *cln, struct buffer_t *b) -{ - if (cln->xmit_buf) - list_add_tail(&b->entry, &cln->xmit_queue); - else - cln->xmit_buf = b; -} - -static int cli_client_send(struct cli_client_t *tcln, const void *_buf, int size) -{ - struct tcp_client_t *cln = container_of(tcln, typeof(*cln), cli_client); - int n, k; - struct buffer_t *b; - const uint8_t *buf = (const uint8_t *)_buf; - - if (cln->disconnect) - return -1; - - if (!list_empty(&cln->xmit_queue)) { - b = _malloc(sizeof(*b) + size); - b->size = size; - memcpy(b->buf, buf, size); - queue_buffer(cln, b); - return 0; - } - - for (n = 0; n < size; n += k) { - k = write(cln->hnd.fd, buf + n, size - n); - if (k < 0) { - if (errno == EAGAIN) { - b = _malloc(sizeof(*b) + size - n); - b->size = size - n; - memcpy(b->buf, buf, size - n); - queue_buffer(cln, b); - - triton_md_enable_handler(&cln->hnd, MD_MODE_WRITE); - break; - } - if (errno != EPIPE) - log_error("cli: write: %s\n", strerror(errno)); - //disconnect(cln); - cln->disconnect = 1; - return -1; - } - } - return 0; -} - -static int cli_client_sendv(struct cli_client_t *tcln, const char *fmt, va_list ap) -{ - struct tcp_client_t *cln = container_of(tcln, typeof(*cln), cli_client); - int r = vsnprintf((char *)temp_buf, RECV_BUF_SIZE, fmt, ap); - - if (r >= RECV_BUF_SIZE) { - strcpy((char *)temp_buf + RECV_BUF_SIZE - 5, "...\n"); - r = RECV_BUF_SIZE; - } - - return cli_client_send(tcln, temp_buf, r); -} - -static int cln_read(struct triton_md_handler_t *h) -{ - struct tcp_client_t *cln = container_of(h, typeof(*cln), hnd); - int n; - char *d; - - while (1) { - n = read(h->fd, cln->cmdline + cln->recv_pos, RECV_BUF_SIZE - cln->recv_pos); - if (n == 0) - break; - if (n < 0) { - if (errno != EAGAIN) - log_error("cli: read: %s\n", strerror(errno)); - return 0; - } - - cln->recv_pos += n; - - while (cln->recv_pos) { - d = strchr((char *)cln->cmdline, '\n'); - if (!d) { - if (cln->recv_pos == RECV_BUF_SIZE) { - log_warn("cli: tcp: recv buffer overflow\n"); - goto drop; - } - break; - } - - *d = 0; - - if (!cln->auth) { - if (strcmp((char *)cln->cmdline, conf_cli_passwd)) - goto drop; - cln->auth = 1; - } else - cli_process_cmd(&cln->cli_client); - - if (cln->disconnect) - goto drop; - - cln->recv_pos -= (uint8_t *)d + 1 - cln->cmdline; - memmove(cln->cmdline, d + 1, cln->recv_pos); - } - } - -drop: - disconnect(cln); - return -1; -} - -static int cln_write(struct triton_md_handler_t *h) -{ - struct tcp_client_t *cln = container_of(h, typeof(*cln), hnd); - int k; - - while (1) { - for (; cln->xmit_pos < cln->xmit_buf->size; cln->xmit_pos += k) { - k = write(cln->hnd.fd, cln->xmit_buf->buf + cln->xmit_pos, cln->xmit_buf->size - cln->xmit_pos); - if (k < 0) { - if (errno == EAGAIN) - return 0; - if (errno != EPIPE) - log_error("cli: tcp: write: %s\n", strerror(errno)); - disconnect(cln); - return -1; - } - } - - _free(cln->xmit_buf); - cln->xmit_pos = 0; - - if (list_empty(&cln->xmit_queue)) - break; - - cln->xmit_buf = list_entry(cln->xmit_queue.next, typeof(*cln->xmit_buf), entry); - list_del(&cln->xmit_buf->entry); - } - - triton_md_disable_handler(&cln->hnd, MD_MODE_WRITE); - - return 0; -} - -static int serv_read(struct triton_md_handler_t *h) -{ - struct sockaddr_in addr; - socklen_t size = sizeof(addr); - int sock; - struct tcp_client_t *conn; - - while(1) { - sock = accept(h->fd, (struct sockaddr *)&addr, &size); - if (sock < 0) { - if (errno == EAGAIN) - return 0; - log_error("cli: tcp: accept failed: %s\n", strerror(errno)); - continue; - } - - log_info2("cli: tcp: new connection from %s\n", inet_ntoa(addr.sin_addr)); - - if (fcntl(sock, F_SETFL, O_NONBLOCK)) { - log_error("cli: tcp: failed to set nonblocking mode: %s, closing connection...\n", strerror(errno)); - close(sock); - continue; - } - - conn = _malloc(sizeof(*conn)); - memset(conn, 0, sizeof(*conn)); - conn->hnd.fd = sock; - conn->hnd.read = cln_read; - conn->hnd.write = cln_write; - conn->cmdline = _malloc(RECV_BUF_SIZE); - INIT_LIST_HEAD(&conn->xmit_queue); - - conn->cli_client.cmdline = conn->cmdline; - conn->cli_client.send = cli_client_send; - conn->cli_client.sendv = cli_client_sendv; - conn->cli_client.disconnect = cli_client_disconnect; - - triton_md_register_handler(&serv_ctx, &conn->hnd); - triton_md_enable_handler(&conn->hnd,MD_MODE_READ); - - list_add_tail(&conn->entry, &clients); - - if (!conf_cli_passwd) - conn->auth = 1; - } - return 0; -} - -static void serv_close(struct triton_context_t *ctx) -{ - struct tcp_client_t *cln; - - while (!list_empty(&clients)) { - cln = list_entry(clients.next, typeof(*cln), entry); - disconnect(cln); - } - - triton_md_unregister_handler(&serv_hnd); - close(serv_hnd.fd); - triton_context_unregister(ctx); -} - -static struct triton_context_t serv_ctx = { - .close = serv_close, - .before_switch = log_switch, -}; - -static struct triton_md_handler_t serv_hnd = { - .read = serv_read, -}; - -static void start_server(const char *host, int port) -{ - struct sockaddr_in addr; - - serv_hnd.fd = socket(PF_INET, SOCK_STREAM, 0); - if (serv_hnd.fd < 0) { - log_emerg("cli: tcp: failed to create server socket: %s\n", strerror(errno)); - return; - } - - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - if (host) - addr.sin_addr.s_addr = inet_addr(host); - else - addr.sin_addr.s_addr = htonl(INADDR_ANY); - - setsockopt(serv_hnd.fd, SOL_SOCKET, SO_REUSEADDR, &serv_hnd.fd, 4); - if (bind (serv_hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { - log_emerg("cli: tcp: failed to bind socket: %s\n", strerror(errno)); - close(serv_hnd.fd); - return; - } - - if (listen (serv_hnd.fd, 1) < 0) { - log_emerg("cli: tcp: failed to listen socket: %s\n", strerror(errno)); - close(serv_hnd.fd); - return; - } - - if (fcntl(serv_hnd.fd, F_SETFL, O_NONBLOCK)) { - log_emerg("cli: tcp: failed to set nonblocking mode: %s\n", strerror(errno)); - close(serv_hnd.fd); - return; - } - - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = inet_addr(host); - - triton_context_register(&serv_ctx, NULL); - triton_context_set_priority(&serv_ctx, 1); - triton_md_register_handler(&serv_ctx, &serv_hnd); - triton_md_enable_handler(&serv_hnd, MD_MODE_READ); - triton_context_wakeup(&serv_ctx); -} - -static void __init init(void) -{ - const char *opt; - char *host, *d; - int port; - - opt = conf_get_opt("cli", "tcp"); - if (!opt) - return; - - host = strdup(opt); - d = strstr(host, ":"); - if (!d) - goto err_fmt; - - *d = 0; - port = atoi(d + 1); - if (port <= 0) - goto err_fmt; - - temp_buf = malloc(RECV_BUF_SIZE); - - start_server(host, port); - - return; -err_fmt: - log_emerg("cli: tcp: invalid format\n"); - free(host); -} - diff --git a/accel-pptpd/cli/telnet.c b/accel-pptpd/cli/telnet.c deleted file mode 100644 index 0ea19fb..0000000 --- a/accel-pptpd/cli/telnet.c +++ /dev/null @@ -1,757 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "triton.h" -#include "log.h" -#include "ppp.h" -#include "list.h" -#include "memdebug.h" - -#include "cli_p.h" - -#define RECV_BUF_SIZE 1024 - -#define MSG_AUTH_FAILED "\r\nAuthentication failed\r\n" -#define MSG_SHUTDOWN_IN_PROGRESS "note: 'shutdown soft' is in progress...\r\n" - -#define ESC_LEFT "[D" -#define ESC_RIGHT "[C" -#define ESC_UP "[A" -#define ESC_DOWN "[B" - -struct telnet_client_t -{ - struct cli_client_t cli_client; - struct list_head entry; - struct triton_md_handler_t hnd; - struct list_head xmit_queue; - struct buffer_t *xmit_buf; - int xmit_pos; - struct list_head history; - struct list_head *history_pos; - uint8_t *cmdline; - int cmdline_pos; - int cmdline_pos2; - int cmdline_len; - int auth:1; - int echo:1; - int telcmd:1; - int esc:1; - int disconnect:1; -}; - -struct buffer_t -{ - struct list_head entry; - int size; - struct buffer_t *p_buf; - uint8_t buf[0]; -}; - -static struct triton_context_t serv_ctx; -static struct triton_md_handler_t serv_hnd; -static LIST_HEAD(clients); - -static uint8_t *recv_buf; -static uint8_t *temp_buf; - -static int conf_history_len = 100; -static const char *conf_history_file = "/var/run/accel-pptp/history"; -static LIST_HEAD(history); -static int history_len; -static pthread_mutex_t history_lock = PTHREAD_MUTEX_INITIALIZER; - -static void disconnect(struct telnet_client_t *cln) -{ - struct buffer_t *b, *b2; - - log_debug("cli: disconnect\n"); - - triton_stop_collect_cpu_usage(); - - list_del(&cln->entry); - - triton_md_unregister_handler(&cln->hnd); - close(cln->hnd.fd); - - if (cln->xmit_buf) - _free(cln->xmit_buf); - - while (!list_empty(&cln->xmit_queue)) { - b = list_entry(cln->xmit_queue.next, typeof(*b), entry); - list_del(&b->entry); - _free(b); - } - - pthread_mutex_lock(&history_lock); - while (!list_empty(&cln->history)) { - b = list_entry(cln->history.prev, typeof(*b), entry); - list_del(&b->entry); - if (!b->p_buf) { - if (history_len == conf_history_len) { - b2 = list_entry(history.next, typeof(*b2), entry); - list_del(&b2->entry); - _free(b2); - } else - history_len++; - list_add_tail(&b->entry, &history); - } else - _free(b); - } - pthread_mutex_unlock(&history_lock); - - _free(cln->cmdline); - _free(cln); -} - -static void cli_client_disconnect(struct cli_client_t *tcln) -{ - struct telnet_client_t *cln = container_of(tcln, typeof(*cln), cli_client); - cln->disconnect = 1; -} - -static void queue_buffer(struct telnet_client_t *cln, struct buffer_t *b) -{ - if (cln->xmit_buf) - list_add_tail(&b->entry, &cln->xmit_queue); - else - cln->xmit_buf = b; -} - -static int telnet_send(struct telnet_client_t *cln, const void *_buf, int size) -{ - int n, k; - struct buffer_t *b; - const uint8_t *buf = (const uint8_t *)_buf; - - if (cln->disconnect) - return -1; - - if (!list_empty(&cln->xmit_queue)) { - b = _malloc(sizeof(*b) + size); - b->size = size; - memcpy(b->buf, buf, size); - queue_buffer(cln, b); - return 0; - } - - for (n = 0; n < size; n += k) { - k = write(cln->hnd.fd, buf + n, size - n); - if (k < 0) { - if (errno == EAGAIN) { - b = _malloc(sizeof(*b) + size - n); - b->size = size - n; - memcpy(b->buf, buf, size - n); - queue_buffer(cln, b); - - triton_md_enable_handler(&cln->hnd, MD_MODE_WRITE); - break; - } - if (errno != EPIPE) - log_error("cli: write: %s\n", strerror(errno)); - //disconnect(cln); - cln->disconnect = 1; - return -1; - } - } - return 0; -} - -static int cli_client_send(struct cli_client_t *tcln, const void *buf, int size) -{ - struct telnet_client_t *cln = container_of(tcln, typeof(*cln), cli_client); - return telnet_send(cln, buf, size); -} - -static int cli_client_sendv(struct cli_client_t *tcln, const char *fmt, va_list ap) -{ - struct telnet_client_t *cln = container_of(tcln, typeof(*cln), cli_client); - int r = vsnprintf((char *)temp_buf, RECV_BUF_SIZE, fmt, ap); - - if (r >= RECV_BUF_SIZE) { - strcpy((char *)temp_buf + RECV_BUF_SIZE - 6, "...\r\n"); - r = RECV_BUF_SIZE; - } - - return telnet_send(cln, temp_buf, r); -} - -static int send_banner(struct telnet_client_t *cln) -{ - if (telnet_send(cln, "accel-pptp version " ACCEL_PPTP_VERSION "\r\n", sizeof("accel-pptp version " ACCEL_PPTP_VERSION "\r\n"))) - return -1; - return 0; -} - -static int send_config(struct telnet_client_t *cln) -{ - uint8_t buf[] = {IAC, WILL, TELOPT_ECHO, IAC, WILL, TELOPT_SGA, IAC, DONT, TELOPT_LINEMODE}; - return telnet_send(cln, buf, sizeof(buf)); -} - -static int send_password_request(struct telnet_client_t *cln) -{ - uint8_t buf0[] = {IAC, WILL, TELOPT_ECHO}; - uint8_t buf1[] = "Password: "; - - if (telnet_send(cln, buf0, sizeof(buf0))) - return -1; - - if (telnet_send(cln, buf1, sizeof(buf1))) - return -1; - - return 0; -} - -static int send_prompt(struct telnet_client_t *cln) -{ - sprintf((char *)temp_buf, "%s%s# ", conf_cli_prompt, ppp_shutdown ? "(shutdown)" : ""); - return telnet_send(cln, temp_buf, strlen((char *)temp_buf)); -} - -/*static void print_buf(const uint8_t *buf, int size) -{ - int i; - - for (i = 0; i < size; i++) - log_debug("%x ", buf[i]); - log_debug("\n"); -}*/ - -static int send_cmdline_tail(struct telnet_client_t *cln, int corr) -{ - if (telnet_send(cln, cln->cmdline + cln->cmdline_pos, cln->cmdline_len - cln->cmdline_pos)) - return -1; - - memset(temp_buf, '\b', cln->cmdline_len - cln->cmdline_pos - corr); - - if (telnet_send(cln, temp_buf, cln->cmdline_len - cln->cmdline_pos - corr)) - return -1; - - return 0; -} - -static int load_history(struct telnet_client_t *cln) -{ - struct buffer_t *b = list_entry(cln->history_pos, typeof(*b), entry); - if (b->size < cln->cmdline_len) { - memset(temp_buf, '\b', cln->cmdline_len - b->size); - memset(temp_buf + cln->cmdline_len - b->size, ' ', cln->cmdline_len - b->size); - if (telnet_send(cln, temp_buf, (cln->cmdline_len - b->size) * 2)) - return -1; - } - if (telnet_send(cln, "\r", 1)) - return -1; - if (send_prompt(cln)) - return -1; - memcpy(cln->cmdline, b->p_buf ? b->p_buf->buf : b->buf, b->size); - cln->cmdline_pos = b->size; - cln->cmdline_len = b->size; - if (telnet_send(cln, b->p_buf ? b->p_buf->buf : b->buf, b->size)) - return -1; - - return 0; -} - -static int telnet_input_char(struct telnet_client_t *cln, uint8_t c) -{ - uint8_t buf[] = {IAC, DONT, 0}; - struct buffer_t *b; - - if (c == '\n') - return 0; - - if (c == '\r') { - cln->cmdline[cln->cmdline_len] = 0; - - if (cln->echo) { - if (telnet_send(cln, "\r\n", 2)) - return -1; - } - - if (!cln->auth) { - if (strcmp((char *)cln->cmdline, conf_cli_passwd)) { - if (telnet_send(cln, MSG_AUTH_FAILED, sizeof(MSG_AUTH_FAILED))) - return -1; - cln->disconnect = 1; - return -1; - } - cln->auth = 1; - if (ppp_shutdown) { - if (telnet_send(cln, MSG_SHUTDOWN_IN_PROGRESS, sizeof(MSG_SHUTDOWN_IN_PROGRESS))) - return -1; - } - } else if (cln->cmdline_len) { - b = _malloc(sizeof(*b) + cln->cmdline_len); - b->p_buf = NULL; - memcpy(b->buf, cln->cmdline, cln->cmdline_len); - b->size = cln->cmdline_len; - list_add(&b->entry, cln->history.next); - cln->history_pos = cln->history.next; - - if (cli_process_cmd(&cln->cli_client)) - return -1; - } - - cln->cmdline_pos = 0; - cln->cmdline_len = 0; - - return send_prompt(cln); - } - - if (cln->telcmd) { - if (cln->cmdline_pos2 == RECV_BUF_SIZE - 1) { - log_error("cli: buffer overflow, dropping connection ...\n"); - disconnect(cln); - return -1; - } - - cln->cmdline[cln->cmdline_pos2] = c; - cln->cmdline_pos2++; - - if (cln->cmdline[cln->cmdline_len] >= WILL && cln->cmdline[cln->cmdline_len] <= DONT && cln->cmdline_pos2 - cln->cmdline_len != 2) - return 0; - - switch (cln->cmdline[cln->cmdline_len]) { - case WILL: - case WONT: - buf[2] = c; - if (telnet_send(cln, buf, 3)) - return -1; - break; - case DO: - if (c == TELOPT_ECHO) - cln->echo = 1; - break; - case SB: - if (c != SE) - return 0; - } - - cln->telcmd = 0; - } else if (cln->esc) { - if (cln->cmdline_pos2 == RECV_BUF_SIZE - 1) { - log_error("cli: buffer overflow, dropping connection ...\n"); - disconnect(cln); - return -1; - } - - cln->cmdline[cln->cmdline_pos2] = c; - cln->cmdline_pos2++; - - if (cln->cmdline_pos2 - cln->cmdline_len != 2) - return 0; - - cln->esc = 0; - - if (cln->auth) { - if (!memcmp(cln->cmdline + cln->cmdline_len, ESC_LEFT, 2)) { - if (cln->cmdline_pos) { - if (telnet_send(cln, "\b", 1)) - return -1; - cln->cmdline_pos--; - } - } else if (!memcmp(cln->cmdline + cln->cmdline_len, ESC_RIGHT, 2)) { - if (cln->cmdline_pos < cln->cmdline_len) { - if (send_cmdline_tail(cln, 1)) - return -1; - cln->cmdline_pos++; - } - } else if (!memcmp(cln->cmdline + cln->cmdline_len, ESC_UP, 2)) { - if (cln->history_pos == cln->history.next) { - b = list_entry(cln->history_pos, typeof(*b), entry); - memcpy(b->buf, cln->cmdline, cln->cmdline_len); - b->size = cln->cmdline_len; - } - cln->history_pos = cln->history_pos->next; - if (cln->history_pos == &cln->history) { - cln->history_pos = cln->history_pos->prev; - return 0; - } - if (load_history(cln)) - return -1; - } else if (!memcmp(cln->cmdline + cln->cmdline_len, ESC_DOWN, 2)) { - cln->history_pos = cln->history_pos->prev; - if (cln->history_pos == &cln->history) { - cln->history_pos = cln->history_pos->next; - return 0; - } - if (load_history(cln)) - return -1; - } - } - } else { - switch (c) { - case 0xff: - cln->cmdline_pos2 = cln->cmdline_len; - cln->telcmd = 1; - return 0; - case 0x1b: - cln->cmdline_pos2 = cln->cmdline_len; - cln->esc = 1; - return 0; - case 0x7f: - if (cln->cmdline_pos) { - if (cln->cmdline_pos < cln->cmdline_len) { - memmove(cln->cmdline + cln->cmdline_pos - 1, cln->cmdline + cln->cmdline_pos, cln->cmdline_len - cln->cmdline_pos); - - cln->cmdline[cln->cmdline_len - 1] = ' '; - - if (telnet_send(cln, "\b", 1)) - return -1; - - cln->cmdline_pos--; - - if (send_cmdline_tail(cln, 0)) - return -1; - } else { - buf[0] = '\b'; - buf[1] = ' '; - buf[2] = '\b'; - if (telnet_send(cln, buf, 3)) - return -1; - cln->cmdline_pos--; - } - - cln->cmdline_len--; - } - return 0; - case 3: - cln->disconnect = 1; - return -1; - } - - if (isprint(c)) { - if (cln->cmdline_len == RECV_BUF_SIZE - 1) - return 0; - - if (cln->cmdline_pos < cln->cmdline_len) - memmove(cln->cmdline + cln->cmdline_pos + 1, cln->cmdline + cln->cmdline_pos, cln->cmdline_len - cln->cmdline_pos); - cln->cmdline[cln->cmdline_pos] = c; - cln->cmdline_pos++; - cln->cmdline_len++; - - if (cln->echo) { - if (!cln->auth) { - if (telnet_send(cln, "*", 1)) - return -1; - } else { - if (telnet_send(cln, &c, 1)) - return -1; - } - } - - if (cln->cmdline_pos < cln->cmdline_len) { - if (send_cmdline_tail(cln, 0)) - return -1; - } - } - } - - return 0; -} - -static int cln_read(struct triton_md_handler_t *h) -{ - struct telnet_client_t *cln = container_of(h, typeof(*cln), hnd); - int i, n; - - while (1) { - n = read(h->fd, recv_buf, RECV_BUF_SIZE); - if (n == 0) { - disconnect(cln); - return -1; - } - if (n < 0) { - if (errno != EAGAIN) - log_error("cli: telnet: read: %s\n", strerror(errno)); - return 0; - } - /*log_debug("cli: read(%i): ", n); - print_buf(cln->recv_buf + cln->recv_pos, n);*/ - for (i = 0; i < n; i++) { - if (telnet_input_char(cln, recv_buf[i])) - break; - } - if (cln->disconnect) { - disconnect(cln); - return -1; - } - } - - return 0; -} - -static int cln_write(struct triton_md_handler_t *h) -{ - struct telnet_client_t *cln = container_of(h, typeof(*cln), hnd); - int k; - - while (1) { - for (; cln->xmit_pos < cln->xmit_buf->size; cln->xmit_pos += k) { - k = write(cln->hnd.fd, cln->xmit_buf->buf + cln->xmit_pos, cln->xmit_buf->size - cln->xmit_pos); - if (k < 0) { - if (errno == EAGAIN) - return 0; - if (errno != EPIPE) - log_error("cli: telnet: write: %s\n", strerror(errno)); - disconnect(cln); - return -1; - } - } - - _free(cln->xmit_buf); - cln->xmit_pos = 0; - - if (list_empty(&cln->xmit_queue)) - break; - - cln->xmit_buf = list_entry(cln->xmit_queue.next, typeof(*cln->xmit_buf), entry); - list_del(&cln->xmit_buf->entry); - } - - triton_md_disable_handler(&cln->hnd, MD_MODE_WRITE); - - return 0; -} - -static int serv_read(struct triton_md_handler_t *h) -{ - struct sockaddr_in addr; - socklen_t size = sizeof(addr); - int sock; - struct telnet_client_t *conn; - struct buffer_t *b, *b2; - - while(1) { - sock = accept(h->fd, (struct sockaddr *)&addr, &size); - if (sock < 0) { - if (errno == EAGAIN) - return 0; - log_error("cli: telnet: accept failed: %s\n", strerror(errno)); - continue; - } - - log_info2("cli: telnet: new connection from %s\n", inet_ntoa(addr.sin_addr)); - - if (fcntl(sock, F_SETFL, O_NONBLOCK)) { - log_error("cli: telnet: failed to set nonblocking mode: %s, closing connection...\n", strerror(errno)); - close(sock); - continue; - } - - conn = _malloc(sizeof(*conn)); - memset(conn, 0, sizeof(*conn)); - conn->hnd.fd = sock; - conn->hnd.read = cln_read; - conn->hnd.write = cln_write; - conn->cmdline = _malloc(RECV_BUF_SIZE); - INIT_LIST_HEAD(&conn->xmit_queue); - INIT_LIST_HEAD(&conn->history); - - b = _malloc(sizeof(*b) + RECV_BUF_SIZE); - b->p_buf = b; - b->size = 0; - list_add_tail(&b->entry, &conn->history); - - pthread_mutex_lock(&history_lock); - list_for_each_entry(b, &history, entry) { - b2 = _malloc(sizeof(*b)); - b2->p_buf = b; - b2->size = b->size; - list_add(&b2->entry, conn->history.next); - } - pthread_mutex_unlock(&history_lock); - - conn->history_pos = conn->history.next; - - conn->cli_client.cmdline = conn->cmdline; - conn->cli_client.send = cli_client_send; - conn->cli_client.sendv = cli_client_sendv; - conn->cli_client.disconnect = cli_client_disconnect; - - triton_md_register_handler(&serv_ctx, &conn->hnd); - triton_md_enable_handler(&conn->hnd,MD_MODE_READ); - - list_add_tail(&conn->entry, &clients); - - if (send_banner(conn)) - continue; - - if (send_config(conn)) - continue; - - if (conf_cli_passwd) - send_password_request(conn); - else { - conn->auth = 1; - if (ppp_shutdown) { - if (telnet_send(conn, MSG_SHUTDOWN_IN_PROGRESS, sizeof(MSG_SHUTDOWN_IN_PROGRESS))) - continue; - } - send_prompt(conn); - } - triton_collect_cpu_usage(); - } - return 0; -} -static void serv_close(struct triton_context_t *ctx) -{ - struct telnet_client_t *cln; - - while (!list_empty(&clients)) { - cln = list_entry(clients.next, typeof(*cln), entry); - disconnect(cln); - } - - triton_md_unregister_handler(&serv_hnd); - close(serv_hnd.fd); - triton_context_unregister(ctx); -} - -static struct triton_context_t serv_ctx = { - .close = serv_close, - .before_switch = log_switch, -}; - -static struct triton_md_handler_t serv_hnd = { - .read = serv_read, -}; - -static void start_server(const char *host, int port) -{ - struct sockaddr_in addr; - - serv_hnd.fd = socket(PF_INET, SOCK_STREAM, 0); - if (serv_hnd.fd < 0) { - log_emerg("cli: telnet: failed to create server socket: %s\n", strerror(errno)); - return; - } - - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - if (host) - addr.sin_addr.s_addr = inet_addr(host); - else - addr.sin_addr.s_addr = htonl(INADDR_ANY); - - setsockopt(serv_hnd.fd, SOL_SOCKET, SO_REUSEADDR, &serv_hnd.fd, 4); - if (bind (serv_hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { - log_emerg("cli: telnet: failed to bind socket: %s\n", strerror(errno)); - close(serv_hnd.fd); - return; - } - - if (listen (serv_hnd.fd, 1) < 0) { - log_emerg("cli: telnet: failed to listen socket: %s\n", strerror(errno)); - close(serv_hnd.fd); - return; - } - - if (fcntl(serv_hnd.fd, F_SETFL, O_NONBLOCK)) { - log_emerg("cli: telnet: failed to set nonblocking mode: %s\n", strerror(errno)); - close(serv_hnd.fd); - return; - } - - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = inet_addr(host); - - triton_context_register(&serv_ctx, NULL); - triton_context_set_priority(&serv_ctx, 1); - triton_md_register_handler(&serv_ctx, &serv_hnd); - triton_md_enable_handler(&serv_hnd, MD_MODE_READ); - triton_context_wakeup(&serv_ctx); -} - -static void save_history_file(void) -{ - int fd; - struct buffer_t *b; - - fd = open(conf_history_file, O_WRONLY | O_TRUNC | O_CREAT, S_IREAD | S_IWRITE); - if (!fd) - return; - - list_for_each_entry(b, &history, entry) { - b->buf[b->size] = '\n'; - write(fd, b->buf, b->size + 1); - } - - close(fd); -} - -static void load_history_file(void) -{ - struct buffer_t *b; - FILE *f; - - f = fopen(conf_history_file, "r"); - if (!f) - return; - - while (fgets((char *)temp_buf, RECV_BUF_SIZE, f)) { - b = _malloc(sizeof(*b) + strlen((char *)temp_buf)); - b->p_buf = NULL; - b->size = strlen((char *)temp_buf) - 1; - memcpy(b->buf, temp_buf, b->size); - list_add_tail(&b->entry, &history); - } - - fclose(f); -} - -static void __init init(void) -{ - const char *opt; - char *host, *d; - int port; - - opt = conf_get_opt("cli", "telnet"); - if (!opt) - return; - - host = strdup(opt); - d = strstr(host, ":"); - if (!d) - goto err_fmt; - - *d = 0; - port = atoi(d + 1); - if (port <= 0) - goto err_fmt; - - opt = conf_get_opt("cli", "history-file"); - if (opt) - conf_history_file = _strdup(opt); - - recv_buf = malloc(RECV_BUF_SIZE); - temp_buf = malloc(RECV_BUF_SIZE); - - load_history_file(); - - start_server(host, port); - - atexit(save_history_file); - - return; -err_fmt: - log_emerg("cli: telnet: invalid format\n"); - free(host); -} - diff --git a/accel-pptpd/ctrl/CMakeLists.txt b/accel-pptpd/ctrl/CMakeLists.txt deleted file mode 100644 index 6b37bc4..0000000 --- a/accel-pptpd/ctrl/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -ADD_SUBDIRECTORY(pptp) -ADD_SUBDIRECTORY(pppoe) -ADD_SUBDIRECTORY(l2tp) diff --git a/accel-pptpd/ctrl/l2tp/CMakeLists.txt b/accel-pptpd/ctrl/l2tp/CMakeLists.txt deleted file mode 100644 index e0edd51..0000000 --- a/accel-pptpd/ctrl/l2tp/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) - -ADD_DEFINITIONS(-DDICTIONARY="${CMAKE_INSTALL_PREFIX}/share/accel-pptp/l2tp/dictionary") - -ADD_LIBRARY(l2tp SHARED - l2tp.c - dict.c - packet.c - # netlink.c -) -#TARGET_LINK_LIBRARIES(l2tp nl nl-genl) - -INSTALL(TARGETS l2tp LIBRARY DESTINATION lib/accel-pptp) - -FILE(GLOB dict "${CMAKE_CURRENT_SOURCE_DIR}/dict/*") -INSTALL(FILES ${dict} DESTINATION share/accel-pptp/l2tp) - diff --git a/accel-pptpd/ctrl/l2tp/attr_defs.h b/accel-pptpd/ctrl/l2tp/attr_defs.h deleted file mode 100644 index e799157..0000000 --- a/accel-pptpd/ctrl/l2tp/attr_defs.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef __ATTR_DEFS_H -#define __ATTR_DEFS_H - -#define Message_Type 0 -#define Random_Vector 36 -#define Result_Code 1 -#define Protocol_Version 2 -#define Framing_Capabilities 3 -#define Bearer_Capabilities 4 -#define Tie_Breaker 5 -#define Firmware_Revision 6 -#define Host_Name 7 -#define Vendor_Name 8 -#define Assigned_Tunnel_ID 9 -#define Recv_Window_Size 10 -#define Challenge 11 -#define Challenge_Response 13 -#define Cause_Code 12 -#define Assigned_Session_ID 14 -#define Call_Serial_Number 15 -#define Minimum_BPS 16 -#define Maximum_BPS 17 -#define Bearer_Type 18 -#define Framing_Type 19 -#define Called_Number 21 -#define Calling_Number 22 -#define Sub_Address 23 -#define TX_Speed 24 -#define RX_Speed 38 -#define Physical_Channel_ID 25 -#define Private_Group_ID 37 -#define Sequencing_Required 39 -#define Init_Recv_LCP 26 -#define Last_Sent_LCP 27 -#define Last_Recv_LCP 28 -#define Proxy_Authen_Type 29 -#define Proxy_Authen_Name 30 -#define Proxy_Authen_Challenge 31 -#define Proxy_Authen_ID 32 -#define Proxy_Authen_Response 33 -#define Call_Errors 34 -#define ACCM 35 -#define Message_Type_Start_Ctrl_Conn_Request 1 -#define Message_Type_Start_Ctrl_Conn_Reply 2 -#define Message_Type_Start_Ctrl_Conn_Connected 3 -#define Message_Type_Stop_Ctrl_Conn_Notify 4 -#define Message_Type_Hello 6 -#define Message_Type_Outgoing_Call_Request 7 -#define Message_Type_Outgoing_Call_Reply 8 -#define Message_Type_Outgoing_Call_Connected 9 -#define Message_Type_Incoming_Call_Request 10 -#define Message_Type_Incoming_Call_Reply 11 -#define Message_Type_Incoming_Call_Connected 12 -#define Message_Type_Call_Disconnect_Notify 14 -#define Message_Type_WAN_Error_Notify 15 -#define Message_Type_Set_Link_Info 16 -#define Message_Digest 59 -#define Router_ID 60 -#define Assigned_Connection_ID 61 -#define Pseudowire_Capabilities 62 -#define Prefered_Language 72 -#define Local_Session_ID 63 -#define Remote_Session_ID 64 -#define Assigned_Cookie 65 -#define Remote_End_ID 66 -#define Pseudowire_Type 68 -#define L2_Specific_Sublayer 69 -#define Data_Sequencing 70 -#define TX_Connect_Speeed 74 -#define RX_Connect_Speeed 75 -#define Circuit_Status 71 - -#endif diff --git a/accel-pptpd/ctrl/l2tp/dict.c b/accel-pptpd/ctrl/l2tp/dict.c deleted file mode 100644 index c93ccd4..0000000 --- a/accel-pptpd/ctrl/l2tp/dict.c +++ /dev/null @@ -1,271 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "list.h" -#include "l2tp.h" -#include "log.h" -#include "triton.h" - -#include "memdebug.h" - -struct l2tp_dict_t -{ - struct list_head items; -}; - -static struct l2tp_dict_t *dict; - -#define BUF_SIZE 1024 -static char *path, *fname1, *buf; - -struct l2tp_dict_attr_t *l2tp_dict_find_attr_by_name(const char *name) -{ - struct l2tp_dict_attr_t *attr; - - list_for_each_entry(attr, &dict->items, entry) { - if (!strcmp(attr->name, name)) - return attr; - } - - return NULL; -} - -struct l2tp_dict_attr_t *l2tp_dict_find_attr_by_id(int id) -{ - struct l2tp_dict_attr_t *attr; - - list_for_each_entry(attr, &dict->items, entry) { - if (attr->id == id) - return attr; - } - - return NULL; -} - -struct l2tp_dict_value_t *l2tp_dict_find_value(struct l2tp_dict_attr_t *attr, l2tp_value_t val) -{ - struct l2tp_dict_value_t *v; - - list_for_each_entry(v, &attr->values, entry) { - switch (attr->type) { - case ATTR_TYPE_INT16: - if (v->val.int16 == val.int16) - return v; - break; - case ATTR_TYPE_INT32: - if (v->val.int32 == val.int32) - return v; - break; - } - } - - return NULL; -} - -static char *skip_word(char *ptr) -{ - for(; *ptr; ptr++) - if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') - break; - return ptr; -} - -static char *skip_space(char *ptr) -{ - for(; *ptr; ptr++) - if (*ptr != ' ' && *ptr != '\t') - break; - return ptr; -} - -static int split(char *buf, char **ptr) -{ - int i; - - for (i = 0; i < 6; i++) { - buf = skip_word(buf); - if (!*buf) - return i; - - *buf = 0; - - buf = skip_space(buf + 1); - if (!*buf) - return i; - - ptr[i] = buf; - } - - buf = skip_word(buf); - //if (*buf == '\n') - *buf = 0; - //else if (*buf) - // return -1; - - return i; -} - - -static int dict_load(const char *fname) -{ - FILE *f; - char *ptr[6], *endptr; - struct l2tp_dict_attr_t *attr; - struct l2tp_dict_value_t *value; - struct list_head *items; - int i, r, n = 0; - - f = fopen(fname, "r"); - if (!f) { - log_emerg("l2tp: open '%s': %s\n", fname, strerror(errno)); - return -1; - } - - items = &dict->items; - while (fgets(buf, BUF_SIZE, f)) { - n++; - if (buf[0] == '#' || buf[0] == '\n' || buf[0] == 0) - continue; - - r = split(buf, ptr); - - if (!strcmp(buf, "$INCLUDE")) { - if (r != 1) - goto out_syntax; - - for (i = strlen(path) - 1; i; i--) { - if (path[i] == '/') { - path[i + 1] = 0; - break; - } - } - - strcpy(fname1, path); - strcat(fname1, ptr[0]); - - if (dict_load(fname1)) - goto out_err; - } else if (!strcmp(buf, "ATTRIBUTE")) { - if (r < 3) - goto out_syntax; - - attr = malloc(sizeof(*attr)); - memset(attr, 0, sizeof(*attr)); - list_add_tail(&attr->entry, items); - INIT_LIST_HEAD(&attr->values); - - attr->name = strdup(ptr[0]); - attr->id = strtol(ptr[1], &endptr, 10); - if (*endptr != 0) - goto out_syntax; - - if (!strcmp(ptr[2], "none")) - attr->type = ATTR_TYPE_NONE; - else if (!strcmp(ptr[2], "int16")) - attr->type = ATTR_TYPE_INT16; - else if (!strcmp(ptr[2], "int32")) - attr->type = ATTR_TYPE_INT32; - else if (!strcmp(ptr[2], "int64")) - attr->type = ATTR_TYPE_INT64; - else if (!strcmp(ptr[2], "octets")) - attr->type = ATTR_TYPE_OCTETS; - else if (!strcmp(ptr[2], "string")) - attr->type = ATTR_TYPE_STRING; - else - goto out_syntax; - - attr->M = -1; - attr->H = -1; - - for (i = 3; i < r; i++) { - if (!strcmp(ptr[i], "M=0")) - attr->M = 0; - else if (!strcmp(ptr[i], "M=1")) - attr->M = 1; - else if (!strcmp(ptr[i], "H=0")) - attr->H = 0; - else if (!strcmp(ptr[i], "H=1")) - attr->H = 1; - else - goto out_syntax; - } - } else if (!strcmp(buf, "VALUE")) { - if (r != 3) - goto out_syntax; - - attr = l2tp_dict_find_attr_by_name(ptr[0]); - if (!attr) { - log_emerg("l2tp:%s:%i: attribute not found\n", fname, n); - goto out_err; - } - - value = malloc(sizeof(*value)); - memset(value, 0, sizeof(*value)); - list_add_tail(&value->entry, &attr->values); - - value->name = strdup(ptr[1]); - switch (attr->type) { - case ATTR_TYPE_INT16: - case ATTR_TYPE_INT32: - value->val.int16 = strtol(ptr[2], &endptr, 10); - if (*endptr != 0) - goto out_syntax; - break; - case ATTR_TYPE_STRING: - value->val.string = strdup(ptr[2]); - break; - } - } else - goto out_syntax; - } - - fclose(f); - - return 0; - -out_syntax: - log_emerg("l2tp:%s:%i: syntaxis error\n", fname, n); -out_err: - fclose(f); - return -1; -} - -static int l2tp_dict_load(const char *fname) -{ - int r; - - dict = _malloc(sizeof(*dict)); - memset(dict, 0, sizeof(*dict)); - INIT_LIST_HEAD(&dict->items); - - path = _malloc(PATH_MAX); - fname1 = _malloc(PATH_MAX); - buf = _malloc(BUF_SIZE); - - strcpy(path, fname); - - r = dict_load(fname); - - _free(buf); - _free(fname1); - _free(path); - - return r; -} - -static void __init dict_init(void) -{ - char *opt; - - opt = conf_get_opt("l2tp", "dictionary"); - if (!opt) - opt = DICTIONARY; - - if (l2tp_dict_load(opt)) - _exit(EXIT_FAILURE); -} - diff --git a/accel-pptpd/ctrl/l2tp/dict/dictionary b/accel-pptpd/ctrl/l2tp/dict/dictionary deleted file mode 100644 index f5d7c42..0000000 --- a/accel-pptpd/ctrl/l2tp/dict/dictionary +++ /dev/null @@ -1,2 +0,0 @@ -$INCLUDE dictionary.rfc2661 -$INCLUDE dictionary.rfc3931 diff --git a/accel-pptpd/ctrl/l2tp/dict/dictionary.rfc2661 b/accel-pptpd/ctrl/l2tp/dict/dictionary.rfc2661 deleted file mode 100644 index 3fd9614..0000000 --- a/accel-pptpd/ctrl/l2tp/dict/dictionary.rfc2661 +++ /dev/null @@ -1,55 +0,0 @@ -ATTRIBUTE Message-Type 0 int16 H=0 -ATTRIBUTE Random-Vector 36 octets M=1 H=0 -ATTRIBUTE Result-Code 1 octets M=1 H=0 -ATTRIBUTE Protocol-Version 2 int16 M=1 H=0 -ATTRIBUTE Framing-Capabilities 3 int32 M=1 -ATTRIBUTE Bearer-Capabilities 4 int32 M=1 -ATTRIBUTE Tie-Breaker 5 int64 M=0 -ATTRIBUTE Firmware-Revision 6 int16 M=0 -ATTRIBUTE Host-Name 7 string M=1 -ATTRIBUTE Vendor-Name 8 string M=0 -ATTRIBUTE Assigned-Tunnel-ID 9 int16 M=1 -ATTRIBUTE Recv-Window-Size 10 int16 M=1 -ATTRIBUTE Challenge 11 octets M=1 -ATTRIBUTE Challenge-Response 13 octets M=1 -ATTRIBUTE Cause-Code 12 int32 M=1 H=0 -ATTRIBUTE Assigned-Session-ID 14 int16 M=1 -ATTRIBUTE Call-Serial-Number 15 int32 M=1 -ATTRIBUTE Minimum-BPS 16 int32 M=1 -ATTRIBUTE Maximum-BPS 17 int32 M=1 -ATTRIBUTE Bearer-Type 18 int32 M=1 -ATTRIBUTE Framing-Type 19 int32 M=1 -ATTRIBUTE Called-Number 21 string M=1 -ATTRIBUTE Calling-Number 22 string M=1 -ATTRIBUTE Sub-Address 23 string M=1 -ATTRIBUTE TX-Speed 24 int32 M=1 -ATTRIBUTE RX-Speed 38 int32 M=1 -ATTRIBUTE Physical-Channel-ID 25 int32 M=0 -ATTRIBUTE Private-Group-ID 37 int32 M=0 -ATTRIBUTE Sequencing-Required 39 none M=1 H=0 -ATTRIBUTE Init-Recv-LCP 26 octets M=0 -ATTRIBUTE Last-Sent-LCP 27 octets M=0 -ATTRIBUTE Last-Recv-LCP 28 octets M=0 -ATTRIBUTE Proxy-Authen-Type 29 int16 M=0 -ATTRIBUTE Proxy-Authen-Name 30 string M=0 -ATTRIBUTE Proxy-Authen-Challenge 31 octets M=0 -ATTRIBUTE Proxy-Authen-ID 32 int16 M=0 -ATTRIBUTE Proxy-Authen-Response 33 octets M=0 -ATTRIBUTE Call-Errors 34 octets M=1 -ATTRIBUTE ACCM 35 octets M=1 - -VALUE Message-Type Start-Ctrl-Conn-Request 1 -VALUE Message-Type Start-Ctrl-Conn-Reply 2 -VALUE Message-Type Start-Ctrl-Conn-Connected 3 -VALUE Message-Type Stop-Ctrl-Conn-Notify 4 -VALUE Message-Type Hello 6 -VALUE Message-Type Outgoing-Call-Request 7 -VALUE Message-Type Outgoing-Call-Reply 8 -VALUE Message-Type Outgoing-Call-Connected 9 -VALUE Message-Type Incoming-Call-Request 10 -VALUE Message-Type Incoming-Call-Reply 11 -VALUE Message-Type Incoming-Call-Connected 12 -VALUE Message-Type Call-Disconnect-Notify 14 -VALUE Message-Type WAN-Error-Notify 15 -VALUE Message-Type Set-Link-Info 16 - diff --git a/accel-pptpd/ctrl/l2tp/dict/dictionary.rfc3931 b/accel-pptpd/ctrl/l2tp/dict/dictionary.rfc3931 deleted file mode 100644 index d6ad410..0000000 --- a/accel-pptpd/ctrl/l2tp/dict/dictionary.rfc3931 +++ /dev/null @@ -1,15 +0,0 @@ -ATTRIBUTE Message-Digest 59 octets M=1 H=0 -ATTRIBUTE Router-ID 60 int32 H=0 -ATTRIBUTE Assigned-Connection-ID 61 int32 -ATTRIBUTE Pseudowire-Capabilities 62 octets -ATTRIBUTE Prefered-Language 72 octets -ATTRIBUTE Local-Session-ID 63 int32 -ATTRIBUTE Remote-Session-ID 64 int32 -ATTRIBUTE Assigned-Cookie 65 octets -ATTRIBUTE Remote-End-ID 66 octets -ATTRIBUTE Pseudowire-Type 68 int16 -ATTRIBUTE L2-Specific-Sublayer 69 int16 -ATTRIBUTE Data-Sequencing 70 int16 -ATTRIBUTE TX-Connect-Speeed 74 int64 -ATTRIBUTE RX-Connect-Speeed 75 int64 -ATTRIBUTE Circuit-Status 71 int16 diff --git a/accel-pptpd/ctrl/l2tp/dict2c.py b/accel-pptpd/ctrl/l2tp/dict2c.py deleted file mode 100644 index ff0961e..0000000 --- a/accel-pptpd/ctrl/l2tp/dict2c.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys,re - -hdr = file(sys.argv[2],'w') - -def process(fname, hdr): - for line in file(fname): - if line[:-1].strip() == '': - continue - if line[0] == '#': - continue - f = re.compile('[$.a-zA-Z0-9\-]+').findall(line) - if f[0] == 'ATTRIBUTE' or f[0] == 'VENDOR': - hdr.write('#define {0} {1}\n'.format(f[1].replace('-','_').replace('.','_'), f[2])) - elif f[0] == 'VALUE': - hdr.write('#define {0}_{1} {2}\n'.format(f[1].replace('-','_').replace('.','_'), f[2].replace('-','_'),f[3])) - elif f[0] == '$INCLUDE': - process(f[1], hdr) - -if __name__ == '__main__': - process(sys.argv[1], hdr) diff --git a/accel-pptpd/ctrl/l2tp/l2tp.c b/accel-pptpd/ctrl/l2tp/l2tp.c deleted file mode 100644 index ca56051..0000000 --- a/accel-pptpd/ctrl/l2tp/l2tp.c +++ /dev/null @@ -1,1141 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "triton.h" -#include "mempool.h" -#include "log.h" -#include "ppp.h" -#include "events.h" -#include "utils.h" -#include "iprange.h" -#include "cli.h" - -#include "memdebug.h" - -#include "l2tp.h" -#include "attr_defs.h" - -#ifndef SOL_PPPOL2TP -#define SOL_PPPOL2TP 273 -#endif - -#define STATE_WAIT_SCCCN 1 -#define STATE_WAIT_ICRQ 2 -#define STATE_WAIT_ICCN 3 -#define STATE_WAIT_OCRP 4 -#define STATE_WAIT_OCCN 5 -#define STATE_ESTB 6 -#define STATE_PPP 7 -#define STATE_FIN 8 -#define STATE_CLOSE 0 - -int conf_verbose = 0; -int conf_timeout = 60; -int conf_rtimeout = 5; -int conf_retransmit = 5; -int conf_hello_interval = 60; -char *conf_host_name = NULL; - -static unsigned int stat_active; -static unsigned int stat_starting; - -struct l2tp_serv_t -{ - struct triton_context_t ctx; - struct triton_md_handler_t hnd; - struct sockaddr_in addr; -}; - -struct l2tp_conn_t -{ - struct triton_context_t ctx; - struct triton_md_handler_t hnd; - struct triton_timer_t timeout_timer; - struct triton_timer_t rtimeout_timer; - struct triton_timer_t hello_timer; - - int tunnel_fd; - - struct sockaddr_in addr; - uint16_t tid; - uint16_t sid; - uint16_t peer_tid; - uint16_t peer_sid; - uint32_t framing_cap; - - int retransmit; - uint16_t Ns, Nr; - struct list_head send_queue; - - int state; - int state1; - int state2; - - struct ppp_ctrl_t ctrl; - struct ppp_t ppp; -}; - -static pthread_mutex_t l2tp_lock = PTHREAD_MUTEX_INITIALIZER; -static struct l2tp_conn_t **l2tp_conn; -static uint16_t l2tp_tid; - -static mempool_t l2tp_conn_pool; - -static void l2tp_timeout(struct triton_timer_t *t); -static void l2tp_rtimeout(struct triton_timer_t *t); -static void l2tp_send_HELLO(struct triton_timer_t *t); -static void l2tp_send_SCCRP(struct l2tp_conn_t *conn); -static int l2tp_send(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack, int log_debug); -static int l2tp_conn_read(struct triton_md_handler_t *); - -static void l2tp_disconnect(struct l2tp_conn_t *conn) -{ - struct l2tp_packet_t *pack; - - triton_md_unregister_handler(&conn->hnd); - close(conn->hnd.fd); - - if (conn->timeout_timer.tpd) - triton_timer_del(&conn->timeout_timer); - - if (conn->rtimeout_timer.tpd) - triton_timer_del(&conn->rtimeout_timer); - - if (conn->hello_timer.tpd) - triton_timer_del(&conn->hello_timer); - - if (conn->state == STATE_PPP) { - __sync_sub_and_fetch(&stat_active, 1); - conn->state = STATE_FIN; - ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); - } else if (conn->state != STATE_FIN) - __sync_sub_and_fetch(&stat_starting, 1); - - pthread_mutex_lock(&l2tp_lock); - l2tp_conn[conn->tid] = NULL; - pthread_mutex_unlock(&l2tp_lock); - - if (conn->ppp.fd != -1) - close(conn->ppp.fd); - - if (conn->tunnel_fd != -1) - close(conn->tunnel_fd); - - triton_event_fire(EV_CTRL_FINISHED, &conn->ppp); - - log_ppp_info1("disconnected\n"); - - triton_context_unregister(&conn->ctx); - - while (!list_empty(&conn->send_queue)) { - pack = list_entry(conn->send_queue.next, typeof(*pack), entry); - list_del(&pack->entry); - l2tp_packet_free(pack); - } - - if (conn->ppp.chan_name) - _free(conn->ppp.chan_name); - - _free(conn->ctrl.calling_station_id); - _free(conn->ctrl.called_station_id); - - mempool_free(conn); -} - -static int l2tp_terminate(struct l2tp_conn_t *conn, int res, int err) -{ - struct l2tp_packet_t *pack; - struct l2tp_avp_result_code rc = {res, err}; - - log_ppp_debug("l2tp: terminate (%i, %i)\n", res, err); - - pack = l2tp_packet_alloc(2, Message_Type_Stop_Ctrl_Conn_Notify, &conn->addr); - if (!pack) - return -1; - - if (l2tp_packet_add_int16(pack, Assigned_Tunnel_ID, conn->tid, 1)) - goto out_err; - if (l2tp_packet_add_octets(pack, Result_Code, (uint8_t *)&rc, sizeof(rc), 0)) - goto out_err; - - l2tp_send(conn, pack, 0); - - conn->state = STATE_FIN; - - return 0; - -out_err: - l2tp_packet_free(pack); - return -1; -} - -static void l2tp_ppp_started(struct ppp_t *ppp) -{ - struct l2tp_conn_t *conn = container_of(ppp, typeof(*conn), ppp); - - log_ppp_debug("l2tp: ppp started\n"); - - if (conf_hello_interval) - triton_timer_add(&conn->ctx, &conn->hello_timer, 0); -} - -static void l2tp_ppp_finished(struct ppp_t *ppp) -{ - struct l2tp_conn_t *conn = container_of(ppp, typeof(*conn), ppp); - - log_ppp_debug("l2tp: ppp finished\n"); - - if (conn->state != STATE_FIN) { - __sync_sub_and_fetch(&stat_active, 1); - if (l2tp_terminate(conn, 0, 0)) - triton_context_call(&conn->ctx, (triton_event_func)l2tp_disconnect, conn); - } -} - -static void l2tp_conn_close(struct triton_context_t *ctx) -{ - struct l2tp_conn_t *conn = container_of(ctx, typeof(*conn), ctx); - - if (conn->state == STATE_PPP) { - __sync_sub_and_fetch(&stat_active, 1); - conn->state = STATE_FIN; - ppp_terminate(&conn->ppp, TERM_ADMIN_RESET, 1); - } - - if (l2tp_terminate(conn, 0, 0)) - l2tp_disconnect(conn); -} - -static int l2tp_tunnel_alloc(struct l2tp_serv_t *serv, struct l2tp_packet_t *pack, struct in_pktinfo *pkt_info, struct l2tp_attr_t *assigned_tid, struct l2tp_attr_t *framing_cap) -{ - struct l2tp_conn_t *conn; - struct sockaddr_in addr; - uint16_t tid; - //char *opt; - int flag = 1; - - conn = mempool_alloc(l2tp_conn_pool); - if (!conn) { - log_emerg("l2tp: out of memory\n"); - return -1; - } - - memset(conn, 0, sizeof(*conn)); - INIT_LIST_HEAD(&conn->send_queue); - - conn->hnd.fd = socket(PF_INET, SOCK_DGRAM, 0); - if (conn->hnd.fd < 0) { - log_error("l2tp: socket: %s\n", strerror(errno)); - mempool_free(conn); - return -1; - } - - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; - addr.sin_addr = pkt_info->ipi_addr; - addr.sin_port = htons(L2TP_PORT); - - setsockopt(conn->hnd.fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); - if (bind(conn->hnd.fd, &addr, sizeof(addr))) { - log_error("l2tp: bind: %s\n", strerror(errno)); - goto out_err; - } - - if (connect(conn->hnd.fd, (struct sockaddr *)&pack->addr, sizeof(addr))) { - log_error("l2tp: connect: %s\n", strerror(errno)); - goto out_err; - } - - if (fcntl(conn->hnd.fd, F_SETFL, O_NONBLOCK)) { - log_emerg("l2tp: failed to set nonblocking mode: %s\n", strerror(errno)); - goto out_err; - } - - pthread_mutex_lock(&l2tp_lock); - for (tid = l2tp_tid + 1; tid != l2tp_tid; tid++) { - if (tid == L2TP_MAX_TID) - tid = 1; - if (!l2tp_conn[tid]) { - l2tp_conn[tid] = conn; - conn->tid = tid; - break; - } - } - pthread_mutex_unlock(&l2tp_lock); - - if (!conn->tid) { - if (conf_verbose) - log_warn("l2tp: no free tid available\n"); - mempool_free(conn); - return -1; - } - - conn->sid = 1; - - memcpy(&conn->addr, &pack->addr, sizeof(pack->addr)); - conn->peer_tid = assigned_tid->val.uint16; - conn->framing_cap = framing_cap->val.uint32; - - conn->ctx.before_switch = log_switch; - conn->ctx.close = l2tp_conn_close; - conn->hnd.read = l2tp_conn_read; - conn->timeout_timer.expire = l2tp_timeout; - conn->timeout_timer.period = conf_timeout * 1000; - conn->rtimeout_timer.expire = l2tp_rtimeout; - conn->rtimeout_timer.period = conf_rtimeout * 1000; - conn->hello_timer.expire = l2tp_send_HELLO; - conn->hello_timer.period = conf_hello_interval * 1000; - conn->ctrl.ctx = &conn->ctx; - conn->ctrl.name = "l2tp"; - conn->ctrl.started = l2tp_ppp_started; - conn->ctrl.finished = l2tp_ppp_finished; - conn->ctrl.max_mtu = 1420; - - conn->ctrl.calling_station_id = _malloc(17); - conn->ctrl.called_station_id = _malloc(17); - u_inet_ntoa(conn->addr.sin_addr.s_addr, conn->ctrl.calling_station_id); - u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.called_station_id); - - ppp_init(&conn->ppp); - conn->ppp.ctrl = &conn->ctrl; - conn->ppp.fd = -1; - conn->tunnel_fd = -1; - - triton_context_register(&conn->ctx, &conn->ppp); - triton_md_register_handler(&conn->ctx, &conn->hnd); - triton_md_enable_handler(&conn->hnd, MD_MODE_READ); - triton_context_wakeup(&conn->ctx); - - if (conf_verbose) { - log_switch(&conn->ctx, &conn->ppp); - log_ppp_info2("recv "); - l2tp_packet_print(pack, log_ppp_info2); - } - - triton_context_call(&conn->ctx, (triton_event_func)l2tp_send_SCCRP, conn); - - __sync_add_and_fetch(&stat_starting, 1); - - return 0; - -out_err: - close(conn->hnd.fd); - mempool_free(conn); - return -1; -} - -static int l2tp_connect(struct l2tp_conn_t *conn) -{ - struct sockaddr_pppol2tp pppox_addr; - int arg = 1; - - memset(&pppox_addr, 0, sizeof(pppox_addr)); - pppox_addr.sa_family = AF_PPPOX; - pppox_addr.sa_protocol = PX_PROTO_OL2TP; - pppox_addr.pppol2tp.fd = conn->hnd.fd; - memcpy(&pppox_addr.pppol2tp.addr, &conn->addr, sizeof(conn->addr)); - pppox_addr.pppol2tp.s_tunnel = conn->tid; - pppox_addr.pppol2tp.d_tunnel = conn->peer_tid; - - conn->tunnel_fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP); - if (!conn->ppp.fd) { - log_ppp_error("l2tp: socket(AF_PPPOX): %s\n", strerror(errno)); - return -1; - } - - conn->ppp.fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP); - if (!conn->ppp.fd) { - close(conn->tunnel_fd); - conn->tunnel_fd = -1; - log_ppp_error("l2tp: socket(AF_PPPOX): %s\n", strerror(errno)); - return -1; - } - - if (connect(conn->tunnel_fd, (struct sockaddr *)&pppox_addr, sizeof(pppox_addr)) < 0) { - log_ppp_error("l2tp: connect(tunnel): %s\n", strerror(errno)); - return -1; - } - - pppox_addr.pppol2tp.s_session = conn->sid; - pppox_addr.pppol2tp.d_session = conn->peer_sid; - - if (connect(conn->ppp.fd, (struct sockaddr *)&pppox_addr, sizeof(pppox_addr)) < 0) { - log_ppp_error("l2tp: connect(session): %s\n", strerror(errno)); - return -1; - } - - if (setsockopt(conn->ppp.fd, SOL_PPPOL2TP, PPPOL2TP_SO_LNSMODE, &arg, sizeof(arg))) { - log_ppp_error("l2tp: setsockopt: %s\n", strerror(errno)); - return -1; - } - - conn->ppp.chan_name = _strdup(inet_ntoa(conn->addr.sin_addr)); - - triton_event_fire(EV_CTRL_STARTED, &conn->ppp); - - if (establish_ppp(&conn->ppp)) - return -1; - - __sync_sub_and_fetch(&stat_starting, 1); - __sync_add_and_fetch(&stat_active, 1); - - conn->state = STATE_PPP; - - return 0; -} - -static void l2tp_rtimeout(struct triton_timer_t *t) -{ - struct l2tp_conn_t *conn = container_of(t, typeof(*conn), rtimeout_timer); - struct l2tp_packet_t *pack; - - if (!list_empty(&conn->send_queue)) { - log_ppp_debug("l2tp: retransmit (%i)\n", conn->retransmit); - if (++conn->retransmit <= conf_retransmit) { - pack = list_entry(conn->send_queue.next, typeof(*pack), entry); - pack->hdr.Nr = htons(conn->Nr + 1); - if (conf_verbose) { - log_ppp_debug("send "); - l2tp_packet_print(pack, log_ppp_debug); - } - if (l2tp_packet_send(conn->hnd.fd, pack) == 0) - return; - } else - l2tp_disconnect(conn); - } -} - -static void l2tp_timeout(struct triton_timer_t *t) -{ - struct l2tp_conn_t *conn = container_of(t, typeof(*conn), timeout_timer); - log_ppp_debug("l2tp: timeout\n"); - l2tp_disconnect(conn); -} - -static int l2tp_send(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack, int log_debug) -{ - conn->retransmit = 0; - - pack->hdr.tid = htons(conn->peer_tid); - //pack->hdr.sid = htons(conn->peer_sid); - pack->hdr.Nr = htons(conn->Nr + 1); - pack->hdr.Ns = htons(conn->Ns); - - if (!list_empty(&pack->attrs)) - conn->Ns++; - - if (conf_verbose) { - if (log_debug) { - log_ppp_debug("send "); - l2tp_packet_print(pack, log_ppp_debug); - } else { - log_ppp_info2("send "); - l2tp_packet_print(pack, log_ppp_info2); - } - } - - if (l2tp_packet_send(conn->hnd.fd, pack)) - goto out_err; - - if (!list_empty(&pack->attrs)) { - list_add_tail(&pack->entry, &conn->send_queue); - if (!conn->rtimeout_timer.tpd) - triton_timer_add(&conn->ctx, &conn->rtimeout_timer, 0); - } else - l2tp_packet_free(pack); - - return 0; - -out_err: - l2tp_packet_free(pack); - return -1; -} - -static int l2tp_send_ZLB(struct l2tp_conn_t *conn) -{ - struct l2tp_packet_t *pack; - - pack = l2tp_packet_alloc(2, 0, &conn->addr); - if (!pack) - return -1; - - if (l2tp_send(conn, pack, 1)) - return -1; - - return 0; -} - -static void l2tp_send_HELLO(struct triton_timer_t *t) -{ - struct l2tp_conn_t *conn = container_of(t, typeof(*conn), hello_timer); - struct l2tp_packet_t *pack; - - pack = l2tp_packet_alloc(2, Message_Type_Hello, &conn->addr); - if (!pack) { - l2tp_disconnect(conn); - return; - } - - if (l2tp_send(conn, pack, 1)) - l2tp_disconnect(conn); -} - -static void l2tp_send_SCCRP(struct l2tp_conn_t *conn) -{ - struct l2tp_packet_t *pack; - - pack = l2tp_packet_alloc(2, Message_Type_Start_Ctrl_Conn_Reply, &conn->addr); - if (!pack) - goto out; - - if (l2tp_packet_add_int16(pack, Protocol_Version, L2TP_V2_PROTOCOL_VERSION, 1)) - goto out_err; - if (conf_host_name && l2tp_packet_add_string(pack, Host_Name, conf_host_name, 1)) - goto out_err; - if (l2tp_packet_add_int32(pack, Framing_Capabilities, conn->framing_cap, 1)) - goto out_err; - if (l2tp_packet_add_int16(pack, Assigned_Tunnel_ID, conn->tid, 1)) - goto out_err; - - if (l2tp_send(conn, pack, 0)) - goto out; - - if (!conn->timeout_timer.tpd) - triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); - else - triton_timer_mod(&conn->timeout_timer, 0); - - conn->state = STATE_WAIT_SCCCN; - - return; - -out_err: - l2tp_packet_free(pack); -out: - l2tp_disconnect(conn); -} - -static int l2tp_send_ICRP(struct l2tp_conn_t *conn) -{ - struct l2tp_packet_t *pack; - - pack = l2tp_packet_alloc(2, Message_Type_Incoming_Call_Reply, &conn->addr); - if (!pack) - return -1; - - pack->hdr.sid = htons(conn->peer_sid); - - if (l2tp_packet_add_int16(pack, Assigned_Session_ID, conn->sid, 1)) - goto out_err; - - l2tp_send(conn, pack, 0); - - if (!conn->timeout_timer.tpd) - triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); - else - triton_timer_mod(&conn->timeout_timer, 0); - - conn->state1 = STATE_WAIT_ICCN; - - return 0; - -out_err: - l2tp_packet_free(pack); - return -1; -} - -static int l2tp_send_OCRQ(struct l2tp_conn_t *conn) -{ - struct l2tp_packet_t *pack; - - pack = l2tp_packet_alloc(2, Message_Type_Outgoing_Call_Request, &conn->addr); - if (!pack) - return -1; - - pack->hdr.sid = htons(conn->peer_sid); - - if (l2tp_packet_add_int16(pack, Assigned_Session_ID, conn->sid, 1)) - goto out_err; - if (l2tp_packet_add_int32(pack, Call_Serial_Number, 0, 1)) - goto out_err; - if (l2tp_packet_add_int32(pack, Minimum_BPS, 100, 1)) - goto out_err; - if (l2tp_packet_add_int32(pack, Maximum_BPS, 100000, 1)) - goto out_err; - if (l2tp_packet_add_int32(pack, Bearer_Type, 3, 1)) - goto out_err; - if (l2tp_packet_add_int32(pack, Framing_Type, 3, 1)) - goto out_err; - if (l2tp_packet_add_string(pack, Called_Number, "", 1)) - goto out_err; - - if (l2tp_send(conn, pack, 0)) - return -1; - - if (!conn->timeout_timer.tpd) - triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); - else - triton_timer_mod(&conn->timeout_timer, 0); - - conn->state2 = STATE_WAIT_OCRP; - - return 0; - -out_err: - l2tp_packet_free(pack); - return -1; -} - - -static int l2tp_recv_SCCRQ(struct l2tp_serv_t *serv, struct l2tp_packet_t *pack, struct in_pktinfo *pkt_info) -{ - struct l2tp_attr_t *attr; - struct l2tp_attr_t *protocol_version = NULL; - struct l2tp_attr_t *assigned_tid = NULL; - struct l2tp_attr_t *assigned_cid = NULL; - struct l2tp_attr_t *framing_cap = NULL; - struct l2tp_attr_t *router_id = NULL; - - if (ppp_shutdown) - return 0; - - list_for_each_entry(attr, &pack->attrs, entry) { - switch (attr->attr->id) { - case Protocol_Version: - protocol_version = attr; - break; - case Framing_Capabilities: - framing_cap = attr; - break; - case Assigned_Tunnel_ID: - assigned_tid = attr; - break; - case Challenge: - if (conf_verbose) - log_warn("l2tp: Challenge in SCCRQ is not supported\n"); - return -1; - case Assigned_Connection_ID: - assigned_cid = attr; - break; - case Router_ID: - router_id = attr; - break; - case Message_Digest: - if (conf_verbose) - log_warn("l2tp: Message-Digest is not supported\n"); - return -1; - } - } - - if (assigned_tid) { - if (!protocol_version) { - if (conf_verbose) - log_warn("l2tp: SCCRQ: no Protocol-Version present in message\n"); - return -1; - } - if (protocol_version->val.uint16 != L2TP_V2_PROTOCOL_VERSION) { - if (conf_verbose) - log_warn("l2tp: protocol version %02x is not supported\n", protocol_version->val.uint16); - return -1; - } - if (!framing_cap) { - if (conf_verbose) - log_warn("l2tp: SCCRQ: no Framing-Capabilities present in message\n"); - return -1; - } - - if (l2tp_tunnel_alloc(serv, pack, pkt_info, assigned_tid, framing_cap)) - return -1; - - } else if (assigned_cid) { - // not yet implemented - return 0; - } else { - if (conf_verbose) - log_warn("l2tp: SCCRQ: no Assigned-Tunnel-ID or Assigned-Connection-ID present in message\n"); - return -1; - } - - return 0; -} - -static int l2tp_recv_SCCCN(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) -{ - if (conn->state == STATE_WAIT_SCCCN) { - triton_timer_mod(&conn->timeout_timer, 0); - conn->state = STATE_ESTB; - conn->state1 = STATE_WAIT_ICRQ; - } - else - log_ppp_warn("l2tp: unexpected SCCCN\n"); - - return 0; -} - -static int l2tp_recv_StopCCN(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) -{ - l2tp_send_ZLB(conn); - return -1; -} - -static int l2tp_recv_HELLO(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) -{ - if (l2tp_send_ZLB(conn)) - return -1; - - return 0; -} - -static int l2tp_recv_ICRQ(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) -{ - struct l2tp_attr_t *attr; - struct l2tp_attr_t *assigned_sid = NULL; - - if (conn->state1 != STATE_WAIT_ICRQ) { - log_ppp_warn("l2tp: unexpected ICRQ\n"); - return 0; - } - - list_for_each_entry(attr, &pack->attrs, entry) { - switch(attr->attr->id) { - case Assigned_Session_ID: - assigned_sid = attr; - break; - case Message_Type: - case Call_Serial_Number: - case Bearer_Type: - case Calling_Number: - case Called_Number: - case Sub_Address: - case Physical_Channel_ID: - break; - default: - if (attr->M) { - if (conf_verbose) { - log_ppp_warn("l2tp: ICRQ: unknown attribute %i\n", attr->attr->id); - if (l2tp_terminate(conn, 2, 8)) - return -1; - return 0; - } - } - } - } - - if (!assigned_sid) { - if (conf_verbose) - log_ppp_warn("l2tp: ICRQ: no Assigned-Session-ID attribute present in message\n"); - if (l2tp_terminate(conn, 2, 0)) - return -1; - } - - conn->peer_sid = assigned_sid->val.uint16; - - if (l2tp_send_ICRP(conn)) - return -1; - - if (l2tp_send_OCRQ(conn)) - return -1; - - return 0; -} - -static int l2tp_recv_ICCN(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) -{ - if (conn->state1 != STATE_WAIT_ICCN) { - log_ppp_warn("l2tp: unexpected ICCN\n"); - return 0; - } - - conn->state1 = STATE_ESTB; - - if (l2tp_connect(conn)) { - if (l2tp_terminate(conn, 2, 0)) - return -1; - return 0; - } - - if (l2tp_send_ZLB(conn)) - return -1; - - triton_timer_del(&conn->timeout_timer); - - return 0; -} - -static int l2tp_recv_OCRP(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) -{ - if (conn->state2 != STATE_WAIT_OCRP) { - log_ppp_warn("l2tp: unexpected OCRP\n"); - return 0; - } - - conn->state2 = STATE_WAIT_OCCN; - - return 0; -} - -static int l2tp_recv_OCCN(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) -{ - if (conn->state2 != STATE_WAIT_OCCN) { - log_ppp_warn("l2tp: unexpected OCCN\n"); - return 0; - } - - conn->state2 = STATE_ESTB; - - return 0; -} - -static int l2tp_recv_CDN(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) -{ - if (ntohs(pack->hdr.sid) != conn->sid) { - if (conf_verbose) - log_warn("l2tp: sid %i is incorrect\n", ntohs(pack->hdr.sid)); - return 0; - } - - if (conn->state == STATE_PPP) { - __sync_sub_and_fetch(&stat_active, 1); - conn->state = STATE_FIN; - ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); - } - - if (l2tp_terminate(conn, 0, 0)) - return -1; - - return 0; -} - -static int l2tp_recv_SLI(struct l2tp_conn_t *conn, struct l2tp_packet_t *pack) -{ - return 0; -} - -static int l2tp_conn_read(struct triton_md_handler_t *h) -{ - struct l2tp_conn_t *conn = container_of(h, typeof(*conn), hnd); - struct l2tp_packet_t *pack, *p; - struct l2tp_attr_t *msg_type; - - while (1) { - if (l2tp_recv(h->fd, &pack, NULL)) - return 0; - - if (!pack) - continue; - - if (ntohs(pack->hdr.tid) != conn->tid) { - if (conf_verbose) - log_warn("l2tp: incorrect tid %i in tunnel %i\n", ntohs(pack->hdr.tid), conn->tid); - l2tp_packet_free(pack); - continue; - } - - if (ntohs(pack->hdr.Ns) == conn->Nr + 1) { - if (!list_empty(&pack->attrs)) - conn->Nr++; - if (!list_empty(&conn->send_queue)) { - p = list_entry(conn->send_queue.next, typeof(*pack), entry); - list_del(&p->entry); - l2tp_packet_free(p); - conn->retransmit = 0; - } - if (!list_empty(&conn->send_queue)) - triton_timer_mod(&conn->rtimeout_timer, 0); - else { - if (conn->rtimeout_timer.tpd) - triton_timer_del(&conn->rtimeout_timer); - if (conn->state == STATE_FIN) - goto drop; - } - } else { - if (ntohs(pack->hdr.Ns) < conn->Nr + 1 || (ntohs(pack->hdr.Ns > 32767 && conn->Nr + 1 < 32767))) { - log_ppp_debug("duplicate packet\n"); - if (l2tp_send_ZLB(conn)) - goto drop; - } else - log_ppp_debug("reordered packet\n"); - l2tp_packet_free(pack); - continue; - } - - if (list_empty(&pack->attrs)) { - l2tp_packet_free(pack); - continue; - } - - msg_type = list_entry(pack->attrs.next, typeof(*msg_type), entry); - - if (msg_type->attr->id != Message_Type) { - if (conf_verbose) - log_ppp_error("l2tp: first attribute is not Message-Type, dropping connection...\n"); - goto drop; - } - - if (conf_verbose) { - if (msg_type->val.uint16 == Message_Type_Hello) { - log_ppp_debug("recv "); - l2tp_packet_print(pack, log_ppp_debug); - } else { - log_ppp_info2("recv "); - l2tp_packet_print(pack, log_ppp_info2); - } - } - - switch (msg_type->val.uint16) { - case Message_Type_Start_Ctrl_Conn_Connected: - if (l2tp_recv_SCCCN(conn, pack)) - goto drop; - break; - case Message_Type_Stop_Ctrl_Conn_Notify: - if (l2tp_recv_StopCCN(conn, pack)) - goto drop; - break; - case Message_Type_Hello: - if (l2tp_recv_HELLO(conn, pack)) - goto drop; - break; - case Message_Type_Incoming_Call_Request: - if (l2tp_recv_ICRQ(conn, pack)) - goto drop; - break; - case Message_Type_Incoming_Call_Connected: - if (l2tp_recv_ICCN(conn, pack)) - goto drop; - break; - case Message_Type_Outgoing_Call_Reply: - if (l2tp_recv_OCRP(conn, pack)) - goto drop; - break; - case Message_Type_Outgoing_Call_Connected: - if (l2tp_recv_OCCN(conn, pack)) - goto drop; - break; - case Message_Type_Call_Disconnect_Notify: - if (l2tp_recv_CDN(conn, pack)) - goto drop; - break; - case Message_Type_Set_Link_Info: - if (l2tp_recv_SLI(conn, pack)) - goto drop; - break; - case Message_Type_Start_Ctrl_Conn_Request: - case Message_Type_Start_Ctrl_Conn_Reply: - case Message_Type_Outgoing_Call_Request: - case Message_Type_Incoming_Call_Reply: - case Message_Type_WAN_Error_Notify: - if (conf_verbose) - log_warn("l2tp: unexpected Message-Type %i\n", msg_type->val.uint16); - break; - default: - if (conf_verbose) - log_warn("l2tp: unknown Message-Type %i\n", msg_type->val.uint16); - if (msg_type->M) { - if (l2tp_terminate(conn, 2, 8)) - goto drop; - } - } - - l2tp_packet_free(pack); - } - -drop: - l2tp_packet_free(pack); - l2tp_disconnect(conn); - return -1; -} - -static int l2tp_udp_read(struct triton_md_handler_t *h) -{ - struct l2tp_serv_t *serv = container_of(h, typeof(*serv), hnd); - struct l2tp_packet_t *pack; - struct l2tp_attr_t *msg_type; - struct in_pktinfo pkt_info; - - while (1) { - if (l2tp_recv(h->fd, &pack, &pkt_info)) - break; - - if (!pack) - continue; - - if (iprange_client_check(pack->addr.sin_addr.s_addr)) { - log_warn("l2tp: IP is out of client-ip-range, droping connection...\n"); - goto skip; - } - - if (pack->hdr.tid) - goto skip; - - if (list_empty(&pack->attrs)) { - if (conf_verbose) - log_warn("l2tp: to Message-Type attribute present\n"); - goto skip; - } - - msg_type = list_entry(pack->attrs.next, typeof(*msg_type), entry); - if (msg_type->attr->id != Message_Type) { - if (conf_verbose) - log_warn("l2tp: first attribute is not Message-Type\n"); - goto skip; - } - - if (msg_type->val.uint16 == Message_Type_Start_Ctrl_Conn_Request) - l2tp_recv_SCCRQ(serv, pack, &pkt_info); - else { - if (conf_verbose) { - log_warn("recv (unexpected) "); - l2tp_packet_print(pack, log_ppp_warn); - } - } -skip: - l2tp_packet_free(pack); - } - - return 0; -} - -static void l2tp_udp_close(struct triton_context_t *ctx) -{ - struct l2tp_serv_t *serv = container_of(ctx, typeof(*serv), ctx); - triton_md_unregister_handler(&serv->hnd); - close(serv->hnd.fd); - triton_context_unregister(&serv->ctx); -} - -static struct l2tp_serv_t udp_serv = -{ - .hnd.read = l2tp_udp_read, - .ctx.close = l2tp_udp_close, - .ctx.before_switch = log_switch, -}; - -/*static struct l2tp_serv_t ip_serv = -{ - .hnd.read=l2t_ip_read, - .ctx.close=l2tp_ip_close, -};*/ - -static void start_udp_server(void) -{ - struct sockaddr_in addr; - char *opt; - int flag = 1; - - udp_serv.hnd.fd = socket(PF_INET, SOCK_DGRAM, 0); - if (udp_serv.hnd.fd < 0) { - log_emerg("l2tp: socket: %s\n", strerror(errno)); - return; - } - - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; - addr.sin_port = htons(L2TP_PORT); - - opt = conf_get_opt("l2tp", "bind"); - if (opt) - addr.sin_addr.s_addr = inet_addr(opt); - else - addr.sin_addr.s_addr = htonl(INADDR_ANY); - - setsockopt(udp_serv.hnd.fd, SOL_SOCKET, SO_REUSEADDR, &udp_serv.hnd.fd, sizeof(udp_serv.hnd.fd)); - setsockopt(udp_serv.hnd.fd, SOL_SOCKET, SO_NO_CHECK, &udp_serv.hnd.fd, sizeof(udp_serv.hnd.fd)); - - if (bind (udp_serv.hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { - log_emerg("l2tp: bind: %s\n", strerror(errno)); - close(udp_serv.hnd.fd); - return; - } - - if (fcntl(udp_serv.hnd.fd, F_SETFL, O_NONBLOCK)) { - log_emerg("l2tp: failed to set nonblocking mode: %s\n", strerror(errno)); - close(udp_serv.hnd.fd); - return; - } - - if (setsockopt(udp_serv.hnd.fd, IPPROTO_IP, IP_PKTINFO, &flag, sizeof(flag))) { - log_emerg("l2tp: setsockopt(IP_PKTINFO): %s\n", strerror(errno)); - close(udp_serv.hnd.fd); - return; - } - - memcpy(&udp_serv.addr, &addr, sizeof(addr)); - - triton_context_register(&udp_serv.ctx, NULL); - triton_md_register_handler(&udp_serv.ctx, &udp_serv.hnd); - triton_md_enable_handler(&udp_serv.hnd, MD_MODE_READ); - triton_context_wakeup(&udp_serv.ctx); -} - -static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "l2tp:\r\n"); - cli_sendv(client, " starting: %u\r\n", stat_starting); - cli_sendv(client, " active: %u\r\n", stat_active); - - return CLI_CMD_OK; -} - -static void load_config(void) -{ - char *opt; - - opt = conf_get_opt("l2tp", "verbose"); - if (opt && atoi(opt) > 0) - conf_verbose = 1; - - opt = conf_get_opt("l2tp", "hello-interval"); - if (opt && atoi(opt) > 0) - conf_hello_interval = atoi(opt); - - opt = conf_get_opt("l2tp", "timeout"); - if (opt && atoi(opt) > 0) - conf_timeout = atoi(opt); - - opt = conf_get_opt("l2tp", "rtimeout"); - if (opt && atoi(opt) > 0) - conf_rtimeout = atoi(opt); - - opt = conf_get_opt("l2tp", "retransmit"); - if (opt && atoi(opt) > 0) - conf_retransmit = atoi(opt); - - if (conf_host_name) - _free(conf_host_name); - opt = conf_get_opt("l2tp", "host-name"); - if (opt) - conf_host_name = _strdup(opt); - else - conf_host_name = NULL; -} - -static void __init l2tp_init(void) -{ - l2tp_conn = malloc(L2TP_MAX_TID * sizeof(void *)); - memset(l2tp_conn, 0, L2TP_MAX_TID * sizeof(void *)); - - l2tp_conn_pool = mempool_create(sizeof(struct l2tp_conn_t)); - - load_config(); - - start_udp_server(); - - cli_register_simple_cmd2(&show_stat_exec, NULL, 2, "show", "stat"); - - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); -} - diff --git a/accel-pptpd/ctrl/l2tp/l2tp.h b/accel-pptpd/ctrl/l2tp/l2tp.h deleted file mode 100644 index ac9b8e0..0000000 --- a/accel-pptpd/ctrl/l2tp/l2tp.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef __L2TP_H -#define __L2TP_H - -#include - -#include "list.h" -#include "l2tp_prot.h" - -#define ATTR_TYPE_NONE 0 -#define ATTR_TYPE_INT16 1 -#define ATTR_TYPE_INT32 2 -#define ATTR_TYPE_INT64 3 -#define ATTR_TYPE_OCTETS 4 -#define ATTR_TYPE_STRING 5 - -#define L2TP_MAX_PACKET_SIZE 65536 -#define L2TP_MAX_TID 65534 - -#define L2TP_V2_PROTOCOL_VERSION ( 1 << 8 | 0 ) - -typedef union -{ - uint32_t uint32; - int32_t int32; - uint16_t uint16; - int16_t int16; - uint64_t uint64; - uint8_t *octets; - char *string; -} l2tp_value_t; - -struct l2tp_dict_attr_t -{ - struct list_head entry; - const char *name; - int id; - int type; - int M; - int H; - struct list_head values; -}; - -struct l2tp_dict_value_t -{ - struct list_head entry; - const char *name; - l2tp_value_t val; -}; - -struct l2tp_attr_t -{ - struct list_head entry; - struct l2tp_dict_attr_t *attr; - int M:1; - int H:1; - int length; - l2tp_value_t val; -}; - -struct l2tp_packet_t -{ - struct list_head entry; - struct sockaddr_in addr; - struct l2tp_hdr_t hdr; - struct list_head attrs; -}; - -extern int conf_verbose; - -struct l2tp_dict_attr_t *l2tp_dict_find_attr_by_name(const char *name); -struct l2tp_dict_attr_t *l2tp_dict_find_attr_by_id(int id); -struct l2tp_dict_value_t *l2tp_dict_find_value(struct l2tp_dict_attr_t *attr, l2tp_value_t val); - -int l2tp_recv(int fd, struct l2tp_packet_t **, struct in_pktinfo *); -void l2tp_packet_free(struct l2tp_packet_t *); -void l2tp_packet_print(struct l2tp_packet_t *, void (*print)(const char *fmt, ...)); -struct l2tp_packet_t *l2tp_packet_alloc(int ver, int msg_type, struct sockaddr_in *addr); -int l2tp_packet_send(int sock, struct l2tp_packet_t *); -int l2tp_packet_add_int16(struct l2tp_packet_t *pack, int id, int16_t val, int M); -int l2tp_packet_add_int32(struct l2tp_packet_t *pack, int id, int32_t val, int M); -int l2tp_packet_add_string(struct l2tp_packet_t *pack, int id, const char *val, int M); -int l2tp_packet_add_octets(struct l2tp_packet_t *pack, int id, const uint8_t *val, int size, int M); - -void l2tp_nl_create_tunnel(int fd, int tid, int peer_tid); -void l2tp_nl_create_session(int tid, int sid, int peer_sid); -void l2tp_nl_delete_tunnel(int tid); - -#endif diff --git a/accel-pptpd/ctrl/l2tp/l2tp_kernel.h b/accel-pptpd/ctrl/l2tp/l2tp_kernel.h deleted file mode 100644 index 4bdb31d..0000000 --- a/accel-pptpd/ctrl/l2tp/l2tp_kernel.h +++ /dev/null @@ -1,163 +0,0 @@ -/* - * L2TP-over-IP socket for L2TPv3. - * - * Author: James Chapman - */ - -#ifndef _LINUX_L2TP_H_ -#define _LINUX_L2TP_H_ - -#include -#ifdef __KERNEL__ -#include -#include -#else -#include -#endif - -#define IPPROTO_L2TP 115 - -/** - * struct sockaddr_l2tpip - the sockaddr structure for L2TP-over-IP sockets - * @l2tp_family: address family number AF_L2TPIP. - * @l2tp_addr: protocol specific address information - * @l2tp_conn_id: connection id of tunnel - */ -#define __SOCK_SIZE__ 16 /* sizeof(struct sockaddr) */ -struct sockaddr_l2tpip { - /* The first fields must match struct sockaddr_in */ - sa_family_t l2tp_family; /* AF_INET */ - __be16 l2tp_unused; /* INET port number (unused) */ - struct in_addr l2tp_addr; /* Internet address */ - - __u32 l2tp_conn_id; /* Connection ID of tunnel */ - - /* Pad to size of `struct sockaddr'. */ - unsigned char __pad[sizeof(struct sockaddr) - sizeof(sa_family_t) - - sizeof(__be16) - sizeof(struct in_addr) - - sizeof(__u32)]; -}; - -/***************************************************************************** - * NETLINK_GENERIC netlink family. - *****************************************************************************/ - -/* - * Commands. - * Valid TLVs of each command are:- - * TUNNEL_CREATE - CONN_ID, pw_type, netns, ifname, ipinfo, udpinfo, udpcsum, vlanid - * TUNNEL_DELETE - CONN_ID - * TUNNEL_MODIFY - CONN_ID, udpcsum - * TUNNEL_GETSTATS - CONN_ID, (stats) - * TUNNEL_GET - CONN_ID, (...) - * SESSION_CREATE - SESSION_ID, PW_TYPE, offset, data_seq, cookie, peer_cookie, offset, l2spec - * SESSION_DELETE - SESSION_ID - * SESSION_MODIFY - SESSION_ID, data_seq - * SESSION_GET - SESSION_ID, (...) - * SESSION_GETSTATS - SESSION_ID, (stats) - * - */ -enum { - L2TP_CMD_NOOP, - L2TP_CMD_TUNNEL_CREATE, - L2TP_CMD_TUNNEL_DELETE, - L2TP_CMD_TUNNEL_MODIFY, - L2TP_CMD_TUNNEL_GET, - L2TP_CMD_SESSION_CREATE, - L2TP_CMD_SESSION_DELETE, - L2TP_CMD_SESSION_MODIFY, - L2TP_CMD_SESSION_GET, - __L2TP_CMD_MAX, -}; - -#define L2TP_CMD_MAX (__L2TP_CMD_MAX - 1) - -/* - * ATTR types defined for L2TP - */ -enum { - L2TP_ATTR_NONE, /* no data */ - L2TP_ATTR_PW_TYPE, /* u16, enum l2tp_pwtype */ - L2TP_ATTR_ENCAP_TYPE, /* u16, enum l2tp_encap_type */ - L2TP_ATTR_OFFSET, /* u16 */ - L2TP_ATTR_DATA_SEQ, /* u16 */ - L2TP_ATTR_L2SPEC_TYPE, /* u8, enum l2tp_l2spec_type */ - L2TP_ATTR_L2SPEC_LEN, /* u8, enum l2tp_l2spec_type */ - L2TP_ATTR_PROTO_VERSION, /* u8 */ - L2TP_ATTR_IFNAME, /* string */ - L2TP_ATTR_CONN_ID, /* u32 */ - L2TP_ATTR_PEER_CONN_ID, /* u32 */ - L2TP_ATTR_SESSION_ID, /* u32 */ - L2TP_ATTR_PEER_SESSION_ID, /* u32 */ - L2TP_ATTR_UDP_CSUM, /* u8 */ - L2TP_ATTR_VLAN_ID, /* u16 */ - L2TP_ATTR_COOKIE, /* 0, 4 or 8 bytes */ - L2TP_ATTR_PEER_COOKIE, /* 0, 4 or 8 bytes */ - L2TP_ATTR_DEBUG, /* u32 */ - L2TP_ATTR_RECV_SEQ, /* u8 */ - L2TP_ATTR_SEND_SEQ, /* u8 */ - L2TP_ATTR_LNS_MODE, /* u8 */ - L2TP_ATTR_USING_IPSEC, /* u8 */ - L2TP_ATTR_RECV_TIMEOUT, /* msec */ - L2TP_ATTR_FD, /* int */ - L2TP_ATTR_IP_SADDR, /* u32 */ - L2TP_ATTR_IP_DADDR, /* u32 */ - L2TP_ATTR_UDP_SPORT, /* u16 */ - L2TP_ATTR_UDP_DPORT, /* u16 */ - L2TP_ATTR_MTU, /* u16 */ - L2TP_ATTR_MRU, /* u16 */ - L2TP_ATTR_STATS, /* nested */ - __L2TP_ATTR_MAX, -}; - -#define L2TP_ATTR_MAX (__L2TP_ATTR_MAX - 1) - -/* Nested in L2TP_ATTR_STATS */ -enum { - L2TP_ATTR_STATS_NONE, /* no data */ - L2TP_ATTR_TX_PACKETS, /* u64 */ - L2TP_ATTR_TX_BYTES, /* u64 */ - L2TP_ATTR_TX_ERRORS, /* u64 */ - L2TP_ATTR_RX_PACKETS, /* u64 */ - L2TP_ATTR_RX_BYTES, /* u64 */ - L2TP_ATTR_RX_SEQ_DISCARDS, /* u64 */ - L2TP_ATTR_RX_OOS_PACKETS, /* u64 */ - L2TP_ATTR_RX_ERRORS, /* u64 */ - __L2TP_ATTR_STATS_MAX, -}; - -#define L2TP_ATTR_STATS_MAX (__L2TP_ATTR_STATS_MAX - 1) - -enum l2tp_pwtype { - L2TP_PWTYPE_NONE = 0x0000, - L2TP_PWTYPE_ETH_VLAN = 0x0004, - L2TP_PWTYPE_ETH = 0x0005, - L2TP_PWTYPE_PPP = 0x0007, - L2TP_PWTYPE_PPP_AC = 0x0008, - L2TP_PWTYPE_IP = 0x000b, - __L2TP_PWTYPE_MAX -}; - -enum l2tp_l2spec_type { - L2TP_L2SPECTYPE_NONE, - L2TP_L2SPECTYPE_DEFAULT, -}; - -enum l2tp_encap_type { - L2TP_ENCAPTYPE_UDP, - L2TP_ENCAPTYPE_IP, -}; - -enum l2tp_seqmode { - L2TP_SEQ_NONE = 0, - L2TP_SEQ_IP = 1, - L2TP_SEQ_ALL = 2, -}; - -/* - * NETLINK_GENERIC related info - */ -#define L2TP_GENL_NAME "l2tp" -#define L2TP_GENL_VERSION 0x1 - -#endif diff --git a/accel-pptpd/ctrl/l2tp/l2tp_prot.h b/accel-pptpd/ctrl/l2tp/l2tp_prot.h deleted file mode 100644 index 1c1d9da..0000000 --- a/accel-pptpd/ctrl/l2tp/l2tp_prot.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef __L2TP_PROT_H -#define __L2TP_PROT_H - -#include - -#define L2TP_PORT 1701 - -struct l2tp_hdr_t -{ - uint8_t P:1; - uint8_t O:1; - uint8_t reserved2:1; - uint8_t S:1; - uint8_t reserved1:2; - uint8_t L:1; - uint8_t T:1; - uint8_t ver:4; - uint8_t reserved3:4; - uint16_t length; - union { - struct { - uint16_t tid; - uint16_t sid; - }; - uint32_t cid; - }; - uint16_t Ns; - uint16_t Nr; -} __attribute__((packed)); - -/*#define L2TP_T(hdr) (hdr->flags >> 15) -#define L2TP_L(hdr) ((hdr->flags >> 14) & 1) -#define L2TP_S(hdr) ((hdr->flags >> 10) & 1) -#define L2TP_O(hdr) ((hdr->flags >> 8) & 1) -#define L2TP_VER(hdr) (hdr->flags & 0xf)*/ - -struct l2tp_avp_t -{ - uint16_t length:10; - uint16_t reserved:4; - uint16_t H:1; - uint16_t M:1; - uint16_t vendor; - uint16_t type; - uint8_t val[0]; -} __attribute__((packed)); - -struct l2tp_avp_result_code -{ - uint16_t result_code; - uint16_t error_code; -} __attribute__((packed)); - -#endif - diff --git a/accel-pptpd/ctrl/l2tp/netlink.c b/accel-pptpd/ctrl/l2tp/netlink.c deleted file mode 100644 index 7c8c79a..0000000 --- a/accel-pptpd/ctrl/l2tp/netlink.c +++ /dev/null @@ -1,94 +0,0 @@ -#include -#include -#include - -#include "l2tp_kernel.h" -#include "triton.h" - -static int family; - -void l2tp_nl_delete_tunnel(int tid) -{ - struct nl_sock *nl_sock; - struct nl_msg *msg; - - nl_sock = nl_socket_alloc(); - msg = nlmsg_alloc(); - - genl_connect(nl_sock); - - genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_REQUEST, L2TP_CMD_TUNNEL_DELETE, L2TP_GENL_VERSION); - nla_put_u32(msg, L2TP_ATTR_CONN_ID, tid); - - nl_send_auto_complete(nl_sock, msg); - nl_recvmsgs_default(nl_sock); - - nlmsg_free(msg); - nl_close(nl_sock); - nl_socket_free(nl_sock); -} - -void l2tp_nl_create_tunnel(int fd, int tid, int peer_tid) -{ - struct nl_sock *nl_sock; - struct nl_msg *msg; - - nl_sock = nl_socket_alloc(); - msg = nlmsg_alloc(); - - genl_connect(nl_sock); - - genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_REQUEST, L2TP_CMD_TUNNEL_CREATE, L2TP_GENL_VERSION); - nla_put_u16(msg, L2TP_ATTR_ENCAP_TYPE, L2TP_ENCAPTYPE_UDP); - nla_put_u8(msg, L2TP_ATTR_PROTO_VERSION, 2); - nla_put_u32(msg, L2TP_ATTR_CONN_ID, tid); - nla_put_u32(msg, L2TP_ATTR_PEER_CONN_ID, peer_tid); - nla_put_u32(msg, L2TP_ATTR_FD, fd); - //nla_put_u32(msg, L2TP_ATTR_DEBUG, 0xffffffff); - - nl_send_auto_complete(nl_sock, msg); - nl_recvmsgs_default(nl_sock); - - nlmsg_free(msg); - nl_close(nl_sock); - nl_socket_free(nl_sock); -} - -void l2tp_nl_create_session(int tid, int sid, int peer_sid) -{ - struct nl_sock *nl_sock; - struct nl_msg *msg; - - nl_sock = nl_socket_alloc(); - msg = nlmsg_alloc(); - - genl_connect(nl_sock); - - genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_REQUEST, L2TP_CMD_SESSION_CREATE, L2TP_GENL_VERSION); - nla_put_u32(msg, L2TP_ATTR_CONN_ID, tid); - nla_put_u32(msg, L2TP_ATTR_SESSION_ID, sid); - nla_put_u32(msg, L2TP_ATTR_PEER_SESSION_ID, peer_sid); - nla_put_u16(msg, L2TP_ATTR_PW_TYPE, L2TP_PWTYPE_PPP); - nla_put_u8(msg, L2TP_ATTR_LNS_MODE, 1); - //nla_put_u32(msg, L2TP_ATTR_DEBUG, 0xffffffff); - - nl_send_auto_complete(nl_sock, msg); - nl_recvmsgs_default(nl_sock); - - nlmsg_free(msg); - nl_close(nl_sock); - nl_socket_free(nl_sock); -} - -static void __init init(void) -{ - struct nl_sock *nl_sock = nl_socket_alloc(); - - genl_connect(nl_sock); - - family = genl_ctrl_resolve(nl_sock, L2TP_GENL_NAME); - - nl_close(nl_sock); - nl_socket_free(nl_sock); -} - diff --git a/accel-pptpd/ctrl/l2tp/packet.c b/accel-pptpd/ctrl/l2tp/packet.c deleted file mode 100644 index e3f6896..0000000 --- a/accel-pptpd/ctrl/l2tp/packet.c +++ /dev/null @@ -1,494 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -#include "triton.h" -#include "log.h" -#include "mempool.h" -#include "memdebug.h" - -#include "l2tp.h" -#include "attr_defs.h" - -static mempool_t attr_pool; -static mempool_t pack_pool; -static mempool_t buf_pool; - -void l2tp_packet_print(struct l2tp_packet_t *pack, void (*print)(const char *fmt, ...)) -{ - struct l2tp_attr_t *attr; - struct l2tp_dict_value_t *val; - - if (pack->hdr.ver == 2) { - print("[L2TP tid=%i sid=%i", ntohs(pack->hdr.tid), ntohs(pack->hdr.sid)); - log_ppp_debug(" Ns=%i Nr=%i", ntohs(pack->hdr.Ns), ntohs(pack->hdr.Nr)); - } else { - print("[L2TP cid=%u", pack->hdr.cid); - log_ppp_debug(" Ns=%i Nr=%i", ntohs(pack->hdr.Ns), ntohs(pack->hdr.Nr)); - } - - list_for_each_entry(attr, &pack->attrs, entry) { - print(" <%s", attr->attr->name); - val = l2tp_dict_find_value(attr->attr, attr->val); - if (val) - print(" %s", val->name); - else { - switch (attr->attr->type) { - case ATTR_TYPE_INT16: - print(" %i", attr->val.int16); - break; - case ATTR_TYPE_INT32: - print(" %i", attr->val.int32); - break; - case ATTR_TYPE_STRING: - print(" %s", attr->val.string); - break; - } - } - print(">"); - } - - print("]\n"); -} - -struct l2tp_packet_t *l2tp_packet_alloc(int ver, int msg_type, struct sockaddr_in *addr) -{ - struct l2tp_packet_t *pack = mempool_alloc(pack_pool); - if (!pack) - return NULL; - - memset(pack, 0, sizeof(*pack)); - INIT_LIST_HEAD(&pack->attrs); - pack->hdr.ver = ver; - pack->hdr.T = 1; - pack->hdr.L = 1; - pack->hdr.S = 1; - memcpy(&pack->addr, addr, sizeof(*addr)); - - if (msg_type) { - if (l2tp_packet_add_int16(pack, Message_Type, msg_type, 1)) { - mempool_free(pack); - return NULL; - } - } - - return pack; -} - -void l2tp_packet_free(struct l2tp_packet_t *pack) -{ - struct l2tp_attr_t *attr; - - while (!list_empty(&pack->attrs)) { - attr = list_entry(pack->attrs.next, typeof(*attr), entry); - if (attr->attr->type == ATTR_TYPE_OCTETS || attr->attr->type == ATTR_TYPE_STRING) - _free(attr->val.octets); - list_del(&attr->entry); - mempool_free(attr); - } - - mempool_free(pack); -} - -int l2tp_recv(int fd, struct l2tp_packet_t **p, struct in_pktinfo *pkt_info) -{ - int n, length; - uint8_t *buf; - struct l2tp_hdr_t *hdr; - struct l2tp_avp_t *avp; - struct l2tp_dict_attr_t *da; - struct l2tp_attr_t *attr, *RV = NULL; - uint8_t *ptr; - struct l2tp_packet_t *pack; - struct sockaddr_in addr; - socklen_t len = sizeof(addr); - struct msghdr msg; - char msg_control[128]; - struct cmsghdr *cmsg; - - *p = NULL; - - if (pkt_info) { - memset(&msg, 0, sizeof(msg)); - msg.msg_control = msg_control; - msg.msg_controllen = 128; - - n = recvmsg(fd, &msg, MSG_PEEK); - - if (n < 0) { - if (errno == EAGAIN) - return -1; - log_error("l2tp: recvmsg: %s\n", strerror(errno)); - return 0; - } - - for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) { - if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO) { - memcpy(pkt_info, CMSG_DATA(cmsg), sizeof(*pkt_info)); - break; - } - } - } - - buf = mempool_alloc(buf_pool); - if (!buf) { - log_emerg("l2tp: out of memory\n"); - return 0; - } - hdr = (struct l2tp_hdr_t *)buf; - ptr = (uint8_t *)(hdr + 1); - - n = recvfrom(fd, buf, L2TP_MAX_PACKET_SIZE, 0, &addr, &len); - - if (n < 0) { - mempool_free(buf); - if (errno == EAGAIN) - return -1; - log_error("l2tp: recv: %s\n", strerror(errno)); - return 0; - } - - if (n < sizeof(*hdr)) { - if (conf_verbose) - log_warn("l2tp: short packet received (%i/%i)\n", n, sizeof(*hdr)); - goto out_err_hdr; - } - - if (n < ntohs(hdr->length)) { - if (conf_verbose) - log_warn("l2tp: short packet received (%i/%i)\n", n, ntohs(hdr->length)); - goto out_err_hdr; - } - - if (hdr->T == 0) - goto out_err_hdr; - - if (hdr->ver == 2) { - if (hdr->L == 0) { - if (conf_verbose) - log_warn("l2tp: incorrect message received (L=0)\n"); - goto out_err_hdr; - } - - if (hdr->S == 0) { - if (conf_verbose) - log_warn("l2tp: incorrect message received (S=0)\n"); - goto out_err_hdr; - } - - if (hdr->O == 1) { - if (conf_verbose) - log_warn("l2tp: incorrect message received (O=1)\n"); - goto out_err_hdr; - } - } else if (hdr->ver != 3) { - if (conf_verbose) - log_warn("l2tp: protocol version %i is not supported\n", hdr->ver); - goto out_err_hdr; - } - - pack = mempool_alloc(pack_pool); - if (!pack) { - log_emerg("l2tp: out of memory\n"); - goto out_err_hdr; - } - - memset(pack, 0, sizeof(*pack)); - INIT_LIST_HEAD(&pack->attrs); - - memcpy(&pack->addr, &addr, sizeof(addr)); - memcpy(&pack->hdr, hdr, sizeof(*hdr)); - length = ntohs(hdr->length) - sizeof(*hdr); - - while (length) { - *(uint16_t *)ptr = ntohs(*(uint16_t *)ptr); - avp = (struct l2tp_avp_t *)ptr; - - if (avp->length > length) { - if (conf_verbose) - log_warn("l2tp: incorrect avp received (exceeds message length)\n"); - goto out_err; - } - - if (avp->vendor) - goto skip; - - da = l2tp_dict_find_attr_by_id(ntohs(avp->type)); - if (!da) { - if (conf_verbose) - log_warn("l2tp: unknown avp received (type=%i, M=%u)\n", ntohs(avp->type), avp->M); - if (avp->M) - goto out_err; - } else { - if (da->M != -1 && da->M != avp->M) { - if (conf_verbose) - log_warn("l2tp: incorrect avp received (type=%i, M=%i, must be %i)\n", ntohs(avp->type), avp->M, da->M); - goto out_err; - } - - if (da->H != -1 && da->H != avp->H) { - if (conf_verbose) - log_warn("l2tp: incorrect avp received (type=%i, H=%i, must be %i)\n", ntohs(avp->type), avp->H, da->H); - goto out_err; - } - - if (avp->H) { - if (!RV) { - if (conf_verbose) - log_warn("l2tp: incorrect avp received (type=%i, H=1, but Random-Vector is not received)\n", ntohs(avp->type)); - goto out_err; - } else { - if (conf_verbose) - log_warn("l2tp: hidden avp received (type=%i)\n", ntohs(avp->type)); - } - } - - attr = mempool_alloc(attr_pool); - memset(attr, 0, sizeof(*attr)); - list_add_tail(&attr->entry, &pack->attrs); - - attr->attr = da; - attr->M = avp->M; - attr->H = avp->H; - attr->length = avp->length - sizeof(*avp); - - if (attr->attr->id == Random_Vector) - RV = attr; - - switch (da->type) { - case ATTR_TYPE_INT16: - if (avp->length != sizeof(*avp) + 2) - goto out_err_len; - attr->val.uint16 = ntohs(*(uint16_t *)avp->val); - break; - case ATTR_TYPE_INT32: - if (avp->length != sizeof(*avp) + 4) - goto out_err_len; - attr->val.uint32 = ntohl(*(uint32_t *)avp->val); - break; - case ATTR_TYPE_INT64: - if (avp->length != sizeof(*avp) + 8) - goto out_err_len; - attr->val.uint64 = *(uint64_t *)avp->val; - break; - case ATTR_TYPE_OCTETS: - attr->val.octets = _malloc(attr->length); - if (!attr->val.octets) - goto out_err_mem; - memcpy(attr->val.octets, avp->val, attr->length); - break; - case ATTR_TYPE_STRING: - attr->val.string = _malloc(attr->length + 1); - if (!attr->val.string) - goto out_err_mem; - memcpy(attr->val.string, avp->val, attr->length); - attr->val.string[attr->length] = 0; - break; - } - } -skip: - ptr += avp->length; - length -= avp->length; - } - - *p = pack; - - mempool_free(buf); - - return 0; - -out_err: - l2tp_packet_free(pack); -out_err_hdr: - mempool_free(buf); - return 0; -out_err_len: - if (conf_verbose) - log_warn("l2tp: incorrect avp received (type=%i, incorrect length %i)\n", ntohs(avp->type), avp->length); - goto out_err; -out_err_mem: - log_emerg("l2tp: out of memory\n"); - goto out_err; -} - -int l2tp_packet_send(int sock, struct l2tp_packet_t *pack) -{ - uint8_t *buf = mempool_alloc(buf_pool); - struct l2tp_avp_t *avp; - struct l2tp_attr_t *attr; - uint8_t *ptr; - int n; - int len = sizeof(pack->hdr); - - if (!buf) { - log_emerg("l2tp: out of memory\n"); - return -1; - } - - memset(buf, 0, L2TP_MAX_PACKET_SIZE); - - ptr = buf + sizeof(pack->hdr); - - list_for_each_entry(attr, &pack->attrs, entry) { - if (len + sizeof(*avp) + attr->length >= L2TP_MAX_PACKET_SIZE) { - log_error("l2tp: cann't send packet (exceeds maximum size)\n"); - mempool_free(buf); - return -1; - } - avp = (struct l2tp_avp_t *)ptr; - avp->type = htons(attr->attr->id); - avp->M = attr->M; - avp->H = attr->H; - avp->length = sizeof(*avp) + attr->length; - *(uint16_t *)ptr = htons(*(uint16_t *)ptr); - switch (attr->attr->type) { - case ATTR_TYPE_INT16: - *(int16_t *)avp->val = htons(attr->val.int16); - break; - case ATTR_TYPE_INT32: - *(int32_t *)avp->val = htonl(attr->val.int32); - break; - case ATTR_TYPE_STRING: - case ATTR_TYPE_OCTETS: - memcpy(avp->val, attr->val.string, attr->length); - break; - } - - ptr += sizeof(*avp) + attr->length; - len += sizeof(*avp) + attr->length; - } - - pack->hdr.length = htons(len); - memcpy(buf, &pack->hdr, sizeof(pack->hdr)); - - n = write(sock, buf, ntohs(pack->hdr.length)); - - mempool_free(buf); - - if (n < 0) { - if (errno == EAGAIN) { - if (conf_verbose) - log_warn("l2tp: buffer overflow (packet lost)\n"); - } else { - if (conf_verbose) - log_warn("l2tp: sendto: %s\n", strerror(errno)); - return -1; - } - } - - if (n != ntohs(pack->hdr.length)) { - if (conf_verbose) - log_warn("l2tp: short write (%i/%i)\n", n, ntohs(pack->hdr.length)); - } - - return 0; -} - -static struct l2tp_attr_t *attr_alloc(int id, int M) -{ - struct l2tp_attr_t *attr; - struct l2tp_dict_attr_t *da; - - da = l2tp_dict_find_attr_by_id(id); - if (!da) - return NULL; - - attr = mempool_alloc(attr_pool); - if (!attr) { - log_emerg("l2tp: out of memory\n"); - return NULL; - } - - memset(attr, 0, sizeof(*attr)); - - attr->attr = da; - - if (da->M != -1) - attr->M = da->M; - else - attr->M = M; - - //if (da->H != -1) - //attr->H = da->H; - - return attr; -} - -int l2tp_packet_add_int16(struct l2tp_packet_t *pack, int id, int16_t val, int M) -{ - struct l2tp_attr_t *attr = attr_alloc(id, M); - - if (!attr) - return -1; - - attr->length = 2; - attr->val.int16 = val; - list_add_tail(&attr->entry, &pack->attrs); - - return 0; -} -int l2tp_packet_add_int32(struct l2tp_packet_t *pack, int id, int32_t val, int M) -{ - struct l2tp_attr_t *attr = attr_alloc(id, M); - - if (!attr) - return -1; - - attr->length = 4; - attr->val.int32 = val; - list_add_tail(&attr->entry, &pack->attrs); - - return 0; -} -int l2tp_packet_add_string(struct l2tp_packet_t *pack, int id, const char *val, int M) -{ - struct l2tp_attr_t *attr = attr_alloc(id, M); - - if (!attr) - return -1; - - attr->length = strlen(val); - attr->val.string = _strdup(val); - if (!attr->val.string) { - log_emerg("l2tp: out of memory\n"); - mempool_free(attr); - return -1; - } - memcpy(attr->val.string, val, attr->length); - list_add_tail(&attr->entry, &pack->attrs); - - return 0; -} - -int l2tp_packet_add_octets(struct l2tp_packet_t *pack, int id, const uint8_t *val, int size, int M) -{ - struct l2tp_attr_t *attr = attr_alloc(id, M); - - if (!attr) - return -1; - - attr->length = size; - attr->val.octets = _malloc(size); - if (!attr->val.string) { - log_emerg("l2tp: out of memory\n"); - mempool_free(attr); - return -1; - } - memcpy(attr->val.octets, val, attr->length); - list_add_tail(&attr->entry, &pack->attrs); - - return 0; -} - -static void __init init(void) -{ - attr_pool = mempool_create(sizeof(struct l2tp_attr_t)); - pack_pool = mempool_create(sizeof(struct l2tp_packet_t)); - buf_pool = mempool_create(L2TP_MAX_PACKET_SIZE); -} - diff --git a/accel-pptpd/ctrl/pppoe/CMakeLists.txt b/accel-pptpd/ctrl/pppoe/CMakeLists.txt deleted file mode 100644 index f047936..0000000 --- a/accel-pptpd/ctrl/pppoe/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) - -SET(sources - pppoe.c - mac_filter.c - dpado.c - cli.c -) - -IF (RADIUS) -SET(sources ${sources} tr101.c) -ENDIF(RADIUS) - -ADD_LIBRARY(pppoe SHARED ${sources}) -TARGET_LINK_LIBRARIES(pppoe crypto) - -INSTALL(TARGETS pppoe LIBRARY DESTINATION lib/accel-pptp) diff --git a/accel-pptpd/ctrl/pppoe/cli.c b/accel-pptpd/ctrl/pppoe/cli.c deleted file mode 100644 index 9929f66..0000000 --- a/accel-pptpd/ctrl/pppoe/cli.c +++ /dev/null @@ -1,205 +0,0 @@ -#include -#include -#include -#include - -#include "triton.h" -#include "cli.h" -#include "ppp.h" -#include "memdebug.h" - -#include "pppoe.h" - -static void show_interfaces(void *cli) -{ - struct pppoe_serv_t *serv; - - cli_send(cli, "interface: connections: state:\r\n"); - cli_send(cli, "-----------------------------------\r\n"); - - pthread_rwlock_rdlock(&serv_lock); - list_for_each_entry(serv, &serv_list, entry) { - cli_sendv(cli, "%9s %11u %6s\r\n", serv->ifname, serv->conn_cnt, serv->stopping ? "stop" : "active"); - } - pthread_rwlock_unlock(&serv_lock); -} - -static void intf_help(char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "pppoe interface add - start pppoe server on specified interface\r\n"); - cli_send(client, "pppoe interface del - stop pppoe server on specified interface and drop his connections\r\n"); - cli_send(client, "pppoe interface show - show interfaces on which pppoe server started\r\n"); -} - -static int intf_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) -{ - if (fields_cnt == 2) - goto help; - - if (fields_cnt == 3) { - if (!strcmp(fields[2], "show")) - show_interfaces(client); - else - goto help; - - return CLI_CMD_OK; - } - - if (fields_cnt != 4) - goto help; - - if (!strcmp(fields[2], "add")) - pppoe_server_start(fields[3], client); - else if (!strcmp(fields[2], "del")) - pppoe_server_stop(fields[3]); - else - goto help; - - return CLI_CMD_OK; -help: - intf_help(fields, fields_cnt, client); - return CLI_CMD_OK; -} - -//=================================== - -static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "pppoe:\r\n"); - cli_sendv(client, " active: %u\r\n", stat_active); - cli_sendv(client, " delayed PADO: %u\r\n", stat_delayed_pado); - cli_sendv(client, " recv PADI: %lu\r\n", stat_PADI_recv); - cli_sendv(client, " sent PADO: %lu\r\n", stat_PADO_sent); - cli_sendv(client, " recv PADR(dup): %lu(%lu)\r\n", stat_PADR_recv, stat_PADR_dup_recv); - cli_sendv(client, " sent PADS: %lu\r\n", stat_PADS_sent); - - return CLI_CMD_OK; -} - -//=================================== - -static void set_verbose_help(char * const *f, int f_cnt, void *cli) -{ - cli_send(cli, "pppoe set verbose - set verbosity of pppoe logging\r\n"); - cli_send(cli, "pppoe set PADO-delay - set PADO delays (ms)\r\n"); - cli_send(cli, "pppoe set Service-Name - set Service-Name to respond\r\n"); - cli_send(cli, "pppoe set Service-Name * - respond with client's Service-Name\r\n"); - cli_send(cli, "pppoe set AC-Name - set AC-Name tag value\r\n"); - cli_send(cli, "pppoe show verbose - show current verbose value\r\n"); - cli_send(cli, "pppoe show PADO-delay - show current PADO delay value\r\n"); - cli_send(cli, "pppoe show Service-Name - show current Service-Name value\r\n"); - cli_send(cli, "pppoe show AC-Name - show current AC-Name tag value\r\n"); -} - -static int show_verbose_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - if (f_cnt != 3) - return CLI_CMD_SYNTAX; - - cli_sendv(cli, "%i\r\n", conf_verbose); - - return CLI_CMD_OK; -} - -static int show_pado_delay_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - if (f_cnt != 3) - return CLI_CMD_SYNTAX; - - cli_sendv(cli, "%s\r\n", conf_pado_delay); - - return CLI_CMD_OK; -} - -static int show_service_name_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - if (f_cnt != 3) - return CLI_CMD_SYNTAX; - - if (conf_service_name) - cli_sendv(cli, "%s\r\n", conf_service_name); - else - cli_sendv(cli, "*\r\n", conf_service_name); - - return CLI_CMD_OK; -} - -static int show_ac_name_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - if (f_cnt != 3) - return CLI_CMD_SYNTAX; - - cli_sendv(cli, "%s\r\n", conf_ac_name); - - return CLI_CMD_OK; -} - -static int set_verbose_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - if (f_cnt != 4) - return CLI_CMD_SYNTAX; - - if (!strcmp(f[3], "0")) - conf_verbose = 0; - else if (!strcmp(f[3], "1")) - conf_verbose = 1; - else - return CLI_CMD_INVAL; - - return CLI_CMD_OK; -} - -static int set_pado_delay_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - if (f_cnt != 4) - return CLI_CMD_SYNTAX; - - if (dpado_parse(f[3])) - return CLI_CMD_INVAL; - - return CLI_CMD_OK; -} - -static int set_service_name_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - if (f_cnt != 4) - return CLI_CMD_SYNTAX; - - if (conf_service_name) - _free(conf_service_name); - - if (!strcmp(f[3], "*")) - conf_service_name = NULL; - else - conf_service_name = _strdup(f[3]); - - return CLI_CMD_OK; -} - -static int set_ac_name_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - if (f_cnt != 4) - return CLI_CMD_SYNTAX; - - _free(conf_ac_name); - conf_ac_name = _strdup(f[3]); - - return CLI_CMD_OK; -} -//=================================== - - -static void __init init(void) -{ - cli_register_simple_cmd2(show_stat_exec, NULL, 2, "show", "stat"); - cli_register_simple_cmd2(intf_exec, intf_help, 2, "pppoe", "interface"); - cli_register_simple_cmd2(set_verbose_exec, set_verbose_help, 3, "pppoe", "set", "verbose"); - cli_register_simple_cmd2(set_pado_delay_exec, NULL, 3, "pppoe", "set", "PADO-delay"); - cli_register_simple_cmd2(set_service_name_exec, NULL, 3, "pppoe", "set", "Service-Name"); - cli_register_simple_cmd2(set_ac_name_exec, NULL, 3, "pppoe", "set", "AC-Name"); - cli_register_simple_cmd2(show_verbose_exec, NULL, 3, "pppoe", "show", "verbose"); - cli_register_simple_cmd2(show_pado_delay_exec, NULL, 3, "pppoe", "show", "PADO-delay"); - cli_register_simple_cmd2(show_service_name_exec, NULL, 3, "pppoe", "show", "Service-Name"); - cli_register_simple_cmd2(show_ac_name_exec, NULL, 3, "pppoe", "show", "AC-Name"); -} - diff --git a/accel-pptpd/ctrl/pppoe/dpado.c b/accel-pptpd/ctrl/pppoe/dpado.c deleted file mode 100644 index 3f56519..0000000 --- a/accel-pptpd/ctrl/pppoe/dpado.c +++ /dev/null @@ -1,162 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include "list.h" -#include "cli.h" -#include "triton.h" -#include "log.h" -#include "memdebug.h" - -#include "pppoe.h" - -struct dpado_range_t -{ - struct list_head entry; - unsigned int conn_cnt; - int pado_delay; -}; - -static pthread_mutex_t dpado_range_lock = PTHREAD_MUTEX_INITIALIZER; -static LIST_HEAD(dpado_range_list); -static struct dpado_range_t *dpado_range_next; -static struct dpado_range_t *dpado_range_prev; -int pado_delay; - -void dpado_check_next(int conn_cnt) -{ - pthread_mutex_lock(&dpado_range_lock); - if (dpado_range_next && conn_cnt == dpado_range_next->conn_cnt) { - pado_delay = dpado_range_next->pado_delay; - dpado_range_prev = dpado_range_next; - if (dpado_range_next->entry.next != &dpado_range_list) - dpado_range_next = list_entry(dpado_range_next->entry.next, typeof(*dpado_range_next), entry); - else - dpado_range_next = NULL; - /*printf("active=%i, prev=%i:%i, next=%i:%i, pado_delay=%i\n", stat_active, - dpado_range_prev?dpado_range_prev->pado_delay:0,dpado_range_prev?dpado_range_prev->conn_cnt:0, - dpado_range_next?dpado_range_next->pado_delay:0,dpado_range_next?dpado_range_next->conn_cnt:0, - pado_delay);*/ - } - pthread_mutex_unlock(&dpado_range_lock); -} - -void dpado_check_prev(int conn_cnt) -{ - pthread_mutex_lock(&dpado_range_lock); - if (dpado_range_prev && conn_cnt == dpado_range_prev->conn_cnt) { - dpado_range_next = dpado_range_prev; - dpado_range_prev = list_entry(dpado_range_prev->entry.prev, typeof(*dpado_range_prev), entry); - pado_delay = dpado_range_prev->pado_delay; - /*printf("active=%i, prev=%i:%i, next=%i:%i, pado_delay=%i\n", stat_active, - dpado_range_prev?dpado_range_prev->pado_delay:0,dpado_range_prev?dpado_range_prev->conn_cnt:0, - dpado_range_next?dpado_range_next->pado_delay:0,dpado_range_next?dpado_range_next->conn_cnt:0, - pado_delay);*/ - } - pthread_mutex_unlock(&dpado_range_lock); -} - -static void strip(char *str) -{ - char *ptr = str; - char *endptr = strchr(str, 0); - while (1) { - ptr = strchr(ptr, ' '); - if (ptr) - memmove(ptr, ptr + 1, endptr - ptr - 1); - else - break; - } -} - -int dpado_parse(const char *str) -{ - char *str1 = _strdup(str); - char *ptr1, *ptr2, *ptr3, *endptr; - LIST_HEAD(range_list); - struct dpado_range_t *r; - - strip(str1); - - ptr1 = str1; - - while (1) { - ptr2 = strchr(ptr1, ','); - if (ptr2) - *ptr2 = 0; - ptr3 = strchr(ptr1, ':'); - if (ptr3) - *ptr3 = 0; - - r = _malloc(sizeof(*r)); - memset(r, 0, sizeof(*r)); - - r->pado_delay = strtol(ptr1, &endptr, 10); - if (*endptr) - goto out_err; - - if (list_empty(&range_list)) - r->conn_cnt = INT_MAX; - else { - if (!ptr3) - goto out_err; - r->conn_cnt = strtol(ptr3 + 1, &endptr, 10); - if (*endptr) - goto out_err; - } - - list_add_tail(&r->entry, &range_list); - //printf("parsed range: %i:%i\n", r->pado_delay, r->conn_cnt); - - if (!ptr2) - break; - - ptr1 = ptr2 + 1; - } - - pthread_mutex_lock(&dpado_range_lock); - while (!list_empty(&dpado_range_list)) { - r = list_entry(dpado_range_list.next, typeof(*r), entry); - list_del(&r->entry); - _free(r); - } - - dpado_range_next = NULL; - dpado_range_prev = NULL; - - while (!list_empty(&range_list)) { - r = list_entry(range_list.next, typeof(*r), entry); - list_del(&r->entry); - list_add_tail(&r->entry, &dpado_range_list); - - if (!dpado_range_prev || stat_active >= r->conn_cnt) - dpado_range_prev = r; - else if (!dpado_range_next) - dpado_range_next = r; - } - - pado_delay = dpado_range_prev->pado_delay; - - if (conf_pado_delay) - _free(conf_pado_delay); - conf_pado_delay = _strdup(str); - /*printf("active=%i, prev=%i:%i, next=%i:%i, pado_delay=%i\n", stat_active, - dpado_range_prev?dpado_range_prev->pado_delay:0,dpado_range_prev?dpado_range_prev->conn_cnt:0, - dpado_range_next?dpado_range_next->pado_delay:0,dpado_range_next?dpado_range_next->conn_cnt:0, - pado_delay);*/ - - pthread_mutex_unlock(&dpado_range_lock); - - _free(str1); - return 0; - -out_err: - _free(str1); - log_emerg("pppoe: pado_delay: invalid format\n"); - return -1; -} - diff --git a/accel-pptpd/ctrl/pppoe/mac_filter.c b/accel-pptpd/ctrl/pppoe/mac_filter.c deleted file mode 100644 index 9b101c6..0000000 --- a/accel-pptpd/ctrl/pppoe/mac_filter.c +++ /dev/null @@ -1,255 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "list.h" -#include "cli.h" -#include "triton.h" -#include "log.h" -#include "ppp.h" -#include "memdebug.h" - -#include "pppoe.h" - -struct mac_t -{ - struct list_head entry; - uint8_t addr[ETH_ALEN]; -}; - -static LIST_HEAD(mac_list); -static int type; // -1 - disabled, 1 - allow, 0 - denied -static pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER; -static const char *conf_mac_filter; - -int mac_filter_check(const uint8_t *addr) -{ - struct mac_t *mac; - int res = type; - - if (type == -1) - return 0; - - pthread_rwlock_rdlock(&lock); - list_for_each_entry(mac, &mac_list, entry) { - if (memcmp(mac->addr, addr, ETH_ALEN)) - continue; - res = !type; - break; - } - pthread_rwlock_unlock(&lock); - - return res; -} - -static int mac_filter_load(const char *opt) -{ - struct mac_t *mac; - FILE *f; - char *c; - char *name = _strdup(opt); - char *buf = _malloc(1024); - int n[ETH_ALEN]; - int i, line = 0; - - c = strstr(name, ","); - if (!c) - goto err_inval; - - *c = 0; - - if (!strcmp(c + 1, "allow")) - type = 1; - else if (!strcmp(c + 1, "deny")) - type = 0; - else - goto err_inval; - - f = fopen(name, "r"); - if (!f) { - log_emerg("pppoe: open '%s': %s\n", name, strerror(errno)); - goto err; - } - - conf_mac_filter = opt; - - pthread_rwlock_wrlock(&lock); - while (!list_empty(&mac_list)) { - mac = list_entry(mac_list.next, typeof(*mac), entry); - list_del(&mac->entry); - _free(mac); - } - - while (fgets(buf, 1024, f)) { - line++; - if (buf[0] == '#' || buf[0] == ';' || buf[0] == '\n') - continue; - if (sscanf(buf, "%x:%x:%x:%x:%x:%x", - n + 0, n + 1, n + 2, n + 3, n + 4, n + 5) != 6) { - log_warn("pppoe: mac-filter:%s:%i: address is invalid\n", name, line); - continue; - } - mac = _malloc(sizeof(*mac)); - for (i = 0; i < ETH_ALEN; i++) { - if (n[i] > 255) { - log_warn("pppoe: mac-filter:%s:%i: address is invalid\n", name, line); - _free(mac); - continue; - } - mac->addr[i] = n[i]; - } - list_add_tail(&mac->entry, &mac_list); - } - pthread_rwlock_unlock(&lock); - - fclose(f); - - _free(name); - _free(buf); - - return 0; - -err_inval: - log_emerg("pppoe: mac-filter format is invalid\n"); -err: - _free(name); - _free(buf); - return -1; -} - -static void mac_filter_add(const char *addr, void *client) -{ - int n[ETH_ALEN]; - struct mac_t *mac; - int i; - - if (sscanf(addr, "%x:%x:%x:%x:%x:%x", - n + 0, n + 1, n + 2, n + 3, n + 4, n + 5) != 6) { - cli_send(client, "invalid format\r\n"); - return; - } - - mac = _malloc(sizeof(*mac)); - for (i = 0; i < ETH_ALEN; i++) { - if (n[i] > 255) { - _free(mac); - cli_send(client, "invalid format\r\n"); - return; - } - mac->addr[i] = n[i]; - } - - pthread_rwlock_wrlock(&lock); - list_add_tail(&mac->entry, &mac_list); - pthread_rwlock_unlock(&lock); -} - -static void mac_filter_del(const char *addr, void *client) -{ - int n[ETH_ALEN]; - uint8_t a[ETH_ALEN]; - struct mac_t *mac; - int i; - int found = 0; - - if (sscanf(addr, "%x:%x:%x:%x:%x:%x", - n + 0, n + 1, n + 2, n + 3, n + 4, n + 5) != 6) { - cli_send(client, "invalid format\r\n"); - return; - } - - for (i = 0; i < ETH_ALEN; i++) { - if (n[i] > 255) { - cli_send(client, "invalid format\r\n"); - return; - } - a[i] = n[i]; - } - - pthread_rwlock_wrlock(&lock); - list_for_each_entry(mac, &mac_list, entry) { - if (memcmp(a, mac->addr, ETH_ALEN)) - continue; - list_del(&mac->entry); - _free(mac); - found = 1; - break; - } - pthread_rwlock_unlock(&lock); - - if (!found) - cli_send(client, "not found\r\n"); -} - -static void mac_filter_show(void *client) -{ - struct mac_t *mac; - const char *filter_type; - - if (type == 0) - filter_type = "deny"; - else if (type == 1) - filter_type = "allow"; - else - filter_type = "disabled"; - - cli_sendv(client, "filter type: %s\r\n", filter_type); - - pthread_rwlock_rdlock(&lock); - list_for_each_entry(mac, &mac_list, entry) { - cli_sendv(client, "%02x:%02x:%02x:%02x:%02x:%02x\r\n", - mac->addr[0], mac->addr[1], mac->addr[2], - mac->addr[3], mac->addr[4], mac->addr[5]); - } - pthread_rwlock_unlock(&lock); -} - -static void cmd_help(char * const *fields, int fields_cnt, void *client); -static int cmd_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) -{ - if (fields_cnt == 2) - goto help; - - if (!strcmp(fields[2], "reload")) { - if (!conf_mac_filter) - cli_send(client, "error: mac-filter was not specified in the config\r\n"); - else if (mac_filter_load(conf_mac_filter)) - cli_send(client, "error: check logs\r\n"); - } else if (!strcmp(fields[2], "add")) { - if (fields_cnt != 4) - goto help; - mac_filter_add(fields[3], client); - } else if (!strcmp(fields[2], "del")) { - if (fields_cnt != 4) - goto help; - mac_filter_del(fields[3], client); - } else if (!strcmp(fields[2], "show")) { - mac_filter_show(client); - } - - return CLI_CMD_OK; -help: - cmd_help(fields, fields_cnt, client); - return CLI_CMD_OK; -} - -static void cmd_help(char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "pppoe mac-filter reload - reload mac-filter file\r\n"); - cli_send(client, "pppoe mac-filter add
- add address to mac-filter list\r\n"); - cli_send(client, "pppoe mac-filter del
- delete address from mac-filter list\r\n"); - cli_send(client, "pppoe mac-filter show - show current mac-filter list\r\n"); -} - -static void __init init(void) -{ - const char *opt = conf_get_opt("pppoe", "mac-filter"); - if (!opt || mac_filter_load(opt)) - type = -1; - - cli_register_simple_cmd2(cmd_exec, cmd_help, 2, "pppoe", "mac-filter"); -} - diff --git a/accel-pptpd/ctrl/pppoe/pppoe.c b/accel-pptpd/ctrl/pppoe/pppoe.c deleted file mode 100644 index 95ae394..0000000 --- a/accel-pptpd/ctrl/pppoe/pppoe.c +++ /dev/null @@ -1,1288 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "events.h" -#include "triton.h" -#include "log.h" -#include "ppp.h" -#include "mempool.h" -#include "cli.h" - -#ifdef RADIUS -#include "radius.h" -#endif - -#include "pppoe.h" - -#include "memdebug.h" - -struct pppoe_conn_t -{ - struct list_head entry; - struct triton_context_t ctx; - struct pppoe_serv_t *serv; - int disc_sock; - uint16_t sid; - uint8_t addr[ETH_ALEN]; - int ppp_started:1; - - struct pppoe_tag *relay_sid; - struct pppoe_tag *host_uniq; - struct pppoe_tag *service_name; - struct pppoe_tag *tr101; - uint8_t cookie[COOKIE_LENGTH]; - - struct ppp_ctrl_t ctrl; - struct ppp_t ppp; -#ifdef RADIUS - struct rad_plugin_t radius; -#endif -}; - -struct delayed_pado_t -{ - struct list_head entry; - struct triton_timer_t timer; - struct pppoe_serv_t *serv; - uint8_t addr[ETH_ALEN]; - struct pppoe_tag *host_uniq; - struct pppoe_tag *relay_sid; - struct pppoe_tag *service_name; -}; - -int conf_verbose; -char *conf_service_name; -char *conf_ac_name; -int conf_ifname_in_sid; -char *conf_pado_delay; - -static mempool_t conn_pool; -static mempool_t pado_pool; - -unsigned int stat_active; -unsigned int stat_delayed_pado; -unsigned long stat_PADI_recv; -unsigned long stat_PADO_sent; -unsigned long stat_PADR_recv; -unsigned long stat_PADR_dup_recv; -unsigned long stat_PADS_sent; - -pthread_rwlock_t serv_lock = PTHREAD_RWLOCK_INITIALIZER; -LIST_HEAD(serv_list); - -static uint8_t bc_addr[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; - -static void pppoe_send_PADT(struct pppoe_conn_t *conn); -static void _server_stop(struct pppoe_serv_t *serv); -void pppoe_server_free(struct pppoe_serv_t *serv); -static int init_secret(struct pppoe_serv_t *serv); - -static void disconnect(struct pppoe_conn_t *conn) -{ - if (conn->ppp_started) { - dpado_check_prev(__sync_fetch_and_sub(&stat_active, 1)); - conn->ppp_started = 0; - ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); - } - - pppoe_send_PADT(conn); - - close(conn->disc_sock); - - - triton_event_fire(EV_CTRL_FINISHED, &conn->ppp); - - log_ppp_info1("disconnected\n"); - - pthread_mutex_lock(&conn->serv->lock); - conn->serv->conn[conn->sid] = NULL; - list_del(&conn->entry); - conn->serv->conn_cnt--; - if (conn->serv->stopping && conn->serv->conn_cnt == 0) { - pthread_mutex_unlock(&conn->serv->lock); - pppoe_server_free(conn->serv); - } else - pthread_mutex_unlock(&conn->serv->lock); - - _free(conn->ctrl.calling_station_id); - _free(conn->ctrl.called_station_id); - _free(conn->service_name); - if (conn->host_uniq) - _free(conn->host_uniq); - if (conn->relay_sid) - _free(conn->relay_sid); - - triton_context_unregister(&conn->ctx); - - mempool_free(conn); -} - -static void ppp_started(struct ppp_t *ppp) -{ - log_ppp_debug("pppoe: ppp started\n"); -} - -static void ppp_finished(struct ppp_t *ppp) -{ - struct pppoe_conn_t *conn = container_of(ppp, typeof(*conn), ppp); - - log_ppp_debug("pppoe: ppp finished\n"); - - if (conn->ppp_started) { - dpado_check_prev(__sync_fetch_and_sub(&stat_active, 1)); - conn->ppp_started = 0; - triton_context_call(&conn->ctx, (triton_event_func)disconnect, conn); - } -} - -static void pppoe_conn_close(struct triton_context_t *ctx) -{ - struct pppoe_conn_t *conn = container_of(ctx, typeof(*conn), ctx); - - if (conn->ppp_started) - ppp_terminate(&conn->ppp, TERM_ADMIN_RESET, 0); - else - disconnect(conn); -} - -#ifdef RADIUS -static int pppoe_rad_send_access_request(struct rad_plugin_t *rad, struct rad_packet_t *pack) -{ - struct pppoe_conn_t *conn = container_of(rad, typeof(*conn), radius); - - if (conn->tr101) - return tr101_send_access_request(conn->tr101, pack); - - return 0; -} - -static int pppoe_rad_send_accounting_request(struct rad_plugin_t *rad, struct rad_packet_t *pack) -{ - struct pppoe_conn_t *conn = container_of(rad, typeof(*conn), radius); - - if (conn->tr101) - return tr101_send_accounting_request(conn->tr101, pack); - - return 0; -} -#endif - -static struct pppoe_conn_t *allocate_channel(struct pppoe_serv_t *serv, const uint8_t *addr, const struct pppoe_tag *host_uniq, const struct pppoe_tag *relay_sid, const struct pppoe_tag *service_name, const struct pppoe_tag *tr101, const uint8_t *cookie) -{ - struct pppoe_conn_t *conn; - int sid; - - conn = mempool_alloc(conn_pool); - if (!conn) { - log_emerg("pppoe: out of memory\n"); - return NULL; - } - - memset(conn, 0, sizeof(*conn)); - - pthread_mutex_lock(&serv->lock); - for (sid = serv->sid + 1; sid != serv->sid; sid++) { - if (sid == MAX_SID) - sid = 1; - if (!serv->conn[sid]) { - conn->sid = sid; - serv->sid = sid; - serv->conn[sid] = conn; - list_add_tail(&conn->entry, &serv->conn_list); - serv->conn_cnt++; - break; - } - } - pthread_mutex_unlock(&serv->lock); - - if (!conn->sid) { - log_warn("pppoe: no free sid available\n"); - mempool_free(conn); - return NULL; - } - - conn->serv = serv; - memcpy(conn->addr, addr, ETH_ALEN); - - if (host_uniq) { - conn->host_uniq = _malloc(sizeof(*host_uniq) + ntohs(host_uniq->tag_len)); - memcpy(conn->host_uniq, host_uniq, sizeof(*host_uniq) + ntohs(host_uniq->tag_len)); - } - - if (relay_sid) { - conn->relay_sid = _malloc(sizeof(*relay_sid) + ntohs(relay_sid->tag_len)); - memcpy(conn->relay_sid, relay_sid, sizeof(*relay_sid) + ntohs(relay_sid->tag_len)); - } - - if (tr101) { - conn->tr101 = _malloc(sizeof(*tr101) + ntohs(tr101->tag_len)); - memcpy(conn->tr101, tr101, sizeof(*tr101) + ntohs(tr101->tag_len)); - } - - conn->service_name = _malloc(sizeof(*service_name) + ntohs(service_name->tag_len)); - memcpy(conn->service_name, service_name, sizeof(*service_name) + ntohs(service_name->tag_len)); - - memcpy(conn->cookie, cookie, COOKIE_LENGTH); - - conn->ctx.before_switch = log_switch; - conn->ctx.close = pppoe_conn_close; - conn->ctrl.ctx = &conn->ctx; - conn->ctrl.started = ppp_started; - conn->ctrl.finished = ppp_finished; - conn->ctrl.max_mtu = MAX_PPPOE_MTU; - conn->ctrl.name = "pppoe"; - - conn->ctrl.calling_station_id = _malloc(IFNAMSIZ + 19); - conn->ctrl.called_station_id = _malloc(IFNAMSIZ + 19); - - if (conf_ifname_in_sid == 1 || conf_ifname_in_sid == 3) - sprintf(conn->ctrl.calling_station_id, "%s:%02x:%02x:%02x:%02x:%02x:%02x", serv->ifname, - addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); - else - sprintf(conn->ctrl.calling_station_id, "%02x:%02x:%02x:%02x:%02x:%02x", - addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); - - if (conf_ifname_in_sid == 2 || conf_ifname_in_sid == 3) - sprintf(conn->ctrl.called_station_id, "%s:%02x:%02x:%02x:%02x:%02x:%02x", serv->ifname, - serv->hwaddr[0], serv->hwaddr[1], serv->hwaddr[2], serv->hwaddr[3], serv->hwaddr[4], serv->hwaddr[5]); - else - sprintf(conn->ctrl.called_station_id, "%02x:%02x:%02x:%02x:%02x:%02x", - serv->hwaddr[0], serv->hwaddr[1], serv->hwaddr[2], serv->hwaddr[3], serv->hwaddr[4], serv->hwaddr[5]); - - ppp_init(&conn->ppp); - - conn->ppp.ctrl = &conn->ctrl; - conn->ppp.chan_name = conn->ctrl.calling_station_id; - - triton_context_register(&conn->ctx, &conn->ppp); - triton_context_wakeup(&conn->ctx); - - triton_event_fire(EV_CTRL_STARTING, &conn->ppp); - triton_event_fire(EV_CTRL_STARTED, &conn->ppp); - - conn->disc_sock = dup(serv->hnd.fd); - - return conn; -} - -static void connect_channel(struct pppoe_conn_t *conn) -{ - int sock; - struct sockaddr_pppox sp; - - sock = socket(AF_PPPOX, SOCK_STREAM, PX_PROTO_OE); - if (!sock) { - log_error("pppoe: socket(PPPOX): %s\n", strerror(errno)); - goto out_err; - } - - memset(&sp, 0, sizeof(sp)); - - sp.sa_family = AF_PPPOX; - sp.sa_protocol = PX_PROTO_OE; - sp.sa_addr.pppoe.sid = htons(conn->sid); - strcpy(sp.sa_addr.pppoe.dev, conn->serv->ifname); - memcpy(sp.sa_addr.pppoe.remote, conn->addr, ETH_ALEN); - - if (connect(sock, (struct sockaddr *)&sp, sizeof(sp))) { - log_error("pppoe: connect: %s\n", strerror(errno)); - goto out_err_close; - } - - conn->ppp.fd = sock; - - if (establish_ppp(&conn->ppp)) - goto out_err_close; - -#ifdef RADIUS - if (conn->tr101) { - conn->radius.send_access_request = pppoe_rad_send_access_request; - conn->radius.send_accounting_request = pppoe_rad_send_accounting_request; - rad_register_plugin(&conn->ppp, &conn->radius); - } -#endif - - conn->ppp_started = 1; - - dpado_check_next(__sync_add_and_fetch(&stat_active, 1)); - - return; - -out_err_close: - close(sock); -out_err: - disconnect(conn); -} - -static struct pppoe_conn_t *find_channel(struct pppoe_serv_t *serv, const uint8_t *cookie) -{ - struct pppoe_conn_t *conn; - - list_for_each_entry(conn, &serv->conn_list, entry) - if (!memcmp(conn->cookie, cookie, COOKIE_LENGTH)) - return conn; - - return NULL; -} - -static void print_tag_string(struct pppoe_tag *tag) -{ - int i; - - for (i = 0; i < ntohs(tag->tag_len); i++) - log_info2("%c", tag->tag_data[i]); -} - -static void print_tag_octets(struct pppoe_tag *tag) -{ - int i; - - for (i = 0; i < ntohs(tag->tag_len); i++) - log_info2("%02x", (uint8_t)tag->tag_data[i]); -} - -static void print_packet(uint8_t *pack) -{ - struct ethhdr *ethhdr = (struct ethhdr *)pack; - struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); - struct pppoe_tag *tag; - int n; - - log_info2("[PPPoE "); - - switch (hdr->code) { - case CODE_PADI: - log_info2("PADI"); - break; - case CODE_PADO: - log_info2("PADO"); - break; - case CODE_PADR: - log_info2("PADR"); - break; - case CODE_PADS: - log_info2("PADS"); - break; - case CODE_PADT: - log_info2("PADT"); - break; - } - - log_info2(" %02x:%02x:%02x:%02x:%02x:%02x => %02x:%02x:%02x:%02x:%02x:%02x", - ethhdr->h_source[0], ethhdr->h_source[1], ethhdr->h_source[2], ethhdr->h_source[3], ethhdr->h_source[4], ethhdr->h_source[5], - ethhdr->h_dest[0], ethhdr->h_dest[1], ethhdr->h_dest[2], ethhdr->h_dest[3], ethhdr->h_dest[4], ethhdr->h_dest[5]); - - log_info2(" sid=%04x", ntohs(hdr->sid)); - - for (n = 0; n < ntohs(hdr->length); n += sizeof(*tag) + ntohs(tag->tag_len)) { - tag = (struct pppoe_tag *)(pack + ETH_HLEN + sizeof(*hdr) + n); - switch (ntohs(tag->tag_type)) { - case TAG_END_OF_LIST: - log_info2(" "); - break; - case TAG_SERVICE_NAME: - log_info2(" "); - break; - case TAG_AC_NAME: - log_info2(" "); - break; - case TAG_HOST_UNIQ: - log_info2(" "); - break; - case TAG_AC_COOKIE: - log_info2(" "); - break; - case TAG_VENDOR_SPECIFIC: - if (ntohs(tag->tag_len) < 4) - log_info2(" "); - else - log_info2(" ", ntohl(*(uint32_t *)tag->tag_data)); - break; - case TAG_RELAY_SESSION_ID: - log_info2(" "); - break; - case TAG_SERVICE_NAME_ERROR: - log_info2(" "); - break; - case TAG_AC_SYSTEM_ERROR: - log_info2(" "); - break; - case TAG_GENERIC_ERROR: - log_info2(" "); - break; - default: - log_info2(" ", ntohs(tag->tag_type)); - break; - } - } - - log_info2("]\n"); -} - -static void generate_cookie(struct pppoe_serv_t *serv, const uint8_t *src, uint8_t *cookie) -{ - MD5_CTX ctx; - DES_cblock key; - DES_key_schedule ks; - int i; - union { - DES_cblock b[3]; - uint8_t raw[24]; - } u1, u2; - - memset(&key, 0, sizeof(key)); - DES_random_key(&key); - DES_set_key(&key, &ks); - - MD5_Init(&ctx); - MD5_Update(&ctx, serv->secret, SECRET_LENGTH); - MD5_Update(&ctx, serv->hwaddr, ETH_ALEN); - MD5_Update(&ctx, src, ETH_ALEN); - MD5_Update(&ctx, &key, 8); - MD5_Final(u1.raw, &ctx); - - for (i = 0; i < 2; i++) - DES_ecb_encrypt(&u1.b[i], &u2.b[i], &ks, DES_ENCRYPT); - memcpy(u2.b[2], &key, 8); - - for (i = 0; i < 3; i++) - DES_ecb_encrypt(&u2.b[i], &u1.b[i], &serv->des_ks, DES_ENCRYPT); - - memcpy(cookie, u1.raw, 24); -} - -static int check_cookie(struct pppoe_serv_t *serv, const uint8_t *src, const uint8_t *cookie) -{ - MD5_CTX ctx; - DES_key_schedule ks; - int i; - union { - DES_cblock b[3]; - uint8_t raw[24]; - } u1, u2; - - memcpy(u1.raw, cookie, 24); - - for (i = 0; i < 3; i++) - DES_ecb_encrypt(&u1.b[i], &u2.b[i], &serv->des_ks, DES_DECRYPT); - - if (DES_set_key_checked(&u2.b[2], &ks)) - return -1; - - for (i = 0; i < 2; i++) - DES_ecb_encrypt(&u2.b[i], &u1.b[i], &ks, DES_DECRYPT); - - MD5_Init(&ctx); - MD5_Update(&ctx, serv->secret, SECRET_LENGTH); - MD5_Update(&ctx, serv->hwaddr, ETH_ALEN); - MD5_Update(&ctx, src, ETH_ALEN); - MD5_Update(&ctx, u2.b[2], 8); - MD5_Final(u2.raw, &ctx); - - return memcmp(u1.raw, u2.raw, 16); -} - -static void setup_header(uint8_t *pack, const uint8_t *src, const uint8_t *dst, int code, uint16_t sid) -{ - struct ethhdr *ethhdr = (struct ethhdr *)pack; - struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); - - memcpy(ethhdr->h_source, src, ETH_ALEN); - memcpy(ethhdr->h_dest, dst, ETH_ALEN); - ethhdr->h_proto = htons(ETH_P_PPP_DISC); - - hdr->ver = 1; - hdr->type = 1; - hdr->code = code; - hdr->sid = htons(sid); - hdr->length = 0; -} - -static void add_tag(uint8_t *pack, int type, const uint8_t *data, int len) -{ - struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); - struct pppoe_tag *tag = (struct pppoe_tag *)(pack + ETH_HLEN + sizeof(*hdr) + ntohs(hdr->length)); - - tag->tag_type = htons(type); - tag->tag_len = htons(len); - memcpy(tag->tag_data, data, len); - - hdr->length = htons(ntohs(hdr->length) + sizeof(*tag) + len); -} - -static void add_tag2(uint8_t *pack, const struct pppoe_tag *t) -{ - struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); - struct pppoe_tag *tag = (struct pppoe_tag *)(pack + ETH_HLEN + sizeof(*hdr) + ntohs(hdr->length)); - - memcpy(tag, t, sizeof(*t) + ntohs(t->tag_len)); - - hdr->length = htons(ntohs(hdr->length) + sizeof(*tag) + ntohs(t->tag_len)); -} - -static void pppoe_send(int fd, const uint8_t *pack) -{ - struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); - int n, s; - - s = ETH_HLEN + sizeof(*hdr) + ntohs(hdr->length); - n = write(fd, pack, s); - if (n < 0 ) - log_error("pppoe: write: %s\n", strerror(errno)); - else if (n != s) { - log_warn("pppoe: short write %i/%i\n", n,s); - } -} - -static void pppoe_send_PADO(struct pppoe_serv_t *serv, const uint8_t *addr, const struct pppoe_tag *host_uniq, const struct pppoe_tag *relay_sid, const struct pppoe_tag *service_name) -{ - uint8_t pack[ETHER_MAX_LEN]; - uint8_t cookie[COOKIE_LENGTH]; - - setup_header(pack, serv->hwaddr, addr, CODE_PADO, 0); - - add_tag(pack, TAG_AC_NAME, (uint8_t *)conf_ac_name, strlen(conf_ac_name)); - if (conf_service_name) - add_tag(pack, TAG_SERVICE_NAME, (uint8_t *)conf_service_name, strlen(conf_service_name)); - - if (service_name) - add_tag2(pack, service_name); - - generate_cookie(serv, addr, cookie); - add_tag(pack, TAG_AC_COOKIE, cookie, COOKIE_LENGTH); - - if (host_uniq) - add_tag2(pack, host_uniq); - - if (relay_sid) - add_tag2(pack, relay_sid); - - if (conf_verbose) { - log_info2("send "); - print_packet(pack); - } - - __sync_add_and_fetch(&stat_PADO_sent, 1); - pppoe_send(serv->hnd.fd, pack); -} - -static void pppoe_send_err(struct pppoe_serv_t *serv, const uint8_t *addr, const struct pppoe_tag *host_uniq, const struct pppoe_tag *relay_sid, int code, int tag_type) -{ - uint8_t pack[ETHER_MAX_LEN]; - - setup_header(pack, serv->hwaddr, addr, code, 0); - - add_tag(pack, TAG_AC_NAME, (uint8_t *)conf_ac_name, strlen(conf_ac_name)); - add_tag(pack, tag_type, NULL, 0); - - if (host_uniq) - add_tag2(pack, host_uniq); - - if (relay_sid) - add_tag2(pack, relay_sid); - - if (conf_verbose) { - log_info2("send "); - print_packet(pack); - } - - pppoe_send(serv->hnd.fd, pack); -} - -static void pppoe_send_PADS(struct pppoe_conn_t *conn) -{ - uint8_t pack[ETHER_MAX_LEN]; - - setup_header(pack, conn->serv->hwaddr, conn->addr, CODE_PADS, conn->sid); - - add_tag(pack, TAG_AC_NAME, (uint8_t *)conf_ac_name, strlen(conf_ac_name)); - - add_tag2(pack, conn->service_name); - - if (conn->host_uniq) - add_tag2(pack, conn->host_uniq); - - if (conn->relay_sid) - add_tag2(pack, conn->relay_sid); - - if (conf_verbose) { - log_info2("send "); - print_packet(pack); - } - - __sync_add_and_fetch(&stat_PADS_sent, 1); - pppoe_send(conn->disc_sock, pack); -} - -static void pppoe_send_PADT(struct pppoe_conn_t *conn) -{ - uint8_t pack[ETHER_MAX_LEN]; - - setup_header(pack, conn->serv->hwaddr, conn->addr, CODE_PADT, conn->sid); - - add_tag(pack, TAG_AC_NAME, (uint8_t *)conf_ac_name, strlen(conf_ac_name)); - - add_tag2(pack, conn->service_name); - - if (conn->host_uniq) - add_tag2(pack, conn->host_uniq); - - if (conn->relay_sid) - add_tag2(pack, conn->relay_sid); - - if (conf_verbose) { - log_info2("send "); - print_packet(pack); - } - - pppoe_send(conn->disc_sock, pack); -} - -static void free_delayed_pado(struct delayed_pado_t *pado) -{ - triton_timer_del(&pado->timer); - - __sync_sub_and_fetch(&stat_delayed_pado, 1); - list_del(&pado->entry); - - if (pado->host_uniq) - _free(pado->host_uniq); - if (pado->relay_sid) - _free(pado->relay_sid); - if (pado->service_name) - _free(pado->service_name); - - mempool_free(pado); -} - -static void pado_timer(struct triton_timer_t *t) -{ - struct delayed_pado_t *pado = container_of(t, typeof(*pado), timer); - - if (!ppp_shutdown) - pppoe_send_PADO(pado->serv, pado->addr, pado->host_uniq, pado->relay_sid, pado->service_name); - - free_delayed_pado(pado); -} - -static void pppoe_recv_PADI(struct pppoe_serv_t *serv, uint8_t *pack, int size) -{ - struct ethhdr *ethhdr = (struct ethhdr *)pack; - struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); - struct pppoe_tag *tag; - struct pppoe_tag *host_uniq_tag = NULL; - struct pppoe_tag *relay_sid_tag = NULL; - struct pppoe_tag *service_name_tag = NULL; - int n, service_match = 0; - struct delayed_pado_t *pado; - - __sync_add_and_fetch(&stat_PADI_recv, 1); - - if (ppp_shutdown || pado_delay == -1) - return; - - if (hdr->sid) { - log_warn("pppoe: discarding PADI packet (sid is not zero)\n"); - return; - } - - if (conf_verbose) { - log_info2("recv "); - print_packet(pack); - } - - for (n = 0; n < ntohs(hdr->length); n += sizeof(*tag) + ntohs(tag->tag_len)) { - tag = (struct pppoe_tag *)(pack + ETH_HLEN + sizeof(*hdr) + n); - switch (ntohs(tag->tag_type)) { - case TAG_END_OF_LIST: - break; - case TAG_SERVICE_NAME: - if (conf_service_name && tag->tag_len) { - if (ntohs(tag->tag_len) != strlen(conf_service_name)) - break; - if (memcmp(tag->tag_data, conf_service_name, ntohs(tag->tag_len))) - break; - service_match = 1; - } else { - service_name_tag = tag; - service_match = 1; - } - break; - case TAG_HOST_UNIQ: - host_uniq_tag = tag; - break; - case TAG_RELAY_SESSION_ID: - relay_sid_tag = tag; - break; - } - } - - if (!service_match) { - if (conf_verbose) - log_warn("pppoe: discarding PADI packet (Service-Name mismatch)\n"); - return; - } - - if (pado_delay) { - list_for_each_entry(pado, &serv->pado_list, entry) { - if (memcmp(pado->addr, ethhdr->h_source, ETH_ALEN)) - continue; - if (conf_verbose) - log_warn("pppoe: discarding PADI packet (already queued)\n"); - return; - } - pado = mempool_alloc(pado_pool); - memset(pado, 0, sizeof(*pado)); - pado->serv = serv; - memcpy(pado->addr, ethhdr->h_source, ETH_ALEN); - - if (host_uniq_tag) { - pado->host_uniq = _malloc(sizeof(*host_uniq_tag) + ntohs(host_uniq_tag->tag_len)); - memcpy(pado->host_uniq, host_uniq_tag, sizeof(*host_uniq_tag) + ntohs(host_uniq_tag->tag_len)); - } - - if (relay_sid_tag) { - pado->relay_sid = _malloc(sizeof(*relay_sid_tag) + ntohs(relay_sid_tag->tag_len)); - memcpy(pado->relay_sid, relay_sid_tag, sizeof(*relay_sid_tag) + ntohs(relay_sid_tag->tag_len)); - } - - if (service_name_tag) { - pado->service_name = _malloc(sizeof(*service_name_tag) + ntohs(service_name_tag->tag_len)); - memcpy(pado->service_name, service_name_tag, sizeof(*service_name_tag) + ntohs(service_name_tag->tag_len)); - } - - pado->timer.expire = pado_timer; - pado->timer.period = pado_delay; - - triton_timer_add(&serv->ctx, &pado->timer, 0); - - list_add_tail(&pado->entry, &serv->pado_list); - __sync_add_and_fetch(&stat_delayed_pado, 1); - } else - pppoe_send_PADO(serv, ethhdr->h_source, host_uniq_tag, relay_sid_tag, service_name_tag); -} - -static void pppoe_recv_PADR(struct pppoe_serv_t *serv, uint8_t *pack, int size) -{ - struct ethhdr *ethhdr = (struct ethhdr *)pack; - struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); - struct pppoe_tag *tag; - struct pppoe_tag *host_uniq_tag = NULL; - struct pppoe_tag *relay_sid_tag = NULL; - struct pppoe_tag *ac_cookie_tag = NULL; - struct pppoe_tag *service_name_tag = NULL; - struct pppoe_tag *tr101_tag = NULL; - int n, service_match = 0; - struct pppoe_conn_t *conn; - int vendor_id; - - __sync_add_and_fetch(&stat_PADR_recv, 1); - - if (ppp_shutdown) - return; - - if (!memcmp(ethhdr->h_dest, bc_addr, ETH_ALEN)) { - if (conf_verbose) - log_warn("pppoe: discard PADR (destination address is broadcast)\n"); - return; - } - - if (hdr->sid) { - if (conf_verbose) - log_warn("pppoe: discarding PADR packet (sid is not zero)\n"); - return; - } - - if (conf_verbose) { - log_info2("recv "); - print_packet(pack); - } - - for (n = 0; n < ntohs(hdr->length); n += sizeof(*tag) + ntohs(tag->tag_len)) { - tag = (struct pppoe_tag *)(pack + ETH_HLEN + sizeof(*hdr) + n); - switch (ntohs(tag->tag_type)) { - case TAG_END_OF_LIST: - break; - case TAG_SERVICE_NAME: - service_name_tag = tag; - if (tag->tag_len == 0) - service_match = 1; - else if (conf_service_name) { - if (ntohs(tag->tag_len) != strlen(conf_service_name)) - break; - if (memcmp(tag->tag_data, conf_service_name, ntohs(tag->tag_len))) - break; - service_match = 1; - } else { - service_match = 1; - } - break; - case TAG_HOST_UNIQ: - host_uniq_tag = tag; - break; - case TAG_AC_COOKIE: - ac_cookie_tag = tag; - break; - case TAG_RELAY_SESSION_ID: - relay_sid_tag = tag; - break; - case TAG_VENDOR_SPECIFIC: - if (ntohs(tag->tag_len) < 4) - continue; - vendor_id = ntohl(*(uint32_t *)tag->tag_data); - if (vendor_id == VENDOR_ADSL_FORUM) - tr101_tag = tag; - break; - } - } - - if (!ac_cookie_tag) { - if (conf_verbose) - log_warn("pppoe: discard PADR packet (no AC-Cookie tag present)\n"); - return; - } - - if (ntohs(ac_cookie_tag->tag_len) != COOKIE_LENGTH) { - if (conf_verbose) - log_warn("pppoe: discard PADR packet (incorrect AC-Cookie tag length)\n"); - return; - } - - if (check_cookie(serv, ethhdr->h_source, (uint8_t *)ac_cookie_tag->tag_data)) { - if (conf_verbose) - log_warn("pppoe: discard PADR packet (incorrect AC-Cookie)\n"); - return; - } - - if (!service_match) { - if (conf_verbose) - log_warn("pppoe: Service-Name mismatch\n"); - pppoe_send_err(serv, ethhdr->h_source, host_uniq_tag, relay_sid_tag, CODE_PADS, TAG_SERVICE_NAME_ERROR); - return; - } - - pthread_mutex_lock(&serv->lock); - conn = find_channel(serv, (uint8_t *)ac_cookie_tag->tag_data); - if (conn && !conn->ppp.username) { - __sync_add_and_fetch(&stat_PADR_dup_recv, 1); - pppoe_send_PADS(conn); - } - pthread_mutex_unlock(&serv->lock); - - if (conn) - return; - - conn = allocate_channel(serv, ethhdr->h_source, host_uniq_tag, relay_sid_tag, service_name_tag, tr101_tag, (uint8_t *)ac_cookie_tag->tag_data); - if (!conn) - pppoe_send_err(serv, ethhdr->h_source, host_uniq_tag, relay_sid_tag, CODE_PADS, TAG_AC_SYSTEM_ERROR); - else { - pppoe_send_PADS(conn); - triton_context_call(&conn->ctx, (triton_event_func)connect_channel, conn); - } -} - -static void pppoe_recv_PADT(struct pppoe_serv_t *serv, uint8_t *pack) -{ - struct ethhdr *ethhdr = (struct ethhdr *)pack; - struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); - struct pppoe_conn_t *conn; - - if (!memcmp(ethhdr->h_dest, bc_addr, ETH_ALEN)) { - if (conf_verbose) - log_warn("pppoe: discard PADT (destination address is broadcast)\n"); - return; - } - - if (conf_verbose) { - log_info2("recv "); - print_packet(pack); - } - - pthread_mutex_lock(&serv->lock); - conn = serv->conn[ntohs(hdr->sid)]; - if (conn && !memcmp(conn->addr, ethhdr->h_source, ETH_ALEN)) - triton_context_call(&conn->ctx, (void (*)(void *))disconnect, conn); - pthread_mutex_unlock(&serv->lock); -} - -static int pppoe_serv_read(struct triton_md_handler_t *h) -{ - struct pppoe_serv_t *serv = container_of(h, typeof(*serv), hnd); - uint8_t pack[ETHER_MAX_LEN]; - struct ethhdr *ethhdr = (struct ethhdr *)pack; - struct pppoe_hdr *hdr = (struct pppoe_hdr *)(pack + ETH_HLEN); - int n; - - while (1) { - n = read(h->fd, pack, sizeof(pack)); - if (n < 0) { - if (errno == EAGAIN) - break; - log_error("pppoe: read: %s\n", strerror(errno)); - return 0; - } - - if (n < ETH_HLEN + sizeof(*hdr)) { - if (conf_verbose) - log_warn("pppoe: short packet received (%i)\n", n); - continue; - } - - if (mac_filter_check(ethhdr->h_source)) - continue; - - if (memcmp(ethhdr->h_dest, bc_addr, ETH_ALEN) && memcmp(ethhdr->h_dest, serv->hwaddr, ETH_ALEN)) - continue; - - if (!memcmp(ethhdr->h_source, bc_addr, ETH_ALEN)) { - if (conf_verbose) - log_warn("pppoe: discarding packet (host address is broadcast)\n"); - continue; - } - - if ((ethhdr->h_source[0] & 1) != 0) { - if (conf_verbose) - log_warn("pppoe: discarding packet (host address is not unicast)\n"); - continue; - } - - if (n < ETH_HLEN + sizeof(*hdr) + ntohs(hdr->length)) { - if (conf_verbose) - log_warn("pppoe: short packet received\n"); - continue; - } - - if (hdr->ver != 1) { - if (conf_verbose) - log_warn("pppoe: discarding packet (unsupported version %i)\n", hdr->ver); - continue; - } - - if (hdr->type != 1) { - if (conf_verbose) - log_warn("pppoe: discarding packet (unsupported type %i)\n", hdr->type); - } - - switch (hdr->code) { - case CODE_PADI: - pppoe_recv_PADI(serv, pack, n); - break; - case CODE_PADR: - pppoe_recv_PADR(serv, pack, n); - break; - case CODE_PADT: - pppoe_recv_PADT(serv, pack); - break; - } - } - return 0; -} - -static void pppoe_serv_close(struct triton_context_t *ctx) -{ - struct pppoe_serv_t *serv = container_of(ctx, typeof(*serv), ctx); - - triton_md_disable_handler(&serv->hnd, MD_MODE_READ | MD_MODE_WRITE); - - serv->stopping = 1; - - pthread_mutex_lock(&serv->lock); - if (!serv->conn_cnt) { - pthread_mutex_unlock(&serv->lock); - pppoe_server_free(serv); - return; - } - pthread_mutex_unlock(&serv->lock); -} - -void pppoe_server_start(const char *ifname, void *cli) -{ - struct pppoe_serv_t *serv; - int sock; - int opt = 1; - struct ifreq ifr; - struct sockaddr_ll sa; - - pthread_rwlock_rdlock(&serv_lock); - list_for_each_entry(serv, &serv_list, entry) { - if (!strcmp(serv->ifname, ifname)) { - if (cli) - cli_send(cli, "error: already exists\r\n"); - pthread_rwlock_unlock(&serv_lock); - return; - } - } - pthread_rwlock_unlock(&serv_lock); - - serv = _malloc(sizeof(*serv)); - memset(serv, 0, sizeof(*serv)); - - if (init_secret(serv)) { - if (cli) - cli_sendv(cli, "init secret failed\r\n"); - _free(serv); - return; - } - - sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_PPP_DISC)); - if (sock < 0) { - if (cli) - cli_sendv(cli, "socket: %s\r\n", strerror(errno)); - log_emerg("pppoe: socket: %s\n", strerror(errno)); - _free(serv); - return; - } - - if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt))) { - if (cli) - cli_sendv(cli, "setsockopt(SO_BROADCAST): %s\r\n", strerror(errno)); - log_emerg("pppoe: setsockopt(SO_BROADCAST): %s\n", strerror(errno)); - goto out_err; - } - - strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)); - if (ioctl(sock, SIOCGIFHWADDR, &ifr)) { - if (cli) - cli_sendv(cli, "ioctl(SIOCGIFHWADDR): %s\r\n", strerror(errno)); - log_emerg("pppoe: ioctl(SIOCGIFHWADDR): %s\n", strerror(errno)); - goto out_err; - } - -#ifdef ARPHDR_ETHER - if (ifr.ifr_hwaddr.sa_family != ARPHDR_ETHER) { - log_emerg("pppoe: interface %s is not ethernet\n", ifname); - goto out_err; - } -#endif - - if ((ifr.ifr_hwaddr.sa_data[0] & 1) != 0) { - if (cli) - cli_sendv(cli, "interface %s has not unicast address\r\n", ifname); - log_emerg("pppoe: interface %s has not unicast address\n", ifname); - goto out_err; - } - - memcpy(serv->hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN); - - if (ioctl(sock, SIOCGIFMTU, &ifr)) { - if (cli) - cli_sendv(cli, "ioctl(SIOCGIFMTU): %s\r\n", strerror(errno)); - log_emerg("pppoe: ioctl(SIOCGIFMTU): %s\n", strerror(errno)); - goto out_err; - } - - if (ifr.ifr_mtu < ETH_DATA_LEN) { - if (cli) - cli_sendv(cli, "interface %s has MTU of %i, should be %i\r\n", ifname, ifr.ifr_mtu, ETH_DATA_LEN); - log_emerg("pppoe: interface %s has MTU of %i, should be %i\n", ifname, ifr.ifr_mtu, ETH_DATA_LEN); - } - - if (ioctl(sock, SIOCGIFINDEX, &ifr)) { - if (cli) - cli_sendv(cli, "ioctl(SIOCGIFINDEX): %s\r\n", strerror(errno)); - log_emerg("pppoe: ioctl(SIOCGIFINDEX): %s\n", strerror(errno)); - goto out_err; - } - - memset(&sa, 0, sizeof(sa)); - sa.sll_family = AF_PACKET; - sa.sll_protocol = htons(ETH_P_PPP_DISC); - sa.sll_ifindex = ifr.ifr_ifindex; - - if (bind(sock, (struct sockaddr *)&sa, sizeof(sa))) { - if (cli) - cli_sendv(cli, "bind: %s\n", strerror(errno)); - log_emerg("pppoe: bind: %s\n", strerror(errno)); - goto out_err; - } - - if (fcntl(sock, F_SETFL, O_NONBLOCK)) { - if (cli) - cli_sendv(cli, "failed to set nonblocking mode: %s\n", strerror(errno)); - log_emerg("pppoe: failed to set nonblocking mode: %s\n", strerror(errno)); - goto out_err; - } - - serv->ctx.close = pppoe_serv_close; - serv->ctx.before_switch = log_switch; - serv->hnd.fd = sock; - serv->hnd.read = pppoe_serv_read; - serv->ifname = _strdup(ifname); - pthread_mutex_init(&serv->lock, NULL); - - INIT_LIST_HEAD(&serv->conn_list); - INIT_LIST_HEAD(&serv->pado_list); - - triton_context_register(&serv->ctx, NULL); - triton_md_register_handler(&serv->ctx, &serv->hnd); - triton_md_enable_handler(&serv->hnd, MD_MODE_READ); - triton_context_wakeup(&serv->ctx); - - pthread_rwlock_wrlock(&serv_lock); - list_add_tail(&serv->entry, &serv_list); - pthread_rwlock_unlock(&serv_lock); - - return; - -out_err: - close(sock); - _free(serv); -} - -static void _conn_stop(struct pppoe_conn_t *conn) -{ - ppp_terminate(&conn->ppp, 0, TERM_ADMIN_RESET); -} - -static void _server_stop(struct pppoe_serv_t *serv) -{ - struct pppoe_conn_t *conn; - - if (serv->stopping) - return; - - serv->stopping = 1; - triton_md_disable_handler(&serv->hnd, MD_MODE_READ | MD_MODE_WRITE); - - pthread_mutex_lock(&serv->lock); - if (!serv->conn_cnt) { - pthread_mutex_unlock(&serv->lock); - pppoe_server_free(serv); - return; - } - list_for_each_entry(conn, &serv->conn_list, entry) - triton_context_call(&conn->ctx, (triton_event_func)_conn_stop, conn); - pthread_mutex_unlock(&serv->lock); -} - -void pppoe_server_free(struct pppoe_serv_t *serv) -{ - struct delayed_pado_t *pado; - - pthread_rwlock_wrlock(&serv_lock); - list_del(&serv->entry); - pthread_rwlock_unlock(&serv_lock); - - while (!list_empty(&serv->pado_list)) { - pado = list_entry(serv->pado_list.next, typeof(*pado), entry); - free_delayed_pado(pado); - } - - triton_md_unregister_handler(&serv->hnd); - close(serv->hnd.fd); - triton_context_unregister(&serv->ctx); - _free(serv->ifname); - _free(serv); -} - -void pppoe_server_stop(const char *ifname) -{ - struct pppoe_serv_t *serv; - - pthread_rwlock_rdlock(&serv_lock); - list_for_each_entry(serv, &serv_list, entry) { - if (strcmp(serv->ifname, ifname)) - continue; - triton_context_call(&serv->ctx, (triton_event_func)_server_stop, serv); - break; - } - pthread_rwlock_unlock(&serv_lock); -} - -static int init_secret(struct pppoe_serv_t *serv) -{ - int fd; - DES_cblock key; - - fd = open("/dev/urandom", O_RDONLY); - if (fd < 0) { - log_emerg("pppoe: cann't open /dev/urandom: %s\n", strerror(errno)); - return -1; - } - - if (read(fd, serv->secret, SECRET_LENGTH) < 0) { - log_emerg("pppoe: faild to read /dev/urandom\n", strerror(errno)); - close(fd); - return -1; - } - - close(fd); - - memset(key, 0, sizeof(key)); - DES_random_key(&key); - DES_set_key(&key, &serv->des_ks); - - return 0; -} - -static void __init pppoe_init(void) -{ - struct conf_sect_t *s = conf_get_section("pppoe"); - struct conf_option_t *opt; - - conn_pool = mempool_create(sizeof(struct pppoe_conn_t)); - pado_pool = mempool_create(sizeof(struct delayed_pado_t)); - - if (!s) { - log_emerg("pppoe: no configuration, disabled...\n"); - return; - } - - list_for_each_entry(opt, &s->items, entry) { - if (!strcmp(opt->name, "interface")) { - if (opt->val) - pppoe_server_start(opt->val, NULL); - } else if (!strcmp(opt->name, "verbose")) { - if (atoi(opt->val) > 0) - conf_verbose = 1; - } else if (!strcmp(opt->name, "ac-name") || !strcmp(opt->name, "AC-Name")) { - if (opt->val && strlen(opt->val)) - conf_ac_name = _strdup(opt->val); - } else if (!strcmp(opt->name, "service-name") || !strcmp(opt->name, "Service-Name")) { - if (opt->val && strlen(opt->val)) - conf_service_name = _strdup(opt->val); - } else if (!strcmp(opt->name, "pado-delay") || !strcmp(opt->name, "PADO-delay")) { - if (dpado_parse(opt->val)) - _exit(EXIT_FAILURE); - } else if (!strcmp(opt->name, "ifname-in-sid")) { - if (!opt->val) - continue; - if (!strcmp(opt->val, "called-sid")) - conf_ifname_in_sid = 1; - else if (!strcmp(opt->val, "calling-sid")) - conf_ifname_in_sid = 2; - else if (!strcmp(opt->val, "both")) - conf_ifname_in_sid = 3; - else if (atoi(opt->val) >= 0) - conf_ifname_in_sid = atoi(opt->val); - } - } - - if (!conf_ac_name) - conf_ac_name = _strdup("accel-pptp"); -} - diff --git a/accel-pptpd/ctrl/pppoe/pppoe.h b/accel-pptpd/ctrl/pppoe/pppoe.h deleted file mode 100644 index 2264dd1..0000000 --- a/accel-pptpd/ctrl/pppoe/pppoe.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef __PPPOE_H -#define __PPPOE_H - -#include - -#include - -#include -#include - -/* PPPoE codes */ -#define CODE_PADI 0x09 -#define CODE_PADO 0x07 -#define CODE_PADR 0x19 -#define CODE_PADS 0x65 -#define CODE_PADT 0xA7 -#define CODE_SESS 0x00 - -/* PPPoE Tags */ -#define TAG_END_OF_LIST 0x0000 -#define TAG_SERVICE_NAME 0x0101 -#define TAG_AC_NAME 0x0102 -#define TAG_HOST_UNIQ 0x0103 -#define TAG_AC_COOKIE 0x0104 -#define TAG_VENDOR_SPECIFIC 0x0105 -#define TAG_RELAY_SESSION_ID 0x0110 -#define TAG_SERVICE_NAME_ERROR 0x0201 -#define TAG_AC_SYSTEM_ERROR 0x0202 -#define TAG_GENERIC_ERROR 0x0203 - -/* Discovery phase states */ -#define STATE_SENT_PADI 0 -#define STATE_RECEIVED_PADO 1 -#define STATE_SENT_PADR 2 -#define STATE_SESSION 3 -#define STATE_TERMINATED 4 - -/* Header size of a PPPoE packet */ -#define PPPOE_OVERHEAD 6 /* type, code, session, length */ -#define HDR_SIZE (sizeof(struct ethhdr) + PPPOE_OVERHEAD) -#define MAX_PPPOE_PAYLOAD (ETH_DATA_LEN - PPPOE_OVERHEAD) -#define MAX_PPPOE_MTU (MAX_PPPOE_PAYLOAD - 2) - -#define VENDOR_ADSL_FORUM 0xde9 - -#define MAX_SID 65534 -#define SECRET_LENGTH 16 -#define COOKIE_LENGTH 24 - -struct pppoe_tag_t -{ - struct list_head entry; - int type; - int len; -}; - -struct pppoe_packet_t -{ - uint8_t src[ETH_ALEN]; - uint8_t dst[ETH_ALEN]; - int code; - uint16_t sid; - struct list_head tags; -}; - -struct pppoe_serv_t -{ - struct list_head entry; - struct triton_context_t ctx; - struct triton_md_handler_t hnd; - uint8_t hwaddr[ETH_ALEN]; - char *ifname; - - uint8_t secret[SECRET_LENGTH]; - DES_key_schedule des_ks; - - pthread_mutex_t lock; - struct pppoe_conn_t *conn[MAX_SID]; - uint16_t sid; - int stopping:1; - - unsigned int conn_cnt; - struct list_head conn_list; - struct list_head pado_list; -}; - -extern int conf_verbose; -extern char *conf_service_name; -extern char *conf_ac_name; -extern char *conf_pado_delay; - -extern unsigned int stat_active; -extern unsigned int stat_delayed_pado; -extern unsigned long stat_PADI_recv; -extern unsigned long stat_PADO_sent; -extern unsigned long stat_PADR_recv; -extern unsigned long stat_PADR_dup_recv; -extern unsigned long stat_PADS_sent; - -extern pthread_rwlock_t serv_lock; -extern struct list_head serv_list; - -int mac_filter_check(const uint8_t *addr); -void pppoe_server_start(const char *intf, void *client); -void pppoe_server_stop(const char *intf); - -extern int pado_delay; -void dpado_check_next(int conn_cnt); -void dpado_check_prev(int conn_cnt); -int dpado_parse(const char *str); - -struct rad_packet_t; -int tr101_send_access_request(struct pppoe_tag *tr101, struct rad_packet_t *pack); -int tr101_send_accounting_request(struct pppoe_tag *tr101, struct rad_packet_t *pack); - -#endif - diff --git a/accel-pptpd/ctrl/pppoe/tr101.c b/accel-pptpd/ctrl/pppoe/tr101.c deleted file mode 100644 index cfb0fbc..0000000 --- a/accel-pptpd/ctrl/pppoe/tr101.c +++ /dev/null @@ -1,97 +0,0 @@ -#include -#include -#include -#include - -#include "triton.h" -#include "ppp.h" -#include "log.h" -#include "radius.h" -#include "memdebug.h" - -#include "pppoe.h" - -#define OPT_CIRCUIT_ID 0x01 -#define OPT_REMOTE_AGENT_ID 0x02 -#define OPT_ACTUAL_DATA_RATE_UP 0x81 -#define OPT_ACTUAL_DATA_RATE_DOWN 0x82 -#define OPT_MIN_DATA_RATE_UP 0x83 -#define OPT_MAX_DATA_RATE_DOWN 0x84 - -static int tr101_send_request(struct pppoe_tag *tr101, struct rad_packet_t *pack, int type) -{ - uint8_t *ptr = (uint8_t *)tr101->tag_data + 4; - uint8_t *endptr = (uint8_t *)tr101->tag_data + ntohs(tr101->tag_len); - int id, len; - char str[64]; - - while (ptr < endptr) { - if (ptr + 2 > endptr) - goto inval; - id = *ptr++; - len = *ptr++; - if (ptr + len - 2 > endptr) - goto inval; - if (type && id > 0x80) - continue; - switch (id) { - case OPT_CIRCUIT_ID: - if (len - 2 > 63) - goto inval; - memcpy(str, ptr, len); - str[len - 2] = 0; - if (rad_packet_add_str(pack, "ADSL-Forum", "ADSL-Agent-Circuit-Id", str)) - return -1; - break; - case OPT_REMOTE_AGENT_ID: - if (len - 2 > 63) - goto inval; - memcpy(str, ptr, len); - str[len - 2] = 0; - if (rad_packet_add_str(pack, "ADSL-Forum", "ADSL-Agent-Remote-Id", str)) - return -1; - break; - case OPT_ACTUAL_DATA_RATE_UP: - if (len != 6) - goto inval; - if (rad_packet_add_int(pack, "ADSL-Forum", "Actual-Data-Rate-Upstream", ntohl(*(uint32_t *)ptr))) - return -1; - break; - case OPT_ACTUAL_DATA_RATE_DOWN: - if (len != 6) - goto inval; - if (rad_packet_add_int(pack, "ADSL-Forum", "Actual-Data-Rate-Downstream", ntohl(*(uint32_t *)ptr))) - return -1; - break; - case OPT_MIN_DATA_RATE_UP: - if (len != 6) - goto inval; - if (rad_packet_add_int(pack, "ADSL-Forum", "Minimum-Data-Rate-Upstream", ntohl(*(uint32_t *)ptr))) - return -1; - break; - case OPT_MAX_DATA_RATE_DOWN: - if (len != 6) - goto inval; - if (rad_packet_add_int(pack, "ADSL-Forum", "Maximum-Data-Rate-Upstream", ntohl(*(uint32_t *)ptr))) - return -1; - break; - } - ptr += len - 2; - } - - return 0; - -inval: - log_ppp_warn("pppoe:tr101: invalid tag received\n"); - return -1; -} - -int tr101_send_access_request(struct pppoe_tag *tr101, struct rad_packet_t *pack) -{ - return tr101_send_request(tr101, pack, 1); -} - -int tr101_send_accounting_request(struct pppoe_tag *tr101, struct rad_packet_t *pack) -{ - return tr101_send_request(tr101, pack, 0); -} diff --git a/accel-pptpd/ctrl/pptp/CMakeLists.txt b/accel-pptpd/ctrl/pptp/CMakeLists.txt deleted file mode 100644 index e9c2779..0000000 --- a/accel-pptpd/ctrl/pptp/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) - -ADD_LIBRARY(pptp SHARED pptp.c) - -INSTALL(TARGETS pptp LIBRARY DESTINATION lib/accel-pptp ) diff --git a/accel-pptpd/ctrl/pptp/pptp.c b/accel-pptpd/ctrl/pptp/pptp.c deleted file mode 100644 index 687aecb..0000000 --- a/accel-pptpd/ctrl/pptp/pptp.c +++ /dev/null @@ -1,775 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "if_pppox.h" - -#include "events.h" -#include "list.h" -#include "pptp_prot.h" -#include "triton.h" -#include "log.h" -#include "ppp.h" -#include "mempool.h" -#include "iprange.h" -#include "utils.h" -#include "cli.h" - -#include "memdebug.h" - -#define STATE_IDLE 0 -#define STATE_ESTB 1 -#define STATE_PPP 2 -#define STATE_FIN 3 -#define STATE_CLOSE 4 - -struct pptp_conn_t -{ - struct triton_context_t ctx; - struct triton_md_handler_t hnd; - struct triton_timer_t timeout_timer; - struct triton_timer_t echo_timer; - int call_id; - int peer_call_id; - int state; - int echo_sent; - - uint8_t *in_buf; - int in_size; - uint8_t *out_buf; - int out_size; - int out_pos; - - struct ppp_ctrl_t ctrl; - struct ppp_t ppp; -}; - -static int conf_timeout = 5; -static int conf_echo_interval = 0; -static int conf_echo_failure = 3; -static int conf_verbose = 0; -static mempool_t conn_pool; - -static unsigned int stat_starting; -static unsigned int stat_active; - -static int pptp_read(struct triton_md_handler_t *h); -static int pptp_write(struct triton_md_handler_t *h); -static void pptp_timeout(struct triton_timer_t *); -static void ppp_started(struct ppp_t *); -static void ppp_finished(struct ppp_t *); - -static void disconnect(struct pptp_conn_t *conn) -{ - log_ppp_debug("pptp: disconnect\n"); - - triton_md_unregister_handler(&conn->hnd); - close(conn->hnd.fd); - - if (conn->timeout_timer.tpd) - triton_timer_del(&conn->timeout_timer); - - if (conn->echo_timer.tpd) - triton_timer_del(&conn->echo_timer); - - if (conn->state == STATE_PPP) { - __sync_sub_and_fetch(&stat_active, 1); - conn->state = STATE_CLOSE; - ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); - } else if (conn->state != STATE_CLOSE) - __sync_sub_and_fetch(&stat_starting, 1); - - triton_event_fire(EV_CTRL_FINISHED, &conn->ppp); - - log_ppp_info1("disconnected\n"); - - triton_context_unregister(&conn->ctx); - - if (conn->ppp.chan_name) - _free(conn->ppp.chan_name); - - _free(conn->in_buf); - _free(conn->out_buf); - _free(conn->ctrl.calling_station_id); - _free(conn->ctrl.called_station_id); - mempool_free(conn); -} - -static int post_msg(struct pptp_conn_t *conn, void *buf, int size) -{ - int n; - if (conn->out_size) { - log_error("pptp: buffer is not empty\n"); - return -1; - } - - n=write(conn->hnd.fd, buf, size); - if (n < 0) { - if (errno == EINTR || errno == EAGAIN) - n = 0; - else { - if (errno != EPIPE) { - if (conf_verbose) - log_ppp_info2("pptp: write: %s\n", strerror(errno)); - return -1; - } - } - } - - if ( nout_buf, buf + n, size - n); - triton_md_enable_handler(&conn->hnd, MD_MODE_WRITE); - } - - return 0; -} - -static int send_pptp_stop_ctrl_conn_rqst(struct pptp_conn_t *conn, int reason) -{ - struct pptp_stop_ctrl_conn msg = { - .header = PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RQST), - .reason_result = hton8(reason), - }; - - if (conf_verbose) - log_ppp_info2("send [PPTP Stop-Ctrl-Conn-Request ]\n", reason); - - return post_msg(conn, &msg, sizeof(msg)); -} - -static int send_pptp_stop_ctrl_conn_rply(struct pptp_conn_t *conn, int reason, int err_code) -{ - struct pptp_stop_ctrl_conn msg = { - .header = PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RPLY), - .reason_result = hton8(reason), - .error_code = hton8(err_code), - }; - - if (conf_verbose) - log_ppp_info2("send [PPTP Stop-Ctrl-Conn-Reply ]\n", msg.reason_result, msg.error_code); - - return post_msg(conn, &msg, sizeof(msg)); -} -static int pptp_stop_ctrl_conn_rqst(struct pptp_conn_t *conn) -{ - struct pptp_stop_ctrl_conn *msg = (struct pptp_stop_ctrl_conn *)conn->in_buf; - if (conf_verbose) - log_ppp_info2("recv [PPTP Stop-Ctrl-Conn-Request ]\n", msg->reason_result); - - send_pptp_stop_ctrl_conn_rply(conn, PPTP_CONN_STOP_OK, 0); - - return -1; -} - -static int pptp_stop_ctrl_conn_rply(struct pptp_conn_t *conn) -{ - struct pptp_stop_ctrl_conn *msg = (struct pptp_stop_ctrl_conn*)conn->in_buf; - if (conf_verbose) - log_ppp_info2("recv [PPTP Stop-Ctrl-Conn-Reply ]\n", msg->reason_result, msg->error_code); - return -1; -} - -static int send_pptp_start_ctrl_conn_rply(struct pptp_conn_t *conn, int res_code, int err_code) -{ - struct pptp_start_ctrl_conn msg = { - .header = PPTP_HEADER_CTRL(PPTP_START_CTRL_CONN_RPLY), - .version = htons(PPTP_VERSION), - .result_code = res_code, - .error_code = err_code, - .framing_cap = htonl(3), - .bearer_cap = htonl(3), - .max_channels = htons(1), - .firmware_rev = htons(PPTP_FIRMWARE_VERSION), - }; - - memset(msg.hostname, 0, sizeof(msg.hostname)); - strcpy((char*)msg.hostname, PPTP_HOSTNAME); - - memset(msg.vendor, 0, sizeof(msg.vendor)); - strcpy((char*)msg.vendor, PPTP_VENDOR); - - if (conf_verbose) - log_ppp_info2("send [PPTP Start-Ctrl-Conn-Reply ]\n", msg.version, msg.result_code, msg.error_code, ntohl(msg.framing_cap), ntohl(msg.bearer_cap), ntohs(msg.max_channels)); - - return post_msg(conn, &msg, sizeof(msg)); -} - -static int pptp_start_ctrl_conn_rqst(struct pptp_conn_t *conn) -{ - struct pptp_start_ctrl_conn *msg = (struct pptp_start_ctrl_conn *)conn->in_buf; - - if (conf_verbose) - log_ppp_info2("recv [PPTP Start-Ctrl-Conn-Request ]\n", msg->version, ntohl(msg->framing_cap), ntohl(msg->bearer_cap), ntohs(msg->max_channels)); - - if (conn->state != STATE_IDLE) { - log_ppp_warn("unexpected PPTP_START_CTRL_CONN_RQST\n"); - if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_EXISTS, 0)) - return -1; - return 0; - } - - if (msg->version != htons(PPTP_VERSION)) { - log_ppp_warn("PPTP version mismatch: expecting %x, received %s\n", PPTP_VERSION, msg->version); - if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_PROTOCOL, 0)) - return -1; - return 0; - } - /*if (!(ntohl(msg->framing_cap) & PPTP_FRAME_SYNC)) { - log_ppp_warn("connection does not supports sync mode\n"); - if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_GE, 0)) - return -1; - return 0; - }*/ - if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_SUCCESS, 0)) - return -1; - - triton_timer_mod(&conn->timeout_timer, 0); - - conn->state = STATE_ESTB; - - return 0; -} - -static int send_pptp_out_call_rply(struct pptp_conn_t *conn, struct pptp_out_call_rqst *rqst, int call_id, int res_code, int err_code) -{ - struct pptp_out_call_rply msg = { - .header = PPTP_HEADER_CTRL(PPTP_OUT_CALL_RPLY), - .call_id = htons(call_id), - .call_id_peer = rqst->call_id, - .result_code = res_code, - .error_code = err_code, - .cause_code = 0, - .speed = rqst->bps_max, - .recv_size = rqst->recv_size, - .delay = 0, - .channel = 0, - }; - - if (conf_verbose) - log_ppp_info2("send [PPTP Outgoing-Call-Reply ]\n", ntohs(msg.call_id), ntohs(msg.call_id_peer), msg.result_code, msg.error_code, ntohs(msg.cause_code), ntohl(msg.speed), ntohs(msg.recv_size), ntohs(msg.delay), ntohl(msg.channel)); - - return post_msg(conn, &msg, sizeof(msg)); -} - -static int pptp_out_call_rqst(struct pptp_conn_t *conn) -{ - struct pptp_out_call_rqst *msg = (struct pptp_out_call_rqst *)conn->in_buf; - struct sockaddr_pppox src_addr, dst_addr; - struct sockaddr_in addr; - socklen_t addrlen; - int pptp_sock; - - if (conf_verbose) - log_ppp_info2("recv [PPTP Outgoing-Call-Request ]\n", ntohs(msg->call_id), ntohs(msg->call_sernum), ntohl(msg->bps_min), ntohl(msg->bps_max), ntohl(msg->bearer), ntohl(msg->framing), ntohs(msg->recv_size), ntohs(msg->delay)); - - if (conn->state != STATE_ESTB) { - log_ppp_warn("unexpected PPTP_OUT_CALL_RQST\n"); - if (send_pptp_out_call_rply(conn, msg, 0, PPTP_CALL_RES_GE, PPTP_GE_NOCONN)) - return -1; - return 0; - } - - memset(&src_addr, 0, sizeof(src_addr)); - src_addr.sa_family = AF_PPPOX; - src_addr.sa_protocol = PX_PROTO_PPTP; - src_addr.sa_addr.pptp.call_id = 0; - addrlen = sizeof(addr); - getsockname(conn->hnd.fd, (struct sockaddr*)&addr, &addrlen); - src_addr.sa_addr.pptp.sin_addr = addr.sin_addr; - - memset(&dst_addr, 0, sizeof(dst_addr)); - dst_addr.sa_family = AF_PPPOX; - dst_addr.sa_protocol = PX_PROTO_PPTP; - dst_addr.sa_addr.pptp.call_id = htons(msg->call_id); - addrlen = sizeof(addr); - getpeername(conn->hnd.fd, (struct sockaddr*)&addr, &addrlen); - dst_addr.sa_addr.pptp.sin_addr = addr.sin_addr; - - pptp_sock = socket(AF_PPPOX, SOCK_STREAM, PX_PROTO_PPTP); - if (pptp_sock < 0) { - log_ppp_error("failed to create PPTP socket (%s)\n", strerror(errno)); - return -1; - } - if (bind(pptp_sock, (struct sockaddr*)&src_addr, sizeof(src_addr))) { - log_ppp_error("failed to bind PPTP socket (%s)\n", strerror(errno)); - close(pptp_sock); - return -1; - } - addrlen = sizeof(src_addr); - getsockname(pptp_sock, (struct sockaddr*)&src_addr, &addrlen); - - if (connect(pptp_sock, (struct sockaddr*)&dst_addr, sizeof(dst_addr))) { - log_ppp_error("failed to connect PPTP socket (%s)\n", strerror(errno)); - close(pptp_sock); - return -1; - } - - if (send_pptp_out_call_rply(conn, msg, src_addr.sa_addr.pptp.call_id, PPTP_CALL_RES_OK, 0)) - return -1; - - conn->call_id = src_addr.sa_addr.pptp.call_id; - conn->peer_call_id = msg->call_id; - conn->ppp.fd = pptp_sock; - conn->ppp.chan_name = _strdup(inet_ntoa(dst_addr.sa_addr.pptp.sin_addr)); - - triton_event_fire(EV_CTRL_STARTED, &conn->ppp); - - if (establish_ppp(&conn->ppp)) { - close(pptp_sock); - //if (send_pptp_stop_ctrl_conn_rqst(conn, 0, 0)) - conn->state = STATE_FIN; - return -1; - } - conn->state = STATE_PPP; - __sync_sub_and_fetch(&stat_starting, 1); - __sync_add_and_fetch(&stat_active, 1); - - if (conn->timeout_timer.tpd) - triton_timer_del(&conn->timeout_timer); - - if (conf_echo_interval) { - conn->echo_timer.period = conf_echo_interval * 1000; - triton_timer_add(&conn->ctx, &conn->echo_timer, 0); - } - - return 0; -} - -static int send_pptp_call_disconnect_notify(struct pptp_conn_t *conn, int result) -{ - struct pptp_call_clear_ntfy msg = { - .header = PPTP_HEADER_CTRL(PPTP_CALL_CLEAR_NTFY), - .call_id = htons(conn->peer_call_id), - .result_code = result, - .error_code = 0, - .cause_code = 0, - }; - - if (conf_verbose) - log_ppp_info2("send [PPTP Call-Disconnect-Notify ]\n", ntohs(msg.call_id), msg.result_code, msg.error_code, msg.cause_code); - - return post_msg(conn, &msg, sizeof(msg)); -} - -static int pptp_call_clear_rqst(struct pptp_conn_t *conn) -{ - struct pptp_call_clear_rqst *rqst = (struct pptp_call_clear_rqst *)conn->in_buf; - - if (conf_verbose) - log_ppp_info2("recv [PPTP Call-Clear-Request ]\n", ntohs(rqst->call_id)); - - if (conn->state == STATE_PPP) { - __sync_sub_and_fetch(&stat_active, 1); - conn->state = STATE_CLOSE; - ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); - } - - return send_pptp_call_disconnect_notify(conn, 4); -} - -static int pptp_echo_rqst(struct pptp_conn_t *conn) -{ - struct pptp_echo_rqst *in_msg = (struct pptp_echo_rqst *)conn->in_buf; - struct pptp_echo_rply out_msg = { - .header = PPTP_HEADER_CTRL(PPTP_ECHO_RPLY), - .identifier = in_msg->identifier, - .result_code = 1, - }; - - if (conf_verbose) { - log_ppp_debug("recv [PPTP Echo-Request ]\n", in_msg->identifier); - log_ppp_debug("send [PPTP Echo-Reply ]\n", out_msg.identifier); - } - - return post_msg(conn, &out_msg, sizeof(out_msg)); -} - -static int pptp_echo_rply(struct pptp_conn_t *conn) -{ - struct pptp_echo_rply *msg = (struct pptp_echo_rply *)conn->in_buf; - - if (conf_verbose) - log_ppp_debug("recv [PPTP Echo-Reply ]\n", msg->identifier); - - if (msg->identifier != conn->echo_sent) { - log_ppp_warn("pptp:echo: identifier mismatch\n"); - //return -1; - } - conn->echo_sent = 0; - return 0; -} -static void pptp_send_echo(struct triton_timer_t *t) -{ - struct pptp_conn_t *conn = container_of(t, typeof(*conn), echo_timer); - struct pptp_echo_rqst msg = { - .header = PPTP_HEADER_CTRL(PPTP_ECHO_RQST), - }; - - if (++conn->echo_sent == conf_echo_failure) { - log_ppp_warn("pptp: no echo reply\n"); - disconnect(conn); - return; - } - - conn->echo_sent = random(); - msg.identifier = conn->echo_sent; - - if (conf_verbose) - log_ppp_debug("send [PPTP Echo-Request ]\n", msg.identifier); - - if (post_msg(conn, &msg, sizeof(msg))) - disconnect(conn); -} - -static int process_packet(struct pptp_conn_t *conn) -{ - struct pptp_header *hdr = (struct pptp_header *)conn->in_buf; - switch(ntohs(hdr->ctrl_type)) - { - case PPTP_START_CTRL_CONN_RQST: - return pptp_start_ctrl_conn_rqst(conn); - case PPTP_STOP_CTRL_CONN_RQST: - return pptp_stop_ctrl_conn_rqst(conn); - case PPTP_STOP_CTRL_CONN_RPLY: - return pptp_stop_ctrl_conn_rply(conn); - case PPTP_OUT_CALL_RQST: - return pptp_out_call_rqst(conn); - case PPTP_ECHO_RQST: - return pptp_echo_rqst(conn); - case PPTP_ECHO_RPLY: - return pptp_echo_rply(conn); - case PPTP_CALL_CLEAR_RQST: - return pptp_call_clear_rqst(conn); - case PPTP_SET_LINK_INFO: - if (conf_verbose) - log_ppp_info2("recv [PPTP Set-Link-Info]\n"); - return 0; - default: - log_ppp_warn("recv [PPTP Unknown (%x)]\n", ntohs(hdr->ctrl_type)); - } - return 0; -} - -static int pptp_read(struct triton_md_handler_t *h) -{ - struct pptp_conn_t *conn=container_of(h,typeof(*conn),hnd); - struct pptp_header *hdr=(struct pptp_header *)conn->in_buf; - int n; - - while(1) { - n = read(h->fd, conn->in_buf + conn->in_size, PPTP_CTRL_SIZE_MAX - conn->in_size); - if (n < 0) { - if (errno == EINTR) - continue; - if (errno == EAGAIN) - return 0; - log_ppp_error("pptp: read: %s\n",strerror(errno)); - goto drop; - } - if (n == 0) { - if (conf_verbose) - log_ppp_info2("pptp: disconnect by peer\n"); - goto drop; - } - conn->in_size += n; - if (conn->in_size >= sizeof(*hdr)) { - if (hdr->magic != htonl(PPTP_MAGIC)) { - log_ppp_error("pptp: invalid magic\n"); - goto drop; - } - if (ntohs(hdr->length) >= PPTP_CTRL_SIZE_MAX) { - log_ppp_error("pptp: message is too long\n"); - goto drop; - } - if (ntohs(hdr->length) > conn->in_size) - continue; - if (ntohs(hdr->length) <= conn->in_size) { - if (ntohs(hdr->length) != PPTP_CTRL_SIZE(ntohs(hdr->ctrl_type))) { - log_ppp_error("pptp: invalid message length\n"); - goto drop; - } - if (process_packet(conn)) - goto drop; - conn->in_size -= ntohs(hdr->length); - if (conn->in_size) - memmove(conn->in_buf, conn->in_buf + ntohs(hdr->length), conn->in_size); - } - } - } -drop: - disconnect(conn); - return 1; -} -static int pptp_write(struct triton_md_handler_t *h) -{ - struct pptp_conn_t *conn = container_of(h, typeof(*conn), hnd); - int n; - - while (1) { - n = write(h->fd, conn->out_buf+conn->out_pos, conn->out_size-conn->out_pos); - - if (n < 0) { - if (errno == EINTR) - continue; - if (errno == EAGAIN) - n = 0; - else { - if (errno != EPIPE) { - if (conf_verbose) - log_ppp_info2("pptp: post_msg: %s\n", strerror(errno)); - } - disconnect(conn); - return 1; - } - } - - conn->out_pos += n; - if (conn->out_pos == conn->out_size) { - conn->out_pos = 0; - conn->out_size = 0; - triton_md_disable_handler(h, MD_MODE_WRITE); - return 0; - } - } -} -static void pptp_timeout(struct triton_timer_t *t) -{ - struct pptp_conn_t *conn = container_of(t, typeof(*conn), timeout_timer); - disconnect(conn); -} -static void pptp_close(struct triton_context_t *ctx) -{ - struct pptp_conn_t *conn = container_of(ctx, typeof(*conn), ctx); - if (conn->state == STATE_PPP) { - __sync_sub_and_fetch(&stat_active, 1); - conn->state = STATE_CLOSE; - ppp_terminate(&conn->ppp, TERM_ADMIN_RESET, 1); - if (send_pptp_call_disconnect_notify(conn, 3)) { - triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); - return; - } - } else { - if (send_pptp_stop_ctrl_conn_rqst(conn, 0)) { - triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); - return; - } - } - - if (conn->timeout_timer.tpd) - triton_timer_mod(&conn->timeout_timer, 0); - else - triton_timer_add(ctx, &conn->timeout_timer, 0); -} -static void ppp_started(struct ppp_t *ppp) -{ - log_ppp_debug("pptp: ppp started\n"); -} -static void ppp_finished(struct ppp_t *ppp) -{ - struct pptp_conn_t *conn = container_of(ppp, typeof(*conn), ppp); - - if (conn->state != STATE_CLOSE) { - log_ppp_debug("pptp: ppp finished\n"); - conn->state = STATE_CLOSE; - __sync_sub_and_fetch(&stat_active, 1); - - if (send_pptp_call_disconnect_notify(conn, 3)) - triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); - else if (send_pptp_stop_ctrl_conn_rqst(conn, 0)) - triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); - else { - if (conn->timeout_timer.tpd) - triton_timer_mod(&conn->timeout_timer, 0); - else - triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); - } - } -} - -//================================== - -struct pptp_serv_t -{ - struct triton_context_t ctx; - struct triton_md_handler_t hnd; -}; - -static int pptp_connect(struct triton_md_handler_t *h) -{ - struct sockaddr_in addr; - socklen_t size = sizeof(addr); - int sock; - struct pptp_conn_t *conn; - - while(1) { - sock = accept(h->fd, (struct sockaddr *)&addr, &size); - if (sock < 0) { - if (errno == EAGAIN) - return 0; - log_error("pptp: accept failed: %s\n", strerror(errno)); - continue; - } - - if (ppp_shutdown) { - close(sock); - continue; - } - - log_info2("pptp: new connection from %s\n", inet_ntoa(addr.sin_addr)); - - if (iprange_client_check(addr.sin_addr.s_addr)) { - log_warn("pptp: IP is out of client-ip-range, droping connection...\n"); - close(sock); - continue; - } - - if (fcntl(sock, F_SETFL, O_NONBLOCK)) { - log_error("pptp: failed to set nonblocking mode: %s, closing connection...\n", strerror(errno)); - close(sock); - continue; - } - - conn = mempool_alloc(conn_pool); - memset(conn, 0, sizeof(*conn)); - conn->hnd.fd = sock; - conn->hnd.read = pptp_read; - conn->hnd.write = pptp_write; - conn->ctx.close = pptp_close; - conn->ctx.before_switch = log_switch; - conn->in_buf = _malloc(PPTP_CTRL_SIZE_MAX); - conn->out_buf = _malloc(PPTP_CTRL_SIZE_MAX); - conn->timeout_timer.expire = pptp_timeout; - conn->timeout_timer.period = conf_timeout * 1000; - conn->echo_timer.expire = pptp_send_echo; - conn->ctrl.ctx = &conn->ctx; - conn->ctrl.started = ppp_started; - conn->ctrl.finished = ppp_finished; - conn->ctrl.max_mtu = PPTP_MAX_MTU; - conn->ctrl.name = "pptp"; - - conn->ctrl.calling_station_id = _malloc(17); - conn->ctrl.called_station_id = _malloc(17); - u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.calling_station_id); - getsockname(sock, &addr, &size); - u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.called_station_id); - - ppp_init(&conn->ppp); - conn->ppp.ctrl = &conn->ctrl; - - triton_context_register(&conn->ctx, &conn->ppp); - triton_md_register_handler(&conn->ctx, &conn->hnd); - triton_md_enable_handler(&conn->hnd,MD_MODE_READ); - triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); - triton_context_wakeup(&conn->ctx); - - triton_event_fire(EV_CTRL_STARTING, &conn->ppp); - - __sync_add_and_fetch(&stat_starting, 1); - } - return 0; -} -static void pptp_serv_close(struct triton_context_t *ctx) -{ - struct pptp_serv_t *s=container_of(ctx,typeof(*s),ctx); - triton_md_unregister_handler(&s->hnd); - close(s->hnd.fd); - triton_context_unregister(ctx); -} - -static struct pptp_serv_t serv= -{ - .hnd.read = pptp_connect, - .ctx.close = pptp_serv_close, - .ctx.before_switch = log_switch, -}; - -static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "pptp:\r\n"); - cli_sendv(client," starting: %u\r\n", stat_starting); - cli_sendv(client," active: %u\r\n", stat_active); - - return CLI_CMD_OK; -} - -static void load_config(void) -{ - char *opt; - - opt = conf_get_opt("pptp", "timeout"); - if (opt && atoi(opt) > 0) - conf_timeout = atoi(opt); - - opt = conf_get_opt("pptp", "echo-interval"); - if (opt && atoi(opt) >= 0) - conf_echo_interval = atoi(opt); - - opt = conf_get_opt("pptp", "echo-failure"); - if (opt && atoi(opt) > 0) - conf_echo_failure = atoi(opt); - - opt = conf_get_opt("pptp", "verbose"); - if (opt && atoi(opt) > 0) - conf_verbose = 1; -} - -static void __init pptp_init(void) -{ - struct sockaddr_in addr; - char *opt; - - serv.hnd.fd = socket(PF_INET, SOCK_STREAM, 0); - if (serv.hnd.fd < 0) { - log_emerg("pptp: failed to create server socket: %s\n", strerror(errno)); - return; - } - addr.sin_family = AF_INET; - addr.sin_port = htons(PPTP_PORT); - - opt = conf_get_opt("pptp", "bind"); - if (opt) - addr.sin_addr.s_addr = inet_addr(opt); - else - addr.sin_addr.s_addr = htonl(INADDR_ANY); - - setsockopt(serv.hnd.fd, SOL_SOCKET, SO_REUSEADDR, &serv.hnd.fd, 4); - if (bind (serv.hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { - log_emerg("pptp: failed to bind socket: %s\n", strerror(errno)); - close(serv.hnd.fd); - return; - } - - if (listen (serv.hnd.fd, 100) < 0) { - log_emerg("pptp: failed to listen socket: %s\n", strerror(errno)); - close(serv.hnd.fd); - return; - } - - if (fcntl(serv.hnd.fd, F_SETFL, O_NONBLOCK)) { - log_emerg("pptp: failed to set nonblocking mode: %s\n", strerror(errno)); - close(serv.hnd.fd); - return; - } - - conn_pool = mempool_create(sizeof(struct pptp_conn_t)); - - load_config(); - - triton_context_register(&serv.ctx, NULL); - triton_md_register_handler(&serv.ctx, &serv.hnd); - triton_md_enable_handler(&serv.hnd, MD_MODE_READ); - triton_context_wakeup(&serv.ctx); - - cli_register_simple_cmd2(show_stat_exec, NULL, 2, "show", "stat"); - - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); -} - diff --git a/accel-pptpd/ctrl/pptp/pptp_prot.h b/accel-pptpd/ctrl/pptp/pptp_prot.h deleted file mode 100644 index ee8cb34..0000000 --- a/accel-pptpd/ctrl/pptp/pptp_prot.h +++ /dev/null @@ -1,299 +0,0 @@ -#ifndef PPTP_PROT_H -#define PPTP_PROT_H - -#include - -#define PPTP_MAX_MTU 1436 - -#define hton8(x) (x) -#define ntoh8(x) (x) -#define hton16(x) htons(x) -#define ntoh16(x) ntohs(x) -#define hton32(x) htonl(x) -#define ntoh32(x) ntohl(x) - -/* PPTP magic numbers: ----------------------------------------- */ - -#define PPTP_MAGIC 0x1A2B3C4D /* Magic cookie for PPTP datagrams */ -#define PPTP_PORT 1723 /* PPTP TCP port number */ -#define PPTP_PROTO 47 /* PPTP IP protocol number */ - -/* PPTP result codes:---------------------------------------- */ -#define PPTP_CONN_RES_SUCCESS 1 -#define PPTP_CONN_RES_GE 2 -#define PPTP_CONN_RES_EXISTS 3 -#define PPTP_CONN_RES_AUTH 4 -#define PPTP_CONN_RES_PROTOCOL 5 - -#define PPTP_CONN_STOP_OK 1 -#define PPTP_CONN_STOP_GE 2 - -#define PPTP_CALL_RES_OK 1 -#define PPTP_CALL_RES_GE 2 - -#define PPTP_GE_NOCONN 1 - -/* Control Connection Message Types: --------------------------- */ - -#define PPTP_MESSAGE_CONTROL 1 -#define PPTP_MESSAGE_MANAGE 2 - -/* Control Message Types: -------------------------------------- */ - -/* (Control Connection Management) */ -#define PPTP_START_CTRL_CONN_RQST 1 -#define PPTP_START_CTRL_CONN_RPLY 2 -#define PPTP_STOP_CTRL_CONN_RQST 3 -#define PPTP_STOP_CTRL_CONN_RPLY 4 -#define PPTP_ECHO_RQST 5 -#define PPTP_ECHO_RPLY 6 - -/* (Call Management) */ -#define PPTP_OUT_CALL_RQST 7 -#define PPTP_OUT_CALL_RPLY 8 -#define PPTP_IN_CALL_RQST 9 -#define PPTP_IN_CALL_RPLY 10 -#define PPTP_IN_CALL_CONNECT 11 -#define PPTP_CALL_CLEAR_RQST 12 -#define PPTP_CALL_CLEAR_NTFY 13 - -/* (Error Reporting) */ -#define PPTP_WAN_ERR_NTFY 14 - -/* (PPP Session Control) */ -#define PPTP_SET_LINK_INFO 15 - -/* PPTP version information: --------------------------------------*/ -#define PPTP_VERSION_STRING "1.00" -#define PPTP_VERSION 0x100 -#define PPTP_FIRMWARE_STRING "0.01" -#define PPTP_FIRMWARE_VERSION 0x001 - -#define PPTP_HOSTNAME "local" -#define PPTP_VENDOR "cananian" - -/* PPTP capabilities: ---------------------------------------------*/ - -/* (Framing capabilities for msg sender) */ -#define PPTP_FRAME_ASYNC 1 -#define PPTP_FRAME_SYNC 2 -#define PPTP_FRAME_ANY 3 - -/* (Bearer capabilities for msg sender) */ -#define PPTP_BEARER_ANALOG 1 -#define PPTP_BEARER_DIGITAL 2 -#define PPTP_BEARER_ANY 3 - -#define PPTP_RESULT_GENERAL_ERROR 2 - -/* (Reasons to close a connection) */ -#define PPTP_STOP_NONE 1 /* no good reason */ -#define PPTP_STOP_PROTOCOL 2 /* can't support peer's protocol version */ -#define PPTP_STOP_LOCAL_SHUTDOWN 3 /* requester is being shut down */ - -/* PPTP datagram structures (all data in network byte order): ----------*/ - -struct pptp_header -{ - uint16_t length; /* message length in octets, including header */ - uint16_t pptp_type; /* PPTP message type. 1 for control message. */ - uint32_t magic; /* this should be PPTP_MAGIC. */ - uint16_t ctrl_type; /* Control message type (0-15) */ - uint16_t reserved0; /* reserved. MUST BE ZERO. */ -}__attribute__((packed)); - -struct pptp_start_ctrl_conn /* for control message types 1 and 2 */ -{ - struct pptp_header header; - - uint16_t version; /* PPTP protocol version. = PPTP_VERSION */ - uint8_t result_code; /* these two fields should be zero on rqst msg*/ - uint8_t error_code; /* 0 unless result_code==2 (General Error) */ - uint32_t framing_cap; /* Framing capabilities */ - uint32_t bearer_cap; /* Bearer Capabilities */ - uint16_t max_channels; /* Maximum Channels (=0 for PNS, PAC ignores) */ - uint16_t firmware_rev; /* Firmware or Software Revision */ - uint8_t hostname[64]; /* Host Name (64 octets, zero terminated) */ - uint8_t vendor[64]; /* Vendor string (64 octets, zero term.) */ -}__attribute__((packed)); - -struct pptp_stop_ctrl_conn /* for control message types 3 and 4 */ -{ - struct pptp_header header; - - uint8_t reason_result; /* reason for rqst, result for rply */ - uint8_t error_code; /* MUST be 0, unless rply result==2 (general err)*/ - uint16_t reserved1; /* MUST be 0 */ -}__attribute__((packed)); - -struct pptp_echo_rqst /* for control message type 5 */ -{ - struct pptp_header header; - uint32_t identifier; /* arbitrary value set by sender which is used */ - /* to match up reply and request */ -}__attribute__((packed)); - -struct pptp_echo_rply /* for control message type 6 */ -{ - struct pptp_header header; - uint32_t identifier; /* should correspond to id of rqst */ - uint8_t result_code; - uint8_t error_code; /* =0, unless result_code==2 (general error) */ - uint16_t reserved1; /* MUST BE ZERO */ -}__attribute__((packed)); - -struct pptp_out_call_rqst /* for control message type 7 */ -{ - struct pptp_header header; - uint16_t call_id; /* Call ID (unique id used to multiplex data) */ - uint16_t call_sernum; /* Call Serial Number (used for logging) */ - uint32_t bps_min; /* Minimum BPS (lowest acceptable line speed) */ - uint32_t bps_max; /* Maximum BPS (highest acceptable line speed) */ - uint32_t bearer; /* Bearer type */ - uint32_t framing; /* Framing type */ - uint16_t recv_size; /* Recv. Window Size (no. of buffered packets) */ - uint16_t delay; /* Packet Processing Delay (in 1/10 sec) */ - uint16_t phone_len; /* Phone Number Length (num. of valid digits) */ - uint16_t reserved1; /* MUST BE ZERO */ - uint8_t phone_num[64]; /* Phone Number (64 octets, null term.) */ - uint8_t subaddress[64]; /* Subaddress (64 octets, null term.) */ -}__attribute__((packed)); - -struct pptp_out_call_rply /* for control message type 8 */ -{ - struct pptp_header header; - uint16_t call_id; /* Call ID (used to multiplex data over tunnel)*/ - uint16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/ - uint8_t result_code; /* Result Code (1 is no errors) */ - uint8_t error_code; /* Error Code (=0 unless result_code==2) */ - uint16_t cause_code; /* Cause Code (addt'l failure information) */ - uint32_t speed; /* Connect Speed (in BPS) */ - uint16_t recv_size; /* Recv. Window Size (no. of buffered packets) */ - uint16_t delay; /* Packet Processing Delay (in 1/10 sec) */ - uint32_t channel; /* Physical Channel ID (for logging) */ -}__attribute__((packed)); - -struct pptp_in_call_rqst /* for control message type 9 */ -{ - struct pptp_header header; - uint16_t call_id; /* Call ID (unique id used to multiplex data) */ - uint16_t call_sernum; /* Call Serial Number (used for logging) */ - uint32_t bearer; /* Bearer type */ - uint32_t channel; /* Physical Channel ID (for logging) */ - uint16_t dialed_len; /* Dialed Number Length (# of valid digits) */ - uint16_t dialing_len; /* Dialing Number Length (# of valid digits) */ - uint8_t dialed_num[64]; /* Dialed Number (64 octets, zero term.) */ - uint8_t dialing_num[64]; /* Dialing Number (64 octets, zero term.) */ - uint8_t subaddress[64]; /* Subaddress (64 octets, zero term.) */ -}__attribute__((packed)); - -struct pptp_in_call_rply /* for control message type 10 */ -{ - struct pptp_header header; - uint16_t call_id; /* Call ID (used to multiplex data over tunnel)*/ - uint16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/ - uint8_t result_code; /* Result Code (1 is no errors) */ - uint8_t error_code; /* Error Code (=0 unless result_code==2) */ - uint16_t recv_size; /* Recv. Window Size (no. of buffered packets) */ - uint16_t delay; /* Packet Processing Delay (in 1/10 sec) */ - uint16_t reserved1; /* MUST BE ZERO */ -}__attribute__((packed)); - -struct pptp_in_call_connect /* for control message type 11 */ -{ - struct pptp_header header; - uint16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/ - uint16_t reserved1; /* MUST BE ZERO */ - uint32_t speed; /* Connect Speed (in BPS) */ - uint16_t recv_size; /* Recv. Window Size (no. of buffered packets) */ - uint16_t delay; /* Packet Processing Delay (in 1/10 sec) */ - uint32_t framing; /* Framing type */ -}__attribute__((packed)); - -struct pptp_call_clear_rqst /* for control message type 12 */ -{ - struct pptp_header header; - uint16_t call_id; /* Call ID (used to multiplex data over tunnel)*/ - uint16_t reserved1; /* MUST BE ZERO */ -}__attribute__((packed)); - -struct pptp_call_clear_ntfy /* for control message type 13 */ -{ - struct pptp_header header; - uint16_t call_id; /* Call ID (used to multiplex data over tunnel)*/ - uint8_t result_code; /* Result Code */ - uint8_t error_code; /* Error Code (=0 unless result_code==2) */ - uint16_t cause_code; /* Cause Code (for ISDN, is Q.931 cause code) */ - uint16_t reserved1; /* MUST BE ZERO */ - uint8_t call_stats[128]; /* Call Statistics: 128 octets, ascii, 0-term */ -}__attribute__((packed)); - -struct pptp_wan_err_ntfy /* for control message type 14 */ -{ - struct pptp_header header; - uint16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/ - uint16_t reserved1; /* MUST BE ZERO */ - uint32_t crc_errors; /* CRC errors */ - uint32_t frame_errors; /* Framing errors */ - uint32_t hard_errors; /* Hardware overruns */ - uint32_t buff_errors; /* Buffer overruns */ - uint32_t time_errors; /* Time-out errors */ - uint32_t align_errors; /* Alignment errors */ -}__attribute__((packed)); - -struct pptp_set_link_info /* for control message type 15 */ -{ - struct pptp_header header; - uint16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst) */ - uint16_t reserved1; /* MUST BE ZERO */ - uint32_t send_accm; /* Send ACCM (for PPP packets; default 0xFFFFFFFF)*/ - uint32_t recv_accm; /* Receive ACCM (for PPP pack.;default 0xFFFFFFFF)*/ -}__attribute__((packed)); - -/* helpful #defines: -------------------------------------------- */ -#define pptp_isvalid_ctrl(header, type, length) \ - (!( ( ntoh16(((struct pptp_header *)header)->length) < (length) ) || \ - ( ntoh16(((struct pptp_header *)header)->pptp_type) !=(type) ) || \ - ( ntoh32(((struct pptp_header *)header)->magic) !=PPTP_MAGIC) || \ - ( ntoh16(((struct pptp_header *)header)->ctrl_type) > PPTP_SET_LINK_INFO) || \ - ( ntoh16(((struct pptp_header *)header)->reserved0) !=0 ) )) - -#define PPTP_HEADER_CTRL(type) \ -{ hton16(PPTP_CTRL_SIZE(type)), \ - hton16(PPTP_MESSAGE_CONTROL), \ - hton32(PPTP_MAGIC), \ - hton16(type), 0 } - -#define PPTP_CTRL_SIZE(type) ( \ -(type==PPTP_START_CTRL_CONN_RQST)?sizeof(struct pptp_start_ctrl_conn): \ -(type==PPTP_START_CTRL_CONN_RPLY)?sizeof(struct pptp_start_ctrl_conn): \ -(type==PPTP_STOP_CTRL_CONN_RQST )?sizeof(struct pptp_stop_ctrl_conn): \ -(type==PPTP_STOP_CTRL_CONN_RPLY )?sizeof(struct pptp_stop_ctrl_conn): \ -(type==PPTP_ECHO_RQST )?sizeof(struct pptp_echo_rqst): \ -(type==PPTP_ECHO_RPLY )?sizeof(struct pptp_echo_rply): \ -(type==PPTP_OUT_CALL_RQST )?sizeof(struct pptp_out_call_rqst): \ -(type==PPTP_OUT_CALL_RPLY )?sizeof(struct pptp_out_call_rply): \ -(type==PPTP_IN_CALL_RQST )?sizeof(struct pptp_in_call_rqst): \ -(type==PPTP_IN_CALL_RPLY )?sizeof(struct pptp_in_call_rply): \ -(type==PPTP_IN_CALL_CONNECT )?sizeof(struct pptp_in_call_connect): \ -(type==PPTP_CALL_CLEAR_RQST )?sizeof(struct pptp_call_clear_rqst): \ -(type==PPTP_CALL_CLEAR_NTFY )?sizeof(struct pptp_call_clear_ntfy): \ -(type==PPTP_WAN_ERR_NTFY )?sizeof(struct pptp_wan_err_ntfy): \ -(type==PPTP_SET_LINK_INFO )?sizeof(struct pptp_set_link_info): \ -0) -#define max(a,b) (((a)>(b))?(a):(b)) -#define PPTP_CTRL_SIZE_MAX ( \ -max(sizeof(struct pptp_start_ctrl_conn), \ -max(sizeof(struct pptp_echo_rqst), \ -max(sizeof(struct pptp_echo_rply), \ -max(sizeof(struct pptp_out_call_rqst), \ -max(sizeof(struct pptp_out_call_rply), \ -max(sizeof(struct pptp_in_call_rqst), \ -max(sizeof(struct pptp_in_call_rply), \ -max(sizeof(struct pptp_in_call_connect), \ -max(sizeof(struct pptp_call_clear_rqst), \ -max(sizeof(struct pptp_call_clear_ntfy), \ -max(sizeof(struct pptp_wan_err_ntfy), \ -max(sizeof(struct pptp_set_link_info), 0))))))))))))) - -#endif diff --git a/accel-pptpd/extra/CMakeLists.txt b/accel-pptpd/extra/CMakeLists.txt deleted file mode 100644 index 5578e93..0000000 --- a/accel-pptpd/extra/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -ADD_LIBRARY(pppd_compat SHARED pppd_compat.c) -ADD_LIBRARY(ippool SHARED ippool.c) -ADD_LIBRARY(sigchld SHARED sigchld.c) -ADD_LIBRARY(chap-secrets SHARED chap-secrets.c) - -INSTALL(TARGETS pppd_compat ippool sigchld chap-secrets - LIBRARY DESTINATION lib/accel-pptp -) - -IF (SHAPER) - ADD_LIBRARY(shaper_tbf SHARED shaper_tbf.c) - IF (LIBNL_PREFIX) - SET_PROPERTY(TARGET shaper_tbf PROPERTY COMPILE_FLAGS "-I${LIBNL_PREFIX}/include") - SET_PROPERTY(TARGET shaper_tbf PROPERTY LINK_FLAGS "-L${LIBNL_PREFIX}/lib") - ENDIF (LIBNL_PREFIX) - TARGET_LINK_LIBRARIES(shaper_tbf nl m) - INSTALL(TARGETS shaper_tbf LIBRARY DESTINATION lib/accel-pptp) -ENDIF (SHAPER) - diff --git a/accel-pptpd/extra/chap-secrets.c b/accel-pptpd/extra/chap-secrets.c deleted file mode 100644 index 3550347..0000000 --- a/accel-pptpd/extra/chap-secrets.c +++ /dev/null @@ -1,281 +0,0 @@ -#include -#include -#include -#include -#include - -#include "pwdb.h" -#include "ipdb.h" -#include "ppp.h" -#include "events.h" -#include "triton.h" -#include "log.h" - -#include "memdebug.h" - -static char *def_chap_secrets = "/etc/ppp/chap-secrets"; -static char *conf_chap_secrets; -static in_addr_t conf_gw_ip_address = 0; - -static void *pd_key; -static struct ipdb_t ipdb; - -struct cs_pd_t -{ - struct ppp_pd_t pd; - struct ipdb_item_t ip; - char *passwd; - char *rate; -}; - -static char *skip_word(char *ptr) -{ - char quote = 0; - - if (*ptr == '\'' || *ptr == '"') { - quote = *ptr; - ptr++; - } - - for(; *ptr; ptr++) { - if (quote) { - if (*ptr == '\n') - break; - if (*ptr == '\\' && ptr[1] && ptr[1] != '\n') { - memmove(ptr, ptr + 1, strlen(ptr)); - continue; - } - if (*ptr == quote) { - *ptr = ' '; - break; - } - } else if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') - break; - } - return ptr; -} -static char *skip_space(char *ptr) -{ - for(; *ptr; ptr++) - if (*ptr != ' ' && *ptr != '\t') - break; - return ptr; -} -static int split(char *buf, char **ptr) -{ - int i; - - for (i = 0; i < 4; i++) { - buf = skip_word(buf); - if (!*buf) - return i; - - *buf = 0; - - buf = skip_space(buf + 1); - if (!*buf) - return i; - - if (*buf == '"' || *buf == '\'') - ptr[i] = buf + 1; - else - ptr[i] = buf; - } - - buf = skip_word(buf); - //if (*buf == '\n') - *buf = 0; - //else if (*buf) - // return -1; - - return i; -} - - -static struct cs_pd_t *create_pd(struct ppp_t *ppp, const char *username) -{ - FILE *f; - char *buf; - char *ptr[5]; - int n; - struct cs_pd_t *pd; - - if (!conf_chap_secrets) - return NULL; - - f = fopen(conf_chap_secrets, "r"); - if (!f) { - log_error("chap-secrets: open '%s': %s\n", conf_chap_secrets, strerror(errno)); - return NULL; - } - - buf = _malloc(4096); - if (!buf) { - log_emerg("chap-secrets: out of memory\n"); - fclose(f); - return NULL; - } - - while (fgets(buf, 4096, f)) { - if (buf[0] == '#') - continue; - n = split(buf, ptr); - if (n < 3) - continue; - if (*buf == '\'' || *buf == '"') { - if (!strcmp(buf + 1, username)) - goto found; - } else { - if (!strcmp(buf, username)) - goto found; - } - } - -out: - fclose(f); - _free(buf); - return NULL; - -found: - pd = _malloc(sizeof(*pd)); - if (!pd) { - log_emerg("chap-secrets: out of memory\n"); - goto out; - } - - memset(pd, 0, sizeof(*pd)); - pd->pd.key = &pd_key; - pd->passwd = _strdup(ptr[1]); - if (!pd->passwd) { - log_emerg("chap-secrets: out of memory\n"); - _free(pd); - goto out; - } - - pd->ip.addr = conf_gw_ip_address; - if (n >= 3) - pd->ip.peer_addr = inet_addr(ptr[2]); - pd->ip.owner = &ipdb; - - if (n == 4) - pd->rate = _strdup(ptr[3]); - - list_add_tail(&pd->pd.entry, &ppp->pd_list); - - fclose(f); - _free(buf); - - return pd; -} - -static struct cs_pd_t *find_pd(struct ppp_t *ppp) -{ - struct ppp_pd_t *pd; - - list_for_each_entry(pd, &ppp->pd_list, entry) { - if (pd->key == &pd_key) { - return container_of(pd, typeof(struct cs_pd_t), pd); - } - } - - return NULL; -} - -static void ev_ppp_finished(struct ppp_t *ppp) -{ - struct cs_pd_t *pd = find_pd(ppp); - - if (!pd) - return; - - list_del(&pd->pd.entry); - _free(pd->passwd); - if (pd->rate) - _free(pd->rate); - _free(pd); -} - -static void ev_ppp_pre_up(struct ppp_t *ppp) -{ - struct cs_pd_t *pd = find_pd(ppp); - struct ev_shaper_t ev = { - .ppp = ppp, - }; - - if (!pd) - return; - - if (pd->rate) { - ev.val = pd->rate; - triton_event_fire(EV_SHAPER, &ev); - } -} - -static struct ipdb_item_t *get_ip(struct ppp_t *ppp) -{ - struct cs_pd_t *pd; - - if (!conf_gw_ip_address) - return NULL; - - pd = find_pd(ppp); - - if (!pd) - return NULL; - - if (!pd->ip.addr) - return NULL; - - return &pd->ip; -} - -static char* get_passwd(struct pwdb_t *pwdb, struct ppp_t *ppp, const char *username) -{ - struct cs_pd_t *pd = find_pd(ppp); - - if (!pd) - pd = create_pd(ppp, username); - - if (!pd) - return NULL; - - return _strdup(pd->passwd); -} - -static struct ipdb_t ipdb = { - .get = get_ip, -}; - -static struct pwdb_t pwdb = { - .get_passwd = get_passwd, -}; - -static void load_config(void) -{ - const char *opt; - - if (conf_chap_secrets && conf_chap_secrets != def_chap_secrets) - _free(conf_chap_secrets); - opt = conf_get_opt("chap-secrets", "chap-secrets"); - if (opt) - conf_chap_secrets = _strdup(opt); - else - conf_chap_secrets = def_chap_secrets; - - opt = conf_get_opt("chap-secrets", "gw-ip-address"); - if (opt) - conf_gw_ip_address = inet_addr(opt); -} - -static void __init init(void) -{ - load_config(); - - pwdb_register(&pwdb); - ipdb_register(&ipdb); - - triton_event_register_handler(EV_PPP_FINISHED, (triton_event_func)ev_ppp_finished); - triton_event_register_handler(EV_PPP_PRE_UP, (triton_event_func)ev_ppp_pre_up); - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); -} - diff --git a/accel-pptpd/extra/ippool.c b/accel-pptpd/extra/ippool.c deleted file mode 100644 index 6136a14..0000000 --- a/accel-pptpd/extra/ippool.c +++ /dev/null @@ -1,208 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "ipdb.h" -#include "list.h" -#include "spinlock.h" - -#include "memdebug.h" - -struct ippool_item_t -{ - struct list_head entry; - struct ipdb_item_t it; -}; - -struct ipaddr_t -{ - struct list_head entry; - in_addr_t addr; -}; - -static LIST_HEAD(gw_list); -static LIST_HEAD(tunnel_list); -static LIST_HEAD(ippool); -static spinlock_t pool_lock = SPINLOCK_INITIALIZER; -static struct ipdb_t ipdb; - -static in_addr_t conf_gw_ip_address; -static int cnt; - -static void parse_gw_ip_address(const char *val) -{ - if (!val) - return; - - conf_gw_ip_address = inet_addr(val); -} - -//parses ranges like x.x.x.x/mask -static int parse1(const char *str, uint32_t *begin, uint32_t *end) -{ - int n, f1, f2, f3, f4, m, mask = 0; - - n = sscanf(str, "%u.%u.%u.%u/%u",&f1, &f2, &f3, &f4, &m); - if (n != 5) - return -1; - if (f1 > 255) - return -1; - if (f2 > 255) - return -1; - if (f3 > 255) - return -1; - if (f4 > 255) - return -1; - if (m == 0 || m > 32) - return -1; - - for (n = 0; n < m ; n++) - mask |= 1 << n; - - *begin = (f4 << 24) | (f3 << 16) | (f2 << 8) | f1; - *end = *begin | ~mask; - - return 0; -} - -//parses ranges like x.x.x.x-y -static int parse2(const char *str, uint32_t *begin, uint32_t *end) -{ - int n, f1, f2, f3, f4, m; - - n = sscanf(str, "%u.%u.%u.%u-%u",&f1, &f2, &f3, &f4, &m); - if (n != 5) - return -1; - if (f1 > 255) - return -1; - if (f2 > 255) - return -1; - if (f3 > 255) - return -1; - if (f4 > 255) - return -1; - if (m < f4 || m > 255) - return -1; - - *begin = (f4 << 24) | (f3 << 16) | (f2 << 8) | f1; - *end = (m << 24) | (f3 << 16) | (f2 << 8) | f1; - - return 0; -} - -static void add_range(struct list_head *list, const char *name) -{ - uint32_t i,startip, endip; - struct ipaddr_t *ip; - - if (parse1(name, &startip, &endip)) - if (parse2(name, &startip, &endip)) { - fprintf(stderr, "ippool: cann't parse '%s'\n", name); - _exit(EXIT_FAILURE); - } - - for (i = ntohl(startip); i <= ntohl(endip); i++) { - ip = malloc(sizeof(*ip)); - ip->addr = htonl(i); - list_add_tail(&ip->entry, list); - cnt++; - } -} - -static void generate_pool(void) -{ - struct ippool_item_t *it; - struct ipaddr_t *addr = NULL; - struct ipaddr_t *peer_addr; - - while (1) { - if (list_empty(&tunnel_list)) - break; - else { - peer_addr = list_entry(tunnel_list.next, typeof(*peer_addr), entry); - list_del(&peer_addr->entry); - } - - if (!conf_gw_ip_address) { - if (list_empty(&gw_list)) - break; - else { - addr = list_entry(gw_list.next, typeof(*addr), entry); - list_del(&addr->entry); - } - } - - it = malloc(sizeof(*it)); - if (!it) { - fprintf(stderr, "ippool: out of memory\n"); - break; - } - - it->it.owner = &ipdb; - if (conf_gw_ip_address) - it->it.addr = conf_gw_ip_address; - else - it->it.addr = addr->addr; - - it->it.peer_addr = peer_addr->addr; - - list_add_tail(&it->entry, &ippool); - } -} - -static struct ipdb_item_t *get_ip(struct ppp_t *ppp) -{ - struct ippool_item_t *it; - - spin_lock(&pool_lock); - if (!list_empty(&ippool)) { - it = list_entry(ippool.next, typeof(*it), entry); - list_del(&it->entry); - } else - it = NULL; - spin_unlock(&pool_lock); - - return it ? &it->it : NULL; -} - -static void put_ip(struct ppp_t *ppp, struct ipdb_item_t *it) -{ - struct ippool_item_t *pit = container_of(it, typeof(*pit), it); - - spin_lock(&pool_lock); - list_add_tail(&pit->entry, &ippool); - spin_unlock(&pool_lock); -} - -static struct ipdb_t ipdb = { - .get = get_ip, - .put = put_ip, -}; - -static void __init ipool_init(void) -{ - struct conf_sect_t *s = conf_get_section("ip-pool"); - struct conf_option_t *opt; - - if (!s) - return; - - list_for_each_entry(opt, &s->items, entry) { - if (!strcmp(opt->name, "gw-ip-address")) - parse_gw_ip_address(opt->val); - else if (!strcmp(opt->name, "gw")) - add_range(&gw_list, opt->val); - else if (!strcmp(opt->name, "tunnel")) - add_range(&tunnel_list, opt->val); - else if (!opt->val) - add_range(&tunnel_list, opt->name); - } - - generate_pool(); - - ipdb_register(&ipdb); -} - diff --git a/accel-pptpd/extra/pppd_compat.c b/accel-pptpd/extra/pppd_compat.c deleted file mode 100644 index f897dd6..0000000 --- a/accel-pptpd/extra/pppd_compat.c +++ /dev/null @@ -1,523 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "linux_ppp.h" - -#include "triton.h" - -#include "events.h" -#include "ppp.h" -#include "log.h" -#include "utils.h" -#include "sigchld.h" - -#ifdef RADIUS -#include "radius.h" -#endif - -#include "memdebug.h" - -static char *conf_ip_up = "/etc/ppp/ip-up"; -static char *conf_ip_pre_up; -static char *conf_ip_down = "/etc/ppp/ip-down"; -static char *conf_ip_change; -static char *conf_radattr_prefix = "/var/run/radattr."; -static int conf_verbose = 0; - -static void *pd_key; - -struct pppd_compat_pd_t -{ - struct ppp_pd_t pd; - struct ppp_t *ppp; - struct sigchld_handler_t ip_pre_up_hnd; - struct sigchld_handler_t ip_up_hnd; - struct sigchld_handler_t ip_change_hnd; - struct sigchld_handler_t ip_down_hnd; -#ifdef RADIUS - int radattr_saved:1; -#endif - int started:1; - int res; - int bytes_sent; - int bytes_rcvd; -}; - -static struct pppd_compat_pd_t *find_pd(struct ppp_t *ppp); -static void fill_argv(char **argv, struct ppp_t *ppp, char *path); -static void fill_env(char **env, struct pppd_compat_pd_t *pd); -#ifdef RADIUS -static void remove_radattr(struct ppp_t *ppp); -static void write_radattr(struct ppp_t *ppp, struct rad_packet_t *pack, int save_old); -#endif - -static void ip_pre_up_handler(struct sigchld_handler_t *h, int status) -{ - struct pppd_compat_pd_t *pd = container_of(h, typeof(*pd), ip_pre_up_hnd); - if (conf_verbose) { - log_switch(NULL, pd->ppp); - log_ppp_info2("pppd_compat: ip-pre-up finished (%i)\n", status); - pd->res = status; - } - sched_yield(); - triton_context_wakeup(pd->ppp->ctrl->ctx); -} - -static void ip_up_handler(struct sigchld_handler_t *h, int status) -{ - struct pppd_compat_pd_t *pd = container_of(h, typeof(*pd), ip_up_hnd); - if (conf_verbose) { - log_switch(NULL, pd->ppp); - log_ppp_info2("pppd_compat: ip-up finished (%i)\n", status); - } -} - -static void ip_down_handler(struct sigchld_handler_t *h, int status) -{ - struct pppd_compat_pd_t *pd = container_of(h, typeof(*pd), ip_down_hnd); - if (conf_verbose) { - log_switch(NULL, pd->ppp); - log_ppp_info2("pppd_compat: ip-down finished (%i)\n", status); - } - sched_yield(); - triton_context_wakeup(pd->ppp->ctrl->ctx); -} - -static void ip_change_handler(struct sigchld_handler_t *h, int status) -{ - struct pppd_compat_pd_t *pd = container_of(h, typeof(*pd), ip_change_hnd); - if (conf_verbose) { - log_switch(NULL, pd->ppp); - log_ppp_info2("pppd_compat: ip-change finished (%i)\n", status); - } - sched_yield(); - pd->res = status; - triton_context_wakeup(pd->ppp->ctrl->ctx); -} - -static void ev_ppp_starting(struct ppp_t *ppp) -{ - struct pppd_compat_pd_t *pd = _malloc(sizeof(*pd)); - - if (!pd) { - log_emerg("pppd_compat: out of memory\n"); - return; - } - - memset(pd, 0, sizeof(*pd)); - pd->pd.key = &pd_key; - pd->ppp = ppp; - pd->ip_pre_up_hnd.handler = ip_pre_up_handler; - pd->ip_up_hnd.handler = ip_up_handler; - pd->ip_down_hnd.handler = ip_down_handler; - pd->ip_change_hnd.handler = ip_change_handler; - list_add_tail(&pd->pd.entry, &ppp->pd_list); -} - -static void ev_ppp_pre_up(struct ppp_t *ppp) -{ - pid_t pid; - char *argv[8]; - char *env[2]; - char ipaddr[17]; - char peer_ipaddr[17]; - char peername[64]; - struct pppd_compat_pd_t *pd = find_pd(ppp); - - if (!pd) - return; - - argv[4] = ipaddr; - argv[5] = peer_ipaddr; - fill_argv(argv, ppp, conf_ip_up); - - env[0] = peername; - env[1] = NULL; - fill_env(env, pd); - - if (conf_ip_pre_up) { - sigchld_lock(); - pid = fork(); - if (pid > 0) { - pd->ip_pre_up_hnd.pid = pid; - sigchld_register_handler(&pd->ip_pre_up_hnd); - if (conf_verbose) - log_ppp_info2("pppd_compat: ip-pre-up started (pid %i)\n", pid); - sigchld_unlock(); - triton_context_schedule(); - pthread_mutex_lock(&pd->ip_pre_up_hnd.lock); - pthread_mutex_unlock(&pd->ip_pre_up_hnd.lock); - if (pd->res != 0) { - ppp_terminate(ppp, 0, pd->res < 0 ? TERM_NAS_ERROR : TERM_ADMIN_RESET); - return; - } - } else if (pid == 0) { - execve(conf_ip_pre_up, argv, env); - log_emerg("pppd_compat: exec '%s': %s\n", conf_ip_pre_up, strerror(errno)); - _exit(EXIT_FAILURE); - } else - log_error("pppd_compat: fork: %s\n", strerror(errno)); - } -} - -static void ev_ppp_started(struct ppp_t *ppp) -{ - pid_t pid; - char *argv[8]; - char *env[2]; - char ipaddr[17]; - char peer_ipaddr[17]; - char peername[64]; - struct pppd_compat_pd_t *pd = find_pd(ppp); - - if (!pd) - return; - - argv[4] = ipaddr; - argv[5] = peer_ipaddr; - fill_argv(argv, ppp, conf_ip_up); - - env[0] = peername; - env[1] = NULL; - fill_env(env, pd); - - if (conf_ip_up) { - sigchld_lock(); - pid = fork(); - if (pid > 0) { - pd->ip_up_hnd.pid = pid; - sigchld_register_handler(&pd->ip_up_hnd); - if (conf_verbose) - log_ppp_info2("pppd_compat: ip-up started (pid %i)\n", pid); - sigchld_unlock(); - } else if (pid == 0) { - execve(conf_ip_up, argv, env); - log_emerg("pppd_compat: exec '%s': %s\n", conf_ip_up, strerror(errno)); - _exit(EXIT_FAILURE); - } else - log_error("pppd_compat: fork: %s\n", strerror(errno)); - } - - pd->started = 1; -} - -static void ev_ppp_finishing(struct ppp_t *ppp) -{ - struct ifpppstatsreq ifreq; - struct pppd_compat_pd_t *pd = find_pd(ppp); - - if (!pd) - return; - - memset(&ifreq, 0, sizeof(ifreq)); - ifreq.stats_ptr = (void *)&ifreq.stats; - strcpy(ifreq.ifr__name, ppp->ifname); - - if (ioctl(sock_fd, SIOCGPPPSTATS, &ifreq)) { - log_ppp_error("pppd_compat: failed to get ppp statistics: %s\n", strerror(errno)); - return; - } - - pd->bytes_sent = ifreq.stats.p.ppp_obytes; - pd->bytes_rcvd = ifreq.stats.p.ppp_ibytes; -} - -static void ev_ppp_finished(struct ppp_t *ppp) -{ - pid_t pid; - char *argv[8]; - char *env[5]; - char ipaddr[17]; - char peer_ipaddr[17]; - char peername[64]; - char connect_time[24]; - char bytes_sent[24]; - char bytes_rcvd[24]; - struct pppd_compat_pd_t *pd = find_pd(ppp); - - if (!pd) - return; - - if (!pd->started) - goto skip; - - pthread_mutex_lock(&pd->ip_up_hnd.lock); - if (pd->ip_up_hnd.pid) { - log_ppp_warn("pppd_compat: ip-up is not yet finished, terminating it ...\n"); - kill(pd->ip_up_hnd.pid, SIGTERM); - } - pthread_mutex_unlock(&pd->ip_up_hnd.lock); - - argv[4] = ipaddr; - argv[5] = peer_ipaddr; - fill_argv(argv, pd->ppp, conf_ip_down); - - env[0] = peername; - env[1] = connect_time; - env[2] = bytes_sent; - env[3] = bytes_rcvd; - env[4] = NULL; - fill_env(env, pd); - - sigchld_lock(); - pid = fork(); - if (pid > 0) { - pd->ip_down_hnd.pid = pid; - sigchld_register_handler(&pd->ip_down_hnd); - if (conf_verbose) - log_ppp_info2("pppd_compat: ip-down started (pid %i)\n", pid); - sigchld_unlock(); - triton_context_schedule(); - pthread_mutex_lock(&pd->ip_down_hnd.lock); - pthread_mutex_unlock(&pd->ip_down_hnd.lock); - } else if (pid == 0) { - execve(conf_ip_down, argv, env); - log_emerg("pppd_compat: exec '%s': %s\n", conf_ip_down, strerror(errno)); - _exit(EXIT_FAILURE); - } else - log_error("pppd_compat: fork: %s\n", strerror(errno)); - - pthread_mutex_lock(&pd->ip_up_hnd.lock); - if (pd->ip_up_hnd.pid) { - log_ppp_warn("pppd_compat: ip-up is not yet finished, killing it ...\n"); - kill(pd->ip_up_hnd.pid, SIGKILL); - pthread_mutex_unlock(&pd->ip_up_hnd.lock); - sigchld_unregister_handler(&pd->ip_up_hnd); - } else - pthread_mutex_unlock(&pd->ip_up_hnd.lock); - -skip: -#ifdef RADIUS - if (pd->radattr_saved) - remove_radattr(ppp); -#endif - - list_del(&pd->pd.entry); - _free(pd); -} - -#ifdef RADIUS -static void ev_radius_access_accept(struct ev_radius_t *ev) -{ - struct pppd_compat_pd_t *pd = find_pd(ev->ppp); - - write_radattr(ev->ppp, ev->reply, 0); - - pd->radattr_saved = 1; -} - -static void ev_radius_coa(struct ev_radius_t *ev) -{ - pid_t pid; - char *argv[8]; - char *env[2]; - char ipaddr[17]; - char peer_ipaddr[17]; - char peername[64]; - struct pppd_compat_pd_t *pd = find_pd(ev->ppp); - - if (!pd) - return; - - write_radattr(ev->ppp, ev->request, 1); - - argv[4] = ipaddr; - argv[5] = peer_ipaddr; - fill_argv(argv, pd->ppp, conf_ip_change); - - env[0] = peername; - env[1] = NULL; - fill_env(env, pd); - - sigchld_lock(); - pid = fork(); - if (pid > 0) { - pd->ip_change_hnd.pid = pid; - sigchld_register_handler(&pd->ip_change_hnd); - sigchld_unlock(); - if (conf_verbose) - log_ppp_info2("pppd_compat: ip-change started (pid %i)\n", pid); - triton_context_schedule(); - if (!ev->res) - ev->res = pd->res; - } else if (pid == 0) { - execve(conf_ip_change, argv, env); - log_emerg("pppd_compat: exec '%s': %s\n", conf_ip_change, strerror(errno)); - _exit(EXIT_FAILURE); - } else - log_error("pppd_compat: fork: %s\n", strerror(errno)); -} - -static void remove_radattr(struct ppp_t *ppp) -{ - char *fname; - - fname = _malloc(PATH_MAX); - if (!fname) { - log_emerg("pppd_compat: out of memory\n"); - return; - } - - sprintf(fname, "%s.%s", conf_radattr_prefix, ppp->ifname); - if (unlink(fname)) { - log_ppp_warn("pppd_compat: failed to remove '%s': %s\n", fname, strerror(errno)); - } - sprintf(fname, "%s_old.%s", conf_radattr_prefix, ppp->ifname); - unlink(fname); - - _free(fname); -} - -static void write_radattr(struct ppp_t *ppp, struct rad_packet_t *pack, int save_old) -{ - struct rad_attr_t *attr; - struct rad_dict_value_t *val; - FILE *f; - char *fname1, *fname2 = NULL; - int i; - - fname1 = _malloc(PATH_MAX); - if (!fname1) { - log_emerg("pppd_compat: out of memory\n"); - return; - } - - if (save_old) { - fname2 = _malloc(PATH_MAX); - if (!fname2) { - log_emerg("pppd_compat: out of memory\n"); - _free(fname1); - return; - } - } - - sprintf(fname1, "%s.%s", conf_radattr_prefix, ppp->ifname); - if (save_old) { - sprintf(fname2, "%s_old.%s", conf_radattr_prefix, ppp->ifname); - if (rename(fname1, fname2)) { - log_ppp_warn("pppd_compat: rename: %s\n", strerror(errno)); - } - } - - f = fopen(fname1, "w"); - if (f) { - list_for_each_entry(attr, &pack->attrs, entry) { - fprintf(f, "%s ", attr->attr->name); - switch (attr->attr->type) { - case ATTR_TYPE_INTEGER: - val = rad_dict_find_val(attr->attr, attr->val); - if (val) - fprintf(f, "%s\n", val->name); - else - fprintf(f, "%i\n", attr->val.integer); - break; - case ATTR_TYPE_STRING: - fprintf(f, "%s\n", attr->val.string); - break; - case ATTR_TYPE_OCTETS: - for (i = 0; i < attr->len; i++) - fprintf(f, "%02X", attr->val.octets[i]); - fprintf(f, "\n"); - break; - case ATTR_TYPE_IPADDR: - fprintf(f, "%i.%i.%i.%i\n", attr->val.ipaddr & 0xff, (attr->val.ipaddr >> 8) & 0xff, (attr->val.ipaddr >> 16) & 0xff, (attr->val.ipaddr >> 24) & 0xff); - break; - case ATTR_TYPE_DATE: - fprintf(f, "%lu\n", attr->val.date); - break; - } - } - fclose(f); - } else - log_ppp_warn("pppd_compat: failed to create '%s': %s\n", fname1, strerror(errno)); - - _free(fname1); - if (save_old) - _free(fname2); -} -#endif - -static struct pppd_compat_pd_t *find_pd(struct ppp_t *ppp) -{ - struct ppp_pd_t *pd; - struct pppd_compat_pd_t *cpd; - - list_for_each_entry(pd, &ppp->pd_list, entry) { - if (pd->key == &pd_key) { - cpd = container_of(pd, typeof(*cpd), pd); - return cpd; - } - } - - log_ppp_warn("pppd_compat: pd not found\n"); - return NULL; -} - -static void fill_argv(char **argv, struct ppp_t *ppp, char *path) -{ - argv[0] = path; - argv[1] = ppp->ifname; - argv[2] = "none"; - argv[3] = "0"; - u_inet_ntoa(ppp->ipaddr, argv[4]); - u_inet_ntoa(ppp->peer_ipaddr, argv[5]); - argv[6] = ppp->ctrl->calling_station_id; - argv[7] = NULL; -} - -static void fill_env(char **env, struct pppd_compat_pd_t *pd) -{ - snprintf(env[0], 64, "PEERNAME=%s", pd->ppp->username); - - if (pd->ppp->stop_time && env[1]) { - snprintf(env[1], 24, "CONNECT_TIME=%lu", pd->ppp->stop_time - pd->ppp->start_time); - snprintf(env[2], 24, "BYTES_SENT=%u", pd->bytes_sent); - snprintf(env[3], 24, "BYTES_RCVD=%u", pd->bytes_rcvd); - } -} - -static void __init init(void) -{ - char *opt; - - opt = conf_get_opt("pppd-compat", "ip-pre-up"); - if (opt) - conf_ip_pre_up = _strdup(opt); - - opt = conf_get_opt("pppd-compat", "ip-up"); - if (opt) - conf_ip_up = _strdup(opt); - - opt = conf_get_opt("pppd-compat", "ip-down"); - if (opt) - conf_ip_down = _strdup(opt); - - opt = conf_get_opt("pppd-compat", "ip-change"); - if (opt) - conf_ip_change = _strdup(opt); - - opt = conf_get_opt("pppd-compat", "radattr-prefix"); - if (opt) - conf_radattr_prefix = _strdup(opt); - - opt = conf_get_opt("pppd-compat", "verbose"); - if (opt && atoi(opt) > 0) - conf_verbose = 1; - - triton_event_register_handler(EV_PPP_STARTING, (triton_event_func)ev_ppp_starting); - triton_event_register_handler(EV_PPP_PRE_UP, (triton_event_func)ev_ppp_pre_up); - triton_event_register_handler(EV_PPP_STARTED, (triton_event_func)ev_ppp_started); - triton_event_register_handler(EV_PPP_FINISHING, (triton_event_func)ev_ppp_finishing); - triton_event_register_handler(EV_PPP_FINISHED, (triton_event_func)ev_ppp_finished); -#ifdef RADIUS - triton_event_register_handler(EV_RADIUS_ACCESS_ACCEPT, (triton_event_func)ev_radius_access_accept); - triton_event_register_handler(EV_RADIUS_COA, (triton_event_func)ev_radius_coa); -#endif -} diff --git a/accel-pptpd/extra/shaper_tbf.c b/accel-pptpd/extra/shaper_tbf.c deleted file mode 100644 index d7e4f0b..0000000 --- a/accel-pptpd/extra/shaper_tbf.c +++ /dev/null @@ -1,1274 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "netlink/netlink.h" -#include "netlink/socket.h" -#include "netlink/msg.h" - -#include "triton.h" -#include "events.h" -#include "log.h" -#include "ppp.h" -#include "cli.h" - -#ifdef RADIUS -#include "radius.h" -#endif - -#include "memdebug.h" - -#define RTNL_TC_RTABLE_SIZE 256 -#define TIME_UNITS_PER_SEC 1000000 - -#define ATTR_UP 1 -#define ATTR_DOWN 2 - -static int conf_verbose = 0; -#ifdef RADIUS -static int conf_attr_down = 11; //Filter-Id -static int conf_attr_up = 11; //Filter-Id -static int conf_vendor = 0; -#endif -static double conf_down_burst_factor = 0.1; -static double conf_up_burst_factor = 1; -static int conf_latency = 50; -static int conf_mpu = 0; - -static int temp_down_speed; -static int temp_up_speed; - -static pthread_rwlock_t shaper_lock = PTHREAD_RWLOCK_INITIALIZER; -static LIST_HEAD(shaper_list); - -static double tick_in_usec = 1; -static double clock_factor = 1; - -struct time_range_pd_t; -struct shaper_pd_t -{ - struct list_head entry; - struct ppp_t *ppp; - struct ppp_pd_t pd; - int temp_down_speed; - int temp_up_speed; - int down_speed; - int up_speed; - struct list_head tr_list; - struct time_range_pd_t *cur_tr; -}; - -struct time_range_pd_t -{ - struct list_head entry; - int id; - int down_speed; - int down_burst; - int up_speed; - int up_burst; -}; - -struct time_range_t -{ - struct list_head entry; - int id; - struct triton_timer_t begin; - struct triton_timer_t end; -}; - -static void *pd_key; - -static LIST_HEAD(time_range_list); -static int time_range_id; - -static void shaper_ctx_close(struct triton_context_t *); -static struct triton_context_t shaper_ctx = { - .close = shaper_ctx_close, - .before_switch = log_switch, -}; - -static unsigned tc_time2tick(unsigned time) -{ - return time*tick_in_usec; -} - -/*static unsigned tc_tick2time(unsigned tick) -{ - return tick/tick_in_usec; -}*/ - -static unsigned tc_calc_xmittime(unsigned rate, unsigned size) -{ - return tc_time2tick(TIME_UNITS_PER_SEC*((double)size/rate)); -} - -/*static unsigned tc_calc_xmitsize(unsigned rate, unsigned ticks) -{ - return ((double)rate*tc_tick2time(ticks))/TIME_UNITS_PER_SEC; -}*/ - -static void tc_calc_rtable(struct tc_ratespec *r, uint32_t *rtab, int cell_log, unsigned mtu) -{ - int i; - unsigned sz; - unsigned bps = r->rate; - unsigned mpu = r->mpu; - - if (mtu == 0) - mtu = 2047; - - if (cell_log <= 0) { - cell_log = 0; - while ((mtu >> cell_log) > 255) - cell_log++; - } - - for (i=0; i<256; i++) { - //sz = tc_adjust_size((i + 1) << cell_log, mpu, linklayer); - sz = (i + 1) << cell_log; - if (sz < mpu) - sz = mpu; - rtab[i] = tc_calc_xmittime(bps, sz); - } - - r->cell_align=-1; // Due to the sz calc - r->cell_log=cell_log; -} - -static int install_tbf(struct nl_sock *h, int ifindex, int speed, int burst) -{ - struct tc_tbf_qopt opt; - struct nl_msg *msg; - struct nl_msg *pmsg = NULL; - uint32_t rtab[RTNL_TC_RTABLE_SIZE]; - double rate = speed * 1000 / 8; - double bucket = burst ? burst : rate * conf_down_burst_factor; - - struct tcmsg tchdr = { - .tcm_family = AF_UNSPEC, - .tcm_ifindex = ifindex, - .tcm_handle = 0x00010000, - .tcm_parent = TC_H_ROOT, - }; - - memset(&opt, 0, sizeof(opt)); - - opt.rate.rate = rate; - opt.rate.mpu = conf_mpu; - opt.limit = rate*conf_latency/1000 + bucket; - opt.buffer = tc_calc_xmittime(rate, bucket); - - tc_calc_rtable(&opt.rate, rtab, 0, 0); - - msg = nlmsg_alloc(); - if (!msg) - goto out_err; - - NLA_PUT(msg, TCA_TBF_PARMS, sizeof(opt), &opt); - NLA_PUT(msg, TCA_TBF_RTAB, sizeof(rtab), rtab); - - pmsg = nlmsg_alloc_simple(RTM_NEWQDISC, NLM_F_CREATE | NLM_F_REPLACE); - if (!pmsg) - goto out_err; - - if (nlmsg_append(pmsg, &tchdr, sizeof(tchdr), NLMSG_ALIGNTO) < 0) - goto out_err; - - NLA_PUT_STRING(pmsg, TCA_KIND, "tbf"); - nla_put_nested(pmsg, TCA_OPTIONS, msg); - - if (nl_send_auto_complete(h, pmsg) < 0) - goto out_err; - - if (nl_wait_for_ack(h) < 0) - goto out_err; - - nlmsg_free(msg); - nlmsg_free(pmsg); - - return 0; - -out_err: -nla_put_failure: - - if (msg) - nlmsg_free(msg); - - if (pmsg) - nlmsg_free(pmsg); - - log_ppp_error("tbf: error occured, tbf is not installed\n"); - - return -1; -} - -static int install_ingress(struct nl_sock *h, int ifindex) -{ - struct nl_msg *pmsg; - - struct tcmsg tchdr = { - .tcm_family = AF_UNSPEC, - .tcm_ifindex = ifindex, - .tcm_handle = 0xffff0000, - .tcm_parent = TC_H_INGRESS, - }; - - pmsg = nlmsg_alloc_simple(RTM_NEWQDISC, NLM_F_CREATE | NLM_F_REPLACE); - if (!pmsg) - goto out_err; - - if (nlmsg_append(pmsg, &tchdr, sizeof(tchdr), NLMSG_ALIGNTO) < 0) - goto out_err; - - NLA_PUT_STRING(pmsg, TCA_KIND, "ingress"); - - if (nl_send_auto_complete(h, pmsg) < 0) - goto out_err; - - if (nl_wait_for_ack(h) < 0) - goto out_err; - - nlmsg_free(pmsg); - - return 0; - -out_err: -nla_put_failure: - - if (pmsg) - nlmsg_free(pmsg); - - log_ppp_error("tbf: error occured, ingress is not installed\n"); - - return -1; -} - -static int install_filter(struct nl_sock *h, int ifindex, int speed, int burst) -{ - //double rate = speed*1000/8; - //double bucket = rate*conf_burst_factor; - double rate = speed * 1000 / 8; - double bucket = burst ? burst : rate * conf_up_burst_factor; - struct nl_msg *pmsg = NULL; - struct nl_msg *msg = NULL; - struct nl_msg *msg1 = NULL; - struct nl_msg *msg2 = NULL; - struct nl_msg *msg3 = NULL; - uint32_t rtab[RTNL_TC_RTABLE_SIZE]; - - struct tcmsg tchdr = { - .tcm_family = AF_UNSPEC, - .tcm_ifindex = ifindex, - .tcm_handle = 1, - .tcm_parent = 0xffff0000, - .tcm_info = TC_H_MAKE(10 << 16, ntohs(ETH_P_IP)), - }; - - struct sel_t { - struct tc_u32_sel sel; - struct tc_u32_key key; - } sel = { - .sel.nkeys = 1, - .sel.flags = TC_U32_TERMINAL, - .key.off = 12, - }; - - struct tc_police police = { - .action = TC_POLICE_SHOT, - .rate.rate = rate, - .rate.mpu = conf_mpu, - .limit = rate*conf_latency/1000 + bucket, - .burst = tc_calc_xmittime(rate, bucket), - }; - - tc_calc_rtable(&police.rate, rtab, 0, 0); - - pmsg = nlmsg_alloc_simple(RTM_NEWTFILTER, NLM_F_CREATE | NLM_F_REPLACE); - if (!pmsg) - goto out_err; - - msg = nlmsg_alloc(); - if (!msg) - goto out_err; - - msg1 = nlmsg_alloc(); - if (!msg1) - goto out_err; - - msg2 = nlmsg_alloc(); - if (!msg2) - goto out_err; - - msg3 = nlmsg_alloc(); - if (!msg3) - goto out_err; - - if (nlmsg_append(pmsg, &tchdr, sizeof(tchdr), NLMSG_ALIGNTO) < 0) - goto out_err; - - NLA_PUT_STRING(pmsg, TCA_KIND, "u32"); - - NLA_PUT_U32(msg, TCA_U32_CLASSID, 1); - NLA_PUT(msg, TCA_U32_SEL, sizeof(sel), &sel); - - NLA_PUT_STRING(msg3, TCA_ACT_KIND, "police"); - - NLA_PUT(msg2, TCA_POLICE_TBF, sizeof(police), &police); - NLA_PUT(msg2, TCA_POLICE_RATE, sizeof(rtab), rtab); - - if (nla_put_nested(msg3, TCA_ACT_OPTIONS, msg2) < 0) - goto out_err; - - if (nla_put_nested(msg1, 1, msg3) < 0) - goto out_err; - - if (nla_put_nested(msg, TCA_U32_ACT, msg1)) - goto out_err; - - if (nla_put_nested(pmsg, TCA_OPTIONS, msg)) - goto out_err; - - if (nl_send_auto_complete(h, pmsg) < 0) - goto out_err; - - if (nl_wait_for_ack(h) < 0) - goto out_err; - - nlmsg_free(pmsg); - nlmsg_free(msg); - nlmsg_free(msg1); - nlmsg_free(msg2); - nlmsg_free(msg3); - - return 0; - -out_err: -nla_put_failure: - - if (pmsg) - nlmsg_free(pmsg); - - if (msg) - nlmsg_free(msg); - - if (msg1) - nlmsg_free(msg1); - - if (msg2) - nlmsg_free(msg1); - - if (msg3) - nlmsg_free(msg1); - - log_ppp_error("tbf: error occured, filter is not installed\n"); - - return -1; -} - - -static int install_shaper(const char *ifname, int down_speed, int down_burst, int up_speed, int up_burst) -{ - struct nl_sock *h; - struct ifreq ifr; - int err; - - memset(&ifr, 0, sizeof(ifr)); - strcpy(ifr.ifr_name, ifname); - - if (ioctl(sock_fd, SIOCGIFINDEX, &ifr)) { - log_ppp_error("tbf: ioctl(SIOCGIFINDEX)", strerror(errno)); - return -1; - } - - h = nl_socket_alloc(); - if (!h) { - log_ppp_error("tbf: nl_socket_alloc failed\n"); - return -1; - } - - err = nl_connect(h, NETLINK_ROUTE); - if (err < 0) { - log_ppp_error("tbf: nl_connect: %s", strerror(errno)); - goto out; - } - - if (down_speed) - if (install_tbf(h, ifr.ifr_ifindex, down_speed, down_burst)) - return -1; - - if (up_speed) { - if (install_ingress(h, ifr.ifr_ifindex)) - return -1; - if (install_filter(h, ifr.ifr_ifindex, up_speed, up_burst)) - return -1; - } - - nl_close(h); -out: - nl_socket_free(h); - - return 0; -} - -static struct shaper_pd_t *find_pd(struct ppp_t *ppp, int create) -{ - struct ppp_pd_t *pd; - struct shaper_pd_t *spd; - - list_for_each_entry(pd, &ppp->pd_list, entry) { - if (pd->key == &pd_key) { - spd = container_of(pd, typeof(*spd), pd); - return spd; - } - } - - if (create) { - spd = _malloc(sizeof(*spd)); - if (!spd) { - log_emerg("tbf: out of memory\n"); - return NULL; - } - - memset(spd, 0, sizeof(*spd)); - spd->ppp = ppp; - list_add_tail(&spd->pd.entry, &ppp->pd_list); - spd->pd.key = &pd_key; - INIT_LIST_HEAD(&spd->tr_list); - - pthread_rwlock_wrlock(&shaper_lock); - list_add_tail(&spd->entry, &shaper_list); - pthread_rwlock_unlock(&shaper_lock); - return spd; - } - - return NULL; -} - -static int remove_shaper(const char *ifname) -{ - struct nl_sock *h; - struct ifreq ifr; - struct nl_msg *pmsg; - int err; - - memset(&ifr, 0, sizeof(ifr)); - strcpy(ifr.ifr_name, ifname); - - if (ioctl(sock_fd, SIOCGIFINDEX, &ifr)) { - log_ppp_error("tbf: ioctl(SIOCGIFINDEX)", strerror(errno)); - return -1; - } - - struct tcmsg tchdr1 = { - .tcm_family = AF_UNSPEC, - .tcm_ifindex = ifr.ifr_ifindex, - .tcm_handle = 0x00010000, - .tcm_parent = TC_H_ROOT, - }; - - struct tcmsg tchdr2 = { - .tcm_family = AF_UNSPEC, - .tcm_ifindex = ifr.ifr_ifindex, - .tcm_handle = 0xffff0000, - .tcm_parent = TC_H_INGRESS, - }; - - h = nl_socket_alloc(); - if (!h) { - log_ppp_error("tbf: nl_socket_alloc failed\n"); - return -1; - } - - err = nl_connect(h, NETLINK_ROUTE); - if (err < 0) { - log_ppp_error("tbf: nl_connect: %s", strerror(errno)); - nl_socket_free(h); - return -1; - } - - pmsg = nlmsg_alloc_simple(RTM_DELQDISC, NLM_F_CREATE | NLM_F_REPLACE); - if (!pmsg) - goto out_err; - - if (nlmsg_append(pmsg, &tchdr1, sizeof(tchdr1), NLMSG_ALIGNTO) < 0) - goto out_err; - - if (nl_send_auto_complete(h, pmsg) < 0) - goto out_err; - - if (nl_wait_for_ack(h) < 0) - goto out_err; - - nlmsg_free(pmsg); - - pmsg = nlmsg_alloc_simple(RTM_DELQDISC, NLM_F_CREATE | NLM_F_REPLACE); - if (!pmsg) - goto out_err; - - if (nlmsg_append(pmsg, &tchdr2, sizeof(tchdr2), NLMSG_ALIGNTO) < 0) - goto out_err; - - if (nl_send_auto_complete(h, pmsg) < 0) - goto out_err; - - if (nl_wait_for_ack(h) < 0) - goto out_err; - - nlmsg_free(pmsg); - - nl_close(h); - nl_socket_free(h); - return 0; - -out_err: - log_ppp_error("tbf: failed to remove shaper\n"); - - if (pmsg) - nlmsg_free(pmsg); - - nl_close(h); - nl_socket_free(h); - - return -1; -} - -static void parse_string(const char *str, int dir, int *speed, int *burst, int *tr_id) -{ - char *endptr; - long int val; - unsigned int n1, n2, n3; - - if (strstr(str, "lcp:interface-config#1=rate-limit output access-group") == str) { - if (dir == ATTR_DOWN) { - val = sscanf(str, "lcp:interface-config#1=rate-limit output access-group %i %u %u %u conform-action transmit exceed-action drop", tr_id, &n1, &n2, &n3); - if (val == 4) { - *speed = n1/1000; - *burst = n2; - } - } - return; - } else if (strstr(str, "lcp:interface-config#1=rate-limit input access-group") == str) { - if (dir == ATTR_UP) { - val = sscanf(str, "lcp:interface-config#1=rate-limit input access-group %i %u %u %u conform-action transmit exceed-action drop", tr_id, &n1, &n2, &n3); - if (val == 4) { - *speed = n1/1000; - *burst = n2; - } - } - return; - } else if (strstr(str, "lcp:interface-config#1=rate-limit output") == str) { - if (dir == ATTR_DOWN) { - val = sscanf(str, "lcp:interface-config#1=rate-limit output %u %u %u conform-action transmit exceed-action drop", &n1, &n2, &n3); - if (val == 3) { - *speed = n1/1000; - *burst = n2; - } - } - return; - } else if (strstr(str, "lcp:interface-config#1=rate-limit input") == str) { - if (dir == ATTR_UP) { - val = sscanf(str, "lcp:interface-config#1=rate-limit input %u %u %u conform-action transmit exceed-action drop", &n1, &n2, &n3); - if (val == 3) { - *speed = n1/1000; - *burst = n2; - } - } - return; - } - - val = strtol(str, &endptr, 10); - if (*endptr == 0) { - *speed = val; - return; - } - if (*endptr == ',') { - *tr_id = val; - val = strtol(endptr + 1, &endptr, 10); - } - if (*endptr == 0) { - *speed = val; - return; - } else { - if (*endptr == '/' || *endptr == '\\' || *endptr == ':') { - if (dir == ATTR_DOWN) - *speed = val; - else - *speed = strtol(endptr + 1, &endptr, 10); - } - } -} - -#ifdef RADIUS -static void parse_attr(struct rad_attr_t *attr, int dir, int *speed, int *burst, int *tr_id) -{ - if (attr->attr->type == ATTR_TYPE_STRING) - parse_string(attr->val.string, dir, speed, burst, tr_id); - else if (attr->attr->type == ATTR_TYPE_INTEGER) - *speed = attr->val.integer; -} - -static struct time_range_pd_t *get_tr_pd(struct shaper_pd_t *pd, int id) -{ - struct time_range_pd_t *tr_pd; - - list_for_each_entry(tr_pd, &pd->tr_list, entry) { - if (tr_pd->id == id) - return tr_pd; - } - - tr_pd = _malloc(sizeof(*tr_pd)); - memset(tr_pd, 0, sizeof(*tr_pd)); - tr_pd->id = id; - - if (id == time_range_id) - pd->cur_tr = tr_pd; - - list_add_tail(&tr_pd->entry, &pd->tr_list); - - return tr_pd; -} - -static void clear_tr_pd(struct shaper_pd_t *pd) -{ - struct time_range_pd_t *tr_pd; - - while (!list_empty(&pd->tr_list)) { - tr_pd = list_entry(pd->tr_list.next, typeof(*tr_pd), entry); - list_del(&tr_pd->entry); - _free(tr_pd); - } -} - -static void check_radius_attrs(struct shaper_pd_t *pd, struct rad_packet_t *pack) -{ - struct rad_attr_t *attr; - int down_speed, down_burst; - int up_speed, up_burst; - int tr_id; - struct time_range_pd_t *tr_pd; - - list_for_each_entry(attr, &pack->attrs, entry) { - if (attr->vendor && attr->vendor->id != conf_vendor) - continue; - if (!attr->vendor && conf_vendor) - continue; - if (attr->attr->id != conf_attr_down && attr->attr->id != conf_attr_up) - continue; - tr_id = 0; - down_speed = 0; - down_burst = 0; - up_speed = 0; - up_burst = 0; - if (attr->attr->id == conf_attr_down) - parse_attr(attr, ATTR_DOWN, &down_speed, &down_burst, &tr_id); - if (attr->attr->id == conf_attr_up) - parse_attr(attr, ATTR_UP, &up_speed, &up_burst, &tr_id); - tr_pd = get_tr_pd(pd, tr_id); - if (down_speed) - tr_pd->down_speed = down_speed; - if (down_burst) - tr_pd->down_burst = down_burst; - if (up_speed) - tr_pd->up_speed = up_speed; - if (up_burst) - tr_pd->up_burst = up_burst; - } -} - -static void ev_radius_access_accept(struct ev_radius_t *ev) -{ - int down_speed, down_burst; - int up_speed, up_burst; - struct shaper_pd_t *pd = find_pd(ev->ppp, 1); - - if (!pd) - return; - - check_radius_attrs(pd, ev->reply); - - if (temp_down_speed || temp_up_speed) { - pd->temp_down_speed = temp_down_speed; - pd->temp_up_speed = temp_up_speed; - pd->down_speed = temp_down_speed; - pd->up_speed = temp_up_speed; - down_speed = temp_down_speed; - up_speed = temp_up_speed; - down_burst = 0; - up_burst = 0; - } else { - if (!pd->cur_tr) - return; - pd->down_speed = pd->cur_tr->down_speed; - pd->up_speed = pd->cur_tr->up_speed; - down_speed = pd->cur_tr->down_speed; - up_speed = pd->cur_tr->up_speed; - down_burst = pd->cur_tr->down_burst; - up_burst = pd->cur_tr->up_speed; - } - - if (down_speed > 0 && up_speed > 0) { - if (!install_shaper(ev->ppp->ifname, down_speed, down_burst, up_speed, up_burst)) { - if (conf_verbose) - log_ppp_info2("tbf: installed shaper %i/%i (Kbit)\n", down_speed, up_speed); - } - } -} - -static void ev_radius_coa(struct ev_radius_t *ev) -{ - struct shaper_pd_t *pd = find_pd(ev->ppp, 0); - - if (!pd) { - ev->res = -1; - return; - } - - clear_tr_pd(pd); - check_radius_attrs(pd, ev->request); - - if (pd->temp_down_speed || pd->temp_up_speed) - return; - - if (!pd->cur_tr) { - if (pd->down_speed || pd->up_speed) { - pd->down_speed = 0; - pd->up_speed = 0; - if (conf_verbose) - log_ppp_info2("tbf: removed shaper\n"); - remove_shaper(ev->ppp->ifname); - } - return; - } - - if (pd->down_speed != pd->cur_tr->down_speed || pd->up_speed != pd->cur_tr->up_speed) { - pd->down_speed = pd->cur_tr->down_speed; - pd->up_speed = pd->cur_tr->up_speed; - - if (remove_shaper(ev->ppp->ifname)) { - ev->res = -1; - return; - } - - if (pd->down_speed > 0 || pd->up_speed > 0) { - if (install_shaper(ev->ppp->ifname, pd->cur_tr->down_speed, pd->cur_tr->down_burst, pd->cur_tr->up_speed, pd->cur_tr->up_burst)) { - ev->res= -1; - return; - } else { - if (conf_verbose) - log_ppp_info2("tbf: changed shaper %i/%i (Kbit)\n", pd->down_speed, pd->up_speed); - } - } else { - if (conf_verbose) - log_ppp_info2("tbf: removed shaper\n"); - } - } -} -#endif - -static void ev_shaper(struct ev_shaper_t *ev) -{ - struct shaper_pd_t *pd = find_pd(ev->ppp, 1); - int down_speed = 0, down_burst = 0; - int up_speed = 0, up_burst = 0; - int tr_id; - - if (!pd) - return; - - parse_string(ev->val, ATTR_DOWN, &down_speed, &down_burst, &tr_id); - parse_string(ev->val, ATTR_UP, &up_speed, &up_burst, &tr_id); - - if (down_speed > 0 && up_speed > 0) { - pd->down_speed = down_speed; - pd->up_speed = up_speed; - if (!install_shaper(ev->ppp->ifname, down_speed, down_burst, up_speed, up_burst)) { - if (conf_verbose) - log_ppp_info2("tbf: installed shaper %i/%i (Kbit)\n", down_speed, up_speed); - } - } -} - -static void ev_ctrl_finished(struct ppp_t *ppp) -{ - struct shaper_pd_t *pd = find_pd(ppp, 0); - - if (pd) { - clear_tr_pd(pd); - pthread_rwlock_wrlock(&shaper_lock); - list_del(&pd->entry); - pthread_rwlock_unlock(&shaper_lock); - list_del(&pd->pd.entry); - _free(pd); - } -} - -static void shaper_change_help(char * const *f, int f_cnt, void *cli) -{ - cli_send(cli, "shaper change [temp] - change shaper on specified interface, if temp is set then previous settings may be restored later by 'shaper restore'\r\n"); - cli_send(cli, "shaper change all [temp] - change shaper on all interfaces, if temp is set also new interfaces will have specified shaper value\r\n"); -} - -static void shaper_change(struct shaper_pd_t *pd) -{ - if ((pd->temp_down_speed && pd->temp_up_speed) || (pd->down_speed && pd->up_speed)) - remove_shaper(pd->ppp->ifname); - - if (pd->temp_down_speed && pd->temp_up_speed) - install_shaper(pd->ppp->ifname, pd->temp_down_speed, 0, pd->temp_up_speed, 0); - else if (pd->down_speed && pd->up_speed) - install_shaper(pd->ppp->ifname, pd->cur_tr->down_speed, pd->cur_tr->down_burst, pd->cur_tr->up_speed, pd->cur_tr->up_burst); -} - -static int shaper_change_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - struct shaper_pd_t *pd; - int down_speed = 0, up_speed = 0, down_burst = 0, up_burst = 0; - int all = 0, temp = 0, found = 0; - int tr_id; - - if (f_cnt < 4) - return CLI_CMD_SYNTAX; - - parse_string(f[3], ATTR_DOWN, &down_speed, &down_burst, &tr_id); - parse_string(f[3], ATTR_UP, &up_speed, &up_burst, &tr_id); - - if (down_speed == 0 || up_speed == 0) - return CLI_CMD_INVAL; - - if (!strcmp(f[2], "all")) - all = 1; - - if (f_cnt == 5) { - if (strcmp(f[4], "temp")) - return CLI_CMD_SYNTAX; - else - temp = 1; - } - - if (all && temp) { - temp_down_speed = down_speed; - temp_up_speed = up_speed; - } - - pthread_rwlock_rdlock(&shaper_lock); - list_for_each_entry(pd, &shaper_list, entry) { - if (all || !strcmp(f[2], pd->ppp->ifname)) { - if (temp) { - pd->temp_down_speed = down_speed; - pd->temp_up_speed = up_speed; - } else { - pd->temp_down_speed = 0; - pd->temp_up_speed = 0; - if (!pd->cur_tr) - pd->cur_tr = get_tr_pd(pd, 0); - pd->cur_tr->down_speed = down_speed; - pd->cur_tr->down_burst = down_burst; - pd->cur_tr->up_speed = up_speed; - pd->cur_tr->up_burst = up_burst; - } - triton_context_call(pd->ppp->ctrl->ctx, (triton_event_func)shaper_change, pd); - if (!all) { - found = 1; - break; - } - } - } - pthread_rwlock_unlock(&shaper_lock); - - if (!all && !found) - cli_send(cli, "not found\r\n"); - - return CLI_CMD_OK; -} - -static void shaper_restore_help(char * const *f, int f_cnt, void *cli) -{ - cli_send(cli, "shaper restore - restores shaper settings on specified interface made by 'shaper change' command with 'temp' flag\r\n"); - cli_send(cli, "shaper restore all - restores shaper settings on all interfaces made by 'shaper change' command with 'temp' flag\r\n"); -} - -static void shaper_restore(struct shaper_pd_t *pd) -{ - remove_shaper(pd->ppp->ifname); - - if (pd->cur_tr) - install_shaper(pd->ppp->ifname, pd->cur_tr->down_speed, pd->cur_tr->down_burst, pd->cur_tr->up_speed, pd->cur_tr->up_burst); -} - -static int shaper_restore_exec(const char *cmd, char * const *f, int f_cnt, void *cli) -{ - struct shaper_pd_t *pd; - int all, found = 0;; - - if (f_cnt != 3) - return CLI_CMD_SYNTAX; - - if (strcmp(f[2], "all")) - all = 0; - else - all = 1; - - pthread_rwlock_rdlock(&shaper_lock); - if (all) { - temp_down_speed = 0; - temp_up_speed = 0; - } - list_for_each_entry(pd, &shaper_list, entry) { - if (!pd->temp_down_speed) - continue; - if (all || !strcmp(f[2], pd->ppp->ifname)) { - pd->temp_down_speed = 0; - pd->temp_up_speed = 0; - triton_context_call(pd->ppp->ctrl->ctx, (triton_event_func)shaper_restore, pd); - if (!all) { - found = 1; - break; - } - } - } - pthread_rwlock_unlock(&shaper_lock); - - if (!all && !found) - cli_send(cli, "not found\r\n"); - - return CLI_CMD_OK; -} - -static void print_rate(const struct ppp_t *ppp, char *buf) -{ - struct shaper_pd_t *pd = find_pd((struct ppp_t *)ppp, 0); - - if (pd && (pd->down_speed || pd->up_speed)) - sprintf(buf, "%i/%i", pd->down_speed, pd->up_speed); - else - *buf = 0; -} - -static void shaper_ctx_close(struct triton_context_t *ctx) -{ - struct time_range_t *r; - - while (!list_empty(&time_range_list)) { - r = list_entry(time_range_list.next, typeof(*r), entry); - list_del(&r->entry); - if (r->begin.tpd) - triton_timer_del(&r->begin); - if (r->end.tpd) - triton_timer_del(&r->end); - _free(r); - } - - triton_context_unregister(ctx); -} - -static void update_shaper_tr(struct shaper_pd_t *pd) -{ - struct time_range_pd_t *tr; - - list_for_each_entry(tr, &pd->tr_list, entry) { - if (tr->id != time_range_id) - continue; - pd->cur_tr = tr; - break; - } - - if (pd->temp_down_speed || pd->temp_up_speed) - return; - - if (pd->down_speed || pd->up_speed) { - if (pd->cur_tr && pd->down_speed == pd->cur_tr->down_speed && pd->up_speed == pd->cur_tr->up_speed) - return; - remove_shaper(pd->ppp->ifname); - } - - if (pd->cur_tr && (pd->cur_tr->down_speed || pd->cur_tr->up_speed)) { - pd->down_speed = pd->cur_tr->down_speed; - pd->up_speed = pd->cur_tr->up_speed; - if (!install_shaper(pd->ppp->ifname, pd->cur_tr->down_speed, pd->cur_tr->down_burst, pd->cur_tr->up_speed, pd->cur_tr->up_burst)) { - if (conf_verbose) - log_ppp_info2("tbf: changed shaper %i/%i (Kbit)\n", pd->cur_tr->down_speed, pd->cur_tr->up_speed); - } - } else - if (conf_verbose) - log_ppp_info2("tbf: removed shaper\n"); - -} - -static void time_range_begin_timer(struct triton_timer_t *t) -{ - struct time_range_t *tr = container_of(t, typeof(*tr), begin); - struct shaper_pd_t *pd; - - time_range_id = tr->id; - - log_debug("tbf: time_range_begin_timer: id=%i\n", time_range_id); - - pthread_rwlock_rdlock(&shaper_lock); - list_for_each_entry(pd, &shaper_list, entry) - triton_context_call(pd->ppp->ctrl->ctx, (triton_event_func)update_shaper_tr, pd); - pthread_rwlock_unlock(&shaper_lock); -} - -static void time_range_end_timer(struct triton_timer_t *t) -{ - struct shaper_pd_t *pd; - - time_range_id = 0; - - log_debug("tbf: time_range_end_timer\n"); - - pthread_rwlock_rdlock(&shaper_lock); - list_for_each_entry(pd, &shaper_list, entry) - triton_context_call(pd->ppp->ctrl->ctx, (triton_event_func)update_shaper_tr, pd); - pthread_rwlock_unlock(&shaper_lock); -} - -static struct time_range_t *parse_range(const char *val) -{ - char *endptr; - int id; - time_t t; - struct tm begin_tm, end_tm; - struct time_range_t *r; - - id = strtol(val, &endptr, 10); - if (*endptr != ',') - return NULL; - if (id <= 0) - return NULL; - - time(&t); - localtime_r(&t, &begin_tm); - begin_tm.tm_sec = 1; - end_tm = begin_tm; - end_tm.tm_sec = 0; - - endptr = strptime(endptr + 1, "%H:%M", &begin_tm); - if (*endptr != '-') - return NULL; - - endptr = strptime(endptr + 1, "%H:%M", &end_tm); - if (*endptr) - return NULL; - - r = _malloc(sizeof(*r)); - memset(r, 0, sizeof(*r)); - - r->id = id; - r->begin.expire_tv.tv_sec = mktime(&begin_tm); - r->begin.period = 24 * 60 * 60 * 1000; - r->begin.expire = time_range_begin_timer; - r->end.expire_tv.tv_sec = mktime(&end_tm); - r->end.period = 24 * 60 * 60 * 1000; - r->end.expire = time_range_end_timer; - - return r; -} - -static void load_time_ranges(void) -{ - struct conf_sect_t *s = conf_get_section("tbf"); - struct conf_option_t *opt; - struct time_range_t *r; - time_t ts; - - if (!s) - return; - - time(&ts); - - while (!list_empty(&time_range_list)) { - r = list_entry(time_range_list.next, typeof(*r), entry); - list_del(&r->entry); - if (r->begin.tpd) - triton_timer_del(&r->begin); - if (r->end.tpd) - triton_timer_del(&r->end); - _free(r); - } - - list_for_each_entry(opt, &s->items, entry) { - if (strcmp(opt->name, "time-range")) - continue; - r = parse_range(opt->val); - if (r) { - list_add_tail(&r->entry, &time_range_list); - if (r->begin.expire_tv.tv_sec > r->end.expire_tv.tv_sec) { - if (ts >= r->begin.expire_tv.tv_sec - 24*60*60 && ts <= r->end.expire_tv.tv_sec) - time_range_begin_timer(&r->begin); - } else { - if (ts >= r->begin.expire_tv.tv_sec && ts <= r->end.expire_tv.tv_sec) - time_range_begin_timer(&r->begin); - } - if (r->begin.expire_tv.tv_sec < ts) - r->begin.expire_tv.tv_sec += 24 * 60 * 60; - if (r->end.expire_tv.tv_sec < ts) - r->end.expire_tv.tv_sec += 24 * 60 * 60; - triton_timer_add(&shaper_ctx, &r->begin, 1); - triton_timer_add(&shaper_ctx, &r->end, 1); - } else - log_emerg("tbf: failed to parse time-range '%s'\n", opt->val); - } -} - -#ifdef RADIUS -static int parse_attr_opt(const char *opt) -{ - struct rad_dict_attr_t *attr; - struct rad_dict_vendor_t *vendor; - - if (conf_vendor) - vendor = rad_dict_find_vendor_id(conf_vendor); - else - vendor = NULL; - - if (conf_vendor) { - if (vendor) - attr = rad_dict_find_vendor_attr(vendor, opt); - else - attr = NULL; - }else - attr = rad_dict_find_attr(opt); - - if (attr) - return attr->id; - - return atoi(opt); -} - -static int parse_vendor_opt(const char *opt) -{ - struct rad_dict_vendor_t *vendor; - - vendor = rad_dict_find_vendor_name(opt); - if (vendor) - return vendor->id; - - return atoi(opt); -} -#endif - -static void load_config(void) -{ - const char *opt; - -#ifdef RADIUS - opt = conf_get_opt("tbf", "vendor"); - if (opt) - conf_vendor = parse_vendor_opt(opt); - - opt = conf_get_opt("tbf", "attr"); - if (opt) { - conf_attr_down = parse_attr_opt(opt); - conf_attr_up = parse_attr_opt(opt); - } - - opt = conf_get_opt("tbf", "attr-down"); - if (opt) - conf_attr_down = parse_attr_opt(opt); - - opt = conf_get_opt("tbf", "attr-up"); - if (opt) - conf_attr_up = parse_attr_opt(opt); - - if (conf_attr_up <= 0 || conf_attr_down <= 0) { - log_emerg("tbf: incorrect attribute(s), tbf disabled...\n"); - return; - } -#endif - - opt = conf_get_opt("tbf", "burst-factor"); - if (opt) { - conf_down_burst_factor = strtod(opt, NULL); - conf_up_burst_factor = conf_down_burst_factor * 10; - } - - opt = conf_get_opt("tbf", "down-burst-factor"); - if (opt) - conf_down_burst_factor = strtod(opt, NULL); - - opt = conf_get_opt("tbf", "up-burst-factor"); - if (opt) - conf_up_burst_factor = strtod(opt, NULL); - - opt = conf_get_opt("tbf", "latency"); - if (opt && atoi(opt) > 0) - conf_latency = atoi(opt); - - opt = conf_get_opt("tbf", "mpu"); - if (opt && atoi(opt) >= 0) - conf_mpu = atoi(opt); - - opt = conf_get_opt("tbf", "verbose"); - if (opt && atoi(opt) > 0) - conf_verbose = 1; - - triton_context_call(&shaper_ctx, (triton_event_func)load_time_ranges, NULL); -} - -static int clock_init(void) -{ - FILE *fp; - uint32_t clock_res; - uint32_t t2us; - uint32_t us2t; - - fp = fopen("/proc/net/psched", "r"); - - if (!fp) { - log_emerg("tbf: failed to open /proc/net/psched: %s\n", strerror(errno)); - return -1; - } - - if (fscanf(fp, "%08x%08x%08x", &t2us, &us2t, &clock_res) != 3) { - log_emerg("tbf: failed to parse /proc/net/psched\n"); - fclose(fp); - return -1; - } - - fclose(fp); - - /* compatibility hack: for old iproute binaries (ignoring - * the kernel clock resolution) the kernel advertises a - * tick multiplier of 1000 in case of nano-second resolution, - * which really is 1. */ - if (clock_res == 1000000000) - t2us = us2t; - - clock_factor = (double)clock_res / TIME_UNITS_PER_SEC; - tick_in_usec = (double)t2us / us2t * clock_factor; - - return 0; -} - -static void __init init(void) -{ - if (clock_init()) - return; - - triton_context_register(&shaper_ctx, NULL); - triton_context_wakeup(&shaper_ctx); - - load_config(); - -#ifdef RADIUS - triton_event_register_handler(EV_RADIUS_ACCESS_ACCEPT, (triton_event_func)ev_radius_access_accept); - triton_event_register_handler(EV_RADIUS_COA, (triton_event_func)ev_radius_coa); -#endif - triton_event_register_handler(EV_CTRL_FINISHED, (triton_event_func)ev_ctrl_finished); - triton_event_register_handler(EV_SHAPER, (triton_event_func)ev_shaper); - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); - - cli_register_simple_cmd2(shaper_change_exec, shaper_change_help, 2, "shaper", "change"); - cli_register_simple_cmd2(shaper_restore_exec, shaper_restore_help, 2, "shaper", "restore"); - cli_show_ses_register("rate-limit", "rate limit down-stream/up-stream (Kbit)", print_rate); -} - diff --git a/accel-pptpd/extra/sigchld.c b/accel-pptpd/extra/sigchld.c deleted file mode 100644 index abfd42f..0000000 --- a/accel-pptpd/extra/sigchld.c +++ /dev/null @@ -1,116 +0,0 @@ -#include -#include -#include -#include -#include - -#include "triton.h" -#include "spinlock.h" -#include "log.h" - -#include "sigchld.h" - -#include "memdebug.h" - -static LIST_HEAD(handlers); -static int lock_refs; -static pthread_mutex_t handlers_lock = PTHREAD_MUTEX_INITIALIZER; -static pthread_cond_t refs_cond = PTHREAD_COND_INITIALIZER; -static pthread_t sigchld_thr; - -static void* sigchld_thread(void *arg) -{ - sigset_t set; - struct sigchld_handler_t *h, *h0; - pid_t pid; - int status, sig; - - sigfillset(&set); - sigdelset(&set, SIGKILL); - sigdelset(&set, SIGSTOP); - pthread_sigmask(SIG_BLOCK, &set, NULL); - - sigemptyset(&set); - sigaddset(&set, SIGCHLD); - sigaddset(&set, SIGQUIT); - - while (1) { - pid = waitpid(0, &status, 0); - if (pid < 0) { - if (errno == EINTR) - continue; - if (errno == ECHILD) { - sigwait(&set, &sig); - if (sig == SIGQUIT) - break; - continue; - } - log_error("sigchld: waitpid: %s\n", strerror(errno)); - continue; - } - - pthread_mutex_lock(&handlers_lock); - while (lock_refs) - pthread_cond_wait(&refs_cond, &handlers_lock); - - h0 = NULL; - list_for_each_entry(h, &handlers, entry) { - if (h->pid == pid) { - h0 = h; - list_del(&h0->entry); - pthread_mutex_lock(&h0->lock); - break; - } - } - pthread_mutex_unlock(&handlers_lock); - if (h0) { - h0->handler(h0, WEXITSTATUS(status)); - h0->pid = 0; - pthread_mutex_unlock(&h0->lock); - } - } - - return NULL; -} - -void __export sigchld_register_handler(struct sigchld_handler_t *h) -{ - pthread_mutex_init(&h->lock, NULL); - - pthread_mutex_lock(&handlers_lock); - list_add_tail(&h->entry, &handlers); - pthread_mutex_unlock(&handlers_lock); -} - -void __export sigchld_unregister_handler(struct sigchld_handler_t *h) -{ - pthread_mutex_lock(&handlers_lock); - pthread_mutex_lock(&h->lock); - if (h->pid) { - list_del(&h->entry); - h->pid = 0; - } - pthread_mutex_unlock(&h->lock); - pthread_mutex_unlock(&handlers_lock); -} - -void __export sigchld_lock() -{ - pthread_mutex_lock(&handlers_lock); - ++lock_refs; - pthread_mutex_unlock(&handlers_lock); -} - -void __export sigchld_unlock() -{ - pthread_mutex_lock(&handlers_lock); - if (--lock_refs == 0) - pthread_cond_signal(&refs_cond); - pthread_mutex_unlock(&handlers_lock); -} - -static void __init init(void) -{ - if (pthread_create(&sigchld_thr, NULL, sigchld_thread, NULL)) - log_emerg("sigchld: pthread_create: %s\n", strerror(errno)); -} diff --git a/accel-pptpd/extra/sigchld.h b/accel-pptpd/extra/sigchld.h deleted file mode 100644 index 27d1adf..0000000 --- a/accel-pptpd/extra/sigchld.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef __SIGCHLD_H -#define __SIGCHLD_H - -#include -#include "list.h" - -struct sigchld_handler_t -{ - struct list_head entry; - pthread_mutex_t lock; - pid_t pid; - void (*handler)(struct sigchld_handler_t *, int status); -}; - -void sigchld_register_handler(struct sigchld_handler_t *); -void sigchld_unregister_handler(struct sigchld_handler_t *); -void sigchld_lock(); -void sigchld_unlock(); - -#endif - diff --git a/accel-pptpd/include/cli.h b/accel-pptpd/include/cli.h deleted file mode 120000 index b0f4902..0000000 --- a/accel-pptpd/include/cli.h +++ /dev/null @@ -1 +0,0 @@ -../cli/cli.h \ No newline at end of file diff --git a/accel-pptpd/include/events.h b/accel-pptpd/include/events.h deleted file mode 100644 index 6a8caf0..0000000 --- a/accel-pptpd/include/events.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef __EVENTS_H -#define __EVENTS_H - -#include - -#define EV_PPP_STARTING 1 -#define EV_PPP_STARTED 2 -#define EV_PPP_FINISHING 3 -#define EV_PPP_FINISHED 4 -#define EV_PPP_AUTHORIZED 5 -#define EV_CTRL_STARTING 6 -#define EV_CTRL_STARTED 7 -#define EV_CTRL_FINISHED 8 -#define EV_PPP_PRE_UP 9 -#define EV_PPP_ACCT_START 10 -#define EV_CONFIG_RELOAD 11 -#define EV_IP_CHANGED 100 -#define EV_SHAPER 101 -#define EV_MPPE_KEYS 102 -#define EV_RADIUS_ACCESS_ACCEPT 200 -#define EV_RADIUS_COA 201 - -struct ppp_t; -struct rad_packet_t; -struct ev_radius_t -{ - struct ppp_t *ppp; - struct rad_packet_t *request; - struct rad_packet_t *reply; - int res; -}; - -struct ev_mppe_keys_t -{ - struct ppp_t *ppp; - uint8_t *recv_key; - uint8_t *send_key; - int policy; - int type; -}; - -struct ev_shaper_t -{ - struct ppp_t *ppp; - const char *val; -}; - -#endif - diff --git a/accel-pptpd/include/if_pppox.h b/accel-pptpd/include/if_pppox.h deleted file mode 100644 index 0532d18..0000000 --- a/accel-pptpd/include/if_pppox.h +++ /dev/null @@ -1,234 +0,0 @@ -/*************************************************************************** - * Linux PPP over X - Generic PPP transport layer sockets - * Linux PPP over Ethernet (PPPoE) Socket Implementation (RFC 2516) - * - * This file supplies definitions required by the PPP over Ethernet driver - * (pppox.c). All version information wrt this file is located in pppox.c - * - * License: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version - * 2 of the License, or (at your option) any later version. - * - */ - -#ifndef __LINUX_IF_PPPOX_H -#define __LINUX_IF_PPPOX_H - - -#include -#include -#include -#include -#include - -#ifdef __KERNEL__ -#include -#include -#include -#endif /* __KERNEL__ */ - -/* For user-space programs to pick up these definitions - * which they wouldn't get otherwise without defining __KERNEL__ - */ -#ifndef AF_PPPOX -#define AF_PPPOX 24 -#define PF_PPPOX AF_PPPOX -#endif /* !(AF_PPPOX) */ - -struct pppoe_addr { - __be16 sid; - unsigned char remote[ETH_ALEN]; - char dev[IFNAMSIZ]; -}; - -struct pptp_addr { - __u16 call_id; - struct in_addr sin_addr; -}; -/************************************************************************ - * Protocols supported by AF_PPPOX - */ -#define PX_PROTO_OE 0 /* Currently just PPPoE */ -#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,22) -#define PX_PROTO_PPTP 1 -#define PX_MAX_PROTO 2 -#else -#define PX_PROTO_PPTP 2 -#define PX_MAX_PROTO 3 -#endif - -struct sockaddr_pppox { - sa_family_t sa_family; /* address family, AF_PPPOX */ - unsigned int sa_protocol; /* protocol identifier */ - union{ - struct pppoe_addr pppoe; - struct pptp_addr pptp; - }sa_addr; -}__attribute__ ((packed)); - - -/********************************************************************* - * - * ioctl interface for defining forwarding of connections - * - ********************************************************************/ - -#define PPPOEIOCSFWD _IOW(0xB1 ,0, size_t) -#define PPPOEIOCDFWD _IO(0xB1 ,1) -/*#define PPPOEIOCGFWD _IOWR(0xB1,2, size_t)*/ - -/* Codes to identify message types */ -#define PADI_CODE 0x09 -#define PADO_CODE 0x07 -#define PADR_CODE 0x19 -#define PADS_CODE 0x65 -#define PADT_CODE 0xa7 -struct pppoe_tag { - __u16 tag_type; - __u16 tag_len; - char tag_data[0]; -} __attribute ((packed)); - -/* Tag identifiers */ -#define PTT_EOL __constant_htons(0x0000) -#define PTT_SRV_NAME __constant_htons(0x0101) -#define PTT_AC_NAME __constant_htons(0x0102) -#define PTT_HOST_UNIQ __constant_htons(0x0103) -#define PTT_AC_COOKIE __constant_htons(0x0104) -#define PTT_VENDOR __constant_htons(0x0105) -#define PTT_RELAY_SID __constant_htons(0x0110) -#define PTT_SRV_ERR __constant_htons(0x0201) -#define PTT_SYS_ERR __constant_htons(0x0202) -#define PTT_GEN_ERR __constant_htons(0x0203) - -struct pppoe_hdr { -#if defined(__LITTLE_ENDIAN_BITFIELD) - __u8 ver : 4; - __u8 type : 4; -#elif defined(__BIG_ENDIAN_BITFIELD) - __u8 type : 4; - __u8 ver : 4; -#else -#error "Please fix " -#endif - __u8 code; - __u16 sid; - __u16 length; - struct pppoe_tag tag[0]; -} __attribute__ ((packed)); - - -/* Socket options */ -#define PPTP_SO_TIMEOUT 1 - - -#ifdef __KERNEL__ -#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,0) -struct pppoe_opt { - struct net_device *dev; /* device associated with socket*/ - struct pppoe_addr pa; /* what this socket is bound to*/ - struct sockaddr_pppox relay; /* what socket data will be - relayed to (PPPoE relaying) */ -}; -#endif -struct pptp_opt { - struct pptp_addr src_addr; - struct pptp_addr dst_addr; - int timeout; - __u32 ack_sent, ack_recv; - __u32 seq_sent, seq_recv; - int ppp_flags; - int flags; - struct sk_buff_head skb_buf; - #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) - struct tq_struct buf_work; //check bufferd packets work - struct timer_list buf_timer; - #else - #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20) - struct delayed_work buf_work; //check bufferd packets work - #else - struct work_struct buf_work; //check bufferd packets work - #endif - #endif - struct gre_statistics *stat; - spinlock_t xmit_lock; - spinlock_t rcv_lock; -}; -#define PPTP_FLAG_PAUSE 0 -#define PPTP_FLAG_PROC 1 - -#include - -struct pppox_sock { - /* struct sock must be the first member of pppox_sock */ - #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) - struct ppp_channel chan; - struct sock *sk; - #else - struct sock sk; - struct ppp_channel chan; - #endif - struct pppox_sock *next; /* for hash table */ - union { - struct pppoe_opt pppoe; - struct pptp_opt pptp; - } proto; - unsigned short num; -}; -#define pppoe_dev proto.pppoe.dev -#define pppoe_pa proto.pppoe.pa -#define pppoe_relay proto.pppoe.relay - -static inline struct pppox_sock *pppox_sk(struct sock *sk) -{ - #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) - return (struct pppox_sock *)sk->protinfo.pppox; - #else - return (struct pppox_sock *)sk; - #endif -} - -static inline struct sock *sk_pppox(struct pppox_sock *po) -{ - #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) - return po->sk; - #else - return (struct sock *)po; - #endif -} - -struct module; - -struct pppox_proto { - #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24) - int (*create)(struct socket *sock); - #else - int (*create)(struct net *net, struct socket *sock); - #endif - int (*ioctl)(struct socket *sock, unsigned int cmd, - unsigned long arg); - #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,15) - struct module *owner; - #endif -}; - -extern int register_pppox_proto(int proto_num, struct pppox_proto *pp); -extern void unregister_pppox_proto(int proto_num); -extern void pppox_unbind_sock(struct sock *sk);/* delete ppp-channel binding */ -extern int pppox_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg); - -/* PPPoX socket states */ -enum { - PPPOX_NONE = 0, /* initial state */ - PPPOX_CONNECTED = 1, /* connection established ==TCP_ESTABLISHED */ - PPPOX_BOUND = 2, /* bound to ppp device */ - PPPOX_RELAY = 4, /* forwarding is enabled */ - PPPOX_ZOMBIE = 8, /* dead, but still bound to ppp device */ - PPPOX_DEAD = 16 /* dead, useless, please clean me up!*/ -}; - -#endif /* __KERNEL__ */ - -#endif /* !(__LINUX_IF_PPPOX_H) */ diff --git a/accel-pptpd/include/ipdb.h b/accel-pptpd/include/ipdb.h deleted file mode 120000 index 77ab85b..0000000 --- a/accel-pptpd/include/ipdb.h +++ /dev/null @@ -1 +0,0 @@ -../ipdb.h \ No newline at end of file diff --git a/accel-pptpd/include/iprange.h b/accel-pptpd/include/iprange.h deleted file mode 120000 index b8c2c43..0000000 --- a/accel-pptpd/include/iprange.h +++ /dev/null @@ -1 +0,0 @@ -../iprange.h \ No newline at end of file diff --git a/accel-pptpd/include/linux_ppp.h b/accel-pptpd/include/linux_ppp.h deleted file mode 100644 index ebb4c23..0000000 --- a/accel-pptpd/include/linux_ppp.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef __KERNEL_PPP_H -#define __KERNEL_PPP_H - -#include - -#ifndef aligned_u64 -#define aligned_u64 __u64 __attribute__((aligned(8))) -#endif - -#ifndef __aligned_u64 -#define __aligned_u64 __u64 __attribute__((aligned(8))) -#endif - -#include -#include -#include - -#endif - diff --git a/accel-pptpd/include/list.h b/accel-pptpd/include/list.h deleted file mode 120000 index 4b6d9a9..0000000 --- a/accel-pptpd/include/list.h +++ /dev/null @@ -1 +0,0 @@ -../triton/list.h \ No newline at end of file diff --git a/accel-pptpd/include/log.h b/accel-pptpd/include/log.h deleted file mode 120000 index 49a04dd..0000000 --- a/accel-pptpd/include/log.h +++ /dev/null @@ -1 +0,0 @@ -../log.h \ No newline at end of file diff --git a/accel-pptpd/include/memdebug.h b/accel-pptpd/include/memdebug.h deleted file mode 120000 index 3ee61bc..0000000 --- a/accel-pptpd/include/memdebug.h +++ /dev/null @@ -1 +0,0 @@ -../memdebug.h \ No newline at end of file diff --git a/accel-pptpd/include/mempool.h b/accel-pptpd/include/mempool.h deleted file mode 120000 index 2637ab6..0000000 --- a/accel-pptpd/include/mempool.h +++ /dev/null @@ -1 +0,0 @@ -../triton/mempool.h \ No newline at end of file diff --git a/accel-pptpd/include/ppp.h b/accel-pptpd/include/ppp.h deleted file mode 120000 index ae3fa2e..0000000 --- a/accel-pptpd/include/ppp.h +++ /dev/null @@ -1 +0,0 @@ -../ppp/ppp.h \ No newline at end of file diff --git a/accel-pptpd/include/ppp_auth.h b/accel-pptpd/include/ppp_auth.h deleted file mode 120000 index 527c853..0000000 --- a/accel-pptpd/include/ppp_auth.h +++ /dev/null @@ -1 +0,0 @@ -../ppp/ppp_auth.h \ No newline at end of file diff --git a/accel-pptpd/include/ppp_fsm.h b/accel-pptpd/include/ppp_fsm.h deleted file mode 120000 index 5c6b7f4..0000000 --- a/accel-pptpd/include/ppp_fsm.h +++ /dev/null @@ -1 +0,0 @@ -../ppp/ppp_fsm.h \ No newline at end of file diff --git a/accel-pptpd/include/ppp_lcp.h b/accel-pptpd/include/ppp_lcp.h deleted file mode 120000 index 4902752..0000000 --- a/accel-pptpd/include/ppp_lcp.h +++ /dev/null @@ -1 +0,0 @@ -../ppp/ppp_lcp.h \ No newline at end of file diff --git a/accel-pptpd/include/pwdb.h b/accel-pptpd/include/pwdb.h deleted file mode 120000 index 360efe4..0000000 --- a/accel-pptpd/include/pwdb.h +++ /dev/null @@ -1 +0,0 @@ -../pwdb.h \ No newline at end of file diff --git a/accel-pptpd/include/radius.h b/accel-pptpd/include/radius.h deleted file mode 120000 index e1465f1..0000000 --- a/accel-pptpd/include/radius.h +++ /dev/null @@ -1 +0,0 @@ -../radius/radius.h \ No newline at end of file diff --git a/accel-pptpd/include/sigchld.h b/accel-pptpd/include/sigchld.h deleted file mode 120000 index 9b74ebd..0000000 --- a/accel-pptpd/include/sigchld.h +++ /dev/null @@ -1 +0,0 @@ -../extra/sigchld.h \ No newline at end of file diff --git a/accel-pptpd/include/spinlock.h b/accel-pptpd/include/spinlock.h deleted file mode 120000 index 09edcf6..0000000 --- a/accel-pptpd/include/spinlock.h +++ /dev/null @@ -1 +0,0 @@ -../triton/spinlock.h \ No newline at end of file diff --git a/accel-pptpd/include/triton.h b/accel-pptpd/include/triton.h deleted file mode 120000 index 6f35a2f..0000000 --- a/accel-pptpd/include/triton.h +++ /dev/null @@ -1 +0,0 @@ -../triton/triton.h \ No newline at end of file diff --git a/accel-pptpd/include/utils.h b/accel-pptpd/include/utils.h deleted file mode 120000 index 6cd5d4f..0000000 --- a/accel-pptpd/include/utils.h +++ /dev/null @@ -1 +0,0 @@ -../utils.h \ No newline at end of file diff --git a/accel-pptpd/ipdb.c b/accel-pptpd/ipdb.c deleted file mode 100644 index a08d3be..0000000 --- a/accel-pptpd/ipdb.c +++ /dev/null @@ -1,31 +0,0 @@ -#include "triton.h" -#include "ipdb.h" - -#include "memdebug.h" - -static LIST_HEAD(ipdb_handlers); - -__export struct ipdb_item_t *ipdb_get(struct ppp_t *ppp) -{ - struct ipdb_t *ipdb; - struct ipdb_item_t *it; - - list_for_each_entry(ipdb, &ipdb_handlers, entry) { - it = ipdb->get(ppp); - if (it) - return it; - } - - return NULL; -} - -void __export ipdb_put(struct ppp_t *ppp, struct ipdb_item_t *it) -{ - if (it->owner->put) - it->owner->put(ppp, it); -} - -void __export ipdb_register(struct ipdb_t *ipdb) -{ - list_add_tail(&ipdb->entry, &ipdb_handlers); -} diff --git a/accel-pptpd/ipdb.h b/accel-pptpd/ipdb.h deleted file mode 100644 index ebf3885..0000000 --- a/accel-pptpd/ipdb.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef IPDB_H -#define IPDB_H - -#include - -#include "ppp.h" -#include "list.h" - -struct ipdb_item_t -{ - struct ipdb_t *owner; - in_addr_t addr; - in_addr_t peer_addr; -}; - -struct ipdb_t -{ - struct list_head entry; - struct ipdb_item_t *(*get)(struct ppp_t *ppp); - void (*put)(struct ppp_t *ppp, struct ipdb_item_t *); -}; - -struct ipdb_item_t *ipdb_get(struct ppp_t *ppp); -void ipdb_put(struct ppp_t *ppp, struct ipdb_item_t *); - -void ipdb_register(struct ipdb_t *); - -#endif - diff --git a/accel-pptpd/iprange.c b/accel-pptpd/iprange.c deleted file mode 100644 index 411dcb7..0000000 --- a/accel-pptpd/iprange.c +++ /dev/null @@ -1,146 +0,0 @@ -#include -#include -#include -#include -#include - -#include "triton.h" -#include "list.h" -#include "log.h" - -#include "iprange.h" - -#include "memdebug.h" - -struct iprange_t -{ - struct list_head entry; - uint32_t begin; - uint32_t end; -}; - -static int conf_disable = 0; - -static LIST_HEAD(client_ranges); -//static LIST_HEAD(tunnel_ranges); - -//parses ranges like x.x.x.x/mask -static struct iprange_t *parse1(const char *str) -{ - int n,f1,f2,f3,f4,m; - struct iprange_t *r; - int mask; - - n = sscanf(str, "%u.%u.%u.%u/%u",&f1, &f2, &f3, &f4, &m); - if (n != 5) - return NULL; - if (f1 > 255) - return NULL; - if (f2 > 255) - return NULL; - if (f3 > 255) - return NULL; - if (f4 > 255) - return NULL; - if (m == 0 || m > 32) - return NULL; - - r = _malloc(sizeof(*r)); - r->begin = (f4 << 24) | (f3 << 16) | (f2 << 8) | f1; - - mask = htonl(~((1 << (32 - m)) - 1)); - r->end = ntohl(r->begin | ~mask); - r->begin = ntohl(r->begin); - - return r; -} - -//parses ranges like x.x.x.x-y -static struct iprange_t *parse2(const char *str) -{ - int n,f1,f2,f3,f4,m; - struct iprange_t *r; - - n = sscanf(str, "%u.%u.%u.%u-%u",&f1, &f2, &f3, &f4, &m); - if (n != 5) - return NULL; - if (f1 > 255) - return NULL; - if (f2 > 255) - return NULL; - if (f3 > 255) - return NULL; - if (f4 > 255) - return NULL; - if (m < f4 || m > 255) - return NULL; - - r = _malloc(sizeof(*r)); - r->begin = ntohl((f4 << 24) | (f3 << 16) | (f2 << 8) | f1); - r->end = ntohl((m << 24) | (f3 << 16) | (f2 << 8) | f1); - - return r; -} - -static void load_ranges(struct list_head *list, const char *conf_sect) -{ - struct conf_sect_t *s = conf_get_section(conf_sect); - struct conf_option_t *opt; - struct iprange_t *r; - - if (!s) { - log_emerg("iprange: section '%s' not found in config file, pptp and l2tp probably will not work...\n", conf_sect); - return; - } - - list_for_each_entry(opt, &s->items, entry) { - if (!strcmp(opt->name, "disable")) { - conf_disable = 1; - log_emerg("iprange: iprange module disabled so improper ip address assigning may cause kernel soft lockup!\n"); - continue; - } - r = parse1(opt->name); - if (!r) - r = parse2(opt->name); - if (!r) { - log_emerg("iprange: cann't parse '%s' in '%s'\n", opt->name, conf_sect); - _exit(EXIT_FAILURE); - } - list_add_tail(&r->entry, list); - } -} - -static int check_range(struct list_head *list, in_addr_t ipaddr) -{ - struct iprange_t *r; - uint32_t a = ntohl(ipaddr); - - list_for_each_entry(r, list, entry) { - if (a >= r->begin && a <= r->end) - return 0; - } - - return -1; -} - -int __export iprange_client_check(in_addr_t ipaddr) -{ - if (conf_disable) - return 0; - - return check_range(&client_ranges, ipaddr); -} -int __export iprange_tunnel_check(in_addr_t ipaddr) -{ - if (conf_disable) - return 0; - - return !check_range(&client_ranges, ipaddr); -} - -static void __init iprange_init(void) -{ - load_ranges(&client_ranges, "client-ip-range"); - //load_ranges(&tunnel_ranges, "tunnel-ip-range"); -} - diff --git a/accel-pptpd/iprange.h b/accel-pptpd/iprange.h deleted file mode 100644 index 88a2486..0000000 --- a/accel-pptpd/iprange.h +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef __IPRANGE_H -#define __IPRANGE_H - -#include - -int iprange_client_check(in_addr_t ipaddr); -int iprange_tunnel_check(in_addr_t ipaddr); - -#endif - diff --git a/accel-pptpd/log.c b/accel-pptpd/log.c deleted file mode 100644 index 428fedd..0000000 --- a/accel-pptpd/log.c +++ /dev/null @@ -1,501 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "triton/mempool.h" -#include "events.h" -#include "ppp.h" - -#include "log.h" - -#include "memdebug.h" - -struct log_pd_t -{ - struct ppp_pd_t pd; - struct ppp_t *ppp; - struct list_head msgs; - struct log_msg_t *msg; - int authorized:1; -}; - -struct _log_msg_t -{ - struct list_head entry; - int level; - struct timeval timestamp; - struct list_head chunks; - unsigned int refs; -}; - -static int log_level; - -static LIST_HEAD(targets); -static mempool_t msg_pool; -static mempool_t _msg_pool; -static mempool_t chunk_pool; - -static __thread struct ppp_t *cur_ppp; -static __thread struct _log_msg_t *cur_msg; -static __thread char *stat_buf; - -static FILE *emerg_file; -static FILE *debug_file; - -static void _log_free_msg(struct _log_msg_t *msg); -static struct log_msg_t *clone_msg(struct _log_msg_t *msg); -static int add_msg(struct _log_msg_t *msg, const char *buf); -//static struct log_pd_t *find_pd(struct ppp_t *ppp); -static void write_msg(FILE *f, struct _log_msg_t *msg, struct ppp_t *ppp); - -static void do_log(int level, const char *fmt, va_list ap, struct ppp_t *ppp) -{ - struct log_target_t *t; - struct log_msg_t *m; - - if (!stat_buf) - stat_buf = _malloc(LOG_MAX_SIZE + 1); - - vsnprintf(stat_buf, LOG_MAX_SIZE, fmt, ap); - - if (!cur_msg) { - cur_msg = mempool_alloc(_msg_pool); - if (!cur_msg) - return; - INIT_LIST_HEAD(&cur_msg->chunks); - cur_msg->refs = 1; - cur_msg->level = level; - gettimeofday(&cur_msg->timestamp, NULL); - } - - if (add_msg(cur_msg, stat_buf)) - goto out; - - if (stat_buf[strlen(stat_buf) - 1] != '\n') - return; - - if (debug_file) - write_msg(debug_file, cur_msg, ppp); - - list_for_each_entry(t, &targets, entry) { - m = clone_msg(cur_msg); - if (!m) - break; - t->log(t, m, ppp); - } - -out: - _log_free_msg(cur_msg); - cur_msg = NULL; -} - -void __export log_error(const char *fmt,...) -{ - if (log_level >= LOG_ERROR) { - va_list ap; - va_start(ap,fmt); - do_log(LOG_ERROR, fmt, ap, NULL); - va_end(ap); - } -} - -void __export log_warn(const char *fmt,...) -{ - if (log_level >= LOG_WARN) { - va_list ap; - va_start(ap,fmt); - do_log(LOG_WARN, fmt, ap, NULL); - va_end(ap); - } -} - -void __export log_info1(const char *fmt,...) -{ - if (log_level >= LOG_INFO1) { - va_list ap; - va_start(ap, fmt); - do_log(LOG_INFO1, fmt, ap, NULL); - va_end(ap); - } -} - -void __export log_info2(const char *fmt,...) -{ - if (log_level >= LOG_INFO2) { - va_list ap; - va_start(ap, fmt); - do_log(LOG_INFO2, fmt, ap, NULL); - va_end(ap); - } -} - -void __export log_debug(const char *fmt,...) -{ - if (log_level >= LOG_DEBUG) { - va_list ap; - va_start(ap, fmt); - do_log(LOG_DEBUG, fmt, ap, NULL); - va_end(ap); - } -} - -void __export log_debug2(const char *fmt,...) -{ - va_list ap; - va_start(ap, fmt); - vfprintf(debug_file, fmt, ap); - va_end(ap); - fflush(debug_file); -} -void __export log_msg(const char *fmt,...) -{ - va_list ap; - va_start(ap, fmt); - do_log(LOG_MSG, fmt, ap, NULL); - va_end(ap); -} - -void __export log_ppp_error(const char *fmt,...) -{ - if (log_level >= LOG_ERROR) { - va_list ap; - va_start(ap, fmt); - do_log(LOG_ERROR, fmt, ap, cur_ppp); - va_end(ap); - } -} - -void __export log_ppp_warn(const char *fmt,...) -{ - if (log_level >= LOG_WARN) { - va_list ap; - va_start(ap, fmt); - do_log(LOG_WARN, fmt, ap, cur_ppp); - va_end(ap); - } -} - -void __export log_ppp_info1(const char *fmt,...) -{ - if (log_level >= LOG_INFO1) { - va_list ap; - va_start(ap, fmt); - do_log(LOG_INFO1, fmt, ap, cur_ppp); - va_end(ap); - } -} - -void __export log_ppp_info2(const char *fmt,...) -{ - if (log_level >= LOG_INFO2) { - va_list ap; - va_start(ap, fmt); - do_log(LOG_INFO2, fmt, ap, cur_ppp); - va_end(ap); - } -} - -void __export log_ppp_debug(const char *fmt,...) -{ - if (log_level >= LOG_DEBUG) { - va_list ap; - va_start(ap, fmt); - do_log(LOG_DEBUG, fmt, ap, cur_ppp); - va_end(ap); - } -} - -void __export log_ppp_msg(const char *fmt,...) -{ - va_list ap; - va_start(ap, fmt); - do_log(LOG_MSG, fmt, ap, cur_ppp); - va_end(ap); -} - -void __export log_emerg(const char *fmt, ...) -{ - if (emerg_file) { - va_list ap; - va_start(ap, fmt); - vfprintf(emerg_file, fmt, ap); - va_end(ap); - fflush(emerg_file); - } -} - -void __export log_free_msg(struct log_msg_t *m) -{ - struct _log_msg_t *msg = (struct _log_msg_t *)m->lpd; - - //printf("free msg %p\n", m); - - mempool_free(m->hdr); - _log_free_msg(msg); - - mempool_free(m); -} - - -static void _log_free_msg(struct _log_msg_t *msg) -{ - struct log_chunk_t *chunk; - - if (__sync_sub_and_fetch(&msg->refs, 1)) - return; - - while(!list_empty(&msg->chunks)) { - chunk = list_entry(msg->chunks.next, typeof(*chunk), entry); - list_del(&chunk->entry); - mempool_free(chunk); - } - - mempool_free(msg); -} - -static struct log_msg_t *clone_msg(struct _log_msg_t *msg) -{ - struct log_msg_t *m = mempool_alloc(msg_pool); - if (!m) { - log_emerg("log: out of memory\n"); - return NULL; - } - - m->hdr = mempool_alloc(chunk_pool); - if (!m->hdr) { - log_emerg("log: out of memory\n"); - mempool_free(m); - return NULL; - } - - m->hdr->len = 0; - m->lpd = msg; - m->chunks = &msg->chunks; - m->timestamp = msg->timestamp; - m->level = msg->level; - - __sync_add_and_fetch(&msg->refs, 1); - - //printf("clone msg %p\n", m); - return m; -} - -static int add_msg(struct _log_msg_t *msg, const char *buf) -{ - struct log_chunk_t *chunk; - int i, len, chunk_cnt; - - len = strlen(buf); - chunk_cnt = (len - 1)/LOG_CHUNK_SIZE + 1; - - for (i = 0; i < chunk_cnt; i++) { - chunk = mempool_alloc(chunk_pool); - if (!chunk) - return -1; - - chunk->len = i == chunk_cnt -1 ? len - i * LOG_CHUNK_SIZE : LOG_CHUNK_SIZE; - memcpy(chunk->msg, buf + i * LOG_CHUNK_SIZE, chunk->len); - chunk->msg[chunk->len] = 0; - - list_add_tail(&chunk->entry, &msg->chunks); - } - - return 0; -} - -static void write_msg(FILE *f, struct _log_msg_t *msg, struct ppp_t *ppp) -{ - struct log_chunk_t *chunk; - - if (ppp) - sprintf(stat_buf,"%s: %s: ", ppp->ifname, ppp->sessionid); - else - stat_buf[0] = 0; - - list_for_each_entry(chunk, &msg->chunks, entry) - strcat(stat_buf, chunk->msg); - - fwrite(stat_buf, strlen(stat_buf), 1, f); - fflush(f); -} - -/*static struct log_pd_t *find_pd(struct ppp_t *ppp) -{ - struct ppp_pd_t *pd; - struct log_pd_t *lpd; - - list_for_each_entry(pd, &ppp->pd_list, entry) { - if (pd->key == &pd_key) { - lpd = container_of(pd, typeof(*lpd), pd); - return lpd; - } - } - log_emerg("log:BUG: pd not found\n"); - abort(); -} - -static void ev_ctrl_starting(struct ppp_t *ppp) -{ - struct log_pd_t *lpd = _malloc(sizeof(*lpd)); - if (!lpd) { - log_emerg("log: out of memory\n"); - return; - } - - memset(lpd, 0, sizeof(*lpd)); - lpd->pd.key = &pd_key; - lpd->ppp = ppp; - INIT_LIST_HEAD(&lpd->msgs); - list_add_tail(&lpd->pd.entry, &ppp->pd_list); -} - -static void ev_ctrl_finished(struct ppp_t *ppp) -{ - struct log_pd_t *lpd = find_pd(ppp); - struct _log_msg_t *msg; - struct log_msg_t *m; - struct log_target_t *t; - - if (lpd->msg) { - log_emerg("log:BUG: lpd->msg is not NULL\n"); - abort(); - } - - if (lpd->authorized) { - if (!list_empty(&lpd->msgs)) { - log_emerg("log:BUG: lpd->msgs is not empty\n"); - abort(); - } - list_for_each_entry(t, &targets, entry) - if (t->session_stop) - t->session_stop(ppp); - } - - while (!list_empty(&lpd->msgs)) { - msg = list_entry(lpd->msgs.next, typeof(*msg), entry); - list_del(&msg->entry); - - list_for_each_entry(t, &targets, entry) { - if (!t->log) - continue; - m = clone_msg(msg); - if (!m) - break; - t->log(m); - } - - _log_free_msg(msg); - } - - list_del(&lpd->pd.entry); - _free(lpd); -} - -static void ev_ppp_authorized(struct ppp_t *ppp) -{ - struct log_pd_t *lpd = find_pd(ppp); - struct _log_msg_t *msg; - struct log_msg_t *m; - struct log_target_t *t; - - list_for_each_entry(t, &targets, entry) - if (t->session_start) - t->session_start(ppp); - - while(!list_empty(&lpd->msgs)) { - msg = list_entry(lpd->msgs.next, typeof(*msg), entry); - list_del(&msg->entry); - - list_for_each_entry(t, &targets, entry) { - if (!t->session_log) - continue; - m = clone_msg(msg); - if (!m) - break; - t->session_log(lpd->ppp, m); - } - - _log_free_msg(msg); - } - - lpd->authorized = 1; -}*/ - -void __export log_switch(struct triton_context_t *ctx, void *arg) -{ - cur_ppp = (struct ppp_t *)arg; -} - - -void __export log_register_target(struct log_target_t *t) -{ - list_add_tail(&t->entry, &targets); -} - -static void sighup(int n) -{ - struct log_target_t *t; - - list_for_each_entry(t, &targets, entry) - if (t->reopen) - t->reopen(); -} - -static void load_config(void) -{ - char *opt; - - opt = conf_get_opt("log", "level"); - if (opt && atoi(opt) >= 0) - log_level = atoi(opt); - - opt = conf_get_opt("log", "log-emerg"); - if (opt) { - if (emerg_file) - emerg_file = freopen(opt, "a", emerg_file); - else - emerg_file = fopen(opt, "a"); - if (!emerg_file) - fprintf(stderr, "log:open: %s\n", strerror(errno)); - } else if (emerg_file) { - fclose(emerg_file); - emerg_file = NULL; - } - - opt = conf_get_opt("log", "log-debug"); - if (opt) { - if (debug_file) - debug_file = freopen(opt, "a", debug_file); - else - debug_file = fopen(opt, "a"); - if (!debug_file) - fprintf(stderr, "log:open: %s\n", strerror(errno)); - } else if (debug_file) { - fclose(debug_file); - debug_file = NULL; - } -} - -static void __init log_init(void) -{ - struct sigaction sa = { - .sa_handler = sighup, - }; - - msg_pool = mempool_create(sizeof(struct log_msg_t)); - _msg_pool = mempool_create(sizeof(struct _log_msg_t)); - chunk_pool = mempool_create(sizeof(struct log_chunk_t) + LOG_CHUNK_SIZE + 1); - - load_config(); - - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); - - sigaction(SIGHUP, &sa, NULL); -} - diff --git a/accel-pptpd/log.h b/accel-pptpd/log.h deleted file mode 100644 index d87c42c..0000000 --- a/accel-pptpd/log.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef __LOG_H -#define __LOG_H - -#include -#include -#include "list.h" - -#define LOG_MSG 0 -#define LOG_ERROR 1 -#define LOG_WARN 2 -#define LOG_INFO1 3 -#define LOG_INFO2 4 -#define LOG_DEBUG 5 - -#define LOG_CHUNK_SIZE 128 -#define LOG_MAX_SIZE 4096 - -struct ppp_t; -struct triton_context_t; - -struct log_msg_t -{ - struct list_head entry; - void *lpd; - void *tpd; - struct timeval timestamp; - int level; - struct log_chunk_t *hdr; - struct list_head *chunks; -}; - -struct log_chunk_t -{ - struct list_head entry; - int len; - char msg[0]; -}; - -struct log_target_t -{ - struct list_head entry; - - void (*log)(struct log_target_t *, struct log_msg_t *, struct ppp_t *ppp); - void (*reopen)(void); -}; - -void log_free_msg(struct log_msg_t *msg); - -void log_emerg(const char *fmt, ...); - -void log_error(const char *fmt,...); -void log_warn(const char *fmt,...); -void log_info1(const char *fmt,...); -void log_info2(const char *fmt,...); -void log_debug(const char *fmt,...); -void log_msg(const char *fmt,...); - -void log_ppp_error(const char *fmt,...); -void log_ppp_warn(const char *fmt,...); -void log_ppp_info1(const char *fmt,...); -void log_ppp_info2(const char *fmt,...); -void log_ppp_debug(const char *fmt,...); -void log_ppp_msg(const char *fmt,...); - -void log_switch(struct triton_context_t *ctx, void *arg); - -void log_register_target(struct log_target_t *t); - -#endif diff --git a/accel-pptpd/logs/CMakeLists.txt b/accel-pptpd/logs/CMakeLists.txt deleted file mode 100644 index 0665e9a..0000000 --- a/accel-pptpd/logs/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -ADD_LIBRARY(log_file SHARED log_file.c) -TARGET_LINK_LIBRARIES(log_file rt) - -ADD_LIBRARY(log_tcp SHARED log_tcp.c) - -INSTALL(TARGETS log_file log_tcp - LIBRARY DESTINATION lib/accel-pptp -) - -IF(LOG_PGSQL) - ADD_LIBRARY(log_pgsql SHARED log_pgsql.c) - TARGET_LINK_LIBRARIES(log_pgsql pq) - INSTALL(TARGETS log_pgsql - LIBRARY DESTINATION lib/accel-pptp - ) -ENDIF(LOG_PGSQL) - diff --git a/accel-pptpd/logs/log_file.c b/accel-pptpd/logs/log_file.c deleted file mode 100644 index e435757..0000000 --- a/accel-pptpd/logs/log_file.c +++ /dev/null @@ -1,614 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "log.h" -#include "events.h" -#include "ppp.h" -#include "spinlock.h" -#include "mempool.h" - -#include "memdebug.h" - -#define LOG_BUF_SIZE 16*1024 - -#define RED_COLOR "\033[1;31m" -#define GREEN_COLOR "\033[1;32m" -#define YELLOW_COLOR "\033[1;33m" -#define BLUE_COLOR "\033[1;34m" -#define NORMAL_COLOR "\033[0;39m" - -struct log_file_t -{ - struct list_head entry; - struct list_head msgs; - spinlock_t lock; - int need_free:1; - int queued:1; - struct log_file_pd_t *lpd; - - int fd; - int new_fd; - off_t offset; - unsigned long magic; -}; - -struct log_file_pd_t -{ - struct ppp_pd_t pd; - struct log_file_t lf; - unsigned long tmp; -}; - -static int conf_color; -static int conf_per_session; -static char *conf_per_user_dir; -static char *conf_per_session_dir; -static int conf_copy; - -static const char* level_name[]={" msg", "error", " warn", " info", " info", "debug"}; -static const char* level_color[]={NORMAL_COLOR, RED_COLOR, YELLOW_COLOR, GREEN_COLOR, GREEN_COLOR, BLUE_COLOR}; - -static void *pd_key1; -static void *pd_key2; -static struct log_file_t *log_file; - -static mempool_t lpd_pool; -static char *log_buf; - -static struct aiocb aiocb = { - .aio_lio_opcode = LIO_WRITE, - .aio_sigevent.sigev_notify = SIGEV_SIGNAL, - .aio_sigevent.sigev_signo = SIGIO, -}; - -static LIST_HEAD(lf_queue); -static spinlock_t lf_queue_lock = SPINLOCK_INITIALIZER; -static int lf_queue_sleeping = 1; - -static unsigned long temp_seq; - -static void send_next_chunk(); - - -static void log_file_init(struct log_file_t *lf) -{ - spinlock_init(&lf->lock); - INIT_LIST_HEAD(&lf->msgs); - lf->fd = -1; - lf->new_fd = -1; -} - -static int log_file_open(struct log_file_t *lf, const char *fname) -{ - lf->fd = open(fname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); - if (lf->fd < 0) { - log_emerg("log_file: open '%s': %s\n", fname, strerror(errno)); - return -1; - } - - lf->offset = lseek(lf->fd, 0, SEEK_END); - - return 0; -} - -static void sigio(int num, siginfo_t *si, void *uc) -{ - struct log_file_t *lf; - int n; - - if (si->si_signo != SIGIO) - return; - - if (si->si_code != SI_ASYNCIO) { - if (aio_write(&aiocb)) - log_emerg("log_file: aio_write: %s\n", strerror(errno)); - return; - } - - lf = (struct log_file_t *)si->si_ptr; - - n = aio_return(&aiocb); - if (n < 0) - log_emerg("log_file: %s\n", strerror(aio_error(&aiocb))); - else if (n != aiocb.aio_nbytes) - log_emerg("log_file: short write %p %i %lu\n", lf, n, aiocb.aio_nbytes); - - spin_lock(&lf->lock); - lf->offset += n; - if (list_empty(&lf->msgs)) { - if (lf->need_free) { - spin_unlock(&lf->lock); - close(lf->fd); - mempool_free(lf->lpd); - } else { - lf->queued = 0; - spin_unlock(&lf->lock); - } - } else { - spin_unlock(&lf->lock); - - spin_lock(&lf_queue_lock); - list_add_tail(&lf->entry, &lf_queue); - spin_unlock(&lf_queue_lock); - } - - send_next_chunk(); -} - -static int dequeue_log(struct log_file_t *lf) -{ - int n, pos = 0; - struct log_msg_t *msg; - struct log_chunk_t *chunk; - - while (1) { - spin_lock(&lf->lock); - if (list_empty(&lf->msgs)) { - spin_unlock(&lf->lock); - return pos; - } - msg = list_entry(lf->msgs.next, typeof(*msg), entry); - list_del(&msg->entry); - spin_unlock(&lf->lock); - - if (pos + msg->hdr->len > LOG_BUF_SIZE) - goto overrun; - memcpy(log_buf + pos, msg->hdr->msg, msg->hdr->len); - n = msg->hdr->len; - - list_for_each_entry(chunk, msg->chunks, entry) { - if (pos + n + chunk->len > LOG_BUF_SIZE) - goto overrun; - memcpy(log_buf + pos + n, chunk->msg, chunk->len); - n += chunk->len; - } - - log_free_msg(msg); - pos += n; - } - -overrun: - spin_lock(&lf->lock); - list_add(&msg->entry, &lf->msgs); - spin_unlock(&lf->lock); - - return pos; -} - -static void send_next_chunk(void) -{ - struct log_file_t *lf; - int n; - - spin_lock(&lf_queue_lock); - if (list_empty(&lf_queue)) { - lf_queue_sleeping = 1; - spin_unlock(&lf_queue_lock); - return; - } - lf = list_entry(lf_queue.next, typeof(*lf), entry); - - n = log_file->entry.next == NULL; - list_del(&lf->entry); - - spin_unlock(&lf_queue_lock); - - if (lf->new_fd != -1) { - close(lf->fd); - lf->fd = lf->new_fd; - lf->new_fd = -1; - lf->offset = 0; - } - - aiocb.aio_fildes = lf->fd; - aiocb.aio_offset = lf->offset; - aiocb.aio_sigevent.sigev_value.sival_ptr = lf; - aiocb.aio_nbytes = dequeue_log(lf); - - if (aio_write(&aiocb)) - log_emerg("log_file: aio_write: %s\n", strerror(errno)); -} - -static void queue_lf(struct log_file_t *lf) -{ - int r; - - spin_lock(&lf_queue_lock); - list_add_tail(&lf->entry, &lf_queue); - r = lf_queue_sleeping; - lf_queue_sleeping = 0; - spin_unlock(&lf_queue_lock); - - if (r) - send_next_chunk(); -} - -static void queue_log(struct log_file_t *lf, struct log_msg_t *msg) -{ - int r; - - spin_lock(&lf->lock); - list_add_tail(&msg->entry, &lf->msgs); - if (lf->fd != -1) { - r = lf->queued; - lf->queued = 1; - } else - r = 1; - spin_unlock(&lf->lock); - - if (!r) - queue_lf(lf); -} - -static void set_hdr(struct log_msg_t *msg, struct ppp_t *ppp) -{ - struct tm tm; - char timestamp[32]; - - localtime_r(&msg->timestamp.tv_sec, &tm); - - strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &tm); - sprintf(msg->hdr->msg, "%s[%s]: %s: %s%s%s", conf_color ? level_color[msg->level] : "", - timestamp, level_name[msg->level], - ppp ? ppp->ifname : "", - ppp ? ": " : "", - conf_color ? NORMAL_COLOR : ""); - msg->hdr->len = strlen(msg->hdr->msg); -} - -static void general_log(struct log_target_t *t, struct log_msg_t *msg, struct ppp_t *ppp) -{ - if (ppp && !conf_copy) { - log_free_msg(msg); - return; - } - - set_hdr(msg, ppp); - queue_log(log_file, msg); -} - -static struct log_file_pd_t *find_pd(struct ppp_t *ppp, void *pd_key) -{ - struct ppp_pd_t *pd; - struct log_file_pd_t *lpd; - - list_for_each_entry(pd, &ppp->pd_list, entry) { - if (pd->key == pd_key) { - lpd = container_of(pd, typeof(*lpd), pd); - return lpd; - } - } - return NULL; -} - -static void per_user_log(struct log_target_t *t, struct log_msg_t *msg, struct ppp_t *ppp) -{ - struct log_file_pd_t *lpd; - - if (!ppp) { - log_free_msg(msg); - return; - } - - lpd = find_pd(ppp, &pd_key1); - - if (!lpd) { - log_free_msg(msg); - return; - } - - set_hdr(msg, ppp); - queue_log(&lpd->lf, msg); -} - -static void per_session_log(struct log_target_t *t, struct log_msg_t *msg, struct ppp_t *ppp) -{ - struct log_file_pd_t *lpd; - - if (!ppp) { - log_free_msg(msg); - return; - } - - lpd = find_pd(ppp, &pd_key2); - - if (!lpd) { - log_free_msg(msg); - return; - } - - set_hdr(msg, ppp); - queue_log(&lpd->lf, msg); -} - -static void general_reopen(void) -{ - char *fname = conf_get_opt("log", "log-file"); - int fd = open(fname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); - if (fd < 0) { - log_emerg("log_file: open '%s': %s\n", fname, strerror(errno)); - return; - } - log_file->new_fd = fd; -} - -static void free_lpd(struct log_file_pd_t *lpd) -{ - struct log_msg_t *msg; - - spin_lock(&lpd->lf.lock); - list_del(&lpd->pd.entry); - lpd->lf.need_free = 1; - if (lpd->lf.queued) - spin_unlock(&lpd->lf.lock); - else { - while (!list_empty(&lpd->lf.msgs)) { - msg = list_entry(lpd->lf.msgs.next, typeof(*msg), entry); - list_del(&msg->entry); - log_free_msg(msg); - } - if (lpd->lf.fd != -1) - close(lpd->lf.fd); - spin_unlock(&lpd->lf.lock); - mempool_free(lpd); - } -} - -static void ev_ctrl_started(struct ppp_t *ppp) -{ - struct log_file_pd_t *lpd; - char *fname; - - if (conf_per_user_dir) { - lpd = mempool_alloc(lpd_pool); - if (!lpd) { - log_emerg("log_file: out of memory\n"); - return; - } - memset(lpd, 0, sizeof(*lpd)); - lpd->pd.key = &pd_key1; - log_file_init(&lpd->lf); - lpd->lf.lpd = lpd; - list_add_tail(&lpd->pd.entry, &ppp->pd_list); - } - - if (conf_per_session_dir) { - lpd = mempool_alloc(lpd_pool); - if (!lpd) { - log_emerg("log_file: out of memory\n"); - return; - } - memset(lpd, 0, sizeof(*lpd)); - lpd->pd.key = &pd_key2; - log_file_init(&lpd->lf); - lpd->lf.lpd = lpd; - - fname = _malloc(PATH_MAX); - if (!fname) { - mempool_free(lpd); - log_emerg("log_file: out of memory\n"); - return; - } - - lpd->tmp = temp_seq++; - strcpy(fname, conf_per_session_dir); - strcat(fname, "/tmp"); - sprintf(fname + strlen(fname), "%lu", lpd->tmp); - - if (log_file_open(&lpd->lf, fname)) { - mempool_free(lpd); - _free(fname); - return; - } - - _free(fname); - - list_add_tail(&lpd->pd.entry, &ppp->pd_list); - } -} - -static void ev_ctrl_finished(struct ppp_t *ppp) -{ - struct log_file_pd_t *lpd; - char *fname; - - lpd = find_pd(ppp, &pd_key1); - if (lpd) - free_lpd(lpd); - - - lpd = find_pd(ppp, &pd_key2); - if (lpd) { - if (lpd->tmp) { - fname = _malloc(PATH_MAX); - if (fname) { - strcpy(fname, conf_per_session_dir); - strcat(fname, "/tmp"); - sprintf(fname + strlen(fname), "%lu", lpd->tmp); - if (unlink(fname)) - log_emerg("log_file: unlink '%s': %s\n", fname, strerror(errno)); - _free(fname); - } else - log_emerg("log_file: out of memory\n"); - } - free_lpd(lpd); - } -} - -static void ev_ppp_starting(struct ppp_t *ppp) -{ - struct log_file_pd_t *lpd; - char *fname1, *fname2; - - lpd = find_pd(ppp, &pd_key2); - if (!lpd) - return; - - fname1 = _malloc(PATH_MAX); - if (!fname1) { - log_emerg("log_file: out of memory\n"); - return; - } - - fname2 = _malloc(PATH_MAX); - if (!fname2) { - log_emerg("log_file: out of memory\n"); - _free(fname1); - return; - } - - strcpy(fname1, conf_per_session_dir); - strcat(fname1, "/tmp"); - sprintf(fname1 + strlen(fname1), "%lu", lpd->tmp); - - strcpy(fname2, conf_per_session_dir); - strcat(fname2, "/"); - strcat(fname2, ppp->sessionid); - strcat(fname2, ".log"); - - if (rename(fname1, fname2)) - log_emerg("log_file: rename '%s' to '%s': %s\n", fname1, fname2, strerror(errno)); - - lpd->tmp = 0; - - _free(fname1); - _free(fname2); -} - -static void ev_ppp_authorized(struct ppp_t *ppp) -{ - struct log_file_pd_t *lpd; - char *fname; - - lpd = find_pd(ppp, &pd_key1); - if (!lpd) - return; - - fname = _malloc(PATH_MAX); - if (!fname) { - log_emerg("log_file: out of memory\n"); - return; - } - - strcpy(fname, conf_per_user_dir); - strcat(fname, "/"); - strcat(fname, ppp->username); - if (conf_per_session) { - if (mkdir(fname, S_IRWXU) && errno != EEXIST) { - log_emerg("log_file: mkdir '%s': %s'\n", fname, strerror(errno)); - goto out_err; - } - strcat(fname, "/"); - strcat(fname, ppp->sessionid); - } - strcat(fname, ".log"); - - if (log_file_open(&lpd->lf, fname)) - goto out_err; - - _free(fname); - - if (!list_empty(&lpd->lf.msgs)) { - lpd->lf.queued = 1; - queue_lf(&lpd->lf); - } - - return; - -out_err: - _free(fname); - list_del(&lpd->pd.entry); - free_lpd(lpd); -} - -static struct log_target_t general_target = -{ - .log = general_log, - .reopen = general_reopen, -}; - -static struct log_target_t per_user_target = -{ - .log = per_user_log, -}; - -static struct log_target_t per_session_target = -{ - .log = per_session_log, -}; - -static void __init init(void) -{ - char *opt; - - sigset_t set; - sigemptyset(&set); - sigaddset(&set, SIGIO); - - struct sigaction sa = { - .sa_sigaction = sigio, - .sa_flags = SA_SIGINFO, - .sa_mask = set, - }; - - lpd_pool = mempool_create(sizeof(struct log_file_pd_t)); - log_buf = malloc(LOG_BUF_SIZE); - aiocb.aio_buf = log_buf; - - if (sigaction(SIGIO, &sa, NULL)) { - log_emerg("log_file: sigaction: %s\n", strerror(errno)); - return; - } - - opt = conf_get_opt("log", "log-file"); - if (opt) { - log_file = malloc(sizeof(*log_file)); - memset(log_file, 0, sizeof(*log_file)); - log_file_init(log_file); - if (log_file_open(log_file, opt)) { - free(log_file); - _exit(EXIT_FAILURE); - } - } - - opt = conf_get_opt("log","color"); - if (opt && atoi(opt) > 0) - conf_color = 1; - - opt = conf_get_opt("log", "per-user-dir"); - if (opt) - conf_per_user_dir = _strdup(opt); - - opt = conf_get_opt("log", "per-session-dir"); - if (opt) - conf_per_session_dir = _strdup(opt); - - opt = conf_get_opt("log", "per-session"); - if (opt && atoi(opt) > 0) - conf_per_session = 1; - - opt = conf_get_opt("log", "copy"); - if (opt && atoi(opt) > 0) - conf_copy = 1; - - log_register_target(&general_target); - - if (conf_per_user_dir) - log_register_target(&per_user_target); - - if (conf_per_session_dir) - log_register_target(&per_session_target); - - triton_event_register_handler(EV_CTRL_STARTED, (triton_event_func)ev_ctrl_started); - triton_event_register_handler(EV_CTRL_FINISHED, (triton_event_func)ev_ctrl_finished); - triton_event_register_handler(EV_PPP_STARTING, (triton_event_func)ev_ppp_starting); - triton_event_register_handler(EV_PPP_AUTHORIZED, (triton_event_func)ev_ppp_authorized); -} diff --git a/accel-pptpd/logs/log_pgsql.c b/accel-pptpd/logs/log_pgsql.c deleted file mode 100644 index af67e0b..0000000 --- a/accel-pptpd/logs/log_pgsql.c +++ /dev/null @@ -1,321 +0,0 @@ -#include -#include -#include - -#include - -#include "triton.h" -#include "spinlock.h" -#include "log.h" -#include "list.h" -#include "ppp.h" - -#include "memdebug.h" - -static char *conf_conninfo; -static int conf_queue_max = 1000; -static char *conf_query; -#define QUERY_TEMPLATE "insert into %s (timestamp, username, sessionid, msg) values ($1, $2, $3, $4)" - -static void start_connect(void); -static void start_connect_timer(struct triton_timer_t *); -static void pgsql_close(struct triton_context_t *ctx); - -static struct triton_context_t pgsql_ctx = { - .close = pgsql_close, - .before_switch = log_switch, -}; -static struct triton_md_handler_t pgsql_hnd; -static struct triton_timer_t connect_timer = { - .period = 5000, - .expire = start_connect_timer, -}; - -static PGconn *conn; - -static LIST_HEAD(msg_queue); -static int queue_size; -static int sleeping = 0; -static spinlock_t queue_lock = SPINLOCK_INITIALIZER; -static char *log_buf; -static int need_close; - -static void unpack_msg(struct log_msg_t *msg) -{ - struct log_chunk_t *chunk; - int pos = 0; - - list_for_each_entry(chunk, msg->chunks, entry) { - memcpy(log_buf + pos, chunk->msg, chunk->len); - pos += chunk->len; - } - if (pos > 1) - log_buf[pos - 1] = 0; - else - log_buf[0] = 0; -} - -static void set_hdr(struct log_msg_t *msg, struct ppp_t *ppp) -{ - struct tm tm; - - localtime_r(&msg->timestamp.tv_sec, &tm); - - strftime(msg->hdr->msg, LOG_CHUNK_SIZE, "%Y-%m-%d %H:%M:%S", &tm); - msg->hdr->len = strlen(msg->hdr->msg) + 1; - if (ppp && ppp->username) { - strcpy(msg->hdr->msg + msg->hdr->len, ppp->username); - msg->hdr->len += strlen(ppp->username) + 1; - strcpy(msg->hdr->msg + msg->hdr->len, ppp->sessionid); - msg->hdr->len += strlen(ppp->sessionid) + 1; - } else - memset(msg->hdr->msg + msg->hdr->len, 0, 2); - -} - -static void write_next_msg(void) -{ - struct log_msg_t *msg; - const char *paramValues[4]; - int paramFormats[4] = {0, 0, 0, 0}; - char *ptr1, *ptr2; - int r; - - spin_lock(&queue_lock); - if (list_empty(&msg_queue)) { - sleeping = 1; - spin_unlock(&queue_lock); - if (need_close) { - triton_md_unregister_handler(&pgsql_hnd); - PQfinish(conn); - conn = NULL; - triton_context_unregister(&pgsql_ctx); - } - return; - } - - msg = list_entry(msg_queue.next, typeof(*msg), entry); - list_del(&msg->entry); - --queue_size; - spin_unlock(&queue_lock); - - unpack_msg(msg); - - ptr1 = strchr(msg->hdr->msg, 0); - ptr2 = strchr(ptr1 + 1, 0); - - paramValues[1] = ptr1[1] ? ptr1 + 1 : NULL; - paramValues[2] = ptr2[1] ? ptr2 + 1 : NULL; - paramValues[0] = msg->hdr->msg; - paramValues[3] = log_buf; - - if (!PQsendQueryParams(conn, conf_query, 4, NULL, paramValues, NULL, paramFormats, 0)) - log_emerg("log_pgsql: %s\n", PQerrorMessage(conn)); - - log_free_msg(msg); - - r = PQflush(conn); - if (r == -1) - log_emerg("log_pgsql: %s\n", PQerrorMessage(conn)); - if (r == 0) - triton_md_enable_handler(&pgsql_hnd, MD_MODE_WRITE); -} - -static int pgsql_check_ready(struct triton_md_handler_t *h) -{ - PGresult *res; - - if (!PQconsumeInput(conn)) { - log_emerg("log_pgsql: %s\n", PQerrorMessage(conn)); - if (PQstatus(conn) == CONNECTION_BAD) { - PQfinish(conn); - start_connect(); - } - } - - if (PQisBusy(conn)) - return 0; - - while (1) { - res = PQgetResult(conn); - if (!res) - break; - if (PQresultStatus(res) != PGRES_COMMAND_OK) - log_emerg("log_pgsql: %s\n", PQerrorMessage(conn)); - PQclear(res); - } - - write_next_msg(); - - return 0; -} - -static int pgsql_flush(struct triton_md_handler_t *h) -{ - int r; - - r = PQflush(conn); - if (r == -1) - log_emerg("log_pgsql: %s\n", PQerrorMessage(conn)); - if (r == 1) - return 0; - - triton_md_disable_handler(&pgsql_hnd, MD_MODE_WRITE); - return 0; -} - -static void wakeup_log(void) -{ - write_next_msg(); -} - -static void queue_log(struct log_msg_t *msg) -{ - int r = 0, f = 0; - spin_lock(&queue_lock); - if (!conn) { - log_free_msg(msg); - spin_unlock(&queue_lock); - return; - } - if (queue_size < conf_queue_max) { - list_add_tail(&msg->entry, &msg_queue); - ++queue_size; - r = sleeping; - sleeping = 0; - } else - f = 1; - spin_unlock(&queue_lock); - - if (r) - triton_context_call(&pgsql_ctx, (void (*)(void*))wakeup_log, NULL); - else if (f) - log_free_msg(msg); -} - - -static void general_log(struct log_target_t *t, struct log_msg_t *msg, struct ppp_t *ppp) -{ - set_hdr(msg, ppp); - queue_log(msg); -} - -static int wait_connect(struct triton_md_handler_t *h) -{ - PostgresPollingStatusType status = PQconnectPoll(conn); - char *err_msg; - - switch(status) { - case PGRES_POLLING_READING: - triton_md_enable_handler(h, MD_MODE_READ); - triton_md_disable_handler(h, MD_MODE_WRITE); - break; - case PGRES_POLLING_WRITING: - triton_md_enable_handler(h, MD_MODE_WRITE); - triton_md_disable_handler(h, MD_MODE_READ); - break; - case PGRES_POLLING_FAILED: - err_msg = PQerrorMessage(conn); - log_emerg("log_pgsql: %s\n", err_msg); - triton_md_disable_handler(h, MD_MODE_READ | MD_MODE_WRITE); - PQfinish(conn); - h->read = NULL; - h->write = NULL; - if (!connect_timer.tpd) - triton_timer_add(&pgsql_ctx, &connect_timer, 0); - break; - case PGRES_POLLING_OK: - //triton_md_disable_handler(h, MD_MODE_READ | MD_MODE_WRITE); - PQsetnonblocking(conn, 1); - h->write = pgsql_flush; - h->read = pgsql_check_ready; - triton_md_enable_handler(&pgsql_hnd, MD_MODE_READ); - wakeup_log(); - break; - default: - break; - } - return 0; -} - -static void start_connect(void) -{ - conn = PQconnectStart(conf_conninfo); - if (!conn) { - log_emerg("log_pgsql: out of memory\n"); - return; - } - - if (PQstatus(conn) == CONNECTION_BAD) { - log_emerg("log_pgsql: PQconnectStart failed\n"); - } - - pgsql_hnd.fd = PQsocket(conn); - pgsql_hnd.read = wait_connect; - pgsql_hnd.write = wait_connect; - - wait_connect(&pgsql_hnd); -} - -static void start_connect_timer(struct triton_timer_t *t) -{ - triton_timer_del(t); - start_connect(); -} - -static void pgsql_close(struct triton_context_t *ctx) -{ - spin_lock(&queue_lock); - if (sleeping) { - triton_md_unregister_handler(&pgsql_hnd); - PQfinish(conn); - conn = NULL; - triton_context_unregister(&pgsql_ctx); - } else - need_close = 1; - spin_unlock(&queue_lock); -} - -static struct log_target_t target = { - .log = general_log, -}; - -static void __init init(void) -{ - char *opt; - - opt = conf_get_opt("log-pgsql", "conninfo"); - if (!opt) - return; - conf_conninfo = _strdup(opt); - - opt = conf_get_opt("log-pgsql", "connect-inteval"); - if (opt && atoi(opt) > 0) - connect_timer.period = atoi(opt) * 1000; - - opt = conf_get_opt("log-pgsql", "log-query"); - if (opt) - conf_query = _strdup(opt); - else { - opt = conf_get_opt("log-pgsql", "log-table"); - if (!opt || strlen(opt) > 32) - opt = "log"; - conf_query = _malloc(sizeof(QUERY_TEMPLATE) + strlen(opt)); - sprintf(conf_query, QUERY_TEMPLATE, opt); - } - - log_buf = _malloc(LOG_MAX_SIZE + 1); - if (!log_buf) { - log_emerg("log_pgsql: out of memory\n"); - return; - } - - triton_context_register(&pgsql_ctx, NULL); - triton_md_register_handler(&pgsql_ctx, &pgsql_hnd); - triton_md_set_trig(&pgsql_hnd, MD_TRIG_LEVEL); - triton_context_wakeup(&pgsql_ctx); - - start_connect(); - - log_register_target(&target); -} diff --git a/accel-pptpd/logs/log_tcp.c b/accel-pptpd/logs/log_tcp.c deleted file mode 100644 index 306c450..0000000 --- a/accel-pptpd/logs/log_tcp.c +++ /dev/null @@ -1,323 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "log.h" -#include "triton.h" -#include "events.h" -#include "ppp.h" -#include "spinlock.h" -#include "mempool.h" - -#include "memdebug.h" - -struct tcp_target_t -{ - struct log_target_t target; - struct list_head entry; - struct triton_md_handler_t hnd; - struct triton_timer_t conn_timer; - struct sockaddr_in addr; - char *buf; - int buf_size; - int buf_pos; - spinlock_t lock; - struct list_head queue; - int queue_len; - int connected:1; - int wait:1; -}; - -static int conf_connect_interval = 5; -static int conf_queue_len = 1000; - -static struct triton_context_t tcp_ctx; - -static const char* level_name[]={" msg", "error", " warn", " info", " info", "debug"}; - -static void start_connect(struct tcp_target_t *t); - -static LIST_HEAD(targets); - -static void disconnect(struct tcp_target_t *t) -{ - triton_md_unregister_handler(&t->hnd); - close(t->hnd.fd); - - start_connect(t); -} - -static void unpack_msg(struct tcp_target_t *t, struct log_msg_t *msg) -{ - struct log_chunk_t *chunk; - int pos = strlen(msg->hdr->msg); - - strcpy(t->buf, msg->hdr->msg); - - list_for_each_entry(chunk, msg->chunks, entry) { - memcpy(t->buf + pos, chunk->msg, chunk->len); - pos += chunk->len; - } - - t->buf_size = pos; - t->buf_pos = 0; -} - -static int send_log(struct tcp_target_t *t) -{ - struct log_msg_t *msg; - int n; - - while (1) { - spin_lock(&t->lock); - if (!t->queue_len) { - t->wait = 0; - spin_unlock(&t->lock); - return 0; - } - msg = list_entry(t->queue.next, typeof(*msg), entry); - list_del(&msg->entry); - t->queue_len--; - spin_unlock(&t->lock); - - unpack_msg(t, msg); - - log_free_msg(msg); - - while (t->buf_pos != t->buf_size) { - n = write(t->hnd.fd, t->buf + t->buf_pos, t->buf_size - t->buf_pos); - if (n < 0) { - if (errno == EAGAIN) - return 1; - if (errno != EPIPE) - log_emerg("log-tcp: write: %s\n", strerror(errno)); - disconnect(t); - return 0; - } - t->buf_pos += n; - } - } -} - -static void queue_log(struct tcp_target_t *t, struct log_msg_t *msg) -{ - int r; - - spin_lock(&t->lock); - if (t->queue_len == conf_queue_len) { - spin_unlock(&t->lock); - log_free_msg(msg); - return; - } - list_add_tail(&msg->entry, &t->queue); - t->queue_len++; - if (t->connected) { - r = t->wait; - t->wait = 1; - } else - r = 1; - spin_unlock(&t->lock); - - if (!r) { - if (send_log(t)) - triton_md_enable_handler(&t->hnd, MD_MODE_WRITE); - } -} - -static void set_hdr(struct log_msg_t *msg, struct ppp_t *ppp) -{ - struct tm tm; - char timestamp[32]; - - localtime_r(&msg->timestamp.tv_sec, &tm); - - strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &tm); - sprintf(msg->hdr->msg, "[%s]: %s: %s: ", timestamp, level_name[msg->level], ppp ? ppp->ifname : ""); - msg->hdr->len = strlen(msg->hdr->msg); -} - -static void general_log(struct log_target_t *lt, struct log_msg_t *msg, struct ppp_t *ppp) -{ - struct tcp_target_t *t = container_of(lt, typeof(*t), target); - - set_hdr(msg, ppp); - queue_log(t, msg); -} - -static int log_tcp_write(struct triton_md_handler_t *h) -{ - struct tcp_target_t *t = container_of(h, typeof(*t), hnd); - - if (!send_log(t)) - triton_md_disable_handler(h, MD_MODE_WRITE); - - return 0; -} - -static int log_tcp_connect(struct triton_md_handler_t *h) -{ - struct tcp_target_t *t = container_of(h, typeof(*t), hnd); - - if (connect(t->hnd.fd, &t->addr, sizeof(t->addr))) { - if (errno == EAGAIN) - return 0; - if (errno == EINPROGRESS) - return 0; - log_emerg("log-tcp: connect: %s\n", strerror(errno)); - triton_md_unregister_handler(&t->hnd); - close(t->hnd.fd); - triton_timer_add(&tcp_ctx, &t->conn_timer, 0); - return 0; - } - - t->hnd.write = log_tcp_write; - - triton_md_disable_handler(&t->hnd, MD_MODE_WRITE); - - spin_lock(&t->lock); - t->connected = 1; - t->wait = 1; - spin_unlock(&t->lock); - - if (send_log(t)) - triton_md_enable_handler(&t->hnd, MD_MODE_WRITE); - - return 0; -} - -static void connect_timer(struct triton_timer_t *timer) -{ - struct tcp_target_t *t = container_of(timer, typeof(*t), conn_timer); - - triton_timer_del(timer); - - start_connect(t); -} - -static void start_connect(struct tcp_target_t *t) -{ - t->hnd.write = log_tcp_connect; - t->hnd.fd = socket(PF_INET, SOCK_STREAM, 0); - - if (!t->hnd.fd) { - log_emerg("log-tcp: socket: %s\n", strerror(errno)); - return; - } - - if (fcntl(t->hnd.fd, F_SETFL, O_NONBLOCK)) { - log_emerg("log-tcp: failed to set nonblocking mode: %s\n", strerror(errno)); - close(t->hnd.fd); - return; - } - - if (connect(t->hnd.fd, &t->addr, sizeof(t->addr))) { - if (errno != EINPROGRESS) { - log_emerg("log-tcp: connect: %s\n", strerror(errno)); - close(t->hnd.fd); - return; - } - } - - triton_md_register_handler(&tcp_ctx, &t->hnd); - triton_md_enable_handler(&t->hnd, MD_MODE_WRITE); -} - -static void log_tcp_close(struct triton_context_t *ctx) -{ - struct tcp_target_t *t; - - while (!list_empty(&targets)) { - t = list_entry(targets.next, typeof(*t), entry); - list_del(&t->entry); - if (t->conn_timer.tpd) - triton_timer_del(&t->conn_timer); - else { - t->connected = 0; - triton_md_unregister_handler(&t->hnd); - close(t->hnd.fd); - } - } - - triton_context_unregister(&tcp_ctx); -} - -static int start_log(const char *_opt) -{ - struct tcp_target_t *t; - char *opt = strdup(_opt); - int port; - char *d; - - d = strchr(opt, ':'); - if (!d) - goto err; - - *d = 0; - - port = atoi(d + 1); - if (port <= 0) - goto err; - - t = _malloc(sizeof(*t)); - memset(t, 0, sizeof(*t)); - - t->buf = _malloc(LOG_MAX_SIZE + 64); - - t->conn_timer.expire_tv.tv_sec = conf_connect_interval; - t->conn_timer.expire = connect_timer; - - t->target.log = general_log; - - memset(&t->addr, 0, sizeof(t->addr)); - t->addr.sin_family = AF_INET; - t->addr.sin_port = htons(port); - t->addr.sin_addr.s_addr = inet_addr(opt); - - INIT_LIST_HEAD(&t->queue); - - spinlock_init(&t->lock); - - start_connect(t); - - log_register_target(&t->target); - - list_add_tail(&t->entry, &targets); - - return 0; - -err: - free(opt); - return -1; -} - -static struct triton_context_t tcp_ctx ={ - .close = log_tcp_close, - .before_switch = log_switch, -}; - -static void __init init(void) -{ - struct conf_sect_t *s = conf_get_section("log"); - struct conf_option_t *opt; - - if (!s) - return; - - triton_context_register(&tcp_ctx, NULL); - - list_for_each_entry(opt, &s->items, entry) { - if (strcmp(opt->name, "log-tcp")) - continue; - if (!opt->val || start_log(opt->val)) - log_emerg("log: log-tcp: invalid format: '%s'\n", opt->val); - } - - triton_context_wakeup(&tcp_ctx); -} - diff --git a/accel-pptpd/main.c b/accel-pptpd/main.c deleted file mode 100644 index 5a02685..0000000 --- a/accel-pptpd/main.c +++ /dev/null @@ -1,201 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "triton/triton.h" - -#include "memdebug.h" -#include "log.h" -#include "events.h" - -static int goto_daemon; -static char *pid_file; -static char *conf_file; - -#define ARG_MAX 128 -static int parse_cmdline(char ***argv) -{ - FILE *f; - int i; - size_t len; - - f = fopen("/proc/self/cmdline", "r"); - if (!f) { - perror("open cmdline"); - _exit(EXIT_FAILURE); - } - - *argv = _malloc(ARG_MAX * sizeof(void *)); - memset(*argv, 0, ARG_MAX * sizeof(void *)); - - for(i = 0; i < ARG_MAX; i++) { - len = 0; - if (getdelim(&(*argv)[i], &len, 0, f) < 0) - break; - } - - fclose(f); - - return i; -} -static void __init __main(void) -{ - int i,argc; - char **argv; - - argc=parse_cmdline(&argv); - - if (argc < 2) - goto usage; - - for(i = 1; i < argc; i++) { - if (!strcmp(argv[i], "-d")) - goto_daemon = 1; - else if (!strcmp(argv[i], "-p")) { - if (i == argc - 1) - goto usage; - pid_file = argv[++i]; - } else if (!strcmp(argv[i], "-c")) { - if (i == argc - 1) - goto usage; - conf_file = argv[++i]; - } - } - - if (!conf_file) - goto usage; - - if (triton_init(conf_file)) - _exit(EXIT_FAILURE); - - return; - -usage: - printf("usage: pptpd [-d] [-p ] -c \n\ - where:\n\ - -d - daemon mode\n\ - -p - write pid to \n\ - -c - config file\n"); - _exit(EXIT_FAILURE); -} - -static void change_limits(void) -{ - FILE *f; - struct rlimit lim; - unsigned int file_max; - - f = fopen("/proc/sys/fs/file-max", "r"); - if (f) { - fscanf(f, "%d", &file_max); - fclose(f); - - lim.rlim_cur = file_max; - lim.rlim_max = file_max; - if (setrlimit(RLIMIT_NOFILE, &lim)) - log_emerg("main: setrlimit: %s\n", strerror(errno)); - } else - log_emerg("main: failed to open '/proc/sys/fs/file-max': %s\n", strerror(errno)); -} - -static void config_reload_notify(int r) -{ - if (!r) - triton_event_fire(EV_CONFIG_RELOAD, NULL); -} -static void config_reload(int num) -{ - triton_conf_reload(config_reload_notify); -} - -int main(int argc, char **argv) -{ - sigset_t set; - int sig; - - if (goto_daemon) { - /*pid_t pid = fork(); - if (pid > 0) - _exit(EXIT_SUCCESS); - if (pid < 0) { - perror("fork"); - return EXIT_FAILURE; - } - if (setsid() < 0) - _exit(EXIT_FAILURE); - pid = fork(); - if (pid) - _exit(0); - umask(0); - chdir("/"); - close(STDIN_FILENO); - close(STDOUT_FILENO); - close(STDERR_FILENO);*/ - daemon(0, 0); - } - - if (pid_file) { - FILE *f = fopen(pid_file, "w"); - if (f) { - fprintf(f, "%i", getpid()); - fclose(f); - } - } - - //signal(SIGTERM, sigterm); - //signal(SIGPIPE, sigterm); - - change_limits(); - - if (triton_load_modules("modules")) - return EXIT_FAILURE; - - log_msg("accel-pptp version %s\n", ACCEL_PPTP_VERSION); - - triton_run(); - - sigfillset(&set); - - struct sigaction sa = { - .sa_handler = config_reload, - .sa_mask = set, - }; - - sigaction(SIGUSR1, &sa, NULL); - - sigdelset(&set, SIGKILL); - sigdelset(&set, SIGSTOP); - sigdelset(&set, SIGSEGV); - sigdelset(&set, SIGFPE); - sigdelset(&set, SIGILL); - sigdelset(&set, SIGBUS); - sigdelset(&set, SIGHUP); - sigdelset(&set, SIGIO); - sigdelset(&set, SIGINT); - sigdelset(&set, SIGUSR1); - sigdelset(&set, 35); - sigdelset(&set, 36); - pthread_sigmask(SIG_SETMASK, &set, NULL); - - sigemptyset(&set); - //sigaddset(&set, SIGINT); - sigaddset(&set, SIGTERM); - sigaddset(&set, SIGSEGV); - sigaddset(&set, SIGILL); - sigaddset(&set, SIGFPE); - sigaddset(&set, SIGBUS); - - sigwait(&set, &sig); - log_info1("terminate, sig = %i\n", sig); - - triton_terminate(); - - return EXIT_SUCCESS; -} - diff --git a/accel-pptpd/memdebug.c b/accel-pptpd/memdebug.c deleted file mode 100644 index c33e34b..0000000 --- a/accel-pptpd/memdebug.c +++ /dev/null @@ -1,184 +0,0 @@ -#undef MEMDEBUG - -#include -#include -#include -#include -#include -#include - -#include "spinlock.h" -#include "list.h" - -#define __init __attribute__((constructor)) -#define __export __attribute__((visibility("default"))) - -#undef offsetof -#ifdef __compiler_offsetof -#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER) -#else -#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) -#endif - -#define container_of(ptr, type, member) ({ \ - const typeof( ((type *)0)->member ) *__mptr = (ptr); \ - (type *)( (char *)__mptr - offsetof(type,member) );}) - - -#define MAGIC1 0x1122334455667788llu - -struct mem_t -{ - struct list_head entry; - char fname[PATH_MAX]; - int line; - size_t size; - uint64_t magic2; - uint64_t magic1; - char data[0]; -}; - -static LIST_HEAD(mem_list); -static spinlock_t mem_list_lock = SPINLOCK_INITIALIZER; - -struct mem_t *_md_malloc(size_t size, const char *fname, int line) -{ - struct mem_t *mem = malloc(sizeof(*mem) + size + 8); - - if (size > 4096) - line = 0; - - strcpy(mem->fname, fname); - mem->line = line; - mem->size = size; - mem->magic1 = MAGIC1; - mem->magic2 = (uint64_t)random() * (uint64_t)random(); - *(uint64_t*)(mem->data + size) = mem->magic2; - - spin_lock(&mem_list_lock); - list_add_tail(&mem->entry, &mem_list); - spin_unlock(&mem_list_lock); - - return mem; -} - -void __export *md_malloc(size_t size, const char *fname, int line) -{ - struct mem_t *mem = _md_malloc(size, fname, line); - - return mem->data; -} - -void __export md_free(void *ptr, const char *fname, int line) -{ - struct mem_t *mem = container_of(ptr, typeof(*mem), data); - - if (!ptr) { - printf("free null pointer at %s:%i\n", fname, line); - abort(); - } - - if (mem->magic1 != MAGIC1) { - printf("memory corruption:\nfree at %s:%i\n", fname, line); - abort(); - } - - if (mem->magic2 != *(uint64_t*)(mem->data + mem->size)) { - printf("memory corruption:\nmalloc(%lu) at %s:%i\nfree at %s:%i\n", (long unsigned)mem->size, mem->fname, mem->line, fname, line); - abort(); - } - - mem->magic1 = 0; - mem->magic2 = 0; - - spin_lock(&mem_list_lock); - list_del(&mem->entry); - spin_unlock(&mem_list_lock); - - free(mem); - return; -} - -void __export *md_realloc(void *ptr, size_t size, const char *fname, int line) -{ - struct mem_t *mem = container_of(ptr, typeof(*mem), data); - struct mem_t *mem2; - - if (mem->magic1 != MAGIC1) { - printf("memory corruption:\nfree at %s:%i\n", fname, line); - abort(); - } - - if (mem->magic2 != *(uint64_t*)(mem->data + mem->size)) { - printf("memory corruption:\nmalloc(%lu) at %s:%i\nfree at %s:%i\n", (long unsigned)mem->size, mem->fname, mem->line, fname, line); - abort(); - } - - mem2 = _md_malloc(size, fname, line); - memcpy(mem2->data, mem->data, mem->size); - - md_free(mem->data, fname, line); - - return mem2->data; -} - -char __export *md_strdup(const char *ptr, const char *fname, int line) -{ - struct mem_t *mem = _md_malloc(strlen(ptr) + 1, fname, line); - memcpy(mem->data, ptr, strlen(ptr) + 1); - return mem->data; -} - -char __export *md_strndup(const char *ptr, size_t n, const char *fname, int line) -{ - struct mem_t *mem = _md_malloc(n + 1, fname, line); - memcpy(mem->data, ptr, n); - mem->data[n] = 0; - return mem->data; -} - -static void siginfo(int num) -{ - struct mem_t *mem; - size_t total = 0; - - spin_lock(&mem_list_lock); - list_for_each_entry(mem, &mem_list, entry) { - printf("%s:%i %lu\n", mem->fname, mem->line, (long unsigned)mem->size); - total += mem->size; - } - spin_unlock(&mem_list_lock); - printf("total = %lu\n", (long unsigned)total); -} - -static void siginfo2(int num) -{ - struct mem_t *mem; - - spin_lock(&mem_list_lock); - list_for_each_entry(mem, &mem_list, entry) { - if (mem->magic1 != MAGIC1 || mem->magic2 != *(uint64_t*)(mem->data + mem->size)) - printf("%s:%i %lu\n", mem->fname, mem->line, (long unsigned)mem->size); - } - spin_unlock(&mem_list_lock); -} - -void __export md_check(void *ptr) -{ - struct mem_t *mem = container_of(ptr, typeof(*mem), data); - - if (!ptr) - abort(); - - if (mem->magic1 != MAGIC1) - abort(); - - if (mem->magic2 != *(uint64_t*)(mem->data + mem->size)) - abort(); -} - -static void __init init(void) -{ - signal(36, siginfo); - signal(37, siginfo2); -} diff --git a/accel-pptpd/memdebug.h b/accel-pptpd/memdebug.h deleted file mode 100644 index dc6b9ad..0000000 --- a/accel-pptpd/memdebug.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef __MEMDEBUG_H -#define __MEMDEBUG_H - -#ifdef MEMDEBUG - -#include - -#define _malloc(size) md_malloc(size, __FILE__, __LINE__) -#define _realloc(ptr, size) md_realloc(ptr, size, __FILE__, __LINE__) -#define _free(ptr) md_free(ptr, __FILE__, __LINE__) -#define _strdup(str) md_strdup(str, __FILE__, __LINE__) -#define _strndup(str, size) md_strndup(str, size, __FILE__, __LINE__) - -void *md_malloc(size_t size, const char *fname, int line); -void *md_realloc(void *ptr, size_t size, const char *fname, int line); -void md_free(void *ptr, const char *fname, int line); -char* md_strdup(const char *ptr, const char *fname, int line); -char* md_strndup(const char *ptr, size_t size, const char *fname, int line); -void md_check(void *ptr); - -#else -#define _malloc(size) malloc(size) -#define _realloc(ptr, size) realloc(ptr, size) -#define _free(ptr) free(ptr) -#endif - -#endif - diff --git a/accel-pptpd/ppp/CMakeLists.txt b/accel-pptpd/ppp/CMakeLists.txt deleted file mode 100644 index f4c0f04..0000000 --- a/accel-pptpd/ppp/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -SET(target ppp) -SET(sources_c - ppp.c - ppp_fsm.c - ppp_lcp.c - lcp_opt_mru.c - lcp_opt_magic.c - lcp_opt_pcomp.c - lcp_opt_accomp.c - ppp_auth.c - ppp_ipcp.c - ipcp_opt_ipaddr.c - ipcp_opt_dns.c - ppp_ccp.c -) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) - -ADD_LIBRARY(${target} SHARED ${sources_c}) - diff --git a/accel-pptpd/ppp/ccp_mppe.c b/accel-pptpd/ppp/ccp_mppe.c deleted file mode 100644 index 0952aa0..0000000 --- a/accel-pptpd/ppp/ccp_mppe.c +++ /dev/null @@ -1,259 +0,0 @@ -#include -#include -#include -#include -#include -#include "linux_ppp.h" - -#include "ppp.h" -#include "ppp_ccp.h" -#include "log.h" -#include "events.h" - -#include "memdebug.h" - -#define MPPE_H (1 << 24) -#define MPPE_M (1 << 7) -#define MPPE_S (1 << 6) -#define MPPE_L (1 << 5) -#define MPPE_D (1 << 4) -#define MPPE_C (1 << 0) - -#define MPPE_PAD 4 - -static struct ccp_option_t *mppe_init(struct ppp_ccp_t *ccp); -static void mppe_free(struct ppp_ccp_t *ccp, struct ccp_option_t *opt); -static int mppe_send_conf_req(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr); -static int mppe_recv_conf_req(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr); -static int mppe_recv_conf_nak(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr); -static int mppe_recv_conf_rej(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr); -static void mppe_print(void (*print)(const char *fmt,...),struct ccp_option_t*, uint8_t *ptr); - -struct mppe_option_t -{ - struct ccp_option_t opt; - int mppe; - uint8_t recv_key[16]; - uint8_t send_key[16]; - int policy; // 1 - allowed, 2 - required -}; - -static struct ccp_option_handler_t mppe_opt_hnd = { - .init = mppe_init, - .send_conf_req = mppe_send_conf_req, - .send_conf_nak = mppe_send_conf_req, - .recv_conf_req = mppe_recv_conf_req, - .recv_conf_nak = mppe_recv_conf_nak, - .recv_conf_rej = mppe_recv_conf_rej, - .free = mppe_free, - .print = mppe_print, -}; - -static struct ccp_option_t *mppe_init(struct ppp_ccp_t *ccp) -{ - struct mppe_option_t *mppe_opt = _malloc(sizeof(*mppe_opt)); - memset(mppe_opt, 0, sizeof(*mppe_opt)); - mppe_opt->mppe = -1; - mppe_opt->opt.id = CI_MPPE; - mppe_opt->opt.len = 6; - - return &mppe_opt->opt; -} - -static void mppe_free(struct ppp_ccp_t *ccp, struct ccp_option_t *opt) -{ - struct mppe_option_t *mppe_opt = container_of(opt, typeof(*mppe_opt), opt); - - _free(mppe_opt); -} - -static int setup_mppe_key(int fd, int transmit, uint8_t *key) -{ - struct ppp_option_data data; - uint8_t buf[6 + 16]; - - memset(buf, 0, sizeof(buf)); - buf[0] = CI_MPPE; - buf[1] = 6; - *(uint32_t*)(buf + 2) = htonl(MPPE_S | MPPE_H); - if (key) - memcpy(buf + 6, key, 16); - - memset(&data, 0, sizeof(data)); - data.ptr = buf; - data.length = sizeof(buf); - data.transmit = transmit; - - if (ioctl(fd, PPPIOCSCOMPRESS, &data)) { - log_ppp_warn("mppe: MPPE requested but not supported by kernel\n"); - return -1; - } - - return 0; -} - -static int decrease_mtu(struct ppp_t *ppp) -{ - struct ifreq ifr; - - strcpy(ifr.ifr_name, ppp->ifname); - - if (ioctl(sock_fd, SIOCGIFMTU, &ifr)) { - log_ppp_error("mppe: failed to get MTU: %s\n", strerror(errno)); - return -1; - } - - ifr.ifr_mtu -= MPPE_PAD; - - if (ioctl(sock_fd, SIOCSIFMTU, &ifr)) { - log_ppp_error("mppe: failed to set MTU: %s\n", strerror(errno)); - return -1; - } - - return 0; -} - -static int mppe_send_conf_req(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr) -{ - struct mppe_option_t *mppe_opt = container_of(opt,typeof(*mppe_opt),opt); - struct ccp_opt32_t *opt32 = (struct ccp_opt32_t*)ptr; - - if (mppe_opt->mppe != -1) { - opt32->hdr.id = CI_MPPE; - opt32->hdr.len = 6; - opt32->val = mppe_opt->mppe ? htonl(MPPE_S | MPPE_H) : 0; - - if (mppe_opt->mppe && setup_mppe_key(ccp->ppp->unit_fd, 0, mppe_opt->recv_key)) - return 0; - - return 6; - } - return 0; -} - -static int mppe_recv_conf_req(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr) -{ - struct mppe_option_t *mppe_opt = container_of(opt, typeof(*mppe_opt), opt); - struct ccp_opt32_t *opt32 = (struct ccp_opt32_t *)ptr; - - /*if (!ptr) { - if (mppe_opt->policy == 2) - return CCP_OPT_NAK; - return CCP_OPT_ACK; - }*/ - - if (opt32->hdr.len != 6) - return CCP_OPT_REJ; - - if (mppe_opt->policy == 2) { - if (ntohl(opt32->val) != (MPPE_S | MPPE_H)) - return CCP_OPT_NAK; - } else if (mppe_opt->policy == 1) { - if (ntohl(opt32->val) == (MPPE_S | MPPE_H)) - mppe_opt->mppe = 1; - else if ((ntohl(opt32->val) & (MPPE_S | MPPE_H)) == (MPPE_S | MPPE_H)) { - mppe_opt->mppe = 1; - return CCP_OPT_NAK; - } else if (opt32->val) { - mppe_opt->mppe = 0; - return CCP_OPT_NAK; - } else - mppe_opt->mppe = 0; - } else - return CCP_OPT_REJ; - - if (mppe_opt->mppe) { - if (setup_mppe_key(ccp->ppp->unit_fd, 1, mppe_opt->send_key)) - return CCP_OPT_REJ; - - decrease_mtu(ccp->ppp); - - log_ppp_debug(" (mppe enabled)"); - } - - return CCP_OPT_ACK; -} - -static int mppe_recv_conf_rej(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr) -{ - struct mppe_option_t *mppe_opt = container_of(opt, typeof(*mppe_opt), opt); - - if (mppe_opt->mppe != 2) { - mppe_opt->mppe = -1; - return 0; - } - - return -1; -} - -static int mppe_recv_conf_nak(struct ppp_ccp_t *ccp, struct ccp_option_t *opt, uint8_t *ptr) -{ - struct mppe_option_t *mppe_opt = container_of(opt, typeof(*mppe_opt), opt); - struct ccp_opt32_t *opt32 = (struct ccp_opt32_t *)ptr; - - if (opt32->hdr.len != 6) - return -1; - - if (mppe_opt->policy == 2) { - if (ntohl(opt32->val) == (MPPE_S | MPPE_H)) - return -1; - } else if (mppe_opt->policy == 1) { - if ((ntohl(opt32->val) & (MPPE_S | MPPE_H)) == (MPPE_S | MPPE_H)) - mppe_opt->mppe = 0; - else - mppe_opt->mppe = 1; - } else { - if (opt32->val == 0) - return -1; - } - - return 0; -} - -static void mppe_print(void (*print)(const char *fmt,...),struct ccp_option_t *opt, uint8_t *ptr) -{ - struct mppe_option_t *mppe_opt = container_of(opt, typeof(*mppe_opt), opt); - struct ccp_opt32_t *opt32 = (struct ccp_opt32_t *)ptr; - uint32_t bits; - - if (ptr) - bits = ntohl(opt32->val); - else - if (mppe_opt->mppe) - bits = MPPE_S | MPPE_H; - else - bits = 0; - - print("", - bits & MPPE_H ? "+" : "-", - bits & MPPE_M ? "+" : "-", - bits & MPPE_S ? "+" : "-", - bits & MPPE_L ? "+" : "-", - bits & MPPE_D ? "+" : "-", - bits & MPPE_C ? "+" : "-" - ); -} - -static void ev_mppe_keys(struct ev_mppe_keys_t *ev) -{ - struct mppe_option_t *mppe_opt = container_of(ccp_find_option(ev->ppp, &mppe_opt_hnd), typeof(*mppe_opt), opt); - - if ((ev->type & 0x04) == 0) { - log_ppp_warn("mppe: 128-bit session keys not allowed, disabling mppe ...\n"); - return; - } - - memcpy(mppe_opt->recv_key, ev->recv_key, 16); - memcpy(mppe_opt->send_key, ev->send_key, 16); - mppe_opt->policy = ev->policy; - - if (ev->policy == 2) - mppe_opt->mppe = 1; -} - -static void __init mppe_opt_init() -{ - ccp_option_register(&mppe_opt_hnd); - triton_event_register_handler(EV_MPPE_KEYS, (triton_event_func)ev_mppe_keys); -} - diff --git a/accel-pptpd/ppp/ipcp_opt_dns.c b/accel-pptpd/ppp/ipcp_opt_dns.c deleted file mode 100644 index c177092..0000000 --- a/accel-pptpd/ppp/ipcp_opt_dns.c +++ /dev/null @@ -1,155 +0,0 @@ -#include -#include -#include - -#include "ppp.h" -#include "ppp_ipcp.h" -#include "log.h" -#include "ipdb.h" - -#include "memdebug.h" - -static in_addr_t conf_dns1; -static in_addr_t conf_dns2; - -static struct ipcp_option_t *dns1_init(struct ppp_ipcp_t *ipcp); -static struct ipcp_option_t *dns2_init(struct ppp_ipcp_t *ipcp); -static void dns_free(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt); -static int dns_send_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); -static int dns_send_conf_nak(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); -static int dns_recv_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); -static void dns1_print(void (*print)(const char *fmt,...),struct ipcp_option_t*, uint8_t *ptr); -static void dns2_print(void (*print)(const char *fmt,...),struct ipcp_option_t*, uint8_t *ptr); - -struct dns_option_t -{ - struct ipcp_option_t opt; - in_addr_t addr; -}; - -static struct ipcp_option_handler_t dns1_opt_hnd= -{ - .init=dns1_init, - .send_conf_req=dns_send_conf_req, - .send_conf_nak=dns_send_conf_nak, - .recv_conf_req=dns_recv_conf_req, - .free=dns_free, - .print=dns1_print, -}; -static struct ipcp_option_handler_t dns2_opt_hnd= -{ - .init=dns2_init, - .send_conf_req=dns_send_conf_req, - .send_conf_nak=dns_send_conf_nak, - .recv_conf_req=dns_recv_conf_req, - .free=dns_free, - .print=dns2_print, -}; - -static struct ipcp_option_t *dns1_init(struct ppp_ipcp_t *ipcp) -{ - struct dns_option_t *dns_opt=_malloc(sizeof(*dns_opt)); - memset(dns_opt,0,sizeof(*dns_opt)); - dns_opt->opt.id=CI_DNS1; - dns_opt->opt.len=6; - - return &dns_opt->opt; -} - -static struct ipcp_option_t *dns2_init(struct ppp_ipcp_t *ipcp) -{ - struct dns_option_t *dns_opt=_malloc(sizeof(*dns_opt)); - memset(dns_opt,0,sizeof(*dns_opt)); - dns_opt->opt.id=CI_DNS2; - dns_opt->opt.len=6; - - return &dns_opt->opt; -} - -static void dns_free(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt) -{ - struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); - - _free(dns_opt); -} - -static int dns_send_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) -{ - return 0; -} - -static int dns_send_conf_nak(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) -{ - struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); - struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; - opt32->hdr.id=dns_opt->opt.id; - opt32->hdr.len=6; - opt32->val=dns_opt->addr; - return 6; -} - -static int dns_recv_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) -{ - struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); - struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; - - if (opt32->hdr.len != 6) - return IPCP_OPT_REJ; - - if (!dns_opt->addr) - { - if (dns_opt->opt.id == CI_DNS1 && conf_dns1) dns_opt->addr=conf_dns1; - else if (dns_opt->opt.id == CI_DNS2 && conf_dns2) dns_opt->addr=conf_dns2; - - if (!dns_opt->addr) - { - dns_opt->addr=opt32->val; - return IPCP_OPT_ACK; - } - } - - if (dns_opt->addr==opt32->val) - return IPCP_OPT_ACK; - - return IPCP_OPT_NAK; -} - -static void dns1_print(void (*print)(const char *fmt,...),struct ipcp_option_t *opt, uint8_t *ptr) -{ - struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); - struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; - struct in_addr in; - - if (ptr) in.s_addr=opt32->val; - else in.s_addr=dns_opt->addr; - - print("",inet_ntoa(in)); -} - -static void dns2_print(void (*print)(const char *fmt,...),struct ipcp_option_t *opt, uint8_t *ptr) -{ - struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); - struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; - struct in_addr in; - - if (ptr) in.s_addr=opt32->val; - else in.s_addr=dns_opt->addr; - - print("",inet_ntoa(in)); -} - -static void __init dns_opt_init() -{ - char *opt; - - opt = conf_get_opt("dns", "dns1"); - if (opt) - conf_dns1 = inet_addr(opt); - - opt = conf_get_opt("dns", "dns2"); - if (opt) - conf_dns2 = inet_addr(opt); - - ipcp_option_register(&dns1_opt_hnd); - ipcp_option_register(&dns2_opt_hnd); -} diff --git a/accel-pptpd/ppp/ipcp_opt_ipaddr.c b/accel-pptpd/ppp/ipcp_opt_ipaddr.c deleted file mode 100644 index 334f425..0000000 --- a/accel-pptpd/ppp/ipcp_opt_ipaddr.c +++ /dev/null @@ -1,227 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include "linux_ppp.h" - -#include "ppp.h" -#include "ppp_ipcp.h" -#include "log.h" -#include "ipdb.h" -#include "iprange.h" -#include "events.h" - -#include "memdebug.h" - -static int conf_check_exists; - -static struct ipcp_option_t *ipaddr_init(struct ppp_ipcp_t *ipcp); -static void ipaddr_free(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt); -static int ipaddr_send_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); -static int ipaddr_send_conf_nak(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); -static int ipaddr_recv_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); -//static int ipaddr_recv_conf_ack(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr); -static void ipaddr_print(void (*print)(const char *fmt,...),struct ipcp_option_t*, uint8_t *ptr); - -struct ipaddr_option_t -{ - struct ipcp_option_t opt; - struct ipdb_item_t *ip; - int started:1; -}; - -static struct ipcp_option_handler_t ipaddr_opt_hnd= -{ - .init=ipaddr_init, - .send_conf_req=ipaddr_send_conf_req, - .send_conf_nak=ipaddr_send_conf_nak, - .recv_conf_req=ipaddr_recv_conf_req, - .free=ipaddr_free, - .print=ipaddr_print, -}; - -static struct ipcp_option_t *ipaddr_init(struct ppp_ipcp_t *ipcp) -{ - struct ipaddr_option_t *ipaddr_opt=_malloc(sizeof(*ipaddr_opt)); - memset(ipaddr_opt,0,sizeof(*ipaddr_opt)); - ipaddr_opt->opt.id=CI_ADDR; - ipaddr_opt->opt.len=6; - - return &ipaddr_opt->opt; -} - -static void ipaddr_free(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt) -{ - struct ipaddr_option_t *ipaddr_opt=container_of(opt,typeof(*ipaddr_opt),opt); - - if (ipaddr_opt->ip) - ipdb_put(ipcp->ppp, ipaddr_opt->ip); - - _free(ipaddr_opt); -} - -static int check_exists(struct ppp_t *self_ppp, in_addr_t addr) -{ - struct ppp_t *ppp; - int r = 0; - - pthread_rwlock_rdlock(&ppp_lock); - list_for_each_entry(ppp, &ppp_list, entry) { - if (!ppp->terminating && ppp->peer_ipaddr == addr && ppp != self_ppp) { - log_ppp_warn("ppp:ipcp: requested IP already assigned to %s\n", ppp->ifname); - r = 1; - break; - } - } - pthread_rwlock_unlock(&ppp_lock); - - return r; -} - -static int ipaddr_send_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) -{ - struct ipaddr_option_t *ipaddr_opt=container_of(opt,typeof(*ipaddr_opt),opt); - struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; - - if (!ipaddr_opt->ip) { - ipaddr_opt->ip = ipdb_get(ipcp->ppp); - if (!ipaddr_opt->ip) { - log_ppp_warn("ppp:ipcp: no free IP address\n"); - return -1; - } - } - - if (iprange_tunnel_check(ipaddr_opt->ip->peer_addr)) { - log_ppp_warn("ppp:ipcp: to avoid kernel soft lockup requested IP cannot be assigned (%i.%i.%i.%i)\n", - ipaddr_opt->ip->peer_addr&0xff, - (ipaddr_opt->ip->peer_addr >> 8)&0xff, - (ipaddr_opt->ip->peer_addr >> 16)&0xff, - (ipaddr_opt->ip->peer_addr >> 24)&0xff); - return -1; - } - - if (conf_check_exists && check_exists(ipcp->ppp, ipaddr_opt->ip->peer_addr)) - return -1; - - opt32->hdr.id=CI_ADDR; - opt32->hdr.len=6; - opt32->val=ipaddr_opt->ip->addr; - return 6; -} - -static int ipaddr_send_conf_nak(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) -{ - struct ipaddr_option_t *ipaddr_opt=container_of(opt,typeof(*ipaddr_opt),opt); - struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; - opt32->hdr.id=CI_ADDR; - opt32->hdr.len=6; - opt32->val=ipaddr_opt->ip->peer_addr; - return 6; -} - -static int ipaddr_recv_conf_req(struct ppp_ipcp_t *ipcp, struct ipcp_option_t *opt, uint8_t *ptr) -{ - struct ipaddr_option_t *ipaddr_opt = container_of(opt,typeof(*ipaddr_opt), opt); - struct ipcp_opt32_t *opt32 = (struct ipcp_opt32_t*)ptr; - struct ifreq ifr; - struct sockaddr_in addr; - struct npioctl np; - - if (opt32->hdr.len != 6) - return IPCP_OPT_REJ; - - if (ipaddr_opt->ip->peer_addr == opt32->val) - goto ack; - - /*if (!ipaddr_opt->peer_addr) { - ipaddr_opt->peer_addr = opt32->val; - goto ack; - }*/ - - return IPCP_OPT_NAK; - -ack: - if (ipaddr_opt->started) - return IPCP_OPT_ACK; - - ipaddr_opt->started = 1; - - ipcp->ppp->ipaddr = ipaddr_opt->ip->addr; - ipcp->ppp->peer_ipaddr = ipaddr_opt->ip->peer_addr; - - triton_event_fire(EV_PPP_ACCT_START, ipcp->ppp); - if (ipcp->ppp->stop_time) - return IPCP_OPT_ACK; - - triton_event_fire(EV_PPP_PRE_UP, ipcp->ppp); - if (ipcp->ppp->stop_time) - return IPCP_OPT_ACK; - - memset(&ifr, 0, sizeof(ifr)); - memset(&addr, 0, sizeof(addr)); - - strcpy(ifr.ifr_name, ipcp->ppp->ifname); - - addr.sin_family = AF_INET; - addr.sin_addr.s_addr = ipaddr_opt->ip->addr; - memcpy(&ifr.ifr_addr,&addr,sizeof(addr)); - - if (ioctl(sock_fd, SIOCSIFADDR, &ifr)) - log_ppp_error("ipcp: failed to set PA address: %s\n", strerror(errno)); - - addr.sin_addr.s_addr = ipaddr_opt->ip->peer_addr; - memcpy(&ifr.ifr_dstaddr,&addr,sizeof(addr)); - - if (ioctl(sock_fd, SIOCSIFDSTADDR, &ifr)) - log_ppp_error("ipcp: failed to set remote PA address: %s\n", strerror(errno)); - - if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr)) - log_ppp_error("ipcp: failed to get interface flags: %s\n", strerror(errno)); - - ifr.ifr_flags |= IFF_UP | IFF_POINTOPOINT; - - if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr)) - log_ppp_error("ipcp: failed to set interface flags: %s\n", strerror(errno)); - - np.protocol = PPP_IP; - np.mode = NPMODE_PASS; - - if (ioctl(ipcp->ppp->unit_fd, PPPIOCSNPMODE, &np)) - log_ppp_error("ipcp: failed to set NP mode: %s\n", strerror(errno)); - - return IPCP_OPT_ACK; -} - -static void ipaddr_print(void (*print)(const char *fmt,...),struct ipcp_option_t *opt, uint8_t *ptr) -{ - struct ipaddr_option_t *ipaddr_opt=container_of(opt,typeof(*ipaddr_opt),opt); - struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; - struct in_addr in = { .s_addr = 0, }; - - if (ptr) - in.s_addr = opt32->val; - else if (ipaddr_opt->ip) - in.s_addr = ipaddr_opt->ip->addr; - - print("",inet_ntoa(in)); -} - -static void load_config(void) -{ - const char *opt; - - opt = conf_get_opt("ppp", "check-ip"); - if (opt && atoi(opt) > 0) - conf_check_exists = 1; -} - -static void __init ipaddr_opt_init() -{ - ipcp_option_register(&ipaddr_opt_hnd); - load_config(); - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); -} - diff --git a/accel-pptpd/ppp/lcp_opt_accomp.c b/accel-pptpd/ppp/lcp_opt_accomp.c deleted file mode 100644 index 241b0e0..0000000 --- a/accel-pptpd/ppp/lcp_opt_accomp.c +++ /dev/null @@ -1,106 +0,0 @@ -#include -#include -#include - -#include "ppp.h" -#include "ppp_lcp.h" -#include "log.h" - -#include "memdebug.h" - -static struct lcp_option_t *accomp_init(struct ppp_lcp_t *lcp); -static void accomp_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt); -static int accomp_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int accomp_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int accomp_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static void accomp_print(void (*print)(const char *fmt,...),struct lcp_option_t*, uint8_t *ptr); - -struct accomp_option_t -{ - struct lcp_option_t opt; - int accomp; // 0 - disabled, 1 - enabled, 2 - allow,disabled, 3 - allow,enabled - int require; -}; - -static struct lcp_option_handler_t accomp_opt_hnd= -{ - .init=accomp_init, - .send_conf_req=accomp_send_conf_req, - .send_conf_nak=accomp_send_conf_nak, - .recv_conf_req=accomp_recv_conf_req, - .free=accomp_free, - .print=accomp_print, -}; - -static struct lcp_option_t *accomp_init(struct ppp_lcp_t *lcp) -{ - struct accomp_option_t *accomp_opt=_malloc(sizeof(*accomp_opt)); - memset(accomp_opt,0,sizeof(*accomp_opt)); - accomp_opt->accomp=0; - accomp_opt->opt.id=CI_ACCOMP; - accomp_opt->opt.len=2; - - return &accomp_opt->opt; -} - -static void accomp_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt) -{ - struct accomp_option_t *accomp_opt=container_of(opt,typeof(*accomp_opt),opt); - - _free(accomp_opt); -} - -static int accomp_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct accomp_option_t *accomp_opt=container_of(opt,typeof(*accomp_opt),opt); - struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; - if (accomp_opt->accomp==1 || accomp_opt->accomp==3) - { - opt0->id=CI_ACCOMP; - opt0->len=2; - return 2; - } - return 0; -} - -static int accomp_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct accomp_option_t *accomp_opt=container_of(opt,typeof(*accomp_opt),opt); - struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; - opt0->id=CI_ACCOMP; - opt0->len=2; - return 2; -} - -static int accomp_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct accomp_option_t *accomp_opt=container_of(opt,typeof(*accomp_opt),opt); - struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; - - /*if (!ptr) { - if (accomp_opt->require) - return LCP_OPT_NAK; - accomp_opt->accomp=0; - return LCP_OPT_ACK; - }*/ - - if (opt0->len != 2) - return LCP_OPT_REJ; - - if (accomp_opt->accomp>0) - { - accomp_opt->accomp=1; - return LCP_OPT_ACK; - }else return LCP_OPT_REJ; -} - -static void accomp_print(void (*print)(const char *fmt,...),struct lcp_option_t *opt, uint8_t *ptr) -{ - print(""); -} - -static void __init accomp_opt_init() -{ - lcp_option_register(&accomp_opt_hnd); -} - diff --git a/accel-pptpd/ppp/lcp_opt_magic.c b/accel-pptpd/ppp/lcp_opt_magic.c deleted file mode 100644 index 4a61ef9..0000000 --- a/accel-pptpd/ppp/lcp_opt_magic.c +++ /dev/null @@ -1,91 +0,0 @@ -#include -#include -#include - -#include "ppp.h" -#include "ppp_lcp.h" -#include "log.h" - -#include "memdebug.h" - -static struct lcp_option_t *magic_init(struct ppp_lcp_t *lcp); -static void magic_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt); -static int magic_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int magic_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static void magic_print(void (*print)(const char *fmt,...),struct lcp_option_t*, uint8_t *ptr); - -struct magic_option_t -{ - struct lcp_option_t opt; - int magic; -}; - -static struct lcp_option_handler_t magic_opt_hnd= -{ - .init=magic_init, - .send_conf_req=magic_send_conf_req, - .recv_conf_req=magic_recv_conf_req, - .free=magic_free, - .print=magic_print, -}; - -static struct lcp_option_t *magic_init(struct ppp_lcp_t *lcp) -{ - struct magic_option_t *magic_opt=_malloc(sizeof(*magic_opt)); - memset(magic_opt,0,sizeof(*magic_opt)); - magic_opt->magic=random(); - magic_opt->opt.id=CI_MAGIC; - magic_opt->opt.len=6; - - lcp->magic = magic_opt->magic; - - return &magic_opt->opt; -} - -static void magic_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt) -{ - struct magic_option_t *magic_opt=container_of(opt,typeof(*magic_opt),opt); - - _free(magic_opt); -} - -static int magic_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct magic_option_t *magic_opt=container_of(opt,typeof(*magic_opt),opt); - struct lcp_opt32_t *opt32=(struct lcp_opt32_t*)ptr; - opt32->hdr.id=CI_MAGIC; - opt32->hdr.len=6; - opt32->val=htonl(magic_opt->magic); - return 6; -} - -static int magic_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct magic_option_t *magic_opt=container_of(opt,typeof(*magic_opt),opt); - struct lcp_opt32_t *opt32=(struct lcp_opt32_t*)ptr; - - /*if (!ptr) - return LCP_OPT_NAK;*/ - - if (opt32->hdr.len != 6) - return LCP_OPT_REJ; - - if (magic_opt->magic==ntohl(opt32->val)) - { - log_ppp_error("loop detected"); - return -1; - } - return LCP_OPT_ACK; -} - -static void magic_print(void (*print)(const char *fmt,...),struct lcp_option_t *opt, uint8_t *ptr) -{ - struct magic_option_t *magic_opt=container_of(opt,typeof(*magic_opt),opt); - - print("",magic_opt->magic); -} - -static void __init magic_opt_init() -{ - lcp_option_register(&magic_opt_hnd); -} diff --git a/accel-pptpd/ppp/lcp_opt_mru.c b/accel-pptpd/ppp/lcp_opt_mru.c deleted file mode 100644 index 78e06b5..0000000 --- a/accel-pptpd/ppp/lcp_opt_mru.c +++ /dev/null @@ -1,195 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include "linux_ppp.h" - -#include "ppp.h" -#include "ppp_lcp.h" -#include "log.h" -#include "events.h" - -#include "memdebug.h" - -static int conf_mtu; -static int conf_mru; -static int conf_min_mtu = 100; -static int conf_max_mtu = 1500; - -static struct lcp_option_t *mru_init(struct ppp_lcp_t *lcp); -static void mru_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt); -static int mru_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int mru_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int mru_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int mru_recv_conf_ack(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int mru_recv_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static void mru_print(void (*print)(const char *fmt,...),struct lcp_option_t*, uint8_t *ptr); - -struct mru_option_t -{ - struct lcp_option_t opt; - int mru; - int mtu; - int naked:1; -}; - -static struct lcp_option_handler_t mru_opt_hnd= -{ - .init=mru_init, - .send_conf_req=mru_send_conf_req, - .send_conf_nak=mru_send_conf_nak, - .recv_conf_req=mru_recv_conf_req, - .recv_conf_ack=mru_recv_conf_ack, - .recv_conf_nak=mru_recv_conf_nak, - .free=mru_free, - .print=mru_print, -}; - -static struct lcp_option_t *mru_init(struct ppp_lcp_t *lcp) -{ - struct mru_option_t *mru_opt=_malloc(sizeof(*mru_opt)); - memset(mru_opt, 0, sizeof(*mru_opt)); - mru_opt->mru = (conf_mru && conf_mru <= lcp->ppp->ctrl->max_mtu) ? conf_mru : lcp->ppp->ctrl->max_mtu; - if (mru_opt->mru > conf_max_mtu) - mru_opt->mru = conf_max_mtu; - mru_opt->mtu = (conf_mtu && conf_mtu <= lcp->ppp->ctrl->max_mtu) ? conf_mtu : lcp->ppp->ctrl->max_mtu; - if (mru_opt->mtu > conf_max_mtu) - mru_opt->mtu = conf_max_mtu; - mru_opt->opt.id = CI_MRU; - mru_opt->opt.len = 4; - - return &mru_opt->opt; -} - -static void mru_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt) -{ - struct mru_option_t *mru_opt = container_of(opt, typeof(*mru_opt), opt); - - _free(mru_opt); -} - -static int mru_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct mru_option_t *mru_opt = container_of(opt,typeof(*mru_opt),opt); - struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; - - if (mru_opt->naked) - return 0; - - opt16->hdr.id = CI_MRU; - opt16->hdr.len = 4; - opt16->val = htons(mru_opt->mru); - return 4; -} - -static int mru_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct mru_option_t *mru_opt = container_of(opt,typeof(*mru_opt),opt); - struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; - opt16->hdr.id = CI_MRU; - opt16->hdr.len = 4; - opt16->val = htons(mru_opt->mtu); - return 4; -} - -static int mru_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct mru_option_t *mru_opt = container_of(opt,typeof(*mru_opt),opt); - struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; - - /*if (!ptr) - return LCP_OPT_NAK;*/ - - if (opt16->hdr.len != 4) - return LCP_OPT_REJ; - - if (ntohs(opt16->val) < conf_min_mtu || ntohs(opt16->val) > lcp->ppp->ctrl->max_mtu || ntohs(opt16->val) > conf_max_mtu) - return LCP_OPT_NAK; - - mru_opt->mtu = ntohs(opt16->val); - return LCP_OPT_ACK; -} - -static int mru_recv_conf_ack(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct mru_option_t *mru_opt = container_of(opt,typeof(*mru_opt), opt); - struct ifreq ifr = { - .ifr_mtu = mru_opt->mtu, - }; - - strcpy(ifr.ifr_name, lcp->ppp->ifname); - - if (ioctl(lcp->ppp->unit_fd, PPPIOCSMRU, &mru_opt->mru)) - log_ppp_error("lcp:mru: failed to set MRU: %s\n", strerror(errno)); - - if (ioctl(sock_fd, SIOCSIFMTU, &ifr)) - log_ppp_error("lcp:mru: failed to set MTU: %s\n", strerror(errno)); - - return 0; -} - -static int mru_recv_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct mru_option_t *mru_opt = container_of(opt,typeof(*mru_opt), opt); - mru_opt->naked = 1; - return 0; -} - -static void mru_print(void (*print)(const char *fmt,...), struct lcp_option_t *opt, uint8_t *ptr) -{ - struct mru_option_t *mru_opt = container_of(opt, typeof(*mru_opt), opt); - struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; - - if (ptr) - print("",ntohs(opt16->val)); - else - print("",mru_opt->mru); -} - -static void load_config(void) -{ - char *opt; - - opt = conf_get_opt("ppp", "mtu"); - if (opt && atoi(opt) > 0) - conf_mtu = atoi(opt); - - opt = conf_get_opt("ppp", "mru"); - if (opt && atoi(opt) > 0) - conf_mru = atoi(opt); - - opt = conf_get_opt("ppp", "min-mtu"); - if (opt && atoi(opt) > 0) - conf_min_mtu = atoi(opt); - - opt = conf_get_opt("ppp", "max-mtu"); - if (opt && atoi(opt) > 0) - conf_max_mtu = atoi(opt); - - if (conf_min_mtu > conf_mru) { - log_emerg("min-mtu cann't be greater then mtu/mru\n"); - conf_min_mtu = conf_mru; - } - - if (conf_min_mtu > 1500) { - log_emerg("min-mtu cann't be greater then 1500\n"); - conf_min_mtu = 1500; - } - - if (conf_mru > 1500 || conf_mtu > 1500) { - log_emerg("mtu/mru cann't be greater then 1500\n"); - conf_mru = 1500; - } -} - -static void __init mru_opt_init() -{ - load_config(); - lcp_option_register(&mru_opt_hnd); - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); -} - diff --git a/accel-pptpd/ppp/lcp_opt_pcomp.c b/accel-pptpd/ppp/lcp_opt_pcomp.c deleted file mode 100644 index 1f8532b..0000000 --- a/accel-pptpd/ppp/lcp_opt_pcomp.c +++ /dev/null @@ -1,106 +0,0 @@ -#include -#include -#include - -#include "ppp.h" -#include "ppp_lcp.h" -#include "log.h" - -#include "memdebug.h" - -static struct lcp_option_t *pcomp_init(struct ppp_lcp_t *lcp); -static void pcomp_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt); -static int pcomp_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int pcomp_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int pcomp_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static void pcomp_print(void (*print)(const char *fmt,...),struct lcp_option_t*, uint8_t *ptr); - -struct pcomp_option_t -{ - struct lcp_option_t opt; - int pcomp; // 0 - disabled, 1 - enabled, 2 - allow,disabled, 3 - allow,enabled - int require; -}; - -static struct lcp_option_handler_t pcomp_opt_hnd= -{ - .init=pcomp_init, - .send_conf_req=pcomp_send_conf_req, - .send_conf_nak=pcomp_send_conf_nak, - .recv_conf_req=pcomp_recv_conf_req, - .free=pcomp_free, - .print=pcomp_print, -}; - -static struct lcp_option_t *pcomp_init(struct ppp_lcp_t *lcp) -{ - struct pcomp_option_t *pcomp_opt=_malloc(sizeof(*pcomp_opt)); - memset(pcomp_opt,0,sizeof(*pcomp_opt)); - pcomp_opt->pcomp=0; - pcomp_opt->opt.id=CI_PCOMP; - pcomp_opt->opt.len=2; - - return &pcomp_opt->opt; -} - -static void pcomp_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt) -{ - struct pcomp_option_t *pcomp_opt=container_of(opt,typeof(*pcomp_opt),opt); - - _free(pcomp_opt); -} - -static int pcomp_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct pcomp_option_t *pcomp_opt=container_of(opt,typeof(*pcomp_opt),opt); - struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; - if (pcomp_opt->pcomp==1 || pcomp_opt->pcomp==3) - { - opt0->id=CI_PCOMP; - opt0->len=2; - return 2; - } - return 0; -} - -static int pcomp_send_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct pcomp_option_t *pcomp_opt=container_of(opt,typeof(*pcomp_opt),opt); - struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; - opt0->id=CI_PCOMP; - opt0->len=2; - return 2; -} - -static int pcomp_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct pcomp_option_t *pcomp_opt=container_of(opt,typeof(*pcomp_opt),opt); - struct lcp_opt_hdr_t *opt0=(struct lcp_opt_hdr_t*)ptr; - - /*if (!ptr) { - if (pcomp_opt->require) - return LCP_OPT_NAK; - pcomp_opt->pcomp=0; - return LCP_OPT_ACK; - }*/ - - if (opt0->len != 2) - return LCP_OPT_REJ; - - if (pcomp_opt->pcomp>0) - { - pcomp_opt->pcomp=1; - return LCP_OPT_ACK; - }else return LCP_OPT_REJ; -} - -static void pcomp_print(void (*print)(const char *fmt,...),struct lcp_option_t *opt, uint8_t *ptr) -{ - print(""); -} - -static void __init pcomp_opt_init() -{ - lcp_option_register(&pcomp_opt_hnd); -} - diff --git a/accel-pptpd/ppp/ppp.c b/accel-pptpd/ppp/ppp.c deleted file mode 100644 index 6cf1c72..0000000 --- a/accel-pptpd/ppp/ppp.c +++ /dev/null @@ -1,681 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "linux_ppp.h" - -#include - -#include "triton.h" - -#include "events.h" -#include "ppp.h" -#include "ppp_fsm.h" -#include "log.h" -#include "spinlock.h" - -#include "memdebug.h" - -int __export conf_ppp_verbose; -static int conf_sid_ucase; - -pthread_rwlock_t __export ppp_lock = PTHREAD_RWLOCK_INITIALIZER; -__export LIST_HEAD(ppp_list); - -static LIST_HEAD(layers); -int __export sock_fd; - -int __export ppp_shutdown; - -static unsigned long long seq; -#if __WORDSIZE == 32 -static spinlock_t seq_lock; -#endif - - -struct ppp_stat_t ppp_stat; - -struct layer_node_t -{ - struct list_head entry; - int order; - struct list_head items; -}; - -static int ppp_chan_read(struct triton_md_handler_t*); -static int ppp_unit_read(struct triton_md_handler_t*); -static void init_layers(struct ppp_t *); -static void _free_layers(struct ppp_t *); -static void start_first_layer(struct ppp_t *); - -void __export ppp_init(struct ppp_t *ppp) -{ - memset(ppp,0,sizeof(*ppp)); - INIT_LIST_HEAD(&ppp->layers); - INIT_LIST_HEAD(&ppp->chan_handlers); - INIT_LIST_HEAD(&ppp->unit_handlers); - INIT_LIST_HEAD(&ppp->pd_list); -} - -static void _free_ppp(struct ppp_t *ppp) -{ - if (ppp->chan_buf) - free(ppp->chan_buf); - if (ppp->unit_buf) - _free(ppp->unit_buf); - if (ppp->username) - _free(ppp->username); -} - -static void generate_sessionid(struct ppp_t *ppp) -{ - unsigned long long sid; - -#if __WORDSIZE == 32 - spin_lock(&seq_lock); - sid = ++seq; - spin_unlock(&seq_lock); -#else - sid = __sync_add_and_fetch(&seq, 1); -#endif - - if (conf_sid_ucase) - sprintf(ppp->sessionid, "%016llX", sid); - else - sprintf(ppp->sessionid, "%016llx", sid); -} - -int __export establish_ppp(struct ppp_t *ppp) -{ - /* Open an instance of /dev/ppp and connect the channel to it */ - if (ioctl(ppp->fd, PPPIOCGCHAN, &ppp->chan_idx) == -1) { - log_ppp_error("ioctl(PPPIOCGCHAN): %s\n", strerror(errno)); - return -1; - } - - ppp->chan_fd = open("/dev/ppp", O_RDWR); - if (ppp->chan_fd < 0) { - log_ppp_error("open(chan) /dev/ppp: %s\n", strerror(errno)); - return -1; - } - - if (ioctl(ppp->chan_fd, PPPIOCATTCHAN, &ppp->chan_idx) < 0) { - log_ppp_error("ioctl(PPPIOCATTCHAN): %s\n", strerror(errno)); - goto exit_close_chan; - } - - ppp->unit_fd = open("/dev/ppp", O_RDWR); - if (ppp->unit_fd < 0) { - log_ppp_error("open(unit) /dev/ppp: %s\n", strerror(errno)); - goto exit_close_chan; - } - - ppp->unit_idx = -1; - if (ioctl(ppp->unit_fd, PPPIOCNEWUNIT, &ppp->unit_idx) < 0) { - log_ppp_error("ioctl(PPPIOCNEWUNIT): %s\n", strerror(errno)); - goto exit_close_unit; - } - - if (ioctl(ppp->chan_fd, PPPIOCCONNECT, &ppp->unit_idx) < 0) { - log_ppp_error("ioctl(PPPIOCCONNECT): %s\n", strerror(errno)); - goto exit_close_unit; - } - - if (fcntl(ppp->chan_fd, F_SETFL, O_NONBLOCK)) { - log_ppp_error("ppp: cann't to set nonblocking mode: %s\n", strerror(errno)); - goto exit_close_unit; - } - - if (fcntl(ppp->unit_fd, F_SETFL, O_NONBLOCK)) { - log_ppp_error("ppp: cann't to set nonblocking mode: %s\n", strerror(errno)); - goto exit_close_unit; - } - - ppp->start_time = time(NULL); - generate_sessionid(ppp); - sprintf(ppp->ifname, "ppp%i", ppp->unit_idx); - - log_ppp_info1("connect: %s <--> %s(%s)\n", ppp->ifname, ppp->ctrl->name, ppp->chan_name); - - init_layers(ppp); - - if (list_empty(&ppp->layers)) { - log_ppp_error("no layers to start\n"); - goto exit_close_unit; - } - - ppp->chan_buf = _malloc(PPP_MRU); - ppp->unit_buf = _malloc(PPP_MRU); - - ppp->chan_hnd.fd = ppp->chan_fd; - ppp->chan_hnd.read = ppp_chan_read; - ppp->unit_hnd.fd = ppp->unit_fd; - ppp->unit_hnd.read = ppp_unit_read; - triton_md_register_handler(ppp->ctrl->ctx, &ppp->chan_hnd); - triton_md_register_handler(ppp->ctrl->ctx, &ppp->unit_hnd); - - triton_md_enable_handler(&ppp->chan_hnd, MD_MODE_READ); - triton_md_enable_handler(&ppp->unit_hnd, MD_MODE_READ); - - ppp->state = PPP_STATE_STARTING; - __sync_add_and_fetch(&ppp_stat.starting, 1); - - pthread_rwlock_wrlock(&ppp_lock); - list_add_tail(&ppp->entry, &ppp_list); - pthread_rwlock_unlock(&ppp_lock); - - log_ppp_debug("ppp established\n"); - - triton_event_fire(EV_PPP_STARTING, ppp); - - start_first_layer(ppp); - - return 0; - -exit_close_unit: - close(ppp->unit_fd); -exit_close_chan: - close(ppp->chan_fd); - - _free_ppp(ppp); - - return -1; -} - -static void destablish_ppp(struct ppp_t *ppp) -{ - pthread_rwlock_wrlock(&ppp_lock); - list_del(&ppp->entry); - pthread_rwlock_unlock(&ppp_lock); - - switch (ppp->state) { - case PPP_STATE_ACTIVE: - __sync_sub_and_fetch(&ppp_stat.active, 1); - break; - case PPP_STATE_STARTING: - __sync_sub_and_fetch(&ppp_stat.starting, 1); - break; - case PPP_STATE_FINISHING: - __sync_sub_and_fetch(&ppp_stat.finishing, 1); - break; - } - - triton_md_unregister_handler(&ppp->chan_hnd); - triton_md_unregister_handler(&ppp->unit_hnd); - - close(ppp->unit_fd); - close(ppp->chan_fd); - close(ppp->fd); - - ppp->unit_fd = -1; - ppp->chan_fd = -1; - ppp->fd = -1; - - _free(ppp->unit_buf); - _free(ppp->chan_buf); - - _free_layers(ppp); - - ppp->terminated = 1; - - log_ppp_debug("ppp destablished\n"); - - triton_event_fire(EV_PPP_FINISHED, ppp); - ppp->ctrl->finished(ppp); - - if (ppp->username) { - _free(ppp->username); - ppp->username = NULL; - } - - if (ppp_shutdown && !ppp_stat.starting && !ppp_stat.active && !ppp_stat.finishing) - kill(getpid(), SIGTERM); -} - -/*void print_buf(uint8_t *buf, int size) -{ - int i; - for(i=0;ichan_fd,data,size); - if (n < size) - log_ppp_error("ppp_chan_send: short write %i, excpected %i\n", n, size); - return n; -} - -int __export ppp_unit_send(struct ppp_t *ppp, void *data, int size) -{ - int n; - - //printf("ppp_unit_send: "); - //print_buf((uint8_t*)data,size); - - n=write(ppp->unit_fd, data, size); - if (n < size) - log_ppp_error("ppp_unit_send: short write %i, excpected %i\n",n,size); - return n; -} - -static int ppp_chan_read(struct triton_md_handler_t *h) -{ - struct ppp_t *ppp = container_of(h, typeof(*ppp), chan_hnd); - struct ppp_handler_t *ppp_h; - uint16_t proto; - - while(1) { -cont: - ppp->chan_buf_size = read(h->fd, ppp->chan_buf, PPP_MRU); - if (ppp->chan_buf_size < 0) { - if (errno == EAGAIN) - return 0; - log_ppp_error("ppp_chan_read: %s\n", strerror(errno)); - return 0; - } - - //printf("ppp_chan_read: "); - //print_buf(ppp->chan_buf,ppp->chan_buf_size); - if (ppp->chan_buf_size == 0) { - ppp_terminate(ppp, 1, TERM_NAS_ERROR); - return 1; - } - - if (ppp->chan_buf_size < 2) { - log_ppp_error("ppp_chan_read: short read %i\n", ppp->chan_buf_size); - continue; - } - - proto = ntohs(*(uint16_t*)ppp->chan_buf); - list_for_each_entry(ppp_h, &ppp->chan_handlers, entry) { - if (ppp_h->proto == proto) { - ppp_h->recv(ppp_h); - if (ppp->chan_fd == -1) { - ppp->ctrl->finished(ppp); - return 1; - } - goto cont; - } - } - - lcp_send_proto_rej(ppp, proto); - //log_ppp_warn("ppp_chan_read: discarding unknown packet %x\n", proto); - } -} - -static int ppp_unit_read(struct triton_md_handler_t *h) -{ - struct ppp_t *ppp = container_of(h, typeof(*ppp), unit_hnd); - struct ppp_handler_t *ppp_h; - uint16_t proto; - - while (1) { -cont: - ppp->unit_buf_size = read(h->fd, ppp->unit_buf, PPP_MRU); - if (ppp->unit_buf_size < 0) { - if (errno == EAGAIN) - return 0; - log_ppp_error("ppp_unit_read: %s\n",strerror(errno)); - return 0; - } - - md_check(ppp->unit_buf); - //printf("ppp_unit_read: "); - //print_buf(ppp->unit_buf,ppp->unit_buf_size); - - if (ppp->unit_buf_size == 0) { - ppp_terminate(ppp, 1, TERM_NAS_ERROR); - return 1; - } - - if (ppp->unit_buf_size < 2) { - log_ppp_error("ppp_unit_read: short read %i\n", ppp->unit_buf_size); - continue; - } - - proto=ntohs(*(uint16_t*)ppp->unit_buf); - list_for_each_entry(ppp_h, &ppp->unit_handlers, entry) { - if (ppp_h->proto == proto) { - ppp_h->recv(ppp_h); - if (ppp->unit_fd == -1) { - ppp->ctrl->finished(ppp); - return 1; - } - goto cont; - } - } - lcp_send_proto_rej(ppp, proto); - //log_ppp_warn("ppp_unit_read: discarding unknown packet %x\n", proto); - } -} - -void ppp_recv_proto_rej(struct ppp_t *ppp, uint16_t proto) -{ - struct ppp_handler_t *ppp_h; - - list_for_each_entry(ppp_h, &ppp->chan_handlers, entry) { - if (ppp_h->proto == proto) { - if (ppp_h->recv_proto_rej) - ppp_h->recv_proto_rej(ppp_h); - return; - } - } - - list_for_each_entry(ppp_h, &ppp->unit_handlers, entry) { - if (ppp_h->proto == proto) { - if (ppp_h->recv_proto_rej) - ppp_h->recv_proto_rej(ppp_h); - return; - } - } -} - -void __export ppp_layer_started(struct ppp_t *ppp, struct ppp_layer_data_t *d) -{ - struct layer_node_t *n = d->node; - - if (d->started) - return; - - d->started = 1; - - list_for_each_entry(d, &n->items, entry) - if (!d->started) return; - - if (n->entry.next == &ppp->layers) { - ppp->state = PPP_STATE_ACTIVE; - __sync_sub_and_fetch(&ppp_stat.starting, 1); - __sync_add_and_fetch(&ppp_stat.active, 1); - ppp->ctrl->started(ppp); - triton_event_fire(EV_PPP_STARTED, ppp); - } else { - n = list_entry(n->entry.next, typeof(*n), entry); - list_for_each_entry(d, &n->items, entry) { - d->starting = 1; - if (d->layer->start(d)) { - ppp_terminate(ppp, TERM_NAS_ERROR, 0); - return; - } - } - } -} - -void __export ppp_layer_finished(struct ppp_t *ppp, struct ppp_layer_data_t *d) -{ - struct layer_node_t *n = d->node; - - d->finished = 1; - d->starting = 0; - - list_for_each_entry(n, &ppp->layers, entry) { - list_for_each_entry(d, &n->items, entry) { - if (d->starting && !d->finished) - return; - } - } - - destablish_ppp(ppp); -} - -void __export ppp_terminate(struct ppp_t *ppp, int cause, int hard) -{ - struct layer_node_t *n; - struct ppp_layer_data_t *d; - int s = 0; - - if (ppp->terminated) - return; - - if (!ppp->stop_time) - time(&ppp->stop_time); - - if (!ppp->terminate_cause) - ppp->terminate_cause = cause; - - if (ppp->terminating) { - if (hard) - destablish_ppp(ppp); - return; - } - - ppp->terminating = 1; - if (ppp->state == PPP_STATE_ACTIVE) - __sync_sub_and_fetch(&ppp_stat.active, 1); - else - __sync_sub_and_fetch(&ppp_stat.starting, 1); - __sync_add_and_fetch(&ppp_stat.finishing, 1); - ppp->state = PPP_STATE_FINISHING; - - log_ppp_debug("ppp_terminate\n"); - - triton_event_fire(EV_PPP_FINISHING, ppp); - - if (hard) { - destablish_ppp(ppp); - return; - } - - list_for_each_entry(n,&ppp->layers,entry) { - list_for_each_entry(d,&n->items,entry) { - if (d->starting) { - s = 1; - d->layer->finish(d); - } - } - } - if (s) - return; - destablish_ppp(ppp); -} - -void __export ppp_register_chan_handler(struct ppp_t *ppp,struct ppp_handler_t *h) -{ - list_add_tail(&h->entry,&ppp->chan_handlers); -} -void __export ppp_register_unit_handler(struct ppp_t *ppp,struct ppp_handler_t *h) -{ - list_add_tail(&h->entry,&ppp->unit_handlers); -} -void __export ppp_unregister_handler(struct ppp_t *ppp,struct ppp_handler_t *h) -{ - list_del(&h->entry); -} - -static int get_layer_order(const char *name) -{ - if (!strcmp(name,"lcp")) return 0; - if (!strcmp(name,"auth")) return 1; - if (!strcmp(name,"ccp")) return 2; - if (!strcmp(name,"ipcp")) return 2; - return -1; -} - -int __export ppp_register_layer(const char *name, struct ppp_layer_t *layer) -{ - int order; - struct layer_node_t *n,*n1; - - order = get_layer_order(name); - - if (order < 0) - return order; - - list_for_each_entry(n, &layers, entry) { - if (order > n->order) - continue; - if (order < n->order) { - n1 = _malloc(sizeof(*n1)); - memset(n1, 0, sizeof(*n1)); - n1->order = order; - INIT_LIST_HEAD(&n1->items); - list_add_tail(&n1->entry, &n->entry); - n = n1; - } - goto insert; - } - n1 = _malloc(sizeof(*n1)); - memset(n1, 0, sizeof(*n1)); - n1->order = order; - INIT_LIST_HEAD(&n1->items); - list_add_tail(&n1->entry, &layers); - n = n1; -insert: - list_add_tail(&layer->entry, &n->items); - - return 0; -} -void __export ppp_unregister_layer(struct ppp_layer_t *layer) -{ - list_del(&layer->entry); -} - -static void init_layers(struct ppp_t *ppp) -{ - struct layer_node_t *n, *n1; - struct ppp_layer_t *l; - struct ppp_layer_data_t *d; - - list_for_each_entry(n,&layers,entry) { - n1 = _malloc(sizeof(*n1)); - memset(n1, 0, sizeof(*n1)); - INIT_LIST_HEAD(&n1->items); - list_add_tail(&n1->entry, &ppp->layers); - list_for_each_entry(l, &n->items, entry) { - d = l->init(ppp); - d->layer = l; - d->started = 0; - d->node = n1; - list_add_tail(&d->entry, &n1->items); - } - } -} - -static void _free_layers(struct ppp_t *ppp) -{ - struct layer_node_t *n; - struct ppp_layer_data_t *d; - - while (!list_empty(&ppp->layers)) { - n = list_entry(ppp->layers.next, typeof(*n), entry); - while (!list_empty(&n->items)) { - d = list_entry(n->items.next, typeof(*d), entry); - list_del(&d->entry); - d->layer->free(d); - } - list_del(&n->entry); - _free(n); - } -} - -static void start_first_layer(struct ppp_t *ppp) -{ - struct layer_node_t *n; - struct ppp_layer_data_t *d; - - n = list_entry(ppp->layers.next, typeof(*n), entry); - list_for_each_entry(d, &n->items, entry) { - d->starting = 1; - if (d->layer->start(d)) { - ppp_terminate(ppp, TERM_NAS_ERROR, 0); - return; - } - } -} - -struct ppp_layer_data_t *ppp_find_layer_data(struct ppp_t *ppp, struct ppp_layer_t *layer) -{ - struct layer_node_t *n; - struct ppp_layer_data_t *d; - - list_for_each_entry(n,&ppp->layers,entry) { - list_for_each_entry(d,&n->items,entry) { - if (d->layer == layer) - return d; - } - } - - return NULL; -} - -void ppp_shutdown_soft(void) -{ - ppp_shutdown = 1; - - if (!ppp_stat.starting && !ppp_stat.active && !ppp_stat.finishing) - kill(getpid(), SIGTERM); -} - -static void save_seq(void) -{ - FILE *f; - char *opt = conf_get_opt("ppp", "seq-file"); - if (!opt) - opt = "/var/run/accel-pptp/seq"; - - f = fopen(opt, "w"); - if (f) { - fprintf(f, "%llu", seq); - fclose(f); - } -} - -static void load_config(void) -{ - char *opt; - - opt = conf_get_opt("ppp", "verbose"); - if (opt && atoi(opt) > 0) - conf_ppp_verbose = 1; - - opt = conf_get_opt("ppp", "sid-case"); - if (opt) { - if (!strcmp(opt, "upper")) - conf_sid_ucase = 1; - else if (strcmp(opt, "lower")) - log_emerg("ppp: sid-case: invalid format\n"); - } -} - -static void __init init(void) -{ - char *opt; - FILE *f; - - sock_fd = socket(AF_INET, SOCK_DGRAM, 0); - if (sock_fd < 0) { - perror("socket"); - _exit(EXIT_FAILURE); - } - - opt = conf_get_opt("ppp", "seq-file"); - if (!opt) - opt = "/var/run/accel-pptp/seq"; - - f = fopen(opt, "r"); - if (f) { - fscanf(f, "%llu", &seq); - fclose(f); - } else - seq = (unsigned long long)random() * (unsigned long long)random(); - - load_config(); - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); - - atexit(save_seq); -} - diff --git a/accel-pptpd/ppp/ppp.h b/accel-pptpd/ppp/ppp.h deleted file mode 100644 index c633135..0000000 --- a/accel-pptpd/ppp/ppp.h +++ /dev/null @@ -1,189 +0,0 @@ -#ifndef PPP_H -#define PPP_H - -#include -#include -#include -#include - -#include "triton.h" -#include "list.h" - -/* - * Packet header = Code, id, length. - */ -#define PPP_HEADERLEN 4 -#define PPP_MTU 1500 - - -/* - * Protocol field values. - */ -#define PPP_IP 0x21 /* Internet Protocol */ -#define PPP_AT 0x29 /* AppleTalk Protocol */ -#define PPP_IPX 0x2b /* IPX protocol */ -#define PPP_VJC_COMP 0x2d /* VJ compressed TCP */ -#define PPP_VJC_UNCOMP 0x2f /* VJ uncompressed TCP */ -#define PPP_IPV6 0x57 /* Internet Protocol Version 6 */ -#define PPP_COMP 0xfd /* compressed packet */ -#define PPP_IPCP 0x8021 /* IP Control Protocol */ -#define PPP_ATCP 0x8029 /* AppleTalk Control Protocol */ -#define PPP_IPXCP 0x802b /* IPX Control Protocol */ -#define PPP_IPV6CP 0x8057 /* IPv6 Control Protocol */ -#define PPP_CCP 0x80fd /* Compression Control Protocol */ -#define PPP_ECP 0x8053 /* Encryption Control Protocol */ -#define PPP_LCP 0xc021 /* Link Control Protocol */ -#define PPP_PAP 0xc023 /* Password Authentication Protocol */ -#define PPP_LQR 0xc025 /* Link Quality Report protocol */ -#define PPP_CHAP 0xc223 /* Cryptographic Handshake Auth. Protocol */ -#define PPP_CBCP 0xc029 /* Callback Control Protocol */ -#define PPP_EAP 0xc227 /* Extensible Authentication Protocol */ - -#define PPP_SESSIONID_LEN 16 -#define PPP_IFNAME_LEN 10 - -#define PPP_STATE_STARTING 1 -#define PPP_STATE_ACTIVE 2 -#define PPP_STATE_FINISHING 3 - -#define TERM_USER_REQUEST 1 -#define TERM_SESSION_TIMEOUT 2 -#define TERM_ADMIN_RESET 3 -#define TERM_USER_ERROR 4 -#define TERM_NAS_ERROR 5 -#define TERM_NAS_REQUEST 6 -#define TERM_NAS_REBOOT 7 -#define TERM_AUTH_ERROR 8 - - -struct ppp_t; - -struct ppp_ctrl_t -{ - struct triton_context_t *ctx; - const char *name; - int max_mtu; - char *calling_station_id; - char *called_station_id; - void (*started)(struct ppp_t*); - void (*finished)(struct ppp_t*); -}; - -struct ppp_pd_t -{ - struct list_head entry; - void *key; -}; - -struct ppp_t -{ - struct list_head entry; - struct triton_md_handler_t chan_hnd; - struct triton_md_handler_t unit_hnd; - int fd; - int chan_fd; - int unit_fd; - - int chan_idx; - int unit_idx; - - int state; - char *chan_name; - char ifname[PPP_IFNAME_LEN]; - char sessionid[PPP_SESSIONID_LEN+1]; - time_t start_time; - time_t stop_time; - char *username; - in_addr_t ipaddr; - in_addr_t peer_ipaddr; - - struct ppp_ctrl_t *ctrl; - - int terminating:1; - int terminated:1; - int terminate_cause; - - void *chan_buf; - int chan_buf_size; - void *unit_buf; - int unit_buf_size; - - struct list_head chan_handlers; - struct list_head unit_handlers; - - struct list_head layers; - - struct ppp_lcp_t *lcp; - - struct list_head pd_list; -}; - -struct ppp_layer_t; -struct layer_node_t; -struct ppp_layer_data_t -{ - struct list_head entry; - struct ppp_layer_t *layer; - struct layer_node_t *node; - int starting:1; - int started:1; - int finished:1; -}; - -struct ppp_layer_t -{ - struct list_head entry; - struct ppp_layer_data_t *(*init)(struct ppp_t *); - int (*start)(struct ppp_layer_data_t*); - void (*finish)(struct ppp_layer_data_t*); - void (*free)(struct ppp_layer_data_t *); -}; - -struct ppp_handler_t -{ - struct list_head entry; - int proto; - void (*recv)(struct ppp_handler_t*); - void (*recv_proto_rej)(struct ppp_handler_t *h); -}; - -struct ppp_stat_t -{ - unsigned int active; - unsigned int starting; - unsigned int finishing; -}; - -struct ppp_t *alloc_ppp(void); -void ppp_init(struct ppp_t *ppp); -int establish_ppp(struct ppp_t *ppp); -int ppp_chan_send(struct ppp_t *ppp, void *data, int size); -int ppp_unit_send(struct ppp_t *ppp, void *data, int size); -void lcp_send_proto_rej(struct ppp_t *ppp, uint16_t proto); -void ppp_recv_proto_rej(struct ppp_t *ppp, uint16_t proto); - -struct ppp_fsm_t* ppp_lcp_init(struct ppp_t *ppp); -void ppp_layer_started(struct ppp_t *ppp,struct ppp_layer_data_t*); -void ppp_layer_finished(struct ppp_t *ppp,struct ppp_layer_data_t*); -void ppp_terminate(struct ppp_t *ppp, int hard, int cause); - -void ppp_register_chan_handler(struct ppp_t *, struct ppp_handler_t *); -void ppp_register_unit_handler(struct ppp_t * ,struct ppp_handler_t *); -void ppp_unregister_handler(struct ppp_t *, struct ppp_handler_t *); - -int ppp_register_layer(const char *name, struct ppp_layer_t *); -void ppp_unregister_layer(struct ppp_layer_t *); -struct ppp_layer_data_t *ppp_find_layer_data(struct ppp_t *, struct ppp_layer_t *); - -extern int ppp_shutdown; -void ppp_shutdown_soft(void); - -extern int conf_ppp_verbose; - -extern pthread_rwlock_t ppp_lock; -extern struct list_head ppp_list; - -extern struct ppp_stat_t ppp_stat; - -extern int sock_fd; // internet socket for ioctls -#endif diff --git a/accel-pptpd/ppp/ppp_auth.c b/accel-pptpd/ppp/ppp_auth.c deleted file mode 100644 index 32413c6..0000000 --- a/accel-pptpd/ppp/ppp_auth.c +++ /dev/null @@ -1,346 +0,0 @@ -#include -#include -#include - -#include "ppp.h" -#include "events.h" -#include "ppp_lcp.h" -#include "log.h" - -#include "ppp_auth.h" - -#include "memdebug.h" - -static LIST_HEAD(auth_handlers); -static int extra_opt_len = 0; - -static struct lcp_option_t *auth_init(struct ppp_lcp_t *lcp); -static void auth_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt); -static int auth_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int auth_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int auth_recv_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int auth_recv_conf_rej(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static int auth_recv_conf_ack(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr); -static void auth_print(void (*print)(const char *fmt,...), struct lcp_option_t*, uint8_t *ptr); - -static struct ppp_layer_data_t *auth_layer_init(struct ppp_t*); -static int auth_layer_start(struct ppp_layer_data_t *); -static void auth_layer_finish(struct ppp_layer_data_t *); -static void auth_layer_free(struct ppp_layer_data_t *); - -struct auth_option_t -{ - struct lcp_option_t opt; - struct list_head auth_list; - struct auth_data_t *auth; - struct auth_data_t *peer_auth; - int started:1; -}; - -struct auth_layer_data_t -{ - struct ppp_layer_data_t ld; - struct auth_option_t auth_opt; - struct ppp_t *ppp; -}; - -static struct lcp_option_handler_t auth_opt_hnd = -{ - .init = auth_init, - .send_conf_req = auth_send_conf_req, - .send_conf_nak = auth_send_conf_req, - .recv_conf_req = auth_recv_conf_req, - .recv_conf_nak = auth_recv_conf_nak, - .recv_conf_rej = auth_recv_conf_rej, - .recv_conf_ack = auth_recv_conf_ack, - .free = auth_free, - .print = auth_print, -}; - -static struct ppp_layer_t auth_layer = -{ - .init = auth_layer_init, - .start = auth_layer_start, - .finish = auth_layer_finish, - .free = auth_layer_free, -}; - -static struct lcp_option_t *auth_init(struct ppp_lcp_t *lcp) -{ - struct ppp_auth_handler_t *h; - struct auth_data_t *d; - struct auth_layer_data_t *ad; - - ad = container_of(ppp_find_layer_data(lcp->ppp, &auth_layer), typeof(*ad), ld); - - ad->auth_opt.opt.id = CI_AUTH; - ad->auth_opt.opt.len = 4 + extra_opt_len; - - INIT_LIST_HEAD(&ad->auth_opt.auth_list); - - list_for_each_entry(h, &auth_handlers, entry) { - d = h->init(lcp->ppp); - d->h = h; - list_add_tail(&d->entry, &ad->auth_opt.auth_list); - } - - return &ad->auth_opt.opt; -} - -static void auth_free(struct ppp_lcp_t *lcp, struct lcp_option_t *opt) -{ - struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); - struct auth_data_t *d; - - if (auth_opt->started && auth_opt->auth) { - auth_opt->auth->h->finish(lcp->ppp, auth_opt->auth); - auth_opt->started = 0; - } - - while(!list_empty(&auth_opt->auth_list)) { - d = list_entry(auth_opt->auth_list.next, typeof(*d), entry); - list_del(&d->entry); - d->h->free(lcp->ppp, d); - } -} - -static int auth_send_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); - struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; - struct auth_data_t *d; - int n; - - if (list_empty(&auth_opt->auth_list)) - return 0; - - if (!auth_opt->auth || auth_opt->auth->state == LCP_OPT_NAK) { - list_for_each_entry(d, &auth_opt->auth_list, entry) { - if (d->state == LCP_OPT_NAK || d->state == LCP_OPT_REJ) - continue; - auth_opt->auth = d; - break; - } - } - - opt16->hdr.id = CI_AUTH; - opt16->val = htons(auth_opt->auth->proto); - n = auth_opt->auth->h->send_conf_req(lcp->ppp, auth_opt->auth, (uint8_t*)(opt16 + 1)); - opt16->hdr.len = 4 + n; - - return 4 + n; -} - -static int auth_recv_conf_req(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct auth_option_t *auth_opt = container_of(opt,typeof(*auth_opt),opt); - struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; - struct auth_data_t *d; - int r; - - if (list_empty(&auth_opt->auth_list)) - return LCP_OPT_REJ; - - if (!ptr) - return LCP_OPT_ACK; - - - list_for_each_entry(d, &auth_opt->auth_list, entry) { - if (d->proto == ntohs(opt16->val)) { - r = d->h->recv_conf_req(lcp->ppp, d, (uint8_t*)(opt16 + 1)); - if (r == LCP_OPT_FAIL) - return LCP_OPT_FAIL; - if (r == LCP_OPT_REJ) - break; - auth_opt->peer_auth = d; - return r; - } - } - - list_for_each_entry(d, &auth_opt->auth_list, entry) { - if (d->state != LCP_OPT_NAK) { - auth_opt->peer_auth = d; - return LCP_OPT_NAK; - } - } - - log_ppp_error("cann't negotiate authentication type\n"); - return LCP_OPT_FAIL; -} - -static int auth_recv_conf_ack(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); - - auth_opt->peer_auth = NULL; - - return 0; -} - -static int auth_recv_conf_nak(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); - struct auth_data_t *d; - - if (!auth_opt->auth) { - log_ppp_error("auth: unexcepcted configure-nak\n"); - return -1; - } - auth_opt->auth->state = LCP_OPT_NAK; - if (auth_opt->peer_auth) - auth_opt->auth = auth_opt->peer_auth; - - list_for_each_entry(d, &auth_opt->auth_list, entry) { - if (d->state != LCP_OPT_NAK) - return 0; - } - - log_ppp_error("cann't negotiate authentication type\n"); - return -1; -} - -static int auth_recv_conf_rej(struct ppp_lcp_t *lcp, struct lcp_option_t *opt, uint8_t *ptr) -{ - struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); - struct auth_data_t *d; - - if (!auth_opt->auth) { - log_ppp_error("auth: unexcepcted configure-reject\n"); - return -1; - } - - auth_opt->auth->state = LCP_OPT_NAK; - if (auth_opt->peer_auth) - auth_opt->auth = auth_opt->peer_auth; - - list_for_each_entry(d, &auth_opt->auth_list, entry) { - if (d->state != LCP_OPT_NAK) - return 0; - } - - log_ppp_error("cann't negotiate authentication type\n"); - return -1; -} - -static void auth_print(void (*print)(const char *fmt,...), struct lcp_option_t *opt, uint8_t *ptr) -{ - struct auth_option_t *auth_opt = container_of(opt, typeof(*auth_opt), opt); - struct lcp_opt16_t *opt16 = (struct lcp_opt16_t*)ptr; - struct auth_data_t *d; - - if (ptr) { - list_for_each_entry(d, &auth_opt->auth_list, entry) { - if (d->proto == ntohs(opt16->val) && (!d->h->check || d->h->check((uint8_t *)(opt16 + 1)))) - goto print_d; - } - - print("", ntohs(opt16->val)); - return; - } else if (auth_opt->auth) - d = auth_opt->auth; - else - return; - -print_d: - print("", d->h->name); -} - -static struct ppp_layer_data_t *auth_layer_init(struct ppp_t *ppp) -{ - struct auth_layer_data_t *ad = _malloc(sizeof(*ad)); - - log_ppp_debug("auth_layer_init\n"); - - memset(ad, 0, sizeof(*ad)); - - ad->ppp = ppp; - - return &ad->ld; -} - -static int auth_layer_start(struct ppp_layer_data_t *ld) -{ - struct auth_layer_data_t *ad = container_of(ld,typeof(*ad),ld); - - log_ppp_debug("auth_layer_start\n"); - - if (ad->auth_opt.auth) { - ad->auth_opt.started = 1; - ad->auth_opt.auth->h->start(ad->ppp, ad->auth_opt.auth); - } else { - log_ppp_debug("auth_layer_started\n"); - ppp_layer_started(ad->ppp, ld); - } - - return 0; -} - -static void auth_layer_finish(struct ppp_layer_data_t *ld) -{ - struct auth_layer_data_t *ad = container_of(ld, typeof(*ad), ld); - - log_ppp_debug("auth_layer_finish\n"); - - if (ad->auth_opt.auth) - ad->auth_opt.auth->h->finish(ad->ppp, ad->auth_opt.auth); - - ad->auth_opt.started = 0; - - log_ppp_debug("auth_layer_finished\n"); - ppp_layer_finished(ad->ppp, ld); -} - -static void auth_layer_free(struct ppp_layer_data_t *ld) -{ - struct auth_layer_data_t *ad = container_of(ld, typeof(*ad), ld); - - log_ppp_debug("auth_layer_free\n"); - - _free(ad); -} - -void __export ppp_auth_successed(struct ppp_t *ppp, char *username) -{ - struct auth_layer_data_t *ad = container_of(ppp_find_layer_data(ppp, &auth_layer), typeof(*ad), ld); - log_ppp_debug("auth_layer_started\n"); - ppp->username = username; - ppp_layer_started(ppp, &ad->ld); - log_ppp_info1("%s: authentication successed\n", username); - triton_event_fire(EV_PPP_AUTHORIZED, ppp); -} - -void __export ppp_auth_failed(struct ppp_t *ppp, const char *username) -{ - if (username) - log_ppp_info1("%s: authentication failed\n", username); - else - log_ppp_info1("authentication failed\n"); - ppp_terminate(ppp, TERM_AUTH_ERROR, 0); -} - -int __export ppp_auth_register_handler(struct ppp_auth_handler_t *h) -{ - list_add_tail(&h->entry, &auth_handlers); - return 0; -} - -int __export ppp_auth_restart(struct ppp_t *ppp) -{ - struct auth_layer_data_t *ad = container_of(ppp_find_layer_data(ppp, &auth_layer), typeof(*ad), ld); - log_ppp_debug("ppp_auth_restart\n"); - - if (!ad->auth_opt.auth->h->restart) - return -1; - - if (ad->auth_opt.auth->h->restart(ppp, ad->auth_opt.auth)) - return -1; - - return 0; -} - -static void __init ppp_auth_init() -{ - ppp_register_layer("auth", &auth_layer); - lcp_option_register(&auth_opt_hnd); -} - diff --git a/accel-pptpd/ppp/ppp_auth.h b/accel-pptpd/ppp/ppp_auth.h deleted file mode 100644 index 87cc742..0000000 --- a/accel-pptpd/ppp/ppp_auth.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef PPP_AUTH_H -#define PPP_AUTH_H - -#include "list.h" - -struct ppp_auth_handler_t; - -struct auth_data_t -{ - struct list_head entry; - int proto; - int state; - struct ppp_auth_handler_t *h; -}; - -struct ppp_auth_handler_t -{ - struct list_head entry; - const char *name; - struct auth_data_t* (*init)(struct ppp_t*); - int (*send_conf_req)(struct ppp_t*, struct auth_data_t*, uint8_t*); - int (*recv_conf_req)(struct ppp_t*, struct auth_data_t*, uint8_t*); - int (*start)(struct ppp_t*, struct auth_data_t*); - int (*finish)(struct ppp_t*, struct auth_data_t*); - void (*free)(struct ppp_t*,struct auth_data_t*); - int (*check)(uint8_t *); - int (*restart)(struct ppp_t*,struct auth_data_t*); -}; - -int ppp_auth_register_handler(struct ppp_auth_handler_t*); - -void ppp_auth_successed(struct ppp_t *ppp, char *username); -void ppp_auth_failed(struct ppp_t *ppp, const char *username); -int ppp_auth_restart(struct ppp_t *ppp); - -#endif - diff --git a/accel-pptpd/ppp/ppp_ccp.c b/accel-pptpd/ppp/ppp_ccp.c deleted file mode 100644 index 721dd9b..0000000 --- a/accel-pptpd/ppp/ppp_ccp.c +++ /dev/null @@ -1,759 +0,0 @@ -#include -#include -#include -#include -#include -#include "linux_ppp.h" - -#include "triton.h" - -#include "log.h" -#include "events.h" - -#include "ppp.h" -#include "ppp_ccp.h" - -#include "memdebug.h" - -struct recv_opt_t -{ - struct list_head entry; - struct ccp_opt_hdr_t *hdr; - int len; - int state; - struct ccp_option_t *lopt; -}; - -static int conf_ccp = 1; - -static struct ppp_layer_t ccp_layer; -static LIST_HEAD(option_handlers); - -static void ccp_layer_up(struct ppp_fsm_t*); -static void ccp_layer_down(struct ppp_fsm_t*); -static int send_conf_req(struct ppp_fsm_t*); -static void send_conf_ack(struct ppp_fsm_t*); -static void send_conf_nak(struct ppp_fsm_t*); -static void send_conf_rej(struct ppp_fsm_t*); -static void send_term_req(struct ppp_fsm_t *fsm); -static void send_term_ack(struct ppp_fsm_t *fsm); -static void ccp_recv(struct ppp_handler_t*); -static void ccp_recv_proto_rej(struct ppp_handler_t*); - -static void ccp_options_init(struct ppp_ccp_t *ccp) -{ - struct ccp_option_t *lopt; - struct ccp_option_handler_t *h; - - ccp->conf_req_len = sizeof(struct ccp_hdr_t); - - list_for_each_entry(h, &option_handlers, entry) { - lopt = h->init(ccp); - if (lopt) { - lopt->h = h; - list_add_tail(&lopt->entry, &ccp->options); - ccp->conf_req_len += lopt->len; - } - } -} - -static void ccp_options_free(struct ppp_ccp_t *ccp) -{ - struct ccp_option_t *lopt; - - while (!list_empty(&ccp->options)) { - lopt = list_entry(ccp->options.next, typeof(*lopt), entry); - list_del(&lopt->entry); - lopt->h->free(ccp, lopt); - } -} - -static int ccp_set_flags(int fd, int isopen, int isup) -{ - int flags; - - if (ioctl(fd, PPPIOCGFLAGS, &flags)) { - log_ppp_error("ccp: failed to get flags: %s\n", strerror(errno)); - return -1; - } - - flags &= ~(SC_CCP_OPEN | SC_CCP_UP); - flags |= (isopen ? SC_CCP_OPEN : 0) | (isup ? SC_CCP_UP : 0); - - if (ioctl(fd, PPPIOCSFLAGS, &flags)) { - log_ppp_error("ccp: failed to set flags: %s\n", strerror(errno)); - return -1; - } - - return 0; -} - -static struct ppp_layer_data_t *ccp_layer_init(struct ppp_t *ppp) -{ - struct ppp_ccp_t *ccp = _malloc(sizeof(*ccp)); - memset(ccp, 0, sizeof(*ccp)); - - log_ppp_debug("ccp_layer_init\n"); - - ccp->ppp = ppp; - ccp->fsm.ppp = ppp; - - ccp->hnd.proto = PPP_CCP; - ccp->hnd.recv = ccp_recv; - ccp->hnd.recv_proto_rej = ccp_recv_proto_rej; - - ppp_register_unit_handler(ppp, &ccp->hnd); - - INIT_LIST_HEAD(&ccp->options); - ccp_options_init(ccp); - - ccp->passive = 0; - - ccp->fsm.proto = PPP_CCP; - ppp_fsm_init(&ccp->fsm); - - ccp->fsm.layer_up = ccp_layer_up; - ccp->fsm.layer_finished = ccp_layer_down; - ccp->fsm.send_conf_req = send_conf_req; - ccp->fsm.send_conf_ack = send_conf_ack; - ccp->fsm.send_conf_nak = send_conf_nak; - ccp->fsm.send_conf_rej = send_conf_rej; - ccp->fsm.send_term_req = send_term_req; - ccp->fsm.send_term_ack = send_term_ack; - - INIT_LIST_HEAD(&ccp->ropt_list); - - return &ccp->ld; -} - -int ccp_layer_start(struct ppp_layer_data_t *ld) -{ - struct ppp_ccp_t *ccp = container_of(ld, typeof(*ccp), ld); - - log_ppp_debug("ccp_layer_start\n"); - - if (list_empty(&ccp->options) || !conf_ccp) { - ppp_layer_started(ccp->ppp, &ccp->ld); - return 0; - } - - ppp_fsm_lower_up(&ccp->fsm); - if (ppp_fsm_open(&ccp->fsm)) - return -1; - - if (ccp_set_flags(ccp->ppp->unit_fd, 1, 0)) { - ppp_fsm_close(&ccp->fsm); - return -1; - } - - return 0; -} - -void ccp_layer_finish(struct ppp_layer_data_t *ld) -{ - struct ppp_ccp_t *ccp = container_of(ld, typeof(*ccp), ld); - - log_ppp_debug("ccp_layer_finish\n"); - - ccp_set_flags(ccp->ppp->unit_fd, 0, 0); - - ccp->fsm.fsm_state = FSM_Closed; - - log_ppp_debug("ccp_layer_finished\n"); - ppp_layer_finished(ccp->ppp, &ccp->ld); -} - -void ccp_layer_free(struct ppp_layer_data_t *ld) -{ - struct ppp_ccp_t *ccp = container_of(ld, typeof(*ccp), ld); - - log_ppp_debug("ccp_layer_free\n"); - - ppp_unregister_handler(ccp->ppp, &ccp->hnd); - ccp_options_free(ccp); - ppp_fsm_free(&ccp->fsm); - - _free(ccp); -} - -static void ccp_layer_up(struct ppp_fsm_t *fsm) -{ - struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); - - log_ppp_debug("ccp_layer_started\n"); - - if (!ccp->started) { - ccp->started = 1; - if (ccp_set_flags(ccp->ppp->unit_fd, 1, 1)) { - ppp_terminate(ccp->ppp, TERM_NAS_ERROR, 0); - return; - } - ppp_layer_started(ccp->ppp, &ccp->ld); - } -} - -static void ccp_layer_down(struct ppp_fsm_t *fsm) -{ - struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); - - log_ppp_debug("ccp_layer_finished\n"); - - if (!ccp->started) - ppp_layer_started(ccp->ppp, &ccp->ld); - ccp->started = 0; - ppp_layer_finished(ccp->ppp, &ccp->ld); -} - -static void print_ropt(struct recv_opt_t *ropt) -{ - int i; - uint8_t *ptr = (uint8_t*)ropt->hdr; - - log_ppp_info2("<"); - for (i = 0; i < ropt->len; i++) { - log_ppp_info2(" %x", ptr[i]); - } - log_ppp_info2(" >"); -} - -static int send_conf_req(struct ppp_fsm_t *fsm) -{ - struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); - uint8_t *buf, *ptr; - struct ccp_hdr_t *ccp_hdr; - struct ccp_option_t *lopt; - int n; - - ccp->need_req = 0; - - if (ccp->passive) { - ccp->passive--; - return 0; - } - - buf = _malloc(ccp->conf_req_len); - ccp_hdr = (struct ccp_hdr_t*)buf; - - ccp_hdr->proto = htons(PPP_CCP); - ccp_hdr->code = CONFREQ; - ccp_hdr->id = ++ccp->fsm.id; - ccp_hdr->len = 0; - - ptr = (uint8_t*)(ccp_hdr + 1); - - if (conf_ppp_verbose) - log_ppp_info2("send [CCP ConfReq id=%x", ccp_hdr->id); - - list_for_each_entry(lopt, &ccp->options, entry) { - n = lopt->h->send_conf_req(ccp, lopt, ptr); - if (n < 0) - return -1; - if (n) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, NULL); - } - } - ptr += n; - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - ccp_hdr->len = htons(ptr - buf - 2); - ppp_unit_send(ccp->ppp, ccp_hdr, ptr - buf); - - _free(buf); - - return 0; -} - -static void send_conf_ack(struct ppp_fsm_t *fsm) -{ - struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); - struct ccp_hdr_t *hdr = (struct ccp_hdr_t*)ccp->ppp->unit_buf; - - hdr->code = CONFACK; - - if (conf_ppp_verbose) - log_ppp_info2("send [CCP ConfAck id=%x]\n", ccp->fsm.recv_id); - - ppp_unit_send(ccp->ppp,hdr,ntohs(hdr->len)+2); -} - -static void send_conf_nak(struct ppp_fsm_t *fsm) -{ - struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); - uint8_t *buf = _malloc(ccp->conf_req_len), *ptr = buf; - struct ccp_hdr_t *ccp_hdr = (struct ccp_hdr_t*)ptr; - struct recv_opt_t *ropt; - - if (conf_ppp_verbose) - log_ppp_info2("send [CCP ConfNak id=%x", ccp->fsm.recv_id); - - ccp_hdr->proto = htons(PPP_CCP); - ccp_hdr->code = CONFNAK; - ccp_hdr->id = ccp->fsm.recv_id; - ccp_hdr->len = 0; - - ptr += sizeof(*ccp_hdr); - - list_for_each_entry(ropt, &ccp->ropt_list, entry) { - if (ropt->state == CCP_OPT_NAK) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - ropt->lopt->h->print(log_ppp_info2, ropt->lopt, NULL); - } - ptr += ropt->lopt->h->send_conf_nak(ccp, ropt->lopt, ptr); - } - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - ccp_hdr->len = htons(ptr - buf - 2); - ppp_unit_send(ccp->ppp, ccp_hdr, ptr - buf); - - _free(buf); -} - -static void send_conf_rej(struct ppp_fsm_t *fsm) -{ - struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); - uint8_t *buf = _malloc(ccp->ropt_len + sizeof(struct ccp_hdr_t)), *ptr = buf; - struct ccp_hdr_t *ccp_hdr = (struct ccp_hdr_t*)ptr; - struct recv_opt_t *ropt; - - if (conf_ppp_verbose) - log_ppp_info2("send [CCP ConfRej id=%x", ccp->fsm.recv_id); - - ccp_hdr->proto = htons(PPP_CCP); - ccp_hdr->code = CONFREJ; - ccp_hdr->id = ccp->fsm.recv_id; - ccp_hdr->len = 0; - - ptr += sizeof(*ccp_hdr); - - list_for_each_entry(ropt, &ccp->ropt_list, entry) { - if (ropt->state == CCP_OPT_REJ) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - if (ropt->lopt) - ropt->lopt->h->print(log_ppp_info2, ropt->lopt, (uint8_t*)ropt->hdr); - else - print_ropt(ropt); - } - memcpy(ptr, ropt->hdr, ropt->len); - ptr += ropt->len; - } - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - ccp_hdr->len = htons(ptr - buf - 2); - ppp_unit_send(ccp->ppp, ccp_hdr, ptr-buf); - - _free(buf); -} - -static int ccp_recv_conf_req(struct ppp_ccp_t *ccp, uint8_t *data, int size) -{ - struct ccp_opt_hdr_t *hdr; - struct recv_opt_t *ropt; - struct ccp_option_t *lopt; - int r, ret = 1, ack = 0; - - ccp->need_req = 0; - ccp->ropt_len = size; - - while (size > 0) { - hdr = (struct ccp_opt_hdr_t *)data; - - ropt = _malloc(sizeof(*ropt)); - memset(ropt, 0, sizeof(*ropt)); - - if (hdr->len > size) - ropt->len = size; - else - ropt->len = hdr->len; - - ropt->hdr = hdr; - ropt->state = CCP_OPT_NONE; - list_add_tail(&ropt->entry, &ccp->ropt_list); - - data += ropt->len; - size -= ropt->len; - } - - if (conf_ppp_verbose) - log_ppp_info2("recv [CCP ConfReq id=%x", ccp->fsm.recv_id); - - list_for_each_entry(ropt, &ccp->ropt_list, entry) { - list_for_each_entry(lopt, &ccp->options, entry) { - if (lopt->id == ropt->hdr->id) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, (uint8_t*)ropt->hdr); - } - r = lopt->h->recv_conf_req(ccp, lopt, (uint8_t*)ropt->hdr); - if (ack) { - lopt->state = CCP_OPT_REJ; - ropt->state = CCP_OPT_REJ; - } else { - /*if (lopt->state == CCP_OPT_NAK && r == CCP_OPT_ACK) - ccp->need_req = 1;*/ - lopt->state = r; - ropt->state = r; - } - ropt->lopt = lopt; - if (r < ret) - ret = r; - break; - } - } - if (ropt->state == CCP_OPT_ACK || ropt->state == CCP_OPT_NAK) - ack = 1; - else if (!ropt->lopt) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - print_ropt(ropt); - } - ropt->state = CCP_OPT_REJ; - ret = CCP_OPT_REJ; - } - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - /*list_for_each_entry(lopt,&ccp->options,entry) - { - if (lopt->state==CCP_OPT_NONE) - { - r=lopt->h->recv_conf_req(ccp,lopt,NULL); - lopt->state=r; - if (rropt_list)) { - ropt = list_entry(ccp->ropt_list.next, typeof(*ropt), entry); - list_del(&ropt->entry); - _free(ropt); - } -} - -static int ccp_recv_conf_rej(struct ppp_ccp_t *ccp, uint8_t *data, int size) -{ - struct ccp_opt_hdr_t *hdr; - struct ccp_option_t *lopt; - int res = 0; - - if (conf_ppp_verbose) - log_ppp_info2("recv [CCP ConfRej id=%x", ccp->fsm.recv_id); - - if (ccp->fsm.recv_id != ccp->fsm.id) { - if (conf_ppp_verbose) - log_ppp_info2(": id mismatch ]\n"); - return 0; - } - - while (size > 0) { - hdr = (struct ccp_opt_hdr_t *)data; - - list_for_each_entry(lopt, &ccp->options, entry) { - if (lopt->id == hdr->id) { - if (!lopt->h->recv_conf_rej) - res = -1; - else if (lopt->h->recv_conf_rej(ccp, lopt, data)) - res = -1; - break; - } - } - - data += hdr->len; - size -= hdr->len; - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - return res; -} - -static int ccp_recv_conf_nak(struct ppp_ccp_t *ccp, uint8_t *data, int size) -{ - struct ccp_opt_hdr_t *hdr; - struct ccp_option_t *lopt; - int res = 0; - - if (conf_ppp_verbose) - log_ppp_info2("recv [CCP ConfNak id=%x", ccp->fsm.recv_id); - - if (ccp->fsm.recv_id != ccp->fsm.id) { - if (conf_ppp_verbose) - log_ppp_info2(": id mismatch ]\n"); - return 0; - } - - while (size > 0) { - hdr = (struct ccp_opt_hdr_t *)data; - - list_for_each_entry(lopt, &ccp->options, entry) { - if (lopt->id == hdr->id) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, data); - } - if (lopt->h->recv_conf_nak && lopt->h->recv_conf_nak(ccp, lopt, data)) - res = -1; - //lopt->state = CCP_OPT_NAK; - //ccp->need_req = 1; - break; - } - } - - data += hdr->len; - size -= hdr->len; - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - return res; -} - -static int ccp_recv_conf_ack(struct ppp_ccp_t *ccp, uint8_t *data, int size) -{ - struct ccp_opt_hdr_t *hdr; - struct ccp_option_t *lopt; - int res = 0; - - if (conf_ppp_verbose) - log_ppp_info2("recv [CCP ConfAck id=%x", ccp->fsm.recv_id); - - if (ccp->fsm.recv_id != ccp->fsm.id) { - if (conf_ppp_verbose) - log_ppp_info2(": id mismatch ]\n"); - return 0; - } - - while (size > 0) { - hdr = (struct ccp_opt_hdr_t *)data; - - list_for_each_entry(lopt, &ccp->options, entry) { - if (lopt->id == hdr->id) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2,lopt,data); - } - if (!lopt->h->recv_conf_ack) - break; - if (lopt->h->recv_conf_ack(ccp, lopt, data)) - res = -1; - break; - } - } - - data += hdr->len; - size -= hdr->len; - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - return res; -} - -static void send_term_req(struct ppp_fsm_t *fsm) -{ - struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); - struct ccp_hdr_t hdr = { - .proto = htons(PPP_CCP), - .code = TERMREQ, - .id = ++ccp->fsm.id, - .len = htons(4), - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [CCP TermReq id=%i]\n", hdr.id); - - ppp_chan_send(ccp->ppp, &hdr, 6); -} - -static void send_term_ack(struct ppp_fsm_t *fsm) -{ - struct ppp_ccp_t *ccp = container_of(fsm, typeof(*ccp), fsm); - struct ccp_hdr_t hdr = { - .proto = htons(PPP_CCP), - .code = TERMACK, - .id = ccp->fsm.recv_id, - .len = htons(4), - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [CCP TermAck id=%i]\n", hdr.id); - - ppp_chan_send(ccp->ppp, &hdr, 6); -} - -static void ccp_recv(struct ppp_handler_t*h) -{ - struct ccp_hdr_t *hdr; - struct ppp_ccp_t *ccp = container_of(h, typeof(*ccp), hnd); - int r; - - if (ccp->fsm.fsm_state == FSM_Initial || ccp->fsm.fsm_state == FSM_Closed || ccp->ppp->terminating) { - if (conf_ppp_verbose) - log_ppp_warn("CCP: discarding packet\n"); - if (ccp->fsm.fsm_state == FSM_Closed || !conf_ccp) - lcp_send_proto_rej(ccp->ppp, PPP_CCP); - return; - } - - if (ccp->ppp->unit_buf_size < PPP_HEADERLEN + 2) { - log_ppp_warn("CCP: short packet received\n"); - return; - } - - hdr = (struct ccp_hdr_t *)ccp->ppp->unit_buf; - if (ntohs(hdr->len) < PPP_HEADERLEN) { - log_ppp_warn("CCP: short packet received\n"); - return; - } - - ccp->fsm.recv_id = hdr->id; - switch(hdr->code) { - case CONFREQ: - r = ccp_recv_conf_req(ccp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); - switch(r) { - case CCP_OPT_ACK: - ppp_fsm_recv_conf_req_ack(&ccp->fsm); - break; - case CCP_OPT_NAK: - ppp_fsm_recv_conf_req_nak(&ccp->fsm); - break; - case CCP_OPT_REJ: - ppp_fsm_recv_conf_req_rej(&ccp->fsm); - break; - } - ccp_free_conf_req(ccp); - - if (r == CCP_OPT_ACK && ccp->passive) { - ccp->passive = 0; - send_conf_req(&ccp->fsm); - } - if (r == CCP_OPT_FAIL) - ppp_terminate(ccp->ppp, TERM_USER_ERROR, 0); - break; - case CONFACK: - if (ccp_recv_conf_ack(ccp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) - ppp_terminate(ccp->ppp, TERM_USER_ERROR, 0); - else { - ppp_fsm_recv_conf_ack(&ccp->fsm); - if (ccp->need_req) - send_conf_req(&ccp->fsm); - } - break; - case CONFNAK: - ccp_recv_conf_nak(ccp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); - ppp_fsm_recv_conf_rej(&ccp->fsm); - break; - case CONFREJ: - if (ccp_recv_conf_rej(ccp, (uint8_t*)(hdr + 1),ntohs(hdr->len) - PPP_HDRLEN)) - ppp_terminate(ccp->ppp, TERM_USER_ERROR, 0); - else - ppp_fsm_recv_conf_rej(&ccp->fsm); - break; - case TERMREQ: - if (conf_ppp_verbose) - log_ppp_info2("recv [CCP TermReq id=%x]\n", hdr->id); - ppp_fsm_recv_term_req(&ccp->fsm); - ppp_fsm_close(&ccp->fsm); - break; - case TERMACK: - if (conf_ppp_verbose) - log_ppp_info2("recv [CCP TermAck id=%x]\n", hdr->id); - ppp_fsm_recv_term_ack(&ccp->fsm); - break; - case CODEREJ: - if (conf_ppp_verbose) - log_ppp_info2("recv [CCP CodeRej id=%x]\n", hdr->id); - ppp_fsm_recv_code_rej_bad(&ccp->fsm); - break; - default: - ppp_fsm_recv_unk(&ccp->fsm); - break; - } -} - -static void ccp_recv_proto_rej(struct ppp_handler_t *h) -{ - struct ppp_ccp_t *ccp = container_of(h, typeof(*ccp), hnd); - - if (ccp->fsm.fsm_state == FSM_Initial || ccp->fsm.fsm_state == FSM_Closed) - return; - - ppp_fsm_lower_down(&ccp->fsm); - ppp_fsm_close(&ccp->fsm); -} - -int ccp_option_register(struct ccp_option_handler_t *h) -{ - /*struct ccp_option_drv_t *p; - - list_for_each_entry(p,option_drv_list,entry) - if (p->id==h->id) - return -1;*/ - - list_add_tail(&h->entry,&option_handlers); - - return 0; -} - -struct ccp_option_t *ccp_find_option(struct ppp_t *ppp, struct ccp_option_handler_t *h) -{ - struct ppp_ccp_t *ccp = container_of(ppp_find_layer_data(ppp, &ccp_layer), typeof(*ccp), ld); - struct ccp_option_t *opt; - - list_for_each_entry(opt, &ccp->options, entry) - if (opt->h == h) - return opt; - - log_emerg("ccp: BUG: option not found\n"); - abort(); -} - -static struct ppp_layer_t ccp_layer= -{ - .init = ccp_layer_init, - .start = ccp_layer_start, - .finish = ccp_layer_finish, - .free = ccp_layer_free, -}; - -static void load_config(void) -{ - const char *opt; - - opt = conf_get_opt("ppp", "ccp"); - if (opt && atoi(opt) >= 0) - conf_ccp = atoi(opt); -} - -static void __init ccp_init(void) -{ - ppp_register_layer("ccp", &ccp_layer); - - load_config(); - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); -} - diff --git a/accel-pptpd/ppp/ppp_ccp.h b/accel-pptpd/ppp/ppp_ccp.h deleted file mode 100644 index 2c2dc6d..0000000 --- a/accel-pptpd/ppp/ppp_ccp.h +++ /dev/null @@ -1,96 +0,0 @@ -#ifndef PPP_CCP_H -#define PPP_CCP_H - -#include - -#include "triton.h" -#include "ppp_fsm.h" -/* - * Options. - */ - -#define CI_MPPE 18 /* MPPE */ - -struct ccp_hdr_t -{ - uint16_t proto; - uint8_t code; - uint8_t id; - uint16_t len; -} __attribute__((packed)); -struct ccp_opt_hdr_t -{ - uint8_t id; - uint8_t len; -} __attribute__((packed)); -struct ccp_opt8_t -{ - struct ccp_opt_hdr_t hdr; - uint8_t val; -} __attribute__((packed)); -struct ccp_opt16_t -{ - struct ccp_opt_hdr_t hdr; - uint16_t val; -} __attribute__((packed)); -struct ccp_opt32_t -{ - struct ccp_opt_hdr_t hdr; - uint32_t val; -} __attribute__((packed)); - -#define CCP_OPT_NONE 0 -#define CCP_OPT_ACK 1 -#define CCP_OPT_NAK -1 -#define CCP_OPT_REJ -2 -#define CCP_OPT_FAIL -3 - -struct ppp_ccp_t; -struct ccp_option_handler_t; - -struct ccp_option_t -{ - struct list_head entry; - int id; - int len; - int state; - struct ccp_option_handler_t *h; -}; - -struct ccp_option_handler_t -{ - struct list_head entry; - struct ccp_option_t* (*init)(struct ppp_ccp_t*); - int (*send_conf_req)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); - int (*send_conf_rej)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); - int (*send_conf_nak)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); - int (*recv_conf_req)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); - int (*recv_conf_rej)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); - int (*recv_conf_nak)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); - int (*recv_conf_ack)(struct ppp_ccp_t*,struct ccp_option_t*,uint8_t*); - void (*free)(struct ppp_ccp_t*,struct ccp_option_t*); - void (*print)(void (*print)(const char *fmt,...), struct ccp_option_t*,uint8_t*); -}; - -struct ppp_ccp_t -{ - struct ppp_layer_data_t ld; - struct ppp_handler_t hnd; - struct ppp_fsm_t fsm; - struct ppp_t *ppp; - struct list_head options; - - struct list_head ropt_list; // last received ConfReq - int ropt_len; - - int conf_req_len; - int passive; - int started:1; - int need_req:1; -}; - -int ccp_option_register(struct ccp_option_handler_t *h); -struct ccp_option_t *ccp_find_option(struct ppp_t *ppp, struct ccp_option_handler_t *h); - -#endif - diff --git a/accel-pptpd/ppp/ppp_fsm.c b/accel-pptpd/ppp/ppp_fsm.c deleted file mode 100644 index c6bc430..0000000 --- a/accel-pptpd/ppp/ppp_fsm.c +++ /dev/null @@ -1,544 +0,0 @@ -#include -#include - -#include "triton.h" - -#include "ppp.h" -#include "ppp_fsm.h" -#include "ppp_lcp.h" -#include "log.h" -#include "events.h" - -#include "memdebug.h" - -static int conf_max_terminate = 2; -static int conf_max_configure = 10; -static int conf_max_failure = 10; -static int conf_timeout = 5; - -void send_term_req(struct ppp_fsm_t *layer); -void send_term_ack(struct ppp_fsm_t *layer); -void send_echo_reply(struct ppp_fsm_t *layer); - -static void init_req_counter(struct ppp_fsm_t *layer,int timeout); -static void zero_req_counter(struct ppp_fsm_t *layer); -static void restart_timer_func(struct triton_timer_t *t); -static void stop_timer(struct ppp_fsm_t *fsm); - -void ppp_fsm_init(struct ppp_fsm_t *layer) -{ - layer->fsm_state = FSM_Initial; - layer->restart_timer.expire = restart_timer_func; - layer->restart_timer.period = conf_timeout * 1000; - layer->restart_counter = 0; - - layer->max_terminate = conf_max_terminate; - layer->max_configure = conf_max_configure; - layer->max_failure = conf_max_failure; - layer->timeout = conf_timeout; -} -void ppp_fsm_free(struct ppp_fsm_t *layer) -{ - stop_timer(layer); -} - -int ppp_fsm_lower_up(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Initial: - layer->fsm_state=FSM_Closed; - break; - case FSM_Starting: - //if (layer->init_req_cnt) layer->init_req_cnt(layer); - init_req_counter(layer,layer->max_configure); - --layer->restart_counter; - if (layer->send_conf_req) - if (layer->send_conf_req(layer)) - return -1; - layer->fsm_state=FSM_Req_Sent; - break; - default: - break; - } - return 0; -} - -void ppp_fsm_lower_down(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Closed: - case FSM_Closing: - layer->fsm_state=FSM_Initial; - break; - case FSM_Stopped: - if (layer->layer_started) layer->layer_started(layer); - layer->fsm_state=FSM_Starting; - break; - case FSM_Stopping: - case FSM_Req_Sent: - case FSM_Ack_Rcvd: - case FSM_Ack_Sent: - layer->fsm_state=FSM_Starting; - break; - case FSM_Opened: - if (layer->layer_down) layer->layer_down(layer); - layer->fsm_state=FSM_Starting; - break; - default: - break; - } -} - -int ppp_fsm_open(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Initial: - if (layer->layer_started) layer->layer_started(layer); - layer->fsm_state=FSM_Starting; - break; - case FSM_Starting: - break; - case FSM_Closed: - //if (layer->init_req_cnt) layer->init_req_cnt(layer); - init_req_counter(layer,layer->max_configure); - --layer->restart_counter; - if (layer->send_conf_req) - if (layer->send_conf_req(layer)) - return -1; - layer->fsm_state=FSM_Req_Sent; - break; - case FSM_Closing: - case FSM_Stopping: - case FSM_Stopped: - case FSM_Opened: - ppp_fsm_lower_down(layer); - ppp_fsm_lower_up(layer); - break; - default: - break; - } - return 0; -} - -void ppp_fsm_close(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Starting: - stop_timer(layer); - layer->fsm_state=FSM_Initial; - if (layer->layer_finished) layer->layer_finished(layer); - break; - case FSM_Stopped: - layer->fsm_state=FSM_Closed; - stop_timer(layer); - break; - case FSM_Stopping: - layer->fsm_state=FSM_Closing; - break; - case FSM_Opened: - if (layer->layer_down) layer->layer_down(layer); - case FSM_Req_Sent: - case FSM_Ack_Rcvd: - case FSM_Ack_Sent: - //if (layer->init_req_cnt) layer->init_req_cnt(layer); - init_req_counter(layer,layer->max_terminate); - layer->send_term_req(layer); - layer->fsm_state=FSM_Closing; - break; - default: - break; - } -} - -void ppp_fsm_timeout0(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Closing: - case FSM_Stopping: - --layer->restart_counter; - layer->send_term_req(layer); - break; - case FSM_Ack_Rcvd: - layer->fsm_state=FSM_Req_Sent; - case FSM_Req_Sent: - case FSM_Ack_Sent: - --layer->restart_counter; - --layer->id; - if (layer->send_conf_req) layer->send_conf_req(layer); - break; - default: - break; - } -} - -void ppp_fsm_timeout1(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Closing: - stop_timer(layer); - layer->fsm_state=FSM_Closed; - if (layer->layer_finished) layer->layer_finished(layer); - break; - case FSM_Stopping: - stop_timer(layer); - layer->fsm_state=FSM_Stopped; - if (layer->layer_finished) layer->layer_finished(layer); - break; - case FSM_Ack_Rcvd: - case FSM_Req_Sent: - case FSM_Ack_Sent: - stop_timer(layer); - layer->fsm_state=FSM_Stopped; - if (layer->layer_finished) layer->layer_finished(layer); - break; - default: - break; - } -} - -void ppp_fsm_recv_conf_req_ack(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Closed: - layer->send_term_ack(layer); - break; - case FSM_Stopped: - //if (layer->init_req_cnt) layer->init_req_cnt(layer); - init_req_counter(layer,layer->max_configure); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - case FSM_Req_Sent: - case FSM_Ack_Sent: - if (layer->send_conf_ack) layer->send_conf_ack(layer); - layer->fsm_state=FSM_Ack_Sent; - break; - case FSM_Ack_Rcvd: - if (layer->send_conf_ack) layer->send_conf_ack(layer); - stop_timer(layer); - if (layer->layer_up) layer->layer_up(layer); - layer->fsm_state=FSM_Opened; - break; - case FSM_Opened: - if (layer->layer_down) layer->layer_down(layer); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - if (layer->send_conf_ack) layer->send_conf_ack(layer); - layer->fsm_state=FSM_Ack_Sent; - break; - default: - break; - } -} - -void ppp_fsm_recv_conf_req_nak(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Closed: - layer->send_term_ack(layer); - break; - case FSM_Stopped: - //if (layer->init_req_cnt) layer->init_req_cnt(layer); - init_req_counter(layer,layer->max_configure); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - case FSM_Ack_Sent: - if (layer->send_conf_nak) layer->send_conf_nak(layer); - layer->fsm_state=FSM_Req_Sent; - break; - case FSM_Req_Sent: - case FSM_Ack_Rcvd: - if (++layer->conf_failure == layer->max_failure) { - if (layer->layer_finished) layer->layer_finished(layer); - return; - } - if (layer->send_conf_nak) layer->send_conf_nak(layer); - break; - case FSM_Opened: - if (layer->layer_down) layer->layer_down(layer); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - if (layer->send_conf_nak) layer->send_conf_nak(layer); - layer->fsm_state=FSM_Req_Sent; - break; - default: - break; - } -} - -void ppp_fsm_recv_conf_req_rej(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Closed: - layer->send_term_ack(layer); - break; - case FSM_Stopped: - //if (layer->init_req_cnt) layer->init_req_cnt(layer); - init_req_counter(layer,layer->max_configure); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - case FSM_Ack_Sent: - if (++layer->conf_failure == layer->max_failure) { - if (layer->layer_down) layer->layer_down(layer); - return; - } - if (layer->send_conf_rej) layer->send_conf_rej(layer); - layer->fsm_state=FSM_Req_Sent; - break; - case FSM_Req_Sent: - case FSM_Ack_Rcvd: - if (++layer->conf_failure == layer->max_failure) { - if (layer->layer_finished) layer->layer_finished(layer); - return; - } - if (layer->send_conf_rej) layer->send_conf_rej(layer); - break; - case FSM_Opened: - if (layer->layer_down) layer->layer_down(layer); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - if (layer->send_conf_rej) layer->send_conf_rej(layer); - layer->fsm_state=FSM_Req_Sent; - break; - default: - break; - } -} - -void ppp_fsm_recv_conf_ack(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Closed: - case FSM_Stopped: - layer->send_term_ack(layer); - break; - case FSM_Req_Sent: - //if (layer->init_req_cnt) layer->init_req_cnt(layer); - init_req_counter(layer,layer->max_configure); - layer->fsm_state=FSM_Ack_Rcvd; - break; - case FSM_Ack_Rcvd: - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - layer->fsm_state=FSM_Req_Sent; - break; - case FSM_Ack_Sent: - //if (layer->init_req_cnt) layer->init_req_cnt(layer); - //init_req_counter(layer,layer->max_configure); - //tlu - stop_timer(layer); - if (layer->layer_up) layer->layer_up(layer); - layer->fsm_state=FSM_Opened; - break; - case FSM_Opened: - if (layer->layer_down) layer->layer_down(layer); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - layer->fsm_state=FSM_Req_Sent; - default: - break; - } -} - -void ppp_fsm_recv_conf_rej(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Closed: - case FSM_Stopped: - layer->send_term_ack(layer); - break; - case FSM_Req_Sent: - if (++layer->conf_failure == layer->max_failure) { - if (layer->layer_down) layer->layer_down(layer); - return; - } - //if (layer->init_req_cnt) layer->init_req_cnt(layer); - init_req_counter(layer,layer->max_failure); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - break; - case FSM_Ack_Rcvd: - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - layer->fsm_state=FSM_Req_Sent; - break; - case FSM_Ack_Sent: - //if (layer->init_req_cnt) layer->init_req_cnt(layer); - init_req_counter(layer,layer->max_configure); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - break; - case FSM_Opened: - if (layer->layer_down) layer->layer_down(layer); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - layer->fsm_state=FSM_Req_Sent; - break; - default: - break; - } -} - -void ppp_fsm_recv_term_req(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Opened: - if (layer->layer_down) layer->layer_down(layer); - //send_term_req(layer); - layer->send_term_ack(layer); - //if (layer->zero_req_cnt) layer->zero_req_cnt(layer); - zero_req_counter(layer); - layer->fsm_state=FSM_Stopping; - break; - case FSM_Req_Sent: - case FSM_Ack_Rcvd: - case FSM_Ack_Sent: - layer->send_term_ack(layer); - layer->fsm_state=FSM_Req_Sent; - break; - default: - layer->send_term_ack(layer); - break; - } -} - -void ppp_fsm_recv_term_ack(struct ppp_fsm_t *layer) -{ - stop_timer(layer); - switch(layer->fsm_state) - { - case FSM_Closing: - layer->fsm_state=FSM_Closed; - if (layer->layer_finished) layer->layer_finished(layer); - break; - case FSM_Stopping: - layer->fsm_state=FSM_Stopped; - if (layer->layer_finished) layer->layer_finished(layer); - break; - case FSM_Ack_Rcvd: - layer->fsm_state=FSM_Req_Sent; - break; - case FSM_Opened: - if (layer->layer_down) layer->layer_down(layer); - --layer->restart_counter; - if (layer->send_conf_req) layer->send_conf_req(layer); - layer->fsm_state=FSM_Req_Sent; - break; - default: - break; - } -} - -void ppp_fsm_recv_unk(struct ppp_fsm_t *layer) -{ - if (layer->send_code_rej) layer->send_code_rej(layer); -} - -void ppp_fsm_recv_code_rej_perm(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Ack_Rcvd: - layer->fsm_state=FSM_Req_Sent; - break; - default: - break; - } -} - -void ppp_fsm_recv_code_rej_bad(struct ppp_fsm_t *layer) -{ - switch(layer->fsm_state) - { - case FSM_Opened: - if (layer->layer_down) layer->layer_down(layer); - --layer->restart_counter; - layer->send_term_req(layer); - layer->fsm_state=FSM_Stopping; - break; - case FSM_Closing: - layer->fsm_state=FSM_Closed; - if (layer->layer_finished) layer->layer_finished(layer); - break; - case FSM_Stopping: - case FSM_Req_Sent: - case FSM_Ack_Rcvd: - case FSM_Ack_Sent: - layer->fsm_state=FSM_Stopped; - if (layer->layer_finished) layer->layer_finished(layer); - break; - default: - break; - } -} - -static void stop_timer(struct ppp_fsm_t *fsm) -{ - if (fsm->restart_timer.tpd) - triton_timer_del(&fsm->restart_timer); -} -static void init_req_counter(struct ppp_fsm_t *layer,int timeout) -{ - layer->restart_counter = timeout; - - if (!layer->restart_timer.tpd) - triton_timer_add(layer->ppp->ctrl->ctx, &layer->restart_timer, 0); -} -static void zero_req_counter(struct ppp_fsm_t *layer) -{ - layer->restart_counter=0; - - if (!layer->restart_timer.tpd) - triton_timer_add(layer->ppp->ctrl->ctx, &layer->restart_timer, 0); -} - -static void restart_timer_func(struct triton_timer_t *t) -{ - struct ppp_fsm_t *layer = container_of(t, typeof(*layer), restart_timer); - - log_ppp_debug("fsm timeout\n"); - - if (layer->restart_counter>0) - ppp_fsm_timeout0(layer); - else - ppp_fsm_timeout1(layer); -} - -static void load_config(void) -{ - char *opt; - - opt = conf_get_opt("ppp", "max-terminate"); - if (opt && atoi(opt) > 0) - conf_max_terminate = atoi(opt); - - opt = conf_get_opt("ppp", "max-configure"); - if (opt && atoi(opt) > 0) - conf_max_configure = atoi(opt); - - opt = conf_get_opt("ppp", "max-failure"); - if (opt && atoi(opt) > 0) - conf_max_failure = atoi(opt); - - opt = conf_get_opt("ppp", "timeout"); - if (opt && atoi(opt) > 0) - conf_timeout = atoi(opt); -} - -void __init fsm_init(void) -{ - load_config(); - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); -} - diff --git a/accel-pptpd/ppp/ppp_fsm.h b/accel-pptpd/ppp/ppp_fsm.h deleted file mode 100644 index 6010240..0000000 --- a/accel-pptpd/ppp/ppp_fsm.h +++ /dev/null @@ -1,72 +0,0 @@ -#ifndef PPP_FSM_H -#define PPP_FSM_H - -typedef enum {FSM_Initial=0,FSM_Starting,FSM_Closed,FSM_Stopped,FSM_Closing,FSM_Stopping,FSM_Req_Sent,FSM_Ack_Rcvd,FSM_Ack_Sent,FSM_Opened} FSM_STATE; -/* - * CP (LCP, IPCP, etc.) codes. - */ -#define CONFREQ 1 /* Configuration Request */ -#define CONFACK 2 /* Configuration Ack */ -#define CONFNAK 3 /* Configuration Nak */ -#define CONFREJ 4 /* Configuration Reject */ -#define TERMREQ 5 /* Termination Request */ -#define TERMACK 6 /* Termination Ack */ -#define CODEREJ 7 /* Code Reject */ -#define PROTOREJ 8 /* Code Reject */ -#define ECHOREQ 9 /* Echo Request */ -#define ECHOREP 10 /* Echo Reply */ -#define IDENT 12 /* Identification */ - -struct ppp_t; - -struct ppp_fsm_t -{ - struct ppp_t *ppp; - FSM_STATE fsm_state; - uint16_t proto; - - struct triton_timer_t restart_timer; - int restart_counter; - int max_terminate; - int max_configure; - int max_failure; - int timeout; - int conf_failure; - - int id; - int recv_id; - - //fsm handling - void (*layer_up)(struct ppp_fsm_t*); - void (*layer_down)(struct ppp_fsm_t*); - void (*layer_started)(struct ppp_fsm_t*); - void (*layer_finished)(struct ppp_fsm_t*); - int (*send_conf_req)(struct ppp_fsm_t*); - void (*send_conf_ack)(struct ppp_fsm_t*); - void (*send_conf_nak)(struct ppp_fsm_t*); - void (*send_conf_rej)(struct ppp_fsm_t*); - void (*send_code_rej)(struct ppp_fsm_t*); - void (*send_term_req)(struct ppp_fsm_t*); - void (*send_term_ack)(struct ppp_fsm_t*); -}; - -void ppp_fsm_init(struct ppp_fsm_t*); -void ppp_fsm_free(struct ppp_fsm_t*); - -int ppp_fsm_lower_up(struct ppp_fsm_t*); -void ppp_fsm_lower_down(struct ppp_fsm_t*); -int ppp_fsm_open(struct ppp_fsm_t*); -void ppp_fsm_close(struct ppp_fsm_t*); -void ppp_fsm_timeout0(struct ppp_fsm_t *layer); -void ppp_fsm_timeout1(struct ppp_fsm_t *layer); -void ppp_fsm_recv_conf_req_ack(struct ppp_fsm_t *layer); -void ppp_fsm_recv_conf_req_nak(struct ppp_fsm_t *layer); -void ppp_fsm_recv_conf_req_rej(struct ppp_fsm_t *layer); -void ppp_fsm_recv_conf_ack(struct ppp_fsm_t *layer); -void ppp_fsm_recv_conf_rej(struct ppp_fsm_t *layer); -void ppp_fsm_recv_term_req(struct ppp_fsm_t *layer); -void ppp_fsm_recv_term_ack(struct ppp_fsm_t *layer); -void ppp_fsm_recv_unk(struct ppp_fsm_t *layer); -void ppp_fsm_recv_code_rej_bad(struct ppp_fsm_t *layer); - -#endif diff --git a/accel-pptpd/ppp/ppp_ipcp.c b/accel-pptpd/ppp/ppp_ipcp.c deleted file mode 100644 index 7cdcdbc..0000000 --- a/accel-pptpd/ppp/ppp_ipcp.c +++ /dev/null @@ -1,665 +0,0 @@ -#include -#include -#include -#include -#include "linux_ppp.h" - -#include "triton.h" - -#include "log.h" - -#include "ppp.h" -#include "ppp_ipcp.h" - -#include "memdebug.h" - -struct recv_opt_t -{ - struct list_head entry; - struct ipcp_opt_hdr_t *hdr; - int len; - int state; - struct ipcp_option_t *lopt; -}; - -static LIST_HEAD(option_handlers); - -static void ipcp_layer_up(struct ppp_fsm_t*); -static void ipcp_layer_down(struct ppp_fsm_t*); -static int send_conf_req(struct ppp_fsm_t*); -static void send_conf_ack(struct ppp_fsm_t*); -static void send_conf_nak(struct ppp_fsm_t*); -static void send_conf_rej(struct ppp_fsm_t*); -static void ipcp_recv(struct ppp_handler_t*); -static void send_term_req(struct ppp_fsm_t *fsm); -static void send_term_ack(struct ppp_fsm_t *fsm); - -static void ipcp_options_init(struct ppp_ipcp_t *ipcp) -{ - struct ipcp_option_t *lopt; - struct ipcp_option_handler_t *h; - - ipcp->conf_req_len = sizeof(struct ipcp_hdr_t); - - list_for_each_entry(h,&option_handlers,entry) { - lopt = h->init(ipcp); - if (lopt) { - lopt->h = h; - list_add_tail(&lopt->entry, &ipcp->options); - ipcp->conf_req_len += lopt->len; - } - } -} - -static void ipcp_options_free(struct ppp_ipcp_t *ipcp) -{ - struct ipcp_option_t *lopt; - - while (!list_empty(&ipcp->options)) { - lopt = list_entry(ipcp->options.next, typeof(*lopt), entry); - list_del(&lopt->entry); - lopt->h->free(ipcp, lopt); - } -} - -static struct ppp_layer_data_t *ipcp_layer_init(struct ppp_t *ppp) -{ - struct ppp_ipcp_t *ipcp = _malloc(sizeof(*ipcp)); - memset(ipcp, 0, sizeof(*ipcp)); - - log_ppp_debug("ipcp_layer_init\n"); - - ipcp->ppp = ppp; - ipcp->fsm.ppp = ppp; - - ipcp->hnd.proto = PPP_IPCP; - ipcp->hnd.recv = ipcp_recv; - - ppp_register_unit_handler(ppp, &ipcp->hnd); - - ipcp->fsm.proto = PPP_IPCP; - ppp_fsm_init(&ipcp->fsm); - - ipcp->fsm.layer_up = ipcp_layer_up; - ipcp->fsm.layer_finished = ipcp_layer_down; - ipcp->fsm.send_conf_req = send_conf_req; - ipcp->fsm.send_conf_ack = send_conf_ack; - ipcp->fsm.send_conf_nak = send_conf_nak; - ipcp->fsm.send_conf_rej = send_conf_rej; - ipcp->fsm.send_term_req = send_term_req; - ipcp->fsm.send_term_ack = send_term_ack; - - INIT_LIST_HEAD(&ipcp->options); - INIT_LIST_HEAD(&ipcp->ropt_list); - - return &ipcp->ld; -} - -int ipcp_layer_start(struct ppp_layer_data_t *ld) -{ - struct ppp_ipcp_t *ipcp = container_of(ld, typeof(*ipcp), ld); - - log_ppp_debug("ipcp_layer_start\n"); - - ipcp_options_init(ipcp); - ppp_fsm_lower_up(&ipcp->fsm); - if (ppp_fsm_open(&ipcp->fsm)) - return -1; - - return 0; -} - -void ipcp_layer_finish(struct ppp_layer_data_t *ld) -{ - struct ppp_ipcp_t *ipcp = container_of(ld, typeof(*ipcp), ld); - - log_ppp_debug("ipcp_layer_finish\n"); - - ipcp->fsm.fsm_state = FSM_Closed; - - log_ppp_debug("ipcp_layer_finished\n"); - ppp_layer_finished(ipcp->ppp, &ipcp->ld); -} - -void ipcp_layer_free(struct ppp_layer_data_t *ld) -{ - struct ppp_ipcp_t *ipcp = container_of(ld, typeof(*ipcp), ld); - - log_ppp_debug("ipcp_layer_free\n"); - - ppp_unregister_handler(ipcp->ppp, &ipcp->hnd); - ipcp_options_free(ipcp); - ppp_fsm_free(&ipcp->fsm); - - _free(ipcp); -} - -static void ipcp_layer_up(struct ppp_fsm_t *fsm) -{ - struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); - - log_ppp_debug("ipcp_layer_started\n"); - - if (!ipcp->started) { - ipcp->started = 1; - ppp_layer_started(ipcp->ppp, &ipcp->ld); - } -} - -static void ipcp_layer_down(struct ppp_fsm_t *fsm) -{ - struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); - - log_ppp_debug("ipcp_layer_finished\n"); - - if (ipcp->started) { - ipcp->started = 0; - ppp_layer_finished(ipcp->ppp, &ipcp->ld); - } else - ppp_terminate(ipcp->ppp, TERM_NAS_ERROR, 0); -} - -static void print_ropt(struct recv_opt_t *ropt) -{ - int i; - uint8_t *ptr = (uint8_t*)ropt->hdr; - - log_ppp_info2("<"); - for (i = 0; i < ropt->len; i++) { - log_ppp_info2(" %x", ptr[i]); - } - log_ppp_info2(" >"); -} - -static int send_conf_req(struct ppp_fsm_t *fsm) -{ - struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); - uint8_t *buf = _malloc(ipcp->conf_req_len), *ptr = buf; - struct ipcp_hdr_t *ipcp_hdr = (struct ipcp_hdr_t*)ptr; - struct ipcp_option_t *lopt; - int n; - - ipcp_hdr->proto = htons(PPP_IPCP); - ipcp_hdr->code = CONFREQ; - ipcp_hdr->id = ++ipcp->fsm.id; - ipcp_hdr->len = 0; - - ptr += sizeof(*ipcp_hdr); - - list_for_each_entry(lopt, &ipcp->options, entry) { - n = lopt->h->send_conf_req(ipcp, lopt, ptr); - if (n < 0) - return -1; - if (n) { - ptr += n; - lopt->print = 1; - } else - lopt->print = 0; - } - - if (conf_ppp_verbose) { - log_ppp_info2("send [IPCP ConfReq id=%x", ipcp_hdr->id); - list_for_each_entry(lopt,&ipcp->options,entry) { - if (lopt->print) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, NULL); - } - } - log_ppp_info2("]\n"); - } - - ipcp_hdr->len = htons(ptr - buf - 2); - ppp_unit_send(ipcp->ppp, ipcp_hdr, ptr - buf); - - _free(buf); - - return 0; -} - -static void send_conf_ack(struct ppp_fsm_t *fsm) -{ - struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); - struct ipcp_hdr_t *hdr = (struct ipcp_hdr_t*)ipcp->ppp->unit_buf; - - hdr->code = CONFACK; - - if (conf_ppp_verbose) - log_ppp_info2("send [IPCP ConfAck id=%x]\n", ipcp->fsm.recv_id); - - ppp_unit_send(ipcp->ppp, hdr, ntohs(hdr->len) + 2); -} - -static void send_conf_nak(struct ppp_fsm_t *fsm) -{ - struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); - uint8_t *buf = _malloc(ipcp->conf_req_len), *ptr = buf; - struct ipcp_hdr_t *ipcp_hdr = (struct ipcp_hdr_t*)ptr; - struct recv_opt_t *ropt; - - if (conf_ppp_verbose) - log_ppp_info2("send [IPCP ConfNak id=%x", ipcp->fsm.recv_id); - - ipcp_hdr->proto = htons(PPP_IPCP); - ipcp_hdr->code = CONFNAK; - ipcp_hdr->id = ipcp->fsm.recv_id; - ipcp_hdr->len = 0; - - ptr += sizeof(*ipcp_hdr); - - list_for_each_entry(ropt, &ipcp->ropt_list, entry) { - if (ropt->state == IPCP_OPT_NAK) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - ropt->lopt->h->print(log_ppp_info2, ropt->lopt, NULL); - } - ptr += ropt->lopt->h->send_conf_nak(ipcp, ropt->lopt, ptr); - } - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - ipcp_hdr->len = htons(ptr-buf-2); - ppp_unit_send(ipcp->ppp, ipcp_hdr, ptr - buf); - - _free(buf); -} - -static void send_conf_rej(struct ppp_fsm_t *fsm) -{ - struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); - uint8_t *buf = _malloc(ipcp->ropt_len + sizeof(struct ipcp_hdr_t)), *ptr = buf; - struct ipcp_hdr_t *ipcp_hdr = (struct ipcp_hdr_t*)ptr; - struct recv_opt_t *ropt; - - if (conf_ppp_verbose) - log_ppp_info2("send [IPCP ConfRej id=%x", ipcp->fsm.recv_id); - - ipcp_hdr->proto = htons(PPP_IPCP); - ipcp_hdr->code = CONFREJ; - ipcp_hdr->id = ipcp->fsm.recv_id; - ipcp_hdr->len = 0; - - ptr += sizeof(*ipcp_hdr); - - list_for_each_entry(ropt, &ipcp->ropt_list, entry) { - if (ropt->state == IPCP_OPT_REJ) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - if (ropt->lopt) - ropt->lopt->h->print(log_ppp_info2, ropt->lopt, (uint8_t*)ropt->hdr); - else - print_ropt(ropt); - } - memcpy(ptr, ropt->hdr, ropt->len); - ptr += ropt->len; - } - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - ipcp_hdr->len = htons(ptr - buf - 2); - ppp_unit_send(ipcp->ppp, ipcp_hdr, ptr-buf); - - _free(buf); -} - -static int ipcp_recv_conf_req(struct ppp_ipcp_t *ipcp, uint8_t *data, int size) -{ - struct ipcp_opt_hdr_t *hdr; - struct recv_opt_t *ropt; - struct ipcp_option_t *lopt; - int r,ret = 1; - - ipcp->ropt_len = size; - - while (size > 0) { - hdr = (struct ipcp_opt_hdr_t *)data; - - ropt = _malloc(sizeof(*ropt)); - memset(ropt, 0, sizeof(*ropt)); - - if (hdr->len > size) - ropt->len = size; - else - ropt->len = hdr->len; - ropt->hdr = hdr; - ropt->state = IPCP_OPT_NONE; - list_add_tail(&ropt->entry, &ipcp->ropt_list); - - data += ropt->len; - size -= ropt->len; - } - - list_for_each_entry(lopt, &ipcp->options, entry) - lopt->state=IPCP_OPT_NONE; - - if (conf_ppp_verbose) { - log_ppp_info2("recv [IPCP ConfReq id=%x", ipcp->fsm.recv_id); - - list_for_each_entry(ropt, &ipcp->ropt_list, entry) { - list_for_each_entry(lopt, &ipcp->options, entry) { - if (lopt->id == ropt->hdr->id) { - ropt->lopt = lopt; - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, (uint8_t*)ropt->hdr); - break; - } - } - if (!ropt->lopt) { - log_ppp_info2(" "); - print_ropt(ropt); - } - } - log_ppp_info2("]\n"); - } - - list_for_each_entry(ropt, &ipcp->ropt_list, entry) { - list_for_each_entry(lopt, &ipcp->options, entry) { - if (lopt->id == ropt->hdr->id) { - r = lopt->h->recv_conf_req(ipcp, lopt, (uint8_t*)ropt->hdr); - if (ipcp->ppp->stop_time) - return -1; - lopt->state = r; - ropt->state = r; - ropt->lopt = lopt; - if (r < ret) - ret = r; - break; - } - } - if (!ropt->lopt) { - ropt->state = IPCP_OPT_REJ; - ret = IPCP_OPT_REJ; - } - } - - - /*list_for_each_entry(lopt,&ipcp->options,entry) - { - if (lopt->state==IPCP_OPT_NONE) - { - r=lopt->h->recv_conf_req(ipcp,lopt,NULL); - lopt->state=r; - if (rropt_list)) { - ropt = list_entry(ipcp->ropt_list.next, typeof(*ropt), entry); - list_del(&ropt->entry); - _free(ropt); - } -} - -static int ipcp_recv_conf_rej(struct ppp_ipcp_t *ipcp, uint8_t *data, int size) -{ - struct ipcp_opt_hdr_t *hdr; - struct ipcp_option_t *lopt; - int res = 0; - - if (conf_ppp_verbose) - log_ppp_info2("recv [IPCP ConfRej id=%x", ipcp->fsm.recv_id); - - if (ipcp->fsm.recv_id != ipcp->fsm.id) { - if (conf_ppp_verbose) - log_ppp_info2(": id mismatch ]\n"); - return 0; - } - - while (size > 0) { - hdr = (struct ipcp_opt_hdr_t *)data; - - list_for_each_entry(lopt, &ipcp->options, entry) { - if (lopt->id == hdr->id) { - if (!lopt->h->recv_conf_rej) - res = -1; - else if (lopt->h->recv_conf_rej(ipcp, lopt, data)) - res = -1; - break; - } - } - - data += hdr->len; - size -= hdr->len; - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - return res; -} - -static int ipcp_recv_conf_nak(struct ppp_ipcp_t *ipcp, uint8_t *data, int size) -{ - struct ipcp_opt_hdr_t *hdr; - struct ipcp_option_t *lopt; - int res = 0; - - if (conf_ppp_verbose) - log_ppp_info2("recv [IPCP ConfNak id=%x", ipcp->fsm.recv_id); - - if (ipcp->fsm.recv_id != ipcp->fsm.id) { - if (conf_ppp_verbose) - log_ppp_info2(": id mismatch ]\n"); - return 0; - } - - while (size > 0) { - hdr = (struct ipcp_opt_hdr_t *)data; - - list_for_each_entry(lopt, &ipcp->options, entry) { - if (lopt->id == hdr->id) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2,lopt,data); - } - if (lopt->h->recv_conf_nak && lopt->h->recv_conf_nak(ipcp, lopt, data)) - res =- 1; - break; - } - } - - data += hdr->len; - size -= hdr->len; - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - return res; -} - -static int ipcp_recv_conf_ack(struct ppp_ipcp_t *ipcp, uint8_t *data, int size) -{ - struct ipcp_opt_hdr_t *hdr; - struct ipcp_option_t *lopt; - int res = 0; - - if (conf_ppp_verbose) - log_ppp_info2("recv [IPCP ConfAck id=%x", ipcp->fsm.recv_id); - - if (ipcp->fsm.recv_id != ipcp->fsm.id) { - if (conf_ppp_verbose) - log_ppp_info2(": id mismatch ]\n"); - return 0; - } - - while (size > 0) { - hdr = (struct ipcp_opt_hdr_t *)data; - - list_for_each_entry(lopt, &ipcp->options, entry) { - if (lopt->id == hdr->id) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, data); - } - if (!lopt->h->recv_conf_ack) - break; - if (lopt->h->recv_conf_ack(ipcp, lopt, data)) - res = -1; - break; - } - } - - data += hdr->len; - size -= hdr->len; - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - return res; -} - -static void send_term_req(struct ppp_fsm_t *fsm) -{ - struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); - struct ipcp_hdr_t hdr = { - .proto = htons(PPP_IPCP), - .code = TERMREQ, - .id = ++ipcp->fsm.id, - .len = htons(4), - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [IPCP TermReq id=%i]\n", hdr.id); - - ppp_unit_send(ipcp->ppp, &hdr, 6); -} - -static void send_term_ack(struct ppp_fsm_t *fsm) -{ - struct ppp_ipcp_t *ipcp = container_of(fsm, typeof(*ipcp), fsm); - struct ipcp_hdr_t hdr = { - .proto = htons(PPP_IPCP), - .code = TERMACK, - .id = ipcp->fsm.recv_id, - .len = htons(4), - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [IPCP TermAck id=%i]\n", hdr.id); - - ppp_unit_send(ipcp->ppp, &hdr, 6); -} - -static void ipcp_recv(struct ppp_handler_t*h) -{ - struct ipcp_hdr_t *hdr; - struct ppp_ipcp_t *ipcp = container_of(h, typeof(*ipcp), hnd); - int r; - - if (ipcp->fsm.fsm_state == FSM_Initial || ipcp->fsm.fsm_state == FSM_Closed || ipcp->ppp->terminating) { - if (conf_ppp_verbose) - log_ppp_warn("IPCP: discarding packet\n"); - return; - } - - if (ipcp->ppp->unit_buf_size < PPP_HEADERLEN + 2) { - log_ppp_warn("IPCP: short packet received\n"); - return; - } - - hdr = (struct ipcp_hdr_t *)ipcp->ppp->unit_buf; - if (ntohs(hdr->len) < PPP_HEADERLEN) { - log_ppp_warn("IPCP: short packet received\n"); - return; - } - - ipcp->fsm.recv_id = hdr->id; - switch(hdr->code) { - case CONFREQ: - r = ipcp_recv_conf_req(ipcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); - if (ipcp->ppp->stop_time) { - ipcp_free_conf_req(ipcp); - return; - } - switch(r) { - case IPCP_OPT_ACK: - ppp_fsm_recv_conf_req_ack(&ipcp->fsm); - break; - case IPCP_OPT_NAK: - ppp_fsm_recv_conf_req_nak(&ipcp->fsm); - break; - case IPCP_OPT_REJ: - ppp_fsm_recv_conf_req_rej(&ipcp->fsm); - break; - } - ipcp_free_conf_req(ipcp); - if (r == IPCP_OPT_FAIL) - ppp_terminate(ipcp->ppp, TERM_USER_ERROR, 0); - break; - case CONFACK: - if (ipcp_recv_conf_ack(ipcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) - ppp_terminate(ipcp->ppp, TERM_USER_ERROR, 0); - else - ppp_fsm_recv_conf_ack(&ipcp->fsm); - break; - case CONFNAK: - ipcp_recv_conf_nak(ipcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); - ppp_fsm_recv_conf_rej(&ipcp->fsm); - break; - case CONFREJ: - if (ipcp_recv_conf_rej(ipcp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) - ppp_terminate(ipcp->ppp, TERM_USER_ERROR, 0); - else - ppp_fsm_recv_conf_rej(&ipcp->fsm); - break; - case TERMREQ: - if (conf_ppp_verbose) - log_ppp_info2("recv [IPCP TermReq id=%x]\n", hdr->id); - ppp_fsm_recv_term_req(&ipcp->fsm); - ppp_terminate(ipcp->ppp, TERM_USER_REQUEST, 0); - break; - case TERMACK: - if (conf_ppp_verbose) - log_ppp_info2("recv [IPCP TermAck id=%x]\n", hdr->id); - //ppp_fsm_recv_term_ack(&ipcp->fsm); - //ppp_terminate(ipcp->ppp, 0); - break; - case CODEREJ: - if (conf_ppp_verbose) - log_ppp_info2("recv [IPCP CodeRej id=%x]\n", hdr->id); - ppp_fsm_recv_code_rej_bad(&ipcp->fsm); - break; - default: - ppp_fsm_recv_unk(&ipcp->fsm); - break; - } -} - -int ipcp_option_register(struct ipcp_option_handler_t *h) -{ - /*struct ipcp_option_drv_t *p; - - list_for_each_entry(p,option_drv_list,entry) - if (p->id==h->id) - return -1;*/ - - list_add_tail(&h->entry, &option_handlers); - - return 0; -} - -static struct ppp_layer_t ipcp_layer = -{ - .init = ipcp_layer_init, - .start = ipcp_layer_start, - .finish = ipcp_layer_finish, - .free = ipcp_layer_free, -}; - -static void __init ipcp_init(void) -{ - ppp_register_layer("ipcp", &ipcp_layer); -} - diff --git a/accel-pptpd/ppp/ppp_ipcp.h b/accel-pptpd/ppp/ppp_ipcp.h deleted file mode 100644 index c955987..0000000 --- a/accel-pptpd/ppp/ppp_ipcp.h +++ /dev/null @@ -1,96 +0,0 @@ -#ifndef PPP_IPCP_H -#define PPP_IPCP_H - -#include - -#include "triton.h" -#include "ppp_fsm.h" -/* - * Options. - */ -#define CI_COMP 2 /* IP-Compress-Protocol */ -#define CI_ADDR 3 /* IP-Address */ -#define CI_DNS1 129 /* Primary-DNS-Address */ -#define CI_DNS2 131 /* Secondary-DNS-Address */ - -struct ipcp_hdr_t -{ - uint16_t proto; - uint8_t code; - uint8_t id; - uint16_t len; -} __attribute__((packed)); -struct ipcp_opt_hdr_t -{ - uint8_t id; - uint8_t len; -} __attribute__((packed)); -struct ipcp_opt8_t -{ - struct ipcp_opt_hdr_t hdr; - uint8_t val; -} __attribute__((packed)); -struct ipcp_opt16_t -{ - struct ipcp_opt_hdr_t hdr; - uint16_t val; -} __attribute__((packed)); -struct ipcp_opt32_t -{ - struct ipcp_opt_hdr_t hdr; - uint32_t val; -} __attribute__((packed)); - -#define IPCP_OPT_NONE 0 -#define IPCP_OPT_ACK 1 -#define IPCP_OPT_NAK -1 -#define IPCP_OPT_REJ -2 -#define IPCP_OPT_FAIL -3 - -struct ppp_ipcp_t; -struct ipcp_option_handler_t; - -struct ipcp_option_t -{ - struct list_head entry; - int id; - int len; - int state; - int print:1; - struct ipcp_option_handler_t *h; -}; - -struct ipcp_option_handler_t -{ - struct list_head entry; - struct ipcp_option_t* (*init)(struct ppp_ipcp_t*); - int (*send_conf_req)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); - int (*send_conf_rej)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); - int (*send_conf_nak)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); - int (*recv_conf_req)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); - int (*recv_conf_rej)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); - int (*recv_conf_nak)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); - int (*recv_conf_ack)(struct ppp_ipcp_t*,struct ipcp_option_t*,uint8_t*); - void (*free)(struct ppp_ipcp_t*,struct ipcp_option_t*); - void (*print)(void (*print)(const char *fmt,...), struct ipcp_option_t*,uint8_t*); -}; - -struct ppp_ipcp_t -{ - struct ppp_layer_data_t ld; - struct ppp_handler_t hnd; - struct ppp_fsm_t fsm; - struct ppp_t *ppp; - struct list_head options; - - struct list_head ropt_list; // last received ConfReq - int ropt_len; - - int conf_req_len; - int started:1; -}; - -int ipcp_option_register(struct ipcp_option_handler_t *h); - -#endif - diff --git a/accel-pptpd/ppp/ppp_lcp.c b/accel-pptpd/ppp/ppp_lcp.c deleted file mode 100644 index e40e321..0000000 --- a/accel-pptpd/ppp/ppp_lcp.c +++ /dev/null @@ -1,847 +0,0 @@ -#include -#include -#include -#include -#include "linux_ppp.h" - -#include "triton.h" - -#include "log.h" - -#include "ppp.h" -#include "ppp_lcp.h" -#include "events.h" - -#include "memdebug.h" - -struct recv_opt_t -{ - struct list_head entry; - struct lcp_opt_hdr_t *hdr; - int len; - int state; - struct lcp_option_t *lopt; -}; - -static int conf_echo_interval = 0; -static int conf_echo_failure = 3; - -static LIST_HEAD(option_handlers); -static struct ppp_layer_t lcp_layer; - -static void lcp_layer_up(struct ppp_fsm_t*); -static void lcp_layer_down(struct ppp_fsm_t*); -static void lcp_layer_finished(struct ppp_fsm_t*); -static int send_conf_req(struct ppp_fsm_t*); -static void send_conf_ack(struct ppp_fsm_t*); -static void send_conf_nak(struct ppp_fsm_t*); -static void send_conf_rej(struct ppp_fsm_t*); -static void send_code_rej(struct ppp_fsm_t*); -static void start_echo(struct ppp_lcp_t *lcp); -static void stop_echo(struct ppp_lcp_t *lcp); -static void send_term_req(struct ppp_fsm_t *fsm); -static void send_term_ack(struct ppp_fsm_t *fsm); -static void lcp_recv(struct ppp_handler_t*); - -static void lcp_options_init(struct ppp_lcp_t *lcp) -{ - struct lcp_option_t *lopt; - struct lcp_option_handler_t *h; - - INIT_LIST_HEAD(&lcp->options); - - lcp->conf_req_len = sizeof(struct lcp_hdr_t); - - list_for_each_entry(h, &option_handlers, entry) { - lopt = h->init(lcp); - if (lopt) { - lopt->h = h; - list_add_tail(&lopt->entry, &lcp->options); - lcp->conf_req_len += lopt->len; - } - } -} - -static void lcp_options_free(struct ppp_lcp_t *lcp) -{ - struct lcp_option_t *lopt; - - while (!list_empty(&lcp->options)) { - lopt = list_entry(lcp->options.next, typeof(*lopt), entry); - list_del(&lopt->entry); - lopt->h->free(lcp, lopt); - } -} - -static struct ppp_layer_data_t *lcp_layer_init(struct ppp_t *ppp) -{ - struct ppp_lcp_t *lcp = _malloc(sizeof(*lcp)); - memset(lcp, 0, sizeof(*lcp)); - - log_ppp_debug("lcp_layer_init\n"); - - lcp->ppp = ppp; - lcp->fsm.ppp = ppp; - - lcp->hnd.proto = PPP_LCP; - lcp->hnd.recv = lcp_recv; - - ppp_register_chan_handler(ppp, &lcp->hnd); - - lcp->fsm.proto = PPP_LCP; - ppp_fsm_init(&lcp->fsm); - - lcp->fsm.layer_up = lcp_layer_up; - lcp->fsm.layer_down = lcp_layer_down; - lcp->fsm.layer_finished = lcp_layer_finished; - lcp->fsm.send_conf_req = send_conf_req; - lcp->fsm.send_conf_ack = send_conf_ack; - lcp->fsm.send_conf_nak = send_conf_nak; - lcp->fsm.send_conf_rej = send_conf_rej; - lcp->fsm.send_code_rej = send_code_rej; - lcp->fsm.send_term_req = send_term_req; - lcp->fsm.send_term_ack = send_term_ack; - - INIT_LIST_HEAD(&lcp->ropt_list); - - return &lcp->ld; -} - -int lcp_layer_start(struct ppp_layer_data_t *ld) -{ - struct ppp_lcp_t *lcp = container_of(ld, typeof(*lcp), ld); - - log_ppp_debug("lcp_layer_start\n"); - - lcp_options_init(lcp); - ppp_fsm_lower_up(&lcp->fsm); - if (ppp_fsm_open(&lcp->fsm)) - return -1; - - return 0; -} - -static void _lcp_layer_finished(struct ppp_lcp_t *lcp) -{ - ppp_layer_finished(lcp->ppp, &lcp->ld); -} - -void lcp_layer_finish(struct ppp_layer_data_t *ld) -{ - struct ppp_lcp_t *lcp = container_of(ld,typeof(*lcp),ld); - - log_ppp_debug("lcp_layer_finish\n"); - - if (lcp->started) { - stop_echo(lcp); - ppp_fsm_close(&lcp->fsm); - } else - triton_context_call(lcp->ppp->ctrl->ctx, (triton_event_func)_lcp_layer_finished, lcp); -} - -void lcp_layer_free(struct ppp_layer_data_t *ld) -{ - struct ppp_lcp_t *lcp = container_of(ld, typeof(*lcp), ld); - - log_ppp_debug("lcp_layer_free\n"); - - stop_echo(lcp); - ppp_unregister_handler(lcp->ppp, &lcp->hnd); - lcp_options_free(lcp); - ppp_fsm_free(&lcp->fsm); - triton_cancel_call(lcp->ppp->ctrl->ctx, (triton_event_func)_lcp_layer_finished); - - _free(lcp); -} - -static void lcp_layer_up(struct ppp_fsm_t *fsm) -{ - struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); - - log_ppp_debug("lcp_layer_started\n"); - - if (!lcp->started) { - lcp->started = 1; - ppp_layer_started(lcp->ppp, &lcp->ld); - } - start_echo(lcp); -} - -static void lcp_layer_down(struct ppp_fsm_t *fsm) -{ - struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); - //ppp_fsm_close(&lcp->fsm); - stop_echo(lcp); - //ppp_layer_finished(lcp->ppp,&lcp->ld); -} - -static void lcp_layer_finished(struct ppp_fsm_t *fsm) -{ - struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); - - log_ppp_debug("lcp_layer_finished\n"); - - stop_echo(lcp); - if (lcp->started) { - lcp->started = 0; - if (lcp->ppp->terminating) - ppp_layer_finished(lcp->ppp, &lcp->ld); - else - ppp_terminate(lcp->ppp, TERM_NAS_ERROR, 0); - } else - ppp_terminate(lcp->ppp, TERM_NAS_ERROR, 0); -} - -static void print_ropt(struct recv_opt_t *ropt) -{ - int i; - uint8_t *ptr = (uint8_t*)ropt->hdr; - - log_ppp_info2("<"); - for (i = 0; i < ropt->len; i++) { - log_ppp_info2(" %x", ptr[i]); - } - log_ppp_info2(" >"); -} - -static int send_conf_req(struct ppp_fsm_t *fsm) -{ - struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); - uint8_t *buf = _malloc(lcp->conf_req_len), *ptr = buf; - struct lcp_hdr_t *lcp_hdr = (struct lcp_hdr_t*)ptr; - struct lcp_option_t *lopt; - int n; - - lcp_hdr->proto = htons(PPP_LCP); - lcp_hdr->code = CONFREQ; - lcp_hdr->id = ++lcp->fsm.id; - lcp_hdr->len = 0; - - ptr += sizeof(*lcp_hdr); - - list_for_each_entry(lopt, &lcp->options, entry) { - n = lopt->h->send_conf_req(lcp, lopt, ptr); - if (n < 0) - return -1; - if (n) { - ptr += n; - lopt->print = 1; - } else - lopt->print = 0; - } - - if (conf_ppp_verbose) { - log_ppp_info2("send [LCP ConfReq id=%x", lcp_hdr->id); - list_for_each_entry(lopt,&lcp->options,entry) { - if (lopt->print) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, NULL); - } - } - log_ppp_info2("]\n"); - } - - lcp_hdr->len = htons(ptr - buf - 2); - ppp_chan_send(lcp->ppp, lcp_hdr, ptr-buf); - - _free(buf); - - return 0; -} - -static void send_conf_ack(struct ppp_fsm_t *fsm) -{ - struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); - struct lcp_hdr_t *hdr = (struct lcp_hdr_t*)lcp->ppp->chan_buf; - - hdr->code = CONFACK; - - if (conf_ppp_verbose) - log_ppp_info2("send [LCP ConfAck id=%x ]\n", lcp->fsm.recv_id); - - ppp_chan_send(lcp->ppp, hdr, ntohs(hdr->len) + 2); -} - -static void send_code_rej(struct ppp_fsm_t *fsm) -{ - struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); - struct lcp_hdr_t *hdr = (struct lcp_hdr_t*)lcp->ppp->chan_buf; - - hdr->code = CONFACK; - - if (conf_ppp_verbose) - log_ppp_info2("send [LCP CodeRej %x id=%x ]\n",hdr->code, lcp->fsm.recv_id); - - ppp_chan_send(lcp->ppp, hdr, ntohs(hdr->len) + 2); -} - -static void send_conf_nak(struct ppp_fsm_t *fsm) -{ - struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); - uint8_t *buf = _malloc(lcp->conf_req_len), *ptr = buf; - struct lcp_hdr_t *lcp_hdr = (struct lcp_hdr_t*)ptr; - struct lcp_option_t *lopt; - - if (conf_ppp_verbose) - log_ppp_info2("send [LCP ConfNak id=%x", lcp->fsm.recv_id); - - lcp_hdr->proto = htons(PPP_LCP); - lcp_hdr->code = CONFNAK; - lcp_hdr->id = lcp->fsm.recv_id; - lcp_hdr->len = 0; - - ptr += sizeof(*lcp_hdr); - - list_for_each_entry(lopt, &lcp->options, entry) { - if (lopt->state == LCP_OPT_NAK) { - ptr+=lopt->h->send_conf_nak(lcp,lopt,ptr); - - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, NULL); - } - } - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - lcp_hdr->len = htons(ptr - buf - 2); - ppp_chan_send(lcp->ppp, lcp_hdr,ptr - buf); - - _free(buf); -} - -static void send_conf_rej(struct ppp_fsm_t *fsm) -{ - struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); - uint8_t *buf = _malloc(lcp->ropt_len + sizeof(struct lcp_hdr_t)), *ptr = buf; - struct lcp_hdr_t *lcp_hdr = (struct lcp_hdr_t*)ptr; - struct recv_opt_t *ropt; - - if (conf_ppp_verbose) - log_ppp_info2("send [LCP ConfRej id=%x ", lcp->fsm.recv_id); - - lcp_hdr->proto = htons(PPP_LCP); - lcp_hdr->code = CONFREJ; - lcp_hdr->id = lcp->fsm.recv_id; - lcp_hdr->len = 0; - - ptr += sizeof(*lcp_hdr); - - list_for_each_entry(ropt, &lcp->ropt_list, entry) { - if (ropt->state == LCP_OPT_REJ) { - memcpy(ptr, ropt->hdr, ropt->len); - ptr += ropt->len; - - if (conf_ppp_verbose) { - log_ppp_info2(" "); - if (ropt->lopt) - ropt->lopt->h->print(log_ppp_info2, ropt->lopt, (uint8_t*)ropt->hdr); - else - print_ropt(ropt); - } - } - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - lcp_hdr->len = htons(ptr - buf - 2); - ppp_chan_send(lcp->ppp, lcp_hdr, ptr - buf); - - _free(buf); -} - -static int lcp_recv_conf_req(struct ppp_lcp_t *lcp, uint8_t *data, int size) -{ - struct lcp_opt_hdr_t *hdr; - struct recv_opt_t *ropt; - struct lcp_option_t *lopt; - int r, ret = 1; - - lcp->ropt_len = size; - - while (size > 0) { - hdr = (struct lcp_opt_hdr_t *)data; - - ropt = _malloc(sizeof(*ropt)); - memset(ropt, 0, sizeof(*ropt)); - - if (hdr->len > size) - ropt->len = size; - else - ropt->len = hdr->len; - - ropt->hdr = hdr; - ropt->state = LCP_OPT_NONE; - list_add_tail(&ropt->entry, &lcp->ropt_list); - - data += ropt->len; - size -= ropt->len; - } - - list_for_each_entry(lopt, &lcp->options, entry) - lopt->state = LCP_OPT_NONE; - - if (conf_ppp_verbose) - log_ppp_info2("recv [LCP ConfReq id=%x", lcp->fsm.recv_id); - - list_for_each_entry(ropt, &lcp->ropt_list, entry) { - list_for_each_entry(lopt, &lcp->options, entry) { - if (lopt->id == ropt->hdr->id) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, (uint8_t*)ropt->hdr); - } - r = lopt->h->recv_conf_req(lcp, lopt, (uint8_t*)ropt->hdr); - lopt->state = r; - ropt->state = r; - ropt->lopt = lopt; - if (rlopt) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - print_ropt(ropt); - } - ropt->state=LCP_OPT_REJ; - ret=LCP_OPT_REJ; - } - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - /*list_for_each_entry(lopt,&lcp->options,entry) - { - if (lopt->state==LCP_OPT_NONE) - { - r=lopt->h->recv_conf_req(lcp,lopt,NULL); - lopt->state=r; - if (rropt_list)) { - ropt = list_entry(lcp->ropt_list.next, typeof(*ropt), entry); - list_del(&ropt->entry); - _free(ropt); - } -} - -static int lcp_recv_conf_rej(struct ppp_lcp_t *lcp, uint8_t *data, int size) -{ - struct lcp_opt_hdr_t *hdr; - struct lcp_option_t *lopt; - int res = 0; - - if (conf_ppp_verbose) - log_ppp_info2("recv [LCP ConfRej id=%x", lcp->fsm.recv_id); - - if (lcp->fsm.recv_id != lcp->fsm.id) { - if (conf_ppp_verbose) - log_ppp_info2(": id mismatch ]\n"); - return 0; - } - - while (size > 0) { - hdr = (struct lcp_opt_hdr_t *)data; - - list_for_each_entry(lopt, &lcp->options, entry) { - if (lopt->id == hdr->id) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, (uint8_t*)hdr); - } - if (!lopt->h->recv_conf_rej) - res = -1; - else if (lopt->h->recv_conf_rej(lcp, lopt, data)) - res = -1; - break; - } - } - - data += hdr->len; - size -= hdr->len; - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - return res; -} - -static int lcp_recv_conf_nak(struct ppp_lcp_t *lcp, uint8_t *data, int size) -{ - struct lcp_opt_hdr_t *hdr; - struct lcp_option_t *lopt; - int res = 0; - - if (conf_ppp_verbose) - log_ppp_info2("recv [LCP ConfNak id=%x", lcp->fsm.recv_id); - - if (lcp->fsm.recv_id != lcp->fsm.id) { - if (conf_ppp_verbose) - log_ppp_info2(": id mismatch ]\n"); - return 0; - } - - while (size > 0) { - hdr = (struct lcp_opt_hdr_t *)data; - - list_for_each_entry(lopt,&lcp->options,entry) { - if (lopt->id == hdr->id) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, data); - } - if (lopt->h->recv_conf_nak && lopt->h->recv_conf_nak(lcp, lopt, data)) - res = -1; - break; - } - } - - data += hdr->len; - size -= hdr->len; - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - return res; -} - -static int lcp_recv_conf_ack(struct ppp_lcp_t *lcp, uint8_t *data, int size) -{ - struct lcp_opt_hdr_t *hdr; - struct lcp_option_t *lopt; - int res=0; - - if (conf_ppp_verbose) - log_ppp_info2("recv [LCP ConfAck id=%x", lcp->fsm.recv_id); - - if (lcp->fsm.recv_id != lcp->fsm.id) { - if (conf_ppp_verbose) - log_ppp_info2(": id mismatch ]\n"); - return 0; - } - - while (size > 0) { - hdr = (struct lcp_opt_hdr_t *)data; - - list_for_each_entry(lopt, &lcp->options, entry) { - if (lopt->id == hdr->id) { - if (conf_ppp_verbose) { - log_ppp_info2(" "); - lopt->h->print(log_ppp_info2, lopt, data); - } - if (!lopt->h->recv_conf_ack) - break; - if (lopt->h->recv_conf_ack(lcp, lopt, data)) - res = -1; - break; - } - } - - data += hdr->len; - size -= hdr->len; - } - - if (conf_ppp_verbose) - log_ppp_info2("]\n"); - - return res; -} - -static void lcp_recv_echo_repl(struct ppp_lcp_t *lcp, uint8_t *data, int size) -{ - uint32_t magic = *(uint32_t *)data; - - if (size != 4) { - log_ppp_error("lcp:echo: magic number size mismatch\n"); - ppp_terminate(lcp->ppp, TERM_USER_ERROR, 0); - } - - if (conf_ppp_verbose) - log_ppp_debug("recv [LCP EchoRep id=%x ]\n", lcp->fsm.recv_id, magic); - - if (magic == lcp->magic) { - log_ppp_error("lcp: echo: loop-back detected\n"); - ppp_terminate(lcp->ppp, TERM_NAS_ERROR, 0); - } - - lcp->echo_sent = 0; -} - -static void send_echo_reply(struct ppp_lcp_t *lcp) -{ - struct lcp_hdr_t *hdr = (struct lcp_hdr_t*)lcp->ppp->chan_buf; - uint32_t magic = *(uint32_t *)(hdr + 1); - - hdr->code = ECHOREP; - *(uint32_t *)(hdr + 1) = lcp->magic; - - if (conf_ppp_verbose) - log_ppp_debug("send [LCP EchoRep id=%x ]\n", hdr->id, magic); - - ppp_chan_send(lcp->ppp, hdr, ntohs(hdr->len) + 2); -} - -static void send_echo_request(struct triton_timer_t *t) -{ - struct ppp_lcp_t *lcp = container_of(t, typeof(*lcp), echo_timer); - struct lcp_echo_req_t - { - struct lcp_hdr_t hdr; - uint32_t magic; - } __attribute__((packed)) msg = { - .hdr.proto = htons(PPP_LCP), - .hdr.code = ECHOREQ, - .hdr.id = ++lcp->fsm.id, - .hdr.len = htons(8), - .magic = lcp->magic, - }; - - if (++lcp->echo_sent > lcp->echo_failure) { - log_ppp_warn("lcp: no echo reply\n"); - ppp_terminate(lcp->ppp, TERM_USER_ERROR, 1); - } else { - if (conf_ppp_verbose) - log_ppp_debug("send [LCP EchoReq id=%x ]\n", msg.hdr.id, msg.magic); - ppp_chan_send(lcp->ppp,&msg,ntohs(msg.hdr.len)+2); - } -} - -static void start_echo(struct ppp_lcp_t *lcp) -{ - lcp->echo_interval = conf_echo_interval; - lcp->echo_failure = conf_echo_failure; - - lcp->echo_timer.period = lcp->echo_interval * 1000; - lcp->echo_timer.expire = send_echo_request; - if (lcp->echo_timer.period && !lcp->echo_timer.tpd) - triton_timer_add(lcp->ppp->ctrl->ctx, &lcp->echo_timer, 0); -} -static void stop_echo(struct ppp_lcp_t *lcp) -{ - if (lcp->echo_timer.tpd) - triton_timer_del(&lcp->echo_timer); -} - -static void send_term_req(struct ppp_fsm_t *fsm) -{ - struct ppp_lcp_t *lcp=container_of(fsm,typeof(*lcp),fsm); - struct lcp_hdr_t hdr = { - .proto = htons(PPP_LCP), - .code = TERMREQ, - .id = ++lcp->fsm.id, - .len = htons(4), - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [LCP TermReq id=%i]\n", hdr.id); - - ppp_chan_send(lcp->ppp, &hdr, 6); -} - -static void send_term_ack(struct ppp_fsm_t *fsm) -{ - struct ppp_lcp_t *lcp = container_of(fsm, typeof(*lcp), fsm); - struct lcp_hdr_t hdr = { - .proto = htons(PPP_LCP), - .code = TERMACK, - .id = lcp->fsm.recv_id, - .len = htons(4), - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [LCP TermAck id=%i]\n", hdr.id); - - ppp_chan_send(lcp->ppp, &hdr, 6); -} - -void lcp_send_proto_rej(struct ppp_t *ppp, uint16_t proto) -{ - struct ppp_lcp_t *lcp = container_of(ppp_find_layer_data(ppp, &lcp_layer), typeof(*lcp), ld); - struct rej_msg_t - { - struct lcp_hdr_t hdr; - uint16_t proto; - } __attribute__((packed)) msg = { - .hdr.proto = htons(PPP_LCP), - .hdr.code = PROTOREJ, - .hdr.id = ++lcp->fsm.id, - .hdr.len = htons(6), - .proto = ntohs(proto), - }; - - if (conf_ppp_verbose) - log_ppp_info2("send [LCP ProtoRej id=%i <%04x>]\n", msg.hdr.id, proto); - - ppp_chan_send(lcp->ppp, &msg, sizeof(msg)); -} - -static void lcp_recv(struct ppp_handler_t*h) -{ - struct lcp_hdr_t *hdr; - struct ppp_lcp_t *lcp = container_of(h, typeof(*lcp), hnd); - int r; - char *term_msg; - - if (lcp->fsm.fsm_state == FSM_Initial || lcp->fsm.fsm_state == FSM_Closed || lcp->ppp->terminating) { - /*if (conf_ppp_verbose) - log_ppp_warn("LCP: discaring packet\n"); - lcp_send_proto_rej(ccp->ppp, htons(PPP_CCP));*/ - return; - } - - if (lcp->ppp->chan_buf_size < PPP_HEADERLEN + 2) { - log_ppp_warn("LCP: short packet received\n"); - return; - } - - hdr = (struct lcp_hdr_t *)lcp->ppp->chan_buf; - if (ntohs(hdr->len) < PPP_HEADERLEN) { - log_ppp_warn("LCP: short packet received\n"); - return; - } - - lcp->fsm.recv_id = hdr->id; - switch(hdr->code) { - case CONFREQ: - r = lcp_recv_conf_req(lcp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); - switch(r) { - case LCP_OPT_ACK: - ppp_fsm_recv_conf_req_ack(&lcp->fsm); - break; - case LCP_OPT_NAK: - ppp_fsm_recv_conf_req_nak(&lcp->fsm); - break; - case LCP_OPT_REJ: - ppp_fsm_recv_conf_req_rej(&lcp->fsm); - break; - } - lcp_free_conf_req(lcp); - if (r == LCP_OPT_FAIL) - ppp_terminate(lcp->ppp, TERM_USER_ERROR, 0); - break; - case CONFACK: - if (lcp_recv_conf_ack(lcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) - ppp_terminate(lcp->ppp, TERM_USER_ERROR, 0); - else - if (lcp->fsm.recv_id != lcp->fsm.id) - break; - ppp_fsm_recv_conf_ack(&lcp->fsm); - break; - case CONFNAK: - lcp_recv_conf_nak(lcp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); - if (lcp->fsm.recv_id != lcp->fsm.id) - break; - ppp_fsm_recv_conf_rej(&lcp->fsm); - break; - case CONFREJ: - if (lcp_recv_conf_rej(lcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) - ppp_terminate(lcp->ppp, TERM_USER_ERROR, 0); - else - if (lcp->fsm.recv_id != lcp->fsm.id) - break; - ppp_fsm_recv_conf_rej(&lcp->fsm); - break; - case TERMREQ: - if (conf_ppp_verbose) - log_ppp_info2("recv [LCP TermReq id=%x]\n", hdr->id); - ppp_fsm_recv_term_req(&lcp->fsm); - ppp_terminate(lcp->ppp, TERM_USER_REQUEST, 0); - break; - case TERMACK: - if (conf_ppp_verbose) - log_ppp_info2("recv [LCP TermAck id=%x]\n", hdr->id); - ppp_fsm_recv_term_ack(&lcp->fsm); - break; - case CODEREJ: - if (conf_ppp_verbose) - log_ppp_info2("recv [LCP CodeRej id=%x]\n", hdr->id); - ppp_fsm_recv_code_rej_bad(&lcp->fsm); - break; - case ECHOREQ: - if (conf_ppp_verbose) - log_ppp_debug("recv [LCP EchoReq id=%x ]\n", hdr->id, *(uint32_t*)(hdr + 1)); - send_echo_reply(lcp); - break; - case ECHOREP: - lcp_recv_echo_repl(lcp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN); - break; - case PROTOREJ: - if (conf_ppp_verbose) - log_ppp_info2("recv [LCP ProtoRej id=%x <%04x>]\n", hdr->code, hdr->id, ntohs(*(uint16_t*)(hdr + 1))); - ppp_recv_proto_rej(lcp->ppp, ntohs(*(uint16_t *)(hdr + 1))); - break; - case IDENT: - if (conf_ppp_verbose) { - term_msg = _strndup((char*)(hdr + 1) + 4, ntohs(hdr->len) - 4 - 4); - log_ppp_info2("recv [LCP Ident id=%x <%s>]\n", hdr->id, term_msg); - _free(term_msg); - } - break; - default: - if (conf_ppp_verbose) - log_ppp_info2("recv [LCP Unknown %x]\n", hdr->code); - ppp_fsm_recv_unk(&lcp->fsm); - break; - } -} - -int lcp_option_register(struct lcp_option_handler_t *h) -{ - /*struct lcp_option_drv_t *p; - - list_for_each_entry(p,option_drv_list,entry) - if (p->id==h->id) - return -1;*/ - - list_add_tail(&h->entry, &option_handlers); - - return 0; -} - -static struct ppp_layer_t lcp_layer= -{ - .init = lcp_layer_init, - .start = lcp_layer_start, - .finish = lcp_layer_finish, - .free = lcp_layer_free, -}; - -static void load_config(void) -{ - char *opt; - - opt = conf_get_opt("lcp", "echo-interval"); - if (opt && atoi(opt) > 0) - conf_echo_interval = atoi(opt); - - opt = conf_get_opt("lcp", "echo-failure"); - if (opt && atoi(opt) > 0) - conf_echo_failure = atoi(opt); -} - -static void __init lcp_init(void) -{ - load_config(); - - ppp_register_layer("lcp", &lcp_layer); - - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); -} - diff --git a/accel-pptpd/ppp/ppp_lcp.h b/accel-pptpd/ppp/ppp_lcp.h deleted file mode 100644 index 6d67b69..0000000 --- a/accel-pptpd/ppp/ppp_lcp.h +++ /dev/null @@ -1,136 +0,0 @@ -#ifndef PPP_LCP_H -#define PPP_LCP_H - -#include - -#include "triton.h" -#include "ppp_fsm.h" -/* - * Options. - */ -#define CI_VENDOR 0 /* Vendor Specific */ -#define CI_MRU 1 /* Maximum Receive Unit */ -#define CI_ASYNCMAP 2 /* Async Control Character Map */ -#define CI_AUTH 3 /* Authentication Type */ -#define CI_QUALITY 4 /* Quality Protocol */ -#define CI_MAGIC 5 /* Magic Number */ -#define CI_PCOMP 7 /* Protocol Field Compression */ -#define CI_ACCOMP 8 /* Address/Control Field Compression */ -#define CI_FCSALTERN 9 /* FCS-Alternatives */ -#define CI_SDP 10 /* Self-Describing-Pad */ -#define CI_NUMBERED 11 /* Numbered-Mode */ -#define CI_CALLBACK 13 /* callback */ -#define CI_MRRU 17 /* max reconstructed receive unit; multilink */ -#define CI_SSNHF 18 /* short sequence numbers for multilink */ -#define CI_EPDISC 19 /* endpoint discriminator */ -#define CI_MPPLUS 22 /* Multi-Link-Plus-Procedure */ -#define CI_LDISC 23 /* Link-Discriminator */ -#define CI_LCPAUTH 24 /* LCP Authentication */ -#define CI_COBS 25 /* Consistent Overhead Byte Stuffing */ -#define CI_PREFELIS 26 /* Prefix Elision */ -#define CI_MPHDRFMT 27 /* MP Header Format */ -#define CI_I18N 28 /* Internationalization */ -#define CI_SDL 29 /* Simple Data Link */ - -struct lcp_hdr_t -{ - uint16_t proto; - uint8_t code; - uint8_t id; - uint16_t len; -} __attribute__((packed)); -struct lcp_opt_hdr_t -{ - uint8_t id; - uint8_t len; -} __attribute__((packed)); -struct lcp_opt8_t -{ - struct lcp_opt_hdr_t hdr; - uint8_t val; -} __attribute__((packed)); -struct lcp_opt16_t -{ - struct lcp_opt_hdr_t hdr; - uint16_t val; -} __attribute__((packed)); -struct lcp_opt32_t -{ - struct lcp_opt_hdr_t hdr; - uint32_t val; -} __attribute__((packed)); - -/*struct lcp_options_t -{ - int magic; - int mtu; - int mru; - int accomp; // 0 - disabled, 1 - enable, 2 - allow, disabled, 3 - allow,enabled - int pcomp; // 0 - disabled, 1 - enable, 2 - allow, disabled, 3 - allow,enabled - // negotiated options; - int neg_mru; - int neg_mtu; - int neg_accomp; // -1 - rejected - int neg_pcomp; - int neg_auth[AUTH_MAX]; -};*/ - -#define LCP_OPT_NONE 0 -#define LCP_OPT_ACK 1 -#define LCP_OPT_NAK -1 -#define LCP_OPT_REJ -2 -#define LCP_OPT_FAIL -3 - -struct ppp_lcp_t; -struct lcp_option_handler_t; - -struct lcp_option_t -{ - struct list_head entry; - int id; - int len; - int state; - int print:1; - struct lcp_option_handler_t *h; -}; - -struct lcp_option_handler_t -{ - struct list_head entry; - struct lcp_option_t* (*init)(struct ppp_lcp_t*); - int (*send_conf_req)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); - int (*send_conf_rej)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); - int (*send_conf_nak)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); - int (*recv_conf_req)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); - int (*recv_conf_rej)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); - int (*recv_conf_nak)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); - int (*recv_conf_ack)(struct ppp_lcp_t*,struct lcp_option_t*,uint8_t*); - void (*free)(struct ppp_lcp_t*,struct lcp_option_t*); - void (*print)(void (*print)(const char *fmt,...), struct lcp_option_t*,uint8_t*); -}; - -struct ppp_lcp_t -{ - struct ppp_layer_data_t ld; - struct ppp_handler_t hnd; - struct ppp_fsm_t fsm; - struct ppp_t *ppp; - struct list_head options; - - struct triton_timer_t echo_timer; - int echo_interval; - int echo_failure; - int echo_sent; - int magic; - - struct list_head ropt_list; // last received ConfReq - int ropt_len; - - int conf_req_len; - int started:1; -}; - -int lcp_option_register(struct lcp_option_handler_t *h); - -#endif - diff --git a/accel-pptpd/ppp/ppp_notify.c b/accel-pptpd/ppp/ppp_notify.c deleted file mode 100644 index ad9fd1f..0000000 --- a/accel-pptpd/ppp/ppp_notify.c +++ /dev/null @@ -1,54 +0,0 @@ -#include "ppp.h" - -static LIST_HEAD(notified_list); - -void __export ppp_register_notified(struct ppp_notified_t *n) -{ - list_add_tail(&n->entry, ¬ified_list); -} - -void __export ppp_unregister_notified(struct ppp_notified_t *n) -{ - list_del(&n->entry); -} - -void ppp_notify_starting(struct ppp_t *ppp) -{ - struct ppp_notified_t *n; - - list_for_each_entry(n, ¬ified_list, entry) { - if (n->starting) - n->starting(n, ppp); - } -} - -void ppp_notify_started(struct ppp_t *ppp) -{ - struct ppp_notified_t *n; - - list_for_each_entry(n, ¬ified_list, entry) { - if (n->started) - n->started(n, ppp); - } -} - -void ppp_notify_finished(struct ppp_t *ppp) -{ - struct ppp_notified_t *n; - - list_for_each_entry(n, ¬ified_list, entry) { - if (n->finished) - n->finished(n, ppp); - } -} - -void ppp_notify_finishing(struct ppp_t *ppp) -{ - struct ppp_notified_t *n; - - list_for_each_entry(n, ¬ified_list, entry) { - if (n->finishing) - n->finishing(n, ppp); - } -} - diff --git a/accel-pptpd/ppp/ppp_pd.c b/accel-pptpd/ppp/ppp_pd.c deleted file mode 100644 index f770208..0000000 --- a/accel-pptpd/ppp/ppp_pd.c +++ /dev/null @@ -1,14 +0,0 @@ -#include "ppp.h" - -#include "memdebug.h" - -int ppp_store_pd(struct ppp_t *ppp, pd_key_t key, void *data) -{ - struct ppp_pd_t *pd; - - list_for_each_entry(pd, &ppp->pd_list, entry) - if (pd->key == key) - return -1; - - -} diff --git a/accel-pptpd/pwdb.c b/accel-pptpd/pwdb.c deleted file mode 100644 index 4c0ab02..0000000 --- a/accel-pptpd/pwdb.c +++ /dev/null @@ -1,56 +0,0 @@ -#include - -#include "triton.h" - -#include "pwdb.h" - -#include "memdebug.h" - -static LIST_HEAD(pwdb_handlers); - -int __export pwdb_check(struct ppp_t *ppp, const char *username, int type, ...) -{ - struct pwdb_t *pwdb; - int r, res = PWDB_NO_IMPL; - va_list args; - - va_start(args, type); - - list_for_each_entry(pwdb, &pwdb_handlers, entry) { - if (!pwdb->check) - continue; - r = pwdb->check(pwdb, ppp, username, type, args); - if (r == PWDB_NO_IMPL) - continue; - if (r == PWDB_SUCCESS) - return PWDB_SUCCESS; - res = r; - } - - return res; -} -__export char *pwdb_get_passwd(struct ppp_t *ppp, const char *username) -{ - struct pwdb_t *pwdb; - char *r = NULL; - - list_for_each_entry(pwdb, &pwdb_handlers, entry) { - if (!pwdb->get_passwd) - continue; - r = pwdb->get_passwd(pwdb, ppp, username); - if (r) - break; - } - - return r; -} - -void __export pwdb_register(struct pwdb_t *pwdb) -{ - list_add_tail(&pwdb->entry, &pwdb_handlers); -} -void __export pwdb_unregister(struct pwdb_t *pwdb) -{ - list_del(&pwdb->entry); -} - diff --git a/accel-pptpd/pwdb.h b/accel-pptpd/pwdb.h deleted file mode 100644 index a1c2ced..0000000 --- a/accel-pptpd/pwdb.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef PWDB_H -#define PWDB_H - -#include -#include "list.h" - -struct ppp_t; - -#define PWDB_SUCCESS 0 -#define PWDB_DENIED 1 -#define PWDB_NO_IMPL 2 - -struct pwdb_t -{ - struct list_head entry; - int (*check)(struct pwdb_t *, struct ppp_t *, const char *username, int type, va_list args); - char* (*get_passwd)(struct pwdb_t *, struct ppp_t *, const char *username); -}; - -int pwdb_check(struct ppp_t *, const char *username, int type, ...); -char *pwdb_get_passwd(struct ppp_t *, const char *username); - -void pwdb_register(struct pwdb_t *); -void pwdb_unregister(struct pwdb_t *); - -#endif - diff --git a/accel-pptpd/radius/CMakeLists.txt b/accel-pptpd/radius/CMakeLists.txt deleted file mode 100644 index 8b8e67d..0000000 --- a/accel-pptpd/radius/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -SET(sources - dict.c - req.c - packet.c - auth.c - acct.c - dm_coa.c - radius.c -) - -ADD_DEFINITIONS(-DDICTIONARY="${CMAKE_INSTALL_PREFIX}/share/accel-pptp/radius/dictionary") - -ADD_LIBRARY(radius SHARED ${sources}) - -INSTALL(TARGETS radius - LIBRARY DESTINATION lib/accel-pptp -) -FILE(GLOB dict "${CMAKE_CURRENT_SOURCE_DIR}/dict/*") -INSTALL(FILES ${dict} DESTINATION share/accel-pptp/radius) diff --git a/accel-pptpd/radius/acct.c b/accel-pptpd/radius/acct.c deleted file mode 100644 index ddb3e08..0000000 --- a/accel-pptpd/radius/acct.c +++ /dev/null @@ -1,328 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include "linux_ppp.h" - -#include - -#include "log.h" -#include "radius_p.h" - -#include "memdebug.h" - -#define STAT_UPDATE_INTERVAL (10 * 60 * 1000) - -static int req_set_RA(struct rad_req_t *req, const char *secret) -{ - MD5_CTX ctx; - - if (rad_packet_build(req->pack, req->RA)) - return -1; - - MD5_Init(&ctx); - MD5_Update(&ctx, req->pack->buf, req->pack->len); - MD5_Update(&ctx, secret, strlen(secret)); - MD5_Final(req->pack->buf + 4, &ctx); - - return 0; -} - -static void req_set_stat(struct rad_req_t *req, struct ppp_t *ppp) -{ - struct ifpppstatsreq ifreq; - time_t stop_time; - - if (ppp->stop_time) - stop_time = ppp->stop_time; - else - time(&stop_time); - - memset(&ifreq, 0, sizeof(ifreq)); - ifreq.stats_ptr = (void *)&ifreq.stats; - strcpy(ifreq.ifr__name, ppp->ifname); - - if (ioctl(sock_fd, SIOCGPPPSTATS, &ifreq)) { - log_ppp_error("radius: failed to get ppp statistics: %s\n", strerror(errno)); - return; - } - - if (ifreq.stats.p.ppp_ibytes < req->rpd->acct_input_octets) - req->rpd->acct_input_gigawords++; - req->rpd->acct_input_octets = ifreq.stats.p.ppp_ibytes; - - if (ifreq.stats.p.ppp_obytes < req->rpd->acct_output_octets) - req->rpd->acct_output_gigawords++; - req->rpd->acct_output_octets = ifreq.stats.p.ppp_obytes; - - rad_packet_change_int(req->pack, NULL, "Acct-Input-Octets", ifreq.stats.p.ppp_ibytes); - rad_packet_change_int(req->pack, NULL, "Acct-Output-Octets", ifreq.stats.p.ppp_obytes); - rad_packet_change_int(req->pack, NULL, "Acct-Input-Packets", ifreq.stats.p.ppp_ipackets); - rad_packet_change_int(req->pack, NULL, "Acct-Output-Packets", ifreq.stats.p.ppp_opackets); - rad_packet_change_int(req->pack, NULL, "Acct-Input-Gigawords", req->rpd->acct_input_gigawords); - rad_packet_change_int(req->pack, NULL, "Acct-Output-Gigawords", req->rpd->acct_output_gigawords); - rad_packet_change_int(req->pack, NULL, "Acct-Session-Time", stop_time - ppp->start_time); -} - -static int rad_acct_read(struct triton_md_handler_t *h) -{ - struct rad_req_t *req = container_of(h, typeof(*req), hnd); - struct rad_packet_t *pack; - int r; - - if (req->reply) { - rad_packet_free(req->reply); - req->reply = NULL; - } - - while (1) { - r = rad_packet_recv(h->fd, &pack, NULL); - - if (pack) { - if (req->reply) - rad_packet_free(req->reply); - req->reply = pack; - if (conf_interim_verbose) { - log_ppp_info2("recv "); - rad_packet_print(req->reply, log_ppp_info2); - } - } - - if (r) - break; - } - - if (!req->reply) - return 0; - - if (req->reply->code != CODE_ACCOUNTING_RESPONSE || req->reply->id != req->pack->id) { - rad_packet_free(req->reply); - req->reply = NULL; - } else { - if (req->timeout.tpd) - triton_timer_del(&req->timeout); - } - - return 0; -} - -static void rad_acct_timeout(struct triton_timer_t *t) -{ - struct rad_req_t *req = container_of(t, typeof(*req), timeout); - time_t ts, dt; - - __sync_add_and_fetch(&stat_interim_lost, 1); - - time(&ts); - - dt = ts - req->rpd->acct_timestamp; - - if (dt > conf_acct_timeout) { - log_ppp_warn("radius:acct: no response, terminating session...\n"); - ppp_terminate(req->rpd->ppp, TERM_NAS_ERROR, 0); - return; - } - if (dt > conf_acct_timeout / 2) { - req->timeout.period += 1000; - triton_timer_mod(&req->timeout, 0); - } else if (dt > conf_acct_timeout / 3) { - if (req->timeout.period != conf_timeout * 2000) { - req->timeout.period = conf_timeout * 2000; - triton_timer_mod(&req->timeout, 0); - } - } - - req->pack->id++; - - rad_packet_change_int(req->pack, NULL, "Acct-Delay-Time", dt); - req_set_RA(req, conf_acct_secret); - rad_req_send(req, conf_interim_verbose); - __sync_add_and_fetch(&stat_interim_sent, 1); -} - -static void rad_acct_interim_update(struct triton_timer_t *t) -{ - struct radius_pd_t *rpd = container_of(t, typeof(*rpd), acct_interim_timer); - - if (rpd->acct_req->timeout.tpd) - return; - - req_set_stat(rpd->acct_req, rpd->ppp); - if (!rpd->acct_interim_interval) - return; - - time(&rpd->acct_timestamp); - rpd->acct_req->pack->id++; - - rad_packet_change_val(rpd->acct_req->pack, NULL, "Acct-Status-Type", "Interim-Update"); - rad_packet_change_int(rpd->acct_req->pack, NULL, "Acct-Delay-Time", 0); - req_set_RA(rpd->acct_req, conf_acct_secret); - rad_req_send(rpd->acct_req, conf_interim_verbose); - __sync_add_and_fetch(&stat_interim_sent, 1); - if (conf_acct_timeout) { - rpd->acct_req->timeout.period = conf_timeout * 1000; - triton_timer_add(rpd->ppp->ctrl->ctx, &rpd->acct_req->timeout, 0); - } -} - -int rad_acct_start(struct radius_pd_t *rpd) -{ - int i; - time_t ts; - - rpd->acct_req = rad_req_alloc(rpd, CODE_ACCOUNTING_REQUEST, rpd->ppp->username); - if (!rpd->acct_req) { - log_emerg("radius: out of memory\n"); - return -1; - } - - if (rad_req_acct_fill(rpd->acct_req)) { - log_ppp_error("radius:acct: failed to fill accounting attributes\n"); - goto out_err; - } - - //if (rad_req_add_val(rpd->acct_req, "Acct-Status-Type", "Start", 4)) - // goto out_err; - //if (rad_req_add_str(rpd->acct_req, "Acct-Session-Id", rpd->ppp->sessionid, PPP_SESSIONID_LEN, 1)) - // goto out_err; - - if (rpd->acct_req->reply) { - rad_packet_free(rpd->acct_req->reply); - rpd->acct_req->reply = NULL; - } - - time(&rpd->acct_timestamp); - - for (i = 0; i < conf_max_try; i++) { - time(&ts); - rad_packet_change_int(rpd->acct_req->pack, NULL, "Acct-Delay-Time", ts - rpd->acct_timestamp); - if (req_set_RA(rpd->acct_req, conf_acct_secret)) - goto out_err; - if (rad_req_send(rpd->acct_req, conf_verbose)) - goto out_err; - __sync_add_and_fetch(&stat_acct_sent, 1); - rad_req_wait(rpd->acct_req, conf_timeout); - if (!rpd->acct_req->reply) { - rpd->acct_req->pack->id++; - __sync_add_and_fetch(&stat_acct_lost, 1); - continue; - } - if (rpd->acct_req->reply->id != rpd->acct_req->pack->id || rpd->acct_req->reply->code != CODE_ACCOUNTING_RESPONSE) { - rad_packet_free(rpd->acct_req->reply); - rpd->acct_req->reply = NULL; - rpd->acct_req->pack->id++; - __sync_add_and_fetch(&stat_acct_lost, 1); - } else - break; - } - - if (!rpd->acct_req->reply) { - log_ppp_warn("radius:acct_start: no response\n"); - goto out_err; - } - - rpd->acct_req->hnd.read = rad_acct_read; - - triton_md_register_handler(rpd->ppp->ctrl->ctx, &rpd->acct_req->hnd); - if (triton_md_enable_handler(&rpd->acct_req->hnd, MD_MODE_READ)) - goto out_err; - - rpd->acct_req->timeout.expire = rad_acct_timeout; - rpd->acct_req->timeout.period = conf_timeout * 1000; - - rpd->acct_interim_timer.expire = rad_acct_interim_update; - rpd->acct_interim_timer.period = rpd->acct_interim_interval ? rpd->acct_interim_interval * 1000 : STAT_UPDATE_INTERVAL; - if (rpd->acct_interim_interval && triton_timer_add(rpd->ppp->ctrl->ctx, &rpd->acct_interim_timer, 0)) { - triton_md_unregister_handler(&rpd->acct_req->hnd); - triton_timer_del(&rpd->acct_req->timeout); - goto out_err; - } - return 0; - -out_err: - rad_req_free(rpd->acct_req); - rpd->acct_req = NULL; - return -1; -} - -void rad_acct_stop(struct radius_pd_t *rpd) -{ - int i; - time_t ts; - - if (rpd->acct_interim_timer.tpd) - triton_timer_del(&rpd->acct_interim_timer); - - if (rpd->acct_req) { - triton_md_unregister_handler(&rpd->acct_req->hnd); - if (rpd->acct_req->timeout.tpd) - triton_timer_del(&rpd->acct_req->timeout); - - switch (rpd->ppp->terminate_cause) { - case TERM_USER_REQUEST: - rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "User-Request"); - break; - case TERM_SESSION_TIMEOUT: - rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "Session-Timeout"); - break; - case TERM_ADMIN_RESET: - rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "Admin-Reset"); - break; - case TERM_USER_ERROR: - case TERM_AUTH_ERROR: - rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "User-Error"); - break; - case TERM_NAS_ERROR: - rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "NAS-Error"); - break; - case TERM_NAS_REQUEST: - rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "NAS-Request"); - break; - case TERM_NAS_REBOOT: - rad_packet_add_val(rpd->acct_req->pack, NULL, "Acct-Terminate-Cause", "NAS-Reboot"); - break; - } - rad_packet_change_val(rpd->acct_req->pack, NULL, "Acct-Status-Type", "Stop"); - req_set_stat(rpd->acct_req, rpd->ppp); - req_set_RA(rpd->acct_req, conf_acct_secret); - /// !!! rad_req_add_val(rpd->acct_req, "Acct-Terminate-Cause", ""); - - if (rpd->acct_req->reply) { - rad_packet_free(rpd->acct_req->reply); - rpd->acct_req->reply = NULL; - } - - time(&rpd->acct_timestamp); - - for(i = 0; i < conf_max_try; i++) { - time(&ts); - rad_packet_change_int(rpd->acct_req->pack, NULL, "Acct-Delay-Time", ts - rpd->acct_timestamp); - rpd->acct_req->pack->id++; - if (req_set_RA(rpd->acct_req, conf_acct_secret)) - break; - if (rad_req_send(rpd->acct_req, conf_verbose)) - break; - __sync_add_and_fetch(&stat_acct_sent, 1); - rad_req_wait(rpd->acct_req, conf_timeout); - if (!rpd->acct_req->reply) { - __sync_add_and_fetch(&stat_acct_lost, 1); - continue; - } - if (rpd->acct_req->reply->id != rpd->acct_req->pack->id || rpd->acct_req->reply->code != CODE_ACCOUNTING_RESPONSE) { - rad_packet_free(rpd->acct_req->reply); - rpd->acct_req->reply = NULL; - __sync_add_and_fetch(&stat_acct_lost, 1); - } else - break; - } - if (!rpd->acct_req->reply) - log_ppp_warn("radius:acct_stop: no response\n"); - - rad_req_free(rpd->acct_req); - rpd->acct_req = NULL; - } -} - diff --git a/accel-pptpd/radius/attr_defs.h b/accel-pptpd/radius/attr_defs.h deleted file mode 100644 index e9b617e..0000000 --- a/accel-pptpd/radius/attr_defs.h +++ /dev/null @@ -1,287 +0,0 @@ -#define User_Name 1 -#define User_Password 2 -#define CHAP_Password 3 -#define NAS_IP_Address 4 -#define NAS_Port 5 -#define Service_Type 6 -#define Framed_Protocol 7 -#define Framed_IP_Address 8 -#define Framed_IP_Netmask 9 -#define Framed_Routing 10 -#define Filter_Id 11 -#define Framed_MTU 12 -#define Framed_Compression 13 -#define Login_IP_Host 14 -#define Login_Service 15 -#define Login_TCP_Port 16 -#define Reply_Message 18 -#define Callback_Number 19 -#define Callback_Id 20 -#define Framed_Route 22 -#define Framed_IPX_Network 23 -#define State 24 -#define Class 25 -#define Vendor_Specific 26 -#define Session_Timeout 27 -#define Idle_Timeout 28 -#define Termination_Action 29 -#define Called_Station_Id 30 -#define Calling_Station_Id 31 -#define NAS_Identifier 32 -#define Proxy_State 33 -#define Login_LAT_Service 34 -#define Login_LAT_Node 35 -#define Login_LAT_Group 36 -#define Framed_AppleTalk_Link 37 -#define Framed_AppleTalk_Network 38 -#define Framed_AppleTalk_Zone 39 -#define CHAP_Challenge 60 -#define NAS_Port_Type 61 -#define Port_Limit 62 -#define Login_LAT_Port 63 -#define Service_Type_Login_User 1 -#define Service_Type_Framed_User 2 -#define Service_Type_Callback_Login_User 3 -#define Service_Type_Callback_Framed_User 4 -#define Service_Type_Outbound_User 5 -#define Service_Type_Administrative_User 6 -#define Service_Type_NAS_Prompt_User 7 -#define Service_Type_Authenticate_Only 8 -#define Service_Type_Callback_NAS_Prompt 9 -#define Service_Type_Call_Check 10 -#define Service_Type_Callback_Administrative 11 -#define Framed_Protocol_PPP 1 -#define Framed_Protocol_SLIP 2 -#define Framed_Protocol_ARAP 3 -#define Framed_Protocol_Gandalf_SLML 4 -#define Framed_Protocol_Xylogics_IPX_SLIP 5 -#define Framed_Protocol_X_75_Synchronous 6 -#define Framed_Routing_None 0 -#define Framed_Routing_Broadcast 1 -#define Framed_Routing_Listen 2 -#define Framed_Routing_Broadcast_Listen 3 -#define Framed_Compression_None 0 -#define Framed_Compression_Van_Jacobson_TCP_IP 1 -#define Framed_Compression_IPX_Header_Compression 2 -#define Framed_Compression_Stac_LZS 3 -#define Login_Service_Telnet 0 -#define Login_Service_Rlogin 1 -#define Login_Service_TCP_Clear 2 -#define Login_Service_PortMaster 3 -#define Login_Service_LAT 4 -#define Login_Service_X25_PAD 5 -#define Login_Service_X25_T3POS 6 -#define Login_Service_TCP_Clear_Quiet 8 -#define Login_TCP_Port_Telnet 23 -#define Login_TCP_Port_Rlogin 513 -#define Login_TCP_Port_Rsh 514 -#define Termination_Action_Default 0 -#define Termination_Action_RADIUS_Request 1 -#define NAS_Port_Type_Async 0 -#define NAS_Port_Type_Sync 1 -#define NAS_Port_Type_ISDN 2 -#define NAS_Port_Type_ISDN_V120 3 -#define NAS_Port_Type_ISDN_V110 4 -#define NAS_Port_Type_Virtual 5 -#define NAS_Port_Type_PIAFS 6 -#define NAS_Port_Type_HDLC_Clear_Channel 7 -#define NAS_Port_Type_X_25 8 -#define NAS_Port_Type_X_75 9 -#define NAS_Port_Type_G_3_Fax 10 -#define NAS_Port_Type_SDSL 11 -#define NAS_Port_Type_ADSL_CAP 12 -#define NAS_Port_Type_ADSL_DMT 13 -#define NAS_Port_Type_IDSL 14 -#define NAS_Port_Type_Ethernet 15 -#define NAS_Port_Type_xDSL 16 -#define NAS_Port_Type_Cable 17 -#define NAS_Port_Type_Wireless_Other 18 -#define NAS_Port_Type_Wireless_802_11 19 -#define Acct_Status_Type 40 -#define Acct_Delay_Time 41 -#define Acct_Input_Octets 42 -#define Acct_Output_Octets 43 -#define Acct_Session_Id 44 -#define Acct_Authentic 45 -#define Acct_Session_Time 46 -#define Acct_Input_Packets 47 -#define Acct_Output_Packets 48 -#define Acct_Terminate_Cause 49 -#define Acct_Multi_Session_Id 50 -#define Acct_Link_Count 51 -#define Acct_Status_Type_Start 1 -#define Acct_Status_Type_Stop 2 -#define Acct_Status_Type_Alive 3 -#define Acct_Status_Type_Interim_Update 3 -#define Acct_Status_Type_Accounting_On 7 -#define Acct_Status_Type_Accounting_Off 8 -#define Acct_Status_Type_Failed 15 -#define Acct_Authentic_RADIUS 1 -#define Acct_Authentic_Local 2 -#define Acct_Authentic_Remote 3 -#define Acct_Authentic_Diameter 4 -#define Acct_Terminate_Cause_User_Request 1 -#define Acct_Terminate_Cause_Lost_Carrier 2 -#define Acct_Terminate_Cause_Lost_Service 3 -#define Acct_Terminate_Cause_Idle_Timeout 4 -#define Acct_Terminate_Cause_Session_Timeout 5 -#define Acct_Terminate_Cause_Admin_Reset 6 -#define Acct_Terminate_Cause_Admin_Reboot 7 -#define Acct_Terminate_Cause_Port_Error 8 -#define Acct_Terminate_Cause_NAS_Error 9 -#define Acct_Terminate_Cause_NAS_Request 10 -#define Acct_Terminate_Cause_NAS_Reboot 11 -#define Acct_Terminate_Cause_Port_Unneeded 12 -#define Acct_Terminate_Cause_Port_Preempted 13 -#define Acct_Terminate_Cause_Port_Suspended 14 -#define Acct_Terminate_Cause_Service_Unavailable 15 -#define Acct_Terminate_Cause_Callback 16 -#define Acct_Terminate_Cause_User_Error 17 -#define Acct_Terminate_Cause_Host_Request 18 -#define Acct_Tunnel_Connection 68 -#define Acct_Tunnel_Packets_Lost 86 -#define Acct_Status_Type_Tunnel_Start 9 -#define Acct_Status_Type_Tunnel_Stop 10 -#define Acct_Status_Type_Tunnel_Reject 11 -#define Acct_Status_Type_Tunnel_Link_Start 12 -#define Acct_Status_Type_Tunnel_Link_Stop 13 -#define Acct_Status_Type_Tunnel_Link_Reject 14 -#define Tunnel_Type 64 -#define Tunnel_Medium_Type 65 -#define Tunnel_Client_Endpoint 66 -#define Tunnel_Server_Endpoint 67 -#define Tunnel_Password 69 -#define Tunnel_Private_Group_Id 81 -#define Tunnel_Assignment_Id 82 -#define Tunnel_Preference 83 -#define Tunnel_Client_Auth_Id 90 -#define Tunnel_Server_Auth_Id 91 -#define Tunnel_Type_PPTP 1 -#define Tunnel_Type_L2F 2 -#define Tunnel_Type_L2TP 3 -#define Tunnel_Type_ATMP 4 -#define Tunnel_Type_VTP 5 -#define Tunnel_Type_AH 6 -#define Tunnel_Type_IP 7 -#define Tunnel_Type_MIN_IP 8 -#define Tunnel_Type_ESP 9 -#define Tunnel_Type_GRE 10 -#define Tunnel_Type_DVS 11 -#define Tunnel_Type_IP_in_IP 12 -#define Tunnel_Medium_Type_IP 1 -#define Tunnel_Medium_Type_IPv4 1 -#define Tunnel_Medium_Type_IPv6 2 -#define Tunnel_Medium_Type_NSAP 3 -#define Tunnel_Medium_Type_HDLC 4 -#define Tunnel_Medium_Type_BBN_1822 5 -#define Tunnel_Medium_Type_IEEE_802 6 -#define Tunnel_Medium_Type_E_163 7 -#define Tunnel_Medium_Type_E_164 8 -#define Tunnel_Medium_Type_F_69 9 -#define Tunnel_Medium_Type_X_121 10 -#define Tunnel_Medium_Type_IPX 11 -#define Tunnel_Medium_Type_Appletalk 12 -#define Tunnel_Medium_Type_DecNet_IV 13 -#define Tunnel_Medium_Type_Banyan_Vines 14 -#define Tunnel_Medium_Type_E_164_NSAP 15 -#define Acct_Input_Gigawords 52 -#define Acct_Output_Gigawords 53 -#define Event_Timestamp 55 -#define ARAP_Password 70 -#define ARAP_Features 71 -#define ARAP_Zone_Access 72 -#define ARAP_Security 73 -#define ARAP_Security_Data 74 -#define Password_Retry 75 -#define Prompt 76 -#define Connect_Info 77 -#define Configuration_Token 78 -#define EAP_Message 79 -#define Message_Authenticator 80 -#define ARAP_Challenge_Response 84 -#define Acct_Interim_Interval 85 -#define NAS_Port_Id 87 -#define Framed_Pool 88 -#define ARAP_Zone_Access_Default_Zone 1 -#define ARAP_Zone_Access_Zone_Filter_Inclusive 2 -#define ARAP_Zone_Access_Zone_Filter_Exclusive 4 -#define Prompt_No_Echo 0 -#define Prompt_Echo 1 -#define Error_Cause 101 -#define Service_Type_Authorize_Only 17 -#define Error_Cause_Residual_Context_Removed 201 -#define Error_Cause_Invalid_EAP_Packet 202 -#define Error_Cause_Unsupported_Attribute 401 -#define Error_Cause_Missing_Attribute 402 -#define Error_Cause_NAS_Identification_Mismatch 403 -#define Error_Cause_Invalid_Request 404 -#define Error_Cause_Unsupported_Service 405 -#define Error_Cause_Unsupported_Extension 406 -#define Error_Cause_Administratively_Prohibited 501 -#define Error_Cause_Proxy_Request_Not_Routable 502 -#define Error_Cause_Session_Context_Not_Found 503 -#define Error_Cause_Session_Context_Not_Removable 504 -#define Error_Cause_Proxy_Processing_Error 505 -#define Error_Cause_Resources_Unavailable 506 -#define Error_Cause_Request_Initiated 507 -#define Acct_Terminate_Cause_Supplicant_Restart 19 -#define Acct_Terminate_Cause_Reauthentication_Failure 20 -#define Acct_Terminate_Cause_Port_Reinit 21 -#define Acct_Terminate_Cause_Port_Disabled 22 -#define NAS_Port_Type_Token_Ring 20 -#define NAS_Port_Type_FDDI 21 -#define Tunnel_Type_VLAN 13 -#define EAP_Key_Name 102 -#define Chargeable_User_Identity 89 -#define Error_Cause_Invalid_Attribute_Value 407 -#define Error_Cause_Multiple_Session_Selection_Unsupported 508 -#define Vendor_Microsoft 311 -#define MS_CHAP_Response 1 -#define MS_CHAP_Error 2 -#define MS_CHAP_CPW_1 3 -#define MS_CHAP_CPW_2 4 -#define MS_CHAP_LM_Enc_PW 5 -#define MS_CHAP_NT_Enc_PW 6 -#define MS_MPPE_Encryption_Policy 7 -#define MS_MPPE_Encryption_Type 8 -#define MS_MPPE_Encryption_Types 8 -#define MS_RAS_Vendor 9 -#define MS_CHAP_Domain 10 -#define MS_CHAP_Challenge 11 -#define MS_CHAP_MPPE_Keys 12 -#define MS_BAP_Usage 13 -#define MS_Link_Utilization_Threshold 14 -#define MS_Link_Drop_Time_Limit 15 -#define MS_MPPE_Send_Key 16 -#define MS_MPPE_Recv_Key 17 -#define MS_RAS_Version 18 -#define MS_Old_ARAP_Password 19 -#define MS_New_ARAP_Password 20 -#define MS_ARAP_PW_Change_Reason 21 -#define MS_Filter 22 -#define MS_Acct_Auth_Type 23 -#define MS_Acct_EAP_Type 24 -#define MS_CHAP2_Response 25 -#define MS_CHAP2_Success 26 -#define MS_CHAP2_CPW 27 -#define MS_Primary_DNS_Server 28 -#define MS_Secondary_DNS_Server 29 -#define MS_Primary_NBNS_Server 30 -#define MS_Secondary_NBNS_Server 31 -#define MS_BAP_Usage_Not_Allowed 0 -#define MS_BAP_Usage_Allowed 1 -#define MS_BAP_Usage_Required 2 -#define MS_ARAP_PW_Change_Reason_Just_Change_Password 1 -#define MS_ARAP_PW_Change_Reason_Expired_Password 2 -#define MS_ARAP_PW_Change_Reason_Admin_Requires_Password_Change 3 -#define MS_ARAP_PW_Change_Reason_Password_Too_Short 4 -#define MS_Acct_Auth_Type_PAP 1 -#define MS_Acct_Auth_Type_CHAP 2 -#define MS_Acct_Auth_Type_MS_CHAP_1 3 -#define MS_Acct_Auth_Type_MS_CHAP_2 4 -#define MS_Acct_Auth_Type_EAP 5 -#define MS_Acct_EAP_Type_MD5 4 -#define MS_Acct_EAP_Type_OTP 5 -#define MS_Acct_EAP_Type_Generic_Token_Card 6 -#define MS_Acct_EAP_Type_TLS 13 -#define Traffic_Shape_in 231 diff --git a/accel-pptpd/radius/auth.c b/accel-pptpd/radius/auth.c deleted file mode 100644 index 692830e..0000000 --- a/accel-pptpd/radius/auth.c +++ /dev/null @@ -1,497 +0,0 @@ -#include -#include -#include -#include - -#include "triton.h" -#include "events.h" -#include "log.h" -#include "pwdb.h" - -#include "radius_p.h" -#include "attr_defs.h" - -#include "memdebug.h" - -static int decrypt_chap_mppe_keys(struct rad_req_t *req, struct rad_attr_t *attr, const uint8_t *challenge, uint8_t *key) -{ - MD5_CTX md5_ctx; - SHA_CTX sha1_ctx; - uint8_t md5[MD5_DIGEST_LENGTH]; - uint8_t sha1[SHA_DIGEST_LENGTH]; - uint8_t plain[32]; - int i; - - if (attr->len != 32) { - log_ppp_warn("radius: %s: incorrect attribute length (%i)\n", attr->attr->name, attr->len); - return -1; - } - - memcpy(plain, attr->val.octets, 32); - - MD5_Init(&md5_ctx); - MD5_Update(&md5_ctx, conf_auth_secret, strlen(conf_auth_secret)); - MD5_Update(&md5_ctx, req->pack->buf + 4, 16); - MD5_Final(md5, &md5_ctx); - - for (i = 0; i < 16; i++) - plain[i] ^= md5[i]; - - MD5_Init(&md5_ctx); - MD5_Update(&md5_ctx, conf_auth_secret, strlen(conf_auth_secret)); - MD5_Update(&md5_ctx, attr->val.octets, 16); - MD5_Final(md5, &md5_ctx); - - for (i = 0; i < 16; i++) - plain[i + 16] ^= md5[i]; - - SHA1_Init(&sha1_ctx); - SHA1_Update(&sha1_ctx, plain + 8, 16); - SHA1_Update(&sha1_ctx, plain + 8, 16); - SHA1_Update(&sha1_ctx, challenge, 8); - SHA1_Final(sha1, &sha1_ctx); - - memcpy(key, sha1, 16); - - return 0; -} - -static int decrypt_mppe_key(struct rad_req_t *req, struct rad_attr_t *attr, uint8_t *key) -{ - MD5_CTX md5_ctx; - uint8_t md5[16]; - uint8_t plain[32]; - int i; - - if (attr->len != 34) { - log_ppp_warn("radius: %s: incorrect attribute length (%i)\n", attr->attr->name, attr->len); - return -1; - } - - if ((attr->val.octets[0] & 0x80) == 0) { - log_ppp_warn("radius: %s: incorrect salt value (%x)\n", attr->attr->name, attr->len); - return -1; - } - - MD5_Init(&md5_ctx); - MD5_Update(&md5_ctx, conf_auth_secret, strlen(conf_auth_secret)); - MD5_Update(&md5_ctx, req->pack->buf + 4, 16); - MD5_Update(&md5_ctx, attr->val.octets, 2); - MD5_Final(md5, &md5_ctx); - - memcpy(plain, attr->val.octets + 2, 32); - - for (i = 0; i < 16; i++) - plain[i] ^= md5[i]; - - if (plain[0] != 16) { - log_ppp_warn("radius: %s: incorrect key length (%i)\n", attr->attr->name, plain[0]); - return -1; - } - - MD5_Init(&md5_ctx); - MD5_Update(&md5_ctx, conf_auth_secret, strlen(conf_auth_secret)); - MD5_Update(&md5_ctx, attr->val.octets + 2, 16); - MD5_Final(md5, &md5_ctx); - - plain[16] ^= md5[0]; - - memcpy(key, plain + 1, 16); - - return 0; -} - - -static uint8_t* encrypt_password(const char *passwd, const char *secret, const uint8_t *RA, int *epasswd_len) -{ - uint8_t *epasswd; - int i, j, chunk_cnt; - uint8_t b[16], c[16]; - MD5_CTX ctx; - - if (strlen(passwd)) - chunk_cnt = (strlen(passwd) - 1) / 16 + 1; - else { - *epasswd_len = 0; - return (uint8_t *)1; - } - - epasswd = _malloc(chunk_cnt * 16); - if (!epasswd) { - log_emerg("radius: out of memory\n"); - return NULL; - } - - memset(epasswd, 0, chunk_cnt * 16); - memcpy(epasswd, passwd, strlen(passwd)); - memcpy(c, RA, 16); - - for (i = 0; i < chunk_cnt; i++) { - MD5_Init(&ctx); - MD5_Update(&ctx, secret, strlen(secret)); - MD5_Update(&ctx, c, 16); - MD5_Final(b, &ctx); - - for(j = 0; j < 16; j++) - epasswd[i * 16 + j] ^= b[j]; - - memcpy(c, epasswd + i * 16, 16); - } - - *epasswd_len = chunk_cnt * 16; - return epasswd; -} - -static int rad_auth_send(struct rad_req_t *req) -{ - int i; - - for(i = 0; i < conf_max_try; i++) { - __sync_add_and_fetch(&stat_auth_sent, 1); - if (rad_req_send(req, conf_verbose)) - goto out; - - rad_req_wait(req, conf_timeout); - - if (req->reply) { - if (req->reply->id != req->pack->id) { - __sync_add_and_fetch(&stat_auth_lost, 1); - rad_packet_free(req->reply); - req->reply = NULL; - } else - break; - } else - __sync_add_and_fetch(&stat_auth_lost, 1); - } - - if (!req->reply) - log_ppp_warn("radius:auth: no response\n"); - else if (req->reply->code == CODE_ACCESS_ACCEPT) { - if (rad_proc_attrs(req)) - return PWDB_DENIED; - return PWDB_SUCCESS; - } - -out: - return PWDB_DENIED; -} - -int rad_auth_pap(struct radius_pd_t *rpd, const char *username, va_list args) -{ - struct rad_req_t *req; - int r = PWDB_DENIED; - //int id = va_arg(args, int); - const char *passwd = va_arg(args, const char *); - uint8_t *epasswd; - int epasswd_len; - - req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); - if (!req) - return PWDB_DENIED; - - epasswd = encrypt_password(passwd, conf_auth_secret, req->RA, &epasswd_len); - if (!epasswd) - goto out; - - if (rad_packet_add_octets(req->pack, NULL, "User-Password", epasswd, epasswd_len)) { - if (epasswd_len) - _free(epasswd); - goto out; - } - - if (epasswd_len) - _free(epasswd); - - if (conf_sid_in_auth) - if (rad_packet_add_str(req->pack, NULL, "Acct-Session-Id", rpd->ppp->sessionid)) - return -1; - - r = rad_auth_send(req); - if (r == PWDB_SUCCESS) { - struct ev_radius_t ev = { - .ppp = rpd->ppp, - .request = req->pack, - .reply = req->reply, - }; - triton_event_fire(EV_RADIUS_ACCESS_ACCEPT, &ev); - } - -out: - rad_req_free(req); - - return r; -} - -int rad_auth_chap_md5(struct radius_pd_t *rpd, const char *username, va_list args) -{ - int r = PWDB_DENIED; - uint8_t chap_password[17]; - - int id = va_arg(args, int); - uint8_t *challenge = va_arg(args, uint8_t *); - int challenge_len = va_arg(args, int); - uint8_t *response = va_arg(args, uint8_t *); - - chap_password[0] = id; - memcpy(chap_password + 1, response, 16); - - if (!rpd->auth_req) { - rpd->auth_req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); - if (!rpd->auth_req) - return PWDB_DENIED; - - if (challenge_len == 16) - memcpy(rpd->auth_req->RA, challenge, 16); - else { - if (rad_packet_add_octets(rpd->auth_req->pack, NULL, "CHAP-Challenge", challenge, challenge_len)) - goto out; - } - - if (rad_packet_add_octets(rpd->auth_req->pack, NULL, "CHAP-Password", chap_password, 17)) - goto out; - } else { - if (challenge_len == 16) - memcpy(rpd->auth_req->RA, challenge, 16); - else { - if (rad_packet_change_octets(rpd->auth_req->pack, NULL, "CHAP-Challenge", challenge, challenge_len)) - goto out; - } - - if (rad_packet_change_octets(rpd->auth_req->pack, NULL, "CHAP-Password", chap_password, 17)) - goto out; - - if (rpd->attr_state) { - if (rad_packet_find_attr(rpd->auth_req->pack, NULL, "State")) { - if (rad_packet_change_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) - goto out; - } else { - if (rad_packet_add_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) - goto out; - } - } - - if (rad_packet_build(rpd->auth_req->pack, rpd->auth_req->RA)) - return -1; - } - - if (conf_sid_in_auth) - if (rad_packet_add_str(rpd->auth_req->pack, NULL, "Acct-Session-Id", rpd->ppp->sessionid)) - goto out; - - r = rad_auth_send(rpd->auth_req); - if (r == PWDB_SUCCESS) { - struct ev_radius_t ev = { - .ppp = rpd->ppp, - .request = rpd->auth_req->pack, - .reply = rpd->auth_req->reply, - }; - triton_event_fire(EV_RADIUS_ACCESS_ACCEPT, &ev); - rpd->auth_req->pack->id++; - } - - return r; -out: - rad_req_free(rpd->auth_req); - rpd->auth_req = NULL; - - return r; -} - -static void setup_mppe(struct rad_req_t *req, const uint8_t *challenge) -{ - struct rad_attr_t *attr; - uint8_t mppe_recv_key[16]; - uint8_t mppe_send_key[16]; - struct ev_mppe_keys_t ev_mppe = { - .ppp = req->rpd->ppp, - }; - - list_for_each_entry(attr, &req->reply->attrs, entry) { - if (attr->vendor && attr->vendor->id == Vendor_Microsoft) { - switch (attr->attr->id) { - case MS_CHAP_MPPE_Keys: - if (decrypt_chap_mppe_keys(req, attr, challenge, mppe_recv_key)) - continue; - ev_mppe.recv_key = mppe_recv_key; - ev_mppe.send_key = mppe_recv_key; - break; - case MS_MPPE_Recv_Key: - if (decrypt_mppe_key(req, attr, mppe_recv_key)) - continue; - ev_mppe.recv_key = mppe_recv_key; - break; - case MS_MPPE_Send_Key: - if (decrypt_mppe_key(req, attr, mppe_send_key)) - continue; - ev_mppe.send_key = mppe_send_key; - break; - case MS_MPPE_Encryption_Policy: - ev_mppe.policy = attr->val.integer; - break; - case MS_MPPE_Encryption_Type: - ev_mppe.type = attr->val.integer; - break; - } - } - } - - if (ev_mppe.recv_key && ev_mppe.send_key) - triton_event_fire(EV_MPPE_KEYS, &ev_mppe); -} - -int rad_auth_mschap_v1(struct radius_pd_t *rpd, const char *username, va_list args) -{ - int r = PWDB_DENIED; - uint8_t response[50]; - - int id = va_arg(args, int); - const uint8_t *challenge = va_arg(args, const uint8_t *); - int challenge_len = va_arg(args, int); - const uint8_t *lm_response = va_arg(args, const uint8_t *); - const uint8_t *nt_response = va_arg(args, const uint8_t *); - int flags = va_arg(args, int); - - response[0] = id; - response[1] = flags; - memcpy(response + 2, lm_response, 24); - memcpy(response + 2 + 24, nt_response, 24); - - if (!rpd->auth_req) { - rpd->auth_req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); - if (!rpd->auth_req) - return PWDB_DENIED; - - if (rad_packet_add_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Challenge", challenge, challenge_len)) - goto out; - - if (rad_packet_add_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Response", response, sizeof(response))) - goto out; - } else { - if (rad_packet_change_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Challenge", challenge, challenge_len)) - goto out; - - if (rad_packet_change_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Response", response, sizeof(response))) - goto out; - - if (rpd->attr_state) { - if (rad_packet_find_attr(rpd->auth_req->pack, NULL, "State")) { - if (rad_packet_change_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) - goto out; - } else { - if (rad_packet_add_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) - goto out; - } - } - - if (rad_packet_build(rpd->auth_req->pack, rpd->auth_req->RA)) - return -1; - } - - if (conf_sid_in_auth) - if (rad_packet_add_str(rpd->auth_req->pack, NULL, "Acct-Session-Id", rpd->ppp->sessionid)) - goto out; - - r = rad_auth_send(rpd->auth_req); - if (r == PWDB_SUCCESS) { - struct ev_radius_t ev = { - .ppp = rpd->ppp, - .request = rpd->auth_req->pack, - .reply = rpd->auth_req->reply, - }; - triton_event_fire(EV_RADIUS_ACCESS_ACCEPT, &ev); - setup_mppe(rpd->auth_req, challenge); - rpd->auth_req->pack->id++; - } - - return r; -out: - rad_req_free(rpd->auth_req); - rpd->auth_req = NULL; - - return r; -} - -int rad_auth_mschap_v2(struct radius_pd_t *rpd, const char *username, va_list args) -{ - int r = PWDB_DENIED; - struct rad_attr_t *ra; - uint8_t mschap_response[50]; - - int id = va_arg(args, int); - const uint8_t *challenge = va_arg(args, const uint8_t *); - const uint8_t *peer_challenge = va_arg(args, const uint8_t *); - const uint8_t *reserved = va_arg(args, const uint8_t *); - const uint8_t *response = va_arg(args, const uint8_t *); - int flags = va_arg(args, int); - uint8_t *authenticator = va_arg(args, uint8_t *); - - mschap_response[0] = id; - mschap_response[1] = flags; - memcpy(mschap_response + 2, peer_challenge, 16); - memcpy(mschap_response + 2 + 16, reserved, 8); - memcpy(mschap_response + 2 + 16 + 8, response, 24); - - if (!rpd->auth_req) { - rpd->auth_req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); - if (!rpd->auth_req) - return PWDB_DENIED; - - if (rad_packet_add_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Challenge", challenge, 16)) - goto out; - - if (rad_packet_add_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP2-Response", mschap_response, sizeof(mschap_response))) - goto out; - } else { - if (rad_packet_change_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP-Challenge", challenge, 16)) - goto out; - - if (rad_packet_change_octets(rpd->auth_req->pack, "Microsoft", "MS-CHAP2-Response", mschap_response, sizeof(mschap_response))) - goto out; - - if (rpd->attr_state) { - if (rad_packet_find_attr(rpd->auth_req->pack, NULL, "State")) { - if (rad_packet_change_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) - goto out; - } else { - if (rad_packet_add_octets(rpd->auth_req->pack, NULL, "State", rpd->attr_state, rpd->attr_state_len)) - goto out; - } - } - - if (rad_packet_build(rpd->auth_req->pack, rpd->auth_req->RA)) - return -1; - } - - if (conf_sid_in_auth) - if (rad_packet_add_str(rpd->auth_req->pack, NULL, "Acct-Session-Id", rpd->ppp->sessionid)) - goto out; - - r = rad_auth_send(rpd->auth_req); - if (r == PWDB_SUCCESS) { - ra = rad_packet_find_attr(rpd->auth_req->reply, "Microsoft", "MS-CHAP2-Success"); - if (!ra) { - log_error("radius:auth:mschap-v2: 'MS-CHAP-Success' not found in radius response\n"); - r = PWDB_DENIED; - } else - memcpy(authenticator, ra->val.octets + 3, 40); - } - if (r == PWDB_SUCCESS) { - struct ev_radius_t ev = { - .ppp = rpd->ppp, - .request = rpd->auth_req->pack, - .reply = rpd->auth_req->reply, - }; - triton_event_fire(EV_RADIUS_ACCESS_ACCEPT, &ev); - setup_mppe(rpd->auth_req, NULL); - rpd->auth_req->pack->id++; - } - - return r; -out: - rad_req_free(rpd->auth_req); - rpd->auth_req = NULL; - - return r; -} - - diff --git a/accel-pptpd/radius/dict.c b/accel-pptpd/radius/dict.c deleted file mode 100644 index 9704569..0000000 --- a/accel-pptpd/radius/dict.c +++ /dev/null @@ -1,356 +0,0 @@ -#include -#include -#include -#include -#include - -#include "list.h" -#include "radius_p.h" -#include "log.h" - -#include "memdebug.h" - -static struct rad_dict_t *dict; - -static char *skip_word(char *ptr) -{ - for(; *ptr; ptr++) - if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') - break; - return ptr; -} -static char *skip_space(char *ptr) -{ - for(; *ptr; ptr++) - if (*ptr != ' ' && *ptr != '\t') - break; - return ptr; -} -static int split(char *buf, char **ptr) -{ - int i; - - for (i = 0; i < 3; i++) { - buf = skip_word(buf); - if (!*buf) - return i; - - *buf = 0; - - buf = skip_space(buf + 1); - if (!*buf) - return i; - - ptr[i] = buf; - } - - buf = skip_word(buf); - //if (*buf == '\n') - *buf = 0; - //else if (*buf) - // return -1; - - return i; -} - -struct rad_dict_attr_t *find_attr(struct list_head *items, const char *name) -{ - struct rad_dict_attr_t *attr; - - list_for_each_entry(attr, items, entry) - if (!strcmp(attr->name, name)) - return attr; - - return NULL; -} - -#define BUF_SIZE 1024 - -static char *path, *fname1, *buf; -static int dict_load(const char *fname) -{ - FILE *f; - char *ptr[3], *endptr; - int r, n = 0; - struct rad_dict_attr_t *attr; - struct rad_dict_value_t *val; - struct rad_dict_vendor_t *vendor; - struct list_head *items; - - f = fopen(fname, "r"); - if (!f) { - log_emerg("radius: open dictioanary '%s': %s\n", fname, strerror(errno)); - return -1; - } - - items = &dict->items; - - while (fgets(buf, BUF_SIZE, f)) { - n++; - if (buf[0] == '#' || buf[0] == '\n' || buf[0] == 0) - continue; - r = split(buf, ptr); - if (r == 1) { - if (!strcmp(buf, "BEGIN-VENDOR")) { - vendor = rad_dict_find_vendor_name(ptr[0]); - if (!vendor) { - log_emerg("radius:%s:%i: vendor not found\n", fname, n); - goto out_err; - } - items = &vendor->items; - } else if (!strcmp(buf, "END-VENDOR")) - items = &dict->items; - else if (!strcmp(buf, "$INCLUDE")) { - for (r = strlen(path) - 1; r; r--) - if (path[r] == '/') { - path[r + 1] = 0; - break; - } - strcpy(fname1, path); - strcat(fname1, ptr[0]); - if (dict_load(fname1)) - goto out_err; - } else - goto out_err_syntax; - } else if (r == 2) { - if (!strcmp(buf, "VENDOR")) { - vendor = malloc(sizeof(*vendor)); - if (!vendor) { - log_emerg("radius: out of memory\n"); - goto out_err; - } - vendor->id = strtol(ptr[1], &endptr, 10); - if (*endptr != 0) - goto out_err_syntax; - vendor->name = strdup(ptr[0]); - if (!vendor->name) { - log_emerg("radius: out of memory\n"); - goto out_err; - } - INIT_LIST_HEAD(&vendor->items); - list_add_tail(&vendor->entry, &dict->vendors); - } else - goto out_err_syntax; - } else if (r == 3) { - if (!strcmp(buf, "ATTRIBUTE")) { - attr = malloc(sizeof(*attr)); - if (!attr) { - log_emerg("radius: out of memory\n"); - goto out_err; - } - memset(attr, 0, sizeof(*attr)); - INIT_LIST_HEAD(&attr->values); - list_add_tail(&attr->entry, items); - attr->name = strdup(ptr[0]); - attr->id = strtol(ptr[1], &endptr, 10); - if (*endptr != 0) - goto out_err_syntax; - if (!strcmp(ptr[2], "integer")) - attr->type = ATTR_TYPE_INTEGER; - else if (!strcmp(ptr[2], "string")) - attr->type = ATTR_TYPE_STRING; - else if (!strcmp(ptr[2], "date")) - attr->type = ATTR_TYPE_DATE; - else if (!strcmp(ptr[2], "ipaddr")) - attr->type = ATTR_TYPE_IPADDR; - else if (!strcmp(ptr[2], "octets")) - attr->type = ATTR_TYPE_OCTETS; - else { - log_emerg("radius:%s:%i: unknown attribute type\n", fname, n); - goto out_err; - } - } else if (!strcmp(buf, "VALUE")) { - attr = find_attr(items, ptr[0]); - if (!attr) { - log_emerg("radius:%s:%i: unknown attribute\n", fname, n); - goto out_err; - } - val = malloc(sizeof(*val)); - if (!val) { - log_emerg("radius: out of memory\n"); - goto out_err; - } - memset(val, 0, sizeof(*val)); - list_add_tail(&val->entry, &attr->values); - val->name = strdup(ptr[1]); - switch (attr->type) { - case ATTR_TYPE_INTEGER: - val->val.integer = strtol(ptr[2], &endptr, 10); - if (*endptr != 0) - goto out_err_syntax; - break; - case ATTR_TYPE_STRING: - val->val.string = strdup(ptr[2]); - break; - case ATTR_TYPE_DATE: - log_warn("radius:%s:%i: VALUE of type 'date' is not implemented yet\n", fname, n); - break; - case ATTR_TYPE_IPADDR: - log_warn("radius:%s:%i: VALUE of type 'ipaddr' is not implemented yet\n", fname, n); - break; - } - } else - goto out_err_syntax; - } else - goto out_err_syntax; - } - - fclose(f); - - return 0; - -out_err_syntax: - log_emerg("radius:%s:%i: syntaxis error\n", fname, n); -out_err: - fclose(f); - return -1; -} - -int rad_dict_load(const char *fname) -{ - int r = -1; - - dict = malloc(sizeof(*dict)); - if (!dict) { - log_emerg("radius: out of memory\n"); - return -1; - } - INIT_LIST_HEAD(&dict->items); - INIT_LIST_HEAD(&dict->vendors); - - path = _malloc(PATH_MAX); - if (!path) { - log_emerg("radius: out of memory\n"); - goto out_free_dict; - } - - fname1 = _malloc(PATH_MAX); - if (!fname1) { - log_emerg("radius: out of memory\n"); - goto out_free_path; - } - - buf = _malloc(BUF_SIZE); - if (!buf) { - log_emerg("radius: out of memory\n"); - goto out_free_fname1; - } - - strcpy(path, fname); - - r = dict_load(fname); - -out_free_fname1: - _free(fname1); -out_free_path: - _free(path); -out_free_dict: - if (r) - rad_dict_free(dict); - return r; -} - -void rad_dict_free(struct rad_dict_t *dict) -{ - struct rad_dict_attr_t *attr; - struct rad_dict_value_t *val; - - while (!list_empty(&dict->items)) { - attr = list_entry(dict->items.next, typeof(*attr), entry); - while (!list_empty(&attr->values)) { - val = list_entry(attr->values.next, typeof(*val), entry); - list_del(&val->entry); - _free((char*)val->name); - if (attr->type == ATTR_TYPE_STRING) - _free((char*)val->val.string); - _free(val); - } - list_del(&attr->entry); - _free((char*)attr->name); - _free(attr); - } - free(dict); -} - -static struct rad_dict_attr_t *dict_find_attr(struct list_head *items, const char *name) -{ - struct rad_dict_attr_t *attr; - - list_for_each_entry(attr, items, entry) - if (!strcmp(attr->name, name)) - return attr; - - return NULL; -} - -__export struct rad_dict_attr_t *rad_dict_find_attr(const char *name) -{ - return dict_find_attr(&dict->items, name); -} - -__export struct rad_dict_attr_t *rad_dict_find_attr_id(struct rad_dict_vendor_t *vendor, int id) -{ - struct rad_dict_attr_t *attr; - struct list_head *items = vendor ? &vendor->items : &dict->items; - - list_for_each_entry(attr, items, entry) - if (attr->id == id) - return attr; - - return NULL; -} - -__export struct rad_dict_value_t *rad_dict_find_val_name(struct rad_dict_attr_t *attr, const char *name) -{ - struct rad_dict_value_t *val; - - list_for_each_entry(val, &attr->values, entry) - if (!strcmp(val->name, name)) - return val; - - return NULL; -} - -__export struct rad_dict_value_t *rad_dict_find_val(struct rad_dict_attr_t *attr, rad_value_t v) -{ - struct rad_dict_value_t *val; - - if (attr->type != ATTR_TYPE_INTEGER) - return NULL; - - list_for_each_entry(val, &attr->values, entry) - if (val->val.integer == v.integer) - return val; - - return NULL; -} - -__export struct rad_dict_vendor_t *rad_dict_find_vendor_name(const char *name) -{ - struct rad_dict_vendor_t *vendor; - - list_for_each_entry(vendor, &dict->vendors, entry) { - if (!strcmp(vendor->name, name)) - return vendor; - } - - return NULL; -} - -__export struct rad_dict_vendor_t *rad_dict_find_vendor_id(int id) -{ - struct rad_dict_vendor_t *vendor; - - list_for_each_entry(vendor, &dict->vendors, entry) { - if (vendor->id == id) - return vendor; - } - - return NULL; -} - -__export struct rad_dict_attr_t *rad_dict_find_vendor_attr(struct rad_dict_vendor_t *vendor, const char *name) -{ - return dict_find_attr(&vendor->items, name); -} - diff --git a/accel-pptpd/radius/dict/dictionary b/accel-pptpd/radius/dict/dictionary deleted file mode 100644 index 2797310..0000000 --- a/accel-pptpd/radius/dict/dictionary +++ /dev/null @@ -1,79 +0,0 @@ -# -*- text -*- -# -# Version $Id: dictionary,v 1.155 2008/04/20 14:47:55 aland Exp $ -# -# DO NOT EDIT THE FILES IN THIS DIRECTORY -# -# The files in this directory are maintained and updated by -# the FreeRADIUS project. Newer releases of software may update -# or change these files. -# -# Use the main dictionary file (usually /etc/raddb/dictionary) -# for local system attributes and $INCLUDEs. -# -# -# -# This file contains dictionary translations for parsing -# requests and generating responses. All transactions are -# composed of Attribute/Value Pairs. The value of each attribute -# is specified as one of 4 data types. Valid data types are: -# -# text - printable, generally UTF-8 encoded (subset of 'string') -# string - 0-253 octets -# ipaddr - 4 octets in network byte order -# integer - 32 bit value in big endian order (high byte first) -# date - 32 bit value in big endian order - seconds since -# 00:00:00 GMT, Jan. 1, 1970 -# ifid - 8 octets in network byte order -# ipv6addr - 16 octets in network byte order -# ipv6prefix - 18 octets in network byte order -# ether - 6 octets of hh:hh:hh:hh:hh:hh -# where 'h' is hex digits, upper or lowercase. -# -# FreeRADIUS includes extended data types which are not defined -# in the RFC's. These data types are: -# -# abinary - Ascend's binary filter format. -# octets - raw octets, printed and input as hex strings. -# e.g.: 0x123456789abcdef -# -# -# Enumerated values are stored in the user file with dictionary -# VALUE translations for easy administration. -# -# Example: -# -# ATTRIBUTE VALUE -# --------------- ----- -# Framed-Protocol = PPP -# 7 = 1 (integer encoding) -# - -# -# Include compatibility dictionary for older users file. Move -# this directive to the end of this file if you want to see the -# old names in the logfiles, INSTEAD OF the new names. -# -# -# Include the RFC dictionaries next. -# -# For a complete list of the standard attributes and values, -# see: -# http://www.iana.org/assignments/radius-types -# -$INCLUDE dictionary.rfc2865 -$INCLUDE dictionary.rfc2866 -$INCLUDE dictionary.rfc2867 -$INCLUDE dictionary.rfc2868 -$INCLUDE dictionary.rfc2869 -$INCLUDE dictionary.rfc3576 -$INCLUDE dictionary.rfc3580 -$INCLUDE dictionary.rfc4072 -$INCLUDE dictionary.rfc4372 -$INCLUDE dictionary.rfc4679 -$INCLUDE dictionary.rfc5176 - -$INCLUDE dictionary.microsoft -$INCLUDE dictionary.cisco - -ATTRIBUTE Traffic-Shape-in 231 integer diff --git a/accel-pptpd/radius/dict/dictionary.cisco b/accel-pptpd/radius/dict/dictionary.cisco deleted file mode 100644 index 6d1efbe..0000000 --- a/accel-pptpd/radius/dict/dictionary.cisco +++ /dev/null @@ -1,156 +0,0 @@ -# -*- text -*- -# -# dictionary.cisco -# -# Accounting VSAs originally by -# "Marcelo M. Sosa Lugones" -# -# Version: $Id: dictionary.cisco,v 1.16 2006/06/05 16:55:21 pnixon Exp $ -# -# For documentation on Cisco RADIUS attributes, see: -# -# http://www.cisco.com/univercd/cc/td/doc/product/access/acs_serv/vapp_dev/vsaig3.htm -# -# For general documentation on Cisco RADIUS configuration, see: -# -# http://www.cisco.com/en/US/partner/tech/tk583/tk547/tsd_technology_support_sub-protocol_home.html -# - -VENDOR Cisco 9 - -# -# Standard attribute -# -BEGIN-VENDOR Cisco - -ATTRIBUTE Cisco-AVPair 1 string -ATTRIBUTE Cisco-NAS-Port 2 string - -# -# T.37 Store-and-Forward attributes. -# -ATTRIBUTE Cisco-Fax-Account-Id-Origin 3 string -ATTRIBUTE Cisco-Fax-Msg-Id 4 string -ATTRIBUTE Cisco-Fax-Pages 5 string -ATTRIBUTE Cisco-Fax-Coverpage-Flag 6 string -ATTRIBUTE Cisco-Fax-Modem-Time 7 string -ATTRIBUTE Cisco-Fax-Connect-Speed 8 string -ATTRIBUTE Cisco-Fax-Recipient-Count 9 string -ATTRIBUTE Cisco-Fax-Process-Abort-Flag 10 string -ATTRIBUTE Cisco-Fax-Dsn-Address 11 string -ATTRIBUTE Cisco-Fax-Dsn-Flag 12 string -ATTRIBUTE Cisco-Fax-Mdn-Address 13 string -ATTRIBUTE Cisco-Fax-Mdn-Flag 14 string -ATTRIBUTE Cisco-Fax-Auth-Status 15 string -ATTRIBUTE Cisco-Email-Server-Address 16 string -ATTRIBUTE Cisco-Email-Server-Ack-Flag 17 string -ATTRIBUTE Cisco-Gateway-Id 18 string -ATTRIBUTE Cisco-Call-Type 19 string -ATTRIBUTE Cisco-Port-Used 20 string -ATTRIBUTE Cisco-Abort-Cause 21 string - -# -# Voice over IP attributes. -# -ATTRIBUTE h323-remote-address 23 string -ATTRIBUTE h323-conf-id 24 string -ATTRIBUTE h323-setup-time 25 string -ATTRIBUTE h323-call-origin 26 string -ATTRIBUTE h323-call-type 27 string -ATTRIBUTE h323-connect-time 28 string -ATTRIBUTE h323-disconnect-time 29 string -ATTRIBUTE h323-disconnect-cause 30 string -ATTRIBUTE h323-voice-quality 31 string -ATTRIBUTE h323-gw-id 33 string -ATTRIBUTE h323-incoming-conf-id 35 string - -ATTRIBUTE h323-credit-amount 101 string -ATTRIBUTE h323-credit-time 102 string -ATTRIBUTE h323-return-code 103 string -ATTRIBUTE h323-prompt-id 104 string -ATTRIBUTE h323-time-and-day 105 string -ATTRIBUTE h323-redirect-number 106 string -ATTRIBUTE h323-preferred-lang 107 string -ATTRIBUTE h323-redirect-ip-address 108 string -ATTRIBUTE h323-billing-model 109 string -ATTRIBUTE h323-currency 110 string -ATTRIBUTE subscriber 111 string -ATTRIBUTE gw-rxd-cdn 112 string -ATTRIBUTE gw-final-xlated-cdn 113 string -ATTRIBUTE remote-media-address 114 string -ATTRIBUTE release-source 115 string -ATTRIBUTE gw-rxd-cgn 116 string -ATTRIBUTE gw-final-xlated-cgn 117 string - -# SIP Attributes -ATTRIBUTE call-id 141 string -ATTRIBUTE session-protocol 142 string -ATTRIBUTE method 143 string -ATTRIBUTE prev-hop-via 144 string -ATTRIBUTE prev-hop-ip 145 string -ATTRIBUTE incoming-req-uri 146 string -ATTRIBUTE outgoing-req-uri 147 string -ATTRIBUTE next-hop-ip 148 string -ATTRIBUTE next-hop-dn 149 string -ATTRIBUTE sip-hdr 150 string - -# -# Extra attributes sent by the Cisco, if you configure -# "radius-server vsa accounting" (requires IOS11.2+). -# -ATTRIBUTE Cisco-Multilink-ID 187 integer -ATTRIBUTE Cisco-Num-In-Multilink 188 integer -ATTRIBUTE Cisco-Pre-Input-Octets 190 integer -ATTRIBUTE Cisco-Pre-Output-Octets 191 integer -ATTRIBUTE Cisco-Pre-Input-Packets 192 integer -ATTRIBUTE Cisco-Pre-Output-Packets 193 integer -ATTRIBUTE Cisco-Maximum-Time 194 integer -ATTRIBUTE Cisco-Disconnect-Cause 195 integer -ATTRIBUTE Cisco-Data-Rate 197 integer -ATTRIBUTE Cisco-PreSession-Time 198 integer -ATTRIBUTE Cisco-PW-Lifetime 208 integer -ATTRIBUTE Cisco-IP-Direct 209 integer -ATTRIBUTE Cisco-PPP-VJ-Slot-Comp 210 integer -ATTRIBUTE Cisco-PPP-Async-Map 212 integer -ATTRIBUTE Cisco-IP-Pool-Definition 217 string -ATTRIBUTE Cisco-Assign-IP-Pool 218 integer -ATTRIBUTE Cisco-Route-IP 228 integer -ATTRIBUTE Cisco-Link-Compression 233 integer -ATTRIBUTE Cisco-Target-Util 234 integer -ATTRIBUTE Cisco-Maximum-Channels 235 integer -ATTRIBUTE Cisco-Data-Filter 242 integer -ATTRIBUTE Cisco-Call-Filter 243 integer -ATTRIBUTE Cisco-Idle-Limit 244 integer -ATTRIBUTE Cisco-Account-Info 250 string -ATTRIBUTE Cisco-Service-Info 251 string -ATTRIBUTE Cisco-Command-Code 252 string -ATTRIBUTE Cisco-Control-Info 253 string -ATTRIBUTE Cisco-Xmit-Rate 255 integer - -VALUE Cisco-Disconnect-Cause Unknown 2 -VALUE Cisco-Disconnect-Cause CLID-Authentication-Failure 4 -VALUE Cisco-Disconnect-Cause No-Carrier 10 -VALUE Cisco-Disconnect-Cause Lost-Carrier 11 -VALUE Cisco-Disconnect-Cause No-Detected-Result-Codes 12 -VALUE Cisco-Disconnect-Cause User-Ends-Session 20 -VALUE Cisco-Disconnect-Cause Idle-Timeout 21 -VALUE Cisco-Disconnect-Cause Exit-Telnet-Session 22 -VALUE Cisco-Disconnect-Cause No-Remote-IP-Addr 23 -VALUE Cisco-Disconnect-Cause Exit-Raw-TCP 24 -VALUE Cisco-Disconnect-Cause Password-Fail 25 -VALUE Cisco-Disconnect-Cause Raw-TCP-Disabled 26 -VALUE Cisco-Disconnect-Cause Control-C-Detected 27 -VALUE Cisco-Disconnect-Cause EXEC-Program-Destroyed 28 -VALUE Cisco-Disconnect-Cause Timeout-PPP-LCP 40 -VALUE Cisco-Disconnect-Cause Failed-PPP-LCP-Negotiation 41 -VALUE Cisco-Disconnect-Cause Failed-PPP-PAP-Auth-Fail 42 -VALUE Cisco-Disconnect-Cause Failed-PPP-CHAP-Auth 43 -VALUE Cisco-Disconnect-Cause Failed-PPP-Remote-Auth 44 -VALUE Cisco-Disconnect-Cause PPP-Remote-Terminate 45 -VALUE Cisco-Disconnect-Cause PPP-Closed-Event 46 -VALUE Cisco-Disconnect-Cause Session-Timeout 100 -VALUE Cisco-Disconnect-Cause Session-Failed-Security 101 -VALUE Cisco-Disconnect-Cause Session-End-Callback 102 -VALUE Cisco-Disconnect-Cause Invalid-Protocol 120 - -END-VENDOR Cisco diff --git a/accel-pptpd/radius/dict/dictionary.microsoft b/accel-pptpd/radius/dict/dictionary.microsoft deleted file mode 100644 index 9ca6b8e..0000000 --- a/accel-pptpd/radius/dict/dictionary.microsoft +++ /dev/null @@ -1,83 +0,0 @@ -# -*- text -*- -# -# Microsoft's VSA's, from RFC 2548 -# -# $Id: dictionary.microsoft,v 1.8 2005/08/08 22:23:37 aland Exp $ -# - -VENDOR Microsoft 311 - -BEGIN-VENDOR Microsoft -ATTRIBUTE MS-CHAP-Response 1 octets -ATTRIBUTE MS-CHAP-Error 2 string -ATTRIBUTE MS-CHAP-CPW-1 3 octets -ATTRIBUTE MS-CHAP-CPW-2 4 octets -ATTRIBUTE MS-CHAP-LM-Enc-PW 5 octets -ATTRIBUTE MS-CHAP-NT-Enc-PW 6 octets -ATTRIBUTE MS-MPPE-Encryption-Policy 7 integer -# This is referred to as both singular and plural in the RFC. -# Plural seems to make more sense. -ATTRIBUTE MS-MPPE-Encryption-Type 8 integer -ATTRIBUTE MS-MPPE-Encryption-Types 8 integer -ATTRIBUTE MS-RAS-Vendor 9 integer # content is Vendor-ID -ATTRIBUTE MS-CHAP-Domain 10 string -ATTRIBUTE MS-CHAP-Challenge 11 octets -ATTRIBUTE MS-CHAP-MPPE-Keys 12 octets encrypt=1 -ATTRIBUTE MS-BAP-Usage 13 integer -ATTRIBUTE MS-Link-Utilization-Threshold 14 integer # values are 1-100 -ATTRIBUTE MS-Link-Drop-Time-Limit 15 integer -ATTRIBUTE MS-MPPE-Send-Key 16 octets encrypt=2 -ATTRIBUTE MS-MPPE-Recv-Key 17 octets encrypt=2 -ATTRIBUTE MS-RAS-Version 18 string -ATTRIBUTE MS-Old-ARAP-Password 19 octets -ATTRIBUTE MS-New-ARAP-Password 20 octets -ATTRIBUTE MS-ARAP-PW-Change-Reason 21 integer - -ATTRIBUTE MS-Filter 22 octets -ATTRIBUTE MS-Acct-Auth-Type 23 integer -ATTRIBUTE MS-Acct-EAP-Type 24 integer - -ATTRIBUTE MS-CHAP2-Response 25 octets -ATTRIBUTE MS-CHAP2-Success 26 octets -ATTRIBUTE MS-CHAP2-CPW 27 octets - -ATTRIBUTE MS-Primary-DNS-Server 28 ipaddr -ATTRIBUTE MS-Secondary-DNS-Server 29 ipaddr -ATTRIBUTE MS-Primary-NBNS-Server 30 ipaddr -ATTRIBUTE MS-Secondary-NBNS-Server 31 ipaddr - -#ATTRIBUTE MS-ARAP-Challenge 33 octets - -# -# Integer Translations -# - -# MS-BAP-Usage Values - -VALUE MS-BAP-Usage Not-Allowed 0 -VALUE MS-BAP-Usage Allowed 1 -VALUE MS-BAP-Usage Required 2 - -# MS-ARAP-Password-Change-Reason Values - -VALUE MS-ARAP-PW-Change-Reason Just-Change-Password 1 -VALUE MS-ARAP-PW-Change-Reason Expired-Password 2 -VALUE MS-ARAP-PW-Change-Reason Admin-Requires-Password-Change 3 -VALUE MS-ARAP-PW-Change-Reason Password-Too-Short 4 - -# MS-Acct-Auth-Type Values - -VALUE MS-Acct-Auth-Type PAP 1 -VALUE MS-Acct-Auth-Type CHAP 2 -VALUE MS-Acct-Auth-Type MS-CHAP-1 3 -VALUE MS-Acct-Auth-Type MS-CHAP-2 4 -VALUE MS-Acct-Auth-Type EAP 5 - -# MS-Acct-EAP-Type Values - -VALUE MS-Acct-EAP-Type MD5 4 -VALUE MS-Acct-EAP-Type OTP 5 -VALUE MS-Acct-EAP-Type Generic-Token-Card 6 -VALUE MS-Acct-EAP-Type TLS 13 - -END-VENDOR Microsoft diff --git a/accel-pptpd/radius/dict/dictionary.rfc2865 b/accel-pptpd/radius/dict/dictionary.rfc2865 deleted file mode 100644 index 7e5bf58..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc2865 +++ /dev/null @@ -1,137 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 2865. -# http://www.ietf.org/rfc/rfc2865.txt -# -# $Id: dictionary.rfc2865,v 1.3 2005/08/10 20:59:40 aland Exp $ -# -ATTRIBUTE User-Name 1 string -ATTRIBUTE User-Password 2 octets -ATTRIBUTE CHAP-Password 3 octets -ATTRIBUTE NAS-IP-Address 4 ipaddr -ATTRIBUTE NAS-Port 5 integer -ATTRIBUTE Service-Type 6 integer -ATTRIBUTE Framed-Protocol 7 integer -ATTRIBUTE Framed-IP-Address 8 ipaddr -ATTRIBUTE Framed-IP-Netmask 9 ipaddr -ATTRIBUTE Framed-Routing 10 integer -ATTRIBUTE Filter-Id 11 string -ATTRIBUTE Framed-MTU 12 integer -ATTRIBUTE Framed-Compression 13 integer -ATTRIBUTE Login-IP-Host 14 ipaddr -ATTRIBUTE Login-Service 15 integer -ATTRIBUTE Login-TCP-Port 16 integer -# Attribute 17 is undefined -ATTRIBUTE Reply-Message 18 string -ATTRIBUTE Callback-Number 19 string -ATTRIBUTE Callback-Id 20 string -# Attribute 21 is undefined -ATTRIBUTE Framed-Route 22 string -ATTRIBUTE Framed-IPX-Network 23 ipaddr -ATTRIBUTE State 24 octets -ATTRIBUTE Class 25 octets -ATTRIBUTE Vendor-Specific 26 octets -ATTRIBUTE Session-Timeout 27 integer -ATTRIBUTE Idle-Timeout 28 integer -ATTRIBUTE Termination-Action 29 integer -ATTRIBUTE Called-Station-Id 30 string -ATTRIBUTE Calling-Station-Id 31 string -ATTRIBUTE NAS-Identifier 32 string -ATTRIBUTE Proxy-State 33 octets -ATTRIBUTE Login-LAT-Service 34 string -ATTRIBUTE Login-LAT-Node 35 string -ATTRIBUTE Login-LAT-Group 36 octets -ATTRIBUTE Framed-AppleTalk-Link 37 integer -ATTRIBUTE Framed-AppleTalk-Network 38 integer -ATTRIBUTE Framed-AppleTalk-Zone 39 string - -ATTRIBUTE CHAP-Challenge 60 octets -ATTRIBUTE NAS-Port-Type 61 integer -ATTRIBUTE Port-Limit 62 integer -ATTRIBUTE Login-LAT-Port 63 integer - -# -# Integer Translations -# - -# Service types - -VALUE Service-Type Login-User 1 -VALUE Service-Type Framed-User 2 -VALUE Service-Type Callback-Login-User 3 -VALUE Service-Type Callback-Framed-User 4 -VALUE Service-Type Outbound-User 5 -VALUE Service-Type Administrative-User 6 -VALUE Service-Type NAS-Prompt-User 7 -VALUE Service-Type Authenticate-Only 8 -VALUE Service-Type Callback-NAS-Prompt 9 -VALUE Service-Type Call-Check 10 -VALUE Service-Type Callback-Administrative 11 - -# Framed Protocols - -VALUE Framed-Protocol PPP 1 -VALUE Framed-Protocol SLIP 2 -VALUE Framed-Protocol ARAP 3 -VALUE Framed-Protocol Gandalf-SLML 4 -VALUE Framed-Protocol Xylogics-IPX-SLIP 5 -VALUE Framed-Protocol X.75-Synchronous 6 - -# Framed Routing Values - -VALUE Framed-Routing None 0 -VALUE Framed-Routing Broadcast 1 -VALUE Framed-Routing Listen 2 -VALUE Framed-Routing Broadcast-Listen 3 - -# Framed Compression Types - -VALUE Framed-Compression None 0 -VALUE Framed-Compression Van-Jacobson-TCP-IP 1 -VALUE Framed-Compression IPX-Header-Compression 2 -VALUE Framed-Compression Stac-LZS 3 - -# Login Services - -VALUE Login-Service Telnet 0 -VALUE Login-Service Rlogin 1 -VALUE Login-Service TCP-Clear 2 -VALUE Login-Service PortMaster 3 -VALUE Login-Service LAT 4 -VALUE Login-Service X25-PAD 5 -VALUE Login-Service X25-T3POS 6 -VALUE Login-Service TCP-Clear-Quiet 8 - -# Login-TCP-Port (see /etc/services for more examples) - -VALUE Login-TCP-Port Telnet 23 -VALUE Login-TCP-Port Rlogin 513 -VALUE Login-TCP-Port Rsh 514 - -# Termination Options - -VALUE Termination-Action Default 0 -VALUE Termination-Action RADIUS-Request 1 - -# NAS Port Types - -VALUE NAS-Port-Type Async 0 -VALUE NAS-Port-Type Sync 1 -VALUE NAS-Port-Type ISDN 2 -VALUE NAS-Port-Type ISDN-V120 3 -VALUE NAS-Port-Type ISDN-V110 4 -VALUE NAS-Port-Type Virtual 5 -VALUE NAS-Port-Type PIAFS 6 -VALUE NAS-Port-Type HDLC-Clear-Channel 7 -VALUE NAS-Port-Type X.25 8 -VALUE NAS-Port-Type X.75 9 -VALUE NAS-Port-Type G.3-Fax 10 -VALUE NAS-Port-Type SDSL 11 -VALUE NAS-Port-Type ADSL-CAP 12 -VALUE NAS-Port-Type ADSL-DMT 13 -VALUE NAS-Port-Type IDSL 14 -VALUE NAS-Port-Type Ethernet 15 -VALUE NAS-Port-Type xDSL 16 -VALUE NAS-Port-Type Cable 17 -VALUE NAS-Port-Type Wireless-Other 18 -VALUE NAS-Port-Type Wireless-802.11 19 diff --git a/accel-pptpd/radius/dict/dictionary.rfc2866 b/accel-pptpd/radius/dict/dictionary.rfc2866 deleted file mode 100644 index 15472bd..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc2866 +++ /dev/null @@ -1,57 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 2866. -# http://www.ietf.org/rfc/rfc2866.txt -# -# $Id: dictionary.rfc2866,v 1.2 2005/08/08 22:23:38 aland Exp $ -# -ATTRIBUTE Acct-Status-Type 40 integer -ATTRIBUTE Acct-Delay-Time 41 integer -ATTRIBUTE Acct-Input-Octets 42 integer -ATTRIBUTE Acct-Output-Octets 43 integer -ATTRIBUTE Acct-Session-Id 44 string -ATTRIBUTE Acct-Authentic 45 integer -ATTRIBUTE Acct-Session-Time 46 integer -ATTRIBUTE Acct-Input-Packets 47 integer -ATTRIBUTE Acct-Output-Packets 48 integer -ATTRIBUTE Acct-Terminate-Cause 49 integer -ATTRIBUTE Acct-Multi-Session-Id 50 string -ATTRIBUTE Acct-Link-Count 51 integer - -# Accounting Status Types - -VALUE Acct-Status-Type Start 1 -VALUE Acct-Status-Type Stop 2 -VALUE Acct-Status-Type Alive 3 # dup -VALUE Acct-Status-Type Interim-Update 3 -VALUE Acct-Status-Type Accounting-On 7 -VALUE Acct-Status-Type Accounting-Off 8 -VALUE Acct-Status-Type Failed 15 - -# Authentication Types - -VALUE Acct-Authentic RADIUS 1 -VALUE Acct-Authentic Local 2 -VALUE Acct-Authentic Remote 3 -VALUE Acct-Authentic Diameter 4 - -# Acct Terminate Causes - -VALUE Acct-Terminate-Cause User-Request 1 -VALUE Acct-Terminate-Cause Lost-Carrier 2 -VALUE Acct-Terminate-Cause Lost-Service 3 -VALUE Acct-Terminate-Cause Idle-Timeout 4 -VALUE Acct-Terminate-Cause Session-Timeout 5 -VALUE Acct-Terminate-Cause Admin-Reset 6 -VALUE Acct-Terminate-Cause Admin-Reboot 7 -VALUE Acct-Terminate-Cause Port-Error 8 -VALUE Acct-Terminate-Cause NAS-Error 9 -VALUE Acct-Terminate-Cause NAS-Request 10 -VALUE Acct-Terminate-Cause NAS-Reboot 11 -VALUE Acct-Terminate-Cause Port-Unneeded 12 -VALUE Acct-Terminate-Cause Port-Preempted 13 -VALUE Acct-Terminate-Cause Port-Suspended 14 -VALUE Acct-Terminate-Cause Service-Unavailable 15 -VALUE Acct-Terminate-Cause Callback 16 -VALUE Acct-Terminate-Cause User-Error 17 -VALUE Acct-Terminate-Cause Host-Request 18 diff --git a/accel-pptpd/radius/dict/dictionary.rfc2867 b/accel-pptpd/radius/dict/dictionary.rfc2867 deleted file mode 100644 index b018aba..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc2867 +++ /dev/null @@ -1,16 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 2867. -# http://www.ietf.org/rfc/rfc2867.txt -# -# $Id: dictionary.rfc2867,v 1.2 2005/08/08 22:23:38 aland Exp $ -# -ATTRIBUTE Acct-Tunnel-Connection 68 string -ATTRIBUTE Acct-Tunnel-Packets-Lost 86 integer - -VALUE Acct-Status-Type Tunnel-Start 9 -VALUE Acct-Status-Type Tunnel-Stop 10 -VALUE Acct-Status-Type Tunnel-Reject 11 -VALUE Acct-Status-Type Tunnel-Link-Start 12 -VALUE Acct-Status-Type Tunnel-Link-Stop 13 -VALUE Acct-Status-Type Tunnel-Link-Reject 14 diff --git a/accel-pptpd/radius/dict/dictionary.rfc2868 b/accel-pptpd/radius/dict/dictionary.rfc2868 deleted file mode 100644 index f6a4047..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc2868 +++ /dev/null @@ -1,54 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 2868. -# http://www.ietf.org/rfc/rfc2868.txt -# -# $Id: dictionary.rfc2868,v 1.4 2007/02/13 13:28:17 aland Exp $ -# -ATTRIBUTE Tunnel-Type 64 integer has_tag -ATTRIBUTE Tunnel-Medium-Type 65 integer has_tag -ATTRIBUTE Tunnel-Client-Endpoint 66 string has_tag -ATTRIBUTE Tunnel-Server-Endpoint 67 string has_tag - -ATTRIBUTE Tunnel-Password 69 string has_tag,encrypt=2 - -ATTRIBUTE Tunnel-Private-Group-Id 81 string has_tag -ATTRIBUTE Tunnel-Assignment-Id 82 string has_tag -ATTRIBUTE Tunnel-Preference 83 integer has_tag - -ATTRIBUTE Tunnel-Client-Auth-Id 90 string has_tag -ATTRIBUTE Tunnel-Server-Auth-Id 91 string has_tag - -# Tunnel Type - -VALUE Tunnel-Type PPTP 1 -VALUE Tunnel-Type L2F 2 -VALUE Tunnel-Type L2TP 3 -VALUE Tunnel-Type ATMP 4 -VALUE Tunnel-Type VTP 5 -VALUE Tunnel-Type AH 6 -VALUE Tunnel-Type IP 7 -VALUE Tunnel-Type MIN-IP 8 -VALUE Tunnel-Type ESP 9 -VALUE Tunnel-Type GRE 10 -VALUE Tunnel-Type DVS 11 -VALUE Tunnel-Type IP-in-IP 12 - -# Tunnel Medium Type - -VALUE Tunnel-Medium-Type IP 1 -VALUE Tunnel-Medium-Type IPv4 1 -VALUE Tunnel-Medium-Type IPv6 2 -VALUE Tunnel-Medium-Type NSAP 3 -VALUE Tunnel-Medium-Type HDLC 4 -VALUE Tunnel-Medium-Type BBN-1822 5 -VALUE Tunnel-Medium-Type IEEE-802 6 -VALUE Tunnel-Medium-Type E.163 7 -VALUE Tunnel-Medium-Type E.164 8 -VALUE Tunnel-Medium-Type F.69 9 -VALUE Tunnel-Medium-Type X.121 10 -VALUE Tunnel-Medium-Type IPX 11 -VALUE Tunnel-Medium-Type Appletalk 12 -VALUE Tunnel-Medium-Type DecNet-IV 13 -VALUE Tunnel-Medium-Type Banyan-Vines 14 -VALUE Tunnel-Medium-Type E.164-NSAP 15 diff --git a/accel-pptpd/radius/dict/dictionary.rfc2869 b/accel-pptpd/radius/dict/dictionary.rfc2869 deleted file mode 100644 index 1a2631e..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc2869 +++ /dev/null @@ -1,39 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 2869. -# http://www.ietf.org/rfc/rfc2869.txt -# -# $Id: dictionary.rfc2869,v 1.2 2005/08/08 22:23:39 aland Exp $ -# -ATTRIBUTE Acct-Input-Gigawords 52 integer -ATTRIBUTE Acct-Output-Gigawords 53 integer - -ATTRIBUTE Event-Timestamp 55 date - -ATTRIBUTE ARAP-Password 70 octets # 16 octets of data -ATTRIBUTE ARAP-Features 71 octets # 14 octets of data -ATTRIBUTE ARAP-Zone-Access 72 integer -ATTRIBUTE ARAP-Security 73 integer -ATTRIBUTE ARAP-Security-Data 74 string -ATTRIBUTE Password-Retry 75 integer -ATTRIBUTE Prompt 76 integer -ATTRIBUTE Connect-Info 77 string -ATTRIBUTE Configuration-Token 78 string -ATTRIBUTE EAP-Message 79 octets -ATTRIBUTE Message-Authenticator 80 octets - -ATTRIBUTE ARAP-Challenge-Response 84 octets # 8 octets of data -ATTRIBUTE Acct-Interim-Interval 85 integer -# 86: RFC 2867 -ATTRIBUTE NAS-Port-Id 87 string -ATTRIBUTE Framed-Pool 88 string - -# ARAP Zone Access - -VALUE ARAP-Zone-Access Default-Zone 1 -VALUE ARAP-Zone-Access Zone-Filter-Inclusive 2 -VALUE ARAP-Zone-Access Zone-Filter-Exclusive 4 - -# Prompt -VALUE Prompt No-Echo 0 -VALUE Prompt Echo 1 diff --git a/accel-pptpd/radius/dict/dictionary.rfc3576 b/accel-pptpd/radius/dict/dictionary.rfc3576 deleted file mode 100644 index 35aeb32..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc3576 +++ /dev/null @@ -1,30 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 3576. -# http://www.ietf.org/rfc/rfc3576.txt -# -# $Id: dictionary.rfc3576,v 1.2 2005/08/08 22:23:39 aland Exp $ -# -ATTRIBUTE Error-Cause 101 integer - -# Service Types - -VALUE Service-Type Authorize-Only 17 - -# Error causes - -VALUE Error-Cause Residual-Context-Removed 201 -VALUE Error-Cause Invalid-EAP-Packet 202 -VALUE Error-Cause Unsupported-Attribute 401 -VALUE Error-Cause Missing-Attribute 402 -VALUE Error-Cause NAS-Identification-Mismatch 403 -VALUE Error-Cause Invalid-Request 404 -VALUE Error-Cause Unsupported-Service 405 -VALUE Error-Cause Unsupported-Extension 406 -VALUE Error-Cause Administratively-Prohibited 501 -VALUE Error-Cause Proxy-Request-Not-Routable 502 -VALUE Error-Cause Session-Context-Not-Found 503 -VALUE Error-Cause Session-Context-Not-Removable 504 -VALUE Error-Cause Proxy-Processing-Error 505 -VALUE Error-Cause Resources-Unavailable 506 -VALUE Error-Cause Request-Initiated 507 diff --git a/accel-pptpd/radius/dict/dictionary.rfc3580 b/accel-pptpd/radius/dict/dictionary.rfc3580 deleted file mode 100644 index 1bd4ca3..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc3580 +++ /dev/null @@ -1,16 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 3580. -# http://www.ietf.org/rfc/rfc3580.txt -# -# $Id: dictionary.rfc3580,v 1.2 2005/08/08 22:23:39 aland Exp $ -# -VALUE Acct-Terminate-Cause Supplicant-Restart 19 -VALUE Acct-Terminate-Cause Reauthentication-Failure 20 -VALUE Acct-Terminate-Cause Port-Reinit 21 -VALUE Acct-Terminate-Cause Port-Disabled 22 - -VALUE NAS-Port-Type Token-Ring 20 -VALUE NAS-Port-Type FDDI 21 - -VALUE Tunnel-Type VLAN 13 diff --git a/accel-pptpd/radius/dict/dictionary.rfc4072 b/accel-pptpd/radius/dict/dictionary.rfc4072 deleted file mode 100644 index 2280d07..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc4072 +++ /dev/null @@ -1,9 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 4072 -# http://www.ietf.org/rfc/4072.txt -# -# $Id: dictionary.rfc4072,v 1.1 2007/11/14 09:00:25 aland Exp $ -# - -ATTRIBUTE EAP-Key-Name 102 string diff --git a/accel-pptpd/radius/dict/dictionary.rfc4372 b/accel-pptpd/radius/dict/dictionary.rfc4372 deleted file mode 100644 index b8af44a..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc4372 +++ /dev/null @@ -1,8 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 4372. -# http://www.ietf.org/rfc/4372.txt -# -# $Id: dictionary.rfc4372,v 1.1 2007/04/07 14:47:34 aland Exp $ -# -ATTRIBUTE Chargeable-User-Identity 89 string diff --git a/accel-pptpd/radius/dict/dictionary.rfc4675 b/accel-pptpd/radius/dict/dictionary.rfc4675 deleted file mode 100644 index 8d1187f..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc4675 +++ /dev/null @@ -1,28 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 4675. -# http://www.ietf.org/rfc/4675.txt -# -# $Id: dictionary.rfc4675,v 1.1 2007/04/07 14:54:14 aland Exp $ -# - -# -# High byte = '1' (0x31) means the frames are tagged. -# High byte = '2' (0x32) means the frames are untagged. -# -# Next 12 bits MUST be zero. -# -# Lower 12 bits is the IEEE-802.1Q VLAN VID. -# -ATTRIBUTE Egress-VLANID 56 integer -ATTRIBUTE Ingress-Filters 57 integer - -# -# First byte == '1' (0x31) means that the frames are tagged. -# First byte == '2' (0x32) means that the frames are untagged. -# -ATTRIBUTE Egress-VLAN-Name 58 string -ATTRIBUTE User-Priority-Table 59 octets # 8 - -VALUE Ingress-Filters Enabled 1 -VALUE Ingress-Filters Disabled 2 diff --git a/accel-pptpd/radius/dict/dictionary.rfc4679 b/accel-pptpd/radius/dict/dictionary.rfc4679 deleted file mode 100644 index 39892a5..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc4679 +++ /dev/null @@ -1,62 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 4679. -# http://www.ietf.org/rfc/4679.txt -# -# $Id: dictionary.rfc4679,v 1.1 2007/04/08 14:18:01 aland Exp $ -# - -VENDOR ADSL-Forum 3561 - -BEGIN-VENDOR ADSL-Forum - -# -# The first two attributes are prefixed with "ADSL-" because of -# conflicting names in dictionary.redback. -# -ATTRIBUTE ADSL-Agent-Circuit-Id 1 string -ATTRIBUTE ADSL-Agent-Remote-Id 2 string -ATTRIBUTE Actual-Data-Rate-Upstream 129 integer -ATTRIBUTE Actual-Data-Rate-Downstream 130 integer -ATTRIBUTE Minimum-Data-Rate-Upstream 131 integer -ATTRIBUTE Minimum-Data-Rate-Downstream 132 integer -ATTRIBUTE Attainable-Data-Rate-Upstream 133 integer -ATTRIBUTE Attainable-Data-Rate-Downstream 134 integer -ATTRIBUTE Maximum-Data-Rate-Upstream 135 integer -ATTRIBUTE Maximum-Data-Rate-Downstream 136 integer -ATTRIBUTE Minimum-Data-Rate-Upstream-Low-Power 137 integer -ATTRIBUTE Minimum-Data-Rate-Downstream-Low-Power 138 integer -ATTRIBUTE Maximum-Interleaving-Delay-Upstream 139 integer -ATTRIBUTE Actual-Interleaving-Delay-Upstream 140 integer -ATTRIBUTE Maximum-Interleaving-Delay-Downstream 141 integer -ATTRIBUTE Actual-Interleaving-Delay-Downstream 142 integer - -# -# This next attribute has a weird encoding. -# -# Octet[0] - 0x01 AAL5 -# Octet[0] - 0x02 Ethernet - -# Octet[1] - 0x00 Not Available -# Octet[1] - 0x01 Untagged Ethernet -# Octet[1] - 0x02 Single-Tagged Ethernet - -# Octet[2] - 0x00 Not available -# Octet[2] - 0x01 PPPoA LLC -# Octet[2] - 0x02 PPPoA Null -# Octet[2] - 0x03 IPoA LLC -# Octet[2] - 0x04 IPoA NULL -# Octet[2] - 0x05 Ethernet over AAL5 LLC with FCS -# Octet[2] - 0x06 Ethernet over AAL5 LLC without FCS -# Octet[2] - 0x07 Ethernet over AAL5 Null with FCS -# Octet[2] - 0x08 Ethernet over AAL5 Null without FCS -# -ATTRIBUTE Access-Loop-Encapsulation 144 octets # 3 - -# -# If this attribute exists, it means that IFW has been performed -# for the subscribers session. -# -ATTRIBUTE IWF-Session 252 octets # 0 - -END-VENDOR ADSL-Forum diff --git a/accel-pptpd/radius/dict/dictionary.rfc4818 b/accel-pptpd/radius/dict/dictionary.rfc4818 deleted file mode 100644 index 4ea5945..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc4818 +++ /dev/null @@ -1,11 +0,0 @@ -# -*- text -*- -############################################################################## -# -# Attributes and values defined in RFC 4818. -# http://www.ietf.org/rfc/rfc4818.txt -# -# $Id: dictionary.rfc4818,v 1.1 2007/05/16 10:06:36 aland Exp $ -# -############################################################################## - -ATTRIBUTE Delegated-IPv6-Prefix 123 ipv6prefix diff --git a/accel-pptpd/radius/dict/dictionary.rfc4849 b/accel-pptpd/radius/dict/dictionary.rfc4849 deleted file mode 100644 index 1738eea..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc4849 +++ /dev/null @@ -1,8 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 4849. -# http://www.ietf.org/rfc/rfc4849.txt -# -# $Id: dictionary.rfc4849,v 1.2 2007/06/15 13:08:03 aland Exp $ -# -ATTRIBUTE NAS-Filter-Rule 92 string diff --git a/accel-pptpd/radius/dict/dictionary.rfc5176 b/accel-pptpd/radius/dict/dictionary.rfc5176 deleted file mode 100644 index 9308961..0000000 --- a/accel-pptpd/radius/dict/dictionary.rfc5176 +++ /dev/null @@ -1,9 +0,0 @@ -# -*- text -*- -# -# Attributes and values defined in RFC 5176. -# http://www.ietf.org/rfc/rfc5176.txt -# -# $Id: dictionary.rfc5176,v 1.1 2008/03/08 16:17:44 aland Exp $ -# -VALUE Error-Cause Invalid-Attribute-Value 407 -VALUE Error-Cause Multiple-Session-Selection-Unsupported 508 diff --git a/accel-pptpd/radius/dict2c.py b/accel-pptpd/radius/dict2c.py deleted file mode 100644 index ff0961e..0000000 --- a/accel-pptpd/radius/dict2c.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys,re - -hdr = file(sys.argv[2],'w') - -def process(fname, hdr): - for line in file(fname): - if line[:-1].strip() == '': - continue - if line[0] == '#': - continue - f = re.compile('[$.a-zA-Z0-9\-]+').findall(line) - if f[0] == 'ATTRIBUTE' or f[0] == 'VENDOR': - hdr.write('#define {0} {1}\n'.format(f[1].replace('-','_').replace('.','_'), f[2])) - elif f[0] == 'VALUE': - hdr.write('#define {0}_{1} {2}\n'.format(f[1].replace('-','_').replace('.','_'), f[2].replace('-','_'),f[3])) - elif f[0] == '$INCLUDE': - process(f[1], hdr) - -if __name__ == '__main__': - process(sys.argv[1], hdr) diff --git a/accel-pptpd/radius/dm_coa.c b/accel-pptpd/radius/dm_coa.c deleted file mode 100644 index 366bb41..0000000 --- a/accel-pptpd/radius/dm_coa.c +++ /dev/null @@ -1,295 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "triton.h" -#include "events.h" -#include "log.h" - -#include "radius_p.h" - -#include "memdebug.h" - -#define PD_COA_PORT 3799 - -struct dm_coa_serv_t -{ - struct triton_context_t ctx; - struct triton_md_handler_t hnd; -}; - -static struct dm_coa_serv_t serv; - -static int dm_coa_check_RA(struct rad_packet_t *pack, const char *secret) -{ - uint8_t RA[16]; - MD5_CTX ctx; - - memset(RA, 0, 16); - - MD5_Init(&ctx); - MD5_Update(&ctx, pack->buf, 4); - MD5_Update(&ctx, RA, 16); - MD5_Update(&ctx, pack->buf + 20, pack->len - 20); - MD5_Update(&ctx, secret, strlen(secret)); - MD5_Final(RA, &ctx); - - return memcmp(RA, pack->buf + 4, 16); -} - -static void dm_coa_set_RA(struct rad_packet_t *pack, const char *secret) -{ - MD5_CTX ctx; - - MD5_Init(&ctx); - MD5_Update(&ctx, pack->buf, pack->len); - MD5_Update(&ctx, secret, strlen(secret)); - MD5_Final(pack->buf + 4, &ctx); -} - -static int dm_coa_send_ack(int fd, struct rad_packet_t *req, struct sockaddr_in *addr) -{ - struct rad_packet_t *reply; - uint8_t RA[16]; - - memcpy(RA, req->buf + 4, sizeof(RA)); - - reply = rad_packet_alloc(req->code == CODE_COA_REQUEST ? CODE_COA_ACK : CODE_DISCONNECT_ACK); - if (!reply) - return -1; - - reply->id = req->id; - - if (rad_packet_build(reply, RA)) { - rad_packet_free(reply); - return -1; - } - - dm_coa_set_RA(reply, conf_dm_coa_secret); - - if (conf_verbose) { - log_ppp_info2("send "); - rad_packet_print(reply, log_ppp_info2); - } - - rad_packet_send(reply, fd, addr); - - rad_packet_free(reply); - - return 0; -} - -static int dm_coa_send_nak(int fd, struct rad_packet_t *req, struct sockaddr_in *addr, int err_code) -{ - struct rad_packet_t *reply; - uint8_t RA[16]; - - memcpy(RA, req->buf + 4, sizeof(RA)); - - reply = rad_packet_alloc(req->code == CODE_COA_REQUEST ? CODE_COA_NAK : CODE_DISCONNECT_NAK); - if (!reply) - return -1; - - reply->id = req->id; - - if (err_code) - rad_packet_add_int(reply, NULL, "Error-Cause", err_code); - - if (rad_packet_build(reply, RA)) { - rad_packet_free(reply); - return -1; - } - - dm_coa_set_RA(reply, conf_dm_coa_secret); - - if (conf_verbose) { - log_ppp_info2("send "); - rad_packet_print(reply, log_ppp_info2); - } - - rad_packet_send(reply, fd, addr); - - rad_packet_free(reply); - - return 0; -} - - -static void disconnect_request(struct radius_pd_t *rpd) -{ - if (conf_verbose) { - log_ppp_info2("recv "); - rad_packet_print(rpd->dm_coa_req, log_ppp_info2); - } - - dm_coa_send_ack(serv.hnd.fd, rpd->dm_coa_req, &rpd->dm_coa_addr); - - rad_packet_free(rpd->dm_coa_req); - - pthread_mutex_lock(&rpd->lock); - rpd->dm_coa_req = NULL; - pthread_mutex_unlock(&rpd->lock); - - ppp_terminate(rpd->ppp, TERM_ADMIN_RESET, 0); -} - -static void coa_request(struct radius_pd_t *rpd) -{ - struct ev_radius_t ev = { - .ppp = rpd->ppp, - .request = rpd->dm_coa_req, - }; - - if (conf_verbose) { - log_ppp_info2("recv "); - rad_packet_print(rpd->dm_coa_req, log_ppp_info2); - } - - triton_event_fire(EV_RADIUS_COA, &ev); - - if (ev.res) - dm_coa_send_nak(serv.hnd.fd, rpd->dm_coa_req, &rpd->dm_coa_addr, 0); - else - dm_coa_send_ack(serv.hnd.fd, rpd->dm_coa_req, &rpd->dm_coa_addr); - - rad_packet_free(rpd->dm_coa_req); - - pthread_mutex_lock(&rpd->lock); - rpd->dm_coa_req = NULL; - pthread_mutex_unlock(&rpd->lock); -} - -void dm_coa_cancel(struct radius_pd_t *rpd) -{ - triton_cancel_call(rpd->ppp->ctrl->ctx, (triton_event_func)disconnect_request); - triton_cancel_call(rpd->ppp->ctrl->ctx, (triton_event_func)coa_request); - rad_packet_free(rpd->dm_coa_req); -} - -static int dm_coa_read(struct triton_md_handler_t *h) -{ - struct rad_packet_t *pack; - struct radius_pd_t *rpd; - int err_code; - struct sockaddr_in addr; - - while (1) { - if (rad_packet_recv(h->fd, &pack, &addr)) - return 0; - - if (!pack) - continue; - - if (pack->code != CODE_DISCONNECT_REQUEST && pack->code != CODE_COA_REQUEST) { - log_warn("radius:dm_coa: unexpected code (%i) received\n", pack->code); - goto out_err_no_reply; - } - - if (dm_coa_check_RA(pack, conf_dm_coa_secret)) { - log_warn("radius:dm_coa: RA validation failed\n"); - goto out_err_no_reply; - } - - if (conf_verbose) { - log_debug("recv "); - rad_packet_print(pack, log_debug); - } - - if (rad_check_nas_pack(pack)) { - log_warn("radius:dm_coa: NAS identification failed\n"); - err_code = 403; - goto out_err; - } - - rpd = rad_find_session_pack(pack); - if (!rpd) { - log_warn("radius:dm_coa: session not found\n"); - err_code = 503; - goto out_err; - } - - if (rpd->dm_coa_req) { - pthread_mutex_unlock(&rpd->lock); - goto out_err_no_reply; - } - - rpd->dm_coa_req = pack; - memcpy(&rpd->dm_coa_addr, &addr, sizeof(addr)); - - if (pack->code == CODE_DISCONNECT_REQUEST) - triton_context_call(rpd->ppp->ctrl->ctx, (triton_event_func)disconnect_request, rpd); - else - triton_context_call(rpd->ppp->ctrl->ctx, (triton_event_func)coa_request, rpd); - - pthread_mutex_unlock(&rpd->lock); - - continue; - - out_err: - dm_coa_send_nak(h->fd, pack, &addr, err_code); - - out_err_no_reply: - rad_packet_free(pack); - } -} - -static void dm_coa_close(struct triton_context_t *ctx) -{ - struct dm_coa_serv_t *serv = container_of(ctx, typeof(*serv), ctx); - triton_md_unregister_handler(&serv->hnd); - close(serv->hnd.fd); - triton_context_unregister(ctx); -} - -static struct dm_coa_serv_t serv = { - .ctx.close = dm_coa_close, - .ctx.before_switch = log_switch, - .hnd.read = dm_coa_read, -}; - -static void __init init(void) -{ - struct sockaddr_in addr; - - if (!conf_dm_coa_secret) { - log_emerg("radius: no dm_coa_secret specified, DM/CoA disabled...\n"); - return; - } - - serv.hnd.fd = socket (PF_INET, SOCK_DGRAM, 0); - if (serv.hnd.fd < 0) { - log_emerg("radius:dm_coa: socket: %s\n", strerror(errno)); - return; - } - addr.sin_family = AF_INET; - addr.sin_port = htons (conf_dm_coa_port); - if (conf_dm_coa_server) - addr.sin_addr.s_addr = conf_dm_coa_server; - else - addr.sin_addr.s_addr = htonl (INADDR_ANY); - if (bind (serv.hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { - log_emerg("radius:dm_coa: bind: %s\n", strerror(errno)); - close(serv.hnd.fd); - return; - } - - if (fcntl(serv.hnd.fd, F_SETFL, O_NONBLOCK)) { - log_emerg("radius:dm_coa: failed to set nonblocking mode: %s\n", strerror(errno)); - close(serv.hnd.fd); - return; - } - - triton_context_register(&serv.ctx, NULL); - triton_md_register_handler(&serv.ctx, &serv.hnd); - triton_md_enable_handler(&serv.hnd, MD_MODE_READ); - triton_context_wakeup(&serv.ctx); -} diff --git a/accel-pptpd/radius/packet.c b/accel-pptpd/radius/packet.c deleted file mode 100644 index 4e24ded..0000000 --- a/accel-pptpd/radius/packet.c +++ /dev/null @@ -1,644 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include "log.h" -#include "mempool.h" - -#include "radius_p.h" - -#include "memdebug.h" - -static mempool_t packet_pool; -static mempool_t attr_pool; - -struct rad_packet_t *rad_packet_alloc(int code) -{ - struct rad_packet_t *pack; - - pack = mempool_alloc(packet_pool); - if (!pack) { - log_emerg("radius:packet: out of memory\n"); - return NULL; - } - - memset(pack, 0, sizeof(*pack)); - pack->code = code; - pack->len = 20; - pack->id = 1; - INIT_LIST_HEAD(&pack->attrs); - - return pack; -} - -void print_buf(uint8_t *buf,int size) -{ - int i; - for(i=0;ibuf) - ptr = _realloc(pack->buf, pack->len); - else - ptr = _malloc(pack->len); - - if (!ptr) { - log_emerg("radius:packet: out of memory\n"); - return -1; - } - - pack->buf = ptr; - *ptr = pack->code; ptr++; - *ptr = pack->id; ptr++; - *(uint16_t*)ptr = htons(pack->len); ptr+= 2; - memcpy(ptr, RA, 16); ptr+=16; - - list_for_each_entry(attr, &pack->attrs, entry) { - if (attr->vendor) { - *ptr = 26; ptr++; - *ptr = attr->len + 2 + 6; ptr++; - *(uint32_t *)ptr = htonl(attr->vendor->id); ptr+=4; - } - *ptr = attr->attr->id; ptr++; - *ptr = attr->len + 2; ptr++; - switch(attr->attr->type) { - case ATTR_TYPE_INTEGER: - *(uint32_t*)ptr = htonl(attr->val.integer); - break; - case ATTR_TYPE_OCTETS: - case ATTR_TYPE_STRING: - memcpy(ptr, attr->val.string, attr->len); - break; - case ATTR_TYPE_IPADDR: - *(in_addr_t*)ptr = attr->val.ipaddr; - break; - case ATTR_TYPE_DATE: - *(uint32_t*)ptr = htonl(attr->val.date); - break; - default: - log_emerg("radius:packet:BUG: unknown attribute type\n"); - abort(); - } - ptr += attr->len; - } - - //print_buf(pack->buf, pack->len); - return 0; -} - -int rad_packet_recv(int fd, struct rad_packet_t **p, struct sockaddr_in *addr) -{ - struct rad_packet_t *pack; - struct rad_attr_t *attr; - struct rad_dict_attr_t *da; - struct rad_dict_vendor_t *vendor; - uint8_t *ptr; - int n, id, len, vendor_id; - socklen_t addr_len = sizeof(*addr); - - *p = NULL; - - pack = rad_packet_alloc(0); - if (!pack) - return 0; - - pack->buf = _malloc(REQ_LENGTH_MAX); - if (!pack->buf) { - log_emerg("radius:packet: out of memory\n"); - goto out_err; - } - - while (1) { - if (addr) - n = recvfrom(fd, pack->buf, REQ_LENGTH_MAX, 0, addr, &addr_len); - else - n = read(fd, pack->buf, REQ_LENGTH_MAX); - if (n < 0) { - if (errno == EAGAIN) { - rad_packet_free(pack); - return -1; - } - if (errno != ECONNREFUSED) - log_ppp_error("radius:packet:read: %s\n", strerror(errno)); - goto out_err; - } - break; - } - - if (n < 20) { - log_ppp_warn("radius:packet: short packed received (%i)\n", n); - goto out_err; - } - - ptr = (uint8_t *)pack->buf; - - pack->code = *ptr; ptr++; - pack->id = *ptr; ptr++; - pack->len = ntohs(*(uint16_t*)ptr); ptr += 2; - - if (pack->len > n) { - log_ppp_warn("radius:packet: short packet received %i, expected %i\n", pack->len, n); - goto out_err; - } - - ptr += 16; - n -= 20; - - while (n>0) { - id = *ptr; ptr++; - len = *ptr - 2; ptr++; - if (len < 0) { - log_ppp_warn("radius:packet short attribute len received\n"); - goto out_err; - } - if (2 + len > n) { - log_ppp_warn("radius:packet: too long attribute received (%i, %i)\n", id, len); - goto out_err; - } - if (id == 26) { - vendor_id = ntohl(*(uint32_t *)ptr); - vendor = rad_dict_find_vendor_id(vendor_id); - if (vendor) { - ptr += 4; - id = *ptr; ptr++; - len = *ptr - 2; ptr++; - n -= 2 + 4; - } else - log_ppp_warn("radius:packet: vendor %i not found\n", id); - } else - vendor = NULL; - da = rad_dict_find_attr_id(vendor, id); - if (da) { - attr = mempool_alloc(attr_pool); - if (!attr) { - log_emerg("radius:packet: out of memory\n"); - goto out_err; - } - memset(attr, 0, sizeof(*attr)); - attr->vendor = vendor; - attr->attr = da; - attr->len = len; - switch (da->type) { - case ATTR_TYPE_STRING: - attr->val.string = _malloc(len+1); - if (!attr->val.string) { - log_emerg("radius:packet: out of memory\n"); - _free(attr); - goto out_err; - } - memcpy(attr->val.string, ptr, len); - attr->val.string[len] = 0; - break; - case ATTR_TYPE_OCTETS: - attr->val.octets = _malloc(len); - if (!attr->val.octets) { - log_emerg("radius:packet: out of memory\n"); - _free(attr); - goto out_err; - } - memcpy(attr->val.octets, ptr, len); - break; - case ATTR_TYPE_DATE: - case ATTR_TYPE_INTEGER: - attr->val.integer = ntohl(*(uint32_t*)ptr); - break; - case ATTR_TYPE_IPADDR: - attr->val.integer = *(uint32_t*)ptr; - break; - } - list_add_tail(&attr->entry, &pack->attrs); - } else - log_ppp_warn("radius:packet: unknown attribute received (%i,%i)\n", vendor ? vendor->id : 0, id); - ptr += len; - n -= 2 + len; - } - - *p = pack; - - return 0; - -out_err: - rad_packet_free(pack); - return 0; -} - -void rad_packet_free(struct rad_packet_t *pack) -{ - struct rad_attr_t *attr; - - if (pack->buf) - _free(pack->buf); - - while(!list_empty(&pack->attrs)) { - attr = list_entry(pack->attrs.next, typeof(*attr), entry); - list_del(&attr->entry); - if (attr->attr->type == ATTR_TYPE_STRING || attr->attr->type == ATTR_TYPE_OCTETS) - _free(attr->val.string); - mempool_free(attr); - } - - mempool_free(pack); -} - -void rad_packet_print(struct rad_packet_t *pack, void (*print)(const char *fmt, ...)) -{ - struct rad_attr_t *attr; - struct rad_dict_value_t *val; - - print("[RADIUS "); - switch(pack->code) { - case CODE_ACCESS_REQUEST: - print("Access-Request"); - break; - case CODE_ACCESS_CHALLENGE: - print("Access-Challenge"); - break; - case CODE_ACCESS_ACCEPT: - print("Access-Accept"); - break; - case CODE_ACCESS_REJECT: - print("Access-Reject"); - break; - case CODE_ACCOUNTING_REQUEST: - print("Accounting-Request"); - break; - case CODE_ACCOUNTING_RESPONSE: - print("Accounting-Response"); - break; - case CODE_DISCONNECT_REQUEST: - print("Disconnect-Request"); - break; - case CODE_DISCONNECT_ACK: - print("Disconnect-ACK"); - break; - case CODE_DISCONNECT_NAK: - print("Disconnect-NAK"); - break; - case CODE_COA_REQUEST: - print("CoA-Request"); - break; - case CODE_COA_ACK: - print("CoA-ACK"); - break; - case CODE_COA_NAK: - print("CoA-NAK"); - break; - default: - print("Unknown (%i)", pack->code); - } - print(" id=%x", pack->id); - - list_for_each_entry(attr, &pack->attrs, entry) { - if (attr->vendor) - print("<%s %s ", attr->vendor->name, attr->attr->name); - else - print(" <%s ", attr->attr->name); - switch (attr->attr->type) { - case ATTR_TYPE_INTEGER: - val = rad_dict_find_val(attr->attr, attr->val); - if (val) - print("%s", val->name); - else - print("%u", attr->val.integer); - break; - case ATTR_TYPE_STRING: - print("\"%s\"", attr->val.string); - break; - case ATTR_TYPE_IPADDR: - print("%i.%i.%i.%i", attr->val.ipaddr & 0xff, (attr->val.ipaddr >> 8) & 0xff, (attr->val.ipaddr >> 16) & 0xff, (attr->val.ipaddr >> 24) & 0xff); - break; - } - print(">"); - } - print("]\n"); -} - -int __export rad_packet_add_int(struct rad_packet_t *pack, const char *vendor_name, const char *name, int val) -{ - struct rad_attr_t *ra; - struct rad_dict_attr_t *attr; - struct rad_dict_vendor_t *vendor; - - if (pack->len + (vendor_name ? 8 : 2) + 4 >= REQ_LENGTH_MAX) - return -1; - - if (vendor_name) { - vendor = rad_dict_find_vendor_name(vendor_name); - if (!vendor) - return -1; - attr = rad_dict_find_vendor_attr(vendor, name); - } else { - vendor = NULL; - attr = rad_dict_find_attr(name); - } - - if (!attr) - return -1; - - ra = mempool_alloc(attr_pool); - if (!ra) - return -1; - - memset(ra, 0, sizeof(*ra)); - ra->vendor = vendor; - ra->attr = attr; - ra->len = 4; - ra->val.integer = val; - list_add_tail(&ra->entry, &pack->attrs); - pack->len += (vendor_name ? 8 : 2) + 4; - - return 0; -} - -int __export rad_packet_change_int(struct rad_packet_t *pack, const char *vendor_name, const char *name, int val) -{ - struct rad_attr_t *ra; - - ra = rad_packet_find_attr(pack, vendor_name, name); - if (!ra) - return -1; - - ra->val.integer = val; - - return 0; -} - -int __export rad_packet_add_octets(struct rad_packet_t *pack, const char *vendor_name, const char *name, const uint8_t *val, int len) -{ - struct rad_attr_t *ra; - struct rad_dict_attr_t *attr; - struct rad_dict_vendor_t *vendor; - - if (pack->len + (vendor_name ? 8 : 2) + len >= REQ_LENGTH_MAX) - return -1; - - if (vendor_name) { - vendor = rad_dict_find_vendor_name(vendor_name); - if (!vendor) - return -1; - attr = rad_dict_find_vendor_attr(vendor, name); - } else { - vendor = NULL; - attr = rad_dict_find_attr(name); - } - - if (!attr) - return -1; - - ra = mempool_alloc(attr_pool); - if (!ra) { - log_emerg("radius: out of memory\n"); - return -1; - } - - memset(ra, 0, sizeof(*ra)); - ra->vendor = vendor; - ra->attr = attr; - ra->len = len; - ra->val.octets = _malloc(len); - if (!ra->val.octets) { - log_emerg("radius: out of memory\n"); - _free(ra); - return -1; - } - memcpy(ra->val.octets, val, len); - list_add_tail(&ra->entry, &pack->attrs); - pack->len += (vendor_name ? 8 : 2) + len; - - return 0; -} - -int __export rad_packet_change_octets(struct rad_packet_t *pack, const char *vendor_name, const char *name, const uint8_t *val, int len) -{ - struct rad_attr_t *ra; - - ra = rad_packet_find_attr(pack, vendor_name, name); - if (!ra) - return -1; - - if (ra->len != len) { - if (pack->len - ra->len + len >= REQ_LENGTH_MAX) - return -1; - - ra->val.octets = _realloc(ra->val.octets, len); - if (!ra->val.octets) { - log_emerg("radius: out of memory\n"); - return -1; - } - - pack->len += len - ra->len; - ra->len = len; - } - - memcpy(ra->val.octets, val, len); - - return 0; -} - - -int __export rad_packet_add_str(struct rad_packet_t *pack, const char *vendor_name, const char *name, const char *val) -{ - struct rad_attr_t *ra; - struct rad_dict_attr_t *attr; - struct rad_dict_vendor_t *vendor; - int len = strlen(val); - - if (pack->len + (vendor_name ? 8 : 2) + len >= REQ_LENGTH_MAX) - return -1; - - if (vendor_name) { - vendor = rad_dict_find_vendor_name(vendor_name); - if (!vendor) - return -1; - attr = rad_dict_find_vendor_attr(vendor, name); - } else { - vendor = NULL; - attr = rad_dict_find_attr(name); - } - - if (!attr) - return -1; - - ra = mempool_alloc(attr_pool); - if (!ra) { - log_emerg("radius: out of memory\n"); - return -1; - } - - memset(ra, 0, sizeof(*ra)); - ra->vendor = vendor; - ra->attr = attr; - ra->len = len; - ra->val.string = _malloc(len + 1); - if (!ra->val.string) { - log_emerg("radius: out of memory\n"); - _free(ra); - return -1; - } - memcpy(ra->val.string, val, len); - ra->val.string[len] = 0; - list_add_tail(&ra->entry, &pack->attrs); - pack->len += (vendor_name ? 8 : 2) + len; - - return 0; -} - -int __export rad_packet_change_str(struct rad_packet_t *pack, const char *vendor_name, const char *name, const char *val, int len) -{ - struct rad_attr_t *ra; - - ra = rad_packet_find_attr(pack, vendor_name, name); - if (!ra) - return -1; - - if (ra->len != len) { - if (pack->len - ra->len + len >= REQ_LENGTH_MAX) - return -1; - - ra->val.string = _realloc(ra->val.string, len + 1); - if (!ra->val.string) { - log_emerg("radius: out of memory\n"); - return -1; - } - - pack->len += len - ra->len; - ra->len = len; - } - - memcpy(ra->val.string, val, len); - ra->val.string[len] = 0; - - return 0; -} - -int __export rad_packet_add_val(struct rad_packet_t *pack, const char *vendor_name, const char *name, const char *val) -{ - struct rad_attr_t *ra; - struct rad_dict_attr_t *attr; - struct rad_dict_value_t *v; - struct rad_dict_vendor_t *vendor; - - if (pack->len + (vendor_name ? 8 : 2) + 4 >= REQ_LENGTH_MAX) - return -1; - - if (vendor_name) { - vendor = rad_dict_find_vendor_name(vendor_name); - if (!vendor) - return -1; - attr = rad_dict_find_vendor_attr(vendor, name); - } else { - vendor = NULL; - attr = rad_dict_find_attr(name); - } - - if (!attr) - return -1; - - v = rad_dict_find_val_name(attr, val); - if (!v) - return -1; - - ra = mempool_alloc(attr_pool); - if (!ra) - return -1; - - memset(ra, 0, sizeof(*ra)); - ra->vendor = vendor; - ra->attr = attr; - ra->len = 4; - ra->val = v->val; - list_add_tail(&ra->entry, &pack->attrs); - pack->len += (vendor_name ? 8 : 2) + 4; - - return 0; -} - -int __export rad_packet_change_val(struct rad_packet_t *pack, const char *vendor_name, const char *name, const char *val) -{ - struct rad_attr_t *ra; - struct rad_dict_value_t *v; - - ra = rad_packet_find_attr(pack, vendor_name, name); - if (!ra) - return -1; - - v = rad_dict_find_val_name(ra->attr, val); - if (!v) - return -1; - - ra->val = v->val; - - return 0; -} - -int __export rad_packet_add_ipaddr(struct rad_packet_t *pack, const char *vendor_name, const char *name, in_addr_t ipaddr) -{ - return rad_packet_add_int(pack, vendor_name, name, ipaddr); -} - - -struct rad_attr_t __export *rad_packet_find_attr(struct rad_packet_t *pack, const char *vendor_name, const char *name) -{ - struct rad_attr_t *ra; - struct rad_dict_vendor_t *vendor; - - if (vendor_name) { - vendor = rad_dict_find_vendor_name(vendor_name); - if (!vendor) - return NULL; - } else - vendor = NULL; - - list_for_each_entry(ra, &pack->attrs, entry) { - if (vendor && vendor != ra->vendor) - continue; - - if (strcmp(ra->attr->name, name)) - continue; - - return ra; - } - - return NULL; -} - -int rad_packet_send(struct rad_packet_t *pack, int fd, struct sockaddr_in *addr) -{ - int n; - - while (1) { - if (addr) - n = sendto(fd, pack->buf, pack->len, 0, addr, sizeof(*addr)); - else - n = write(fd, pack->buf, pack->len); - if (n < 0) { - if (errno == EINTR) - continue; - log_ppp_error("radius:write: %s\n", strerror(errno)); - return -1; - } else if (n != pack->len) { - log_ppp_error("radius:write: short write %i, excpected %i\n", n, pack->len); - return -1; - } - break; - } - - return 0; -} - -static void __init init(void) -{ - attr_pool = mempool_create(sizeof(struct rad_attr_t)); - packet_pool = mempool_create(sizeof(struct rad_packet_t)); -} diff --git a/accel-pptpd/radius/radius.c b/accel-pptpd/radius/radius.c deleted file mode 100644 index 8976a33..0000000 --- a/accel-pptpd/radius/radius.c +++ /dev/null @@ -1,529 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "mempool.h" -#include "events.h" -#include "log.h" -#include "ppp.h" -#include "pwdb.h" -#include "ipdb.h" -#include "ppp_auth.h" -#include "cli.h" - -#include "radius_p.h" -#include "attr_defs.h" - -#include "memdebug.h" - -#define CHAP_MD5 5 -#define MSCHAP_V1 0x80 -#define MSCHAP_V2 0x81 - -int conf_max_try = 3; -int conf_timeout = 3; -int conf_acct_timeout = 600; -char *conf_nas_identifier; -in_addr_t conf_nas_ip_address; -in_addr_t conf_gw_ip_address; -in_addr_t conf_bind; -int conf_verbose; -int conf_interim_verbose; - -in_addr_t conf_auth_server; -int conf_auth_server_port = 1812; -char *conf_auth_secret; - -in_addr_t conf_acct_server; -int conf_acct_server_port = 1813; -char *conf_acct_secret; - -in_addr_t conf_dm_coa_server; -int conf_dm_coa_port = 3799; -char *conf_dm_coa_secret; - -int conf_sid_in_auth; -int conf_require_nas_ident; -int conf_acct_interim_interval; - -unsigned long stat_auth_sent; -unsigned long stat_auth_lost; -unsigned long stat_acct_sent; -unsigned long stat_acct_lost; -unsigned long stat_interim_sent; -unsigned long stat_interim_lost; - -static LIST_HEAD(sessions); -static pthread_rwlock_t sessions_lock = PTHREAD_RWLOCK_INITIALIZER; - -static void *pd_key; -static struct ipdb_t ipdb; - -static mempool_t rpd_pool; - -int rad_proc_attrs(struct rad_req_t *req) -{ - struct rad_attr_t *attr; - int res = 0; - - req->rpd->acct_interim_interval = conf_acct_interim_interval; - - list_for_each_entry(attr, &req->reply->attrs, entry) { - if (attr->vendor) - continue; - switch(attr->attr->id) { - case Framed_IP_Address: - if (!conf_gw_ip_address) - log_ppp_warn("radius: gw-ip-address not specified, cann't assign IP address...\n"); - else { - req->rpd->ipaddr.owner = &ipdb; - req->rpd->ipaddr.peer_addr = attr->val.ipaddr; - req->rpd->ipaddr.addr = conf_gw_ip_address; - } - break; - case Acct_Interim_Interval: - req->rpd->acct_interim_interval = attr->val.integer; - break; - case Session_Timeout: - req->rpd->session_timeout.period = attr->val.integer * 1000; - break; - case Class: - if (!req->rpd->attr_class) - req->rpd->attr_class = _malloc(attr->len); - else if (req->rpd->attr_class_len != attr->len) - req->rpd->attr_class = _realloc(req->rpd->attr_class, attr->len); - memcpy(req->rpd->attr_class, attr->val.octets, attr->len); - req->rpd->attr_class_len = attr->len; - break; - case State: - if (!req->rpd->attr_state) - req->rpd->attr_state = _malloc(attr->len); - else if (req->rpd->attr_state_len != attr->len) - req->rpd->attr_state = _realloc(req->rpd->attr_state, attr->len); - memcpy(req->rpd->attr_state, attr->val.octets, attr->len); - req->rpd->attr_state_len = attr->len; - break; - case Termination_Action: - req->rpd->termination_action = attr->val.integer; - break; - } - } - - return res; -} - -static int check(struct pwdb_t *pwdb, struct ppp_t *ppp, const char *username, int type, va_list _args) -{ - int r = PWDB_NO_IMPL; - va_list args; - int chap_type; - struct radius_pd_t *rpd = find_pd(ppp); - - va_copy(args, _args); - - switch(type) { - case PPP_PAP: - r = rad_auth_pap(rpd, username, args); - break; - case PPP_CHAP: - chap_type = va_arg(args, int); - switch(chap_type) { - case CHAP_MD5: - r = rad_auth_chap_md5(rpd, username, args); - break; - case MSCHAP_V1: - r = rad_auth_mschap_v1(rpd, username, args); - break; - case MSCHAP_V2: - r = rad_auth_mschap_v2(rpd, username, args); - break; - } - break; - } - - va_end(args); - - return r; -} - -static struct ipdb_item_t *get_ip(struct ppp_t *ppp) -{ - struct radius_pd_t *rpd = find_pd(ppp); - - if (rpd->ipaddr.peer_addr) - return &rpd->ipaddr; - return NULL; -} - -static void session_timeout(struct triton_timer_t *t) -{ - struct radius_pd_t *rpd = container_of(t, typeof(*rpd), session_timeout); - log_ppp_msg("radius: session timed out\n"); - - if (rpd->ppp->stop_time) - return; - - if (rpd->termination_action == Termination_Action_RADIUS_Request) { - if (ppp_auth_restart(rpd->ppp)) - ppp_terminate(rpd->ppp, TERM_SESSION_TIMEOUT, 0); - } else - ppp_terminate(rpd->ppp, TERM_SESSION_TIMEOUT, 0); -} - -static void ppp_starting(struct ppp_t *ppp) -{ - struct radius_pd_t *rpd = mempool_alloc(rpd_pool); - - memset(rpd, 0, sizeof(*rpd)); - rpd->pd.key = &pd_key; - rpd->ppp = ppp; - pthread_mutex_init(&rpd->lock, NULL); - INIT_LIST_HEAD(&rpd->plugin_list); - list_add_tail(&rpd->pd.entry, &ppp->pd_list); - - pthread_rwlock_wrlock(&sessions_lock); - list_add_tail(&rpd->entry, &sessions); - pthread_rwlock_unlock(&sessions_lock); -} - -static void ppp_acct_start(struct ppp_t *ppp) -{ - struct radius_pd_t *rpd = find_pd(ppp); - - if (rad_acct_start(rpd)) { - ppp_terminate(rpd->ppp, TERM_NAS_ERROR, 0); - return; - } - - if (rpd->session_timeout.period) { - rpd->session_timeout.expire = session_timeout; - triton_timer_add(ppp->ctrl->ctx, &rpd->session_timeout, 0); - } -} -static void ppp_finishing(struct ppp_t *ppp) -{ - struct radius_pd_t *rpd = find_pd(ppp); - - rad_acct_stop(rpd); -} -static void ppp_finished(struct ppp_t *ppp) -{ - struct radius_pd_t *rpd = find_pd(ppp); - - pthread_rwlock_wrlock(&sessions_lock); - pthread_mutex_lock(&rpd->lock); - list_del(&rpd->entry); - pthread_mutex_unlock(&rpd->lock); - pthread_rwlock_unlock(&sessions_lock); - - if (rpd->auth_req) - rad_req_free(rpd->auth_req); - - if (rpd->acct_req) - rad_req_free(rpd->acct_req); - - if (rpd->dm_coa_req) - dm_coa_cancel(rpd); - - if (rpd->session_timeout.tpd) - triton_timer_del(&rpd->session_timeout); - - if (rpd->attr_class) - _free(rpd->attr_class); - - if (rpd->attr_state) - _free(rpd->attr_state); - - list_del(&rpd->pd.entry); - - mempool_free(rpd); -} - -struct radius_pd_t *find_pd(struct ppp_t *ppp) -{ - struct ppp_pd_t *pd; - struct radius_pd_t *rpd; - - list_for_each_entry(pd, &ppp->pd_list, entry) { - if (pd->key == &pd_key) { - rpd = container_of(pd, typeof(*rpd), pd); - return rpd; - } - } - log_emerg("radius:BUG: rpd not found\n"); - abort(); -} - - -struct radius_pd_t *rad_find_session(const char *sessionid, const char *username, int port_id, in_addr_t ipaddr, const char *csid) -{ - struct radius_pd_t *rpd; - - pthread_rwlock_rdlock(&sessions_lock); - list_for_each_entry(rpd, &sessions, entry) { - if (!rpd->ppp->username) - continue; - if (sessionid && strcmp(sessionid, rpd->ppp->sessionid)) - continue; - if (username && strcmp(username, rpd->ppp->username)) - continue; - if (port_id >= 0 && port_id != rpd->ppp->unit_idx) - continue; - if (ipaddr && ipaddr != rpd->ppp->peer_ipaddr) - continue; - if (csid && rpd->ppp->ctrl->calling_station_id && strcmp(csid, rpd->ppp->ctrl->calling_station_id)) - continue; - pthread_mutex_lock(&rpd->lock); - pthread_rwlock_unlock(&sessions_lock); - return rpd; - } - pthread_rwlock_unlock(&sessions_lock); - return NULL; -} - -struct radius_pd_t *rad_find_session_pack(struct rad_packet_t *pack) -{ - struct rad_attr_t *attr; - const char *sessionid = NULL; - const char *username = NULL; - const char *csid = NULL; - int port_id = -1; - in_addr_t ipaddr = 0; - - list_for_each_entry(attr, &pack->attrs, entry) { - switch(attr->attr->id) { - case Acct_Session_Id: - sessionid = attr->val.string; - break; - case User_Name: - username = attr->val.string; - break; - case NAS_Port: - port_id = attr->val.integer; - break; - case Framed_IP_Address: - ipaddr = attr->val.ipaddr; - break; - case Calling_Station_Id: - csid = attr->val.string; - break; - } - } - - if (!sessionid && !username && port_id == -1 && ipaddr == 0 && !csid) - return NULL; - - if (username && !sessionid && port_id == -1 && ipaddr == 0) - return NULL; - - return rad_find_session(sessionid, username, port_id, ipaddr, csid); -} - -int rad_check_nas_pack(struct rad_packet_t *pack) -{ - struct rad_attr_t *attr; - const char *ident = NULL; - in_addr_t ipaddr = 0; - - list_for_each_entry(attr, &pack->attrs, entry) { - if (!strcmp(attr->attr->name, "NAS-Identifier")) - ident = attr->val.string; - else if (!strcmp(attr->attr->name, "NAS-IP-Address")) - ipaddr = attr->val.ipaddr; - } - - if (conf_require_nas_ident && !ident && !ipaddr) - return -1; - - if (conf_nas_identifier && ident && strcmp(conf_nas_identifier, ident)) - return -1; - - if (conf_nas_ip_address && ipaddr && conf_nas_ip_address != ipaddr) - return -1; - - return 0; -} - -static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) -{ - cli_send(client, "radius:\r\n"); - cli_sendv(client, " auth sent: %lu\r\n", stat_auth_sent); - cli_sendv(client, " auth lost: %lu\r\n", stat_auth_lost); - cli_sendv(client, " acct sent: %lu\r\n", stat_acct_sent); - cli_sendv(client, " acct lost: %lu\r\n", stat_acct_lost); - cli_sendv(client, " interim sent: %lu\r\n", stat_interim_sent); - cli_sendv(client, " interim lost: %lu\r\n", stat_interim_lost); - return CLI_CMD_OK; -} - -void __export rad_register_plugin(struct ppp_t *ppp, struct rad_plugin_t *plugin) -{ - struct radius_pd_t *rpd = find_pd(ppp); - - if (!rpd) - return; - - list_add_tail(&plugin->entry, &rpd->plugin_list); -} - -static struct ipdb_t ipdb = { - .get = get_ip, -}; - -static struct pwdb_t pwdb = { - .check = check, -}; - -static int parse_server(const char *opt, in_addr_t *addr, int *port, char **secret) -{ - char *str = _strdup(opt); - char *p1, *p2; - - p1 = strstr(str, ":"); - p2 = strstr(str, ","); - - if (p1) - *p1 = 0; - if (p2) - *p2 = 0; - else - return -1; - - *addr = inet_addr(str); - - if (p1) { - *port = atoi(p1 + 1); - if (*port <=0 ) - return -1; - } - - p1 = _strdup(p2 + 1); - p2 = *secret; - *secret = p1; - if (p2) - _free(p2); - - _free(str); - - return 0; -} - -static int load_config(void) -{ - char *opt; - - opt = conf_get_opt("radius", "max-try"); - if (opt && atoi(opt) > 0) - conf_max_try = atoi(opt); - - opt = conf_get_opt("radius", "timeout"); - if (opt && atoi(opt) > 0) - conf_timeout = atoi(opt); - - opt = conf_get_opt("radius", "acct-timeout"); - if (opt && atoi(opt) > 0) - conf_acct_timeout = atoi(opt); - - opt = conf_get_opt("radius", "verbose"); - if (opt && atoi(opt) > 0) - conf_verbose = 1; - - opt = conf_get_opt("radius", "interim-verbose"); - if (opt && atoi(opt) > 0) - conf_interim_verbose = 1; - - opt = conf_get_opt("radius", "nas-ip-address"); - if (opt) - conf_nas_ip_address = inet_addr(opt); - - if (conf_nas_identifier) - _free(conf_nas_identifier); - opt = conf_get_opt("radius", "nas-identifier"); - if (opt) - conf_nas_identifier = _strdup(opt); - else - conf_nas_identifier = NULL; - - opt = conf_get_opt("radius", "gw-ip-address"); - if (opt) - conf_gw_ip_address = inet_addr(opt); - - opt = conf_get_opt("radius", "bind"); - if (opt) - conf_bind = inet_addr(opt); - else if (conf_nas_ip_address) - conf_bind = conf_nas_ip_address; - - opt = conf_get_opt("radius", "auth-server"); - if (!opt) - opt = conf_get_opt("radius", "auth_server"); - if (!opt) { - log_emerg("radius: auth-server not specified\n"); - return -1; - } else if (parse_server(opt, &conf_auth_server, &conf_auth_server_port, &conf_auth_secret)) { - log_emerg("radius: failed to parse auth_server\n"); - return -1; - } - - opt = conf_get_opt("radius", "acct-server"); - if (!opt) - opt = conf_get_opt("radius", "acct_server"); - if (!opt) - log_emerg("radius: acct-server not specified\n"); - if (opt && parse_server(opt, &conf_acct_server, &conf_acct_server_port, &conf_acct_secret)) { - log_emerg("radius: failed to parse acct_server\n"); - return -1; - } - - opt = conf_get_opt("radius", "dae-server"); - if (opt && parse_server(opt, &conf_dm_coa_server, &conf_dm_coa_port, &conf_dm_coa_secret)) { - log_emerg("radius: failed to parse dae-server\n"); - return -1; - } - - opt = conf_get_opt("radius", "sid_in_auth"); - if (opt && atoi(opt) > 0) - conf_sid_in_auth = 1; - - opt = conf_get_opt("radius", "require-nas-identification"); - if (opt && atoi(opt) > 0) - conf_require_nas_ident = 1; - - opt = conf_get_opt("radius", "acct-interim-interval"); - if (opt && atoi(opt) > 0) - conf_acct_interim_interval = atoi(opt); - - return 0; -} - -static void __init radius_init(void) -{ - char *opt; - char *dict = DICTIONARY; - - rpd_pool = mempool_create(sizeof(struct radius_pd_t)); - - if (load_config()) - _exit(EXIT_FAILURE); - - opt = conf_get_opt("radius", "dictionary"); - if (opt) - dict = opt; - - if (rad_dict_load(dict)) - _exit(EXIT_FAILURE); - - pwdb_register(&pwdb); - ipdb_register(&ipdb); - - triton_event_register_handler(EV_PPP_STARTING, (triton_event_func)ppp_starting); - triton_event_register_handler(EV_PPP_ACCT_START, (triton_event_func)ppp_acct_start); - triton_event_register_handler(EV_PPP_FINISHING, (triton_event_func)ppp_finishing); - triton_event_register_handler(EV_PPP_FINISHED, (triton_event_func)ppp_finished); - triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); - - cli_register_simple_cmd2(show_stat_exec, NULL, 2, "show", "stat"); -} diff --git a/accel-pptpd/radius/radius.h b/accel-pptpd/radius/radius.h deleted file mode 100644 index ad229d2..0000000 --- a/accel-pptpd/radius/radius.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef __RADIUS_H -#define __RADIUS_H - -#include - -#define REQ_LENGTH_MAX 4096 - -#define ATTR_TYPE_INTEGER 0 -#define ATTR_TYPE_STRING 1 -#define ATTR_TYPE_OCTETS 2 -#define ATTR_TYPE_DATE 3 -#define ATTR_TYPE_IPADDR 4 - -#define CODE_ACCESS_REQUEST 1 -#define CODE_ACCESS_ACCEPT 2 -#define CODE_ACCESS_REJECT 3 -#define CODE_ACCESS_CHALLENGE 11 - -#define CODE_ACCOUNTING_REQUEST 4 -#define CODE_ACCOUNTING_RESPONSE 5 - -#define CODE_DISCONNECT_REQUEST 40 -#define CODE_DISCONNECT_ACK 41 -#define CODE_DISCONNECT_NAK 42 -#define CODE_COA_REQUEST 43 -#define CODE_COA_ACK 44 -#define CODE_COA_NAK 45 - -typedef union -{ - int integer; - char *string; - uint8_t *octets; - time_t date; - in_addr_t ipaddr; -} rad_value_t; - -struct rad_dict_t -{ - struct list_head items; - struct list_head vendors; -}; - -struct rad_dict_vendor_t -{ - struct list_head entry; - int id; - const char *name; - struct list_head items; -}; - -struct rad_dict_value_t -{ - struct list_head entry; - rad_value_t val; - const char *name; -}; - -struct rad_dict_attr_t -{ - struct list_head entry; - const char *name; - int id; - int type; - struct list_head values; -}; - -struct rad_attr_t -{ - struct list_head entry; - struct rad_dict_attr_t *attr; - struct rad_dict_vendor_t *vendor; - //struct rad_dict_value_t *val; - rad_value_t val; - int len; -}; - -struct rad_packet_t -{ - int code; - uint8_t id; - int len; - struct list_head attrs; - void *buf; -}; - -struct rad_plugin_t -{ - struct list_head entry; - int (*send_access_request)(struct rad_plugin_t *, struct rad_packet_t *pack); - int (*send_accounting_request)(struct rad_plugin_t *, struct rad_packet_t *pack); -}; - -struct ppp_t; - -void rad_register_plugin(struct ppp_t *, struct rad_plugin_t *); - -struct rad_dict_attr_t *rad_dict_find_attr(const char *name); -struct rad_dict_attr_t *rad_dict_find_attr_id(struct rad_dict_vendor_t *vendor, int type); -struct rad_dict_value_t *rad_dict_find_val_name(struct rad_dict_attr_t *, const char *name); -struct rad_dict_value_t *rad_dict_find_val(struct rad_dict_attr_t *, rad_value_t val); -struct rad_dict_vendor_t *rad_dict_find_vendor_name(const char *name); -struct rad_dict_vendor_t *rad_dict_find_vendor_id(int id); -struct rad_dict_attr_t *rad_dict_find_vendor_attr(struct rad_dict_vendor_t *vendor, const char *name); - -struct rad_attr_t *rad_packet_find_attr(struct rad_packet_t *pack, const char *vendor, const char *name); -int rad_packet_add_int(struct rad_packet_t *pack, const char *vendor, const char *name, int val); -int rad_packet_add_val(struct rad_packet_t *pack, const char *vendor, const char *name, const char *val); -int rad_packet_add_str(struct rad_packet_t *pack, const char *vendor, const char *name, const char *val); -int rad_packet_add_octets(struct rad_packet_t *pack, const char *vendor, const char *name, const uint8_t *val, int len); -int rad_packet_change_int(struct rad_packet_t *pack, const char *vendor, const char *name, int val); -int rad_packet_change_val(struct rad_packet_t *pack, const char *vendor, const char *name, const char *val); -int rad_packet_change_octets(struct rad_packet_t *pack, const char *vendor, const char *name, const uint8_t *val, int len); -int rad_packet_add_ipaddr(struct rad_packet_t *pack, const char *vendor, const char *name, in_addr_t ipaddr); - -#endif - diff --git a/accel-pptpd/radius/radius_p.h b/accel-pptpd/radius/radius_p.h deleted file mode 100644 index 71c1a63..0000000 --- a/accel-pptpd/radius/radius_p.h +++ /dev/null @@ -1,122 +0,0 @@ -#ifndef __RADIUS_P_H -#define __RADIUS_P_H - -#include -#include - -#include "triton.h" -#include "radius.h" -#include "ppp.h" -#include "ipdb.h" - -struct radius_pd_t -{ - struct list_head entry; - struct ppp_pd_t pd; - struct ppp_t *ppp; - pthread_mutex_t lock; - - struct rad_req_t *auth_req; - struct rad_req_t *acct_req; - struct triton_timer_t acct_interim_timer; - uint32_t acct_input_octets; - uint32_t acct_output_octets; - uint32_t acct_input_gigawords; - uint32_t acct_output_gigawords; - - struct triton_timer_t session_timeout; - - struct rad_packet_t *dm_coa_req; - struct sockaddr_in dm_coa_addr; - - struct ipdb_item_t ipaddr; - int acct_interim_interval; - time_t acct_timestamp; - - uint8_t *attr_class; - int attr_class_len; - uint8_t *attr_state; - int attr_state_len; - int termination_action; - - struct list_head plugin_list; -}; - -struct rad_req_t -{ - struct triton_context_t ctx; - struct triton_md_handler_t hnd; - struct triton_timer_t timeout; - uint8_t RA[16]; - struct rad_packet_t *pack; - struct rad_packet_t *reply; - in_addr_t server_addr; - int server_port; - - struct radius_pd_t *rpd; -}; - -extern int conf_max_try; -extern int conf_timeout; -extern int conf_acct_timeout; -extern int conf_verbose; -extern int conf_interim_verbose; -extern char *conf_nas_identifier; -extern in_addr_t conf_nas_ip_address; -extern in_addr_t conf_bind; -extern in_addr_t conf_gw_ip_address; -extern in_addr_t conf_auth_server; -extern char *conf_auth_secret; -extern int conf_auth_server_port; -extern in_addr_t conf_acct_server; -extern char *conf_acct_secret; -extern int conf_acct_server_port; -extern char *conf_dm_coa_secret; -extern int conf_sid_in_auth; -extern int conf_require_nas_ident; -extern in_addr_t conf_dm_coa_server; -extern int conf_dm_coa_port; -extern int conf_acct_interim_interval; - -extern unsigned long stat_auth_sent; -extern unsigned long stat_auth_lost; -extern unsigned long stat_acct_sent; -extern unsigned long stat_acct_lost; -extern unsigned long stat_interim_sent; -extern unsigned long stat_interim_lost; - -int rad_check_nas_pack(struct rad_packet_t *pack); -struct radius_pd_t *rad_find_session(const char *sessionid, const char *username, int port_id, in_addr_t ipaddr, const char *csid); -struct radius_pd_t *rad_find_session_pack(struct rad_packet_t *pack); - -int rad_dict_load(const char *fname); -void rad_dict_free(struct rad_dict_t *dict); - -struct rad_req_t *rad_req_alloc(struct radius_pd_t *rpd, int code, const char *username); -int rad_req_acct_fill(struct rad_req_t *); -void rad_req_free(struct rad_req_t *); -int rad_req_send(struct rad_req_t *, int verbose); -int rad_req_wait(struct rad_req_t *, int); - -struct radius_pd_t *find_pd(struct ppp_t *ppp); -int rad_proc_attrs(struct rad_req_t *req); - -int rad_auth_pap(struct radius_pd_t *rpd, const char *username, va_list args); -int rad_auth_chap_md5(struct radius_pd_t *rpd, const char *username, va_list args); -int rad_auth_mschap_v1(struct radius_pd_t *rpd, const char *username, va_list args); -int rad_auth_mschap_v2(struct radius_pd_t *rpd, const char *username, va_list args); - -int rad_acct_start(struct radius_pd_t *rpd); -void rad_acct_stop(struct radius_pd_t *rpd); - -struct rad_packet_t *rad_packet_alloc(int code); -int rad_packet_build(struct rad_packet_t *pack, uint8_t *RA); -int rad_packet_recv(int fd, struct rad_packet_t **, struct sockaddr_in *addr); -void rad_packet_free(struct rad_packet_t *); -void rad_packet_print(struct rad_packet_t *pack, void (*print)(const char *fmt, ...)); -int rad_packet_send(struct rad_packet_t *pck, int fd, struct sockaddr_in *addr); - -void dm_coa_cancel(struct radius_pd_t *pd); - -#endif - diff --git a/accel-pptpd/radius/req.c b/accel-pptpd/radius/req.c deleted file mode 100644 index a384f23..0000000 --- a/accel-pptpd/radius/req.c +++ /dev/null @@ -1,277 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "log.h" -#include "radius_p.h" - -#include "memdebug.h" - -static int urandom_fd; - -static int rad_req_read(struct triton_md_handler_t *h); -static void rad_req_timeout(struct triton_timer_t *t); - -struct rad_req_t *rad_req_alloc(struct radius_pd_t *rpd, int code, const char *username) -{ - struct rad_plugin_t *plugin; - struct rad_req_t *req = _malloc(sizeof(*req)); - - if (!req) - return NULL; - - memset(req, 0, sizeof(*req)); - req->rpd = rpd; - req->hnd.fd = -1; - req->ctx.before_switch = log_switch; - - req->server_addr = conf_auth_server; - req->server_port = conf_auth_server_port; - - while (1) { - if (read(urandom_fd, req->RA, 16) != 16) { - if (errno == EINTR) - continue; - log_ppp_error("radius:req:read urandom: %s\n", strerror(errno)); - goto out_err; - } - break; - } - - req->pack = rad_packet_alloc(code); - if (!req->pack) - goto out_err; - - if (rad_packet_add_str(req->pack, NULL, "User-Name", username)) - goto out_err; - if (conf_nas_identifier) - if (rad_packet_add_str(req->pack, NULL, "NAS-Identifier", conf_nas_identifier)) - goto out_err; - if (conf_nas_ip_address) - if (rad_packet_add_ipaddr(req->pack, NULL, "NAS-IP-Address", conf_nas_ip_address)) - goto out_err; - if (rad_packet_add_int(req->pack, NULL, "NAS-Port", rpd->ppp->unit_idx)) - goto out_err; - if (rad_packet_add_val(req->pack, NULL, "NAS-Port-Type", "Virtual")) - goto out_err; - if (rad_packet_add_val(req->pack, NULL, "Service-Type", "Framed-User")) - goto out_err; - if (rad_packet_add_val(req->pack, NULL, "Framed-Protocol", "PPP")) - goto out_err; - if (rpd->ppp->ctrl->calling_station_id) - if (rad_packet_add_str(req->pack, NULL, "Calling-Station-Id", rpd->ppp->ctrl->calling_station_id)) - goto out_err; - if (rpd->ppp->ctrl->called_station_id) - if (rad_packet_add_str(req->pack, NULL, "Called-Station-Id", rpd->ppp->ctrl->called_station_id)) - goto out_err; - if (rpd->attr_class) - if (rad_packet_add_octets(req->pack, NULL, "Class", rpd->attr_class, rpd->attr_class_len)) - goto out_err; - - list_for_each_entry(plugin, &req->rpd->plugin_list, entry) { - switch (code) { - case CODE_ACCESS_REQUEST: - if (plugin->send_access_request && plugin->send_access_request(plugin, req->pack)) - goto out_err; - break; - case CODE_ACCOUNTING_REQUEST: - if (plugin->send_accounting_request && plugin->send_accounting_request(plugin, req->pack)) - goto out_err; - break; - } - } - - return req; - -out_err: - rad_req_free(req); - return NULL; -} - -int rad_req_acct_fill(struct rad_req_t *req) -{ - req->server_addr = conf_acct_server; - req->server_port = conf_acct_server_port; - - memset(req->RA, 0, sizeof(req->RA)); - - if (rad_packet_add_val(req->pack, NULL, "Acct-Status-Type", "Start")) - return -1; - if (rad_packet_add_val(req->pack, NULL, "Acct-Authentic", "RADIUS")) - return -1; - if (rad_packet_add_str(req->pack, NULL, "Acct-Session-Id", req->rpd->ppp->sessionid)) - return -1; - if (rad_packet_add_int(req->pack, NULL, "Acct-Session-Time", 0)) - return -1; - if (rad_packet_add_int(req->pack, NULL, "Acct-Input-Octets", 0)) - return -1; - if (rad_packet_add_int(req->pack, NULL, "Acct-Output-Octets", 0)) - return -1; - if (rad_packet_add_int(req->pack, NULL, "Acct-Input-Packets", 0)) - return -1; - if (rad_packet_add_int(req->pack, NULL, "Acct-Output-Packets", 0)) - return -1; - if (rad_packet_add_int(req->pack, NULL, "Acct-Input-Gigawords", 0)) - return -1; - if (rad_packet_add_int(req->pack, NULL, "Acct-Output-Gigawords", 0)) - return -1; - if (rad_packet_add_int(req->pack, NULL, "Acct-Delay-Time", 0)) - return -1; - if (rad_packet_add_ipaddr(req->pack, NULL, "Framed-IP-Address", req->rpd->ppp->peer_ipaddr)) - return -1; - - return 0; -} - -void rad_req_free(struct rad_req_t *req) -{ - if (req->hnd.fd >= 0 ) - close(req->hnd.fd); - if (req->pack) - rad_packet_free(req->pack); - if (req->reply) - rad_packet_free(req->reply); - _free(req); -} - -static int make_socket(struct rad_req_t *req) -{ - struct sockaddr_in addr; - - req->hnd.fd = socket(PF_INET, SOCK_DGRAM, 0); - if (req->hnd.fd < 0) { - log_ppp_error("radius:socket: %s\n", strerror(errno)); - return -1; - } - - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; - - if (conf_bind) { - addr.sin_addr.s_addr = conf_bind; - if (bind(req->hnd.fd, (struct sockaddr *) &addr, sizeof(addr))) { - log_ppp_error("radius:bind: %s\n", strerror(errno)); - goto out_err; - } - } - - addr.sin_addr.s_addr = req->server_addr; - addr.sin_port = htons(req->server_port); - - if (connect(req->hnd.fd, (struct sockaddr *) &addr, sizeof(addr))) { - log_ppp_error("radius:connect: %s\n", strerror(errno)); - goto out_err; - } - - if (fcntl(req->hnd.fd, F_SETFL, O_NONBLOCK)) { - log_ppp_error("radius: failed to set nonblocking mode: %s\n", strerror(errno)); - goto out_err; - } - - return 0; - -out_err: - close(req->hnd.fd); - req->hnd.fd = -1; - return -1; -} - -int rad_req_send(struct rad_req_t *req, int verbose) -{ - if (req->hnd.fd == -1 && make_socket(req)) - return -1; - - if (!req->pack->buf && rad_packet_build(req->pack, req->RA)) - goto out_err; - - if (verbose) { - log_ppp_info1("send "); - rad_packet_print(req->pack, log_ppp_info1); - } - - rad_packet_send(req->pack, req->hnd.fd, NULL); - - return 0; - -out_err: - close(req->hnd.fd); - req->hnd.fd = -1; - return -1; -} - -static void req_wakeup(struct rad_req_t *req) -{ - struct triton_context_t *ctx = req->rpd->ppp->ctrl->ctx; - triton_timer_del(&req->timeout); - triton_md_unregister_handler(&req->hnd); - triton_context_unregister(&req->ctx); - triton_context_wakeup(ctx); -} -static int rad_req_read(struct triton_md_handler_t *h) -{ - struct rad_req_t *req = container_of(h, typeof(*req), hnd); - struct rad_packet_t *pack; - int r; - - while (1) { - r = rad_packet_recv(h->fd, &pack, NULL); - - if (pack) { - if (req->reply) - rad_packet_free(req->reply); - req->reply = pack; - } - - if (r) - break; - } - - req_wakeup(req); - - return 1; -} -static void rad_req_timeout(struct triton_timer_t *t) -{ - struct rad_req_t *req = container_of(t, typeof(*req), timeout); - - req_wakeup(req); -} - -int rad_req_wait(struct rad_req_t *req, int timeout) -{ - req->hnd.read = rad_req_read; - req->timeout.expire = rad_req_timeout; - - triton_context_register(&req->ctx, req->rpd->ppp); - triton_md_register_handler(&req->ctx, &req->hnd); - triton_md_enable_handler(&req->hnd, MD_MODE_READ); - - req->timeout.period = timeout * 1000; - triton_timer_add(&req->ctx, &req->timeout, 0); - - triton_context_wakeup(&req->ctx); - - triton_context_schedule(); - - if (conf_verbose && req->reply) { - log_ppp_info1("recv "); - rad_packet_print(req->reply, log_ppp_info1); - } - return 0; -} - -void __init req_init(void) -{ - urandom_fd = open("/dev/urandom", O_RDONLY); - if (!urandom_fd) { - log_emerg("radius:req: open /dev/urandom: %s\n", strerror(errno)); - _exit(EXIT_FAILURE); - } -} diff --git a/accel-pptpd/triton/CMakeLists.txt b/accel-pptpd/triton/CMakeLists.txt deleted file mode 100644 index 0c6786d..0000000 --- a/accel-pptpd/triton/CMakeLists.txt +++ /dev/null @@ -1,40 +0,0 @@ -SET(sources_c - md.c - timer.c - triton.c - conf_file.c - loader.c - log.c - mempool.c - event.c -) - -INCLUDE(CheckFunctionExists) -CHECK_FUNCTION_EXISTS(timerfd_create HAVE_TIMERFD) - -IF (HAVE_TIMERFD) - ADD_DEFINITIONS(-DHAVE_TIMERFD) -ELSE (HAVE_TIMERFD) - INCLUDE (CheckCSourceCompiles) - CHECK_C_SOURCE_COMPILES(" - #include - int main() - { - syscall(SYS_timerfd_create); - }" HAVE_SYSCALL) - IF (NOT HAVE_SYSCALL) - MESSAGE(FATAL_ERROR "Your system is too old and is not supported by accel-pptp, sorry...") - ENDIF (NOT HAVE_SYSCALL) - SET(sources_c ${sources_c} timerfd.c) -ENDIF (HAVE_TIMERFD) - -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) - -ADD_DEFINITIONS(-DMODULE_PATH="${CMAKE_INSTALL_PREFIX}/lib/accel-pptp") - -ADD_LIBRARY(triton SHARED ${sources_c}) -TARGET_LINK_LIBRARIES(triton dl) - -INSTALL(TARGETS triton - LIBRARY DESTINATION lib/accel-pptp -) diff --git a/accel-pptpd/triton/conf_file.c b/accel-pptpd/triton/conf_file.c deleted file mode 100644 index ce8549c..0000000 --- a/accel-pptpd/triton/conf_file.c +++ /dev/null @@ -1,248 +0,0 @@ -#include -#include -#include -#include -#include - -#include "triton_p.h" - -#include "memdebug.h" - -struct sect_t -{ - struct list_head entry; - - struct conf_sect_t *sect; -}; - -static pthread_mutex_t conf_lock = PTHREAD_MUTEX_INITIALIZER; -static LIST_HEAD(sections); -static char *conf_fname; - -static char* skip_space(char *str); -static char* skip_word(char *str); - -static struct conf_sect_t *find_sect(const char *name); -static struct conf_sect_t *create_sect(const char *name); -static void sect_add_item(struct conf_sect_t *sect, const char *name, const char *val); -static struct conf_option_t *find_item(struct conf_sect_t *, const char *name); - -static char *buf; - -int __conf_load(const char *fname, struct conf_sect_t *cur_sect) -{ - char *str,*str2; - int cur_line = 0; - - FILE *f = fopen(fname, "r"); - if (!f) { - perror("conf_file:open"); - return -1; - } - - while(!feof(f)) { - if (!fgets(buf, 1024, f)) - break; - ++cur_line; - if (buf[strlen(buf) - 1] == '\n') - buf[strlen(buf) - 1] = 0; - - str = skip_space(buf); - if (*str == '#' || *str == 0) - continue; - if (strncmp(str, "$include", 8) == 0) { - str = skip_word(str); - str = skip_space(str); - if (__conf_load(str, cur_sect)); - break; - continue; - } - if (*str == '[') { - for (str2 = ++str; *str2 && *str2 != ']'; str2++); - if (*str2 != ']') { - fprintf(stderr, "conf_file:%s:%i: sintax error\n", fname, cur_line); - return -1; - } - *str2 = 0; - cur_sect = find_sect(str); - if (!cur_sect) - cur_sect = create_sect(str); - continue; - } - if (!cur_sect) { - fprintf(stderr, "conf_file:%s:%i: no section opened\n", fname, cur_line); - return -1; - } - str2 = skip_word(str); - if (*str2 == ' ') { - *str2 = 0; - ++str2; - } - str2 = skip_space(str2); - if (*str2 == '=' || *str2 == ',') { - *str2 = 0; - str2 = skip_space(str2 + 1); - if (*str2 && *(str2 + 1) && *str2 == '$' && *(str2 + 1) == '{') { - char *s; - struct conf_option_t *opt; - for (s = str2+2; *s && *s != '}'; s++); - if (*s == '}') { - *s = 0; - str2 += 2; - } - opt = find_item(cur_sect, str2); - if (!opt) { - fprintf(stderr, "conf_file:%s:%i: parent option not found\n", fname, cur_line); - return -1; - } - str2 = opt->val; - } - } else - str2 = NULL; - sect_add_item(cur_sect, str, str2); - } - - fclose(f); - - return 0; -} - -int conf_load(const char *fname) -{ - int r; - - if (fname) { - if (conf_fname) - _free(conf_fname); - conf_fname = _strdup(fname); - } else - fname = conf_fname; - - buf = _malloc(1024); - - r = __conf_load(fname, NULL); - - _free(buf); - - return r; -} - -int conf_reload(const char *fname) -{ - struct sect_t *sect; - struct conf_option_t *opt; - int r; - LIST_HEAD(sections_bak); - - pthread_mutex_lock(&conf_lock); - - while (!list_empty(§ions)) { - sect = list_entry(sections.next, typeof(*sect), entry); - list_del(§->entry); - list_add_tail(§->entry, §ions_bak); - } - - r = conf_load(fname); - - if (r) { - while (!list_empty(§ions_bak)) { - sect = list_entry(sections_bak.next, typeof(*sect), entry); - list_del(§->entry); - list_add_tail(§->entry, §ions); - } - pthread_mutex_unlock(&conf_lock); - } else { - pthread_mutex_unlock(&conf_lock); - while (!list_empty(§ions_bak)) { - sect = list_entry(sections_bak.next, typeof(*sect), entry); - list_del(§->entry); - while (!list_empty(§->sect->items)) { - opt = list_entry(sect->sect->items.next, typeof(*opt), entry); - list_del(&opt->entry); - if (opt->val) - _free(opt->val); - _free(opt->name); - _free(opt); - } - _free((char *)sect->sect->name); - _free(sect->sect); - _free(sect); - } - } - - return r; -} - -static char* skip_space(char *str) -{ - for (; *str && *str == ' '; str++); - return str; -} -static char* skip_word(char *str) -{ - for (; *str && (*str != ' ' && *str != '='); str++); - return str; -} - -static struct conf_sect_t *find_sect(const char *name) -{ - struct sect_t *s; - list_for_each_entry(s, §ions, entry) - if (strcmp(s->sect->name, name) == 0) return s->sect; - return NULL; -} - -static struct conf_sect_t *create_sect(const char *name) -{ - struct sect_t *s = _malloc(sizeof(struct sect_t)); - - s->sect = _malloc(sizeof(struct conf_sect_t)); - s->sect->name = (char*)_strdup(name); - INIT_LIST_HEAD(&s->sect->items); - - list_add_tail(&s->entry, §ions); - - return s->sect; -} - -static void sect_add_item(struct conf_sect_t *sect, const char *name, const char *val) -{ - struct conf_option_t *opt = _malloc(sizeof(struct conf_option_t)); - - opt->name = _strdup(name); - opt->val = val ? _strdup(val) : NULL; - - list_add_tail(&opt->entry, §->items); -} - -static struct conf_option_t *find_item(struct conf_sect_t *sect, const char *name) -{ - struct conf_option_t *opt; - list_for_each_entry(opt, §->items, entry) { - if (strcmp(opt->name, name) == 0) - return opt; - } - - return NULL; -} - -__export struct conf_sect_t * conf_get_section(const char *name) -{ - return find_sect(name); -} - -__export char * conf_get_opt(const char *sect, const char *name) -{ - struct conf_option_t *opt; - struct conf_sect_t *s = conf_get_section(sect); - - if (!s) - return NULL; - - opt = find_item(s, name); - if (!opt) - return NULL; - - return opt->val; -} - diff --git a/accel-pptpd/triton/event.c b/accel-pptpd/triton/event.c deleted file mode 100644 index d45eca0..0000000 --- a/accel-pptpd/triton/event.c +++ /dev/null @@ -1,105 +0,0 @@ -#include -#include -#include - -#include "triton_p.h" - -#include "memdebug.h" - -static int max_events = 1024; -static struct _triton_event_t **events; - -struct event_handler_t -{ - struct list_head entry; - triton_event_func func; -}; - -int event_init(void) -{ - events = malloc(max_events * sizeof(void *)); - if (!events) { - fprintf(stderr,"event:cann't allocate memory\n"); - return -1; - } - - memset(events, 0, max_events * sizeof(void *)); - - return 0; -} - -int __export triton_event_register_handler(int ev_id, triton_event_func func) -{ - struct _triton_event_t *ev; - struct event_handler_t *h; - - if (ev_id >= max_events) - return -1; - - ev = events[ev_id]; - if (!ev) { - ev = malloc(sizeof(*ev)); - if (!ev) { - triton_log_error("event: out of memory\n"); - return -1; - } - INIT_LIST_HEAD(&ev->handlers); - events[ev_id] = ev; - } - - h = malloc(sizeof(*h)); - if (!h) { - triton_log_error("event: out of memory\n"); - return -1; - } - - h->func = func; - list_add_tail(&h->entry, &ev->handlers); - - return 0; -} - -/*int triton_event_unregister_handler(int ev_id, triton_event_func func) -{ - struct _triton_event_t *ev; - struct event_handler_t *h; - - if (ev_id >= max_events) - return -1; - - ev = events[ev_id]; - if (!ev) { - return -1; - } - - list_for_each_entry(h, &ev->handlers, entry) { - if (h->func == func) { - if (ev->in_progress) - h->func = NULL; - else { - list_del(&h->entry); - _free(h); - } - return 0; - } - } - - return -1; -}*/ - -void __export triton_event_fire(int ev_id, void *arg) -{ - struct _triton_event_t *ev; - struct event_handler_t *h; - - if (ev_id >= max_events) - return; - - ev = events[ev_id]; - if (!ev) - return; - - list_for_each_entry(h, &ev->handlers, entry) - h->func(arg); -} - diff --git a/accel-pptpd/triton/list.h b/accel-pptpd/triton/list.h deleted file mode 100644 index d95dd71..0000000 --- a/accel-pptpd/triton/list.h +++ /dev/null @@ -1,249 +0,0 @@ -#ifndef _LINUX_LIST_H -#define _LINUX_LIST_H - -//#if defined(__KERNEL__) || defined(_LVM_H_INCLUDE) - -//#include - -/* - * Simple doubly linked list implementation. - * - * Some of the internal functions ("__xxx") are useful when - * manipulating whole lists rather than single entries, as - * sometimes we already know the next/prev entries and we can - * generate better code by using them directly rather than - * using the generic single-entry routines. - */ - -typedef struct list_head { - struct list_head *next, *prev; -} list_t; - -#define LIST_HEAD_INIT(name) { &(name), &(name) } - -#define LIST_HEAD(name) \ - struct list_head name = LIST_HEAD_INIT(name) - -#define INIT_LIST_HEAD(ptr) do { \ - (ptr)->next = (ptr); (ptr)->prev = (ptr); \ -} while (0) - -/* - * Insert a new entry between two known consecutive entries. - * - * This is only for internal list manipulation where we know - * the prev/next entries already! - */ - -static void inline prefetch(void *p){} - -static inline void __list_add(struct list_head *new, - struct list_head *prev, - struct list_head *next) -{ - next->prev = new; - new->next = next; - new->prev = prev; - prev->next = new; -} - -/** - * list_add - add a new entry - * @new: new entry to be added - * @head: list head to add it after - * - * Insert a new entry after the specified head. - * This is good for implementing stacks. - */ -static inline void list_add(struct list_head *new, struct list_head *head) -{ - __list_add(new, head, head->next); -} - -/** - * list_add_tail - add a new entry - * @new: new entry to be added - * @head: list head to add it before - * - * Insert a new entry before the specified head. - * This is useful for implementing queues. - */ -static inline void list_add_tail(struct list_head *new, struct list_head *head) -{ - __list_add(new, head->prev, head); -} - -/* - * Delete a list entry by making the prev/next entries - * point to each other. - * - * This is only for internal list manipulation where we know - * the prev/next entries already! - */ -static inline void __list_del(struct list_head *prev, struct list_head *next) -{ - next->prev = prev; - prev->next = next; -} - -/** - * list_del - deletes entry from list. - * @entry: the element to delete from the list. - * Note: list_empty on entry does not return true after this, the entry is in an undefined state. - */ -static inline void list_del(struct list_head *entry) -{ - __list_del(entry->prev, entry->next); - entry->next = (void *) 0; - entry->prev = (void *) 0; -} - -/** - * list_del_init - deletes entry from list and reinitialize it. - * @entry: the element to delete from the list. - */ -static inline void list_del_init(struct list_head *entry) -{ - __list_del(entry->prev, entry->next); - INIT_LIST_HEAD(entry); -} - -/** - * list_move - delete from one list and add as another's head - * @list: the entry to move - * @head: the head that will precede our entry - */ -static inline void list_move(struct list_head *list, struct list_head *head) -{ - __list_del(list->prev, list->next); - list_add(list, head); -} - -/** - * list_move_tail - delete from one list and add as another's tail - * @list: the entry to move - * @head: the head that will follow our entry - */ -static inline void list_move_tail(struct list_head *list, - struct list_head *head) -{ - __list_del(list->prev, list->next); - list_add_tail(list, head); -} - -/** - * list_empty - tests whether a list is empty - * @head: the list to test. - */ -static inline int list_empty(struct list_head *head) -{ - return head->next == head; -} - -static inline void __list_splice(struct list_head *list, - struct list_head *head) -{ - struct list_head *first = list->next; - struct list_head *last = list->prev; - struct list_head *at = head->next; - - first->prev = head; - head->next = first; - - last->next = at; - at->prev = last; -} - -/** - * list_splice - join two lists - * @list: the new list to add. - * @head: the place to add it in the first list. - */ -static inline void list_splice(struct list_head *list, struct list_head *head) -{ - if (!list_empty(list)) - __list_splice(list, head); -} - -/** - * list_splice_init - join two lists and reinitialise the emptied list. - * @list: the new list to add. - * @head: the place to add it in the first list. - * - * The list at @list is reinitialised - */ -static inline void list_splice_init(struct list_head *list, - struct list_head *head) -{ - if (!list_empty(list)) { - __list_splice(list, head); - INIT_LIST_HEAD(list); - } -} - -/** - * list_entry - get the struct for this entry - * @ptr: the &struct list_head pointer. - * @type: the type of the struct this is embedded in. - * @member: the name of the list_struct within the struct. - */ -#define list_entry(ptr, type, member) \ - ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) - -/** - * list_for_each - iterate over a list - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. - */ -#define list_for_each(pos, head) \ - for (pos = (head)->next, prefetch(pos->next); pos != (head); \ - pos = pos->next, prefetch(pos->next)) - -/** - * __list_for_each - iterate over a list - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. - * - * This variant differs from list_for_each() in that it's the - * simplest possible list iteration code, no prefetching is done. - * Use this for code that knows the list to be very short (empty - * or 1 entry) most of the time. - */ -#define __list_for_each(pos, head) \ - for (pos = (head)->next; pos != (head); pos = pos->next) - -/** - * list_for_each_prev - iterate over a list backwards - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. - */ -#define list_for_each_prev(pos, head) \ - for (pos = (head)->prev, prefetch(pos->prev); pos != (head); \ - pos = pos->prev, prefetch(pos->prev)) - -/** - * list_for_each_safe - iterate over a list safe against removal of list entry - * @pos: the &struct list_head to use as a loop counter. - * @n: another &struct list_head to use as temporary storage - * @head: the head for your list. - */ -#define list_for_each_safe(pos, n, head) \ - for (pos = (head)->next, n = pos->next; pos != (head); \ - pos = n, n = pos->next) - -/** - * list_for_each_entry - iterate over list of given type - * @pos: the type * to use as a loop counter. - * @head: the head for your list. - * @member: the name of the list_struct within the struct. - */ -#define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member), \ - prefetch(pos->member.next); \ - &pos->member != (head); \ - pos = list_entry(pos->member.next, typeof(*pos), member), \ - prefetch(pos->member.next)) - -//#endif /* __KERNEL__ || _LVM_H_INCLUDE */ - -#endif diff --git a/accel-pptpd/triton/loader.c b/accel-pptpd/triton/loader.c deleted file mode 100644 index 2a2a2e2..0000000 --- a/accel-pptpd/triton/loader.c +++ /dev/null @@ -1,62 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include "triton_p.h" - -#include "memdebug.h" - -int load_modules(const char *name) -{ - struct conf_sect_t *sect; - struct conf_option_t *opt; - char *fname; - char *path = MODULE_PATH; - - sect = conf_get_section(name); - if (!sect) { - fprintf(stderr, "loader: section '%s' not found\n", name); - return -1; - } - - fname = _malloc(PATH_MAX); - - list_for_each_entry(opt, §->items, entry) { - if (!strcmp(opt->name,"path") && opt->val) { - path = opt->val; - continue; - } - - strcpy(fname, path); - strcat(fname, "/"); - strcat(fname, opt->name); - if (access(fname, F_OK)) { - strcpy(fname, path); - strcat(fname, "/lib"); - strcat(fname, opt->name); - strcat(fname, ".so"); - if (access(fname, F_OK)) { - strcpy(fname, opt->name); - if (access(opt->name, F_OK)) { - triton_log_error("loader: '%s' not found\n", opt->name); - continue; - } - } - } - - if (!dlopen(fname, RTLD_LAZY | RTLD_GLOBAL)) { - triton_log_error("loader: failed to load '%s': %s\n", opt->name, dlerror()); - _free(fname); - return -1; - } - } - - _free(fname); - - return 0; -} - diff --git a/accel-pptpd/triton/log.c b/accel-pptpd/triton/log.c deleted file mode 100644 index c7e6b7f..0000000 --- a/accel-pptpd/triton/log.c +++ /dev/null @@ -1,73 +0,0 @@ -#include -#include - -#include "triton_p.h" - -#include "memdebug.h" - -static FILE *f_error; -static FILE *f_debug; -static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; - -int log_init(void) -{ - char *log_error = conf_get_opt("core","log-error"); - char *log_debug = conf_get_opt("core","log-debug"); - - if (log_error) { - f_error = fopen(log_error, "a"); - if (!f_error) { - perror("log:log_error:open"); - return -1; - } - } - if (log_debug) { - f_debug = fopen(log_debug, "a"); - if (!f_debug) { - perror("log:log_debug:open"); - return -1; - } - } - - return 0; -} - -static void do_log(FILE *f, const char *fmt, va_list ap) -{ - struct timeval tv; - struct tm tm; - char date[64]; - - gettimeofday(&tv, NULL); - localtime_r(&tv.tv_sec, &tm); - strftime(date, sizeof(date), "%F %H:%M:%S", &tm); - - pthread_mutex_lock(&lock); - fprintf(f, "[%s.%i]", date, (int)tv.tv_usec / 1000); - vfprintf(f, fmt,ap); - pthread_mutex_unlock(&lock); - - fflush(f); -} -void triton_log_error(const char *fmt,...) -{ - va_list ap; - - if (!f_error) - return; - - va_start(ap, fmt); - do_log(f_error, fmt, ap); -} - -void triton_log_debug(const char *fmt,...) -{ - va_list ap; - - if (!f_debug) - return; - - va_start(ap, fmt); - do_log(f_debug, fmt, ap); -} - diff --git a/accel-pptpd/triton/md.c b/accel-pptpd/triton/md.c deleted file mode 100644 index 84073d0..0000000 --- a/accel-pptpd/triton/md.c +++ /dev/null @@ -1,216 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include "triton_p.h" - -#include "memdebug.h" - -extern int max_events; - -static int epoll_fd; -static struct epoll_event *epoll_events; - -static pthread_t md_thr; -static void *md_thread(void *arg); - -static mempool_t *md_pool; - -static pthread_mutex_t freed_list_lock = PTHREAD_MUTEX_INITIALIZER; -static LIST_HEAD(freed_list); -static LIST_HEAD(freed_list2); - -int md_init(void) -{ - epoll_fd = epoll_create(1); - if (epoll_fd < 0) { - perror("md:epoll_create"); - return -1; - } - - epoll_events = _malloc(max_events * sizeof(struct epoll_event)); - if (!epoll_events) { - fprintf(stderr,"md:cann't allocate memory\n"); - return -1; - } - - md_pool = mempool_create(sizeof(struct _triton_md_handler_t)); - - return 0; -} -void md_run(void) -{ - if (pthread_create(&md_thr, NULL, md_thread, NULL)) { - triton_log_error("md:pthread_create: %s", strerror(errno)); - _exit(-1); - } -} - -void md_terminate(void) -{ - pthread_cancel(md_thr); - pthread_join(md_thr, NULL); -} - -static void *md_thread(void *arg) -{ - int i,n,r; - struct _triton_md_handler_t *h; - sigset_t set; - - sigfillset(&set); - sigdelset(&set, SIGKILL); - sigdelset(&set, SIGSTOP); - pthread_sigmask(SIG_BLOCK, &set, NULL); - - while(1) { - n = epoll_wait(epoll_fd, epoll_events, max_events, -1); - if (n < 0) { - if (errno == EINTR) - continue; - triton_log_error("md:epoll_wait: %s\n", strerror(errno)); - _exit(-1); - } - - for(i = 0; i < n; i++) { - h = (struct _triton_md_handler_t *)epoll_events[i].data.ptr; - if (!h->ud) - continue; - spin_lock(&h->ctx->lock); - if (h->ud) { - h->trig_epoll_events |= epoll_events[i].events; - if (!h->pending) { - list_add_tail(&h->entry2, &h->ctx->pending_handlers); - h->pending = 1; - __sync_add_and_fetch(&triton_stat.md_handler_pending, 1); - r = triton_queue_ctx(h->ctx); - } else - r = 0; - } else - r = 0; - spin_unlock(&h->ctx->lock); - if (r) - triton_thread_wakeup(h->ctx->thread); - } - - while (!list_empty(&freed_list2)) { - h = list_entry(freed_list2.next, typeof(*h), entry); - list_del(&h->entry); - mempool_free(h); - } - - pthread_mutex_lock(&freed_list_lock); - while (!list_empty(&freed_list)) { - h = list_entry(freed_list.next, typeof(*h), entry); - list_del(&h->entry); - list_add(&h->entry, &freed_list2); - } - pthread_mutex_unlock(&freed_list_lock); - } - - return NULL; -} - -void __export triton_md_register_handler(struct triton_context_t *ctx, struct triton_md_handler_t *ud) -{ - struct _triton_md_handler_t *h = mempool_alloc(md_pool); - memset(h, 0, sizeof(*h)); - h->ud = ud; - h->epoll_event.data.ptr = h; - if (ctx) - h->ctx = (struct _triton_context_t *)ctx->tpd; - else - h->ctx = (struct _triton_context_t *)default_ctx.tpd; - ud->tpd = h; - spin_lock(&h->ctx->lock); - list_add_tail(&h->entry, &h->ctx->handlers); - spin_unlock(&h->ctx->lock); - - triton_stat.md_handler_count++; -} -void __export triton_md_unregister_handler(struct triton_md_handler_t *ud) -{ - struct _triton_md_handler_t *h = (struct _triton_md_handler_t *)ud->tpd; - triton_md_disable_handler(ud, MD_MODE_READ | MD_MODE_WRITE); - - spin_lock(&h->ctx->lock); - h->ud = NULL; - list_del(&h->entry); - if (h->pending) { - list_del(&h->entry2); - __sync_sub_and_fetch(&triton_stat.md_handler_pending, 1); - } - spin_unlock(&h->ctx->lock); - - sched_yield(); - - pthread_mutex_lock(&freed_list_lock); - list_add_tail(&h->entry, &freed_list); - pthread_mutex_unlock(&freed_list_lock); - - triton_stat.md_handler_count--; -} -int __export triton_md_enable_handler(struct triton_md_handler_t *ud, int mode) -{ - struct _triton_md_handler_t *h = (struct _triton_md_handler_t *)ud->tpd; - int r; - int events = h->epoll_event.events; - - if (mode & MD_MODE_READ) - h->epoll_event.events |= EPOLLIN; - if (mode & MD_MODE_WRITE) - h->epoll_event.events |= EPOLLOUT; - - if (!h->trig_level) - h->epoll_event.events |= EPOLLET; - - if (events) - r = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, h->ud->fd, &h->epoll_event); - else - r = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, h->ud->fd, &h->epoll_event); - - if (r) { - triton_log_error("md:epoll_ctl: %s\n",strerror(errno)); - abort(); - } - - return r; -} -int __export triton_md_disable_handler(struct triton_md_handler_t *ud,int mode) -{ - struct _triton_md_handler_t *h = (struct _triton_md_handler_t *)ud->tpd; - int r=0; - - if (!h->epoll_event.events) - return -1; - - if (mode & MD_MODE_READ) - h->epoll_event.events &= ~EPOLLIN; - if (mode & MD_MODE_WRITE) - h->epoll_event.events &= ~EPOLLOUT; - - if (h->epoll_event.events & (EPOLLIN | EPOLLOUT)) - r = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, h->ud->fd, &h->epoll_event); - else { - h->epoll_event.events = 0; - r = epoll_ctl(epoll_fd, EPOLL_CTL_DEL, h->ud->fd, NULL); - } - - if (r) { - triton_log_error("md:epoll_ctl: %s\n",strerror(errno)); - abort(); - } - - return r; -} - -void __export triton_md_set_trig(struct triton_md_handler_t *ud, int mode) -{ - struct _triton_md_handler_t *h = (struct _triton_md_handler_t *)ud->tpd; - h->trig_level = mode; -} - diff --git a/accel-pptpd/triton/mempool.c b/accel-pptpd/triton/mempool.c deleted file mode 100644 index 855e22e..0000000 --- a/accel-pptpd/triton/mempool.c +++ /dev/null @@ -1,338 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include "triton_p.h" - -#include "memdebug.h" - -#ifdef VALGRIND -#include -#define DELAY 5 -#endif - -//#define MEMPOOL_DISABLE - -#define MAGIC1 0x2233445566778899llu - -struct _mempool_t -{ - struct list_head entry; - int size; - struct list_head items; -#ifdef MEMDEBUG - struct list_head ditems; -#endif - spinlock_t lock; - uint64_t magic; - int mmap:1; -}; - -struct _item_t -{ - struct list_head entry; -#ifdef VALGRIND - time_t timestamp; -#endif - struct _mempool_t *owner; -#ifdef MEMDEBUG - const char *fname; - int line; -#endif - uint64_t magic2; - uint64_t magic1; - char ptr[0]; -}; - -static LIST_HEAD(pools); -static spinlock_t pools_lock = SPINLOCK_INITIALIZER; - -mempool_t __export *mempool_create(int size) -{ - struct _mempool_t *p = _malloc(sizeof(*p)); - - memset(p, 0, sizeof(*p)); - INIT_LIST_HEAD(&p->items); -#ifdef MEMDEBUG - INIT_LIST_HEAD(&p->ditems); -#endif - spinlock_init(&p->lock); - p->size = size; - p->magic = (uint64_t)random() * (uint64_t)random(); - - spin_lock(&pools_lock); - list_add_tail(&p->entry, &pools); - spin_unlock(&pools_lock); - - return (mempool_t *)p; -} - -mempool_t __export *mempool_create2(int size) -{ - struct _mempool_t *p = (struct _mempool_t *)mempool_create(size); - - p->mmap = 1; - - return (mempool_t *)p; -} - -#ifndef MEMDEBUG -void __export *mempool_alloc(mempool_t *pool) -{ - struct _mempool_t *p = (struct _mempool_t *)pool; - struct _item_t *it; - uint32_t size = sizeof(*it) + p->size + 8; - - spin_lock(&p->lock); - if (!list_empty(&p->items)) { - it = list_entry(p->items.next, typeof(*it), entry); - list_del(&it->entry); - spin_unlock(&p->lock); - - __sync_sub_and_fetch(&triton_stat.mempool_available, size); - - it->magic1 = MAGIC1; - - return it->ptr; - } - spin_unlock(&p->lock); - - if (p->mmap) - it = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_32BIT, -1, 0); - else - it = _malloc(size); - - if (!it) { - triton_log_error("mempool: out of memory\n"); - return NULL; - } - it->owner = p; - it->magic1 = MAGIC1; - it->magic2 = p->magic; - *(uint64_t*)(it->data + p->size) = it->magic2; - - __sync_add_and_fetch(&triton_stat.mempool_allocated, size); - - return it->ptr; -} -#endif - -void __export *mempool_alloc_md(mempool_t *pool, const char *fname, int line) -{ - struct _mempool_t *p = (struct _mempool_t *)pool; - struct _item_t *it; - uint32_t size = sizeof(*it) + p->size + 8; - int i, n; - - spin_lock(&p->lock); - if (!list_empty(&p->items)) { - it = list_entry(p->items.next, typeof(*it), entry); -#ifdef VALGRIND - if (it->timestamp + DELAY < time(NULL)) { - VALGRIND_MAKE_MEM_DEFINED(&it->owner, size - sizeof(it->entry) - sizeof(it->timestamp)); - VALGRIND_MAKE_MEM_UNDEFINED(it->ptr, p->size); -#endif - list_del(&it->entry); - list_add(&it->entry, &p->ditems); - spin_unlock(&p->lock); - - it->fname = fname; - it->line = line; - - __sync_sub_and_fetch(&triton_stat.mempool_available, size); - - it->magic1 = MAGIC1; - - return it->ptr; -#ifdef VALGRIND - } -#endif - } - spin_unlock(&p->lock); - - if (p->mmap) { - n = (sysconf(_SC_PAGE_SIZE) - 1) / size + 1; - it = mmap(NULL, n * size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_32BIT, -1, 0); - __sync_add_and_fetch(&triton_stat.mempool_allocated, size * (n - 1)); - __sync_add_and_fetch(&triton_stat.mempool_available, size * (n - 1)); - spin_lock(&p->lock); - for (i = 0; i < n - 1; i++, it) { - it->owner = p; - it->magic2 = p->magic; - it->magic1 = MAGIC1; - *(uint64_t*)(it->ptr + p->size) = it->magic2; - list_add_tail(&it->entry,&p->items); -#ifdef VALGRIND - it->timestamp = 0; - VALGRIND_MAKE_MEM_NOACCESS(&it->owner, size - sizeof(it->entry) - sizeof(it->timestamp)); -#endif - it = (struct _item_t *)((char *)it + size); - } - spin_unlock(&p->lock); -#ifdef VALGRIND - VALGRIND_MAKE_MEM_UNDEFINED(it, size); -#endif - } else - it = md_malloc(size, fname, line); - - if (!it) { - triton_log_error("mempool: out of memory\n"); - return NULL; - } - it->owner = p; - it->magic2 = p->magic; - it->magic1 = MAGIC1; - it->fname = fname; - it->line = line; - *(uint64_t*)(it->ptr + p->size) = it->magic2; - - spin_lock(&p->lock); - list_add(&it->entry, &p->ditems); - spin_unlock(&p->lock); - - __sync_add_and_fetch(&triton_stat.mempool_allocated, size); - - return it->ptr; -} - - -void __export mempool_free(void *ptr) -{ - struct _item_t *it = container_of(ptr, typeof(*it), ptr); - struct _mempool_t *p = it->owner; - uint32_t size = sizeof(*it) + it->owner->size + 8; - -#ifdef MEMDEBUG - if (it->magic1 != MAGIC1) { - triton_log_error("mempool: memory corruption detected"); - abort(); - } - - if (it->magic2 != it->owner->magic) { - triton_log_error("mempool: memory corruption detected"); - abort(); - } - - if (it->magic2 != *(uint64_t*)(it->ptr + it->owner->size)) { - triton_log_error("mempool: memory corruption detected"); - abort(); - } - - it->magic1 = 0; -#endif - - spin_lock(&p->lock); -#ifdef MEMDEBUG - list_del(&it->entry); -#endif -#ifndef MEMPOOL_DISABLE - list_add_tail(&it->entry,&it->owner->items); -#endif -#ifdef VALGRIND - time(&it->timestamp); - VALGRIND_MAKE_MEM_NOACCESS(&it->owner, size - sizeof(it->entry) - sizeof(it->timestamp)); -#endif - spin_unlock(&p->lock); - -#ifdef MEMPOOL_DISABLE - if (it->owner->mmap) - munmap(it, size); - else - _free(it); -#endif - - __sync_add_and_fetch(&triton_stat.mempool_available, size); -} - -void __export mempool_clean(mempool_t *pool) -{ - struct _mempool_t *p = (struct _mempool_t *)pool; - struct _item_t *it; - uint32_t size = sizeof(*it) + p->size + 8; - - spin_lock(&p->lock); - while (!list_empty(&p->items)) { - it = list_entry(p->items.next, typeof(*it), entry); -#ifdef VALGRIND - if (it->timestamp + DELAY < time(NULL)) { - VALGRIND_MAKE_MEM_DEFINED(&it->owner, size - sizeof(it->entry) - sizeof(it->timestamp)); -#endif - list_del(&it->entry); - if (p->mmap) - munmap(it, size); - else - _free(it); - __sync_sub_and_fetch(&triton_stat.mempool_allocated, size); - __sync_sub_and_fetch(&triton_stat.mempool_available, size); -#ifdef VALGRIND - } else - break; -#endif - } - spin_unlock(&p->lock); -} - -#ifdef MEMDEBUG -void __export mempool_show(mempool_t *pool) -{ - struct _mempool_t *p = (struct _mempool_t *)pool; - struct _item_t *it; - - spin_lock(&p->lock); - list_for_each_entry(it, &p->ditems, entry) - triton_log_error("%s:%i %p\n", it->fname, it->line, it->ptr); - spin_unlock(&p->lock); -} -#endif - -void sigclean(int num) -{ - struct _mempool_t *p; - struct _item_t *it; - uint32_t size; - - triton_log_error("mempool: clean\n"); - - spin_lock(&pools_lock); - list_for_each_entry(p, &pools, entry) { - if (p->mmap) - continue; - size = sizeof(*it) + p->size + 8; - spin_lock(&p->lock); - while (!list_empty(&p->items)) { - it = list_entry(p->items.next, typeof(*it), entry); -#ifdef VALGRIND - if (it->timestamp + DELAY < time(NULL)) { - VALGRIND_MAKE_MEM_DEFINED(&it->owner, size - sizeof(it->entry) - sizeof(it->timestamp)); -#endif - list_del(&it->entry); - _free(it); - __sync_sub_and_fetch(&triton_stat.mempool_allocated, size); - __sync_sub_and_fetch(&triton_stat.mempool_available, size); -#ifdef VALGRIND - } else - break; -#endif - } - spin_unlock(&p->lock); - } - spin_unlock(&pools_lock); -} - -static void __init init(void) -{ - sigset_t set; - sigfillset(&set); - - struct sigaction sa = { - .sa_handler = sigclean, - .sa_mask = set, - }; - - sigaction(35, &sa, NULL); -} - diff --git a/accel-pptpd/triton/mempool.h b/accel-pptpd/triton/mempool.h deleted file mode 100644 index bdb3e71..0000000 --- a/accel-pptpd/triton/mempool.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef __TRITON_MEMPOOL_H -#define __TRITON_MEMPOOL_H - -#include - -struct mempool_stat_t -{ - uint32_t allocated; - uint32_t available; -}; - -typedef void * mempool_t; -mempool_t *mempool_create(int size); -mempool_t *mempool_create2(int size); -void mempool_free(void*); -struct mempool_stat_t mempool_get_stat(void); - -#ifdef MEMDEBUG -void *mempool_alloc_md(mempool_t*, const char *fname, int line); -#define mempool_alloc(pool) mempool_alloc_md(pool, __FILE__, __LINE__) -#else -void *mempool_alloc(mempool_t*); -#endif - -#endif - diff --git a/accel-pptpd/triton/options.c b/accel-pptpd/triton/options.c deleted file mode 100644 index a5214e2..0000000 --- a/accel-pptpd/triton/options.c +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include - -#include "triton_p.h" -#include "conf_file.h" - -#include "memdebug.h" - -static struct conf_file_sect_t *sect=NULL; - -static const char* find_option(const char *name) -{ - struct option_t *opt; - - if (!sect) - { - sect=conf_file_get_section("options"); - if (!sect) return 0; - } - - list_for_each_entry(opt,§->items,entry) - { - if (strcmp(opt->name,name)==0) - return opt->val; - } - - return NULL; -} -int triton_get_int_option(const char *str) -{ - const char *val=find_option(str); - if (!val) return 0; - - return atoi(val); -} -const char* triton_get_str_option(const char *str) -{ - const char *val=find_option(str); - - return val; -} -double triton_get_double_option(const char *str) -{ - const char *val=find_option(str); - if (!val) return 0; - - return atof(val); -} diff --git a/accel-pptpd/triton/spinlock.h b/accel-pptpd/triton/spinlock.h deleted file mode 100644 index bb8dcf4..0000000 --- a/accel-pptpd/triton/spinlock.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef __TRITON_SPINLOCK_H -#define __TRITON_SPINLOCK_H - -#if defined(FUTEX_SPINLOCK) - -/*#include -#include -#include -typedef volatile int __attribute__((aligned)) spinlock_t; -static inline void _spin_lock(spinlock_t *l) -{ - syscall(SYS_futex, l, FUTEX_WAIT, r, NULL, NULL, 0); -} -static inline void _spin_unlock(spinlock_t *l) -{ - syscall(SYS_futex, l, FUTEX_WAKE, 2, NULL, NULL, 0); -} -#define spin_lock(l) _spin_lock(l) -#define spin_unlock(l) _spin_unlock(l) -#define SPINLOCK_INITIALIZER 1 -#define spinlock_init(l) {*(l)=1;}*/ - -#elif defined(GCC_SPINLOCK) - -typedef volatile int __attribute__((aligned)) spinlock_t; -#define spin_lock(l) {while(__sync_lock_test_and_set(l,1));} -#define spin_unlock(l) __sync_lock_release(l) -#define SPINLOCK_INITIALIZER 0 -#define spinlock_init(l) {*(l)=0;} - -#else - -#include -typedef pthread_mutex_t spinlock_t; -#define spin_lock(l) pthread_mutex_lock(l) -#define spin_unlock(l) pthread_mutex_unlock(l) -#define SPINLOCK_INITIALIZER PTHREAD_MUTEX_INITIALIZER -#define spinlock_init(l) pthread_mutex_init(l,NULL) -#endif - -#endif - diff --git a/accel-pptpd/triton/timer.c b/accel-pptpd/triton/timer.c deleted file mode 100644 index e419e93..0000000 --- a/accel-pptpd/triton/timer.c +++ /dev/null @@ -1,222 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef HAVE_TIMERFD -#include -#else -#include "timerfd.h" -#endif - -#include "triton_p.h" - -#include "memdebug.h" - -extern int max_events; -static int epoll_fd; -static struct epoll_event *epoll_events; - -static pthread_t timer_thr; -static void *timer_thread(void *arg); - -static mempool_t *timer_pool; - -static pthread_mutex_t freed_list_lock = PTHREAD_MUTEX_INITIALIZER; -static LIST_HEAD(freed_list); -static LIST_HEAD(freed_list2); - -int timer_init(void) -{ - epoll_fd = epoll_create(1); - if (epoll_fd < 0) { - perror("timer:epoll_create"); - return -1; - } - - epoll_events = _malloc(max_events * sizeof(struct epoll_event)); - if (!epoll_events) { - fprintf(stderr,"timer:cann't allocate memory\n"); - return -1; - } - - timer_pool = mempool_create(sizeof(struct _triton_timer_t)); - - return 0; -} - -void timer_run(void) -{ - if (pthread_create(&timer_thr, NULL, timer_thread, NULL)) { - triton_log_error("timer:pthread_create: %s",strerror(errno)); - _exit(-1); - } -} - -void timer_terminate(void) -{ - pthread_cancel(timer_thr); - pthread_join(timer_thr, NULL); -} - -void *timer_thread(void *arg) -{ - int i,n,r; - struct _triton_timer_t *t; - sigset_t set; - - sigfillset(&set); - sigdelset(&set, SIGKILL); - sigdelset(&set, SIGSTOP); - pthread_sigmask(SIG_BLOCK, &set, NULL); - - while(1) { - n = epoll_wait(epoll_fd, epoll_events, max_events, -1); - if (n < 0) { - if (errno == EINTR) - continue; - triton_log_error("timer:epoll_wait: %s", strerror(errno)); - _exit(-1); - } - - for(i = 0; i < n; i++) { - t = (struct _triton_timer_t *)epoll_events[i].data.ptr; - if (!t->ud) - continue; - spin_lock(&t->ctx->lock); - if (t->ud) { - if (!t->pending) { - list_add_tail(&t->entry2, &t->ctx->pending_timers); - t->pending = 1; - __sync_add_and_fetch(&triton_stat.timer_pending, 1); - r = triton_queue_ctx(t->ctx); - } else - r = 0; - } else - r = 0; - spin_unlock(&t->ctx->lock); - if (r) - triton_thread_wakeup(t->ctx->thread); - } - - while (!list_empty(&freed_list2)) { - t = list_entry(freed_list2.next, typeof(*t), entry); - list_del(&t->entry); - mempool_free(t); - } - - pthread_mutex_lock(&freed_list_lock); - while (!list_empty(&freed_list)) { - t = list_entry(freed_list.next, typeof(*t), entry); - list_del(&t->entry); - list_add(&t->entry, &freed_list2); - } - pthread_mutex_unlock(&freed_list_lock); - } - - return NULL; -} - - -int __export triton_timer_add(struct triton_context_t *ctx, struct triton_timer_t *ud, int abs_time) -{ - struct _triton_timer_t *t = mempool_alloc(timer_pool); - - memset(t, 0, sizeof(*t)); - t->ud = ud; - t->epoll_event.data.ptr = t; - t->epoll_event.events = EPOLLIN | EPOLLET; - if (ctx) - t->ctx = (struct _triton_context_t *)ctx->tpd; - else - t->ctx = (struct _triton_context_t *)default_ctx.tpd; - t->fd = timerfd_create(abs_time ? CLOCK_REALTIME : CLOCK_MONOTONIC, 0); - if (t->fd < 0) { - triton_log_error("timer:timerfd_create: %s", strerror(errno)); - mempool_free(t); - return -1; - } - - if (fcntl(t->fd, F_SETFL, O_NONBLOCK)) { - triton_log_error("timer: failed to set nonblocking mode: %s\n", strerror(errno)); - goto out_err; - } - - ud->tpd = t; - - if (triton_timer_mod(ud, abs_time)) - goto out_err; - - spin_lock(&t->ctx->lock); - list_add_tail(&t->entry, &t->ctx->timers); - spin_unlock(&t->ctx->lock); - - if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, t->fd, &t->epoll_event)) { - triton_log_error("timer:epoll_ctl: %s", strerror(errno)); - spin_lock(&t->ctx->lock); - t->ud = NULL; - list_del(&t->entry); - spin_unlock(&t->ctx->lock); - goto out_err; - } - - triton_stat.timer_count++; - - return 0; - -out_err: - ud->tpd = NULL; - close(t->fd); - mempool_free(t); - return -1; -} -int __export triton_timer_mod(struct triton_timer_t *ud,int abs_time) -{ - struct _triton_timer_t *t = (struct _triton_timer_t *)ud->tpd; - struct itimerspec ts = { - .it_value.tv_sec = ud->expire_tv.tv_sec, - .it_value.tv_nsec = ud->expire_tv.tv_usec * 1000, - .it_interval.tv_sec = ud->period / 1000, - .it_interval.tv_nsec = (ud->period % 1000) * 1000, - }; - - if (ud->expire_tv.tv_sec == 0 && ud->expire_tv.tv_usec == 0) - ts.it_value = ts.it_interval; - - if (timerfd_settime(t->fd, abs_time ? TFD_TIMER_ABSTIME : 0, &ts, NULL)) { - triton_log_error("timer:timerfd_settime: %s", strerror(errno)); - return -1; - } - - return 0; -} -void __export triton_timer_del(struct triton_timer_t *ud) -{ - struct _triton_timer_t *t = (struct _triton_timer_t *)ud->tpd; - epoll_ctl(epoll_fd, EPOLL_CTL_DEL, t->fd, &t->epoll_event); - close(t->fd); - spin_lock(&t->ctx->lock); - t->ud = NULL; - list_del(&t->entry); - if (t->pending) { - list_del(&t->entry2); - __sync_sub_and_fetch(&triton_stat.timer_pending, 1); - } - spin_unlock(&t->ctx->lock); - - sched_yield(); - - pthread_mutex_lock(&freed_list_lock); - list_add_tail(&t->entry, &freed_list); - pthread_mutex_unlock(&freed_list_lock); - - ud->tpd = NULL; - - triton_stat.timer_count--; -} - diff --git a/accel-pptpd/triton/timerfd.c b/accel-pptpd/triton/timerfd.c deleted file mode 100644 index b026258..0000000 --- a/accel-pptpd/triton/timerfd.c +++ /dev/null @@ -1,19 +0,0 @@ -#include -#include -#include - -#include "timerfd.h" - -int timerfd_create (clockid_t __clock_id, int __flags) -{ - return syscall(SYS_timerfd_create, __clock_id, __flags); -} - - -int timerfd_settime (int __ufd, int __flags, - __const struct itimerspec *__utmr, - struct itimerspec *__otmr) -{ - return syscall(SYS_timerfd_settime, __ufd, __flags, __utmr, __otmr); -} - diff --git a/accel-pptpd/triton/timerfd.h b/accel-pptpd/triton/timerfd.h deleted file mode 100644 index c1bb06f..0000000 --- a/accel-pptpd/triton/timerfd.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (C) 2008 Free Software Foundation, Inc. - This file is part of the GNU C Library. - - The GNU C Library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - The GNU C Library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with the GNU C Library; if not, write to the Free - Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - 02111-1307 USA. */ - -#ifndef _SYS_TIMERFD_H -#define _SYS_TIMERFD_H 1 - -#include - - -/* Bits to be set in the FLAGS parameter of `timerfd_create'. */ -enum - { - TFD_CLOEXEC = 02000000, -#define TFD_CLOEXEC TFD_CLOEXEC - TFD_NONBLOCK = 04000 -#define TFD_NONBLOCK TFD_NONBLOCK - }; - - -/* Bits to be set in the FLAGS parameter of `timerfd_settime'. */ -enum - { - TFD_TIMER_ABSTIME = 1 << 0 -#define TFD_TIMER_ABSTIME TFD_TIMER_ABSTIME - }; - - -__BEGIN_DECLS - -/* Return file descriptor for new interval timer source. */ -extern int timerfd_create (clockid_t __clock_id, int __flags) __THROW; - -/* Set next expiration time of interval timer source UFD to UTMR. If - FLAGS has the TFD_TIMER_ABSTIME flag set the timeout value is - absolute. Optionally return the old expiration time in OTMR. */ -extern int timerfd_settime (int __ufd, int __flags, - __const struct itimerspec *__utmr, - struct itimerspec *__otmr) __THROW; - -/* Return the next expiration time of UFD. */ -extern int timerfd_gettime (int __ufd, struct itimerspec *__otmr) __THROW; - -__END_DECLS - -#endif /* sys/timerfd.h */ diff --git a/accel-pptpd/triton/triton.c b/accel-pptpd/triton/triton.c deleted file mode 100644 index 00dfcf6..0000000 --- a/accel-pptpd/triton/triton.c +++ /dev/null @@ -1,610 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include "triton_p.h" -#include "memdebug.h" - -int thread_count = 2; -int max_events = 64; - -static spinlock_t threads_lock = SPINLOCK_INITIALIZER; -static LIST_HEAD(threads); -static LIST_HEAD(sleep_threads); - -static LIST_HEAD(ctx_queue); - -static spinlock_t ctx_list_lock = SPINLOCK_INITIALIZER; -static LIST_HEAD(ctx_list); - -static int terminate; -static int need_terminate; - -static int need_config_reload; -static void (*config_reload_notify)(int); - -static mempool_t *ctx_pool; -static mempool_t *call_pool; - -struct triton_stat_t __export triton_stat; - -static struct timeval ru_utime; -static struct timeval ru_stime; -static struct timespec ru_timestamp; -static int ru_refs; -static void ru_update(struct triton_timer_t *); -static struct triton_timer_t ru_timer = { - .period = 1000, - .expire = ru_update, -}; -struct triton_context_t default_ctx; - -static struct triton_context_t __thread *this_ctx; - -#define log_debug2(fmt, ...) - -void triton_thread_wakeup(struct _triton_thread_t *thread) -{ - log_debug2("wake up thread %p\n", thread); - pthread_kill(thread->thread, SIGUSR1); -} - -static void __config_reload(void (*notify)(int)) -{ - struct _triton_thread_t *t; - int r; - - log_debug2("config_reload: enter\n"); - r = conf_reload(NULL); - notify(r); - - spin_lock(&threads_lock); - need_config_reload = 0; - list_for_each_entry(t, &threads, entry) - triton_thread_wakeup(t); - spin_unlock(&threads_lock); - log_debug2("config_reload: exit\n"); -} - -static void ctx_thread(struct _triton_context_t *ctx); -static void* triton_thread(struct _triton_thread_t *thread) -{ - sigset_t set; - int sig; - - sigfillset(&set); - sigdelset(&set, SIGKILL); - sigdelset(&set, SIGSTOP); - pthread_sigmask(SIG_BLOCK, &set, NULL); - - sigemptyset(&set); - sigaddset(&set, SIGUSR1); - sigaddset(&set, SIGQUIT); - - pthread_mutex_lock(&thread->sleep_lock); - pthread_mutex_unlock(&thread->sleep_lock); - - while (1) { - spin_lock(&threads_lock); - if (!list_empty(&ctx_queue) && !need_config_reload) { - thread->ctx = list_entry(ctx_queue.next, typeof(*thread->ctx), entry2); - log_debug2("thread: %p: dequeued ctx %p\n", thread, thread->ctx); - list_del(&thread->ctx->entry2); - spin_unlock(&threads_lock); - spin_lock(&thread->ctx->lock); - thread->ctx->thread = thread; - thread->ctx->queued = 0; - spin_unlock(&thread->ctx->lock); - __sync_sub_and_fetch(&triton_stat.context_pending, 1); - } else { - if (triton_stat.thread_count > thread_count + triton_stat.context_sleeping) { - __sync_sub_and_fetch(&triton_stat.thread_active, 1); - __sync_sub_and_fetch(&triton_stat.thread_count, 1); - list_del(&thread->entry); - spin_unlock(&threads_lock); - pthread_detach(pthread_self()); - log_debug2("thread: %p: exit\n", thread); - _free(thread); - return NULL; - } - log_debug2("thread: %p: sleeping\n", thread); - if (!terminate) - list_add(&thread->entry2, &sleep_threads); - - if (__sync_sub_and_fetch(&triton_stat.thread_active, 1) == 0 && need_config_reload) { - spin_unlock(&threads_lock); - __config_reload(config_reload_notify); - } else - spin_unlock(&threads_lock); - - if (terminate) - return NULL; - - //printf("thread %p: enter sigwait\n", thread); - sigwait(&set, &sig); - //printf("thread %p: exit sigwait\n", thread); - - spin_lock(&threads_lock); - __sync_add_and_fetch(&triton_stat.thread_active, 1); - if (!thread->ctx) { - list_del(&thread->entry2); - spin_unlock(&threads_lock); - continue; - } - spin_unlock(&threads_lock); - } - -cont: - log_debug2("thread %p: ctx=%p %p\n", thread, thread->ctx, thread->ctx ? thread->ctx->thread : NULL); - this_ctx = thread->ctx->ud; - if (thread->ctx->ud->before_switch) - thread->ctx->ud->before_switch(thread->ctx->ud, thread->ctx->bf_arg); - - log_debug2("thread %p: switch to %p\n", thread, thread->ctx); - ctx_thread(thread->ctx); - log_debug2("thread %p: switch from %p %p\n", thread, thread->ctx, thread->ctx->thread); - - spin_lock(&thread->ctx->lock); - if (thread->ctx->pending) { - spin_unlock(&thread->ctx->lock); - goto cont; - } - thread->ctx->thread = NULL; - spin_unlock(&thread->ctx->lock); - - if (thread->ctx->need_free) { - log_debug2("- context %p removed\n", thread->ctx); - mempool_free(thread->ctx); - } - - thread->ctx = NULL; - } -} - -static void ctx_thread(struct _triton_context_t *ctx) -{ - struct _triton_md_handler_t *h; - struct _triton_timer_t *t; - struct _triton_ctx_call_t *call; - uint64_t tt; - - log_debug2("ctx %p %p: enter\n", ctx, ctx->thread); - if (ctx->need_close) { - if (ctx->ud->close) - ctx->ud->close(ctx->ud); - ctx->need_close = 0; - } - - while (1) { - spin_lock(&ctx->lock); - if (!list_empty(&ctx->pending_timers)) { - t = list_entry(ctx->pending_timers.next, typeof(*t), entry2); - list_del(&t->entry2); - t->pending = 0; - spin_unlock(&ctx->lock); - __sync_sub_and_fetch(&triton_stat.timer_pending, 1); - read(t->fd, &tt, sizeof(tt)); - t->ud->expire(t->ud); - continue; - } - if (!list_empty(&ctx->pending_handlers)) { - h = list_entry(ctx->pending_handlers.next, typeof(*h), entry2); - list_del(&h->entry2); - h->pending = 0; - spin_unlock(&ctx->lock); - __sync_sub_and_fetch(&triton_stat.md_handler_pending, 1); - if (h->trig_epoll_events & (EPOLLIN | EPOLLERR | EPOLLHUP)) - if (h->ud && h->ud->read) - if (h->ud->read(h->ud)) - continue; - if (h->trig_epoll_events & (EPOLLOUT | EPOLLERR | EPOLLHUP)) - if (h->ud && h->ud->write) - if (h->ud->write(h->ud)) - continue; - h->trig_epoll_events = 0; - continue; - } - if (!list_empty(&ctx->pending_calls)) { - call = list_entry(ctx->pending_calls.next, typeof(*call), entry); - list_del(&call->entry); - spin_unlock(&ctx->lock); - call->func(call->arg); - mempool_free(call); - continue; - } - ctx->pending = 0; - spin_unlock(&ctx->lock); - break; - } - - log_debug2("ctx %p %p: exit\n", ctx, ctx->thread); -} - -struct _triton_thread_t *create_thread() -{ - struct _triton_thread_t *thread = _malloc(sizeof(*thread)); - if (!thread) - return NULL; - - memset(thread, 0, sizeof(*thread)); - pthread_mutex_init(&thread->sleep_lock, NULL); - pthread_cond_init(&thread->sleep_cond, NULL); - pthread_mutex_lock(&thread->sleep_lock); - if (pthread_create(&thread->thread, NULL, (void*(*)(void*))triton_thread, thread)) { - triton_log_error("pthread_create: %s", strerror(errno)); - return NULL; - } - - __sync_add_and_fetch(&triton_stat.thread_count, 1); - __sync_add_and_fetch(&triton_stat.thread_active, 1); - - return thread; -} - -int triton_queue_ctx(struct _triton_context_t *ctx) -{ - ctx->pending = 1; - if (ctx->thread || ctx->queued || ctx->init) - return 0; - - spin_lock(&threads_lock); - if (list_empty(&sleep_threads) || need_config_reload) { - if (ctx->priority) - list_add(&ctx->entry2, &ctx_queue); - else - list_add_tail(&ctx->entry2, &ctx_queue); - spin_unlock(&threads_lock); - ctx->queued = 1; - log_debug2("ctx %p: queued\n", ctx); - __sync_add_and_fetch(&triton_stat.context_pending, 1); - return 0; - } - - ctx->thread = list_entry(sleep_threads.next, typeof(*ctx->thread), entry2); - ctx->thread->ctx = ctx; - log_debug2("ctx %p: assigned to thread %p\n", ctx, ctx->thread); - list_del(&ctx->thread->entry2); - spin_unlock(&threads_lock); - - return 1; -} - -int __export triton_context_register(struct triton_context_t *ud, void *bf_arg) -{ - struct _triton_context_t *ctx = mempool_alloc(ctx_pool); - - log_debug2("ctx %p: register\n", ctx); - if (!ctx) - return -1; - - memset(ctx, 0, sizeof(*ctx)); - ctx->ud = ud; - ctx->bf_arg = bf_arg; - ctx->init = 1; - spinlock_init(&ctx->lock); - INIT_LIST_HEAD(&ctx->handlers); - INIT_LIST_HEAD(&ctx->timers); - INIT_LIST_HEAD(&ctx->pending_handlers); - INIT_LIST_HEAD(&ctx->pending_timers); - INIT_LIST_HEAD(&ctx->pending_calls); - - ud->tpd = ctx; - - spin_lock(&ctx_list_lock); - list_add_tail(&ctx->entry, &ctx_list); - spin_unlock(&ctx_list_lock); - - __sync_add_and_fetch(&triton_stat.context_sleeping, 1); - __sync_add_and_fetch(&triton_stat.context_count, 1); - - return 0; -} - -void __export triton_context_unregister(struct triton_context_t *ud) -{ - struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; - struct _triton_ctx_call_t *call; - struct _triton_thread_t *t; - - log_debug2("ctx %p: unregister\n", ctx); - - while (!list_empty(&ctx->pending_calls)) { - call = list_entry(ctx->pending_calls.next, typeof(*call), entry); - list_del(&call->entry); - mempool_free(call); - } - - if (!list_empty(&ctx->handlers)) { - triton_log_error("BUG:ctx:triton_unregister_ctx: handlers is not empty"); - { - struct _triton_md_handler_t *h; - list_for_each_entry(h, &ctx->handlers, entry) - if (h->ud) - printf("%p\n", h->ud); - } - abort(); - } - if (!list_empty(&ctx->pending_handlers)) { - triton_log_error("BUG:ctx:triton_unregister_ctx: pending_handlers is not empty"); - abort(); - } - if (!list_empty(&ctx->timers)) { - triton_log_error("BUG:ctx:triton_unregister_ctx: timers is not empty"); - abort(); - } - if (!list_empty(&ctx->pending_timers)) { - triton_log_error("BUG:ctx:triton_unregister_ctx: pending_timers is not empty"); - abort(); - } - - ctx->need_free = 1; - spin_lock(&ctx_list_lock); - list_del(&ctx->entry); - if (__sync_sub_and_fetch(&triton_stat.context_count, 1) == 1) { - if (need_terminate) - terminate = 1; - } - spin_unlock(&ctx_list_lock); - - if (terminate) { - list_for_each_entry(t, &threads, entry) - triton_thread_wakeup(t); - } -} - -void __export triton_context_set_priority(struct triton_context_t *ud, int prio) -{ - struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; - - ctx->priority = prio > 0; -} - -void __export triton_context_schedule() -{ - struct _triton_context_t *ctx = (struct _triton_context_t *)this_ctx->tpd; - struct _triton_thread_t *t = NULL; - - log_debug2("ctx %p: enter schedule\n", ctx); - __sync_add_and_fetch(&triton_stat.context_sleeping, 1); - __sync_sub_and_fetch(&triton_stat.thread_active, 1); - pthread_mutex_lock(&ctx->thread->sleep_lock); - while (1) { - if (ctx->wakeup) { - ctx->wakeup = 0; - break; - } else { - if (!t && triton_stat.thread_count <= thread_count + triton_stat.context_sleeping) { - t = create_thread(); - spin_lock(&threads_lock); - list_add_tail(&t->entry, &threads); - spin_unlock(&threads_lock); - pthread_mutex_unlock(&t->sleep_lock); - } - pthread_cond_wait(&ctx->thread->sleep_cond, &ctx->thread->sleep_lock); - } - } - pthread_mutex_unlock(&ctx->thread->sleep_lock); - __sync_sub_and_fetch(&triton_stat.context_sleeping, 1); - __sync_add_and_fetch(&triton_stat.thread_active, 1); - log_debug2("ctx %p: exit schedule\n", ctx); -} - -struct triton_context_t __export *triton_context_self(void) -{ - return this_ctx; -} - -void triton_context_print(void) -{ - struct _triton_context_t *ctx; - - list_for_each_entry(ctx, &ctx_list, entry) - printf("%p\n", ctx); -} - -void __export triton_context_wakeup(struct triton_context_t *ud) -{ - struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; - int r = 0; - - log_debug2("ctx %p: wakeup\n", ctx); - - if (ctx->init) { - __sync_sub_and_fetch(&triton_stat.context_sleeping, 1); - spin_lock(&ctx->lock); - ctx->init = 0; - if (ctx->pending) - r = triton_queue_ctx(ctx); - spin_unlock(&ctx->lock); - if (r) - triton_thread_wakeup(ctx->thread); - return; - } - - pthread_mutex_lock(&ctx->thread->sleep_lock); - ctx->wakeup = 1; - pthread_cond_signal(&ctx->thread->sleep_cond); - pthread_mutex_unlock(&ctx->thread->sleep_lock); -} - -int __export triton_context_call(struct triton_context_t *ud, void (*func)(void *), void *arg) -{ - struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; - struct _triton_ctx_call_t *call = mempool_alloc(call_pool); - int r; - - if (!call) - return -1; - - call->func = func; - call->arg = arg; - - spin_lock(&ctx->lock); - list_add_tail(&call->entry, &ctx->pending_calls); - r = triton_queue_ctx(ctx); - spin_unlock(&ctx->lock); - - if (r) - triton_thread_wakeup(ctx->thread); - - return 0; -} - -void __export triton_cancel_call(struct triton_context_t *ud, void (*func)(void *)) -{ - struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; - struct list_head *pos, *n; - struct _triton_ctx_call_t *call; - - list_for_each_safe(pos, n, &ctx->pending_calls) { - call = list_entry(pos, typeof(*call), entry); - if (call->func != func) - continue; - list_del(&call->entry); - mempool_free(call); - } -} - -void __export triton_collect_cpu_usage(void) -{ - struct rusage rusage; - - if (__sync_fetch_and_add(&ru_refs, 1) == 0) { - triton_timer_add(NULL, &ru_timer, 0); - getrusage(RUSAGE_SELF, &rusage); - clock_gettime(CLOCK_MONOTONIC, &ru_timestamp); - ru_utime = rusage.ru_utime; - ru_stime = rusage.ru_stime; - triton_stat.cpu = 0; - } -} - -void __export triton_stop_collect_cpu_usage(void) -{ - if (__sync_sub_and_fetch(&ru_refs, 1) == 0) - triton_timer_del(&ru_timer); -} - -static void ru_update(struct triton_timer_t *t) -{ - struct timespec ts; - struct rusage rusage; - unsigned int dt; - unsigned int val; - - getrusage(RUSAGE_SELF, &rusage); - clock_gettime(CLOCK_MONOTONIC, &ts); - - dt = (ts.tv_sec - ru_timestamp.tv_sec) * 1000000 + (ts.tv_nsec - ru_timestamp.tv_nsec) / 1000000; - val = (double)((rusage.ru_utime.tv_sec - ru_utime.tv_sec) * 1000000 + (rusage.ru_utime.tv_usec - ru_utime.tv_usec) + - (rusage.ru_stime.tv_sec - ru_stime.tv_sec) * 1000000 + (rusage.ru_stime.tv_usec - ru_stime.tv_usec)) / dt * 100; - - if (val <= 100) - triton_stat.cpu = val; - - ru_timestamp = ts; - ru_utime = rusage.ru_utime; - ru_stime = rusage.ru_stime; -} - -int __export triton_init(const char *conf_file) -{ - ctx_pool = mempool_create2(sizeof(struct _triton_context_t)); - call_pool = mempool_create(sizeof(struct _triton_ctx_call_t)); - - if (conf_load(conf_file)) - return -1; - - if (log_init()) - return -1; - - if (md_init()) - return -1; - - if (timer_init()) - return -1; - - if (event_init()) - return -1; - - return 0; -} - -int __export triton_load_modules(const char *mod_sect) -{ - if (load_modules(mod_sect)) - return -1; - - return 0; -} - -void __export triton_conf_reload(void (*notify)(int)) -{ - spin_lock(&threads_lock); - need_config_reload = 1; - config_reload_notify = notify; - if (triton_stat.thread_active == 0) { - spin_unlock(&threads_lock); - __config_reload(notify); - } else - spin_unlock(&threads_lock); -} - -void __export triton_run() -{ - struct _triton_thread_t *t; - int i; - char *opt; - - opt = conf_get_opt("core", "thread-count"); - if (opt && atoi(opt) > 0) - thread_count = atoi(opt); - - for(i = 0; i < thread_count; i++) { - t = create_thread(); - if (!t) - _exit(-1); - - list_add_tail(&t->entry, &threads); - pthread_mutex_unlock(&t->sleep_lock); - } - - time(&triton_stat.start_time); - - md_run(); - timer_run(); - - triton_context_register(&default_ctx, NULL); - triton_context_wakeup(&default_ctx); -} - -void __export triton_terminate() -{ - struct _triton_context_t *ctx; - struct _triton_thread_t *t; - int r; - - need_terminate = 1; - - spin_lock(&ctx_list_lock); - list_for_each_entry(ctx, &ctx_list, entry) { - spin_lock(&ctx->lock); - ctx->need_close = 1; - r = triton_queue_ctx(ctx); - if (r) - triton_thread_wakeup(ctx->thread); - spin_unlock(&ctx->lock); - } - spin_unlock(&ctx_list_lock); - - list_for_each_entry(t, &threads, entry) - pthread_join(t->thread, NULL); - - md_terminate(); - timer_terminate(); -} - diff --git a/accel-pptpd/triton/triton.h b/accel-pptpd/triton/triton.h deleted file mode 100644 index 6866d52..0000000 --- a/accel-pptpd/triton/triton.h +++ /dev/null @@ -1,138 +0,0 @@ -#ifndef TRITON_H -#define TRITON_H - -#include -#include - -#include "list.h" - -struct triton_context_t -{ - const void *tpd; // triton private data, don't touch - void (*close)(struct triton_context_t*); - void (*free)(struct triton_context_t*); - void (*before_switch)(struct triton_context_t *ctx, void *arg); -}; - -struct triton_md_handler_t -{ - const void *tpd; // triton private data, don't touch! - int fd; - int (*read)(struct triton_md_handler_t *); - int (*write)(struct triton_md_handler_t *); -}; - -struct triton_timer_t -{ - const void *tpd; // triton private data, don't touch! - struct timeval expire_tv; - int period; - void (*expire)(struct triton_timer_t *); -}; - -struct triton_sigchld_handler_t -{ - void *tpd; - int pid; - void (*handler)(struct triton_sigchld_handler_t *h, int status); -}; - -struct conf_option_t -{ - struct list_head entry; - char *name; - char *val; -}; - -struct conf_sect_t -{ - const char *name; - struct list_head items; -}; - -struct triton_stat_t -{ - unsigned int mempool_allocated; - unsigned int mempool_available; - unsigned int thread_count; - unsigned int thread_active; - unsigned int context_count; - unsigned int context_sleeping; - unsigned int context_pending; - unsigned int md_handler_count; - unsigned int md_handler_pending; - unsigned int timer_count; - unsigned int timer_pending; - time_t start_time; - unsigned int cpu; -}; - -extern struct triton_stat_t triton_stat; -int triton_context_register(struct triton_context_t *, void *arg); -void triton_context_unregister(struct triton_context_t *); -void triton_context_set_priority(struct triton_context_t *, int); -void triton_context_schedule(void); -void triton_context_wakeup(struct triton_context_t *); -int triton_context_call(struct triton_context_t *, void (*func)(void *), void *arg); -void triton_cancel_call(struct triton_context_t *, void (*func)(void *)); -struct triton_context_t *triton_context_self(void); - -#define MD_MODE_READ 1 -#define MD_MODE_WRITE 2 - -#define MD_TRIG_EDGE 0 -#define MD_TRIG_LEVEL 1 - -void triton_md_register_handler(struct triton_context_t *, struct triton_md_handler_t *); -void triton_md_unregister_handler(struct triton_md_handler_t *h); -int triton_md_enable_handler(struct triton_md_handler_t *h, int mode); -int triton_md_disable_handler(struct triton_md_handler_t *h,int mode); -void triton_md_set_trig(struct triton_md_handler_t *h, int mode); - -int triton_timer_add(struct triton_context_t *ctx, struct triton_timer_t*,int abs_time); -int triton_timer_mod(struct triton_timer_t *,int abs_time); -void triton_timer_del(struct triton_timer_t *); - -typedef void (*triton_event_func)(void *); -int triton_event_register_handler(int ev_id, triton_event_func func); -void triton_event_fire(int ev_id, void *arg); - -struct conf_sect_t *conf_get_section(const char *name); -char *conf_get_opt(const char *sect, const char *name); -void triton_conf_reload(void (*notify)(int)); - -void triton_collect_cpu_usage(void); -void triton_stop_collect_cpu_usage(void); - - -#define TRITON_OK 0 -#define TRITON_ERR_NOCOMP -1 -#define TRITON_ERR_NOSUPP -2 -#define TRITON_ERR_NOINTF -3 -#define TRITON_ERR_EXISTS -4 -#define TRITON_ERR_NOCHAN -5 -#define TRITON_ERR_NOMSG -6 -#define TRITON_ERR_BUSY -5 - -int triton_init(const char *conf_file); -int triton_load_modules(const char *md_sect); -void triton_run(void); -void triton_terminate(void); - - -#define __init __attribute__((constructor)) -#define __exit __attribute__((destructor)) -#define __export __attribute__((visibility("default"))) - -#undef offsetof -#ifdef __compiler_offsetof -#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER) -#else -#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) -#endif - -#define container_of(ptr, type, member) ({ \ - const typeof( ((type *)0)->member ) *__mptr = (ptr); \ - (type *)( (char *)__mptr - offsetof(type,member) );}) - -#endif diff --git a/accel-pptpd/triton/triton_p.h b/accel-pptpd/triton/triton_p.h deleted file mode 100644 index 235eb70..0000000 --- a/accel-pptpd/triton/triton_p.h +++ /dev/null @@ -1,103 +0,0 @@ -#ifndef TRITON_P_H -#define TRITON_P_H - -#include -#include - -#include "triton.h" -#include "list.h" -#include "spinlock.h" -#include "mempool.h" - -struct _triton_thread_t -{ - struct list_head entry; - struct list_head entry2; - pthread_t thread; - int terminate; - struct _triton_context_t *ctx; - pthread_mutex_t sleep_lock; - pthread_cond_t sleep_cond; -}; - -struct _triton_context_t -{ - struct list_head entry; - struct list_head entry2; - - spinlock_t lock; - struct _triton_thread_t *thread; - - struct list_head handlers; - struct list_head timers; - struct list_head pending_handlers; - struct list_head pending_timers; - struct list_head pending_calls; - - int init; - int queued; - int wakeup; - int need_close; - int need_free; - int pending; - int priority; - - struct triton_context_t *ud; - void *bf_arg; -}; - -struct _triton_md_handler_t -{ - struct list_head entry; - struct list_head entry2; - struct _triton_context_t *ctx; - struct epoll_event epoll_event; - uint32_t trig_epoll_events; - int pending:1; - int trig_level:1; - struct triton_md_handler_t *ud; -}; - -struct _triton_timer_t -{ - struct list_head entry; - struct list_head entry2; - struct epoll_event epoll_event; - struct _triton_context_t *ctx; - int fd; - int pending:1; - struct triton_timer_t *ud; -}; - -struct _triton_event_t -{ - struct list_head handlers; -}; - -struct _triton_ctx_call_t -{ - struct list_head entry; - - void *arg; - void (*func)(void *); -}; - -int log_init(void); -int md_init(); -int timer_init(); -int event_init(); - -void md_run(); -void md_terminate(); -void timer_run(); -void timer_terminate(); -extern struct triton_context_t default_ctx; -int triton_queue_ctx(struct _triton_context_t*); -void triton_thread_wakeup(struct _triton_thread_t*); -int conf_load(const char *fname); -int conf_reload(const char *fname); -void triton_log_error(const char *fmt,...); -void triton_log_debug(const char *fmt,...); -int load_modules(const char *name); - -#endif diff --git a/accel-pptpd/utils.c b/accel-pptpd/utils.c deleted file mode 100644 index 491e650..0000000 --- a/accel-pptpd/utils.c +++ /dev/null @@ -1,11 +0,0 @@ -#include - -#include "triton.h" -#include "utils.h" - -#include "memdebug.h" - -void __export u_inet_ntoa(in_addr_t addr, char *str) -{ - sprintf(str, "%i.%i.%i.%i", addr & 0xff, (addr >> 8) & 0xff, (addr >> 16) & 0xff, (addr >> 24) & 0xff); -} diff --git a/accel-pptpd/utils.h b/accel-pptpd/utils.h deleted file mode 100644 index 27d4d05..0000000 --- a/accel-pptpd/utils.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef __UTILS_H -#define __UTILS_H - -#include - -void u_inet_ntoa(in_addr_t, char *str); - -#endif -- cgit v1.2.3