Added system signal handling to Linux version
[openocd.git] / src / server / server.c
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, write to the *
23 * Free Software Foundation, Inc., *
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
25 ***************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "server.h"
32 #include <target/target.h>
33 #include <target/target_request.h>
34 #include <target/openrisc/jsp_server.h>
35 #include "openocd.h"
36 #include "tcl_server.h"
37 #include "telnet_server.h"
38
39 #include <signal.h>
40
41 #ifndef _WIN32
42 #include <netinet/tcp.h>
43 #endif
44
45 static struct service *services;
46
47 /* shutdown_openocd == 1: exit the main event loop, and quit the debugger */
48 static int shutdown_openocd;
49
50 /* store received signal to exit application by killing ourselves */
51 static int last_signal;
52
53 /* set the polling period to 100ms */
54 static int polling_period = 100;
55
56 static int add_connection(struct service *service, struct command_context *cmd_ctx)
57 {
58 socklen_t address_size;
59 struct connection *c, **p;
60 int retval;
61 int flag = 1;
62
63 c = malloc(sizeof(struct connection));
64 c->fd = -1;
65 c->fd_out = -1;
66 memset(&c->sin, 0, sizeof(c->sin));
67 c->cmd_ctx = copy_command_context(cmd_ctx);
68 c->service = service;
69 c->input_pending = 0;
70 c->priv = NULL;
71 c->next = NULL;
72
73 if (service->type == CONNECTION_TCP) {
74 address_size = sizeof(c->sin);
75
76 c->fd = accept(service->fd, (struct sockaddr *)&service->sin, &address_size);
77 c->fd_out = c->fd;
78
79 /* This increases performance dramatically for e.g. GDB load which
80 * does not have a sliding window protocol.
81 *
82 * Ignore errors from this fn as it probably just means less performance
83 */
84 setsockopt(c->fd, /* socket affected */
85 IPPROTO_TCP, /* set option at TCP level */
86 TCP_NODELAY, /* name of option */
87 (char *)&flag, /* the cast is historical cruft */
88 sizeof(int)); /* length of option value */
89
90 LOG_INFO("accepting '%s' connection on tcp/%s", service->name, service->port);
91 retval = service->new_connection(c);
92 if (retval != ERROR_OK) {
93 close_socket(c->fd);
94 LOG_ERROR("attempted '%s' connection rejected", service->name);
95 command_done(c->cmd_ctx);
96 free(c);
97 return retval;
98 }
99 } else if (service->type == CONNECTION_STDINOUT) {
100 c->fd = service->fd;
101 c->fd_out = fileno(stdout);
102
103 #ifdef _WIN32
104 /* we are using stdin/out so ignore ctrl-c under windoze */
105 SetConsoleCtrlHandler(NULL, TRUE);
106 #endif
107
108 /* do not check for new connections again on stdin */
109 service->fd = -1;
110
111 LOG_INFO("accepting '%s' connection from pipe", service->name);
112 retval = service->new_connection(c);
113 if (retval != ERROR_OK) {
114 LOG_ERROR("attempted '%s' connection rejected", service->name);
115 command_done(c->cmd_ctx);
116 free(c);
117 return retval;
118 }
119 } else if (service->type == CONNECTION_PIPE) {
120 c->fd = service->fd;
121 /* do not check for new connections again on stdin */
122 service->fd = -1;
123
124 char *out_file = alloc_printf("%so", service->port);
125 c->fd_out = open(out_file, O_WRONLY);
126 free(out_file);
127 if (c->fd_out == -1) {
128 LOG_ERROR("could not open %s", service->port);
129 exit(1);
130 }
131
132 LOG_INFO("accepting '%s' connection from pipe %s", service->name, service->port);
133 retval = service->new_connection(c);
134 if (retval != ERROR_OK) {
135 LOG_ERROR("attempted '%s' connection rejected", service->name);
136 command_done(c->cmd_ctx);
137 free(c);
138 return retval;
139 }
140 }
141
142 /* add to the end of linked list */
143 for (p = &service->connections; *p; p = &(*p)->next)
144 ;
145 *p = c;
146
147 service->max_connections--;
148
149 return ERROR_OK;
150 }
151
152 static int remove_connection(struct service *service, struct connection *connection)
153 {
154 struct connection **p = &service->connections;
155 struct connection *c;
156
157 /* find connection */
158 while ((c = *p)) {
159 if (c->fd == connection->fd) {
160 service->connection_closed(c);
161 if (service->type == CONNECTION_TCP)
162 close_socket(c->fd);
163 else if (service->type == CONNECTION_PIPE) {
164 /* The service will listen to the pipe again */
165 c->service->fd = c->fd;
166 }
167
168 command_done(c->cmd_ctx);
169
170 /* delete connection */
171 *p = c->next;
172 free(c);
173
174 service->max_connections++;
175 break;
176 }
177
178 /* redirect p to next list pointer */
179 p = &(*p)->next;
180 }
181
182 return ERROR_OK;
183 }
184
185 /* FIX! make service return error instead of invoking exit() */
186 int add_service(char *name,
187 const char *port,
188 int max_connections,
189 new_connection_handler_t new_connection_handler,
190 input_handler_t input_handler,
191 connection_closed_handler_t connection_closed_handler,
192 void *priv)
193 {
194 struct service *c, **p;
195 int so_reuseaddr_option = 1;
196
197 c = malloc(sizeof(struct service));
198
199 c->name = strdup(name);
200 c->port = strdup(port);
201 c->max_connections = 1; /* Only TCP/IP ports can support more than one connection */
202 c->fd = -1;
203 c->connections = NULL;
204 c->new_connection = new_connection_handler;
205 c->input = input_handler;
206 c->connection_closed = connection_closed_handler;
207 c->priv = priv;
208 c->next = NULL;
209 long portnumber;
210 if (strcmp(c->port, "pipe") == 0)
211 c->type = CONNECTION_STDINOUT;
212 else {
213 char *end;
214 portnumber = strtol(c->port, &end, 0);
215 if (!*end && (parse_long(c->port, &portnumber) == ERROR_OK)) {
216 c->portnumber = portnumber;
217 c->type = CONNECTION_TCP;
218 } else
219 c->type = CONNECTION_PIPE;
220 }
221
222 if (c->type == CONNECTION_TCP) {
223 c->max_connections = max_connections;
224
225 c->fd = socket(AF_INET, SOCK_STREAM, 0);
226 if (c->fd == -1) {
227 LOG_ERROR("error creating socket: %s", strerror(errno));
228 exit(-1);
229 }
230
231 setsockopt(c->fd,
232 SOL_SOCKET,
233 SO_REUSEADDR,
234 (void *)&so_reuseaddr_option,
235 sizeof(int));
236
237 socket_nonblock(c->fd);
238
239 memset(&c->sin, 0, sizeof(c->sin));
240 c->sin.sin_family = AF_INET;
241 c->sin.sin_addr.s_addr = INADDR_ANY;
242 c->sin.sin_port = htons(c->portnumber);
243
244 if (bind(c->fd, (struct sockaddr *)&c->sin, sizeof(c->sin)) == -1) {
245 LOG_ERROR("couldn't bind to socket: %s", strerror(errno));
246 exit(-1);
247 }
248
249 #ifndef _WIN32
250 int segsize = 65536;
251 setsockopt(c->fd, IPPROTO_TCP, TCP_MAXSEG, &segsize, sizeof(int));
252 #endif
253 int window_size = 128 * 1024;
254
255 /* These setsockopt()s must happen before the listen() */
256
257 setsockopt(c->fd, SOL_SOCKET, SO_SNDBUF,
258 (char *)&window_size, sizeof(window_size));
259 setsockopt(c->fd, SOL_SOCKET, SO_RCVBUF,
260 (char *)&window_size, sizeof(window_size));
261
262 if (listen(c->fd, 1) == -1) {
263 LOG_ERROR("couldn't listen on socket: %s", strerror(errno));
264 exit(-1);
265 }
266 } else if (c->type == CONNECTION_STDINOUT) {
267 c->fd = fileno(stdin);
268
269 #ifdef _WIN32
270 /* for win32 set stdin/stdout to binary mode */
271 if (_setmode(_fileno(stdout), _O_BINARY) < 0)
272 LOG_WARNING("cannot change stdout mode to binary");
273 if (_setmode(_fileno(stdin), _O_BINARY) < 0)
274 LOG_WARNING("cannot change stdin mode to binary");
275 if (_setmode(_fileno(stderr), _O_BINARY) < 0)
276 LOG_WARNING("cannot change stderr mode to binary");
277 #else
278 socket_nonblock(c->fd);
279 #endif
280 } else if (c->type == CONNECTION_PIPE) {
281 #ifdef _WIN32
282 /* we currenty do not support named pipes under win32
283 * so exit openocd for now */
284 LOG_ERROR("Named pipes currently not supported under this os");
285 exit(1);
286 #else
287 /* Pipe we're reading from */
288 c->fd = open(c->port, O_RDONLY | O_NONBLOCK);
289 if (c->fd == -1) {
290 LOG_ERROR("could not open %s", c->port);
291 exit(1);
292 }
293 #endif
294 }
295
296 /* add to the end of linked list */
297 for (p = &services; *p; p = &(*p)->next)
298 ;
299 *p = c;
300
301 return ERROR_OK;
302 }
303
304 static int remove_services(void)
305 {
306 struct service *c = services;
307
308 /* loop service */
309 while (c) {
310 struct service *next = c->next;
311
312 if (c->name)
313 free(c->name);
314
315 if (c->type == CONNECTION_PIPE) {
316 if (c->fd != -1)
317 close(c->fd);
318 }
319 if (c->port)
320 free(c->port);
321
322 if (c->priv)
323 free(c->priv);
324
325 /* delete service */
326 free(c);
327
328 /* remember the last service for unlinking */
329 c = next;
330 }
331
332 services = NULL;
333
334 return ERROR_OK;
335 }
336
337 int server_loop(struct command_context *command_context)
338 {
339 struct service *service;
340
341 bool poll_ok = true;
342
343 /* used in select() */
344 fd_set read_fds;
345 int fd_max;
346
347 /* used in accept() */
348 int retval;
349
350 #ifndef _WIN32
351 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
352 LOG_ERROR("couldn't set SIGPIPE to SIG_IGN");
353 #endif
354
355 while (!shutdown_openocd) {
356 /* monitor sockets for activity */
357 fd_max = 0;
358 FD_ZERO(&read_fds);
359
360 /* add service and connection fds to read_fds */
361 for (service = services; service; service = service->next) {
362 if (service->fd != -1) {
363 /* listen for new connections */
364 FD_SET(service->fd, &read_fds);
365
366 if (service->fd > fd_max)
367 fd_max = service->fd;
368 }
369
370 if (service->connections) {
371 struct connection *c;
372
373 for (c = service->connections; c; c = c->next) {
374 /* check for activity on the connection */
375 FD_SET(c->fd, &read_fds);
376 if (c->fd > fd_max)
377 fd_max = c->fd;
378 }
379 }
380 }
381
382 struct timeval tv;
383 tv.tv_sec = 0;
384 if (poll_ok) {
385 /* we're just polling this iteration, this is faster on embedded
386 * hosts */
387 tv.tv_usec = 0;
388 retval = socket_select(fd_max + 1, &read_fds, NULL, NULL, &tv);
389 } else {
390 /* Every 100ms, can be changed with "poll_period" command */
391 tv.tv_usec = polling_period * 1000;
392 /* Only while we're sleeping we'll let others run */
393 openocd_sleep_prelude();
394 kept_alive();
395 retval = socket_select(fd_max + 1, &read_fds, NULL, NULL, &tv);
396 openocd_sleep_postlude();
397 }
398
399 if (retval == -1) {
400 #ifdef _WIN32
401
402 errno = WSAGetLastError();
403
404 if (errno == WSAEINTR)
405 FD_ZERO(&read_fds);
406 else {
407 LOG_ERROR("error during select: %s", strerror(errno));
408 exit(-1);
409 }
410 #else
411
412 if (errno == EINTR)
413 FD_ZERO(&read_fds);
414 else {
415 LOG_ERROR("error during select: %s", strerror(errno));
416 exit(-1);
417 }
418 #endif
419 }
420
421 if (retval == 0) {
422 /* We only execute these callbacks when there was nothing to do or we timed
423 *out */
424 target_call_timer_callbacks();
425 process_jim_events(command_context);
426
427 FD_ZERO(&read_fds); /* eCos leaves read_fds unchanged in this case! */
428
429 /* We timed out/there was nothing to do, timeout rather than poll next time
430 **/
431 poll_ok = false;
432 } else {
433 /* There was something to do, next time we'll just poll */
434 poll_ok = true;
435 }
436
437 /* This is a simple back-off algorithm where we immediately
438 * re-poll if we did something this time around.
439 *
440 * This greatly improves performance of DCC.
441 */
442 poll_ok = poll_ok || target_got_message();
443
444 for (service = services; service; service = service->next) {
445 /* handle new connections on listeners */
446 if ((service->fd != -1)
447 && (FD_ISSET(service->fd, &read_fds))) {
448 if (service->max_connections > 0)
449 add_connection(service, command_context);
450 else {
451 if (service->type == CONNECTION_TCP) {
452 struct sockaddr_in sin;
453 socklen_t address_size = sizeof(sin);
454 int tmp_fd;
455 tmp_fd = accept(service->fd,
456 (struct sockaddr *)&service->sin,
457 &address_size);
458 close_socket(tmp_fd);
459 }
460 LOG_INFO(
461 "rejected '%s' connection, no more connections allowed",
462 service->name);
463 }
464 }
465
466 /* handle activity on connections */
467 if (service->connections) {
468 struct connection *c;
469
470 for (c = service->connections; c; ) {
471 if ((FD_ISSET(c->fd, &read_fds)) || c->input_pending) {
472 retval = service->input(c);
473 if (retval != ERROR_OK) {
474 struct connection *next = c->next;
475 if (service->type == CONNECTION_PIPE ||
476 service->type == CONNECTION_STDINOUT) {
477 /* if connection uses a pipe then
478 * shutdown openocd on error */
479 shutdown_openocd = 1;
480 }
481 remove_connection(service, c);
482 LOG_INFO("dropped '%s' connection",
483 service->name);
484 c = next;
485 continue;
486 }
487 }
488 c = c->next;
489 }
490 }
491 }
492
493 #ifdef _WIN32
494 MSG msg;
495 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
496 if (msg.message == WM_QUIT)
497 shutdown_openocd = 1;
498 }
499 #endif
500 }
501
502 return ERROR_OK;
503 }
504
505 #ifdef _WIN32
506 BOOL WINAPI ControlHandler(DWORD dwCtrlType)
507 {
508 shutdown_openocd = 1;
509 return TRUE;
510 }
511 #endif
512
513 void sig_handler(int sig)
514 {
515 /* store only first signal that hits us */
516 if (!last_signal)
517 last_signal = sig;
518 shutdown_openocd = 1;
519 }
520
521 int server_preinit(void)
522 {
523 /* this currently only calls WSAStartup on native win32 systems
524 * before any socket operations are performed.
525 * This is an issue if you call init in your config script */
526
527 #ifdef _WIN32
528 WORD wVersionRequested;
529 WSADATA wsaData;
530
531 wVersionRequested = MAKEWORD(2, 2);
532
533 if (WSAStartup(wVersionRequested, &wsaData) != 0) {
534 LOG_ERROR("Failed to Open Winsock");
535 exit(-1);
536 }
537
538 /* register ctrl-c handler */
539 SetConsoleCtrlHandler(ControlHandler, TRUE);
540
541 signal(SIGBREAK, sig_handler);
542 #endif
543 signal(SIGINT, sig_handler);
544 signal(SIGTERM, sig_handler);
545 signal(SIGABRT, sig_handler);
546
547 return ERROR_OK;
548 }
549
550 int server_init(struct command_context *cmd_ctx)
551 {
552 int ret = tcl_init();
553 if (ERROR_OK != ret)
554 return ret;
555
556 return telnet_init("Open On-Chip Debugger");
557 }
558
559 int server_quit(void)
560 {
561 remove_services();
562
563 #ifdef _WIN32
564 WSACleanup();
565 SetConsoleCtrlHandler(ControlHandler, FALSE);
566
567 return ERROR_OK;
568 #endif
569
570 /* return signal number so we can kill ourselves */
571 return last_signal;
572 }
573
574 void exit_on_signal(int sig)
575 {
576 #ifndef _WIN32
577 /* bring back default system handler and kill yourself */
578 signal(sig, SIG_DFL);
579 kill(getpid(), sig);
580 #endif
581 }
582
583 int connection_write(struct connection *connection, const void *data, int len)
584 {
585 if (len == 0) {
586 /* successful no-op. Sockets and pipes behave differently here... */
587 return 0;
588 }
589 if (connection->service->type == CONNECTION_TCP)
590 return write_socket(connection->fd_out, data, len);
591 else
592 return write(connection->fd_out, data, len);
593 }
594
595 int connection_read(struct connection *connection, void *data, int len)
596 {
597 if (connection->service->type == CONNECTION_TCP)
598 return read_socket(connection->fd, data, len);
599 else
600 return read(connection->fd, data, len);
601 }
602
603 /* tell the server we want to shut down */
604 COMMAND_HANDLER(handle_shutdown_command)
605 {
606 LOG_USER("shutdown command invoked");
607
608 shutdown_openocd = 1;
609
610 return ERROR_COMMAND_CLOSE_CONNECTION;
611 }
612
613 COMMAND_HANDLER(handle_poll_period_command)
614 {
615 if (CMD_ARGC == 0)
616 LOG_WARNING("You need to set a period value");
617 else
618 COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], polling_period);
619
620 LOG_INFO("set servers polling period to %ums", polling_period);
621
622 return ERROR_OK;
623 }
624
625 static const struct command_registration server_command_handlers[] = {
626 {
627 .name = "shutdown",
628 .handler = &handle_shutdown_command,
629 .mode = COMMAND_ANY,
630 .usage = "",
631 .help = "shut the server down",
632 },
633 {
634 .name = "poll_period",
635 .handler = &handle_poll_period_command,
636 .mode = COMMAND_ANY,
637 .usage = "",
638 .help = "set the servers polling period",
639 },
640 COMMAND_REGISTRATION_DONE
641 };
642
643 int server_register_commands(struct command_context *cmd_ctx)
644 {
645 int retval = telnet_register_commands(cmd_ctx);
646 if (ERROR_OK != retval)
647 return retval;
648
649 retval = tcl_register_commands(cmd_ctx);
650 if (ERROR_OK != retval)
651 return retval;
652
653 retval = jsp_register_commands(cmd_ctx);
654 if (ERROR_OK != retval)
655 return retval;
656
657 return register_commands(cmd_ctx, NULL, server_command_handlers);
658 }
659
660 COMMAND_HELPER(server_port_command, unsigned short *out)
661 {
662 switch (CMD_ARGC) {
663 case 0:
664 command_print(CMD_CTX, "%d", *out);
665 break;
666 case 1:
667 {
668 uint16_t port;
669 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[0], port);
670 *out = port;
671 break;
672 }
673 default:
674 return ERROR_COMMAND_SYNTAX_ERROR;
675 }
676 return ERROR_OK;
677 }
678
679 COMMAND_HELPER(server_pipe_command, char **out)
680 {
681 switch (CMD_ARGC) {
682 case 0:
683 command_print(CMD_CTX, "%s", *out);
684 break;
685 case 1:
686 {
687 if (CMD_CTX->mode == COMMAND_EXEC) {
688 LOG_WARNING("unable to change server port after init");
689 return ERROR_COMMAND_ARGUMENT_INVALID;
690 }
691 free(*out);
692 *out = strdup(CMD_ARGV[0]);
693 break;
694 }
695 default:
696 return ERROR_COMMAND_SYNTAX_ERROR;
697 }
698 return ERROR_OK;
699 }