/[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.6 by sysadm, Thu Oct 21 17:28:46 2004 UTC Revision 1.100 by sysadm, Tue Dec 2 08:04:29 2025 UTC
# Line 1  Line 1 
1  /***************************************************************************  /* SPDX-License-Identifier: GPL-3.0-or-later */
2                            net_server.c  -  description  /*
3                               -------------------   * net_server
4      begin                : Mon Oct 11 2004   *   - network server with SSH support
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
12   *   it under the terms of the GNU General Public License as published by  *  
13   *   the Free Software Foundation; either version 2 of the License, or     *  #include "bbs.h"
14   *   (at your option) any later version.                                   *  #include "bbs_main.h"
15   *                                                                         *  #include "bwf.h"
  ***************************************************************************/  
   
16  #include "common.h"  #include "common.h"
17    #include "database.h"
18    #include "file_loader.h"
19    #include "hash_dict.h"
20    #include "io.h"
21    #include "init.h"
22    #include "log.h"
23    #include "login.h"
24    #include "menu.h"
25    #include "net_server.h"
26    #include "section_list.h"
27    #include "section_list_loader.h"
28    #include <errno.h>
29    #include <fcntl.h>
30    #include <pty.h>
31    #include <signal.h>
32    #include <stdlib.h>
33    #include <string.h>
34    #include <unistd.h>
35    #include <utmp.h>
36    #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/ioctl.h>
42    #include <sys/socket.h>
43    #include <sys/stat.h>
44    #include <sys/types.h>
45    #include <sys/wait.h>
46    
47    #ifdef HAVE_SYS_EPOLL_H
48    #include <sys/epoll.h>
49    #else
50    #include <poll.h>
51    #endif
52    
53    #ifdef HAVE_SYSTEMD_SD_DAEMON_H
54    #include <systemd/sd-daemon.h>
55    #endif
56    
57  int  enum _net_server_constant_t
 net_server (const char *hostaddr, unsigned int port)  
58  {  {
59    int sock_server, sock_client, namelen, seq, netint;          WAIT_CHILD_PROCESS_EXIT_TIMEOUT = 5, // second
60    struct sockaddr_in sin;          WAIT_CHILD_PROCESS_KILL_TIMEOUT = 1, // second
61    char temp[256];  
62            SSH_AUTH_MAX_DURATION = 60 * 1000, // milliseconds
63    sock_server = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);  };
64    
65    if (sock_server < 0)  /* A userdata struct for session. */
66      {  struct session_data_struct
67        log_error ("Create socket failed\n");  {
68        exit (1);          int tries;
69      }          int error;
70    };
71    sin.sin_family = AF_INET;  
72    sin.sin_addr.s_addr =  /* A userdata struct for channel. */
73      (strlen (hostaddr) > 0 ? inet_addr (hostaddr) : INADDR_ANY);  struct channel_data_struct
74    sin.sin_port = htons (port);  {
75            /* pid of the child process the channel will spawn. */
76    if (bind (sock_server, (struct sockaddr *)&sin, sizeof(sin)) < 0)          pid_t pid;
77      {          /* For PTY allocation */
78        sprintf(temp, "Bind address %s:%u failed\n",          socket_t pty_master;
79          inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));          socket_t pty_slave;
80        log_error (temp);          /* For communication with the child process. */
81        exit (2);          socket_t child_stdin;
82      }          socket_t child_stdout;
83            /* Only used for subsystem and exec requests. */
84    if (listen (sock_server, 10) < 0)          socket_t child_stderr;
85      {          /* Event which is used to poll the above descriptors. */
86        log_error ("Socket listen failed\n");          ssh_event event;
87        exit (3);          /* Terminal size struct. */
88      }          struct winsize *winsize;
89    };
90    socket_server = sock_server;  
91    strcpy(hostaddr_server,(const char *)inet_ntoa(sin.sin_addr));  static int socket_server[2];
92    port_server = ntohs(sin.sin_port);  static int socket_client;
93      
94    sprintf(temp, "Listening at %s:%d\n",  #ifdef HAVE_SYS_EPOLL_H
95      hostaddr_server, port_server);  static int epollfd_server = -1;
96    log_std (temp);  #endif
97    
98    namelen = sizeof (sin);  static ssh_bind sshbind;
99    while(1)  
100      {  static HASH_DICT *hash_dict_pid_sockaddr = NULL;
101        if ((sock_client = accept (sock_server, (struct sockaddr *) &sin, &namelen)) < 0)  static HASH_DICT *hash_dict_sockaddr_count = NULL;
102          {  
103            log_error ("Accept connection error\n");  static const char SFTP_SERVER_PATH[] = "/usr/lib/sftp-server";
104          }  
105        else  static int auth_password(ssh_session session, const char *user,
106          {                                                   const char *password, void *userdata)
107            sprintf(temp, "Accept connection from %s:%d\n",  {
108              inet_ntoa(sin.sin_addr),ntohs(sin.sin_port));          struct session_data_struct *sdata = (struct session_data_struct *)userdata;
109            log_std (temp);          int ret;
110          }  
111                  if (strcmp(user, "guest") == 0)
112        if (fork_server(sock_server, sock_client, &sin)<0)          {
113          {                  ret = load_guest_info();
114            log_error ("Fork error\n");          }
115          }          else
116                  {
117        if (close(sock_client) == -1)                  ret = check_user(user, password);
118          {          }
119            log_error("Close client socket failed\n");  
120          }          if (ret == 0)
121      }          {
122                    return SSH_AUTH_SUCCESS;
123            }
124    
125            if ((++(sdata->tries)) >= BBS_login_retry_times)
126            {
127                    sdata->error = 1;
128            }
129    
130            return SSH_AUTH_DENIED;
131    }
132    
133    static int pty_request(ssh_session session, ssh_channel channel, const char *term,
134                                               int cols, int rows, int px, int py, void *userdata)
135    {
136            struct channel_data_struct *cdata = (struct channel_data_struct *)userdata;
137            int rc;
138    
139            (void)session;
140            (void)channel;
141            (void)term;
142    
143            cdata->winsize->ws_row = (unsigned short int)rows;
144            cdata->winsize->ws_col = (unsigned short int)cols;
145            cdata->winsize->ws_xpixel = (unsigned short int)px;
146            cdata->winsize->ws_ypixel = (unsigned short int)py;
147    
148            rc = openpty(&cdata->pty_master, &cdata->pty_slave, NULL, NULL, cdata->winsize);
149            if (rc != 0)
150            {
151                    log_error("Failed to open pty\n");
152                    return SSH_ERROR;
153            }
154    
155            return SSH_OK;
156    }
157    
158    static int pty_resize(ssh_session session, ssh_channel channel, int cols, int rows,
159                                              int py, int px, void *userdata)
160    {
161            struct channel_data_struct *cdata = (struct channel_data_struct *)userdata;
162    
163            (void)session;
164            (void)channel;
165    
166            cdata->winsize->ws_row = (unsigned short int)rows;
167            cdata->winsize->ws_col = (unsigned short int)cols;
168            cdata->winsize->ws_xpixel = (unsigned short int)px;
169            cdata->winsize->ws_ypixel = (unsigned short int)py;
170    
171            if (cdata->pty_master != -1)
172            {
173                    return ioctl(cdata->pty_master, TIOCSWINSZ, cdata->winsize);
174            }
175    
176            return SSH_ERROR;
177    }
178    
179    static int exec_pty(const char *mode, const char *command, struct channel_data_struct *cdata)
180    {
181            (void)cdata;
182    
183            if (command != NULL)
184            {
185                    log_error("Forbid exec /bin/sh %s %s)\n", mode, command);
186            }
187    
188            return SSH_OK;
189    }
190    
191    static int exec_nopty(const char *command, struct channel_data_struct *cdata)
192    {
193            (void)cdata;
194    
195            if (command != NULL)
196            {
197                    log_error("Forbid exec /bin/sh -c %s)\n", command);
198            }
199    
200            return SSH_OK;
201    }
202    
203    static int exec_request(ssh_session session, ssh_channel channel, const char *command, void *userdata)
204    {
205            struct channel_data_struct *cdata = (struct channel_data_struct *)userdata;
206    
207            (void)session;
208            (void)channel;
209    
210            if (cdata->pid > 0)
211            {
212                    return SSH_ERROR;
213            }
214    
215            if (cdata->pty_master != -1 && cdata->pty_slave != -1)
216            {
217                    return exec_pty("-c", command, cdata);
218            }
219            return exec_nopty(command, cdata);
220    }
221    
222    static int shell_request(ssh_session session, ssh_channel channel, void *userdata)
223    {
224            struct channel_data_struct *cdata = (struct channel_data_struct *)userdata;
225    
226            (void)session;
227            (void)channel;
228    
229            if (cdata->pid > 0)
230            {
231                    return SSH_ERROR;
232            }
233    
234            if (cdata->pty_master != -1 && cdata->pty_slave != -1)
235            {
236                    return exec_pty("-l", NULL, cdata);
237            }
238            /* Client requested a shell without a pty, let's pretend we allow that */
239            return SSH_OK;
240    }
241    
242    static int subsystem_request(ssh_session session, ssh_channel channel, const char *subsystem, void *userdata)
243    {
244            (void)session;
245            (void)channel;
246    
247            log_error("subsystem_request(subsystem=%s)\n", subsystem);
248    
249            /* subsystem requests behave similarly to exec requests. */
250            if (strcmp(subsystem, "sftp") == 0)
251            {
252                    return exec_request(session, channel, SFTP_SERVER_PATH, userdata);
253            }
254            return SSH_ERROR;
255    }
256    
257    static ssh_channel channel_open(ssh_session session, void *userdata)
258    {
259            (void)userdata;
260    
261            if (SSH_channel != NULL)
262            {
263                    return NULL;
264            }
265    
266            SSH_channel = ssh_channel_new(session);
267    
268            return SSH_channel;
269    }
270    
271    static int fork_server(void)
272    {
273            ssh_event event;
274            long int ssh_timeout = 0;
275            int pid;
276            int i;
277            int ret;
278    
279            /* Structure for storing the pty size. */
280            struct winsize wsize = {
281                    .ws_row = 0,
282                    .ws_col = 0,
283                    .ws_xpixel = 0,
284                    .ws_ypixel = 0};
285    
286            /* Our struct holding information about the channel. */
287            struct channel_data_struct cdata = {
288                    .pid = 0,
289                    .pty_master = -1,
290                    .pty_slave = -1,
291                    .child_stdin = -1,
292                    .child_stdout = -1,
293                    .child_stderr = -1,
294                    .event = NULL,
295                    .winsize = &wsize};
296    
297            struct session_data_struct cb_data = {
298                    .tries = 0,
299                    .error = 0,
300            };
301    
302            struct ssh_channel_callbacks_struct channel_cb = {
303                    .userdata = &cdata,
304                    .channel_pty_request_function = pty_request,
305                    .channel_pty_window_change_function = pty_resize,
306                    .channel_shell_request_function = shell_request,
307                    .channel_exec_request_function = exec_request,
308                    .channel_subsystem_request_function = subsystem_request};
309    
310            struct ssh_server_callbacks_struct server_cb = {
311                    .userdata = &cb_data,
312                    .auth_password_function = auth_password,
313                    .channel_open_request_session_function = channel_open,
314            };
315    
316            pid = fork();
317    
318            if (pid > 0) // Parent process
319            {
320                    SYS_child_process_count++;
321                    log_common("Child process (%d) start\n", pid);
322                    return pid;
323            }
324            else if (pid < 0) // Error
325            {
326                    log_error("fork() error (%d)\n", errno);
327                    return -1;
328            }
329    
330            // Child process
331    #ifdef HAVE_SYS_EPOLL_H
332            if (close(epollfd_server) < 0)
333            {
334                    log_error("close(epollfd_server) error (%d)\n");
335            }
336    #endif
337    
338            for (i = 0; i < 2; i++)
339            {
340                    if (close(socket_server[i]) == -1)
341                    {
342                            log_error("Close server socket failed\n");
343                    }
344            }
345    
346            hash_dict_destroy(hash_dict_pid_sockaddr);
347            hash_dict_destroy(hash_dict_sockaddr_count);
348    
349            SSH_session = ssh_new();
350    
351            if (SSH_v2)
352            {
353                    if (ssh_bind_accept_fd(sshbind, SSH_session, socket_client) != SSH_OK)
354                    {
355                            log_error("ssh_bind_accept_fd() error: %s\n", ssh_get_error(SSH_session));
356                            goto cleanup;
357                    }
358    
359                    ssh_bind_free(sshbind);
360    
361                    ssh_timeout = 60; // second
362                    if (ssh_options_set(SSH_session, SSH_OPTIONS_TIMEOUT, &ssh_timeout) < 0)
363                    {
364                            log_error("Error setting SSH options: %s\n", ssh_get_error(SSH_session));
365                            goto cleanup;
366                    }
367    
368                    ssh_set_auth_methods(SSH_session, SSH_AUTH_METHOD_PASSWORD);
369    
370                    ssh_callbacks_init(&server_cb);
371                    ssh_callbacks_init(&channel_cb);
372    
373                    ssh_set_server_callbacks(SSH_session, &server_cb);
374    
375                    if (ssh_handle_key_exchange(SSH_session))
376                    {
377                            log_error("ssh_handle_key_exchange() error: %s\n", ssh_get_error(SSH_session));
378                            goto cleanup;
379                    }
380    
381                    event = ssh_event_new();
382                    ssh_event_add_session(event, SSH_session);
383    
384                    for (i = 0; i < SSH_AUTH_MAX_DURATION && !SYS_server_exit && !cb_data.error && SSH_channel == NULL; i += 100)
385                    {
386                            ret = ssh_event_dopoll(event, 100); // 0.1 second
387                            if (ret == SSH_ERROR)
388                            {
389    #ifdef _DEBUG
390                                    log_error("ssh_event_dopoll() error: %s\n", ssh_get_error(SSH_session));
391    #endif
392                                    goto cleanup;
393                            }
394                    }
395    
396                    if (cb_data.error)
397                    {
398                            log_error("SSH auth error, tried %d times\n", cb_data.tries);
399                            goto cleanup;
400                    }
401    
402                    ssh_set_channel_callbacks(SSH_channel, &channel_cb);
403    
404                    do
405                    {
406                            ret = ssh_event_dopoll(event, 100); // 0.1 second
407                            if (ret == SSH_ERROR)
408                            {
409                                    ssh_channel_close(SSH_channel);
410                            }
411    
412                            if (ret == SSH_AGAIN) // loop until SSH connection is fully established
413                            {
414                                    /* Executed only once, once the child process starts. */
415                                    cdata.event = event;
416                                    break;
417                            }
418                    } while (ssh_channel_is_open(SSH_channel));
419    
420                    ssh_timeout = 0;
421                    if (ssh_options_set(SSH_session, SSH_OPTIONS_TIMEOUT, &ssh_timeout) < 0)
422                    {
423                            log_error("Error setting SSH options: %s\n", ssh_get_error(SSH_session));
424                            goto cleanup;
425                    }
426    
427                    ssh_set_blocking(SSH_session, 0);
428            }
429    
430            // Redirect Input
431            if (dup2(socket_client, STDIN_FILENO) == -1)
432            {
433                    log_error("Redirect stdin to client socket failed\n");
434                    goto cleanup;
435            }
436    
437            // Redirect Output
438            if (dup2(socket_client, STDOUT_FILENO) == -1)
439            {
440                    log_error("Redirect stdout to client socket failed\n");
441                    goto cleanup;
442            }
443    
444            if (io_init() < 0)
445            {
446                    log_error("io_init() error\n");
447                    goto cleanup;
448            }
449    
450            SYS_child_process_count = 0;
451    
452            // BWF compile
453            if (bwf_compile() < 0)
454            {
455                    log_error("bwf_compile() error\n");
456                    goto cleanup;
457            }
458    
459            bbs_main();
460    
461    cleanup:
462            // Child process exit
463            SYS_server_exit = 1;
464    
465            if (SSH_v2)
466            {
467                    if (cdata.pty_master != -1)
468                    {
469                            close(cdata.pty_master);
470                    }
471                    if (cdata.child_stdin != -1)
472                    {
473                            close(cdata.child_stdin);
474                    }
475                    if (cdata.child_stdout != -1)
476                    {
477                            close(cdata.child_stdout);
478                    }
479                    if (cdata.child_stderr != -1)
480                    {
481                            close(cdata.child_stderr);
482                    }
483    
484                    ssh_channel_free(SSH_channel);
485                    ssh_disconnect(SSH_session);
486            }
487            else if (close(socket_client) == -1)
488            {
489                    log_error("Close client socket failed\n");
490            }
491    
492            ssh_free(SSH_session);
493            ssh_finalize();
494    
495            // BWF cleanup
496            bwf_cleanup();
497    
498            // Close Input and Output for client
499            io_cleanup();
500            close(STDIN_FILENO);
501            close(STDOUT_FILENO);
502    
503            log_common("Process exit normally\n");
504            log_end();
505    
506            _exit(0);
507    
508            return 0;
509    }
510    
511    int net_server(const char *hostaddr, in_port_t port[])
512    {
513            struct stat file_stat;
514            unsigned int addrlen;
515            int ret;
516            int flags_server[2];
517            struct sockaddr_in sin;
518    
519    #ifdef HAVE_SYS_EPOLL_H
520            struct epoll_event ev, events[MAX_EVENTS];
521    #else
522            struct pollfd pfds[2];
523    #endif
524    
525            int nfds;
526            int notify_child_exit = 0;
527            time_t tm_notify_child_exit = time(NULL);
528            int i, j;
529            pid_t pid;
530            int ssh_key_valid = 0;
531            int ssh_log_level = SSH_LOG_NOLOG;
532    
533    #ifdef HAVE_SYSTEMD_SD_DAEMON_H
534            int sd_notify_stopping = 0;
535    #endif
536    
537            ssh_init();
538    
539            sshbind = ssh_bind_new();
540    
541            if (ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_HOSTKEY, SSH_HOST_RSA_KEY_FILE) < 0)
542            {
543                    log_error("Error loading SSH RSA key: %s\n", SSH_HOST_RSA_KEY_FILE);
544            }
545            else
546            {
547                    ssh_key_valid = 1;
548            }
549            if (ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_HOSTKEY, SSH_HOST_ED25519_KEY_FILE) < 0)
550            {
551                    log_error("Error loading SSH ED25519 key: %s\n", SSH_HOST_ED25519_KEY_FILE);
552            }
553            else
554            {
555                    ssh_key_valid = 1;
556            }
557            if (ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_HOSTKEY, SSH_HOST_ECDSA_KEY_FILE) < 0)
558            {
559                    log_error("Error loading SSH ECDSA key: %s\n", SSH_HOST_ECDSA_KEY_FILE);
560            }
561            else
562            {
563                    ssh_key_valid = 1;
564            }
565    
566            if (!ssh_key_valid)
567            {
568                    log_error("Error: no valid SSH host key\n");
569                    ssh_bind_free(sshbind);
570                    return -1;
571            }
572    
573            if (ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDADDR, hostaddr) < 0 ||
574                    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDPORT, &port) < 0 ||
575                    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_HOSTKEY_ALGORITHMS, "+ssh-rsa") < 0 ||
576                    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_LOG_VERBOSITY, &ssh_log_level) < 0)
577            {
578                    log_error("Error setting SSH bind options: %s\n", ssh_get_error(sshbind));
579                    ssh_bind_free(sshbind);
580                    return -1;
581            }
582    
583    #ifdef HAVE_SYS_EPOLL_H
584            epollfd_server = epoll_create1(0);
585            if (epollfd_server == -1)
586            {
587                    log_error("epoll_create1() error (%d)\n", errno);
588                    return -1;
589            }
590    #endif
591    
592            // Server socket
593            for (i = 0; i < 2; i++)
594            {
595                    socket_server[i] = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
596    
597                    if (socket_server[i] < 0)
598                    {
599                            log_error("Create socket_server error (%d)\n", errno);
600                            return -1;
601                    }
602    
603                    sin.sin_family = AF_INET;
604                    sin.sin_addr.s_addr = (hostaddr[0] != '\0' ? inet_addr(hostaddr) : INADDR_ANY);
605                    sin.sin_port = htons(port[i]);
606    
607                    // Reuse address and port
608                    flags_server[i] = 1;
609                    if (setsockopt(socket_server[i], SOL_SOCKET, SO_REUSEADDR, &flags_server[i], sizeof(flags_server[i])) < 0)
610                    {
611                            log_error("setsockopt SO_REUSEADDR error (%d)\n", errno);
612                    }
613    #if defined(SO_REUSEPORT)
614                    if (setsockopt(socket_server[i], SOL_SOCKET, SO_REUSEPORT, &flags_server[i], sizeof(flags_server[i])) < 0)
615                    {
616                            log_error("setsockopt SO_REUSEPORT error (%d)\n", errno);
617                    }
618    #endif
619    
620                    if (bind(socket_server[i], (struct sockaddr *)&sin, sizeof(sin)) < 0)
621                    {
622                            log_error("Bind address %s:%u error (%d)\n",
623                                              inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), errno);
624                            return -1;
625                    }
626    
627                    if (listen(socket_server[i], 10) < 0)
628                    {
629                            log_error("Telnet socket listen error (%d)\n", errno);
630                            return -1;
631                    }
632    
633                    log_common("Listening at %s:%u\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
634    
635    #ifdef HAVE_SYS_EPOLL_H
636                    ev.events = EPOLLIN;
637                    ev.data.fd = socket_server[i];
638                    if (epoll_ctl(epollfd_server, EPOLL_CTL_ADD, socket_server[i], &ev) == -1)
639                    {
640                            log_error("epoll_ctl(socket_server[%d]) error (%d)\n", i, errno);
641                            if (close(epollfd_server) < 0)
642                            {
643                                    log_error("close(epoll) error (%d)\n");
644                            }
645                            return -1;
646                    }
647    #endif
648    
649                    flags_server[i] = fcntl(socket_server[i], F_GETFL, 0);
650                    fcntl(socket_server[i], F_SETFL, flags_server[i] | O_NONBLOCK);
651            }
652    
653            ssh_bind_set_blocking(sshbind, 0);
654    
655            hash_dict_pid_sockaddr = hash_dict_create(MAX_CLIENT_LIMIT);
656            if (hash_dict_pid_sockaddr == NULL)
657            {
658                    log_error("hash_dict_create(hash_dict_pid_sockaddr) error\n");
659                    return -1;
660            }
661            hash_dict_sockaddr_count = hash_dict_create(MAX_CLIENT_LIMIT);
662            if (hash_dict_sockaddr_count == NULL)
663            {
664                    log_error("hash_dict_create(hash_dict_sockaddr_count) error\n");
665                    return -1;
666            }
667    
668            // Startup complete
669    #ifdef HAVE_SYSTEMD_SD_DAEMON_H
670            sd_notifyf(0, "READY=1\n"
671                                      "STATUS=Listening at %s:%d (Telnet) and %s:%d (SSH2)\n"
672                                      "MAINPID=%d",
673                               hostaddr, port[0], hostaddr, port[1], getpid());
674    #endif
675    
676            while (!SYS_server_exit || SYS_child_process_count > 0)
677            {
678    #ifdef HAVE_SYSTEMD_SD_DAEMON_H
679                    if (SYS_server_exit && !sd_notify_stopping)
680                    {
681                            sd_notify(0, "STOPPING=1");
682                            sd_notify_stopping = 1;
683                    }
684    #endif
685    
686                    while ((SYS_child_exit || SYS_server_exit) && SYS_child_process_count > 0)
687                    {
688                            SYS_child_exit = 0;
689    
690                            pid = waitpid(-1, &ret, WNOHANG);
691                            if (pid > 0)
692                            {
693                                    SYS_child_exit = 1; // Retry waitid
694                                    SYS_child_process_count--;
695    
696                                    if (WIFEXITED(ret))
697                                    {
698                                            log_common("Child process (%d) exited, status=%d\n", pid, WEXITSTATUS(ret));
699                                    }
700                                    else if (WIFSIGNALED(ret))
701                                    {
702                                            log_common("Child process (%d) is killed, status=%d\n", pid, WTERMSIG(ret));
703                                    }
704                                    else
705                                    {
706                                            log_common("Child process (%d) exited abnormally, status=%d\n", pid, ret);
707                                    }
708    
709                                    if (pid != section_list_loader_pid)
710                                    {
711                                            j = 0;
712                                            ret = hash_dict_get(hash_dict_pid_sockaddr, (uint64_t)pid, (int64_t *)&j);
713                                            if (ret < 0)
714                                            {
715                                                    log_error("hash_dict_get(hash_dict_pid_sockaddr, %d) error\n", pid);
716                                            }
717                                            else
718                                            {
719                                                    ret = hash_dict_inc(hash_dict_sockaddr_count, (uint64_t)j, -1);
720                                                    if (ret < 0)
721                                                    {
722                                                            log_error("hash_dict_inc(hash_dict_sockaddr_count, %d, -1) error\n", j);
723                                                    }
724    
725                                                    ret = hash_dict_del(hash_dict_pid_sockaddr, (uint64_t)pid);
726                                                    if (ret < 0)
727                                                    {
728                                                            log_error("hash_dict_del(hash_dict_pid_sockaddr, %d) error\n", pid);
729                                                    }
730                                            }
731                                    }
732                            }
733                            else if (pid == 0)
734                            {
735                                    break;
736                            }
737                            else if (pid < 0)
738                            {
739                                    log_error("Error in waitpid(): %d\n", errno);
740                                    break;
741                            }
742                    }
743    
744                    if (SYS_server_exit && !SYS_child_exit && SYS_child_process_count > 0)
745                    {
746                            if (notify_child_exit == 0)
747                            {
748    #ifdef HAVE_SYSTEMD_SD_DAEMON_H
749                                    sd_notifyf(0, "STATUS=Notify %d child process to exit", SYS_child_process_count);
750                                    log_common("Notify %d child process to exit\n", SYS_child_process_count);
751    #endif
752    
753                                    if (kill(0, SIGTERM) < 0)
754                                    {
755                                            log_error("Send SIGTERM signal failed (%d)\n", errno);
756                                    }
757    
758                                    notify_child_exit = 1;
759                                    tm_notify_child_exit = time(NULL);
760                            }
761                            else if (notify_child_exit == 1 && time(NULL) - tm_notify_child_exit >= WAIT_CHILD_PROCESS_EXIT_TIMEOUT)
762                            {
763    #ifdef HAVE_SYSTEMD_SD_DAEMON_H
764                                    sd_notifyf(0, "STATUS=Kill %d child process", SYS_child_process_count);
765    #endif
766    
767                                    if (kill(0, SIGKILL) < 0)
768                                    {
769                                            log_error("Send SIGKILL signal failed (%d)\n", errno);
770                                    }
771    
772                                    notify_child_exit = 2;
773                                    tm_notify_child_exit = time(NULL);
774                            }
775                            else if (notify_child_exit == 2 && time(NULL) - tm_notify_child_exit >= WAIT_CHILD_PROCESS_KILL_TIMEOUT)
776                            {
777                                    log_error("Main process prepare to exit without waiting for %d child process any longer\n", SYS_child_process_count);
778                                    SYS_child_process_count = 0;
779                            }
780                    }
781    
782                    if (SYS_conf_reload && !SYS_server_exit)
783                    {
784                            SYS_conf_reload = 0;
785    
786    #ifdef HAVE_SYSTEMD_SD_DAEMON_H
787                            sd_notify(0, "RELOADING=1");
788    #endif
789    
790                            // Restart log
791                            if (log_restart() < 0)
792                            {
793                                    log_error("Restart logging failed\n");
794                            }
795    
796                            // Reload configuration
797                            if (load_conf(CONF_BBSD) < 0)
798                            {
799                                    log_error("Reload conf failed\n");
800                            }
801    
802                            // Reload BWF config
803                            if (bwf_load(CONF_BWF) < 0)
804                            {
805                                    log_error("Reload BWF conf failed\n");
806                            }
807    
808                            // Get EULA modification tm
809                            if (stat(DATA_EULA, &file_stat) == -1)
810                            {
811                                    log_error("stat(%s) error\n", DATA_EULA, errno);
812                            }
813                            else
814                            {
815                                    BBS_eula_tm = file_stat.st_mtim.tv_sec;
816                            }
817    
818                            if (detach_menu_shm(&bbs_menu) < 0)
819                            {
820                                    log_error("detach_menu_shm(bbs_menu) error\n");
821                            }
822                            if (load_menu(&bbs_menu, CONF_MENU) < 0)
823                            {
824                                    log_error("load_menu(bbs_menu) error\n");
825                                    unload_menu(&bbs_menu);
826                            }
827    
828                            if (detach_menu_shm(&top10_menu) < 0)
829                            {
830                                    log_error("detach_menu_shm(top10_menu) error\n");
831                            }
832                            if (load_menu(&top10_menu, CONF_TOP10_MENU) < 0)
833                            {
834                                    log_error("load_menu(top10_menu) error\n");
835                                    unload_menu(&top10_menu);
836                            }
837    
838                            for (int i = 0; i < data_files_load_startup_count; i++)
839                            {
840                                    if (load_file(data_files_load_startup[i]) < 0)
841                                    {
842                                            log_error("load_file(%s) error\n", data_files_load_startup[i]);
843                                    }
844                            }
845    
846                            // Load section config and gen_ex
847                            if (load_section_config_from_db(1) < 0)
848                            {
849                                    log_error("load_section_config_from_db(1) error\n");
850                            }
851    
852                            // Notify child processes to reload configuration
853                            if (kill(0, SIGUSR1) < 0)
854                            {
855                                    log_error("Send SIGUSR1 signal failed (%d)\n", errno);
856                            }
857    
858    #ifdef HAVE_SYSTEMD_SD_DAEMON_H
859                            sd_notify(0, "READY=1");
860    #endif
861                    }
862    
863    #ifdef HAVE_SYS_EPOLL_H
864                    nfds = epoll_wait(epollfd_server, events, MAX_EVENTS, 100); // 0.1 second
865                    ret = nfds;
866    #else
867                    pfds[0].fd = socket_server[0];
868                    pfds[0].events = POLLIN;
869                    pfds[1].fd = socket_server[1];
870                    pfds[1].events = POLLIN;
871                    nfds = 2;
872                    ret = poll(pfds, (nfds_t)nfds, 100); // 0.1 second
873    #endif
874                    if (ret < 0)
875                    {
876                            if (errno != EINTR)
877                            {
878    #ifdef HAVE_SYS_EPOLL_H
879                                    log_error("epoll_wait() error (%d)\n", errno);
880    #else
881                                    log_error("poll() error (%d)\n", errno);
882    #endif
883                                    break;
884                            }
885                            continue;
886                    }
887    
888                    // Stop accept new connection on exit
889                    if (SYS_server_exit)
890                    {
891                            continue;
892                    }
893    
894                    for (int i = 0; i < nfds; i++)
895                    {
896    #ifdef HAVE_SYS_EPOLL_H
897                            if (events[i].data.fd == socket_server[0] || events[i].data.fd == socket_server[1])
898    #else
899                            if ((pfds[i].fd == socket_server[0] || pfds[i].fd == socket_server[1]) && (pfds[i].revents & POLLIN))
900    #endif
901                            {
902    #ifdef HAVE_SYS_EPOLL_H
903                                    SSH_v2 = (events[i].data.fd == socket_server[1] ? 1 : 0);
904    #else
905                                    SSH_v2 = (pfds[i].fd == socket_server[1] ? 1 : 0);
906    #endif
907    
908                                    while (!SYS_server_exit) // Accept all incoming connections until error
909                                    {
910                                            addrlen = sizeof(sin);
911                                            socket_client = accept(socket_server[SSH_v2], (struct sockaddr *)&sin, (socklen_t *)&addrlen);
912                                            if (socket_client < 0)
913                                            {
914                                                    if (errno == EAGAIN || errno == EWOULDBLOCK)
915                                                    {
916                                                            break;
917                                                    }
918                                                    else if (errno == EINTR)
919                                                    {
920                                                            continue;
921                                                    }
922                                                    else
923                                                    {
924                                                            log_error("accept(socket_server) error (%d)\n", errno);
925                                                            break;
926                                                    }
927                                            }
928    
929                                            strncpy(hostaddr_client, inet_ntoa(sin.sin_addr), sizeof(hostaddr_client) - 1);
930                                            hostaddr_client[sizeof(hostaddr_client) - 1] = '\0';
931    
932                                            port_client = ntohs(sin.sin_port);
933    
934                                            log_common("Accept %s connection from %s:%d\n", (SSH_v2 ? "SSH" : "telnet"), hostaddr_client, port_client);
935    
936                                            if (SYS_child_process_count - 1 < BBS_max_client)
937                                            {
938                                                    j = 0;
939                                                    ret = hash_dict_get(hash_dict_sockaddr_count, (uint64_t)sin.sin_addr.s_addr, (int64_t *)&j);
940                                                    if (ret < 0)
941                                                    {
942                                                            log_error("hash_dict_get(hash_dict_sockaddr_count, %s) error\n", hostaddr_client);
943                                                    }
944    
945                                                    if (j < BBS_max_client_per_ip)
946                                                    {
947                                                            if ((pid = fork_server()) < 0)
948                                                            {
949                                                                    log_error("fork_server() error\n");
950                                                            }
951                                                            else if (pid > 0)
952                                                            {
953                                                                    ret = hash_dict_set(hash_dict_pid_sockaddr, (uint64_t)pid, sin.sin_addr.s_addr);
954                                                                    if (ret < 0)
955                                                                    {
956                                                                            log_error("hash_dict_set(hash_dict_pid_sockaddr, %d, %s) error\n", pid, hostaddr_client);
957                                                                    }
958    
959                                                                    ret = hash_dict_inc(hash_dict_sockaddr_count, (uint64_t)sin.sin_addr.s_addr, 1);
960                                                                    if (ret < 0)
961                                                                    {
962                                                                            log_error("hash_dict_inc(hash_dict_sockaddr_count, %s, %d) error\n", hostaddr_client, 1);
963                                                                    }
964                                                            }
965                                                    }
966                                                    else
967                                                    {
968                                                            log_error("Rejected client connection from %s over limit per IP (%d)\n", hostaddr_client, BBS_max_client_per_ip);
969                                                    }
970                                            }
971                                            else
972                                            {
973                                                    log_error("Rejected client connection over limit (%d)\n", SYS_child_process_count - 1);
974                                            }
975    
976                                            if (close(socket_client) == -1)
977                                            {
978                                                    log_error("close(socket_lient) error (%d)\n", errno);
979                                            }
980                                    }
981                            }
982                    }
983            }
984    
985    #ifdef HAVE_SYS_EPOLL_H
986            if (close(epollfd_server) < 0)
987            {
988                    log_error("close(epollfd_server) error (%d)\n");
989            }
990    #endif
991    
992            for (i = 0; i < 2; i++)
993            {
994                    if (close(socket_server[i]) == -1)
995                    {
996                            log_error("Close server socket failed\n");
997                    }
998            }
999    
1000            hash_dict_destroy(hash_dict_pid_sockaddr);
1001            hash_dict_destroy(hash_dict_sockaddr_count);
1002    
1003            ssh_bind_free(sshbind);
1004            ssh_finalize();
1005    
1006    return 0;          return 0;
1007  }  }


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

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