diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 00000000..32acafe8 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,41 @@ +# LBBS — Copilot Instructions + +Short, specific pointers to help an AI coding agent be productive in this repo. + +**Build & Test** +- **Install deps**: libssh, libpcre2 and a MySQL/MariaDB client dev package (e.g., libssh-dev, libpcre2-dev, libmariadb-dev or libmysqlclient-dev). CI also installs `libsystemd-dev`. +- **Build**: `autoreconf --install --force` then `./configure --enable-systemd --disable-silent-rules` and `make`. +- **Run tests**: `make check` (tests are custom binaries built under `src/`, e.g. `test_trie_dict`). CI runs `make check` and `make distcheck` (see [.github/workflows/makefile.yml](.github/workflows/makefile.yml#L1-L40)). + +**Run & Debug** +- **Server binary**: `src/bbsd` (entry: [src/main.c](src/main.c#L1-L60)). +- **Run in foreground**: `src/bbsd -f` (use `--display-log`/`--display-error-log` to redirect logs to stderr). +- **Debug**: run with `gdb --args src/bbsd -f` or attach to the process; logs are in `log/`. + +**High-level architecture** +- **Process**: `bbsd` (server) loads config and data files at start, initializes shared pools, listens for telnet/ssh clients and spawns handlers. +- **Networking**: accept loop and client lifecycle are in [src/net_server.c](src/net_server.c#L1-L140); user-facing shuttle/menu networking is in [src/bbs_net.c](src/bbs_net.c#L1-L60). +- **IO / Encoding**: terminal IO and non-blocking I/O are handled in [src/io.c](src/io.c#L1-L80). The project supports epoll/poll (conditional) and uses iconv for charset conversion. Default charset is `UTF-8`. +- **Auth & DB**: login and auth live in [src/login.c](src/login.c#L1-L40); database access is in [src/database.c](src/database.c#L1-L40). DB credentials are read from `conf/bbsd.conf` (example in [conf/bbsd.conf](conf/bbsd.conf#L1-L40)). + +**Config & runtime files** +- **Configs**: `conf/` contains runtime config (e.g., `conf/bbsd.conf`, `conf/bbsnet.conf`). Config constants are centralized in [src/common.c](src/common.c#L1-L40) as `CONF_*`. +- **b b snet format**: each line is `ORG SITE HOST PORT USE_SSH(Y/N) CHARSET` (see how it's parsed in [src/bbs_net.c](src/bbs_net.c#L88-L118)). +- **SSH keys**: host keys live in `conf/` (see `SSH_HOST_*` constants in [src/common.c](src/common.c#L1-L40)). +- **Data & runtime**: static text files in `data/`; generated runtime files and caches in `var/`; logs in `log/`. + +**Project patterns and conventions** +- **Autotools**: use `autoconf/automake` (`configure.ac`, `Makefile.am`); prefer `autoreconf` + `./configure` for local iterations. +- **Tests**: tests are small programs named `test_*` in `src/` and are exercised by `make check`. Add new tests as `test_.c` and register in `src/Makefile.am`. +- **Error/logging**: prefer `log_common()` / `log_error()` instead of printing to stdout. Most functions return negative on error. +- **Globals & constants**: global config names use prefixes like `BBS_`, `VAR_`, `CONF_` (see [src/common.c](src/common.c#L1-L80)). + +**When changing networking/IO code** +- Run `make check` and manually run `src/bbsd -f` to exercise interactive code paths. +- For SSH-related changes, ensure `libssh` is present and try `test_ssh_server` in `src/`. +- For charset changes, check `io.c` and the per-connection iconv usage (see [src/bbs_net.c](src/bbs_net.c#L250-L320)). + +**CI & packaging** +- CI uses Ubuntu runners, installs system packages and runs `./configure`, `make`, `make check`, `make distcheck` (see [.github/workflows/makefile.yml](.github/workflows/makefile.yml#L1-L80)). + +If any of these sections look incomplete or you want more examples (e.g., walk-through for adding a test or adding a `configure` option), tell me which area to expand. I can iterate. (Drafted by AI; please confirm tone and level of detail.) \ No newline at end of file diff --git a/conf/lbbs.logrotate.in b/conf/lbbs.logrotate.in index 67dfc6d1..45930fe4 100644 --- a/conf/lbbs.logrotate.in +++ b/conf/lbbs.logrotate.in @@ -1,7 +1,7 @@ @prefix@/log/*.log { daily missingok - compress + rotate 90 delaycompress notifempty create 640 bbs bbs diff --git a/configure.ac b/configure.ac index 88a93b6a..fa066a99 100644 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ # Process this file with autoconf to produce a configure script. AC_PREREQ([2.69]) -AC_INIT([lbbs],[1.6.2]) +AC_INIT([lbbs],[1.6.3]) AC_CONFIG_SRCDIR([src/]) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_MACRO_DIRS([m4]) diff --git a/include/article_favor.h b/include/article_favor.h index 7558680b..8342ee30 100644 --- a/include/article_favor.h +++ b/include/article_favor.h @@ -44,7 +44,7 @@ extern int article_favor_check(int32_t aid, const ARTICLE_FAVOR *p_favor); // Set specific article as favorite extern int article_favor_set(int32_t aid, ARTICLE_FAVOR *p_favor, int state); -extern int query_favor_articles(ARTICLE_FAVOR *p_favor, int page_id, ARTICLE **p_articles, +extern int query_favor_articles(ARTICLE_FAVOR *p_favor, int page_id, const ARTICLE **p_articles, char p_snames[][BBS_section_name_max_len + 1], int *p_article_count, int *p_page_count); #endif //_ARTICLE_FAVOR_H_ diff --git a/include/hash_dict.h b/include/hash_dict.h index 799ce84d..c3ec7748 100644 --- a/include/hash_dict.h +++ b/include/hash_dict.h @@ -39,9 +39,16 @@ typedef struct hash_dict_t HASH_DICT; extern HASH_DICT *hash_dict_create(int item_count_limit); extern void hash_dict_destroy(HASH_DICT *p_dict); +// Return 1 if existing key updated, 0 if new key added, -1 on error extern int hash_dict_set(HASH_DICT *p_dict, uint64_t key, int64_t value); + +// Return 1 if existing key updated, 0 if key not exist, -1 on error extern int hash_dict_inc(HASH_DICT *p_dict, uint64_t key, int64_t value_inc); + +// Return 1 if key found, 0 if key not exist, -1 on error extern int hash_dict_get(HASH_DICT *p_dict, uint64_t key, int64_t *p_value); + +// Return 1 if key deleted, 0 if key not exist, -1 on error extern int hash_dict_del(HASH_DICT *p_dict, uint64_t key); inline unsigned int hash_dict_item_count(HASH_DICT *p_dict) diff --git a/include/log.h b/include/log.h index 70fb893a..ab6b8d57 100644 --- a/include/log.h +++ b/include/log.h @@ -13,8 +13,9 @@ enum log_level_t { - LOG_LEVEL_COMMON = 1, - LOG_LEVEL_ERROR = 2, + LOG_LEVEL_COMMON, + LOG_LEVEL_ERROR, + LOG_LEVEL_DEBUG, }; extern int log_begin(const char *common_log_file, const char *error_log_file); @@ -25,6 +26,12 @@ extern int log_printf(enum log_level_t log_level, const char *app_file, int app_ #define log_common(...) log_printf(LOG_LEVEL_COMMON, __FILE__, __LINE__, __VA_ARGS__) #define log_error(...) log_printf(LOG_LEVEL_ERROR, __FILE__, __LINE__, __VA_ARGS__) +#ifdef _DEBUG +#define log_debug(...) log_printf(LOG_LEVEL_DEBUG, __FILE__, __LINE__, __VA_ARGS__) +#else +#define log_debug(...) ((void)0) +#endif + extern int log_common_redir(int fd); extern int log_error_redir(int fd); diff --git a/include/section_list_loader.h b/include/section_list_loader.h index 90053623..6cf830e1 100644 --- a/include/section_list_loader.h +++ b/include/section_list_loader.h @@ -42,7 +42,7 @@ extern int section_list_loader_launch(void); // Return on success : real page_id (>= 0) // failure : error number (< 0) -extern int query_section_articles(SECTION_LIST *p_section, int page_id, ARTICLE *p_articles[], +extern int query_section_articles(SECTION_LIST *p_section, int page_id, const ARTICLE *p_articles[], int *p_article_count, int *p_page_count, int *p_ontop_start_offset); // Input direction = 0 : locate p_article_cur diff --git a/src/article_cache.c b/src/article_cache.c index 39431c2e..db57d8a1 100644 --- a/src/article_cache.c +++ b/src/article_cache.c @@ -129,11 +129,9 @@ int article_cache_generate(const char *cache_dir, const ARTICLE *p_article, cons if (header_len != cache.line_offsets[header_line_cnt]) { -#ifdef _DEBUG - log_error("Header of article(aid=%d) is truncated from %ld to %ld\n, body_line=%ld, body_line_limit=%ld", + log_debug("Header of article(aid=%d) is truncated from %ld to %ld\n, body_line=%ld, body_line_limit=%ld", p_article->aid, header_len, cache.line_offsets[header_line_cnt], header_line_cnt, MAX_SPLIT_FILE_LINES); -#endif header_len = (size_t)cache.line_offsets[header_line_cnt]; } @@ -147,11 +145,9 @@ int article_cache_generate(const char *cache_dir, const ARTICLE *p_article, cons if (body_len != (size_t)cache.line_offsets[cache.line_total]) { -#ifdef _DEBUG - log_error("Body of article(aid=%d) is truncated from %ld to %ld, body_line=%ld, body_line_limit=%ld\n", + log_debug("Body of article(aid=%d) is truncated from %ld to %ld, body_line=%ld, body_line_limit=%ld\n", p_article->aid, body_len, cache.line_offsets[cache.line_total], body_line_cnt, MAX_SPLIT_FILE_LINES - header_line_cnt); -#endif cache.data_len = header_len + (size_t)(cache.line_offsets[cache.line_total]); } @@ -165,11 +161,9 @@ int article_cache_generate(const char *cache_dir, const ARTICLE *p_article, cons if (footer_len != cache.line_offsets[cache.line_total + footer_line_cnt]) { -#ifdef _DEBUG - log_error("Footer of article(aid=%d) is truncated from %ld to %ld, footer_line=%ld, footer_line_limit=%ld\n", + log_debug("Footer of article(aid=%d) is truncated from %ld to %ld, footer_line=%ld, footer_line_limit=%ld\n", p_article->aid, footer_len, cache.line_offsets[cache.line_total + footer_line_cnt], footer_line_cnt, MAX_SPLIT_FILE_LINES - cache.line_total); -#endif footer_len = (size_t)(cache.line_offsets[cache.line_total + footer_line_cnt]); } diff --git a/src/article_favor.c b/src/article_favor.c index a93eb679..4b6f038b 100644 --- a/src/article_favor.c +++ b/src/article_favor.c @@ -445,7 +445,7 @@ int article_favor_set(int32_t aid, ARTICLE_FAVOR *p_favor, int state) return 1; // Set complete } -int query_favor_articles(ARTICLE_FAVOR *p_favor, int page_id, ARTICLE **p_articles, +int query_favor_articles(ARTICLE_FAVOR *p_favor, int page_id, const ARTICLE **p_articles, char p_snames[][BBS_section_name_max_len + 1], int *p_article_count, int *p_page_count) { SECTION_LIST *p_section; diff --git a/src/article_favor_display.c b/src/article_favor_display.c index d94f087c..7d1fb275 100644 --- a/src/article_favor_display.c +++ b/src/article_favor_display.c @@ -56,7 +56,7 @@ static int article_favor_draw_screen(int display_sname) return 0; } -static int article_favor_draw_items(int page_id, ARTICLE *p_articles[], char p_snames[][BBS_section_name_max_len + 1], +static int article_favor_draw_items(int page_id, const ARTICLE *p_articles[], char p_snames[][BBS_section_name_max_len + 1], int article_count, int display_sname) { char str_time[LINE_BUFFER_LEN]; @@ -172,7 +172,7 @@ static enum select_cmd_t article_favor_select(int total_page, int item_count, in switch (ch) { case KEY_NULL: // broken pipe - log_error("KEY_NULL\n"); + log_debug("KEY_NULL\n"); case KEY_ESC: case KEY_LEFT: return EXIT_LIST; // exit list @@ -299,7 +299,7 @@ int article_favor_display(ARTICLE_FAVOR *p_favor) char page_info_str[LINE_BUFFER_LEN]; char snames[BBS_article_limit_per_page][BBS_section_name_max_len + 1]; - ARTICLE *p_articles[BBS_article_limit_per_page]; + const ARTICLE *p_articles[BBS_article_limit_per_page]; int article_count; int page_count; int page_id = 0; diff --git a/src/bbs_main.c b/src/bbs_main.c index d697ea85..40be68d6 100644 --- a/src/bbs_main.c +++ b/src/bbs_main.c @@ -171,9 +171,7 @@ int bbs_center() if (ch != KEY_NULL && ch != KEY_TIMEOUT) { BBS_last_access_tm = time(NULL); -#ifdef _DEBUG - log_error("Debug: BBS_last_access_tm is updated\n"); -#endif + log_debug("Debug: BBS_last_access_tm is updated\n"); } if (bbs_menu.choose_step == 0 && time(NULL) - t_last_action >= 10) @@ -194,7 +192,7 @@ int bbs_center() switch (ch) { case KEY_NULL: // broken pipe - log_error("KEY_NULL\n"); + log_debug("KEY_NULL\n"); loop = 0; break; case KEY_TIMEOUT: diff --git a/src/bbs_net.c b/src/bbs_net.c index 737cdf3e..b91bc82f 100644 --- a/src/bbs_net.c +++ b/src/bbs_net.c @@ -49,11 +49,13 @@ static const char MENU_CONF_DELIM[] = " \t\r\n"; enum _bbs_net_constant_t { - MAX_PROCESS_BAR_LEN = 30, MAXSTATION = 26 * 2, STATION_PER_LINE = 4, USERNAME_MAX_LEN = 20, PASSWORD_MAX_LEN = 20, + REMOTE_CONNECT_TIMEOUT = 10, // seconds + SSH_CONNECT_TIMEOUT = 5, // seconds + PROGRESS_BAR_LEN = 30, }; struct _bbsnet_conf @@ -61,13 +63,15 @@ struct _bbsnet_conf char org_name[40]; char site_name[40]; char host_name[IP_ADDR_LEN]; - in_port_t port; + char port[6]; int8_t use_ssh; char charset[CHARSET_MAX_LEN + 1]; } bbsnet_conf[MAXSTATION]; static MENU_SET bbsnet_menu; +static void unload_bbsnet_conf(void); + static int load_bbsnet_conf(const char *file_config) { FILE *fp; @@ -75,18 +79,16 @@ static int load_bbsnet_conf(const char *file_config) MENU_ITEM *p_menu_item; MENU_ITEM_ID menu_item_id; char line[LINE_BUFFER_LEN], *t1, *t2, *t3, *t4, *t5, *t6, *saveptr; + long port; + char *endptr; - fp = fopen(file_config, "r"); - if (fp == NULL) - { - return -1; - } + unload_bbsnet_conf(); bbsnet_menu.p_menu_pool = calloc(1, sizeof(MENU)); if (bbsnet_menu.p_menu_pool == NULL) { log_error("calloc(p_menu_pool) error\n"); - return -3; + return -1; } bbsnet_menu.menu_count = 1; @@ -94,7 +96,8 @@ static int load_bbsnet_conf(const char *file_config) if (bbsnet_menu.p_menu_item_pool == NULL) { log_error("calloc(p_menu_item_pool) error\n"); - return -3; + unload_bbsnet_conf(); + return -1; } bbsnet_menu.menu_item_count = MAXSTATION; @@ -105,6 +108,13 @@ static int load_bbsnet_conf(const char *file_config) p_menu->title.show = 0; p_menu->screen_show = 0; + fp = fopen(file_config, "r"); + if (fp == NULL) + { + unload_bbsnet_conf(); + return -2; + } + menu_item_id = 0; while (fgets(line, sizeof(line), fp) && menu_item_id < MAXSTATION) { @@ -116,7 +126,7 @@ static int load_bbsnet_conf(const char *file_config) t6 = strtok_r(NULL, MENU_CONF_DELIM, &saveptr); if (t1 == NULL || t2 == NULL || t3 == NULL || t4 == NULL || - t5 == NULL || t6 == NULL || line[0] == '#' || line[0] == '*') + t5 == NULL || t6 == NULL || t1[0] == '#') { continue; } @@ -127,7 +137,16 @@ static int load_bbsnet_conf(const char *file_config) bbsnet_conf[menu_item_id].org_name[sizeof(bbsnet_conf[menu_item_id].org_name) - 1] = '\0'; strncpy(bbsnet_conf[menu_item_id].host_name, t3, sizeof(bbsnet_conf[menu_item_id].host_name) - 1); bbsnet_conf[menu_item_id].host_name[sizeof(bbsnet_conf[menu_item_id].host_name) - 1] = '\0'; - bbsnet_conf[menu_item_id].port = (in_port_t)(t4 ? atoi(t4) : 23); + port = strtol(t4, &endptr, 10); + if (*endptr != '\0' || port <= 0 || port > 65535) + { + log_error("Invalid port value %ld of menu item %d\n", port, menu_item_id); + fclose(fp); + unload_bbsnet_conf(); + return -3; + } + strncpy(bbsnet_conf[menu_item_id].port, t4, sizeof(bbsnet_conf[menu_item_id].port) - 1); + bbsnet_conf[menu_item_id].port[sizeof(bbsnet_conf[menu_item_id].port) - 1] = '\0'; bbsnet_conf[menu_item_id].use_ssh = (toupper(t5[0]) == 'Y'); strncpy(bbsnet_conf[menu_item_id].charset, t6, sizeof(bbsnet_conf[menu_item_id].charset) - 1); bbsnet_conf[menu_item_id].charset[sizeof(bbsnet_conf[menu_item_id].charset) - 1] = '\0'; @@ -136,7 +155,9 @@ static int load_bbsnet_conf(const char *file_config) if (p_menu_item == NULL) { log_error("get_menu_item_by_id(%d) return NULL pointer\n", menu_item_id); - return -1; + fclose(fp); + unload_bbsnet_conf(); + return -3; } p_menu_item->row = (int16_t)(2 + menu_item_id / STATION_PER_LINE); @@ -146,9 +167,9 @@ static int load_bbsnet_conf(const char *file_config) p_menu_item->priv = 0; p_menu_item->level = 0; p_menu_item->name[0] = - (char)(menu_item_id < MAXSTATION / 2 ? 'A' + menu_item_id : 'a' + menu_item_id); + (char)(menu_item_id < MAXSTATION / 2 ? 'A' + menu_item_id : 'a' + menu_item_id - MAXSTATION / 2); p_menu_item->name[1] = '\0'; - snprintf(p_menu_item->text, sizeof(p_menu_item->text), "%c. %s", + snprintf(p_menu_item->text, sizeof(p_menu_item->text), "\033[1;36m%c.\033[m %s", p_menu_item->name[0], bbsnet_conf[menu_item_id].site_name); p_menu->items[p_menu->item_count] = menu_item_id; @@ -171,48 +192,75 @@ static void unload_bbsnet_conf(void) bbsnet_menu.menu_count = 0; bbsnet_menu.menu_item_count = 0; - free(bbsnet_menu.p_menu_pool); - bbsnet_menu.p_menu_pool = NULL; - free(bbsnet_menu.p_menu_item_pool); - bbsnet_menu.p_menu_item_pool = NULL; + if (bbsnet_menu.p_menu_pool) + { + free(bbsnet_menu.p_menu_pool); + bbsnet_menu.p_menu_pool = NULL; + } + + if (bbsnet_menu.p_menu_item_pool) + { + free(bbsnet_menu.p_menu_item_pool); + bbsnet_menu.p_menu_item_pool = NULL; + } } -static void process_bar(int n, int len) +static void progress_bar(int percent, int len) { + char line[LINE_BUFFER_LEN]; char buf[LINE_BUFFER_LEN]; char buf2[LINE_BUFFER_LEN]; + int pos; - if (len > LINE_BUFFER_LEN) + if (len < 4) + { + len = 4; + } + else if (len + 2 > LINE_BUFFER_LEN) { - len = LINE_BUFFER_LEN - 1; + len = LINE_BUFFER_LEN - 3; } - if (n < 0) + if (percent < 0) { - n = 0; + percent = 0; } - else if (n > len) + else if (percent > 100) { - n = len; + percent = 100; } + pos = len * percent / 100; + + line[0] = ' '; + for (int i = 1; i <= len; i++) + { + line[i] = '-'; + } + line[len + 1] = ' '; + line[len + 2] = '\0'; + + snprintf(buf, sizeof(buf), "%*s%3d%%%*s", + (len - 4) / 2, "", percent, (len - 4 + 1) / 2, ""); + memcpy(buf2, buf, (size_t)pos); + buf2[pos] = '\0'; + moveto(4, 1); - prints(" ------------------------------ \r\n"); - snprintf(buf, sizeof(buf), " %3d%% ", n * 100 / len); - memcpy(buf2, buf, (size_t)n); - buf2[n] = '\0'; - prints("|\033[46m%s\033[44m%s\033[m|\r\n", buf2, buf + n); - prints(" ------------------------------ \r\n"); + prints("%s\r\n", line); + prints("|\033[46m%s\033[44m%s\033[m|\r\n", buf2, buf + pos); + prints("%s\r\n", line); iflush(); } static int bbsnet_connect(int n) { - int sock, ret, loop, error; + int sock = -1; + int ret = 0; + int loop; + int error; int sock_connected = 0; - int flags_sock; - int flags_stdin; - int flags_stdout; - int len; + int flags_sock = -1; + int flags_stdin = -1; + int flags_stdout = -1; struct sockaddr_in sin; char input_buf[LINE_BUFFER_LEN]; char output_buf[LINE_BUFFER_LEN]; @@ -226,13 +274,13 @@ static int bbsnet_connect(int n) int output_conv_len = 0; int input_conv_offset = 0; int output_conv_offset = 0; - iconv_t input_cd = NULL; - iconv_t output_cd = NULL; - char tocode[32]; + iconv_t input_cd = (iconv_t)(-1); + iconv_t output_cd = (iconv_t)(-1); + char tocode[CHARSET_MAX_LEN + 20]; #ifdef HAVE_SYS_EPOLL_H struct epoll_event ev, events[MAX_EVENTS]; - int epollfd; + int epollfd = -1; #else struct pollfd pfds[3]; #endif @@ -242,20 +290,21 @@ static int bbsnet_connect(int n) int stdout_write_wait = 0; int sock_read_wait = 0; int sock_write_wait = 0; - struct hostent *p_host = NULL; + struct addrinfo hints, *res = NULL; int tos; - char remote_addr[IP_ADDR_LEN]; + char remote_addr[INET_ADDRSTRLEN]; int remote_port; - char local_addr[IP_ADDR_LEN]; + char local_addr[INET_ADDRSTRLEN]; int local_port; socklen_t sock_len; - time_t t_used = time(NULL); - struct tm *tm_used; + time_t t_begin, t_used; + struct timespec ts_begin, ts_now; + int progress, progress_last; int ch; char remote_user[USERNAME_MAX_LEN + 1]; char remote_pass[PASSWORD_MAX_LEN + 1]; - ssh_session session = NULL; - ssh_channel channel = NULL; + ssh_session outbound_session = NULL; + ssh_channel outbound_channel = NULL; int ssh_process_config = 0; int ssh_log_level = SSH_LOG_NOLOG; @@ -310,63 +359,114 @@ static int bbsnet_connect(int n) bbsnet_conf[n].site_name, bbsnet_conf[n].host_name); iflush(); - p_host = gethostbyname(bbsnet_conf[n].host_name); + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; - if (p_host == NULL) + if ((ret = getaddrinfo(BBS_address, NULL, &hints, &res)) != 0) { - prints("\033[1;31m查找主机名失败!\033[m\r\n"); - press_any_key(); - return -1; + log_error("getaddrinfo() error (%d): %s\n", ret, gai_strerror(ret)); + ret = -1; + goto cleanup; } - sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (inet_ntop(AF_INET, &(((struct sockaddr_in *)res->ai_addr)->sin_addr), local_addr, sizeof(local_addr)) == NULL) + { + log_error("inet_ntop() error (%d)\n", errno); + ret = -1; + goto cleanup; + } + local_port = ntohs(((struct sockaddr_in *)res->ai_addr)->sin_port); + sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (sock < 0) { - prints("\033[1;31m无法创建socket!\033[m\r\n"); - press_any_key(); - return -1; + log_error("socket() error (%d)\n", errno); + ret = -1; + goto cleanup; } - sin.sin_family = AF_INET; - sin.sin_addr.s_addr = (BBS_address[0] != '\0' ? inet_addr(BBS_address) : INADDR_ANY); - sin.sin_port = 0; - - if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) + if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) { - log_error("Bind address %s:%u failed (%d)\n", - inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), errno); - return -2; + log_error("bind(%s:%u) error (%d)\n", local_addr, local_port, errno); + ret = -1; + goto cleanup; } - memset(&sin, 0, sizeof(sin)); - sin.sin_family = AF_INET; - sin.sin_addr = *(struct in_addr *)p_host->h_addr_list[0]; - sin.sin_port = htons(bbsnet_conf[n].port); + freeaddrinfo(res); + res = NULL; - strncpy(remote_addr, inet_ntoa(sin.sin_addr), sizeof(remote_addr) - 1); - remote_addr[sizeof(remote_addr) - 1] = '\0'; - remote_port = ntohs(sin.sin_port); + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_flags = AI_NUMERICSERV; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + + if ((ret = getaddrinfo(bbsnet_conf[n].host_name, bbsnet_conf[n].port, &hints, &res)) != 0) + { + log_error("getaddrinfo() error (%d): %s\n", ret, gai_strerror(ret)); + prints("\033[1;31m查找主机名失败!\033[m\r\n"); + press_any_key(); + ret = -1; + goto cleanup; + } - prints("\033[1;32m穿梭进度条提示您当前已使用的时间,按\033[1;33mCtrl+C\033[1;32m中断。\033[m\r\n"); - process_bar(0, MAX_PROCESS_BAR_LEN); + if (inet_ntop(AF_INET, &(((struct sockaddr_in *)res->ai_addr)->sin_addr), remote_addr, sizeof(remote_addr)) == NULL) + { + log_error("inet_ntop() error (%d)\n", errno); + ret = -1; + goto cleanup; + } + remote_port = ntohs(((struct sockaddr_in *)res->ai_addr)->sin_port); // Set socket as non-blocking - flags_sock = fcntl(sock, F_GETFL, 0); - fcntl(sock, F_SETFL, flags_sock | O_NONBLOCK); + if ((flags_sock = fcntl(sock, F_GETFL, 0)) == -1) + { + log_error("fcntl(F_GETFL) error (%d)\n", errno); + ret = -1; + goto cleanup; + } + if ((fcntl(sock, F_SETFL, flags_sock | O_NONBLOCK)) == -1) + { + log_error("fcntl(F_SETFL) error (%d)\n", errno); + ret = -1; + goto cleanup; + } // Set STDIN/STDOUT as non-blocking - flags_stdin = fcntl(STDIN_FILENO, F_GETFL, 0); - flags_stdout = fcntl(STDOUT_FILENO, F_GETFL, 0); - fcntl(STDIN_FILENO, F_SETFL, flags_stdin | O_NONBLOCK); - fcntl(STDOUT_FILENO, F_SETFL, flags_stdout | O_NONBLOCK); + if ((flags_stdin = fcntl(STDIN_FILENO, F_GETFL, 0)) == -1) + { + log_error("fcntl(F_GETFL) error (%d)\n", errno); + ret = -1; + goto cleanup; + } + if ((flags_stdout = fcntl(STDOUT_FILENO, F_GETFL, 0)) == -1) + { + log_error("fcntl(F_GETFL) error (%d)\n", errno); + ret = -1; + goto cleanup; + } + if ((fcntl(STDIN_FILENO, F_SETFL, flags_stdin | O_NONBLOCK)) == -1) + { + log_error("fcntl(F_SETFL) error (%d)\n", errno); + ret = -1; + goto cleanup; + } + if ((fcntl(STDOUT_FILENO, F_SETFL, flags_stdout | O_NONBLOCK)) == -1) + { + log_error("fcntl(F_SETFL) error (%d)\n", errno); + ret = -1; + goto cleanup; + } #ifdef HAVE_SYS_EPOLL_H epollfd = epoll_create1(0); if (epollfd < 0) { log_error("epoll_create1() error (%d)\n", errno); - return -1; + ret = -1; + goto cleanup; } ev.events = EPOLLOUT | EPOLLET; @@ -374,6 +474,7 @@ static int bbsnet_connect(int n) if (epoll_ctl(epollfd, EPOLL_CTL_ADD, sock, &ev) == -1) { log_error("epoll_ctl(socket) error (%d)\n", errno); + ret = -1; goto cleanup; } @@ -382,13 +483,19 @@ static int bbsnet_connect(int n) if (epoll_ctl(epollfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev) == -1) { log_error("epoll_ctl(STDIN_FILENO) error (%d)\n", errno); + ret = -1; goto cleanup; } #endif while (!SYS_server_exit) { - if ((ret = connect(sock, (struct sockaddr *)&sin, sizeof(sin))) < 0) + if ((ret = connect(sock, res->ai_addr, res->ai_addrlen)) == 0) + { + sock_connected = 1; + break; + } + else if (ret < 0) { if (errno == EAGAIN || errno == EALREADY || errno == EINPROGRESS) { @@ -404,19 +511,33 @@ static int bbsnet_connect(int n) else { log_error("connect(socket) error (%d)\n", errno); - prints("\033[1;31m连接失败!\033[m\r\n"); press_any_key(); - + ret = -1; goto cleanup; } } } - for (int j = 0; j < MAX_PROCESS_BAR_LEN && !sock_connected && !SYS_server_exit; j++) + progress = progress_last = 0; + prints("\033[1;32m连接进行中,按\033[1;33mCtrl+C\033[1;32m中断。\033[m\r\n"); + progress_bar(0, PROGRESS_BAR_LEN); + + if (clock_gettime(CLOCK_REALTIME, &ts_begin) == -1) + { + log_error("clock_gettime() error (%d)\n", errno); + ret = -1; + goto cleanup; + } + ts_now = ts_begin; + + while ((ts_now.tv_sec - ts_begin.tv_sec) * 1000 + + (ts_now.tv_nsec - ts_begin.tv_nsec) / 1000 / 1000 < + REMOTE_CONNECT_TIMEOUT * 1000 && + !sock_connected && !SYS_server_exit) { #ifdef HAVE_SYS_EPOLL_H - nfds = epoll_wait(epollfd, events, MAX_EVENTS, 500); // 0.5 second + nfds = epoll_wait(epollfd, events, MAX_EVENTS, 100); // 0.1 second ret = nfds; #else pfds[0].fd = sock; @@ -424,7 +545,7 @@ static int bbsnet_connect(int n) pfds[1].fd = STDIN_FILENO; pfds[1].events = POLLIN; nfds = 2; - ret = poll(pfds, (nfds_t)nfds, 500); // 0.5 second + ret = poll(pfds, (nfds_t)nfds, 100); // 0.1 second #endif if (ret < 0) @@ -441,7 +562,31 @@ static int bbsnet_connect(int n) } else if (ret == 0) // timeout { - process_bar(j + 1, MAX_PROCESS_BAR_LEN); + if (clock_gettime(CLOCK_REALTIME, &ts_now) == -1) + { + log_error("clock_gettime() error (%d)\n", errno); + ret = -1; + goto cleanup; + } + + progress = (int)((ts_now.tv_sec - ts_begin.tv_sec) * 1000 + + (ts_now.tv_nsec - ts_begin.tv_nsec) / 1000 / 1000) / + REMOTE_CONNECT_TIMEOUT / 10 + + 1; + if (progress < 0) + { + progress = 0; + } + if (progress > 100) + { + progress = 100; + } + + if (progress > progress_last) + { + progress_last = progress; + progress_bar(progress, PROGRESS_BAR_LEN); + } } else // ret > 0 { @@ -453,15 +598,17 @@ static int bbsnet_connect(int n) if (pfds[i].fd == sock && (pfds[i].revents & POLLOUT)) #endif { - len = sizeof(error); - if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&len) < 0) + socklen_t len = sizeof(error); + if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0) { - log_error("getsockopt() error (%d) !\n", error); + log_error("getsockopt() error (%d) !\n", errno); + ret = -1; goto cleanup; } if (error == 0) { sock_connected = 1; + break; } } #ifdef HAVE_SYS_EPOLL_H @@ -476,6 +623,7 @@ static int bbsnet_connect(int n) } while (ch == 0); if (ch == Ctrl('C') || ch == KEY_ESC) { + ret = 0; goto cleanup; } } @@ -484,13 +632,15 @@ static int bbsnet_connect(int n) } if (SYS_server_exit) { + ret = 0; goto cleanup; } if (!sock_connected) { + progress_bar(100, PROGRESS_BAR_LEN); prints("\033[1;31m连接失败!\033[m\r\n"); press_any_key(); - + ret = -1; goto cleanup; } @@ -504,60 +654,82 @@ static int bbsnet_connect(int n) if (getsockname(sock, (struct sockaddr *)&sin, &sock_len) < 0) { log_error("getsockname() error: %d", errno); + ret = -1; goto cleanup; } - strncpy(local_addr, inet_ntoa(sin.sin_addr), sizeof(local_addr) - 1); - local_addr[sizeof(local_addr) - 1] = '\0'; + if (inet_ntop(AF_INET, &(sin.sin_addr), local_addr, sizeof(local_addr)) == NULL) + { + log_error("inet_ntop() error (%d)\n", errno); + ret = -1; + goto cleanup; + } local_port = ntohs(sin.sin_port); if (bbsnet_conf[n].use_ssh) { - session = ssh_new(); - if (session == NULL) + outbound_session = ssh_new(); + if (outbound_session == NULL) { log_error("ssh_new() error\n"); + ret = -1; goto cleanup; } - if (ssh_options_set(session, SSH_OPTIONS_FD, &sock) < 0 || - ssh_options_set(session, SSH_OPTIONS_PROCESS_CONFIG, &ssh_process_config) < 0 || - ssh_options_set(session, SSH_OPTIONS_KNOWNHOSTS, SSH_KNOWN_HOSTS_FILE) < 0 || - ssh_options_set(session, SSH_OPTIONS_HOST, bbsnet_conf[n].host_name) < 0 || - ssh_options_set(session, SSH_OPTIONS_USER, remote_user) < 0 || - ssh_options_set(session, SSH_OPTIONS_HOSTKEYS, "+ssh-rsa") < 0 || - ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &ssh_log_level) < 0) + if (ssh_options_set(outbound_session, SSH_OPTIONS_FD, &sock) < 0 || + ssh_options_set(outbound_session, SSH_OPTIONS_PROCESS_CONFIG, &ssh_process_config) < 0 || + ssh_options_set(outbound_session, SSH_OPTIONS_KNOWNHOSTS, SSH_KNOWN_HOSTS_FILE) < 0 || + ssh_options_set(outbound_session, SSH_OPTIONS_HOST, bbsnet_conf[n].host_name) < 0 || + ssh_options_set(outbound_session, SSH_OPTIONS_USER, remote_user) < 0 || + ssh_options_set(outbound_session, SSH_OPTIONS_HOSTKEYS, "+ssh-ed25519,ecdsa-sha2-nistp256,ssh-rsa") < 0 || + ssh_options_set(outbound_session, SSH_OPTIONS_LOG_VERBOSITY, &ssh_log_level) < 0) { - log_error("Error setting SSH options: %s\n", ssh_get_error(session)); + log_error("Error setting SSH options: %s\n", ssh_get_error(outbound_session)); + ret = -1; goto cleanup; } - ssh_set_blocking(session, 0); + ssh_set_blocking(outbound_session, 0); - while (!SYS_server_exit) + t_begin = time(NULL); + ret = SSH_ERROR; + while (!SYS_server_exit && time(NULL) - t_begin < SSH_CONNECT_TIMEOUT) { - ret = ssh_connect(session); + ret = ssh_connect(outbound_session); if (ret == SSH_OK) { break; } - else if (ret == SSH_ERROR) + else if (ret == SSH_AGAIN) + { + // log_debug("ssh_connect() error: SSH_AGAIN\n"); + } + else // if (ret == SSH_ERROR) { - log_error("ssh_connect() error\n"); + log_error("ssh_connect() error: SSH_ERROR\n"); + ret = -1; goto cleanup; } } + if (ret != SSH_OK) + { + prints("\033[1;31m连接超时!\033[m\r\n"); + press_any_key(); + ret = -1; + goto cleanup; + } - ret = ssh_session_is_known_server(session); + ret = ssh_session_is_known_server(outbound_session); switch (ret) { case SSH_KNOWN_HOSTS_NOT_FOUND: case SSH_KNOWN_HOSTS_UNKNOWN: - if (ssh_session_update_known_hosts(session) != SSH_OK) + if (ssh_session_update_known_hosts(outbound_session) != SSH_OK) { log_error("ssh_session_update_known_hosts(%s) error\n", bbsnet_conf[n].host_name); - prints("\033[1;31m无法添加服务器证书\033[m"); + prints("\033[1;31m无法添加服务器证书\033[m\r\n"); press_any_key(); + ret = -1; goto cleanup; } log_common("SSH key of (%s) is added into %s\n", bbsnet_conf[n].host_name, SSH_KNOWN_HOSTS_FILE); @@ -566,101 +738,135 @@ static int bbsnet_connect(int n) case SSH_KNOWN_HOSTS_CHANGED: case SSH_KNOWN_HOSTS_OTHER: log_error("ssh_session_is_known_server(%s) error: %d\n", bbsnet_conf[n].host_name, ret); - prints("\033[1;31m服务器证书已变更\033[m"); + prints("\033[1;31m服务器证书已变更\033[m\r\n"); press_any_key(); + ret = -1; goto cleanup; } - for (int i = 0; !SYS_server_exit;) + ret = SSH_AUTH_ERROR; + while (!SYS_server_exit && time(NULL) - t_begin < SSH_CONNECT_TIMEOUT) { - ret = ssh_userauth_password(session, NULL, remote_pass); + ret = ssh_userauth_password(outbound_session, NULL, remote_pass); if (ret == SSH_AUTH_SUCCESS) { break; } else if (ret == SSH_AUTH_AGAIN) { -#ifdef _DEBUG - log_error("ssh_userauth_password() error: SSH_AUTH_AGAIN\n"); -#endif + // log_debug("ssh_userauth_password() error: SSH_AUTH_AGAIN\n"); } else if (ret == SSH_AUTH_ERROR) { - log_error("ssh_userauth_password() error: %d\n", ret); + log_error("ssh_userauth_password() error: SSH_AUTH_ERROR\n"); + ret = -1; goto cleanup; } else // if (ret == SSH_AUTH_DENIED) { + log_error("ssh_userauth_password() error: SSH_AUTH_DENIED\n"); prints("\033[1;31m身份验证失败!\033[m\r\n"); - i++; - if (i < BBS_login_retry_times) - { - prints("请输入密码: "); - iflush(); - if (str_input(remote_pass, sizeof(remote_pass), NOECHO) < 0) - { - goto cleanup; - } - if (remote_pass[0] == '\0') - { - goto cleanup; - } - } - else - { - goto cleanup; - } + press_any_key(); + ret = -1; + goto cleanup; } } + if (ret != SSH_AUTH_SUCCESS) + { + prints("\033[1;31m连接超时!\033[m\r\n"); + press_any_key(); + ret = -1; + goto cleanup; + } - channel = ssh_channel_new(session); - if (channel == NULL) + outbound_channel = ssh_channel_new(outbound_session); + if (outbound_channel == NULL) { log_error("ssh_channel_new() error\n"); + ret = -1; goto cleanup; } - while (!SYS_server_exit) + ret = SSH_ERROR; + while (!SYS_server_exit && time(NULL) - t_begin < SSH_CONNECT_TIMEOUT) { - ret = ssh_channel_open_session(channel); + ret = ssh_channel_open_session(outbound_channel); if (ret == SSH_OK) { break; } - else if (ret == SSH_ERROR) + else if (ret == SSH_AGAIN) + { + // log_debug("ssh_channel_open_session() error: SSH_AGAIN\n"); + } + else // if (ret == SSH_ERROR) { - log_error("ssh_channel_open_session() error\n"); + log_error("ssh_channel_open_session() error: SSH_ERROR\n"); + ret = -1; goto cleanup; } } + if (ret != SSH_OK) + { + prints("\033[1;31m连接超时!\033[m\r\n"); + press_any_key(); + ret = -1; + goto cleanup; + } - while (!SYS_server_exit) + ret = SSH_ERROR; + while (!SYS_server_exit && time(NULL) - t_begin < SSH_CONNECT_TIMEOUT) { - ret = ssh_channel_request_pty(channel); + ret = ssh_channel_request_pty(outbound_channel); if (ret == SSH_OK) { break; } - else if (ret == SSH_ERROR) + else if (ret == SSH_AGAIN) + { + // log_debug("ssh_channel_request_pty() error: SSH_AGAIN\n"); + } + else // if (ret == SSH_ERROR) { - log_error("ssh_channel_request_pty() error\n"); + log_error("ssh_channel_request_pty() error: SSH_ERROR\n"); + ret = -1; goto cleanup; } } + if (ret != SSH_OK) + { + prints("\033[1;31m连接超时!\033[m\r\n"); + press_any_key(); + ret = -1; + goto cleanup; + } - while (!SYS_server_exit) + ret = SSH_ERROR; + while (!SYS_server_exit && time(NULL) - t_begin < SSH_CONNECT_TIMEOUT) { - ret = ssh_channel_request_shell(channel); + ret = ssh_channel_request_shell(outbound_channel); if (ret == SSH_OK) { break; } - else if (ret == SSH_ERROR) + else if (ret == SSH_AGAIN) + { + // log_debug("ssh_channel_request_shell() error: SSH_AGAIN\n"); + } + else // if (ret == SSH_ERROR) { - log_error("ssh_channel_request_shell() error\n"); + log_error("ssh_channel_request_shell() error: SSH_ERROR\n"); + ret = -1; goto cleanup; } } + if (ret != SSH_OK) + { + prints("\033[1;31m连接超时!\033[m\r\n"); + press_any_key(); + ret = -1; + goto cleanup; + } } prints("\033[1;31m连接成功!\033[m\r\n"); @@ -674,6 +880,7 @@ static int bbsnet_connect(int n) if (input_cd == (iconv_t)(-1)) { log_error("iconv_open(%s->%s) error: %d\n", stdio_charset, tocode, errno); + ret = -1; goto cleanup; } @@ -683,7 +890,7 @@ static int bbsnet_connect(int n) if (output_cd == (iconv_t)(-1)) { log_error("iconv_open(%s->%s) error: %d\n", bbsnet_conf[n].charset, tocode, errno); - iconv_close(input_cd); + ret = -1; goto cleanup; } @@ -693,6 +900,7 @@ static int bbsnet_connect(int n) if (epoll_ctl(epollfd, EPOLL_CTL_MOD, sock, &ev) == -1) { log_error("epoll_ctl(socket) error (%d)\n", errno); + ret = -1; goto cleanup; } @@ -701,25 +909,26 @@ static int bbsnet_connect(int n) if (epoll_ctl(epollfd, EPOLL_CTL_ADD, STDOUT_FILENO, &ev) == -1) { log_error("epoll_ctl(STDOUT_FILENO) error (%d)\n", errno); + ret = -1; goto cleanup; } #endif - BBS_last_access_tm = t_used = time(NULL); + BBS_last_access_tm = t_begin = time(NULL); loop = 1; while (loop && !SYS_server_exit) { if (SSH_v2 && ssh_channel_is_closed(SSH_channel)) { - log_error("SSH channel is closed\n"); + log_debug("SSH channel is closed\n"); loop = 0; break; } - if (bbsnet_conf[n].use_ssh && ssh_channel_is_closed(channel)) + if (bbsnet_conf[n].use_ssh && ssh_channel_is_closed(outbound_channel)) { - log_error("Remote SSH channel is closed\n"); + log_debug("Outbound channel is closed\n"); loop = 0; break; } @@ -762,7 +971,22 @@ static int bbsnet_connect(int n) for (int i = 0; i < nfds; i++) { #ifdef HAVE_SYS_EPOLL_H - if (events[i].data.fd == STDIN_FILENO) + if (events[i].events & (EPOLLHUP | EPOLLERR)) +#else + if (pfds[i].revents & (POLLHUP | POLLERR)) +#endif + { +#ifdef HAVE_SYS_EPOLL_H + log_debug("FD (%d) error events (%d)\n", events[i].data.fd, events[i].events); +#else + log_debug("FD (%d) error events (%d)\n", pfds[i].fd, pfds[i].revents); +#endif + loop = 0; + break; + } + +#ifdef HAVE_SYS_EPOLL_H + if (events[i].data.fd == STDIN_FILENO && (events[i].events & EPOLLIN)) #else if (pfds[i].fd == STDIN_FILENO && (pfds[i].revents & POLLIN)) #endif @@ -796,7 +1020,7 @@ static int bbsnet_connect(int n) } #ifdef HAVE_SYS_EPOLL_H - if (events[i].data.fd == STDOUT_FILENO) + if (events[i].data.fd == STDOUT_FILENO && (events[i].events & EPOLLOUT)) #else if (pfds[i].fd == STDOUT_FILENO && (pfds[i].revents & POLLOUT)) #endif @@ -814,7 +1038,7 @@ static int bbsnet_connect(int n) ret = ssh_channel_read_nonblocking(SSH_channel, input_buf + input_buf_len, sizeof(input_buf) - (uint32_t)input_buf_len, 0); if (ret == SSH_ERROR) { - log_error("ssh_channel_read_nonblocking() error: %s\n", ssh_get_error(SSH_session)); + log_debug("ssh_channel_read_nonblocking() error: %s\n", ssh_get_error(SSH_session)); loop = 0; break; } @@ -829,8 +1053,8 @@ static int bbsnet_connect(int n) // Send NO-OP to remote server input_buf[input_buf_len] = '\0'; input_buf_len++; - BBS_last_access_tm = time(NULL); + BBS_last_access_tm = time(NULL); stdin_read_wait = 0; break; // Check whether channel is still open } @@ -859,9 +1083,7 @@ static int bbsnet_connect(int n) } else if (ret == 0) // broken pipe { -#ifdef _DEBUG - log_error("read(STDIN) EOF\n"); -#endif + log_debug("read(STDIN) EOF\n"); stdin_read_wait = 0; loop = 0; break; @@ -890,7 +1112,7 @@ static int bbsnet_connect(int n) #ifdef _DEBUG for (int j = input_buf_offset; j < input_buf_len; j++) { - log_error("Debug input: <--[%u]\n", (input_buf[j] + 256) % 256); + log_debug("input: <--[%u]\n", (input_buf[j] + 256) % 256); } #endif @@ -905,7 +1127,7 @@ static int bbsnet_connect(int n) #ifdef _DEBUG for (int j = input_conv_offset; j < input_conv_len; j++) { - log_error("Debug input_conv: <--[%u]\n", (input_conv[j] + 256) % 256); + log_debug("input_conv: <--[%u]\n", (input_conv[j] + 256) % 256); } #endif } @@ -914,10 +1136,10 @@ static int bbsnet_connect(int n) { if (bbsnet_conf[n].use_ssh) { - ret = ssh_channel_write(channel, input_conv + input_conv_offset, (uint32_t)(input_conv_len - input_conv_offset)); + ret = ssh_channel_write(outbound_channel, input_conv + input_conv_offset, (uint32_t)(input_conv_len - input_conv_offset)); if (ret == SSH_ERROR) { - log_error("ssh_channel_write() error: %s\n", ssh_get_error(session)); + log_debug("ssh_channel_write() error: %s\n", ssh_get_error(outbound_session)); loop = 0; break; } @@ -939,16 +1161,14 @@ static int bbsnet_connect(int n) } else { - log_error("write(socket) error (%d)\n", errno); + log_debug("write(socket) error (%d)\n", errno); loop = 0; break; } } else if (ret == 0) // broken pipe { -#ifdef _DEBUG - log_error("write(socket) EOF\n"); -#endif + log_debug("write(socket) EOF\n"); sock_write_wait = 0; loop = 0; break; @@ -973,11 +1193,11 @@ static int bbsnet_connect(int n) { if (bbsnet_conf[n].use_ssh) { - ret = ssh_channel_read_nonblocking(channel, output_buf + output_buf_len, + ret = ssh_channel_read_nonblocking(outbound_channel, output_buf + output_buf_len, (uint32_t)(sizeof(output_buf) - (size_t)output_buf_len), 0); if (ret == SSH_ERROR) { - log_error("ssh_channel_read_nonblocking() error: %s\n", ssh_get_error(session)); + log_debug("ssh_channel_read_nonblocking() error: %s\n", ssh_get_error(outbound_session)); loop = 0; break; } @@ -1010,16 +1230,14 @@ static int bbsnet_connect(int n) } else { - log_error("read(socket) error (%d)\n", errno); + log_debug("read(socket) error (%d)\n", errno); loop = 0; break; } } else if (ret == 0) // broken pipe { -#ifdef _DEBUG - log_error("read(socket) EOF\n"); -#endif + log_debug("read(socket) EOF\n"); sock_read_wait = 0; loop = 0; break; @@ -1051,7 +1269,7 @@ static int bbsnet_connect(int n) ret = ssh_channel_write(SSH_channel, output_conv + output_conv_offset, (uint32_t)(output_conv_len - output_conv_offset)); if (ret == SSH_ERROR) { - log_error("ssh_channel_write() error: %s\n", ssh_get_error(SSH_session)); + log_debug("ssh_channel_write() error: %s\n", ssh_get_error(SSH_session)); loop = 0; break; } @@ -1073,16 +1291,14 @@ static int bbsnet_connect(int n) } else { - log_error("write(STDOUT) error (%d)\n", errno); + log_debug("write(STDOUT) error (%d)\n", errno); loop = 0; break; } } else if (ret == 0) // broken pipe { -#ifdef _DEBUG - log_error("write(STDOUT) EOF\n"); -#endif + log_debug("write(STDOUT) EOF\n"); stdout_write_wait = 0; loop = 0; break; @@ -1102,12 +1318,28 @@ static int bbsnet_connect(int n) } } - iconv_close(input_cd); - iconv_close(output_cd); + ret = 1; // Normal disconnect + BBS_last_access_tm = time(NULL); + t_used = BBS_last_access_tm - t_begin; + log_common("BBSNET disconnect, %ld days %ld hours %ld minutes %ld seconds used\n", + t_used / 86400, t_used % 86400 / 3600, t_used % 3600 / 60, t_used % 60); cleanup: + // Clear sensitive data + memset(remote_pass, 0, sizeof(remote_pass)); + memset(remote_user, 0, sizeof(remote_user)); + + if (input_cd != (iconv_t)(-1)) + { + iconv_close(input_cd); + } + if (output_cd != (iconv_t)(-1)) + { + iconv_close(output_cd); + } + #ifdef HAVE_SYS_EPOLL_H - if (close(epollfd) < 0) + if (epollfd != -1 && close(epollfd) < 0) { log_error("close(epoll) error (%d)\n"); } @@ -1115,30 +1347,40 @@ static int bbsnet_connect(int n) if (bbsnet_conf[n].use_ssh) { - ssh_channel_free(channel); - ssh_disconnect(session); - ssh_free(session); + if (outbound_channel != NULL) + { + ssh_channel_send_eof(outbound_channel); + ssh_channel_close(outbound_channel); + ssh_channel_free(outbound_channel); + } + if (outbound_session != NULL) + { + ssh_disconnect(outbound_session); + ssh_free(outbound_session); + } } // Restore STDIN/STDOUT flags - fcntl(STDIN_FILENO, F_SETFL, flags_stdin); - fcntl(STDOUT_FILENO, F_SETFL, flags_stdout); + if (flags_stdin != -1 && fcntl(STDIN_FILENO, F_SETFL, flags_stdin) == -1) + { + log_error("fcntl(F_SETFL) error (%d)\n", errno); + } + if (flags_stdout != -1 && fcntl(STDOUT_FILENO, F_SETFL, flags_stdout) == -1) + { + log_error("fcntl(F_SETFL) error (%d)\n", errno); + } - if (close(sock) == -1) + if (sock != -1 && close(sock) == -1) { log_error("Close socket failed\n"); } - t_used = time(NULL) - t_used; - tm_used = gmtime(&t_used); - - log_common("BBSNET disconnect, %d days %d hours %d minutes %d seconds used\n", - tm_used->tm_mday - 1, tm_used->tm_hour, tm_used->tm_min, - tm_used->tm_sec); - - BBS_last_access_tm = time(NULL); + if (res) + { + freeaddrinfo(res); + } - return 0; + return ret; } static int bbsnet_refresh() @@ -1180,7 +1422,7 @@ static int bbsnet_selchange() prints("|"); moveto(21, 1); clrtoeol(); - prints("|\033[1m连往: \033[1;33m%-20s\033[m 端口: \033[1;33m%-5d\033[m 编码: \033[1;33m%s\033[m", + prints("|\033[1m连往: \033[1;33m%-20s\033[m 端口: \033[1;33m%-5s\033[m 编码: \033[1;33m%s\033[m", bbsnet_conf[i].host_name, bbsnet_conf[i].port, bbsnet_conf[i].charset); moveto(21, 80); prints("|"); @@ -1191,9 +1433,16 @@ static int bbsnet_selchange() int bbs_net() { - int ch, i; + int ch; - load_bbsnet_conf(CONF_BBSNET); + if (load_bbsnet_conf(CONF_BBSNET) < 0) + { + clearscr(); + moveto(1, 1); + prints("加载穿梭配置失败!"); + press_any_key(); + return -1; + } bbsnet_refresh(); display_menu(&bbsnet_menu); @@ -1211,7 +1460,7 @@ int bbs_net() switch (ch) { case KEY_NULL: // broken pipe - log_error("KEY_NULL\n"); + log_debug("KEY_NULL\n"); goto cleanup; case KEY_TIMEOUT: if (time(NULL) - BBS_last_access_tm >= BBS_max_user_idle_time) @@ -1224,7 +1473,10 @@ int bbs_net() case Ctrl('C'): // user cancel goto cleanup; case CR: - bbsnet_connect(bbsnet_menu.menu_item_pos[0]); + if (bbsnet_connect(bbsnet_menu.menu_item_pos[0]) < 0) + { + log_debug("bbsnet_connect() error\n"); + } // Force cleanup anything remaining in the output buffer clearscr(); iflush(); @@ -1234,14 +1486,14 @@ int bbs_net() bbsnet_selchange(); break; case KEY_UP: - for (i = 0; i < STATION_PER_LINE; i++) + for (int i = 0; i < STATION_PER_LINE; i++) { menu_control(&bbsnet_menu, KEY_UP); } bbsnet_selchange(); break; case KEY_DOWN: - for (i = 0; i < STATION_PER_LINE; i++) + for (int i = 0; i < STATION_PER_LINE; i++) { menu_control(&bbsnet_menu, KEY_DOWN); } diff --git a/src/bwf.c b/src/bwf.c index 0dabd17f..ddcada1e 100644 --- a/src/bwf.c +++ b/src/bwf.c @@ -91,9 +91,7 @@ int bwf_load(const char *filename) fclose(fp); -#ifdef _DEBUG - log_error("Debug: bwf_pattern_str: %s\n", bwf_pattern_str); -#endif + log_debug("Debug: bwf_pattern_str: %s\n", bwf_pattern_str); return 0; } @@ -172,10 +170,8 @@ int check_badwords(char *str, char c_mask) } else { -#ifdef _DEBUG - log_error("Debug: match pattern #%d of %d at offsets [%d, %d]\n", + log_debug("Debug: match pattern #%d of %d at offsets [%d, %d]\n", i, match_count, ovector[i * 2], ovector[i * 2 + 1] - ovector[i * 2]); -#endif memset(str + ovector[i * 2], c_mask, ovector[i * 2 + 1] - ovector[i * 2]); total_match_count++; startoffset = ovector[i * 2 + 1]; diff --git a/src/editor.c b/src/editor.c index 2ec426c1..56ad07cd 100644 --- a/src/editor.c +++ b/src/editor.c @@ -272,10 +272,8 @@ int editor_data_insert(EDITOR_DATA *p_editor_data, long *p_display_line, long *p { if (p_editor_data->display_line_total >= MAX_EDITOR_DATA_LINES) { -#ifdef _DEBUG - log_error("Split line error, display_line_total(%ld) reach limit(%d)\n", + log_debug("Split line error, display_line_total(%ld) reach limit(%d)\n", p_editor_data->display_line_total, MAX_EDITOR_DATA_LINES); -#endif return -2; } @@ -369,9 +367,7 @@ int editor_data_insert(EDITOR_DATA *p_editor_data, long *p_display_line, long *p // Insert blank display line after last_display_line if (p_editor_data->display_line_total >= MAX_EDITOR_DATA_LINES) { -#ifdef _DEBUG - log_error("display_line_total over limit %d >= %d\n", p_editor_data->display_line_total, MAX_EDITOR_DATA_LINES); -#endif + log_debug("display_line_total over limit %d >= %d\n", p_editor_data->display_line_total, MAX_EDITOR_DATA_LINES); // Terminate prior display line with \n, to avoid error on cleanup if (display_line + i - 1 >= 0 && p_editor_data->display_line_lengths[display_line + i - 1] > 0) @@ -763,9 +759,7 @@ int editor_display(EDITOR_DATA *p_editor_data) ch = igetch(100); // 0.1 second if (ch == KEY_NULL || ch == KEY_TIMEOUT) // Ignore received bytes if no futher input { -#ifdef _DEBUG - log_error("Ignore %d bytes of incomplete UTF8 character\n", str_len); -#endif + log_debug("Ignore %d bytes of incomplete UTF8 character\n", str_len); str_len = 0; break; } @@ -974,7 +968,7 @@ int editor_display(EDITOR_DATA *p_editor_data) switch (ch) { case KEY_NULL: - log_error("KEY_NULL\n"); + log_debug("KEY_NULL\n"); goto cleanup; case KEY_TIMEOUT: log_error("User input timeout\n"); diff --git a/src/hash_dict.c b/src/hash_dict.c index f26e51bc..2338c978 100644 --- a/src/hash_dict.c +++ b/src/hash_dict.c @@ -147,7 +147,7 @@ int hash_dict_set(HASH_DICT *p_dict, uint64_t key, int64_t value) if (p_item->key == key) { p_item->value = value; - return 0; + return 1; } p_item = p_item->p_next; } @@ -190,25 +190,11 @@ int hash_dict_inc(HASH_DICT *p_dict, uint64_t key, int64_t value_inc) if (p_item->key == key) { p_item->value += value_inc; - return 0; + return 1; } p_item = p_item->p_next; } - p_item = (HASH_ITEM *)memory_pool_alloc(p_dict->p_item_pool); - if (p_item == NULL) - { - log_error("memory_pool_alloc(HASH_ITEM) error\n"); - return -1; - } - - p_item->key = key; - p_item->value = value_inc; - p_item->p_next = p_dict->buckets[bucket_index][item_index_in_bucket]; - p_dict->buckets[bucket_index][item_index_in_bucket] = p_item; - - (p_dict->item_count)++; - return 0; } diff --git a/src/io.c b/src/io.c index 01351b98..89cdeeae 100644 --- a/src/io.c +++ b/src/io.c @@ -64,8 +64,8 @@ static int stdout_conv_len = 0; static int stdin_conv_offset = 0; static int stdout_conv_offset = 0; -static iconv_t stdin_cd = NULL; -static iconv_t stdout_cd = NULL; +static iconv_t stdin_cd = (iconv_t)(-1); +static iconv_t stdout_cd = (iconv_t)(-1); int io_init(void) { @@ -246,15 +246,11 @@ int iflush(void) #endif int nfds; - int retry; int ret = 0; // Retry wait / flush for at most 3 times - retry = 3; - while (retry > 0 && !SYS_server_exit) + for (int retry = 3; retry > 0 && !SYS_server_exit; retry--) { - retry--; - #ifdef HAVE_SYS_EPOLL_H nfds = epoll_wait(stdout_epollfd, events, MAX_EVENTS, 100); // 0.1 second ret = nfds; @@ -286,7 +282,22 @@ int iflush(void) for (int i = 0; i < nfds; i++) { #ifdef HAVE_SYS_EPOLL_H - if (events[i].data.fd == STDOUT_FILENO) + if (events[i].data.fd == STDOUT_FILENO && (events[i].events & (EPOLLHUP | EPOLLERR))) +#else + if (pfds[i].fd == STDOUT_FILENO && (pfds[i].revents & (POLLHUP | POLLERR))) +#endif + { +#ifdef HAVE_SYS_EPOLL_H + log_debug("STDOUT error events (%d)\n", events[i].events); +#else + log_debug("STDOUT error events (%d)\n", pfds[i].revents); +#endif + retry = 0; + break; + } + +#ifdef HAVE_SYS_EPOLL_H + if (events[i].data.fd == STDOUT_FILENO && (events[i].events & EPOLLOUT)) #else if (pfds[i].fd == STDOUT_FILENO && (pfds[i].revents & POLLOUT)) #endif @@ -308,7 +319,7 @@ int iflush(void) ret = ssh_channel_write(SSH_channel, stdout_conv + stdout_conv_offset, (uint32_t)(stdout_conv_len - stdout_conv_offset)); if (ret == SSH_ERROR) { - log_error("ssh_channel_write() error: %s\n", ssh_get_error(SSH_session)); + log_debug("ssh_channel_write() error: %s\n", ssh_get_error(SSH_session)); retry = 0; break; } @@ -329,9 +340,7 @@ int iflush(void) } else { -#ifdef _DEBUG - log_error("write(STDOUT) error (%d)\n", errno); -#endif + log_debug("write(STDOUT) error (%d)\n", errno); retry = 0; break; } @@ -392,7 +401,7 @@ int igetch(int timeout) { if (SSH_v2 && ssh_channel_is_closed(SSH_channel)) { - log_error("SSH channel is closed\n"); + log_debug("SSH channel is closed\n"); loop = 0; break; } @@ -431,7 +440,22 @@ int igetch(int timeout) for (int i = 0; i < nfds; i++) { #ifdef HAVE_SYS_EPOLL_H - if (events[i].data.fd == STDIN_FILENO) + if (events[i].data.fd == STDIN_FILENO && (events[i].events & (EPOLLHUP | EPOLLERR))) +#else + if (pfds[i].fd == STDIN_FILENO && (pfds[i].revents & (POLLHUP | POLLERR))) +#endif + { +#ifdef HAVE_SYS_EPOLL_H + log_debug("STDIN error events (%d)\n", events[i].events); +#else + log_debug("STDIN error events (%d)\n", pfds[i].revents); +#endif + loop = 0; + break; + } + +#ifdef HAVE_SYS_EPOLL_H + if (events[i].data.fd == STDIN_FILENO && (events[i].events & EPOLLIN)) #else if (pfds[i].fd == STDIN_FILENO && (pfds[i].revents & POLLIN)) #endif @@ -450,7 +474,7 @@ int igetch(int timeout) ret = ssh_channel_read_nonblocking(SSH_channel, stdin_buf + stdin_buf_len, sizeof(stdin_buf) - (uint32_t)stdin_buf_len, 0); if (ret == SSH_ERROR) { - log_error("ssh_channel_read_nonblocking() error: %s\n", ssh_get_error(SSH_session)); + log_debug("ssh_channel_read_nonblocking() error: %s\n", ssh_get_error(SSH_session)); loop = 0; break; } @@ -487,9 +511,7 @@ int igetch(int timeout) } else { -#ifdef _DEBUG - log_error("read(STDIN) error (%d)\n", errno); -#endif + log_debug("read(STDIN) error (%d)\n", errno); loop = 0; break; } @@ -512,7 +534,7 @@ int igetch(int timeout) #ifdef _DEBUG for (int j = stdin_buf_offset; j < stdin_buf_len; j++) { - log_error("Debug input: <--[%u]\n", (stdin_buf[j] + 256) % 256); + log_debug("input: <--[%u]\n", (stdin_buf[j] + 256) % 256); } #endif } @@ -530,7 +552,7 @@ int igetch(int timeout) #ifdef _DEBUG for (int j = stdin_conv_offset; j < stdin_conv_len; j++) { - log_error("Debug input_conv: <--[%u]\n", (stdin_conv[j] + 256) % 256); + log_debug("input_conv: <--[%u]\n", (stdin_conv[j] + 256) % 256); } #endif } @@ -996,7 +1018,7 @@ int igetch(int timeout) #ifdef _DEBUG if (out != KEY_TIMEOUT && out != KEY_NULL) { - log_error("Debug: -->[0x %x]\n", out); + log_debug("output: -->[0x %x]\n", out); } #endif @@ -1090,9 +1112,7 @@ int io_buf_conv(iconv_t cd, char *p_buf, int *p_buf_len, int *p_buf_offset, char { if (errno == EINVAL) // Incomplete { -#ifdef _DEBUG - log_error("iconv(inbytes=%d, outbytes=%d) error: EINVAL, in_buf[0]=%d\n", in_bytes, out_bytes, in_buf[0]); -#endif + log_debug("iconv(inbytes=%d, outbytes=%d) error: EINVAL, in_buf[0]=%d\n", in_bytes, out_bytes, in_buf[0]); if (p_buf != in_buf) { *p_buf_len -= (int)(in_buf - p_buf); @@ -1120,23 +1140,17 @@ int io_buf_conv(iconv_t cd, char *p_buf, int *p_buf_len, int *p_buf_offset, char if (in_bytes == 0) { in_bytes = (size_t)(*p_buf_len - *p_buf_offset); -#ifdef _DEBUG - log_error("Reset in_bytes from 0 to %d\n", in_bytes); -#endif + log_debug("Reset in_bytes from 0 to %d\n", in_bytes); } -#ifdef _DEBUG - log_error("iconv(in_bytes=%d, out_bytes=%d) error: EILSEQ, in_buf[0]=%d\n", + log_debug("iconv(in_bytes=%d, out_bytes=%d) error: EILSEQ, in_buf[0]=%d\n", in_bytes, out_bytes, in_buf[0]); -#endif skip_current = 1; } else // something strange { -#ifdef _DEBUG - log_error("iconv(in_bytes=%d, out_bytes=%d) error: %d, in_buf[0]=%d\n", + log_debug("iconv(in_bytes=%d, out_bytes=%d) error: %d, in_buf[0]=%d\n", in_bytes, out_bytes, errno, in_buf[0]); -#endif *p_buf_offset = (int)(in_buf - p_buf); *p_conv_len = (int)(conv_size - out_bytes); skip_current = 1; @@ -1189,6 +1203,7 @@ int io_conv_init(const char *charset) { log_error("iconv_open(%s->%s) error: %d\n", BBS_default_charset, tocode, errno); iconv_close(stdin_cd); + stdin_cd = (iconv_t)(-1); return -2; } @@ -1197,15 +1212,15 @@ int io_conv_init(const char *charset) int io_conv_cleanup(void) { - if (stdin_cd != NULL) + if (stdin_cd != (iconv_t)(-1)) { iconv_close(stdin_cd); - stdin_cd = NULL; + stdin_cd = (iconv_t)(-1); } - if (stdout_cd != NULL) + if (stdout_cd != (iconv_t)(-1)) { iconv_close(stdout_cd); - stdout_cd = NULL; + stdout_cd = (iconv_t)(-1); } return 0; diff --git a/src/lml.c b/src/lml.c index 33f64631..5db6a1df 100644 --- a/src/lml.c +++ b/src/lml.c @@ -217,12 +217,12 @@ int lml_render(const char *str_in, char *str_out, int buf_len, int width, int qu char tab_spaces[TAB_SIZE + 1]; int tab_width = 0; + clock_begin = clock(); + #ifdef _DEBUG size_t str_in_len = strlen(str_in); #endif - clock_begin = clock(); - lml_init(); lml_tag_disabled = 0; diff --git a/src/log.c b/src/log.c index 3adaa2c8..5c20cd23 100644 --- a/src/log.c +++ b/src/log.c @@ -79,10 +79,14 @@ inline static void log_head(char *buf, size_t len, int log_level, const char *ap { snprintf(buf, len, "[%s] [%d] [INFO] ", s_time, getpid()); } - else // if (log_level == LOG_LEVEL_ERROR) + else if (log_level == LOG_LEVEL_ERROR) { snprintf(buf, len, "[%s] [%d] [ERROR] [%s:%d] ", s_time, getpid(), app_file, app_line); } + else // if (log_level == LOG_LEVEL_DEBUG) + { + snprintf(buf, len, "[%s] [%d] [DEBUG] [%s:%d] ", s_time, getpid(), app_file, app_line); + } } int log_printf(enum log_level_t log_level, const char *app_file, int app_line, const char *format, ...) @@ -92,7 +96,7 @@ int log_printf(enum log_level_t log_level, const char *app_file, int app_line, c char buf[LINE_BUFFER_LEN]; FILE *fp_log; - fp_log = (log_level == LOG_LEVEL_ERROR ? fp_error_log : fp_common_log); + fp_log = (log_level == LOG_LEVEL_COMMON ? fp_common_log : fp_error_log); log_head(buf, sizeof(buf), log_level, app_file, app_line); strncat(buf, format, sizeof(buf) - strnlen(buf, sizeof(buf))); diff --git a/src/main.c b/src/main.c index 36e1be18..f13a2c19 100644 --- a/src/main.c +++ b/src/main.c @@ -393,6 +393,12 @@ int main(int argc, char *argv[]) goto cleanup; } act.sa_handler = SIG_IGN; + if (sigaction(SIGPIPE, &act, NULL) == -1) + { + log_error("set signal action of SIGPIPE error: %d\n", errno); + goto cleanup; + } + act.sa_handler = SIG_IGN; if (sigaction(SIGUSR1, &act, NULL) == -1) { log_error("set signal action of SIGUSR1 error: %d\n", errno); diff --git a/src/menu.c b/src/menu.c index b8c3941d..17df7865 100644 --- a/src/menu.c +++ b/src/menu.c @@ -1141,9 +1141,7 @@ int menu_control(MENU_SET *p_menu_set, int key) if (p_menu->item_count == 0) { -#ifdef _DEBUG - log_error("Empty menu (%s)\n", p_menu->name); -#endif + log_debug("Empty menu (%s)\n", p_menu->name); if (p_menu_set->choose_step > 0) { p_menu_set->choose_step--; diff --git a/src/menu_proc.c b/src/menu_proc.c index baf39d8f..fd568de8 100644 --- a/src/menu_proc.c +++ b/src/menu_proc.c @@ -314,7 +314,7 @@ int show_top10_menu(void *param) switch (ch) { case KEY_NULL: // broken pipe - log_error("KEY_NULL\n"); + log_debug("KEY_NULL\n"); loop = 0; break; case KEY_TIMEOUT: diff --git a/src/net_server.c b/src/net_server.c index 2c726b1b..269a1e36 100644 --- a/src/net_server.c +++ b/src/net_server.c @@ -391,9 +391,7 @@ static int fork_server(void) ret = ssh_event_dopoll(event, 100); // 0.1 second if (ret == SSH_ERROR) { -#ifdef _DEBUG - log_error("ssh_event_dopoll() error: %s\n", ssh_get_error(SSH_session)); -#endif + log_debug("ssh_event_dopoll() error: %s\n", ssh_get_error(SSH_session)); goto cleanup; } } @@ -530,7 +528,6 @@ int net_server(const char *hostaddr, in_port_t port[]) int nfds; int notify_child_exit = 0; time_t tm_notify_child_exit = time(NULL); - int i, j; pid_t pid; int ssh_key_valid = 0; int ssh_log_level = SSH_LOG_NOLOG; @@ -577,7 +574,7 @@ int net_server(const char *hostaddr, in_port_t port[]) if (ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDADDR, hostaddr) < 0 || ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDPORT, &port) < 0 || - ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, "+ssh-rsa") < 0 || + ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, "+ssh-ed25519,ecdsa-sha2-nistp256,ssh-rsa") < 0 || ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_LOG_VERBOSITY, &ssh_log_level) < 0) { log_error("Error setting SSH bind options: %s\n", ssh_get_error(sshbind)); @@ -595,7 +592,7 @@ int net_server(const char *hostaddr, in_port_t port[]) #endif // Server socket - for (i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { socket_server[i] = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); @@ -713,24 +710,24 @@ int net_server(const char *hostaddr, in_port_t port[]) if (pid != section_list_loader_pid) { - j = 0; - ret = hash_dict_get(hash_dict_pid_sockaddr, (uint64_t)pid, (int64_t *)&j); + int64_t j = 0; + ret = hash_dict_get(hash_dict_pid_sockaddr, (uint64_t)pid, &j); if (ret < 0) { log_error("hash_dict_get(hash_dict_pid_sockaddr, %d) error\n", pid); } else { - ret = hash_dict_inc(hash_dict_sockaddr_count, (uint64_t)j, -1); - if (ret < 0) + ret = hash_dict_inc(hash_dict_sockaddr_count, (in_addr_t)j, -1); + if (ret <= 0) { - log_error("hash_dict_inc(hash_dict_sockaddr_count, %d, -1) error\n", j); + log_error("hash_dict_inc(hash_dict_sockaddr_count, %lu, -1) error: %d\n", (in_addr_t)j, ret); } ret = hash_dict_del(hash_dict_pid_sockaddr, (uint64_t)pid); if (ret < 0) { - log_error("hash_dict_del(hash_dict_pid_sockaddr, %d) error\n", pid); + log_error("hash_dict_del(hash_dict_pid_sockaddr, %lu) error\n", (uint64_t)pid); } } } @@ -937,12 +934,10 @@ int net_server(const char *hostaddr, in_port_t port[]) port_client = ntohs(sin.sin_port); - log_common("Accept %s connection from %s:%d\n", (SSH_v2 ? "SSH" : "telnet"), hostaddr_client, port_client); - if (SYS_child_process_count - 1 < BBS_max_client) { - j = 0; - ret = hash_dict_get(hash_dict_sockaddr_count, (uint64_t)sin.sin_addr.s_addr, (int64_t *)&j); + int64_t j = 0; + ret = hash_dict_get(hash_dict_sockaddr_count, sin.sin_addr.s_addr, &j); if (ret < 0) { log_error("hash_dict_get(hash_dict_sockaddr_count, %s) error\n", hostaddr_client); @@ -959,24 +954,45 @@ int net_server(const char *hostaddr, in_port_t port[]) ret = hash_dict_set(hash_dict_pid_sockaddr, (uint64_t)pid, sin.sin_addr.s_addr); if (ret < 0) { - log_error("hash_dict_set(hash_dict_pid_sockaddr, %d, %s) error\n", pid, hostaddr_client); + log_error("hash_dict_set(hash_dict_pid_sockaddr, %lu, %s) error\n", (uint64_t)pid, hostaddr_client); } - ret = hash_dict_inc(hash_dict_sockaddr_count, (uint64_t)sin.sin_addr.s_addr, 1); - if (ret < 0) + if (j == 0) + { + // First connection from this IP + log_common("Accept %s connection from %s:%d\n", + (SSH_v2 ? "SSH" : "telnet"), hostaddr_client, port_client); + + ret = hash_dict_set(hash_dict_sockaddr_count, (uint64_t)sin.sin_addr.s_addr, 1); + if (ret < 0) + { + log_error("hash_dict_set(hash_dict_sockaddr_count, %s, 1) error\n", hostaddr_client); + } + } + else { - log_error("hash_dict_inc(hash_dict_sockaddr_count, %s, %d) error\n", hostaddr_client, 1); + // Increase connection count from this IP + log_common("Accept %s connection from %s:%d, already have %d connections\n", + (SSH_v2 ? "SSH" : "telnet"), hostaddr_client, port_client, j); + + ret = hash_dict_inc(hash_dict_sockaddr_count, (uint64_t)sin.sin_addr.s_addr, 1); + if (ret <= 0) + { + log_error("hash_dict_inc(hash_dict_sockaddr_count, %s, 1) error: %d\n", hostaddr_client, ret); + } } } } else { - log_error("Rejected client connection from %s over limit per IP (%d)\n", hostaddr_client, BBS_max_client_per_ip); + log_error("Rejected %s connection from %s:%d over limit per IP (%d >= %d)\n", + (SSH_v2 ? "SSH" : "telnet"), hostaddr_client, port_client, j, BBS_max_client_per_ip); } } else { - log_error("Rejected client connection over limit (%d)\n", SYS_child_process_count - 1); + log_error("Rejected %s connection from %s:%d over limit (%d >= %d)\n", + (SSH_v2 ? "SSH" : "telnet"), hostaddr_client, port_client, SYS_child_process_count - 1, BBS_max_client); } if (close(socket_client) == -1) @@ -995,7 +1011,7 @@ int net_server(const char *hostaddr, in_port_t port[]) } #endif - for (i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { if (close(socket_server[i]) == -1) { diff --git a/src/screen.c b/src/screen.c index 7d5774be..1bb7ce12 100644 --- a/src/screen.c +++ b/src/screen.c @@ -209,9 +209,7 @@ static int _str_input(char *buffer, int buf_size, int max_display_len, enum io_e ch = igetch(100); // 0.1 second if (ch == KEY_NULL || ch == KEY_TIMEOUT) // Ignore received bytes if no futher input { -#ifdef _DEBUG - log_error("Ignore %d bytes of incomplete UTF8 character\n", str_len); -#endif + log_debug("Ignore %d bytes of incomplete UTF8 character\n", str_len); str_len = 0; break; } @@ -533,9 +531,7 @@ int get_data(int row, int col, char *prompt, char *buffer, int buf_size, int max ch = igetch(100); // 0.1 second if (ch == KEY_NULL || ch == KEY_TIMEOUT) // Ignore received bytes if no futher input { -#ifdef _DEBUG - log_error("Ignore %d bytes of incomplete UTF8 character\n", str_len); -#endif + log_debug("Ignore %d bytes of incomplete UTF8 character\n", str_len); str_len = 0; break; } @@ -720,7 +716,7 @@ int display_data(const void *p_data, long display_line_total, const long *p_line switch (ch) { case KEY_NULL: - log_error("KEY_NULL\n"); + log_debug("KEY_NULL\n"); goto cleanup; case KEY_TIMEOUT: log_error("User input timeout\n"); diff --git a/src/section_list_display.c b/src/section_list_display.c index 5ca6ec3a..39f8d0cb 100644 --- a/src/section_list_display.c +++ b/src/section_list_display.c @@ -71,7 +71,7 @@ enum select_cmd_t SEARCH_USER, }; -static int section_list_draw_items(int page_id, ARTICLE *p_articles[], int article_count, int display_nickname, int ontop_start_offset) +static int section_list_draw_items(int page_id, const ARTICLE *p_articles[], int article_count, int display_nickname, int ontop_start_offset) { char str_time[LINE_BUFFER_LEN]; struct tm tm_sub; @@ -281,7 +281,7 @@ static enum select_cmd_t section_list_select(int total_page, int item_count, int switch (ch) { case KEY_NULL: // broken pipe - log_error("KEY_NULL\n"); + log_debug("KEY_NULL\n"); return EXIT_SECTION; case KEY_TIMEOUT: if (time(NULL) - BBS_last_access_tm >= BBS_max_user_idle_time) @@ -590,7 +590,7 @@ int section_list_display(const char *sname, int32_t aid) char stitle[BBS_section_title_max_len + 1]; char master_list[(BBS_username_max_len + 1) * 3 + 1]; char page_info_str[LINE_BUFFER_LEN]; - ARTICLE *p_articles[BBS_article_limit_per_page]; + const ARTICLE *p_articles[BBS_article_limit_per_page]; int article_count; int page_count; int ontop_start_offset; @@ -1415,7 +1415,7 @@ int section_list_ex_dir_display(SECTION_LIST *p_section) switch (ch) { case KEY_NULL: // broken pipe - log_error("KEY_NULL\n"); + log_debug("KEY_NULL\n"); loop = 0; break; case KEY_TIMEOUT: diff --git a/src/section_list_loader.c b/src/section_list_loader.c index a2d03c2a..924aa22c 100644 --- a/src/section_list_loader.c +++ b/src/section_list_loader.c @@ -173,9 +173,7 @@ int load_section_config_from_db(int update_gen_ex) { p_section->ex_menu_set.allow_exit = 1; // Allow exit menu p_section->ex_menu_tm = atol(row[7]); -#ifdef _DEBUG - log_common("Loaded gen_ex_menu of section %d [%s]\n", p_section->sid, p_section->sname); -#endif + log_debug("Loaded gen_ex_menu of section %d [%s]\n", p_section->sid, p_section->sname); } } @@ -866,7 +864,7 @@ int section_list_loader_launch(void) return 0; } -int query_section_articles(SECTION_LIST *p_section, int page_id, ARTICLE *p_articles[], +int query_section_articles(SECTION_LIST *p_section, int page_id, const ARTICLE *p_articles[], int *p_article_count, int *p_page_count, int *p_ontop_start_offset) { ARTICLE *p_article; @@ -897,9 +895,7 @@ int query_section_articles(SECTION_LIST *p_section, int page_id, ARTICLE *p_arti } else if (page_id < 0 || page_id >= *p_page_count) { -#ifdef _DEBUG - log_error("Invalid page_id=%d, not in range [0, %d)\n", page_id, *p_page_count); -#endif + log_debug("Invalid page_id=%d, not in range [0, %d)\n", page_id, *p_page_count); ret = -3; } else diff --git a/src/str_process.c b/src/str_process.c index 8276ea07..d0b88db2 100644 --- a/src/str_process.c +++ b/src/str_process.c @@ -76,9 +76,7 @@ int str_length(const char *str, int skip_ctrl_seq) if (mbstowcs(wcs, input_str, 1) == (size_t)-1) { -#ifdef _DEBUG - log_error("mbstowcs(%s) error\n", input_str); -#endif + log_debug("mbstowcs(%s) error\n", input_str); wc_len = (UTF8_fixed_width ? 2 : 1); // Fallback } else @@ -142,9 +140,7 @@ int split_line(const char *buffer, int max_display_len, int *p_eol, int *p_displ if (mbstowcs(wcs, input_str, 1) == (size_t)-1) { -#ifdef _DEBUG - log_error("mbstowcs(%s) error\n", input_str); -#endif + log_debug("mbstowcs(%s) error\n", input_str); wc_len = (UTF8_fixed_width ? 2 : 1); // Fallback } else @@ -203,9 +199,7 @@ long split_data_lines(const char *p_buf, int max_display_len, long *p_line_offse // Exceed max_line_cnt if (line_cnt + 1 >= line_offsets_count) { -#ifdef _DEBUG - log_error("Line count %d reaches limit %d\n", line_cnt + 1, line_offsets_count); -#endif + log_debug("Line count %d reaches limit %d\n", line_cnt + 1, line_offsets_count); return line_cnt; } diff --git a/src/test_hash_dict.c b/src/test_hash_dict.c index 9e5b54b5..f58a54e0 100644 --- a/src/test_hash_dict.c +++ b/src/test_hash_dict.c @@ -55,15 +55,7 @@ int main(int argc, char *argv[]) for (i = 0; i < dict_item_count; i++) { key = i * 37 + 13; - if (i % 2 == 0) - { - if (hash_dict_set(p_dict, key, i * 3 + 7) != 0) - { - printf("hash_dict_set(%lu) error\n", key); - break; - } - } - else + if (i % 2 == 1) { if (hash_dict_inc(p_dict, key, i * 3 + 7) != 0) { @@ -71,6 +63,12 @@ int main(int argc, char *argv[]) break; } } + + if (hash_dict_set(p_dict, key, i * 3 + 7) != 0) + { + printf("hash_dict_set(%lu) error\n", key); + break; + } } ret = (int)hash_dict_item_count(p_dict); @@ -98,9 +96,9 @@ int main(int argc, char *argv[]) for (i = 0; i < dict_item_count; i++) { key = i * 37 + 13; - if (hash_dict_inc(p_dict, key, i * 5 + 17) != 0) + if (hash_dict_inc(p_dict, key, i * 5 + 17) != 1) { - printf("hash_dict_set(%lu) error\n", key); + printf("hash_dict_inc(%lu) error\n", key); break; } } diff --git a/src/test_ssh_server.c b/src/test_ssh_server.c index 7f9d8523..c4e75347 100644 --- a/src/test_ssh_server.c +++ b/src/test_ssh_server.c @@ -160,7 +160,7 @@ int ssh_server(const char *hostaddr, unsigned int port) if (ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDADDR, hostaddr) < 0 || ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDPORT, &port) < 0 || - ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, "+ssh-rsa") < 0 || + ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, "+ssh-ed25519,ecdsa-sha2-nistp256,ssh-rsa") < 0 || ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_LOG_VERBOSITY, &ssh_log_level) < 0) { log_error("Error setting SSH bind options: %s\n", ssh_get_error(sshbind)); diff --git a/src/user_list.c b/src/user_list.c index 0cd866e9..34a6d8ca 100644 --- a/src/user_list.c +++ b/src/user_list.c @@ -240,16 +240,12 @@ int user_list_load(MYSQL *db, USER_LIST *p_list) qsort(p_list->index_uid, (size_t)i, sizeof(USER_INFO_INDEX_UID), user_info_index_uid_comp); -#ifdef _DEBUG - log_error("Rebuild index of %d users, last_uid=%d\n", i, p_list->users[i - 1].uid); -#endif + log_debug("Rebuild index of %d users, last_uid=%d\n", i, p_list->users[i - 1].uid); } p_list->user_count = i; -#ifdef _DEBUG - log_error("Loaded %d users\n", p_list->user_count); -#endif + log_debug("Loaded %d users\n", p_list->user_count); cleanup: mysql_free_result(rs); @@ -1361,9 +1357,7 @@ int query_user_info_by_username(const char *username_prefix, int max_user_cnt, if (strncasecmp(username_prefix, p_user_list_pool->user_list[p_user_list_pool->user_list_index_current].users[left].username, prefix_len) == 0) // Found { -#ifdef _DEBUG - log_error("Debug: match found, pos=%d\n", left); -#endif + log_debug("Debug: match found, pos=%d\n", left); left_save = left; right = left; @@ -1389,9 +1383,7 @@ int query_user_info_by_username(const char *username_prefix, int max_user_cnt, } } -#ifdef _DEBUG - log_error("Debug: first match found, pos=%d\n", right); -#endif + log_debug("Debug: first match found, pos=%d\n", right); left = left_save; left_save = right; @@ -1417,9 +1409,7 @@ int query_user_info_by_username(const char *username_prefix, int max_user_cnt, } } -#ifdef _DEBUG - log_error("Debug: last match found, pos=%d\n", left); -#endif + log_debug("Debug: last match found, pos=%d\n", left); right = left; left = left_save; diff --git a/src/user_list_display.c b/src/user_list_display.c index 2bb15d59..3ede9a59 100644 --- a/src/user_list_display.c +++ b/src/user_list_display.c @@ -229,7 +229,7 @@ static enum select_cmd_t user_list_select(int total_page, int item_count, int *p switch (ch) { case KEY_NULL: // broken pipe - log_error("KEY_NULL\n"); + log_debug("KEY_NULL\n"); case KEY_ESC: case KEY_LEFT: return EXIT_LIST; // exit list diff --git a/src/user_stat.c b/src/user_stat.c index 33fe9c26..230f742d 100644 --- a/src/user_stat.c +++ b/src/user_stat.c @@ -78,10 +78,8 @@ int user_stat_map_update(USER_STAT_MAP *p_map) if (p_article->uid > p_map->last_uid) { -#ifdef _DEBUG - log_error("uid=%d of article(aid=%d) is greater than last_uid=%d\n", + log_debug("uid=%d of article(aid=%d) is greater than last_uid=%d\n", p_article->uid, p_article->aid, p_map->last_uid); -#endif continue; }