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


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

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