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


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

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