e186724d59359470112df82a34612a5566d1c425
[fw/openocd] / src / helper / ioutil.c
1 /***************************************************************************
2  *   Copyright (C) 2007-2010 by Ã˜yvind Harboe                              *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
18  ***************************************************************************/
19
20 /* this file contains various functionality useful to standalone systems */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include "log.h"
27 #include "time_support.h"
28
29 #ifdef HAVE_ARPA_INET_H
30 #include <arpa/inet.h>
31 #endif
32 #ifdef HAVE_DIRENT_H
33 #include <dirent.h>
34 #endif
35 #ifdef HAVE_NETDB_H
36 #include <netdb.h>
37 #endif
38 #ifdef HAVE_NET_IF_H
39 #include <net/if.h>
40 #endif
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
43 #endif
44 #ifdef HAVE_SYS_STAT_H
45 #include <sys/stat.h>
46 #endif
47 #ifdef HAVE_IFADDRS_H
48 #include <ifaddrs.h>
49 #endif
50 #ifdef HAVE_MALLOC_H
51 #include <malloc.h>
52 #endif
53
54 /* loads a file and returns a pointer to it in memory. The file contains
55  * a 0 byte(sentinel) after len bytes - the length of the file. */
56 static int load_file(const char *fileName, char **data, size_t *len)
57 {
58         /* ensure returned length is always sane */
59         *len = 0;
60
61         FILE *pFile;
62         pFile = fopen(fileName, "rb");
63         if (pFile == NULL) {
64                 LOG_ERROR("Can't open %s", fileName);
65                 return ERROR_FAIL;
66         }
67         if (fseek(pFile, 0, SEEK_END) != 0) {
68                 LOG_ERROR("Can't open %s", fileName);
69                 fclose(pFile);
70                 return ERROR_FAIL;
71         }
72         long fsize = ftell(pFile);
73         if (fsize == -1) {
74                 LOG_ERROR("Can't open %s", fileName);
75                 fclose(pFile);
76                 return ERROR_FAIL;
77         }
78         *len = fsize;
79
80         if (fseek(pFile, 0, SEEK_SET) != 0) {
81                 LOG_ERROR("Can't open %s", fileName);
82                 fclose(pFile);
83                 return ERROR_FAIL;
84         }
85         *data = malloc(*len + 1);
86         if (*data == NULL) {
87                 LOG_ERROR("Can't open %s", fileName);
88                 fclose(pFile);
89                 return ERROR_FAIL;
90         }
91
92         if (fread(*data, 1, *len, pFile) != *len) {
93                 fclose(pFile);
94                 free(*data);
95                 LOG_ERROR("Can't open %s", fileName);
96                 return ERROR_FAIL;
97         }
98         fclose(pFile);
99
100         /* 0-byte after buffer (not included in *len) serves as a sentinel */
101         (*data)[*len] = 0;
102
103         return ERROR_OK;
104 }
105
106 COMMAND_HANDLER(handle_cat_command)
107 {
108         if (CMD_ARGC != 1)
109                 return ERROR_COMMAND_SYNTAX_ERROR;
110
111         /* NOTE!!! we only have line printing capability so we print the entire file as a single
112          * line. */
113         char *data;
114         size_t len;
115
116         int retval = load_file(CMD_ARGV[0], &data, &len);
117         if (retval == ERROR_OK) {
118                 command_print(CMD_CTX, "%s", data);
119                 free(data);
120         } else
121                 command_print(CMD_CTX, "%s not found", CMD_ARGV[0]);
122
123         return ERROR_OK;
124 }
125
126 COMMAND_HANDLER(handle_trunc_command)
127 {
128         if (CMD_ARGC != 1)
129                 return ERROR_COMMAND_SYNTAX_ERROR;
130
131         FILE *config_file = NULL;
132         config_file = fopen(CMD_ARGV[0], "w");
133         if (config_file != NULL)
134                 fclose(config_file);
135
136         return ERROR_OK;
137 }
138
139 #ifdef HAVE_MALLOC_H
140 COMMAND_HANDLER(handle_meminfo_command)
141 {
142         static int prev;
143         struct mallinfo info;
144
145         if (CMD_ARGC != 0)
146                 return ERROR_COMMAND_SYNTAX_ERROR;
147
148         info = mallinfo();
149
150         if (prev > 0)
151                 command_print(CMD_CTX, "Diff:            %d", prev - info.fordblks);
152         prev = info.fordblks;
153
154         command_print(CMD_CTX, "Available ram:   %d", info.fordblks);
155
156         return ERROR_OK;
157 }
158 #endif
159
160 COMMAND_HANDLER(handle_append_command)
161 {
162         if (CMD_ARGC < 1)
163                 return ERROR_COMMAND_SYNTAX_ERROR;
164
165         int retval = ERROR_FAIL;
166         FILE *config_file = NULL;
167
168         config_file = fopen(CMD_ARGV[0], "a");
169         if (config_file != NULL) {
170                 fseek(config_file, 0, SEEK_END);
171
172                 unsigned i;
173                 for (i = 1; i < CMD_ARGC; i++) {
174                         if (fwrite(CMD_ARGV[i], 1, strlen(CMD_ARGV[i]),
175                                         config_file) != strlen(CMD_ARGV[i]))
176                                 break;
177                         if (i != CMD_ARGC - 1) {
178                                 if (fwrite(" ", 1, 1, config_file) != 1)
179                                         break;
180                         }
181                 }
182                 if ((i == CMD_ARGC) && (fwrite("\n", 1, 1, config_file) == 1))
183                         retval = ERROR_OK;
184
185                 fclose(config_file);
186         }
187
188         return retval;
189 }
190
191 COMMAND_HANDLER(handle_cp_command)
192 {
193         if (CMD_ARGC != 2)
194                 return ERROR_COMMAND_SYNTAX_ERROR;
195
196         /* NOTE!!! we only have line printing capability so we print the entire file as a single
197          * line. */
198         char *data;
199         size_t len;
200
201         int retval = load_file(CMD_ARGV[0], &data, &len);
202         if (retval != ERROR_OK)
203                 return retval;
204
205         FILE *f = fopen(CMD_ARGV[1], "wb");
206         if (f == NULL)
207                 retval = ERROR_COMMAND_SYNTAX_ERROR;
208
209         size_t pos = 0;
210         for (;; ) {
211                 size_t chunk = len - pos;
212                 static const size_t maxChunk = 512 * 1024;      /* ~1/sec */
213                 if (chunk > maxChunk)
214                         chunk = maxChunk;
215
216                 if ((retval == ERROR_OK) && (fwrite(data + pos, 1, chunk, f) != chunk))
217                         retval = ERROR_COMMAND_SYNTAX_ERROR;
218
219                 if (retval != ERROR_OK)
220                         break;
221
222                 command_print(CMD_CTX, "%zu", len - pos);
223
224                 pos += chunk;
225
226                 if (pos == len)
227                         break;
228         }
229
230         if (retval == ERROR_OK)
231                 command_print(CMD_CTX, "Copied %s to %s", CMD_ARGV[0], CMD_ARGV[1]);
232         else
233                 command_print(CMD_CTX, "copy failed");
234
235         if (data != NULL)
236                 free(data);
237         if (f != NULL)
238                 fclose(f);
239
240         if (retval != ERROR_OK)
241                 unlink(CMD_ARGV[1]);
242
243         return retval;
244 }
245
246 COMMAND_HANDLER(handle_rm_command)
247 {
248         if (CMD_ARGC != 1)
249                 return ERROR_COMMAND_SYNTAX_ERROR;
250
251         bool del = false;
252         if (rmdir(CMD_ARGV[0]) == 0)
253                 del = true;
254         else if (unlink(CMD_ARGV[0]) == 0)
255                 del = true;
256
257         return del ? ERROR_OK : ERROR_FAIL;
258 }
259
260 static int ioutil_Jim_Command_ls(Jim_Interp *interp,
261         int argc,
262         Jim_Obj * const *argv)
263 {
264         if (argc != 2) {
265                 Jim_WrongNumArgs(interp, 1, argv, "ls ?dir?");
266                 return JIM_ERR;
267         }
268
269         const char *name = Jim_GetString(argv[1], NULL);
270
271         DIR *dirp = NULL;
272         dirp = opendir(name);
273         if (dirp == NULL)
274                 return JIM_ERR;
275         Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
276
277         for (;; ) {
278                 struct dirent *entry = NULL;
279                 entry = readdir(dirp);
280                 if (entry == NULL)
281                         break;
282
283                 if ((strcmp(".", entry->d_name) == 0) || (strcmp("..", entry->d_name) == 0))
284                         continue;
285
286                 Jim_ListAppendElement(interp, objPtr,
287                         Jim_NewStringObj(interp, entry->d_name, strlen(entry->d_name)));
288         }
289         closedir(dirp);
290
291         Jim_SetResult(interp, objPtr);
292
293         return JIM_OK;
294 }
295
296 static int ioutil_Jim_Command_peek(Jim_Interp *interp,
297         int argc,
298         Jim_Obj *const *argv)
299 {
300         if (argc != 2) {
301                 Jim_WrongNumArgs(interp, 1, argv, "peek ?address?");
302                 return JIM_ERR;
303         }
304
305         long address;
306         if (Jim_GetLong(interp, argv[1], &address) != JIM_OK)
307                 return JIM_ERR;
308
309         int value = *((volatile int *) address);
310
311         Jim_SetResult(interp, Jim_NewIntObj(interp, value));
312
313         return JIM_OK;
314 }
315
316 static int ioutil_Jim_Command_poke(Jim_Interp *interp,
317         int argc,
318         Jim_Obj *const *argv)
319 {
320         if (argc != 3) {
321                 Jim_WrongNumArgs(interp, 1, argv, "poke ?address? ?value?");
322                 return JIM_ERR;
323         }
324
325         long address;
326         if (Jim_GetLong(interp, argv[1], &address) != JIM_OK)
327                 return JIM_ERR;
328         long value;
329         if (Jim_GetLong(interp, argv[2], &value) != JIM_OK)
330                 return JIM_ERR;
331
332         *((volatile int *) address) = value;
333
334         return JIM_OK;
335 }
336
337 /* not so pretty code to fish out ip number*/
338 static int ioutil_Jim_Command_ip(Jim_Interp *interp, int argc,
339         Jim_Obj *const *argv)
340 {
341 #if !defined(__CYGWIN__)
342         Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
343
344         struct ifaddrs *ifa = NULL, *ifp = NULL;
345
346         if (getifaddrs(&ifp) < 0)
347                 return JIM_ERR;
348
349         for (ifa = ifp; ifa; ifa = ifa->ifa_next) {
350                 char ip[200];
351                 socklen_t salen;
352
353                 if (ifa->ifa_addr->sa_family == AF_INET)
354                         salen = sizeof(struct sockaddr_in);
355                 else if (ifa->ifa_addr->sa_family == AF_INET6)
356                         salen = sizeof(struct sockaddr_in6);
357                 else
358                         continue;
359
360                 if (getnameinfo(ifa->ifa_addr, salen, ip, sizeof(ip), NULL, 0,
361                                 NI_NUMERICHOST) < 0)
362                         continue;
363
364                 Jim_AppendString(interp, tclOutput, ip, strlen(ip));
365                 break;
366
367         }
368
369         freeifaddrs(ifp);
370 #else
371         Jim_Obj *tclOutput = Jim_NewStringObj(interp, "fixme!!!", 0);
372         LOG_ERROR("NOT IMPLEMENTED!!!");
373 #endif
374         Jim_SetResult(interp, tclOutput);
375
376         return JIM_OK;
377 }
378
379 #ifdef HAVE_SYS_IOCTL_H
380 #ifdef SIOCGIFHWADDR
381 /* not so pretty code to fish out eth0 mac address */
382 static int ioutil_Jim_Command_mac(Jim_Interp *interp, int argc,
383         Jim_Obj *const *argv)
384 {
385         struct ifreq *ifr, *ifend;
386         struct ifreq ifreq;
387         struct ifconf ifc;
388         struct ifreq ifs[5];
389         int SockFD;
390
391         SockFD = socket(AF_INET, SOCK_DGRAM, 0);
392         if (SockFD < 0)
393                 return JIM_ERR;
394
395         ifc.ifc_len = sizeof(ifs);
396         ifc.ifc_req = ifs;
397         if (ioctl(SockFD, SIOCGIFCONF, &ifc) < 0) {
398                 close(SockFD);
399                 return JIM_ERR;
400         }
401
402         ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
403         for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
404                 /* if (ifr->ifr_addr.sa_family == AF_INET) */
405                 {
406                         if (strcmp("eth0", ifr->ifr_name) != 0)
407                                 continue;
408                         strncpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
409                         if (ioctl(SockFD, SIOCGIFHWADDR, &ifreq) < 0) {
410                                 close(SockFD);
411                                 return JIM_ERR;
412                         }
413
414                         close(SockFD);
415
416                         Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
417
418                         char buffer[256];
419                         sprintf(buffer, "%02x-%02x-%02x-%02x-%02x-%02x",
420                                 ifreq.ifr_hwaddr.sa_data[0]&0xff,
421                                 ifreq.ifr_hwaddr.sa_data[1]&0xff,
422                                 ifreq.ifr_hwaddr.sa_data[2]&0xff,
423                                 ifreq.ifr_hwaddr.sa_data[3]&0xff,
424                                 ifreq.ifr_hwaddr.sa_data[4]&0xff,
425                                 ifreq.ifr_hwaddr.sa_data[5]&0xff);
426
427                         Jim_AppendString(interp, tclOutput, buffer, strlen(buffer));
428
429                         Jim_SetResult(interp, tclOutput);
430
431                         return JIM_OK;
432                 }
433         }
434         close(SockFD);
435
436         return JIM_ERR;
437
438 }
439 #endif
440 #endif
441
442 static const struct command_registration ioutil_command_handlers[] = {
443         {
444                 .name = "cat",
445                 .handler = handle_cat_command,
446                 .mode = COMMAND_ANY,
447                 .help = "display text file content",
448                 .usage = "file_name",
449         },
450         {
451                 .name = "trunc",
452                 .handler = handle_trunc_command,
453                 .mode = COMMAND_ANY,
454                 .help = "truncate a file to zero length",
455                 .usage = "file_name",
456         },
457         {
458                 .name = "cp",
459                 .handler = handle_cp_command,
460                 .mode = COMMAND_ANY,
461                 .help = "copy a file",
462                 .usage = "src_file_name dst_file_name",
463         },
464         {
465                 .name = "append_file",
466                 .handler = handle_append_command,
467                 .mode = COMMAND_ANY,
468                 .help = "append a variable number of strings to a file",
469                 .usage = "file_name [<string1>, [<string2>, ...]]",
470         },
471 #ifdef HAVE_MALLOC_H
472         {
473                 .name = "meminfo",
474                 .handler = handle_meminfo_command,
475                 .mode = COMMAND_ANY,
476                 .help = "display free heap space",
477         },
478 #endif
479         {
480                 .name = "rm",
481                 .mode = COMMAND_ANY,
482                 .handler = handle_rm_command,
483                 .help = "remove a directory or file",
484                 .usage = "file_name",
485         },
486
487         /*
488          * Peek and poke are security holes -- they manipulate
489          * server-internal addresses.
490          */
491
492         /* jim handlers */
493         {
494                 .name = "peek",
495                 .mode = COMMAND_ANY,
496                 .jim_handler = ioutil_Jim_Command_peek,
497                 .help = "peek at a memory address",
498                 .usage = "address",
499         },
500         {
501                 .name = "poke",
502                 .mode = COMMAND_ANY,
503                 .jim_handler = ioutil_Jim_Command_poke,
504                 .help = "poke at a memory address",
505                 .usage = "address value",
506         },
507         {
508                 .name = "ls",
509                 .mode = COMMAND_ANY,
510                 .jim_handler = ioutil_Jim_Command_ls,
511                 .help = "show a listing of files",
512                 .usage = "dirname",
513         },
514 #ifdef HAVE_SYS_IOCTL_H
515 #ifdef SIOCGIFHWADDR
516         {
517                 .name = "mac",
518                 .mode = COMMAND_ANY,
519                 .jim_handler = ioutil_Jim_Command_mac,
520                 .help = "show MAC address",
521         },
522 #endif
523 #endif
524         {
525                 .name = "ip",
526                 .jim_handler = ioutil_Jim_Command_ip,
527                 .mode = COMMAND_ANY,
528                 .help = "show IP address",
529         },
530         COMMAND_REGISTRATION_DONE
531 };
532
533 int ioutil_init(struct command_context *cmd_ctx)
534 {
535         return register_commands(cmd_ctx, NULL, ioutil_command_handlers);
536 }