diff options
author | Kozlov Dmitry <dima@server> | 2010-10-06 16:55:05 +0400 |
---|---|---|
committer | Kozlov Dmitry <dima@server> | 2010-10-06 16:55:05 +0400 |
commit | 45b3c9c5bdd896f51f47e29069e3c030ddb17d51 (patch) | |
tree | cbec5824ffb2eee20b98ad9892a357304384ff01 /accel-pptpd | |
parent | ba3db9f17477ea4b49c266c5cb50f63f3b074db2 (diff) | |
parent | 01ccd98495c9da1e79f7867bf52416b23f20200d (diff) | |
download | accel-ppp-45b3c9c5bdd896f51f47e29069e3c030ddb17d51.tar.gz accel-ppp-45b3c9c5bdd896f51f47e29069e3c030ddb17d51.zip |
merged branch accel-pptpd
Diffstat (limited to 'accel-pptpd')
115 files changed, 17203 insertions, 0 deletions
diff --git a/accel-pptpd/CMakeLists.txt b/accel-pptpd/CMakeLists.txt new file mode 100644 index 00000000..dd1b2570 --- /dev/null +++ b/accel-pptpd/CMakeLists.txt @@ -0,0 +1,56 @@ +SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -fvisibility=hidden -D_GNU_SOURCE -DGCC_SPINLOCK -DMEMDEBUG") + +INCLUDE_DIRECTORIES(include) + +ADD_SUBDIRECTORY(triton) +ADD_SUBDIRECTORY(ctrl) +ADD_SUBDIRECTORY(auth) +ADD_SUBDIRECTORY(radius) +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 + + pwdb.c + ipdb.c + + iprange.c + + utils.c + + log.c + main.c + memdebug.c +) + +SET( FALSE) +SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) + +TARGET_LINK_LIBRARIES(accel-pptpd triton rt pthread ssl) +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}/usr/lib/accel-pptp) + +INSTALL(TARGETS accel-pptpd + RUNTIME DESTINATION usr/sbin +) + +INSTALL(FILES accel-pptp.conf DESTINATION /etc) +INSTALL(FILES accel-pptp.conf.5 DESTINATION usr/share/man/man5) + +INSTALL(CODE "EXECUTE_PROCESS(COMMAND mkdir -p /var/log/accel-pptp)") + diff --git a/accel-pptpd/accel-pptp.conf b/accel-pptpd/accel-pptp.conf new file mode 100644 index 00000000..62c0f897 --- /dev/null +++ b/accel-pptpd/accel-pptp.conf @@ -0,0 +1,77 @@ +[modules] +#path=/usr/local/lib/accel-pptp +log_file +#log_pgsql +pptp +auth_pap +auth_chap_md5 +auth_mschap_v1 +auth_mschap_v2 +radius +ippool +sigchld +pppd_compat + +[core] +log-error=/var/log/accel-pptp/core.log +thread-count=4 + +[ppp] +verbose=1 +min-mtu=1000 +mtu=1200 +mru=1200 + +[lcp] +echo-interval=30 +echo-failure=3 + +[pptp] +echo-interval=30 +verbose=1 + +[dns] +#dns1=172.16.0.1 +#dns2=172.16.1.1 + +[radius] +#dictionary=/usr/local/share/accel-pptp/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 +dm_coa_secret=testing123 +verbose=1 + +[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 +copy=1 +#color=1 +#per-user-dir=per_user +#per-session-dir=per_session +#per-session=1 +level=3 + +[log-pgsql] +conninfo=user=log +log-table=log + +[pppd-compat] +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 diff --git a/accel-pptpd/accel-pptp.conf.5 b/accel-pptpd/accel-pptp.conf.5 new file mode 100644 index 00000000..a983c7c9 --- /dev/null +++ b/accel-pptpd/accel-pptp.conf.5 @@ -0,0 +1,272 @@ +.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_pgsql +This is logging target which logs messages to PostgreSQL. +.TP +.BI pptp +.br +PPTP controlling connection 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 +.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 [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 "dm_coa_secret=" secret +Specifies secret to use in DM/CoA communication. +.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 "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 information messages (use this level in conjuction with verbose option of other modules if you need verbose logging) +.br +.B 4 +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-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 new file mode 100644 index 00000000..69b18b7b --- /dev/null +++ b/accel-pptpd/auth/CMakeLists.txt @@ -0,0 +1,9 @@ +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) + +INSTALL(TARGETS auth_pap auth_chap_md5 auth_mschap_v1 auth_mschap_v2 + LIBRARY DESTINATION usr/lib/accel-pptp +) + diff --git a/accel-pptpd/auth/auth_chap_md5.c b/accel-pptpd/auth/auth_chap_md5.c new file mode 100644 index 00000000..4031a9a7 --- /dev/null +++ b/accel-pptpd/auth/auth_chap_md5.c @@ -0,0 +1,398 @@ +#include <stdint.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <fcntl.h> +#include <errno.h> +#include <stdio.h> +#include <arpa/inet.h> + +#include <openssl/md5.h> + +#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 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(struct triton_timer_t *t); +static void chap_restart(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_info("%x", buf[i]); +} +static void print_str(const char *buf, int size) +{ + int i; + for (i = 0; i < size; i++) + log_ppp_info("%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); + + _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; + d->timeout.period = conf_timeout * 1000; + d->interval.expire = chap_restart; + 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(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, 0); + else + auth_failed(d->ppp); + } else { + --d->id; + chap_send_challenge(d); + } +} + +static void chap_restart(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_info("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_info("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_info("send [CHAP Challenge id=%x <", msg.hdr.id); + print_buf(msg.val, VALUE_SIZE); + log_ppp_info(">]\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_info("recv [CHAP Response id=%x <", msg->hdr.id); + print_buf(msg->val, msg->val_size); + log_ppp_info(">, name=\""); + print_str(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); + log_ppp_info("\"]\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, 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, 0); + } + + name = _strndup(msg->name,ntohs(msg->hdr.len) - sizeof(*msg) + 2); + + 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, 0); + else + auth_failed(ad->ppp); + }else + { + chap_send_success(ad); + if (!ad->started) { + ad->started = 1; + if (conf_interval) + triton_timer_add(ad->ppp->ctrl->ctx, &ad->interval, 0); + auth_successed(ad->ppp, name); + } + } + _free(name); + _free(passwd); + } else if (r == PWDB_DENIED) { + chap_send_failure(ad); + _free(name); + if (ad->started) + ppp_terminate(ad->ppp, 0); + else + auth_failed(ad->ppp); + } else { + chap_send_success(ad); + if (!ad->started) { + ad->started = 1; + if (conf_interval) + triton_timer_add(ad->ppp->ctrl->ctx, &ad->interval, 0); + auth_successed(ad->ppp, name); + } + } +} + +static int chap_check(uint8_t *ptr) +{ + return *ptr == CHAP_MD5; +} + +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, +}; + +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); + + 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 new file mode 100644 index 00000000..5b4935ea --- /dev/null +++ b/accel-pptpd/auth/auth_mschap_v1.c @@ -0,0 +1,453 @@ +#include <stdint.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <fcntl.h> +#include <errno.h> +#include <stdio.h> +#include <byteswap.h> +#include <arpa/inet.h> + +#include <openssl/md4.h> +#include <openssl/des.h> + +#include "log.h" +#include "ppp.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 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(struct triton_timer_t *t); +static void chap_restart(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_info("%x", buf[i]); +} +static void print_str(const char *buf, int size) +{ + int i; + for(i = 0; i < size; i++) + log_ppp_info("%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); + + _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; + d->timeout.period = conf_timeout * 1000; + d->interval.expire = chap_restart; + 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(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, 0); + else + auth_failed(d->ppp); + } else { + --d->id; + chap_send_challenge(d); + } +} + +static void chap_restart(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_info("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_info("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_info("send [MSCHAP-v1 Challenge id=%x <", msg.hdr.id); + print_buf(msg.val, VALUE_SIZE); + log_ppp_info(">]\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_info("recv [MSCHAP-v1 Response id=%x <", msg->hdr.id); + print_buf(msg->lm_hash, 24); + log_ppp_info(">, <"); + print_buf(msg->nt_hash, 24); + log_ppp_info(">, F=%i, name=\"", msg->flags); + print_str(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); + log_ppp_info("\"]\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, 0); + else + auth_failed(ad->ppp); + } + + 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, 0); + else + auth_failed(ad->ppp); + } + + 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, 0); + else + auth_failed(ad->ppp); + 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) + r = chap_check_response(ad, msg, name); + + if (r == PWDB_DENIED) { + chap_send_failure(ad); + if (ad->started) + ppp_terminate(ad->ppp, 0); + else + auth_failed(ad->ppp); + _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); + auth_successed(ad->ppp, 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); + + _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 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, +}; + +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); + + 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 new file mode 100644 index 00000000..a93fad62 --- /dev/null +++ b/accel-pptpd/auth/auth_mschap_v2.c @@ -0,0 +1,529 @@ +#include <stdint.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <fcntl.h> +#include <errno.h> +#include <stdio.h> +#include <byteswap.h> +#include <arpa/inet.h> + +#include <openssl/md4.h> +#include <openssl/des.h> +#include <openssl/sha.h> + +#include "log.h" +#include "ppp.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; + +static 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}; +static 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}; + +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(struct triton_timer_t *t); +static void chap_restart(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_info("%x", buf[i]); +} + +static void print_str(const char *buf, int size) +{ + int i; + for (i = 0; i < size; i++) + log_ppp_info("%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); + + _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; + d->timeout.period = conf_timeout * 1000; + d->interval.expire = chap_restart; + 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(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, 0); + else + auth_failed(d->ppp); + } else { + --d->id; + chap_send_challenge(d); + } +} + +static void chap_restart(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_info("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; + + passwd = pwdb_get_passwd(ad->ppp,name); + if (!passwd) + return -1; + + 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; + } + + MD4_Init(&md4_ctx); + MD4_Update(&md4_ctx,u_passwd,strlen(passwd)*2); + MD4_Final(pw_hash,&md4_ctx); + + MD4_Init(&md4_ctx); + MD4_Update(&md4_ctx,pw_hash,16); + MD4_Final(pw_hash,&md4_ctx); + + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx,pw_hash,16); + SHA1_Update(&sha_ctx,msg->nt_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_info("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_info("send [MSCHAP-v2 Challenge id=%x <", msg.hdr.id); + print_buf(msg.val, VALUE_SIZE); + log_ppp_info(">]\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[40]; + int r; + + if (ad->timeout.tpd) + triton_timer_del(&ad->timeout); + + if (conf_ppp_verbose) { + log_ppp_info("recv [MSCHAP-v2 Response id=%x <", msg->hdr.id); + print_buf(msg->peer_challenge,16); + log_ppp_info(">, <"); + print_buf(msg->nt_hash, 24); + log_ppp_info(">, F=%i, name=\"", msg->flags); + print_str(msg->name, ntohs(msg->hdr.len) - sizeof(*msg) + 2); + log_ppp_info("\"]\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, 0); + else + auth_failed(ad->ppp); + } + + 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, 0); + else + auth_failed(ad->ppp); + } + + 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, 0); + else + auth_failed(ad->ppp); + 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 (generate_response(ad, msg, name, authenticator)) + r = PWDB_DENIED; + } + + if (r == PWDB_DENIED) { + chap_send_failure(ad); + if (ad->started) + ppp_terminate(ad->ppp, 0); + else + auth_failed(ad->ppp); + _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); + auth_successed(ad->ppp, 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; i<strlen(passwd); i++) + { + u_passwd[i*2]=passwd[i]; + u_passwd[i*2+1]=0; + } + + 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); + + 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); + + _free(passwd); + _free(u_passwd); + + return memcmp(nt_hash,msg->nt_hash,24); +} + +static int chap_check(uint8_t *ptr) +{ + return *ptr == MSCHAP_V2; +} + +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, +}; + +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 new file mode 100644 index 00000000..b044f640 --- /dev/null +++ b/accel-pptpd/auth/auth_pap.c @@ -0,0 +1,259 @@ +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <arpa/inet.h> + +#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 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"); + + auth_failed(d->ppp); +} + +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_info("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_info("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; + const 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_info("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); + 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; + } + 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, 0); + else + auth_failed(p->ppp); + ret=-1; + _free(peer_id); + } else { + pap_send_ack(p, hdr->id); + if (!p->started) { + p->started = 1; + 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); + + ppp_auth_register_handler(&pap); +} + diff --git a/accel-pptpd/ctrl/CMakeLists.txt b/accel-pptpd/ctrl/CMakeLists.txt new file mode 100644 index 00000000..53b0dc1c --- /dev/null +++ b/accel-pptpd/ctrl/CMakeLists.txt @@ -0,0 +1,8 @@ +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +ADD_LIBRARY(pptp SHARED pptp.c) + +INSTALL(TARGETS pptp + LIBRARY DESTINATION usr/lib/accel-pptp +) + diff --git a/accel-pptpd/ctrl/pptp.c b/accel-pptpd/ctrl/pptp.c new file mode 100644 index 00000000..1151dabe --- /dev/null +++ b/accel-pptpd/ctrl/pptp.c @@ -0,0 +1,736 @@ +#include <unistd.h> +#include <stdlib.h> +#include <stdio.h> +#include <stdarg.h> +#include <errno.h> +#include <string.h> +#include <fcntl.h> +#include <time.h> +#include <arpa/inet.h> +#include <netinet/in.h> +#include <sys/socket.h> + +#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 "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 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) { + conn->state = STATE_CLOSE; + ppp_terminate(&conn->ppp, 1); + } + + triton_event_fire(EV_CTRL_FINISHED, &conn->ppp); + + if (conf_verbose) + log_ppp_info("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_info("pptp: write: %s\n", strerror(errno)); + return -1; + } + } + } + + if ( n<size ) { + memcpy(conn->out_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_info("send [PPTP Stop-Ctrl-Conn-Request <Reason %i>]\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_info("send [PPTP Stop-Ctrl-Conn-Reply <Result %i> <Error %i>]\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_info("recv [PPTP Stop-Ctrl-Conn-Request <Reason %i>]\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_info("recv [PPTP Stop-Ctrl-Conn-Reply <Result %i> <Error %i>]\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_info("send [PPTP Start-Ctrl-Conn-Reply <Version %i> <Result %i> <Error %i> <Framing %x> <Bearer %x> <Max-Chan %i>]\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_info("recv [PPTP Start-Ctrl-Conn-Request <Version %i> <Framing %x> <Bearer %x> <Max-Chan %i>]\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_info("send [PPTP Outgoing-Call-Reply <Call-ID %x> <Peer-Call-ID %x> <Result %i> <Error %i> <Cause %i> <Speed %i> <Window-Size %i> <Delay %i> <Channel %x>]\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_info("recv [PPTP Outgoing-Call-Request <Call-ID %x> <Call-Serial %x> <Min-BPS %i> <Max-BPS %i> <Bearer %x> <Framing %x> <Window-Size %i> <Delay %i>]\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; + } + + 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; + + 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; + + 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_info("send [PPTP Call-Disconnect-Notify <Call-ID %x> <Result %i> <Error %i> <Cause %i>]\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_info("recv [PPTP Call-Clear-Request <Call-ID %x>]\n", ntohs(rqst->call_id)); + + if (conn->state == STATE_PPP) { + conn->state = STATE_CLOSE; + ppp_terminate(&conn->ppp, 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_info("recv [PPTP Echo-Request <Identifier %x>]\n", in_msg->identifier); + log_ppp_info("send [PPTP Echo-Reply <Identifier %x>]\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_info("recv [PPTP Echo-Reply <Identifier %x>]\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_info("send [PPTP Echo-Request <Identifier %x>]\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_info("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_info("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_info("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) { + conn->state = STATE_CLOSE; + ppp_terminate(&conn->ppp, 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; + + 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; + } + + log_info("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); + } + 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, +}; + +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; + } + + 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; + + conn_pool = mempool_create(sizeof(struct pptp_conn_t)); + + 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/ctrl/pptp_prot.h b/accel-pptpd/ctrl/pptp_prot.h new file mode 100644 index 00000000..ee8cb341 --- /dev/null +++ b/accel-pptpd/ctrl/pptp_prot.h @@ -0,0 +1,299 @@ +#ifndef PPTP_PROT_H +#define PPTP_PROT_H + +#include <sys/types.h> + +#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 new file mode 100644 index 00000000..a14a5a3b --- /dev/null +++ b/accel-pptpd/extra/CMakeLists.txt @@ -0,0 +1,8 @@ +ADD_LIBRARY(pppd_compat SHARED pppd_compat.c) +ADD_LIBRARY(ippool SHARED ippool.c) +ADD_LIBRARY(sigchld SHARED sigchld.c) + +INSTALL(TARGETS pppd_compat ippool sigchld + LIBRARY DESTINATION usr/lib/accel-pptp +) + diff --git a/accel-pptpd/extra/ippool.c b/accel-pptpd/extra/ippool.c new file mode 100644 index 00000000..5f90fe8a --- /dev/null +++ b/accel-pptpd/extra/ippool.c @@ -0,0 +1,208 @@ +#include <stdlib.h> +#include <stdio.h> +#include <stdint.h> +#include <unistd.h> +#include <string.h> +#include <arpa/inet.h> + +#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 (f1 > 255) + return -1; + if (f1 > 255) + return -1; + if (f1 > 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 new file mode 100644 index 00000000..8dd35028 --- /dev/null +++ b/accel-pptpd/extra/pppd_compat.c @@ -0,0 +1,379 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <signal.h> +#include <unistd.h> +#include <sched.h> +#include <limits.h> + +#include "triton.h" + +#include "events.h" +#include "ppp.h" +#include "log.h" +#include "radius.h" +#include "utils.h" +#include "sigchld.h" + +#include "memdebug.h" + +static char *conf_ip_up = "/etc/ppp/ip-up"; +static char *conf_ip_down = "/etc/ppp/ip-down"; +static char *conf_ip_change = "/etc/ppp/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_up_hnd; + struct sigchld_handler_t ip_change_hnd; + struct sigchld_handler_t ip_down_hnd; + int radattr_saved:1; + int started:1; + int ip_change_res; +}; + +static void remove_radattr(struct ppp_t *ppp); +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 write_radattr(struct ppp_t *ppp, struct rad_packet_t *pack, int save_old); + +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_info("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_info("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_info("pppd_compat: ip-change finished (%i)\n", status); + } + sched_yield(); + pd->ip_change_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_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_started(struct ppp_t *ppp) +{ + pid_t pid; + char *argv[8]; + char ipaddr[16]; + char peer_ipaddr[16]; + 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); + + 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_info("pppd_compat: ip-up started (pid %i)\n", pid); + sigchld_unlock(); + } else if (pid == 0) { + execv(conf_ip_up, argv); + 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_finished(struct ppp_t *ppp) +{ + pid_t pid; + char *argv[8]; + char ipaddr[16]; + char peer_ipaddr[16]; + 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); + + 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_info("pppd_compat: ip-down started (pid %i)\n", pid); + sigchld_unlock(); + triton_context_schedule(pd->ppp->ctrl->ctx); + pthread_mutex_lock(&pd->ip_down_hnd.lock); + pthread_mutex_unlock(&pd->ip_down_hnd.lock); + } else if (pid == 0) { + execv(conf_ip_down, argv); + 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)); + + 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: + if (pd->radattr_saved) + remove_radattr(ppp); + + list_del(&pd->pd.entry); + _free(pd); +} + +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 ipaddr[16]; + char peer_ipaddr[16]; + 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); + + 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_debug("pppd_compat: ip-change started (pid %i)\n", pid); + triton_context_schedule(pd->ppp->ctrl->ctx); + if (!ev->res) + ev->res = pd->ip_change_res; + } else if (pid == 0) { + execv(conf_ip_change, argv); + 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; + 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); +} + +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] = "none"; + argv[7] = NULL; +} + +static void __init init(void) +{ + char *opt; + + opt = conf_get_opt("pppd-compat", "ip-up"); + if (opt) + conf_ip_up = opt; + + opt = conf_get_opt("pppd-compat", "ip-down"); + if (opt) + conf_ip_down = opt; + + opt = conf_get_opt("pppd-compat", "ip-change"); + if (opt) + conf_ip_change = opt; + + opt = conf_get_opt("pppd-compat", "radattr-prefix"); + if (opt) + conf_radattr_prefix = 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_STARTED, (triton_event_func)ev_ppp_started); + triton_event_register_handler(EV_PPP_FINISHED, (triton_event_func)ev_ppp_finished); + 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); +} + diff --git a/accel-pptpd/extra/sigchld.c b/accel-pptpd/extra/sigchld.c new file mode 100644 index 00000000..49bcfd43 --- /dev/null +++ b/accel-pptpd/extra/sigchld.c @@ -0,0 +1,117 @@ +#include <stdio.h> +#include <string.h> +#include <errno.h> +#include <signal.h> +#include <sys/signalfd.h> +#include <sys/wait.h> + +#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; + pthread_mutex_lock(&h0->lock); + break; + } + } + pthread_mutex_unlock(&handlers_lock); + if (h0) { + list_del(&h0->entry); + 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 new file mode 100644 index 00000000..27d1adf4 --- /dev/null +++ b/accel-pptpd/extra/sigchld.h @@ -0,0 +1,21 @@ +#ifndef __SIGCHLD_H +#define __SIGCHLD_H + +#include <pthread.h> +#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/events.h b/accel-pptpd/include/events.h new file mode 100644 index 00000000..2f4c4e5c --- /dev/null +++ b/accel-pptpd/include/events.h @@ -0,0 +1,38 @@ +#ifndef __EVENTS_H +#define __EVENTS_H + +#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_IP_CHANGED 100 +#define EV_SHAPE_CHANGED 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; +}; + +#endif + diff --git a/accel-pptpd/include/if_pppox.h b/accel-pptpd/include/if_pppox.h new file mode 100644 index 00000000..da327a1c --- /dev/null +++ b/accel-pptpd/include/if_pppox.h @@ -0,0 +1,227 @@ +/*************************************************************************** + * 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 <asm/types.h> +#include <asm/byteorder.h> +#include <linux/version.h> + +#ifdef __KERNEL__ +#include <linux/in.h> +#include <linux/if_ether.h> +#include <linux/if.h> +#include <linux/netdevice.h> +#include <linux/ppp_channel.h> +#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 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 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 <asm/byteorder.h>" +#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 <net/sock.h> + +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 new file mode 120000 index 00000000..77ab85b8 --- /dev/null +++ b/accel-pptpd/include/ipdb.h @@ -0,0 +1 @@ +../ipdb.h
\ No newline at end of file diff --git a/accel-pptpd/include/iprange.h b/accel-pptpd/include/iprange.h new file mode 120000 index 00000000..b8c2c43d --- /dev/null +++ b/accel-pptpd/include/iprange.h @@ -0,0 +1 @@ +../iprange.h
\ No newline at end of file diff --git a/accel-pptpd/include/list.h b/accel-pptpd/include/list.h new file mode 120000 index 00000000..4b6d9a91 --- /dev/null +++ b/accel-pptpd/include/list.h @@ -0,0 +1 @@ +../triton/list.h
\ No newline at end of file diff --git a/accel-pptpd/include/log.h b/accel-pptpd/include/log.h new file mode 120000 index 00000000..49a04dd9 --- /dev/null +++ b/accel-pptpd/include/log.h @@ -0,0 +1 @@ +../log.h
\ No newline at end of file diff --git a/accel-pptpd/include/memdebug.h b/accel-pptpd/include/memdebug.h new file mode 120000 index 00000000..3ee61bc2 --- /dev/null +++ b/accel-pptpd/include/memdebug.h @@ -0,0 +1 @@ +../memdebug.h
\ No newline at end of file diff --git a/accel-pptpd/include/mempool.h b/accel-pptpd/include/mempool.h new file mode 120000 index 00000000..2637ab65 --- /dev/null +++ b/accel-pptpd/include/mempool.h @@ -0,0 +1 @@ +../triton/mempool.h
\ No newline at end of file diff --git a/accel-pptpd/include/ppp.h b/accel-pptpd/include/ppp.h new file mode 120000 index 00000000..ae3fa2ef --- /dev/null +++ b/accel-pptpd/include/ppp.h @@ -0,0 +1 @@ +../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 new file mode 120000 index 00000000..527c8538 --- /dev/null +++ b/accel-pptpd/include/ppp_auth.h @@ -0,0 +1 @@ +../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 new file mode 120000 index 00000000..5c6b7f47 --- /dev/null +++ b/accel-pptpd/include/ppp_fsm.h @@ -0,0 +1 @@ +../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 new file mode 120000 index 00000000..49027522 --- /dev/null +++ b/accel-pptpd/include/ppp_lcp.h @@ -0,0 +1 @@ +../ppp/ppp_lcp.h
\ No newline at end of file diff --git a/accel-pptpd/include/pwdb.h b/accel-pptpd/include/pwdb.h new file mode 120000 index 00000000..360efe4d --- /dev/null +++ b/accel-pptpd/include/pwdb.h @@ -0,0 +1 @@ +../pwdb.h
\ No newline at end of file diff --git a/accel-pptpd/include/radius.h b/accel-pptpd/include/radius.h new file mode 120000 index 00000000..e1465f19 --- /dev/null +++ b/accel-pptpd/include/radius.h @@ -0,0 +1 @@ +../radius/radius.h
\ No newline at end of file diff --git a/accel-pptpd/include/sigchld.h b/accel-pptpd/include/sigchld.h new file mode 120000 index 00000000..9b74ebdb --- /dev/null +++ b/accel-pptpd/include/sigchld.h @@ -0,0 +1 @@ +../extra/sigchld.h
\ No newline at end of file diff --git a/accel-pptpd/include/spinlock.h b/accel-pptpd/include/spinlock.h new file mode 120000 index 00000000..09edcf6b --- /dev/null +++ b/accel-pptpd/include/spinlock.h @@ -0,0 +1 @@ +../triton/spinlock.h
\ No newline at end of file diff --git a/accel-pptpd/include/triton.h b/accel-pptpd/include/triton.h new file mode 120000 index 00000000..6f35a2fe --- /dev/null +++ b/accel-pptpd/include/triton.h @@ -0,0 +1 @@ +../triton/triton.h
\ No newline at end of file diff --git a/accel-pptpd/include/utils.h b/accel-pptpd/include/utils.h new file mode 120000 index 00000000..6cd5d4fd --- /dev/null +++ b/accel-pptpd/include/utils.h @@ -0,0 +1 @@ +../utils.h
\ No newline at end of file diff --git a/accel-pptpd/ipdb.c b/accel-pptpd/ipdb.c new file mode 100644 index 00000000..a08d3be2 --- /dev/null +++ b/accel-pptpd/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-pptpd/ipdb.h b/accel-pptpd/ipdb.h new file mode 100644 index 00000000..ebf38853 --- /dev/null +++ b/accel-pptpd/ipdb.h @@ -0,0 +1,29 @@ +#ifndef IPDB_H +#define IPDB_H + +#include <netinet/in.h> + +#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 new file mode 100644 index 00000000..0b1997e9 --- /dev/null +++ b/accel-pptpd/iprange.c @@ -0,0 +1,136 @@ +#include <stdlib.h> +#include <stdio.h> +#include <stdint.h> +#include <unistd.h> + +#include "triton.h" +#include "list.h" + +#include "iprange.h" + +#include "memdebug.h" + +struct iprange_t +{ + struct list_head entry; + uint32_t prefix; + uint32_t mask; + uint32_t end; +}; + +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; + + n = sscanf(str, "%u.%u.%u.%u/%u",&f1, &f2, &f3, &f4, &m); + if (n != 5) + return NULL; + if (f1 > 255) + return NULL; + if (f1 > 255) + return NULL; + if (f1 > 255) + return NULL; + if (f1 > 255) + return NULL; + if (m == 0 || m > 32) + return NULL; + + r = _malloc(sizeof(*r)); + r->prefix = (f4 << 24) | (f3 << 16) | (f2 << 8) | f1; + r->mask = 0; + + for (n = 0; n < m ; n++) + r->mask |= 1 << n; + + 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->prefix = (f4 << 24) | (f3 << 16) | (f2 << 8) | f1; + r->end = (m << 24) | (f3 << 16) | (f2 << 8) | f1; + r->mask = 0; + + 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) { + fprintf(stderr, "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) { + r = parse1(opt->name); + if (!r) + r = parse2(opt->name); + if (!r) { + fprintf(stderr, "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; + + list_for_each_entry(r, list, entry) { + if (r->mask) { + if ((r->prefix & r->mask) == (ipaddr & r->mask)) + return 0; + } else { + if (ipaddr >= r->prefix && ipaddr <= r->end) + return 0; + } + } + + return -1; +} + +int __export iprange_client_check(in_addr_t ipaddr) +{ + return check_range(&client_ranges, ipaddr); +} +/*int __export iprange_tunnel_check(in_addr_t ipaddr) +{ + return check_range(&tunnel_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 new file mode 100644 index 00000000..88a2486a --- /dev/null +++ b/accel-pptpd/iprange.h @@ -0,0 +1,10 @@ +#ifndef __IPRANGE_H +#define __IPRANGE_H + +#include <netinet/in.h> + +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 new file mode 100644 index 00000000..476c077f --- /dev/null +++ b/accel-pptpd/log.c @@ -0,0 +1,452 @@ +#include <unistd.h> +#include <stdlib.h> +#include <stdio.h> +#include <stdarg.h> +#include <errno.h> +#include <string.h> +#include <stdint.h> +#include <signal.h> +#include <sys/time.h> + +#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; + uint8_t refs; +}; + +static int log_level=10; + +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(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_info(const char *fmt,...) +{ + if (log_level >= LOG_INFO) { + va_list ap; + va_start(ap, fmt); + do_log(LOG_INFO, 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_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_info(const char *fmt,...) +{ + if (log_level >= LOG_INFO) { + va_list ap; + va_start(ap, fmt); + do_log(LOG_INFO, 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); + } +} + +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 __init log_init(void) +{ + char *opt; + struct sigaction sa = { + .sa_handler = sighup, + }; + + opt = conf_get_opt("log", "level"); + if (opt && atoi(opt) >= 0) + log_level = atoi(opt); + + opt = conf_get_opt("log", "log-emerg"); + if (opt) { + emerg_file = fopen(opt, "a"); + if (!emerg_file) + fprintf(stderr, "log:open: %s\n", strerror(errno)); + } + + opt = conf_get_opt("log", "log-debug"); + if (opt) { + debug_file = fopen(opt, "a"); + if (!emerg_file) + fprintf(stderr, "log:open: %s\n", strerror(errno)); + } + + 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); + + sigaction(SIGHUP, &sa, NULL); +} + diff --git a/accel-pptpd/log.h b/accel-pptpd/log.h new file mode 100644 index 00000000..140dad1d --- /dev/null +++ b/accel-pptpd/log.h @@ -0,0 +1,66 @@ +#ifndef __LOG_H +#define __LOG_H + +#include <stdarg.h> +#include <sys/time.h> +#include "list.h" + +#define LOG_MSG 0 +#define LOG_ERROR 1 +#define LOG_WARN 2 +#define LOG_INFO 3 +#define LOG_DEBUG 4 + +#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_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_info(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_info(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 new file mode 100644 index 00000000..f1b09ca8 --- /dev/null +++ b/accel-pptpd/logs/CMakeLists.txt @@ -0,0 +1,13 @@ +ADD_LIBRARY(log_file SHARED log_file.c) +INSTALL(TARGETS log_file + LIBRARY DESTINATION usr/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 usr/lib/accel-pptp + ) +ENDIF(LOG_PGSQL) + diff --git a/accel-pptpd/logs/log_file.c b/accel-pptpd/logs/log_file.c new file mode 100644 index 00000000..be615ad8 --- /dev/null +++ b/accel-pptpd/logs/log_file.c @@ -0,0 +1,613 @@ +#include <stdlib.h> +#include <stdio.h> +#include <errno.h> +#include <string.h> +#include <fcntl.h> +#include <unistd.h> +#include <limits.h> +#include <aio.h> +#include <sys/signalfd.h> + +#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", "debug"}; +static const char* level_color[]={NORMAL_COLOR, RED_COLOR, YELLOW_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; + } + + 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_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_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_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 = __sync_fetch_and_add(&temp_seq, 1); + 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 = opt; + + opt = conf_get_opt("log", "per-session-dir"); + if (opt) + conf_per_session_dir = 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 new file mode 100644 index 00000000..0eed2431 --- /dev/null +++ b/accel-pptpd/logs/log_pgsql.c @@ -0,0 +1,320 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include <postgresql/libpq-fe.h> + +#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, +}; +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_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 = 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 = 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/main.c b/accel-pptpd/main.c new file mode 100644 index 00000000..e261fbb4 --- /dev/null +++ b/accel-pptpd/main.c @@ -0,0 +1,155 @@ +#include <signal.h> +#include <string.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdio.h> +#include <sys/stat.h> +#include <sys/mman.h> + +#include "triton/triton.h" + +#include "memdebug.h" +#include "log.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 <file>] -c <file>\n\ + where:\n\ + -d - daemon mode\n\ + -p - write pid to <file>\n\ + -c - config file\n"); + _exit(EXIT_FAILURE); +} +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); + + if (triton_load_modules("modules")) + return EXIT_FAILURE; + + triton_run(); + + sigfillset(&set); + 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, 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_info("terminate, sig = %i\n", sig); + + triton_terminate(); + + return EXIT_SUCCESS; +} + diff --git a/accel-pptpd/memdebug.c b/accel-pptpd/memdebug.c new file mode 100644 index 00000000..2acdc7a8 --- /dev/null +++ b/accel-pptpd/memdebug.c @@ -0,0 +1,180 @@ +#undef MEMDEBUG + +#include <stdlib.h> +#include <stdint.h> +#include <string.h> +#include <stdio.h> +#include <limits.h> +#include <signal.h> + +#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; + +struct mem_t *_md_malloc(size_t size, const char *fname, int line) +{ + struct mem_t *mem = malloc(sizeof(*mem) + size + 8); + 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", 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", 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, mem->size); + total += mem->size; + } + spin_unlock(&mem_list_lock); + printf("total = %lu\n", 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, 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 new file mode 100644 index 00000000..dc6b9ad1 --- /dev/null +++ b/accel-pptpd/memdebug.h @@ -0,0 +1,28 @@ +#ifndef __MEMDEBUG_H +#define __MEMDEBUG_H + +#ifdef MEMDEBUG + +#include <sys/types.h> + +#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 new file mode 100644 index 00000000..f4c0f04a --- /dev/null +++ b/accel-pptpd/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-pptpd/ppp/ccp_mppe.c b/accel-pptpd/ppp/ccp_mppe.c new file mode 100644 index 00000000..3ac3ad6a --- /dev/null +++ b/accel-pptpd/ppp/ccp_mppe.c @@ -0,0 +1,215 @@ +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <sys/ioctl.h> +#include <linux/if_ppp.h> +#include <net/if.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 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, + .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->policy == 2 || 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 (setup_mppe_key(ccp->ppp->unit_fd, 1, mppe_opt->send_key)) + return CCP_OPT_REJ; + + decrease_mtu(ccp->ppp); + + return CCP_OPT_ACK; +} + +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("<mppe %sH %sM %sS %sL %sD %sC>", + 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 new file mode 100644 index 00000000..4c48fd4c --- /dev/null +++ b/accel-pptpd/ppp/ipcp_opt_dns.c @@ -0,0 +1,163 @@ +#include <stdlib.h> +#include <string.h> +#include <arpa/inet.h> + +#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) +{ + struct dns_option_t *dns_opt=container_of(opt,typeof(*dns_opt),opt); + struct ipcp_opt32_t *opt32=(struct ipcp_opt32_t*)ptr; + + if (!dns_opt->addr) + return 0; + opt32->hdr.id=dns_opt->opt.id; + opt32->hdr.len=6; + opt32->val=dns_opt->addr; + return 6; +} + +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("<dns1 %s>",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("<dns2 %s>",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 new file mode 100644 index 00000000..efbc41ec --- /dev/null +++ b/accel-pptpd/ppp/ipcp_opt_ipaddr.c @@ -0,0 +1,177 @@ +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> +#include <arpa/inet.h> +#include <net/if.h> +#include <sys/ioctl.h> +#include <linux/if_ppp.h> + +#include "ppp.h" +#include "ppp_ipcp.h" +#include "log.h" +#include "ipdb.h" +#include "iprange.h" + +#include "memdebug.h" + +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; +}; + +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 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_client_check(ipaddr_opt->ip->peer_addr)) { + log_ppp_warn("ppp:ipcp: to avoid hard loops 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; + } + + 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: + ipcp->ppp->ipaddr = ipaddr_opt->ip->addr; + ipcp->ppp->peer_ipaddr = ipaddr_opt->ip->peer_addr; + + 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("<addr %s>",inet_ntoa(in)); +} + +static void __init ipaddr_opt_init() +{ + ipcp_option_register(&ipaddr_opt_hnd); +} + diff --git a/accel-pptpd/ppp/lcp_opt_accomp.c b/accel-pptpd/ppp/lcp_opt_accomp.c new file mode 100644 index 00000000..241b0e06 --- /dev/null +++ b/accel-pptpd/ppp/lcp_opt_accomp.c @@ -0,0 +1,106 @@ +#include <stdlib.h> +#include <string.h> +#include <arpa/inet.h> + +#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("<accomp>"); +} + +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 new file mode 100644 index 00000000..4a61ef91 --- /dev/null +++ b/accel-pptpd/ppp/lcp_opt_magic.c @@ -0,0 +1,91 @@ +#include <stdlib.h> +#include <string.h> +#include <arpa/inet.h> + +#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 %04x>",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 new file mode 100644 index 00000000..eab57b02 --- /dev/null +++ b/accel-pptpd/ppp/lcp_opt_mru.c @@ -0,0 +1,159 @@ +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <stdio.h> +#include <arpa/inet.h> +#include <net/if.h> +#include <linux/if_ppp.h> +#include <sys/ioctl.h> + +#include "ppp.h" +#include "ppp_lcp.h" +#include "log.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 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; +}; + +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, + .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; + 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 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("<mru %i>",ntohs(opt16->val)); + else + print("<mru %i>",mru_opt->mru); +} + +static void __init mru_opt_init() +{ + 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); + + lcp_option_register(&mru_opt_hnd); +} + diff --git a/accel-pptpd/ppp/lcp_opt_pcomp.c b/accel-pptpd/ppp/lcp_opt_pcomp.c new file mode 100644 index 00000000..1f8532bb --- /dev/null +++ b/accel-pptpd/ppp/lcp_opt_pcomp.c @@ -0,0 +1,106 @@ +#include <stdlib.h> +#include <string.h> +#include <arpa/inet.h> + +#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("<pcomp>"); +} + +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 new file mode 100644 index 00000000..3e51ecbb --- /dev/null +++ b/accel-pptpd/ppp/ppp.c @@ -0,0 +1,537 @@ + +#include <stdio.h> +#include <fcntl.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdint.h> +#include <string.h> +#include <errno.h> +#include <sys/ioctl.h> +#include <arpa/inet.h> +#include <linux/ppp_defs.h> +#include <linux/if_ppp.h> +#include <openssl/md5.h> + +#include "triton.h" + +#include "events.h" +#include "ppp.h" +#include "ppp_fsm.h" +#include "log.h" + +#include "memdebug.h" + +int __export conf_ppp_verbose; + +static LIST_HEAD(layers); +int __export sock_fd; + +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) +{ + _free(ppp->chan_buf); + _free(ppp->unit_buf); + + if (ppp->username) + _free(ppp->username); +} + +static void generate_sessionid(struct ppp_t *ppp) +{ + MD5_CTX ctx; + uint8_t md5[MD5_DIGEST_LENGTH]; + int i; + + MD5_Init(&ctx); + MD5_Update(&ctx,&ppp->unit_idx, 4); + MD5_Update(&ctx,&ppp->unit_fd, 4); + MD5_Update(&ctx,&ppp->chan_fd, 4); + MD5_Update(&ctx,&ppp->fd, 4); + MD5_Update(&ctx,&ppp->start_time, sizeof(time_t)); + MD5_Update(&ctx,ppp->ctrl->ctx, sizeof(void *)); + MD5_Final(md5,&ctx); + + for( i = 0; i < 16; i++) + sprintf(ppp->sessionid + i*2, "%02X", md5[i]); +} + +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("Couldn't get channel number\n"); + return -1; + } + + ppp->chan_fd = open("/dev/ppp", O_RDWR); + if (ppp->chan_fd < 0) { + log_ppp_error("Couldn't reopen /dev/ppp\n"); + return -1; + } + + if (ioctl(ppp->chan_fd, PPPIOCATTCHAN, &ppp->chan_idx) < 0) { + log_ppp_error("Couldn't attach to channel %d\n", ppp->chan_idx); + goto exit_close_chan; + } + + ppp->unit_fd = open("/dev/ppp", O_RDWR); + if (ppp->unit_fd < 0) { + log_ppp_error("Couldn't reopen /dev/ppp\n"); + goto exit_close_chan; + } + + ppp->unit_idx = -1; + if (ioctl(ppp->unit_fd, PPPIOCNEWUNIT, &ppp->unit_idx) < 0) { + log_ppp_error("Couldn't create new ppp unit\n"); + goto exit_close_unit; + } + + if (ioctl(ppp->chan_fd, PPPIOCCONNECT, &ppp->unit_idx) < 0) { + log_ppp_error("Couldn't attach to PPP unit %d\n", ppp->unit_idx); + 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); + + if (conf_ppp_verbose) + log_ppp_info("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); + + 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) +{ + 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; + + _free(ppp->unit_buf); + _free(ppp->chan_buf); + + _free_layers(ppp); + + 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; + } +} + +/*void print_buf(uint8_t *buf, int size) +{ + int i; + for(i=0;i<size;i++) + printf("%x ",buf[i]); + printf("\n"); +}*/ + +int __export ppp_chan_send(struct ppp_t *ppp, void *data, int size) +{ + int n; + + //printf("ppp_chan_send: "); + //print_buf((uint8_t*)data,size); + + n = write(ppp->chan_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 < 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_chan_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 < 2) { + log_ppp_error("ppp_chan_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 __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->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, 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->finished) + return; + } + } + + destablish_ppp(ppp); +} + +void __export ppp_terminate(struct ppp_t *ppp, int hard) +{ + struct layer_node_t *n; + struct ppp_layer_data_t *d; + int s = 0; + + if (ppp->terminating) { + if (hard) + destablish_ppp(ppp); + return; + } + + ppp->terminating = 1; + + 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 3; + 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, 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; +} + +static void __init init(void) +{ + char *opt; + + sock_fd = socket(AF_INET, SOCK_DGRAM, 0); + if (sock_fd < 0) { + perror("socket"); + _exit(EXIT_FAILURE); + } + + opt = conf_get_opt("ppp", "verbose"); + if (opt && atoi(opt) > 0) + conf_ppp_verbose = 1; +} + diff --git a/accel-pptpd/ppp/ppp.h b/accel-pptpd/ppp/ppp.h new file mode 100644 index 00000000..fb6b20f6 --- /dev/null +++ b/accel-pptpd/ppp/ppp.h @@ -0,0 +1,158 @@ +#ifndef PPP_H +#define PPP_H + +#include <sys/types.h> +#include <time.h> +#include <netinet/in.h> + +#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_LAYER_LCP 1 +#define PPP_LAYER_AUTH 2 +#define PPP_LAYER_CCP 3 +#define PPP_LAYER_IPCP 4 + +#define PPP_SESSIONID_LEN 32 +#define PPP_IFNAME_LEN 10 + +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 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; + + char *chan_name; + char ifname[PPP_IFNAME_LEN]; + char sessionid[PPP_SESSIONID_LEN+1]; + time_t start_time; + char *username; + in_addr_t ipaddr; + in_addr_t peer_ipaddr; + + struct ppp_ctrl_t *ctrl; + + int log:1; + int terminating:1; + + 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*); +}; + +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); + +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); + +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 conf_ppp_verbose; + +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 new file mode 100644 index 00000000..65ca223f --- /dev/null +++ b/accel-pptpd/ppp/ppp_auth.c @@ -0,0 +1,326 @@ +#include <stdlib.h> +#include <string.h> +#include <arpa/inet.h> + +#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; +}; + +struct auth_layer_data_t +{ + struct ppp_layer_data_t ld; + struct auth_option_t auth_opt; + struct ppp_t *ppp; + int started:1; +}; + +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; + + 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("<auth %02x>", ntohs(opt16->val)); + return; + } else if (auth_opt->auth) + d = auth_opt->auth; + else + return; + +print_d: + print("<auth %s>", 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"); + + ad->started = 1; + + if (ad->auth_opt.auth) + 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->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"); + + if (ad->started && ad->auth_opt.auth) + ad->auth_opt.auth->h->finish(ad->ppp, ad->auth_opt.auth); + + _free(ad); +} + +void __export 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); + triton_event_fire(EV_PPP_AUTHORIZED, ppp); +} + +void __export auth_failed(struct ppp_t *ppp) +{ + ppp_terminate(ppp, 0); +} + +int __export ppp_auth_register_handler(struct ppp_auth_handler_t *h) +{ + list_add_tail(&h->entry, &auth_handlers); + 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 new file mode 100644 index 00000000..fbd2017c --- /dev/null +++ b/accel-pptpd/ppp/ppp_auth.h @@ -0,0 +1,35 @@ +#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 ppp_auth_register_handler(struct ppp_auth_handler_t*); + +void auth_successed(struct ppp_t *ppp, char *username); +void auth_failed(struct ppp_t *ppp); + +#endif + diff --git a/accel-pptpd/ppp/ppp_ccp.c b/accel-pptpd/ppp/ppp_ccp.c new file mode 100644 index 00000000..ae9e6375 --- /dev/null +++ b/accel-pptpd/ppp/ppp_ccp.c @@ -0,0 +1,724 @@ +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <linux/ppp_defs.h> +#include <linux/if_ppp.h> +#include <sys/ioctl.h> + +#include "triton.h" + +#include "log.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 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_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; + + ppp_register_unit_handler(ppp, &ccp->hnd); + + INIT_LIST_HEAD(&ccp->options); + ccp_options_init(ccp); + + ccp->passive = 1; + + 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)) { + 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; + 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, 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_info("<"); + for (i = 0; i < ropt->len; i++) { + log_ppp_info(" %x", ptr[i]); + } + log_ppp_info(" >"); +} + +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) + 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_info("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_info(" "); + lopt->h->print(log_ppp_info, lopt, NULL); + } + } + ptr += n; + } + + if (conf_ppp_verbose) + log_ppp_info("]\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_info("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_info("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_info(" "); + ropt->lopt->h->print(log_ppp_info, ropt->lopt, NULL); + } + ptr += ropt->lopt->h->send_conf_nak(ccp, ropt->lopt, ptr); + } + } + + if (conf_ppp_verbose) + log_ppp_info("]\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_info("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_info(" "); + if (ropt->lopt) + ropt->lopt->h->print(log_ppp_info, 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_info("]\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_info("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_info(" "); + lopt->h->print(log_ppp_info, 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_info(" "); + print_ropt(ropt); + } + ropt->state = CCP_OPT_REJ; + ret = CCP_OPT_REJ; + } + } + + if (conf_ppp_verbose) + log_ppp_info("]\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 (r<ret) ret=r; + } + }*/ + + return ret; +} + +static void ccp_free_conf_req(struct ppp_ccp_t *ccp) +{ + struct recv_opt_t *ropt; + + while (!list_empty(&ccp->ropt_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_info("recv [CCP ConfRej id=%x", ccp->fsm.recv_id); + + if (ccp->fsm.recv_id != ccp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info(": 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_info("]\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_info("recv [CCP ConfNak id=%x", ccp->fsm.recv_id); + + if (ccp->fsm.recv_id != ccp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info(": 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_info(" "); + lopt->h->print(log_ppp_info, lopt, data); + } + if (lopt->h->recv_conf_nak(ccp, lopt, data)) + res = -1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info("]\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_info("recv [CCP ConfAck id=%x", ccp->fsm.recv_id); + + if (ccp->fsm.recv_id != ccp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info(": 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_info(" "); + lopt->h->print(log_ppp_info,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_info("]\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_info("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_info("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) { + if (conf_ppp_verbose) + log_ppp_warn("CCP: discaring packet\n"); + lcp_send_proto_rej(ccp->ppp, htons(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, 0); + break; + case CONFACK: + if (ccp_recv_conf_ack(ccp, (uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) + ppp_terminate(ccp->ppp, 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, 0); + else + ppp_fsm_recv_conf_rej(&ccp->fsm); + break; + case TERMREQ: + if (conf_ppp_verbose) + log_ppp_info("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_info("recv [CCP TermAck id=%x]\n", hdr->id); + ppp_fsm_recv_term_ack(&ccp->fsm); + break; + case CODEREJ: + if (conf_ppp_verbose) + log_ppp_info("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; + } +} + +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 __init ccp_init(void) +{ + ppp_register_layer("ccp", &ccp_layer); +} + diff --git a/accel-pptpd/ppp/ppp_ccp.h b/accel-pptpd/ppp/ppp_ccp.h new file mode 100644 index 00000000..27b303e6 --- /dev/null +++ b/accel-pptpd/ppp/ppp_ccp.h @@ -0,0 +1,96 @@ +#ifndef PPP_CCP_H +#define PPP_CCP_H + +#include <stdint.h> + +#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 started:1; + int passive: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 new file mode 100644 index 00000000..4769dc89 --- /dev/null +++ b/accel-pptpd/ppp/ppp_fsm.c @@ -0,0 +1,525 @@ +#include <arpa/inet.h> +#include <stdlib.h> + +#include "triton.h" + +#include "ppp.h" +#include "ppp_fsm.h" +#include "ppp_lcp.h" +#include "log.h" + +#include "memdebug.h" + +static int conf_max_terminate = 2; +static int conf_max_configure = 5; +static int conf_max_failure = 5; +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: + if (layer->layer_finished) layer->layer_finished(layer); + layer->fsm_state=FSM_Initial; + break; + case FSM_Stopped: + layer->fsm_state=FSM_Closed; + 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->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; + 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); + if (layer->layer_finished) layer->layer_finished(layer); + layer->fsm_state=FSM_Stopped; + 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->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_down) layer->layer_down(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_req(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: + if (layer->layer_finished) layer->layer_finished(layer); + layer->fsm_state=FSM_Stopped; + 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->send_term_req(layer); + layer->fsm_state=FSM_Stopping; + break; + case FSM_Closing: + if (layer->layer_finished) layer->layer_finished(layer); + layer->fsm_state=FSM_Closed; + break; + case FSM_Stopping: + case FSM_Req_Sent: + case FSM_Ack_Rcvd: + case FSM_Ack_Sent: + if (layer->layer_finished) layer->layer_finished(layer); + layer->fsm_state=FSM_Stopped; + 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_timer.expire_tv.tv_sec=0; + layer->restart_counter=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); +} + +void __init fsm_init(void) +{ + char *opt; + + opt = conf_get_opt("lcp", "max-terminate"); + if (opt && atoi(opt) > 0) + conf_max_terminate = atoi(opt); + + opt = conf_get_opt("lcp", "max-configure"); + if (opt && atoi(opt) > 0) + conf_max_configure = atoi(opt); + + opt = conf_get_opt("lcp", "max-failure"); + if (opt && atoi(opt) > 0) + conf_max_failure = atoi(opt); + + opt = conf_get_opt("lcp", "timeout"); + if (opt && atoi(opt) > 0) + conf_timeout = atoi(opt); +} diff --git a/accel-pptpd/ppp/ppp_fsm.h b/accel-pptpd/ppp/ppp_fsm.h new file mode 100644 index 00000000..6010240a --- /dev/null +++ b/accel-pptpd/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-pptpd/ppp/ppp_ipcp.c b/accel-pptpd/ppp/ppp_ipcp.c new file mode 100644 index 00000000..c46b1bdb --- /dev/null +++ b/accel-pptpd/ppp/ppp_ipcp.c @@ -0,0 +1,651 @@ +#include <stdlib.h> +#include <string.h> +#include <linux/ppp_defs.h> +#include <linux/if_ppp.h> +#include <arpa/inet.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; + 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"); + + ppp_layer_finished(ipcp->ppp, &ipcp->ld); + if (ipcp->started) + ipcp->started = 0; + else + ppp_terminate(ipcp->ppp, 1); +} + +static void print_ropt(struct recv_opt_t *ropt) +{ + int i; + uint8_t *ptr = (uint8_t*)ropt->hdr; + + log_ppp_info("<"); + for (i = 0; i < ropt->len; i++) { + log_ppp_info(" %x", ptr[i]); + } + log_ppp_info(" >"); +} + +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_info("send [IPCP ConfReq id=%x", ipcp_hdr->id); + list_for_each_entry(lopt,&ipcp->options,entry) { + if (lopt->print) { + log_ppp_info(" "); + lopt->h->print(log_ppp_debug, lopt, NULL); + } + } + log_ppp_info("]\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_info("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_info("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_info(" "); + ropt->lopt->h->print(log_ppp_info, ropt->lopt, NULL); + } + ptr += ropt->lopt->h->send_conf_nak(ipcp, ropt->lopt, ptr); + } + } + + if (conf_ppp_verbose) + log_ppp_info("]\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_info("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_info(" "); + if (ropt->lopt) + ropt->lopt->h->print(log_ppp_info, 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_info("]\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_info("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) { + if (conf_ppp_verbose) { + log_ppp_info(" "); + lopt->h->print(log_ppp_info, lopt, (uint8_t*)ropt->hdr); + } + r = lopt->h->recv_conf_req(ipcp, lopt, (uint8_t*)ropt->hdr); + lopt->state = r; + ropt->state = r; + ropt->lopt = lopt; + if (r < ret) + ret = r; + break; + } + } + if (!ropt->lopt) + { + if (conf_ppp_verbose) { + log_ppp_debug(" "); + print_ropt(ropt); + } + ropt->state = IPCP_OPT_REJ; + ret = IPCP_OPT_REJ; + } + } + + if (conf_ppp_verbose) + log_ppp_info("]\n"); + + /*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 (r<ret) ret=r; + } + }*/ + + return ret; +} + +static void ipcp_free_conf_req(struct ppp_ipcp_t *ipcp) +{ + struct recv_opt_t *ropt; + + while (!list_empty(&ipcp->ropt_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_info("recv [IPCP ConfRej id=%x", ipcp->fsm.recv_id); + + if (ipcp->fsm.recv_id != ipcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info(": 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_info("]\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_info("recv [IPCP ConfNak id=%x", ipcp->fsm.recv_id); + + if (ipcp->fsm.recv_id != ipcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info(": 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_info(" "); + lopt->h->print(log_ppp_info,lopt,data); + } + if (lopt->h->recv_conf_nak(ipcp, lopt, data)) + res =- 1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info("]\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_info("recv [IPCP ConfAck id=%x", ipcp->fsm.recv_id); + + if (ipcp->fsm.recv_id != ipcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info(": 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_info(" "); + lopt->h->print(log_ppp_info, 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_info("]\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_info("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_info("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) { + if (conf_ppp_verbose) + log_ppp_warn("IPCP: discaring 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); + 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, 0); + break; + case CONFACK: + if (ipcp_recv_conf_ack(ipcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) + ppp_terminate(ipcp->ppp, 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, 0); + else + ppp_fsm_recv_conf_rej(&ipcp->fsm); + break; + case TERMREQ: + if (conf_ppp_verbose) + log_ppp_info("recv [IPCP TermReq id=%x]\n", hdr->id); + ppp_fsm_recv_term_req(&ipcp->fsm); + ppp_terminate(ipcp->ppp, 0); + break; + case TERMACK: + if (conf_ppp_verbose) + log_ppp_info("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_info("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 new file mode 100644 index 00000000..c9559872 --- /dev/null +++ b/accel-pptpd/ppp/ppp_ipcp.h @@ -0,0 +1,96 @@ +#ifndef PPP_IPCP_H +#define PPP_IPCP_H + +#include <stdint.h> + +#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 new file mode 100644 index 00000000..08fd359e --- /dev/null +++ b/accel-pptpd/ppp/ppp_lcp.c @@ -0,0 +1,821 @@ +#include <stdlib.h> +#include <string.h> +#include <linux/ppp_defs.h> +#include <linux/if_ppp.h> +#include <arpa/inet.h> + +#include "triton.h" + +#include "log.h" + +#include "ppp.h" +#include "ppp_lcp.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; +} + +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"); + + stop_echo(lcp); + + ppp_fsm_close(&lcp->fsm); +} + +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); + + _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); + ppp_layer_finished(lcp->ppp, &lcp->ld); + if (lcp->started) + lcp->started = 0; + else + ppp_terminate(lcp->ppp, 1); +} + +static void print_ropt(struct recv_opt_t *ropt) +{ + int i; + uint8_t *ptr = (uint8_t*)ropt->hdr; + + log_ppp_debug("<"); + for (i = 0; i < ropt->len; i++) { + log_ppp_info(" %x", ptr[i]); + } + log_ppp_debug(" >"); +} + +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_info("send [LCP ConfReq id=%x", lcp_hdr->id); + list_for_each_entry(lopt,&lcp->options,entry) { + if (lopt->print) { + log_ppp_debug(" "); + lopt->h->print(log_ppp_debug, lopt, NULL); + } + } + log_ppp_debug("]\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_info("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_info("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_debug("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_debug(" "); + lopt->h->print(log_ppp_info, lopt, NULL); + } + } + } + + if (conf_ppp_verbose) + log_ppp_info("]\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_info("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_info(" "); + if (ropt->lopt) + ropt->lopt->h->print(log_ppp_info, ropt->lopt, (uint8_t*)ropt->hdr); + else + print_ropt(ropt); + } + } + } + + if (conf_ppp_verbose) + log_ppp_info("]\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_info("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_info(" "); + lopt->h->print(log_ppp_info, 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 (r<ret) + ret = r; + break; + } + } + if (!ropt->lopt) { + if (conf_ppp_verbose) { + log_ppp_info(" "); + print_ropt(ropt); + } + ropt->state=LCP_OPT_REJ; + ret=LCP_OPT_REJ; + } + } + + if (conf_ppp_verbose) + log_ppp_info("]\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 (r<ret) ret=r; + } + }*/ + + return ret; +} + +static void lcp_free_conf_req(struct ppp_lcp_t *lcp) +{ + struct recv_opt_t *ropt; + + while (!list_empty(&lcp->ropt_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_info("recv [LCP ConfRej id=%x", lcp->fsm.recv_id); + + if (lcp->fsm.recv_id != lcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info(": 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_info(" "); + lopt->h->print(log_ppp_info, 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_info("]\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_info("recv [LCP ConfNak id=%x", lcp->fsm.recv_id); + + if (lcp->fsm.recv_id != lcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info(": 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_info(" "); + lopt->h->print(log_ppp_info, lopt, data); + } + if (lopt->h->recv_conf_nak(lcp, lopt, data)) + res = -1; + break; + } + } + + data += hdr->len; + size -= hdr->len; + } + + if (conf_ppp_verbose) + log_ppp_info("]\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_info("recv [LCP ConfAck id=%x", lcp->fsm.recv_id); + + if (lcp->fsm.recv_id != lcp->fsm.id) { + if (conf_ppp_verbose) + log_ppp_info(": 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_info(" "); + lopt->h->print(log_ppp_info, 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_info("]\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, 0); + } + + if (conf_ppp_verbose) + log_ppp_info("recv [LCP EchoRep id=%x <magic %x>]\n", lcp->fsm.recv_id, magic); + + if (magic == lcp->magic) { + log_ppp_error("lcp: echo: loop-back detected\n"); + ppp_terminate(lcp->ppp, 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_info("send [LCP EchoRep id=%x <magic %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, 0); + } else { + if (conf_ppp_verbose) + log_ppp_info("send [LCP EchoReq id=%x <magic %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) + 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_info("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_info("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 = proto, + }; + + if (conf_ppp_verbose) + log_ppp_info("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->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, 0); + break; + case CONFACK: + if (lcp_recv_conf_ack(lcp,(uint8_t*)(hdr + 1), ntohs(hdr->len) - PPP_HDRLEN)) + ppp_terminate(lcp->ppp, 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, 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_info("recv [LCP TermReq id=%x]\n", hdr->id); + ppp_fsm_recv_term_req(&lcp->fsm); + ppp_terminate(lcp->ppp, 0); + break; + case TERMACK: + if (conf_ppp_verbose) + log_ppp_info("recv [LCP TermAck id=%x]\n", hdr->id); + ppp_fsm_recv_term_ack(&lcp->fsm); + break; + case CODEREJ: + if (conf_ppp_verbose) + log_ppp_info("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_info("recv [LCP EchoReq id=%x <magic %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_info("recv [LCP ProtoRej id=%x <%x>]\n", hdr->code, hdr->id, *(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_info("recv [LCP Ident id=%x <%s>]\n", hdr->id, term_msg); + _free(term_msg); + } + break; + default: + if (conf_ppp_verbose) + log_ppp_info("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 __init lcp_init(void) +{ + char *opt; + + ppp_register_layer("lcp", &lcp_layer); + + 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); +} + diff --git a/accel-pptpd/ppp/ppp_lcp.h b/accel-pptpd/ppp/ppp_lcp.h new file mode 100644 index 00000000..6d67b698 --- /dev/null +++ b/accel-pptpd/ppp/ppp_lcp.h @@ -0,0 +1,136 @@ +#ifndef PPP_LCP_H +#define PPP_LCP_H + +#include <stdint.h> + +#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 new file mode 100644 index 00000000..ad9fd1fc --- /dev/null +++ b/accel-pptpd/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-pptpd/ppp/ppp_pd.c b/accel-pptpd/ppp/ppp_pd.c new file mode 100644 index 00000000..f7702083 --- /dev/null +++ b/accel-pptpd/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-pptpd/pwdb.c b/accel-pptpd/pwdb.c new file mode 100644 index 00000000..4c0ab02e --- /dev/null +++ b/accel-pptpd/pwdb.c @@ -0,0 +1,56 @@ +#include <stdlib.h> + +#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 new file mode 100644 index 00000000..a1c2cedb --- /dev/null +++ b/accel-pptpd/pwdb.h @@ -0,0 +1,27 @@ +#ifndef PWDB_H +#define PWDB_H + +#include <stdarg.h> +#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 new file mode 100644 index 00000000..b82512e9 --- /dev/null +++ b/accel-pptpd/radius/CMakeLists.txt @@ -0,0 +1,20 @@ +SET(sources + radius.c + dict.c + req.c + packet.c + auth.c + acct.c + dm_coa.c +) + +ADD_DEFINITIONS(-DDICT_PATH="${CMAKE_INSTALL_PREFIX}/usr/share/accel-pptp/dictionary") + +ADD_LIBRARY(radius SHARED ${sources}) + +INSTALL(TARGETS radius + LIBRARY DESTINATION usr/lib/accel-pptp +) +FILE(GLOB dict "${CMAKE_CURRENT_SOURCE_DIR}/dict/*") +INSTALL(FILES ${dict} DESTINATION usr/share/accel-pptp) + diff --git a/accel-pptpd/radius/acct.c b/accel-pptpd/radius/acct.c new file mode 100644 index 00000000..a8346edd --- /dev/null +++ b/accel-pptpd/radius/acct.c @@ -0,0 +1,208 @@ +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> +#include <unistd.h> +#include <sys/ioctl.h> +#include <linux/if_ppp.h> +#include <openssl/md5.h> + +#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; + + 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, "Acct-Input-Octets", ifreq.stats.p.ppp_ibytes); + rad_packet_change_int(req->pack, "Acct-Output-Octets", ifreq.stats.p.ppp_obytes); + rad_packet_change_int(req->pack, "Acct-Input-Packets", ifreq.stats.p.ppp_ipackets); + rad_packet_change_int(req->pack, "Acct-Output-Packets", ifreq.stats.p.ppp_opackets); + rad_packet_change_int(req->pack, "Acct-Input-Gigawords", req->rpd->acct_input_gigawords); + rad_packet_change_int(req->pack, "Acct-Output-Gigawords", req->rpd->acct_output_gigawords); + rad_packet_change_int(req->pack, "Acct-Session-Time", time(NULL) - 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); + + if (req->reply) + rad_packet_free(req->reply); + + req->reply = rad_packet_recv(h->fd, NULL); + if (!req->reply) + return 0; + + if (conf_verbose) { + log_ppp_info("recv "); + rad_packet_print(req->reply, log_ppp_info); + } + + if (req->reply->code != CODE_ACCOUNTING_RESPONSE || req->reply->id != req->pack->id) { + rad_packet_free(req->reply); + req->reply = NULL; + } else { + req->pack->id++; + 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); + + rad_req_send(req); +} + +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; + + rad_packet_change_val(rpd->acct_req->pack, "Acct-Status-Type", "Interim-Update"); + req_set_RA(rpd->acct_req, conf_acct_secret); + rad_req_send(rpd->acct_req); + 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) +{ + 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 (req_set_RA(rpd->acct_req, conf_acct_secret)) + goto out_err; + + if (rad_req_send(rpd->acct_req)) + 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; + if (triton_timer_add(rpd->ppp->ctrl->ctx, &rpd->acct_req->timeout, 0)) { + triton_md_unregister_handler(&rpd->acct_req->hnd); + goto out_err; + } + + 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; + + 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); + + rad_packet_change_val(rpd->acct_req->pack, "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; + } + + for(i = 0; i < conf_max_try; i++) { + if (rad_req_send(rpd->acct_req)) + break; + rad_req_wait(rpd->acct_req, conf_timeout); + if (!rpd->acct_req->reply) + 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; + } 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 new file mode 100644 index 00000000..e9b617e4 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/auth.c b/accel-pptpd/radius/auth.c new file mode 100644 index 00000000..3be58253 --- /dev/null +++ b/accel-pptpd/radius/auth.c @@ -0,0 +1,397 @@ +#include <stdlib.h> +#include <string.h> +#include <openssl/md5.h> +#include <openssl/sha.h> + +#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; + + chunk_cnt = (strlen(passwd) - 1) / 16 + 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++) { + if (rad_req_send(req)) + goto out; + + rad_req_wait(req, conf_timeout); + + if (req->reply) { + if (req->reply->id != req->pack->id) { + rad_packet_free(req->reply); + req->reply = NULL; + } else + break; + } + } + + if (!req->reply) + log_ppp_warn("radius:auth: no response\n"); + else if (req->reply->code == CODE_ACCESS_ACCEPT) { + rad_proc_attrs(req); + 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, "User-Password", epasswd, epasswd_len)) { + _free(epasswd); + goto out; + } + + _free(epasswd); + + 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) +{ + struct rad_req_t *req; + 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); + + req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); + if (!req) + return PWDB_DENIED; + + if (challenge_len == 16) + memcpy(req->RA, challenge, 16); + else { + if (rad_packet_add_octets(req->pack, "CHAP-Challenge", challenge, challenge_len)) + goto out; + } + + if (rad_packet_add_octets(req->pack, "CHAP-Password", chap_password, 17)) + goto out; + + 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; +} + +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; + struct rad_req_t *req; + 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); + + req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); + if (!req) + return PWDB_DENIED; + + response[0] = id; + response[1] = flags; + memcpy(response + 2, lm_response, 24); + memcpy(response + 2 + 24, nt_response, 24); + + if (rad_packet_add_vendor_octets(req->pack, "Microsoft", "MS-CHAP-Challenge", challenge, challenge_len)) + goto out; + + if (rad_packet_add_vendor_octets(req->pack, "Microsoft", "MS-CHAP-Response", response, sizeof(response))) + goto out; + + 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); + setup_mppe(req, challenge); + } + +out: + rad_req_free(req); + + return r; +} + +int rad_auth_mschap_v2(struct radius_pd_t *rpd, const char *username, va_list args) +{ + int r; + struct rad_req_t *req; + 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 *); + + req = rad_req_alloc(rpd, CODE_ACCESS_REQUEST, username); + if (!req) + return PWDB_DENIED; + + 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 (rad_packet_add_vendor_octets(req->pack, "Microsoft", "MS-CHAP-Challenge", challenge, 16)) + goto out; + + if (rad_packet_add_vendor_octets(req->pack, "Microsoft", "MS-CHAP2-Response", mschap_response, sizeof(mschap_response))) + goto out; + + r = rad_auth_send(req); + if (r == PWDB_SUCCESS) { + ra = rad_packet_find_vendor_attr(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 = req->pack, + .reply = req->reply, + }; + triton_event_fire(EV_RADIUS_ACCESS_ACCEPT, &ev); + setup_mppe(req, NULL); + } + +out: + rad_req_free(req); + + return r; +} + + diff --git a/accel-pptpd/radius/dict.c b/accel-pptpd/radius/dict.c new file mode 100644 index 00000000..54cf895e --- /dev/null +++ b/accel-pptpd/radius/dict.c @@ -0,0 +1,356 @@ +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> +#include <limits.h> + +#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_error("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_error("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_error("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_error("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_error("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 new file mode 100644 index 00000000..64db18fe --- /dev/null +++ b/accel-pptpd/radius/dict/dictionary @@ -0,0 +1,78 @@ +# -*- 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.rfc5176 + + +$INCLUDE dictionary.microsoft + +ATTRIBUTE Traffic-Shape-in 231 integer diff --git a/accel-pptpd/radius/dict/dictionary.microsoft b/accel-pptpd/radius/dict/dictionary.microsoft new file mode 100644 index 00000000..9ca6b8e9 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc2865 b/accel-pptpd/radius/dict/dictionary.rfc2865 new file mode 100644 index 00000000..7e5bf583 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc2866 b/accel-pptpd/radius/dict/dictionary.rfc2866 new file mode 100644 index 00000000..15472bd5 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc2867 b/accel-pptpd/radius/dict/dictionary.rfc2867 new file mode 100644 index 00000000..b018aba4 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc2868 b/accel-pptpd/radius/dict/dictionary.rfc2868 new file mode 100644 index 00000000..f6a4047a --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc2869 b/accel-pptpd/radius/dict/dictionary.rfc2869 new file mode 100644 index 00000000..1a2631ec --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc3576 b/accel-pptpd/radius/dict/dictionary.rfc3576 new file mode 100644 index 00000000..35aeb326 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc3580 b/accel-pptpd/radius/dict/dictionary.rfc3580 new file mode 100644 index 00000000..1bd4ca3e --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc4072 b/accel-pptpd/radius/dict/dictionary.rfc4072 new file mode 100644 index 00000000..2280d075 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc4372 b/accel-pptpd/radius/dict/dictionary.rfc4372 new file mode 100644 index 00000000..b8af44ac --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc4675 b/accel-pptpd/radius/dict/dictionary.rfc4675 new file mode 100644 index 00000000..8d1187f4 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc4679 b/accel-pptpd/radius/dict/dictionary.rfc4679 new file mode 100644 index 00000000..39892a54 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc4818 b/accel-pptpd/radius/dict/dictionary.rfc4818 new file mode 100644 index 00000000..4ea59452 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc4849 b/accel-pptpd/radius/dict/dictionary.rfc4849 new file mode 100644 index 00000000..1738eea0 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict/dictionary.rfc5176 b/accel-pptpd/radius/dict/dictionary.rfc5176 new file mode 100644 index 00000000..93089612 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dict2c.py b/accel-pptpd/radius/dict2c.py new file mode 100644 index 00000000..ff0961e7 --- /dev/null +++ b/accel-pptpd/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-pptpd/radius/dm_coa.c b/accel-pptpd/radius/dm_coa.c new file mode 100644 index 00000000..64fe97ac --- /dev/null +++ b/accel-pptpd/radius/dm_coa.c @@ -0,0 +1,278 @@ +#include <unistd.h> +#include <stdlib.h> +#include <stdio.h> +#include <stdarg.h> +#include <errno.h> +#include <string.h> +#include <fcntl.h> +#include <time.h> +#include <arpa/inet.h> +#include <netinet/in.h> +#include <sys/socket.h> +#include <openssl/md5.h> + +#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_info("send "); + rad_packet_print(reply, log_ppp_info); + } + + 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, "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_info("send "); + rad_packet_print(reply, log_ppp_info); + } + + 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_info("recv "); + rad_packet_print(rpd->dm_coa_req, log_ppp_info); + } + + dm_coa_send_ack(serv.hnd.fd, rpd->dm_coa_req, &rpd->dm_coa_addr); + + rad_packet_free(rpd->dm_coa_req); + rpd->dm_coa_req = NULL; + + ppp_terminate(rpd->ppp, 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_info("recv "); + rad_packet_print(rpd->dm_coa_req, log_ppp_info); + } + + 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); +} + +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; + + + pack = rad_packet_recv(h->fd, &addr); + if (!pack) + return 0; + + 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, (void (*)(void *))disconnect_request, rpd); + else + triton_context_call(rpd->ppp->ctrl->ctx, (void (*)(void *))coa_request, rpd); + + pthread_mutex_unlock(&rpd->lock); + + return 0; + +out_err: + dm_coa_send_nak(h->fd, pack, &addr, err_code); + +out_err_no_reply: + rad_packet_free(pack); + return 0; +} + +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; + + 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 (PD_COA_PORT); + if (conf_nas_ip_address) + addr.sin_addr.s_addr = inet_addr(conf_nas_ip_address); + 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 new file mode 100644 index 00000000..e3d4cfc0 --- /dev/null +++ b/accel-pptpd/radius/packet.c @@ -0,0 +1,607 @@ +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> +#include <stdio.h> +#include <unistd.h> +#include <fcntl.h> + +#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;i<size;i++) + printf("%x ",buf[i]); + printf("\n"); +} + +int rad_packet_build(struct rad_packet_t *pack, uint8_t *RA) +{ + struct rad_attr_t *attr; + uint8_t *ptr; + + if (pack->buf) + 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; +} + +struct rad_packet_t *rad_packet_recv(int fd, 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); + + pack = rad_packet_alloc(0); + if (!pack) + return NULL; + + 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 == EINTR) + continue; + 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)\n", id); + ptr += len; + n -= 2 + len; + } + + return pack; + +out_err: + rad_packet_free(pack); + return NULL; +} + +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("%i", 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 rad_packet_add_int(struct rad_packet_t *pack, const char *name, int val) +{ + struct rad_attr_t *ra; + struct rad_dict_attr_t *attr; + + if (pack->len + 2 + 4 >= REQ_LENGTH_MAX) + return -1; + + 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->attr = attr; + ra->len = 4; + ra->val.integer = val; + list_add_tail(&ra->entry, &pack->attrs); + pack->len += 2 + 4; + + return 0; +} + +int rad_packet_change_int(struct rad_packet_t *pack, const char *name, int val) +{ + struct rad_attr_t *ra; + + ra = rad_packet_find_attr(pack, name); + if (!ra) + return -1; + + ra->val.integer = val; + + return 0; +} + +int rad_packet_add_octets(struct rad_packet_t *pack, const char *name, uint8_t *val, int len) +{ + struct rad_attr_t *ra; + struct rad_dict_attr_t *attr; + + if (pack->len + 2 + len >= REQ_LENGTH_MAX) + return -1; + + 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->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 += 2 + len; + + return 0; +} +int rad_packet_add_str(struct rad_packet_t *pack, const char *name, const char *val, int len) +{ + struct rad_attr_t *ra; + struct rad_dict_attr_t *attr; + + if (pack->len + 2 + len >= REQ_LENGTH_MAX) + return -1; + + 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->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 += 2 + len; + + return 0; +} + +int rad_packet_change_str(struct rad_packet_t *pack, const char *name, const char *val, int len) +{ + struct rad_attr_t *ra; + + ra = rad_packet_find_attr(pack, 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 rad_packet_add_val(struct rad_packet_t *pack, const char *name, const char *val) +{ + struct rad_attr_t *ra; + struct rad_dict_attr_t *attr; + struct rad_dict_value_t *v; + + if (pack->len + 2 + 4 >= REQ_LENGTH_MAX) + return -1; + + 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->attr = attr; + ra->len = 4; + ra->val = v->val; + list_add_tail(&ra->entry, &pack->attrs); + pack->len += 2 + 4; + + return 0; +} + +int rad_packet_change_val(struct rad_packet_t *pack, const char *name, const char *val) +{ + struct rad_attr_t *ra; + struct rad_dict_value_t *v; + + ra = rad_packet_find_attr(pack, 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 rad_packet_add_ipaddr(struct rad_packet_t *pack, const char *name, in_addr_t ipaddr) +{ + return rad_packet_add_int(pack, name, ipaddr); +} + + +struct rad_attr_t *rad_packet_find_attr(struct rad_packet_t *pack, const char *name) +{ + struct rad_attr_t *ra; + + list_for_each_entry(ra, &pack->attrs, entry) + if (!strcmp(ra->attr->name, name)) + 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; +} + +int rad_packet_add_vendor_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 + 6 + 2 + len >= REQ_LENGTH_MAX) + return -1; + + vendor = rad_dict_find_vendor_name(vendor_name); + if (!vendor) + return -1; + + attr = rad_dict_find_vendor_attr(vendor, 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 += 6 + 2 + len; + + return 0; +} + +struct rad_attr_t *rad_packet_find_vendor_attr(struct rad_packet_t *pack, const char *vendor_name, const char *name) +{ + struct rad_attr_t *ra; + + list_for_each_entry(ra, &pack->attrs, entry) { + if (!ra->vendor) + continue; + if (strcmp(ra->vendor->name, vendor_name)) + continue; + if (strcmp(ra->attr->name, name)) + continue; + + return ra; + } + + return NULL; +} + +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 new file mode 100644 index 00000000..9f5c7ffc --- /dev/null +++ b/accel-pptpd/radius/radius.c @@ -0,0 +1,373 @@ +#include <stdlib.h> +#include <stdarg.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <arpa/inet.h> + +#include "mempool.h" +#include "events.h" +#include "log.h" +#include "ppp.h" +#include "pwdb.h" +#include "ipdb.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; +char *conf_nas_identifier = "accel-pptpd"; +char *conf_nas_ip_address; +char *conf_gw_ip_address; +int conf_verbose = 0; + +char *conf_auth_server; +int conf_auth_server_port = 1812; +char *conf_auth_secret; + +char *conf_acct_server; +int conf_acct_server_port = 1813; +char *conf_acct_secret; +char *conf_dm_coa_secret; + +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; + +void rad_proc_attrs(struct rad_req_t *req) +{ + struct rad_attr_t *attr; + + 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 = inet_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.expire_tv.tv_sec = attr->val.integer; + break; + } + } +} + +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"); + ppp_terminate(rpd->ppp, 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); + 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_started(struct ppp_t *ppp) +{ + struct radius_pd_t *rpd = find_pd(ppp); + + if (rad_acct_start(rpd)) + ppp_terminate(rpd->ppp, 0); + + if (rpd->session_timeout.expire_tv.tv_sec) { + 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->acct_req) + rad_req_free(rpd->acct_req); + + if (rpd->dm_coa_req) + rad_packet_free(rpd->dm_coa_req); + + if (rpd->session_timeout.tpd) + triton_timer_del(&rpd->session_timeout); + + 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 (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->ipaddr.peer_addr) + 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) { + if (!strcmp(attr->attr->name, "Acct-Session-Id")) + sessionid = attr->val.string; + else if (!strcmp(attr->attr->name, "User-Name")) + username = attr->val.string; + else if (!strcmp(attr->attr->name, "NAS-Port")) + port_id = attr->val.integer; + else if (!strcmp(attr->attr->name, "Framed-IP-Address")) + ipaddr = attr->val.ipaddr; + else if (!strcmp(attr->attr->name, "Calling-Station-Id")) + csid = attr->val.string; + } + + if (!sessionid && !username && port_id == -1 && ipaddr == 0 && !csid) + return NULL; + + if (username && !sessionid) + 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_nas_identifier && (!ident || strcmp(conf_nas_identifier, ident))) + return -1; + if (conf_nas_ip_address && inet_addr(conf_nas_ip_address) != ipaddr) + return -1; + + return 0; +} + +static struct ipdb_t ipdb = { + .get = get_ip, +}; + +static struct pwdb_t pwdb = { + .check = check, +}; + +static int parse_server(const char *opt, char **name, 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; + + *name = str; + if (p1) { + *port = atoi(p1 + 1); + if (*port <=0 ) + return -1; + } + *secret = p2 + 1; + + return 0; +} + +static void __init radius_init(void) +{ + char *opt; + char *dict = DICT_PATH; + + rpd_pool = mempool_create(sizeof(struct radius_pd_t)); + + 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", "verbose"); + if (opt && atoi(opt) > 0) + conf_verbose = 1; + + opt = conf_get_opt("radius", "nas-ip-address"); + if (opt) + conf_nas_ip_address = opt; + + opt = conf_get_opt("radius", "nas-identifier"); + if (opt) + conf_nas_identifier = opt; + + opt = conf_get_opt("radius", "gw-ip-address"); + if (opt) + conf_gw_ip_address = opt; + + opt = conf_get_opt("radius", "auth_server"); + if (!opt) { + log_emerg("radius: auth_server not specified\n"); + _exit(EXIT_FAILURE); + } else if (parse_server(opt, &conf_auth_server, &conf_auth_server_port, &conf_auth_secret)) { + log_emerg("radius: failed to parse auth_server\n"); + _exit(EXIT_FAILURE); + } + + opt = conf_get_opt("radius", "acct_server"); + if (opt && parse_server(opt, &conf_acct_server, &conf_acct_server_port, &conf_acct_secret)) { + log_emerg("radius: failed to parse acct_server\n"); + _exit(EXIT_FAILURE); + } + + opt = conf_get_opt("radius", "dm_coa_secret"); + if (opt) + conf_dm_coa_secret = opt; + + 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_STARTED, (triton_event_func)ppp_started); + triton_event_register_handler(EV_PPP_FINISHING, (triton_event_func)ppp_finishing); + triton_event_register_handler(EV_PPP_FINISHED, (triton_event_func)ppp_finished); +} diff --git a/accel-pptpd/radius/radius.h b/accel-pptpd/radius/radius.h new file mode 100644 index 00000000..e202e264 --- /dev/null +++ b/accel-pptpd/radius/radius.h @@ -0,0 +1,107 @@ +#ifndef __RADIUS_H +#define __RADIUS_H + +#include <stdint.h> + +#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; + int id; + int len; + struct list_head attrs; + void *buf; +}; + +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 *name); +int rad_packet_add_int(struct rad_packet_t *pack, const char *name, int val); +int rad_packet_add_val(struct rad_packet_t *pack, const char *name, const char *val); +int rad_packet_add_str(struct rad_packet_t *pack, const char *name, const char *val, int len); +int rad_packet_add_octets(struct rad_packet_t *pack, const char *name, uint8_t *val, int len); +int rad_packet_change_int(struct rad_packet_t *pack, const char *name, int val); +int rad_packet_change_val(struct rad_packet_t *pack, const char *name, const char *val); +int rad_packet_add_ipaddr(struct rad_packet_t *pack, const char *name, in_addr_t ipaddr); +int rad_packet_add_vendor_octets(struct rad_packet_t *pack, const char *vendor_name, const char *name, const uint8_t *val, int len); +struct rad_attr_t *rad_packet_find_vendor_attr(struct rad_packet_t *pack, const char *vendor_name, const char *name); + +#endif + diff --git a/accel-pptpd/radius/radius_p.h b/accel-pptpd/radius/radius_p.h new file mode 100644 index 00000000..9537641b --- /dev/null +++ b/accel-pptpd/radius/radius_p.h @@ -0,0 +1,96 @@ +#ifndef __RADIUS_P_H +#define __RADIUS_P_H + +#include <netinet/in.h> +#include <pthread.h> + +#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 *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; +}; + +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; + const char *server_name; + int server_port; + + struct radius_pd_t *rpd; +}; + +extern int conf_max_try; +extern int conf_timeout; +extern int conf_verbose; +extern char *conf_nas_identifier; +extern char *conf_nas_ip_address; +extern char *conf_gw_ip_address; +extern char *conf_auth_server; +extern char *conf_auth_secret; +extern int conf_auth_server_port; +extern char *conf_acct_server; +extern char *conf_acct_secret; +extern int conf_acct_server_port; +extern char *conf_dm_coa_secret; + +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 rad_req_wait(struct rad_req_t *, int); + +struct radius_pd_t *find_pd(struct ppp_t *ppp); +void 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); +struct rad_packet_t *rad_packet_recv(int fd, 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); + + +#endif + diff --git a/accel-pptpd/radius/req.c b/accel-pptpd/radius/req.c new file mode 100644 index 00000000..f3f41386 --- /dev/null +++ b/accel-pptpd/radius/req.c @@ -0,0 +1,242 @@ +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> +#include <fcntl.h> +#include <unistd.h> +#include <sched.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> + +#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_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_name = 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, "User-Name", username, strlen(username))) + goto out_err; + if (conf_nas_identifier) + if (rad_packet_add_str(req->pack, "NAS-Identifier", conf_nas_identifier, strlen(conf_nas_identifier))) + goto out_err; + if (conf_nas_ip_address) + if (rad_packet_add_ipaddr(req->pack, "NAS-IP-Address", inet_addr(conf_nas_ip_address))) + goto out_err; + if (rad_packet_add_int(req->pack, "NAS-Port", rpd->ppp->unit_idx)) + goto out_err; + if (rad_packet_add_val(req->pack, "NAS-Port-Type", "Virtual")) + goto out_err; + if (rad_packet_add_val(req->pack, "Service-Type", "Framed-User")) + goto out_err; + if (rad_packet_add_val(req->pack, "Framed-Protocol", "PPP")) + goto out_err; + if (rpd->ppp->ctrl->calling_station_id) + if (rad_packet_add_str(req->pack, "Calling-Station-Id", rpd->ppp->ctrl->calling_station_id, strlen(rpd->ppp->ctrl->calling_station_id))) + goto out_err; + if (rpd->ppp->ctrl->called_station_id) + if (rad_packet_add_str(req->pack, "Called-Station-Id", rpd->ppp->ctrl->called_station_id, strlen(rpd->ppp->ctrl->called_station_id))) + goto out_err; + + return req; + +out_err: + rad_req_free(req); + return NULL; +} + +int rad_req_acct_fill(struct rad_req_t *req) +{ + req->server_name = conf_acct_server; + req->server_port = conf_acct_server_port; + + memset(req->RA, 0, sizeof(req->RA)); + + if (rad_packet_add_val(req->pack, "Acct-Authentic", "RADIUS")) + return -1; + if (rad_packet_add_val(req->pack, "Acct-Status-Type", "Start")) + return -1; + if (rad_packet_add_str(req->pack, "Acct-Session-Id", req->rpd->ppp->sessionid, PPP_SESSIONID_LEN)) + return -1; + if (rad_packet_add_int(req->pack, "Acct-Session-Time", 0)) + return -1; + if (rad_packet_add_int(req->pack, "Acct-Input-Octets", 0)) + return -1; + if (rad_packet_add_int(req->pack, "Acct-Output-Octets", 0)) + return -1; + if (rad_packet_add_int(req->pack, "Acct-Input-Packets", 0)) + return -1; + if (rad_packet_add_int(req->pack, "Acct-Output-Packets", 0)) + return -1; + if (rad_packet_add_int(req->pack, "Acct-Input-Gigawords", 0)) + return -1; + if (rad_packet_add_int(req->pack, "Acct-Output-Gigawords", 0)) + 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_nas_ip_address) { + addr.sin_addr.s_addr = inet_addr(conf_nas_ip_address); + 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 = inet_addr(req->server_name); + 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) +{ + 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 (conf_verbose) { + log_ppp_info("send "); + rad_packet_print(req->pack, log_ppp_info); + } + + 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); + + req->reply = rad_packet_recv(h->fd, NULL); + req_wakeup(req); + + return 0; +} +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(req->rpd->ppp->ctrl->ctx); + + if (conf_verbose && req->reply) { + log_ppp_info("recv "); + rad_packet_print(req->reply, log_ppp_info); + } + 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 new file mode 100644 index 00000000..3e5e068a --- /dev/null +++ b/accel-pptpd/triton/CMakeLists.txt @@ -0,0 +1,20 @@ +SET(sources_c + md.c + timer.c + triton.c + conf_file.c + loader.c + log.c + mempool.c + event.c +) + +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +ADD_DEFINITIONS(-DMODULE_PATH="${CMAKE_INSTALL_PREFIX}/usr/lib/accel-pptp") + +ADD_LIBRARY(triton SHARED ${sources_c}) + +INSTALL(TARGETS triton + LIBRARY DESTINATION usr/lib/accel-pptp +) diff --git a/accel-pptpd/triton/conf_file.c b/accel-pptpd/triton/conf_file.c new file mode 100644 index 00000000..6eb2e7a8 --- /dev/null +++ b/accel-pptpd/triton/conf_file.c @@ -0,0 +1,187 @@ +#include <string.h> +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> + +#include "triton_p.h" + +#include "memdebug.h" + +struct sect_t +{ + struct list_head entry; + + struct conf_sect_t *sect; +}; + +static LIST_HEAD(sections); + +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); + +int conf_load(const char *fname) +{ + char *buf,*str,*str2; + char *path0,*path; + int cur_line = 0; + static struct conf_sect_t *cur_sect = NULL; + + FILE *f = fopen(fname, "r"); + if (!f) { + perror("conf_file:open"); + return -1; + } + + buf = _malloc(1024); + path0 = _malloc(4096); + path = _malloc(4096); + + getcwd(path0, 1024); + + 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); + conf_load(str); + 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); + } + + _free(buf); + _free(path); + _free(path0); + fclose(f); + + return 0; +} + +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 new file mode 100644 index 00000000..d45eca01 --- /dev/null +++ b/accel-pptpd/triton/event.c @@ -0,0 +1,105 @@ +#include <stdlib.h> +#include <string.h> +#include <stdio.h> + +#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 new file mode 100644 index 00000000..d95dd714 --- /dev/null +++ b/accel-pptpd/triton/list.h @@ -0,0 +1,249 @@ +#ifndef _LINUX_LIST_H +#define _LINUX_LIST_H + +//#if defined(__KERNEL__) || defined(_LVM_H_INCLUDE) + +//#include <linux/prefetch.h> + +/* + * 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 new file mode 100644 index 00000000..b6c1914e --- /dev/null +++ b/accel-pptpd/triton/loader.c @@ -0,0 +1,62 @@ +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <stdio.h> +#include <errno.h> +#include <dlfcn.h> +#include <limits.h> + +#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_NOW | 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 new file mode 100644 index 00000000..c7e6b7fe --- /dev/null +++ b/accel-pptpd/triton/log.c @@ -0,0 +1,73 @@ +#include <stdio.h> +#include <stdarg.h> + +#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 new file mode 100644 index 00000000..444aebf0 --- /dev/null +++ b/accel-pptpd/triton/md.c @@ -0,0 +1,188 @@ +#include <stdio.h> +#include <stdlib.h> +#include <sys/time.h> +#include <signal.h> +#include <string.h> +#include <errno.h> +#include <unistd.h> + +#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; + +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; + 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; + 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); + } + } + + 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); + + __sync_fetch_and_add(&triton_stat.md_handler_count, 1); +} +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); + list_del(&h->entry); + if (h->pending) + list_del(&h->entry2); + h->ud = NULL; + spin_unlock(&h->ctx->lock); + sched_yield(); + mempool_free(h); + + __sync_fetch_and_sub(&triton_stat.md_handler_count, 1); +} +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 new file mode 100644 index 00000000..c96c3ba2 --- /dev/null +++ b/accel-pptpd/triton/mempool.c @@ -0,0 +1,179 @@ +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <signal.h> + +#include "triton_p.h" + +#include "memdebug.h" + +#define MAGIC1 0x2233445566778899llu + +struct _mempool_t +{ + struct list_head entry; + int size; + struct list_head items; + spinlock_t lock; + uint64_t magic; +}; + +struct _item_t +{ + struct _mempool_t *owner; + struct list_head entry; + uint64_t magic2; + uint64_t magic1; + char ptr[0]; +}; + +static LIST_HEAD(pools); +static spinlock_t pools_lock = SPINLOCK_INITIALIZER; + +__export mempool_t *mempool_create(int size) +{ + struct _mempool_t *p = _malloc(sizeof(*p)); + + memset(p, 0, sizeof(*p)); + INIT_LIST_HEAD(&p->items); + 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; +} + +#ifndef MEMDEBUG +__export void *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_fetch_and_sub(&triton_stat.mempool_available, size); + + it->magic1 = MAGIC1; + + return it->ptr; + } + spin_unlock(&p->lock); + + 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_fetch_and_add(&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; + + 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_fetch_and_sub(&triton_stat.mempool_available, size); + + it->magic1 = MAGIC1; + + return it->ptr; + } + spin_unlock(&p->lock); + + 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; + *(uint64_t*)(it->ptr + p->size) = it->magic2; + + __sync_fetch_and_add(&triton_stat.mempool_allocated, size); + + return it->ptr; +} + + +__export void mempool_free(void *ptr) +{ + struct _item_t *it = container_of(ptr, typeof(*it), ptr); + uint32_t size = sizeof(*it) + it->owner->size + 8; + + 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; + + spin_lock(&it->owner->lock); + list_add_tail(&it->entry,&it->owner->items); + spin_unlock(&it->owner->lock); + + __sync_fetch_and_add(&triton_stat.mempool_available, size); +} + +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) { + size = sizeof(*it) + p->size; + spin_lock(&p->lock); + while (!list_empty(&p->items)) { + it = list_entry(p->items.next, typeof(*it), entry); + list_del(&it->entry); + _free(it); + __sync_fetch_and_sub(&triton_stat.mempool_allocated, size); + __sync_fetch_and_sub(&triton_stat.mempool_available, size); + } + spin_unlock(&p->lock); + } + spin_unlock(&pools_lock); +} + +static void __init init(void) +{ + signal(35, sigclean); +} diff --git a/accel-pptpd/triton/mempool.h b/accel-pptpd/triton/mempool.h new file mode 100644 index 00000000..d3539215 --- /dev/null +++ b/accel-pptpd/triton/mempool.h @@ -0,0 +1,25 @@ +#ifndef __TRITON_MEMPOOL_H +#define __TRITON_MEMPOOL_H + +#include <stdint.h> + +struct mempool_stat_t +{ + uint32_t allocated; + uint32_t available; +}; + +typedef void * mempool_t; +mempool_t *mempool_create(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 new file mode 100644 index 00000000..a5214e21 --- /dev/null +++ b/accel-pptpd/triton/options.c @@ -0,0 +1,48 @@ +#include <stdlib.h> +#include <string.h> + +#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 new file mode 100644 index 00000000..b13cde61 --- /dev/null +++ b/accel-pptpd/triton/spinlock.h @@ -0,0 +1,20 @@ +#ifndef __TRITON_SPINLOCK_H +#define __TRITON_SPINLOCK_H + +#ifdef GCC_SPINLOCK +typedef volatile unsigned char 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 <pthread.h> +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 new file mode 100644 index 00000000..cbf2b13d --- /dev/null +++ b/accel-pptpd/triton/timer.c @@ -0,0 +1,181 @@ +#include <stdio.h> +#include <stdlib.h> +#include <sys/time.h> +#include <sys/epoll.h> +#include <sys/timerfd.h> +#include <string.h> +#include <errno.h> +#include <unistd.h> + +#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; + +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; + spin_lock(&t->ctx->lock); + if (t->ud) { + if (!t->pending) { + list_add_tail(&t->entry2, &t->ctx->pending_timers); + t->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); + } + } + + 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(CLOCK_MONOTONIC, TFD_NONBLOCK); + if (t->fd < 0) { + triton_log_error("timer:timerfd_create: %s" ,strerror(errno)); + mempool_free(t); + return -1; + } + + ud->tpd = t; + + if (triton_timer_mod(ud, abs_time)) { + close(t->fd); + mempool_free(t); + return -1; + } + + 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); + close(t->fd); + mempool_free(t); + ud->tpd = NULL; + return -1; + } + + __sync_fetch_and_add(&triton_stat.timer_count, 1); + + return 0; +} +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); + list_del(&t->entry); + if (t->pending) + list_del(&t->entry2); + t->ud = NULL; + spin_unlock(&t->ctx->lock); + sched_yield(); + mempool_free(t); + ud->tpd = NULL; + + __sync_fetch_and_sub(&triton_stat.timer_count, 1); +} + diff --git a/accel-pptpd/triton/triton.c b/accel-pptpd/triton/triton.c new file mode 100644 index 00000000..b2aaa7bb --- /dev/null +++ b/accel-pptpd/triton/triton.c @@ -0,0 +1,472 @@ +#include <signal.h> +#include <errno.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +#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 mempool_t *ctx_pool; +static mempool_t *call_pool; +static mempool_t *ctx_stack_pool; + +__export struct triton_stat_t triton_stat; + +void triton_thread_wakeup(struct _triton_thread_t *thread) +{ + //printf("wake up thread %p\n", thread); + pthread_kill(thread->thread, SIGUSR1); +} + +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); + + while (1) { + spin_lock(&threads_lock); + if (!list_empty(&ctx_queue)) { + thread->ctx = list_entry(ctx_queue.next, typeof(*thread->ctx), entry2); + //printf("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_fetch_and_sub(&triton_stat.context_pending, 1); + } else { + //printf("thread: %p: sleeping\n", thread); + if (!terminate) + list_add(&thread->entry2, &sleep_threads); + spin_unlock(&threads_lock); + if (terminate) + return NULL; + + __sync_fetch_and_sub(&triton_stat.thread_active, 1); + //printf("thread %p: enter sigwait\n", thread); + sigwait(&set, &sig); + //printf("thread %p: exit sigwait\n", thread); + __sync_fetch_and_add(&triton_stat.thread_active, 1); + + if (!thread->ctx) + continue; + } + +cont: + //printf("thread %p: ctx=%p %p\n", thread, thread->ctx, thread->ctx ? thread->ctx->thread : NULL); + if (thread->ctx->ud->before_switch) + thread->ctx->ud->before_switch(thread->ctx->ud, thread->ctx->bf_arg); + + //printf("thread %p: switch to %p\n", thread, thread->ctx); + while (1) { + if (swapcontext(&thread->uctx, &thread->ctx->uctx)) { + if (errno == EINTR) + continue; + triton_log_error("swapcontext: %s\n", strerror(errno)); + } else + break; + } + //printf("thread %p: switch from %p %p\n", thread, thread->ctx, thread->ctx->thread); + + if (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) { + //printf("- context %p removed\n", thread->ctx); + mempool_free(thread->ctx->uctx.uc_stack.ss_sp); + 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; + + while (1) { + //printf("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); + 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); + if (h->trig_epoll_events & (EPOLLIN | EPOLLERR | EPOLLHUP)) + if (h->ud && h->ud->read) + h->ud->read(h->ud); + if (h->trig_epoll_events & (EPOLLOUT | EPOLLERR | EPOLLHUP)) + if (h->ud && h->ud->write) + h->ud->write(h->ud); + 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); + } + ctx->pending = 0; + spin_unlock(&ctx->lock); + break; + } + + //printf("ctx %p %p: exit\n", ctx, ctx->thread); + while (1) { + if (swapcontext(&ctx->uctx, &ctx->thread->uctx)) { + if (errno == EINTR) + continue; + triton_log_error("swapcontext: %s\n", strerror(errno)); + } else + break; + } + } +} + +struct _triton_thread_t *create_thread() +{ + struct _triton_thread_t *thread = malloc(sizeof(*thread)); + if (!thread) + return NULL; + + memset(thread, 0, sizeof(*thread)); + if (pthread_create(&thread->thread, NULL, (void*(*)(void*))triton_thread, thread)) { + triton_log_error("pthread_create: %s", strerror(errno)); + return NULL; + } + + triton_stat.thread_count++; + triton_stat.thread_active++; + + return thread; +} + +int triton_queue_ctx(struct _triton_context_t *ctx) +{ + ctx->pending = 1; + if (ctx->thread || ctx->queued || ctx->sleeping) + return 0; + + spin_lock(&threads_lock); + if (list_empty(&sleep_threads)) { + list_add_tail(&ctx->entry2, &ctx_queue); + spin_unlock(&threads_lock); + ctx->queued = 1; + //printf("ctx %p: queued\n", ctx); + __sync_fetch_and_add(&triton_stat.context_pending, 1); + return 0; + } + + ctx->thread = list_entry(sleep_threads.next, typeof(*ctx->thread), entry2); + ctx->thread->ctx = ctx; + //printf("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); + + if (!ctx) + return -1; + + memset(ctx, 0, sizeof(*ctx)); + ctx->ud = ud; + ctx->bf_arg = bf_arg; + ctx->sleeping = 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); + + if (getcontext(&ctx->uctx)) { + triton_log_error("getcontext: %s\n", strerror(errno)); + _free(ctx); + return -1; + } + + ctx->uctx.uc_stack.ss_size = CTX_STACK_SIZE; + ctx->uctx.uc_stack.ss_sp = mempool_alloc(ctx_stack_pool); + if (!ctx->uctx.uc_stack.ss_sp) { + triton_log_error("out of memory\n"); + _free(ctx); + return -1; + } + sigfillset(&ctx->uctx.uc_sigmask); + makecontext(&ctx->uctx, (void (*)())ctx_thread, 1, ctx); + + ud->tpd = ctx; + + spin_lock(&ctx_list_lock); + list_add_tail(&ctx->entry, &ctx_list); + spin_unlock(&ctx_list_lock); + + __sync_fetch_and_add(&triton_stat.context_sleeping, 1); + __sync_fetch_and_add(&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; + + 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 (need_terminate && list_empty(&ctx_list)) + terminate = 1; + spin_unlock(&ctx_list_lock); + + __sync_fetch_and_sub(&triton_stat.context_count, 1); + + if (terminate) { + list_for_each_entry(t, &threads, entry) + triton_thread_wakeup(t); + } +} +void __export triton_context_schedule(struct triton_context_t *ud) +{ + struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; + ucontext_t *uctx = &ctx->thread->uctx; + + spin_lock(&ctx->lock); + if (ctx->wakeup) { + ctx->wakeup = 0; + spin_unlock(&ctx->lock); + return; + } + ctx->sleeping = 1; + ctx->thread = NULL; + spin_unlock(&ctx->lock); + + while (1) { + if (swapcontext(&ctx->uctx, uctx)) { + if (errno == EINTR) + continue; + triton_log_error("swaswpntext: %s\n", strerror(errno)); + } else + break; + } + + __sync_fetch_and_add(&triton_stat.context_sleeping, 1); +} + +int __export triton_context_wakeup(struct triton_context_t *ud) +{ + struct _triton_context_t *ctx = (struct _triton_context_t *)ud->tpd; + int r; + + spin_lock(&ctx->lock); + if (!ctx->sleeping) { + ctx->wakeup = 1; + spin_unlock(&ctx->lock); + return -1; + } + ctx->sleeping = 0; + r = triton_queue_ctx(ctx); + spin_unlock(&ctx->lock); + + if (r) + triton_thread_wakeup(ctx->thread); + + __sync_fetch_and_sub(&triton_stat.context_sleeping, 1); + + return 0; +} + +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; +} + +int __export triton_init(const char *conf_file) +{ + ctx_pool = mempool_create(sizeof(struct _triton_context_t)); + call_pool = mempool_create(sizeof(struct _triton_ctx_call_t)); + ctx_stack_pool = mempool_create(CTX_STACK_SIZE); + + 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_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); + } + + md_run(); + timer_run(); +} + +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 new file mode 100644 index 00000000..4b4d9c41 --- /dev/null +++ b/accel-pptpd/triton/triton.h @@ -0,0 +1,127 @@ +#ifndef TRITON_H +#define TRITON_H + +#include <sys/time.h> +#include <stdint.h> + +#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 +{ + uint32_t mempool_allocated; + uint32_t mempool_available; + uint32_t thread_count; + uint32_t thread_active; + uint32_t context_count; + uint32_t context_sleeping; + uint32_t context_pending; + uint32_t md_handler_count; + uint32_t md_handler_pending; + uint32_t timer_count; + uint32_t timer_pending; +}; + +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_schedule(struct triton_context_t *); +int triton_context_wakeup(struct triton_context_t *); +int triton_context_call(struct triton_context_t *, void (*func)(void *), void *arg); + +#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); + +#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 __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 new file mode 100644 index 00000000..c685051a --- /dev/null +++ b/accel-pptpd/triton/triton_p.h @@ -0,0 +1,105 @@ +#ifndef TRITON_P_H +#define TRITON_P_H + +#include <pthread.h> +#include <sys/epoll.h> +#include <ucontext.h> + +#include "triton.h" +#include "list.h" +#include "spinlock.h" +#include "mempool.h" + +#define CTX_STACK_SIZE 8196 + +struct _triton_thread_t +{ + struct list_head entry; + struct list_head entry2; + pthread_t thread; + int terminate:1; + struct _triton_context_t *ctx; + ucontext_t uctx; +}; + +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; + + ucontext_t uctx; + + int queued:1; + int sleeping:1; + int wakeup:1; + int need_close:1; + int need_free:1; + int pending:1; + + 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(); +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); +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 new file mode 100644 index 00000000..491e6507 --- /dev/null +++ b/accel-pptpd/utils.c @@ -0,0 +1,11 @@ +#include <stdio.h> + +#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 new file mode 100644 index 00000000..27d4d058 --- /dev/null +++ b/accel-pptpd/utils.h @@ -0,0 +1,8 @@ +#ifndef __UTILS_H +#define __UTILS_H + +#include <netinet/in.h> + +void u_inet_ntoa(in_addr_t, char *str); + +#endif |