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


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

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