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


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

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