/[LeafOK_CVS]/lbbs/src/bbs_net.c
ViewVC logotype

Diff of /lbbs/src/bbs_net.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

Revision 1.9 by sysadm, Tue Mar 22 12:12:33 2005 UTC Revision 1.109 by sysadm, Mon Dec 22 06:54:10 2025 UTC
# Line 1  Line 1 
1  /***************************************************************************  /* SPDX-License-Identifier: GPL-3.0-or-later */
2                            bbs_net.c  -  description  /*
3                               -------------------   * bbs_net
4      begin                : Mon Oct 18 2004   *   - user interactive feature of site shuttle
5      copyright            : (C) 2004 by Leaflet   *
6      email                : leaflet@leafok.com   * Copyright (C) 2004-2025  Leaflet <leaflet@leafok.com>
7   ***************************************************************************/   */
8    
9  /***************************************************************************  #ifdef HAVE_CONFIG_H
10   *                                                                         *  #include "config.h"
11   *   This program is free software; you can redistribute it and/or modify  *  #endif
  *   it under the terms of the GNU General Public License as published by  *  
  *   the Free Software Foundation; either version 2 of the License, or     *  
  *   (at your option) any later version.                                   *  
  *                                                                         *  
  ***************************************************************************/  
12    
13  #include "bbs.h"  #include "bbs.h"
14    #include "bbs_net.h"
15  #include "common.h"  #include "common.h"
16  #include "io.h"  #include "io.h"
17    #include "log.h"
18    #include "login.h"
19  #include "menu.h"  #include "menu.h"
20  #include "tcplib.h"  #include "screen.h"
21  #include <stdio.h>  #include "str_process.h"
22    #include <errno.h>
23    #include <fcntl.h>
24    #include <netdb.h>
25  #include <stdarg.h>  #include <stdarg.h>
26  #include <sys/ioctl.h>  #include <stdio.h>
27  #include <sys/socket.h>  #include <stdlib.h>
28  #include <netinet/in.h>  #include <string.h>
 #include <arpa/inet.h>  
29  #include <time.h>  #include <time.h>
30  #include <unistd.h>  #include <unistd.h>
31  #include <netdb.h>  #include <arpa/inet.h>
32    #include <ctype.h>
33    #include <libssh/libssh.h>
34    #include <libssh/server.h>
35    #include <libssh/callbacks.h>
36    #include <netinet/in.h>
37    #include <netinet/ip.h>
38    #include <sys/select.h>
39    #include <sys/ioctl.h>
40    #include <sys/socket.h>
41    
42  #define TIME_OUT                15  #ifdef HAVE_SYS_EPOLL_H
43  #define MAX_PROCESS_BAR_LEN     30  #include <sys/epoll.h>
44  #define MAXSTATION              26*2  #else
45  #define STATION_PER_LINE        4  #include <poll.h>
46    #endif
47    
48    enum _bbs_net_constant_t
49    {
50            MAXSTATION = 26 * 2,
51            STATION_PER_LINE = 4,
52            ORG_NAME_MAX_LEN = 40,
53            SITE_NAME_MAX_LEN = 40,
54            HOSTNAME_MAX_LEN = 253,
55            PORT_STR_MAX_LEN = 5,
56            USERNAME_MAX_LEN = 20,
57            PASSWORD_MAX_LEN = 20,
58            REMOTE_CONNECT_TIMEOUT = 10, // seconds
59            SSH_CONNECT_TIMEOUT = 5,         // seconds
60            PROGRESS_BAR_LEN = 30,
61    };
62    
63  struct _bbsnet_conf  struct _bbsnet_conf
64  {  {
65    char host1[20];          char org_name[ORG_NAME_MAX_LEN + 1];
66    char host2[40];          char site_name[SITE_NAME_MAX_LEN + 1];
67    char ip[40];          char host_name[HOSTNAME_MAX_LEN + 1];
68    int port;          char port[PORT_STR_MAX_LEN + 1];
69            int8_t use_ssh;
70            char charset[CHARSET_MAX_LEN + 1];
71  } bbsnet_conf[MAXSTATION];  } bbsnet_conf[MAXSTATION];
72    
73  MENU_SET bbsnet_menu;  static const char MENU_CONF_DELIM[] = " \t\r\n";
74    
75    static MENU_SET bbsnet_menu;
76    
77    static void unload_bbsnet_conf(void);
78    
79    static int load_bbsnet_conf(const char *file_config)
80    {
81            FILE *fin;
82            int fin_line = 0;
83            MENU *p_menu;
84            MENU_ITEM *p_menu_item;
85            MENU_ITEM_ID menu_item_id;
86            char line[LINE_BUFFER_LEN];
87            char *p = NULL;
88            char *saveptr = NULL;
89            long port;
90            char *endptr;
91    
92            unload_bbsnet_conf();
93    
94            bbsnet_menu.p_menu_pool = calloc(1, sizeof(MENU));
95            if (bbsnet_menu.p_menu_pool == NULL)
96            {
97                    log_error("calloc(p_menu_pool) error");
98                    return -1;
99            }
100            bbsnet_menu.menu_count = 1;
101    
102            bbsnet_menu.p_menu_item_pool = calloc(MAXSTATION, sizeof(MENU_ITEM));
103            if (bbsnet_menu.p_menu_item_pool == NULL)
104            {
105                    log_error("calloc(p_menu_item_pool) error");
106                    unload_bbsnet_conf();
107                    return -1;
108            }
109            bbsnet_menu.menu_item_count = MAXSTATION;
110    
111            p_menu = (MENU *)get_menu_by_id(&bbsnet_menu, 0);
112    
113            strncpy(p_menu->name, "BBSNET", sizeof(p_menu->name) - 1);
114            p_menu->name[sizeof(p_menu->name) - 1] = '\0';
115            p_menu->title.show = 0;
116            p_menu->screen_show = 0;
117    
118            fin = fopen(file_config, "r");
119            if (fin == NULL)
120            {
121                    unload_bbsnet_conf();
122                    return -2;
123            }
124    
125            menu_item_id = 0;
126            while (fgets(line, sizeof(line), fin) && menu_item_id < MAXSTATION)
127            {
128                    fin_line++;
129    
130                    p = strtok_r(line, MENU_CONF_DELIM, &saveptr);
131                    if (p == NULL) // Blank line
132                    {
133                            continue;
134                    }
135    
136                    if (*p == '#' || *p == '\r' || *p == '\n') // Comment or blank line
137                    {
138                            continue;
139                    }
140    
141                    if (strlen(p) > sizeof(bbsnet_conf[menu_item_id].org_name) - 1)
142                    {
143                            log_error("Error org_name in BBSNET config line %d", fin_line);
144                            continue;
145                    }
146                    strncpy(bbsnet_conf[menu_item_id].org_name, p, sizeof(bbsnet_conf[menu_item_id].org_name) - 1);
147                    bbsnet_conf[menu_item_id].org_name[sizeof(bbsnet_conf[menu_item_id].org_name) - 1] = '\0';
148    
149                    p = strtok_r(NULL, MENU_CONF_DELIM, &saveptr);
150                    if (p == NULL || strlen(p) > sizeof(bbsnet_conf[menu_item_id].site_name) - 1)
151                    {
152                            log_error("Error site_name in BBSNET config line %d", fin_line);
153                            continue;
154                    }
155                    strncpy(bbsnet_conf[menu_item_id].site_name, p, sizeof(bbsnet_conf[menu_item_id].site_name) - 1);
156                    bbsnet_conf[menu_item_id].site_name[sizeof(bbsnet_conf[menu_item_id].site_name) - 1] = '\0';
157    
158                    p = strtok_r(NULL, MENU_CONF_DELIM, &saveptr);
159                    if (p == NULL || strlen(p) > sizeof(bbsnet_conf[menu_item_id].host_name) - 1)
160                    {
161                            log_error("Error host_name in BBSNET config line %d", fin_line);
162                            continue;
163                    }
164                    strncpy(bbsnet_conf[menu_item_id].host_name, p, sizeof(bbsnet_conf[menu_item_id].host_name) - 1);
165                    bbsnet_conf[menu_item_id].host_name[sizeof(bbsnet_conf[menu_item_id].host_name) - 1] = '\0';
166    
167                    p = strtok_r(NULL, MENU_CONF_DELIM, &saveptr);
168                    if (p == NULL || strlen(p) > sizeof(bbsnet_conf[menu_item_id].port) - 1)
169                    {
170                            log_error("Error port in BBSNET config line %d", fin_line);
171                            continue;
172                    }
173                    port = strtol(p, &endptr, 10);
174                    if (*endptr != '\0' || port <= 0 || port > 65535)
175                    {
176                            log_error("Invalid port %ld in BBSNET config line %d", port, fin_line);
177                            continue;
178                    }
179                    strncpy(bbsnet_conf[menu_item_id].port, p, sizeof(bbsnet_conf[menu_item_id].port) - 1);
180                    bbsnet_conf[menu_item_id].port[sizeof(bbsnet_conf[menu_item_id].port) - 1] = '\0';
181    
182                    p = strtok_r(NULL, MENU_CONF_DELIM, &saveptr);
183                    if (p == NULL || strlen(p) != 1)
184                    {
185                            log_error("Error use_ssh in BBSNET config line %d", fin_line);
186                            continue;
187                    }
188                    bbsnet_conf[menu_item_id].use_ssh = (toupper(p[0]) == 'Y');
189    
190                    p = strtok_r(NULL, MENU_CONF_DELIM, &saveptr);
191                    if (p == NULL || strlen(p) > sizeof(bbsnet_conf[menu_item_id].charset) - 1)
192                    {
193                            log_error("Error charset in BBSNET config line %d", fin_line);
194                            continue;
195                    }
196                    strncpy(bbsnet_conf[menu_item_id].charset, p, sizeof(bbsnet_conf[menu_item_id].charset) - 1);
197                    bbsnet_conf[menu_item_id].charset[sizeof(bbsnet_conf[menu_item_id].charset) - 1] = '\0';
198    
199                    p_menu_item = get_menu_item_by_id(&bbsnet_menu, menu_item_id);
200                    if (p_menu_item == NULL)
201                    {
202                            log_error("get_menu_item_by_id(%d) error: NULL pointer", menu_item_id);
203                            fclose(fin);
204                            unload_bbsnet_conf();
205                            return -3;
206                    }
207    
208                    p_menu_item->row = (int16_t)(2 + menu_item_id / STATION_PER_LINE);
209                    p_menu_item->col = (int16_t)(5 + menu_item_id % STATION_PER_LINE * 20);
210                    snprintf(p_menu_item->action, sizeof(p_menu_item->action), "%d", (int16_t)menu_item_id);
211                    p_menu_item->submenu = 0;
212                    p_menu_item->priv = 0;
213                    p_menu_item->level = 0;
214                    p_menu_item->name[0] =
215                            (char)(menu_item_id < MAXSTATION / 2 ? 'A' + menu_item_id : 'a' + menu_item_id - MAXSTATION / 2);
216                    p_menu_item->name[1] = '\0';
217                    snprintf(p_menu_item->text, sizeof(p_menu_item->text), "\033[1;36m%c.\033[m %s",
218                                     p_menu_item->name[0], bbsnet_conf[menu_item_id].site_name);
219    
220                    p_menu->items[p_menu->item_count] = menu_item_id;
221                    p_menu->item_count++;
222                    menu_item_id++;
223            }
224    
225            bbsnet_menu.menu_item_count = (int16_t)menu_item_id;
226            bbsnet_menu.menu_id_path[0] = 0;
227            bbsnet_menu.menu_item_pos[0] = 0;
228            bbsnet_menu.choose_step = 0;
229    
230            fclose(fin);
231    
232            return 0;
233    }
234    
235    static void unload_bbsnet_conf(void)
236    {
237            bbsnet_menu.menu_count = 0;
238            bbsnet_menu.menu_item_count = 0;
239    
240            if (bbsnet_menu.p_menu_pool)
241            {
242                    free(bbsnet_menu.p_menu_pool);
243                    bbsnet_menu.p_menu_pool = NULL;
244            }
245    
246            if (bbsnet_menu.p_menu_item_pool)
247            {
248                    free(bbsnet_menu.p_menu_item_pool);
249                    bbsnet_menu.p_menu_item_pool = NULL;
250            }
251    }
252    
253  int  static void progress_bar(int percent, int len)
 load_bbsnet_conf (const char *file_config)  
