1/* Licensed to the Apache Software Foundation (ASF) under one or more 2 * contributor license agreements. See the NOTICE file distributed with 3 * this work for additional information regarding copyright ownership. 4 * The ASF licenses this file to You under the Apache License, Version 2.0 5 * (the "License"); you may not use this file except in compliance with 6 * the License. You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#ifdef WIN32 18 19#define CORE_PRIVATE 20#include "httpd.h" 21#include "http_main.h" 22#include "http_log.h" 23#include "http_config.h" /* for read_config */ 24#include "http_core.h" /* for get_remote_host */ 25#include "http_connection.h" 26#include "apr_portable.h" 27#include "apr_thread_proc.h" 28#include "apr_getopt.h" 29#include "apr_strings.h" 30#include "apr_lib.h" 31#include "apr_shm.h" 32#include "apr_thread_mutex.h" 33#include "ap_mpm.h" 34#include "ap_config.h" 35#include "ap_listen.h" 36#include "mpm_default.h" 37#include "mpm_winnt.h" 38#include "mpm_common.h" 39#include <malloc.h> 40#include "apr_atomic.h" 41 42/* Because ap_setup_listeners() is skipped in the child, any merging 43 * of [::]:80 and 0.0.0.0:80 for AP_ENABLE_V4_MAPPED in the parent 44 * won't have taken place in the child, so the child will expect to 45 * read two sockets for "Listen 80" but the parent will send only 46 * one. 47 */ 48#ifdef AP_ENABLE_V4_MAPPED 49#error The WinNT MPM does not currently support AP_ENABLE_V4_MAPPED 50#endif 51 52/* scoreboard.c does the heavy lifting; all we do is create the child 53 * score by moving a handle down the pipe into the child's stdin. 54 */ 55extern apr_shm_t *ap_scoreboard_shm; 56server_rec *ap_server_conf; 57 58/* Definitions of WINNT MPM specific config globals */ 59static HANDLE shutdown_event; /* used to signal the parent to shutdown */ 60static HANDLE restart_event; /* used to signal the parent to restart */ 61 62char ap_coredump_dir[MAX_STRING_LEN]; 63 64static int one_process = 0; 65static char const* signal_arg = NULL; 66 67OSVERSIONINFO osver; /* VER_PLATFORM_WIN32_NT */ 68 69static DWORD parent_pid; 70DWORD my_pid; 71 72int ap_threads_per_child = 0; 73int use_acceptex = 1; 74static int thread_limit = DEFAULT_THREAD_LIMIT; 75static int first_thread_limit = 0; 76static int changed_limit_at_restart; 77int winnt_mpm_state = AP_MPMQ_STARTING; 78/* ap_my_generation are used by the scoreboard code */ 79ap_generation_t volatile ap_my_generation=0; 80 81 82/* shared by service.c as global, although 83 * perhaps it should be private. 84 */ 85apr_pool_t *pconf; 86 87 88/* definitions from child.c */ 89void child_main(apr_pool_t *pconf); 90 91/* used by parent to signal the child to start and exit 92 * NOTE: these are not sophisticated enough for multiple children 93 * so they ultimately should not be shared with child.c 94 */ 95extern apr_proc_mutex_t *start_mutex; 96extern HANDLE exit_event; 97 98/* Only one of these, the pipe from our parent, ment only for 99 * one child worker's consumption (not to be inherited!) 100 * XXX: decorate this name for the trunk branch, was left simplified 101 * only to make the 2.2 patch trivial to read. 102 */ 103static HANDLE pipe; 104 105/* 106 * Command processors 107 */ 108 109static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, const char *arg) 110{ 111 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY); 112 if (err != NULL) { 113 return err; 114 } 115 116 ap_threads_per_child = atoi(arg); 117 if (ap_threads_per_child > thread_limit) { 118 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 119 "WARNING: ThreadsPerChild of %d exceeds ThreadLimit " 120 "value of %d threads,", ap_threads_per_child, 121 thread_limit); 122 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 123 " lowering ThreadsPerChild to %d. To increase, please" 124 " see the", thread_limit); 125 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 126 " ThreadLimit directive."); 127 ap_threads_per_child = thread_limit; 128 } 129 else if (ap_threads_per_child < 1) { 130 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 131 "WARNING: Require ThreadsPerChild > 0, setting to 1"); 132 ap_threads_per_child = 1; 133 } 134 return NULL; 135} 136static const char *set_thread_limit (cmd_parms *cmd, void *dummy, const char *arg) 137{ 138 int tmp_thread_limit; 139 140 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY); 141 if (err != NULL) { 142 return err; 143 } 144 145 tmp_thread_limit = atoi(arg); 146 /* you cannot change ThreadLimit across a restart; ignore 147 * any such attempts 148 */ 149 if (first_thread_limit && 150 tmp_thread_limit != thread_limit) { 151 /* how do we log a message? the error log is a bit bucket at this 152 * point; we'll just have to set a flag so that ap_mpm_run() 153 * logs a warning later 154 */ 155 changed_limit_at_restart = 1; 156 return NULL; 157 } 158 thread_limit = tmp_thread_limit; 159 160 if (thread_limit > MAX_THREAD_LIMIT) { 161 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 162 "WARNING: ThreadLimit of %d exceeds compile time limit " 163 "of %d threads,", thread_limit, MAX_THREAD_LIMIT); 164 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 165 " lowering ThreadLimit to %d.", MAX_THREAD_LIMIT); 166 thread_limit = MAX_THREAD_LIMIT; 167 } 168 else if (thread_limit < 1) { 169 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 170 "WARNING: Require ThreadLimit > 0, setting to 1"); 171 thread_limit = 1; 172 } 173 return NULL; 174} 175static const char *set_disable_acceptex(cmd_parms *cmd, void *dummy) 176{ 177 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY); 178 if (err != NULL) { 179 return err; 180 } 181 if (use_acceptex) { 182 use_acceptex = 0; 183 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL, 184 "Disabled use of AcceptEx() WinSock2 API"); 185 } 186 return NULL; 187} 188 189static const command_rec winnt_cmds[] = { 190LISTEN_COMMANDS, 191AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, 192 "Number of threads each child creates" ), 193AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF, 194 "Maximum worker threads in a server for this run of Apache"), 195AP_INIT_NO_ARGS("Win32DisableAcceptEx", set_disable_acceptex, NULL, RSRC_CONF, 196 "Disable use of the high performance AcceptEx WinSock2 API to work around buggy VPN or Firewall software"), 197 198{ NULL } 199}; 200 201 202/* 203 * Signalling Apache on NT. 204 * 205 * Under Unix, Apache can be told to shutdown or restart by sending various 206 * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so 207 * we use "events" instead. The parent apache process goes into a loop 208 * where it waits forever for a set of events. Two of those events are 209 * called 210 * 211 * apPID_shutdown 212 * apPID_restart 213 * 214 * (where PID is the PID of the apache parent process). When one of these 215 * is signalled, the Apache parent performs the appropriate action. The events 216 * can become signalled through internal Apache methods (e.g. if the child 217 * finds a fatal error and needs to kill its parent), via the service 218 * control manager (the control thread will signal the shutdown event when 219 * requested to stop the Apache service), from the -k Apache command line, 220 * or from any external program which finds the Apache PID from the 221 * httpd.pid file. 222 * 223 * The signal_parent() function, below, is used to signal one of these events. 224 * It can be called by any child or parent process, since it does not 225 * rely on global variables. 226 * 227 * On entry, type gives the event to signal. 0 means shutdown, 1 means 228 * graceful restart. 229 */ 230/* 231 * Initialise the signal names, in the global variables signal_name_prefix, 232 * signal_restart_name and signal_shutdown_name. 233 */ 234#define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */ 235char signal_name_prefix[MAX_SIGNAL_NAME]; 236char signal_restart_name[MAX_SIGNAL_NAME]; 237char signal_shutdown_name[MAX_SIGNAL_NAME]; 238void setup_signal_names(char *prefix) 239{ 240 apr_snprintf(signal_name_prefix, sizeof(signal_name_prefix), prefix); 241 apr_snprintf(signal_shutdown_name, sizeof(signal_shutdown_name), 242 "%s_shutdown", signal_name_prefix); 243 apr_snprintf(signal_restart_name, sizeof(signal_restart_name), 244 "%s_restart", signal_name_prefix); 245} 246 247int volatile is_graceful = 0; 248 249AP_DECLARE(int) ap_graceful_stop_signalled(void) 250{ 251 return is_graceful; 252} 253 254AP_DECLARE(void) ap_signal_parent(ap_signal_parent_e type) 255{ 256 HANDLE e; 257 char *signal_name; 258 259 if (parent_pid == my_pid) { 260 switch(type) { 261 case SIGNAL_PARENT_SHUTDOWN: 262 { 263 SetEvent(shutdown_event); 264 break; 265 } 266 /* This MPM supports only graceful restarts right now */ 267 case SIGNAL_PARENT_RESTART: 268 case SIGNAL_PARENT_RESTART_GRACEFUL: 269 { 270 is_graceful = 1; 271 SetEvent(restart_event); 272 break; 273 } 274 } 275 return; 276 } 277 278 switch(type) { 279 case SIGNAL_PARENT_SHUTDOWN: 280 { 281 signal_name = signal_shutdown_name; 282 break; 283 } 284 /* This MPM supports only graceful restarts right now */ 285 case SIGNAL_PARENT_RESTART: 286 case SIGNAL_PARENT_RESTART_GRACEFUL: 287 { 288 signal_name = signal_restart_name; 289 is_graceful = 1; 290 break; 291 } 292 default: 293 return; 294 } 295 296 e = OpenEvent(EVENT_MODIFY_STATE, FALSE, signal_name); 297 if (!e) { 298 /* Um, problem, can't signal the parent, which means we can't 299 * signal ourselves to die. Ignore for now... 300 */ 301 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf, 302 "OpenEvent on %s event", signal_name); 303 return; 304 } 305 if (SetEvent(e) == 0) { 306 /* Same problem as above */ 307 ap_log_error(APLOG_MARK, APLOG_EMERG, apr_get_os_error(), ap_server_conf, 308 "SetEvent on %s event", signal_name); 309 CloseHandle(e); 310 return; 311 } 312 CloseHandle(e); 313} 314 315 316/* 317 * Passed the following handles [in sync with send_handles_to_child()] 318 * 319 * ready event [signal the parent immediately, then close] 320 * exit event [save to poll later] 321 * start mutex [signal from the parent to begin accept()] 322 * scoreboard shm handle [to recreate the ap_scoreboard] 323 */ 324static void get_handles_from_parent(server_rec *s, HANDLE *child_exit_event, 325 apr_proc_mutex_t **child_start_mutex, 326 apr_shm_t **scoreboard_shm) 327{ 328 HANDLE hScore; 329 HANDLE ready_event; 330 HANDLE os_start; 331 DWORD BytesRead; 332 void *sb_shared; 333 apr_status_t rv; 334 335 /* *** We now do this was back in winnt_rewrite_args 336 * pipe = GetStdHandle(STD_INPUT_HANDLE); 337 */ 338 if (!ReadFile(pipe, &ready_event, sizeof(HANDLE), 339 &BytesRead, (LPOVERLAPPED) NULL) 340 || (BytesRead != sizeof(HANDLE))) { 341 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 342 "Child %lu: Unable to retrieve the ready event from the parent", my_pid); 343 exit(APEXIT_CHILDINIT); 344 } 345 346 SetEvent(ready_event); 347 CloseHandle(ready_event); 348 349 if (!ReadFile(pipe, child_exit_event, sizeof(HANDLE), 350 &BytesRead, (LPOVERLAPPED) NULL) 351 || (BytesRead != sizeof(HANDLE))) { 352 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 353 "Child %lu: Unable to retrieve the exit event from the parent", my_pid); 354 exit(APEXIT_CHILDINIT); 355 } 356 357 if (!ReadFile(pipe, &os_start, sizeof(os_start), 358 &BytesRead, (LPOVERLAPPED) NULL) 359 || (BytesRead != sizeof(os_start))) { 360 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 361 "Child %lu: Unable to retrieve the start_mutex from the parent", my_pid); 362 exit(APEXIT_CHILDINIT); 363 } 364 *child_start_mutex = NULL; 365 if ((rv = apr_os_proc_mutex_put(child_start_mutex, &os_start, s->process->pool)) 366 != APR_SUCCESS) { 367 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 368 "Child %lu: Unable to access the start_mutex from the parent", my_pid); 369 exit(APEXIT_CHILDINIT); 370 } 371 372 if (!ReadFile(pipe, &hScore, sizeof(hScore), 373 &BytesRead, (LPOVERLAPPED) NULL) 374 || (BytesRead != sizeof(hScore))) { 375 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 376 "Child %lu: Unable to retrieve the scoreboard from the parent", my_pid); 377 exit(APEXIT_CHILDINIT); 378 } 379 *scoreboard_shm = NULL; 380 if ((rv = apr_os_shm_put(scoreboard_shm, &hScore, s->process->pool)) 381 != APR_SUCCESS) { 382 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 383 "Child %lu: Unable to access the scoreboard from the parent", my_pid); 384 exit(APEXIT_CHILDINIT); 385 } 386 387 rv = ap_reopen_scoreboard(s->process->pool, scoreboard_shm, 1); 388 if (rv || !(sb_shared = apr_shm_baseaddr_get(*scoreboard_shm))) { 389 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, 390 "Child %lu: Unable to reopen the scoreboard from the parent", my_pid); 391 exit(APEXIT_CHILDINIT); 392 } 393 /* We must 'initialize' the scoreboard to relink all the 394 * process-local pointer arrays into the shared memory block. 395 */ 396 ap_init_scoreboard(sb_shared); 397 398 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, 399 "Child %lu: Retrieved our scoreboard from the parent.", my_pid); 400} 401 402 403static int send_handles_to_child(apr_pool_t *p, 404 HANDLE child_ready_event, 405 HANDLE child_exit_event, 406 apr_proc_mutex_t *child_start_mutex, 407 apr_shm_t *scoreboard_shm, 408 HANDLE hProcess, 409 apr_file_t *child_in) 410{ 411 apr_status_t rv; 412 HANDLE hCurrentProcess = GetCurrentProcess(); 413 HANDLE hDup; 414 HANDLE os_start; 415 HANDLE hScore; 416 apr_size_t BytesWritten; 417 418 if (!DuplicateHandle(hCurrentProcess, child_ready_event, hProcess, &hDup, 419 EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) { 420 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 421 "Parent: Unable to duplicate the ready event handle for the child"); 422 return -1; 423 } 424 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten)) 425 != APR_SUCCESS) { 426 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 427 "Parent: Unable to send the exit event handle to the child"); 428 return -1; 429 } 430 if (!DuplicateHandle(hCurrentProcess, child_exit_event, hProcess, &hDup, 431 EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, 0)) { 432 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 433 "Parent: Unable to duplicate the exit event handle for the child"); 434 return -1; 435 } 436 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten)) 437 != APR_SUCCESS) { 438 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 439 "Parent: Unable to send the exit event handle to the child"); 440 return -1; 441 } 442 if ((rv = apr_os_proc_mutex_get(&os_start, child_start_mutex)) != APR_SUCCESS) { 443 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 444 "Parent: Unable to retrieve the start mutex for the child"); 445 return -1; 446 } 447 if (!DuplicateHandle(hCurrentProcess, os_start, hProcess, &hDup, 448 SYNCHRONIZE, FALSE, 0)) { 449 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 450 "Parent: Unable to duplicate the start mutex to the child"); 451 return -1; 452 } 453 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten)) 454 != APR_SUCCESS) { 455 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 456 "Parent: Unable to send the start mutex to the child"); 457 return -1; 458 } 459 if ((rv = apr_os_shm_get(&hScore, scoreboard_shm)) != APR_SUCCESS) { 460 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 461 "Parent: Unable to retrieve the scoreboard handle for the child"); 462 return -1; 463 } 464 if (!DuplicateHandle(hCurrentProcess, hScore, hProcess, &hDup, 465 FILE_MAP_READ | FILE_MAP_WRITE, FALSE, 0)) { 466 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 467 "Parent: Unable to duplicate the scoreboard handle to the child"); 468 return -1; 469 } 470 if ((rv = apr_file_write_full(child_in, &hDup, sizeof(hDup), &BytesWritten)) 471 != APR_SUCCESS) { 472 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 473 "Parent: Unable to send the scoreboard handle to the child"); 474 return -1; 475 } 476 477 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, 478 "Parent: Sent the scoreboard to the child"); 479 return 0; 480} 481 482 483/* 484 * get_listeners_from_parent() 485 * The listen sockets are opened in the parent. This function, which runs 486 * exclusively in the child process, receives them from the parent and 487 * makes them availeble in the child. 488 */ 489static void get_listeners_from_parent(server_rec *s) 490{ 491 WSAPROTOCOL_INFO WSAProtocolInfo; 492 ap_listen_rec *lr; 493 DWORD BytesRead; 494 int lcnt = 0; 495 SOCKET nsd; 496 497 /* Set up a default listener if necessary */ 498 if (ap_listeners == NULL) { 499 ap_listen_rec *lr; 500 lr = apr_palloc(s->process->pool, sizeof(ap_listen_rec)); 501 lr->sd = NULL; 502 lr->next = ap_listeners; 503 ap_listeners = lr; 504 } 505 506 /* Open the pipe to the parent process to receive the inherited socket 507 * data. The sockets have been set to listening in the parent process. 508 * 509 * *** We now do this was back in winnt_rewrite_args 510 * pipe = GetStdHandle(STD_INPUT_HANDLE); 511 */ 512 for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) { 513 if (!ReadFile(pipe, &WSAProtocolInfo, sizeof(WSAPROTOCOL_INFO), 514 &BytesRead, (LPOVERLAPPED) NULL)) { 515 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 516 "setup_inherited_listeners: Unable to read socket data from parent"); 517 exit(APEXIT_CHILDINIT); 518 } 519 nsd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, 520 &WSAProtocolInfo, 0, 0); 521 if (nsd == INVALID_SOCKET) { 522 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf, 523 "Child %lu: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid); 524 exit(APEXIT_CHILDINIT); 525 } 526 527 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { 528 HANDLE hProcess = GetCurrentProcess(); 529 HANDLE dup; 530 if (DuplicateHandle(hProcess, (HANDLE) nsd, hProcess, &dup, 531 0, FALSE, DUPLICATE_SAME_ACCESS)) { 532 closesocket(nsd); 533 nsd = (SOCKET) dup; 534 } 535 } 536 else { 537 /* A different approach. Many users report errors such as 538 * (32538)An operation was attempted on something that is not 539 * a socket. : Parent: WSADuplicateSocket failed... 540 * 541 * This appears that the duplicated handle is no longer recognized 542 * as a socket handle. SetHandleInformation should overcome that 543 * problem by not altering the handle identifier. But this won't 544 * work on 9x - it's unsupported. 545 */ 546 if (!SetHandleInformation((HANDLE)nsd, HANDLE_FLAG_INHERIT, 0)) { 547 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), ap_server_conf, 548 "set_listeners_noninheritable: SetHandleInformation failed."); 549 } 550 } 551 apr_os_sock_put(&lr->sd, &nsd, s->process->pool); 552 } 553 554 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, 555 "Child %lu: retrieved %d listeners from parent", my_pid, lcnt); 556} 557 558 559static int send_listeners_to_child(apr_pool_t *p, DWORD dwProcessId, 560 apr_file_t *child_in) 561{ 562 apr_status_t rv; 563 int lcnt = 0; 564 ap_listen_rec *lr; 565 LPWSAPROTOCOL_INFO lpWSAProtocolInfo; 566 apr_size_t BytesWritten; 567 568 /* Run the chain of open sockets. For each socket, duplicate it 569 * for the target process then send the WSAPROTOCOL_INFO 570 * (returned by dup socket) to the child. 571 */ 572 for (lr = ap_listeners; lr; lr = lr->next, ++lcnt) { 573 apr_os_sock_t nsd; 574 lpWSAProtocolInfo = apr_pcalloc(p, sizeof(WSAPROTOCOL_INFO)); 575 apr_os_sock_get(&nsd, lr->sd); 576 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, ap_server_conf, 577 "Parent: Duplicating socket %d and sending it to child process %lu", 578 nsd, dwProcessId); 579 if (WSADuplicateSocket(nsd, dwProcessId, 580 lpWSAProtocolInfo) == SOCKET_ERROR) { 581 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_netos_error(), ap_server_conf, 582 "Parent: WSADuplicateSocket failed for socket %d. Check the FAQ.", nsd); 583 return -1; 584 } 585 586 if ((rv = apr_file_write_full(child_in, lpWSAProtocolInfo, 587 sizeof(WSAPROTOCOL_INFO), &BytesWritten)) 588 != APR_SUCCESS) { 589 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 590 "Parent: Unable to write duplicated socket %d to the child.", nsd); 591 return -1; 592 } 593 } 594 595 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, 596 "Parent: Sent %d listeners to child %lu", lcnt, dwProcessId); 597 return 0; 598} 599 600enum waitlist_e { 601 waitlist_ready = 0, 602 waitlist_term = 1 603}; 604 605static int create_process(apr_pool_t *p, HANDLE *child_proc, HANDLE *child_exit_event, 606 DWORD *child_pid) 607{ 608 /* These NEVER change for the lifetime of this parent 609 */ 610 static char **args = NULL; 611 static char pidbuf[28]; 612 613 apr_status_t rv; 614 apr_pool_t *ptemp; 615 apr_procattr_t *attr; 616 apr_proc_t new_child; 617 apr_file_t *child_out, *child_err; 618 HANDLE hExitEvent; 619 HANDLE waitlist[2]; /* see waitlist_e */ 620 char *cmd; 621 char *cwd; 622 char **env; 623 int envc; 624 625 apr_pool_create_ex(&ptemp, p, NULL, NULL); 626 627 /* Build the command line. Should look something like this: 628 * C:/apache/bin/httpd.exe -f ap_server_confname 629 * First, get the path to the executable... 630 */ 631 apr_procattr_create(&attr, ptemp); 632 apr_procattr_cmdtype_set(attr, APR_PROGRAM); 633 apr_procattr_detach_set(attr, 1); 634 if (((rv = apr_filepath_get(&cwd, 0, ptemp)) != APR_SUCCESS) 635 || ((rv = apr_procattr_dir_set(attr, cwd)) != APR_SUCCESS)) { 636 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 637 "Parent: Failed to get the current path"); 638 } 639 640 if (!args) { 641 /* Build the args array, only once since it won't change 642 * for the lifetime of this parent process. 643 */ 644 if ((rv = ap_os_proc_filepath(&cmd, ptemp)) 645 != APR_SUCCESS) { 646 ap_log_error(APLOG_MARK, APLOG_CRIT, ERROR_BAD_PATHNAME, ap_server_conf, 647 "Parent: Failed to get full path of %s", 648 ap_server_conf->process->argv[0]); 649 apr_pool_destroy(ptemp); 650 return -1; 651 } 652 653 args = malloc((ap_server_conf->process->argc + 1) * sizeof (char*)); 654 memcpy(args + 1, ap_server_conf->process->argv + 1, 655 (ap_server_conf->process->argc - 1) * sizeof (char*)); 656 args[0] = malloc(strlen(cmd) + 1); 657 strcpy(args[0], cmd); 658 args[ap_server_conf->process->argc] = NULL; 659 } 660 else { 661 cmd = args[0]; 662 } 663 664 /* Create a pipe to send handles to the child */ 665 if ((rv = apr_procattr_io_set(attr, APR_FULL_BLOCK, 666 APR_NO_PIPE, APR_NO_PIPE)) != APR_SUCCESS) { 667 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 668 "Parent: Unable to create child stdin pipe."); 669 apr_pool_destroy(ptemp); 670 return -1; 671 } 672 673 /* httpd-2.0/2.2 specific to work around apr_proc_create bugs */ 674 /* set "NUL" as sysout for the child */ 675 if (((rv = apr_file_open(&child_out, "NUL", APR_WRITE | APR_READ, APR_OS_DEFAULT,p)) 676 != APR_SUCCESS) || 677 ((rv = apr_procattr_child_out_set(attr, child_out, NULL)) 678 != APR_SUCCESS)) { 679 ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, 680 "Parent: Could not set child process stdout"); 681 } 682 if (((rv = apr_file_open_stderr(&child_err, p)) 683 != APR_SUCCESS) || 684 ((rv = apr_procattr_child_err_set(attr, child_err, NULL)) 685 != APR_SUCCESS)) { 686 ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, 687 "Parent: Could not set child process stderr"); 688 } 689 690 /* Create the child_ready_event */ 691 waitlist[waitlist_ready] = CreateEvent(NULL, TRUE, FALSE, NULL); 692 if (!waitlist[waitlist_ready]) { 693 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 694 "Parent: Could not create ready event for child process"); 695 apr_pool_destroy (ptemp); 696 return -1; 697 } 698 699 /* Create the child_exit_event */ 700 hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 701 if (!hExitEvent) { 702 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 703 "Parent: Could not create exit event for child process"); 704 apr_pool_destroy(ptemp); 705 CloseHandle(waitlist[waitlist_ready]); 706 return -1; 707 } 708 709 /* Build the env array */ 710 for (envc = 0; _environ[envc]; ++envc) { 711 ; 712 } 713 env = apr_palloc(ptemp, (envc + 2) * sizeof (char*)); 714 memcpy(env, _environ, envc * sizeof (char*)); 715 apr_snprintf(pidbuf, sizeof(pidbuf), "AP_PARENT_PID=%lu", parent_pid); 716 env[envc] = pidbuf; 717 env[envc + 1] = NULL; 718 719 rv = apr_proc_create(&new_child, cmd, (const char * const *)args, 720 (const char * const *)env, attr, ptemp); 721 if (rv != APR_SUCCESS) { 722 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, 723 "Parent: Failed to create the child process."); 724 apr_pool_destroy(ptemp); 725 CloseHandle(hExitEvent); 726 CloseHandle(waitlist[waitlist_ready]); 727 CloseHandle(new_child.hproc); 728 return -1; 729 } 730 apr_file_close(child_out); 731 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf, 732 "Parent: Created child process %d", new_child.pid); 733 734 if (send_handles_to_child(ptemp, waitlist[waitlist_ready], hExitEvent, 735 start_mutex, ap_scoreboard_shm, 736 new_child.hproc, new_child.in)) { 737 /* 738 * This error is fatal, mop up the child and move on 739 * We toggle the child's exit event to cause this child 740 * to quit even as it is attempting to start. 741 */ 742 SetEvent(hExitEvent); 743 apr_pool_destroy(ptemp); 744 CloseHandle(hExitEvent); 745 CloseHandle(waitlist[waitlist_ready]); 746 CloseHandle(new_child.hproc); 747 return -1; 748 } 749 750 /* Important: 751 * Give the child process a chance to run before dup'ing the sockets. 752 * We have already set the listening sockets noninheritable, but if 753 * WSADuplicateSocket runs before the child process initializes 754 * the listeners will be inherited anyway. 755 */ 756 waitlist[waitlist_term] = new_child.hproc; 757 rv = WaitForMultipleObjects(2, waitlist, FALSE, INFINITE); 758 CloseHandle(waitlist[waitlist_ready]); 759 if (rv != WAIT_OBJECT_0) { 760 /* 761 * Outch... that isn't a ready signal. It's dead, Jim! 762 */ 763 SetEvent(hExitEvent); 764 apr_pool_destroy(ptemp); 765 CloseHandle(hExitEvent); 766 CloseHandle(new_child.hproc); 767 return -1; 768 } 769 770 if (send_listeners_to_child(ptemp, new_child.pid, new_child.in)) { 771 /* 772 * This error is fatal, mop up the child and move on 773 * We toggle the child's exit event to cause this child 774 * to quit even as it is attempting to start. 775 */ 776 SetEvent(hExitEvent); 777 apr_pool_destroy(ptemp); 778 CloseHandle(hExitEvent); 779 CloseHandle(new_child.hproc); 780 return -1; 781 } 782 783 apr_file_close(new_child.in); 784 785 *child_exit_event = hExitEvent; 786 *child_proc = new_child.hproc; 787 *child_pid = new_child.pid; 788 789 return 0; 790} 791 792/*********************************************************************** 793 * master_main() 794 * master_main() runs in the parent process. It creates the child 795 * process which handles HTTP requests then waits on one of three 796 * events: 797 * 798 * restart_event 799 * ------------- 800 * The restart event causes master_main to start a new child process and 801 * tells the old child process to exit (by setting the child_exit_event). 802 * The restart event is set as a result of one of the following: 803 * 1. An apache -k restart command on the command line 804 * 2. A command received from Windows service manager which gets 805 * translated into an ap_signal_parent(SIGNAL_PARENT_RESTART) 806 * call by code in service.c. 807 * 3. The child process calling ap_signal_parent(SIGNAL_PARENT_RESTART) 808 * as a result of hitting MaxRequestsPerChild. 809 * 810 * shutdown_event 811 * -------------- 812 * The shutdown event causes master_main to tell the child process to 813 * exit and that the server is shutting down. The shutdown event is 814 * set as a result of one of the following: 815 * 1. An apache -k shutdown command on the command line 816 * 2. A command received from Windows service manager which gets 817 * translated into an ap_signal_parent(SIGNAL_PARENT_SHUTDOWN) 818 * call by code in service.c. 819 * 820 * child process handle 821 * -------------------- 822 * The child process handle will be signaled if the child process 823 * exits for any reason. In a normal running server, the signaling 824 * of this event means that the child process has exited prematurely 825 * due to a seg fault or other irrecoverable error. For server 826 * robustness, master_main will restart the child process under this 827 * condtion. 828 * 829 * master_main uses the child_exit_event to signal the child process 830 * to exit. 831 **********************************************************************/ 832#define NUM_WAIT_HANDLES 3 833#define CHILD_HANDLE 0 834#define SHUTDOWN_HANDLE 1 835#define RESTART_HANDLE 2 836static int master_main(server_rec *s, HANDLE shutdown_event, HANDLE restart_event) 837{ 838 int rv, cld; 839 int child_created; 840 int restart_pending; 841 int shutdown_pending; 842 HANDLE child_exit_event; 843 HANDLE event_handles[NUM_WAIT_HANDLES]; 844 DWORD child_pid; 845 846 child_created = restart_pending = shutdown_pending = 0; 847 848 event_handles[SHUTDOWN_HANDLE] = shutdown_event; 849 event_handles[RESTART_HANDLE] = restart_event; 850 851 /* Create a single child process */ 852 rv = create_process(pconf, &event_handles[CHILD_HANDLE], 853 &child_exit_event, &child_pid); 854 if (rv < 0) 855 { 856 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 857 "master_main: create child process failed. Exiting."); 858 shutdown_pending = 1; 859 goto die_now; 860 } 861 862 child_created = 1; 863 864 if (!strcasecmp(signal_arg, "runservice")) { 865 mpm_service_started(); 866 } 867 868 /* Update the scoreboard. Note that there is only a single active 869 * child at once. 870 */ 871 ap_scoreboard_image->parent[0].quiescing = 0; 872 ap_scoreboard_image->parent[0].pid = child_pid; 873 874 /* Wait for shutdown or restart events or for child death */ 875 winnt_mpm_state = AP_MPMQ_RUNNING; 876 rv = WaitForMultipleObjects(NUM_WAIT_HANDLES, (HANDLE *) event_handles, FALSE, INFINITE); 877 cld = rv - WAIT_OBJECT_0; 878 if (rv == WAIT_FAILED) { 879 /* Something serious is wrong */ 880 ap_log_error(APLOG_MARK,APLOG_CRIT, apr_get_os_error(), ap_server_conf, 881 "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown"); 882 shutdown_pending = 1; 883 } 884 else if (rv == WAIT_TIMEOUT) { 885 /* Hey, this cannot happen */ 886 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s, 887 "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT"); 888 shutdown_pending = 1; 889 } 890 else if (cld == SHUTDOWN_HANDLE) { 891 /* shutdown_event signalled */ 892 shutdown_pending = 1; 893 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, s, 894 "Parent: Received shutdown signal -- Shutting down the server."); 895 if (ResetEvent(shutdown_event) == 0) { 896 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s, 897 "ResetEvent(shutdown_event)"); 898 } 899 } 900 else if (cld == RESTART_HANDLE) { 901 /* Received a restart event. Prepare the restart_event to be reused 902 * then signal the child process to exit. 903 */ 904 restart_pending = 1; 905 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, 906 "Parent: Received restart signal -- Restarting the server."); 907 if (ResetEvent(restart_event) == 0) { 908 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s, 909 "Parent: ResetEvent(restart_event) failed."); 910 } 911 if (SetEvent(child_exit_event) == 0) { 912 ap_log_error(APLOG_MARK, APLOG_ERR, apr_get_os_error(), s, 913 "Parent: SetEvent for child process %pp failed.", 914 event_handles[CHILD_HANDLE]); 915 } 916 /* Don't wait to verify that the child process really exits, 917 * just move on with the restart. 918 */ 919 CloseHandle(event_handles[CHILD_HANDLE]); 920 event_handles[CHILD_HANDLE] = NULL; 921 } 922 else { 923 /* The child process exited prematurely due to a fatal error. */ 924 DWORD exitcode; 925 if (!GetExitCodeProcess(event_handles[CHILD_HANDLE], &exitcode)) { 926 /* HUH? We did exit, didn't we? */ 927 exitcode = APEXIT_CHILDFATAL; 928 } 929 if ( exitcode == APEXIT_CHILDFATAL 930 || exitcode == APEXIT_CHILDINIT 931 || exitcode == APEXIT_INIT) { 932 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, ap_server_conf, 933 "Parent: child process exited with status %lu -- Aborting.", exitcode); 934 shutdown_pending = 1; 935 } 936 else { 937 int i; 938 restart_pending = 1; 939 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf, 940 "Parent: child process exited with status %lu -- Restarting.", exitcode); 941 for (i = 0; i < ap_threads_per_child; i++) { 942 ap_update_child_status_from_indexes(0, i, SERVER_DEAD, NULL); 943 } 944 } 945 CloseHandle(event_handles[CHILD_HANDLE]); 946 event_handles[CHILD_HANDLE] = NULL; 947 } 948 if (restart_pending) { 949 ++ap_my_generation; 950 ap_scoreboard_image->global->running_generation = ap_my_generation; 951 } 952die_now: 953 if (shutdown_pending) 954 { 955 int timeout = 30000; /* Timeout is milliseconds */ 956 winnt_mpm_state = AP_MPMQ_STOPPING; 957 958 if (!child_created) { 959 return 0; /* Tell the caller we do not want to restart */ 960 } 961 962 /* This shutdown is only marginally graceful. We will give the 963 * child a bit of time to exit gracefully. If the time expires, 964 * the child will be wacked. 965 */ 966 if (!strcasecmp(signal_arg, "runservice")) { 967 mpm_service_stopping(); 968 } 969 /* Signal the child processes to exit */ 970 if (SetEvent(child_exit_event) == 0) { 971 ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_os_error(), ap_server_conf, 972 "Parent: SetEvent for child process %pp failed", 973 event_handles[CHILD_HANDLE]); 974 } 975 if (event_handles[CHILD_HANDLE]) { 976 rv = WaitForSingleObject(event_handles[CHILD_HANDLE], timeout); 977 if (rv == WAIT_OBJECT_0) { 978 ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf, 979 "Parent: Child process exited successfully."); 980 CloseHandle(event_handles[CHILD_HANDLE]); 981 event_handles[CHILD_HANDLE] = NULL; 982 } 983 else { 984 ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf, 985 "Parent: Forcing termination of child process %pp", 986 event_handles[CHILD_HANDLE]); 987 TerminateProcess(event_handles[CHILD_HANDLE], 1); 988 CloseHandle(event_handles[CHILD_HANDLE]); 989 event_handles[CHILD_HANDLE] = NULL; 990 } 991 } 992 CloseHandle(child_exit_event); 993 return 0; /* Tell the caller we do not want to restart */ 994 } 995 winnt_mpm_state = AP_MPMQ_STARTING; 996 CloseHandle(child_exit_event); 997 return 1; /* Tell the caller we want a restart */ 998} 999 1000/* service_nt_main_fn needs to append the StartService() args 1001 * outside of our call stack and thread as the service starts... 1002 */ 1003apr_array_header_t *mpm_new_argv; 1004 1005/* Remember service_to_start failures to log and fail in pre_config. 1006 * Remember inst_argc and inst_argv for installing or starting the 1007 * service after we preflight the config. 1008 */ 1009 1010AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result) 1011{ 1012 switch(query_code){ 1013 case AP_MPMQ_MAX_DAEMON_USED: 1014 *result = MAXIMUM_WAIT_OBJECTS; 1015 return APR_SUCCESS; 1016 case AP_MPMQ_IS_THREADED: 1017 *result = AP_MPMQ_STATIC; 1018 return APR_SUCCESS; 1019 case AP_MPMQ_IS_FORKED: 1020 *result = AP_MPMQ_NOT_SUPPORTED; 1021 return APR_SUCCESS; 1022 case AP_MPMQ_HARD_LIMIT_DAEMONS: 1023 *result = HARD_SERVER_LIMIT; 1024 return APR_SUCCESS; 1025 case AP_MPMQ_HARD_LIMIT_THREADS: 1026 *result = thread_limit; 1027 return APR_SUCCESS; 1028 case AP_MPMQ_MAX_THREADS: 1029 *result = ap_threads_per_child; 1030 return APR_SUCCESS; 1031 case AP_MPMQ_MIN_SPARE_DAEMONS: 1032 *result = 0; 1033 return APR_SUCCESS; 1034 case AP_MPMQ_MIN_SPARE_THREADS: 1035 *result = 0; 1036 return APR_SUCCESS; 1037 case AP_MPMQ_MAX_SPARE_DAEMONS: 1038 *result = 0; 1039 return APR_SUCCESS; 1040 case AP_MPMQ_MAX_SPARE_THREADS: 1041 *result = 0; 1042 return APR_SUCCESS; 1043 case AP_MPMQ_MAX_REQUESTS_DAEMON: 1044 *result = ap_max_requests_per_child; 1045 return APR_SUCCESS; 1046 case AP_MPMQ_MAX_DAEMONS: 1047 *result = 0; 1048 return APR_SUCCESS; 1049 case AP_MPMQ_MPM_STATE: 1050 *result = winnt_mpm_state; 1051 return APR_SUCCESS; 1052 } 1053 return APR_ENOTIMPL; 1054} 1055 1056#define SERVICE_UNSET (-1) 1057static apr_status_t service_set = SERVICE_UNSET; 1058static apr_status_t service_to_start_success; 1059static int inst_argc; 1060static const char * const *inst_argv; 1061static const char *service_name = NULL; 1062 1063static void winnt_rewrite_args(process_rec *process) 1064{ 1065 /* Handle the following SCM aspects in this phase: 1066 * 1067 * -k runservice [transition for WinNT, nothing for Win9x] 1068 * -k install 1069 * -k config 1070 * -k uninstall 1071 * -k stop 1072 * -k shutdown (same as -k stop). Maintained for backward compatability. 1073 * 1074 * We can't leave this phase until we know our identity 1075 * and modify the command arguments appropriately. 1076 * 1077 * We do not care if the .conf file exists or is parsable when 1078 * attempting to stop or uninstall a service. 1079 */ 1080 apr_status_t rv; 1081 char *def_server_root; 1082 char *binpath; 1083 char optbuf[3]; 1084 const char *optarg; 1085 int fixed_args; 1086 char *pid; 1087 apr_getopt_t *opt; 1088 int running_as_service = 1; 1089 int errout = 0; 1090 1091 pconf = process->pconf; 1092 1093 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); 1094 GetVersionEx(&osver); 1095 1096 /* AP_PARENT_PID is only valid in the child */ 1097 pid = getenv("AP_PARENT_PID"); 1098 if (pid) 1099 { 1100 HANDLE filehand; 1101 HANDLE hproc = GetCurrentProcess(); 1102 1103 /* This is the child */ 1104 my_pid = GetCurrentProcessId(); 1105 parent_pid = (DWORD) atol(pid); 1106 1107 /* Prevent holding open the (nonexistant) console */ 1108 ap_real_exit_code = 0; 1109 1110 /* The parent gave us stdin, we need to remember this 1111 * handle, and no longer inherit it at our children 1112 * (we can't slurp it up now, we just aren't ready yet). 1113 * The original handle is closed below, at apr_file_dup2() 1114 */ 1115 pipe = GetStdHandle(STD_INPUT_HANDLE); 1116 if (DuplicateHandle(hproc, pipe, 1117 hproc, &filehand, 0, FALSE, 1118 DUPLICATE_SAME_ACCESS)) { 1119 pipe = filehand; 1120 } 1121 1122 /* The parent gave us stdout of the NUL device, 1123 * and expects us to suck up stdin of all of our 1124 * shared handles and data from the parent. 1125 * Don't infect child processes with our stdin 1126 * handle, use another handle to NUL! 1127 */ 1128 { 1129 apr_file_t *infile, *outfile; 1130 if ((apr_file_open_stdout(&outfile, process->pool) == APR_SUCCESS) 1131 && (apr_file_open_stdin(&infile, process->pool) == APR_SUCCESS)) 1132 apr_file_dup2(infile, outfile, process->pool); 1133 } 1134 1135 /* This child needs the existing stderr opened for logging, 1136 * already 1137 */ 1138 1139 /* The parent is responsible for providing the 1140 * COMPLETE ARGUMENTS REQUIRED to the child. 1141 * 1142 * No further argument parsing is needed, but 1143 * for good measure we will provide a simple 1144 * signal string for later testing. 1145 */ 1146 signal_arg = "runchild"; 1147 return; 1148 } 1149 1150 /* This is the parent, we have a long way to go :-) */ 1151 parent_pid = my_pid = GetCurrentProcessId(); 1152 1153 /* This behavior is voided by setting real_exit_code to 0 */ 1154 atexit(hold_console_open_on_error); 1155 1156 /* Rewrite process->argv[]; 1157 * 1158 * strip out -k signal into signal_arg 1159 * strip out -n servicename and set the names 1160 * add default -d serverroot from the path of this executable 1161 * 1162 * The end result will look like: 1163 * 1164 * The invocation command (%0) 1165 * The -d serverroot default from the running executable 1166 * The requested service's (-n) registry ConfigArgs 1167 * The WinNT SCM's StartService() args 1168 */ 1169 if ((rv = ap_os_proc_filepath(&binpath, process->pconf)) 1170 != APR_SUCCESS) { 1171 ap_log_error(APLOG_MARK,APLOG_CRIT, rv, NULL, 1172 "Failed to get the full path of %s", process->argv[0]); 1173 exit(APEXIT_INIT); 1174 } 1175 /* WARNING: There is an implict assumption here that the 1176 * executable resides in ServerRoot or ServerRoot\bin 1177 */ 1178 def_server_root = (char *) apr_filepath_name_get(binpath); 1179 if (def_server_root > binpath) { 1180 *(def_server_root - 1) = '\0'; 1181 def_server_root = (char *) apr_filepath_name_get(binpath); 1182 if (!strcasecmp(def_server_root, "bin")) 1183 *(def_server_root - 1) = '\0'; 1184 } 1185 apr_filepath_merge(&def_server_root, NULL, binpath, 1186 APR_FILEPATH_TRUENAME, process->pool); 1187 1188 /* Use process->pool so that the rewritten argv 1189 * lasts for the lifetime of the server process, 1190 * because pconf will be destroyed after the 1191 * initial pre-flight of the config parser. 1192 */ 1193 mpm_new_argv = apr_array_make(process->pool, process->argc + 2, 1194 sizeof(const char *)); 1195 *(const char **)apr_array_push(mpm_new_argv) = process->argv[0]; 1196 *(const char **)apr_array_push(mpm_new_argv) = "-d"; 1197 *(const char **)apr_array_push(mpm_new_argv) = def_server_root; 1198 1199 fixed_args = mpm_new_argv->nelts; 1200 1201 optbuf[0] = '-'; 1202 optbuf[2] = '\0'; 1203 apr_getopt_init(&opt, process->pool, process->argc, process->argv); 1204 opt->errfn = NULL; 1205 while ((rv = apr_getopt(opt, "wn:k:" AP_SERVER_BASEARGS, 1206 optbuf + 1, &optarg)) == APR_SUCCESS) { 1207 switch (optbuf[1]) { 1208 1209 /* Shortcuts; include the -w option to hold the window open on error. 1210 * This must not be toggled once we reset ap_real_exit_code to 0! 1211 */ 1212 case 'w': 1213 if (ap_real_exit_code) 1214 ap_real_exit_code = 2; 1215 break; 1216 1217 case 'n': 1218 service_set = mpm_service_set_name(process->pool, &service_name, 1219 optarg); 1220 break; 1221 1222 case 'k': 1223 signal_arg = optarg; 1224 break; 1225 1226 case 'E': 1227 errout = 1; 1228 /* Fall through so the Apache main() handles the 'E' arg */ 1229 default: 1230 *(const char **)apr_array_push(mpm_new_argv) = 1231 apr_pstrdup(process->pool, optbuf); 1232 1233 if (optarg) { 1234 *(const char **)apr_array_push(mpm_new_argv) = optarg; 1235 } 1236 break; 1237 } 1238 } 1239 1240 /* back up to capture the bad argument */ 1241 if (rv == APR_BADCH || rv == APR_BADARG) { 1242 opt->ind--; 1243 } 1244 1245 while (opt->ind < opt->argc) { 1246 *(const char **)apr_array_push(mpm_new_argv) = 1247 apr_pstrdup(process->pool, opt->argv[opt->ind++]); 1248 } 1249 1250 /* Track the number of args actually entered by the user */ 1251 inst_argc = mpm_new_argv->nelts - fixed_args; 1252 1253 /* Provide a default 'run' -k arg to simplify signal_arg tests */ 1254 if (!signal_arg) 1255 { 1256 signal_arg = "run"; 1257 running_as_service = 0; 1258 } 1259 1260 if (!strcasecmp(signal_arg, "runservice")) 1261 { 1262 /* Start the NT Service _NOW_ because the WinNT SCM is 1263 * expecting us to rapidly assume control of our own 1264 * process, the SCM will tell us our service name, and 1265 * may have extra StartService() command arguments to 1266 * add for us. 1267 * 1268 * The SCM will generally invoke the executable with 1269 * the c:\win\system32 default directory. This is very 1270 * lethal if folks use ServerRoot /foopath on windows 1271 * without a drive letter. Change to the default root 1272 * (path to apache root, above /bin) for safety. 1273 */ 1274 apr_filepath_set(def_server_root, process->pool); 1275 1276 /* Any other process has a console, so we don't to begin 1277 * a Win9x service until the configuration is parsed and 1278 * any command line errors are reported. 1279 * 1280 * We hold the return value so that we can die in pre_config 1281 * after logging begins, and the failure can land in the log. 1282 */ 1283 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) 1284 { 1285 apr_file_t *nullfile; 1286 1287 if (!errout) { 1288 mpm_nt_eventlog_stderr_open(service_name, process->pool); 1289 } 1290 service_to_start_success = mpm_service_to_start(&service_name, 1291 process->pool); 1292 if (service_to_start_success == APR_SUCCESS) { 1293 service_set = APR_SUCCESS; 1294 } 1295 1296 /* Open a null handle to soak stdout in this process. 1297 * Windows service processes are missing any file handle 1298 * usable for stdin/out/err. This was the cause of later 1299 * trouble with invocations of apr_file_open_stdout() 1300 */ 1301 if ((rv = apr_file_open(&nullfile, "NUL", 1302 APR_READ | APR_WRITE, APR_OS_DEFAULT, 1303 process->pool)) == APR_SUCCESS) { 1304 apr_file_t *nullstdout; 1305 if (apr_file_open_stdout(&nullstdout, process->pool) 1306 == APR_SUCCESS) 1307 apr_file_dup2(nullstdout, nullfile, process->pool); 1308 apr_file_close(nullfile); 1309 } 1310 } 1311 } 1312 1313 /* Get the default for any -k option, except run */ 1314 if (service_set == SERVICE_UNSET && strcasecmp(signal_arg, "run")) { 1315 service_set = mpm_service_set_name(process->pool, &service_name, 1316 AP_DEFAULT_SERVICE_NAME); 1317 } 1318 1319 if (!strcasecmp(signal_arg, "install")) /* -k install */ 1320 { 1321 if (service_set == APR_SUCCESS) 1322 { 1323 ap_log_error(APLOG_MARK,APLOG_ERR, 0, NULL, 1324 "%s: Service is already installed.", service_name); 1325 exit(APEXIT_INIT); 1326 } 1327 } 1328 else if (running_as_service) 1329 { 1330 if (service_set == APR_SUCCESS) 1331 { 1332 /* Attempt to Uninstall, or stop, before 1333 * we can read the arguments or .conf files 1334 */ 1335 if (!strcasecmp(signal_arg, "uninstall")) { 1336 rv = mpm_service_uninstall(); 1337 exit(rv); 1338 } 1339 1340 if ((!strcasecmp(signal_arg, "stop")) || 1341 (!strcasecmp(signal_arg, "shutdown"))) { 1342 mpm_signal_service(process->pool, 0); 1343 exit(0); 1344 } 1345 1346 rv = mpm_merge_service_args(process->pool, mpm_new_argv, 1347 fixed_args); 1348 if (rv == APR_SUCCESS) { 1349 ap_log_error(APLOG_MARK,APLOG_INFO, 0, NULL, 1350 "Using ConfigArgs of the installed service " 1351 "\"%s\".", service_name); 1352 } 1353 else { 1354 ap_log_error(APLOG_MARK,APLOG_WARNING, rv, NULL, 1355 "No installed ConfigArgs for the service " 1356 "\"%s\", using Apache defaults.", service_name); 1357 } 1358 } 1359 else 1360 { 1361 ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL, 1362 "No installed service named \"%s\".", service_name); 1363 exit(APEXIT_INIT); 1364 } 1365 } 1366 if (strcasecmp(signal_arg, "install") && service_set && service_set != SERVICE_UNSET) 1367 { 1368 ap_log_error(APLOG_MARK,APLOG_ERR, service_set, NULL, 1369 "No installed service named \"%s\".", service_name); 1370 exit(APEXIT_INIT); 1371 } 1372 1373 /* Track the args actually entered by the user. 1374 * These will be used for the -k install parameters, as well as 1375 * for the -k start service override arguments. 1376 */ 1377 inst_argv = (const char * const *)mpm_new_argv->elts 1378 + mpm_new_argv->nelts - inst_argc; 1379 1380 /* Now, do service install or reconfigure then proceed to 1381 * post_config to test the installed configuration. 1382 */ 1383 if (!strcasecmp(signal_arg, "config")) { /* -k config */ 1384 /* Reconfigure the service */ 1385 rv = mpm_service_install(process->pool, inst_argc, inst_argv, 1); 1386 if (rv != APR_SUCCESS) { 1387 exit(rv); 1388 } 1389 1390 fprintf(stderr,"Testing httpd.conf....\n"); 1391 fprintf(stderr,"Errors reported here must be corrected before the " 1392 "service can be started.\n"); 1393 } 1394 else if (!strcasecmp(signal_arg, "install")) { /* -k install */ 1395 /* Install the service */ 1396 rv = mpm_service_install(process->pool, inst_argc, inst_argv, 0); 1397 if (rv != APR_SUCCESS) { 1398 exit(rv); 1399 } 1400 1401 fprintf(stderr,"Testing httpd.conf....\n"); 1402 fprintf(stderr,"Errors reported here must be corrected before the " 1403 "service can be started.\n"); 1404 } 1405 1406 process->argc = mpm_new_argv->nelts; 1407 process->argv = (const char * const *) mpm_new_argv->elts; 1408} 1409 1410 1411static int winnt_pre_config(apr_pool_t *pconf_, apr_pool_t *plog, apr_pool_t *ptemp) 1412{ 1413 /* Handle the following SCM aspects in this phase: 1414 * 1415 * -k runservice [WinNT errors logged from rewrite_args] 1416 */ 1417 1418 /* Initialize shared static objects. 1419 * TODO: Put config related statics into an sconf structure. 1420 */ 1421 pconf = pconf_; 1422 1423 if (ap_exists_config_define("ONE_PROCESS") || 1424 ap_exists_config_define("DEBUG")) 1425 one_process = -1; 1426 1427 if (!strcasecmp(signal_arg, "runservice") 1428 && (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) 1429 && (service_to_start_success != APR_SUCCESS)) { 1430 ap_log_error(APLOG_MARK,APLOG_CRIT, service_to_start_success, NULL, 1431 "%s: Unable to start the service manager.", 1432 service_name); 1433 exit(APEXIT_INIT); 1434 } 1435 1436 /* Win9x: disable AcceptEx */ 1437 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { 1438 use_acceptex = 0; 1439 } 1440 1441 ap_listen_pre_config(); 1442 ap_threads_per_child = DEFAULT_THREADS_PER_CHILD; 1443 ap_pid_fname = DEFAULT_PIDLOG; 1444 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD; 1445#ifdef AP_MPM_WANT_SET_MAX_MEM_FREE 1446 ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED; 1447#endif 1448 /* use_acceptex which is enabled by default is not available on Win9x. 1449 */ 1450 if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { 1451 use_acceptex = 0; 1452 } 1453 1454 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir)); 1455 1456 return OK; 1457} 1458 1459static int winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* s) 1460{ 1461 static int restart_num = 0; 1462 apr_status_t rv = 0; 1463 1464 /* Handle the following SCM aspects in this phase: 1465 * 1466 * -k install (catch and exit as install was handled in rewrite_args) 1467 * -k config (catch and exit as config was handled in rewrite_args) 1468 * -k start 1469 * -k restart 1470 * -k runservice [Win95, only once - after we parsed the config] 1471 * 1472 * because all of these signals are useful _only_ if there 1473 * is a valid conf\httpd.conf environment to start. 1474 * 1475 * We reached this phase by avoiding errors that would cause 1476 * these options to fail unexpectedly in another process. 1477 */ 1478 1479 if (!strcasecmp(signal_arg, "install")) { 1480 /* Service install happens in the rewrite_args hooks. If we 1481 * made it this far, the server configuration is clean and the 1482 * service will successfully start. 1483 */ 1484 apr_pool_destroy(s->process->pool); 1485 apr_terminate(); 1486 exit(0); 1487 } 1488 if (!strcasecmp(signal_arg, "config")) { 1489 /* Service reconfiguration happens in the rewrite_args hooks. If we 1490 * made it this far, the server configuration is clean and the 1491 * service will successfully start. 1492 */ 1493 apr_pool_destroy(s->process->pool); 1494 apr_terminate(); 1495 exit(0); 1496 } 1497 1498 if (!strcasecmp(signal_arg, "start")) { 1499 ap_listen_rec *lr; 1500 1501 /* Close the listening sockets. */ 1502 for (lr = ap_listeners; lr; lr = lr->next) { 1503 apr_socket_close(lr->sd); 1504 lr->active = 0; 1505 } 1506 rv = mpm_service_start(ptemp, inst_argc, inst_argv); 1507 apr_pool_destroy(s->process->pool); 1508 apr_terminate(); 1509 exit (rv); 1510 } 1511 1512 if (!strcasecmp(signal_arg, "restart")) { 1513 mpm_signal_service(ptemp, 1); 1514 apr_pool_destroy(s->process->pool); 1515 apr_terminate(); 1516 exit (rv); 1517 } 1518 1519 if (parent_pid == my_pid) 1520 { 1521 if (restart_num++ == 1) 1522 { 1523 /* This code should be run once in the parent and not run 1524 * across a restart 1525 */ 1526 PSECURITY_ATTRIBUTES sa = GetNullACL(); /* returns NULL if invalid (Win95?) */ 1527 setup_signal_names(apr_psprintf(pconf,"ap%lu", parent_pid)); 1528 1529 ap_log_pid(pconf, ap_pid_fname); 1530 1531 /* Create shutdown event, apPID_shutdown, where PID is the parent 1532 * Apache process ID. Shutdown is signaled by 'apache -k shutdown'. 1533 */ 1534 shutdown_event = CreateEvent(sa, FALSE, FALSE, signal_shutdown_name); 1535 if (!shutdown_event) { 1536 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 1537 "Parent: Cannot create shutdown event %s", signal_shutdown_name); 1538 CleanNullACL((void *)sa); 1539 return HTTP_INTERNAL_SERVER_ERROR; 1540 } 1541 1542 /* Create restart event, apPID_restart, where PID is the parent 1543 * Apache process ID. Restart is signaled by 'apache -k restart'. 1544 */ 1545 restart_event = CreateEvent(sa, FALSE, FALSE, signal_restart_name); 1546 if (!restart_event) { 1547 CloseHandle(shutdown_event); 1548 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf, 1549 "Parent: Cannot create restart event %s", signal_restart_name); 1550 CleanNullACL((void *)sa); 1551 return HTTP_INTERNAL_SERVER_ERROR; 1552 } 1553 CleanNullACL((void *)sa); 1554 1555 /* Now that we are flying at 15000 feet... 1556 * wipe out the Win95 service console, 1557 * signal the SCM the WinNT service started, or 1558 * if not a service, setup console handlers instead. 1559 */ 1560 if (!strcasecmp(signal_arg, "runservice")) 1561 { 1562 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT) 1563 { 1564 rv = mpm_service_to_start(&service_name, 1565 s->process->pool); 1566 if (rv != APR_SUCCESS) { 1567 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf, 1568 "%s: Unable to start the service manager.", 1569 service_name); 1570 return HTTP_INTERNAL_SERVER_ERROR; 1571 } 1572 } 1573 } 1574 1575 /* Create the start mutex, as an unnamed object for security. 1576 * Ths start mutex is used during a restart to prevent more than 1577 * one child process from entering the accept loop at once. 1578 */ 1579 rv = apr_proc_mutex_create(&start_mutex, NULL, 1580 APR_LOCK_DEFAULT, 1581 ap_server_conf->process->pool); 1582 if (rv != APR_SUCCESS) { 1583 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf, 1584 "%s: Unable to create the start_mutex.", 1585 service_name); 1586 return HTTP_INTERNAL_SERVER_ERROR; 1587 } 1588 } 1589 /* Always reset our console handler to be the first, even on a restart 1590 * because some modules (e.g. mod_perl) might have set a console 1591 * handler to terminate the process. 1592 */ 1593 if (strcasecmp(signal_arg, "runservice")) 1594 mpm_start_console_handler(); 1595 } 1596 else /* parent_pid != my_pid */ 1597 { 1598 mpm_start_child_console_handler(); 1599 } 1600 return OK; 1601} 1602 1603/* This really should be a post_config hook, but the error log is already 1604 * redirected by that point, so we need to do this in the open_logs phase. 1605 */ 1606static int winnt_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) 1607{ 1608 /* Initialize shared static objects. 1609 */ 1610 ap_server_conf = s; 1611 1612 if (parent_pid != my_pid) { 1613 return OK; 1614 } 1615 1616 /* We cannot initialize our listeners if we are restarting 1617 * (the parent process already has glomed on to them) 1618 * nor should we do so for service reconfiguration 1619 * (since the service may already be running.) 1620 */ 1621 if (!strcasecmp(signal_arg, "restart") 1622 || !strcasecmp(signal_arg, "config")) { 1623 return OK; 1624 } 1625 1626 if (ap_setup_listeners(s) < 1) { 1627 ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0, 1628 NULL, "no listening sockets available, shutting down"); 1629 return DONE; 1630 } 1631 1632 return OK; 1633} 1634 1635static void winnt_child_init(apr_pool_t *pchild, struct server_rec *s) 1636{ 1637 apr_status_t rv; 1638 1639 setup_signal_names(apr_psprintf(pchild,"ap%lu", parent_pid)); 1640 1641 /* This is a child process, not in single process mode */ 1642 if (!one_process) { 1643 /* Set up events and the scoreboard */ 1644 get_handles_from_parent(s, &exit_event, &start_mutex, 1645 &ap_scoreboard_shm); 1646 1647 /* Set up the listeners */ 1648 get_listeners_from_parent(s); 1649 1650 /* Done reading from the parent, close that channel */ 1651 CloseHandle(pipe); 1652 1653 ap_my_generation = ap_scoreboard_image->global->running_generation; 1654 } 1655 else { 1656 /* Single process mode - this lock doesn't even need to exist */ 1657 rv = apr_proc_mutex_create(&start_mutex, signal_name_prefix, 1658 APR_LOCK_DEFAULT, s->process->pool); 1659 if (rv != APR_SUCCESS) { 1660 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf, 1661 "%s child %lu: Unable to init the start_mutex.", 1662 service_name, my_pid); 1663 exit(APEXIT_CHILDINIT); 1664 } 1665 1666 /* Borrow the shutdown_even as our _child_ loop exit event */ 1667 exit_event = shutdown_event; 1668 } 1669} 1670 1671 1672AP_DECLARE(int) ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s ) 1673{ 1674 static int restart = 0; /* Default is "not a restart" */ 1675 1676 if (!restart) { 1677 first_thread_limit = thread_limit; 1678 } 1679 1680 if (changed_limit_at_restart) { 1681 ap_log_error(APLOG_MARK, APLOG_WARNING, APR_SUCCESS, ap_server_conf, 1682 "WARNING: Attempt to change ThreadLimit ignored " 1683 "during restart"); 1684 changed_limit_at_restart = 0; 1685 } 1686 1687 /* ### If non-graceful restarts are ever introduced - we need to rerun 1688 * the pre_mpm hook on subsequent non-graceful restarts. But Win32 1689 * has only graceful style restarts - and we need this hook to act 1690 * the same on Win32 as on Unix. 1691 */ 1692 if (!restart && ((parent_pid == my_pid) || one_process)) { 1693 /* Set up the scoreboard. */ 1694 if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) { 1695 return 1; 1696 } 1697 } 1698 1699 if ((parent_pid != my_pid) || one_process) 1700 { 1701 /* The child process or in one_process (debug) mode 1702 */ 1703 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf, 1704 "Child %lu: Child process is running", my_pid); 1705 1706 child_main(pconf); 1707 1708 ap_log_error(APLOG_MARK, APLOG_NOTICE, APR_SUCCESS, ap_server_conf, 1709 "Child %lu: Child process is exiting", my_pid); 1710 return 1; 1711 } 1712 else 1713 { 1714 /* A real-honest to goodness parent */ 1715 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, 1716 "%s configured -- resuming normal operations", 1717 ap_get_server_description()); 1718 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, 1719 "Server built: %s", ap_get_server_built()); 1720 1721 restart = master_main(ap_server_conf, shutdown_event, restart_event); 1722 1723 if (!restart) 1724 { 1725 /* Shutting down. Clean up... */ 1726 const char *pidfile = ap_server_root_relative (pconf, ap_pid_fname); 1727 1728 if (pidfile != NULL && unlink(pidfile) == 0) { 1729 ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, 1730 ap_server_conf, "removed PID file %s (pid=%ld)", 1731 pidfile, GetCurrentProcessId()); 1732 } 1733 apr_proc_mutex_destroy(start_mutex); 1734 1735 CloseHandle(restart_event); 1736 CloseHandle(shutdown_event); 1737 1738 return 1; 1739 } 1740 } 1741 1742 return 0; /* Restart */ 1743} 1744 1745static void winnt_hooks(apr_pool_t *p) 1746{ 1747 /* The prefork open_logs phase must run before the core's, or stderr 1748 * will be redirected to a file, and the messages won't print to the 1749 * console. 1750 */ 1751 static const char *const aszSucc[] = {"core.c", NULL}; 1752 1753 ap_hook_pre_config(winnt_pre_config, NULL, NULL, APR_HOOK_MIDDLE); 1754 ap_hook_post_config(winnt_post_config, NULL, NULL, 0); 1755 ap_hook_child_init(winnt_child_init, NULL, NULL, APR_HOOK_MIDDLE); 1756 ap_hook_open_logs(winnt_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE); 1757} 1758 1759AP_MODULE_DECLARE_DATA module mpm_winnt_module = { 1760 MPM20_MODULE_STUFF, 1761 winnt_rewrite_args, /* hook to run before apache parses args */ 1762 NULL, /* create per-directory config structure */ 1763 NULL, /* merge per-directory config structures */ 1764 NULL, /* create per-server config structure */ 1765 NULL, /* merge per-server config structures */ 1766 winnt_cmds, /* command apr_table_t */ 1767 winnt_hooks /* register_hooks */ 1768}; 1769 1770#endif /* def WIN32 */ 1771