util.c 39.8 KB
Newer Older
1 2 3
/*****************************************************************************
 * util.c: Utils for the multicat suite
 *****************************************************************************
4
 * Copyright (C) 2004, 2009, 2011, 2015-2016 VideoLAN
5
 * $Id$
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * Authors: Christophe Massiot <massiot@via.ecp.fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

Jörg Krause's avatar
Jörg Krause committed
24 25
#define _GNU_SOURCE

26 27 28 29
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
30
#include <inttypes.h>
31 32 33 34 35 36 37 38 39 40 41
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#include <sys/time.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
42 43 44
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
45
#include <sys/mman.h>
46
#include <netdb.h>
47
#include <syslog.h>
48 49 50

#include "util.h"

51
#define DEBUG_SOCKET
52

53 54 55 56 57
/*****************************************************************************
 * Local declarations
 *****************************************************************************/
#define MAX_MSG 1024
#define PSZ_AUX_EXT "aux"
58
#define PSZ_TS_EXT "ts"
59 60

int i_verbose = VERB_DBG;
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
static int b_syslog = 0;

/*****************************************************************************
 * msg_Openlog
 *****************************************************************************/
void msg_Openlog( const char *ident, int option, int facility )
{
    openlog(ident, option, facility);
    b_syslog = 1;
}

/*****************************************************************************
 * msg_Closelog
 *****************************************************************************/
void msg_Closelog( void )
{
    closelog();
    b_syslog = 0;
}
80 81 82 83 84 85

/*****************************************************************************
 * msg_Info
 *****************************************************************************/
void msg_Info( void *_unused, const char *psz_format, ... )
{
86
    if ( i_verbose < VERB_INFO )
87 88 89 90 91 92
        return;

    va_list args;
    va_start( args, psz_format );

    if ( !b_syslog )
93 94 95 96 97
    {
        char psz_fmt[MAX_MSG];
        snprintf( psz_fmt, MAX_MSG, "info: %s\n", psz_format );
        vfprintf( stderr, psz_fmt, args );
    }
98 99 100 101 102 103
    else
    {
        vsyslog( LOG_INFO, psz_format, args );
    }

    va_end( args );
104 105 106 107 108 109 110 111 112 113
}

/*****************************************************************************
 * msg_Err
 *****************************************************************************/
void msg_Err( void *_unused, const char *psz_format, ... )
{
    va_list args;
    va_start( args, psz_format );

114 115 116 117 118 119 120 121 122 123 124 125
    if ( !b_syslog )
    {
        char psz_fmt[MAX_MSG];
        snprintf( psz_fmt, MAX_MSG, "error: %s\n", psz_format );
        vfprintf( stderr, psz_fmt, args );
    }
    else
    {
        vsyslog( LOG_ERR, psz_format, args );
    }

    va_end( args );
126 127 128 129 130 131 132
}

/*****************************************************************************
 * msg_Warn
 *****************************************************************************/
void msg_Warn( void *_unused, const char *psz_format, ... )
{
133
    if ( i_verbose < VERB_WARN )
134 135 136 137 138 139
        return;

    va_list args;
    va_start( args, psz_format );

    if ( !b_syslog )
140 141 142 143 144
    {
        char psz_fmt[MAX_MSG];
        snprintf( psz_fmt, MAX_MSG, "warning: %s\n", psz_format );
        vfprintf( stderr, psz_fmt, args );
    }
145 146 147 148 149 150
    else
    {
        vsyslog( LOG_WARNING, psz_format, args );
    }

    va_end( args );
151 152 153 154 155 156 157
}

/*****************************************************************************
 * msg_Dbg
 *****************************************************************************/
void msg_Dbg( void *_unused, const char *psz_format, ... )
{
158
    if ( i_verbose < VERB_DBG )
159 160 161 162 163 164
        return;

    va_list args;
    va_start( args, psz_format );

    if ( !b_syslog )
165 166 167 168 169
    {
        char psz_fmt[MAX_MSG];
        snprintf( psz_fmt, MAX_MSG, "debug: %s\n", psz_format );
        vfprintf( stderr, psz_fmt, args );
    }
170 171 172 173 174 175
    else
    {
        vsyslog( LOG_DEBUG, psz_format, args );
    }

    va_end( args );
176 177 178
}

/*****************************************************************************
179
 * msg_Raw: only used for usage()
180 181 182 183 184 185 186 187 188
 *****************************************************************************/
void msg_Raw( void *_unused, const char *psz_format, ... )
{
    va_list args;
    char psz_fmt[MAX_MSG];
    va_start( args, psz_format );

    snprintf( psz_fmt, MAX_MSG, "%s\n", psz_format );
    vfprintf( stderr, psz_fmt, args );
Christophe Massiot's avatar
Christophe Massiot committed
189
    va_end( args );
190 191 192
}

/*****************************************************************************
193
 * wall_Date/real_Date: returns a 27 MHz timestamp
194
 *****************************************************************************/
195
static uint64_t _wall_Date( bool b_realtime )
196 197 198 199 200
{
#if defined (HAVE_CLOCK_NANOSLEEP)
    struct timespec ts;

    /* Try to use POSIX monotonic clock if available */
Christophe Massiot's avatar
Christophe Massiot committed
201
    if( b_realtime || clock_gettime( CLOCK_MONOTONIC, &ts ) == -1 )
202 203 204 205
        /* Run-time fallback to real-time clock (always available) */
        (void)clock_gettime( CLOCK_REALTIME, &ts );

    return ((uint64_t)ts.tv_sec * (uint64_t)27000000)
206
            + ((uint64_t)ts.tv_nsec * 27 / 1000);
207 208 209 210 211 212 213 214 215 216 217
#else
    struct timeval tv_date;

    /* gettimeofday() could return an error, and should be tested. However, the
     * only possible error, according to 'man', is EFAULT, which can not happen
     * here, since tv is a local variable. */
    gettimeofday( &tv_date, NULL );
    return( (uint64_t) tv_date.tv_sec * 27000000 + (uint64_t) tv_date.tv_usec * 27 );
#endif
}

