1 /*
2 * Miscellaneous useful functions.
3 *
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1
6 *
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
11 *
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
15 * License.
16 *
17 * The Original Code is the MPEG TS, PS and ES tools.
18 *
19 * The Initial Developer of the Original Code is Amino Communications Ltd.
20 * Portions created by the Initial Developer are Copyright (C) 2008
21 * the Initial Developer. All Rights Reserved.
22 *
23 * Contributor(s):
24 * Amino Communications Ltd, Swavesey, Cambridge UK
25 *
26 * ***** END LICENSE BLOCK *****
27 */
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <math.h>
32
33 // For the command line utilities
34 #include <limits.h>
35 #include <errno.h>
36 #include <string.h>
37 #include <fcntl.h> // O_... flags
38
39 #ifdef _WIN32
40 #include <winsock2.h>
41 #include <ws2tcpip.h>
42 #include <io.h>
43 #else // _WIN32
44 // For the socket handling
45 #include <sys/types.h>
46 #include <sys/socket.h>
47 #include <netdb.h>
48 #include <netinet/in.h> // sockaddr_in
49 #include <arpa/inet.h> // inet_aton
50 #include <unistd.h> // open, close
51 #endif // _WIN32
52
53 #include "compat.h"
54 #include "misc_fns.h"
55 #include "es_fns.h"
56 #include "pes_fns.h"
57
58 #define DEBUG_SEEK 1
59
60 // ============================================================
61 // CRC calculation
62 // ============================================================
63
64 static uint32_t crc_table[256];
65
66 /*
67 * Populate the (internal) CRC table. May safely be called more than once.
68 */
make_crc_table()69 static void make_crc_table()
70 {
71 int i, j;
72 int already_done = 0;
73 uint32_t crc;
74
75 if (already_done)
76 return;
77 else
78 already_done = 1;
79
80 for (i = 0; i < 256; i++)
81 {
82 crc = i << 24;
83 for (j = 0; j < 8; j++)
84 {
85 if (crc & 0x80000000L)
86 crc = (crc << 1) ^ CRC32_POLY;
87 else
88 crc = ( crc << 1 );
89 }
90 crc_table[i] = crc;
91 }
92
93 }
94
95 /*
96 * Compute CRC32 over a block of data, by table method.
97 *
98 * Returns a working value, suitable for re-input for further blocks
99 *
100 * Notes: Input value should be 0xffffffff for the first block,
101 * else return value from previous call (not sure if that
102 * needs complementing before being passed back in).
103 */
crc32_block(uint32_t crc,byte * pData,int blk_len)104 extern uint32_t crc32_block(uint32_t crc, byte *pData, int blk_len)
105 {
106 static int table_made = FALSE;
107 int i, j;
108
109 if (!table_made) make_crc_table();
110
111 for (j = 0; j < blk_len; j++)
112 {
113 i = ((crc >> 24) ^ *pData++) & 0xff;
114 crc = (crc << 8) ^ crc_table[i];
115 }
116 return crc;
117 }
118
119 /*
120 * Print out (the first `max`) bytes of a byte array.
121 *
122 * - `stream` is the stream to print on.
123 * - `name` is identifying text to start the report with.
124 * - `data` is the byte data to print. This may be NULL.
125 * - `length` is its length
126 * - `max` is the maximum number of bytes to print
127 *
128 * Prints out::
129 *
130 * <name> (<length>): b1 b2 b3 b4 ...
131 *
132 * where no more than `max` bytes are to be printed (and "..." is printed
133 * if not all bytes were shown).
134 */
print_data(FILE * stream,char * name,byte data[],int length,int max)135 extern void print_data(FILE *stream,
136 char *name,
137 byte data[],
138 int length,
139 int max)
140 {
141 int ii;
142
143 if (length == 0)
144 {
145 fprintf(stream,"%s (0 bytes)\n",name);
146 return;
147 }
148
149 #define MAX_LINE_LENGTH 80
150
151 fprintf(stream,"%s (%d byte%s):",name,length,(length==1?"":"s"));
152 if (data == NULL)
153 fprintf(stream," <null>"); // Shouldn't happen, but let's be careful.
154 else
155 {
156 for (ii = 0; ii < (length<max?length:max); ii++)
157 fprintf(stream," %02x",data[ii]);
158 if (max < length)
159 fprintf(stream,"...");
160 }
161 fprintf(stream,"\n");
162 }
163
164 /*
165 * Print out (the last `max`) bytes of a byte array.
166 *
167 * - `stream` is the stream to print on.
168 * - `name` is identifying text to start the report with.
169 * - `data` is the byte data to print. This may be NULL.
170 * - `length` is its length
171 * - `max` is the maximum number of bytes to print
172 *
173 * Prints out::
174 *
175 * <name> (<length>): ... b1 b2 b3 b4
176 *
177 * where no more than `max` bytes are to be printed (and "..." is printed
178 * if not all bytes were shown).
179 */
print_end_of_data(FILE * stream,char * name,byte data[],int length,int max)180 extern void print_end_of_data(FILE *stream,
181 char *name,
182 byte data[],
183 int length,
184 int max)
185 {
186 int ii;
187 if (length == 0)
188 {
189 fprintf(stream,"%s (0 bytes)\n",name);
190 return;
191 }
192
193 fprintf(stream,"%s (%d byte%s):",name,length,(length==1?"":"s"));
194 if (data == NULL)
195 fprintf(stream," <null>"); // Shouldn't happen, but let's be careful.
196 else
197 {
198 if (max < length)
199 fprintf(stream," ...");
200 for (ii = (length<max?0:length-max); ii < length; ii++)
201 fprintf(stream," %02x",data[ii]);
202 }
203 fprintf(stream,"\n");
204 }
205
206 /*
207 * Print out the bottom N bits from a byte on the given stream
208 */
print_bits(FILE * stream,int num_bits,byte value)209 extern void print_bits(FILE *stream,
210 int num_bits,
211 byte value)
212 {
213 int ii;
214 byte masks[8] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
215 for (ii = 8-num_bits; ii < 8; ii++)
216 {
217 fprintf(stream,"%d",((value & masks[ii]) >> (8-ii-1)));
218 }
219 }
220
221 /*
222 * Calculate log2 of `x` - for some reason this is missing from <math.h>
223 */
log2(double x)224 extern double log2(double x)
225 {
226 if (x == 2.0)
227 return 1.0;
228 else
229 return log10(x) / log10(2);
230 }
231
232 // ============================================================
233 // Simple file I/O utilities
234 // ============================================================
235 /*
236 * Read a given number of bytes from a file.
237 *
238 * This is a jacket for `read`, allowing for the future possibility of
239 * buffered input, and simplifying error handling.
240 *
241 * - `input` is the file descriptor for the file
242 * - `num_bytes` is how many bytes to read
243 * - `data` is the buffer to read the bytes into
244 *
245 * Returns 0 if all goes well, EOF if end of file was read, or 1 if some
246 * other error occurred (in which case it will already have output a message
247 * on stderr about the problem).
248 */
read_bytes(int input,int num_bytes,byte * data)249 extern int read_bytes(int input,
250 int num_bytes,
251 byte *data)
252 {
253 #ifdef _WIN32
254 int total = 0;
255 int length;
256 #else
257 ssize_t total = 0;
258 ssize_t length;
259 #endif
260
261 // Make some allowance for short reads - for instance, if we're reading
262 // from a pipe and going just a bit faster than the sender
263 while (total < num_bytes)
264 {
265 length = read(input,&(data[total]),num_bytes-total);
266 if (length == 0)
267 return EOF;
268 else if (length == -1)
269 {
270 fprintf(stderr,"### Error reading %d bytes: %s\n",num_bytes,
271 strerror(errno));
272 return 1;
273 }
274 total += length;
275 }
276 return 0;
277 }
278
279 /*
280 * Utility function to seek within a file
281 *
282 * - `filedes` is the file to seek within
283 * - `posn` is the position to which to seek
284 *
285 * This is a jacket for::
286 *
287 * new_posn = lseek(filedes,posn,SEEK_SET);
288 *
289 * Returns 0 if all went well, 1 if the seek failed (either because
290 * it returned -1, or because the position reached was not the position
291 * requested). If an error occurs, then an explanatory message will
292 * already have been written to stderr.
293 */
seek_file(int filedes,offset_t posn)294 extern int seek_file(int filedes,
295 offset_t posn)
296 {
297 offset_t newposn = lseek(filedes,posn,SEEK_SET);
298 if (newposn == -1)
299 {
300 fprintf(stderr,"### Error moving (seeking) to position " OFFSET_T_FORMAT
301 " in file: %s\n",posn,strerror(errno));
302 return 1;
303 }
304 else if (newposn != posn)
305 {
306 fprintf(stderr,"### Error moving (seeking) to position " OFFSET_T_FORMAT
307 " in file: actually moved to " OFFSET_T_FORMAT "\n",posn,newposn);
308 return 1;
309 }
310 return 0;
311 }
312
313 /*
314 * Utility function to report the current location within a file
315 *
316 * - `filedes` is the file to seek within
317 *
318 * This is a jacket for::
319 *
320 * posn = lseek(filedes,0,SEEK_CUR);
321 *
322 * Returns the current position in the file if all went well, otherwise
323 * -1 (in which case an error message will already have been written
324 * on stderr)
325 */
tell_file(int filedes)326 extern offset_t tell_file(int filedes)
327 {
328 #ifdef _WIN32
329 offset_t newposn = _tell(filedes);
330 #else
331 offset_t newposn = lseek(filedes,0,SEEK_CUR);
332 #endif
333 if (newposn == -1)
334 fprintf(stderr,"### Error determining current position in file: %s\n",
335 strerror(errno));
336 return newposn;
337 }
338
339 /*
340 * Utility function to open a file (descriptor), and report any errors
341 *
342 * This is intended only for very simple usage, and is not mean to be
343 * a general purpose "open" replacement.
344 *
345 * - `filename` is the name of the file to open
346 * - `for_write` should be TRUE if the file is to be written to,
347 * in which case it will be opened with flags O_WRONLY|O_CREAT|O_TRUNC,
348 * or FALSE if the file is to be read, in which case it will be
349 * opened with flag O_RDONLY. In both cases, on Windows the flag
350 * O_BINARY will also be set.
351 *
352 * Returns the file descriptor for the file, or -1 if it failed to open
353 * the file.
354 */
open_binary_file(char * filename,int for_write)355 extern int open_binary_file(char *filename,
356 int for_write)
357 {
358 #ifdef _WIN32
359 int flags = O_BINARY;
360 #else
361 int flags = 0;
362 #endif
363 int filedes;
364 if (for_write)
365 {
366 flags = flags | O_WRONLY | O_CREAT | O_TRUNC;
367 filedes = open(filename,flags,00777);
368 }
369 else
370 {
371 flags = flags | O_RDONLY;
372 filedes = open(filename,flags);
373 }
374 if (filedes == -1)
375 fprintf(stderr,"### Error opening file %s for %s: %s\n",
376 filename,(for_write?"write":"read"),strerror(errno));
377 return filedes;
378 }
379
380 /*
381 * Utility function to close a file (descriptor), and report any errors
382 *
383 * Does nothing if filedes is -1 or STDIN_FILENO
384 *
385 * Returns 0 if all went well, 1 if an error occurred.
386 */
close_file(int filedes)387 extern int close_file(int filedes)
388 {
389 int err;
390
391 if (filedes == -1 || filedes == STDIN_FILENO)
392 return 0;
393
394 err = close(filedes);
395 if (err)
396 {
397 fprintf(stderr,"### Error closing file: %s\n",strerror(errno));
398 return 1;
399 }
400 else
401 return 0;
402 }
403
404 // ============================================================
405 // More complex file I/O utilities
406 // ============================================================
407 /*
408 * Open an input file appropriately for reading as ES.
409 *
410 * - `name` is the name of the file, or NULL if standard input
411 * is to be read from (which is not allowed if `use_pes` is
412 * TRUE).
413 *
414 * - If `use_pes` is true then the input file is PS or TS and should
415 * be read via a PES reader.
416 *
417 * - If `quiet` is true then information about the file being read will
418 * not be written out. Otherwise, its name and what is decided about
419 * its content will be printed.
420 *
421 * - If `force_stream_type` is true, then the caller asserts that
422 * the input shall be read according to `want_data`, and not whatever
423 * might be deduced from looking at the file itself.
424 *
425 * - If `force_stream_type` is true, then `want_data` should be one of
426 * VIDEO_H262, VIDEO_H264 or VIDEO_AVS. `is_data` will then be
427 * returned with the same value.
428 *
429 * - If `force_stream_type` is false, then the function will attempt
430 * to determine what type of data it has, and `is_data` will be set
431 * to whatever is determined (presumably one of VIDEO_H262, VIDEO_H264
432 * or VIDEO_AVS). It if cannot decide, then it will set it to VIDEO_UNKNOWN.
433 *
434 * - If input is from standard input, and `force_stream_type` is FALSE,
435 * `is_data` will always be set to VIDEO_H262, which may be incorrect.
436 *
437 * - `es` is the new ES reader context.
438 *
439 * Returns 0 if all goes well, 1 if something goes wrong. In the latter case,
440 * suitable messages will have been written out to standard error.
441 */
open_input_as_ES(char * name,int use_pes,int quiet,int force_stream_type,int want_data,int * is_data,ES_p * es)442 extern int open_input_as_ES(char *name,
443 int use_pes,
444 int quiet,
445 int force_stream_type,
446 int want_data,
447 int *is_data,
448 ES_p *es)
449 {
450 int err;
451 int use_stdin = (name == NULL);
452 PES_reader_p reader = NULL;
453
454 if (use_pes)
455 {
456 if (use_stdin)
457 {
458 fprintf(stderr,"### Cannot use standard input to read PES\n");
459 return 1;
460 }
461
462 err = open_PES_reader(name,!quiet,!quiet,&reader);
463 if (err)
464 {
465 fprintf(stderr,"### Error trying to build PES reader for input"
466 " file %s\n",name);
467 return 1;
468 }
469 err = build_elementary_stream_PES(reader,es);
470 if (err)
471 {
472 fprintf(stderr,"### Error trying to build ES reader from PES reader\n"
473 " for input file %s\n",name);
474 (void) close_PES_reader(&reader);
475 return 1;
476 }
477 }
478 else
479 {
480 err = open_elementary_stream(name,es);
481 if (err) return 1;
482 }
483
484 if (!quiet)
485 printf("Reading from %s\n",(use_stdin?"<stdin>":name));
486
487 if (force_stream_type || use_stdin)
488 {
489 if (force_stream_type)
490 *is_data = want_data;
491 else
492 *is_data = VIDEO_H262;
493 if (!quiet)
494 printf("Reading input as %s\n",
495 (*is_data==VIDEO_H262?"MPEG-2 (H.262)":
496 *is_data==VIDEO_H264?"MPEG-4/AVC (H.264)":
497 *is_data==VIDEO_AVS ?"AVS":
498 "???"));
499 }
500 else
501 {
502 if (use_pes)
503 {
504 *is_data = reader->video_type;
505 }
506 else
507 {
508 int video_type;
509 err = decide_ES_video_type(*es,FALSE,FALSE,&video_type);
510 if (err)
511 {
512 fprintf(stderr,"### Error deciding on stream type for file %s\n",name);
513 close_elementary_stream(es);
514 return 1;
515 }
516
517 *is_data = video_type;
518 if (!quiet)
519 printf("Input appears to be %s\n",
520 (*is_data==VIDEO_H262?"MPEG-2 (H.262)":
521 *is_data==VIDEO_H264?"MPEG-4/AVC (H.264)":
522 *is_data==VIDEO_AVS?"AVS":
523 *is_data==VIDEO_UNKNOWN?"Unknown":
524 "???"));
525 }
526 }
527 return 0;
528 }
529
530 /*
531 * Close an input ES stream opened with `open_input_as_ES`.
532 *
533 * Specifically, this will close the ES stream and also any underlying PES
534 * reader and file (unless the input was standard input).
535 *
536 * - `name` is the name of the file, used for error reporting.
537 * - `es` is the ES stream to close. This will be set to NULL.
538 *
539 * Returns 0 if all goes well, 1 if something goes wrong. In the latter case,
540 * suitable messages will have been written out to standard error.
541 */
close_input_as_ES(char * name,ES_p * es)542 extern int close_input_as_ES(char *name,
543 ES_p *es)
544 {
545 if (!(*es)->reading_ES)
546 {
547 int err = close_PES_reader(&(*es)->reader);
548 if (err)
549 {
550 fprintf(stderr,"### Error closing PES reader for file %s\n",name);
551 close_elementary_stream(es);
552 return 1;
553 }
554 }
555 close_elementary_stream(es);
556 return 0;
557 }
558
559 // ============================================================
560 // Command line "helpers"
561 // ============================================================
562 /*
563 * Read in an unsigned integer value, checking for extraneous characters.
564 *
565 * - `prefix` is an optional prefix for error messages, typically the
566 * name of the program. It may be NULL.
567 * - `cmd` is the command switch we're reading for (typically ``argv[ii]``),
568 * which is used in error messages.
569 * - `str` is the string to read (typically ``argv[ii+1]``).
570 * - `base` is the base to read to. If it is 0, then the user can use
571 * C-style expressions like "0x68" to specify the base on the command line.
572 * - `value` is the value read.
573 *
574 * Returns 0 if all went well, 1 otherwise (in which case a message
575 * explaining will have been written to stderr).
576 */
unsigned_value(char * prefix,char * cmd,char * arg,int base,uint32_t * value)577 extern int unsigned_value(char *prefix,
578 char *cmd,
579 char *arg,
580 int base,
581 uint32_t *value)
582 {
583 char *ptr;
584 unsigned long val;
585 errno = 0;
586 val = strtoul(arg,&ptr,base);
587 if (errno)
588 {
589 fprintf(stderr,"### ");
590 if (prefix != NULL)
591 fprintf(stderr,"%s: ",prefix);
592 if (errno == ERANGE && val == 0)
593 fprintf(stderr,"String cannot be converted to (long) unsigned integer in %s %s\n",
594 cmd,arg);
595 else if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
596 fprintf(stderr,"Number is too big (overflows) in %s %s\n",cmd,arg);
597 else
598 fprintf(stderr,"Cannot read number in %s %s (%s)\n",
599 cmd,arg,strerror(errno));
600 return 1;
601 }
602 if (ptr[0] != '\0')
603 {
604 fprintf(stderr,"### ");
605 if (prefix != NULL)
606 fprintf(stderr,"%s: ",prefix);
607 if (ptr-arg == 0)
608 fprintf(stderr,
609 "Argument to %s should be a number, in %s %s\n",
610 cmd,cmd,arg);
611 else
612 fprintf(stderr,
613 "Unexpected characters ('%s') after the %.*s in %s %s\n",
614 ptr,
615 (int)(ptr-arg),arg,
616 cmd,arg);
617 return 1;
618 }
619
620 *value = val;
621 return 0;
622 }
623
624 /*
625 * Read in an integer value, checking for extraneous characters.
626 *
627 * - `prefix` is an optional prefix for error messages, typically the
628 * name of the program. It may be NULL.
629 * - `cmd` is the command switch we're reading for (typically ``argv[ii]``),
630 * which is used in error messages.
631 * - `str` is the string to read (typically ``argv[ii+1]``).
632 * - if `positive` is true, then the number read must be positive (0 or more).
633 * - `base` is the base to read to. If it is 0, then the user can use
634 * C-style expressions like "0x68" to specify the base on the command line.
635 * - `value` is the value read.
636 *
637 * Returns 0 if all went well, 1 otherwise (in which case a message
638 * explaining will have been written to stderr).
639 */
int_value(char * prefix,char * cmd,char * arg,int positive,int base,int * value)640 extern int int_value(char *prefix,
641 char *cmd,
642 char *arg,
643 int positive,
644 int base,
645 int *value)
646 {
647 char *ptr;
648 long val;
649 errno = 0;
650 val = strtol(arg,&ptr,base);
651 if (errno)
652 {
653 fprintf(stderr,"### ");
654 if (prefix != NULL)
655 fprintf(stderr,"%s: ",prefix);
656 if (errno == ERANGE && val == 0)
657 fprintf(stderr,"String cannot be converted to (long) integer in %s %s\n",
658 cmd,arg);
659 else if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
660 fprintf(stderr,"Number is too big (overflows) in %s %s\n",cmd,arg);
661 else
662 fprintf(stderr,"Cannot read number in %s %s (%s)\n",
663 cmd,arg,strerror(errno));
664 return 1;
665 }
666 if (ptr[0] != '\0')
667 {
668 fprintf(stderr,"### ");
669 if (prefix != NULL)
670 fprintf(stderr,"%s: ",prefix);
671 if (ptr-arg == 0)
672 fprintf(stderr,
673 "Argument to %s should be a number, in %s %s\n",
674 cmd,cmd,arg);
675 else
676 fprintf(stderr,
677 "Unexpected characters ('%s') after the %.*s in %s %s\n",
678 ptr,
679 (int)(ptr-arg),arg,
680 cmd,arg);
681 return 1;
682 }
683
684 if (val > INT_MAX || val < INT_MIN)
685 {
686 fprintf(stderr,"### ");
687 if (prefix != NULL)
688 fprintf(stderr,"%s: ",prefix);
689 fprintf(stderr,"Value %ld (in %s %s) is too large (to fit into 'int')\n",
690 val,cmd,arg);
691 return 1;
692 }
693
694 if (positive && val < 0)
695 {
696 fprintf(stderr,"### ");
697 if (prefix != NULL)
698 fprintf(stderr,"%s: ",prefix);
699 fprintf(stderr,"Value %ld (in %s %s) is less than zero\n",
700 val,cmd,arg);
701 return 1;
702 }
703
704 *value = val;
705 return 0;
706 }
707
708 /*
709 * Read in an integer value, checking for extraneous characters and a range.
710 *
711 * - `prefix` is an optional prefix for error messages, typically the
712 * name of the program. It may be NULL.
713 * - `cmd` is the command switch we're reading for (typically ``argv[ii]``),
714 * which is used in error messages.
715 * - `str` is the string to read (typically ``argv[ii+1]``).
716 * - `minimum` is the minimum value allowed.
717 * - `maximum` is the maximum value allowed.
718 * - `base` is the base to read to. If it is 0, then the user can use
719 * C-style expressions like "0x68" to specify the base on the command line.
720 * - `value` is the value read.
721 *
722 * Returns 0 if all went well, 1 otherwise (in which case a message
723 * explaining will have been written to stderr).
724 */
int_value_in_range(char * prefix,char * cmd,char * arg,int minimum,int maximum,int base,int * value)725 extern int int_value_in_range(char *prefix,
726 char *cmd,
727 char *arg,
728 int minimum,
729 int maximum,
730 int base,
731 int *value)
732 {
733 int err, temp;
734 err = int_value(prefix,cmd,arg,(minimum >= 0),base,&temp);
735 if (err) return err;
736
737 if (temp > maximum || temp < minimum)
738 {
739 fprintf(stderr,"### ");
740 if (prefix != NULL)
741 fprintf(stderr,"%s: ",prefix);
742 fprintf(stderr,"Value %d (in %s %s) is not in range %d..%d (0x%x..0x%x)\n",
743 temp,cmd,arg,minimum,maximum,minimum,maximum);
744 return 1;
745 }
746 *value = temp;
747 return 0;
748 }
749
750 /*
751 * Read in a double value, checking for extraneous characters.
752 *
753 * - `prefix` is an optional prefix for error messages, typically the
754 * name of the program. It may be NULL.
755 * - `cmd` is the command switch we're reading for (typically ``argv[ii]``),
756 * which is used in error messages.
757 * - `str` is the string to read (typically ``argv[ii+1]``).
758 * - if `positive` is true, then the number read must be positive (0 or more).
759 * - `value` is the value read.
760 *
761 * Returns 0 if all went well, 1 otherwise (in which case a message
762 * explaining will have been written to stderr).
763 */
double_value(char * prefix,char * cmd,char * arg,int positive,double * value)764 extern int double_value(char *prefix,
765 char *cmd,
766 char *arg,
767 int positive,
768 double *value)
769 {
770 char *ptr;
771 double val;
772 errno = 0;
773 val = strtod(arg,&ptr);
774 if (errno)
775 {
776 fprintf(stderr,"### ");
777 if (prefix != NULL)
778 fprintf(stderr,"%s: ",prefix);
779 if (errno == ERANGE && val == 0)
780 fprintf(stderr,"String cannot be converted to (double) float in %s %s\n",
781 cmd,arg);
782 else if (errno == ERANGE && (val == HUGE_VAL || val == -HUGE_VAL))
783 fprintf(stderr,"Number is too big (overflows) in %s %s\n",cmd,arg);
784 else
785 fprintf(stderr,"Cannot read number in %s %s (%s)\n",
786 cmd,arg,strerror(errno));
787 return 1;
788 }
789 if (ptr[0] != '\0')
790 {
791 fprintf(stderr,"### ");
792 if (prefix != NULL)
793 fprintf(stderr,"%s: ",prefix);
794 fprintf(stderr,
795 "Unexpected characters ('%s') after the %.*s in %s %s\n",
796 ptr,
797 (int)(ptr-arg),arg,
798 cmd,arg);
799 return 1;
800 }
801
802 if (positive && val < 0)
803 {
804 fprintf(stderr,"### ");
805 if (prefix != NULL)
806 fprintf(stderr,"%s: ",prefix);
807 fprintf(stderr,"Value %f (in %s %s) is less than zero\n",
808 val,cmd,arg);
809 return 1;
810 }
811
812 *value = val;
813 return 0;
814 }
815
816 /*
817 * Read in a hostname and (optional) port
818 *
819 * - `prefix` is an optional prefix for error messages, typically the
820 * name of the program. It may be NULL.
821 * - `cmd` is the command switch we're reading for (typically ``argv[ii]``),
822 * which is used in error messages. It may be NULL if we are reading a
823 * "plain" host name, with no command switch in front of it.
824 * - `arg` is the string to read (typically ``argv[ii+1]``).
825 * - `hostname` is the host name read
826 * - `port` is the port read (note that this is not touched if there is
827 * no port number, so it may be set to a default before calling this
828 * function)
829 *
830 * Note that this works by pointing `hostname` to the start of the `arg`
831 * string, and then if there is a ':' in `arg`, changing that colon to
832 * a '\0' delimiter, and interpreting the string thereafter as the port
833 * number. If *that* fails, it resets the '\0' as a ':'.
834 *
835 * Returns 0 if all went well, 1 otherwise (in which case a message
836 * explaining will have been written to stderr).
837 */
host_value(char * prefix,char * cmd,char * arg,char ** hostname,int * port)838 extern int host_value(char *prefix,
839 char *cmd,
840 char *arg,
841 char **hostname,
842 int *port)
843 {
844 char *p = strchr(arg,':');
845
846 *hostname = arg;
847
848 if (p != NULL)
849 {
850 char *ptr;
851 p[0] = '\0'; // yep, modifying argv[ii+1]
852 errno = 0;
853 *port = strtol(p+1,&ptr,10);
854 if (errno)
855 {
856 p[0] = ':';
857 fprintf(stderr,"### ");
858 if (prefix != NULL)
859 fprintf(stderr,"%s: ",prefix);
860 if (cmd)
861 fprintf(stderr,"Cannot read port number in %s %s (%s)\n",
862 cmd,arg,strerror(errno));
863 else
864 fprintf(stderr,"Cannot read port number in %s (%s)\n",
865 arg,strerror(errno));
866 return 1;
867 }
868 if (ptr[0] != '\0')
869 {
870 p[0] = ':';
871 fprintf(stderr,"### ");
872 if (prefix != NULL)
873 fprintf(stderr,"%s: ",prefix);
874 if (cmd)
875 fprintf(stderr,"Unexpected characters in port number in %s %s\n",
876 cmd,arg);
877 else
878 fprintf(stderr,"Unexpected characters in port number in %s\n",
879 arg);
880 return 1;
881 }
882 if (*port < 0)
883 {
884 p[0] = ':';
885 fprintf(stderr,"### ");
886 if (prefix != NULL)
887 fprintf(stderr,"%s: ",prefix);
888 if (cmd)
889 fprintf(stderr,"Negative port number in %s %s\n",cmd,arg);
890 else
891 fprintf(stderr,"Negative port number in %s\n",arg);
892 return 1;
893 }
894 }
895 return 0;
896 }
897
898 #ifdef _WIN32
899 // ============================================================
900 // WINDOWS32 specific socket stuff
901 // ============================================================
902
903 /*
904 * Start up WINSOCK so we can use sockets.
905 *
906 * Note that each successful call of this *must* be matched by a call
907 * of winsock_cleanup().
908 *
909 * Returns 0 if it works, 1 if it fails.
910 */
winsock_startup()911 extern int winsock_startup()
912 {
913 // The code herein is borrowed from the example in the Windows Sockets
914 // Version 2: Platform DSK documentation for WSAStartup.
915 WORD wVersionRequested;
916 WSADATA wsaData;
917 int err;
918
919 wVersionRequested = MAKEWORD(2,2);
920
921 err = WSAStartup(wVersionRequested,&wsaData);
922 if (err != 0)
923 {
924 // We could not find a usable WinSock DLL
925 fprintf(stderr,"### Unable to find a usable WinSock DLL\n");
926 return 1;
927 }
928
929 // Confirm that the WinSock DLL supports 2.2.
930 // Note that if the DLL supports versions greater than 2.2 in addition to
931 // 2.2, it will still return 2.2 in wVersion since that is the version we
932 // requested.
933 if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2 )
934 {
935 fprintf(stderr,"### WinSock DLL was version %d.%d, not 2.2 or more\n",
936 LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
937 WSACleanup();
938 return 1;
939 }
940 return 0;
941 }
942
943 /*
944 * Convert a WinSock error number into a string and print it out on stderr
945 */
print_winsock_err(int err)946 extern void print_winsock_err(int err)
947 {
948 switch (err)
949 {
950 case WSABASEERR:
951 fprintf(stderr,"(WSABASEERR) No Error");
952 break;
953
954 case WSAEINTR:
955 fprintf(stderr,"(WSAEINTR) Interrupted system call");
956 break;
957
958 case WSAEBADF:
959 fprintf(stderr,"(WSAEBADF) Bad file number");
960 break;
961
962 case WSAEACCES:
963 fprintf(stderr,"(WSAEACCES) Permission denied");
964 break;
965
966 case WSAEFAULT:
967 fprintf(stderr,"(WSAEFAULT) Bad address");
968 break;
969
970 case WSAEINVAL:
971 fprintf(stderr,"(WSAEINVAL) Invalid argument");
972 break;
973
974 case WSAEMFILE:
975 fprintf(stderr,"(WSAEMFILE) Too many open files");
976 break;
977
978 case WSAEWOULDBLOCK:
979 fprintf(stderr,"(WSAEWOULDBLOCK) Operation would block");
980 break;
981
982 case WSAEINPROGRESS:
983 fprintf(stderr,"(WSAEINPROGRESS) A transaction is still in progress");
984 break;
985
986 case WSAEALREADY:
987 fprintf(stderr,"(WSAEALREADY) Operation already in progress");
988 break;
989
990 case WSAENOTSOCK:
991 fprintf(stderr,"(WSAENOTSOCK) Socket operation on non-socket");
992 break;
993
994 case WSAEDESTADDRREQ:
995 fprintf(stderr,"(WSAEDESTADDRREQ) Destination address required");
996 break;
997
998 case WSAEMSGSIZE:
999 fprintf(stderr,"(WSAEMSGSIZE) Message too long");
1000 break;
1001
1002 case WSAEPROTOTYPE:
1003 fprintf(stderr,"(WSAEPROTOTYPE) Protocol wrong type for socket");
1004 break;
1005
1006 case WSAENOPROTOOPT:
1007 fprintf(stderr,"(WSAENOPROTOOPT) Bad protocol option");
1008 break;
1009
1010 case WSAEPROTONOSUPPORT:
1011 fprintf(stderr,"(WSAEPROTONOSUPPORT) Protocol not supported");
1012 break;
1013
1014 case WSAESOCKTNOSUPPORT:
1015 fprintf(stderr,"(WSAESOCKTNOSUPPORT) Socket type not supported");
1016 break;
1017
1018 case WSAEOPNOTSUPP:
1019 fprintf(stderr,"(WSAEOPNOTSUPP) Operation not supported on socket");
1020 break;
1021
1022 case WSAEPFNOSUPPORT:
1023 fprintf(stderr,"(WSAEPFNOSUPPORT) Protocol family not supported");
1024 break;
1025
1026 case WSAEAFNOSUPPORT:
1027 fprintf(stderr,"(WSAEAFNOSUPPORT) Address family not supported by protocol family");
1028 break;
1029
1030 case WSAEADDRINUSE:
1031 fprintf(stderr,"(WSAEADDRINUSE) Address already in use");
1032 break;
1033
1034 case WSAEADDRNOTAVAIL:
1035 fprintf(stderr,"(WSAEADDRNOTAVAIL) Can't assign requested address");
1036 break;
1037
1038 case WSAENETDOWN:
1039 fprintf(stderr,"(WSAENETDOWN) Network is down");
1040 break;
1041
1042 case WSAENETUNREACH:
1043 fprintf(stderr,"(WSAENETUNREACH) Network is unreachable");
1044 break;
1045
1046 case WSAENETRESET:
1047 fprintf(stderr,"(WSAENETRESET) Net dropped connection or reset");
1048 break;
1049
1050 case WSAECONNABORTED:
1051 fprintf(stderr,"(WSAECONNABORTED) Software caused connection abort");
1052 break;
1053
1054 case WSAECONNRESET:
1055 fprintf(stderr,"(WSAECONNRESET) Connection reset by peer");
1056 break;
1057
1058 case WSAENOBUFS:
1059 fprintf(stderr,"(WSAENOBUFS) No buffer space available");
1060 break;
1061
1062 case WSAEISCONN:
1063 fprintf(stderr,"(WSAEISCONN) Socket is already connected");
1064 break;
1065
1066 case WSAENOTCONN:
1067 fprintf(stderr,"(WSAENOTCONN) Socket is not connected");
1068 break;
1069
1070 case WSAESHUTDOWN:
1071 fprintf(stderr,"(WSAESHUTDOWN) Can't send after socket shutdown");
1072 break;
1073
1074 case WSAETOOMANYREFS:
1075 fprintf(stderr,"(WSAETOOMANYREFS) Too many references, can't splice");
1076 break;
1077
1078 case WSAETIMEDOUT:
1079 fprintf(stderr,"(WSAETIMEDOUT) Connection timed out");
1080 break;
1081
1082 case WSAECONNREFUSED:
1083 fprintf(stderr,"(WSAECONNREFUSED) Connection refused");
1084 break;
1085
1086 case WSAELOOP:
1087 fprintf(stderr,"(WSAELOOP) Too many levels of symbolic links");
1088 break;
1089
1090 case WSAENAMETOOLONG:
1091 fprintf(stderr,"(WSAENAMETOOLONG) File name too long");
1092 break;
1093
1094 case WSAEHOSTDOWN:
1095 fprintf(stderr,"(WSAEHOSTDOWN) Host is down");
1096 break;
1097
1098 case WSAEHOSTUNREACH:
1099 fprintf(stderr,"(WSAEHOSTUNREACH) No Route to Host");
1100 break;
1101
1102 case WSAENOTEMPTY:
1103 fprintf(stderr,"(WSAENOTEMPTY) Directory not empty");
1104 break;
1105
1106 case WSAEPROCLIM:
1107 fprintf(stderr,"(WSAEPROCLIM) Too many processes");
1108 break;
1109
1110 case WSAEUSERS:
1111 fprintf(stderr,"(WSAEUSERS) Too many users");
1112 break;
1113
1114 case WSAEDQUOT:
1115 fprintf(stderr,"(WSAEDQUOT) Disc Quota Exceeded");
1116 break;
1117
1118 case WSAESTALE:
1119 fprintf(stderr,"(WSAESTALE) Stale NFS file handle");
1120 break;
1121
1122 case WSASYSNOTREADY:
1123 fprintf(stderr,"(WSASYSNOTREADY) Network SubSystem is unavailable");
1124 break;
1125
1126 case WSAVERNOTSUPPORTED:
1127 fprintf(stderr,"(WSAVERNOTSUPPORTED) WINSOCK DLL Version out of range");
1128 break;
1129
1130 case WSANOTINITIALISED:
1131 fprintf(stderr,"(WSANOTINITIALISED) Successful WSASTARTUP not yet performed");
1132 break;
1133
1134 case WSAEREMOTE:
1135 fprintf(stderr,"(WSAEREMOTE) Too many levels of remote in path");
1136 break;
1137
1138 case WSAHOST_NOT_FOUND:
1139 fprintf(stderr,"(WSAHOST_NOT_FOUND) Host not found");
1140 break;
1141
1142 case WSATRY_AGAIN:
1143 fprintf(stderr,"(WSATRY_AGAIN) Non-Authoritative Host not found");
1144 break;
1145
1146 case WSANO_RECOVERY:
1147 fprintf(stderr,"(WSANO_RECOVERY) Non-Recoverable errors: FORMERR, REFUSED, NOTIMP");
1148 break;
1149
1150 case WSANO_DATA:
1151 fprintf(stderr,"(WSANO_DATA) Valid name, no data record of requested type");
1152 break;
1153
1154 default:
1155 fprintf(stderr,"winsock error %d",err);
1156 break;
1157 }
1158 }
1159
1160 /*
1161 * Clean up WINSOCK after we've used sockets.
1162 *
1163 * Returns 0 if it works, 1 if it fails.
1164 */
winsock_cleanup()1165 static int winsock_cleanup()
1166 {
1167 int err = WSACleanup();
1168 if (err != 0)
1169 {
1170 err = WSAGetLastError();
1171 fprintf(stderr,"### Error cleaning up WinSock: ");
1172 print_winsock_err(err);
1173 fprintf(stderr,"\n");
1174 return 1;
1175 }
1176 return 0;
1177 }
1178 #endif
1179
1180 // ============================================================
1181 // Socket support
1182 // ============================================================
1183 /*
1184 * Connect to a socket, to allow us to write to it, using TCP/IP.
1185 *
1186 * - `hostname` is the name of the host to connect to
1187 * - `port` is the port to use
1188 * - if `use_tcpip`, then a TCP/IP connection will be made, otherwise UDP.
1189 * For UDP, multicast TTL will be enabled.
1190 * - If the destination address (`hostname`) is multicast and `multicast_ifaddr`
1191 * is supplied, it is used to select (by IP address) the network interface
1192 * on which to send the multicasts. It may be NULL to use the default,
1193 * or for non-multicast cases.
1194 *
1195 * A socket connected to via this function must be disconnected from with
1196 * disconnect_socket().
1197 *
1198 * (This is actually only crucial on Windows, where WinSock must be
1199 * neatly shut down, but should also be done on Unix in case future
1200 * termination code is added.)
1201 *
1202 * Returns a positive integer (the file descriptor for the socket) if it
1203 * succeeds, or -1 if it fails, in which case it will have complained on
1204 * stderr.
1205 */
connect_socket(char * hostname,int port,int use_tcpip,char * multicast_ifaddr)1206 extern int connect_socket(char *hostname,
1207 int port,
1208 int use_tcpip,
1209 char *multicast_ifaddr)
1210 {
1211 #ifdef _WIN32
1212 SOCKET output;
1213 #else // _WIN32
1214 int output;
1215 #endif // _WIN32
1216 int result;
1217 struct hostent *hp;
1218 struct sockaddr_in ipaddr;
1219
1220 #ifdef _WIN32
1221 int err = winsock_startup();
1222 if (err) return 1;
1223 #endif
1224
1225 output = socket(AF_INET, (use_tcpip?SOCK_STREAM:SOCK_DGRAM), 0);
1226 #ifdef _WIN32
1227 if (output == INVALID_SOCKET)
1228 {
1229 err = WSAGetLastError();
1230 fprintf(stderr,"### Unable to create socket: ");
1231 print_winsock_err(err);
1232 fprintf(stderr,"\n");
1233 return -1;
1234 }
1235 #else // _WIN32
1236 if (output == -1)
1237 {
1238 fprintf(stderr,"### Unable to create socket: %s\n",strerror(errno));
1239 return -1;
1240 }
1241 #endif // _WIN32
1242
1243 #if _WIN32
1244 // On Windows, apparently, gethostbyname will not work for numeric IP addresses.
1245 // The clever solution would be to move to using getaddrinfo for all forms of
1246 // host address, but the simpler solution is just to do:
1247 {
1248 unsigned long addr = inet_addr(hostname);
1249 if (addr != INADDR_NONE) // i.e., success
1250 {
1251 ipaddr.sin_addr.s_addr = addr;
1252 ipaddr.sin_family = AF_INET;
1253 }
1254 else
1255 {
1256 hp = gethostbyname(hostname);
1257 if (hp == NULL)
1258 {
1259 err = WSAGetLastError();
1260 fprintf(stderr,"### Unable to resolve host %s: ",hostname);
1261 print_winsock_err(err);
1262 fprintf(stderr,"\n");
1263 return -1;
1264 }
1265 memcpy(&ipaddr.sin_addr.s_addr, hp->h_addr, hp->h_length);
1266 ipaddr.sin_family = hp->h_addrtype;
1267 }
1268 }
1269 ipaddr.sin_port = htons(port);
1270 #else // _WIN32
1271 hp = gethostbyname(hostname);
1272 if (hp == NULL)
1273 {
1274 fprintf(stderr,"### Unable to resolve host %s: %s\n",
1275 hostname,hstrerror(h_errno));
1276 return -1;
1277 }
1278 memcpy(&ipaddr.sin_addr.s_addr, hp->h_addr, hp->h_length);
1279 ipaddr.sin_family = hp->h_addrtype;
1280 #if !defined(__linux__)
1281 // On BSD, the length is defined in the datastructure
1282 ipaddr.sin_len = sizeof(struct sockaddr_in);
1283 #endif // __linux__
1284 ipaddr.sin_port = htons(port);
1285 #endif // _WIN32
1286
1287 if (IN_CLASSD(ntohl(ipaddr.sin_addr.s_addr)))
1288 {
1289 // Needed if we're doing multicast
1290 byte ttl = 16;
1291 result = setsockopt(output, IPPROTO_IP, IP_MULTICAST_TTL,
1292 (char *)&ttl, sizeof(ttl));
1293 #ifdef _WIN32
1294 if (result == SOCKET_ERROR)
1295 {
1296 err = WSAGetLastError();
1297 fprintf(stderr,"### Error setting socket for IP_MULTICAST_TTL: ");
1298 print_winsock_err(err);
1299 fprintf(stderr,"\n");
1300 return -1;
1301 }
1302 #else // _WIN32
1303 if (result < 0)
1304 {
1305 fprintf(stderr,
1306 "### Error setting socket for IP_MULTICAST_TTL: %s\n",
1307 strerror(errno));
1308 return -1;
1309 }
1310 #endif // _WIN32
1311
1312 if (multicast_ifaddr)
1313 {
1314 #ifdef _WIN32
1315 unsigned long addr;
1316 fprintf(stderr,"!!! Specifying the multicast interface is not supported on "
1317 "some versions of Windows\n");
1318 // Also, choosing an invalid address is not (may not be) detected on Windows
1319 addr = inet_addr(multicast_ifaddr);
1320 if (addr == INADDR_NONE)
1321 {
1322 err = WSAGetLastError();
1323 fprintf(stderr,"### Error translating '%s' as a dotted IP address: ",
1324 multicast_ifaddr);
1325 print_winsock_err(err);
1326 fprintf(stderr,"\n");
1327 return -1;
1328 }
1329 #else // _WIN32
1330 struct in_addr addr;
1331 inet_aton(multicast_ifaddr, &addr);
1332 #endif // _WIN32
1333 result = setsockopt(output,IPPROTO_IP,IP_MULTICAST_IF,
1334 (char *)&addr,sizeof(addr));
1335 #ifdef _WIN32
1336 if (result == SOCKET_ERROR)
1337 {
1338 err = WSAGetLastError();
1339 fprintf(stderr,"### Unable to set multicast interface %s: ");
1340 print_winsock_err(err);
1341 fprintf(stderr,"\n");
1342 return -1;
1343 }
1344 #else // _WIN32
1345 if (result < 0)
1346 {
1347 fprintf(stderr,"### Unable to set multicast interface %s: %s\n",
1348 multicast_ifaddr,strerror(errno));
1349 return -1;
1350 }
1351 #endif // _WIN32
1352 }
1353 }
1354
1355 result = connect(output,(struct sockaddr*)&ipaddr,sizeof(ipaddr));
1356 #ifdef _WIN32
1357 if (result == SOCKET_ERROR)
1358 {
1359 err = WSAGetLastError();
1360 fprintf(stderr,"### Unable to connect to host %s: ",hostname);
1361 print_winsock_err(err);
1362 fprintf(stderr,"\n");
1363 return -1;
1364 }
1365 #else // _WIN32
1366 if (result < 0)
1367 {
1368 fprintf(stderr,"### Unable to connect to host %s: %s\n",
1369 hostname,strerror(errno));
1370 return -1;
1371 }
1372 #endif // _WIN32
1373 return output;
1374 }
1375
1376 /*
1377 * Disconnect from a socket (close it).
1378 *
1379 * Returns 0 if all goes well, 1 otherwise.
1380 */
1381 #ifdef _WIN32
disconnect_socket(SOCKET socket)1382 extern int disconnect_socket(SOCKET socket)
1383 {
1384 int err = closesocket(socket);
1385 if (err != 0)
1386 {
1387 err = WSAGetLastError();
1388 fprintf(stderr,"### Error closing output: ");
1389 print_winsock_err(err);
1390 fprintf(stderr,"\n");
1391 return 1;
1392 }
1393
1394 err = winsock_cleanup();
1395 if (err) return 1;
1396 return 0;
1397 }
1398 #else // _WIN32
disconnect_socket(int socket)1399 extern int disconnect_socket(int socket)
1400 {
1401 int err = close(socket);
1402 if (err == EOF)
1403 {
1404 fprintf(stderr,"### Error closing output: %s\n",strerror(errno));
1405 return 1;
1406 }
1407 return 0;
1408 }
1409 #endif // _WIN32
1410
ipv4_addr_to_string(const uint32_t addr)1411 const char *ipv4_addr_to_string(const uint32_t addr)
1412 {
1413 static char buf[64];
1414
1415 sprintf(buf, "%d.%d.%d.%d",
1416 (addr >> 24)&0xff,
1417 (addr >> 16)&0xff,
1418 (addr >> 8)&0xff,
1419 (addr & 0xff));
1420 return buf;
1421 }
1422
ipv4_string_to_addr(uint32_t * dest,const char * string)1423 int ipv4_string_to_addr(uint32_t *dest, const char *string)
1424 {
1425 char *str_cpy = strdup(string);
1426 int rv =0;
1427 char *p, *p2;
1428 int val;
1429 int nr;
1430 uint32_t out = 0;
1431
1432 for (nr = 0,p = str_cpy; nr < 4 && *p; p = p2+1, ++nr)
1433 {
1434 char *px = NULL;
1435 p2 = strchr(p, '.');
1436 if (p2)
1437 {
1438 *p2 = '\0';
1439 }
1440 val = strtoul(p, &px, 0);
1441 if (px && *px)
1442 {
1443 return -1;
1444 }
1445 out |= (val << ((3-nr)<<3));
1446 }
1447
1448 (*dest) = out;
1449 free(str_cpy);
1450 return rv;
1451
1452 }
1453
1454
1455 // Local Variables:
1456 // tab-width: 8
1457 // indent-tabs-mode: nil
1458 // c-basic-offset: 2
1459 // End:
1460 // vim: set tabstop=8 shiftwidth=2 expandtab:
1461