254  {  {
255    FILE *fp;          char line[LINE_BUFFER_LEN];
256    MENU *p_menu;          char buf[LINE_BUFFER_LEN];
257    MENU_ITEM *p_menuitem;          int pos;
258    char t[256], *t1, *t2, *t3, *t4;  
259    int item_count = 0;          if (len < 4)
260            {
261    fp = fopen (file_config, "r");                  len = 4;
262    if (fp == NULL)          }
263      return -1;          else if (len + 2 > LINE_BUFFER_LEN)
264            {
265    p_menu = bbsnet_menu.p_menu[0] = malloc (sizeof (MENU));                  len = LINE_BUFFER_LEN - 3;
266    strcpy (p_menu->name, "BBSNET");          }
267    p_menu->title.show = 0;          if (percent < 0)
268    p_menu->screen.show = 0;          {
269                    percent = 0;
270    while (fgets (t, 255, fp) && item_count < MAXSTATION)          }
271      {          else if (percent > 100)
272        t1 = strtok (t, " \t");          {
273        t2 = strtok (NULL, " \t\n");                  percent = 100;
274        t3 = strtok (NULL, " \t\n");          }
275        t4 = strtok (NULL, " \t\n");  
276            pos = len * percent / 100;
277        if (t1[0] == '#' || t1[0] == '*' || t1 == NULL || t2 == NULL  
278            || t3 == NULL)          line[0] = ' ';
279          continue;          for (int i = 1; i <= len; i++)
280        strncpy (bbsnet_conf[item_count].host1, t2, 18);          {
281        bbsnet_conf[item_count].host1[18] = 0;                  line[i] = '-';
282        strncpy (bbsnet_conf[item_count].host2, t1, 36);          }
283        bbsnet_conf[item_count].host2[36] = 0;          line[len + 1] = ' ';
284        strncpy (bbsnet_conf[item_count].ip, t3, 36);          line[len + 2] = '\0';
285        bbsnet_conf[item_count].ip[36] = 0;  
286        bbsnet_conf[item_count].port = t4 ? atoi (t4) : 23;          snprintf(buf, sizeof(buf), "%*s%3d%%%*s",
287                             (len - 4) / 2, "", percent, (len - 4 + 1) / 2, "");
       p_menuitem = p_menu->items[item_count] = malloc (sizeof (MENU_ITEM));  
       p_menuitem->row = 2 + item_count / STATION_PER_LINE;  
       p_menuitem->col = 5 + item_count % STATION_PER_LINE * 20;  
       sprintf (p_menuitem->action, "%d", item_count);  
       p_menuitem->submenu = 0;  
       p_menuitem->priv = 0;  
       p_menuitem->level = 0;  
       p_menuitem->display = 0;  
       p_menuitem->name[0] =  
         (item_count < MAXSTATION / 2 ? 'A' + item_count : 'a' + item_count);  
       p_menuitem->name[1] = '\0';  
       sprintf (p_menuitem->text, "%c. %s",  
                p_menuitem->name[0], bbsnet_conf[item_count].host1);  
   
       item_count++;  
     }  
   fclose (fp);  
   
   p_menu->item_count = item_count;  
   p_menu->item_cur_pos = 0;  
   
   bbsnet_menu.menu_count = 1;  
   bbsnet_menu.menu_select_depth = 0;  
   bbsnet_menu.p_menu_select[0] = bbsnet_menu.p_menu[0];  
288    
289    return 0;          moveto(4, 1);
290            prints("%s\r\n", line);
291            prints("|\033[46m%.*s\033[44m%s\033[m|\r\n", pos, buf, buf + pos);
292            prints("%s\r\n", line);
293            iflush();
294  }  }
295    
296  static void  static int connect_timeout(struct timespec *p_ts_begin, struct timespec *p_ts_now,
297  process_bar (int n, int len)                                                     int total_time_ms, int *p_progress_last, int bar_len)
298  {  {
299    char buf[256];          long duration_ms;
300    char buf2[256];          int progress;
301    char *ptr;  
302    char *ptr2;          if (clock_gettime(CLOCK_REALTIME, p_ts_now) == -1)
303    char *ptr3;          {
304                    log_error("clock_gettime() error (%d)", errno);
305    moveto (4, 0);                  return -1;
306    prints ("\r\n");          }
307    sprintf (buf2, "            %3d%%              ", n * 100 / len);  
308    ptr = buf;          duration_ms = (p_ts_now->tv_sec - p_ts_begin->tv_sec) * 1000 +
309    ptr2 = buf2;                                    (p_ts_now->tv_nsec - p_ts_begin->tv_nsec) / 1000 / 1000;
310    ptr3 = buf + n;  
311    while (ptr != ptr3)          if (duration_ms >= total_time_ms)
312      *ptr++ = *ptr2++;          {
313    *ptr++ = '\x1b';                  progress_bar(100, bar_len);
314    *ptr++ = '[';                  prints("\033[1;31m连接超时!\033[m\r\n");
315    *ptr++ = '4';                  press_any_key();
316    *ptr++ = '4';  
317    *ptr++ = 'm';                  return 1;
318    while (*ptr2 != '\0')          }
319      *ptr++ = *ptr2++;  
320    *ptr++ = '\0';          progress = (int)(duration_ms * 100 / total_time_ms) + 1;
321    prints ("\033[46m%s\033[m\r\n", buf);  
322    prints ("\r\n");          if (progress != *p_progress_last)
323    iflush ();          {
324                    *p_progress_last = progress;
325                    progress_bar(progress, bar_len);
326            }
327    
328            return 0;
329  }  }
330    
331  int  static int bbsnet_connect(int n)
 bbsnet_connect (int n)  
