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

Diff of /lbbs/src/net_server.c

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

Revision 1.13 by sysadm, Mon Apr 28 03:31:00 2025 UTC Revision 1.69 by sysadm, Sun Jun 29 02:28:02 2025 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2                                                    net_server.c  -  description                                                    net_server.c  -  description
3                                                           -------------------                                                           -------------------
4          begin                : Mon Oct 11 2004          Copyright            : (C) 2004-2025 by Leaflet
5          copyright            : (C) 2004 by Leaflet          Email                : leaflet@leafok.com
         email                : leaflet@leafok.com  
6   ***************************************************************************/   ***************************************************************************/
7    
8  /***************************************************************************  /***************************************************************************
9   *                                                                         *   *                                                                         *
10   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
11   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
12   *   the Free Software Foundation; either version 2 of the License, or     *   *   the Free Software Foundation; either version 3 of the License, or     *
13   *   (at your option) any later version.                                   *   *   (at your option) any later version.                                   *
14   *                                                                         *   *                                                                         *
15   ***************************************************************************/   ***************************************************************************/
16    
17    #include "bbs.h"
18    #include "bbs_main.h"
19  #include "common.h"  #include "common.h"
20    #include "database.h"
21    #include "file_loader.h"
22  #include "io.h"  #include "io.h"
23  #include "tcplib.h"  #include "init.h"
24  #include <sys/socket.h>  #include "log.h"
25  #include <netinet/in.h>  #include "login.h"
26    #include "menu.h"
27    #include "net_server.h"
28    #include "section_list.h"
29    #include "section_list_loader.h"
30    #include <errno.h>
31    #include <fcntl.h>
32    #include <signal.h>
33    #include <stdlib.h>
34    #include <string.h>
35    #include <unistd.h>
36  #include <arpa/inet.h>  #include <arpa/inet.h>
37    #include <libssh/callbacks.h>
38    #include <libssh/libssh.h>
39    #include <libssh/server.h>
40    #include <netinet/in.h>
41    #include <sys/epoll.h>
42    #include <sys/socket.h>
43    #include <sys/syscall.h>
44    #include <sys/types.h>
45    #include <sys/wait.h>
46    #include <systemd/sd-daemon.h>
47    
48  int net_server(const char *hostaddr, unsigned int port)  struct process_sockaddr_t
49  {  {
50          int namelen, seq, netint, result, flags;          pid_t pid;
51          struct sockaddr_in sin;          in_addr_t s_addr;
52          char temp[256];  };
53          fd_set testfds;  typedef struct process_sockaddr_t PROCESS_SOCKADDR;
54          struct timeval timeout;  
55    static PROCESS_SOCKADDR process_sockaddr_pool[MAX_CLIENT_LIMIT];
56    
57          socket_server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  #define SSH_AUTH_MAX_DURATION (60 * 1000) // milliseconds
58    
59          if (socket_server < 0)  struct ssl_server_cb_data_t
60    {
61            int tries;
62            int error;
63    };
64    
65    static int auth_password(ssh_session session, const char *user,
66                                                     const char *password, void *userdata)
67    {
68            struct ssl_server_cb_data_t *p_data = userdata;
69            int ret;
70    
71            if (strcmp(user, "guest") == 0)
72          {          {
73                  log_error("Create socket failed\n");                  ret = load_guest_info();
74                  exit(1);          }
75            else
76            {
77                    ret = check_user(user, password);
78          }          }
79    
80          sin.sin_family = AF_INET;          if (ret == 0)
81          sin.sin_addr.s_addr =          {
82                  (strlen(hostaddr) > 0 ? inet_addr(hostaddr) : INADDR_ANY);                  return SSH_AUTH_SUCCESS;
83          sin.sin_port = htons(port);          }
84    
85          if (bind(socket_server, (struct sockaddr *)&sin, sizeof(sin)) < 0)          if ((++(p_data->tries)) >= BBS_login_retry_times)
86          {          {
87                  log_error("Bind address %s:%u failed\n",                  p_data->error = 1;
                                   inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));  
                 exit(2);  
88          }          }
89    
90          if (listen(socket_server, 10) < 0)          return SSH_AUTH_DENIED;
91    }
92    
93    static int pty_request(ssh_session session, ssh_channel channel, const char *term,
94                                               int x, int y, int px, int py, void *userdata)
95    {
96            return 0;
97    }
98    
99    static int shell_request(ssh_session session, ssh_channel channel, void *userdata)
100    {
101            return 0;
102    }
103    
104    static struct ssh_channel_callbacks_struct channel_cb = {
105            .channel_pty_request_function = pty_request,
106            .channel_shell_request_function = shell_request};
107    
108    static ssh_channel new_session_channel(ssh_session session, void *userdata)
109    {
110            if (SSH_channel != NULL)
111          {          {
112                  log_error("Socket listen failed\n");                  return NULL;
                 exit(3);  
113          }          }
114    
115          strcpy(hostaddr_server, inet_ntoa(sin.sin_addr));          SSH_channel = ssh_channel_new(session);
116          port_server = ntohs(sin.sin_port);          ssh_callbacks_init(&channel_cb);
117            ssh_set_channel_callbacks(SSH_channel, &channel_cb);
118    
119            return SSH_channel;
120    }
121    
122    static int fork_server(void)
123    {
124            ssh_event event;
125            int pid;
126            int i;
127            int ret;
128    
129            struct ssl_server_cb_data_t cb_data = {
130                    .tries = 0,
131                    .error = 0,
132            };
133    
134            struct ssh_server_callbacks_struct cb = {
135                    .userdata = &cb_data,
136                    .auth_password_function = auth_password,
137                    .channel_open_request_session_function = new_session_channel,
138            };
139    
140            pid = fork();
141    
142          log_std("Listening at %s:%d\n", hostaddr_server, port_server);          if (pid > 0) // Parent process
143            {
144                    SYS_child_process_count++;
145                    log_common("Child process (%d) start\n", pid);
146                    return pid;
147            }
148            else if (pid < 0) // Error
149            {
150                    log_error("fork() error (%d)\n", errno);
151                    return -1;
152            }
153    
154            // Child process
155    
156          namelen = sizeof(sin);          if (close(socket_server[0]) == -1 || close(socket_server[1]) == -1)
         while (!SYS_exit)  
157          {          {
158                  FD_ZERO(&testfds);                  log_error("Close server socket failed\n");
159                  FD_SET(socket_server, &testfds);          }
160    
161                  timeout.tv_sec = 1;          SSH_session = ssh_new();
                 timeout.tv_usec = 0;  
162    
163                  result = SignalSafeSelect(FD_SETSIZE, &testfds, NULL, NULL, &timeout);          if (SSH_v2)
164                  if (result < 0)          {
165                    if (ssh_bind_accept_fd(sshbind, SSH_session, socket_client) != SSH_OK)
166                  {                  {
167                          log_error("Accept connection error\n");                          log_error("ssh_bind_accept_fd() error: %s\n", ssh_get_error(SSH_session));
168                          continue;                          goto cleanup;
169                    }
170    
171                    ssh_bind_free(sshbind);
172    
173                    ssh_callbacks_init(&cb);
174                    ssh_set_server_callbacks(SSH_session, &cb);
175    
176                    if (ssh_handle_key_exchange(SSH_session))
177                    {
178                            log_error("ssh_handle_key_exchange() error: %s\n", ssh_get_error(SSH_session));
179                            goto cleanup;
180                  }                  }
181                    ssh_set_auth_methods(SSH_session, SSH_AUTH_METHOD_PASSWORD);
182    
183                    event = ssh_event_new();
184                    ssh_event_add_session(event, SSH_session);
185    
186                  if (result == 0)                  for (i = 0; i < SSH_AUTH_MAX_DURATION && !SYS_server_exit && !cb_data.error && SSH_channel == NULL; i += 100)
187                  {                  {
188                          continue;                          ret = ssh_event_dopoll(event, 100); // 0.1 second
189                            if (ret == SSH_ERROR)
190                            {
191                                    log_error("ssh_event_dopoll() error: %s\n", ssh_get_error(SSH_session));
192                                    goto cleanup;
193                            }
194                    }
195    
196                    if (cb_data.error)
197                    {
198                            log_error("SSH auth error, tried %d times\n", cb_data.tries);
199                            goto cleanup;
200                    }
201            }
202    
203            // Redirect Input
204            close(STDIN_FILENO);
205            if (dup2(socket_client, STDIN_FILENO) == -1)
206            {
207                    log_error("Redirect stdin to client socket failed\n");
208                    goto cleanup;
209            }
210    
211            // Redirect Output
212            close(STDOUT_FILENO);
213            if (dup2(socket_client, STDOUT_FILENO) == -1)
214            {
215                    log_error("Redirect stdout to client socket failed\n");
216                    goto cleanup;
217            }
218    
219            SYS_child_process_count = 0;
220    
221            bbs_main();
222    
223    cleanup:
224            // Child process exit
225            SYS_server_exit = 1;
226    
227            if (SSH_v2)
228            {
229                    ssh_channel_free(SSH_channel);
230                    ssh_disconnect(SSH_session);
231            }
232            else if (close(socket_client) == -1)
233            {
234                    log_error("Close client socket failed\n");
235            }
236    
237            ssh_free(SSH_session);
238            ssh_finalize();
239    
240            // Close Input and Output for client
241            close(STDIN_FILENO);
242            close(STDOUT_FILENO);
243    
244            log_common("Process exit normally\n");
245            log_end();
246    
247            _exit(0);
248    
249            return 0;
250    }
251    
252    int net_server(const char *hostaddr, in_port_t port[])
253    {
254            unsigned int addrlen;
255            int ret;
256            int flags[2];
257            struct sockaddr_in sin;
258            struct epoll_event ev, events[MAX_EVENTS];
259            int nfds, epollfd;
260            siginfo_t siginfo;
261            int sd_notify_stopping = 0;
262            MENU_SET bbs_menu_new;
263            int i, j;
264            pid_t pid;
265            int ssh_log_level = SSH_LOG_NOLOG;
266    
267            ssh_init();
268    
269            sshbind = ssh_bind_new();
270    
271            if (ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDADDR, hostaddr) < 0 ||
272                    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDPORT, &port) < 0 ||
273                    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_HOSTKEY, SSH_HOST_KEYFILE) < 0 ||
274                    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, "ssh-rsa,rsa-sha2-512,rsa-sha2-256") < 0 ||
275                    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_LOG_VERBOSITY, &ssh_log_level) < 0)
276            {
277                    log_error("Error setting SSH bind options: %s\n", ssh_get_error(sshbind));
278                    ssh_bind_free(sshbind);
279                    return -1;
280            }
281    
282            epollfd = epoll_create1(0);
283            if (epollfd < 0)
284            {
285                    log_error("epoll_create1() error (%d)\n", errno);
286                    return -1;
287            }
288    
289            // Server socket
290            for (i = 0; i < 2; i++)
291            {
292                    socket_server[i] = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
293    
294                    if (socket_server[i] < 0)
295                    {
296                            log_error("Create socket_server error (%d)\n", errno);
297                            return -1;
298                  }                  }
299    
300                  if (FD_ISSET(socket_server, &testfds))                  sin.sin_family = AF_INET;
301                    sin.sin_addr.s_addr = (hostaddr[0] != '\0' ? inet_addr(hostaddr) : INADDR_ANY);
302                    sin.sin_port = htons(port[i]);
303    
304                    // Reuse address and port
305                    flags[i] = 1;
306                    if (setsockopt(socket_server[i], SOL_SOCKET, SO_REUSEADDR, &flags[i], sizeof(flags[i])) < 0)
307                  {                  {
308                          flags = fcntl(socket_server, F_GETFL, 0);                          log_error("setsockopt SO_REUSEADDR error (%d)\n", errno);
309                          fcntl(socket_server, F_SETFL, flags | O_NONBLOCK);                  }
310                          while ((socket_client =                  if (setsockopt(socket_server[i], SOL_SOCKET, SO_REUSEPORT, &flags[i], sizeof(flags[i])) < 0)
311                                                  accept(socket_server, (struct sockaddr *)&sin, &namelen)) < 0)                  {
312                            log_error("setsockopt SO_REUSEPORT error (%d)\n", errno);
313                    }
314    
315                    if (bind(socket_server[i], (struct sockaddr *)&sin, sizeof(sin)) < 0)
316                    {
317                            log_error("Bind address %s:%u error (%d)\n",
318                                              inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), errno);
319                            return -1;
320                    }
321    
322                    if (listen(socket_server[i], 10) < 0)
323                    {
324                            log_error("Telnet socket listen error (%d)\n", errno);
325                            return -1;
326                    }
327    
328                    log_common("Listening at %s:%u\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
329    
330                    ev.events = EPOLLIN;
331                    ev.data.fd = socket_server[i];
332                    if (epoll_ctl(epollfd, EPOLL_CTL_ADD, socket_server[i], &ev) == -1)
333                    {
334                            log_error("epoll_ctl(socket_server[%d]) error (%d)\n", i, errno);
335                            if (close(epollfd) < 0)
336                          {                          {
337                                  if (errno != EWOULDBLOCK && errno != ECONNABORTED && errno != EINTR)                                  log_error("close(epoll) error (%d)\n");
338                            }
339                            return -1;
340                    }
341    
342                    flags[i] = fcntl(socket_server[i], F_GETFL, 0);
343                    fcntl(socket_server[i], F_SETFL, flags[i] | O_NONBLOCK);
344            }
345    
346            // Startup complete
347            sd_notifyf(0, "READY=1\n"
348                                      "STATUS=Listening at %s:%d (Telnet) and %s:%d (SSH2)\n"
349                                      "MAINPID=%d",
350                               hostaddr, port[0], hostaddr, port[1], getpid());
351    
352            while (!SYS_server_exit || SYS_child_process_count > 0)
353            {
354                    if (SYS_server_exit && !sd_notify_stopping)
355                    {
356                            sd_notify(0, "STOPPING=1");
357                            sd_notify_stopping = 1;
358                    }
359    
360                    while ((SYS_child_exit || SYS_server_exit) && SYS_child_process_count > 0)
361                    {
362                            SYS_child_exit = 0;
363    
364                            siginfo.si_pid = 0;
365                            ret = waitid(P_ALL, 0, &siginfo, WEXITED | WNOHANG);
366                            if (ret == 0 && siginfo.si_pid > 0)
367                            {
368                                    SYS_child_exit = 1; // Retry waitid
369    
370                                    SYS_child_process_count--;
371                                    log_common("Child process (%d) exited\n", siginfo.si_pid);
372    
373                                    if (siginfo.si_pid != section_list_loader_pid)
374                                  {                                  {
375                                          log_error("Accept connection error\n");                                          i = 0;
376                                          break;                                          for (; i < BBS_max_client; i++)
377                                            {
378                                                    if (process_sockaddr_pool[i].pid == siginfo.si_pid)
379                                                    {
380                                                            process_sockaddr_pool[i].pid = 0;
381                                                            break;
382                                                    }
383                                            }
384                                            if (i >= BBS_max_client)
385                                            {
386                                                    log_error("Child process (%d) not found in process sockaddr pool\n", siginfo.si_pid);
387                                            }
388                                  }                                  }
389                          }                          }
390                          fcntl(socket_server, F_SETFL, flags);                          else if (ret == 0)
391                            {
392                                    break;
393                            }
394                            else if (ret < 0)
395                            {
396                                    log_error("Error in waitid: %d\n", errno);
397                                    break;
398                            }
399                  }                  }
400    
401                  if (socket_client < 0)                  if (SYS_server_exit && !SYS_child_exit && SYS_child_process_count > 0)
402                  {                  {
403                          log_error("Accept connection error\n");                          log_common("Notify %d child process to exit\n", SYS_child_process_count);
404                          continue;                          if (kill(0, SIGTERM) < 0)
405                            {
406                                    log_error("Send SIGTERM signal failed (%d)\n", errno);
407                            }
408    
409                            sd_notifyf(0, "STATUS=Waiting for %d child process to exit", SYS_child_process_count);
410    
411                            sleep(1); // Sleep for a while to avoid notifying child processes too frequently
412                  }                  }
413    
414                  strcpy(hostaddr_client, (const char *)inet_ntoa(sin.sin_addr));                  if (SYS_conf_reload && !SYS_server_exit)
415                  port_client = ntohs(sin.sin_port);                  {
416                            SYS_conf_reload = 0;
417                            sd_notify(0, "RELOADING=1");
418    
419                            // Reload configuration
420                            if (load_conf(CONF_BBSD) < 0)
421                            {
422                                    log_error("Reload conf failed\n");
423                            }
424    
425                            if (load_menu(&bbs_menu_new, CONF_MENU) < 0)
426                            {
427                                    unload_menu(&bbs_menu_new);
428                                    log_error("Reload menu failed\n");
429                            }
430                            else
431                            {
432                                    unload_menu(&bbs_menu);
433                                    memcpy(&bbs_menu, &bbs_menu_new, sizeof(bbs_menu_new));
434                                    log_common("Reload menu successfully\n");
435                            }
436    
437                            for (int i = 0; i < data_files_load_startup_count; i++)
438                            {
439                                    if (load_file(data_files_load_startup[i]) < 0)
440                                    {
441                                            log_error("load_file_mmap(%s) error\n", data_files_load_startup[i]);
442                                    }
443                            }
444                            log_common("Reload data files successfully\n");
445    
446                            // Load section config and gen_ex
447                            if (load_section_config_from_db(1) < 0)
448                            {
449                                    log_error("load_section_config_from_db(1) error\n");
450                            }
451                            else
452                            {
453                                    log_common("Reload section config and gen_ex successfully\n");
454                            }
455    
456                            sd_notify(0, "READY=1");
457                    }
458    
459                  log_std("Accept connection from %s:%d\n", hostaddr_client,                  nfds = epoll_wait(epollfd, events, MAX_EVENTS, 100); // 0.1 second
                                 port_client);  
