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

Linking to existing account procedure

If you already have an account and want to add another login method you MUST first sign in with your existing account and then change URL to read https://review.openocd.org/login/?link to get to this page again but this time it'll work for linking. Thank you.

SSH host keys fingerprints

1024 SHA256:YKx8b7u5ZWdcbp7/4AeXNaqElP49m6QrwfXaqQGJAOk gerrit-code-review@openocd.zylin.com (DSA)
384 SHA256:jHIbSQa4REvwCFG4cq5LBlBLxmxSqelQPem/EXIrxjk gerrit-code-review@openocd.org (ECDSA)
521 SHA256:UAOPYkU9Fjtcao0Ul/Rrlnj/OsQvt+pgdYSZ4jOYdgs gerrit-code-review@openocd.org (ECDSA)
256 SHA256:A13M5QlnozFOvTllybRZH6vm7iSt0XLxbA48yfc2yfY gerrit-code-review@openocd.org (ECDSA)
256 SHA256:spYMBqEYoAOtK7yZBrcwE8ZpYt6b68Cfh9yEVetvbXg gerrit-code-review@openocd.org (ED25519)
+--[ED25519 256]--+
|=..              |
|+o..   .         |
|*.o   . .        |
|+B . . .         |
|Bo. = o S        |
|Oo.+ + =         |
|oB=.* = . o      |
| =+=.+   + E     |
|. .=o   . o      |
+----[SHA256]-----+
2048 SHA256:0Onrb7/PHjpo6iVZ7xQX2riKN83FJ3KGU0TvI0TaFG4 gerrit-code-review@openocd.zylin.com (RSA)