From 86cc496009534a972bca3d37e10e6927fba83440 Mon Sep 17 00:00:00 2001 From: yizhou Date: Fri, 7 Apr 2023 22:40:54 +0800 Subject: [PATCH 01/14] add cmake support --- .gitignore | 6 ++++-- CMakeLists.txt | 12 ++++++++++++ auth.h => include/auth.h | 0 {libs => include}/common.h | 0 configparse.h => include/configparse.h | 0 daemon.h => include/daemon.h | 0 debug.h => include/debug.h | 0 eapol.h => include/eapol.h | 2 +- keepalive.h => include/keepalive.h | 0 {libs => include/libs}/md4.h | 0 {libs => include/libs}/md5.h | 0 {libs => include/libs}/sha1.h | 0 auth.c => src/auth.c | 6 +++--- {libs => src}/common.c | 2 +- configparse.c => src/configparse.c | 0 daemon.c => src/daemon.c | 0 eapol.c => src/eapol.c | 4 ++-- keepalive.c => src/keepalive.c | 6 +++--- main.c => src/main.c | 4 ++-- {libs => src}/md4.c | 2 +- {libs => src}/md5.c | 2 +- {libs => src}/sha1.c | 2 +- 22 files changed, 31 insertions(+), 17 deletions(-) create mode 100644 CMakeLists.txt rename auth.h => include/auth.h (100%) rename {libs => include}/common.h (100%) rename configparse.h => include/configparse.h (100%) rename daemon.h => include/daemon.h (100%) rename debug.h => include/debug.h (100%) rename eapol.h => include/eapol.h (99%) rename keepalive.h => include/keepalive.h (100%) rename {libs => include/libs}/md4.h (100%) rename {libs => include/libs}/md5.h (100%) rename {libs => include/libs}/sha1.h (100%) rename auth.c => src/auth.c (99%) rename {libs => src}/common.c (99%) rename configparse.c => src/configparse.c (100%) rename daemon.c => src/daemon.c (100%) rename eapol.c => src/eapol.c (99%) rename keepalive.c => src/keepalive.c (99%) rename main.c => src/main.c (99%) rename {libs => src}/md4.c (99%) rename {libs => src}/md5.c (99%) rename {libs => src}/sha1.c (99%) diff --git a/.gitignore b/.gitignore index b3153d0..905432f 100644 --- a/.gitignore +++ b/.gitignore @@ -4,9 +4,11 @@ test.conf dogcom main .vscode - +build/ # Prerequisites *.d +.DS_Store +.idea/ # Object files *.o @@ -56,4 +58,4 @@ modules.order Module.symvers Mkfile.old dkms.conf -*.stackdump \ No newline at end of file +*.stackdump diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..d8d9651 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 3.0.0) +project(dogcom) + +file(GLOB_RECURSE SRCS "src/*.c" "include/*.h") +include_directories(${PROJECT_SOURCE_DIR}/include) +message(${SRCS}) +add_executable(dogcom ${SRCS}) + +if (CMAKE_SYSTEM_NAME STREQUAL "Windows") + message("on windows!\n") + add_link_options("-lws2_32") +endif () \ No newline at end of file diff --git a/auth.h b/include/auth.h similarity index 100% rename from auth.h rename to include/auth.h diff --git a/libs/common.h b/include/common.h similarity index 100% rename from libs/common.h rename to include/common.h diff --git a/configparse.h b/include/configparse.h similarity index 100% rename from configparse.h rename to include/configparse.h diff --git a/daemon.h b/include/daemon.h similarity index 100% rename from daemon.h rename to include/daemon.h diff --git a/debug.h b/include/debug.h similarity index 100% rename from debug.h rename to include/debug.h diff --git a/eapol.h b/include/eapol.h similarity index 99% rename from eapol.h rename to include/eapol.h index ed7df0c..28e6c19 100644 --- a/eapol.h +++ b/include/eapol.h @@ -1,7 +1,7 @@ #ifndef EAPOL_H__ #define EAPOL_H__ -#include "libs/common.h" +#include #define IDEN_LEN UNAME_LEN diff --git a/keepalive.h b/include/keepalive.h similarity index 100% rename from keepalive.h rename to include/keepalive.h diff --git a/libs/md4.h b/include/libs/md4.h similarity index 100% rename from libs/md4.h rename to include/libs/md4.h diff --git a/libs/md5.h b/include/libs/md5.h similarity index 100% rename from libs/md5.h rename to include/libs/md5.h diff --git a/libs/sha1.h b/include/libs/sha1.h similarity index 100% rename from libs/sha1.h rename to include/libs/sha1.h diff --git a/auth.c b/src/auth.c similarity index 99% rename from auth.c rename to src/auth.c index 57d1883..fcc1900 100644 --- a/auth.c +++ b/src/auth.c @@ -18,9 +18,9 @@ typedef int socklen_t; #include "configparse.h" #include "debug.h" #include "keepalive.h" -#include "libs/md4.h" -#include "libs/md5.h" -#include "libs/sha1.h" +#include +#include +#include #define BIND_PORT 61440 #define DEST_PORT 61440 diff --git a/libs/common.c b/src/common.c similarity index 99% rename from libs/common.c rename to src/common.c index 6db6bd7..0c6f0fa 100644 --- a/libs/common.c +++ b/src/common.c @@ -9,7 +9,7 @@ #include #include #include -#include "common.h" +#include "common.h> // #ifdef LINUX #include diff --git a/configparse.c b/src/configparse.c similarity index 100% rename from configparse.c rename to src/configparse.c diff --git a/daemon.c b/src/daemon.c similarity index 100% rename from daemon.c rename to src/daemon.c diff --git a/eapol.c b/src/eapol.c similarity index 99% rename from eapol.c rename to src/eapol.c index d5aac62..15732bd 100644 --- a/eapol.c +++ b/src/eapol.c @@ -1,8 +1,8 @@ #ifdef linux #include "eapol.h" -#include "libs/common.h" -#include "libs/md5.h" +#include +#include #include #include diff --git a/keepalive.c b/src/keepalive.c similarity index 99% rename from keepalive.c rename to src/keepalive.c index 2d3919f..961e360 100644 --- a/keepalive.c +++ b/src/keepalive.c @@ -14,9 +14,9 @@ typedef int socklen_t; #include "configparse.h" #include "debug.h" #include "keepalive.h" -#include "libs/md4.h" -#include "libs/md5.h" -#include "libs/sha1.h" +#include +#include +#include int keepalive_1(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsigned char auth_information[]) { if (drcom_config.keepalive1_mod) { diff --git a/main.c b/src/main.c similarity index 99% rename from main.c rename to src/main.c index 19b2440..49561fa 100644 --- a/main.c +++ b/src/main.c @@ -7,9 +7,9 @@ #ifdef linux #include -#include "daemon.h" +#include "daemon.h> #include "eapol.h" -#include "libs/common.h" +#include #endif #define VERSION "1.6.2" diff --git a/libs/md4.c b/src/md4.c similarity index 99% rename from libs/md4.c rename to src/md4.c index b73fbda..07a0d6e 100644 --- a/libs/md4.c +++ b/src/md4.c @@ -39,7 +39,7 @@ #include -#include "md4.h" +#include /* * The basic MD4 functions. diff --git a/libs/md5.c b/src/md5.c similarity index 99% rename from libs/md5.c rename to src/md5.c index cf3e170..3bf14c8 100644 --- a/libs/md5.c +++ b/src/md5.c @@ -39,7 +39,7 @@ #include -#include "md5.h" +#include /* * The basic MD5 functions. diff --git a/libs/sha1.c b/src/sha1.c similarity index 99% rename from libs/sha1.c rename to src/sha1.c index 972bbff..68f1d25 100644 --- a/libs/sha1.c +++ b/src/sha1.c @@ -24,7 +24,7 @@ A million repetitions of "a" #include #include #include -#include "sha1.h" +#include #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) From 245f9f2b554ababcbadc71f3dc9c6f045954a5ad Mon Sep 17 00:00:00 2001 From: yizhou Date: Fri, 7 Apr 2023 23:05:08 +0800 Subject: [PATCH 02/14] fix FORCE_ENCRYPT --- CMakeLists.txt | 14 ++++++++++---- Makefile | 49 ------------------------------------------------- README.md | 13 ++++++++----- 3 files changed, 18 insertions(+), 58 deletions(-) delete mode 100644 Makefile diff --git a/CMakeLists.txt b/CMakeLists.txt index d8d9651..04eec53 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,12 +1,18 @@ cmake_minimum_required(VERSION 3.0.0) project(dogcom) +set(CMAKE_C_STANDARD_REQUIRED 99) +set(FORCE_ENCRYPT ON) + file(GLOB_RECURSE SRCS "src/*.c" "include/*.h") include_directories(${PROJECT_SOURCE_DIR}/include) -message(${SRCS}) -add_executable(dogcom ${SRCS}) + +if (${FORCE_ENCRYPT}) + add_compile_definitions(FORCE_ENCRYPT) +endif () if (CMAKE_SYSTEM_NAME STREQUAL "Windows") - message("on windows!\n") add_link_options("-lws2_32") -endif () \ No newline at end of file +endif () + +add_executable(dogcom ${SRCS}) \ No newline at end of file diff --git a/Makefile b/Makefile deleted file mode 100644 index fd7b6f5..0000000 --- a/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -CC = gcc -TARGET = dogcom -INSTALL_DIR = /usr/bin/ - -ifeq ($(debug), y) - CFLAGS += -DDEBUG -g -endif - -ifeq ($(win32), y) - CFLAGS += -lws2_32 - # TARGET = dogcom.exe -endif - -ifeq ($(static), y) - CFLAGS += -static -endif - -ifeq ($(strip), y) - CFLAGS += -Os -s -Wno-unused-result -endif - -ifeq ($(force_encrypt), y) - CFLAGS += -DFORCE_ENCRYPT -endif - -ifeq ($(test), y) - CFLAGS += -std=gnu99 -Werror -DTEST -else - CFLAGS += -std=gnu99 -Werror -endif - -SOURCES = $(wildcard *.c) $(wildcard libs/*.c) -OBJS = $(patsubst %.c, %.o, $(SOURCES)) - -$(TARGET): $(OBJS) - $(CC) $(DEBUG) $(TEST) $(OBJS) $(CFLAGS) -o $(TARGET) - -all: $(TARGET) - -install: $(TARGET) - cp $(TARGET) $(INSTALL_DIR) - -clean: - rm -f $(OBJS) - rm -f $(TARGET) - -distclean: clean - -.PHONY: all clean distclean install diff --git a/README.md b/README.md index 0984eba..857dc00 100644 --- a/README.md +++ b/README.md @@ -34,12 +34,15 @@ $ dogcom -m dhcp -c dogcom.conf -b 10.2.3.12 -v #### To build: -```bash -$ make # Linux -$ make win32=y # Windows(MinGW) -$ make test=y # For testing purposes -$ make force_encrypt=y # Force open encrypt mode in PPPoE version +Dogcom use cmake for building. + +CMake will detect your platform and compiler, then decide how to compile. + +If you want force-encrypt, you should add +```cmake +set(FORCE_ENCRYPT ON) ``` +in CMakeLists.txt #### Openwrt-package [https://github.com/mchome/openwrt-dogcom](https://github.com/mchome/openwrt-dogcom) From 0cb04bb0694d94843d0a809197062be02cfc69eb Mon Sep 17 00:00:00 2001 From: tsurumiyizhou Date: Sat, 8 Apr 2023 00:17:47 +0800 Subject: [PATCH 03/14] windows surpport --- CMakeLists.txt | 8 +- include/libs/getopt4win.h | 193 ++++++ src/auth.c | 30 +- src/common.c | 2 +- src/getopt4win.c | 1274 +++++++++++++++++++++++++++++++++++++ src/keepalive.c | 3 +- src/main.c | 9 +- 7 files changed, 1505 insertions(+), 14 deletions(-) create mode 100644 include/libs/getopt4win.h create mode 100644 src/getopt4win.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 04eec53..6a48f2a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.0.0) project(dogcom) set(CMAKE_C_STANDARD_REQUIRED 99) -set(FORCE_ENCRYPT ON) +set(FORCE_ENCRYPT OFF) file(GLOB_RECURSE SRCS "src/*.c" "include/*.h") include_directories(${PROJECT_SOURCE_DIR}/include) @@ -11,8 +11,8 @@ if (${FORCE_ENCRYPT}) add_compile_definitions(FORCE_ENCRYPT) endif () +add_executable(dogcom ${SRCS}) + if (CMAKE_SYSTEM_NAME STREQUAL "Windows") - add_link_options("-lws2_32") + target_link_libraries(dogcom PRIVATE ws2_32) endif () - -add_executable(dogcom ${SRCS}) \ No newline at end of file diff --git a/include/libs/getopt4win.h b/include/libs/getopt4win.h new file mode 100644 index 0000000..6e2fa27 --- /dev/null +++ b/include/libs/getopt4win.h @@ -0,0 +1,193 @@ +/* Declarations for getopt. + Copyright (C) 1989-1994,1996-1999,2001,2003,2004,2009,2010 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#ifndef _GETOPT_H + +#ifndef __need_getopt +# define _GETOPT_H 1 +#endif + +/* If __GNU_LIBRARY__ is not already defined, either we are being used + standalone, or this is the first header included in the source file. + If we are being used with glibc, we need to include , but + that does not exist if we are standalone. So: if __GNU_LIBRARY__ is + not defined, include , which will pull in for us + if it's from glibc. (Why ctype.h? It's guaranteed to exist and it + doesn't flood the namespace with stuff the way some other headers do.) */ +#if !defined __GNU_LIBRARY__ +# include +#endif + +#ifndef __THROW +# ifndef __GNUC_PREREQ +# define __GNUC_PREREQ(maj, min) (0) +# endif +# if defined __cplusplus && __GNUC_PREREQ (2,8) +# define __THROW throw () +# else +# define __THROW +# endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +extern char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +extern int optind; + +/* Callers store zero here to inhibit the error message `getopt' prints + for unrecognized options. */ + +extern int opterr; + +/* Set to an option character which was unrecognized. */ + +extern int optopt; + +#ifndef __need_getopt +/* Describe the long-named options requested by the application. + The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector + of `struct option' terminated by an element containing a name which is + zero. + + The field `has_arg' is: + no_argument (or 0) if the option does not take an argument, + required_argument (or 1) if the option requires an argument, + optional_argument (or 2) if the option takes an optional argument. + + If the field `flag' is not NULL, it points to a variable that is set + to the value given in the field `val' when the option is found, but + left unchanged if the option is not found. + + To have a long-named option do something other than set an `int' to + a compiled-in constant, such as set a value from `optarg', set the + option's `flag' field to zero and its `val' field to a nonzero + value (the equivalent single-letter option character, if there is + one). For long options that have a zero `flag' field, `getopt' + returns the contents of the `val' field. */ + +struct option +{ + const char *name; + /* has_arg can't be an enum because some compilers complain about + type mismatches in all the code that assumes it is an int. */ + int has_arg; + int *flag; + int val; +}; + +/* Names for the values of the `has_arg' field of `struct option'. */ + +# define no_argument 0 +# define required_argument 1 +# define optional_argument 2 +#endif /* need getopt */ + + +/* Get definitions and prototypes for functions to process the + arguments in ARGV (ARGC of them, minus the program name) for + options given in OPTS. + + Return the option character from OPTS just read. Return -1 when + there are no more options. For unrecognized options, or options + missing arguments, `optopt' is set to the option letter, and '?' is + returned. + + The OPTS string is a list of characters which are recognized option + letters, optionally followed by colons, specifying that that letter + takes an argument, to be placed in `optarg'. + + If a letter in OPTS is followed by two colons, its argument is + optional. This behavior is specific to the GNU `getopt'. + + The argument `--' causes premature termination of argument + scanning, explicitly telling `getopt' that there are no more + options. + + If OPTS begins with `--', then non-option arguments are treated as + arguments to the option '\0'. This behavior is specific to the GNU + `getopt'. */ + +#ifdef __GNU_LIBRARY__ +/* Many other libraries have conflicting prototypes for getopt, with + differences in the consts, in stdlib.h. To avoid compilation + errors, only prototype getopt for the GNU C library. */ +extern int getopt (int ___argc, char *const *___argv, const char *__shortopts) + __THROW; + +# if defined __need_getopt && defined __USE_POSIX2 \ + && !defined __USE_POSIX_IMPLICITLY && !defined __USE_GNU +/* The GNU getopt has more functionality than the standard version. The + additional functionality can be disable at runtime. This redirection + helps to also do this at runtime. */ +# ifdef __REDIRECT + extern int __REDIRECT_NTH (getopt, (int ___argc, char *const *___argv, + const char *__shortopts), + __posix_getopt); +# else +extern int __posix_getopt (int ___argc, char *const *___argv, + const char *__shortopts) __THROW; +# define getopt __posix_getopt +# endif +# endif +#else /* not __GNU_LIBRARY__ */ +extern int getopt (); +#endif /* __GNU_LIBRARY__ */ + +#ifndef __need_getopt +extern int getopt_long (int ___argc, char *const *___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind) + __THROW; +extern int getopt_long_only (int ___argc, char *const *___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind) + __THROW; + +#endif + +#ifdef __cplusplus +} +#endif + +/* Make sure we later can get all the definitions and declarations. */ +#undef __need_getopt + +#endif /* getopt.h */ diff --git a/src/auth.c b/src/auth.c index fcc1900..2ff2f16 100644 --- a/src/auth.c +++ b/src/auth.c @@ -1,9 +1,7 @@ #include #include #include -#include #include -#include #ifdef WIN32 #include @@ -14,6 +12,20 @@ typedef int socklen_t; #include #endif + +#ifdef _MSC_VER +#include +inline void sleep(int seconds) { + Sleep(1000 * seconds); +} +inline void usleep(int useconds) { + Sleep(useconds); +} +#else +#include +#include +#endif + #include "auth.h" #include "configparse.h" #include "debug.h" @@ -102,7 +114,8 @@ int dhcp_login(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsign } else { login_packet_size = 330; } - unsigned char login_packet[login_packet_size], recv_packet[1024], MD5A[16], MACxorMD5A[6], MD5B[16], checksum1[8], checksum2[4]; + unsigned char* login_packet = (unsigned char*) malloc(login_packet_size); + unsigned char recv_packet[1024], MD5A[16], MACxorMD5A[6], MD5B[16], checksum1[8], checksum2[4]; memset(login_packet, 0, login_packet_size); memset(recv_packet, 0, 100); @@ -112,7 +125,7 @@ int dhcp_login(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsign login_packet[2] = 0x00; login_packet[3] = strlen(drcom_config.username) + 20; int MD5A_len = 6 + strlen(drcom_config.password); - unsigned char MD5A_str[MD5A_len]; + unsigned char* MD5A_str = (unsigned char*)malloc(MD5A_len); MD5A_str[0] = 0x03; MD5A_str[1] = 0x01; memcpy(MD5A_str + 2, seed, 4); @@ -140,7 +153,7 @@ int dhcp_login(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsign } memcpy(login_packet + 58, MACxorMD5A, sizeof(MACxorMD5A)); int MD5B_len = 9 + strlen(drcom_config.password); - unsigned char MD5B_str[MD5B_len]; + unsigned char* MD5B_str = (unsigned char*) malloc (MD5B_len); memset(MD5B_str, 0, MD5B_len); MD5B_str[0] = 0x01; memcpy(MD5B_str + 1, drcom_config.password, strlen(drcom_config.password)); @@ -229,7 +242,7 @@ int dhcp_login(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsign } login_packet[counter] = 0x02; login_packet[counter + 1] = 0x0c; - unsigned char checksum2_str[counter + 18]; // [counter + 14 + 4] + unsigned char* checksum2_str = (unsigned char*) malloc (counter + 18); // [counter + 14 + 4] memset(checksum2_str, 0, counter + 18); unsigned char checksum2_tmp[6] = {0x01, 0x26, 0x07, 0x11}; memcpy(checksum2_str, login_packet, counter + 2); @@ -359,6 +372,11 @@ int dhcp_login(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsign DEBUG_PRINT(("Get notice packet.")); } + free(login_packet); + free(MD5A_str); + free(MD5B_str); + free(checksum2_str); + return 0; } diff --git a/src/common.c b/src/common.c index 0c6f0fa..6db6bd7 100644 --- a/src/common.c +++ b/src/common.c @@ -9,7 +9,7 @@ #include #include #include -#include "common.h> +#include "common.h" // #ifdef LINUX #include diff --git a/src/getopt4win.c b/src/getopt4win.c new file mode 100644 index 0000000..3940758 --- /dev/null +++ b/src/getopt4win.c @@ -0,0 +1,1274 @@ +/* Getopt for GNU. +NOTE: getopt is now part of the C library, so if you don't know what +"Keep this file name-space clean" means, talk to drepper@gnu.org +before changing it! +Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001 +Free Software Foundation, Inc. +This file is part of the GNU C Library. + +The GNU C Library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +The GNU C Library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with the GNU C Library; if not, write to the Free +Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. */ + +/* This tells Alpha OSF/1 not to define a getopt prototype in . +Ditto for AIX 3.2 and . */ +#ifndef _NO_PROTO +# define _NO_PROTO +#endif + +#ifdef HAVE_CONFIG_H +# include +#endif + +#if !defined __STDC__ || !__STDC__ +/* This is a separate conditional since some stdc systems +reject `defined (const)'. */ +# ifndef const +# define const +# endif +#endif + +#include + +/* Comment out all this code if we are using the GNU C Library, and are not +actually compiling the library itself. This code is part of the GNU C +Library, but also included in many other GNU distributions. Compiling +and linking in this code is a waste when using the GNU C library +(especially if it is a shared library). Rather than having every GNU +program understand `configure --with-gnu-libc' and omit the object files, +it is simpler to just do this in the source for each such file. */ + +#define GETOPT_INTERFACE_VERSION 2 +#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 +# include +# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION +# define ELIDE_CODE +# endif +#endif + +#ifndef ELIDE_CODE + + +/* This needs to come after some library #include +to get __GNU_LIBRARY__ defined. */ +#ifdef __GNU_LIBRARY__ +/* Don't include stdlib.h for non-GNU C libraries because some of them +contain conflicting prototypes for getopt. */ +# include +# include +#endif /* GNU C library. */ + +#ifdef VMS +# include +# if HAVE_STRING_H - 0 +# include +# endif +#endif + +#ifndef _ +/* This is for other GNU distributions with internationalized messages. */ +# if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC +# include +# ifndef _ +# define _(msgid) gettext (msgid) +# endif +# else +# define _(msgid) (msgid) +# endif +# if defined _LIBC && defined USE_IN_LIBIO +# include +# endif +#endif + +/* This version of `getopt' appears to the caller like standard Unix `getopt' +but it behaves differently for the user, since it allows the user +to intersperse the options with the other arguments. + +As `getopt' works, it permutes the elements of ARGV so that, +when it is done, all the options precede everything else. Thus +all application programs are extended to handle flexible argument order. + +Setting the environment variable POSIXLY_CORRECT disables permutation. +Then the behavior is completely standard. + +GNU application programs can use a third alternative mode in which +they can distinguish the relative order of options and other arguments. */ + +#include "libs/getopt4win.h" + +/* For communication from `getopt' to the caller. +When `getopt' finds an option that takes an argument, +the argument value is returned here. +Also, when `ordering' is RETURN_IN_ORDER, +each non-option ARGV-element is returned here. */ + +char *optarg; + +/* Index in ARGV of the next element to be scanned. +This is used for communication to and from the caller +and for communication between successive calls to `getopt'. + +On entry to `getopt', zero means this is the first call; initialize. + +When `getopt' returns -1, this is the index of the first of the +non-option elements that the caller should itself scan. + +Otherwise, `optind' communicates from one call to the next +how much of ARGV has been scanned so far. */ + +/* 1003.2 says this must be 1 before any call. */ +int optind = 1; + +/* Formerly, initialization of getopt depended on optind==0, which +causes problems with re-calling getopt as programs generally don't +know that. */ + +int __getopt_initialized; + +/* The next char to be scanned in the option-element +in which the last option character we returned was found. +This allows us to pick up the scan where we left off. + +If this is zero, or a null string, it means resume the scan +by advancing to the next ARGV-element. */ + +static char *nextchar; + +/* Callers store zero here to inhibit the error message +for unrecognized options. */ + +int opterr = 1; + +/* Set to an option character which was unrecognized. +This must be initialized on some systems to avoid linking in the +system's own getopt implementation. */ + +int optopt = '?'; + +/* Describe how to deal with options that follow non-option ARGV-elements. + +If the caller did not specify anything, +the default is REQUIRE_ORDER if the environment variable +POSIXLY_CORRECT is defined, PERMUTE otherwise. + +REQUIRE_ORDER means don't recognize them as options; +stop option processing when the first non-option is seen. +This is what Unix does. +This mode of operation is selected by either setting the environment +variable POSIXLY_CORRECT, or using `+' as the first character +of the list of option characters. + +PERMUTE is the default. We permute the contents of ARGV as we scan, +so that eventually all the non-options are at the end. This allows options +to be given in any order, even with programs that were not written to +expect this. + +RETURN_IN_ORDER is an option available to programs that were written +to expect options and other ARGV-elements in any order and that care about +the ordering of the two. We describe each non-option ARGV-element +as if it were the argument of an option with character code 1. +Using `-' as the first character of the list of option characters +selects this mode of operation. + +The special argument `--' forces an end of option-scanning regardless +of the value of `ordering'. In the case of RETURN_IN_ORDER, only +`--' can cause `getopt' to return -1 with `optind' != ARGC. */ + +static enum +{ + REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER +} ordering; + +/* Value of POSIXLY_CORRECT environment variable. */ +static char *posixly_correct; + +#ifdef __GNU_LIBRARY__ +/* We want to avoid inclusion of string.h with non-GNU libraries +because there are many ways it can cause trouble. +On some systems, it contains special magic macros that don't work +in GCC. */ +# include +# define my_index strchr +#else + +#define HAVE_STRING_H 1 +# if HAVE_STRING_H +# include +# else +# include +# endif + +/* Avoid depending on library functions or files +whose names are inconsistent. */ + +#ifndef getenv +extern char *getenv(); +#endif + +static char * +my_index(str, chr) +const char *str; +int chr; +{ + while (*str) + { + if (*str == chr) + return (char *)str; + str++; + } + return 0; +} + +/* If using GCC, we can safely declare strlen this way. +If not using GCC, it is ok not to declare it. */ +#ifdef __GNUC__ +/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. +That was relevant to code that was here before. */ +# if (!defined __STDC__ || !__STDC__) && !defined strlen +/* gcc with -traditional declares the built-in strlen to return int, +and has done so at least since version 2.4.5. -- rms. */ +extern int strlen(const char *); +# endif /* not __STDC__ */ +#endif /* __GNUC__ */ + +#endif /* not __GNU_LIBRARY__ */ + +/* Handle permutation of arguments. */ + +/* Describe the part of ARGV that contains non-options that have +been skipped. `first_nonopt' is the index in ARGV of the first of them; +`last_nonopt' is the index after the last of them. */ + +static int first_nonopt; +static int last_nonopt; + +#ifdef _LIBC +/* Stored original parameters. +XXX This is no good solution. We should rather copy the args so +that we can compare them later. But we must not use malloc(3). */ +extern int __libc_argc; +extern char **__libc_argv; + +/* Bash 2.0 gives us an environment variable containing flags +indicating ARGV elements that should not be considered arguments. */ + +# ifdef USE_NONOPTION_FLAGS +/* Defined in getopt_init.c */ +extern char *__getopt_nonoption_flags; + +static int nonoption_flags_max_len; +static int nonoption_flags_len; +# endif + +# ifdef USE_NONOPTION_FLAGS +# define SWAP_FLAGS(ch1, ch2) \ +if (nonoption_flags_len > 0) \ +{ \ + char __tmp = __getopt_nonoption_flags[ch1]; \ + __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ + __getopt_nonoption_flags[ch2] = __tmp; \ +} +# else +# define SWAP_FLAGS(ch1, ch2) +# endif +#else /* !_LIBC */ +# define SWAP_FLAGS(ch1, ch2) +#endif /* _LIBC */ + +/* Exchange two adjacent subsequences of ARGV. +One subsequence is elements [first_nonopt,last_nonopt) +which contains all the non-options that have been skipped so far. +The other is elements [last_nonopt,optind), which contains all +the options processed since those non-options were skipped. + +`first_nonopt' and `last_nonopt' are relocated so that they describe +the new indices of the non-options in ARGV after they are moved. */ + +#if defined __STDC__ && __STDC__ +static void exchange(char **); +#endif + +static void +exchange(argv) +char **argv; +{ + int bottom = first_nonopt; + int middle = last_nonopt; + int top = optind; + char *tem; + + /* Exchange the shorter segment with the far end of the longer segment. + That puts the shorter segment into the right place. + It leaves the longer segment in the right place overall, + but it consists of two parts that need to be swapped next. */ + +#if defined _LIBC && defined USE_NONOPTION_FLAGS + /* First make sure the handling of the `__getopt_nonoption_flags' + string can work normally. Our top argument must be in the range + of the string. */ + if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) + { + /* We must extend the array. The user plays games with us and + presents new arguments. */ + char *new_str = malloc(top + 1); + if (new_str == NULL) + nonoption_flags_len = nonoption_flags_max_len = 0; + else + { + memset(__mempcpy(new_str, __getopt_nonoption_flags, + nonoption_flags_max_len), + '\0', top + 1 - nonoption_flags_max_len); + nonoption_flags_max_len = top + 1; + __getopt_nonoption_flags = new_str; + } + } +#endif + + while (top > middle && middle > bottom) + { + if (top - middle > middle - bottom) + { + /* Bottom segment is the short one. */ + int len = middle - bottom; + register int i; + + /* Swap it with the top part of the top segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[top - (middle - bottom) + i]; + argv[top - (middle - bottom) + i] = tem; + SWAP_FLAGS(bottom + i, top - (middle - bottom) + i); + } + /* Exclude the moved bottom segment from further swapping. */ + top -= len; + } + else + { + /* Top segment is the short one. */ + int len = top - middle; + register int i; + + /* Swap it with the bottom part of the bottom segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[middle + i]; + argv[middle + i] = tem; + SWAP_FLAGS(bottom + i, middle + i); + } + /* Exclude the moved top segment from further swapping. */ + bottom += len; + } + } + + /* Update records for the slots the non-options now occupy. */ + + first_nonopt += (optind - last_nonopt); + last_nonopt = optind; +} + +/* Initialize the internal data when the first call is made. */ + +#if defined __STDC__ && __STDC__ +static const char *_getopt_initialize(int, char *const *, const char *); +#endif +static const char * +_getopt_initialize(argc, argv, optstring) +int argc; +char *const *argv; +const char *optstring; +{ + /* Start processing options with ARGV-element 1 (since ARGV-element 0 + is the program name); the sequence of previously skipped + non-option ARGV-elements is empty. */ + + first_nonopt = last_nonopt = optind; + + nextchar = NULL; + + posixly_correct = getenv("POSIXLY_CORRECT"); + + /* Determine how to handle the ordering of options and nonoptions. */ + + if (optstring[0] == '-') + { + ordering = RETURN_IN_ORDER; + ++optstring; + } + else if (optstring[0] == '+') + { + ordering = REQUIRE_ORDER; + ++optstring; + } + else if (posixly_correct != NULL) + ordering = REQUIRE_ORDER; + else + ordering = PERMUTE; + +#if defined _LIBC && defined USE_NONOPTION_FLAGS + if (posixly_correct == NULL + && argc == __libc_argc && argv == __libc_argv) + { + if (nonoption_flags_max_len == 0) + { + if (__getopt_nonoption_flags == NULL + || __getopt_nonoption_flags[0] == '\0') + nonoption_flags_max_len = -1; + else + { + const char *orig_str = __getopt_nonoption_flags; + int len = nonoption_flags_max_len = strlen(orig_str); + if (nonoption_flags_max_len < argc) + nonoption_flags_max_len = argc; + __getopt_nonoption_flags = + (char *)malloc(nonoption_flags_max_len); + if (__getopt_nonoption_flags == NULL) + nonoption_flags_max_len = -1; + else + memset(__mempcpy(__getopt_nonoption_flags, orig_str, len), + '\0', nonoption_flags_max_len - len); + } + } + nonoption_flags_len = nonoption_flags_max_len; + } + else + nonoption_flags_len = 0; +#endif + + return optstring; +} + +/* Scan elements of ARGV (whose length is ARGC) for option characters +given in OPTSTRING. + +If an element of ARGV starts with '-', and is not exactly "-" or "--", +then it is an option element. The characters of this element +(aside from the initial '-') are option characters. If `getopt' +is called repeatedly, it returns successively each of the option characters +from each of the option elements. + +If `getopt' finds another option character, it returns that character, +updating `optind' and `nextchar' so that the next call to `getopt' can +resume the scan with the following option character or ARGV-element. + +If there are no more option characters, `getopt' returns -1. +Then `optind' is the index in ARGV of the first ARGV-element +that is not an option. (The ARGV-elements have been permuted +so that those that are not options now come last.) + +OPTSTRING is a string containing the legitimate option characters. +If an option character is seen that is not listed in OPTSTRING, +return '?' after printing an error message. If you set `opterr' to +zero, the error message is suppressed but we still return '?'. + +If a char in OPTSTRING is followed by a colon, that means it wants an arg, +so the following text in the same ARGV-element, or the text of the following +ARGV-element, is returned in `optarg'. Two colons mean an option that +wants an optional arg; if there is text in the current ARGV-element, +it is returned in `optarg', otherwise `optarg' is set to zero. + +If OPTSTRING starts with `-' or `+', it requests different methods of +handling the non-option ARGV-elements. +See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. + +Long-named options begin with `--' instead of `-'. +Their names may be abbreviated as long as the abbreviation is unique +or is an exact match for some defined option. If they have an +argument, it follows the option name in the same ARGV-element, separated +from the option name by a `=', or else the in next ARGV-element. +When `getopt' finds a long-named option, it returns 0 if that option's +`flag' field is nonzero, the value of the option's `val' field +if the `flag' field is zero. + +The elements of ARGV aren't really const, because we permute them. +But we pretend they're const in the prototype to be compatible +with other systems. + +LONGOPTS is a vector of `struct option' terminated by an +element containing a name which is zero. + +LONGIND returns the index in LONGOPT of the long-named option found. +It is only valid when a long-named option has been found by the most +recent call. + +If LONG_ONLY is nonzero, '-' as well as '--' can introduce +long-named options. */ + +int +_getopt_internal(argc, argv, optstring, longopts, longind, long_only) +int argc; +char *const *argv; +const char *optstring; +const struct option *longopts; +int *longind; +int long_only; +{ + int print_errors = opterr; + if (optstring[0] == ':') + print_errors = 0; + + if (argc < 1) + return -1; + + optarg = NULL; + + if (optind == 0 || !__getopt_initialized) + { + if (optind == 0) + optind = 1; /* Don't scan ARGV[0], the program name. */ + optstring = _getopt_initialize(argc, argv, optstring); + __getopt_initialized = 1; + } + + /* Test whether ARGV[optind] points to a non-option argument. + Either it does not have option syntax, or there is an environment flag + from the shell indicating it is not an option. The later information + is only used when the used in the GNU libc. */ +#if defined _LIBC && defined USE_NONOPTION_FLAGS +# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ + || (optind < nonoption_flags_len \ + && __getopt_nonoption_flags[optind] == '1')) +#else +# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') +#endif + + if (nextchar == NULL || *nextchar == '\0') + { + /* Advance to the next ARGV-element. */ + + /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been + moved back by the user (who may also have changed the arguments). */ + if (last_nonopt > optind) + last_nonopt = optind; + if (first_nonopt > optind) + first_nonopt = optind; + + if (ordering == PERMUTE) + { + /* If we have just processed some options following some non-options, + exchange them so that the options come first. */ + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange((char **)argv); + else if (last_nonopt != optind) + first_nonopt = optind; + + /* Skip any additional non-options + and extend the range of non-options previously skipped. */ + + while (optind < argc && NONOPTION_P) + optind++; + last_nonopt = optind; + } + + /* The special ARGV-element `--' means premature end of options. + Skip it like a null option, + then exchange with previous non-options as if it were an option, + then skip everything else like a non-option. */ + + if (optind != argc && !strcmp(argv[optind], "--")) + { + optind++; + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange((char **)argv); + else if (first_nonopt == last_nonopt) + first_nonopt = optind; + last_nonopt = argc; + + optind = argc; + } + + /* If we have done all the ARGV-elements, stop the scan + and back over any non-options that we skipped and permuted. */ + + if (optind == argc) + { + /* Set the next-arg-index to point at the non-options + that we previously skipped, so the caller will digest them. */ + if (first_nonopt != last_nonopt) + optind = first_nonopt; + return -1; + } + + /* If we have come to a non-option and did not permute it, + either stop the scan or describe it to the caller and pass it by. */ + + if (NONOPTION_P) + { + if (ordering == REQUIRE_ORDER) + return -1; + optarg = argv[optind++]; + return 1; + } + + /* We have found another option-ARGV-element. + Skip the initial punctuation. */ + + nextchar = (argv[optind] + 1 + + (longopts != NULL && argv[optind][1] == '-')); + } + + /* Decode the current option-ARGV-element. */ + + /* Check whether the ARGV-element is a long option. + + If long_only and the ARGV-element has the form "-f", where f is + a valid short option, don't consider it an abbreviated form of + a long option that starts with f. Otherwise there would be no + way to give the -f short option. + + On the other hand, if there's a long option "fubar" and + the ARGV-element is "-fu", do consider that an abbreviation of + the long option, just like "--fu", and not "-f" with arg "u". + + This distinction seems to be the most useful approach. */ + + if (longopts != NULL + && (argv[optind][1] == '-' + || (long_only && (argv[optind][2] || !my_index(optstring, argv[optind][1]))))) + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = -1; + int option_index; + + for (nameend = nextchar; *nameend && *nameend != '='; nameend++) + /* Do nothing. */; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp(p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int)(nameend - nextchar) + == (unsigned int)strlen(p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else if (long_only + || pfound->has_arg != p->has_arg + || pfound->flag != p->flag + || pfound->val != p->val) + /* Second or later nonexact match found. */ + ambig = 1; + } + + if (ambig && !exact) + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf(&buf, _("%s: option `%s' is ambiguous\n"), + argv[0], argv[optind]); + + if (_IO_fwide(stderr, 0) > 0) + __fwprintf(stderr, L"%s", buf); + else + fputs(buf, stderr); + + free(buf); +#else + fprintf(stderr, _("%s: option `%s' is ambiguous\n"), + argv[0], argv[optind]); +#endif + } + nextchar += strlen(nextchar); + optind++; + optopt = 0; + return '?'; + } + + if (pfound != NULL) + { + option_index = indfound; + optind++; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + optarg = nameend + 1; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; +#endif + + if (argv[optind - 1][1] == '-') + { + /* --option */ +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf(&buf, _("\ + %s: option `--%s' doesn't allow an argument\n"), + argv[0], pfound->name); +#else + fprintf(stderr, _("\ + %s: option `--%s' doesn't allow an argument\n"), + argv[0], pfound->name); +#endif + } + else + { + /* +option or -option */ +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf(&buf, _("\ + %s: option `%c%s' doesn't allow an argument\n"), + argv[0], argv[optind - 1][0], + pfound->name); +#else + fprintf(stderr, _("\ + %s: option `%c%s' doesn't allow an argument\n"), + argv[0], argv[optind - 1][0], pfound->name); +#endif + } + +#if defined _LIBC && defined USE_IN_LIBIO + if (_IO_fwide(stderr, 0) > 0) + __fwprintf(stderr, L"%s", buf); + else + fputs(buf, stderr); + + free(buf); +#endif + } + + nextchar += strlen(nextchar); + + optopt = pfound->val; + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (optind < argc) + optarg = argv[optind++]; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf(&buf, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[optind - 1]); + + if (_IO_fwide(stderr, 0) > 0) + __fwprintf(stderr, L"%s", buf); + else + fputs(buf, stderr); + + free(buf); +#else + fprintf(stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[optind - 1]); +#endif + } + nextchar += strlen(nextchar); + optopt = pfound->val; + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen(nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + + /* Can't find it as a long option. If this is not getopt_long_only, + or the option starts with '--' or is not a valid short + option, then it's an error. + Otherwise interpret it as a short option. */ + if (!long_only || argv[optind][1] == '-' + || my_index(optstring, *nextchar) == NULL) + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; +#endif + + if (argv[optind][1] == '-') + { + /* --option */ +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf(&buf, _("%s: unrecognized option `--%s'\n"), + argv[0], nextchar); +#else + fprintf(stderr, _("%s: unrecognized option `--%s'\n"), + argv[0], nextchar); +#endif + } + else + { + /* +option or -option */ +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf(&buf, _("%s: unrecognized option `%c%s'\n"), + argv[0], argv[optind][0], nextchar); +#else + fprintf(stderr, _("%s: unrecognized option `%c%s'\n"), + argv[0], argv[optind][0], nextchar); +#endif + } + +#if defined _LIBC && defined USE_IN_LIBIO + if (_IO_fwide(stderr, 0) > 0) + __fwprintf(stderr, L"%s", buf); + else + fputs(buf, stderr); + + free(buf); +#endif + } + nextchar = (char *) ""; + optind++; + optopt = 0; + return '?'; + } + } + + /* Look at and handle the next short option-character. */ + + { + char c = *nextchar++; + char *temp = my_index(optstring, c); + + /* Increment `optind' when we start to process its last character. */ + if (*nextchar == '\0') + ++optind; + + if (temp == NULL || c == ':') + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; +#endif + + if (posixly_correct) + { + /* 1003.2 specifies the format of this message. */ +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf(&buf, _("%s: illegal option -- %c\n"), + argv[0], c); +#else + fprintf(stderr, _("%s: illegal option -- %c\n"), argv[0], c); +#endif + } + else + { +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf(&buf, _("%s: invalid option -- %c\n"), + argv[0], c); +#else + fprintf(stderr, _("%s: invalid option -- %c\n"), argv[0], c); +#endif + } + +#if defined _LIBC && defined USE_IN_LIBIO + if (_IO_fwide(stderr, 0) > 0) + __fwprintf(stderr, L"%s", buf); + else + fputs(buf, stderr); + + free(buf); +#endif + } + optopt = c; + return '?'; + } + /* Convenience. Treat POSIX -W foo same as long option --foo */ + if (temp[0] == 'W' && temp[1] == ';') + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = 0; + int option_index; + + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (print_errors) + { + /* 1003.2 specifies the format of this message. */ +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf(&buf, _("%s: option requires an argument -- %c\n"), + argv[0], c); + + if (_IO_fwide(stderr, 0) > 0) + __fwprintf(stderr, L"%s", buf); + else + fputs(buf, stderr); + + free(buf); +#else + fprintf(stderr, _("%s: option requires an argument -- %c\n"), + argv[0], c); +#endif + } + optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + return c; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + + /* optarg is now the argument, see if it's in the + table of longopts. */ + + for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) + /* Do nothing. */; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp(p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int)(nameend - nextchar) == strlen(p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + if (ambig && !exact) + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf(&buf, _("%s: option `-W %s' is ambiguous\n"), + argv[0], argv[optind]); + + if (_IO_fwide(stderr, 0) > 0) + __fwprintf(stderr, L"%s", buf); + else + fputs(buf, stderr); + + free(buf); +#else + fprintf(stderr, _("%s: option `-W %s' is ambiguous\n"), + argv[0], argv[optind]); +#endif + } + nextchar += strlen(nextchar); + optind++; + return '?'; + } + if (pfound != NULL) + { + option_index = indfound; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + optarg = nameend + 1; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf(&buf, _("\ + %s: option `-W %s' doesn't allow an argument\n"), + argv[0], pfound->name); + + if (_IO_fwide(stderr, 0) > 0) + __fwprintf(stderr, L"%s", buf); + else + fputs(buf, stderr); + + free(buf); +#else + fprintf(stderr, _("\ + %s: option `-W %s' doesn't allow an argument\n"), + argv[0], pfound->name); +#endif + } + + nextchar += strlen(nextchar); + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (optind < argc) + optarg = argv[optind++]; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf(&buf, _("\ + %s: option `%s' requires an argument\n"), + argv[0], argv[optind - 1]); + + if (_IO_fwide(stderr, 0) > 0) + __fwprintf(stderr, L"%s", buf); + else + fputs(buf, stderr); + + free(buf); +#else + fprintf(stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[optind - 1]); +#endif + } + nextchar += strlen(nextchar); + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen(nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + nextchar = NULL; + return 'W'; /* Let the application handle it. */ + } + if (temp[1] == ':') + { + if (temp[2] == ':') + { + /* This is an option that accepts an argument optionally. */ + if (*nextchar != '\0') + { + optarg = nextchar; + optind++; + } + else + optarg = NULL; + nextchar = NULL; + } + else + { + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (print_errors) + { + /* 1003.2 specifies the format of this message. */ +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf(&buf, + _("%s: option requires an argument -- %c\n"), + argv[0], c); + + if (_IO_fwide(stderr, 0) > 0) + __fwprintf(stderr, L"%s", buf); + else + fputs(buf, stderr); + + free(buf); +#else + fprintf(stderr, + _("%s: option requires an argument -- %c\n"), + argv[0], c); +#endif + } + optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + nextchar = NULL; + } + } + return c; + } +} + +int +getopt(argc, argv, optstring) +int argc; +char *const *argv; +const char *optstring; +{ + return _getopt_internal(argc, argv, optstring, + (const struct option *) 0, + (int *)0, + 0); +} + + + + +int +getopt_long(int argc, char *const *argv, const char *options, +const struct option *long_options, int *opt_index) +{ + return _getopt_internal(argc, argv, options, long_options, opt_index, 0, 0); +} + +int +getopt_long_only(int argc, char *const *argv, const char *options, +const struct option *long_options, int *opt_index) +{ + return _getopt_internal(argc, argv, options, long_options, opt_index, 1, 0); +} + + + + + +#endif /* Not ELIDE_CODE. */ + +#ifdef TEST + +/* Compile with -DTEST to make an executable for use in testing +the above definition of `getopt'. */ + +int +main(argc, argv) +int argc; +char **argv; +{ + int c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = optind ? optind : 1; + + c = getopt(argc, argv, "abc:d:0123456789"); + if (c == -1) + break; + + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf("digits occur in two different argv-elements.\n"); + digit_optind = this_option_optind; + printf("option %c\n", c); + break; + + case 'a': + printf("option a\n"); + break; + + case 'b': + printf("option b\n"); + break; + + case 'c': + printf("option c with value `%s'\n", optarg); + break; + + case '?': + break; + + default: + printf("?? getopt returned character code 0%o ??\n", c); + } + } + + if (optind < argc) + { + printf("non-option ARGV-elements: "); + while (optind < argc) + printf("%s ", argv[optind++]); + printf("\n"); + } + + exit(0); +} + +#endif /* TEST */ diff --git a/src/keepalive.c b/src/keepalive.c index 961e360..e89b0c2 100644 --- a/src/keepalive.c +++ b/src/keepalive.c @@ -110,7 +110,7 @@ int keepalive_1(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsig memset(keepalive_1_packet, 0, 42); keepalive_1_packet[0] = 0xff; int MD5A_len = 6 + strlen(drcom_config.password); - unsigned char MD5A_str[MD5A_len]; + unsigned char* MD5A_str = (unsigned char*) malloc(MD5A_len); MD5A_str[0] = 0x03; MD5A_str[1] = 0x01; memcpy(MD5A_str + 2, seed, 4); @@ -163,6 +163,7 @@ int keepalive_1(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsig } } } + free(MD5A_str); } return 0; diff --git a/src/main.c b/src/main.c index 49561fa..d297d37 100644 --- a/src/main.c +++ b/src/main.c @@ -1,4 +1,3 @@ -#include #include #include #include @@ -7,11 +6,17 @@ #ifdef linux #include -#include "daemon.h> +#include "daemon.h" #include "eapol.h" #include #endif +#ifdef _MSC_VER +#include +#else +#include +#endif + #define VERSION "1.6.2" void print_help(int exval); From cf46a7d4f2c4fcd146b0265fca995c70f45a0449 Mon Sep 17 00:00:00 2001 From: yizhou Date: Thu, 11 May 2023 01:50:22 +0800 Subject: [PATCH 04/14] add github workflow --- .github/workflow/action.yaml | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 .github/workflow/action.yaml diff --git a/.github/workflow/action.yaml b/.github/workflow/action.yaml new file mode 100644 index 0000000..de8f9ff --- /dev/null +++ b/.github/workflow/action.yaml @@ -0,0 +1,32 @@ +name: "dogcom" + +on: + push: + branchies: + - "main" + +jobs: + build: + runs-on: ${{ matrix.config.os }} + strategy: + matrix: + config: + - os: ubuntu-latest + triplet: x64-linux + - os: windows-latest + triplet: x64-windows + + steps: + - uses: lukka/get-cmake@latest + + - name: Checkout + uses: actions/checkout@v3 + + - name: Build + run: mkdir build && cd build + cmake .. -DCMAKE_BUILD_TYPE=Release + + - name: Release + uses: softprops/action-gh-release@v1 + with: + files: dogcom, dogcom.exe From c4a87ae68cf466b61bd8467fad5dfc225abbc44b Mon Sep 17 00:00:00 2001 From: yizhou Date: Thu, 11 May 2023 01:50:59 +0800 Subject: [PATCH 05/14] add github workflow --- .github/workflow/action.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflow/action.yaml b/.github/workflow/action.yaml index de8f9ff..d8aee96 100644 --- a/.github/workflow/action.yaml +++ b/.github/workflow/action.yaml @@ -3,7 +3,7 @@ name: "dogcom" on: push: branchies: - - "main" + - "master" jobs: build: From d6e62b2c2e9da2a1e557f6a1c509a30ab3cdc456 Mon Sep 17 00:00:00 2001 From: Don Yihtseu <89072149+tsurumi-yizhou@users.noreply.github.com> Date: Thu, 11 May 2023 01:54:47 +0800 Subject: [PATCH 06/14] Create cmake.yml --- .github/workflows/cmake.yml | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 .github/workflows/cmake.yml diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml new file mode 100644 index 0000000..6954df0 --- /dev/null +++ b/.github/workflows/cmake.yml @@ -0,0 +1,36 @@ +name: CMake + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + +env: + # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) + BUILD_TYPE: Release + +jobs: + build: + # The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac. + # You can convert this to a matrix build if you need cross-platform coverage. + # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix + runs-on: ubuntu-latest, windows-latest + + steps: + - uses: actions/checkout@v3 + + - name: Configure CMake + # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. + # See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} + + - name: Build + # Build your program with the given configuration + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} + + - name: Release + uses: softprops/action-gh-release@v1 + with: + files: ${{github.workspace}}/build/dogcom, ${{github.workspace}}/build/dogcom.exe + From 67e19010eacb6138baa9add2ca80de51588c6e90 Mon Sep 17 00:00:00 2001 From: yizhou Date: Thu, 11 May 2023 12:14:15 +0800 Subject: [PATCH 07/14] delete useless files --- .github/workflow/action.yaml | 32 -------------------------------- 1 file changed, 32 deletions(-) delete mode 100644 .github/workflow/action.yaml diff --git a/.github/workflow/action.yaml b/.github/workflow/action.yaml deleted file mode 100644 index d8aee96..0000000 --- a/.github/workflow/action.yaml +++ /dev/null @@ -1,32 +0,0 @@ -name: "dogcom" - -on: - push: - branchies: - - "master" - -jobs: - build: - runs-on: ${{ matrix.config.os }} - strategy: - matrix: - config: - - os: ubuntu-latest - triplet: x64-linux - - os: windows-latest - triplet: x64-windows - - steps: - - uses: lukka/get-cmake@latest - - - name: Checkout - uses: actions/checkout@v3 - - - name: Build - run: mkdir build && cd build - cmake .. -DCMAKE_BUILD_TYPE=Release - - - name: Release - uses: softprops/action-gh-release@v1 - with: - files: dogcom, dogcom.exe From 012de40b475e238da358fc08e4ceb0bb0605ff76 Mon Sep 17 00:00:00 2001 From: yizhou Date: Thu, 11 Apr 2024 02:46:40 +0800 Subject: [PATCH 08/14] refactor: from c to cpp --- .github/workflows/clang.yml | 23 + .github/workflows/cmake.yml | 36 - .github/workflows/gcc.yml | 25 + .github/workflows/msvc.yml | 23 + .gitignore | 64 +- .travis.yml | 16 - CMakeLists.txt | 23 +- README.md | 56 +- include/auth.h | 33 - include/client.hpp | 42 ++ include/common.h | 161 ----- include/config.hpp | 32 + include/configparse.h | 36 - include/daemon.h | 11 - include/debug.h | 7 - include/eapol.h | 119 ---- include/keepalive.h | 9 - include/libs/getopt4win.h | 193 ------ include/libs/md4.h | 47 -- include/libs/md5.h | 47 -- include/libs/sha1.h | 24 - include/utils.hpp | 17 + src/auth.c | 775 --------------------- src/client.cpp | 12 + src/common.c | 329 --------- src/config.cpp | 4 + src/configparse.c | 181 ----- src/daemon.c | 98 --- src/dhcp.cpp | 105 +++ src/eapol.c | 500 -------------- src/eapol.cpp | 21 + src/getopt4win.c | 1274 ----------------------------------- src/keepalive.c | 406 ----------- src/keepalive.cpp | 17 + src/main.c | 209 ------ src/main.cpp | 9 + src/md4.c | 277 -------- src/md5.c | 298 -------- src/pppoe.cpp | 17 + src/sha1.c | 203 ------ src/utils.cpp | 45 ++ vcpkg.json | 8 + 42 files changed, 421 insertions(+), 5411 deletions(-) create mode 100644 .github/workflows/clang.yml delete mode 100644 .github/workflows/cmake.yml create mode 100644 .github/workflows/gcc.yml create mode 100644 .github/workflows/msvc.yml delete mode 100644 .travis.yml delete mode 100644 include/auth.h create mode 100644 include/client.hpp delete mode 100644 include/common.h create mode 100644 include/config.hpp delete mode 100644 include/configparse.h delete mode 100644 include/daemon.h delete mode 100644 include/debug.h delete mode 100644 include/eapol.h delete mode 100644 include/keepalive.h delete mode 100644 include/libs/getopt4win.h delete mode 100644 include/libs/md4.h delete mode 100644 include/libs/md5.h delete mode 100644 include/libs/sha1.h create mode 100644 include/utils.hpp delete mode 100644 src/auth.c create mode 100644 src/client.cpp delete mode 100644 src/common.c create mode 100644 src/config.cpp delete mode 100644 src/configparse.c delete mode 100644 src/daemon.c create mode 100644 src/dhcp.cpp delete mode 100644 src/eapol.c create mode 100644 src/eapol.cpp delete mode 100644 src/getopt4win.c delete mode 100644 src/keepalive.c create mode 100644 src/keepalive.cpp delete mode 100644 src/main.c create mode 100644 src/main.cpp delete mode 100644 src/md4.c delete mode 100644 src/md5.c create mode 100644 src/pppoe.cpp delete mode 100644 src/sha1.c create mode 100644 src/utils.cpp create mode 100644 vcpkg.json diff --git a/.github/workflows/clang.yml b/.github/workflows/clang.yml new file mode 100644 index 0000000..28f97c5 --- /dev/null +++ b/.github/workflows/clang.yml @@ -0,0 +1,23 @@ +name: Clang + +on: + push: + branches: + - master + +jobs: + build: + runs-on: macos-latest + steps: + - uses: action/checkout@v4.1.2 + + - uses: KyleMayes/install-llvm-action@v2 + with: + version: "17.0.0" + arch: "arm64" + + - uses: threeal/cmake-action@main + with: + generator: Ninja + c-compiler: clang + cxx-compiler: clang++ \ No newline at end of file diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml deleted file mode 100644 index 6954df0..0000000 --- a/.github/workflows/cmake.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: CMake - -on: - push: - branches: [ "master" ] - pull_request: - branches: [ "master" ] - -env: - # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) - BUILD_TYPE: Release - -jobs: - build: - # The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac. - # You can convert this to a matrix build if you need cross-platform coverage. - # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix - runs-on: ubuntu-latest, windows-latest - - steps: - - uses: actions/checkout@v3 - - - name: Configure CMake - # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. - # See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type - run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} - - - name: Build - # Build your program with the given configuration - run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} - - - name: Release - uses: softprops/action-gh-release@v1 - with: - files: ${{github.workspace}}/build/dogcom, ${{github.workspace}}/build/dogcom.exe - diff --git a/.github/workflows/gcc.yml b/.github/workflows/gcc.yml new file mode 100644 index 0000000..7c6df7f --- /dev/null +++ b/.github/workflows/gcc.yml @@ -0,0 +1,25 @@ +name: GCC + +on: + push: + branches: + - master + + +jobs: + build: + runs-on: + ubuntu-latest + steps: + - uses: action/checkout@4.1.2 + + - uses: egor-tensin/setup-gcc@v1 + with: + version: latest + platform: x64 + + - uses: threeal/cmake-action@main + with: + generator: Ninja + c-compiler: gcc + cxx-compiler: g++ \ No newline at end of file diff --git a/.github/workflows/msvc.yml b/.github/workflows/msvc.yml new file mode 100644 index 0000000..5a807bf --- /dev/null +++ b/.github/workflows/msvc.yml @@ -0,0 +1,23 @@ +name: MSVC + +on: + push: + branches: + - master + +jobs: + build: + runs-on: windows-latest + + steps: + - uses: actions/checkout@v4.1.2 + + - uses: TheMrMilchmann/setup-msvc-dev@v3 + with: + arch: x64 + + - uses: threeal/cmake-action@main + with: + generator: Ninja + c-compiler: cl + cxx-compiler: cl \ No newline at end of file diff --git a/.gitignore b/.gitignore index 905432f..5a6e616 100644 --- a/.gitignore +++ b/.gitignore @@ -1,61 +1,11 @@ -test -drcom.conf -test.conf -dogcom -main -.vscode +out/ build/ -# Prerequisites -*.d -.DS_Store -.idea/ - -# Object files -*.o -*.ko -*.obj -*.elf - -# Linker output -*.ilk -*.map -*.exp - -# Precompiled Headers -*.gch -*.pch -# Libraries -*.lib -*.a -*.la -*.lo - -# Shared objects (inc. Windows DLLs) -*.dll -*.so -*.so.* -*.dylib - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex +.idea/ +.vscode/ +.vs/ -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb +.DS_Store +*/.DS_Store -# Kernel Module Compile Results -*.mod* -*.cmd -modules.order -Module.symvers -Mkfile.old -dkms.conf -*.stackdump +*/*.c \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 23f947a..0000000 --- a/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: c -os: - - linux - - osx -compiler: - - gcc - - clang - -script: - - make test=y - - ./dogcom -m dhcp -c sample-d.conf - - ./dogcom -m pppoe -c sample-p.conf - -branches: - only: - - master \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 6a48f2a..14e5c25 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,18 +1,15 @@ -cmake_minimum_required(VERSION 3.0.0) +cmake_minimum_required(VERSION 3.28.0) project(dogcom) -set(CMAKE_C_STANDARD_REQUIRED 99) -set(FORCE_ENCRYPT OFF) +set(CMAKE_CXX_STANDARD 23) +set(CMAKE_CXX_STANDARD_REQUIRED ON) -file(GLOB_RECURSE SRCS "src/*.c" "include/*.h") -include_directories(${PROJECT_SOURCE_DIR}/include) +include_directories(include) +file(GLOB_RECURSE SOURCE src/*.cpp) +add_executable(${PROJECT_NAME} ${SOURCE}) -if (${FORCE_ENCRYPT}) - add_compile_definitions(FORCE_ENCRYPT) -endif () +find_package(Boost REQUIRED system log) +target_link_libraries(${PROJECT_NAME} PRIVATE Boost::boost Boost::system Boost::log) -add_executable(dogcom ${SRCS}) - -if (CMAKE_SYSTEM_NAME STREQUAL "Windows") - target_link_libraries(dogcom PRIVATE ws2_32) -endif () +find_package(cryptopp CONFIG REQUIRED) +target_link_libraries(${PROJECT_NAME} PRIVATE cryptopp::cryptopp) \ No newline at end of file diff --git a/README.md b/README.md index 857dc00..cceedf9 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,13 @@ -# dogcom [![travis-ci](https://travis-ci.org/mchome/dogcom.svg "Build status")](https://travis-ci.org/mchome/dogcom) [![badge](https://img.shields.io/badge/%20built%20with-%20%E2%9D%A4-ff69b4.svg "build with love")](https://github.com/mchome/dogcom) [![version](https://img.shields.io/badge/stable%20-%20v1.6.2-4dc71f.svg "stable version")](https://github.com/mchome/dogcom/tree/v1.6.2) +# dogcom -[Drcom-generic](https://github.com/drcoms/drcom-generic) implementation in C. - -``` -Usage: - dogcom -m -c [options ]... - -Options: - --mode , -m set your dogcom mode - --conf , -c import configuration file - --bindip , -b bind your ip address(default is 0.0.0.0) - --log , -l specify log file - --802.1x, -x enable 802.1x - --daemon, -d set daemon flag - --eternal, -e set eternal flag - --verbose, -v set verbose flag - --help, -h display this help -``` - -Config file is compatible with [drcom-generic](https://github.com/drcoms/drcom-generic). - -#### Example: - -```bash -$ dogcom -m dhcp -c dogcom.conf -$ dogcom -m dhcp -c dogcom.conf -l /tmp/dogcom.log -v -$ dogcom -m dhcp -c dogcom.conf -d # (PS: only on Linux build) -$ dogcom -m pppoe -c dogcom.conf -x # (PS: only on Linux build) -$ dogcom -m pppoe -c dogcom.conf -e # eternal dogcoming (default times is 5) -$ dogcom -m pppoe -c dogcom.conf -v -$ dogcom -m dhcp -c dogcom.conf -b 10.2.3.12 -v -``` - -#### To build: - -Dogcom use cmake for building. - -CMake will detect your platform and compiler, then decide how to compile. - -If you want force-encrypt, you should add -```cmake -set(FORCE_ENCRYPT ON) -``` -in CMakeLists.txt - -#### Openwrt-package -[https://github.com/mchome/openwrt-dogcom](https://github.com/mchome/openwrt-dogcom) - -#### Tutorial -[![asciicast](https://asciinema.org/a/9j7cj1s61jiczx2s0206tosjr.png)](https://asciinema.org/a/9j7cj1s61jiczx2s0206tosjr) +![MSVC on Win](https://github.com/tsurumi-yizhou/dogcom/actions/workflows/msvc.yml/badge.svg) +![GCC on Linux](https://github.com/tsurumi-yizhou/dogcom/actions/workflows/gcc.yml/badge.svg) +![LLVM on OSX](https://github.com/tsurumi-yizhou/dogcom/actions/workflows/clang.yml/badge.svg) ### Thanks: - [gdut-drcom](https://github.com/chenhaowen01/gdut-drcom 'chenhaowen01') - [jlu-drcom-client](https://github.com/drcoms/jlu-drcom-client/tree/master/C-version 'feix') - [leetking](https://github.com/leetking 'leetking') - -### Special thanks: - [Drcom-generic](https://github.com/drcoms/drcom-generic 'ly0') ### License: diff --git a/include/auth.h b/include/auth.h deleted file mode 100644 index 6623602..0000000 --- a/include/auth.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef AUTH_H_ -#define AUTH_H_ - -#ifdef WIN32 -#include -#else -#include -#endif - -enum { - CHECK_MAC = 0x01, - SERVER_BUSY = 0x02, - WRONG_PASS = 0x03, - NOT_ENOUGH = 0x04, - FREEZE_UP = 0x05, - NOT_ON_THIS_IP = 0x07, - NOT_ON_THIS_MAC = 0x0B, - TOO_MUCH_IP = 0x14, - UPDATE_CLIENT = 0x15, - NOT_ON_THIS_IP_MAC = 0x16, - MUST_USE_DHCP = 0x17 -}; - -int dhcp_challenge(int sockfd, struct sockaddr_in addr, unsigned char seed[]); -int dhcp_login(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsigned char auth_information[], int try_JLUversion); -int pppoe_challenge(int sockfd, struct sockaddr_in addr, int *pppoe_counter, unsigned char seed[], unsigned char sip[], int *encrypt_mode); -int pppoe_login(int sockfd, struct sockaddr_in addr, int *pppoe_counter, unsigned char seed[], unsigned char sip[], int *first, int *encrypt_mode, int *encrypt_type); -int dogcom(int try_times); -void print_packet(char msg[10], unsigned char *packet, int length); -void logging(char msg[10], unsigned char *packet, int length); -void get_lasterror(char *msg); - -#endif // AUTH_H_ \ No newline at end of file diff --git a/include/client.hpp b/include/client.hpp new file mode 100644 index 0000000..c4691dc --- /dev/null +++ b/include/client.hpp @@ -0,0 +1,42 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// + +#ifndef DOGCOM_HPP +#define DOGCOM_HPP +#include +#include +#include +#include +#include + +using boost::asio::io_service; +using boost::asio::awaitable; +using boost::asio::ip::tcp; + +namespace dogcom { + +class client_t : std::enable_shared_from_this { + config_t config; + io_service service; + tcp::socket socket; + bool is_jlu_mode; + std::string seed; + +public: + client_t(const client_t&) = delete; + explicit client_t(const config_t& info); + awaitable dhcp_challenge(); + awaitable dhcp_login(); + awaitable pppoe_challenge(); + awaitable pppoe_login(); + awaitable keepalive1(); + awaitable keepalive2(); + awaitable eap_login(); + awaitable eap_fresh(); + awaitable eap_set_ifname(); +}; + +} + +#endif //DOGCOM_HPP diff --git a/include/common.h b/include/common.h deleted file mode 100644 index 2820579..0000000 --- a/include/common.h +++ /dev/null @@ -1,161 +0,0 @@ -#ifndef COMMON_H__ -#define COMMON_H__ -/* - * 通用的代码和定义 - */ -typedef unsigned char uchar; /* 一个字节 */ -typedef unsigned short uint16; /* 两个字节 */ -typedef unsigned int uint32; /* 四个字节 */ - -/* 用户名和密码长度 */ -#define UNAME_LEN (32) -#define PWD_LEN (32) - -#define FORMAT_TIME_MAX (64) - -// #ifdef LINUX -#include -#include -#include -#include -#define EXE_PATH_MAX (PATH_MAX+1) -// #elif WIN32 -// # include -// # define ETH_ALEN (6) -// # define IF_NAMSIZE (64) -// # define MTU_MAX (65536) -// # define EXE_PATH_MAX (MAX_PATH+1) -// # define IFDESCSIZ (126) -// #endif - -typedef struct { - char name[IF_NAMESIZE]; /* linux下是eth0, windows采用的是注册表类似的(\Device\NPF_{xxxx-xxx-xx-xx-xxx}) */ -// #ifdef WIN32 -// char desc[IFDESCSIZ]; /* windows下描述(AMD PCNET Family PCI Ethernet Adapter) */ -// #endif -}iflist_t; - - -#undef ARRAY_SIZE -#define ARRAY_SIZE(arr) (sizeof(arr)/sizeof(arr[0])) - -#define MAX(x, y) ((x)>(y)?(x):(y)) -#define MIN(x, y) ((x)>(y)?(y):(x)) - -#undef PRINT -#ifdef GUI -# include -# define PRINT(...) g_print(__VA_ARGS__) -#else -# include -# define PRINT(...) fprintf(stderr, __VA_ARGS__) -#endif - -#ifdef DEBUG -# define _D(...) \ - do { \ - PRINT("%s:%s:%d:", format_time(), __FILE__, __LINE__); \ - PRINT(__VA_ARGS__); \ - } while(0) -#else -# define _D(...) ((void)0) -#endif - -#define _M(...) PRINT(__VA_ARGS__); - -/* - * 获取程序所在的实际绝对路径的目录 - * exedir: 返回目录,加上\0一起长度是EXE_PATH_MAX, - * 如果本上长度达到了EXE_PATH_MAX(不包括\0),那么也会返回失败 - * @return: 0: 成功 - * !0: 失败 - */ -extern int getexedir(char *exedir); -/* - * 比较两个mac是否相同 - * @return: 0: 不同 - * !0: 相同 - */ -extern int mac_equal(uchar const *mac1, uchar const *mac2); - -/* - * 判断两个ip是否相等 - * type: AF_INET or AF_INET6, 分别对应ipv4,ipv6 - * ip1, ip2: 比较的两个ip,同为struct in_addr或struct in6_addr的指针 - * @return: 0: 不同 - * !0: 相同 - */ -extern int ip_equal(int type, void const *ip1, void const *ip2); - -/* - * 获取所有网络接口 - * ifnames 实际获取的接口 - * cnt 两个作用,1:传入表示ifnames最多可以存储的接口个数 - * 2:返回表示实际获取了的接口个数 - * 返回接口个数在cnt里 - * @return: >=0 成功,实际获取的接口个数 - * -1 获取失败 - * -2 cnt过小 - */ -extern int getall_ifs(iflist_t *ifs, int *cnt); -/* - * 获取当前时间按照 - * yyyy-MM-dd HH:mm:ss - * 格式返回 - * NOTE 不要去修改返回结果,并且不是线程安全的 - * @return: NULL: 失败 - * !NULL: 存储的结果 - */ -extern char const *format_time(void); -/* - * 简单的复制文件,暂时不进行细致错误检查 - * NOTE 是绝对路径 - * scr: 源文件 - * dst: 目标文件 - * @return: 0: 成功 - * -1: 失败 - */ -extern int copy(char const *src, char const *dst); - -/* - * 字节序转换相关函数 - * host to lsb/msb short/long (host->l/m) - * lsb/msb to host short/long (l/m->host) - */ -extern uint16 htols(uint16 n); -extern uint16 htoms(uint16 n); -extern uint16 ltohs(uint16 n); -extern uint16 mtohs(uint16 n); - -extern uint32 htoll(uint32 n); -extern uint32 htoml(uint32 n); -extern uint32 ltohl(uint32 n); -extern uint32 mtohl(uint32 n); - -extern uchar const *format_mac(uchar const *mac); - -/* - * 判断网络是否连通 - * ifname: 接口名字 - * @return: !0: 连通 - * 0: 没有连通 - */ -extern int isnetok(char const *ifname); -/* - * 返回t1-t0的时间差 - * 由于这里精度没必要达到ns,故返回相差微秒ms - * @return: 时间差,单位微秒(1s == 1000ms) - */ -extern long difftimespec(struct timespec t1, struct timespec t0); - -/* - * 休眠ms微秒 - */ -extern void msleep(long ms); - -/* - * 以16进制打印数据 - */ -extern void format_data(uchar const *d, size_t len); - -#endif \ No newline at end of file diff --git a/include/config.hpp b/include/config.hpp new file mode 100644 index 0000000..2105727 --- /dev/null +++ b/include/config.hpp @@ -0,0 +1,32 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// + +#ifndef CONFIG_HPP +#define CONFIG_HPP +#include +#include + +namespace dogcom { +struct config_t { + std::string server; + std::string username; + std::string password; + std::array host_addr; + std::string host_name; + std::array dns_addr; + std::string mac_addr; + std::string os_ver; + std::array dhcp_server; + char auth_ver[2]; + int ror_version; + int keepalive1_mod; + char pppoe_flag; + char CONTROLCHECKSTATUS; + char ADAPTERNUM; + char IPDOG; + unsigned char KEEP_ALIVE_VERSION[2]; +}; +} + +#endif //CONFIG_HPP diff --git a/include/configparse.h b/include/configparse.h deleted file mode 100644 index 1bd5648..0000000 --- a/include/configparse.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef CONFIGPARSE_H_ -#define CONFIGPARSE_H_ - -struct config { - char server[20]; - char username[36]; - char password[20]; - unsigned char CONTROLCHECKSTATUS; - unsigned char ADAPTERNUM; - char host_ip[20]; - unsigned char IPDOG; - char host_name[20]; - char PRIMARY_DNS[20]; - char dhcp_server[20]; - unsigned char AUTH_VERSION[2]; - unsigned char mac[6]; - char host_os[20]; - unsigned char KEEP_ALIVE_VERSION[2]; - int ror_version; - int keepalive1_mod; - unsigned char pppoe_flag; - unsigned char keep_alive2_flag; /* abandoned */ -}; - -extern struct config drcom_config; -extern int verbose_flag; -extern int logging_flag; -extern int eapol_flag; -extern int eternal_flag; -extern char *log_path; -extern char mode[10]; -extern char bind_ip[20]; - -int config_parse(char *filepath); - -#endif // CONFIGPARSE_H_ \ No newline at end of file diff --git a/include/daemon.h b/include/daemon.h deleted file mode 100644 index 0e2f764..0000000 --- a/include/daemon.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef DAEMON_H_ -#define DAEMON_H_ - -void kill_daemon(); -void signal_handler(int signal); -void daemonise(); - -extern int daemon_flag; -extern int pid_file_handle; - -#endif // DAEMON_H_ \ No newline at end of file diff --git a/include/debug.h b/include/debug.h deleted file mode 100644 index 8432293..0000000 --- a/include/debug.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifdef DEBUG -#define DEBUG_PRINT(s) printf s -#else -#define DEBUG_PRINT(s) \ - do { \ - } while (0) -#endif \ No newline at end of file diff --git a/include/eapol.h b/include/eapol.h deleted file mode 100644 index 28e6c19..0000000 --- a/include/eapol.h +++ /dev/null @@ -1,119 +0,0 @@ -#ifndef EAPOL_H__ -#define EAPOL_H__ - -#include - -#define IDEN_LEN UNAME_LEN - -#define TRY_TIMES (3) -/* 每次请求超过TIMEOUT秒,就重新请求一次 */ -#define TIMEOUT (3) -/* eap 在EAP_KPALV_TIMEOUT秒内没有回应,认为不需要心跳 */ -#define EAP_KPALV_TIMEOUT (420) /* 7分钟 */ - -/* ethii层取0x888e表示上层是8021.x */ -#define ETHII_8021X (0x888e) - -#define EAPOL_VER (0x01) -#define EAPOL_PACKET (0x00) -#define EAPOL_START (0x01) -#define EAPOL_LOGOFF (0x02) -/* 貌似请求下线的id都是这个 */ -#define EAPOL_LOGOFF_ID (255) - -#define EAP_CODE_REQ (0x01) -#define EAP_CODE_RES (0x02) -#define EAP_CODE_SUCS (0x03) -#define EAP_CODE_FAIL (0x04) -#define EAP_TYPE_IDEN (0x01) -#define EAP_TYPE_MD5 (0x04) - -#pragma pack(1) -/* ethii 帧 */ -/* 其实这个和struct ether_header是一样的结构 */ -typedef struct { - uchar dst_mac[ETH_ALEN]; - uchar src_mac[ETH_ALEN]; - uint16 type; /* 取值0x888e,表明是8021.x */ -} ethII_t; -/* eapol 帧 */ -typedef struct { - uchar ver; /* 取值0x01 */ - /* - * 0x00: eapol-packet - * 0x01: eapol-start - * 0x02: eapol-logoff - */ - uchar type; - uint16 len; -} eapol_t; -/* eap报文头 */ -typedef struct { - /* - * 0x01: request - * 0x02: response - * 0x03: success - * 0x04: failure - */ - uchar code; - uchar id; - uint16 len; - /* - * 0x01: identity - * 0x04: md5-challenge - */ - uchar type; -} eap_t; -/* 报文体 */ -#define MD5_SIZE 16 -#define STUFF_LEN (64) -typedef union { - uchar identity[IDEN_LEN]; - struct { - uchar _size; - uchar _md5value[MD5_SIZE]; - uchar _exdata[STUFF_LEN]; - } md5clg; -} eapbody_t; -#define md5size md5clg._size -#define md5value md5clg._md5value -#define md5exdata md5clg._exdata -#pragma pack() - -/* - * eap认证 - * uname: 用户名 - * pwd: 密码 - * @return: 0: 成功 - * 1: 用户不存在 - * 2: 密码错误 - * 3: 其他超时 - * 4: 服务器拒绝请求登录 - * -1: 没有找到合适网络接口 - * -2: 没有找到服务器 - */ -extern int eaplogin(char const *uname, char const *pwd); -/* - * eap下线 - */ -extern int eaplogoff(void); -/* - * eap重新登录 - */ -extern int eaprefresh(char const *uname, char const *pwd); -/* - * 用来设置ifname - */ -extern void setifname(char const *ifname); -// #ifdef WIN32 -/* - * 由于windows下实现进程的特殊性,这里把eap_daemon导出给main_cli使用 - * ifname: 心跳的物理接口名字 - * @return: 0: keep alive 进程正常退出,也许并不需要心跳进程 - * !0: 错误原因导致keep alive 进程退出,也许是没法创建进程 - */ -// extern int eap_daemon(char const *ifname); -// #endif /* WINDOWS */ -#undef IDEN_LEN - -#endif diff --git a/include/keepalive.h b/include/keepalive.h deleted file mode 100644 index df6c801..0000000 --- a/include/keepalive.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef KEEPALIVE_H_ -#define KEEPALIVE_H_ - -int keepalive_1(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsigned char auth_information[]); -int keepalive_2(int sockfd, struct sockaddr_in addr, int *keepalive_counter, int *first, int *encrypt_type); -void gen_crc(unsigned char seed[], int encrypt_type, unsigned char crc[]); -void keepalive_2_packetbuilder(unsigned char keepalive_2_packet[], int keepalive_counter, int filepacket, int type, int encrypt_type); - -#endif // KEEPALIVE_H_ \ No newline at end of file diff --git a/include/libs/getopt4win.h b/include/libs/getopt4win.h deleted file mode 100644 index 6e2fa27..0000000 --- a/include/libs/getopt4win.h +++ /dev/null @@ -1,193 +0,0 @@ -/* Declarations for getopt. - Copyright (C) 1989-1994,1996-1999,2001,2003,2004,2009,2010 - Free Software Foundation, Inc. - This file is part of the GNU C Library. - - The GNU C Library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - The GNU C Library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with the GNU C Library; if not, write to the Free - Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - 02111-1307 USA. */ - -#ifndef _GETOPT_H - -#ifndef __need_getopt -# define _GETOPT_H 1 -#endif - -/* If __GNU_LIBRARY__ is not already defined, either we are being used - standalone, or this is the first header included in the source file. - If we are being used with glibc, we need to include , but - that does not exist if we are standalone. So: if __GNU_LIBRARY__ is - not defined, include , which will pull in for us - if it's from glibc. (Why ctype.h? It's guaranteed to exist and it - doesn't flood the namespace with stuff the way some other headers do.) */ -#if !defined __GNU_LIBRARY__ -# include -#endif - -#ifndef __THROW -# ifndef __GNUC_PREREQ -# define __GNUC_PREREQ(maj, min) (0) -# endif -# if defined __cplusplus && __GNUC_PREREQ (2,8) -# define __THROW throw () -# else -# define __THROW -# endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* For communication from `getopt' to the caller. - When `getopt' finds an option that takes an argument, - the argument value is returned here. - Also, when `ordering' is RETURN_IN_ORDER, - each non-option ARGV-element is returned here. */ - -extern char *optarg; - -/* Index in ARGV of the next element to be scanned. - This is used for communication to and from the caller - and for communication between successive calls to `getopt'. - - On entry to `getopt', zero means this is the first call; initialize. - - When `getopt' returns -1, this is the index of the first of the - non-option elements that the caller should itself scan. - - Otherwise, `optind' communicates from one call to the next - how much of ARGV has been scanned so far. */ - -extern int optind; - -/* Callers store zero here to inhibit the error message `getopt' prints - for unrecognized options. */ - -extern int opterr; - -/* Set to an option character which was unrecognized. */ - -extern int optopt; - -#ifndef __need_getopt -/* Describe the long-named options requested by the application. - The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector - of `struct option' terminated by an element containing a name which is - zero. - - The field `has_arg' is: - no_argument (or 0) if the option does not take an argument, - required_argument (or 1) if the option requires an argument, - optional_argument (or 2) if the option takes an optional argument. - - If the field `flag' is not NULL, it points to a variable that is set - to the value given in the field `val' when the option is found, but - left unchanged if the option is not found. - - To have a long-named option do something other than set an `int' to - a compiled-in constant, such as set a value from `optarg', set the - option's `flag' field to zero and its `val' field to a nonzero - value (the equivalent single-letter option character, if there is - one). For long options that have a zero `flag' field, `getopt' - returns the contents of the `val' field. */ - -struct option -{ - const char *name; - /* has_arg can't be an enum because some compilers complain about - type mismatches in all the code that assumes it is an int. */ - int has_arg; - int *flag; - int val; -}; - -/* Names for the values of the `has_arg' field of `struct option'. */ - -# define no_argument 0 -# define required_argument 1 -# define optional_argument 2 -#endif /* need getopt */ - - -/* Get definitions and prototypes for functions to process the - arguments in ARGV (ARGC of them, minus the program name) for - options given in OPTS. - - Return the option character from OPTS just read. Return -1 when - there are no more options. For unrecognized options, or options - missing arguments, `optopt' is set to the option letter, and '?' is - returned. - - The OPTS string is a list of characters which are recognized option - letters, optionally followed by colons, specifying that that letter - takes an argument, to be placed in `optarg'. - - If a letter in OPTS is followed by two colons, its argument is - optional. This behavior is specific to the GNU `getopt'. - - The argument `--' causes premature termination of argument - scanning, explicitly telling `getopt' that there are no more - options. - - If OPTS begins with `--', then non-option arguments are treated as - arguments to the option '\0'. This behavior is specific to the GNU - `getopt'. */ - -#ifdef __GNU_LIBRARY__ -/* Many other libraries have conflicting prototypes for getopt, with - differences in the consts, in stdlib.h. To avoid compilation - errors, only prototype getopt for the GNU C library. */ -extern int getopt (int ___argc, char *const *___argv, const char *__shortopts) - __THROW; - -# if defined __need_getopt && defined __USE_POSIX2 \ - && !defined __USE_POSIX_IMPLICITLY && !defined __USE_GNU -/* The GNU getopt has more functionality than the standard version. The - additional functionality can be disable at runtime. This redirection - helps to also do this at runtime. */ -# ifdef __REDIRECT - extern int __REDIRECT_NTH (getopt, (int ___argc, char *const *___argv, - const char *__shortopts), - __posix_getopt); -# else -extern int __posix_getopt (int ___argc, char *const *___argv, - const char *__shortopts) __THROW; -# define getopt __posix_getopt -# endif -# endif -#else /* not __GNU_LIBRARY__ */ -extern int getopt (); -#endif /* __GNU_LIBRARY__ */ - -#ifndef __need_getopt -extern int getopt_long (int ___argc, char *const *___argv, - const char *__shortopts, - const struct option *__longopts, int *__longind) - __THROW; -extern int getopt_long_only (int ___argc, char *const *___argv, - const char *__shortopts, - const struct option *__longopts, int *__longind) - __THROW; - -#endif - -#ifdef __cplusplus -} -#endif - -/* Make sure we later can get all the definitions and declarations. */ -#undef __need_getopt - -#endif /* getopt.h */ diff --git a/include/libs/md4.h b/include/libs/md4.h deleted file mode 100644 index 2c0c073..0000000 --- a/include/libs/md4.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. - * MD4 Message-Digest Algorithm (RFC 1320). - * - * Homepage: - * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md4 - * - * Author: - * Alexander Peslyak, better known as Solar Designer - * - * This software was written by Alexander Peslyak in 2001. No copyright is - * claimed, and the software is hereby placed in the public domain. - * In case this attempt to disclaim copyright and place the software in the - * public domain is deemed null and void, then the software is - * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the - * general public under the following terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted. - * - * There's ABSOLUTELY NO WARRANTY, express or implied. - * - * See md4.c for more information. - */ - -#ifdef HAVE_OPENSSL -#include -#elif !defined(_MD4_H) -#define _MD4_H - -/* Any 32-bit or wider unsigned integer data type will do */ -typedef unsigned int MD4_u32plus; - -typedef struct { - MD4_u32plus lo, hi; - MD4_u32plus a, b, c, d; - unsigned char buffer[64]; - MD4_u32plus block[16]; -} MD4_CTX; - -extern void MD4_Init(MD4_CTX *ctx); -extern void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size); -extern void MD4_Final(unsigned char *result, MD4_CTX *ctx); - -void MD4(const void *data, unsigned long size, unsigned char *result); - -#endif diff --git a/include/libs/md5.h b/include/libs/md5.h deleted file mode 100644 index 0f992b1..0000000 --- a/include/libs/md5.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. - * MD5 Message-Digest Algorithm (RFC 1321). - * - * Homepage: - * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 - * - * Author: - * Alexander Peslyak, better known as Solar Designer - * - * This software was written by Alexander Peslyak in 2001. No copyright is - * claimed, and the software is hereby placed in the public domain. - * In case this attempt to disclaim copyright and place the software in the - * public domain is deemed null and void, then the software is - * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the - * general public under the following terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted. - * - * There's ABSOLUTELY NO WARRANTY, express or implied. - * - * See md5.c for more information. - */ - -#ifdef HAVE_OPENSSL -#include -#elif !defined(_MD5_H) -#define _MD5_H - -/* Any 32-bit or wider unsigned integer data type will do */ -typedef unsigned int MD5_u32plus; - -typedef struct { - MD5_u32plus lo, hi; - MD5_u32plus a, b, c, d; - unsigned char buffer[64]; - MD5_u32plus block[16]; -} MD5_CTX; - -extern void MD5_Init(MD5_CTX *ctx); -extern void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size); -extern void MD5_Final(unsigned char *result, MD5_CTX *ctx); - -void MD5(const void *data, unsigned long size, unsigned char *result); - -#endif diff --git a/include/libs/sha1.h b/include/libs/sha1.h deleted file mode 100644 index 5f47a98..0000000 --- a/include/libs/sha1.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef SHA1_H -#define SHA1_H -/* ================ sha1.h ================ */ -/* -SHA-1 in C -By Steve Reid -100% Public Domain -*/ -#include - -typedef struct { - uint32_t state[5]; - uint32_t count[2]; - unsigned char buffer[64]; -} SHA1_CTX; - -void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]); -void SHA1Init(SHA1_CTX* context); -void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len); -void SHA1Final(unsigned char digest[20], SHA1_CTX* context); - -void SHA1(const unsigned char* data, uint32_t len, unsigned char digest[20]); - -#endif diff --git a/include/utils.hpp b/include/utils.hpp new file mode 100644 index 0000000..583cdd4 --- /dev/null +++ b/include/utils.hpp @@ -0,0 +1,17 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// + +#ifndef UTILS_HPP +#define UTILS_HPP +#include + +namespace dogcom { + +std::string md4(std::string_view); +std::string md5(std::string_view); +std::string sha(std::string_view); + +} + +#endif //UTILS_HPP diff --git a/src/auth.c b/src/auth.c deleted file mode 100644 index 2ff2f16..0000000 --- a/src/auth.c +++ /dev/null @@ -1,775 +0,0 @@ -#include -#include -#include -#include - -#ifdef WIN32 -#include -typedef int socklen_t; -#else -#include -#include -#include -#endif - - -#ifdef _MSC_VER -#include -inline void sleep(int seconds) { - Sleep(1000 * seconds); -} -inline void usleep(int useconds) { - Sleep(useconds); -} -#else -#include -#include -#endif - -#include "auth.h" -#include "configparse.h" -#include "debug.h" -#include "keepalive.h" -#include -#include -#include - -#define BIND_PORT 61440 -#define DEST_PORT 61440 - -int dhcp_challenge(int sockfd, struct sockaddr_in addr, unsigned char seed[]) { - unsigned char challenge_packet[20], recv_packet[1024]; - memset(challenge_packet, 0, 20); - challenge_packet[0] = 0x01; - challenge_packet[1] = 0x02; - challenge_packet[2] = rand() & 0xff; - challenge_packet[3] = rand() & 0xff; - challenge_packet[4] = drcom_config.AUTH_VERSION[0]; - - sendto(sockfd, challenge_packet, 20, 0, (struct sockaddr *)&addr, sizeof(addr)); - - if (verbose_flag) { - print_packet("[Challenge sent] ", challenge_packet, 20); - } - if (logging_flag) { - logging("[Challenge sent] ", challenge_packet, 20); - } -#ifdef TEST - unsigned char test[4] = {0x52, 0x6c, 0xe4, 0x00}; - memcpy(seed, test, 4); - print_packet("[TEST MODE] ", seed, 4); - return 0; -#endif - - socklen_t addrlen = sizeof(addr); - if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) { -#ifdef WIN32 - get_lasterror("Failed to recv data"); -#else - perror("Failed to recv data"); -#endif - return 1; - } - - if (verbose_flag) { - print_packet("[Challenge recv] ", recv_packet, 76); - } - if (logging_flag) { - logging("[Challenge recv] ", recv_packet, 76); - } - - if (recv_packet[0] != 0x02) { - printf("Bad challenge response received.\n"); - return 1; - } - - memcpy(seed, &recv_packet[4], 4); -#ifdef DEBUG - print_packet(" ", seed, 4); -#endif - - return 0; -} - -int dhcp_login(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsigned char auth_information[], int try_JLUversion) { - unsigned int login_packet_size; - unsigned int length_padding = 0; - int JLU_padding = 0; - - if (strlen(drcom_config.password) > 8) { - length_padding = strlen(drcom_config.password) - 8 + (length_padding % 2); - if (try_JLUversion) { - printf("Start JLU mode.\n"); - if (logging_flag) { - logging("Start JLU mode.", NULL, 0); - } - if (strlen(drcom_config.password) != 16) { - JLU_padding = strlen(drcom_config.password) / 4; - } - length_padding = 28 + (strlen(drcom_config.password) - 8) + JLU_padding; - } - } - if (drcom_config.ror_version) { - login_packet_size = 338 + length_padding; - } else { - login_packet_size = 330; - } - unsigned char* login_packet = (unsigned char*) malloc(login_packet_size); - unsigned char recv_packet[1024], MD5A[16], MACxorMD5A[6], MD5B[16], checksum1[8], checksum2[4]; - memset(login_packet, 0, login_packet_size); - memset(recv_packet, 0, 100); - - // build login-packet - login_packet[0] = 0x03; - login_packet[1] = 0x01; - login_packet[2] = 0x00; - login_packet[3] = strlen(drcom_config.username) + 20; - int MD5A_len = 6 + strlen(drcom_config.password); - unsigned char* MD5A_str = (unsigned char*)malloc(MD5A_len); - MD5A_str[0] = 0x03; - MD5A_str[1] = 0x01; - memcpy(MD5A_str + 2, seed, 4); - memcpy(MD5A_str + 6, drcom_config.password, strlen(drcom_config.password)); - MD5(MD5A_str, MD5A_len, MD5A); - memcpy(login_packet + 4, MD5A, 16); - memcpy(login_packet + 20, drcom_config.username, strlen(drcom_config.username)); - memcpy(login_packet + 56, &drcom_config.CONTROLCHECKSTATUS, 1); - memcpy(login_packet + 57, &drcom_config.ADAPTERNUM, 1); - uint64_t sum = 0; - uint64_t mac = 0; - // unpack - for (int i = 0; i < 6; i++) { - sum = (int)MD5A[i] + sum * 256; - } - // unpack - for (int i = 0; i < 6; i++) { - mac = (int)drcom_config.mac[i] + mac * 256; - } - sum ^= mac; - // pack - for (int i = 6; i > 0; i--) { - MACxorMD5A[i - 1] = (unsigned char)(sum % 256); - sum /= 256; - } - memcpy(login_packet + 58, MACxorMD5A, sizeof(MACxorMD5A)); - int MD5B_len = 9 + strlen(drcom_config.password); - unsigned char* MD5B_str = (unsigned char*) malloc (MD5B_len); - memset(MD5B_str, 0, MD5B_len); - MD5B_str[0] = 0x01; - memcpy(MD5B_str + 1, drcom_config.password, strlen(drcom_config.password)); - memcpy(MD5B_str + strlen(drcom_config.password) + 1, seed, 4); - MD5(MD5B_str, MD5B_len, MD5B); - memcpy(login_packet + 64, MD5B, 16); - login_packet[80] = 0x01; - unsigned char host_ip[4]; - sscanf(drcom_config.host_ip, "%hhd.%hhd.%hhd.%hhd", - &host_ip[0], - &host_ip[1], - &host_ip[2], - &host_ip[3]); - memcpy(login_packet + 81, host_ip, 4); - unsigned char checksum1_str[101], checksum1_tmp[4] = {0x14, 0x00, 0x07, 0x0b}; - memcpy(checksum1_str, login_packet, 97); - memcpy(checksum1_str + 97, checksum1_tmp, 4); - MD5(checksum1_str, 101, checksum1); - memcpy(login_packet + 97, checksum1, 8); - memcpy(login_packet + 105, &drcom_config.IPDOG, 1); - memcpy(login_packet + 110, &drcom_config.host_name, strlen(drcom_config.host_name)); - unsigned char PRIMARY_DNS[4]; - sscanf(drcom_config.PRIMARY_DNS, "%hhd.%hhd.%hhd.%hhd", - &PRIMARY_DNS[0], - &PRIMARY_DNS[1], - &PRIMARY_DNS[2], - &PRIMARY_DNS[3]); - memcpy(login_packet + 142, PRIMARY_DNS, 4); - unsigned char dhcp_server[4]; - sscanf(drcom_config.dhcp_server, "%hhd.%hhd.%hhd.%hhd", - &dhcp_server[0], - &dhcp_server[1], - &dhcp_server[2], - &dhcp_server[3]); - memcpy(login_packet + 146, dhcp_server, 4); - unsigned char OSVersionInfoSize[4] = {0x94}; - unsigned char OSMajor[4] = {0x05}; - unsigned char OSMinor[4] = {0x01}; - unsigned char OSBuild[4] = {0x28, 0x0a}; - unsigned char PlatformID[4] = {0x02}; - if (try_JLUversion) { - OSVersionInfoSize[0] = 0x94; - OSMajor[0] = 0x06; - OSMinor[0] = 0x02; - OSBuild[0] = 0xf0; - OSBuild[1] = 0x23; - PlatformID[0] = 0x02; - unsigned char ServicePack[40] = {0x33, 0x64, 0x63, 0x37, 0x39, 0x66, 0x35, 0x32, 0x31, 0x32, 0x65, 0x38, 0x31, 0x37, 0x30, 0x61, 0x63, 0x66, 0x61, 0x39, 0x65, 0x63, 0x39, 0x35, 0x66, 0x31, 0x64, 0x37, 0x34, 0x39, 0x31, 0x36, 0x35, 0x34, 0x32, 0x62, 0x65, 0x37, 0x62, 0x31}; - unsigned char hostname[9] = {0x44, 0x72, 0x43, 0x4f, 0x4d, 0x00, 0xcf, 0x07, 0x68}; - memcpy(login_packet + 182, hostname, 9); - memcpy(login_packet + 246, ServicePack, 40); - } - memcpy(login_packet + 162, OSVersionInfoSize, 4); - memcpy(login_packet + 166, OSMajor, 4); - memcpy(login_packet + 170, OSMinor, 4); - memcpy(login_packet + 174, OSBuild, 4); - memcpy(login_packet + 178, PlatformID, 4); - if (!try_JLUversion) { - memcpy(login_packet + 182, &drcom_config.host_os, strlen(drcom_config.host_os)); - } - memcpy(login_packet + 310, drcom_config.AUTH_VERSION, 2); - int counter = 312; - unsigned int ror_padding = 0; - if (strlen(drcom_config.password) <= 8) { - ror_padding = 8 - strlen(drcom_config.password); - } else { - if ((strlen(drcom_config.password) - 8) % 2) { - ror_padding = 1; - } - if (try_JLUversion) { - ror_padding = JLU_padding; - } - } - if (drcom_config.ror_version) { - MD5(MD5A_str, MD5A_len, MD5A); - login_packet[counter + 1] = strlen(drcom_config.password); - counter += 2; - for (int i = 0, x = 0; i < strlen(drcom_config.password); i++) { - x = (int)MD5A[i] ^ (int)drcom_config.password[i]; - login_packet[counter + i] = (unsigned char)(((x << 3) & 0xff) + (x >> 5)); - } - counter += strlen(drcom_config.password); - // print_packet("TEST ", ror, strlen(drcom_config.password)); - } else { - ror_padding = 2; - } - login_packet[counter] = 0x02; - login_packet[counter + 1] = 0x0c; - unsigned char* checksum2_str = (unsigned char*) malloc (counter + 18); // [counter + 14 + 4] - memset(checksum2_str, 0, counter + 18); - unsigned char checksum2_tmp[6] = {0x01, 0x26, 0x07, 0x11}; - memcpy(checksum2_str, login_packet, counter + 2); - memcpy(checksum2_str + counter + 2, checksum2_tmp, 6); - memcpy(checksum2_str + counter + 8, drcom_config.mac, 6); - sum = 1234; - uint64_t ret = 0; - for (int i = 0; i < counter + 14; i += 4) { - ret = 0; - // reverse unsigned char array[4] - for (int j = 4; j > 0; j--) { - ret = ret * 256 + (int)checksum2_str[i + j - 1]; - } - sum ^= ret; - } - sum = (1968 * sum) & 0xffffffff; - for (int j = 0; j < 4; j++) { - checksum2[j] = (unsigned char)(sum >> (j * 8) & 0xff); - } - memcpy(login_packet + counter + 2, checksum2, 4); - memcpy(login_packet + counter + 8, drcom_config.mac, 6); - login_packet[counter + ror_padding + 14] = 0xe9; - login_packet[counter + ror_padding + 15] = 0x13; - if (try_JLUversion) { - login_packet[counter + ror_padding + 14] = 0x60; - login_packet[counter + ror_padding + 15] = 0xa2; - } - - sendto(sockfd, login_packet, sizeof(login_packet), 0, (struct sockaddr *)&addr, sizeof(addr)); - - if (verbose_flag) { - print_packet("[Login sent] ", login_packet, sizeof(login_packet)); - } - if (logging_flag) { - logging("[Login sent] ", login_packet, sizeof(login_packet)); - } - -#ifdef TEST - unsigned char test[16] = {0x44, 0x72, 0x63, 0x6f, 0x77, 0x27, 0x20, 0xca, 0xed, 0x05, 0x6e, 0x35, 0xaa, 0x8b, 0x01, 0xfb}; - memcpy(auth_information, test, 16); - print_packet("[TEST MODE] ", auth_information, 16); - return 0; -#endif - - socklen_t addrlen = sizeof(addr); - if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) { -#ifdef WIN32 - get_lasterror("Failed to recv data"); -#else - perror("Failed to recv data"); -#endif - return 1; - } - - if (recv_packet[0] != 0x04) { - if (verbose_flag) { - print_packet("[login recv] ", recv_packet, 100); - } - printf("<<< Login failed >>>\n"); - if (logging_flag) { - logging("[login recv] ", recv_packet, 100); - logging("<<< Login failed >>>", NULL, 0); - } - char err_msg[256]; - if (recv_packet[0] == 0x05) { - switch (recv_packet[4]) { - case CHECK_MAC: - strcpy(err_msg, "[Tips] Someone is using this account with wired."); - break; - case SERVER_BUSY: - strcpy(err_msg, "[Tips] The server is busy, please log back in again."); - break; - case WRONG_PASS: - strcpy(err_msg, "[Tips] Account and password not match."); - break; - case NOT_ENOUGH: - strcpy(err_msg, "[Tips] The cumulative time or traffic for this account has exceeded the limit."); - break; - case FREEZE_UP: - strcpy(err_msg, "[Tips] This account is suspended."); - break; - case NOT_ON_THIS_IP: - strcpy(err_msg, "[Tips] IP address does not match, this account can only be used in the specified IP address."); - break; - case NOT_ON_THIS_MAC: - strcpy(err_msg, "[Tips] MAC address does not match, this account can only be used in the specified IP and MAC address."); - break; - case TOO_MUCH_IP: - strcpy(err_msg, "[Tips] This account has too many IP addresses."); - break; - case UPDATE_CLIENT: - strcpy(err_msg, "[Tips] The client version is incorrect."); - break; - case NOT_ON_THIS_IP_MAC: - strcpy(err_msg, "[Tips] This account can only be used on specified MAC and IP address."); - break; - case MUST_USE_DHCP: - strcpy(err_msg, "[Tips] Your PC set up a static IP, please change to DHCP, and then re-login."); - break; - default: - strcpy(err_msg, "[Tips] Unknown error number."); - break; - } - printf("%s\n", err_msg); - if (logging_flag) { - logging(err_msg, NULL, 0); - } - } - return 1; - } else { - if (verbose_flag) { - print_packet("[login recv] ", recv_packet, 100); - } - printf("<<< Logged in >>>\n"); - if (logging_flag) { - logging("[login recv] ", recv_packet, 100); - logging("<<< Logged in >>>", NULL, 0); - } - } - - memcpy(auth_information, &recv_packet[23], 16); -#ifdef DEBUG - print_packet(" ", auth_information, 16); -#endif - - if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) >= 0) { - DEBUG_PRINT(("Get notice packet.")); - } - - free(login_packet); - free(MD5A_str); - free(MD5B_str); - free(checksum2_str); - - return 0; -} - -int pppoe_challenge(int sockfd, struct sockaddr_in addr, int *pppoe_counter, unsigned char seed[], unsigned char sip[], int *encrypt_mode) { - unsigned char challenge_packet[8], recv_packet[1024]; - memset(challenge_packet, 0, 8); - unsigned char challenge_tmp[5] = {0x07, 0x00, 0x08, 0x00, 0x01}; - memcpy(challenge_packet, challenge_tmp, 5); - challenge_packet[1] = *pppoe_counter % 0xFF; - (*pppoe_counter)++; - - sendto(sockfd, challenge_packet, 8, 0, (struct sockaddr *)&addr, sizeof(addr)); - - if (verbose_flag) { - print_packet("[Challenge sent] ", challenge_packet, 8); - } - if (logging_flag) { - logging("[Challenge sent] ", challenge_packet, 8); - } -#ifdef TEST - unsigned char test1[4] = {0x26, 0xe6, 0xe1, 0x02}; - unsigned char test2[4] = {0xc0, 0xa8, 0x01, 0x0b}; - memcpy(seed, test1, 4); - memcpy(sip, test2, 4); - *encrypt_mode = 1; /* encrypt_mode test switch [0 or 1] */ - print_packet("[TEST MODE] ", seed, 4); - print_packet("[TEST MODE] ", sip, 4); - printf("[TEST MODE] %d\n", *encrypt_mode); - return 0; -#endif - - socklen_t addrlen = sizeof(addr); - if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) { -#ifdef WIN32 - get_lasterror("Failed to recv data"); -#else - perror("Failed to recv data"); -#endif - return 1; - } - - if (verbose_flag) { - print_packet("[Challenge recv] ", recv_packet, 32); - } - if (logging_flag) { - logging("[Challenge recv] ", recv_packet, 32); - } - - if (recv_packet[0] != 0x07) { - printf("Bad challenge response received.\n"); - return 1; - } - if (recv_packet[5] != 0x00) { - *encrypt_mode = 1; - } else { - *encrypt_mode = 0; - } - -#ifdef FORCE_ENCRYPT - *encrypt_mode = 1; -#endif - - memcpy(seed, &recv_packet[8], 4); - memcpy(sip, &recv_packet[12], 4); - memcpy(drcom_config.KEEP_ALIVE_VERSION, &recv_packet[28], 2); -#ifdef DEBUG - print_packet(" ", seed, 4); - print_packet(" ", sip, 4); - printf(" %d", *encrypt_mode); -#endif - - return 0; -} - -int pppoe_login(int sockfd, struct sockaddr_in addr, int *pppoe_counter, unsigned char seed[], unsigned char sip[], int *login_first, int *encrypt_mode, int *encrypt_type) { - unsigned char login_packet[96], recv_packet[1024]; - memset(login_packet, 0, 96); - unsigned char login_tmp[5] = {0x07, 0x00, 0x60, 0x00, 0x03}; - memcpy(login_packet, login_tmp, 5); - login_packet[1] = *pppoe_counter % 0xFF; - (*pppoe_counter)++; - memcpy(login_packet + 12, sip, 4); - if (*login_first) { - login_packet[17] = 0x62; - } else { - login_packet[17] = 0x63; - } - memcpy(login_packet + 19, &drcom_config.pppoe_flag, 1); - memcpy(login_packet + 20, seed, 4); - unsigned char crc[8] = {0}; - *encrypt_type = seed[0] & 3; - if (!*encrypt_mode) { - *encrypt_type = 0; - } - gen_crc(seed, *encrypt_type, crc); - unsigned char crc_tmp[32] = {0}; - memcpy(crc_tmp, login_packet, 32); - memcpy(crc_tmp + 24, crc, 8); - uint64_t ret = 0; - uint64_t sum = 0; - unsigned char crc2[4] = {0}; - if (*encrypt_type == 0) { - for (int i = 0; i < 32; i += 4) { - ret = 0; - for (int j = 4; j > 0; j--) { - ret = ret * 256 + (int)crc_tmp[i + j - 1]; - } - sum ^= ret; - sum &= 0xffffffff; - } - sum = sum * 19680126 & 0xffffffff; - for (int i = 0; i < 4; i++) { - crc2[i] = (unsigned char)(sum % 256); - sum /= 256; - } - memcpy(login_packet + 24, crc2, 4); - } else { - memcpy(login_packet + 24, crc, 8); - } - // login_packet[39] = 0x8b; - // memcpy(login_packet + 40, sip, 4); - // unsigned char smask[4] = {0xff, 0xff, 0xff, 0xff}; - // memcpy(login_packet + 44, smask, 4); - // login_packet[54] = 0x40; - - sendto(sockfd, login_packet, 96, 0, (struct sockaddr *)&addr, sizeof(addr)); - if (verbose_flag) { - print_packet("[PPPoE_login sent] ", login_packet, 96); - } - if (logging_flag) { - logging("[PPPoE_login sent] ", login_packet, 96); - } -#ifdef TEST - return 0; -#endif - - socklen_t addrlen = sizeof(addr); - if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) { -#ifdef WIN32 - get_lasterror("Failed to recv data"); -#else - perror("Failed to recv data"); -#endif - return 1; - } - - if (verbose_flag) { - print_packet("[PPPoE_login recv] ", recv_packet, 48); - } - if (logging_flag) { - logging("[PPPoE_login recv] ", recv_packet, 48); - } - - if (recv_packet[0] != 0x07) { - printf("Bad pppoe_login response received.\n"); - return 1; - } - - if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) >= 0) { - DEBUG_PRINT(("Get notice packet.")); - } - - return 0; -} - -int dogcom(int try_times) { -#ifdef WIN32 - WORD sockVersion = MAKEWORD(2, 2); - WSADATA wsaData; - if (WSAStartup(sockVersion, &wsaData) != 0) { - return 1; - } -#endif - int sockfd; - - struct sockaddr_in bind_addr; - memset(&bind_addr, 0, sizeof(bind_addr)); - bind_addr.sin_family = AF_INET; - if (verbose_flag) { - printf("You are binding at %s!\n\n", bind_ip); - } -#ifdef WIN32 - bind_addr.sin_addr.S_un.S_addr = inet_addr(bind_ip); -#else - bind_addr.sin_addr.s_addr = inet_addr(bind_ip); -#endif - bind_addr.sin_port = htons(BIND_PORT); - - struct sockaddr_in dest_addr; - memset(&dest_addr, 0, sizeof(dest_addr)); - dest_addr.sin_family = AF_INET; -#ifdef WIN32 - dest_addr.sin_addr.S_un.S_addr = inet_addr(drcom_config.server); -#else - dest_addr.sin_addr.s_addr = inet_addr(drcom_config.server); -#endif - dest_addr.sin_port = htons(DEST_PORT); - - srand(time(NULL)); - - // create socket - if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { -#ifdef WIN32 - get_lasterror("Failed to create socket"); -#else - perror("Failed to create socket"); -#endif - return 1; - } - // bind socket - if (bind(sockfd, (struct sockaddr *)&bind_addr, sizeof(bind_addr)) < 0) { -#ifdef WIN32 - get_lasterror("Failed to bind socket"); -#else - perror("Failed to bind socket"); -#endif - return 1; - } - - // set timeout -#ifdef WIN32 - int timeout = 3000; -#else - struct timeval timeout; - timeout.tv_sec = 3; - timeout.tv_usec = 0; -#endif - if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) { -#ifdef WIN32 - get_lasterror("Failed to set sock opt"); -#else - perror("Failed to set sock opt"); -#endif - return 1; - } - - // start dogcoming - if (strcmp(mode, "dhcp") == 0) { - int login_failed_attempts = 0; - int try_JLUversion = 0; - for (int try_counter = 0; try_counter < try_times; try_counter++) { - if (eternal_flag) { - try_counter = 0; - } - unsigned char seed[4]; - unsigned char auth_information[16]; - if (dhcp_challenge(sockfd, dest_addr, seed)) { - printf("Retrying...\n"); - if (logging_flag) { - logging("Retrying...", NULL, 0); - } - sleep(3); - } else { - usleep(200000); // 0.2 sec - if (login_failed_attempts > 2) { - try_JLUversion = 1; - } - if (!dhcp_login(sockfd, dest_addr, seed, auth_information, try_JLUversion)) { - int keepalive_counter = 0; - int keepalive_try_counter = 0; - int first = 1; - while (1) { - if (!keepalive_1(sockfd, dest_addr, seed, auth_information)) { - usleep(200000); // 0.2 sec - if (keepalive_2(sockfd, dest_addr, &keepalive_counter, &first, 0)) { - continue; - } - if (verbose_flag) { - printf("Keepalive in loop.\n"); - } - if (logging_flag) { - logging("Keepalive in loop.", NULL, 0); - } - sleep(20); - } else { - if (keepalive_try_counter > 5) { - break; - } - keepalive_try_counter++; - continue; - } - } - } else { - login_failed_attempts += 1; - printf("Retrying...\n"); - if (logging_flag) { - logging("Retrying...", NULL, 0); - } - sleep(3); - }; - } - } - } else if (strcmp(mode, "pppoe") == 0) { - int pppoe_counter = 0; - int keepalive_counter = 0; - unsigned char seed[4], sip[4]; /* pppoe's seed == dhcp's KEEP_ALIVE_VERSION */ - int login_first = 1; - int first = 1; - int encrypt_mode = 0; - int encrypt_type = 0; - int try_counter = 0; - while (1) { - if (pppoe_challenge(sockfd, dest_addr, &pppoe_counter, seed, sip, &encrypt_mode)) { - printf("Retrying...\n"); - if (logging_flag) { - logging("Retrying...", NULL, 0); - } - login_first = 1; - try_counter++; - if (eternal_flag) { - try_counter = 0; - } - if (try_counter >= try_times) { - break; - } - sleep(5); - continue; - } else { - usleep(200000); // 0.2 sec - if (pppoe_login(sockfd, dest_addr, &pppoe_counter, seed, sip, &login_first, &encrypt_mode, &encrypt_type)) { - continue; - } else { - login_first = 0; - if (keepalive_2(sockfd, dest_addr, &keepalive_counter, &first, &encrypt_type)) { - continue; - } else { - if (verbose_flag) { - printf("PPPoE in loop.\n"); - } - if (logging_flag) { - logging("PPPoE in loop.", NULL, 0); - } - sleep(10); - continue; - } - } - } - } - } - - printf(">>>>> Failed to keep in touch with server, exiting <<<<<\n\n"); - if (logging_flag) { - logging(">>>>> Failed to keep in touch with server, exiting <<<<<", NULL, 0); - } -#ifdef WIN32 - closesocket(sockfd); - WSACleanup(); -#else - close(sockfd); -#endif - return 1; -} - -void print_packet(char msg[10], unsigned char *packet, int length) { - printf("%s", msg); - for (int i = 0; i < length; i++) { - printf("%02x", packet[i]); - } - printf("\n"); -} - -void logging(char msg[10], unsigned char *packet, int length) { - FILE *ptr_file; - ptr_file = fopen(log_path, "a"); - - char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; - time_t timep; - struct tm *p; - time(&timep); - p = localtime(&timep); - fprintf(ptr_file, "[%04d/%02d/%02d %s %02d:%02d:%02d] ", - (1900 + p->tm_year), (1 + p->tm_mon), p->tm_mday, wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec); - - fprintf(ptr_file, "%s", msg); - for (int i = 0; i < length; i++) { - fprintf(ptr_file, "%02x", packet[i]); - } - fprintf(ptr_file, "\n"); - - fclose(ptr_file); -} - -#ifdef WIN32 -void get_lasterror(char *msg) { - char err_msg[256]; - err_msg[0] = '\0'; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - WSAGetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - err_msg, - sizeof(err_msg), - NULL); - fprintf(stderr, "%s: %s", msg, err_msg); -} -#endif \ No newline at end of file diff --git a/src/client.cpp b/src/client.cpp new file mode 100644 index 0000000..c64e543 --- /dev/null +++ b/src/client.cpp @@ -0,0 +1,12 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// +#include + +namespace dogcom { + +client_t::client_t(const config_t &info): config(info), socket(service) { + +} + +} \ No newline at end of file diff --git a/src/common.c b/src/common.c deleted file mode 100644 index 6db6bd7..0000000 --- a/src/common.c +++ /dev/null @@ -1,329 +0,0 @@ -#ifdef linux - -/* - * 一些通用的代码 - */ -#include -#include -#include -#include -#include -#include -#include "common.h" - -// #ifdef LINUX -#include -#include -#include -#include -#include -#include -#include -#include -#define PATH_SEP '/' -// #elif WIN32 -// # include -// # include -// # define PATH_SEP '\\' -// #endif - - -extern int getexedir(char *exedir) -{ -// #ifdef LINUX - int cnt = readlink("/proc/self/exe", exedir, EXE_PATH_MAX); -// #elif WIN32 -// int cnt = GetModuleFileName(NULL, exedir, EXE_PATH_MAX); -// #endif - if (cnt < 0 || cnt >= EXE_PATH_MAX) - return -1; - _D("exedir: %s\n", exedir); - char *end = strrchr(exedir, PATH_SEP); - if (!end) return -1; - *(end+1) = '\0'; - _D("exedir: %s\n", exedir); - return 0; -} - -extern int mac_equal(uchar const *mac1, uchar const *mac2) -{ - int i; - for (i = 0; i < ETH_ALEN; ++i) { - if (mac1[i] != mac2[i]) - return 0; - } - - return 1; -} -extern int ip_equal(int type, void const *ip1, void const *ip2) -{ - uchar const *p1 = (uchar const*)ip1; - uchar const *p2 = (uchar const*)ip2; - int len = 4; - if (AF_INET6 == type) { - len = 16; - } - int i; - for (i = 0; i < len; ++i) { - if (p1[i] != p2[i]) - return 0; - } - return 1; -} - -static int is_filter(char const *ifname) -{ - /* 过滤掉无线,虚拟机接口等 */ - char const *filter[] = { - /* windows */ - "Wireless", "Microsoft", - "Virtual", - /* linux */ - "lo", "wlan", "vboxnet", - "ifb", "gre", "teql", - "br", "imq", "ra", - "wds", "sit", "apcli", - }; - unsigned int i; - for (i = 0; i < ARRAY_SIZE(filter); ++i) { - if (strstr(ifname, filter[i])) - return 1; - } - return 0; -} -// #ifdef LINUX -static char *get_ifname_from_buff(char *buff) -{ - char *s; - while (isspace(*buff)) - ++buff; - s = buff; - while (':' != *buff && '\0' != *buff) - ++buff; - *buff = '\0'; - return s; -} -// #endif -/* - * 获取所有网络接口 - * ifnames 实际获取的接口 - * cnt 两个作用,1:传入表示ifnames最多可以存储的接口个数 - * 2:返回表示实际获取了的接口个数 - * 返回接口个数在cnt里 - * @return: >=0 成功,实际获取的接口个数 - * -1 获取失败 - * -2 cnt过小 - */ -extern int getall_ifs(iflist_t *ifs, int *cnt) -{ - int i = 0; - if (!ifs || *cnt <= 0) return -2; - -// #ifdef LINUX /* linux (unix osx?) */ -#define _PATH_PROCNET_DEV "/proc/net/dev" -#define BUFF_LINE_MAX (1024) - char buff[BUFF_LINE_MAX]; - FILE *fd = fopen(_PATH_PROCNET_DEV, "r"); - char *name; - if (NULL == fd) { - perror("fopen"); - return -1; - } - /* _PATH_PROCNET_DEV文件格式如下,...表示后面我们不关心 - * Inter-| Receive ... - * face |bytes packets ... - * eth0: 147125283 119599 ... - * wlan0: 229230 2635 ... - * lo: 10285509 38254 ... - */ - /* 略过开始两行 */ - fgets(buff, BUFF_LINE_MAX, fd); - fgets(buff, BUFF_LINE_MAX, fd); - while (NULL != fgets(buff, BUFF_LINE_MAX, fd)) { - name = get_ifname_from_buff(buff); - _D("%s\n", name); - /* 过滤无关网络接口 */ - if (is_filter(name)) { - _D("filtered %s.\n", name); - continue; - } - strncpy(ifs[i].name, name, IFNAMSIZ); - _D("ifs[%d].name: %s\n", i, ifs[i].name); - ++i; - if (i >= *cnt) { - fclose(fd); - return -2; - } - } - fclose(fd); - -// #elif WIN32 -// pcap_if_t *alldevs; -// char errbuf[PCAP_ERRBUF_SIZE]; -// if (-1 == pcap_findalldevs(&alldevs, errbuf)) { -// _M("Get interfaces handler error: %s\n", errbuf); -// return -1; -// } -// for (pcap_if_t *d = alldevs; d; d = d->next) { -// if (is_filter(d->description)) { -// _D("filtered %s.\n", d->description); -// continue; -// } -// if (i >= *cnt) return -2; -// strncpy(ifs[i].name, d->name, IFNAMSIZ); -// strncpy(ifs[i].desc, d->description, IFDESCSIZ); -// ++i; -// } -// pcap_freealldevs(alldevs); -// #endif - - *cnt = i; - return i; -} - -extern char const *format_time(void) -{ - static char buff[FORMAT_TIME_MAX]; - time_t rawtime; - struct tm *timeinfo; - - time(&rawtime); - timeinfo = localtime(&rawtime); - if (NULL == timeinfo) return NULL; - strftime(buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", timeinfo); - - return buff; -} -extern int copy(char const *f1, char const *f2) -{ - if (NULL == f1 || NULL == f2) return -1; - FILE *src, *dst; - src = fopen(f1, "r"); - dst = fopen(f2, "w"); - if (NULL == src || NULL == dst) return -1; - char buff[1024]; - int n; - while (0 < (n = fread(buff, 1, 1024, src))) - fwrite(buff, 1, n, dst); - - fclose(src); - fclose(dst); - - return 0; -} -/* - * 本地是否是小端序 - * @return: !0: 是 - * 0: 不是(大端序) - */ -static int islsb() -{ - static uint16 a = 0x0001; - return (int)(*(uchar*)&a); -} -static uint16 exorders(uint16 n) -{ - return ((n>>8)|(n<<8)); -} -static uint32 exorderl(uint32 n) -{ - return (n>>24)|((n&0x00ff0000)>>8)|((n&0x0000ff00)<<8)|(n<<24); -} -extern uint16 htols(uint16 n) -{ - return islsb()?n:exorders(n); -} -extern uint16 htoms(uint16 n) -{ - return islsb()?exorders(n):n; -} -extern uint16 ltohs(uint16 n) -{ - return islsb()?n:exorders(n); -} -extern uint16 mtohs(uint16 n) -{ - return islsb()?exorders(n):n; -} -extern uint32 htoll(uint32 n) -{ - return islsb()?n:exorderl(n); -} -extern uint32 htoml(uint32 n) -{ - return islsb()?exorderl(n):n; -} -extern uint32 ltohl(uint32 n) -{ - return islsb()?n:exorderl(n); -} -extern uint32 mtohl(uint32 n) -{ - return islsb()?exorderl(n):n; -} -extern uchar const *format_mac(uchar const *macarr) -{ - static uchar formatmac[] = - "xx:xx:xx:xx:xx:xx"; - if (NULL == macarr) - return NULL; - sprintf((char*)formatmac, "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X", - macarr[0], macarr[1], macarr[2], - macarr[3], macarr[4], macarr[5]); - return formatmac; -} -/* - * 以16进制打印数据 - */ -extern void format_data(uchar const *d, size_t len) -{ - int i; - for (i = 0; i < (long)len; ++i) { - if (i != 0 && i%16 == 0) - _M("\n"); - _M("%02x ", d[i]); - } - _M("\n"); -} - -#ifdef LINUX -/* - * 返回t1-t0的时间差 - * 由于这里精度没必要达到ns,故返回相差微秒ms - * @return: 时间差,单位微秒(1s == 1000ms) - */ -extern long difftimespec(struct timespec t1, struct timespec t0) -{ - long d = t1.tv_sec-t0.tv_sec; - d *= 1000; - d += (t1.tv_nsec-t0.tv_nsec)/(long)(1e6); - return d; -} - -/* - * 判断网络是否连通 - * 最长延时3s,也就是说如果3s内没有检测到数据回应,那么认为网络不通 - * TODO 使用icmp协议判断 - * @return: !0: 连通 - * 0: 没有连通 - */ -extern int isnetok(char const *ifname) -{ - static char baidu[] = "baidu.com"; - sleep(100); - return 1; -} - -/* - * 休眠ms微秒 - */ -extern void msleep(long ms) -{ - struct timeval tv; - tv.tv_sec = ms/1000; - tv.tv_usec = ms%1000*1000; - select(0, 0, 0, 0, &tv); -} -#endif /* LINUX */ - -#endif \ No newline at end of file diff --git a/src/config.cpp b/src/config.cpp new file mode 100644 index 0000000..a82abdb --- /dev/null +++ b/src/config.cpp @@ -0,0 +1,4 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// +#include \ No newline at end of file diff --git a/src/configparse.c b/src/configparse.c deleted file mode 100644 index 5b4d4d0..0000000 --- a/src/configparse.c +++ /dev/null @@ -1,181 +0,0 @@ -#include "configparse.h" -#include -#include -#include -#include "debug.h" - -int verbose_flag = 0; -int logging_flag = 0; -int eapol_flag = 0; -int eternal_flag = 0; -char *log_path; -char mode[10]; -char bind_ip[20]; -struct config drcom_config; - -static int read_d_config(char *buf, int size); -static int read_p_config(char *buf, int size); - -int config_parse(char *filepath) { - FILE *ptr_file; - char buf[100]; - - ptr_file = fopen(filepath, "r"); - if (!ptr_file) { - printf("Failed to read config file.\n"); - exit(1); - } - - while (fgets(buf, sizeof(buf), ptr_file)) { - if (strcmp(mode, "dhcp") == 0) { - read_d_config(buf, sizeof(buf)); - } else if (strcmp(mode, "pppoe") == 0) { - read_p_config(buf, sizeof(buf)); - } - } - if (verbose_flag) { - printf("\n\n"); - } - fclose(ptr_file); - - return 0; -} - -static int read_d_config(char *buf, int size) { - if (verbose_flag) { - printf("%s", buf); - } - - char *delim = " ='\r\n"; - char *delim2 = "\\x"; - char *key; - char *value; - if (strlen(key = strtok(buf, delim))) { - value = strtok(NULL, delim); - } - drcom_config.keepalive1_mod = 0; - - if (strcmp(key, "server") == 0) { - strcpy(drcom_config.server, value); - DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.server)); - } else if (strcmp(key, "username") == 0) { - strcpy(drcom_config.username, value); - DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.username)); - } else if (strcmp(key, "password") == 0) { - strcpy(drcom_config.password, value); - DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.password)); - } else if (strcmp(key, "CONTROLCHECKSTATUS") == 0) { - value = strtok(value, delim2); - sscanf(value, "%02hhx", &drcom_config.CONTROLCHECKSTATUS); - DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.CONTROLCHECKSTATUS)); - } else if (strcmp(key, "ADAPTERNUM") == 0) { - value = strtok(value, delim2); - sscanf(value, "%02hhx", &drcom_config.ADAPTERNUM); - DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.ADAPTERNUM)); - } else if (strcmp(key, "host_ip") == 0) { - strcpy(drcom_config.host_ip, value); - DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.host_ip)); - } else if (strcmp(key, "IPDOG") == 0) { - value = strtok(value, delim2); - sscanf(value, "%02hhx", &drcom_config.IPDOG); - DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.IPDOG)); - } else if (strcmp(key, "host_name") == 0) { - strcpy(drcom_config.host_name, value); - DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.host_name)); - } else if (strcmp(key, "PRIMARY_DNS") == 0) { - strcpy(drcom_config.PRIMARY_DNS, value); - DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.PRIMARY_DNS)); - } else if (strcmp(key, "dhcp_server") == 0) { - strcpy(drcom_config.dhcp_server, value); - DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.dhcp_server)); - } else if (strcmp(key, "AUTH_VERSION") == 0) { - char *v1 = strtok(value, delim2); - char *v2 = strtok(NULL, delim2); - sscanf(v1, "%02hhx", v1); - sscanf(v2, "%02hhx", v2); - memcpy(&drcom_config.AUTH_VERSION[0], v1, 1); - memcpy(&drcom_config.AUTH_VERSION[1], v2, 1); - DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.AUTH_VERSION[0])); - DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.AUTH_VERSION[1])); - } else if (strcmp(key, "mac") == 0) { - char *delim3 = "x"; - // strsep(&value, delim3); - value = strtok(value, delim3); - value = strtok(NULL, delim3); - sscanf(value, "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx", - &drcom_config.mac[0], - &drcom_config.mac[1], - &drcom_config.mac[2], - &drcom_config.mac[3], - &drcom_config.mac[4], - &drcom_config.mac[5]); -#ifdef DEBUG - printf("[PARSER_DEBUG]0x"); - for (int i = 0; i < 6; i++) { - printf("%02x", drcom_config.mac[i]); - } - printf("\n"); -#endif - } else if (strcmp(key, "host_os") == 0) { - strcpy(drcom_config.host_os, value); - DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.host_os)); - } else if (strcmp(key, "KEEP_ALIVE_VERSION") == 0) { - char *v1 = strtok(value, delim2); - char *v2 = strtok(NULL, delim2); - sscanf(v1, "%02hhx", v1); - sscanf(v2, "%02hhx", v2); - memcpy(&drcom_config.KEEP_ALIVE_VERSION[0], v1, 1); - memcpy(&drcom_config.KEEP_ALIVE_VERSION[1], v2, 1); - DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.KEEP_ALIVE_VERSION[0])); - DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.KEEP_ALIVE_VERSION[1])); - } else if (strcmp(key, "ror_version") == 0) { - if (strcmp(value, "True") == 0) { - drcom_config.ror_version = 1; - } else { - drcom_config.ror_version = 0; - } - DEBUG_PRINT(("\n[PARSER_DEBUG]\n%d\n", drcom_config.ror_version)); - } else if (strcmp(key, "keepalive1_mod") == 0) { - if (strcmp(value, "True") == 0) { - drcom_config.keepalive1_mod = 1; - } else { - drcom_config.keepalive1_mod = 0; - } - DEBUG_PRINT(("\n[PARSER_DEBUG]\n%d\n", drcom_config.keepalive1_mod)); - } else { - return 1; - } - - return 0; -} - -static int read_p_config(char *buf, int size) { - if (verbose_flag) { - printf("%s", buf); - } - - char *delim = " ='\r\n"; - char *delim2 = "\\x"; - char *key; - char *value; - if (strlen(key = strtok(buf, delim))) { - value = strtok(NULL, delim); - } - - if (strcmp(key, "server") == 0) { - strcpy(drcom_config.server, value); - DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.server)); - } else if (strcmp(key, "pppoe_flag") == 0) { - value = strtok(value, delim2); - sscanf(value, "%02hhx", &drcom_config.pppoe_flag); - DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.pppoe_flag)); - } else if (strcmp(key, "keep_alive2_flag") == 0) { - value = strtok(value, delim2); - sscanf(value, "%02hhx", &drcom_config.keep_alive2_flag); - DEBUG_PRINT(("\n[PARSER_DEBUG]0x%02x\n", drcom_config.keep_alive2_flag)); - } else { - return 1; - } - - return 0; -} \ No newline at end of file diff --git a/src/daemon.c b/src/daemon.c deleted file mode 100644 index dea5e98..0000000 --- a/src/daemon.c +++ /dev/null @@ -1,98 +0,0 @@ -#ifdef linux - -#include -#include -#include -#include -#include -#include -#include -#include "debug.h" - -int daemon_flag = 0; -int pid_file_handle; - -void kill_daemon() { - close(pid_file_handle); - remove("/tmp/dogcom.pid"); -} - -void signal_handler(int signal) { - switch (signal) { - case SIGHUP: - break; - case SIGINT: - break; - case SIGTERM: - kill_daemon(); - exit(0); - break; - default: - break; - } -} - -void daemonise() { - pid_t pid; - struct sigaction sig_action; - sigset_t sigset; - - pid = fork(); - if (pid < 0) { - printf("Fork failed!\n"); - exit(1); - } else if (pid > 0) { - DEBUG_PRINT(("PID is %d.\n", pid)); - exit(0); - } - if (setsid() < 0) { - printf("Setsid failed!\n"); - exit(1); - } - - sigemptyset(&sigset); - sigaddset(&sigset, SIGCHLD); - sigaddset(&sigset, SIGTSTP); - sigaddset(&sigset, SIGTTOU); - sigaddset(&sigset, SIGTTIN); - sigprocmask(SIG_BLOCK, &sigset, NULL); - sig_action.sa_handler = signal_handler; - sigemptyset(&sig_action.sa_mask); - sig_action.sa_flags = 0; - sigaction(SIGHUP, &sig_action, NULL); - sigaction(SIGTERM, &sig_action, NULL); - sigaction(SIGINT, &sig_action, NULL); - - pid = fork(); - if (pid < 0) { - printf("Fork failed!\n"); - exit(1); - } else if (pid > 0) { - DEBUG_PRINT(("PID is %d.\n", pid)); - exit(0); - } - - chdir("/tmp/"); - umask(027); - - close(STDIN_FILENO); - close(STDOUT_FILENO); - close(STDERR_FILENO); - open("/dev/null", O_RDONLY); - open("/dev/null", O_WRONLY); - open("/dev/null", O_RDWR); - - pid_file_handle = open("/tmp/dogcom.pid", O_RDWR | O_CREAT, 0600); - if (pid_file_handle < 0) { - exit(1); - } - if (lockf(pid_file_handle, F_TLOCK, 0) < 0) { - exit(1); - } - - char spid[10]; - sprintf(spid, "%d\n", getpid()); - write(pid_file_handle, spid, strlen(spid)); -} - -#endif \ No newline at end of file diff --git a/src/dhcp.cpp b/src/dhcp.cpp new file mode 100644 index 0000000..e1cb861 --- /dev/null +++ b/src/dhcp.cpp @@ -0,0 +1,105 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// +#include +#include +#include +#include +#include +#include +#include + +using boost::asio::buffer; +using boost::asio::async_read; +using boost::asio::async_write; +using boost::asio::use_awaitable; + +namespace dogcom { + +awaitable client_t::dhcp_challenge() { + size_t size = 0; + std::string chanllenge_packet{'\0', 20}; + chanllenge_packet[0] = 0x01; + chanllenge_packet[1] = 0x02; + chanllenge_packet[2] = 114 & 0xff; + chanllenge_packet[3] = 514 & 0xff; + chanllenge_packet[4] = config.auth_ver[0]; + + size = co_await async_write(socket, buffer(chanllenge_packet), use_awaitable); + BOOST_LOG_TRIVIAL(info) << std::format("Chanllenge send {} bytes", size); + + std::string buff; + size = co_await async_read(socket, buffer(buff), use_awaitable); + BOOST_LOG_TRIVIAL(info) << std::format("Chanllenge recv {} bytes", size); + + if (buff[0] != 0x02) { + BOOST_LOG_TRIVIAL(error) << std::format("Bad chanllenge: {}", buff[0]); + } else { + std::copy_n(buff.data() + 4, 4, seed.begin()); + } + + co_return; +} + +awaitable client_t::dhcp_login() { + size_t size = 0; + std::string login_packet{}; + + login_packet[0] = 0x03; + login_packet[1] = 0x01; + login_packet[2] = 0x00; + login_packet[3] = config.username.size() + 20; + + std::ranges::copy(config.username.begin(), config.username.end(), login_packet.begin() + 20); + login_packet[56] = config.CONTROLCHECKSTATUS; + login_packet[57] = config.ADAPTERNUM; + + login_packet[80] = 0x01; + std::ranges::copy(config.host_addr.begin(), config.host_addr.end(), login_packet.begin() + 81); + login_packet[105] = config.IPDOG; + std::ranges::copy(config.host_name.begin(), config.host_name.end(), login_packet.begin() + 110); + std::ranges::copy(config.dns_addr.begin(), config.dns_addr.end(), login_packet.begin() + 142); + std::ranges::copy(config.dhcp_server.begin(), config.dhcp_server.end(), login_packet.begin() + 146); + + std::array os_info_size {0x94}; + std::array os_major {0x05}; + std::array os_minor{0x01}; + std::array os_build{0x28, 0x0a}; + std::array platform{0x02}; + if (is_jlu_mode) { + os_major[0] = 0x06; + os_minor[0] = 0x02; + os_build[0] = 0xf0; + os_build[1] = 0x23; + platform[0] = 0x02; + std::array service {0x33, 0x64, 0x63, 0x37, 0x39, 0x66, 0x35, 0x32, 0x31, 0x32, 0x65, 0x38, 0x31, 0x37, 0x30, 0x61, 0x63, 0x66, 0x61, 0x39, 0x65, 0x63, 0x39, 0x35, 0x66, 0x31, 0x64, 0x37, 0x34, 0x39, 0x31, 0x36, 0x35, 0x34, 0x32, 0x62, 0x65, 0x37, 0x62, 0x31}; + std::array hostname{0x44, 0x72, 0x43, 0x4f, 0x4d, 0x00, 0xcf, 0x07, 0x68}; + std::ranges::copy(hostname.begin(), hostname.end(), login_packet.begin() + 182); + std::ranges::copy(service.begin(), service.end(), login_packet.begin() + 246); + } + std::ranges::copy(os_info_size.begin(), os_info_size.end(), login_packet.begin() + 162); + std::ranges::copy(os_major.begin(), os_major.end(), login_packet.begin() + 166); + std::ranges::copy(os_minor.begin(), os_minor.end(), login_packet.begin() + 170); + std::ranges::copy(os_build.begin(), os_build.end(), login_packet.begin() + 174); + std::ranges::copy(platform.begin(), platform.end(), login_packet.begin() + 178); + if (!is_jlu_mode) { + std::ranges::copy(config.os_ver.begin(), config.os_ver.end(), login_packet.begin() + 182); + } + std::ranges::copy_n(config.auth_ver, 2, login_packet.begin() + 310); + + size = co_await async_write(socket, buffer(login_packet), use_awaitable); + BOOST_LOG_TRIVIAL(info) << std::format("Login sent {} bytes", size); + + std::string buff; + size = co_await async_read(socket, buffer(buff), use_awaitable); + + if (buff[0] != 0x04) { + BOOST_LOG_TRIVIAL(error) << std::format("Login failed, recv {} bytes", size); + } else { + BOOST_LOG_TRIVIAL(info) << "Login succeed"; + } + co_return; +} + + +} \ No newline at end of file diff --git a/src/eapol.c b/src/eapol.c deleted file mode 100644 index 15732bd..0000000 --- a/src/eapol.c +++ /dev/null @@ -1,500 +0,0 @@ -#ifdef linux - -#include "eapol.h" -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#define BUFF_LEN (512) - -static uchar client_mac[ETH_ALEN]; - -static uchar sendbuff[BUFF_LEN]; -static uchar recvbuff[BUFF_LEN]; -static char ifname[IFNAMSIZ] = "eth0"; -static ethII_t *sendethii, *recvethii; -static eapol_t *sendeapol, *recveapol; -static eap_t *sendeap, *recveap; -static eapbody_t *sendeapbody, *recveapbody; - -static char _uname[UNAME_LEN]; -static char _pwd[PWD_LEN]; -static int pwdlen; - -static int eap_keep_alive(int skfd, struct sockaddr const *skaddr); -static int eap_md5_clg(int skfd, struct sockaddr const *skaddr); -static int eap_res_identity(int skfd, struct sockaddr const *skaddr); -static int eapol_init(int *skfd, struct sockaddr *skaddr); -static int eapol_start(int skfd, struct sockaddr const *skaddr); -static int eapol_logoff(int skfd, struct sockaddr const *skaddr); -static int filte_req_identity(int skfd, struct sockaddr const *skaddr); -static int filte_req_md5clg(int skfd, struct sockaddr const *skaddr); -static int filte_success(int skfd, struct sockaddr const *skaddr); -static int eap_daemon(int skfd, struct sockaddr const *skaddr); - -/* - * 初始化缓存区,生产套接字和地址接口信息 - * skfd: 被初始化的socket - * skaddr: 被初始化地址接口信息 - * @return: 0: 成功 - * -1: 初始化套接字失败 - * -2: 初始化地址信息失败 - */ -static int eapol_init(int *skfd, struct sockaddr *skaddr) { - struct ifreq ifr; - struct sockaddr_ll *skllp = (struct sockaddr_ll *)skaddr; - sendethii = (ethII_t *)sendbuff; - sendeapol = (eapol_t *)((uchar *)sendethii + sizeof(ethII_t)); - sendeap = (eap_t *)((uchar *)sendeapol + sizeof(eapol_t)); - sendeapbody = (eapbody_t *)((uchar *)sendeap + sizeof(eap_t)); - recvethii = (ethII_t *)recvbuff; - recveapol = (eapol_t *)((uchar *)recvethii + sizeof(ethII_t)); - recveap = (eap_t *)((uchar *)recveapol + sizeof(eapol_t)); - recveapbody = (eapbody_t *)((uchar *)recveap + sizeof(eap_t)); - - if (-1 == (*skfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)))) { - perror("Socket"); - return -1; - } - /* 先假定就是eth0接口 */ - memset(skaddr, 0, sizeof(struct sockaddr_ll)); - memset(&ifr, 0, sizeof(struct ifreq)); - strncpy(ifr.ifr_name, ifname, IFNAMSIZ); - if (-1 == ioctl(*skfd, SIOCGIFINDEX, &ifr)) { - perror("Get index"); - goto addr_err; - } - skllp->sll_ifindex = ifr.ifr_ifindex; - _D("%s's index: %d\n", ifname, skllp->sll_ifindex); - if (-1 == ioctl(*skfd, SIOCGIFHWADDR, &ifr)) { - perror("Get MAC"); - goto addr_err; - } - memcpy(client_mac, ifr.ifr_hwaddr.sa_data, ETH_ALEN); - _D("%s's MAC: %02X-%02X-%02X-%02X-%02X-%02X\n", ifname, - client_mac[0], client_mac[1], client_mac[2], - client_mac[3], client_mac[4], client_mac[5]); - skllp->sll_family = PF_PACKET; - /*skllp->sll_protocol = ETH_P_ARP;*/ - /*skllp->sll_ifindex = ? 已给出 */ - skllp->sll_hatype = ARPHRD_ETHER; - skllp->sll_pkttype = PACKET_HOST; - skllp->sll_halen = ETH_ALEN; - return 0; - -addr_err: - close(*skfd); - return -2; -} - -/* - * 过滤得到eap-request-identity包 - * @return: 0: 成功获取 - * -1: 超时 - */ -static int filte_req_identity(int skfd, struct sockaddr const *skaddr) { - (void)skaddr; - int stime = time((time_t *)NULL); - for (; difftime(time((time_t *)NULL), stime) <= TIMEOUT;) { - /* TODO 看下能不能只接受某类包,包过滤 */ - recvfrom(skfd, recvbuff, BUFF_LEN, 0, NULL, NULL); - /* eap包且是request */ - if (recvethii->type == htons(ETHII_8021X) && mac_equal(recvethii->dst_mac, client_mac) && recveapol->type == EAPOL_PACKET && recveap->code == EAP_CODE_REQ && recveap->type == EAP_TYPE_IDEN) { - return 0; - } - } - return -1; -} -/* - * 过滤得到eap-request-md5clg包 - * @return: 0: 成功获取 - * -1: 超时 - * -2: 服务器中止登录,用户名不存在 - */ -static int filte_req_md5clg(int skfd, struct sockaddr const *skaddr) { - (void)skaddr; - int stime = time((time_t *)NULL); - for (; difftime(time((time_t *)NULL), stime) <= TIMEOUT;) { - recvfrom(skfd, recvbuff, BUFF_LEN, 0, NULL, NULL); - /* 是request且是eap-request-md5clg */ - if (recvethii->type == htons(ETHII_8021X) && mac_equal(recvethii->dst_mac, client_mac) && recveapol->type == EAPOL_PACKET) { - if (recveap->code == EAP_CODE_REQ && recveap->type == EAP_TYPE_MD5) { -#ifdef DEBUG - _M("id: %d\n", sendeap->id); - _M("md5: "); - int i; - for (i = 0; i < recveapbody->md5size; ++i) - _M("%.2x", recveapbody->md5value[i]); - _M("\n"); - _M("ex-md5: "); - for (i = 0; i < ntohs(recveap->len) - recveapbody->md5size - 2; ++i) - _M("%.2x", recveapbody->md5exdata[i]); - _M("\n"); -#endif - return 0; - } else if (recveap->id == sendeap->id && recveap->code == EAP_CODE_FAIL) { - _D("id: %d fail.\n", sendeap->id); - return -2; - } - } - } - return -1; -} -/* - * 过滤得到登录成功包 - * @return: 0: 成功获取 - * -1: 超时 - * -2: 服务器中止登录,密码错误吧 - */ -static int filte_success(int skfd, struct sockaddr const *skaddr) { - (void)skaddr; - int stime = time((time_t *)NULL); - for (; difftime(time((time_t *)NULL), stime) <= TIMEOUT;) { - recvfrom(skfd, recvbuff, BUFF_LEN, 0, NULL, NULL); - if (recvethii->type == htons(ETHII_8021X) && mac_equal(recvethii->dst_mac, client_mac) && recveapol->type == EAPOL_PACKET) { - if (recveap->id == sendeap->id && recveap->code == EAP_CODE_SUCS) { - _D("id: %d login success.\n", sendeap->id); - return 0; - } else if (recveap->id == sendeap->id && recveap->code == EAP_CODE_FAIL) { - _D("id: %d fail.\n", sendeap->id); - return -2; - } - } - } - return -1; -} -/* - * 广播发送eapol-start - */ -static int eapol_start(int skfd, struct sockaddr const *skaddr) { - /* 这里采用eap标记的组播mac地址,也许采用广播也可以吧 */ - uchar broadcast_mac[ETH_ALEN] = { - // 0x01, 0x80, 0xc2, 0x00, 0x00, 0x03, - 0xff, - 0xff, - 0xff, - 0xff, - 0xff, - 0xff, - }; - memcpy(sendethii->dst_mac, broadcast_mac, ETH_ALEN); - memcpy(sendethii->src_mac, client_mac, ETH_ALEN); - sendethii->type = htons(ETHII_8021X); - sendeapol->ver = EAPOL_VER; - sendeapol->type = EAPOL_START; - sendeapol->len = 0x0; - sendto(skfd, sendbuff, ETH_ALEN * 2 + 6, 0, skaddr, sizeof(struct sockaddr_ll)); - return 0; -} -/* 退出登录 */ -static int eapol_logoff(int skfd, struct sockaddr const *skaddr) { - uchar broadcast_mac[ETH_ALEN] = { - // 0x01, 0x80, 0xc2, 0x00, 0x00, 0x03, - 0xff, - 0xff, - 0xff, - 0xff, - 0xff, - 0xff, - }; - memcpy(sendethii->dst_mac, broadcast_mac, ETH_ALEN); - memcpy(sendethii->src_mac, client_mac, ETH_ALEN); - sendethii->type = htons(ETHII_8021X); - sendeapol->ver = EAPOL_VER; - sendeapol->type = EAPOL_LOGOFF; - sendeapol->len = 0x0; - sendeap->id = EAPOL_LOGOFF_ID; - sendto(skfd, sendbuff, ETH_ALEN * 2 + 6, 0, skaddr, sizeof(struct sockaddr_ll)); - return 0; -} -/* 回应request-identity */ -static int eap_res_identity(int skfd, struct sockaddr const *skaddr) { - memcpy(sendethii->dst_mac, recvethii->src_mac, ETH_ALEN); - sendeapol->type = EAPOL_PACKET; - sendeapol->len = htons(sizeof(eap_t) + sizeof(eapbody_t)); - sendeap->code = EAP_CODE_RES; - sendeap->id = recveap->id; - sendeap->len = htons(sizeof(eapbody_t)); - sendeap->type = EAP_TYPE_IDEN; - strncpy((char *)sendeapbody->identity, _uname, UNAME_LEN); - sendto(skfd, sendbuff, ETH_ALEN * 2 + 6 + 5 + sizeof(eapbody_t), - 0, skaddr, sizeof(struct sockaddr_ll)); - return 0; -} -/* 回应md5clg */ -static int eap_md5_clg(int skfd, struct sockaddr const *skaddr) { - uchar md5buff[BUFF_LEN]; - sendeap->id = recveap->id; - sendeap->len = htons(sizeof(eapbody_t)); - sendeap->type = EAP_TYPE_MD5; - sendeapbody->md5size = recveapbody->md5size; - memcpy(md5buff, &sendeap->id, 1); - memcpy(md5buff + 1, _pwd, pwdlen); - memcpy(md5buff + 1 + pwdlen, recveapbody->md5value, recveapbody->md5size); - MD5(md5buff, 1 + pwdlen + recveapbody->md5size, sendeapbody->md5value); - memcpy((char *)sendeapbody->md5exdata, _uname, strlen(_uname)); - sendto(skfd, sendbuff, ETH_ALEN * 2 + 6 + 5 + sizeof(eapbody_t), - 0, skaddr, sizeof(struct sockaddr_ll)); - return 0; -} - -/* - * 保持在线 - * eap心跳包 - * 某些eap实现需要心跳或多次认证 - * 目前有些服务器会有如下特征 - * 每一分钟,服务端发送一个request-identity包来判断是否在线 - */ -static int eap_keep_alive(int skfd, struct sockaddr const *skaddr) { - int status; - time_t stime, etime; - /* EAP_KPALV_TIMEOUT时间内已经不再有心跳包,我们认为服务器不再需要心跳包了 */ - //for (; difftime(time((time_t*)NULL), stime) <= EAP_KPALV_TIMEOUT; ) { - stime = time((time_t *)NULL); - for (;;) { - status = filte_req_identity(skfd, skaddr); - //_D("%s: [EAP:KPALV] get status: %d\n", format_time(), status); - if (0 == status) { - etime = time((time_t *)NULL); - _D("dtime: %fs\n", difftime(etime, stime)); - if (difftime(etime, stime) <= 10) { - stime = time((time_t *)NULL); - continue; - } - stime = time((time_t *)NULL); -#if 0 -#ifdef DEBUG - _D("[KPALV] get eap request identity:\n"); - _D("dst<-src: %2X:%2X:%2X:%2X:%2X:%2X <- %2X:%2X:%2X:%2X:%2X:%2X\n", - recvethii->dst_mac[0], recvethii->dst_mac[1], recvethii->dst_mac[2], - recvethii->dst_mac[3], recvethii->dst_mac[4], recvethii->dst_mac[5], - recvethii->src_mac[0], recvethii->src_mac[1], recvethii->src_mac[2], - recvethii->src_mac[3], recvethii->src_mac[4], recvethii->src_mac[5]); - _D("ethII.type: 0x%4x\n", ntohs(recvethii->type)); - _D("recveapol.type: %s\n", recveapol->type==EAPOL_PACKET?"EAPOL_PACKET":"UNKNOWN"); - _D("recveapol.len: %d\n", ntohs(recveapol->len)); - _D("recveap.code: %s\n", recveap->code==EAP_CODE_REQ?"EAP_CODE_REQ":"UNKNOWN"); - _D("recveap.id: %d\n", recveap->id); - _D("recveap.type: %s\n", recveap->type==EAP_TYPE_IDEN?"EAP_TYPE_IDEN":"UNKNOWN"); -#endif -#endif - _M("%s: [EAP:KPALV] get a request-identity\n", format_time()); - eap_res_identity(skfd, skaddr); -#if 0 -#ifdef DEBUG - _D("[EAP:KPALV] send eap response identity:\n"); - _D("dst<-src: %2X:%2X:%2X:%2X:%2X:%2X <- %2X:%2X:%2X:%2X:%2X:%2X\n", - sendethii->dst_mac[0], sendethii->dst_mac[1], sendethii->dst_mac[2], - sendethii->dst_mac[3], sendethii->dst_mac[4], sendethii->dst_mac[5], - sendethii->src_mac[0], sendethii->src_mac[1], sendethii->src_mac[2], - sendethii->src_mac[3], sendethii->src_mac[4], sendethii->src_mac[5]); - _D("ethII.type: 0x%4x\n", ntohs(sendethii->type)); - _D("sendeapol.type: %s\n", sendeapol->type==EAPOL_PACKET?"EAPOL_PACKET":"UNKNOWN"); - _D("sendeapol.len: %d\n", ntohs(sendeapol->len)); - _D("sendeap.code: %s\n", sendeap->code==EAP_CODE_RES?"EAP_CODE_RES":"UNKNOWN"); - _D("sendeap.id: %d\n", sendeap->id); - _D("sendeap.type: %s\n", sendeap->type==EAP_TYPE_IDEN?"EAP_TYPE_IDEN":"UNKNOWN"); - _D("sendeapbody.identity: %s\n", sendeapbody->identity); -#endif -#endif - } - status = -1; - } - return 0; -} -/* - * 后台心跳进程 - * @return: 0, 正常运行 - * -1, 运行失败 - */ -static int eap_daemon(int skfd, struct sockaddr const *skaddr) { - /* 如果存在原来的keep alive进程,就干掉他 */ -#define PID_FILE "/tmp/cwnu-drcom-eap.pid" - FILE *kpalvfd = fopen(PID_FILE, "r+"); - if (NULL == kpalvfd) { - _M("[EAP:KPALV] No process pidfile. %s: %s\n", PID_FILE, strerror(errno)); - kpalvfd = fopen(PID_FILE, "w+"); /* 不存在,创建 */ - if (NULL == kpalvfd) { - _M("[EAP:KPALV] Detect pid file eror(%s)! quit!\n", strerror(errno)); - return -1; - } - } - pid_t oldpid; - - fseek(kpalvfd, 0L, SEEK_SET); - if ((1 == fscanf(kpalvfd, "%d", (int *)&oldpid)) && (oldpid != (pid_t)-1)) { - _D("oldkpalv pid: %d\n", oldpid); - kill(oldpid, SIGKILL); - } - setsid(); - if (0 != chdir("/")) - _M("[EAP:KPALV:WARN] %s\n", strerror(errno)); - umask(0); - /* 在/tmp下写入自己(keep alive)pid */ - pid_t curpid = getpid(); - _D("kpalv curpid: %d\n", curpid); - /* - * if (0 != ftruncate(fileno(kpalvfd), 0)) - * 这个写法有时不能正常截断文件,截断后前面有\0? - */ - if (NULL == (kpalvfd = freopen(PID_FILE, "w+", kpalvfd))) - _M("[EAP:KPALV:WARN] truncat pidfile '%s': %s\n", PID_FILE, strerror(errno)); - fprintf(kpalvfd, "%d", curpid); - fflush(kpalvfd); - if (0 == eap_keep_alive(skfd, skaddr)) { - _M("%s: [EAP:KPALV] Server maybe not need keep alive paket.\n", format_time()); - _M("%s: [EAP:KPALV] Now, keep alive process quit!\n", format_time()); - } - if (NULL == (kpalvfd = freopen(PID_FILE, "w+", kpalvfd))) - _M("[EAP:KPALV:WARN] truncat pidfile '%s': %s\n", PID_FILE, strerror(errno)); - fprintf(kpalvfd, "-1"); /* 写入-1表示已经离开 */ - fflush(kpalvfd); - fclose(kpalvfd); - - return 0; -} - -/* - * eap认证 - * uname: 用户名 - * pwd: 密码 - * @return: 0: 成功 - * 1: 用户不存在 - * 2: 密码错误 - * 3: 其他超时 - * 4: 服务器拒绝请求登录 - * -1: 没有找到合适网络接口 - * -2: 没有找到服务器 - */ -int eaplogin(char const *uname, char const *pwd) { - int i; - int state; - int skfd; - struct sockaddr_ll ll; - - _M("Use user '%s' to login...\n", uname); - _M("[EAP:0] Initilize interface...\n"); - strncpy(_uname, uname, UNAME_LEN); - strncpy(_pwd, pwd, PWD_LEN); - pwdlen = strlen(_pwd); - if (0 != eapol_init(&skfd, (struct sockaddr *)&ll)) - return -1; - /* 无论如何先请求一下下线 */ - eapol_logoff(skfd, (struct sockaddr *)&ll); - /* eap-start */ - _M("[EAP:1] Send eap-start...\n"); - for (i = 0; i < TRY_TIMES; ++i) { - eapol_start(skfd, (struct sockaddr *)&ll); - if (0 == filte_req_identity(skfd, (struct sockaddr *)&ll)) - break; - _M(" [EAP:1] %dth Try send eap-start...\n", i + 1); - } - if (i >= TRY_TIMES) goto _timeout; - - /* response-identity */ - _M("[EAP:2] Send response-identity...\n"); - for (i = 0; i < TRY_TIMES; ++i) { - eap_res_identity(skfd, (struct sockaddr *)&ll); - state = filte_req_md5clg(skfd, (struct sockaddr *)&ll); - if (0 == state) - break; - else if (-2 == state) - goto _no_uname; - _M(" [EAP:2] %dth Try send response-identity...\n", i + 1); - } - if (i >= TRY_TIMES) goto _timeout; - - /* response-md5clg */ - _M("[EAP:3] Send response-md5clg...\n"); - for (i = 0; i < TRY_TIMES; ++i) { - eap_md5_clg(skfd, (struct sockaddr *)&ll); - state = filte_success(skfd, (struct sockaddr *)&ll); - if (0 == state) { - _M("[EAP:4] Login success.\n"); - break; /* 登录成功 */ - } else if (-2 == state) - goto _pwd_err; - _M(" [EAP:3] %dth Try send response-md5clg...\n", i + 1); - } - if (i >= TRY_TIMES) goto _timeout; - - /* 登录成功,生成心跳进程 */ - switch (fork()) { - case 0: - if (0 != eap_daemon(skfd, (struct sockaddr *)&ll)) { - _M("[EAP:ERROR] Create daemon process to keep alive error!\n"); - close(skfd); - exit(1); - } - exit(0); - break; - case -1: - _M("[EAP:WARN] Cant create daemon, maybe `OFFLINE` after soon.\n"); - } - close(skfd); - return 0; - -_timeout: - _M("[EAP:ERROR] Not server in range.\n"); - close(skfd); - return -2; -_no_uname: - _M("[EAP:ERROR] No this user(%s).\n", uname); - close(skfd); - return 1; -_pwd_err: - _M("[EAP:ERROR] The server refuse to login. Password error.\n"); - close(skfd); - return 4; -} - -int eaplogoff(void) { - int skfd; - struct sockaddr_ll ll; - int state; - int i; - - _M("[EAP:0] Initilize interface...\n"); - if (0 != eapol_init(&skfd, (struct sockaddr *)&ll)) - return -1; - _M("[EAP:1] Requset logoff...\n"); - for (i = 0; i < TRY_TIMES; ++i) { - eapol_logoff(skfd, (struct sockaddr *)&ll); - state = filte_success(skfd, (struct sockaddr *)&ll); - if (-2 == state) { - _M("[EAP:2] Logoff!\n"); - return 0; - } - _M(" [EAP:1] %dth Try Requset logoff...\n", i + 1); - } - _M("[EAP:ERROR] Not server in range. or You were logoff.\n"); - return -1; -} - -int eaprefresh(char const *uname, char const *pwd) { - return eaplogin(uname, pwd); -} - -/* 设置ifname */ -void setifname(char const *_ifname) { - strncpy(ifname, _ifname, IFNAMSIZ); -} - -#endif \ No newline at end of file diff --git a/src/eapol.cpp b/src/eapol.cpp new file mode 100644 index 0000000..4461886 --- /dev/null +++ b/src/eapol.cpp @@ -0,0 +1,21 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// +#include + +namespace dogcom { + +awaitable client_t::eap_login() { + throw std::runtime_error("Not Implemented"); +} + +awaitable client_t::eap_fresh() { + throw std::runtime_error("Not Implemented"); +} + +awaitable client_t::eap_set_ifname() { + throw std::runtime_error("Not Implemented"); +} + + +} \ No newline at end of file diff --git a/src/getopt4win.c b/src/getopt4win.c deleted file mode 100644 index 3940758..0000000 --- a/src/getopt4win.c +++ /dev/null @@ -1,1274 +0,0 @@ -/* Getopt for GNU. -NOTE: getopt is now part of the C library, so if you don't know what -"Keep this file name-space clean" means, talk to drepper@gnu.org -before changing it! -Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001 -Free Software Foundation, Inc. -This file is part of the GNU C Library. - -The GNU C Library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -The GNU C Library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with the GNU C Library; if not, write to the Free -Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA -02111-1307 USA. */ - -/* This tells Alpha OSF/1 not to define a getopt prototype in . -Ditto for AIX 3.2 and . */ -#ifndef _NO_PROTO -# define _NO_PROTO -#endif - -#ifdef HAVE_CONFIG_H -# include -#endif - -#if !defined __STDC__ || !__STDC__ -/* This is a separate conditional since some stdc systems -reject `defined (const)'. */ -# ifndef const -# define const -# endif -#endif - -#include - -/* Comment out all this code if we are using the GNU C Library, and are not -actually compiling the library itself. This code is part of the GNU C -Library, but also included in many other GNU distributions. Compiling -and linking in this code is a waste when using the GNU C library -(especially if it is a shared library). Rather than having every GNU -program understand `configure --with-gnu-libc' and omit the object files, -it is simpler to just do this in the source for each such file. */ - -#define GETOPT_INTERFACE_VERSION 2 -#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 -# include -# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION -# define ELIDE_CODE -# endif -#endif - -#ifndef ELIDE_CODE - - -/* This needs to come after some library #include -to get __GNU_LIBRARY__ defined. */ -#ifdef __GNU_LIBRARY__ -/* Don't include stdlib.h for non-GNU C libraries because some of them -contain conflicting prototypes for getopt. */ -# include -# include -#endif /* GNU C library. */ - -#ifdef VMS -# include -# if HAVE_STRING_H - 0 -# include -# endif -#endif - -#ifndef _ -/* This is for other GNU distributions with internationalized messages. */ -# if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC -# include -# ifndef _ -# define _(msgid) gettext (msgid) -# endif -# else -# define _(msgid) (msgid) -# endif -# if defined _LIBC && defined USE_IN_LIBIO -# include -# endif -#endif - -/* This version of `getopt' appears to the caller like standard Unix `getopt' -but it behaves differently for the user, since it allows the user -to intersperse the options with the other arguments. - -As `getopt' works, it permutes the elements of ARGV so that, -when it is done, all the options precede everything else. Thus -all application programs are extended to handle flexible argument order. - -Setting the environment variable POSIXLY_CORRECT disables permutation. -Then the behavior is completely standard. - -GNU application programs can use a third alternative mode in which -they can distinguish the relative order of options and other arguments. */ - -#include "libs/getopt4win.h" - -/* For communication from `getopt' to the caller. -When `getopt' finds an option that takes an argument, -the argument value is returned here. -Also, when `ordering' is RETURN_IN_ORDER, -each non-option ARGV-element is returned here. */ - -char *optarg; - -/* Index in ARGV of the next element to be scanned. -This is used for communication to and from the caller -and for communication between successive calls to `getopt'. - -On entry to `getopt', zero means this is the first call; initialize. - -When `getopt' returns -1, this is the index of the first of the -non-option elements that the caller should itself scan. - -Otherwise, `optind' communicates from one call to the next -how much of ARGV has been scanned so far. */ - -/* 1003.2 says this must be 1 before any call. */ -int optind = 1; - -/* Formerly, initialization of getopt depended on optind==0, which -causes problems with re-calling getopt as programs generally don't -know that. */ - -int __getopt_initialized; - -/* The next char to be scanned in the option-element -in which the last option character we returned was found. -This allows us to pick up the scan where we left off. - -If this is zero, or a null string, it means resume the scan -by advancing to the next ARGV-element. */ - -static char *nextchar; - -/* Callers store zero here to inhibit the error message -for unrecognized options. */ - -int opterr = 1; - -/* Set to an option character which was unrecognized. -This must be initialized on some systems to avoid linking in the -system's own getopt implementation. */ - -int optopt = '?'; - -/* Describe how to deal with options that follow non-option ARGV-elements. - -If the caller did not specify anything, -the default is REQUIRE_ORDER if the environment variable -POSIXLY_CORRECT is defined, PERMUTE otherwise. - -REQUIRE_ORDER means don't recognize them as options; -stop option processing when the first non-option is seen. -This is what Unix does. -This mode of operation is selected by either setting the environment -variable POSIXLY_CORRECT, or using `+' as the first character -of the list of option characters. - -PERMUTE is the default. We permute the contents of ARGV as we scan, -so that eventually all the non-options are at the end. This allows options -to be given in any order, even with programs that were not written to -expect this. - -RETURN_IN_ORDER is an option available to programs that were written -to expect options and other ARGV-elements in any order and that care about -the ordering of the two. We describe each non-option ARGV-element -as if it were the argument of an option with character code 1. -Using `-' as the first character of the list of option characters -selects this mode of operation. - -The special argument `--' forces an end of option-scanning regardless -of the value of `ordering'. In the case of RETURN_IN_ORDER, only -`--' can cause `getopt' to return -1 with `optind' != ARGC. */ - -static enum -{ - REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER -} ordering; - -/* Value of POSIXLY_CORRECT environment variable. */ -static char *posixly_correct; - -#ifdef __GNU_LIBRARY__ -/* We want to avoid inclusion of string.h with non-GNU libraries -because there are many ways it can cause trouble. -On some systems, it contains special magic macros that don't work -in GCC. */ -# include -# define my_index strchr -#else - -#define HAVE_STRING_H 1 -# if HAVE_STRING_H -# include -# else -# include -# endif - -/* Avoid depending on library functions or files -whose names are inconsistent. */ - -#ifndef getenv -extern char *getenv(); -#endif - -static char * -my_index(str, chr) -const char *str; -int chr; -{ - while (*str) - { - if (*str == chr) - return (char *)str; - str++; - } - return 0; -} - -/* If using GCC, we can safely declare strlen this way. -If not using GCC, it is ok not to declare it. */ -#ifdef __GNUC__ -/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. -That was relevant to code that was here before. */ -# if (!defined __STDC__ || !__STDC__) && !defined strlen -/* gcc with -traditional declares the built-in strlen to return int, -and has done so at least since version 2.4.5. -- rms. */ -extern int strlen(const char *); -# endif /* not __STDC__ */ -#endif /* __GNUC__ */ - -#endif /* not __GNU_LIBRARY__ */ - -/* Handle permutation of arguments. */ - -/* Describe the part of ARGV that contains non-options that have -been skipped. `first_nonopt' is the index in ARGV of the first of them; -`last_nonopt' is the index after the last of them. */ - -static int first_nonopt; -static int last_nonopt; - -#ifdef _LIBC -/* Stored original parameters. -XXX This is no good solution. We should rather copy the args so -that we can compare them later. But we must not use malloc(3). */ -extern int __libc_argc; -extern char **__libc_argv; - -/* Bash 2.0 gives us an environment variable containing flags -indicating ARGV elements that should not be considered arguments. */ - -# ifdef USE_NONOPTION_FLAGS -/* Defined in getopt_init.c */ -extern char *__getopt_nonoption_flags; - -static int nonoption_flags_max_len; -static int nonoption_flags_len; -# endif - -# ifdef USE_NONOPTION_FLAGS -# define SWAP_FLAGS(ch1, ch2) \ -if (nonoption_flags_len > 0) \ -{ \ - char __tmp = __getopt_nonoption_flags[ch1]; \ - __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ - __getopt_nonoption_flags[ch2] = __tmp; \ -} -# else -# define SWAP_FLAGS(ch1, ch2) -# endif -#else /* !_LIBC */ -# define SWAP_FLAGS(ch1, ch2) -#endif /* _LIBC */ - -/* Exchange two adjacent subsequences of ARGV. -One subsequence is elements [first_nonopt,last_nonopt) -which contains all the non-options that have been skipped so far. -The other is elements [last_nonopt,optind), which contains all -the options processed since those non-options were skipped. - -`first_nonopt' and `last_nonopt' are relocated so that they describe -the new indices of the non-options in ARGV after they are moved. */ - -#if defined __STDC__ && __STDC__ -static void exchange(char **); -#endif - -static void -exchange(argv) -char **argv; -{ - int bottom = first_nonopt; - int middle = last_nonopt; - int top = optind; - char *tem; - - /* Exchange the shorter segment with the far end of the longer segment. - That puts the shorter segment into the right place. - It leaves the longer segment in the right place overall, - but it consists of two parts that need to be swapped next. */ - -#if defined _LIBC && defined USE_NONOPTION_FLAGS - /* First make sure the handling of the `__getopt_nonoption_flags' - string can work normally. Our top argument must be in the range - of the string. */ - if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) - { - /* We must extend the array. The user plays games with us and - presents new arguments. */ - char *new_str = malloc(top + 1); - if (new_str == NULL) - nonoption_flags_len = nonoption_flags_max_len = 0; - else - { - memset(__mempcpy(new_str, __getopt_nonoption_flags, - nonoption_flags_max_len), - '\0', top + 1 - nonoption_flags_max_len); - nonoption_flags_max_len = top + 1; - __getopt_nonoption_flags = new_str; - } - } -#endif - - while (top > middle && middle > bottom) - { - if (top - middle > middle - bottom) - { - /* Bottom segment is the short one. */ - int len = middle - bottom; - register int i; - - /* Swap it with the top part of the top segment. */ - for (i = 0; i < len; i++) - { - tem = argv[bottom + i]; - argv[bottom + i] = argv[top - (middle - bottom) + i]; - argv[top - (middle - bottom) + i] = tem; - SWAP_FLAGS(bottom + i, top - (middle - bottom) + i); - } - /* Exclude the moved bottom segment from further swapping. */ - top -= len; - } - else - { - /* Top segment is the short one. */ - int len = top - middle; - register int i; - - /* Swap it with the bottom part of the bottom segment. */ - for (i = 0; i < len; i++) - { - tem = argv[bottom + i]; - argv[bottom + i] = argv[middle + i]; - argv[middle + i] = tem; - SWAP_FLAGS(bottom + i, middle + i); - } - /* Exclude the moved top segment from further swapping. */ - bottom += len; - } - } - - /* Update records for the slots the non-options now occupy. */ - - first_nonopt += (optind - last_nonopt); - last_nonopt = optind; -} - -/* Initialize the internal data when the first call is made. */ - -#if defined __STDC__ && __STDC__ -static const char *_getopt_initialize(int, char *const *, const char *); -#endif -static const char * -_getopt_initialize(argc, argv, optstring) -int argc; -char *const *argv; -const char *optstring; -{ - /* Start processing options with ARGV-element 1 (since ARGV-element 0 - is the program name); the sequence of previously skipped - non-option ARGV-elements is empty. */ - - first_nonopt = last_nonopt = optind; - - nextchar = NULL; - - posixly_correct = getenv("POSIXLY_CORRECT"); - - /* Determine how to handle the ordering of options and nonoptions. */ - - if (optstring[0] == '-') - { - ordering = RETURN_IN_ORDER; - ++optstring; - } - else if (optstring[0] == '+') - { - ordering = REQUIRE_ORDER; - ++optstring; - } - else if (posixly_correct != NULL) - ordering = REQUIRE_ORDER; - else - ordering = PERMUTE; - -#if defined _LIBC && defined USE_NONOPTION_FLAGS - if (posixly_correct == NULL - && argc == __libc_argc && argv == __libc_argv) - { - if (nonoption_flags_max_len == 0) - { - if (__getopt_nonoption_flags == NULL - || __getopt_nonoption_flags[0] == '\0') - nonoption_flags_max_len = -1; - else - { - const char *orig_str = __getopt_nonoption_flags; - int len = nonoption_flags_max_len = strlen(orig_str); - if (nonoption_flags_max_len < argc) - nonoption_flags_max_len = argc; - __getopt_nonoption_flags = - (char *)malloc(nonoption_flags_max_len); - if (__getopt_nonoption_flags == NULL) - nonoption_flags_max_len = -1; - else - memset(__mempcpy(__getopt_nonoption_flags, orig_str, len), - '\0', nonoption_flags_max_len - len); - } - } - nonoption_flags_len = nonoption_flags_max_len; - } - else - nonoption_flags_len = 0; -#endif - - return optstring; -} - -/* Scan elements of ARGV (whose length is ARGC) for option characters -given in OPTSTRING. - -If an element of ARGV starts with '-', and is not exactly "-" or "--", -then it is an option element. The characters of this element -(aside from the initial '-') are option characters. If `getopt' -is called repeatedly, it returns successively each of the option characters -from each of the option elements. - -If `getopt' finds another option character, it returns that character, -updating `optind' and `nextchar' so that the next call to `getopt' can -resume the scan with the following option character or ARGV-element. - -If there are no more option characters, `getopt' returns -1. -Then `optind' is the index in ARGV of the first ARGV-element -that is not an option. (The ARGV-elements have been permuted -so that those that are not options now come last.) - -OPTSTRING is a string containing the legitimate option characters. -If an option character is seen that is not listed in OPTSTRING, -return '?' after printing an error message. If you set `opterr' to -zero, the error message is suppressed but we still return '?'. - -If a char in OPTSTRING is followed by a colon, that means it wants an arg, -so the following text in the same ARGV-element, or the text of the following -ARGV-element, is returned in `optarg'. Two colons mean an option that -wants an optional arg; if there is text in the current ARGV-element, -it is returned in `optarg', otherwise `optarg' is set to zero. - -If OPTSTRING starts with `-' or `+', it requests different methods of -handling the non-option ARGV-elements. -See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. - -Long-named options begin with `--' instead of `-'. -Their names may be abbreviated as long as the abbreviation is unique -or is an exact match for some defined option. If they have an -argument, it follows the option name in the same ARGV-element, separated -from the option name by a `=', or else the in next ARGV-element. -When `getopt' finds a long-named option, it returns 0 if that option's -`flag' field is nonzero, the value of the option's `val' field -if the `flag' field is zero. - -The elements of ARGV aren't really const, because we permute them. -But we pretend they're const in the prototype to be compatible -with other systems. - -LONGOPTS is a vector of `struct option' terminated by an -element containing a name which is zero. - -LONGIND returns the index in LONGOPT of the long-named option found. -It is only valid when a long-named option has been found by the most -recent call. - -If LONG_ONLY is nonzero, '-' as well as '--' can introduce -long-named options. */ - -int -_getopt_internal(argc, argv, optstring, longopts, longind, long_only) -int argc; -char *const *argv; -const char *optstring; -const struct option *longopts; -int *longind; -int long_only; -{ - int print_errors = opterr; - if (optstring[0] == ':') - print_errors = 0; - - if (argc < 1) - return -1; - - optarg = NULL; - - if (optind == 0 || !__getopt_initialized) - { - if (optind == 0) - optind = 1; /* Don't scan ARGV[0], the program name. */ - optstring = _getopt_initialize(argc, argv, optstring); - __getopt_initialized = 1; - } - - /* Test whether ARGV[optind] points to a non-option argument. - Either it does not have option syntax, or there is an environment flag - from the shell indicating it is not an option. The later information - is only used when the used in the GNU libc. */ -#if defined _LIBC && defined USE_NONOPTION_FLAGS -# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ - || (optind < nonoption_flags_len \ - && __getopt_nonoption_flags[optind] == '1')) -#else -# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') -#endif - - if (nextchar == NULL || *nextchar == '\0') - { - /* Advance to the next ARGV-element. */ - - /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been - moved back by the user (who may also have changed the arguments). */ - if (last_nonopt > optind) - last_nonopt = optind; - if (first_nonopt > optind) - first_nonopt = optind; - - if (ordering == PERMUTE) - { - /* If we have just processed some options following some non-options, - exchange them so that the options come first. */ - - if (first_nonopt != last_nonopt && last_nonopt != optind) - exchange((char **)argv); - else if (last_nonopt != optind) - first_nonopt = optind; - - /* Skip any additional non-options - and extend the range of non-options previously skipped. */ - - while (optind < argc && NONOPTION_P) - optind++; - last_nonopt = optind; - } - - /* The special ARGV-element `--' means premature end of options. - Skip it like a null option, - then exchange with previous non-options as if it were an option, - then skip everything else like a non-option. */ - - if (optind != argc && !strcmp(argv[optind], "--")) - { - optind++; - - if (first_nonopt != last_nonopt && last_nonopt != optind) - exchange((char **)argv); - else if (first_nonopt == last_nonopt) - first_nonopt = optind; - last_nonopt = argc; - - optind = argc; - } - - /* If we have done all the ARGV-elements, stop the scan - and back over any non-options that we skipped and permuted. */ - - if (optind == argc) - { - /* Set the next-arg-index to point at the non-options - that we previously skipped, so the caller will digest them. */ - if (first_nonopt != last_nonopt) - optind = first_nonopt; - return -1; - } - - /* If we have come to a non-option and did not permute it, - either stop the scan or describe it to the caller and pass it by. */ - - if (NONOPTION_P) - { - if (ordering == REQUIRE_ORDER) - return -1; - optarg = argv[optind++]; - return 1; - } - - /* We have found another option-ARGV-element. - Skip the initial punctuation. */ - - nextchar = (argv[optind] + 1 - + (longopts != NULL && argv[optind][1] == '-')); - } - - /* Decode the current option-ARGV-element. */ - - /* Check whether the ARGV-element is a long option. - - If long_only and the ARGV-element has the form "-f", where f is - a valid short option, don't consider it an abbreviated form of - a long option that starts with f. Otherwise there would be no - way to give the -f short option. - - On the other hand, if there's a long option "fubar" and - the ARGV-element is "-fu", do consider that an abbreviation of - the long option, just like "--fu", and not "-f" with arg "u". - - This distinction seems to be the most useful approach. */ - - if (longopts != NULL - && (argv[optind][1] == '-' - || (long_only && (argv[optind][2] || !my_index(optstring, argv[optind][1]))))) - { - char *nameend; - const struct option *p; - const struct option *pfound = NULL; - int exact = 0; - int ambig = 0; - int indfound = -1; - int option_index; - - for (nameend = nextchar; *nameend && *nameend != '='; nameend++) - /* Do nothing. */; - - /* Test all long options for either exact match - or abbreviated matches. */ - for (p = longopts, option_index = 0; p->name; p++, option_index++) - if (!strncmp(p->name, nextchar, nameend - nextchar)) - { - if ((unsigned int)(nameend - nextchar) - == (unsigned int)strlen(p->name)) - { - /* Exact match found. */ - pfound = p; - indfound = option_index; - exact = 1; - break; - } - else if (pfound == NULL) - { - /* First nonexact match found. */ - pfound = p; - indfound = option_index; - } - else if (long_only - || pfound->has_arg != p->has_arg - || pfound->flag != p->flag - || pfound->val != p->val) - /* Second or later nonexact match found. */ - ambig = 1; - } - - if (ambig && !exact) - { - if (print_errors) - { -#if defined _LIBC && defined USE_IN_LIBIO - char *buf; - - __asprintf(&buf, _("%s: option `%s' is ambiguous\n"), - argv[0], argv[optind]); - - if (_IO_fwide(stderr, 0) > 0) - __fwprintf(stderr, L"%s", buf); - else - fputs(buf, stderr); - - free(buf); -#else - fprintf(stderr, _("%s: option `%s' is ambiguous\n"), - argv[0], argv[optind]); -#endif - } - nextchar += strlen(nextchar); - optind++; - optopt = 0; - return '?'; - } - - if (pfound != NULL) - { - option_index = indfound; - optind++; - if (*nameend) - { - /* Don't test has_arg with >, because some C compilers don't - allow it to be used on enums. */ - if (pfound->has_arg) - optarg = nameend + 1; - else - { - if (print_errors) - { -#if defined _LIBC && defined USE_IN_LIBIO - char *buf; -#endif - - if (argv[optind - 1][1] == '-') - { - /* --option */ -#if defined _LIBC && defined USE_IN_LIBIO - __asprintf(&buf, _("\ - %s: option `--%s' doesn't allow an argument\n"), - argv[0], pfound->name); -#else - fprintf(stderr, _("\ - %s: option `--%s' doesn't allow an argument\n"), - argv[0], pfound->name); -#endif - } - else - { - /* +option or -option */ -#if defined _LIBC && defined USE_IN_LIBIO - __asprintf(&buf, _("\ - %s: option `%c%s' doesn't allow an argument\n"), - argv[0], argv[optind - 1][0], - pfound->name); -#else - fprintf(stderr, _("\ - %s: option `%c%s' doesn't allow an argument\n"), - argv[0], argv[optind - 1][0], pfound->name); -#endif - } - -#if defined _LIBC && defined USE_IN_LIBIO - if (_IO_fwide(stderr, 0) > 0) - __fwprintf(stderr, L"%s", buf); - else - fputs(buf, stderr); - - free(buf); -#endif - } - - nextchar += strlen(nextchar); - - optopt = pfound->val; - return '?'; - } - } - else if (pfound->has_arg == 1) - { - if (optind < argc) - optarg = argv[optind++]; - else - { - if (print_errors) - { -#if defined _LIBC && defined USE_IN_LIBIO - char *buf; - - __asprintf(&buf, - _("%s: option `%s' requires an argument\n"), - argv[0], argv[optind - 1]); - - if (_IO_fwide(stderr, 0) > 0) - __fwprintf(stderr, L"%s", buf); - else - fputs(buf, stderr); - - free(buf); -#else - fprintf(stderr, - _("%s: option `%s' requires an argument\n"), - argv[0], argv[optind - 1]); -#endif - } - nextchar += strlen(nextchar); - optopt = pfound->val; - return optstring[0] == ':' ? ':' : '?'; - } - } - nextchar += strlen(nextchar); - if (longind != NULL) - *longind = option_index; - if (pfound->flag) - { - *(pfound->flag) = pfound->val; - return 0; - } - return pfound->val; - } - - /* Can't find it as a long option. If this is not getopt_long_only, - or the option starts with '--' or is not a valid short - option, then it's an error. - Otherwise interpret it as a short option. */ - if (!long_only || argv[optind][1] == '-' - || my_index(optstring, *nextchar) == NULL) - { - if (print_errors) - { -#if defined _LIBC && defined USE_IN_LIBIO - char *buf; -#endif - - if (argv[optind][1] == '-') - { - /* --option */ -#if defined _LIBC && defined USE_IN_LIBIO - __asprintf(&buf, _("%s: unrecognized option `--%s'\n"), - argv[0], nextchar); -#else - fprintf(stderr, _("%s: unrecognized option `--%s'\n"), - argv[0], nextchar); -#endif - } - else - { - /* +option or -option */ -#if defined _LIBC && defined USE_IN_LIBIO - __asprintf(&buf, _("%s: unrecognized option `%c%s'\n"), - argv[0], argv[optind][0], nextchar); -#else - fprintf(stderr, _("%s: unrecognized option `%c%s'\n"), - argv[0], argv[optind][0], nextchar); -#endif - } - -#if defined _LIBC && defined USE_IN_LIBIO - if (_IO_fwide(stderr, 0) > 0) - __fwprintf(stderr, L"%s", buf); - else - fputs(buf, stderr); - - free(buf); -#endif - } - nextchar = (char *) ""; - optind++; - optopt = 0; - return '?'; - } - } - - /* Look at and handle the next short option-character. */ - - { - char c = *nextchar++; - char *temp = my_index(optstring, c); - - /* Increment `optind' when we start to process its last character. */ - if (*nextchar == '\0') - ++optind; - - if (temp == NULL || c == ':') - { - if (print_errors) - { -#if defined _LIBC && defined USE_IN_LIBIO - char *buf; -#endif - - if (posixly_correct) - { - /* 1003.2 specifies the format of this message. */ -#if defined _LIBC && defined USE_IN_LIBIO - __asprintf(&buf, _("%s: illegal option -- %c\n"), - argv[0], c); -#else - fprintf(stderr, _("%s: illegal option -- %c\n"), argv[0], c); -#endif - } - else - { -#if defined _LIBC && defined USE_IN_LIBIO - __asprintf(&buf, _("%s: invalid option -- %c\n"), - argv[0], c); -#else - fprintf(stderr, _("%s: invalid option -- %c\n"), argv[0], c); -#endif - } - -#if defined _LIBC && defined USE_IN_LIBIO - if (_IO_fwide(stderr, 0) > 0) - __fwprintf(stderr, L"%s", buf); - else - fputs(buf, stderr); - - free(buf); -#endif - } - optopt = c; - return '?'; - } - /* Convenience. Treat POSIX -W foo same as long option --foo */ - if (temp[0] == 'W' && temp[1] == ';') - { - char *nameend; - const struct option *p; - const struct option *pfound = NULL; - int exact = 0; - int ambig = 0; - int indfound = 0; - int option_index; - - /* This is an option that requires an argument. */ - if (*nextchar != '\0') - { - optarg = nextchar; - /* If we end this ARGV-element by taking the rest as an arg, - we must advance to the next element now. */ - optind++; - } - else if (optind == argc) - { - if (print_errors) - { - /* 1003.2 specifies the format of this message. */ -#if defined _LIBC && defined USE_IN_LIBIO - char *buf; - - __asprintf(&buf, _("%s: option requires an argument -- %c\n"), - argv[0], c); - - if (_IO_fwide(stderr, 0) > 0) - __fwprintf(stderr, L"%s", buf); - else - fputs(buf, stderr); - - free(buf); -#else - fprintf(stderr, _("%s: option requires an argument -- %c\n"), - argv[0], c); -#endif - } - optopt = c; - if (optstring[0] == ':') - c = ':'; - else - c = '?'; - return c; - } - else - /* We already incremented `optind' once; - increment it again when taking next ARGV-elt as argument. */ - optarg = argv[optind++]; - - /* optarg is now the argument, see if it's in the - table of longopts. */ - - for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) - /* Do nothing. */; - - /* Test all long options for either exact match - or abbreviated matches. */ - for (p = longopts, option_index = 0; p->name; p++, option_index++) - if (!strncmp(p->name, nextchar, nameend - nextchar)) - { - if ((unsigned int)(nameend - nextchar) == strlen(p->name)) - { - /* Exact match found. */ - pfound = p; - indfound = option_index; - exact = 1; - break; - } - else if (pfound == NULL) - { - /* First nonexact match found. */ - pfound = p; - indfound = option_index; - } - else - /* Second or later nonexact match found. */ - ambig = 1; - } - if (ambig && !exact) - { - if (print_errors) - { -#if defined _LIBC && defined USE_IN_LIBIO - char *buf; - - __asprintf(&buf, _("%s: option `-W %s' is ambiguous\n"), - argv[0], argv[optind]); - - if (_IO_fwide(stderr, 0) > 0) - __fwprintf(stderr, L"%s", buf); - else - fputs(buf, stderr); - - free(buf); -#else - fprintf(stderr, _("%s: option `-W %s' is ambiguous\n"), - argv[0], argv[optind]); -#endif - } - nextchar += strlen(nextchar); - optind++; - return '?'; - } - if (pfound != NULL) - { - option_index = indfound; - if (*nameend) - { - /* Don't test has_arg with >, because some C compilers don't - allow it to be used on enums. */ - if (pfound->has_arg) - optarg = nameend + 1; - else - { - if (print_errors) - { -#if defined _LIBC && defined USE_IN_LIBIO - char *buf; - - __asprintf(&buf, _("\ - %s: option `-W %s' doesn't allow an argument\n"), - argv[0], pfound->name); - - if (_IO_fwide(stderr, 0) > 0) - __fwprintf(stderr, L"%s", buf); - else - fputs(buf, stderr); - - free(buf); -#else - fprintf(stderr, _("\ - %s: option `-W %s' doesn't allow an argument\n"), - argv[0], pfound->name); -#endif - } - - nextchar += strlen(nextchar); - return '?'; - } - } - else if (pfound->has_arg == 1) - { - if (optind < argc) - optarg = argv[optind++]; - else - { - if (print_errors) - { -#if defined _LIBC && defined USE_IN_LIBIO - char *buf; - - __asprintf(&buf, _("\ - %s: option `%s' requires an argument\n"), - argv[0], argv[optind - 1]); - - if (_IO_fwide(stderr, 0) > 0) - __fwprintf(stderr, L"%s", buf); - else - fputs(buf, stderr); - - free(buf); -#else - fprintf(stderr, - _("%s: option `%s' requires an argument\n"), - argv[0], argv[optind - 1]); -#endif - } - nextchar += strlen(nextchar); - return optstring[0] == ':' ? ':' : '?'; - } - } - nextchar += strlen(nextchar); - if (longind != NULL) - *longind = option_index; - if (pfound->flag) - { - *(pfound->flag) = pfound->val; - return 0; - } - return pfound->val; - } - nextchar = NULL; - return 'W'; /* Let the application handle it. */ - } - if (temp[1] == ':') - { - if (temp[2] == ':') - { - /* This is an option that accepts an argument optionally. */ - if (*nextchar != '\0') - { - optarg = nextchar; - optind++; - } - else - optarg = NULL; - nextchar = NULL; - } - else - { - /* This is an option that requires an argument. */ - if (*nextchar != '\0') - { - optarg = nextchar; - /* If we end this ARGV-element by taking the rest as an arg, - we must advance to the next element now. */ - optind++; - } - else if (optind == argc) - { - if (print_errors) - { - /* 1003.2 specifies the format of this message. */ -#if defined _LIBC && defined USE_IN_LIBIO - char *buf; - - __asprintf(&buf, - _("%s: option requires an argument -- %c\n"), - argv[0], c); - - if (_IO_fwide(stderr, 0) > 0) - __fwprintf(stderr, L"%s", buf); - else - fputs(buf, stderr); - - free(buf); -#else - fprintf(stderr, - _("%s: option requires an argument -- %c\n"), - argv[0], c); -#endif - } - optopt = c; - if (optstring[0] == ':') - c = ':'; - else - c = '?'; - } - else - /* We already incremented `optind' once; - increment it again when taking next ARGV-elt as argument. */ - optarg = argv[optind++]; - nextchar = NULL; - } - } - return c; - } -} - -int -getopt(argc, argv, optstring) -int argc; -char *const *argv; -const char *optstring; -{ - return _getopt_internal(argc, argv, optstring, - (const struct option *) 0, - (int *)0, - 0); -} - - - - -int -getopt_long(int argc, char *const *argv, const char *options, -const struct option *long_options, int *opt_index) -{ - return _getopt_internal(argc, argv, options, long_options, opt_index, 0, 0); -} - -int -getopt_long_only(int argc, char *const *argv, const char *options, -const struct option *long_options, int *opt_index) -{ - return _getopt_internal(argc, argv, options, long_options, opt_index, 1, 0); -} - - - - - -#endif /* Not ELIDE_CODE. */ - -#ifdef TEST - -/* Compile with -DTEST to make an executable for use in testing -the above definition of `getopt'. */ - -int -main(argc, argv) -int argc; -char **argv; -{ - int c; - int digit_optind = 0; - - while (1) - { - int this_option_optind = optind ? optind : 1; - - c = getopt(argc, argv, "abc:d:0123456789"); - if (c == -1) - break; - - switch (c) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - if (digit_optind != 0 && digit_optind != this_option_optind) - printf("digits occur in two different argv-elements.\n"); - digit_optind = this_option_optind; - printf("option %c\n", c); - break; - - case 'a': - printf("option a\n"); - break; - - case 'b': - printf("option b\n"); - break; - - case 'c': - printf("option c with value `%s'\n", optarg); - break; - - case '?': - break; - - default: - printf("?? getopt returned character code 0%o ??\n", c); - } - } - - if (optind < argc) - { - printf("non-option ARGV-elements: "); - while (optind < argc) - printf("%s ", argv[optind++]); - printf("\n"); - } - - exit(0); -} - -#endif /* TEST */ diff --git a/src/keepalive.c b/src/keepalive.c deleted file mode 100644 index e89b0c2..0000000 --- a/src/keepalive.c +++ /dev/null @@ -1,406 +0,0 @@ -#include -#include -#include - -#ifdef WIN32 -#include -typedef int socklen_t; -#else -#include -#include -#endif - -#include "auth.h" -#include "configparse.h" -#include "debug.h" -#include "keepalive.h" -#include -#include -#include - -int keepalive_1(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsigned char auth_information[]) { - if (drcom_config.keepalive1_mod) { - unsigned char keepalive_1_packet1[8] = {0x07, 0x01, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00}; - unsigned char recv_packet1[1024], keepalive_1_packet2[38], recv_packet2[1024]; - memset(keepalive_1_packet2, 0, 38); - sendto(sockfd, keepalive_1_packet1, 8, 0, (struct sockaddr *)&addr, sizeof(addr)); - if (verbose_flag) { - print_packet("[Keepalive1_packet1 sent] ", keepalive_1_packet1, 8); - } - if (logging_flag) { - logging("[Keepalive1_packet1 sent] ", keepalive_1_packet1, 8); - } -#ifdef TEST - printf("[TEST MODE]IN TEST MODE, PASS\n"); - return 0; -#endif - socklen_t addrlen = sizeof(addr); - while (1) { - if (recvfrom(sockfd, recv_packet1, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) { -#ifdef WIN32 - get_lasterror("Failed to recv data"); -#else - perror("Failed to recv data"); -#endif - return 1; - } else { - if (verbose_flag) { - print_packet("[Keepalive1 challenge_recv] ", recv_packet1, 100); - } - if (logging_flag) { - logging("[Keepalive1 challenge_recv] ", recv_packet1, 100); - } - - if (recv_packet1[0] == 0x07) { - break; - } else if (recv_packet1[0] == 0x4d) { - DEBUG_PRINT(("Get notice packet.\n")); - continue; - } else { - printf("Bad keepalive1 challenge response received.\n"); - return 1; - } - } - } - - unsigned char keepalive1_seed[4] = {0}; - int encrypt_type; - unsigned char crc[8] = {0}; - memcpy(keepalive1_seed, &recv_packet1[8], 4); - encrypt_type = keepalive1_seed[0] & 3; - gen_crc(keepalive1_seed, encrypt_type, crc); - keepalive_1_packet2[0] = 0xff; - memcpy(keepalive_1_packet2 + 8, keepalive1_seed, 4); - memcpy(keepalive_1_packet2 + 12, crc, 8); - memcpy(keepalive_1_packet2 + 20, auth_information, 16); - keepalive_1_packet2[36] = rand() & 0xff; - keepalive_1_packet2[37] = rand() & 0xff; - - sendto(sockfd, keepalive_1_packet2, 38, 0, (struct sockaddr *)&addr, sizeof(addr)); - if (verbose_flag) { - print_packet("[Keepalive1_packet2 sent] ", keepalive_1_packet2, 38); - } - if (logging_flag) { - logging("[Keepalive1_packet2 sent] ", keepalive_1_packet2, 38); - } - - if (recvfrom(sockfd, recv_packet2, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) { -#ifdef WIN32 - get_lasterror("Failed to recv data"); -#else - perror("Failed to recv data"); -#endif - return 1; - } else { - if (verbose_flag) { - print_packet("[Keepalive1 recv] ", recv_packet2, 100); - } - if (logging_flag) { - logging("[Keepalive1 recv] ", recv_packet2, 100); - } - - if (recv_packet2[0] != 0x07) { - printf("Bad keepalive1 response received.\n"); - return 1; - } - } - - } else { - unsigned char keepalive_1_packet[42], recv_packet[1024], MD5A[16]; - memset(keepalive_1_packet, 0, 42); - keepalive_1_packet[0] = 0xff; - int MD5A_len = 6 + strlen(drcom_config.password); - unsigned char* MD5A_str = (unsigned char*) malloc(MD5A_len); - MD5A_str[0] = 0x03; - MD5A_str[1] = 0x01; - memcpy(MD5A_str + 2, seed, 4); - memcpy(MD5A_str + 6, drcom_config.password, strlen(drcom_config.password)); - MD5(MD5A_str, MD5A_len, MD5A); - memcpy(keepalive_1_packet + 1, MD5A, 16); - memcpy(keepalive_1_packet + 20, auth_information, 16); - keepalive_1_packet[36] = rand() & 0xff; - keepalive_1_packet[37] = rand() & 0xff; - - sendto(sockfd, keepalive_1_packet, 42, 0, (struct sockaddr *)&addr, sizeof(addr)); - - if (verbose_flag) { - print_packet("[Keepalive1 sent] ", keepalive_1_packet, 42); - } - if (logging_flag) { - logging("[Keepalive1 sent] ", keepalive_1_packet, 42); - } - -#ifdef TEST - printf("[TEST MODE]IN TEST MODE, PASS\n"); - return 0; -#endif - - socklen_t addrlen = sizeof(addr); - while (1) { - if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) { -#ifdef WIN32 - get_lasterror("Failed to recv data"); -#else - perror("Failed to recv data"); -#endif - return 1; - } else { - if (verbose_flag) { - print_packet("[Keepalive1 recv] ", recv_packet, 100); - } - if (logging_flag) { - logging("[Keepalive1 recv] ", recv_packet, 100); - } - - if (recv_packet[0] == 0x07) { - break; - } else if (recv_packet[0] == 0x4d) { - DEBUG_PRINT(("Get notice packet.")); - continue; - } else { - printf("Bad keepalive1 response received.\n"); - return 1; - } - } - } - free(MD5A_str); - } - - return 0; -} - -void gen_crc(unsigned char seed[], int encrypt_type, unsigned char crc[]) { - if (encrypt_type == 0) { - char DRCOM_DIAL_EXT_PROTO_CRC_INIT[4] = {0xc7, 0x2f, 0x31, 0x01}; - char gencrc_tmp[4] = {0x7e}; - memcpy(crc, DRCOM_DIAL_EXT_PROTO_CRC_INIT, 4); - memcpy(crc + 4, gencrc_tmp, 4); - } else if (encrypt_type == 1) { - unsigned char hash[32] = {0}; - MD5(seed, 4, hash); - crc[0] = hash[2]; - crc[1] = hash[3]; - crc[2] = hash[8]; - crc[3] = hash[9]; - crc[4] = hash[5]; - crc[5] = hash[6]; - crc[6] = hash[13]; - crc[7] = hash[14]; - } else if (encrypt_type == 2) { - unsigned char hash[32] = {0}; - MD4(seed, 4, hash); - crc[0] = hash[1]; - crc[1] = hash[2]; - crc[2] = hash[8]; - crc[3] = hash[9]; - crc[4] = hash[4]; - crc[5] = hash[5]; - crc[6] = hash[11]; - crc[7] = hash[12]; - } else if (encrypt_type == 3) { - unsigned char hash[32] = {0}; - SHA1(seed, 4, hash); - crc[0] = hash[2]; - crc[1] = hash[3]; - crc[2] = hash[9]; - crc[3] = hash[10]; - crc[4] = hash[5]; - crc[5] = hash[6]; - crc[6] = hash[15]; - crc[7] = hash[16]; - } -} - -void keepalive_2_packetbuilder(unsigned char keepalive_2_packet[], int keepalive_counter, int filepacket, int type, int encrypt_type) { - keepalive_2_packet[0] = 0x07; - keepalive_2_packet[1] = keepalive_counter; - keepalive_2_packet[2] = 0x28; - keepalive_2_packet[4] = 0x0b; - keepalive_2_packet[5] = type; - if (filepacket) { - keepalive_2_packet[6] = 0x0f; - keepalive_2_packet[7] = 0x27; - } else { - memcpy(keepalive_2_packet + 6, drcom_config.KEEP_ALIVE_VERSION, 2); - } - keepalive_2_packet[8] = 0x2f; - keepalive_2_packet[9] = 0x12; - if (type == 3) { - unsigned char host_ip[4] = {0}; - if (strcmp(mode, "dhcp") == 0) { - sscanf(drcom_config.host_ip, "%hhd.%hhd.%hhd.%hhd", - &host_ip[0], - &host_ip[1], - &host_ip[2], - &host_ip[3]); - memcpy(keepalive_2_packet + 28, host_ip, 4); - } else if (strcmp(mode, "pppoe") == 0) { - unsigned char crc[8] = {0}; - gen_crc(keepalive_2_packet, encrypt_type, crc); - memcpy(keepalive_2_packet + 32, crc, 8); - } - } -} - -int keepalive_2(int sockfd, struct sockaddr_in addr, int *keepalive_counter, int *first, int *encrypt_type) { - unsigned char keepalive_2_packet[40], recv_packet[1024], tail[4]; - socklen_t addrlen = sizeof(addr); - -#ifdef TEST - printf("[TEST MODE]IN TEST MODE, PASS\n"); -#else - if (*first) { - // send the file packet - memset(keepalive_2_packet, 0, 40); - if (strcmp(mode, "pppoe") == 0) { - keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 1, *encrypt_type); - } else { - keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 1, 0); - } - (*keepalive_counter)++; - - sendto(sockfd, keepalive_2_packet, 40, 0, (struct sockaddr *)&addr, sizeof(addr)); - - if (verbose_flag) { - print_packet("[Keepalive2_file sent] ", keepalive_2_packet, 40); - } - if (logging_flag) { - logging("[Keepalive2_file sent] ", keepalive_2_packet, 40); - } - if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) { -#ifdef WIN32 - get_lasterror("Failed to recv data"); -#else - perror("Failed to recv data"); -#endif - return 1; - } - if (verbose_flag) { - print_packet("[Keepalive2_file recv] ", recv_packet, 40); - } - if (logging_flag) { - logging("[Keepalive2_file recv] ", recv_packet, 40); - } - - if (recv_packet[0] == 0x07) { - if (recv_packet[2] == 0x10) { - if (verbose_flag) { - printf("Filepacket received.\n"); - } - } else if (recv_packet[2] != 0x28) { - if (verbose_flag) { - printf("Bad keepalive2 response received.\n"); - } - return 1; - } - } else { - printf("Bad keepalive2 response received.\n"); - return 1; - } - } -#endif - - // send the first packet - *first = 0; - memset(keepalive_2_packet, 0, 40); - if (strcmp(mode, "pppoe") == 0) { - keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 1, *encrypt_type); - } else { - keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 1, 0); - } - (*keepalive_counter)++; - sendto(sockfd, keepalive_2_packet, 40, 0, (struct sockaddr *)&addr, sizeof(addr)); - - if (verbose_flag) { - print_packet("[Keepalive2_A sent] ", keepalive_2_packet, 40); - } - if (logging_flag) { - logging("[Keepalive2_A sent] ", keepalive_2_packet, 40); - } - -#ifdef TEST - unsigned char test[4] = {0x13, 0x38, 0xe2, 0x11}; - memcpy(tail, test, 4); - print_packet("[TEST MODE] ", tail, 4); -#else - if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) { -#ifdef WIN32 - get_lasterror("Failed to recv data"); -#else - perror("Failed to recv data"); -#endif - return 1; - } - if (verbose_flag) { - print_packet("[Keepalive2_B recv] ", recv_packet, 40); - } - if (logging_flag) { - logging("[Keepalive2_B recv] ", recv_packet, 40); - } - - if (recv_packet[0] == 0x07) { - if (recv_packet[2] != 0x28) { - printf("Bad keepalive2 response received.\n"); - return 1; - } - } else { - printf("Bad keepalive2 response received.\n"); - return 1; - } - memcpy(tail, &recv_packet[16], 4); -#endif - -#ifdef DEBUG - print_packet(" ", tail, 4); -#endif - - // send the third packet - memset(keepalive_2_packet, 0, 40); - if (strcmp(mode, "pppoe") == 0) { - keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 3, *encrypt_type); - } else { - keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 3, 0); - } - memcpy(keepalive_2_packet + 16, tail, 4); - (*keepalive_counter)++; - sendto(sockfd, keepalive_2_packet, 40, 0, (struct sockaddr *)&addr, sizeof(addr)); - - if (verbose_flag) { - print_packet("[Keepalive2_C sent] ", keepalive_2_packet, 40); - } - if (logging_flag) { - logging("[Keepalive2_C sent] ", keepalive_2_packet, 40); - } - -#ifdef TEST - printf("[TEST MODE]IN TEST MODE, PASS\n"); - exit(0); -#endif - - if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) { -#ifdef WIN32 - get_lasterror("Failed to recv data"); -#else - perror("Failed to recv data"); -#endif - return 1; - } - if (verbose_flag) { - print_packet("[Keepalive2_D recv] ", recv_packet, 40); - } - if (logging_flag) { - logging("[Keepalive2_D recv] ", recv_packet, 40); - } - - if (recv_packet[0] == 0x07) { - if (recv_packet[2] != 0x28) { - printf("Bad keepalive2 response received.\n"); - return 1; - } - } else { - printf("Bad keepalive2 response received.\n"); - return 1; - } - - return 0; -} \ No newline at end of file diff --git a/src/keepalive.cpp b/src/keepalive.cpp new file mode 100644 index 0000000..b0bbbee --- /dev/null +++ b/src/keepalive.cpp @@ -0,0 +1,17 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// +#include + +namespace dogcom { + +awaitable client_t::keepalive1() { + +} + +awaitable client_t::keepalive2() { + +} + + +} \ No newline at end of file diff --git a/src/main.c b/src/main.c deleted file mode 100644 index d297d37..0000000 --- a/src/main.c +++ /dev/null @@ -1,209 +0,0 @@ -#include -#include -#include -#include "auth.h" -#include "configparse.h" - -#ifdef linux -#include -#include "daemon.h" -#include "eapol.h" -#include -#endif - -#ifdef _MSC_VER -#include -#else -#include -#endif - -#define VERSION "1.6.2" - -void print_help(int exval); -int try_smart_eaplogin(void); - -static const char default_bind_ip[20] = "0.0.0.0"; - -int main(int argc, char *argv[]) { - if (argc == 1) { - print_help(1); - } - - char *file_path; - - while (1) { - static const struct option long_options[] = { - {"mode", required_argument, 0, 'm'}, - {"conf", required_argument, 0, 'c'}, - {"bindip", required_argument, 0, 'b'}, - {"log", required_argument, 0, 'l'}, -#ifdef linux - {"daemon", no_argument, 0, 'd'}, - {"802.1x", no_argument, 0, 'x'}, -#endif - {"eternal", no_argument, 0, 'e'}, - {"verbose", no_argument, 0, 'v'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0}}; - - int c; - int option_index = 0; -#ifdef linux - c = getopt_long(argc, argv, "m:c:b:l:dxevh", long_options, &option_index); -#else - c = getopt_long(argc, argv, "m:c:b:l:evh", long_options, &option_index); -#endif - - if (c == -1) { - break; - } - switch (c) { - case 'm': - if (strcmp(optarg, "dhcp") == 0) { - strcpy(mode, optarg); - } else if (strcmp(optarg, "pppoe") == 0) { - strcpy(mode, optarg); - } else { - printf("unknown mode\n"); - exit(1); - } - break; - case 'c': -#ifndef __APPLE__ - if (mode != NULL) { -#endif -#ifdef linux - char path_c[PATH_MAX]; - realpath(optarg, path_c); - file_path = strdup(path_c); -#else - file_path = optarg; -#endif -#ifndef __APPLE__ - } -#endif - break; - case 'b': - strcpy(bind_ip, optarg); - break; - case 'l': -#ifndef __APPLE__ - if (mode != NULL) { -#endif -#ifdef linux - char path_l[PATH_MAX]; - realpath(optarg, path_l); - log_path = strdup(path_l); -#else - log_path = optarg; -#endif - logging_flag = 1; -#ifndef __APPLE__ - } -#endif - break; -#ifdef linux - case 'd': - daemon_flag = 1; - break; - case 'x': - eapol_flag = 1; - break; -#endif - case 'e': - eternal_flag = 1; - break; - case 'v': - verbose_flag = 1; - break; - case 'h': - print_help(0); - break; - case '?': - print_help(1); - break; - default: - break; - } - } - -#ifndef __APPLE__ - if (mode != NULL && file_path != NULL) { -#endif -#ifdef linux - if (daemon_flag) { - daemonise(); - } -#endif - -#ifdef WIN32 // dirty fix with win32 - char tmp[10] = {0}; - strcpy(tmp, mode); -#endif - if (!config_parse(file_path)) { -#ifdef WIN32 // dirty fix with win32 - strcpy(mode, tmp); -#endif - -#ifdef linux - if (eapol_flag) { // eable 802.1x authorization - if (0 != try_smart_eaplogin()) { - printf("Can't finish 802.1x authorization!\n"); - return 1; - } - } -#endif - if (strlen(bind_ip) == 0) { - memcpy(bind_ip, default_bind_ip, sizeof(default_bind_ip)); - } - dogcom(5); - } else { - return 1; - } -#ifndef __APPLE__ - } else { - printf("Need more options!\n\n"); - return 1; - } -#endif - return 0; -} - -void print_help(int exval) { - printf("\nDrcom-generic implementation in C.\n"); - printf("Version: %s\n\n", VERSION); - - printf("Usage:\n"); - printf("\tdogcom -m -c [options ]...\n\n"); - - printf("Options:\n"); - printf("\t--mode , -m set your dogcom mode \n"); - printf("\t--conf , -c import configuration file\n"); - printf("\t--bindip , -b bind your ip address(default is 0.0.0.0)\n"); - printf("\t--log , -l specify log file\n"); -#ifdef linux - printf("\t--daemon, -d set daemon flag\n"); - printf("\t--802.1x, -x enable 802.1x\n"); -#endif - printf("\t--eternal, -e set eternal flag\n"); - printf("\t--verbose, -v set verbose flag\n"); - printf("\t--help, -h display this help\n\n"); - exit(exval); -} - -#ifdef linux -int try_smart_eaplogin(void) { -#define IFS_MAX (64) - int ifcnt = IFS_MAX; - iflist_t ifs[IFS_MAX]; - if (0 > getall_ifs(ifs, &ifcnt)) - return -1; - - for (int i = 0; i < ifcnt; ++i) { - setifname(ifs[i].name); - if (0 == eaplogin(drcom_config.username, drcom_config.password)) - return 0; - } - return -1; -} -#endif \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..6c6234a --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,9 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// +#include + +int main(int argc, char* argv[]) { + dogcom::config_t config; + dogcom::client_t client {config}; +} \ No newline at end of file diff --git a/src/md4.c b/src/md4.c deleted file mode 100644 index 07a0d6e..0000000 --- a/src/md4.c +++ /dev/null @@ -1,277 +0,0 @@ -/* - * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. - * MD4 Message-Digest Algorithm (RFC 1320). - * - * Homepage: - * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md4 - * - * Author: - * Alexander Peslyak, better known as Solar Designer - * - * This software was written by Alexander Peslyak in 2001. No copyright is - * claimed, and the software is hereby placed in the public domain. - * In case this attempt to disclaim copyright and place the software in the - * public domain is deemed null and void, then the software is - * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the - * general public under the following terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted. - * - * There's ABSOLUTELY NO WARRANTY, express or implied. - * - * (This is a heavily cut-down "BSD license".) - * - * This differs from Colin Plumb's older public domain implementation in that - * no exactly 32-bit integer data type is required (any 32-bit or wider - * unsigned integer data type will do), there's no compile-time endianness - * configuration, and the function prototypes match OpenSSL's. No code from - * Colin Plumb's implementation has been reused; this comment merely compares - * the properties of the two independent implementations. - * - * The primary goals of this implementation are portability and ease of use. - * It is meant to be fast, but not as fast as possible. Some known - * optimizations are not included to reduce source code size and avoid - * compile-time configuration. - */ - -#ifndef HAVE_OPENSSL - -#include - -#include - -/* - * The basic MD4 functions. - * - * F and G are optimized compared to their RFC 1320 definitions, with the - * optimization for F borrowed from Colin Plumb's MD5 implementation. - */ -#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) -#define G(x, y, z) (((x) & ((y) | (z))) | ((y) & (z))) -#define H(x, y, z) ((x) ^ (y) ^ (z)) - -/* - * The MD4 transformation for all three rounds. - */ -#define STEP(f, a, b, c, d, x, s) \ - (a) += f((b), (c), (d)) + (x); \ - (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); - -/* - * SET reads 4 input bytes in little-endian byte order and stores them in a - * properly aligned word in host byte order. - * - * The check for little-endian architectures that tolerate unaligned memory - * accesses is just an optimization. Nothing will break if it fails to detect - * a suitable architecture. - * - * Unfortunately, this optimization may be a C strict aliasing rules violation - * if the caller's data buffer has effective type that cannot be aliased by - * MD4_u32plus. In practice, this problem may occur if these MD4 routines are - * inlined into a calling function, or with future and dangerously advanced - * link-time optimizations. For the time being, keeping these MD4 routines in - * their own translation unit avoids the problem. - */ -#if defined(__i386__) || defined(__x86_64__) || defined(__vax__) -#define SET(n) \ - (*(MD4_u32plus *)&ptr[(n) * 4]) -#define GET(n) \ - SET(n) -#else -#define SET(n) \ - (ctx->block[(n)] = \ - (MD4_u32plus)ptr[(n) * 4] | \ - ((MD4_u32plus)ptr[(n) * 4 + 1] << 8) | \ - ((MD4_u32plus)ptr[(n) * 4 + 2] << 16) | \ - ((MD4_u32plus)ptr[(n) * 4 + 3] << 24)) -#define GET(n) \ - (ctx->block[(n)]) -#endif - -/* - * This processes one or more 64-byte data blocks, but does NOT update the bit - * counters. There are no alignment requirements. - */ -static const void *body(MD4_CTX *ctx, const void *data, unsigned long size) -{ - const unsigned char *ptr; - MD4_u32plus a, b, c, d; - MD4_u32plus saved_a, saved_b, saved_c, saved_d; - const MD4_u32plus ac1 = 0x5a827999, ac2 = 0x6ed9eba1; - - ptr = (const unsigned char *)data; - - a = ctx->a; - b = ctx->b; - c = ctx->c; - d = ctx->d; - - do { - saved_a = a; - saved_b = b; - saved_c = c; - saved_d = d; - -/* Round 1 */ - STEP(F, a, b, c, d, SET(0), 3) - STEP(F, d, a, b, c, SET(1), 7) - STEP(F, c, d, a, b, SET(2), 11) - STEP(F, b, c, d, a, SET(3), 19) - STEP(F, a, b, c, d, SET(4), 3) - STEP(F, d, a, b, c, SET(5), 7) - STEP(F, c, d, a, b, SET(6), 11) - STEP(F, b, c, d, a, SET(7), 19) - STEP(F, a, b, c, d, SET(8), 3) - STEP(F, d, a, b, c, SET(9), 7) - STEP(F, c, d, a, b, SET(10), 11) - STEP(F, b, c, d, a, SET(11), 19) - STEP(F, a, b, c, d, SET(12), 3) - STEP(F, d, a, b, c, SET(13), 7) - STEP(F, c, d, a, b, SET(14), 11) - STEP(F, b, c, d, a, SET(15), 19) - -/* Round 2 */ - STEP(G, a, b, c, d, GET(0) + ac1, 3) - STEP(G, d, a, b, c, GET(4) + ac1, 5) - STEP(G, c, d, a, b, GET(8) + ac1, 9) - STEP(G, b, c, d, a, GET(12) + ac1, 13) - STEP(G, a, b, c, d, GET(1) + ac1, 3) - STEP(G, d, a, b, c, GET(5) + ac1, 5) - STEP(G, c, d, a, b, GET(9) + ac1, 9) - STEP(G, b, c, d, a, GET(13) + ac1, 13) - STEP(G, a, b, c, d, GET(2) + ac1, 3) - STEP(G, d, a, b, c, GET(6) + ac1, 5) - STEP(G, c, d, a, b, GET(10) + ac1, 9) - STEP(G, b, c, d, a, GET(14) + ac1, 13) - STEP(G, a, b, c, d, GET(3) + ac1, 3) - STEP(G, d, a, b, c, GET(7) + ac1, 5) - STEP(G, c, d, a, b, GET(11) + ac1, 9) - STEP(G, b, c, d, a, GET(15) + ac1, 13) - -/* Round 3 */ - STEP(H, a, b, c, d, GET(0) + ac2, 3) - STEP(H, d, a, b, c, GET(8) + ac2, 9) - STEP(H, c, d, a, b, GET(4) + ac2, 11) - STEP(H, b, c, d, a, GET(12) + ac2, 15) - STEP(H, a, b, c, d, GET(2) + ac2, 3) - STEP(H, d, a, b, c, GET(10) + ac2, 9) - STEP(H, c, d, a, b, GET(6) + ac2, 11) - STEP(H, b, c, d, a, GET(14) + ac2, 15) - STEP(H, a, b, c, d, GET(1) + ac2, 3) - STEP(H, d, a, b, c, GET(9) + ac2, 9) - STEP(H, c, d, a, b, GET(5) + ac2, 11) - STEP(H, b, c, d, a, GET(13) + ac2, 15) - STEP(H, a, b, c, d, GET(3) + ac2, 3) - STEP(H, d, a, b, c, GET(11) + ac2, 9) - STEP(H, c, d, a, b, GET(7) + ac2, 11) - STEP(H, b, c, d, a, GET(15) + ac2, 15) - - a += saved_a; - b += saved_b; - c += saved_c; - d += saved_d; - - ptr += 64; - } while (size -= 64); - - ctx->a = a; - ctx->b = b; - ctx->c = c; - ctx->d = d; - - return ptr; -} - -void MD4_Init(MD4_CTX *ctx) -{ - ctx->a = 0x67452301; - ctx->b = 0xefcdab89; - ctx->c = 0x98badcfe; - ctx->d = 0x10325476; - - ctx->lo = 0; - ctx->hi = 0; -} - -void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size) -{ - MD4_u32plus saved_lo; - unsigned long used, available; - - saved_lo = ctx->lo; - if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) - ctx->hi++; - ctx->hi += size >> 29; - - used = saved_lo & 0x3f; - - if (used) { - available = 64 - used; - - if (size < available) { - memcpy(&ctx->buffer[used], data, size); - return; - } - - memcpy(&ctx->buffer[used], data, available); - data = (const unsigned char *)data + available; - size -= available; - body(ctx, ctx->buffer, 64); - } - - if (size >= 64) { - data = body(ctx, data, size & ~(unsigned long)0x3f); - size &= 0x3f; - } - - memcpy(ctx->buffer, data, size); -} - -#define OUT(dst, src) \ - (dst)[0] = (unsigned char)(src); \ - (dst)[1] = (unsigned char)((src) >> 8); \ - (dst)[2] = (unsigned char)((src) >> 16); \ - (dst)[3] = (unsigned char)((src) >> 24); - -void MD4_Final(unsigned char *result, MD4_CTX *ctx) -{ - unsigned long used, available; - - used = ctx->lo & 0x3f; - - ctx->buffer[used++] = 0x80; - - available = 64 - used; - - if (available < 8) { - memset(&ctx->buffer[used], 0, available); - body(ctx, ctx->buffer, 64); - used = 0; - available = 64; - } - - memset(&ctx->buffer[used], 0, available - 8); - - ctx->lo <<= 3; - OUT(&ctx->buffer[56], ctx->lo) - OUT(&ctx->buffer[60], ctx->hi) - - body(ctx, ctx->buffer, 64); - - OUT(&result[0], ctx->a) - OUT(&result[4], ctx->b) - OUT(&result[8], ctx->c) - OUT(&result[12], ctx->d) - - memset(ctx, 0, sizeof(*ctx)); -} - -void MD4(const void *data, unsigned long size, unsigned char *result) { - MD4_CTX ctx; - MD4_Init(&ctx); - MD4_Update(&ctx, data, size); - MD4_Final(result, &ctx); -} - -#endif diff --git a/src/md5.c b/src/md5.c deleted file mode 100644 index 3bf14c8..0000000 --- a/src/md5.c +++ /dev/null @@ -1,298 +0,0 @@ -/* - * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. - * MD5 Message-Digest Algorithm (RFC 1321). - * - * Homepage: - * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 - * - * Author: - * Alexander Peslyak, better known as Solar Designer - * - * This software was written by Alexander Peslyak in 2001. No copyright is - * claimed, and the software is hereby placed in the public domain. - * In case this attempt to disclaim copyright and place the software in the - * public domain is deemed null and void, then the software is - * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the - * general public under the following terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted. - * - * There's ABSOLUTELY NO WARRANTY, express or implied. - * - * (This is a heavily cut-down "BSD license".) - * - * This differs from Colin Plumb's older public domain implementation in that - * no exactly 32-bit integer data type is required (any 32-bit or wider - * unsigned integer data type will do), there's no compile-time endianness - * configuration, and the function prototypes match OpenSSL's. No code from - * Colin Plumb's implementation has been reused; this comment merely compares - * the properties of the two independent implementations. - * - * The primary goals of this implementation are portability and ease of use. - * It is meant to be fast, but not as fast as possible. Some known - * optimizations are not included to reduce source code size and avoid - * compile-time configuration. - */ - -#ifndef HAVE_OPENSSL - -#include - -#include - -/* - * The basic MD5 functions. - * - * F and G are optimized compared to their RFC 1321 definitions for - * architectures that lack an AND-NOT instruction, just like in Colin Plumb's - * implementation. - */ -#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) -#define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) -#define H(x, y, z) (((x) ^ (y)) ^ (z)) -#define H2(x, y, z) ((x) ^ ((y) ^ (z))) -#define I(x, y, z) ((y) ^ ((x) | ~(z))) - -/* - * The MD5 transformation for all four rounds. - */ -#define STEP(f, a, b, c, d, x, t, s) \ - (a) += f((b), (c), (d)) + (x) + (t); \ - (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ - (a) += (b); - -/* - * SET reads 4 input bytes in little-endian byte order and stores them in a - * properly aligned word in host byte order. - * - * The check for little-endian architectures that tolerate unaligned memory - * accesses is just an optimization. Nothing will break if it fails to detect - * a suitable architecture. - * - * Unfortunately, this optimization may be a C strict aliasing rules violation - * if the caller's data buffer has effective type that cannot be aliased by - * MD5_u32plus. In practice, this problem may occur if these MD5 routines are - * inlined into a calling function, or with future and dangerously advanced - * link-time optimizations. For the time being, keeping these MD5 routines in - * their own translation unit avoids the problem. - */ -#if defined(__i386__) || defined(__x86_64__) || defined(__vax__) -#define SET(n) \ - (*(MD5_u32plus *)&ptr[(n) * 4]) -#define GET(n) \ - SET(n) -#else -#define SET(n) \ - (ctx->block[(n)] = \ - (MD5_u32plus)ptr[(n) * 4] | \ - ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ - ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ - ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) -#define GET(n) \ - (ctx->block[(n)]) -#endif - -/* - * This processes one or more 64-byte data blocks, but does NOT update the bit - * counters. There are no alignment requirements. - */ -static const void *body(MD5_CTX *ctx, const void *data, unsigned long size) -{ - const unsigned char *ptr; - MD5_u32plus a, b, c, d; - MD5_u32plus saved_a, saved_b, saved_c, saved_d; - - ptr = (const unsigned char *)data; - - a = ctx->a; - b = ctx->b; - c = ctx->c; - d = ctx->d; - - do { - saved_a = a; - saved_b = b; - saved_c = c; - saved_d = d; - -/* Round 1 */ - STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) - STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) - STEP(F, c, d, a, b, SET(2), 0x242070db, 17) - STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) - STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) - STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) - STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) - STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) - STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) - STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) - STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) - STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) - STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) - STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) - STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) - STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) - -/* Round 2 */ - STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) - STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) - STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) - STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) - STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) - STEP(G, d, a, b, c, GET(10), 0x02441453, 9) - STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) - STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) - STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) - STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) - STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) - STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) - STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) - STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) - STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) - STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) - -/* Round 3 */ - STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) - STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11) - STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) - STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23) - STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) - STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11) - STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) - STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23) - STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) - STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11) - STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) - STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23) - STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) - STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11) - STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) - STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23) - -/* Round 4 */ - STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) - STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) - STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) - STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) - STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) - STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) - STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) - STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) - STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) - STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) - STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) - STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) - STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) - STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) - STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) - STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) - - a += saved_a; - b += saved_b; - c += saved_c; - d += saved_d; - - ptr += 64; - } while (size -= 64); - - ctx->a = a; - ctx->b = b; - ctx->c = c; - ctx->d = d; - - return ptr; -} - -void MD5_Init(MD5_CTX *ctx) -{ - ctx->a = 0x67452301; - ctx->b = 0xefcdab89; - ctx->c = 0x98badcfe; - ctx->d = 0x10325476; - - ctx->lo = 0; - ctx->hi = 0; -} - -void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size) -{ - MD5_u32plus saved_lo; - unsigned long used, available; - - saved_lo = ctx->lo; - if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) - ctx->hi++; - ctx->hi += size >> 29; - - used = saved_lo & 0x3f; - - if (used) { - available = 64 - used; - - if (size < available) { - memcpy(&ctx->buffer[used], data, size); - return; - } - - memcpy(&ctx->buffer[used], data, available); - data = (const unsigned char *)data + available; - size -= available; - body(ctx, ctx->buffer, 64); - } - - if (size >= 64) { - data = body(ctx, data, size & ~(unsigned long)0x3f); - size &= 0x3f; - } - - memcpy(ctx->buffer, data, size); -} - -#define OUT(dst, src) \ - (dst)[0] = (unsigned char)(src); \ - (dst)[1] = (unsigned char)((src) >> 8); \ - (dst)[2] = (unsigned char)((src) >> 16); \ - (dst)[3] = (unsigned char)((src) >> 24); - -void MD5_Final(unsigned char *result, MD5_CTX *ctx) -{ - unsigned long used, available; - - used = ctx->lo & 0x3f; - - ctx->buffer[used++] = 0x80; - - available = 64 - used; - - if (available < 8) { - memset(&ctx->buffer[used], 0, available); - body(ctx, ctx->buffer, 64); - used = 0; - available = 64; - } - - memset(&ctx->buffer[used], 0, available - 8); - - ctx->lo <<= 3; - OUT(&ctx->buffer[56], ctx->lo) - OUT(&ctx->buffer[60], ctx->hi) - - body(ctx, ctx->buffer, 64); - - OUT(&result[0], ctx->a) - OUT(&result[4], ctx->b) - OUT(&result[8], ctx->c) - OUT(&result[12], ctx->d) - - memset(ctx, 0, sizeof(*ctx)); -} - -void MD5(const void *data, unsigned long size, unsigned char *result) { - MD5_CTX ctx; - MD5_Init(&ctx); - MD5_Update(&ctx, data, size); - MD5_Final(result, &ctx); -} - -#endif diff --git a/src/pppoe.cpp b/src/pppoe.cpp new file mode 100644 index 0000000..22a81da --- /dev/null +++ b/src/pppoe.cpp @@ -0,0 +1,17 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// +#include + +namespace dogcom { + +awaitable client_t::pppoe_login() { + throw std::runtime_error("Not Implemented"); +} + +awaitable client_t::pppoe_challenge() { + throw std::runtime_error("Not Implemented"); +} + + +} \ No newline at end of file diff --git a/src/sha1.c b/src/sha1.c deleted file mode 100644 index 68f1d25..0000000 --- a/src/sha1.c +++ /dev/null @@ -1,203 +0,0 @@ - -/* from valgrind tests */ - -/* ================ sha1.c ================ */ -/* -SHA-1 in C -By Steve Reid -100% Public Domain - -Test Vectors (from FIPS PUB 180-1) -"abc" - A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D -"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" - 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 -A million repetitions of "a" - 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F -*/ - -/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ -/* #define SHA1HANDSOFF * Copies data before messing with it. */ - -#define SHA1HANDSOFF - -#include -#include -#include -#include - -#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) - -/* blk0() and blk() perform the initial expand. */ -/* I got the idea of expanding during the round function from SSLeay */ -#if BYTE_ORDER == LITTLE_ENDIAN -#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ - |(rol(block->l[i],8)&0x00FF00FF)) -#elif BYTE_ORDER == BIG_ENDIAN -#define blk0(i) block->l[i] -#else -#error "Endianness not defined!" -#endif -#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ - ^block->l[(i+2)&15]^block->l[i&15],1)) - -/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ -#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); -#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); -#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); -#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); - - -/* Hash a single 512-bit block. This is the core of the algorithm. */ - -void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) -{ - uint32_t a, b, c, d, e; - typedef union { - unsigned char c[64]; - uint32_t l[16]; - } CHAR64LONG16; -#ifdef SHA1HANDSOFF - CHAR64LONG16 block[1]; /* use array to appear as a pointer */ - memcpy(block, buffer, 64); -#else - /* The following had better never be used because it causes the - * pointer-to-const buffer to be cast into a pointer to non-const. - * And the result is written through. I threw a "const" in, hoping - * this will cause a diagnostic. - */ - CHAR64LONG16* block = (const CHAR64LONG16*)buffer; -#endif - /* Copy context->state[] to working vars */ - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - /* 4 rounds of 20 operations each. Loop unrolled. */ - R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); - R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); - R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); - R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); - R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); - R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); - R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); - R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); - R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); - R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); - R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); - R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); - R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); - R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); - R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); - R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); - R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); - R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); - R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); - R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); - /* Add the working vars back into context.state[] */ - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - state[4] += e; - /* Wipe variables */ - a = b = c = d = e = 0; -#ifdef SHA1HANDSOFF - memset(block, '\0', sizeof(block)); -#endif -} - - -/* SHA1Init - Initialize new context */ - -void SHA1Init(SHA1_CTX* context) -{ - /* SHA1 initialization constants */ - context->state[0] = 0x67452301; - context->state[1] = 0xEFCDAB89; - context->state[2] = 0x98BADCFE; - context->state[3] = 0x10325476; - context->state[4] = 0xC3D2E1F0; - context->count[0] = context->count[1] = 0; -} - - -/* Run your data through this. */ - -void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len) -{ - uint32_t i, j; - - j = context->count[0]; - if ((context->count[0] += len << 3) < j) - context->count[1]++; - context->count[1] += (len>>29); - j = (j >> 3) & 63; - if ((j + len) > 63) { - memcpy(&context->buffer[j], data, (i = 64-j)); - SHA1Transform(context->state, context->buffer); - for ( ; i + 63 < len; i += 64) { - SHA1Transform(context->state, &data[i]); - } - j = 0; - } - else i = 0; - memcpy(&context->buffer[j], &data[i], len - i); -} - - -/* Add padding and return the message digest. */ - -void SHA1Final(unsigned char digest[20], SHA1_CTX* context) -{ - unsigned i; - unsigned char finalcount[8]; - unsigned char c; - -#if 0 /* untested "improvement" by DHR */ - /* Convert context->count to a sequence of bytes - * in finalcount. Second element first, but - * big-endian order within element. - * But we do it all backwards. - */ - unsigned char *fcp = &finalcount[8]; - - for (i = 0; i < 2; i++) - { - uint32_t t = context->count[i]; - int j; - - for (j = 0; j < 4; t >>= 8, j++) - *--fcp = (unsigned char) t; - } -#else - for (i = 0; i < 8; i++) { - finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] - >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ - } -#endif - c = 0200; - SHA1Update(context, &c, 1); - while ((context->count[0] & 504) != 448) { - c = 0000; - SHA1Update(context, &c, 1); - } - SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */ - for (i = 0; i < 20; i++) { - digest[i] = (unsigned char) - ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); - } - /* Wipe variables */ - memset(context, '\0', sizeof(*context)); - memset(&finalcount, '\0', sizeof(finalcount)); -} -/* ================ end of sha1.c ================ */ - -void SHA1(const unsigned char* data, uint32_t len, unsigned char digest[20]) { - SHA1_CTX ctx; - SHA1Init(&ctx); - SHA1Update(&ctx, data, len); - SHA1Final(digest, &ctx); -} \ No newline at end of file diff --git a/src/utils.cpp b/src/utils.cpp new file mode 100644 index 0000000..b6ca9aa --- /dev/null +++ b/src/utils.cpp @@ -0,0 +1,45 @@ +// +// Created by Don Yihtseu on 11/04/2024. +// +#include +#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 +#include +#include +#include + +using CryptoPP::byte; +using CryptoPP::Weak1::MD4; +using CryptoPP::Weak1::MD5; +using CryptoPP::SHA1; + +namespace dogcom { + +std::string md4(std::string_view data) { + std::string digest; + MD4 hash; + hash.Update(reinterpret_cast(&data[0]) , data.size()); + digest.resize(hash.DigestSize()); + hash.Final(reinterpret_cast(&digest[0])); + return std::move(digest); +} + +std::string md5(std::string_view data) { + std::string digest; + MD5 hash; + hash.Update(reinterpret_cast(&data[0]) , data.size()); + digest.resize(hash.DigestSize()); + hash.Final(reinterpret_cast(&digest[0])); + return std::move(digest); +} + +std::string sha(std::string_view data) { + std::string digest; + SHA1 hash; + hash.Update(reinterpret_cast(&data[0]) , data.size()); + digest.resize(hash.DigestSize()); + hash.Final(reinterpret_cast(&digest[0])); + return std::move(digest); +} + + +} \ No newline at end of file diff --git a/vcpkg.json b/vcpkg.json new file mode 100644 index 0000000..c3d275f --- /dev/null +++ b/vcpkg.json @@ -0,0 +1,8 @@ +{ + "name": "dogcom", + "version-string": "1.0.0", + "dependencies": [ + "boost-asio", "boost-log", + "cryptopp" + ] +} \ No newline at end of file From 0871b79b57158b52ff09bac5d07750211facbc14 Mon Sep 17 00:00:00 2001 From: yizhou Date: Thu, 11 Apr 2024 03:04:03 +0800 Subject: [PATCH 09/14] fix: actions --- .github/workflows/clang.yml | 13 +++++++++++-- .github/workflows/gcc.yml | 15 ++++++++++++--- .github/workflows/msvc.yml | 13 +++++++++++-- 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/.github/workflows/clang.yml b/.github/workflows/clang.yml index 28f97c5..ea8cff9 100644 --- a/.github/workflows/clang.yml +++ b/.github/workflows/clang.yml @@ -9,15 +9,24 @@ jobs: build: runs-on: macos-latest steps: - - uses: action/checkout@v4.1.2 + - uses: actions/checkout@latest - uses: KyleMayes/install-llvm-action@v2 with: version: "17.0.0" arch: "arm64" + - uses: lukka/get-cmake@latest + + - uses: lukka/run-vcpkg@v11 + with: + vcpkgDirectory: ${{ github.workspace }}/vcpkg + runVcpkgInstall: true + vcpkgJsonGlob: ${{ github.workspace }}/vcpkg.json + - uses: threeal/cmake-action@main with: generator: Ninja c-compiler: clang - cxx-compiler: clang++ \ No newline at end of file + cxx-compiler: clang++ + options: CMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake \ No newline at end of file diff --git a/.github/workflows/gcc.yml b/.github/workflows/gcc.yml index 7c6df7f..30772de 100644 --- a/.github/workflows/gcc.yml +++ b/.github/workflows/gcc.yml @@ -11,15 +11,24 @@ jobs: runs-on: ubuntu-latest steps: - - uses: action/checkout@4.1.2 + - uses: actions/checkout@latest - uses: egor-tensin/setup-gcc@v1 with: version: latest platform: x64 + - uses: lukka/get-cmake@latest + + - uses: lukka/run-vcpkg@v11 + with: + vcpkgDirectory: ${{ github.workspace }}/vcpkg + runVcpkgInstall: true + vcpkgJsonGlob: ${{ github.workspace }}/vcpkg.json + - uses: threeal/cmake-action@main with: - generator: Ninja + generator: Unix Makefiles c-compiler: gcc - cxx-compiler: g++ \ No newline at end of file + cxx-compiler: g++ + options: CMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake \ No newline at end of file diff --git a/.github/workflows/msvc.yml b/.github/workflows/msvc.yml index 5a807bf..63990b0 100644 --- a/.github/workflows/msvc.yml +++ b/.github/workflows/msvc.yml @@ -10,14 +10,23 @@ jobs: runs-on: windows-latest steps: - - uses: actions/checkout@v4.1.2 + - uses: actions/checkout@latest - uses: TheMrMilchmann/setup-msvc-dev@v3 with: arch: x64 + - uses: lukka/get-cmake@latest + + - uses: lukka/run-vcpkg@v11 + with: + vcpkgDirectory: ${{ github.workspace }}/vcpkg + runVcpkgInstall: true + vcpkgJsonGlob: ${{ github.workspace }}/vcpkg.json + - uses: threeal/cmake-action@main with: generator: Ninja c-compiler: cl - cxx-compiler: cl \ No newline at end of file + cxx-compiler: cl + options: CMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake \ No newline at end of file From c3723ff9e39bc1aeb7ec99a35c25c76d603a13ed Mon Sep 17 00:00:00 2001 From: yizhou Date: Thu, 11 Apr 2024 03:05:20 +0800 Subject: [PATCH 10/14] fix: actions --- .github/workflows/clang.yml | 2 +- .github/workflows/gcc.yml | 2 +- .github/workflows/msvc.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang.yml b/.github/workflows/clang.yml index ea8cff9..129525b 100644 --- a/.github/workflows/clang.yml +++ b/.github/workflows/clang.yml @@ -9,7 +9,7 @@ jobs: build: runs-on: macos-latest steps: - - uses: actions/checkout@latest + - uses: actions/checkout@v4 - uses: KyleMayes/install-llvm-action@v2 with: diff --git a/.github/workflows/gcc.yml b/.github/workflows/gcc.yml index 30772de..db407d3 100644 --- a/.github/workflows/gcc.yml +++ b/.github/workflows/gcc.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@latest + - uses: actions/checkout@v4 - uses: egor-tensin/setup-gcc@v1 with: diff --git a/.github/workflows/msvc.yml b/.github/workflows/msvc.yml index 63990b0..4fde5ee 100644 --- a/.github/workflows/msvc.yml +++ b/.github/workflows/msvc.yml @@ -10,7 +10,7 @@ jobs: runs-on: windows-latest steps: - - uses: actions/checkout@latest + - uses: actions/checkout@v4 - uses: TheMrMilchmann/setup-msvc-dev@v3 with: From 741cd35c1ad2bea6ad64554203a25260dd64a94b Mon Sep 17 00:00:00 2001 From: yizhou Date: Thu, 11 Apr 2024 03:11:20 +0800 Subject: [PATCH 11/14] fix: actions --- .github/workflows/clang.yml | 2 +- .github/workflows/gcc.yml | 2 +- .github/workflows/msvc.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang.yml b/.github/workflows/clang.yml index 129525b..3871a61 100644 --- a/.github/workflows/clang.yml +++ b/.github/workflows/clang.yml @@ -22,7 +22,7 @@ jobs: with: vcpkgDirectory: ${{ github.workspace }}/vcpkg runVcpkgInstall: true - vcpkgJsonGlob: ${{ github.workspace }}/vcpkg.json + vcpkgJsonGlob: vcpkg.json - uses: threeal/cmake-action@main with: diff --git a/.github/workflows/gcc.yml b/.github/workflows/gcc.yml index db407d3..c196939 100644 --- a/.github/workflows/gcc.yml +++ b/.github/workflows/gcc.yml @@ -24,7 +24,7 @@ jobs: with: vcpkgDirectory: ${{ github.workspace }}/vcpkg runVcpkgInstall: true - vcpkgJsonGlob: ${{ github.workspace }}/vcpkg.json + vcpkgJsonGlob: vcpkg.json - uses: threeal/cmake-action@main with: diff --git a/.github/workflows/msvc.yml b/.github/workflows/msvc.yml index 4fde5ee..e4226aa 100644 --- a/.github/workflows/msvc.yml +++ b/.github/workflows/msvc.yml @@ -22,7 +22,7 @@ jobs: with: vcpkgDirectory: ${{ github.workspace }}/vcpkg runVcpkgInstall: true - vcpkgJsonGlob: ${{ github.workspace }}/vcpkg.json + vcpkgJsonGlob: vcpkg.json - uses: threeal/cmake-action@main with: From 7e534bb427c9757f6b17f5626f7983b78d550ead Mon Sep 17 00:00:00 2001 From: yizhou Date: Thu, 11 Apr 2024 03:14:26 +0800 Subject: [PATCH 12/14] fix: vcpkg baseline --- vcpkg.json | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/vcpkg.json b/vcpkg.json index c3d275f..d1cb6cd 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -2,7 +2,9 @@ "name": "dogcom", "version-string": "1.0.0", "dependencies": [ - "boost-asio", "boost-log", + "boost-asio", + "boost-log", "cryptopp" - ] -} \ No newline at end of file + ], + "builtin-baseline": "1751f9f8c732c2e6f9e81ce56c10e4c4aa265b4a" +} From 68148ff46739e3828ff2162b02ad2b577b1c9092 Mon Sep 17 00:00:00 2001 From: Don Yihtseu Date: Thu, 11 Apr 2024 03:28:55 +0800 Subject: [PATCH 13/14] fix: non-null corotine --- src/keepalive.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/keepalive.cpp b/src/keepalive.cpp index b0bbbee..d2ab508 100644 --- a/src/keepalive.cpp +++ b/src/keepalive.cpp @@ -6,11 +6,11 @@ namespace dogcom { awaitable client_t::keepalive1() { - + throw std::runtime_error("Not Implemented"); } awaitable client_t::keepalive2() { - + throw std::runtime_error("Not Implemented"); } From eea13edf49e6deb9fd9501adea53cab3bdc8f927 Mon Sep 17 00:00:00 2001 From: Don Yihtseu Date: Thu, 11 Apr 2024 03:29:45 +0800 Subject: [PATCH 14/14] fix: format dependency --- src/dhcp.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/dhcp.cpp b/src/dhcp.cpp index e1cb861..63f1ff4 100644 --- a/src/dhcp.cpp +++ b/src/dhcp.cpp @@ -2,6 +2,7 @@ // Created by Don Yihtseu on 11/04/2024. // #include +#include #include #include #include