Debian Codegraph @

common/utils.c

raw
1 /*
2 * Cisco router simulation platform.
3 * Copyright (c) 2005,2006 Christophe Fillot. All rights reserved.
4 *
5 * Utility functions.
6 */
7
8 #include "dynamips_common.h"
9
10 #define _GNU_SOURCE
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <stdarg.h>
15 #include <unistd.h>
16 #include <time.h>
17 #include <signal.h>
18 #include <sys/time.h>
19 #include <sys/ioctl.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/mman.h>
23 #include <sys/socket.h>
24 #include <arpa/inet.h>
25 #include <netdb.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <assert.h>
29 #ifdef __CYGWIN__
30 #include <malloc.h>
31 #endif
32
33 #include "utils.h"
34
35 extern FILE *log_file;
36
37 /* Add an element to a list */
38 m_list_t *m_list_add(m_list_t **head,void *data)
39 {
40 m_list_t *item;
41
42 if ((item = malloc(sizeof(*item))) != NULL) {
43 item->data = data;
44 item->next = *head;
45 *head = item;
46 }
47
48 return item;
49 }
50
51 /* Dynamic sprintf */
52 char *dyn_sprintf(const char *fmt,...)
53 {
54 int n,size = 512;
55 va_list ap;
56 char *p,*p2;
57
58 if ((p = malloc(size)) == NULL) {
59 perror("dyn_sprintf: malloc");
60 return NULL;
61 }
62
63 for(;;)
64 {
65 /* Try to print in the allocated space */
66 va_start(ap,fmt);
67 n = vsnprintf(p,size,fmt,ap);
68 va_end(ap);
69
70 /* If that worked, return the string */
71 if ((n > -1) && (n < size))
72 return p;
73
74 /* Else try again with more space. */
75 if (n > -1)
76 size = n + 1;
77 else
78 size *= 2;
79
80 if ((p2 = realloc(p,size)) == NULL) {
81 perror("dyn_sprintf: realloc");
82 free(p);
83 return NULL;
84 }
85
86 p = p2;
87 }
88 }
89
90 /* Split a string */
91 int m_strsplit(char *str,char delim,char **array,int max_count)
92 {
93 int i,pos = 0;
94 size_t len;
95 char *ptr;
96
97 for(i=0;i<max_count;i++)
98 array[i] = NULL;
99
100 do {
101 if (pos == max_count)
102 goto error;
103
104 ptr = strchr(str,delim);
105 if (!ptr)
106 ptr = str + strlen(str);
107
108 len = ptr - str;
109
110 if (!(array[pos] = malloc(len+1)))
111 goto error;
112
113 memcpy(array[pos],str,len);
114 array[pos][len] = 0;
115
116 str = ptr + 1;
117 pos++;
118 }while(*ptr);
119
120 return(pos);
121
122 error:
123 for(i=0;i<max_count;i++)
124 free(array[i]);
125 return(-1);
126 }
127
128 /* Tokenize a string */
129 int m_strtok(char *str,char delim,char **array,int max_count)
130 {
131 int i,pos = 0;
132 size_t len;
133 char *ptr;
134
135 for(i=0;i<max_count;i++)
136 array[i] = NULL;
137
138 do {
139 if (pos == max_count)
140 goto error;
141
142 ptr = strchr(str,delim);
143 if (!ptr)
144 ptr = str + strlen(str);
145
146 len = ptr - str;
147
148 if (!(array[pos] = malloc(len+1)))
149 goto error;
150
151 memcpy(array[pos],str,len);
152 array[pos][len] = 0;
153
154 while(*ptr == delim)
155 ptr++;
156
157 str = ptr;
158 pos++;
159 }while(*ptr);
160
161 return(pos);
162
163 error:
164 for(i=0;i<max_count;i++)
165 free(array[i]);
166 return(-1);
167 }
168
169 /* Quote a string */
170 char *m_strquote(char *buffer,size_t buf_len,char *str)
171 {
172 char *p;
173
174 if (!(p = strpbrk(str," \t\"'")))
175 return str;
176
177 snprintf(buffer,buf_len,"\"%s\"",str);
178 return buffer;
179 }
180
181 /*
182 * Decode from hex.
183 *
184 * hex to raw bytes, returning count of bytes.
185 * maxlen limits output buffer size.
186 */
187 int hex_decode(unsigned char *out,const unsigned char *in,int maxlen)
188 {
189 #define BAD -1
190 static const char hexval[] = {
191 BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD,
192 BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD,
193 BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD,
194 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,BAD,BAD, BAD,BAD,BAD,BAD,
195 BAD, 10, 11, 12, 13, 14, 15,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD,
196 BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD,
197 BAD, 10, 11, 12, 13, 14, 15,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD
198 };
199 int len = 0;
200 int empty = TRUE;
201
202 for(;len < maxlen;) {
203 if (*in > sizeof(hexval) || hexval[*in] == BAD)
204 break;
205
206 if (empty) {
207 *out = (unsigned char)hexval[*in] << 4;
208 }
209 else {
210 *out |= (unsigned char)hexval[*in];
211 ++out;
212 ++len;
213 }
214 ++in;
215 empty = !empty;
216 }
217
218 return(len);
219 }
220
221 /* Ugly function that dumps a structure in hexa and ascii. */
222 void mem_dump(FILE *f_output,u_char *pkt,u_int len)
223 {
224 u_int x,i = 0, tmp;
225
226 while (i < len)
227 {
228 if ((len - i) > 16)
229 x = 16;
230 else x = len - i;
231
232 fprintf(f_output,"%4.4x: ",i);
233
234 for (tmp=0;tmp<x;tmp++)
235 fprintf(f_output,"%2.2x ",pkt[i+tmp]);
236 for (tmp=x;tmp<16;tmp++) fprintf(f_output," ");
237
238 for (tmp=0;tmp<x;tmp++) {
239 char c = pkt[i+tmp];
240
241 if (((c >= 'A') && (c <= 'Z')) ||
242 ((c >= 'a') && (c <= 'z')) ||
243 ((c >= '0') && (c <= '9')))
244 fprintf(f_output,"%c",c);
245 else
246 fputs(".",f_output);
247 }
248
249 i += x;
250 fprintf(f_output,"\n");
251 }
252
253 fprintf(f_output,"\n");
254 fflush(f_output);
255 }
256
257 /* Logging function */
258 void m_flog(FILE *fd,char *module,char *fmt,va_list ap)
259 {
260 struct timespec spec;
261 struct tm tmn;
262 char buf[256];
263
264 if (fd != NULL) {
265 clock_gettime(CLOCK_REALTIME, &spec);
266 gmtime_r(&spec.tv_sec, &tmn);
267
268 strftime(buf,sizeof(buf),"%b %d %H:%M:%S",&tmn);
269
270 fprintf(fd,"%s.%03ld %s: ",buf,(long)spec.tv_nsec/1000000,module);
271 vfprintf(fd,fmt,ap);
272 fflush(fd);
273 }
274 }
275
276 /* Logging function */
277 void m_log(char *module,char *fmt,...)
278 {
279 va_list ap;
280
281 va_start(ap,fmt);
282 m_flog(log_file,module,fmt,ap);
283 va_end(ap);
284 }
285
286 /* Write an array of string to a logfile */
287 void m_flog_str_array(FILE *fd,int count,char *str[])
288 {
289 int i;
290
291 for(i=0;i<count;i++)
292 fprintf(fd,"%s ",str[i]);
293
294 fprintf(fd,"\n");
295 fflush(fd);
296 }
297
298 /* Returns a line from specified file (remove trailing '\n') */
299 char *m_fgets(char *buffer,int size,FILE *fd)
300 {
301 int len;
302
303 buffer[0] = '\0';
304 fgets(buffer,size,fd);
305
306 if ((len = strlen(buffer)) == 0)
307 return NULL;
308
309 /* remove trailing '\n' */
310 if (buffer[len-1] == '\n')
311 buffer[len-1] = '\0';
312
313 return buffer;
314 }
315
316 /* Read a file and returns it in a buffer */
317 int m_read_file(const char *filename,u_char **buffer,size_t *length)
318 {
319 FILE *fd;
320 long len;
321
322 // open
323 fd = fopen(filename,"rb");
324 if (fd == NULL) {
325 return(-1);
326 }
327
328 // len
329 fseek(fd, 0, SEEK_END);
330 len = ftell(fd);
331 fseek(fd, 0, SEEK_SET);
332 if (len < 0 || ferror(fd)) {
333 fclose(fd);
334 return(-1);
335 }
336
337 if (length) {
338 *length = (size_t)len;
339 }
340
341 // data
342 if (buffer) {
343 *buffer = (u_char *)malloc((size_t)len);
344 if (*buffer == NULL || fread(*buffer, (size_t)len, 1, fd) != 1) {
345 free(*buffer);
346 *buffer = NULL;
347 fclose(fd);
348 return(-1);
349 }
350 }
351
352 // close
353 fclose(fd);
354 return(0);
355 }
356
357 /* Allocate aligned memory */
358 void *m_memalign(size_t boundary,size_t size)
359 {
360 void *p;
361
362 #if defined(__linux__) || HAS_POSIX_MEMALIGN
363 if (posix_memalign((void *)&p,boundary,size))
364 #else
365 #if defined(__CYGWIN__) || defined(SUNOS)
366 if (!(p = memalign(boundary,size)))
367 #else
368 if (!(p = malloc(size)))
369 #endif
370 #endif
371 return NULL;
372
373 assert(((m_iptr_t)p & (boundary-1)) == 0);
374 return p;
375 }
376
377 /* Block specified signal for calling thread */
378 int m_signal_block(int sig)
379 {
380 sigset_t sig_mask;
381 sigemptyset(&sig_mask);
382 sigaddset(&sig_mask,sig);
383 return(pthread_sigmask(SIG_BLOCK,&sig_mask,NULL));
384 }
385
386 /* Unblock specified signal for calling thread */
387 int m_signal_unblock(int sig)
388 {
389 sigset_t sig_mask;
390 sigemptyset(&sig_mask);
391 sigaddset(&sig_mask,sig);
392 return(pthread_sigmask(SIG_UNBLOCK,&sig_mask,NULL));
393 }
394
395 /* Set non-blocking mode on a file descriptor */
396 int m_fd_set_non_block(int fd)
397 {
398 int flags;
399
400 if ((flags = fcntl(fd,F_GETFL,0)) < 0)
401 return(-1);
402
403 return(fcntl(fd,F_SETFL, flags | O_NONBLOCK));
404 }
405
406 /* Sync a memory zone */
407 int memzone_sync(void *addr, size_t len)
408 {
409 return(msync(addr, len, MS_SYNC));
410 }
411
412 /* Sync all mappings of a memory zone */
413 int memzone_sync_all(void *addr, size_t len)
414 {
415 return(msync(addr, len, MS_SYNC | MS_INVALIDATE));
416 }
417
418 /* Unmap a memory zone */
419 int memzone_unmap(void *addr, size_t len)
420 {
421 return(munmap(addr, len));
422 }
423
424 /* Return a memory zone or NULL on error */
425 static void *mmap_or_null(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
426 {
427 void *ptr;
428
429 if ((ptr = mmap(addr, length, prot, flags, fd, offset)) == MAP_FAILED)
430 return(NULL);
431
432 return(ptr);
433 }
434
435 /* Map a memory zone as an executable area */
436 u_char *memzone_map_exec_area(size_t len)
437 {
438 return(mmap_or_null(NULL,len,PROT_EXEC|PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,(off_t)0));
439 }
440
441 /* Map a memory zone from a file */
442 u_char *memzone_map_file(int fd,size_t len)
443 {
444 return(mmap_or_null(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,(off_t)0));
445 }
446
447 /* Map a memory zone from a ro file */
448 u_char *memzone_map_file_ro(int fd,size_t len)
449 {
450 return(mmap_or_null(NULL,len,PROT_READ,MAP_PRIVATE,fd,(off_t)0));
451 }
452
453 /* Map a memory zone from a file, with copy-on-write (COW) */
454 u_char *memzone_map_cow_file(int fd,size_t len)
455 {
456 return(mmap_or_null(NULL,len,PROT_READ|PROT_WRITE,MAP_PRIVATE,fd,(off_t)0));
457 }
458
459 /* Create a file to serve as a memory zone */
460 int memzone_create_file(char *filename,size_t len,u_char **ptr)
461 {
462 int fd;
463
464 if ((fd = open(filename,O_CREAT|O_RDWR,S_IRWXU)) == -1) {
465 perror("memzone_create_file: open");
466 return(-1);
467 }
468
469 if (ftruncate(fd,len) == -1) {
470 perror("memzone_create_file: ftruncate");
471 close(fd);
472 return(-1);
473 }
474
475 *ptr = memzone_map_file(fd,len);
476
477 if (!*ptr) {
478 close(fd);
479 fd = -1;
480 }
481
482 return(fd);
483 }
484
485 /* Open a file to serve as a COW memory zone */
486 int memzone_open_cow_file(char *filename,size_t len,u_char **ptr)
487 {
488 int fd;
489
490 if ((fd = open(filename,O_RDONLY,S_IRWXU)) == -1) {
491 perror("memzone_open_file: open");
492 return(-1);
493 }
494
495 *ptr = memzone_map_cow_file(fd,len);
496
497 if (!*ptr) {
498 close(fd);
499 fd = -1;
500 }
501
502 return(fd);
503 }
504
505 /* Open a file and map it in memory */
506 int memzone_open_file(char *filename,u_char **ptr,off_t *fsize)
507 {
508 struct stat fprop;
509 int fd;
510
511 if ((fd = open(filename,O_RDWR,S_IRWXU)) == -1)
512 return(-1);
513
514 if (fstat(fd,&fprop) == -1)
515 goto err_fstat;
516
517 *fsize = fprop.st_size;
518 if (!(*ptr = memzone_map_file(fd,*fsize)))
519 goto err_mmap;
520
521 return(fd);
522
523 err_mmap:
524 err_fstat:
525 close(fd);
526 return(-1);
527 }
528
529 int memzone_open_file_ro(char *filename,u_char **ptr,off_t *fsize)
530 {
531 struct stat fprop;
532 int fd;
533
534 if ((fd = open(filename,O_RDONLY,S_IRWXU)) == -1)
535 return(-1);
536
537 if (fstat(fd,&fprop) == -1)
538 goto err_fstat;
539
540 *fsize = fprop.st_size;
541 if (!(*ptr = memzone_map_file_ro(fd,*fsize)))
542 goto err_mmap;
543
544 return(fd);
545
546 err_mmap:
547 err_fstat:
548 close(fd);
549 return(-1);
550 }
551
552 /* Compute NVRAM checksum */
553 m_uint16_t nvram_cksum(m_uint16_t *ptr,size_t count)
554 {
555 m_uint32_t sum = 0;
556
557 while(count > 1) {
558 sum = sum + ntohs(*ptr);
559 ptr++;
560 count -= sizeof(m_uint16_t);
561 }
562
563 if (count > 0)
564 sum = sum + ((ntohs(*ptr) & 0xFF) << 8);
565
566 while(sum>>16)
567 sum = (sum & 0xffff) + (sum >> 16);
568
569 return(~sum);
570 }
571
572 /* Byte-swap a memory block */
573 void mem_bswap32(void *ptr,size_t len)
574 {
575 m_uint32_t *p _not_aligned = ptr;
576 size_t count = len >> 2;
577 int i;
578
579 for(i=0;i<count;i++,p++)
580 *p = swap32(*p);
581 }
582
583 /* Reverse a byte */
584 m_uint8_t m_reverse_u8(m_uint8_t val)
585 {
586 m_uint8_t res = 0;
587 int i;
588
589 for(i=0;i<8;i++)
590 if (val & (1 << i))
591 res |= 1 << (7 - i);
592
593 return(res);
594 }
595
596 /* Generate a pseudo random block of data */
597 void m_randomize_block(m_uint8_t *buf,size_t len)
598 {
599 int i;
600
601 for(i=0;i<len;i++)
602 buf[i] = rand() & 0xFF;
603 }
604
605 /* Free an FD pool */
606 void fd_pool_free(fd_pool_t *pool)
607 {
608 fd_pool_t *p,*next;
609 int i;
610
611 for(p=pool;p;p=next) {
612 next = p->next;
613
614 for(i=0;i<FD_POOL_MAX;i++) {
615 if (p->fd[i] != -1) {
616 shutdown(p->fd[i],2);
617 close(p->fd[i]);
618 }
619 }
620
621 if (pool != p)
622 free(p);
623 }
624 }
625
626 /* Initialize an empty pool */
627 void fd_pool_init(fd_pool_t *pool)
628 {
629 int i;
630
631 for(i=0;i<FD_POOL_MAX;i++)
632 pool->fd[i] = -1;
633
634 pool->next = NULL;
635 }
636
637 /* Get a free slot for a FD in a pool */
638 int fd_pool_get_free_slot(fd_pool_t *pool,int **slot)
639 {
640 fd_pool_t *p;
641 int i;
642
643 for(p=pool;p;p=p->next) {
644 for(i=0;i<FD_POOL_MAX;i++) {
645 if (p->fd[i] == -1) {
646 *slot = &p->fd[i];
647 return(0);
648 }
649 }
650 }
651
652 /* No free slot, allocate a new pool */
653 if (!(p = malloc(sizeof(*p))))
654 return(-1);
655
656 fd_pool_init(p);
657 *slot = &p->fd[0];
658
659 p->next = pool->next;
660 pool->next = p;
661 return(0);
662 }
663
664 /* Fill a FD set and get the maximum FD in order to use with select */
665 int fd_pool_set_fds(fd_pool_t *pool,fd_set *fds)
666 {
667 fd_pool_t *p;
668 int i,max_fd = -1;
669
670 for(p=pool;p;p=p->next)
671 for(i=0;i<FD_POOL_MAX;i++) {
672 if (p->fd[i] != -1) {
673 FD_SET(p->fd[i],fds);
674
675 if (p->fd[i] > max_fd)
676 max_fd = p->fd[i];
677 }
678 }
679
680 return(max_fd);
681 }
682
683 /* Send a buffer to all FDs of a pool */
684 int fd_pool_send(fd_pool_t *pool,void *buffer,size_t len,int flags)
685 {
686 fd_pool_t *p;
687 ssize_t res;
688 int i,err;
689
690 for(p=pool,err=0;p;p=p->next)
691 for(i=0;i<FD_POOL_MAX;i++) {
692 if (p->fd[i] == -1)
693 continue;
694
695 res = send(p->fd[i],buffer,len,flags);
696
697 if (res != len) {
698 shutdown(p->fd[i],2);
699 close(p->fd[i]);
700 p->fd[i] = -1;
701 err++;
702 }
703 }
704
705 return(err);
706 }
707
708 /* Call a function for each FD having incoming data */
709 int fd_pool_check_input(fd_pool_t *pool,fd_set *fds,
710 void (*cbk)(int *fd_slot,void *opt),void *opt)
711 {
712 fd_pool_t *p;
713 int i,count;
714
715 for(p=pool,count=0;p;p=p->next)
716 for(i=0;i<FD_POOL_MAX;i++) {
717 if ((p->fd[i] != -1) && FD_ISSET(p->fd[i],fds)) {
718 cbk(&p->fd[i],opt);
719 count++;
720 }
721 }
722
723 return(count);
724 }
725
726 /* Equivalent to fprintf, but for a posix fd */
727 ssize_t fd_printf(int fd,int flags,char *fmt,...)
728 {
729 char buffer[2048];
730 va_list ap;
731
732 va_start(ap,fmt);
733 vsnprintf(buffer,sizeof(buffer),fmt,ap);
734 va_end(ap);
735
736 return(send(fd,buffer,strlen(buffer),flags));
737 }