218 219 220 221 222 223 224 225 226 227
uint64_t wall_Date( void )
{
    return _wall_Date( false );
}

uint64_t real_Date( void )
{
    return _wall_Date( true );
}

228
/*****************************************************************************
229
 * wall_Sleep/real_Sleep
230
 *****************************************************************************/
231
static void _wall_Sleep( uint64_t i_delay, bool b_realtime )
232 233 234 235 236 237
{
    struct timespec ts;
    ts.tv_sec = i_delay / 27000000;
    ts.tv_nsec = (i_delay % 27000000) * 1000 / 27;

#if defined( HAVE_CLOCK_NANOSLEEP )
238 239 240 241
    int val = EINVAL;
    if ( !b_realtime )
        while ( ( val = clock_nanosleep( CLOCK_MONOTONIC, 0, &ts, &ts ) ) == EINTR );
    if( val == EINVAL )
242 243 244 245 246 247 248 249 250 251
    {
        ts.tv_sec = i_delay / 27000000;
        ts.tv_nsec = (i_delay % 27000000) * 1000 / 27;
        while ( clock_nanosleep( CLOCK_REALTIME, 0, &ts, &ts ) == EINTR );
    }
#else
    while ( nanosleep( &ts, &ts ) && errno == EINTR );
#endif
}

252 253 254 255 256 257 258 259 260 261
void wall_Sleep( uint64_t i_delay )
{
    _wall_Sleep( i_delay, false );
}

void real_Sleep( uint64_t i_delay )
{
    _wall_Sleep( i_delay, true );
}

262 263 264 265 266
/*****************************************************************************
 * GetInterfaceIndex: returns the index of an interface
 *****************************************************************************/
