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