460    
461                  if (fork_server() < 0)                  if (nfds < 0)
462                  {                  {
463                          log_error("Fork error\n");                          if (errno != EINTR)
464                            {
465                                    log_error("epoll_wait() error (%d)\n", errno);
466                                    break;
467                            }
468                            continue;
469                    }
470    
471                    // Stop accept new connection on exit
472                    if (SYS_server_exit)
473                    {
474                            continue;
475                  }                  }
476    
477                  if (close(socket_client) == -1)                  for (int i = 0; i < nfds; i++)
478                  {                  {
479                          log_error("Close client socket failed\n");                          if (events[i].data.fd == socket_server[0] || events[i].data.fd == socket_server[1])
480                            {
481                                    SSH_v2 = (events[i].data.fd == socket_server[1] ? 1 : 0);
482    
483                                    while (!SYS_server_exit) // Accept all incoming connections until error
484                                    {
485                                            addrlen = sizeof(sin);
486                                            socket_client = accept(socket_server[SSH_v2], (struct sockaddr *)&sin, &addrlen);
487                                            if (socket_client < 0)
488                                            {
489                                                    if (errno == EAGAIN || errno == EWOULDBLOCK)
490                                                    {
491                                                            break;
492                                                    }
493                                                    else if (errno == EINTR)
494                                                    {
495                                                            continue;
496                                                    }
497                                                    else
498                                                    {
499                                                            log_error("accept(socket_server) error (%d)\n", errno);
500                                                            break;
501                                                    }
502                                            }
503    
504                                            strncpy(hostaddr_client, inet_ntoa(sin.sin_addr), sizeof(hostaddr_client) - 1);
505                                            hostaddr_client[sizeof(hostaddr_client) - 1] = '\0';
506    
507                                            port_client = ntohs(sin.sin_port);
508    
509                                            log_common("Accept %s connection from %s:%d\n", (SSH_v2 ? "SSH" : "telnet"), hostaddr_client, port_client);
510    
511                                            if (SYS_child_process_count - 1 < BBS_max_client)
512                                            {
513                                                    j = 0;
514                                                    for (i = 0; i < BBS_max_client; i++)
515                                                    {
516                                                            if (process_sockaddr_pool[i].pid != 0 && process_sockaddr_pool[i].s_addr == sin.sin_addr.s_addr)
517                                                            {
518                                                                    j++;
519                                                                    if (j >= BBS_max_client_per_ip)
520                                                                    {
521                                                                            log_common("Too many client connections (%d) from %s\n", j, hostaddr_client);
522                                                                            break;
523                                                                    }
524                                                            }
525                                                    }
526    
527                                                    if (j < BBS_max_client_per_ip)
528                                                    {
529                                                            if ((pid = fork_server()) < 0)
530                                                            {
531                                                                    log_error("fork_server() error\n");
532                                                            }
533                                                            else if (pid > 0)
534                                                            {
535                                                                    i = 0;
536                                                                    for (; i < BBS_max_client; i++)
537                                                                    {
538                                                                            if (process_sockaddr_pool[i].pid == 0)
539                                                                            {
540                                                                                    break;
541                                                                            }
542                                                                    }
543    
544                                                                    if (i >= BBS_max_client)
545                                                                    {
546                                                                            log_error("Process sockaddr pool depleted\n");
547                                                                    }
548                                                                    else
549                                                                    {
550                                                                            process_sockaddr_pool[i].pid = pid;
551                                                                            process_sockaddr_pool[i].s_addr = sin.sin_addr.s_addr;
552                                                                    }
553                                                            }
554                                                    }
555                                            }
556                                            else
557                                            {
558                                                    log_error("Rejected client connection over limit (%d)\n", SYS_child_process_count - 1);
559                                            }
560    
561                                            if (close(socket_client) == -1)
562                                            {
563                                                    log_error("close(socket_lient) error (%d)\n", errno);
564                                            }
565                                    }
566                            }
567                  }                  }
568          }          }
569    
570          if (close(socket_server) == -1)          if (close(epollfd) < 0)
571          {          {
572                  log_error("Close server socket failed\n");                  log_error("close(epoll) error (%d)\n");
573            }
574    
575            for (i = 0; i < 2; i++)
576            {
577                    fcntl(socket_server[i], F_SETFL, flags[i]);
578    
579                    if (close(socket_server[i]) == -1)
580                    {
581                            log_error("Close server socket failed\n");
582                    }
583          }          }
584    
585            ssh_bind_free(sshbind);
586            ssh_finalize();
587    
588          return 0;          return 0;
589  }  }


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

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