1 /* This file is part of GNU Pies. 2 Copyright (C) 2008-2020 Sergey Poznyakoff 3 4 GNU Pies is free software; you can redistribute it and/or modify 5 it under the terms of the GNU General Public License as published by 6 the Free Software Foundation; either version 3, or (at your option) 7 any later version. 8 9 GNU Pies is distributed in the hope that it will be useful, 10 but WITHOUT ANY WARRANTY; without even the implied warranty of 11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 GNU General Public License for more details. 13 14 You should have received a copy of the GNU General Public License 15 along with GNU Pies. If not, see <http://www.gnu.org/licenses/>. */ 16 17 #ifdef HAVE_CONFIG_H 18 # include <config.h> 19 #endif 20 #include <sys/types.h> 21 #include <sys/socket.h> 22 #include <sys/wait.h> 23 #include <sys/stat.h> 24 #include <sys/time.h> 25 #include <sys/resource.h> 26 #include <netinet/in.h> 27 #include <sys/un.h> 28 #include <arpa/inet.h> 29 #include <netdb.h> 30 #include <stdio.h> 31 #include <stdlib.h> 32 #include <stdarg.h> 33 #include <stdint.h> 34 #include <unistd.h> 35 #include <fcntl.h> 36 #include <syslog.h> 37 #include <getopt.h> 38 #include <errno.h> 39 #include <string.h> 40 #include <pwd.h> 41 #include <grp.h> 42 #include <signal.h> 43 #include <time.h> 44 #include <sysexits.h> 45 #include <ctype.h> 46 47 #include <grecs.h> 48 #include <wordsplit.h> 49 50 #include "progname.h" 51 #include "inttostr.h" 52 #include "c-ctype.h" 53 #include "quotearg.h" 54 #include "fprintftime.h" 55 56 #include "identity.h" 57 #include "acl.h" 58 #include "libpies.h" 59 #include "envop.h" 60 #include "grecs/json.h" 61 #include "pies_syslog.h" 62 63 #define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) 64 65 #define TESTTIME 2*60 66 #define SLEEPTIME 5*60 67 #define MAXSPAWN 10 68 69 #define DEFAULT_PASS_FD_TIMEOUT 5 70 71 #define RETR_OUT 0 72 #define RETR_ERR 1 73 74 enum redir_type 75 { 76 redir_null, 77 redir_syslog, 78 redir_file 79 }; 80 81 struct redirector 82 { 83 enum redir_type type; 84 union 85 { 86 int prio; 87 char *file; 88 } v; 89 }; 90 91 typedef struct limits_rec *limits_record_t; 92 93 enum return_action 94 { 95 action_restart, 96 action_disable, 97 }; 98 99 #define STATUS_SIG_BIT 0x80000000 100 #define STATUS_CODE(c) ((c) & ~STATUS_SIG_BIT) 101 102 struct action 103 { 104 size_t nstat; 105 unsigned *status; 106 enum return_action act; /* Action to take when the component terminates */ 107 char *addr; /* Addresses to notify about it. */ 108 char *message; /* Notification mail. */ 109 char *command; /* Execute this command */ 110 }; 111 112 113 /* user privs */ 114 struct pies_privs 115 { 116 char *user; 117 int allgroups; 118 struct grecs_list *groups; 119 }; 120 121 enum pies_comp_mode 122 { 123 /* 124 ** Pies native component types. 125 */ 126 /* Execute the component, no sockets are opened. This is the default 127 Pies mode. */ 128 pies_comp_exec, 129 /* Open a socket and start a component with stdin/stdout bound to that 130 socket. Corresponds to MeTA1 notion of `start_action = accept'. 131 */ 132 pies_comp_accept, 133 /* Inetd mode: like above, but start the component only when an 134 incoming connection is requested. Corresponds to 135 `start_action = nostartaccept' in MeTA1. 136 */ 137 pies_comp_inetd, 138 /* Open a socket, start a component, and pass the socket fd to the 139 component via the UNIX domain socket. Corresponds to 140 `start_action = pass' in MeTA1. */ 141 pies_comp_pass_fd, 142 143 /* Components of this type runs once on program startup. Running other 144 components is delayed until the last startup component finishes. */ 145 pies_comp_startup, 146 147 /* Components of this type are run right before program termination. 148 They have shutdown_timeout seconds to finish their job and terminate 149 gracefully, othervise they will be terminated forcefully via SIGTERM 150 (and SIGKILL, for persisting ones). */ 151 pies_comp_shutdown, 152 153 /* 154 ** Init-style components 155 */ 156 pies_mark_sysvinit, 157 /* Start the process when the specified runlevel is entered and wait 158 for its termination */ 159 pies_comp_wait = pies_mark_sysvinit, 160 /* Execute the component once, when the specified runlevel is entered */ 161 pies_comp_once, 162 /* Execute the component during system boot. Ignore runlevel settings. */ 163 pies_comp_boot, 164 /* Execute the component during system boot and wait for it to terminate. 165 Ignore runlevel settings. */ 166 pies_comp_bootwait, 167 /* Execute the component when the power goes down. */ 168 pies_comp_powerfail, 169 /* Execute the component when the power goes down. Wait for it to 170 terminate. */ 171 pies_comp_powerwait, 172 /* Execute the component when the power is restored. Wait for it to 173 terminate. */ 174 pies_comp_powerokwait, 175 /* Execute the process when SIGINT is delivered, i.e. someone has 176 pressed the Ctrl+Alt+Del combination. */ 177 pies_comp_ctrlaltdel, 178 /* Execute the component when a specified ondemand runlevel is called */ 179 pies_comp_ondemand, 180 /* Execute the component on the system boot. */ 181 pies_comp_sysinit, 182 /* Execute the component when running on the UPS and pies is informed that 183 the UPS battery is almost empty. */ 184 pies_comp_powerfailnow, 185 /* Execute the component a signal from the keyboard handler arrives, 186 indicating that a special key combination was pressed on the console 187 keyboard. */ 188 pies_comp_kbrequest, 189 190 /* Restart the component wherever it terminates */ 191 pies_comp_respawn = pies_comp_exec, 192 }; 193 194 #define PIES_COMP_DEFAULT 0 195 #define PIES_COMP_MASK(m) (1 << ((m))) 196 197 #define CF_DISABLED 0x001 /* The componenet is disabled */ 198 #define CF_PRECIOUS 0x002 /* The component is precious (should not 199 be disabled) */ 200 #define CF_WAIT 0x004 /* Wait for the component instance to 201 terminate. */ 202 #define CF_TCPMUX 0x008 /* A plain TCPMUX service */ 203 #define CF_TCPMUXPLUS 0x010 /* A TCPMUX-plus service, i.e. pies 204 must emit a '+' response before starting 205 it */ 206 #define CF_INTERNAL 0x020 /* An internal inetd service */ 207 #define CF_SOCKENV 0x040 /* Component wants socket information in 208 the environment */ 209 #define CF_RESOLVE 0x080 /* Resolve IP addresses */ 210 #define CF_SIGGROUP 0x100 /* Send signals to the process group */ 211 #define CF_NULLINPUT 0x200 /* Provide null input stream */ 212 #define CF_SHELL 0x400 /* Invoke via sh -c */ 213 #define CF_EXPANDENV 0x800 /* Expand environment variables in the command 214 line */ 215 216 #define CF_REMOVE 0xf000 /* Marked for removal */ 217 218 #define ISCF_TCPMUX(f) ((f) & (CF_TCPMUX | CF_TCPMUXPLUS)) 219 220 struct prog; 221 222 struct component 223 { 224 struct component *prev, *next; /* Components form doubly-linked list. */ 225 int listidx; /* Index of the list. */ 226 size_t arridx; /* Index of this component. */ 227 size_t ref_count; /* Reference count. */ 228 struct prog *prog; /* Prog associated with this component. */ 229 230 enum pies_comp_mode mode; 231 char *tag; /* Entry tag (for diagnostics purposes) */ 232 char *program; /* Program name */ 233 char *command; /* Full command line */ 234 size_t argc; /* Number of command line arguments */ 235 char **argv; /* Program command line */ 236 envop_t *envop; /* Environment modification program */ 237 char *dir; /* Working directory */ 238 struct grecs_list *prereq; /* Prerequisites */ 239 struct grecs_list *depend; /* Dependency targets */ 240 int flags; /* CF_ bitmask */ 241 size_t max_instances; /* Maximum number of simultaneously running 242 instances */ 243 char *rmfile; /* Try to remove this file before starting */ 244 struct pies_privs privs; /* UID/GIDS+groups to run as */ 245 mode_t umask; /* Umask to install before starting */ 246 limits_record_t limits; /* System limits */ 247 248 /* For exec (init) components */ 249 char *runlevels; 250 251 /* For inetd components */ 252 size_t max_rate; /* Maximum number of invocations per minute */ 253 size_t max_ip_connections; /* Max. number of connections per IP address */ 254 int socket_type; /* Socket type */ 255 struct inetd_builtin *builtin; /* Builtin function */ 256 char *service; 257 258 struct pies_url *socket_url; /* Socket to listen on 259 (if mode != pies_comp_exec) */ 260 char *pass_fd_socket; /* Socket to pass fd on 261 (if mode == pies_comp_pass_fd) */ 262 unsigned pass_fd_timeout; /* Maximum time to wait for pass_fd socket to 263 become available. */ 264 pies_acl_t acl; /* Connection ACL */ 265 char *tcpmux; /* Master service for TCPMUX */ 266 267 /* Optional error messages to be sent back on the socket: */ 268 char *access_denied_message; 269 char *max_instances_message; 270 char *max_ip_connections_message; 271 272 /* Redirectors: */ 273 struct redirector redir[2]; /* Repeaters for stdout and stderr */ 274 /* Actions to execute on various exit codes: */ 275 struct grecs_list *act_list; 276 /* ACLs for control interface */ 277 pies_acl_t list_acl; /* List access control list */ 278 pies_acl_t adm_acl; /* Administrative ACL (stop, start, etc.) */ 279 }; 280 281 #define is_sysvinit(cp) \ 282 (PIES_SYSVINIT_ENABLED \ 283 && ((cp)->mode >= pies_mark_sysvinit || (cp)->runlevels)) 284 285 #define SYSVINIT_ACTIVE (PIES_SYSVINIT_ENABLED && init_process) 286 287 enum pies_action { 288 ACTION_CONT, 289 ACTION_STOP, 290 ACTION_RESTART, 291 ACTION_RELOAD, 292 ACTION_CTRLALTDEL, 293 ACTION_KBREQUEST, 294 ACTION_POWER, 295 ACTION_COMMIT 296 }; 297 298 extern char *instance; 299 extern unsigned long shutdown_timeout; 300 extern struct component default_component; 301 extern pies_acl_t pies_acl; 302 extern limits_record_t pies_limits; 303 extern char *mailer_program; 304 extern char *mailer_command_line; 305 extern int mailer_argc; 306 extern char **mailer_argv; 307 extern size_t default_max_rate; 308 extern char *qotdfile; 309 310 extern int init_process; 311 extern char *console_device; 312 extern int initdefault; 313 314 extern size_t pies_master_argc; 315 extern char **pies_master_argv; 316 extern char *default_control_url[2]; 317 318 enum config_syntax_type 319 { 320 CONF_PIES, 321 CONF_META1, 322 CONF_INETD, 323 CONF_INITTAB 324 }; 325 326 struct config_syntax; 327 328 struct config_syntax *str_to_config_syntax (const char *str); 329 void config_file_add (struct config_syntax *syntax, const char *name); 330 void config_file_add_type (enum config_syntax_type syntax, const char *name); 331 void config_file_list_serialize (struct json_value *ar); 332 333 int config_file_remove (const char *name); 334 void config_file_remove_all (void); 335 336 void free_redirector (struct redirector *rp); 337 338 void pies_schedule_action (int act); 339 void free_action (struct action *act); 340 341 void argv_free (char **argv); 342 343 #define PIES_CHLD_NONE 0 344 #define PIES_CHLD_CLEANUP 0x01 345 #define PIES_CHLD_WAKEUP 0x02 346 #define PIES_CHLD_GC 0x04 347 #define PIES_CHLD_RESCHEDULE_ALARM 0x08 348 349 void pies_schedule_children (int op); 350 351 int pies_read_config (void); 352 int pies_reread_config (void); 353 354 void register_prog (struct component *comp); 355 void program_init_startup (void); 356 int progman_waiting_p (void); 357 void progman_start (void); 358 void progman_gc (void); 359 void progman_wake_sleeping (int); 360 void progman_stop (void); 361 void progman_cleanup (int expect_term); 362 void progman_filter (int (*filter) (struct component *, void *data), 363 void *data); 364 int progman_accept (int socket, void *data); 365 366 void progman_create_sockets (void); 367 struct component *progman_lookup_component (const char *tag); 368 struct component *progman_lookup_tcpmux (const char *service, 369 const char *master); 370 371 void progman_run_comp (struct component *comp, int fd, 372 union pies_sockaddr_storage *sa, socklen_t salen); 373 void progman_recompute_alarm (void); 374 375 void fd_report (int fd, const char *msg); 376 377 int check_acl (pies_acl_t acl, struct sockaddr *s, socklen_t salen, 378 pies_identity_t identity); 379 380 void log_setup (int want_stderr); 381 void signal_setup (RETSIGTYPE (*sf)(int)); 382 void setsigvhan (RETSIGTYPE (*handler) (int signo), int *sigv, int sigc); 383 void add_extra_sigv (int *sigv, int sigc); 384 385 typedef struct pies_depmap *pies_depmap_t; 386 typedef struct pies_depmap_pos *pies_depmap_pos_t; 387 enum pies_depmap_direction 388 { 389 depmap_row = 0, 390 depmap_col = !depmap_row 391 }; 392 393 pies_depmap_t depmap_alloc (size_t count); 394 pies_depmap_t depmap_copy (pies_depmap_t dpm); 395 size_t depmap_dim (struct pies_depmap *dmap); 396 void depmap_free (pies_depmap_t dmap); 397 void depmap_set (pies_depmap_t dmap, size_t row, size_t col); 398 int depmap_isset (pies_depmap_t dmap, size_t row, size_t col); 399 void depmap_clear (pies_depmap_t dmap, size_t row, size_t col); 400 void depmap_remove (pies_depmap_t dmap, size_t n); 401 402 void depmap_tc (pies_depmap_t dmap); 403 size_t depmap_first (pies_depmap_t dmap, enum pies_depmap_direction dir, 404 size_t coord, pies_depmap_pos_t *ppos); 405 size_t depmap_next (pies_depmap_t dmap, pies_depmap_pos_t pos); 406 void depmap_end (pies_depmap_pos_t pos); 407 408 409 struct depmap_path_elem 410 { 411 int idx; 412 struct depmap_path_elem *next; 413 }; 414 415 struct depmap_path 416 { 417 size_t len; 418 struct depmap_path_elem *head, *tail; 419 struct depmap_path *next; 420 }; 421 422 void depmap_path_free (struct depmap_path *path); 423 struct depmap_path *depmap_cycle_detect (pies_depmap_t dmap); 424 425 int assert_grecs_value_type (grecs_locus_t *locus, 426 const grecs_value_t *value, int type); 427 428 int str_to_socket_type (const char *str, int *pret); 429 int socket_type_to_str (int socket_type, const char **pres); 430 431 struct component *component_create (const char *name); 432 void component_free (struct component *comp); 433 void component_ref_incr (struct component *comp); 434 void component_ref_decr (struct component *comp); 435 436 int component_list_is_empty (void); 437 438 void component_config_begin (void); 439 void component_config_rollback (void); 440 void component_config_commit (void); 441 442 int component_is_active (struct component *comp); 443 444 void component_finish (struct component *comp, grecs_locus_t *locus); 445 struct grecs_keyword *find_component_keyword (const char *ident); 446 int component_foreach (int (*filter) (struct component *, void *), 447 void *data); 448 449 void components_dump_depmap (void); 450 void components_trace (char **argv, enum pies_depmap_direction dir); 451 452 struct component *component_depmap_first (enum pies_depmap_direction dir, 453 size_t idx, pies_depmap_pos_t *ppos); 454 struct component *component_depmap_next (pies_depmap_pos_t pos); 455 456 457 458 void pies_set_hook (int (*f) (void)); 459 void pies_pause (void); 460 461 enum 462 { 463 PIES_EVT_RD, 464 PIES_EVT_WR, 465 PIES_EVT_EX 466 }; 467 468 typedef int (*socket_handler_t) (int, void *); 469 470 void *register_socket (int fd, 471 socket_handler_t rd, 472 socket_handler_t wr, 473 socket_handler_t ex, 474 void *data, 475 void (*free_data)(void*)); 476 void deregister_socket (int fd); 477 void update_socket (int fd, int evt, socket_handler_t f); 478 479 int register_program_socket (int socktype, int fd, void *data, 480 void (*free_data)(void*)); 481 int pass_fd (const char *socket, int fd, unsigned time_out); 482 int create_socket (struct pies_url *url, int socket_type, 483 const char *user, mode_t umask); 484 void disable_socket (int fd); 485 void enable_socket (int fd); 486 487 488 int parse_limits (limits_record_t *plrec, char *str, char **endp); 489 int set_limits (const char *name, limits_record_t lrec); 490 void free_limits (limits_record_t rec); 491 int limits_cmp (limits_record_t a, limits_record_t b); 492 493 494 void meta1_parser_set_debug (void); 495 int meta1lex (void); 496 int meta1error (char const *s); 497 int meta1parse (void); 498 499 500 /* diag.c */ 501 #define DIAG_TO_SYSLOG 0x01 502 #define DIAG_TO_STDERR 0x02 503 #define DIAG_TO_MASK 0x0f 504 #define DIAG_REOPEN_LOG 0x10 505 506 #define DIAG_ALL (DIAG_REOPEN_LOG|DIAG_TO_STDERR|DIAG_TO_SYSLOG) 507 508 extern int diag_output; 509 510 #define DIAG_OUTPUT(x) (diag_output & (x)) 511 512 void diag_setup (int flags); 513 514 #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7) 515 # define __attribute__(x) 516 #endif 517 518 #ifndef PIES_PRINTFLIKE 519 # define PIES_PRINTFLIKE(fmt,narg) __attribute__ ((__format__ (__printf__, fmt, narg))) 520 #endif 521 522 void diagmsg (int logf, int prio, const char *fmt, ...) 523 PIES_PRINTFLIKE(3,4); 524 525 void vlogmsg (int prio, const char *fmt, va_list ap); 526 void logmsg (int prio, const char *fmt, ...) PIES_PRINTFLIKE(2,3); 527 void logmsg_printf (int prio, const char *fmt, ...) PIES_PRINTFLIKE(2,3); 528 void logmsg_vprintf (int prio, const char *fmt, va_list ap); 529 void logfuncall (const char *fun, const char *arg, int err); 530 531 void pies_diag_printer (grecs_locus_t const *locus, int err, int errcode, 532 const char *msg); 533 534 extern unsigned debug_level; 535 extern int source_info_option; 536 void debug_msg (const char *fmt, ...) PIES_PRINTFLIKE(1,2); 537 538 #define debug(lev, args) \ 539 do \ 540 if (debug_level >= lev) \ 541 { \ 542 if (source_info_option) \ 543 logmsg_printf (LOG_DEBUG, "%s:%d:%s: ", \ 544 __FILE__, __LINE__, __FUNCTION__); \ 545 debug_msg args; \ 546 } \ 547 while (0) 548 549 /* userprivs.c */ 550 int switch_to_privs (uid_t uid, gid_t gid, struct grecs_list *retain_groups); 551 552 void pies_priv_setup (struct pies_privs *); 553 void pies_epriv_setup (struct pies_privs *); 554 555 int pies_privs_cmp (struct pies_privs const *a, struct pies_privs const *b); 556 void pies_privs_free (struct pies_privs *p); 557 558 559 /* inetd.c */ 560 int inetd_config_parse (const char *file); 561 562 /* inetd-bi.c */ 563 struct inetd_builtin 564 { 565 const char *service; 566 int socktype; 567 int single_process; 568 int flags; 569 void (*fun) (int, struct component const *); 570 }; 571 572 struct inetd_builtin *inetd_builtin_lookup (const char *service, int socktype); 573 574 /* sysvinit.c */ 575 void sysvinit_begin (void); 576 int is_comp_wait (struct component *comp); 577 int is_valid_runlevel (int c); 578 int console_open (int mode); 579 int telinit (int argc, char **argv); 580 int inittab_parse (const char *file); 581 int sysvinit_sigtrans (int sig, int *pact); 582 void sysvinit_runlevel_setup (int mask); 583 void sysvinit_sysdep_begin (void); 584 void sysvinit_power (void); 585 586 void sysvinit_report (struct json_value *obj); 587 int sysvinit_set_runlevel (int newlevel); 588 void sysvinit_parse_argv (int argc, char **argv); 589 590 int sysvinit_envlocate (char const *name, char **value); 591 int sysvinit_envdelete (char const *name); 592 int sysvinit_envupdate (char const *var); 593 594 int cb_initdefault (enum grecs_callback_command cmd, 595 grecs_node_t *node, 596 void *varptr, void *cb_data); 597 int cb_runlevels (enum grecs_callback_command cmd, 598 grecs_node_t *node, 599 void *varptr, void *cb_data); 600 601 extern char *sysvinit_environ_hint[]; 602 extern char *init_fifo; 603 604 #ifndef INIT_FIFO 605 # define INIT_FIFO "/dev/initctl" 606 #endif 607 608 #ifndef POWER_STAT_FILE 609 # define POWER_STAT_FILE "/var/run/powerstatus" 610 #endif 611 612 /* Power status values */ 613 #define POWER_STAT_FAIL 'F' 614 #define POWER_STAT_LOW 'L' 615 #define POWER_STAT_OK 'O' 616 617 /* Request codes */ 618 #define INIT_MAGIC 0x03091969 619 #define INIT_CMD_START 0 620 #define INIT_CMD_RUNLVL 1 621 #define INIT_CMD_POWERFAIL 2 622 #define INIT_CMD_POWERFAILNOW 3 623 #define INIT_CMD_POWEROK 4 624 #define INIT_CMD_BSD 5 625 #define INIT_CMD_SETENV 6 626 #define INIT_CMD_UNSETENV 7 627 628 #define INIT_CMD_CHANGECONS 12345 629 630 struct sysvinit_request 631 { 632 int magic; /* Magic number */ 633 int cmd; /* What kind of request */ 634 int runlevel; /* Runlevel to change to */ 635 int sleeptime; /* Time between TERM and KILL */ 636 char data[368]; 637 }; 638 639 640 641 /* utmp.c */ 642 #define SYSV_ACCT_BOOT 0 643 #define SYSV_ACCT_RUNLEVEL 1 644 #define SYSV_ACCT_PROC_START 2 645 #define SYSV_ACCT_PROC_STOP 3 646 647 void sysvinit_acct (int what, const char *user, const char *id, pid_t pid, 648 const char *line); 649 650 651 /* ctl.c */ 652 struct control 653 { 654 struct pies_url *url; /* Control socket URL */ 655 pies_acl_t conn_acl; /* Connection ACL */ 656 pies_acl_t adm_acl; /* Administrative ACL */ 657 pies_acl_t usr_acl; /* User ACL */ 658 unsigned int idle_timeout; /* Session idle timeout */ 659 char *realm; /* Authentication realm */ 660 }; 661 662 extern struct control control; 663 664 int ctl_open(void); 665 666 void json_object_set_string (struct json_value *obj, 667 char const *name, char const *fmt, ...); 668 void json_object_set_number (struct json_value *obj, 669 char const *name, double val); 670 void json_object_set_bool (struct json_value *obj, char const *name, int val); 671