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