332  {  {
333    int sock, ch, result, len, loop;          int sock = -1;
334    struct sockaddr_in sin;          int ret = 0;
335    char buf[256];          int loop;
336    fd_set inputs, testfds;          int error;
337    struct timeval timeout;          int sock_connected = 0;
338    struct hostent *pHost = NULL;          int ssh_connected = 0;
339    int rc, rv, tos = 020, i;          int flags_sock = -1;
340    char remote_addr[256];          int flags_stdin = -1;
341    int remote_port;          int flags_stdout = -1;
342    time_t t_used;          struct sockaddr_in sin;
343    struct tm * tm_used;          char input_buf[LINE_BUFFER_LEN];
344            char output_buf[LINE_BUFFER_LEN];
345    clearscr ();          int input_buf_len = 0;
346            int output_buf_len = 0;
347    moveto (0, 0);          int input_buf_offset = 0;
348    prints ("\033[1;32mڲ %s (%s) ӣԺ... \033[m\r\n",          int output_buf_offset = 0;
349      bbsnet_conf[n].host1, bbsnet_conf[n].ip);          char input_conv[LINE_BUFFER_LEN * 2];
350    prints ("\033[1;32m %d ޷ϣ򽫷ӡ\033[m\r\n",          char output_conv[LINE_BUFFER_LEN * 2];
351      TIME_OUT);          int input_conv_len = 0;
352    iflush ();          int output_conv_len = 0;
353            int input_conv_offset = 0;
354    pHost = gethostbyname (bbsnet_conf[n].ip);          int output_conv_offset = 0;
355            iconv_t input_cd = (iconv_t)(-1);
356    if (pHost == NULL)          iconv_t output_cd = (iconv_t)(-1);
357      {          char tocode[CHARSET_MAX_LEN + 20];
358        prints ("\033[1;31mʧܣ\033[m\r\n");  
359        press_any_key ();  #ifdef HAVE_SYS_EPOLL_H
360        return -1;          struct epoll_event ev, events[MAX_EVENTS];
361      }          int epollfd = -1;
362    #else
363    sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);          struct pollfd pfds[3];
364    #endif
365    if (sock < 0)  
366      {          int nfds;
367        prints ("\033[1;31m޷socket\033[m\r\n");          int stdin_read_wait = 0;
368        press_any_key ();          int stdout_write_wait = 0;
369        return -1;          int sock_read_wait = 0;
370      }          int sock_write_wait = 0;
371            struct addrinfo hints, *res = NULL;
372    sin.sin_family = AF_INET;          int tos;
373    sin.sin_addr.s_addr =          char remote_addr[INET_ADDRSTRLEN];
374      (strlen (hostaddr_server) > 0 ? inet_addr (hostaddr_server) : INADDR_ANY);          int remote_port;
375    sin.sin_port = 0;          char local_addr[INET_ADDRSTRLEN];
376            int local_port;
377    if (bind (sock, (struct sockaddr *) &sin, sizeof (sin)) < 0)          socklen_t sock_len;
378      {          time_t t_begin, t_used;
379        log_error ("Bind address %s:%u failed\n",          struct timespec ts_begin, ts_now;
380                   inet_ntoa (sin.sin_addr), ntohs (sin.sin_port));          int progress_last = 0;
381        return -2;          int ch;
382      }          char remote_user[USERNAME_MAX_LEN + 1];
383              char remote_pass[PASSWORD_MAX_LEN + 1];
384    bzero (&sin, sizeof (sin));          ssh_session outbound_session = NULL;
385    sin.sin_family = AF_INET;          ssh_channel outbound_channel = NULL;
386    sin.sin_addr = *(struct in_addr *) pHost->h_addr_list[0];          int ssh_process_config = 0;
387    sin.sin_port = htons (bbsnet_conf[n].port);          int ssh_log_level = SSH_LOG_NOLOG;
388    
389    strcpy (remote_addr, inet_ntoa (sin.sin_addr));          if (user_online_update("BBS_NET") < 0)
390    remote_port = ntohs (sin.sin_port);          {
391                    log_error("user_online_update(BBS_NET) error");
392    prints ("\033[1;32mʾǰʹõʱ䡣\033[m\r\n");          }
393    process_bar (0, MAX_PROCESS_BAR_LEN);  
394    for (i = 0; i < MAX_PROCESS_BAR_LEN; i++)          if (bbsnet_conf[n].use_ssh)
395      {          {
396        if (i == 0)                  clearscr();
397          rv =  
398            NonBlockConnectEx (sock, (struct sockaddr *) &sin, sizeof (sin),                  if (!SSH_v2)
399                               500, 1);                  {
400        else                          moveto(1, 1);
401          rv =                          prints("只有在以SSH方式登陆本站时,才能使用SSH站点穿梭。");
402            NonBlockConnectEx (sock, (struct sockaddr *) &sin, sizeof (sin),                          press_any_key();
403                               500, 0);                          return 0;
404        if (rv == ERR_TCPLIB_TIMEOUT)                  }
405          {  
406            process_bar (i + 1, MAX_PROCESS_BAR_LEN);                  moveto(1, 1);
407            continue;                  prints("\033[1;32m正在准备往 %s (%s:%s) 的%s连接... \033[m\r\n",
408          }                             bbsnet_conf[n].site_name, bbsnet_conf[n].host_name, bbsnet_conf[n].port,
409        else if (rv == 0)                             (bbsnet_conf[n].use_ssh ? "SSH" : "Telnet"));
410          break;                  prints("请输入用户名: ");
411        else                  iflush();
412          {                  if (str_input(remote_user, sizeof(remote_user), DOECHO) < 0)
413            prints ("\033[1;31mʧܣ\033[m\r\n");                  {
414            press_any_key ();                          return -1;
415            return -1;                  }
416          }                  if (remote_user[0] == '\0')
417      }                  {
418    if (i == MAX_PROCESS_BAR_LEN)                          return 0;
419      {                  }
420        prints ("\033[1;31mӳʱ\033[m\r\n");  
421        press_any_key ();                  moveto(3, 1);
422        return -1;                  prints("请输入密码: ");
423      }                  iflush();
424    setsockopt (sock, IPPROTO_IP, IP_TOS, &tos, sizeof (int));                  if (str_input(remote_pass, sizeof(remote_pass), NOECHO) < 0)
425                    {
426    prints ("\033[1;31mӳɹ\033[m\r\n");                          return -1;
427    log_std ("BBSNET connect to %s:%d\n",                  }
428      remote_addr, remote_port);                  if (remote_pass[0] == '\0')
429                    {
430    FD_ZERO (&inputs);                          return 0;
431    FD_SET (0, &inputs);                  }
432    FD_SET (sock, &inputs);          }
433    
434    BBS_last_access_tm = t_used = time (0);          clearscr();
435    
436    loop = 1;          moveto(1, 1);
437            prints("\033[1;32m正在测试往 %s (%s:%s) 的%s连接,请稍候... \033[m\r\n",
438    while (loop)                     bbsnet_conf[n].site_name, bbsnet_conf[n].host_name, bbsnet_conf[n].port,
439      {                     (bbsnet_conf[n].use_ssh ? "SSH" : "Telnet"));
440        testfds = inputs;          prints("\033[1;32m连接进行中,按\033[1;33mCtrl+C\033[1;32m中断。\033[m\r\n");
441        timeout.tv_sec = TIME_OUT;          progress_bar(0, PROGRESS_BAR_LEN);
442        timeout.tv_usec = 0;  
443            if (clock_gettime(CLOCK_REALTIME, &ts_begin) == -1)
444        result = select (FD_SETSIZE, &testfds, (fd_set *) NULL,          {
445                         (fd_set *) NULL, &timeout);                  log_error("clock_gettime() error (%d)", errno);
446                    ret = -1;
447        switch (result)                  goto cleanup;
448          {          }
449          case 0:          ts_now = ts_begin;
450            if (time (0) - BBS_last_access_tm >= MAX_DELAY_TIME)  
451              {          memset(&hints, 0, sizeof(hints));
452                loop = 0;          hints.ai_family = AF_INET;
453              }          hints.ai_socktype = SOCK_STREAM;
454            break;          hints.ai_protocol = IPPROTO_TCP;
455          case -1:  
456            log_error ("select() error!\n");          if ((ret = getaddrinfo(BBS_address, NULL, &hints, &res)) != 0)
457            break;          {
458          default:                  log_error("getaddrinfo() error (%d): %s", ret, gai_strerror(ret));
459            if (FD_ISSET (0, &testfds))                  ret = -1;
460              {                  goto cleanup;
461                len = read (0, buf, 255);          }
462                if (len == 0)  
463                  {          if (inet_ntop(AF_INET, &(((struct sockaddr_in *)res->ai_addr)->sin_addr), local_addr, sizeof(local_addr)) == NULL)
464                    loop = 0;          {
465                    break;                  log_error("inet_ntop() error (%d)", errno);
466                  }                  ret = -1;
467                write (sock, buf, len);                  goto cleanup;
468              }          }
469            if (FD_ISSET (sock, &testfds))          local_port = ntohs(((struct sockaddr_in *)res->ai_addr)->sin_port);
470              {  
471                len = read (sock, buf, 255);          sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
472                if (len == 0)          if (sock < 0)
473                  {          {
474                    loop = 0;                  log_error("socket() error (%d)", errno);
475                    break;                  ret = -1;
476                  }                  goto cleanup;
477                write (1, buf, len);          }
478              }  
479            break;          if (bind(sock, res->ai_addr, res->ai_addrlen) < 0)
480            BBS_last_access_tm = time (0);          {
481          }                  log_error("bind(%s:%u) error (%d)", local_addr, local_port, errno);
482      }                  ret = -1;
483                    goto cleanup;
484    if (close (sock) == -1)          }
485      {  
486        log_error ("Close socket failed\n");          freeaddrinfo(res);
487      }          res = NULL;
488    
489            memset(&hints, 0, sizeof(hints));
490            hints.ai_family = AF_INET;
491            hints.ai_flags = AI_NUMERICSERV;
492            hints.ai_socktype = SOCK_STREAM;
493            hints.ai_protocol = IPPROTO_TCP;
494    
495            if ((ret = getaddrinfo(bbsnet_conf[n].host_name, bbsnet_conf[n].port, &hints, &res)) != 0)
496            {
497                    log_error("getaddrinfo() error (%d): %s", ret, gai_strerror(ret));
498                    prints("\033[1;31m查找主机名失败!\033[m\r\n");
499                    press_any_key();
500                    ret = -1;
501                    goto cleanup;
502            }
503    
504            if (inet_ntop(AF_INET, &(((struct sockaddr_in *)res->ai_addr)->sin_addr), remote_addr, sizeof(remote_addr)) == NULL)
505            {
506                    log_error("inet_ntop() error (%d)", errno);
507                    ret = -1;
508                    goto cleanup;
509            }
510            remote_port = ntohs(((struct sockaddr_in *)res->ai_addr)->sin_port);
511    
512            // Set socket as non-blocking
513            if ((flags_sock = fcntl(sock, F_GETFL, 0)) == -1)
514            {
515                    log_error("fcntl(F_GETFL) error (%d)", errno);
516                    ret = -1;
517                    goto cleanup;
518            }
519            if ((fcntl(sock, F_SETFL, flags_sock | O_NONBLOCK)) == -1)
520            {
521                    log_error("fcntl(F_SETFL) error (%d)", errno);
522                    ret = -1;
523                    goto cleanup;
524            }
525    
526            // Set STDIN/STDOUT as non-blocking
527            if ((flags_stdin = fcntl(STDIN_FILENO, F_GETFL, 0)) == -1)
528            {
529                    log_error("fcntl(F_GETFL) error (%d)", errno);
530                    ret = -1;
531                    goto cleanup;
532            }
533            if ((flags_stdout = fcntl(STDOUT_FILENO, F_GETFL, 0)) == -1)
534            {
535                    log_error("fcntl(F_GETFL) error (%d)", errno);
536                    ret = -1;
537                    goto cleanup;
538            }
539            if ((fcntl(STDIN_FILENO, F_SETFL, flags_stdin | O_NONBLOCK)) == -1)
540            {
541                    log_error("fcntl(F_SETFL) error (%d)", errno);
542                    ret = -1;
543                    goto cleanup;
544            }
545            if ((fcntl(STDOUT_FILENO, F_SETFL, flags_stdout | O_NONBLOCK)) == -1)
546            {
547                    log_error("fcntl(F_SETFL) error (%d)", errno);
548                    ret = -1;
549                    goto cleanup;
550            }
551    
552    #ifdef HAVE_SYS_EPOLL_H
553            epollfd = epoll_create1(0);
554            if (epollfd < 0)
555            {
556                    log_error("epoll_create1() error (%d)", errno);
557                    ret = -1;
558                    goto cleanup;
559            }
560    
561            ev.events = EPOLLOUT | EPOLLET;
562            ev.data.fd = sock;
563            if (epoll_ctl(epollfd, EPOLL_CTL_ADD, sock, &ev) == -1)
564            {
565                    log_error("epoll_ctl(socket) error (%d)", errno);
566                    ret = -1;
567                    goto cleanup;
568            }
569    
570            ev.events = EPOLLIN | EPOLLET;
571            ev.data.fd = STDIN_FILENO;
572            if (epoll_ctl(epollfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev) == -1)
573            {
574                    log_error("epoll_ctl(STDIN_FILENO) error (%d)", errno);
575                    ret = -1;
576                    goto cleanup;
577            }
578    #endif
579    
580            while (!SYS_server_exit &&
581                       !connect_timeout(&ts_begin, &ts_now, REMOTE_CONNECT_TIMEOUT * 1000, &progress_last, PROGRESS_BAR_LEN))
582            {
583                    if ((ret = connect(sock, res->ai_addr, res->ai_addrlen)) == 0)
584                    {
585                            sock_connected = 1;
586                            break;
587                    }
588                    else if (ret < 0)
589                    {
590                            if (errno == EAGAIN || errno == EALREADY || errno == EINPROGRESS)
591                            {
592                                    // Use select / epoll to check writability of the socket,
593                                    // then use getsockopt to check the status of the socket.
594                                    // See man connect(2)
595                                    break;
596                            }
597                            else if (errno == EINTR)
598                            {
599                            }
600                            else
601                            {
602                                    log_error("connect(socket) error (%d)", errno);
603                                    prints("\033[1;31m连接失败!\033[m\r\n");
604                                    press_any_key();
605                                    ret = -1;
606                                    goto cleanup;
607                            }
608                    }
609            }
610    
611            while (!SYS_server_exit && !sock_connected &&
612                       !connect_timeout(&ts_begin, &ts_now, REMOTE_CONNECT_TIMEOUT * 1000, &progress_last, PROGRESS_BAR_LEN))
613            {
614    #ifdef HAVE_SYS_EPOLL_H
615                    nfds = epoll_wait(epollfd, events, MAX_EVENTS, 100); // 0.1 second
616                    ret = nfds;
617    #else
618                    pfds[0].fd = sock;
619                    pfds[0].events = POLLOUT;
620                    pfds[1].fd = STDIN_FILENO;
621                    pfds[1].events = POLLIN;
622                    nfds = 2;
623                    ret = poll(pfds, (nfds_t)nfds, 100); // 0.1 second
624    #endif
625    
626                    if (ret < 0)
627                    {
628                            if (errno != EINTR)
629                            {
630    #ifdef HAVE_SYS_EPOLL_H
631                                    log_error("epoll_wait() error (%d)", errno);
632    #else
633                                    log_error("poll() error (%d)", errno);
634    #endif
635                                    break;
636                            }
637                    }
638                    else if (ret == 0) // timeout
639                    {
640                    }
641                    else // ret > 0
642                    {
643                            for (int i = 0; i < nfds; i++)
644                            {
645    #ifdef HAVE_SYS_EPOLL_H
646                                    if (events[i].data.fd == sock)
647    #else
648                                    if (pfds[i].fd == sock && (pfds[i].revents & POLLOUT))
649    #endif
650                                    {
651                                            socklen_t len = sizeof(error);
652                                            if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
653                                            {
654                                                    log_error("getsockopt() error (%d) !", errno);
655                                                    ret = -1;
656                                                    goto cleanup;
657                                            }
658                                            if (error == 0)
659                                            {
660                                                    sock_connected = 1;
661                                                    break;
662                                            }
663                                    }
664    #ifdef HAVE_SYS_EPOLL_H
665                                    else if (events[i].data.fd == STDIN_FILENO)
666    #else
667                                    else if (pfds[i].fd == STDIN_FILENO && (pfds[i].revents & POLLIN))
668    #endif
669                                    {
670                                            do
671                                            {
672                                                    ch = igetch(0);
673                                            } while (ch == 0);
674                                            if (ch == Ctrl('C') || ch == KEY_ESC)
675                                            {
676                                                    ret = 0;
677                                                    goto cleanup;
678                                            }
679                                    }
680                            }
681                    }
682            }
683            if (!sock_connected)
684            {
685                    ret = -1;
686                    goto cleanup;
687            }
688    
689            tos = IPTOS_LOWDELAY;
690            if (setsockopt(sock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
691            {
692                    log_error("setsockopt IP_TOS=%d error (%d)", tos, errno);
693            }
694    
695            sock_len = sizeof(sin);
696            if (getsockname(sock, (struct sockaddr *)&sin, &sock_len) < 0)
697            {
698                    log_error("getsockname() error: %d", errno);
699                    ret = -1;
700                    goto cleanup;
701            }
702    
703            if (inet_ntop(AF_INET, &(sin.sin_addr), local_addr, sizeof(local_addr)) == NULL)
704            {
705                    log_error("inet_ntop() error (%d)", errno);
706                    ret = -1;
707                    goto cleanup;
708            }
709            local_port = ntohs(sin.sin_port);
710    
711            if (bbsnet_conf[n].use_ssh)
712            {
713                    outbound_session = ssh_new();
714                    if (outbound_session == NULL)
715                    {
716                            log_error("ssh_new() error");
717                            ret = -1;
718                            goto cleanup;
719                    }
720    
721                    if (ssh_options_set(outbound_session, SSH_OPTIONS_FD, &sock) < 0 ||
722                            ssh_options_set(outbound_session, SSH_OPTIONS_PROCESS_CONFIG, &ssh_process_config) < 0 ||
723                            ssh_options_set(outbound_session, SSH_OPTIONS_KNOWNHOSTS, SSH_KNOWN_HOSTS_FILE) < 0 ||
724                            ssh_options_set(outbound_session, SSH_OPTIONS_HOST, bbsnet_conf[n].host_name) < 0 ||
725                            ssh_options_set(outbound_session, SSH_OPTIONS_USER, remote_user) < 0 ||
726                            ssh_options_set(outbound_session, SSH_OPTIONS_HOSTKEYS, "+ssh-ed25519,ecdsa-sha2-nistp256,ssh-rsa") < 0 ||
727                            ssh_options_set(outbound_session, SSH_OPTIONS_LOG_VERBOSITY, &ssh_log_level) < 0)
728                    {
729                            log_error("Error setting SSH options: %s", ssh_get_error(outbound_session));
730                            ret = -1;
731                            goto cleanup;
732                    }
733    
734                    ssh_set_blocking(outbound_session, 0);
735    
736                    ssh_connected = 0;
737                    while (!SYS_server_exit &&
738                               !connect_timeout(&ts_begin, &ts_now, REMOTE_CONNECT_TIMEOUT * 1000, &progress_last, PROGRESS_BAR_LEN))
739                    {
740                            ret = ssh_connect(outbound_session);
741                            if (ret == SSH_OK)
742                            {
743                                    ssh_connected = 1;
744                                    break;
745                            }
746                            else if (ret == SSH_AGAIN)
747                            {
748                                    // log_debug("ssh_connect() error: SSH_AGAIN");
749                            }
750                            else // if (ret == SSH_ERROR)
751                            {
752                                    log_error("ssh_connect() error: SSH_ERROR");
753                                    ret = -1;
754                                    goto cleanup;
755                            }
756                    }
757                    if (!ssh_connected)
758                    {
759                            ret = -1;
760                            goto cleanup;
761                    }
762    
763                    ret = ssh_session_is_known_server(outbound_session);
764                    switch (ret)
765                    {
766                    case SSH_KNOWN_HOSTS_NOT_FOUND:
767                    case SSH_KNOWN_HOSTS_UNKNOWN:
768                            if (ssh_session_update_known_hosts(outbound_session) != SSH_OK)
769                            {
770                                    log_error("ssh_session_update_known_hosts(%s) error", bbsnet_conf[n].host_name);
771                                    prints("\033[1;31m无法添加服务器证书\033[m\r\n");
772                                    press_any_key();
773                                    ret = -1;
774                                    goto cleanup;
775                            }
776                            log_common("SSH key of (%s) is added into %s", bbsnet_conf[n].host_name, SSH_KNOWN_HOSTS_FILE);
777                    case SSH_KNOWN_HOSTS_OK:
778                            break;
779                    case SSH_KNOWN_HOSTS_CHANGED:
780                    case SSH_KNOWN_HOSTS_OTHER:
781                            log_error("ssh_session_is_known_server(%s) error: %d", bbsnet_conf[n].host_name, ret);
782                            prints("\033[1;31m服务器证书已变更\033[m\r\n");
783                            press_any_key();
784                            ret = -1;
785                            goto cleanup;
786                    }
787    
788                    ssh_connected = 0;
789                    while (!SYS_server_exit &&
790                               !connect_timeout(&ts_begin, &ts_now, REMOTE_CONNECT_TIMEOUT * 1000, &progress_last, PROGRESS_BAR_LEN))
791                    {
792                            ret = ssh_userauth_password(outbound_session, NULL, remote_pass);
793                            if (ret == SSH_AUTH_SUCCESS)
794                            {
795                                    ssh_connected = 1;
796                                    break;
797                            }
798                            else if (ret == SSH_AUTH_AGAIN)
799                            {
800                                    // log_debug("ssh_userauth_password() error: SSH_AUTH_AGAIN");
801                            }
802                            else if (ret == SSH_AUTH_ERROR)
803                            {
804                                    log_error("ssh_userauth_password() error: SSH_AUTH_ERROR");
805                                    ret = -1;
806                                    goto cleanup;
807                            }
808                            else // if (ret == SSH_AUTH_DENIED)
809                            {
810                                    log_debug("ssh_userauth_password() error: SSH_AUTH_DENIED");
811                                    prints("\033[1;31m身份验证失败!\033[m\r\n");
812                                    press_any_key();
813                                    ret = 0;
814                                    goto cleanup;
815                            }
816                    }
817                    if (!ssh_connected)
818                    {
819                            ret = -1;
820                            goto cleanup;
821                    }
822    
823                    outbound_channel = ssh_channel_new(outbound_session);
824                    if (outbound_channel == NULL)
825                    {
826                            log_error("ssh_channel_new() error");
827                            ret = -1;
828                            goto cleanup;
829                    }
830    
831                    ssh_connected = 0;
832                    while (!SYS_server_exit &&
833                               !connect_timeout(&ts_begin, &ts_now, REMOTE_CONNECT_TIMEOUT * 1000, &progress_last, PROGRESS_BAR_LEN))
834                    {
835                            ret = ssh_channel_open_session(outbound_channel);
836                            if (ret == SSH_OK)
837                            {
838                                    ssh_connected = 1;
839                                    break;
840                            }
841                            else if (ret == SSH_AGAIN)
842                            {
843                                    // log_debug("ssh_channel_open_session() error: SSH_AGAIN");
844                            }
845                            else // if (ret == SSH_ERROR)
846                            {
847                                    log_error("ssh_channel_open_session() error: SSH_ERROR");
848                                    ret = -1;
849                                    goto cleanup;
850                            }
851                    }
852                    if (!ssh_connected)
853                    {
854                            ret = -1;
855                            goto cleanup;
856                    }
857    
858                    ssh_connected = 0;
859                    while (!SYS_server_exit &&
860                               !connect_timeout(&ts_begin, &ts_now, REMOTE_CONNECT_TIMEOUT * 1000, &progress_last, PROGRESS_BAR_LEN))
861                    {
862                            ret = ssh_channel_request_pty(outbound_channel);
863                            if (ret == SSH_OK)
864                            {
865                                    ssh_connected = 1;
866                                    break;
867                            }
868                            else if (ret == SSH_AGAIN)
869                            {
870                                    // log_debug("ssh_channel_request_pty() error: SSH_AGAIN");
871                            }
872                            else // if (ret == SSH_ERROR)
873                            {
874                                    log_error("ssh_channel_request_pty() error: SSH_ERROR");
875                                    ret = -1;
876                                    goto cleanup;
877                            }
878                    }
879                    if (!ssh_connected)
880                    {
881                            ret = -1;
882                            goto cleanup;
883                    }
884    
885                    ssh_connected = 0;
886                    while (!SYS_server_exit &&
887                               !connect_timeout(&ts_begin, &ts_now, REMOTE_CONNECT_TIMEOUT * 1000, &progress_last, PROGRESS_BAR_LEN))
888                    {
889                            ret = ssh_channel_request_shell(outbound_channel);
890                            if (ret == SSH_OK)
891                            {
892                                    ssh_connected = 1;
893                                    break;
894                            }
895                            else if (ret == SSH_AGAIN)
896                            {
897                                    // log_debug("ssh_channel_request_shell() error: SSH_AGAIN");
898                            }
899                            else // if (ret == SSH_ERROR)
900                            {
901                                    log_error("ssh_channel_request_shell() error: SSH_ERROR");
902                                    ret = -1;
903                                    goto cleanup;
904                            }
905                    }
906                    if (!ssh_connected)
907                    {
908                            ret = -1;
909                            goto cleanup;
910                    }
911            }
912    
913            prints("\033[1;31m连接成功!\033[m\r\n");
914            iflush();
915            log_common("BBSNET connect to %s:%d from %s:%d by [%s]",
916                               remote_addr, remote_port, local_addr, local_port, BBS_username);
917    
918            snprintf(tocode, sizeof(tocode), "%s%s", bbsnet_conf[n].charset,
919                             (strcasecmp(stdio_charset, bbsnet_conf[n].charset) == 0 ? "" : "//IGNORE"));
920            input_cd = iconv_open(tocode, stdio_charset);
921            if (input_cd == (iconv_t)(-1))
922            {
923                    log_error("iconv_open(%s->%s) error: %d", stdio_charset, tocode, errno);
924                    ret = -1;
925                    goto cleanup;
926            }
927    
928            snprintf(tocode, sizeof(tocode), "%s%s", stdio_charset,
929                             (strcasecmp(bbsnet_conf[n].charset, stdio_charset) == 0 ? "" : "//TRANSLIT"));
930            output_cd = iconv_open(tocode, bbsnet_conf[n].charset);
931            if (output_cd == (iconv_t)(-1))
932            {
933                    log_error("iconv_open(%s->%s) error: %d", bbsnet_conf[n].charset, tocode, errno);
934                    ret = -1;
935                    goto cleanup;
936            }
937    
938    #ifdef HAVE_SYS_EPOLL_H
939            ev.events = EPOLLIN | EPOLLOUT | EPOLLET;
940            ev.data.fd = sock;
941            if (epoll_ctl(epollfd, EPOLL_CTL_MOD, sock, &ev) == -1)
942            {
943                    log_error("epoll_ctl(socket) error (%d)", errno);
944                    ret = -1;
945                    goto cleanup;
946            }
947    
948            ev.events = EPOLLOUT | EPOLLET;
949            ev.data.fd = STDOUT_FILENO;
950            if (epoll_ctl(epollfd, EPOLL_CTL_ADD, STDOUT_FILENO, &ev) == -1)
951            {
952                    log_error("epoll_ctl(STDOUT_FILENO) error (%d)", errno);
953                    ret = -1;
954                    goto cleanup;
955            }
956    #endif
957    
958            BBS_last_access_tm = t_begin = time(NULL);
959            loop = 1;
960    
961            while (loop && !SYS_server_exit)
962            {
963                    if (SSH_v2 && ssh_channel_is_closed(SSH_channel))
964                    {
965                            log_debug("SSH channel is closed");
966                            loop = 0;
967                            break;
968                    }
969    
970                    if (bbsnet_conf[n].use_ssh && ssh_channel_is_closed(outbound_channel))
971                    {
972                            log_debug("Outbound channel is closed");
973                            loop = 0;
974                            break;
975                    }
976    
977    #ifdef HAVE_SYS_EPOLL_H
978                    nfds = epoll_wait(epollfd, events, MAX_EVENTS, 100); // 0.1 second
979                    ret = nfds;
980    #else
981                    pfds[0].fd = STDIN_FILENO;
982                    pfds[0].events = POLLIN;
983                    pfds[1].fd = sock;
984                    pfds[1].events = POLLIN | POLLOUT;
985                    pfds[2].fd = STDOUT_FILENO;
986                    pfds[2].events = POLLOUT;
987                    nfds = 3;
988                    ret = poll(pfds, (nfds_t)nfds, 100); // 0.1 second
989    #endif
990    
991                    if (ret < 0)
992                    {
993                            if (errno != EINTR)
994                            {
995    #ifdef HAVE_SYS_EPOLL_H
996                                    log_error("epoll_wait() error (%d)", errno);
997    #else
998                                    log_error("poll() error (%d)", errno);
999    #endif
1000                                    break;
1001                            }
1002                            continue;
1003                    }
1004                    else if (ret == 0) // timeout
1005                    {
1006                            if (time(NULL) - BBS_last_access_tm >= BBS_max_user_idle_time)
1007                            {
1008                                    log_debug("User input timeout");
1009                                    break;
1010                            }
1011                    }
1012    
1013                    for (int i = 0; i < nfds; i++)
1014                    {
1015    #ifdef HAVE_SYS_EPOLL_H
1016                            if (events[i].events & (EPOLLHUP | EPOLLERR))
1017    #else
1018                            if (pfds[i].revents & (POLLHUP | POLLERR))
1019    #endif
1020                            {
1021    #ifdef HAVE_SYS_EPOLL_H
1022                                    log_debug("FD (%d) error events (%d)", events[i].data.fd, events[i].events);
1023    #else
1024                                    log_debug("FD (%d) error events (%d)", pfds[i].fd, pfds[i].revents);
1025    #endif
1026                                    loop = 0;
1027                                    break;
1028                            }
1029    
1030    #ifdef HAVE_SYS_EPOLL_H
1031                            if (events[i].data.fd == STDIN_FILENO && (events[i].events & EPOLLIN))
1032    #else
1033                            if (pfds[i].fd == STDIN_FILENO && (pfds[i].revents & POLLIN))
1034    #endif
1035                            {
1036                                    stdin_read_wait = 1;
1037                            }
1038    
1039    #ifdef HAVE_SYS_EPOLL_H
1040                            if (events[i].data.fd == sock)
1041    #else
1042                            if (pfds[i].fd == sock)
1043    #endif
1044                            {
1045    #ifdef HAVE_SYS_EPOLL_H
1046                                    if (events[i].events & EPOLLIN)
1047    #else
1048                                    if (pfds[i].revents & POLLIN)
1049    #endif
1050                                    {
1051                                            sock_read_wait = 1;
1052                                    }
1053    
1054    #ifdef HAVE_SYS_EPOLL_H
1055                                    if (events[i].events & EPOLLOUT)
1056    #else
1057                                    if (pfds[i].revents & POLLOUT)
1058    #endif
1059                                    {
1060                                            sock_write_wait = 1;
1061                                    }
1062                            }
1063    
1064    #ifdef HAVE_SYS_EPOLL_H
1065                            if (events[i].data.fd == STDOUT_FILENO && (events[i].events & EPOLLOUT))
1066    #else
1067                            if (pfds[i].fd == STDOUT_FILENO && (pfds[i].revents & POLLOUT))
1068    #endif
1069                            {
1070                                    stdout_write_wait = 1;
1071                            }
1072                    }
1073    
1074                    if (stdin_read_wait)
1075                    {
1076                            while (input_buf_len < sizeof(input_buf) && !SYS_server_exit)
1077                            {
1078                                    if (SSH_v2)
1079                                    {
1080                                            ret = ssh_channel_read_nonblocking(SSH_channel, input_buf + input_buf_len, sizeof(input_buf) - (uint32_t)input_buf_len, 0);
1081                                            if (ret == SSH_ERROR)
1082                                            {
1083                                                    log_debug("ssh_channel_read_nonblocking() error: %s", ssh_get_error(SSH_session));
1084                                                    loop = 0;
1085                                                    break;
1086                                            }
1087                                            else if (ret == SSH_EOF)
1088                                            {
1089                                                    stdin_read_wait = 0;
1090                                                    loop = 0;
1091                                                    break;
1092                                            }
1093                                            else if (ret == 0)
1094                                            {
1095                                                    // Send NO-OP to remote server
1096                                                    input_buf[input_buf_len] = '\0';
1097                                                    input_buf_len++;
1098    
1099                                                    BBS_last_access_tm = time(NULL);
1100                                                    stdin_read_wait = 0;
1101                                                    break; // Check whether channel is still open
1102                                            }
1103                                    }
1104                                    else
1105                                    {
1106                                            ret = (int)read(STDIN_FILENO, input_buf + input_buf_len, sizeof(input_buf) - (size_t)input_buf_len);
1107                                    }
1108                                    if (ret < 0)
1109                                    {
1110                                            if (errno == EAGAIN || errno == EWOULDBLOCK)
1111                                            {
1112                                                    stdin_read_wait = 0;
1113                                                    break;
1114                                            }
1115                                            else if (errno == EINTR)
1116                                            {
1117                                                    continue;
1118                                            }
1119                                            else
1120                                            {
1121                                                    log_error("read(STDIN) error (%d)", errno);
1122                                                    loop = 0;
1123                                                    break;
1124                                            }
1125                                    }
1126                                    else if (ret == 0) // broken pipe
1127                                    {
1128                                            log_debug("read(STDIN) EOF");
1129                                            stdin_read_wait = 0;
1130                                            loop = 0;
1131                                            break;
1132                                    }
1133                                    else
1134                                    {
1135                                            input_buf_len += ret;
1136                                            BBS_last_access_tm = time(NULL);
1137    
1138                                            // Refresh current action while user input
1139                                            if (user_online_update("BBS_NET") < 0)
1140                                            {
1141                                                    log_error("user_online_update(BBS_NET) error");
1142                                            }
1143    
1144                                            continue;
1145                                    }
1146                            }
1147                    }
1148    
1149                    if (sock_write_wait)
1150                    {
1151                            if (input_buf_offset < input_buf_len)
1152                            {
1153                                    // For debug
1154    #ifdef _DEBUG
1155                                    for (int j = input_buf_offset; j < input_buf_len; j++)
1156                                    {
1157                                            log_debug("input: <--[%u]", (unsigned char)(input_buf[j]));
1158                                    }
1159    #endif
1160    
1161                                    ret = io_buf_conv(input_cd, input_buf, &input_buf_len, &input_buf_offset, input_conv, sizeof(input_conv), &input_conv_len);
1162                                    if (ret < 0)
1163                                    {
1164                                            log_error("io_buf_conv(input, %d, %d, %d) error", input_buf_len, input_buf_offset, input_conv_len);
1165                                            input_buf_len = input_buf_offset; // Discard invalid sequence
1166                                    }
1167    
1168                                    // For debug
1169    #ifdef _DEBUG
1170                                    for (int j = input_conv_offset; j < input_conv_len; j++)
1171                                    {
1172                                            log_debug("input_conv: <--[%u]", (unsigned char)(input_conv[j]));
1173                                    }
1174    #endif
1175                            }
1176    
1177                            while (input_conv_offset < input_conv_len && !SYS_server_exit)
1178                            {
1179                                    if (bbsnet_conf[n].use_ssh)
1180                                    {
1181                                            ret = ssh_channel_write(outbound_channel, input_conv + input_conv_offset, (uint32_t)(input_conv_len - input_conv_offset));
1182                                            if (ret == SSH_ERROR)
1183                                            {
1184                                                    log_debug("ssh_channel_write() error: %s", ssh_get_error(outbound_session));
1185                                                    loop = 0;
1186                                                    break;
1187                                            }
1188                                    }
1189                                    else
1190                                    {
1191                                            ret = (int)write(sock, input_conv + input_conv_offset, (size_t)(input_conv_len - input_conv_offset));
1192                                    }
1193                                    if (ret < 0)
1194                                    {
1195                                            if (errno == EAGAIN || errno == EWOULDBLOCK)
1196                                            {
1197                                                    sock_write_wait = 0;
1198                                                    break;
1199                                            }
1200                                            else if (errno == EINTR)
1201                                            {
1202                                                    continue;
1203                                            }
1204                                            else
1205                                            {
1206                                                    log_debug("write(socket) error (%d)", errno);
1207                                                    loop = 0;
1208                                                    break;
1209                                            }
1210                                    }
1211                                    else if (ret == 0) // broken pipe
1212                                    {
1213                                            log_debug("write(socket) EOF");
1214                                            sock_write_wait = 0;
1215                                            loop = 0;
1216                                            break;
1217                                    }
1218                                    else
1219                                    {
1220                                            input_conv_offset += ret;
1221                                            if (input_conv_offset >= input_conv_len) // Output buffer complete
1222                                            {
1223                                                    input_conv_offset = 0;
1224                                                    input_conv_len = 0;
1225                                                    break;
1226                                            }
1227                                            continue;
1228                                    }
1229                            }
1230                    }
1231    
1232                    if (sock_read_wait)
1233                    {
1234                            while (output_buf_len < sizeof(output_buf) && !SYS_server_exit)
1235                            {
1236                                    if (bbsnet_conf[n].use_ssh)
1237                                    {
1238                                            ret = ssh_channel_read_nonblocking(outbound_channel, output_buf + output_buf_len,
1239                                                                                                               (uint32_t)(sizeof(output_buf) - (size_t)output_buf_len), 0);
1240                                            if (ret == SSH_ERROR)
1241                                            {
1242                                                    log_debug("ssh_channel_read_nonblocking() error: %s", ssh_get_error(outbound_session));
1243                                                    loop = 0;
1244                                                    break;
1245                                            }
1246                                            else if (ret == SSH_EOF)
1247                                            {
1248                                                    sock_read_wait = 0;
1249                                                    loop = 0;
1250                                                    break;
1251                                            }
1252                                            else if (ret == 0)
1253                                            {
1254                                                    sock_read_wait = 0;
1255                                                    break;
1256                                            }
1257                                    }
1258                                    else
1259                                    {
1260                                            ret = (int)read(sock, output_buf + output_buf_len, sizeof(output_buf) - (size_t)output_buf_len);
1261                                    }
1262                                    if (ret < 0)
1263                                    {
1264                                            if (errno == EAGAIN || errno == EWOULDBLOCK)
1265                                            {
1266                                                    sock_read_wait = 0;
1267                                                    break;
1268                                            }
1269                                            else if (errno == EINTR)
1270                                            {
1271                                                    continue;
1272                                            }
1273                                            else
1274                                            {
1275                                                    log_debug("read(socket) error (%d)", errno);
1276                                                    loop = 0;
1277                                                    break;
1278                                            }
1279                                    }
1280                                    else if (ret == 0) // broken pipe
1281                                    {
1282                                            log_debug("read(socket) EOF");
1283                                            sock_read_wait = 0;
1284                                            loop = 0;
1285                                            break;
1286                                    }
1287                                    else
1288                                    {
1289                                            output_buf_len += ret;
1290                                            continue;
1291                                    }
1292                            }
1293                    }
1294    
1295                    if (stdout_write_wait)
1296                    {
1297                            if (output_buf_offset < output_buf_len)
1298                            {
1299                                    ret = io_buf_conv(output_cd, output_buf, &output_buf_len, &output_buf_offset, output_conv, sizeof(output_conv), &output_conv_len);
1300                                    if (ret < 0)
1301                                    {
1302                                            log_error("io_buf_conv(output, %d, %d, %d) error", output_buf_len, output_buf_offset, output_conv_len);
1303                                            output_buf_len = output_buf_offset; // Discard invalid sequence
1304                                    }
1305                            }
1306    
1307                            while (output_conv_offset < output_conv_len && !SYS_server_exit)
1308                            {
1309                                    if (SSH_v2)
1310                                    {
1311                                            ret = ssh_channel_write(SSH_channel, output_conv + output_conv_offset, (uint32_t)(output_conv_len - output_conv_offset));
1312                                            if (ret == SSH_ERROR)
1313                                            {
1314                                                    log_debug("ssh_channel_write() error: %s", ssh_get_error(SSH_session));
1315                                                    loop = 0;
1316                                                    break;
1317                                            }
1318                                    }
1319                                    else
1320                                    {
1321                                            ret = (int)write(STDOUT_FILENO, output_conv + output_conv_offset, (size_t)(output_conv_len - output_conv_offset));
1322                                    }
1323                                    if (ret < 0)
1324                                    {
1325                                            if (errno == EAGAIN || errno == EWOULDBLOCK)
1326                                            {
1327                                                    stdout_write_wait = 0;
1328                                                    break;
1329                                            }
1330                                            else if (errno == EINTR)
1331                                            {
1332                                                    continue;
1333                                            }
1334                                            else
1335                                            {
1336                                                    log_debug("write(STDOUT) error (%d)", errno);
1337                                                    loop = 0;
1338                                                    break;
1339                                            }
1340                                    }
1341                                    else if (ret == 0) // broken pipe
1342                                    {
1343                                            log_debug("write(STDOUT) EOF");
1344                                            stdout_write_wait = 0;
1345                                            loop = 0;
1346                                            break;
1347                                    }
1348                                    else
1349                                    {
1350                                            output_conv_offset += ret;
1351                                            if (output_conv_offset >= output_conv_len) // Output buffer complete
1352                                            {
1353                                                    output_conv_offset = 0;
1354                                                    output_conv_len = 0;
1355                                                    break;
1356                                            }
1357                                            continue;
1358                                    }
1359                            }
1360                    }
1361            }
1362    
1363            ret = 1; // Normal disconnect
1364            BBS_last_access_tm = time(NULL);
1365            t_used = BBS_last_access_tm - t_begin;
1366            log_common("BBSNET disconnect, %ld days %ld hours %ld minutes %ld seconds used",
1367                               t_used / 86400, t_used % 86400 / 3600, t_used % 3600 / 60, t_used % 60);
1368    
1369    cleanup:
1370            // Clear sensitive data
1371            memset(remote_pass, 0, sizeof(remote_pass));
1372            memset(remote_user, 0, sizeof(remote_user));
1373    
1374            if (input_cd != (iconv_t)(-1) && iconv_close(input_cd) < 0)
1375            {
1376                    log_error("iconv_close(input) error (%d)", errno);
1377            }
1378            if (output_cd != (iconv_t)(-1) && iconv_close(output_cd) < 0)
1379            {
1380                    log_error("iconv_close(output) error (%d)", errno);
1381            }
1382    
1383    #ifdef HAVE_SYS_EPOLL_H
1384            if (epollfd != -1 && close(epollfd) < 0)
1385            {
1386                    log_error("close(epoll) error (%d)");
1387            }
1388    #endif
1389    
1390            if (bbsnet_conf[n].use_ssh)
1391            {
1392                    if (outbound_channel != NULL)
1393                    {
1394                            ssh_channel_send_eof(outbound_channel);
1395                            ssh_channel_close(outbound_channel);
1396                            ssh_channel_free(outbound_channel);
1397                    }
1398                    if (outbound_session != NULL)
1399                    {
1400                            ssh_disconnect(outbound_session);
1401                            ssh_free(outbound_session);
1402                    }
1403            }
1404    
1405            // Restore STDIN/STDOUT flags
1406            if (flags_stdin != -1 && fcntl(STDIN_FILENO, F_SETFL, flags_stdin) == -1)
1407            {
1408                    log_error("fcntl(F_SETFL) error (%d)", errno);
1409            }
1410            if (flags_stdout != -1 && fcntl(STDOUT_FILENO, F_SETFL, flags_stdout) == -1)
1411            {
1412                    log_error("fcntl(F_SETFL) error (%d)", errno);
1413            }
1414    
1415    t_used = time (0) - t_used;          if (sock != -1)
1416    tm_used = gmtime (&t_used);          {
1417                    close(sock);
1418            }
1419    
1420    log_std ("BBSNET disconnect, %d days %d hours %d minutes %d seconds used\n",          if (res)
1421      tm_used->tm_mday - 1, tm_used->tm_hour, tm_used->tm_min, tm_used->tm_sec);          {
1422                    freeaddrinfo(res);
1423            }
1424    
1425    return 0;          return ret;
1426  }  }
1427    
1428  static int  static int bbsnet_refresh()
 bbsnet_refresh ()  
1429  {  {
1430    int i;          clearscr();
1431    
1432    clearscr ();          moveto(1, 1);
1433    moveto (1, 0);          prints(" ------------------------------------------------------------------------------ ");
1434    prints          for (int i = 2; i < 19; i++)
1435      ("qTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTr");          {
1436    for (i = 2; i < 19; i++)                  moveto(i, 1);
1437      {                  prints("|");
1438        moveto (i, 0);                  moveto(i, 80);
1439        prints ("U");                  prints("|");
1440        moveto (i, 79);          }
1441        prints ("U");          moveto(19, 1);
1442      }          prints("|------------------------------------------------------------------------------|");
1443    moveto (19, 0);          moveto(22, 1);
1444    prints          prints(" ------------------------------------------------------------------------------ ");
1445      ("UU");          moveto(23, 1);
1446    moveto (22, 0);          prints(" [\033[1;32mCtrl+C\033[m]退出");
   prints  
     ("tTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTs");  
   moveto (23, 0);  
   prints (" [\x1b[1;32mCtrl+C\x1b[m]˳");  
   iflush ();  
1447    
1448    return 0;          iflush();
1449    
1450            return 0;
1451  }  }
1452    
1453  int  static int bbsnet_selchange()
 bbsnet_selchange (int new_pos)  
1454  {  {
1455    moveto (20, 0);          int i = bbsnet_menu.menu_item_pos[0];
1456    clrtoeol ();  
1457    prints ("U\x1b[1mλ:\x1b[1;33m%-18s\x1b[m  վ:\x1b[1;33m%s\x1b[m",          moveto(20, 1);
1458            bbsnet_conf[new_pos].host2, bbsnet_conf[new_pos].host1);          clrtoeol();
1459    moveto (20, 79);          prints("|\033[1m单位: \033[1;33m%s\033[m%*s  站名: \033[1;33m%s\033[m%*s  类型: \033[1;33m%s\033[m",
1460    prints ("U");                     bbsnet_conf[i].org_name, 20 - str_length(bbsnet_conf[i].org_name, 1), "",
1461    moveto (21, 0);                     bbsnet_conf[i].site_name, 20 - str_length(bbsnet_conf[i].site_name, 1), "",
1462    clrtoeol ();                     (bbsnet_conf[i].use_ssh ? "SSH" : "Telnet"));
1463    prints ("U\x1b[1m:\x1b[1;33m%-20s", bbsnet_conf[new_pos].ip);          moveto(20, 80);
1464    if (bbsnet_conf[new_pos].port != 23)          prints("|");
1465      prints ("  %d", bbsnet_conf[new_pos].port);          moveto(21, 1);
1466    prints ("\x1b[m");          clrtoeol();
1467    moveto (21, 79);          prints("|\033[1m连往: \033[1;33m%-20s\033[m  端口: \033[1;33m%-5s\033[m                 编码: \033[1;33m%s\033[m",
1468    prints ("U");                     bbsnet_conf[i].host_name, bbsnet_conf[i].port, bbsnet_conf[i].charset);
1469    iflush ();          moveto(21, 80);
1470            prints("|");
1471            iflush();
1472    
1473    return 0;          return 0;
1474  }  }
1475    
1476  int  int bbs_net()
 bbs_net ()  
1477  {  {
1478    int ch, pos, i;          int ch;
   char file_config[256];  
1479    
1480    strcpy (file_config, app_home_dir);          if (load_bbsnet_conf(CONF_BBSNET) < 0)
1481    strcat (file_config, "conf/bbsnet.conf");          {
1482                    clearscr();
1483                    moveto(1, 1);
1484                    prints("加载穿梭配置失败!");
1485                    press_any_key();
1486                    return -1;
1487            }
1488    
1489            bbsnet_refresh();
1490            display_menu(&bbsnet_menu);
1491            bbsnet_selchange();
1492    
1493            while (!SYS_server_exit)
1494            {
1495                    ch = igetch(100);
1496    
1497    load_bbsnet_conf (file_config);                  if (ch != KEY_NULL && ch != KEY_TIMEOUT)
1498                    {
1499                            BBS_last_access_tm = time(NULL);
1500                    }
1501    
1502    BBS_last_access_tm = time (0);                  switch (ch)
1503                    {
1504    clearscr ();                  case KEY_NULL: // broken pipe
1505    bbsnet_refresh ();                          log_debug("KEY_NULL");
1506    pos = bbsnet_menu.p_menu[0]->item_cur_pos;                          goto cleanup;
1507    display_menu (get_menu (&bbsnet_menu, "BBSNET"));                  case KEY_TIMEOUT:
1508    bbsnet_selchange (pos);                          if (time(NULL) - BBS_last_access_tm >= BBS_max_user_idle_time)
1509                            {
1510    while (1)                                  log_debug("User input timeout");
1511      {                                  goto cleanup;
1512        ch = igetch ();                          }
1513        switch (ch)                          continue;
1514          {                  case KEY_ESC:
1515          case KEY_NULL:                  case Ctrl('C'): // user cancel
1516          case Ctrl ('C'):                          goto cleanup;
1517            return 0;                  case CR:
1518          case KEY_TIMEOUT:                          if (bbsnet_connect(bbsnet_menu.menu_item_pos[0]) < 0)
1519            if (time (0) - BBS_last_access_tm >= MAX_DELAY_TIME)                          {
1520              {                                  log_debug("bbsnet_connect() error");
1521                return -1;                          }
1522              }                          // Force cleanup anything remaining in the output buffer
1523            continue;                          clearscr();
1524          case CR:                          iflush();
1525            pos = bbsnet_menu.p_menu[0]->item_cur_pos;                          // Clear screen and redraw menu
1526            bbsnet_connect (pos);                          bbsnet_refresh();
1527            bbsnet_refresh ();                          display_menu(&bbsnet_menu);
1528            display_current_menu (&bbsnet_menu);                          bbsnet_selchange();
1529            bbsnet_selchange (pos);                          break;
1530            break;                  case KEY_UP:
1531          case KEY_UP:                          for (int i = 0; i < STATION_PER_LINE; i++)
1532            for (i = 0; i < STATION_PER_LINE; i++)                          {
1533              menu_control (&bbsnet_menu, KEY_UP);                                  menu_control(&bbsnet_menu, KEY_UP);
1534            pos = bbsnet_menu.p_menu[0]->item_cur_pos;                          }
1535            bbsnet_selchange (pos);                          bbsnet_selchange();
1536            break;                          break;
1537          case KEY_DOWN:                  case KEY_DOWN:
1538            for (i = 0; i < STATION_PER_LINE; i++)                          for (int i = 0; i < STATION_PER_LINE; i++)
1539              menu_control (&bbsnet_menu, KEY_DOWN);                          {
1540            pos = bbsnet_menu.p_menu[0]->item_cur_pos;                                  menu_control(&bbsnet_menu, KEY_DOWN);
1541            bbsnet_selchange (pos);                          }
1542            break;                          bbsnet_selchange();
1543          case KEY_LEFT:                          break;
1544            menu_control (&bbsnet_menu, KEY_UP);                  case KEY_LEFT:
1545            pos = bbsnet_menu.p_menu[0]->item_cur_pos;                          menu_control(&bbsnet_menu, KEY_UP);
1546            bbsnet_selchange (pos);                          bbsnet_selchange();
1547            break;                          break;
1548          case KEY_RIGHT:                  case KEY_RIGHT:
1549            menu_control (&bbsnet_menu, KEY_DOWN);                          menu_control(&bbsnet_menu, KEY_DOWN);
1550            pos = bbsnet_menu.p_menu[0]->item_cur_pos;                          bbsnet_selchange();
1551            bbsnet_selchange (pos);                          break;
1552            break;                  case KEY_HOME:
1553          default:                  case KEY_PGUP:
1554            menu_control (&bbsnet_menu, ch);                          menu_control(&bbsnet_menu, KEY_PGUP);
1555            pos = bbsnet_menu.p_menu[0]->item_cur_pos;                          bbsnet_selchange();
1556            bbsnet_selchange (pos);                          break;
1557            break;                  case KEY_END:
1558                    case KEY_PGDN:
1559                            menu_control(&bbsnet_menu, KEY_PGDN);
1560                            bbsnet_selchange();
1561                            break;
1562                    default:
1563                            menu_control(&bbsnet_menu, ch);
1564                            bbsnet_selchange();
1565                            break;
1566                    }
1567          }          }
       BBS_last_access_tm = time (0);  
     }  
1568    
1569    return 0;  cleanup:
1570            unload_bbsnet_conf();
1571    
1572            return 0;
1573  }  }


Legend:
Removed lines/characters  
Changed lines/characters
  Added lines/characters

webmaster@leafok.com
ViewVC Help
Powered by ViewVC 1.3.0-beta1