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


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

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