1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008 by Spencer Oliver *
9 * spen@spen-soft.co.uk *
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. *
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. *
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 ***************************************************************************/
30 #include <target/target.h>
31 #include <target/target_request.h>
32 #include <target/openrisc/jsp_server.h>
34 #include "tcl_server.h"
35 #include "telnet_server.h"
44 #include <netinet/tcp.h>
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;
73 c = malloc(sizeof(struct connection));
76 memset(&c->sin, 0, sizeof(c->sin));
77 c->cmd_ctx = copy_command_context(cmd_ctx);
83 if (service->type == CONNECTION_TCP) {
84 address_size = sizeof(c->sin);
86 c->fd = accept(service->fd, (struct sockaddr *)&service->sin, &address_size);
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) {
104 LOG_ERROR("attempted '%s' connection rejected", service->name);
105 command_done(c->cmd_ctx);
109 } else if (service->type == CONNECTION_STDINOUT) {
111 c->fd_out = fileno(stdout);
114 /* we are using stdin/out so ignore ctrl-c under windoze */
115 SetConsoleCtrlHandler(NULL, TRUE);
118 /* do not check for new connections again on stdin */
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);
129 } else if (service->type == CONNECTION_PIPE) {
131 /* do not check for new connections again on stdin */
134 char *out_file = alloc_printf("%so", service->port);
135 c->fd_out = open(out_file, O_WRONLY);
137 if (c->fd_out == -1) {
138 LOG_ERROR("could not open %s", service->port);
139 command_done(c->cmd_ctx);
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);
154 /* add to the end of linked list */
155 for (p = &service->connections; *p; p = &(*p)->next)
159 if (service->max_connections != CONNECTION_LIMIT_UNLIMITED)
160 service->max_connections--;
165 static int remove_connection(struct service *service, struct connection *connection)
167 struct connection **p = &service->connections;
168 struct connection *c;
170 /* find connection */
172 if (c->fd == connection->fd) {
173 service->connection_closed(c);
174 if (service->type == CONNECTION_TCP)
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 */
187 if (service->max_connections != CONNECTION_LIMIT_UNLIMITED)
188 service->max_connections++;
193 /* redirect p to next list pointer */
200 static void free_service(struct service *c)
207 int add_service(char *name,
210 new_connection_handler_t new_connection_handler,
211 input_handler_t input_handler,
212 connection_closed_handler_t connection_closed_handler,
215 struct service *c, **p;
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 */
225 c->connections = NULL;
226 c->new_connection = new_connection_handler;
227 c->input = input_handler;
228 c->connection_closed = connection_closed_handler;
232 if (strcmp(c->port, "pipe") == 0)
233 c->type = CONNECTION_STDINOUT;
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;
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);
249 LOG_ERROR("error creating socket: %s", strerror(errno));
257 (void *)&so_reuseaddr_option,
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);
268 hp = gethostbyname(bindto_name);
270 LOG_ERROR("couldn't resolve bindto address: %s", bindto_name);
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));
288 setsockopt(c->fd, IPPROTO_TCP, TCP_MAXSEG, &segsize, sizeof(int));
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));
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);
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");
324 socket_nonblock(c->fd);
326 } else if (c->type == CONNECTION_PIPE) {
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");
334 /* Pipe we're reading from */
335 c->fd = open(c->port, O_RDONLY | O_NONBLOCK);
337 LOG_ERROR("could not open %s", c->port);
344 /* add to the end of linked list */
345 for (p = &services; *p; p = &(*p)->next)
352 static void remove_connections(struct service *service)
354 struct connection *connection;
356 connection = service->connections;
359 struct connection *tmp;
361 tmp = connection->next;
362 remove_connection(service, connection);
367 int remove_service(const char *name, const char *port)
370 struct service *prev;
374 for (tmp = services; tmp; prev = tmp, tmp = tmp->next) {
375 if (!strcmp(tmp->name, name) && !strcmp(tmp->port, port)) {
376 remove_connections(tmp);
379 services = tmp->next;
381 prev->next = tmp->next;
383 if (tmp->type != CONNECTION_STDINOUT)
384 close_socket(tmp->fd);
396 static int remove_services(void)
398 struct service *c = services;
402 struct service *next = c->next;
404 remove_connections(c);
409 if (c->type == CONNECTION_PIPE) {
422 /* remember the last service for unlinking */
431 int server_loop(struct command_context *command_context)
433 struct service *service;
437 /* used in select() */
441 /* used in accept() */
445 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
446 LOG_ERROR("couldn't set SIGPIPE to SIG_IGN");
449 while (shutdown_openocd == CONTINUE_MAIN_LOOP) {
450 /* monitor sockets for activity */
454 /* add service and connection fds to read_fds */
455 for (service = services; service; service = service->next) {
456 if (service->fd != -1) {
457 /* listen for new connections */
458 FD_SET(service->fd, &read_fds);
460 if (service->fd > fd_max)
461 fd_max = service->fd;
464 if (service->connections) {
465 struct connection *c;
467 for (c = service->connections; c; c = c->next) {
468 /* check for activity on the connection */
469 FD_SET(c->fd, &read_fds);
479 /* we're just polling this iteration, this is faster on embedded
482 retval = socket_select(fd_max + 1, &read_fds, NULL, NULL, &tv);
484 /* Every 100ms, can be changed with "poll_period" command */
485 tv.tv_usec = polling_period * 1000;
486 /* Only while we're sleeping we'll let others run */
487 openocd_sleep_prelude();
489 retval = socket_select(fd_max + 1, &read_fds, NULL, NULL, &tv);
490 openocd_sleep_postlude();
496 errno = WSAGetLastError();
498 if (errno == WSAEINTR)
501 LOG_ERROR("error during select: %s", strerror(errno));
509 LOG_ERROR("error during select: %s", strerror(errno));
516 /* We only execute these callbacks when there was nothing to do or we timed
518 target_call_timer_callbacks();
519 process_jim_events(command_context);
521 FD_ZERO(&read_fds); /* eCos leaves read_fds unchanged in this case! */
523 /* We timed out/there was nothing to do, timeout rather than poll next time
527 /* There was something to do, next time we'll just poll */
531 /* This is a simple back-off algorithm where we immediately
532 * re-poll if we did something this time around.
534 * This greatly improves performance of DCC.
536 poll_ok = poll_ok || target_got_message();
538 for (service = services; service; service = service->next) {
539 /* handle new connections on listeners */
540 if ((service->fd != -1)
541 && (FD_ISSET(service->fd, &read_fds))) {
542 if (service->max_connections != 0)
543 add_connection(service, command_context);
545 if (service->type == CONNECTION_TCP) {
546 struct sockaddr_in sin;
547 socklen_t address_size = sizeof(sin);
549 tmp_fd = accept(service->fd,
550 (struct sockaddr *)&service->sin,
552 close_socket(tmp_fd);
555 "rejected '%s' connection, no more connections allowed",
560 /* handle activity on connections */
561 if (service->connections) {
562 struct connection *c;
564 for (c = service->connections; c; ) {
565 if ((FD_ISSET(c->fd, &read_fds)) || c->input_pending) {
566 retval = service->input(c);
567 if (retval != ERROR_OK) {
568 struct connection *next = c->next;
569 if (service->type == CONNECTION_PIPE ||
570 service->type == CONNECTION_STDINOUT) {
571 /* if connection uses a pipe then
572 * shutdown openocd on error */
573 shutdown_openocd = SHUTDOWN_REQUESTED;
575 remove_connection(service, c);
576 LOG_INFO("dropped '%s' connection",
589 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
590 if (msg.message == WM_QUIT)
591 shutdown_openocd = SHUTDOWN_WITH_SIGNAL_CODE;
596 /* when quit for signal or CTRL-C, run (eventually user implemented) "shutdown" */
597 if (shutdown_openocd == SHUTDOWN_WITH_SIGNAL_CODE)
598 command_run_line(command_context, "shutdown");
600 return shutdown_openocd == SHUTDOWN_WITH_ERROR_CODE ? ERROR_FAIL : ERROR_OK;
603 void sig_handler(int sig)
605 /* store only first signal that hits us */
606 if (shutdown_openocd == CONTINUE_MAIN_LOOP) {
607 shutdown_openocd = SHUTDOWN_WITH_SIGNAL_CODE;
609 LOG_DEBUG("Terminating on Signal %d", sig);
611 LOG_DEBUG("Ignored extra Signal %d", sig);
616 BOOL WINAPI ControlHandler(DWORD dwCtrlType)
618 shutdown_openocd = SHUTDOWN_WITH_SIGNAL_CODE;
622 static void sigkey_handler(int sig)
624 /* ignore keystroke generated signals if not in foreground process group */
626 if (tcgetpgrp(STDIN_FILENO) > 0)
629 LOG_DEBUG("Ignored Signal %d", sig);
634 int server_preinit(void)
636 /* this currently only calls WSAStartup on native win32 systems
637 * before any socket operations are performed.
638 * This is an issue if you call init in your config script */
641 WORD wVersionRequested;
644 wVersionRequested = MAKEWORD(2, 2);
646 if (WSAStartup(wVersionRequested, &wsaData) != 0) {
647 LOG_ERROR("Failed to Open Winsock");
651 /* register ctrl-c handler */
652 SetConsoleCtrlHandler(ControlHandler, TRUE);
654 signal(SIGBREAK, sig_handler);
655 signal(SIGINT, sig_handler);
657 signal(SIGHUP, sig_handler);
658 signal(SIGPIPE, sig_handler);
659 signal(SIGQUIT, sigkey_handler);
660 signal(SIGINT, sigkey_handler);
662 signal(SIGTERM, sig_handler);
663 signal(SIGABRT, sig_handler);
668 int server_init(struct command_context *cmd_ctx)
670 int ret = tcl_init();
675 ret = telnet_init("Open On-Chip Debugger");
677 if (ret != ERROR_OK) {
685 int server_quit(void)
692 SetConsoleCtrlHandler(ControlHandler, FALSE);
697 /* return signal number so we can kill ourselves */
701 void server_free(void)
704 telnet_service_free();
708 void exit_on_signal(int sig)
711 /* bring back default system handler and kill yourself */
712 signal(sig, SIG_DFL);
717 int connection_write(struct connection *connection, const void *data, int len)
720 /* successful no-op. Sockets and pipes behave differently here... */
723 if (connection->service->type == CONNECTION_TCP)
724 return write_socket(connection->fd_out, data, len);
726 return write(connection->fd_out, data, len);
729 int connection_read(struct connection *connection, void *data, int len)
731 if (connection->service->type == CONNECTION_TCP)
732 return read_socket(connection->fd, data, len);
734 return read(connection->fd, data, len);
737 /* tell the server we want to shut down */
738 COMMAND_HANDLER(handle_shutdown_command)
740 LOG_USER("shutdown command invoked");
742 shutdown_openocd = SHUTDOWN_REQUESTED;
745 if (!strcmp(CMD_ARGV[0], "error")) {
746 shutdown_openocd = SHUTDOWN_WITH_ERROR_CODE;
751 return ERROR_COMMAND_CLOSE_CONNECTION;
754 COMMAND_HANDLER(handle_poll_period_command)
757 LOG_WARNING("You need to set a period value");
759 COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], polling_period);
761 LOG_INFO("set servers polling period to %ums", polling_period);
766 COMMAND_HANDLER(handle_bindto_command)
770 command_print(CMD_CTX, "bindto name: %s", bindto_name);
774 bindto_name = strdup(CMD_ARGV[0]);
777 return ERROR_COMMAND_SYNTAX_ERROR;
782 static const struct command_registration server_command_handlers[] = {
785 .handler = &handle_shutdown_command,
788 .help = "shut the server down",
791 .name = "poll_period",
792 .handler = &handle_poll_period_command,
795 .help = "set the servers polling period",
799 .handler = &handle_bindto_command,
802 .help = "Specify address by name on which to listen for "
803 "incoming TCP/IP connections",
805 COMMAND_REGISTRATION_DONE
808 int server_register_commands(struct command_context *cmd_ctx)
810 int retval = telnet_register_commands(cmd_ctx);
811 if (ERROR_OK != retval)
814 retval = tcl_register_commands(cmd_ctx);
815 if (ERROR_OK != retval)
818 retval = jsp_register_commands(cmd_ctx);
819 if (ERROR_OK != retval)
822 return register_commands(cmd_ctx, NULL, server_command_handlers);
825 COMMAND_HELPER(server_port_command, unsigned short *out)
829 command_print(CMD_CTX, "%d", *out);
834 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[0], port);
839 return ERROR_COMMAND_SYNTAX_ERROR;
844 COMMAND_HELPER(server_pipe_command, char **out)
848 command_print(CMD_CTX, "%s", *out);
852 if (CMD_CTX->mode == COMMAND_EXEC) {
853 LOG_WARNING("unable to change server port after init");
854 return ERROR_COMMAND_ARGUMENT_INVALID;
857 *out = strdup(CMD_ARGV[0]);
861 return ERROR_COMMAND_SYNTAX_ERROR;