static int GetInterfaceIndex( const char *psz_name )
{
267
#if !defined(__APPLE__)
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    int i_fd;
    struct ifreq ifr;

    if ( (i_fd = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 )
    {
        msg_Err( NULL, "unable to open socket (%s)", strerror(errno) );
        exit(EXIT_FAILURE);
    }

    strncpy( ifr.ifr_name, psz_name, IFNAMSIZ );
    ifr.ifr_name[IFNAMSIZ-1] = '\0';

    if ( ioctl( i_fd, SIOCGIFINDEX, &ifr ) < 0 )
    {
        msg_Err( NULL, "unable to get interface index (%s)", strerror(errno) );
        exit(EXIT_FAILURE);
    }

    close( i_fd );

288 289 290
#if defined(__FreeBSD__)
    return ifr.ifr_index;
#else
291
    return ifr.ifr_ifindex;
292
#endif
Christophe Massiot's avatar
Christophe Massiot committed
293 294 295
#else
    return 0;
#endif
296 297
}

298 299 300
/*****************************************************************************
 * PrintSocket: print socket characteristics for debug purposes
 *****************************************************************************/
301 302
static void PrintSocket( const char *psz_text, sockaddr_t *p_bind,
                         sockaddr_t *p_connect )
303
{
304
    if ( p_bind->ss.ss_family == AF_INET )
305 306
    {
        msg_Dbg( NULL, "%s bind:%s:%u", psz_text,
307
                 inet_ntoa(p_bind->sin.sin_addr), ntohs(p_bind->sin.sin_port) );
308
    }
309
    else if ( p_bind->ss.ss_family == AF_INET6 )
310 311 312
    {
        char buf[INET6_ADDRSTRLEN];
        msg_Dbg( NULL, "%s bind:[%s]:%u", psz_text,
313 314
                 inet_ntop(AF_INET6, &p_bind->sin6.sin6_addr, buf, sizeof(buf)),
                 ntohs(p_bind->sin6.sin6_port) );
315
    }
316

317
    if ( p_connect->ss.ss_family == AF_INET )
318 319
    {
        msg_Dbg( NULL, "%s connect:%s:%u", psz_text,
320 321
                 inet_ntoa(p_connect->sin.sin_addr),
                 ntohs(p_connect->sin.sin_port) );
322
    }
323
    else if ( p_connect->ss.ss_family == AF_INET6 )
324 325 326
    {
        char buf[INET6_ADDRSTRLEN];
        msg_Dbg( NULL, "%s connect:[%s]:%u", psz_text,
327 328 329
                 inet_ntop(AF_INET6, &p_connect->sin6.sin6_addr, buf,
                           sizeof(buf)),
                 ntohs(p_connect->sin6.sin6_port) );
330
    }
331 332
}

333
/*****************************************************************************
334
 * ParseNodeService: parse a host:port string
335
 *****************************************************************************/
336 337 338
static struct addrinfo *ParseNodeService( char *_psz_string, char **ppsz_end,
                                          uint16_t i_default_port,
                                          int *pi_if_index )
339
{
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
    int i_family = AF_INET;
    char psz_port_buffer[6];
    char *psz_string = strdup( _psz_string );
    char *psz_node, *psz_port = NULL, *psz_end;
    struct addrinfo *p_res;
    struct addrinfo hint;
    int i_ret;

    if ( psz_string[0] == '[' )
    {
        i_family = AF_INET6;
        psz_node = psz_string + 1;
        psz_end = strchr( psz_node, ']' );
        if ( psz_end == NULL )
        {
            msg_Warn( NULL, "invalid IPv6 address %s", _psz_string );
            free( psz_string );
            return NULL;
        }
        *psz_end++ = '\0';

        char *psz_intf = strrchr( psz_node, '%' );
        if ( psz_intf != NULL )
        {
            *psz_intf++ = '\0';
            if ( pi_if_index != NULL )
                *pi_if_index = GetInterfaceIndex( psz_intf );
        }
368 369
    }
    else
370 371 372 373
    {
        psz_node = psz_string;
        psz_end = strpbrk( psz_string, "@:,/" );
    }
374

375
    if ( psz_end != NULL && psz_end[0] == ':' )
376
    {
377 378 379
        *psz_end++ = '\0';
        psz_port = psz_end;
        psz_end = strpbrk( psz_port, "@:,/" );
380 381
    }

382
    if ( psz_end != NULL )
383
    {
384 385 386
        *psz_end = '\0';
        if ( ppsz_end != NULL )
            *ppsz_end = _psz_string + (psz_end - psz_string);
387
    }
388 389
    else if ( ppsz_end != NULL )
        *ppsz_end = _psz_string + strlen(_psz_string);
390

391
    if ( i_default_port != 0 && (psz_port == NULL || !*psz_port) )
392
    {
393 394
        sprintf( psz_port_buffer, "%u", i_default_port );
        psz_port = psz_port_buffer;
395 396
    }

397 398
    if ( psz_node[0] == '\0' )
        psz_node = "0.0.0.0";
399

400 401 402 403 404 405 406
    if ( i_family != AF_INET6 )
    {
        /* Give a try to inet_aton because experience shows that getaddrinfo()
         * fails in certain cases, like when network is down. */
        struct in_addr addr;
        if ( inet_aton( psz_node, &addr ) != 0 )
        {
Christophe Massiot's avatar
Christophe Massiot committed
407 408 409 410 411
            uint8_t *p_buffer = malloc( sizeof(struct addrinfo) +
                                        sizeof(struct sockaddr_in) );
            p_res = (struct addrinfo *)p_buffer;
            struct sockaddr_in *p_sin =
                (struct sockaddr_in *)(p_buffer + sizeof(struct addrinfo));
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
            p_sin->sin_family = AF_INET;
            if ( psz_port != NULL )
                p_sin->sin_port = ntohs( atoi( psz_port ) );
            else
                p_sin->sin_port = 0;
            p_sin->sin_addr = addr;

            p_res->ai_family = AF_INET;
            p_res->ai_socktype = SOCK_DGRAM;
            p_res->ai_protocol = 0;
            p_res->ai_addrlen = sizeof(struct sockaddr_in);
            p_res->ai_addr = (struct sockaddr *)p_sin;
            p_res->ai_canonname = NULL;
            p_res->ai_next = NULL;

            free( psz_string );
            return p_res;
        }
    }

432 433 434 435 436
    memset( &hint, 0, sizeof(hint) );
    hint.ai_family = i_family;
    hint.ai_socktype = SOCK_DGRAM;
    hint.ai_protocol = 0;
    hint.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ADDRCONFIG;
437
    if ( (i_ret = getaddrinfo( psz_node, psz_port, &hint, &p_res )) != 0 )
438 439 440 441 442
    {
        //msg_Warn( NULL, "getaddrinfo error: %s", gai_strerror(i_ret) );
        free( psz_string );
        return NULL;
    }
443

444 445 446
    free( psz_string );
    return p_res;
}
447

448 449 450 451 452 453 454 455
/*****************************************************************************
 * RawFillHeaders - fill ip/udp headers for RAW socket
 *****************************************************************************/
static void RawFillHeaders(struct udprawpkt *dgram,
                        in_addr_t ipsrc, in_addr_t ipdst,
                        uint16_t portsrc, uint16_t portdst,
                        uint8_t ttl, uint8_t tos, uint16_t len)
{
456
#ifndef __APPLE__
457 458 459
#if defined(__FreeBSD__)
    struct ip *iph = &(dgram->iph);
#else
460
    struct iphdr *iph = &(dgram->iph);
461
#endif
462 463 464 465 466 467 468 469 470 471 472 473
    struct udphdr *udph = &(dgram->udph);

#ifdef DEBUG_SOCKET
    char ipsrc_str[16], ipdst_str[16];
    struct in_addr insrc, indst;
    insrc.s_addr = ipsrc;
    indst.s_addr = ipdst;
    strncpy(ipsrc_str, inet_ntoa(insrc), 16);
    strncpy(ipdst_str, inet_ntoa(indst), 16);
    printf("Filling raw header (%p) (%s:%u -> %s:%u)\n", dgram, ipsrc_str, portsrc, ipdst_str, portdst);
#endif

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
#if defined(__FreeBSD__)
    // Fill ip header
    iph->ip_hl    = 5;              // ip header with no specific option
    iph->ip_v     = 4;
    iph->ip_tos   = tos;
    iph->ip_len   = sizeof(struct udprawpkt) + len; // auto-htoned ?
    iph->ip_id    = htons(0);       // auto-generated if frag_off (flags) = 0 ?
    iph->ip_off   = 0;
    iph->ip_ttl   = ttl;
    iph->ip_p     = IPPROTO_UDP;
    iph->ip_sum   = 0;
    iph->ip_src.s_addr = ipsrc;
    iph->ip_dst.s_addr = ipdst;

    // Fill udp header
    udph->uh_sport = htons(portsrc);
    udph->uh_dport = htons(portdst);
    udph->uh_ulen  = htons(sizeof(struct udphdr) + len);
    udph->uh_sum   = 0;
#else
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    // Fill ip header
    iph->ihl      = 5;              // ip header with no specific option
    iph->version  = 4;
    iph->tos      = tos;
    iph->tot_len  = sizeof(struct udprawpkt) + len; // auto-htoned ?
    iph->id       = htons(0);       // auto-generated if frag_off (flags) = 0 ?
    iph->frag_off = 0;
    iph->ttl      = ttl;
    iph->protocol = IPPROTO_UDP;
    iph->check    = 0;
    iph->saddr    = ipsrc;
    iph->daddr    = ipdst;

    // Fill udp header
    udph->source = htons(portsrc);
    udph->dest   = htons(portdst);
    udph->len    = htons(sizeof(struct udphdr) + len);
    udph->check  = 0;
512
#endif
513 514 515

    // Compute ip header checksum. Computed by kernel when frag_off = 0 ?
    //iph->check = csum((unsigned short *)iph, sizeof(struct iphdr));
516
#endif
517 518
}

519
/*****************************************************************************
520
 * OpenSocket: parse argv and open IPv4 & IPv6 sockets
521
 *****************************************************************************/
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
static char *config_stropt( char *psz_string )
{
    char *ret, *tmp;
    if ( !psz_string || strlen( psz_string ) == 0 )
        return NULL;
    ret = tmp = strdup( psz_string );
    while (*tmp) {
        if (*tmp == '_')
            *tmp = ' ';
        if (*tmp == '/') {
            *tmp = '\0';
            break;
        }
        tmp++;
    }
    return ret;
}

540
int OpenSocket( const char *_psz_arg, int i_ttl, uint16_t i_bind_port,
541 542
                uint16_t i_connect_port, unsigned int *pi_weight, bool *pb_tcp,
                struct opensocket_opt *p_opt)
543
{
544
    sockaddr_t bind_addr, connect_addr;
545
    int i_fd = -1, i;
546
    char *psz_arg = strdup(_psz_arg);
547 548 549
    char *psz_token = psz_arg;
    char *psz_token2 = NULL;
    int i_bind_if_index = 0, i_connect_if_index = 0;
550 551
    in_addr_t i_if_addr = INADDR_ANY;
    int i_tos = 0;
552 553 554 555
    bool b_tcp;
    struct addrinfo *p_ai;
    int i_family;
    socklen_t i_sockaddr_len;
556 557
    bool b_host = false;
    bool b_raw_packets = false;
558
    in_addr_t i_raw_srcaddr = INADDR_ANY;
559
    int i_raw_srcport = 0;
560
    char *psz_ifname = NULL;
Christophe Massiot's avatar
Christophe Massiot committed
561
#ifdef __FreeBSD__
562
    int hincl = 1;
Christophe Massiot's avatar
Christophe Massiot committed
563
#endif
564

565 566
    bind_addr.ss.ss_family = AF_UNSPEC;
    connect_addr.ss.ss_family = AF_UNSPEC;
567

568 569 570
    if ( pb_tcp == NULL )
        pb_tcp = &b_tcp;
    *pb_tcp = false;
571

572 573 574
    if ( p_opt != NULL && p_opt->pb_multicast != NULL )
        *p_opt->pb_multicast = false;

575 576
    psz_token2 = strrchr( psz_arg, ',' );
    if ( psz_token2 )
577
    {
578
        *psz_token2++ = '\0';
579
        if ( pi_weight )
580
            *pi_weight = strtoul( psz_token2, NULL, 0 );
581 582 583 584
    }
    else if ( pi_weight )
        *pi_weight = 1;

585 586 587
    psz_token2 = strchr( psz_arg, '/' );
    if ( psz_token2 )
        *psz_token2 = '\0';
588

589 590 591 592 593
    if ( *psz_token == '\0' )
        return -1;

    /* Hosts */
    if ( psz_token[0] != '@' )
594
    {
595
        b_host = true;
596 597 598
        p_ai = ParseNodeService( psz_token, &psz_token, i_connect_port,
                                 &i_connect_if_index );
        if ( p_ai == NULL )
599
            return -1;
600
        memcpy( &connect_addr.ss, p_ai->ai_addr, p_ai->ai_addrlen );
601
        freeaddrinfo( p_ai );
602 603
    }

604
    if ( psz_token[0] == '@' )
605
    {
606 607 608 609
        psz_token++;
        p_ai = ParseNodeService( psz_token, &psz_token, i_bind_port,
                                 &i_bind_if_index );
        if ( p_ai == NULL )
610
            return -1;
611
        memcpy( &bind_addr.ss, p_ai->ai_addr, p_ai->ai_addrlen );
612
        freeaddrinfo( p_ai );
613
    }
614

615 616
    if ( bind_addr.ss.ss_family == AF_UNSPEC &&
         connect_addr.ss.ss_family == AF_UNSPEC )
617
        return -1;
618

619 620 621
#ifdef DEBUG_SOCKET
    PrintSocket( "socket definition:", &bind_addr, &connect_addr );
#endif
622 623 624 625 626 627 628
    /* opensocket optional struct */
    if (p_opt) {
        if (p_opt->p_raw_pktheader) {
            memset(p_opt->p_raw_pktheader, 0, sizeof(struct udprawpkt));
            b_raw_packets = true;
        }
    }
629

630 631
    /* Weights and options */
    if ( psz_token2 )
632 633 634
    {
        do
        {
635
            *psz_token2++ = '\0';
636

637 638
#define IS_OPTION( option ) (!strncasecmp( psz_token2, option, strlen(option) ))
#define ARG_OPTION( option ) (psz_token2 + strlen(option))
639 640

            if ( IS_OPTION("ifindex=") )
641 642
                i_bind_if_index = i_connect_if_index =
                    strtol( ARG_OPTION("ifindex="), NULL, 0 );
643
            else if ( IS_OPTION("ifaddr=") )
644 645
            {
                char *option = config_stropt( ARG_OPTION("ifaddr=") );
646
                i_if_addr = inet_addr( option );
647 648
                free( option );
            }
649 650 651 652 653 654 655
            else if ( IS_OPTION("ifname=") )
            {
                psz_ifname = config_stropt( ARG_OPTION("ifname=") );
                if (strlen(psz_ifname) >= IFNAMSIZ) {
                    psz_ifname[IFNAMSIZ-1] = '\0';
                }
            }
656 657 658 659
            else if ( IS_OPTION("ttl=") )
                i_ttl = strtol( ARG_OPTION("ttl="), NULL, 0 );
            else if ( IS_OPTION("tos=") )
                i_tos = strtol( ARG_OPTION("tos="), NULL, 0 );
660 661
            else if ( IS_OPTION("tcp") )
                *pb_tcp = true;
662 663 664 665 666 667 668 669
            else if ( IS_OPTION("srcaddr=") )
            {
                char *option = config_stropt( ARG_OPTION("srcaddr=") );
                i_raw_srcaddr = inet_addr( option );
                free( option );
            }
            else if ( IS_OPTION("srcport=") )
                i_raw_srcport = strtol( ARG_OPTION("srcport="), NULL, 0 );
670 671
            else if ( IS_OPTION("fd=") )
                i_fd = strtol( ARG_OPTION("fd="), NULL, 0 );
672
            else
673
                msg_Warn( NULL, "unrecognized option %s", psz_token2 );
674 675 676 677

#undef IS_OPTION
#undef ARG_OPTION
        }
678
        while ( (psz_token2 = strchr( psz_token2, '/' )) != NULL );
679 680
    }

681 682
    free( psz_arg );

683
    /* Sanity checks */
684 685 686
    if ( bind_addr.ss.ss_family != AF_UNSPEC
          && connect_addr.ss.ss_family != AF_UNSPEC
          && bind_addr.ss.ss_family != connect_addr.ss.ss_family )
687
    {
688
        msg_Err( NULL, "incompatible address types" );
689 690
        exit(EXIT_FAILURE);
    }
691 692 693 694 695 696 697 698 699
    if ( bind_addr.ss.ss_family != AF_UNSPEC )
        i_family = bind_addr.ss.ss_family;
    else if ( connect_addr.ss.ss_family != AF_UNSPEC )
        i_family = connect_addr.ss.ss_family;
    else
    {
        msg_Err( NULL, "ambiguous address declaration" );
        exit(EXIT_FAILURE);
    }
700 701
    i_sockaddr_len = (i_family == AF_INET) ? sizeof(struct sockaddr_in) :
                     sizeof(struct sockaddr_in6);
702

703 704
    if ( i_bind_if_index && i_connect_if_index
          && i_bind_if_index != i_connect_if_index )
705
    {
706
        msg_Err( NULL, "incompatible bind and connect interfaces" );
707 708
        exit(EXIT_FAILURE);
    }
709 710
    if ( i_connect_if_index ) i_bind_if_index = i_connect_if_index;
    else i_connect_if_index = i_bind_if_index;
711

712
    /* Socket configuration */
713
    if ( i_fd < 0 )
714
    {
715 716 717 718 719 720
        if (b_raw_packets && b_host)
        { 
            RawFillHeaders(p_opt->p_raw_pktheader,
                i_raw_srcaddr, connect_addr.sin.sin_addr.s_addr, i_raw_srcport,
                ntohs(connect_addr.sin.sin_port), i_ttl, i_tos, 0);
            i_fd = socket( AF_INET, SOCK_RAW, IPPROTO_RAW );
721 722 723 724 725 726 727
#ifdef __FreeBSD__
            if ( setsockopt( i_fd, IPPROTO_IP, IP_HDRINCL, &hincl, sizeof(hincl)) == -1 )
            {
                msg_Err( NULL, "unable to set socket (%s)", strerror(errno) );
                exit(EXIT_FAILURE);
            }
#endif
728 729 730 731 732 733 734 735
        } else
            i_fd = socket( i_family, *pb_tcp ? SOCK_STREAM : SOCK_DGRAM, 0);

        if ( i_fd < 0 )
        {
            msg_Err( NULL, "unable to open socket (%s)", strerror(errno) );
            exit(EXIT_FAILURE);
        }
736

737 738 739
        i = 1;
        if ( setsockopt( i_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&i,
                         sizeof(i) ) == -1 )
740
        {
741
            msg_Err( NULL, "unable to set socket (%s)", strerror(errno) );
742 743 744
            exit(EXIT_FAILURE);
        }

745
        if ( i_family == AF_INET6 )
746
        {
747 748 749
            if ( i_bind_if_index
                  && setsockopt( i_fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
                         (void *)&i_bind_if_index, sizeof(i_bind_if_index) ) < 0 )
750
            {
751 752 753 754
                msg_Err( NULL, "couldn't set interface index" );
                PrintSocket( "socket definition:", &bind_addr, &connect_addr );
                exit(EXIT_FAILURE);
            }
755

756 757
            if ( bind_addr.ss.ss_family != AF_UNSPEC )
            {
758
                #if !defined(__APPLE__) && !defined(__FreeBSD__)
759
                if ( IN6_IS_ADDR_MULTICAST( &bind_addr.sin6.sin6_addr ) )
760
                {
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
                    struct ipv6_mreq imr;
                    sockaddr_t bind_addr_any = bind_addr;
                    bind_addr_any.sin6.sin6_addr = in6addr_any;

                    if ( bind( i_fd, &bind_addr_any.so,
                               sizeof(bind_addr_any) ) < 0 )
                    {
                        msg_Err( NULL, "couldn't bind" );
                        PrintSocket( "socket definition:", &bind_addr,
                                     &connect_addr );
                        exit(EXIT_FAILURE);
                    }

                    imr.ipv6mr_multiaddr = bind_addr.sin6.sin6_addr;
                    imr.ipv6mr_interface = i_bind_if_index;

                    /* Join Multicast group without source filter */
                    if ( setsockopt( i_fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
                                     (char *)&imr, sizeof(struct ipv6_mreq) ) < 0 )
                    {
                        msg_Err( NULL, "couldn't join multicast group" );
                        PrintSocket( "socket definition:", &bind_addr,
                                      &connect_addr );
                        exit(EXIT_FAILURE);
                    }
786 787 788

                    if ( p_opt != NULL && p_opt->pb_multicast != NULL )
                        *p_opt->pb_multicast = true;
789
                }
790 791 792
                else
                #endif
                    goto normal_bind;
793
            }
794
        }
795
        else if ( bind_addr.ss.ss_family != AF_UNSPEC )
796
        {
797 798 799 800 801 802 803
normal_bind:
            if ( bind( i_fd, &bind_addr.so, i_sockaddr_len ) < 0 )
            {
                msg_Err( NULL, "couldn't bind" );
                PrintSocket( "socket definition:", &bind_addr, &connect_addr );
                exit(EXIT_FAILURE);
            }
804
        }
805
    }
806

807 808 809 810 811 812
    if ( !*pb_tcp )
    {
        /* Increase the receive buffer size to 1/2MB (8Mb/s during 1/2s) to
         * avoid packet loss caused by scheduling problems */
        i = 0x80000;
        setsockopt( i_fd, SOL_SOCKET, SO_RCVBUF, (void *) &i, sizeof( i ) );
813

814
        /* Join the multicast group if the socket is a multicast address */
815 816
        if ( bind_addr.ss.ss_family == AF_INET
              && IN_MULTICAST( ntohl(bind_addr.sin.sin_addr.s_addr)) )
817
        {
Christophe Massiot's avatar
Christophe Massiot committed
818
#ifdef IP_ADD_SOURCE_MEMBERSHIP /* unavailable on GNU Hurd */
819
            if ( connect_addr.ss.ss_family != AF_UNSPEC )
820 821 822
            {
                /* Source-specific multicast */
                struct ip_mreq_source imr;
823
                imr.imr_multiaddr = bind_addr.sin.sin_addr;
824
                imr.imr_interface.s_addr = i_if_addr;
825
                imr.imr_sourceaddr = connect_addr.sin.sin_addr;
826 827 828 829 830
                if ( i_bind_if_index )
                    msg_Warn( NULL, "ignoring ifindex option in SSM" );

                if ( setsockopt( i_fd, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP,
                            (char *)&imr, sizeof(struct ip_mreq_source) ) < 0 )
Christophe Massiot's avatar
Christophe Massiot committed
831
                {
832 833 834 835 836
                    msg_Err( NULL, "couldn't join multicast group (%s)",
                             strerror(errno) );
                    PrintSocket( "socket definition:", &bind_addr,
                                 &connect_addr );
                    exit(EXIT_FAILURE);
Christophe Massiot's avatar
Christophe Massiot committed
837
                }
838
            }
Christophe Massiot's avatar
Christophe Massiot committed
839 840 841 842
            else
#endif
#ifndef __FreeBSD__
            if ( i_bind_if_index )
843 844 845
            {
                /* Linux-specific interface-bound multicast */
                struct ip_mreqn imr;
846
                imr.imr_multiaddr = bind_addr.sin.sin_addr;
847 848 849 850 851
                imr.imr_address.s_addr = i_if_addr;
                imr.imr_ifindex = i_bind_if_index;

                if ( setsockopt( i_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
                                 (char *)&imr, sizeof(struct ip_mreqn) ) < 0 )
Christophe Massiot's avatar
Christophe Massiot committed
852
                {
853 854 855 856 857
                    msg_Err( NULL, "couldn't join multicast group (%s)",
                             strerror(errno) );
                    PrintSocket( "socket definition:", &bind_addr,
                                 &connect_addr );
                    exit(EXIT_FAILURE);
Christophe Massiot's avatar
Christophe Massiot committed
858
                }
859 860
            }
            else
Christophe Massiot's avatar
Christophe Massiot committed
861
#endif
862 863 864
            {
                /* Regular multicast */
                struct ip_mreq imr;
865
                imr.imr_multiaddr = bind_addr.sin.sin_addr;
866 867 868 869 870 871 872 873 874 875 876 877
                imr.imr_interface.s_addr = i_if_addr;

                if ( setsockopt( i_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
                                 (char *)&imr, sizeof(struct ip_mreq) ) < 0 )
                {
                    msg_Err( NULL, "couldn't join multicast group (%s)",
                             strerror(errno) );
                    PrintSocket( "socket definition:", &bind_addr,
                                 &connect_addr );
                    exit(EXIT_FAILURE);
                }
            }
878 879 880 881 882 883 884 885 886 887 888 889
#ifdef SO_BINDTODEVICE
            if (psz_ifname) {
                if ( setsockopt( i_fd, SOL_SOCKET, SO_BINDTODEVICE,
                                 psz_ifname, strlen(psz_ifname)+1 ) < 0 ) {
                    msg_Err( NULL, "couldn't bind to device %s (%s)",
                             psz_ifname, strerror(errno) );
                    exit(EXIT_FAILURE);
                }
                free(psz_ifname);
                psz_ifname = NULL;
            }
#endif
890

891 892 893
            if ( p_opt != NULL && p_opt->pb_multicast != NULL )
                *p_opt->pb_multicast = true;
        }
894
    }
895

896
    if ( connect_addr.ss.ss_family != AF_UNSPEC )
897
    {
898
        if ( connect( i_fd, &connect_addr.so, i_sockaddr_len ) < 0 )
899
        {
900 901 902
            msg_Err( NULL, "cannot connect socket (%s)",
                     strerror(errno) );
            PrintSocket( "socket definition:", &bind_addr, &connect_addr );
903 904 905
            exit(EXIT_FAILURE);
        }

906 907
        if ( !*pb_tcp )
        {
908 909
            if ( i_family == AF_INET
                  && IN_MULTICAST(ntohl(connect_addr.sin.sin_addr.s_addr)) )
910
            {
911 912 913 914 915 916
                if ( p_opt != NULL && p_opt->pb_multicast != NULL )
                    *p_opt->pb_multicast = true;

                if ( i_ttl &&
                     setsockopt( i_fd, IPPROTO_IP, IP_MULTICAST_TTL,
                                 (void *)&i_ttl, sizeof(i_ttl) ) == -1 )
917
                {
918 919 920 921 922
                    msg_Err( NULL, "couldn't set TTL (%s)",
                             strerror(errno) );
                    PrintSocket( "socket definition:", &bind_addr,
                                 &connect_addr );
                    exit(EXIT_FAILURE);
923
                }
924
            }
925

926 927 928 929 930 931 932 933 934
            if ( i_family == AF_INET6
                  && IN6_IS_ADDR_MULTICAST(&connect_addr.sin6.sin6_addr) )
            {
                if ( p_opt != NULL && p_opt->pb_multicast != NULL )
                    *p_opt->pb_multicast = true;

                if ( i_ttl &&
                     setsockopt( i_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
                                 (void *)&i_ttl, sizeof(i_ttl) ) == -1 )
935
                {
936 937 938 939 940
                    msg_Err( NULL, "couldn't set TTL (%s)",
                             strerror(errno) );
                    PrintSocket( "socket definition:", &bind_addr,
                                 &connect_addr );
                    exit(EXIT_FAILURE);
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
                }
            }

            if ( i_tos )
            {
                if ( setsockopt( i_fd, IPPROTO_IP, IP_TOS,
                                 (void *)&i_tos, sizeof(i_tos) ) == -1 )
                {
                    msg_Err( NULL, "couldn't set TOS (%s)", strerror(errno) );
                    PrintSocket( "socket definition:", &bind_addr,
                                 &connect_addr );
                    exit(EXIT_FAILURE);
                }
            }
        }
    }
    else if ( *pb_tcp )
958
    {
959 960 961
        /* Open in listen mode - wait for an incoming connection */
        int i_new_fd;
        if ( listen( i_fd, 1 ) < 0 )
962
        {
963 964
            msg_Err( NULL, "couldn't listen (%s)", strerror(errno) );
            PrintSocket( "socket definition:", &bind_addr, &connect_addr );
965 966 967
            exit(EXIT_FAILURE);
        }

968
        while ( (i_new_fd = accept( i_fd, NULL, NULL )) < 0 )
969
        {
970
            if ( errno != EINTR )
971
            {
972 973
                msg_Err( NULL, "couldn't accept (%s)", strerror(errno) );
                PrintSocket( "socket definition:", &bind_addr, &connect_addr );
974 975 976
                exit(EXIT_FAILURE);
            }
        }
977 978
        close( i_fd );
        return i_new_fd;
979 980 981 982 983
    }

    return i_fd;
}

984 985 986 987 988 989 990 991 992 993 994
/*****************************************************************************
 * StatFile: parse argv and return the mode of the named file
 *****************************************************************************/
mode_t StatFile( const char *psz_arg )
{
    struct stat sb;
    if ( stat( psz_arg, &sb ) < 0 )
        return 0;
    return sb.st_mode;
}

995 996 997
/*****************************************************************************
 * OpenFile: parse argv and open file descriptors
 *****************************************************************************/
998
int OpenFile( const char *psz_arg, bool b_read, bool b_append )
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
{
    struct stat sb;
    int i_fd;
    int i_mode = b_read ? O_RDONLY : O_WRONLY;

    if ( stat( psz_arg, &sb ) < 0 )
    {
        if ( b_read )
        {
            msg_Err( NULL, "file %s doesn't exist (%s)", psz_arg,
                     strerror(errno) );
1010
            return -1;
1011 1012 1013
        }
        i_mode |= O_CREAT;
    }
1014
    else if ( !(S_ISCHR(sb.st_mode) || S_ISFIFO(sb.st_mode)) && !b_read )
1015
    {
1016 1017 1018 1019
        if ( b_append )
            i_mode |= O_APPEND;
        else
            i_mode |= O_TRUNC;
1020 1021 1022 1023 1024
    }

    if ( (i_fd = open( psz_arg, i_mode, 0644 )) < 0 )
    {
        msg_Err( NULL, "couldn't open file %s (%s)", psz_arg, strerror(errno) );
1025
        return -1;
1026 1027 1028 1029 1030 1031
    }

    return i_fd;
}

/*****************************************************************************
1032 1033
 * GetAuxFile: generate a file name for the TS file
 * Remember to free the returned string
1034
 *****************************************************************************/
1035
char *GetAuxFile( const char *psz_arg, size_t i_payload_size )
1036
{
1037
    char *psz_aux = malloc( strlen(psz_arg) + 256 );
1038 1039 1040
    char *psz_token;

    strcpy( psz_aux, psz_arg );
1041 1042 1043 1044 1045 1046

    psz_token = strrchr( psz_aux, '/' );
    if ( psz_token != NULL )
        psz_token++;
    else
        psz_token = psz_aux + 1;
1047
    if ( *psz_token ) psz_token++; /* Skip first character of base name */
1048 1049

    /* Strip extension */
1050
    psz_token = strrchr( psz_token, '.' );
1051
    if ( psz_token ) *psz_token = '\0';
1052 1053

    /* Append extension */
1054
    strcat( psz_aux, "." PSZ_AUX_EXT );
1055 1056 1057 1058 1059
    if ( i_payload_size != DEFAULT_PAYLOAD_SIZE )
        sprintf( psz_aux + strlen(psz_aux), "%zu", i_payload_size );

    return psz_aux;
}
1060

1061 1062 1063 1064 1065 1066 1067 1068
/*****************************************************************************
 * OpenAuxFile
 *****************************************************************************/
FILE *OpenAuxFile( const char *psz_arg, bool b_read, bool b_append )
{
    FILE *p_aux;

    if ( (p_aux = fopen( psz_arg,
1069
                         b_read ? "rb" : (b_append ? "ab" : "wb") )) == NULL )
1070
    {
1071
        msg_Err( NULL, "couldn't open file %s (%s)", psz_arg,
1072 1073 1074 1075 1076 1077
                 strerror(errno) );
        exit(EXIT_FAILURE);
    }

    return p_aux;
}
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129


/*****************************************************************************
 * LookupAuxFile: find an STC in an auxiliary file
 *****************************************************************************/
off_t LookupAuxFile( const char *psz_arg, int64_t i_wanted, bool b_absolute )
{
    uint8_t *p_aux;
    off_t i_offset1 = 0, i_offset2;
    int i_stc_fd;
    struct stat stc_stat;

    if ( (i_stc_fd = open( psz_arg, O_RDONLY )) == -1 )
    {
        msg_Err( NULL, "unable to open %s (%s)", psz_arg, strerror(errno) );
        return -1;
    }

    if ( fstat( i_stc_fd, &stc_stat ) == -1
          || stc_stat.st_size < sizeof(uint64_t) )
    {
        msg_Err( NULL, "unable to stat %s (%s)", psz_arg, strerror(errno) );
        return -1;
    }

    p_aux = mmap( NULL, stc_stat.st_size, PROT_READ, MAP_SHARED,
                  i_stc_fd, 0 );
    if ( p_aux == MAP_FAILED )
    {
        msg_Err( NULL, "unable to mmap %s (%s)", psz_arg, strerror(errno) );
        return -1;
    }

    i_offset2 = stc_stat.st_size / sizeof(uint64_t);

    if ( i_wanted < 0 )
        i_wanted += FromSTC( p_aux + (i_offset2 - 1) * sizeof(uint64_t) );
    else if ( !b_absolute )
        i_wanted += FromSTC( p_aux );

    if ( i_wanted < 0 )
    {
        msg_Err( NULL, "invalid offset" );
        return -1;
    }

    for ( ; ; )
    {
        off_t i_mid_offset = (i_offset1 + i_offset2) / 2;
        uint8_t *p_mid_aux = p_aux + i_mid_offset * sizeof(uint64_t);
        uint64_t i_mid_stc = FromSTC( p_mid_aux );

1130
        if ( i_offset1 == i_mid_offset )
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
            break;

        if ( i_mid_stc >= i_wanted )
            i_offset2 = i_mid_offset;
        else
            i_offset1 = i_mid_offset;
    }

    munmap( p_aux, stc_stat.st_size );
    close( i_stc_fd );

1142
    return i_offset1;
1143 1144
}

1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
/*****************************************************************************
 * CheckFileSizes: check the consistency of file and aux sizes
 *****************************************************************************/
void CheckFileSizes( const char *psz_file, const char *psz_aux_file,
                     size_t i_payload_size )
{
    struct stat st;
    off_t i_file_packets, i_aux_packets;

    if ( stat( psz_file, &st ) < 0 )
        i_file_packets = 0;
    else
    {
        i_file_packets = st.st_size / i_payload_size;
        if ( st.st_size % i_payload_size )
        {
            msg_Warn( NULL, "file size is not a multiple of %jd, truncating",
                      i_payload_size );
            if ( truncate( psz_file, i_file_packets * i_payload_size ) < 0 )
                msg_Err( NULL, "truncate failed (%s)", strerror(errno) );
        }
    }

    if ( stat( psz_aux_file, &st ) < 0 )
        i_aux_packets = 0;
    else
    {
        i_aux_packets = st.st_size / sizeof(uint64_t);
        if ( st.st_size % sizeof(uint64_t) )
        {
            msg_Warn( NULL, "aux size is not a multiple of %jd, truncating",
                      sizeof(uint64_t) );
            if ( truncate( psz_aux_file, i_aux_packets * sizeof(uint64_t) ) < 0 )
                msg_Err( NULL, "truncate failed (%s)", strerror(errno) );
        }
    }

    if ( i_file_packets < i_aux_packets )
    {
        msg_Warn( NULL, "truncating aux file" );
        if ( truncate( psz_aux_file, i_file_packets * sizeof(uint64_t) ) < 0 )
            msg_Err( NULL, "truncate failed (%s)", strerror(errno) );
    }
    else if ( i_aux_packets < i_file_packets )
    {
        msg_Warn( NULL, "truncating file" );
        if ( truncate( psz_file, i_aux_packets * i_payload_size ) < 0 )
            msg_Err( NULL, "truncate failed (%s)", strerror(errno) );
    }
}

1196 1197 1198
/*****************************************************************************
 * GetDirFile: return the prefix of the file according to the STC
 *****************************************************************************/
1199 1200
uint64_t GetDirFile( uint64_t i_rotate_size, uint64_t i_rotate_offset,
                     int64_t i_wanted )
1201 1202 1203 1204 1205 1206
{
    if ( i_wanted <= 0 )
        i_wanted += real_Date();
    if ( i_wanted <= 0 )
        return 0;

1207
    return (i_wanted - i_rotate_offset) / i_rotate_size;
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
}

/*****************************************************************************
 * OpenDirFile: return fd + aux file pointer
 *****************************************************************************/
int OpenDirFile( const char *psz_dir_path, uint64_t i_file, bool b_read,
                 size_t i_payload_size, FILE **pp_aux_file )
{
    int i_fd;
    char psz_file[strlen(psz_dir_path) + sizeof(PSZ_TS_EXT) +
                  sizeof(".18446744073709551615")];
1219 1220
    char *psz_aux_file;

1221
    sprintf( psz_file, "%s/%"PRIu64"."PSZ_TS_EXT, psz_dir_path, i_file );
1222 1223 1224 1225
    psz_aux_file = GetAuxFile( psz_file, i_payload_size );

    if ( !b_read )
        CheckFileSizes( psz_file, psz_aux_file, i_payload_size );
1226 1227

    i_fd = OpenFile( psz_file, b_read, !b_read );
1228 1229 1230 1231 1232
    if ( i_fd < 0 )
    {
        free( psz_aux_file );
        return -1;
    }
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259

    *pp_aux_file = OpenAuxFile( psz_aux_file, b_read, !b_read );
    free( psz_aux_file );
    if ( *pp_aux_file == NULL )
    {
        close( i_fd );
        return -1;
    }
    return i_fd;
}

/*****************************************************************************
 * LookupDirAuxFile: find an STC in an auxiliary file of a directory
 *****************************************************************************/
off_t LookupDirAuxFile( const char *psz_dir_path, uint64_t i_file,
                        int64_t i_wanted, size_t i_payload_size )
{
    off_t i_ret;
    char psz_file[strlen(psz_dir_path) + sizeof(PSZ_TS_EXT) +
                  sizeof(".18446744073709551615")];
    sprintf( psz_file, "%s/%"PRIu64"."PSZ_TS_EXT, psz_dir_path, i_file );

    char *psz_aux_file = GetAuxFile( psz_file, i_payload_size );
    i_ret = LookupAuxFile( psz_aux_file, i_wanted, true );
    free( psz_aux_file );
    return i_ret;
}