05018694bc375ecf433cc33a4b94c415681ab3c8
[fw/openocd] / src / server / server.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007,2008 Ã˜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.h"
32
33 #include <signal.h>
34
35 #ifndef _WIN32
36 #include <netinet/tcp.h>
37 #endif
38
39
40 service_t *services = NULL;
41
42 /* shutdown_openocd == 1: exit the main event loop, and quit the debugger */
43 static int shutdown_openocd = 0;
44
45 /* set when using pipes rather than tcp */
46 int server_use_pipes = 0;
47
48 int add_connection(service_t *service, command_context_t *cmd_ctx)
49 {
50         socklen_t address_size;
51         connection_t *c, **p;
52         int retval;
53         int flag = 1;
54
55         c = malloc(sizeof(connection_t));
56         c->fd = -1;
57         memset(&c->sin, 0, sizeof(c->sin));
58         c->cmd_ctx = copy_command_context(cmd_ctx);
59         c->service = service;
60         c->input_pending = 0;
61         c->priv = NULL;
62         c->next = NULL;
63
64         if (service->type == CONNECTION_TCP)
65         {
66                 address_size = sizeof(c->sin);
67
68                 c->fd = accept(service->fd, (struct sockaddr *)&service->sin, &address_size);
69
70                 /* This increases performance dramatically for e.g. GDB load which
71                  * does not have a sliding window protocol. */
72                 retval = setsockopt(c->fd,      /* socket affected */
73                                 IPPROTO_TCP,            /* set option at TCP level */
74                                 TCP_NODELAY,            /* name of option */
75                                 (char *)&flag,          /* the cast is historical cruft */
76                                 sizeof(int));           /* length of option value */
77
78                 LOG_INFO("accepting '%s' connection from %i", service->name, c->sin.sin_port);
79                 if ((retval = service->new_connection(c)) != ERROR_OK)
80                 {
81                         close_socket(c->fd);
82                         LOG_ERROR("attempted '%s' connection rejected", service->name);
83                         free(c);
84                         return retval;
85                 }
86         }
87         else if (service->type == CONNECTION_PIPE)
88         {
89                 c->fd = service->fd;
90
91                 /* do not check for new connections again on stdin */
92                 service->fd = -1;
93
94                 LOG_INFO("accepting '%s' connection from pipe", service->name);
95                 if ((retval = service->new_connection(c)) != ERROR_OK)
96                 {
97                         LOG_ERROR("attempted '%s' connection rejected", service->name);
98                         free(c);
99                         return retval;
100                 }
101         }
102
103         /* add to the end of linked list */
104         for (p = &service->connections; *p; p = &(*p)->next);
105         *p = c;
106
107         service->max_connections--;
108
109         return ERROR_OK;
110 }
111
112 int remove_connection(service_t *service, connection_t *connection)
113 {
114         connection_t **p = &service->connections;
115         connection_t *c;
116
117         /* find connection */
118         while ((c = *p))
119         {
120                 if (c->fd == connection->fd)
121                 {
122                         service->connection_closed(c);
123                         if (service->type == CONNECTION_TCP)
124                                 close_socket(c->fd);
125                         command_done(c->cmd_ctx);
126
127                         /* delete connection */
128                         *p = c->next;
129                         free(c);
130
131                         service->max_connections++;
132                         break;
133                 }
134
135                 /* redirect p to next list pointer */
136                 p = &(*p)->next;
137         }
138
139         return ERROR_OK;
140 }
141
142 int add_service(char *name, enum connection_type type, unsigned short 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)
143 {
144         service_t *c, **p;
145         int so_reuseaddr_option = 1;
146
147         c = malloc(sizeof(service_t));
148
149         c->name = strdup(name);
150         c->type = type;
151         c->port = port;
152         c->max_connections = max_connections;
153         c->fd = -1;
154         c->connections = NULL;
155         c->new_connection = new_connection_handler;
156         c->input = input_handler;
157         c->connection_closed = connection_closed_handler;
158         c->priv = priv;
159         c->next = NULL;
160
161         if (type == CONNECTION_TCP)
162         {
163                 if ((c->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
164                 {
165                         LOG_ERROR("error creating socket: %s", strerror(errno));
166                         exit(-1);
167                 }
168
169                 setsockopt(c->fd, SOL_SOCKET, SO_REUSEADDR, (void*)&so_reuseaddr_option, sizeof(int));
170
171                 socket_nonblock(c->fd);
172
173                 memset(&c->sin, 0, sizeof(c->sin));
174                 c->sin.sin_family = AF_INET;
175                 c->sin.sin_addr.s_addr = INADDR_ANY;
176                 c->sin.sin_port = htons(port);
177
178                 if (bind(c->fd, (struct sockaddr *)&c->sin, sizeof(c->sin)) == -1)
179                 {
180                         LOG_ERROR("couldn't bind to socket: %s", strerror(errno));
181                         exit(-1);
182                 }
183
184 #ifndef _WIN32
185                 int segsize = 65536;
186                 setsockopt(c->fd, IPPROTO_TCP, TCP_MAXSEG,  &segsize, sizeof(int));
187 #endif
188                 int window_size = 128 * 1024;
189
190                 /* These setsockopt()s must happen before the listen() */
191
192                 setsockopt(c->fd, SOL_SOCKET, SO_SNDBUF,
193                         (char *)&window_size, sizeof(window_size));
194                 setsockopt(c->fd, SOL_SOCKET, SO_RCVBUF,
195                         (char *)&window_size, sizeof(window_size));
196
197                 if (listen(c->fd, 1) == -1)
198                 {
199                         LOG_ERROR("couldn't listen on socket: %s", strerror(errno));
200                         exit(-1);
201                 }
202         }
203         else if (type == CONNECTION_PIPE)
204         {
205                 /* use stdin */
206                 c->fd = STDIN_FILENO;
207
208 #ifdef _WIN32
209                 /* for win32 set stdin/stdout to binary mode */
210                 if (_setmode(_fileno(stdout), _O_BINARY) < 0)
211                         LOG_WARNING("cannot change stdout mode to binary");
212                 if (_setmode(_fileno(stdin), _O_BINARY) < 0)
213                         LOG_WARNING("cannot change stdin mode to binary");
214                 if (_setmode(_fileno(stderr), _O_BINARY) < 0)
215                         LOG_WARNING("cannot change stderr mode to binary");
216 #else
217                 socket_nonblock(c->fd);
218 #endif
219         }
220         else
221         {
222                 LOG_ERROR("unknown connection type: %d", type);
223                 exit(1);
224         }
225
226         /* add to the end of linked list */
227         for (p = &services; *p; p = &(*p)->next);
228         *p = c;
229
230         return ERROR_OK;
231 }
232
233 int remove_service(unsigned short port)
234 {
235         service_t **p = &services;
236         service_t *c;
237
238         /* find service */
239         while ((c = *p))
240         {
241                 if (c->port == port)
242                 {
243                         if (c->name)
244                                 free(c->name);
245
246                         if (c->priv)
247                                 free(c->priv);
248
249                         /* delete service */
250                         *p = c->next;
251                         free(c);
252                 }
253
254                 /* redirect p to next list pointer */
255                 p = &(*p)->next;
256         }
257
258         return ERROR_OK;
259 }
260
261 int remove_services(void)
262 {
263         service_t *c = services;
264
265         /* loop service */
266         while (c)
267         {
268                 service_t *next = c->next;
269
270                 if (c->name)
271                         free(c->name);
272
273                 if (c->priv)
274                         free(c->priv);
275
276                 /* delete service */
277                 free(c);
278
279                 /* remember the last service for unlinking */
280                 c = next;
281         }
282
283         services = NULL;
284
285         return ERROR_OK;
286 }
287
288 extern void openocd_sleep_prelude(void);
289 extern void openocd_sleep_postlude(void);
290
291 int server_loop(command_context_t *command_context)
292 {
293         service_t *service;
294
295         /* used in select() */
296         fd_set read_fds;
297         struct timeval tv;
298         int fd_max;
299
300         /* used in accept() */
301         int retval;
302
303 #ifndef _WIN32
304         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
305                 LOG_ERROR("couldn't set SIGPIPE to SIG_IGN");
306 #endif
307
308         /* do regular tasks after at most 10ms */
309         tv.tv_sec = 0;
310         tv.tv_usec = 10000;
311
312         while (!shutdown_openocd)
313         {
314                 /* monitor sockets for acitvity */
315                 fd_max = 0;
316                 FD_ZERO(&read_fds);
317
318                 /* add service and connection fds to read_fds */
319                 for (service = services; service; service = service->next)
320                 {
321                         if (service->fd != -1)
322                         {
323                                 /* listen for new connections */
324                                 FD_SET(service->fd, &read_fds);
325
326                                 if (service->fd > fd_max)
327                                         fd_max = service->fd;
328                         }
329
330                         if (service->connections)
331                         {
332                                 connection_t *c;
333
334                                 for (c = service->connections; c; c = c->next)
335                                 {
336                                         /* check for activity on the connection */
337                                         FD_SET(c->fd, &read_fds);
338                                         if (c->fd > fd_max)
339                                                 fd_max = c->fd;
340                                 }
341                         }
342                 }
343
344 #ifndef _WIN32
345 #if BUILD_ECOSBOARD == 0
346                 if (server_use_pipes == 0)
347                 {
348                         /* add STDIN to read_fds */
349                         FD_SET(fileno(stdin), &read_fds);
350                 }
351 #endif
352 #endif
353
354                 openocd_sleep_prelude();
355                 kept_alive();
356
357                 /* Only while we're sleeping we'll let others run */
358                 retval = socket_select(fd_max + 1, &read_fds, NULL, NULL, &tv);
359                 openocd_sleep_postlude();
360
361                 if (retval == -1)
362                 {
363 #ifdef _WIN32
364
365                         errno = WSAGetLastError();
366
367                         if (errno == WSAEINTR)
368                                 FD_ZERO(&read_fds);
369                         else
370                         {
371                                 LOG_ERROR("error during select: %s", strerror(errno));
372                                 exit(-1);
373                         }
374 #else
375
376                         if (errno == EINTR)
377                         {
378                                 FD_ZERO(&read_fds);
379                         }
380                         else
381                         {
382                                 LOG_ERROR("error during select: %s", strerror(errno));
383                                 exit(-1);
384                         }
385 #endif
386                 }
387
388                 target_call_timer_callbacks();
389                 process_jim_events ();
390
391                 if (retval == 0)
392                 {
393                         /* do regular tasks after at most 100ms */
394                         tv.tv_sec = 0;
395                         tv.tv_usec = 10000;
396                         FD_ZERO(&read_fds); /* eCos leaves read_fds unchanged in this case!  */
397                 }
398
399                 for (service = services; service; service = service->next)
400                 {
401                         /* handle new connections on listeners */
402                         if ((service->fd != -1)
403                                 && (FD_ISSET(service->fd, &read_fds)))
404                         {
405                                 if (service->max_connections > 0)
406                                 {
407                                         add_connection(service, command_context);
408                                 }
409                                 else
410                                 {
411                                         if (service->type != CONNECTION_PIPE)
412                                         {
413                                                 struct sockaddr_in sin;
414                                                 socklen_t address_size = sizeof(sin);
415                                                 int tmp_fd;
416                                                 tmp_fd = accept(service->fd, (struct sockaddr *)&service->sin, &address_size);
417                                                 close_socket(tmp_fd);
418                                         }
419                                         LOG_INFO("rejected '%s' connection, no more connections allowed", service->name);
420                                 }
421                         }
422
423                         /* handle activity on connections */
424                         if (service->connections)
425                         {
426                                 connection_t *c;
427
428                                 for (c = service->connections; c;)
429                                 {
430                                         if ((FD_ISSET(c->fd, &read_fds)) || c->input_pending)
431                                         {
432                                                 if ((retval = service->input(c)) != ERROR_OK)
433                                                 {
434                                                         connection_t *next = c->next;
435                                                         if (service->type == CONNECTION_PIPE)
436                                                         {
437                                                                 /* if connection uses a pipe then shutdown openocd on error */
438                                                                 shutdown_openocd = 1;
439                                                         }
440                                                         remove_connection(service, c);
441                                                         LOG_INFO("dropped '%s' connection - error %d", service->name, retval);
442                                                         c = next;
443                                                         continue;
444                                                 }
445                                         }
446                                         c = c->next;
447                                 }
448                         }
449                 }
450
451 #ifndef _WIN32
452 #if BUILD_ECOSBOARD == 0
453                 /* check for data on stdin if not using pipes */
454                 if (server_use_pipes == 0)
455                 {
456                         if (FD_ISSET(fileno(stdin), &read_fds))
457                         {
458                                 if (getc(stdin) == 'x')
459                                 {
460                                         shutdown_openocd = 1;
461                                 }
462                         }
463                 }
464 #endif
465 #else
466                 MSG msg;
467                 while (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
468                 {
469                         if (msg.message == WM_QUIT)
470                                 shutdown_openocd = 1;
471                 }
472 #endif
473         }
474
475         return ERROR_OK;
476 }
477
478 #ifdef _WIN32
479 BOOL WINAPI ControlHandler(DWORD dwCtrlType)
480 {
481         shutdown_openocd = 1;
482         return TRUE;
483 }
484
485 void sig_handler(int sig) {
486         shutdown_openocd = 1;
487 }
488 #endif
489
490 int server_init(void)
491 {
492 #ifdef _WIN32
493         WORD wVersionRequested;
494         WSADATA wsaData;
495
496         wVersionRequested = MAKEWORD(2, 2);
497
498         if (WSAStartup(wVersionRequested, &wsaData) != 0)
499         {
500                 LOG_ERROR("Failed to Open Winsock");
501                 exit(-1);
502         }
503
504         if (server_use_pipes == 0)
505         {
506                 /* register ctrl-c handler */
507                 SetConsoleCtrlHandler(ControlHandler, TRUE);
508         }
509         else
510         {
511                 /* we are using pipes so ignore ctrl-c */
512                 SetConsoleCtrlHandler(NULL, TRUE);
513         }
514
515         signal(SIGINT, sig_handler);
516         signal(SIGTERM, sig_handler);
517         signal(SIGBREAK, sig_handler);
518         signal(SIGABRT, sig_handler);
519 #endif
520
521         return ERROR_OK;
522 }
523
524 int server_quit(void)
525 {
526         remove_services();
527
528 #ifdef _WIN32
529         WSACleanup();
530         SetConsoleCtrlHandler(ControlHandler, FALSE);
531 #endif
532
533         return ERROR_OK;
534 }
535
536 /* tell the server we want to shut down */
537 static int handle_shutdown_command(struct command_context_s *cmd_ctx,
538                 char *cmd, char **args, int argc)
539 {
540         shutdown_openocd = 1;
541
542         return ERROR_COMMAND_CLOSE_CONNECTION;
543 }
544
545 int server_register_commands(command_context_t *context)
546 {
547         register_command(context, NULL, "shutdown",
548                         handle_shutdown_command, COMMAND_ANY,
549                         "shut the server down");
550
551         return ERROR_OK;
552 }
553
554
555 int server_port_command(struct command_context_s *cmd_ctx,
556                 char *cmd, char **args, int argc, unsigned short *out)
557 {
558         switch (argc) {
559         case 0:
560                 command_print(cmd_ctx, "%d", *out);
561                 break;
562         case 1:
563         {
564                 uint16_t port;
565                 COMMAND_PARSE_NUMBER(u16, args[0], port);
566                 *out = port;
567                 break;
568         }
569         default:
570                 return ERROR_INVALID_ARGUMENTS;
571         }
572         return ERROR_OK;
573 }