server: explicitly call "shutdown" when catch CTRL-C or a signal
[openocd.git] / src / server / server.c
blobbc5856cccbc88c03ce91ee0c18d052559fdd6aae
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008 by Spencer Oliver *
9 * spen@spen-soft.co.uk *
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 * This program is distributed in the hope that it will be useful, *
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
19 * GNU General Public License for more details. *
20 * *
21 * You should have received a copy of the GNU General Public License *
22 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
23 ***************************************************************************/
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
29 #include "server.h"
30 #include <target/target.h>
31 #include <target/target_request.h>
32 #include <target/openrisc/jsp_server.h>
33 #include "openocd.h"
34 #include "tcl_server.h"
35 #include "telnet_server.h"
37 #include <signal.h>
39 #ifdef HAVE_NETDB_H
40 #include <netdb.h>
41 #endif
43 #ifndef _WIN32
44 #include <netinet/tcp.h>
45 #endif
47 static struct service *services;
49 enum shutdown_reason {
50 CONTINUE_MAIN_LOOP, /* stay in main event loop */
51 SHUTDOWN_REQUESTED, /* set by shutdown command; exit the event loop and quit the debugger */
52 SHUTDOWN_WITH_ERROR_CODE, /* set by shutdown command; quit with non-zero return code */
53 SHUTDOWN_WITH_SIGNAL_CODE /* set by sig_handler; exec shutdown then exit with signal as return code */
55 static enum shutdown_reason shutdown_openocd = CONTINUE_MAIN_LOOP;
57 /* store received signal to exit application by killing ourselves */
58 static int last_signal;
60 /* set the polling period to 100ms */
61 static int polling_period = 100;
63 /* address by name on which to listen for incoming TCP/IP connections */
64 static char *bindto_name;
66 static int add_connection(struct service *service, struct command_context *cmd_ctx)
68 socklen_t address_size;
69 struct connection *c, **p;
70 int retval;
71 int flag = 1;
73 c = malloc(sizeof(struct connection));
74 c->fd = -1;
75 c->fd_out = -1;
76 memset(&c->sin, 0, sizeof(c->sin));
77 c->cmd_ctx = copy_command_context(cmd_ctx);
78 c->service = service;
79 c->input_pending = 0;
80 c->priv = NULL;
81 c->next = NULL;
83 if (service->type == CONNECTION_TCP) {
84 address_size = sizeof(c->sin);
86 c->fd = accept(service->fd, (struct sockaddr *)&service->sin, &address_size);
87 c->fd_out = c->fd;
89 /* This increases performance dramatically for e.g. GDB load which
90 * does not have a sliding window protocol.
92 * Ignore errors from this fn as it probably just means less performance
94 setsockopt(c->fd, /* socket affected */
95 IPPROTO_TCP, /* set option at TCP level */
96 TCP_NODELAY, /* name of option */
97 (char *)&flag, /* the cast is historical cruft */
98 sizeof(int)); /* length of option value */
100 LOG_INFO("accepting '%s' connection on tcp/%s", service->name, service->port);
101 retval = service->new_connection(c);
102 if (retval != ERROR_OK) {
103 close_socket(c->fd);
104 LOG_ERROR("attempted '%s' connection rejected", service->name);
105 command_done(c->cmd_ctx);
106 free(c);
107 return retval;
109 } else if (service->type == CONNECTION_STDINOUT) {
110 c->fd = service->fd;
111 c->fd_out = fileno(stdout);
113 #ifdef _WIN32
114 /* we are using stdin/out so ignore ctrl-c under windoze */
115 SetConsoleCtrlHandler(NULL, TRUE);
116 #endif
118 /* do not check for new connections again on stdin */
119 service->fd = -1;
121 LOG_INFO("accepting '%s' connection from pipe", service->name);
122 retval = service->new_connection(c);
123 if (retval != ERROR_OK) {
124 LOG_ERROR("attempted '%s' connection rejected", service->name);
125 command_done(c->cmd_ctx);
126 free(c);
127 return retval;
129 } else if (service->type == CONNECTION_PIPE) {
130 c->fd = service->fd;
131 /* do not check for new connections again on stdin */
132 service->fd = -1;
134 char *out_file = alloc_printf("%so", service->port);
135 c->fd_out = open(out_file, O_WRONLY);
136 free(out_file);
137 if (c->fd_out == -1) {
138 LOG_ERROR("could not open %s", service->port);
139 command_done(c->cmd_ctx);
140 free(c);
141 return ERROR_FAIL;
144 LOG_INFO("accepting '%s' connection from pipe %s", service->name, service->port);
145 retval = service->new_connection(c);
146 if (retval != ERROR_OK) {
147 LOG_ERROR("attempted '%s' connection rejected", service->name);
148 command_done(c->cmd_ctx);
149 free(c);
150 return retval;
154 /* add to the end of linked list */
155 for (p = &service->connections; *p; p = &(*p)->next)
157 *p = c;
159 if (service->max_connections != CONNECTION_LIMIT_UNLIMITED)
160 service->max_connections--;
162 return ERROR_OK;
165 static int remove_connection(struct service *service, struct connection *connection)
167 struct connection **p = &service->connections;
168 struct connection *c;
170 /* find connection */
171 while ((c = *p)) {
172 if (c->fd == connection->fd) {
173 service->connection_closed(c);
174 if (service->type == CONNECTION_TCP)
175 close_socket(c->fd);
176 else if (service->type == CONNECTION_PIPE) {
177 /* The service will listen to the pipe again */
178 c->service->fd = c->fd;
181 command_done(c->cmd_ctx);
183 /* delete connection */
184 *p = c->next;
185 free(c);
187 if (service->max_connections != CONNECTION_LIMIT_UNLIMITED)
188 service->max_connections++;
190 break;
193 /* redirect p to next list pointer */
194 p = &(*p)->next;
197 return ERROR_OK;
200 static void free_service(struct service *c)
202 free(c->name);
203 free(c->port);
204 free(c);
207 int add_service(char *name,
208 const char *port,
209 int max_connections,
210 new_connection_handler_t new_connection_handler,
211 input_handler_t input_handler,
212 connection_closed_handler_t connection_closed_handler,
213 void *priv)
215 struct service *c, **p;
216 struct hostent *hp;
217 int so_reuseaddr_option = 1;
219 c = malloc(sizeof(struct service));
221 c->name = strdup(name);
222 c->port = strdup(port);
223 c->max_connections = 1; /* Only TCP/IP ports can support more than one connection */
224 c->fd = -1;
225 c->connections = NULL;
226 c->new_connection = new_connection_handler;
227 c->input = input_handler;
228 c->connection_closed = connection_closed_handler;
229 c->priv = priv;
230 c->next = NULL;
231 long portnumber;
232 if (strcmp(c->port, "pipe") == 0)
233 c->type = CONNECTION_STDINOUT;
234 else {
235 char *end;
236 portnumber = strtol(c->port, &end, 0);
237 if (!*end && (parse_long(c->port, &portnumber) == ERROR_OK)) {
238 c->portnumber = portnumber;
239 c->type = CONNECTION_TCP;
240 } else
241 c->type = CONNECTION_PIPE;
244 if (c->type == CONNECTION_TCP) {
245 c->max_connections = max_connections;
247 c->fd = socket(AF_INET, SOCK_STREAM, 0);
248 if (c->fd == -1) {
249 LOG_ERROR("error creating socket: %s", strerror(errno));
250 free_service(c);
251 return ERROR_FAIL;
254 setsockopt(c->fd,
255 SOL_SOCKET,
256 SO_REUSEADDR,
257 (void *)&so_reuseaddr_option,
258 sizeof(int));
260 socket_nonblock(c->fd);
262 memset(&c->sin, 0, sizeof(c->sin));
263 c->sin.sin_family = AF_INET;
265 if (bindto_name == NULL)
266 c->sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
267 else {
268 hp = gethostbyname(bindto_name);
269 if (hp == NULL) {
270 LOG_ERROR("couldn't resolve bindto address: %s", bindto_name);
271 close_socket(c->fd);
272 free_service(c);
273 return ERROR_FAIL;
275 memcpy(&c->sin.sin_addr, hp->h_addr_list[0], hp->h_length);
277 c->sin.sin_port = htons(c->portnumber);
279 if (bind(c->fd, (struct sockaddr *)&c->sin, sizeof(c->sin)) == -1) {
280 LOG_ERROR("couldn't bind %s to socket on port %d: %s", name, c->portnumber, strerror(errno));
281 close_socket(c->fd);
282 free_service(c);
283 return ERROR_FAIL;
286 #ifndef _WIN32
287 int segsize = 65536;
288 setsockopt(c->fd, IPPROTO_TCP, TCP_MAXSEG, &segsize, sizeof(int));
289 #endif
290 int window_size = 128 * 1024;
292 /* These setsockopt()s must happen before the listen() */
294 setsockopt(c->fd, SOL_SOCKET, SO_SNDBUF,
295 (char *)&window_size, sizeof(window_size));
296 setsockopt(c->fd, SOL_SOCKET, SO_RCVBUF,
297 (char *)&window_size, sizeof(window_size));
299 if (listen(c->fd, 1) == -1) {
300 LOG_ERROR("couldn't listen on socket: %s", strerror(errno));
301 close_socket(c->fd);
302 free_service(c);
303 return ERROR_FAIL;
306 struct sockaddr_in addr_in;
307 addr_in.sin_port = 0;
308 socklen_t addr_in_size = sizeof(addr_in);
309 if (getsockname(c->fd, (struct sockaddr *)&addr_in, &addr_in_size) == 0)
310 LOG_INFO("Listening on port %hu for %s connections",
311 ntohs(addr_in.sin_port), name);
312 } else if (c->type == CONNECTION_STDINOUT) {
313 c->fd = fileno(stdin);
315 #ifdef _WIN32
316 /* for win32 set stdin/stdout to binary mode */
317 if (_setmode(_fileno(stdout), _O_BINARY) < 0)
318 LOG_WARNING("cannot change stdout mode to binary");
319 if (_setmode(_fileno(stdin), _O_BINARY) < 0)
320 LOG_WARNING("cannot change stdin mode to binary");
321 if (_setmode(_fileno(stderr), _O_BINARY) < 0)
322 LOG_WARNING("cannot change stderr mode to binary");
323 #else
324 socket_nonblock(c->fd);
325 #endif
326 } else if (c->type == CONNECTION_PIPE) {
327 #ifdef _WIN32
328 /* we currenty do not support named pipes under win32
329 * so exit openocd for now */
330 LOG_ERROR("Named pipes currently not supported under this os");
331 free_service(c);
332 return ERROR_FAIL;
333 #else
334 /* Pipe we're reading from */
335 c->fd = open(c->port, O_RDONLY | O_NONBLOCK);
336 if (c->fd == -1) {
337 LOG_ERROR("could not open %s", c->port);
338 free_service(c);
339 return ERROR_FAIL;
341 #endif
344 /* add to the end of linked list */
345 for (p = &services; *p; p = &(*p)->next)
347 *p = c;
349 return ERROR_OK;
352 static void remove_connections(struct service *service)
354 struct connection *connection;
356 connection = service->connections;
358 while (connection) {
359 struct connection *tmp;
361 tmp = connection->next;
362 remove_connection(service, connection);
363 connection = tmp;
367 static int remove_services(void)
369 struct service *c = services;
371 /* loop service */
372 while (c) {
373 struct service *next = c->next;
375 remove_connections(c);
377 if (c->name)
378 free(c->name);
380 if (c->type == CONNECTION_PIPE) {
381 if (c->fd != -1)
382 close(c->fd);
384 if (c->port)
385 free(c->port);
387 if (c->priv)
388 free(c->priv);
390 /* delete service */
391 free(c);
393 /* remember the last service for unlinking */
394 c = next;
397 services = NULL;
399 return ERROR_OK;
402 int server_loop(struct command_context *command_context)
404 struct service *service;
406 bool poll_ok = true;
408 /* used in select() */
409 fd_set read_fds;
410 int fd_max;
412 /* used in accept() */
413 int retval;
415 #ifndef _WIN32
416 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
417 LOG_ERROR("couldn't set SIGPIPE to SIG_IGN");
418 #endif
420 while (shutdown_openocd == CONTINUE_MAIN_LOOP) {
421 /* monitor sockets for activity */
422 fd_max = 0;
423 FD_ZERO(&read_fds);
425 /* add service and connection fds to read_fds */
426 for (service = services; service; service = service->next) {
427 if (service->fd != -1) {
428 /* listen for new connections */
429 FD_SET(service->fd, &read_fds);
431 if (service->fd > fd_max)
432 fd_max = service->fd;
435 if (service->connections) {
436 struct connection *c;
438 for (c = service->connections; c; c = c->next) {
439 /* check for activity on the connection */
440 FD_SET(c->fd, &read_fds);
441 if (c->fd > fd_max)
442 fd_max = c->fd;
447 struct timeval tv;
448 tv.tv_sec = 0;
449 if (poll_ok) {
450 /* we're just polling this iteration, this is faster on embedded
451 * hosts */
452 tv.tv_usec = 0;
453 retval = socket_select(fd_max + 1, &read_fds, NULL, NULL, &tv);
454 } else {
455 /* Every 100ms, can be changed with "poll_period" command */
456 tv.tv_usec = polling_period * 1000;
457 /* Only while we're sleeping we'll let others run */
458 openocd_sleep_prelude();
459 kept_alive();
460 retval = socket_select(fd_max + 1, &read_fds, NULL, NULL, &tv);
461 openocd_sleep_postlude();
464 if (retval == -1) {
465 #ifdef _WIN32
467 errno = WSAGetLastError();
469 if (errno == WSAEINTR)
470 FD_ZERO(&read_fds);
471 else {
472 LOG_ERROR("error during select: %s", strerror(errno));
473 return ERROR_FAIL;
475 #else
477 if (errno == EINTR)
478 FD_ZERO(&read_fds);
479 else {
480 LOG_ERROR("error during select: %s", strerror(errno));
481 return ERROR_FAIL;
483 #endif
486 if (retval == 0) {
487 /* We only execute these callbacks when there was nothing to do or we timed
488 *out */
489 target_call_timer_callbacks();
490 process_jim_events(command_context);
492 FD_ZERO(&read_fds); /* eCos leaves read_fds unchanged in this case! */
494 /* We timed out/there was nothing to do, timeout rather than poll next time
496 poll_ok = false;
497 } else {
498 /* There was something to do, next time we'll just poll */
499 poll_ok = true;
502 /* This is a simple back-off algorithm where we immediately
503 * re-poll if we did something this time around.
505 * This greatly improves performance of DCC.
507 poll_ok = poll_ok || target_got_message();
509 for (service = services; service; service = service->next) {
510 /* handle new connections on listeners */
511 if ((service->fd != -1)
512 && (FD_ISSET(service->fd, &read_fds))) {
513 if (service->max_connections != 0)
514 add_connection(service, command_context);
515 else {
516 if (service->type == CONNECTION_TCP) {
517 struct sockaddr_in sin;
518 socklen_t address_size = sizeof(sin);
519 int tmp_fd;
520 tmp_fd = accept(service->fd,
521 (struct sockaddr *)&service->sin,
522 &address_size);
523 close_socket(tmp_fd);
525 LOG_INFO(
526 "rejected '%s' connection, no more connections allowed",
527 service->name);
531 /* handle activity on connections */
532 if (service->connections) {
533 struct connection *c;
535 for (c = service->connections; c; ) {
536 if ((FD_ISSET(c->fd, &read_fds)) || c->input_pending) {
537 retval = service->input(c);
538 if (retval != ERROR_OK) {
539 struct connection *next = c->next;
540 if (service->type == CONNECTION_PIPE ||
541 service->type == CONNECTION_STDINOUT) {
542 /* if connection uses a pipe then
543 * shutdown openocd on error */
544 shutdown_openocd = SHUTDOWN_REQUESTED;
546 remove_connection(service, c);
547 LOG_INFO("dropped '%s' connection",
548 service->name);
549 c = next;
550 continue;
553 c = c->next;
558 #ifdef _WIN32
559 MSG msg;
560 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
561 if (msg.message == WM_QUIT)
562 shutdown_openocd = SHUTDOWN_WITH_SIGNAL_CODE;
564 #endif
567 /* when quit for signal or CTRL-C, run (eventually user implemented) "shutdown" */
568 if (shutdown_openocd == SHUTDOWN_WITH_SIGNAL_CODE)
569 command_run_line(command_context, "shutdown");
571 return shutdown_openocd == SHUTDOWN_WITH_ERROR_CODE ? ERROR_FAIL : ERROR_OK;
574 void sig_handler(int sig)
576 /* store only first signal that hits us */
577 if (shutdown_openocd == CONTINUE_MAIN_LOOP) {
578 shutdown_openocd = SHUTDOWN_WITH_SIGNAL_CODE;
579 last_signal = sig;
580 LOG_DEBUG("Terminating on Signal %d", sig);
581 } else
582 LOG_DEBUG("Ignored extra Signal %d", sig);
586 #ifdef _WIN32
587 BOOL WINAPI ControlHandler(DWORD dwCtrlType)
589 shutdown_openocd = SHUTDOWN_WITH_SIGNAL_CODE;
590 return TRUE;
592 #else
593 static void sigkey_handler(int sig)
595 /* ignore keystroke generated signals if not in foreground process group */
597 if (tcgetpgrp(STDIN_FILENO) > 0)
598 sig_handler(sig);
599 else
600 LOG_DEBUG("Ignored Signal %d", sig);
602 #endif
605 int server_preinit(void)
607 /* this currently only calls WSAStartup on native win32 systems
608 * before any socket operations are performed.
609 * This is an issue if you call init in your config script */
611 #ifdef _WIN32
612 WORD wVersionRequested;
613 WSADATA wsaData;
615 wVersionRequested = MAKEWORD(2, 2);
617 if (WSAStartup(wVersionRequested, &wsaData) != 0) {
618 LOG_ERROR("Failed to Open Winsock");
619 return ERROR_FAIL;
622 /* register ctrl-c handler */
623 SetConsoleCtrlHandler(ControlHandler, TRUE);
625 signal(SIGBREAK, sig_handler);
626 signal(SIGINT, sig_handler);
627 #else
628 signal(SIGHUP, sig_handler);
629 signal(SIGPIPE, sig_handler);
630 signal(SIGQUIT, sigkey_handler);
631 signal(SIGINT, sigkey_handler);
632 #endif
633 signal(SIGTERM, sig_handler);
634 signal(SIGABRT, sig_handler);
636 return ERROR_OK;
639 int server_init(struct command_context *cmd_ctx)
641 int ret = tcl_init();
643 if (ret != ERROR_OK)
644 return ret;
646 ret = telnet_init("Open On-Chip Debugger");
648 if (ret != ERROR_OK) {
649 remove_services();
650 return ret;
653 return ERROR_OK;
656 int server_quit(void)
658 remove_services();
659 target_quit();
661 #ifdef _WIN32
662 WSACleanup();
663 SetConsoleCtrlHandler(ControlHandler, FALSE);
665 return ERROR_OK;
666 #endif
668 /* return signal number so we can kill ourselves */
669 return last_signal;
672 void server_free(void)
674 tcl_service_free();
675 telnet_service_free();
676 jsp_service_free();
679 void exit_on_signal(int sig)
681 #ifndef _WIN32
682 /* bring back default system handler and kill yourself */
683 signal(sig, SIG_DFL);
684 kill(getpid(), sig);
685 #endif
688 int connection_write(struct connection *connection, const void *data, int len)
690 if (len == 0) {
691 /* successful no-op. Sockets and pipes behave differently here... */
692 return 0;
694 if (connection->service->type == CONNECTION_TCP)
695 return write_socket(connection->fd_out, data, len);
696 else
697 return write(connection->fd_out, data, len);
700 int connection_read(struct connection *connection, void *data, int len)
702 if (connection->service->type == CONNECTION_TCP)
703 return read_socket(connection->fd, data, len);
704 else
705 return read(connection->fd, data, len);
708 /* tell the server we want to shut down */
709 COMMAND_HANDLER(handle_shutdown_command)
711 LOG_USER("shutdown command invoked");
713 shutdown_openocd = SHUTDOWN_REQUESTED;
715 if (CMD_ARGC == 1) {
716 if (!strcmp(CMD_ARGV[0], "error")) {
717 shutdown_openocd = SHUTDOWN_WITH_ERROR_CODE;
718 return ERROR_FAIL;
722 return ERROR_COMMAND_CLOSE_CONNECTION;
725 COMMAND_HANDLER(handle_poll_period_command)
727 if (CMD_ARGC == 0)
728 LOG_WARNING("You need to set a period value");
729 else
730 COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], polling_period);
732 LOG_INFO("set servers polling period to %ums", polling_period);
734 return ERROR_OK;
737 COMMAND_HANDLER(handle_bindto_command)
739 switch (CMD_ARGC) {
740 case 0:
741 command_print(CMD_CTX, "bindto name: %s", bindto_name);
742 break;
743 case 1:
744 free(bindto_name);
745 bindto_name = strdup(CMD_ARGV[0]);
746 break;
747 default:
748 return ERROR_COMMAND_SYNTAX_ERROR;
750 return ERROR_OK;
753 static const struct command_registration server_command_handlers[] = {
755 .name = "shutdown",
756 .handler = &handle_shutdown_command,
757 .mode = COMMAND_ANY,
758 .usage = "",
759 .help = "shut the server down",
762 .name = "poll_period",
763 .handler = &handle_poll_period_command,
764 .mode = COMMAND_ANY,
765 .usage = "",
766 .help = "set the servers polling period",
769 .name = "bindto",
770 .handler = &handle_bindto_command,
771 .mode = COMMAND_ANY,
772 .usage = "[name]",
773 .help = "Specify address by name on which to listen for "
774 "incoming TCP/IP connections",
776 COMMAND_REGISTRATION_DONE
779 int server_register_commands(struct command_context *cmd_ctx)
781 int retval = telnet_register_commands(cmd_ctx);
782 if (ERROR_OK != retval)
783 return retval;
785 retval = tcl_register_commands(cmd_ctx);
786 if (ERROR_OK != retval)
787 return retval;
789 retval = jsp_register_commands(cmd_ctx);
790 if (ERROR_OK != retval)
791 return retval;
793 return register_commands(cmd_ctx, NULL, server_command_handlers);
796 COMMAND_HELPER(server_port_command, unsigned short *out)
798 switch (CMD_ARGC) {
799 case 0:
800 command_print(CMD_CTX, "%d", *out);
801 break;
802 case 1:
804 uint16_t port;
805 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[0], port);
806 *out = port;
807 break;
809 default:
810 return ERROR_COMMAND_SYNTAX_ERROR;
812 return ERROR_OK;
815 COMMAND_HELPER(server_pipe_command, char **out)
817 switch (CMD_ARGC) {
818 case 0:
819 command_print(CMD_CTX, "%s", *out);
820 break;
821 case 1:
823 if (CMD_CTX->mode == COMMAND_EXEC) {
824 LOG_WARNING("unable to change server port after init");
825 return ERROR_COMMAND_ARGUMENT_INVALID;
827 free(*out);
828 *out = strdup(CMD_ARGV[0]);
829 break;
831 default:
832 return ERROR_COMMAND_SYNTAX_ERROR;
834 return ERROR_OK;